diff --git a/.checker-floor.json b/.checker-floor.json new file mode 100644 index 000000000..a768bf5ee --- /dev/null +++ b/.checker-floor.json @@ -0,0 +1,71 @@ +{ + "measured_at": "2026-11-14T15:35:48Z", + "commit": "abadd6290619c4dac280865ec2a2cd9ca5d9e0fd", + "tool": "common-ground-checker scan-local", + "tool_version": "0.0.2+aa578398248c", + "scoring_digest": "9fecce06b1cacea2", + "score": 100, + "criteria": { + "adrvalidator": "pass", + "changelog": "pass", + "cicd": "pass", + "codeofconduct": "pass", + "complexity": "pass", + "contributing": "pass", + "copyrightowner": "pass", + "coverage": "pass", + "docker": "pass", + "dockerimage": "pass", + "documentation": "pass", + "eupllicense": "pass", + "fivelayer": "pass", + "helmchart": "pass", + "licenceconsistency": "pass", + "license": "pass", + "maintainability": "pass", + "openapi": "pass", + "opensourcehealth": "pass", + "openssfscorecard": "info", + "owaspsecurecoding": "pass", + "publiccode": "pass", + "sbom": "pass", + "secretscanning": "pass", + "security": "pass", + "semver": "pass", + "sourcecode": "pass", + "spdxheaders": "pass", + "testcoderatio": "warn", + "tests": "pass" + }, + "stars": { + "adrvalidator": 5, + "changelog": 5, + "cicd": 5, + "codeofconduct": 5, + "complexity": 5, + "contributing": 5, + "copyrightowner": 5, + "coverage": 5, + "docker": 5, + "dockerimage": 5, + "documentation": 5, + "eupllicense": 5, + "fivelayer": 5, + "helmchart": 5, + "licenceconsistency": 5, + "license": 5, + "maintainability": 4, + "openapi": 5, + "opensourcehealth": 4, + "owaspsecurecoding": 5, + "publiccode": 5, + "sbom": 5, + "secretscanning": 5, + "security": 5, + "semver": 5, + "sourcecode": 5, + "spdxheaders": 5, + "testcoderatio": 3, + "tests": 5 + } +} diff --git a/.claude/commands/check.md b/.claude/commands/check.md new file mode 100644 index 000000000..e5ce75001 --- /dev/null +++ b/.claude/commands/check.md @@ -0,0 +1,18 @@ +--- +description: Run LaunchPad's PHP and frontend quality checks +--- + +Run the quality suite from the repository root and report each failure with its +file and line. Dependencies must be installed first (`composer install`, +`npm ci`). + +1. PHP: `composer check:strict` (lint, lint:initial-state, lint:openapi, + lint:spec-annotations, lint:licenses, phpcs, phpmd, psalm, phpstan, + test:all). For a quicker pass use `composer check` (lint, phpcs, psalm, + test:unit). +2. Frontend: `npm run lint` (eslint, check:manifest, lint:initial-state, + lint:translation-domain), then `npm run stylelint` and `npm run format`. +3. Translations: `npm run check:l10n-parity`. + +Auto-fixers, only when asked: `composer cs:fix`, `npm run lint:fix`, +`npm run stylelint:fix`, `npm run format:fix`. diff --git a/.claude/commands/e2e.md b/.claude/commands/e2e.md new file mode 100644 index 000000000..d704713d3 --- /dev/null +++ b/.claude/commands/e2e.md @@ -0,0 +1,17 @@ +--- +description: Run LaunchPad's Playwright end-to-end tests against a Nextcloud instance +--- + +Run the Playwright suite (config `playwright.config.ts`, tests in `tests/e2e/`, +details in `tests/e2e/README.md`). + +1. The suite writes to the target instance and has no default URL. Ask which + instance to use unless one of `PLAYWRIGHT_BASE_URL`, `BASE_URL`, + `NEXTCLOUD_URL` or `NC_BASE_URL` is already set. Admin credentials come + from `NC_ADMIN_USER` / `NC_ADMIN_PASS` (default `admin` / `admin`). +2. Install the browser once: `npx playwright install chromium`. +3. Run: `NC_BASE_URL= npm run test:e2e`, or a single spec with + `NC_BASE_URL= npx playwright test tests/e2e/.spec.ts`. + +Other configs: `npm run test:e2e:excluded` (specs excluded from CI) and +`npm run test:e2e:docs` (documentation screenshots). diff --git a/.claude/commands/new-change.md b/.claude/commands/new-change.md new file mode 100644 index 000000000..a60b15150 --- /dev/null +++ b/.claude/commands/new-change.md @@ -0,0 +1,21 @@ +--- +description: Start a new OpenSpec change for LaunchPad +--- + +Start an OpenSpec change named `$ARGUMENTS` (kebab-case). + +1. Read `openspec/config.yaml` (project context and per-artifact rules) and + look at one or two existing changes in `openspec/changes/` and + `openspec/changes/archive/` for the house structure. +2. Check `openspec/specs/` for the capabilities the change touches. +3. Create `openspec/changes//` with: + - `proposal.md`: Why, What Changes, Capabilities, Impact. + - `design.md`: Context, Goals / Non-Goals, Decisions, Risks / Trade-offs. + - `tasks.md`: checklist of implementation and test tasks. + - `specs//spec.md`: delta requirements with GIVEN/WHEN/THEN + scenarios. + Most existing changes also carry `screens.md`, listing the screens the + change touches. +4. Accepted behaviour lives in `openspec/specs/`. When the change is done, + its delta specs are merged there and the change folder moves to + `openspec/changes/archive/-/`. diff --git a/.claude/commands/test.md b/.claude/commands/test.md new file mode 100644 index 000000000..90d967825 --- /dev/null +++ b/.claude/commands/test.md @@ -0,0 +1,13 @@ +--- +description: Run LaunchPad's PHPUnit and Vitest unit tests +--- + +Run the unit tests from the repository root and summarise failures. + +1. PHP: `composer test:unit` (PHPUnit, suite `tests/Unit`, config `phpunit.xml`). + To run one file: `./vendor/bin/phpunit --configuration phpunit.xml `. +2. Frontend: `npm test` (Vitest, config `vitest.config.js`, specs in + `src/**/__tests__/` and `tests/vitest/`). To run one file: + `npx vitest run `. + +If `$ARGUMENTS` names a file or folder, run only the matching suite for it. diff --git a/.coverage-baseline b/.coverage-baseline index 90737ba31..265fbfb0d 100644 --- a/.coverage-baseline +++ b/.coverage-baseline @@ -1 +1 @@ -49.47 +80.00 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..ec2ed7ce4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +# Build context for the evaluation image. The image installs vendor/ and +# builds js/ itself, so local dependencies stay out. +# Rendered from ConductionNL/.github templates/app-deploy. +.git +**/node_modules +vendor +coverage +.phpunit.cache +.phpunit.result.cache +tests/e2e/results +playwright-report +test-results +*.log +.env +# The deployment files themselves, so editing them does not rebuild the app. +Dockerfile +.dockerignore +docker-compose*.yml +charts +.github diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0535df19a..939087e6c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -74,3 +74,10 @@ updates: - "*" exclude: - "conduction/*" + + # Keeps the commit-SHA pins of the workflow actions current; the version + # comment next to each pin is what dependabot reads and rewrites. + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/sig-floor.json b/.github/sig-floor.json new file mode 100644 index 000000000..da8686eec --- /dev/null +++ b/.github/sig-floor.json @@ -0,0 +1,40 @@ +{ + "about": "SIG 4-star checks this app meets and must keep meeting (gate 123, sig-floor). Generated by check_sig_floor.py write; raised by the workflow, never lowered by hand.", + "schema": 1, + "profile": "four-star", + "tools": { + "lizard": "1.24.3" + }, + "unit_reader": 2, + "measured_at": "9080e1fa1847f34da7d39925e3f7422eb8afbd7b", + "checks": [ + "javascript duplication", + "javascript unit_complexity >10", + "javascript unit_complexity >25", + "javascript unit_complexity >5", + "javascript unit_interfacing >2", + "javascript unit_interfacing >4", + "javascript unit_interfacing >6", + "javascript unit_size >15", + "javascript unit_size >30", + "javascript unit_size >60", + "php module_coupling >10", + "php module_coupling >20", + "php module_coupling >50", + "php unit_complexity >10", + "php unit_complexity >25", + "php unit_interfacing >4", + "php unit_interfacing >6", + "php unit_size >60", + "vue duplication", + "vue unit_complexity >10", + "vue unit_complexity >25", + "vue unit_complexity >5", + "vue unit_interfacing >2", + "vue unit_interfacing >4", + "vue unit_interfacing >6", + "vue unit_size >15", + "vue unit_size >30", + "vue unit_size >60" + ] +} diff --git a/.github/workflows/branch-policy.yml b/.github/workflows/branch-policy.yml index 1dca5b78c..f5aa12261 100644 --- a/.github/workflows/branch-policy.yml +++ b/.github/workflows/branch-policy.yml @@ -4,6 +4,9 @@ on: pull_request: branches: [main, beta, development] +permissions: + contents: read + jobs: check-source-branch: name: Branch Policy Check @@ -12,9 +15,12 @@ jobs: timeout-minutes: 10 steps: - name: Verify source branch + # Branch names come in through the environment, never interpolated + # into the script, so a crafted branch name cannot inject shell. + env: + SOURCE: ${{ github.head_ref }} + TARGET: ${{ github.base_ref }} run: | - SOURCE="${{ github.head_ref }}" - TARGET="${{ github.base_ref }}" # hotfix/* is always allowed if [[ "$SOURCE" == hotfix/* ]]; then diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml index a26a7dfce..8985f009d 100644 --- a/.github/workflows/code-quality.yml +++ b/.github/workflows/code-quality.yml @@ -142,41 +142,23 @@ concurrency: # update-baseline / features-extract (contents write), and the Quality # Report PR comment (issues / pull-requests write). permissions: - contents: write - actions: write - issues: write - pull-requests: write + contents: read jobs: quality: + permissions: + contents: write + actions: write + issues: write + pull-requests: write if: (github.event_name != 'pull_request' || github.head_ref != 'development') uses: ConductionNL/.github/.github/workflows/quality.yml@main with: app-name: launchpad php-version: "8.3" - # Pinned, because the shared workflow's DEFAULT is '["stable31", "stable32"]' - # and stable31 CANNOT WORK here. `additional-apps` below installs - # openregister, which declares min-version="32" (its - # lib/ContextChat/ContentProvider.php implements - # OCP\ContextChat\IContentProvider, absent from core before NC32). On NC31 - # `occ app:enable openregister` fails with - # App "Open Register" cannot be installed because it is not compatible - # with this version of the server. - # and the run continues anyway, because that failure is only a ::warning::. - # Every /apps/openregister/... call then returns Nextcloud's HTML 404 page. - # - # Order matters as much as membership: newman, playwright and - # journeydoc-capture all check out `fromJSON(nextcloud-test-refs)[0]` as - # their single server, so with the inherited default those three jobs ran - # entirely on the version openregister cannot load. - # - # THE LIST IS THE WHOLE DECLARED RANGE. This comment previously said - # "launchpad's own appinfo/info.xml floor stays at 29 … the NC32 constraint - # here is a property of the CI fixture, not of launchpad's code" — that is - # no longer true of the file it describes. info.xml on this branch declares - # , so 32 is the app's own - # floor, not a fixture artefact, and 32, 33 and 34 each get a leg. - nextcloud-test-refs: '["stable34", "stable32", "stable33"]' + # nextcloud-test-refs is deliberately not set: the shared quality.yml + # derives the Nextcloud matrix from appinfo/info.xml (min-version 32 to + # max-version 35), so the tested range follows the declared range. enable-psalm: true enable-phpstan: true enable-phpmetrics: true @@ -212,6 +194,10 @@ jobs: # Its `testIgnore` names every excluded spec with the run that # measured it (31367057618: 65 of 80 passed). enable-phpunit: true + # PHPUnit on every database Nextcloud supports that we can run in CI, + # so a query that only works on PostgreSQL shows up before a customer + # on MySQL or SQLite finds it. + database-test-matrix: '["pgsql", "mysql", "sqlite"]' enable-newman: true newman-environment-path: "tests/integration/local.env.json" # Creates the non-admin account the collection's authorization assertions @@ -377,6 +363,15 @@ jobs: # deliberate). Floating both halves keeps caller and callee in step, # which is the only configuration in which a pinned path cannot expire. enable-hydra-gates: true + # Gate 122 (SIG unit ratchet) blocks: a unit this change adds or makes + # worse must stay at NLOC 60, McCabe 10 and at most 4 parameters, and a + # new duplicated fragment of 6+ lines fails. Units the change does not + # touch, or touches without making worse, are inherited and do not count. + hydra-gates-sig-blocking: true + # Maintainability floor: no rating in .maintainability-floor.json may drop + # more than 0.01 against the merge base (pull request) or below the + # committed floor (push). The floor is raised after improving merges. + enable-maintainability-floor: true # ── Cost controls (see ConductionNL/.github#596, #599) ─────────────── # Run PHPUnit and Playwright only when the diff could change their # verdict. Fails safe TOWARDS running: an unreadable diff, a force-push, @@ -408,8 +403,8 @@ jobs: permissions: contents: read steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 - name: Every required locale carries every source key diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 000000000..d72a9abc0 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2026 Conduction B.V. +# SPDX-License-Identifier: EUPL-1.2 + +# CodeQL static analysis of the JavaScript/TypeScript frontend and of the +# workflows themselves. CodeQL has no PHP extractor; the PHP side is covered by +# psalm and phpstan in the quality pipeline. +name: CodeQL + +on: + push: + branches: [development, main] + pull_request: + branches: [development, main] + schedule: + - cron: '17 3 * * 2' + +permissions: read-all + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-latest + permissions: + security-events: write + contents: read + actions: read + strategy: + fail-fast: false + matrix: + language: [javascript-typescript, actions] + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Initialise CodeQL + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + languages: ${{ matrix.language }} + build-mode: none + + - name: Analyse + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + category: /language:${{ matrix.language }} diff --git a/.github/workflows/container-image.yml b/.github/workflows/container-image.yml new file mode 100644 index 000000000..0c4d279b3 --- /dev/null +++ b/.github/workflows/container-image.yml @@ -0,0 +1,89 @@ +name: Container image + +# Builds the evaluation image (root Dockerfile) for a release and pushes it to +# ghcr.io/conductionnl/launchpad. A stable release gets its version and +# `latest`; a beta or unstable release only moves `edge`. +# +# Releases are created by the Release workflow with the workflow token, and a +# release made that way starts no other workflow. So this one follows the +# Release run instead, and builds the newest release it finds. +# +# Rendered from ConductionNL/.github templates/app-deploy. + +on: + workflow_run: + workflows: [Release] + types: [completed] + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: "Release tag to build, for example v1.2.3 (empty: the newest release)" + required: false + type: string + +permissions: + contents: read + packages: write + +concurrency: + group: container-image + cancel-in-progress: false + +jobs: + image: + if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' + runs-on: ubuntu-latest + steps: + - name: Resolve the release + id: release + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + EVENT_TAG: ${{ github.event.release.tag_name }} + INPUT_TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + tag="${EVENT_TAG:-${INPUT_TAG:-}}" + if [ -z "$tag" ]; then + tag="$(gh release list --repo "$REPO" --limit 1 --exclude-drafts --json tagName --jq '.[0].tagName')" + fi + [ -n "$tag" ] || { echo "::error::No release to build."; exit 1; } + version="${tag#v}" + image=ghcr.io/conductionnl/launchpad + case "$version" in + *-*) tags="$image:edge" ;; + *) tags="$image:$version,$image:latest" ;; + esac + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "tags=$tags" >> "$GITHUB_OUTPUT" + echo "Building $tag as $tags" + + - uses: actions/checkout@v4 + with: + ref: ${{ steps.release.outputs.tag }} + + - name: Record the commit + id: commit + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ github.token }} + + - uses: docker/build-push-action@v6 + with: + context: . + push: true + tags: ${{ steps.release.outputs.tags }} + labels: | + org.opencontainers.image.version=${{ steps.release.outputs.version }} + org.opencontainers.image.revision=${{ steps.commit.outputs.sha }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index 1f7ccf072..b3f847639 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -12,8 +12,14 @@ on: pull_request: branches: [development] +permissions: + contents: read + jobs: deploy: + permissions: + contents: write + packages: write uses: ConductionNL/.github/.github/workflows/documentation.yml@main # A reusable workflow receives NO secrets by default. Without this block the # callee's publish step finds CF_API_TOKEN empty, skips itself on its own diff --git a/.github/workflows/issue-triage.yml b/.github/workflows/issue-triage.yml index a122c1601..30c2dbed1 100644 --- a/.github/workflows/issue-triage.yml +++ b/.github/workflows/issue-triage.yml @@ -10,8 +10,14 @@ on: type: boolean default: true +permissions: + contents: read + jobs: triage: + permissions: + issues: write + contents: read uses: ConductionNL/.github/.github/workflows/issue-triage.yml@main with: app-name: launchpad diff --git a/.github/workflows/merge-hygiene.yml b/.github/workflows/merge-hygiene.yml index 4852cee5e..749a25cac 100644 --- a/.github/workflows/merge-hygiene.yml +++ b/.github/workflows/merge-hygiene.yml @@ -33,7 +33,7 @@ jobs: name: Conflict markers and PHP syntax runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 # Conflict markers, anywhere in the tree we author. A marker means a merge # was committed half-finished; every downstream signal from that commit is @@ -64,7 +64,7 @@ jobs: fi echo "No conflict markers." - - uses: shivammathur/setup-php@v2 + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 with: php-version: '8.3' coverage: none diff --git a/.github/workflows/openspec-sync.yml b/.github/workflows/openspec-sync.yml index cd5de2c3a..ef24c8790 100644 --- a/.github/workflows/openspec-sync.yml +++ b/.github/workflows/openspec-sync.yml @@ -42,8 +42,14 @@ on: paths: ['openspec/**'] workflow_dispatch: +permissions: + contents: read + jobs: sync: + permissions: + issues: write + contents: read uses: ConductionNL/.github/.github/workflows/openspec-sync.yml@main with: app-name: launchpad diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1a4950612..02ffc4b1b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,9 +27,15 @@ concurrency: group: release-${{ github.ref_name }} cancel-in-progress: false +permissions: + contents: read + jobs: unstable: if: github.ref == 'refs/heads/development' + permissions: + contents: write + pull-requests: write uses: ConductionNL/.github/.github/workflows/release.yml@main with: release-type: unstable @@ -38,6 +44,9 @@ jobs: beta: if: github.ref == 'refs/heads/beta' + permissions: + contents: write + pull-requests: write uses: ConductionNL/.github/.github/workflows/release.yml@main with: release-type: beta @@ -46,6 +55,9 @@ jobs: stable: if: github.ref == 'refs/heads/main' + permissions: + contents: write + pull-requests: write uses: ConductionNL/.github/.github/workflows/release.yml@main with: release-type: stable diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml new file mode 100644 index 000000000..974fea8be --- /dev/null +++ b/.github/workflows/scorecard.yml @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: 2026 Conduction B.V. +# SPDX-License-Identifier: EUPL-1.2 + +# OpenSSF Scorecard: rates this repository's supply-chain practices and +# publishes the result to the public Scorecard API and the Security tab. +name: Scorecard supply-chain security + +on: + branch_protection_rule: + schedule: + - cron: '30 4 * * 1' + push: + branches: [main] + workflow_dispatch: + +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-latest + permissions: + # Upload the results to code scanning. + security-events: write + # Publish the results and get a badge (OIDC token for the Scorecard API). + id-token: write + contents: read + actions: read + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Run analysis + uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0 + with: + results_file: results.sarif + results_format: sarif + publish_results: true + + - name: Upload artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: SARIF file + path: results.sarif + retention-days: 5 + + - name: Upload to code scanning + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + sarif_file: results.sarif diff --git a/.github/workflows/sync-to-beta.yml b/.github/workflows/sync-to-beta.yml index 76a442693..62fd631be 100644 --- a/.github/workflows/sync-to-beta.yml +++ b/.github/workflows/sync-to-beta.yml @@ -5,6 +5,12 @@ on: branches: - development +permissions: + contents: read + jobs: sync: + permissions: + contents: write + pull-requests: write uses: ConductionNL/.github/.github/workflows/sync-to-beta.yml@main diff --git a/.gitignore b/.gitignore index 5f731da4b..15734820d 100644 --- a/.gitignore +++ b/.gitignore @@ -19,7 +19,7 @@ Thumbs.db # Dependencies /vendor/ -/node_modules/ +/node_modules # Build artifacts /js/ @@ -62,8 +62,7 @@ Thumbs.db /custom_apps/ /config/ -# SBOM is published as release asset (see SECURITY.md), not stored in repo -sbom.cdx.json +# Intermediate SBOM files. The merged sbom.cdx.json at the root is committed. bom-php.cdx.json bom-npm.cdx.json @@ -81,3 +80,6 @@ bom-npm.cdx.json .stale/ /.e2e-state/ .phpunit.cache + +# embed-sdk build output (npm run build:embed-sdk) and its test builds +/src/embed-sdk/__tests__/.dist-*/ diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 000000000..ce6fe139e --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,76 @@ +# gitleaks configuration: the default rules, plus allowlists for findings +# that are not secrets. Each allowlist names the exact files and only the +# rules that fire there, so anything else in those files is still reported. + +[extend] +useDefault = true + +[[allowlists]] +description = "Documentation examples: the default admin:admin login of the local development and demo containers." +targetRules = ["curl-auth-user"] +paths = [ + '''(^|/)docs/Installation/demo\-environment\.md$''', +] + +[[allowlists]] +description = "Spec scenario: an example public-share token in a Given/When/Then step, not a credential." +targetRules = ["generic-api-key"] +paths = [ + '''(^|/)openspec/changes/archive/2026\-06\-14\-dashboard\-public\-share/specs/dashboard\-public\-share/spec\.md$''', +] + +[[allowlists]] +description = "Smoke-test notes: curl logins of the throwaway local test users (admin, user, alice)." +targetRules = ["curl-auth-user"] +paths = [ + '''(^|/)openspec/changes/archive/2026\-06\-14\-role\-based\-content/smoke\.md$''', +] + +[[allowlists]] +description = "Spec example: a truncated sample JWT in an SDK usage snippet, not a credential." +targetRules = ["generic-api-key"] +paths = [ + '''(^|/)openspec/changes/embedded\-analytics/specs/sdk\-and\-rendering\.md$''', +] + +[[allowlists]] +description = "Spec example: the same truncated sample JWT in the embedded-analytics SDK scenarios, not a credential." +targetRules = ["generic-api-key"] +paths = [ + '''(^|/)openspec/changes/embedded\-analytics/specs/embedded\-analytics/spec\.md$''', +] + +[[allowlists]] +description = "Design note: a curl example with a user:app-password placeholder." +targetRules = ["curl-auth-user"] +paths = [ + '''(^|/)openspec/changes/archive/2026\-11\-19\-governance\-rest\-api\-reference/design\.md$''', +] + +[[allowlists]] +description = "Spec scenario: an example public-share token in a Given/When/Then step, not a credential." +targetRules = ["generic-api-key"] +paths = [ + '''(^|/)openspec/specs/dashboard\-public\-share/spec\.md$''', +] + +[[allowlists]] +description = "E2E seed script: curl login built from the ADMIN_USER/ADMIN_PASSWORD environment variables, not a literal." +targetRules = ["curl-auth-user"] +paths = [ + '''(^|/)tests/e2e/seed\.sh$''', +] + +[[allowlists]] +description = "Feature documentation: a curl example with an alice:app-password placeholder." +targetRules = ["curl-auth-user"] +paths = [ + '''(^|/)docs/features/rest\-api\.md$''', +] + +[[allowlists]] +description = "Mock register seed data: embed token hashes are rotations of the hex string 0123456789abcdef, not hashes of real tokens." +targetRules = ["generic-api-key"] +paths = [ + '''(^|/)lib/Settings/launchpad_mock_register\.json$''', +] diff --git a/.maintainability-floor.json b/.maintainability-floor.json new file mode 100644 index 000000000..964e0f5e0 --- /dev/null +++ b/.maintainability-floor.json @@ -0,0 +1,21 @@ +{ + "measured_at": "2026-11-11T15:41:23Z", + "commit": "4d835a4387a923ae69cd19c49c13c80257b82aa6", + "tool_version": "estimator sha256:391d6ca5ea39; lizard 1.24.3; jscpd 4.0.5; profile five-star", + "tolerance": 0.01, + "overall": 4.21, + "overall_range": [ + 4.21, + 4.32 + ], + "properties": { + "volume": null, + "duplication": 4.54, + "unit_size": 3.4, + "unit_complexity": 4.02, + "unit_interfacing": 3.14, + "module_coupling": 4.65, + "component_independence": 5.5, + "component_entanglement": 5.5 + } +} diff --git a/.procedure-code-baseline.json b/.procedure-code-baseline.json new file mode 100644 index 000000000..57e568c36 --- /dev/null +++ b/.procedure-code-baseline.json @@ -0,0 +1 @@ +{"count": 0} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..9261e00f6 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,113 @@ +# AGENTS.md + +Guidance for coding agents working in this repository. Human contributor docs +are in [CONTRIBUTING.md](CONTRIBUTING.md), [DEVELOPMENT.md](DEVELOPMENT.md) and +[docs/development.md](docs/development.md). + +## What this app is + +LaunchPad is a Nextcloud app (app id `launchpad`, PHP backend in `lib/`, Vue +frontend in `src/`) that turns the Nextcloud dashboard into multiple +personalized dashboards with drag-and-drop widgets, custom shortcut tiles and +conditional visibility rules. Admins can roll dashboards out to groups as +templates; see [README.md](README.md) and [appinfo/info.xml](appinfo/info.xml). + +## Setup + +- Development happens in the nextcloud-docker-dev environment with this app + mounted into the Nextcloud container, as described in + [DEVELOPMENT.md](DEVELOPMENT.md). +- [docker/docker-compose.yml](docker/docker-compose.yml) is an evaluation stack + (Nextcloud with LaunchPad and OpenRegister, PostgreSQL, Redis): + `docker compose -f docker/docker-compose.yml up -d --build`, then open + `http://localhost:8080/apps/launchpad/`. +- [launchpad-compose.yaml](launchpad-compose.yaml) is a demo environment, not a + development environment: it does not mount your working copy. +- Install dependencies with `composer install` and `npm ci`. Both set + `git config core.hooksPath .githooks` (composer `post-install-cmd`, npm + `prepare`). + +## Build + +```bash +npm run dev # development build +npm run watch # development build, rebuilds on change +npm run build # production build, includes the embed SDK (npm run build:embed-sdk) +``` + +## Test + +```bash +composer test:unit # PHPUnit, suite in tests/Unit (config: phpunit.xml) +npm test # Vitest (config: vitest.config.js; src/**/__tests__, tests/vitest) +npm run test:e2e # Playwright against a running instance (config: playwright.config.ts, tests in tests/e2e) +composer test:integration # Newman run of tests/integration/launchpad.postman_collection.json +``` + +Coverage: `composer test:coverage` (PHP) and `npm run test:coverage` (Vitest). + +## Lint and quality + +```bash +composer check # lint, phpcs, psalm, test:unit +composer check:strict # full PHP suite: lint, lint:initial-state, lint:openapi, + # lint:spec-annotations, lint:licenses, phpcs, phpmd, psalm, phpstan, test:all +composer cs:fix # auto-fix PHP code style +npm run lint # eslint, then check:manifest, lint:initial-state, lint:translation-domain +npm run stylelint # styles in src/ and css/ +npm run format # prettier check +npm run check:l10n-parity +``` + +The API description in [openapi.json](openapi.json) is generated by +`composer openapi:generate` and checked by `composer lint:openapi`. + +## OpenSpec flow + +Behaviour is specified in [openspec/](openspec/) (project rules in +[openspec/config.yaml](openspec/config.yaml)). + +1. Propose a change in `openspec/changes//`: `proposal.md`, `design.md`, + `tasks.md` and delta specs in `specs//spec.md`, following the + existing changes in that folder. +2. The current, accepted behaviour lives in `openspec/specs//spec.md`. +3. When a change is done it moves to + `openspec/changes/archive/-/`. + +The pre-commit hook in [.githooks/pre-commit](.githooks/pre-commit) regenerates +`docs/features.json` when staged changes touch `openspec/specs/`. + +## Architecture decisions + +- App-level decision records live in + [openspec/architecture/](openspec/architecture/) (for example + `adr-001-information-architecture.md`). +- Company-wide ADRs live in the hydra repo; the pointer and index are in + [docs/adr/README.md](docs/adr/README.md), and LaunchPad's compliance against + them is tracked in [docs/adr-audit.md](docs/adr-audit.md). +- Per-change design decisions are in each change's `design.md` under + `openspec/changes/` (including `archive/`). +- Architecture overview: [docs/architecture.md](docs/architecture.md). + +## Repo conventions + +- Pages are manifest configuration: `src/main.js` builds the router from the + `pages` in [src/manifest.json](src/manifest.json) (via `routesFromManifest`), + merged with per-change fragments in [src/manifest.d/](src/manifest.d/). + Validate with `npm run check:manifest`. +- Custom widget types are registered in one place, + [src/constants/widgetRegistry.js](src/constants/widgetRegistry.js); keep + `EXPECTED_TYPES` in + `src/constants/__tests__/widgetRegistry.completeness.spec.js` in sync (see + [DEVELOPMENT.md](DEVELOPMENT.md)). +- OpenRegister is optional at runtime and is not an install-time dependency + (see `appinfo/info.xml` and the "Runtime-only OR consumption policy" in + [docs/architecture.md](docs/architecture.md)). +- Routes are declared in [appinfo/routes.php](appinfo/routes.php). +- User-visible strings are translated; translations live in [l10n/](l10n/). + +## Commit format + +Conventional Commits (`feat:`, `fix:`, `chore:`, `docs:`, `refactor:`), present +tense, imperative mood, first line at most 72 characters, as described in +[CONTRIBUTING.md](CONTRIBUTING.md). Pull requests target `development`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d222bee4..d6992fd82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,44 @@ All notable changes to this project will be documented in this file. ### Added +- **Scheduled Exports v1** (`scheduled-exports`): recurring exports with + multi-format rendering and multi-channel delivery (email, Files, webhook, + SFTP). Exports and their run records are OpenRegister objects reached + through `/api/exports` (owner or administrator only); a background runner + fires due exports every minute, renders PDF/PNG through an + operator-configured headless browser (`export_chromium_binary`) and + CSV/XLSX from the widgets' rows, once per distinct recipient filter + context, and delivers with per-recipient retries and exponential backoff. + Webhooks are HMAC-SHA256-signed (`X-LaunchPad-Signature`); webhook and + SFTP hosts must be listed in `export_allowed_hosts`; channel secrets are + encrypted at rest and redacted on read. An hourly janitor enforces + artefact and audit retention. + +- **Widget calculated fields, evaluation engine** (`widget-calculated-fields`, + in progress): spreadsheet-like formulas over a widget's data, parsed to a + JSON AST and type-checked at save time against an allowlisted function + set (math, aggregates, dates, durations, strings, conditionals, coercion). + Two evaluators, the browser's and PHP's, run the same AST and are held to + one shared test suite. Cross-widget references (`widget:.`) are + evaluated in dependency order and cycles are refused. A failing field + shows `null` with an inline error while the rest of the dashboard renders. + Format options (currency, number, date, duration) apply at display time + only, so alerting and export keep the native value. Storing fields on a + widget and server-side materialisation in OpenRegister follow. + +- **Cross-widget filter bus** (`drill-down-cross-widget-filter`): add a + cross-widget filter bus enabling drill-down exploration across dashboard + widgets. Widgets publish filters on click; all consuming widgets + re-render. Filter state is bookmarkable via the URL (`?f=`). An "Active filters" panel shows + every clause with its source and offers "Reset filters"; pinned clauses + survive a reset. Opt-in telemetry (an admin switch, off by default) + records which dimensions are filtered, never the values, and + `GET /api/dashboards/{uuid}/filter-events/report` counts the most-used + drill-down paths for the dashboard's owner and administrators. A chart + joins the bus by declaring `consumes` / `publishes` next to its + `dataSource`; a chart that declares nothing renders as before. Publishing + from a chart click waits on the chart library emitting its selection. + - **Dashboard quota limits** (`dashboard-quota-limits`): two admin-configurable numeric quotas — `maxDashboardsPerUser` and `maxWidgetsPerDashboard` — with server-side fail-closed enforcement on diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 6fb4ae953..dca602d63 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -1,80 +1,80 @@ -# Development - -## Prerequisites - -- Docker & Docker Compose -- Node.js >= 18 -- npm -- A running Nextcloud instance - -## Local Development - -This app is developed using the [nextcloud-docker-dev](https://github.com/juliushaertl/nextcloud-docker-dev) environment. The app is volume-mounted into the Nextcloud container. - -```bash -# Start the development environment -docker compose -f openregister/docker-compose.yml up -d - -# Build the frontend -cd launchpad -npm install -npm run dev -``` - -The app will be available at `http://localhost:8080/apps/launchpad`. - -## Frontend Build - -```bash -npm install # Install dependencies -npm run dev # Development build (watch mode) -npm run build # Production build -``` - -## Product Page - -The product page at [launchpad.app](https://launchpad.app) is built with [Docusaurus 3](https://docusaurus.io/) and deployed via GitHub Pages. - -### How it works - -- The Docusaurus setup lives in the `docusaurus/` folder -- Documentation content comes from the `docs/` folder at the project root — **not** duplicated inside `docusaurus/` -- The Docusaurus config uses `path: '../docs'` to reference the root docs directly -- Pushing to the `development` branch triggers the GitHub Actions workflow (`.github/workflows/documentation.yml`) which builds and deploys to the `gh-pages` branch -- GitHub Pages serves the built site at `launchpad.app` (configured via `static/CNAME`) - -### Local preview - -```bash -cd docusaurus -npm install -npm start # Dev server at http://localhost:3000 with hot reload -``` - -### Adding documentation - -Simply add or edit Markdown files in the `docs/` folder. The sidebar is auto-generated from the folder structure. Changes will appear on the product page after pushing to `development`. - -## Adding a widget type - -The widget registry (`src/constants/widgetRegistry.js`) is the single source of truth for "addable" custom widget types (REQ-WDG-014). Because many widget capabilities ship in parallel branches that all touch the same object, the file is a heavy merge-conflict site -- a regression that silently drops a type would silently disappear from the Add Custom Widget picker without any test signal. To add a new widget type: - -- Update `src/constants/widgetRegistry.js` with the new entry (`renderer`, `form`, `defaultContent`, `displayName`, `icon`). -- Update `EXPECTED_TYPES` in `src/constants/__tests__/widgetRegistry.completeness.spec.js` (REQ-WDG-023) so the completeness guard stays in sync. The test will fail with a precise diff if you forget. -- Implement the renderer + form Vue components following the pattern of an existing widget (e.g. `LabelWidget.vue` + `LabelForm.vue`). -- Add i18n keys for the type's `displayName` and any user-facing form labels to all four `l10n/` files (`en.js`, `en.json`, `nl.js`, `nl.json`). -- Add the canonical capability spec under `openspec/specs//spec.md` so the type's REQ-* identifiers, defaults, and acceptance scenarios are documented. - -## Security review checklist - -### Extending the SVG sanitiser whitelist - -`lib/Service/SvgSanitiser.php` enforces a deliberately conservative whitelist of allowed SVG element and attribute names (REQ-RES-010 / REQ-RES-011 in `openspec/specs/resource-uploads/spec.md`). Every uploaded SVG is parsed via `DOMDocument` with `LIBXML_NONET | LIBXML_NOENT` and the resulting tree is filtered against `ALLOWED_ELEMENTS` and `ALLOWED_ATTRIBUTES`. Anything not on those lists is removed before persistence, and the persisted bytes (NOT the original) are what subsequently get served back to other users' browsers. - -If you propose adding a new element name to `ALLOWED_ELEMENTS` or a new attribute to `ALLOWED_ATTRIBUTES`: - -- A security review is required before merge (XSS surface change). -- Verify the new element / attribute cannot carry executable payloads in any browser SVG renderer (e.g. `` `attributeName` injection, `` event triggering, etc.). -- Add a PHPUnit scenario covering the new surface, plus a negative scenario showing that a known-bad construct involving the new name is still rejected. -- Update REQ-RES-010 / REQ-RES-011 in the canonical spec to reflect the new whitelist size and add the element / attribute name explicitly. -- The sanitiser runs server-side BEFORE the size cap (REQ-RES-009), so an over-permissive whitelist becomes stored XSS the moment a sanitised-looking SVG is rendered back into a logged-in user's browser. +# Development + +## Prerequisites + +- Docker & Docker Compose +- Node.js >= 18 +- npm +- A running Nextcloud instance + +## Local Development + +This app is developed using the [nextcloud-docker-dev](https://github.com/juliushaertl/nextcloud-docker-dev) environment. The app is volume-mounted into the Nextcloud container. + +```bash +# Start the development environment +docker compose -f openregister/docker-compose.yml up -d + +# Build the frontend +cd launchpad +npm install +npm run dev +``` + +The app will be available at `http://localhost:8080/apps/launchpad`. + +## Frontend Build + +```bash +npm install # Install dependencies +npm run dev # Development build (watch mode) +npm run build # Production build +``` + +## Product Page + +The product page at [launchpad.app](https://launchpad.app) is built with [Docusaurus 3](https://docusaurus.io/) and deployed via GitHub Pages. + +### How it works + +- The Docusaurus setup lives in the `docusaurus/` folder +- Documentation content comes from the `docs/` folder at the project root — **not** duplicated inside `docusaurus/` +- The Docusaurus config uses `path: '../docs'` to reference the root docs directly +- Pushing to the `development` branch triggers the GitHub Actions workflow (`.github/workflows/documentation.yml`) which builds and deploys to the `gh-pages` branch +- GitHub Pages serves the built site at `launchpad.app` (configured via `static/CNAME`) + +### Local preview + +```bash +cd docusaurus +npm install +npm start # Dev server at http://localhost:3000 with hot reload +``` + +### Adding documentation + +Simply add or edit Markdown files in the `docs/` folder. The sidebar is auto-generated from the folder structure. Changes will appear on the product page after pushing to `development`. + +## Adding a widget type + +The widget registry (`src/constants/widgetRegistry.js`) is the single source of truth for "addable" custom widget types (REQ-WDG-014). Because many widget capabilities ship in parallel branches that all touch the same object, the file is a heavy merge-conflict site -- a regression that silently drops a type would silently disappear from the Add Custom Widget picker without any test signal. To add a new widget type: + +- Update `src/constants/widgetRegistry.js` with the new entry (`renderer`, `form`, `defaultContent`, `displayName`, `icon`). +- Update `EXPECTED_TYPES` in `src/constants/__tests__/widgetRegistry.completeness.spec.js` (REQ-WDG-023) so the completeness guard stays in sync. The test will fail with a precise diff if you forget. +- Implement the renderer + form Vue components following the pattern of an existing widget (e.g. `LabelWidget.vue` + `LabelForm.vue`). +- Add i18n keys for the type's `displayName` and any user-facing form labels to `l10n/en.json` (identity), `l10n/nl.json` and `l10n/nl.js`. Do not add them to `l10n/en.js`: it carries only entries whose English differs from the key (renamed ids, plurals), because an identity entry costs bytes on every page and changes nothing (`tests/vitest/l10n-browser-catalogue.spec.ts` fails on one). +- Add the canonical capability spec under `openspec/specs//spec.md` so the type's REQ-* identifiers, defaults, and acceptance scenarios are documented. + +## Security review checklist + +### Extending the SVG sanitiser whitelist + +`lib/Service/SvgSanitiser.php` enforces a deliberately conservative whitelist of allowed SVG element and attribute names (REQ-RES-010 / REQ-RES-011 in `openspec/specs/resource-uploads/spec.md`). Every uploaded SVG is parsed via `DOMDocument` with `LIBXML_NONET | LIBXML_NOENT` and the resulting tree is filtered against `ALLOWED_ELEMENTS` and `ALLOWED_ATTRIBUTES`. Anything not on those lists is removed before persistence, and the persisted bytes (NOT the original) are what subsequently get served back to other users' browsers. + +If you propose adding a new element name to `ALLOWED_ELEMENTS` or a new attribute to `ALLOWED_ATTRIBUTES`: + +- A security review is required before merge (XSS surface change). +- Verify the new element / attribute cannot carry executable payloads in any browser SVG renderer (e.g. `` `attributeName` injection, `` event triggering, etc.). +- Add a PHPUnit scenario covering the new surface, plus a negative scenario showing that a known-bad construct involving the new name is still rejected. +- Update REQ-RES-010 / REQ-RES-011 in the canonical spec to reflect the new whitelist size and add the element / attribute name explicitly. +- The sanitiser runs server-side BEFORE the size cap (REQ-RES-009), so an over-permissive whitelist becomes stored XSS the moment a sanitised-looking SVG is rendered back into a logged-in user's browser. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..6778093f4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,109 @@ +# syntax=docker/dockerfile:1 +# +# Evaluation image for launchpad: the official Nextcloud image with this app, +# built from this repository, and OpenRegister, taken from its release. +# +# docker build -t ghcr.io/conductionnl/launchpad . +# +# The supported production install is still the Nextcloud App Store. This image +# is for trying the app out, for demos and for test environments. +# +# Rendered from ConductionNL/.github templates/app-deploy. Change the template, +# not this copy, and render it again. +# +# SPDX-FileCopyrightText: 2026 Conduction B.V. +# SPDX-License-Identifier: EUPL-1.2 + +# Nextcloud 33 is the newest major whose image still ships PHP 8.3. The 34 and +# 35 images ship PHP 8.5, which some apps in the fleet do not support yet. +ARG NEXTCLOUD_IMAGE=nextcloud:33.0.10-apache +ARG APP_ID=launchpad + +# ── Frontend: the same steps the release workflow runs ── +FROM node:22-bookworm-slim AS frontend +WORKDIR /app +COPY . . +# Honour engines.npm: Node 22 bundles npm 10, several apps require npm 11. +RUN set -eu; \ + range="$(node -p "((require('./package.json').engines)||{}).npm||''")"; \ + if [ -n "$range" ]; then npm install -g "npm@$range"; fi; \ + npm ci --no-audit --no-fund; \ + npm run build; \ + rm -rf node_modules + +# ── Backend: runtime composer dependencies only ── +FROM composer:2 AS vendor +WORKDIR /app +COPY --from=frontend /app /app +# The lock was resolved for the app's own platform; the composer image does not +# carry Nextcloud's PHP extensions, so platform checks are left to Nextcloud. +RUN composer install --no-dev --no-interaction --no-progress \ + --optimize-autoloader --classmap-authoritative --ignore-platform-reqs + +# ── Package: the same file set as the release tarball ── +FROM alpine:3.20 AS package +ARG APP_ID +# hadolint ignore=DL3018 +RUN apk add --no-cache rsync +COPY --from=vendor /app /app +RUN mkdir -p "/out/${APP_ID}" && rsync -a \ + --exclude='/.git*' --exclude='/.github' --exclude='/.claude' \ + --exclude='/.hydra' --exclude='/.vscode' --exclude='/.nextcloud' \ + --exclude='/docker' --exclude='/charts' \ + --exclude='/Dockerfile' --exclude='/.dockerignore' \ + --exclude='/docker-compose*.yml' --exclude='/*-compose.yaml' \ + --exclude='/docs' --exclude='/docusaurus' --exclude='/website' \ + --exclude='/node_modules' \ + --include='/src/' --include='/src/manifest.json' --exclude='/src/*' \ + --exclude='/tests' --exclude='/test-scenarios' --exclude='/openspec' \ + --exclude='/data' --exclude='/resources' --exclude='/phpcs-custom-sniffs' \ + --exclude='/package*.json' --exclude='/composer.*' \ + --exclude='/*.config.js' --exclude='/*.config.mjs' --exclude='/*.config.ts' \ + --exclude='/php*.xml' --exclude='/psalm.xml' --exclude='/phpstan*' \ + --exclude='/sbom.cdx.json' --exclude='/.phpunit*' \ + /app/ "/out/${APP_ID}/" + +# ── OpenRegister: the newest stable release, checked against its SHA-256 ── +FROM alpine:3.20 AS openregister +ARG APP_ID +# Empty means the newest stable release at build time. Prereleases are refused. +# Pin it for a reproducible build: --build-arg OPENREGISTER_VERSION=2.1.0 +ARG OPENREGISTER_VERSION= +SHELL ["/bin/ash", "-euo", "pipefail", "-c"] +# hadolint ignore=DL3018 +RUN apk add --no-cache curl jq tar +RUN mkdir -p /out; \ + if [ "${APP_ID}" = "openregister" ]; then exit 0; fi; \ + version="${OPENREGISTER_VERSION#v}"; \ + if [ -z "$version" ]; then \ + version="$(curl -fsSL https://api.github.com/repos/ConductionNL/openregister/releases/latest \ + | jq -r '.tag_name' | sed 's/^v//')"; \ + fi; \ + case "$version" in \ + ''|*-*) echo "OpenRegister '$version' is not a stable release" >&2; exit 1 ;; \ + esac; \ + base="https://github.com/ConductionNL/openregister/releases/download/v${version}/openregister-${version}.tar.gz"; \ + curl -fsSL -o /tmp/or.tar.gz "$base"; \ + sha="$(curl -fsSL "${base}.sha256" | cut -d' ' -f1)"; \ + echo "${sha} /tmp/or.tar.gz" | sha256sum -c -; \ + mkdir /tmp/stage && tar -xzf /tmp/or.tar.gz -C /tmp/stage; \ + mv "$(find /tmp/stage -mindepth 1 -maxdepth 1 -type d | head -n 1)" /out/openregister; \ + printf '%s sha256:%s\n' "$version" "$sha" > /out/openregister/.image-release + +# ── Runtime ── +# hadolint ignore=DL3006 +FROM ${NEXTCLOUD_IMAGE} +ARG APP_ID +LABEL org.opencontainers.image.title="${APP_ID}" \ + org.opencontainers.image.description="Nextcloud with ${APP_ID} and OpenRegister, for evaluation" \ + org.opencontainers.image.source="https://github.com/ConductionNL/${APP_ID}" \ + org.opencontainers.image.vendor="Conduction B.V." +# The entrypoint copies these into the custom_apps volume on first start; the +# before-starting hook keeps that copy in step with the image afterwards. +COPY --from=openregister --chown=www-data:www-data /out/ /usr/src/nextcloud/custom_apps/ +COPY --from=package --chown=www-data:www-data /out/ /usr/src/nextcloud/custom_apps/ +COPY --chmod=0755 docker/entrypoint-hooks/before-starting/ /docker-entrypoint-hooks.d/before-starting/ +# Enabled in this order: OpenRegister owns the registers the app declares into. +ENV NEXTCLOUD_IMAGE_APPS="openregister ${APP_ID}" +# Apache starts as root to bind port 80 and serves every request as www-data; +# the entrypoint and its hooks run occ as www-data too. diff --git a/README.md b/README.md index d4911e6e3..0129dd223 100644 --- a/README.md +++ b/README.md @@ -17,10 +17,16 @@ --- -LaunchPad supercharges the Nextcloud dashboard. Create multiple personalized workspaces with drag-and-drop widgets, custom shortcut tiles, and smart visibility rules — then let admins roll out templates to entire teams. It works with every existing Nextcloud dashboard widget out of the box, supporting both the v1 and v2 Dashboard APIs. +LaunchPad supercharges the Nextcloud dashboard. Create multiple personalized workspaces with drag-and-drop widgets, custom shortcut tiles, and smart visibility rules — then let admins roll out templates to entire teams. It works with every existing Nextcloud dashboard widget out of the box, supporting both the v1 and v2 Dashboard APIs. LaunchPad is available in the [Nextcloud App Store](https://apps.nextcloud.com/apps/launchpad). 📚 **[Step-by-step tutorials](https://launchpad.conduction.nl/docs/category/tutorials)** — user + admin walkthroughs with screenshots, kept in sync with the live UI via the [journeydoc](https://github.com/ConductionNL/hydra/blob/development/openspec/architecture/adr-030-journeydoc-pattern.md) capture spec. +## Test coverage + + +Measured test coverage: 95.6% of statements (PHP 96.2% of 32,721 statements, JavaScript 94.1% of 13,116 statements), at commit `6fae5e0d0` on 2026-11-23. The figures come from [`coverage-summary.json`](coverage-summary.json); refresh them with `composer coverage:publish`. + + ## Screenshots @@ -134,6 +140,29 @@ npm run build php occ app:enable launchpad ``` +### Try it with Docker + +The repository builds an evaluation image: the official Nextcloud image with launchpad and OpenRegister installed and enabled. It is meant for trying the app out and for test environments. For production, install the app from the Nextcloud App Store. + +```bash +docker compose -f docker/docker-compose.yml up -d --build +``` + +Open http://localhost:8080/apps/launchpad/ and sign in as `admin` with password `admin`. The first start takes a minute or two. Set `NEXTCLOUD_ADMIN_PASSWORD` and `APP_PORT` to change the password and the port; `docker/docker-compose.yml` lists every setting. `docker compose -f docker/docker-compose.yml down -v` removes the stack and its data. + +Released versions are published as `ghcr.io/conductionnl/launchpad`, so leaving out `--build` uses the published image. + +### Run it on Kubernetes + +`charts/launchpad` wraps the official [Nextcloud Helm chart](https://github.com/nextcloud/helm) and runs the same image with PostgreSQL: + +```bash +helm dependency build charts/launchpad +helm install launchpad charts/launchpad --set nextcloud.nextcloud.host=launchpad.example.org +``` + +Change the passwords in `charts/launchpad/values.yaml` before you install it anywhere that matters. + ## Development ### Start the environment diff --git a/REUSE.toml b/REUSE.toml index 1418abaa1..030b3d702 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -46,3 +46,10 @@ path = [ ] SPDX-FileCopyrightText = "2024 Conduction B.V. " SPDX-License-Identifier = "CC0-1.0" + +# Material Design Icons (newspaper-variant-outline, link-variant). +[[annotations]] +path = ["img/news-dark.svg", "img/links-dark.svg"] +precedence = "override" +SPDX-FileCopyrightText = "2020 Pictogrammers " +SPDX-License-Identifier = "Apache-2.0" diff --git a/SECURITY.md b/SECURITY.md index 4657ac8a5..34a631ad4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -60,7 +60,7 @@ curl -sL https://github.com/ConductionNL/launchpad/releases/download/v1.0.0/sbom ### Update cadence -A new SBOM is generated and attached on every release tag. We do not commit SBOMs into the repository tree — they are published exclusively as release assets to keep main-branch history clean and to guarantee every SBOM corresponds to an immutable release artifact. +A new SBOM is generated and attached on every release tag. The `sbom.cdx.json` at the repository root is a snapshot of the dependencies on the `development` branch. For an SBOM that matches an immutable release, use the release assets above. ### Format diff --git a/appinfo/info.xml b/appinfo/info.xml index 933756679..65dc9c900 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -6,11 +6,11 @@ launchpad - LaunchPad - LaunchPad + Launchpad + Launchpad Drag-and-drop dashboards with templates, tiles, and smart visibility Drag-and-drop dashboards met templates, tegels en slimme zichtbaarheid - - - 1.1.6-beta.20261002211709 + 1.1.17-unstable.20261125083210 EUPL-1.2 Conduction LaunchPad @@ -80,7 +80,7 @@ Vrij en open source onder de EUPL-1.2-licentie. dependency here. --> - + OCA\LaunchPad\BackgroundJob\HealthPingRefreshJob + + OCA\LaunchPad\BackgroundJob\ProfileFieldsSyncJob + + OCA\LaunchPad\BackgroundJob\ScheduledExportRunner + + OCA\LaunchPad\BackgroundJob\ScheduledExportJanitor + + OCA\LaunchPad\BackgroundJob\AnnouncementNotifyJob + + OCA\LaunchPad\BackgroundJob\StorageSnapshotJob + + OCA\LaunchPad\BackgroundJob\SummaryMailJob @@ -118,6 +130,27 @@ Vrij en open source onder de EUPL-1.2-licentie. no default template. Idempotent, so an instance that already has dashboards is untouched. --> OCA\LaunchPad\Repair\SeedDefaultDashboard + + OCA\LaunchPad\Repair\MirrorSharedDashboards + + OCA\LaunchPad\Repair\BroadenDefaultWidgetRule + + OCA\LaunchPad\Repair\BroadenShippedGroupWidgetRules + + OCA\LaunchPad\Repair\SetDefaultApp + + OCA\LaunchPad\Repair\MergeAllowedSites + + OCA\LaunchPad\Repair\MintAnnouncementKeys OCA\LaunchPad\Repair\InitializeActions @@ -139,6 +172,9 @@ Vrij en open source onder de EUPL-1.2-licentie. dashboard at all and renders the "contact your administrator" empty state. --> OCA\LaunchPad\Repair\SeedDefaultDashboard + + OCA\LaunchPad\Repair\SetDefaultApp @@ -162,6 +198,8 @@ Vrij en open source onder de EUPL-1.2-licentie. OCA\LaunchPad\Command\DemoShowcasesInstallCommand OCA\LaunchPad\Command\DemoShowcasesListCommand + OCA\LaunchPad\Command\DemoLoadCommand + OCA\LaunchPad\Command\TemplateInstallCommand OCA\LaunchPad\Command\SetupCommand @@ -172,6 +210,15 @@ Vrij en open source onder de EUPL-1.2-licentie. + + + OCA\LaunchPad\Activity\Settings\DashboardSharedSetting + OCA\LaunchPad\Activity\Settings\DashboardPublishedSetting + OCA\LaunchPad\Activity\Settings\DashboardUpdatedSetting + OCA\LaunchPad\Activity\Settings\DashboardAcknowledgedSetting + ', + subject: $html + ); + }//end shieldStorageMarkup() + + /** + * Undo shieldStorageMarkup() on serialised body HTML. + * + * @param string $html The serialised body. + * + * @return string The body with storage element names and CDATA restored. + */ + private static function restoreStorageMarkup(string $html): string { + $html = (string)preg_replace(pattern: '/<(\/?)(ac|ri)--/i', replacement: '<$1$2:', subject: $html); + return (string)preg_replace_callback( + pattern: '//', + callback: static fn (array $match): string => '', + subject: $html + ); + }//end restoreStorageMarkup() + /** * Regex fallback for body extraction when DOMXPath finds nothing. * diff --git a/lib/Service/Confluence/HtmlSanitizer.php b/lib/Service/Confluence/HtmlSanitizer.php index 69b3feb7f..5092935fd 100644 --- a/lib/Service/Confluence/HtmlSanitizer.php +++ b/lib/Service/Confluence/HtmlSanitizer.php @@ -276,7 +276,7 @@ private function stripDisallowedAttributes(DOMElement $element): void { * Only `href` and `src` are URL-bearing in the allow-list. For those, * the value is accepted only when it is: * - a relative path (no scheme), OR - * - begins with `http://`, `https://`, or `mailto:`. + * - begins with `http://`, `https://`, `mailto:` or `tel:`. * * Everything else — including `javascript:`, `data:`, `vbscript:`, * `blob:`, and `file:` — is blocked (REQ-CFLI-012-SEC). @@ -303,7 +303,7 @@ private function isUnsafeUrl(string $name, string $value): bool { } // Allow only the safe explicit schemes. - if (preg_match(pattern: '/^(?:https?|mailto):/iu', subject: $needle) === 1) { + if (preg_match(pattern: '/^(?:https?|mailto|tel):/iu', subject: $needle) === 1) { return false; } diff --git a/lib/Service/ConfluenceDashboardWriters.php b/lib/Service/ConfluenceDashboardWriters.php new file mode 100644 index 000000000..6eb287b30 --- /dev/null +++ b/lib/Service/ConfluenceDashboardWriters.php @@ -0,0 +1,52 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; + +/** + * What the Confluence importer writes dashboards with: the factory, the tree checks and the + * dashboard and placement mappers. + * + * @spec openspec/specs/dashboards/spec.md + */ +class ConfluenceDashboardWriters { + /** + * Constructor. + * + * @param DashboardFactory $dashboardFactory Dashboard factory. + * @param DashboardTreeService $treeService Tree validation / lookups. + * @param DashboardMapper $dashboardMapper Dashboard mapper. + * @param WidgetPlacementMapper $placementMapper Widget mapper. + */ + public function __construct( + public readonly DashboardFactory $dashboardFactory, + public readonly DashboardTreeService $treeService, + public readonly DashboardMapper $dashboardMapper, + public readonly WidgetPlacementMapper $placementMapper, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ConfluenceImportRun.php b/lib/Service/ConfluenceImportRun.php new file mode 100644 index 000000000..f7f1c32e5 --- /dev/null +++ b/lib/Service/ConfluenceImportRun.php @@ -0,0 +1,142 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2024 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Service\Confluence\ParsedPage; +use Throwable; + +/** + * Tally of one Confluence import. + * + * @spec openspec/specs/confluence-html-import/spec.md + */ +final class ConfluenceImportRun { + + /** + * Lower-cased pageId to the created dashboard UUID. + * + * @var array + */ + public array $pageIdToUuid = []; + + /** + * PageId to the created page. + * + * @var array + */ + public array $createdPages = []; + + /** + * Number of dashboards created. + * + * @var integer + */ + public int $createdCount = 0; + + /** + * Number of pages skipped. + * + * @var integer + */ + public int $skippedCount = 0; + + /** + * One entry per skipped page. + * + * @var array + */ + public array $errors = []; + + /** + * Constructor. + * + * @param string $currentUserId Importing user UID. + * @param string|null $rootParentUuid Dashboard UUID root pages are slotted under, or null. + */ + public function __construct( + public readonly string $currentUserId, + public readonly ?string $rootParentUuid, + ) { + }//end __construct() + + /** + * Record a page that became a dashboard. + * + * @param ParsedPage $page The page. + * @param string $dashboardUuid The new dashboard UUID. + * + * @return void + * + * @spec openspec/specs/confluence-html-import/spec.md + */ + public function recordCreated(ParsedPage $page, string $dashboardUuid): void { + $this->pageIdToUuid[strtolower(string: $page->pageId)] = $dashboardUuid; + $this->createdPages[$page->pageId] = $page; + $this->createdCount++; + }//end recordCreated() + + /** + * Record a page that could not be imported. + * + * @param ParsedPage $page The page. + * @param Throwable $reason Why it failed. + * + * @return void + * + * @spec openspec/specs/confluence-html-import/spec.md + */ + public function recordSkipped(ParsedPage $page, Throwable $reason): void { + $this->skippedCount++; + $this->errors[] = [ + 'pageId' => $page->pageId, + 'reason' => $reason->getMessage(), + ]; + }//end recordSkipped() + + /** + * The import result. + * + * @param array $warnings Archive and link-rewrite warnings. + * @param string $assetFolder The asset folder path. + * + * @return array{ + * createdDashboardCount:int, + * skippedPageCount:int, + * errors:array, + * warnings:array, + * assetFolder:string + * } + * + * @spec openspec/specs/confluence-html-import/spec.md + */ + public function result(array $warnings, string $assetFolder): array { + return [ + 'createdDashboardCount' => $this->createdCount, + 'skippedPageCount' => $this->skippedCount, + 'errors' => $this->errors, + 'warnings' => $warnings, + 'assetFolder' => $assetFolder, + ]; + }//end result() +}//end class diff --git a/lib/Service/ConfluenceImportService.php b/lib/Service/ConfluenceImportService.php index 49e0b27d9..4dd7d5cb5 100644 --- a/lib/Service/ConfluenceImportService.php +++ b/lib/Service/ConfluenceImportService.php @@ -30,13 +30,9 @@ use DateTime; use OCA\LaunchPad\Db\Dashboard; -use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacement; -use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Kernel\Contracts\ConfluenceImportServiceInterface; use OCA\LaunchPad\Service\Confluence\ArchiveParser; -use OCA\LaunchPad\Service\Confluence\HtmlSanitizer; -use OCA\LaunchPad\Service\Confluence\LinkRewriter; -use OCA\LaunchPad\Service\Confluence\MacroRenderer; use OCA\LaunchPad\Service\Confluence\ParsedPage; use OCP\AppFramework\Db\DoesNotExistException; use OCP\IDBConnection; @@ -50,7 +46,7 @@ * Top-level orchestrator must collaborate with parser, sanitiser, * macro renderer, link rewriter, factory, and two mappers. */ -class ConfluenceImportService { +class ConfluenceImportService implements ConfluenceImportServiceInterface { /** * Default text-display widget identifier (matches the built-in @@ -77,29 +73,18 @@ class ConfluenceImportService { /** * Constructor. * - * @param ArchiveParser $parser Archive reader. - * @param HtmlSanitizer $sanitizer HTML allow-list filter. - * @param MacroRenderer $macroRenderer Macro → HTML renderer. - * @param LinkRewriter $linkRewriter Internal-link rewriter. - * @param DashboardFactory $dashboardFactory Dashboard factory. - * @param DashboardTreeService $treeService Tree validation / lookups. - * @param DashboardMapper $dashboardMapper Dashboard mapper. - * @param WidgetPlacementMapper $placementMapper Widget mapper. - * @param IDBConnection $db DB connection. - * @param LoggerInterface $logger PSR-3 logger. + * @param ConfluencePageReaders $readers The archive parser, HTML sanitizer, macro renderer and link rewriter. + * @param ConfluenceDashboardWriters $writers The dashboard factory, tree service and dashboard and + * placement mappers. + * @param IDBConnection $db DB connection. + * @param LoggerInterface $logger PSR-3 logger. @SuppressWarnings(PHPMD.ExcessiveParameterList) + * Top-level orchestrator must wire every collaborator. * * @SuppressWarnings(PHPMD.ExcessiveParameterList) - * Top-level orchestrator must wire every collaborator. */ public function __construct( - private readonly ArchiveParser $parser, - private readonly HtmlSanitizer $sanitizer, - private readonly MacroRenderer $macroRenderer, - private readonly LinkRewriter $linkRewriter, - private readonly DashboardFactory $dashboardFactory, - private readonly DashboardTreeService $treeService, - private readonly DashboardMapper $dashboardMapper, - private readonly WidgetPlacementMapper $placementMapper, + private readonly ConfluencePageReaders $readers, + private readonly ConfluenceDashboardWriters $writers, private readonly IDBConnection $db, private readonly LoggerInterface $logger, ) { @@ -125,7 +110,7 @@ public function __construct( * @spec openspec/specs/confluence-html-import/spec.md */ public function dryRun(string $zipPath): array { - $archive = $this->parser->parse(zipPath: $zipPath); + $archive = $this->readers->parser->parse(zipPath: $zipPath); $timestamp = $this->buildTimestamp(); return [ @@ -161,141 +146,123 @@ public function import( string $currentUserId, ?string $parentUuid = null, ): array { - $archive = $this->parser->parse(zipPath: $zipPath); + $archive = $this->readers->parser->parse(zipPath: $zipPath); $timestamp = $this->buildTimestamp(); - if ($parentUuid !== null && $parentUuid !== '') { - // 404 surfaces to caller as a warning — pages still import as roots. - try { - $this->dashboardMapper->findByUuid(uuid: $parentUuid); - } catch (DoesNotExistException) { - $this->logger->warning( - message: 'Confluence import: parent dashboard not found, falling back to roots', - context: ['parentUuid' => $parentUuid] - ); - $parentUuid = null; - } - } + $run = new ConfluenceImportRun( + currentUserId: $currentUserId, + rootParentUuid: $this->existingRootParent(parentUuid: $parentUuid) + ); $ordered = $this->orderParentsBeforeChildren(pages: $archive->pages); - $pageIdToUuid = []; - $pageIdToOrder = []; - $createdCount = 0; - $skippedCount = 0; - $errors = []; - $rewriteWarnings = $archive->warnings; - + $archiveWarnings = $archive->warnings; foreach ($ordered as $page) { - $resolvedParent = $this->resolveParentUuid( - page: $page, - pageIdToUuid: $pageIdToUuid, - rootParentUuid: $parentUuid - ); + $this->importPage(page: $page, run: $run); + } - try { - $dashboardUuid = $this->createDashboardForPage( - page: $page, - parentUuid: $resolvedParent, - currentUserId: $currentUserId - ); - - $pageIdToUuid[strtolower(string: $page->pageId)] = $dashboardUuid; - $pageIdToOrder[$page->pageId] = $page; - $createdCount++; - } catch (Throwable $e) { - $skippedCount++; - $errors[] = [ - 'pageId' => $page->pageId, - 'reason' => $e->getMessage(), - ]; - $this->logger->warning( - message: 'Confluence page skipped during import', - context: ['pageId' => $page->pageId, 'exception' => $e] - ); - }//end try - }//end foreach - - $rewriteWarnings = array_merge( - $rewriteWarnings, + $warnings = array_merge( + $archiveWarnings, $this->backfillWidgetContent( - pages: $pageIdToOrder, - pageIdToUuid: $pageIdToUuid + pages: $run->createdPages, + pageIdToUuid: $run->pageIdToUuid ) ); - return [ - 'createdDashboardCount' => $createdCount, - 'skippedPageCount' => $skippedCount, - 'errors' => $errors, - 'warnings' => $rewriteWarnings, - 'assetFolder' => 'LaunchPad/Imports/' . $timestamp, - ]; + return $run->result(warnings: $warnings, assetFolder: 'LaunchPad/Imports/' . $timestamp); }//end import() /** - * Topologically order pages so every parent is created before its - * children. Pages whose declared parent never resolves are emitted - * at the end so they end up as orphans (root-level imports). + * The requested root parent UUID when that dashboard exists. * - * @param ParsedPage[] $pages The pages to sort. + * A missing parent is logged and the pages import as roots (REQ-CFLI-011). * - * @return ParsedPage[] Ordered list (parents first). + * @param string|null $parentUuid The requested parent dashboard UUID. * - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * Two-pass topological order with a sibling sort and parent - * cycle detection — splitting into helpers would require - * passing the per-pass closure state across method boundaries. - * @SuppressWarnings(PHPMD.NPathComplexity) - * Same two-pass ordering: the acyclic-path count is the product of - * the independent per-page checks (known parent, self-reference, - * already-resolved, cycle break), which multiply even though the - * passes themselves stay flat. + * @return string|null The parent UUID to slot root pages under, or null. */ - private function orderParentsBeforeChildren(array $pages): array { - $byPageId = []; - foreach ($pages as $page) { - $byPageId[strtolower(string: $page->pageId)] = $page; + private function existingRootParent(string|null $parentUuid): string|null { + if ($parentUuid === null || $parentUuid === '') { + return $parentUuid; } - $resolved = []; - $emitted = []; + if ($this->dashboardExists(uuid: $parentUuid) === true) { + return $parentUuid; + } - $emit = static function (ParsedPage $page) use (&$emitted, &$resolved): void { - $key = strtolower(string: $page->pageId); - if (isset($emitted[$key]) === true) { - return; - } + $this->logger->warning( + message: 'Confluence import: parent dashboard not found, falling back to roots', + context: ['parentUuid' => $parentUuid] + ); + return null; + }//end existingRootParent() - $emitted[$key] = true; - $resolved[] = $page; - }; + /** + * Whether a dashboard with this UUID exists. + * + * @param string $uuid The dashboard UUID. + * + * @return bool True when the mapper finds it. + */ + private function dashboardExists(string $uuid): bool { + try { + $this->writers->dashboardMapper->findByUuid(uuid: $uuid); + } catch (DoesNotExistException) { + return false; + } - $visit = function (ParsedPage $page) use (&$visit, &$emitted, &$byPageId, $emit): void { - $key = strtolower(string: $page->pageId); - if (isset($emitted[$key]) === true) { - return; - } + return true; + }//end dashboardExists() - $parentKey = null; - if ($page->parentPageId !== null) { - $parentKey = strtolower(string: $page->parentPageId); - } + /** + * Create the dashboard for one page and tally the outcome. + * + * @param ParsedPage $page The page to import. + * @param ConfluenceImportRun $run The import in progress. + * + * @return void + */ + private function importPage(ParsedPage $page, ConfluenceImportRun $run): void { + $resolvedParent = $this->resolveParentUuid( + page: $page, + pageIdToUuid: $run->pageIdToUuid, + rootParentUuid: $run->rootParentUuid + ); - if ($parentKey !== null - && $parentKey !== $key - && isset($byPageId[$parentKey]) === true - && isset($emitted[$parentKey]) === false - ) { - $visit($byPageId[$parentKey]); - } + try { + $dashboardUuid = $this->createDashboardForPage( + page: $page, + parentUuid: $resolvedParent, + currentUserId: $run->currentUserId + ); - $emit($page); - }; + $run->recordCreated(page: $page, dashboardUuid: $dashboardUuid); + } catch (Throwable $e) { + $run->recordSkipped(page: $page, reason: $e); + $this->logger->warning( + message: 'Confluence page skipped during import', + context: ['pageId' => $page->pageId, 'exception' => $e] + ); + }//end try + }//end importPage() + /** + * Topologically order pages so every parent is created before its + * children. Pages whose declared parent never resolves are emitted + * at the end so they end up as orphans (root-level imports). + * + * @param ParsedPage[] $pages The pages to sort. + * + * @return ParsedPage[] Ordered list (parents first). + * + */ + private function orderParentsBeforeChildren(array $pages): array { + $byPageId = []; foreach ($pages as $page) { - $visit($page); + $byPageId[strtolower(string: $page->pageId)] = $page; } + $resolved = (new ParentFirstPageOrder(byPageId: $byPageId))->order(pages: $pages); + // Stable secondary sort within siblings by parent + sortOrder. usort( array: $resolved, @@ -305,45 +272,7 @@ private function orderParentsBeforeChildren(array $pages): array { ); // Re-apply parent-before-children after the sort. - $emitted = []; - $finalOrder = []; - $reEmit = static function (ParsedPage $page) use (&$emitted, &$finalOrder): void { - $key = strtolower(string: $page->pageId); - if (isset($emitted[$key]) === true) { - return; - } - - $emitted[$key] = true; - $finalOrder[] = $page; - }; - - $reVisit = function (ParsedPage $page) use (&$reVisit, &$emitted, &$byPageId, $reEmit): void { - $key = strtolower(string: $page->pageId); - if (isset($emitted[$key]) === true) { - return; - } - - $parentKey = null; - if ($page->parentPageId !== null) { - $parentKey = strtolower(string: $page->parentPageId); - } - - if ($parentKey !== null - && $parentKey !== $key - && isset($byPageId[$parentKey]) === true - && isset($emitted[$parentKey]) === false - ) { - $reVisit($byPageId[$parentKey]); - } - - $reEmit($page); - }; - - foreach ($resolved as $page) { - $reVisit($page); - } - - return $finalOrder; + return (new ParentFirstPageOrder(byPageId: $byPageId))->order(pages: $resolved); }//end orderParentsBeforeChildren() /** @@ -393,22 +322,15 @@ private function createDashboardForPage( $this->db->beginTransaction(); try { // Validate parent + depth. NULL parents always pass. - $this->treeService->validateParent( + $this->writers->treeService->validateParent( movingUuid: null, newParentUuid: $parentUuid ); - $dashboard = $this->dashboardFactory->create( + $dashboard = $this->writers->dashboardFactory->create( userId: $currentUserId, name: $page->title, - description: null, - type: Dashboard::TYPE_USER, - groupId: null, - gridColumns: 12, - permissionLevel: Dashboard::PERMISSION_FULL, - parentUuid: $parentUuid, - slug: null, - sortOrder: $page->sortOrder + options: $this->pageDashboardOptions(page: $page, parentUuid: $parentUuid) ); // Suffix slug with pageId on collision so re-import always @@ -419,24 +341,59 @@ private function createDashboardForPage( pageId: $page->pageId ); - $persisted = $this->dashboardMapper->insert(entity: $dashboard); - - $placement = $this->buildPlaceholderWidget( - dashboardId: (int)$persisted->getId(), - page: $page - ); - - $this->placementMapper->insert(entity: $placement); + $dashboardUuid = $this->insertWithPlaceholderWidget(dashboard: $dashboard, page: $page); $this->db->commit(); - return (string)$persisted->getUuid(); + return $dashboardUuid; } catch (Throwable $e) { $this->db->rollBack(); throw $e; }//end try }//end createDashboardForPage() + /** + * Insert the page's dashboard and its placeholder text widget. + * + * @param Dashboard $dashboard The unsaved dashboard. + * @param ParsedPage $page The source page. + * + * @return string The new dashboard UUID. + */ + private function insertWithPlaceholderWidget(Dashboard $dashboard, ParsedPage $page): string { + $persisted = $this->writers->dashboardMapper->insert(entity: $dashboard); + + $placement = $this->buildPlaceholderWidget( + dashboardId: (int)$persisted->getId(), + page: $page + ); + + $this->writers->placementMapper->insert(entity: $placement); + + return (string)$persisted->getUuid(); + }//end insertWithPlaceholderWidget() + + /** + * The dashboard factory options for one imported page. + * + * @param ParsedPage $page The parsed page. + * @param string|null $parentUuid Resolved parent dashboard UUID. + * + * @return array The factory options. + */ + private function pageDashboardOptions(ParsedPage $page, ?string $parentUuid): array { + return [ + 'description' => null, + 'type' => Dashboard::TYPE_USER, + 'groupId' => null, + 'gridColumns' => 12, + 'permissionLevel' => Dashboard::PERMISSION_FULL, + 'parentUuid' => $parentUuid, + 'slug' => null, + 'sortOrder' => $page->sortOrder, + ]; + }//end pageDashboardOptions() + /** * Build the placeholder text widget for a freshly-inserted dashboard. * @@ -498,42 +455,65 @@ private function backfillWidgetContent(array $pages, array $pageIdToUuid): array $warnings = []; foreach ($pages as $page) { - try { - $dashboard = $this->dashboardMapper->findByUuid( - uuid: $pageIdToUuid[strtolower(string: $page->pageId)] - ); - } catch (DoesNotExistException) { - continue; - } - - $placements = $this->placementMapper->findByDashboardId( - dashboardId: (int)$dashboard->getId() + $warnings = array_merge( + $warnings, + $this->backfillPageWidget(page: $page, pageIdToUuid: $pageIdToUuid) ); + } - if ($placements === []) { - continue; - } + return $warnings; + }//end backfillWidgetContent() - $expanded = $this->macroRenderer->render(html: $page->body); - $rewriteRes = $this->linkRewriter->rewrite( - html: $expanded, - pageIdToUuid: $pageIdToUuid - ); - $sanitised = $this->sanitizer->sanitize(html: $rewriteRes['html']); + /** + * Write one page's sanitised + rewritten HTML into its text widget. + * + * @param ParsedPage $page The created page. + * @param array $pageIdToUuid PageId (lower) → uuid. + * + * @return array Warnings collected during link rewriting. + */ + private function backfillPageWidget(ParsedPage $page, array $pageIdToUuid): array { + $placements = $this->importedPagePlacements(uuid: $pageIdToUuid[strtolower(string: $page->pageId)]); + if ($placements === []) { + return []; + } - $placement = $placements[0]; - $config = $placement->getStyleConfigArray(); - $config['text'] = $sanitised; - $placement->setStyleConfigArray(config: $config); - $placement->setUpdatedAt((new DateTime())->format(format: 'Y-m-d H:i:s')); + $expanded = $this->readers->macroRenderer->render(html: $page->body); + $rewriteRes = $this->readers->linkRewriter->rewrite( + html: $expanded, + pageIdToUuid: $pageIdToUuid + ); + $sanitised = $this->readers->sanitizer->sanitize(html: $rewriteRes['html']); - $this->placementMapper->update(entity: $placement); + $placement = $placements[0]; + $config = $placement->getStyleConfigArray(); + $config['text'] = $sanitised; + $placement->setStyleConfigArray(config: $config); + $placement->setUpdatedAt((new DateTime())->format(format: 'Y-m-d H:i:s')); - $warnings = array_merge($warnings, $rewriteRes['warnings']); - }//end foreach + $this->writers->placementMapper->update(entity: $placement); - return $warnings; - }//end backfillWidgetContent() + return $rewriteRes['warnings']; + }//end backfillPageWidget() + + /** + * The widget placements of an imported dashboard; none when it is gone. + * + * @param string $uuid The dashboard UUID. + * + * @return WidgetPlacement[] The placements. + */ + private function importedPagePlacements(string $uuid): array { + try { + $dashboard = $this->writers->dashboardMapper->findByUuid(uuid: $uuid); + } catch (DoesNotExistException) { + return []; + } + + return $this->writers->placementMapper->findByDashboardId( + dashboardId: (int)$dashboard->getId() + ); + }//end importedPagePlacements() /** * Append `-` to the slug when a sibling already owns it. @@ -561,39 +541,63 @@ private function ensureUniqueSlug( } try { - $this->treeService->validateSlugUnique( + $this->writers->treeService->validateSlugUnique( parentUuid: $parentUuid, slug: $slug ); return $dashboard; } catch (\InvalidArgumentException) { - $suffix = SlugGenerator::slugify(name: $pageId); - if ($suffix === '') { - $suffix = (string)random_int(min: 1000, max: 9999); - } - - $candidate = ($slug . '-' . $suffix); - // Final fallback: append timestamp segment (always unique). - try { - $this->treeService->validateSlugUnique( - parentUuid: $parentUuid, - slug: $candidate - ); - } catch (\InvalidArgumentException) { - $candidate = ($candidate . '-' . (string)time()); - } - - $dashboard->setSlug($candidate); + $candidate = ($slug . '-' . $this->pageIdSlugSuffix(pageId: $pageId)); + $dashboard->setSlug($this->timestampedWhenTaken(candidate: $candidate, parentUuid: $parentUuid)); return $dashboard; }//end try }//end ensureUniqueSlug() + /** + * The slug suffix for a page: its slugified pageId, or a random number when that is empty. + * + * @param string $pageId The Confluence page identifier. + * + * @return string The suffix. + */ + private function pageIdSlugSuffix(string $pageId): string { + $suffix = SlugGenerator::slugify(name: $pageId); + if ($suffix === '') { + $suffix = (string)random_int(min: 1000, max: 9999); + } + + return $suffix; + }//end pageIdSlugSuffix() + + /** + * The candidate slug, or with a timestamp segment appended when a sibling owns it. + * + * @param string $candidate The suffixed slug. + * @param string|null $parentUuid The resolved parent UUID. + * + * @return string The slug to use (the timestamp fallback is always unique). + */ + private function timestampedWhenTaken(string $candidate, ?string $parentUuid): string { + try { + $this->writers->treeService->validateSlugUnique( + parentUuid: $parentUuid, + slug: $candidate + ); + } catch (\InvalidArgumentException) { + $candidate = ($candidate . '-' . (string)time()); + } + + return $candidate; + }//end timestampedWhenTaken() + /** * Build the timestamp segment for the asset folder. * - * @return string The ISO 8601 segment (e.g. `2026-05-02T10-30-00`). + * Microseconds keep two runs started in the same second apart. + * + * @return string The ISO 8601 segment (e.g. `2026-05-02T10-30-00.123456`). */ private function buildTimestamp(): string { - return (new DateTime())->format(format: 'Y-m-d\TH-i-s'); + return (new DateTime())->format(format: 'Y-m-d\TH-i-s.u'); }//end buildTimestamp() }//end class diff --git a/lib/Service/ConfluencePageReaders.php b/lib/Service/ConfluencePageReaders.php new file mode 100644 index 000000000..e07f0bcdc --- /dev/null +++ b/lib/Service/ConfluencePageReaders.php @@ -0,0 +1,54 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Service\Confluence\ArchiveParser; +use OCA\LaunchPad\Service\Confluence\HtmlSanitizer; +use OCA\LaunchPad\Service\Confluence\LinkRewriter; +use OCA\LaunchPad\Service\Confluence\MacroRenderer; + +/** + * What the Confluence importer reads a page with: the archive parser, the HTML sanitizer, the macro + * renderer and the link rewriter. + * + * @spec openspec/specs/dashboards/spec.md + */ +class ConfluencePageReaders { + /** + * Constructor. + * + * @param ArchiveParser $parser Archive reader. + * @param HtmlSanitizer $sanitizer HTML allow-list filter. + * @param MacroRenderer $macroRenderer Macro → HTML renderer. + * @param LinkRewriter $linkRewriter Internal-link rewriter. + */ + public function __construct( + public readonly ArchiveParser $parser, + public readonly HtmlSanitizer $sanitizer, + public readonly MacroRenderer $macroRenderer, + public readonly LinkRewriter $linkRewriter, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/Connection/ConnectionReporter.php b/lib/Service/Connection/ConnectionReporter.php index 02e806355..f842bef31 100644 --- a/lib/Service/Connection/ConnectionReporter.php +++ b/lib/Service/Connection/ConnectionReporter.php @@ -168,7 +168,7 @@ class ConnectionReporter { * @var array> */ public const REFRESH_KEYS = [ - self::KEY_REGISTRY => [StoreService::CONFIG_URL, StoreService::CONFIG_REGISTER, StoreService::CONFIG_TOKEN], + self::KEY_REGISTRY => [StoreService::CONFIG_URL, StoreService::CONFIG_REGISTER, StoreService::CONFIG_REGISTRY_AUTH], ]; /** diff --git a/lib/Service/ContractBindings.php b/lib/Service/ContractBindings.php new file mode 100644 index 000000000..9b6a534d4 --- /dev/null +++ b/lib/Service/ContractBindings.php @@ -0,0 +1,117 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec exclude Composition root wiring, no functional requirement. + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Kernel\Contracts\AcknowledgementServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\AnalyticsServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\AnnouncementCommentServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\AnnouncementFollowNotifierInterface; +use OCA\LaunchPad\Kernel\Contracts\AnnouncementFollowServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\AnnouncementServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\AttentionSourceServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\CalendarWidgetServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\CommandServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\ConditionalServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\ConfluenceImportServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\DashboardLockServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\DemoDataServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\ExportServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\FeedRefreshServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\FooterServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\OrphanedDataCleanupServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\PersonalLayerServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\ProfileFieldServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\PublicStartPageInterface; +use OCA\LaunchPad\Kernel\Contracts\QuotaServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\RdpFileWriterInterface; +use OCA\LaunchPad\Kernel\Contracts\ResourceServeServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\SearchShortcutServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\ServiceDiscoveryServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\SetupWizardServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\ShippedTemplateServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\ShippedTemplateUpdateServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\TemplateResyncServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\TileAnalyticsServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\WeatherServiceInterface; +use OCP\AppFramework\Bootstrap\IRegistrationContext; + +/** + * Nextcloud autowires concrete classes but not interfaces, so every contract + * in OCA\LaunchPad\Kernel\Contracts that a caller type-hints needs an alias to + * the class that implements it. An alias resolves to the same shared instance + * as the implementation itself. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * @spec exclude Composition root wiring, no functional requirement. + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ +final class ContractBindings { + + /** + * Alias every Kernel contract to its implementation. + * + * @param IRegistrationContext $context The registration context. + * + * @return void + * + * @spec exclude Composition root wiring, no functional requirement. + */ + public function register(IRegistrationContext $context): void { + $context->registerServiceAlias(AcknowledgementServiceInterface::class, AcknowledgementService::class); + $context->registerServiceAlias(AnalyticsServiceInterface::class, AnalyticsService::class); + $context->registerServiceAlias(AnnouncementCommentServiceInterface::class, AnnouncementCommentService::class); + $context->registerServiceAlias(AnnouncementFollowNotifierInterface::class, AnnouncementFollowNotifier::class); + $context->registerServiceAlias(AnnouncementFollowServiceInterface::class, AnnouncementFollowService::class); + $context->registerServiceAlias(AnnouncementServiceInterface::class, AnnouncementService::class); + $context->registerServiceAlias(AttentionSourceServiceInterface::class, AttentionSourceService::class); + $context->registerServiceAlias(CalendarWidgetServiceInterface::class, CalendarWidgetService::class); + $context->registerServiceAlias(CommandServiceInterface::class, CommandService::class); + $context->registerServiceAlias(ConditionalServiceInterface::class, ConditionalService::class); + $context->registerServiceAlias(ConfluenceImportServiceInterface::class, ConfluenceImportService::class); + $context->registerServiceAlias(DashboardLockServiceInterface::class, DashboardLockService::class); + $context->registerServiceAlias(DemoDataServiceInterface::class, DemoDataService::class); + $context->registerServiceAlias(ExportServiceInterface::class, ExportService::class); + $context->registerServiceAlias(FeedRefreshServiceInterface::class, FeedRefreshService::class); + $context->registerServiceAlias(FooterServiceInterface::class, FooterService::class); + $context->registerServiceAlias(OrphanedDataCleanupServiceInterface::class, OrphanedDataCleanupService::class); + $context->registerServiceAlias(PersonalLayerServiceInterface::class, PersonalLayerService::class); + $context->registerServiceAlias(ProfileFieldServiceInterface::class, ProfileFieldService::class); + $context->registerServiceAlias(PublicStartPageInterface::class, PublicStartPage::class); + $context->registerServiceAlias(QuotaServiceInterface::class, QuotaService::class); + $context->registerServiceAlias(RdpFileWriterInterface::class, RdpFileWriter::class); + $context->registerServiceAlias(ResourceServeServiceInterface::class, ResourceServeService::class); + $context->registerServiceAlias(SearchShortcutServiceInterface::class, SearchShortcutService::class); + $context->registerServiceAlias(ServiceDiscoveryServiceInterface::class, ServiceDiscoveryService::class); + $context->registerServiceAlias(SetupWizardServiceInterface::class, SetupWizardService::class); + $context->registerServiceAlias(ShippedTemplateServiceInterface::class, ShippedTemplateService::class); + $context->registerServiceAlias(ShippedTemplateUpdateServiceInterface::class, ShippedTemplateUpdateService::class); + $context->registerServiceAlias(TemplateResyncServiceInterface::class, TemplateResyncService::class); + $context->registerServiceAlias(TileAnalyticsServiceInterface::class, TileAnalyticsService::class); + $context->registerServiceAlias(WeatherServiceInterface::class, WeatherService::class); + }//end register() +}//end class diff --git a/lib/Service/CustomCssSanitiser.php b/lib/Service/CustomCssSanitiser.php new file mode 100644 index 000000000..242b505e1 --- /dev/null +++ b/lib/Service/CustomCssSanitiser.php @@ -0,0 +1,575 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * Reads CSS as a list of plain rules (and `@media` groups of them) and rebuilds + * only what it can read and judge safe. It works as an allow-list: anything it + * cannot read is dropped, never passed through. Every at-rule except `@media` + * is dropped, so `@import` and `@font-face` never survive. A declaration is + * dropped when it holds an escape, markup, `expression(`, a script address, a + * `behavior` or `-moz-binding` property, or a `url()` that is not one of + * LaunchPad's own resources. Every selector is prefixed with the scope. The + * result lists what was dropped, so the administrator can see it. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ +final class CustomCssSanitiser { + + /** + * The largest CSS accepted and stored, in bytes. + */ + public const MAX_BYTES = 20480; + + /** + * The scope of the CSS for all of LaunchPad. + */ + public const GLOBAL_SCOPE = '.launchpad-workspace'; + + /** + * Properties that run code in old browsers. + */ + private const SCRIPT_PROPERTIES = ['behavior', '-moz-binding']; + + /** + * Value fragments that run code or reach an address. + * + * @var array Fragment => what the administrator is told. + */ + /** + * What the running {@see self::sanitise()} call dropped, as labels. + * + * @var list + */ + private array $removed = []; + + private const UNSAFE_VALUES = [ + 'expression(' => 'expression()', + 'javascript:' => 'javascript:', + 'vbscript:' => 'javascript:', + 'image-set(' => 'url() to another site', + 'image(' => 'url() to another site', + 'cross-fade(' => 'url() to another site', + 'element(' => 'url() to another site', + 'src(' => 'url() to another site', + ]; + + /** + * The scope of the CSS for one dashboard: its region on the page. + * + * @param string $uuid The dashboard's UUID. + * + * @return string The selector of that dashboard's region. + * + * @throws InvalidArgumentException When the UUID could break out of the selector. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + public static function dashboardScope(string $uuid): string { + if (preg_match('/^[A-Za-z0-9-]{1,64}$/', $uuid) !== 1) { + throw new InvalidArgumentException('The dashboard has no usable identifier.'); + } + + return '.launchpad-dashboard[data-dashboard-uuid="' . $uuid . '"]'; + }//end dashboardScope() + + /** + * Clean and scope CSS. + * + * @param string $css The CSS as the administrator entered it. + * @param string $scope The selector every rule is scoped to. + * + * @return array{css: string, removed: list} The CSS to store and what was dropped. + * + * @throws InvalidArgumentException When the CSS, or its scoped form, is larger than 20 KB. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + public function sanitise(string $css, string $scope): array { + if (strlen($css) > self::MAX_BYTES) { + throw new InvalidArgumentException('Custom CSS may be at most 20 KB.'); + } + + $this->removed = []; + $source = (string)preg_replace('~/\*.*?(?:\*/|$)~s', '', $css); + $rules = $this->readRules(css: $source, scope: $scope, inGroup: false); + $output = implode("\n\n", $rules); + + if (strlen($output) > self::MAX_BYTES) { + throw new InvalidArgumentException('Custom CSS may be at most 20 KB, also after scoping it to LaunchPad.'); + } + + return ['css' => $output, 'removed' => array_values(array_unique($this->removed))]; + }//end sanitise() + + /** + * Read a list of rules and rebuild the safe ones. + * + * @param string $css The CSS, without comments. + * @param string $scope The selector every rule is scoped to. + * @param bool $inGroup Whether this list sits inside an `@media` group. + * + * @return list The rebuilt rules. + */ + private function readRules(string $css, string $scope, bool $inGroup): array { + $rules = []; + $length = strlen($css); + $pos = 0; + while (true) { + while ($pos < $length && ctype_space($css[$pos]) === true) { + $pos++; + } + + if ($pos >= $length) { + break; + } + + $end = $this->findTopLevel(css: $css, from: $pos, stops: '{;}'); + if ($end >= $length || $css[$end] !== '{') { + // A statement without a block (`@import ...;`) or text that is no rule. + $this->removed[] = $this->label(prelude: substr($css, $pos, ($end - $pos))); + $pos = ($end + 1); + continue; + } + + $close = $this->matchingBrace(css: $css, open: $end); + if ($close >= $length) { + $this->removed[] = 'unreadable CSS'; + break; + } + + $prelude = trim(substr($css, $pos, ($end - $pos))); + $body = substr($css, ($end + 1), ($close - $end - 1)); + $pos = ($close + 1); + + $rule = $this->readRule(prelude: $prelude, body: $body, scope: $scope, inGroup: $inGroup); + if ($rule !== null) { + $rules[] = $rule; + } + }//end while + + return $rules; + }//end readRules() + + /** + * Rebuild one rule or `@media` group, or null when nothing of it is kept. + * + * @param string $prelude The selector list or at-rule prelude. + * @param string $body What is between the braces. + * @param string $scope The selector every rule is scoped to. + * @param bool $inGroup Whether the rule sits inside an `@media` group. + * + * @return string|null The rebuilt rule. + */ + private function readRule(string $prelude, string $body, string $scope, bool $inGroup): ?string { + if (str_starts_with($prelude, '@') === true) { + $isMedia = preg_match('/^@media\s+([a-zA-Z0-9\s(),:.\-]+)$/i', $prelude, $match) === 1; + if ($isMedia === false || $inGroup === true) { + $this->removed[] = $this->label(prelude: $prelude); + return null; + } + + $inner = $this->readRules(css: $body, scope: $scope, inGroup: true); + if ($inner === []) { + return null; + } + + $query = (string)preg_replace('/\s+/', ' ', trim($match[1])); + return '@media ' . $query . " {\n" . implode("\n\n", $inner) . "\n}"; + } + + if ($this->findTopLevel(css: $body, from: 0, stops: '{') < strlen($body)) { + $this->removed[] = 'nested rules'; + return null; + } + + $selectors = $this->scopeSelectors(prelude: $prelude, scope: $scope); + if ($selectors === null) { + $this->removed[] = 'unsafe selector'; + return null; + } + + $declarations = $this->readDeclarations(body: $body); + if ($declarations === []) { + return null; + } + + return $selectors . " {\n " . implode(";\n ", $declarations) . ";\n}"; + }//end readRule() + + /** + * Prefix every selector of a list with the scope, or null when one cannot be judged. + * + * @param string $prelude The selector list. + * @param string $scope The scope. + * + * @return string|null The scoped list. + */ + private function scopeSelectors(string $prelude, string $scope): ?string { + if ($prelude === '' || preg_match('/[<\\\\@;{}]|url\(/i', $prelude) === 1) { + return null; + } + + $scoped = []; + foreach ($this->splitTopLevel(text: $prelude, separator: ',') as $selector) { + $selector = (string)preg_replace('/\s+/', ' ', trim($selector)); + if ($selector === '') { + return null; + } + + $scoped[] = $this->scopeOne(selector: $selector, scope: $scope); + } + + return implode(', ', $scoped); + }//end scopeSelectors() + + /** + * Prefix one selector with the scope, unless it already starts at the scope + * itself and stays inside it. A sibling combinator (`+`, `~`) right after the + * scope's compound reaches the region's siblings, outside the scope, so such + * a selector is prefixed as well. + * + * @param string $selector The selector. + * @param string $scope The scope. + * + * @return string The scoped selector. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + private function scopeOne(string $selector, string $scope): string { + if (str_starts_with($selector, $scope) === true) { + $rest = substr($selector, strlen($scope)); + if (($rest === '' || preg_match('/^[A-Za-z0-9_-]/', $rest) !== 1) + && self::leavesTheCompoundBySibling(rest: $rest) === false + ) { + return $selector; + } + } + + return $scope . ' ' . $selector; + }//end scopeOne() + + /** + * Whether the first combinator after the scope's compound is a sibling + * combinator. The compound may go on with classes, ids, attributes and + * pseudo-classes (their brackets and quotes are skipped); it ends at the + * first top-level space or combinator. + * + * @param string $rest The selector after the scope. + * + * @return bool + */ + private static function leavesTheCompoundBySibling(string $rest): bool { + $nesting = ['depth' => 0, 'quote' => null]; + $length = strlen($rest); + for ($i = 0; $i < $length; $i++) { + $char = $rest[$i]; + if (self::nestingStep(char: $char, nesting: $nesting) === true || $nesting['depth'] > 0) { + continue; + } + + if (strpos(' >+~', $char) !== false) { + return in_array(ltrim(substr($rest, $i))[0] ?? '', ['+', '~'], true); + } + } + + return false; + }//end leavesTheCompoundBySibling() + + /** + * Read the declarations of a rule and keep the safe ones. + * + * @param string $body What is between the braces. + * + * @return list The kept declarations, as `property: value`. + */ + private function readDeclarations(string $body): array { + $kept = []; + foreach ($this->splitTopLevel(text: $body, separator: ';') as $declaration) { + $declaration = trim($declaration); + if ($declaration === '') { + continue; + } + + $colon = strpos($declaration, ':'); + if ($colon === false) { + $this->removed[] = 'unreadable CSS'; + continue; + } + + $property = strtolower(trim(substr($declaration, 0, $colon))); + $value = (string)preg_replace('/\s+/', ' ', trim(substr($declaration, ($colon + 1)))); + $problem = $this->declarationProblem(property: $property, value: $value); + if ($problem !== null) { + $this->removed[] = $problem; + continue; + } + + $kept[] = $property . ': ' . $value; + }//end foreach + + return $kept; + }//end readDeclarations() + + /** + * Why a declaration is dropped, or null when it is kept. + * + * @param string $property The property, lower case. + * @param string $value The value. + * + * @return string|null What the administrator is told. + */ + private function declarationProblem(string $property, string $value): ?string { + if (preg_match('/^-{0,2}[a-z][a-z0-9-]*$/', $property) !== 1 || $value === '') { + return 'unreadable CSS'; + } + + if (in_array($property, self::SCRIPT_PROPERTIES, true) === true) { + return $property; + } + + if (str_contains($value, '\\') === true) { + return 'escapes'; + } + + if (str_contains($value, '<') === true) { + return 'markup'; + } + + $lower = strtolower($value); + foreach (self::UNSAFE_VALUES as $fragment => $label) { + if (str_contains($lower, $fragment) === true) { + return $label; + } + } + + return $this->urlProblem(value: $value); + }//end declarationProblem() + + /** + * Why the `url()` references of a value are refused, or null when every one is a LaunchPad resource. + * + * @param string $value The value. + * + * @return string|null What the administrator is told. + */ + private function urlProblem(string $value): ?string { + $calls = substr_count(strtolower($value), 'url('); + if ($calls === 0) { + return null; + } + + $found = preg_match_all('~url\(\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s"\'()]*))\s*\)~i', $value, $matches, PREG_SET_ORDER); + if ($found !== $calls) { + return 'url() to another site'; + } + + foreach ($matches as $match) { + $target = (($match[1] ?? '') . ($match[2] ?? '') . ($match[3] ?? '')); + if ($this->isOwnResource(target: $target) === false) { + return 'url() to another site'; + } + } + + return null; + }//end urlProblem() + + /** + * Whether an address is one of LaunchPad's own uploaded resources, on this server. + * + * @param string $target The address inside `url()`. + * + * @return bool + */ + private function isOwnResource(string $target): bool { + if (str_contains($target, '..') === true) { + return false; + } + + $isOwnPath = preg_match('~^(?:/[A-Za-z0-9_][A-Za-z0-9._-]*)*/apps/launchpad/resource/([^/?#]+)$~', $target, $match) === 1; + + return $isOwnPath === true && DashboardLook::isResourceName(name: $match[1]) === true; + }//end isOwnResource() + + /** + * What the administrator is told about a dropped at-rule or unreadable text. + * + * @param string $prelude The text that was dropped. + * + * @return string The label. + */ + private function label(string $prelude): string { + if (preg_match('/^\s*(@[A-Za-z-]+)/', $prelude, $match) === 1) { + return strtolower($match[1]); + } + + return 'unreadable CSS'; + }//end label() + + /** + * The first position of one of the stop characters outside strings, + * parentheses and brackets, or the length of the text when there is none. + * + * @param string $css The text. + * @param int $from Where to start. + * @param string $stops The stop characters. + * + * @return int The position. + */ + private function findTopLevel(string $css, int $from, string $stops): int { + $length = strlen($css); + $nesting = ['depth' => 0, 'quote' => null]; + for ($pos = $from; $pos < $length; $pos++) { + $char = $css[$pos]; + if (self::nestingStep(char: $char, nesting: $nesting) === true) { + continue; + } + + if ($nesting['depth'] === 0 && str_contains($stops, $char) === true) { + return $pos; + } + } + + return $length; + }//end findTopLevel() + + /** + * Track one character's effect on string and bracket nesting. + * + * @param string $char The character. + * @param array{depth: int, quote: string|null} $nesting The parenthesis and bracket depth and the + * quote of the open string; updated. + * + * @return bool True when the character belongs to the nesting (inside a + * string, a quote, or a bracket that opens or closes one), so + * it is no stop character. + */ + private static function nestingStep(string $char, array &$nesting): bool { + return self::quoteStep(char: $char, nesting: $nesting) === true + || self::bracketStep(char: $char, nesting: $nesting) === true; + }//end nestingStep() + + /** + * Track a character inside a string, or a quote that opens one. + * + * @param string $char The character. + * @param array{depth: int, quote: string|null} $nesting The nesting; its quote is updated. + * + * @return bool True when the character is inside a string or a quote. + */ + private static function quoteStep(string $char, array &$nesting): bool { + if ($nesting['quote'] !== null) { + if ($char === $nesting['quote']) { + $nesting['quote'] = null; + } + + return true; + } + + if ($char === '"' || $char === "'") { + $nesting['quote'] = $char; + return true; + } + + return false; + }//end quoteStep() + + /** + * Track a bracket that opens, or closes an open one. + * + * @param string $char The character. + * @param array{depth: int, quote: string|null} $nesting The nesting; its depth is updated. + * + * @return bool True when the character opens a parenthesis or bracket, or closes an open one. + */ + private static function bracketStep(string $char, array &$nesting): bool { + $delta = (['(' => 1, '[' => 1, ')' => -1, ']' => -1][$char] ?? 0); + if ($delta === 0 || ($nesting['depth'] + $delta) < 0) { + return false; + } + + $nesting['depth'] += $delta; + return true; + }//end bracketStep() + + /** + * The position of the brace that closes the one at `$open`, or the length when it is never closed. + * + * @param string $css The text. + * @param int $open The position of the opening brace. + * + * @return int The position. + */ + private function matchingBrace(string $css, int $open): int { + $length = strlen($css); + $depth = 0; + $pos = $open; + while ($pos < $length) { + $pos = $this->findTopLevel(css: $css, from: $pos, stops: '{}'); + if ($pos >= $length) { + return $length; + } + + if ($css[$pos] === '{') { + $depth++; + } + + if ($css[$pos] === '}') { + $depth--; + if ($depth === 0) { + return $pos; + } + } + + $pos++; + } + + return $length; + }//end matchingBrace() + + /** + * Split text on a separator outside strings, parentheses and brackets. + * + * @param string $text The text. + * @param string $separator The separator character. + * + * @return list The parts. + */ + private function splitTopLevel(string $text, string $separator): array { + $parts = []; + $length = strlen($text); + $start = 0; + while ($start <= $length) { + $end = $this->findTopLevel(css: $text, from: $start, stops: $separator); + $parts[] = substr($text, $start, ($end - $start)); + $start = ($end + 1); + } + + return $parts; + }//end splitTopLevel() +}//end class diff --git a/lib/Service/CustomCssService.php b/lib/Service/CustomCssService.php new file mode 100644 index 000000000..235bac57d --- /dev/null +++ b/lib/Service/CustomCssService.php @@ -0,0 +1,122 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTime; +use InvalidArgumentException; +use OCA\LaunchPad\Db\AdminSetting; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCA\LaunchPad\Db\DashboardMapper; + +/** + * The global CSS is the `custom_css` admin setting; a dashboard's CSS is its + * `custom_css` column. Only the cleaned form is ever stored. Callers check + * that the user is an administrator. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ +class CustomCssService { + + /** + * Constructor. + * + * @param AdminSettingMapper $settings The admin settings. + * @param DashboardMapper $dashboards The dashboards. + * @param CustomCssSanitiser $sanitiser Cleans and scopes the CSS. + */ + public function __construct( + private readonly AdminSettingMapper $settings, + private readonly DashboardMapper $dashboards, + private readonly CustomCssSanitiser $sanitiser, + ) { + }//end __construct() + + /** + * The stored CSS for all of LaunchPad, or '' when there is none. + * + * @return string The cleaned CSS. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + public function getGlobalCss(): string { + $value = $this->settings->getValue(key: AdminSetting::KEY_CUSTOM_CSS, default: ''); + if (is_string($value) === false) { + return ''; + } + + return $value; + }//end getGlobalCss() + + /** + * Clean, scope and store the CSS for all of LaunchPad. + * + * @param string $css The CSS as the administrator entered it; '' clears it. + * + * @return array{customCss: string, removed: list} What was stored and what was dropped. + * + * @throws InvalidArgumentException When the CSS is larger than 20 KB. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + public function setGlobalCss(string $css): array { + $result = $this->sanitiser->sanitise(css: $css, scope: CustomCssSanitiser::GLOBAL_SCOPE); + $this->settings->setSetting(key: AdminSetting::KEY_CUSTOM_CSS, value: $result['css']); + + return ['customCss' => $result['css'], 'removed' => $result['removed']]; + }//end setGlobalCss() + + /** + * Clean, scope and store the CSS for one dashboard. + * + * @param string $uuid The dashboard's UUID. + * @param string $css The CSS as the administrator entered it; '' clears it. + * + * @return array{customCss: string, removed: list} What was stored and what was dropped. + * + * @throws InvalidArgumentException When the CSS is larger than 20 KB. + * @throws \OCP\AppFramework\Db\DoesNotExistException When there is no such dashboard. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + public function setDashboardCss(string $uuid, string $css): array { + $dashboard = $this->dashboards->findByUuid(uuid: $uuid); + $result = $this->sanitiser->sanitise( + css: $css, + scope: CustomCssSanitiser::dashboardScope(uuid: (string)$dashboard->getUuid()) + ); + + $stored = null; + if ($result['css'] !== '') { + $stored = $result['css']; + } + + $dashboard->setCustomCss($stored); + $dashboard->setUpdatedAt((new DateTime())->format(format: 'Y-m-d H:i:s')); + $this->dashboards->update(entity: $dashboard); + + return ['customCss' => $result['css'], 'removed' => $result['removed']]; + }//end setDashboardCss() +}//end class diff --git a/lib/Service/DashboardBuilders.php b/lib/Service/DashboardBuilders.php new file mode 100644 index 000000000..2bf90f648 --- /dev/null +++ b/lib/Service/DashboardBuilders.php @@ -0,0 +1,48 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * What DashboardService builds new dashboards from: templates, the factory and the resolver. + * + * @spec openspec/specs/dashboards/spec.md + */ +class DashboardBuilders { + /** + * Constructor. + * + * @param TemplateService $templateService Template service. + * @param DashboardFactory $dashboardFactory Dashboard factory. + * @param DashboardResolver $dashResolver Dashboard resolver. + * @param AdminTemplateService $adminTemplateService Routing resolver — single source of truth for + * `IGroupManager::getUserGroupIds` (REQ-TMPL-013). + */ + public function __construct( + public readonly TemplateService $templateService, + public readonly DashboardFactory $dashboardFactory, + public readonly DashboardResolver $dashResolver, + public readonly AdminTemplateService $adminTemplateService, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/DashboardFactory.php b/lib/Service/DashboardFactory.php index c7d6d93da..f551e0258 100644 --- a/lib/Service/DashboardFactory.php +++ b/lib/Service/DashboardFactory.php @@ -27,6 +27,20 @@ * Factory service for creating dashboard entities. */ class DashboardFactory { + /** + * The optional create() fields and their defaults. + */ + private const DEFAULT_OPTIONS = [ + 'description' => null, + 'type' => Dashboard::TYPE_USER, + 'groupId' => null, + 'gridColumns' => 12, + 'permissionLevel' => Dashboard::PERMISSION_FULL, + 'parentUuid' => null, + 'slug' => null, + 'sortOrder' => 0, + ]; + /** * Create a new dashboard entity. * @@ -40,38 +54,19 @@ class DashboardFactory { * `TYPE_GROUP_SHARED` / * `TYPE_ADMIN_TEMPLATE`. * @param string $name The dashboard name. - * @param string|null $description The dashboard description. - * @param string $type The dashboard type (default - * {@see Dashboard::TYPE_USER}). - * @param string|null $groupId The group ID — required when - * `type === TYPE_GROUP_SHARED`, - * forbidden otherwise. - * @param int $gridColumns The grid column count. - * @param string $permissionLevel The owner's permission level on - * this dashboard. Defaults to - * {@see Dashboard::PERMISSION_FULL}; - * callers may pass a more restrictive - * level when forking a shared - * dashboard or creating a read-only - * template. - * @param string|null $parentUuid Optional parent dashboard UUID - * (REQ-DASH-023). NULL ⇒ root. - * The factory does NOT verify the - * parent exists or that the depth - * constraint holds — that is the - * service layer's job - * (`DashboardTreeService`). - * @param string|null $slug Optional caller-supplied slug - * (REQ-DASH-024). When NULL the - * factory derives one from the - * `name` via `SlugGenerator`. The - * factory rejects an explicit - * slug that fails grammar - * validation. - * @param int $sortOrder Optional sibling sort order - * (REQ-DASH-029). Defaults to 0; - * ties broken alphabetically by - * name in tree responses. + * @param array $options Optional fields, each with its default: + * `description` (null); `type` + * ({@see Dashboard::TYPE_USER}); `groupId` (null, + * required when `type === TYPE_GROUP_SHARED`, + * forbidden otherwise); `gridColumns` (12); + * `permissionLevel` (the owner's level, + * {@see Dashboard::PERMISSION_FULL}); `parentUuid` + * (null ⇒ root, REQ-DASH-023; the factory does + * not verify the parent or the depth); `slug` + * (null ⇒ derived from the name via + * `SlugGenerator`, REQ-DASH-024; an explicit slug + * that fails the grammar is rejected); `sortOrder` + * (0, REQ-DASH-029). * * @return Dashboard The created dashboard entity (not yet persisted). * @@ -81,32 +76,23 @@ class DashboardFactory { * * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-16 */ - public function create( - ?string $userId, - string $name, - ?string $description = null, - string $type = Dashboard::TYPE_USER, - ?string $groupId = null, - int $gridColumns = 12, - string $permissionLevel = Dashboard::PERMISSION_FULL, - ?string $parentUuid = null, - ?string $slug = null, - int $sortOrder = 0, - ): Dashboard { - $this->assertTypeGroupInvariant(type: $type, groupId: $groupId); - - $resolvedSlug = $this->resolveSlug(name: $name, slug: $slug); + public function create(?string $userId, string $name, array $options=[]): Dashboard { + $options += self::DEFAULT_OPTIONS; + $type = $options['type']; + $this->assertTypeGroupInvariant(type: $type, groupId: $options['groupId']); + + $resolvedSlug = $this->resolveSlug(name: $name, slug: $options['slug']); $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); $dashboard = new Dashboard(); $dashboard->setUuid($this->generateUuid()); $dashboard->setName($name); - $dashboard->setDescription($description); + $dashboard->setDescription($options['description']); $dashboard->setType($type); $dashboard->setUserId($userId); - $dashboard->setGroupId($groupId); - $dashboard->setGridColumns($gridColumns); - $dashboard->setPermissionLevel($permissionLevel); + $dashboard->setGroupId($options['groupId']); + $dashboard->setGridColumns($options['gridColumns']); + $dashboard->setPermissionLevel($options['permissionLevel']); // Group-shared dashboards are not "active" per-user — activation // is a personal-scope concept tied to the active-dashboard cookie. $isActive = 0; @@ -117,9 +103,9 @@ public function create( $dashboard->setIsActive($isActive); $dashboard->setCreatedAt($now); $dashboard->setUpdatedAt($now); - $dashboard->setParentUuid($parentUuid); + $dashboard->setParentUuid($options['parentUuid']); $dashboard->setSlug($resolvedSlug); - $dashboard->setSortOrder($sortOrder); + $dashboard->setSortOrder($options['sortOrder']); // REQ-DASH-031 / design D2: every newly created dashboard MUST // default to publicationStatus = 'draft'. The database column diff --git a/lib/Service/DashboardHierarchies.php b/lib/Service/DashboardHierarchies.php new file mode 100644 index 000000000..9839025b2 --- /dev/null +++ b/lib/Service/DashboardHierarchies.php @@ -0,0 +1,197 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * The hierarchy descriptors of a dashboard: `{id, levels: [{dimension, label, parentDimension}]}`. + * + * Levels run from the broadest to the finest. Each level's parent is the + * level above it, so `parentDimension` is derived; a given one must match. + * A dimension belongs to one level of one hierarchy only, because the bus + * resolves a clause on the first level that carries its dimension. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ +class DashboardHierarchies { + + /** + * The most hierarchies one dashboard stores. + */ + public const MAX_HIERARCHIES = 8; + + /** + * The most levels one hierarchy has. + */ + public const MAX_LEVELS = 8; + + /** + * The longest level label. + */ + public const MAX_LABEL_LENGTH = 128; + + /** + * A hierarchy id: lowercase letters, digits and dashes. + */ + private const ID_PATTERN = '/^[a-z0-9][a-z0-9-]{0,63}$/'; + + /** + * A dimension: a letter, then letters, digits, dots and underscores. + */ + private const DIMENSION_PATTERN = '/^[A-Za-z][A-Za-z0-9_.]{0,63}$/'; + + /** + * The descriptors as given, normalised, or the refusal. + * + * Null and the empty list both mean "no hierarchies". + * + * @param mixed $value The `hierarchies` of an update. + * + * @return list}> + * + * @throws InvalidArgumentException When the value is not a valid list of descriptors. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + public static function validated(mixed $value): array { + if ($value === null) { + return []; + } + + if (is_array($value) === false || array_is_list($value) === false) { + throw new InvalidArgumentException(message: 'hierarchies must be a list'); + } + + if (count($value) > self::MAX_HIERARCHIES) { + throw new InvalidArgumentException(message: 'hierarchies holds at most '.self::MAX_HIERARCHIES.' entries'); + } + + $result = []; + $ids = []; + $dimensions = []; + foreach ($value as $index => $entry) { + $hierarchy = self::hierarchy(entry: $entry, index: $index); + if (in_array($hierarchy['id'], $ids, true) === true) { + throw new InvalidArgumentException(message: 'hierarchies['.$index.'].id '.$hierarchy['id'].' is used twice'); + } + + foreach ($hierarchy['levels'] as $level) { + if (in_array($level['dimension'], $dimensions, true) === true) { + throw new InvalidArgumentException( + message: 'hierarchies['.$index.'] repeats dimension '.$level['dimension'] + ); + } + + $dimensions[] = $level['dimension']; + } + + $ids[] = $hierarchy['id']; + $result[] = $hierarchy; + }//end foreach + + return $result; + }//end validated() + + /** + * One descriptor, normalised. + * + * @param mixed $entry The descriptor. + * @param int $index Its position, for the refusal message. + * + * @return array{id: string, levels: list} + * + * @throws InvalidArgumentException When the descriptor is malformed. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + private static function hierarchy(mixed $entry, int $index): array { + $path = 'hierarchies['.$index.']'; + if (is_array($entry) === false) { + throw new InvalidArgumentException(message: $path.' must be an object'); + } + + $hierarchyId = $entry['id'] ?? null; + if (is_string($hierarchyId) === false || preg_match(self::ID_PATTERN, $hierarchyId) !== 1) { + throw new InvalidArgumentException(message: $path.'.id must be lowercase letters, digits and dashes'); + } + + $levels = $entry['levels'] ?? null; + if (is_array($levels) === false || array_is_list($levels) === false || $levels === []) { + throw new InvalidArgumentException(message: $path.'.levels must be a non-empty list'); + } + + if (count($levels) > self::MAX_LEVELS) { + throw new InvalidArgumentException(message: $path.'.levels holds at most '.self::MAX_LEVELS.' levels'); + } + + $normalised = []; + $parent = null; + foreach ($levels as $position => $level) { + $normalised[] = self::level(level: $level, path: $path.'.levels['.$position.']', parent: $parent); + $parent = $normalised[array_key_last($normalised)]['dimension']; + } + + return ['id' => $hierarchyId, 'levels' => $normalised]; + }//end hierarchy() + + /** + * One level, normalised, with its parent set to the level above. + * + * @param mixed $level The level. + * @param string $path Its path, for the refusal message. + * @param string|null $parent The dimension of the level above, or null for the first level. + * + * @return array{dimension: string, label: string, parentDimension: string|null} + * + * @throws InvalidArgumentException When the level is malformed. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + private static function level(mixed $level, string $path, ?string $parent): array { + if (is_array($level) === false) { + throw new InvalidArgumentException(message: $path.' must be an object'); + } + + $dimension = $level['dimension'] ?? null; + if (is_string($dimension) === false || preg_match(self::DIMENSION_PATTERN, $dimension) !== 1) { + throw new InvalidArgumentException(message: $path.'.dimension must be a field name'); + } + + $label = $level['label'] ?? ''; + if (is_string($label) === false || mb_strlen($label) > self::MAX_LABEL_LENGTH) { + throw new InvalidArgumentException( + message: $path.'.label must be text of at most '.self::MAX_LABEL_LENGTH.' characters' + ); + } + + $given = $level['parentDimension'] ?? null; + if ($given !== null && $given !== $parent) { + throw new InvalidArgumentException(message: $path.'.parentDimension must be the dimension of the level above'); + } + + return ['dimension' => $dimension, 'label' => trim($label), 'parentDimension' => $parent]; + }//end level() +}//end class diff --git a/lib/Service/DashboardImportRun.php b/lib/Service/DashboardImportRun.php new file mode 100644 index 000000000..a9e04cbe5 --- /dev/null +++ b/lib/Service/DashboardImportRun.php @@ -0,0 +1,124 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; + +/** + * One import batch of ImportService: who imports, whether archive UUIDs + * are kept, and the counts, errors and created dashboards so far. Built + * by ImportService for one batch and never handed out. + * + * @spec openspec/specs/dashboard-export-import/spec.md + */ +final class DashboardImportRun { + /** + * Dashboards imported so far. + * + * @var integer + */ + public int $imported = 0; + + /** + * Dashboards skipped so far. + * + * @var integer + */ + public int $skipped = 0; + + /** + * Errors of the skipped dashboards, in order. + * + * @var array> + */ + public array $errors = []; + + /** + * The created dashboards: sourceUuid, uuid and id. + * + * @var array> + */ + public array $created = []; + + /** + * Constructor + * + * @param string $currentUserId The importing user. + * @param boolean $preserveUuids Whether archive UUIDs are kept. + */ + public function __construct( + public readonly string $currentUserId, + public readonly bool $preserveUuids, + ) { + }//end __construct() + + /** + * Count one imported dashboard and list it under its archive UUID. + * + * @param string $sourceUuid The UUID in the archive. + * @param Dashboard $persisted The inserted dashboard. + * + * @return void + * + * @spec openspec/specs/dashboard-export-import/spec.md + */ + public function recordImported(string $sourceUuid, Dashboard $persisted): void { + $this->imported++; + $this->created[] = [ + 'sourceUuid' => $sourceUuid, + 'uuid' => (string)$persisted->getUuid(), + 'id' => (int)$persisted->getId(), + ]; + }//end recordImported() + + /** + * Count one skipped dashboard with its error. + * + * @param array $error The error entry. + * + * @return void + * + * @spec openspec/specs/dashboard-export-import/spec.md + */ + public function recordSkipped(array $error): void { + $this->skipped++; + $this->errors[] = $error; + }//end recordSkipped() + + /** + * The batch result: counts, errors and created dashboards. + * + * @return array{importedDashboardCount: int, skippedDashboardCount: int, + * errors: array>, + * dashboards: array>} + * + * @spec openspec/specs/dashboard-export-import/spec.md + */ + public function summary(): array { + return [ + 'importedDashboardCount' => $this->imported, + 'skippedDashboardCount' => $this->skipped, + 'errors' => $this->errors, + 'dashboards' => $this->created, + ]; + }//end summary() +}//end class diff --git a/lib/Service/DashboardLimits.php b/lib/Service/DashboardLimits.php new file mode 100644 index 000000000..c72bc3dc5 --- /dev/null +++ b/lib/Service/DashboardLimits.php @@ -0,0 +1,61 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Lock\ILockingProvider; + +/** + * The optional limits on dashboard writes: role features, public-share bearers, quotas and the fork + * lock. + * + * @spec openspec/specs/dashboards/spec.md + */ +class DashboardLimits { + /** + * Constructor. + * + * @param RoleFeaturePermissionService|null $roleFeaturePerm Role-default layout seeding (REQ-RFP-002). + * Nullable to keep legacy PHPUnit doubles working + * — the seedLayoutFromRoleDefaults call site below + * guards on null and degrades to the original no- + * op behaviour. + * @param PublicShareContext|null $publicShareContext Optional public-share bearer context; when + * present a share bearer cannot mutate + * dashboards (dashboard-public-share). + * @param QuotaService|null $quotaService Optional quota-enforcement service gating per-user + * dashboard creation (dashboard-quota-limits). + * @param ILockingProvider|null $lockingProvider Optional cluster lock provider used to serialise + * the fork naming + insert sequence per user so + * concurrent forks cannot produce duplicate slugs + * (REQ-DASH-020). + */ + public function __construct( + public readonly ?RoleFeaturePermissionService $roleFeaturePerm=null, + public readonly ?PublicShareContext $publicShareContext=null, + public readonly ?QuotaService $quotaService=null, + public readonly ?ILockingProvider $lockingProvider=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/DashboardLockService.php b/lib/Service/DashboardLockService.php index 4e87df71b..fd20bc266 100644 --- a/lib/Service/DashboardLockService.php +++ b/lib/Service/DashboardLockService.php @@ -38,49 +38,34 @@ use DateTime; use OCA\LaunchPad\Db\DashboardLock; -use OCA\LaunchPad\Db\DashboardLockMapper; use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Exception\LockConflictException; use OCA\LaunchPad\Exception\LockForbiddenException; use OCA\LaunchPad\Exception\LockNotFoundException; +use OCA\LaunchPad\Kernel\Contracts\DashboardLockServiceInterface; use OCP\AppFramework\Db\DoesNotExistException; use OCP\IGroupManager; use OCP\IUserManager; -use Psr\Log\LoggerInterface; /** * Service for acquiring, refreshing, releasing and querying dashboard * editing locks. */ -class DashboardLockService { +class DashboardLockService implements DashboardLockServiceInterface { /** * Constructor * - * @param DashboardLockMapper $lockMapper The lock mapper. - * @param DashboardMapper $dashboardMapper Used to verify the - * dashboard exists - * before a lock row - * is written. - * @param IUserManager $userManager Resolves display names for - * new locks. - * @param IGroupManager $groupManager Admin check for force-release. - * @param LoggerInterface $logger PSR logger — used for - * the force-release audit - * trail (REQ-LOCK-006, - * design D4). - * @param PermissionService $permissionService Permission resolver — used - * to verify the caller has at - * least view access before - * granting or extending a lock - * (C3 fix: REQ-LOCK-001 + - * REQ-PERM-001). + * @param LockStore $locks The lock mapper and logger. + * @param DashboardMapper $dashboardMapper Used to verify the dashboard exists before a lock row is written. + * @param LockDirectory $directory The user and group managers. + * @param PermissionService $permissionService Permission resolver — used to verify the caller has at + * least view access before granting or extending a lock (C3 + * fix: REQ-LOCK-001 + REQ-PERM-001). */ public function __construct( - private readonly DashboardLockMapper $lockMapper, + private readonly LockStore $locks, private readonly DashboardMapper $dashboardMapper, - private readonly IUserManager $userManager, - private readonly IGroupManager $groupManager, - private readonly LoggerInterface $logger, + private readonly LockDirectory $directory, private readonly PermissionService $permissionService, ) { }//end __construct() @@ -127,7 +112,32 @@ public function acquireLock( // C3 fix (REQ-LOCK-001 + REQ-PERM-001): a caller without at least // view access MUST NOT be allowed to acquire an edit lock — the // lock acts as a denial-of-service vector against any discovered UUID. - $dashboardId = (int)$dashboard->getId(); + $this->assertCanView(userId: $userId, dashboardId: (int)$dashboard->getId()); + + // Inline cleanup so stale rows don't block the new acquire. + $this->locks->lockMapper->deleteExpiredForDashboard( + dashboardUuid: $dashboardUuid + ); + + $existing = $this->storedLock(dashboardUuid: $dashboardUuid); + if ($existing !== null) { + return $this->reenterLock(existing: $existing, userId: $userId); + } + + return $this->insertLock(dashboardUuid: $dashboardUuid, userId: $userId); + }//end acquireLock() + + /** + * Refuse a caller without at least view access to the dashboard. + * + * @param string $userId The caller. + * @param int $dashboardId The dashboard ID. + * + * @return void + * + * @throws LockForbiddenException When the caller cannot view the dashboard. + */ + private function assertCanView(string $userId, int $dashboardId): void { if ($this->permissionService->canViewDashboard( userId: $userId, dashboardId: $dashboardId @@ -137,34 +147,59 @@ public function acquireLock( message: 'You do not have access to this dashboard' ); } + }//end assertCanView() - // Inline cleanup so stale rows don't block the new acquire. - $this->lockMapper->deleteExpiredForDashboard( - dashboardUuid: $dashboardUuid - ); - + /** + * The lock row of a dashboard, or null when there is none. + * + * @param string $dashboardUuid The dashboard UUID. + * + * @return DashboardLock|null The lock, or null. + */ + private function storedLock(string $dashboardUuid): DashboardLock|null { try { - $existing = $this->lockMapper->findByDashboardUuid( + return $this->locks->lockMapper->findByDashboardUuid( dashboardUuid: $dashboardUuid ); } catch (DoesNotExistException) { - $existing = null; + return null; } + }//end storedLock() - if ($existing !== null) { - if ($existing->getUserId() === $userId) { - // Re-entrant refresh — bump heartbeat and return. - $existing->setUpdatedAt($this->now()); - return $this->lockMapper->update(entity: $existing); - } - - // Held by someone else — surface the conflict. - throw new LockConflictException( - message: 'Lock held by another user', - existingLock: $existing, - ); + /** + * Acquire an existing lock again: the holder's own acquire bumps the + * heartbeat, anyone else's is a conflict. + * + * @param DashboardLock $existing The existing lock. + * @param string $userId The caller. + * + * @return DashboardLock The refreshed lock. + * + * @throws LockConflictException When another user holds the lock. + */ + private function reenterLock(DashboardLock $existing, string $userId): DashboardLock { + if ($existing->getUserId() === $userId) { + // Re-entrant refresh — bump heartbeat and return. + $existing->setUpdatedAt($this->now()); + return $this->locks->lockMapper->update(entity: $existing); } + // Held by someone else — surface the conflict. + throw new LockConflictException( + message: 'Lock held by another user', + existingLock: $existing, + ); + }//end reenterLock() + + /** + * Insert a fresh lock for the caller. + * + * @param string $dashboardUuid The dashboard UUID. + * @param string $userId The caller. + * + * @return DashboardLock The inserted lock. + */ + private function insertLock(string $dashboardUuid, string $userId): DashboardLock { $now = $this->now(); $lock = new DashboardLock(); $lock->setDashboardUuid($dashboardUuid); @@ -173,8 +208,8 @@ public function acquireLock( $lock->setCreatedAt($now); $lock->setUpdatedAt($now); - return $this->lockMapper->insert(entity: $lock); - }//end acquireLock() + return $this->locks->lockMapper->insert(entity: $lock); + }//end insertLock() /** * Refresh the lock by bumping `updatedAt` (the "heartbeat"). @@ -203,24 +238,9 @@ public function heartbeat( // C3 fix: verify the caller has at least view access before // allowing a heartbeat — prevents indefinite lock extension by // an attacker who discovered the UUID. - try { - $dashboard = $this->dashboardMapper->findByUuid(uuid: $dashboardUuid); - $dashboardId = (int)$dashboard->getId(); - } catch (DoesNotExistException) { - throw new LockNotFoundException(message: 'Lock not found; call acquire first'); - } + $this->assertCanView(userId: $userId, dashboardId: $this->lockedDashboardId(dashboardUuid: $dashboardUuid)); - if ($this->permissionService->canViewDashboard( - userId: $userId, - dashboardId: $dashboardId - ) === false - ) { - throw new LockForbiddenException( - message: 'You do not have access to this dashboard' - ); - } - - $existing = $this->lockMapper->findActive( + $existing = $this->locks->lockMapper->findActive( dashboardUuid: $dashboardUuid ); @@ -237,9 +257,28 @@ public function heartbeat( } $existing->setUpdatedAt($this->now()); - return $this->lockMapper->update(entity: $existing); + return $this->locks->lockMapper->update(entity: $existing); }//end heartbeat() + /** + * The ID of the dashboard a heartbeat targets; a missing dashboard + * has no lock to extend. + * + * @param string $dashboardUuid The dashboard UUID. + * + * @return int The dashboard ID. + * + * @throws LockNotFoundException When the dashboard does not exist. + */ + private function lockedDashboardId(string $dashboardUuid): int { + try { + $dashboard = $this->dashboardMapper->findByUuid(uuid: $dashboardUuid); + return (int)$dashboard->getId(); + } catch (DoesNotExistException) { + throw new LockNotFoundException(message: 'Lock not found; call acquire first'); + } + }//end lockedDashboardId() + /** * Release the editing lock on a dashboard. * @@ -269,7 +308,7 @@ public function releaseLock( string $userId, bool $allowAdminOverride = true, ): void { - $existing = $this->lockMapper->findActive( + $existing = $this->locks->lockMapper->findActive( dashboardUuid: $dashboardUuid ); @@ -280,7 +319,7 @@ public function releaseLock( if ($existing->getUserId() !== $userId) { if ($allowAdminOverride === false - || $this->groupManager->isAdmin(userId: $userId) === false + || $this->directory->groupManager->isAdmin(userId: $userId) === false ) { throw new LockForbiddenException( message: 'Only the lock owner or an admin can release this lock' @@ -288,7 +327,7 @@ public function releaseLock( } // L2: audit log when an admin overrides another user's lock. - $this->logger->info( + $this->locks->logger->info( message: sprintf( 'launchpad.dashboard_lock.admin_override_release admin=%s dashboard=%s previous_owner=%s', $userId, @@ -298,7 +337,7 @@ public function releaseLock( ); } - $this->lockMapper->delete(entity: $existing); + $this->locks->lockMapper->delete(entity: $existing); }//end releaseLock() /** @@ -317,11 +356,11 @@ public function getLockState(string $dashboardUuid): ?DashboardLock { // Inline cleanup so the next read is never polluted by a stale // row. Cheap on the indexed `(dashboard_uuid, updated_at)` // path even when the row is fresh (no-op delete). - $this->lockMapper->deleteExpiredForDashboard( + $this->locks->lockMapper->deleteExpiredForDashboard( dashboardUuid: $dashboardUuid ); - return $this->lockMapper->findActive( + return $this->locks->lockMapper->findActive( dashboardUuid: $dashboardUuid ); }//end getLockState() @@ -349,22 +388,22 @@ public function forceRelease( string $dashboardUuid, string $adminUserId, ): void { - if ($this->groupManager->isAdmin(userId: $adminUserId) === false) { + if ($this->directory->groupManager->isAdmin(userId: $adminUserId) === false) { throw new LockForbiddenException( message: 'Only an administrator may force-release a lock' ); } - $existing = $this->lockMapper->findActive( + $existing = $this->locks->lockMapper->findActive( dashboardUuid: $dashboardUuid ); $previousOwner = null; if ($existing !== null) { $previousOwner = (string)$existing->getUserId(); - $this->lockMapper->delete(entity: $existing); + $this->locks->lockMapper->delete(entity: $existing); } - $this->logger->info( + $this->locks->logger->info( message: sprintf( 'launchpad.dashboard_lock.force_release admin=%s dashboard=%s previous_owner=%s', $adminUserId, @@ -388,7 +427,7 @@ public function forceRelease( * @spec openspec/specs/dashboard-locking/spec.md */ public function cascadeDelete(string $dashboardUuid): int { - return $this->lockMapper->deleteByDashboardUuid( + return $this->locks->lockMapper->deleteByDashboardUuid( dashboardUuid: $dashboardUuid ); }//end cascadeDelete() @@ -405,7 +444,7 @@ public function cascadeDelete(string $dashboardUuid): int { * @return string The display name. */ private function resolveDisplayName(string $userId): string { - $user = $this->userManager->get(uid: $userId); + $user = $this->directory->userManager->get(uid: $userId); if ($user === null) { return $userId; } diff --git a/lib/Service/DashboardLook.php b/lib/Service/DashboardLook.php new file mode 100644 index 000000000..1f8e6df16 --- /dev/null +++ b/lib/Service/DashboardLook.php @@ -0,0 +1,168 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; +use OCA\LaunchPad\Exception\ContrastTooLowException; + +/** + * Colours are `#rrggbb`. Contrast is the WCAG 2.2 ratio between the relative + * luminances of two colours. Text on a dashboard background is black or + * white, whichever contrasts more, so body text always reaches 4.5:1. An + * accent (buttons, borders, focus rings) must reach 3:1 against the + * background, WCAG 2.2 SC 1.4.11; the accent's own text colour is derived + * the same way, so it reaches 4.5:1 by construction. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ +final class DashboardLook { + + /** + * The least contrast an accent needs against the background (SC 1.4.11). + */ + public const MIN_ACCENT_CONTRAST = 3.0; + + /** + * The background a dashboard without its own background colour is drawn on. + * + * Nextcloud's default main background; a theme that darkens it is not known + * on the server, so an accent is checked against white when the dashboard + * sets no background of its own. + */ + public const INSTANCE_BACKGROUND = '#ffffff'; + + /** + * A colour in canonical form: lower-case `#rrggbb`; `#rgb` is expanded. + * + * @param string $colour The colour as entered. + * @param string $field The field name, for the message. + * + * @return string + * + * @throws InvalidArgumentException When the colour is not a hex colour. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 + */ + public static function normaliseHex(string $colour, string $field): string { + $colour = strtolower(trim($colour)); + if (preg_match('/^#([0-9a-f]{3})$/', $colour, $short) === 1) { + $colour = '#' . $short[1][0] . $short[1][0] . $short[1][1] . $short[1][1] . $short[1][2] . $short[1][2]; + } + + if (preg_match('/^#[0-9a-f]{6}$/', $colour) !== 1) { + throw new InvalidArgumentException($field . ' must be a colour like #1f5c3a.'); + } + + return $colour; + }//end normaliseHex() + + /** + * The WCAG relative luminance of a `#rrggbb` colour. + * + * @param string $colour The colour. + * + * @return float Between 0 (black) and 1 (white). + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ + public static function relativeLuminance(string $colour): float { + $channels = []; + foreach ([1, 3, 5] as $offset) { + $value = hexdec(substr($colour, $offset, 2)) / 255; + if ($value <= 0.04045) { + $channels[] = $value / 12.92; + continue; + } + + $channels[] = ((($value + 0.055) / 1.055) ** 2.4); + } + + return (0.2126 * $channels[0]) + (0.7152 * $channels[1]) + (0.0722 * $channels[2]); + }//end relativeLuminance() + + /** + * The WCAG contrast ratio between two colours. + * + * @param string $first One colour. + * @param string $second The other colour. + * + * @return float From 1 (same) to 21 (black on white). + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ + public static function contrast(string $first, string $second): float { + $lighter = max(self::relativeLuminance(colour: $first), self::relativeLuminance(colour: $second)); + $darker = min(self::relativeLuminance(colour: $first), self::relativeLuminance(colour: $second)); + + return ($lighter + 0.05) / ($darker + 0.05); + }//end contrast() + + /** + * Black or white, whichever reads better on the background. + * + * @param string $background The background colour. + * + * @return string `#000000` or `#ffffff`. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ + public static function textColorFor(string $background): string { + if (self::contrast(first: '#000000', second: $background) >= self::contrast(first: '#ffffff', second: $background)) { + return '#000000'; + } + + return '#ffffff'; + }//end textColorFor() + + /** + * Refuse an accent that would be hard to see on the background. + * + * @param string $accent The accent colour. + * @param string|null $background The dashboard's background colour, or null for the instance's. + * + * @return void + * + * @throws ContrastTooLowException When the contrast is under 3:1. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ + public static function assertAccentReadable(string $accent, ?string $background): void { + $ratio = self::contrast(first: $accent, second: ($background ?? self::INSTANCE_BACKGROUND)); + if ($ratio < self::MIN_ACCENT_CONTRAST) { + throw new ContrastTooLowException(ratio: $ratio); + } + }//end assertAccentReadable() + + /** + * Whether a value is a LaunchPad resource file name (what the upload returns). + * + * @param string $name The value. + * + * @return bool + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 + */ + public static function isResourceName(string $name): bool { + return preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{0,200}\.(png|jpe?g|gif|webp|svg)$/i', $name) === 1 + && str_contains($name, '..') === false; + }//end isResourceName() +}//end class diff --git a/lib/Service/DashboardOutlets.php b/lib/Service/DashboardOutlets.php new file mode 100644 index 000000000..94d4ad112 --- /dev/null +++ b/lib/Service/DashboardOutlets.php @@ -0,0 +1,57 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Activity\DashboardActivityEmitter; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IURLGenerator; +use Psr\Log\LoggerInterface; + +/** + * Where DashboardService reports to: the log, events, URLs and the activity stream. + * + * @spec openspec/specs/dashboards/spec.md + */ +class DashboardOutlets { + /** + * Constructor. + * + * @param LoggerInterface $logger PSR logger. + * @param IEventDispatcher|null $eventDispatcher Event dispatcher for DashboardDeletedEvent. Nullable + * for backwards- compat with existing test doubles. + * @param IURLGenerator|null $urlGenerator URL generator used to build widget / app image paths + * and to resolve app image paths for default tile logos, + * so they render regardless of the app's install + * location. + * @param DashboardActivityEmitter|null $activity Sends dashboard_published and dashboard_updated to the + * audience (#713). + */ + public function __construct( + public readonly LoggerInterface $logger, + public readonly ?IEventDispatcher $eventDispatcher=null, + public readonly ?IURLGenerator $urlGenerator=null, + public readonly ?DashboardActivityEmitter $activity=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/DashboardPlatform.php b/lib/Service/DashboardPlatform.php new file mode 100644 index 000000000..3490c3049 --- /dev/null +++ b/lib/Service/DashboardPlatform.php @@ -0,0 +1,56 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\L10N\IFactory; + +/** + * The Nextcloud services DashboardService runs on: groups, the database, config and l10n. + * + * @spec openspec/specs/dashboards/spec.md + */ +class DashboardPlatform { + /** + * Constructor. + * + * @param IGroupManager $groupManager Group manager (used for `isAdmin` only — group membership lookups go + * through the routing resolver per REQ-TMPL-013). + * @param IDBConnection $db DB connection (for the transactional default flip — REQ-DASH-015). + * @param IConfig $config Nextcloud per-user preference storage. + * @param IFactory $l10nFactory L10N factory used to build the "My copy of {name}" default fork name + * (REQ-DASH-020). + * @param GroupDashboardCreation|null $groupCreation Decides who may create a group dashboard (REQ-DASH-014). + */ + public function __construct( + public readonly IGroupManager $groupManager, + public readonly IDBConnection $db, + public readonly IConfig $config, + public readonly IFactory $l10nFactory, + public readonly ?GroupDashboardCreation $groupCreation = null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/DashboardPresenceService.php b/lib/Service/DashboardPresenceService.php new file mode 100644 index 000000000..1ec516c16 --- /dev/null +++ b/lib/Service/DashboardPresenceService.php @@ -0,0 +1,220 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * @spec openspec/specs/dashboard-co-editing/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Exception\ForbiddenException; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\ICache; +use OCP\ICacheFactory; +use OCP\IUserManager; + +/** + * Keeps and reads the editors present on a dashboard. + * + * @spec openspec/specs/dashboard-co-editing/spec.md + */ +class DashboardPresenceService { + + /** + * Seconds an editor stays listed after its last heartbeat. + * + * @var int + */ + public const PRESENCE_TTL = 90; + + /** + * The cache the presence lists are kept in. + * + * @var ICache + */ + private ICache $cache; + + /** + * Constructor. + * + * @param ICacheFactory $cacheFactory Gives the distributed cache. + * @param DashboardMapper $dashboardMapper Resolves the dashboard of a UUID. + * @param PermissionService $permissionService Tells who may edit a dashboard. + * @param IUserManager $userManager Gives an editor's display name. + * @param ITimeFactory $timeFactory Tells the time. + * + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ + public function __construct( + ICacheFactory $cacheFactory, + private readonly DashboardMapper $dashboardMapper, + private readonly PermissionService $permissionService, + private readonly IUserManager $userManager, + private readonly ITimeFactory $timeFactory, + ) { + $this->cache = $cacheFactory->createDistributed(prefix: 'launchpad_presence_'); + }//end __construct() + + /** + * Announce that a person edits a dashboard, or renew the announcement, + * and answer who else is editing it. + * + * The first announcement sets the moment the person started; renewing + * keeps it. + * + * @param string $dashboardUuid The dashboard. + * @param string $userId The editor. + * + * @return list The colleagues editing it, longest first. + * + * @throws DoesNotExistException When the dashboard does not exist. + * @throws ForbiddenException When the person may not edit the dashboard. + * + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ + public function join(string $dashboardUuid, string $userId): array { + $dashboard = $this->dashboardMapper->findByUuid(uuid: $dashboardUuid); + if ($this->permissionService->canEditDashboard(userId: $userId, dashboardId: (int)$dashboard->getId()) === false) { + throw new ForbiddenException(message: 'You may not edit this dashboard'); + } + + $now = $this->timeFactory->getTime(); + $editors = $this->present(dashboardUuid: $dashboardUuid, now: $now); + + $since = ($editors[$userId]['since'] ?? date(format: DATE_ATOM, timestamp: $now)); + $editors[$userId] = [ + 'displayName' => $this->displayName(userId: $userId), + 'since' => $since, + 'seenAt' => $now, + ]; + $this->store(dashboardUuid: $dashboardUuid, editors: $editors); + + unset($editors[$userId]); + return $this->colleagues(editors: $editors); + }//end join() + + /** + * Take a person off a dashboard's editors. Idempotent. + * + * @param string $dashboardUuid The dashboard. + * @param string $userId The editor leaving. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ + public function leave(string $dashboardUuid, string $userId): void { + $editors = $this->present(dashboardUuid: $dashboardUuid, now: $this->timeFactory->getTime()); + if (array_key_exists($userId, $editors) === false) { + return; + } + + unset($editors[$userId]); + $this->store(dashboardUuid: $dashboardUuid, editors: $editors); + }//end leave() + + /** + * The editors of a dashboard whose heartbeat is still fresh. + * + * @param string $dashboardUuid The dashboard. + * @param int $now The current time, in seconds. + * + * @return array By user id. + */ + private function present(string $dashboardUuid, int $now): array { + $stored = $this->cache->get(key: $dashboardUuid); + if (is_array($stored) === false) { + return []; + } + + $editors = []; + foreach ($stored as $userId => $editor) { + if (is_array($editor) === false || is_int($editor['seenAt'] ?? null) === false) { + continue; + } + + if ($now - $editor['seenAt'] > self::PRESENCE_TTL) { + continue; + } + + $editors[(string)$userId] = [ + 'displayName' => (string)($editor['displayName'] ?? $userId), + 'since' => (string)($editor['since'] ?? ''), + 'seenAt' => $editor['seenAt'], + ]; + } + + return $editors; + }//end present() + + /** + * Keep a dashboard's editors, or drop the entry when nobody is left. + * + * @param string $dashboardUuid The dashboard. + * @param array $editors By user id. + * + * @return void + */ + private function store(string $dashboardUuid, array $editors): void { + if ($editors === []) { + $this->cache->remove(key: $dashboardUuid); + return; + } + + $this->cache->set(key: $dashboardUuid, value: $editors, ttl: self::PRESENCE_TTL); + }//end store() + + /** + * The colleagues as the editor sees them: name and start, longest first, + * without their user ids. + * + * @param array $editors By user id. + * + * @return list + */ + private function colleagues(array $editors): array { + $list = array_map( + static fn (array $editor): array => ['displayName' => $editor['displayName'], 'since' => $editor['since']], + array_values($editors) + ); + usort($list, static fn (array $a, array $b): int => strcmp($a['since'], $b['since'])); + + return $list; + }//end colleagues() + + /** + * A person's display name, the user id when there is none. + * + * @param string $userId The user id. + * + * @return string + */ + private function displayName(string $userId): string { + $name = $this->userManager->get(uid: $userId)?->getDisplayName(); + if ($name === null || $name === '') { + return $userId; + } + + return $name; + }//end displayName() +}//end class diff --git a/lib/Service/DashboardResolver.php b/lib/Service/DashboardResolver.php index 88d392316..1ee5d9838 100644 --- a/lib/Service/DashboardResolver.php +++ b/lib/Service/DashboardResolver.php @@ -61,19 +61,13 @@ public function __construct( * * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-18 */ - public function tryGetActiveDashboard(string $userId): ?array { + public function tryGetActiveDashboard(string $userId): array|null { try { $dashboard = $this->dashboardMapper->findActiveByUserId( userId: $userId ); - $placements = $this->placementMapper->findByDashboardId( - dashboardId: $dashboard->getId() - ); - return $this->buildResult( - dashboard: $dashboard, - placements: $placements - ); + return $this->resultWithPlacements(dashboard: $dashboard); } catch (DoesNotExistException) { return null; } @@ -88,7 +82,7 @@ public function tryGetActiveDashboard(string $userId): ?array { * * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-18 */ - public function tryActivateExistingDashboard(string $userId): ?array { + public function tryActivateExistingDashboard(string $userId): array|null { $userDashboards = $this->dashboardMapper->findByUserId( userId: $userId ); @@ -103,14 +97,7 @@ public function tryActivateExistingDashboard(string $userId): ?array { ); $dashboard->setIsActive(1); - $placements = $this->placementMapper->findByDashboardId( - dashboardId: $dashboard->getId() - ); - - return $this->buildResult( - dashboard: $dashboard, - placements: $placements - ); + return $this->resultWithPlacements(dashboard: $dashboard); }//end tryActivateExistingDashboard() /** @@ -171,85 +158,40 @@ public function findSharedDashboards(string $userId, array $userGroupIds): array $entries = []; foreach (array_keys($levels) as $dashboardId) { - try { - $dashboard = $this->dashboardMapper->find(id: (int)$dashboardId); - } catch (DoesNotExistException) { - // Orphaned share row — the cleanup job reaps these. - continue; - } - - if ($dashboard->getUserId() === $userId) { - continue; + $dashboard = $this->sharedDashboard(dashboardId: (int)$dashboardId, userId: $userId); + if ($dashboard !== null) { + $entries[] = [ + 'dashboard' => $dashboard, + 'source' => Dashboard::SOURCE_SHARED, + ]; } - - $entries[] = [ - 'dashboard' => $dashboard, - 'source' => Dashboard::SOURCE_SHARED, - ]; } return $entries; }//end findSharedDashboards() /** - * Try to resolve a dashboard shared with the user as their active one. - * - * This is the LAST-RESORT step of the resolution chain: it only ever - * runs after every dashboard the user owns (or reaches through group - * membership) has been considered, so a share can never displace a - * selection the user or their admin already made. Without it a share - * is inert — a recipient with no dashboard of their own lands on the - * empty state and the shared dashboard is unreachable. - * - * The returned `permissionLevel` comes from the SHARE, not from the - * dashboard row: the row carries the OWNER's level, which would tell a - * view-only recipient they may edit. + * A dashboard shared with the user; null for an orphaned share row + * (the cleanup job reaps these) or a dashboard the user owns. * - * Publication state is deliberately NOT a filter here, matching - * {@see \OCA\LaunchPad\Service\DashboardService::getVisibleToUser()}: - * every factory-created dashboard starts as `draft`, so filtering would - * make sharing inert again. The share row is the owner's explicit, - * named grant. The two paths MUST agree — when they disagreed, - * `GET /api/dashboard` served a draft while `/api/dashboards/visible` - * returned nothing for the same user. + * @param int $dashboardId The shared dashboard ID. + * @param string $userId The user ID. * - * @param string $userId The user ID. - * @param array $userGroupIds The user's Nextcloud group IDs. - * - * @return array|null The dashboard result or null when nothing is shared. - * - * @spec openspec/specs/dashboard-sharing/spec.md + * @return Dashboard|null The dashboard, or null. */ - public function tryGetSharedDashboard(string $userId, array $userGroupIds): ?array { - $levels = $this->findSharedLevels( - userId: $userId, - userGroupIds: $userGroupIds - ); - - foreach ($levels as $dashboardId => $level) { - try { - $dashboard = $this->dashboardMapper->find(id: (int)$dashboardId); - } catch (DoesNotExistException) { - continue; - } - - if ($dashboard->getUserId() === $userId) { - continue; - } - - $placements = $this->placementMapper->findByDashboardId( - dashboardId: $dashboard->getId() - ); + private function sharedDashboard(int $dashboardId, string $userId): Dashboard|null { + try { + $dashboard = $this->dashboardMapper->find(id: $dashboardId); + } catch (DoesNotExistException) { + return null; + } - return [ - 'dashboard' => $dashboard, - 'placements' => $placements, - 'permissionLevel' => $level, - ]; - }//end foreach + if ($dashboard->getUserId() === $userId) { + return null; + } - return null; - }//end tryGetSharedDashboard() + return $dashboard; + }//end sharedDashboard() /** * Handle a template-based dashboard result. @@ -272,22 +214,13 @@ public function handleTemplateResult( userId: $userId, template: $template ); - $placements = $this->placementMapper->findByDashboardId( - dashboardId: $dashboard->getId() - ); - return $this->buildResult( - dashboard: $dashboard, - placements: $placements - ); + return $this->resultWithPlacements(dashboard: $dashboard); } - $placements = $this->placementMapper->findByDashboardId( - dashboardId: $template->getId() - ); return [ 'dashboard' => $template, - 'placements' => $placements, + 'placements' => $this->placementsOf(dashboard: $template), 'permissionLevel' => Dashboard::PERMISSION_VIEW_ONLY, ]; }//end handleTemplateResult() @@ -317,6 +250,34 @@ public function buildResult( ]; }//end buildResult() + /** + * The result for a dashboard with its placements and its effective + * permission level. + * + * @param Dashboard $dashboard The dashboard. + * + * @return array{dashboard: Dashboard, placements: array, permissionLevel: string} + */ + private function resultWithPlacements(Dashboard $dashboard): array { + return $this->buildResult( + dashboard: $dashboard, + placements: $this->placementsOf(dashboard: $dashboard) + ); + }//end resultWithPlacements() + + /** + * The widget placements of a dashboard. + * + * @param Dashboard $dashboard The dashboard. + * + * @return array The placements. + */ + private function placementsOf(Dashboard $dashboard): array { + return $this->placementMapper->findByDashboardId( + dashboardId: $dashboard->getId() + ); + }//end placementsOf() + /** * Get the effective permission level for a dashboard. * diff --git a/lib/Service/DashboardService.php b/lib/Service/DashboardService.php index 01e8640c1..5ac78a99a 100644 --- a/lib/Service/DashboardService.php +++ b/lib/Service/DashboardService.php @@ -26,29 +26,25 @@ use DateTimeImmutable; use Exception; use InvalidArgumentException; -use OCA\LaunchPad\Activity\DashboardActivityEmitter; use OCA\LaunchPad\AppInfo\Application; use OCA\LaunchPad\Db\AdminSetting; -use OCA\LaunchPad\Db\AdminSettingMapper; use OCA\LaunchPad\Db\Dashboard; -use OCA\LaunchPad\Db\DashboardLockMapper; use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacement; use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Event\DashboardAudienceChangedEvent; use OCA\LaunchPad\Event\DashboardDeletedEvent; use OCA\LaunchPad\Exception\DashboardHasChildrenException; +use OCA\LaunchPad\Exception\ForbiddenException; use OCA\LaunchPad\Exception\PersonalDashboardsDisabledException; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IL10N; use OCP\IURLGenerator; -use OCP\L10N\IFactory; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; -use Psr\Log\LoggerInterface; use Throwable; /** @@ -72,6 +68,35 @@ * @spec openspec/specs/dashboards/spec.md */ class DashboardService { + /** + * The optional createDashboard() fields and their defaults. + */ + private const CREATE_DEFAULTS = [ + 'description' => null, + 'icon' => null, + 'parentUuid' => null, + 'slug' => null, + 'sortOrder' => 0, + 'seedDefaults' => false, + 'seedSet' => self::SEED_SET_DEFAULT, + 'menuAppIds' => [], + 'gridColumns' => null, + ]; + + /** + * Seed set: the default widget bundle. + * + * @var string + */ + public const SEED_SET_DEFAULT = 'default'; + + /** + * Seed set: the starter widgets of a first dashboard ({@see StarterWidgetSeeds}). + * + * @var string + */ + public const SEED_SET_STARTERS = 'starters'; + /** * HTTP-like error message for non-admin attempting an admin-only mutation. * @@ -122,6 +147,18 @@ class DashboardService { */ public const DEFAULT_DASHBOARD_UUID_PREF_KEY = 'default_dashboard_uuid'; + /** + * User preference holding a JSON list of organisation-wide dashboards + * (the `default` group) this user does not see. Only `default`-group + * rows can be set aside this way: what a user owns, reaches through + * their own group or was shared stays visible. The demo seed writes it + * for its first-run user so a first visit shows the empty state without + * touching the organisation's dashboard (Ruben, 25 Nov 2026). + * + * @var string + */ + public const HIDDEN_DASHBOARDS_PREF_KEY = 'hidden_dashboard_uuids'; + /** * HTTP-like error message for non-owner / non-admin attempting a * publication state mutation. REQ-DASH-032..034. @@ -146,194 +183,94 @@ class DashboardService { */ public const ERR_UNPUBLISH_BEFORE_PUBLISH = 'unpublishAt must be after publishAt'; + /** + * The default widget set of a brand-new dashboard. + * + * A tile with `iconType` `url` names a bundled image under + * `launchpad/img/`; {@see self::defaultWidgetSeeds()} resolves it. + * + * @var array> + */ + private const DEFAULT_WIDGET_SEEDS = [ + [ + 'widgetId' => 'tile', + 'gridX' => 0, + 'gridY' => 0, + 'gridWidth' => 4, + 'gridHeight' => 3, + 'sortOrder' => 0, + 'tile' => [ + 'title' => 'Conduction', + 'icon' => 'conduction-logo.png', + 'iconType' => 'url', + 'backgroundColor' => '#ffffff', + 'textColor' => '#000000', + 'linkType' => 'url', + 'linkValue' => 'https://conduction.nl', + ], + ], + [ + 'widgetId' => 'tile', + 'gridX' => 4, + 'gridY' => 0, + 'gridWidth' => 4, + 'gridHeight' => 3, + 'sortOrder' => 1, + 'tile' => [ + 'title' => 'Sendent', + 'icon' => 'sendent-logo.png', + 'iconType' => 'url', + 'backgroundColor' => '#ffffff', + 'textColor' => '#000000', + 'linkType' => 'url', + 'linkValue' => 'https://sendent.com', + ], + ], + [ + 'widgetId' => 'tile', + 'gridX' => 8, + 'gridY' => 0, + 'gridWidth' => 4, + 'gridHeight' => 3, + 'sortOrder' => 2, + 'tile' => [ + 'title' => 'Nextcloud', + 'icon' => 'icon-nextcloud', + 'iconType' => 'class', + 'backgroundColor' => '#0082c9', + 'textColor' => '#ffffff', + 'linkType' => 'url', + 'linkValue' => 'https://nextcloud.com', + ], + ], + [ + 'widgetId' => 'files', + 'gridX' => 0, + 'gridY' => 3, + 'gridWidth' => 12, + 'gridHeight' => 5, + 'sortOrder' => 3, + 'tile' => null, + ], + ]; + /** * Constructor * - * @param DashboardMapper $dashboardMapper Dashboard mapper. - * @param WidgetPlacementMapper $placementMapper Widget placement mapper. - * @param AdminSettingMapper $settingMapper Admin setting mapper. - * @param TemplateService $templateService Template service. - * @param DashboardFactory $dashboardFactory Dashboard factory. - * @param DashboardResolver $dashResolver Dashboard resolver. - * @param DashboardTreeService $treeService Tree-aware - * validation - * / cascade - * walker - * (REQ-DASH-023..030). - * @param IGroupManager $groupManager Group manager (used for - * `isAdmin` only — - * group membership - * lookups go through the - * routing resolver per - * REQ-TMPL-013). - * @param AdminTemplateService $adminTemplateService Routing resolver - * — single - * source of truth - * for - * `IGroupManager::getUserGroupIds` - * (REQ-TMPL-013). - * @param IDBConnection $db DB connection (for the - * transactional default - * flip — - * REQ-DASH-015). - * @param IConfig $config Nextcloud per-user - * preference - * storage. - * @param IFactory $l10nFactory L10N factory used to - * build the "My copy - * of {name}" default - * fork name - * (REQ-DASH-020). - * @param LoggerInterface $logger PSR logger. - * @param PersonalLayerService $personalLayers Lays a reader's own - * arrangement over a - * dashboard somebody else - * owns (REQ-DWMS-001). - * Required, not nullable: - * a null here is - * indistinguishable from a - * reader who has no layer, - * so broken wiring would - * store layers and show - * none of them, in silence - * and with every test - * green. - * @param DashboardTranslationService|null $translationService Optional - * translation - * service - * for the - * per-language - * content - * variants - * (REQ-DASH-038..044). - * Nullable - * so - * legacy - * test - * doubles - * constructed - * without - * it keep - * working. - * @param DashboardLockMapper|null $lockMapper Optional lock - * mapper. When - * provided the - * delete path - * cascades the - * row removal - * to the - * editing-lock - * table per - * REQ-LOCK-008. - * Nullable to - * keep the - * constructor - * backwards- - * compatible - * with existing - * unit tests. - * @param FooterService|null $footerService Optional - * per-dashboard - * footer - * sanitiser - * + - * resolver - * (REQ-FTR-006). - * Nullable - * for - * backwards- - * compat - * with - * existing - * test - * doubles. - * @param RoleFeaturePermissionService|null $roleFeaturePerm Role-default - * layout - * seeding - * (REQ-RFP-002). - * Nullable to - * keep legacy - * PHPUnit - * doubles - * working — - * the - * seedLayoutFromRoleDefaults - * call site - * below guards - * on null and - * degrades to - * the original - * no- op - * behaviour. - * @param IEventDispatcher|null $eventDispatcher Event - * dispatcher - * for - * DashboardDeletedEvent. - * Nullable - * for - * backwards- - * compat - * with - * existing - * test - * doubles. - * @param PublicShareContext|null $publicShareContext Optional public-share - * bearer context; when - * present a share - * bearer cannot mutate - * dashboards - * (dashboard-public-share). - * @param QuotaService|null $quotaService Optional quota-enforcement - * service gating per-user - * dashboard creation - * (dashboard-quota-limits). - * @param IURLGenerator|null $urlGenerator URL generator used to - * build widget / app - * image paths and to - * resolve app image - * paths for default - * tile logos, so they - * render regardless of - * the app's install - * location. - * @param ILockingProvider|null $lockingProvider Optional cluster lock - * provider used to - * serialise the fork - * naming + insert - * sequence per user so - * concurrent forks - * cannot produce - * duplicate slugs - * (REQ-DASH-020). - * @param DashboardActivityEmitter|null $activity Sends dashboard_published - * and dashboard_updated to - * the audience (#713). + * @param DashboardStores $stores The dashboard, placement, admin-setting and lock mappers. + * @param DashboardBuilders $builders The template services, the dashboard factory and the resolver. + * @param DashboardStructure $structure The tree, personal-layer, translation and footer services. + * @param DashboardPlatform $platform The group manager, database connection, config and l10n factory. + * @param DashboardOutlets $outlets The logger, event dispatcher, URL generator and activity emitter. + * @param DashboardLimits $limits The optional role-feature, public-share, quota and locking collaborators. */ public function __construct( - private readonly DashboardMapper $dashboardMapper, - private readonly WidgetPlacementMapper $placementMapper, - private readonly AdminSettingMapper $settingMapper, - private readonly TemplateService $templateService, - private readonly DashboardFactory $dashboardFactory, - private readonly DashboardResolver $dashResolver, - private readonly DashboardTreeService $treeService, - private readonly IGroupManager $groupManager, - private readonly AdminTemplateService $adminTemplateService, - private readonly IDBConnection $db, - private readonly IConfig $config, - private readonly IFactory $l10nFactory, - private readonly LoggerInterface $logger, - private readonly PersonalLayerService $personalLayers, - private readonly ?DashboardTranslationService $translationService = null, - private readonly ?DashboardLockMapper $lockMapper = null, - private readonly ?FooterService $footerService = null, - private readonly ?RoleFeaturePermissionService $roleFeaturePerm = null, - private readonly ?IEventDispatcher $eventDispatcher = null, - private readonly ?PublicShareContext $publicShareContext = null, - private readonly ?QuotaService $quotaService = null, - private readonly ?IURLGenerator $urlGenerator = null, - private readonly ?ILockingProvider $lockingProvider = null, - private readonly ?DashboardActivityEmitter $activity = null, + private readonly DashboardStores $stores, + private readonly DashboardBuilders $builders, + private readonly DashboardStructure $structure, + private readonly DashboardPlatform $platform, + private readonly DashboardOutlets $outlets, + private readonly DashboardLimits $limits = new DashboardLimits(), ) { }//end __construct() @@ -349,8 +286,8 @@ public function __construct( * @return string The web path to the image. */ private function appImagePath(string $image): string { - if ($this->urlGenerator !== null) { - return $this->urlGenerator->imagePath('launchpad', $image); + if ($this->outlets->urlGenerator !== null) { + return $this->outlets->urlGenerator->imagePath('launchpad', $image); } return '/apps/launchpad/img/' . $image; @@ -369,7 +306,7 @@ private function appImagePath(string $image): string { * @spec openspec/specs/dashboards/spec.md */ public function getUserDashboards(string $userId): array { - return $this->dashboardMapper->findByUserId(userId: $userId); + return $this->stores->dashboardMapper->findByUserId(userId: $userId); }//end getUserDashboards() /** @@ -401,23 +338,16 @@ public function getDashboardForUser( // entity — calling `getId()` on the wrapper triggers the // "member function on array" fatal that broke the switch flow // when this method first shipped. - $visible = $this->getVisibleToUser(userId: $userId); - $dashboard = null; - $source = ''; - foreach ($visible as $entry) { - $candidate = $entry['dashboard']; - if ($candidate->getId() === $dashboardId) { - $dashboard = $candidate; - $source = (string)$entry['source']; - break; - } - } - - if ($dashboard === null) { + $entry = $this->findVisibleEntryById( + visible: $this->getVisibleToUser(userId: $userId), + dashboardId: $dashboardId + ); + if ($entry === null) { return null; } - $placements = $this->placementMapper->findByDashboardId( + $dashboard = $entry['dashboard']; + $placements = $this->stores->placementMapper->findByDashboardId( dashboardId: $dashboard->getId() ); @@ -427,35 +357,71 @@ public function getDashboardForUser( // rights to a view-only recipient. Server-side enforcement already // goes through PermissionService::resolveAccessLevel(); this keeps // the envelope the frontend renders from agreeing with it. - if ($source === Dashboard::SOURCE_SHARED) { - $levels = $this->dashResolver->findSharedLevels( - userId: $userId, - userGroupIds: $this->adminTemplateService->getUserGroupIdsFor( - userId: $userId - ) - ); - if (isset($levels[$dashboard->getId()]) === true) { - return [ - 'dashboard' => $dashboard, - 'placements' => $this->withPersonalLayer( - placements: $placements, - dashboard: $dashboard, - userId: $userId - ), - 'permissionLevel' => $levels[$dashboard->getId()], - ]; - } + $sharedLevel = null; + if ((string)$entry['source'] === Dashboard::SOURCE_SHARED) { + $sharedLevel = $this->sharedPermissionLevel(dashboard: $dashboard, userId: $userId); } - return $this->dashResolver->buildResult( + $layered = $this->withPersonalLayer( + placements: $placements, dashboard: $dashboard, - placements: $this->withPersonalLayer( - placements: $placements, - dashboard: $dashboard, + userId: $userId + ); + + if ($sharedLevel !== null) { + return [ + 'dashboard' => $dashboard, + 'placements' => $layered, + 'permissionLevel' => $sharedLevel, + ]; + } + + return $this->builders->dashResolver->buildResult( + dashboard: $dashboard, + placements: $layered + ); + }//end getDashboardForUser() + + /** + * The first visible entry for the dashboard ID. + * + * @param array $visible The user's visible set. + * @param int $dashboardId The dashboard ID. + * + * @return array{dashboard: Dashboard, source: string}|null + */ + private function findVisibleEntryById(array $visible, int $dashboardId): ?array { + foreach ($visible as $entry) { + if ($entry['dashboard']->getId() === $dashboardId) { + return $entry; + } + } + + return null; + }//end findVisibleEntryById() + + /** + * The permission level a share grants the user on the dashboard, or NULL when none does. + * + * @param Dashboard $dashboard The shared dashboard. + * @param string $userId The recipient. + * + * @return string|null + */ + private function sharedPermissionLevel(Dashboard $dashboard, string $userId): ?string { + $levels = $this->builders->dashResolver->findSharedLevels( + userId: $userId, + userGroupIds: $this->builders->adminTemplateService->getUserGroupIdsFor( userId: $userId ) ); - }//end getDashboardForUser() + + if (isset($levels[$dashboard->getId()]) === true) { + return $levels[$dashboard->getId()]; + } + + return null; + }//end sharedPermissionLevel() /** * Lay the caller's own arrangement over a dashboard somebody else owns. @@ -476,7 +442,7 @@ public function getDashboardForUser( * * @return array The placements the caller sees. * - * @spec openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md */ private function withPersonalLayer( array $placements, @@ -487,7 +453,7 @@ private function withPersonalLayer( return $placements; } - return $this->personalLayers->applyTo( + return $this->structure->personalLayers->applyTo( placements: $placements, userId: $userId, dashboardId: (int)$dashboard->getId() @@ -509,7 +475,7 @@ private function withPersonalLayer( * @return array|null The effective dashboard data or null. * * @spec openspec/specs/dashboards/spec.md - * @spec openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md */ public function getEffectiveDashboard(string $userId): ?array { $result = $this->resolveEffectiveDashboard(userId: $userId); @@ -536,82 +502,181 @@ public function getEffectiveDashboard(string $userId): ?array { * @spec openspec/specs/dashboards/spec.md */ private function resolveEffectiveDashboard(string $userId): ?array { - // Steps 0-1 — resolve the explicit default-dashboard pin (wave3.7), - // then the auto-overwriting last-used preference (REQ-DASH-019), - // both against the user's full visible set. This honours a - // group/default (showcase) dashboard whose `user_id` is NULL — - // not just personal `is_active` rows — so the API-driven view - // matches the server-rendered landing URL, which - // resolveActiveDashboard() resolves the same way. A stale pref - // (UUID no longer visible) falls through to the legacy chain. + $result = $this->resolvePreferredEffectiveDashboard(userId: $userId); + if ($result !== null) { + return $result; + } + + $result = $this->resolveOwnedEffectiveDashboard(userId: $userId); + if ($result !== null) { + return $result; + } + + $result = $this->resolveRoleLayoutOrDefaultGroupDashboard(userId: $userId); + if ($result !== null) { + return $result; + } + + return $this->resolveSharedOrTemplateDashboard(userId: $userId); + }//end resolveEffectiveDashboard() + + /** + * Steps 0-1 of {@see self::resolveEffectiveDashboard()}: the pinned + * default, then the last-used preference. + * + * Both resolve against the user's full visible set. This honours a + * group/default (showcase) dashboard whose `user_id` is NULL — not + * just personal `is_active` rows — so the API-driven view matches the + * server-rendered landing URL, which resolveActiveDashboard() resolves + * the same way. A stale pref (UUID no longer visible) falls through to + * the legacy chain. + * + * @param string $userId The user ID. + * + * @return array|null The built result, or null when neither preference is visible. + * + * @spec openspec/specs/dashboards/spec.md + */ + private function resolvePreferredEffectiveDashboard(string $userId): array|null { $defaultUuid = $this->getDefaultPreference(userId: $userId); - $activeUuid = (string)$this->config->getUserValue( + $activeUuid = $this->getLastUsedPreference(userId: $userId); + if ($defaultUuid === '' && $activeUuid === '') { + return null; + } + + $visible = $this->getVisibleToUser(userId: $userId); + // Default pin wins over last-used — same precedence as + // resolveActiveDashboard() steps 0 then 1. + foreach ([$defaultUuid, $activeUuid] as $prefUuid) { + $entry = $this->findVisibleByUuid(visible: $visible, uuid: $prefUuid); + if ($entry !== null) { + return $this->preferredResult(entry: $entry, userId: $userId); + } + } + + return null; + }//end resolvePreferredEffectiveDashboard() + + /** + * The auto-overwriting last-used dashboard preference (REQ-DASH-019). + * + * @param string $userId The user ID. + * + * @return string The stored UUID, or '' when unset. + */ + private function getLastUsedPreference(string $userId): string { + return (string)$this->platform->config->getUserValue( userId: $userId, appName: Application::APP_ID, key: self::ACTIVE_DASHBOARD_UUID_PREF_KEY, default: '' ); - if ($defaultUuid !== '' || $activeUuid !== '') { - $visible = $this->getVisibleToUser(userId: $userId); - // Default pin wins over last-used — same precedence as - // resolveActiveDashboard() steps 0 then 1. - foreach ([$defaultUuid, $activeUuid] as $prefUuid) { - if ($prefUuid === '') { - continue; - } + }//end getLastUsedPreference() - foreach ($visible as $entry) { - $candidate = $entry['dashboard']; - if ((string)$candidate->getUuid() === $prefUuid) { - $placements = $this->placementMapper->findByDashboardId( - dashboardId: $candidate->getId() - ); - return $this->dashResolver->buildResult( - dashboard: $candidate, - placements: $placements - ); - } - } + /** + * The visible entry with this UUID; null for an empty UUID or no match. + * + * @param array $visible The user's visible set. + * @param string $uuid The preferred UUID. + * + * @return array{dashboard: Dashboard, source: string}|null The first match. + */ + private function findVisibleByUuid(array $visible, string $uuid): ?array { + if ($uuid === '') { + return null; + } + + foreach ($visible as $entry) { + if ((string)$entry['dashboard']->getUuid() === $uuid) { + return $entry; } - }//end if + } - $result = $this->dashResolver->tryGetActiveDashboard( - userId: $userId - ); - if ($result !== null) { - return $result; + return null; + }//end findVisibleByUuid() + + /** + * The result for a preferred dashboard. One reached through a share + * reports the SHARE's level (REQ-SHARE-004), not the owner's row level, + * which would tell a view-only recipient they may edit. + * + * @param array{dashboard: Dashboard, source: string} $entry The visible entry. + * @param string $userId The user ID. + * + * @return array The built result. + */ + private function preferredResult(array $entry, string $userId): array { + $result = $this->buildResultWithPlacements(dashboard: $entry['dashboard']); + if ((string)$entry['source'] === Dashboard::SOURCE_SHARED) { + $result['permissionLevel'] = ($this->sharedPermissionLevel(dashboard: $entry['dashboard'], userId: $userId) ?? $result['permissionLevel']); } - $result = $this->dashResolver->tryActivateExistingDashboard( - userId: $userId + return $result; + }//end preferredResult() + + /** + * The resolver result for a dashboard with its placements loaded. + * + * @param Dashboard $dashboard The resolved dashboard. + * + * @return array The built result. + */ + private function buildResultWithPlacements(Dashboard $dashboard): array { + $placements = $this->stores->placementMapper->findByDashboardId( + dashboardId: $dashboard->getId() ); - if ($result !== null) { - return $result; - } + return $this->builders->dashResolver->buildResult( + dashboard: $dashboard, + placements: $placements + ); + }//end buildResultWithPlacements() - $result = $this->resolveRoleLayoutOrDefaultGroupDashboard(userId: $userId); + /** + * The user's legacy `is_active` personal dashboard, else the first + * existing one, activated. + * + * @param string $userId The user ID. + * + * @return array|null The result, or null when the user owns none. + */ + private function resolveOwnedEffectiveDashboard(string $userId): ?array { + $result = $this->builders->dashResolver->tryGetActiveDashboard( + userId: $userId + ); if ($result !== null) { return $result; } - // REQ-SHARE-002: a dashboard someone deliberately shared with this - // user beats auto-provisioning a brand-new one from a template. - // Placed AFTER both owned-dashboard steps (same precedence as - // resolveActiveDashboard step 6b) and BEFORE the template step - // because tryCreateFromTemplate WRITES — it would otherwise mint an - // empty personal dashboard and permanently bury the share. - $result = $this->dashResolver->tryGetSharedDashboard( - userId: $userId, - userGroupIds: $this->adminTemplateService->getUserGroupIdsFor( - userId: $userId - ) + return $this->builders->dashResolver->tryActivateExistingDashboard( + userId: $userId ); - if ($result !== null) { - return $result; + }//end resolveOwnedEffectiveDashboard() + + /** + * A dashboard shared with the user, else a new one from a template. + * + * REQ-SHARE-002: a dashboard someone deliberately shared with this + * user beats auto-provisioning a brand-new one from a template. + * Placed AFTER both owned-dashboard steps (same precedence as + * resolveActiveDashboard step 6b) and BEFORE the template step + * because tryCreateFromTemplate WRITES — it would otherwise mint an + * empty personal dashboard and permanently bury the share. + * + * @param string $userId The user ID. + * + * @return array|null The result. + */ + private function resolveSharedOrTemplateDashboard(string $userId): ?array { + // Taken from the visible set so a share obeys the same publication + // filter here as in `/api/dashboards/visible` (REQ-DASH-036). + foreach ($this->getVisibleToUser(userId: $userId) as $entry) { + if ((string)$entry['source'] === Dashboard::SOURCE_SHARED) { + return $this->preferredResult(entry: $entry, userId: $userId); + } } return $this->tryCreateFromTemplate(userId: $userId); - }//end resolveEffectiveDashboard() + }//end resolveSharedOrTemplateDashboard() /** * The user's role layout when their groups carry one, else the instance default. @@ -626,6 +691,15 @@ private function resolveEffectiveDashboard(string $userId): ?array { * @spec openspec/specs/role-feature-permissions/spec.md#req-rfp-002-role-based-default-dashboard-layout */ private function resolveRoleLayoutOrDefaultGroupDashboard(string $userId): ?array { + // REQ-TMPL-019: a member who owns nothing yet gets the template meant + // for them, ahead of the dashboard everyone shares. Whoever owns a + // personal dashboard left the chain two steps earlier. The page shell + // takes the same rung at the same place (resolveTemplateOrGroupShared). + $fromTemplate = $this->resolveTemplateRung(userId: $userId); + if ($fromTemplate !== null) { + return $this->describeTemplateRung(rung: $fromTemplate); + } + // 🔴 ROLE DEFAULTS MUST BEAT THE INSTANCE-WIDE DEFAULT DASHBOARD. // REQ-RFP-002 says a new user is seeded from their group's // RoleLayoutDefault rows. Since #361 seeds one `default` @@ -641,7 +715,7 @@ private function resolveRoleLayoutOrDefaultGroupDashboard(string $userId): ?arra // `tryCreateFromTemplate()` still answers null when personal // dashboards are switched off, which falls through to the old // behaviour. - if ($this->roleFeaturePerm?->hasRoleLayoutDefaultsFor(userId: $userId) === true) { + if ($this->limits->roleFeaturePerm?->hasRoleLayoutDefaultsFor(userId: $userId) === true) { $result = $this->tryCreateFromTemplate(userId: $userId); if ($result !== null) { return $result; @@ -687,9 +761,9 @@ private function resolveDefaultGroupDashboard(string $userId): ?array { return null; } - return $this->dashResolver->buildResult( + return $this->builders->dashResolver->buildResult( dashboard: $groupShared['dashboard'], - placements: $this->placementMapper->findByDashboardId( + placements: $this->stores->placementMapper->findByDashboardId( dashboardId: $groupShared['dashboard']->getId() ) ); @@ -707,130 +781,252 @@ private function resolveDefaultGroupDashboard(string $userId): ?array { * * @param string $userId The user ID. * @param string $name The dashboard name. - * @param string|null $description The dashboard description. - * @param string|null $icon Opaque icon identifier (registry - * key or URL); see the - * `dashboard-icons` capability. - * @param string|null $parentUuid Optional parent dashboard UUID - * (REQ-DASH-023). NULL ⇒ root. - * @param string|null $slug Optional caller-supplied slug - * (REQ-DASH-024). NULL ⇒ - * derive from the name. - * @param int $sortOrder Optional sibling sort order - * (REQ-DASH-029). Defaults to - * 0. - * @param bool $seedDefaults Whether to seed the default - * widget bundle (Conduction + - * Sendent + Nextcloud tiles + - * a Files widget) on the new - * dashboard. The controller - * path (`POST - * /api/dashboard`) opts in; - * the bootstrap path keeps it - * off to avoid double-seeding - * when role defaults already - * apply. + * @param array $options Optional fields: `description` (null); + * `icon`, an opaque icon identifier (registry key + * or URL, see the `dashboard-icons` capability; + * null or '' ⇒ default glyph); `parentUuid` (null + * ⇒ root, REQ-DASH-023); `slug` (null ⇒ derived + * from the name, REQ-DASH-024); `sortOrder` (0, + * REQ-DASH-029); `seedDefaults` (false), whether + * to seed the default widget bundle (Conduction + + * Sendent + Nextcloud tiles + a Files widget). + * The controller path (`POST /api/dashboard`) + * opts in; the bootstrap path keeps it off to + * avoid double-seeding when role defaults apply. * * @return Dashboard The created dashboard. * * @spec openspec/specs/dashboards/spec.md */ - public function createDashboard( - string $userId, - string $name, - ?string $description = null, - ?string $icon = null, - ?string $parentUuid = null, - ?string $slug = null, - int $sortOrder = 0, - bool $seedDefaults = false, - ): Dashboard { - // Task-7 of dashboard-public-share — public-share bearer cannot mutate. - $this->publicShareContext?->requireMutable(); - // Dashboard-quota-limits REQ-QUOTA-002: enforce the per-user - // dashboard quota at the single creation choke point so every - // user-initiated surface (REST create, CLI, template - // instantiation) is bound. Admin provisioning paths wrap their - // calls in QuotaService::runProvisioning() to bypass this - // (REQ-QUOTA-004). Runs before any DB write. - $this->quotaService?->assertCanCreateDashboard(userId: $userId); - // REQ-DASH-023, REQ-DASH-028: parent existence + cycle + - // depth checks BEFORE the entity is built so the request is - // rejected without a partial row in memory. - $this->treeService->validateParent( - movingUuid: null, - newParentUuid: $parentUuid - ); + public function createDashboard(string $userId, string $name, array $options=[]): Dashboard { + $options += self::CREATE_DEFAULTS; + $this->assertMayCreate(userId: $userId, parentUuid: $options['parentUuid']); + $options['gridColumns'] ??= $this->defaultGridColumns(); - $dashboard = $this->dashboardFactory->create( + $dashboard = $this->builders->dashboardFactory->create( userId: $userId, name: $name, - description: $description, - parentUuid: $parentUuid, - slug: $slug, - sortOrder: $sortOrder + options: self::factoryOptions(options: $options) + ); + $this->applyNewIcon(dashboard: $dashboard, icon: $options['icon']); + $this->assertNewSlugUnique(dashboard: $dashboard, options: $options); + + $this->stores->dashboardMapper->deactivateAllForUser(userId: $userId); + + $persisted = $this->stores->dashboardMapper->insert(entity: $dashboard); + $this->completeNewDashboard(persisted: $persisted, options: $options); + + return $persisted; + }//end createDashboard() + + /** + * The checks every dashboard creation passes first, before any DB + * write or entity is built. + * + * Task-7 of dashboard-public-share — public-share bearer cannot mutate. + * Dashboard-quota-limits REQ-QUOTA-002: enforce the per-user + * dashboard quota at the single creation choke point so every + * user-initiated surface (REST create, CLI, template + * instantiation) is bound. Admin provisioning paths wrap their + * calls in QuotaService::runProvisioning() to bypass this + * (REQ-QUOTA-004). REQ-DASH-023, REQ-DASH-028: parent existence + + * cycle + depth checks BEFORE the entity is built so the request is + * rejected without a partial row in memory. + * + * @param string $userId The user ID. + * @param string|null $parentUuid The requested parent, or null for a root. + * + * @return void + */ + private function assertMayCreate(string $userId, ?string $parentUuid): void { + $this->limits->publicShareContext?->requireMutable(); + $this->limits->quotaService?->assertCanCreateDashboard(userId: $userId); + $this->structure->treeService->validateParent( + movingUuid: null, + newParentUuid: $parentUuid ); + }//end assertMayCreate() + + /** + * The options the dashboard factory takes from the create options. + * + * @param array $options The create options with defaults. + * + * @return array The factory options. + */ + private static function factoryOptions(array $options): array { + return [ + 'description' => $options['description'], + 'parentUuid' => $options['parentUuid'], + 'slug' => $options['slug'], + 'sortOrder' => $options['sortOrder'], + 'gridColumns' => $options['gridColumns'], + ]; + }//end factoryOptions() + + /** + * The grid columns a new dashboard gets when the create names none: the + * administrator's default (REQ-ASET-006), 12 when it is unset or not one + * of the offered counts. + * + * @return int The column count. + * + * @spec openspec/specs/admin-settings/spec.md + */ + private function defaultGridColumns(): int { + $value = $this->stores->settingMapper->getValue(key: AdminSetting::KEY_DEFAULT_GRID_COLUMNS, default: 12); + if (is_numeric($value) === true && in_array((int)$value, [6, 8, 12], true) === true) { + return (int)$value; + } - // Icon is an opaque string (registry key or URL) — see the - // `dashboard-icons` capability. NULL/empty means "use the - // frontend default glyph". + return 12; + }//end defaultGridColumns() + + /** + * Set a new dashboard's icon when one was given. + * + * Icon is an opaque string (registry key or URL) — see the + * `dashboard-icons` capability. NULL/empty means "use the + * frontend default glyph". + * + * @param Dashboard $dashboard The new dashboard. + * @param string|null $icon The requested icon. + * + * @return void + */ + private function applyNewIcon(Dashboard $dashboard, ?string $icon): void { if ($icon !== null && $icon !== '') { // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters $dashboard->setIcon($icon); } + }//end applyNewIcon() - // REQ-DASH-024: slug uniqueness within parent scope. The - // factory may have emitted NULL when the name yields no legal - // characters and the caller did not supply an explicit slug — - // skip the unique check in that case (NULL slugs are simply - // unaddressable by path). + /** + * REQ-DASH-024: slug uniqueness within parent scope. The + * factory may have emitted NULL when the name yields no legal + * characters and the caller did not supply an explicit slug — + * skip the unique check in that case (NULL slugs are simply + * unaddressable by path). + * + * Root slugs share one namespace across users, so a slug derived from + * the name of a new root dashboard is first moved off one that any + * root dashboard holds. + * + * @param Dashboard $dashboard The new dashboard. + * @param array $options The create options: parentUuid, slug. + * + * @return void + */ + private function assertNewSlugUnique(Dashboard $dashboard, array $options): void { $resolvedSlug = $dashboard->getSlug(); - if ($resolvedSlug !== null && $resolvedSlug !== '') { - $this->treeService->validateSlugUnique( - parentUuid: $parentUuid, - slug: $resolvedSlug - ); + if ($resolvedSlug === null || $resolvedSlug === '') { + return; } - $this->dashboardMapper->deactivateAllForUser(userId: $userId); + if ($options['slug'] === null && $options['parentUuid'] === null) { + $resolvedSlug = $this->freeRootSlug(slug: $resolvedSlug); + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $dashboard->setSlug($resolvedSlug); + } - $persisted = $this->dashboardMapper->insert(entity: $dashboard); + $this->structure->treeService->validateSlugUnique( + parentUuid: $options['parentUuid'], + slug: $resolvedSlug + ); + }//end assertNewSlugUnique() - // REQ-DASH-038, REQ-DASH-044: every newly created dashboard gets - // a primary translation row in the owner's Nextcloud locale (or - // the default fallback when no preference is set). The seed is - // best-effort — failure here does not abort dashboard creation, - // because the legacy materialiser keeps reads working until the - // seed retries via a subsequent translation API call. - if ($this->translationService !== null) { - try { - $this->translationService->seedPrimaryFor( - dashboard: $persisted - ); - } catch (Throwable $t) { - $this->logger->warning( - message: 'launchpad: failed to seed primary translation: {message}', - context: ['message' => $t->getMessage()] - ); + /** + * The first of `slug`, `slug-2`, `slug-3`… that no root dashboard + * holds, the owner's own included: names need not be unique, so a + * second "Work" gets `work-2` (REQ-DASH-007). + * + * @param string $slug The slug derived from the name. + * + * @return string The slug to store. + */ + private function freeRootSlug(string $slug): string { + $base = substr(string: $slug, offset: 0, length: 120); + for ($number = 1; $number <= 100; $number++) { + $candidate = $slug; + if ($number > 1) { + $candidate = $base . '-' . $number; + } + + $holder = $this->stores->dashboardMapper->findChildBySlug(parentUuid: null, slug: $candidate); + if ($holder === null) { + return $candidate; } } - // User-initiated dashboards (the "+" affordance in the sidebar) - // arrive here with $seedDefaults=true and are bootstrapped with - // the standard tile + files bundle. The bootstrap path - // (tryCreateFromTemplate) keeps $seedDefaults=false because it - // runs its own role-default-driven seed afterwards and would - // otherwise double-seed. - if ($seedDefaults === true) { - $this->seedDefaultWidgets(dashboardId: $persisted->getId()); + return $base . '-' . bin2hex(random_bytes(4)); + }//end freeRootSlug() + + /** + * Seed a stored dashboard's primary translation and, when asked, its + * default widgets. + * + * User-initiated dashboards (the "+" affordance in the sidebar) + * arrive here with $seedDefaults=true and are bootstrapped with + * the standard tile + files bundle. The bootstrap path + * (tryCreateFromTemplate) keeps $seedDefaults=false because it + * runs its own role-default-driven seed afterwards and would + * otherwise double-seed. + * + * @param Dashboard $persisted The stored dashboard. + * @param array $options The create options with defaults. + * + * @return void + */ + private function completeNewDashboard(Dashboard $persisted, array $options): void { + $this->seedPrimaryTranslation(dashboard: $persisted); + + if ($options['seedDefaults'] === true) { + $this->seedDefaultWidgets( + dashboardId: $persisted->getId(), + seedSet: (string)$options['seedSet'], + menuAppIds: array_values(array_filter((array)$options['menuAppIds'], 'is_string')) + ); } + }//end completeNewDashboard() - return $persisted; - }//end createDashboard() + /** + * REQ-DASH-038, REQ-DASH-044: every newly created dashboard gets + * a primary translation row in the owner's Nextcloud locale (or + * the default fallback when no preference is set). The seed is + * best-effort — failure here does not abort dashboard creation, + * because the legacy materialiser keeps reads working until the + * seed retries via a subsequent translation API call. + * + * @param Dashboard $dashboard The stored dashboard. + * + * @return void + */ + private function seedPrimaryTranslation(Dashboard $dashboard): void { + if ($this->structure->translationService === null) { + return; + } + + try { + $this->structure->translationService->seedPrimaryFor( + dashboard: $dashboard + ); + } catch (Throwable $t) { + $this->outlets->logger->warning( + message: 'launchpad: failed to seed primary translation: {message}', + context: ['message' => $t->getMessage()] + ); + } + }//end seedPrimaryTranslation() /** * Update a dashboard. * + * The caller authorises the update first: the layout and look through + * PermissionService::canEditDashboard(), the name and other metadata + * through PermissionService::canEditDashboardMetadata(). That lets a + * LaunchPad admin or a group's editor save a dashboard they do not own + * (REQ-ROLE-001, REQ-ROLE-002). + * * @param int $dashboardId The dashboard ID. * @param string $userId The user ID. * @param array $data The data to update. @@ -845,11 +1041,12 @@ public function updateDashboard( array $data, ): Dashboard { // Task-7 of dashboard-public-share — public-share bearer cannot mutate. - $this->publicShareContext?->requireMutable(); - $dashboard = $this->dashboardMapper->find(id: $dashboardId); + $this->limits->publicShareContext?->requireMutable(); + $dashboard = $this->stores->dashboardMapper->find(id: $dashboardId); - if ($dashboard->getUserId() !== $userId) { - throw new Exception(message: 'Access denied'); + // REQ-THM-003: only administrators set custom CSS. + if (array_key_exists('customCss', $data) === true && $this->isAdmin(userId: $userId) === false) { + throw new ForbiddenException(message: 'Access denied'); } $this->applyDashboardUpdates( @@ -857,9 +1054,9 @@ public function updateDashboard( data: $data ); - $saved = $this->dashboardMapper->update(entity: $dashboard); + $saved = $this->stores->dashboardMapper->update(entity: $dashboard); // Shared dashboards announce a save, at most once a day (#713). - $this->activity?->updated(dashboard: $saved, actor: $userId); + $this->outlets->activity?->updated(dashboard: $saved, actor: $userId); return $saved; }//end updateDashboard() @@ -888,11 +1085,11 @@ public function deleteDashboard( bool $cascade = false, ): void { // Task-7 of dashboard-public-share — public-share bearer cannot mutate. - $this->publicShareContext?->requireMutable(); - $dashboard = $this->dashboardMapper->find(id: $dashboardId); + $this->limits->publicShareContext?->requireMutable(); + $dashboard = $this->stores->dashboardMapper->find(id: $dashboardId); if ($dashboard->getUserId() !== $userId) { - throw new Exception(message: 'Access denied'); + throw new ForbiddenException(message: 'Access denied'); } $uuid = (string)$dashboard->getUuid(); @@ -933,7 +1130,7 @@ private function assertNoChildrenUnlessCascading(string $uuid, bool $cascade): v return; } - $childCount = $this->dashboardMapper->countChildrenByParent( + $childCount = $this->stores->dashboardMapper->countChildrenByParent( parentUuid: $uuid ); if ($childCount > 0) { @@ -968,34 +1165,48 @@ private function deleteLeafWithChildRows( string $uuid, string $fallbackOwnerId, ): void { + $this->deleteChildRows(dashboardId: $dashboardId, uuid: $uuid); + + $this->stores->dashboardMapper->delete(entity: $dashboard); + + $this->dispatchDashboardDeleted( + dashboard: $dashboard, + uuid: $uuid, + fallbackOwnerId: $fallbackOwnerId + ); + }//end deleteLeafWithChildRows() + + /** + * Delete the child rows this service owns for one dashboard: its + * translation variants (REQ-DASH-044), placements and editing lock + * (REQ-LOCK-008). + * + * @param int $dashboardId The dashboard's numeric ID. + * @param string $uuid Its UUID (may be empty). + * + * @return void + */ + private function deleteChildRows(int $dashboardId, string $uuid): void { // REQ-DASH-044: cascade-delete translation variants for the // dashboard about to disappear so they don't outlive the parent. - if ($uuid !== '' && $this->translationService !== null) { - $this->translationService->deleteAllForDashboard( + if ($uuid !== '' && $this->structure->translationService !== null) { + $this->structure->translationService->deleteAllForDashboard( dashboardUuid: $uuid ); } - $this->placementMapper->deleteByDashboardId( + $this->stores->placementMapper->deleteByDashboardId( dashboardId: $dashboardId ); // Cascade-clear the editing lock so a deleted dashboard never // leaves an orphaned lock row behind (REQ-LOCK-008). - if ($this->lockMapper !== null && $uuid !== '') { - $this->lockMapper->deleteByDashboardUuid( + if ($this->stores->lockMapper !== null && $uuid !== '') { + $this->stores->lockMapper->deleteByDashboardUuid( dashboardUuid: $uuid ); } - - $this->dashboardMapper->delete(entity: $dashboard); - - $this->dispatchDashboardDeleted( - dashboard: $dashboard, - uuid: $uuid, - fallbackOwnerId: $fallbackOwnerId - ); - }//end deleteLeafWithChildRows() + }//end deleteChildRows() /** * Delete a dashboard's whole subtree, clearing the child rows the @@ -1017,31 +1228,31 @@ private function deleteLeafWithChildRows( * @spec openspec/specs/dashboards/spec.md */ private function deleteSubtreeWithChildRows(Dashboard $dashboard, string $uuid): void { - if ($this->translationService !== null) { - $descendants = $this->dashboardMapper->findDescendants( + if ($this->structure->translationService !== null) { + $descendants = $this->stores->dashboardMapper->findDescendants( ancestorUuid: $uuid ); foreach ($descendants as $descendant) { $descendantUuid = (string)$descendant->getUuid(); if ($descendantUuid !== '') { - $this->translationService->deleteAllForDashboard( + $this->structure->translationService->deleteAllForDashboard( dashboardUuid: $descendantUuid ); } } - $this->translationService->deleteAllForDashboard( + $this->structure->translationService->deleteAllForDashboard( dashboardUuid: $uuid ); } - if ($this->lockMapper !== null) { - $this->lockMapper->deleteByDashboardUuid( + if ($this->stores->lockMapper !== null) { + $this->stores->lockMapper->deleteByDashboardUuid( dashboardUuid: $uuid ); } - $this->treeService->deleteSubtree(dashboard: $dashboard); + $this->structure->treeService->deleteSubtree(dashboard: $dashboard); }//end deleteSubtreeWithChildRows() /** @@ -1067,7 +1278,7 @@ private function dispatchDashboardDeleted( string $uuid, string $fallbackOwnerId, ): void { - if ($this->eventDispatcher === null || $uuid === '') { + if ($this->outlets->eventDispatcher === null || $uuid === '') { return; } @@ -1077,7 +1288,7 @@ private function dispatchDashboardDeleted( $resolvedOwnerId = $ownerId; } - $this->eventDispatcher->dispatchTyped( + $this->outlets->eventDispatcher->dispatchTyped( new DashboardDeletedEvent( dashboardUuid: $uuid, ownerUserId: $resolvedOwnerId, @@ -1094,21 +1305,33 @@ private function dispatchDashboardDeleted( * @param int $dashboardId The dashboard ID. * @param string $userId The user ID. * + * A recipient of a share gets the dashboard back unchanged: the active + * flag lives on the owner's row, so nothing is written (REQ-SHARE-005). + * * @return Dashboard The activated dashboard. * * @spec openspec/specs/dashboards/spec.md + * @spec openspec/specs/dashboard-sharing/spec.md#requirement-owner-only-metadata-and-lifecycle-operations-req-share-005 */ public function activateDashboard( int $dashboardId, string $userId, ): Dashboard { - $dashboard = $this->dashboardMapper->find(id: $dashboardId); + $dashboard = $this->stores->dashboardMapper->find(id: $dashboardId); if ($dashboard->getUserId() !== $userId) { - throw new Exception(message: 'Access denied'); + $entry = $this->findVisibleEntryById( + visible: $this->getVisibleToUser(userId: $userId), + dashboardId: $dashboardId + ); + if ($entry !== null && (string)$entry['source'] === Dashboard::SOURCE_SHARED) { + return $dashboard; + } + + throw new ForbiddenException(message: 'Access denied'); } - $this->dashboardMapper->setActive( + $this->stores->dashboardMapper->setActive( $dashboardId, userId: $userId ); @@ -1133,9 +1356,31 @@ public function activateDashboard( * @spec openspec/specs/dashboards/spec.md */ public function findByUuid(string $uuid): Dashboard { - return $this->dashboardMapper->findByUuid(uuid: $uuid); + return $this->stores->dashboardMapper->findByUuid(uuid: $uuid); }//end findByUuid() + /** + * Whether a dashboard with this id exists, whoever owns it. + * + * Lets a read tell a dashboard the caller may not see (403) from one + * that does not exist (404), without handing the entity out. + * + * @param int $dashboardId The dashboard ID. + * + * @return bool True when the row exists. + * + * @spec openspec/specs/dashboard-sharing/spec.md + */ + public function dashboardExists(int $dashboardId): bool { + try { + $this->stores->dashboardMapper->find(id: $dashboardId); + } catch (DoesNotExistException) { + return false; + } + + return true; + }//end dashboardExists() + /** * List the group-shared dashboards in a single group. * @@ -1148,7 +1393,7 @@ public function findByUuid(string $uuid): Dashboard { * @spec openspec/specs/dashboards/spec.md */ public function listGroupDashboards(string $groupId): array { - return $this->dashboardMapper->findByGroup(groupId: $groupId); + return $this->stores->dashboardMapper->findByGroup(groupId: $groupId); }//end listGroupDashboards() /** @@ -1174,7 +1419,7 @@ public function findGroupDashboard( string $groupId, string $uuid, ): Dashboard { - $dashboard = $this->dashboardMapper->findByUuid(uuid: $uuid); + $dashboard = $this->stores->dashboardMapper->findByUuid(uuid: $uuid); if ($dashboard->getType() !== Dashboard::TYPE_GROUP_SHARED) { throw new DoesNotExistException( @@ -1194,41 +1439,39 @@ public function findGroupDashboard( /** * Create a new group-shared dashboard. * - * Admin-only — caller MUST have validated the actor with - * {@see DashboardService::isAdmin()}. The route attribute alone is - * not enough (per Hydra semantic-auth gate). + * For a Nextcloud administrator, a LaunchPad Admin, or an Editor in that + * group ({@see GroupDashboardCreation::allows()}, + * REQ-DASH-014). Checked here as well as by the caller. * * @param string $actorUserId The acting user ID (for the admin * check). * @param string $groupId The group ID. - * @param string $name The dashboard name. - * @param string|null $description The dashboard description. - * @param int $gridColumns The grid column count. + * @param array $fields The dashboard `name`, and optional `description` + * (null) and `gridColumns` (12). * * @return Dashboard The created group-shared dashboard. * - * @throws Exception When the actor is not an administrator. + * @throws Exception When the actor may not create a dashboard for the group. * * @spec openspec/specs/dashboards/spec.md */ - public function createGroupShared( - string $actorUserId, - string $groupId, - string $name, - ?string $description = null, - int $gridColumns = 12, - ): Dashboard { - if ($this->isAdmin(userId: $actorUserId) === false) { + public function createGroupShared(string $actorUserId, string $groupId, array $fields): Dashboard { + $fields += ['description' => null, 'gridColumns' => 12]; + if ($this->isAdmin(userId: $actorUserId) === false + && $this->platform->groupCreation?->allows(userId: $actorUserId, groupId: $groupId) !== true + ) { throw new Exception(message: self::ERR_FORBIDDEN_NOT_ADMIN); } - $dashboard = $this->dashboardFactory->create( + $dashboard = $this->builders->dashboardFactory->create( userId: null, - name: $name, - description: $description, - type: Dashboard::TYPE_GROUP_SHARED, - groupId: $groupId, - gridColumns: $gridColumns + name: $fields['name'], + options: [ + 'description' => $fields['description'], + 'type' => Dashboard::TYPE_GROUP_SHARED, + 'groupId' => $groupId, + 'gridColumns' => $fields['gridColumns'], + ] ); $dashboard->setPermissionLevel(Dashboard::PERMISSION_VIEW_ONLY); // REQ-DASH-016: new group-shared rows always start non-default. @@ -1236,7 +1479,10 @@ public function createGroupShared( // POST /api/dashboards/group/{groupId}/default endpoint. $dashboard->setIsDefault(0); - return $this->dashboardMapper->insert(entity: $dashboard); + $persisted = $this->stores->dashboardMapper->insert(entity: $dashboard); + $this->announceAudience(dashboard: $persisted); + + return $persisted; }//end createGroupShared() /** @@ -1286,9 +1532,9 @@ public function updateGroupShared( data: $patch ); - $saved = $this->dashboardMapper->update(entity: $dashboard); + $saved = $this->stores->dashboardMapper->update(entity: $dashboard); // The group hears about a save, at most once a day (#713). - $this->activity?->updated(dashboard: $saved, actor: $actorUserId); + $this->outlets->activity?->updated(dashboard: $saved, actor: $actorUserId); return $saved; }//end updateGroupShared() @@ -1318,34 +1564,83 @@ public function deleteGroupShared( string $groupId, string $uuid, ): void { - if ($this->isAdmin(userId: $actorUserId) === false) { - throw new Exception(message: self::ERR_FORBIDDEN_NOT_ADMIN); - } + $this->assertAdmin(userId: $actorUserId); $dashboard = $this->findGroupDashboard( groupId: $groupId, uuid: $uuid ); - if ($groupId !== Dashboard::DEFAULT_GROUP_ID) { - $count = $this->dashboardMapper->countByGroup( - groupId: $groupId - ); - if ($count <= 1) { - throw new Exception(message: self::ERR_LAST_IN_GROUP); - } + $this->assertNotLastInGroup(groupId: $groupId); + $this->deleteWithPlacements(dashboard: $dashboard); + $this->dispatchGroupSharedDeleted(dashboard: $dashboard, actorUserId: $actorUserId); + }//end deleteGroupShared() + + /** + * Refuse an admin-only mutation for a non-admin actor. + * + * @param string $userId The acting user ID. + * + * @return void + * + * @throws Exception When the actor is not an admin. + */ + private function assertAdmin(string $userId): void { + if ($this->isAdmin(userId: $userId) === false) { + throw new Exception(message: self::ERR_FORBIDDEN_NOT_ADMIN); + } + }//end assertAdmin() + + /** + * Refuse removing the only group-shared dashboard of a group; the + * `default` group is exempt (REQ-DASH-014). + * + * @param string $groupId The group ID. + * + * @return void + * + * @throws Exception When the group has one dashboard or fewer. + */ + private function assertNotLastInGroup(string $groupId): void { + if ($groupId === Dashboard::DEFAULT_GROUP_ID) { + return; } - $this->placementMapper->deleteByDashboardId( + $count = $this->stores->dashboardMapper->countByGroup( + groupId: $groupId + ); + if ($count <= 1) { + throw new Exception(message: self::ERR_LAST_IN_GROUP); + } + }//end assertNotLastInGroup() + + /** + * Delete a dashboard's placements, then the dashboard itself. + * + * @param Dashboard $dashboard The dashboard to delete. + * + * @return void + */ + private function deleteWithPlacements(Dashboard $dashboard): void { + $this->stores->placementMapper->deleteByDashboardId( dashboardId: $dashboard->getId() ); - $this->dashboardMapper->delete(entity: $dashboard); + $this->stores->dashboardMapper->delete(entity: $dashboard); + }//end deleteWithPlacements() - // SB1 fix: dispatch DashboardDeletedEvent for cascade cleanup - // (REQ-CSC-001). Actor is the admin who performed the delete. + /** + * SB1 fix: dispatch DashboardDeletedEvent for cascade cleanup + * (REQ-CSC-001). Actor is the admin who performed the delete. + * + * @param Dashboard $dashboard The deleted group-shared dashboard. + * @param string $actorUserId The admin who deleted it. + * + * @return void + */ + private function dispatchGroupSharedDeleted(Dashboard $dashboard, string $actorUserId): void { $deletedUuid = (string)$dashboard->getUuid(); - if ($this->eventDispatcher !== null && $deletedUuid !== '') { - $this->eventDispatcher->dispatchTyped( + if ($this->outlets->eventDispatcher !== null && $deletedUuid !== '') { + $this->outlets->eventDispatcher->dispatchTyped( new DashboardDeletedEvent( dashboardUuid: $deletedUuid, ownerUserId: $actorUserId, @@ -1355,7 +1650,7 @@ public function deleteGroupShared( ) ); } - }//end deleteGroupShared() + }//end dispatchGroupSharedDeleted() /** * Promote a single group-shared dashboard to the group's default. @@ -1394,9 +1689,26 @@ public function setGroupDefault( throw new Exception(message: self::ERR_FORBIDDEN_NOT_ADMIN); } - $this->db->beginTransaction(); + $this->swapGroupDefault(groupId: $groupId, uuid: $uuid); + }//end setGroupDefault() + + /** + * Make one dashboard the group's default and clear every other default + * of that group, in one transaction (REQ-DASH-015). + * + * @param string $groupId The group ID. + * @param string $uuid The dashboard that becomes the default. + * + * @return void + * + * @throws DoesNotExistException When the dashboard does not belong to + * the group (rolled back). + * @throws Throwable Any other DB error, after rollback. + */ + private function swapGroupDefault(string $groupId, string $uuid): void { + $this->platform->db->beginTransaction(); try { - $affected = $this->dashboardMapper->setGroupDefaultUuid( + $affected = $this->stores->dashboardMapper->setGroupDefaultUuid( groupId: $groupId, uuid: $uuid ); @@ -1406,26 +1718,26 @@ public function setGroupDefault( // back so the existing default in the group is // preserved. REQ-DASH-015 scenario "Default cannot be // set across groups". - $this->db->rollBack(); + $this->platform->db->rollBack(); throw new DoesNotExistException( msg: self::ERR_DEFAULT_TARGET_NOT_IN_GROUP ); } - $this->dashboardMapper->clearGroupDefaults( + $this->stores->dashboardMapper->clearGroupDefaults( groupId: $groupId, exceptUuid: $uuid ); - $this->db->commit(); + $this->platform->db->commit(); } catch (DoesNotExistException $e) { // Already rolled back above — re-throw for the controller. throw $e; } catch (Throwable $t) { - $this->db->rollBack(); + $this->platform->db->rollBack(); throw $t; }//end try - }//end setGroupDefault() + }//end swapGroupDefault() /** * Get all dashboards visible to a user, source-tagged. @@ -1435,6 +1747,7 @@ public function setGroupDefault( * single source of truth for `IGroupManager::getUserGroupIds`) and * wires the result into the mapper's union query. Returns the * deduplicated list with `source` set per row. REQ-DASH-013. + * Due scheduled dashboards are stored as published first. * * @param string $userId The user ID. * @@ -1444,11 +1757,13 @@ public function setGroupDefault( * @spec openspec/specs/dashboards/spec.md */ public function getVisibleToUser(string $userId): array { - $userGroupIds = $this->adminTemplateService->getUserGroupIdsFor( + $this->materialiseScheduledDashboards(); + + $userGroupIds = $this->builders->adminTemplateService->getUserGroupIdsFor( userId: $userId ); - $entries = $this->dashboardMapper->findVisibleToUser( + $entries = $this->stores->dashboardMapper->findVisibleToUser( userId: $userId, userGroupIds: $userGroupIds ); @@ -1466,32 +1781,23 @@ public function getVisibleToUser(string $userId): array { ); // REQ-SHARE-002: dashboards reached through an explicit share row - // are part of "visible to me" too. The mapper's union only covers - // ownership, group_shared membership and the `default` sentinel, so - // without this a share is invisible: the recipient never sees the - // dashboard in the switcher and the resolver can never land on it. - // - // Appended AFTER the publication filter, deliberately. Every - // dashboard DashboardFactory creates starts as `draft` - // (REQ-DASH-031), and the filter hides drafts from non-owners — so - // running shares through it would delete every share again, for the - // ordinary case, and leave the feature exactly as dead as before. - // A share row is the owner's explicit, named grant to this specific - // user; it is the same class of entitlement that already exempts - // the owner and admins from the hide, and it is what - // PermissionService::resolveAccessLevel() already honours. Users - // WITHOUT a share still cannot see a draft. - // - // Deduped by UUID against the filtered set so an owned or - // group-reached row always keeps its stronger source tag. + // are part of "visible to me" too; the mapper's union only covers + // ownership, group_shared membership and the `default` sentinel. + // They pass the same publication filter (REQ-DASH-036): a recipient + // sees a shared dashboard once it is published. Deduped by UUID so an + // owned or group-reached row keeps its stronger source tag. $seenUuids = []; foreach ($filtered as $entry) { $seenUuids[(string)$entry['dashboard']->getUuid()] = true; } - $sharedEntries = $this->dashResolver->findSharedDashboards( - userId: $userId, - userGroupIds: $userGroupIds + $sharedEntries = $this->filterByPublicationState( + entries: $this->builders->dashResolver->findSharedDashboards( + userId: $userId, + userGroupIds: $userGroupIds + ), + actorUserId: $userId, + actorIsAdmin: $isAdmin ); foreach ($sharedEntries as $sharedEntry) { $uuid = (string)$sharedEntry['dashboard']->getUuid(); @@ -1499,49 +1805,76 @@ public function getVisibleToUser(string $userId): array { continue; } - // A due scheduled row still materialises in-memory so the - // recipient sees the same `published` state everyone else does. - $this->materialiseDueSchedule(dashboard: $sharedEntry['dashboard']); - $seenUuids[$uuid] = true; $filtered[] = $sharedEntry; } - return $filtered; + return $this->withoutSetAside(userId: $userId, entries: $filtered); }//end getVisibleToUser() /** - * Surface a due `scheduled` dashboard as `published`, in memory only. - * - * Extracted from {@see self::filterByPublicationState()} so the - * share-reached path (which deliberately bypasses the visibility hide, - * see `getVisibleToUser`) still reports the same publication state as - * every other viewer. No DB write — REQ-DASH-034. + * Drop the organisation-wide dashboards a user has set aside + * ({@see self::HIDDEN_DASHBOARDS_PREF_KEY}). Only `default`-source + * entries are dropped; a malformed preference hides nothing. * - * @param Dashboard $dashboard The dashboard to materialise. + * @param string $userId The user. + * @param array $entries The visible set. * - * @return void + * @return array The visible set without the set-aside rows. * - * @spec openspec/specs/dashboards/spec.md + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md */ - private function materialiseDueSchedule(Dashboard $dashboard): void { - if ($dashboard->getPublicationStatus() !== Dashboard::STATUS_SCHEDULED) { - return; + private function withoutSetAside(string $userId, array $entries): array { + $stored = json_decode( + (string)$this->platform->config->getUserValue( + userId: $userId, + appName: Application::APP_ID, + key: self::HIDDEN_DASHBOARDS_PREF_KEY, + default: '' + ), + true + ); + if (is_array($stored) === false || $stored === []) { + return $entries; } + $hidden = array_fill_keys(keys: array_filter(array: $stored, callback: 'is_string'), value: true); + $kept = []; + foreach ($entries as $entry) { + if ($entry['source'] === Dashboard::SOURCE_DEFAULT + && isset($hidden[(string)$entry['dashboard']->getUuid()]) === true + ) { + continue; + } + + $kept[] = $entry; + } + + return $kept; + }//end withoutSetAside() + + /** + * Whether a dashboard's `publishAt` has passed. A missing or + * malformed timestamp is never due (the row stays scheduled). + * + * @param Dashboard $dashboard The dashboard. + * @param DateTime $now The moment to compare against. + * + * @return bool True when the scheduled publication is due. + */ + private function isDue(Dashboard $dashboard, DateTime $now): bool { $publishAt = $dashboard->getPublishAt(); if ($publishAt === null || $publishAt === '') { - return; + return false; } try { - if (new DateTime($publishAt) <= new DateTime()) { - $dashboard->setPublicationStatus(Dashboard::STATUS_PUBLISHED); - } + return new DateTime($publishAt) <= $now; } catch (Exception) { // Malformed timestamp — leave the row as scheduled. + return false; } - }//end materialiseDueSchedule() + }//end isDue() /** * Defensive admin check for the visibility filter. @@ -1558,7 +1891,7 @@ private function materialiseDueSchedule(Dashboard $dashboard): void { */ private function safeIsAdmin(string $userId): bool { try { - return (bool)$this->groupManager->isAdmin(userId: $userId); + return (bool)$this->platform->groupManager->isAdmin(userId: $userId); } catch (Throwable) { return false; } @@ -1590,28 +1923,32 @@ private function filterByPublicationState( ): array { $now = new DateTime(); $filtered = []; - foreach ($entries as $entry) { - $dashboard = $entry['dashboard']; - $status = $this->effectivePublicationStatus(dashboard: $dashboard, now: $now); - - if ($status === Dashboard::STATUS_PUBLISHED) { - $filtered[] = $entry; - continue; - } - - // Status is now draft or (still) scheduled — hide from + $published = $this->effectivePublicationStatus(dashboard: $entry['dashboard'], now: $now) === Dashboard::STATUS_PUBLISHED; + // A draft or (still) scheduled dashboard is hidden from // non-owner non-admin viewers. - $ownerId = $dashboard->getUserId(); - $isOwner = ($ownerId !== null && $ownerId === $actorUserId); - if ($isOwner === true || $actorIsAdmin === true) { + if ($published === true || $this->isOwnedBy(dashboard: $entry['dashboard'], userId: $actorUserId) === true || $actorIsAdmin === true) { $filtered[] = $entry; } - }//end foreach + } return $filtered; }//end filterByPublicationState() + /** + * Whether a dashboard has an owner and it is the given user. + * + * @param Dashboard $dashboard The dashboard. + * @param string $userId The viewing user. + * + * @return bool True for the owner. + */ + private function isOwnedBy(Dashboard $dashboard, string $userId): bool { + $ownerId = $dashboard->getUserId(); + + return $ownerId !== null && $ownerId === $userId; + }//end isOwnedBy() + /** * The publication state a dashboard has at read time, applied to the * entity in memory only: an empty legacy status reads as published @@ -1627,44 +1964,48 @@ private function filterByPublicationState( * @spec openspec/specs/dashboards/spec.md */ private function effectivePublicationStatus(Dashboard $dashboard, DateTime $now): string { + $status = $this->materialisedStatus(dashboard: $dashboard, now: $now); + + // REQ-SCHEDUI-002 (sharing-dashboard-schedule-screen): a published + // dashboard whose take-down time has passed reads as a draft, so + // only its owner and administrators keep seeing it. + if ($status === Dashboard::STATUS_PUBLISHED && $this->isTakenDown(dashboard: $dashboard, now: $now) === true) { + $dashboard->setPublicationStatus(Dashboard::STATUS_DRAFT); + return Dashboard::STATUS_DRAFT; + } + + return $status; + }//end effectivePublicationStatus() + + /** + * The stored publication status, with legacy empty rows read as + * published and due scheduled rows published in place. + * + * @param Dashboard $dashboard The dashboard (mutated when due). + * @param DateTime $now The moment to compare against. + * + * @return string The status before the take-down check. + */ + private function materialisedStatus(Dashboard $dashboard, DateTime $now): string { $status = $dashboard->getPublicationStatus(); // Pre-migration / legacy rows that never set the column // semantically remain visible (REQ-DASH-035): treat an // empty string as `'published'` so backwards compatibility // holds even if an entity is hydrated without the column. if ($status === '') { - $status = Dashboard::STATUS_PUBLISHED; + return Dashboard::STATUS_PUBLISHED; } // REQ-DASH-034: lazy materialisation of due scheduled rows. - if ($status === Dashboard::STATUS_SCHEDULED) { - $publishAt = $dashboard->getPublishAt(); - if ($publishAt !== null && $publishAt !== '') { - try { - $when = new DateTime($publishAt); - if ($when <= $now) { - $dashboard->setPublicationStatus( - Dashboard::STATUS_PUBLISHED - ); - $status = Dashboard::STATUS_PUBLISHED; - } - } catch (Exception) { - // Malformed timestamp — leave as scheduled and - // fall through to the visibility check below. - } - } - } - - // REQ-SCHEDUI-002 (sharing-dashboard-schedule-screen): a published - // dashboard whose take-down time has passed reads as a draft, so - // only its owner and administrators keep seeing it. - if ($status === Dashboard::STATUS_PUBLISHED && $this->isTakenDown(dashboard: $dashboard, now: $now) === true) { - $dashboard->setPublicationStatus(Dashboard::STATUS_DRAFT); - $status = Dashboard::STATUS_DRAFT; + if ($status === Dashboard::STATUS_SCHEDULED && $this->isDue(dashboard: $dashboard, now: $now) === true) { + $dashboard->setPublicationStatus( + Dashboard::STATUS_PUBLISHED + ); + return Dashboard::STATUS_PUBLISHED; } return $status; - }//end effectivePublicationStatus() + }//end materialisedStatus() /** * Resolve the active dashboard for a user using the 7-step precedence @@ -1703,17 +2044,60 @@ public function resolveActiveDashboard( ?string $primaryGroupId, ): ?array { // Normalise the sentinel so steps 2-5 can rely on it. - $groupId = $primaryGroupId; - if ($primaryGroupId === null || $primaryGroupId === '') { - $groupId = Dashboard::DEFAULT_GROUP_ID; - } + $groupId = $this->normalisedGroupId(primaryGroupId: $primaryGroupId); // Pre-fetch all visible dashboards once — used for the pref lookup // and to avoid redundant DB round-trips. $visible = $this->getVisibleToUser(userId: $userId); - // Build a UUID-keyed index for O(1) pref lookup. - // @var array $byUuid. + // Steps 0-1: the pinned default, then the saved preference. + $preferred = $this->resolvePreferredActiveDashboard( + userId: $userId, + byUuid: $this->indexVisibleByUuid(visible: $visible) + ); + if ($preferred !== null) { + return $preferred; + } + + // Steps 2-3: group-shared with isDefault = 1. + // Steps 4-5: first group-shared (sortOrder ASC, createdAt ASC). + // Step 1b (REQ-TMPL-019) sits in front of them: the admin template + // meant for a user who owns no dashboard yet. + $groupShared = $this->resolveTemplateOrGroupShared( + userId: $userId, + visible: $visible, + groupId: $groupId + ); + if ($groupShared !== null) { + return $groupShared; + } + + return $this->findFirstPersonalOrShared(visible: $visible); + }//end resolveActiveDashboard() + + /** + * The primary group, or {@see Dashboard::DEFAULT_GROUP_ID} for none. + * + * @param string|null $primaryGroupId The user's primary group ID. + * + * @return string The group ID steps 2-5 resolve against. + */ + private function normalisedGroupId(string|null $primaryGroupId): string { + if ($primaryGroupId === null || $primaryGroupId === '') { + return Dashboard::DEFAULT_GROUP_ID; + } + + return $primaryGroupId; + }//end normalisedGroupId() + + /** + * A UUID-keyed index of the visible set for O(1) pref lookup. + * + * @param array $visible The user's visible set. + * + * @return array The index; empty UUIDs left out. + */ + private function indexVisibleByUuid(array $visible): array { $byUuid = []; foreach ($visible as $entry) { $uuid = (string)$entry['dashboard']->getUuid(); @@ -1722,11 +2106,24 @@ public function resolveActiveDashboard( } } - // Step 0 (wave3.7): explicit default — if the user has pinned - // a default dashboard via the per-row "Set as default" action, - // it always wins over the auto-overwriting `active_dashboard_uuid` - // pref so visiting `/apps/launchpad/` consistently opens the same - // dashboard regardless of where the user navigated last. + return $byUuid; + }//end indexVisibleByUuid() + + /** + * Steps 0-1 of {@see self::resolveActiveDashboard()}. + * + * Step 0 (wave3.7): explicit default — if the user has pinned a + * default dashboard via the per-row "Set as default" action, it always + * wins over the auto-overwriting `active_dashboard_uuid` pref so + * visiting `/apps/launchpad/` consistently opens the same dashboard + * regardless of where the user navigated last. Step 1: saved preference. + * + * @param string $userId The user ID. + * @param array $byUuid UUID-keyed visible index. + * + * @return array{dashboard: Dashboard, source: string}|null The hit, or null to fall through. + */ + private function resolvePreferredActiveDashboard(string $userId, array $byUuid): ?array { $pinned = $this->resolvePreferredDashboard( userId: $userId, byUuid: $byUuid, @@ -1736,27 +2133,29 @@ public function resolveActiveDashboard( return $pinned; } - // Step 1: saved preference. - $saved = $this->resolvePreferredDashboard( + return $this->resolvePreferredDashboard( userId: $userId, byUuid: $byUuid, prefKey: self::ACTIVE_DASHBOARD_UUID_PREF_KEY ); - if ($saved !== null) { - return $saved; - } - - // Steps 2-3: group-shared with isDefault = 1. - // Steps 4-5: first group-shared (sortOrder ASC, createdAt ASC). - $groupShared = $this->resolveGroupSharedDashboard( - visible: $visible, - groupId: $groupId - ); - if ($groupShared !== null) { - return $groupShared; - } + }//end resolvePreferredActiveDashboard() - // Step 6: first personal dashboard. + /** + * Steps 6-7 of {@see self::resolveActiveDashboard()}. + * + * Step 6: first personal dashboard. Step 6b (REQ-SHARE-002): first + * dashboard shared WITH the user. Deliberately the LAST resort — after + * the saved preference, every group-shared candidate and every personal + * dashboard — so a share can never hijack a selection the user or their + * admin already made. It only ever fires for a user who would otherwise + * land on the empty state, which is exactly the case that made sharing + * inert. Step 7: nothing found ⇒ NULL. + * + * @param array $visible The user's visible set. + * + * @return array{dashboard: Dashboard, source: string}|null The hit, or null. + */ + private function findFirstPersonalOrShared(array $visible): ?array { $personal = $this->findFirstBySource( visible: $visible, source: Dashboard::SOURCE_USER @@ -1765,18 +2164,11 @@ public function resolveActiveDashboard( return $personal; } - // Step 6b (REQ-SHARE-002): first dashboard shared WITH the user. - // Deliberately the LAST resort — after the saved preference, every - // group-shared candidate and every personal dashboard — so a share - // can never hijack a selection the user or their admin already made. - // It only ever fires for a user who would otherwise land on the - // empty state, which is exactly the case that made sharing inert. - // Step 7: nothing found ⇒ NULL. return $this->findFirstBySource( visible: $visible, source: Dashboard::SOURCE_SHARED ); - }//end resolveActiveDashboard() + }//end findFirstPersonalOrShared() /** * Resolve a user-preference dashboard pointer, self-healing a stale @@ -1801,7 +2193,7 @@ private function resolvePreferredDashboard( array $byUuid, string $prefKey, ): ?array { - $uuid = $this->config->getUserValue( + $uuid = $this->platform->config->getUserValue( userId: $userId, appName: Application::APP_ID, key: $prefKey, @@ -1817,12 +2209,12 @@ private function resolvePreferredDashboard( } // Stale pref: UUID is no longer visible — clear and fall through. - $this->config->deleteUserValue( + $this->platform->config->deleteUserValue( userId: $userId, appName: Application::APP_ID, key: $prefKey ); - $this->logger->warning( + $this->outlets->logger->warning( message: 'launchpad: stale ' . $prefKey . ' "{uuid}" cleared for user "{user}"', context: ['uuid' => $uuid, 'user' => $userId] ); @@ -1831,41 +2223,180 @@ private function resolvePreferredDashboard( }//end resolvePreferredDashboard() /** - * Resolve steps 2-5 of the active-dashboard ladder: the group-shared - * candidates. + * Step 1b, then steps 2-5, of the page shell's chain. * - * Order is normative — primary-group default, default-group default, - * primary-group first, default-group first. The primary-group rungs - * are skipped when the user has no primary group (the sentinel). + * Without step 1b the page never looked at templates at all: a group + * dashboard for everyone (one is seeded on install) always won, and with + * none the page said "No dashboards available" while `GET /api/dashboard` + * held the template. * + * @param string $userId The user. * @param array $visible The visible set. * @param string $groupId The normalised primary group. * * @return array{dashboard: Dashboard, source: string}|NULL The hit, or NULL to fall through. * - * @spec openspec/specs/dashboards/spec.md + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-019 */ - private function resolveGroupSharedDashboard(array $visible, string $groupId): ?array { - $hasPrimaryGroup = ($groupId !== Dashboard::DEFAULT_GROUP_ID); + private function resolveTemplateOrGroupShared(string $userId, array $visible, string $groupId): ?array { + $fromTemplate = $this->resolveTemplateRung(userId: $userId); + if ($fromTemplate === null) { + return $this->resolveGroupSharedDashboard(visible: $visible, groupId: $groupId); + } + + $source = Dashboard::SOURCE_USER; + if ($fromTemplate['viewOnly'] === true) { + $source = Dashboard::SOURCE_GROUP; + } - $rungs = []; - if ($hasPrimaryGroup === true) { - // Step 2: primary group default. - $rungs[] = [$groupId, Dashboard::SOURCE_GROUP, true]; + return ['dashboard' => $fromTemplate['dashboard'], 'source' => $source]; + }//end resolveTemplateOrGroupShared() + + /** + * The template rung of both resolution chains (REQ-TMPL-019). + * + * Answers for a user who owns no personal dashboard and has no saved + * choice the caller could honour. Such a user gets the admin template + * that applies to them: one that targets a group of theirs, else the + * default template. + * + * A template that targets the user's group outranks every group + * dashboard. The default template outranks the dashboards of the + * `default` group (everyone), and steps aside for a default dashboard of + * the user's own primary group, which is the more specific of the two. + * + * With personal dashboards allowed the user receives a copy, once, and it + * becomes their saved choice, so every later visit resolves it through + * the preference step and this rung stays silent (it only fires for a + * user who owns nothing). With personal dashboards off no copy may be + * made (REQ-ASET-003), and the template itself is shown, view only. + * + * @param string $userId The user. + * + * @return array{dashboard: Dashboard, viewOnly: bool}|null The dashboard to show, or null to fall through. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-019 + */ + private function resolveTemplateRung(string $userId): ?array { + $template = $this->builders->templateService->getApplicableTemplate(userId: $userId); + if ($template === null || $this->templateStepsAside(userId: $userId, template: $template) === true) { + return null; + } + + if ($this->getAllowUserDashboards() === false) { + return ['dashboard' => $template, 'viewOnly' => true]; + } + + return ['dashboard' => $this->copyTemplateFor(userId: $userId, template: $template), 'viewOnly' => false]; + }//end resolveTemplateRung() + + /** + * Whether the applicable template is not this user's start: they own + * a dashboard already, or the template targets no group and their + * primary group has a default of its own. + * + * "First time" means: owns nothing yet. Whoever has a personal + * dashboard already made, or was given, their start. + * + * @param string $userId The user. + * @param Dashboard $template The applicable template. + * + * @return bool True when the template is not shown. + */ + private function templateStepsAside(string $userId, Dashboard $template): bool { + return $this->stores->dashboardMapper->findByUserId(userId: $userId) !== [] + || ($template->getTargetGroupsArray() === [] + && $this->hasPrimaryGroupDefault(userId: $userId) === true); + }//end templateStepsAside() + + /** + * Copy the template for the user and make the copy their active + * dashboard. + * + * @param string $userId The user. + * @param Dashboard $template The applicable template. + * + * @return Dashboard The copy. + */ + private function copyTemplateFor(string $userId, Dashboard $template): Dashboard { + $copy = $this->builders->templateService->createDashboardFromTemplate( + userId: $userId, + template: $template + ); + $this->platform->config->setUserValue( + userId: $userId, + appName: Application::APP_ID, + key: self::ACTIVE_DASHBOARD_UUID_PREF_KEY, + value: (string)$copy->getUuid() + ); + + return $copy; + }//end copyTemplateFor() + + /** + * Whether the user's primary group has a default group dashboard. + * + * @param string $userId The user. + * + * @return bool True when one exists. + */ + private function hasPrimaryGroupDefault(string $userId): bool { + $groupId = $this->builders->adminTemplateService->resolvePrimaryGroup(userId: $userId); + if ($groupId === Dashboard::DEFAULT_GROUP_ID) { + return false; } - // Step 3: default-group default. - $rungs[] = [Dashboard::DEFAULT_GROUP_ID, Dashboard::SOURCE_DEFAULT, true]; + return $this->findFirstGroupSharedWhere( + visible: $this->getVisibleToUser(userId: $userId), + groupId: $groupId, + source: Dashboard::SOURCE_GROUP, + requireDefault: true + ) !== null; + }//end hasPrimaryGroupDefault() + + /** + * Shape the template rung's answer for `GET /api/dashboard`. + * + * @param array{dashboard: Dashboard, viewOnly: bool} $rung The rung's answer. + * + * @return array The dashboard result. + */ + private function describeTemplateRung(array $rung): array { + $placements = $this->stores->placementMapper->findByDashboardId( + dashboardId: $rung['dashboard']->getId() + ); - if ($hasPrimaryGroup === true) { - // Step 4: primary group first. - $rungs[] = [$groupId, Dashboard::SOURCE_GROUP, false]; + if ($rung['viewOnly'] === true) { + return [ + 'dashboard' => $rung['dashboard'], + 'placements' => $placements, + 'permissionLevel' => Dashboard::PERMISSION_VIEW_ONLY, + ]; } - // Step 5: default-group first. - $rungs[] = [Dashboard::DEFAULT_GROUP_ID, Dashboard::SOURCE_DEFAULT, false]; + return $this->builders->dashResolver->buildResult( + dashboard: $rung['dashboard'], + placements: $placements + ); + }//end describeTemplateRung() - foreach ($rungs as $rung) { + /** + * Resolve steps 2-5 of the active-dashboard ladder: the group-shared + * candidates. + * + * Order is normative — primary-group default, default-group default, + * primary-group first, default-group first. The primary-group rungs + * are skipped when the user has no primary group (the sentinel). + * + * @param array $visible The visible set. + * @param string $groupId The normalised primary group. + * + * @return array{dashboard: Dashboard, source: string}|NULL The hit, or NULL to fall through. + * + * @spec openspec/specs/dashboards/spec.md + */ + private function resolveGroupSharedDashboard(array $visible, string $groupId): ?array { + foreach (self::groupSharedRungs(groupId: $groupId) as $rung) { $result = $this->findFirstGroupSharedWhere( visible: $visible, groupId: $rung[0], @@ -1880,6 +2411,32 @@ private function resolveGroupSharedDashboard(array $visible, string $groupId): ? return null; }//end resolveGroupSharedDashboard() + /** + * The group-shared fallback rungs in order, each `[groupId, source, + * requireDefault]`. Steps 2 and 4 (the primary group's default, then + * its first dashboard) only exist for a viewer whose primary group is + * not the default group; steps 3 and 5 are the default group's. + * + * @param string $groupId The viewer's primary group. + * + * @return list The rungs. + */ + private static function groupSharedRungs(string $groupId): array { + if ($groupId === Dashboard::DEFAULT_GROUP_ID) { + return [ + [Dashboard::DEFAULT_GROUP_ID, Dashboard::SOURCE_DEFAULT, true], + [Dashboard::DEFAULT_GROUP_ID, Dashboard::SOURCE_DEFAULT, false], + ]; + } + + return [ + [$groupId, Dashboard::SOURCE_GROUP, true], + [Dashboard::DEFAULT_GROUP_ID, Dashboard::SOURCE_DEFAULT, true], + [$groupId, Dashboard::SOURCE_GROUP, false], + [Dashboard::DEFAULT_GROUP_ID, Dashboard::SOURCE_DEFAULT, false], + ]; + }//end groupSharedRungs() + /** * Return the first visible entry carrying the given source, in * iteration order. @@ -1917,7 +2474,7 @@ private function findFirstBySource(array $visible, string $source): ?array { */ public function setActivePreference(string $userId, string $uuid): void { if ($uuid === '') { - $this->config->deleteUserValue( + $this->platform->config->deleteUserValue( userId: $userId, appName: Application::APP_ID, key: self::ACTIVE_DASHBOARD_UUID_PREF_KEY @@ -1925,7 +2482,7 @@ public function setActivePreference(string $userId, string $uuid): void { return; } - $this->config->setUserValue( + $this->platform->config->setUserValue( userId: $userId, appName: Application::APP_ID, key: self::ACTIVE_DASHBOARD_UUID_PREF_KEY, @@ -1956,7 +2513,7 @@ public function setActivePreference(string $userId, string $uuid): void { */ public function setDefaultPreference(string $userId, string $uuid): void { if ($uuid === '') { - $this->config->deleteUserValue( + $this->platform->config->deleteUserValue( userId: $userId, appName: Application::APP_ID, key: self::DEFAULT_DASHBOARD_UUID_PREF_KEY @@ -1964,7 +2521,7 @@ public function setDefaultPreference(string $userId, string $uuid): void { return; } - $this->config->setUserValue( + $this->platform->config->setUserValue( userId: $userId, appName: Application::APP_ID, key: self::DEFAULT_DASHBOARD_UUID_PREF_KEY, @@ -1987,7 +2544,7 @@ public function setDefaultPreference(string $userId, string $uuid): void { * @spec openspec/specs/dashboards/spec.md */ public function getDefaultPreference(string $userId): string { - return (string)$this->config->getUserValue( + return (string)$this->platform->config->getUserValue( userId: $userId, appName: Application::APP_ID, key: self::DEFAULT_DASHBOARD_UUID_PREF_KEY, @@ -2017,7 +2574,7 @@ public function getDefaultPreference(string $userId): string { * @spec openspec/specs/dashboards/spec.md */ public function publishDashboard(string $uuid, string $userId): Dashboard { - $dashboard = $this->dashboardMapper->findByUuid(uuid: $uuid); + $dashboard = $this->stores->dashboardMapper->findByUuid(uuid: $uuid); $this->assertOwnerOrAdmin( dashboard: $dashboard, actorUserId: $userId @@ -2033,7 +2590,7 @@ public function publishDashboard(string $uuid, string $userId): Dashboard { $dashboard->setUnpublishAt(null); if ($dashboard->getPublicationStatus() === Dashboard::STATUS_PUBLISHED) { $dashboard->setUpdatedAt($now); - return $this->dashboardMapper->update(entity: $dashboard); + return $this->stores->dashboardMapper->update(entity: $dashboard); } } @@ -2058,10 +2615,10 @@ public function publishDashboard(string $uuid, string $userId): Dashboard { $dashboard->setPublishAt(null); $dashboard->setUpdatedAt($now); - $saved = $this->dashboardMapper->update(entity: $dashboard); + $saved = $this->stores->dashboardMapper->update(entity: $dashboard); // Only the transition into published is announced; the idempotent // early return above sends nothing (#713). - $this->activity?->published(dashboard: $saved, actor: $userId); + $this->outlets->activity?->published(dashboard: $saved, actor: $userId); return $saved; }//end publishDashboard() @@ -2085,7 +2642,7 @@ public function publishDashboard(string $uuid, string $userId): Dashboard { * @spec openspec/specs/dashboards/spec.md */ public function unpublish(string $uuid, string $userId): Dashboard { - $dashboard = $this->dashboardMapper->findByUuid(uuid: $uuid); + $dashboard = $this->stores->dashboardMapper->findByUuid(uuid: $uuid); $this->assertOwnerOrAdmin( dashboard: $dashboard, actorUserId: $userId @@ -2106,7 +2663,7 @@ public function unpublish(string $uuid, string $userId): Dashboard { (new DateTime())->format(format: 'Y-m-d H:i:s') ); - return $this->dashboardMapper->update(entity: $dashboard); + return $this->stores->dashboardMapper->update(entity: $dashboard); }//end unpublish() /** @@ -2141,14 +2698,41 @@ public function schedule( string $userId, ?string $unpublishAt = null, ): Dashboard { - $dashboard = $this->dashboardMapper->findByUuid(uuid: $uuid); + $dashboard = $this->stores->dashboardMapper->findByUuid(uuid: $uuid); $this->assertOwnerOrAdmin( dashboard: $dashboard, actorUserId: $userId ); - $hasPublishAt = ($publishAt !== null && trim($publishAt) !== ''); - $hasUnpublishAt = ($unpublishAt !== null && trim($unpublishAt) !== ''); + $window = $this->parsePublicationWindow(publishAt: $publishAt, unpublishAt: $unpublishAt); + + if ($window->publishAt !== null) { + $dashboard->setPublicationStatus(Dashboard::STATUS_SCHEDULED); + $dashboard->setPublishAt($window->publishAt); + } + + $dashboard->setUnpublishAt($window->unpublishAt); + $dashboard->setUpdatedAt( + (new DateTime())->format(format: 'Y-m-d H:i:s') + ); + + return $this->stores->dashboardMapper->update(entity: $dashboard); + }//end schedule() + + /** + * Validate and parse the go-live and take-down times of a schedule request. + * + * @param string|null $publishAt The requested go-live time. + * @param string|null $unpublishAt The requested take-down time. + * + * @return PublicationWindow The parsed times; null where none was given. + * + * @throws InvalidArgumentException When neither is given, either is unparseable + * or past, or the take-down is not after the go-live. + */ + private function parsePublicationWindow(string|null $publishAt, string|null $unpublishAt): PublicationWindow { + $hasPublishAt = $this->isFilledTime(value: $publishAt); + $hasUnpublishAt = $this->isFilledTime(value: $unpublishAt); if ($hasPublishAt === false && $hasUnpublishAt === false) { throw new InvalidArgumentException(message: self::ERR_SCHEDULE_PAST_DATE); } @@ -2160,26 +2744,44 @@ public function schedule( $parsedUnpublish = null; if ($hasUnpublishAt === true) { - // REQ-SCHEDUI-002 (sharing-dashboard-schedule-screen): the take-down - // time is also in the future, and after the go-live time. - $parsedUnpublish = $this->parseFuturePublishAt(publishAt: (string)$unpublishAt); - if ($parsedPublish !== null && $parsedUnpublish <= $parsedPublish) { - throw new InvalidArgumentException(message: self::ERR_UNPUBLISH_BEFORE_PUBLISH); - } + $parsedUnpublish = $this->parseTakeDownAfter(unpublishAt: (string)$unpublishAt, publishAt: $parsedPublish); } - if ($parsedPublish !== null) { - $dashboard->setPublicationStatus(Dashboard::STATUS_SCHEDULED); - $dashboard->setPublishAt($parsedPublish); - } + return new PublicationWindow(publishAt: $parsedPublish, unpublishAt: $parsedUnpublish); + }//end parsePublicationWindow() - $dashboard->setUnpublishAt($parsedUnpublish); - $dashboard->setUpdatedAt( - (new DateTime())->format(format: 'Y-m-d H:i:s') - ); + /** + * Whether a requested time is given (not null, not blank). + * + * @param string|null $value The requested time. + * + * @return bool + */ + private function isFilledTime(string|null $value): bool { + return $value !== null && trim($value) !== ''; + }//end isFilledTime() - return $this->dashboardMapper->update(entity: $dashboard); - }//end schedule() + /** + * Parse a take-down time that is in the future and after the go-live time. + * + * REQ-SCHEDUI-002 (sharing-dashboard-schedule-screen): the take-down + * time is also in the future, and after the go-live time. + * + * @param string $unpublishAt The requested take-down time. + * @param string|null $publishAt The parsed go-live time, or null. + * + * @return string The parsed take-down time. + * + * @throws InvalidArgumentException When it is unparseable, past, or not after the go-live. + */ + private function parseTakeDownAfter(string $unpublishAt, string|null $publishAt): string { + $parsedUnpublish = $this->parseFuturePublishAt(publishAt: $unpublishAt); + if ($publishAt !== null && $parsedUnpublish <= $publishAt) { + throw new InvalidArgumentException(message: self::ERR_UNPUBLISH_BEFORE_PUBLISH); + } + + return $parsedUnpublish; + }//end parseTakeDownAfter() /** * Eagerly materialise scheduled dashboards whose `publishAt` is @@ -2187,22 +2789,24 @@ public function schedule( * * Iterates every row with `publication_status = 'scheduled'` and * `publish_at <= now()`, flips it to `'published'`, and stamps - * `publishedAt = now()`. Lazy materialisation in the visibility - * filter still runs at read time (correctness guarantee); this - * method exists only to keep the database row consistent with the - * effective state for cleaner audit queries. + * `publishedAt = now()`. It runs at the start of every visibility + * read, so the first read after the go-live flips the row and + * announces the dashboard to its audience once (REQ-DIGE-002). Lazy + * materialisation in the visibility filter still covers the read + * itself (correctness guarantee). * - * @return int The number of dashboards materialised. + * @return int The number of dashboards this call flipped. * * @spec openspec/specs/dashboards/spec.md */ public function materialiseScheduledDashboards(): int { - $dueRows = $this->dashboardMapper->findDueScheduled(); + $dueRows = $this->stores->dashboardMapper->findDueScheduled(); if (count($dueRows) === 0) { return 0; } $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); + $claimed = 0; foreach ($dueRows as $dashboard) { $dashboard->setPublicationStatus(Dashboard::STATUS_PUBLISHED); if ($dashboard->getPublishedAt() === null) { @@ -2211,13 +2815,17 @@ public function materialiseScheduledDashboards(): int { $dashboard->setPublishAt(null); $dashboard->setUpdatedAt($now); - $saved = $this->dashboardMapper->update(entity: $dashboard); - // A scheduled dashboard is announced once, when its row flips - // to published here; the owner is the actor (#713). - $this->activity?->published(dashboard: $saved, actor: (string) $saved->getUserId()); + if ($this->stores->dashboardMapper->setPublishedIfScheduled(dashboard: $dashboard) === false) { + continue; + } + + // Announced once, by the request that flipped the row, and not + // to the owner who scheduled it (REQ-DIGE-002). + $this->outlets->activity?->surfaced(dashboard: $dashboard); + $claimed++; } - return count($dueRows); + return $claimed; }//end materialiseScheduledDashboards() /** @@ -2298,7 +2906,7 @@ public function forkAsPersonal( // personal-scope dashboard, so it is bound by the per-user // dashboard quota exactly like a plain create. Runs before any DB // write and before the transaction opens. - $this->quotaService?->assertCanCreateDashboard(userId: $userId); + $this->limits->quotaService?->assertCanCreateDashboard(userId: $userId); // REQ-DASH-020: source must be visible to the user — reuse the // visible-to-user resolver so personal / group / default-group @@ -2347,7 +2955,7 @@ public function forkAsPersonal( ); } finally { if ($lockAcquired === true) { - $this->lockingProvider?->releaseLock( + $this->limits->lockingProvider?->releaseLock( path: $lockKey, type: ILockingProvider::LOCK_EXCLUSIVE ); @@ -2373,42 +2981,47 @@ public function forkAsPersonal( * @throws Throwable Whatever the transaction body threw, after rollback. * * @spec openspec/specs/dashboards/spec.md + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies */ private function persistFork( string $userId, Dashboard $source, string $resolvedName, ): Dashboard { - $this->db->beginTransaction(); + $this->platform->db->beginTransaction(); try { // REQ-DASH-020: force `isDefault = 0` and `groupId = null` // on the fork — the factory is the single source of truth // for the (type, groupId) invariant (REQ-DASH-011). - $fork = $this->dashboardFactory->create( + $fork = $this->builders->dashboardFactory->create( userId: $userId, name: $resolvedName, - description: $source->getDescription(), - type: Dashboard::TYPE_USER, - groupId: null, - gridColumns: $source->getGridColumns(), - permissionLevel: Dashboard::PERMISSION_FULL + options: [ + 'description' => $source->getDescription(), + 'type' => Dashboard::TYPE_USER, + 'groupId' => null, + 'gridColumns' => $source->getGridColumns(), + 'permissionLevel' => Dashboard::PERMISSION_FULL, + ] ); // Defensive — the factory already sets this for TYPE_USER but // we make the contract visible at the call site. $fork->setIsDefault(0); + // REQ-CWF-011: the copy's filter bus joins widgets as the source's does. + $fork->setHierarchiesArray($source->getHierarchiesArray()); // REQ-DASH-020: deactivate every other personal dashboard // for this user before persisting the fork — mirrors // {@see self::createDashboard()} so the single-active // invariant holds across the transaction. - $this->dashboardMapper->deactivateAllForUser(userId: $userId); + $this->stores->dashboardMapper->deactivateAllForUser(userId: $userId); $fork->setIsActive(1); - $persisted = $this->dashboardMapper->insert(entity: $fork); + $persisted = $this->stores->dashboardMapper->insert(entity: $fork); // REQ-DASH-020: byte-for-byte placement clone. Any DB error // bubbles out of the mapper and the catch below rolls back. - $this->placementMapper->cloneToDashboard( + $this->stores->placementMapper->cloneToDashboard( sourceDashboardId: (int)$source->getId(), targetDashboardId: (int)$persisted->getId() ); @@ -2425,11 +3038,11 @@ private function persistFork( ); } - $this->db->commit(); + $this->platform->db->commit(); return $persisted; } catch (Throwable $t) { - $this->db->rollBack(); + $this->platform->db->rollBack(); throw $t; }//end try }//end persistFork() @@ -2453,14 +3066,14 @@ private function persistFork( * @return bool True when the lock was acquired (caller MUST release it). */ private function acquireForkLock(string $lockKey): bool { - if ($this->lockingProvider === null) { + if ($this->limits->lockingProvider === null) { return false; } $maxAttempts = 10; for ($attempt = 0; $attempt < $maxAttempts; $attempt++) { try { - $this->lockingProvider->acquireLock( + $this->limits->lockingProvider->acquireLock( path: $lockKey, type: ILockingProvider::LOCK_EXCLUSIVE ); @@ -2471,7 +3084,7 @@ private function acquireForkLock(string $lockKey): bool { } } - $this->logger->warning( + $this->outlets->logger->warning( message: 'forkAsPersonal could not acquire the fork-naming lock; proceeding unlocked', context: [ 'app' => Application::APP_ID, @@ -2487,7 +3100,8 @@ private function acquireForkLock(string $lockKey): bool { * chain. * * Personal, group-shared (matching), and default-group sentinel - * dashboards are all eligible source candidates. A source UUID the + * dashboards are all eligible source candidates, and so is every admin + * template the gallery offers the user (REQ-TMPL-018). A source UUID the * caller cannot see MUST be reported as a 404 to avoid leaking * existence (REQ-DASH-020 scenario "Cannot fork a dashboard you * cannot read"). @@ -2511,6 +3125,15 @@ private function findVisibleDashboardForFork( } } + // REQ-TMPL-018: a template the gallery offers the user is a source too. + $template = $this->builders->adminTemplateService->findOfferedTemplate( + userId: $userId, + uuid: $sourceUuid + ); + if ($template !== null) { + return $template; + } + throw new DoesNotExistException(msg: 'Dashboard not found'); }//end findVisibleDashboardForFork() @@ -2543,9 +3166,9 @@ private function resolveForkName( return $trimmed; } - $l10n = $this->l10nFactory->get( + $l10n = $this->platform->l10nFactory->get( app: Application::APP_ID, - lang: $this->config->getUserValue( + lang: $this->platform->config->getUserValue( userId: $userId, appName: 'core', key: 'lang', @@ -2578,7 +3201,7 @@ private function makeUniquePersonalName( string $baseName, ): string { $taken = []; - foreach ($this->dashboardMapper->findByUserId(userId: $userId) as $dash) { + foreach ($this->stores->dashboardMapper->findByUserId(userId: $userId) as $dash) { // Forks land at the root, so only root siblings can collide. if ($dash->getParentUuid() !== null) { continue; @@ -2612,7 +3235,7 @@ private function makeUniquePersonalName( * @spec openspec/specs/dashboards/spec.md */ public function isAdmin(string $userId): bool { - return $this->groupManager->isAdmin(userId: $userId); + return $this->platform->groupManager->isAdmin(userId: $userId); }//end isAdmin() /** @@ -2629,11 +3252,11 @@ public function isAdmin(string $userId): bool { * @spec openspec/changes/launchpad-legacy-quality-cleanup/tasks.md#task-1 */ public function userCanAccessGroup(string $userId, string $groupId): bool { - if ($this->groupManager->isAdmin(userId: $userId) === true) { + if ($this->platform->groupManager->isAdmin(userId: $userId) === true) { return true; } - $userGroupIds = $this->adminTemplateService->getUserGroupIdsFor( + $userGroupIds = $this->builders->adminTemplateService->getUserGroupIdsFor( userId: $userId ); @@ -2665,7 +3288,7 @@ public function userCanAccessGroup(string $userId, string $groupId): bool { * @spec openspec/specs/dashboards/spec.md */ public function getAllowUserDashboards(): bool { - return (bool)$this->settingMapper->getValue( + return (bool)$this->stores->settingMapper->getValue( key: AdminSetting::KEY_ALLOW_USER_DASHBOARDS, default: false ); @@ -2718,32 +3341,57 @@ private function findFirstGroupSharedWhere( string $source, bool $requireDefault, ): ?array { - foreach ($visible as $entry) { - if ($entry['source'] !== $source) { - continue; - } - - $dashboard = $entry['dashboard']; - if ($dashboard->getType() !== Dashboard::TYPE_GROUP_SHARED) { - continue; - } - - if ($dashboard->getGroupId() !== $groupId) { - continue; - } - - if ($requireDefault === true - && (int)$dashboard->getIsDefault() !== 1 + foreach (self::entriesFromSource(visible: $visible, source: $source) as $entry) { + if (self::isGroupSharedIn(dashboard: $entry['dashboard'], groupId: $groupId) === true + && self::meetsDefaultRequirement(dashboard: $entry['dashboard'], requireDefault: $requireDefault) === true ) { - continue; + return $entry; } - - return $entry; - }//end foreach + } return null; }//end findFirstGroupSharedWhere() + /** + * The visible entries resolved through the given source, in order. + * + * @param array $visible The visible entries. + * @param string $source The source. + * + * @return array The matching entries. + */ + private static function entriesFromSource(array $visible, string $source): array { + return array_filter( + array: $visible, + callback: static fn (array $entry): bool => $entry['source'] === $source + ); + }//end entriesFromSource() + + /** + * Whether a dashboard is a group-shared dashboard of the given group. + * + * @param Dashboard $dashboard The dashboard. + * @param string $groupId The group ID. + * + * @return bool True when it is. + */ + private static function isGroupSharedIn(Dashboard $dashboard, string $groupId): bool { + return $dashboard->getType() === Dashboard::TYPE_GROUP_SHARED + && $dashboard->getGroupId() === $groupId; + }//end isGroupSharedIn() + + /** + * Whether a dashboard satisfies the rung's default requirement. + * + * @param Dashboard $dashboard The dashboard. + * @param bool $requireDefault Whether only a default dashboard qualifies. + * + * @return bool True when it qualifies. + */ + private static function meetsDefaultRequirement(Dashboard $dashboard, bool $requireDefault): bool { + return $requireDefault === false || (int)$dashboard->getIsDefault() === 1; + }//end meetsDefaultRequirement() + /** * A root slug for this user's auto-provisioned dashboard that no sibling holds. * @@ -2768,7 +3416,7 @@ private function uniqueRootSlugFor(string $userId): string { } try { - $this->treeService->validateSlugUnique(parentUuid: null, slug: $candidate); + $this->structure->treeService->validateSlugUnique(parentUuid: null, slug: $candidate); return $candidate; } catch (InvalidArgumentException) { continue; @@ -2787,13 +3435,10 @@ private function uniqueRootSlugFor(string $userId): string { */ private function tryCreateFromTemplate(string $userId): ?array { $allowUserDashboards = $this->getAllowUserDashboards(); - - $template = $this->templateService->getApplicableTemplate( - userId: $userId - ); + $template = $this->builders->templateService->getApplicableTemplate(userId: $userId); if ($template !== null) { - return $this->dashResolver->handleTemplateResult( + return $this->builders->dashResolver->handleTemplateResult( template: $template, allowUserDashboards: $allowUserDashboards, userId: $userId @@ -2801,59 +3446,95 @@ private function tryCreateFromTemplate(string $userId): ?array { } if ($allowUserDashboards === true) { - // 🔴 THE SLUG IS PER USER, BECAUSE THE ROOT SLUG NAMESPACE IS NOT. - // `validateSlugUnique()` looks for any root dashboard with this - // slug, whoever owns it, and every auto-provisioned dashboard is - // named 'My Dashboard'. So the SECOND user ever to reach this - // branch got `Slug must be unique among siblings` and the request - // answered HTTP 500 with no dashboard at all. Measured on a fresh - // instance: the first user provisioned, the next one 500'd. - $dashboard = $this->createDashboard( - userId: $userId, - name: 'My Dashboard', - slug: $this->uniqueRootSlugFor(userId: $userId) - ); + return $this->provisionPersonalDashboard(userId: $userId); + } - // REQ-RFP-002: when no admin template applies, prefer seeding - // from the user's RoleLayoutDefault rows. Only fall back to the - // hardcoded recommendations + activity pair when no role-defaults - // exist for any of the user's groups (or the user is in no group). - // The dependency is nullable to keep legacy PHPUnit doubles (built - // before role-based-content shipped) working — when null we treat - // it as "no defaults seeded" so the legacy hardcoded fallback runs. - $seeded = 0; - if ($this->roleFeaturePerm !== null) { - $seeded = $this->roleFeaturePerm->seedLayoutFromRoleDefaults( - userId: $userId, - dashboard: $dashboard - ); - } + return null; + }//end tryCreateFromTemplate() - // The comment above says the hardcoded pair is a FALLBACK, and it - // was not: it was created on every path, so a role-seeded layout - // came out carrying the role defaults AND tile/tile/tile/files. - $placements = []; - if ($seeded > 0) { - $placements = $this->placementMapper->findByDashboardId( - dashboardId: $dashboard->getId() - ); - } + /** + * Provision a user's first personal dashboard, laid out from their + * role defaults or, without any, the default bundle. + * + * 🔴 THE SLUG IS PER USER, BECAUSE THE ROOT SLUG NAMESPACE IS NOT. + * `validateSlugUnique()` looks for any root dashboard with this + * slug, whoever owns it, and every auto-provisioned dashboard is + * named 'My Dashboard'. So the SECOND user ever to reach this + * branch got `Slug must be unique among siblings` and the request + * answered HTTP 500 with no dashboard at all. Measured on a fresh + * instance: the first user provisioned, the next one 500'd. + * + * @param string $userId The user ID. + * + * @return array{dashboard: Dashboard, placements: array, permissionLevel: string} + */ + private function provisionPersonalDashboard(string $userId): array { + $dashboard = $this->createDashboard( + userId: $userId, + name: 'My Dashboard', + options: ['slug' => $this->uniqueRootSlugFor(userId: $userId)] + ); - if ($seeded === 0) { - $placements = $this->createDefaultPlacements( - dashboardId: $dashboard->getId() - ); - } + $seeded = $this->seedFromRoleDefaults(userId: $userId, dashboard: $dashboard); + + return [ + 'dashboard' => $dashboard, + 'placements' => $this->provisionedPlacements(dashboard: $dashboard, seeded: $seeded), + 'permissionLevel' => Dashboard::PERMISSION_FULL, + ]; + }//end provisionPersonalDashboard() + + /** + * REQ-RFP-002: when no admin template applies, prefer seeding + * from the user's RoleLayoutDefault rows. The dependency is nullable + * to keep legacy PHPUnit doubles (built before role-based-content + * shipped) working — when null we treat it as "no defaults seeded" so + * the legacy hardcoded fallback runs. + * + * @param string $userId The user ID. + * @param Dashboard $dashboard The provisioned dashboard. + * + * @return int The number of placements seeded from role defaults. + */ + private function seedFromRoleDefaults(string $userId, Dashboard $dashboard): int { + if ($this->limits->roleFeaturePerm === null) { + return 0; + } + + return $this->limits->roleFeaturePerm->seedLayoutFromRoleDefaults( + userId: $userId, + dashboard: $dashboard + ); + }//end seedFromRoleDefaults() + + /** + * The provisioned dashboard's placements: the role-seeded ones, or — + * only when nothing was seeded — the hardcoded default bundle. + * + * The hardcoded pair is a FALLBACK: it used to be created on every + * path, so a role-seeded layout came out carrying the role defaults + * AND tile/tile/tile/files. + * + * @param Dashboard $dashboard The provisioned dashboard. + * @param int $seeded The number of role-seeded placements. + * + * @return array The placements. + */ + private function provisionedPlacements(Dashboard $dashboard, int $seeded): array { + if ($seeded > 0) { + return $this->stores->placementMapper->findByDashboardId( + dashboardId: $dashboard->getId() + ); + } - return [ - 'dashboard' => $dashboard, - 'placements' => $placements, - 'permissionLevel' => Dashboard::PERMISSION_FULL, - ]; - }//end if + if ($seeded === 0) { + return $this->createDefaultPlacements( + dashboardId: $dashboard->getId() + ); + } - return null; - }//end tryCreateFromTemplate() + return []; + }//end provisionedPlacements() /** * Create default widget placements for a new dashboard. @@ -2885,7 +3566,7 @@ private function createDefaultPlacements(int $dashboardId): array { * @spec openspec/specs/dashboards/spec.md */ public function findPlacements(int $dashboardId): array { - return $this->placementMapper->findByDashboardId( + return $this->stores->placementMapper->findByDashboardId( dashboardId: $dashboardId ); }//end findPlacements() @@ -2935,20 +3616,22 @@ public function findPlacements(int $dashboardId): array { * @spec openspec/specs/default-widget-bundle/spec.md */ public function ensureDefaultDashboard(): ?Dashboard { - $existing = $this->dashboardMapper->findByGroup( + $existing = $this->stores->dashboardMapper->findByGroup( groupId: Dashboard::DEFAULT_GROUP_ID ); if (count(value: $existing) > 0) { return null; } - $dashboard = $this->dashboardFactory->create( + $dashboard = $this->builders->dashboardFactory->create( userId: null, name: 'Dashboard', - description: 'The dashboard everyone starts on. Edit it to change what your whole organisation sees.', - type: Dashboard::TYPE_GROUP_SHARED, - groupId: Dashboard::DEFAULT_GROUP_ID, - permissionLevel: Dashboard::PERMISSION_VIEW_ONLY + options: [ + 'description' => 'The dashboard everyone starts on. Edit it to change what your whole organisation sees.', + 'type' => Dashboard::TYPE_GROUP_SHARED, + 'groupId' => Dashboard::DEFAULT_GROUP_ID, + 'permissionLevel' => Dashboard::PERMISSION_VIEW_ONLY, + ] ); // Rung 3 of resolveGroupSharedDashboard() requires isDefault; without // it the row is only reachable through the weaker rung-5 fallback. @@ -2956,12 +3639,27 @@ public function ensureDefaultDashboard(): ?Dashboard { // Drafts are hidden from every non-owner, and this row has no owner. $dashboard->setPublicationStatus(Dashboard::STATUS_PUBLISHED); - $persisted = $this->dashboardMapper->insert(entity: $dashboard); + $persisted = $this->stores->dashboardMapper->insert(entity: $dashboard); $this->seedDefaultWidgets(dashboardId: $persisted->getId()); + $this->announceAudience(dashboard: $persisted); return $persisted; }//end ensureDefaultDashboard() + /** + * Announce a new group dashboard's audience, so its discussion object is + * written (openregister-leaf-integrations). + * + * @param Dashboard $dashboard The persisted group dashboard. + * + * @return void + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-4 + */ + private function announceAudience(Dashboard $dashboard): void { + $this->outlets->eventDispatcher?->dispatchTyped(new DashboardAudienceChangedEvent(dashboardId: (int)$dashboard->getId())); + }//end announceAudience() + /** * Seed the default widget bundle on a freshly-created dashboard. * @@ -2987,16 +3685,28 @@ public function ensureDefaultDashboard(): ?Dashboard { * app's real web root (so the URLs work regardless of which apps * directory the app is served from). * - * @param int $dashboardId The dashboard ID to seed. + * With `$seedSet` {@see self::SEED_SET_STARTERS} the dashboard gets the + * first-run starter widgets ({@see StarterWidgetSeeds}) instead. + * + * @param int $dashboardId The dashboard ID to seed. + * @param string $seedSet Which set: {@see self::SEED_SET_DEFAULT} or {@see self::SEED_SET_STARTERS}. + * @param array $menuAppIds The app ids in the user's app menu, for the starter app tiles. * - * @return WidgetPlacement[] The persisted placements (4 entries). + * @return WidgetPlacement[] The persisted placements. + * + * @spec openspec/specs/runtime-shell/spec.md#req-shell-005 */ - private function seedDefaultWidgets(int $dashboardId): array { + private function seedDefaultWidgets(int $dashboardId, string $seedSet=self::SEED_SET_DEFAULT, array $menuAppIds=[]): array { $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); + $seeds = $this->defaultWidgetSeeds(); + if ($seedSet === self::SEED_SET_STARTERS) { + $seeds = StarterWidgetSeeds::seeds(menuAppIds: $menuAppIds); + } + $placements = []; - foreach ($this->defaultWidgetSeeds() as $config) { - $placements[] = $this->placementMapper->insert( + foreach ($seeds as $config) { + $placements[] = $this->stores->placementMapper->insert( entity: $this->buildSeedPlacement( dashboardId: $dashboardId, config: $config, @@ -3021,68 +3731,15 @@ private function seedDefaultWidgets(int $dashboardId): array { * @spec openspec/specs/dashboards/spec.md */ private function defaultWidgetSeeds(): array { - return [ - [ - 'widgetId' => 'tile', - 'gridX' => 0, - 'gridY' => 0, - 'gridWidth' => 4, - 'gridHeight' => 3, - 'sortOrder' => 0, - 'tile' => [ - 'title' => 'Conduction', - 'icon' => $this->appImagePath(image: 'conduction-logo.png'), - 'iconType' => 'url', - 'backgroundColor' => '#ffffff', - 'textColor' => '#000000', - 'linkType' => 'url', - 'linkValue' => 'https://conduction.nl', - ], - ], - [ - 'widgetId' => 'tile', - 'gridX' => 4, - 'gridY' => 0, - 'gridWidth' => 4, - 'gridHeight' => 3, - 'sortOrder' => 1, - 'tile' => [ - 'title' => 'Sendent', - 'icon' => $this->appImagePath(image: 'sendent-logo.png'), - 'iconType' => 'url', - 'backgroundColor' => '#ffffff', - 'textColor' => '#000000', - 'linkType' => 'url', - 'linkValue' => 'https://sendent.com', - ], - ], - [ - 'widgetId' => 'tile', - 'gridX' => 8, - 'gridY' => 0, - 'gridWidth' => 4, - 'gridHeight' => 3, - 'sortOrder' => 2, - 'tile' => [ - 'title' => 'Nextcloud', - 'icon' => 'icon-nextcloud', - 'iconType' => 'class', - 'backgroundColor' => '#0082c9', - 'textColor' => '#ffffff', - 'linkType' => 'url', - 'linkValue' => 'https://nextcloud.com', - ], - ], - [ - 'widgetId' => 'files', - 'gridX' => 0, - 'gridY' => 3, - 'gridWidth' => 12, - 'gridHeight' => 5, - 'sortOrder' => 3, - 'tile' => null, - ], - ]; + $seeds = self::DEFAULT_WIDGET_SEEDS; + foreach ($seeds as $index => $seed) { + // A `url` icon names a bundled image; resolve it to the app's real web root. + if (($seed['tile']['iconType'] ?? null) === 'url') { + $seeds[$index]['tile']['icon'] = $this->appImagePath(image: $seed['tile']['icon']); + } + } + + return $seeds; }//end defaultWidgetSeeds() /** @@ -3111,10 +3768,28 @@ private function buildSeedPlacement(int $dashboardId, array $config, string $now $placement->setCreatedAt($now); $placement->setUpdatedAt($now); + if (isset($config['content']) === true) { + $placement->setContentArray(content: $config['content']); + } + if ($config['tile'] === null) { return $placement; } + $this->applySeedTile(placement: $placement, tile: $config['tile']); + + return $placement; + }//end buildSeedPlacement() + + /** + * Copy a seed config's tile fields onto a placement. + * + * @param WidgetPlacement $placement The placement being seeded. + * @param array $tile The seed config's `tile` entry. + * + * @return void + */ + private function applySeedTile(WidgetPlacement $placement, array $tile): void { // `tileType` MUST be non-null for `WidgetPlacement::jsonSerialize()` // to emit the flat tile* fields the renderer reads. The // sentinel `'preset'` distinguishes seed-tiles from the @@ -3123,16 +3798,14 @@ private function buildSeedPlacement(int $dashboardId, array $config, string $now // placements still flow through the registry-backed // TileWidget renderer (REQ-WDG-022). $placement->setTileType('preset'); - $placement->setTileTitle($config['tile']['title']); - $placement->setTileIcon($config['tile']['icon']); - $placement->setTileIconType($config['tile']['iconType']); - $placement->setTileBackgroundColor($config['tile']['backgroundColor']); - $placement->setTileTextColor($config['tile']['textColor']); - $placement->setTileLinkType($config['tile']['linkType']); - $placement->setTileLinkValue($config['tile']['linkValue']); - - return $placement; - }//end buildSeedPlacement() + $placement->setTileTitle($tile['title']); + $placement->setTileIcon($tile['icon']); + $placement->setTileIconType($tile['iconType']); + $placement->setTileBackgroundColor($tile['backgroundColor']); + $placement->setTileTextColor($tile['textColor']); + $placement->setTileLinkType($tile['linkType']); + $placement->setTileLinkValue($tile['linkValue']); + }//end applySeedTile() /** * Apply updates to a dashboard entity. @@ -3146,47 +3819,299 @@ private function applyDashboardUpdates( Dashboard $dashboard, array $data, ): void { - if (isset($data['name']) === true) { - $dashboard->setName($data['name']); - } + $this->applyFieldUpdates(dashboard: $dashboard, data: $data); + $this->applyTreeUpdates(dashboard: $dashboard, data: $data); + $this->applyFooterUpdates(dashboard: $dashboard, data: $data); + $this->applyLookUpdates(dashboard: $dashboard, data: $data); + $this->applyLinkTargetUpdate(dashboard: $dashboard, data: $data); + $this->applyHierarchiesUpdate(dashboard: $dashboard, data: $data); + $this->applyConversationUpdate(dashboard: $dashboard, data: $data); - if (isset($data['description']) === true) { - $dashboard->setDescription($data['description']); + $dashboard->setUpdatedAt( + (new DateTime())->format(format: 'Y-m-d H:i:s') + ); + + $this->applyPlacementUpdates(data: $data); + }//end applyDashboardUpdates() + + /** + * Apply a patched look: accent, background colour and background image (REQ-THM-001/002). + * + * An empty string clears a field, so the dashboard follows the theme + * again. Colours are stored as lower-case `#rrggbb`, the image as a + * LaunchPad resource file name. Whenever the accent or the background + * changes, the accent that results must reach 3:1 against the background + * that results (the instance's when the dashboard has none). + * + * @param Dashboard $dashboard The dashboard being updated. + * @param array $data The update payload. + * + * @return void + * + * @throws InvalidArgumentException When a colour or image is malformed, or the accent is too pale. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ + private function applyLookUpdates(Dashboard $dashboard, array $data): void { + $colours = $this->patchedColours( + data: $data, + current: ['themeAccent' => $dashboard->getThemeAccent(), 'themeBackgroundColor' => $dashboard->getThemeBackgroundColor()] + ); + $accent = $colours['themeAccent']; + $background = $colours['themeBackgroundColor']; + $this->applyBackgroundResourceUpdate(dashboard: $dashboard, data: $data); + + $colourChanged = array_key_exists('themeAccent', $data) === true || array_key_exists('themeBackgroundColor', $data) === true; + if ($colourChanged === true && $accent !== null) { + DashboardLook::assertAccentReadable(accent: $accent, background: $background); } - // Icon may be NULL/empty (use default), a registry key, or a URL. - // The discriminator + lookup live frontend-side in the - // `dashboard-icons` capability — we just store the opaque string. - if (array_key_exists(key: 'icon', array: $data) === true) { - $iconValue = $data['icon']; - $iconToStore = null; - if (is_string($iconValue) === true) { - $iconToStore = $iconValue; + $dashboard->setThemeAccent($accent); + $dashboard->setThemeBackgroundColor($background); + $this->applyCustomCssUpdate(dashboard: $dashboard, data: $data); + }//end applyLookUpdates() + + /** + * The colours a patch leaves in the look: per field the current one when + * the patch does not name it, null when it sends an empty value, else the + * value as lower-case `#rrggbb` (REQ-THM-001). Fields are read in the order + * of `$current`, so the accent is judged before the background. + * + * @param array $data The update payload. + * @param array $current The dashboard's colours now, by field. + * + * @return array The colours to store, by field. + * + * @throws InvalidArgumentException When a colour is malformed. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ + private function patchedColours(array $data, array $current): array { + $labels = ['themeAccent' => 'The accent', 'themeBackgroundColor' => 'The background colour']; + foreach (array_keys($current) as $key) { + if (array_key_exists($key, $data) === false) { + continue; } - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - $dashboard->setIcon($iconToStore); + $current[$key] = null; + if (trim((string)$data[$key]) !== '') { + $current[$key] = DashboardLook::normaliseHex(colour: (string)$data[$key], field: $labels[$key]); + } } - if (isset($data['gridColumns']) === true) { - $dashboard->setGridColumns($data['gridColumns']); + return $current; + }//end patchedColours() + + /** + * Apply a patched background image: a LaunchPad resource file name, or + * none for an empty value (REQ-THM-001). + * + * @param Dashboard $dashboard The dashboard being updated. + * @param array $data The update payload. + * + * @return void + * + * @throws InvalidArgumentException When the name is no LaunchPad resource. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 + */ + private function applyBackgroundResourceUpdate(Dashboard $dashboard, array $data): void { + if (array_key_exists('themeBackgroundResource', $data) === false) { + return; } - $this->applyTreeUpdates(dashboard: $dashboard, data: $data); - $this->applyFooterUpdates(dashboard: $dashboard, data: $data); + $resource = trim((string)$data['themeBackgroundResource']); + if ($resource !== '' && DashboardLook::isResourceName(name: $resource) === false) { + throw new InvalidArgumentException('The background image must be an image uploaded to LaunchPad.'); + } - $dashboard->setUpdatedAt( - (new DateTime())->format(format: 'Y-m-d H:i:s') + $stored = null; + if ($resource !== '') { + $stored = $resource; + } + + $dashboard->setThemeBackgroundResource($stored); + }//end applyBackgroundResourceUpdate() + + /** + * Apply patched administrator CSS, cleaned and scoped to this dashboard (REQ-THM-003). + * + * The caller has checked that the user is an administrator. An empty + * value clears the CSS. + * + * @param Dashboard $dashboard The dashboard being updated. + * @param array $data The update payload. + * + * @return void + * + * @throws InvalidArgumentException When the CSS is larger than 20 KB. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + private function applyCustomCssUpdate(Dashboard $dashboard, array $data): void { + if (array_key_exists('customCss', $data) === false) { + return; + } + + $result = (new CustomCssSanitiser())->sanitise( + css: (string)$data['customCss'], + scope: CustomCssSanitiser::dashboardScope(uuid: (string)$dashboard->getUuid()) + ); + + $stored = null; + if ($result['css'] !== '') { + $stored = $result['css']; + } + + $dashboard->setCustomCss($stored); + }//end applyCustomCssUpdate() + + /** + * Apply the patched default link target, when the payload names one. + * + * An empty value clears it, so tiles follow the link-type rule again. + * + * @param Dashboard $dashboard The dashboard being updated. + * @param array $data The update payload. + * + * @return void + * + * @throws \InvalidArgumentException When the value is not a link target. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + private function applyLinkTargetUpdate(Dashboard $dashboard, array $data): void { + if (array_key_exists(key: 'defaultLinkTarget', array: $data) === false) { + return; + } + + $dashboard->setDefaultLinkTarget( + TileLinkTarget::validated(value: $data['defaultLinkTarget'], field: 'defaultLinkTarget') ); + }//end applyLinkTargetUpdate() + + /** + * Apply the patched hierarchy descriptors, when the payload names them. + * + * The empty list clears them, so widgets that consume a hierarchy + * dimension leave the filter bus (REQ-CWF-011). + * + * @param Dashboard $dashboard The dashboard being updated. + * @param array $data The update payload. + * + * @return void + * + * @throws InvalidArgumentException When a descriptor is malformed. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + private function applyHierarchiesUpdate(Dashboard $dashboard, array $data): void { + if (array_key_exists(key: 'hierarchies', array: $data) === false) { + return; + } + + $dashboard->setHierarchiesArray(DashboardHierarchies::validated(value: $data['hierarchies'])); + }//end applyHierarchiesUpdate() + + /** + * Apply the patched conversation switch, when the payload names it: + * true shows the Talk conversation beside a shared dashboard, false + * hides it, null returns to the default (shown). + * + * @param Dashboard $dashboard The dashboard being updated. + * @param array $data The update payload. + * + * @return void + * + * @throws InvalidArgumentException When the value is not a boolean or null. + * + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ + private function applyConversationUpdate(Dashboard $dashboard, array $data): void { + if (array_key_exists(key: 'conversationEnabled', array: $data) === false) { + return; + } + + $value = $data['conversationEnabled']; + if ($value === null) { + $dashboard->setConversationEnabled(null); + return; + } + + if (is_bool($value) === false && in_array(needle: $value, haystack: [0, 1], strict: true) === false) { + throw new InvalidArgumentException(message: 'conversationEnabled must be true, false or null'); + } + + $dashboard->setConversationEnabled((int) $value); + }//end applyConversationUpdate() + /** + * Apply a patched placement position list, when the payload has one. + * + * @param array $data The update payload. + * + * @return void + */ + private function applyPlacementUpdates(array $data): void { if (isset($data['placements']) === true && is_array($data['placements']) === true ) { - $this->placementMapper->updatePositions( + $this->stores->placementMapper->updatePositions( updates: $data['placements'] ); } - }//end applyDashboardUpdates() + }//end applyPlacementUpdates() + + /** + * Apply the patched name, description, icon and grid columns. + * + * @param Dashboard $dashboard The dashboard being updated. + * @param array $data The update payload. + * + * @return void + */ + private function applyFieldUpdates(Dashboard $dashboard, array $data): void { + if (isset($data['name']) === true) { + $dashboard->setName($data['name']); + } + + if (isset($data['description']) === true) { + $dashboard->setDescription($data['description']); + } + + $this->applyIconUpdate(dashboard: $dashboard, data: $data); + + if (isset($data['gridColumns']) === true) { + $dashboard->setGridColumns($data['gridColumns']); + } + }//end applyFieldUpdates() + + /** + * Apply a patched icon: a string is stored as given, anything else + * clears it. + * + * Icon may be NULL/empty (use default), a registry key, or a URL. + * The discriminator + lookup live frontend-side in the + * `dashboard-icons` capability — we just store the opaque string. + * + * @param Dashboard $dashboard The dashboard being updated. + * @param array $data The update payload. + * + * @return void + */ + private function applyIconUpdate(Dashboard $dashboard, array $data): void { + if (array_key_exists(key: 'icon', array: $data) === false) { + return; + } + + $iconToStore = null; + if (is_string($data['icon']) === true) { + $iconToStore = $data['icon']; + } + + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $dashboard->setIcon($iconToStore); + }//end applyIconUpdate() /** * Apply per-dashboard footer override updates (REQ-FTR-006). @@ -3225,7 +4150,7 @@ private function applyFooterUpdates( ); if ($newMode === Dashboard::FOOTER_MODE_CUSTOM) { - $sanitised = $this->footerService->sanitiseHtml( + $sanitised = $this->structure->footerService->sanitiseHtml( html: $this->resolveCustomFooterHtml( dashboard: $dashboard, data: $data, @@ -3271,20 +4196,34 @@ private function resolveFooterMode( $newMode = $data['dashboardFooterMode']; } - if ($newMode === null || $newMode === '') { - $newMode = Dashboard::FOOTER_MODE_INHERIT; + return self::validFooterMode(mode: $newMode); + }//end resolveFooterMode() + + /** + * A footer mode with null / empty read as `inherit`, refused unless it + * is one of the known modes. + * + * @param mixed $mode The candidate mode. + * + * @return string The mode. + * + * @throws InvalidArgumentException When the mode is unknown. + */ + private static function validFooterMode(mixed $mode): string { + if ($mode === null || $mode === '') { + $mode = Dashboard::FOOTER_MODE_INHERIT; } - if (is_string($newMode) === false - || in_array(needle: $newMode, haystack: Dashboard::FOOTER_MODES, strict: true) === false + if (is_string($mode) === false + || in_array(needle: $mode, haystack: Dashboard::FOOTER_MODES, strict: true) === false ) { throw new InvalidArgumentException( message: 'dashboardFooterMode must be one of: ' . implode(separator: ', ', array: Dashboard::FOOTER_MODES) ); } - return $newMode; - }//end resolveFooterMode() + return $mode; + }//end validFooterMode() /** * Resolve the raw custom-footer HTML an update is asking to store. @@ -3336,7 +4275,7 @@ private function resolveCustomFooterHtml( * @spec openspec/specs/dashboards/spec.md */ public function resolveFooterForDashboard(Dashboard $dashboard): ?array { - return $this->footerService->resolveFooterForDashboard(dashboard: $dashboard); + return $this->structure->footerService->resolveFooterForDashboard(dashboard: $dashboard); }//end resolveFooterForDashboard() /** @@ -3363,51 +4302,15 @@ private function applyTreeUpdates( Dashboard $dashboard, array $data, ): void { - $movingUuid = $dashboard->getUuid(); - - // Track the parent the slug uniqueness check should fire against. - $effectiveParent = $dashboard->getParentUuid(); - if (array_key_exists(key: 'parentUuid', array: $data) === true) { - $newParent = $data['parentUuid']; - if ($newParent !== null && is_string($newParent) === false) { - $newParent = (string)$newParent; - } - - // REQ-DASH-028: cycle + depth before applying. - $this->treeService->validateParent( - movingUuid: $movingUuid, - newParentUuid: $newParent - ); - - $dashboard->setParentUuid($newParent); - $effectiveParent = $newParent; + $this->applyParentUpdate(dashboard: $dashboard, newParent: $data['parentUuid']); } + // The slug uniqueness check fires against the parent as it stands + // after any re-parenting above. if (array_key_exists(key: 'slug', array: $data) === true) { - $newSlug = $data['slug']; - if ($newSlug !== null && is_string($newSlug) === false) { - $newSlug = (string)$newSlug; - } - - if ($newSlug !== null && $newSlug !== '') { - if (SlugGenerator::isValid(slug: $newSlug) === false) { - throw new InvalidArgumentException( - message: 'Slug must match [a-z0-9_-]+ and be at most 128 characters' - ); - } - - // REQ-DASH-024: per-parent uniqueness — exclude the row - // being updated so no-op writes succeed. - $this->treeService->validateSlugUnique( - parentUuid: $effectiveParent, - slug: $newSlug, - excludeUuid: $movingUuid - ); - } - - $dashboard->setSlug($newSlug); - }//end if + $this->applySlugUpdate(dashboard: $dashboard, newSlug: $data['slug']); + } if (array_key_exists(key: 'sortOrder', array: $data) === true) { $sortOrder = $data['sortOrder']; @@ -3415,6 +4318,85 @@ private function applyTreeUpdates( } }//end applyTreeUpdates() + /** + * Re-parent the dashboard after the REQ-DASH-028 cycle + depth check. + * + * @param Dashboard $dashboard The dashboard being updated. + * @param mixed $newParent The requested parent UUID (NULL for root). + * + * @return void + */ + private function applyParentUpdate(Dashboard $dashboard, mixed $newParent): void { + $newParent = $this->stringOrNull(value: $newParent); + + $this->structure->treeService->validateParent( + movingUuid: $dashboard->getUuid(), + newParentUuid: $newParent + ); + + $dashboard->setParentUuid($newParent); + }//end applyParentUpdate() + + /** + * Set the slug; a non-empty one must be well-formed and unique under the dashboard's parent. + * + * @param Dashboard $dashboard The dashboard being updated. + * @param mixed $newSlug The requested slug. + * + * @return void + * + * @throws InvalidArgumentException When the slug is malformed or taken. + */ + private function applySlugUpdate(Dashboard $dashboard, mixed $newSlug): void { + $newSlug = $this->stringOrNull(value: $newSlug); + if ($newSlug !== null && $newSlug !== '') { + $this->assertSlugAllowed(dashboard: $dashboard, slug: $newSlug); + } + + $dashboard->setSlug($newSlug); + }//end applySlugUpdate() + + /** + * Refuse a malformed slug, then one a sibling already owns. + * + * @param Dashboard $dashboard The dashboard being updated. + * @param string $slug The non-empty requested slug. + * + * @return void + * + * @throws InvalidArgumentException When the slug is malformed or taken. + */ + private function assertSlugAllowed(Dashboard $dashboard, string $slug): void { + if (SlugGenerator::isValid(slug: $slug) === false) { + throw new InvalidArgumentException( + message: 'Slug must match [a-z0-9_-]+ and be at most 128 characters' + ); + } + + // REQ-DASH-024: per-parent uniqueness — exclude the row + // being updated so no-op writes succeed. + $this->structure->treeService->validateSlugUnique( + parentUuid: $dashboard->getParentUuid(), + slug: $slug, + excludeUuid: $dashboard->getUuid() + ); + }//end assertSlugAllowed() + + /** + * The value as a string, NULL kept as NULL. + * + * @param mixed $value A payload value. + * + * @return string|null The cast value. + */ + private function stringOrNull(mixed $value): string|null { + if ($value !== null && is_string($value) === false) { + return (string)$value; + } + + return $value; + }//end stringOrNull() + /** * Assert the actor is allowed to mutate the dashboard's publication * state. REQ-DASH-031..034. diff --git a/lib/Service/DashboardShareService.php b/lib/Service/DashboardShareService.php index d20fc32b2..37227e319 100644 --- a/lib/Service/DashboardShareService.php +++ b/lib/Service/DashboardShareService.php @@ -24,20 +24,19 @@ namespace OCA\LaunchPad\Service; use DateTime; -use Exception; use InvalidArgumentException; -use OCA\LaunchPad\Activity\DashboardActivityEmitter; use OCA\LaunchPad\Db\Dashboard; use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\DashboardShare; use OCA\LaunchPad\Db\DashboardShareMapper; +use OCA\LaunchPad\Exception\ForbiddenException; +use OCP\AppFramework\Db\DoesNotExistException; use OCP\IDBConnection; -use OCP\IGroupManager; -use OCP\Notification\IManager as INotificationManager; -use Throwable; /** * Service for creating and managing dashboard shares. + * + * @spec openspec/specs/dashboard-sharing/spec.md */ class DashboardShareService { @@ -57,18 +56,18 @@ class DashboardShareService { * * @param DashboardShareMapper $shareMapper The share mapper. * @param DashboardMapper $dashboardMapper The dashboard mapper. - * @param IGroupManager $groupManager The group manager. - * @param INotificationManager $notificationManager The notification manager. * @param IDBConnection $db The DB connection. - * @param DashboardActivityEmitter|null $activity Sends dashboard_shared to the recipients (#713). + * @param ShareNotifier $notifier Announces written shares to their recipients. + * @param SharingLimits|null $limits Who may share, and with whom (REQ-SHARE-014); the + * container always injects it, null only in tests that + * construct the service by hand. */ public function __construct( private readonly DashboardShareMapper $shareMapper, private readonly DashboardMapper $dashboardMapper, - private readonly IGroupManager $groupManager, - private readonly INotificationManager $notificationManager, private readonly IDBConnection $db, - private readonly ?DashboardActivityEmitter $activity = null, + private readonly ShareNotifier $notifier, + private readonly ?SharingLimits $limits = null, ) { }//end __construct() @@ -80,7 +79,7 @@ public function __construct( * * @return DashboardShare[] The shares. * - * @throws Exception When the user is not the dashboard owner. + * @throws ForbiddenException When the user is not the dashboard owner. * * @spec openspec/specs/dashboard-sharing/spec.md */ @@ -93,44 +92,33 @@ public function listShares(int $dashboardId, string $userId): array { * Add or upsert a single share. Publishes a notification when the * entry is new or the permission level is upgraded. REQ-SHARE-008. * - * @param int $dashboardId The dashboard ID. - * @param string $shareType The share type ('user' or 'group'). - * @param string $shareWith The recipient user/group ID. - * @param string $permissionLevel The permission level. - * @param string $callerId The calling user (must be dashboard owner). + * @param int $dashboardId The dashboard ID. + * @param ShareGrant $grant Share type, recipient and permission level. + * @param string $callerId The calling user (must be dashboard owner). * * @return DashboardShare The persisted share. * - * @throws Exception When the caller is not the owner or input is invalid. + * @throws ForbiddenException When the caller is not the owner. + * @throws InvalidArgumentException When the input is invalid. * * @spec openspec/specs/dashboard-sharing/spec.md */ public function addShare( int $dashboardId, - string $shareType, - string $shareWith, - string $permissionLevel, + ShareGrant $grant, string $callerId, ): DashboardShare { $dashboard = $this->assertOwner( dashboardId: $dashboardId, userId: $callerId ); - $this->validateInput( - shareType: $shareType, - shareWith: $shareWith, - permissionLevel: $permissionLevel - ); + $this->validateInput(grant: $grant); + $this->limits?->assertMayShare(sharerId: $callerId, shareType: $grant->shareType, shareWith: $grant->shareWith); - $result = $this->persistShare( - dashboardId: $dashboardId, - shareType: $shareType, - shareWith: $shareWith, - permissionLevel: $permissionLevel - ); + $result = $this->persistShare(dashboardId: $dashboardId, grant: $grant); if ($result['isNew'] === true || $result['isUpgrade'] === true) { - $this->notifyShared( + $this->notifier->shared( share: $result['share'], sharerUserId: $callerId, dashboard: $dashboard @@ -149,18 +137,23 @@ public function addShare( * * @return void * - * @throws Exception When the share does not exist or caller is not owner. + * @throws ForbiddenException When the caller is not the owner, or the share does not exist. * * @spec openspec/specs/dashboard-sharing/spec.md */ public function removeShare(int $shareId, string $callerId): void { - $share = $this->shareMapper->find(id: $shareId); - $dashboard = $this->dashboardMapper->find( - id: (int)$share->getDashboardId() - ); + try { + $share = $this->shareMapper->find(id: $shareId); + $dashboard = $this->dashboardMapper->find( + id: (int)$share->getDashboardId() + ); + } catch (DoesNotExistException) { + // A missing share answers like someone else's, so share ids cannot be probed. + throw new ForbiddenException(message: 'Access denied'); + } if ($dashboard->getUserId() !== $callerId) { - throw new Exception(message: 'Access denied'); + throw new ForbiddenException(message: 'Access denied'); } $this->shareMapper->delete(entity: $share); @@ -171,7 +164,8 @@ public function removeShare(int $shareId, string $callerId): void { * * Deletes every existing share not in the payload, upserts matching * ones. Publishes one notification per newly-added or upgraded - * recipient only. All DB writes run in a single transaction. + * recipient only. All DB writes run in a single transaction; a database + * error is rethrown after the rollback. * * @param int $dashboardId The dashboard ID. * @param array $shares Array of {shareType, shareWith, permissionLevel}. @@ -179,8 +173,8 @@ public function removeShare(int $shareId, string $callerId): void { * * @return DashboardShare[] The new full share list. * - * @throws Exception When the caller is not the owner or input is invalid. - * @throws Throwable On DB error (rolls back). + * @throws ForbiddenException When the caller is not the owner. + * @throws InvalidArgumentException When the input is invalid. * * @spec openspec/specs/dashboard-sharing/spec.md */ @@ -195,23 +189,97 @@ public function replaceShares( ); // Validate all entries up-front before touching the DB. - foreach ($shares as $entry) { - $this->validateInput( - shareType: $entry['shareType'] ?? '', - shareWith: $entry['shareWith'] ?? '', - permissionLevel: $entry['permissionLevel'] ?? '' + $grants = $this->validatedGrants(shares: $shares); + $this->assertNewSharesAllowed(dashboardId: $dashboardId, grants: $grants, sharerId: $userId); + + $notifyQueue = $this->replaceInTransaction(dashboardId: $dashboardId, grants: $grants); + + // Publish notifications after the transaction commits. + if ($notifyQueue !== []) { + $this->notifier->sharedAll( + shares: $notifyQueue, + sharerUserId: $userId, + dashboard: $dashboard ); } - // Build the keep-key set for deletion. - $keepKeys = []; + return $this->shareMapper->findByDashboardId(dashboardId: $dashboardId); + }//end replaceShares() + + /** + * Refuse a replace that would create a share the limits do not allow. + * + * Only shares the dashboard does not already have are checked: a limit set + * later does not stop an owner saving the shares the dashboard already has. + * + * @param int $dashboardId The dashboard ID. + * @param ShareGrant[] $grants The validated grants. + * @param string $sharerId The owner saving them. + * + * @return void + * + * @throws ForbiddenException When a new share is not allowed. + * + * @spec openspec/changes/record-parity-requirements/specs/dashboard-sharing/spec.md#requirement-administrators-decide-who-may-share-and-with-whom-req-share-014 + */ + private function assertNewSharesAllowed(int $dashboardId, array $grants, string $sharerId): void { + if ($this->limits === null) { + return; + } + + $existing = []; + foreach ($this->shareMapper->findByDashboardId(dashboardId: $dashboardId) as $share) { + $existing[(string)$share->getShareType() . ':' . (string)$share->getShareWith()] = true; + } + + foreach ($grants as $grant) { + if (isset($existing[$grant->shareType . ':' . $grant->shareWith]) === false) { + $this->limits->assertMayShare(sharerId: $sharerId, shareType: $grant->shareType, shareWith: $grant->shareWith); + } + } + }//end assertNewSharesAllowed() + + /** + * Turn every payload entry into a validated grant. + * + * @param array $shares The payload entries. + * + * @return ShareGrant[] The grants, in payload order. + * + * @throws InvalidArgumentException When any entry is invalid. + */ + private function validatedGrants(array $shares): array { + $grants = []; foreach ($shares as $entry) { - $keepKeys[] = $entry['shareType'] . ':' . $entry['shareWith']; + $grant = $this->grantFrom(entry: $entry); + $this->validateInput(grant: $grant); + $grants[] = $grant; + } + + return $grants; + }//end validatedGrants() + + /** + * Replace the shares of a dashboard with the grants in one transaction. + * + * Shares whose `type:with` key is not granted are deleted first; every + * grant is then upserted. Rolls back when any step throws. + * + * @param int $dashboardId The dashboard ID. + * @param ShareGrant[] $grants The validated grants. + * + * @return DashboardShare[] The new and upgraded shares to notify. + */ + private function replaceInTransaction(int $dashboardId, array $grants): array { + $keepKeys = []; + foreach ($grants as $grant) { + $keepKeys[] = $grant->shareType . ':' . $grant->shareWith; } $notifyQueue = []; $this->db->beginTransaction(); + $committed = false; try { // Remove shares not in payload. $this->shareMapper->deleteNotIn( @@ -219,37 +287,23 @@ public function replaceShares( keepKeys: $keepKeys ); - // Upsert each entry. - foreach ($shares as $entry) { - $result = $this->persistShare( - dashboardId: $dashboardId, - shareType: $entry['shareType'], - shareWith: $entry['shareWith'], - permissionLevel: $entry['permissionLevel'] - ); - + foreach ($grants as $grant) { + $result = $this->persistShare(dashboardId: $dashboardId, grant: $grant); if ($result['isNew'] === true || $result['isUpgrade'] === true) { $notifyQueue[] = $result['share']; } } $this->db->commit(); - } catch (Throwable $t) { - $this->db->rollBack(); - throw $t; + $committed = true; + } finally { + if ($committed === false) { + $this->db->rollBack(); + } }//end try - // Publish notifications after the transaction commits. - foreach ($notifyQueue as $share) { - $this->notifyShared( - share: $share, - sharerUserId: $userId, - dashboard: $dashboard - ); - } - - return $this->shareMapper->findByDashboardId(dashboardId: $dashboardId); - }//end replaceShares() + return $notifyQueue; + }//end replaceInTransaction() /** * Remove every share where the caller is the owner AND the share targets @@ -362,6 +416,20 @@ public function transferOwnership(int $dashboardId, string $newUserId): void { } }//end transferOwnership() + /** + * The user dashboards a person owns, oldest first (REQ-SHARE-016: the + * dashboards a leaver's handover moves). + * + * @param string $userId The owner. + * + * @return Dashboard[] The dashboards. + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + public function ownedDashboards(string $userId): array { + return $this->dashboardMapper->findByUserId(userId: $userId); + }//end ownedDashboards() + /** * Publish a `dashboard_ownership_transferred` notification. * @@ -378,70 +446,75 @@ public function notifyOwnershipTransferred( int $dashboardId, string $dashboardName, ): void { - $notification = $this->notificationManager->createNotification(); - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - $notification->setApp('launchpad') - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - ->setUser($newOwnerId) - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - ->setDateTime(new DateTime()) - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - ->setObject('dashboard', (string)$dashboardId) - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - ->setSubject('dashboard_ownership_transferred', [$dashboardName]); - - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - $this->notificationManager->notify($notification); + $this->notifier->ownershipTransferred( + newOwnerId: $newOwnerId, + dashboardId: $dashboardId, + dashboardName: $dashboardName + ); }//end notifyOwnershipTransferred() /** * Persist a single share (insert or update). Returns metadata about * whether the row is new or the level was upgraded. * - * @param int $dashboardId The dashboard ID. - * @param string $shareType The share type. - * @param string $shareWith The recipient. - * @param string $permissionLevel The permission level. + * @param int $dashboardId The dashboard ID. + * @param ShareGrant $grant Share type, recipient and permission level. * * @return array{share: DashboardShare, isNew: bool, isUpgrade: bool} */ - private function persistShare( - int $dashboardId, - string $shareType, - string $shareWith, - string $permissionLevel, - ): array { - $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); + private function persistShare(int $dashboardId, ShareGrant $grant): array { $existing = $this->shareMapper->findShare( dashboardId: $dashboardId, - shareType: $shareType, - shareWith: $shareWith + shareType: $grant->shareType, + shareWith: $grant->shareWith ); if ($existing === null) { - // Insert new share. - $share = new DashboardShare(); - $share->setDashboardId($dashboardId); - $share->setShareType($shareType); - $share->setShareWith($shareWith); - $share->setPermissionLevel($permissionLevel); - $share->setCreatedAt($now); - $share->setUpdatedAt($now); - return [ - 'share' => $this->shareMapper->insert(entity: $share), + 'share' => $this->insertShare(dashboardId: $dashboardId, grant: $grant), 'isNew' => true, 'isUpgrade' => false, ]; } - // Detect upgrade. - $oldLevel = (string)$existing->getPermissionLevel(); - $newOrder = (self::LEVEL_ORDER[$permissionLevel] ?? 0); - $oldOrder = (self::LEVEL_ORDER[$oldLevel] ?? 0); - $isUpgrade = ($newOrder > $oldOrder); + return $this->changeLevel(existing: $existing, permissionLevel: $grant->permissionLevel); + }//end persistShare() + + /** + * Insert a new share row for a grant. + * + * @param int $dashboardId The dashboard ID. + * @param ShareGrant $grant The validated grant. + * + * @return DashboardShare The inserted share. + */ + private function insertShare(int $dashboardId, ShareGrant $grant): DashboardShare { + $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); + + $share = new DashboardShare(); + $share->setDashboardId($dashboardId); + $share->setShareType($grant->shareType); + $share->setShareWith($grant->shareWith); + $share->setPermissionLevel($grant->permissionLevel); + $share->setCreatedAt($now); + $share->setUpdatedAt($now); + + return $this->shareMapper->insert(entity: $share); + }//end insertShare() - // No-op: same level. + /** + * Move an existing share to a permission level. + * + * The same level is a no-op; a different level is written, and flagged + * as an upgrade only when it ranks higher than the old one. + * + * @param DashboardShare $existing The existing share. + * @param string $permissionLevel The requested level. + * + * @return array{share: DashboardShare, isNew: bool, isUpgrade: bool} + */ + private function changeLevel(DashboardShare $existing, string $permissionLevel): array { + $oldLevel = (string)$existing->getPermissionLevel(); if ($oldLevel === $permissionLevel) { return [ 'share' => $existing, @@ -450,130 +523,64 @@ private function persistShare( ]; } - // Update level. + $isUpgrade = ((self::LEVEL_ORDER[$permissionLevel] ?? 0) > (self::LEVEL_ORDER[$oldLevel] ?? 0)); + $existing->setPermissionLevel($permissionLevel); - $existing->setUpdatedAt($now); + $existing->setUpdatedAt((new DateTime())->format(format: 'Y-m-d H:i:s')); return [ 'share' => $this->shareMapper->update(entity: $existing), 'isNew' => false, 'isUpgrade' => $isUpgrade, ]; - }//end persistShare() + }//end changeLevel() /** - * Publish `dashboard_shared` notifications for a share. + * Read one entry of a share replace as a grant: an object whose + * shareType, shareWith and permissionLevel, when present, are strings. + * A missing field reads as an empty string, which + * {@see self::validateInput()} then rejects. * - * For `user`-type shares: one notification. - * For `group`-type shares: fan out one notification per current group - * member, excluding the sharer. REQ-SHARE-008. + * @param array|string|int|float|bool|null $entry The entry from the request. * - * @param DashboardShare $share The share row. - * @param string $sharerUserId The user who created the share. - * @param Dashboard $dashboard The shared dashboard. + * @return ShareGrant The grant. * - * @return void + * @throws InvalidArgumentException When the entry is not an object or a field is not a string. */ - private function notifyShared( - DashboardShare $share, - string $sharerUserId, - Dashboard $dashboard, - ): void { - $dashboardName = (string)$dashboard->getName(); - $recipients = $this->resolveRecipients( - share: $share, - excludeUserId: $sharerUserId - ); - - // The activity stream and digest get the same audience as the - // notification (engagement-activity-digest D2, issue #713). - $this->activity?->shared( - dashboard: $dashboard, - share: $share, - actor: $sharerUserId, - recipients: $recipients - ); - - foreach ($recipients as $recipientId) { - $notification = $this->notificationManager->createNotification(); - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - $notification->setApp('launchpad') - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - ->setUser($recipientId) - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - ->setDateTime(new DateTime()) - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - ->setObject('dashboard', (string)$share->getDashboardId()) - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - ->setSubject( - 'dashboard_shared', - [ - $sharerUserId, - $dashboardName, - (string)$share->getPermissionLevel(), - ] - ); - - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - $this->notificationManager->notify($notification); - }//end foreach - }//end notifyShared() - - /** - * Resolve the recipient user IDs for a share. - * - * @param DashboardShare $share The share. - * @param string $excludeUserId A user ID to exclude (the sharer). - * - * @return string[] The recipient user IDs. - */ - private function resolveRecipients( - DashboardShare $share, - string $excludeUserId, - ): array { - if ($share->getShareType() === DashboardShare::SHARE_TYPE_USER) { - $uid = (string)$share->getShareWith(); - if ($uid === $excludeUserId) { - return []; - } - - return [$uid]; + private function grantFrom(array|string|int|float|bool|null $entry): ShareGrant { + if (is_array($entry) === false) { + throw new InvalidArgumentException(message: 'Each share must be an object'); } - // Group share — expand members. - $groupId = (string)$share->getShareWith(); - $group = $this->groupManager->get(gid: $groupId); - if ($group === null) { - return []; - } - - $recipients = []; - foreach ($group->getUsers() as $user) { - $uid = $user->getUID(); - if ($uid !== $excludeUserId) { - $recipients[] = $uid; + $fields = []; + foreach (['shareType', 'shareWith', 'permissionLevel'] as $field) { + $value = $entry[$field] ?? ''; + if (is_string($value) === false) { + throw new InvalidArgumentException(message: $field . ' must be a string'); } + + $fields[$field] = $value; } - return $recipients; - }//end resolveRecipients() + return new ShareGrant( + shareType: $fields['shareType'], + shareWith: $fields['shareWith'], + permissionLevel: $fields['permissionLevel'] + ); + }//end grantFrom() /** * Validate share type, shareWith, and permission level. * - * @param string $shareType The share type. - * @param string $shareWith The recipient. - * @param string $permissionLevel The permission level. + * @param ShareGrant $grant Share type, recipient and permission level. * * @return void * * @throws InvalidArgumentException On invalid input. */ - private function validateInput( - string $shareType, - string $shareWith, - string $permissionLevel, - ): void { + private function validateInput(ShareGrant $grant): void { + $shareType = $grant->shareType; + $permissionLevel = $grant->permissionLevel; $validType = in_array( needle: $shareType, haystack: DashboardShare::VALID_SHARE_TYPES, @@ -585,7 +592,7 @@ private function validateInput( ); } - if ($shareWith === '') { + if ($grant->shareWith === '') { throw new InvalidArgumentException(message: 'shareWith is required'); } @@ -609,13 +616,13 @@ private function validateInput( * * @return Dashboard The dashboard. * - * @throws Exception When the user is not the owner. + * @throws ForbiddenException When the user is not the owner. */ private function assertOwner(int $dashboardId, string $userId): Dashboard { $dashboard = $this->dashboardMapper->find(id: $dashboardId); if ($dashboard->getUserId() !== $userId) { - throw new Exception(message: 'Access denied'); + throw new ForbiddenException(message: 'Access denied'); } return $dashboard; diff --git a/lib/Service/DashboardStores.php b/lib/Service/DashboardStores.php new file mode 100644 index 000000000..cff009303 --- /dev/null +++ b/lib/Service/DashboardStores.php @@ -0,0 +1,55 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCA\LaunchPad\Db\DashboardLockMapper; +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; + +/** + * The tables DashboardService reads and writes: dashboards, placements, admin settings and locks. + * + * @spec openspec/specs/dashboards/spec.md + */ +class DashboardStores { + /** + * Constructor. + * + * @param DashboardMapper $dashboardMapper Dashboard mapper. + * @param WidgetPlacementMapper $placementMapper Widget placement mapper. + * @param AdminSettingMapper $settingMapper Admin setting mapper. + * @param DashboardLockMapper|null $lockMapper Optional lock mapper. When provided the delete path cascades + * the row removal to the editing-lock table per REQ-LOCK-008. + * Nullable to keep the constructor backwards- compatible with + * existing unit tests. + */ + public function __construct( + public readonly DashboardMapper $dashboardMapper, + public readonly WidgetPlacementMapper $placementMapper, + public readonly AdminSettingMapper $settingMapper, + public readonly ?DashboardLockMapper $lockMapper=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/DashboardStructure.php b/lib/Service/DashboardStructure.php new file mode 100644 index 000000000..8ec2500ed --- /dev/null +++ b/lib/Service/DashboardStructure.php @@ -0,0 +1,58 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The tree, the personal layer, the translations and the footer of a dashboard. + * + * @spec openspec/specs/dashboards/spec.md + */ +class DashboardStructure { + /** + * Constructor. + * + * @param DashboardTreeService $treeService Tree-aware validation / cascade walker + * (REQ-DASH-023..030). + * @param PersonalLayerService $personalLayers Lays a reader's own arrangement over a dashboard + * somebody else owns (REQ-DWMS-001). Required, not + * nullable: a null here is indistinguishable from a + * reader who has no layer, so broken wiring would + * store layers and show none of them, in silence and + * with every test green. + * @param DashboardTranslationService|null $translationService Optional translation service for the + * per-language content variants + * (REQ-DASH-038..044). Nullable so legacy test + * doubles constructed without it keep working. + * @param FooterService|null $footerService Optional per-dashboard footer sanitiser + resolver + * (REQ-FTR-006). Nullable for backwards- compat with + * existing test doubles. + */ + public function __construct( + public readonly DashboardTreeService $treeService, + public readonly PersonalLayerService $personalLayers, + public readonly ?DashboardTranslationService $translationService=null, + public readonly ?FooterService $footerService=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/DashboardTranslationService.php b/lib/Service/DashboardTranslationService.php index 2784ebcd0..cbfe33e3d 100644 --- a/lib/Service/DashboardTranslationService.php +++ b/lib/Service/DashboardTranslationService.php @@ -53,7 +53,7 @@ class DashboardTranslationService { * * @var string */ - public const ERR_LAST_VARIANT = 'Cannot delete the only language variant'; + public const ERR_LAST_VARIANT = 'Cannot delete the only language variant. Promote another variant to primary first.'; /** * Sentinel error message: cannot delete the primary variant directly @@ -154,19 +154,8 @@ public function listAvailableLanguages(string $dashboardUuid): array { public function resolveForLocale( string $dashboardUuid, string $preferredLanguage, - ): ?array { - $normalised = DashboardTranslationMapper::normaliseLanguageCode( - raw: $preferredLanguage - ); - - $exact = null; - if ($normalised !== '') { - $exact = $this->translationMapper->findByDashboardUuidAndLanguage( - dashboardUuid: $dashboardUuid, - languageCode: $normalised - ); - } - + ): array|null { + $exact = $this->exactVariant(dashboardUuid: $dashboardUuid, preferredLanguage: $preferredLanguage); if ($exact !== null) { return [ 'translation' => $exact, @@ -187,6 +176,29 @@ public function resolveForLocale( ]; }//end resolveForLocale() + /** + * The variant in exactly the preferred language; null when the + * language normalises to nothing or has no variant. + * + * @param string $dashboardUuid The dashboard UUID. + * @param string $preferredLanguage The caller's raw language preference. + * + * @return DashboardTranslation|null The variant, or null. + */ + private function exactVariant(string $dashboardUuid, string $preferredLanguage): DashboardTranslation|null { + $normalised = DashboardTranslationMapper::normaliseLanguageCode( + raw: $preferredLanguage + ); + if ($normalised === '') { + return null; + } + + return $this->translationMapper->findByDashboardUuidAndLanguage( + dashboardUuid: $dashboardUuid, + languageCode: $normalised + ); + }//end exactVariant() + /** * Auto-seed a primary translation for a freshly-created dashboard. * @@ -223,23 +235,24 @@ public function seedPrimaryFor(Dashboard $dashboard): DashboardTranslation { return $existing; } - $language = $this->resolveOwnerLocale( - userId: $dashboard->getUserId() - ); + $translation = $this->materialiseLegacyVariant(dashboard: $dashboard); + self::stampCreated(translation: $translation); + return $this->translationMapper->insert(entity: $translation); + }//end seedPrimaryFor() + + /** + * Stamp a new translation's created and updated time with now. + * + * @param DashboardTranslation $translation The new translation. + * + * @return void + */ + private static function stampCreated(DashboardTranslation $translation): void { $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); - $translation = new DashboardTranslation(); - $translation->setDashboardUuid($uuid); - $translation->setLanguageCode($language); - $translation->setName($dashboard->getName()); - $translation->setDescription($dashboard->getDescription()); - $translation->setWidgetTreeJson(null); - $translation->setIsPrimary(1); $translation->setCreatedAt($now); $translation->setUpdatedAt($now); - - return $this->translationMapper->insert(entity: $translation); - }//end seedPrimaryFor() + }//end stampCreated() /** * Create a new translation variant for a dashboard, optionally @@ -248,13 +261,11 @@ public function seedPrimaryFor(Dashboard $dashboard): DashboardTranslation { * @param string $dashboardUuid The dashboard UUID. * @param string $languageCode The (raw) language code; will * be normalised before storage. - * @param string|null $name Optional explicit name. - * @param string|null $description Optional explicit description. - * @param string|null $widgetTreeJson Optional explicit tree JSON. - * @param string|null $copyFromLanguage Optional language code to seed - * from (`'primary'` or another - * language); defaults to the - * primary variant when null. + * @param array $content Optional `name`, `description` and + * `widgetTreeJson` (explicit values win over the + * seed) and `copyFromLanguage`, the language code + * to seed from (`'primary'` or another language; + * the primary variant when null). * * @return DashboardTranslation The created variant. * @@ -265,14 +276,31 @@ public function seedPrimaryFor(Dashboard $dashboard): DashboardTranslation { * * @spec openspec/specs/dashboard-language-content/spec.md */ - public function createVariant( - string $dashboardUuid, - string $languageCode, - ?string $name = null, - ?string $description = null, - ?string $widgetTreeJson = null, - ?string $copyFromLanguage = null, - ): DashboardTranslation { + public function createVariant(string $dashboardUuid, string $languageCode, array $content=[]): DashboardTranslation { + $content += ['name' => null, 'description' => null, 'widgetTreeJson' => null, 'copyFromLanguage' => null]; + + $translation = new DashboardTranslation(); + $translation->setDashboardUuid($dashboardUuid); + $translation->setLanguageCode($this->unusedLanguageCode(dashboardUuid: $dashboardUuid, languageCode: $languageCode)); + $this->fillVariantContent(translation: $translation, content: $content); + $translation->setIsPrimary(0); + self::stampCreated(translation: $translation); + + return $this->translationMapper->insert(entity: $translation); + }//end createVariant() + + /** + * The normalised language code of a new variant. + * + * @param string $dashboardUuid The dashboard UUID. + * @param string $languageCode The requested language code. + * + * @return string The normalised code. + * + * @throws InvalidArgumentException When the code normalises to nothing. + * @throws Exception When the dashboard already has that language. + */ + private function unusedLanguageCode(string $dashboardUuid, string $languageCode): string { $normalised = DashboardTranslationMapper::normaliseLanguageCode( raw: $languageCode ); @@ -290,36 +318,40 @@ public function createVariant( throw new Exception(message: self::ERR_LANGUAGE_EXISTS); } + return $normalised; + }//end unusedLanguageCode() + + /** + * Fill a new variant's name, description and widget tree: each given + * value, else the seed's (the primary or the `copyFromLanguage` variant). + * + * @param DashboardTranslation $translation The new variant. + * @param array $content The given content and `copyFromLanguage`. + * + * @return void + */ + private function fillVariantContent(DashboardTranslation $translation, array $content): void { $seed = $this->resolveSeed( - dashboardUuid: $dashboardUuid, - copyFromLanguage: $copyFromLanguage + dashboardUuid: (string)$translation->getDashboardUuid(), + copyFromLanguage: $content['copyFromLanguage'] ); - $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); - $translation = new DashboardTranslation(); - $translation->setDashboardUuid($dashboardUuid); - $translation->setLanguageCode($normalised); $translation->setName( - $this->coalesce(value: $name, fallback: $seed?->getName()) + $this->coalesce(value: $content['name'], fallback: $seed?->getName()) ); $translation->setDescription( $this->coalesce( - value: $description, + value: $content['description'], fallback: $seed?->getDescription() ) ); $translation->setWidgetTreeJson( $this->coalesce( - value: $widgetTreeJson, + value: $content['widgetTreeJson'], fallback: $seed?->getWidgetTreeJson() ) ); - $translation->setIsPrimary(0); - $translation->setCreatedAt($now); - $translation->setUpdatedAt($now); - - return $this->translationMapper->insert(entity: $translation); - }//end createVariant() + }//end fillVariantContent() /** * Update an existing translation variant. @@ -391,10 +423,8 @@ public function deleteVariant( languageCode: $languageCode ); - if ((int)$translation->getIsPrimary() === 1) { - throw new Exception(message: self::ERR_DELETE_PRIMARY); - } - + // REQ-DASH-042: the only variant is also the primary; it is refused + // as the only one. $count = $this->translationMapper->countByDashboardUuid( dashboardUuid: $dashboardUuid ); @@ -402,6 +432,10 @@ public function deleteVariant( throw new Exception(message: self::ERR_LAST_VARIANT); } + if ((int)$translation->getIsPrimary() === 1) { + throw new Exception(message: self::ERR_DELETE_PRIMARY); + } + $this->translationMapper->delete(entity: $translation); }//end deleteVariant() @@ -436,17 +470,7 @@ public function promoteVariantToPrimary( $this->db->beginTransaction(); try { - $this->translationMapper->clearPrimary( - dashboardUuid: $dashboardUuid, - exceptId: $translation->getId() - ); - $translation->setIsPrimary(1); - $translation->setUpdatedAt( - (new DateTime())->format(format: 'Y-m-d H:i:s') - ); - $updated = $this->translationMapper->update( - entity: $translation - ); + $updated = $this->makePrimary(translation: $translation, dashboardUuid: $dashboardUuid); $this->db->commit(); return $updated; } catch (Throwable $t) { @@ -455,6 +479,29 @@ public function promoteVariantToPrimary( } }//end promoteVariantToPrimary() + /** + * Clear the other primary rows of the dashboard and flag this one. + * + * @param DashboardTranslation $translation The variant to promote. + * @param string $dashboardUuid The dashboard UUID. + * + * @return DashboardTranslation The updated variant. + */ + private function makePrimary(DashboardTranslation $translation, string $dashboardUuid): DashboardTranslation { + $this->translationMapper->clearPrimary( + dashboardUuid: $dashboardUuid, + exceptId: $translation->getId() + ); + $translation->setIsPrimary(1); + $translation->setUpdatedAt( + (new DateTime())->format(format: 'Y-m-d H:i:s') + ); + + return $this->translationMapper->update( + entity: $translation + ); + }//end makePrimary() + /** * Cascade-delete every translation variant for a dashboard. Called * from the dashboard delete path so the translation rows do not @@ -510,7 +557,7 @@ public function materialiseLegacyVariant( * * @return string The normalised language code. */ - private function resolveOwnerLocale(?string $userId): string { + private function resolveOwnerLocale(string|null $userId): string { if ($userId === null || $userId === '') { return DashboardTranslation::DEFAULT_LANGUAGE; } @@ -545,8 +592,8 @@ private function resolveOwnerLocale(?string $userId): string { */ private function resolveSeed( string $dashboardUuid, - ?string $copyFromLanguage, - ): ?DashboardTranslation { + string|null $copyFromLanguage, + ): DashboardTranslation|null { if ($copyFromLanguage === null || $copyFromLanguage === '' || strtolower($copyFromLanguage) === 'primary' diff --git a/lib/Service/DashboardTreeService.php b/lib/Service/DashboardTreeService.php index 9149a9161..1e417224e 100644 --- a/lib/Service/DashboardTreeService.php +++ b/lib/Service/DashboardTreeService.php @@ -134,10 +134,10 @@ public function __construct( * @spec openspec/specs/dashboard-switcher/spec.md */ public function validateParent( - ?string $movingUuid, - ?string $newParentUuid, + string|null $movingUuid, + string|null $newParentUuid, ): void { - if ($newParentUuid === null || $newParentUuid === '') { + if (self::isBlank(uuid: $newParentUuid) === true) { // Root-level placement is always legal. return; } @@ -149,15 +149,7 @@ public function validateParent( ); } - try { - $parent = $this->dashboardMapper->findByUuid( - uuid: $newParentUuid - ); - } catch (DoesNotExistException) { - throw new InvalidArgumentException( - message: self::ERR_PARENT_NOT_FOUND - ); - } + $parent = $this->findParent(parentUuid: (string)$newParentUuid); $this->assertNotDescendant( movingUuid: $movingUuid, @@ -170,6 +162,38 @@ public function validateParent( ); }//end validateParent() + /** + * The proposed parent dashboard. + * + * @param string $parentUuid The proposed parent UUID. + * + * @return Dashboard The parent. + * + * @throws InvalidArgumentException When no dashboard has that UUID. + */ + private function findParent(string $parentUuid): Dashboard { + try { + return $this->dashboardMapper->findByUuid( + uuid: $parentUuid + ); + } catch (DoesNotExistException) { + throw new InvalidArgumentException( + message: self::ERR_PARENT_NOT_FOUND + ); + } + }//end findParent() + + /** + * Whether a UUID is missing: null or empty. + * + * @param string|null $uuid The UUID. + * + * @return bool True when null or empty. + */ + private static function isBlank(string|null $uuid): bool { + return $uuid === null || $uuid === ''; + }//end isBlank() + /** * Validate that a slug is unique within its parent scope. * @@ -343,7 +367,7 @@ public function resolvePath(string $path): ?Dashboard { * @spec openspec/specs/dashboard-switcher/spec.md */ public function buildTree( - ?string $parentUuid, + string|null $parentUuid, int $depth = 0, ): array { if ($depth >= Dashboard::MAX_DEPTH) { @@ -356,27 +380,54 @@ public function buildTree( ); foreach ($children as $child) { - $childUuid = $child->getUuid(); - $childTree = []; - if ($childUuid !== null && $childUuid !== '') { - $childTree = $this->buildTree( - parentUuid: $childUuid, - depth: ($depth + 1) - ); - } - - $nodes[] = [ - 'uuid' => $childUuid, - 'name' => $child->getName(), - 'slug' => $child->getSlug(), - 'sortOrder' => (int)$child->getSortOrder(), - 'children' => $childTree, - ]; + $nodes[] = self::treeNode( + child: $child, + children: $this->childTree(child: $child, depth: $depth) + ); } return $nodes; }//end buildTree() + /** + * The subtree below a child at the given depth; none for a child + * without a UUID. + * + * @param Dashboard $child The child dashboard. + * @param int $depth The depth of the child's level. + * + * @return array + */ + private function childTree(Dashboard $child, int $depth): array { + $childUuid = $child->getUuid(); + if (self::isBlank(uuid: $childUuid) === true) { + return []; + } + + return $this->buildTree( + parentUuid: $childUuid, + depth: ($depth + 1) + ); + }//end childTree() + + /** + * One tree node: the dashboard's identity and its children. + * + * @param Dashboard $child The dashboard. + * @param array $children The nodes below it. + * + * @return array{uuid: ?string, name: ?string, slug: ?string, sortOrder: int, children: array} + */ + private static function treeNode(Dashboard $child, array $children): array { + return [ + 'uuid' => $child->getUuid(), + 'name' => $child->getName(), + 'slug' => $child->getSlug(), + 'sortOrder' => (int)$child->getSortOrder(), + 'children' => $children, + ]; + }//end treeNode() + /** * Build the full tree of root-level dashboards. * @@ -409,7 +460,7 @@ public function getFullTree(): array { */ public function getFilteredTree(array $visibleUuids): array { return $this->buildFilteredTree( - parentUuid: null, + level: new TreeLevel(parentUuid: null, depth: 0), visibleUuids: $visibleUuids ); }//end getFilteredTree() @@ -417,51 +468,30 @@ public function getFilteredTree(array $visibleUuids): array { /** * Internal recursive helper for getFilteredTree(). * - * @param string|null $parentUuid The parent UUID (null for roots). + * @param TreeLevel $level The parent and depth of this level. * @param array $visibleUuids Allowed UUID map. - * @param int $depth Recursion depth guard. * * @return array */ - private function buildFilteredTree( - ?string $parentUuid, - array $visibleUuids, - int $depth = 0, - ): array { - if ($depth >= Dashboard::MAX_DEPTH) { + private function buildFilteredTree(TreeLevel $level, array $visibleUuids): array { + if ($level->isBeyondCap() === true) { return []; } $nodes = []; - $children = $this->dashboardMapper->findByParent( - parentUuid: $parentUuid - ); - - foreach ($children as $child) { - $childUuid = $child->getUuid(); + foreach ($this->dashboardMapper->findByParent(parentUuid: $level->parentUuid) as $child) { + $childUuid = (string)$child->getUuid(); // Skip nodes the caller cannot see. - if ($childUuid === null - || $childUuid === '' - || isset($visibleUuids[$childUuid]) === false - ) { + if ($childUuid === '' || isset($visibleUuids[$childUuid]) === false) { continue; } - $childTree = $this->buildFilteredTree( - parentUuid: $childUuid, - visibleUuids: $visibleUuids, - depth: ($depth + 1) + $nodes[] = self::treeNode( + child: $child, + children: $this->buildFilteredTree(level: $level->below(childUuid: $childUuid), visibleUuids: $visibleUuids) ); - - $nodes[] = [ - 'uuid' => $childUuid, - 'name' => $child->getName(), - 'slug' => $child->getSlug(), - 'sortOrder' => (int)$child->getSortOrder(), - 'children' => $childTree, - ]; - }//end foreach + } return $nodes; }//end buildFilteredTree() @@ -482,37 +512,9 @@ private function buildFilteredTree( * @spec openspec/specs/dashboard-switcher/spec.md */ public function deleteSubtree(Dashboard $dashboard): int { - $rootUuid = (string)$dashboard->getUuid(); - $deleted = 0; - $this->db->beginTransaction(); try { - $descendants = []; - if ($rootUuid !== '') { - $descendants = $this->dashboardMapper->findDescendants( - ancestorUuid: $rootUuid - ); - } - - $deletedAt = new DateTimeImmutable(); - - // Delete leaves first (descendants reverse order) so that the - // adjacency-list invariants stay consistent during the walk. - foreach (array_reverse($descendants) as $child) { - $this->deleteDashboardWithPlacements( - target: $child, - fallback: $dashboard, - deletedAt: $deletedAt - ); - $deleted++; - }//end foreach - - $this->deleteDashboardWithPlacements( - target: $dashboard, - fallback: $dashboard, - deletedAt: $deletedAt - ); - $deleted++; + $deleted = $this->deleteLeavesFirst(dashboard: $dashboard); $this->db->commit(); } catch (\Throwable $t) { @@ -523,28 +525,53 @@ public function deleteSubtree(Dashboard $dashboard): int { return $deleted; }//end deleteSubtree() + /** + * Delete the descendants of a dashboard, leaves first, then the + * dashboard itself. + * + * Leaves go first (descendants in reverse order) so that the + * adjacency-list invariants stay consistent during the walk. + * + * @param Dashboard $dashboard The subtree root. + * + * @return int The number of dashboards deleted. + */ + private function deleteLeavesFirst(Dashboard $dashboard): int { + $rootUuid = (string)$dashboard->getUuid(); + $descendants = []; + if ($rootUuid !== '') { + $descendants = $this->dashboardMapper->findDescendants( + ancestorUuid: $rootUuid + ); + } + + $deletion = new SubtreeDeletion(root: $dashboard, deletedAt: new DateTimeImmutable()); + foreach (array_reverse($descendants) as $child) { + $this->deleteDashboardWithPlacements(target: $child, deletion: $deletion); + } + + $this->deleteDashboardWithPlacements(target: $dashboard, deletion: $deletion); + + return (count($descendants) + 1); + }//end deleteLeavesFirst() + /** * Delete one dashboard, its widget placements, and announce the removal. * * Shared by the descendant walk and the subtree root. Owner and type - * are read off the target and fall back to `$fallback` (the subtree - * root) when the row does not carry them — a root passes itself as its - * own fallback, which collapses to reading its own values. + * are read off the target and fall back to the subtree root when the + * row does not carry them — for the root itself that collapses to + * reading its own values. * * The event is only dispatched when a dispatcher is wired and the * dashboard carries a non-empty UUID (REQ-CSC-001). * - * @param Dashboard $target The dashboard to remove. - * @param Dashboard $fallback Source of owner/type when the target lacks them. - * @param DateTimeImmutable $deletedAt The timestamp shared by the whole cascade. + * @param Dashboard $target The dashboard to remove. + * @param SubtreeDeletion $deletion The subtree root and the timestamp shared by the whole cascade. * * @return void */ - private function deleteDashboardWithPlacements( - Dashboard $target, - Dashboard $fallback, - DateTimeImmutable $deletedAt, - ): void { + private function deleteDashboardWithPlacements(Dashboard $target, SubtreeDeletion $deletion): void { $targetId = $target->getId(); if ($targetId !== null) { $this->placementMapper->deleteByDashboardId( @@ -555,19 +582,36 @@ private function deleteDashboardWithPlacements( $this->dashboardMapper->delete(entity: $target); // SB1 fix: dispatch cascade event (REQ-CSC-001). + $this->dispatchDeleted(target: $target, deletion: $deletion); + }//end deleteDashboardWithPlacements() + + /** + * Dispatch the cascade event of a deleted dashboard; skipped without + * a dispatcher or a UUID. The owner and type fall back to the subtree + * root's. + * + * @param Dashboard $target The deleted dashboard. + * @param SubtreeDeletion $deletion The subtree delete it is part of. + * + * @return void + */ + private function dispatchDeleted(Dashboard $target, SubtreeDeletion $deletion): void { $targetUuid = (string)$target->getUuid(); - if ($this->eventDispatcher !== null && $targetUuid !== '') { - $this->eventDispatcher->dispatchTyped( - new DashboardDeletedEvent( - dashboardUuid: $targetUuid, - ownerUserId: (string)($target->getUserId() ?? $fallback->getUserId() ?? ''), - type: (string)($target->getType() ?? $fallback->getType() ?? Dashboard::TYPE_USER), - deletedAt: $deletedAt, - dashboardId: $targetId - ) - ); + if ($this->eventDispatcher === null || $targetUuid === '') { + return; } - }//end deleteDashboardWithPlacements() + + $fallback = $deletion->root; + $this->eventDispatcher->dispatchTyped( + new DashboardDeletedEvent( + dashboardUuid: $targetUuid, + ownerUserId: (string)($target->getUserId() ?? $fallback->getUserId() ?? ''), + type: (string)($target->getType() ?? $fallback->getType() ?? Dashboard::TYPE_USER), + deletedAt: $deletion->deletedAt, + dashboardId: $target->getId() + ) + ); + }//end dispatchDeleted() /** * Reject a parent that is a descendant of the moving dashboard @@ -586,46 +630,46 @@ private function deleteDashboardWithPlacements( * @throws InvalidArgumentException When the parent is a descendant. */ private function assertNotDescendant( - ?string $movingUuid, + string|null $movingUuid, Dashboard $parent, ): void { - if ($movingUuid === null || $movingUuid === '') { - return; - } - $parentUuid = $parent->getUuid(); - if ($parentUuid === null || $parentUuid === '') { + if (self::isBlank(uuid: $movingUuid) === true || self::isBlank(uuid: $parentUuid) === true) { return; } // Walk parent's ancestor chain — the moving uuid MUST NOT appear. - $ancestors = $this->dashboardMapper->findAncestors( - uuid: $parentUuid - ); - - foreach ($ancestors as $ancestor) { - if ($ancestor->getUuid() === $movingUuid) { - throw new InvalidArgumentException( - message: self::ERR_CYCLE_DETECTED - ); - } + $ancestors = $this->dashboardMapper->findAncestors(uuid: (string)$parentUuid); + if (self::containsUuid(dashboards: $ancestors, uuid: (string)$movingUuid) === true) { + throw new InvalidArgumentException(message: self::ERR_CYCLE_DETECTED); } // Also walk the moving dashboard's descendants — if the proposed // parent appears there, the assignment is a cycle on the other // side of the chain. - $descendants = $this->dashboardMapper->findDescendants( - ancestorUuid: $movingUuid - ); + $descendants = $this->dashboardMapper->findDescendants(ancestorUuid: (string)$movingUuid); + if (self::containsUuid(dashboards: $descendants, uuid: (string)$parentUuid) === true) { + throw new InvalidArgumentException(message: self::ERR_CYCLE_DETECTED); + } + }//end assertNotDescendant() - foreach ($descendants as $descendant) { - if ($descendant->getUuid() === $parentUuid) { - throw new InvalidArgumentException( - message: self::ERR_CYCLE_DETECTED - ); + /** + * Whether one of the dashboards has the UUID. + * + * @param Dashboard[] $dashboards The dashboards. + * @param string $uuid The UUID to look for. + * + * @return bool True when found. + */ + private static function containsUuid(array $dashboards, string $uuid): bool { + foreach ($dashboards as $dashboard) { + if ($dashboard->getUuid() === $uuid) { + return true; } } - }//end assertNotDescendant() + + return false; + }//end containsUuid() /** * Reject a parent assignment that would push the resulting tree @@ -645,32 +689,25 @@ private function assertNotDescendant( * @throws InvalidArgumentException When the cap would be exceeded. */ private function assertDepthWithinCap( - ?string $movingUuid, + string|null $movingUuid, Dashboard $parent, ): void { $parentUuid = $parent->getUuid(); - if ($parentUuid === null || $parentUuid === '') { + if (self::isBlank(uuid: $parentUuid) === true) { return; } $parentDepth = (count( $this->dashboardMapper->findAncestors( - uuid: $parentUuid + uuid: (string)$parentUuid ) ) + 1); - $movingSubtreeDepth = 0; - if ($movingUuid !== null && $movingUuid !== '') { - $movingSubtreeDepth = $this->measureSubtreeDepth( - rootUuid: $movingUuid - ); - } - // Layout once the move lands: // parentDepth (ancestors of parent + parent itself) // + 1 (the moving dashboard slotted as child) // + movingSubtreeDepth (deepest descendant below the moving row). - $finalDepth = ($parentDepth + 1 + $movingSubtreeDepth); + $finalDepth = ($parentDepth + 1 + $this->movingSubtreeDepth(movingUuid: $movingUuid)); if ($finalDepth > Dashboard::MAX_DEPTH) { throw new InvalidArgumentException( @@ -679,6 +716,21 @@ private function assertDepthWithinCap( } }//end assertDepthWithinCap() + /** + * The depth of the subtree below the moving dashboard; 0 on create. + * + * @param string|null $movingUuid The dashboard being re-parented, or null. + * + * @return int The subtree depth. + */ + private function movingSubtreeDepth(string|null $movingUuid): int { + if (self::isBlank(uuid: $movingUuid) === true) { + return 0; + } + + return $this->measureSubtreeDepth(rootUuid: (string)$movingUuid); + }//end movingSubtreeDepth() + /** * Measure the depth of the subtree rooted at `$rootUuid`. * @@ -696,36 +748,40 @@ private function measureSubtreeDepth(string $rootUuid): int { while ($frontier !== []) { $next = []; foreach ($frontier as $entry) { - $children = $this->dashboardMapper->findByParent( - parentUuid: $entry['uuid'] - ); - - foreach ($children as $child) { - $childUuid = $child->getUuid(); - if ($childUuid === null || $childUuid === '') { - continue; - } - - $childDepth = ($entry['depth'] + 1); - if ($childDepth > $maxDepth) { - $maxDepth = $childDepth; - } - - if ($childDepth < Dashboard::MAX_DEPTH) { - $next[] = [ - 'uuid' => $childUuid, - 'depth' => $childDepth, - ]; + foreach ($this->childEntries(entry: $entry) as $childEntry) { + $maxDepth = max($maxDepth, $childEntry['depth']); + if ($childEntry['depth'] < Dashboard::MAX_DEPTH) { + $next[] = $childEntry; } } - }//end foreach + } $frontier = $next; - }//end while + } return $maxDepth; }//end measureSubtreeDepth() + /** + * The frontier entries of the children of one entry: their UUID and + * depth. Children without a UUID are left out. + * + * @param array{uuid: string, depth: int} $entry The parent entry. + * + * @return list The child entries. + */ + private function childEntries(array $entry): array { + $entries = []; + foreach ($this->dashboardMapper->findByParent(parentUuid: $entry['uuid']) as $child) { + $childUuid = $child->getUuid(); + if (self::isBlank(uuid: $childUuid) === false) { + $entries[] = ['uuid' => (string)$childUuid, 'depth' => ($entry['depth'] + 1)]; + } + } + + return $entries; + }//end childEntries() + /** * Split a slug-chain path into its segments. * diff --git a/lib/Service/DashboardVersionService.php b/lib/Service/DashboardVersionService.php index 4448b441d..f4d6557b2 100644 --- a/lib/Service/DashboardVersionService.php +++ b/lib/Service/DashboardVersionService.php @@ -40,15 +40,13 @@ use DateTime; use Exception; use OCA\LaunchPad\Db\Dashboard; -use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\DashboardVersion; use OCA\LaunchPad\Db\DashboardVersionMapper; use OCA\LaunchPad\Db\WidgetPlacement; -use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Service\Versions\SnapshotChangeDescriber; use OCP\AppFramework\Db\DoesNotExistException; use OCP\ICache; use OCP\ICacheFactory; -use OCP\IDBConnection; use OCP\IGroupManager; use Psr\Log\LoggerInterface; use Throwable; @@ -81,6 +79,7 @@ class DashboardVersionService { private const BLOB_SETTERS = [ 'styleConfig' => 'setStyleConfigArray', 'content' => 'setContentArray', + 'calculatedFields' => 'setCalculatedFieldsArray', ]; /** @@ -126,39 +125,19 @@ class DashboardVersionService { /** * Constructor * - * @param DashboardVersionMapper $versionMapper Version row mapper. - * @param DashboardMapper $dashboardMapper Dashboard row mapper. - * @param WidgetPlacementMapper $placementMapper Widget placement mapper - * (drives snapshot - * payload assembly). - * @param IGroupManager $groupManager Group manager — used - * exclusively for the - * owner-or-admin - * permission guard - * (no group-membership - * lookups). - * @param ICacheFactory $cacheFactory NC cache factory - * supplying the - * debounce backing - * store. + * @param VersionStores $stores The version, dashboard and placement mappers and the database. + * @param IGroupManager $groupManager Group manager — used exclusively for the owner-or-admin permission + * guard (no group-membership lookups). + * @param ICacheFactory $cacheFactory NC cache factory supplying the debounce backing store. * @param LoggerInterface $logger PSR logger. - * @param IDBConnection|null $db DB connection used to - * wrap restoreVersion - * in a transaction - * (WF1 fix). - * Nullable for - * backwards-compat - * with existing test - * doubles. + * @param SnapshotChangeDescriber $changeDescriber Writes the "What changed" note of automatic snapshots. */ public function __construct( - private readonly DashboardVersionMapper $versionMapper, - private readonly DashboardMapper $dashboardMapper, - private readonly WidgetPlacementMapper $placementMapper, + private readonly VersionStores $stores, private readonly IGroupManager $groupManager, private readonly ICacheFactory $cacheFactory, private readonly LoggerInterface $logger, - private readonly ?IDBConnection $db = null, + private readonly SnapshotChangeDescriber $changeDescriber=new SnapshotChangeDescriber(), ) { }//end __construct() @@ -185,29 +164,25 @@ public function __construct( * controllers that don't yet pass an explicit body. * * @param Dashboard $dashboard The dashboard being snapshotted. - * @param string|null $snapshotJson Pre-built snapshot JSON, or null - * to auto-build from the live - * state. - * @param string $createdBy The acting user ID. - * @param string|null $note Optional note for explicit - * snapshots; ignored / coerced to - * null on automatic captures. - * @param boolean $explicit Whether to bypass the debounce. + * @param string $createdBy The acting user ID. + * @param array $options Optional `snapshotJson` (pre-built + * snapshot JSON; null or empty to + * auto-build from the live state), `note` + * (kept on explicit snapshots only; an + * automatic snapshot notes what changed + * since the previous version) and + * `explicit` (bypass the debounce; false). * * @return DashboardVersion|null The persisted version row, or null * when an automatic snapshot was * suppressed by the debounce window. * * @spec openspec/specs/dashboard-versioning/spec.md + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-each-automatic-version-says-what-changed-req-versui-004 */ - public function captureSnapshot( - Dashboard $dashboard, - ?string $snapshotJson, - string $createdBy, - ?string $note = null, - bool $explicit = false, - ): ?DashboardVersion { - $uuid = (string)$dashboard->getUuid(); + public function captureSnapshot(Dashboard $dashboard, string $createdBy, array $options=[]): ?DashboardVersion { + $options += ['snapshotJson' => null, 'note' => null, 'explicit' => false]; + $uuid = (string)$dashboard->getUuid(); if ($uuid === '') { // Defensive — without a UUID we have nothing to key the // snapshot to. Refuse silently rather than throw because @@ -215,10 +190,55 @@ public function captureSnapshot( return null; } - if ($explicit === false && $this->isDebounced(uuid: $uuid) === true) { + if ($options['explicit'] === false && $this->isDebounced(uuid: $uuid) === true) { + return null; + } + + $entity = $this->newVersion(dashboard: $dashboard, options: $options); + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $entity->setCreatedBy($createdBy); + + return $this->insertVersion(entity: $entity); + }//end captureSnapshot() + + /** + * The stored dashboard and its snapshot payload, built before an update so + * the automatic snapshot holds the state the update replaces, placements + * included (REQ-VERS-001). Pass both to captureSnapshot() once the update + * succeeded. + * + * @param int $dashboardId The dashboard about to be updated. + * + * @return array{dashboard: Dashboard, snapshotJson: string}|null The state, or null when the dashboard does not exist. + * + * @spec openspec/specs/dashboard-versioning/spec.md + */ + public function stateBeforeUpdate(int $dashboardId): ?array { + try { + $dashboard = $this->stores->dashboardMapper->find(id: $dashboardId); + } catch (DoesNotExistException) { return null; } + return ['dashboard' => $dashboard, 'snapshotJson' => $this->buildDefaultSnapshot(dashboard: $dashboard)]; + }//end stateBeforeUpdate() + + /** + * The next version row of a dashboard, not yet persisted and without + * its author. + * + * @param Dashboard $dashboard The dashboard being snapshotted (it has a UUID). + * @param array $options `snapshotJson`, `note` and `explicit` as + * {@see self::captureSnapshot()} takes them. + * + * @return DashboardVersion The unsaved row. + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-each-automatic-version-says-what-changed-req-versui-004 + */ + private function newVersion(Dashboard $dashboard, array $options): DashboardVersion { + $uuid = (string)$dashboard->getUuid(); + $snapshotJson = $options['snapshotJson']; + $note = $options['note']; // Auto-build the payload when the caller hands us nothing — // this keeps the integration with `DashboardService` simple. if ($snapshotJson === null || $snapshotJson === '') { @@ -226,11 +246,15 @@ public function captureSnapshot( } $coercedNote = null; - if ($explicit === true && $note !== null && $note !== '') { + if ($options['explicit'] === true && $note !== null && $note !== '') { $coercedNote = $note; } - $next = ($this->versionMapper->findMaxVersionNumber( + if ($options['explicit'] === false) { + $coercedNote = $this->describeChange(dashboardUuid: $uuid, snapshotJson: $snapshotJson); + } + + $next = ($this->stores->versionMapper->findMaxVersionNumber( dashboardUuid: $uuid ) + 1); @@ -241,18 +265,62 @@ public function captureSnapshot( $entity->setDashboardUuid($uuid); $entity->setVersionNumber($next); $entity->setSnapshotJson($snapshotJson); - $entity->setCreatedBy($createdBy); $entity->setCreatedAt( (new DateTime())->format(format: 'Y-m-d H:i:s') ); $entity->setNote($coercedNote); // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters - $persisted = $this->versionMapper->insert(entity: $entity); + return $entity; + }//end newVersion() + + /** + * What changed between a dashboard's newest stored version and a new + * snapshot, for the note of an automatic snapshot. + * + * @param string $dashboardUuid The dashboard UUID. + * @param string $snapshotJson The new snapshot. + * + * @return string|null The description, or null when there is no previous + * version, nothing differs or the lookup fails. + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-each-automatic-version-says-what-changed-req-versui-004 + */ + private function describeChange(string $dashboardUuid, string $snapshotJson): ?string { + try { + $latest = $this->stores->versionMapper->findLatestByDashboard(dashboardUuid: $dashboardUuid, limit: 1); + if ($latest === []) { + return null; + } + + return $this->changeDescriber->describe( + previousJson: (string)$latest[0]->getSnapshotJson(), + currentJson: $snapshotJson + ); + } catch (Throwable $t) { + $this->logger->debug( + message: 'launchpad: failed to describe the snapshot change', + context: ['exception' => $t] + ); + return null; + } + }//end describeChange() + + /** + * Persist a version row, prune past the retention limit and refresh + * the debounce key. + * + * @param DashboardVersion $entity The row to insert. + * + * @return DashboardVersion The persisted row. + */ + private function insertVersion(DashboardVersion $entity): DashboardVersion { + $uuid = (string)$entity->getDashboardUuid(); + $persisted = $this->stores->versionMapper->insert(entity: $entity); // REQ-VERS-006: prune inline so the table never exceeds the // retention limit by more than the single in-flight insert. - $this->versionMapper->pruneOldVersions( + $this->stores->versionMapper->pruneOldVersions( dashboardUuid: $uuid, keepCount: self::RETENTION_LIMIT ); @@ -264,7 +332,7 @@ public function captureSnapshot( $this->markDebounced(uuid: $uuid); return $persisted; - }//end captureSnapshot() + }//end insertVersion() /** * List the versions available for a dashboard, newest-first @@ -304,7 +372,7 @@ public function listVersions( ]; } - $rows = $this->versionMapper->findLatestByDashboard( + $rows = $this->stores->versionMapper->findLatestByDashboard( dashboardUuid: (string)$dashboard->getUuid(), limit: self::RETENTION_LIMIT ); @@ -349,7 +417,7 @@ public function fetchSnapshot( ); } - return $this->versionMapper->findByDashboardAndVersion( + return $this->stores->versionMapper->findByDashboardAndVersion( dashboardUuid: (string)$dashboard->getUuid(), versionNumber: $versionNumber ); @@ -389,10 +457,8 @@ public function createExplicitSnapshot( $persisted = $this->captureSnapshot( dashboard: $dashboard, - snapshotJson: null, createdBy: $requestingUser, - note: $note, - explicit: true + options: ['note' => $note, 'explicit' => true] ); if ($persisted === null) { @@ -413,10 +479,11 @@ public function createExplicitSnapshot( * BEFORE the restore overwrites the body so the operation is * itself reversible. * - * Restoring to the latest version is treated as a no-op (idempotent - * round-trip) — no new snapshot is created and the existing - * dashboard is returned untouched. This matches the - * "restore to current is a no-op" scenario in REQ-VERS-005. + * Restoring the latest version while it holds the dashboard's current + * placements is a no-op: no new snapshot, the dashboard untouched + * ("restore to current is a no-op" in REQ-VERS-005). A latest version + * that differs, such as a pre-restore snapshot, is restored normally + * ("restore is reversible"). * * @param Dashboard $dashboard The dashboard. * @param integer $versionNumber The target version number. @@ -440,24 +507,20 @@ public function restoreVersion( actorUserId: $restoringUser ); - if ($this->isGroupfolderBacked(dashboard: $dashboard) === true) { - throw new Exception( - message: self::ERR_VERSIONING_UNAVAILABLE - ); - } + $this->assertVersioningAvailable(dashboard: $dashboard); $uuid = (string)$dashboard->getUuid(); - $target = $this->versionMapper->findByDashboardAndVersion( + $target = $this->stores->versionMapper->findByDashboardAndVersion( dashboardUuid: $uuid, versionNumber: $versionNumber ); - $latest = $this->versionMapper->findMaxVersionNumber( + $latest = $this->stores->versionMapper->findMaxVersionNumber( dashboardUuid: $uuid ); - if ($latest === $versionNumber) { + if ($latest === $versionNumber && $this->holdsCurrentPlacements(dashboard: $dashboard, target: $target) === true) { // REQ-VERS-005: restoring to the current version is a no-op. return [ 'snapshot' => (string)$target->getSnapshotJson(), @@ -465,54 +528,92 @@ public function restoreVersion( ]; } - // WF1 fix: wrap the wipe-and-reinsert in a DB transaction so a - // mid-loop insert failure never leaves the dashboard with zero or - // partial placements. When no db connection is wired (test doubles) - // the operations run without an explicit transaction envelope, - // preserving backwards-compat. - if ($this->db !== null) { - $this->db->beginTransaction(); - } - - $snapshotJson = ''; - try { - // Capture pre-restore state as a new snapshot so the restore - // itself is reversible (REQ-VERS-005 design D3). - $this->captureSnapshot( - dashboard: $dashboard, - snapshotJson: $this->buildDefaultSnapshot(dashboard: $dashboard), - createdBy: $restoringUser, - note: 'pre-restore', - explicit: true - ); + $snapshotJson = $this->inRestoreTransaction( + restore: function () use ($dashboard, $target, $restoringUser): string { + // Capture pre-restore state as a new snapshot so the restore + // itself is reversible (REQ-VERS-005 design D3). + $preRestore = ['snapshotJson' => $this->buildDefaultSnapshot(dashboard: $dashboard), 'note' => 'pre-restore', 'explicit' => true]; + $this->captureSnapshot(dashboard: $dashboard, createdBy: $restoringUser, options: $preRestore); - // C3 fix: decode the target snapshot and apply it to the DB so - // the restore is a real state change, not a no-op. - $snapshotJson = (string)$target->getSnapshotJson(); - $payload = json_decode($snapshotJson, associative: true); - if (is_array($payload) === true) { - $this->applySnapshotPayload( - dashboard: $dashboard, - payload: $payload - ); + return $this->applyVersion(dashboard: $dashboard, target: $target); } + ); - // Stamp the dashboard's updatedAt so callers that listen on - // metadata see the restore (REQ-VERS-005 scenario "restore - // updates the modified timestamp"). - // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters - $dashboard->setUpdatedAt( - (new DateTime())->format(format: 'Y-m-d H:i:s') - ); - $this->dashboardMapper->update(entity: $dashboard); + return [ + 'snapshot' => $snapshotJson, + 'version' => $target, + ]; + }//end restoreVersion() + + /** + * Whether a version holds the same placements as the dashboard now, + * ignoring the row ids and timestamps a restore does not keep. + * + * @param Dashboard $dashboard The dashboard. + * @param DashboardVersion $target The version to compare. + * + * @return boolean True when restoring the version would change no placement. + */ + private function holdsCurrentPlacements(Dashboard $dashboard, DashboardVersion $target): bool { + $current = json_decode($this->buildDefaultSnapshot(dashboard: $dashboard), associative: true); + $stored = json_decode((string)$target->getSnapshotJson(), associative: true); + + return $this->comparablePlacements(payload: $current) === $this->comparablePlacements(payload: $stored); + }//end holdsCurrentPlacements() + + /** + * The placements of a decoded snapshot as sorted JSON strings without + * id, dashboardId, createdAt and updatedAt. + * + * @param mixed $payload The decoded snapshot. + * + * @return string[] One string per placement, sorted. + */ + private function comparablePlacements(mixed $payload): array { + $placements = []; + if (is_array($payload) === true && is_array($payload['placements'] ?? null) === true) { + $placements = $payload['placements']; + } - if ($this->db !== null) { - $this->db->commit(); + $comparable = []; + foreach ($placements as $placement) { + if (is_array($placement) === false) { + continue; } + + unset($placement['id'], $placement['dashboardId'], $placement['createdAt'], $placement['updatedAt']); + ksort($placement); + $comparable[] = (string)json_encode($placement); + } + + sort($comparable); + return $comparable; + }//end comparablePlacements() + + /** + * Run a restore inside one DB transaction, rolled back and logged on failure. + * + * WF1 fix: wrap the wipe-and-reinsert in a DB transaction so a + * mid-loop insert failure never leaves the dashboard with zero or + * partial placements. When no db connection is wired (test doubles) + * the operations run without an explicit transaction envelope, + * preserving backwards-compat. + * + * @param \Closure $restore Runs the restore and returns the applied snapshot JSON. + * + * @return string The applied snapshot JSON. + * + * @throws Throwable The restore's failure, after the rollback. + */ + private function inRestoreTransaction(\Closure $restore): string { + $this->stores->db?->beginTransaction(); + + try { + $snapshotJson = $restore(); + + $this->stores->db?->commit(); } catch (Throwable $t) { - if ($this->db !== null) { - $this->db->rollBack(); - } + $this->stores->db?->rollBack(); $this->logger->error( message: 'launchpad: restoreVersion failed, transaction rolled back', @@ -521,11 +622,57 @@ public function restoreVersion( throw $t; }//end try - return [ - 'snapshot' => $snapshotJson, - 'version' => $target, - ]; - }//end restoreVersion() + return $snapshotJson; + }//end inRestoreTransaction() + + /** + * Refuse versioning for a dashboard backed by a group folder. + * + * @param Dashboard $dashboard The dashboard. + * + * @return void + * + * @throws Exception With {@see self::ERR_VERSIONING_UNAVAILABLE}. + */ + private function assertVersioningAvailable(Dashboard $dashboard): void { + if ($this->isGroupfolderBacked(dashboard: $dashboard) === true) { + throw new Exception( + message: self::ERR_VERSIONING_UNAVAILABLE + ); + } + }//end assertVersioningAvailable() + + /** + * Apply a stored version to the dashboard and stamp its modification time. + * + * C3 fix: the target snapshot is decoded and applied to the DB so the + * restore is a real state change, not a no-op. The dashboard's + * updatedAt is stamped so callers that listen on metadata see the + * restore (REQ-VERS-005 scenario "restore updates the modified timestamp"). + * + * @param Dashboard $dashboard The dashboard to restore. + * @param DashboardVersion $target The version to restore to. + * + * @return string The applied snapshot JSON. + */ + private function applyVersion(Dashboard $dashboard, DashboardVersion $target): string { + $snapshotJson = (string)$target->getSnapshotJson(); + $payload = json_decode($snapshotJson, associative: true); + if (is_array($payload) === true) { + $this->applySnapshotPayload( + dashboard: $dashboard, + payload: $payload + ); + } + + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $dashboard->setUpdatedAt( + (new DateTime())->format(format: 'Y-m-d H:i:s') + ); + $this->stores->dashboardMapper->update(entity: $dashboard); + + return $snapshotJson; + }//end applyVersion() /* * NO CASCADE-DELETE WRAPPER HERE. @@ -674,7 +821,7 @@ private function buildDefaultSnapshot(Dashboard $dashboard): string { $placements = []; if ($dashboardId !== null) { try { - $rows = $this->placementMapper->findByDashboardId( + $rows = $this->stores->placementMapper->findByDashboardId( dashboardId: $dashboardId ); foreach ($rows as $row) { @@ -734,7 +881,7 @@ private function applySnapshotPayload(Dashboard $dashboard, array $payload): voi } try { - $this->placementMapper->deleteByDashboardId( + $this->stores->placementMapper->deleteByDashboardId( dashboardId: $dashboardId ); @@ -751,7 +898,7 @@ private function applySnapshotPayload(Dashboard $dashboard, array $payload): voi continue; } - $this->placementMapper->insert(entity: $entity); + $this->stores->placementMapper->insert(entity: $entity); }//end foreach } catch (Throwable $t) { $this->logger->error( diff --git a/lib/Service/DashboardWidgetRegistry.php b/lib/Service/DashboardWidgetRegistry.php new file mode 100644 index 000000000..6014f6e18 --- /dev/null +++ b/lib/Service/DashboardWidgetRegistry.php @@ -0,0 +1,153 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-010-initial-state-widget-allowlist + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\App\IAppManager; +use OCP\Dashboard\IConditionalWidget; +use OCP\Dashboard\IManager; +use OCP\Dashboard\IWidget; +use Psr\Container\ContainerInterface; +use ReflectionException; +use ReflectionProperty; +use Throwable; + +/** + * Reads the dashboard widget registry the way `IManager::getWidgets()` does, + * minus the `load()` call on every widget. + * + * `load()` is where a widget calls `Util::addScript()`, so calling + * `getWidgets()` while rendering the workspace page injects every widget's + * JavaScript into a page that renders no Nextcloud dashboard. The public API + * has no other way to list the widgets, so this reads the manager's pending + * registrations and builds each widget the way the manager would. When the + * manager does not have that shape the answer is null and the caller falls + * back to `GET /api/widgets`. + * + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-010-initial-state-widget-allowlist + */ +class DashboardWidgetRegistry { + /** + * Constructor. + * + * @param IManager $dashboardManager The dashboard widget registry. + * @param IAppManager $appManager Whether a widget's app is enabled for the user. + * @param ContainerInterface $container Builds a registered widget class. + */ + public function __construct( + private readonly IManager $dashboardManager, + private readonly IAppManager $appManager, + private readonly ContainerInterface $container, + ) { + }//end __construct() + + /** + * The widgets enabled for the current user, none of them loaded. + * + * When the registry was already loaded in this request, reading it again + * costs nothing, so its widgets are returned as they are. + * + * @return list|null The widgets, or null when the registry cannot be read without loading it. + * + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-010-initial-state-widget-allowlist + */ + public function widgetsWithoutLoading(): ?array { + $pending = $this->pendingRegistrations(); + if ($pending === null) { + return null; + } + + if ($pending === []) { + return array_values(array: $this->dashboardManager->getWidgets()); + } + + $widgets = []; + foreach ($pending as $registration) { + $widget = $this->build(registration: $registration); + if ($widget !== null && isset($widgets[$widget->getId()]) === false) { + $widgets[$widget->getId()] = $widget; + } + } + + return array_values(array: $widgets); + }//end widgetsWithoutLoading() + + /** + * The manager's registrations that have not been loaded yet. + * + * @return list|null The registrations, or null when the manager has no such list. + */ + private function pendingRegistrations(): ?array { + try { + $property = new ReflectionProperty($this->dashboardManager, 'lazyWidgets'); + } catch (ReflectionException) { + return null; + } + + $value = $property->getValue($this->dashboardManager); + if (is_array($value) === false) { + return null; + } + + $registrations = []; + foreach ($value as $entry) { + if (is_array($entry) === false || is_string($entry['class'] ?? null) === false || is_string($entry['appId'] ?? null) === false) { + return null; + } + + $registrations[] = ['class' => $entry['class'], 'appId' => $entry['appId']]; + } + + return $registrations; + }//end pendingRegistrations() + + /** + * One registered widget, when its app is enabled for the user, it can be + * built and it is not switched off. + * + * @param array{class: string, appId: string} $registration The registration. + * + * @return IWidget|null The widget, or null to leave it out. + */ + private function build(array $registration): ?IWidget { + try { + if ($this->appManager->isEnabledForUser($registration['appId']) === false) { + return null; + } + + $widget = $this->container->get($registration['class']); + if ($widget instanceof IWidget === false) { + return null; + } + + if ($widget instanceof IConditionalWidget && $widget->isEnabled() === false) { + return null; + } + } catch (Throwable) { + return null; + } + + return $widget; + }//end build() +}//end class diff --git a/lib/Service/DefaultAppSetting.php b/lib/Service/DefaultAppSetting.php new file mode 100644 index 000000000..1c64df3af --- /dev/null +++ b/lib/Service/DefaultAppSetting.php @@ -0,0 +1,199 @@ + + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\AdminSettingKey; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCP\IConfig; + +/** + * Sets, keeps or restores the instance default app. + * + * @spec openspec/specs/dashboard-public-share/spec.md#requirement-the-start-page-offers-a-way-in-for-staff-req-psp-003 + */ +class DefaultAppSetting { + + /** + * The Nextcloud system value that holds the default app. + * + * @var string + */ + public const SYSTEM_KEY = 'defaultapp'; + + /** + * Outcome: LaunchPad is now the default app. + * + * @var string + */ + public const SET = 'set'; + + /** + * Outcome: the administrator's own default app was kept. + * + * @var string + */ + public const KEPT = 'kept'; + + /** + * Outcome: the toggle is off, nothing was changed. + * + * @var string + */ + public const DISABLED = 'disabled'; + + /** + * Outcome: the default app is unset again, so Nextcloud's own fallback applies. + * + * @var string + */ + public const RESTORED = 'restored'; + + /** + * Outcome: nothing to change. + * + * @var string + */ + public const UNCHANGED = 'unchanged'; + + /** + * Constructor. + * + * @param IConfig $config The system configuration. + * @param AdminSettingMapper $settingMapper The admin settings store. + */ + public function __construct( + private readonly IConfig $config, + private readonly AdminSettingMapper $settingMapper, + ) { + }//end __construct() + + /** + * Whether LaunchPad should be the default app. On unless switched off. + * + * @return bool + * + * @spec openspec/specs/dashboard-public-share/spec.md#requirement-the-start-page-offers-a-way-in-for-staff-req-psp-003 + */ + public function isEnabled(): bool { + return $this->settingMapper->getValue(key: AdminSettingKey::DEFAULT_APP_ENABLED->value, default: true) !== false; + }//end isEnabled() + + /** + * Make LaunchPad the default app when the toggle is on and no default app is configured. + * + * Runs on install and on every upgrade, so it must never overwrite a choice: + * only an absent `defaultapp` value is filled. + * + * @return string One of {@see self::SET}, {@see self::KEPT}, {@see self::DISABLED} + * or {@see self::UNCHANGED} (LaunchPad already is the default). + * + * @spec openspec/specs/dashboard-public-share/spec.md#requirement-the-start-page-offers-a-way-in-for-staff-req-psp-003 + */ + public function claim(): string { + if ($this->isEnabled() === false) { + return self::DISABLED; + } + + $current = $this->current(); + if ($current === Application::APP_ID) { + return self::UNCHANGED; + } + + if ($current !== null) { + return self::KEPT; + } + + $this->config->setSystemValue(self::SYSTEM_KEY, Application::APP_ID); + return self::SET; + }//end claim() + + /** + * Switch the toggle. Only a change acts: off restores, on sets. + * + * @param bool $enabled The new toggle value. + * + * @return string What happened to the default app. + * + * @spec openspec/specs/dashboard-public-share/spec.md#requirement-the-start-page-offers-a-way-in-for-staff-req-psp-003 + */ + public function setEnabled(bool $enabled): string { + if ($enabled === $this->isEnabled()) { + return self::UNCHANGED; + } + + $this->settingMapper->setSetting(key: AdminSettingKey::DEFAULT_APP_ENABLED->value, value: $enabled); + if ($enabled === true) { + return $this->claim(); + } + + return $this->release(); + }//end setEnabled() + + /** + * Give back the empty default LaunchPad filled, when LaunchPad still is the default. + * + * @return string {@see self::RESTORED} or {@see self::UNCHANGED}. + */ + private function release(): string { + if ($this->current() !== Application::APP_ID) { + return self::UNCHANGED; + } + + $this->config->deleteSystemValue(self::SYSTEM_KEY); + return self::RESTORED; + }//end release() + + /** + * The default app as configured, trimmed; null when no value is configured. + * + * @return string|null + */ + private function current(): ?string { + $value = $this->config->getSystemValue(self::SYSTEM_KEY, null); + if ($value === null) { + return null; + } + + if (is_string($value) === false) { + return ''; + } + + return trim($value); + }//end current() +}//end class diff --git a/lib/Service/DemoAnnouncements.php b/lib/Service/DemoAnnouncements.php new file mode 100644 index 000000000..5329121f5 --- /dev/null +++ b/lib/Service/DemoAnnouncements.php @@ -0,0 +1,166 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/engagement-announcements/tasks.md#task-11 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTime; +use OCA\LaunchPad\Db\Announcement; +use OCA\LaunchPad\Db\AnnouncementMapper; +use OCP\AppFramework\Utility\ITimeFactory; + +/** + * Seeds two news items and a maintenance notice, only when there are no announcements yet. + * + * Seeded announcements are published at once and stamped as notified, so a + * demo install sends no follow notifications. The notice ends on the coming + * Saturday at 12:00 and cannot be dismissed. + * + * @spec openspec/changes/engagement-announcements/tasks.md#task-11 + */ +class DemoAnnouncements { + + /** + * The author recorded on the demo announcements. + * + * @var string + */ + public const AUTHOR = 'admin'; + + /** + * Constructor. + * + * @param AnnouncementMapper $announcements The announcements. + * @param ITimeFactory $time The clock. + * + * @spec openspec/changes/engagement-announcements/tasks.md#task-11 + */ + public function __construct( + private readonly AnnouncementMapper $announcements, + private readonly ITimeFactory $time, + ) { + }//end __construct() + + /** + * Seed the demo announcements unless any announcement exists. + * + * @return int How many were seeded. + * + * @spec openspec/changes/engagement-announcements/tasks.md#task-11 + */ + public function seed(): int { + $now = $this->time->getDateTime(); + if ($this->announcements->findLive(now: $now) !== [] || $this->announcements->findDrafts(authorId: null) !== []) { + return 0; + } + + $saturday = (clone $now)->modify('next saturday')->setTime(12, 0); + $rows = [ + [ + 'news', + 'Nieuwe werkplekken op de 3e verdieping', + 'Vanaf maandag zijn er twintig flexplekken extra op de derde verdieping. Reserveren gaat via de werkplekkenapp.', + 'Facilitair', + [], + null, + ], + [ + 'news', + 'Inloopspreekuur privacy', + 'Elke donderdag van 13:00 tot 14:00 beantwoordt de privacy officer je vragen, in kamer 2.14 of online.', + 'Privacy', + ['Medewerkers'], + null, + ], + [ + 'notice', + 'Onderhoud zaaksysteem zaterdag 08:00 tot 12:00', + 'Het zaaksysteem is zaterdag tussen 08:00 en 12:00 niet bereikbaar wegens onderhoud.', + null, + [], + $saturday, + ], + ]; + foreach ($rows as [$kind, $title, $body, $category, $groups, $expiresAt]) { + $this->announcements->insert( + entity: $this->announcement(kind: $kind, text: [$title, $body], category: $category, groups: $groups, expiresAt: $expiresAt) + ); + } + + return count($rows); + }//end seed() + + /** + * One published demo announcement. + * + * @param string $kind `news` or `notice`. + * @param array $text The title and the body. + * @param string|null $category The category. + * @param list $groups The target groups. + * @param DateTime|null $expiresAt The end time. + * + * @return Announcement + * + * @spec openspec/changes/engagement-announcements/tasks.md#task-11 + */ + private function announcement(string $kind, array $text, ?string $category, array $groups, ?DateTime $expiresAt): Announcement { + $now = $this->time->getDateTime(); + $announcement = new Announcement(); + $announcement->setUuid($this->uuid()); + $announcement->setKind($kind); + $announcement->setTitle($text[0]); + $announcement->setBody($text[1]); + $announcement->setCategory($category); + $announcement->setTargetGroupList($groups); + $announcement->setStatus(Announcement::STATUS_PUBLISHED); + $announcement->setLevel(null); + if ($kind === Announcement::KIND_NOTICE) { + $announcement->setLevel('warning'); + } + $announcement->setDismissible(0); + $announcement->setAllowComments((int) ($kind === Announcement::KIND_NEWS)); + $announcement->setPublishAt($now); + $announcement->setExpiresAt($expiresAt); + $announcement->setNotifiedAt($now); + $announcement->setAuthorId(self::AUTHOR); + $announcement->setCreatedAt($now); + $announcement->setUpdatedAt($now); + + return $announcement; + }//end announcement() + + /** + * A random version-4 UUID. + * + * @return string + * + * @spec openspec/changes/engagement-announcements/tasks.md#task-11 + */ + private function uuid(): string { + $data = random_bytes(16); + $data[6] = chr((ord($data[6]) & 0x0F) | 0x40); + $data[8] = chr((ord($data[8]) & 0x3F) | 0x80); + + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); + }//end uuid() +}//end class diff --git a/lib/Service/DemoDataService.php b/lib/Service/DemoDataService.php index 0fc9a5ccb..a83270aaf 100644 --- a/lib/Service/DemoDataService.php +++ b/lib/Service/DemoDataService.php @@ -27,6 +27,7 @@ namespace OCA\LaunchPad\Service; use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Kernel\Contracts\DemoDataServiceInterface; use OCP\App\IAppManager; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; @@ -37,7 +38,7 @@ * * @spec exclude Demo-data import; ADR-111 rule 1, no per-app behavioural spec. */ -class DemoDataService { +class DemoDataService implements DemoDataServiceInterface { /** * App-relative path to the generated mock descriptor. * @@ -63,6 +64,8 @@ class DemoDataService { * @param IAppManager $appManager Resolves this app's path and version. * @param ContainerInterface $container Resolves OpenRegister's importer. * @param LoggerInterface $logger Records what was imported. + * @param ProfileFieldService $profileFields Defines the demo profile fields. + * @param DemoAnnouncements|null $announcements Seeds the demo announcements (engagement-announcements task 11). * * @return void */ @@ -70,6 +73,8 @@ public function __construct( private readonly IAppManager $appManager, private readonly ContainerInterface $container, private readonly LoggerInterface $logger, + private readonly ProfileFieldService $profileFields, + private readonly ?DemoAnnouncements $announcements = null, ) { }//end __construct() @@ -84,24 +89,6 @@ public function isAvailable(): bool { return is_file($this->descriptorPath()) === true; }//end isAvailable() - /** - * The answer that means "plant nothing". - * - * 🔴 NOT THE ABSENCE OF AN ANSWER. An operator who declines has FINISHED the - * step; a step that can never be marked done reopens the wizard over every - * page (nextcloud-vue#806). - * - * @var string - */ - public const NONE_DATASET = 'none'; - - /** - * The id of the dataset this app ships. - * - * @var string - */ - public const DEMO_DATASET = 'demo'; - /** * Every answer the wizard's choice step may offer, declining included. * @@ -232,6 +219,12 @@ public function install(): array { force: true ); + // Widgets-people-expertise-and-fields: the demo profile fields + // (office, cost centre, expertise tags), only when none are defined. + $this->profileFields->seedDemoDefinitions(); + // Engagement-announcements: two news items and a maintenance notice, only when there are none. + $this->announcements?->seed(); + $imported = [ 'objects' => $objects, 'registers' => count((array)($result['registers'] ?? [])), diff --git a/lib/Service/DemoSeedAccounts.php b/lib/Service/DemoSeedAccounts.php new file mode 100644 index 000000000..cf972a6b3 --- /dev/null +++ b/lib/Service/DemoSeedAccounts.php @@ -0,0 +1,181 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\IGroupManager; +use OCP\IUser; +use OCP\IUserManager; +use RuntimeException; + +/** + * Seed demo groups and users. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedAccounts { + /** + * Constructor. + * + * @param IUserManager $userManager Creates and finds users. + * @param IGroupManager $groupManager Creates groups and memberships. + */ + public function __construct( + private readonly IUserManager $userManager, + private readonly IGroupManager $groupManager, + ) { + }//end __construct() + + /** + * Ensure every seeded group exists with its display name. + * + * @param array> $groups The seed groups, `{id, name}`. + * + * @return array The ids of the groups created by this run. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function ensureGroups(array $groups): array { + $created = []; + foreach ($groups as $definition) { + $groupId = (string)$definition['id']; + $group = $this->groupManager->get(gid: $groupId); + if ($group === null) { + $group = $this->groupManager->createGroup(gid: $groupId); + $created[] = $groupId; + } + + $name = (string)($definition['name'] ?? $groupId); + if ($group !== null && $group->getDisplayName() !== $name) { + $group->setDisplayName(displayName: $name); + } + } + + return $created; + }//end ensureGroups() + + /** + * Ensure every seeded user exists with its display name, e-mail and + * exactly the seeded memberships of the seeded groups. + * + * Memberships of groups outside the seed are left alone, so an + * administrator's own grouping survives a re-run. + * + * The seed manages its own groups and `admin`. + * + * @param array $seed The seed, with its `users` and `groups`. + * @param string $password The password for users this run creates. + * + * @return array The ids of the users created by this run. + * + * @throws RuntimeException When a user cannot be created. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function ensureUsers(array $seed, string $password): array { + $managed = [...array_column(array: (array)($seed['groups'] ?? []), column_key: 'id'), 'admin']; + $created = []; + foreach ((array)($seed['users'] ?? []) as $definition) { + $userId = (string)$definition['id']; + $user = $this->userManager->get(uid: $userId); + if ($user === null) { + $user = $this->createUser(userId: $userId, password: $password); + $created[] = $userId; + } + + $this->applyProfile(user: $user, definition: $definition); + $this->applyMemberships(user: $user, membership: ['wanted' => (array)($definition['groups'] ?? []), 'managed' => $managed]); + } + + return $created; + }//end ensureUsers() + + /** + * Create one demo user. + * + * @param string $userId The user id. + * @param string $password The password. + * + * @return IUser The new user. + * + * @throws RuntimeException When Nextcloud refuses the user. + */ + private function createUser(string $userId, string $password): IUser { + $user = $this->userManager->createUser(uid: $userId, password: $password); + if ($user === false) { + throw new RuntimeException(message: 'Could not create demo user ' . $userId); + } + + return $user; + }//end createUser() + + /** + * Bring a user's display name and e-mail to the seeded values. + * + * @param IUser $user The user. + * @param array $definition The seed user. + * + * @return void + */ + private function applyProfile(IUser $user, array $definition): void { + $displayName = (string)($definition['displayName'] ?? ''); + if ($displayName !== '' && $user->getDisplayName() !== $displayName) { + $user->setDisplayName(displayName: $displayName); + } + + $email = (string)($definition['email'] ?? ''); + if ($email !== '' && $user->getSystemEMailAddress() !== $email) { + $user->setSystemEMailAddress(mailAddress: $email); + } + }//end applyProfile() + + /** + * Add the user to its seeded groups and remove it from the other seed + * groups. + * + * @param IUser $user The user. + * @param array> $membership `wanted`: the groups the seed gives the user; + * `managed`: the groups the seed manages. + * + * @return void + */ + private function applyMemberships(IUser $user, array $membership): void { + $wanted = array_map(callback: 'strval', array: $membership['wanted']); + foreach ($membership['managed'] as $groupId) { + $group = $this->groupManager->get(gid: (string)$groupId); + if ($group === null) { + continue; + } + + $isMember = $group->inGroup(user: $user); + $shouldJoin = in_array(needle: $groupId, haystack: $wanted, strict: true); + if ($shouldJoin === true && $isMember === false) { + $group->addUser(user: $user); + } elseif ($shouldJoin === false && $isMember === true) { + $group->removeUser(user: $user); + } + } + }//end applyMemberships() +}//end class diff --git a/lib/Service/DemoSeedContent.php b/lib/Service/DemoSeedContent.php new file mode 100644 index 000000000..b58c13ee2 --- /dev/null +++ b/lib/Service/DemoSeedContent.php @@ -0,0 +1,266 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTime; +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\Announcement; +use OCA\LaunchPad\Db\AnnouncementMapper; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\IAppConfig; + +/** + * Seed the app catalogue, announcements and allowed sites. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedContent { + /** + * Constructor. + * + * @param CatalogueService $catalogue The app catalogue. + * @param AnnouncementMapper $announcements Announcements and banners. + * @param IAppConfig $appConfig The allowed-site lists. + */ + public function __construct( + private readonly CatalogueService $catalogue, + private readonly AnnouncementMapper $announcements, + private readonly IAppConfig $appConfig, + private readonly ?ProfileFieldService $profileFields = null, + ) { + }//end __construct() + + /** + * Give the seed's new colleagues a start date (REQ-PPL-014): the field the + * administrator marked as the start date, or a new self-filled date field + * marked so when there is none. Dates are days from today, so the demo's + * "New colleagues" stays current whenever it is loaded. + * + * @param array $entry `{field: {key, label}, offsets: {uid: days}}`. + * @param string $today Today, `YYYY-MM-DD`. + * + * @return array The start date written per person. + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ + public function seedStartDates(array $entry, string $today): array { + $offsets = (array)($entry['offsets'] ?? []); + if ($this->profileFields === null || $offsets === []) { + return []; + } + + $key = $this->startDateKey(field: (array)($entry['field'] ?? [])); + $base = strtotime(datetime: $today.' 12:00:00 UTC'); + $written = []; + foreach ($offsets as $userId => $days) { + $date = gmdate(format: 'Y-m-d', timestamp: $base + ((int)$days * 86400)); + $this->profileFields->saveOwnValues(userId: (string)$userId, values: [$key => $date]); + $written[(string)$userId] = $date; + } + + return $written; + }//end seedStartDates() + + /** + * The key of the start-date field, adding the seed's field when none is marked. + * + * @param array $field `{key, label}` of the seed's field. + * + * @return string The key. + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ + private function startDateKey(array $field): string { + $definitions = $this->profileFields->getDefinitions(); + foreach ($definitions as $definition) { + if (($definition['startDate'] ?? false) === true) { + return (string)$definition['key']; + } + } + + $key = (string)($field['key'] ?? 'start_date'); + $definitions[] = [ + 'key' => $key, + 'label' => (string)($field['label'] ?? 'Start date'), + 'type' => 'date', + 'source' => 'self', + 'searchable' => false, + 'shownInWidget' => false, + 'startDate' => true, + ]; + $this->profileFields->saveDefinitions(raw: $definitions); + + return $key; + }//end startDateKey() + + /** + * Add the seeded hosts to each JSON host list in app config, keeping + * the hosts an administrator added. + * + * @param array $values Config key to list of hosts. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function mergeAppConfig(array $values): void { + foreach ($values as $key => $hosts) { + $current = json_decode( + json: $this->appConfig->getValueString(Application::APP_ID, (string)$key, '[]'), + associative: true + ); + if (is_array($current) === false) { + $current = []; + } + + $merged = array_values( + array: array_unique(array: [...array_map(callback: 'strval', array: $current), ...array_map(callback: 'strval', array: (array)$hosts)]) + ); + $this->appConfig->setValueString(Application::APP_ID, (string)$key, (string)json_encode(value: $merged)); + } + }//end mergeAppConfig() + + /** + * Add or update one catalogue entry per seeded tile, matched by name, or + * by the app or address it opens (so a seed loaded in another language + * renames its entries instead of adding a second set). + * + * @param array> $tiles The seed's tile catalogue. + * + * @return array{created: int, updated: int} What this run changed. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function seedCatalogue(array $tiles): array { + $byName = []; + $byLink = []; + foreach ($this->catalogue->listAll() as $app) { + $byName[(string)$app->getName()] = (string)$app->getUuid(); + $byLink[(string)$app->getLinkType() . ':' . (string)$app->getLinkValue()] ??= (string)$app->getUuid(); + } + + $counts = ['created' => 0, 'updated' => 0]; + $position = 0; + foreach ($tiles as $tile) { + $input = $this->catalogueInput(tile: $tile, position: $position++); + $uuid = ($byName[$input['name']] ?? $byLink[$input['linkType'] . ':' . $input['linkValue']] ?? null); + if ($uuid !== null) { + $this->catalogue->update(uuid: $uuid, input: $input); + $counts['updated']++; + continue; + } + + $this->catalogue->create(input: $input); + $counts['created']++; + } + + return $counts; + }//end seedCatalogue() + + /** + * The catalogue input of a seeded tile: a Nextcloud app link when the + * tile names an app, its web address otherwise. + * + * @param array $tile The tile. + * @param integer $position Its sort order. + * + * @return array The catalogue input. + */ + private function catalogueInput(array $tile, int $position): array { + $appId = (string)($tile['appId'] ?? ''); + $linkType = 'url'; + $link = (string)($tile['url'] ?? ''); + if ($appId !== '') { + $linkType = 'app'; + $link = $appId; + } + + return [ + 'name' => (string)$tile['name'], + 'description' => (string)($tile['description'] ?? ''), + 'icon' => 'icon-category-office', + 'iconType' => 'class', + 'linkType' => $linkType, + 'linkValue' => $link, + 'targetGroups' => [], + 'sortOrder' => $position, + ]; + }//end catalogueInput() + + /** + * Add or update the seeded announcements, matched by UUID. + * + * @param array> $entries The seed announcements. + * + * @return integer The number of announcements written. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function seedAnnouncements(array $entries): int { + $now = new DateTime(); + foreach ($entries as $entry) { + try { + $announcement = $this->announcements->findByUuid(uuid: (string)$entry['uuid']); + $this->announcements->update(entity: $this->applyAnnouncement(announcement: $announcement, entry: $entry)); + } catch (DoesNotExistException) { + $announcement = $this->applyAnnouncement(announcement: new Announcement(), entry: $entry); + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $announcement->setCreatedAt($now); + $this->announcements->insert(entity: $announcement); + } + } + + return count($entries); + }//end seedAnnouncements() + + /** + * Write a seeded announcement's fields, published from now without expiry. + * + * @param Announcement $announcement The announcement. + * @param array $entry The seed announcement. + * + * @return Announcement The announcement. + */ + private function applyAnnouncement(Announcement $announcement, array $entry): Announcement { + $now = new DateTime(); + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $announcement->setUuid((string)$entry['uuid']); + $announcement->setKind((string)($entry['kind'] ?? Announcement::KIND_NEWS)); + $announcement->setTitle((string)$entry['title']); + $announcement->setBody((string)($entry['body'] ?? '')); + $announcement->setCategory((string)($entry['category'] ?? '')); + $announcement->setLevel((string)($entry['level'] ?? 'info')); + $announcement->setDismissible((int)($entry['dismissible'] ?? 1)); + $announcement->setTargetGroups((string)json_encode(value: array_values(array: (array)($entry['targetGroups'] ?? [])))); + $announcement->setStatus(Announcement::STATUS_PUBLISHED); + $announcement->setPublishAt($now); + $announcement->setExpiresAt(null); + $announcement->setAllowComments(0); + $announcement->setAuthorId((string)($entry['author'] ?? 'admin')); + $announcement->setUpdatedAt($now); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + return $announcement; + }//end applyAnnouncement() +}//end class diff --git a/lib/Service/DemoSeedDashboards.php b/lib/Service/DemoSeedDashboards.php new file mode 100644 index 000000000..c6b13a70b --- /dev/null +++ b/lib/Service/DemoSeedDashboards.php @@ -0,0 +1,285 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTime; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\WidgetPlacement; +use OCP\AppFramework\Db\DoesNotExistException; +use RuntimeException; +use Throwable; + +/** + * Write seeded dashboards, their placements, shares and user preferences. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedDashboards { + /** + * Builds placements from payloads, the same way showcases and imports do. + * + * @var PlacementPayloadHydrator + */ + private readonly PlacementPayloadHydrator $hydrator; + + /** + * Constructor. + * + * @param ShowcaseStores $stores The dashboard and placement mappers and the database. + * @param DashboardShareService $shares Replaces a dashboard's shares and notifies new recipients. + * @param DemoSeedPreferences $preferences Which dashboard opens first; tour progress. + */ + public function __construct( + private readonly ShowcaseStores $stores, + private readonly DashboardShareService $shares, + private readonly DemoSeedPreferences $preferences, + ) { + $this->hydrator = new PlacementPayloadHydrator(); + }//end __construct() + + /** + * Write one seeded dashboard with its placements and shares. + * + * @param array $definition The seed dashboard. + * @param array> $payloads The expanded placement payloads. + * + * @return array{uuid: string, created: bool} The dashboard UUID and whether this run created it. + * + * @throws RuntimeException When the dashboard cannot be written. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function write(array $definition, array $payloads): array { + $this->stores->db->beginTransaction(); + try { + [$dashboard, $created] = $this->writeRows(definition: $definition, payloads: $payloads); + $this->stores->db->commit(); + } catch (Throwable $e) { + $this->stores->db->rollBack(); + throw new RuntimeException( + message: 'Could not seed dashboard ' . (string)$definition['name'] . ': ' . $e->getMessage(), + code: 0, + previous: $e + ); + } + + $this->applyAudience(dashboard: $dashboard, definition: $definition); + + return ['uuid' => (string)$definition['uuid'], 'created' => $created]; + }//end write() + + /** + * Write the dashboard row and replace its placements. + * + * @param array $definition The seed dashboard. + * @param array> $payloads The expanded placement payloads. + * + * @return array{0: Dashboard, 1: bool} The dashboard and whether it was created. + */ + private function writeRows(array $definition, array $payloads): array { + [$dashboard, $created] = $this->upsertDashboard(uuid: (string)$definition['uuid'], definition: $definition); + $dashboardId = (int)$dashboard->getId(); + + $this->stores->placementMapper->deleteByDashboardId(dashboardId: $dashboardId); + foreach ($payloads as $payload) { + $this->stores->placementMapper->insert(entity: $this->placementFor(dashboardId: $dashboardId, payload: $payload)); + } + + return [$dashboard, $created]; + }//end writeRows() + + /** + * Give the dashboard its shares and make it the first dashboard of the + * users the seed names. + * + * @param Dashboard $dashboard The written dashboard. + * @param array $definition The seed dashboard. + * + * @return void + */ + private function applyAudience(Dashboard $dashboard, array $definition): void { + $this->replaceShares(dashboard: $dashboard, shares: (array)($definition['shares'] ?? [])); + + foreach ((array)($definition['defaultFor'] ?? []) as $userId) { + $this->preferences->setDefaultDashboard(userId: (string)$userId, uuid: (string)$dashboard->getUuid()); + } + }//end applyAudience() + + /** + * The dashboard with this UUID brought to the seeded fields, inserted + * when it does not exist yet. + * + * @param string $uuid The fixed UUID. + * @param array $definition The seed dashboard. + * + * @return array{0: Dashboard, 1: bool} The persisted dashboard and whether it was created. + */ + private function upsertDashboard(string $uuid, array $definition): array { + $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); + try { + $dashboard = $this->stores->dashboardMapper->findByUuid(uuid: $uuid); + $created = false; + } catch (DoesNotExistException) { + $dashboard = new Dashboard(); + $created = true; + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $dashboard->setUuid($uuid); + $dashboard->setCreatedAt($now); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + } + + $this->applyFields(dashboard: $dashboard, definition: $definition); + + if ($created === true) { + return [$this->stores->dashboardMapper->insert(entity: $dashboard), true]; + } + + return [$this->stores->dashboardMapper->update(entity: $dashboard), false]; + }//end upsertDashboard() + + /** + * Write the seeded fields onto a dashboard. + * + * @param Dashboard $dashboard The dashboard. + * @param array $definition The seed dashboard. + * + * @return void + */ + private function applyFields(Dashboard $dashboard, array $definition): void { + $this->applyOwnership(dashboard: $dashboard, definition: $definition); + + // Entity setters resolve through __call, which reads $args[0]. + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $dashboard->setName((string)$definition['name']); + $dashboard->setDescription($this->stringOrNull(value: $definition['description'] ?? null)); + $dashboard->setIcon($this->stringOrNull(value: $definition['icon'] ?? null)); + $dashboard->setSlug('demo-' . (string)$definition['key']); + $dashboard->setGridColumns((int)($definition['gridColumns'] ?? 12)); + $dashboard->setSortOrder((int)($definition['sortOrder'] ?? 0)); + $dashboard->setPublicationStatus(Dashboard::STATUS_PUBLISHED); + $dashboard->setReactionsEnabled((int)($definition['reactionsEnabled'] ?? 0)); + $dashboard->setUpdatedAt((new DateTime())->format(format: 'Y-m-d H:i:s')); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + }//end applyFields() + + /** + * Write who a dashboard belongs to and what its audience may do: a + * personal dashboard has an owner, a group dashboard a group. + * + * @param Dashboard $dashboard The dashboard. + * @param array $definition The seed dashboard. + * + * @return void + */ + private function applyOwnership(Dashboard $dashboard, array $definition): void { + $type = (string)($definition['type'] ?? Dashboard::TYPE_USER); + $userId = $this->stringOrNull(value: $definition['owner'] ?? null); + $groupId = null; + if ($type === Dashboard::TYPE_GROUP_SHARED) { + $userId = null; + $groupId = (string)$definition['group']; + } + + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $dashboard->setType($type); + $dashboard->setUserId($userId); + $dashboard->setGroupId($groupId); + $dashboard->setPermissionLevel((string)($definition['permissionLevel'] ?? Dashboard::PERMISSION_FULL)); + $dashboard->setIsDefault(0); + $dashboard->setIsActive(0); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + }//end applyOwnership() + + /** + * A seed value as a string, null when it is absent. + * + * @param mixed $value The seed value. + * + * @return string|null The string, or null. + */ + private function stringOrNull(mixed $value): ?string { + if ($value === null) { + return null; + } + + return (string)$value; + }//end stringOrNull() + + /** + * A placement for a payload, with its read receipt when the payload asks + * for one. A relative deadline (`+4 days`) resolves against the run time. + * + * @param integer $dashboardId The dashboard id. + * @param array $payload The placement payload. + * + * @return WidgetPlacement The placement, not yet persisted. + */ + private function placementFor(int $dashboardId, array $payload): WidgetPlacement { + $placement = $this->hydrator->hydrate(dashboardId: $dashboardId, payload: $payload); + if ((int)($payload['requiresAcknowledgement'] ?? 0) !== 1) { + return $placement; + } + + $deadline = (string)($payload['acknowledgementDeadline'] ?? ''); + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $placement->setRequiresAcknowledgement(1); + $placement->setAcknowledgementPrompt((string)($payload['acknowledgementPrompt'] ?? '')); + if ($deadline !== '') { + $placement->setAcknowledgementDeadline((new DateTime($deadline))->format(format: 'Y-m-d H:i:s')); + } + + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + return $placement; + }//end placementFor() + + /** + * Give a personal dashboard exactly the seeded shares, through the share + * service, so a recipient who is new to the dashboard is notified once. + * A group dashboard has no owner and reaches its audience through its group. + * + * @param Dashboard $dashboard The written dashboard. + * @param array> $shares The seeded shares, `{type, with, permissionLevel}`. + * + * @return void + */ + private function replaceShares(Dashboard $dashboard, array $shares): void { + $owner = (string)$dashboard->getUserId(); + if ($owner === '') { + return; + } + + $grants = []; + foreach ($shares as $share) { + $grants[] = [ + 'shareType' => (string)$share['type'], + 'shareWith' => (string)$share['with'], + 'permissionLevel' => (string)($share['permissionLevel'] ?? Dashboard::PERMISSION_VIEW_ONLY), + ]; + } + + $this->shares->replaceShares(dashboardId: (int)$dashboard->getId(), shares: $grants, userId: $owner); + }//end replaceShares() +}//end class diff --git a/lib/Service/DemoSeedFiles.php b/lib/Service/DemoSeedFiles.php new file mode 100644 index 000000000..798b4fcbc --- /dev/null +++ b/lib/Service/DemoSeedFiles.php @@ -0,0 +1,167 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Constants; +use OCP\Files\Folder; +use OCP\Files\IRootFolder; +use OCP\Share\IManager as IShareManager; +use OCP\Share\IShare; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Seed the demo team folder and its group share. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedFiles { + /** + * Constructor. + * + * @param IRootFolder $rootFolder The user folders. + * @param IShareManager $shareManager Creates the group share. + * @param LoggerInterface $logger Logs a folder that could not be created. + */ + public function __construct( + private readonly IRootFolder $rootFolder, + private readonly IShareManager $shareManager, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * Ensure the team folder when the seed has one. A failure is logged and + * reported: the dashboards still load without the folder. + * + * @param mixed $definition The seed's `files` entry, or null. + * + * @return array What this run added, `{skipped: true}`, or `{error}`. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function ensureSafely(mixed $definition): array { + if (is_array($definition) === false) { + return ['skipped' => true]; + } + + try { + return $this->ensure(definition: $definition); + } catch (Throwable $e) { + $this->logger->warning( + message: 'Demo seed could not create the team folder: ' . $e->getMessage(), + context: ['exception' => $e] + ); + return ['error' => $e->getMessage()]; + } + }//end ensureSafely() + + /** + * Ensure the folder, its files and its group share exist. + * + * @param array $definition `{owner, folder, shareWithGroup, names}`. + * + * @return array{createdFiles: int, shared: bool} What this run added. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function ensure(array $definition): array { + $owner = (string)$definition['owner']; + $folderName = (string)$definition['folder']; + $home = $this->rootFolder->getUserFolder(userId: $owner); + + $folder = $this->folderIn(home: $home, name: $folderName); + $createdFiles = 0; + foreach ((array)($definition['names'] ?? []) as $name) { + if ($folder->nodeExists(path: (string)$name) === true) { + continue; + } + + $folder->newFile(path: (string)$name, content: ''); + $createdFiles++; + } + + $group = (string)($definition['shareWithGroup'] ?? ''); + $shared = false; + if ($group !== '') { + $shared = $this->shareWithGroup(folder: $folder, share: ['owner' => $owner, 'group' => $group]); + } + + return ['createdFiles' => $createdFiles, 'shared' => $shared]; + }//end ensure() + + /** + * The named folder in a home folder, created when absent. + * + * @param Folder $home The home folder. + * @param string $name The folder name. + * + * @return Folder The folder. + */ + private function folderIn(Folder $home, string $name): Folder { + if ($home->nodeExists(path: $name) === true) { + $node = $home->get(path: $name); + if ($node instanceof Folder) { + return $node; + } + } + + return $home->newFolder(path: $name); + }//end folderIn() + + /** + * Share the folder with a group unless that share exists. + * + * @param Folder $folder The folder. + * @param array $share `{owner, group}`: who shares it, and with which group. + * + * @return bool True when this run created the share. + */ + private function shareWithGroup(Folder $folder, array $share): bool { + ['owner' => $owner, 'group' => $group] = $share; + $existing = $this->shareManager->getSharesBy( + userId: $owner, + shareType: IShare::TYPE_GROUP, + path: $folder + ); + foreach ($existing as $share) { + if ($share->getSharedWith() === $group) { + return false; + } + } + + $share = $this->shareManager->newShare(); + $share->setNode(node: $folder); + $share->setShareType(shareType: IShare::TYPE_GROUP); + $share->setSharedWith(sharedWith: $group); + $share->setSharedBy(sharedBy: $owner); + $share->setShareOwner(shareOwner: $owner); + $share->setPermissions(permissions: Constants::PERMISSION_ALL); + $this->shareManager->createShare(share: $share); + + return true; + }//end shareWithGroup() +}//end class diff --git a/lib/Service/DemoSeedFirstRun.php b/lib/Service/DemoSeedFirstRun.php new file mode 100644 index 000000000..428408ef3 --- /dev/null +++ b/lib/Service/DemoSeedFirstRun.php @@ -0,0 +1,122 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeImmutable; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Event\DashboardDeletedEvent; + +/** + * Reset the first-run user and mark the tour as seen for the others. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedFirstRun { + /** + * Constructor. + * + * @param ShowcaseStores $stores The dashboard and placement mappers. + * @param DemoSeedPreferences $preferences Dashboard choices and tour progress. + * @param ShowcasePlatform $platform Announces deleted dashboards so their rows are cleaned up. + */ + public function __construct( + private readonly ShowcaseStores $stores, + private readonly DemoSeedPreferences $preferences, + private readonly ShowcasePlatform $platform, + ) { + }//end __construct() + + /** + * Record that a user has seen the getting-started tour. + * + * @param string $userId The user. + * @param string $version The tour version seen. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function markTourSeen(string $userId, string $version): void { + $this->preferences->markTourSeen(userId: $userId, version: $version); + }//end markTourSeen() + + /** + * Remove a user's own dashboards, dashboard choices and tour progress, + * and set the organisation-wide dashboards aside for them, so the next + * visit is a first visit. + * + * @param string $userId The user. + * + * @return integer The number of dashboards removed. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function resetToFirstRun(string $userId): int { + $removed = 0; + foreach ($this->stores->dashboardMapper->findByUserId(userId: $userId) as $dashboard) { + $dashboardId = (int)$dashboard->getId(); + $this->stores->placementMapper->deleteByDashboardId(dashboardId: $dashboardId); + $this->stores->dashboardMapper->delete(entity: $dashboard); + $this->platform->eventDispatcher?->dispatchTyped( + new DashboardDeletedEvent( + dashboardUuid: (string)$dashboard->getUuid(), + ownerUserId: $userId, + type: (string)$dashboard->getType(), + deletedAt: new DateTimeImmutable(), + dashboardId: $dashboardId + ) + ); + $removed++; + } + + $this->preferences->clear(userId: $userId); + $this->preferences->hideDashboards(userId: $userId, uuids: $this->organisationWideUuids()); + + return $removed; + }//end resetToFirstRun() + + /** + * The UUIDs of the organisation-wide (`default` group) dashboards, such + * as the install default from the SeedDefaultDashboard repair step. + * The first-run user has them set aside instead of deleted, so an + * administrator's edits to them survive the seed (Ruben, 25 Nov 2026). + * + * @return array The UUIDs. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + private function organisationWideUuids(): array { + $uuids = []; + foreach ($this->stores->dashboardMapper->findByGroup(groupId: Dashboard::DEFAULT_GROUP_ID) as $dashboard) { + $uuid = (string)$dashboard->getUuid(); + if ($uuid !== '') { + $uuids[] = $uuid; + } + } + + return $uuids; + }//end organisationWideUuids() +}//end class diff --git a/lib/Service/DemoSeedParts.php b/lib/Service/DemoSeedParts.php new file mode 100644 index 000000000..0d2502d23 --- /dev/null +++ b/lib/Service/DemoSeedParts.php @@ -0,0 +1,47 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Users and groups, dashboards, the first visit and the team folder of a seed. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedParts { + /** + * Constructor. + * + * @param DemoSeedAccounts $accounts Demo users and groups. + * @param DemoSeedDashboards $dashboards Seeded dashboards, placements and shares. + * @param DemoSeedFirstRun $firstRun The first visit of the first-run user; tour progress of the others. + * @param DemoSeedFiles $files The shared team folder. + */ + public function __construct( + public readonly DemoSeedAccounts $accounts, + public readonly DemoSeedDashboards $dashboards, + public readonly DemoSeedFirstRun $firstRun, + public readonly DemoSeedFiles $files, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/DemoSeedPreferences.php b/lib/Service/DemoSeedPreferences.php new file mode 100644 index 000000000..e5fa79fc9 --- /dev/null +++ b/lib/Service/DemoSeedPreferences.php @@ -0,0 +1,144 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\AppInfo\Application; +use OCP\IConfig; + +/** + * Set and clear the demo users' LaunchPad preferences. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedPreferences { + /** + * The user preference that records which version of the getting-started + * tour a user completed (manifest `walkthrough.completionConfigKey`, stored + * by PreferencesController with its `pref_` prefix). + * + * @var string + */ + public const WALKTHROUGH_PREF_KEY = 'pref_walkthrough_completed_version'; + + /** + * The user preference holding the dashboard that opens first; the key the + * dashboard resolver reads as its pinned default. + * + * @var string + */ + public const DEFAULT_DASHBOARD_PREF_KEY = 'default_dashboard_uuid'; + + /** + * The user preference holding the dashboard opened last. + * + * @var string + */ + public const ACTIVE_DASHBOARD_PREF_KEY = 'active_dashboard_uuid'; + + /** + * Constructor. + * + * @param IConfig $config The user preferences. + */ + public function __construct( + private readonly IConfig $config, + ) { + }//end __construct() + + /** + * Make a dashboard the one that opens first for a user. + * + * @param string $userId The user. + * @param string $uuid The dashboard UUID. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function setDefaultDashboard(string $userId, string $uuid): void { + $this->config->setUserValue($userId, Application::APP_ID, self::DEFAULT_DASHBOARD_PREF_KEY, $uuid); + }//end setDefaultDashboard() + + /** + * Record that a user has seen the getting-started tour, so it does not + * cover the demo dashboards. + * + * @param string $userId The user. + * @param string $version The tour version seen. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function markTourSeen(string $userId, string $version): void { + $this->config->setUserValue($userId, Application::APP_ID, self::WALKTHROUGH_PREF_KEY, $version); + }//end markTourSeen() + + /** + * Set organisation-wide dashboards aside for a user, so they do not + * open for that user and do not cover the first-visit empty state. + * Nothing is deleted: the dashboards stay for everyone else. + * + * @param string $userId The user. + * @param array $uuids The dashboard UUIDs; none clears the list. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function hideDashboards(string $userId, array $uuids): void { + if ($uuids === []) { + $this->config->deleteUserValue($userId, Application::APP_ID, DashboardService::HIDDEN_DASHBOARDS_PREF_KEY); + return; + } + + $this->config->setUserValue( + $userId, + Application::APP_ID, + DashboardService::HIDDEN_DASHBOARDS_PREF_KEY, + (string)json_encode(value: array_values(array: $uuids)) + ); + }//end hideDashboards() + + /** + * Clear a user's dashboard choices and tour progress. + * + * @param string $userId The user. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function clear(string $userId): void { + $keys = [ + self::DEFAULT_DASHBOARD_PREF_KEY, + self::ACTIVE_DASHBOARD_PREF_KEY, + self::WALKTHROUGH_PREF_KEY, + DashboardService::HIDDEN_DASHBOARDS_PREF_KEY, + ]; + foreach ($keys as $key) { + $this->config->deleteUserValue($userId, Application::APP_ID, $key); + } + }//end clear() +}//end class diff --git a/lib/Service/DemoSeedPublishing.php b/lib/Service/DemoSeedPublishing.php new file mode 100644 index 000000000..9274000ca --- /dev/null +++ b/lib/Service/DemoSeedPublishing.php @@ -0,0 +1,153 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\AdminSettingKey; +use OCA\LaunchPad\Db\AdminSettingMapper; + +/** + * Seed administrator settings, the public start page and kiosk playlists. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedPublishing { + /** + * Constructor. + * + * @param AdminSettingMapper $settings The administrator settings. + * @param PublicShareService $shares Public links. + * @param KioskService $kiosk Kiosk playlists. + */ + public function __construct( + private readonly AdminSettingMapper $settings, + private readonly PublicShareService $shares, + private readonly KioskService $kiosk, + ) { + }//end __construct() + + /** + * Bring administrator settings to the seeded values. A list is merged + * with the one an administrator keeps, any other value is set. + * + * @param array $values Setting key to value. + * + * @return void + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + public function mergeAdminSettings(array $values): void { + foreach ($values as $key => $value) { + if (is_array($value) === true && array_is_list($value) === true) { + $current = $this->settings->getValue(key: (string)$key, default: []); + if (is_array($current) === false) { + $current = []; + } + + $value = array_values(array: array_unique(array: [...$current, ...$value])); + } + + $this->settings->setSetting(key: (string)$key, value: $value); + } + }//end mergeAdminSettings() + + /** + * Prepare a dashboard as the public start page: its first public link + * without password or expiry, created when there is none, chosen as the + * start page. This does not switch the start page on (see + * enableStartPage()): while it is on, the plain login address shows the + * start page, and a demo seed must not change how an installation signs + * in unless it asks to. + * + * @param string $dashboardUuid The dashboard. + * @param string $publisher The administrator who publishes it. + * + * @return string The link token. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + public function publishStartPage(string $dashboardUuid, string $publisher): string { + $token = ''; + foreach ($this->shares->listActiveShares(dashboardUuid: $dashboardUuid, callerId: $publisher) as $share) { + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + if ((string)$share->getPasswordHash() === '' && $share->getExpiresAt() === null) { + $token = (string)$share->getToken(); + break; + } + + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + } + + if ($token === '') { + $token = (string)$this->shares->createPublicShare(dashboardUuid: $dashboardUuid, callerId: $publisher)->getToken(); + } + + $this->settings->setSetting(key: AdminSettingKey::PUBLIC_START_SHARE_TOKEN->value, value: $token); + + return $token; + }//end publishStartPage() + + /** + * Switch the public start page on, so signed-out visitors of the plain + * login address see it. Only called when a seed asks for it. + * + * @return void + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + public function enableStartPage(): void { + $this->settings->setSetting(key: AdminSettingKey::PUBLIC_START_ENABLED->value, value: true); + }//end enableStartPage() + + /** + * Bring a kiosk playlist to the seeded entries: the publisher's live + * playlist of that name keeps its token, otherwise a new one is made. + * + * @param array $playlist `{name, refresh, entries: [{dashboardUuid, dwellSeconds}]}`. + * @param string $publisher The administrator who owns it. + * + * @return string The playlist token. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + public function ensurePlaylist(array $playlist, string $publisher): string { + $draft = new KioskPlaylistDraft( + name: (string)($playlist['name'] ?? ''), + entries: (array)($playlist['entries'] ?? []), + refresh: (int)($playlist['refresh'] ?? 300) + ); + + foreach ($this->kiosk->listPlaylists(callerId: $publisher) as $existing) { + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + if ((string)$existing->getName() === $draft->name && $existing->getRevokedAt() === null) { + return (string)$this->kiosk->updatePlaylist(id: (int)$existing->getId(), draft: $draft, callerId: $publisher)->getToken(); + } + + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + } + + return (string)$this->kiosk->createPlaylist(draft: $draft, callerId: $publisher)->getToken(); + }//end ensurePlaylist() +}//end class diff --git a/lib/Service/DemoSeedService.php b/lib/Service/DemoSeedService.php new file mode 100644 index 000000000..63d59a004 --- /dev/null +++ b/lib/Service/DemoSeedService.php @@ -0,0 +1,329 @@ +.json`; this service writes it. It extends the demo + * showcases (same placement hydrator, same rule for which widget types can + * render, same catalogue seed), but where a showcase is one dashboard for + * everyone, the seed sets up a whole cast of people with their own and + * shared dashboards. + * + * Idempotent: users, groups, catalogue entries and announcements are + * matched by id, name or UUID and brought to the seeded values, and every + * dashboard has a fixed UUID whose placements and shares are replaced. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; +use OCP\App\IAppManager; +use RuntimeException; + +/** + * Load the LaunchPad demo environment. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedService { + /** + * The seeds that ship with LaunchPad. + * + * @var array + */ + public const SEED_IDS = ['zuiddrecht-boards']; + + /** + * The password a demo user gets when the seed creates it. Demo only; + * documented in docs/features/demo-seed.md. + * + * @var string + */ + public const DEFAULT_PASSWORD = 'Zuiddrecht-demo-2026!'; + + /** + * Constructor. + * + * @param DemoSeedParts $parts Accounts, dashboards, the first visit and the team folder. + * @param DemoSeedContent $content App catalogue, announcements and allowed sites. + * @param DemoShowcasesService $showcases Which widget types render; the bundled showcases. + * @param IAppManager $appManager Which apps are enabled. + * @param DemoSeedPublishing $publishing Administrator settings, the public start page and kiosk playlists. + */ + public function __construct( + private readonly DemoSeedParts $parts, + private readonly DemoSeedContent $content, + private readonly DemoShowcasesService $showcases, + private readonly IAppManager $appManager, + private readonly DemoSeedPublishing $publishing, + ) { + }//end __construct() + + /** + * Read and decode a seed definition, in the requested language when the + * seed has a translation for it (`..json`), as written otherwise. + * + * @param string $seedId The seed id. + * @param string $language The language, such as `en` or `en_GB`; '' for the seed as written. + * + * @return array The definition. + * + * @throws InvalidArgumentException When the seed is unknown or unreadable. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function definition(string $seedId, string $language = ''): array { + if (in_array(needle: $seedId, haystack: self::SEED_IDS, strict: true) === false) { + throw new InvalidArgumentException( + message: 'Unknown demo seed ' . $seedId . '. Known: ' . implode(separator: ', ', array: self::SEED_IDS) + ); + } + + $decoded = self::readJson(path: self::seedDirectory() . $seedId . '.json'); + if ($decoded === null) { + throw new InvalidArgumentException(message: 'Demo seed ' . $seedId . ' is missing or not valid JSON'); + } + + $translation = $this->translation(seedId: $seedId, language: $language); + return (new DemoSeedTranslation())->apply(seed: $decoded, strings: $translation['strings']); + }//end definition() + + /** + * The translation of a seed for a language: the most specific translation + * file that exists, or none. + * + * @param string $seedId The seed id. + * @param string $language The requested language, '' for none. + * + * @return array{language: string, strings: array} The language applied ('' for none) and its texts. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function translation(string $seedId, string $language): array { + foreach ((new DemoSeedTranslation())->candidates(language: $language) as $candidate) { + $decoded = self::readJson(path: self::seedDirectory() . $seedId . '.' . $candidate . '.json'); + if ($decoded !== null && is_array($decoded['strings'] ?? null) === true) { + return [ + 'language' => $candidate, + 'strings' => array_map(callback: 'strval', array: $decoded['strings']), + ]; + } + } + + return ['language' => '', 'strings' => []]; + }//end translation() + + /** + * The directory that holds the seed files, with a trailing slash. + * + * @return string The directory. + */ + private static function seedDirectory(): string { + return dirname(path: __DIR__, levels: 2) . '/data/demo-seed/'; + }//end seedDirectory() + + /** + * Decode a JSON file into an array. + * + * @param string $path The file. + * + * @return array|null The decoded array, null when missing or not a JSON object. + */ + private static function readJson(string $path): array|null { + if (is_readable(filename: $path) === false) { + return null; + } + + $decoded = json_decode(json: (string)file_get_contents(filename: $path), associative: true); + if (is_array($decoded) === false) { + return null; + } + + return $decoded; + }//end readJson() + + /** + * Load a seed. + * + * @param string $seedId The seed id. + * @param string $password The password for users this run creates. + * @param string $language The language of the texts, '' for the seed as written. + * + * @return array What the run did: the language applied, + * created users and groups, and per dashboard + * its UUID, placed widgets, skipped widget + * types and fallbacks used. + * + * @throws InvalidArgumentException When the seed is unknown. + * @throws RuntimeException When a user or dashboard cannot be written. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ + public function load(string $seedId, string $password = self::DEFAULT_PASSWORD, string $language = ''): array { + $seed = $this->definition(seedId: $seedId, language: $language); + $report = $this->seedAccounts(seed: $seed, password: $password); + + $report['language'] = $this->translation(seedId: $seedId, language: $language)['language']; + + $this->content->mergeAppConfig(values: (array)($seed['appConfig'] ?? [])); + $report['catalogue'] = $this->content->seedCatalogue(tiles: (array)($seed['tiles'] ?? [])); + $report['startDates'] = $this->content->seedStartDates(entry: (array)($seed['startDates'] ?? []), today: gmdate(format: 'Y-m-d')); + $report['announcements'] = $this->content->seedAnnouncements(entries: (array)($seed['announcements'] ?? [])); + $report['files'] = $this->parts->files->ensureSafely(definition: $seed['files'] ?? null); + $report['dashboards'] = $this->seedDashboards(seed: $seed); + $this->publishing->mergeAdminSettings(values: (array)($seed['adminSettings'] ?? [])); + $report['published'] = $this->publish(definition: (array)($seed['publishing'] ?? [])); + $report['firstRun'] = $this->resetFirstRunUsers( + users: (array)($seed['users'] ?? []), + tourVersion: (string)($seed['walkthroughSeenVersion'] ?? '') + ); + + return $report; + }//end load() + + /** + * Publish the seed's public start page and kiosk playlists as its + * publisher, an administrator account of the seed. + * + * @param array $definition `{publisher, startPage, enableStartPage, kioskPlaylists}`. + * + * @return array{startPage: string, kioskPlaylists: array} The link and playlist tokens. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + private function publish(array $definition): array { + $publisher = (string)($definition['publisher'] ?? ''); + $published = ['startPage' => '', 'kioskPlaylists' => []]; + if ($publisher === '') { + return $published; + } + + $startPage = (string)($definition['startPage'] ?? ''); + if ($startPage !== '') { + $published['startPage'] = $this->publishing->publishStartPage(dashboardUuid: $startPage, publisher: $publisher); + if (($definition['enableStartPage'] ?? false) === true) { + $this->publishing->enableStartPage(); + } + } + + foreach ((array)($definition['kioskPlaylists'] ?? []) as $playlist) { + $name = (string)($playlist['name'] ?? ''); + $published['kioskPlaylists'][$name] = $this->publishing->ensurePlaylist(playlist: (array)$playlist, publisher: $publisher); + } + + return $published; + }//end publish() + + /** + * Ensure the seed's groups and users. + * + * @param array $seed The seed. + * @param string $password The password for users this run creates. + * + * @return array{createdGroups: array, createdUsers: array} What this run created. + */ + private function seedAccounts(array $seed, string $password): array { + return [ + 'createdGroups' => $this->parts->accounts->ensureGroups(groups: (array)($seed['groups'] ?? [])), + 'createdUsers' => $this->parts->accounts->ensureUsers(seed: $seed, password: $password), + ]; + }//end seedAccounts() + + /** + * Uninstall every installed bundled showcase. Showcases are visible to + * everyone, so while one is installed no user ever sees the empty state + * of a first visit. + * + * @return array The ids of the showcases uninstalled. + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function retireShowcases(): array { + $retired = []; + foreach (DemoShowcasesService::BUNDLED_IDS as $showcaseId) { + if ($this->showcases->getInstalledUuid(showcaseId: $showcaseId) === '') { + continue; + } + + $this->showcases->uninstallShowcase(showcaseId: $showcaseId); + $retired[] = $showcaseId; + } + + return $retired; + }//end retireShowcases() + + /** + * Write every seeded dashboard. + * + * @param array $seed The seed. + * + * @return array> Per dashboard: key, board, name, uuid, created, placed, skipped, fallbacks. + */ + private function seedDashboards(array $seed): array { + $expander = new DemoSeedWidgets( + tiles: (array)($seed['tiles'] ?? []), + knownTypes: $this->showcases->renderableWidgetTypes(), + enabledApps: array_fill_keys(keys: $this->appManager->getEnabledApps(), value: true) + ); + + $result = []; + foreach ((array)($seed['dashboards'] ?? []) as $definition) { + $expanded = $expander->expand(entries: (array)($definition['widgets'] ?? [])); + $written = $this->parts->dashboards->write(definition: $definition, payloads: $expanded['placed']); + $result[] = [ + 'key' => (string)$definition['key'], + 'board' => (string)($definition['board'] ?? ''), + 'name' => (string)$definition['name'], + ...$written, + 'placed' => count($expanded['placed']), + 'skipped' => $expanded['skipped'], + 'fallbacks' => $expanded['fallbacks'], + ]; + } + + return $result; + }//end seedDashboards() + + /** + * Reset every first-run user to a first visit, and mark the tour as seen + * for every other demo user. + * + * @param array> $users The seed users. + * @param string $tourVersion The tour version to mark as seen, '' for none. + * + * @return array Per first-run user, the dashboards removed. + */ + private function resetFirstRunUsers(array $users, string $tourVersion): array { + $removed = []; + foreach ($users as $user) { + $userId = (string)$user['id']; + if (($user['firstRun'] ?? false) === true) { + $removed[$userId] = $this->parts->firstRun->resetToFirstRun(userId: $userId); + continue; + } + + if ($tourVersion !== '') { + $this->parts->firstRun->markTourSeen(userId: $userId, version: $tourVersion); + } + } + + return $removed; + }//end resetFirstRunUsers() +}//end class diff --git a/lib/Service/DemoSeedTileGaps.php b/lib/Service/DemoSeedTileGaps.php new file mode 100644 index 000000000..ef5445dda --- /dev/null +++ b/lib/Service/DemoSeedTileGaps.php @@ -0,0 +1,114 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Move tiles left over the cells of left-out tiles. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedTileGaps +{ + /** + * Move the tiles right of a left-out tile one place left, so a row of + * tiles has no hole. A tile only moves within its section (the columns + * of the section heading above it) and never past another widget. + * + * @param array> $placed The placed payloads. + * @param array $tiles The indexes of the tile payloads in $placed. + * @param array> $gaps The cells of the left-out tiles, `{x, y, w}`. + * + * @return array> The payloads with the gaps closed. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + public function close(array $placed, array $tiles, array $gaps): array { + usort($gaps, static fn (array $a, array $b): int => $b['x'] <=> $a['x']); + foreach ($gaps as $gap) { + foreach ($tiles as $index) { + $tileX = (int)$placed[$index]['gridX']; + if ((int)$placed[$index]['gridY'] !== $gap['y'] || $tileX <= $gap['x']) { + continue; + } + + if ($this->sectionOf(placed: $placed, column: $tileX) !== $this->sectionOf(placed: $placed, column: $gap['x']) + || $this->widgetBetween(placed: $placed, tiles: $tiles, gap: $gap, toX: $tileX) === true + ) { + continue; + } + + $placed[$index]['gridX'] = $tileX - $gap['w']; + } + } + + return $placed; + }//end close() + + /** + * The index of the section heading whose columns hold $column, -1 for none. + * + * @param array> $placed The placed payloads. + * @param int $column The column. + * + * @return int The heading's index. + */ + private function sectionOf(array $placed, int $column): int { + foreach ($placed as $index => $payload) { + $left = (int)($payload['gridX'] ?? 0); + if (($payload['widgetId'] ?? '') === 'section-heading' && $column >= $left && $column < $left + (int)($payload['gridWidth'] ?? 1)) { + return $index; + } + } + + return -1; + }//end sectionOf() + + /** + * Whether a widget other than a tile covers a cell of the gap's row between the gap and column $toX. + * + * @param array> $placed The placed payloads. + * @param array $tiles The indexes of the tile payloads. + * @param array $gap The gap, `{x, y, w}`. + * @param int $toX The tile's column. + * + * @return bool True when another widget sits in between. + */ + private function widgetBetween(array $placed, array $tiles, array $gap, int $toX): bool { + foreach ($placed as $index => $payload) { + if (in_array($index, $tiles, true) === true) { + continue; + } + + $left = (int)($payload['gridX'] ?? 0); + $top = (int)($payload['gridY'] ?? 0); + $overlapsColumns = $left < $toX && $left + (int)($payload['gridWidth'] ?? 1) > $gap['x']; + $overlapsRow = $gap['y'] >= $top && $gap['y'] < $top + (int)($payload['gridHeight'] ?? 1); + if ($overlapsColumns === true && $overlapsRow === true) { + return true; + } + } + + return false; + }//end widgetBetween() +}//end class diff --git a/lib/Service/DemoSeedTranslation.php b/lib/Service/DemoSeedTranslation.php new file mode 100644 index 000000000..679672721 --- /dev/null +++ b/lib/Service/DemoSeedTranslation.php @@ -0,0 +1,110 @@ +..json` maps + * each text of the seed to its translation, and this class swaps them in. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Translate the texts of a demo seed definition. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +final class DemoSeedTranslation { + /** + * Keys whose value is an identifier, a link, a filter or data that other + * apps match on. Their values, and everything under them, stay as written. + * + * @var array + */ + public const KEEP_KEYS = [ + '_comment', 'seedId', 'seedVersion', 'walkthroughSeenVersion', 'groups', 'users', 'files', 'appConfig', + 'uuid', 'key', 'board', 'widgetId', 'tile', 'icon', 'url', 'link', 'appId', 'owner', 'group', 'targetGroups', + 'author', 'shares', 'source', 'filter', 'status', 'values', 'with', 'internalCalendars', 'space', 'project', + 'scope', 'feedUrls', 'videoUrl', 'colors', 'location', 'timezone', 'adminSettings', 'publishing', + ]; + + /** + * Replace every text of the seed that the map translates. A text is + * replaced only when its whole value is a key of the map. + * + * @param array $seed The seed definition. + * @param array $strings Each original text and its translation. + * + * @return array The translated definition. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + public function apply(array $seed, array $strings): array { + if ($strings === []) { + return $seed; + } + + return $this->translateArray(values: $seed, strings: $strings); + }//end apply() + + /** + * The language tags to try for a requested language, most specific first: + * `en_GB` tries `en_GB`, then `en`. + * + * @param string $language The requested language, '' for none. + * + * @return array The candidate tags. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + public function candidates(string $language): array { + $language = str_replace(search: '-', replace: '_', subject: trim(string: $language)); + if (preg_match(pattern: '/^[A-Za-z]{2,3}(_[A-Za-z0-9]{2,8})?$/', subject: $language) !== 1) { + return []; + } + + $base = strtolower(string: explode(separator: '_', string: $language)[0]); + return array_values(array: array_unique(array: [$language, $base])); + }//end candidates() + + /** + * Translate one level of the definition. + * + * @param array $values The values. + * @param array $strings The translation map. + * + * @return array The translated values. + */ + private function translateArray(array $values, array $strings): array { + foreach ($values as $key => $value) { + if (is_string(value: $key) === true && in_array(needle: $key, haystack: self::KEEP_KEYS, strict: true) === true) { + continue; + } + + if (is_array(value: $value) === true) { + $values[$key] = $this->translateArray(values: $value, strings: $strings); + continue; + } + + if (is_string(value: $value) === true && isset($strings[$value]) === true) { + $values[$key] = $strings[$value]; + } + } + + return $values; + }//end translateArray() +}//end class diff --git a/lib/Service/DemoSeedWidgets.php b/lib/Service/DemoSeedWidgets.php new file mode 100644 index 000000000..1d9df0b18 --- /dev/null +++ b/lib/Service/DemoSeedWidgets.php @@ -0,0 +1,343 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * @spec openspec/specs/demo-data-showcases/spec.md + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Expand demo seed widget entries into placement payloads. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +class DemoSeedWidgets { + /** + * Settings a tile entry may carry into its placement's content, with the + * type each must have: a tile that shows only its glyph, one whose rows + * take its own size on a dashboard that fills the screen, its pin, its + * count and its outage dot (LpVandaag, LpWerkplek). + * + * @var array + */ + private const TILE_CONTENT_SETTINGS = [ + 'iconOnly' => 'boolean', + 'fitRows' => 'boolean', + 'pinned' => 'boolean', + ]; + + /** + * The widget type of a single app tile. + * + * @var string + */ + public const APP_TILE_TYPE = 'app-tile'; + + /** + * The Zuiddrecht colour of each tile colour token. A launcher tile stores + * a hex colour (seven characters), so it gets this value and keeps the + * token in its content. + * + * @var array + */ + public const TOKEN_FALLBACKS = [ + 'primary' => '#3669a5', + 'primary-deep' => '#234a78', + 'accent' => '#cc0000', + 'accent-deep' => '#a30000', + 'work-ink' => '#1b1c1d', + 'work-text' => '#3d4047', + 'work-muted' => '#5e6168', + 'work-field' => '#828a95', + ]; + + /** + * Constructor. + * + * @param array> $tiles The seed's tile catalogue, keyed by tile key. + * @param array $knownTypes The widget types this instance renders. + * @param array $enabledApps The app ids enabled on this instance. + */ + public function __construct( + private readonly array $tiles, + private readonly array $knownTypes, + private readonly array $enabledApps, + ) { + }//end __construct() + + /** + * Expand a dashboard's widget entries. + * + * Sort order follows the entry order, so a re-run places the same + * widgets in the same order. + * + * @param array> $entries The seed entries. + * + * @return array{placed: array>, skipped: array, fallbacks: array} + * + * @spec openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md + */ + public function expand(array $entries): array { + $placed = []; + $skipped = []; + $fallbacks = []; + $gaps = []; + $tiles = []; + foreach (array_values(array: $entries) as $order => $entry) { + $payload = $this->resolve(entry: $entry); + if ($payload === null) { + $skipped[] = $this->labelOf(entry: $entry); + if (isset($entry['tile']) === true) { + $gaps[] = ['x' => (int)($entry['gridX'] ?? 0), 'y' => (int)($entry['gridY'] ?? 0), 'w' => (int)($entry['gridWidth'] ?? 2)]; + } + + continue; + } + + if (isset($entry['tile']) === true) { + $tiles[] = count($placed); + } + + if ($payload['widgetId'] !== ($entry['widgetId'] ?? $payload['widgetId'])) { + $fallbacks[] = (string)$entry['widgetId'] . ' -> ' . $payload['widgetId']; + } + + $payload['sortOrder'] = $order; + $placed[] = $payload; + } + + $placed = (new DemoSeedTileGaps())->close(placed: $placed, tiles: $tiles, gaps: $gaps); + + return ['placed' => $placed, 'skipped' => $skipped, 'fallbacks' => $fallbacks]; + }//end expand() + + /** + * The payload one entry places, null when nothing it names can render. + * + * @param array $entry The seed entry. + * + * @return array|null The payload. + */ + private function resolve(array $entry): ?array { + if (isset($entry['tile']) === true) { + return $this->tilePayload(entry: $entry); + } + + if ($this->isRenderable(entry: $entry) === true) { + unset($entry['fallback']); + return $entry; + } + + $fallback = $entry['fallback'] ?? null; + if (is_array($fallback) === true && $this->isRenderable(entry: $fallback) === true) { + return $fallback; + } + + return null; + }//end resolve() + + /** + * Whether an entry's widget type is registered. An `nc-widget` also needs + * the Nextcloud dashboard widget it shows, otherwise it only says that + * the widget is unavailable. + * + * @param array $entry The seed entry. + * + * @return bool True when the entry can render. + */ + private function isRenderable(array $entry): bool { + $widgetId = (string)($entry['widgetId'] ?? ''); + if (isset($this->knownTypes[$widgetId]) === false) { + return false; + } + + if ($widgetId !== 'nc-widget') { + return true; + } + + return isset($this->knownTypes[(string)($entry['content']['widgetId'] ?? '')]) === true; + }//end isRenderable() + + /** + * The payload of a tile entry: an app tile for an enabled app, a + * coloured launcher tile otherwise. + * + * @param array $entry The seed entry, `{tile, gridX, gridY}`. + * + * @return array|null The payload, null for an unknown tile key. + */ + private function tilePayload(array $entry): ?array { + $tile = $this->tiles[(string)$entry['tile']] ?? null; + if (is_array($tile) === false) { + return null; + } + + $layout = [ + 'gridX' => (int)($entry['gridX'] ?? 0), + 'gridY' => (int)($entry['gridY'] ?? 0), + 'gridWidth' => (int)($entry['gridWidth'] ?? 2), + 'gridHeight' => (int)($entry['gridHeight'] ?? 2), + 'showTitle' => 0, + ]; + + $fields = $this->tileFields(tile: $tile); + if ($fields === null) { + return null; + } + + $payload = [...$layout, ...$fields]; + foreach (self::TILE_CONTENT_SETTINGS as $key => $type) { + if (isset($entry[$key]) === true && gettype($entry[$key]) === $type) { + $payload['content'][$key] = $entry[$key]; + } + } + + return $payload; + }//end tilePayload() + + /** + * The type-specific fields of a tile: an app tile for an enabled app when + * that type exists, a launcher tile otherwise. + * + * A tile whose address opens an app that is not enabled is left out: as a + * launcher tile it would link to a page that does not exist, and as an app + * tile it would show "not available" on a demo dashboard. + * + * @param array $tile The catalogue tile. + * + * @return array|null The placement fields, null when the tile cannot work here. + */ + private function tileFields(array $tile): ?array { + $colour = (string)($tile['colour'] ?? 'primary'); + $appId = (string)($tile['appId'] ?? ''); + $enabled = $appId !== '' && isset($this->enabledApps[$appId]) === true; + $missing = $appId !== '' && $enabled === false && str_contains((string)($tile['url'] ?? ''), '/apps/' . $appId . '/') === true; + $appTiles = isset($this->knownTypes[self::APP_TILE_TYPE]); + if ($missing === true) { + return null; + } + + if ($enabled === true && $appTiles === true) { + $content = ['appId' => $appId, 'colour' => $colour, 'showCount' => true]; + // The board's glyph and the app's own counter (LpVandaag). + if (is_string($tile['icon'] ?? null) === true) { + $content['icon'] = $tile['icon']; + } + + if (is_array($tile['countSource'] ?? null) === true) { + $content['countSource'] = $tile['countSource']; + } + + return [ + 'widgetId' => self::APP_TILE_TYPE, + 'customTitle' => (string)$tile['name'], + 'content' => $content, + ]; + } + + return $this->launcherTileFields(tile: $tile, colour: $colour); + }//end tileFields() + + /** + * The fields of a launcher tile in the tile's colour. + * + * @param array $tile The catalogue tile. + * @param string $colour The colour token. + * + * @return array The placement fields. + */ + private function launcherTileFields(array $tile, string $colour): array { + // REQ-ICT-004: the tile renders through its theme token; REQ-ICT-002: + // it reads its count live from its source, never a static value. + $content = ['colour' => $colour, 'colourToken' => '--sc-' . $colour]; + $source = $this->countSourceOf(source: $tile['countSource'] ?? null); + if ($source !== null) { + $content['countSource'] = $source; + } + + return [ + 'widgetId' => 'tile', + 'tileType' => 'custom', + 'tileTitle' => (string)$tile['name'], + 'tileIcon' => (string)($tile['icon'] ?? ''), + 'tileIconType' => 'mdi', + 'tileBackgroundColor' => self::TOKEN_FALLBACKS[$colour] ?? self::TOKEN_FALLBACKS['primary'], + 'tileTextColor' => '#ffffff', + 'tileLinkType' => 'url', + 'tileLinkValue' => (string)($tile['url'] ?? ''), + 'content' => $content, + ]; + }//end launcherTileFields() + + /** + * A catalogue count source in the shape a launcher tile reads: a + * register source with its register, schema and filter, or the items of + * a Nextcloud dashboard widget. + * + * @param mixed $source The catalogue's count source. + * + * @return array|null The tile's count source, null for none. + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ + private function countSourceOf(mixed $source): ?array { + if (is_array($source) === false) { + return null; + } + + if (is_string($source['dashboardWidget'] ?? null) === true && $source['dashboardWidget'] !== '') { + return ['type' => 'nc-widget', 'widgetId' => $source['dashboardWidget']]; + } + + if (is_string($source['register'] ?? null) === true && is_string($source['schema'] ?? null) === true) { + $filter = []; + if (is_array($source['filter'] ?? null) === true) { + $filter = $source['filter']; + } + + return ['type' => 'register', 'register' => $source['register'], 'schema' => $source['schema'], 'filter' => $filter]; + } + + return null; + }//end countSourceOf() + + /** + * A readable name for a skipped entry. + * + * @param array $entry The seed entry. + * + * @return string The widget type, with its title when it has one. + */ + private function labelOf(array $entry): string { + if (isset($entry['tile']) === true) { + return 'tile ' . (string)$entry['tile']; + } + + $label = (string)($entry['widgetId'] ?? '?'); + if (isset($entry['customTitle']) === true) { + $label .= ' (' . (string)$entry['customTitle'] . ')'; + } + + return $label; + }//end labelOf() +}//end class diff --git a/lib/Service/DemoShowcasesService.php b/lib/Service/DemoShowcasesService.php index c5b77edb8..3c80a4c47 100644 --- a/lib/Service/DemoShowcasesService.php +++ b/lib/Service/DemoShowcasesService.php @@ -37,16 +37,11 @@ use DateTimeImmutable; use OCA\LaunchPad\AppInfo\Application; use OCA\LaunchPad\Db\Dashboard; -use OCA\LaunchPad\Db\DashboardMapper; -use OCA\LaunchPad\Db\WidgetPlacementMapper; use OCA\LaunchPad\Event\DashboardDeletedEvent; use OCA\LaunchPad\Exception\ShowcaseNotFoundException; +use OCA\LaunchPad\Support\WidgetTypeList; use OCP\AppFramework\Db\DoesNotExistException; use OCP\Dashboard\IManager; -use OCP\EventDispatcher\IEventDispatcher; -use OCP\IAppConfig; -use OCP\IDBConnection; -use OCP\IURLGenerator; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; use Psr\Log\LoggerInterface; @@ -99,19 +94,10 @@ class DemoShowcasesService { 'gemeente-duin', 'horizon-labs', 'van-der-berg', + 'zuiddrecht-intranet', + 'zuiddrecht-management', ]; - /** - * Where the list of LaunchPad's own widget types lives. - * - * Shared with the frontend: `widgetRegistry.completeness.spec.js` - * asserts the registry's keys equal this file, so the types the - * installer keeps and the types the workspace can render cannot drift. - * - * @var string - */ - private const WIDGET_TYPES_PATH = __DIR__ . '/../widget-types.json'; - /** * Optional data-directory override (test seam). * @@ -139,35 +125,16 @@ class DemoShowcasesService { /** * Constructor. * - * @param DashboardMapper $dashboardMapper Dashboard data mapper. - * @param WidgetPlacementMapper $placementMapper Widget placement mapper. - * @param IDBConnection $db Database connection. - * @param IAppConfig $appConfig App config service. - * @param IManager $dashboardManager Nextcloud dashboard registry. - * @param LoggerInterface $logger PSR-3 logger. - * @param ILockingProvider $lockingProvider Advisory lock provider - * (M8 — concurrency guard - * on installShowcase). - * @param IURLGenerator $urlGenerator URL generator used to - * build routed thumbnail - * URLs that resolve from - * any apps directory. - * @param IEventDispatcher|null $eventDispatcher Event dispatcher for - * DashboardDeletedEvent - * (SB1 fix, REQ-CSC-001). - * Nullable for backwards- - * compat. + * @param ShowcaseStores $stores The dashboard and placement mappers, the database and the lock provider. + * @param ShowcasePlatform $platform App config, dashboard manager, URL generator and event dispatcher. + * @param LoggerInterface $logger PSR-3 logger. + * @param CatalogueService|null $catalogue Seeds the demo app catalogue entries on an install (launcher-app-catalogue). */ public function __construct( - private readonly DashboardMapper $dashboardMapper, - private readonly WidgetPlacementMapper $placementMapper, - private readonly IDBConnection $db, - private readonly IAppConfig $appConfig, - private readonly IManager $dashboardManager, + private readonly ShowcaseStores $stores, + private readonly ShowcasePlatform $platform, private readonly LoggerInterface $logger, - private readonly ILockingProvider $lockingProvider, - private readonly IURLGenerator $urlGenerator, - private readonly ?IEventDispatcher $eventDispatcher = null, + private readonly ?CatalogueService $catalogue = null, ) { $this->placementHydrator = new PlacementPayloadHydrator(); }//end __construct() @@ -244,29 +211,67 @@ public function getAvailableShowcases(): array { * @spec openspec/specs/demo-data-showcases/spec.md */ public function describeShowcase(string $showcaseId): ?array { - $zipPath = $this->getZipPath(showcaseId: $showcaseId); - if (file_exists(filename: $zipPath) === false) { + $manifest = $this->readShowcaseManifest(showcaseId: $showcaseId); + if ($manifest === null) { return null; } - $manifest = $this->readManifest(zipPath: $zipPath); - if ($manifest === null) { + return $this->descriptorFor(showcaseId: $showcaseId, manifest: $manifest); + }//end describeShowcase() + + /** + * The manifest of a showcase's archive, null when the archive is + * absent or its manifest unreadable. + * + * @param string $showcaseId The showcase ID. + * + * @return array|null The decoded manifest. + */ + private function readShowcaseManifest(string $showcaseId): ?array { + $zipPath = $this->getZipPath(showcaseId: $showcaseId); + if (file_exists(filename: $zipPath) === false) { return null; } + return $this->readManifest(zipPath: $zipPath); + }//end readShowcaseManifest() + + /** + * Build the gallery descriptor of a readable showcase. + * + * @param string $showcaseId The showcase ID. + * @param array $manifest The decoded manifest. + * + * @return array The descriptor. + */ + private function descriptorFor(string $showcaseId, array $manifest): array { $installedUuid = $this->getInstalledUuid(showcaseId: $showcaseId); - $installedDashboardId = null; - if ($installedUuid !== '') { - $installedDashboardId = $installedUuid; - } + return [ + 'id' => $showcaseId, + 'name' => (string)($manifest['showcaseName'] ?? $showcaseId), + 'description' => (string)($manifest['showcaseDescription'] ?? ''), + 'language' => (string)($manifest['showcaseLanguage'] ?? 'nl'), + 'thumbnailUrl' => $this->thumbnailUrl(showcaseId: $showcaseId), + 'isInstalled' => $installedUuid !== '', + 'installedDashboardUuid' => $this->installedDashboardUuid(installedUuid: $installedUuid), + ]; + }//end descriptorFor() + + /** + * The showcase's preview image URL, null (logged) when it is absent. + * + * @param string $showcaseId The showcase ID. + * + * @return string|null The URL, or null. + */ + private function thumbnailUrl(string $showcaseId): ?string { // The imagePath() call THROWS when the image is absent, and this runs once per // showcase inside the listing, so one showcase without a preview used // to 500 the whole gallery. A missing thumbnail is a cosmetic gap in // one card, not a reason to hide the other five. - $thumbnailUrl = null; try { - $thumbnailUrl = $this->urlGenerator->imagePath( + return $this->platform->urlGenerator->imagePath( Application::APP_ID, 'showcases/' . $showcaseId . '.png' ); @@ -275,18 +280,24 @@ public function describeShowcase(string $showcaseId): ?array { message: 'Showcase ' . $showcaseId . ' has no preview image', context: ['exception' => $e] ); + return null; } + }//end thumbnailUrl() - return [ - 'id' => $showcaseId, - 'name' => (string)($manifest['showcaseName'] ?? $showcaseId), - 'description' => (string)($manifest['showcaseDescription'] ?? ''), - 'language' => (string)($manifest['showcaseLanguage'] ?? 'nl'), - 'thumbnailUrl' => $thumbnailUrl, - 'isInstalled' => $installedUuid !== '', - 'installedDashboardUuid' => $installedDashboardId, - ]; - }//end describeShowcase() + /** + * The installed dashboard UUID, null when the showcase is not installed. + * + * @param string $installedUuid The recorded UUID, or `''`. + * + * @return string|null The UUID, or null. + */ + private function installedDashboardUuid(string $installedUuid): ?string { + if ($installedUuid === '') { + return null; + } + + return $installedUuid; + }//end installedDashboardUuid() /** * Install a showcase as a `group_shared` dashboard. @@ -316,6 +327,32 @@ public function installShowcase( string $lang = 'nl', bool $force = false, ): array { + $this->assertInstallable(showcaseId: $showcaseId); + + // M8: acquire an exclusive advisory lock keyed on the showcase ID + // before the existence check to serialise concurrent installs. + // Two simultaneous admin requests both pass the existence check + // before either inserts without this guard. + $lockKey = 'launchpad-showcase-install-' . $showcaseId; + $this->acquireInstallLock(lockKey: $lockKey, showcaseId: $showcaseId); + + try { + return $this->installLocked(showcaseId: $showcaseId, options: new ShowcaseInstallOptions(lang: $lang, force: $force)); + } finally { + $this->releaseInstallLock(lockKey: $lockKey); + } + }//end installShowcase() + + /** + * Refuse an unknown showcase or one whose archive is missing. + * + * @param string $showcaseId The showcase ID. + * + * @return void + * + * @throws ShowcaseNotFoundException When the showcase cannot be installed. + */ + private function assertInstallable(string $showcaseId): void { $this->assertKnownShowcase(showcaseId: $showcaseId); $zipPath = $this->getZipPath(showcaseId: $showcaseId); @@ -324,14 +361,21 @@ public function installShowcase( message: 'Showcase ZIP missing for ' . $showcaseId ); } + }//end assertInstallable() - // M8: acquire an exclusive advisory lock keyed on the showcase ID - // before the existence check to serialise concurrent installs. - // Two simultaneous admin requests both pass the existence check - // before either inserts without this guard. - $lockKey = 'launchpad-showcase-install-' . $showcaseId; + /** + * Take the exclusive install lock of a showcase. + * + * @param string $lockKey The lock path. + * @param string $showcaseId The showcase ID (for the message). + * + * @return void + * + * @throws RuntimeException When another install holds the lock. + */ + private function acquireInstallLock(string $lockKey, string $showcaseId): void { try { - $this->lockingProvider->acquireLock( + $this->stores->lockingProvider->acquireLock( path: $lockKey, type: ILockingProvider::LOCK_EXCLUSIVE ); @@ -342,32 +386,47 @@ public function installShowcase( previous: $e ); } + }//end acquireInstallLock() - try { - $existingUuid = $this->getInstalledUuid(showcaseId: $showcaseId); - if ($existingUuid !== '' && $force === false) { - return [ - 'installedDashboardUuid' => $existingUuid, - 'skippedWidgets' => [], - 'alreadyInstalled' => true, - ]; - } + /** + * Release the exclusive install lock of a showcase. + * + * @param string $lockKey The lock path. + * + * @return void + */ + private function releaseInstallLock(string $lockKey): void { + $this->stores->lockingProvider->releaseLock( + path: $lockKey, + type: ILockingProvider::LOCK_EXCLUSIVE + ); + }//end releaseInstallLock() - if ($existingUuid !== '' && $force === true) { - $this->uninstallShowcase(showcaseId: $showcaseId); - } + /** + * Install while the lock is held: reuse an existing install, or + * replace it when forced, else install fresh. + * + * @param string $showcaseId The showcase ID. + * @param ShowcaseInstallOptions $options The language and force flag. + * + * @return array{installedDashboardUuid:string, skippedWidgets:array, alreadyInstalled:bool} + */ + private function installLocked(string $showcaseId, ShowcaseInstallOptions $options): array { + $existingUuid = $this->getInstalledUuid(showcaseId: $showcaseId); + if ($existingUuid !== '' && $options->force === false) { + return [ + 'installedDashboardUuid' => $existingUuid, + 'skippedWidgets' => [], + 'alreadyInstalled' => true, + ]; + } - return $this->doInstallShowcase( - showcaseId: $showcaseId, - lang: $lang - ); - } finally { - $this->lockingProvider->releaseLock( - path: $lockKey, - type: ILockingProvider::LOCK_EXCLUSIVE - ); - }//end try - }//end installShowcase() + if ($existingUuid !== '') { + $this->uninstallShowcase(showcaseId: $showcaseId); + } + + return $this->doInstallShowcase(showcaseId: $showcaseId, lang: $options->lang); + }//end installLocked() /** * Internal install logic (called while lock is held). @@ -391,20 +450,20 @@ private function doInstallShowcase(string $showcaseId, string $lang): array { sourceLanguage: $lang ); - $this->db->beginTransaction(); + $this->stores->db->beginTransaction(); try { - $persisted = $this->dashboardMapper->insert(entity: $dashboard); + $persisted = $this->stores->dashboardMapper->insert(entity: $dashboard); foreach ($valid as $widgetPayload) { $placement = $this->placementHydrator->hydrate( dashboardId: (int)$persisted->getId(), payload: $widgetPayload ); - $this->placementMapper->insert(entity: $placement); + $this->stores->placementMapper->insert(entity: $placement); } - $this->db->commit(); + $this->stores->db->commit(); } catch (Throwable $e) { - $this->db->rollBack(); + $this->stores->db->rollBack(); throw new RuntimeException( message: 'Failed to persist showcase: ' . $e->getMessage(), code: 0, @@ -417,6 +476,7 @@ private function doInstallShowcase(string $showcaseId, string $lang): array { showcaseId: $showcaseId, dashboardUuid: $installedUuid ); + $this->seedCatalogue(); $this->logger->info( message: 'Installed demo showcase', @@ -435,6 +495,30 @@ private function doInstallShowcase(string $showcaseId, string $lang): array { ]; }//end doInstallShowcase() + /** + * Give an empty app catalogue the demo entries a municipality would + * recognise (launcher-app-catalogue, design "Seed data"). A failure is + * logged and does not undo the showcase. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-9 + */ + private function seedCatalogue(): void { + if ($this->catalogue === null) { + return; + } + + try { + $this->catalogue->seedDemoEntries(); + } catch (Throwable $e) { + $this->logger->warning( + message: 'Could not seed the demo app catalogue: ' . $e->getMessage(), + context: ['exception' => $e] + ); + } + }//end seedCatalogue() + /** * Uninstall a previously-installed showcase. * @@ -455,16 +539,16 @@ public function uninstallShowcase(string $showcaseId): void { } try { - $dashboard = $this->dashboardMapper->findByUuid(uuid: $existingUuid); + $dashboard = $this->stores->dashboardMapper->findByUuid(uuid: $existingUuid); $dashId = (int)$dashboard->getId(); - $this->placementMapper->deleteByDashboardId(dashboardId: $dashId); - $this->dashboardMapper->delete(entity: $dashboard); + $this->stores->placementMapper->deleteByDashboardId(dashboardId: $dashId); + $this->stores->dashboardMapper->delete(entity: $dashboard); // SB1 fix: dispatch DashboardDeletedEvent for cascade cleanup // (REQ-CSC-001). $deletedUuid = (string)$dashboard->getUuid(); - if ($this->eventDispatcher !== null && $deletedUuid !== '') { - $this->eventDispatcher->dispatchTyped( + if ($this->platform->eventDispatcher !== null && $deletedUuid !== '') { + $this->platform->eventDispatcher->dispatchTyped( new DashboardDeletedEvent( dashboardUuid: $deletedUuid, ownerUserId: (string)($dashboard->getUserId() ?? ''), @@ -496,7 +580,7 @@ public function uninstallShowcase(string $showcaseId): void { * @spec openspec/specs/demo-data-showcases/spec.md */ public function getInstalledUuid(string $showcaseId): string { - return $this->appConfig->getValueString( + return $this->platform->appConfig->getValueString( Application::APP_ID, self::CONFIG_PREFIX . $showcaseId, '' @@ -508,21 +592,11 @@ public function getInstalledUuid(string $showcaseId): string { * skip (REQ-DEMO-005). * * A widget is kept when LaunchPad can render it. That is true in three - * cases, checked in this order: - * - * 1. it is a tile (`tileType` set), rendered by LaunchPad's tile renderer; - * 2. its `widgetId` is one of LaunchPad's OWN widget types - * (`lib/widget-types.json`: `object-list`, `nc-widget`, `calendar`, - * `text` and the rest), rendered by the workspace's widget registry; - * 3. its `widgetId` is a Nextcloud dashboard widget registered on this - * instance (`IManager::getWidgets()`), rendered through the bridge. - * - * Anything else is skipped, which is what the skip exists for: a bare - * Nextcloud widget id whose app is not installed here. - * - * Case 2 is new. Before it, a LaunchPad type counted as "unknown" - * because it is not in Nextcloud's registry, so the `case-handler` - * showcase, built entirely from LaunchPad types, installed as an empty + * cases: it is a tile (`tileType` set), it is one of LaunchPad's own + * widget types (`lib/widget-types.json`), or it is a Nextcloud dashboard + * widget registered on this instance. Before the second case existed + * every LaunchPad widget was skipped, so a showcase built entirely from + * LaunchPad types, installed as an empty * dashboard and still reported success. * * An `nc-widget` is kept whatever widget it proxies. The check is on the @@ -539,44 +613,66 @@ public function getInstalledUuid(string $showcaseId): string { * @spec openspec/specs/demo-data-showcases/spec.md */ public function partitionWidgets(array $widgets): array { - $registered = []; - foreach ($this->dashboardManager->getWidgets() as $widget) { - $registered[$widget->getId()] = true; - } - - $ownTypes = $this->getLaunchpadWidgetTypes(); + $known = $this->renderableWidgetTypes(); $valid = []; $skipped = []; - foreach ($widgets as $widget) { - if (is_array($widget) === false) { - continue; + foreach (array_filter(array: $widgets, callback: 'is_array') as $widget) { + if ($this->isPlaceable(widget: $widget, known: $known) === true) { + $valid[] = $widget; + } elseif ((string)($widget['widgetId'] ?? '') !== '') { + $skipped[] = (string)$widget['widgetId']; } + } - $widgetId = (string)($widget['widgetId'] ?? ''); - $tileType = (string)($widget['tileType'] ?? ''); + return [$valid, $skipped]; + }//end partitionWidgets() - // Tile placements bypass the widget registry — they render - // through the LaunchPad tile renderer (REQ-DEMO-005). - if ($tileType !== '') { - $valid[] = $widget; - continue; - } + /** + * The widget types this instance can render: LaunchPad's own types and + * the Nextcloud dashboard widgets registered here, keyed for `isset()`. + * + * @return array The renderable widget types. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + public function renderableWidgetTypes(): array { + return $this->getLaunchpadWidgetTypes() + $this->registeredWidgetIds(); + }//end renderableWidgetTypes() - if (isset($ownTypes[$widgetId]) === true - || isset($registered[$widgetId]) === true - ) { - $valid[] = $widget; - continue; - } + /** + * The ids of the Nextcloud dashboard widgets registered on this + * instance, keyed for `isset()` lookups. + * + * @return array The registered ids. + */ + private function registeredWidgetIds(): array { + $registered = []; + foreach ($this->platform->dashboardManager->getWidgets() as $widget) { + $registered[$widget->getId()] = true; + } - if ($widgetId !== '') { - $skipped[] = $widgetId; - } - }//end foreach + return $registered; + }//end registeredWidgetIds() - return [$valid, $skipped]; - }//end partitionWidgets() + /** + * Whether LaunchPad can render a showcase widget: a tile, or a widget + * whose id is a known LaunchPad or registered Nextcloud type. + * + * @param array $widget The widget payload. + * @param array $known The renderable widget ids. + * + * @return bool True when the widget is placed. + */ + private function isPlaceable(array $widget, array $known): bool { + // Tile placements bypass the widget registry — they render + // through the LaunchPad tile renderer (REQ-DEMO-005). + if ((string)($widget['tileType'] ?? '') !== '') { + return true; + } + + return isset($known[(string)($widget['widgetId'] ?? '')]) === true; + }//end isPlaceable() /** * Load LaunchPad's own widget types from `lib/widget-types.json`. @@ -598,29 +694,8 @@ private function getLaunchpadWidgetTypes(): array { return $this->launchpadWidgetTypes; } - $decoded = null; - if (is_readable(filename: self::WIDGET_TYPES_PATH) === true) { - $raw = file_get_contents(filename: self::WIDGET_TYPES_PATH); - if (is_string($raw) === true) { - $decoded = json_decode(json: $raw, associative: true); - } - } - - if (is_array($decoded) === false || is_array($decoded['types'] ?? null) === false) { - throw new RuntimeException( - message: 'LaunchPad widget type list missing or malformed: ' . self::WIDGET_TYPES_PATH - ); - } - - $types = []; - foreach ($decoded['types'] as $type) { - if (is_string($type) === true && $type !== '') { - $types[$type] = true; - } - } - - $this->launchpadWidgetTypes = $types; - return $types; + $this->launchpadWidgetTypes = array_fill_keys(keys: (new WidgetTypeList())->types(), value: true); + return $this->launchpadWidgetTypes; }//end getLaunchpadWidgetTypes() /** @@ -694,35 +769,79 @@ private function loadDashboardPayload(string $zipPath): array { } try { - for ($i = 0; $i < $zip->numFiles; $i++) { - $name = (string)$zip->getNameIndex(index: $i); - if (str_starts_with(haystack: $name, needle: 'dashboards/') === false) { - continue; - } - - if (str_ends_with(haystack: $name, needle: '.json') === false) { - continue; - } - - $raw = $zip->getFromIndex(index: $i); - if ($raw === false) { - continue; - } - - $decoded = json_decode(json: $raw, associative: true); - if (is_array($decoded) === true) { - return $decoded; - } - } + $payload = $this->firstDashboardEntry(zip: $zip); } finally { $zip->close(); - }//end try + } + + if ($payload !== null) { + return $payload; + } throw new RuntimeException( message: 'Showcase archive contained no dashboard JSON entry.' ); }//end loadDashboardPayload() + /** + * The first `dashboards/*.json` entry of an open archive that decodes + * to a JSON object or list. + * + * @param ZipArchive $zip The open archive. + * + * @return array|null The payload, or null when none decodes. + */ + private function firstDashboardEntry(ZipArchive $zip): ?array { + for ($i = 0; $i < $zip->numFiles; $i++) { + if ($this->isDashboardEntryName(name: (string)$zip->getNameIndex(index: $i)) === false) { + continue; + } + + $decoded = $this->decodeZipEntry(zip: $zip, index: $i); + if ($decoded !== null) { + return $decoded; + } + } + + return null; + }//end firstDashboardEntry() + + /** + * Whether an archive entry name is a dashboard payload + * (`dashboards/*.json`). + * + * @param string $name The entry name. + * + * @return bool True for a dashboard payload entry. + */ + private function isDashboardEntryName(string $name): bool { + return str_starts_with(haystack: $name, needle: 'dashboards/') === true + && str_ends_with(haystack: $name, needle: '.json') === true; + }//end isDashboardEntryName() + + /** + * Decode one archive entry, null when it is unreadable or not a JSON + * object or list. + * + * @param ZipArchive $zip The open archive. + * @param integer $index The entry index. + * + * @return array|null The decoded entry, or null. + */ + private function decodeZipEntry(ZipArchive $zip, int $index): ?array { + $raw = $zip->getFromIndex(index: $index); + if ($raw === false) { + return null; + } + + $decoded = json_decode(json: $raw, associative: true); + if (is_array($decoded) === false) { + return null; + } + + return $decoded; + }//end decodeZipEntry() + /** * Hydrate a Dashboard entity for a freshly-installed showcase. * @@ -762,7 +881,7 @@ private function buildDashboardEntity( } // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters - $dashboard->setUuid($this->generateUuidV4()); + $dashboard->setUuid(UuidV4::generate()); $dashboard->setName($name); $dashboard->setDescription($description); $dashboard->setIcon($icon); @@ -804,7 +923,7 @@ private function buildDashboardEntity( * @return void */ private function markInstalled(string $showcaseId, string $dashboardUuid): void { - $this->appConfig->setValueString( + $this->platform->appConfig->setValueString( Application::APP_ID, self::CONFIG_PREFIX . $showcaseId, $dashboardUuid @@ -819,7 +938,7 @@ private function markInstalled(string $showcaseId, string $dashboardUuid): void * @return void */ private function clearInstalledMarker(string $showcaseId): void { - $this->appConfig->deleteKey( + $this->platform->appConfig->deleteKey( Application::APP_ID, self::CONFIG_PREFIX . $showcaseId ); @@ -841,24 +960,4 @@ private function assertKnownShowcase(string $showcaseId): void { ); } }//end assertKnownShowcase() - - /** - * Generate a v4 UUID for the freshly-installed dashboard. - * - * @return string The UUID. - */ - private function generateUuidV4(): string { - $bytes = random_bytes(length: 16); - $bytes[6] = chr(codepoint: ord(character: $bytes[6]) & 0x0f | 0x40); - $bytes[8] = chr(codepoint: ord(character: $bytes[8]) & 0x3f | 0x80); - $hex = bin2hex(string: $bytes); - return sprintf( - '%s-%s-%s-%s-%s', - substr(string: $hex, offset: 0, length: 8), - substr(string: $hex, offset: 8, length: 4), - substr(string: $hex, offset: 12, length: 4), - substr(string: $hex, offset: 16, length: 4), - substr(string: $hex, offset: 20, length: 12), - ); - }//end generateUuidV4() }//end class diff --git a/lib/Service/Discussion/DashboardAudience.php b/lib/Service/Discussion/DashboardAudience.php new file mode 100644 index 000000000..b27cbd657 --- /dev/null +++ b/lib/Service/Discussion/DashboardAudience.php @@ -0,0 +1,51 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md#requirement-req-leaf-003-discussion-access-follows-the-existing-view-guard + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Discussion; + +/** + * The audience of one dashboard, as RBAC-matchable lists. + */ +final class DashboardAudience { + + /** + * Constructor. + * + * @param list $users User ids that may view it. + * @param list $groups Group ids whose members may view it. + * @param bool $everyone Whether every signed-in user may view it. + * @param bool $collaborative Whether anyone but its owner may view it. + */ + public function __construct( + public readonly array $users, + public readonly array $groups, + public readonly bool $everyone, + public readonly bool $collaborative, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/Discussion/DashboardAudienceDeriver.php b/lib/Service/Discussion/DashboardAudienceDeriver.php new file mode 100644 index 000000000..34ae3372e --- /dev/null +++ b/lib/Service/Discussion/DashboardAudienceDeriver.php @@ -0,0 +1,109 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md#requirement-req-leaf-003-discussion-access-follows-the-existing-view-guard + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Discussion; + +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\DashboardShare; + +/** + * Derives a dashboard's audience from its type, owner and shares. + */ +class DashboardAudienceDeriver { + + /** + * The audience of a dashboard with its shares. + * + * @param Dashboard $dashboard The dashboard. + * @param list $shares Its user and group shares. + * + * @return DashboardAudience + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-7 + */ + public function derive(Dashboard $dashboard, array $shares): DashboardAudience { + if ($dashboard->getType() === Dashboard::TYPE_GROUP_SHARED) { + return $this->ofGroup(groupId: (string)$dashboard->getGroupId()); + } + + if ($dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE) { + return new DashboardAudience(users: [], groups: [], everyone: false, collaborative: false); + } + + $users = []; + $groups = []; + $owner = (string)$dashboard->getUserId(); + if ($owner !== '') { + $users[] = $owner; + } + + foreach ($shares as $share) { + $with = (string)$share->getShareWith(); + if ($with === '') { + continue; + } + + if ($share->getShareType() === DashboardShare::SHARE_TYPE_GROUP) { + $groups[] = $with; + continue; + } + + $users[] = $with; + } + + $users = array_values(array_unique($users)); + $groups = array_values(array_unique($groups)); + + return new DashboardAudience( + users: $users, + groups: $groups, + everyone: false, + collaborative: ($groups !== [] || count($users) > 1) + ); + }//end of() + + /** + * The audience of a group dashboard. + * + * @param string $groupId The dashboard's group. + * + * @return DashboardAudience + */ + private function ofGroup(string $groupId): DashboardAudience { + if ($groupId === Dashboard::DEFAULT_GROUP_ID) { + return new DashboardAudience(users: [], groups: [], everyone: true, collaborative: true); + } + + $groups = []; + if ($groupId !== '') { + $groups[] = $groupId; + } + + return new DashboardAudience(users: [], groups: $groups, everyone: false, collaborative: true); + }//end ofGroup() +}//end class diff --git a/lib/Service/Discussion/DashboardDiscussionMirror.php b/lib/Service/Discussion/DashboardDiscussionMirror.php new file mode 100644 index 000000000..5260f0dbb --- /dev/null +++ b/lib/Service/Discussion/DashboardDiscussionMirror.php @@ -0,0 +1,207 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md#requirement-req-leaf-003-discussion-access-follows-the-existing-view-guard + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Discussion; + +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\DashboardShareMapper; +use OCA\LaunchPad\Service\ScheduledExport\ExportObjectStore; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Writes, narrows and removes the OpenRegister object of a shared dashboard. + */ +class DashboardDiscussionMirror { + + /** + * The schema of the mirror objects in the `launchpad` register. + */ + public const SCHEMA = 'dashboard'; + + /** + * Constructor. + * + * @param ExportObjectStore $store Object CRUD on the `launchpad` register, OpenRegister optional. + * @param DashboardMapper $dashboards Reads the dashboards. + * @param DashboardShareMapper $shares Reads their shares. + * @param LoggerInterface $logger Logs a mirror that could not be written. + */ + public function __construct( + private readonly ExportObjectStore $store, + private readonly DashboardMapper $dashboards, + private readonly DashboardShareMapper $shares, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * Bring one dashboard's mirror in step with who may view it. + * + * @param int $dashboardId The dashboard. + * + * @return void + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-4 + */ + public function syncDashboard(int $dashboardId): void { + try { + $this->sync(dashboard: $this->dashboards->find(id: $dashboardId)); + } catch (Throwable $e) { + $this->logFailure(subject: 'dashboard '.$dashboardId, error: $e); + } + }//end syncDashboard() + + /** + * Bring the mirrors of every dashboard an owner holds in step: a + * revocation by recipient can reach several of them. + * + * @param string $ownerId The owner. + * + * @return void + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-8 + */ + public function syncOwnedBy(string $ownerId): void { + try { + foreach ($this->dashboards->findByUserId(userId: $ownerId) as $dashboard) { + $this->sync(dashboard: $dashboard); + } + } catch (Throwable $e) { + $this->logFailure(subject: 'the dashboards of '.$ownerId, error: $e); + } + }//end syncOwnedBy() + + /** + * Bring every shared and group dashboard's mirror in step, for an + * instance whose dashboards were shared before the mirror existed. + * + * @return int How many dashboards were looked at. + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-4 + */ + public function syncAllShared(): int { + if ($this->store->isAvailable() === false) { + return 0; + } + + $ids = $this->shares->findSharedDashboardIds(); + foreach ($this->dashboards->findByGroup(groupId: null) as $dashboard) { + $ids[] = (int)$dashboard->getId(); + } + + $ids = array_values(array_unique($ids)); + foreach ($ids as $id) { + $this->syncDashboard(dashboardId: $id); + } + + return count($ids); + }//end syncAllShared() + + /** + * Remove a deleted dashboard's mirror. + * + * @param string $dashboardUuid The deleted dashboard's uuid. + * + * @return void + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-8 + */ + public function remove(string $dashboardUuid): void { + if ($dashboardUuid === '' || $this->store->isAvailable() === false) { + return; + } + + try { + $mirror = $this->store->find(schema: self::SCHEMA, uuid: $dashboardUuid); + if ($mirror !== null) { + $this->store->delete(uuid: (string)$mirror['id']); + } + } catch (Throwable $e) { + $this->logFailure(subject: 'dashboard '.$dashboardUuid, error: $e); + } + }//end remove() + + /** + * Write a dashboard's mirror when it is shared, narrow an existing one + * when it is not, and leave an unshared dashboard without one. + * + * @param Dashboard $dashboard The dashboard. + * + * @return void + */ + private function sync(Dashboard $dashboard): void { + $uuid = (string)$dashboard->getUuid(); + if ($uuid === '' || $this->store->isAvailable() === false) { + return; + } + + $audience = (new DashboardAudienceDeriver())->derive( + dashboard: $dashboard, + shares: $this->shares->findByDashboardId(dashboardId: (int)$dashboard->getId()) + ); + $existing = $this->store->find(schema: self::SCHEMA, uuid: $uuid); + if ($existing === null && $audience->collaborative === false) { + return; + } + + $this->store->save(schema: self::SCHEMA, data: [ + 'id' => (string)($existing['id'] ?? $uuid), + 'slug' => $uuid, + 'title' => (string)($dashboard->getName() ?? 'Dashboard'), + 'type' => (string)$dashboard->getType(), + 'groupId' => $dashboard->getGroupId(), + 'audienceUsers' => $audience->users, + 'audienceGroups' => $audience->groups, + 'audienceEveryone' => $audience->everyone, + ]); + }//end sync() + + /** + * Log a mirror that could not be written; the dashboard itself is unaffected. + * + * @param string $subject What was being mirrored. + * @param Throwable $error Why it failed. + * + * @return void + */ + private function logFailure(string $subject, Throwable $error): void { + $this->logger->warning( + 'LaunchPad: the discussion object of '.$subject.' could not be updated: '.$error->getMessage(), + ['app' => 'launchpad', 'exception' => $error] + ); + }//end logFailure() +}//end class diff --git a/lib/Service/DisplayNamePageCollector.php b/lib/Service/DisplayNamePageCollector.php new file mode 100644 index 000000000..2767371d1 --- /dev/null +++ b/lib/Service/DisplayNamePageCollector.php @@ -0,0 +1,125 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/people-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\IUser; + +/** + * Collects one page of users in display-name order. + * + * Built by {@see PeopleWidgetService} for one page; never shared. + * + * @spec openspec/specs/people-widget/spec.md + */ +final class DisplayNamePageCollector { + /** + * Matching users still to skip before the page starts. + * + * @var integer + */ + private int $toSkip; + + /** + * The page collected so far. + * + * @var IUser[] + */ + private array $page = []; + + /** + * Constructor. + * + * @param PeoplePage $window Whether disabled users are skipped, the page + * size (1..MAX_LIMIT) and the offset (>= 0). + */ + public function __construct( + private readonly PeoplePage $window, + ) { + $this->toSkip = $window->offset; + }//end __construct() + + /** + * Take users from a backend batch until the page is full. + * + * @param IUser[] $users One batch, in display-name order. + * + * @return void + * + * @spec openspec/specs/people-widget/spec.md + */ + public function takeFrom(array $users): void { + foreach ($users as $user) { + if ($this->take(user: $user) === true) { + return; + } + } + }//end takeFrom() + + /** + * Whether the page holds `limit` users. + * + * @return bool True when full. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function isFull(): bool { + return count(value: $this->page) >= $this->window->limit; + }//end isFull() + + /** + * The collected page. + * + * @return IUser[] The users, in display-name order. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function page(): array { + return $this->page; + }//end page() + + /** + * Skip a disabled user (when asked) or one inside the offset, else add + * it to the page. + * + * @param IUser $user The next user. + * + * @return bool True when the page is now full. + */ + private function take(IUser $user): bool { + if ($this->window->excludeDisabled === true && $user->isEnabled() === false) { + return false; + } + + if ($this->toSkip > 0) { + $this->toSkip--; + return false; + } + + $this->page[] = $user; + + return $this->isFull(); + }//end take() +}//end class diff --git a/lib/Service/Embed/CspService.php b/lib/Service/Embed/CspService.php new file mode 100644 index 000000000..5c9f0f72f --- /dev/null +++ b/lib/Service/Embed/CspService.php @@ -0,0 +1,142 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +/** + * Validates host origins and builds the frame-ancestors header. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-003--csp-frame-ancestors-enforced-from-token-hostorigins + */ +final class CspService { + + /** + * The header an embed answers with. + * + * @var string + */ + public const HEADER = 'Content-Security-Policy'; + + /** + * The value of the CSP header for a token's host origins. Without a valid + * origin the embed may be framed by nobody (`'none'`). + * + * @param array $hostOrigins The token's host origins. + * + * @return string The header value, e.g. `frame-ancestors https://www.zeist.nl`. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-003--csp-frame-ancestors-enforced-from-token-hostorigins + */ + public function generateCspHeader(array $hostOrigins): string { + $valid = []; + foreach ($hostOrigins as $origin) { + if (is_string($origin) === true && $this->validateOriginFormat(origin: $origin) === true) { + $valid[] = $this->normalise(origin: $origin); + } + } + + $valid = array_values(array_unique($valid)); + if ($valid === []) { + return "frame-ancestors 'none'"; + } + + return 'frame-ancestors ' . implode(' ', $valid); + }//end generateCspHeader() + + /** + * Why a list of host origins is refused, or null when it is accepted. + * + * @param mixed $origins The submitted host origins. + * + * @return array{error: string, message: string, details: array}|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-003--csp-frame-ancestors-enforced-from-token-hostorigins + */ + public function validateOrigins(mixed $origins): ?array { + if (is_array($origins) === false || $origins === []) { + return $this->refusal( + message: 'Specify at least one origin that may embed this content, e.g., ["https://www.example.com"]', + reason: 'origin_required' + ); + } + + foreach ($origins as $origin) { + if (is_string($origin) === true && str_contains($origin, '*') === true) { + return $this->refusal( + message: 'Wildcard origin \'*\' is not permitted. Specify explicit origins, e.g., ["https://www.example.com"]', + reason: 'wildcard_not_permitted' + ); + } + + if (is_string($origin) === false || $this->validateOriginFormat(origin: $origin) === false) { + return $this->refusal( + message: 'An origin is a scheme and a host, e.g., https://www.example.com, without a path.', + reason: 'invalid_origin' + ); + } + } + + return null; + }//end validateOrigins() + + /** + * Whether one origin is `http(s)://host[:port]` (RFC 6454) with nothing else. + * + * @param string $origin The origin. + * + * @return bool + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-003--csp-frame-ancestors-enforced-from-token-hostorigins + */ + public function validateOriginFormat(string $origin): bool { + $origin = rtrim(trim($origin), '/'); + $pattern = '~^https?://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~i'; + + return preg_match($pattern, $origin) === 1; + }//end validateOriginFormat() + + /** + * An origin as it goes into the header: lower case, no trailing slash. + * + * @param string $origin The origin. + * + * @return string + */ + private function normalise(string $origin): string { + return strtolower(rtrim(trim($origin), '/')); + }//end normalise() + + /** + * The validation refusal body. + * + * @param string $message The message. + * @param string $reason The reason code for hostOrigins. + * + * @return array{error: string, message: string, details: array} + */ + private function refusal(string $message, string $reason): array { + return ['error' => 'validation_error', 'message' => $message, 'details' => ['hostOrigins' => $reason]]; + }//end refusal() + +}//end class diff --git a/lib/Service/Embed/EmbedGate.php b/lib/Service/Embed/EmbedGate.php new file mode 100644 index 000000000..ac27f6e9f --- /dev/null +++ b/lib/Service/Embed/EmbedGate.php @@ -0,0 +1,335 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCA\LaunchPad\Entity\EmbedToken; +use OCA\LaunchPad\Exception\EmbedRefusalException; +use OCA\LaunchPad\Exception\InvalidTokenException; +use OCA\LaunchPad\Exception\TokenExpiredException; +use OCA\LaunchPad\Exception\TokenRevokedException; +use OCP\IRequest; + +/** + * Admits an embed request or says why not. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ +class EmbedGate { + + /** + * The token came as `?token=`. + * + * @var string + */ + public const FORM_QUERY = 'query'; + + /** + * The token came in the Authorization Bearer header. + * + * @var string + */ + public const FORM_BEARER = 'bearer'; + + /** + * Constructor. + * + * @param EmbedTokenService $tokens The token store and validator. + * @param ScopeEnforcementService $scopes The scope decisions. + * @param JoseEncoding $jose The JWS segment encoding. + */ + public function __construct( + private readonly EmbedTokenService $tokens, + private readonly ScopeEnforcementService $scopes, + private readonly JoseEncoding $jose, + ) { + }//end __construct() + + /** + * The token a request carries and how: the Bearer header first, else + * `?token=` when the caller allows the query form. Null without one. + * + * @param IRequest $request The request. + * @param bool $allowQuery Whether `?token=` counts (only on the render route). + * + * @return array{jwt: string, form: string}|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + public function credentials(IRequest $request, bool $allowQuery): ?array { + $header = trim((string)$request->getHeader('Authorization')); + if (preg_match('/^Bearer\s+(\S+)$/i', $header, $match) === 1) { + return ['jwt' => $match[1], 'form' => self::FORM_BEARER]; + } + + if ($allowQuery === false) { + return null; + } + + $query = $request->getParam('token'); + if (is_string($query) === true && trim($query) !== '') { + return ['jwt' => trim($query), 'form' => self::FORM_QUERY]; + } + + return null; + }//end credentials() + + /** + * Whether a request outside the render route carries a LaunchPad embed + * token: a Bearer JWT whose (still unverified) issuer is LaunchPad. Other + * Bearer credentials, such as app passwords, are left to Nextcloud. + * + * @param IRequest $request The request. + * + * @return bool + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function carriesEmbedToken(IRequest $request): bool { + $credentials = $this->credentials(request: $request, allowQuery: false); + if ($credentials === null) { + return false; + } + + return ($this->claimsOf(jwt: $credentials['jwt'])['iss'] ?? null) === EmbedTokenService::ISSUER; + }//end carriesEmbedToken() + + /** + * The valid token of a request and how it came, or the 401 refusal the + * spec gives for a missing, invalid, expired or revoked one. + * + * @param IRequest $request The request. + * @param bool $allowQuery Whether `?token=` counts. + * + * @return array{token: EmbedToken, form: string} + * + * @throws EmbedRefusalException When there is no valid token. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + public function authenticate(IRequest $request, bool $allowQuery): array { + $credentials = $this->credentials(request: $request, allowQuery: $allowQuery); + if ($credentials === null) { + throw new EmbedRefusalException( + status: 401, + body: [ + 'error' => 'missing_token', + 'message' => 'No token provided. Include ?token= or use the Authorization: Bearer header', + ], + headers: ['WWW-Authenticate' => 'Bearer'] + ); + } + + try { + $token = $this->tokens->validateToken(jwt: $credentials['jwt']); + } catch (TokenExpiredException) { + // Expiry and revocation are decided after the signature verified, + // so the token id is genuine and its usage event can be written. + throw self::unauthorized( + error: 'token_expired', + message: 'The provided token has expired', + description: 'The token has expired', + tokenId: $this->tokenIdOf(jwt: $credentials['jwt']) + ); + } catch (TokenRevokedException) { + throw self::unauthorized( + error: 'token_revoked', + message: 'The provided token has been revoked', + description: 'The token has been revoked', + tokenId: $this->tokenIdOf(jwt: $credentials['jwt']) + ); + } catch (InvalidTokenException) { + throw self::unauthorized(error: 'invalid_token', message: 'The provided token is invalid or malformed', description: 'The token is invalid'); + } + + return ['token' => $token, 'form' => $credentials['form']]; + }//end authenticate() + + /** + * The 403 for a request the token's scope does not allow, or null. GET and + * HEAD always pass; a write needs an interactions token naming its action. + * + * @param string $method The HTTP method. + * @param string $path The request path. + * @param EmbedToken $token The token. + * + * @return EmbedRefusalException|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function scopeRefusal(string $method, string $path, EmbedToken $token): ?EmbedRefusalException { + $refusal = $this->scopes->refusalFor(method: $method, action: $this->scopes->actionOf(path: $path), scope: $token->scope); + if ($refusal === null) { + return null; + } + + return new EmbedRefusalException(status: $refusal['status'], body: $refusal['body']); + }//end scopeRefusal() + + /** + * The 403 for a page that frames the embed from an origin the token does + * not list, or null. The Referer's origin is checked when the browser says + * the request is cross-site, and for a Bearer token unless the browser says + * it is same-origin (the embed page loading its own subject); without a + * Referer (a privacy-preserving browser) the request passes and CSP + * frame-ancestors still holds. + * + * @param IRequest $request The request. + * @param EmbedToken $token The token. + * @param string $form How the token came. + * + * @return EmbedRefusalException|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-003--csp-frame-ancestors-enforced-from-token-hostorigins + */ + public function originRefusal(IRequest $request, EmbedToken $token, string $form): ?EmbedRefusalException { + $origin = self::originOf(url: (string)$request->getHeader('Referer')); + if ($origin === '') { + return null; + } + + $site = strtolower(trim((string)$request->getHeader('Sec-Fetch-Site'))); + if ($site === 'same-origin' || ($site !== 'cross-site' && $form !== self::FORM_BEARER)) { + return null; + } + + $allowed = array_map(static fn (mixed $host): string => rtrim(strtolower((string)$host), '/'), $token->hostOrigins); + if (in_array($origin, $allowed, true) === true) { + return null; + } + + return new EmbedRefusalException( + status: 403, + body: ['error' => 'origin_mismatch', 'message' => 'This iframe cannot be embedded on this origin'] + ); + }//end originRefusal() + + /** + * The 403 for a token used on another subject; it does not say whether + * that subject exists. + * + * @return EmbedRefusalException + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + public function subjectMismatch(): EmbedRefusalException { + return new EmbedRefusalException( + status: 403, + body: ['error' => 'scope_mismatch', 'message' => 'The provided token does not grant access to this resource'] + ); + }//end subjectMismatch() + + /** + * A 401 with its WWW-Authenticate challenge. + * + * @param string $error The error code. + * @param string $message The body message. + * @param string $description The challenge's error_description. + * @param string $tokenId The genuine token id, or ''. + * + * @return EmbedRefusalException + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + private static function unauthorized(string $error, string $message, string $description, string $tokenId=''): EmbedRefusalException { + return new EmbedRefusalException( + status: 401, + body: ['error' => $error, 'message' => $message], + headers: ['WWW-Authenticate' => sprintf('Bearer error="invalid_token", error_description="%s"', $description)], + tokenId: $tokenId + ); + }//end unauthorized() + + /** + * The unverified claims of a JWT, [] when it is not one. + * + * @param string $jwt The token. + * + * @return array + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + private function claimsOf(string $jwt): array { + $segments = explode('.', $jwt); + if (count($segments) !== 3) { + return []; + } + + try { + $claims = json_decode($this->jose->base64UrlDecode(segment: $segments[1]), true); + } catch (InvalidTokenException) { + return []; + } + + if (is_array($claims) === false) { + return []; + } + + return $claims; + }//end claimsOf() + + /** + * The `jti` of a JWT whose signature already verified. + * + * @param string $jwt The token. + * + * @return string + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-008--usage-telemetry-without-leaking-pii + */ + private function tokenIdOf(string $jwt): string { + $id = ($this->claimsOf(jwt: $jwt)['jti'] ?? ''); + if (is_string($id) === false) { + return ''; + } + + return $id; + }//end tokenIdOf() + + /** + * The lower-cased `scheme://host[:port]` of a URL, '' when it has none. + * + * @param string $url The URL. + * + * @return string + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-003--csp-frame-ancestors-enforced-from-token-hostorigins + */ + private static function originOf(string $url): string { + $parts = parse_url(trim($url)); + if (is_array($parts) === false || isset($parts['scheme'], $parts['host']) === false) { + return ''; + } + + $origin = strtolower($parts['scheme'] . '://' . $parts['host']); + if (isset($parts['port']) === true) { + $origin .= ':' . $parts['port']; + } + + return $origin; + }//end originOf() + +}//end class diff --git a/lib/Service/Embed/EmbedObjectStore.php b/lib/Service/Embed/EmbedObjectStore.php new file mode 100644 index 000000000..d421e7447 --- /dev/null +++ b/lib/Service/Embed/EmbedObjectStore.php @@ -0,0 +1,304 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use JsonSerializable; +use OCA\OpenRegister\Kernel\Contracts\Value\ObjectDeletion; +use Psr\Container\ContainerInterface; +use ReflectionMethod; +use RuntimeException; +use Throwable; + +/** + * The launchpad register's embed objects, as plain arrays with an `id`. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-2 + */ +class EmbedObjectStore { + + /** + * The register every embed schema lives in. + * + * @var string + */ + public const REGISTER = 'launchpad'; + + /** + * Embed tokens. + * + * @var string + */ + public const TOKENS = 'embed_token'; + + /** + * Tenant themes. + * + * @var string + */ + public const THEMES = 'tenant_theme'; + + /** + * Usage events. + * + * @var string + */ + public const USAGE = 'embed_usage_event'; + + /** + * Signing keys. + * + * @var string + */ + public const KEYS = 'signing_key'; + + /** + * OpenRegister's object service, by name (it may not be installed). + * + * @var string + */ + private const SERVICE = 'OCA\\OpenRegister\\Service\\ObjectService'; + + /** + * The slug-search target newer OpenRegister releases take. + */ + private const TARGET_CLASS = 'OCA\\OpenRegister\\Contract\\RegisterSchemaSlugs'; + + /** + * Constructor. + * + * @param ContainerInterface $container Resolves OpenRegister's object service. + */ + public function __construct( + private readonly ContainerInterface $container, + ) { + }//end __construct() + + /** + * Save an object: created when it has no `id`, updated when it has one. + * + * @param string $schema The schema slug. + * @param array $object The object. + * + * @return array The stored object with its `id`. + * + * @throws RuntimeException When OpenRegister is unavailable or the save fails. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-2 + */ + public function save(string $schema, array $object): array { + $service = $this->service(schema: $schema); + try { + $saved = $service->saveObject(object: $object, _rbac: false, _multitenancy: false); + } catch (Throwable $failure) { + throw new RuntimeException(message: 'The ' . $schema . ' object could not be saved.', previous: $failure); + } + + return self::toArray(entity: $saved) ?? throw new RuntimeException(message: 'The ' . $schema . ' object could not be saved.'); + }//end save() + + /** + * One object by id, or null when there is none. + * + * @param string $schema The schema slug. + * @param string $id The object id. + * + * @return array|null + * + * @throws RuntimeException When OpenRegister is unavailable. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-2 + */ + public function find(string $schema, string $id): ?array { + if ($id === '') { + return null; + } + + $service = $this->service(schema: $schema); + try { + $entity = $service->find(id: $id, _rbac: false, _multitenancy: false); + } catch (Throwable) { + return null; + } + + return self::toArray(entity: $entity); + }//end find() + + /** + * Every object of a schema whose fields equal the filters. + * + * @param string $schema The schema slug. + * @param array $filters Field => value. + * + * @return list> + * + * @throws RuntimeException When OpenRegister is unavailable. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-2 + */ + public function findBy(string $schema, array $filters=[]): array { + $service = $this->service(schema: $schema); + $rows = self::searchBySlug(service: $service, schema: $schema, filters: $filters); + if (is_array($rows) === false) { + return []; + } + + if (isset($rows['results']) === true && is_array($rows['results']) === true) { + $rows = $rows['results']; + } + + $objects = []; + foreach ($rows as $row) { + $object = self::toArray(entity: $row); + if ($object !== null) { + $objects[] = $object; + } + } + + return $objects; + }//end findBy() + + /** + * Delete an object, as the system; false when there was nothing to delete. + * + * @param string $schema The schema slug. + * @param string $id The object id. + * + * @return bool + * + * @throws RuntimeException When OpenRegister is unavailable or the delete fails. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ + public function delete(string $schema, string $id): bool { + if ($this->find(schema: $schema, id: $id) === null) { + return false; + } + + $service = $this->service(schema: $schema); + try { + return $service->deleteObject(deletion: new ObjectDeletion(uuid: $id), _rbac: false, _multitenancy: false) === true; + } catch (Throwable $failure) { + throw new RuntimeException(message: 'The ' . $schema . ' object could not be deleted.', previous: $failure); + } + }//end delete() + + /** + * The object service, pointed at the launchpad register and a schema. + * + * @param string $schema The schema slug. + * + * @return \OCA\OpenRegister\Contract\ObjectServiceInterface + * + * @throws RuntimeException When OpenRegister is unavailable. + */ + private function service(string $schema): object { + try { + $service = $this->container->get(self::SERVICE); + } catch (Throwable $failure) { + throw new RuntimeException(message: 'Embeds need OpenRegister, which is not available.', previous: $failure); + } + + if (is_object($service) === false) { + throw new RuntimeException(message: 'Embeds need OpenRegister, which is not available.'); + } + + return $service->setRegister(register: self::REGISTER)->setSchema(schema: $schema); + }//end service() + + /** + * Search the launchpad register by slug, in the shape this OpenRegister + * takes it: newer releases take one `RegisterSchemaSlugs $target`, older + * ones `$registerSlug` and `$schemaSlug`. Named arguments for the wrong + * shape are a fatal error (HTTP 500 on every embed token create). + * + * @param object $service The object service. + * @param string $schema The schema slug. + * @param array $filters Field => value. + * + * @return mixed What the object service returned. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-2 + */ + private static function searchBySlug(object $service, string $schema, array $filters): mixed { + $first = (new ReflectionMethod($service, 'searchObjectsBySlug'))->getParameters()[0] ?? null; + if ($first !== null && $first->getName() === 'target') { + $class = self::TARGET_CLASS; + $target = new $class(register: self::REGISTER, schema: $schema); + return $service->searchObjectsBySlug( + target: $target, + filters: $filters, + _rbac: false, + _multitenancy: false + ); + } + + return $service->searchObjectsBySlug( + registerSlug: self::REGISTER, + schemaSlug: $schema, + filters: $filters, + _rbac: false, + _multitenancy: false + ); + }//end searchBySlug() + + /** + * An entity or array as a plain object with its `id`; null for anything else. + * + * @param mixed $entity What the object service returned. + * + * @return array|null + */ + private static function toArray(mixed $entity): ?array { + $id = null; + if (is_object($entity) === true && method_exists($entity, 'getObject') === true) { + if (method_exists($entity, 'getUuid') === true) { + $id = $entity->getUuid(); + } + + $entity = $entity->getObject(); + } else if ($entity instanceof JsonSerializable) { + $entity = $entity->jsonSerialize(); + } + + if (is_array($entity) === false) { + return null; + } + + $id = ($id ?? $entity['id'] ?? $entity['@self']['id'] ?? $entity['uuid'] ?? null); + if (is_string($id) === false || $id === '') { + return null; + } + + unset($entity['@self']); + $entity['id'] = $id; + + return $entity; + }//end toArray() +}//end class diff --git a/lib/Service/Embed/EmbedRenderService.php b/lib/Service/Embed/EmbedRenderService.php new file mode 100644 index 000000000..50368f51e --- /dev/null +++ b/lib/Service/Embed/EmbedRenderService.php @@ -0,0 +1,223 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Entity\EmbedToken; +use OCA\LaunchPad\Kernel\Contracts\ConditionalServiceInterface; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Http\ContentSecurityPolicy; +use OCP\AppFramework\Http\TemplateResponse; + +/** + * Builds what an embed shows. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ +class EmbedRenderService { + + /** + * Constructor. + * + * @param DashboardMapper $dashboards The dashboards. + * @param WidgetPlacementMapper $widgets The widget placements. + * @param TenantThemeService $themes The tenant themes. + * @param ScopeEnforcementService $scopes The scope decisions. + * @param ConditionalServiceInterface|null $visibility Applies the widget visibility rules. + */ + public function __construct( + private readonly DashboardMapper $dashboards, + private readonly WidgetPlacementMapper $widgets, + private readonly TenantThemeService $themes, + private readonly ScopeEnforcementService $scopes, + private readonly ?ConditionalServiceInterface $visibility = null, + ) { + }//end __construct() + + /** + * One widget for its token. + * + * @param string $widgetId The placement id. + * @param EmbedToken $token The token, which names this widget. + * @param array $requestFilters The filters the embed asks for. + * + * @return array|null Null when the widget no longer exists. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + public function renderWidget(string $widgetId, EmbedToken $token, array $requestFilters=[]): ?array { + if (ctype_digit($widgetId) === false) { + return null; + } + + try { + $placement = $this->widgets->find(id: (int)$widgetId); + } catch (DoesNotExistException) { + return null; + } + + return $this->envelope(token: $token, requestFilters: $requestFilters) + [ + 'subjectType' => 'widget', + 'placements' => $this->forVisitor(placements: [$placement->jsonSerialize()]), + ]; + }//end renderWidget() + + /** + * One dashboard, with its widgets, for its token. + * + * @param string $dashboardId The dashboard uuid. + * @param EmbedToken $token The token, which names this dashboard. + * @param array $requestFilters The filters the embed asks for. + * + * @return array|null Null when the dashboard no longer exists. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + public function renderDashboard(string $dashboardId, EmbedToken $token, array $requestFilters=[]): ?array { + try { + $dashboard = $this->dashboards->findByUuid(uuid: $dashboardId); + } catch (DoesNotExistException) { + return null; + } + + return $this->envelope(token: $token, requestFilters: $requestFilters) + [ + 'subjectType' => 'dashboard', + 'dashboard' => $dashboard->jsonSerialize(), + 'placements' => $this->forVisitor( + placements: array_map( + static fn ($placement): array => $placement->jsonSerialize(), + $this->widgets->findByDashboardId(dashboardId: (int)$dashboard->getId()) + ) + ), + ]; + }//end renderDashboard() + + /** + * The placements an embed shows: an embed has no viewer who can edit, so + * a widget the visibility rules hide is left out (REQ-VIS-013). + * + * @param array> $placements The serialised placements. + * + * @return array> The placements to render. + */ + private function forVisitor(array $placements): array { + return ($this->visibility?->visiblePlacements(placements: $placements, userId: '', canEdit: false) ?? $placements); + }//end forVisitor() + + /** + * The subject named by type, or null for an unknown type or a missing subject. + * + * @param string $subjectType `widget` or `dashboard`. + * @param string $subjectId Its id. + * @param EmbedToken $token The token. + * @param array $requestFilters The filters the embed asks for. + * + * @return array|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + public function render(string $subjectType, string $subjectId, EmbedToken $token, array $requestFilters=[]): ?array { + return match ($subjectType) { + 'widget' => $this->renderWidget(widgetId: $subjectId, token: $token, requestFilters: $requestFilters), + 'dashboard' => $this->renderDashboard(dashboardId: $subjectId, token: $token, requestFilters: $requestFilters), + default => null, + }; + }//end render() + + /** + * The page that frames an embed: the bare base layout (no navigation), + * the tenant theme's :root block, and the token's host origins as the only + * frame ancestors. X-Frame-Options stays as the legacy fallback (3.5). + * The page URL can carry the token (`?token=`), so the Referer it sends is + * only ever its origin, never that URL (`strict-origin`): the token does + * not reach access logs through the requests the page makes. + * + * @param string $subjectType `widget` or `dashboard`. + * @param string $subjectId Its id. + * @param EmbedToken $token The token. + * + * @return TemplateResponse + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-003--csp-frame-ancestors-enforced-from-token-hostorigins + */ + public function page(string $subjectType, string $subjectId, EmbedToken $token): TemplateResponse { + $response = new TemplateResponse( + appName: Application::APP_ID, + templateName: 'embed', + params: [ + 'subjectType' => $subjectType, + 'subjectId' => $subjectId, + 'themeCss' => $this->themes->rootCss(themeId: $token->tenantThemeId), + ], + renderAs: TemplateResponse::RENDER_AS_BASE + ); + + $csp = new ContentSecurityPolicy(); + $csp->addAllowedImageDomain(domain: 'data:'); + foreach ($token->hostOrigins as $origin) { + $csp->addAllowedFrameAncestorDomain(domain: (string)$origin); + } + + $response->setContentSecurityPolicy(csp: $csp); + $response->addHeader('X-Frame-Options', 'SAMEORIGIN'); + $response->addHeader('X-Content-Type-Options', 'nosniff'); + $response->addHeader('Referrer-Policy', 'strict-origin'); + + return $response; + }//end page() + + /** + * What every embed payload carries: the scope the frontend honours, the + * filters in force (pinned context over the allowed request filters) and + * the theme block. + * + * @param EmbedToken $token The token. + * @param array $requestFilters The filters the embed asks for. + * + * @return array + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-005--per-tenant-theming-via-css-variables + */ + private function envelope(EmbedToken $token, array $requestFilters): array { + $filterContext = $token->subject['filterContext'] ?? []; + if (is_array($filterContext) === false) { + $filterContext = []; + } + + return [ + 'scope' => [ + 'mode' => (string)($token->scope['mode'] ?? ScopeEnforcementService::MODE_READ), + 'allowedActions' => array_values((array)($token->scope['allowedActions'] ?? [])), + 'allowedFilters' => array_values((array)($token->scope['allowedFilters'] ?? [])), + ], + 'filters' => $this->scopes->restrictFilters(requestFilters: $requestFilters, scope: $token->scope, filterContext: $filterContext), + 'themeCss' => $this->themes->rootCss(themeId: $token->tenantThemeId), + ]; + }//end envelope() + +}//end class diff --git a/lib/Service/Embed/EmbedRequestContext.php b/lib/Service/Embed/EmbedRequestContext.php new file mode 100644 index 000000000..ff1ddfd8a --- /dev/null +++ b/lib/Service/Embed/EmbedRequestContext.php @@ -0,0 +1,112 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCA\LaunchPad\Entity\EmbedToken; + +/** + * Holds the validated embed token of the current request. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ +class EmbedRequestContext { + + /** + * The token, once validated. + * + * @var EmbedToken|null + */ + private ?EmbedToken $token = null; + + /** + * How it arrived: `query` (?token=) or `bearer` (Authorization header). + * + * @var string + */ + private string $form = ''; + + /** + * When the request started, in milliseconds, for the latency of its usage event. + * + * @var float + */ + private float $startedAt = 0.0; + + /** + * Record the token the request was let in with. + * + * @param EmbedToken $token The validated token. + * @param string $form `query` or `bearer`. + * @param float $startedAt Milliseconds since the epoch. + * + * @return void + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function admit(EmbedToken $token, string $form, float $startedAt): void { + $this->token = $token; + $this->form = $form; + $this->startedAt = $startedAt; + }//end admit() + + /** + * The token, or null when the request carries none. + * + * @return EmbedToken|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function token(): ?EmbedToken { + return $this->token; + }//end token() + + /** + * How the token arrived, '' without one. + * + * @return string + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function form(): string { + return $this->form; + }//end form() + + /** + * The milliseconds since the request was admitted. + * + * @param float $now Milliseconds since the epoch. + * + * @return int + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function latencyMs(float $now): int { + if ($this->startedAt <= 0.0) { + return 0; + } + + return max(0, (int)round($now - $this->startedAt)); + }//end latencyMs() + +}//end class diff --git a/lib/Service/Embed/EmbedTokenService.php b/lib/Service/Embed/EmbedTokenService.php new file mode 100644 index 000000000..eb4e68c22 --- /dev/null +++ b/lib/Service/Embed/EmbedTokenService.php @@ -0,0 +1,696 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use DateTime; +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Entity\EmbedToken; +use OCA\LaunchPad\Exception\InvalidTokenException; +use OCA\LaunchPad\Exception\TokenExpiredException; +use OCA\LaunchPad\Exception\TokenRevokedException; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\Log\Audit\CriticalActionPerformedEvent; +use OCP\Notification\IManager; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Issues, shows, validates and revokes embed tokens. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-001--token-issuance-returns-jwt-exactly-once + */ +class EmbedTokenService { + + /** + * The one-time warning that accompanies a new JWT. + * + * @var string + */ + public const WARNING = 'keepThisSafe: This JWT is shown only once. Save it now. If lost, you must re-issue the token.'; + + /** + * The issuer claim of every embed token. + * + * @var string + */ + public const ISSUER = 'launchpad'; + + /** + * The notification subject sent to a revoked token's creator. + * + * @var string + */ + public const REVOKED_SUBJECT = 'embed_token_revoked'; + + /** + * Constructor. + * + * @param EmbedObjectStore $store The register objects. + * @param SigningKeyService $keys The signing keys. + * @param JwtSigningService $jwt Signs and verifies. + * @param CspService $csp Validates host origins. + * @param RevocationCache $revocations The 60-second revocation cache. + * @param ITimeFactory $time The clock. + * @param IManager $notifications Tells a creator their token was revoked. + * @param LoggerInterface $logger Logs a notification that could not be sent. + * @param IEventDispatcher $dispatcher Carries the audit events of the token lifecycle. + */ + public function __construct( + private readonly EmbedObjectStore $store, + private readonly SigningKeyService $keys, + private readonly JwtSigningService $jwt, + private readonly CspService $csp, + private readonly RevocationCache $revocations, + private readonly ITimeFactory $time, + private readonly IManager $notifications, + private readonly LoggerInterface $logger, + private readonly IEventDispatcher $dispatcher, + ) { + }//end __construct() + + /** + * Issue a token: validate, store, sign, store the hash, return the JWT once. + * + * @param array $input The create payload. + * @param string $userId The issuing admin. + * + * @return array {id, name, jwt, warning, createdAt}, or a refusal + * {status: error, error, message, fieldErrors}. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-001--token-issuance-returns-jwt-exactly-once + */ + public function createToken(array $input, string $userId): array { + $refusal = $this->refusalFor(input: $input); + if ($refusal !== null) { + return $refusal; + } + + $now = $this->nowIso(); + $token = EmbedToken::fromObject( + object: [ + 'name' => trim((string)$input['name']), + 'description' => (string)($input['description'] ?? ''), + 'subject' => self::subjectOf(subject: $input['subject']), + 'scope' => self::scopeOf(scope: $input['scope'] ?? []), + 'hostOrigins' => array_values($input['hostOrigins']), + 'tenantThemeId' => $input['tenantThemeId'] ?? null, + 'tokenExpiresAt' => $input['tokenExpiresAt'] ?? null, + 'rateLimitPolicy' => $input['rateLimitPolicy'] ?? null, + 'createdBy' => $userId, + 'createdAt' => $now, + ] + ); + + $issued = $this->issue(token: $token); + $this->audit(message: 'LaunchPad embed token "%s" (%s) issued by %s', params: [$issued['name'], $issued['id'], $userId]); + + return $issued; + }//end createToken() + + /** + * A token's metadata (no JWT, no hash) with its actions, or null. + * + * @param string $id The token id. + * + * @return array|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-001--token-issuance-returns-jwt-exactly-once + */ + public function getToken(string $id): ?array { + $token = $this->load(id: $id); + if ($token === null) { + return null; + } + + return $token->metadata() + ['actions' => self::actionsOf(token: $token)]; + }//end getToken() + + /** + * Every token's metadata, newest first. + * + * @return list> + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-4 + */ + public function listTokens(): array { + $tokens = array_map( + static fn (array $object): array => EmbedToken::fromObject(object: $object)->metadata(), + $this->store->findBy(schema: EmbedObjectStore::TOKENS) + ); + usort($tokens, static fn (array $a, array $b): int => strcmp((string)$b['createdAt'], (string)$a['createdAt'])); + + return $tokens; + }//end listTokens() + + /** + * Update what may change on a token: name, description, rate limit. + * Subject, scope and host origins are signed into the JWT and never change; + * any other field in the input is ignored. + * + * @param string $id The token id. + * @param array $input {name?, description?, rateLimitPolicy?}. + * + * @return array|null The updated metadata, a refusal, or null when there is no such token. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-32 + */ + public function updateToken(string $id, array $input): ?array { + $token = $this->load(id: $id); + if ($token === null) { + return null; + } + + $object = $token->toObject(); + if (array_key_exists('name', $input) === true) { + if (trim((string)$input['name']) === '') { + return self::refusal(error: 'invalid_name', message: 'Give the token a name.', field: 'name'); + } + + $object['name'] = trim((string)$input['name']); + } + + if (array_key_exists('description', $input) === true) { + $object['description'] = (string)$input['description']; + } + + if (array_key_exists('rateLimitPolicy', $input) === true) { + $refusal = self::policyRefusal(policy: $input['rateLimitPolicy']); + if ($refusal !== null) { + return $refusal; + } + + $object['rateLimitPolicy'] = $input['rateLimitPolicy']; + } + + $object['updatedAt'] = $this->nowIso(); + $updated = EmbedToken::fromObject(object: $this->store->save(schema: EmbedObjectStore::TOKENS, object: $object)); + + return $updated->metadata() + ['actions' => self::actionsOf(token: $updated)]; + }//end updateToken() + + /** + * The stored token a presented JWT stands for, when it holds. + * + * @param string $jwt The presented JWT. + * + * @return EmbedToken + * + * @throws InvalidTokenException When the signature, the claims or the stored hash do not match. + * @throws TokenExpiredException When the token has expired. + * @throws TokenRevokedException When the token is revoked. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + public function validateToken(string $jwt): EmbedToken { + $claims = $this->jwt->verify(jwt: $jwt, keys: $this->keys->keys()); + if (($claims['iss'] ?? null) !== self::ISSUER || is_string($claims['jti'] ?? null) === false) { + throw new InvalidTokenException(message: 'The token was not issued by LaunchPad.'); + } + + $token = $this->load(id: $claims['jti']); + // The hash comparison runs whether or not the row exists, so a missing + // row and a wrong token cost the same. + $stored = ($token->tokenHash ?? str_repeat('0', 64)); + if (hash_equals($stored, hash('sha256', $jwt)) === false || $token === null) { + throw new InvalidTokenException(message: 'The token is not a current LaunchPad token.'); + } + + if ($this->revocations->isRevoked(tokenId: $token->id, lookup: static fn (): bool => $token->isRevoked()) === true) { + throw new TokenRevokedException(message: 'The token has been revoked.'); + } + + if ($token->isExpiredAt(now: $this->time->getTime()) === true) { + throw new TokenExpiredException(message: 'The token has expired.'); + } + + return $token; + }//end validateToken() + + /** + * Revoke a token and tell its creator. + * + * @param string $id The token id. + * @param string $reason One of EmbedToken::REASONS. + * @param string|null $notes Free text. + * @param string $userId The revoking admin. + * + * @return array|null The updated metadata, a refusal for a bad reason, null when there is no such token. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-009--token-revocation-takes-effect-within-60-seconds + */ + public function revokeToken(string $id, string $reason, ?string $notes, string $userId): ?array { + if (in_array($reason, EmbedToken::REASONS, true) === false) { + return self::refusal(error: 'invalid_reason', message: 'Choose a revocation reason: ' . implode(', ', EmbedToken::REASONS) . '.', field: 'reason'); + } + + $token = $this->load(id: $id); + if ($token === null) { + return null; + } + + $revoked = $token->revoked(revokedAt: $this->nowIso(), reason: $reason, notes: $notes, revokedBy: $userId); + $this->store->save(schema: EmbedObjectStore::TOKENS, object: $revoked->toObject()); + $this->revocations->markRevoked(tokenId: $token->id); + $this->notifyCreator(token: $revoked); + $this->audit(message: 'LaunchPad embed token "%s" (%s) revoked by %s, reason %s', params: [$revoked->name, $revoked->id, $userId, $reason]); + + return $revoked->metadata() + ['actions' => self::actionsOf(token: $revoked)]; + }//end revokeToken() + + /** + * Clear a token's revocation. + * + * @param string $id The token id. + * @param string|null $userId The admin, for the audit log. + * + * @return array|null The updated metadata, null when there is no such token. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-009--token-revocation-takes-effect-within-60-seconds + */ + public function unrevokeToken(string $id, ?string $userId=null): ?array { + $token = $this->load(id: $id); + if ($token === null) { + return null; + } + + $restored = $token->unrevoked(restoredAt: $this->nowIso()); + $this->store->save(schema: EmbedObjectStore::TOKENS, object: $restored->toObject()); + $this->revocations->purge(tokenId: $token->id); + $this->audit(message: 'LaunchPad embed token "%s" (%s) restored by %s', params: [$restored->name, $restored->id, (string)$userId]); + + return $restored->metadata() + ['actions' => self::actionsOf(token: $restored)]; + }//end unrevokeToken() + + /** + * Re-issue: revoke the token as `re-issued` and issue a new one like it. + * + * @param string $id The token id. + * @param string $userId The admin. + * + * @return array|null The new token's create response, null when there is no such token. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-001--token-issuance-returns-jwt-exactly-once + */ + public function reissueToken(string $id, string $userId): ?array { + $token = $this->load(id: $id); + if ($token === null) { + return null; + } + + $now = $this->nowIso(); + if ($token->isRevoked() === false) { + $retired = $token->revoked(revokedAt: $now, reason: 're-issued', notes: null, revokedBy: $userId); + $this->store->save(schema: EmbedObjectStore::TOKENS, object: $retired->toObject()); + $this->revocations->markRevoked(tokenId: $token->id); + } + + $fresh = $token->toObject(); + foreach (['id', 'tokenHash', 'keyId', 'revokedAt', 'revocationReason', 'revocationNotes', 'revokedBy', 'updatedAt'] as $field) { + unset($fresh[$field]); + } + + $issued = $this->issue(token: EmbedToken::fromObject(object: ['createdBy' => $userId, 'createdAt' => $now] + $fresh)); + $this->audit(message: 'LaunchPad embed token "%s" (%s) re-issued as %s by %s', params: [$token->name, $token->id, $issued['id'], $userId]); + + return $issued; + }//end reissueToken() + + /** + * Drop a token's cached revocation answer, so every worker reads the store. + * + * @param string $id The token id. + * + * @return string|null The purge time, null when there is no such token. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-009--token-revocation-takes-effect-within-60-seconds + */ + public function purgeCache(string $id): ?string { + if ($this->load(id: $id) === null) { + return null; + } + + $this->revocations->purge(tokenId: $id); + + return $this->nowIso(); + }//end purgeCache() + + /** + * Store a token, sign its JWT under its id, store the hash. + * + * @param EmbedToken $token The token, not stored yet. + * + * @return array {id, name, jwt, warning, createdAt}. + */ + private function issue(EmbedToken $token): array { + $keys = $this->keys->keysWithActive(); + $active = $this->jwt->activeKey(keys: $keys); + // The JWT needs the stored id, so the first write carries a random hash + // that no token matches and that the schema's pattern accepts. + $stored = EmbedToken::fromObject( + object: $this->store->save( + schema: EmbedObjectStore::TOKENS, + object: ['tokenHash' => bin2hex(random_bytes(32))] + $token->toObject() + ) + ); + + $claims = [ + 'iss' => self::ISSUER, + 'jti' => $stored->id, + 'sub' => (string)($stored->subject['type'] ?? '') . ':' . (string)($stored->subject['id'] ?? ''), + 'scope' => $stored->scope, + 'hostOrigins' => $stored->hostOrigins, + 'iat' => $this->time->getTime(), + ]; + if ($stored->tokenExpiresAt !== null) { + $claims['exp'] = (int)strtotime($stored->tokenExpiresAt); + } + + $jwt = $this->jwt->sign(claims: $claims, keys: $keys); + $this->store->save( + schema: EmbedObjectStore::TOKENS, + object: ['tokenHash' => hash('sha256', $jwt), 'keyId' => (string)$active['kid']] + $stored->toObject() + ); + + return [ + 'id' => $stored->id, + 'name' => $stored->name, + 'jwt' => $jwt, + 'warning' => self::WARNING, + 'createdAt' => $stored->createdAt, + ]; + }//end issue() + + /** + * Why a create payload is refused, or null when it is acceptable. + * + * @param array $input The create payload. + * + * @return array|null + */ + private function refusalFor(array $input): ?array { + if (trim((string)($input['name'] ?? '')) === '') { + return self::refusal(error: 'invalid_name', message: 'Give the token a name.', field: 'name'); + } + + $subject = ($input['subject'] ?? null); + if (is_array($subject) === false || in_array($subject['type'] ?? null, ['widget', 'dashboard'], true) === false + || is_string($subject['id'] ?? null) === false || $subject['id'] === '' + ) { + return self::refusal(error: 'invalid_subject', message: 'The subject is a widget or a dashboard with an id.', field: 'subject'); + } + + $scopeRefusal = self::scopeRefusal(scope: $input['scope'] ?? []); + if ($scopeRefusal !== null) { + return $scopeRefusal; + } + + $originRefusal = $this->originRefusal(origins: $input['hostOrigins'] ?? null); + if ($originRefusal !== null) { + return $originRefusal; + } + + return self::policyRefusal(policy: $input['rateLimitPolicy'] ?? null) + ?? self::expiryRefusal(expiresAt: $input['tokenExpiresAt'] ?? null, now: $this->time->getTime()); + }//end refusalFor() + + /** + * Why a scope is refused, or null. + * + * @param mixed $scope The scope. + * + * @return array|null + */ + private static function scopeRefusal(mixed $scope): ?array { + if (is_array($scope) === false + || in_array($scope['mode'] ?? EmbedToken::MODE_READ, [EmbedToken::MODE_READ, EmbedToken::MODE_INTERACT], true) === false + ) { + return self::refusal(error: 'invalid_scope', message: 'The scope mode is read or read-with-interactions.', field: 'scope.mode'); + } + + foreach ((array)($scope['allowedActions'] ?? []) as $action) { + if (in_array($action, EmbedToken::ACTIONS, true) === false) { + return self::refusal( + error: 'invalid_scope', + message: 'Allowed actions are ' . implode(', ', EmbedToken::ACTIONS) . '.', + field: 'scope.allowedActions' + ); + } + } + + return null; + }//end scopeRefusal() + + /** + * Why the host origins are refused, naming the first bad one, or null. + * + * @param mixed $origins The host origins. + * + * @return array|null + */ + private function originRefusal(mixed $origins): ?array { + $verdict = $this->csp->validateOrigins(origins: $origins); + if ($verdict === null) { + return null; + } + + $index = 0; + $listed = []; + if (is_array($origins) === true) { + $listed = array_values($origins); + } + + foreach ($listed as $index => $origin) { + if (is_string($origin) === false || str_contains($origin, '*') === true || $this->csp->validateOriginFormat(origin: $origin) === false) { + break; + } + } + + $message = (string)($verdict['message'] ?? 'Invalid host origins.'); + if ($listed !== []) { + $problem = 'not an origin'; + if (is_string($listed[$index] ?? null) === true && str_contains((string)$listed[$index], '://') === false) { + $problem = 'missing URI scheme'; + } + + $message = 'Invalid origin format at index ' . $index . ': ' . $problem . '. Expected format: https://domain.com'; + if (($verdict['details']['hostOrigins'] ?? '') === 'wildcard_not_permitted') { + $message = (string)$verdict['message']; + } + } + + return self::refusal(error: 'invalid_hostOrigins', message: $message, field: 'hostOrigins[' . $index . ']'); + }//end originRefusal() + + /** + * Why a rate-limit policy is refused, or null (null policy = the default). + * + * @param mixed $policy The policy. + * + * @return array|null + */ + private static function policyRefusal(mixed $policy): ?array { + if ($policy === null) { + return null; + } + + $valid = is_array($policy) === true + && is_int($policy['requestsPerMinute'] ?? null) === true && $policy['requestsPerMinute'] >= 1 + && is_int($policy['burstSize'] ?? null) === true && $policy['burstSize'] >= 1; + + if ($valid === true) { + return null; + } + + return self::refusal( + error: 'invalid_rateLimitPolicy', + message: 'requestsPerMinute and burstSize are whole numbers of at least 1.', + field: 'rateLimitPolicy' + ); + }//end policyRefusal() + + /** + * Why an expiry is refused, or null (null = never expires). + * + * @param mixed $expiresAt The expiry. + * @param int $now Unix time. + * + * @return array|null + */ + private static function expiryRefusal(mixed $expiresAt, int $now): ?array { + if ($expiresAt === null) { + return null; + } + + $time = false; + if (is_string($expiresAt) === true) { + $time = strtotime($expiresAt); + } + + if ($time === false || $time <= $now) { + return self::refusal( + error: 'invalid_tokenExpiresAt', + message: 'The expiry is a date and time in the future, or empty for no expiry.', + field: 'tokenExpiresAt' + ); + } + + return null; + }//end expiryRefusal() + + /** + * The stored subject: type and id, and the filter context when one is given. + * + * @param array $subject The validated subject. + * + * @return array + */ + private static function subjectOf(array $subject): array { + $stored = ['type' => $subject['type'], 'id' => $subject['id']]; + if (is_array($subject['filterContext'] ?? null) === true) { + $stored['filterContext'] = $subject['filterContext']; + } + + return $stored; + }//end subjectOf() + + /** + * The stored scope, with its defaults filled in. + * + * @param array $scope The validated scope. + * + * @return array + */ + private static function scopeOf(array $scope): array { + return [ + 'mode' => (string)($scope['mode'] ?? EmbedToken::MODE_READ), + 'allowedFilters' => array_values(array_filter((array)($scope['allowedFilters'] ?? []), is_string(...))), + 'allowedActions' => array_values((array)($scope['allowedActions'] ?? [])), + ]; + }//end scopeOf() + + /** + * The actions an admin can take on a token. + * + * @param EmbedToken $token The token. + * + * @return list> + */ + private static function actionsOf(EmbedToken $token): array { + $actions = [['id' => 're-issue', 'label' => 'Re-issue token', 'description' => 'Revoke this token and generate a new one']]; + if ($token->isRevoked() === true) { + $actions[] = ['id' => 'unrevoke', 'label' => 'Un-revoke token', 'description' => 'Accept this token again']; + $actions[] = ['id' => 'purge-cache', 'label' => 'Purge cache', 'description' => 'Make every render worker re-read this token now']; + + return $actions; + } + + $actions[] = ['id' => 'revoke', 'label' => 'Revoke token', 'description' => 'Stop this token from rendering']; + + return $actions; + }//end actionsOf() + + /** + * A stored token, or null. + * + * @param string $id The token id. + * + * @return EmbedToken|null + */ + private function load(string $id): ?EmbedToken { + $object = $this->store->find(schema: EmbedObjectStore::TOKENS, id: $id); + + if ($object === null) { + return null; + } + + return EmbedToken::fromObject(object: $object); + }//end load() + + /** + * Tell the token's creator it was revoked; a failure is logged, never thrown. + * + * @param EmbedToken $token The revoked token. + * + * @return void + */ + private function notifyCreator(EmbedToken $token): void { + if ($token->createdBy === '') { + return; + } + + try { + $notification = $this->notifications->createNotification(); + $notification->setApp(Application::APP_ID) + ->setUser($token->createdBy) + ->setDateTime(new DateTime((string)$token->revokedAt)) + ->setObject('embed_token', $token->id) + ->setSubject( + self::REVOKED_SUBJECT, + [$token->name, (string)$token->revokedBy, (string)$token->revocationReason, (string)$token->revocationNotes, (string)$token->revokedAt] + ); + $this->notifications->notify($notification); + } catch (Throwable $failure) { + $this->logger->warning('[EmbedTokenService] The revocation notice could not be sent: ' . $failure->getMessage(), ['token' => $token->id]); + } + }//end notifyCreator() + + /** + * Write a token lifecycle step to the audit log. + * + * @param string $message The audit message, sprintf-style. + * @param list $params Its parameters. + * + * @return void + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + */ + private function audit(string $message, array $params): void { + $this->dispatcher->dispatchTyped(new CriticalActionPerformedEvent($message, $params)); + }//end audit() + + /** + * Now, as ISO 8601 in UTC. + * + * @return string + */ + private function nowIso(): string { + return gmdate('Y-m-d\TH:i:s\Z', $this->time->getTime()); + }//end nowIso() + + /** + * A refusal in the REQ-EMB-001 1.3 shape. + * + * @param string $error The error code. + * @param string $message The message. + * @param string $field The field at fault. + * + * @return array + */ + private static function refusal(string $error, string $message, string $field): array { + return ['status' => 'error', 'error' => $error, 'message' => $message, 'fieldErrors' => [$field => $error]]; + }//end refusal() +}//end class diff --git a/lib/Service/Embed/JoseEncoding.php b/lib/Service/Embed/JoseEncoding.php new file mode 100644 index 000000000..b15fc7ff5 --- /dev/null +++ b/lib/Service/Embed/JoseEncoding.php @@ -0,0 +1,129 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCA\LaunchPad\Exception\InvalidTokenException; + +/** + * JWS byte encodings, without state. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ +final class JoseEncoding { + + /** + * The length of one ES256 signature half (R or S), in bytes. + * + * @var integer + */ + public const ES256_PART = 32; + + /** + * Bytes in unpadded base64url. + * + * @param string $bytes The bytes. + * + * @return string + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ + public function base64Url(string $bytes): string { + return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '='); + }//end base64Url() + + /** + * Unpadded base64url, decoded. + * + * @param string $segment The text. + * + * @return string + * + * @throws InvalidTokenException When it is not base64url. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ + public function base64UrlDecode(string $segment): string { + $bytes = base64_decode(strtr($segment, '-_', '+/'), true); + if ($bytes === false || preg_match('/^[A-Za-z0-9_-]*$/', $segment) !== 1) { + throw new InvalidTokenException(message: 'The token is not a signed JWT.'); + } + + return $bytes; + }//end base64UrlDecode() + + /** + * An ECDSA DER signature as JOSE's R||S. + * + * @param string $der The DER signature. + * + * @return string The 64-byte signature. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ + public function derToRaw(string $der): string { + $offset = 2; + if ((ord($der[1]) & 0x80) !== 0) { + $offset += (ord($der[1]) & 0x7f); + } + + $parts = []; + for ($index = 0; $index < 2; $index++) { + $length = ord($der[$offset + 1]); + $value = substr($der, $offset + 2, $length); + $parts[] = str_pad(ltrim($value, "\0"), self::ES256_PART, "\0", STR_PAD_LEFT); + $offset += 2 + $length; + } + + return implode('', $parts); + }//end derToRaw() + + /** + * JOSE's R||S as an ECDSA DER signature. + * + * @param string $raw The 64-byte signature. + * + * @return string The DER signature. + * + * @throws InvalidTokenException When it is not 64 bytes. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ + public function rawToDer(string $raw): string { + if (strlen($raw) !== 2 * self::ES256_PART) { + throw new InvalidTokenException(message: 'The token signature does not verify.'); + } + + $body = ''; + foreach (str_split($raw, self::ES256_PART) as $part) { + $part = ltrim($part, "\0"); + if ($part === '' || (ord($part[0]) & 0x80) !== 0) { + $part = "\0" . $part; + } + + $body .= "\x02" . chr(strlen($part)) . $part; + } + + return "\x30" . chr(strlen($body)) . $body; + }//end rawToDer() +}//end class diff --git a/lib/Service/Embed/JwtSigningService.php b/lib/Service/Embed/JwtSigningService.php new file mode 100644 index 000000000..ddf48f180 --- /dev/null +++ b/lib/Service/Embed/JwtSigningService.php @@ -0,0 +1,397 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use InvalidArgumentException; +use JsonException; +use OCA\LaunchPad\Exception\InvalidTokenException; +use OCA\LaunchPad\Exception\TokenExpiredException; +use OCP\AppFramework\Utility\ITimeFactory; +use RuntimeException; + +/** + * Signs and verifies embed JWTs (RFC 7515/7519) with rotating asymmetric keys. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ +final class JwtSigningService { + + /** + * Constructor. + * + * @param JoseEncoding $jose The JWS byte encodings. + * @param ITimeFactory|null $time The clock; the system clock when none is given. + */ + public function __construct( + private readonly JoseEncoding $jose = new JoseEncoding(), + private readonly ?ITimeFactory $time = null, + ) { + }//end __construct() + + /** + * RSASSA-PKCS1-v1_5 with SHA-256. + * + * @var string + */ + public const RS256 = 'RS256'; + + /** + * ECDSA on P-256 with SHA-256. + * + * @var string + */ + public const ES256 = 'ES256'; + + /** + * The key signs new tokens and verifies. + * + * @var string + */ + public const STATUS_ACTIVE = 'active'; + + /** + * The key no longer signs, but still verifies the tokens it signed. + * + * @var string + */ + public const STATUS_RETIRING = 'retiring'; + + /** + * The key neither signs nor verifies. + * + * @var string + */ + public const STATUS_REVOKED = 'revoked'; + + /** + * The smallest RSA modulus accepted, in bits. + * + * @var integer + */ + public const MIN_RSA_BITS = 2048; + + /** + * A new key pair for an algorithm, active. + * + * @param string $algorithm RS256 or ES256. + * @param string|null $kid The key id; a random one when null. + * + * @return array The key record: kid, algorithm, status, publicKeyPem, + * privateKeyPem, publicKeyJwk, createdAt, retiredAt. + * + * @throws InvalidArgumentException When the algorithm is not supported. + * @throws RuntimeException When OpenSSL cannot make the key. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ + public function generateKeyPair(string $algorithm, ?string $kid = null): array { + $options = match ($algorithm) { + self::RS256 => ['private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => self::MIN_RSA_BITS], + self::ES256 => ['private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1'], + default => throw new InvalidArgumentException(message: sprintf('Unsupported signing algorithm "%s"; use RS256 or ES256.', $algorithm)), + }; + + $key = openssl_pkey_new($options); + if ($key === false || openssl_pkey_export($key, $privatePem) === false) { + throw new RuntimeException(message: 'The signing key pair could not be generated.'); + } + + $kid ??= strtolower($algorithm) . '-' . bin2hex(random_bytes(8)); + $details = openssl_pkey_get_details($key); + + return [ + 'kid' => $kid, + 'algorithm' => $algorithm, + 'status' => self::STATUS_ACTIVE, + 'publicKeyPem' => (string)$details['key'], + 'privateKeyPem' => (string)$privatePem, + 'publicKeyJwk' => $this->jwk(details: $details, id: ['alg' => $algorithm, 'kid' => $kid]), + 'createdAt' => gmdate('Y-m-d\TH:i:s\Z', $this->now()), + 'retiredAt' => null, + ]; + }//end generateKeyPair() + + /** + * The key that signs new tokens: the newest active one. + * + * @param array> $keys The known keys. + * + * @return array + * + * @throws RuntimeException When no key is active. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ + public function activeKey(array $keys): array { + $active = null; + foreach ($keys as $key) { + if (($key['status'] ?? null) === self::STATUS_ACTIVE + && ($active === null || (string)($key['createdAt'] ?? '') >= (string)($active['createdAt'] ?? '')) + ) { + $active = $key; + } + } + + if ($active === null) { + throw new RuntimeException(message: 'There is no active signing key.'); + } + + return $active; + }//end activeKey() + + /** + * Sign claims with the active key, naming it in the `kid` header. + * + * @param array $claims The claims. + * @param array> $keys The known keys. + * + * @return string The compact JWS. + * + * @throws RuntimeException When there is no active key or signing fails. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ + public function sign(array $claims, array $keys): string { + $key = $this->activeKey(keys: $keys); + $algorithm = (string)$key['algorithm']; + $header = ['alg' => $algorithm, 'typ' => 'JWT', 'kid' => (string)$key['kid']]; + $input = $this->encode(data: $header) . '.' . $this->encode(data: $claims); + + $private = openssl_pkey_get_private((string)($key['privateKeyPem'] ?? '')); + if ($private === false || openssl_sign($input, $signature, $private, OPENSSL_ALGO_SHA256) === false) { + throw new RuntimeException(message: 'The token could not be signed.'); + } + + if ($algorithm === self::ES256) { + $signature = $this->jose->derToRaw(der: $signature); + } + + return $input . '.' . $this->jose->base64Url(bytes: $signature); + }//end sign() + + /** + * The claims of a token whose signature verifies against the key its `kid` names, inside its validity period. + * + * The key must be active or retiring and must be of the algorithm the + * header names; `none` and a symmetric algorithm are never accepted. + * + * @param string $jwt The compact JWS. + * @param array> $keys The known keys. + * + * @return array The claims. + * + * @throws InvalidTokenException When the token is malformed, names no usable key, or its signature does not verify. + * @throws TokenExpiredException When `exp` has passed or `nbf` is still to come. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-002--public-render-route-validates-jwt-and-enforces-scope + */ + public function verify(string $jwt, array $keys): array { + $parts = explode('.', $jwt); + if (count($parts) !== 3) { + throw new InvalidTokenException(message: 'The token is not a signed JWT.'); + } + + $header = $this->decode(segment: $parts[0]); + $claims = $this->decode(segment: $parts[1]); + $key = $this->verifyingKey(header: $header, keys: $keys); + + $signature = $this->jose->base64UrlDecode(segment: $parts[2]); + if ($key['algorithm'] === self::ES256) { + $signature = $this->jose->rawToDer(raw: $signature); + } + + $public = openssl_pkey_get_public((string)($key['publicKeyPem'] ?? '')); + if ($public === false || openssl_verify($parts[0] . '.' . $parts[1], $signature, $public, OPENSSL_ALGO_SHA256) !== 1) { + throw new InvalidTokenException(message: 'The token signature does not verify.'); + } + + $this->assertValidAt(claims: $claims, now: $this->now()); + + return $claims; + }//end verify() + + /** + * Rotate: every active key becomes retiring, and a new active key is added. + * + * Tokens signed by a retiring key keep verifying until they expire; new + * tokens are signed with the new key. + * + * @param array> $keys The known keys. + * @param string $algorithm The new key's algorithm. + * + * @return array> The keys after rotation, the new one last. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-3 + */ + public function rotate(array $keys, string $algorithm): array { + $now = $this->now(); + $rotated = []; + foreach ($keys as $key) { + if (($key['status'] ?? null) === self::STATUS_ACTIVE) { + $key['status'] = self::STATUS_RETIRING; + $key['retiredAt'] = gmdate('Y-m-d\TH:i:s\Z', $now); + } + + $rotated[] = $key; + } + + $rotated[] = $this->generateKeyPair(algorithm: $algorithm); + + return $rotated; + }//end rotate() + + /** + * The key a token header selects, refused unless it may verify. + * + * @param array $header The token header. + * @param array> $keys The known keys. + * + * @return array + * + * @throws InvalidTokenException When no usable key matches. + */ + private function verifyingKey(array $header, array $keys): array { + $kid = $header['kid'] ?? null; + $alg = $header['alg'] ?? null; + if (is_string($kid) === false || in_array($alg, [self::RS256, self::ES256], true) === false) { + throw new InvalidTokenException(message: 'The token names no supported key.'); + } + + foreach ($keys as $key) { + if (($key['kid'] ?? null) === $kid + && ($key['algorithm'] ?? null) === $alg + && in_array($key['status'] ?? null, [self::STATUS_ACTIVE, self::STATUS_RETIRING], true) === true + ) { + return $key; + } + } + + throw new InvalidTokenException(message: 'The token names no usable key.'); + }//end verifyingKey() + + /** + * Refuse a token outside its `nbf`..`exp` window; a token without `exp` does not expire. + * + * @param array $claims The claims. + * @param int $now The current moment (unix seconds). + * + * @return void + * + * @throws TokenExpiredException When outside the window. + */ + private function assertValidAt(array $claims, int $now): void { + if (isset($claims['exp']) === true && is_numeric($claims['exp']) === true && (int)$claims['exp'] <= $now) { + throw new TokenExpiredException(message: 'The token has expired.'); + } + + if (isset($claims['nbf']) === true && is_numeric($claims['nbf']) === true && (int)$claims['nbf'] > $now) { + throw new TokenExpiredException(message: 'The token is not valid yet.'); + } + }//end assertValidAt() + + /** + * The public JWK (RFC 7517) of a key. + * + * @param array $details openssl_pkey_get_details() of the key. + * @param array $id Its `alg` (RS256 or ES256) and `kid`. + * + * @return array + */ + private function jwk(array $details, array $id): array { + if ($id['alg'] === self::RS256) { + return [ + 'kty' => 'RSA', + 'use' => 'sig', + 'alg' => $id['alg'], + 'kid' => $id['kid'], + 'n' => $this->jose->base64Url(bytes: (string)$details['rsa']['n']), + 'e' => $this->jose->base64Url(bytes: (string)$details['rsa']['e']), + ]; + } + + return [ + 'kty' => 'EC', + 'use' => 'sig', + 'alg' => $id['alg'], + 'kid' => $id['kid'], + 'crv' => 'P-256', + 'x' => $this->jose->base64Url(bytes: str_pad((string)$details['ec']['x'], JoseEncoding::ES256_PART, "\0", STR_PAD_LEFT)), + 'y' => $this->jose->base64Url(bytes: str_pad((string)$details['ec']['y'], JoseEncoding::ES256_PART, "\0", STR_PAD_LEFT)), + ]; + }//end jwk() + + /** + * The current moment in unix seconds, from the clock when one is injected. + * + * @return int + */ + private function now(): int { + if ($this->time === null) { + return time(); + } + + return $this->time->getTime(); + }//end now() + + /** + * A JSON segment, base64url-encoded. + * + * @param array $data The data. + * + * @return string + */ + private function encode(array $data): string { + return $this->jose->base64Url(bytes: json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)); + }//end encode() + + /** + * A base64url-encoded JSON object segment, decoded. + * + * @param string $segment The segment. + * + * @return array + * + * @throws InvalidTokenException When it is not a JSON object. + */ + private function decode(string $segment): array { + try { + $data = json_decode($this->jose->base64UrlDecode(segment: $segment), true, 16, JSON_THROW_ON_ERROR); + } catch (JsonException) { + throw new InvalidTokenException(message: 'The token is not a signed JWT.'); + } + + if (is_array($data) === false) { + throw new InvalidTokenException(message: 'The token is not a signed JWT.'); + } + + return $data; + }//end decode() +}//end class diff --git a/lib/Service/Embed/RateLimitService.php b/lib/Service/Embed/RateLimitService.php new file mode 100644 index 000000000..124cb2233 --- /dev/null +++ b/lib/Service/Embed/RateLimitService.php @@ -0,0 +1,180 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCP\ICache; +use OCP\ICacheFactory; + +/** + * Admits or refuses one request against its token's bucket. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-007--rate-limiting-and-request-budgeting-per-token + */ +class RateLimitService { + + /** + * The org default when a token carries no policy. + * + * @var array{requestsPerMinute: int, burstSize: int} + */ + public const DEFAULT_POLICY = ['requestsPerMinute' => 600, 'burstSize' => 60]; + + /** + * How long a bucket is kept after its last request, in seconds. + * + * @var int + */ + private const TTL = 3600; + + /** + * The bucket store. + * + * @var ICache + */ + private readonly ICache $cache; + + /** + * Constructor. + * + * @param ICacheFactory $cacheFactory Builds the distributed cache. + */ + public function __construct(ICacheFactory $cacheFactory) { + $this->cache = $cacheFactory->createDistributed('launchpad-embed-ratelimit'); + }//end __construct() + + /** + * Take one request from the token's bucket. + * + * @param string $tokenId The token. + * @param array|null $policy The token's `rateLimitPolicy`, null for the default. + * @param float $now The time, in seconds since the epoch. + * + * @return array{allowed: bool, limit: int, remaining: int, retryAfter: int, resetAt: int} + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-007--rate-limiting-and-request-budgeting-per-token + */ + public function checkRateLimit(string $tokenId, ?array $policy, float $now): array { + $policy = $this->policy(policy: $policy); + $capacity = (float)$policy['burstSize']; + $rate = ($policy['requestsPerMinute'] / 60.0); + + $tokens = $this->refillBucket(tokenId: $tokenId, capacity: $capacity, rate: $rate, now: $now); + $allowed = ($tokens >= 1.0); + if ($allowed === true) { + $tokens -= 1.0; + } + + $this->cache->set($this->key(tokenId: $tokenId), ['tokens' => $tokens, 'at' => $now], self::TTL); + + $retryAfter = 0; + if ($allowed === false) { + $retryAfter = (int)ceil((1.0 - $tokens) / $rate); + } + + return [ + 'allowed' => $allowed, + 'limit' => $policy['requestsPerMinute'], + 'remaining' => (int)floor($tokens), + 'retryAfter' => $retryAfter, + 'resetAt' => (int)ceil($now + (($capacity - $tokens) / $rate)), + ]; + }//end checkRateLimit() + + /** + * The tokens in a bucket now: the stored count plus what refilled since, + * never more than the capacity. A new bucket starts full. + * + * @param string $tokenId The token. + * @param float $capacity The burst size. + * @param float $rate Requests per second. + * @param float $now The time. + * + * @return float + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-007--rate-limiting-and-request-budgeting-per-token + */ + public function refillBucket(string $tokenId, float $capacity, float $rate, float $now): float { + $state = $this->cache->get($this->key(tokenId: $tokenId)); + if (is_array($state) === false || isset($state['tokens'], $state['at']) === false) { + return $capacity; + } + + $elapsed = max(0.0, ($now - (float)$state['at'])); + + return min($capacity, ((float)$state['tokens'] + ($elapsed * $rate))); + }//end refillBucket() + + /** + * The 429 body for a refused request. + * + * @param array{limit: int, retryAfter: int, resetAt: int} $verdict The verdict. + * + * @return array + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-007--rate-limiting-and-request-budgeting-per-token + */ + public function refusalBody(array $verdict): array { + return [ + 'error' => 'rate_limit_exceeded', + 'message' => sprintf( + 'Rate limit exceeded. The token allows %d requests per minute. Try again in %d seconds.', + $verdict['limit'], + $verdict['retryAfter'] + ), + 'retryAfter' => $verdict['retryAfter'], + 'resetAt' => gmdate('Y-m-d\TH:i:s\Z', $verdict['resetAt']), + ]; + }//end refusalBody() + + /** + * The policy in force: the token's, when both numbers are positive, else the default. + * + * @param array|null $policy The token's policy. + * + * @return array{requestsPerMinute: int, burstSize: int} + */ + private function policy(?array $policy): array { + $perMinute = (int)($policy['requestsPerMinute'] ?? 0); + $burst = (int)($policy['burstSize'] ?? 0); + if ($perMinute < 1 || $burst < 1) { + return self::DEFAULT_POLICY; + } + + return ['requestsPerMinute' => $perMinute, 'burstSize' => $burst]; + }//end policy() + + /** + * The cache key of a token's bucket. + * + * @param string $tokenId The token. + * + * @return string + */ + private function key(string $tokenId): string { + return 'bucket-' . hash('sha256', $tokenId); + }//end key() + +}//end class diff --git a/lib/Service/Embed/RevocationCache.php b/lib/Service/Embed/RevocationCache.php new file mode 100644 index 000000000..689c0cff3 --- /dev/null +++ b/lib/Service/Embed/RevocationCache.php @@ -0,0 +1,143 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCP\ICache; +use OCP\ICacheFactory; + +/** + * The 60-second revocation cache of embed tokens. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-009--token-revocation-takes-effect-within-60-seconds + */ +class RevocationCache { + + /** + * The longest a cached answer is trusted, in seconds. + * + * @var integer + */ + public const TTL = 60; + + /** + * The cached value of a revoked token. + * + * @var string + */ + private const REVOKED = 'revoked'; + + /** + * The cached value of a token that is not revoked. + * + * @var string + */ + private const VALID = 'valid'; + + /** + * The shared cache. + * + * @var ICache + */ + private ICache $cache; + + /** + * Constructor. + * + * @param ICacheFactory $cacheFactory Builds the distributed cache. + */ + public function __construct(ICacheFactory $cacheFactory) { + $this->cache = $cacheFactory->createDistributed('launchpad-embed-revocation'); + }//end __construct() + + /** + * Whether a token is revoked: the cached answer, else the store's, cached. + * + * @param string $tokenId The token id. + * @param callable $lookup fn(): bool, whether the stored token is revoked. + * + * @return bool + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-009--token-revocation-takes-effect-within-60-seconds + */ + public function isRevoked(string $tokenId, callable $lookup): bool { + $cached = $this->cache->get(self::key(tokenId: $tokenId)); + if ($cached === self::REVOKED) { + return true; + } + + if ($cached === self::VALID) { + return false; + } + + $revoked = ($lookup() === true); + $value = self::VALID; + if ($revoked === true) { + $value = self::REVOKED; + } + + $this->cache->set(self::key(tokenId: $tokenId), $value, self::TTL); + + return $revoked; + }//end isRevoked() + + /** + * Record a revocation for every worker at once. + * + * @param string $tokenId The token id. + * + * @return void + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-009--token-revocation-takes-effect-within-60-seconds + */ + public function markRevoked(string $tokenId): void { + $this->cache->set(self::key(tokenId: $tokenId), self::REVOKED, self::TTL); + }//end markRevoked() + + /** + * Drop the cached answer, so the next request reads the store. + * + * @param string $tokenId The token id. + * + * @return void + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-009--token-revocation-takes-effect-within-60-seconds + */ + public function purge(string $tokenId): void { + $this->cache->remove(self::key(tokenId: $tokenId)); + }//end purge() + + /** + * The cache key of a token. + * + * @param string $tokenId The token id. + * + * @return string + */ + private static function key(string $tokenId): string { + return 'token-' . hash('sha256', $tokenId); + }//end key() +}//end class diff --git a/lib/Service/Embed/ScopeEnforcementService.php b/lib/Service/Embed/ScopeEnforcementService.php new file mode 100644 index 000000000..32576ecf3 --- /dev/null +++ b/lib/Service/Embed/ScopeEnforcementService.php @@ -0,0 +1,191 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +/** + * Decides whether a request fits an embed token's scope. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ +final class ScopeEnforcementService { + + /** + * A token that only reads. + * + * @var string + */ + public const MODE_READ = 'read'; + + /** + * A token that reads and runs the actions it names. + * + * @var string + */ + public const MODE_INTERACT = 'read-with-interactions'; + + /** + * Methods that never change state. + * + * @var array + */ + private const SAFE_METHODS = ['GET', 'HEAD']; + + /** + * The refusal of a request the scope does not allow, or null when it may run. + * + * Any write under a `read` token is refused, whatever the operation (4.6); + * under `read-with-interactions` a write must name an allowed action. An + * unknown mode is treated as `read`: the stricter reading. + * + * @param string $method The HTTP method. + * @param string|null $action The action the request runs, if any. + * @param array $scope The token's scope (`mode`, `allowedActions`). + * + * @return array{status: int, body: array}|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function refusalFor(string $method, ?string $action, array $scope): ?array { + if (in_array(strtoupper($method), self::SAFE_METHODS, true) === true) { + return null; + } + + $mode = (string)($scope['mode'] ?? self::MODE_READ); + if ($mode !== self::MODE_INTERACT) { + return [ + 'status' => 403, + 'body' => [ + 'error' => 'read_only_token', + 'message' => 'This token does not permit write operations. Token scope: mode=read', + ], + ]; + } + + return $this->enforceActionScope(action: (string)$action, scope: $scope); + }//end refusalFor() + + /** + * The refusal of an action the scope does not name, or null. + * + * @param string $action The action. + * @param array $scope The token's scope. + * + * @return array{status: int, body: array}|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function enforceActionScope(string $action, array $scope): ?array { + $allowed = array_values(array_filter( + array_map('strval', (array)($scope['allowedActions'] ?? [])), + static fn (string $name): bool => $name !== '' + )); + if ($action !== '' && in_array($action, $allowed, true) === true) { + return null; + } + + $list = 'none'; + if ($allowed !== []) { + $list = implode(', ', $allowed); + } + + return [ + 'status' => 403, + 'body' => [ + 'error' => 'action_not_in_scope', + 'message' => sprintf('The action \'%s\' is not permitted by this token. Allowed actions: %s', $action, $list), + ], + ]; + }//end enforceActionScope() + + /** + * The request's filters with the token's filter context pinned over them. + * + * @param array $requestFilters The filters the request asks for. + * @param array $filterContext The token's `subject.filterContext`. + * + * @return array + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function applyFilterContext(array $requestFilters, array $filterContext): array { + return array_merge($requestFilters, $filterContext); + }//end applyFilterContext() + + /** + * The request's filters on the dimensions the scope allows, with the + * token's filter context pinned over them. A filter on a dimension outside + * `allowedFilters` is dropped; a `read` token, or one without + * `allowedFilters`, keeps only the pinned context (4.9). + * + * @param array $requestFilters The filters the request asks for. + * @param array $scope The token's scope. + * @param array $filterContext The token's `subject.filterContext`. + * + * @return array + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function restrictFilters(array $requestFilters, array $scope, array $filterContext): array { + $allowed = []; + if ((string)($scope['mode'] ?? self::MODE_READ) === self::MODE_INTERACT) { + $allowed = array_map('strval', (array)($scope['allowedFilters'] ?? [])); + } + + $kept = array_filter( + $requestFilters, + static fn (int|string $dimension): bool => in_array((string)$dimension, $allowed, true) === true, + ARRAY_FILTER_USE_KEY + ); + + return $this->applyFilterContext(requestFilters: $kept, filterContext: $filterContext); + }//end restrictFilters() + + /** + * The scope action a write request runs, read from its last path segment: + * `export` is export, `drill-down` (or `drilldown`) is drillDown, and + * `filters` or `interactions` is interact. Anything else names no action, + * so an interactions token refuses it too. + * + * @param string $path The request path. + * + * @return string|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-004--read-only-enforcement-at-the-api-tier + */ + public function actionOf(string $path): ?string { + $segments = explode('/', trim($path, '/')); + $last = strtolower((string)end($segments)); + + return match ($last) { + 'export' => 'export', + 'drill-down', 'drilldown' => 'drillDown', + 'filters', 'interactions' => 'interact', + default => null, + }; + }//end actionOf() + +}//end class diff --git a/lib/Service/Embed/SigningKeyService.php b/lib/Service/Embed/SigningKeyService.php new file mode 100644 index 000000000..48de87f40 --- /dev/null +++ b/lib/Service/Embed/SigningKeyService.php @@ -0,0 +1,145 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCA\LaunchPad\Entity\SigningKey; +use OCP\Security\ICrypto; +use Throwable; + +/** + * Loads, creates and rotates the stored signing keys. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-4 + */ +class SigningKeyService { + + /** + * Constructor. + * + * @param EmbedObjectStore $store The register objects. + * @param JwtSigningService $jwt Generates and rotates key pairs. + * @param ICrypto $crypto Encrypts the private keys at rest. + */ + public function __construct( + private readonly EmbedObjectStore $store, + private readonly JwtSigningService $jwt, + private readonly ICrypto $crypto, + ) { + }//end __construct() + + /** + * Every stored key as a key record. A private key that cannot be + * decrypted reads as '' — the key still verifies, it cannot sign. + * + * @return list> + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-4 + */ + public function keys(): array { + $records = []; + foreach ($this->store->findBy(schema: EmbedObjectStore::KEYS) as $object) { + $records[] = SigningKey::toRecord(object: $object, privateKeyPem: $this->decrypt(value: (string)($object['privateKeyEncrypted'] ?? ''))); + } + + return $records; + }//end keys() + + /** + * The keys, with a new active RS256 key stored first when none is active. + * + * @return list> + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-4 + */ + public function keysWithActive(): array { + $keys = $this->keys(); + foreach ($keys as $key) { + if (($key['status'] ?? null) === JwtSigningService::STATUS_ACTIVE && (string)($key['privateKeyPem'] ?? '') !== '') { + return $keys; + } + } + + $keys[] = $this->persist(record: $this->jwt->generateKeyPair(algorithm: JwtSigningService::RS256)); + + return $keys; + }//end keysWithActive() + + /** + * Rotate: every active key turns retiring and a new active key is stored. + * + * @param string $algorithm RS256 or ES256. + * + * @return list> The keys after rotation. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-4 + */ + public function rotate(string $algorithm): array { + $before = $this->keys(); + $rotated = []; + foreach ($this->jwt->rotate(keys: $before, algorithm: $algorithm) as $index => $record) { + if (isset($before[$index]) === true && $before[$index] === $record) { + $rotated[] = $record; + continue; + } + + $rotated[] = $this->persist(record: $record); + } + + return $rotated; + }//end rotate() + + /** + * Store a key record, its private key encrypted. + * + * @param array $record The key record. + * + * @return array The record with its stored id. + */ + private function persist(array $record): array { + $encrypted = $this->crypto->encrypt((string)($record['privateKeyPem'] ?? '')); + $stored = $this->store->save(schema: EmbedObjectStore::KEYS, object: SigningKey::toObject(record: $record, privateKeyEncrypted: $encrypted)); + + return ['id' => (string)$stored['id']] + $record; + }//end persist() + + /** + * A decrypted private key, '' when it cannot be decrypted. + * + * @param string $value The encrypted value. + * + * @return string + */ + private function decrypt(string $value): string { + if ($value === '') { + return ''; + } + + try { + return $this->crypto->decrypt($value); + } catch (Throwable) { + return ''; + } + }//end decrypt() +}//end class diff --git a/lib/Service/Embed/TenantThemeService.php b/lib/Service/Embed/TenantThemeService.php new file mode 100644 index 000000000..b444acae9 --- /dev/null +++ b/lib/Service/Embed/TenantThemeService.php @@ -0,0 +1,333 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCA\LaunchPad\Entity\TenantTheme; +use OCP\AppFramework\Utility\ITimeFactory; + +/** + * Creates, updates and renders tenant themes. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-005--per-tenant-theming-via-css-variables + */ +class TenantThemeService { + + /** + * The smallest contrast ratio accepted for text (WCAG 2.1 AA). + * + * @var float + */ + public const MIN_CONTRAST = 4.5; + + /** + * The colours checked against `--c-surface`, with how the message names them. + * + * @var array + */ + private const CONTRAST_PAIRS = ['--c-primary' => 'Primary', '--c-text' => 'Text']; + + /** + * Constructor. + * + * @param EmbedObjectStore $store The register objects. + * @param TenantThemeValidator $validator CSS and contrast checks. + * @param ITimeFactory $time The clock. + */ + public function __construct( + private readonly EmbedObjectStore $store, + private readonly TenantThemeValidator $validator, + private readonly ITimeFactory $time, + ) { + }//end __construct() + + /** + * Create a theme. + * + * @param array $input {name, cssVariables, logoUrl?, customCss?}. + * @param string $userId The admin. + * + * @return array The stored theme, or a refusal {status: error, error, message, fieldErrors}. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-005--per-tenant-theming-via-css-variables + */ + public function createTheme(array $input, string $userId): array { + $refusal = $this->refusalFor(input: $input); + if ($refusal !== null) { + return $refusal; + } + + $theme = TenantTheme::fromObject( + object: [ + 'createdBy' => $userId, + 'createdAt' => gmdate('Y-m-d\TH:i:s\Z', $this->time->getTime()), + ] + self::fields(input: $input) + ); + + return $this->store->save(schema: EmbedObjectStore::THEMES, object: $theme->toObject()); + }//end createTheme() + + /** + * Update a theme; every token using it follows at once (REQ-EMB-005 5.7). + * + * @param string $id The theme id. + * @param array $input The full new theme. + * + * @return array|null The stored theme, a refusal, or null when there is no such theme. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-005--per-tenant-theming-via-css-variables + */ + public function updateTheme(string $id, array $input): ?array { + $current = $this->getTheme(id: $id); + if ($current === null) { + return null; + } + + $refusal = $this->refusalFor(input: $input); + if ($refusal !== null) { + return $refusal; + } + + $theme = TenantTheme::fromObject( + object: ['id' => $current->id, 'createdBy' => $current->createdBy, 'createdAt' => $current->createdAt] + self::fields(input: $input) + ); + + return $this->store->save(schema: EmbedObjectStore::THEMES, object: $theme->toObject()); + }//end updateTheme() + + /** + * A theme, or null. + * + * @param string $id The theme id. + * + * @return TenantTheme|null + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-11 + */ + public function getTheme(string $id): ?TenantTheme { + $object = $this->store->find(schema: EmbedObjectStore::THEMES, id: $id); + if ($object === null) { + return null; + } + + return TenantTheme::fromObject(object: $object); + }//end getTheme() + + /** + * Every theme, with how many tokens use it (to warn before deleting). + * + * @return list> + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-11 + */ + public function listThemes(): array { + $usage = []; + foreach ($this->store->findBy(schema: EmbedObjectStore::TOKENS) as $token) { + $themeId = (string)($token['tenantThemeId'] ?? ''); + if ($themeId !== '') { + $usage[$themeId] = (($usage[$themeId] ?? 0) + 1); + } + } + + $themes = []; + foreach ($this->store->findBy(schema: EmbedObjectStore::THEMES) as $object) { + $theme = TenantTheme::fromObject(object: $object); + $themes[] = $theme->toObject() + ['id' => $theme->id, 'tokenCount' => ($usage[$theme->id] ?? 0)]; + } + + return $themes; + }//end listThemes() + + /** + * Delete a theme. A theme tokens still use is kept unless `force` is set: + * those tokens then render with the platform default (5.4). + * + * @param string $id The theme id. + * @param bool $force Delete even when tokens use it. + * + * @return array|null {deleted, tokenCount}, a refusal {status: error, error: theme_in_use, tokenCount}, + * or null when there is no such theme. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ + public function deleteTheme(string $id, bool $force=false): ?array { + if ($this->getTheme(id: $id) === null) { + return null; + } + + $tokenCount = count($this->store->findBy(schema: EmbedObjectStore::TOKENS, filters: ['tenantThemeId' => $id])); + if ($tokenCount > 0 && $force === false) { + return [ + 'status' => 'error', + 'error' => 'theme_in_use', + 'message' => 'Embed tokens still use this theme; they fall back to the default theme when it is deleted.', + 'tokenCount' => $tokenCount, + ]; + } + + $this->store->delete(schema: EmbedObjectStore::THEMES, id: $id); + + return ['deleted' => true, 'tokenCount' => $tokenCount]; + }//end deleteTheme() + + /** + * The CSS an embed injects for a theme: its variables and custom CSS on + * :root; '' without a theme, so the platform default applies (5.4). + * + * @param string|null $themeId The token's theme. + * + * @return string + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-005--per-tenant-theming-via-css-variables + */ + public function rootCss(?string $themeId): string { + if ($themeId === null || $themeId === '') { + return ''; + } + + $theme = $this->getTheme(id: $themeId); + if ($theme === null) { + return ''; + } + + $css = $this->validator->rootBlock(cssVariables: $theme->cssVariables); + if ($theme->customCss !== '' && $this->validator->validateCss(customCss: $theme->customCss) === null) { + $css = trim($css . "\n" . trim($theme->customCss)); + } + + return $css; + }//end rootCss() + + /** + * Why a theme is refused, or null. + * + * @param array $input The theme. + * + * @return array|null + */ + private function refusalFor(array $input): ?array { + if (trim((string)($input['name'] ?? '')) === '') { + return self::refusal(error: 'invalid_name', message: 'Give the theme a name.', field: 'name', code: 'invalid_name'); + } + + $variables = ($input['cssVariables'] ?? []); + if (is_array($variables) === false) { + return self::refusal( + error: 'invalid_cssVariables', + message: 'CSS variables are an object of --name: value.', + field: 'cssVariables', + code: 'invalid_cssVariables' + ); + } + + foreach ($variables as $name => $value) { + if (is_string($name) === false || preg_match('~^--[a-zA-Z0-9_-]+$~', $name) !== 1 + || is_scalar($value) === false || preg_match('~[;{}<>\\\\]~', (string)$value) === 1 + ) { + return self::refusal( + error: 'invalid_cssVariables', + message: 'A CSS variable is named --name and its value holds no ; { } < > or \\.', + field: 'cssVariables.' . (string)$name, + code: 'invalid_cssVariables' + ); + } + } + + $css = $this->validator->validateCss(customCss: (string)($input['customCss'] ?? '')); + if ($css !== null) { + return self::refusal(error: 'invalid_customCss', message: (string)$css['message'], field: 'customCss', code: 'non_root_selector'); + } + + $logo = ($input['logoUrl'] ?? null); + if ($logo !== null && $logo !== '' && (is_string($logo) === false || preg_match('~^https://[^\s"\'<>]+$~', $logo) !== 1)) { + return self::refusal(error: 'invalid_logoUrl', message: 'The logo is an https URL.', field: 'logoUrl', code: 'invalid_logoUrl'); + } + + return $this->contrastRefusal(variables: $variables); + }//end refusalFor() + + /** + * Why the colours fail WCAG AA on the surface, or null. + * + * @param array $variables The CSS variables. + * + * @return array|null + */ + private function contrastRefusal(array $variables): ?array { + $surface = (string)($variables['--c-surface'] ?? ''); + if ($surface === '') { + return null; + } + + foreach (self::CONTRAST_PAIRS as $name => $label) { + $colour = (string)($variables[$name] ?? ''); + $ratio = $this->validator->contrastRatio(foreground: $colour, background: $surface); + if ($ratio === null || $ratio >= self::MIN_CONTRAST) { + continue; + } + + // Rounded down, so a ratio just under 4.5 never reads as 4.5. + $shown = number_format((floor($ratio * 10) / 10), 1); + + return self::refusal( + error: 'insufficient_contrast', + message: sprintf('%s colour %s against surface %s has contrast ratio %s:1. WCAG AA requires 4.5:1 for text.', $label, $colour, $surface, $shown), + field: 'cssVariables.' . $name, + code: 'insufficient_contrast' + ); + } + + return null; + }//end contrastRefusal() + + /** + * The stored fields of a validated theme. + * + * @param array $input The theme. + * + * @return array + */ + private static function fields(array $input): array { + return [ + 'name' => trim((string)$input['name']), + 'cssVariables' => (array)($input['cssVariables'] ?? []), + 'logoUrl' => ($input['logoUrl'] ?? null), + 'customCss' => trim((string)($input['customCss'] ?? '')), + ]; + }//end fields() + + /** + * A refusal in the REQ-EMB-005 5.3 shape. + * + * @param string $error The error code. + * @param string $message The message. + * @param string $field The field at fault. + * @param string $code The field's error code. + * + * @return array + */ + private static function refusal(string $error, string $message, string $field, string $code): array { + return ['status' => 'error', 'error' => $error, 'message' => $message, 'fieldErrors' => [$field => $code]]; + }//end refusal() +}//end class diff --git a/lib/Service/Embed/TenantThemeValidator.php b/lib/Service/Embed/TenantThemeValidator.php new file mode 100644 index 000000000..acdc41ad7 --- /dev/null +++ b/lib/Service/Embed/TenantThemeValidator.php @@ -0,0 +1,194 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +/** + * Validates and renders a tenant theme's CSS. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-005--per-tenant-theming-via-css-variables + */ +final class TenantThemeValidator { + + /** + * The minimum contrast of normal text (WCAG 1.4.3). + * + * @var float + */ + public const MIN_CONTRAST = 4.5; + + /** + * The refusal of custom CSS that reaches outside `:root`, or null when it is accepted. + * + * @param string $customCss The custom CSS. + * + * @return array{error: string, message: string}|null + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-005--per-tenant-theming-via-css-variables + */ + public function validateCss(string $customCss): ?array { + $css = trim((string)preg_replace('~/\*.*?\*/~s', '', $customCss)); + if ($css === '') { + return null; + } + + if (preg_match('~[<@\\\\]~', $css) === 1) { + return $this->refusal(message: 'Custom CSS may hold only :root declarations: no at-rules, escapes or markup.'); + } + + if (preg_match_all('~([^{}]*)\{([^{}]*)\}~', $css, $rules, PREG_SET_ORDER) === 0 + || trim((string)preg_replace('~[^{}]*\{[^{}]*\}~', '', $css)) !== '' + ) { + return $this->refusal(message: 'Custom CSS could not be read as :root rules.'); + } + + foreach ($rules as $rule) { + foreach (explode(',', $rule[1]) as $selector) { + $selector = trim($selector); + if ($selector !== ':root') { + return $this->refusal(message: sprintf( + 'CSS rules must be scoped to :root only. Found selector \'%s\' which targets elements outside :root. ' + . 'Non-:root selectors can be used to disable required UI affordances (e.g., hide accessibility focus rings).', + $selector + )); + } + } + } + + return null; + }//end validateCss() + + /** + * The WCAG contrast ratio of two `#rgb` or `#rrggbb` colours, or null when one is not such a colour. + * + * @param string $foreground The text colour. + * @param string $background The surface colour. + * + * @return float|null The ratio, from 1 to 21, rounded to two decimals. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-010--wcag-21-aa-compliance-enforced-in-embed-rendering + */ + public function contrastRatio(string $foreground, string $background): ?float { + $one = $this->luminance(colour: $foreground); + $two = $this->luminance(colour: $background); + if ($one === null || $two === null) { + return null; + } + + return round((max($one, $two) + 0.05) / (min($one, $two) + 0.05), 2); + }//end contrastRatio() + + /** + * Whether text in one colour is readable on the other (at least 4.5:1). + * + * @param string $foreground The text colour. + * @param string $background The surface colour. + * + * @return bool False also for a colour that cannot be read. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-010--wcag-21-aa-compliance-enforced-in-embed-rendering + */ + public function validateContrastRatio(string $foreground, string $background): bool { + $ratio = $this->contrastRatio(foreground: $foreground, background: $background); + + return $ratio !== null && $ratio >= self::MIN_CONTRAST; + }//end validateContrastRatio() + + /** + * The `:root` block of a theme's CSS variables. A name that is not a + * custom property, or a value that could close the declaration or the + * style element, is left out. + * + * @param array $cssVariables Name => value. + * + * @return string The block, or '' when no variable is usable. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-005--per-tenant-theming-via-css-variables + */ + public function rootBlock(array $cssVariables): string { + $lines = []; + foreach ($cssVariables as $name => $value) { + if (is_string($name) === false || preg_match('~^--[a-zA-Z0-9_-]+$~', $name) !== 1) { + continue; + } + + if (is_scalar($value) === false || preg_match('~[;{}<>\\\\]~', (string)$value) === 1) { + continue; + } + + $lines[] = ' ' . $name . ': ' . trim((string)$value) . ';'; + } + + if ($lines === []) { + return ''; + } + + return ":root {\n" . implode("\n", $lines) . "\n}"; + }//end rootBlock() + + /** + * The relative luminance of a hex colour, or null. + * + * @param string $colour The colour. + * + * @return float|null + */ + private function luminance(string $colour): ?float { + $hex = ltrim(trim($colour), '#'); + if (preg_match('~^([0-9a-f]{3}|[0-9a-f]{6})$~i', $hex) !== 1) { + return null; + } + + if (strlen($hex) === 3) { + $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; + } + + $channels = []; + foreach ([0, 2, 4] as $offset) { + $value = (hexdec(substr($hex, $offset, 2)) / 255); + if ($value <= 0.03928) { + $channels[] = ($value / 12.92); + continue; + } + + $channels[] = ((($value + 0.055) / 1.055) ** 2.4); + } + + return ((0.2126 * $channels[0]) + (0.7152 * $channels[1]) + (0.0722 * $channels[2])); + }//end luminance() + + /** + * The validation refusal body. + * + * @param string $message The message. + * + * @return array{error: string, message: string} + */ + private function refusal(string $message): array { + return ['error' => 'validation_error', 'message' => $message]; + }//end refusal() + +}//end class diff --git a/lib/Service/Embed/UsageTelemetryService.php b/lib/Service/Embed/UsageTelemetryService.php new file mode 100644 index 000000000..7b631031e --- /dev/null +++ b/lib/Service/Embed/UsageTelemetryService.php @@ -0,0 +1,283 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Embed; + +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Entity\EmbedUsageEvent; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IAppConfig; +use OCP\Log\Audit\CriticalActionPerformedEvent; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Records embed usage and reports it in aggregate. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-008--usage-telemetry-without-leaking-pii + */ +class UsageTelemetryService { + + /** + * The app setting that turns telemetry on (default) or off. + * + * @var string + */ + public const SETTING = 'embed_telemetry_enabled'; + + /** + * The report window, in days. + * + * @var integer + */ + public const REPORT_DAYS = 7; + + /** + * How many browsers the report lists. + * + * @var integer + */ + private const TOP_BROWSERS = 10; + + /** + * Constructor. + * + * @param EmbedObjectStore $store The register objects. + * @param IAppConfig $appConfig Holds the telemetry setting. + * @param ITimeFactory $time The clock. + * @param IEventDispatcher $dispatcher Carries the audit event. + * @param LoggerInterface $logger Logs an event that could not be written. + */ + public function __construct( + private readonly EmbedObjectStore $store, + private readonly IAppConfig $appConfig, + private readonly ITimeFactory $time, + private readonly IEventDispatcher $dispatcher, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * Whether usage events are written. + * + * @return bool + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-30 + */ + public function isEnabled(): bool { + return $this->appConfig->getValueBool(Application::APP_ID, self::SETTING, true); + }//end isEnabled() + + /** + * Turn telemetry on or off, and audit the change. + * + * @param bool $enabled Whether to write usage events. + * @param string $userId The admin. + * + * @return void + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-30 + */ + public function setEnabled(bool $enabled, string $userId): void { + $before = $this->isEnabled(); + $this->appConfig->setValueBool(Application::APP_ID, self::SETTING, $enabled); + if ($before === $enabled) { + return; + } + + $state = 'off'; + if ($enabled === true) { + $state = 'on'; + } + + $this->dispatcher->dispatchTyped( + new CriticalActionPerformedEvent('LaunchPad embed usage telemetry turned %s by %s', [$state, $userId]) + ); + }//end setEnabled() + + /** + * Write one usage event; nothing when telemetry is off. A write failure + * is logged and never reaches the caller (the embed still renders). + * + * @param string $tokenId The token. + * @param string $eventType One of EmbedUsageEvent::TYPES. + * @param string|null $origin The Origin header. + * @param string|null $referer The Referer header. + * @param string|null $userAgent The User-Agent header. + * @param string|null $viewport The viewport the SDK reported. + * @param int $status The response status. + * @param int $latencyMs The response latency. + * + * @return array|null The stored event, null when none was written. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-008--usage-telemetry-without-leaking-pii + */ + public function record( + string $tokenId, + string $eventType, + ?string $origin, + ?string $referer, + ?string $userAgent, + ?string $viewport, + int $status, + int $latencyMs, + ): ?array { + if ($this->isEnabled() === false) { + return null; + } + + $event = EmbedUsageEvent::build( + tokenId: $tokenId, + eventType: $eventType, + origin: $origin, + referer: $referer, + userAgent: $userAgent, + viewport: $viewport, + status: $status, + latencyMs: $latencyMs, + timestamp: gmdate('Y-m-d\TH:i:s\Z', $this->time->getTime()) + ); + + try { + return $this->store->save(schema: EmbedObjectStore::USAGE, object: $event); + } catch (Throwable $failure) { + $this->logger->warning('[UsageTelemetryService] A usage event could not be written: ' . $failure->getMessage(), ['token' => $tokenId]); + return null; + } + }//end record() + + /** + * A token's usage over the last seven days, in aggregate only. + * + * @param string $tokenId The token. + * @param string|null $revokedAt When the token was revoked, to count use after it. + * + * @return array + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-29 + */ + public function report(string $tokenId, ?string $revokedAt=null): array { + $now = $this->time->getTime(); + $since = gmdate('Y-m-d', $now - ((self::REPORT_DAYS - 1) * 86400)); + + $byDate = []; + for ($day = (self::REPORT_DAYS - 1); $day >= 0; $day--) { + $byDate[gmdate('Y-m-d', $now - ($day * 86400))] = 0; + } + + $origins = []; + $viewports = ['small' => 0, 'medium' => 0, 'large' => 0, 'unknown' => 0]; + $browsers = []; + $interactions = ['filterApplied' => 0, 'drillDown' => 0, 'export' => 0]; + $statuses = []; + $pageViews = 0; + $rateLimited = 0; + $afterRevoke = 0; + $last = null; + + foreach ($this->store->findBy(schema: EmbedObjectStore::USAGE, filters: ['tokenId' => $tokenId]) as $event) { + $timestamp = (string)($event['timestamp'] ?? ''); + $date = substr($timestamp, 0, 10); + if ($date < $since) { + continue; + } + + $type = (string)($event['eventType'] ?? ''); + $status = (int)($event['responseStatusCode'] ?? 0); + if ($last === null || $timestamp > $last) { + $last = $timestamp; + } + + if ($revokedAt !== null && $timestamp > $revokedAt) { + $afterRevoke++; + } + + $statuses[(string)$status] = (($statuses[(string)$status] ?? 0) + 1); + if ($status === 429 || $type === 'rateLimited') { + $rateLimited++; + } + + if (isset($interactions[$type]) === true) { + $interactions[$type]++; + continue; + } + + if ($type !== 'pageView') { + continue; + } + + $pageViews++; + if (isset($byDate[$date]) === true) { + $byDate[$date]++; + } + + $origin = (string)($event['hostOrigin'] ?? 'unknown'); + $origins[$origin] = (($origins[$origin] ?? 0) + 1); + $viewport = (string)($event['viewportSize'] ?? 'unknown'); + if (isset($viewports[$viewport]) === false) { + $viewport = 'unknown'; + } + + $viewports[$viewport]++; + $browser = (string)($event['userAgent'] ?? 'Other'); + $browsers[$browser] = (($browsers[$browser] ?? 0) + 1); + }//end foreach + + arsort($origins); + arsort($browsers); + ksort($statuses); + + return [ + 'tokenId' => $tokenId, + 'days' => self::REPORT_DAYS, + 'telemetryEnabled' => $this->isEnabled(), + 'summary' => ['pageViews' => $pageViews, 'lastActivity' => $last, 'usedAfterRevocation' => $afterRevoke], + 'byDate' => self::series(counts: $byDate), + 'byHostOrigin' => self::series(counts: $origins), + 'byViewport' => $viewports, + 'byBrowser' => self::series(counts: array_slice($browsers, 0, self::TOP_BROWSERS, true)), + 'interactions' => $interactions, + 'rateLimited' => $rateLimited, + 'byStatus' => $statuses, + ]; + }//end report() + + /** + * Counts as a chart series: [{label, count}]. + * + * @param array $counts Label => count. + * + * @return list + */ + private static function series(array $counts): array { + $series = []; + foreach ($counts as $label => $count) { + $series[] = ['label' => (string)$label, 'count' => $count]; + } + + return $series; + }//end series() +}//end class diff --git a/lib/Service/ExportService.php b/lib/Service/ExportService.php index 89d775a76..22db883f4 100644 --- a/lib/Service/ExportService.php +++ b/lib/Service/ExportService.php @@ -36,6 +36,7 @@ use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacement; use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Kernel\Contracts\ExportServiceInterface; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Http; use OCP\AppFramework\Http\StreamResponse; @@ -57,7 +58,7 @@ * inherently racy — another request's cleanup may win. Cleanup is * best-effort by design, so the warning is noise. */ -class ExportService { +class ExportService implements ExportServiceInterface { /** * Manifest schema version emitted by this exporter (REQ-EXIM-001). * @@ -232,6 +233,33 @@ private function buildArchive( string $scope, string $currentUserId, ): string { + [$zip, $tempPath] = $this->openArchive(); + + $manifest = $this->buildManifest( + scope: $scope, + dashboardCount: count($dashboards), + currentUserId: $currentUserId + ); + + $zip->addFromString( + name: 'manifest.json', + content: $this->encodeJson(payload: $manifest) + ); + + $assetsAdded = $this->addDashboards(zip: $zip, dashboards: $dashboards); + $this->closeArchive(zip: $zip, assetsAdded: $assetsAdded); + + return $tempPath; + }//end buildArchive() + + /** + * Allocate the temporary file and open it as a new ZIP archive. + * + * @return array{0: ZipArchive, 1: string} The open archive and its path. + * + * @throws RuntimeException When the file or the archive cannot be opened. + */ + private function openArchive(): array { $tempPath = tempnam(directory: sys_get_temp_dir(), prefix: 'launchpad-export-'); if ($tempPath === false) { throw new RuntimeException( @@ -245,17 +273,18 @@ private function buildArchive( throw new RuntimeException(message: 'Could not open ZIP archive for writing.'); } - $manifest = $this->buildManifest( - scope: $scope, - dashboardCount: count($dashboards), - currentUserId: $currentUserId - ); - - $zip->addFromString( - name: 'manifest.json', - content: $this->encodeJson(payload: $manifest) - ); + return [$zip, $tempPath]; + }//end openArchive() + /** + * Write one JSON file per dashboard, with its asset placeholders. + * + * @param ZipArchive $zip The open archive. + * @param Dashboard[] $dashboards The dashboards to include. + * + * @return bool Whether any asset placeholder was added. + */ + private function addDashboards(ZipArchive $zip, array $dashboards): bool { $assetsAdded = false; foreach ($dashboards as $dashboard) { $payload = $this->serializeDashboard(dashboard: $dashboard); @@ -275,6 +304,19 @@ private function buildArchive( ) || $assetsAdded; } + return $assetsAdded; + }//end addDashboards() + + /** + * Write the metadata-fields file, reserve the asset directories when no + * asset was added, and close the archive. + * + * @param ZipArchive $zip The open archive. + * @param bool $assetsAdded Whether any asset placeholder was added. + * + * @return void + */ + private function closeArchive(ZipArchive $zip, bool $assetsAdded): void { // The metadata-fields.json is always emitted (empty list when // no metadata-fields capability has been registered yet) so the // downstream `confluence-html-import` consumer never has to @@ -292,9 +334,7 @@ private function buildArchive( } $zip->close(); - - return $tempPath; - }//end buildArchive() + }//end closeArchive() /** * Add icon / widget asset placeholders for a dashboard. diff --git a/lib/Service/FeedFetchTools.php b/lib/Service/FeedFetchTools.php new file mode 100644 index 000000000..5831c8a65 --- /dev/null +++ b/lib/Service/FeedFetchTools.php @@ -0,0 +1,54 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/widgets/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Service\Connection\ConnectionReporter; +use OCP\Http\Client\IClientService; +use OCP\ICacheFactory; + +/** + * + * + * @spec openspec/specs/widgets/spec.md + */ +class FeedFetchTools { + /** + * Constructor. + * + * @param IClientService $clientService Builds the HTTP client used for synchronous on-demand feed + * fetches. + * @param ICacheFactory $cacheFactory Backing factory for the distributed cache used to hold raw + * feed payloads. + * @param UrlSafetyValidator $urlValidator Shared SSRF / allow-list guard. + * @param ConnectionReporter|null $connectionReporter Tells integriq what a feed fetch met, or nothing when + * absent. + */ + public function __construct( + public readonly IClientService $clientService, + public readonly ICacheFactory $cacheFactory, + public readonly UrlSafetyValidator $urlValidator, + public readonly ?ConnectionReporter $connectionReporter=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/FeedItemParser.php b/lib/Service/FeedItemParser.php new file mode 100644 index 000000000..9604a5d71 --- /dev/null +++ b/lib/Service/FeedItemParser.php @@ -0,0 +1,346 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use RuntimeException; +use SimpleXMLElement; + +/** + * Parses and normalises the feed bodies FeedRefreshService fetches. + * + * @spec openspec/specs/background-job-feed-refresh/spec.md + */ +final class FeedItemParser { + + /** + * Parse an RSS 2.0 / Atom 1.0 feed body and return normalised items + * sorted newest-first (REQ-FRJ-005). + * + * @param string $body The XML body. + * @param string $feedUrl The feed URL (for sourceUrl/sourceTitle). + * + * @return array> The normalised items. + * + * @throws RuntimeException When parsing fails. + * + * @spec openspec/specs/background-job-feed-refresh/spec.md + */ + public function parse(string $body, string $feedUrl): array { + $xml = $this->loadFeedXml(body: $body); + $source = new FeedSource(url: $feedUrl, title: $this->extractFeedTitle(xml: $xml, feedUrl: $feedUrl)); + $items = $this->extractItems(xml: $xml, source: $source); + + // Sort newest-first by pubDate. + usort( + array: $items, + callback: static fn (array $left, array $right): int => self::compareByPubDate( + left: $left, + right: $right + ) + ); + + return $items; + }//end parse() + + /** + * Parse the raw XML body, converting libxml's error channel into an + * exception. + * + * C2: LIBXML_NOENT is deliberately NOT passed — it resolves (not + * disables) entities, enabling XXE; LIBXML_NONET blocks external + * DTD/entity fetches. L1: LIBXML_NOCDATA is deliberately NOT passed — + * it folds CDATA into text nodes, masking downstream sanitisation. + * + * @param string $body The raw XML body. + * + * @return SimpleXMLElement The parsed document. + * + * @throws RuntimeException When the body is not well-formed XML; the + * message carries the first libxml error. + */ + private function loadFeedXml(string $body): SimpleXMLElement { + $previous = libxml_use_internal_errors(use_errors: true); + try { + $xml = simplexml_load_string( + data: $body, + class_name: 'SimpleXMLElement', + options: LIBXML_NONET + ); + if ($xml === false) { + $errors = libxml_get_errors(); + libxml_clear_errors(); + $message = 'malformed XML'; + if (isset($errors[0]) === true) { + $message = trim(string: $errors[0]->message); + } + + throw new RuntimeException(message: $message); + } + } finally { + libxml_clear_errors(); + libxml_use_internal_errors(use_errors: $previous); + }//end try + + return $xml; + }//end loadFeedXml() + + /** + * Collect the normalised entries from an RSS 2.0 or Atom 1.0 document. + * + * RSS is probed first; a document carrying neither shape yields an + * empty list, so an empty feed is not a parse failure. + * + * @param SimpleXMLElement $xml The parsed feed document. + * @param FeedSource $source The feed URL and resolved channel/feed title. + * + * @return array> Normalised items, unsorted. + */ + private function extractItems(SimpleXMLElement $xml, FeedSource $source): array { + $items = []; + + // RSS 2.0 — ... + if (isset($xml->channel) === true && isset($xml->channel->item) === true) { + foreach ($xml->channel->item as $item) { + $items[] = $this->normaliseRssItem(item: $item, source: $source); + } + } elseif (isset($xml->entry) === true) { + // Atom 1.0 — ... + foreach ($xml->entry as $entry) { + $items[] = $this->normaliseAtomEntry(entry: $entry, source: $source); + } + } + + return $items; + }//end extractItems() + + /** + * Newest-first comparator over the normalised `pubDate` field. + * + * A missing or unparseable date sorts as epoch 0, i.e. last. + * + * @param array $left Left-hand normalised item. + * @param array $right Right-hand normalised item. + * + * @return int Negative, zero or positive per the usort contract. + */ + private static function compareByPubDate(array $left, array $right): int { + $leftRaw = strtotime(datetime: (string)($left['pubDate'] ?? '')); + $rightRaw = strtotime(datetime: (string)($right['pubDate'] ?? '')); + $leftTs = 0; + if ($leftRaw !== false) { + $leftTs = $leftRaw; + } + + $rightTs = 0; + if ($rightRaw !== false) { + $rightTs = $rightRaw; + } + + return ($rightTs <=> $leftTs); + }//end compareByPubDate() + + /** + * Extract the channel-level title (RSS) or feed-level title (Atom), + * falling back to the URL hostname. + * + * @param SimpleXMLElement $xml The parsed feed. + * @param string $feedUrl The feed URL. + * + * @return string The source title. + */ + private function extractFeedTitle( + SimpleXMLElement $xml, + string $feedUrl, + ): string { + $title = self::declaredTitle(xml: $xml); + if ($title !== '') { + return $title; + } + + $host = (string)parse_url(url: $feedUrl, component: PHP_URL_HOST); + if ($host !== '') { + return $host; + } + + return $feedUrl; + }//end extractFeedTitle() + + /** + * The trimmed channel title (RSS), else the trimmed feed title (Atom), + * or '' when neither is present and non-blank. + * + * @param SimpleXMLElement $xml The parsed feed. + * + * @return string + */ + private static function declaredTitle(SimpleXMLElement $xml): string { + if (isset($xml->channel) === true && isset($xml->channel->title) === true) { + $title = trim(string: (string)$xml->channel->title); + if ($title !== '') { + return $title; + } + } + + if (isset($xml->title) === true) { + return trim(string: (string)$xml->title); + } + + return ''; + }//end declaredTitle() + + /** + * Normalise a single RSS 2.0 item to the news-widget schema. + * + * @param SimpleXMLElement $item The RSS item element. + * @param FeedSource $source The feed URL and channel title. + * + * @return array + */ + private function normaliseRssItem(SimpleXMLElement $item, FeedSource $source): array { + return self::itemRecord( + fields: [ + 'guid' => trim(string: (string)($item->guid ?? '')), + 'title' => trim(string: (string)($item->title ?? '')), + 'summary' => trim(string: (string)($item->description ?? '')), + 'link' => trim(string: (string)($item->link ?? '')), + 'pubDate' => trim(string: (string)($item->pubDate ?? '')), + 'thumbnailUrl' => self::imageEnclosureUrl(item: $item), + ], + source: $source + ); + }//end normaliseRssItem() + + /** + * The URL of an RSS item's enclosure when its type is `image/*`, else null. + * + * @param SimpleXMLElement $item The RSS item element. + * + * @return string|null + */ + private static function imageEnclosureUrl(SimpleXMLElement $item): ?string { + if (isset($item->enclosure) === false) { + return null; + } + + $attrs = $item->enclosure->attributes(); + if ($attrs === null || isset($attrs['type']) === false) { + return null; + } + + if (str_starts_with(haystack: (string)$attrs['type'], needle: 'image/') === true) { + return (string)$attrs['url']; + } + + return null; + }//end imageEnclosureUrl() + + /** + * Normalise a single Atom 1.0 entry to the news-widget schema. + * + * @param SimpleXMLElement $entry The Atom entry element. + * @param FeedSource $source The feed URL and feed title. + * + * @return array + */ + private function normaliseAtomEntry(SimpleXMLElement $entry, FeedSource $source): array { + return self::itemRecord( + fields: [ + 'guid' => trim(string: (string)($entry->id ?? '')), + 'title' => trim(string: (string)($entry->title ?? '')), + 'summary' => self::firstNonBlank(node: $entry, names: ['summary', 'content']), + 'link' => self::atomAlternateLink(entry: $entry), + 'pubDate' => self::firstNonBlank(node: $entry, names: ['published', 'updated']), + 'thumbnailUrl' => null, + ], + source: $source + ); + }//end normaliseAtomEntry() + + /** + * The first child, out of `$names`, whose trimmed text is not empty; + * '' when none is. + * + * @param SimpleXMLElement $node Parent element. + * @param string[] $names Child names, tried in order. + * + * @return string + */ + private static function firstNonBlank(SimpleXMLElement $node, array $names): string { + foreach ($names as $name) { + $text = trim(string: (string)($node->$name ?? '')); + if ($text !== '') { + return $text; + } + } + + return ''; + }//end firstNonBlank() + + /** + * The href of an Atom entry's first non-empty `alternate` link (a link + * without `rel` counts as alternate), or '' without one. + * + * @param SimpleXMLElement $entry The Atom entry element. + * + * @return string + */ + private static function atomAlternateLink(SimpleXMLElement $entry): string { + if (isset($entry->link) === false) { + return ''; + } + + foreach ($entry->link as $linkElement) { + $attrs = $linkElement->attributes(); + if ($attrs === null) { + continue; + } + + $rel = (string)($attrs['rel'] ?? 'alternate'); + $href = (string)($attrs['href'] ?? ''); + if ($rel === 'alternate' && $href !== '') { + return $href; + } + } + + return ''; + }//end atomAlternateLink() + + /** + * Complete the fields read from one entry into the news-widget item: + * the entry id, or `sha256(title . pubDate . feedUrl)` when it has + * none, plus the feed source. + * + * @param array $fields Fields read from the entry: guid (the entry id), title, summary, link, pubDate + * (strings) and thumbnailUrl (string or null). + * @param FeedSource $source The feed URL and title. + * + * @return array + */ + private static function itemRecord(array $fields, FeedSource $source): array { + if ($fields['guid'] === '') { + $fields['guid'] = hash(algo: 'sha256', data: ($fields['title'] . $fields['pubDate'] . $source->url)); + } + + return $source->item(fields: $fields); + }//end itemRecord() +}//end class diff --git a/lib/Service/FeedRefreshRun.php b/lib/Service/FeedRefreshRun.php new file mode 100644 index 000000000..881b67494 --- /dev/null +++ b/lib/Service/FeedRefreshRun.php @@ -0,0 +1,128 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTime; +use OCA\LaunchPad\Db\FeedCache; +use OCA\LaunchPad\Db\FeedCacheMapper; + +/** + * State shared by the steps of one FeedRefreshService::refreshFeed() call. + * Only FeedRefreshService builds and reads it. + * + * @spec openspec/specs/background-job-feed-refresh/spec.md + */ +final class FeedRefreshRun { + + /** + * The feed URL. + * + * @var string + */ + public readonly string $feedUrl; + + /** + * Refresh start time in epoch milliseconds. + * + * @var integer + */ + public readonly int $startedAt; + + /** + * The cache row being refreshed. + * + * @var FeedCache + */ + public readonly FeedCache $row; + + /** + * The `lastFetchedAt` timestamp of this refresh, `Y-m-d H:i:s`. + * + * @var string + */ + public readonly string $now; + + /** + * Start a refresh: note the start time, load or create the cache row, + * then take the fetch timestamp — in that order. + * + * @param FeedCacheMapper $mapper The feed-cache mapper. + * @param string $feedUrl The feed URL. + */ + public function __construct(FeedCacheMapper $mapper, string $feedUrl) { + $this->feedUrl = $feedUrl; + $this->startedAt = self::nowMs(); + $this->row = $mapper->upsertUrl(feedUrl: $feedUrl); + $this->now = (new DateTime())->format(format: 'Y-m-d H:i:s'); + }//end __construct() + + /** + * The result envelope of this refresh. + * + * @param string $status `ok`, `not-modified`, `skipped` or `failed`. + * @param int $itemCount Number of items the row now holds. + * + * @return array{status: string, itemCount: int, durationMs: int} + * + * @spec openspec/specs/background-job-feed-refresh/spec.md + */ + public function result(string $status, int $itemCount): array { + return [ + 'status' => $status, + 'itemCount' => $itemCount, + 'durationMs' => (self::nowMs() - $this->startedAt), + ]; + }//end result() + + /** + * Number of items still cached on the row from the last successful fetch. + * + * @return int + * + * @spec openspec/specs/background-job-feed-refresh/spec.md + */ + public function cachedItemCount(): int { + return count(value: $this->row->decodeItems()); + }//end cachedItemCount() + + /** + * Stamp this refresh's fetch timestamp on the row. + * + * @return void + * + * @spec openspec/specs/background-job-feed-refresh/spec.md + */ + public function stampFetched(): void { + $this->row->setLastFetchedAt($this->now); + }//end stampFetched() + + /** + * Current time in epoch milliseconds. + * + * @return int + */ + private static function nowMs(): int { + return (int)(microtime(as_float: true) * 1000); + }//end nowMs() +}//end class diff --git a/lib/Service/FeedRefreshService.php b/lib/Service/FeedRefreshService.php index a4dfeec89..6a2b9beaa 100644 --- a/lib/Service/FeedRefreshService.php +++ b/lib/Service/FeedRefreshService.php @@ -26,17 +26,13 @@ namespace OCA\LaunchPad\Service; -use DateTime; use OCA\LaunchPad\AppInfo\Application; -use OCA\LaunchPad\Db\FeedCache; -use OCA\LaunchPad\Db\FeedCacheMapper; +use OCA\LaunchPad\Db\WidgetPlacement; use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Kernel\Contracts\FeedRefreshServiceInterface; use OCP\Http\Client\IClientService; use OCP\IAppConfig; -use OCP\IConfig; use Psr\Log\LoggerInterface; -use RuntimeException; -use SimpleXMLElement; use Throwable; /** @@ -46,7 +42,7 @@ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) * @spec openspec/specs/background-job-feed-refresh/spec.md */ -class FeedRefreshService { +class FeedRefreshService implements FeedRefreshServiceInterface { /** * Maximum response body size accepted from a feed server (10 MB). * Larger responses are rejected with `lastFailureReason = "response @@ -112,22 +108,16 @@ class FeedRefreshService { /** * Constructor. * - * @param IClientService $clientService The HTTP client factory. - * @param IAppConfig $appConfig The app config reader. - * @param IConfig $config The system config reader. - * @param FeedCacheMapper $cacheMapper The feed-cache mapper. + * @param FeedRefreshSources $sources The HTTP client service, URL validator, feed cache mapper and config. + * @param IAppConfig $appConfig The app config reader. * @param WidgetPlacementMapper $placementMapper The widget-placement mapper. - * @param LoggerInterface $logger The diagnostic logger. - * @param UrlSafetyValidator $urlValidator SSRF guard (H3). + * @param LoggerInterface $logger The diagnostic logger. */ public function __construct( - private readonly IClientService $clientService, + private readonly FeedRefreshSources $sources, private readonly IAppConfig $appConfig, - private readonly IConfig $config, - private readonly FeedCacheMapper $cacheMapper, private readonly WidgetPlacementMapper $placementMapper, private readonly LoggerInterface $logger, - private readonly UrlSafetyValidator $urlValidator, ) { }//end __construct() @@ -150,9 +140,24 @@ public function __construct( */ public function discoverFeedUrls(): array { $rawUrls = []; + foreach ($this->findNewsPlacements() as $placement) { + array_push($rawUrls, ...self::configuredFeedUrls(placement: $placement)); + } + $unique = array_values(array: array_unique(array: $rawUrls)); + sort(array: $unique); + + return $unique; + }//end discoverFeedUrls() + + /** + * The news-widget placements, or none when they cannot be read. + * + * @return WidgetPlacement[] + */ + private function findNewsPlacements(): array { try { - $placements = $this->placementMapper->findByWidgetId( + return $this->placementMapper->findByWidgetId( widgetId: self::NEWS_WIDGET_ID ); } catch (Throwable $exception) { @@ -166,26 +171,31 @@ public function discoverFeedUrls(): array { ); return []; } + }//end findNewsPlacements() - foreach ($placements as $placement) { - $config = $placement->getStyleConfigArray(); - $urls = ($config['feedUrls'] ?? []); - if (is_array(value: $urls) === false) { - continue; - } + /** + * The non-empty string entries of a placement's `feedUrls` list. + * + * @param WidgetPlacement $placement A news-widget placement. + * + * @return string[] + */ + private static function configuredFeedUrls(WidgetPlacement $placement): array { + $config = $placement->getStyleConfigArray(); + $urls = ($config['feedUrls'] ?? []); + if (is_array(value: $urls) === false) { + return []; + } - foreach ($urls as $url) { - if (is_string(value: $url) === true && $url !== '') { - $rawUrls[] = $url; - } + $out = []; + foreach ($urls as $url) { + if (is_string(value: $url) === true && $url !== '') { + $out[] = $url; } } - $unique = array_values(array: array_unique(array: $rawUrls)); - sort(array: $unique); - - return $unique; - }//end discoverFeedUrls() + return $out; + }//end configuredFeedUrls() /** * Refresh a single feed URL — performs HTTP conditional GET, parses @@ -200,59 +210,81 @@ public function discoverFeedUrls(): array { * @spec openspec/specs/background-job-feed-refresh/spec.md */ public function refreshFeed(string $feedUrl): array { - $startedAt = (int)(microtime(as_float: true) * 1000); - $row = $this->cacheMapper->upsertUrl(feedUrl: $feedUrl); - $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); + $run = new FeedRefreshRun(mapper: $this->sources->cacheMapper, feedUrl: $feedUrl); - $rejected = $this->rejectBeforeFetch(row: $row, feedUrl: $feedUrl, now: $now, startedAt: $startedAt); - if ($rejected !== null) { - return $rejected; - } + return $this->rejectBeforeFetch(run: $run) ?? $this->fetchAndStore(run: $run); + }//end refreshFeed() + /** + * Conditional GET, post-fetch guards, parse and persist. + * + * @param FeedRefreshRun $run The refresh in progress. + * + * @return array{status: string, itemCount: int, durationMs: int} + */ + private function fetchAndStore(FeedRefreshRun $run): array { try { - $response = $this->doConditionalGet(row: $row, feedUrl: $feedUrl); + $response = (new ConditionalFeedRequest(sources: $this->sources, appConfig: $this->appConfig))->send( + row: $run->row, + feedUrl: $run->feedUrl + ); } catch (Throwable $exception) { - $row->setLastFetchedAt($now); + $run->stampFetched(); return $this->recordFailure( - row: $row, - reason: $this->classifyTransportError(exception: $exception), - startedAt: $startedAt + run: $run, + reason: $this->classifyTransportError(exception: $exception) ); } - $row->setLastFetchedAt($now); + $run->stampFetched(); - $early = $this->rejectResponse(row: $row, response: $response, startedAt: $startedAt); - if ($early !== null) { - return $early; - } + return $this->rejectResponse(run: $run, response: $response) ?? $this->storeItems(run: $run, response: $response); + }//end fetchAndStore() + /** + * Parse a fetched body and persist its items and validators, or record + * the parse failure. + * + * @param FeedRefreshRun $run The refresh in progress. + * @param array $response Envelope from `ConditionalFeedRequest::send()`. + * + * @return array{status: string, itemCount: int, durationMs: int} + */ + private function storeItems(FeedRefreshRun $run, array $response): array { try { - $items = $this->parseFeedBody( + $items = (new FeedItemParser())->parse( body: $response['body'], - feedUrl: $feedUrl + feedUrl: $run->feedUrl ); } catch (Throwable $exception) { return $this->recordFailure( - row: $row, - reason: 'parse error: ' . $exception->getMessage(), - startedAt: $startedAt + run: $run, + reason: 'parse error: ' . $exception->getMessage() ); } - $row->encodeItems(items: $items); - $row->setLastSuccessAt($now); - $row->setLastFailureReason(null); - $row->setEtag($response['etag']); - $row->setLastModified($response['lastModified']); - $this->cacheMapper->update(entity: $row); + $run->row->encodeItems(items: $items); + $this->markSucceeded(run: $run, response: $response); - return [ - 'status' => 'ok', - 'itemCount' => count(value: $items), - 'durationMs' => ((int)(microtime(as_float: true) * 1000) - $startedAt), - ]; - }//end refreshFeed() + return $run->result(status: 'ok', itemCount: count(value: $items)); + }//end storeItems() + + /** + * Mark the row successfully fetched: success time, no failure reason, + * the response's validators; then persist it. + * + * @param FeedRefreshRun $run The refresh in progress. + * @param array $response Envelope from `ConditionalFeedRequest::send()`. + * + * @return void + */ + private function markSucceeded(FeedRefreshRun $run, array $response): void { + $run->row->setLastSuccessAt($run->now); + $run->row->setLastFailureReason(null); + $run->row->setEtag($response['etag']); + $run->row->setLastModified($response['lastModified']); + $this->sources->cacheMapper->update(entity: $run->row); + }//end markSucceeded() /** * Persist a per-feed failure and build the `failed` result envelope. @@ -260,157 +292,164 @@ public function refreshFeed(string $feedUrl): array { * The reported item count is the one still cached from the previous * successful fetch — a failure never discards items (REQ-FRJ-006). * - * @param FeedCache $row The cache row being refreshed. + * @param FeedRefreshRun $run The refresh in progress. * @param string $reason Human-readable failure reason. - * @param int $startedAt Refresh start time in epoch milliseconds. * * @return array{status: string, itemCount: int, durationMs: int} * * @spec openspec/specs/background-job-feed-refresh/spec.md */ - private function recordFailure( - FeedCache $row, - string $reason, - int $startedAt, - ): array { - $row->setLastFailureReason($reason); - $this->cacheMapper->update(entity: $row); + private function recordFailure(FeedRefreshRun $run, string $reason): array { + $run->row->setLastFailureReason($reason); + $this->sources->cacheMapper->update(entity: $run->row); - return [ - 'status' => 'failed', - 'itemCount' => count(value: $row->decodeItems()), - 'durationMs' => ((int)(microtime(as_float: true) * 1000) - $startedAt), - ]; + return $run->result(status: 'failed', itemCount: $run->cachedItemCount()); }//end recordFailure() /** - * Pre-fetch guards: allow-list, SSRF safety and URL scheme. + * Pre-fetch guards, in order: allow-list, SSRF safety and URL scheme. * * Each rejection stamps `lastFetchedAt` and persists the row. An * allow-list miss reports `skipped`; SSRF and scheme report `failed`. * - * @param FeedCache $row The cache row being refreshed. - * @param string $feedUrl The feed URL under test. - * @param string $now Current timestamp, `Y-m-d H:i:s`. - * @param int $startedAt Refresh start time in epoch milliseconds. + * @param FeedRefreshRun $run The refresh in progress. * * @return array{status: string, itemCount: int, durationMs: int}|null * The early result envelope, or null when the URL may be fetched. * * @spec openspec/specs/background-job-feed-refresh/spec.md */ - private function rejectBeforeFetch( - FeedCache $row, - string $feedUrl, - string $now, - int $startedAt, - ): ?array { - // Allow-list pre-check (REQ-FRJ-011). - if ($this->isHostAllowed(feedUrl: $feedUrl) === false) { - $row->setLastFailureReason('host not in allow-list'); - $row->setLastFetchedAt($now); - $this->cacheMapper->update(entity: $row); - $this->logger->warning( - message: 'Feed host not in allow-list — skipping fetch', - context: [ - 'app' => Application::APP_ID, - 'feedUrl' => $feedUrl, - ] - ); - return [ - 'status' => 'skipped', - 'itemCount' => count(value: $row->decodeItems()), - 'durationMs' => ((int)(microtime(as_float: true) * 1000) - $startedAt), - ]; - } + private function rejectBeforeFetch(FeedRefreshRun $run): ?array { + return $this->rejectDisallowedHost(run: $run) + ?? $this->rejectUnsafeUrl(run: $run) + ?? $this->rejectInvalidScheme(run: $run); + }//end rejectBeforeFetch() - // H3: SSRF guard — reject URLs that resolve to private/reserved IP - // ranges and enforce HTTPS-only. Delegates to UrlSafetyValidator. - if ($this->urlValidator->isSafe(url: $feedUrl) === false) { - $row->setLastFetchedAt($now); - $result = $this->recordFailure( - row: $row, - reason: 'SSRF guard: private/reserved IP or non-HTTPS URL rejected', - startedAt: $startedAt - ); - $this->logger->warning( - message: 'Feed URL rejected by SSRF guard — private IP or non-HTTPS', - context: [ - 'app' => Application::APP_ID, - 'feedUrl' => $feedUrl, - ] - ); - return $result; + /** + * Allow-list pre-check (REQ-FRJ-011): a host outside the admin + * allow-list is skipped, not failed. + * + * @param FeedRefreshRun $run The refresh in progress. + * + * @return array{status: string, itemCount: int, durationMs: int}|null + */ + private function rejectDisallowedHost(FeedRefreshRun $run): ?array { + if ($this->isHostAllowed(feedUrl: $run->feedUrl) === true) { + return null; + } + + $run->row->setLastFailureReason('host not in allow-list'); + $run->stampFetched(); + $this->sources->cacheMapper->update(entity: $run->row); + $this->logger->warning( + message: 'Feed host not in allow-list — skipping fetch', + context: [ + 'app' => Application::APP_ID, + 'feedUrl' => $run->feedUrl, + ] + ); + + return $run->result(status: 'skipped', itemCount: $run->cachedItemCount()); + }//end rejectDisallowedHost() + + /** + * H3: SSRF guard — reject URLs that resolve to private/reserved IP + * ranges and enforce HTTPS-only. Delegates to UrlSafetyValidator. + * + * @param FeedRefreshRun $run The refresh in progress. + * + * @return array{status: string, itemCount: int, durationMs: int}|null + */ + private function rejectUnsafeUrl(FeedRefreshRun $run): ?array { + if ($this->sources->urlValidator->isSafe(url: $run->feedUrl) === true) { + return null; } - // Scheme guard — only HTTP/HTTPS (REQ-FRJ-010 scenario "Invalid - // feedUrl scheme rejected" applies at the controller layer; here - // we double-check at service layer for defence in depth). - $scheme = strtolower(string: (string)parse_url(url: $feedUrl, component: PHP_URL_SCHEME)); - if (in_array(needle: $scheme, haystack: ['http', 'https'], strict: true) === false) { - $row->setLastFetchedAt($now); - return $this->recordFailure( - row: $row, - reason: 'invalid scheme: ' . $scheme, - startedAt: $startedAt - ); + $run->stampFetched(); + $result = $this->recordFailure( + run: $run, + reason: 'SSRF guard: private/reserved IP or non-HTTPS URL rejected' + ); + $this->logger->warning( + message: 'Feed URL rejected by SSRF guard — private IP or non-HTTPS', + context: [ + 'app' => Application::APP_ID, + 'feedUrl' => $run->feedUrl, + ] + ); + + return $result; + }//end rejectUnsafeUrl() + + /** + * Scheme guard — only HTTP/HTTPS (REQ-FRJ-010 scenario "Invalid feedUrl + * scheme rejected" applies at the controller layer; here we + * double-check at service layer for defence in depth). + * + * @param FeedRefreshRun $run The refresh in progress. + * + * @return array{status: string, itemCount: int, durationMs: int}|null + */ + private function rejectInvalidScheme(FeedRefreshRun $run): ?array { + $scheme = strtolower(string: (string)parse_url(url: $run->feedUrl, component: PHP_URL_SCHEME)); + if (in_array(needle: $scheme, haystack: ['http', 'https'], strict: true) === true) { + return null; } - return null; - }//end rejectBeforeFetch() + $run->stampFetched(); + return $this->recordFailure(run: $run, reason: 'invalid scheme: ' . $scheme); + }//end rejectInvalidScheme() /** * Post-fetch guards: not-modified, non-2xx status and the size cap. * * Assumes the caller has already stamped `lastFetchedAt` on the row. * - * @param FeedCache $row The cache row being refreshed. - * @param array $response Envelope from `doConditionalGet()` with + * @param FeedRefreshRun $run The refresh in progress. + * @param array $response Envelope from `ConditionalFeedRequest::send()` with * keys `status`, `reason` and `body`. - * @param int $startedAt Refresh start time in epoch milliseconds. * * @return array{status: string, itemCount: int, durationMs: int}|null * The early result envelope, or null when the body should be parsed. * * @spec openspec/specs/background-job-feed-refresh/spec.md */ - private function rejectResponse( - FeedCache $row, - array $response, - int $startedAt, - ): ?array { - $statusCode = (int)$response['status']; - - if ($statusCode === 304) { + private function rejectResponse(FeedRefreshRun $run, array $response): ?array { + if ((int)$response['status'] === 304) { // Items untouched — only lastFetchedAt is updated // (REQ-FRJ-004 "items untouched, only lastFetchedAt updated"). - $this->cacheMapper->update(entity: $row); - return [ - 'status' => 'not-modified', - 'itemCount' => count(value: $row->decodeItems()), - 'durationMs' => ((int)(microtime(as_float: true) * 1000) - $startedAt), - ]; + $this->sources->cacheMapper->update(entity: $run->row); + return $run->result(status: 'not-modified', itemCount: $run->cachedItemCount()); + } + + $reason = self::responseFailureReason(response: $response); + if ($reason === null) { + return null; } + return $this->recordFailure(run: $run, reason: $reason); + }//end rejectResponse() + + /** + * Why a non-304 response cannot be parsed: a non-2xx status, or a body + * over the size cap (REQ-FRJ-005 design D3); null when it can. + * + * @param array $response Envelope from `ConditionalFeedRequest::send()`. + * + * @return string|null + */ + private static function responseFailureReason(array $response): ?string { + $statusCode = (int)$response['status']; if ($statusCode < 200 || $statusCode >= 300) { - return $this->recordFailure( - row: $row, - reason: $statusCode . ' ' . $response['reason'], - startedAt: $startedAt - ); + return $statusCode . ' ' . $response['reason']; } - // Size cap (REQ-FRJ-005 design D3). if (strlen(string: $response['body']) > self::MAX_RESPONSE_SIZE) { - return $this->recordFailure( - row: $row, - reason: 'response too large', - startedAt: $startedAt - ); + return 'response too large'; } return null; - }//end rejectResponse() + }//end responseFailureReason() /** * Refresh all discovered feed URLs (or a single one when @@ -436,34 +475,48 @@ public function refreshAll(?string $onlyUrl = null): array { message: 'No news widget placements found; nothing to refresh', context: ['app' => Application::APP_ID] ); - return [ - 'processedCount' => 0, - 'successCount' => 0, - 'failureCount' => 0, - 'durationMs' => ((int)(microtime(as_float: true) * 1000) - $startedAt), - ]; + return self::tickSummary(tally: ['processed' => 0, 'success' => 0, 'failure' => 0], startedAt: $startedAt); } - // Apply cursor — only relevant for the full-refresh path. - $startIndex = 0; - if ($onlyUrl === null) { - $startIndex = $this->resolveStartIndex(urls: $urls); + if ($onlyUrl !== null) { + return self::tickSummary(tally: $this->refreshBatch(urls: $urls, startIndex: 0), startedAt: $startedAt); } + return self::tickSummary(tally: $this->refreshFromCursor(urls: $urls), startedAt: $startedAt); + }//end refreshAll() + + /** + * Run one tick of the full sweep: start after the persisted cursor, + * then advance or clear it (REQ-FRJ-008). + * + * @param array $urls The sorted, deduplicated feed URL set. + * + * @return array{processed: int, success: int, failure: int} This tick's tally. + */ + private function refreshFromCursor(array $urls): array { + $startIndex = $this->resolveStartIndex(urls: $urls); $tally = $this->refreshBatch(urls: $urls, startIndex: $startIndex); + $this->persistCursor(urls: $urls, startIndex: $startIndex, processed: $tally['processed']); - // Cursor bookkeeping — full refresh only. - if ($onlyUrl === null) { - $this->persistCursor(urls: $urls, startIndex: $startIndex, processed: $tally['processed']); - } + return $tally; + }//end refreshFromCursor() + /** + * The refreshAll() summary of a tick's tally. + * + * @param array{processed: int, success: int, failure: int} $tally This tick's tally. + * @param int $startedAt Tick start time in epoch milliseconds. + * + * @return array{processedCount: int, successCount: int, failureCount: int, durationMs: int} + */ + private static function tickSummary(array $tally, int $startedAt): array { return [ 'processedCount' => $tally['processed'], 'successCount' => $tally['success'], 'failureCount' => $tally['failure'], 'durationMs' => ((int)(microtime(as_float: true) * 1000) - $startedAt), ]; - }//end refreshAll() + }//end tickSummary() /** * Resolve the batch start offset from the persisted cursor. @@ -511,57 +564,58 @@ private function resolveStartIndex(array $urls): int { * @spec openspec/specs/background-job-feed-refresh/spec.md */ private function refreshBatch(array $urls, int $startIndex): array { - $processed = 0; - $success = 0; - $failure = 0; + $tally = ['processed' => 0, 'success' => 0, 'failure' => 0]; $deadline = (microtime(as_float: true) + self::WALL_CLOCK_BUDGET); $batchLimit = ($startIndex + self::BATCH_SIZE); $urlCount = count(value: $urls); for ($index = $startIndex; $index < $urlCount; $index++) { - if ($index >= $batchLimit) { - break; - } - - if (microtime(as_float: true) >= $deadline) { + if ($index >= $batchLimit || microtime(as_float: true) >= $deadline) { break; } - $feedUrl = $urls[$index]; - try { - $result = $this->refreshFeed(feedUrl: $feedUrl); - $processed++; - if ($result['status'] === 'ok' || $result['status'] === 'not-modified') { - $success++; - } - - if ($result['status'] !== 'ok' && $result['status'] !== 'not-modified') { - $failure++; - } - } catch (Throwable $exception) { - // RefreshFeed swallows all per-feed exceptions — this is - // a defence-in-depth catch in case of a bug there. - $processed++; - $failure++; - $this->logger->error( - message: 'FeedRefreshService unexpected refreshFeed exception', - context: [ - 'app' => Application::APP_ID, - 'feedUrl' => $feedUrl, - 'exception' => $exception->getMessage(), - ] - ); - }//end try - }//end for + $outcome = $this->refreshCounted(feedUrl: $urls[$index]); + $tally['processed']++; + $tally[$outcome]++; + } - return [ - 'processed' => $processed, - 'success' => $success, - 'failure' => $failure, - ]; + return $tally; }//end refreshBatch() + /** + * Refresh one feed and say how the tally counts it: `ok` and + * `not-modified` are a `success`, anything else — including an + * exception escaping refreshFeed() — a `failure`. + * + * @param string $feedUrl The feed URL. + * + * @return string `success` or `failure`. + */ + private function refreshCounted(string $feedUrl): string { + try { + $result = $this->refreshFeed(feedUrl: $feedUrl); + } catch (Throwable $exception) { + // RefreshFeed swallows all per-feed exceptions — this is + // a defence-in-depth catch in case of a bug there. + $this->logger->error( + message: 'FeedRefreshService unexpected refreshFeed exception', + context: [ + 'app' => Application::APP_ID, + 'feedUrl' => $feedUrl, + 'exception' => $exception->getMessage(), + ] + ); + return 'failure'; + } + + if ($result['status'] === 'ok' || $result['status'] === 'not-modified') { + return 'success'; + } + + return 'failure'; + }//end refreshCounted() + /** * Advance or clear the sweep cursor after a tick. * @@ -604,377 +658,6 @@ private function persistCursor( } }//end persistCursor() - /** - * Perform the conditional HTTP GET. Returns a normalised response - * dict with keys: status, reason, body, etag, lastModified. - * - * @param FeedCache $row The cache row (for ETag/Last-Modified). - * @param string $feedUrl The feed URL. - * - * @return array{status: int, reason: string, body: string, etag: ?string, lastModified: ?string} - */ - private function doConditionalGet( - FeedCache $row, - string $feedUrl, - ): array { - $client = $this->clientService->newClient(); - - $headers = [ - 'User-Agent' => $this->buildUserAgent(), - 'Accept' => 'application/rss+xml, application/atom+xml, application/xml;q=0.9, */*;q=0.5', - ]; - - if ($row->getEtag() !== null && $row->getEtag() !== '') { - $headers['If-None-Match'] = (string)$row->getEtag(); - } - - if ($row->getLastModified() !== null && $row->getLastModified() !== '') { - $headers['If-Modified-Since'] = (string)$row->getLastModified(); - } - - $options = [ - 'connect_timeout' => self::CONNECT_TIMEOUT, - 'timeout' => self::REQUEST_TIMEOUT, - 'headers' => $headers, - // 304 must NOT be treated as an HTTP exception by Guzzle. - 'http_errors' => false, - // C5: disable automatic redirect following to prevent SSRF via - // open-redirect. Feed URLs are validated by urlValidator before - // the first request; a 302 to an internal host (e.g. cloud - // metadata endpoint) would bypass that guard. Mirror the explicit - // pattern in NewsWidgetService and CalendarWidgetService. - 'allow_redirects' => false, - ]; - - $proxy = (string)$this->config->getSystemValue('proxy', ''); - if ($proxy !== '') { - $options['proxy'] = $proxy; - $proxyAuth = (string)$this->config->getSystemValue('proxyuserpwd', ''); - if ($proxyAuth !== '') { - $options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode(string: $proxyAuth); - } - } - - $response = $client->get(uri: $feedUrl, options: $options); - - $headersOut = $response->getHeaders(); - - return [ - 'status' => (int)$response->getStatusCode(), - 'reason' => $this->extractReason(response: $response), - 'body' => (string)$response->getBody(), - 'etag' => $this->firstHeader(headers: $headersOut, name: 'ETag'), - 'lastModified' => $this->firstHeader(headers: $headersOut, name: 'Last-Modified'), - ]; - }//end doConditionalGet() - - /** - * Parse an RSS 2.0 / Atom 1.0 feed body and return normalised items - * sorted newest-first (REQ-FRJ-005). - * - * @param string $body The XML body. - * @param string $feedUrl The feed URL (for sourceUrl/sourceTitle). - * - * @return array> The normalised items. - * - * @throws RuntimeException When parsing fails. - */ - private function parseFeedBody(string $body, string $feedUrl): array { - $xml = $this->loadFeedXml(body: $body); - $sourceTitle = $this->extractFeedTitle(xml: $xml, feedUrl: $feedUrl); - $items = $this->extractItems(xml: $xml, feedUrl: $feedUrl, sourceTitle: $sourceTitle); - - // Sort newest-first by pubDate. - usort( - array: $items, - callback: static fn (array $left, array $right): int => self::compareByPubDate( - left: $left, - right: $right - ) - ); - - return $items; - }//end parseFeedBody() - - /** - * Parse the raw XML body, converting libxml's error channel into an - * exception. - * - * C2: LIBXML_NOENT is deliberately NOT passed — it resolves (not - * disables) entities, enabling XXE; LIBXML_NONET blocks external - * DTD/entity fetches. L1: LIBXML_NOCDATA is deliberately NOT passed — - * it folds CDATA into text nodes, masking downstream sanitisation. - * - * @param string $body The raw XML body. - * - * @return SimpleXMLElement The parsed document. - * - * @throws RuntimeException When the body is not well-formed XML; the - * message carries the first libxml error. - */ - private function loadFeedXml(string $body): SimpleXMLElement { - $previous = libxml_use_internal_errors(use_errors: true); - try { - $xml = simplexml_load_string( - data: $body, - class_name: 'SimpleXMLElement', - options: LIBXML_NONET - ); - if ($xml === false) { - $errors = libxml_get_errors(); - libxml_clear_errors(); - $message = 'malformed XML'; - if (isset($errors[0]) === true) { - $message = trim(string: $errors[0]->message); - } - - throw new RuntimeException(message: $message); - } - } finally { - libxml_clear_errors(); - libxml_use_internal_errors(use_errors: $previous); - }//end try - - return $xml; - }//end loadFeedXml() - - /** - * Collect the normalised entries from an RSS 2.0 or Atom 1.0 document. - * - * RSS is probed first; a document carrying neither shape yields an - * empty list, so an empty feed is not a parse failure. - * - * @param SimpleXMLElement $xml The parsed feed document. - * @param string $feedUrl The feed URL (for sourceUrl). - * @param string $sourceTitle Resolved channel/feed title. - * - * @return array> Normalised items, unsorted. - */ - private function extractItems( - SimpleXMLElement $xml, - string $feedUrl, - string $sourceTitle, - ): array { - $items = []; - - // RSS 2.0 — ... - if (isset($xml->channel) === true && isset($xml->channel->item) === true) { - foreach ($xml->channel->item as $item) { - $items[] = $this->normaliseRssItem( - item: $item, - feedUrl: $feedUrl, - sourceTitle: $sourceTitle - ); - } - } elseif (isset($xml->entry) === true) { - // Atom 1.0 — ... - foreach ($xml->entry as $entry) { - $items[] = $this->normaliseAtomEntry( - entry: $entry, - feedUrl: $feedUrl, - sourceTitle: $sourceTitle - ); - } - } - - return $items; - }//end extractItems() - - /** - * Newest-first comparator over the normalised `pubDate` field. - * - * A missing or unparseable date sorts as epoch 0, i.e. last. - * - * @param array $left Left-hand normalised item. - * @param array $right Right-hand normalised item. - * - * @return int Negative, zero or positive per the usort contract. - */ - private static function compareByPubDate(array $left, array $right): int { - $leftRaw = strtotime(datetime: (string)($left['pubDate'] ?? '')); - $rightRaw = strtotime(datetime: (string)($right['pubDate'] ?? '')); - $leftTs = 0; - if ($leftRaw !== false) { - $leftTs = $leftRaw; - } - - $rightTs = 0; - if ($rightRaw !== false) { - $rightTs = $rightRaw; - } - - return ($rightTs <=> $leftTs); - }//end compareByPubDate() - - /** - * Extract the channel-level title (RSS) or feed-level title (Atom), - * falling back to the URL hostname. - * - * @param SimpleXMLElement $xml The parsed feed. - * @param string $feedUrl The feed URL. - * - * @return string The source title. - */ - private function extractFeedTitle( - SimpleXMLElement $xml, - string $feedUrl, - ): string { - if (isset($xml->channel) === true && isset($xml->channel->title) === true) { - $title = trim(string: (string)$xml->channel->title); - if ($title !== '') { - return $title; - } - } - - if (isset($xml->title) === true) { - $title = trim(string: (string)$xml->title); - if ($title !== '') { - return $title; - } - } - - $host = (string)parse_url(url: $feedUrl, component: PHP_URL_HOST); - if ($host !== '') { - return $host; - } - - return $feedUrl; - }//end extractFeedTitle() - - /** - * Normalise a single RSS 2.0 item to the news-widget schema. - * - * @param SimpleXMLElement $item The RSS item element. - * @param string $feedUrl The feed URL. - * @param string $sourceTitle The channel title. - * - * @return array - */ - private function normaliseRssItem( - SimpleXMLElement $item, - string $feedUrl, - string $sourceTitle, - ): array { - $title = trim(string: (string)($item->title ?? '')); - $summary = trim(string: (string)($item->description ?? '')); - $link = trim(string: (string)($item->link ?? '')); - $pubDate = trim(string: (string)($item->pubDate ?? '')); - $guidValue = trim(string: (string)($item->guid ?? '')); - $thumbnail = null; - - if (isset($item->enclosure) === true) { - $attrs = $item->enclosure->attributes(); - if ($attrs !== null && isset($attrs['type']) === true) { - $type = (string)$attrs['type']; - if (str_starts_with(haystack: $type, needle: 'image/') === true) { - $thumbnail = (string)$attrs['url']; - } - } - } - - $guid = hash(algo: 'sha256', data: ($title . $pubDate . $feedUrl)); - if ($guidValue !== '') { - $guid = $guidValue; - } - - return [ - 'guid' => $guid, - 'title' => $title, - 'summary' => $summary, - 'link' => $link, - 'pubDate' => $pubDate, - 'sourceUrl' => $feedUrl, - 'sourceTitle' => $sourceTitle, - 'thumbnailUrl' => $thumbnail, - ]; - }//end normaliseRssItem() - - /** - * Normalise a single Atom 1.0 entry to the news-widget schema. - * - * @param SimpleXMLElement $entry The Atom entry element. - * @param string $feedUrl The feed URL. - * @param string $sourceTitle The feed title. - * - * @return array - */ - private function normaliseAtomEntry( - SimpleXMLElement $entry, - string $feedUrl, - string $sourceTitle, - ): array { - $title = trim(string: (string)($entry->title ?? '')); - $summary = trim(string: (string)($entry->summary ?? '')); - if ($summary === '') { - $summary = trim(string: (string)($entry->content ?? '')); - } - - $link = ''; - if (isset($entry->link) === true) { - foreach ($entry->link as $linkElement) { - $attrs = $linkElement->attributes(); - if ($attrs === null) { - continue; - } - - $rel = (string)($attrs['rel'] ?? 'alternate'); - $href = (string)($attrs['href'] ?? ''); - if ($rel === 'alternate' && $href !== '') { - $link = $href; - break; - } - } - } - - $pubDate = trim(string: (string)($entry->published ?? '')); - if ($pubDate === '') { - $pubDate = trim(string: (string)($entry->updated ?? '')); - } - - $idValue = trim(string: (string)($entry->id ?? '')); - $guid = hash(algo: 'sha256', data: ($title . $pubDate . $feedUrl)); - if ($idValue !== '') { - $guid = $idValue; - } - - return [ - 'guid' => $guid, - 'title' => $title, - 'summary' => $summary, - 'link' => $link, - 'pubDate' => $pubDate, - 'sourceUrl' => $feedUrl, - 'sourceTitle' => $sourceTitle, - 'thumbnailUrl' => null, - ]; - }//end normaliseAtomEntry() - - /** - * Build the User-Agent header per REQ-FRJ-012. - * - * @return string The User-Agent string. - */ - private function buildUserAgent(): string { - $appVersion = $this->appConfig->getValueString( - Application::APP_ID, - 'installed_version', - '1.0.0' - ); - $instanceUrl = (string)$this->config->getSystemValue( - 'overwrite.cli.url', - '' - ); - if ($instanceUrl === '') { - $instanceUrl = 'https://localhost'; - } - - return sprintf( - 'Mozilla/5.0 (compatible; LaunchPad/%s; +%s/apps/launchpad)', - $appVersion, - rtrim(string: $instanceUrl, characters: '/') - ); - }//end buildUserAgent() - /** * Whether the URL's host matches the admin allow-list. * @@ -1032,44 +715,4 @@ private function classifyTransportError(Throwable $exception): string { return 'transport error: ' . $message; }//end classifyTransportError() - /** - * Best-effort extraction of the HTTP reason phrase from a Guzzle - * (or NC-wrapped) response object. - * - * @param object $response The response object. - * - * @return string The reason phrase, or empty string when unknown. - */ - private function extractReason(object $response): string { - if (method_exists(object_or_class: $response, method: 'getReasonPhrase') === true) { - return (string)$response->getReasonPhrase(); - } - - return ''; - }//end extractReason() - - /** - * Pull the first value of a header from an associative - * `name => string|string[]` headers map. - * - * @param array> $headers The headers map. - * @param string $name The header name. - * - * @return string|null The first header value, or null when absent. - */ - private function firstHeader(array $headers, string $name): ?string { - foreach ($headers as $key => $value) { - if (strcasecmp(string1: $key, string2: $name) !== 0) { - continue; - } - - if (is_array(value: $value) === true) { - return ($value[0] ?? null); - } - - return (string)$value; - } - - return null; - }//end firstHeader() }//end class diff --git a/lib/Service/FeedRefreshSources.php b/lib/Service/FeedRefreshSources.php new file mode 100644 index 000000000..7b9c49035 --- /dev/null +++ b/lib/Service/FeedRefreshSources.php @@ -0,0 +1,51 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/widgets/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\FeedCacheMapper; +use OCP\Http\Client\IClientService; +use OCP\IConfig; + +/** + * What a feed refresh reads and keeps: the HTTP client, the URL check, the feed cache and config. + * + * @spec openspec/specs/widgets/spec.md + */ +class FeedRefreshSources { + /** + * Constructor. + * + * @param IClientService $clientService The HTTP client factory. + * @param UrlSafetyValidator $urlValidator SSRF guard (H3). + * @param FeedCacheMapper $cacheMapper The feed-cache mapper. + * @param IConfig $config The system config reader. + */ + public function __construct( + public readonly IClientService $clientService, + public readonly UrlSafetyValidator $urlValidator, + public readonly FeedCacheMapper $cacheMapper, + public readonly IConfig $config, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/FeedSource.php b/lib/Service/FeedSource.php new file mode 100644 index 000000000..4994ad6fd --- /dev/null +++ b/lib/Service/FeedSource.php @@ -0,0 +1,87 @@ + + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use SimpleXMLElement; + +/** + * Feed URL plus the display name stamped on every item parsed from it. + * + * @spec openspec/specs/news-widget/spec.md + */ +final class FeedSource { + /** + * Constructor + * + * @param string $url URL the payload was fetched from. + * @param string $title Display name for the feed. + */ + public function __construct( + public readonly string $url, + public readonly string $title, + ) { + }//end __construct() + + /** + * This source renamed after the `` child of a feed or channel + * node, or this source unchanged when the node has no title. + * + * @param SimpleXMLElement $node The Atom `<feed>` or RSS `<channel>` node. + * + * @return self + * + * @spec openspec/specs/news-widget/spec.md + */ + public function titledBy(SimpleXMLElement $node): self { + if (isset($node->title) === true) { + return new self(url: $this->url, title: (string)$node->title); + } + + return $this; + }//end titledBy() + + /** + * The canonical news item for fields read from one entry of this feed: + * the entry's fields in schema order, with this source's URL and title + * between `pubDate` and `thumbnailUrl`. + * + * @param array<string, string|null> $fields Final guid, title, summary, link, pubDate (strings) and + * thumbnailUrl (string or null). + * + * @return array<string, mixed> + * + * @spec openspec/specs/news-widget/spec.md + */ + public function item(array $fields): array { + return [ + 'guid' => $fields['guid'], + 'title' => $fields['title'], + 'summary' => $fields['summary'], + 'link' => $fields['link'], + 'pubDate' => $fields['pubDate'], + 'sourceUrl' => $this->url, + 'sourceTitle' => $this->title, + 'thumbnailUrl' => $fields['thumbnailUrl'], + ]; + }//end item() +}//end class diff --git a/lib/Service/FileService.php b/lib/Service/FileService.php index adaff40cc..a07570fef 100644 --- a/lib/Service/FileService.php +++ b/lib/Service/FileService.php @@ -39,6 +39,7 @@ use OCP\Files\File; use OCP\Files\Folder; use OCP\Files\IRootFolder; +use OCP\Files\Node; use OCP\Files\NotFoundException; use OCP\IURLGenerator; use Throwable; @@ -138,12 +139,12 @@ public function __construct( * * @param string $userId Owner of the target Files area. * @param string $filename Leaf filename — strictly validated. - * @param string $dir Target subdirectory inside the user's - * folder (default `/`). - * @param string $content Bytes to write (default empty). - * @param string $onExisting ON_EXISTING_REPLACE (default) or - * ON_EXISTING_REFUSE, which answers 409 - * instead of replacing a file (#712). + * @param array $write Optional `dir` (target subdirectory inside + * the user's folder; `/`), `content` (bytes to + * write; empty) and `onExisting` + * (ON_EXISTING_REPLACE, the default, or + * ON_EXISTING_REFUSE, which answers 409 instead + * of replacing a file, #712). * * @return array{status: string, fileId: int, url: string} * @@ -160,35 +161,23 @@ public function __construct( * * @spec openspec/specs/resource-uploads/spec.md */ - public function createFile( - string $userId, - string $filename, - string $dir = '/', - string $content = '', - string $onExisting = self::ON_EXISTING_REPLACE, - ): array { + public function createFile(string $userId, string $filename, array $write=[]): array { + $write += ['dir' => '/', 'content' => '', 'onExisting' => self::ON_EXISTING_REPLACE]; + $dir = $write['dir']; $this->assertValidFilename(filename: $filename); $this->assertValidDirectory(dir: $dir); $this->assertAllowedExtension(filename: $filename); - try { - $userFolder = $this->rootFolder->getUserFolder(userId: $userId); - } catch (Throwable $e) { - throw new StorageFailureException( - message: 'Failed to resolve user folder' - ); - } - $targetFolder = $this->resolveTargetFolder( - userFolder: $userFolder, + userFolder: $this->userFolder(userId: $userId), dir: $dir ); $file = $this->writeFile( folder: $targetFolder, filename: $filename, - content: $content, - onExisting: $onExisting + content: $write['content'], + onExisting: $write['onExisting'] ); $url = $this->urlGenerator->linkToRouteAbsolute( @@ -203,6 +192,25 @@ public function createFile( ]; }//end createFile() + /** + * Resolve a user's home folder. + * + * @param string $userId The owning NC user ID. + * + * @return Folder The user's home folder. + * + * @throws StorageFailureException When the folder cannot be resolved. + */ + private function userFolder(string $userId): Folder { + try { + return $this->rootFolder->getUserFolder(userId: $userId); + } catch (Throwable $e) { + throw new StorageFailureException( + message: 'Failed to resolve user folder' + ); + } + }//end userFolder() + /** * Returns the currently configured extension allow-list. * @@ -225,24 +233,7 @@ public function getAllowedExtensions(): array { return self::DEFAULT_ALLOWED_EXTENSIONS; } - $normalised = []; - foreach ($stored as $value) { - if (is_string($value) === false) { - continue; - } - - $token = strtolower(string: ltrim(string: trim(string: $value), characters: '.')); - if ($token === '') { - continue; - } - - if (preg_match(pattern: '/^[a-z0-9]+$/', subject: $token) !== 1) { - continue; - } - - $normalised[$token] = $token; - } - + $normalised = self::normaliseExtensions(values: $stored); if (count($normalised) === 0) { return self::DEFAULT_ALLOWED_EXTENSIONS; } @@ -267,23 +258,7 @@ public function getAllowedExtensions(): array { * @spec openspec/specs/resource-uploads/spec.md */ public function setAllowedExtensions(array $extensions): array { - $normalised = []; - foreach ($extensions as $value) { - if (is_string($value) === false) { - continue; - } - - $token = strtolower(string: ltrim(string: trim(string: $value), characters: '.')); - if ($token === '') { - continue; - } - - if (preg_match(pattern: '/^[a-z0-9]+$/', subject: $token) !== 1) { - continue; - } - - $normalised[$token] = $token; - } + $normalised = self::normaliseExtensions(values: $extensions); $stored = self::DEFAULT_ALLOWED_EXTENSIONS; if (count($normalised) > 0) { @@ -298,6 +273,47 @@ public function setAllowedExtensions(array $extensions): array { return $stored; }//end setAllowedExtensions() + /** + * Normalise a list of extensions: lowercase, trimmed, leading dots + * stripped, alphanumeric only, de-duplicated, in first-seen order. + * + * @param array $values The candidate extensions. + * + * @return array<string, string> The kept extensions, keyed by themselves. + */ + private static function normaliseExtensions(array $values): array { + $normalised = []; + foreach ($values as $value) { + $token = self::normaliseExtension(value: $value); + if ($token !== null) { + $normalised[$token] = $token; + } + } + + return $normalised; + }//end normaliseExtensions() + + /** + * Normalise one extension, null when it is not a string or not a + * non-empty alphanumeric token after normalisation. + * + * @param mixed $value The candidate extension. + * + * @return string|null The token, or null when dropped. + */ + private static function normaliseExtension(mixed $value): ?string { + if (is_string($value) === false) { + return null; + } + + $token = strtolower(string: ltrim(string: trim(string: $value), characters: '.')); + if ($token === '' || preg_match(pattern: '/^[a-z0-9]+$/', subject: $token) !== 1) { + return null; + } + + return $token; + }//end normaliseExtension() + /** * Reject filenames that fail any of the REQ-LBN-004 task 1.2 checks. * @@ -312,26 +328,32 @@ private function assertValidFilename(string $filename): void { throw new InvalidFilenameException(); } - if (str_contains(haystack: $filename, needle: "\0") === true) { + if (self::containsAny(haystack: $filename, needles: ["\0", '..', '/', '\\']) === true) { throw new InvalidFilenameException(); } - if (str_contains(haystack: $filename, needle: '..') === true) { - throw new InvalidFilenameException(); - } - - if (str_contains(haystack: $filename, needle: '/') === true) { + if (preg_match(pattern: self::FILENAME_PATTERN, subject: $filename) !== 1) { throw new InvalidFilenameException(); } + }//end assertValidFilename() - if (str_contains(haystack: $filename, needle: '\\') === true) { - throw new InvalidFilenameException(); + /** + * Whether a string contains any of the given substrings. + * + * @param string $haystack The string to search. + * @param array<string> $needles The substrings to look for. + * + * @return bool True when at least one occurs. + */ + private static function containsAny(string $haystack, array $needles): bool { + foreach ($needles as $needle) { + if (str_contains(haystack: $haystack, needle: $needle) === true) { + return true; + } } - if (preg_match(pattern: self::FILENAME_PATTERN, subject: $filename) !== 1) { - throw new InvalidFilenameException(); - } - }//end assertValidFilename() + return false; + }//end containsAny() /** * Reject directories that fail any of the REQ-LBN-004 task 1.3 checks. @@ -396,25 +418,26 @@ private function resolveTargetFolder(Folder $userFolder, string $dir): Folder { return $userFolder; } - try { - $node = $userFolder->get(path: $normalised); - if ($node instanceof Folder) { - return $node; - } + return $this->folderAt(userFolder: $userFolder, path: $normalised); + }//end resolveTargetFolder() - // A file (not a folder) already occupies the path. - throw new StorageFailureException( - message: 'Failed to resolve target folder' - ); + /** + * The folder at a subdirectory path, created when it is missing. + * + * @param Folder $userFolder Owner's Files-area root. + * @param string $path The normalised subdirectory path (not `/`). + * + * @return Folder The resolved (or freshly created) folder. + * + * @throws StorageFailureException When the folder cannot be + * resolved or created. + */ + private function folderAt(Folder $userFolder, string $path): Folder { + try { + return $this->existingFolder(userFolder: $userFolder, path: $path); } catch (NotFoundException $e) { // Auto-create missing subdirectory chain. - try { - return $userFolder->newFolder(path: $normalised); - } catch (Throwable $createError) { - throw new StorageFailureException( - message: 'Failed to create target folder' - ); - } + return $this->createFolder(userFolder: $userFolder, path: $path); } catch (StorageFailureException $e) { throw $e; } catch (Throwable $e) { @@ -422,7 +445,50 @@ private function resolveTargetFolder(Folder $userFolder, string $dir): Folder { message: 'Failed to resolve target folder' ); }//end try - }//end resolveTargetFolder() + }//end folderAt() + + /** + * The folder at a path inside the user's Files area. + * + * @param Folder $userFolder Owner's Files-area root. + * @param string $path The normalised subdirectory path. + * + * @return Folder The folder. + * + * @throws NotFoundException When nothing exists at the path. + * @throws StorageFailureException When a file occupies the path. + */ + private function existingFolder(Folder $userFolder, string $path): Folder { + $node = $userFolder->get(path: $path); + if ($node instanceof Folder) { + return $node; + } + + // A file (not a folder) already occupies the path. + throw new StorageFailureException( + message: 'Failed to resolve target folder' + ); + }//end existingFolder() + + /** + * Create a missing subdirectory chain inside the user's Files area. + * + * @param Folder $userFolder Owner's Files-area root. + * @param string $path The normalised subdirectory path. + * + * @return Folder The created folder. + * + * @throws StorageFailureException When the folder cannot be created. + */ + private function createFolder(Folder $userFolder, string $path): Folder { + try { + return $userFolder->newFolder(path: $path); + } catch (Throwable $createError) { + throw new StorageFailureException( + message: 'Failed to create target folder' + ); + } + }//end createFolder() /** * Write the file with overwrite-on-exists semantics @@ -441,20 +507,8 @@ private function resolveTargetFolder(Folder $userFolder, string $dir): Folder { private function writeFile(Folder $folder, string $filename, string $content, string $onExisting): File { try { if ($folder->nodeExists(path: $filename) === true) { - if ($onExisting === self::ON_EXISTING_REFUSE) { - throw new FileAlreadyExistsException(); - } - - $existing = $folder->get(path: $filename); - if ($existing instanceof File) { - $existing->putContent(data: $content); - return $existing; - } - - // A folder with the same name already exists. - throw new StorageFailureException( - message: 'Failed to write file' - ); + self::assertMayReplace(onExisting: $onExisting); + return self::overwrite(existing: $folder->get(path: $filename), content: $content); } // Folder::newFile() returns a File node — the contract is @@ -470,4 +524,41 @@ private function writeFile(Folder $folder, string $filename, string $content, st ); }//end try }//end writeFile() + + /** + * Refuse to replace an existing file when the caller asked for that. + * + * @param string $onExisting ON_EXISTING_REPLACE or ON_EXISTING_REFUSE. + * + * @return void + * + * @throws FileAlreadyExistsException When $onExisting is ON_EXISTING_REFUSE. + */ + private static function assertMayReplace(string $onExisting): void { + if ($onExisting === self::ON_EXISTING_REFUSE) { + throw new FileAlreadyExistsException(); + } + }//end assertMayReplace() + + /** + * Replace the contents of the existing file node at the target name. + * + * @param Node $existing The node at the target name. + * @param string $content Bytes to write. + * + * @return File The overwritten file. + * + * @throws StorageFailureException When a folder occupies the name. + */ + private static function overwrite(Node $existing, string $content): File { + if ($existing instanceof File) { + $existing->putContent(data: $content); + return $existing; + } + + // A folder with the same name already exists. + throw new StorageFailureException( + message: 'Failed to write file' + ); + }//end overwrite() }//end class diff --git a/lib/Service/FilesWidgetService.php b/lib/Service/FilesWidgetService.php index c83217ceb..d3fec2a2a 100644 --- a/lib/Service/FilesWidgetService.php +++ b/lib/Service/FilesWidgetService.php @@ -39,6 +39,7 @@ use OCA\LaunchPad\Exception\FolderNotFoundException; use OCA\LaunchPad\Exception\NoAccessException; use OCP\Constants; +use OCP\Files\Cache\IFileAccess; use OCP\Files\File; use OCP\Files\Folder; use OCP\Files\IRootFolder; @@ -58,6 +59,7 @@ * unavoidable for this * capability. * @spec openspec/specs/files-widget/spec.md + * @SuppressWarnings(PHPMD.ExcessiveClassLength) The listing, paths and previews of one widget belong together. */ class FilesWidgetService { /** @@ -95,36 +97,30 @@ class FilesWidgetService { * deep links into the Files app. * @param IPreview $previewManager Decides which files have a * previewable thumbnail. + * @param IFileAccess|null $fileAccess File cache lookup that tells a + * folder the viewer cannot see + * from one that is gone. */ public function __construct( private readonly IRootFolder $rootFolder, private readonly IURLGenerator $urlGenerator, private readonly IPreview $previewManager, + private readonly ?IFileAccess $fileAccess=null, ) { }//end __construct() /** - * List the contents of a folder for the given viewer. - * - * Resolves the configured folder (fileId preferred over path), - * applies the optional MIME filter, sorts the result, and slices - * out the requested page. Folders the viewer cannot read are - * skipped silently. + * List the visible contents of the placement's configured folder (or a + * sub-path of it) for the viewing user (REQ-FLS-003, REQ-FLS-004). * * @param string $userId Viewing user's UID. - * @param array $config Placement config — - * supports `fileId`, - * `folderPath`, - * `mimeTypeFilter`, `sortBy`, - * `sortDescending`. - * @param string|null $currentSubPath Optional sub-path relative to - * the configured folder (set - * when the user navigates into - * a subfolder). - * @param integer $limit Page size. - * @param string $cursor Opaque cursor (offset string) - * supplied by the previous - * response. + * @param array $config Placement config (`fileId`, `folderPath`, + * `mimeTypeFilter`, `sortBy`, `sortDescending`). + * @param array $page Optional `currentSubPath` (sub-path relative to the + * configured folder, set when the user navigates into + * a subfolder; null for the folder itself), `limit` + * (page size) and `cursor` (opaque offset string + * supplied by the previous response). * * @return array{items: list<array<string,mixed>>, nextCursor: ?string} * @@ -135,49 +131,64 @@ public function __construct( * * @spec openspec/specs/files-widget/spec.md */ - public function getContentsForPlacement( - string $userId, - array $config, - ?string $currentSubPath = null, - int $limit = self::DEFAULT_LIMIT, - string $cursor = '', - ): array { + public function getContentsForPlacement(string $userId, array $config, array $page=[]): array { + $page += ['currentSubPath' => null, 'limit' => self::DEFAULT_LIMIT, 'cursor' => '']; + $limit = (int)$page['limit']; + $cursor = (string)$page['cursor']; $rootFolder = $this->resolveConfiguredFolder(userId: $userId, config: $config); - - $target = $this->descendInto( - root: $rootFolder, - subPath: ($currentSubPath ?? '/') - ); + $target = $this->descendInto(root: $rootFolder, subPath: ($page['currentSubPath'] ?? '/')); if ($target->isReadable() === false) { throw new NoAccessException(); } - $children = $target->getDirectoryListing(); + $items = $this->listVisibleItems(folder: $target, config: $config, root: $rootFolder); + + return $this->paginate(items: $items, limit: $this->clampLimit(limit: $limit), cursor: $cursor); + }//end getContentsForPlacement() + /** + * The folder's children the viewer may read and the placement's MIME + * filter lets through (folders always pass), as metadata, sorted per + * the placement config. + * + * @param Folder $folder The readable folder being listed. + * @param array $config Placement config. + * @param Folder $root The widget's configured root folder. + * + * @return list<array<string,mixed>> The sorted item metadata. + */ + private function listVisibleItems(Folder $folder, array $config, Folder $root): array { + $children = $folder->getDirectoryListing(); $mimeFilter = $this->normaliseMimeFilter(filter: ($config['mimeTypeFilter'] ?? [])); $items = []; foreach ($children as $child) { - if ($child->isReadable() === false) { - continue; - } - - if ($child instanceof File && $this->matchesMimeFilter(node: $child, filter: $mimeFilter) === false) { - continue; + if ($this->isListed(node: $child, mimeFilter: $mimeFilter) === true) { + $items[] = $this->buildFileMetadata(node: $child, root: $root); } - - $items[] = $this->buildFileMetadata(node: $child); } - $items = $this->sortItems( + return $this->sortItems( items: $items, sortBy: ($config['sortBy'] ?? 'name'), sortDescending: (bool)($config['sortDescending'] ?? false) ); + }//end listVisibleItems() - return $this->paginate(items: $items, limit: $this->clampLimit(limit: $limit), cursor: $cursor); - }//end getContentsForPlacement() + /** + * Whether a child is listed: the viewer can read it, and it is a + * folder or a file that passes the MIME filter. + * + * @param Node $node The child node. + * @param list<string> $mimeFilter Normalised filter list. + * + * @return bool True when the child is listed. + */ + private function isListed(Node $node, array $mimeFilter): bool { + return $node->isReadable() === true + && (($node instanceof File) === false || $this->matchesMimeFilter(node: $node, filter: $mimeFilter) === true); + }//end isListed() /** * Upload one or more files into the configured folder (or a @@ -211,53 +222,122 @@ public function uploadFiles( } $root = $this->resolveConfiguredFolder(userId: $userId, config: $config); - $target = $this->descendInto(root: $root, subPath: ($currentSubPath ?? '/')); + $target = $this->writableFolder(root: $root, subPath: $currentSubPath); + + return $this->storeUploads(target: $this->uploadTarget(folder: $target, config: $config, root: $root), uploadedFiles: $uploadedFiles); + }//end uploadFiles() + /** + * The sub-path folder an upload writes into, refused when the viewer + * may not write to it. + * + * @param Folder $root The configured root folder. + * @param string|null $subPath Sub-path inside the configured folder. + * + * @return Folder The writable folder. + * + * @throws FolderNotFoundException When the sub-path does not resolve. + * @throws NoAccessException When the folder is not writable. + */ + private function writableFolder(Folder $root, ?string $subPath): Folder { + $target = $this->descendInto(root: $root, subPath: ($subPath ?? '/')); if ($target->isUpdateable() === false) { throw new NoAccessException(); } + return $target; + }//end writableFolder() + + /** + * The upload destination with the placement's MIME filter. + * + * @param Folder $folder The writable destination folder. + * @param array $config Placement config. + * @param Folder $root The widget's configured root folder. + * + * @return FilesWidgetUploadTarget The destination. + */ + private function uploadTarget(Folder $folder, array $config, Folder $root): FilesWidgetUploadTarget { // M3: normalise the placement's MIME type filter so we can gate // uploads against it (same filter already enforced on reads). $mimeFilter = $this->normaliseMimeFilter( filter: ($config['mimeTypeFilter'] ?? []) ); + return new FilesWidgetUploadTarget(folder: $folder, mimeFilter: $mimeFilter, root: $root); + }//end uploadTarget() + + /** + * Store each uploaded entry, collecting the stored files' metadata and + * the per-entry errors, in upload order. + * + * @param FilesWidgetUploadTarget $target The destination. + * @param array $uploadedFiles Normalised `$_FILES` entries. + * + * @return array{uploaded: list<array<string,mixed>>, errors: list<array<string,mixed>>} + */ + private function storeUploads(FilesWidgetUploadTarget $target, array $uploadedFiles): array { $uploaded = []; $errors = []; foreach ($uploadedFiles as $entry) { - $name = (string)$entry['name']; - - $rejection = $this->rejectUpload(entry: $entry, mimeFilter: $mimeFilter); - if ($rejection !== null) { - $errors[] = [ - 'name' => $name, - 'error' => $rejection, - ]; + $outcome = $this->storeUpload(target: $target, entry: $entry); + if (is_string($outcome) === true) { + $errors[] = ['name' => (string)$entry['name'], 'error' => $outcome]; continue; } - $safeName = $this->resolveAvailableName(folder: $target, desired: $name); - try { - $file = $this->streamToNewFile( - target: $target, - tmp: (string)$entry['tmp_name'], - safeName: $safeName - ); - $uploaded[] = $this->buildFileMetadata(node: $file); - } catch (Throwable $e) { - $errors[] = [ - 'name' => $name, - 'error' => 'storage_failed', - ]; - }//end try - }//end foreach + $uploaded[] = $outcome; + } - return [ - 'uploaded' => $uploaded, - 'errors' => $errors, - ]; - }//end uploadFiles() + return ['uploaded' => $uploaded, 'errors' => $errors]; + }//end storeUploads() + + /** + * Screen and store one uploaded entry under a collision-free name. + * + * @param FilesWidgetUploadTarget $target The destination. + * @param array $entry One normalised `$_FILES` entry. + * + * @return array<string,mixed>|string The stored file's metadata, or the + * client-facing error code. + */ + private function storeUpload(FilesWidgetUploadTarget $target, array $entry): array|string { + $rejection = $this->rejectUpload(entry: $entry, mimeFilter: $target->mimeFilter); + if ($rejection !== null) { + return $rejection; + } + + return $this->writeUpload(target: $target, entry: $entry); + }//end storeUpload() + + /** + * Write a screened upload under a collision-free name. + * + * @param FilesWidgetUploadTarget $target The destination. + * @param array $entry One screened `$_FILES` entry. + * + * @return array<string,mixed>|string The stored file's metadata, + * `insufficient_storage` or + * `storage_failed`. + */ + private function writeUpload(FilesWidgetUploadTarget $target, array $entry): array|string { + $free = $target->folder->getFreeSpace(); + if (is_numeric(value: $free) === true && $free >= 0 && (int)$entry['size'] > $free) { + return 'insufficient_storage'; + } + + $safeName = (new UploadNamePicker())->availableName(folder: $target->folder, desired: (string)$entry['name']); + try { + $file = $this->streamToNewFile( + target: $target->folder, + tmp: (string)$entry['tmp_name'], + safeName: $safeName + ); + return $this->buildFileMetadata(node: $file, root: $target->root); + } catch (Throwable $e) { + return 'storage_failed'; + } + }//end writeUpload() /** * Screen one uploaded entry before it is written to storage. @@ -277,27 +357,45 @@ public function uploadFiles( * @spec openspec/specs/files-widget/spec.md */ private function rejectUpload(array $entry, array $mimeFilter): ?string { - $name = (string)$entry['name']; - $tmp = (string)$entry['tmp_name']; - $error = (int)$entry['error']; - $size = (int)$entry['size']; - - if ($name === '' || $error !== UPLOAD_ERR_OK || $tmp === '') { - return 'upload_failed'; - } - - // M3: assert the temp file came through a real PHP upload to - // prevent local-file-inclusion via a crafted tmp_name. - if (is_uploaded_file(filename: $tmp) === false) { + if ($this->isGenuineUpload(entry: $entry) === false) { return 'upload_failed'; } // M3: reject files that exceed the hard size cap. - if ($size > self::MAX_UPLOAD_BYTES) { + if ((int)$entry['size'] > self::MAX_UPLOAD_BYTES) { return 'file_too_large'; } - // M3: honour the placement MIME type filter on writes. + return $this->rejectUploadType(tmp: (string)$entry['tmp_name'], mimeFilter: $mimeFilter); + }//end rejectUpload() + + /** + * Whether an entry is a complete upload: named, without a transport + * error, and with a temp file that came through a real PHP upload + * (M3: prevents local-file inclusion via a crafted `tmp_name`). + * + * @param array $entry One normalised `$_FILES` entry. + * + * @return bool True when the entry may be screened further. + */ + private function isGenuineUpload(array $entry): bool { + $tmp = (string)$entry['tmp_name']; + + return (string)$entry['name'] !== '' + && (int)$entry['error'] === UPLOAD_ERR_OK + && $tmp !== '' + && is_uploaded_file(filename: $tmp) === true; + }//end isGenuineUpload() + + /** + * M3: honour the placement MIME type filter on writes. + * + * @param string $tmp Path of the PHP temporary upload file. + * @param array $mimeFilter Normalised MIME filter; `[]` means allow all. + * + * @return string|null `file_type_not_allowed`, or null when allowed. + */ + private function rejectUploadType(string $tmp, array $mimeFilter): ?string { if ($mimeFilter === []) { return null; } @@ -308,7 +406,7 @@ private function rejectUpload(array $entry, array $mimeFilter): ?string { } return null; - }//end rejectUpload() + }//end rejectUploadType() /** * Stream a temporary upload into a new file under `$target`. @@ -340,10 +438,17 @@ private function streamToNewFile(Folder $target, string $tmp, string $safeName): throw new RuntimeException('Cannot open destination file'); } - stream_copy_to_stream(from: $handle, to: $outHandle); + $copied = stream_copy_to_stream(from: $handle, to: $outHandle); fclose($handle); fclose($outHandle); + // A quota or storage limit can cut the write short without an error: + // a partly written file is removed rather than listed. + if ($copied !== filesize(filename: $tmp)) { + $file->delete(); + throw new RuntimeException('Short write to destination file'); + } + return $file; }//end streamToNewFile() @@ -369,10 +474,29 @@ public function deleteFile(string $userId, array $config, int $fileId): array { } $root = $this->resolveConfiguredFolder(userId: $userId, config: $config); + $node = $this->userNodeById(userId: $userId, fileId: $fileId); + $this->assertDeletableWithin(root: $root, node: $node); + $this->deleteNode(node: $node); - // Find the file inside the configured folder by id. The id - // search is scoped to the user folder so we do not have to - // worry about cross-storage leaks. + return [ + 'status' => 'success', + 'fileId' => $fileId, + ]; + }//end deleteFile() + + /** + * Find a node by id inside the viewer's own Files area. The id + * search is scoped to the user folder so we do not have to worry + * about cross-storage leaks. + * + * @param string $userId Viewing user's UID. + * @param integer $fileId The file ID. + * + * @return Node The first match. + * + * @throws FolderNotFoundException When the lookup fails or finds nothing. + */ + private function userNodeById(string $userId, int $fileId): Node { try { $userFolder = $this->rootFolder->getUserFolder(userId: $userId); $matches = $userFolder->getById(id: $fileId); @@ -384,8 +508,21 @@ public function deleteFile(string $userId, array $config, int $fileId): array { throw new FolderNotFoundException(); } - $node = $matches[0]; + return $matches[0]; + }//end userNodeById() + /** + * Refuse a delete of a node outside the configured root folder or one + * the viewer may not delete. + * + * @param Folder $root The configured root folder. + * @param Node $node The node to delete. + * + * @return void + * + * @throws NoAccessException When the delete is not allowed. + */ + private function assertDeletableWithin(Folder $root, Node $node): void { // Defence-in-depth: the resolved node must live inside the // configured root folder. Otherwise a viewer with both // placements could pass an arbitrary fileId from a different @@ -397,30 +534,37 @@ public function deleteFile(string $userId, array $config, int $fileId): array { if ($node->isDeletable() === false) { throw new NoAccessException(); } + }//end assertDeletableWithin() + /** + * Delete a node, answering any storage failure as no access. + * + * @param Node $node The node to delete. + * + * @return void + * + * @throws NoAccessException When the storage refuses the delete. + */ + private function deleteNode(Node $node): void { try { $node->delete(); } catch (Throwable $e) { throw new NoAccessException(); } - - return [ - 'status' => 'success', - 'fileId' => $fileId, - ]; - }//end deleteFile() + }//end deleteNode() /** * Build the normalised JSON-friendly file metadata blob the * frontend renderer consumes (REQ-FLS-003). * - * @param Node $node A file or folder node. + * @param Node $node A file or folder node. + * @param Folder|null $root The widget's configured root folder, which `path` is relative to. * * @return array<string, mixed> * * @spec openspec/specs/files-widget/spec.md */ - public function buildFileMetadata(Node $node): array { + public function buildFileMetadata(Node $node, ?Folder $root=null): array { $isFolder = $node instanceof Folder; // Emit a preview URL for any file Nextcloud can render a thumbnail @@ -450,7 +594,7 @@ public function buildFileMetadata(Node $node): array { return [ 'fileId' => (int)$node->getId(), 'name' => $node->getName(), - 'path' => $node->getInternalPath(), + 'path' => $this->pathWithinRoot(node: $node, root: $root), 'mimeType' => $node->getMimetype(), 'size' => (int)$node->getSize(), 'modifiedAt' => $this->formatTimestamp(timestamp: $node->getMTime()), @@ -461,6 +605,24 @@ public function buildFileMetadata(Node $node): array { ]; }//end buildFileMetadata() + /** + * A node's path relative to the widget's root folder, with a leading + * slash; just `/<name>` when no root is known or the node is outside it. + * + * @param Node $node The listed node. + * @param Folder|null $root The widget's configured root folder. + * + * @return string The root-relative path. + */ + private function pathWithinRoot(Node $node, ?Folder $root): string { + $relative = $root?->getRelativePath(path: $node->getPath()); + if (is_string($relative) === true && $relative !== '') { + return $relative; + } + + return '/' . $node->getName(); + }//end pathWithinRoot() + /** * Resolve the placement's configured folder for the given user. * @@ -485,33 +647,92 @@ public function resolveConfiguredFolder(string $userId, array $config): Folder { throw new FolderNotFoundException(); } + $node = $this->configuredNode(userFolder: $userFolder, config: $config); + if ($node === null) { + if ($this->existsOutsideViewer(fileId: $this->extractFileId(config: $config)) === true) { + throw new NoAccessException(); + } + + throw new FolderNotFoundException(); + } + + if ($node->isReadable() === false) { + throw new NoAccessException(); + } + + return $node; + }//end resolveConfiguredFolder() + + /** + * Whether a folder id the viewer cannot resolve still exists in + * someone's files: then the viewer lacks access, rather than the + * folder being gone. A trashed folder counts as gone. + * + * @param integer|null $fileId The configured folder id. + * + * @return bool True when the folder exists outside the viewer's view. + * + * @spec openspec/specs/files-widget/spec.md + */ + private function existsOutsideViewer(?int $fileId): bool { + if ($fileId === null || $this->fileAccess === null) { + return false; + } + + try { + $entry = $this->fileAccess->getByFileId(fileId: $fileId); + } catch (Throwable $e) { + return false; + } + + return $entry !== null && str_starts_with(haystack: $entry->getPath(), needle: 'files/') === true; + }//end existsOutsideViewer() + + /** + * The folder a placement config names: by `fileId` first, else by + * `folderPath`, else — for an unconfigured placement — the home folder. + * + * @param Folder $userFolder The viewer's home folder. + * @param array $config Placement config. + * + * @return Folder|null The folder, or null when the configured one is gone. + */ + private function configuredNode(Folder $userFolder, array $config): ?Folder { $fileId = $this->extractFileId(config: $config); $folderPath = (string)($config['folderPath'] ?? ''); $node = $this->resolveByFileId(userFolder: $userFolder, fileId: $fileId); - if ($node === null && $folderPath !== '') { - $node = $this->resolveByPath(userFolder: $userFolder, folderPath: $folderPath); + if ($node !== null) { + return $node; + } + + if ($folderPath !== '') { + return $this->resolveByPath(userFolder: $userFolder, folderPath: $folderPath); } // Unconfigured placement (neither a fileId nor a folderPath set): // default to the user's home folder rather than erroring, so a // freshly-added or seeded files widget shows something usable until a - // folder is chosen. A configured-but-missing folder still falls - // through to the throw below. - if ($node === null && $fileId === null && $folderPath === '') { - $node = $userFolder; - } + // folder is chosen. A configured-but-missing folder still yields null. + return $this->homeWhenUnconfigured(userFolder: $userFolder, fileId: $fileId); + }//end configuredNode() - if ($node === null) { - throw new FolderNotFoundException(); - } - - if ($node->isReadable() === false) { - throw new NoAccessException(); + /** + * The home folder for a placement without a `fileId`; null for one + * whose `fileId` no longer resolves. + * + * @param Folder $userFolder The viewer's home folder. + * @param integer|null $fileId Configured file id, or null. + * + * @return Folder|null The home folder, or null. + */ + private function homeWhenUnconfigured(Folder $userFolder, ?int $fileId): ?Folder { + if ($fileId === null) { + return $userFolder; } - return $node; - }//end resolveConfiguredFolder() + return null; + }//end homeWhenUnconfigured() /** * Resolve the placement folder by its stable `fileId`. @@ -531,13 +752,23 @@ private function resolveByFileId(Folder $userFolder, ?int $fileId): ?Folder { return null; } - $matches = $userFolder->getById(id: $fileId); + return $this->firstFolder(matches: $userFolder->getById(id: $fileId)); + }//end resolveByFileId() + + /** + * The first match when it is a folder. + * + * @param array<int, Node> $matches The id lookup's matches. + * + * @return Folder|null The folder, or null. + */ + private function firstFolder(array $matches): ?Folder { if (count($matches) > 0 && $matches[0] instanceof Folder) { return $matches[0]; } return null; - }//end resolveByFileId() + }//end firstFolder() /** * Resolve the placement folder by its configured path. @@ -598,24 +829,34 @@ private function descendInto(Folder $root, string $subPath): Folder { throw new FolderNotFoundException(); } - try { - $node = $root->get(path: ltrim(string: $clean, characters: '/')); - } catch (NotFoundException $e) { - throw new FolderNotFoundException(); - } catch (NotPermittedException $e) { + $node = $this->nodeBelow(root: $root, path: ltrim(string: $clean, characters: '/')); + if (($node instanceof Folder) === false || $node->isReadable() === false) { throw new FolderNotFoundException(); } - if (($node instanceof Folder) === false) { - throw new FolderNotFoundException(); - } + return $node; + }//end descendInto() - if ($node->isReadable() === false) { + /** + * The node at a relative path below a folder; missing and not + * permitted paths are both answered as not found. + * + * @param Folder $root The folder to look below. + * @param string $path The relative path. + * + * @return Node The node. + * + * @throws FolderNotFoundException When the path is missing or not permitted. + */ + private function nodeBelow(Folder $root, string $path): Node { + try { + return $root->get(path: $path); + } catch (NotFoundException $e) { + throw new FolderNotFoundException(); + } catch (NotPermittedException $e) { throw new FolderNotFoundException(); } - - return $node; - }//end descendInto() + }//end nodeBelow() /** * Coerce the placement's `fileId` config value into a positive @@ -635,15 +876,28 @@ private function extractFileId(array $config): ?int { return $value; } - if (is_string($value) === true && ctype_digit($value) === true) { - $coerced = (int)$value; - if ($coerced > 0) { - return $coerced; - } + return $this->positiveIntFromDigits(value: $value); + }//end extractFileId() + + /** + * A positive integer from a digit-only string; null for anything else. + * + * @param mixed $value The candidate value. + * + * @return integer|null The integer, or null. + */ + private function positiveIntFromDigits(mixed $value): ?int { + if (is_string($value) === false || ctype_digit($value) === false) { + return null; + } + + $coerced = (int)$value; + if ($coerced > 0) { + return $coerced; } return null; - }//end extractFileId() + }//end positiveIntFromDigits() /** * Normalise the MIME filter array — drops non-strings and empty @@ -688,19 +942,7 @@ private function matchesMimeFilter(Node $node, array $filter): bool { return true; } - $mime = strtolower(string: (string)$node->getMimetype()); - foreach ($filter as $pattern) { - if (str_ends_with(haystack: $pattern, needle: '/*') === true) { - $prefix = substr(string: $pattern, offset: 0, length: -1); - if (str_starts_with(haystack: $mime, needle: $prefix) === true) { - return true; - } - } elseif ($pattern === $mime) { - return true; - } - } - - return false; + return $this->mimeMatchesFilter(mime: strtolower(string: (string)$node->getMimetype()), filter: $filter); }//end matchesMimeFilter() /** @@ -733,8 +975,8 @@ private function detectMimeType(string $path): string { * Test a raw MIME type string against a normalised filter list. * * Accepts both exact matches (`image/png`) and wildcard prefixes - * (`image/*`) — mirrors the read-path `matchesMimeFilter` but - * operates on a raw string rather than a Node. + * (`image/*`) — shared by the read-path `matchesMimeFilter` and the + * upload screening. * * @param string $mime The detected MIME type. * @param list<string> $filter Normalised filter list. @@ -747,12 +989,7 @@ private function mimeMatchesFilter(string $mime, array $filter): bool { } foreach ($filter as $pattern) { - if (str_ends_with(haystack: $pattern, needle: '/*') === true) { - $prefix = substr(string: $pattern, offset: 0, length: -1); - if (str_starts_with(haystack: $mime, needle: $prefix) === true) { - return true; - } - } elseif ($pattern === $mime) { + if (self::mimeMatchesPattern(mime: $mime, pattern: $pattern) === true) { return true; } } @@ -760,6 +997,23 @@ private function mimeMatchesFilter(string $mime, array $filter): bool { return false; }//end mimeMatchesFilter() + /** + * Test a MIME type against one filter entry: an exact type, or a + * `type/*` wildcard prefix. + * + * @param string $mime The MIME type. + * @param string $pattern One normalised filter entry. + * + * @return bool True on a match. + */ + private static function mimeMatchesPattern(string $mime, string $pattern): bool { + if (str_ends_with(haystack: $pattern, needle: '/*') === true) { + return str_starts_with(haystack: $mime, needle: substr(string: $pattern, offset: 0, length: -1)); + } + + return $pattern === $mime; + }//end mimeMatchesPattern() + /** * Sort an item list according to the placement config. * @@ -770,29 +1024,7 @@ private function mimeMatchesFilter(string $mime, array $filter): bool { * @return list<array<string,mixed>> */ private function sortItems(array $items, string $sortBy, bool $sortDescending): array { - $allowed = ['name', 'modified', 'size', 'type']; - if (in_array(needle: $sortBy, haystack: $allowed, strict: true) === false) { - $sortBy = 'name'; - } - - usort( - array: $items, - callback: function (array $a, array $b) use ($sortBy): int { - if ($sortBy === 'modified') { - return strcmp(string1: (string)($a['modifiedAt'] ?? ''), string2: (string)($b['modifiedAt'] ?? '')); - } - - if ($sortBy === 'size') { - return ((int)($a['size'] ?? 0)) <=> ((int)($b['size'] ?? 0)); - } - - if ($sortBy === 'type') { - return strcmp(string1: (string)($a['mimeType'] ?? ''), string2: (string)($b['mimeType'] ?? '')); - } - - return strnatcasecmp(string1: (string)($a['name'] ?? ''), string2: (string)($b['name'] ?? '')); - } - ); + usort(array: $items, callback: self::itemComparator(sortBy: $sortBy)); if ($sortDescending === true) { $items = array_reverse(array: $items); @@ -801,6 +1033,23 @@ private function sortItems(array $items, string $sortBy, bool $sortDescending): return array_values(array: $items); }//end sortItems() + /** + * The comparator for a sort field: `modified`, `size` or `type`, and + * natural case-insensitive name order for `name` or any other value. + * + * @param string $sortBy Sort field. + * + * @return callable(array<string,mixed>, array<string,mixed>): int The comparator. + */ + private static function itemComparator(string $sortBy): callable { + return match ($sortBy) { + 'modified' => static fn (array $a, array $b): int => strcmp(string1: (string)($a['modifiedAt'] ?? ''), string2: (string)($b['modifiedAt'] ?? '')), + 'size' => static fn (array $a, array $b): int => ((int)($a['size'] ?? 0)) <=> ((int)($b['size'] ?? 0)), + 'type' => static fn (array $a, array $b): int => strcmp(string1: (string)($a['mimeType'] ?? ''), string2: (string)($b['mimeType'] ?? '')), + default => static fn (array $a, array $b): int => strnatcasecmp(string1: (string)($a['name'] ?? ''), string2: (string)($b['name'] ?? '')), + }; + }//end itemComparator() + /** * Slice the sorted item list into a single page using an opaque * offset cursor (REQ-FLS-003 design D3). @@ -864,43 +1113,6 @@ private function formatTimestamp(int $timestamp): string { return gmdate(format: 'Y-m-d\\TH:i:s\\Z', timestamp: $timestamp); }//end formatTimestamp() - /** - * Find a free filename inside the target folder by appending - * `(1)`, `(2)` etc. when the desired name is taken (REQ-FLS-007). - * - * @param Folder $folder Target folder. - * @param string $desired Desired leaf name. - * - * @return string - */ - private function resolveAvailableName(Folder $folder, string $desired): string { - $sanitised = str_replace(search: ['/', '\\', "\0"], replace: '_', subject: $desired); - if ($sanitised === '' || $sanitised === '.' || $sanitised === '..') { - $sanitised = 'upload'; - } - - if ($folder->nodeExists(path: $sanitised) === false) { - return $sanitised; - } - - $extPos = strrpos(haystack: $sanitised, needle: '.'); - $base = $sanitised; - $ext = ''; - if ($extPos !== false && $extPos !== 0) { - $base = substr(string: $sanitised, offset: 0, length: $extPos); - $ext = substr(string: $sanitised, offset: $extPos); - } - - for ($i = 1; $i <= 999; $i++) { - $candidate = $base . ' (' . $i . ')' . $ext; - if ($folder->nodeExists(path: $candidate) === false) { - return $candidate; - } - } - - return $base . ' (' . uniqid() . ')' . $ext; - }//end resolveAvailableName() - /** * Walk parents of `$candidate` and return true when `$parent` is * one of them (or the same node). @@ -916,21 +1128,28 @@ private function isDescendantOf(Folder $parent, Node $candidate): bool { return true; } - $cursor = $candidate; - for ($depth = 0; $depth < 32; $depth++) { - try { - $next = $cursor->getParent(); - } catch (Throwable $e) { - return false; - } + return $this->hasAncestorWithId(node: $candidate, ancestorId: $parentId); + }//end isDescendantOf() - if ($next->getId() === $parentId) { - return true; + /** + * Walk at most 32 parents up from a node looking for an id; the walk + * stops at the user-folder root or on a parent that cannot be read. + * + * @param Node $node The node to start from. + * @param mixed $ancestorId The id to look for. + * + * @return bool True when a parent within reach has the id. + */ + private function hasAncestorWithId(Node $node, mixed $ancestorId): bool { + $cursor = $node; + for ($depth = 0; $depth < 32; $depth++) { + $next = $this->parentOf(node: $cursor); + if ($next === null || $next->getId() === $ancestorId) { + return $next !== null; } - // Reached the user-folder root without hitting `$parent`. - $nextPath = $next->getPath(); - if ($nextPath === '/' || $nextPath === '') { + // Reached the user-folder root without hitting the ancestor. + if (in_array(needle: $next->getPath(), haystack: ['/', ''], strict: true) === true) { return false; } @@ -938,5 +1157,20 @@ private function isDescendantOf(Folder $parent, Node $candidate): bool { } return false; - }//end isDescendantOf() + }//end hasAncestorWithId() + + /** + * A node's parent, null when it cannot be read. + * + * @param Node $node The node. + * + * @return Node|null The parent, or null. + */ + private function parentOf(Node $node): ?Node { + try { + return $node->getParent(); + } catch (Throwable $e) { + return null; + } + }//end parentOf() }//end class diff --git a/lib/Service/FilesWidgetUploadTarget.php b/lib/Service/FilesWidgetUploadTarget.php new file mode 100644 index 000000000..d8db9772a --- /dev/null +++ b/lib/Service/FilesWidgetUploadTarget.php @@ -0,0 +1,48 @@ +<?php + +/** + * FilesWidgetUploadTarget + * + * The folder a files-widget upload writes into and the placement's + * normalised MIME type filter the upload is screened against. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/files-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Files\Folder; + +/** + * The folder a files-widget upload writes into and its MIME filter. + * + * @spec openspec/specs/files-widget/spec.md + */ +final class FilesWidgetUploadTarget { + /** + * Constructor. + * + * @param Folder $folder The writable destination folder. + * @param list<string> $mimeFilter Normalised MIME filter; `[]` means allow all. + * @param Folder|null $root The widget's configured root folder. + */ + public function __construct( + public readonly Folder $folder, + public readonly array $mimeFilter, + public readonly ?Folder $root=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/FilterEventReportService.php b/lib/Service/FilterEventReportService.php new file mode 100644 index 000000000..d891fd262 --- /dev/null +++ b/lib/Service/FilterEventReportService.php @@ -0,0 +1,424 @@ +<?php + +/** + * FilterEventReportService + * + * The aggregate "most-used drill-down paths" report over a dashboard's + * `filter_event` objects (drill-down-cross-widget-filter REQ-CWF-010). The + * rows hold dimensions and operators, never filter values, and the report + * only counts paths, so it names no value either. + * + * Who sees what: the dashboard's owner and administrators get the paths of + * every user; anyone else who may view the dashboard gets only the paths of + * their own events; anyone else gets nothing (the dashboard reads as absent). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-010-telemetry-of-filter-usage-is-opt-in-and-aggregated + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\IGroupManager; +use Psr\Container\ContainerInterface; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Builds the drill-down path report of one dashboard. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-16 + */ +class FilterEventReportService { + + /** + * The register the events live in. + */ + public const REGISTER = 'launchpad'; + + /** + * The schema of the events. + */ + public const SCHEMA = 'filter_event'; + + /** + * The most events one report reads. + */ + public const MAX_EVENTS = 5000; + + /** + * The most paths one report returns. + */ + public const MAX_PATHS = 100; + + /** + * The separator between the steps of a path. + */ + public const STEP_SEPARATOR = ' → '; + + /** + * The OpenRegister service the events are read through. + */ + private const OBJECT_SERVICE = 'OCA\OpenRegister\Service\ObjectService'; + + /** + * Constructor. + * + * @param DashboardMapper $dashboardMapper Finds the dashboard. + * @param PermissionService $permissionService Whether the caller may view it. + * @param RoleService $roleService LaunchPad's admin role. + * @param IGroupManager $groupManager Nextcloud's admin group. + * @param ContainerInterface $container Loads OpenRegister's ObjectService lazily. + * @param LoggerInterface $logger Logs an unreadable register. + */ + public function __construct( + private readonly DashboardMapper $dashboardMapper, + private readonly PermissionService $permissionService, + private readonly RoleService $roleService, + private readonly IGroupManager $groupManager, + private readonly ContainerInterface $container, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * The report of one dashboard for one caller. + * + * @param string $dashboardUuid The dashboard's uuid. + * @param string $userId The caller. + * @param int $limit The most paths returned (1 to MAX_PATHS). + * + * @return array{dashboardId: string, scope: string, events: int, paths: list<array{path: string, count: int}>} + * + * @throws DoesNotExistException When the dashboard does not exist or the caller may not view it. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-16 + */ + public function report(string $dashboardUuid, string $userId, int $limit=20): array { + $dashboard = $this->dashboardMapper->findByUuid(uuid: $dashboardUuid); + + $everyone = $dashboard->getUserId() === $userId || $this->isAdmin(userId: $userId) === true; + if ($everyone === false + && $this->permissionService->canViewDashboard(userId: $userId, dashboardId: (int) $dashboard->getId()) === false + ) { + throw new DoesNotExistException('Dashboard not found'); + } + + $onlyUser = null; + $scope = 'all'; + if ($everyone === false) { + $onlyUser = $userId; + $scope = 'own'; + } + + $events = $this->loadEvents(dashboardUuid: $dashboardUuid, onlyUser: $onlyUser); + $paths = self::aggregatePaths(events: $events); + + return [ + 'dashboardId' => $dashboardUuid, + 'scope' => $scope, + 'events' => count($events), + 'paths' => array_slice($paths, 0, max(1, min(self::MAX_PATHS, $limit))), + ]; + }//end report() + + /** + * Count drill-down paths in a set of events. + * + * Per user, in time order, `apply` events extend the current path with + * the dimensions of their delta (a dimension already last on the path is + * not repeated); a `reset` ends the path; a `bookmark` ends it and starts + * a new one from the bookmarked dimensions. A `share` changes nothing. + * Every ended path with at least one step is counted once. The result is + * ordered by count, most used first, then by path. + * + * @param array<int, array<string, mixed>> $events The `filter_event` rows. + * + * @return list<array{path: string, count: int}> + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-16 + */ + public static function aggregatePaths(array $events): array { + $counts = []; + foreach (self::groupByUser(events: $events) as $userEvents) { + self::countUserPaths(counts: $counts, events: $userEvents); + } + + $paths = []; + foreach ($counts as $path => $count) { + $paths[] = ['path' => (string) $path, 'count' => $count]; + } + + usort( + $paths, + static fn (array $a, array $b): int => [$b['count'], $a['path']] <=> [$a['count'], $b['path']] + ); + + return $paths; + }//end aggregatePaths() + + /** + * The events with an event type, grouped by user. + * + * @param array<int, mixed> $events The `filter_event` rows. + * + * @return array<string, list<array<string, mixed>>> + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-16 + */ + private static function groupByUser(array $events): array { + $byUser = []; + foreach ($events as $event) { + if (is_array($event) === true && is_string($event['eventType'] ?? null) === true) { + $byUser[(string) ($event['userId'] ?? '')][] = $event; + } + } + + return $byUser; + }//end groupByUser() + + /** + * Count the paths of one user's events. + * + * @param array<string, int> $counts The counts so far, by path. + * @param list<array<string, mixed>> $events One user's events. + * + * @return void + */ + private static function countUserPaths(array &$counts, array $events): void { + usort( + $events, + static fn (array $a, array $b): int => strcmp((string) ($a['timestamp'] ?? ''), (string) ($b['timestamp'] ?? '')) + ); + + $steps = []; + foreach ($events as $event) { + $type = $event['eventType']; + if (in_array($type, ['reset', 'bookmark'], true) === true) { + self::countPath(counts: $counts, steps: $steps); + $steps = []; + } + + if (in_array($type, ['apply', 'bookmark'], true) === true) { + $steps = self::extend(steps: $steps, delta: $event['filterDelta'] ?? []); + } + } + + self::countPath(counts: $counts, steps: $steps); + }//end countUserPaths() + + /** + * The path's steps extended with a delta's dimensions. + * + * @param list<string> $steps The path so far. + * @param mixed $delta The event's `filterDelta`. + * + * @return list<string> + */ + private static function extend(array $steps, mixed $delta): array { + $items = []; + if (is_array($delta) === true) { + $items = $delta; + } + + foreach ($items as $item) { + $dimension = self::dimensionOf(item: $item); + if ($dimension !== null && end($steps) !== $dimension) { + $steps[] = $dimension; + } + } + + return $steps; + }//end extend() + + /** + * The dimension a delta item names. + * + * @param mixed $item One item of a `filterDelta`. + * + * @return string|null The dimension, or null when the item names none. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-16 + */ + private static function dimensionOf(mixed $item): ?string { + $dimension = null; + if (is_array($item) === true) { + $dimension = $item['dimension'] ?? null; + } + + if (is_string($dimension) === false || $dimension === '') { + return null; + } + + return $dimension; + }//end dimensionOf() + + /** + * Count one ended path. + * + * @param array<string, int> $counts The counts so far, by path. + * @param list<string> $steps The ended path. + * + * @return void + */ + private static function countPath(array &$counts, array $steps): void { + if ($steps === []) { + return; + } + + $path = implode(self::STEP_SEPARATOR, $steps); + $counts[$path] = ($counts[$path] ?? 0) + 1; + }//end countPath() + + /** + * Whether the caller is a Nextcloud or LaunchPad administrator. + * + * @param string $userId The caller. + * + * @return bool + */ + private function isAdmin(string $userId): bool { + return $this->groupManager->isAdmin(userId: $userId) === true + || $this->roleService->isAdmin(userId: $userId) === true; + }//end isAdmin() + + /** + * The dashboard's events, optionally of one user only. + * + * Access was decided by report() before this runs, so the read skips + * OpenRegister's per-object RBAC: an owner must count the events other + * users wrote. An unreadable register (OpenRegister off, schema not yet + * imported) reads as no events. + * + * @param string $dashboardUuid The dashboard's uuid. + * @param string|null $onlyUser Only this user's events, or everyone's. + * + * @return list<array<string, mixed>> + */ + private function loadEvents(string $dashboardUuid, ?string $onlyUser): array { + $filters = [ + 'register' => self::REGISTER, + 'schema' => self::SCHEMA, + 'dashboardId' => $dashboardUuid, + ]; + if ($onlyUser !== null) { + $filters['userId'] = $onlyUser; + } + + $events = []; + foreach ($this->findEvents(filters: $filters) as $item) { + $data = self::extractData(item: $item); + // The filter is the store's; the check here keeps the report + // right whatever the store matched. + if (self::belongs(data: $data, dashboardUuid: $dashboardUuid, onlyUser: $onlyUser) === true) { + $events[] = $data; + } + } + + return $events; + }//end loadEvents() + + /** + * The register's rows for a filter, or none when it cannot be read. + * + * @param array<string, string> $filters The OpenRegister filters. + * + * @return array<int|string, mixed> + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-16 + */ + private function findEvents(array $filters): array { + try { + $objectService = $this->container->get(self::OBJECT_SERVICE); + $results = $objectService->findAll( + config: ['filters' => $filters, 'limit' => self::MAX_EVENTS], + _rbac: false + ); + } catch (Throwable $e) { + $this->logger->warning( + message: 'LaunchPad: the filter events could not be read: ' . $e->getMessage(), + context: ['app' => 'launchpad'] + ); + return []; + } + + if (is_array($results) === false) { + return []; + } + + return $results; + }//end findEvents() + + /** + * Whether a row is of the dashboard, and of the one user when asked. + * + * @param array<string, mixed> $data The row. + * @param string $dashboardUuid The dashboard's uuid. + * @param string|null $onlyUser Only this user's rows, or everyone's. + * + * @return bool + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-16 + */ + private static function belongs(array $data, string $dashboardUuid, ?string $onlyUser): bool { + if (($data['dashboardId'] ?? null) !== $dashboardUuid) { + return false; + } + + return $onlyUser === null || ($data['userId'] ?? null) === $onlyUser; + }//end belongs() + + /** + * A plain array from one OpenRegister result. + * + * @param mixed $item An array, or an entity with getObject() or jsonSerialize(). + * + * @return array<string, mixed> + */ + private static function extractData(mixed $item): array { + $data = $item; + if (is_object($item) === true) { + $data = self::objectData(item: $item); + } + + if (is_array($data) === false) { + return []; + } + + return $data; + }//end extractData() + + /** + * The data of an OpenRegister entity. + * + * @param object $item An entity with getObject() or jsonSerialize(). + * + * @return mixed The data, or null for another object. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-16 + */ + private static function objectData(object $item): mixed { + if (method_exists($item, 'getObject') === true) { + return $item->getObject(); + } + + if (method_exists($item, 'jsonSerialize') === true) { + return $item->jsonSerialize(); + } + + return null; + }//end objectData() +}//end class diff --git a/lib/Service/FooterService.php b/lib/Service/FooterService.php index cca080cf4..ad5e82d3c 100644 --- a/lib/Service/FooterService.php +++ b/lib/Service/FooterService.php @@ -47,6 +47,7 @@ use OCA\LaunchPad\Db\AdminSetting; use OCA\LaunchPad\Db\AdminSettingMapper; use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Kernel\Contracts\FooterServiceInterface; /** * Resolve the instance footer + per-dashboard overrides. @@ -64,7 +65,15 @@ * REQ-FTR-005 and the test suite covers each branch. * @spec openspec/specs/dashboards/spec.md */ -class FooterService { +class FooterService implements FooterServiceInterface { + /** + * Colour fields of the settings patch and the setting each is stored in. + */ + private const COLOUR_SETTINGS = [ + 'footerBackgroundColor' => AdminSetting::KEY_FOOTER_BACKGROUND_COLOR, + 'footerTextColor' => AdminSetting::KEY_FOOTER_TEXT_COLOR, + ]; + /** * Maximum allowed footer HTML length (REQ-FTR-002 — 8 KB cap). * Inputs that exceed this MUST be rejected with HTTP 413 by the @@ -159,55 +168,71 @@ public function __construct( * @spec openspec/specs/footer-customization/spec.md */ public function getGlobalSettings(): array { - $enabled = (bool)$this->settingMapper->getValue( - key: AdminSetting::KEY_FOOTER_ENABLED, - default: false - ); + return [ + 'footerEnabled' => (bool)$this->settingMapper->getValue( + key: AdminSetting::KEY_FOOTER_ENABLED, + default: false + ), + 'footerHtml' => $this->storedFooterHtml(), + 'footerConfig' => $this->storedFooterConfig(), + 'footerBackgroundColor' => $this->storedColour(key: AdminSetting::KEY_FOOTER_BACKGROUND_COLOR), + 'footerTextColor' => $this->storedColour(key: AdminSetting::KEY_FOOTER_TEXT_COLOR), + ]; + }//end getGlobalSettings() + /** + * Read the stored footer HTML; anything but a string or a variant map + * reads as the empty string. + * + * @return string|array<string, string> The stored footer HTML. + */ + private function storedFooterHtml(): string|array { $html = $this->settingMapper->getValue( key: AdminSetting::KEY_FOOTER_HTML, default: '' ); if (is_string($html) === false && is_array($html) === false) { - $html = ''; + return ''; } + return $html; + }//end storedFooterHtml() + + /** + * Read the stored structured footer config; a non-array reads as empty. + * + * @return array<string, mixed> The stored config. + */ + private function storedFooterConfig(): array { $config = $this->settingMapper->getValue( key: AdminSetting::KEY_FOOTER_CONFIG, default: [] ); if (is_array($config) === false) { - $config = []; + return []; } - $backgroundColor = $this->settingMapper->getValue( - key: AdminSetting::KEY_FOOTER_BACKGROUND_COLOR, - default: null - ); + return $config; + }//end storedFooterConfig() - if ($backgroundColor !== null && is_string($backgroundColor) === false) { - $backgroundColor = null; - } - - $textColor = $this->settingMapper->getValue( - key: AdminSetting::KEY_FOOTER_TEXT_COLOR, - default: null - ); + /** + * Read one stored footer colour; a non-string reads as NULL. + * + * @param string $key The AdminSetting key of the colour. + * + * @return string|null The stored colour. + */ + private function storedColour(string $key): ?string { + $colour = $this->settingMapper->getValue(key: $key, default: null); - if ($textColor !== null && is_string($textColor) === false) { - $textColor = null; + if (is_string($colour) === false) { + return null; } - return [ - 'footerEnabled' => $enabled, - 'footerHtml' => $html, - 'footerConfig' => $config, - 'footerBackgroundColor' => $backgroundColor, - 'footerTextColor' => $textColor, - ]; - }//end getGlobalSettings() + return $colour; + }//end storedColour() /** * Patch one or more global footer settings (REQ-FTR-001..003, @@ -242,88 +267,147 @@ public function updateGlobalSettings(array $patch): void { ); } - if (array_key_exists(key: 'footerHtml', array: $patch) === true) { - $raw = $patch['footerHtml']; - $sanitised = ''; - if ($raw !== null && is_array($raw) === false && is_string($raw) === false) { - throw new InvalidArgumentException( - message: 'footerHtml must be a string, NULL, or a variant map' - ); - } - - if ($raw === null) { - $sanitised = ''; - } - - if (is_array($raw) === true) { - // Language-tagged variant map (REQ-FTR-007). Sanitise - // each variant independently. - $sanitised = []; - foreach ($raw as $locale => $variant) { - if (is_string($locale) === false || is_string($variant) === false) { - throw new InvalidArgumentException( - message: 'footerHtml language variants must be string→string' - ); - } - - $sanitised[$locale] = $this->sanitiseHtml(html: $variant); - } - } - - if (is_string($raw) === true) { - $sanitised = $this->sanitiseHtml(html: $raw); - }//end if + $this->storeFooterContent(patch: $patch); + $this->storeFooterColours(patch: $patch); + }//end updateGlobalSettings() + /** + * Store the footerHtml and footerConfig values of a patch, when present. + * + * @param array<string, mixed> $patch Partial payload from the HTTP body. + * + * @return void + * + * @throws InvalidArgumentException When a value fails validation. + */ + private function storeFooterContent(array $patch): void { + if (array_key_exists(key: 'footerHtml', array: $patch) === true) { $this->settingMapper->setSetting( key: AdminSetting::KEY_FOOTER_HTML, - value: $sanitised + value: $this->sanitiseFooterHtml(raw: $patch['footerHtml']) ); - }//end if + } if (array_key_exists(key: 'footerConfig', array: $patch) === true) { - $rawConfig = $patch['footerConfig']; - if ($rawConfig === null) { - $rawConfig = []; - } - - if (is_array($rawConfig) === false) { - throw new InvalidArgumentException( - message: 'footerConfig must be a JSON object' - ); - } - - $this->validateStructuredConfig(config: $rawConfig); - $this->settingMapper->setSetting( key: AdminSetting::KEY_FOOTER_CONFIG, - value: $rawConfig + value: $this->validatedFooterConfig(rawConfig: $patch['footerConfig']) ); } + }//end storeFooterContent() - if (array_key_exists(key: 'footerBackgroundColor', array: $patch) === true) { - $colour = $patch['footerBackgroundColor']; - if ($colour !== null) { - $this->assertHexColour(value: $colour, fieldName: 'footerBackgroundColor'); + /** + * Store the colour values of a patch, when present; NULL clears one. + * + * @param array<string, mixed> $patch Partial payload from the HTTP body. + * + * @return void + * + * @throws InvalidArgumentException When a colour is not a hex string. + */ + private function storeFooterColours(array $patch): void { + foreach (self::COLOUR_SETTINGS as $field => $key) { + if (array_key_exists(key: $field, array: $patch) === true) { + $colour = $patch[$field]; + if ($colour !== null) { + $this->assertHexColour(value: $colour, fieldName: $field); + } + + $this->settingMapper->setSetting(key: $key, value: $colour); } + } + }//end storeFooterColours() - $this->settingMapper->setSetting( - key: AdminSetting::KEY_FOOTER_BACKGROUND_COLOR, - value: $colour + /** + * Sanitise the footerHtml value of a patch: NULL clears it, a string is + * sanitised, a language-tagged variant map (REQ-FTR-007) is sanitised + * per variant. + * + * @param mixed $raw The footerHtml value. + * + * @return string|array<string, string> The value to store. + * + * @throws InvalidArgumentException When the value has the wrong shape. + */ + private function sanitiseFooterHtml(mixed $raw): string|array { + $this->assertFooterHtmlShape(raw: $raw); + + if (is_string($raw) === true) { + return $this->sanitiseHtml(html: $raw); + } + + if (is_array($raw) === true) { + return $this->sanitiseHtmlVariants(variants: $raw); + } + + return ''; + }//end sanitiseFooterHtml() + + /** + * Refuse a footerHtml value that is neither NULL, a string nor a map. + * + * @param mixed $raw The footerHtml value. + * + * @return void + * + * @throws InvalidArgumentException When the value has the wrong shape. + */ + private function assertFooterHtmlShape(mixed $raw): void { + if ($raw !== null && is_array($raw) === false && is_string($raw) === false) { + throw new InvalidArgumentException( + message: 'footerHtml must be a string, NULL, or a variant map' ); } + }//end assertFooterHtmlShape() - if (array_key_exists(key: 'footerTextColor', array: $patch) === true) { - $colour = $patch['footerTextColor']; - if ($colour !== null) { - $this->assertHexColour(value: $colour, fieldName: 'footerTextColor'); + /** + * Sanitise each variant of a language-tagged footer HTML map. + * + * @param array<mixed, mixed> $variants The locale => HTML map. + * + * @return array<string, string> The sanitised map. + * + * @throws InvalidArgumentException When a locale or variant is not a string. + */ + private function sanitiseHtmlVariants(array $variants): array { + $sanitised = []; + foreach ($variants as $locale => $variant) { + if (is_string($locale) === false || is_string($variant) === false) { + throw new InvalidArgumentException( + message: 'footerHtml language variants must be string→string' + ); } - $this->settingMapper->setSetting( - key: AdminSetting::KEY_FOOTER_TEXT_COLOR, - value: $colour + $sanitised[$locale] = $this->sanitiseHtml(html: $variant); + } + + return $sanitised; + }//end sanitiseHtmlVariants() + + /** + * Validate the footerConfig value of a patch; NULL stores an empty config. + * + * @param mixed $rawConfig The footerConfig value. + * + * @return array<string, mixed> The config to store. + * + * @throws InvalidArgumentException When it is not a valid config object. + */ + private function validatedFooterConfig(mixed $rawConfig): array { + if ($rawConfig === null) { + $rawConfig = []; + } + + if (is_array($rawConfig) === false) { + throw new InvalidArgumentException( + message: 'footerConfig must be a JSON object' ); } - }//end updateGlobalSettings() + + $this->validateStructuredConfig(config: $rawConfig); + + return $rawConfig; + }//end validatedFooterConfig() /** * Sanitise raw footer HTML against the allow-list (REQ-FTR-002, @@ -356,25 +440,44 @@ public function sanitiseHtml(string $html): string { return ''; } - // Strip <script>...</script> bodies entirely (content + tags). - $stripped = preg_replace( + $stripped = $this->stripScriptElements(html: $html); + if ($stripped === null) { + return ''; + } + + return $this->sanitiseTags(html: $stripped); + }//end sanitiseHtml() + + /** + * Strip <script>...</script> bodies entirely (content + tags). + * + * @param string $html The raw HTML input. + * + * @return string|null The HTML without script elements, NULL on a regex failure. + */ + private function stripScriptElements(string $html): ?string { + return preg_replace( pattern: '#<script\b[^>]*>.*?</script>#is', replacement: '', subject: $html ); + }//end stripScriptElements() - if ($stripped === null) { - return ''; - } - - // Replace any tag with a sanitised version or empty string. The - // callback inspects each match, validates the tag name, drops - // disallowed attributes, and force-tags external <a> elements - // with rel/target. + /** + * Replace any tag with a sanitised version or empty string. The + * callback inspects each match, validates the tag name, drops + * disallowed attributes, and force-tags external <a> elements + * with rel/target. + * + * @param string $html HTML without script elements. + * + * @return string The sanitised HTML, '' on a regex failure. + */ + private function sanitiseTags(string $html): string { $result = preg_replace_callback( pattern: '#<(/?)\s*([a-zA-Z0-9]+)\b([^>]*)>#s', callback: fn (array $matches): string => $this->sanitiseTag(matches: $matches), - subject: $stripped + subject: $html ); if ($result === null) { @@ -382,7 +485,7 @@ public function sanitiseHtml(string $html): string { } return $result; - }//end sanitiseHtml() + }//end sanitiseTags() /** * Rebuild one matched tag in its sanitised form (REQ-FTR-002). @@ -398,27 +501,47 @@ public function sanitiseHtml(string $html): string { * @return string The sanitised tag, or '' when the tag is disallowed. */ private function sanitiseTag(array $matches): string { - $closing = ($matches[1] === '/'); $tag = strtolower(string: $matches[2]); - $attrs = $matches[3]; if (in_array(needle: $tag, haystack: self::ALLOWED_TAGS, strict: true) === false) { return ''; } - if ($closing === true) { + if ($matches[1] === '/') { return '</' . $tag . '>'; } - $kept = $this->sanitiseTagAttributes(tag: $tag, attrs: $attrs); + $kept = $this->sanitiseTagAttributes(tag: $tag, attrs: $matches[3]); - $rendered = '<' . $tag; + return '<' . $tag . $this->renderAttributes(kept: $kept) . $this->externalLinkAttributes(tag: $tag, kept: $kept) . $this->tagEnd(tag: $tag); + }//end sanitiseTag() + + /** + * Render kept attributes as ` name="value"` pairs. + * + * @param array<string, string> $kept The escaped name => value pairs. + * + * @return string The rendered attributes. + */ + private function renderAttributes(array $kept): string { + $rendered = ''; foreach ($kept as $name => $value) { $rendered .= ' ' . $name . '="' . $value . '"'; } - // External <a> elements get rel + target automatically - // (REQ-FTR-002 external-link scenario). + return $rendered; + }//end renderAttributes() + + /** + * External <a> elements get rel + target automatically + * (REQ-FTR-002 external-link scenario). + * + * @param string $tag The lower-cased tag name. + * @param array<string, string> $kept The kept attributes. + * + * @return string The extra attributes, or ''. + */ + private function externalLinkAttributes(string $tag, array $kept): string { if ($tag === 'a' && isset($kept['href']) === true && preg_match( @@ -426,18 +549,26 @@ private function sanitiseTag(array $matches): string { subject: $kept['href'] ) === 1 ) { - $rendered .= ' rel="noopener noreferrer" target="_blank"'; + return ' rel="noopener noreferrer" target="_blank"'; } - $closingTag = '>'; + return ''; + }//end externalLinkAttributes() + + /** + * The end of an opening tag: self-closing for void elements. + * + * @param string $tag The lower-cased tag name. + * + * @return string The tag end. + */ + private function tagEnd(string $tag): string { if (in_array(needle: $tag, haystack: ['br', 'img'], strict: true) === true) { - $closingTag = ' />'; + return ' />'; } - $rendered .= $closingTag; - - return $rendered; - }//end sanitiseTag() + return '>'; + }//end tagEnd() /** * Extract the attributes of one opening tag that survive the @@ -454,12 +585,42 @@ private function sanitiseTag(array $matches): string { * @return array<string, string> The escaped name => value pairs to keep. */ private function sanitiseTagAttributes(string $tag, string $attrs): array { - $allowedAttrs = (self::ALLOWED_ATTRIBUTES[$tag] ?? []); + $allowedAttrs = $this->allowedAttributesFor(tag: $tag); $kept = []; if ($allowedAttrs === [] || trim(string: $attrs) === '') { return $kept; } + foreach ($this->parseAttributes(attrs: $attrs) as $attr) { + $value = $this->keptAttributeValue(attr: $attr, allowedAttrs: $allowedAttrs); + if ($value !== null) { + $kept[strtolower(string: $attr[1])] = $value; + } + } + + return $kept; + }//end sanitiseTagAttributes() + + /** + * The attribute names allow-listed for a tag. + * + * @param string $tag The lower-cased tag name. + * + * @return array<int, string> The allowed attribute names. + */ + private function allowedAttributesFor(string $tag): array { + return (self::ALLOWED_ATTRIBUTES[$tag] ?? []); + }//end allowedAttributesFor() + + /** + * Split a raw attribute blob into name/value matches. + * + * @param string $attrs The raw attribute blob from the source tag. + * + * @return array<int, array<int, string>> The matches, in source order. + */ + private function parseAttributes(string $attrs): array { + $found = []; if (preg_match_all( pattern: '#([a-zA-Z][a-zA-Z0-9_-]*)\s*=\s*("([^"]*)"|\'([^\']*)\'|([^\s"\'>]+))#', subject: $attrs, @@ -467,38 +628,59 @@ private function sanitiseTagAttributes(string $tag, string $attrs): array { flags: PREG_SET_ORDER ) > 0 ) { - foreach ($found as $attr) { - $name = strtolower(string: $attr[1]); - if (in_array(needle: $name, haystack: $allowedAttrs, strict: true) === false) { - continue; - } + return $found; + } - $value = ($attr[3] ?? ($attr[4] ?? ($attr[5] ?? ''))); - // Reject data: / javascript: schemes on URL - // attributes (href / src). The allow-list - // already restricted us to those names so a - // scheme check is enough. - if (preg_match( - pattern: '#^\s*(javascript|data|vbscript):#i', - subject: $value - ) === 1 - ) { - continue; - } + return []; + }//end parseAttributes() - // Strip any control char or newline; keep - // simple value escaping for HTML context. - $cleanValue = htmlspecialchars( - string: $value, - flags: (ENT_QUOTES | ENT_HTML5), - encoding: 'UTF-8' - ); - $kept[$name] = $cleanValue; - }//end foreach - }//end if + /** + * The escaped value of one attribute match, or NULL when the attribute + * is not allow-listed or carries a `javascript:` / `data:` / + * `vbscript:` scheme. + * + * @param array<int, string> $attr One attribute match. + * @param array<int, string> $allowedAttrs The names allowed on this tag. + * + * @return string|null The escaped value, or NULL to drop it. + */ + private function keptAttributeValue(array $attr, array $allowedAttrs): ?string { + if (in_array(needle: strtolower(string: $attr[1]), haystack: $allowedAttrs, strict: true) === false) { + return null; + } - return $kept; - }//end sanitiseTagAttributes() + $value = $this->attributeValue(attr: $attr); + // Reject data: / javascript: schemes on URL attributes (href / src). + // The allow-list already restricted us to those names so a scheme + // check is enough. + if (preg_match(pattern: '#^\s*(javascript|data|vbscript):#i', subject: $value) === 1) { + return null; + } + + // Keep simple value escaping for HTML context. + return htmlspecialchars( + string: $value, + flags: (ENT_QUOTES | ENT_HTML5), + encoding: 'UTF-8' + ); + }//end keptAttributeValue() + + /** + * The raw value of one attribute match, whichever quoting it used. + * + * @param array<int, string> $attr One attribute match. + * + * @return string The raw value. + */ + private function attributeValue(array $attr): string { + $raw = $attr[2]; + $quote = substr(string: $raw, offset: 0, length: 1); + if ($quote === '"' || $quote === "'") { + return substr(string: $raw, offset: 1, length: -1); + } + + return $raw; + }//end attributeValue() /** * Validate a structured-mode config payload against the documented @@ -514,47 +696,99 @@ private function sanitiseTagAttributes(string $tag, string $attrs): array { * @spec openspec/specs/footer-customization/spec.md */ public function validateStructuredConfig(array $config): void { + $this->assertKnownConfigKeys(config: $config); + + if (array_key_exists(key: 'layoutMode', array: $config) === true) { + $this->assertLayoutMode(mode: $config['layoutMode']); + } + + if (array_key_exists(key: 'links', array: $config) === true) { + $this->assertFooterLinks(links: $config['links']); + } + }//end validateStructuredConfig() + + /** + * Refuse a structured config that carries a key outside the schema; the + * refusal names the unknown key and every allowed one (REQ-FTR-003). + * + * @param array<string, mixed> $config The structured config. + * + * @return void + * + * @throws InvalidArgumentException On an unknown key. + */ + private function assertKnownConfigKeys(array $config): void { foreach (array_keys(array: $config) as $key) { if (in_array(needle: $key, haystack: self::STRUCTURED_CONFIG_KEYS, strict: true) === false) { throw new InvalidArgumentException( message: 'footerConfig contains unknown key: ' . (string)$key + . '; allowed keys: ' . implode(separator: ', ', array: self::STRUCTURED_CONFIG_KEYS) ); } } + }//end assertKnownConfigKeys() - if (array_key_exists(key: 'layoutMode', array: $config) === true) { - $mode = $config['layoutMode']; - if (is_string($mode) === false - || in_array(needle: $mode, haystack: self::LAYOUT_MODES, strict: true) === false - ) { - throw new InvalidArgumentException( - message: 'footerConfig.layoutMode must be one of: ' . implode(separator: ', ', array: self::LAYOUT_MODES) - ); - } + /** + * Refuse a layoutMode outside {@see self::LAYOUT_MODES}. + * + * @param mixed $mode The layoutMode value. + * + * @return void + * + * @throws InvalidArgumentException On an unknown layout mode. + */ + private function assertLayoutMode(mixed $mode): void { + if (is_string($mode) === false + || in_array(needle: $mode, haystack: self::LAYOUT_MODES, strict: true) === false + ) { + throw new InvalidArgumentException( + message: 'footerConfig.layoutMode must be one of: ' . implode(separator: ', ', array: self::LAYOUT_MODES) + ); } + }//end assertLayoutMode() - if (array_key_exists(key: 'links', array: $config) === true) { - $links = $config['links']; - if (is_array($links) === false) { + /** + * Refuse a links value that is not a list of {label, url} string pairs. + * + * @param mixed $links The links value. + * + * @return void + * + * @throws InvalidArgumentException On a malformed links value. + */ + private function assertFooterLinks(mixed $links): void { + if (is_array($links) === false) { + throw new InvalidArgumentException( + message: 'footerConfig.links must be an array' + ); + } + + foreach ($links as $entry) { + if ($this->isFooterLink(entry: $entry) === false) { throw new InvalidArgumentException( - message: 'footerConfig.links must be an array' + message: 'footerConfig.links entries must be {label, url} string pairs' ); } + } + }//end assertFooterLinks() - foreach ($links as $entry) { - if (is_array($entry) === false - || isset($entry['label']) === false - || isset($entry['url']) === false - || is_string($entry['label']) === false - || is_string($entry['url']) === false - ) { - throw new InvalidArgumentException( - message: 'footerConfig.links entries must be {label, url} string pairs' - ); - } - } - }//end if - }//end validateStructuredConfig() + /** + * Whether a links entry is a {label, url} string pair. + * + * @param mixed $entry One links entry. + * + * @return bool TRUE for a well-formed entry. + */ + private function isFooterLink(mixed $entry): bool { + if (is_array($entry) === false) { + return false; + } + + return isset($entry['label']) === true + && isset($entry['url']) === true + && is_string($entry['label']) === true + && is_string($entry['url']) === true; + }//end isFooterLink() /** * Resolve the effective footer payload for a single dashboard @@ -579,12 +813,7 @@ public function validateStructuredConfig(array $config): void { * @spec openspec/specs/footer-customization/spec.md */ public function resolveFooterForDashboard(Dashboard $dashboard): ?array { - $rawMode = $dashboard->getDashboardFooterMode(); - $mode = $rawMode; - if ($rawMode === '') { - $mode = Dashboard::FOOTER_MODE_INHERIT; - } - + $mode = $this->effectiveFooterMode(dashboard: $dashboard); if ($mode === Dashboard::FOOTER_MODE_HIDDEN) { return null; } @@ -592,53 +821,136 @@ public function resolveFooterForDashboard(Dashboard $dashboard): ?array { $globals = $this->getGlobalSettings(); if ($mode === Dashboard::FOOTER_MODE_CUSTOM) { - $html = $dashboard->getDashboardFooterHtml(); - if ($html === null || trim(string: $html) === '') { - return null; - } + return $this->customFooter(dashboard: $dashboard, globals: $globals); + } - return [ - 'mode' => Dashboard::FOOTER_MODE_CUSTOM, - 'html' => $html, - 'config' => null, - 'backgroundColor' => $globals['footerBackgroundColor'], - 'textColor' => $globals['footerTextColor'], - ]; + return $this->inheritedFooter(globals: $globals); + }//end resolveFooterForDashboard() + + /** + * The footer a page without an active dashboard shows: the global one, + * as an inherit dashboard would (REQ-FTR-004); NULL when it is off. + * + * @return array<string, mixed>|null The effective footer payload. + * + * @spec openspec/specs/footer-customization/spec.md + */ + public function resolveGlobalFooter(): ?array { + return $this->inheritedFooter(globals: $this->getGlobalSettings()); + }//end resolveGlobalFooter() + + /** + * The dashboard's footer mode; an empty mode means inherit. + * + * @param Dashboard $dashboard The dashboard. + * + * @return string The footer mode. + */ + private function effectiveFooterMode(Dashboard $dashboard): string { + $mode = $dashboard->getDashboardFooterMode(); + if ($mode === '') { + return Dashboard::FOOTER_MODE_INHERIT; } - // Inherit branch — must consult the global toggle. - if ($globals['footerEnabled'] !== true) { + return $mode; + }//end effectiveFooterMode() + + /** + * The payload for a dashboard with its own footer HTML; NULL when the + * HTML is blank. + * + * @param Dashboard $dashboard The dashboard. + * @param array<string, mixed> $globals The global footer settings. + * + * @return array<string, mixed>|null The effective footer payload. + */ + private function customFooter(Dashboard $dashboard, array $globals): ?array { + $html = $dashboard->getDashboardFooterHtml(); + if ($html === null || trim(string: $html) === '') { return null; } - $html = $globals['footerHtml']; - $htmlValue = null; - if (is_string($html) === true && $html !== '') { - $htmlValue = $html; - } elseif (is_array($html) === true && $html !== []) { - // Language-variant map — the frontend selects the locale. - $htmlValue = $html; - } + return $this->withFooterColours( + payload: ['mode' => Dashboard::FOOTER_MODE_CUSTOM, 'html' => $html, 'config' => null], + globals: $globals + ); + }//end customFooter() - $config = $globals['footerConfig']; - $configValue = null; - if (is_array($config) === true && $config !== []) { - $configValue = $config; + /** + * The payload for a dashboard that inherits the global footer; NULL + * when the global footer is off or has no content. + * + * @param array<string, mixed> $globals The global footer settings. + * + * @return array<string, mixed>|null The effective footer payload. + */ + private function inheritedFooter(array $globals): ?array { + if ($globals['footerEnabled'] !== true) { + return null; } + $htmlValue = $this->nonEmptyFooterHtml(html: $globals['footerHtml']); + $configValue = $this->nonEmptyFooterConfig(config: $globals['footerConfig']); if ($htmlValue === null && $configValue === null) { // Footer enabled but nothing configured — skip rendering. return null; } - return [ - 'mode' => 'global', - 'html' => $htmlValue, - 'config' => $configValue, - 'backgroundColor' => $globals['footerBackgroundColor'], - 'textColor' => $globals['footerTextColor'], - ]; - }//end resolveFooterForDashboard() + return $this->withFooterColours( + payload: ['mode' => 'global', 'html' => $htmlValue, 'config' => $configValue], + globals: $globals + ); + }//end inheritedFooter() + + /** + * The global footer HTML when it is a non-empty string or a non-empty + * language-variant map (the frontend selects the locale), else NULL. + * + * @param mixed $html The global footer HTML. + * + * @return string|array<string, string>|null The HTML to render. + */ + private function nonEmptyFooterHtml(mixed $html): string|array|null { + if (is_string($html) === true && $html !== '') { + return $html; + } + + if (is_array($html) === true && $html !== []) { + return $html; + } + + return null; + }//end nonEmptyFooterHtml() + + /** + * The global structured config when it is a non-empty array, else NULL. + * + * @param mixed $config The global structured config. + * + * @return array<string, mixed>|null The config to render. + */ + private function nonEmptyFooterConfig(mixed $config): ?array { + if (is_array($config) === true && $config !== []) { + return $config; + } + + return null; + }//end nonEmptyFooterConfig() + + /** + * Append the global background and text colours to a footer payload. + * + * @param array<string, mixed> $payload The mode, html and config. + * @param array<string, mixed> $globals The global footer settings. + * + * @return array<string, mixed> The complete footer payload. + */ + private function withFooterColours(array $payload, array $globals): array { + $payload['backgroundColor'] = $globals['footerBackgroundColor']; + $payload['textColor'] = $globals['footerTextColor']; + + return $payload; + }//end withFooterColours() /** * Validate that a value is a `#rgb` / `#rrggbb` hex colour string diff --git a/lib/Service/FreeSpotFinder.php b/lib/Service/FreeSpotFinder.php new file mode 100644 index 000000000..1f523e510 --- /dev/null +++ b/lib/Service/FreeSpotFinder.php @@ -0,0 +1,95 @@ +<?php + +/** + * FreeSpotFinder + * + * Finds where a new widget goes on a dashboard grid: the spot asked for when + * it is free, else the first free spot, scanning row by row from the top + * left, so a new widget never lands over another one + * (building-edit-a-dashboard-together, task 1.3). + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * @spec openspec/specs/dashboard-co-editing/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Places a rectangle on a grid without overlapping the occupied ones. + * + * @spec openspec/specs/dashboard-co-editing/spec.md + */ +class FreeSpotFinder { + + /** + * The spot for a widget of a given size. + * + * @param array<int,array{gridX:int,gridY:int,gridWidth:int,gridHeight:int}> $occupied The saved widgets. + * @param int $columns The grid's column count. + * @param array{gridX:int,gridY:int,gridWidth:int,gridHeight:int} $wanted The spot asked for and the size. + * + * @return array{gridX:int,gridY:int,gridWidth:int,gridHeight:int} The spot, the width kept within the grid. + * + * @spec openspec/specs/dashboard-co-editing/spec.md + */ + public function place(array $occupied, int $columns, array $wanted): array { + $columns = max(1, $columns); + $width = min(max(1, $wanted['gridWidth']), $columns); + $height = max(1, $wanted['gridHeight']); + $spot = ['gridX' => max(0, $wanted['gridX']), 'gridY' => max(0, $wanted['gridY']), 'gridWidth' => $width, 'gridHeight' => $height]; + + if ($spot['gridX'] + $width <= $columns && $this->isFree(occupied: $occupied, spot: $spot) === true) { + return $spot; + } + + $bottom = 0; + foreach ($occupied as $rect) { + $bottom = max($bottom, $rect['gridY'] + $rect['gridHeight']); + } + + // Every row up to the bottom of the lowest widget is tried; the row + // just below it is always free. + for ($y = 0; $y <= $bottom; $y++) { + for ($x = 0; $x + $width <= $columns; $x++) { + $candidate = ['gridX' => $x, 'gridY' => $y, 'gridWidth' => $width, 'gridHeight' => $height]; + if ($this->isFree(occupied: $occupied, spot: $candidate) === true) { + return $candidate; + } + } + } + + return ['gridX' => 0, 'gridY' => $bottom, 'gridWidth' => $width, 'gridHeight' => $height]; + }//end place() + + /** + * Whether a spot overlaps none of the occupied rectangles. + * + * @param array<int,array{gridX:int,gridY:int,gridWidth:int,gridHeight:int}> $occupied The saved widgets. + * @param array{gridX:int,gridY:int,gridWidth:int,gridHeight:int} $spot The spot. + * + * @return bool + */ + private function isFree(array $occupied, array $spot): bool { + foreach ($occupied as $rect) { + if ($spot['gridX'] < $rect['gridX'] + $rect['gridWidth'] + && $rect['gridX'] < $spot['gridX'] + $spot['gridWidth'] + && $spot['gridY'] < $rect['gridY'] + $rect['gridHeight'] + && $rect['gridY'] < $spot['gridY'] + $spot['gridHeight'] + ) { + return false; + } + } + + return true; + }//end isFree() +}//end class diff --git a/lib/Service/GroupDashboardCreation.php b/lib/Service/GroupDashboardCreation.php new file mode 100644 index 000000000..0903a9b15 --- /dev/null +++ b/lib/Service/GroupDashboardCreation.php @@ -0,0 +1,75 @@ +<?php + +/** + * GroupDashboardCreation + * + * Who may create a group dashboard for a group (REQ-DASH-014). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\RoleAssignment; + +/** + * An Admin (a Nextcloud administrator is one) may create a group dashboard + * for any group, an Editor for a group they belong to. The default group + * means everyone, so an Editor cannot aim a dashboard at it. + * + * @spec openspec/specs/dashboards/spec.md + */ +class GroupDashboardCreation { + /** + * Constructor. + * + * @param RoleService $roles Resolves the effective LaunchPad role. + * @param AdminTemplateService $templates Resolves a user's groups (REQ-TMPL-013). + */ + public function __construct( + private readonly RoleService $roles, + private readonly AdminTemplateService $templates, + ) { + }//end __construct() + + /** + * Whether a user may create a group dashboard for a group. + * + * @param string $userId The user ID. + * @param string $groupId The group the dashboard is for. + * + * @return bool Whether the user may create it. + * + * @spec openspec/specs/dashboards/spec.md + */ + public function allows(string $userId, string $groupId): bool { + $role = $this->roles->getEffectiveRole(userId: $userId); + if ($role === RoleAssignment::ROLE_ADMIN) { + return true; + } + + if ($role !== RoleAssignment::ROLE_EDITOR || $groupId === Dashboard::DEFAULT_GROUP_ID) { + return false; + } + + return in_array( + needle: $groupId, + haystack: $this->templates->getUserGroupIdsFor(userId: $userId), + strict: true + ); + }//end allows() +}//end class diff --git a/lib/Service/HealthPingService.php b/lib/Service/HealthPingService.php index 623a3ec20..bb23fd1d8 100644 --- a/lib/Service/HealthPingService.php +++ b/lib/Service/HealthPingService.php @@ -18,13 +18,15 @@ * reading exists (REQ-HPING-002 "Allow-list enforced at ping time"). * - When the request IS attempted, a transport failure (timeout, * connection refused) or a response whose status does not match - * `expectedStatus` is itself a DEFINITIVE, cacheable `offline` reading - * (REQ-HPING-002 "Offline on failure or unexpected status") — this is - * distinct from the allow-list-refusal case above, which never - * produces a reading at all. - * - Results are cached in `ICache`, keyed on placement id, with a TTL - * equal to the tile's configured interval (default 60s, clamped to a - * 15s minimum). + * `expectedStatus` is a FAILED ping. A failed ping serves the + * last-known badge marked `stale`; only after + * `healthping_offline_after_failures` consecutive failed pings (default + * 3) is the badge classified `offline` (REQ-HPING-002, REQ-HPING-003). + * A successful ping resets the count. + * - Results are cached in `ICache`, keyed on placement id. The tile's + * interval (default 60s, clamped to a 15s minimum) decides when the + * next ping is due; the entry itself is kept for a day so the + * last-known badge and the failure count outlive the interval. * * @category Service * @package OCA\LaunchPad\Service @@ -47,11 +49,8 @@ use OCA\LaunchPad\Db\WidgetPlacement; use OCA\LaunchPad\Db\WidgetPlacementMapper; use OCA\LaunchPad\Service\Connection\ConnectionReporter; -use OCP\Http\Client\IClientService; use OCP\IAppConfig; use OCP\ICache; -use OCP\ICacheFactory; -use Psr\Log\LoggerInterface; use Throwable; /** @@ -65,6 +64,7 @@ * @spec openspec/specs/service-health-ping/spec.md */ class HealthPingService { + use ReadsJsonCache; /** * Default cache TTL / ping interval in seconds when a tile has no (or @@ -137,6 +137,30 @@ class HealthPingService { */ public const DEFAULT_LATENCY_THRESHOLD_MS = 2000; + /** + * IAppConfig key — the number of consecutive failed pings after which + * a badge is classified `offline`; fewer failed pings serve the + * last-known badge marked stale (REQ-HPING-002). + * + * @var string + */ + public const CONFIG_KEY_OFFLINE_AFTER_FAILURES = 'healthping_offline_after_failures'; + + /** + * Default number of consecutive failed pings before `offline`. + * + * @var integer + */ + public const DEFAULT_OFFLINE_AFTER_FAILURES = 3; + + /** + * How long a cached badge is kept, in seconds, independent of the + * ping interval. + * + * @var integer + */ + public const CACHE_TTL_SECONDS = 86400; + /** * Badge states, in priority order — the only three values REQ-HPING-002 * and REQ-HPING-004 recognise. @@ -155,21 +179,17 @@ class HealthPingService { /** * Constructor. * - * @param IClientService $clientService HTTP client factory for the health-check request. - * @param ICacheFactory $cacheFactory Backing factory for the distributed badge cache. - * @param IAppConfig $appConfig Admin config: allow-listed hosts, latency threshold. - * @param WidgetPlacementMapper $placementMapper Resolves placements by id / enumerates all placements. - * @param LoggerInterface $logger PSR logger. + * @param PingTransport $transport The HTTP client and cache factory. + * @param PingSettings $settings The app config and logger. + * @param WidgetPlacementMapper $placementMapper Resolves placements by id / enumerates all placements. * @param ConnectionReporter|null $connectionReporter Tells integriq what a ping met, or nothing when absent. * * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md#requirement-req-lp-conn-003-launchpad-reports-what-its-outbound-calls-met */ public function __construct( - private readonly IClientService $clientService, - private readonly ICacheFactory $cacheFactory, - private readonly IAppConfig $appConfig, + private readonly PingTransport $transport, + private readonly PingSettings $settings, private readonly WidgetPlacementMapper $placementMapper, - private readonly LoggerInterface $logger, private readonly ?ConnectionReporter $connectionReporter = null, ) { }//end __construct() @@ -219,39 +239,117 @@ private function resolveForConfig(int $placementId, array $config): array { $cache = $this->getCache(); $cached = $this->readCache(cache: $cache, cacheKey: $cacheKey); - if ($cached !== null) { - $age = (time() - (int)($cached['checkedAtTs'] ?? 0)); - if ($age >= 0 && $age < $interval) { - return $this->publicShape(reading: $cached, stale: false); - } + if ($cached !== null && $this->isFresh(reading: $cached, interval: $interval) === true) { + return $this->publicShape(reading: $cached, stale: ($cached['stale'] ?? false) === true); } - $fresh = $this->attemptPing(config: $config); + $attempt = $this->attemptPing(config: $config); - if ($fresh !== null) { - $fresh['checkedAtTs'] = time(); - if ($cache !== null) { - $cache->set(key: $cacheKey, value: json_encode($fresh), ttl: $interval); - } + if ($attempt === null) { + // Allow-list refused the ping — REQ-HPING-002 "no ping was + // performed rather than a false 'up' state": degrade to the + // last-known reading rather than fabricate a new one. + return $this->publicShape(reading: $cached ?? [], stale: true); + } - return $this->publicShape(reading: $fresh, stale: false); + $reading = $this->nextReading(previous: $cached, attempt: $attempt); + $cache?->set(key: $cacheKey, value: json_encode($reading), ttl: self::CACHE_TTL_SECONDS); + + return $this->publicShape(reading: $reading, stale: $reading['stale']); + }//end resolveForConfig() + + /** + * The reading after a ping attempt. A successful ping is a fresh + * reading and resets the failure count. A failed ping keeps the + * last-known reading, marked stale, until the configured number of + * consecutive failed pings is reached; then it is an `offline` reading + * (REQ-HPING-002, REQ-HPING-003 "Stale fallback on refresh failure"). + * + * @param array<string,mixed>|null $previous The cached reading, or null. + * @param array<string,mixed> $attempt `{state, latencyMs, failed}` from {@see self::attemptPing()}. + * + * @return array{state: string|null, latencyMs: int|null, checkedAtTs: int|null, + * attemptedAtTs: int, failures: int, firstFailedTs: int|null, stale: bool} + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-an-outage-req-ict-003 + */ + private function nextReading(?array $previous, array $attempt): array { + $now = time(); + $failures = 0; + if ($attempt['failed'] === true) { + $failures = ((int)($previous['failures'] ?? 0) + 1); } - if ($cached !== null) { - // Allow-list refused the ping — REQ-HPING-002 "no ping was - // performed rather than a false 'up' state" / REQ-HPING-003 - // "Stale fallback on refresh failure": degrade gracefully to - // the last-known reading rather than fabricate a new one. - return $this->publicShape(reading: $cached, stale: true); + $firstFailedTs = $this->firstFailedTs(previous: $previous, failed: $attempt['failed'] === true, now: $now); + if ($attempt['failed'] === false || $failures >= $this->offlineAfterFailures()) { + return [ + 'state' => $attempt['state'], + 'latencyMs' => $attempt['latencyMs'], + 'checkedAtTs' => $now, + 'attemptedAtTs' => $now, + 'failures' => $failures, + 'firstFailedTs' => $firstFailedTs, + 'stale' => false, + ]; + } + + $checkedAtTs = null; + if (isset($previous['checkedAtTs']) === true) { + $checkedAtTs = (int)$previous['checkedAtTs']; + } + + $latencyMs = null; + if (isset($previous['latencyMs']) === true) { + $latencyMs = (int)$previous['latencyMs']; } return [ - 'state' => null, - 'checkedAt' => null, - 'latencyMs' => null, + 'state' => $previous['state'] ?? null, + 'latencyMs' => $latencyMs, + 'checkedAtTs' => $checkedAtTs, + 'attemptedAtTs' => $now, + 'failures' => $failures, + 'firstFailedTs' => $firstFailedTs, 'stale' => true, ]; - }//end resolveForConfig() + }//end nextReading() + + /** + * When the current run of failed checks began: kept while checks keep + * failing, now for the first failure, null once a check succeeds. + * + * @param array<string,mixed>|null $previous The cached reading, or null. + * @param boolean $failed Whether this check failed. + * @param integer $now The time of this check. + * + * @return integer|null The unix time of the first failed check, or null. + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-an-outage-req-ict-003 + */ + private function firstFailedTs(?array $previous, bool $failed, int $now): ?int { + if ($failed === false) { + return null; + } + + if ((int)($previous['failures'] ?? 0) > 0 && isset($previous['firstFailedTs']) === true) { + return (int)$previous['firstFailedTs']; + } + + return $now; + }//end firstFailedTs() + + /** + * Whether a cached reading was attempted less than one interval ago. + * + * @param array<string,mixed> $reading The cached reading. + * @param integer $interval The clamped ping interval in seconds. + * + * @return boolean + */ + private function isFresh(array $reading, int $interval): bool { + $age = (time() - (int)($reading['attemptedAtTs'] ?? $reading['checkedAtTs'] ?? 0)); + return ($age >= 0 && $age < $interval); + }//end isFresh() /** * Refresh every due, ping-enabled placement in the instance @@ -271,7 +369,7 @@ public function refreshDuePlacements(): int { try { $placements = $this->placementMapper->findAll(); } catch (Throwable $exception) { - $this->logger->warning( + $this->settings->logger->warning( message: 'HealthPingService: could not enumerate placements for refresh', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); @@ -297,7 +395,7 @@ public function refreshDuePlacements(): int { $refreshed++; } } catch (Throwable $exception) { - $this->logger->info( + $this->settings->logger->info( message: 'HealthPingService: refresh failed for one placement, continuing', context: [ 'app' => Application::APP_ID, @@ -319,7 +417,8 @@ public function refreshDuePlacements(): int { * `healthPingEnabled` is not `true` — an author may save an untouched * (disabled) ping block freely. * - * @param array<string,mixed> $config The candidate `{healthPingEnabled, healthUrl, expectedStatus, pingInterval}` config. + * @param array<string,mixed> $config The candidate `{healthPingEnabled, healthUrl, expectedStatus, + * pingInterval}` config. * * @return string[] Validation error codes; empty when the config is valid. * @@ -338,7 +437,7 @@ public function validateConfig(array $config): array { return $errors; } - if ($this->hasValidScheme(url: $url) === false) { + if (HostAllowList::hasHttpScheme(url: $url) === false) { $errors[] = 'invalid_url'; return $errors; } @@ -388,31 +487,31 @@ private function isDue(int $placementId, array $config): bool { return true; } - $age = (time() - (int)($cached['checkedAtTs'] ?? 0)); - return ($age < 0 || $age >= $interval); + return $this->isFresh(reading: $cached, interval: $interval) === false; }//end isDue() /** * Attempt the allow-listed, server-side health request and classify * the outcome (REQ-HPING-002). Returns `null` — WITHOUT ever opening a - * connection — when the host is not on the allow-list (fail-closed); - * every other outcome (success, wrong status, transport failure) is a - * definitive, cacheable classification. + * connection — when the host is not on the allow-list (fail-closed). + * A wrong status or a transport failure is a failed ping (`failed: + * true`, state `offline`); {@see self::nextReading()} decides whether + * the badge shows it yet. * * @param array<string,mixed> $config The placement's health-ping config. * - * @return array<string,mixed>|null `{state, latencyMs}` or `null` when refused. + * @return array{state: string, latencyMs: int, failed: bool}|null The attempt, or `null` when refused. * * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md#requirement-req-lp-conn-003-launchpad-reports-what-its-outbound-calls-met */ private function attemptPing(array $config): ?array { $url = trim(string: (string)($config['healthUrl'] ?? '')); - if ($url === '' || $this->hasValidScheme(url: $url) === false) { + if ($url === '' || HostAllowList::hasHttpScheme(url: $url) === false) { return null; } if ($this->isHostAllowed(url: $url) === false) { - $this->logger->warning( + $this->settings->logger->warning( message: 'HealthPingService: host not on healthping_allowed_hosts, refusing ping (fail-closed)', context: ['app' => Application::APP_ID] ); @@ -425,28 +524,17 @@ private function attemptPing(array $config): ?array { $startedAt = microtime(as_float: true); try { - $client = $this->clientService->newClient(); - $response = $client->get( - uri: $url, - options: [ - 'connect_timeout' => self::CONNECT_TIMEOUT, - 'timeout' => self::REQUEST_TIMEOUT, - 'http_errors' => false, - // No auto-redirect — a 3xx to an unexpected host would - // bypass the allow-list check above. - 'allow_redirects' => false, - ] - ); + $client = $this->transport->clientService->newClient(); + $response = (new NoRedirectGet(connectTimeout: self::CONNECT_TIMEOUT, timeout: self::REQUEST_TIMEOUT)) + ->send(client: $client, url: $url); } catch (Throwable $exception) { - // REQ-HPING-002 "Offline on failure" — a connection failure or - // timeout IS a definitive reading, not a missed attempt. $latencyMs = (int)round((microtime(as_float: true) - $startedAt) * 1000); - $this->logger->info( - message: 'HealthPingService: ping transport failure, classifying offline', + $this->settings->logger->info( + message: 'HealthPingService: ping transport failure, counting a failed ping', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_HEALTH_PING, url: $url, httpStatus: null); - return ['state' => 'offline', 'latencyMs' => $latencyMs]; + return ['state' => 'offline', 'latencyMs' => $latencyMs, 'failed' => true]; }//end try $latencyMs = (int)round((microtime(as_float: true) - $startedAt) * 1000); @@ -454,14 +542,14 @@ private function attemptPing(array $config): ?array { $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_HEALTH_PING, url: $url, httpStatus: $status); if ($this->matchesExpectedStatus(status: $status, expectedStatus: $expectedStatus) === false) { - return ['state' => 'offline', 'latencyMs' => $latencyMs]; + return ['state' => 'offline', 'latencyMs' => $latencyMs, 'failed' => true]; } if ($latencyMs > $threshold) { - return ['state' => 'degraded', 'latencyMs' => $latencyMs]; + return ['state' => 'degraded', 'latencyMs' => $latencyMs, 'failed' => false]; } - return ['state' => 'online', 'latencyMs' => $latencyMs]; + return ['state' => 'online', 'latencyMs' => $latencyMs, 'failed' => false]; }//end attemptPing() /** @@ -490,7 +578,7 @@ private function matchesExpectedStatus(int $status, int $expectedStatus): bool { * @return integer */ private function latencyThreshold(): int { - $threshold = $this->appConfig->getValueInt( + $threshold = $this->settings->appConfig->getValueInt( app: Application::APP_ID, key: self::CONFIG_KEY_LATENCY_THRESHOLD_MS, default: self::DEFAULT_LATENCY_THRESHOLD_MS @@ -504,52 +592,44 @@ private function latencyThreshold(): int { }//end latencyThreshold() /** - * Validate a URL's scheme is `http` or `https`. + * Resolve the configured number of consecutive failed pings after + * which a badge reads `offline`, at least 1. * - * @param string $url The URL to check. - * - * @return boolean + * @return integer */ - private function hasValidScheme(string $url): bool { - $scheme = strtolower(string: (string)parse_url(url: $url, component: PHP_URL_SCHEME)); - return in_array(needle: $scheme, haystack: ['http', 'https'], strict: true); - }//end hasValidScheme() + private function offlineAfterFailures(): int { + $failures = $this->settings->appConfig->getValueInt( + app: Application::APP_ID, + key: self::CONFIG_KEY_OFFLINE_AFTER_FAILURES, + default: self::DEFAULT_OFFLINE_AFTER_FAILURES + ); + + if ($failures > 0) { + return $failures; + } + + return self::DEFAULT_OFFLINE_AFTER_FAILURES; + }//end offlineAfterFailures() /** - * Check a URL's host against `healthping_allowed_hosts`. FAIL-CLOSED: + * Check a URL's host against `healthping_allowed_hosts` and the allowed websites with + * purpose fetch (REQ-ASET-021). FAIL-CLOSED: * an empty, missing, or unparseable allow-list permits NO host — the * admin must explicitly opt hosts in. * * @param string $url The URL to check. * * @return boolean True only when the host is explicitly allow-listed. + * + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 */ private function isHostAllowed(string $url): bool { - $host = parse_url(url: $url, component: PHP_URL_HOST); - if (is_string(value: $host) === false || $host === '') { - return false; - } - - $raw = $this->appConfig->getValueString( - app: Application::APP_ID, - key: self::CONFIG_KEY_ALLOWED_HOSTS, - default: '' + $allowList = new HostAllowList( + appConfig: $this->settings->appConfig, + configKey: self::CONFIG_KEY_ALLOWED_HOSTS, + purpose: AllowedSitesService::PURPOSE_FETCH ); - - $decoded = json_decode(json: $raw, associative: true); - if (is_array(value: $decoded) === false || $decoded === []) { - // FAIL-CLOSED — no configured list means no host is allowed. - return false; - } - - $needle = strtolower(string: $host); - foreach ($decoded as $allowed) { - if (is_string(value: $allowed) === true && strtolower(string: $allowed) === $needle) { - return true; - } - } - - return false; + return $allowList->permits(url: $url); }//end isHostAllowed() /** @@ -581,18 +661,28 @@ private function readPlacementConfig(WidgetPlacement $placement): array { * @return array<string,mixed> */ private function publicShape(array $reading, bool $stale): array { - $checkedAtTs = (int)($reading['checkedAtTs'] ?? time()); + $checkedAt = null; + if (isset($reading['checkedAtTs']) === true) { + $checkedAt = (new DateTime('@' . (int)$reading['checkedAtTs']))->format(format: DATE_ATOM); + } $latencyMs = null; if (isset($reading['latencyMs']) === true) { $latencyMs = (int)$reading['latencyMs']; } + // REQ-ICT-003: an offline service says since when its checks fail. + $downSince = null; + if (($reading['state'] ?? null) === 'offline' && isset($reading['firstFailedTs']) === true) { + $downSince = (new DateTime('@' . (int)$reading['firstFailedTs']))->format(format: DATE_ATOM); + } + return [ 'state' => $reading['state'] ?? null, - 'checkedAt' => (new DateTime('@' . $checkedAtTs))->format(format: DATE_ATOM), + 'checkedAt' => $checkedAt, 'latencyMs' => $latencyMs, 'stale' => $stale, + 'downSince' => $downSince, ]; }//end publicShape() @@ -607,34 +697,6 @@ private function buildCacheKey(int $placementId): string { return 'badge_' . $placementId; }//end buildCacheKey() - /** - * Read + JSON-decode a cache entry. Returns `null` on a miss or a - * corrupt entry. - * - * @param ICache|null $cache The cache instance, or `null` when the cache - * subsystem is unavailable. - * @param string $cacheKey The cache key. - * - * @return array<string,mixed>|null - */ - private function readCache(?ICache $cache, string $cacheKey): ?array { - if ($cache === null) { - return null; - } - - $raw = $cache->get(key: $cacheKey); - if (is_string(value: $raw) === false) { - return null; - } - - $decoded = json_decode(json: $raw, associative: true); - if (is_array(value: $decoded) === true) { - return $decoded; - } - - return null; - }//end readCache() - /** * Lazily resolve the distributed cache. Returns `null` when the cache * subsystem is unavailable (e.g. unit tests with a stub factory). @@ -647,9 +709,9 @@ private function getCache(): ?ICache { } try { - $this->cache = $this->cacheFactory->createDistributed(prefix: 'launchpad_healthping_'); + $this->cache = $this->transport->cacheFactory->createDistributed(prefix: 'launchpad_healthping_'); } catch (Throwable $exception) { - $this->logger->info( + $this->settings->logger->info( message: 'HealthPingService: cache subsystem unavailable, falling back to direct ping', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); diff --git a/lib/Service/HiddenWidgetsOverview.php b/lib/Service/HiddenWidgetsOverview.php new file mode 100644 index 000000000..62a9cd637 --- /dev/null +++ b/lib/Service/HiddenWidgetsOverview.php @@ -0,0 +1,197 @@ +<?php + +/** + * HiddenWidgetsOverview + * + * Every widget one person hid on a shared dashboard, across all dashboards, + * for the section Verborgen widgets of the personal settings dialog + * (personal-settings REQ-PSET-003). It reads and changes only the caller's + * own personal layers (REQ-DWMS-001): the shared dashboards stay as they are + * for everyone else. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeImmutable; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\PersonalLayer; +use OCA\LaunchPad\Db\PersonalLayerMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; + +/** + * Lists, and shows again, the widgets a person hid. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ +class HiddenWidgetsOverview { + /** + * Constructor. + * + * @param PersonalLayerMapper $layers The personal layers. + * @param WidgetPlacementMapper $placements The shared placements, to name a hidden widget. + * @param DashboardService $dashboards Decides whether the person may still see a dashboard. + */ + public function __construct( + private readonly PersonalLayerMapper $layers, + private readonly WidgetPlacementMapper $placements, + private readonly DashboardService $dashboards, + ) { + }//end __construct() + + /** + * The widgets this person hid, on the dashboards they may still see. + * + * A hidden id whose placement no longer exists is left out: the person + * cannot show again what is not there. A dashboard the person lost access + * to is left out too, so the list never names a dashboard they cannot open. + * + * @param string $userId The caller. + * + * @return array<int, array<string, mixed>> Per hidden widget: `placementId`, + * `dashboardId`, `dashboardName` and the serialised `placement`. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function listFor(string $userId): array { + if ($userId === '') { + return []; + } + + $out = []; + foreach ($this->layers->findAllForUser(userId: $userId) as $layer) { + $hidden = $layer->hiddenArray(); + if ($hidden === []) { + continue; + } + + $dashboardId = (int)$layer->getDashboardId(); + $envelope = $this->dashboards->getDashboardForUser(dashboardId: $dashboardId, userId: $userId); + if ($envelope === null) { + continue; + } + + $name = self::dashboardName(dashboard: $envelope['dashboard'] ?? null); + foreach ($this->placements->findByDashboardId(dashboardId: $dashboardId) as $placement) { + if (in_array((int)$placement->getId(), $hidden, true) === false) { + continue; + } + + $out[] = [ + 'placementId' => (int)$placement->getId(), + 'dashboardId' => $dashboardId, + 'dashboardName' => $name, + 'placement' => $placement->jsonSerialize(), + ]; + } + }//end foreach + + return $out; + }//end listFor() + + /** + * Show one hidden widget again, on the caller's own layer. + * + * @param string $userId The caller. + * @param int $placementId The hidden placement. + * + * @return bool True when it was hidden by this person and now is not. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function showAgain(string $userId, int $placementId): bool { + if ($userId === '' || $placementId <= 0) { + return false; + } + + foreach ($this->layers->findAllForUser(userId: $userId) as $layer) { + $hidden = $layer->hiddenArray(); + if (in_array($placementId, $hidden, true) === false) { + continue; + } + + $this->storeHidden( + layer: $layer, + hidden: array_values(array_diff($hidden, [$placementId])) + ); + + return true; + } + + return false; + }//end showAgain() + + /** + * Show every widget this person hid again, on every dashboard. Their + * other adjustments (position, size) stay. + * + * @param string $userId The caller. + * + * @return int How many widgets came back. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function showAll(string $userId): int { + if ($userId === '') { + return 0; + } + + $count = 0; + foreach ($this->layers->findAllForUser(userId: $userId) as $layer) { + $hidden = $layer->hiddenArray(); + if ($hidden === []) { + continue; + } + + $count += count($hidden); + $this->storeHidden(layer: $layer, hidden: []); + } + + return $count; + }//end showAll() + + /** + * Write a new hidden set on a layer the caller owns. + * + * @param PersonalLayer $layer The caller's layer. + * @param array<int, int> $hidden The placement ids that stay hidden. + * + * @return void + */ + private function storeHidden(PersonalLayer $layer, array $hidden): void { + $layer->setHidden(json_encode($hidden)); + $layer->setUpdatedAt((new DateTimeImmutable())->format(DATE_ATOM)); + $this->layers->update($layer); + }//end storeHidden() + + /** + * The name of a dashboard from the read envelope, entity or array. + * + * @param mixed $dashboard The envelope's `dashboard`. + * + * @return string The name, or an empty string. + */ + private static function dashboardName(mixed $dashboard): string { + if ($dashboard instanceof Dashboard) { + return (string)$dashboard->getName(); + } + + if (is_array($dashboard) === true) { + return (string)($dashboard['name'] ?? ''); + } + + return ''; + }//end dashboardName() +}//end class diff --git a/lib/Service/HostAllowList.php b/lib/Service/HostAllowList.php new file mode 100644 index 000000000..1b2127af9 --- /dev/null +++ b/lib/Service/HostAllowList.php @@ -0,0 +1,166 @@ +<?php + +/** + * HostAllowList + * + * The fail-closed outbound host allow-list and the http(s) scheme check + * shared by the services that fetch admin-configured URLs. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\AppInfo\Application; +use OCP\IAppConfig; + +/** + * One admin-configured list of hosts an outbound request may reach: a JSON + * list stored under an app config key. FAIL-CLOSED: an empty, missing, or + * unparseable list permits NO host — the admin must explicitly opt hosts in. + * + * @spec openspec/specs/service-health-ping/spec.md + */ +final class HostAllowList { + /** + * Constructor + * + * @param IAppConfig $appConfig The app config holding the list. + * @param string $configKey The config key of the list. + * @param string $purpose The purpose on the allowed-websites list + * (`embed` or `fetch`) whose hosts this list + * also admits; '' for none (REQ-ASET-021). + */ + public function __construct( + private readonly IAppConfig $appConfig, + private readonly string $configKey, + private readonly string $purpose = '', + ) { + }//end __construct() + + /** + * Whether a URL's scheme is `http` or `https`. + * + * @param string $url The URL to check. + * + * @return boolean + * + * @spec openspec/specs/service-health-ping/spec.md + */ + public static function hasHttpScheme(string $url): bool { + $scheme = strtolower(string: (string)parse_url(url: $url, component: PHP_URL_SCHEME)); + return in_array(needle: $scheme, haystack: ['http', 'https'], strict: true); + }//end hasHttpScheme() + + /** + * Whether a URL's host is on the list (case-insensitive), or on the + * allowed-websites list for this list's purpose. The lists are only read + * once the URL has a host. + * + * @param string $url The URL to check. + * + * @return boolean True only when the host is explicitly allow-listed. + * + * @spec openspec/specs/service-health-ping/spec.md + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + public function permits(string $url): bool { + $host = parse_url(url: $url, component: PHP_URL_HOST); + if (is_string(value: $host) === false || $host === '') { + return false; + } + + // FAIL-CLOSED — no configured list means no host is allowed. + $decoded = json_decode(json: $this->rawList(), associative: true); + if (is_array(value: $decoded) === true && $this->listsHost(allowed: $decoded, host: $host) === true) { + return true; + } + + return $this->purpose !== '' + && (new AllowedSitesService(appConfig: $this->appConfig))->permits(url: $url, purpose: $this->purpose); + }//end permits() + + /** + * The hosts on the list: trimmed, deduplicated, non-string and blank + * entries dropped, then the allowed-websites hosts for this list's + * purpose. Empty when nothing is configured. + * + * @return string[] + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + public function hosts(): array { + $hosts = $this->ownHosts(); + if ($this->purpose !== '') { + $hosts = array_merge($hosts, (new AllowedSitesService(appConfig: $this->appConfig))->hostsFor(purpose: $this->purpose)); + } + + return array_values(array: array_unique(array: $hosts)); + }//end hosts() + + /** + * The hosts stored under this list's own config key. + * + * @return string[] + */ + private function ownHosts(): array { + $decoded = json_decode(json: $this->rawList(), associative: true); + if (is_array(value: $decoded) === false) { + return []; + } + + $hosts = []; + foreach ($decoded as $entry) { + if (is_string(value: $entry) === true && trim(string: $entry) !== '') { + $hosts[] = trim(string: $entry); + } + } + + return $hosts; + }//end ownHosts() + + /** + * The stored JSON list, '' when unset. + * + * @return string The raw list. + */ + private function rawList(): string { + return $this->appConfig->getValueString( + app: Application::APP_ID, + key: $this->configKey, + default: '' + ); + }//end rawList() + + /** + * Whether a decoded list carries the host (case-insensitive); non-string + * entries never match. + * + * @param array<mixed> $allowed The decoded list. + * @param string $host The URL's host. + * + * @return boolean + */ + private function listsHost(array $allowed, string $host): bool { + $needle = strtolower(string: $host); + foreach ($allowed as $entry) { + if (is_string(value: $entry) === true && strtolower(string: $entry) === $needle) { + return true; + } + } + + return false; + }//end listsHost() +}//end class diff --git a/lib/Service/IframeService.php b/lib/Service/IframeService.php index e29f25f14..8b1e837dc 100644 --- a/lib/Service/IframeService.php +++ b/lib/Service/IframeService.php @@ -275,30 +275,19 @@ public function isHostAllowed(string $url): bool { * FAIL-CLOSED (REQ-IFRAME-002, REQ-IFRAME-003 "Non-allow-listed hosts * are never added"). * + * Also holds the allowed websites with purpose embed (REQ-ASET-021). + * * @return string[] Lower-case-safe hostnames (original casing preserved), deduplicated. * * @spec openspec/specs/iframe-embed-widget/spec.md + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 */ public function getAllowedHosts(): array { - $raw = $this->appConfig->getValueString( - app: Application::APP_ID, - key: self::CONFIG_KEY_ALLOWED_HOSTS, - default: '' - ); - - $decoded = json_decode(json: $raw, associative: true); - if (is_array(value: $decoded) === false || $decoded === []) { - return []; - } - - $hosts = []; - foreach ($decoded as $host) { - if (is_string(value: $host) === true && trim(string: $host) !== '') { - $hosts[] = trim(string: $host); - } - } - - return array_values(array: array_unique(array: $hosts)); + return (new HostAllowList( + appConfig: $this->appConfig, + configKey: self::CONFIG_KEY_ALLOWED_HOSTS, + purpose: AllowedSitesService::PURPOSE_EMBED + ))->hosts(); }//end getAllowedHosts() /** diff --git a/lib/Service/ImageHostService.php b/lib/Service/ImageHostService.php new file mode 100644 index 000000000..1df1c3d65 --- /dev/null +++ b/lib/Service/ImageHostService.php @@ -0,0 +1,138 @@ +<?php + +/** + * ImageHostService + * + * The administrator's allow-list of external hosts image widgets may load + * pictures from (REQ-IMG-006). The list is a JSON array of hostnames under + * `image_allowed_hosts` (IAppConfig), the same shape as + * `iframe_allowed_hosts`, and it is FAIL-CLOSED: an empty or missing list + * admits no external image host. {@see \OCA\LaunchPad\Listener\CspListener} + * adds each host to the `img-src` directive of LaunchPad pages. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; +use OCA\LaunchPad\AppInfo\Application; +use OCP\IAppConfig; + +/** + * Reads and stores the external image host allow-list. + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + */ +class ImageHostService { + + /** + * IAppConfig key: JSON array of hostnames image widgets may load from. + * + * @var string + */ + public const CONFIG_KEY_ALLOWED_HOSTS = 'image_allowed_hosts'; + + /** + * A bare hostname with an optional port: no scheme, path or wildcard. + * + * @var string + */ + private const HOST_PATTERN = '~^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~i'; + + /** + * Constructor. + * + * @param IAppConfig $appConfig Holds the allow-list. + */ + public function __construct( + private readonly IAppConfig $appConfig, + ) { + }//end __construct() + + /** + * The allow-listed hosts; empty when none are configured. + * + * @return string[] + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + */ + public function getAllowedHosts(): array { + return (new HostAllowList(appConfig: $this->appConfig, configKey: self::CONFIG_KEY_ALLOWED_HOSTS))->hosts(); + }//end getAllowedHosts() + + /** + * The hosts images may load from: this list and the allowed websites + * with purpose embed (REQ-ASET-021). The admin editor reads + * {@see self::getAllowedHosts()}; the CSP reads this. + * + * @return string[] + * + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + public function getPermittedHosts(): array { + return (new HostAllowList( + appConfig: $this->appConfig, + configKey: self::CONFIG_KEY_ALLOWED_HOSTS, + purpose: AllowedSitesService::PURPOSE_EMBED + ))->hosts(); + }//end getPermittedHosts() + + /** + * Replace the allow-list. Every entry must be a bare hostname, optionally + * with a port; entries are lower-cased, blanks dropped and duplicates merged. + * + * @param mixed $hosts The submitted list. + * + * @return string[] The stored list. + * + * @throws InvalidArgumentException When the list is not an array of hostnames. + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + */ + public function setAllowedHosts(mixed $hosts): array { + if (is_array(value: $hosts) === false) { + throw new InvalidArgumentException(message: 'The allowed image hosts must be a list of host names.'); + } + + $clean = []; + foreach ($hosts as $host) { + if (is_string(value: $host) === false) { + throw new InvalidArgumentException(message: 'The allowed image hosts must be a list of host names.'); + } + + $host = strtolower(string: trim(string: $host)); + if ($host === '') { + continue; + } + + if (preg_match(pattern: self::HOST_PATTERN, subject: $host) !== 1) { + throw new InvalidArgumentException( + message: sprintf('"%s" is not a host name. Enter a host such as images.example.com, without https:// or a path.', $host) + ); + } + + $clean[] = $host; + } + + $clean = array_values(array: array_unique(array: $clean)); + $this->appConfig->setValueString( + app: Application::APP_ID, + key: self::CONFIG_KEY_ALLOWED_HOSTS, + value: json_encode(value: $clean, flags: JSON_THROW_ON_ERROR) + ); + + return $clean; + }//end setAllowedHosts() +}//end class diff --git a/lib/Service/ImportService.php b/lib/Service/ImportService.php index 09f3d5169..d09829665 100644 --- a/lib/Service/ImportService.php +++ b/lib/Service/ImportService.php @@ -127,6 +127,7 @@ public function __construct( * * @return array{importedDashboardCount:int, skippedDashboardCount:int, * errors:array<int, array<string,mixed>>, + * dashboards:array<int, array{sourceUuid:string, uuid:string, id:int}>, * manifest:array<string,mixed>, * status:string} * @@ -140,6 +141,28 @@ public function import( bool $preserveUuids, string $currentUserId, ): array { + $zip = $this->openArchive(zipPath: $zipPath); + + try { + return $this->importArchive( + zip: $zip, + run: new DashboardImportRun(currentUserId: $currentUserId, preserveUuids: $preserveUuids) + ); + } finally { + $zip->close(); + } + }//end import() + + /** + * Open an uploaded archive read-only. + * + * @param string $zipPath Path to the uploaded ZIP file. + * + * @return ZipArchive The open archive. + * + * @throws InvalidArgumentException When it is missing or not a ZIP. + */ + private function openArchive(string $zipPath): ZipArchive { if (file_exists(filename: $zipPath) === false) { throw new InvalidArgumentException( message: 'Uploaded file is not a valid ZIP archive' @@ -153,38 +176,56 @@ public function import( ); } - try { - $manifest = $this->validateZipStructure(zip: $zip); - $dashboards = $this->readDashboards(zip: $zip); - $collisions = $this->detectUuidCollisions(dashboards: $dashboards); - - if ($preserveUuids === true && $collisions !== []) { - return [ - 'status' => self::ERR_UUID_COLLISION, - 'manifest' => $manifest, - 'importedDashboardCount' => 0, - 'skippedDashboardCount' => 0, - 'errors' => $collisions, - ]; - } + return $zip; + }//end openArchive() - $remapped = $this->remapUuids( - dashboards: $dashboards, - preserveUuids: $preserveUuids - ); + /** + * Validate an open archive and import its dashboards, unless kept UUIDs + * collide with existing ones. + * + * @param ZipArchive $zip The open archive. + * @param DashboardImportRun $run The batch. + * + * @return array<string, mixed> The import result. + */ + private function importArchive(ZipArchive $zip, DashboardImportRun $run): array { + $manifest = $this->validateZipStructure(zip: $zip); + $dashboards = $this->readDashboards(zip: $zip); + $collisions = $this->detectUuidCollisions(dashboards: $dashboards); - return [ - 'status' => 'ok', - 'manifest' => $manifest, - ] + $this->importDashboardBatch( - dashboards: $remapped, - currentUserId: $currentUserId, - preserveUuids: $preserveUuids - ); - } finally { - $zip->close(); - }//end try - }//end import() + if ($run->preserveUuids === true && $collisions !== []) { + return $this->collisionResult(manifest: $manifest, collisions: $collisions); + } + + $remapped = $this->remapUuids( + dashboards: $dashboards, + preserveUuids: $run->preserveUuids + ); + + return [ + 'status' => 'ok', + 'manifest' => $manifest, + ] + $this->importDashboardBatch(dashboards: $remapped, run: $run); + }//end importArchive() + + /** + * The result of an import refused because kept UUIDs collide. + * + * @param array<string, mixed> $manifest The validated manifest. + * @param array<int, array<string, mixed>> $collisions The collision errors. + * + * @return array<string, mixed> The import result. + */ + private function collisionResult(array $manifest, array $collisions): array { + return [ + 'status' => self::ERR_UUID_COLLISION, + 'manifest' => $manifest, + 'importedDashboardCount' => 0, + 'skippedDashboardCount' => 0, + 'errors' => $collisions, + 'dashboards' => [], + ]; + }//end collisionResult() /** * Validate the manifest and return its decoded payload. @@ -198,6 +239,23 @@ public function import( * @spec openspec/specs/dashboard-export-import/spec.md */ public function validateZipStructure(ZipArchive $zip): array { + $decoded = $this->decodeManifest(zip: $zip); + $this->assertManifestFields(manifest: $decoded); + $this->assertSchemaVersion(version: $decoded['schemaVersion']); + + return $decoded; + }//end validateZipStructure() + + /** + * Read and decode the archive's manifest.json. + * + * @param ZipArchive $zip The open archive. + * + * @return array<string, mixed> The decoded manifest. + * + * @throws InvalidArgumentException When it is missing or not a JSON object. + */ + private function decodeManifest(ZipArchive $zip): array { $raw = $zip->getFromName(name: 'manifest.json'); if ($raw === false) { throw new InvalidArgumentException( @@ -212,10 +270,22 @@ public function validateZipStructure(ZipArchive $zip): array { ); } - $required = ['schemaVersion', 'scope']; + return $decoded; + }//end decodeManifest() + + /** + * Refuse a manifest without schemaVersion or scope. + * + * @param array<string, mixed> $manifest The decoded manifest. + * + * @return void + * + * @throws InvalidArgumentException Naming every missing field. + */ + private function assertManifestFields(array $manifest): void { $missing = []; - foreach ($required as $field) { - if (array_key_exists(key: $field, array: $decoded) === false) { + foreach (['schemaVersion', 'scope'] as $field) { + if (array_key_exists(key: $field, array: $manifest) === false) { $missing[] = $field; } } @@ -225,24 +295,42 @@ public function validateZipStructure(ZipArchive $zip): array { message: 'Manifest missing required field(s): ' . implode(separator: ', ', array: $missing) ); } + }//end assertManifestFields() - $version = $decoded['schemaVersion']; + /** + * Refuse a schema version other than {@see self::SCHEMA_VERSION}. + * + * @param mixed $version The manifest's schemaVersion. + * + * @return void + * + * @throws InvalidArgumentException With upgrade advice for a newer version. + */ + private function assertSchemaVersion(mixed $version): void { if (is_int($version) === false || $version !== self::SCHEMA_VERSION) { - $head = 'Unsupported manifest schema version: ' . (string)$version . '.'; - $tail = ' Only version ' . (string)self::SCHEMA_VERSION . ' is supported.'; - // An archive from a NEWER LaunchPad is the one case the admin can - // act on, and REQ-EXIM-009 asks for them to be told how. A version - // below 1 is not an older format, it is a broken manifest, so it - // gets no such advice. - if (is_int($version) === true && $version > self::SCHEMA_VERSION) { - $tail .= ' Upgrade LaunchPad to import archives of version ' . (string)$version . '.'; - } + throw new InvalidArgumentException(message: $this->unsupportedVersionMessage(version: $version)); + } + }//end assertSchemaVersion() - throw new InvalidArgumentException(message: ($head . $tail)); + /** + * The refusal message of an unsupported schema version. An archive from + * a NEWER LaunchPad is the one case the admin can act on, and + * REQ-EXIM-009 asks for them to be told how. A version below 1 is not an + * older format, it is a broken manifest, so it gets no such advice. + * + * @param mixed $version The manifest's schemaVersion. + * + * @return string The message. + */ + private function unsupportedVersionMessage(mixed $version): string { + $head = 'Unsupported manifest schema version: ' . (string)$version . '.'; + $tail = ' Only version ' . (string)self::SCHEMA_VERSION . ' is supported.'; + if (is_int($version) === true && $version > self::SCHEMA_VERSION) { + $tail .= ' Upgrade LaunchPad to import archives of version ' . (string)$version . '.'; } - return $decoded; - }//end validateZipStructure() + return $head . $tail; + }//end unsupportedVersionMessage() /** * Re-map UUIDs across dashboards when `preserveUuids=false`. @@ -266,7 +354,7 @@ public function remapUuids(array $dashboards, bool $preserveUuids): array { continue; } - $uuidMap[$original] = $this->generateUuidV4(); + $uuidMap[$original] = UuidV4::generate(); } $result = []; @@ -299,80 +387,120 @@ public function remapUuids(array $dashboards, bool $preserveUuids): array { * record cannot poison the batch (REQ-EXIM-011). * * @param array<int, array<string, mixed>> $dashboards Decoded dashboards. - * @param string $currentUserId Importing UID. - * @param bool $preserveUuids Preserve flag. + * @param DashboardImportRun $run The batch: importing UID, preserve flag, tally. * * @return array{importedDashboardCount:int, skippedDashboardCount:int, - * errors:array<int, array<string,mixed>>} + * errors:array<int, array<string,mixed>>, + * dashboards:array<int, array{sourceUuid:string, uuid:string, id:int}>} */ - private function importDashboardBatch( - array $dashboards, - string $currentUserId, - bool $preserveUuids, - ): array { - $imported = 0; - $skipped = 0; - $errors = []; - + private function importDashboardBatch(array $dashboards, DashboardImportRun $run): array { foreach ($dashboards as $payload) { - // The archive's UUID, not the one a remap may have minted: it is - // what the admin can find in their file. - $uuid = $this->reportableUuid(payload: $payload); - $missing = $this->validateDashboardPayload(payload: $payload); - if ($missing !== null) { - $skipped++; - $errors[] = $this->invalidDashboardError(payload: $payload, missing: $missing); + $this->importOneDashboard(run: $run, payload: $payload); + } + + return $run->summary(); + }//end importDashboardBatch() + + /** + * Import one dashboard of the batch, or record why it was skipped. + * + * @param DashboardImportRun $run The batch. + * @param array<string, mixed> $payload The decoded dashboard. + * + * @return void + */ + private function importOneDashboard(DashboardImportRun $run, array $payload): void { + // The archive's UUID, not the one a remap may have minted: it is + // what the admin can find in their file. + $uuid = $this->reportableUuid(payload: $payload); + $missing = $this->validateDashboardPayload(payload: $payload); + if ($missing !== null) { + $run->recordSkipped(error: $this->invalidDashboardError(payload: $payload, missing: $missing)); + return; + } + + $this->db->beginTransaction(); + try { + $persisted = $this->persistDashboard(run: $run, payload: $payload); + $this->db->commit(); + $run->recordImported(sourceUuid: $uuid, persisted: $persisted); + } catch (Throwable $e) { + $this->db->rollBack(); + $run->recordSkipped(error: $this->failedDashboardError(payload: $payload, exception: $e)); + } + }//end importOneDashboard() + + /** + * Insert one dashboard and its widget placements. + * + * @param DashboardImportRun $run The batch. + * @param array<string, mixed> $payload The decoded dashboard. + * + * @return Dashboard The inserted dashboard. + */ + private function persistDashboard(DashboardImportRun $run, array $payload): Dashboard { + $dashboard = $this->buildEntity( + payload: $payload, + currentUserId: $run->currentUserId, + preserveUuids: $run->preserveUuids + ); + + $persisted = $this->dashboardMapper->insert(entity: $dashboard); + $this->insertPlacements(persisted: $persisted, widgets: ($payload['widgets'] ?? [])); + + return $persisted; + }//end persistDashboard() + + /** + * Insert a placement for every widget entry that is an object; other + * entries, and a widgets value that is not a list, are ignored. + * + * @param Dashboard $persisted The inserted dashboard. + * @param mixed $widgets The dashboard's widgets value. + * + * @return void + */ + private function insertPlacements(Dashboard $persisted, mixed $widgets): void { + if (is_array($widgets) === false) { + return; + } + + foreach ($widgets as $widgetPayload) { + if (is_array($widgetPayload) === false) { continue; } - $this->db->beginTransaction(); - try { - $dashboard = $this->buildEntity( - payload: $payload, - currentUserId: $currentUserId, - preserveUuids: $preserveUuids - ); - - $persisted = $this->dashboardMapper->insert(entity: $dashboard); - - $widgets = $payload['widgets'] ?? []; - if (is_array($widgets) === true) { - foreach ($widgets as $widgetPayload) { - if (is_array($widgetPayload) === false) { - continue; - } - - $placement = $this->placementHydrator->hydrate( - dashboardId: (int)$persisted->getId(), - payload: $widgetPayload - ); - $this->placementMapper->insert(entity: $placement); - } - } - - $this->db->commit(); - $imported++; - } catch (Throwable $e) { - $this->db->rollBack(); - $skipped++; - $errors[] = [ - 'type' => self::ERR_INVALID_DASHBOARD, - 'uuid' => $this->reportableUuid(payload: $payload), - 'message' => 'Failed to import dashboard: ' . $e->getMessage(), - ]; - $this->logger->warning( - message: 'Skipped dashboard during import', - context: ['uuid' => $uuid, 'exception' => $e] - ); - }//end try - }//end foreach + $placement = $this->placementHydrator->hydrate( + dashboardId: (int)$persisted->getId(), + payload: $widgetPayload, + asTemplate: $persisted->getType() === Dashboard::TYPE_ADMIN_TEMPLATE + ); + $this->placementMapper->insert(entity: $placement); + } + }//end insertPlacements() - return [ - 'importedDashboardCount' => $imported, - 'skippedDashboardCount' => $skipped, - 'errors' => $errors, + /** + * The error entry of a dashboard whose insert failed; logs the skip. + * + * @param array<string, mixed> $payload The decoded dashboard. + * @param Throwable $exception Why it failed. + * + * @return array<string, mixed> The error entry. + */ + private function failedDashboardError(array $payload, Throwable $exception): array { + $uuid = $this->reportableUuid(payload: $payload); + $error = [ + 'type' => self::ERR_INVALID_DASHBOARD, + 'uuid' => $uuid, + 'message' => 'Failed to import dashboard: ' . $exception->getMessage(), ]; - }//end importDashboardBatch() + $this->logger->warning( + message: 'Skipped dashboard during import', + context: ['uuid' => $uuid, 'exception' => $exception] + ); + + return $error; + }//end failedDashboardError() /** * Read decoded dashboards from the archive. @@ -658,6 +786,13 @@ private function applyEntityOwnership( $userId = $currentUserId; } + // An admin template belongs to nobody (admin-templates data model: + // `userId` is null). The fallback above would hand an imported + // template to whoever ran the import. + if ($type === Dashboard::TYPE_ADMIN_TEMPLATE) { + $userId = null; + } + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters $dashboard->setUserId($userId); }//end applyEntityOwnership() @@ -672,6 +807,7 @@ private function applyEntityOwnership( * @param array<string, mixed> $payload The dashboard payload. * * @return void + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies */ private function applyEntityLayout( Dashboard $dashboard, @@ -692,8 +828,49 @@ private function applyEntityLayout( ) { $dashboard->setTargetGroupsArray(groups: $payload['targetGroups']); } + + $this->applyEntityHierarchies(dashboard: $dashboard, payload: $payload); + + // What a template is filed under and how it is described in the + // gallery is part of the template, so it travels with it (REQ-EXIM-012). + foreach (['templateCategory', 'templateDescription'] as $field) { + if (isset($payload[$field]) === true) { + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $dashboard->{'set' . ucfirst($field)}((string)$payload[$field]); + } + } }//end applyEntityLayout() + /** + * Hydrate the hierarchy descriptors of the filter bus (REQ-CWF-011). + * + * Validated like an API update. A malformed list is left out with a + * warning, so one bad field does not cost the whole dashboard. + * + * @param Dashboard $dashboard The entity being hydrated. + * @param array<string, mixed> $payload The dashboard payload. + * + * @return void + * + * @SuppressWarnings(PHPMD.StaticAccess) DashboardHierarchies is a stateless validator. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + private function applyEntityHierarchies(Dashboard $dashboard, array $payload): void { + if (array_key_exists(key: 'hierarchies', array: $payload) === false) { + return; + } + + try { + $dashboard->setHierarchiesArray(DashboardHierarchies::validated(value: $payload['hierarchies'])); + } catch (InvalidArgumentException $e) { + $this->logger->warning( + message: 'LaunchPad import: hierarchies left out of dashboard {name}: {reason}', + context: ['name' => (string)$dashboard->getName(), 'reason' => $e->getMessage()] + ); + } + }//end applyEntityHierarchies() + /** * Hydrate the tree-placement and publication fields. * @@ -736,24 +913,4 @@ private function applyEntityPlacement( $dashboard->setPublicationStatus((string)$payload['publicationStatus']); } }//end applyEntityPlacement() - - /** - * Generate a v4 UUID for re-mapped imports. - * - * @return string The UUID. - */ - private function generateUuidV4(): string { - $bytes = random_bytes(length: 16); - $bytes[6] = chr(codepoint: ord(character: $bytes[6]) & 0x0f | 0x40); - $bytes[8] = chr(codepoint: ord(character: $bytes[8]) & 0x3f | 0x80); - $hex = bin2hex(string: $bytes); - return sprintf( - '%s-%s-%s-%s-%s', - substr(string: $hex, offset: 0, length: 8), - substr(string: $hex, offset: 8, length: 4), - substr(string: $hex, offset: 12, length: 4), - substr(string: $hex, offset: 16, length: 4), - substr(string: $hex, offset: 20, length: 12), - ); - }//end generateUuidV4() }//end class diff --git a/lib/Service/InitialState/Page.php b/lib/Service/InitialState/Page.php index e6a205925..449b4570d 100644 --- a/lib/Service/InitialState/Page.php +++ b/lib/Service/InitialState/Page.php @@ -34,4 +34,6 @@ enum Page: string { case WORKSPACE = 'workspace'; case ADMIN = 'admin'; + // Sharing-public-start-page D3: the public start page at /apps/launchpad/start. + case PUBLIC_START = 'public-start'; }//end enum diff --git a/lib/Service/InitialStateBuilder.php b/lib/Service/InitialStateBuilder.php index b849806c1..9c6e1d5dd 100644 --- a/lib/Service/InitialStateBuilder.php +++ b/lib/Service/InitialStateBuilder.php @@ -39,6 +39,10 @@ * - linkCreateFileExtensions — admin-configurable allow-list for the * link-button-widget createFile flow (REQ-LBN-004) * + * Public start page (`#public-share-vue` at `/start`) keys, version 3: + * - publicStartToken — token of the public link the start page shows + * (sharing-public-start-page D3) + * * Both payloads always carry `_schemaVersion`. * * @category Service @@ -59,6 +63,7 @@ namespace OCA\LaunchPad\Service; +use JsonSerializable; use OCA\LaunchPad\Exception\MissingInitialStateException; use OCA\LaunchPad\Service\InitialState\Page; use OCP\AppFramework\Services\IInitialState; @@ -77,7 +82,7 @@ class InitialStateBuilder { * * @var integer */ - public const INITIAL_STATE_SCHEMA_VERSION = 2; + public const INITIAL_STATE_SCHEMA_VERSION = 3; /** * Reserved payload key carrying the schema version. @@ -115,6 +120,10 @@ class InitialStateBuilder { 'allowUserDashboards', 'linkCreateFileExtensions', ], + // Sharing-public-start-page D3: the link the start page shows. + Page::PUBLIC_START->value => [ + 'publicStartToken', + ], ]; /** @@ -295,6 +304,86 @@ public function setAllowedWidgets(?array $allowedWidgets): self { return $this; }//end setAllowedWidgets() + /** + * Set the first dashboard load (workspace): `{visible, active}` with the + * payloads of `GET /api/dashboards/visible` and `GET /api/dashboard`, so + * the dashboard store starts from them instead of asking for both again. + * Optional key; null (left out) when the page could not build it. + * + * @param array|null $firstLoad The two payloads, or null. + * + * @return self + * + * @spec openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md#task-2 + */ + public function setDashboardFirstLoad(?array $firstLoad): self { + if ($firstLoad !== null) { + $this->values['dashboardFirstLoad'] = $firstLoad; + } + + return $this; + }//end setDashboardFirstLoad() + + /** + * Set the org navigation the shell's first load would fetch + * (`{position, tree, language}`), so the shell starts from it instead of + * asking `GET /api/admin/org-navigation/position` and + * `GET /api/admin/org-navigation`. Optional key; left out when null. + * + * @param array|null $orgNavigation The position, tree and language, or null. + * + * @return self + * + * @spec openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/tasks.md#task-2 + */ + public function setOrgNavigation(?array $orgNavigation): self { + if ($orgNavigation !== null) { + $this->values['orgNavigation'] = $orgNavigation; + } + + return $this; + }//end setOrgNavigation() + + /** + * Set what the workspace view reads while it boots, besides its + * dashboards (`{tiles, pendingAcknowledgements, defaultDashboard}`, each + * part optional), so it starts from them instead of asking + * `GET /api/tiles`, `GET /api/acknowledgements/pending` and + * `GET /api/dashboards/default`. Optional key; left out when null. + * + * @param array|null $bootReads The reads, or null. + * + * @return self + * + * @spec openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/tasks.md#task-2 + */ + public function setWorkspaceBootReads(?array $bootReads): self { + if ($bootReads !== null) { + $this->values['workspaceBootReads'] = $bootReads; + } + + return $this; + }//end setWorkspaceBootReads() + + /** + * Set the runtime manifest kept for the caller, so the page starts from + * it instead of asking `GET /api/manifest`. Optional key; left out when + * null (no manifest kept). + * + * @param array|null $manifest The manifest, or null. + * + * @return self + * + * @spec openspec/changes/archive/2026-11-25-manifest-cached-per-user/tasks.md#task-2 + */ + public function setRuntimeManifest(?array $manifest): self { + if ($manifest !== null) { + $this->values['runtimeManifest'] = $manifest; + } + + return $this; + }//end setRuntimeManifest() + /** * Set the canonical slug-chain path for the active dashboard * (workspace). @@ -338,6 +427,229 @@ public function setQuicksearchFallbackTarget(string $fallbackTarget): self { return $this; }//end setQuicksearchFallbackTarget() + /** + * Set the search shortcuts every search box honours (search-ai-prefix-shortcuts, + * REQ-SPX-002). Optional key, like `quicksearchFallbackTarget`: the JS reader + * defaults it to an empty list. + * + * @param array $shortcuts Validated `{prefix, name, urlTemplate}` entries. + * + * @return self Fluent. + * + * @spec openspec/specs/tile-quick-search/spec.md + */ + public function setSearchShortcuts(array $shortcuts): self { + $this->values['searchShortcuts'] = array_values(array: $shortcuts); + return $this; + }//end setSearchShortcuts() + + /** + * Set the administrator CSS for all of LaunchPad (workspace). + * + * Optional key, like {@see self::setQuicksearchFallbackTarget()}. The + * value is the cleaned and scoped CSS the server stored; the page inserts + * it as the text of a style element, never as markup (REQ-THM-003). + * + * @param string $customCss The stored CSS, or '' for none. + * + * @return self Fluent. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + public function setCustomCss(string $customCss): self { + $this->values['customCss'] = $customCss; + return $this; + }//end setCustomCss() + + /** + * Push whether the organisation opted in to filter telemetry, so the + * dashboard's filter bus writes `filter_event` rows only when it did + * (drill-down-cross-widget-filter REQ-CWF-010). Optional key: the JS + * reader defaults to `false`. + * + * @param bool $enabled True when the administrator switched telemetry on. + * + * @return self Fluent. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-17 + */ + public function setFilterTelemetryEnabled(bool $enabled): self { + $this->values['filterTelemetryEnabled'] = $enabled; + return $this; + }//end setFilterTelemetryEnabled() + + /** + * Push both telemetry switches: whether the organisation opted in to + * filter telemetry (REQ-CWF-010) and whether the administrator switched + * dashboard view analytics on, so the page sends no view-event while it + * is off (REQ-ANLT-011). Optional keys: the JS reader defaults them to + * `false` and `true`. + * + * @param bool $filters True when filter telemetry is on. + * @param bool $views True when `analytics_enabled` is on. + * + * @return self Fluent. + * + * @spec openspec/specs/dashboard-view-analytics/spec.md + */ + public function setTelemetry(bool $filters, bool $views): self { + $this->values['analyticsEnabled'] = $views; + return $this->setFilterTelemetryEnabled(enabled: $filters); + }//end setTelemetry() + + /** + * Push what the Sharing tab may offer the viewer (REQ-SHARE-015): adding + * people or groups when they may share, a public link when they may share + * and public links are on. Optional key: the JS reader offers both. + * + * @param bool $mayShare Whether the viewer may share dashboards. + * @param bool $publicLinksAllowed Whether public links may be created. + * + * @return self Fluent. + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + public function setSharingPolicy(bool $mayShare, bool $publicLinksAllowed): self { + $this->values['sharingPolicy'] = ['mayShare' => $mayShare, 'publicLinksAllowed' => $publicLinksAllowed]; + return $this; + }//end setSharingPolicy() + + /** + * Set what the tile editor offers for program and single sign-on tiles + * (workspace): the schemes the administrator allowed, and the key and + * name of each launch template. The template addresses stay on the + * server, which resolves an sso tile's address itself. + * + * Optional keys, like {@see self::setQuicksearchFallbackTarget()}: the + * JS reader defaults both to an empty list. + * + * @param array<int, string> $schemes The allowed program schemes. + * @param array<int, mixed> $templates The launch templates (`key`, `name`, `urlTemplate`). + * + * @return self Fluent. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-4 + */ + public function setTileLaunchOptions(array $schemes, array $templates): self { + $this->values['tileAllowedSchemes'] = array_values($schemes); + $names = []; + foreach ($templates as $template) { + if (is_array($template) === true && isset($template['key'], $template['name']) === true) { + $names[] = ['key' => (string)$template['key'], 'name' => (string)$template['name']]; + } + } + + $this->values['ssoLaunchTemplates'] = $names; + return $this; + }//end setTileLaunchOptions() + + /** + * Set whether this request comes from inside the office networks. + * + * Optional key, like {@see self::setQuicksearchFallbackTarget()}: a + * server that never calls it leaves the JS reader's `false` default, so + * every tile opens its main address (launcher-tile-internal-address D1). + * + * @param bool $onOfficeNetwork True when the request address falls in an office network. + * + * @return self Fluent. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ + public function setOnOfficeNetwork(bool $onOfficeNetwork): self { + $this->values['onOfficeNetwork'] = $onOfficeNetwork; + return $this; + }//end setOnOfficeNetwork() + + /** + * Set whether Nextcloud Talk is enabled for the viewer (workspace). + * + * Optional key, like {@see self::setQuicksearchFallbackTarget()}: the JS + * reader's `false` default makes the Communities widget explain that Talk + * is needed instead of calling it (engagement-communities REQ-COMM-004). + * + * @param bool $talkEnabled True when Talk is enabled for the viewer. + * + * @return self Fluent. + * + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-without-talk-the-widget-explains-itself-req-comm-004 + */ + public function setTalkEnabled(bool $talkEnabled): self { + $this->values['talkEnabled'] = $talkEnabled; + return $this; + }//end setTalkEnabled() + + /** + * Set which apps behind the integration widgets are enabled for the + * viewer, by app id. The picker leaves out a widget whose app is not. + * A renamed fleet app answers with the id it is installed under. + * Optional key; the JS reader defaults to `{}`, which offers none of them. + * + * @param array<string, bool|string> $apps Whether each app is enabled, or its installed id. + * + * @return self Fluent. + * + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-picker-offers-the-wiki-only-where-it-can-work-req-wiki-004 + */ + public function setIntegrationApps(array $apps): self { + $this->values['integrationApps'] = $apps; + return $this; + }//end setIntegrationApps() + + /** + * Set the viewer's Nextcloud timezone (workspace). + * + * Optional key; the JS reader defaults to '', which makes a clock without + * its own zone follow the device (REQ-CLOCK-002). + * + * @param string $timezone The IANA timezone name, or ''. + * + * @return self Fluent. + * + * @spec openspec/specs/clock-weather-widgets/spec.md + */ + public function setUserTimezone(string $timezone): self { + $this->values['userTimezone'] = $timezone; + return $this; + }//end setUserTimezone() + + /** + * Set the footer the workspace shows below the grid and the viewer's + * Nextcloud language, which picks its variant (workspace). + * + * Optional keys; the JS reader defaults to null, which renders no + * footer, and to 'en' (REQ-FTR-001, REQ-FTR-006, REQ-FTR-007). + * + * @param array<string, mixed>|null $footer The resolved footer payload, or null. + * @param string $viewerLocale The viewer's language code, e.g. `nl`. + * + * @return self Fluent. + * + * @spec openspec/specs/footer-customization/spec.md + */ + public function setFooter(?array $footer, string $viewerLocale): self { + $this->values['effectiveFooter'] = $footer; + $this->values['viewerLocale'] = $viewerLocale; + return $this; + }//end setFooter() + + /** + * Set the Talk conversation tokens the organisation pinned (workspace). + * + * Optional key; the JS reader defaults to an empty list + * (engagement-communities REQ-COMM-003). + * + * @param array<int, string> $tokens The pinned tokens, in the order pinned. + * + * @return self Fluent. + * + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 + */ + public function setPinnedCommunities(array $tokens): self { + $this->values['pinnedCommunities'] = array_values($tokens); + return $this; + }//end setPinnedCommunities() + /** * Set every Nextcloud group (admin). * @@ -386,6 +698,20 @@ public function setLinkCreateFileExtensions(array $extensions): self { return $this; }//end setLinkCreateFileExtensions() + /** + * Set the token of the public link the start page shows (public-start page). + * + * @param string $token The public link's token. + * + * @return self Fluent. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-signed-out-visitors-land-on-the-start-page-req-psp-002 + */ + public function setPublicStartToken(string $token): self { + $this->values['publicStartToken'] = $token; + return $this; + }//end setPublicStartToken() + /** * Validate required keys then push every buffered pair plus the * schema version to {@see IInitialState::provideInitialState()}. @@ -410,7 +736,7 @@ public function apply(): void { } foreach ($this->values as $key => $value) { - $this->initialState->provideInitialState($key, $value); + $this->initialState->provideInitialState($key, $value ?? self::jsonNull()); } $this->initialState->provideInitialState( @@ -418,4 +744,29 @@ public function apply(): void { self::INITIAL_STATE_SCHEMA_VERSION ); }//end apply() + + /** + * A value that encodes as JSON `null`. Nextcloud's initial-state service + * drops a plain PHP `null` with a warning, so a key whose value is + * `null` (e.g. `allowedWidgets` when nothing is configured, REQ-RFP-010) + * would never reach the page. + * + * @return JsonSerializable The JSON null. + * + * @spec openspec/specs/role-feature-permissions/spec.md + */ + private static function jsonNull(): JsonSerializable { + return new class implements JsonSerializable { + /** + * The JSON value. + * + * @return null Always null. + * + * @spec openspec/specs/role-feature-permissions/spec.md + */ + public function jsonSerialize(): mixed { + return null; + }//end jsonSerialize() + }; + }//end jsonNull() }//end class diff --git a/lib/Service/InstalledShippedTemplate.php b/lib/Service/InstalledShippedTemplate.php new file mode 100644 index 000000000..39821a265 --- /dev/null +++ b/lib/Service/InstalledShippedTemplate.php @@ -0,0 +1,66 @@ +<?php + +/** + * InstalledShippedTemplate + * + * A shipped template definition and the dashboard it is installed as. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; + +/** + * The shipped definition of a template together with the template + * dashboard it is installed as. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ +final class InstalledShippedTemplate { + /** + * Constructor + * + * @param array<string, mixed> $definition The shipped definition. + * @param Dashboard $template The installed template dashboard. + */ + public function __construct( + public readonly array $definition, + public readonly Dashboard $template, + ) { + }//end __construct() + + /** + * The installed template's dashboard id. + * + * @return integer + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + public function dashboardId(): int { + return (int)$this->template->getId(); + }//end dashboardId() + + /** + * The shipped definition's version. + * + * @return integer + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + public function version(): int { + return (int)$this->definition['templateVersion']; + }//end version() +}//end class diff --git a/lib/Service/KioskPlaylistDraft.php b/lib/Service/KioskPlaylistDraft.php new file mode 100644 index 000000000..e51924755 --- /dev/null +++ b/lib/Service/KioskPlaylistDraft.php @@ -0,0 +1,44 @@ +<?php + +/** + * KioskPlaylistDraft + * + * The caller-supplied content of a kiosk playlist: its name, its raw + * entries and the requested refresh interval (REQ-KIOSK-002). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Name, raw entries and refresh interval of a playlist being created or + * updated. The entries are validated and the interval clamped by + * KioskService. + */ +final class KioskPlaylistDraft { + /** + * Constructor + * + * @param string $name The playlist name. + * @param array $entries Raw entries [{dashboardUuid, dwellSeconds}, ...]. + * @param int $refresh Requested refresh interval in seconds. + */ + public function __construct( + public readonly string $name, + public readonly array $entries, + public readonly int $refresh, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/KioskService.php b/lib/Service/KioskService.php index e05241963..549d108fe 100644 --- a/lib/Service/KioskService.php +++ b/lib/Service/KioskService.php @@ -32,11 +32,9 @@ use DateTime; use OCA\LaunchPad\Db\Dashboard; -use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\KioskPlaylist; -use OCA\LaunchPad\Db\KioskPlaylistMapper; -use OCA\LaunchPad\Db\WidgetPlacementMapper; use OCA\LaunchPad\Exception\PlaylistNotFoundException; +use OCA\LaunchPad\Kernel\Contracts\ConditionalServiceInterface; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\OCS\OCSForbiddenException; use OCP\IGroupManager; @@ -93,22 +91,18 @@ class KioskService { /** * Constructor. * - * @param KioskPlaylistMapper $playlistMapper Mapper for kiosk playlists. - * @param DashboardMapper $dashMapper Dashboard mapper for existence/ownership. - * @param PublicShareService $shareService Reused owner-or-admin authorization rule. - * @param IGroupManager $groupManager NC group manager for admin scoping. - * @param ISecureRandom $secureRandom CSPRNG for token generation. + * @param KioskStores $stores The playlist, dashboard and placement mappers and the share service. + * @param IGroupManager $groupManager NC group manager for admin scoping. + * @param ISecureRandom $secureRandom CSPRNG for token generation. * @param LoggerInterface $logger PSR-3 logger. - * @param WidgetPlacementMapper $placementMapper Placements of each played dashboard. + * @param ConditionalServiceInterface|null $visibility Applies the widget visibility rules. */ public function __construct( - private readonly KioskPlaylistMapper $playlistMapper, - private readonly DashboardMapper $dashMapper, - private readonly PublicShareService $shareService, + private readonly KioskStores $stores, private readonly IGroupManager $groupManager, private readonly ISecureRandom $secureRandom, private readonly LoggerInterface $logger, - private readonly WidgetPlacementMapper $placementMapper, + private readonly ?ConditionalServiceInterface $visibility = null, ) { }//end __construct() @@ -119,10 +113,8 @@ public function __construct( * (REQ-KIOSK-002): a single unauthorized dashboard rejects the whole * request. Dwell and refresh values are clamped before storage. * - * @param string $name Playlist name. - * @param array $entries Raw entries [{dashboardUuid, dwellSeconds}, ...]. - * @param int $refresh Requested refresh interval in seconds. - * @param string $callerId User ID of the creating user. + * @param KioskPlaylistDraft $draft Name, raw entries and refresh interval. + * @param string $callerId User ID of the creating user. * * @return KioskPlaylist The new playlist with URL populated. * @@ -130,20 +122,15 @@ public function __construct( * * @spec openspec/changes/dashboard-kiosk-mode/tasks.md#task-3 */ - public function createPlaylist( - string $name, - array $entries, - int $refresh, - string $callerId, - ): KioskPlaylist { + public function createPlaylist(KioskPlaylistDraft $draft, string $callerId): KioskPlaylist { $normalised = $this->validateAndNormaliseEntries( - entries: $entries, + entries: $draft->entries, callerId: $callerId ); $playlist = new KioskPlaylist(); // phpcs:disable CustomSn.Functions.NamedParameters -- Entity magic __call breaks with named args. - $playlist->setName($name); + $playlist->setName($draft->name); $playlist->setToken( $this->secureRandom->generate( length: 64, @@ -151,12 +138,12 @@ public function createPlaylist( ) ); $playlist->setEntries((string)json_encode($normalised)); - $playlist->setRefreshSeconds($this->clampRefresh(refresh: $refresh)); + $playlist->setRefreshSeconds($this->clampRefresh(refresh: $draft->refresh)); $playlist->setCreatedBy($callerId); $playlist->setCreatedAt((new DateTime())->format('Y-m-d H:i:s')); // phpcs:enable CustomSn.Functions.NamedParameters - $saved = $this->playlistMapper->insert(entity: $playlist); + $saved = $this->stores->playlistMapper->insert(entity: $playlist); $this->logger->debug( message: sprintf('launchpad: kiosk playlist created by %s', $callerId), @@ -174,10 +161,8 @@ public function createPlaylist( * unchanged and OCSForbiddenException is thrown. * * @param int $id Playlist primary key. - * @param string $name New playlist name. - * @param array $entries Raw entries [{dashboardUuid, dwellSeconds}, ...]. - * @param int $refresh Requested refresh interval in seconds. - * @param string $callerId Caller user ID. + * @param KioskPlaylistDraft $draft New name, raw entries and refresh interval. + * @param string $callerId Caller user ID. * * @return KioskPlaylist The updated playlist with URL populated. * @@ -186,28 +171,22 @@ public function createPlaylist( * * @spec openspec/changes/dashboard-kiosk-mode/tasks.md#task-3 */ - public function updatePlaylist( - int $id, - string $name, - array $entries, - int $refresh, - string $callerId, - ): KioskPlaylist { + public function updatePlaylist(int $id, KioskPlaylistDraft $draft, string $callerId): KioskPlaylist { $playlist = $this->resolveOwnedPlaylist(id: $id, callerId: $callerId); $normalised = $this->validateAndNormaliseEntries( - entries: $entries, + entries: $draft->entries, callerId: $callerId ); // phpcs:disable CustomSn.Functions.NamedParameters - $playlist->setName($name); + $playlist->setName($draft->name); $playlist->setEntries((string)json_encode($normalised)); - $playlist->setRefreshSeconds($this->clampRefresh(refresh: $refresh)); + $playlist->setRefreshSeconds($this->clampRefresh(refresh: $draft->refresh)); // phpcs:enable CustomSn.Functions.NamedParameters - $saved = $this->playlistMapper->update(entity: $playlist); - return $this->playlistMapper->findById(id: (int)$saved->getId()); + $saved = $this->stores->playlistMapper->update(entity: $playlist); + return $this->stores->playlistMapper->findById(id: (int)$saved->getId()); }//end updatePlaylist() /** @@ -224,10 +203,10 @@ public function updatePlaylist( */ public function listPlaylists(string $callerId): array { if ($this->groupManager->isAdmin(userId: $callerId) === true) { - return $this->playlistMapper->findAllActive(); + return $this->stores->playlistMapper->findAllActive(); } - return $this->playlistMapper->findByCreator(createdBy: $callerId); + return $this->stores->playlistMapper->findByCreator(createdBy: $callerId); }//end listPlaylists() /** @@ -248,7 +227,7 @@ public function listPlaylists(string $callerId): array { */ public function revokePlaylist(int $id, string $callerId): void { $playlist = $this->resolveOwnedPlaylist(id: $id, callerId: $callerId); - $this->playlistMapper->softRevoke(id: (int)$playlist->getId()); + $this->stores->playlistMapper->softRevoke(id: (int)$playlist->getId()); }//end revokePlaylist() /** @@ -270,36 +249,17 @@ public function revokePlaylist(int $id, string $callerId): void { */ public function renderPlaylist(string $token): array { try { - $playlist = $this->playlistMapper->findByToken(token: $token); + $playlist = $this->stores->playlistMapper->findByToken(token: $token); } catch (DoesNotExistException) { throw new PlaylistNotFoundException(); } $rendered = []; foreach ($playlist->getEntriesArray() as $entry) { - try { - $dashboard = $this->dashMapper->findByUuid( - uuid: $entry['dashboardUuid'] - ); - } catch (DoesNotExistException) { - // Dashboard deleted since the playlist was created — skip it. - continue; + $payload = $this->entryPayload(entry: $entry); + if ($payload !== null) { + $rendered[] = $payload; } - - // The screen shows the widgets, so each entry carries the - // dashboard's placements, as the public share render does. - $placements = $this->placementMapper->findByDashboardId( - dashboardId: (int)$dashboard->getId() - ); - - $rendered[] = [ - 'dwellSeconds' => $entry['dwellSeconds'], - 'dashboard' => $this->publicDashboardPayload(dashboard: $dashboard), - 'placements' => array_map( - callback: static fn ($placement) => $placement->jsonSerialize(), - array: $placements - ), - ]; } $descriptor = $playlist->jsonSerialize(); @@ -313,6 +273,104 @@ public function renderPlaylist(string $token): array { ]; }//end renderPlaylist() + /** + * Render one entry of a playlist, for the player to fetch just before it + * shows that entry (REQ-KIOSK-004). The dashboard must be an entry of + * the playlist the token names. + * + * @param string $token The playlist token. + * @param string $dashboardUuid The entry's dashboard UUID. + * + * @return array{dwellSeconds: int, dashboard: array, placements: array} The entry payload. + * + * @throws PlaylistNotFoundException When the token is unknown or revoked. + * @throws DoesNotExistException When the dashboard is not an entry, or was deleted. + * + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + public function renderEntry(string $token, string $dashboardUuid): array { + try { + $playlist = $this->stores->playlistMapper->findByToken(token: $token); + } catch (DoesNotExistException) { + throw new PlaylistNotFoundException(); + } + + foreach ($playlist->getEntriesArray() as $entry) { + if (($entry['dashboardUuid'] ?? null) !== $dashboardUuid) { + continue; + } + + $payload = $this->entryPayload(entry: $entry); + if ($payload !== null) { + return $payload; + } + } + + throw new DoesNotExistException(msg: 'Not an entry of this playlist'); + }//end renderEntry() + + /** + * The ids of the dashboards a playlist shows, leaving out deleted ones: + * a widget on the screen reads its data through the playlist's token + * (REQ-PSHR-011). + * + * @param string $token The playlist token. + * + * @return list<int> The entries' dashboard ids. + * + * @throws PlaylistNotFoundException When the token is unknown or revoked. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + public function playlistDashboardIds(string $token): array { + try { + $playlist = $this->stores->playlistMapper->findByToken(token: $token); + } catch (DoesNotExistException) { + throw new PlaylistNotFoundException(); + } + + $ids = []; + foreach ($playlist->getEntriesArray() as $entry) { + try { + $ids[] = (int)$this->stores->dashMapper->findByUuid(uuid: (string)($entry['dashboardUuid'] ?? ''))->getId(); + } catch (DoesNotExistException) { + continue; + } + } + + return array_values(array_unique($ids)); + }//end playlistDashboardIds() + + /** + * The read-only render payload of one playlist entry, or null when its + * dashboard was deleted since the playlist was made (REQ-KIOSK-003). + * + * @param array{dashboardUuid: string, dwellSeconds: int} $entry The stored entry. + * + * @return array{dwellSeconds: int, dashboard: array, placements: array}|null The payload. + */ + private function entryPayload(array $entry): ?array { + try { + $dashboard = $this->stores->dashMapper->findByUuid(uuid: $entry['dashboardUuid']); + } catch (DoesNotExistException) { + return null; + } + + // The screen shows the widgets, so each entry carries the + // dashboard's placements, as the public share render does. + $placements = array_map( + callback: static fn ($placement) => $placement->jsonSerialize(), + array: $this->stores->placementMapper->findByDashboardId(dashboardId: (int)$dashboard->getId()) + ); + + return [ + 'dwellSeconds' => $entry['dwellSeconds'], + 'dashboard' => $this->publicDashboardPayload(dashboard: $dashboard), + // A screen has no viewer who can edit, so a widget the rules hide is left out (REQ-VIS-013). + 'placements' => ($this->visibility?->visiblePlacements(placements: $placements, userId: '', canEdit: false) ?? $placements), + ]; + }//end entryPayload() + /** * Validate and normalise raw playlist entries. * @@ -341,7 +399,7 @@ private function validateAndNormaliseEntries(array $entries, string $callerId): } try { - $dashboard = $this->dashMapper->findByUuid(uuid: $uuid); + $dashboard = $this->stores->dashMapper->findByUuid(uuid: $uuid); } catch (DoesNotExistException) { // Treat a missing dashboard as a permission failure to avoid // leaking which UUIDs exist (matches public-share 404/403 model). @@ -351,7 +409,7 @@ private function validateAndNormaliseEntries(array $entries, string $callerId): // Reuse the dashboard-public-share owner-or-admin rule: the // playlist token grants anonymous read, so the caller must be // allowed to share each dashboard (REQ-PSHR-001). - $this->shareService->authorizeShareMutation( + $this->stores->shareService->authorizeShareMutation( dashboard: $dashboard, userId: $callerId ); @@ -383,7 +441,7 @@ private function validateAndNormaliseEntries(array $entries, string $callerId): */ private function resolveOwnedPlaylist(int $id, string $callerId): KioskPlaylist { try { - $playlist = $this->playlistMapper->findById(id: $id); + $playlist = $this->stores->playlistMapper->findById(id: $id); } catch (DoesNotExistException) { throw new PlaylistNotFoundException(); } diff --git a/lib/Service/KioskStores.php b/lib/Service/KioskStores.php new file mode 100644 index 000000000..9c9c6e5a1 --- /dev/null +++ b/lib/Service/KioskStores.php @@ -0,0 +1,51 @@ +<?php + +/** + * KioskStores + * + * Where kiosk playlists and the dashboards they show are stored. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\KioskPlaylistMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; + +/** + * Where kiosk playlists and the dashboards they show are stored. + * + * @spec openspec/specs/dashboards/spec.md + */ +class KioskStores { + /** + * Constructor. + * + * @param KioskPlaylistMapper $playlistMapper Mapper for kiosk playlists. + * @param DashboardMapper $dashMapper Dashboard mapper for existence/ownership. + * @param WidgetPlacementMapper $placementMapper Placements of each played dashboard. + * @param PublicShareService $shareService Reused owner-or-admin authorization rule. + */ + public function __construct( + public readonly KioskPlaylistMapper $playlistMapper, + public readonly DashboardMapper $dashMapper, + public readonly WidgetPlacementMapper $placementMapper, + public readonly PublicShareService $shareService, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/LeaverHandover.php b/lib/Service/LeaverHandover.php new file mode 100644 index 000000000..b5fe217f3 --- /dev/null +++ b/lib/Service/LeaverHandover.php @@ -0,0 +1,121 @@ +<?php + +/** + * LaunchPad Leaver Handover. + * + * Where a leaver's dashboards go (REQ-SHARE-016, board LpBeheerOnderhoud): + * their manager, otherwise a person the administrator names. Without the + * setting REQ-SHARE-012 applies unchanged. + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\AdminSettingKey; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCP\IUser; +use OCP\IUserManager; + +/** + * The leaver handover setting and the person a leaver's dashboards go to. + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ +class LeaverHandover { + + /** + * Constructor. + * + * @param AdminSettingMapper $settings Reads the setting. + * @param IUserManager $users Tells whether a manager or the named person still has an account. + * + * @return void + */ + public function __construct( + private readonly AdminSettingMapper $settings, + private readonly IUserManager $users, + ) { + }//end __construct() + + /** + * The stored setting: to the manager or not, and the person otherwise ('' for nobody). + * + * @return array{manager: bool, fallbackUid: string} + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + public function setting(): array { + return $this->normalise(value: $this->settings->getValue(key: AdminSettingKey::LEAVER_HANDOVER->value, default: null)); + }//end setting() + + /** + * A setting in its stored shape; anything else reads as not set. + * + * @param mixed $value The raw value. + * + * @return array{manager: bool, fallbackUid: string} + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + public function normalise(mixed $value): array { + if (is_array($value) === false) { + return ['manager' => false, 'fallbackUid' => '']; + } + + $fallback = $value['fallbackUid'] ?? ''; + if (is_string($fallback) === false) { + $fallback = ''; + } + + return [ + 'manager' => ($value['manager'] ?? false) === true, + 'fallbackUid' => trim(string: $fallback), + ]; + }//end normalise() + + /** + * Who the leaver's dashboards go to: their manager when that is set and + * the manager still has an account, else the named person when they + * still have one, else nobody (REQ-SHARE-012 applies). + * + * @param IUser $leaver The person being deleted, read before the account is gone. + * + * @return string|null The new owner's uid, or null. + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + public function targetFor(IUser $leaver): ?string { + $setting = $this->setting(); + $leaverId = $leaver->getUID(); + + $candidates = []; + if ($setting['manager'] === true) { + $candidates = array_map('strval', $leaver->getManagerUids()); + } + + $candidates[] = $setting['fallbackUid']; + foreach ($candidates as $uid) { + if ($uid !== '' && $uid !== $leaverId && $this->users->userExists(uid: $uid) === true) { + return $uid; + } + } + + return null; + }//end targetFor() + +}//end class diff --git a/lib/Service/LinksContentValidator.php b/lib/Service/LinksContentValidator.php new file mode 100644 index 000000000..8cd1511b0 --- /dev/null +++ b/lib/Service/LinksContentValidator.php @@ -0,0 +1,129 @@ +<?php + +/** + * LinksContentValidator + * + * Server-side validator for the `links` widget content blob. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * Validates `links` widget content before a placement is saved. + * + * Every link URL is required and must be an http(s) address, a root-relative + * path without `..`, or a single `../` step; anything else (`javascript:`, + * `data:`, `file:`, a `../` chain) is refused. The column count, when given, + * is a whole number from 1 to 6. + * + * @spec openspec/specs/links-widget/spec.md#requirement-req-lnks-007-url-sanitisation-and-validation + */ +class LinksContentValidator { + + /** + * The fewest columns the grid takes. + */ + private const MIN_COLUMNS = 1; + + /** + * The most columns the grid takes. + */ + private const MAX_COLUMNS = 6; + + /** + * Validate a links placement's content. + * + * @param array $content The placement content. + * + * @return void + * @throws InvalidArgumentException When a URL or the column count is refused. + * + * @spec openspec/specs/links-widget/spec.md#requirement-req-lnks-007-url-sanitisation-and-validation + */ + public function validate(array $content): void { + if (array_key_exists('columns', $content) === true) { + $this->checkColumns(columns: $content['columns']); + } + + $sections = ($content['sections'] ?? []); + if (is_array($sections) === false) { + throw new InvalidArgumentException(message: 'Sections must be a list'); + } + + foreach ($sections as $section) { + $links = []; + if (is_array($section) === true && is_array($section['links'] ?? null) === true) { + $links = $section['links']; + } + + foreach ($links as $link) { + $url = null; + if (is_array($link) === true) { + $url = ($link['url'] ?? null); + } + + $this->checkUrl(url: $url); + } + } + }//end validate() + + /** + * The column count is a whole number from 1 to 6. + * + * @param mixed $columns The `columns` value. + * + * @return void + * @throws InvalidArgumentException When it is out of range or not a whole number. + * + * @spec openspec/specs/links-widget/spec.md#requirement-req-lnks-006-multi-column-grid-layout + */ + private function checkColumns(mixed $columns): void { + $valid = filter_var( + $columns, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => self::MIN_COLUMNS, 'max_range' => self::MAX_COLUMNS]] + ); + if ($valid === false) { + throw new InvalidArgumentException(message: 'Columns must be a whole number from 1 to 6'); + } + }//end checkColumns() + + /** + * A link URL is required and must be http(s) or a safe relative path. + * + * @param mixed $url The link's `url` value. + * + * @return void + * @throws InvalidArgumentException When the URL is missing or unsafe. + * + * @spec openspec/specs/links-widget/spec.md#requirement-req-lnks-007-url-sanitisation-and-validation + */ + private function checkUrl(mixed $url): void { + if (is_string($url) === false || trim($url) === '') { + throw new InvalidArgumentException(message: 'Link URL is required'); + } + + $url = trim($url); + $safe = preg_match('#^https?://[^\s/]#i', $url) === 1 + || (preg_match('#^/(?![/\\\\])#', $url) === 1 && str_contains($url, '..') === false) + || (str_starts_with($url, '../') === true && str_contains(substr($url, 3), '..') === false); + if ($safe === false) { + throw new InvalidArgumentException(message: 'Invalid URL — use HTTP(S) or relative paths.'); + } + }//end checkUrl() +}//end class diff --git a/lib/Service/LiveTileListMapper.php b/lib/Service/LiveTileListMapper.php new file mode 100644 index 000000000..8ec586631 --- /dev/null +++ b/lib/Service/LiveTileListMapper.php @@ -0,0 +1,343 @@ +<?php + +/** + * LaunchPad LiveTileListMapper. + * + * Turns what a live tile's source returned into a list, a table or key-value + * pairs. The author maps up to six fields (a label, a path and a role: + * title, link, date or field); only those fields leave the server, and a + * list or table is cut to the tile's limit. A link that is not an https + * address is dropped. A tile without a display keeps its single value. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-mapping-happens-on-the-server-and-drops-unmapped-data-req-ltc-002 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use Closure; + +/** + * Validates a tile's display, mapping and limit, and maps a source node onto them. + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ +class LiveTileListMapper { + + /** + * Evaluates a `$.path` expression on one item, for the map() call in progress. + * + * @var Closure(mixed, string): mixed + */ + private Closure $extract; + + /** + * The displays a tile can have; `value` is the single value of old tiles. + * + * @var array<int,string> + */ + public const DISPLAYS = ['value', 'list', 'table', 'keyvalue']; + + /** + * What a mapped field is for. + * + * @var array<int,string> + */ + public const ROLES = ['title', 'link', 'date', 'field']; + + /** + * The most fields a tile maps. + * + * @var integer + */ + public const MAX_FIELDS = 6; + + /** + * The rows a list or table shows when the tile names no limit. + * + * @var integer + */ + public const DEFAULT_LIMIT = 10; + + /** + * The most rows a list or table shows. + * + * @var integer + */ + public const MAX_LIMIT = 50; + + /** + * The display a config asks for; a config without one shows a single value. + * + * @param array<string,mixed> $config The tile config. + * + * @return string One of DISPLAYS. + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + public function displayOf(array $config): string { + $display = ($config['display'] ?? 'value'); + if (is_string($display) === true && in_array($display, self::DISPLAYS, true) === true) { + return $display; + } + + return 'value'; + + }//end displayOf() + + /** + * The errors in a config's display, mapping and limit. An old config has none. + * + * @param array<string,mixed> $config The tile config. + * + * @return array<int,string> Error codes. + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + public function configErrors(array $config): array { + if (array_key_exists('display', $config) === true && $this->displayOf(config: $config) !== $config['display']) { + return ['invalid_display']; + } + + $errors = []; + if (array_key_exists('limit', $config) === true && $this->isValidLimit(limit: $config['limit']) === false) { + $errors[] = 'invalid_limit'; + } + + if ($this->displayOf(config: $config) === 'value') { + return $errors; + } + + $mapping = ($config['mapping'] ?? []); + if (is_array($mapping) === false || $mapping === []) { + $errors[] = 'mapping_required'; + return $errors; + } + + if (count($mapping) > self::MAX_FIELDS || $this->allFieldsValid(mapping: $mapping) === false) { + $errors[] = 'invalid_mapping'; + } + + return $errors; + + }//end configErrors() + + /** + * Map a source node onto the tile's display. + * + * @param mixed $node What the tile's expression selected. + * @param array<string,mixed> $config The tile config, already valid. + * @param callable $extract Evaluates a `$.path` expression on one item: fn (mixed $item, string $expr): mixed. + * + * @return array<string,mixed>|null `{items: [[{label, role, value}]]}` for a list or table, + * `{pairs: [{label, role, value}]}` for key-value, or null when the node does not fit. + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-mapping-happens-on-the-server-and-drops-unmapped-data-req-ltc-002 + */ + public function map(mixed $node, array $config, callable $extract): ?array { + if (is_array($node) === false) { + return null; + } + + $this->extract = Closure::fromCallable($extract); + $mapping = array_values((array)($config['mapping'] ?? [])); + if ($this->displayOf(config: $config) === 'keyvalue') { + return $this->pairsOf(node: $node, mapping: $mapping); + } + + return $this->itemsOf(node: $node, config: ['mapping' => $mapping] + $config); + + }//end map() + + /** + * A key-value display: one object's mapped fields; null for a list. + * + * @param array<mixed> $node What the tile's expression selected. + * @param array<int,array<string,mixed>> $mapping The mapping. + * + * @return array<string,mixed>|null + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-mapping-happens-on-the-server-and-drops-unmapped-data-req-ltc-002 + */ + private function pairsOf(array $node, array $mapping): ?array { + if (array_is_list($node) === true && $node !== []) { + return null; + } + + return ['pairs' => $this->mapItem(item: $node, mapping: $mapping)]; + + }//end pairsOf() + + /** + * A list or table display: the first rows of a list, each mapped; null for an object. + * + * @param array<mixed> $node What the tile's expression selected. + * @param array<string,mixed> $config The tile config, its mapping as a list. + * + * @return array<string,mixed>|null + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-mapping-happens-on-the-server-and-drops-unmapped-data-req-ltc-002 + */ + private function itemsOf(array $node, array $config): ?array { + if (array_is_list($node) === false) { + return null; + } + + $items = []; + foreach (array_slice($node, 0, $this->limitOf(config: $config)) as $item) { + $items[] = $this->mapItem(item: $item, mapping: $config['mapping']); + } + + return ['items' => $items]; + + }//end itemsOf() + + /** + * The rows a list or table shows. + * + * @param array<string,mixed> $config The tile config. + * + * @return integer + */ + private function limitOf(array $config): int { + if ($this->isValidLimit(limit: ($config['limit'] ?? null)) === false) { + return self::DEFAULT_LIMIT; + } + + return (int)$config['limit']; + + }//end limitOf() + + /** + * Whether a limit is a whole number from 1 to MAX_LIMIT. + * + * @param mixed $limit The limit. + * + * @return boolean + */ + private function isValidLimit(mixed $limit): bool { + if (is_int($limit) === false && (is_string($limit) === false || ctype_digit($limit) === false)) { + return false; + } + + return (int)$limit >= 1 && (int)$limit <= self::MAX_LIMIT; + + }//end isValidLimit() + + /** + * Whether every mapped field has a string label, a path and a known role. + * + * @param array<mixed> $mapping The mapping. + * + * @return boolean + */ + private function allFieldsValid(array $mapping): bool { + foreach ($mapping as $field) { + if (is_array($field) === false + || is_string($field['label'] ?? null) === false + || $this->expressionOf(path: ($field['path'] ?? null)) === null + || in_array(($field['role'] ?? null), self::ROLES, true) === false + ) { + return false; + } + } + + return true; + + }//end allFieldsValid() + + /** + * A mapping path as a `$.` expression: `name`, `.name`, `$.name` and `$name` all read `name`. + * + * @param mixed $path The mapped path. + * + * @return string|null The expression, or null when the path is not a usable string. + */ + private function expressionOf(mixed $path): ?string { + if (is_string($path) === false) { + return null; + } + + $path = ltrim(trim($path), '$'); + if ($path === '' || preg_match('/^(?:\.?[A-Za-z0-9_]+|\[\d+\])(?:\.[A-Za-z0-9_]+|\[\d+\])*$/', $path) !== 1) { + return null; + } + + if ($path[0] !== '.' && $path[0] !== '[') { + $path = '.'.$path; + } + + return '$'.$path; + + }//end expressionOf() + + /** + * One item's mapped fields, in mapping order. + * + * @param mixed $item One item of the source. + * @param array<int,array<string,mixed>> $mapping The mapping. + * + * @return array<int,array{label: string, role: string, value: string|int|float|bool|null}> + */ + private function mapItem(mixed $item, array $mapping): array { + $fields = []; + foreach ($mapping as $field) { + $expression = $this->expressionOf(path: ($field['path'] ?? null)); + $value = null; + if ($expression !== null) { + $value = $this->scalar(value: ($this->extract)($item, $expression)); + } + + if (($field['role'] ?? '') === 'link' && $this->isHttps(value: $value) === false) { + $value = null; + } + + $fields[] = ['label' => (string)($field['label'] ?? ''), 'role' => (string)($field['role'] ?? 'field'), 'value' => $value]; + } + + return $fields; + + }//end mapItem() + + /** + * A value a tile can show: a scalar, or null for anything nested. + * + * @param mixed $value The extracted value. + * + * @return string|integer|float|boolean|null + */ + private function scalar(mixed $value): string|int|float|bool|null { + if (is_scalar($value) === true) { + return $value; + } + + return null; + + }//end scalar() + + /** + * Whether a value is an https address. + * + * @param mixed $value The mapped link. + * + * @return boolean + */ + private function isHttps(mixed $value): bool { + return is_string($value) === true + && strtolower((string)parse_url($value, PHP_URL_SCHEME)) === 'https' + && (string)parse_url($value, PHP_URL_HOST) !== ''; + + }//end isHttps() +}//end class diff --git a/lib/Service/LiveTileService.php b/lib/Service/LiveTileService.php index 86b8fdf25..16f2f02f6 100644 --- a/lib/Service/LiveTileService.php +++ b/lib/Service/LiveTileService.php @@ -53,13 +53,9 @@ use OCA\LaunchPad\Db\WidgetPlacementMapper; use OCA\LaunchPad\Service\Connection\ConnectionReporter; use OCA\LaunchPad\Support\FleetAppId; -use OCP\App\IAppManager; -use OCP\Http\Client\IClientService; +use OCP\Http\Client\IResponse; use OCP\IAppConfig; use OCP\ICache; -use OCP\ICacheFactory; -use Psr\Container\ContainerInterface; -use Psr\Log\LoggerInterface; use Throwable; /** @@ -77,6 +73,8 @@ * @spec openspec/specs/live-data-tile-widget/spec.md */ class LiveTileService { + use ReadsJsonCache; + use ReadsPlacementContent; /** * Default value-cache TTL in seconds when a placement has no (or an @@ -87,6 +85,16 @@ class LiveTileService { */ public const DEFAULT_REFRESH_SECONDS = 300; + /** + * How long a reading stays in the cache, in seconds. Freshness is judged + * by the reading's own `fetchedAtTs` against the refresh interval; the + * entry outlives that interval so a failed refetch can still serve the + * last-known value as stale (REQ-LIVETILE-003). + * + * @var integer + */ + public const LAST_KNOWN_TTL_SECONDS = 86400; + /** * Minimum permitted refresh interval in seconds — any configured value * below this is clamped up (REQ-LIVETILE-002). @@ -169,33 +177,31 @@ class LiveTileService { */ private ?ICache $cache = null; + /** + * Maps a source node onto a list, table or key-value display. + * + * @var LiveTileListMapper + */ + private readonly LiveTileListMapper $lists; + /** * Constructor. * - * @param IAppManager $appManager Detects whether the connector leaf is enabled, - * under whichever id it registered. - * @param ContainerInterface $container App container used to optionally resolve - * Integriq's data-source service - * (REQ-LIVETILE-005 capability probe). - * @param IClientService $clientService HTTP client factory for the direct-URL fetch. - * @param ICacheFactory $cacheFactory Backing factory for the distributed value cache. - * @param IAppConfig $appConfig Admin config: allow-listed hosts. - * @param WidgetPlacementMapper $placementMapper Resolves placements by id. - * @param LoggerInterface $logger PSR logger. - * @param ConnectionReporter|null $connectionReporter Tells integriq what a direct-URL fetch met, or nothing when absent. + * @param ReadingSources $sources The app manager, container, HTTP client service and cache factory. + * @param LiveTileSettings $settings The app config and logger. + * @param WidgetPlacementMapper $placementMapper Resolves placements by id. + * @param ConnectionReporter|null $connectionReporter Tells integriq what a direct-URL fetch met, or + * nothing when absent. * * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md#requirement-req-lp-conn-003-launchpad-reports-what-its-outbound-calls-met */ public function __construct( - private readonly IAppManager $appManager, - private readonly ContainerInterface $container, - private readonly IClientService $clientService, - private readonly ICacheFactory $cacheFactory, - private readonly IAppConfig $appConfig, + private readonly ReadingSources $sources, + private readonly LiveTileSettings $settings, private readonly WidgetPlacementMapper $placementMapper, - private readonly LoggerInterface $logger, private readonly ?ConnectionReporter $connectionReporter = null, ) { + $this->lists = new LiveTileListMapper(); }//end __construct() /** @@ -217,31 +223,107 @@ public function resolveForPlacement(int $placementId): array { return ['error' => 'placement_not_found']; } - $config = $this->readPlacementConfig(placement: $placement); - $refresh = $this->clampRefresh(seconds: (int)($config['refresh'] ?? 0)); + return $this->valueFor(placementId: $placementId, config: $this->readPlacementConfig(placement: $placement)); + }//end resolveForPlacement() + /** + * Serve the cached value while it is inside the tile's refresh + * interval, otherwise fetch and cache a fresh one, falling back to + * the stale value or the null/stale shape when the fetch fails. + * + * @param integer $placementId The widget placement id. + * @param array<string,mixed> $config The placement's resolved config. + * + * @return array<string,mixed> `{value, formatted, badge, fetchedAt, stale}`. + */ + private function valueFor(int $placementId, array $config): array { $cacheKey = $this->buildCacheKey(placementId: $placementId, config: $config); $cache = $this->getCache(); $cached = $this->readCache(cache: $cache, cacheKey: $cacheKey); + if ($this->isFresh(cached: $cached, config: $config) === true) { + return $this->publicShape(reading: $cached, config: $config, stale: false); + } - if ($cached !== null) { - $age = (time() - (int)($cached['fetchedAtTs'] ?? 0)); - if ($age >= 0 && $age < $refresh) { - return $this->publicShape(reading: $cached, config: $config, stale: false); - } + $fresh = $this->mapped(reading: $this->fetchFresh(config: $config), config: $config); + if ($fresh === null) { + return $this->staleOrEmpty(cached: $cached, config: $config); } - $fresh = $this->fetchFresh(config: $config); + $fresh['fetchedAtTs'] = time(); + $cache?->set(key: $cacheKey, value: json_encode($fresh), ttl: max(self::LAST_KNOWN_TTL_SECONDS, $this->refreshOf(config: $config))); - if ($fresh !== null) { - $fresh['fetchedAtTs'] = time(); - if ($cache !== null) { - $cache->set(key: $cacheKey, value: json_encode($fresh), ttl: $refresh); - } + return $this->publicShape(reading: $fresh, config: $config, stale: false); + }//end valueFor() + + /** + * A reading in the shape that is cached: for a list, table or key-value + * tile only the mapped fields, so the raw response is neither cached nor + * sent to the browser (REQ-LTC-002). A single-value tile is unchanged. + * + * @param array<string,mixed>|null $reading The fresh reading, or null when the fetch failed. + * @param array<string,mixed> $config The tile config. + * + * @return array<string,mixed>|null The reading to cache, or null when it does not fit the display. + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-mapping-happens-on-the-server-and-drops-unmapped-data-req-ltc-002 + */ + private function mapped(?array $reading, array $config): ?array { + if ($reading === null || $this->lists->displayOf(config: $config) === 'value') { + return $reading; + } + + $mapped = $this->lists->map( + node: ($reading['rawValue'] ?? null), + config: $config, + extract: fn (mixed $item, string $expr): mixed => $this->extractValue(data: $item, expr: $expr) + ); + if ($mapped === null) { + return null; + } + + return ['rawValue' => null, 'mapped' => $mapped]; + }//end mapped() + + /** + * The tile's effective refresh interval in seconds. + * + * @param array<string,mixed> $config The placement's resolved config. + * + * @return integer The clamped interval. + */ + private function refreshOf(array $config): int { + return $this->clampRefresh(seconds: (int)($config['refresh'] ?? 0)); + }//end refreshOf() - return $this->publicShape(reading: $fresh, config: $config, stale: false); + /** + * Whether a cached reading exists and is younger than the tile's + * refresh interval; a future stamp counts as stale. + * + * @param array<string,mixed>|null $cached The cached reading, if any. + * @param array<string,mixed> $config The placement's resolved config. + * + * @return bool True when the cached reading may be served as fresh. + */ + private function isFresh(?array $cached, array $config): bool { + if ($cached === null) { + return false; } + $age = (time() - (int)($cached['fetchedAtTs'] ?? 0)); + + return $age >= 0 && $age < $this->refreshOf(config: $config); + }//end isFresh() + + /** + * Answer when the fetch failed: the previous value flagged stale, or + * the null/stale shape when there is none. + * + * @param array<string,mixed>|null $cached The cached reading, if any. + * @param array<string,mixed> $config The placement's resolved config. + * + * @return array<string,mixed> `{value, formatted, badge, fetchedAt, stale}`. + */ + private function staleOrEmpty(?array $cached, array $config): array { if ($cached !== null) { // Upstream failed (or the allow-list/capability probe refused // the fetch) but a previous value exists — degrade gracefully @@ -256,7 +338,7 @@ public function resolveForPlacement(int $placementId): array { 'fetchedAt' => null, 'stale' => true, ]; - }//end resolveForPlacement() + }//end staleOrEmpty() /** * Validate a candidate live-tile source config at save time @@ -270,38 +352,67 @@ public function resolveForPlacement(int $placementId): array { * @spec openspec/specs/live-data-tile-widget/spec.md */ public function validateSourceConfig(array $config): array { - $errors = []; $sourceMode = (string)($config['sourceMode'] ?? ''); if (in_array(needle: $sourceMode, haystack: ['connector', 'url'], strict: true) === false) { - $errors[] = 'invalid_source_mode'; - return $errors; + return ['invalid_source_mode']; } if ($sourceMode === 'url') { - $url = trim(string: (string)($config['url'] ?? '')); - if ($url === '') { - $errors[] = 'url_required'; - } elseif ($this->hasValidScheme(url: $url) === false) { - $errors[] = 'invalid_url'; - } elseif ($this->isHostAllowed(url: $url) === false) { - // FAIL-CLOSED (REQ-LIVETILE-002 "rejected at save time"). - $errors[] = 'host_not_allowed'; - } + $errors = $this->urlConfigErrors(url: trim(string: (string)($config['url'] ?? ''))); + } else { + $errors = $this->connectorConfigErrors(config: $config); } - if ($sourceMode === 'connector') { - if (trim(string: (string)($config['sourceId'] ?? '')) === '') { - $errors[] = 'source_id_required'; - } + // REQ-LTC-001: the display, mapping and limit, checked for both modes. + return array_merge($errors, $this->lists->configErrors(config: $config)); + }//end validateSourceConfig() - if ($this->isConnectorAvailable() === false) { - $errors[] = 'connector_unavailable'; - } + /** + * The save-time error for a `url`-mode source: missing, not http(s), + * or a host off the allow-list. + * + * @param string $url The trimmed configured URL. + * + * @return string[] At most one error code. + */ + private function urlConfigErrors(string $url): array { + if ($url === '') { + return ['url_required']; + } + + if (HostAllowList::hasHttpScheme(url: $url) === false) { + return ['invalid_url']; + } + + if ($this->isHostAllowed(url: $url) === false) { + // FAIL-CLOSED (REQ-LIVETILE-002 "rejected at save time"). + return ['host_not_allowed']; + } + + return []; + }//end urlConfigErrors() + + /** + * The save-time errors for a `connector`-mode source: a missing + * source id and an unavailable connector capability. + * + * @param array<string,mixed> $config The candidate config. + * + * @return string[] The error codes. + */ + private function connectorConfigErrors(array $config): array { + $errors = []; + if (trim(string: (string)($config['sourceId'] ?? '')) === '') { + $errors[] = 'source_id_required'; + } + + if ($this->isConnectorAvailable() === false) { + $errors[] = 'connector_unavailable'; } return $errors; - }//end validateSourceConfig() + }//end connectorConfigErrors() /** * Whether Integriq's `dashboard-http-datasource` capability is @@ -317,7 +428,7 @@ public function validateSourceConfig(array $config): array { public function isConnectorAvailable(): bool { try { $enabled = FleetAppId::isEnabledForUser( - appManager: $this->appManager, + appManager: $this->sources->appManager, canonical: self::CONNECTOR_APP ); if ($enabled === false) { @@ -325,12 +436,12 @@ public function isConnectorAvailable(): bool { } return FleetAppId::hasService( - container: $this->container, + container: $this->sources->container, canonical: self::CONNECTOR_APP, relative: self::CONNECTOR_DATASOURCE_SERVICE_CLASS ); } catch (Throwable $exception) { - $this->logger->info( + $this->settings->logger->info( message: 'LiveTileService: connector capability probe failed, treating as absent', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); @@ -374,8 +485,6 @@ private function fetchFresh(array $config): ?array { * @param array<string,mixed> $config The placement's resolved config (`sourceId`, `valueExpr`). * * @return array<string,mixed>|null `{rawValue: mixed}` or `null`. - * - * @SuppressWarnings(PHPMD.StaticAccess) FleetAppId is a stateless resolver. */ private function fetchFromConnector(array $config): ?array { if ($this->isConnectorAvailable() === false) { @@ -388,35 +497,65 @@ private function fetchFromConnector(array $config): ?array { return null; } - try { - $service = FleetAppId::getService( - container: $this->container, - canonical: self::CONNECTOR_APP, - relative: self::CONNECTOR_DATASOURCE_SERVICE_CLASS - ); - if ($service === null) { - return null; - } + return $this->connectorReading(result: $this->callConnector(sourceId: $sourceId, valueExpr: $valueExpr)); + }//end fetchFromConnector() + + /** + * The reading of a connector answer that carries a `value` key. + * + * @param mixed $result The connector's answer. + * + * @return array<string,mixed>|null `{rawValue: mixed}` or `null`. + */ + private function connectorReading(mixed $result): ?array { + if (is_array(value: $result) === false || array_key_exists(key: 'value', array: $result) === false) { + return null; + } + + return ['rawValue' => $result['value']]; + }//end connectorReading() - if (method_exists(object_or_class: $service, method: self::CONNECTOR_DATASOURCE_METHOD) === false) { + /** + * Call the connector's resolve method; null when the service or its + * method is absent, or the call fails (logged). + * + * @param string $sourceId The connector source id. + * @param string $valueExpr The value expression. + * + * @return mixed The connector's answer, or null. + */ + private function callConnector(string $sourceId, string $valueExpr): mixed { + try { + $service = $this->connectorService(); + if ($service === null || method_exists(object_or_class: $service, method: self::CONNECTOR_DATASOURCE_METHOD) === false) { return null; } - $result = $service->{self::CONNECTOR_DATASOURCE_METHOD}($sourceId, $valueExpr); + return $service->{self::CONNECTOR_DATASOURCE_METHOD}($sourceId, $valueExpr); } catch (Throwable $exception) { - $this->logger->info( + $this->settings->logger->info( message: 'LiveTileService: connector resolve call failed', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); return null; } + }//end callConnector() - if (is_array(value: $result) === false || array_key_exists(key: 'value', array: $result) === false) { - return null; - } - - return ['rawValue' => $result['value']]; - }//end fetchFromConnector() + /** + * The connector's datasource service, under whichever id the + * connector app is installed. + * + * @return object|null The service, or null when none resolves. + * + * @SuppressWarnings(PHPMD.StaticAccess) FleetAppId is a stateless resolver. + */ + private function connectorService(): ?object { + return FleetAppId::getService( + container: $this->sources->container, + canonical: self::CONNECTOR_APP, + relative: self::CONNECTOR_DATASOURCE_SERVICE_CLASS + ); + }//end connectorService() /** * Resolve via a server-side, allow-listed HTTP GET (REQ-LIVETILE-003). @@ -433,52 +572,103 @@ private function fetchFromConnector(array $config): ?array { */ private function fetchFromUrl(array $config): ?array { $url = trim(string: (string)($config['url'] ?? '')); - if ($url === '') { + if ($this->isFetchableUrl(url: $url) === false) { return null; } - if ($this->hasValidScheme(url: $url) === false) { + $response = $this->sendTileRequest(url: $url); + if ($response === null) { return null; } - if ($this->isHostAllowed(url: $url) === false) { - $this->logger->warning( - message: 'LiveTileService: host not on livetile_allowed_hosts, refusing fetch (fail-closed)', - context: ['app' => Application::APP_ID] - ); - $this->connectionReporter?->reportAllowListRefusal(key: ConnectionReporter::KEY_LIVE_TILES); + if ($this->acceptsStatus(status: (int)$response->getStatusCode(), url: $url) === false) { return null; } + return $this->valueFromBody(body: (string)$response->getBody(), config: $config); + }//end fetchFromUrl() + + /** + * Whether a configured URL may be fetched: non-empty, http(s), and on + * the allow-list. A host off the allow-list is logged and reported. + * + * @param string $url The trimmed configured URL. + * + * @return bool True when the GET may be sent. + */ + private function isFetchableUrl(string $url): bool { + if ($url === '' || HostAllowList::hasHttpScheme(url: $url) === false) { + return false; + } + + if ($this->isHostAllowed(url: $url) === false) { + $this->reportRefusedHost(); + return false; + } + + return true; + }//end isFetchableUrl() + + /** + * Log and report a fetch refused for a host off the allow-list. + * + * @return void + */ + private function reportRefusedHost(): void { + $this->settings->logger->warning( + message: 'LiveTileService: host not on livetile_allowed_hosts, refusing fetch (fail-closed)', + context: ['app' => Application::APP_ID] + ); + $this->connectionReporter?->reportAllowListRefusal(key: ConnectionReporter::KEY_LIVE_TILES); + }//end reportRefusedHost() + + /** + * Send the tile's GET; a transport failure is logged, reported without + * a status and answered with null. + * + * @param string $url The allow-listed URL. + * + * @return IResponse|null The response, or null when the call failed. + */ + private function sendTileRequest(string $url): ?IResponse { try { - $client = $this->clientService->newClient(); - $response = $client->get( - uri: $url, - options: [ - 'connect_timeout' => self::CONNECT_TIMEOUT, - 'timeout' => self::REQUEST_TIMEOUT, - 'http_errors' => false, - // No auto-redirect — a 3xx to an unexpected host would - // bypass the allow-list check above. - 'allow_redirects' => false, - ] - ); + $client = $this->sources->clientService->newClient(); + return (new NoRedirectGet(connectTimeout: self::CONNECT_TIMEOUT, timeout: self::REQUEST_TIMEOUT)) + ->send(client: $client, url: $url); } catch (Throwable $exception) { - $this->logger->info( + $this->settings->logger->info( message: 'LiveTileService: direct-URL fetch failed', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_LIVE_TILES, url: $url, httpStatus: null); return null; } + }//end sendTileRequest() - $status = (int)$response->getStatusCode(); + /** + * Report the call with its status, then tell whether the status is 2xx. + * + * @param integer $status The HTTP status. + * @param string $url The URL called. + * + * @return bool True for a 2xx status. + */ + private function acceptsStatus(int $status, string $url): bool { $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_LIVE_TILES, url: $url, httpStatus: $status); - if ($status < 200 || $status >= 300) { - return null; - } - $decoded = json_decode(json: (string)$response->getBody(), associative: true); + return $status >= 200 && $status < 300; + }//end acceptsStatus() + + /** + * Decode a response body and extract the tile's value from it. + * + * @param string $body The response body. + * @param array<string,mixed> $config The placement's resolved config (`valueExpr`). + * + * @return array<string,mixed>|null `{rawValue: mixed}` or `null`. + */ + private function valueFromBody(string $body, array $config): ?array { + $decoded = json_decode(json: $body, associative: true); if (is_array(value: $decoded) === false) { return null; } @@ -489,7 +679,7 @@ private function fetchFromUrl(array $config): ?array { } return ['rawValue' => $value]; - }//end fetchFromUrl() + }//end valueFromBody() /** * Extract a value from a decoded JSON structure via a JSONPath-lite @@ -519,19 +709,22 @@ private function extractValue(mixed $data, string $expr): mixed { return null; } + return $this->walkPath(data: $data, tokens: $tokens); + }//end extractValue() + + /** + * Follow path tokens down a decoded JSON tree; null as soon as a step + * meets a non-array or a missing key. + * + * @param mixed $data The decoded JSON value. + * @param array<int, array<int, string>> $tokens The tokenised path. + * + * @return mixed The value at the end of the path, or null. + */ + private function walkPath(mixed $data, array $tokens): mixed { $current = $data; foreach ($tokens as $token) { - // Alternation: a `[123]` match leaves group 1 as the empty - // string and fills group 2; a `.prop` match matches group 1 - // and omits group 2 entirely. Discriminate on group 2 — its - // presence is what actually distinguishes the two forms. - $indexToken = ($token[2] ?? ''); - - $key = $token[1]; - if ($indexToken !== '') { - $key = (int)$indexToken; - } - + $key = $this->tokenKey(token: $token); if (is_array(value: $current) === false || array_key_exists(key: $key, array: $current) === false) { return null; } @@ -540,7 +733,28 @@ private function extractValue(mixed $data, string $expr): mixed { } return $current; - }//end extractValue() + }//end walkPath() + + /** + * The array key one path token addresses: the integer of a `[123]` + * token, or the property name of a `.prop` token. + * + * @param array<int, string> $token One PREG_SET_ORDER match set. + * + * @return int|string The key. + */ + private function tokenKey(array $token): int|string { + // Alternation: a `[123]` match leaves group 1 as the empty + // string and fills group 2; a `.prop` match matches group 1 + // and omits group 2 entirely. Discriminate on group 2 — its + // presence is what actually distinguishes the two forms. + $indexToken = ($token[2] ?? ''); + if ($indexToken !== '') { + return (int)$indexToken; + } + + return $token[1]; + }//end tokenKey() /** * Split a JSONPath-lite path body into its `.prop` / `[index]` tokens. @@ -635,33 +849,65 @@ private function resolveBadge(mixed $value, array $badge): ?array { return null; } - $number = (float)$value; + return $this->badgeFor(number: (float)$value, sorted: $this->sortedThresholds(thresholds: $thresholds)); + }//end resolveBadge() + + /** + * The thresholds in ascending `max` order. + * + * @param array<int|string,mixed> $thresholds The configured thresholds. + * + * @return array<int,mixed> The sorted thresholds. + */ + private function sortedThresholds(array $thresholds): array { $sorted = $thresholds; usort( array: $sorted, callback: static fn (array $a, array $b): int => ((float)($a['max'] ?? 0)) <=> ((float)($b['max'] ?? 0)) ); + return $sorted; + }//end sortedThresholds() + + /** + * The badge of the first sorted threshold whose `max` the number does + * not exceed, else of the highest tier. + * + * @param float $number The numeric value. + * @param array<int,mixed> $sorted The thresholds in ascending `max` order. + * + * @return array<string,string>|null `{state, label}` or `null`. + */ + private function badgeFor(float $number, array $sorted): ?array { foreach ($sorted as $threshold) { if (is_array(value: $threshold) === false) { continue; } - $max = (float)($threshold['max'] ?? 0); - if ($number <= $max) { + if ($number <= (float)($threshold['max'] ?? 0)) { return $this->badgeShape(threshold: $threshold); } } - // Value exceeds every threshold — use the highest-max (last) - // threshold, which is conventionally the "alert" tier. + return $this->highestTierBadge(sorted: $sorted); + }//end badgeFor() + + /** + * The badge of the highest-max (last) threshold, used when the value + * exceeds every threshold; that tier is conventionally the "alert" one. + * + * @param array<int,mixed> $sorted The thresholds in ascending `max` order. + * + * @return array<string,string>|null `{state, label}` or `null`. + */ + private function highestTierBadge(array $sorted): ?array { $last = end($sorted); if (is_array(value: $last) === true) { return $this->badgeShape(threshold: $last); } return null; - }//end resolveBadge() + }//end highestTierBadge() /** * Shape one threshold entry into the public badge contract. @@ -682,85 +928,26 @@ private function badgeShape(array $threshold): array { }//end badgeShape() /** - * Validate a URL's scheme is `http` or `https`. - * - * @param string $url The URL to check. - * - * @return boolean - */ - private function hasValidScheme(string $url): bool { - $scheme = strtolower(string: (string)parse_url(url: $url, component: PHP_URL_SCHEME)); - return in_array(needle: $scheme, haystack: ['http', 'https'], strict: true); - }//end hasValidScheme() - - /** - * Check a URL's host against `livetile_allowed_hosts`. FAIL-CLOSED: an + * Check a URL's host against `livetile_allowed_hosts` and the allowed websites with + * purpose fetch (REQ-ASET-021). FAIL-CLOSED: an * empty, missing, or unparseable allow-list permits NO host — the * admin must explicitly opt hosts in. * * @param string $url The URL to check. * * @return boolean True only when the host is explicitly allow-listed. + * + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 */ private function isHostAllowed(string $url): bool { - $host = parse_url(url: $url, component: PHP_URL_HOST); - if (is_string(value: $host) === false || $host === '') { - return false; - } - - $raw = $this->appConfig->getValueString( - app: Application::APP_ID, - key: self::CONFIG_KEY_ALLOWED_HOSTS, - default: '' + $allowList = new HostAllowList( + appConfig: $this->settings->appConfig, + configKey: self::CONFIG_KEY_ALLOWED_HOSTS, + purpose: AllowedSitesService::PURPOSE_FETCH ); - - $decoded = json_decode(json: $raw, associative: true); - if (is_array(value: $decoded) === false || $decoded === []) { - // FAIL-CLOSED — no configured list means no host is allowed. - return false; - } - - $needle = strtolower(string: $host); - foreach ($decoded as $allowed) { - if (is_string(value: $allowed) === true && strtolower(string: $allowed) === $needle) { - return true; - } - } - - return false; + return $allowList->permits(url: $url); }//end isHostAllowed() - /** - * Read the placement's live-tile config, falling back to the legacy - * `style_config.content` slot for pre-column rows (mirrors - * {@see WeatherService::readPlacementConfig()}). - * - * @param object $placement The {@see \OCA\LaunchPad\Db\WidgetPlacement} entity. - * - * @return array<string,mixed> - */ - private function readPlacementConfig(object $placement): array { - if (method_exists(object_or_class: $placement, method: 'getContentArray') === true) { - $content = $placement->getContentArray(); - if (is_array(value: $content) === true && $content !== []) { - return $content; - } - } - - if (method_exists(object_or_class: $placement, method: 'getStyleConfigArray') === true) { - $legacy = $placement->getStyleConfigArray(); - if (isset($legacy['content']) === true && is_array(value: $legacy['content']) === true) { - return $legacy['content']; - } - - if (is_array(value: $legacy) === true) { - return $legacy; - } - } - - return []; - }//end readPlacementConfig() - /** * Shape an internal reading array (which also carries the internal * `fetchedAtTs` unix timestamp / `rawValue`) into the public response @@ -790,9 +977,30 @@ private function publicShape(array $reading, array $config, bool $stale): array 'badge' => $badge, 'fetchedAt' => (new DateTime('@' . $fetchedAtTs))->format(format: DATE_ATOM), 'stale' => $stale, - ]; + ] + $this->displayPart(reading: $reading, config: $config); }//end publicShape() + /** + * The display and its mapped rows or pairs, for a list, table or + * key-value tile; nothing for a single-value tile. Only the mapped data, + * never the raw node (REQ-LTC-001). + * + * @param array<string,mixed> $reading The internal reading. + * @param array<string,mixed> $config The placement's resolved config. + * + * @return array<string,mixed> + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-mapping-happens-on-the-server-and-drops-unmapped-data-req-ltc-002 + */ + private function displayPart(array $reading, array $config): array { + $display = $this->lists->displayOf(config: $config); + if ($display === 'value') { + return []; + } + + return ['display' => $display] + (array)($reading['mapped'] ?? []); + }//end displayPart() + /** * Build the value cache key — placement id + a hash of the resolved * config (proposal.md "Caching keyed on placement id + config hash"). @@ -806,34 +1014,6 @@ private function buildCacheKey(int $placementId, array $config): string { return 'value_' . $placementId . '_' . hash(algo: 'sha256', data: (string)json_encode($config)); }//end buildCacheKey() - /** - * Read + JSON-decode a cache entry. Returns `null` on a miss or a - * corrupt entry. - * - * @param ICache|null $cache The cache instance, or `null` when the cache - * subsystem is unavailable. - * @param string $cacheKey The cache key. - * - * @return array<string,mixed>|null - */ - private function readCache(?ICache $cache, string $cacheKey): ?array { - if ($cache === null) { - return null; - } - - $raw = $cache->get(key: $cacheKey); - if (is_string(value: $raw) === false) { - return null; - } - - $decoded = json_decode(json: $raw, associative: true); - if (is_array(value: $decoded) === true) { - return $decoded; - } - - return null; - }//end readCache() - /** * Lazily resolve the distributed cache. Returns `null` when the cache * subsystem is unavailable (e.g. unit tests with a stub factory). @@ -846,9 +1026,9 @@ private function getCache(): ?ICache { } try { - $this->cache = $this->cacheFactory->createDistributed(prefix: 'launchpad_livetile_'); + $this->cache = $this->sources->cacheFactory->createDistributed(prefix: 'launchpad_livetile_'); } catch (Throwable $exception) { - $this->logger->info( + $this->settings->logger->info( message: 'LiveTileService: cache subsystem unavailable, falling back to direct fetch', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); diff --git a/lib/Service/LiveTileSettings.php b/lib/Service/LiveTileSettings.php new file mode 100644 index 000000000..7c2be4f95 --- /dev/null +++ b/lib/Service/LiveTileSettings.php @@ -0,0 +1,46 @@ +<?php + +/** + * LiveTileSettings + * + * The app config and the logger of the live tile service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\IAppConfig; +use Psr\Log\LoggerInterface; + +/** + * The app config and the logger of the live tile service. + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ +class LiveTileSettings { + /** + * Constructor. + * + * @param IAppConfig $appConfig Admin config: allow-listed hosts. + * @param LoggerInterface $logger PSR logger. + */ + public function __construct( + public readonly IAppConfig $appConfig, + public readonly LoggerInterface $logger, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/LockDirectory.php b/lib/Service/LockDirectory.php new file mode 100644 index 000000000..497d187a3 --- /dev/null +++ b/lib/Service/LockDirectory.php @@ -0,0 +1,46 @@ +<?php + +/** + * LockDirectory + * + * The user and group managers of the lock service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboard-locking/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\IGroupManager; +use OCP\IUserManager; + +/** + * The user and group managers of the lock service. + * + * @spec openspec/specs/dashboard-locking/spec.md + */ +class LockDirectory { + /** + * Constructor. + * + * @param IUserManager $userManager Resolves display names for new locks. + * @param IGroupManager $groupManager Admin check for force-release. + */ + public function __construct( + public readonly IUserManager $userManager, + public readonly IGroupManager $groupManager, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/LockStore.php b/lib/Service/LockStore.php new file mode 100644 index 000000000..d2ae91bc1 --- /dev/null +++ b/lib/Service/LockStore.php @@ -0,0 +1,47 @@ +<?php + +/** + * LockStore + * + * The lock mapper and the logger of the lock service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboard-locking/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardLockMapper; +use Psr\Log\LoggerInterface; + +/** + * The lock mapper and the logger of the lock service. + * + * @spec openspec/specs/dashboard-locking/spec.md + */ +class LockStore { + /** + * Constructor. + * + * @param DashboardLockMapper $lockMapper The lock mapper. + * @param LoggerInterface $logger PSR logger — used for the force-release audit trail (REQ-LOCK-006, + * design D4). + */ + public function __construct( + public readonly DashboardLockMapper $lockMapper, + public readonly LoggerInterface $logger, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/MapContentValidator.php b/lib/Service/MapContentValidator.php new file mode 100644 index 000000000..9e55934ec --- /dev/null +++ b/lib/Service/MapContentValidator.php @@ -0,0 +1,218 @@ +<?php + +/** + * MapContentValidator + * + * Server-side validator for the `map` widget content blob, against the + * shape the shared map widget (CnMapWidget) reads. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * Validates `map` widget content before a placement is saved. + * + * A map of `layers` only, or of inline or `url` markers, needs no register. + * What is checked is what would draw a wrong or empty map without an error: + * a register source missing its register or schema, a spatial filter that + * does not read (OpenRegister would answer 422 and the map would stay + * empty), a spatial filter without a register source to narrow, and a + * detail link with an unsafe scheme. + * + * @spec openspec/changes/map-support/tasks.md#backend + */ +class MapContentValidator { + + /** + * Validate a map placement's content. + * + * @param array $content The placement content. + * + * @return void + * @throws InvalidArgumentException When the content would draw a wrong map. + * + * @spec openspec/changes/map-support/tasks.md#backend + */ + public function validate(array $content): void { + $markers = ($content['markers'] ?? null); + if (is_array($markers) === false) { + return; + } + + $this->checkDetailLink(link: ($markers['detailLink'] ?? null)); + $this->checkGeoProperty(property: ($markers['geoProperty'] ?? null)); + + $source = ($markers['dataSource'] ?? null); + if (is_array($source) === false) { + return; + } + + $this->checkRegisterSource(source: $source); + if (isset($source['spatialFilter']) === true) { + $this->checkSpatialFilter(filter: $source['spatialFilter']); + } + }//end validate() + + /** + * A register source names both its register and its schema, and a + * spatial filter needs one. + * + * @param array $source The `markers.dataSource` block. + * + * @return void + * @throws InvalidArgumentException When half a register source is given. + * + * @spec openspec/changes/map-support/tasks.md#backend + */ + private function checkRegisterSource(array $source): void { + $hasRegister = (isset($source['register']) === true && $source['register'] !== ''); + $hasSchema = (isset($source['schema']) === true && $source['schema'] !== ''); + if ($hasRegister !== $hasSchema) { + throw new InvalidArgumentException(message: 'A map source needs both a register and a schema'); + } + + if (isset($source['spatialFilter']) === true && $hasRegister === false) { + throw new InvalidArgumentException(message: 'A spatial filter needs a register and schema source'); + } + }//end checkRegisterSource() + + /** + * A spatial filter is exactly one readable bbox, radius or polygon. + * + * @param mixed $filter The `spatialFilter` block. + * + * @return void + * @throws InvalidArgumentException When the filter does not read. + * + * @spec openspec/changes/map-support/tasks.md#backend + */ + private function checkSpatialFilter(mixed $filter): void { + if (is_array($filter) === false) { + throw new InvalidArgumentException(message: 'A spatial filter must be an object'); + } + + $kinds = array_values(array_intersect(['bbox', 'near', 'within'], array_keys($filter))); + if (count($kinds) !== 1) { + throw new InvalidArgumentException(message: 'A spatial filter has exactly one of bbox, near or within'); + } + + $valid = match ($kinds[0]) { + 'bbox' => $this->isBbox(bbox: $filter['bbox']), + 'near' => $this->isPoint(point: $filter['near']) && is_numeric($filter['radius'] ?? null) && (float) $filter['radius'] > 0, + default => $this->isPolygon(geometry: $filter['within']), + }; + if ($valid === false) { + throw new InvalidArgumentException(message: 'The spatial filter '.$kinds[0].' does not read'); + } + }//end checkSpatialFilter() + + /** + * Whether a value is `[west, south, east, north]` in degrees, west of east and south of north. + * + * @param mixed $bbox The value. + * + * @return bool + */ + private function isBbox(mixed $bbox): bool { + if (is_array($bbox) === false || count($bbox) !== 4 || $this->allNumeric(values: $bbox) === false) { + return false; + } + + [$west, $south, $east, $north] = array_map(floatval(...), array_values($bbox)); + return $this->isPoint(point: [$west, $south]) && $this->isPoint(point: [$east, $north]) && $west < $east && $south < $north; + }//end isBbox() + + /** + * Whether a value is `[lon, lat]` in degrees. + * + * @param mixed $point The value. + * + * @return bool + */ + private function isPoint(mixed $point): bool { + if (is_array($point) === false || count($point) !== 2 || $this->allNumeric(values: $point) === false) { + return false; + } + + [$lon, $lat] = array_map(floatval(...), array_values($point)); + return abs($lon) <= 180 && abs($lat) <= 90; + }//end isPoint() + + /** + * Whether a value is a GeoJSON Polygon or MultiPolygon with coordinates. + * + * @param mixed $geometry The value. + * + * @return bool + */ + private function isPolygon(mixed $geometry): bool { + return is_array($geometry) === true + && in_array(needle: ($geometry['type'] ?? null), haystack: ['Polygon', 'MultiPolygon'], strict: true) === true + && is_array($geometry['coordinates'] ?? null) === true + && $geometry['coordinates'] !== []; + }//end isPolygon() + + /** + * Whether every value is a number. + * + * @param array $values The values. + * + * @return bool + */ + private function allNumeric(array $values): bool { + return array_filter($values, static fn (mixed $value): bool => is_numeric($value) === false) === []; + }//end allNumeric() + + /** + * A detail link is a string, an app path or an http(s) address. + * + * @param mixed $link The `markers.detailLink` value. + * + * @return void + * @throws InvalidArgumentException When it is not. + * + * @spec openspec/changes/map-support/tasks.md#backend + */ + private function checkDetailLink(mixed $link): void { + if ($link === null || $link === '') { + return; + } + + $safe = is_string($link) === true + && (preg_match('#^/(?![/\\\\])#', $link) === 1 || preg_match('#^https?://#i', $link) === 1); + if ($safe === false) { + throw new InvalidArgumentException(message: 'A detail link must be an app path or an http(s) address'); + } + }//end checkDetailLink() + + /** + * A geo property is a property name. + * + * @param mixed $property The `markers.geoProperty` value. + * + * @return void + * @throws InvalidArgumentException When it is not a non-empty string. + * + * @spec openspec/changes/map-support/tasks.md#backend + */ + private function checkGeoProperty(mixed $property): void { + if ($property !== null && (is_string($property) === false || $property === '')) { + throw new InvalidArgumentException(message: 'The geo property must be a property name'); + } + }//end checkGeoProperty() +}//end class diff --git a/lib/Service/MetadataService.php b/lib/Service/MetadataService.php index 9bd7a03ef..da752f4ce 100644 --- a/lib/Service/MetadataService.php +++ b/lib/Service/MetadataService.php @@ -53,6 +53,15 @@ class MetadataService { */ private const MAX_KEY_LENGTH = 64; + /** + * How `created_at` / `updated_at` are written. Both columns are + * DATETIME; MySQL and MariaDB strict mode refuse ISO-8601 with a `T` + * and an offset ('c'), so a field could not be defined there at all. + * + * @var string + */ + private const DB_DATETIME = 'Y-m-d H:i:s'; + /** * Maximum label length (matches schema column). * @@ -108,9 +117,9 @@ public function getField(int $id): MetadataField { * @param string $key The slugified key. * @param string $label The display label. * @param string $type One of {@see MetadataField::VALID_TYPES}. - * @param array<int, string>|null $options Option set (select types only). - * @param int $required 0 / 1. - * @param int $sortOrder UI sort order. + * @param array $settings Optional `options` (the option set, select + * types only; null), `required` (0 / 1; 0) and + * `sortOrder` (UI sort order; 0). * * @return MetadataField The persisted entity. * @@ -118,14 +127,9 @@ public function getField(int $id): MetadataField { * * @spec openspec/specs/dashboard-metadata-fields/spec.md */ - public function createFieldDefinition( - string $key, - string $label, - string $type, - ?array $options = null, - int $required = 0, - int $sortOrder = 0, - ): MetadataField { + public function createFieldDefinition(string $key, string $label, string $type, array $settings=[]): MetadataField { + $settings += ['options' => null, 'required' => 0, 'sortOrder' => 0]; + $options = $settings['options']; self::assertKeyShape(key: $key); self::assertLabelShape(label: $label); self::assertTypeShape(type: $type); @@ -140,10 +144,10 @@ public function createFieldDefinition( // Expected — key is free. } - $now = (new DateTime())->format(format: 'c'); + $now = (new DateTime())->format(format: self::DB_DATETIME); $field = new MetadataField(); $requiredFlag = 0; - if ($required === 1) { + if ($settings['required'] === 1) { $requiredFlag = 1; } @@ -155,7 +159,7 @@ public function createFieldDefinition( $field->setLabel($label); $field->setType($type); $field->setRequired($requiredFlag); - $field->setSortOrder($sortOrder); + $field->setSortOrder($settings['sortOrder']); $field->setCreatedAt($now); $field->setUpdatedAt($now); // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters @@ -190,43 +194,107 @@ public function updateFieldDefinition(int $id, array $patch): MetadataField { $field = $this->fieldMapper->findById(id: $id); + self::patchLabel(field: $field, patch: $patch); + self::patchSortOrder(field: $field, patch: $patch); + self::patchRequired(field: $field, patch: $patch); + self::patchOptions(field: $field, patch: $patch); + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters - if (array_key_exists(key: 'label', array: $patch) === true) { - $label = (string)$patch['label']; - self::assertLabelShape(label: $label); - $field->setLabel($label); - } + $field->setUpdatedAt((new DateTime())->format(format: self::DB_DATETIME)); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters - if (array_key_exists(key: 'sortOrder', array: $patch) === true) { - $field->setSortOrder((int)$patch['sortOrder']); + return $this->fieldMapper->update(entity: $field); + }//end updateFieldDefinition() + + /** + * Apply a patched `label`, validating its length first. + * + * @param MetadataField $field The field being patched. + * @param array<string, mixed> $patch The shallow patch. + * + * @return void + * + * @throws InvalidMetadataFieldException When the label is malformed. + */ + private static function patchLabel(MetadataField $field, array $patch): void { + if (array_key_exists(key: 'label', array: $patch) === false) { + return; } - if (array_key_exists(key: 'required', array: $patch) === true) { - $required = 0; - if ((int)$patch['required'] === 1) { - $required = 1; - } + $label = (string)$patch['label']; + self::assertLabelShape(label: $label); + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $field->setLabel($label); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + }//end patchLabel() - $field->setRequired($required); + /** + * Apply a patched `sortOrder`. + * + * @param MetadataField $field The field being patched. + * @param array<string, mixed> $patch The shallow patch. + * + * @return void + */ + private static function patchSortOrder(MetadataField $field, array $patch): void { + if (array_key_exists(key: 'sortOrder', array: $patch) === false) { + return; } - if (array_key_exists(key: 'options', array: $patch) === true) { - $options = $patch['options']; - if ($options !== null && is_array($options) === false) { - throw new InvalidMetadataFieldException( - message: 'Options must be an array of strings or null' - ); - } + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $field->setSortOrder((int)$patch['sortOrder']); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + }//end patchSortOrder() - self::assertOptionsShape(type: $field->getType(), options: $options); - $field->setOptionsArray(options: $options); + /** + * Apply a patched `required` flag: 1 only for a value that casts to 1. + * + * @param MetadataField $field The field being patched. + * @param array<string, mixed> $patch The shallow patch. + * + * @return void + */ + private static function patchRequired(MetadataField $field, array $patch): void { + if (array_key_exists(key: 'required', array: $patch) === false) { + return; } - $field->setUpdatedAt((new DateTime())->format(format: 'c')); + $required = 0; + if ((int)$patch['required'] === 1) { + $required = 1; + } + + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $field->setRequired($required); // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + }//end patchRequired() - return $this->fieldMapper->update(entity: $field); - }//end updateFieldDefinition() + /** + * Apply patched `options`, which must be an array or null and fit the + * field's type. + * + * @param MetadataField $field The field being patched. + * @param array<string, mixed> $patch The shallow patch. + * + * @return void + * + * @throws InvalidMetadataFieldException When the options do not fit. + */ + private static function patchOptions(MetadataField $field, array $patch): void { + if (array_key_exists(key: 'options', array: $patch) === false) { + return; + } + + $options = $patch['options']; + if ($options !== null && is_array($options) === false) { + throw new InvalidMetadataFieldException( + message: 'Options must be an array of strings or null' + ); + } + + self::assertOptionsShape(type: $field->getType(), options: $options); + $field->setOptionsArray(options: $options); + }//end patchOptions() /** * Delete a field definition (REQ-MDFL-003). @@ -328,52 +396,43 @@ public function setMetadataForDashboard( string $dashboardUuid, array $keyValues, ): array { + $writer = new MetadataValueWriter(valueMapper: $this->valueMapper, dashboardUuid: $dashboardUuid); foreach ($keyValues as $key => $value) { - $stringKey = (string)$key; - if ($stringKey === '') { - throw new InvalidMetadataFieldException( - message: 'Metadata keys must be non-empty strings' - ); - } - - try { - $field = $this->fieldMapper->findByKey(key: $stringKey); - } catch (DoesNotExistException) { - throw new InvalidMetadataFieldException( - message: "Unknown metadata field '" . $stringKey . "'" - ); - } - + $field = $this->fieldForKey(key: (string)$key); $encoded = $this->validationService->validateValue( value: $value, field: $field ); + $writer->write(field: $field, encoded: $encoded); + } - if ($encoded === '' && $field->getRequired() === 0) { - // Empty optional value: remove the row so the read - // payload omits the key (matches scenario "omitted - // keys are not deleted" by allowing explicit empty - // to clear the value — keeps client UX coherent). - $existing = $this->valueMapper->findOne( - dashboardUuid: $dashboardUuid, - fieldId: (int)$field->getId() - ); - if ($existing !== null) { - $this->valueMapper->delete(entity: $existing); - } - - continue; - } + return $this->getMetadataForDashboard(dashboardUuid: $dashboardUuid); + }//end setMetadataForDashboard() - $this->valueMapper->upsert( - dashboardUuid: $dashboardUuid, - fieldId: (int)$field->getId(), - value: $encoded + /** + * The field definition a metadata key names. + * + * @param string $key The metadata key. + * + * @return MetadataField The field. + * + * @throws InvalidMetadataFieldException When the key is empty or unknown. + */ + private function fieldForKey(string $key): MetadataField { + if ($key === '') { + throw new InvalidMetadataFieldException( + message: 'Metadata keys must be non-empty strings' ); - }//end foreach + } - return $this->getMetadataForDashboard(dashboardUuid: $dashboardUuid); - }//end setMetadataForDashboard() + try { + return $this->fieldMapper->findByKey(key: $key); + } catch (DoesNotExistException) { + throw new InvalidMetadataFieldException( + message: "Unknown metadata field '" . $key . "'" + ); + } + }//end fieldForKey() /** * Apply `?metadata.<key>=…` filters to a dashboard list @@ -550,21 +609,46 @@ private static function selectDashboardsByUuid( * @return string|null The UUID or null when unresolvable. */ private static function extractUuid(mixed $dashboard): ?string { - if (is_object($dashboard) === true && method_exists($dashboard, 'getUuid') === true) { - $uuid = $dashboard->getUuid(); - if ($uuid === null) { - return null; - } + // An Entity's getUuid() is a magic getter, which is_callable() sees + // and method_exists() does not. + if (is_object($dashboard) === true && is_callable([$dashboard, 'getUuid']) === true) { + return self::entityUuid(dashboard: $dashboard); + } + + return self::rowUuid(dashboard: $dashboard); + }//end extractUuid() - return (string)$uuid; + /** + * The UUID of a dashboard entity, null when it has none. + * + * @param object $dashboard An object exposing `getUuid()`. + * + * @return string|null The UUID, or null. + */ + private static function entityUuid(object $dashboard): ?string { + $uuid = $dashboard->getUuid(); + if ($uuid === null) { + return null; } + return (string)$uuid; + }//end entityUuid() + + /** + * The `uuid` of a serialised dashboard row, null when it is not a row + * carrying one. + * + * @param mixed $dashboard The candidate row. + * + * @return string|null The UUID, or null. + */ + private static function rowUuid(mixed $dashboard): ?string { if (is_array($dashboard) === true && array_key_exists(key: 'uuid', array: $dashboard) === true) { return (string)$dashboard['uuid']; } return null; - }//end extractUuid() + }//end rowUuid() /** * Per-criterion match logic. @@ -633,19 +717,7 @@ private static function matchesNumberRange(string $stored, mixed $criterion): bo $value = (float)$stored; if (is_array($criterion) === true) { - if (array_key_exists(key: 'min', array: $criterion) === true - && $value < (float)$criterion['min'] - ) { - return false; - } - - if (array_key_exists(key: 'max', array: $criterion) === true - && $value > (float)$criterion['max'] - ) { - return false; - } - - return true; + return self::withinNumberRange(value: $value, range: $criterion); } if (is_numeric(value: $criterion) === false) { @@ -655,6 +727,31 @@ private static function matchesNumberRange(string $stored, mixed $criterion): bo return ($value === (float)$criterion); }//end matchesNumberRange() + /** + * Whether a number lies inside an inclusive `min` / `max` range; + * a missing bound does not limit. + * + * @param float $value The stored number. + * @param array<string, mixed> $range The `min` / `max` criterion. + * + * @return bool True when inside the range. + */ + private static function withinNumberRange(float $value, array $range): bool { + if (array_key_exists(key: 'min', array: $range) === true + && $value < (float)$range['min'] + ) { + return false; + } + + if (array_key_exists(key: 'max', array: $range) === true + && $value > (float)$range['max'] + ) { + return false; + } + + return true; + }//end withinNumberRange() + /** * Date range filter — supports `after` / `before` (inclusive) or * exact-match. @@ -666,29 +763,57 @@ private static function matchesNumberRange(string $stored, mixed $criterion): bo */ private static function matchesDateRange(string $stored, mixed $criterion): bool { if (is_array($criterion) === true) { - if (array_key_exists(key: 'after', array: $criterion) === true - && strcmp( - string1: $stored, - string2: (string)$criterion['after'] - ) < 0 - ) { - return false; - } + return self::withinDateRange(stored: $stored, range: $criterion); + } - if (array_key_exists(key: 'before', array: $criterion) === true - && strcmp( - string1: $stored, - string2: (string)$criterion['before'] - ) > 0 - ) { - return false; - } + return ($stored === (string)$criterion); + }//end matchesDateRange() + /** + * Whether an ISO-8601 date lies inside an inclusive `after` / `before` + * range; a missing bound does not limit. + * + * @param string $stored The persisted ISO-8601 date. + * @param array<string, mixed> $range The `after` / `before` criterion. + * + * @return bool True when inside the range. + */ + private static function withinDateRange(string $stored, array $range): bool { + return self::isOnOrAfter(stored: $stored, range: $range) === true + && self::isOnOrBefore(stored: $stored, range: $range) === true; + }//end withinDateRange() + + /** + * Whether an ISO-8601 date is not before the range's `after` bound. + * + * @param string $stored The persisted ISO-8601 date. + * @param array<string, mixed> $range The `after` / `before` criterion. + * + * @return bool True when there is no bound or the date is on or after it. + */ + private static function isOnOrAfter(string $stored, array $range): bool { + if (array_key_exists(key: 'after', array: $range) === false) { return true; - }//end if + } - return ($stored === (string)$criterion); - }//end matchesDateRange() + return strcmp(string1: $stored, string2: (string)$range['after']) >= 0; + }//end isOnOrAfter() + + /** + * Whether an ISO-8601 date is not after the range's `before` bound. + * + * @param string $stored The persisted ISO-8601 date. + * @param array<string, mixed> $range The `after` / `before` criterion. + * + * @return bool True when there is no bound or the date is on or before it. + */ + private static function isOnOrBefore(string $stored, array $range): bool { + if (array_key_exists(key: 'before', array: $range) === false) { + return true; + } + + return strcmp(string1: $stored, string2: (string)$range['before']) <= 0; + }//end isOnOrBefore() /** * Multi-select containment: the stored value is a JSON array; @@ -788,10 +913,7 @@ private static function assertTypeShape(string $type): void { * @throws InvalidMetadataFieldException When mismatched. */ private static function assertOptionsShape(string $type, ?array $options): void { - $isSelect = ($type === MetadataField::TYPE_SELECT - || $type === MetadataField::TYPE_MULTI_SELECT); - - if ($isSelect === true) { + if (self::isSelectType(type: $type) === true) { self::assertSelectOptions(options: $options); return; } @@ -803,6 +925,18 @@ private static function assertOptionsShape(string $type, ?array $options): void } }//end assertOptionsShape() + /** + * Whether a field type takes a list of options (select / multi-select). + * + * @param string $type The field type. + * + * @return bool True for the select types. + */ + private static function isSelectType(string $type): bool { + return ($type === MetadataField::TYPE_SELECT + || $type === MetadataField::TYPE_MULTI_SELECT); + }//end isSelectType() + /** * Validate the `options` array of a select / multi-select field. * @@ -824,6 +958,19 @@ private static function assertSelectOptions(?array $options): void { ); } + self::assertOptionEntries(options: $options); + }//end assertSelectOptions() + + /** + * Validate that every option is a non-empty string. + * + * @param array<int, mixed> $options The candidate options. + * + * @return void + * + * @throws InvalidMetadataFieldException On a non-string or empty entry. + */ + private static function assertOptionEntries(array $options): void { // Defensive runtime check: callers may pass non-string entries. foreach ($options as $option) { if (is_string($option) === false || $option === '') { @@ -832,5 +979,5 @@ private static function assertSelectOptions(?array $options): void { ); } } - }//end assertSelectOptions() + }//end assertOptionEntries() }//end class diff --git a/lib/Service/MetadataValueWriter.php b/lib/Service/MetadataValueWriter.php new file mode 100644 index 000000000..23a2bb5ab --- /dev/null +++ b/lib/Service/MetadataValueWriter.php @@ -0,0 +1,95 @@ +<?php + +/** + * MetadataValueWriter + * + * Writes encoded metadata values for one dashboard: an empty value of an + * optional field clears its row, every other value is upserted + * (REQ-MDFL-005, REQ-MDFL-006). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboard-metadata-fields/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\MetadataField; +use OCA\LaunchPad\Db\MetadataValueMapper; + +/** + * Writes encoded metadata values for one dashboard. + * + * Built by {@see MetadataService::setMetadataForDashboard()} for one + * write; never shared. + * + * @spec openspec/specs/dashboard-metadata-fields/spec.md + */ +final class MetadataValueWriter { + /** + * Constructor. + * + * @param MetadataValueMapper $valueMapper The value mapper. + * @param string $dashboardUuid The dashboard the values belong to. + */ + public function __construct( + private readonly MetadataValueMapper $valueMapper, + private readonly string $dashboardUuid, + ) { + }//end __construct() + + /** + * Write one field's encoded value. + * + * @param MetadataField $field The field definition. + * @param string $encoded The validated, encoded value. + * + * @return void + * + * @spec openspec/specs/dashboard-metadata-fields/spec.md + */ + public function write(MetadataField $field, string $encoded): void { + if ($encoded === '' && $field->getRequired() === 0) { + // Empty optional value: remove the row so the read + // payload omits the key (matches scenario "omitted + // keys are not deleted" by allowing explicit empty + // to clear the value — keeps client UX coherent). + $this->clear(fieldId: (int)$field->getId()); + return; + } + + $this->valueMapper->upsert( + dashboardUuid: $this->dashboardUuid, + fieldId: (int)$field->getId(), + value: $encoded + ); + }//end write() + + /** + * Remove the dashboard's row for a field, if it has one. + * + * @param integer $fieldId The field id. + * + * @return void + */ + private function clear(int $fieldId): void { + $existing = $this->valueMapper->findOne( + dashboardUuid: $this->dashboardUuid, + fieldId: $fieldId + ); + if ($existing !== null) { + $this->valueMapper->delete(entity: $existing); + } + }//end clear() +}//end class diff --git a/lib/Service/NewColleagues.php b/lib/Service/NewColleagues.php new file mode 100644 index 000000000..91a245057 --- /dev/null +++ b/lib/Service/NewColleagues.php @@ -0,0 +1,167 @@ +<?php + +/** + * LaunchPad New Colleagues. + * + * The people whose start date (the profile field marked as the start date, + * REQ-PEX-005) lies in a window around today, newest start first + * (REQ-PPL-014): the "New colleagues" selection of the people widget. + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\ProfileValueMapper; +use OCP\IUserManager; + +/** + * Who started recently or starts soon. + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ +class NewColleagues { + + /** + * Days back by default, and the allowed range. + */ + public const SINCE_DEFAULT = 30; + public const SINCE_MIN = 1; + public const SINCE_MAX = 90; + + /** + * Days ahead by default, and the allowed range. + */ + public const UNTIL_DEFAULT = 14; + public const UNTIL_MIN = 0; + public const UNTIL_MAX = 30; + + /** + * Constructor. + * + * @param ProfileFieldService $fields The field definitions and who may see a value. + * @param ProfileValueMapper $values The stored values. + * @param IUserManager $users The accounts. + * @param PeopleWidgetService|null $people The people widget's profile (avatar, role, organisation), or none. + * + * @return void + */ + public function __construct( + private readonly ProfileFieldService $fields, + private readonly ProfileValueMapper $values, + private readonly IUserManager $users, + private readonly ?PeopleWidgetService $people = null, + ) { + }//end __construct() + + /** + * The new colleagues the viewer may see, newest start first. Without a + * start-date field `configured` is false and nobody is listed. + * + * @param string|null $viewerId The viewer. + * @param array{since?: int, until?: int, today: string} $window Days back, days ahead and today (`YYYY-MM-DD`). + * + * @return array{configured: bool, since: int, until: int, users: list<array{id: string, displayName: string, startDate: string, starts: bool}>} + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ + public function listNew(?string $viewerId, array $window): array { + $since = min(self::SINCE_MAX, max(self::SINCE_MIN, (int)($window['since'] ?? self::SINCE_DEFAULT))); + $until = min(self::UNTIL_MAX, max(self::UNTIL_MIN, (int)($window['until'] ?? self::UNTIL_DEFAULT))); + $answer = ['configured' => false, 'since' => $since, 'until' => $until, 'users' => []]; + + $definition = $this->startDateField(); + if ($definition === null) { + return $answer; + } + + $answer['configured'] = true; + $today = strtotime(datetime: $window['today'].' 00:00:00 UTC'); + $range = [ + 'from' => gmdate(format: 'Y-m-d', timestamp: $today - ($since * 86400)), + 'to' => gmdate(format: 'Y-m-d', timestamp: $today + ($until * 86400)), + ]; + foreach ($this->values->findDatesBetween(fieldKey: (string)$definition['key'], range: $range) as $row) { + // REQ-PEX-004: the value's own scope as well as the field's visibility. + if ($this->fields->scopeAllows(scope: $row->getScope(), viewerId: $viewerId, ownerId: $row->getUserId()) === false) { + continue; + } + + $entry = $this->entryFor(viewerId: $viewerId, ownerId: $row->getUserId(), definition: $definition); + if ($entry !== null) { + $answer['users'][] = $entry + ['startDate' => $row->getValue(), 'starts' => $row->getValue() > $window['today']]; + } + } + + return $answer; + }//end listNew() + + /** + * The field marked as the start date, or null. + * + * @return array<string, mixed>|null The definition. + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ + private function startDateField(): ?array { + foreach ($this->fields->getDefinitions() as $definition) { + if (($definition['startDate'] ?? false) === true) { + return $definition; + } + } + + return null; + }//end startDateField() + + /** + * One person, when their account is enabled and the viewer may see the field. + * + * @param string|null $viewerId The viewer. + * @param string $ownerId The person. + * @param array<string, mixed> $definition The start-date field. + * + * @return array{id: string, displayName: string, avatarUrl?: string, role?: string, organisation?: string}|null + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ + private function entryFor(?string $viewerId, string $ownerId, array $definition): ?array { + if ($this->fields->canSee(viewerId: $viewerId, ownerId: $ownerId, definition: $definition) === false) { + return null; + } + + $user = $this->users->get(uid: $ownerId); + if ($user === null || $user->isEnabled() === false) { + return null; + } + + $entry = ['id' => $ownerId, 'displayName' => $user->getDisplayName()]; + if ($this->people === null) { + return $entry; + } + + // The list shows photo, role and team (REQ-PPL-014), read as the people widget reads them. + $profile = $this->people->buildUserProfile(user: $user, showBirthdays: false); + foreach (['avatarUrl', 'role', 'organisation'] as $key) { + if (is_string(value: ($profile[$key] ?? null)) === true && $profile[$key] !== '') { + $entry[$key] = $profile[$key]; + } + } + + return $entry; + }//end entryFor() + +}//end class diff --git a/lib/Service/NewsWidgetService.php b/lib/Service/NewsWidgetService.php index 3b4b35423..a111d7e1a 100644 --- a/lib/Service/NewsWidgetService.php +++ b/lib/Service/NewsWidgetService.php @@ -27,12 +27,13 @@ namespace OCA\LaunchPad\Service; use DOMDocument; +use DOMNode; use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacement; use OCA\LaunchPad\Db\WidgetPlacementMapper; use OCA\LaunchPad\Service\Connection\ConnectionReporter; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\Http\Client\IClientService; use OCP\IAppConfig; use OCP\ICache; use OCP\ICacheFactory; @@ -101,6 +102,42 @@ class NewsWidgetService { */ private const FETCH_TIMEOUT_SECONDS = 10; + /** + * Default of each boolean config field (REQ-NEWS-002). + * + * @var array<string, bool> + */ + private const BOOL_FIELD_DEFAULTS = [ + 'showThumbnails' => true, + 'showSummary' => true, + ]; + + /** + * Default, lower bound and upper bound of each integer config field + * (REQ-NEWS-002). + * + * @var array<string, array{0: int, 1: int, 2: int}> + */ + private const INT_FIELD_RANGES = [ + 'itemLimit' => [10, 1, 50], + 'summaryMaxChars' => [200, 0, 5000], + ]; + + /** + * HTTP client options of a live feed fetch. + * + * C1/H3: redirect-following is disabled so an attacker cannot chain a + * public URL to an internal redirect target (SSRF via open redirect). + * + * @var array<string, int|bool> + */ + private const FETCH_OPTIONS = [ + 'timeout' => self::FETCH_TIMEOUT_SECONDS, + 'connect_timeout' => self::FETCH_TIMEOUT_SECONDS, + 'verify' => true, + 'allow_redirects' => false, + ]; + /** * Lazily resolved {@see ICache} backing the per-feed payload cache. * Created on first use so unit tests can construct the service @@ -114,30 +151,24 @@ class NewsWidgetService { * Constructor. * * @param WidgetPlacementMapper $placementMapper Resolves placements by id. - * @param IClientService $clientService Builds the HTTP client used - * for synchronous on-demand - * feed fetches. - * @param IAppConfig $appConfig Reads admin settings: - * `news_widget_feed_cache_ttl_seconds` - * and - * `news_widget_allowed_feed_hosts`. - * @param ICacheFactory $cacheFactory Backing factory for the - * distributed cache used to - * hold raw feed payloads. - * @param LoggerInterface $logger PSR logger. - * @param UrlSafetyValidator $urlValidator Shared SSRF / allow-list guard. - * @param ConnectionReporter|null $connectionReporter Tells integriq what a feed fetch met, or nothing when absent. + * @param FeedFetchTools $fetch The HTTP client service, cache factory, URL validator and + * connection reporter. + * @param IAppConfig $appConfig Reads admin settings: `news_widget_feed_cache_ttl_seconds` and + * `news_widget_allowed_feed_hosts`. + * @param LoggerInterface $logger PSR logger. + * @param MetadataService|null $metadata Reads a dashboard's metadata for the placement's metadata filter; + * without it a configured filter never matches. + * @param DashboardMapper|null $dashboards Resolves the placement's dashboard to its uuid. * * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md#requirement-req-lp-conn-003-launchpad-reports-what-its-outbound-calls-met */ public function __construct( private readonly WidgetPlacementMapper $placementMapper, - private readonly IClientService $clientService, + private readonly FeedFetchTools $fetch, private readonly IAppConfig $appConfig, - private readonly ICacheFactory $cacheFactory, private readonly LoggerInterface $logger, - private readonly UrlSafetyValidator $urlValidator, - private readonly ?ConnectionReporter $connectionReporter = null, + private readonly ?MetadataService $metadata=null, + private readonly ?DashboardMapper $dashboards=null, ) { }//end __construct() @@ -161,16 +192,8 @@ public function __construct( */ public function getItemsForPlacement(int $placementId, int $limit = 10): array { $clamped = $this->clampLimit(limit: $limit); - - try { - $placement = $this->placementMapper->find(id: $placementId); - } catch (DoesNotExistException $e) { - return $this->emptyResponse(); - } catch (Throwable $e) { - $this->logger->warning( - message: 'NewsWidget: failed to resolve placement ' . $placementId, - context: ['exception' => $e] - ); + $placement = $this->findPlacement(placementId: $placementId); + if ($placement === null) { return $this->emptyResponse(); } @@ -187,12 +210,31 @@ public function getItemsForPlacement(int $placementId, int $limit = 10): array { return $this->emptyResponse(); } - return $this->fetchAndMergeFeeds( - feedUrls: $config['feedUrls'], - limit: $clamped - ); + return $this->fetchAndMergeFeeds(feedUrls: $config['feedUrls'], limit: $clamped); }//end getItemsForPlacement() + /** + * The placement with this id, or null when it does not exist or cannot + * be read (logged). + * + * @param integer $placementId Placement entity id. + * + * @return WidgetPlacement|null + */ + private function findPlacement(int $placementId): ?WidgetPlacement { + try { + return $this->placementMapper->find(id: $placementId); + } catch (DoesNotExistException $e) { + return null; + } catch (Throwable $e) { + $this->logger->warning( + message: 'NewsWidget: failed to resolve placement ' . $placementId, + context: ['exception' => $e] + ); + return null; + } + }//end findPlacement() + /** * Parse the placement's persisted JSON content into the canonical * news config shape, applying defaults where fields are missing or @@ -220,38 +262,43 @@ public function extractNewsConfig(WidgetPlacement $placement): array { // the `content` column; `style_config` only carries chrome // (background/title). Read `content` first, falling back to // `style_config` for any legacy placement that stored config there. - $decoded = $this->decodeStyleConfigBlob(raw: $placement->getContent()); - if ($decoded === [] || $this->extractFeedUrls(decoded: $decoded) === []) { - $legacy = $this->decodeStyleConfigBlob(raw: $placement->getStyleConfig()); - if ($legacy !== []) { - $decoded = $legacy; - } - } + $decoded = $this->readConfigBlob(placement: $placement); return [ 'feedUrls' => $this->extractFeedUrls(decoded: $decoded), 'layout' => $this->extractLayout(decoded: $decoded), - 'itemLimit' => $this->extractIntInRange( - decoded: $decoded, - key: 'itemLimit', - default: 10, - min: 1, - max: 50 - ), - 'showThumbnails' => $this->extractBool(decoded: $decoded, key: 'showThumbnails', default: true), - 'showSummary' => $this->extractBool(decoded: $decoded, key: 'showSummary', default: true), - 'summaryMaxChars' => $this->extractIntInRange( - decoded: $decoded, - key: 'summaryMaxChars', - default: 200, - min: 0, - max: 5000 - ), + 'itemLimit' => $this->extractIntInRange(decoded: $decoded, key: 'itemLimit'), + 'showThumbnails' => $this->extractBool(decoded: $decoded, key: 'showThumbnails'), + 'showSummary' => $this->extractBool(decoded: $decoded, key: 'showSummary'), + 'summaryMaxChars' => $this->extractIntInRange(decoded: $decoded, key: 'summaryMaxChars'), 'dateFormat' => $this->extractDateFormat(decoded: $decoded), 'metadataFilter' => $this->extractMetadataFilter(decoded: $decoded), ]; }//end extractNewsConfig() + /** + * Decoded config of a placement: its `content` column, or its legacy + * `style_config` column when `content` holds no feed URLs and the + * legacy column is not empty. + * + * @param WidgetPlacement $placement The placement. + * + * @return array<string, mixed> Decoded content map (empty when invalid). + */ + private function readConfigBlob(WidgetPlacement $placement): array { + $decoded = $this->decodeStyleConfigBlob(raw: $placement->getContent()); + if ($decoded !== [] && $this->extractFeedUrls(decoded: $decoded) !== []) { + return $decoded; + } + + $legacy = $this->decodeStyleConfigBlob(raw: $placement->getStyleConfig()); + if ($legacy !== []) { + return $legacy; + } + + return $decoded; + }//end readConfigBlob() + /** * Parse the widget's persisted JSON blob and unwrap the outer * `{type, content}` envelope when present so callers always get @@ -293,14 +340,7 @@ private function extractFeedUrls(array $decoded): array { $out = []; foreach ($candidates as $candidate) { - if (is_string(value: $candidate) === false || $candidate === '') { - continue; - } - - // C1: accept HTTPS only — plain HTTP leaks feed content in - // transit and bypasses the SSRF guard's scheme check. - $lower = strtolower(string: $candidate); - if (str_starts_with(haystack: $lower, needle: 'https://') === true) { + if (self::isHttpsUrl(candidate: $candidate) === true) { $out[] = $candidate; } } @@ -308,6 +348,26 @@ private function extractFeedUrls(array $decoded): array { return $out; }//end extractFeedUrls() + /** + * Whether a configured feed URL is a non-empty string starting with + * `https://` (any case). + * + * C1: accept HTTPS only — plain HTTP leaks feed content in transit and + * bypasses the SSRF guard's scheme check. + * + * @param mixed $candidate Configured entry. + * + * @return boolean + */ + private static function isHttpsUrl(mixed $candidate): bool { + if (is_string(value: $candidate) === false || $candidate === '') { + return false; + } + + $lower = strtolower(string: $candidate); + return str_starts_with(haystack: $lower, needle: 'https://'); + }//end isHttpsUrl() + /** * Extract the layout enum (`list` | `grid` | `carousel`). * @@ -327,17 +387,16 @@ private function extractLayout(array $decoded): string { }//end extractLayout() /** - * Extract a clamped int field. + * Extract a clamped int field; its default and range come from + * INT_FIELD_RANGES. * * @param array<string, mixed> $decoded Decoded config map. - * @param string $key Field key. - * @param integer $default Default value when missing/invalid. - * @param integer $min Lower bound. - * @param integer $max Upper bound. + * @param string $key Field key (a key of INT_FIELD_RANGES). * * @return integer */ - private function extractIntInRange(array $decoded, string $key, int $default, int $min, int $max): int { + private function extractIntInRange(array $decoded, string $key): int { + [$default, $min, $max] = self::INT_FIELD_RANGES[$key]; $value = $decoded[$key] ?? null; if (is_int(value: $value) === false) { return $default; @@ -347,17 +406,17 @@ private function extractIntInRange(array $decoded, string $key, int $default, in }//end extractIntInRange() /** - * Extract a boolean field with default fallback. + * Extract a boolean field; its default (used when the key is missing) + * comes from BOOL_FIELD_DEFAULTS. * * @param array<string, mixed> $decoded Decoded config map. - * @param string $key Field key. - * @param boolean $default Default value when missing. + * @param string $key Field key (a key of BOOL_FIELD_DEFAULTS). * * @return boolean */ - private function extractBool(array $decoded, string $key, bool $default): bool { + private function extractBool(array $decoded, string $key): bool { if (array_key_exists(key: $key, array: $decoded) === false) { - return $default; + return self::BOOL_FIELD_DEFAULTS[$key]; } return $decoded[$key] === true; @@ -425,68 +484,114 @@ public function fetchAndMergeFeeds(array $feedUrls, int $limit = 10): array { return $this->emptyResponse(); } + $collected = $this->collectFeedItems(feedUrls: $feedUrls); + + return [ + 'items' => $this->rankItems(items: $collected['items'], limit: $limit), + 'feedsFailed' => count(value: $collected['failedUrls']), + // No array_values(): failedUrls is already a list. + 'failedUrls' => $collected['failedUrls'], + ]; + }//end fetchAndMergeFeeds() + + /** + * Fetch and parse every feed URL in order, tolerating failures. + * + * @param array<int, string> $feedUrls List of feed URLs. + * + * @return array{items: array<int, array<string, mixed>>, failedUrls: array<int, string>} + */ + private function collectFeedItems(array $feedUrls): array { $allItems = []; $failedUrls = []; - foreach ($feedUrls as $url) { - // C1: SSRF guard — reject non-HTTPS, private IPs, and any host - // not in the admin allow-list (default-deny when list is - // non-empty; open when list is empty per REQ-NEWS-006). - if ($this->urlValidator->isSafe(url: $url) === false) { - $this->logger->warning( - message: 'NewsWidget: URL rejected by SSRF guard', - context: ['url' => $url] - ); + $parsed = $this->fetchFeedItems(url: $url); + if ($parsed === null) { $failedUrls[] = $url; continue; } - if ($this->checkAllowList(url: $url) === false) { - $this->logger->warning( - message: 'NewsWidget: URL skipped by allow-list', - context: ['url' => $url] - ); - $failedUrls[] = $url; - continue; - } + array_push($allItems, ...$parsed); + } - $payload = $this->fetchFeedPayload(url: $url); - if ($payload === null) { - $failedUrls[] = $url; - continue; - } + return ['items' => $allItems, 'failedUrls' => $failedUrls]; + }//end collectFeedItems() - try { - $parsed = $this->parseRssFeed( - feedContent: $payload, - sourceUrl: $url, - sourceTitle: $url - ); - } catch (Throwable $e) { - $this->logger->warning( - message: 'NewsWidget: feed parse failed for ' . $url, - context: ['exception' => $e] - ); - $failedUrls[] = $url; - continue; - } + /** + * Deduplicate, sort newest first and cap the merged items. + * + * @param array<int, array<string, mixed>> $items Merged items. + * @param integer $limit Hard cap on returned item count. + * + * @return array<int, array<string, mixed>> + */ + private function rankItems(array $items, int $limit): array { + $deduped = $this->deduplicateItems(items: $items); + $sorted = $this->sortItemsByDate(items: $deduped); - foreach ($parsed as $item) { - $allItems[] = $item; - } - }//end foreach + return array_slice(array: $sorted, offset: 0, length: $limit); + }//end rankItems() - $deduped = $this->deduplicateItems(items: $allItems); - $sorted = $this->sortItemsByDate(items: $deduped); - $sliced = array_slice(array: $sorted, offset: 0, length: $limit); + /** + * Guard, fetch and parse one feed URL. + * + * @param string $url Feed URL. + * + * @return array<int, array<string, mixed>>|null Parsed items, or null + * when the feed failed. + */ + private function fetchFeedItems(string $url): ?array { + if ($this->isFeedUrlAccepted(url: $url) === false) { + return null; + } - return [ - 'items' => $sliced, - 'feedsFailed' => count(value: $failedUrls), - // No array_values(): $failedUrls is already a list. - 'failedUrls' => $failedUrls, - ]; - }//end fetchAndMergeFeeds() + $payload = $this->fetchFeedPayload(url: $url); + if ($payload === null) { + return null; + } + + try { + return $this->parseRssFeed(feedContent: $payload, sourceUrl: $url, sourceTitle: $url); + } catch (Throwable $e) { + $this->logger->warning( + message: 'NewsWidget: feed parse failed for ' . $url, + context: ['exception' => $e] + ); + return null; + } + }//end fetchFeedItems() + + /** + * Whether a feed URL passes the SSRF guard and the admin allow-list, + * logging the reason when it does not. + * + * C1: SSRF guard — reject non-HTTPS, private IPs, and any host not in + * the admin allow-list (default-deny when list is non-empty; open when + * list is empty per REQ-NEWS-006). + * + * @param string $url Feed URL. + * + * @return boolean True when the URL may be fetched. + */ + private function isFeedUrlAccepted(string $url): bool { + if ($this->fetch->urlValidator->isSafe(url: $url) === false) { + $this->logger->warning( + message: 'NewsWidget: URL rejected by SSRF guard', + context: ['url' => $url] + ); + return false; + } + + if ($this->checkAllowList(url: $url) === false) { + $this->logger->warning( + message: 'NewsWidget: URL skipped by allow-list', + context: ['url' => $url] + ); + return false; + } + + return true; + }//end isFeedUrlAccepted() /** * Parse a raw feed payload (RSS 2.0 or Atom 1.0) into the canonical @@ -512,51 +617,62 @@ public function parseRssFeed(string $feedContent, string $sourceUrl, string $sou return []; } - $items = []; - $rootName = $xml->getName(); + $source = new FeedSource(url: $sourceUrl, title: $sourceTitle); // Atom 1.0: <feed><entry/>…</feed>. - if ($rootName === 'feed') { - $resolvedTitle = $sourceTitle; - if (isset($xml->title) === true) { - $resolvedTitle = (string)$xml->title; - } + if ($xml->getName() === 'feed') { + return $this->normaliseAtomFeed(feed: $xml, source: $source->titledBy(node: $xml)); + } - foreach ($xml->entry as $entry) { - $items[] = $this->normaliseAtomEntry( - entry: $entry, - sourceUrl: $sourceUrl, - sourceTitle: $resolvedTitle - ); - } + return $this->normaliseRssFeed(xml: $xml, fallback: $source); + }//end parseRssFeed() - return $items; + /** + * Convert every `<entry>` of an Atom feed into the canonical item shape. + * + * @param SimpleXMLElement $feed The Atom `<feed>` root. + * @param FeedSource $source Feed URL and resolved display name. + * + * @return array<int, array<string, mixed>> Parsed items. + */ + private function normaliseAtomFeed(SimpleXMLElement $feed, FeedSource $source): array { + $items = []; + foreach ($feed->entry as $entry) { + $items[] = $this->normaliseAtomEntry(entry: $entry, source: $source); } - // RSS 2.0 (<rss><channel>) plus the bare <channel> some publishers ship. + return $items; + }//end normaliseAtomFeed() + + /** + * Convert every `<item>` of an RSS 2.0 channel into the canonical item + * shape, accepting the bare `<channel>` root some publishers ship. + * + * @param SimpleXMLElement $xml The parsed feed document. + * @param FeedSource $fallback Feed URL and the display name used when + * the channel has no title. + * + * @return array<int, array<string, mixed>> Parsed items, empty for an + * unsupported root. + */ + private function normaliseRssFeed(SimpleXMLElement $xml, FeedSource $fallback): array { + $rootName = $xml->getName(); $channel = self::resolveRssChannel(xml: $xml, rootName: $rootName); if ($channel === null) { $this->logger->info( - message: 'NewsWidget: unsupported feed root <' . $rootName . '> for ' . $sourceUrl + message: 'NewsWidget: unsupported feed root <' . $rootName . '> for ' . $fallback->url ); return []; } - $resolvedTitle = $sourceTitle; - if (isset($channel->title) === true) { - $resolvedTitle = (string)$channel->title; - } - + $source = $fallback->titledBy(node: $channel); + $items = []; foreach ($channel->item as $item) { - $items[] = $this->normaliseRssItem( - item: $item, - sourceUrl: $sourceUrl, - sourceTitle: $resolvedTitle - ); + $items[] = $this->normaliseRssItem(item: $item, source: $source); } return $items; - }//end parseRssFeed() + }//end normaliseRssFeed() /** * Parse a raw feed payload, logging and returning null when the XML is @@ -629,30 +745,40 @@ public function deduplicateItems(array $items): array { $seen = []; $out = []; foreach ($items as $item) { - $guid = ''; - if (isset($item['guid']) === true) { - $guid = (string)$item['guid']; + // Items missing a guid bypass the dedupe map but still flow + // through so we don't lose them; the synthetic guid in + // normaliseRssItem / normaliseAtomEntry ensures this path is + // rarely hit. + $guid = self::itemGuid(item: $item); + if ($guid !== '' && isset($seen[$guid]) === true) { + continue; } - if ($guid === '' || isset($seen[$guid]) === true) { - if ($guid === '') { - // Items missing a guid bypass the dedupe map but - // still flow through so we don't lose them; the - // synthetic guid in normaliseRssItem / normaliseAtomEntry - // ensures this path is rarely hit. - $out[] = $item; - } - - continue; + if ($guid !== '') { + $seen[$guid] = true; } - $seen[$guid] = true; $out[] = $item; - }//end foreach + } return $out; }//end deduplicateItems() + /** + * An item's guid as a string, or '' when it has none. + * + * @param array<string, mixed> $item Item. + * + * @return string + */ + private static function itemGuid(array $item): string { + if (isset($item['guid']) === true) { + return (string)$item['guid']; + } + + return ''; + }//end itemGuid() + /** * Sort items by ISO 8601 `pubDate`, descending (newest first). * Items with an invalid or missing pubDate sink to the end, in @@ -666,38 +792,53 @@ public function deduplicateItems(array $items): array { */ public function sortItemsByDate(array $items): array { $sortable = $items; - usort( - array: $sortable, - callback: function (array $a, array $b): int { - $aTs = false; - if (isset($a['pubDate']) === true) { - $aTs = strtotime(datetime: (string)$a['pubDate']); - } - - $bTs = false; - if (isset($b['pubDate']) === true) { - $bTs = strtotime(datetime: (string)$b['pubDate']); - } - - if ($aTs === false && $bTs === false) { - return 0; - } - - if ($aTs === false) { - return 1; - } - - if ($bTs === false) { - return -1; - } - - return ($bTs <=> $aTs); - } - ); + usort(array: $sortable, callback: self::compareByPubDateDesc(...)); return $sortable; }//end sortItemsByDate() + /** + * Order two items newest first; items without a parseable pubDate + * sink below dated ones and keep their relative order. + * + * @param array<string, mixed> $a First item. + * @param array<string, mixed> $b Second item. + * + * @return integer + */ + private static function compareByPubDateDesc(array $a, array $b): int { + $aTs = self::pubDateTimestamp(item: $a); + $bTs = self::pubDateTimestamp(item: $b); + if ($aTs === false && $bTs === false) { + return 0; + } + + if ($aTs === false) { + return 1; + } + + if ($bTs === false) { + return -1; + } + + return ($bTs <=> $aTs); + }//end compareByPubDateDesc() + + /** + * Unix timestamp of an item's pubDate, or false when absent or unparseable. + * + * @param array<string, mixed> $item Item. + * + * @return integer|false + */ + private static function pubDateTimestamp(array $item): int|false { + if (isset($item['pubDate']) === false) { + return false; + } + + return strtotime(datetime: (string)$item['pubDate']); + }//end pubDateTimestamp() + /** * Allow-list the small set of inline tags safe to render inside a * feed item summary, strip everything else, and force `rel` on @@ -721,16 +862,51 @@ public function sanitiseSummaryHtml(string $html): string { // be neutralised; reuse PHP's HTML parser via DOMDocument so we // can rewrite href attributes safely without false-positives on // body text containing the substring. - // C2: LIBXML_NOENT removed — resolves entities (XXE risk). + $document = self::loadSummaryDocument(html: $stripped); + self::neutraliseAnchors(document: $document); + + // Re-serialise just the wrapper's children so we don't leak + // <html><body> from DOMDocument's auto-wrapping. + $body = $document->getElementsByTagName(qualifiedName: 'div')->item(index: 0); + if ($body === null) { + return $stripped; + } + + return self::serialiseChildren(document: $document, parent: $body); + }//end sanitiseSummaryHtml() + + /** + * Parse stripped summary HTML inside a `<div>` wrapper, silencing + * libxml's warnings for the duration of the parse. + * + * C2: LIBXML_NOENT removed — resolves entities (XXE risk). + * + * @param string $html Tag-stripped summary HTML. + * + * @return DOMDocument + */ + private static function loadSummaryDocument(string $html): DOMDocument { $previousErrors = libxml_use_internal_errors(use_errors: true); $document = new DOMDocument(); $document->loadHTML( - source: '<?xml encoding="UTF-8"><div>' . $stripped . '</div>', + source: '<?xml encoding="UTF-8"><div>' . $html . '</div>', options: LIBXML_NONET ); libxml_clear_errors(); libxml_use_internal_errors(use_errors: $previousErrors); + return $document; + }//end loadSummaryDocument() + + /** + * Point `javascript:` and `data:` anchors at `#` and force `rel` on + * every anchor. + * + * @param DOMDocument $document Parsed summary document. + * + * @return void + */ + private static function neutraliseAnchors(DOMDocument $document): void { $anchors = $document->getElementsByTagName(qualifiedName: 'a'); foreach ($anchors as $anchor) { $href = $anchor->getAttribute(qualifiedName: 'href'); @@ -743,16 +919,19 @@ public function sanitiseSummaryHtml(string $html): string { $anchor->setAttribute(qualifiedName: 'rel', value: 'noopener noreferrer'); } + }//end neutraliseAnchors() - // Re-serialise just the wrapper's children so we don't leak - // <html><body> from DOMDocument's auto-wrapping. - $body = $document->getElementsByTagName(qualifiedName: 'div')->item(index: 0); - if ($body === null) { - return $stripped; - } - + /** + * Serialise the child nodes of a parent element as HTML. + * + * @param DOMDocument $document Document the parent belongs to. + * @param DOMNode $parent The wrapper element. + * + * @return string + */ + private static function serialiseChildren(DOMDocument $document, DOMNode $parent): string { $out = ''; - foreach ($body->childNodes as $child) { + foreach ($parent->childNodes as $child) { $serialised = $document->saveHTML(node: $child); if (is_string(value: $serialised) === true) { $out .= $serialised; @@ -760,7 +939,7 @@ public function sanitiseSummaryHtml(string $html): string { } return $out; - }//end sanitiseSummaryHtml() + }//end serialiseChildren() /** * Whether the supplied URL's hostname is permitted by the admin @@ -774,7 +953,7 @@ public function sanitiseSummaryHtml(string $html): string { * @spec openspec/specs/news-widget/spec.md */ public function checkAllowList(string $url): bool { - return $this->urlValidator->checkAllowList( + return $this->fetch->urlValidator->checkAllowList( url: $url, appId: Application::APP_ID, configKey: self::CONFIG_KEY_ALLOWED_HOSTS @@ -782,12 +961,10 @@ public function checkAllowList(string $url): bool { }//end checkAllowList() /** - * Hook for the (out-of-branch) `dashboard-metadata-fields` capability. - * Until that capability ships, the metadata store is unavailable and - * the filter result is "no metadata defined" — which means a - * configured filter never matches and the widget returns no items - * (REQ-NEWS-007 scenarios "Metadata field missing" and "spec not - * yet implemented"). + * Whether the dashboard's metadata value for the filter's field equals + * the filter's value (REQ-NEWS-007). A field the dashboard has no value + * for is null and never matches; so does a dashboard that cannot be + * read, or a service built without the metadata store. * * @param integer $dashboardId The dashboard whose * metadata to consult. @@ -798,13 +975,23 @@ public function checkAllowList(string $url): bool { * @spec openspec/specs/news-widget/spec.md */ public function checkMetadataFilter(int $dashboardId, array $metadataFilter): bool { - unset($dashboardId); - unset($metadataFilter); + if ($this->metadata === null || $this->dashboards === null) { + return false; + } - // REQ-NEWS-007: gracefully treat missing dashboard-metadata-fields - // implementation as "no fields defined", which causes any - // configured equality filter to fail. - return false; + try { + $uuid = (string)$this->dashboards->find(id: $dashboardId)->getUuid(); + $values = $this->metadata->getMetadataForDashboard(dashboardUuid: $uuid); + } catch (Throwable $exception) { + $this->logger->warning( + message: 'News widget: dashboard metadata unreadable, metadata filter fails', + context: ['app' => Application::APP_ID, 'dashboardId' => $dashboardId, 'exception' => $exception->getMessage()] + ); + return false; + } + + $actual = ($values[$metadataFilter['fieldKey']] ?? null); + return $actual !== null && (string)$actual === $metadataFilter['value']; }//end checkMetadataFilter() /** @@ -842,75 +1029,123 @@ private function clampLimit(int $limit): int { */ private function fetchFeedPayload(string $url): ?string { $cache = $this->getCache(); - $cacheKey = 'feed_' . sha1(string: $url); - - $cached = $this->readCachedPayload(cache: $cache, cacheKey: $cacheKey); + $cached = $this->readCachedPayload(cache: $cache, cacheKey: self::feedCacheKey(url: $url)); if ($cached !== null) { return $cached; } try { - $client = $this->clientService->newClient(); - $response = $client->get( - uri: $url, - options: [ - 'timeout' => self::FETCH_TIMEOUT_SECONDS, - 'connect_timeout' => self::FETCH_TIMEOUT_SECONDS, - 'verify' => true, - // C1/H3: disable redirect-following so an attacker - // cannot chain a public URL to an internal redirect - // target (SSRF via open redirect). - 'allow_redirects' => false, - ] + return $this->fetchAndCachePayload(url: $url, cache: $cache); + } catch (Throwable $e) { + $this->reportFetchFailure(url: $url, exception: $e); + return null; + } + }//end fetchFeedPayload() + + /** + * Cache key of one feed URL's payload. + * + * @param string $url Feed URL. + * + * @return string + */ + private static function feedCacheKey(string $url): string { + return 'feed_' . sha1(string: $url); + }//end feedCacheKey() + + /** + * Fetch a feed live and store an accepted payload in the cache for the + * configured TTL. + * + * @param string $url Feed URL. + * @param ICache|null $cache The resolved cache, or null when unavailable. + * + * @return string|null Raw feed payload, or null when rejected. + */ + private function fetchAndCachePayload(string $url, ?ICache $cache): ?string { + $body = $this->fetchLiveBody(url: $url); + if ($body !== null && $cache !== null) { + $ttl = $this->appConfig->getValueInt( + app: Application::APP_ID, + key: 'news_widget_feed_cache_ttl_seconds', + default: self::DEFAULT_CACHE_TTL ); + $cache->set(key: self::feedCacheKey(url: $url), value: $body, ttl: $ttl); + } - $statusCode = $response->getStatusCode(); - if ($statusCode < 200 || $statusCode >= 300) { - $this->logger->warning( - message: 'NewsWidget: feed fetch returned HTTP ' . $statusCode . ' for ' . $url - ); - $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_NEWS_FEEDS, url: $url, httpStatus: $statusCode); - return null; - } + return $body; + }//end fetchAndCachePayload() + + /** + * GET a feed URL without following redirects and report the status to + * the connection registry. + * + * @param string $url Feed URL. + * + * @return string|null Raw feed payload, or null when the status, an + * empty body or the size cap rejects it. + */ + private function fetchLiveBody(string $url): ?string { + $client = $this->fetch->clientService->newClient(); + $response = $client->get(uri: $url, options: self::FETCH_OPTIONS); - $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_NEWS_FEEDS, url: $url, httpStatus: $statusCode); + $statusCode = $response->getStatusCode(); + if ($statusCode < 200 || $statusCode >= 300) { + $this->logger->warning( + message: 'NewsWidget: feed fetch returned HTTP ' . $statusCode . ' for ' . $url + ); + $this->fetch->connectionReporter?->reportCall(key: ConnectionReporter::KEY_NEWS_FEEDS, url: $url, httpStatus: $statusCode); + return null; + } - $body = (string)$response->getBody(); - if ($body === '') { - return null; - } + $this->fetch->connectionReporter?->reportCall(key: ConnectionReporter::KEY_NEWS_FEEDS, url: $url, httpStatus: $statusCode); - // C1: body cap — reject oversized payloads before XML parse. - if (strlen(string: $body) > self::MAX_RESPONSE_SIZE_BYTES) { - $this->logger->warning( - message: 'NewsWidget: feed response exceeds 1MB cap, skipping ' . $url - ); - return null; - } + return $this->acceptBody(url: $url, body: (string)$response->getBody()); + }//end fetchLiveBody() - if ($cache !== null) { - $ttl = $this->appConfig->getValueInt( - app: Application::APP_ID, - key: 'news_widget_feed_cache_ttl_seconds', - default: self::DEFAULT_CACHE_TTL - ); - $cache->set(key: $cacheKey, value: $body, ttl: $ttl); - } + /** + * The response body, or null when it is empty or over the size cap. + * + * @param string $url Feed URL (for logging). + * @param string $body Response body. + * + * @return string|null + */ + private function acceptBody(string $url, string $body): ?string { + if ($body === '') { + return null; + } - return $body; - } catch (Throwable $e) { + // C1: body cap — reject oversized payloads before XML parse. + if (strlen(string: $body) > self::MAX_RESPONSE_SIZE_BYTES) { $this->logger->warning( - message: 'NewsWidget: feed fetch failed for ' . $url, - context: ['exception' => $e] - ); - $this->connectionReporter?->reportCall( - key: ConnectionReporter::KEY_NEWS_FEEDS, - url: $url, - httpStatus: $this->connectionReporter->httpStatusOf(exception: $e) + message: 'NewsWidget: feed response exceeds 1MB cap, skipping ' . $url ); return null; - }//end try - }//end fetchFeedPayload() + } + + return $body; + }//end acceptBody() + + /** + * Log a failed feed fetch and report it to the connection registry. + * + * @param string $url Feed URL. + * @param Throwable $exception What the fetch threw. + * + * @return void + */ + private function reportFetchFailure(string $url, Throwable $exception): void { + $this->logger->warning( + message: 'NewsWidget: feed fetch failed for ' . $url, + context: ['exception' => $exception] + ); + $this->fetch->connectionReporter?->reportCall( + key: ConnectionReporter::KEY_NEWS_FEEDS, + url: $url, + httpStatus: $this->fetch->connectionReporter->httpStatusOf(exception: $exception) + ); + }//end reportFetchFailure() /** * Read a previously cached feed payload. @@ -951,7 +1186,7 @@ private function getCache(): ?ICache { } try { - $this->cache = $this->cacheFactory->createDistributed(prefix: 'launchpad_news_'); + $this->cache = $this->fetch->cacheFactory->createDistributed(prefix: 'launchpad_news_'); } catch (Throwable $e) { $this->logger->info( message: 'NewsWidget: cache subsystem unavailable, falling back to direct fetch', @@ -989,84 +1224,132 @@ private static function childText(SimpleXMLElement $node, array $names): string * Convert a single Atom `<entry>` into the canonical item shape. * * @param SimpleXMLElement $entry The Atom entry node. - * @param string $sourceUrl The feed URL. - * @param string $sourceTitle The display name for the feed. + * @param FeedSource $source The feed URL and display name. * * @return array<string, mixed> Canonical item. */ - private function normaliseAtomEntry(SimpleXMLElement $entry, string $sourceUrl, string $sourceTitle): array { - $title = self::childText(node: $entry, names: ['title']); - $summary = self::childText(node: $entry, names: ['summary', 'content']); - $pubDate = self::childText(node: $entry, names: ['updated', 'published']); - $guid = self::childText(node: $entry, names: ['id']); - - $link = ''; - if (isset($entry->link) === true) { - // Atom links are <link href="…"/>. - $href = $entry->link['href'] ?? null; - if ($href !== null) { - $link = (string)$href; - } + private function normaliseAtomEntry(SimpleXMLElement $entry, FeedSource $source): array { + return $this->canonicalItem( + fields: [ + 'guid' => self::childText(node: $entry, names: ['id']), + 'title' => self::childText(node: $entry, names: ['title']), + 'summary' => self::childText(node: $entry, names: ['summary', 'content']), + 'link' => self::atomLink(entry: $entry), + 'pubDate' => self::childText(node: $entry, names: ['updated', 'published']), + 'thumbnailUrl' => null, + ], + source: $source + ); + }//end normaliseAtomEntry() + + /** + * The `href` of an Atom entry's `<link href="…"/>`, or '' without one. + * + * @param SimpleXMLElement $entry The Atom entry node. + * + * @return string + */ + private static function atomLink(SimpleXMLElement $entry): string { + if (isset($entry->link) === false) { + return ''; } - if ($guid === '') { - $guid = sha1(string: $title . '|' . $pubDate . '|' . $sourceUrl); + $href = $entry->link['href'] ?? null; + if ($href === null) { + return ''; } - return [ - 'guid' => $guid, - 'title' => $title, - 'summary' => $this->sanitiseSummaryHtml(html: $summary), - 'link' => $link, - 'pubDate' => $pubDate, - 'sourceUrl' => $sourceUrl, - 'sourceTitle' => $sourceTitle, - 'thumbnailUrl' => null, - ]; - }//end normaliseAtomEntry() + return (string)$href; + }//end atomLink() /** * Convert a single RSS `<item>` into the canonical item shape. * * @param SimpleXMLElement $item The RSS item node. - * @param string $sourceUrl The feed URL. - * @param string $sourceTitle The display name for the feed. + * @param FeedSource $source The feed URL and display name. * * @return array<string, mixed> Canonical item. */ - private function normaliseRssItem(SimpleXMLElement $item, string $sourceUrl, string $sourceTitle): array { - $title = self::childText(node: $item, names: ['title']); - $summary = self::childText(node: $item, names: ['description']); - $link = self::childText(node: $item, names: ['link']); - $pubDate = self::childText(node: $item, names: ['pubDate']); - $guid = self::childText(node: $item, names: ['guid']); - - if ($guid === '') { - $guid = sha1(string: $title . '|' . $pubDate . '|' . $sourceUrl); + private function normaliseRssItem(SimpleXMLElement $item, FeedSource $source): array { + return $this->canonicalItem( + fields: [ + 'guid' => self::childText(node: $item, names: ['guid']), + 'title' => self::childText(node: $item, names: ['title']), + 'summary' => self::childText(node: $item, names: ['description']), + 'link' => self::childText(node: $item, names: ['link']), + 'pubDate' => self::childText(node: $item, names: ['pubDate']), + 'thumbnailUrl' => self::rssThumbnail(item: $item), + ], + source: $source + ); + }//end normaliseRssItem() + + /** + * The URL of an RSS item's image enclosure (an enclosure without a + * type counts as an image), or null without one. + * + * @param SimpleXMLElement $item The RSS item node. + * + * @return string|null + */ + private static function rssThumbnail(SimpleXMLElement $item): ?string { + if (isset($item->enclosure) === false) { + return null; } - $thumbnail = null; - if (isset($item->enclosure) === true) { - $url = $item->enclosure['url'] ?? null; - $type = $item->enclosure['type'] ?? null; - if ($url !== null - && ($type === null || str_starts_with(haystack: (string)$type, needle: 'image/') === true) - ) { - $thumbnail = (string)$url; - } + $url = $item->enclosure['url'] ?? null; + $type = $item->enclosure['type'] ?? null; + if ($url !== null && self::isImageEnclosureType(type: $type) === true) { + return (string)$url; } - return [ - 'guid' => $guid, - 'title' => $title, - 'summary' => $this->sanitiseSummaryHtml(html: $summary), - 'link' => $link, - 'pubDate' => $pubDate, - 'sourceUrl' => $sourceUrl, - 'sourceTitle' => $sourceTitle, - 'thumbnailUrl' => $thumbnail, - ]; - }//end normaliseRssItem() + return null; + }//end rssThumbnail() + + /** + * Whether an enclosure type marks an image; a missing type counts as one. + * + * @param SimpleXMLElement|null $type The enclosure's `type` attribute. + * + * @return boolean + */ + private static function isImageEnclosureType(?SimpleXMLElement $type): bool { + return $type === null || str_starts_with(haystack: (string)$type, needle: 'image/') === true; + }//end isImageEnclosureType() + + /** + * Complete the fields read from one feed entry into the canonical item + * shape: a synthetic `sha1(title|pubDate|sourceUrl)` guid when the + * entry has none, the sanitised summary and the feed source. + * + * @param array<string, string|null> $fields Fields read from the entry: guid, title, summary, link, + * pubDate (strings) and thumbnailUrl (string or null). + * @param FeedSource $source The feed URL and display name. + * + * @return array<string, mixed> Canonical item. + */ + private function canonicalItem(array $fields, FeedSource $source): array { + $fields['guid'] = self::guidOf(fields: $fields, source: $source); + $fields['summary'] = $this->sanitiseSummaryHtml(html: $fields['summary']); + + return $source->item(fields: $fields); + }//end canonicalItem() + + /** + * The entry's own guid, or `sha1(title|pubDate|sourceUrl)` when empty. + * + * @param array{guid: string, title: string, pubDate: string} $fields Fields read from the entry. + * @param FeedSource $source The feed URL and display name. + * + * @return string + */ + private static function guidOf(array $fields, FeedSource $source): string { + if ($fields['guid'] !== '') { + return $fields['guid']; + } + + return sha1(string: $fields['title'] . '|' . $fields['pubDate'] . '|' . $source->url); + }//end guidOf() /** * Canonical empty response so callers don't repeat the literal. diff --git a/lib/Service/NoRedirectGet.php b/lib/Service/NoRedirectGet.php new file mode 100644 index 000000000..e2fc7591d --- /dev/null +++ b/lib/Service/NoRedirectGet.php @@ -0,0 +1,69 @@ +<?php + +/** + * NoRedirectGet + * + * The bounded, redirect-free GET the services that fetch admin-configured + * URLs send. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Http\Client\IClient; +use OCP\Http\Client\IResponse; + +/** + * A GET with a connect and a total timeout that never follows a redirect + * and never throws on an HTTP error status: a 3xx to an unexpected host + * would bypass the allow-list / scheme check made before the request. + * + * @spec openspec/specs/service-health-ping/spec.md + */ +final class NoRedirectGet { + /** + * Constructor + * + * @param integer $connectTimeout Connect timeout in seconds. + * @param integer $timeout Total timeout in seconds. + */ + public function __construct( + private readonly int $connectTimeout, + private readonly int $timeout, + ) { + }//end __construct() + + /** + * Send the GET. + * + * @param IClient $client The HTTP client. + * @param string $url The URL, already checked by the caller. + * + * @return IResponse The response, whatever its status. + * + * @spec openspec/specs/service-health-ping/spec.md + */ + public function send(IClient $client, string $url): IResponse { + return $client->get( + uri: $url, + options: [ + 'connect_timeout' => $this->connectTimeout, + 'timeout' => $this->timeout, + 'http_errors' => false, + 'allow_redirects' => false, + ] + ); + }//end send() +}//end class diff --git a/lib/Service/OfficeFileRequest.php b/lib/Service/OfficeFileRequest.php new file mode 100644 index 000000000..15100f169 --- /dev/null +++ b/lib/Service/OfficeFileRequest.php @@ -0,0 +1,47 @@ +<?php + +/** + * OfficeFileRequest + * + * What a "New ..." office tile asks for: the file creator, the file name + * without extension and the folder (integrations-office-tiles, REQ-OFT-002). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The creator, name and folder of one file an office tile creates. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ +final class OfficeFileRequest { + + /** + * Constructor + * + * @param string $creatorId The creator, as the pack names it (`<app>:<extension>`). + * @param string $name The file name without extension. + * @param string $folder The folder, created when missing (default /Documents). + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + public function __construct( + public readonly string $creatorId, + public readonly string $name, + public readonly string $folder = OfficeTilesService::DEFAULT_FOLDER, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/OfficeNetworkService.php b/lib/Service/OfficeNetworkService.php new file mode 100644 index 000000000..ae6e24851 --- /dev/null +++ b/lib/Service/OfficeNetworkService.php @@ -0,0 +1,173 @@ +<?php + +/** + * OfficeNetworkService + * + * Whether a request comes from one of the office networks an administrator + * listed, so a tile can open its office-network address there. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-License-Identifier: EUPL-1.2 + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; +use OCA\LaunchPad\Db\AdminSetting; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCP\IRequest; +use OCP\Security\Ip\IFactory; +use Psr\Log\LoggerInterface; + +/** + * The server decides from the request address (design D1): the browser never + * probes hosts. `IRequest::getRemoteAddress()` honours Nextcloud's trusted + * proxies and forwarded-for headers. No ranges listed means never on the + * office network, so nothing changes until an administrator sets them. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ +class OfficeNetworkService { + + /** + * Constructor. + * + * @param IRequest $request The current request. + * @param IFactory $ipFactory Parses addresses and CIDR ranges. + * @param AdminSettingMapper $settingMapper Reads the stored ranges. + * @param LoggerInterface $logger Reports a stored range that no longer parses. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ + public function __construct( + private readonly IRequest $request, + private readonly IFactory $ipFactory, + private readonly AdminSettingMapper $settingMapper, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * Whether the current request comes from inside the office networks. + * + * @return bool True when its address falls in one of the stored ranges. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ + public function isOfficeRequest(): bool { + return $this->isInside(address: $this->currentAddress(), ranges: $this->storedRanges()); + }//end isOfficeRequest() + + /** + * The current request's address, as Nextcloud resolves it. + * + * @return string The address; empty when there is none. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-administrators-declare-the-office-networks-req-tia-001 + */ + public function currentAddress(): string { + return $this->request->getRemoteAddress(); + }//end currentAddress() + + /** + * Whether an address falls in one of the ranges; a range that does not parse is skipped and logged. + * + * @param string $address The address. + * @param array<int,string> $ranges CIDR ranges. + * + * @return bool True when one range contains it. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ + public function isInside(string $address, array $ranges): bool { + if ($ranges === [] || $address === '') { + return false; + } + + try { + $parsed = $this->ipFactory->addressFromString($address); + } catch (InvalidArgumentException) { + return false; + } + + foreach ($ranges as $range) { + try { + if ($this->ipFactory->rangeFromString((string)$range)->contains($parsed) === true) { + return true; + } + } catch (InvalidArgumentException) { + $this->logger->warning('LaunchPad: a stored office network range does not parse and is ignored.', ['range' => $range]); + } + } + + return false; + }//end isInside() + + /** + * Check and normalise a list of ranges an administrator entered. + * + * @param array<mixed> $ranges The entered ranges. + * + * @return array<int,string> The trimmed ranges, blanks and duplicates left out. + * + * @throws InvalidArgumentException When one is not a valid IPv4 or IPv6 CIDR range; nothing is stored then. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-administrators-declare-the-office-networks-req-tia-001 + */ + public function normaliseRanges(array $ranges): array { + $clean = []; + foreach ($ranges as $range) { + if (is_string($range) === false) { + throw new InvalidArgumentException(message: 'This is not a valid network range'); + } + + $range = trim($range); + if ($range === '') { + continue; + } + + // A bare address is not a range: the administrator must say how wide the network is. + if (str_contains(haystack: $range, needle: '/') === false) { + throw new InvalidArgumentException(message: 'This is not a valid network range: ' . $range); + } + + try { + $this->ipFactory->rangeFromString($range); + } catch (InvalidArgumentException) { + throw new InvalidArgumentException(message: 'This is not a valid network range: ' . $range); + } + + if (in_array(needle: $range, haystack: $clean, strict: true) === false) { + $clean[] = $range; + } + }//end foreach + + return $clean; + }//end normaliseRanges() + + /** + * The ranges an administrator stored. + * + * @return array<int,string> + */ + private function storedRanges(): array { + $stored = ($this->settingMapper->getAllAsArray()[AdminSetting::KEY_OFFICE_NETWORKS] ?? []); + if (is_array($stored) === false) { + return []; + } + + return array_values(array_filter($stored, 'is_string')); + }//end storedRanges() +}//end class diff --git a/lib/Service/OfficeTilesService.php b/lib/Service/OfficeTilesService.php new file mode 100644 index 000000000..d859ebbee --- /dev/null +++ b/lib/Service/OfficeTilesService.php @@ -0,0 +1,327 @@ +<?php + +/** + * OfficeTilesService + * + * The ready-made office tile pack (integrations-office-tiles): a "New ..." + * tile for each file creator the server's office apps register, and tiles + * for Files, Mail, Calendar, Contacts and Talk when those apps are enabled + * for the person (REQ-OFT-001). A "New ..." tile creates the file from the + * office app's own blank template under a free name, never overwriting + * (REQ-OFT-002). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Exception\InvalidDirectoryException; +use OCA\LaunchPad\Exception\InvalidFilenameException; +use OCA\LaunchPad\Exception\ResourceException; +use OCA\LaunchPad\Exception\StorageFailureException; +use OCP\App\IAppManager; +use OCP\Files\Folder; +use OCP\Files\IRootFolder; +use OCP\Files\Template\ITemplateManager; +use OCP\Files\Template\TemplateFileCreator; +use OCP\IURLGenerator; +use OCP\IUserManager; +use Throwable; + +/** + * Builds the office tile pack and creates files from office templates. + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) The template, app, user, file and URL services are each one platform call. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-the-add-flow-offers-an-office-tile-pack-built-from-what-the-server-has-req-oft-001 + */ +class OfficeTilesService { + + /** + * The apps the pack links to when they are enabled, in pack order: app id => tile title. + * + * @var array<string, string> + */ + public const APP_TILES = [ + 'files' => 'Files', + 'mail' => 'Mail', + 'calendar' => 'Calendar', + 'contacts' => 'Contacts', + 'spreed' => 'Talk', + ]; + + /** + * The folder a new file goes to when the person names none. + * + * @var string + */ + public const DEFAULT_FOLDER = '/Documents'; + + /** + * How many numbered names are tried before giving up. + * + * @var int + */ + private const MAX_FREE_NAME_ATTEMPTS = 1000; + + /** + * Constructor. + * + * @param ITemplateManager $templateManager The file creators office apps register. + * @param IAppManager $appManager Which apps are enabled for a person. + * @param IUserManager $userManager Resolves the person. + * @param IRootFolder $rootFolder The person's files. + * @param IURLGenerator $urlGenerator Builds the editor link. + */ + public function __construct( + private readonly ITemplateManager $templateManager, + private readonly IAppManager $appManager, + private readonly IUserManager $userManager, + private readonly IRootFolder $rootFolder, + private readonly IURLGenerator $urlGenerator, + ) { + }//end __construct() + + /** + * The tiles of the pack for one person: a create tile per file creator, + * then a tile per enabled app. An app the person cannot open is left out. + * + * @param string $userId The person. + * + * @return array<int, array<string, string>> Tiles: `{title, linkType, linkValue, icon, iconType}`. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-the-add-flow-offers-an-office-tile-pack-built-from-what-the-server-has-req-oft-001 + */ + public function packFor(string $userId): array { + $tiles = []; + foreach ($this->creators() as $creatorId => $creator) { + $tiles[] = [ + 'title' => $this->labelOf(creator: $creator), + 'linkType' => 'create', + 'linkValue' => $creatorId, + 'icon' => 'icon-filetype-file', + 'iconType' => 'class', + ]; + } + + $user = $this->userManager->get($userId); + foreach (self::APP_TILES as $appId => $title) { + if ($this->appManager->isEnabledForUser($appId, $user) === false) { + continue; + } + + $tiles[] = [ + 'title' => $title, + 'linkType' => 'app', + 'linkValue' => $appId, + 'icon' => 'icon-' . $appId, + 'iconType' => 'class', + ]; + } + + return $tiles; + }//end packFor() + + /** + * Create a file from a creator's blank template under a free name. + * + * @param string $userId The person. + * @param OfficeFileRequest $request The creator, the file name without extension and the folder. + * + * @return array{fileId: int, path: string, url: string} The new file. + * + * @throws InvalidFilenameException When the name or the creator is not acceptable (400). + * @throws InvalidDirectoryException When the folder escapes the person's files (400). + * @throws StorageFailureException When the file cannot be created. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + public function create(string $userId, OfficeFileRequest $request): array { + $creator = ($this->creators()[$request->creatorId] ?? null); + if ($creator === null) { + throw new InvalidFilenameException(message: 'Unknown file creator'); + } + + $name = trim($request->name); + $this->assertValidName(name: $name); + $folderPath = $this->normaliseFolder(folder: $request->folder); + + try { + $target = $this->folderFor(userId: $userId, path: $folderPath); + $fileName = $this->freeName(folder: $target, name: $name, extension: $this->extensionOf(creator: $creator)); + $path = rtrim($folderPath, '/') . '/' . $fileName; + $created = $this->templateManager->createFromTemplate($path, '', 'user'); + } catch (ResourceException $exception) { + throw $exception; + } catch (Throwable $exception) { + throw new StorageFailureException(message: 'Failed to create the file'); + } + + $fileId = (int)($created['fileid'] ?? 0); + + return [ + 'fileId' => $fileId, + 'path' => $path, + 'url' => $this->urlGenerator->linkToRoute('files.view.index', ['openfile' => $fileId]), + ]; + }//end create() + + /** + * The registered file creators, keyed by `<app>:<extension>`. + * + * @return array<string, TemplateFileCreator> + */ + private function creators(): array { + $creators = []; + foreach ($this->templateManager->listCreators() as $creator) { + if ($creator instanceof TemplateFileCreator === false) { + continue; + } + + $extension = $this->extensionOf(creator: $creator); + if ($extension === '') { + continue; + } + + $creators[$creator->getAppId() . ':' . $extension] = $creator; + } + + return $creators; + }//end creators() + + /** + * A creator's file extension, with its leading dot, lowercase. + * + * @param TemplateFileCreator $creator The creator. + * + * @return string The extension, such as `.docx`, or '' when it has none usable. + */ + private function extensionOf(TemplateFileCreator $creator): string { + $extension = strtolower(ltrim((string)($creator->jsonSerialize()['extension'] ?? ''), '.')); + if (preg_match('/^[a-z0-9]{1,10}$/', $extension) !== 1) { + return ''; + } + + return '.' . $extension; + }//end extensionOf() + + /** + * A creator's own label, such as "New document". + * + * @param TemplateFileCreator $creator The creator. + * + * @return string The label. + */ + private function labelOf(TemplateFileCreator $creator): string { + return (string)($creator->jsonSerialize()['label'] ?? ''); + }//end labelOf() + + /** + * Refuse a name the file rules of REQ-LBN-004 refuse. + * + * @param string $name The name without extension. + * + * @return void + * + * @throws InvalidFilenameException When the name is empty, too long or has forbidden characters. + */ + private function assertValidName(string $name): void { + if ($name === '' || strlen($name) > 200 || str_contains($name, '..') === true) { + throw new InvalidFilenameException(); + } + + if (preg_match(FileService::FILENAME_PATTERN, $name) !== 1) { + throw new InvalidFilenameException(); + } + }//end assertValidName() + + /** + * The folder as an absolute path inside the person's files. + * + * @param string $folder The requested folder. + * + * @return string The path, starting with `/`. + * + * @throws InvalidDirectoryException When it contains `..`, a backslash or a null byte. + */ + private function normaliseFolder(string $folder): string { + $folder = trim($folder); + if ($folder === '') { + return self::DEFAULT_FOLDER; + } + + foreach (['..', "\0", '\\'] as $forbidden) { + if (str_contains($folder, $forbidden) === true) { + throw new InvalidDirectoryException(); + } + } + + return '/' . trim($folder, '/'); + }//end normaliseFolder() + + /** + * The person's folder at a path, created when missing. + * + * @param string $userId The person. + * @param string $path The folder path. + * + * @return Folder The folder. + * + * @throws InvalidDirectoryException When the path is a file. + */ + private function folderFor(string $userId, string $path): Folder { + $userFolder = $this->rootFolder->getUserFolder($userId); + if ($path === '/') { + return $userFolder; + } + + $relative = ltrim($path, '/'); + if ($userFolder->nodeExists($relative) === false) { + return $userFolder->newFolder($relative); + } + + $node = $userFolder->get($relative); + if ($node instanceof Folder === false) { + throw new InvalidDirectoryException(); + } + + return $node; + }//end folderFor() + + /** + * A file name that does not exist yet: `Name.ext`, else `Name (2).ext`, `Name (3).ext`, ... + * + * @param Folder $folder The folder. + * @param string $name The name without extension. + * @param string $extension The extension with its dot. + * + * @return string The free file name. + * + * @throws StorageFailureException When no free name is found. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + public function freeName(Folder $folder, string $name, string $extension): string { + $candidate = $name . $extension; + for ($number = 2; $folder->nodeExists($candidate) === true; $number++) { + if ($number > self::MAX_FREE_NAME_ATTEMPTS) { + throw new StorageFailureException(message: 'No free file name'); + } + + $candidate = $name . ' (' . $number . ')' . $extension; + } + + return $candidate; + }//end freeName() +}//end class diff --git a/lib/Service/OrphanedDataCleanupService.php b/lib/Service/OrphanedDataCleanupService.php index 9fc94ac52..aba7312cf 100644 --- a/lib/Service/OrphanedDataCleanupService.php +++ b/lib/Service/OrphanedDataCleanupService.php @@ -40,19 +40,19 @@ use OCA\LaunchPad\AppInfo\Application; use OCA\LaunchPad\Db\CleanupResult; +use OCA\LaunchPad\Kernel\Contracts\OrphanedDataCleanupServiceInterface; use OCA\LaunchPad\Service\Cleanup\CategoryRegistryService; use OCP\Activity\Exceptions\IncompleteActivityException; -use OCP\Activity\IManager as IActivityManager; +use OCP\Activity\IEvent; use OCP\ICache; use OCP\ICacheFactory; use OCP\IDBConnection; -use Psr\Log\LoggerInterface; use Throwable; /** * Orchestrates scan + purge across all registered cleanup categories. */ -class OrphanedDataCleanupService { +class OrphanedDataCleanupService implements OrphanedDataCleanupServiceInterface { /** * Cache TTL for scan results, in seconds (REQ-CLN-010). * @@ -89,23 +89,15 @@ class OrphanedDataCleanupService { * Constructor. * * @param CategoryRegistryService $registry Category registry. - * @param ICacheFactory $cacheFactory Distributed-cache - * factory. - * @param IDBConnection $db DB connection - * (for dry-run - * transactions). - * @param IActivityManager $activityManager Activity event - * publisher. - * @param LoggerInterface $logger PSR-3 logger - * used for purge - * audit lines. + * @param ICacheFactory $cacheFactory Distributed-cache factory. + * @param IDBConnection $db DB connection (for dry-run transactions). + * @param CleanupReporting $reporting The activity manager and logger. */ public function __construct( private readonly CategoryRegistryService $registry, private readonly ICacheFactory $cacheFactory, private readonly IDBConnection $db, - private readonly IActivityManager $activityManager, - private readonly LoggerInterface $logger, + private readonly CleanupReporting $reporting, ) { }//end __construct() @@ -204,44 +196,57 @@ public function purge( ?string $userId = null, string $source = 'api', ): CleanupResult { - $names = $this->resolveCategoryNames(requested: $categoryNames); + $result = $this->timedPurge( + names: $this->resolveCategoryNames(requested: $categoryNames), + dryRun: $dryRun + ); + + if ($dryRun === false) { + $this->recordPurgeOutcome( + result: $result, + byCategory: $result->getByCategory(), + userId: $userId, + source: $source, + ); + } + + return $result; + }//end purge() + + /** + * Purge the named categories and time the run. + * + * A dry run opens a transaction first; {@see self::runCategoryPurges()} + * rolls it back (REQ-CLN-003). + * + * @param array<int, string> $names The resolved category names. + * @param bool $dryRun True for simulation. + * + * @return CleanupResult The result, with its duration. + */ + private function timedPurge(array $names, bool $dryRun): CleanupResult { $start = (int)round(num: (microtime(as_float: true) * 1000)); - $byCategory = []; - $skipped = []; if ($dryRun === true) { $this->db->beginTransaction(); } - $this->runCategoryPurges( + [$byCategory, $skipped] = $this->runCategoryPurges( names: $names, dryRun: $dryRun, - byCategory: $byCategory, - skipped: $skipped, ); $duration = ((int)round(num: (microtime(as_float: true) * 1000)) - $start); - $result = CleanupResult::fromCounts( + return CleanupResult::fromCounts( byCategory: $byCategory, durationMs: $duration, dryRun: $dryRun, skipped: $skipped, ); - - if ($dryRun === false) { - $this->recordPurgeOutcome( - result: $result, - byCategory: $byCategory, - userId: $userId, - source: $source, - ); - } - - return $result; - }//end purge() + }//end timedPurge() /** - * Run every named category's purge, filling the count and skip lists. + * Run every named category's purge and collect the counts and skips. * * A category that is unregistered or reports itself unavailable is * skipped rather than failing the whole run. On a dry run the caller @@ -249,21 +254,17 @@ public function purge( * happy path and the failure path — REQ-CLN-003 requires a simulation * to leave zero persistent side effect. * - * @param array<int, string> $names The category names to purge. - * @param bool $dryRun True for simulation. - * @param array<string, int> $byCategory Per-category row counts, filled in place. - * @param array<int, string> $skipped Skipped category names, filled in place. + * @param array<int, string> $names The category names to purge. + * @param bool $dryRun True for simulation. * - * @return void + * @return array{0: array<string, int>, 1: array<int, string>} Per-category + * row counts and skipped category names. * * @throws Throwable Re-thrown after the dry-run transaction is rolled back. */ - private function runCategoryPurges( - array $names, - bool $dryRun, - array &$byCategory, - array &$skipped, - ): void { + private function runCategoryPurges(array $names, bool $dryRun): array { + $byCategory = []; + $skipped = []; try { foreach ($names as $name) { $category = $this->registry->getCategoryByName(name: $name); @@ -292,6 +293,8 @@ private function runCategoryPurges( throw $t; }//end try + + return [$byCategory, $skipped]; }//end runCategoryPurges() /** @@ -324,7 +327,7 @@ private function recordPurgeOutcome( ); } - $this->logger->info( + $this->reporting->logger->info( message: sprintf( 'launchpad.cleanup.purge source=%s user=%s rows=%d duration_ms=%d categories=%s', $source, @@ -455,36 +458,21 @@ private function emitActivityEvent( string $source, ): void { try { - $event = $this->activityManager->generateEvent(); - $event->setApp(app: Application::APP_ID) - ->setType(type: self::ACTIVITY_TYPE) - ->setAffectedUser(affectedUser: ($userId ?? '')) - ->setAuthor(author: ($userId ?? '')) - ->setSubject( - subject: 'launchpad_cleanup_purge', - parameters: [ - 'totalRows' => $result->getTotalRows(), - 'byCategory' => $result->getByCategory(), - 'durationMs' => $result->getDurationMs(), - 'source' => $source, - ] - ) - ->setObject( - objectType: 'launchpad_cleanup', - objectId: 0, - objectName: $source - ); + $event = $this->purgeEvent( + userId: $userId, + parameters: $this->purgeParameters(result: $result, source: $source) + ); - $this->activityManager->publish(event: $event); + $this->reporting->activityManager->publish(event: $event); } catch (IncompleteActivityException $e) { - $this->logger->warning( + $this->reporting->logger->warning( message: sprintf( 'launchpad.cleanup.activity_emit_failed: %s', $e->getMessage() ) ); } catch (Throwable $t) { - $this->logger->warning( + $this->reporting->logger->warning( message: sprintf( 'launchpad.cleanup.activity_emit_threw: %s', $t->getMessage() @@ -492,4 +480,48 @@ private function emitActivityEvent( ); }//end try }//end emitActivityEvent() + + /** + * The subject parameters of the Activity event of a purge run. + * + * @param CleanupResult $result The purge result. + * @param string $source The source label. + * + * @return array{totalRows: int, byCategory: array<string, int>, durationMs: int, source: string} + */ + private function purgeParameters(CleanupResult $result, string $source): array { + return [ + 'totalRows' => $result->getTotalRows(), + 'byCategory' => $result->getByCategory(), + 'durationMs' => $result->getDurationMs(), + 'source' => $source, + ]; + }//end purgeParameters() + + /** + * The Activity event of a purge run, named after its source. + * + * @param string|null $userId The actor (null = system). + * @param array{totalRows: int, byCategory: array<string, int>, durationMs: int, source: string} $parameters The subject parameters. + * + * @return IEvent + */ + private function purgeEvent(?string $userId, array $parameters): IEvent { + $event = $this->reporting->activityManager->generateEvent(); + $event->setApp(app: Application::APP_ID) + ->setType(type: self::ACTIVITY_TYPE) + ->setAffectedUser(affectedUser: ($userId ?? '')) + ->setAuthor(author: ($userId ?? '')) + ->setSubject( + subject: 'launchpad_cleanup_purge', + parameters: $parameters + ) + ->setObject( + objectType: 'launchpad_cleanup', + objectId: 0, + objectName: $parameters['source'] + ); + + return $event; + }//end purgeEvent() }//end class diff --git a/lib/Service/PageFooter.php b/lib/Service/PageFooter.php new file mode 100644 index 000000000..c9b50f02b --- /dev/null +++ b/lib/Service/PageFooter.php @@ -0,0 +1,105 @@ +<?php + +/** + * PageFooter + * + * The footer the workspace page shows below the grid, and the language the + * footer picks its variant in (footer-customization REQ-FTR-004, REQ-FTR-006, + * REQ-FTR-007). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/footer-customization/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\DashboardTranslationMapper; +use OCP\IUserManager; +use OCP\L10N\IFactory; + +/** + * Resolves the page footer and the viewer's footer language. + * + * @spec openspec/specs/footer-customization/spec.md + */ +class PageFooter { + /** + * Constructor. + * + * @param FooterService $footerService Global footer settings and per-dashboard resolution. + * @param DashboardTranslationMapper $translationMapper The dashboard's language variants. + * @param IFactory $l10nFactory The viewer's Nextcloud language. + * @param IUserManager $userManager Looks the viewer up. + */ + public function __construct( + private readonly FooterService $footerService, + private readonly DashboardTranslationMapper $translationMapper, + private readonly IFactory $l10nFactory, + private readonly IUserManager $userManager, + ) { + }//end __construct() + + /** + * The footer for the page: the active dashboard's effective footer with + * its primary language, which is the second step of the variant choice + * (REQ-FTR-007), or the global footer when no dashboard is active. NULL + * renders no footer. + * + * @param Dashboard|null $dashboard The active dashboard, or null. + * + * @return array<string, mixed>|null The footer payload. + * + * @spec openspec/specs/footer-customization/spec.md + */ + public function footerFor(?Dashboard $dashboard): ?array { + if ($dashboard === null) { + return $this->footerService->resolveGlobalFooter(); + } + + $footer = $this->footerService->resolveFooterForDashboard(dashboard: $dashboard); + if ($footer === null) { + return null; + } + + $primary = $this->translationMapper->findPrimaryByDashboardUuid( + dashboardUuid: (string)$dashboard->getUuid() + ); + if ($primary !== null && $primary->getLanguageCode() !== null) { + $footer['primaryLanguage'] = $primary->getLanguageCode(); + } + + return $footer; + }//end footerFor() + + /** + * The viewer's Nextcloud language, which picks the footer variant + * first (REQ-FTR-007); `en` for nobody. + * + * @param string $userId The viewer, or ''. + * + * @return string The language code. + * + * @spec openspec/specs/footer-customization/spec.md + */ + public function viewerLocale(string $userId): string { + $user = $this->userManager->get($userId); + if ($user === null) { + return 'en'; + } + + return $this->l10nFactory->getUserLanguage($user); + }//end viewerLocale() +}//end class diff --git a/lib/Service/ParentFirstPageOrder.php b/lib/Service/ParentFirstPageOrder.php new file mode 100644 index 000000000..a131e9724 --- /dev/null +++ b/lib/Service/ParentFirstPageOrder.php @@ -0,0 +1,145 @@ +<?php + +/** + * ParentFirstPageOrder + * + * One depth-first pass over Confluence pages that emits every page after + * its known parent, each pageId once. Used by + * {@see ConfluenceImportService} to create parents before children. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Service\Confluence\ParsedPage; + +/** + * Emits pages parent-first; pageIds compare case-insensitively. + * + * @spec openspec/specs/confluence-html-import/spec.md + */ +final class ParentFirstPageOrder { + + /** + * Lower-cased pageIds already emitted. + * + * @var array<string, true> + */ + private array $emitted = []; + + /** + * The emitted pages, in order. + * + * @var ParsedPage[] + */ + private array $ordered = []; + + /** + * Constructor. + * + * @param array<string, ParsedPage> $byPageId Every page, keyed by lower-cased pageId. + */ + public function __construct( + private readonly array $byPageId, + ) { + }//end __construct() + + /** + * Order the given pages parent-first. + * + * @param ParsedPage[] $pages The pages, in visiting order. + * + * @return ParsedPage[] The pages with each known parent before its children. + * + * @spec openspec/specs/confluence-html-import/spec.md + */ + public function order(array $pages): array { + foreach ($pages as $page) { + $this->visit(page: $page); + } + + return $this->ordered; + }//end order() + + /** + * Emit the page's parent chain first, then the page itself. + * + * @param ParsedPage $page The page to visit. + * + * @return void + */ + private function visit(ParsedPage $page): void { + $key = strtolower(string: $page->pageId); + if (isset($this->emitted[$key]) === true) { + return; + } + + $parentKey = $this->pendingParentKey(page: $page, key: $key); + if ($parentKey !== null) { + $this->visit(page: $this->byPageId[$parentKey]); + } + + $this->emit(page: $page); + }//end visit() + + /** + * The parent's key when that parent is known, is not the page itself and is not emitted yet. + * + * @param ParsedPage $page The page. + * @param string $key The page's lower-cased pageId. + * + * @return string|null The parent key to visit first, or null. + */ + private function pendingParentKey(ParsedPage $page, string $key): ?string { + if ($page->parentPageId === null) { + return null; + } + + $parentKey = strtolower(string: $page->parentPageId); + if ($parentKey === $key || $this->isKnownAndNotEmitted(key: $parentKey) === false) { + return null; + } + + return $parentKey; + }//end pendingParentKey() + + /** + * Whether the key belongs to a known page that is not emitted yet. + * + * @param string $key A lower-cased pageId. + * + * @return bool + */ + private function isKnownAndNotEmitted(string $key): bool { + return isset($this->byPageId[$key]) === true && isset($this->emitted[$key]) === false; + }//end isKnownAndNotEmitted() + + /** + * Append the page unless its pageId was emitted already. + * + * @param ParsedPage $page The page. + * + * @return void + */ + private function emit(ParsedPage $page): void { + $key = strtolower(string: $page->pageId); + if (isset($this->emitted[$key]) === true) { + return; + } + + $this->emitted[$key] = true; + $this->ordered[] = $page; + }//end emit() +}//end class diff --git a/lib/Service/PeoplePage.php b/lib/Service/PeoplePage.php new file mode 100644 index 000000000..1118d468f --- /dev/null +++ b/lib/Service/PeoplePage.php @@ -0,0 +1,47 @@ +<?php + +/** + * PeoplePage + * + * The window of one People widget page: which users count and which + * fields show (REQ-PPL-003, REQ-PPL-005). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Whether disabled users are left out, whether birthdates show, the page + * size and the page offset of one People widget request. + * + * @spec openspec/specs/people-widget/spec.md + */ +final class PeoplePage { + /** + * Constructor + * + * @param bool $excludeDisabled True leaves disabled users out. + * @param bool $showBirthdays False strips the birthdate field. + * @param int $limit Page size (1..MAX_LIMIT). + * @param int $offset Page offset (>= 0). + */ + public function __construct( + public readonly bool $excludeDisabled, + public readonly bool $showBirthdays, + public readonly int $limit, + public readonly int $offset, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/PeopleQuery.php b/lib/Service/PeopleQuery.php new file mode 100644 index 000000000..ac72f87df --- /dev/null +++ b/lib/Service/PeopleQuery.php @@ -0,0 +1,63 @@ +<?php + +/** + * PeopleQuery + * + * One People widget request: the placement filters, the sort, the search + * text and the page window (REQ-PPL-002, REQ-PPL-003, REQ-PEX-003). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Filters, sort, search text and page window of a People widget request. + * PeopleWidgetService validates them before it reads the directory. + * + * @spec openspec/specs/people-widget/spec.md + */ +final class PeopleQuery { + /** + * Constructor + * + * @param array $filters Filter predicates `{fieldName, operator, values}`. + * @param string $sortBy One of `displayName`, `group` or `recent-activity`. + * @param string|null $search Search text (2 or more characters), or null. + * @param PeoplePage $page Disabled users, birthdates, page size and offset. + */ + public function __construct( + public readonly array $filters, + public readonly string $sortBy, + public readonly ?string $search, + public readonly PeoplePage $page, + ) { + }//end __construct() + + /** + * Build the page window of a query. + * + * @param bool $excludeDisabled True leaves disabled users out. + * @param bool $showBirthdays False strips the birthdate field. + * @param int $limit Page size (1..MAX_LIMIT). + * @param int $offset Page offset (>= 0). + * + * @return PeoplePage + * + * @spec openspec/specs/people-widget/spec.md + */ + public static function window(bool $excludeDisabled, bool $showBirthdays, int $limit, int $offset): PeoplePage { + return new PeoplePage(excludeDisabled: $excludeDisabled, showBirthdays: $showBirthdays, limit: $limit, offset: $offset); + }//end window() +}//end class diff --git a/lib/Service/PeopleWidgetService.php b/lib/Service/PeopleWidgetService.php index 9ed9beea0..aa71852f3 100644 --- a/lib/Service/PeopleWidgetService.php +++ b/lib/Service/PeopleWidgetService.php @@ -10,10 +10,10 @@ * the single contact point between the {@see PeopleWidgetController} HTTP * layer and Nextcloud's user / group / account managers. * - * Visibility model (REQ-PPL-004): v1 returns every non-empty profile field - * unconditionally — scope-based (`$prop->getScope()`) filtering is a - * documented follow-up. Empty / null values are still omitted from the - * response, never returned as `null` keys. + * Visibility model (REQ-PPL-004, REQ-PEX-004): a standard profile field + * whose Nextcloud scope is private shows to its owner only; custom fields + * follow their definition's audience. Empty / null values are omitted from + * the response, never returned as `null` keys. * * @category Service * @package OCA\LaunchPad\Service @@ -33,6 +33,8 @@ use DateTimeImmutable; use Exception; use InvalidArgumentException; +use OCA\LaunchPad\Exception\InvalidPeopleRequestException; +use OCP\Accounts\IAccount; use OCP\Accounts\IAccountManager; use OCP\IGroupManager; use OCP\IURLGenerator; @@ -88,6 +90,28 @@ class PeopleWidgetService { * * @var string[] */ + /** + * Most name and email matches one search reads (REQ-PEX-003). + * + * @var int + */ + public const SEARCH_CANDIDATE_CAP = 500; + + /** + * Shortest query that asks the server (REQ-PEX-003). + * + * @var int + */ + public const MIN_QUERY_LENGTH = 2; + + /** + * The user the current listing is for; decides which fields they may + * see and match (REQ-PEX-004). Set at the start of every listUsers() call. + * + * @var string|null + */ + private ?string $viewerId = null; + private const STANDARD_PROPERTIES = [ IAccountManager::PROPERTY_PHONE, IAccountManager::PROPERTY_ADDRESS, @@ -112,6 +136,7 @@ class PeopleWidgetService { * @param AdminTemplateService $adminTemplateService Single-source-of-truth wrapper around * `IGroupManager::getUserGroupIds` * (REQ-TMPL-013 grep guard). + * @param ProfileFieldService $profileFields Custom profile fields and their visibility. */ public function __construct( private readonly IUserManager $userManager, @@ -119,6 +144,7 @@ public function __construct( private readonly IAccountManager $accountManager, private readonly IURLGenerator $urlGenerator, private readonly AdminTemplateService $adminTemplateService, + private readonly ProfileFieldService $profileFields, ) { }//end __construct() @@ -132,64 +158,103 @@ public function __construct( * * Response shape: `{users: [...], total: int, hasMore: bool}`. * - * @param array $filters Filter predicate list. Each entry has - * the shape `{fieldName, operator, values}`. - * @param bool $excludeDisabled True (default) excludes disabled NC - * users from the candidate pool. - * @param bool $showBirthdays False strips the birthdate field from - * every result row. - * @param string $sortBy One of `displayName` (default), - * `group`, or `recent-activity`. - * @param int $limit Page size (1..MAX_LIMIT). - * @param int $offset Page offset (>=0). + * @param PeopleQuery $request Filters, sort, search text (2 or more + * characters search the whole directory by + * name, email and profile fields, + * REQ-PEX-003) and page window. + * @param string|null $viewerId The signed-in user the list is for; decides + * which fields show and match (REQ-PEX-004). * * @return array Pagination envelope with keys `users`, `total`, `hasMore`. * * @throws InvalidArgumentException When `limit` exceeds MAX_LIMIT, is * non-positive, or `offset` is negative; - * or when `sortBy` is `recent-activity`. + * when `sortBy` is `recent-activity`; or + * when the query is shorter than 2 characters. * * @spec openspec/specs/people-widget/spec.md */ - public function listUsers( - array $filters = [], - bool $excludeDisabled = true, - bool $showBirthdays = true, - string $sortBy = 'displayName', - int $limit = self::DEFAULT_LIMIT, - int $offset = 0, - ): array { + public function listUsers(PeopleQuery $request, ?string $viewerId=null): array { + $this->viewerId = $viewerId; + $this->assertListable(request: $request); + + $groupFilter = $this->extractGroupFilter(filters: $request->filters); + + if (trim(string: (string)$request->search) !== '') { + return $this->listSearchMatches(request: $request, groupFilter: $groupFilter); + } + + return $this->listBrowsePage(request: $request, groupFilter: $groupFilter); + }//end listUsers() + + /** + * Refuse a page window outside 1..MAX_LIMIT or below offset 0, and the + * not-yet-implemented `recent-activity` sort, in that order. + * + * @param PeopleQuery $request The list request. + * + * @return void + * + * @throws InvalidPeopleRequestException When the window is out of range. + * @throws InvalidArgumentException When the sort key is not implemented. + */ + private function assertListable(PeopleQuery $request): void { + $limit = $request->page->limit; if ($limit < 1 || $limit > self::MAX_LIMIT) { - throw new InvalidArgumentException( - message: 'limit must be between 1 and ' . self::MAX_LIMIT - ); + throw new InvalidPeopleRequestException(message: 'limit must be between 1 and ' . self::MAX_LIMIT); } - if ($offset < 0) { - throw new InvalidArgumentException(message: 'offset must be >= 0'); + if ($request->page->offset < 0) { + throw new InvalidPeopleRequestException(message: 'offset must be >= 0'); } - if ($sortBy === 'recent-activity') { - throw new InvalidArgumentException( - message: 'sortBy=recent-activity is not yet implemented' - ); + if ($request->sortBy === 'recent-activity') { + throw new InvalidArgumentException(message: 'sortBy=recent-activity is not yet implemented'); } + }//end assertListable() - $groupFilter = $this->extractGroupFilter(filters: $filters); + /** + * List the directory-wide search matches of a request with search + * text, in display-name order. + * + * @param PeopleQuery $request The list request. + * @param array|null $groupFilter The group filter, if any. + * + * @return array Pagination envelope with keys `users`, `total`, `hasMore`. + * + * @throws InvalidPeopleRequestException When the query is shorter than MIN_QUERY_LENGTH. + */ + private function listSearchMatches(PeopleQuery $request, ?array $groupFilter): array { + $query = trim(string: (string)$request->search); + if (mb_strlen(string: $query) < self::MIN_QUERY_LENGTH) { + throw new InvalidPeopleRequestException(message: 'q must be at least ' . self::MIN_QUERY_LENGTH . ' characters'); + } + return $this->paginateCandidates( + candidates: $this->searchCandidates(query: $query, groupFilter: $groupFilter), + window: $request->page, + sortBy: 'displayName' + ); + }//end listSearchMatches() + + /** + * List one page of the directory or of the filtered groups, without + * search text. + * + * @param PeopleQuery $request The list request. + * @param array|null $groupFilter The group filter, if any. + * + * @return array Pagination envelope with keys `users`, `total`, `hasMore`. + */ + private function listBrowsePage(PeopleQuery $request, ?array $groupFilter): array { // No `group` filter AND the default `displayName` sort: page // directly from the backend in display-name order so we never // materialize more IUser objects than the requested window // (plus any disabled users skipped inside it). This avoids the // former full-directory `IUserManager::search('')` scan on every // People-widget render. REQ-PPL-003. - if ($groupFilter === null && $sortBy !== 'group') { - return $this->listDirectoryPageByDisplayName( - excludeDisabled: $excludeDisabled, - showBirthdays: $showBirthdays, - limit: $limit, - offset: $offset - ); + if ($groupFilter === null && $request->sortBy !== 'group') { + return $this->listDirectoryPageByDisplayName(window: $request->page); } // Bounded candidate pool: either the union of the filtered group @@ -197,20 +262,12 @@ public function listUsers( // with no group filter — the full directory, since ordering by // each user's primary-group membership is inherently a // full-directory read (see resolveCandidates()). - $candidates = $this->resolveCandidates( - filters: $filters, - groupFilter: $groupFilter - ); - return $this->paginateCandidates( - candidates: $candidates, - excludeDisabled: $excludeDisabled, - showBirthdays: $showBirthdays, - sortBy: $sortBy, - limit: $limit, - offset: $offset + candidates: $this->resolveCandidates(filters: $request->filters, groupFilter: $groupFilter), + window: $request->page, + sortBy: $request->sortBy ); - }//end listUsers() + }//end listBrowsePage() /** * Page the directory directly from the backend in display-name order, @@ -224,38 +281,21 @@ public function listUsers( * the exact `total` is derived from `countUsersTotal()` (minus * `countDisabledUsers()`) so no full scan is needed to size it. * - * @param bool $excludeDisabled Whether disabled users are excluded. - * @param bool $showBirthdays Whether birthdate is projected. - * @param int $limit Page size (already validated 1..MAX_LIMIT). - * @param int $offset Page offset (already validated >= 0). + * @param PeoplePage $window Disabled users, birthdates, size (already + * validated 1..MAX_LIMIT) and offset (>= 0). * * @return array Pagination envelope with keys `users`, `total`, `hasMore`. */ - private function listDirectoryPageByDisplayName( - bool $excludeDisabled, - bool $showBirthdays, - int $limit, - int $offset, - ): array { - $page = $this->collectDisplayNamePage( - excludeDisabled: $excludeDisabled, - limit: $limit, - offset: $offset - ); - $total = $this->countDirectory(excludeDisabled: $excludeDisabled); - - $users = []; - foreach ($page as $user) { - $users[] = $this->buildUserProfile( - user: $user, - showBirthdays: $showBirthdays - ); - } + private function listDirectoryPageByDisplayName(PeoplePage $window): array { + $page = $this->collectDisplayNamePage(window: $window); + $total = $this->countDirectory(excludeDisabled: $window->excludeDisabled); return [ - 'users' => $users, + 'users' => $this->attachCustomFields( + users: $this->buildUserProfiles(page: $page, showBirthdays: $window->showBirthdays) + ), 'total' => $total, - 'hasMore' => ($offset + count(value: $page)) < $total, + 'hasMore' => ($window->offset + count(value: $page)) < $total, ]; }//end listDirectoryPageByDisplayName() @@ -267,61 +307,46 @@ private function listDirectoryPageByDisplayName( * Reads at most `offset + limit` matches (plus any disabled users * interleaved in that window) — never the full user table. * - * @param bool $excludeDisabled Whether disabled users are skipped. - * @param int $limit Number of users to collect. - * @param int $offset Number of matching users to skip first. + * @param PeoplePage $window Whether disabled users are skipped, the + * number of users to collect and the number + * of matching users to skip first. * * @return IUser[] The requested page in display-name order. */ - private function collectDisplayNamePage( - bool $excludeDisabled, - int $limit, - int $offset, - ): array { - $chunkSize = max($limit, self::DEFAULT_LIMIT); - $page = []; - $toSkip = $offset; + private function collectDisplayNamePage(PeoplePage $window): array { + $collector = new DisplayNamePageCollector(window: $window); + $chunkSize = max($window->limit, self::DEFAULT_LIMIT); $backendOffset = 0; - $pageCount = 0; - while ($pageCount < $limit) { - $batch = $this->userManager->searchDisplayName( - pattern: '', - limit: $chunkSize, - offset: $backendOffset - ); - $batchCount = count(value: $batch); - if ($batchCount === 0) { - break; - } - - foreach ($batch as $user) { - if ($excludeDisabled === true && $user->isEnabled() === false) { - continue; - } - - if ($toSkip > 0) { - $toSkip--; - continue; - } - - $page[] = $user; - $pageCount++; - if ($pageCount >= $limit) { - break; - } - } - - $backendOffset += $batchCount; - if ($batchCount < $chunkSize) { + while ($collector->isFull() === false) { + $batch = $this->displayNameBatch(offset: $backendOffset, chunkSize: $chunkSize); + $collector->takeFrom(users: $batch); + $backendOffset += count(value: $batch); + if (count(value: $batch) < $chunkSize) { // Backend exhausted — no more pages to stream. break; } - }//end while + } - return $page; + return $collector->page(); }//end collectDisplayNamePage() + /** + * One chunk of the directory in display-name order. + * + * @param int $offset The backend offset. + * @param int $chunkSize The chunk size. + * + * @return IUser[] The users. + */ + private function displayNameBatch(int $offset, int $chunkSize): array { + return $this->userManager->searchDisplayName( + pattern: '', + limit: $chunkSize, + offset: $offset + ); + }//end displayNameBatch() + /** * Exact directory size for the pagination envelope, computed from the * backend counters rather than by materializing every user. @@ -353,41 +378,68 @@ private function countDirectory(bool $excludeDisabled): int { * Used for the group-filtered path (pool already bounded to group * membership) and the rare no-filter `group` sort path. * - * @param IUser[] $candidates The resolved candidate pool. - * @param bool $excludeDisabled Whether disabled users are excluded. - * @param bool $showBirthdays Whether birthdate is projected. - * @param string $sortBy Sort mode (`displayName` or `group`). - * @param int $limit Page size. - * @param int $offset Page offset. + * @param IUser[] $candidates The resolved candidate pool. + * @param PeoplePage $window Disabled users, birthdates, size and offset. + * @param string $sortBy Sort mode (`displayName` or `group`). * * @return array Pagination envelope with keys `users`, `total`, `hasMore`. */ private function paginateCandidates( array $candidates, - bool $excludeDisabled, - bool $showBirthdays, + PeoplePage $window, string $sortBy, - int $limit, - int $offset, ): array { - if ($excludeDisabled === true) { - $candidates = array_values( - array: array_filter( - array: $candidates, - callback: static fn (IUser $candidate): bool => $candidate->isEnabled() === true - ) - ); - } - - $candidates = $this->sortCandidates(users: $candidates, sortBy: $sortBy); + $candidates = $this->sortCandidates( + users: $this->withoutDisabled(candidates: $candidates, window: $window), + sortBy: $sortBy + ); $total = count(value: $candidates); $page = array_slice( array: $candidates, - offset: $offset, - length: $limit + offset: $window->offset, + length: $window->limit ); + return [ + 'users' => $this->attachCustomFields( + users: $this->buildUserProfiles(page: $page, showBirthdays: $window->showBirthdays) + ), + 'total' => $total, + 'hasMore' => ($window->offset + count(value: $page)) < $total, + ]; + }//end paginateCandidates() + + /** + * Drop disabled accounts from the candidate pool when the window asks for it. + * + * @param IUser[] $candidates The resolved candidate pool. + * @param PeoplePage $window The pagination window. + * + * @return IUser[] The candidates, without disabled accounts when excluded. + */ + private function withoutDisabled(array $candidates, PeoplePage $window): array { + if ($window->excludeDisabled !== true) { + return $candidates; + } + + return array_values( + array: array_filter( + array: $candidates, + callback: static fn (IUser $candidate): bool => $candidate->isEnabled() === true + ) + ); + }//end withoutDisabled() + + /** + * Build the profile payload of every user on one page. + * + * @param IUser[] $page The users on the page. + * @param bool $showBirthdays Whether birthdates are included. + * + * @return array<int, array<string, mixed>> The user profiles, in page order. + */ + private function buildUserProfiles(array $page, bool $showBirthdays): array { $users = []; foreach ($page as $user) { $users[] = $this->buildUserProfile( @@ -396,12 +448,106 @@ private function paginateCandidates( ); } - return [ - 'users' => $users, - 'total' => $total, - 'hasMore' => ($offset + count(value: $page)) < $total, - ]; - }//end paginateCandidates() + return $users; + }//end buildUserProfiles() + + /** + * Name, email and profile-field matches for a search (REQ-PEX-003), + * bounded to the configured groups when the widget has a group filter. + * + * @param string $query The search text. + * @param array|null $groupFilter The widget's group filter, or null. + * + * @return IUser[] Matching users, unsorted. + * + * @spec openspec/specs/people-widget/spec.md + */ + private function searchCandidates(string $query, ?array $groupFilter): array { + $byUid = $this->directoryMatches(query: $query); + if ($groupFilter === null) { + return array_values(array: $byUid); + } + + return $this->withinGroups(byUid: $byUid, groupFilter: $groupFilter); + }//end searchCandidates() + + /** + * The users whose name or email matches, plus those whose profile + * fields the viewer may see match, keyed by UID in that order. + * + * @param string $query The search text. + * + * @return array<string, IUser> The matches. + */ + private function directoryMatches(string $query): array { + $byUid = []; + foreach ($this->userManager->search(pattern: $query, limit: self::SEARCH_CANDIDATE_CAP) as $user) { + $byUid[$user->getUID()] = $user; + } + + return $this->withFieldMatches(byUid: $byUid, query: $query); + }//end directoryMatches() + + /** + * Add the users whose visible profile fields match and who are not + * matched already; UIDs that no longer resolve are left out. + * + * @param array<string, IUser> $byUid The name / email matches. + * @param string $query The search text. + * + * @return array<string, IUser> The matches. + */ + private function withFieldMatches(array $byUid, string $query): array { + foreach ($this->profileFields->findMatchingUserIds(viewerId: $this->viewerId, query: $query) as $uid) { + if (isset($byUid[$uid]) === true) { + continue; + } + + $user = $this->userManager->get(uid: $uid); + if ($user !== null) { + $byUid[$uid] = $user; + } + } + + return $byUid; + }//end withFieldMatches() + + /** + * The matches that are members of the filtered groups. + * + * @param array<string, IUser> $byUid The matches. + * @param array $groupFilter The group filter. + * + * @return IUser[] The matches inside the groups. + */ + private function withinGroups(array $byUid, array $groupFilter): array { + $members = []; + foreach ($this->collectGroupMembers(groupIds: (array)($groupFilter['values'] ?? [])) as $member) { + $members[$member->getUID()] = true; + } + + return array_values(array: array_intersect_key($byUid, $members)); + }//end withinGroups() + + /** + * Add the custom fields the viewer may see to every profile on the page (REQ-PEX-004). + * + * @param array $users Projected profiles. + * + * @return array The profiles with `customFields`. + * + * @spec openspec/specs/people-widget/spec.md + */ + private function attachCustomFields(array $users): array { + $uids = array_map(callback: static fn (array $user): string => $user['uid'], array: $users); + $fields = $this->profileFields->visibleFieldsFor(viewerId: $this->viewerId, userIds: $uids); + + foreach ($users as $index => $user) { + $users[$index]['customFields'] = $fields[$user['uid']] ?? []; + } + + return $users; + }//end attachCustomFields() /** * Compute the number of days between today (UTC) and the user's next @@ -420,20 +566,45 @@ private function paginateCandidates( * @spec openspec/specs/people-widget/spec.md */ public static function computeDaysToBirthday(?string $birthdate): ?int { + $birth = self::parseBirthdate(birthdate: $birthdate); + if ($birth === null) { + return null; + } + + return self::daysUntilNext(monthDay: $birth->format(format: 'm-d')); + }//end computeDaysToBirthday() + + /** + * Parse a stored birthdate, null when it is missing or not a date. + * + * @param string|null $birthdate The stored birthdate. + * + * @return DateTimeImmutable|null The date, or null. + */ + private static function parseBirthdate(?string $birthdate): ?DateTimeImmutable { $iso = self::normaliseToIsoDate(raw: $birthdate); if ($iso === null) { return null; } try { - $birth = new DateTimeImmutable(datetime: $iso); + return new DateTimeImmutable(datetime: $iso); } catch (Exception $e) { return null; } + }//end parseBirthdate() + /** + * Days from today to the next occurrence of a month-day, today itself + * counting as zero. + * + * @param string $monthDay `MM-DD` slug. + * + * @return int Days until the next occurrence. + */ + private static function daysUntilNext(string $monthDay): int { $today = new DateTimeImmutable(datetime: 'today'); - $monthDay = $birth->format(format: 'm-d'); // Feb-29 guard: in non-leap target years, fall back to Feb-28. $candidate = self::buildBirthdayInYear( year: (int)$today->format(format: 'Y'), @@ -447,9 +618,8 @@ public static function computeDaysToBirthday(?string $birthdate): ?int { ); } - $diff = $today->diff(targetObject: $candidate); - return (int)$diff->days; - }//end computeDaysToBirthday() + return (int)$today->diff(targetObject: $candidate)->days; + }//end daysUntilNext() /** * Extract the first `group` filter from the filter list, if present. @@ -501,13 +671,24 @@ private function resolveCandidates(array $filters, ?array $groupFilter = null): return $this->userManager->search(pattern: ''); } + return $this->groupFilterMembers(groupFilter: $groupFilter); + }//end resolveCandidates() + + /** + * The members of a group filter's groups; none when it lists no groups. + * + * @param array $groupFilter The group filter. + * + * @return IUser[] The members. + */ + private function groupFilterMembers(array $groupFilter): array { $values = $groupFilter['values'] ?? []; if (is_array(value: $values) === false || $values === []) { return []; } return $this->collectGroupMembers(groupIds: $values); - }//end resolveCandidates() + }//end groupFilterMembers() /** * Union of the members of every named group, deduplicated by UID. @@ -525,31 +706,36 @@ private function resolveCandidates(array $filters, ?array $groupFilter = null): * @spec openspec/specs/people-widget/spec.md */ private function collectGroupMembers(array $groupIds): array { - $seen = []; - $result = []; + $byUid = []; foreach ($groupIds as $groupId) { - if (is_string(value: $groupId) === false || $groupId === '') { - continue; + foreach ($this->groupUsers(groupId: $groupId) as $user) { + // The first group a user is met in decides their place. + $byUid[$user->getUID()] ??= $user; } + } - $group = $this->groupManager->get(gid: $groupId); - if ($group === null) { - continue; - } + return array_values(array: $byUid); + }//end collectGroupMembers() - foreach ($group->getUsers() as $user) { - $uid = $user->getUID(); - if (isset($seen[$uid]) === true) { - continue; - } + /** + * The users of one group; none for a malformed id or a missing group. + * + * @param mixed $groupId The group ID. + * + * @return IUser[] The users. + */ + private function groupUsers(mixed $groupId): array { + if (is_string(value: $groupId) === false || $groupId === '') { + return []; + } - $seen[$uid] = true; - $result[] = $user; - } - }//end foreach + $group = $this->groupManager->get(gid: $groupId); + if ($group === null) { + return []; + } - return $result; - }//end collectGroupMembers() + return $group->getUsers(); + }//end groupUsers() /** * Stable ordering helper. @@ -619,8 +805,9 @@ private function primaryGroup(IUser $user): string { * unconditionally (REQ-PPL-005). * * @return array<string, mixed> + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 */ - private function buildUserProfile(IUser $user, bool $showBirthdays): array { + public function buildUserProfile(IUser $user, bool $showBirthdays): array { $uid = $user->getUID(); $profile = [ @@ -663,39 +850,97 @@ private function buildAccountFields(IUser $user, bool $showBirthdays): array { } $fields = []; - foreach (self::STANDARD_PROPERTIES as $property) { - if ($property === IAccountManager::PROPERTY_BIRTHDATE - && $showBirthdays === false - ) { - continue; - } + foreach (self::shownProperties(showBirthdays: $showBirthdays) as $property) { + $value = $this->visibleValue(account: $account, property: $property, ownerId: $user->getUID()); + $fields += self::accountField(property: $property, value: $value); + } - try { - $prop = $account->getProperty(property: $property); - $value = $prop->getValue(); - } catch (Exception $e) { - continue; - } + return $fields; + }//end buildAccountFields() - if ($value === '') { - continue; - } + /** + * The standard properties to show, without the birthdate when + * birthdays are switched off. + * + * @param bool $showBirthdays Whether birthdates show. + * + * @return string[] The properties, in display order. + */ + private static function shownProperties(bool $showBirthdays): array { + if ($showBirthdays === true) { + return self::STANDARD_PROPERTIES; + } - if ($property === IAccountManager::PROPERTY_BIRTHDATE) { - $iso = self::normaliseToIsoDate(raw: $value); - if ($iso === null) { - continue; - } + return array_values( + array: array_filter( + array: self::STANDARD_PROPERTIES, + callback: static fn (string $property): bool => $property !== IAccountManager::PROPERTY_BIRTHDATE + ) + ); + }//end shownProperties() - $fields['birthdate'] = $iso; - continue; - } + /** + * One account field for the profile: none for an empty value or an + * unparsable birthdate; the birthdate normalised to ISO. + * + * @param string $property The account property. + * @param string|null $value Its visible value, if any. + * + * @return array<string, string> The field, or `[]`. + */ + private static function accountField(string $property, ?string $value): array { + if ($value === null || $value === '') { + return []; + } - $fields[$property] = $value; - }//end foreach + if ($property === IAccountManager::PROPERTY_BIRTHDATE) { + return self::birthdateField(value: $value); + } - return $fields; - }//end buildAccountFields() + return [$property => $value]; + }//end accountField() + + /** + * The birthdate field, normalised to ISO; none when it cannot be parsed. + * + * @param string $value The stored birthdate. + * + * @return array<string, string> The field, or `[]`. + */ + private static function birthdateField(string $value): array { + $iso = self::normaliseToIsoDate(raw: $value); + if ($iso === null) { + return []; + } + + return ['birthdate' => $iso]; + }//end birthdateField() + + /** + * A standard property's value when the viewer may see it (REQ-PEX-004: + * a private field shows to its owner only), else null. + * + * @param IAccount $account The owner's account. + * @param string $property The property name. + * @param string $ownerId The owner's user id. + * + * @return string|null The value, or null when unreadable or hidden. + * + * @spec openspec/specs/people-widget/spec.md + */ + private function visibleValue(IAccount $account, string $property, string $ownerId): ?string { + try { + $prop = $account->getProperty(property: $property); + } catch (Exception) { + return null; + } + + if ($this->profileFields->scopeAllows(scope: $prop->getScope(), viewerId: $this->viewerId, ownerId: $ownerId) === false) { + return null; + } + + return $prop->getValue(); + }//end visibleValue() /** * Build an absolute avatar URL pointing at the standard NC route. @@ -726,11 +971,7 @@ private function buildAvatarUrl(string $uid): string { * be parsed. */ private static function normaliseToIsoDate(?string $raw): ?string { - if ($raw === null) { - return null; - } - - $trimmed = trim(string: $raw); + $trimmed = trim(string: (string)$raw); if ($trimmed === '') { return null; } @@ -740,9 +981,20 @@ private static function normaliseToIsoDate(?string $raw): ?string { return $trimmed; } - $separators = ['-', '/', '.']; - foreach ($separators as $sep) { - $parts = explode(separator: $sep, string: $trimmed); + return self::isoFromSeparatedDate(date: $trimmed); + }//end normaliseToIsoDate() + + /** + * Try each of the `-`, `/` and `.` separators on a date string and + * answer the first split into three segments that forms a real date. + * + * @param string $date The trimmed stored date. + * + * @return string|null `YYYY-MM-DD`, or null when no separator fits. + */ + private static function isoFromSeparatedDate(string $date): ?string { + foreach (['-', '/', '.'] as $sep) { + $parts = explode(separator: $sep, string: $date); if (count(value: $parts) !== 3) { continue; } @@ -751,10 +1003,10 @@ private static function normaliseToIsoDate(?string $raw): ?string { if ($iso !== null) { return $iso; } - }//end foreach + } return null; - }//end normaliseToIsoDate() + }//end isoFromSeparatedDate() /** * Assemble an ISO-8601 date from three already-split date segments. @@ -771,39 +1023,56 @@ private static function normaliseToIsoDate(?string $raw): ?string { * valid date. */ private static function isoFromDateParts(array $parts): ?string { - if (strlen(string: $parts[2]) !== 4 && strlen(string: $parts[0]) !== 4) { + $yearMonthDay = self::yearMonthDayOrder(parts: $parts); + if ($yearMonthDay === null || self::allDigits(segments: $yearMonthDay) === false) { return null; } - $day = ''; - $month = ''; - $year = ''; - if (strlen(string: $parts[2]) === 4) { - $day = $parts[0]; - $month = $parts[1]; - $year = $parts[2]; + [$year, $month, $day] = $yearMonthDay; + if (checkdate(month: (int)$month, day: (int)$day, year: (int)$year) === false) { + return null; } + return sprintf('%04d-%02d-%02d', (int)$year, (int)$month, (int)$day); + }//end isoFromDateParts() + + /** + * The segments in year, month, day order: YMD when the first segment + * has four characters, else DMY when the last one has; null when + * neither does. + * + * @param array $parts Exactly three date segments. + * + * @return array<int,string>|null The year, month and day segments, or null. + */ + private static function yearMonthDayOrder(array $parts): ?array { if (strlen(string: $parts[0]) === 4) { - $year = $parts[0]; - $month = $parts[1]; - $day = $parts[2]; + return [$parts[0], $parts[1], $parts[2]]; } - if (ctype_digit(text: $year) === false - || ctype_digit(text: $month) === false - || ctype_digit(text: $day) === false - ) { - return null; + if (strlen(string: $parts[2]) === 4) { + return [$parts[2], $parts[1], $parts[0]]; } - $iso = sprintf('%04d-%02d-%02d', (int)$year, (int)$month, (int)$day); - if (checkdate(month: (int)$month, day: (int)$day, year: (int)$year) === false) { - return null; + return null; + }//end yearMonthDayOrder() + + /** + * Whether every segment consists of digits only. + * + * @param array<int,string> $segments The date segments. + * + * @return bool True when all are digit strings. + */ + private static function allDigits(array $segments): bool { + foreach ($segments as $segment) { + if (ctype_digit(text: $segment) === false) { + return false; + } } - return $iso; - }//end isoFromDateParts() + return true; + }//end allDigits() /** * Construct a `DateTimeImmutable` for the given month-day in the diff --git a/lib/Service/PermissionService.php b/lib/Service/PermissionService.php index 266a9c001..238867d27 100644 --- a/lib/Service/PermissionService.php +++ b/lib/Service/PermissionService.php @@ -21,13 +21,13 @@ namespace OCA\LaunchPad\Service; -use Exception; use OCA\LaunchPad\Db\AdminSetting; use OCA\LaunchPad\Db\AdminSettingMapper; use OCA\LaunchPad\Db\Dashboard; use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacement; use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Exception\ForbiddenException; use OCP\AppFramework\Db\DoesNotExistException; use OCP\IGroupManager; @@ -109,9 +109,8 @@ public function canViewDashboard(string $userId, int $dashboardId): bool { * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-22 */ public function canEditDashboard(string $userId, int $dashboardId): bool { - try { - $dashboard = $this->dashboardMapper->find(id: $dashboardId); - } catch (DoesNotExistException) { + $dashboard = $this->findDashboard(dashboardId: $dashboardId); + if ($dashboard === null) { return false; } @@ -120,21 +119,44 @@ public function canEditDashboard(string $userId, int $dashboardId): bool { return false; } - // REQ-ROLE-001 / REQ-ROLE-007: LaunchPad Admin can edit any - // dashboard except for the admin-template type which is gated - // by Nextcloud admin status only (REQ-PERM-011). - if ($this->roleService->isAdmin(userId: $userId) === true - && $dashboard->getType() !== Dashboard::TYPE_ADMIN_TEMPLATE - ) { + if ($this->isAdminEditable(userId: $userId, dashboard: $dashboard) === true) { return true; } - // Admin templates can only be edited by admins. + // REQ-PERM-011: admin templates are edited by Nextcloud admins only. if ($dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE) { - return false; + return $this->groupManager->isAdmin(userId: $userId); } - $level = $this->resolveAccessLevel(userId: $userId, dashboard: $dashboard); + return $this->allowsEditing( + level: $this->resolveAccessLevel(userId: $userId, dashboard: $dashboard) + ); + }//end canEditDashboard() + + /** + * REQ-ROLE-001 / REQ-ROLE-007: LaunchPad Admin can edit any dashboard + * except for the admin-template type which is gated by Nextcloud admin + * status only (REQ-PERM-011). + * + * @param string $userId The user ID. + * @param Dashboard $dashboard The dashboard. + * + * @return bool TRUE when the admin role alone grants editing. + */ + private function isAdminEditable(string $userId, Dashboard $dashboard): bool { + return $this->roleService->isAdmin(userId: $userId) === true + && $dashboard->getType() !== Dashboard::TYPE_ADMIN_TEMPLATE; + }//end isAdminEditable() + + /** + * Whether an access level lets its holder change the dashboard: + * add_only and full do, view_only and no access do not. + * + * @param string|null $level The resolved access level. + * + * @return bool TRUE for add_only or full. + */ + private function allowsEditing(?string $level): bool { if ($level === null) { return false; } @@ -146,7 +168,7 @@ public function canEditDashboard(string $userId, int $dashboardId): bool { Dashboard::PERMISSION_FULL, ] ); - }//end canEditDashboard() + }//end allowsEditing() /** * Check if user can edit dashboard metadata (name, description). Owner only. @@ -162,24 +184,42 @@ public function canEditDashboardMetadata( string $userId, int $dashboardId, ): bool { - try { - $dashboard = $this->dashboardMapper->find(id: $dashboardId); - } catch (DoesNotExistException) { + $dashboard = $this->findDashboard(dashboardId: $dashboardId); + if ($dashboard === null) { + return false; + } + + // REQ-ROLE-008: Viewer role blocks any mutation, renames included. + if ($this->roleService->isViewer(userId: $userId) === true) { return false; } - // L4: admin-template owners retain full metadata-edit rights - // (REQ-PERM-011). An admin who owns a template must not be blocked - // from renaming it. Non-admin users can never edit admin templates. + // REQ-PERM-011: admin templates are edited by Nextcloud admins only, + // and belong to nobody (their userId is null), so ownership is not + // asked. Non-admin users can never edit admin templates. if ($dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE) { - return $dashboard->getUserId() === $userId - && $this->groupManager->isAdmin(userId: $userId); + return $this->groupManager->isAdmin(userId: $userId); } // Only owner can rename / change description. return $dashboard->getUserId() === $userId; }//end canEditDashboardMetadata() + /** + * Check if the user's role lets them delete dashboards at all. Which + * dashboard they may delete is the owner check of the delete itself. + * + * @param string $userId The user ID. + * + * @return bool Whether the user may delete dashboards. + * + * @spec openspec/specs/admin-roles/spec.md#requirement-req-role-008-authorize-viewer-read-only-access + */ + public function canDeleteDashboards(string $userId): bool { + // REQ-ROLE-008: Viewer role blocks any mutation, even of what they own. + return $this->roleService->isViewer(userId: $userId) === false; + }//end canDeleteDashboards() + /** * Check if user can add widgets to a dashboard. * @@ -198,20 +238,73 @@ public function canAddWidget(string $userId, int $dashboardId): bool { return false; } - $level = $this->resolveAccessLevel(userId: $userId, dashboardId: $dashboardId); - if ($level === null) { + $dashboard = $this->findDashboard(dashboardId: $dashboardId); + if ($dashboard === null) { return false; } - return in_array( - needle: $level, - haystack: [ - Dashboard::PERMISSION_ADD_ONLY, - Dashboard::PERMISSION_FULL, - ] + // REQ-PERM-011 / REQ-TMPL-007: an admin template belongs to nobody; + // a Nextcloud admin manages its widgets through the same API. + if ($dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE) { + return $this->groupManager->isAdmin(userId: $userId); + } + + return $this->allowsEditing( + level: $this->resolveAccessLevel(userId: $userId, dashboard: $dashboard) ); }//end canAddWidget() + /** + * Whether a widget the user adds may be marked compulsory: only a + * Nextcloud admin adding it to an admin template (REQ-TMPL-007). + * + * @param string $userId The user ID. + * @param int $dashboardId The dashboard ID. + * + * @return bool TRUE when the compulsory flag is honoured. + * + * @spec openspec/specs/admin-templates/spec.md#requirement-template-widget-management-req-tmpl-007 + */ + public function mayPlaceCompulsory(string $userId, int $dashboardId): bool { + $dashboard = $this->findDashboard(dashboardId: $dashboardId); + + return $dashboard !== null + && $dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE + && $this->groupManager->isAdmin(userId: $userId) === true; + }//end mayPlaceCompulsory() + + /** + * Why a widget change was refused, in the words of REQ-PERM-001 and + * REQ-PERM-004: a view-only dashboard says so, and so does a compulsory + * widget on an add-only dashboard; anything else is "Access denied". + * + * @param string $userId The user ID. + * @param int|null $dashboardId The dashboard, for an add. + * @param int|null $placementId The placement, for a removal. + * + * @return string The refusal message. + * + * @spec openspec/specs/permissions/spec.md + */ + public function widgetRefusal(string $userId, ?int $dashboardId = null, ?int $placementId = null): string { + $placement = null; + if ($placementId !== null) { + $placement = $this->findPlacement(placementId: $placementId); + $dashboardId = $placement?->getDashboardId(); + } + + $level = $this->resolveAccessLevel(userId: $userId, dashboardId: $dashboardId); + if ($level === Dashboard::PERMISSION_VIEW_ONLY) { + return 'This dashboard is view-only'; + } + + if ($level === Dashboard::PERMISSION_ADD_ONLY && $placement?->getIsCompulsory() === 1) { + return 'Compulsory widgets cannot be removed at this permission level'; + } + + return 'Access denied'; + }//end widgetRefusal() + /** * Check if user can remove a widget. * @@ -228,24 +321,33 @@ public function canRemoveWidget(string $userId, int $placementId): bool { return false; } - try { - $placement = $this->placementMapper->find(id: $placementId); - $dashboard = $this->dashboardMapper->find( - id: $placement->getDashboardId() - ); - } catch (DoesNotExistException) { + $placed = $this->findPlacedWidget(placementId: $placementId); + if ($placed === null) { return false; } - $level = $this->resolveAccessLevel(userId: $userId, dashboard: $dashboard); - if ($level === null) { - return false; + // REQ-PERM-011 / REQ-TMPL-007: only a Nextcloud admin removes a + // widget from an admin template. + if ($placed->dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE) { + return $this->groupManager->isAdmin(userId: $userId); } - if ($level === Dashboard::PERMISSION_VIEW_ONLY) { - return false; - } + $level = $this->resolveAccessLevel(userId: $userId, dashboard: $placed->dashboard); + return $this->allowsRemoval(level: $level, placement: $placed->placement); + }//end canRemoveWidget() + + /** + * Whether an access level lets its holder remove a placement: full + * removes any, add_only only a non-compulsory one, view_only and no + * access none. + * + * @param string|null $level The resolved access level. + * @param WidgetPlacement $placement The placement to remove. + * + * @return bool TRUE when removal is allowed. + */ + private function allowsRemoval(?string $level, WidgetPlacement $placement): bool { if ($level === Dashboard::PERMISSION_FULL) { return true; } @@ -255,7 +357,7 @@ public function canRemoveWidget(string $userId, int $placementId): bool { } return false; - }//end canRemoveWidget() + }//end allowsRemoval() /** * Check if user can view a widget's data (read-path). @@ -273,9 +375,8 @@ public function canRemoveWidget(string $userId, int $placementId): bool { * @spec openspec/specs/permissions/spec.md */ public function canViewPlacement(string $userId, int $placementId): bool { - try { - $placement = $this->placementMapper->find(id: $placementId); - } catch (DoesNotExistException) { + $placement = $this->findPlacement(placementId: $placementId); + if ($placement === null) { return false; } @@ -301,26 +402,19 @@ public function canStyleWidget(string $userId, int $placementId): bool { return false; } - try { - $placement = $this->placementMapper->find(id: $placementId); - $dashboard = $this->dashboardMapper->find( - id: $placement->getDashboardId() - ); - } catch (DoesNotExistException) { + $placed = $this->findPlacedWidget(placementId: $placementId); + if ($placed === null) { return false; } - $level = $this->resolveAccessLevel(userId: $userId, dashboard: $dashboard); - if ($level === null) { - return false; + // REQ-PERM-011: an admin template belongs to nobody and is never + // shared, so only Nextcloud admin status lets its widgets change. + if ($placed->dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE) { + return $this->groupManager->isAdmin(userId: $userId); } - return in_array( - needle: $level, - haystack: [ - Dashboard::PERMISSION_ADD_ONLY, - Dashboard::PERMISSION_FULL, - ] + return $this->allowsEditing( + level: $this->resolveAccessLevel(userId: $userId, dashboard: $placed->dashboard) ); }//end canStyleWidget() @@ -396,6 +490,7 @@ public function canHaveMultipleDashboards(): bool { * @return string The effective permission level. * * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-24 + * @spec openspec/specs/admin-settings/spec.md#requirement-retrieve-admin-settings-req-aset-001 */ public function getEffectivePermissionLevel( Dashboard $dashboard, @@ -406,33 +501,13 @@ public function getEffectivePermissionLevel( // the row's persisted `permissionLevel` field (which is kept on // the row for forward-compat with future per-tile editing). if ($dashboard->getType() === Dashboard::TYPE_GROUP_SHARED) { - // REQ-ROLE-001 / REQ-ROLE-007: NC admin OR a LaunchPad Admin - // role grants full permissions on group_shared dashboards. - // Editors get full access only when the underlying group - // membership check (in `resolveAccessLevel`) has already - // succeeded — they edit through the membership path, not - // an unconditional override. - if ($userId !== null - && ($this->groupManager->isAdmin(userId: $userId) === true - || $this->roleService->isAdmin(userId: $userId) === true - || $this->roleService->isEditorOrHigher(userId: $userId) === true) - ) { - return Dashboard::PERMISSION_FULL; - } - - return Dashboard::PERMISSION_VIEW_ONLY; + return $this->groupSharedPermissionLevel(userId: $userId); } // If based on a template, use template's permission level. - if ($dashboard->getBasedOnTemplate() !== null) { - try { - $template = $this->dashboardMapper->find( - id: $dashboard->getBasedOnTemplate() - ); - return $template->getPermissionLevel(); - } catch (DoesNotExistException) { - // Template deleted, use dashboard's level. - } + $templateLevel = $this->templatePermissionLevel(dashboard: $dashboard); + if ($templateLevel !== null) { + return $templateLevel; } // Use dashboard's permission level or default. @@ -441,12 +516,59 @@ public function getEffectivePermissionLevel( return $level; } + // The factory default is add_only, the value GET /api/admin/settings + // reports while no level is stored (REQ-ASET-001); both read it here. return $this->settingMapper->getValue( key: AdminSetting::KEY_DEFAULT_PERMISSION_LEVEL, - default: Dashboard::PERMISSION_FULL + default: Dashboard::PERMISSION_ADD_ONLY ); }//end getEffectivePermissionLevel() + /** + * REQ-ROLE-001 / REQ-ROLE-007: NC admin OR a LaunchPad Admin role + * grants full permissions on group_shared dashboards. Editors get full + * access only when the underlying group membership check (in + * `resolveAccessLevel`) has already succeeded — they edit through the + * membership path, not an unconditional override. + * + * @param string|null $userId The user ID, or NULL for no user. + * + * @return string Full for admins and editors, view_only otherwise. + */ + private function groupSharedPermissionLevel(?string $userId): string { + if ($userId !== null + && ($this->groupManager->isAdmin(userId: $userId) === true + || $this->roleService->isAdmin(userId: $userId) === true + || $this->roleService->isEditorOrHigher(userId: $userId) === true) + ) { + return Dashboard::PERMISSION_FULL; + } + + return Dashboard::PERMISSION_VIEW_ONLY; + }//end groupSharedPermissionLevel() + + /** + * The permission level of the template a dashboard is based on; NULL + * when it is not based on one or the template was deleted. + * + * @param Dashboard $dashboard The dashboard. + * + * @return string|null The template's permission level. + */ + private function templatePermissionLevel(Dashboard $dashboard): ?string { + if ($dashboard->getBasedOnTemplate() === null) { + return null; + } + + $template = $this->findDashboard(dashboardId: $dashboard->getBasedOnTemplate()); + if ($template === null) { + // Template deleted, use dashboard's level. + return null; + } + + return $template->getPermissionLevel(); + }//end templatePermissionLevel() + /** * Resolve the effective permission level a user has on a dashboard: * - If the user is the owner, returns the dashboard's effective level. @@ -468,42 +590,31 @@ public function resolveAccessLevel( ?int $dashboardId = null, ?Dashboard $dashboard = null, ): ?string { + $dashboard = ($dashboard ?? $this->findDashboard(dashboardId: $dashboardId)); if ($dashboard === null) { - try { - $dashboard = $this->dashboardMapper->find(id: $dashboardId); - } catch (DoesNotExistException) { - return null; - } + return null; } // Group-shared dashboards bypass the ownership-vs-share path: // visibility is by group membership, not by per-row sharing. // REQ-DASH-014. if ($dashboard->getType() === Dashboard::TYPE_GROUP_SHARED) { - $groupId = (string)$dashboard->getGroupId(); - if ($groupId === Dashboard::DEFAULT_GROUP_ID) { - return $this->getEffectivePermissionLevel( - dashboard: $dashboard, - userId: $userId - ); - } - - $userGroupIds = $this->adminTemplateService->getUserGroupIdsFor( - userId: $userId - ); - if (in_array(needle: $groupId, haystack: $userGroupIds, strict: true) === true - || $this->groupManager->isAdmin(userId: $userId) === true - || $this->roleService->isAdmin(userId: $userId) === true - ) { - return $this->getEffectivePermissionLevel( - dashboard: $dashboard, - userId: $userId - ); - }//end if + return $this->groupSharedAccessLevel(userId: $userId, dashboard: $dashboard); + } - return null; - }//end if + return $this->ownedOrSharedAccessLevel(userId: $userId, dashboard: $dashboard); + }//end resolveAccessLevel() + /** + * The access level on a personal dashboard: its effective level for + * the owner, the shared level for anyone else. + * + * @param string $userId The user ID. + * @param Dashboard $dashboard The dashboard. + * + * @return string|null The access level, or NULL for no access. + */ + private function ownedOrSharedAccessLevel(string $userId, Dashboard $dashboard): ?string { if ($dashboard->getUserId() === $userId) { return $this->getEffectivePermissionLevel( dashboard: $dashboard, @@ -511,6 +622,65 @@ public function resolveAccessLevel( ); } + return $this->sharedAccessLevel(userId: $userId, dashboard: $dashboard); + }//end ownedOrSharedAccessLevel() + + /** + * The access level on a group-shared dashboard: its effective level + * for members of its group (everyone for the default group) and for + * admins, NULL for anyone else. + * + * @param string $userId The user ID. + * @param Dashboard $dashboard The group-shared dashboard. + * + * @return string|null The access level, or NULL for no access. + */ + private function groupSharedAccessLevel(string $userId, Dashboard $dashboard): ?string { + if ($this->reachesGroupDashboard(userId: $userId, dashboard: $dashboard) === false) { + return null; + } + + return $this->getEffectivePermissionLevel( + dashboard: $dashboard, + userId: $userId + ); + }//end groupSharedAccessLevel() + + /** + * Whether a user reaches a group-shared dashboard: it is shared with + * the default group, the user is in its group, or the user is an NC + * admin or a LaunchPad Admin. + * + * @param string $userId The user ID. + * @param Dashboard $dashboard The group-shared dashboard. + * + * @return bool TRUE when the user reaches it. + */ + private function reachesGroupDashboard(string $userId, Dashboard $dashboard): bool { + $groupId = (string)$dashboard->getGroupId(); + if ($groupId === Dashboard::DEFAULT_GROUP_ID) { + return true; + } + + $userGroupIds = $this->adminTemplateService->getUserGroupIdsFor( + userId: $userId + ); + + return in_array(needle: $groupId, haystack: $userGroupIds, strict: true) === true + || $this->groupManager->isAdmin(userId: $userId) === true + || $this->roleService->isAdmin(userId: $userId) === true; + }//end reachesGroupDashboard() + + /** + * The access level a user holds on someone else's dashboard through a + * user or group share, NULL when it is not shared with them. + * + * @param string $userId The user ID. + * @param Dashboard $dashboard The dashboard. + * + * @return string|null The shared access level. + */ + private function sharedAccessLevel(string $userId, Dashboard $dashboard): ?string { $shares = $this->shareService->resolveSharedDashboards( userId: $userId, groupIds: $this->adminTemplateService->getUserGroupIdsFor( @@ -519,7 +689,7 @@ public function resolveAccessLevel( ); return $shares[$dashboard->getId()] ?? null; - }//end resolveAccessLevel() + }//end sharedAccessLevel() /** * Verify user owns a dashboard. @@ -540,7 +710,7 @@ public function verifyDashboardOwnership( $dashboard = $this->dashboardMapper->find(id: $dashboardId); if ($dashboard->getUserId() !== $userId) { - throw new Exception(message: 'Access denied'); + throw new ForbiddenException(message: 'Access denied'); } return $dashboard; @@ -548,11 +718,14 @@ public function verifyDashboardOwnership( /** * Whether the user may set/change/clear the mandatory-read - * acknowledgement requirement on a placement — a Nextcloud admin, a - * LaunchPad admin, or the owner of the placement's dashboard (the - * template author). A non-author MUST be rejected (REQ-ACK-001, - * ADR-005). Returns false when the placement or its dashboard is - * missing. + * acknowledgement requirement on a placement: a Nextcloud admin, a + * LaunchPad admin, or the author of the announcement. Once a placement + * carries an announcement key the author is the owner of the + * announcement's admin template, or, without a template, the owner of + * the first placement that carried the key; a recipient of a copy is not + * the author. Before that, the owner of the placement's dashboard may set + * a requirement. A non-author MUST be rejected (REQ-ACK-001, ADR-005). + * Returns false when the placement or its dashboard is missing. * * @param string $userId The acting user ID. * @param int $placementId The placement ID. @@ -571,20 +744,117 @@ public function canManageAcknowledgement( return true; } - try { - $placement = $this->placementMapper->find(id: $placementId); - $dashboard = $this->dashboardMapper->find( - id: $placement->getDashboardId() - ); - } catch (DoesNotExistException) { + $placed = $this->findPlacedWidget(placementId: $placementId); + if ($placed === null) { return false; } - return $dashboard->getUserId() === $userId; + $key = (string)$placed->placement->getAnnouncementKey(); + if ($key === '') { + return $placed->dashboard->getUserId() === $userId; + } + + return $this->announcementAuthor(announcementKey: $key) === $userId; }//end canManageAcknowledgement() /** - * Verify user owns a placement's dashboard. + * The author of an announcement: the owner of the admin template that + * carries the key, or, without one, the owner of the placement with the + * lowest id (the original; copies and forks are created later). + * + * @param string $announcementKey The announcement identity. + * + * @return string|null The author's user id, or null. + */ + private function announcementAuthor(string $announcementKey): ?string { + $original = null; + foreach ($this->placementMapper->findByAnnouncementKey(announcementKey: $announcementKey) as $placement) { + $dashboard = $this->findDashboard(dashboardId: $placement->getDashboardId()); + if ($dashboard === null) { + continue; + } + + if ($dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE) { + return $dashboard->getUserId(); + } + + if ($this->isEarlierCopy(placement: $placement, original: $original) === true) { + $original = [$placement->getId(), $dashboard->getUserId()]; + } + } + + return $original[1] ?? null; + }//end announcementAuthor() + + /** + * Whether a placement is an earlier copy of the announcement than the + * earliest one seen so far. + * + * @param WidgetPlacement $placement The placement. + * @param array{0: int, 1: string}|null $original The earliest copy so far: [placement id, owner]. + * + * @return bool TRUE when it is the first or an earlier copy. + */ + private function isEarlierCopy(WidgetPlacement $placement, ?array $original): bool { + return $original === null || $placement->getId() < $original[0]; + }//end isEarlierCopy() + + /** + * Find a dashboard by id, NULL when it does not exist. + * + * @param int|null $dashboardId The dashboard ID. + * + * @return Dashboard|null The dashboard. + */ + private function findDashboard(?int $dashboardId): ?Dashboard { + try { + return $this->dashboardMapper->find(id: $dashboardId); + } catch (DoesNotExistException) { + return null; + } + }//end findDashboard() + + /** + * Find a placement by id, NULL when it does not exist. + * + * @param int $placementId The placement ID. + * + * @return WidgetPlacement|null The placement. + */ + private function findPlacement(int $placementId): ?WidgetPlacement { + try { + return $this->placementMapper->find(id: $placementId); + } catch (DoesNotExistException) { + return null; + } + }//end findPlacement() + + /** + * Find a placement and the dashboard it sits on, NULL when either does + * not exist. + * + * @param int $placementId The placement ID. + * + * @return PlacedWidget|null The placement and its dashboard. + */ + private function findPlacedWidget(int $placementId): ?PlacedWidget { + $placement = $this->findPlacement(placementId: $placementId); + if ($placement === null) { + return null; + } + + $dashboard = $this->findDashboard(dashboardId: $placement->getDashboardId()); + if ($dashboard === null) { + return null; + } + + return new PlacedWidget(placement: $placement, dashboard: $dashboard); + }//end findPlacedWidget() + + /** + * Verify user owns a placement's dashboard, or is a Nextcloud + * administrator, who may manage the visibility rules of every dashboard + * (REQ-VIS-001..004). * * @param string $userId The user ID. * @param int $placementId The placement ID. @@ -594,12 +864,17 @@ public function canManageAcknowledgement( * @throws \Exception If access is denied. * * @spec openspec/specs/permissions/spec.md + * @spec openspec/specs/conditional-visibility/spec.md */ public function verifyPlacementOwnership( string $userId, int $placementId, ): WidgetPlacement { $placement = $this->placementMapper->find(id: $placementId); + if ($this->groupManager->isAdmin(userId: $userId) === true) { + return $placement; + } + $this->verifyDashboardOwnership( userId: $userId, dashboardId: $placement->getDashboardId() diff --git a/lib/Service/PersonalLayerService.php b/lib/Service/PersonalLayerService.php index 981dc4821..b6a76d7de 100644 --- a/lib/Service/PersonalLayerService.php +++ b/lib/Service/PersonalLayerService.php @@ -29,7 +29,7 @@ * * @link https://conduction.nl * - * @spec openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md */ declare(strict_types=1); @@ -40,13 +40,14 @@ use OCA\LaunchPad\Db\PersonalLayer; use OCA\LaunchPad\Db\PersonalLayerMapper; use OCA\LaunchPad\Db\WidgetPlacement; +use OCA\LaunchPad\Kernel\Contracts\PersonalLayerServiceInterface; /** * Applies, saves and resets a personal layer. * - * @spec openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md */ -class PersonalLayerService { +class PersonalLayerService implements PersonalLayerServiceInterface { /** * The placement keys a person may change about a placement. Anything else * a client sends is dropped: a layer holds geometry and order, never @@ -74,7 +75,7 @@ public function __construct( * @return array<int, WidgetPlacement> The placements this person sees, in * their order. A person with no layer gets the input back. * - * @spec openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md */ public function applyTo(array $placements, string $userId, int $dashboardId): array { $layer = $this->layerFor(userId: $userId, dashboardId: $dashboardId); @@ -122,24 +123,16 @@ static function (WidgetPlacement $first, WidgetPlacement $second): int { * @return array{saved: true}|array{error: string, placementId: int} The * refusal names the placement, so the message can say which widget. * - * @spec openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md */ public function save(string $userId, int $dashboardId, array $overrides, array $hide, array $placements): array { - $compulsory = []; - $known = []; - foreach ($placements as $placement) { - $known[] = (int)$placement->getId(); - if ($this->isCompulsory(placement: $placement) === true) { - $compulsory[] = (int)$placement->getId(); - } - } + [$known, $compulsory] = $this->knownAndCompulsoryIds(placements: $placements); - foreach ($hide as $placementId) { - if (in_array((int)$placementId, $compulsory, true) === true) { - // Refused before anything is written, so a batch that touches - // a compulsory widget lands nothing at all. - return ['error' => 'placement_compulsory', 'placementId' => (int)$placementId]; - } + $refused = $this->firstCompulsoryHidden(hide: $hide, compulsory: $compulsory); + if ($refused !== null) { + // Refused before anything is written, so a batch that touches + // a compulsory widget lands nothing at all. + return ['error' => 'placement_compulsory', 'placementId' => $refused]; } $layer = $this->layerFor(userId: $userId, dashboardId: $dashboardId); @@ -165,6 +158,45 @@ public function save(string $userId, int $dashboardId, array $overrides, array $ return ['saved' => true]; }//end save() + /** + * The ids of the shared placements, and those of the compulsory ones. + * + * @param array<int, WidgetPlacement> $placements The shared placements. + * + * @return array{0: array<int, int>, 1: array<int, int>} Every placement id, + * and the compulsory placement ids. + */ + private function knownAndCompulsoryIds(array $placements): array { + $compulsory = []; + $known = []; + foreach ($placements as $placement) { + $known[] = (int)$placement->getId(); + if ($this->isCompulsory(placement: $placement) === true) { + $compulsory[] = (int)$placement->getId(); + } + } + + return [$known, $compulsory]; + }//end knownAndCompulsoryIds() + + /** + * The first placement id asked to be hidden that is compulsory. + * + * @param array<int, int> $hide The placement ids asked to be hidden. + * @param array<int, int> $compulsory The compulsory placement ids. + * + * @return int|null The refused placement id, or null when none is compulsory. + */ + private function firstCompulsoryHidden(array $hide, array $compulsory): ?int { + foreach ($hide as $placementId) { + if (in_array((int)$placementId, $compulsory, true) === true) { + return (int)$placementId; + } + } + + return null; + }//end firstCompulsoryHidden() + /** * Put the dashboard back to what its owner composed. * @@ -174,7 +206,7 @@ public function save(string $userId, int $dashboardId, array $overrides, array $ * @return bool True when a layer was there and is now gone. False means * there was nothing to reset, which is not a failure. * - * @spec openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md */ public function reset(string $userId, int $dashboardId): bool { return ($this->layers->deleteForUser(userId: $userId, dashboardId: $dashboardId) > 0); @@ -208,7 +240,7 @@ public function reset(string $userId, int $dashboardId): bool { * * @return int How many entries were dropped. * - * @spec openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md */ public function pruneOrphans(string $userId, int $dashboardId, array $liveIds): int { $layer = $this->layerFor(userId: $userId, dashboardId: $dashboardId); @@ -216,20 +248,10 @@ public function pruneOrphans(string $userId, int $dashboardId, array $liveIds): return 0; } - $live = array_map('intval', $liveIds); - $overrides = $layer->overridesArray(); - $hidden = $layer->hiddenArray(); + [$keptOverrides, $keptHidden] = $this->liveEntries(layer: $layer, liveIds: $liveIds); - $keptOverrides = array_filter( - $overrides, - static function (int $placementId) use ($live): bool { - return in_array($placementId, $live, true); - }, - ARRAY_FILTER_USE_KEY - ); - $keptHidden = array_values(array_intersect($hidden, $live)); - - $dropped = ((count($overrides) - count($keptOverrides)) + (count($hidden) - count($keptHidden))); + $dropped = ((count($layer->overridesArray()) - count($keptOverrides)) + + (count($layer->hiddenArray()) - count($keptHidden))); if ($dropped === 0) { return 0; } @@ -247,6 +269,55 @@ static function (int $placementId) use ($live): bool { return $dropped; }//end pruneOrphans() + /** + * Drop every person's entries for placements that are gone from one dashboard. + * + * Called after a template re-sync removed placements: one re-sync changes the + * dashboard for everybody, so the sweep walks every layer on it. + * + * @param int $dashboardId The dashboard. + * @param array<int, int> $liveIds The placement ids that still exist. + * + * @return int How many entries were dropped, over all layers. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + public function pruneDashboard(int $dashboardId, array $liveIds): int { + if ($dashboardId <= 0) { + return 0; + } + + $dropped = 0; + foreach ($this->layers->findByDashboard(dashboardId: $dashboardId) as $layer) { + $dropped += $this->pruneOrphans(userId: (string)$layer->getUserId(), dashboardId: $dashboardId, liveIds: $liveIds); + } + + return $dropped; + }//end pruneDashboard() + + /** + * The layer's overrides and hidden ids that still point at a live placement. + * + * @param PersonalLayer $layer The person's layer. + * @param array<int, int> $liveIds The placement ids that still exist. + * + * @return array{0: array<int, array<string, mixed>>, 1: array<int, int>} The + * kept overrides by placement id, and the kept hidden ids. + */ + private function liveEntries(PersonalLayer $layer, array $liveIds): array { + $live = array_map('intval', $liveIds); + + $keptOverrides = array_filter( + $layer->overridesArray(), + static function (int $placementId) use ($live): bool { + return in_array($placementId, $live, true); + }, + ARRAY_FILTER_USE_KEY + ); + + return [$keptOverrides, array_values(array_intersect($layer->hiddenArray(), $live))]; + }//end liveEntries() + /** * The person's layer, or null. * diff --git a/lib/Service/PingSettings.php b/lib/Service/PingSettings.php new file mode 100644 index 000000000..a0188cba1 --- /dev/null +++ b/lib/Service/PingSettings.php @@ -0,0 +1,46 @@ +<?php + +/** + * PingSettings + * + * The app config and the logger of the health ping service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\IAppConfig; +use Psr\Log\LoggerInterface; + +/** + * The app config and the logger of the health ping service. + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ +class PingSettings { + /** + * Constructor. + * + * @param IAppConfig $appConfig Admin config: allow-listed hosts, latency threshold. + * @param LoggerInterface $logger PSR logger. + */ + public function __construct( + public readonly IAppConfig $appConfig, + public readonly LoggerInterface $logger, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/PingTransport.php b/lib/Service/PingTransport.php new file mode 100644 index 000000000..49c0e0c8c --- /dev/null +++ b/lib/Service/PingTransport.php @@ -0,0 +1,46 @@ +<?php + +/** + * PingTransport + * + * The HTTP client and the cache factory of the health ping service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Http\Client\IClientService; +use OCP\ICacheFactory; + +/** + * The HTTP client and the cache factory of the health ping service. + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ +class PingTransport { + /** + * Constructor. + * + * @param IClientService $clientService HTTP client factory for the health-check request. + * @param ICacheFactory $cacheFactory Backing factory for the distributed badge cache. + */ + public function __construct( + public readonly IClientService $clientService, + public readonly ICacheFactory $cacheFactory, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/PlacedWidget.php b/lib/Service/PlacedWidget.php new file mode 100644 index 000000000..af29b6278 --- /dev/null +++ b/lib/Service/PlacedWidget.php @@ -0,0 +1,45 @@ +<?php + +/** + * PlacedWidget + * + * A widget placement together with the dashboard it sits on, as the + * placement-level permission checks read them. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\WidgetPlacement; + +/** + * A placement and its dashboard, both known to exist. + * + * @spec openspec/specs/permissions/spec.md + */ +final class PlacedWidget { + /** + * Constructor + * + * @param WidgetPlacement $placement The placement. + * @param Dashboard $dashboard The dashboard it sits on. + */ + public function __construct( + public readonly WidgetPlacement $placement, + public readonly Dashboard $dashboard, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/PlacementLayout.php b/lib/Service/PlacementLayout.php new file mode 100644 index 000000000..06991141c --- /dev/null +++ b/lib/Service/PlacementLayout.php @@ -0,0 +1,133 @@ +<?php + +/** + * PlacementLayout + * + * The grid layout of a widget placement as one comparable value, and the + * layout a template sync last gave a copy's placement (its baseline). A + * `merge` re-sync keeps the owner's position and size when the placement's + * current layout differs from that baseline (REQ-RESYNC-007). + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\WidgetPlacement; + +/** + * Reads, compares and stamps a placement's grid layout. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + */ +class PlacementLayout { + + /** + * The grid fields a layout is made of. + * + * @var array<int, string> + */ + public const FIELDS = ['gridX', 'gridY', 'gridWidth', 'gridHeight']; + + /** + * The placement's layout as `gridX,gridY,gridWidth,gridHeight`. + * + * @param WidgetPlacement $placement The placement. + * + * @return string The layout. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + */ + public function layoutOf(WidgetPlacement $placement): string { + return implode( + separator: ',', + array: [ + (int)$placement->getGridX(), + (int)$placement->getGridY(), + (int)$placement->getGridWidth(), + (int)$placement->getGridHeight(), + ] + ); + }//end layoutOf() + + /** + * The placement's layout as a rectangle. + * + * @param WidgetPlacement $placement The placement. + * + * @return array{gridX:int,gridY:int,gridWidth:int,gridHeight:int} The rectangle. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + */ + public function rectOf(WidgetPlacement $placement): array { + return [ + 'gridX' => (int)$placement->getGridX(), + 'gridY' => (int)$placement->getGridY(), + 'gridWidth' => (int)$placement->getGridWidth(), + 'gridHeight' => (int)$placement->getGridHeight(), + ]; + }//end rectOf() + + /** + * Record the placement's current layout as the one the template sync gave it. + * + * @param WidgetPlacement $placement The copy's placement (mutated). + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + */ + public function stamp(WidgetPlacement $placement): void { + $placement->setSyncedLayout($this->layoutOf(placement: $placement)); + }//end stamp() + + /** + * Whether the owner moved or resized the placement since the template last + * synced it. Unknown (no baseline) reads as not moved. + * + * @param WidgetPlacement $placement The copy's placement. + * + * @return bool True when the current layout differs from the baseline. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + */ + public function ownerMoved(WidgetPlacement $placement): bool { + $baseline = $placement->getSyncedLayout(); + if ($baseline === null || $baseline === '') { + return false; + } + + return $baseline !== $this->layoutOf(placement: $placement); + }//end ownerMoved() + + /** + * Put a layout back onto a placement. + * + * @param WidgetPlacement $placement The placement (mutated). + * @param array{gridX:int,gridY:int,gridWidth:int,gridHeight:int} $rect The layout. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + */ + public function apply(WidgetPlacement $placement, array $rect): void { + $placement->setGridX($rect['gridX']); + $placement->setGridY($rect['gridY']); + $placement->setGridWidth($rect['gridWidth']); + $placement->setGridHeight($rect['gridHeight']); + }//end apply() +}//end class diff --git a/lib/Service/PlacementPairing.php b/lib/Service/PlacementPairing.php new file mode 100644 index 000000000..aa6d484c3 --- /dev/null +++ b/lib/Service/PlacementPairing.php @@ -0,0 +1,356 @@ +<?php + +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * PlacementPairing + * + * Pairs the widgets a dashboard has now with the widgets a new version of its + * definition brings, and writes the result in place: a widget present in both + * keeps its row and is changed there, only a widget the new version adds gets + * a new row, and only one it drops loses its row. + * + * WHY THE ROWS ARE KEPT. A member's copy remembers, per widget, the id of the + * template widget it was made from, and re-sync matches on that id. Replacing + * every row would still give the right page, but each widget of every copy + * would be removed and added again. + * + * HOW A WIDGET IS RECOGNISED. A definition carries no key per widget, so the + * widgets are paired in three passes, each pass only over what the pass before + * left: (1) every compared field equal, (2) same widget type, same proxied + * Nextcloud widget and same title, (3) same widget type, when exactly one is + * left on each side. What is then left of the new version is added, what is + * left of the current one is removed. + * + * Shared by the shipped-template update (admin-templates REQ-TMPL-020) and the + * marketplace update (dashboard-store REQ-STORE-012). + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeImmutable; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\WidgetPlacement; +use RuntimeException; +use Throwable; + +/** + * Pair a dashboard's widgets with a new version's and write the plan. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ +class PlacementPairing { + /** + * The plain fields a definition sets on a widget, and the word the + * report uses for a change in each. `styleConfig` and `content` are + * compared as decoded JSON, see {@see self::snapshot()}. + * + * @var array<string, string> + */ + private const FIELD_WORDS = [ + 'widgetId' => 'type', + 'gridX' => 'position', + 'gridY' => 'position', + 'gridWidth' => 'size', + 'gridHeight' => 'size', + 'isCompulsory' => 'compulsory', + 'isVisible' => 'visibility', + 'showTitle' => 'title', + 'sortOrder' => 'order', + 'customTitle' => 'title', + 'customIcon' => 'icon', + 'tileType' => 'tile', + 'tileTitle' => 'tile', + 'tileIcon' => 'tile', + 'tileIconType' => 'tile', + 'tileBackgroundColor' => 'tile', + 'tileTextColor' => 'tile', + 'tileLinkType' => 'tile', + 'tileLinkValue' => 'tile', + 'styleConfig' => 'style', + 'content' => 'settings', + ]; + + /** + * Constructor. + * + * @param ShippedTemplateStores $stores The dashboard and placement mappers and the database. + */ + public function __construct( + private readonly ShippedTemplateStores $stores, + ) { + }//end __construct() + + + /** + * Pair the installed widgets with the new version's, in three passes. + * + * @param array<int, WidgetPlacement> $installed The template's widgets now. + * @param array<int, WidgetPlacement> $wanted The new version's widgets, unsaved. + * + * @return array{unchanged:array<int,WidgetPlacement>, added:array<int,WidgetPlacement>, + * changed:array<int,array{installed:WidgetPlacement, wanted:WidgetPlacement}>, + * removed:array<int,WidgetPlacement>} + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + public function pair(array $installed, array $wanted): array { + $exact = $this->pairBy( + installed: $installed, + wanted: $wanted, + key: fn (WidgetPlacement $p): string => (string)json_encode(value: $this->snapshot(placement: $p)), + uniqueOnly: false + ); + $named = $this->pairBy( + installed: $exact['installed'], + wanted: $exact['wanted'], + key: fn (WidgetPlacement $p): string => (string)json_encode( + value: [ + $p->getWidgetId(), + ($p->getContentArray()['widgetId'] ?? null), + $p->getCustomTitle(), + ] + ), + uniqueOnly: false + ); + $typed = $this->pairBy( + installed: $named['installed'], + wanted: $named['wanted'], + key: static fn (WidgetPlacement $p): string => (string)$p->getWidgetId(), + uniqueOnly: true + ); + + $unchanged = []; + foreach ($exact['pairs'] as $pair) { + $unchanged[] = $pair['installed']; + } + + return [ + 'unchanged' => $unchanged, + 'changed' => array_merge($named['pairs'], $typed['pairs']), + 'added' => $typed['wanted'], + 'removed' => $typed['installed'], + ]; + }//end pair() + + /** + * One pairing pass: widgets with the same key are paired in order. + * + * @param array<int, WidgetPlacement> $installed Installed widgets still unpaired. + * @param array<int, WidgetPlacement> $wanted New widgets still unpaired. + * @param callable $key Gives the key two widgets must share. + * @param bool $uniqueOnly Pair a key only when one widget on each side has it. + * + * @return array{pairs:array<int,array{installed:WidgetPlacement, wanted:WidgetPlacement}>, + * installed:array<int,WidgetPlacement>, wanted:array<int,WidgetPlacement>} + * + * @SuppressWarnings(PHPMD.BooleanArgumentFlag) + * Private, and the third pass is the only one that sets it. + */ + private function pairBy(array $installed, array $wanted, callable $key, bool $uniqueOnly): array { + $wantedByKey = []; + foreach ($wanted as $index => $placement) { + $wantedByKey[$key($placement)][] = $index; + } + + $installedCount = array_count_values(array: array_map(callback: $key, array: $installed)); + + $pairs = []; + $leftInstalled = []; + foreach ($installed as $placement) { + $itsKey = $key($placement); + $candidates = ($wantedByKey[$itsKey] ?? []); + $ambiguous = $uniqueOnly === true && ($installedCount[$itsKey] !== 1 || count($candidates) !== 1); + if ($candidates === [] || $ambiguous === true) { + $leftInstalled[] = $placement; + continue; + } + + $index = array_shift($wantedByKey[$itsKey]); + $pairs[] = ['installed' => $placement, 'wanted' => $wanted[$index]]; + unset($wanted[$index]); + } + + return ['pairs' => $pairs, 'installed' => $leftInstalled, 'wanted' => array_values(array: $wanted)]; + }//end pairBy() + + /** + * The fields a definition sets on a widget, in a form two widgets can be + * compared by. JSON blobs are decoded and their keys sorted, so the same + * settings written in another key order are the same settings. + * + * @param WidgetPlacement $placement The widget. + * + * @return array<string, mixed> Field name to comparable value. + */ + private function snapshot(WidgetPlacement $placement): array { + $snapshot = []; + foreach (array_keys(array: self::FIELD_WORDS) as $field) { + if ($field === 'styleConfig' || $field === 'content') { + continue; + } + + $snapshot[$field] = $placement->{'get' . ucfirst(string: $field)}(); + } + + $snapshot['styleConfig'] = self::sorted(value: $placement->getStyleConfigArray()); + $snapshot['content'] = self::sorted(value: $placement->getContentArray()); + + return $snapshot; + }//end snapshot() + + /** + * Sort an array's string keys, at every depth. Lists keep their order. + * + * @param array<int|string, mixed> $value The decoded JSON value. + * + * @return array<int|string, mixed> The same value with sorted keys. + */ + private static function sorted(array $value): array { + foreach ($value as $key => $item) { + if (is_array($item) === true) { + $value[$key] = self::sorted(value: $item); + } + } + + if (array_is_list(array: $value) === false) { + ksort($value); + } + + return $value; + }//end sorted() + + /** + * Turn a plan into the lists the administrator reads. + * + * @param array<string, mixed> $plan From {@see self::pair()}. + * + * @return array{added:array<int,string>, removed:array<int,string>, + * changed:array<int,array{widget:string, fields:array<int,string>}>, unchanged:int} + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + public function describe(array $plan): array { + $changed = []; + foreach ($plan['changed'] as $pair) { + $before = $this->snapshot(placement: $pair['installed']); + $after = $this->snapshot(placement: $pair['wanted']); + $words = []; + foreach ($after as $field => $value) { + if ($before[$field] !== $value) { + $words[self::FIELD_WORDS[$field]] = true; + } + } + + $changed[] = ['widget' => $this->label(placement: $pair['wanted']), 'fields' => array_keys(array: $words)]; + } + + return [ + 'added' => array_map(callback: $this->label(...), array: $plan['added']), + 'removed' => array_map(callback: $this->label(...), array: $plan['removed']), + 'changed' => $changed, + 'unchanged' => count($plan['unchanged']), + ]; + }//end describe() + + /** + * How the report names a widget: its title when it has one, and its type. + * + * @param WidgetPlacement $placement The widget. + * + * @return string For example `Mijn zaken (object-list)`. + */ + private function label(WidgetPlacement $placement): string { + $type = (string)$placement->getWidgetId(); + $title = (string)($placement->getCustomTitle() ?? ''); + if ($title === '') { + $title = (string)($placement->getContentArray()['title'] ?? ''); + } + + if ($title === '') { + return $type; + } + + return $title . ' (' . $type . ')'; + }//end label() + + /** + * Write the plan to the template, in one transaction. + * + * @param Dashboard $template The installed template. + * @param array<string, mixed> $plan From {@see self::pair()}. + * + * @return void + * + * @throws RuntimeException When a write fails. Nothing is kept then. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + public function apply(Dashboard $template, array $plan): void { + $now = (new DateTimeImmutable())->format(format: 'Y-m-d H:i:s'); + $this->stores->db->beginTransaction(); + + try { + foreach ($plan['changed'] as $pair) { + $this->copyFields(from: $pair['wanted'], onto: $pair['installed'], now: $now); + $this->stores->placementMapper->update(entity: $pair['installed']); + } + + foreach ($plan['added'] as $placement) { + $this->stores->placementMapper->insert(entity: $placement); + } + + foreach ($plan['removed'] as $placement) { + $this->stores->placementMapper->delete(entity: $placement); + } + + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $template->setUpdatedAt($now); + $this->stores->dashboardMapper->update(entity: $template); + $this->stores->db->commit(); + } catch (Throwable $e) { + $this->stores->db->rollBack(); + throw new RuntimeException(message: 'Template not updated: ' . $e->getMessage(), previous: $e); + }//end try + }//end apply() + + /** + * Give an installed widget the new version's fields. Its row id stays, + * which is what a member's copy points at. + * + * @param WidgetPlacement $from The new version's widget. + * @param WidgetPlacement $onto The installed widget (changed in place). + * @param string $now The timestamp to stamp. + * + * @return void + */ + private function copyFields(WidgetPlacement $from, WidgetPlacement $onto, string $now): void { + // Entity setters resolve through __call, which reads $args[0]; named + // arguments would break that forwarding. + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + foreach (array_keys(array: self::FIELD_WORDS) as $field) { + $onto->{'set' . ucfirst(string: $field)}($from->{'get' . ucfirst(string: $field)}()); + } + + $onto->setUpdatedAt($now); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + }//end copyFields() +}//end class diff --git a/lib/Service/PlacementPayloadHydrator.php b/lib/Service/PlacementPayloadHydrator.php index f1321f222..e0416a60b 100644 --- a/lib/Service/PlacementPayloadHydrator.php +++ b/lib/Service/PlacementPayloadHydrator.php @@ -21,7 +21,8 @@ * WHAT IS DELIBERATELY NOT CARRIED. Fields that point at THIS instance or at a * workflow on it rather than describing the widget: `id`, `dashboardId`, * `templatePlacementId` (the id of another placement row), `isCompulsory` - * (an admin push, not part of a dashboard's layout), the mandatory-read + * (an admin push, not part of a dashboard's layout; the one exception is an + * admin TEMPLATE, where the flag is the definition itself), the mandatory-read * `acknowledgement*` fields and `announcementKey`. A fresh placement gets * fresh timestamps. * @@ -73,12 +74,23 @@ class PlacementPayloadHydrator { * @param int $dashboardId The dashboard the placement joins. * @param array<string, mixed> $payload One entry of an exported dashboard's * `widgets` array. + * @param bool $asTemplate True when the dashboard is an admin + * template. Only then is `isCompulsory` + * carried: on a template the flag is part + * of the definition every copy is made + * from, anywhere else it is one admin's + * push on one instance (REQ-EXIM-012). * * @return WidgetPlacement The placement, not yet persisted. * + * @SuppressWarnings(PHPMD.BooleanArgumentFlag) + * One fact about the dashboard decides one field; a second builder + * for templates is the drift this class exists to end. + * * @spec openspec/specs/dashboard-export-import/spec.md + * @spec openspec/specs/dashboard-export-import/spec.md#req-exim-012 */ - public function hydrate(int $dashboardId, array $payload): WidgetPlacement { + public function hydrate(int $dashboardId, array $payload, bool $asTemplate = false): WidgetPlacement { $placement = new WidgetPlacement(); $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); @@ -86,17 +98,14 @@ public function hydrate(int $dashboardId, array $payload): WidgetPlacement { // arguments would break that forwarding. // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters $placement->setDashboardId($dashboardId); - $placement->setWidgetId((string)($payload['widgetId'] ?? '')); - $placement->setGridX((int)($payload['gridX'] ?? 0)); - $placement->setGridY((int)($payload['gridY'] ?? 0)); - $placement->setGridWidth((int)($payload['gridWidth'] ?? 4)); - $placement->setGridHeight((int)($payload['gridHeight'] ?? 4)); - $placement->setIsVisible((int)($payload['isVisible'] ?? 1)); - $placement->setShowTitle((int)($payload['showTitle'] ?? 1)); - $placement->setSortOrder((int)($payload['sortOrder'] ?? 0)); + $this->applyLayout(placement: $placement, payload: $payload); $placement->setCreatedAt($now); $placement->setUpdatedAt($now); + if ($asTemplate === true) { + $placement->setIsCompulsory((int)($payload['isCompulsory'] ?? 0)); + } + if (isset($payload['customTitle']) === true) { $placement->setCustomTitle((string)$payload['customTitle']); } @@ -113,6 +122,36 @@ public function hydrate(int $dashboardId, array $payload): WidgetPlacement { return $placement; }//end hydrate() + /** + * Copy the widget id, grid position and size, visibility, title flag and + * sort order from a payload, with the defaults of a new placement. + * + * @param WidgetPlacement $placement The placement being hydrated. + * @param array<string, mixed> $payload The placement payload. + * + * @return void + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + */ + private function applyLayout(WidgetPlacement $placement, array $payload): void { + // phpcs:disable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $placement->setWidgetId((string)($payload['widgetId'] ?? '')); + $placement->setGridX((int)($payload['gridX'] ?? 0)); + $placement->setGridY((int)($payload['gridY'] ?? 0)); + $placement->setGridWidth((int)($payload['gridWidth'] ?? 4)); + $placement->setGridHeight((int)($payload['gridHeight'] ?? 4)); + $placement->setIsVisible((int)($payload['isVisible'] ?? 1)); + $placement->setShowTitle((int)($payload['showTitle'] ?? 1)); + $placement->setSortOrder((int)($payload['sortOrder'] ?? 0)); + // How the visibility rules combine (REQ-VIS-014); anything but `all` is `any`. + $ruleMatch = WidgetPlacement::RULE_MATCH_ANY; + if (($payload['ruleMatch'] ?? null) === WidgetPlacement::RULE_MATCH_ALL) { + $ruleMatch = WidgetPlacement::RULE_MATCH_ALL; + } + + $placement->setRuleMatch($ruleMatch); + // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters + }//end applyLayout() + /** * Copy a tile's type and fields, when the payload is a tile. * diff --git a/lib/Service/PlacementService.php b/lib/Service/PlacementService.php index b4f90dadb..2a442513c 100644 --- a/lib/Service/PlacementService.php +++ b/lib/Service/PlacementService.php @@ -19,39 +19,55 @@ namespace OCA\LaunchPad\Service; use DateTime; +use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacement; use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Exception\StalePlacementException; +use OCP\IDBConnection; +use Throwable; /** * Service for managing widget placement CRUD operations. * * @spec openspec/specs/widgets/spec.md + * @SuppressWarnings(PHPMD.StaticAccess) VideoContent is a pure helper of static functions. */ class PlacementService { + /** + * Grid position, size and content of a new widget placement when the + * caller leaves them out. + */ + private const DEFAULT_LAYOUT = [ + 'gridX' => 0, + 'gridY' => 0, + 'gridWidth' => 4, + 'gridHeight' => 4, + 'content' => null, + 'isCompulsory' => 0, + ]; + /** * Constructor * - * @param WidgetPlacementMapper $placementMapper Widget placement mapper. - * @param TileUpdater $tileUpdater Tile updater service. - * @param PlacementUpdater $placementUpdater Placement updater service. - * @param PublicShareContext|null $publicShareContext Public-share bearer - * guard (nullable for - * legacy test doubles). - * @param QuotaService|null $quotaService Widget-quota enforcer - * (dashboard-quota-limits - * REQ-QUOTA-003). - * Nullable to keep - * existing test doubles - * working — when - * absent no quota is - * enforced. + * @param WidgetPlacementMapper $placementMapper Widget placement mapper. + * @param PlacementUpdaters $updaters The tile and placement updaters. + * @param PublicShareContext|null $publicShareContext Public-share bearer guard (nullable for legacy test doubles). + * @param QuotaService|null $quotaService Widget-quota enforcer (dashboard-quota-limits + * REQ-QUOTA-003). Nullable to keep existing test doubles + * working — when absent no quota is enforced. + * @param DashboardMapper|null $dashboardMapper Reads the dashboard's grid width for a new widget's free spot. + * @param FreeSpotFinder $freeSpots The free-spot search for a new widget. + * @param IDBConnection|null $db Wraps a bookmark import in one transaction + * (launcher-bookmark-import REQ-BMI-003). */ public function __construct( private readonly WidgetPlacementMapper $placementMapper, - private readonly TileUpdater $tileUpdater, - private readonly PlacementUpdater $placementUpdater, + private readonly PlacementUpdaters $updaters, private readonly ?PublicShareContext $publicShareContext = null, private readonly ?QuotaService $quotaService = null, + private readonly ?DashboardMapper $dashboardMapper = null, + private readonly FreeSpotFinder $freeSpots = new FreeSpotFinder(), + private readonly ?IDBConnection $db = null, ) { }//end __construct() @@ -60,14 +76,12 @@ public function __construct( * * @param int $dashboardId Dashboard ID. * @param string $widgetId Widget ID. - * @param int $gridX Grid X position. - * @param int $gridY Grid Y position. - * @param int $gridWidth Grid width. - * @param int $gridHeight Grid height. - * @param array|null $content Optional per-type content payload for - * custom widgets (registry-driven types - * like `label`, `text`, etc. — shape - * matches the type's `defaultContent`). + * @param array $layout Grid position and size (`gridX`, `gridY`, + * `gridWidth`, `gridHeight`; default 0, 0, 4 x 4) + * and the optional per-type `content` payload for + * custom widgets (registry-driven types like + * `label`, `text`, etc. — shape matches the type's + * `defaultContent`). * * @return WidgetPlacement The created widget placement. * @@ -77,15 +91,8 @@ public function __construct( * * @spec openspec/changes/dashboard-quota-limits/specs/dashboard-quota-limits/spec.md#req-quota-003-widget-count-enforcement */ - public function addWidget( - int $dashboardId, - string $widgetId, - int $gridX = 0, - int $gridY = 0, - int $gridWidth = 4, - int $gridHeight = 4, - ?array $content = null, - ): WidgetPlacement { + public function addWidget(int $dashboardId, string $widgetId, array $layout=[]): WidgetPlacement { + $layout += self::DEFAULT_LAYOUT; // Task-7 of dashboard-public-share — bearer cannot mutate placements. $this->publicShareContext?->requireMutable(); // Dashboard-quota-limits REQ-QUOTA-003: enforce the per-dashboard @@ -98,16 +105,17 @@ public function addWidget( $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); $placement->setDashboardId($dashboardId); $placement->setWidgetId($widgetId); - $placement->setGridX($gridX); - $placement->setGridY($gridY); - $placement->setGridWidth($gridWidth); - $placement->setGridHeight($gridHeight); - $placement->setIsCompulsory(0); + $spot = $this->freeSpot(dashboardId: $dashboardId, wanted: $layout); + $placement->setGridX($spot['gridX']); + $placement->setGridY($spot['gridY']); + $placement->setGridWidth($spot['gridWidth']); + $placement->setGridHeight($spot['gridHeight']); + $placement->setIsCompulsory((int)$layout['isCompulsory']); $placement->setIsVisible(1); $placement->setShowTitle(1); - if ($content !== null) { - $placement->setContentArray($content); + if ($layout['content'] !== null) { + $placement->setContentArray(VideoContent::forWidget(widgetId: $widgetId, content: $layout['content'])); } $placement->setCreatedAt($now); @@ -143,17 +151,24 @@ public function addTileFromArray( $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); $placement->setDashboardId($dashboardId); $placement->setWidgetId('tile-' . uniqid()); - $placement->setGridX($tileData['gridX'] ?? 0); - $placement->setGridY($tileData['gridY'] ?? 0); - $placement->setGridWidth($tileData['gridWidth'] ?? 2); - $placement->setGridHeight( - $tileData['gridHeight'] ?? 2 + $spot = $this->freeSpot( + dashboardId: $dashboardId, + wanted: [ + 'gridX' => (int)($tileData['gridX'] ?? 0), + 'gridY' => (int)($tileData['gridY'] ?? 0), + 'gridWidth' => (int)($tileData['gridWidth'] ?? 2), + 'gridHeight' => (int)($tileData['gridHeight'] ?? 2), + ] ); + $placement->setGridX($spot['gridX']); + $placement->setGridY($spot['gridY']); + $placement->setGridWidth($spot['gridWidth']); + $placement->setGridHeight($spot['gridHeight']); $placement->setIsCompulsory(0); $placement->setIsVisible(1); $placement->setShowTitle(1); - $this->tileUpdater->applyTileConfig( + $this->updaters->tileUpdater->applyTileConfig( placement: $placement, tileData: $tileData ); @@ -173,6 +188,7 @@ public function addTileFromArray( * @return WidgetPlacement The updated widget placement. * * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-35 + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 */ public function updatePlacement( int $placementId, @@ -181,20 +197,25 @@ public function updatePlacement( // Task-7 of dashboard-public-share — bearer cannot mutate placements. $this->publicShareContext?->requireMutable(); $placement = $this->placementMapper->find(id: $placementId); + $placement->setVersion($this->nextVersion(placement: $placement, data: $data)); - $this->placementUpdater->applyGridUpdates( + $this->updaters->placementUpdater->applyGridUpdates( + placement: $placement, + data: $data + ); + $this->updaters->placementUpdater->applyDisplayUpdates( placement: $placement, data: $data ); - $this->placementUpdater->applyDisplayUpdates( + $this->updaters->tileUpdater->applyTileUpdates( placement: $placement, data: $data ); - $this->tileUpdater->applyTileUpdates( + $this->updaters->placementUpdater->applyAcknowledgementUpdates( placement: $placement, data: $data ); - $this->placementUpdater->applyAcknowledgementUpdates( + $this->updaters->placementUpdater->applyRuleMatch( placement: $placement, data: $data ); @@ -206,6 +227,92 @@ public function updatePlacement( return $this->placementMapper->update(entity: $placement); }//end updatePlacement() + /** + * The version a save writes: one above the version it was made on. + * + * A save that names the version it was made on claims that version in + * one statement; when a colleague saved first the claim fails and the + * save is refused with the widget as it is now. A save that names no + * version (an older client) just raises the version. + * + * @param WidgetPlacement $placement The widget as loaded. + * @param array<string, mixed> $data The update payload. + * + * @return int + * + * @throws StalePlacementException When the change was made on an older version. + * + * @spec openspec/specs/dashboard-co-editing/spec.md + */ + private function nextVersion(WidgetPlacement $placement, array $data): int { + if (array_key_exists('version', $data) === false || is_numeric($data['version']) === false) { + return ($placement->getVersion() + 1); + } + + $expected = (int)$data['version']; + if ($this->placementMapper->claimVersion(id: (int)$placement->getId(), expected: $expected) === false) { + throw new StalePlacementException(current: $this->placementMapper->find(id: (int)$placement->getId())); + } + + return ($expected + 1); + }//end nextVersion() + + /** + * The spot a new widget takes: the one asked for when free in the saved + * layout, else the first free one, never over another widget. + * + * @param int $dashboardId The dashboard. + * @param array{gridX:int,gridY:int,gridWidth:int,gridHeight:int} $wanted The spot asked for and the size. + * + * @return array{gridX:int,gridY:int,gridWidth:int,gridHeight:int} + * + * @spec openspec/specs/dashboard-co-editing/spec.md + */ + private function freeSpot(int $dashboardId, array $wanted): array { + $occupied = array_map( + static fn (WidgetPlacement $saved): array => [ + 'gridX' => (int)$saved->getGridX(), + 'gridY' => (int)$saved->getGridY(), + 'gridWidth' => (int)$saved->getGridWidth(), + 'gridHeight' => (int)$saved->getGridHeight(), + ], + array_filter( + (array)$this->placementMapper->findByDashboardId(dashboardId: $dashboardId), + static fn ($saved): bool => $saved instanceof WidgetPlacement + ) + ); + + return $this->freeSpots->place( + occupied: array_values($occupied), + columns: $this->columnsOf(dashboardId: $dashboardId), + wanted: [ + 'gridX' => (int)$wanted['gridX'], + 'gridY' => (int)$wanted['gridY'], + 'gridWidth' => (int)$wanted['gridWidth'], + 'gridHeight' => (int)$wanted['gridHeight'], + ] + ); + }//end freeSpot() + + /** + * The dashboard's grid column count; 12 when it cannot be read. + * + * @param int $dashboardId The dashboard. + * + * @return int + */ + private function columnsOf(int $dashboardId): int { + if ($this->dashboardMapper === null) { + return 12; + } + + try { + return max(1, (int)$this->dashboardMapper->find(id: $dashboardId)->getGridColumns()); + } catch (\Throwable) { + return 12; + } + }//end columnsOf() + /** * Remove a widget placement. * @@ -247,4 +354,89 @@ public function getDashboardPlacements(int $dashboardId): array { dashboardId: $dashboardId ); }//end getDashboardPlacements() + + /** + * Create the placements of a bookmark import: the dashboard quota is + * checked once for the whole import before anything is written, and every + * placement is created in one transaction, so a failure leaves nothing + * behind (launcher-bookmark-import REQ-BMI-001, REQ-BMI-003). Everything + * goes below the dashboard's lowest edge (bottom-append). + * + * @param int $dashboardId The dashboard. + * @param BookmarkImportPlan $plan What to create. + * + * @return list<WidgetPlacement> The created placements, containers first. + * + * @throws \OCA\LaunchPad\Exception\QuotaExceededException When the import does not fit the quota. + * @throws Throwable When a write fails; the transaction is rolled back first. + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-the-import-respects-the-widget-quota-as-one-operation-req-bmi-003 + */ + public function importBookmarks(int $dashboardId, BookmarkImportPlan $plan): array { + $this->publicShareContext?->requireMutable(); + $this->quotaService?->assertCanAddPlacements(dashboardId: $dashboardId, count: $plan->placementCount()); + + $bottom = 0; + foreach ($this->getDashboardPlacements(dashboardId: $dashboardId) as $existing) { + $bottom = max($bottom, ((int)$existing->getGridY() + (int)$existing->getGridHeight())); + } + + $this->db?->beginTransaction(); + try { + $created = []; + foreach ($plan->layout(bottom: $bottom) as $spec) { + $created[] = $this->placementMapper->insert(entity: $this->importedPlacement(dashboardId: $dashboardId, spec: $spec)); + } + + $this->db?->commit(); + } catch (Throwable $e) { + $this->db?->rollBack(); + throw $e; + } + + return $created; + }//end importBookmarks() + + /** + * One placement of an import: a container with its link children, or a + * tile opening the bookmark in a new tab. + * + * @param int $dashboardId The dashboard. + * @param array<string, mixed> $spec One entry of {@see BookmarkImportPlan::layout()}. + * + * @return WidgetPlacement + */ + private function importedPlacement(int $dashboardId, array $spec): WidgetPlacement { + $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); + $placement = new WidgetPlacement(); + $placement->setDashboardId($dashboardId); + $placement->setGridX($spec['gridX']); + $placement->setGridY($spec['gridY']); + $placement->setGridWidth($spec['gridWidth']); + $placement->setGridHeight($spec['gridHeight']); + $placement->setIsCompulsory(0); + $placement->setIsVisible(1); + $placement->setShowTitle(1); + $placement->setCreatedAt($now); + $placement->setUpdatedAt($now); + + if (isset($spec['tile']) === true) { + $placement->setWidgetId('tile-' . uniqid()); + $this->updaters->tileUpdater->applyTileConfig( + placement: $placement, + tileData: [ + 'title' => $spec['tile']['title'], + 'linkType' => 'url', + 'linkVal' => $spec['tile']['url'], + 'icon' => 'icon-link', + 'iconType' => 'class', + ] + ); + return $placement; + } + + $placement->setWidgetId((string)$spec['widgetId']); + $placement->setContentArray($spec['content']); + return $placement; + }//end importedPlacement() }//end class diff --git a/lib/Service/PlacementUpdater.php b/lib/Service/PlacementUpdater.php index 36e15ac79..ed90b97d5 100644 --- a/lib/Service/PlacementUpdater.php +++ b/lib/Service/PlacementUpdater.php @@ -24,6 +24,7 @@ * Service for applying grid and display updates to widget placements. * * @spec openspec/specs/widgets/spec.md + * @SuppressWarnings(PHPMD.StaticAccess) VideoContent is a pure helper of static functions. */ class PlacementUpdater { /** @@ -101,9 +102,14 @@ public function applyDisplayUpdates( if (isset($data['content']) === true && is_array($data['content']) === true) { $placement->setContentArray( - $data['content'] + VideoContent::forWidget(widgetId: (string)$placement->getWidgetId(), content: $data['content']) ); } + + // The calculated fields replace the stored list as a whole (widget-calculated-fields, task 21). + if (isset($data['calculatedFields']) === true && is_array($data['calculatedFields']) === true) { + $placement->setCalculatedFieldsArray(fields: $data['calculatedFields']); + } }//end applyDisplayUpdates() /** @@ -224,6 +230,24 @@ private function applyAcknowledgementCadence( } }//end applyAcknowledgementCadence() + /** + * Apply the rule match mode when present: `all` or `any`. The + * controller refuses any other value before it gets here; anything + * else that slips through is stored as `any`. + * + * @param WidgetPlacement $placement The placement entity. + * @param array $data The update data. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + */ + public function applyRuleMatch(WidgetPlacement $placement, array $data): void { + if (isset($data['ruleMatch']) === true) { + $placement->setRuleMatch(WidgetPlacement::normalRuleMatch(value: $data['ruleMatch'])); + } + }//end applyRuleMatch() + /** * Mint the stable announcement identity the first time the requirement * is enabled (REQ-ACK-001 / design D2). @@ -240,23 +264,7 @@ private function mintAnnouncementKey(WidgetPlacement $placement): void { && ($placement->getAnnouncementKey() === null || $placement->getAnnouncementKey() === '') ) { - $placement->setAnnouncementKey($this->generateUuid()); + $placement->setAnnouncementKey(UuidV4::generate()); } }//end mintAnnouncementKey() - - /** - * Generate a v4 UUID using random_bytes (no external dependency). - * Mirrors `TemplateService::generateUuid()`. - * - * @return string A v4 UUID. - */ - private function generateUuid(): string { - $data = random_bytes(length: 16); - $data[6] = chr((ord($data[6]) & 0x0F) | 0x40); - $data[8] = chr((ord($data[8]) & 0x3F) | 0x80); - return vsprintf( - format: '%s%s-%s-%s-%s-%s%s%s', - values: str_split(string: bin2hex(string: $data), length: 4) - ); - }//end generateUuid() }//end class diff --git a/lib/Service/PlacementUpdaters.php b/lib/Service/PlacementUpdaters.php new file mode 100644 index 000000000..56e386cf7 --- /dev/null +++ b/lib/Service/PlacementUpdaters.php @@ -0,0 +1,43 @@ +<?php + +/** + * PlacementUpdaters + * + * The tile and placement updaters of the placement service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/widgets/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The tile and placement updaters of the placement service. + * + * @spec openspec/specs/widgets/spec.md + */ +class PlacementUpdaters { + /** + * Constructor. + * + * @param TileUpdater $tileUpdater Tile updater service. + * @param PlacementUpdater $placementUpdater Placement updater service. + */ + public function __construct( + public readonly TileUpdater $tileUpdater, + public readonly PlacementUpdater $placementUpdater, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ProfileFieldListing.php b/lib/Service/ProfileFieldListing.php new file mode 100644 index 000000000..9ae4008c7 --- /dev/null +++ b/lib/Service/ProfileFieldListing.php @@ -0,0 +1,93 @@ +<?php + +/** + * ProfileFieldListing + * + * The widget's profile-field definitions and the viewer's visibility + * check, applied to the grouped values of the listed people. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/people-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use Closure; + +/** + * Lists the profile fields one viewer may see, per person. + * + * Built by {@see ProfileFieldService::visibleFieldsFor()} for one listing; + * never shared. + * + * @spec openspec/specs/people-widget/spec.md + */ +final class ProfileFieldListing { + /** + * Constructor. + * + * @param array<int, array<string, mixed>> $definitions The widget's field definitions. + * @param Closure $canSee `(string $ownerId, array $definition): bool`. + */ + public function __construct( + private readonly array $definitions, + private readonly Closure $canSee, + ) { + }//end __construct() + + /** + * The visible fields of every person that has at least one. + * + * @param array<string, array<string, string[]>> $grouped Values by person, then field key. + * + * @return array<string, list<array{key: string, label: string, type: string, values: string[]}>> + * + * @spec openspec/specs/people-widget/spec.md + */ + public function fieldsByPerson(array $grouped): array { + $result = []; + foreach ($grouped as $userId => $byKey) { + $fields = $this->fieldsOf(ownerId: (string)$userId, byKey: $byKey); + if ($fields !== []) { + $result[$userId] = $fields; + } + } + + return $result; + }//end fieldsByPerson() + + /** + * One person's fields that have values and that the viewer may see, + * in definition order. + * + * @param string $ownerId The person. + * @param array<string, string[]> $byKey Their values by field key. + * + * @return list<array{key: string, label: string, type: string, values: string[]}> + */ + private function fieldsOf(string $ownerId, array $byKey): array { + $fields = []; + foreach ($this->definitions as $definition) { + $values = $byKey[$definition['key']] ?? []; + if ($values === [] || ($this->canSee)($ownerId, $definition) === false) { + continue; + } + + $fields[] = ['key' => $definition['key'], 'label' => $definition['label'], 'type' => $definition['type'], 'values' => $values]; + } + + return $fields; + }//end fieldsOf() +}//end class diff --git a/lib/Service/ProfileFieldService.php b/lib/Service/ProfileFieldService.php new file mode 100644 index 000000000..2f6736053 --- /dev/null +++ b/lib/Service/ProfileFieldService.php @@ -0,0 +1,910 @@ +<?php + +/** + * ProfileFieldService + * + * Custom profile fields for the people widget (widgets-people-expertise-and-fields, + * REQ-PEX-001..004): the administrator's field definitions, the values people + * fill in themselves or that come from LDAP, a mirror of the searchable + * standard fields with their visibility scope, and the visibility rule that + * decides what a viewer may see and match. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use Exception; +use InvalidArgumentException; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCA\LaunchPad\Db\ProfileValue; +use OCA\LaunchPad\Db\ProfileFieldValues; +use OCA\LaunchPad\Db\ProfileValueMapper; +use OCA\LaunchPad\Kernel\Contracts\ProfileFieldServiceInterface; +use OCP\Accounts\IAccountManager; +use OCP\IUser; + +/** + * Definitions, values and visibility of custom profile fields. + * + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) Definition validation, + * self edits, the LDAP sync, the standard-field mirror and the visibility + * rule share one data model; splitting them would scatter that rule. + * @SuppressWarnings(PHPMD.TooManyPublicMethods) Same reason: the listener, + * the job, both controllers, the people service and the demo installer each + * call their own entry point on this one model. + * + * @spec openspec/specs/people-widget/spec.md + */ +class ProfileFieldService implements ProfileFieldServiceInterface { + /** + * Admin setting key holding the field definitions. + * + * @var string + */ + public const SETTING_KEY = 'profile_fields'; + + /** + * Most custom fields an administrator may define. + * + * @var int + */ + public const MAX_FIELDS = 10; + + /** + * Most tags one person may list in one field. + * + * @var int + */ + public const MAX_TAGS = 25; + + /** + * Longest value, in characters. + * + * @var int + */ + public const MAX_VALUE_LENGTH = 255; + + /** + * Standard fields mirrored for the search, keyed by their row key. + * + * @var array<string, string> + */ + public const MIRRORED_STANDARD_FIELDS = [ + 'nc:role' => IAccountManager::PROPERTY_ROLE, + 'nc:headline' => IAccountManager::PROPERTY_HEADLINE, + 'nc:biography' => IAccountManager::PROPERTY_BIOGRAPHY, + ]; + + private const TYPES = ['text', 'tags', 'date']; + private const SOURCES = ['self', 'ldap']; + private const VISIBILITIES = ['everyone', 'groups']; + + /** + * Group ids per user, memoised for one request. + * + * @var array<string, string[]> + */ + private array $groupCache = []; + + /** + * Constructor. + * + * @param AdminSettingMapper $settingMapper Admin settings store. + * @param ProfileValueMapper $valueMapper Profile values store. + * @param ProfileSources $sources The account manager and LDAP provider factory. + * @param ProfileFieldTools $tools The admin template service and logger. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function __construct( + private readonly AdminSettingMapper $settingMapper, + private readonly ProfileValueMapper $valueMapper, + private readonly ProfileSources $sources, + private readonly ProfileFieldTools $tools, + ) { + }//end __construct() + + /** + * The stored field definitions, cleaned. + * + * @return array<int, array<string, mixed>> + * + * @spec openspec/specs/people-widget/spec.md + */ + public function getDefinitions(): array { + $raw = $this->settingMapper->getValue(key: self::SETTING_KEY, default: []); + if (is_array(value: $raw) === false) { + return []; + } + + try { + return $this->validateDefinitions(raw: $raw); + } catch (InvalidArgumentException) { + return []; + } + }//end getDefinitions() + + /** + * Validate and store the field definitions (REQ-PEX-001). + * + * @param array $raw Definitions as sent by the admin screen. + * + * @return array<int, array<string, mixed>> The stored definitions. + * + * @throws InvalidArgumentException When a definition is invalid. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function saveDefinitions(array $raw): array { + $definitions = $this->validateDefinitions(raw: $raw); + $this->settingMapper->setSetting(key: self::SETTING_KEY, value: $definitions); + + return $definitions; + }//end saveDefinitions() + + /** + * Check and normalise a list of definitions. + * + * @param array $raw Raw definitions. + * + * @return array<int, array<string, mixed>> + * + * @throws InvalidArgumentException When a definition is invalid. + * + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-a-profile-field-can-hold-a-start-date-req-pex-005 + */ + private function validateDefinitions(array $raw): array { + if (count(value: $raw) > self::MAX_FIELDS) { + throw new InvalidArgumentException(message: 'At most ' . self::MAX_FIELDS . ' profile fields'); + } + + $result = []; + $seen = []; + foreach (array_values(array: $raw) as $entry) { + $definition = $this->validateDefinition(entry: $entry); + if (isset($seen[$definition['key']]) === true) { + throw new InvalidArgumentException(message: 'Duplicate field key: ' . $definition['key']); + } + + $seen[$definition['key']] = true; + if ($definition['startDate'] === true) { + // REQ-PEX-005: marking another field as the start date unmarks the previous one. + $result = array_map(callback: static fn (array $earlier): array => array_merge($earlier, ['startDate' => false]), array: $result); + } + + $result[] = $definition; + } + + self::requireOneDepartmentAtMost(definitions: $result); + + return $result; + }//end validateDefinitions() + + /** + * At most one field is the department of read confirmations (REQ-ACK-010). + * + * @param array<int, array<string, mixed>> $definitions The checked definitions. + * + * @return void + * + * @throws InvalidArgumentException When two fields are marked as the department. + * + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + private static function requireOneDepartmentAtMost(array $definitions): void { + $departments = array_filter(array: $definitions, callback: static fn (array $definition): bool => $definition['department'] === true); + if (count(value: $departments) > 1) { + throw new InvalidArgumentException(message: 'Only one profile field can be the department'); + } + }//end requireOneDepartmentAtMost() + + /** + * Check and normalise one definition. + * + * @param mixed $entry Raw definition. + * + * @return array<string, mixed> + * + * @throws InvalidArgumentException When the definition is invalid. + */ + private function validateDefinition(mixed $entry): array { + if (is_array(value: $entry) === false) { + throw new InvalidArgumentException(message: 'A profile field must be an object'); + } + + $definition = $this->definitionFrom(entry: $entry, key: self::validKey(entry: $entry)); + + return self::withCheckedLdapAttribute(definition: $definition); + }//end validateDefinition() + + /** + * The definition's key, checked: lower case letters, digits or `_`, + * starting with a letter, at most 32 characters. + * + * @param array<string, mixed> $entry Raw definition. + * + * @return string The key. + * + * @throws InvalidArgumentException When the key is malformed. + */ + private static function validKey(array $entry): string { + $key = (string)($entry['key'] ?? ''); + if (preg_match(pattern: '/^[a-z][a-z0-9_]{0,31}$/', subject: $key) !== 1) { + throw new InvalidArgumentException(message: 'Field key must be lower case letters, digits or _: ' . $key); + } + + return $key; + }//end validKey() + + /** + * The definition's trimmed label, checked: 1 to 64 characters. + * + * @param array<string, mixed> $entry Raw definition. + * @param string $key The checked key (for the message). + * + * @return string The label. + * + * @throws InvalidArgumentException When the label is empty or too long. + */ + private static function validLabel(array $entry, string $key): string { + $label = trim(string: (string)($entry['label'] ?? '')); + if ($label === '' || mb_strlen(string: $label) > 64) { + throw new InvalidArgumentException(message: 'Field label must be 1 to 64 characters: ' . $key); + } + + return $label; + }//end validLabel() + + /** + * The normalised definition: label, then type, source and visibility + * checked in that order; flags default to not searchable and shown. + * + * @param array<string, mixed> $entry Raw definition. + * @param string $key The checked key. + * + * @return array<string, mixed> The definition, LDAP attribute unchecked. + * + * @throws InvalidArgumentException When a field is invalid. + * + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-a-profile-field-can-hold-a-start-date-req-pex-005 + */ + private function definitionFrom(array $entry, string $key): array { + return [ + 'key' => $key, + 'label' => self::validLabel(entry: $entry, key: $key), + 'type' => $this->oneOf(value: $entry['type'] ?? 'text', allowed: self::TYPES, name: 'type'), + 'source' => $this->oneOf(value: $entry['source'] ?? 'self', allowed: self::SOURCES, name: 'source'), + 'ldapAttribute' => trim(string: (string)($entry['ldapAttribute'] ?? '')), + 'searchable' => ($entry['searchable'] ?? false) === true, + 'shownInWidget' => ($entry['shownInWidget'] ?? true) === true, + 'visibility' => $this->oneOf(value: $entry['visibility'] ?? 'everyone', allowed: self::VISIBILITIES, name: 'visibility'), + // REQ-ACK-010: the field read confirmations show as Department. + 'department' => ($entry['department'] ?? false) === true, + // REQ-PEX-005: the date field that holds the start date ("in dienst sinds"). + 'startDate' => ($entry['startDate'] ?? false) === true && ($entry['type'] ?? 'text') === 'date', + ]; + }//end definitionFrom() + + /** + * An LDAP field must name a valid LDAP attribute; any other field keeps + * none. + * + * @param array<string, mixed> $definition The normalised definition. + * + * @return array<string, mixed> The definition. + * + * @throws InvalidArgumentException When an LDAP field has no valid attribute. + */ + private static function withCheckedLdapAttribute(array $definition): array { + if ($definition['source'] === 'ldap' + && preg_match(pattern: '/^[A-Za-z][A-Za-z0-9-]{0,63}$/', subject: $definition['ldapAttribute']) !== 1 + ) { + throw new InvalidArgumentException(message: 'An LDAP field needs an LDAP attribute name: ' . $definition['key']); + } + + if ($definition['source'] !== 'ldap') { + $definition['ldapAttribute'] = ''; + } + + return $definition; + }//end withCheckedLdapAttribute() + + /** + * Check that a value is one of the allowed strings. + * + * @param mixed $value The value. + * @param string[] $allowed Allowed values. + * @param string $name Property name for the message. + * + * @return string The value. + * + * @throws InvalidArgumentException When it is not allowed. + */ + private function oneOf(mixed $value, array $allowed, string $name): string { + if (is_string(value: $value) === false || in_array(needle: $value, haystack: $allowed, strict: true) === false) { + throw new InvalidArgumentException(message: 'Field ' . $name . ' must be one of ' . implode(separator: ', ', array: $allowed)); + } + + return $value; + }//end oneOf() + + /** + * A person's own fields with their values, for the personal settings (REQ-PEX-002). + * + * @param string $userId The person. + * + * @return array<int, array<string, mixed>> Definitions with `values` and `readOnly`. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function getOwnFields(string $userId): array { + $byKey = $this->groupValues(rows: $this->valueMapper->findByUsers(userIds: [$userId]))[$userId] ?? []; + + $result = []; + foreach ($this->getDefinitions() as $definition) { + $result[] = array_merge( + $definition, + [ + 'values' => $byKey[$definition['key']] ?? [], + 'readOnly' => $definition['source'] !== 'self', + ] + ); + } + + return $result; + }//end getOwnFields() + + /** + * Save a person's own values (REQ-PEX-002). LDAP fields are read-only + * and ignored; unknown keys are rejected. + * + * @param string $userId The person. + * @param array $values Map of field key to a string (text) or a list of strings (tags). + * + * @return array<int, array<string, mixed>> The fields after saving. + * + * @throws InvalidArgumentException When a key or value is invalid. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function saveOwnValues(string $userId, array $values): array { + $clean = $this->cleanOwnValues(definitions: $this->definitionsByKey(), values: $values); + + foreach ($clean as $key => $list) { + $this->valueMapper->replaceValues(userId: $userId, field: new ProfileFieldValues(fieldKey: (string)$key, values: $list, source: 'self')); + } + + return $this->getOwnFields(userId: $userId); + }//end saveOwnValues() + + /** + * The definitions keyed by field key. + * + * @return array<string, array<string, mixed>> + */ + private function definitionsByKey(): array { + $definitions = []; + foreach ($this->getDefinitions() as $definition) { + $definitions[$definition['key']] = $definition; + } + + return $definitions; + }//end definitionsByKey() + + /** + * Check every submitted value before anything is written; values of + * fields the user does not own (LDAP, Nextcloud) are left out. + * + * @param array<string, array<string, mixed>> $definitions The definitions by key. + * @param array<string, mixed> $values Key → value (string or list). + * + * @return array<string, string[]> The cleaned values by key. + * + * @throws InvalidArgumentException On an unknown field or invalid value. + */ + private function cleanOwnValues(array $definitions, array $values): array { + $clean = []; + foreach ($values as $key => $value) { + $definition = $definitions[$key] ?? null; + if ($definition === null) { + throw new InvalidArgumentException(message: 'Unknown profile field: ' . $key); + } + + if ($definition['source'] === 'self') { + $clean[$key] = $this->cleanValues(definition: $definition, value: $value); + } + } + + return $clean; + }//end cleanOwnValues() + + /** + * Turn a submitted value into a clean list of strings. + * + * @param array $definition The field definition. + * @param mixed $value A string, or a list of strings for tags. + * + * @return string[] + * + * @throws InvalidArgumentException When the value does not fit the type. + */ + private function cleanValues(array $definition, mixed $value): array { + $result = []; + foreach (self::valueItems(definition: $definition, value: $value) as $item) { + $text = self::cleanItem(definition: $definition, item: $item); + if ($text !== null) { + // The first spelling of a tag wins. + $result[mb_strtolower(string: $text)] ??= $text; + } + } + + if (count(value: $result) > self::MAX_TAGS) { + throw new InvalidArgumentException(message: 'At most ' . self::MAX_TAGS . ' tags: ' . $definition['key']); + } + + return array_values(array: $result); + }//end cleanValues() + + /** + * The submitted items of a field: a tags field takes a list, any other + * field one value. + * + * @param array<string, mixed> $definition The field definition. + * @param mixed $value The submitted value. + * + * @return array<int|string, mixed> The items. + * + * @throws InvalidArgumentException When a tags field gets no list. + */ + private static function valueItems(array $definition, mixed $value): array { + if ($definition['type'] !== 'tags') { + return [$value]; + } + + if (is_array(value: $value) === false) { + throw new InvalidArgumentException(message: 'Tags must be a list: ' . $definition['key']); + } + + return $value; + }//end valueItems() + + /** + * One submitted item, trimmed; null for a null or blank item. + * + * @param array<string, mixed> $definition The field definition. + * @param mixed $item The submitted item. + * + * @return string|null The text, or null when the item is skipped. + * + * @throws InvalidArgumentException When the item is not text or too long. + */ + private static function cleanItem(array $definition, mixed $item): ?string { + if ($item === null) { + return null; + } + + $text = self::itemText(definition: $definition, item: $item); + if ($text === '') { + return null; + } + + if (mb_strlen(string: $text) > self::MAX_VALUE_LENGTH) { + throw new InvalidArgumentException(message: 'A value is longer than ' . self::MAX_VALUE_LENGTH . ' characters: ' . $definition['key']); + } + + return $text; + }//end cleanItem() + + /** + * A submitted item as trimmed text. + * + * @param array<string, mixed> $definition The field definition. + * @param mixed $item The submitted, non-null item. + * + * @return string The trimmed text. + * + * @throws InvalidArgumentException When the item is not text. + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-a-profile-field-can-hold-a-start-date-req-pex-005 + */ + private static function itemText(array $definition, mixed $item): string { + if (is_string(value: $item) === false) { + throw new InvalidArgumentException(message: 'A value must be text: ' . $definition['key']); + } + + $text = trim(string: $item); + // REQ-PEX-005: a date field holds one calendar date, `YYYY-MM-DD`. + $parts = []; + $isDate = preg_match(pattern: '/^(\d{4})-(\d{2})-(\d{2})$/', subject: $text, matches: $parts) === 1 + && checkdate(month: (int)$parts[2], day: (int)$parts[3], year: (int)$parts[1]); + if ($definition['type'] === 'date' && $text !== '' && $isDate === false) { + throw new InvalidArgumentException(message: 'A date must be written YYYY-MM-DD: ' . $definition['key']); + } + + return $text; + }//end itemText() + + /** + * Custom fields shown in the widget that the viewer may see (REQ-PEX-004). + * + * @param string|null $viewerId The viewer, or null for nobody. + * @param string[] $userIds The people on the page. + * + * @return array<string, array<int, array<string, mixed>>> Per user id: `{key, label, type, values}`. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function visibleFieldsFor(?string $viewerId, array $userIds): array { + $definitions = array_filter( + array: $this->getDefinitions(), + callback: static fn (array $definition): bool => $definition['shownInWidget'] === true + ); + if ($definitions === [] || $userIds === []) { + return []; + } + + $listing = new ProfileFieldListing( + definitions: $definitions, + canSee: fn (string $ownerId, array $definition): bool => $this->canSee(viewerId: $viewerId, ownerId: $ownerId, definition: $definition) + ); + + return $listing->fieldsByPerson(grouped: $this->groupValues(rows: $this->valueMapper->findByUsers(userIds: $userIds))); + }//end visibleFieldsFor() + + /** + * People whose searchable fields contain the query and the viewer may + * see that field (REQ-PEX-003, REQ-PEX-004). + * + * @param string|null $viewerId The viewer. + * @param string $query The search text. + * + * @return string[] Matching user ids. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function findMatchingUserIds(?string $viewerId, string $query): array { + $needle = mb_strtolower(string: trim(string: $query)); + if ($needle === '') { + return []; + } + + $definitions = $this->searchableDefinitions(); + + $matches = []; + foreach ($this->valueMapper->search(needle: $needle) as $row) { + $owner = $row->getUserId(); + if ($this->rowMatchesFor(viewerId: $viewerId, row: $row, definitions: $definitions) === true) { + $matches[$owner] = true; + } + } + + return array_keys(array: $matches); + }//end findMatchingUserIds() + + /** + * The searchable definitions keyed by field key. + * + * @return array<string, array<string, mixed>> + */ + private function searchableDefinitions(): array { + $definitions = []; + foreach ($this->getDefinitions() as $definition) { + if ($definition['searchable'] === true) { + $definitions[$definition['key']] = $definition; + } + } + + return $definitions; + }//end searchableDefinitions() + + /** + * Whether a matching row may count for this viewer. + * + * @param string|null $viewerId The viewer. + * @param ProfileValue $row The matching row. + * @param array<string, array<string, mixed>> $definitions Searchable definitions by key. + * + * @return bool + */ + private function rowMatchesFor(?string $viewerId, ProfileValue $row, array $definitions): bool { + $key = $row->getFieldKey(); + $owner = $row->getUserId(); + + if (isset(self::MIRRORED_STANDARD_FIELDS[$key]) === true) { + return $this->scopeAllows(scope: $row->getScope(), viewerId: $viewerId, ownerId: $owner); + } + + $definition = $definitions[$key] ?? null; + if ($definition === null) { + return false; + } + + return $this->canSee(viewerId: $viewerId, ownerId: $owner, definition: $definition); + }//end rowMatchesFor() + + /** + * Whether a standard field with this Nextcloud scope is visible to the viewer. + * A private field is visible to its owner only; the other scopes reach + * every signed-in user of this instance. + * + * @param string|null $scope The property scope. + * @param string|null $viewerId The viewer. + * @param string $ownerId The owner. + * + * @return bool + * + * @spec openspec/specs/people-widget/spec.md + */ + public function scopeAllows(?string $scope, ?string $viewerId, string $ownerId): bool { + if ($viewerId === null) { + return false; + } + + return $viewerId === $ownerId || $scope !== IAccountManager::SCOPE_PRIVATE; + }//end scopeAllows() + + /** + * Whether the viewer may see a custom field of the owner. + * + * @param string|null $viewerId The viewer. + * @param string $ownerId The owner. + * @param array $definition The field definition. + * + * @return bool + * + * @spec openspec/specs/people-widget/spec.md + */ + public function canSee(?string $viewerId, string $ownerId, array $definition): bool { + if ($viewerId === null) { + return false; + } + + if ($viewerId === $ownerId || $definition['visibility'] === 'everyone') { + return true; + } + + $shared = array_intersect( + $this->groupsOf(userId: $viewerId), + $this->groupsOf(userId: $ownerId) + ); + + return $shared !== []; + }//end canSee() + + /** + * Group ids of a user, memoised. + * + * @param string $userId The user. + * + * @return string[] + */ + private function groupsOf(string $userId): array { + if (isset($this->groupCache[$userId]) === false) { + $this->groupCache[$userId] = $this->tools->adminTemplateService->getUserGroupIdsFor(userId: $userId); + } + + return $this->groupCache[$userId]; + }//end groupsOf() + + /** + * Group rows by user and field key. + * + * @param ProfileValue[] $rows Rows. + * + * @return array<string, array<string, string[]>> + */ + private function groupValues(array $rows): array { + $result = []; + foreach ($rows as $row) { + $result[$row->getUserId()][$row->getFieldKey()][] = $row->getValue(); + } + + return $result; + }//end groupValues() + + /** + * Mirror a person's searchable standard fields with their scope (REQ-PEX-004). + * + * @param IUser $user The person. + * + * @return void + * + * @spec openspec/specs/people-widget/spec.md + */ + public function mirrorStandardFields(IUser $user): void { + try { + $account = $this->sources->accountManager->getAccount(user: $user); + } catch (Exception $e) { + $this->tools->logger->debug(message: 'Profile mirror: no account for ' . $user->getUID() . ': ' . $e->getMessage()); + return; + } + + foreach (self::MIRRORED_STANDARD_FIELDS as $key => $property) { + $value = ''; + $scope = null; + try { + $prop = $account->getProperty(property: $property); + $value = trim(string: $prop->getValue()); + $scope = $prop->getScope(); + } catch (Exception) { + $value = ''; + } + + $values = []; + if ($value !== '') { + $values = [$value]; + } + + $this->valueMapper->replaceValues( + userId: $user->getUID(), + field: new ProfileFieldValues(fieldKey: $key, values: $values, source: 'nextcloud', scope: $scope) + ); + }//end foreach + }//end mirrorStandardFields() + + /** + * Read a person's LDAP-sourced fields (REQ-PEX-001). Does nothing when + * `user_ldap` is not available or the account does not come from LDAP. + * + * @param IUser $user The person. + * + * @return int Number of fields synced. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function syncLdapFields(IUser $user): int { + $definitions = array_filter( + array: $this->getDefinitions(), + callback: static fn (array $definition): bool => $definition['source'] === 'ldap' + ); + if ($definitions === [] || $user->getBackendClassName() !== 'LDAP') { + return 0; + } + + if ($this->sources->ldapProviderFactory->isAvailable() === false) { + return 0; + } + + return $this->syncFromLdap(user: $user, definitions: $definitions); + }//end syncLdapFields() + + /** + * Copy each LDAP field's attribute values from the directory; a + * directory failure is logged and ends the sync. + * + * @param IUser $user The LDAP user. + * @param array<int, array<string, mixed>> $definitions The LDAP field definitions. + * + * @return int The number of fields synced before any failure. + */ + private function syncFromLdap(IUser $user, array $definitions): int { + $synced = 0; + try { + $provider = $this->sources->ldapProviderFactory->getLDAPProvider(); + foreach ($definitions as $definition) { + $raw = $provider->getMultiValueUserAttribute(uid: $user->getUID(), attribute: $definition['ldapAttribute']); + $this->valueMapper->replaceValues(userId: $user->getUID(), field: $this->ldapFieldValues(definition: $definition, raw: $raw)); + $synced++; + } + } catch (Exception $e) { + $this->tools->logger->warning(message: 'Profile LDAP sync failed for ' . $user->getUID() . ': ' . $e->getMessage()); + } + + return $synced; + }//end syncFromLdap() + + /** + * The cleaned LDAP values of one field, ready to replace the stored ones. + * + * @param array<string, mixed> $definition The LDAP field definition. + * @param array $raw The directory's attribute values. + * + * @return ProfileFieldValues The field's new values. + */ + private function ldapFieldValues(array $definition, array $raw): ProfileFieldValues { + $values = $this->cleanLdapValues(definition: $definition, raw: $raw); + + return new ProfileFieldValues(fieldKey: $definition['key'], values: $values, source: 'ldap'); + }//end ldapFieldValues() + + /** + * Clean the values read from LDAP: a text field keeps its first value. + * + * @param array $definition The field definition. + * @param array $raw Values from LDAP. + * + * @return string[] + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-a-profile-field-can-hold-a-start-date-req-pex-005 + */ + private function cleanLdapValues(array $definition, array $raw): array { + $values = []; + foreach ($raw as $item) { + $item = mb_substr(string: trim(string: (string)$item), start: 0, length: self::MAX_VALUE_LENGTH); + if ($item !== '') { + $values[mb_strtolower(string: $item)] ??= $item; + } + } + + $values = array_values(array: $values); + if ($definition['type'] === 'date') { + // REQ-PEX-005: LDAP writes a date as generalized time (`20261012000000Z`) or as `2026-10-12`. + $digits = substr(string: str_replace(search: '-', replace: '', subject: ($values[0] ?? '')), offset: 0, length: 8); + $year = substr(string: $digits, offset: 0, length: 4); + $month = substr(string: $digits, offset: 4, length: 2); + $day = substr(string: $digits, offset: 6, length: 2); + if (preg_match(pattern: '/^\d{8}$/', subject: $digits) !== 1 + || checkdate(month: (int)$month, day: (int)$day, year: (int)$year) === false + ) { + return []; + } + + return [$year.'-'.$month.'-'.$day]; + } + + if ($definition['type'] === 'text') { + return array_slice(array: $values, offset: 0, length: 1); + } + + return array_slice(array: $values, offset: 0, length: self::MAX_TAGS); + }//end cleanLdapValues() + + /** + * Define the demo fields when none are defined yet: an office location + * and a cost centre to fill in, and searchable expertise tags. Existing + * definitions are never touched. + * + * @return bool True when the demo fields were added. + * + * @spec openspec/specs/people-widget/spec.md + */ + public function seedDemoDefinitions(): bool { + if ($this->getDefinitions() !== []) { + return false; + } + + $this->saveDefinitions( + raw: [ + ['key' => 'office', 'label' => 'Kantoorlocatie', 'type' => 'text', 'source' => 'self', 'searchable' => true, 'shownInWidget' => true], + [ + 'key' => 'cost_centre', + 'label' => 'Kostenplaats', + 'type' => 'text', + 'source' => 'self', + 'searchable' => false, + 'shownInWidget' => false, + 'visibility' => 'groups', + ], + ['key' => 'expertise', 'label' => 'Expertise', 'type' => 'tags', 'source' => 'self', 'searchable' => true, 'shownInWidget' => true], + ] + ); + + return true; + }//end seedDemoDefinitions() + + /** + * Remove every value of a deleted person. + * + * @param string $userId The person. + * + * @return void + * + * @spec openspec/specs/people-widget/spec.md + */ + public function deleteUser(string $userId): void { + $this->valueMapper->deleteByUser(userId: $userId); + }//end deleteUser() +}//end class diff --git a/lib/Service/ProfileFieldTools.php b/lib/Service/ProfileFieldTools.php new file mode 100644 index 000000000..a64685aa2 --- /dev/null +++ b/lib/Service/ProfileFieldTools.php @@ -0,0 +1,45 @@ +<?php + +/** + * ProfileFieldTools + * + * The admin template service and the logger of the profile field service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/people-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use Psr\Log\LoggerInterface; + +/** + * The admin template service and the logger of the profile field service. + * + * @spec openspec/specs/people-widget/spec.md + */ +class ProfileFieldTools { + /** + * Constructor. + * + * @param AdminTemplateService $adminTemplateService Group ids of a user. + * @param LoggerInterface $logger Logger. + */ + public function __construct( + public readonly AdminTemplateService $adminTemplateService, + public readonly LoggerInterface $logger, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ProfileSources.php b/lib/Service/ProfileSources.php new file mode 100644 index 000000000..b7685509c --- /dev/null +++ b/lib/Service/ProfileSources.php @@ -0,0 +1,46 @@ +<?php + +/** + * ProfileSources + * + * The account manager and the LDAP provider factory profile values are read from. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/people-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Accounts\IAccountManager; +use OCP\LDAP\ILDAPProviderFactory; + +/** + * The account manager and the LDAP provider factory profile values are read from. + * + * @spec openspec/specs/people-widget/spec.md + */ +class ProfileSources { + /** + * Constructor. + * + * @param IAccountManager $accountManager Standard profile fields. + * @param ILDAPProviderFactory $ldapProviderFactory LDAP attribute access. + */ + public function __construct( + public readonly IAccountManager $accountManager, + public readonly ILDAPProviderFactory $ldapProviderFactory, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/PublicShareService.php b/lib/Service/PublicShareService.php index 88a69037c..b15911422 100644 --- a/lib/Service/PublicShareService.php +++ b/lib/Service/PublicShareService.php @@ -26,6 +26,8 @@ namespace OCA\LaunchPad\Service; use DateTime; +use Exception; +use InvalidArgumentException; use OCA\LaunchPad\Db\Dashboard; use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\PublicShare; @@ -38,6 +40,7 @@ use OCP\AppFramework\OCS\OCSForbiddenException; use OCP\IGroupManager; use OCP\Security\Bruteforce\IThrottler; +use RuntimeException; use OCP\Security\Bruteforce\MaxDelayReached; use OCP\Security\IHasher; use OCP\Security\ISecureRandom; @@ -69,7 +72,16 @@ class PublicShareService { * * @var string */ - public const ACTION_SHARE_PASSWORD = 'launchpad_share_password'; + public const BRUTE_FORCE_ACTION_SHARE_UNLOCK = 'launchpad_share_password'; + + /** + * Former name of BRUTE_FORCE_ACTION_SHARE_UNLOCK. + * + * @deprecated Use BRUTE_FORCE_ACTION_SHARE_UNLOCK. + * + * @var string + */ + public const ACTION_SHARE_PASSWORD = self::BRUTE_FORCE_ACTION_SHARE_UNLOCK; /** * Constructor. @@ -109,24 +121,38 @@ public function __construct( * * @throws DoesNotExistException When dashboard not found. * @throws OCSForbiddenException Via 403 on auth failure. + * @throws InvalidArgumentException When expiresAt is given but is not a date. + * @throws RuntimeException When the share cannot be stored. * * @spec openspec/changes/dashboard-public-share/tasks.md#task-5 - * - * @SuppressWarnings(PHPMD.StaticAccess) - * `DateTime::createFromFormat()` is a PHP built-in named constructor, - * called three times here to try the ATOM, `Y-m-d\TH:i:s\Z` and - * `Y-m-d H:i:s` expiry formats in turn. There is no instance-method - * equivalent and no collaborator to inject in its place. */ public function createPublicShare( string $dashboardUuid, string $callerId, + #[\SensitiveParameter] ?string $password = null, ?string $expiresAt = null, ): PublicShare { $dashboard = $this->dashMapper->findByUuid(uuid: $dashboardUuid); $this->authorizeShareMutation(dashboard: $dashboard, userId: $callerId); + $share = $this->newShare(dashboardUuid: $dashboardUuid, callerId: $callerId); + $this->applyPassword(share: $share, password: $password); + $this->applyExpiry(share: $share, expiresAt: $expiresAt); + + return $this->storeShare(share: $share, dashboardUuid: $dashboardUuid); + }//end createPublicShare() + + /** + * A new, unsaved share for a dashboard with a fresh token, its creator, + * its creation time and no views. + * + * @param string $dashboardUuid Dashboard UUID. + * @param string $callerId User ID of the creating user. + * + * @return PublicShare The share. + */ + private function newShare(string $dashboardUuid, string $callerId): PublicShare { $share = new PublicShare(); // phpcs:disable CustomSn.Functions.NamedParameters -- Entity magic __call breaks with named args. $share->setDashboardUuid($dashboardUuid); @@ -141,30 +167,89 @@ public function createPublicShare( $share->setViewCount(0); // phpcs:enable CustomSn.Functions.NamedParameters + return $share; + }//end newShare() + + /** + * Store the hash of a non-empty password on the share. + * + * @param PublicShare $share The new share. + * @param string|null $password Optional plaintext password. + * + * @return void + */ + private function applyPassword( + PublicShare $share, + #[\SensitiveParameter] + ?string $password, + ): void { if ($password !== null && $password !== '') { // phpcs:disable CustomSn.Functions.NamedParameters $share->setPasswordHash($this->hasher->hash(message: $password)); // phpcs:enable CustomSn.Functions.NamedParameters } + }//end applyPassword() - if ($expiresAt !== null && $expiresAt !== '') { - $parsed = DateTime::createFromFormat(DateTime::ATOM, $expiresAt); - if ($parsed === false) { - $parsed = DateTime::createFromFormat('Y-m-d\TH:i:s\Z', $expiresAt); - } + /** + * Store a non-empty expiry on the share in the database format. + * + * @param PublicShare $share The new share. + * @param string|null $expiresAt Optional expiry timestamp. + * + * @return void + * + * @throws InvalidArgumentException When expiresAt is given but is not a date. + */ + private function applyExpiry(PublicShare $share, ?string $expiresAt): void { + if ($expiresAt === null || $expiresAt === '') { + return; + } - if ($parsed === false) { - $parsed = DateTime::createFromFormat('Y-m-d H:i:s', $expiresAt); - } + $parsed = self::parseExpiry(expiresAt: $expiresAt); + // phpcs:disable CustomSn.Functions.NamedParameters + $share->setExpiresAt($parsed->format('Y-m-d H:i:s')); + // phpcs:enable CustomSn.Functions.NamedParameters + }//end applyExpiry() + /** + * Parse an expiry in the ATOM, `Y-m-d\TH:i:s\Z` or `Y-m-d H:i:s` + * format, tried in that order. + * + * @param string $expiresAt The expiry timestamp. + * + * @return DateTime The parsed expiry. + * + * @throws InvalidArgumentException When no format fits. + * + * @SuppressWarnings(PHPMD.StaticAccess) + * `DateTime::createFromFormat()` is a PHP built-in named constructor, + * called once per accepted expiry format. There is no + * instance-method equivalent and no collaborator to inject in its + * place. + */ + private static function parseExpiry(string $expiresAt): DateTime { + foreach ([DateTime::ATOM, 'Y-m-d\TH:i:s\Z', 'Y-m-d H:i:s'] as $format) { + $parsed = DateTime::createFromFormat($format, $expiresAt); if ($parsed !== false) { - // phpcs:disable CustomSn.Functions.NamedParameters - $share->setExpiresAt($parsed->format('Y-m-d H:i:s')); - // phpcs:enable CustomSn.Functions.NamedParameters + return $parsed; } } - $saved = $this->shareMapper->insert(entity: $share); + throw new InvalidArgumentException(message: 'expiresAt is not a valid date'); + }//end parseExpiry() + + /** + * Insert the new share and log its creation. + * + * @param PublicShare $share The new share. + * @param string $dashboardUuid Dashboard UUID. + * + * @return PublicShare The stored share. + * + * @throws RuntimeException When the share cannot be stored. + */ + private function storeShare(PublicShare $share, string $dashboardUuid): PublicShare { + $saved = $this->insertShare(share: $share); $this->logger->debug( message: sprintf('launchpad: public share created for dashboard %s', $dashboardUuid), @@ -172,7 +257,29 @@ public function createPublicShare( ); return $saved; - }//end createPublicShare() + }//end storeShare() + + /** + * Insert a share; a storage failure is logged by exception class only. + * + * @param PublicShare $share The new share. + * + * @return PublicShare The stored share. + * + * @throws RuntimeException When the share cannot be stored. + */ + private function insertShare(PublicShare $share): PublicShare { + try { + return $this->shareMapper->insert(entity: $share); + } catch (Exception $e) { + // The database error carries the token and password hash; only its class is kept. + $this->logger->error( + message: 'launchpad: storing a public share failed', + context: ['app' => 'launchpad', 'exceptionClass' => $e::class] + ); + throw new RuntimeException(message: 'The public share could not be stored'); + } + }//end insertShare() /** * List all active (non-revoked, non-expired) shares for a dashboard. @@ -259,47 +366,119 @@ public function revokeShare( public function renderShareContent( string $token, string $ipAddress, + #[\SensitiveParameter] ?string $password = null, ): array { + $share = $this->openShare(token: $token, ipAddress: $ipAddress, password: $password); + + return $this->shareContent(share: $share, visit: new PublicShareVisit(token: $token, ipAddress: $ipAddress)); + }//end renderShareContent() + + /** + * The id of the dashboard an active share shows, behind the same token + * and password gate as the render, without counting a visit: a widget on + * the shared page reads its data through it (REQ-PSHR-011). + * + * @param string $token The share token. + * @param string $ipAddress Client IP address for throttling. + * @param string|null $password Plaintext password supplied by the client. + * + * @return integer The shared dashboard's id. + * + * @throws ShareNotFoundException When token invalid, revoked, or expired. + * @throws SharePasswordRequiredException When password is required but not supplied or wrong. + * @throws DoesNotExistException When the shared dashboard was deleted. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + public function sharedDashboardId( + string $token, + string $ipAddress, + #[\SensitiveParameter] + ?string $password = null, + ): int { + $share = $this->openShare(token: $token, ipAddress: $ipAddress, password: $password); + + return (int)$this->dashMapper->findByUuid(uuid: (string)$share->getDashboardUuid())->getId(); + }//end sharedDashboardId() + + /** + * The active share behind a token, once its password gate is passed. + * + * @param string $token The share token. + * @param string $ipAddress Client IP address for throttling. + * @param string|null $password Plaintext password supplied by the client. + * + * @return PublicShare The opened share. + * + * @throws ShareNotFoundException When token invalid, revoked, or expired. + * @throws SharePasswordRequiredException When password is required but not supplied or wrong. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + private function openShare( + string $token, + string $ipAddress, + #[\SensitiveParameter] + ?string $password, + ): PublicShare { $share = $this->resolveActiveShare(token: $token, ipAddress: $ipAddress); - // Password gate. - if ($share->getPasswordHash() !== null) { - if ($password === null || $password === '') { - throw new SharePasswordRequiredException(); - } + // Password gate: an open share passes, a protected one needs the right password. + $hash = $share->getPasswordHash(); + if ($hash === null) { + return $share; + } - if ($this->hasher->verify( - message: $password, - hash: (string)$share->getPasswordHash() - ) === false - ) { - $this->throttler->registerAttempt( - action: self::ACTION_SHARE_PASSWORD, - ip: $ipAddress - ); - throw new SharePasswordRequiredException(); - } + if ($password === null || $password === '') { + throw new SharePasswordRequiredException(); + } + + if ($this->hasher->verify(message: $password, hash: $hash) === false) { + $this->registerPasswordFailure(ipAddress: $ipAddress); + throw new SharePasswordRequiredException(); } + return $share; + }//end openShare() + + /** + * Record a failed password attempt for throttling. + * + * @param string $ipAddress Client IP address. + * + * @return void + */ + private function registerPasswordFailure(string $ipAddress): void { + $this->throttler->registerAttempt( + action: self::BRUTE_FORCE_ACTION_SHARE_UNLOCK, + ip: $ipAddress + ); + }//end registerPasswordFailure() + + /** + * Count the visit and answer with the share's dashboard and placements. + * + * @param PublicShare $share The opened share. + * @param PublicShareVisit $visit The visit's token and IP address. + * + * @return array{share: PublicShare, dashboard: Dashboard, placements: WidgetPlacement[]} + */ + private function shareContent(PublicShare $share, PublicShareVisit $visit): array { $dashboard = $this->dashMapper->findByUuid(uuid: (string)$share->getDashboardUuid()); $this->shareMapper->incrementViewCount( id: (int)$share->getId(), - token: $token, - ipAddress: $ipAddress + token: $visit->token, + ipAddress: $visit->ipAddress ); $placements = $this->placementMapper->findByDashboardId( dashboardId: (int)$dashboard->getId() ); - return [ - 'share' => $share, - 'dashboard' => $dashboard, - 'placements' => $placements, - ]; - }//end renderShareContent() + return ['share' => $share, 'dashboard' => $dashboard, 'placements' => $placements]; + }//end shareContent() /** * Verify a password for a password-protected share (unlock endpoint). @@ -319,13 +498,14 @@ public function renderShareContent( */ public function unlockShare( string $token, + #[\SensitiveParameter] string $password, string $ipAddress, ): bool { // Throttle check before any DB query to prevent enumeration timing attacks. $this->throttler->sleepDelayOrThrowOnMax( ip: $ipAddress, - action: self::ACTION_SHARE_PASSWORD + action: self::BRUTE_FORCE_ACTION_SHARE_UNLOCK ); $share = $this->resolveActiveShare(token: $token, ipAddress: $ipAddress); @@ -341,10 +521,7 @@ public function unlockShare( ); if ($isValid === false) { - $this->throttler->registerAttempt( - action: self::ACTION_SHARE_PASSWORD, - ip: $ipAddress - ); + $this->registerPasswordFailure(ipAddress: $ipAddress); } return $isValid; @@ -368,41 +545,88 @@ public function unlockShare( * to inject in its place. */ private function resolveActiveShare(string $token, string $ipAddress): PublicShare { + $share = $this->findShareByToken(token: $token, ipAddress: $ipAddress); + + if ($share->getRevokedAt() !== null || $this->isExpired(share: $share) === true) { + $this->refuseAccess(ipAddress: $ipAddress); + } + + return $share; + }//end resolveActiveShare() + + /** + * The share with a token; an unknown token is recorded and refused. + * + * @param string $token The share token. + * @param string $ipAddress Client IP address. + * + * @return PublicShare The share. + * + * @throws ShareNotFoundException When no share has the token. + */ + private function findShareByToken(string $token, string $ipAddress): PublicShare { try { - $share = $this->shareMapper->findByToken(token: $token); + return $this->shareMapper->findByToken(token: $token); } catch (DoesNotExistException) { - $this->throttler->registerAttempt( - action: self::ACTION_SHARE_ACCESS, - ip: $ipAddress - ); - throw new ShareNotFoundException(); + $this->refuseAccess(ipAddress: $ipAddress); } + }//end findShareByToken() - if ($share->getRevokedAt() !== null) { - $this->throttler->registerAttempt( - action: self::ACTION_SHARE_ACCESS, - ip: $ipAddress - ); - throw new ShareNotFoundException(); + /** + * Record a failed share access for throttling and refuse it. + * + * @param string $ipAddress Client IP address. + * + * @return never + * + * @throws ShareNotFoundException Always. + */ + private function refuseAccess(string $ipAddress): never { + $this->throttler->registerAttempt( + action: self::ACTION_SHARE_ACCESS, + ip: $ipAddress + ); + throw new ShareNotFoundException(); + }//end refuseAccess() + + /** + * Whether a share's expiry has passed. + * + * @param PublicShare $share The share. + * + * @return bool True when it has an expiry in the past. + */ + private function isExpired(PublicShare $share): bool { + if ($share->getExpiresAt() === null) { + return false; } - if ($share->getExpiresAt() !== null) { - $expiry = DateTime::createFromFormat('Y-m-d H:i:s', (string)$share->getExpiresAt()); - if ($expiry === false) { - $expiry = new DateTime((string)$share->getExpiresAt()); - } + $expiry = self::parseStoredExpiry(expiresAt: (string)$share->getExpiresAt()); - if ($expiry < new DateTime()) { - $this->throttler->registerAttempt( - action: self::ACTION_SHARE_ACCESS, - ip: $ipAddress - ); - throw new ShareNotFoundException(); - } + return $expiry < new DateTime(); + }//end isExpired() + + /** + * Parse a stored expiry: the database format, else any format + * `DateTime` understands. + * + * @param string $expiresAt The stored expiry. + * + * @return DateTime The expiry. + * + * @SuppressWarnings(PHPMD.StaticAccess) + * `DateTime::createFromFormat()` is a PHP built-in named constructor; + * there is no instance-method equivalent to call and no collaborator + * to inject in its place. + */ + private static function parseStoredExpiry(string $expiresAt): DateTime { + $expiry = DateTime::createFromFormat('Y-m-d H:i:s', $expiresAt); + if ($expiry === false) { + return new DateTime($expiresAt); } - return $share; - }//end resolveActiveShare() + return $expiry; + }//end parseStoredExpiry() /** * Assert that the calling user may create/revoke shares for a dashboard. diff --git a/lib/Service/PublicShareVisit.php b/lib/Service/PublicShareVisit.php new file mode 100644 index 000000000..371f1d756 --- /dev/null +++ b/lib/Service/PublicShareVisit.php @@ -0,0 +1,44 @@ +<?php + +/** + * PublicShareVisit + * + * The token and client IP address of one anonymous visit to a public + * dashboard share. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/dashboard-public-share/tasks.md#task-5 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The token and client IP address of one public-share visit. + * + * @spec openspec/changes/dashboard-public-share/tasks.md#task-5 + */ +final class PublicShareVisit { + /** + * Constructor. + * + * @param string $token The share token. + * @param string $ipAddress The client IP address. + */ + public function __construct( + public readonly string $token, + public readonly string $ipAddress, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/PublicStartPage.php b/lib/Service/PublicStartPage.php new file mode 100644 index 000000000..7d5335c81 --- /dev/null +++ b/lib/Service/PublicStartPage.php @@ -0,0 +1,234 @@ +<?php + +/** + * PublicStartPage + * + * The public start page: one existing public link that signed-out visitors + * see instead of the login form, chosen and switched on by an administrator. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTime; +use InvalidArgumentException; +use OCA\LaunchPad\Db\AdminSettingKey; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\PublicShare; +use OCA\LaunchPad\Db\PublicShareMapper; +use OCA\LaunchPad\Kernel\Contracts\PublicStartPageInterface; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Utility\ITimeFactory; + +/** + * Chooses, checks and reports the public start page (design D1). + * + * A link with a password, a revoked link and a link whose expiry has passed + * cannot be chosen, so the start page never asks a visitor for a password. + * When the chosen link later becomes one of those, the start page is off + * ({@see active()} answers false) and {@see status()} says why; the stored + * choice is kept so the administrator sees what was chosen. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + */ +class PublicStartPage implements PublicStartPageInterface { + + /** + * Constructor. + * + * @param AdminSettingMapper $settings The admin settings. + * @param PublicShareMapper $shares The public links. + * @param ITimeFactory $time The clock an expiry is measured against. + * @param DashboardMapper $dashboards The dashboards, for the name an administrator picks a link by. + */ + public function __construct( + private readonly AdminSettingMapper $settings, + private readonly PublicShareMapper $shares, + private readonly ITimeFactory $time, + private readonly DashboardMapper $dashboards, + ) { + }//end __construct() + + /** + * The start page as configured: switched on or not, the chosen link, whether it is live, and why not. + * + * @return array{enabled: bool, token: string, active: bool, reason: string|null} + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + */ + public function status(): array { + $enabled = ($this->settings->getValue(key: AdminSettingKey::PUBLIC_START_ENABLED->value, default: false) === true); + $token = (string)$this->settings->getValue(key: AdminSettingKey::PUBLIC_START_SHARE_TOKEN->value, default: ''); + + $reason = 'off'; + if ($enabled === true) { + $reason = 'no-link'; + if ($token !== '') { + $reason = $this->refusal(share: $this->find(token: $token)); + } + } + + return ['enabled' => $enabled, 'token' => $token, 'active' => ($reason === null), 'reason' => $reason]; + }//end status() + + /** + * The link the start page shows, or null when it is off or its link can no longer be shown. + * + * @return PublicShare|null + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + */ + public function active(): ?PublicShare { + $status = $this->status(); + if ($status['active'] === false) { + return null; + } + + return $this->find(token: $status['token']); + }//end active() + + /** + * Choose the link and switch the start page on or off. + * + * An empty token clears the choice, and is only accepted with the page off. + * + * @param bool $enabled Whether the start page is on. + * @param string $token The chosen link's token, or '' for none. + * + * @return array{enabled: bool, token: string, active: bool, reason: string|null} The new status. + * + * @throws InvalidArgumentException When the link cannot be the start page, or the page is switched on without one. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + */ + public function configure(bool $enabled, string $token): array { + $token = trim($token); + if ($token === '' && $enabled === true) { + throw new InvalidArgumentException(message: 'Choose a public link before switching the start page on.'); + } + + if ($token !== '') { + $reason = $this->refusal(share: $this->find(token: $token)); + if ($reason !== null) { + throw new InvalidArgumentException(message: self::message(reason: $reason)); + } + } + + $this->settings->setSetting(key: AdminSettingKey::PUBLIC_START_SHARE_TOKEN->value, value: $token); + $this->settings->setSetting(key: AdminSettingKey::PUBLIC_START_ENABLED->value, value: $enabled); + + return $this->status(); + }//end configure() + + /** + * The links that may be chosen: not revoked, not expired, no password. + * + * @return list<array{token: string, dashboardUuid: string, dashboardName: string, expiresAt: string|null}> + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + */ + public function candidates(): array { + $candidates = []; + foreach ($this->shares->findStartPageCandidates() as $share) { + if ($this->refusal(share: $share) === null) { + $candidates[] = [ + 'token' => (string)$share->getToken(), + 'dashboardUuid' => (string)$share->getDashboardUuid(), + 'dashboardName' => $this->dashboardName(uuid: (string)$share->getDashboardUuid()), + 'expiresAt' => $share->getExpiresAt(), + ]; + } + } + + return $candidates; + }//end candidates() + + /** + * Why a link cannot be the start page, or null when it can. + * + * @param PublicShare|null $share The link, or null when the token names none. + * + * @return string|null `not-found`, `revoked`, `password` or `expired`. + */ + private function refusal(?PublicShare $share): ?string { + if ($share === null) { + return 'not-found'; + } + + if ($share->getRevokedAt() !== null) { + return 'revoked'; + } + + if ($share->getPasswordHash() !== null && $share->getPasswordHash() !== '') { + return 'password'; + } + + $expiresAt = $share->getExpiresAt(); + if ($expiresAt !== null && $expiresAt !== '') { + $expiry = DateTime::createFromFormat('Y-m-d H:i:s', $expiresAt); + if ($expiry === false || $expiry <= $this->time->getDateTime()) { + return 'expired'; + } + } + + return null; + }//end refusal() + + /** + * A dashboard's name, or '' when it has none or is gone. + * + * @param string $uuid The dashboard uuid. + * + * @return string + */ + private function dashboardName(string $uuid): string { + try { + return (string)$this->dashboards->findByUuid(uuid: $uuid)->getName(); + } catch (DoesNotExistException $e) { + return ''; + } + }//end dashboardName() + + /** + * The share with a token, or null. + * + * @param string $token The token. + * + * @return PublicShare|null + */ + private function find(string $token): ?PublicShare { + try { + return $this->shares->findByToken(token: $token); + } catch (DoesNotExistException $e) { + return null; + } + }//end find() + + /** + * The refusal an administrator reads. + * + * @param string $reason The refusal reason. + * + * @return string + */ + private static function message(string $reason): string { + return match ($reason) { + 'revoked' => 'This public link has been revoked and cannot be the start page.', + 'password' => 'A public link with a password cannot be the start page.', + 'expired' => 'This public link has expired and cannot be the start page.', + default => 'There is no public link with this token.', + }; + }//end message() +}//end class diff --git a/lib/Service/PublicWidgetReadService.php b/lib/Service/PublicWidgetReadService.php new file mode 100644 index 000000000..e62ea08d2 --- /dev/null +++ b/lib/Service/PublicWidgetReadService.php @@ -0,0 +1,185 @@ +<?php + +/** + * PublicWidgetReadService + * + * The data a live widget shows on a public link or a kiosk screen: the + * published announcements for everyone, a weather reading or a live data + * value, read for one placement and only when that placement is on a + * dashboard the link or playlist shows (REQ-PSHR-011). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Announcement; +use OCA\LaunchPad\Db\WidgetPlacement; +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Kernel\Contracts\ConditionalServiceInterface; +use OCP\AppFramework\Db\DoesNotExistException; + +/** + * Reads a live widget's data for an anonymous visitor of a shared dashboard. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +class PublicWidgetReadService { + + /** + * The widget type of the weather widget. + * + * @var string + */ + public const WIDGET_WEATHER = 'weather'; + + /** + * The widget type of the live data widget. + * + * @var string + */ + public const WIDGET_LIVE_DATA = 'livetile'; + + /** + * The widget type of the news widget that lists announcements. + * + * @var string + */ + public const WIDGET_NEWS = 'announcements'; + + /** + * How many announcements the news widget lists when its content sets no limit. + * + * @var integer + */ + public const DEFAULT_NEWS_LIMIT = 10; + + /** + * Constructor. + * + * @param WidgetPlacementMapper $placementMapper Loads the placement asked for. + * @param PublicWidgetSources $sources The weather, live data and announcements. + * @param ConditionalServiceInterface|null $visibility Applies the widget visibility rules. + */ + public function __construct( + private readonly WidgetPlacementMapper $placementMapper, + private readonly PublicWidgetSources $sources, + private readonly ?ConditionalServiceInterface $visibility = null, + ) { + }//end __construct() + + /** + * The data of one live widget on a shared dashboard. + * + * The placement must be on one of the dashboards the link or playlist + * shows, visible to a visitor who cannot edit, and a news, weather or + * live data widget; anything else is refused as not found, so a token + * never reads a widget of another dashboard. + * + * @param list<int> $dashboardIds The dashboards the token shows. + * @param integer $placementId The placement asked for. + * + * @return array{widget: string, data: array<string, mixed>} The widget type and its data. + * + * @throws DoesNotExistException When the placement is not a live widget on a shared dashboard. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + public function read(array $dashboardIds, int $placementId): array { + $placement = $this->sharedPlacement(dashboardIds: $dashboardIds, placementId: $placementId); + $widget = $placement->getWidgetId(); + + return match ($widget) { + self::WIDGET_WEATHER => [ + 'widget' => $widget, + 'data' => $this->sources->weather->resolveForPlacement(placementId: $placementId, userId: ''), + ], + self::WIDGET_LIVE_DATA => [ + 'widget' => $widget, + 'data' => $this->sources->liveData->resolveForPlacement(placementId: $placementId), + ], + self::WIDGET_NEWS => [ + 'widget' => $widget, + 'data' => ['announcements' => $this->news(content: $placement->getContentArray())], + ], + default => throw new DoesNotExistException(msg: 'Not a live widget'), + }; + }//end read() + + /** + * The placement asked for, when it is on a shared dashboard and a + * visitor who cannot edit sees it. + * + * @param list<int> $dashboardIds The dashboards the token shows. + * @param integer $placementId The placement asked for. + * + * @return WidgetPlacement The placement. + * + * @throws DoesNotExistException When it is not on a shared dashboard or the rules hide it. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + private function sharedPlacement(array $dashboardIds, int $placementId): WidgetPlacement { + $placement = $this->placementMapper->find(id: $placementId); + if (in_array($placement->getDashboardId(), $dashboardIds, true) === false) { + throw new DoesNotExistException(msg: 'Not on a shared dashboard'); + } + + if ($this->visibility !== null + && $this->visibility->visiblePlacements(placements: [$placement->jsonSerialize()], userId: '', canEdit: false) === [] + ) { + throw new DoesNotExistException(msg: 'Hidden by the visibility rules'); + } + + return $placement; + }//end sharedPlacement() + + /** + * The news items for everyone, newest first, in the widget's category + * and up to its limit; notices show as banners, not here. Only what the + * card shows leaves the server: no author, no target groups. + * + * @param array<string, mixed> $content The placement's content: `category` and `limit`. + * + * @return list<array<string, mixed>> The news items. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + private function news(array $content): array { + $category = (string)($content['category'] ?? ''); + $limit = (int)($content['limit'] ?? 0); + if ($limit <= 0) { + $limit = self::DEFAULT_NEWS_LIMIT; + } + + // No reader: only what is targeted at everyone; the target check is + // repeated so a group's news can never reach an anonymous visitor. + $items = array_filter( + $this->sources->announcements->visibleTo(userId: ''), + static fn (Announcement $item): bool => $item->getTargetGroupList() === [] + && $item->getKind() !== Announcement::KIND_NOTICE + && ($category === '' || $item->getCategory() === $category) + ); + + return array_map( + static fn (Announcement $item): array => array_intersect_key( + $item->jsonSerialize(), + array_flip(['uuid', 'kind', 'title', 'body', 'category', 'level', 'publishAt']) + ), + array_slice(array_values($items), 0, $limit) + ); + }//end news() +}//end class diff --git a/lib/Service/PublicWidgetSources.php b/lib/Service/PublicWidgetSources.php new file mode 100644 index 000000000..2bb87771c --- /dev/null +++ b/lib/Service/PublicWidgetSources.php @@ -0,0 +1,49 @@ +<?php + +/** + * PublicWidgetSources + * + * Where the live widgets on a public link or a kiosk screen read their data: + * the weather, the live data values and the announcements. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Kernel\Contracts\AnnouncementServiceInterface; +use OCA\LaunchPad\Kernel\Contracts\WeatherServiceInterface; + +/** + * The data sources of the live widgets on a shared dashboard. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +class PublicWidgetSources { + /** + * Constructor. + * + * @param WeatherServiceInterface $weather Resolves a weather reading. + * @param LiveTileService $liveData Resolves a live data value. + * @param AnnouncementServiceInterface $announcements The published announcements. + */ + public function __construct( + public readonly WeatherServiceInterface $weather, + public readonly LiveTileService $liveData, + public readonly AnnouncementServiceInterface $announcements, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/PublicWidgetTokens.php b/lib/Service/PublicWidgetTokens.php new file mode 100644 index 000000000..f8075bd0d --- /dev/null +++ b/lib/Service/PublicWidgetTokens.php @@ -0,0 +1,97 @@ +<?php + +/** + * PublicWidgetTokens + * + * Opens the token of a public share or a kiosk playlist for a live widget's + * read: the dashboards it shows, behind the share's password gate, and the + * request marked as a read-only bearer (REQ-PSHR-011). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Exception\PlaylistNotFoundException; +use OCA\LaunchPad\Exception\ShareNotFoundException; +use OCA\LaunchPad\Exception\SharePasswordRequiredException; +use OCP\AppFramework\Db\DoesNotExistException; + +/** + * The dashboards a public share or kiosk playlist token shows. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +class PublicWidgetTokens { + /** + * Constructor. + * + * @param PublicShareService $shares Opens a public share token. + * @param KioskService $kiosk Opens a kiosk playlist token. + * @param PublicShareContext $shareContext Marks the request as a read-only bearer. + */ + public function __construct( + private readonly PublicShareService $shares, + private readonly KioskService $kiosk, + private readonly PublicShareContext $shareContext, + ) { + }//end __construct() + + /** + * The dashboard a public share shows. + * + * @param string $token The share token. + * @param string $ipAddress Client IP address for throttling. + * @param string|null $password The share password, when sent. + * + * @return list<int> The shared dashboard's id. + * + * @throws ShareNotFoundException When token invalid, revoked, or expired. + * @throws SharePasswordRequiredException When password is required but not supplied or wrong. + * @throws DoesNotExistException When the shared dashboard was deleted. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + public function shareDashboards( + string $token, + string $ipAddress, + #[\SensitiveParameter] + ?string $password, + ): array { + $dashboardId = $this->shares->sharedDashboardId(token: $token, ipAddress: $ipAddress, password: $password); + $this->shareContext->markBearer(token: $token); + + return [$dashboardId]; + }//end shareDashboards() + + /** + * The dashboards a kiosk playlist shows. + * + * @param string $token The playlist token. + * + * @return list<int> The entries' dashboard ids. + * + * @throws PlaylistNotFoundException When the token is unknown or revoked. + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + public function kioskDashboards(string $token): array { + $dashboardIds = $this->kiosk->playlistDashboardIds(token: $token); + $this->shareContext->markBearer(token: $token); + + return $dashboardIds; + }//end kioskDashboards() +}//end class diff --git a/lib/Service/PublicationWindow.php b/lib/Service/PublicationWindow.php new file mode 100644 index 000000000..38b4e2174 --- /dev/null +++ b/lib/Service/PublicationWindow.php @@ -0,0 +1,42 @@ +<?php + +/** + * PublicationWindow + * + * The validated go-live and take-down times of one schedule request + * (REQ-DASH-034, REQ-SCHEDUI-002), as `Y-m-d H:i:s` strings. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * A validated publication window. + * + * @spec openspec/specs/dashboards/spec.md + */ +final class PublicationWindow { + /** + * Constructor. + * + * @param string|null $publishAt The go-live time, or null to leave the status as it is. + * @param string|null $unpublishAt The take-down time, or null for none. + */ + public function __construct( + public readonly string|null $publishAt, + public readonly string|null $unpublishAt, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/QueryUrlTemplate.php b/lib/Service/QueryUrlTemplate.php new file mode 100644 index 000000000..4534ba6bb --- /dev/null +++ b/lib/Service/QueryUrlTemplate.php @@ -0,0 +1,57 @@ +<?php + +/** + * QueryUrlTemplate + * + * The shape check for an address template with a `{query}` placeholder, + * shared by the quick-search web fallback (REQ-QSEARCH-004) and the search + * shortcuts (REQ-SPX-001). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Validates `https` address templates that contain `{query}`. + * + * @spec openspec/specs/tile-quick-search/spec.md + */ +final class QueryUrlTemplate { + /** + * Validate the `https` + `{query}`-placeholder shape of an address + * template. Substitutes a harmless probe string for `{query}` before + * validating so a template like `https://example.org/search?q={query}` + * — not a valid URL as written — validates correctly. + * + * @param string $value the candidate URL template. + * + * @return bool true when `$value` is a valid `https` URL template + * containing `{query}`. + * + * @spec openspec/specs/tile-quick-search/spec.md + */ + public static function isValid(string $value): bool { + if (trim($value) === '' || str_contains(haystack: $value, needle: '{query}') === false) { + return false; + } + + $probe = str_replace(search: '{query}', replace: 'quicksearch-validation-probe', subject: $value); + + if (parse_url(url: $probe, component: PHP_URL_SCHEME) !== 'https') { + return false; + } + + return filter_var(value: $probe, filter: FILTER_VALIDATE_URL) !== false; + }//end isValid() +}//end class diff --git a/lib/Service/QuicklinksContentValidator.php b/lib/Service/QuicklinksContentValidator.php new file mode 100644 index 000000000..89ba772f8 --- /dev/null +++ b/lib/Service/QuicklinksContentValidator.php @@ -0,0 +1,92 @@ +<?php + +/** + * QuicklinksContentValidator + * + * Server-side validator for the `quicklinks` widget content blob. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * Validates `quicklinks` widget content before a placement is saved. + * + * Every link URL is required, at most 2048 characters, and starts with + * `http://`, `https://` or a single `/` (a relative Nextcloud address). + * Anything else, such as `javascript:` or `data:`, is refused as "Invalid URL". + * + * @spec openspec/specs/quicklinks-widget/spec.md#requirement-req-qlnk-008-url-sanitisation-on-save + */ +class QuicklinksContentValidator { + + /** + * The longest URL a link may carry. + */ + private const MAX_URL_LENGTH = 2048; + + /** + * Validate a quicklinks placement's content. + * + * @param array $content The placement content. + * + * @return void + * @throws InvalidArgumentException When a link URL is refused. + * + * @spec openspec/specs/quicklinks-widget/spec.md#requirement-req-qlnk-008-url-sanitisation-on-save + */ + public function validate(array $content): void { + $links = ($content['links'] ?? []); + if (is_array($links) === false) { + throw new InvalidArgumentException(message: 'Links must be a list'); + } + + foreach ($links as $link) { + $url = null; + if (is_array($link) === true) { + $url = ($link['url'] ?? null); + } + + if ($this->isAllowedUrl(url: $url) === false) { + throw new InvalidArgumentException(message: 'Invalid URL'); + } + } + }//end validate() + + /** + * Whether a link URL is a non-empty http(s) address or relative Nextcloud path. + * + * @param mixed $url The link's `url` value. + * + * @return bool True when the URL may be saved. + * + * @spec openspec/specs/quicklinks-widget/spec.md#requirement-req-qlnk-008-url-sanitisation-on-save + */ + private function isAllowedUrl(mixed $url): bool { + if (is_string($url) === false) { + return false; + } + + $url = trim($url); + if ($url === '' || strlen($url) > self::MAX_URL_LENGTH) { + return false; + } + + return preg_match('#^https?://[^\s/]#i', $url) === 1 + || preg_match('#^/(?![/\\\\])#', $url) === 1; + }//end isAllowedUrl() +}//end class diff --git a/lib/Service/QuotaService.php b/lib/Service/QuotaService.php index 44ef587a8..a92ae2046 100644 --- a/lib/Service/QuotaService.php +++ b/lib/Service/QuotaService.php @@ -36,6 +36,7 @@ use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacementMapper; use OCA\LaunchPad\Exception\QuotaExceededException; +use OCA\LaunchPad\Kernel\Contracts\QuotaServiceInterface; use Throwable; /** @@ -43,7 +44,7 @@ * * @spec openspec/changes/dashboard-quota-limits/specs/dashboard-quota-limits/spec.md */ -class QuotaService { +class QuotaService implements QuotaServiceInterface { /** * Provisioning-context depth. Greater than zero means the current call @@ -207,6 +208,43 @@ public function assertCanAddPlacement(int $dashboardId): void { } }//end assertCanAddPlacement() + /** + * Refuse adding several placements at once when they would take the + * dashboard over its widget limit, before any of them is created + * (launcher-bookmark-import REQ-BMI-003). Same bypass and same limit as + * {@see self::assertCanAddPlacement()}. + * + * @param int $dashboardId The target dashboard ID. + * @param int $count How many placements would be added. + * + * @return void + * + * @throws QuotaExceededException When the dashboard has room for fewer than `$count`. + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-the-import-respects-the-widget-quota-as-one-operation-req-bmi-003 + */ + public function assertCanAddPlacements(int $dashboardId, int $count): void { + if ($this->provisioningDepth > 0 || $count <= 0) { + return; + } + + $limit = $this->maxWidgetsPerDashboard(); + if ($limit === 0) { + return; + } + + $current = $this->placementMapper->countByDashboardId( + dashboardId: $dashboardId + ); + if (($current + $count) > $limit) { + throw new QuotaExceededException( + quota: QuotaExceededException::QUOTA_WIDGETS, + limit: $limit, + current: $current + ); + } + }//end assertCanAddPlacements() + /** * Build the additive quota-status envelope for the dashboards list * response (REQ-QUOTA-006). diff --git a/lib/Service/RdpFileWriter.php b/lib/Service/RdpFileWriter.php new file mode 100644 index 000000000..c62877646 --- /dev/null +++ b/lib/Service/RdpFileWriter.php @@ -0,0 +1,101 @@ +<?php + +/** + * RdpFileWriter + * + * Writes the `.rdp` file of a remote-desktop tile from its checked + * connection: host, port, an optional published program and an optional + * gateway. No user name, password or other credential field is ever written. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-3 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Kernel\Contracts\RdpFileWriterInterface; + +/** + * Builds an RDP connection file and its download name (design D3). + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-3 + */ +class RdpFileWriter implements RdpFileWriterInterface { + + /** + * The file name when the tile has no usable title. + */ + private const FALLBACK_NAME = 'remote-desktop'; + + /** + * The contents of the file, one setting per line (CRLF, as Windows writes them). + * + * @param array{host: string, port: int, remoteApp: string, gateway: string} $connection The checked connection. + * + * @return string + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-a-remote-desktop-or-a-published-program-req-tlt-002 + */ + public function contents(array $connection): string { + $lines = [ + 'full address:s:' . $connection['host'], + 'server port:i:' . $connection['port'], + ]; + if ($connection['remoteApp'] !== '') { + $lines[] = 'remoteapplicationmode:i:1'; + $lines[] = 'remoteapplicationprogram:s:' . $connection['remoteApp']; + } + + if ($connection['gateway'] !== '') { + $lines[] = 'gatewayhostname:s:' . $connection['gateway']; + $lines[] = 'gatewayusagemethod:i:1'; + } + + $lines[] = 'use redirection server name:i:1'; + return implode("\r\n", $lines) . "\r\n"; + }//end contents() + + /** + * The download name: the tile's title with characters a file name cannot hold left out. + * + * @param string|null $title The tile's title. + * + * @return string + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-a-remote-desktop-or-a-published-program-req-tlt-002 + */ + public function fileName(?string $title): string { + $name = trim((string)preg_replace('/[\x00-\x1f\x7f\/\\\\:*?"<>|]+/', '', (string)$title), " ."); + if ($name === '') { + $name = self::FALLBACK_NAME; + } + + return mb_substr($name, 0, 120) . '.rdp'; + }//end fileName() + + /** + * The Content-Disposition header that saves the file under its name. + * + * The plain `filename` holds an ASCII copy for old clients; `filename*` + * holds the name itself, percent-encoded (RFC 6266). + * + * @param string $fileName A name from fileName(). + * + * @return string + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-a-remote-desktop-or-a-published-program-req-tlt-002 + */ + public function disposition(string $fileName): string { + $ascii = (string)preg_replace('/[^\x20-\x7e]|["\\%]/', '_', $fileName); + return 'attachment; filename="' . $ascii . '"; filename*=UTF-8\'\'' . rawurlencode($fileName); + }//end disposition() +}//end class diff --git a/lib/Service/ReactionDirectory.php b/lib/Service/ReactionDirectory.php new file mode 100644 index 000000000..8e8719f6e --- /dev/null +++ b/lib/Service/ReactionDirectory.php @@ -0,0 +1,53 @@ +<?php + +/** + * ReactionDirectory + * + * The app config, the user manager and the version rows of the reaction + * service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboard-reactions/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardVersionMapper; +use OCP\IAppConfig; +use OCP\IUserManager; + +/** + * The app config, the user manager and the version rows of the reaction + * service. + * + * @spec openspec/specs/dashboard-reactions/spec.md + */ +class ReactionDirectory { + /** + * Constructor. + * + * @param IAppConfig $appConfig App config — admin settings. + * @param IUserManager $userManager Display name resolution for the reactors-by-emoji endpoint. + * @param DashboardVersionMapper|null $versionMapper The saved versions, for who last changed a dashboard. + * + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard + */ + public function __construct( + public readonly IAppConfig $appConfig, + public readonly IUserManager $userManager, + public readonly ?DashboardVersionMapper $versionMapper = null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ReactionService.php b/lib/Service/ReactionService.php index ffc4b056f..e17d9c156 100644 --- a/lib/Service/ReactionService.php +++ b/lib/Service/ReactionService.php @@ -29,10 +29,9 @@ use OCA\LaunchPad\Db\Dashboard; use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\DashboardReactionMapper; +use OCA\LaunchPad\Db\DashboardVersion; use OCP\AppFramework\Db\DoesNotExistException; use OCP\DB\Exception as DbException; -use OCP\IAppConfig; -use OCP\IUserManager; /** * Service for managing dashboard emoji reactions. @@ -78,22 +77,15 @@ class ReactionService { * Constructor * * @param DashboardReactionMapper $reactionMapper The reaction mapper. - * @param DashboardMapper $dashboardMapper Dashboard lookups - * (toggle resolution). - * @param PermissionService $permissionService VIEW permission gate. - * @param IAppConfig $appConfig App config — admin - * settings. - * @param IUserManager $userManager Display name - * resolution for the - * reactors-by-emoji - * endpoint. + * @param DashboardMapper $dashboardMapper Dashboard lookups (toggle resolution). + * @param PermissionService $permissionService VIEW permission gate. + * @param ReactionDirectory $directory The app config and user manager. */ public function __construct( private readonly DashboardReactionMapper $reactionMapper, private readonly DashboardMapper $dashboardMapper, private readonly PermissionService $permissionService, - private readonly IAppConfig $appConfig, - private readonly IUserManager $userManager, + private readonly ReactionDirectory $directory, ) { }//end __construct() @@ -125,17 +117,19 @@ public function isReactionsEnabled(Dashboard $dashboard): bool { }//end isReactionsEnabled() /** - * Read the admin global on/off toggle. Default: true. + * Read the admin global on/off toggle. Default: false, so a dashboard + * shows no reactions row until an administrator turns reactions on + * (globally, or per dashboard with reactionsEnabled = 1). * * @return bool True when the global default is on. * * @spec openspec/specs/dashboard-reactions/spec.md */ public function isReactionsEnabledByDefault(): bool { - return $this->appConfig->getValueBool( + return $this->directory->appConfig->getValueBool( app: Application::APP_ID, key: self::KEY_ENABLED_DEFAULT, - default: true + default: false ); }//end isReactionsEnabledByDefault() @@ -148,7 +142,7 @@ public function isReactionsEnabledByDefault(): bool { * @spec openspec/specs/dashboard-reactions/spec.md */ public function getAllowedEmojis(): array { - $raw = $this->appConfig->getValueString( + $raw = $this->directory->appConfig->getValueString( app: Application::APP_ID, key: self::KEY_ALLOWED_EMOJIS, default: '' @@ -385,9 +379,70 @@ private function buildSummary(Dashboard $dashboard, string $userId): array { 'enabled' => true, // The reactions bar offers only these (REQ-RXN-007, REQ-RXN-010). 'allowed' => $this->getAllowedEmojis(), + // The bar names who last changed the dashboard (REQ-RXN-010). + 'lastChange' => $this->lastChange(dashboard: $dashboard), ]; }//end buildSummary() + /** + * Who last changed the dashboard and when: the newest saved version's + * author and time, else the dashboard's own change time without a name. + * Null when neither is known. + * + * @param Dashboard $dashboard The dashboard. + * + * @return array{name: string, at: string|null}|null The last change. + * + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard + */ + private function lastChange(Dashboard $dashboard): ?array { + $version = $this->newestVersion(dashboardUuid: (string)$dashboard->getUuid()); + if ($version !== null) { + $author = (string)$version->getCreatedBy(); + $name = $author; + if ($author !== '') { + $name = $this->directory->userManager->get(uid: $author)?->getDisplayName() ?? $author; + } + + return [ + 'name' => $name, + 'at' => $version->getCreatedAt() ?? $dashboard->getUpdatedAt(), + ]; + } + + $updatedAt = $dashboard->getUpdatedAt(); + if ($updatedAt === null || $updatedAt === '') { + return null; + } + + return ['name' => '', 'at' => $updatedAt]; + }//end lastChange() + + /** + * The newest saved version of a dashboard, or null without versions or + * when they cannot be read. + * + * @param string $dashboardUuid The dashboard UUID. + * + * @return DashboardVersion|null The newest version. + * + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard + */ + private function newestVersion(string $dashboardUuid): ?DashboardVersion { + $mapper = $this->directory->versionMapper; + if ($mapper === null) { + return null; + } + + try { + $rows = $mapper->findLatestByDashboard(dashboardUuid: $dashboardUuid, limit: 1); + } catch (DbException) { + return null; + } + + return $rows[0] ?? null; + }//end newestVersion() + /** * List reactors for a single emoji on a dashboard, capped at * {@see self::REACTORS_PAGE_SIZE} per response with simple @@ -418,13 +473,7 @@ public function getReactorsByEmoji( userId: $userId ); - $offset = 0; - if ($cursor !== null && $cursor !== '') { - $candidate = (int)$cursor; - if ($candidate > 0) { - $offset = $candidate; - } - } + $offset = $this->cursorOffset(cursor: $cursor); $rows = $this->reactionMapper->findByEmoji( dashboardUuid: $dashboardUuid, @@ -437,16 +486,7 @@ public function getReactorsByEmoji( emoji: $emoji ); - $items = []; - foreach ($rows as $reaction) { - $reactorId = (string)$reaction->getUserId(); - $user = $this->userManager->get(uid: $reactorId); - $items[] = [ - 'userId' => $reactorId, - 'displayName' => $user?->getDisplayName() ?? $reactorId, - 'reactedAt' => $reaction->getReactedAtFormatted(), - ]; - } + $items = $this->reactorItems(reactions: $rows); $nextOffset = ($offset + count($items)); $nextCursor = null; @@ -461,6 +501,49 @@ public function getReactorsByEmoji( ]; }//end getReactorsByEmoji() + /** + * The offset an opaque reactor cursor stands for; anything but a + * positive integer starts at the first page. + * + * @param string|null $cursor The cursor from the request. + * + * @return int The offset. + */ + private function cursorOffset(?string $cursor): int { + $offset = 0; + if ($cursor !== null && $cursor !== '') { + $candidate = (int)$cursor; + if ($candidate > 0) { + $offset = $candidate; + } + } + + return $offset; + }//end cursorOffset() + + /** + * One `{userId, displayName, reactedAt}` row per reaction; a reactor + * without an account is shown by user ID. + * + * @param array $reactions The reaction rows of one page. + * + * @return array<int, array{userId: string, displayName: string, reactedAt: string|null}> The page items. + */ + private function reactorItems(array $reactions): array { + $items = []; + foreach ($reactions as $reaction) { + $reactorId = (string)$reaction->getUserId(); + $user = $this->directory->userManager->get(uid: $reactorId); + $items[] = [ + 'userId' => $reactorId, + 'displayName' => $user?->getDisplayName() ?? $reactorId, + 'reactedAt' => $reaction->getReactedAtFormatted(), + ]; + } + + return $items; + }//end reactorItems() + /** * Cascade-delete every reaction for a dashboard. Called by the * `ReactionsListener` (REQ-CSC-003) on `DashboardDeletedEvent`. diff --git a/lib/Service/ReadReceiptPeople.php b/lib/Service/ReadReceiptPeople.php new file mode 100644 index 000000000..446aa7065 --- /dev/null +++ b/lib/Service/ReadReceiptPeople.php @@ -0,0 +1,144 @@ +<?php + +/** + * ReadReceiptPeople + * + * The names and departments of the people on a read-receipt report + * (REQ-ACK-010). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\ProfileValueMapper; +use OCP\IUserManager; + +/** + * Adds `displayName` and `department` to every row of a report, and the + * department field's label to the report. The department is the value of + * the profile field the administrator marked as the department, shown only + * where the viewer may see that field; '' otherwise. + * + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ +class ReadReceiptPeople { + /** + * Constructor. + * + * @param IUserManager $userManager Display names. + * @param ProfileFieldService $profileFields The field definitions and who may see them. + * @param ProfileValueMapper $values The profile values. + */ + public function __construct( + private readonly IUserManager $userManager, + private readonly ProfileFieldService $profileFields, + private readonly ProfileValueMapper $values, + ) { + }//end __construct() + + /** + * The report with each row's display name and department, and + * `departmentLabel` ('' when no field is the department). + * + * @param array<string, mixed> $report The report of AcknowledgementService::report(). + * @param string|null $viewerId Who reads the report. + * + * @return array<string, mixed> + * + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + public function withPeople(array $report, ?string $viewerId): array { + $rows = []; + if (is_array(value: $report['rows'] ?? null) === true) { + $rows = $report['rows']; + } + + $userIds = array_values(array: array_map(array: $rows, callback: static fn (array $row): string => (string)($row['userId'] ?? ''))); + $field = $this->departmentField(); + $departments = []; + if ($field !== null) { + $departments = $this->departmentsOf(field: $field, userIds: $userIds, viewerId: $viewerId); + } + + $report['rows'] = array_map( + array: $rows, + callback: fn (array $row): array => $row + [ + 'displayName' => $this->displayName(userId: (string)($row['userId'] ?? '')), + 'department' => $departments[(string)($row['userId'] ?? '')] ?? '', + ] + ); + $report['departmentLabel'] = (string)($field['label'] ?? ''); + + return $report; + }//end withPeople() + + /** + * The field marked as the department, or null. + * + * @return array<string, mixed>|null + */ + private function departmentField(): ?array { + foreach ($this->profileFields->getDefinitions() as $definition) { + if (($definition['department'] ?? false) === true) { + return $definition; + } + } + + return null; + }//end departmentField() + + /** + * Each person's department the viewer may see: the field's values joined. + * + * @param array<string, mixed> $field The department field. + * @param string[] $userIds The people. + * @param string|null $viewerId Who reads the report. + * + * @return array<string, string> userId => department. + */ + private function departmentsOf(array $field, array $userIds, ?string $viewerId): array { + $values = []; + foreach ($this->values->findByUsers(userIds: $userIds) as $value) { + if ($value->getFieldKey() === $field['key']) { + $values[$value->getUserId()][] = $value->getValue(); + } + } + + $departments = []; + foreach ($values as $userId => $list) { + if ($this->profileFields->canSee(viewerId: $viewerId, ownerId: (string)$userId, definition: $field) === true) { + $departments[(string)$userId] = implode(separator: ', ', array: $list); + } + } + + return $departments; + }//end departmentsOf() + + /** + * The person's display name, else the user id. + * + * @param string $userId The person. + * + * @return string + */ + private function displayName(string $userId): string { + $name = (string)$this->userManager->getDisplayName(uid: $userId); + if ($name === '') { + return $userId; + } + + return $name; + }//end displayName() +}//end class diff --git a/lib/Service/ReadingSources.php b/lib/Service/ReadingSources.php new file mode 100644 index 000000000..d6c8a8491 --- /dev/null +++ b/lib/Service/ReadingSources.php @@ -0,0 +1,55 @@ +<?php + +/** + * ReadingSources + * + * Where a remote reading widget gets its data: installed apps, the container, the HTTP client and + * the cache. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/widgets/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\App\IAppManager; +use OCP\Http\Client\IClientService; +use OCP\ICacheFactory; +use Psr\Container\ContainerInterface; + +/** + * Where a remote reading widget gets its data: installed apps, the container, the HTTP client and + * the cache. + * + * @spec openspec/specs/widgets/spec.md + */ +class ReadingSources { + /** + * Constructor. + * + * @param IAppManager $appManager Detects whether `weather_status` is enabled. + * @param ContainerInterface $container App container used to optionally resolve `weather_status`'s forecast + * service (REQ-WEATHER-002 provider reuse). + * @param IClientService $clientService HTTP client factory for the fallback provider fetch. + * @param ICacheFactory $cacheFactory Backing factory for the distributed reading cache. + */ + public function __construct( + public readonly IAppManager $appManager, + public readonly ContainerInterface $container, + public readonly IClientService $clientService, + public readonly ICacheFactory $cacheFactory, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ReadsJsonCache.php b/lib/Service/ReadsJsonCache.php new file mode 100644 index 000000000..980c4e30b --- /dev/null +++ b/lib/Service/ReadsJsonCache.php @@ -0,0 +1,62 @@ +<?php + +/** + * ReadsJsonCache + * + * Reads JSON-encoded entries from a Nextcloud cache. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/live-data-tile-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\ICache; + +/** + * Decodes the JSON array stored under one cache key, for the services that + * cache widget readings. + * + * @spec openspec/specs/live-data-tile-widget/spec.md + */ +trait ReadsJsonCache { + /** + * Read and JSON-decode a cache entry. + * + * @param ICache|null $cache The cache, or null when the cache subsystem is unavailable. + * @param string $cacheKey The cache key. + * + * @return array<string,mixed>|null The decoded array, or null on a miss or a corrupt entry. + * + * @spec openspec/specs/live-data-tile-widget/spec.md + */ + private function readCache(?ICache $cache, string $cacheKey): ?array { + if ($cache === null) { + return null; + } + + $raw = $cache->get(key: $cacheKey); + if (is_string(value: $raw) === false) { + return null; + } + + $decoded = json_decode(json: $raw, associative: true); + if (is_array(value: $decoded) === true) { + return $decoded; + } + + return null; + }//end readCache() +}//end trait diff --git a/lib/Service/ReadsPlacementContent.php b/lib/Service/ReadsPlacementContent.php new file mode 100644 index 000000000..13f7023e9 --- /dev/null +++ b/lib/Service/ReadsPlacementContent.php @@ -0,0 +1,63 @@ +<?php + +/** + * ReadsPlacementContent + * + * Reads the widget config stored on a placement. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/live-data-tile-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Reads a placement's `content` config, with the legacy + * `style_config.content` slot as fallback for rows from before the column. + * + * @spec openspec/specs/live-data-tile-widget/spec.md + */ +trait ReadsPlacementContent { + /** + * Read the placement's widget config. + * + * @param object $placement The {@see \OCA\LaunchPad\Db\WidgetPlacement} entity. + * + * @return array<string,mixed> The config, or an empty array. + * + * @spec openspec/specs/live-data-tile-widget/spec.md + */ + private function readPlacementConfig(object $placement): array { + if (method_exists(object_or_class: $placement, method: 'getContentArray') === true) { + $content = $placement->getContentArray(); + if (is_array(value: $content) === true && $content !== []) { + return $content; + } + } + + if (method_exists(object_or_class: $placement, method: 'getStyleConfigArray') === true) { + $legacy = $placement->getStyleConfigArray(); + if (isset($legacy['content']) === true && is_array(value: $legacy['content']) === true) { + return $legacy['content']; + } + + if (is_array(value: $legacy) === true) { + return $legacy; + } + } + + return []; + }//end readPlacementConfig() +}//end trait diff --git a/lib/Service/RecurrenceResolver.php b/lib/Service/RecurrenceResolver.php new file mode 100644 index 000000000..812c5beac --- /dev/null +++ b/lib/Service/RecurrenceResolver.php @@ -0,0 +1,521 @@ +<?php + +/** + * RecurrenceResolver + * + * Computes the next fire moment of a scheduled export from its recurrence + * rule and its time zone (REQ-SCH-001). Four rule types: `weekly`, + * `monthly`, `daily` and `cron` (five fields). Times are wall-clock times in + * the export's time zone: a Monday 09:00 report stays at 09:00 across a DST + * change. A wall-clock time that falls in a spring-forward gap fires at the + * same distance past the gap (02:30 becomes 03:30), and one that occurs + * twice in an autumn fall-back fires once, at its first occurrence. A + * monthly day past the end of a month is clamped to that month's last day. + * + * The next moment is always strictly after the moment asked about, so a + * runner that was down fires a missed rule once, not once per missed slot. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeImmutable; +use DateTimeInterface; +use DateTimeZone; +use Exception; +use InvalidArgumentException; + +/** + * Next-run computation for scheduled-export recurrence rules. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-001-recurrence-editor-produces-deterministic-next-run-timestamps + * + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) A small cron parser and + * three calendar rules; splitting them apart would scatter one grammar. + */ +class RecurrenceResolver { + + /** + * The recurrence types. + * + * @var list<string> + */ + public const TYPES = ['weekly', 'monthly', 'daily', 'cron']; + + /** + * RFC 5545 BYDAY codes by ISO-8601 day number (1 = Monday). + * + * @var array<string, int> + */ + public const DAY_CODES = ['MO' => 1, 'TU' => 2, 'WE' => 3, 'TH' => 4, 'FR' => 5, 'SA' => 6, 'SU' => 7]; + + /** + * How many days ahead a rule is searched before it is called unsatisfiable. + * Eight years covers a cron rule such as "29 February on a Monday". + * + * @var int + */ + private const SEARCH_DAYS = 2930; + + /** + * Cron month and weekday names. + * + * @var array<string, int> + */ + private const CRON_NAMES = [ + 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, + 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12, + 'SUN' => 0, 'MON' => 1, 'TUE' => 2, 'WED' => 3, 'THU' => 4, 'FRI' => 5, 'SAT' => 6, + ]; + + /** + * The first fire of a recurrence strictly after a moment. + * + * @param array<string, mixed> $recurrence The rule: `type` plus its fields. + * @param string $timezone The IANA time zone it runs in. + * @param DateTimeInterface $after The moment to look past. + * + * @return DateTimeImmutable The next fire, in the rule's time zone. + * + * @throws InvalidArgumentException When the rule or the time zone is invalid, or never fires. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-001-recurrence-editor-produces-deterministic-next-run-timestamps + */ + public function nextRunAt(array $recurrence, string $timezone, DateTimeInterface $after): DateTimeImmutable { + $errors = $this->validate(recurrence: $recurrence); + if ($errors !== []) { + throw new InvalidArgumentException(implode(' ', $errors)); + } + + $zone = self::zone(timezone: $timezone); + $local = DateTimeImmutable::createFromInterface($after)->setTimezone($zone); + + return self::firstAfter(rule: $this->compile(recurrence: $recurrence), local: $local); + }//end nextRunAt() + + /** + * The first moment of a compiled rule after a local time, searched day by + * day for SEARCH_DAYS days in that time's zone. + * + * @param array<string, mixed> $rule The compiled recurrence. + * @param DateTimeImmutable $local The moment to search after, in the schedule's zone. + * + * @return DateTimeImmutable + * + * @throws InvalidArgumentException When the rule never fires. + */ + private static function firstAfter(array $rule, DateTimeImmutable $local): DateTimeImmutable { + $zone = $local->getTimezone(); + $day = $local->setTime(0, 0); + + for ($i = 0; $i < self::SEARCH_DAYS; $i++) { + $date = $day->modify('+' . $i . ' days'); + if (self::matchesDay(rule: $rule, date: $date) === false) { + continue; + } + + foreach ($rule['times'] as [$hour, $minute]) { + // Built from the wall-clock text, so PHP resolves a gap time + // forward; an ambiguous one is moved to its first occurrence. + $candidate = self::firstOccurrence( + candidate: new DateTimeImmutable($date->format('Y-m-d') . sprintf(' %02d:%02d:00', $hour, $minute), $zone), + zone: $zone + ); + if ($candidate > $local) { + return $candidate; + } + } + } + + throw new InvalidArgumentException('The recurrence never fires.'); + }//end firstAfter() + + /** + * The first occurrence of a wall-clock time that a fall-back makes occur + * twice. PHP resolves such a time to its second occurrence; the moment one + * offset-change earlier shows the same wall clock exactly when the time + * was ambiguous. + * + * @param DateTimeImmutable $candidate The time as PHP resolved it. + * @param DateTimeZone $zone The rule's time zone. + * + * @return DateTimeImmutable + */ + private static function firstOccurrence(DateTimeImmutable $candidate, DateTimeZone $zone): DateTimeImmutable { + $timestamp = $candidate->getTimestamp(); + $dayBefore = (new DateTimeImmutable('@' . ($timestamp - 86400)))->setTimezone($zone); + $shift = $dayBefore->getOffset() - $candidate->getOffset(); + if ($shift <= 0) { + return $candidate; + } + + $earlier = (new DateTimeImmutable('@' . ($timestamp - $shift)))->setTimezone($zone); + if ($earlier->format('Y-m-d H:i') === $candidate->format('Y-m-d H:i')) { + return $earlier; + } + + return $candidate; + }//end firstOccurrence() + + /** + * What is wrong with a recurrence rule, or nothing. + * + * @param array<string, mixed> $recurrence The rule. + * + * @return list<string> One sentence per problem. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-001-recurrence-editor-produces-deterministic-next-run-timestamps + */ + public function validate(array $recurrence): array { + $type = $recurrence['type'] ?? null; + if (in_array($type, self::TYPES, true) === false) { + return ['The recurrence type must be weekly, monthly, daily or cron.']; + } + + if ($type === 'cron') { + try { + self::parseCron(expression: (string)($recurrence['expression'] ?? '')); + } catch (InvalidArgumentException $e) { + return [$e->getMessage()]; + } + + return []; + } + + $errors = []; + if (self::timeOf(value: $recurrence['timeOfDay'] ?? null) === null) { + $errors[] = 'The time of day must be HH:MM.'; + } + + if ($type === 'weekly' && self::weekdays(value: $recurrence['daysOfWeek'] ?? null) === null) { + $errors[] = 'A weekly recurrence needs one or more days of the week (MO to SU).'; + } + + if ($type === 'monthly' && ($recurrence['lastDay'] ?? false) !== true) { + $day = $recurrence['dayOfMonth'] ?? null; + if (is_int($day) === false || $day < 1 || $day > 31) { + $errors[] = 'A monthly recurrence needs a day of the month from 1 to 31, or the last day.'; + } + } + + return $errors; + }//end validate() + + /** + * A rule as day filters and sorted wall-clock times. + * + * @param array<string, mixed> $recurrence A valid rule. + * + * @return array{type: string, times: list<array{int, int}>, weekdays?: list<int>, dayOfMonth?: int, lastDay?: bool, cron?: array<string, mixed>} + */ + private function compile(array $recurrence): array { + $type = (string)$recurrence['type']; + if ($type === 'cron') { + $cron = self::parseCron(expression: (string)$recurrence['expression']); + $times = []; + foreach ($cron['hours'] as $hour) { + foreach ($cron['minutes'] as $minute) { + $times[] = [$hour, $minute]; + } + } + + return ['type' => 'cron', 'times' => $times, 'cron' => $cron]; + } + + $rule = ['type' => $type, 'times' => [self::timeOf(value: $recurrence['timeOfDay'])]]; + if ($type === 'weekly') { + $rule['weekdays'] = self::weekdays(value: $recurrence['daysOfWeek']); + } + + if ($type === 'monthly') { + $rule['lastDay'] = (($recurrence['lastDay'] ?? false) === true); + $rule['dayOfMonth'] = (int)($recurrence['dayOfMonth'] ?? 31); + } + + return $rule; + }//end compile() + + /** + * Whether a rule fires on a local date. + * + * @param array<string, mixed> $rule The compiled rule. + * @param DateTimeImmutable $date The local date (at midnight). + * + * @return bool + */ + private static function matchesDay(array $rule, DateTimeImmutable $date): bool { + return match ($rule['type']) { + 'weekly' => in_array((int)$date->format('N'), $rule['weekdays'], true), + 'monthly' => (int)$date->format('j') === self::monthlyDay(rule: $rule, date: $date), + 'cron' => self::cronMatchesDay(cron: $rule['cron'], date: $date), + default => true, + }; + }//end matchesDay() + + /** + * The day of this date's month a monthly rule fires on: its day, + * clamped to the month's last day. + * + * @param array<string, mixed> $rule The compiled monthly rule. + * @param DateTimeImmutable $date A date in the month. + * + * @return int + */ + private static function monthlyDay(array $rule, DateTimeImmutable $date): int { + $last = (int)$date->format('t'); + if ($rule['lastDay'] === true) { + return $last; + } + + return min($rule['dayOfMonth'], $last); + }//end monthlyDay() + + /** + * Whether a cron rule's month, day-of-month and weekday fields match a + * date. As in cron, when both day fields are restricted either may match. + * + * @param array<string, mixed> $cron The parsed cron rule. + * @param DateTimeImmutable $date The local date. + * + * @return bool + */ + private static function cronMatchesDay(array $cron, DateTimeImmutable $date): bool { + if (in_array((int)$date->format('n'), $cron['months'], true) === false) { + return false; + } + + $domMatch = in_array((int)$date->format('j'), $cron['daysOfMonth'], true); + $dowMatch = in_array((int)$date->format('w'), $cron['daysOfWeek'], true); + if ($cron['domRestricted'] === true && $cron['dowRestricted'] === true) { + return $domMatch || $dowMatch; + } + + return $domMatch && $dowMatch; + }//end cronMatchesDay() + + /** + * A five-field cron expression as sets of allowed values. + * + * @param string $expression The expression, e.g. `0 9 * * 1`. + * + * @return array{ + * minutes: list<int>, hours: list<int>, daysOfMonth: list<int>, months: list<int>, + * daysOfWeek: list<int>, domRestricted: bool, dowRestricted: bool + * } + * + * @throws InvalidArgumentException When it is not a valid five-field expression. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-001-recurrence-editor-produces-deterministic-next-run-timestamps + */ + public static function parseCron(string $expression): array { + $fields = preg_split('/\s+/', trim($expression)); + if ($fields === false || count($fields) !== 5) { + throw new InvalidArgumentException('A cron expression has five fields: minute hour day-of-month month day-of-week.'); + } + + $daysOfWeek = array_values(array_unique(array_map( + static fn (int $day): int => $day % 7, + self::cronField(field: $fields[4], bounds: [0, 7]) + ))); + sort($daysOfWeek); + + return [ + 'minutes' => self::cronField(field: $fields[0], bounds: [0, 59]), + 'hours' => self::cronField(field: $fields[1], bounds: [0, 23]), + 'daysOfMonth' => self::cronField(field: $fields[2], bounds: [1, 31]), + 'months' => self::cronField(field: $fields[3], bounds: [1, 12]), + 'daysOfWeek' => $daysOfWeek, + 'domRestricted' => $fields[2] !== '*', + 'dowRestricted' => $fields[4] !== '*', + ]; + }//end parseCron() + + /** + * One cron field as its sorted allowed values: `*`, numbers or names, + * ranges `a-b`, steps `/n`, and comma lists of those. + * + * @param string $field The field. + * @param array{int, int} $bounds The lowest and the highest value allowed. + * + * @return list<int> + * + * @throws InvalidArgumentException When the field is malformed or out of range. + */ + private static function cronField(string $field, array $bounds): array { + [$min, $max] = $bounds; + $values = []; + foreach (explode(',', strtoupper($field)) as $part) { + if (preg_match('/^(\*|[0-9A-Z]+(?:-[0-9A-Z]+)?)(?:\/([0-9]+))?$/', $part, $match) !== 1) { + throw new InvalidArgumentException(sprintf('The cron field "%s" is not valid.', $field)); + } + + $step = (int)($match[2] ?? 1); + [$from, $to] = self::cronRange(range: $match[1], bounds: $bounds, stepped: isset($match[2])); + if ($step < 1 || $from < $min || $to > $max || $from > $to) { + throw new InvalidArgumentException(sprintf('The cron field "%s" is out of range.', $field)); + } + + for ($value = $from; $value <= $to; $value += $step) { + $values[$value] = $value; + } + } + + sort($values); + return $values; + }//end cronField() + + /** + * The bounds of one cron range: `*` is the whole field, `a` alone is a + * single value (or `a` to the end when stepped), `a-b` is a range. + * + * @param string $range The range part. + * @param array{int, int} $bounds The field's lowest and highest value. + * @param bool $stepped Whether a step follows. + * + * @return array{int, int} + */ + private static function cronRange(string $range, array $bounds, bool $stepped): array { + [$min, $max] = $bounds; + if ($range === '*') { + return [$min, $max]; + } + + $bounds = array_map(static fn (string $v): int => self::cronValue(value: $v), explode('-', $range)); + if (count($bounds) === 2) { + return [$bounds[0], $bounds[1]]; + } + + if ($stepped === true) { + return [$bounds[0], $max]; + } + + return [$bounds[0], $bounds[0]]; + }//end cronRange() + + /** + * One cron value: a number or a month or weekday name. + * + * @param string $value The value. + * + * @return int + * + * @throws InvalidArgumentException When it is neither. + */ + private static function cronValue(string $value): int { + if (ctype_digit($value) === true) { + return (int)$value; + } + + if (isset(self::CRON_NAMES[$value]) === true) { + return self::CRON_NAMES[$value]; + } + + throw new InvalidArgumentException(sprintf('The cron value "%s" is not valid.', $value)); + }//end cronValue() + + /** + * `HH:MM` as hour and minute, or null. + * + * @param mixed $value The time of day. + * + * @return array{int, int}|null + */ + private static function timeOf(mixed $value): ?array { + if (is_string($value) === false || preg_match('/^([01][0-9]|2[0-3]):([0-5][0-9])$/', $value, $match) !== 1) { + return null; + } + + return [(int)$match[1], (int)$match[2]]; + }//end timeOf() + + /** + * Days of the week as ISO day numbers, or null when none is valid. Takes + * BYDAY codes (`MO`), English names (`Monday`) or ISO numbers (1-7). + * + * @param mixed $value The days. + * + * @return list<int>|null + */ + private static function weekdays(mixed $value): ?array { + if (is_array($value) === false || $value === []) { + return null; + } + + $days = []; + foreach ($value as $day) { + $number = self::weekday(day: $day); + if ($number === null) { + return null; + } + + $days[$number] = $number; + } + + sort($days); + return $days; + }//end weekdays() + + /** + * One day of the week as its ISO number, or null. + * + * @param mixed $day A BYDAY code, an English name or an ISO number. + * + * @return int|null + */ + private static function weekday(mixed $day): ?int { + if (is_int($day) === true) { + if ($day >= 1 && $day <= 7) { + return $day; + } + + return null; + } + + if (is_string($day) === false || strlen($day) < 2) { + return null; + } + + $code = strtoupper(substr($day, 0, 2)); + $full = ['MO' => 'MONDAY', 'TU' => 'TUESDAY', 'WE' => 'WEDNESDAY', 'TH' => 'THURSDAY', 'FR' => 'FRIDAY', 'SA' => 'SATURDAY', 'SU' => 'SUNDAY']; + if (isset(self::DAY_CODES[$code]) === false) { + return null; + } + + if (strlen($day) > 2 && strtoupper($day) !== $full[$code]) { + return null; + } + + return self::DAY_CODES[$code]; + }//end weekday() + + /** + * A time zone by IANA name. + * + * @param string $timezone The name. + * + * @return DateTimeZone + * + * @throws InvalidArgumentException When it is not a time zone. + */ + private static function zone(string $timezone): DateTimeZone { + try { + return new DateTimeZone($timezone); + } catch (Exception) { + throw new InvalidArgumentException(sprintf('Unknown time zone "%s".', $timezone)); + } + }//end zone() +}//end class diff --git a/lib/Service/Reporting/AreaAggregation.php b/lib/Service/Reporting/AreaAggregation.php new file mode 100644 index 000000000..fa345b1cf --- /dev/null +++ b/lib/Service/Reporting/AreaAggregation.php @@ -0,0 +1,205 @@ +<?php + +/** + * AreaAggregation + * + * Counts and rates per area over a period, for objects that carry a location + * (REQ-DWMS-009). The area is read from a declared property; an object + * without one is counted in an explicit "no location" bucket and never + * dropped, so the areas plus that bucket always add up to the total. + * + * @category Service + * @package OCA\LaunchPad\Service\Reporting + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Reporting; + +use DateTimeImmutable; +use Exception; + +/** + * Groups object rows by an area property within a period. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ +class AreaAggregation { + + /** + * The key of the bucket for objects without an area. + */ + public const NO_LOCATION = 'no-location'; + + /** + * Count rows per area, with the rate of each against the period total. + * + * @param array<int, array<string, mixed>> $rows The objects, as arrays. + * @param string $areaProperty The property naming the area; a dot reads into an object (`address.district`). + * @param string|null $dateProperty The property dating each object; null counts every row. + * @param array{from?: ?DateTimeImmutable, until?: ?DateTimeImmutable} $period The first moment of the period + * (inclusive) and its end (exclusive); either absent leaves that side open. + * + * @return array{total: int, areas: list<array{area: string, count: int, rate: float}>, noLocation: array{count: int, rate: float}} + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-009-geographic-trend-reporting + */ + public function aggregate( + array $rows, + string $areaProperty, + ?string $dateProperty=null, + array $period=[] + ): array { + return $this->countAreas( + rows: $rows, + query: ['area' => $areaProperty, 'date' => $dateProperty, 'from' => ($period['from'] ?? null), 'until' => ($period['until'] ?? null)] + ); + }//end aggregate() + + /** + * Count rows per area for one query; see {@see self::aggregate()}. + * + * @param array<int, array<string, mixed>> $rows The objects, as arrays. + * @param array{area: string, date: ?string, from: ?DateTimeImmutable, until: ?DateTimeImmutable} $query The area property and the period. + * + * @return array{total: int, areas: list<array{area: string, count: int, rate: float}>, noLocation: array{count: int, rate: float}} + */ + private function countAreas(array $rows, array $query): array { + $counts = []; + $noLocation = 0; + $total = 0; + foreach ($rows as $row) { + if (is_array($row) === false || $this->inPeriod(row: $row, query: $query) === false) { + continue; + } + + $total++; + $area = $this->areaOf(row: $row, areaProperty: $query['area']); + if ($area === null) { + $noLocation++; + continue; + } + + $counts[$area] = (($counts[$area] ?? 0) + 1); + } + + ksort($counts, SORT_NATURAL | SORT_FLAG_CASE); + $areas = []; + foreach ($counts as $area => $count) { + $areas[] = ['area' => (string)$area, 'count' => $count, 'rate' => $this->rate(count: $count, total: $total)]; + } + + return [ + 'total' => $total, + 'areas' => $areas, + 'noLocation' => ['count' => $noLocation, 'rate' => $this->rate(count: $noLocation, total: $total)], + ]; + }//end countAreas() + + /** + * The area of one row, or null when it has none. + * + * @param array<string, mixed> $row The object. + * @param string $areaProperty The property path. + * + * @return string|null + */ + private function areaOf(array $row, string $areaProperty): ?string { + $value = $this->read(row: $row, path: $areaProperty); + if (is_string($value) === true) { + $value = trim($value); + if ($value === '') { + return null; + } + + return $value; + } + + if (is_int($value) === true) { + return (string)$value; + } + + return null; + }//end areaOf() + + /** + * Whether a row falls in the period; a row without a readable date falls outside a bounded one. + * + * @param array<string, mixed> $row The object. + * @param array{area: string, date: ?string, from: ?DateTimeImmutable, until: ?DateTimeImmutable} $query The period. + * + * @return bool + */ + private function inPeriod(array $row, array $query): bool { + $from = $query['from']; + $until = $query['until']; + if ($query['date'] === null || ($from === null && $until === null)) { + return true; + } + + $raw = $this->read(row: $row, path: $query['date']); + if (is_string($raw) === false || trim($raw) === '') { + return false; + } + + try { + $date = new DateTimeImmutable($raw); + } catch (Exception) { + return false; + } + + if ($from !== null && $date < $from) { + return false; + } + + return ($until === null || $date < $until); + }//end inPeriod() + + /** + * Read a dot path from a row. + * + * @param array<string, mixed> $row The object. + * @param string $path The path. + * + * @return mixed + */ + private function read(array $row, string $path): mixed { + $value = $row; + foreach (explode('.', $path) as $key) { + if (is_array($value) === false || array_key_exists($key, $value) === false) { + return null; + } + + $value = $value[$key]; + } + + return $value; + }//end read() + + /** + * A share of the total, to four decimals; zero when there is nothing to share. + * + * @param int $count The part. + * @param int $total The whole. + * + * @return float + */ + private function rate(int $count, int $total): float { + if ($total === 0) { + return 0.0; + } + + return round(($count / $total), 4); + }//end rate() +}//end class diff --git a/lib/Service/Reporting/ObjectRows.php b/lib/Service/Reporting/ObjectRows.php new file mode 100644 index 000000000..e36d718a0 --- /dev/null +++ b/lib/Service/Reporting/ObjectRows.php @@ -0,0 +1,182 @@ +<?php + +/** + * ObjectRows + * + * Reads objects from OpenRegister for the shipped reports, through its + * published object service, with the caller's own access applied. + * + * Launchpad runs without OpenRegister, so the service is looked up by name at + * call time and never imported: on an instance without it every read answers + * null, which a report shows as "unavailable" rather than as an error. + * + * @category Service + * @package OCA\LaunchPad\Service\Reporting + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Reporting; + +use JsonSerializable; +use Psr\Container\ContainerInterface; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Object reads for reports, null when OpenRegister or the schema is not there. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ +class ObjectRows { + + /** + * OpenRegister's published object service, held as a string so nothing loads it on an instance without OpenRegister. + */ + public const OBJECT_SERVICE = 'OCA\\OpenRegister\\Contract\\ObjectServiceInterface'; + + /** + * The most rows one report reads. + */ + public const MAX_ROWS = 5000; + + /** + * Constructor. + * + * @param ContainerInterface $container Resolves OpenRegister's object service at call time. + * @param LoggerInterface $logger Logs a read that failed. + */ + public function __construct( + private readonly ContainerInterface $container, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * The objects of one schema in one register, as arrays, or null when they cannot be read. + * + * @param string $register The register slug. + * @param string $schema The schema slug. + * @param array<string, mixed> $filters Property filters, passed to the search as they are. + * @param int $limit The most rows to read, capped at MAX_ROWS. + * + * @return list<array<string, mixed>>|null + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-003-reports-the-product-ships + */ + public function rows(string $register, string $schema, array $filters=[], int $limit=self::MAX_ROWS): ?array { + $query = array_merge( + $filters, + ['@self' => ['register' => $register, 'schema' => $schema], '_limit' => max(1, min($limit, self::MAX_ROWS))] + ); + + return $this->search(query: $query); + }//end rows() + + /** + * Run one search and turn the found objects into arrays; see {@see self::rows()}. + * + * @param array<string, mixed> $query The search query, with `@self` naming the register and schema. + * + * @return list<array<string, mixed>>|null + */ + private function search(array $query): ?array { + $register = $query['@self']['register']; + $schema = $query['@self']['schema']; + $service = $this->service(); + if ($service === null || $register === '' || $schema === '') { + return null; + } + + try { + $found = $service->searchObjects(query: $query); + } catch (Throwable $e) { + $this->logger->info( + message: 'launchpad.report.read_failed', + context: ['register' => $register, 'schema' => $schema, 'exception' => $e->getMessage()] + ); + return null; + } + + if (is_array($found) === false) { + return null; + } + + $rows = []; + foreach ($found as $object) { + $row = $this->toArray(object: $object); + if ($row !== null) { + $rows[] = $row; + } + } + + return $rows; + }//end search() + + /** + * Whether OpenRegister's object service is installed. + * + * @return bool + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-003-reports-the-product-ships + */ + public function isInstalled(): bool { + return ($this->service() !== null); + }//end isInstalled() + + /** + * The object service, or null without OpenRegister. + * + * @return object|null + */ + private function service(): ?object { + try { + if ($this->container->has(self::OBJECT_SERVICE) === false) { + return null; + } + + $service = $this->container->get(self::OBJECT_SERVICE); + } catch (Throwable) { + return null; + } + + if (is_object($service) === false) { + return null; + } + + return $service; + }//end service() + + /** + * One search result as an array. + * + * @param mixed $object An entity or an array. + * + * @return array<string, mixed>|null + */ + private function toArray(mixed $object): ?array { + if (is_array($object) === true) { + return $object; + } + + if ($object instanceof JsonSerializable) { + $data = $object->jsonSerialize(); + if (is_array($data) === true) { + return $data; + } + } + + return null; + }//end toArray() +}//end class diff --git a/lib/Service/Reporting/ReportDefinitions.php b/lib/Service/Reporting/ReportDefinitions.php new file mode 100644 index 000000000..e0be98cd0 --- /dev/null +++ b/lib/Service/Reporting/ReportDefinitions.php @@ -0,0 +1,246 @@ +<?php + +/** + * ReportDefinitions + * + * The report definitions launchpad ships (REQ-DWMS-003): read from + * lib/Settings/reports.json, checked against one shape, and handed out as + * plain arrays. Nothing writes them: a definition changes with the app. + * + * @category Service + * @package OCA\LaunchPad\Service\Reporting + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Reporting; + +use InvalidArgumentException; + +/** + * Loads and checks the shipped report definitions. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ +class ReportDefinitions { + + /** + * The aggregations a definition may run. + */ + public const KINDS = ['count-by', 'area']; + + /** + * The parameter types a definition may declare. + */ + public const PARAMETER_TYPES = ['date', 'string']; + + /** + * The shipped file. + */ + public const FILE = __DIR__ . '/../../Settings/reports.json'; + + /** + * The checked definitions, keyed by id, once read. + * + * @var array<string, array<string, mixed>>|null + */ + private ?array $definitions = null; + + /** + * Constructor. + * + * @param string $file The definitions file; the shipped one unless a test passes another. + */ + public function __construct( + private readonly string $file=self::FILE, + ) { + }//end __construct() + + /** + * Every definition, in file order. + * + * @return list<array<string, mixed>> + * + * @throws InvalidArgumentException When the file or a definition is malformed. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-003-reports-the-product-ships + */ + public function all(): array { + return array_values($this->load()); + }//end all() + + /** + * One definition, or null for an unknown id. + * + * @param string $id The report id. + * + * @return array<string, mixed>|null + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-003-reports-the-product-ships + */ + public function find(string $id): ?array { + return ($this->load()[$id] ?? null); + }//end find() + + /** + * Check one definition against the shape and return it normalised. + * + * @param mixed $definition The raw definition. + * + * @return array<string, mixed> The definition: id, title, description, source {register, schema}, filters, + * aggregation, parameters [{name, type, default}], rendering and requires + * {registers, schemas}. + * + * @throws InvalidArgumentException Naming the field that is wrong. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-003-reports-the-product-ships + */ + public function check(mixed $definition): array { + if (is_array($definition) === false) { + throw new InvalidArgumentException('A report definition must be an object.'); + } + + $id = $this->text(definition: $definition, key: 'id', label: 'report'); + $source = ($definition['source'] ?? null); + if (is_array($source) === false) { + throw new InvalidArgumentException("Report {$id}: source must name a register and a schema."); + } + + $register = $this->text(definition: $source, key: 'register', label: $id); + $schema = $this->text(definition: $source, key: 'schema', label: $id); + $aggregation = ($definition['aggregation'] ?? null); + if (is_array($aggregation) === false || in_array(($aggregation['kind'] ?? null), self::KINDS, true) === false) { + throw new InvalidArgumentException("Report {$id}: aggregation.kind must be one of " . implode(', ', self::KINDS) . '.'); + } + + $this->text(definition: $aggregation, key: 'property', label: $id); + + return [ + 'id' => $id, + 'title' => $this->text(definition: $definition, key: 'title', label: $id), + 'description' => $this->text(definition: $definition, key: 'description', label: $id), + 'source' => ['register' => $register, 'schema' => $schema], + 'filters' => $this->listOrMap(value: ($definition['filters'] ?? []), label: "Report {$id}: filters"), + 'aggregation' => $aggregation, + 'parameters' => $this->parameters(raw: ($definition['parameters'] ?? []), id: $id), + 'rendering' => $this->listOrMap(value: ($definition['rendering'] ?? []), label: "Report {$id}: rendering"), + 'requires' => ['registers' => [$register], 'schemas' => [$register . '/' . $schema]], + ]; + }//end check() + + /** + * Read and check the file once. + * + * @return array<string, array<string, mixed>> + * + * @throws InvalidArgumentException When the file or a definition is malformed. + */ + private function load(): array { + if ($this->definitions !== null) { + return $this->definitions; + } + + $raw = false; + if (is_file($this->file) === true && is_readable($this->file) === true) { + $raw = file_get_contents($this->file); + } + + $decoded = json_decode((string)$raw, true); + if (is_array($decoded) === false || is_array(($decoded['reports'] ?? null)) === false) { + throw new InvalidArgumentException('The report definitions file is missing or not valid JSON.'); + } + + $definitions = []; + foreach ($decoded['reports'] as $definition) { + $checked = $this->check(definition: $definition); + if (isset($definitions[$checked['id']]) === true) { + throw new InvalidArgumentException("Report {$checked['id']} is defined twice."); + } + + $definitions[$checked['id']] = $checked; + } + + $this->definitions = $definitions; + return $definitions; + }//end load() + + /** + * The declared parameters, checked. + * + * @param mixed $raw The raw list. + * @param string $id The report id. + * + * @return list<array{name: string, type: string, default: mixed}> + * + * @throws InvalidArgumentException Naming the parameter that is wrong. + */ + private function parameters(mixed $raw, string $id): array { + if (is_array($raw) === false || array_is_list($raw) === false) { + throw new InvalidArgumentException("Report {$id}: parameters must be a list."); + } + + $parameters = []; + foreach ($raw as $parameter) { + if (is_array($parameter) === false || in_array(($parameter['type'] ?? null), self::PARAMETER_TYPES, true) === false) { + throw new InvalidArgumentException("Report {$id}: every parameter needs a type of " . implode(', ', self::PARAMETER_TYPES) . '.'); + } + + $parameters[] = [ + 'name' => $this->text(definition: $parameter, key: 'name', label: $id), + 'type' => $parameter['type'], + 'default' => ($parameter['default'] ?? null), + ]; + } + + return $parameters; + }//end parameters() + + /** + * A required non-empty string field. + * + * @param array<string, mixed> $definition The object holding it. + * @param string $key The field. + * @param string $label The report, for the message. + * + * @return string + * + * @throws InvalidArgumentException When it is missing or empty. + */ + private function text(array $definition, string $key, string $label): string { + $value = ($definition[$key] ?? null); + if (is_string($value) === false || trim($value) === '') { + throw new InvalidArgumentException("Report {$label}: {$key} must be a non-empty string."); + } + + return trim($value); + }//end text() + + /** + * An object-shaped field, empty when absent. + * + * @param mixed $value The value. + * @param string $label The field, for the message. + * + * @return array<string, mixed> + * + * @throws InvalidArgumentException When it is not an object. + */ + private function listOrMap(mixed $value, string $label): array { + if (is_array($value) === false) { + throw new InvalidArgumentException("{$label} must be an object."); + } + + return $value; + }//end listOrMap() +}//end class diff --git a/lib/Service/Reporting/ReportLibrary.php b/lib/Service/Reporting/ReportLibrary.php new file mode 100644 index 000000000..a705d64c8 --- /dev/null +++ b/lib/Service/Reporting/ReportLibrary.php @@ -0,0 +1,361 @@ +<?php + +/** + * ReportLibrary + * + * The report gallery, a report run, and "save as dashboard" (REQ-DWMS-003). + * + * A report runs without anything being composed first: it reads its source + * through ObjectRows and aggregates in memory. A report whose register or + * schema this instance lacks is listed as unavailable with those names and, + * when opened, answers the same instead of an error. Saving a result creates + * an ordinary dashboard owned by the saver, holding one chart of the result. + * + * @category Service + * @package OCA\LaunchPad\Service\Reporting + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Reporting; + +use DateTimeImmutable; +use Exception; +use InvalidArgumentException; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Service\DashboardService; +use OCA\LaunchPad\Service\PlacementService; + +/** + * Lists, runs and saves the shipped reports. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ +class ReportLibrary { + + /** + * Constructor. + * + * @param ReportDefinitions $definitions The shipped definitions. + * @param ObjectRows $objects Reads a report's source. + * @param AreaAggregation $areas The `area` aggregation. + * @param DashboardService $dashboards Creates the saved dashboard. + * @param PlacementService $placements Places the result on it. + */ + public function __construct( + private readonly ReportDefinitions $definitions, + private readonly ObjectRows $objects, + private readonly AreaAggregation $areas, + private readonly DashboardService $dashboards, + private readonly PlacementService $placements, + ) { + }//end __construct() + + /** + * Every shipped report with whether it can run here and, if not, what is missing. + * + * @return list<array<string, mixed>> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-003-reports-the-product-ships + */ + public function gallery(): array { + $entries = []; + foreach ($this->definitions->all() as $definition) { + $missing = $this->missing(definition: $definition); + $entries[] = $this->summary(definition: $definition) + ['available' => ($missing === []), 'missing' => $missing]; + } + + return $entries; + }//end gallery() + + /** + * Run one report, or null for an unknown id. + * + * An unavailable report answers with `available: false` and the missing + * names, never an exception. + * + * @param string $id The report id. + * @param array<string, mixed> $parameters Values for the declared parameters; others are ignored. + * + * @return array<string, mixed>|null + * + * @throws InvalidArgumentException When a parameter value is not of its declared type. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-003-reports-the-product-ships + */ + public function run(string $id, array $parameters=[]): ?array { + $definition = $this->definitions->find(id: $id); + if ($definition === null) { + return null; + } + + $values = $this->parameterValues(definition: $definition, given: $parameters); + $rows = $this->objects->rows( + register: $definition['source']['register'], + schema: $definition['source']['schema'], + filters: $definition['filters'] + ); + $answer = $this->summary(definition: $definition) + ['parameterValues' => $values]; + if ($rows === null) { + return $answer + ['available' => false, 'missing' => $definition['requires']['schemas'], 'result' => null]; + } + + return $answer + ['available' => true, 'missing' => [], 'result' => $this->aggregate(definition: $definition, rows: $rows, values: $values)]; + }//end run() + + /** + * Save a report's result as an ordinary dashboard owned by the saver. + * + * @param string $id The report id. + * @param array<string, mixed> $parameters The parameter values. + * @param string $userId The saver, who owns the dashboard. + * + * @return Dashboard The new dashboard. + * + * @throws InvalidArgumentException When the report is unknown or cannot run here. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-003-reports-the-product-ships + */ + public function saveAsDashboard(string $id, array $parameters, string $userId): Dashboard { + return $this->dashboardFor(run: $this->runnable(id: $id, parameters: $parameters), userId: $userId); + }//end saveAsDashboard() + + /** + * A successful run of a report. + * + * @param string $id The report id. + * @param array<string, mixed> $parameters The parameter values. + * + * @return array<string, mixed> The run. + * + * @throws InvalidArgumentException When the report is unknown or cannot run here. + */ + private function runnable(string $id, array $parameters): array { + $run = $this->run(id: $id, parameters: $parameters); + if ($run === null) { + throw new InvalidArgumentException("There is no report {$id}."); + } + + if ($run['available'] !== true) { + throw new InvalidArgumentException("Report {$id} cannot run here: missing " . implode(', ', $run['missing']) . '.'); + } + + return $run; + }//end runnable() + + /** + * Create the dashboard a saved run shows: one chart of its result. + * + * @param array<string, mixed> $run A successful run. + * @param string $userId The saver, who owns the dashboard. + * + * @return Dashboard The new dashboard. + */ + private function dashboardFor(array $run, string $userId): Dashboard { + $dashboard = $this->dashboards->createDashboard(userId: $userId, name: $run['title'], options: ['description' => $run['description']]); + $this->placements->addWidget( + dashboardId: (int)$dashboard->getId(), + widgetId: 'chart', + layout: ['gridWidth' => 8, 'gridHeight' => 6, 'content' => $this->chartContent(run: $run)] + ); + + return $dashboard; + }//end dashboardFor() + + /** + * The chart a saved report shows: the result as series and categories, and where it came from. + * + * @param array<string, mixed> $run A successful run. + * + * @return array<string, mixed> + */ + private function chartContent(array $run): array { + $categories = []; + $data = []; + foreach ($run['result']['groups'] as $group) { + $categories[] = $group['label']; + $data[] = $group['count']; + } + + return [ + 'title' => $run['title'], + 'chartKind' => ($run['rendering']['chartKind'] ?? 'bar'), + 'props' => ['series' => [['name' => $run['title'], 'data' => $data]], 'categories' => $categories], + 'report' => ['id' => $run['id'], 'parameters' => $run['parameterValues'], 'savedTotal' => $run['result']['total']], + ]; + }//end chartContent() + + /** + * The names this instance lacks for a definition. + * + * @param array<string, mixed> $definition The definition. + * + * @return list<string> + */ + private function missing(array $definition): array { + $probe = $this->objects->rows( + register: $definition['source']['register'], + schema: $definition['source']['schema'], + limit: 1 + ); + if ($probe === null) { + return $definition['requires']['schemas']; + } + + return []; + }//end missing() + + /** + * Run the definition's aggregation; both kinds answer `groups` and `total`. + * + * @param array<string, mixed> $definition The definition. + * @param list<array<string, mixed>> $rows The source rows. + * @param array<string, mixed> $values The parameter values. + * + * @return array<string, mixed> + */ + private function aggregate(array $definition, array $rows, array $values): array { + $aggregation = $definition['aggregation']; + if ($aggregation['kind'] === 'area') { + $period = ['from' => $this->date(value: ($values['from'] ?? null)), 'until' => $this->date(value: ($values['until'] ?? null))]; + return $this->areaGroups(rows: $rows, aggregation: $aggregation + $period); + } + + return $this->countBy(rows: $rows, aggregation: $aggregation); + }//end aggregate() + + /** + * The `area` aggregation as groups: one per area, then the rows without one. + * + * @param list<array<string, mixed>> $rows The source rows. + * @param array<string, mixed> $aggregation The aggregation, with the period's `from` and `until`. + * + * @return array{total: int, groups: list<array<string, mixed>>} + */ + private function areaGroups(array $rows, array $aggregation): array { + $areas = $this->areas->aggregate( + rows: $rows, + areaProperty: $aggregation['property'], + dateProperty: ($aggregation['dateProperty'] ?? null), + period: ['from' => $aggregation['from'], 'until' => $aggregation['until']] + ); + $groups = array_map( + static fn (array $area): array => ['label' => $area['area'], 'count' => $area['count'], 'rate' => $area['rate']], + $areas['areas'] + ); + $groups[] = ['label' => AreaAggregation::NO_LOCATION, 'count' => $areas['noLocation']['count'], 'rate' => $areas['noLocation']['rate']]; + + return ['total' => $areas['total'], 'groups' => $groups]; + }//end areaGroups() + + /** + * Rows per value of one property, the largest group first. + * + * @param list<array<string, mixed>> $rows The rows. + * @param array<string, mixed> $aggregation The aggregation: its `property`, and `emptyLabel` for rows without a value. + * + * @return array{total: int, groups: list<array{label: string, count: int}>} + */ + private function countBy(array $rows, array $aggregation): array { + $property = $aggregation['property']; + $emptyLabel = (string)($aggregation['emptyLabel'] ?? '-'); + $counts = []; + foreach ($rows as $row) { + $value = ($row[$property] ?? null); + $label = $emptyLabel; + if ((is_string($value) === true && trim($value) !== '') || is_int($value) === true || is_bool($value) === true) { + $label = trim((string)$value); + if (is_bool($value) === true) { + $label = var_export($value, true); + } + } + + $counts[$label] = (($counts[$label] ?? 0) + 1); + } + + uksort( + $counts, + static function (string|int $first, string|int $second) use ($counts): int { + return [$counts[$second], (string)$first] <=> [$counts[$first], (string)$second]; + } + ); + $groups = []; + foreach ($counts as $label => $count) { + $groups[] = ['label' => (string)$label, 'count' => $count]; + } + + return ['total' => count($rows), 'groups' => $groups]; + }//end countBy() + + /** + * The parameter values: given ones of the declared type, defaults otherwise. + * + * @param array<string, mixed> $definition The definition. + * @param array<string, mixed> $given The values asked for. + * + * @return array<string, mixed> + * + * @throws InvalidArgumentException When a value is not of its type. + */ + private function parameterValues(array $definition, array $given): array { + $values = []; + foreach ($definition['parameters'] as $parameter) { + $value = ($given[$parameter['name']] ?? $parameter['default']); + if ($value !== null && (is_string($value) === false || ($parameter['type'] === 'date' && $this->date(value: $value) === null))) { + throw new InvalidArgumentException("Parameter {$parameter['name']} must be a {$parameter['type']}."); + } + + $values[$parameter['name']] = $value; + } + + return $values; + }//end parameterValues() + + /** + * A date parameter as a moment, or null. + * + * @param mixed $value The value. + * + * @return DateTimeImmutable|null + */ + private function date(mixed $value): ?DateTimeImmutable { + if (is_string($value) === false || trim($value) === '') { + return null; + } + + try { + return new DateTimeImmutable($value); + } catch (Exception) { + return null; + } + }//end date() + + /** + * What every listing shows of a definition. + * + * @param array<string, mixed> $definition The definition. + * + * @return array<string, mixed> + */ + private function summary(array $definition): array { + return [ + 'id' => $definition['id'], + 'title' => $definition['title'], + 'description' => $definition['description'], + 'parameters' => $definition['parameters'], + 'rendering' => $definition['rendering'], + 'requires' => $definition['requires'], + ]; + }//end summary() +}//end class diff --git a/lib/Service/RequestGuard.php b/lib/Service/RequestGuard.php new file mode 100644 index 000000000..dece0dac6 --- /dev/null +++ b/lib/Service/RequestGuard.php @@ -0,0 +1,139 @@ +<?php + +/** + * RequestGuard + * + * The administrator and action checks of the API controllers. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/admin-templates/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\OCS\OCSForbiddenException; +use OCP\IGroupManager; +use OCP\IUser; +use OCP\IUserSession; + +/** + * Checks the signed-in user of a request, and answers the refusal the API + * returns otherwise: 401 `Not authenticated` without a session user, 403 + * `Admin required` for a user outside the admin group, 403 `Forbidden` for + * a user the action is not granted to. + * + * @spec openspec/specs/admin-templates/spec.md + */ +class RequestGuard { + /** + * Constructor. + * + * @param IUserSession $userSession The session of the request. + * @param IGroupManager $groupManager Answers whether a user is an administrator. + * @param ActionAuthService $actionAuth Answers whether an action is granted to a user. + * + * @spec openspec/changes/archive/2026-11-19-responsehelper-instance-api/tasks.md#task-2 + */ + public function __construct( + public readonly IUserSession $userSession, + public readonly IGroupManager $groupManager, + private readonly ActionAuthService $actionAuth, + ) { + }//end __construct() + + /** + * The refusal for a caller who is not a signed-in administrator. + * + * @return JSONResponse|null The 401 or 403 to return, or null for an administrator. + * + * @spec openspec/specs/admin-templates/spec.md + */ + public function refusal(): ?JSONResponse { + $adminId = $this->adminId(); + if ($adminId instanceof JSONResponse) { + return $adminId; + } + + return null; + }//end refusal() + + /** + * The signed-in user, or the refusal. + * + * @return IUser|JSONResponse The user, or the 401 to return. + * + * @spec openspec/specs/admin-roles/spec.md + */ + public function sessionUser(): IUser|JSONResponse { + $user = $this->userSession->getUser(); + if ($user === null) { + return new JSONResponse( + data: ['error' => 'Not authenticated'], + statusCode: Http::STATUS_UNAUTHORIZED + ); + } + + return $user; + }//end sessionUser() + + /** + * The signed-in administrator's id, or the refusal. + * + * @return string|JSONResponse The user id, or the 401/403 to return. + * + * @spec openspec/specs/admin-templates/spec.md + */ + public function adminId(): string|JSONResponse { + $user = $this->sessionUser(); + if ($user instanceof JSONResponse) { + return $user; + } + + if ($this->groupManager->isAdmin(userId: $user->getUID()) === false) { + return new JSONResponse( + data: ['error' => 'Admin required'], + statusCode: Http::STATUS_FORBIDDEN + ); + } + + return $user->getUID(); + }//end adminId() + + /** + * The refusal for a caller the action is not granted to. + * + * @param string $action The action key, such as `dashboard-lock.acquire`. + * + * @return JSONResponse|null The 401 or 403 to return, or null when granted. + * + * @spec openspec/specs/admin-roles/spec.md + */ + public function actionRefusal(string $action): ?JSONResponse { + $user = $this->sessionUser(); + if ($user instanceof JSONResponse) { + return $user; + } + + try { + $this->actionAuth->requireAction($user, $action); + } catch (OCSForbiddenException) { + return new JSONResponse(['error' => 'Forbidden'], Http::STATUS_FORBIDDEN); + } + + return null; + }//end actionRefusal() +}//end class diff --git a/lib/Service/ResourceServeService.php b/lib/Service/ResourceServeService.php index f93f3d60a..04ebc236a 100644 --- a/lib/Service/ResourceServeService.php +++ b/lib/Service/ResourceServeService.php @@ -37,6 +37,7 @@ use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; +use OCA\LaunchPad\Kernel\Contracts\ResourceServeServiceInterface; use OCP\Files\IAppData; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFile; @@ -48,7 +49,7 @@ * * @spec openspec/changes/resource-serving/tasks.md */ -class ResourceServeService { +class ResourceServeService implements ResourceServeServiceInterface { /** * Map of file extension → Content-Type for the public serve route. * diff --git a/lib/Service/ResyncDiffer.php b/lib/Service/ResyncDiffer.php new file mode 100644 index 000000000..0a62b92fd --- /dev/null +++ b/lib/Service/ResyncDiffer.php @@ -0,0 +1,415 @@ +<?php + +/** + * ResyncDiffer + * + * The diff engine of a template re-sync: partitions one copy's placements + * against the template's (REQ-RESYNC-003, REQ-RESYNC-004) for the + * `overwrite`, `merge` (REQ-RESYNC-007) and `add_only` (REQ-RESYNC-006) + * strategies. It reads only; {@see TemplateResyncService} writes. + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\WidgetPlacement; + +/** + * Diffs a copy against its template. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + */ +class ResyncDiffer { + + /** + * Where a placement whose template placement is gone goes, per strategy + * (REQ-RESYNC-006). + * + * @var array<string, string> + */ + private const REMOVED_FROM_TEMPLATE = [ + TemplateResyncService::STRATEGY_OVERWRITE => 'toRemove', + TemplateResyncService::STRATEGY_MERGE => 'toRemove', + TemplateResyncService::STRATEGY_ADD_ONLY => 'toPreserve', + ]; + + /** + * The strategy this differ diffs for; see {@see self::bound()}. + * + * @var string + */ + private string $strategy = TemplateResyncService::STRATEGY_MERGE; + + /** + * The copy's grid column count; see {@see self::bound()}. + * + * @var integer + */ + private int $columns = 12; + + /** + * Constructor. + * + * @param PlacementLayout $layout Reads a placement's layout and its baseline. + * @param FreeSpotFinder $freeSpots Where an added widget goes under `add_only`. + */ + public function __construct( + private readonly PlacementLayout $layout = new PlacementLayout(), + private readonly FreeSpotFinder $freeSpots = new FreeSpotFinder(), + ) { + }//end __construct() + + /** + * A differ for one strategy and one copy's grid width. + * + * @param string $strategy `'overwrite'`, `'merge'` or `'add_only'`. + * @param int $columns The copy's grid column count. + * + * @return self The bound differ; this one is left as it was. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + */ + public function bound(string $strategy, int $columns): self { + $bound = clone $this; + // An unknown strategy diffs as `merge`, as it always did; the entry points reject it first. + $bound->strategy = TemplateResyncService::STRATEGY_MERGE; + if (isset(self::REMOVED_FROM_TEMPLATE[$strategy]) === true) { + $bound->strategy = $strategy; + } + + $bound->columns = max(1, $columns); + + return $bound; + }//end bound() + + /** + * Partition one copy's placements against the template's current + * placements (REQ-RESYNC-003, REQ-RESYNC-004). + * + * Matching is by {@see WidgetPlacement::getTemplatePlacementId()}: + * + * - Matched + fields differ → `toUpdate` (reconcile onto the copy). + * - Matched + fields equal → `toPreserve` (no-op, both strategies). + * - Template-origin but the + * matching template placement + * no longer exists → `toRemove` (admin deleted it from the + * template — both strategies). + * - No known origin + * (user-added) → `toPreserve` under `merge`, + * `toRemove` under `overwrite`. + * - A template placement with + * no matching copy placement → `toAdd` (new template placement, or + * a compulsory widget the user removed + * — restored either way). + * + * Compulsory widgets receive no special-case handling: they are + * ordinary template placements, so the `toAdd` (restore) / `toUpdate` + * (align position+flags) branches above already reconcile them under + * EVERY strategy, satisfying REQ-RESYNC-004 without a separate code + * path. + * + * Under `add_only` (REQ-RESYNC-006) a non-compulsory placement is never + * updated or removed, and each addition gets the first free spot on the + * copy (`addSpots`, by `toAdd` index). Under `merge` a placement the + * owner moved or resized keeps its layout (REQ-RESYNC-007). + * + * @param WidgetPlacement[] $templatePlacements The template's current + * placements. + * @param WidgetPlacement[] $copyPlacements The copy's current + * placements. + * + * @return array{ + * toAdd: WidgetPlacement[], + * addSpots: array<int, array{gridX:int,gridY:int,gridWidth:int,gridHeight:int}>, + * toUpdate: array<int, array{copy: WidgetPlacement, template: WidgetPlacement, keepLayout: bool}>, + * toRemove: WidgetPlacement[], + * toPreserve: WidgetPlacement[] + * } + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + */ + public function diff( + array $templatePlacements, + array $copyPlacements, + ): array { + $templateById = []; + foreach ($templatePlacements as $tp) { + $templateById[$tp->getId()] = $tp; + } + + $matchedTemplateIds = []; + $buckets = [ + 'toUpdate' => [], + 'toRemove' => [], + 'toPreserve' => [], + ]; + + foreach ($copyPlacements as $cp) { + $originId = $cp->getTemplatePlacementId(); + if ($originId !== null && isset($templateById[$originId]) === true) { + $matchedTemplateIds[$originId] = true; + } + + [$bucket, $entry] = $this->classifyCopyPlacement(copy: $cp, templateById: $templateById); + if ($bucket === null) { + // No known origin — a genuinely user-added placement. + $bucket = 'toPreserve'; + if ($this->strategy === TemplateResyncService::STRATEGY_OVERWRITE) { + $bucket = 'toRemove'; + } + } + + $buckets[$bucket][] = $entry; + }//end foreach + + $toAdd = $this->unmatchedTemplatePlacements( + templatePlacements: $templatePlacements, + matchedTemplateIds: $matchedTemplateIds + ); + + $addSpots = []; + if ($this->strategy === TemplateResyncService::STRATEGY_ADD_ONLY) { + $addSpots = $this->freeSpotsFor(toAdd: $toAdd, copyPlacements: $copyPlacements); + } + + return [ + 'toAdd' => $toAdd, + 'addSpots' => $addSpots, + 'toUpdate' => $buckets['toUpdate'], + 'toRemove' => $buckets['toRemove'], + 'toPreserve' => $buckets['toPreserve'], + ]; + }//end diff() + + /** + * The spot each added placement takes on a copy under `add_only`: its + * template spot when free, else the first free one, never over a widget + * already on the copy or added before it (REQ-RESYNC-006). + * + * @param WidgetPlacement[] $toAdd The template placements to add. + * @param WidgetPlacement[] $copyPlacements The copy's placements. + * + * @return array<int, array{gridX:int,gridY:int,gridWidth:int,gridHeight:int}> The spots, by `toAdd` index. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + */ + private function freeSpotsFor(array $toAdd, array $copyPlacements): array { + $occupied = array_map( + fn (WidgetPlacement $placement): array => $this->layout->rectOf(placement: $placement), + array_values($copyPlacements) + ); + + $spots = []; + foreach ($toAdd as $index => $templatePlacement) { + $spot = $this->freeSpots->place( + occupied: $occupied, + columns: $this->columns, + wanted: $this->layout->rectOf(placement: $templatePlacement) + ); + $spots[$index] = $spot; + $occupied[] = $spot; + } + + return $spots; + }//end freeSpotsFor() + + /** + * Classify one copy placement against the template placements it may + * originate from (REQ-RESYNC-003). + * + * A placement whose template origin still exists goes to `toUpdate` + * when its fields differ and to `toPreserve` when they are equal; one + * whose origin the admin has since deleted goes to `toRemove` under + * both strategies. A placement with no known origin is user-added: the + * bucket is null and the strategy decides. + * + * Under `add_only` nothing but a compulsory placement is touched: a + * removed or changed template placement stays as the copy has it + * (REQ-RESYNC-006). Under `merge` a non-compulsory placement the owner + * moved or resized keeps its layout and takes the template's other + * fields (REQ-RESYNC-007). + * + * @param WidgetPlacement $copy The copy placement. + * @param array<int, WidgetPlacement> $templateById The template placements by ID. + * + * @return array{0: string|null, 1: WidgetPlacement|array{copy: WidgetPlacement, template: WidgetPlacement, keepLayout: bool}} + * The bucket name (null for a user-added placement) and the entry to put in it. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + */ + private function classifyCopyPlacement(WidgetPlacement $copy, array $templateById): array { + $originId = $copy->getTemplatePlacementId(); + if ($originId === null) { + return [null, $copy]; + } + + if (isset($templateById[$originId]) === false) { + // The admin removed it from the template: gone, except under `add_only`. + return [self::REMOVED_FROM_TEMPLATE[$this->strategy], $copy]; + } + + return $this->classifyMatched(copy: $copy, template: $templateById[$originId]); + }//end classifyCopyPlacement() + + /** + * Classify a copy placement whose template placement still exists. + * + * @param WidgetPlacement $copy The copy placement. + * @param WidgetPlacement $template The template placement it came from. + * + * @return array{0: string, 1: WidgetPlacement|array{copy: WidgetPlacement, template: WidgetPlacement, keepLayout: bool}} + * The bucket name and the entry to put in it. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + */ + private function classifyMatched(WidgetPlacement $copy, WidgetPlacement $template): array { + $compulsory = ((int)$template->getIsCompulsory() === 1); + if ($this->strategy === TemplateResyncService::STRATEGY_ADD_ONLY && $compulsory === false) { + return ['toPreserve', $copy]; + } + + $ignore = array_flip($this->ownerLayoutFields(copy: $copy, template: $template)); + $differs = array_diff_key($this->templateFieldSnapshot(placement: $copy), $ignore) + !== array_diff_key($this->templateFieldSnapshot(placement: $template), $ignore); + + if ($differs === true) { + return [ + 'toUpdate', + [ + 'copy' => $copy, + 'template' => $template, + 'keepLayout' => ($ignore !== []), + ], + ]; + } + + return ['toPreserve', $copy]; + }//end classifyMatched() + + /** + * The grid fields a matched placement keeps from its owner, so the diff + * does not compare them: under `merge`, for a non-compulsory widget the owner moved or resized (REQ-RESYNC-007). + * + * @param WidgetPlacement $copy The copy's placement. + * @param WidgetPlacement $template The template placement it came from. + * + * @return array<int, string> The grid fields when the owner's position and size stay, else none. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it + */ + private function ownerLayoutFields(WidgetPlacement $copy, WidgetPlacement $template): array { + if ($this->strategy !== TemplateResyncService::STRATEGY_MERGE || (int)$template->getIsCompulsory() === 1) { + return []; + } + + if ($this->layout->ownerMoved(placement: $copy) === false) { + return []; + } + + return PlacementLayout::FIELDS; + }//end ownerLayoutFields() + + /** + * Template placements the copy has no counterpart for — i.e. the + * additions a re-sync must make. + * + * @param WidgetPlacement[] $templatePlacements The template's current placements. + * @param array<int, boolean> $matchedTemplateIds Set of template placement IDs + * already matched to a copy + * placement, keyed by ID. + * + * @return WidgetPlacement[] The unmatched template placements, in input order. + */ + private function unmatchedTemplatePlacements(array $templatePlacements, array $matchedTemplateIds): array { + $toAdd = []; + foreach ($templatePlacements as $tp) { + if (isset($matchedTemplateIds[$tp->getId()]) === false) { + $toAdd[] = $tp; + } + } + + return $toAdd; + }//end unmatchedTemplatePlacements() + + /** + * Whether a diff carries any mutation (add/update/remove). Used to + * decide `affectedCount` and to skip untouched copies entirely + * (REQ-RESYNC-005 idempotency). + * + * @param array<string, mixed> $diff The diff computed by + * {@see self::diff()}. + * + * @return bool True when applying the diff would change the copy. + * + * @spec openspec/specs/admin-templates/spec.md#requirement-req-resync-005-re-sync-is-idempotent-audited-async-capable-and-notifies-users + */ + public function hasChanges(array $diff): bool { + return count($diff['toAdd']) > 0 + || count($diff['toUpdate']) > 0 + || count($diff['toRemove']) > 0; + }//end hasChanges() + + /** + * The reconcilable field snapshot compared for equality and applied + * on update. Kept as one array so the equality check + * (the diff) and the field-copy + * (applyTemplateFields / cloneTemplatePlacementInto) + * can never silently drift apart (the field-copy lives in + * {@see TemplateResyncService}). + * + * @param WidgetPlacement $placement The placement to snapshot. + * + * @return array<string, mixed> The comparable field values. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + */ + private function templateFieldSnapshot(WidgetPlacement $placement): array { + return [ + 'widgetId' => $placement->getWidgetId(), + 'gridX' => $placement->getGridX(), + 'gridY' => $placement->getGridY(), + 'gridWidth' => $placement->getGridWidth(), + 'gridHeight' => $placement->getGridHeight(), + 'isCompulsory' => $placement->getIsCompulsory(), + 'isVisible' => $placement->getIsVisible(), + 'styleConfig' => $placement->getStyleConfig(), + 'customTitle' => $placement->getCustomTitle(), + 'customIcon' => $placement->getCustomIcon(), + 'showTitle' => $placement->getShowTitle(), + 'sortOrder' => $placement->getSortOrder(), + 'content' => $placement->getContent(), + 'tileType' => $placement->getTileType(), + 'tileTitle' => $placement->getTileTitle(), + 'tileIcon' => $placement->getTileIcon(), + 'tileIconType' => $placement->getTileIconType(), + 'tileBackgroundColor' => $placement->getTileBackgroundColor(), + 'tileTextColor' => $placement->getTileTextColor(), + 'tileLinkType' => $placement->getTileLinkType(), + 'tileLinkValue' => $placement->getTileLinkValue(), + 'requiresAcknowledgement' => $placement->getRequiresAcknowledgement(), + 'acknowledgementPrompt' => $placement->getAcknowledgementPrompt(), + 'acknowledgementDeadline' => $placement->getAcknowledgementDeadline(), + 'reacknowledgeOnChange' => $placement->getReacknowledgeOnChange(), + 'acknowledgementContentVersion' => $placement->getAcknowledgementContentVersion(), + 'announcementKey' => $placement->getAnnouncementKey(), + 'ruleMatch' => $placement->getRuleMatch(), + ]; + }//end templateFieldSnapshot() +}//end class diff --git a/lib/Service/ResyncFollowUps.php b/lib/Service/ResyncFollowUps.php new file mode 100644 index 000000000..25a370f04 --- /dev/null +++ b/lib/Service/ResyncFollowUps.php @@ -0,0 +1,101 @@ +<?php + +/** + * ResyncFollowUps + * + * What a template resync does to a copy after it changed it: drop the + * personal-layer entries of removed placements, and write the copy's + * version by the template ("Template {name}", "Updated from the template"). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; +use OCP\IL10N; + +/** + * The follow-ups of a resync on one changed copy. + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + */ +class ResyncFollowUps { + + /** + * Longest author a version row stores, in characters. + * + * @var integer + */ + public const MAX_AUTHOR_LENGTH = 64; + + /** + * Constructor + * + * @param PersonalLayerService $personalLayers Drops personal-layer entries for removed placements + * (REQ-DWMS-001). + * @param IL10N $l10n The app's translations for the author and the note. + * @param DashboardVersionService|null $versions Writes the version a changed copy gets; null writes none. + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + */ + public function __construct( + public readonly PersonalLayerService $personalLayers, + private readonly IL10N $l10n, + private readonly ?DashboardVersionService $versions=null, + ) { + }//end __construct() + + /** + * Write the version a re-synced copy gets: its author is the template + * and its note "Updated from the template", instead of the administrator + * who ran the resync and a list of widget changes. + * + * @param Dashboard $copy The copy that took the change. + * @param string $templateName The template's name. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + */ + public function recordTemplateVersion(Dashboard $copy, string $templateName): void { + if ($this->versions === null) { + return; + } + + $this->versions->captureSnapshot( + dashboard: $copy, + createdBy: $this->templateAuthor(templateName: $templateName), + options: ['note' => $this->l10n->t('Updated from the template'), 'explicit' => true] + ); + }//end recordTemplateVersion() + + /** + * The author a template-written version carries, cut to the length the + * version table stores. + * + * @param string $templateName The template's name. + * + * @return string "Template {name}". + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + */ + public function templateAuthor(string $templateName): string { + $author = $this->l10n->t('Template %s', [trim($templateName)]); + + return rtrim(mb_substr($author, 0, self::MAX_AUTHOR_LENGTH)); + }//end templateAuthor() +}//end class diff --git a/lib/Service/ResyncStores.php b/lib/Service/ResyncStores.php new file mode 100644 index 000000000..03fd7e873 --- /dev/null +++ b/lib/Service/ResyncStores.php @@ -0,0 +1,55 @@ +<?php + +/** + * ResyncStores + * + * Where a template resync writes: the dashboard and placement mappers, the database and the job + * list. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCP\BackgroundJob\IJobList; +use OCP\IDBConnection; + +/** + * Where a template resync writes: the dashboard and placement mappers, the database and the job + * list. + * + * @spec openspec/specs/dashboards/spec.md + */ +class ResyncStores { + /** + * Constructor. + * + * @param DashboardMapper $dashboardMapper Dashboard mapper. + * @param WidgetPlacementMapper $placementMapper Widget placement mapper. + * @param IDBConnection $db DB connection — used for the per-copy transaction boundary. + * @param IJobList $jobList Background job list — used to enqueue {@see TemplateResyncJob} for + * large target groups. + */ + public function __construct( + public readonly DashboardMapper $dashboardMapper, + public readonly WidgetPlacementMapper $placementMapper, + public readonly IDBConnection $db, + public readonly IJobList $jobList, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/RetryAttempt.php b/lib/Service/RetryAttempt.php new file mode 100644 index 000000000..dd0247f04 --- /dev/null +++ b/lib/Service/RetryAttempt.php @@ -0,0 +1,52 @@ +<?php + +/** + * One delivery attempt of a scheduled export, as the retry handler weighs it. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeInterface; + +/** + * Whether an attempt delivered, when, under which policy, and why it failed. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ +final class RetryAttempt { + + /** + * Constructor. + * + * @param bool $succeeded Whether this attempt delivered. + * @param DateTimeInterface $now The moment of the attempt. + * @param array<string, mixed> $policy A policy from `RetryHandler::policy()`. + * @param string|null $error Why the attempt failed. + * @param (callable(int, int): int)|null $random The jitter source. + * + * @return void + */ + public function __construct( + public readonly bool $succeeded, + public readonly DateTimeInterface $now, + public readonly array $policy, + public readonly ?string $error = null, + public readonly mixed $random = null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/RetryHandler.php b/lib/Service/RetryHandler.php new file mode 100644 index 000000000..65310674b --- /dev/null +++ b/lib/Service/RetryHandler.php @@ -0,0 +1,234 @@ +<?php + +/** + * RetryHandler + * + * The retry policy of scheduled-export deliveries (REQ-SCH-006): one + * delivery is one recipient on one channel, and each retries on its own. + * A failed attempt waits `initialBackoffSeconds`, doubling on every further + * failure up to `maxBackoffSeconds`, optionally with jitter; after + * `maxAttempts` the delivery is `failed-permanent`. A run rolls up to + * `success` only when every delivery succeeded, however many attempts that + * took. + * + * This class decides; it does not send. The dispatcher records each + * attempt's outcome through `afterAttempt()` and the runner picks up + * deliveries whose `nextAttemptAt` has passed. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeImmutable; +use DateTimeInterface; + +/** + * Backoff, attempt bookkeeping and the run roll-up for export deliveries. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ +class RetryHandler { + + /** + * The policy a recipient without its own override gets. + * + * @var array{maxAttempts: int, initialBackoffSeconds: int, maxBackoffSeconds: int, jitter: bool} + */ + public const DEFAULT_POLICY = [ + 'maxAttempts' => 5, + 'initialBackoffSeconds' => 60, + 'maxBackoffSeconds' => 3600, + 'jitter' => true, + ]; + + public const STATUS_PENDING = 'pending'; + + public const STATUS_RETRYING = 'retrying'; + + public const STATUS_SUCCESS = 'success'; + + public const STATUS_FAILED_PERMANENT = 'failed-permanent'; + + /** + * A recipient's policy: its override on top of the default. Values of the + * wrong type or out of range keep the default. + * + * @param array<string, mixed>|null $override The recipient's `retryPolicy`. + * + * @return array{maxAttempts: int, initialBackoffSeconds: int, maxBackoffSeconds: int, jitter: bool} + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function policy(?array $override): array { + $policy = self::DEFAULT_POLICY; + foreach (['maxAttempts', 'initialBackoffSeconds', 'maxBackoffSeconds'] as $key) { + if (is_int($override[$key] ?? null) === true && $override[$key] >= 1) { + $policy[$key] = $override[$key]; + } + } + + if (is_bool($override['jitter'] ?? null) === true) { + $policy['jitter'] = $override['jitter']; + } + + $policy['maxBackoffSeconds'] = max($policy['maxBackoffSeconds'], $policy['initialBackoffSeconds']); + return $policy; + }//end policy() + + /** + * How long to wait after a delivery's n-th failed attempt: the initial + * backoff doubled per earlier failure, capped at the maximum. With + * jitter, a random wait between half of that and all of it. + * + * @param int $failedAttempts The attempts that failed so far (1 after the first). + * @param array<string, mixed> $policy A policy from `policy()`. + * @param (callable(int, int): int)|null $random Picks an integer in [min, max]; `random_int` by default. + * + * @return int Seconds. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function backoffSeconds(int $failedAttempts, array $policy, ?callable $random = null): int { + $initial = (int)$policy['initialBackoffSeconds']; + $cap = (int)$policy['maxBackoffSeconds']; + $delay = $initial; + for ($i = 1; $i < max(1, $failedAttempts) && $delay < $cap; $i++) { + $delay *= 2; + } + + $delay = min($delay, $cap); + if ($policy['jitter'] !== true) { + return $delay; + } + + $random = $random ?? 'random_int'; + return (int)$random(intdiv($delay, 2), $delay); + }//end backoffSeconds() + + /** + * A delivery after one more attempt: counted, and either delivered, + * waiting for its next attempt, or failed for good once the policy's + * attempts are spent. + * + * @param array<string, mixed> $delivery The delivery as the run-row holds it. + * @param RetryAttempt $attempt Whether it delivered, when, under which policy, and why it failed. + * + * @return array<string, mixed> The updated delivery. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function afterAttempt(array $delivery, RetryAttempt $attempt): array { + $attempts = (int)($delivery['attemptCount'] ?? 0) + 1; + $delivery['attemptCount'] = $attempts; + $attemptedAt = DateTimeImmutable::createFromInterface($attempt->now); + + if ($attempt->succeeded === true) { + $delivery['status'] = self::STATUS_SUCCESS; + $delivery['deliveredAt'] = $attemptedAt->format(DateTimeInterface::ATOM); + $delivery['nextAttemptAt'] = null; + $delivery['error'] = null; + return $delivery; + } + + $delivery['error'] = $attempt->error; + if ($attempts >= (int)$attempt->policy['maxAttempts']) { + $delivery['status'] = self::STATUS_FAILED_PERMANENT; + $delivery['nextAttemptAt'] = null; + return $delivery; + } + + $wait = $this->backoffSeconds(failedAttempts: $attempts, policy: $attempt->policy, random: $attempt->random); + $delivery['status'] = self::STATUS_RETRYING; + $delivery['nextAttemptAt'] = $attemptedAt->modify('+' . $wait . ' seconds')->format(DateTimeInterface::ATOM); + return $delivery; + }//end afterAttempt() + + /** + * Whether a delivery is waiting for an attempt that is due now. + * + * @param array<string, mixed> $delivery The delivery. + * @param DateTimeInterface $now The moment asked about. + * + * @return bool + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function isDue(array $delivery, DateTimeInterface $now): bool { + if (($delivery['status'] ?? null) !== self::STATUS_RETRYING) { + return false; + } + + $next = DateTimeImmutable::createFromFormat(DateTimeInterface::ATOM, (string)($delivery['nextAttemptAt'] ?? '')); + return $next !== false && $next <= $now; + }//end isDue() + + /** + * A manual "Retry" of a delivery that failed for good: a fresh round of + * attempts under the same policy, due at once. Any other delivery is + * returned unchanged. + * + * @param array<string, mixed> $delivery The delivery. + * @param DateTimeInterface $now The moment of the retry. + * + * @return array<string, mixed> + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function rearm(array $delivery, DateTimeInterface $now): array { + if (($delivery['status'] ?? null) !== self::STATUS_FAILED_PERMANENT) { + return $delivery; + } + + $delivery['status'] = self::STATUS_RETRYING; + $delivery['attemptCount'] = 0; + $delivery['nextAttemptAt'] = DateTimeImmutable::createFromInterface($now)->format(DateTimeInterface::ATOM); + return $delivery; + }//end rearm() + + /** + * A run's status from its deliveries: `running` while any is pending or + * retrying, `success` when all succeeded, `failed` when none did, and + * `partial` otherwise. A run without deliveries failed. + * + * @param list<array<string, mixed>> $deliveries The run's deliveries. + * + * @return string `running`, `success`, `partial` or `failed`. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function rollUp(array $deliveries): string { + $statuses = array_map(static fn (array $delivery): string => (string)($delivery['status'] ?? self::STATUS_PENDING), $deliveries); + if ($statuses === []) { + return 'failed'; + } + + if (array_intersect($statuses, [self::STATUS_PENDING, self::STATUS_RETRYING]) !== []) { + return 'running'; + } + + $succeeded = count(array_keys($statuses, self::STATUS_SUCCESS, true)); + if ($succeeded === count($statuses)) { + return 'success'; + } + + if ($succeeded === 0) { + return 'failed'; + } + + return 'partial'; + }//end rollUp() +}//end class diff --git a/lib/Service/RoleFeaturePermissionService.php b/lib/Service/RoleFeaturePermissionService.php index c5550eca3..86b29c9ab 100644 --- a/lib/Service/RoleFeaturePermissionService.php +++ b/lib/Service/RoleFeaturePermissionService.php @@ -624,6 +624,40 @@ public function isWidgetAllowed(string $userId, string $widgetId): bool { return in_array(needle: $widgetId, haystack: $allowed, strict: true); }//end isWidgetAllowed() + /** + * Mark the placements whose widget the user's role does not permit as + * hidden (`isVisible` 0), keeping them, so a placement made under an + * earlier role comes back when the role does (REQ-RFP-003, REQ-RFP-004). + * + * A tile placement (`tile-<uniqid>`) counts as the `tile` widget type. + * + * @param array<int, array<string, mixed>> $placements The serialised placements. + * @param string $userId The user the dashboard renders for. + * + * @return array<int, array<string, mixed>> The placements, the unpermitted ones hidden. + * + * @spec openspec/specs/role-feature-permissions/spec.md + */ + public function hideUnpermittedPlacements(array $placements, string $userId): array { + $allowed = $this->getAllowedWidgetIds(userId: $userId); + if ($allowed === null) { + return $placements; + } + + foreach ($placements as $index => $placement) { + $widgetId = (string)($placement['widgetId'] ?? ''); + if (str_starts_with(haystack: $widgetId, needle: 'tile-') === true) { + $widgetId = 'tile'; + } + + if ($widgetId !== '' && in_array(needle: $widgetId, haystack: $allowed, strict: true) === false) { + $placements[$index]['isVisible'] = 0; + } + } + + return $placements; + }//end hideUnpermittedPlacements() + /** * Whether this user has RoleLayoutDefault rows to be seeded from. * diff --git a/lib/Service/RoleService.php b/lib/Service/RoleService.php index 15b9d53c5..ca9d7d382 100644 --- a/lib/Service/RoleService.php +++ b/lib/Service/RoleService.php @@ -301,7 +301,8 @@ public function assignRole( $assignment->setGroupId($groupId); $assignment->setRole($role); $assignment->setAssignedBy($assignedBy); - $assignment->setAssignedAt((new DateTime())->format('c')); + // The assigned_at column is a DATETIME: MySQL and MariaDB refuse ISO 8601 with an offset. + $assignment->setAssignedAt((new DateTime())->format('Y-m-d H:i:s')); // phpcs:enable CustomSniffs.Functions.NamedParameters.RequireNamedParameters return $this->mapper->insert(entity: $assignment); diff --git a/lib/Service/RuleEvaluatorService.php b/lib/Service/RuleEvaluatorService.php index 4dc4f355e..e66ae92f2 100644 --- a/lib/Service/RuleEvaluatorService.php +++ b/lib/Service/RuleEvaluatorService.php @@ -183,6 +183,11 @@ private function evaluateTimeRule( $startTime = $config['startTime'] ?? '00:00'; $endTime = $config['endTime'] ?? '23:59'; + // A window whose start lies after its end wraps around midnight. + if ($startTime > $endTime) { + return $currentTime >= $startTime || $currentTime <= $endTime; + } + return $currentTime >= $startTime && $currentTime <= $endTime; }//end evaluateTimeRule() diff --git a/lib/Service/RuleSetContext.php b/lib/Service/RuleSetContext.php new file mode 100644 index 000000000..5e4ead1df --- /dev/null +++ b/lib/Service/RuleSetContext.php @@ -0,0 +1,71 @@ +<?php + +/** + * RuleSetContext + * + * The context a rule set is evaluated in: the groups to test `group` rules + * against (null: the user's own), the moment to test `time` / `date` rules + * against (null: now), and how the include rules combine (`any` or `all`, + * REQ-VIS-014). Render time uses the defaults; the preview fills it in. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeInterface; +use OCA\LaunchPad\Db\WidgetPlacement; + +/** + * Groups, moment and match mode for one evaluation of a rule set. + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + */ +final class RuleSetContext { + /** + * The groups to test `group` rules against; null for the user's own. + * + * @var string[]|null + */ + public readonly ?array $groups; + + /** + * The moment to test `time` / `date` rules against; null for now. + * + * @var DateTimeInterface|null + */ + public readonly ?DateTimeInterface $now; + + /** + * `any` (one include rule is enough) or `all`. + * + * @var string + */ + public readonly string $match; + + /** + * Constructor + * + * @param array<string, mixed> $options `groups` (string[]|null), `now` + * (DateTimeInterface|null) and `match` + * (string); each optional. + */ + public function __construct(array $options = []) { + $this->groups = ($options['groups'] ?? null); + $this->now = ($options['now'] ?? null); + $this->match = ($options['match'] ?? WidgetPlacement::RULE_MATCH_ANY); + }//end __construct() +}//end class diff --git a/lib/Service/ScheduledExport/AuditLog.php b/lib/Service/ScheduledExport/AuditLog.php new file mode 100644 index 000000000..fcf92d123 --- /dev/null +++ b/lib/Service/ScheduledExport/AuditLog.php @@ -0,0 +1,233 @@ +<?php + +/** + * AuditLog + * + * The `scheduled_export_run` rows (tasks.md task 7, REQ-SCH-008): one per + * fire, manual or scheduled, holding what was rendered (format, size, + * sha256, path) and how each delivery went (channel, attempts, status, + * provider message id, error). Rows are OpenRegister objects, so the + * standard permission model and retention apply to them. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use DateTimeInterface; +use OCA\LaunchPad\Service\RetryHandler; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Security\ISecureRandom; + +/** + * Writes and reads the audit row of each fire. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-008-audit-row-per-run-with-hash-and-delivery-outcome + */ +class AuditLog { + + /** + * Constructor. + * + * @param ExportObjectStore $store The OpenRegister object store. + * @param RetryHandler $retry Rolls the deliveries up into the run status. + * @param ITimeFactory $time The clock. + * @param ISecureRandom $random Makes the correlation id. + */ + public function __construct( + private readonly ExportObjectStore $store, + private readonly RetryHandler $retry, + private readonly ITimeFactory $time, + private readonly ISecureRandom $random, + ) { + }//end __construct() + + /** + * Open the row of a fire, `running`, before anything is rendered. + * + * @param array<string, mixed> $export The export being fired. + * @param FireTrigger $trigger Who or what fired it. + * + * @return array<string, mixed> The saved row. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-7 + */ + public function start(array $export, FireTrigger $trigger): array { + $row = $this->fresh(export: $export, trigger: $trigger) + ['status' => 'running']; + return $this->store->save(schema: ExportObjectStore::SCHEMA_RUN, data: $row); + }//end start() + + /** + * Close a row with its artefacts and deliveries; the status is the roll-up + * of the deliveries, and `finishedAt` is set once nothing is left to retry. + * + * @param array<string, mixed> $run The row from start(). + * @param list<array<string, mixed>> $artefacts `{format, sizeBytes, sha256, storagePath}` per artefact. + * @param list<array<string, mixed>> $deliveries One entry per recipient delivery. + * + * @return array<string, mixed> The saved row. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-7 + */ + public function record(array $run, array $artefacts, array $deliveries): array { + $run['renderArtefacts'] = array_values($artefacts); + $run['deliveries'] = array_values($deliveries); + $run['status'] = $this->retry->rollUp(deliveries: $run['deliveries']); + if ($run['status'] !== 'running') { + $run['finishedAt'] = $this->now(); + } + + return $this->store->save(schema: ExportObjectStore::SCHEMA_RUN, data: $run); + }//end record() + + /** + * Write the row of a fire that was skipped without rendering (REQ-SCH-002). + * + * @param array<string, mixed> $export The export. + * @param FireTrigger $trigger Who or what fired it. + * @param array{status: string, reason: string} $skip The row's `status` (`partial` for an + * overlap, `failed` for a blocked creator) + * and why it was skipped. + * + * @return array<string, mixed> The saved row. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-002-background-runner-fires-schedules-without-an-active-browser-session + */ + public function skipped(array $export, FireTrigger $trigger, array $skip): array { + $row = $this->fresh(export: $export, trigger: $trigger) + [ + 'status' => $skip['status'], + 'finishedAt' => $this->now(), + 'skipReason' => $skip['reason'], + 'renderArtefacts' => [], + 'deliveries' => [], + ]; + + return $this->store->save(schema: ExportObjectStore::SCHEMA_RUN, data: $row); + }//end skipped() + + /** + * The rows of one export, newest first. + * + * @param string $exportId The export uuid. + * + * @return list<array<string, mixed>> + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-7 + */ + public function runsOf(string $exportId): array { + $runs = $this->store->findAll(schema: ExportObjectStore::SCHEMA_RUN, filters: ['exportId' => $exportId]); + $runs = array_values(array_filter($runs, static fn (array $run): bool => ($run['exportId'] ?? null) === $exportId)); + usort($runs, static fn (array $a, array $b): int => strcmp((string)($b['startedAt'] ?? ''), (string)($a['startedAt'] ?? ''))); + + return $runs; + }//end runsOf() + + /** + * Every row, for the janitor and the retry sweep. + * + * @return list<array<string, mixed>> + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-7 + */ + public function allRuns(): array { + return $this->store->findAll(schema: ExportObjectStore::SCHEMA_RUN); + }//end allRuns() + + /** + * One row of an export, or null when it is not a row of that export. + * + * @param string $exportId The export uuid. + * @param string $runId The row uuid. + * + * @return array<string, mixed>|null + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-7 + */ + public function runOf(string $exportId, string $runId): ?array { + $run = $this->store->find(schema: ExportObjectStore::SCHEMA_RUN, uuid: $runId); + if ($run === null || ($run['exportId'] ?? null) !== $exportId) { + return null; + } + + return $run; + }//end runOf() + + /** + * Save a row as it is (the janitor nulling paths, the retry sweep). + * + * @param array<string, mixed> $run The row. + * + * @return array<string, mixed> + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-7 + */ + public function update(array $run): array { + return $this->store->save(schema: ExportObjectStore::SCHEMA_RUN, data: $run); + }//end update() + + /** + * Delete a row (the janitor, after `keepAuditForDays`). + * + * @param string $runId The row uuid. + * + * @return bool + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-7 + */ + public function delete(string $runId): bool { + return $this->store->delete(uuid: $runId); + }//end delete() + + /** + * The fields every new row starts with. + * + * @param array<string, mixed> $export The export. + * @param FireTrigger $trigger Who or what fired it. + * + * @return array<string, mixed> + */ + private function fresh(array $export, FireTrigger $trigger): array { + return [ + 'exportId' => (string)($export['id'] ?? ''), + 'startedAt' => $this->now(), + 'triggeredBy' => $trigger->kind, + 'triggeredByUser' => $trigger->userId, + 'correlationId' => $this->uuid(), + ]; + }//end fresh() + + /** + * Now, as an ATOM string. + * + * @return string + */ + private function now(): string { + return $this->time->now()->format(DateTimeInterface::ATOM); + }//end now() + + /** + * A random version-4 uuid. + * + * @return string + */ + private function uuid(): string { + $hex = $this->random->generate(32, '0123456789abcdef'); + $hex = substr_replace($hex, '4', 12, 1); + $hex = substr_replace($hex, '89ab'[hexdec($hex[16]) % 4], 16, 1); + + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split($hex, 4)); + }//end uuid() +}//end class diff --git a/lib/Service/ScheduledExport/ConnectorVault.php b/lib/Service/ScheduledExport/ConnectorVault.php new file mode 100644 index 000000000..bc8e2e858 --- /dev/null +++ b/lib/Service/ScheduledExport/ConnectorVault.php @@ -0,0 +1,171 @@ +<?php + +/** + * ConnectorVault + * + * Delivery through the connector app's credential vault (design D5, + * REQ-SCH-010): a recipient with `openconnectorSourceId` is sent through + * that source, so the credential stays in the vault and the call lands in + * the connector's call log. There is no fallback to local credentials: + * without the connector the delivery fails. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use OCA\LaunchPad\Support\FleetAppId; +use OCP\IGroupManager; +use Psr\Container\ContainerInterface; +use Throwable; + +/** + * Sends a request through a connector source. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-010-header-signing-and-credential-vaulting + * @SuppressWarnings(PHPMD.StaticAccess) FleetAppId resolves the connector app under either of its names. + */ +class ConnectorVault { + + private const CONNECTOR_APP = 'integriq'; + + private const CALL_SERVICE = 'Service\\CallService'; + + private const OBJECT_SERVICE = 'OCA\OpenRegister\Service\ObjectService'; + + /** + * Constructor. + * + * @param ContainerInterface $container Resolves the connector's call service and the source object. + * @param IGroupManager $groupManager Tells whether the export's creator is an administrator. + */ + public function __construct( + private readonly ContainerInterface $container, + private readonly IGroupManager $groupManager, + ) { + }//end __construct() + + /** + * Send through a source; the returned id is the connector's call-log entry. + * + * @param string $sourceId The source uuid. + * @param array<string, mixed> $request `endpoint`, `method`, `body` and `headers`. + * @param string $owner The export's creator; the source is used under their access. + * + * @return string The call-log id. + * + * @throws DeliveryException When the vault is unavailable, the source is unknown or not the creator's, or the call fails. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-010-header-signing-and-credential-vaulting + */ + public function send(string $sourceId, array $request, string $owner): string { + $calls = FleetAppId::getService(container: $this->container, canonical: self::CONNECTOR_APP, relative: self::CALL_SERVICE); + if ($calls === null || method_exists($calls, 'call') === false) { + throw new DeliveryException('The credential vault is not available'); + } + + $source = $this->source(sourceId: $sourceId, owner: $owner); + + try { + $log = $calls->call( + source: $source, + endpoint: (string)($request['endpoint'] ?? ''), + method: (string)($request['method'] ?? 'POST'), + config: ['body' => $request['body'] ?? '', 'headers' => $request['headers'] ?? []] + ); + } catch (Throwable $e) { + throw new DeliveryException('The credential vault call failed: ' . $e->getMessage()); + } + + return self::reference(log: $log); + }//end send() + + /** + * The vault source by id, under the export creator's access. + * + * The delivery runs in the background without a session, so the source is + * read without the session's checks and then held to the creator: only a + * source the creator owns, or any source when the creator is an + * administrator. Any other source reads as unknown. + * + * @param string $sourceId The source's id. + * @param string $owner The export's creator. + * + * @return mixed The source. + * + * @throws DeliveryException When it does not exist, cannot be read, or is not the creator's. + */ + private function source(string $sourceId, string $owner): mixed { + try { + $source = $this->container->get(self::OBJECT_SERVICE)->find(id: $sourceId, _rbac: false); + } catch (Throwable) { + $source = null; + } + + if ($source === null || $this->mayUse(source: $source, owner: $owner) === false) { + throw new DeliveryException('Unknown credential vault source: ' . $sourceId); + } + + return $source; + }//end source() + + /** + * Whether the export's creator may deliver through the source. + * + * @param mixed $source The source. + * @param string $owner The export's creator. + * + * @return bool + */ + private function mayUse(mixed $source, string $owner): bool { + if ($owner === '') { + return false; + } + + if ($this->groupManager->isAdmin(userId: $owner) === true) { + return true; + } + + if (is_object($source) === false || method_exists($source, 'getOwner') === false) { + return false; + } + + return (string)$source->getOwner() === $owner; + }//end mayUse() + + /** + * The call log's reference, or `vault` when it carries none. + * + * @param mixed $log What the vault call returned. + * + * @return string The reference. + * + * @throws DeliveryException When the call answered an HTTP error. + */ + private static function reference(mixed $log): string { + $data = []; + if (is_object($log) === true && method_exists($log, 'jsonSerialize') === true) { + $data = (array)$log->jsonSerialize(); + } + + $status = (int)($data['response']['statusCode'] ?? $data['statusCode'] ?? 200); + if ($status >= 400) { + throw new DeliveryException('HTTP ' . $status . ' through the credential vault'); + } + + return (string)($data['@self']['id'] ?? $data['uuid'] ?? $data['id'] ?? 'vault'); + }//end reference() +}//end class diff --git a/lib/Service/ScheduledExport/DeliveryChannels.php b/lib/Service/ScheduledExport/DeliveryChannels.php new file mode 100644 index 000000000..d00d5ab21 --- /dev/null +++ b/lib/Service/ScheduledExport/DeliveryChannels.php @@ -0,0 +1,54 @@ +<?php + +/** + * DeliveryChannels + * + * The Nextcloud services the delivery channels use, kept together to keep + * the dispatcher's constructor short. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use OCP\Files\IRootFolder; +use OCP\Http\Client\IClientService; +use OCP\IAppConfig; +use OCP\Mail\IMailer; + +/** + * Mailer, HTTP client, Files and app config for the dispatcher. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-5 + */ +final class DeliveryChannels { + + /** + * Constructor. + * + * @param IMailer $mailer The email channel. + * @param IClientService $http The webhook channel. + * @param IRootFolder $rootFolder The Files channel. + * @param IAppConfig $appConfig The outbound host allow-list. + */ + public function __construct( + public readonly IMailer $mailer, + public readonly IClientService $http, + public readonly IRootFolder $rootFolder, + public readonly IAppConfig $appConfig, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ScheduledExport/DeliveryContext.php b/lib/Service/ScheduledExport/DeliveryContext.php new file mode 100644 index 000000000..32ada05fa --- /dev/null +++ b/lib/Service/ScheduledExport/DeliveryContext.php @@ -0,0 +1,49 @@ +<?php + +/** + * DeliveryContext + * + * What one delivery attempt sends: the export, the artefacts rendered for + * the recipient's filter context, and the moment of the attempt. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use DateTimeInterface; + +/** + * The export, its artefacts and the moment of a delivery. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-5 + */ +final class DeliveryContext { + + /** + * Constructor. + * + * @param array<string, mixed> $export The export. + * @param list<RenderResult> $artefacts The artefacts to send. + * @param DateTimeInterface $now The moment of the attempt. + */ + public function __construct( + public readonly array $export, + public readonly array $artefacts, + public readonly DateTimeInterface $now, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ScheduledExport/DeliveryDispatcher.php b/lib/Service/ScheduledExport/DeliveryDispatcher.php new file mode 100644 index 000000000..b8c6285c8 --- /dev/null +++ b/lib/Service/ScheduledExport/DeliveryDispatcher.php @@ -0,0 +1,441 @@ +<?php + +/** + * DeliveryDispatcher + * + * Delivery of a fire's artefacts (tasks.md task 5, REQ-SCH-005): one + * delivery per recipient on its channel — email through the Nextcloud + * mailer, a file in the creator's Files, a signed multipart POST to a + * webhook, an SFTP upload — or through the credential vault when the + * recipient names a connector source (REQ-SCH-010). Each attempt goes + * through the retry policy (REQ-SCH-006) and is reported at once, so the + * run-row is written after every attempt. Webhook and SFTP hosts must be on + * the admin's `export_allowed_hosts` list (fail-closed). + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use DateTimeInterface; +use OCA\LaunchPad\Service\HostAllowList; +use OCA\LaunchPad\Service\RetryAttempt; +use OCA\LaunchPad\Service\RetryHandler; +use OCP\Files\File; +use OCP\Files\Folder; +use OCP\Files\NotFoundException; +use Throwable; + +/** + * Sends artefacts to recipients. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-5 + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) Four channels and the vault route, each with its refusals. + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) Mailer, HTTP, Files, SFTP and the vault are the channels themselves. + */ +class DeliveryDispatcher { + + public const CONFIG_ALLOWED_HOSTS = 'export_allowed_hosts'; + + public const SIGNATURE_HEADER = 'X-LaunchPad-Signature'; + + /** + * Constructor. + * + * @param DeliveryChannels $services Mailer, HTTP, Files and config. + * @param SftpUploader $sftp The SFTP channel. + * @param ConnectorVault $vault The credential vault route. + * @param RetryHandler $retry The retry policy. + */ + public function __construct( + private readonly DeliveryChannels $services, + private readonly SftpUploader $sftp, + private readonly ConnectorVault $vault, + private readonly RetryHandler $retry, + ) { + }//end __construct() + + /** + * First attempt for every recipient. + * + * @param DeliveryContext $context The export, its artefacts and the moment. + * @param array<string, array<string, mixed>> $recipients Recipient id to recipient. + * @param callable|null $afterEach Called with the deliveries so far after each attempt. + * + * @return list<array<string, mixed>> One delivery per recipient. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-5 + */ + public function dispatch(DeliveryContext $context, array $recipients, ?callable $afterEach = null): array { + $deliveries = []; + foreach ($recipients as $id => $recipient) { + $fresh = [ + 'recipientId' => (string)$id, + 'channel' => (string)($recipient['channel'] ?? ''), + 'attemptCount' => 0, + 'status' => RetryHandler::STATUS_PENDING, + ]; + $deliveries[] = $this->deliver(delivery: $fresh, recipient: $recipient, context: $context); + if ($afterEach !== null) { + $afterEach($deliveries); + } + } + + return $deliveries; + }//end dispatch() + + /** + * One attempt of one delivery, through the retry policy. + * + * @param array<string, mixed> $delivery The delivery as the run-row holds it. + * @param array<string, mixed> $recipient The recipient, secrets revealed. + * @param DeliveryContext $context The export, its artefacts and the moment. + * + * @return array<string, mixed> The updated delivery. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function deliver(array $delivery, array $recipient, DeliveryContext $context): array { + $override = null; + if (is_array($recipient['retryPolicy'] ?? null) === true) { + $override = $recipient['retryPolicy']; + } + + $policy = $this->retry->policy(override: $override); + try { + $messageId = $this->attempt(recipient: $recipient, context: $context); + $delivery = $this->retry->afterAttempt(delivery: $delivery, attempt: new RetryAttempt(succeeded: true, now: $context->now, policy: $policy)); + $delivery['providerMessageId'] = $messageId; + } catch (Throwable $e) { + $error = 'Delivery failed: ' . $e->getMessage(); + if ($e instanceof DeliveryException || $e instanceof RenderException) { + $error = $e->getMessage(); + } + + $failed = new RetryAttempt(succeeded: false, now: $context->now, policy: $policy, error: $error); + $delivery = $this->retry->afterAttempt(delivery: $delivery, attempt: $failed); + } + + return $delivery; + }//end deliver() + + /** + * Send once on the recipient's channel. + * + * @param array<string, mixed> $recipient The recipient, secrets revealed. + * @param DeliveryContext $context The export, its artefacts and the moment. + * + * @return string The provider's id of what was sent. + * + * @throws DeliveryException When it was not delivered. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-005-email-nextcloud-files-webhook-and-sftp-delivery-channels + */ + public function attempt(array $recipient, DeliveryContext $context): string { + if ($context->artefacts === []) { + throw new DeliveryException('Nothing was rendered for this recipient'); + } + + $config = (array)($recipient['channelConfig'] ?? []); + $channel = (string)($recipient['channel'] ?? ''); + $source = (string)($recipient['openconnectorSourceId'] ?? $config['openconnectorSourceId'] ?? ''); + if ($source !== '' && in_array($channel, ['webhook', 'sftp'], true) === true) { + $payload = $this->multipart(context: $context); + return $this->vault->send(sourceId: $source, request: [ + 'endpoint' => (string)($config['endpoint'] ?? $config['remotePath'] ?? ''), + 'method' => 'POST', + 'body' => $payload['body'], + 'headers' => ['Content-Type' => $payload['contentType']], + ], owner: (string)($context->export['createdBy'] ?? '')); + } + + return match ($channel) { + 'email' => $this->email(config: $config, context: $context), + 'nextcloudFiles' => $this->files(config: $config, context: $context), + 'webhook' => $this->webhook(config: $config, context: $context), + 'sftp' => $this->upload(config: $config, context: $context), + default => throw new DeliveryException('Unknown channel: ' . $channel), + }; + }//end attempt() + + /** + * Email: one message to every address, the artefacts attached. + * + * @param array<string, mixed> $config `addresses` (list) or `to` (comma-separated). + * @param DeliveryContext $context The export and its artefacts. + * + * @return string An id of the message: the mailer exposes none, so LaunchPad derives one. + * + * @throws DeliveryException When an address is invalid or the mailer refuses. + */ + private function email(array $config, DeliveryContext $context): string { + $addresses = $config['addresses'] ?? array_map('trim', explode(',', (string)($config['to'] ?? ''))); + $addresses = array_values(array_filter(array_map('strval', (array)$addresses), static fn (string $a): bool => $a !== '')); + if ($addresses === []) { + throw new DeliveryException('The email recipient has no addresses'); + } + + foreach ($addresses as $address) { + if ($this->services->mailer->validateMailAddress($address) === false) { + throw new DeliveryException('Not a valid email address: ' . $address); + } + } + + $name = (string)($context->export['name'] ?? 'Scheduled export'); + $message = $this->services->mailer->createMessage(); + $message->setTo($addresses); + $message->setSubject($name); + $message->setPlainBody((string)($context->export['description'] ?? $name)); + $message->setAutoSubmitted('auto-generated'); + foreach ($context->artefacts as $artefact) { + $message->attach($this->services->mailer->createAttachment($artefact->content, $artefact->filename, $artefact->mimeType())); + } + + $failed = $this->services->mailer->send($message); + if ($failed !== []) { + throw new DeliveryException('The mailer refused: ' . implode(', ', $failed)); + } + + $seed = array_merge($addresses, $this->hashes(context: $context), [$context->now->format(DateTimeInterface::ATOM)]); + return 'mail-' . substr(hash('sha256', implode('|', $seed)), 0, 32); + }//end email() + + /** + * Files: every artefact into a folder of the export creator's Files; + * an existing file is replaced only with `overwrite: true`. + * + * @param array<string, mixed> $config `targetPath`, `overwrite`, and an optional `user` that must be the creator. + * @param DeliveryContext $context The export and its artefacts. + * + * @return string The file ids written. + * + * @throws DeliveryException When the folder cannot be written. + */ + private function files(array $config, DeliveryContext $context): string { + $owner = (string)($context->export['createdBy'] ?? ''); + $user = (string)($config['user'] ?? $owner); + if ($user !== $owner) { + throw new DeliveryException('An export may only write into the Files of its creator'); + } + + try { + $folder = $this->services->rootFolder->getUserFolder($owner); + $parts = array_filter(explode('/', (string)($config['targetPath'] ?? 'Exports')), static fn (string $part): bool => $part !== ''); + foreach ($parts as $part) { + if ($part === '..') { + throw new DeliveryException('The target path may not contain ..'); + } + + $folder = $this->child(folder: $folder, name: $part); + } + + $ids = []; + foreach ($context->artefacts as $artefact) { + $ids[] = (string)$this->writeFile(folder: $folder, artefact: $artefact, overwrite: ($config['overwrite'] ?? false) === true)->getId(); + } + } catch (DeliveryException $e) { + throw $e; + } catch (Throwable) { + throw new DeliveryException('The target folder could not be written in Files'); + } + + return implode(',', $ids); + }//end files() + + /** + * Webhook: a multipart POST, HMAC-SHA256-signed over the body when a secret is set. + * + * @param array<string, mixed> $config `url` (https, allow-listed host), `signingSecret`. + * @param DeliveryContext $context The export and its artefacts. + * + * @return string The receiver's request id, or `http-<status>`. + * + * @throws DeliveryException When the URL is not allowed or the receiver does not answer 2xx. + */ + private function webhook(array $config, DeliveryContext $context): string { + $url = (string)($config['url'] ?? ''); + if (strtolower((string)parse_url($url, PHP_URL_SCHEME)) !== 'https' || $this->allowList()->permits(url: $url) === false) { + throw new DeliveryException('The webhook URL is not an allowed https address'); + } + + $payload = $this->multipart(context: $context); + $headers = ['Content-Type' => $payload['contentType']]; + if (is_string($config['signingSecret'] ?? null) === true && $config['signingSecret'] !== '') { + $headers[self::SIGNATURE_HEADER] = self::signature(body: $payload['body'], secret: $config['signingSecret']); + } + + try { + $options = ['body' => $payload['body'], 'headers' => $headers, 'timeout' => 30, 'http_errors' => false]; + $response = $this->services->http->newClient()->post($url, $options); + } catch (Throwable) { + throw new DeliveryException('The webhook could not be reached'); + } + + $status = $response->getStatusCode(); + if ($status < 200 || $status >= 300) { + throw new DeliveryException('HTTP ' . $status); + } + + $requestId = $response->getHeader('X-Request-Id'); + if ($requestId === '') { + return 'http-' . $status; + } + + return $requestId; + }//end webhook() + + /** + * SFTP: every artefact uploaded, its size confirmed. + * + * @param array<string, mixed> $config The SFTP configuration. + * @param DeliveryContext $context The artefacts. + * + * @return string The confirmed sizes, per file. + * + * @throws DeliveryException When the host is not allowed or an upload fails. + */ + private function upload(array $config, DeliveryContext $context): string { + if ($this->allowList()->permits(url: 'https://' . (string)($config['host'] ?? '')) === false) { + throw new DeliveryException('The SFTP host is not allowed'); + } + + $confirmed = []; + foreach ($context->artefacts as $artefact) { + $confirmed[] = $artefact->filename . ':' . $this->sftp->upload(config: $config, artefact: $artefact); + } + + return 'sftp-size ' . implode(',', $confirmed); + }//end upload() + + /** + * The `sha256=<hex>` signature of a body. + * + * @param string $body The exact bytes sent. + * @param string $secret The recipient's secret. + * + * @return string + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-010-header-signing-and-credential-vaulting + */ + public static function signature(string $body, string $secret): string { + return 'sha256=' . hash_hmac('sha256', $body, $secret); + }//end signature() + + /** + * The multipart body: a `metadata` JSON part, then one part per artefact. + * + * @param DeliveryContext $context The export and its artefacts. + * + * @return array{body: string, contentType: string} + */ + private function multipart(DeliveryContext $context): array { + $boundary = 'launchpad-' . substr(hash('sha256', implode('|', $this->hashes(context: $context))), 0, 24); + $meta = [ + 'exportId' => (string)($context->export['id'] ?? ''), + 'name' => (string)($context->export['name'] ?? ''), + 'sentAt' => $context->now->format(DateTimeInterface::ATOM), + 'artefacts' => array_map(static fn (RenderResult $a): array => ['filename' => $a->filename] + $a->toAudit(), $context->artefacts), + ]; + + $body = '--' . $boundary . "\r\nContent-Disposition: form-data; name=\"metadata\"\r\n" + . "Content-Type: application/json\r\n\r\n" . json_encode($meta) . "\r\n"; + foreach ($context->artefacts as $i => $artefact) { + $name = addcslashes($artefact->filename, '"\\'); + $body .= '--' . $boundary . "\r\nContent-Disposition: form-data; name=\"file" . $i . '"; filename="' . $name + . "\"\r\nContent-Type: " . $artefact->mimeType() . "\r\n\r\n" . $artefact->content . "\r\n"; + } + + return ['body' => $body . '--' . $boundary . "--\r\n", 'contentType' => 'multipart/form-data; boundary=' . $boundary]; + }//end multipart() + + /** + * Write one artefact, replacing an existing file only when asked. + * + * @param Folder $folder The target folder. + * @param RenderResult $artefact The artefact. + * @param bool $overwrite Whether an existing file is replaced. + * + * @return File + */ + private function writeFile(Folder $folder, RenderResult $artefact, bool $overwrite): File { + $name = $artefact->filename; + if ($folder->nodeExists($name) === true) { + $existing = $folder->get($name); + if ($overwrite === true && $existing instanceof File) { + $existing->putContent($artefact->content); + return $existing; + } + + $dot = strrpos($name, '.'); + $ext = ''; + $stem = $name; + if ($dot !== false) { + $stem = substr($name, 0, $dot); + $ext = substr($name, $dot); + } + + for ($n = 2; $folder->nodeExists($name) === true; $n++) { + $name = $stem . ' (' . $n . ')' . $ext; + } + } + + return $folder->newFile($name, $artefact->content); + }//end writeFile() + + /** + * A child folder, created when missing. + * + * @param Folder $folder The parent. + * @param string $name The child. + * + * @return Folder + * + * @throws DeliveryException When the child is a file. + */ + private function child(Folder $folder, string $name): Folder { + try { + $node = $folder->get($name); + } catch (NotFoundException) { + return $folder->newFolder($name); + } + + if (($node instanceof Folder) === false) { + throw new DeliveryException('The target path is not a folder'); + } + + return $node; + }//end child() + + /** + * The sha256s of the artefacts. + * + * @param DeliveryContext $context The artefacts. + * + * @return list<string> + */ + private function hashes(DeliveryContext $context): array { + return array_map(static fn (RenderResult $a): string => $a->sha256(), $context->artefacts); + }//end hashes() + + /** + * The admin's outbound host allow-list for webhook and SFTP hosts. + * + * @return HostAllowList + */ + private function allowList(): HostAllowList { + return new HostAllowList(appConfig: $this->services->appConfig, configKey: self::CONFIG_ALLOWED_HOSTS); + }//end allowList() +}//end class diff --git a/lib/Service/ScheduledExport/DeliveryException.php b/lib/Service/ScheduledExport/DeliveryException.php new file mode 100644 index 000000000..343192b0b --- /dev/null +++ b/lib/Service/ScheduledExport/DeliveryException.php @@ -0,0 +1,35 @@ +<?php + +/** + * DeliveryException + * + * One delivery attempt that failed (REQ-SCH-005/006); the message is the + * error the run-row records. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use RuntimeException; + +/** + * Why a delivery attempt failed. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ +class DeliveryException extends RuntimeException { +}//end class diff --git a/lib/Service/ScheduledExport/ExportCalculatedValues.php b/lib/Service/ScheduledExport/ExportCalculatedValues.php new file mode 100644 index 000000000..dd893f8bd --- /dev/null +++ b/lib/Service/ScheduledExport/ExportCalculatedValues.php @@ -0,0 +1,142 @@ +<?php + +/** + * ExportCalculatedValues + * + * The calculated fields of an export's widgets, evaluated on the server at + * export time with the same evaluator the client mirrors (widget-calculated- + * fields task 20), so an export carries the values the widgets show. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-20 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use OCA\LaunchPad\Service\CalculatedFields\CalculatedFieldCycleDetector; +use OCA\LaunchPad\Service\CalculatedFields\CalculatedFieldCycleError; +use OCA\LaunchPad\Service\CalculatedFields\CalculatedFieldEvaluator; + +/** + * Evaluates every calculated field of a set of widgets, in dependency order. + * + * Each field reads its widget's data (`row`), the widget's earlier values + * (`calculated`), and the data and values of the widgets it references + * (`widgets`, `widgetCalculated`), exactly as the client's + * `evaluateDashboard()` hands them. A field that fails, or a cycle, gives + * null, as an empty cell; the other fields still evaluate. + * + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-20 + */ +class ExportCalculatedValues { + + /** + * Constructor. + * + * @param CalculatedFieldEvaluator $evaluator Evaluates one compiled expression. + * @param CalculatedFieldCycleDetector $cycleDetector Orders the fields, dependencies first. + */ + public function __construct( + private readonly CalculatedFieldEvaluator $evaluator = new CalculatedFieldEvaluator(), + private readonly CalculatedFieldCycleDetector $cycleDetector = new CalculatedFieldCycleDetector(), + ) { + }//end __construct() + + /** + * The values of every calculated field, by widget id and field name. + * + * @param list<array<string, mixed>> $widgets The widgets, each `{id, calculatedFields}`. + * @param array<string, array<string, mixed>> $dataById Each widget's data, by widget id. + * @param int|float|null $nowMs The moment `now()` reads; the clock when null. + * + * @return array<string, array<string, mixed>> + * + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-20 + */ + public function values(array $widgets, array $dataById, int|float|null $nowMs=null): array { + $byId = $this->compiledWidgets(widgets: $widgets); + $values = array_map(static fn (): array => [], $byId); + try { + $order = $this->cycleDetector->assertAcyclic(widgets: array_values($byId)); + } catch (CalculatedFieldCycleError) { + return $this->allNull(byId: $byId); + } + + foreach ($order as $node) { + $dot = (int) strrpos($node, '.'); + $widgetId = substr($node, 0, $dot); + $name = substr($node, $dot + 1); + $field = ($byId[$widgetId]['fields'][$name] ?? null); + if ($field === null) { + continue; + } + + $outcome = $this->evaluator->evaluateField( + ast: (array) $field['compiledExpression'], + expression: (string) ($field['expression'] ?? ''), + context: [ + 'row' => ($dataById[$widgetId] ?? []), + 'calculated' => $values[$widgetId], + 'widgets' => $dataById, + 'widgetCalculated' => $values, + ], + nowMs: $nowMs + ); + $values[$widgetId][$name] = $outcome['value']; + }//end foreach + + return $values; + }//end values() + + /** + * The widgets with compiled calculated fields, by id, each with its fields by name. + * + * @param list<array<string, mixed>> $widgets The widgets. + * + * @return array<string, array{id: string, calculatedFields: list<array<string, mixed>>, fields: array<string, array<string, mixed>>}> + */ + private function compiledWidgets(array $widgets): array { + $byId = []; + foreach ($widgets as $widget) { + $fields = array_values( + array_filter( + (array) ($widget['calculatedFields'] ?? []), + static fn (mixed $field): bool => is_array($field) === true + && is_string($field['name'] ?? null) === true + && is_array($field['compiledExpression'] ?? null) === true + ) + ); + if ($fields === [] || isset($widget['id']) === false) { + continue; + } + + $id = (string) $widget['id']; + $byId[$id] = ['id' => $id, 'calculatedFields' => $fields, 'fields' => array_column($fields, null, 'name')]; + } + + return $byId; + }//end compiledWidgets() + + /** + * Every field null, for a set of fields that cannot be ordered. + * + * @param array<string, array{fields: array<string, mixed>}> $byId The widgets by id. + * + * @return array<string, array<string, null>> + */ + private function allNull(array $byId): array { + return array_map(static fn (array $widget): array => array_fill_keys(array_keys($widget['fields']), null), $byId); + }//end allNull() +}//end class diff --git a/lib/Service/ScheduledExport/ExportFire.php b/lib/Service/ScheduledExport/ExportFire.php new file mode 100644 index 000000000..392b98f0c --- /dev/null +++ b/lib/Service/ScheduledExport/ExportFire.php @@ -0,0 +1,376 @@ +<?php + +/** + * ExportFire + * + * One fire of a scheduled export (REQ-SCH-002/004/008/009), shared by the + * background runner and "Run now": refuse an overlap and a disabled + * creator, open the run-row, render once per distinct filter context, + * deliver each recipient its context's artefacts (a render failure fails + * only that context's recipients), close the row, notify on permanent + * failures, and record the outcome on the export. Also the retry side: + * due retries, and a manual "Retry" of a run's failed deliveries. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use DateTimeInterface; +use OCA\LaunchPad\Service\RetryHandler; +use OCP\Files\File; +use Throwable; + +/** + * Fires an export, and retries its deliveries. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-8 + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) A fire joins render, dispatch, audit and the export. + */ +class ExportFire { + + public const REASON_OVERLAP = 'The previous run of this export is still running.'; + + public const REASON_CREATOR_DISABLED = 'The creator of this export is disabled.'; + + /** + * Constructor. + * + * @param ScheduledExportService $exports The exports. + * @param AuditLog $log The run-rows. + * @param RenderPipeline $render Renders the targets. + * @param DeliveryDispatcher $dispatch Delivers the artefacts. + * @param FireSupport $support Retry policy, notifier, users, Files, clock. + */ + public function __construct( + private readonly ScheduledExportService $exports, + private readonly AuditLog $log, + private readonly RenderPipeline $render, + private readonly DeliveryDispatcher $dispatch, + private readonly FireSupport $support, + ) { + }//end __construct() + + /** + * Fire an export now. + * + * @param array<string, mixed> $export The export as stored. + * @param FireTrigger $trigger The schedule or a user's "Run now". + * + * @return array<string, mixed> The run-row. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-002-background-runner-fires-schedules-without-an-active-browser-session + */ + public function fire(array $export, FireTrigger $trigger): array { + $now = $this->support->time->now(); + if ($this->inProgress(exportId: (string)($export['id'] ?? '')) === true) { + $run = $this->log->skipped(export: $export, trigger: $trigger, skip: ['status' => 'partial', 'reason' => self::REASON_OVERLAP]); + $this->finish(export: $export, run: $run, trigger: $trigger); + return $run; + } + + $creator = $this->support->users->get((string)($export['createdBy'] ?? '')); + if ($creator === null || $creator->isEnabled() === false) { + $run = $this->log->skipped(export: $export, trigger: $trigger, skip: ['status' => 'failed', 'reason' => self::REASON_CREATOR_DISABLED]); + $this->support->notifier->failed(export: $export + ['creatorEnabled' => false], reason: self::REASON_CREATOR_DISABLED); + $this->finish(export: $export, run: $run, trigger: $trigger); + return $run; + } + + $run = $this->log->start(export: $export, trigger: $trigger); + $secret = $this->exports->forDispatch(id: (string)($export['id'] ?? '')) ?? $export; + + $artefacts = []; + $deliveries = []; + foreach ($this->groups(export: $secret) as $group) { + try { + $rendered = $this->render->render(export: $export, filterContext: $group['filterContext']); + } catch (RenderException $e) { + foreach (array_keys($group['recipients']) as $id) { + $deliveries[] = $this->failedDelivery(id: (string)$id, recipient: $group['recipients'][$id], error: $e->getMessage()); + } + + continue; + } + + $indexes = range(count($artefacts), count($artefacts) + count($rendered) - 1); + $artefacts = array_merge($artefacts, array_map(static fn (RenderResult $r): array => $r->toAudit(), $rendered)); + $done = $deliveries; + $context = new DeliveryContext(export: $secret, artefacts: $rendered, now: $now); + $progress = function (array $sent) use ($run, $done, $artefacts): void { + $this->log->update(run: $run + ['renderArtefacts' => $artefacts, 'deliveries' => array_merge($done, $sent)]); + }; + $sent = $this->dispatch->dispatch(context: $context, recipients: $group['recipients'], afterEach: $progress); + foreach ($sent as $delivery) { + $deliveries[] = $delivery + ['artefactIndexes' => $indexes]; + } + }//end foreach + + $run = $this->log->record(run: $run, artefacts: $artefacts, deliveries: $deliveries); + $this->notifyPermanent(export: $export, deliveries: $deliveries); + $this->finish(export: $export, run: $run, trigger: $trigger); + + return $run; + }//end fire() + + /** + * Attempt every delivery whose retry is due, and close the rows that settle. + * + * @return int The number of deliveries attempted. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function retryDue(): int { + $now = $this->support->time->now(); + $attempts = 0; + foreach ($this->log->allRuns() as $run) { + $isDue = fn ($delivery): bool => is_array($delivery) === true && $this->support->retry->isDue(delivery: $delivery, now: $now); + $due = array_filter((array)($run['deliveries'] ?? []), $isDue); + if ($due === []) { + continue; + } + + $attempts += count($due); + $this->redeliver(run: $run, indexes: array_keys($due), now: $now); + } + + return $attempts; + }//end retryDue() + + /** + * A manual "Retry" of every delivery of a run that failed for good, attempted now. + * + * @param array<string, mixed> $run The run-row. + * + * @return array<string, mixed> The updated run-row. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + public function retryRun(array $run): array { + $now = $this->support->time->now(); + $indexes = []; + foreach ((array)($run['deliveries'] ?? []) as $i => $delivery) { + if (($delivery['status'] ?? null) === RetryHandler::STATUS_FAILED_PERMANENT) { + $run['deliveries'][$i] = $this->support->retry->rearm(delivery: $delivery, now: $now); + $indexes[] = $i; + } + } + + if ($indexes === []) { + return $run; + } + + return $this->redeliver(run: $run, indexes: $indexes, now: $now); + }//end retryRun() + + /** + * Attempt the given deliveries of a run again with its stored artefacts, then close the row. + * + * @param array<string, mixed> $run The run-row. + * @param list<int|string> $indexes The deliveries to attempt. + * @param DateTimeInterface $now The moment. + * + * @return array<string, mixed> The saved run-row. + */ + private function redeliver(array $run, array $indexes, DateTimeInterface $now): array { + $export = $this->exports->forDispatch(id: (string)($run['exportId'] ?? '')); + if ($export === null) { + return $run; + } + + $recipients = $this->recipients(export: $export); + foreach ($indexes as $i) { + $delivery = $run['deliveries'][$i]; + $recipient = $recipients[(string)($delivery['recipientId'] ?? '')] ?? ['channel' => (string)($delivery['channel'] ?? '')]; + $artefacts = $this->storedArtefacts(run: $run, indexes: (array)($delivery['artefactIndexes'] ?? [])); + $context = new DeliveryContext(export: $export, artefacts: $artefacts, now: $now); + + $run['deliveries'][$i] = $this->dispatch->deliver(delivery: $delivery, recipient: $recipient, context: $context); + } + + $run = $this->log->record(run: $run, artefacts: (array)($run['renderArtefacts'] ?? []), deliveries: (array)$run['deliveries']); + $this->notifyPermanent(export: $export, deliveries: array_intersect_key((array)$run['deliveries'], array_flip($indexes))); + if ($run['status'] !== 'running') { + $this->exports->recordFire(export: $export, fields: ['lastRunStatus' => $run['status']]); + } + + return $run; + }//end redeliver() + + /** + * The artefacts of a run read back from Files; a purged one is skipped. + * + * @param array<string, mixed> $run The run-row. + * @param list<int> $indexes Which of its artefacts. + * + * @return list<RenderResult> + */ + private function storedArtefacts(array $run, array $indexes): array { + $results = []; + foreach ($indexes as $index) { + $meta = $run['renderArtefacts'][$index] ?? null; + $path = null; + if (is_array($meta) === true) { + $path = $meta['storagePath'] ?? null; + } + + if (is_string($path) === false || $path === '') { + continue; + } + + try { + $file = $this->support->rootFolder->get($path); + } catch (Throwable) { + continue; + } + + if ($file instanceof File) { + $name = (string)($meta['filename'] ?? $file->getName()); + $results[] = new RenderResult(format: (string)$meta['format'], filename: $name, content: $file->getContent(), storagePath: $path); + } + } + + return $results; + }//end storedArtefacts() + + /** + * Enabled recipients grouped by identical filter context (REQ-SCH-004), so each context renders once. + * + * @param array<string, mixed> $export The export, secrets revealed. + * + * @return list<array{filterContext: array<string, mixed>, recipients: array<string, array<string, mixed>>}> + */ + private function groups(array $export): array { + $groups = []; + foreach ($this->recipients(export: $export) as $id => $recipient) { + if (($recipient['enabled'] ?? true) === false) { + continue; + } + + $context = (array)($recipient['filterContext'] ?? []); + ksort($context); + $key = (string)json_encode($context); + $groups[$key] ??= ['filterContext' => $context, 'recipients' => []]; + $groups[$key]['recipients'][$id] = $recipient; + } + + return array_values($groups); + }//end groups() + + /** + * The export's recipients by id: their own `id`, else their position. + * + * @param array<string, mixed> $export The export. + * + * @return array<string, array<string, mixed>> + */ + private function recipients(array $export): array { + $byId = []; + foreach ((array)($export['recipients'] ?? []) as $index => $recipient) { + if (is_array($recipient) === true) { + $byId[(string)($recipient['id'] ?? $index)] = $recipient; + } + } + + return $byId; + }//end recipients() + + /** + * A delivery that failed before any attempt (its render failed). + * + * @param string $id The recipient id. + * @param array<string, mixed> $recipient The recipient. + * @param string $error Why. + * + * @return array<string, mixed> + */ + private function failedDelivery(string $id, array $recipient, string $error): array { + return [ + 'recipientId' => $id, + 'channel' => (string)($recipient['channel'] ?? ''), + 'attemptCount' => 0, + 'status' => RetryHandler::STATUS_FAILED_PERMANENT, + 'error' => $error, + ]; + }//end failedDelivery() + + /** + * Whether a previous run of the export is still rendering or dispatching + * (a run that only waits for retries does not block the next fire). + * + * @param string $exportId The export. + * + * @return bool + */ + private function inProgress(string $exportId): bool { + foreach ($this->log->runsOf(exportId: $exportId) as $run) { + if (($run['status'] ?? null) !== 'running') { + continue; + } + + $statuses = array_column((array)($run['deliveries'] ?? []), 'status'); + if (in_array(RetryHandler::STATUS_RETRYING, $statuses, true) === false) { + return true; + } + } + + return false; + }//end inProgress() + + /** + * Notify once when any of the deliveries failed for good. + * + * @param array<string, mixed> $export The export. + * @param array<int|string, array<string, mixed>> $deliveries The deliveries. + * + * @return void + */ + private function notifyPermanent(array $export, array $deliveries): void { + $errors = []; + foreach ($deliveries as $delivery) { + if (($delivery['status'] ?? null) === RetryHandler::STATUS_FAILED_PERMANENT) { + $errors[] = (string)($delivery['channel'] ?? '') . ': ' . (string)($delivery['error'] ?? ''); + } + } + + if ($errors !== []) { + $this->support->notifier->failed(export: $export, reason: implode('; ', $errors)); + } + }//end notifyPermanent() + + /** + * Record the fire on the export; a scheduled fire also moves `nextRunAt` on. + * + * @param array<string, mixed> $export The export. + * @param array<string, mixed> $run The run-row. + * @param FireTrigger $trigger The trigger. + * + * @return void + */ + private function finish(array $export, array $run, FireTrigger $trigger): void { + $fields = ['lastRunAt' => (string)($run['startedAt'] ?? ''), 'lastRunStatus' => (string)($run['status'] ?? 'failed')]; + if ($trigger->isScheduled() === true) { + try { + $fields['nextRunAt'] = $this->exports->nextRunAfter(export: $export, after: $this->support->time->now()); + } catch (Throwable) { + // A rule that no longer resolves keeps its old nextRunAt; the export fails validation on its next save. + $fields['lastRunStatus'] = 'failed'; + } + } + + $this->exports->recordFire(export: $export, fields: $fields); + }//end finish() +}//end class diff --git a/lib/Service/ScheduledExport/ExportNotifier.php b/lib/Service/ScheduledExport/ExportNotifier.php new file mode 100644 index 000000000..13ffb2b74 --- /dev/null +++ b/lib/Service/ScheduledExport/ExportNotifier.php @@ -0,0 +1,97 @@ +<?php + +/** + * ExportNotifier + * + * The notifications of failed scheduled exports (REQ-SCH-002, REQ-SCH-006, + * design open question 3): the export's creator and every administrator + * hear about a fire blocked by a disabled creator and about deliveries + * that failed for good. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use DateTime; +use OCP\IGroupManager; +use OCP\IUser; +use OCP\Notification\IManager; +use Throwable; + +/** + * Queues the failure notification of an export. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ +class ExportNotifier { + + public const SUBJECT = 'scheduled_export_failed'; + + /** + * Constructor. + * + * @param IManager $notifications The notification manager. + * @param IGroupManager $groups Finds the administrators. + */ + public function __construct( + private readonly IManager $notifications, + private readonly IGroupManager $groups, + ) { + }//end __construct() + + /** + * Notify the creator (when enabled) and every administrator. + * + * @param array<string, mixed> $export The export. + * @param string $reason What failed. + * + * @return list<string> The users notified. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-002-background-runner-fires-schedules-without-an-active-browser-session + */ + public function failed(array $export, string $reason): array { + $users = []; + $admin = $this->groups->get('admin'); + if ($admin !== null) { + $enabled = array_filter($admin->getUsers(), static fn (IUser $user): bool => $user->isEnabled()); + $users = array_map(static fn (IUser $user): string => $user->getUID(), $enabled); + } + + $creator = (string)($export['createdBy'] ?? ''); + if ($creator !== '' && ($export['creatorEnabled'] ?? true) === true) { + $users[] = $creator; + } + + $users = array_values(array_unique($users)); + foreach ($users as $uid) { + try { + $notification = $this->notifications->createNotification(); + $notification->setApp('launchpad') + ->setUser($uid) + ->setDateTime(new DateTime()) + ->setObject('scheduled_export', (string)($export['id'] ?? '')) + ->setSubject(self::SUBJECT, [(string)($export['name'] ?? ''), $reason]); + $this->notifications->notify($notification); + } catch (Throwable) { + // A notification that cannot be queued must not fail the run. + continue; + } + } + + return $users; + }//end failed() +}//end class diff --git a/lib/Service/ScheduledExport/ExportObjectStore.php b/lib/Service/ScheduledExport/ExportObjectStore.php new file mode 100644 index 000000000..816f40a76 --- /dev/null +++ b/lib/Service/ScheduledExport/ExportObjectStore.php @@ -0,0 +1,277 @@ +<?php + +/** + * ExportObjectStore + * + * The one place scheduled exports touch OpenRegister (design D3, Reuse + * Analysis): exports and their run-rows are objects of the `launchpad` + * register, read and written through OpenRegister's ObjectService, never a + * LaunchPad table. OpenRegister is a soft dependency, so the service is + * resolved lazily and its absence reads as "no objects". + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use Psr\Container\ContainerInterface; +use RuntimeException; +use Throwable; + +/** + * Object CRUD on the `launchpad` register for the scheduled-export schemas. + * + * Every call reads and writes with OpenRegister's RBAC off: the background + * runner and janitor run without a session user, which OpenRegister denies, + * and every request path checks visibility itself in + * {@see ScheduledExportService} (owner or admin) before it reaches the store. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ +class ExportObjectStore { + + public const REGISTER = 'launchpad'; + + public const SCHEMA_EXPORT = 'scheduled_export'; + + public const SCHEMA_RUN = 'scheduled_export_run'; + + private const OBJECT_SERVICE = 'OCA\OpenRegister\Service\ObjectService'; + + private const VALUE_NS = 'OCA\OpenRegister\Kernel\Contracts\Value\\'; + + /** + * OpenRegister's scope for writes the app makes itself, under which the + * schema's readOnly properties may be stamped. Absent before OpenRegister 2.2. + */ + private const SYSTEM_CONTEXT = 'OCA\OpenRegister\Service\SystemOperationContext'; + + /** + * Constructor. + * + * @param ContainerInterface $container Resolves OpenRegister's ObjectService lazily. + */ + public function __construct( + private readonly ContainerInterface $container, + ) { + }//end __construct() + + /** + * Whether OpenRegister is there to read and write objects. + * + * @return bool + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-6 + */ + public function isAvailable(): bool { + return $this->objectService() !== null; + }//end isAvailable() + + /** + * Every object of a schema matching the filters. + * + * @param string $schema The schema slug. + * @param array<string, mixed> $filters Property filters; metadata filters nested under `@self`. + * + * @return list<array<string, mixed>> The objects, each with its `id` and `owner`. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function findAll(string $schema, array $filters = []): array { + $service = $this->objectService(); + if ($service === null) { + return []; + } + + $filters['register'] = self::REGISTER; + $filters['schema'] = $schema; + $rows = $service->findAll(config: ['filters' => $filters, 'limit' => 1000], _rbac: false); + if (is_array($rows) === false) { + return []; + } + + return array_values(array_filter(array_map(fn ($row): array => $this->normalise(item: $row), $rows))); + }//end findAll() + + /** + * One object by uuid, or null when it does not exist or may not be read. + * + * @param string $schema The schema slug. + * @param string $uuid The object uuid. + * + * @return array<string, mixed>|null + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function find(string $schema, string $uuid): ?array { + $service = $this->objectService(); + if ($service === null || $uuid === '') { + return null; + } + + $options = $this->value(name: 'ObjectFindOptions', args: ['register' => self::REGISTER, 'schema' => $schema]); + try { + $row = $service->find(id: $uuid, options: $options, _rbac: false); + } catch (Throwable) { + return null; + } + + $data = $this->normalise(item: $row); + if ($data === []) { + return null; + } + + return $data; + }//end find() + + /** + * Create or update an object. + * + * @param string $schema The schema slug. + * @param array<string, mixed> $data The object's properties; an `id` updates that object. + * + * @return array<string, mixed> The saved object. + * + * @throws RuntimeException When OpenRegister is not available. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function save(string $schema, array $data): array { + $service = $this->objectService(); + if ($service === null) { + throw new RuntimeException('OpenRegister is not available'); + } + + $uuid = null; + if (is_string($data['id'] ?? null) === true && $data['id'] !== '') { + $uuid = $data['id']; + } + + unset($data['id'], $data['owner'], $data['@self']); + + $target = $this->value(name: 'ObjectFindTarget', args: ['register' => self::REGISTER, 'schema' => $schema]); + $options = $this->value(name: 'ObjectSaveOptions', args: ['target' => $target, 'uuid' => $uuid]); + $saved = $service->saveObject(object: $data, options: $options, _rbac: false); + + return $this->normalise(item: $saved); + }//end save() + + /** + * Create or update an object as the app itself, so the properties the + * schema marks readOnly (`nextRunAt`, `lastRunAt`, `lastRunStatus`, + * `createdBy`) can be stamped. Only for values the app computes: callers + * strip those fields from user input first. On an OpenRegister without + * the system scope this is a plain save. + * + * @param string $schema The schema slug. + * @param array<string, mixed> $data The object's properties; an `id` updates that object. + * + * @return array<string, mixed> The saved object. + * + * @throws RuntimeException When OpenRegister is not available. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-8 + */ + public function saveAsSystem(string $schema, array $data): array { + $save = fn (): array => $this->save(schema: $schema, data: $data); + if (class_exists(self::SYSTEM_CONTEXT) === false) { + return $save(); + } + + return call_user_func([self::SYSTEM_CONTEXT, 'run'], $save); + }//end saveAsSystem() + + /** + * Soft-delete an object (OpenRegister's standard delete). + * + * @param string $uuid The object uuid. + * + * @return bool Whether it was deleted. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function delete(string $uuid): bool { + $service = $this->objectService(); + if ($service === null) { + return false; + } + + $deletion = $this->value(name: 'ObjectDeletion', args: ['uuid' => $uuid]); + return $service->deleteObject(deletion: $deletion, _rbac: false) === true; + }//end delete() + + /** + * A plain array from an ObjectService result, with `id` and `owner` lifted + * out of `@self`. + * + * @param mixed $item An ObjectEntity, a serialisable object or an array. + * + * @return array<string, mixed> The data, or [] for anything else. + */ + private function normalise(mixed $item): array { + if (is_object($item) === true && method_exists($item, 'jsonSerialize') === true) { + $item = $item->jsonSerialize(); + } + + if (is_array($item) === false) { + return []; + } + + $self = []; + if (is_array($item['@self'] ?? null) === true) { + $self = $item['@self']; + } + + $item['id'] = $item['id'] ?? $self['id'] ?? $self['uuid'] ?? null; + $item['owner'] = $self['owner'] ?? $item['owner'] ?? null; + unset($item['@self']); + + return $item; + }//end normalise() + + /** + * One of OpenRegister's request value objects, built by name so the + * soft dependency stays soft. + * + * @param string $name The class name under the value namespace. + * @param array<string, mixed> $args Its named constructor arguments. + * + * @return object + */ + private function value(string $name, array $args): object { + $class = self::VALUE_NS . $name; + return new $class(...$args); + }//end value() + + /** + * OpenRegister's ObjectService, or null when OpenRegister is not enabled. + * + * @return object|null + */ + private function objectService(): ?object { + try { + $service = $this->container->get(self::OBJECT_SERVICE); + } catch (Throwable) { + return null; + } + + if (is_object($service) === false) { + return null; + } + + return $service; + }//end objectService() +}//end class diff --git a/lib/Service/ScheduledExport/FireSupport.php b/lib/Service/ScheduledExport/FireSupport.php new file mode 100644 index 000000000..f9f862012 --- /dev/null +++ b/lib/Service/ScheduledExport/FireSupport.php @@ -0,0 +1,57 @@ +<?php + +/** + * FireSupport + * + * The collaborators of a fire besides render, dispatch and audit: the retry + * policy, the failure notifier, the user manager (is the creator still + * enabled?), Files (artefacts read back for a retry) and the clock. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use OCA\LaunchPad\Service\RetryHandler; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Files\IRootFolder; +use OCP\IUserManager; + +/** + * Retry policy, notifier, users, Files and clock for a fire. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-8 + */ +final class FireSupport { + + /** + * Constructor. + * + * @param RetryHandler $retry The retry policy. + * @param ExportNotifier $notifier Failure notifications. + * @param IUserManager $users Whether the creator is enabled. + * @param IRootFolder $rootFolder Artefacts read back for a retry. + * @param ITimeFactory $time The clock. + */ + public function __construct( + public readonly RetryHandler $retry, + public readonly ExportNotifier $notifier, + public readonly IUserManager $users, + public readonly IRootFolder $rootFolder, + public readonly ITimeFactory $time, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ScheduledExport/FireTrigger.php b/lib/Service/ScheduledExport/FireTrigger.php new file mode 100644 index 000000000..d10f434a2 --- /dev/null +++ b/lib/Service/ScheduledExport/FireTrigger.php @@ -0,0 +1,80 @@ +<?php + +/** + * FireTrigger + * + * Who or what fired a scheduled export: the schedule, or a user's "Run now" + * (REQ-SCH-009 records `triggeredBy=manual` and `triggeredByUser`). + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +/** + * The trigger of one fire. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-009-manual-run-now-and-preview-actions + */ +final class FireTrigger { + + /** + * Constructor. + * + * @param string $kind `schedule` or `manual`. + * @param string|null $userId The user who pressed "Run now", for a manual fire. + */ + private function __construct( + public readonly string $kind, + public readonly ?string $userId, + ) { + }//end __construct() + + /** + * A fire by the background runner. + * + * @return self + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-002-background-runner-fires-schedules-without-an-active-browser-session + */ + public static function schedule(): self { + return new self(kind: 'schedule', userId: null); + }//end schedule() + + /** + * A "Run now" by a user. + * + * @param string $userId The user. + * + * @return self + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-009-manual-run-now-and-preview-actions + */ + public static function manual(string $userId): self { + return new self(kind: 'manual', userId: $userId); + }//end manual() + + /** + * Whether this is a scheduled fire. + * + * @return bool + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-009-manual-run-now-and-preview-actions + */ + public function isScheduled(): bool { + return $this->kind === 'schedule'; + }//end isScheduled() +}//end class diff --git a/lib/Service/ScheduledExport/HeadlessRenderer.php b/lib/Service/ScheduledExport/HeadlessRenderer.php new file mode 100644 index 000000000..266355e15 --- /dev/null +++ b/lib/Service/ScheduledExport/HeadlessRenderer.php @@ -0,0 +1,130 @@ +<?php + +/** + * HeadlessRenderer + * + * The PDF and PNG half of a render (REQ-SCH-003): the subject's page is + * printed or captured by a headless Chromium. The browser is an operator + * choice, configured as the app value `export_chromium_binary`; without it + * PDF and PNG targets fail with a clear reason while CSV and XLSX still + * render. Rendering happens in the background job, one at a time (design, + * Risks). + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use OCP\IAppConfig; + +/** + * Prints or captures a page with headless Chromium. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ +class HeadlessRenderer { + + public const CONFIG_BINARY = 'export_chromium_binary'; + + private const TIMEOUT_SECONDS = 120; + + /** + * Constructor. + * + * @param IAppConfig $appConfig Holds the browser path. + */ + public function __construct( + private readonly IAppConfig $appConfig, + ) { + }//end __construct() + + /** + * The bytes of a page as PDF or PNG. + * + * @param string $url The page. + * @param string $format `pdf` or `png`. + * @param array<string, mixed> $options PNG: `width`, `height`, `dpi`. + * + * @return string + * + * @throws RenderException When no browser is configured or the browser fails. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ + public function capture(string $url, string $format, array $options = []): string { + $binary = $this->appConfig->getValueString('launchpad', self::CONFIG_BINARY, ''); + if ($binary === '' || is_executable($binary) === false) { + throw new RenderException('No headless browser is configured for PDF and PNG exports'); + } + + $out = tempnam(sys_get_temp_dir(), 'lpr'); + if ($out === false) { + throw new RenderException('The render could not be written'); + } + + $command = $this->command(binary: $binary, request: ['url' => $url, 'format' => $format, 'options' => $options, 'out' => $out]); + $process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + if (is_resource($process) === false) { + throw new RenderException('The headless browser could not be started'); + } + + stream_get_contents($pipes[1]); + stream_get_contents($pipes[2]); + $exit = proc_close($process); + $bytes = ''; + if (is_file($out) === true) { + $bytes = (string)file_get_contents($out); + unlink($out); + } + + if ($exit !== 0 || $bytes === '') { + throw new RenderException('The headless browser failed to render the ' . strtoupper($format)); + } + + return $bytes; + }//end capture() + + /** + * The browser command line for one capture, as an argument list (no shell). + * + * @param string $binary The browser. + * @param array<string, mixed> $request `url`, `format`, `options` and the `out` file. + * + * @return list<string> + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ + public function command(string $binary, array $request): array { + $options = (array)($request['options'] ?? []); + $command = [$binary, '--headless', '--no-sandbox', '--disable-gpu', '--hide-scrollbars', '--timeout=' . (self::TIMEOUT_SECONDS * 1000)]; + + if ($request['format'] === 'png') { + $width = max(320, (int)($options['width'] ?? 1920)); + $height = max(240, (int)($options['height'] ?? 1080)); + $scale = max(1, (int)($options['dpi'] ?? 96)) / 96; + $command[] = '--window-size=' . $width . ',' . $height; + $command[] = '--force-device-scale-factor=' . rtrim(rtrim(number_format($scale, 2, '.', ''), '0'), '.'); + $command[] = '--screenshot=' . $request['out']; + $command[] = (string)$request['url']; + return $command; + } + + $command[] = '--no-pdf-header-footer'; + $command[] = '--print-to-pdf=' . $request['out']; + $command[] = (string)$request['url']; + return $command; + }//end command() +}//end class diff --git a/lib/Service/ScheduledExport/InvalidFilterContextException.php b/lib/Service/ScheduledExport/InvalidFilterContextException.php new file mode 100644 index 000000000..b965c94f8 --- /dev/null +++ b/lib/Service/ScheduledExport/InvalidFilterContextException.php @@ -0,0 +1,33 @@ +<?php + +/** + * InvalidFilterContextException + * + * A recipient's filter context names a field the subject's data does not + * have (REQ-SCH-004): that recipient fails, the others still run. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +/** + * A filter context the subject cannot satisfy. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-004-per-recipient-filter-context + */ +class InvalidFilterContextException extends RenderException { +}//end class diff --git a/lib/Service/ScheduledExport/RenderException.php b/lib/Service/ScheduledExport/RenderException.php new file mode 100644 index 000000000..fedbee2e2 --- /dev/null +++ b/lib/Service/ScheduledExport/RenderException.php @@ -0,0 +1,35 @@ +<?php + +/** + * RenderException + * + * A render that could not be produced: no headless browser, a missing + * subject, or a browser that failed (REQ-SCH-003). + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use RuntimeException; + +/** + * Why a render failed; the message is safe to show and to record. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ +class RenderException extends RuntimeException { +}//end class diff --git a/lib/Service/ScheduledExport/RenderPipeline.php b/lib/Service/ScheduledExport/RenderPipeline.php new file mode 100644 index 000000000..a0dfea89a --- /dev/null +++ b/lib/Service/ScheduledExport/RenderPipeline.php @@ -0,0 +1,234 @@ +<?php + +/** + * RenderPipeline + * + * One render of an export for one filter context (tasks.md task 4, + * REQ-SCH-003): one artefact per render target, PDF and PNG from the page, + * CSV and XLSX from the subject's tables. A fire's artefacts are written to + * the export creator's Files under `Apps/LaunchPad/Exports/{exportId}/` + * (design D3); a preview returns them without writing. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use DateTimeInterface; +use OCP\Files\Folder; +use OCP\Files\NotFoundException; +use Throwable; + +/** + * Renders the targets of an export. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-4 + */ +class RenderPipeline { + + public const EXPORT_FOLDER = 'Apps/LaunchPad/Exports'; + + /** + * Constructor. + * + * @param SubjectTables $tables The subject's tabular data. + * @param TabularWriter $writer CSV and XLSX. + * @param HeadlessRenderer $browser PDF and PNG. + * @param RenderServices $services Files, URLs and the clock. + */ + public function __construct( + private readonly SubjectTables $tables, + private readonly TabularWriter $writer, + private readonly HeadlessRenderer $browser, + private readonly RenderServices $services, + ) { + }//end __construct() + + /** + * Render every target and store the artefacts in the creator's Files. + * + * @param array<string, mixed> $export The export. + * @param array<string, mixed> $filterContext The filter context of this render. + * + * @return list<RenderResult> + * + * @throws RenderException When a target cannot be rendered or stored. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-4 + */ + public function render(array $export, array $filterContext): array { + $folder = $this->folder(export: $export); + + return array_map(function (RenderResult $result) use ($folder): RenderResult { + try { + $file = $folder->newFile($this->freeName(folder: $folder, name: $result->filename), $result->content); + } catch (Throwable) { + throw new RenderException('The ' . strtoupper($result->format) . ' could not be stored in Files'); + } + + // The archive copy may be renamed to stay unique; recipients get the name the pattern made. + return new RenderResult(format: $result->format, filename: $result->filename, content: $result->content, storagePath: $file->getPath()); + }, $this->preview(export: $export, filterContext: $filterContext)); + }//end render() + + /** + * Render every target without storing anything (REQ-SCH-009 Preview). + * + * @param array<string, mixed> $export The export. + * @param array<string, mixed> $filterContext The filter context of this render. + * + * @return list<RenderResult> + * + * @throws RenderException When a target cannot be rendered. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-009-manual-run-now-and-preview-actions + */ + public function preview(array $export, array $filterContext): array { + $now = $this->services->time->now(); + $tables = null; + $results = []; + foreach ((array)($export['renderTargets'] ?? []) as $target) { + $format = (string)($target['format'] ?? ''); + $options = (array)($target['formatOptions'] ?? []); + if (in_array($format, ['csv', 'xlsx'], true) === true) { + $tables ??= $this->tables->tables(export: $export, filterContext: $filterContext); + } + + $content = match ($format) { + 'csv' => $this->writer->csv(tables: $tables, options: $options), + 'xlsx' => $this->writer->xlsx(tables: $tables, cover: [ + 'name' => (string)($export['name'] ?? ''), + 'runAt' => $now->format(DateTimeInterface::ATOM), + 'sheetPerWidget' => ($options['sheetPerWidget'] ?? true) !== false, + ]), + 'pdf', 'png' => $this->browser->capture(url: $this->pageUrl(export: $export, filterContext: $filterContext), format: $format, options: $options), + default => throw new RenderException('Unknown render format: ' . $format), + }; + + $name = $this->filename(pattern: (string)($target['filenamePattern'] ?? '{name}-{date}.{ext}'), export: $export, format: $format); + $results[] = new RenderResult(format: $format, filename: $name, content: $content); + }//end foreach + + return $results; + }//end preview() + + /** + * A file name from a target's pattern: `{name}`, `{date}`, `{recipient}` + * and `{ext}`, with path separators and control characters removed. + * + * @param string $pattern The pattern. + * @param array<string, mixed> $export The export. + * @param string $format The format, its extension. + * + * @return string + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-4 + */ + public function filename(string $pattern, array $export, string $format): string { + $name = strtr($pattern, [ + '{name}' => (string)($export['name'] ?? 'export'), + '{date}' => $this->services->time->now()->format('Y-m-d'), + '{recipient}' => (string)($export['recipientLabel'] ?? ''), + '{ext}' => $format, + ]); + $name = trim((string)preg_replace('/[\/\\\\\x00-\x1F]+/', '-', $name), " .-"); + if ($name === '') { + $name = 'export'; + } + + if (str_ends_with(strtolower($name), '.' . $format) === false) { + $name .= '.' . $format; + } + + return $name; + }//end filename() + + /** + * The page the browser prints: the dashboard, with the filters as a query. + * + * @param array<string, mixed> $export The export. + * @param array<string, mixed> $filterContext The filters. + * + * @return string + */ + private function pageUrl(array $export, array $filterContext): string { + $query = ['export' => '1', 'subject' => (string)($export['subjectType'] ?? ''), 'id' => (string)($export['subjectId'] ?? '')]; + if ($filterContext !== []) { + $query['filters'] = (string)json_encode($filterContext); + } + + return $this->services->urls->linkToRouteAbsolute('launchpad.page.index') . '?' . http_build_query($query); + }//end pageUrl() + + /** + * The export's folder in its creator's Files, created when missing. + * + * @param array<string, mixed> $export The export. + * + * @return Folder + * + * @throws RenderException When the creator has no Files area. + */ + private function folder(array $export): Folder { + try { + $folder = $this->services->rootFolder->getUserFolder((string)($export['createdBy'] ?? '')); + foreach (explode('/', self::EXPORT_FOLDER . '/' . (string)($export['id'] ?? 'unknown')) as $part) { + try { + $next = $folder->get($part); + } catch (NotFoundException) { + $next = $folder->newFolder($part); + } + + if (($next instanceof Folder) === false) { + throw new RenderException('The export folder is not a folder'); + } + + $folder = $next; + } + } catch (RenderException $e) { + throw $e; + } catch (Throwable) { + throw new RenderException('The export folder could not be opened in Files'); + } + + return $folder; + }//end folder() + + /** + * The name itself, or `name (2).ext` and onward when it is taken: a fire never overwrites. + * + * @param Folder $folder The folder. + * @param string $name The wanted name. + * + * @return string + */ + private function freeName(Folder $folder, string $name): string { + $dot = strrpos($name, '.'); + $stem = $name; + $ext = ''; + if ($dot !== false) { + $stem = substr($name, 0, $dot); + $ext = substr($name, $dot); + } + + $try = $name; + for ($n = 2; $folder->nodeExists($try) === true; $n++) { + $try = $stem . ' (' . $n . ')' . $ext; + } + + return $try; + }//end freeName() +}//end class diff --git a/lib/Service/ScheduledExport/RenderResult.php b/lib/Service/ScheduledExport/RenderResult.php new file mode 100644 index 000000000..f43c563c1 --- /dev/null +++ b/lib/Service/ScheduledExport/RenderResult.php @@ -0,0 +1,95 @@ +<?php + +/** + * RenderResult + * + * One rendered artefact (REQ-SCH-003): its format, size, sha256, where it + * was stored, and its bytes for channels that attach or upload it. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +/** + * A rendered artefact. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ +final class RenderResult { + + private const MIME = [ + 'pdf' => 'application/pdf', + 'png' => 'image/png', + 'csv' => 'text/csv', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ]; + + /** + * Constructor. + * + * @param string $format `pdf`, `png`, `csv` or `xlsx`. + * @param string $filename The file name from the target's pattern. + * @param string $content The bytes. + * @param string|null $storagePath Where it was written in Files, or null for a preview. + */ + public function __construct( + public readonly string $format, + public readonly string $filename, + public readonly string $content, + public readonly ?string $storagePath = null, + ) { + }//end __construct() + + /** + * The hex sha256 of the bytes. + * + * @return string + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-008-audit-row-per-run-with-hash-and-delivery-outcome + */ + public function sha256(): string { + return hash('sha256', $this->content); + }//end sha256() + + /** + * The media type of the format. + * + * @return string + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-005-email-nextcloud-files-webhook-and-sftp-delivery-channels + */ + public function mimeType(): string { + return self::MIME[$this->format] ?? 'application/octet-stream'; + }//end mimeType() + + /** + * The artefact as the run-row records it. + * + * @return array{format: string, sizeBytes: int, sha256: string, storagePath: string|null, filename: string} + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-008-audit-row-per-run-with-hash-and-delivery-outcome + */ + public function toAudit(): array { + return [ + 'format' => $this->format, + 'sizeBytes' => strlen($this->content), + 'sha256' => $this->sha256(), + 'storagePath' => $this->storagePath, + 'filename' => $this->filename, + ]; + }//end toAudit() +}//end class diff --git a/lib/Service/ScheduledExport/RenderServices.php b/lib/Service/ScheduledExport/RenderServices.php new file mode 100644 index 000000000..2da1b6981 --- /dev/null +++ b/lib/Service/ScheduledExport/RenderServices.php @@ -0,0 +1,52 @@ +<?php + +/** + * RenderServices + * + * The Nextcloud services a render needs: the root folder, the URL + * generator and the clock (kept together to keep the pipeline's + * constructor short). + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Files\IRootFolder; +use OCP\IURLGenerator; + +/** + * Files, URLs and the clock for the render pipeline. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-4 + */ +final class RenderServices { + + /** + * Constructor. + * + * @param IRootFolder $rootFolder The users' Files. + * @param IURLGenerator $urls The page URL. + * @param ITimeFactory $time The clock. + */ + public function __construct( + public readonly IRootFolder $rootFolder, + public readonly IURLGenerator $urls, + public readonly ITimeFactory $time, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ScheduledExport/RetentionJanitor.php b/lib/Service/ScheduledExport/RetentionJanitor.php new file mode 100644 index 000000000..fbb2116df --- /dev/null +++ b/lib/Service/ScheduledExport/RetentionJanitor.php @@ -0,0 +1,159 @@ +<?php + +/** + * RetentionJanitor + * + * Retention of scheduled exports (tasks.md task 9, REQ-SCH-007): after + * `keepArtefactsForDays` a run's files are deleted from Files and their + * `storagePath` nulled, the hashes and delivery outcomes kept; after + * `keepAuditForDays` the run-row itself is deleted through OpenRegister's + * standard delete, its remaining files with it. An explicit null keeps + * forever; a missing value takes the schema default (30 and 365 days). + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Files\IRootFolder; +use Throwable; + +/** + * Purges expired artefacts and run-rows. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-007-retention-policy-enforced-by-janitor + * @SuppressWarnings(PHPMD.CyclomaticComplexity) sweep() applies both retention periods to every row in one pass. + */ +class RetentionJanitor { + + public const DEFAULT_ARTEFACT_DAYS = 30; + + public const DEFAULT_AUDIT_DAYS = 365; + + /** + * Constructor. + * + * @param ExportObjectStore $store Reads each run's export for its retention. + * @param AuditLog $log The run-rows. + * @param IRootFolder $rootFolder Deletes the artefact files. + * @param ITimeFactory $time The clock. + */ + public function __construct( + private readonly ExportObjectStore $store, + private readonly AuditLog $log, + private readonly IRootFolder $rootFolder, + private readonly ITimeFactory $time, + ) { + }//end __construct() + + /** + * One pass over every run-row. + * + * @return array{artefactsPurged: int, runsDeleted: int} + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-9 + */ + public function sweep(): array { + $now = $this->time->now()->getTimestamp(); + $exports = []; + $purged = 0; + $deleted = 0; + foreach ($this->log->allRuns() as $run) { + $started = strtotime((string)($run['startedAt'] ?? '')); + if ($started === false || ($run['status'] ?? null) === 'running') { + continue; + } + + $exportId = (string)($run['exportId'] ?? ''); + $exports[$exportId] ??= $this->store->find(schema: ExportObjectStore::SCHEMA_EXPORT, uuid: $exportId) ?? []; + $retention = (array)($exports[$exportId]['retention'] ?? []); + $ageDays = ($now - $started) / 86400; + + $auditDays = $this->days(retention: $retention, key: 'keepAuditForDays', default: self::DEFAULT_AUDIT_DAYS); + if ($auditDays !== null && $ageDays > $auditDays) { + $this->deleteFiles(run: $run); + $deleted += (int)$this->log->delete(runId: (string)($run['id'] ?? '')); + continue; + } + + $artefactDays = $this->days(retention: $retention, key: 'keepArtefactsForDays', default: self::DEFAULT_ARTEFACT_DAYS); + if ($artefactDays !== null && $ageDays > $artefactDays && $this->deleteFiles(run: $run) > 0) { + foreach (array_keys((array)$run['renderArtefacts']) as $i) { + $run['renderArtefacts'][$i]['storagePath'] = null; + } + + $this->log->update(run: $run); + $purged++; + } + }//end foreach + + return ['artefactsPurged' => $purged, 'runsDeleted' => $deleted]; + }//end sweep() + + /** + * A retention period: the value when it is a positive integer, null when explicitly null (forever), else the default. + * + * @param array<string, mixed> $retention The export's retention. + * @param string $key The setting. + * @param int $default Its default. + * + * @return int|null + */ + private function days(array $retention, string $key, int $default): ?int { + if (array_key_exists($key, $retention) === true && $retention[$key] === null) { + return null; + } + + if (is_int($retention[$key] ?? null) === true && $retention[$key] >= 1) { + return $retention[$key]; + } + + return $default; + }//end days() + + /** + * Delete a run's stored files; a file already gone counts as deleted. + * + * @param array<string, mixed> $run The run-row. + * + * @return int How many paths were cleared. + */ + private function deleteFiles(array $run): int { + $cleared = 0; + foreach ((array)($run['renderArtefacts'] ?? []) as $artefact) { + $path = null; + if (is_array($artefact) === true) { + $path = $artefact['storagePath'] ?? null; + } + + if (is_string($path) === false || $path === '') { + continue; + } + + try { + $this->rootFolder->get($path)->delete(); + } catch (Throwable) { + // Gone already, or not deletable: the path is cleared either way. + unset($path); + } + + $cleared++; + } + + return $cleared; + }//end deleteFiles() +}//end class diff --git a/lib/Service/ScheduledExport/ScheduledExportService.php b/lib/Service/ScheduledExport/ScheduledExportService.php new file mode 100644 index 000000000..9e2c5a209 --- /dev/null +++ b/lib/Service/ScheduledExport/ScheduledExportService.php @@ -0,0 +1,547 @@ +<?php + +/** + * ScheduledExportService + * + * CRUD of scheduled exports (tasks.md task 3) over the `scheduled_export` + * schema in OpenRegister: who may see an export (its owner, or an + * administrator), validation of what is saved, `nextRunAt` recomputed + * whenever the recurrence or time zone changes (REQ-SCH-001), and channel + * secrets encrypted at rest and redacted on every read (REQ-SCH-010). + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use DateTimeInterface; +use DateTimeZone; +use InvalidArgumentException; +use OCA\LaunchPad\Service\RecurrenceResolver; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\IGroupManager; +use OCP\Security\ICrypto; +use Throwable; + +/** + * Visibility, validation, scheduling and secret handling of exports. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) Validation and secret sealing of one export document. + * @SuppressWarnings(PHPMD.CyclomaticComplexity) save() merges, validates, seals and reschedules in one pass. + */ +class ScheduledExportService { + + /** + * What a secret reads as through the API. + */ + public const REDACTED = '********'; + + /** + * The `channelConfig` keys that hold a secret. + */ + public const SECRET_KEYS = ['password', 'privateKey', 'signingSecret']; + + public const DEFAULT_TIMEZONE = 'Europe/Amsterdam'; + + private const ENCRYPTED_PREFIX = 'enc:'; + + private const FORMATS = ['pdf', 'png', 'csv', 'xlsx']; + + private const CHANNELS = ['email', 'nextcloudFiles', 'webhook', 'sftp']; + + /** + * Fields the runner owns; a save by a user never sets them. + */ + private const RUNNER_FIELDS = ['nextRunAt', 'lastRunAt', 'lastRunStatus', 'createdBy']; + + /** + * Constructor. + * + * @param ExportObjectStore $store The OpenRegister object store. + * @param RecurrenceResolver $recurrence Computes `nextRunAt`. + * @param ICrypto $crypto Encrypts channel secrets at rest. + * @param IGroupManager $groups Answers whether a user is an administrator. + * @param ITimeFactory $time The clock. + */ + public function __construct( + private readonly ExportObjectStore $store, + private readonly RecurrenceResolver $recurrence, + private readonly ICrypto $crypto, + private readonly IGroupManager $groups, + private readonly ITimeFactory $time, + ) { + }//end __construct() + + /** + * The exports a user may see: their own, or every export for an administrator. + * + * @param string $userId The user. + * + * @return list<array<string, mixed>> The exports, secrets redacted. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function findVisible(string $userId): array { + $filters = []; + if ($this->groups->isAdmin($userId) === false) { + $filters['@self'] = ['owner' => $userId]; + } + + $exports = $this->store->findAll(schema: ExportObjectStore::SCHEMA_EXPORT, filters: $filters); + $visible = array_filter($exports, fn (array $export): bool => $this->isVisibleTo(export: $export, userId: $userId)); + + return array_values(array_map(fn (array $export): array => $this->redact(export: $export), $visible)); + }//end findVisible() + + /** + * One export the user may see. + * + * @param string $id The export uuid. + * @param string $userId The user. + * + * @return array<string, mixed> The export, secrets redacted. + * + * @throws DoesNotExistException When it does not exist or is not the user's to see. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function findOne(string $id, string $userId): array { + return $this->redact(export: $this->stored(id: $id, userId: $userId)); + }//end findOne() + + /** + * Create an export, or update one the user may see. A partial update is + * merged onto the stored export; a secret sent back as the redacted + * placeholder keeps the stored secret. + * + * @param array<string, mixed> $export The export; an `id` updates that export. + * @param string $userId The user saving it. + * + * @return array<string, mixed> The saved export, secrets redacted. + * + * @throws DoesNotExistException When the `id` is not an export the user may see. + * @throws InvalidArgumentException When the export is not valid. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function save(array $export, string $userId): array { + $existing = null; + if (is_string($export['id'] ?? null) === true && $export['id'] !== '') { + $existing = $this->stored(id: $export['id'], userId: $userId); + } + + foreach (self::RUNNER_FIELDS as $field) { + unset($export[$field]); + } + + $merged = self::withDefaults(export: array_merge($existing ?? [], $export)); + // An export stored before `createdBy` was a schema property lost it; its owner made it. + $merged['createdBy'] = $existing['createdBy'] ?? $existing['owner'] ?? $userId; + + $errors = $this->validate(export: $merged); + if ($errors !== []) { + throw new InvalidArgumentException(implode(' ', $errors)); + } + + $merged['recipients'] = $this->sealSecrets(recipients: $merged['recipients'], stored: $existing['recipients'] ?? []); + // The runner fields were stripped from the input above, so the only + // readOnly values this save can change are the ones stamped here. + $stamps = ($existing['createdBy'] ?? null) !== $merged['createdBy']; + if (self::needsReschedule(existing: $existing, merged: $merged) === true) { + $merged['nextRunAt'] = $this->nextRunAfter(export: $merged, after: $this->time->now()); + $stamps = true; + } + + if ($stamps === true) { + return $this->redact(export: $this->store->saveAsSystem(schema: ExportObjectStore::SCHEMA_EXPORT, data: $merged)); + } + + return $this->redact(export: $this->store->save(schema: ExportObjectStore::SCHEMA_EXPORT, data: $merged)); + }//end save() + + /** + * The export with `enabled` defaulting to true and the run time zone to the default. + * + * @param array<string, mixed> $export The export being saved. + * + * @return array<string, mixed> + */ + private static function withDefaults(array $export): array { + $export['enabled'] = ($export['enabled'] ?? true) !== false; + if (is_string($export['runTimezone'] ?? null) === false || $export['runTimezone'] === '') { + $export['runTimezone'] = self::DEFAULT_TIMEZONE; + } + + return $export; + }//end withDefaults() + + /** + * Whether the next run must be computed again: a new export, a changed + * recurrence or time zone, or no next run yet. + * + * @param array<string, mixed>|null $existing The stored export, null for a new one. + * @param array<string, mixed> $merged The export being saved. + * + * @return bool + */ + private static function needsReschedule(?array $existing, array $merged): bool { + if ($existing === null || empty($existing['nextRunAt']) === true) { + return true; + } + + return ($existing['recurrence'] ?? null) !== $merged['recurrence'] + || ($existing['runTimezone'] ?? null) !== $merged['runTimezone']; + }//end needsReschedule() + + /** + * Soft-delete an export the user may see. + * + * @param string $id The export uuid. + * @param string $userId The user. + * + * @return void + * + * @throws DoesNotExistException When it is not an export the user may see. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function delete(string $id, string $userId): void { + $this->stored(id: $id, userId: $userId); + $this->store->delete(uuid: $id); + }//end delete() + + /** + * Switch an export on or off. + * + * @param string $id The export uuid. + * @param bool $enabled Whether it fires on schedule. + * @param string $userId The user. + * + * @return array<string, mixed> The saved export. + * + * @throws DoesNotExistException When it is not an export the user may see. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function setEnabled(string $id, bool $enabled, string $userId): array { + return $this->save(export: ['id' => $id, 'enabled' => $enabled], userId: $userId); + }//end setEnabled() + + /** + * The stored export with its secrets decrypted, for the dispatcher only. + * + * @param string $id The export uuid. + * + * @return array<string, mixed>|null The export, or null when it does not exist. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-010-header-signing-and-credential-vaulting + */ + public function forDispatch(string $id): ?array { + $export = $this->store->find(schema: ExportObjectStore::SCHEMA_EXPORT, uuid: $id); + if ($export === null) { + return null; + } + + $reveal = fn (string $value): string => $this->reveal(value: $value); + $export['recipients'] = array_map(fn ($recipient) => $this->mapSecrets(recipient: $recipient, map: $reveal), $export['recipients'] ?? []); + return $export; + }//end forDispatch() + + /** + * The enabled exports whose `nextRunAt` has passed. + * + * @param DateTimeInterface $now The moment of the check. + * + * @return list<array<string, mixed>> The due exports, as stored. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-002-background-runner-fires-schedules-without-an-active-browser-session + */ + public function due(DateTimeInterface $now): array { + $exports = $this->store->findAll(schema: ExportObjectStore::SCHEMA_EXPORT, filters: ['enabled' => true]); + + return array_values(array_filter($exports, static function (array $export) use ($now): bool { + $next = false; + if (is_string($export['nextRunAt'] ?? null) === true) { + $next = strtotime($export['nextRunAt']); + } + + return ($export['enabled'] ?? true) !== false && $next !== false && $next <= $now->getTimestamp(); + })); + }//end due() + + /** + * Record a fire on the export: its outcome and, for a scheduled fire, the next run. + * + * @param array<string, mixed> $export The export as stored. + * @param array<string, mixed> $fields `lastRunAt`, `lastRunStatus` and optionally `nextRunAt`. + * + * @return array<string, mixed> The saved export. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-002-background-runner-fires-schedules-without-an-active-browser-session + */ + public function recordFire(array $export, array $fields): array { + $stored = $this->store->find(schema: ExportObjectStore::SCHEMA_EXPORT, uuid: (string)($export['id'] ?? '')) ?? $export; + $keep = array_intersect_key($fields, array_flip(['lastRunAt', 'lastRunStatus', 'nextRunAt'])); + + return $this->store->saveAsSystem(schema: ExportObjectStore::SCHEMA_EXPORT, data: array_merge($stored, $keep)); + }//end recordFire() + + /** + * The export's next fire strictly after a moment, as an ATOM string. + * + * @param array<string, mixed> $export The export. + * @param DateTimeInterface $after The moment to look past. + * + * @return string + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-001-recurrence-editor-produces-deterministic-next-run-timestamps + */ + public function nextRunAfter(array $export, DateTimeInterface $after): string { + $timezone = (string)($export['runTimezone'] ?? self::DEFAULT_TIMEZONE); + return $this->recurrence->nextRunAt(recurrence: (array)$export['recurrence'], timezone: $timezone, after: $after)->format(DateTimeInterface::ATOM); + }//end nextRunAfter() + + /** + * Whether a user may see an export: its owner, its creator, or an administrator. + * + * @param array<string, mixed> $export The export. + * @param string $userId The user. + * + * @return bool + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-21 + */ + public function isVisibleTo(array $export, string $userId): bool { + if ($userId === '') { + return false; + } + + if (($export['owner'] ?? null) === $userId || ($export['createdBy'] ?? null) === $userId) { + return true; + } + + return $this->groups->isAdmin($userId); + }//end isVisibleTo() + + /** + * What is wrong with an export, or nothing. + * + * @param array<string, mixed> $export The export. + * + * @return list<string> One sentence per problem. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-3 + */ + public function validate(array $export): array { + $errors = array_merge( + self::identityErrors(export: $export), + self::listErrors(items: $export['renderTargets'] ?? null, rule: ['key' => 'format', 'allowed' => self::FORMATS, 'label' => 'render target']), + self::listErrors(items: $export['recipients'] ?? null, rule: ['key' => 'channel', 'allowed' => self::CHANNELS, 'label' => 'recipient']) + ); + + if (is_array($export['recurrence'] ?? null) === false) { + return array_merge($errors, ['The recurrence is required.']); + } + + try { + new DateTimeZone((string)($export['runTimezone'] ?? self::DEFAULT_TIMEZONE)); + } catch (Throwable) { + $errors[] = 'The time zone is not a valid IANA time zone.'; + } + + return array_merge($errors, $this->recurrence->validate(recurrence: $export['recurrence'])); + }//end validate() + + /** + * Problems with the export's name, subject type and subject. + * + * @param array<string, mixed> $export The export. + * + * @return list<string> + */ + private static function identityErrors(array $export): array { + $errors = []; + $name = $export['name'] ?? null; + if (is_string($name) === false || trim($name) === '' || mb_strlen($name) > 255) { + $errors[] = 'The name is required and at most 255 characters.'; + } + + if (in_array($export['subjectType'] ?? null, ['dashboard', 'widget'], true) === false) { + $errors[] = 'The subject type must be dashboard or widget.'; + } + + if (is_string($export['subjectId'] ?? null) === false || $export['subjectId'] === '') { + $errors[] = 'The subject is required.'; + } + + return $errors; + }//end identityErrors() + + /** + * Problems with a non-empty list of objects that each carry an allowed value under a key. + * + * @param mixed $items The list. + * @param array{key: string, allowed: list<string>, label: string} $rule The discriminating key, + * its allowed values and + * what one item is called. + * + * @return list<string> + */ + private static function listErrors(mixed $items, array $rule): array { + if (is_array($items) === false || $items === [] || array_is_list($items) === false) { + return ['At least one ' . $rule['label'] . ' is required.']; + } + + foreach ($items as $item) { + if (is_array($item) === false || in_array($item[$rule['key']] ?? null, $rule['allowed'], true) === false) { + return ['Every ' . $rule['label'] . ' needs a ' . $rule['key'] . ' of ' . implode(', ', $rule['allowed']) . '.']; + } + } + + return []; + }//end listErrors() + + /** + * The stored export, refused as not found unless the user may see it. + * + * @param string $id The export uuid. + * @param string $userId The user. + * + * @return array<string, mixed> + * + * @throws DoesNotExistException When it does not exist or is not the user's to see. + */ + private function stored(string $id, string $userId): array { + $export = $this->store->find(schema: ExportObjectStore::SCHEMA_EXPORT, uuid: $id); + if ($export === null || $this->isVisibleTo(export: $export, userId: $userId) === false) { + throw new DoesNotExistException('Scheduled export not found'); + } + + return $export; + }//end stored() + + /** + * Recipients with every new secret encrypted, and a redacted placeholder + * replaced by the stored secret of the recipient at the same position. + * + * @param list<array<string, mixed>> $recipients The recipients being saved. + * @param list<array<string, mixed>> $stored The recipients as stored. + * + * @return list<array<string, mixed>> + */ + private function sealSecrets(array $recipients, array $stored): array { + foreach ($recipients as $index => $recipient) { + $config = []; + if (is_array($recipient['channelConfig'] ?? null) === true) { + $config = $recipient['channelConfig']; + } + + $previous = []; + if (is_array($stored[$index]['channelConfig'] ?? null) === true) { + $previous = $stored[$index]['channelConfig']; + } + + $recipients[$index]['channelConfig'] = $this->sealConfig(config: $config, previous: $previous); + } + + return $recipients; + }//end sealSecrets() + + /** + * One channel config with every new secret encrypted, and a redacted + * placeholder replaced by the stored secret (or dropped without one). + * + * @param array<string, mixed> $config The config being saved. + * @param array<string, mixed> $previous The config as stored. + * + * @return array<string, mixed> + */ + private function sealConfig(array $config, array $previous): array { + foreach (self::SECRET_KEYS as $key) { + $value = $config[$key] ?? null; + if (is_string($value) === false || $value === '') { + continue; + } + + if ($value === self::REDACTED) { + unset($config[$key]); + if (is_string($previous[$key] ?? null) === true) { + $config[$key] = $previous[$key]; + } + + continue; + } + + if (str_starts_with($value, self::ENCRYPTED_PREFIX) === false) { + $config[$key] = self::ENCRYPTED_PREFIX . $this->crypto->encrypt($value); + } + } + + return $config; + }//end sealConfig() + + /** + * The export as the API shows it: every secret replaced by the placeholder. + * + * @param array<string, mixed> $export The export. + * + * @return array<string, mixed> + */ + private function redact(array $export): array { + $redacted = static fn (): string => self::REDACTED; + $export['recipients'] = array_map(fn ($recipient) => $this->mapSecrets(recipient: $recipient, map: $redacted), $export['recipients'] ?? []); + return $export; + }//end redact() + + /** + * A recipient with a function applied to each secret it holds. + * + * @param mixed $recipient The recipient. + * @param callable $map Turns a stored secret into what is returned. + * + * @return mixed + */ + private function mapSecrets(mixed $recipient, callable $map): mixed { + if (is_array($recipient) === false || is_array($recipient['channelConfig'] ?? null) === false) { + return $recipient; + } + + foreach (self::SECRET_KEYS as $key) { + if (is_string($recipient['channelConfig'][$key] ?? null) === true && $recipient['channelConfig'][$key] !== '') { + $recipient['channelConfig'][$key] = $map($recipient['channelConfig'][$key]); + } + } + + return $recipient; + }//end mapSecrets() + + /** + * A stored secret decrypted; a value that was never encrypted is returned as is. + * + * @param string $value The stored value. + * + * @return string + */ + private function reveal(string $value): string { + if (str_starts_with($value, self::ENCRYPTED_PREFIX) === false) { + return $value; + } + + return $this->crypto->decrypt(substr($value, strlen(self::ENCRYPTED_PREFIX))); + }//end reveal() +}//end class diff --git a/lib/Service/ScheduledExport/SftpUploader.php b/lib/Service/ScheduledExport/SftpUploader.php new file mode 100644 index 000000000..d74ad7658 --- /dev/null +++ b/lib/Service/ScheduledExport/SftpUploader.php @@ -0,0 +1,181 @@ +<?php + +/** + * SftpUploader + * + * The SFTP channel (REQ-SCH-005): an upload through libcurl's SFTP support + * with the server's host key pinned (`hostKeySha256`, required), then a + * size check of the uploaded file, which the delivery records. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +/** + * Uploads one artefact over SFTP. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-005-email-nextcloud-files-webhook-and-sftp-delivery-channels + */ +class SftpUploader { + + /** + * Upload and confirm the size on the server. + * + * @param array<string, mixed> $config `host`, `port`, `username`, `password` or `privateKey`, `remotePath`, `hostKeySha256`. + * @param RenderResult $artefact The artefact. + * + * @return int The size the server reports for the uploaded file. + * + * @throws DeliveryException When the configuration is incomplete, the upload fails or the sizes differ. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-005-email-nextcloud-files-webhook-and-sftp-delivery-channels + */ + public function upload(array $config, RenderResult $artefact): int { + $keyFile = null; + if (is_string($config['privateKey'] ?? null) === true && $config['privateKey'] !== '') { + $keyFile = tempnam(sys_get_temp_dir(), 'lpk'); + file_put_contents((string)$keyFile, $config['privateKey']); + chmod((string)$keyFile, 0600); + } + + try { + $url = $this->url(config: $config, filename: $artefact->filename); + $stream = fopen('php://temp', 'r+'); + fwrite($stream, $artefact->content); + rewind($stream); + $this->transfer(options: $this->options(config: $config, keyFile: $keyFile) + [ + CURLOPT_URL => $url, + CURLOPT_UPLOAD => true, + CURLOPT_INFILE => $stream, + CURLOPT_INFILESIZE => strlen($artefact->content), + ]); + fclose($stream); + + $check = $this->options(config: $config, keyFile: $keyFile) + [CURLOPT_URL => $url, CURLOPT_NOBODY => true]; + $size = (int)$this->transfer(options: $check, info: CURLINFO_CONTENT_LENGTH_DOWNLOAD); + } finally { + if ($keyFile !== null) { + unlink($keyFile); + } + } + + if ($size !== strlen($artefact->content)) { + throw new DeliveryException('The server reports ' . $size . ' bytes for ' . $artefact->filename . ', expected ' . strlen($artefact->content)); + } + + return $size; + }//end upload() + + /** + * The curl options shared by the upload and the size check. + * + * @param array<string, mixed> $config The channel configuration. + * @param string|null $keyFile The private key file, when key authentication is used. + * + * @return array<int, mixed> + * + * @throws DeliveryException When the host key or the credentials are missing. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-005-email-nextcloud-files-webhook-and-sftp-delivery-channels + */ + public function options(array $config, ?string $keyFile): array { + $fingerprint = (string)($config['hostKeySha256'] ?? ''); + if ($fingerprint === '') { + throw new DeliveryException('SFTP needs the server host key fingerprint (hostKeySha256)'); + } + + $options = [ + CURLOPT_PROTOCOLS => CURLPROTO_SFTP, + CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 => preg_replace('/^SHA256:/', '', $fingerprint), + CURLOPT_CONNECTTIMEOUT => 30, + CURLOPT_TIMEOUT => 300, + CURLOPT_RETURNTRANSFER => true, + ]; + + $user = (string)($config['username'] ?? ''); + if ($keyFile !== null) { + $options[CURLOPT_USERNAME] = $user; + $options[CURLOPT_SSH_AUTH_TYPES] = CURLSSH_AUTH_PUBLICKEY; + $options[CURLOPT_SSH_PRIVATE_KEYFILE] = $keyFile; + return $options; + } + + if (is_string($config['password'] ?? null) === false || $config['password'] === '') { + throw new DeliveryException('SFTP needs a password or a private key'); + } + + $options[CURLOPT_USERPWD] = $user . ':' . $config['password']; + $options[CURLOPT_SSH_AUTH_TYPES] = CURLSSH_AUTH_PASSWORD; + return $options; + }//end options() + + /** + * The sftp:// URL of the remote file. + * + * @param array<string, mixed> $config The channel configuration. + * @param string $filename The file name. + * + * @return string + * + * @throws DeliveryException When the host is missing. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-005-email-nextcloud-files-webhook-and-sftp-delivery-channels + */ + public function url(array $config, string $filename): string { + $host = (string)($config['host'] ?? ''); + if ($host === '' || preg_match('/^[A-Za-z0-9.-]+$/', $host) !== 1) { + throw new DeliveryException('SFTP needs a valid host'); + } + + $segments = array_values(array_filter(explode('/', (string)($config['remotePath'] ?? '')), static fn (string $part): bool => $part !== '')); + if (in_array('..', $segments, true) === true) { + throw new DeliveryException('The SFTP remote path may not contain ..'); + } + + $segments[] = $filename; + return 'sftp://' . $host . ':' . (int)($config['port'] ?? 22) . '/' . implode('/', array_map('rawurlencode', $segments)); + }//end url() + + /** + * Run one curl transfer. + * + * @param array<int, mixed> $options The options. + * @param int|null $info A CURLINFO value to return instead of the body. + * + * @return mixed + * + * @throws DeliveryException When the transfer fails. + */ + private function transfer(array $options, ?int $info = null): mixed { + $handle = curl_init(); + curl_setopt_array($handle, $options); + $body = curl_exec($handle); + $error = curl_error($handle); + $value = $body; + if ($info !== null) { + $value = curl_getinfo($handle, $info); + } + + curl_close($handle); + + if ($body === false) { + throw new DeliveryException('SFTP transfer failed: ' . $error); + } + + return $value; + }//end transfer() +}//end class diff --git a/lib/Service/ScheduledExport/SubjectTables.php b/lib/Service/ScheduledExport/SubjectTables.php new file mode 100644 index 000000000..1c48e0898 --- /dev/null +++ b/lib/Service/ScheduledExport/SubjectTables.php @@ -0,0 +1,332 @@ +<?php + +/** + * SubjectTables + * + * The tabular data behind an export's subject (REQ-SCH-003, REQ-SCH-004): + * one table per visible widget of a LaunchPad dashboard, or the one widget, + * read from LaunchPad's own dashboards and placements: a text widget's + * table, or the rows of objects its content carries (`rows` or `data`), + * with the recipient's filter context applied. A + * filter on a field no table has is refused. A widget with calculated + * fields gets a second table of their values, evaluated on the server over + * the filtered rows, so the export carries what the widget shows. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\WidgetPlacement; +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Service\PermissionService; +use OCP\AppFramework\Db\DoesNotExistException; + +/** + * Widget tables of a dashboard or widget subject. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ +class SubjectTables { + + /** + * Constructor. + * + * @param DashboardMapper $dashboards LaunchPad's dashboards. + * @param WidgetPlacementMapper $placements Their widget placements. + * @param PermissionService $permissions Whether the creator may see the subject. + * @param ExportCalculatedValues $calculated Evaluates the widgets' calculated fields. + */ + public function __construct( + private readonly DashboardMapper $dashboards, + private readonly WidgetPlacementMapper $placements, + private readonly PermissionService $permissions, + private readonly ExportCalculatedValues $calculated = new ExportCalculatedValues(), + ) { + }//end __construct() + + /** + * The subject's tables, filtered. + * + * @param array<string, mixed> $export The export. + * @param array<string, mixed> $filterContext The recipient's filter context. + * + * @return list<array{title: string, headers: list<string>, rows: list<list<mixed>>}> + * + * @throws RenderException When the subject does not exist. + * @throws InvalidFilterContextException When a filter names a field no table has. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-004-per-recipient-filter-context + */ + public function tables(array $export, array $filterContext): array { + $widgets = $this->widgets(export: $export); + $tables = array_map(fn (array $widget): array => $this->table(widget: $widget), $widgets); + + foreach ($filterContext as $field => $value) { + $field = (string)$field; + $hasIt = array_filter($tables, static fn (array $t): bool => in_array($field, $t['headers'], true)); + if ($hasIt === []) { + throw new InvalidFilterContextException('Unknown filter field: ' . $field); + } + + foreach ($tables as $i => $table) { + $column = array_search($field, $table['headers'], true); + if ($column === false) { + continue; + } + + $keep = static fn (array $row): bool => (string)($row[$column] ?? '') === (string)$value; + $tables[$i]['rows'] = array_values(array_filter($table['rows'], $keep)); + } + } + + return $this->withCalculatedTables(widgets: $widgets, tables: $tables); + }//end tables() + + /** + * The tables, each widget's followed by the values of its calculated + * fields: one row, a column per field, headed by the field's label. + * + * A widget's data is its filtered rows, as `rows` (each row by header) + * and `total` (their number), which is what a field can read here. + * + * @param list<array<string, mixed>> $widgets The widgets, in table order. + * @param list<array{title: string, headers: list<string>, rows: list<list<mixed>>}> $tables Their filtered tables. + * + * @return list<array{title: string, headers: list<string>, rows: list<list<mixed>>}> + * + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-20 + */ + private function withCalculatedTables(array $widgets, array $tables): array { + $dataById = []; + foreach ($widgets as $i => $widget) { + $rows = array_map(static fn (array $row): array => array_combine($tables[$i]['headers'], $row), $tables[$i]['rows']); + $dataById[(string) ($widget['id'] ?? $i)] = ['rows' => $rows, 'total' => count($rows)]; + } + + $values = $this->calculated->values(widgets: $widgets, dataById: $dataById); + $out = []; + foreach ($widgets as $i => $widget) { + $out[] = $tables[$i]; + $id = (string) ($widget['id'] ?? $i); + $known = ($values[$id] ?? []); + $fields = array_values( + array_filter( + (array) ($widget['calculatedFields'] ?? []), + static fn (mixed $field): bool => is_array($field) === true && array_key_exists((string) ($field['name'] ?? ''), $known) === true + ) + ); + if ($fields === []) { + continue; + } + + $out[] = [ + 'title' => $tables[$i]['title'] . ': calculated fields', + 'headers' => array_map(static fn (array $field): string => (string) ($field['label'] ?? $field['name']), $fields), + 'rows' => [array_map(static fn (array $field): mixed => $values[$id][(string) $field['name']], $fields)], + ]; + } + + return $out; + }//end withCalculatedTables() + + /** + * The widgets the subject covers, as `{id, title, props, calculatedFields}`: + * the visible placements of a dashboard, or one placement. The render runs + * under the creator's access (REQ-SCH-002): a subject the creator may not + * see reads as gone. + * + * @param array<string, mixed> $export The export. + * + * @return list<array<string, mixed>> + * + * @throws RenderException When the subject does not exist or the creator may not see it. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-002-background-runner-fires-schedules-without-an-active-browser-session + */ + private function widgets(array $export): array { + $subjectId = (string)($export['subjectId'] ?? ''); + $creator = (string)($export['createdBy'] ?? ''); + if (($export['subjectType'] ?? null) === 'dashboard') { + $dashboardId = $this->dashboardId(uuid: $subjectId); + if ($dashboardId === null || $creator === '' || $this->permissions->canViewDashboard(userId: $creator, dashboardId: $dashboardId) === false) { + throw new RenderException('The dashboard of this export no longer exists'); + } + + $visible = array_filter( + $this->placements->findByDashboardId(dashboardId: $dashboardId), + static fn (WidgetPlacement $placement): bool => $placement->getIsVisible() !== 0 + ); + + return array_values(array_map(static fn (WidgetPlacement $placement): array => self::widgetOf(placement: $placement), $visible)); + } + + $placement = $this->placement(id: $subjectId); + if ($placement === null || $creator === '' || $this->permissions->canViewPlacement(userId: $creator, placementId: $placement->getId()) === false) { + throw new RenderException('The widget of this export no longer exists'); + } + + return [self::widgetOf(placement: $placement)]; + }//end widgets() + + /** + * The id of a dashboard by uuid, or null when there is none. + * + * @param string $uuid The dashboard uuid. + * + * @return int|null + */ + private function dashboardId(string $uuid): ?int { + if ($uuid === '') { + return null; + } + + try { + return $this->dashboards->findByUuid(uuid: $uuid)->getId(); + } catch (DoesNotExistException) { + return null; + } + }//end dashboardId() + + /** + * A widget placement by its numeric id, or null when there is none. + * + * @param string $id The placement id. + * + * @return WidgetPlacement|null + */ + private function placement(string $id): ?WidgetPlacement { + if (ctype_digit($id) === false) { + return null; + } + + try { + return $this->placements->find(id: (int)$id); + } catch (DoesNotExistException) { + return null; + } + }//end placement() + + /** + * A placement as the tables read it: its id, the title it shows, its + * content and its calculated fields. + * + * @param WidgetPlacement $placement The placement. + * + * @return array<string, mixed> + */ + private static function widgetOf(WidgetPlacement $placement): array { + $title = (string)($placement->getCustomTitle() ?? ''); + if ($title === '') { + $title = (string)($placement->getTileTitle() ?? ''); + } + + if ($title === '') { + $title = $placement->getWidgetId(); + } + + return [ + 'id' => (string)$placement->getId(), + 'title' => $title, + 'props' => $placement->getContentArray(), + 'calculatedFields' => $placement->getCalculatedFieldsArray(), + ]; + }//end widgetOf() + + /** + * One widget's table: a text widget's table (its first row the headers + * when it has a header row), or rows of objects with the union of their + * keys as headers. + * + * @param array<string, mixed> $widget The widget. + * + * @return array{title: string, headers: list<string>, rows: list<list<mixed>>} + */ + private function table(array $widget): array { + $props = (array)($widget['props'] ?? []); + $title = (string)($props['title'] ?? $widget['title'] ?? 'Widget'); + if (($props['tableMode'] ?? false) === true && is_array($props['tableData']['rows'] ?? null) === true) { + return ['title' => $title] + self::textTable(tableData: (array)$props['tableData']); + } + + $data = $props['rows'] ?? $props['data'] ?? []; + if (is_array($data) === false) { + $data = []; + } + + $data = array_values(array_filter($data, 'is_array')); + + $headers = []; + foreach ($data as $row) { + foreach (array_keys($row) as $key) { + $headers[(string)$key] = true; + } + } + + $headers = array_keys($headers); + $rows = array_map(static fn (array $row): array => array_map(static fn (string $header): mixed => $row[$header] ?? null, $headers), $data); + + return ['title' => $title, 'headers' => array_map('strval', $headers), 'rows' => $rows]; + }//end table() + + /** + * The headers and rows of a text widget's table: cell texts, the first + * row as headers when the table has a header row, else `Column 1` and on. + * Every row is cut or padded to the header count. + * + * @param array<string, mixed> $tableData The widget's `tableData`. + * + * @return array{headers: list<string>, rows: list<list<string>>} + */ + private static function textTable(array $tableData): array { + $texts = []; + foreach ((array)$tableData['rows'] as $row) { + if (is_array($row) === true) { + $texts[] = array_map(static fn (mixed $cell): string => self::cellText(cell: $cell), array_values($row)); + } + } + + $width = max(array_merge([0], array_map('count', $texts))); + $headers = array_map(static fn (int $index): string => 'Column ' . ($index + 1), range(0, max(0, $width - 1))); + if (($tableData['headerRow'] ?? false) === true && $texts !== []) { + $headers = array_pad(array_shift($texts), $width, ''); + } + + if ($width === 0) { + $headers = []; + } + + $rows = array_map(static fn (array $row): array => array_slice(array_pad($row, $width, ''), 0, $width), $texts); + + return ['headers' => array_values($headers), 'rows' => array_values($rows)]; + }//end textTable() + + /** + * The text of one table cell (`{text}`, or a bare value). + * + * @param mixed $cell The cell. + * + * @return string + */ + private static function cellText(mixed $cell): string { + if (is_array($cell) === true) { + $cell = $cell['text'] ?? ''; + } + + return trim((string)$cell); + }//end cellText() +}//end class diff --git a/lib/Service/ScheduledExport/TabularWriter.php b/lib/Service/ScheduledExport/TabularWriter.php new file mode 100644 index 000000000..5512ba637 --- /dev/null +++ b/lib/Service/ScheduledExport/TabularWriter.php @@ -0,0 +1,291 @@ +<?php + +/** + * TabularWriter + * + * The tabular formats of a render (REQ-SCH-003): CSV of the subject's + * tables, and an XLSX workbook with a cover sheet and, with + * `sheetPerWidget`, one sheet per widget. Written without a spreadsheet + * library: the workbook is the minimal SpreadsheetML package. + * + * @category Service + * @package OCA\LaunchPad\Service\ScheduledExport + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\ScheduledExport; + +use ZipArchive; + +/** + * CSV and XLSX from `{title, headers, rows}` tables. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ +class TabularWriter { + + private const MIME_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'; + + private const MIME_WORKBOOK = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'; + + /** + * CSV: one block per table, a blank line between blocks; with more than + * one table each block starts with the table's title. + * + * @param list<array{title: string, headers: list<string>, rows: list<list<mixed>>}> $tables The tables. + * @param array<string, mixed> $options `delimiter`, `quoteChar`. + * + * @return string + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ + public function csv(array $tables, array $options = []): string { + $delimiter = $this->char(value: $options['delimiter'] ?? null, default: ','); + $quote = $this->char(value: $options['quoteChar'] ?? null, default: '"'); + $handle = fopen('php://temp', 'r+'); + foreach ($tables as $index => $table) { + if ($index > 0) { + fwrite($handle, "\n"); + } + + if (count($tables) > 1) { + fputcsv($handle, [$table['title']], $delimiter, $quote, ''); + } + + fputcsv($handle, $table['headers'], $delimiter, $quote, ''); + foreach ($table['rows'] as $row) { + fputcsv($handle, array_map(fn ($cell): string => $this->text(value: $cell), $row), $delimiter, $quote, ''); + } + } + + rewind($handle); + $csv = (string)stream_get_contents($handle); + fclose($handle); + + return $csv; + }//end csv() + + /** + * XLSX: a `Cover` sheet with the export name and run time, then one sheet + * per table (`sheetPerWidget`, the default) or one `Data` sheet holding + * every table. + * + * @param list<array{title: string, headers: list<string>, rows: list<list<mixed>>}> $tables The tables. + * @param array{name: string, runAt: string, sheetPerWidget: bool} $cover The cover and the sheet layout. + * + * @return string The workbook bytes. + * + * @throws RenderException When the package cannot be written. + * + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-003-multi-format-render-from-a-single-fire + */ + public function xlsx(array $tables, array $cover): string { + $sheets = [['name' => 'Cover', 'rows' => [['Export', $cover['name']], ['Run at', $cover['runAt']]]]]; + if ($cover['sheetPerWidget'] === true) { + foreach ($tables as $table) { + $sheets[] = ['name' => $table['title'], 'rows' => array_merge([$table['headers']], $table['rows'])]; + } + + return $this->package(sheets: $this->uniqueNames(sheets: $sheets)); + } + + $rows = []; + foreach ($tables as $table) { + $rows = array_merge($rows, [[$table['title']], $table['headers']], $table['rows'], [[]]); + } + + $sheets[] = ['name' => 'Data', 'rows' => $rows]; + + return $this->package(sheets: $this->uniqueNames(sheets: $sheets)); + }//end xlsx() + + /** + * The SpreadsheetML zip of the sheets. + * + * @param list<array{name: string, rows: list<list<mixed>>}> $sheets The sheets, names already valid. + * + * @return string + * + * @throws RenderException When the package cannot be written. + */ + private function package(array $sheets): string { + $path = tempnam(sys_get_temp_dir(), 'lpx'); + $zip = new ZipArchive(); + if ($path === false || $zip->open($path, ZipArchive::OVERWRITE) !== true) { + throw new RenderException('The workbook could not be written'); + } + + $base = 'http://schemas.openxmlformats.org/'; + $rel = $base . 'officeDocument/2006/relationships'; + $head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; + $overrides = ''; + $entries = ''; + $rels = ''; + foreach ($sheets as $index => $sheet) { + $n = $index + 1; + $part = 'worksheets/sheet' . $n . '.xml'; + $overrides .= '<Override PartName="/xl/' . $part . '" ContentType="' . self::MIME_SHEET . '"/>'; + $entries .= '<sheet name="' . $this->xml(value: $sheet['name']) . '" sheetId="' . $n . '" r:id="rId' . $n . '"/>'; + $rels .= '<Relationship Id="rId' . $n . '" Type="' . $rel . '/worksheet" Target="' . $part . '"/>'; + $zip->addFromString('xl/' . $part, $this->sheetXml(rows: $sheet['rows'])); + } + + $types = '<Types xmlns="' . $base . 'package/2006/content-types">' + . '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' + . '<Default Extension="xml" ContentType="application/xml"/>' + . '<Override PartName="/xl/workbook.xml" ContentType="' . self::MIME_WORKBOOK . '"/>' . $overrides . '</Types>'; + $zip->addFromString('[Content_Types].xml', $head . $types); + $zip->addFromString( + '_rels/.rels', + $head . '<Relationships xmlns="' . $base . 'package/2006/relationships">' + . '<Relationship Id="rId1" Type="' . $rel . '/officeDocument" Target="xl/workbook.xml"/></Relationships>' + ); + $zip->addFromString( + 'xl/workbook.xml', + $head . '<workbook xmlns="' . $base . 'spreadsheetml/2006/main" xmlns:r="' . $rel . '"><sheets>' . $entries . '</sheets></workbook>' + ); + $zip->addFromString( + 'xl/_rels/workbook.xml.rels', + $head . '<Relationships xmlns="' . $base . 'package/2006/relationships">' . $rels . '</Relationships>' + ); + $zip->close(); + + $bytes = (string)file_get_contents($path); + unlink($path); + + return $bytes; + }//end package() + + /** + * One worksheet: numbers as numbers, everything else as inline strings. + * + * @param list<list<mixed>> $rows The rows. + * + * @return string + */ + private function sheetXml(array $rows): string { + $xml = ''; + foreach ($rows as $r => $row) { + $cells = ''; + foreach (array_values($row) as $c => $value) { + $ref = $this->column(index: $c) . ($r + 1); + if (is_int($value) === true || is_float($value) === true) { + $cells .= '<c r="' . $ref . '"><v>' . $value . '</v></c>'; + continue; + } + + $text = $this->xml(value: $this->text(value: $value)); + $cells .= '<c r="' . $ref . '" t="inlineStr"><is><t xml:space="preserve">' . $text . '</t></is></c>'; + } + + $xml .= '<row r="' . ($r + 1) . '">' . $cells . '</row>'; + } + + return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + . '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>' . $xml . '</sheetData></worksheet>'; + }//end sheetXml() + + /** + * Sheet names Excel accepts: no `[]:*?/\`, at most 31 characters, unique. + * + * @param list<array{name: string, rows: list<list<mixed>>}> $sheets The sheets. + * + * @return list<array{name: string, rows: list<list<mixed>>}> + */ + private function uniqueNames(array $sheets): array { + $seen = []; + foreach ($sheets as $index => $sheet) { + $base = mb_substr(trim(str_replace(['[', ']', ':', '*', '?', '/', '\\'], ' ', $sheet['name'])), 0, 31); + if ($base === '') { + $base = 'Sheet'; + } + + $name = $base; + for ($k = 2; isset($seen[mb_strtolower($name)]) === true; $k++) { + $name = mb_substr($base, 0, 31 - strlen((string)$k) - 1) . ' ' . $k; + } + + $seen[mb_strtolower($name)] = true; + $sheets[$index]['name'] = $name; + } + + return $sheets; + }//end uniqueNames() + + /** + * The spreadsheet column letters of a zero-based index. + * + * @param int $index The index. + * + * @return string + */ + private function column(int $index): string { + $letters = ''; + for ($n = $index + 1; $n > 0; $n = intdiv($n - 1, 26)) { + $letters = chr(65 + (($n - 1) % 26)) . $letters; + } + + return $letters; + }//end column() + + /** + * A cell as text: scalars as is, booleans as true/false, the rest as JSON. + * + * @param mixed $value The cell. + * + * @return string + */ + private function text(mixed $value): string { + if ($value === true) { + return 'true'; + } + + if ($value === false) { + return 'false'; + } + + if (is_scalar($value) === true || $value === null) { + return (string)$value; + } + + return (string)json_encode($value); + }//end text() + + /** + * XML-escaped text. + * + * @param string $value The text. + * + * @return string + */ + private function xml(string $value): string { + return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8'); + }//end xml() + + /** + * A one-character CSV option, or the default. + * + * @param mixed $value The option. + * @param string $default The default. + * + * @return string + */ + private function char(mixed $value, string $default): string { + if (is_string($value) === true && strlen($value) === 1) { + return $value; + } + + return $default; + }//end char() +}//end class diff --git a/lib/Service/SearchShortcutService.php b/lib/Service/SearchShortcutService.php new file mode 100644 index 000000000..b9bdf69c4 --- /dev/null +++ b/lib/Service/SearchShortcutService.php @@ -0,0 +1,164 @@ +<?php + +/** + * SearchShortcutService + * + * The administrator's search shortcuts (search-ai-prefix-shortcuts, + * REQ-SPX-001): a prefix such as `!t`, a name and an https address with + * `{query}`. A query in a LaunchPad search box that starts with a known + * prefix goes straight to that site; the query never passes through the + * LaunchPad server. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; +use OCA\LaunchPad\Db\AdminSettingKey; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCA\LaunchPad\Kernel\Contracts\SearchShortcutServiceInterface; + +/** + * Read and validate the search shortcut list. + * + * @spec openspec/specs/tile-quick-search/spec.md + */ +class SearchShortcutService implements SearchShortcutServiceInterface { + /** + * Most shortcuts one instance may define. + * + * @var int + */ + public const MAX_SHORTCUTS = 30; + + /** + * A prefix: `!` and 1 to 10 letters or digits. + * + * @var string + */ + public const PREFIX_PATTERN = '/^![a-z0-9]{1,10}$/'; + + /** + * Constructor. + * + * @param AdminSettingMapper $settingMapper Admin settings store. + * + * @spec openspec/specs/tile-quick-search/spec.md + */ + public function __construct( + private readonly AdminSettingMapper $settingMapper, + ) { + }//end __construct() + + /** + * The stored shortcuts. A stored list that no longer validates reads as + * empty, so the page never receives an address it must not open. + * + * @return array<int, array{prefix: string, name: string, urlTemplate: string}> + * + * @spec openspec/specs/tile-quick-search/spec.md + */ + public function getShortcuts(): array { + $raw = $this->settingMapper->getValue(key: AdminSettingKey::SEARCH_SHORTCUTS->value, default: []); + if (is_array(value: $raw) === false) { + return []; + } + + try { + return $this->validate(raw: $raw); + } catch (InvalidArgumentException) { + return []; + } + }//end getShortcuts() + + /** + * Validate and store the shortcuts. + * + * @param array $raw Shortcuts as sent by the admin screen. + * + * @return array<int, array{prefix: string, name: string, urlTemplate: string}> The stored list. + * + * @throws InvalidArgumentException When an entry is invalid. + * + * @spec openspec/specs/tile-quick-search/spec.md + */ + public function saveShortcuts(array $raw): array { + $shortcuts = $this->validate(raw: $raw); + $this->settingMapper->setSetting(key: AdminSettingKey::SEARCH_SHORTCUTS->value, value: $shortcuts); + + return $shortcuts; + }//end saveShortcuts() + + /** + * Check and normalise the list. + * + * @param array $raw Raw entries. + * + * @return array<int, array{prefix: string, name: string, urlTemplate: string}> + * + * @throws InvalidArgumentException When an entry is invalid. + */ + private function validate(array $raw): array { + if (count(value: $raw) > self::MAX_SHORTCUTS) { + throw new InvalidArgumentException(message: 'At most ' . self::MAX_SHORTCUTS . ' search shortcuts'); + } + + $result = []; + $seen = []; + foreach (array_values(array: $raw) as $entry) { + $shortcut = $this->validateEntry(entry: $entry, seen: $seen); + $seen[$shortcut['prefix']] = true; + $result[] = $shortcut; + } + + return $result; + }//end validate() + + /** + * Check and normalise one entry. + * + * @param mixed $entry Raw entry. + * @param array<string, true> $seen Prefixes of the entries before it. + * + * @return array{prefix: string, name: string, urlTemplate: string} + * + * @throws InvalidArgumentException When the entry is invalid. + */ + private function validateEntry(mixed $entry, array $seen): array { + if (is_array(value: $entry) === false) { + throw new InvalidArgumentException(message: 'A search shortcut must be an object'); + } + + $prefix = mb_strtolower(string: trim(string: (string)($entry['prefix'] ?? ''))); + if (preg_match(pattern: self::PREFIX_PATTERN, subject: $prefix) !== 1) { + throw new InvalidArgumentException(message: 'A prefix is ! followed by 1 to 10 letters or digits: ' . $prefix); + } + + if (isset($seen[$prefix]) === true) { + throw new InvalidArgumentException(message: 'Prefix used twice: ' . $prefix); + } + + $name = trim(string: (string)($entry['name'] ?? '')); + if ($name === '' || mb_strlen(string: $name) > 64) { + throw new InvalidArgumentException(message: 'A shortcut name must be 1 to 64 characters: ' . $prefix); + } + + $template = trim(string: (string)($entry['urlTemplate'] ?? '')); + if (QueryUrlTemplate::isValid(value: $template) === false) { + throw new InvalidArgumentException(message: 'Use an https address that contains {query}: ' . $prefix); + } + + return ['prefix' => $prefix, 'name' => $name, 'urlTemplate' => $template]; + }//end validateEntry() +}//end class diff --git a/lib/Service/ServiceDiscoveryService.php b/lib/Service/ServiceDiscoveryService.php new file mode 100644 index 000000000..2c4f219a8 --- /dev/null +++ b/lib/Service/ServiceDiscoveryService.php @@ -0,0 +1,72 @@ +<?php + +/** + * ServiceDiscoveryService + * + * The apps this Nextcloud runs for the current user, read from their own app + * menu (`INavigationManager::getAll('link')`), so a person can turn one into + * a tile in one click (REQ-DISC-001). The menu is already filtered by the + * apps' enabled state and group restrictions, so discovery never shows an app + * the user may not open. AppAPI external apps with a page are menu entries + * too. Nothing lower is read: no Docker socket, no container labels, no + * AppAPI deployment data (REQ-DISC-003). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-launcher-discover-server-services/specs/tiles/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Kernel\Contracts\ServiceDiscoveryServiceInterface; +use OCP\INavigationManager; + +/** + * Lists the apps in the current user's Nextcloud app menu. + */ +class ServiceDiscoveryService implements ServiceDiscoveryServiceInterface { + /** + * Constructor + * + * @param INavigationManager $navigationManager The current user's app menu. + */ + public function __construct( + private readonly INavigationManager $navigationManager, + ) { + }//end __construct() + + /** + * The apps in the current user's app menu, LaunchPad itself left out. + * + * @return array<int, array{appId: string, name: string, href: string, icon: string}> The apps, in menu order. + * + * @spec openspec/changes/archive/2026-11-19-launcher-discover-server-services/specs/tiles/spec.md#requirement-the-add-flow-lists-the-apps-this-server-runs-for-the-user-req-disc-001 + */ + public function discover(): array { + $apps = []; + foreach ($this->navigationManager->getAll(type: 'link') as $entry) { + $appId = (string)($entry['id'] ?? ''); + if ($appId === '' || $appId === Application::APP_ID) { + continue; + } + + $apps[] = [ + 'appId' => $appId, + 'name' => (string)($entry['name'] ?? $appId), + 'href' => (string)($entry['href'] ?? ''), + 'icon' => (string)($entry['icon'] ?? ''), + ]; + } + + return $apps; + }//end discover() +}//end class diff --git a/lib/Service/SetupWizardService.php b/lib/Service/SetupWizardService.php index e3ac48d26..9d95c7e83 100644 --- a/lib/Service/SetupWizardService.php +++ b/lib/Service/SetupWizardService.php @@ -24,60 +24,47 @@ namespace OCA\LaunchPad\Service; -use InvalidArgumentException; +use OCA\LaunchPad\AppInfo\Application; use OCA\LaunchPad\Db\AdminSetting; use OCA\LaunchPad\Db\AdminSettingMapper; -use OCP\App\IAppManager; +use OCA\LaunchPad\Db\RoleAssignment; +use OCA\LaunchPad\Db\RoleAssignmentMapper; +use OCA\LaunchPad\Kernel\Contracts\SetupWizardServiceInterface; +use OCP\IAppConfig; /** * Service backing the setup wizard state + completion endpoints. * * Status values follow the spec (REQ-WIZ-008): `'done'`, `'skipped'`, * `'pending'`. The wizard "pending" state means a step has not been - * traversed yet (no sibling setting written). `'skipped'` is reserved for - * the optional steps 5/6 — when their guarded capability isn't available, - * the heuristic returns `'skipped'` so the UI can collapse the step. + * traversed yet (no sibling setting written). Step 3 is `'done'` once a + * demo showcase is installed and Step 4 once someone holds the LaunchPad + * admin role; both are `'pending'` before that, and a finished wizard + * without an admin role reports Step 4 `'skipped'` (the data model in the + * spec). Five steps: Welcome, Groups, Examples, Roles, Done + * (REQ-WIZ-012); the footer is set on its own admin tab, not here. + * + * @spec openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/setup-wizard/spec.md#requirement-req-wiz-012-multi-step-wizard-flow-with-5-steps */ -class SetupWizardService { +class SetupWizardService implements SetupWizardServiceInterface { /** - * Total number of wizard steps (REQ-WIZ-002). + * Total number of wizard steps (REQ-WIZ-012). * * @var integer */ - public const STEP_COUNT = 7; - - /** - * Storage backend value: relational database (default). - * - * @var string - */ - public const STORAGE_DATABASE = 'database'; - - /** - * Storage backend value: GroupFolder app. - * - * @var string - */ - public const STORAGE_GROUPFOLDER = 'groupfolder'; - - /** - * GroupFolder dependency app id used by Step 2's tooltip gate. - * - * @var string - */ - public const GROUPFOLDER_APP_ID = 'groupfolders'; + public const STEP_COUNT = 5; /** * Constructor. * - * @param AdminSettingMapper $settingMapper Admin-setting persistence. - * @param IAppManager $appManager Used to detect the optional - * `groupfolders` Nextcloud - * app for Step 2's gate. + * @param AdminSettingMapper $settingMapper Admin-setting persistence. + * @param IAppConfig|null $appConfig Where demo showcase installs are marked. + * @param RoleAssignmentMapper|null $roleAssignments LaunchPad role assignments. */ public function __construct( private readonly AdminSettingMapper $settingMapper, - private readonly IAppManager $appManager, + private readonly ?IAppConfig $appConfig=null, + private readonly ?RoleAssignmentMapper $roleAssignments=null, ) { }//end __construct() @@ -86,12 +73,13 @@ public function __construct( * * Shape: `{complete: bool, currentRecommendedStep: int, * stepStatuses: array<string,string>}`. Step 1 is always - * `'done'`; Step 7 stays `'pending'` until the admin clicks Finish. + * `'done'`; Step 5 stays `'pending'` until the admin clicks Finish. * * @return array{complete: bool, currentRecommendedStep: int, stepStatuses: array<int,string>} * The wizard state payload. * * @spec openspec/specs/setup-wizard/spec.md + * @spec openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/setup-wizard/spec.md#requirement-req-wiz-012-multi-step-wizard-flow-with-5-steps */ public function getWizardState(): array { $complete = $this->isWizardComplete(); @@ -100,7 +88,8 @@ public function getWizardState(): array { return [ 'complete' => $complete, 'currentRecommendedStep' => $this->resolveRecommendedStep( - stepStatuses: $stepStatuses + stepStatuses: $stepStatuses, + complete: $complete ), 'stepStatuses' => $stepStatuses, ]; @@ -124,58 +113,6 @@ public function markWizardComplete(): array { return $this->getWizardState(); }//end markWizardComplete() - /** - * Whether the GroupFolder dependency is installed (REQ-WIZ-003). - * - * @return boolean True when the GroupFolder option may be selected. - */ - public function hasGroupfolderApp(): bool { - return $this->appManager->isInstalled(self::GROUPFOLDER_APP_ID); - }//end hasGroupfolderApp() - - /** - * Persist the storage backend choice from Step 2. - * - * @param string $value `'database'` or `'groupfolder'`. - * - * @return void - * - * @spec openspec/specs/setup-wizard/spec.md - */ - public function setContentStorage(string $value): void { - $allowed = [self::STORAGE_DATABASE, self::STORAGE_GROUPFOLDER]; - if (in_array(needle: $value, haystack: $allowed, strict: true) === false) { - throw new InvalidArgumentException( - message: 'Unsupported storage backend: ' . $value - ); - } - - $this->settingMapper->setSetting( - key: AdminSetting::KEY_CONTENT_STORAGE, - value: $value - ); - }//end setContentStorage() - - /** - * Read the persisted storage backend choice with the safe default. - * - * @return string The persisted backend or `'database'` when unset. - * - * @spec openspec/specs/setup-wizard/spec.md - */ - public function getContentStorage(): string { - $value = $this->settingMapper->getValue( - key: AdminSetting::KEY_CONTENT_STORAGE, - default: null - ); - - if (is_string($value) === true && $value !== '') { - return $value; - } - - return self::STORAGE_DATABASE; - }//end getContentStorage() - /** * Whether the wizard has been completed at least once. * @@ -199,33 +136,33 @@ private function isWizardComplete(): bool { * @param boolean $complete Whether the wizard has been completed. * * @return array<int,string> Step number → status. + * + * @spec openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/setup-wizard/spec.md#requirement-req-wiz-012-multi-step-wizard-flow-with-5-steps */ private function computeStepStatuses(bool $complete): array { $settings = $this->settingMapper->getAllAsArray(); - $hasStorage = isset($settings[AdminSetting::KEY_CONTENT_STORAGE]); $groupOrder = ($settings[AdminSetting::KEY_GROUP_ORDER] ?? null); $hasGroup = (is_array($groupOrder) === true && count($groupOrder) > 0); - $hasFooter = isset($settings[AdminSetting::KEY_FOOTER_CONFIG]); - - // Steps 4 (demos) and 5 (admin-roles) live in sibling capabilities - // not yet implemented in this branch; surface them as `'skipped'` - // so the wizard advances cleanly when the embed component is a - // local stub. They flip to `'done'` once the sibling capability - // ships and writes its own settings. - $statusStorage = 'pending'; - if ($hasStorage === true) { - $statusStorage = 'done'; - } $statusGroup = 'pending'; if ($hasGroup === true) { $statusGroup = 'done'; } - $statusFooter = 'skipped'; - if ($hasFooter === true) { - $statusFooter = 'done'; + $statusDemo = 'pending'; + if ($this->hasInstalledShowcase() === true) { + $statusDemo = 'done'; + } + + // Skip on Step 4 writes nothing, so the server reads a finished + // wizard without an admin role as a skipped Step 4 ("Endpoint + // includes skipped step status"); before the finish it is pending. + $statusRoles = 'pending'; + if ($this->hasAdminRoleAssignment() === true) { + $statusRoles = 'done'; + } else if ($complete === true) { + $statusRoles = 'skipped'; } $statusDone = 'pending'; @@ -235,30 +172,89 @@ private function computeStepStatuses(bool $complete): array { return [ '1' => 'done', - '2' => $statusStorage, - '3' => $statusGroup, - '4' => 'skipped', - '5' => 'skipped', - '6' => $statusFooter, - '7' => $statusDone, + '2' => $statusGroup, + '3' => $statusDemo, + '4' => $statusRoles, + '5' => $statusDone, ]; }//end computeStepStatuses() /** - * The first step whose status is not `'done'`, defaulting to Step 1. + * Whether any demo showcase is installed: DemoShowcasesService marks + * each install as `showcase_installed_<id>` holding the dashboard UUID. + * + * @return bool True when at least one marker holds a UUID. + * + * @spec openspec/specs/setup-wizard/spec.md + */ + private function hasInstalledShowcase(): bool { + if ($this->appConfig === null) { + return false; + } + + foreach ($this->appConfig->getKeys(app: Application::APP_ID) as $key) { + if (str_starts_with(haystack: $key, needle: DemoShowcasesService::CONFIG_PREFIX) === true + && $this->appConfig->getValueString(app: Application::APP_ID, key: $key, default: '') !== '' + ) { + return true; + } + } + + return false; + }//end hasInstalledShowcase() + + /** + * Whether a user or group holds the LaunchPad admin role. + * + * @return bool True when an `admin` role assignment exists. + * + * @spec openspec/specs/setup-wizard/spec.md + */ + private function hasAdminRoleAssignment(): bool { + if ($this->roleAssignments === null) { + return false; + } + + foreach ($this->roleAssignments->findAll() as $assignment) { + if ($assignment->getRole() === RoleAssignment::ROLE_ADMIN) { + return true; + } + } + + return false; + }//end hasAdminRoleAssignment() + + /** + * The step the wizard opens at. A first run (nothing after Step 1 + * done and the wizard not finished) starts at Step 1, Welcome; a + * re-run opens at the first step whose status is not `'done'` + * (REQ-WIZ-008: Step 1 on a fresh instance, the first open step on + * a re-run; "Wizard starts at Step 1"). * * @param array<int,string> $stepStatuses Heuristic per-step statuses. + * @param bool $complete Whether the wizard was finished. * * @return integer The recommended next step index (1..STEP_COUNT). + * + * @spec openspec/specs/setup-wizard/spec.md */ - private function resolveRecommendedStep(array $stepStatuses): int { - for ($step = 1; $step <= self::STEP_COUNT; $step++) { + private function resolveRecommendedStep(array $stepStatuses, bool $complete): int { + $firstOpen = 1; + $anyDone = false; + for ($step = self::STEP_COUNT; $step >= 2; $step--) { $status = ($stepStatuses[$step] ?? 'pending'); - if ($status !== 'done') { - return $step; + if ($status === 'done') { + $anyDone = true; + continue; } + + $firstOpen = $step; + } + + if ($complete === false && $anyDone === false) { + return 1; } - return 1; + return $firstOpen; }//end resolveRecommendedStep() }//end class diff --git a/lib/Service/ShareGrant.php b/lib/Service/ShareGrant.php new file mode 100644 index 000000000..dc4ba8880 --- /dev/null +++ b/lib/Service/ShareGrant.php @@ -0,0 +1,45 @@ +<?php + +/** + * ShareGrant + * + * One requested dashboard share: who it is for and at which permission + * level (REQ-SHARE-001, REQ-SHARE-009). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Share type, recipient and permission level of a share being added or + * kept. DashboardShareService validates the values before it writes. + * + * @spec openspec/specs/dashboard-sharing/spec.md + */ +final class ShareGrant { + /** + * Constructor + * + * @param string $shareType The share type ('user' or 'group'). + * @param string $shareWith The recipient user or group id. + * @param string $permissionLevel The permission level. + */ + public function __construct( + public readonly string $shareType, + public readonly string $shareWith, + public readonly string $permissionLevel, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ShareNotifier.php b/lib/Service/ShareNotifier.php new file mode 100644 index 000000000..32219937e --- /dev/null +++ b/lib/Service/ShareNotifier.php @@ -0,0 +1,274 @@ +<?php + +/** + * ShareNotifier + * + * Tells users about share and ownership changes on a dashboard. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboard-sharing/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTime; +use OCA\LaunchPad\Activity\DashboardActivityEmitter; +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\DashboardShare; +use OCP\IGroupManager; +use OCP\Notification\IManager as INotificationManager; +use OCP\Notification\INotification; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Sends the notifications and activity of a share that is already written. + * + * @spec openspec/specs/dashboard-sharing/spec.md + */ +class ShareNotifier { + /** + * Constructor + * + * @param INotificationManager $notificationManager The notification manager. + * @param IGroupManager $groupManager The group manager. + * @param LoggerInterface $logger Records a failed announcement. + * @param DashboardActivityEmitter|null $activity Sends dashboard_shared to the recipients (#713). + */ + public function __construct( + private readonly INotificationManager $notificationManager, + private readonly IGroupManager $groupManager, + private readonly LoggerInterface $logger, + private readonly ?DashboardActivityEmitter $activity = null, + ) { + }//end __construct() + + /** + * Publish `dashboard_shared` notifications for a share. + * + * @param DashboardShare $share The share row. + * @param string $sharerUserId The user who created the share. + * @param Dashboard $dashboard The shared dashboard. + * + * @return void + * + * @spec openspec/specs/dashboard-sharing/spec.md + */ + public function shared( + DashboardShare $share, + string $sharerUserId, + Dashboard $dashboard, + ): void { + $this->sharedAll(shares: [$share], sharerUserId: $sharerUserId, dashboard: $dashboard); + }//end shared() + + /** + * Publish `dashboard_shared` for the shares one action wrote. + * + * For `user`-type shares: one notification. + * For `group`-type shares: fan out one notification per current group + * member, excluding the sharer. REQ-SHARE-008. + * + * The activity stream gets one row for the sharer naming every + * recipient and one row per recipient (REQ-ACT-005). + * + * The shares are already committed and a retry would send nothing, so a + * failure is logged and the remaining recipients are still notified. + * + * @param DashboardShare[] $shares The share rows. + * @param string $sharerUserId The user who created the shares. + * @param Dashboard $dashboard The shared dashboard. + * + * @return void + * + * @spec openspec/specs/dashboard-sharing/spec.md + * @spec openspec/specs/activity-feed-integration/spec.md + */ + public function sharedAll( + array $shares, + string $sharerUserId, + Dashboard $dashboard, + ): void { + $perShare = []; + try { + foreach ($shares as $index => $share) { + $perShare[$index] = $this->resolveRecipients( + share: $share, + excludeUserId: $sharerUserId + ); + } + + $this->activity?->shared( + dashboard: $dashboard, + shares: $shares, + actor: $sharerUserId, + recipients: array_values(array_unique(array_merge([], ...array_values($perShare)))) + ); + } catch (Throwable $e) { + $this->logFailure(exception: $e); + } + + foreach ($shares as $index => $share) { + $this->notifyRecipients( + share: $share, + recipients: ($perShare[$index] ?? []), + sharerUserId: $sharerUserId, + dashboard: $dashboard + ); + } + }//end sharedAll() + + /** + * Send the `dashboard_shared` notification of one share to its recipients. + * + * @param DashboardShare $share The share row. + * @param string[] $recipients The resolved recipient user ids. + * @param string $sharerUserId The user who created the share. + * @param Dashboard $dashboard The shared dashboard. + * + * @return void + */ + private function notifyRecipients( + DashboardShare $share, + array $recipients, + string $sharerUserId, + Dashboard $dashboard, + ): void { + $subject = [ + $sharerUserId, + (string)$dashboard->getName(), + (string)$share->getPermissionLevel(), + ]; + foreach ($recipients as $recipientId) { + try { + $notification = $this->dashboardNotification( + userId: $recipientId, + dashboardId: (string)$share->getDashboardId() + ); + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $notification->setSubject('dashboard_shared', $subject); + + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $this->notificationManager->notify($notification); + } catch (Throwable $e) { + $this->logFailure(exception: $e); + } + }//end foreach + }//end notifyRecipients() + + /** + * Publish a `dashboard_ownership_transferred` notification. + * + * @param string $newOwnerId The new owner's user ID. + * @param int $dashboardId The dashboard ID. + * @param string $dashboardName The dashboard name. + * + * @return void + * + * @spec openspec/specs/dashboard-sharing/spec.md + */ + public function ownershipTransferred( + string $newOwnerId, + int $dashboardId, + string $dashboardName, + ): void { + $notification = $this->dashboardNotification( + userId: $newOwnerId, + dashboardId: (string)$dashboardId + ); + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $notification->setSubject('dashboard_ownership_transferred', [$dashboardName]); + + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $this->notificationManager->notify($notification); + }//end ownershipTransferred() + + /** + * A launchpad notification about a dashboard for one user, stamped now; + * the caller sets its subject. + * + * @param string $userId The user to notify. + * @param string $dashboardId The dashboard ID. + * + * @return INotification The notification without a subject. + */ + private function dashboardNotification(string $userId, string $dashboardId): INotification { + $notification = $this->notificationManager->createNotification(); + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + $notification->setApp('launchpad') + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + ->setUser($userId) + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + ->setDateTime(new DateTime()) + // phpcs:ignore CustomSniffs.Functions.NamedParameters.RequireNamedParameters + ->setObject('dashboard', $dashboardId); + + return $notification; + }//end dashboardNotification() + + /** + * Resolve the recipient user IDs for a share. + * + * @param DashboardShare $share The share. + * @param string $excludeUserId A user ID to exclude (the sharer). + * + * @return string[] The recipient user IDs. + */ + private function resolveRecipients( + DashboardShare $share, + string $excludeUserId, + ): array { + if ($share->getShareType() === DashboardShare::SHARE_TYPE_USER) { + $uid = (string)$share->getShareWith(); + if ($uid === $excludeUserId) { + return []; + } + + return [$uid]; + } + + // Group share: expand members. + $groupId = (string)$share->getShareWith(); + $group = $this->groupManager->get(gid: $groupId); + if ($group === null) { + return []; + } + + $recipients = []; + foreach ($group->getUsers() as $user) { + $uid = $user->getUID(); + if ($uid !== $excludeUserId) { + $recipients[] = $uid; + } + } + + return $recipients; + }//end resolveRecipients() + + /** + * Log an announcement that failed after its share was written. + * + * @param Throwable $exception The failure. + * + * @return void + */ + private function logFailure(Throwable $exception): void { + $this->logger->error( + message: 'Dashboard share announcement failed: ' . $exception::class, + context: ['app' => Application::APP_ID, 'exceptionClass' => $exception::class, 'exception' => $exception] + ); + }//end logFailure() +}//end class diff --git a/lib/Service/SharingLimits.php b/lib/Service/SharingLimits.php new file mode 100644 index 000000000..1e4974d32 --- /dev/null +++ b/lib/Service/SharingLimits.php @@ -0,0 +1,287 @@ +<?php + +/** + * LaunchPad Sharing Limits. + * + * Who may share a dashboard, and with whom (REQ-SHARE-014). Two admin + * settings: the groups whose members may share (empty means everyone, which + * is how sharing worked before the setting existed), and whether recipients + * are limited to people who share a group with the sharer. The share service + * enforces both on every share it creates, and the sharee search offers only + * recipients that would pass. + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/record-parity-requirements/specs/dashboard-sharing/spec.md + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\AdminSettingKey; +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCA\LaunchPad\Db\DashboardShare; +use InvalidArgumentException; +use OCA\LaunchPad\Exception\ForbiddenException; +use OCP\AppFramework\OCS\OCSForbiddenException; + +/** + * The admin limits on dashboard sharing. + */ +class SharingLimits { + + /** + * Recipients may be anyone. + */ + public const SCOPE_EVERYONE = 'everyone'; + + /** + * Recipients must share a group with the sharer. + */ + public const SCOPE_SHARED_GROUPS = 'shared-groups'; + + /** + * The recipient scopes an administrator can pick. + * + * @var list<string> + */ + public const SCOPES = [self::SCOPE_EVERYONE, self::SCOPE_SHARED_GROUPS]; + + /** + * Everyone may share. + */ + public const ALLOWED_EVERYONE = 'everyone'; + + /** + * Only members of the allowed groups may share. + */ + public const ALLOWED_GROUPS = 'groups'; + + /** + * Nobody but an administrator may share (REQ-SHARE-015). + */ + public const ALLOWED_NONE = 'none'; + + /** + * The "Sharing allowed for" choices an administrator can pick. + * + * @var list<string> + */ + public const ALLOWED_MODES = [self::ALLOWED_EVERYONE, self::ALLOWED_GROUPS, self::ALLOWED_NONE]; + + /** + * The Nextcloud administrators group. + */ + private const ADMIN_GROUP = 'admin'; + + /** + * Constructor. + * + * @param AdminSettingMapper $settings Reads the two settings. + * @param AdminTemplateService $templates Answers a user's groups, the one place that asks Nextcloud. + * + * @return void + */ + public function __construct( + private readonly AdminSettingMapper $settings, + private readonly AdminTemplateService $templates, + ) { + }//end __construct() + + /** + * The groups whose members may share; empty means everyone may. + * + * @return list<string> The group ids. + * + * @spec openspec/changes/record-parity-requirements/specs/dashboard-sharing/spec.md#requirement-administrators-decide-who-may-share-and-with-whom-req-share-014 + */ + public function allowedGroups(): array { + $stored = $this->settings->getValue(key: AdminSettingKey::SHARING_ALLOWED_GROUPS->value, default: []); + if (is_array($stored) === false) { + return []; + } + + return array_values(array_filter(array_map('strval', $stored), static fn (string $id): bool => $id !== '')); + }//end allowedGroups() + + /** + * Who may share: everyone, the allowed groups, or nobody but an administrator. + * + * Only Nobody is stored as an override; otherwise the mode follows the + * group list (REQ-SHARE-014): groups set means `groups`, none set means + * `everyone`. So the group setting keeps working on its own. + * + * @return string One of ALLOWED_MODES. + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + public function allowedMode(): string { + $stored = $this->settings->getValue(key: AdminSettingKey::SHARING_ALLOWED->value, default: null); + if ($stored === self::ALLOWED_NONE) { + return self::ALLOWED_NONE; + } + + if ($this->allowedGroups() === []) { + return self::ALLOWED_EVERYONE; + } + + return self::ALLOWED_GROUPS; + }//end allowedMode() + + /** + * Whether public links may be created; on unless an administrator switched them off. + * + * @return bool False only for a stored `false`. + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + public function publicLinksAllowed(): bool { + return $this->settings->getValue(key: AdminSettingKey::PUBLIC_LINKS_ALLOWED->value, default: true) !== false; + }//end publicLinksAllowed() + + /** + * Who may receive a share: everyone, or people who share a group with the sharer. + * + * An unknown stored value reads as `everyone`, today's behaviour. + * + * @return string One of SCOPES. + * + * @spec openspec/changes/record-parity-requirements/specs/dashboard-sharing/spec.md#requirement-administrators-decide-who-may-share-and-with-whom-req-share-014 + */ + public function recipientScope(): string { + $stored = $this->settings->getValue(key: AdminSettingKey::SHARING_RECIPIENT_SCOPE->value, default: self::SCOPE_EVERYONE); + if (in_array($stored, self::SCOPES, true) === false) { + return self::SCOPE_EVERYONE; + } + + return $stored; + }//end recipientScope() + + /** + * Whether this user may share dashboards at all. + * + * Under `none` only an administrator may (REQ-SHARE-015); under `groups` + * a member of an allowed group; an empty group list lets everyone share. + * + * @param string $userId The sharer. + * + * @return bool True when the user may share. + * + * @spec openspec/changes/record-parity-requirements/specs/dashboard-sharing/spec.md#requirement-administrators-decide-who-may-share-and-with-whom-req-share-014 + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + public function mayShare(string $userId): bool { + $mode = $this->allowedMode(); + if ($mode === self::ALLOWED_NONE) { + return in_array(self::ADMIN_GROUP, $this->groupsOf(userId: $userId), true); + } + + if ($mode === self::ALLOWED_EVERYONE) { + return true; + } + + return array_intersect($this->allowedGroups(), $this->groupsOf(userId: $userId)) !== []; + }//end mayShare() + + /** + * Whether this sharer may share with this recipient. + * + * Under the shared-groups scope a user recipient must share a group with + * the sharer, and a group recipient must be a group the sharer is in. + * + * @param string $sharerId The sharer. + * @param string $shareType `user` or `group`. + * @param string $shareWith The recipient user or group id. + * + * @return bool True when the recipient is allowed. + * + * @spec openspec/changes/record-parity-requirements/specs/dashboard-sharing/spec.md#requirement-administrators-decide-who-may-share-and-with-whom-req-share-014 + */ + public function mayReceive(string $sharerId, string $shareType, string $shareWith): bool { + if ($this->recipientScope() === self::SCOPE_EVERYONE) { + return true; + } + + $sharerGroups = $this->groupsOf(userId: $sharerId); + if ($shareType === DashboardShare::SHARE_TYPE_GROUP) { + return in_array($shareWith, $sharerGroups, true); + } + + return array_intersect($sharerGroups, $this->groupsOf(userId: $shareWith)) !== []; + }//end mayReceive() + + /** + * Refuse a share the limits do not allow. + * + * @param string $sharerId The sharer. + * @param string $shareType `user` or `group`. + * @param string $shareWith The recipient. + * + * @return void + * + * @throws ForbiddenException When the sharer may not share, or not with this recipient. + * + * @spec openspec/changes/record-parity-requirements/specs/dashboard-sharing/spec.md#requirement-administrators-decide-who-may-share-and-with-whom-req-share-014 + */ + public function assertMayShare(string $sharerId, string $shareType, string $shareWith): void { + if ($this->mayShare(userId: $sharerId) === false) { + throw new ForbiddenException(message: 'You are not allowed to share dashboards.'); + } + + if ($this->mayReceive(sharerId: $sharerId, shareType: $shareType, shareWith: $shareWith) === false) { + throw new ForbiddenException(message: 'You can only share with people who share a group with you.'); + } + }//end assertMayShare() + + /** + * Refuse a public link the policy does not allow (REQ-SHARE-015): public + * links switched off, a caller who may not share, or no expiry date. + * + * @param string $callerId The person creating the link. + * @param string|null $expiresAt The requested expiry date. + * + * @return void + * + * @throws OCSForbiddenException When public links are off or the caller may not share (403). + * @throws InvalidArgumentException When the link has no expiry date (400). + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + public function assertMayCreatePublicLink(string $callerId, ?string $expiresAt): void { + if ($this->publicLinksAllowed() === false) { + throw new OCSForbiddenException(message: 'Public links are switched off.'); + } + + if ($this->mayShare(userId: $callerId) === false) { + throw new OCSForbiddenException(message: 'You are not allowed to share dashboards.'); + } + + if ($expiresAt === null || trim(string: $expiresAt) === '') { + throw new InvalidArgumentException(message: 'A public link needs an expiry date (expiresAt).'); + } + }//end assertMayCreatePublicLink() + + /** + * The group ids a user is in; none for an unknown user. + * + * @param string $userId The user. + * + * @return list<string> The group ids. + */ + private function groupsOf(string $userId): array { + return array_values(array_map('strval', $this->templates->getUserGroupIdsFor(userId: $userId))); + }//end groupsOf() + +}//end class diff --git a/lib/Service/ShippedTemplatePlatform.php b/lib/Service/ShippedTemplatePlatform.php new file mode 100644 index 000000000..44c97e647 --- /dev/null +++ b/lib/Service/ShippedTemplatePlatform.php @@ -0,0 +1,46 @@ +<?php + +/** + * ShippedTemplatePlatform + * + * The dashboard widget manager and the group manager of the shipped template service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/admin-templates/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Dashboard\IManager; +use OCP\IGroupManager; + +/** + * The dashboard widget manager and the group manager of the shipped template service. + * + * @spec openspec/specs/admin-templates/spec.md + */ +class ShippedTemplatePlatform { + /** + * Constructor. + * + * @param IManager $dashboardMgr Nextcloud's dashboard widget registry. + * @param IGroupManager $groupManager Checks that a named group exists. + */ + public function __construct( + public readonly IManager $dashboardMgr, + public readonly IGroupManager $groupManager, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ShippedTemplateService.php b/lib/Service/ShippedTemplateService.php new file mode 100644 index 000000000..a5f4425ef --- /dev/null +++ b/lib/Service/ShippedTemplateService.php @@ -0,0 +1,468 @@ +<?php + +/** + * ShippedTemplateService + * + * Lists and installs the admin templates LaunchPad ships with. A shipped + * template is data: one file per template under `data/templates/<id>.json`, + * holding a version number and one dashboard in the shape an export writes + * (`dashboards/<uuid>.json` of a `launchpad-export-v1` archive). + * + * WHY IT GOES THROUGH THE IMPORTER. Installing wraps the definition in an + * export archive and hands it to {@see ImportService}. A shipped template and + * a file an administrator uploads therefore take one path, and a field the + * importer drops is dropped for both, where a second builder would hide it. + * + * WHAT INSTALLING DOES NOT DO. It adds an admin template. It does not hand it + * to anybody: which groups get it, and whether it is the default, is the + * administrator's call, made here through the options or afterwards on the + * Templates page. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Kernel\Contracts\ShippedTemplateServiceInterface; +use OCP\AppFramework\Db\DoesNotExistException; +use RuntimeException; +use ZipArchive; + +/** + * List and install the templates shipped in `data/templates`. + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * Wires the importer, the template service, the mapper and four + * Nextcloud services for one job; each is used once. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ +class ShippedTemplateService implements ShippedTemplateServiceInterface { + /** + * App config key prefix: `shipped_template_<id>` holds the UUID of the + * template the last install created. Empty means not installed. + * + * @var string + */ + public const CONFIG_PREFIX = 'shipped_template_'; + + /** + * App config key prefix for the version that install carried. + * + * @var string + */ + public const CONFIG_VERSION_PREFIX = 'shipped_template_version_'; + + /** + * Optional data-directory override (test seam). + * + * @var string|null + */ + private ?string $dataDirOverride = null; + + /** + * Constructor. + * + * @param ImportService $importService Reads the archive the definition is wrapped in. + * @param AdminTemplateService $templateService Sets the groups and the default flag. + * @param ShippedTemplateStore $store The dashboard mapper and app config. + * @param ShippedTemplatePlatform $platform The widget manager and group manager. + */ + public function __construct( + private readonly ImportService $importService, + private readonly AdminTemplateService $templateService, + private readonly ShippedTemplateStore $store, + private readonly ShippedTemplatePlatform $platform, + ) { + }//end __construct() + + /** + * Point the service at another definitions directory (tests only). + * + * @param string $path Absolute path to a directory of `<id>.json` files. + * + * @return void + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + public function setDataDirForTesting(string $path): void { + $this->dataDirOverride = $path; + }//end setDataDirForTesting() + + /** + * Every shipped template, with whether it is installed here. + * + * @return array<int, array<string, mixed>> One descriptor per template. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + public function listTemplates(): array { + $result = []; + foreach (self::SHIPPED_IDS as $id) { + $definition = $this->readDefinition(templateId: $id); + $dashboard = $definition['dashboard']; + $installedUuid = $this->findInstalledUuid(templateId: $id); + + $installedVersion = null; + if ($installedUuid !== '') { + $installedVersion = $this->store->appConfig->getValueInt( + Application::APP_ID, + self::CONFIG_VERSION_PREFIX . $id, + 0 + ); + } + + $result[] = [ + 'id' => $id, + 'name' => (string)$dashboard['name'], + 'description' => (string)($dashboard['description'] ?? ''), + 'language' => (string)($definition['language'] ?? 'en'), + 'version' => (int)$definition['templateVersion'], + 'widgetCount' => count($dashboard['widgets']), + 'isInstalled' => $installedUuid !== '', + 'installedUuid' => $installedUuid, + 'installedVersion' => $installedVersion, + // REQ-TMPL-020: a newer version ships than the one installed. + 'updateAvailable' => $installedUuid !== '' && $installedVersion < (int)$definition['templateVersion'], + 'missingWidgets' => $this->findMissingWidgets(widgets: $dashboard['widgets']), + 'registers' => $this->findRegisters(widgets: $dashboard['widgets']), + ]; + }//end foreach + + return $result; + }//end listTemplates() + + /** + * Install a shipped template as an admin template. + * + * Already installed and not forced: nothing is added, but the groups and + * the default flag are still applied, so a deploy script can run twice. + * Forced: a fresh copy is added and becomes the recorded install. The + * earlier one stays, because users' dashboards made from it point at it. + * + * @param string $templateId The shipped template id. + * @param array<string, mixed> $options Optional `targetGroups` (groups whose members get the + * template; empty leaves the definition's groups), + * `makeDefault` (make it the default template for + * everyone; false), `force` (add a fresh copy even when + * installed; false) and `userId` (who runs the install, + * for the archive; 'cli'). + * + * @return array{templateId:string, uuid:string, id:int, version:int, alreadyInstalled:bool, + * targetGroups:array<int,string>, isDefault:bool, missingWidgets:array<int,string>, + * registers:array<int,string>} + * + * @throws InvalidArgumentException When the id or a group is unknown. + * @throws RuntimeException When the definition or the import fails. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + public function install(string $templateId, array $options=[]): array { + $options += ['targetGroups' => [], 'makeDefault' => false, 'force' => false, 'userId' => 'cli']; + $targetGroups = $options['targetGroups']; + $makeDefault = $options['makeDefault']; + $force = $options['force']; + $userId = $options['userId']; + $definition = $this->readDefinition(templateId: $templateId); + + // A mistyped group would target nobody and still report success. + foreach ($targetGroups as $group) { + if ($this->platform->groupManager->groupExists(gid: $group) === false) { + throw new InvalidArgumentException(message: 'Unknown group: ' . $group); + } + } + + $alreadyInstalled = false; + $uuid = $this->findInstalledUuid(templateId: $templateId); + if ($uuid !== '' && $force === false) { + $alreadyInstalled = true; + $dashboardId = (int)$this->store->dashboardMapper->findByUuid(uuid: $uuid)->getId(); + } + + if ($alreadyInstalled === false) { + $created = $this->importDefinition(definition: $definition, userId: $userId); + $uuid = $created['uuid']; + $dashboardId = $created['id']; + $this->store->appConfig->setValueString(Application::APP_ID, self::CONFIG_PREFIX . $templateId, $uuid); + $this->store->appConfig->setValueInt( + Application::APP_ID, + self::CONFIG_VERSION_PREFIX . $templateId, + (int)$definition['templateVersion'] + ); + } + + $update = []; + if ($targetGroups !== []) { + $update['targetGroups'] = array_values(array: $targetGroups); + } + + if ($makeDefault === true) { + $update['isDefault'] = true; + } + + $template = $this->store->dashboardMapper->find(id: $dashboardId); + if ($update !== []) { + $template = $this->templateService->updateTemplate(id: $dashboardId, data: $update); + } + + return [ + 'templateId' => $templateId, + 'uuid' => $uuid, + 'id' => $dashboardId, + 'version' => (int)$definition['templateVersion'], + 'alreadyInstalled' => $alreadyInstalled, + 'targetGroups' => $template->getTargetGroupsArray(), + 'isDefault' => $template->getIsDefault() === 1, + 'missingWidgets' => $this->findMissingWidgets(widgets: $definition['dashboard']['widgets']), + 'registers' => $this->findRegisters(widgets: $definition['dashboard']['widgets']), + ]; + }//end install() + + /** + * The installed template of a shipped id, or null when it is not + * installed (or the installed one was deleted). + * + * @param string $templateId The shipped template id. + * + * @return Dashboard|null The installed admin template. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + public function findInstalled(string $templateId): ?Dashboard { + $uuid = $this->findInstalledUuid(templateId: $templateId); + if ($uuid === '') { + return null; + } + + return $this->store->dashboardMapper->findByUuid(uuid: $uuid); + }//end findInstalled() + + /** + * Read and check one shipped definition. + * + * @param string $templateId The shipped template id. + * + * @return array{templateVersion:int, dashboard:array<string, mixed>, language?:string} + * + * @throws InvalidArgumentException When the id is not a shipped template. + * @throws RuntimeException When the file is missing or malformed. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + public function readDefinition(string $templateId): array { + if (in_array(needle: $templateId, haystack: self::SHIPPED_IDS, strict: true) === false) { + throw new InvalidArgumentException( + message: 'Unknown template: ' . $templateId + . '. Shipped templates: ' . implode(separator: ', ', array: self::SHIPPED_IDS) + ); + } + + $dir = ($this->dataDirOverride ?? dirname(path: __DIR__, levels: 2) . '/data/templates'); + $path = $dir . '/' . $templateId . '.json'; + + $decoded = null; + if (is_readable(filename: $path) === true) { + $decoded = json_decode(json: (string)file_get_contents(filename: $path), associative: true); + } + + // A packaging error must be loud: an empty definition would install + // an empty template and report success. + if (is_array($decoded) === false + || is_int($decoded['templateVersion'] ?? null) === false + || $this->isUsableDashboard(dashboard: ($decoded['dashboard'] ?? null)) === false + ) { + throw new RuntimeException(message: 'Template definition missing or malformed: ' . $path); + } + + return $decoded; + }//end readDefinition() + + /** + * Whether a definition's dashboard can be installed: it has a UUID, a + * name and at least one widget. + * + * @param mixed $dashboard The decoded `dashboard` value. + * + * @return bool True when it can be installed. + */ + private function isUsableDashboard(mixed $dashboard): bool { + return is_array($dashboard) === true + && is_string($dashboard['uuid'] ?? null) === true + && is_string($dashboard['name'] ?? null) === true + && is_array($dashboard['widgets'] ?? null) === true + && $dashboard['widgets'] !== []; + }//end isUsableDashboard() + + /** + * The UUID of the installed copy, or '' when there is none. + * + * A recorded UUID whose template was deleted counts as not installed, so + * the template can be added again without `--force`. + * + * @param string $templateId The shipped template id. + * + * @return string The UUID, or an empty string. + */ + private function findInstalledUuid(string $templateId): string { + $uuid = $this->store->appConfig->getValueString(Application::APP_ID, self::CONFIG_PREFIX . $templateId, ''); + if ($uuid === '') { + return ''; + } + + try { + $this->store->dashboardMapper->findByUuid(uuid: $uuid); + } catch (DoesNotExistException) { + return ''; + } + + return $uuid; + }//end findInstalledUuid() + + /** + * The Nextcloud dashboard widgets the template shows that no app on this + * instance registers. Such a widget is still placed, so the template has + * one shape everywhere; the list tells the administrator which app is + * missing. + * + * @param array<int, mixed> $widgets The definition's widgets. + * + * @return array<int, string> Widget ids nothing here registers. + */ + private function findMissingWidgets(array $widgets): array { + $registered = []; + foreach ($this->platform->dashboardMgr->getWidgets() as $widget) { + $registered[$widget->getId()] = true; + } + + $missing = []; + foreach ($widgets as $widget) { + if (is_array($widget) === false || ($widget['widgetId'] ?? '') !== 'nc-widget') { + continue; + } + + $proxied = (string)($widget['content']['widgetId'] ?? ''); + if ($proxied !== '' && isset($registered[$proxied]) === false) { + $missing[] = $proxied; + } + } + + return $missing; + }//end findMissingWidgets() + + /** + * The registers the template's lists read, in the order they first + * appear. LaunchPad does not know which of them are on this instance: + * a list that asked to be hidden when its register is not here hides + * itself on the page (REQ-TMPL-022). The administrator reads the + * names and knows which apps the template expects. + * + * @param array<int, mixed> $widgets The definition's widgets. + * + * @return array<int, string> Register slugs, each once. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-022 + */ + private function findRegisters(array $widgets): array { + $registers = []; + foreach ($widgets as $widget) { + if (is_array($widget) === false) { + continue; + } + + // A list names its register at the top of its content, a number + // (the app tiles of Mijn werkdag 4) under `source`. + $content = (array)($widget['content'] ?? []); + if (($widget['widgetId'] ?? '') === 'object-list') { + $registers[] = (string)($content['register'] ?? ''); + } + + if (($widget['widgetId'] ?? '') === 'stat') { + $registers[] = (string)(((array)($content['source'] ?? []))['register'] ?? ''); + } + } + + return array_values(array: array_unique(array: array_filter($registers))); + }//end findRegisters() + + /** + * Wrap the definition in an export archive and import it. + * + * @param array<string, mixed> $definition The shipped definition. + * @param string $userId Who runs the install. + * + * @return array{sourceUuid:string, uuid:string, id:int} The template created. + * + * @throws RuntimeException When the archive cannot be built or the import skips it. + */ + private function importDefinition(array $definition, string $userId): array { + $zipPath = $this->buildArchive(dashboard: $definition['dashboard']); + + try { + $result = $this->importService->import( + zipPath: $zipPath, + preserveUuids: false, + currentUserId: $userId + ); + } finally { + if (file_exists(filename: $zipPath) === true) { + unlink(filename: $zipPath); + } + } + + if ($result['dashboards'] === []) { + $reason = (string)($result['errors'][0]['message'] ?? 'the import created nothing'); + throw new RuntimeException(message: 'Template not installed: ' . $reason); + } + + return $result['dashboards'][0]; + }//end importDefinition() + + /** + * Write a one-dashboard `launchpad-export-v1` archive to a temp file. + * + * @param array<string, mixed> $dashboard The dashboard payload. + * + * @return string Path of the archive. + * + * @throws RuntimeException When the archive cannot be written. + */ + private function buildArchive(array $dashboard): string { + $zipPath = tempnam(directory: sys_get_temp_dir(), prefix: 'launchpad-template-'); + $zip = new ZipArchive(); + if ($zipPath === false || $zip->open(filename: $zipPath, flags: ZipArchive::OVERWRITE) !== true) { + throw new RuntimeException(message: 'Could not write the template archive.'); + } + + $flags = (JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $zip->addFromString( + name: 'manifest.json', + content: (string)json_encode( + value: ['schemaVersion' => 1, 'scope' => 'dashboard', 'dashboardCount' => 1], + flags: $flags + ) + ); + $zip->addFromString( + name: 'dashboards/' . $dashboard['uuid'] . '.json', + content: (string)json_encode(value: $dashboard, flags: $flags) + ); + $zip->close(); + + return $zipPath; + }//end buildArchive() +}//end class diff --git a/lib/Service/ShippedTemplateStore.php b/lib/Service/ShippedTemplateStore.php new file mode 100644 index 000000000..c248a8986 --- /dev/null +++ b/lib/Service/ShippedTemplateStore.php @@ -0,0 +1,46 @@ +<?php + +/** + * ShippedTemplateStore + * + * The dashboard mapper and the app config of the shipped template service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/admin-templates/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCP\IAppConfig; + +/** + * The dashboard mapper and the app config of the shipped template service. + * + * @spec openspec/specs/admin-templates/spec.md + */ +class ShippedTemplateStore { + /** + * Constructor. + * + * @param DashboardMapper $dashboardMapper Looks up an earlier install. + * @param IAppConfig $appConfig Remembers what was installed. + */ + public function __construct( + public readonly DashboardMapper $dashboardMapper, + public readonly IAppConfig $appConfig, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ShippedTemplateStores.php b/lib/Service/ShippedTemplateStores.php new file mode 100644 index 000000000..ec8c8c317 --- /dev/null +++ b/lib/Service/ShippedTemplateStores.php @@ -0,0 +1,54 @@ +<?php + +/** + * ShippedTemplateStores + * + * Where shipped template updates are written: the dashboard and placement mappers, the database and + * app config. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCP\IAppConfig; +use OCP\IDBConnection; + +/** + * Where shipped template updates are written: the dashboard and placement mappers, the database and + * app config. + * + * @spec openspec/specs/dashboards/spec.md + */ +class ShippedTemplateStores { + /** + * Constructor. + * + * @param DashboardMapper $dashboardMapper Counts the members' copies. + * @param WidgetPlacementMapper $placementMapper Reads and writes the template's widgets. + * @param IDBConnection $db One transaction for the template's widgets. + * @param IAppConfig $appConfig Records the installed version. + */ + public function __construct( + public readonly DashboardMapper $dashboardMapper, + public readonly WidgetPlacementMapper $placementMapper, + public readonly IDBConnection $db, + public readonly IAppConfig $appConfig, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ShippedTemplateUpdateRun.php b/lib/Service/ShippedTemplateUpdateRun.php new file mode 100644 index 000000000..f62a41fd3 --- /dev/null +++ b/lib/Service/ShippedTemplateUpdateRun.php @@ -0,0 +1,42 @@ +<?php + +/** + * ShippedTemplateUpdateRun + * + * One update of an installed shipped template. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * One ShippedTemplateUpdateService::update(): the shipped template id and + * its installed template. Built by update() and never handed out. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ +final class ShippedTemplateUpdateRun { + /** + * Constructor + * + * @param string $templateId The shipped template id. + * @param InstalledShippedTemplate $installed Its definition and installed dashboard. + */ + public function __construct( + public readonly string $templateId, + public readonly InstalledShippedTemplate $installed, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ShippedTemplateUpdateService.php b/lib/Service/ShippedTemplateUpdateService.php new file mode 100644 index 000000000..326b2177b --- /dev/null +++ b/lib/Service/ShippedTemplateUpdateService.php @@ -0,0 +1,306 @@ +<?php + +/** + * ShippedTemplateUpdateService + * + * Brings an installed shipped template to the version LaunchPad ships now, + * in place: the template keeps its id, UUID, name, groups and default flag, + * and its widgets become the new version's. Members' copies then follow + * through the existing re-sync ({@see TemplateResyncService}, `merge`). + * + * WHY THE ROWS ARE KEPT. A member's copy remembers, per widget, the id of the + * template widget it was made from. Re-sync matches on that id. So a widget + * that is in both versions keeps its row and is changed there; only a widget + * the new version adds gets a new row, and only one it drops loses its row. + * Replacing every row would still give members the right page, but each of + * their widgets would be removed and added again. + * + * HOW A WIDGET IS RECOGNISED. A definition carries no key per widget, so the + * installed widgets are paired with the new ones in three passes, each pass + * only over what the pass before left: (1) every compared field equal, (2) + * same widget type, same proxied Nextcloud widget and same title, (3) same + * widget type, when exactly one is left on each side. What is then left of + * the new version is added, what is left of the installed one is removed. + * + * NEVER SILENTLY. The result names every widget added, removed and changed, + * and a dry run returns the same lists without writing anything. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Exception\TemplateNotInstalledException; +use OCA\LaunchPad\Kernel\Contracts\ShippedTemplateUpdateServiceInterface; +use RuntimeException; + +/** + * Update an installed shipped template in place and bring its copies along. + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * One operation over the definition, the template's rows, the + * transaction, the recorded version and the re-sync. Splitting it would + * put the write and the version it must stay in step with in two places. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ +class ShippedTemplateUpdateService implements ShippedTemplateUpdateServiceInterface { + /** + * Pairs the installed widgets with the shipped ones and writes the plan. + * + * @var PlacementPairing + */ + private readonly PlacementPairing $pairing; + + /** + * Constructor. + * + * @param ShippedTemplateService $shipped Reads the definition and finds the install. + * @param ShippedTemplateStores $stores The dashboard and placement mappers, the database and app config. + * @param PlacementPayloadHydrator $hydrator Builds a widget from a definition, as the importer does. + * @param TemplateResyncService $resyncService Brings the members' copies along. + */ + public function __construct( + private readonly ShippedTemplateService $shipped, + private readonly ShippedTemplateStores $stores, + private readonly PlacementPayloadHydrator $hydrator, + private readonly TemplateResyncService $resyncService, + ) { + $this->pairing = new PlacementPairing(stores: $stores); + }//end __construct() + + /** + * Update the installed template to the shipped version, or say what + * that would change. + * + * Nothing happens when the installed version is the shipped one or + * newer: the result says so (`upToDate`) and its lists are empty. + * + * @param string $templateId The shipped template id. + * @param bool $dryRun Report only, write nothing. + * @param string $userId Who runs the update (for the re-sync's audit record). + * + * @return array{templateId:string, uuid:string, id:int, name:string, installedVersion:int, version:int, + * upToDate:bool, dryRun:bool, applied:bool, added:array<int,string>, removed:array<int,string>, + * changed:array<int,array{widget:string, fields:array<int,string>}>, unchanged:int, copies:int, + * resync:array{async:bool, affectedCount:int, totalCopies:int}|null} + * + * @throws \InvalidArgumentException When the id is not a shipped template. + * @throws TemplateNotInstalledException When the template is not installed here. + * @throws RuntimeException When the definition is malformed or the write fails. + * + * @SuppressWarnings(PHPMD.BooleanArgumentFlag) + * The flag is the command's `--dry-run` and the request's `dryRun`, one to one. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + public function update(string $templateId, bool $dryRun = false, string $userId = 'cli'): array { + $run = $this->updateRunFor(templateId: $templateId); + + $result = $this->versionReport(run: $run, dryRun: $dryRun); + if ($result['upToDate'] === true) { + return $result; + } + + $plan = $this->planFor(run: $run); + $result = array_merge($result, $this->pairing->describe(plan: $plan)); + if ($dryRun === true) { + return $result; + } + + $this->applyPlan(run: $run, plan: $plan); + + return $this->appliedResult(result: $result, resync: $this->resyncCopies(run: $run, userId: $userId)); + }//end update() + + /** + * Read a shipped template's definition and find its installed template. + * + * @param string $templateId The shipped template id. + * + * @return ShippedTemplateUpdateRun The update. + * + * @throws TemplateNotInstalledException When it was never installed here. + */ + private function updateRunFor(string $templateId): ShippedTemplateUpdateRun { + $definition = $this->shipped->readDefinition(templateId: $templateId); + + return new ShippedTemplateUpdateRun( + templateId: $templateId, + installed: new InstalledShippedTemplate( + definition: $definition, + template: $this->installedTemplate(templateId: $templateId) + ) + ); + }//end updateRunFor() + + /** + * Mark a report as applied and attach the resync outcome. + * + * @param array<string, mixed> $result The report. + * @param array{async: bool, affectedCount: int, totalCopies: int} $resync The resync outcome. + * + * @return array<string, mixed> The final report. + */ + private function appliedResult(array $result, array $resync): array { + $result['applied'] = true; + $result['resync'] = $resync; + + return $result; + }//end appliedResult() + + /** + * The installed template dashboard of a shipped template. + * + * @param string $templateId The shipped template id. + * + * @return Dashboard The template dashboard. + * + * @throws TemplateNotInstalledException When it was never installed here. + */ + private function installedTemplate(string $templateId): Dashboard { + $template = $this->shipped->findInstalled(templateId: $templateId); + if ($template === null) { + throw new TemplateNotInstalledException( + message: 'Template ' . $templateId . ' is not installed here, so there is nothing to update.' + ); + } + + return $template; + }//end installedTemplate() + + /** + * The report before any pairing: who the template is, the installed + * and shipped versions, and empty change lists. + * + * @param ShippedTemplateUpdateRun $run The update. + * @param boolean $dryRun Whether only to report. + * + * @return array<string, mixed> The report. + */ + private function versionReport(ShippedTemplateUpdateRun $run, bool $dryRun): array { + $installedVersion = $this->stores->appConfig->getValueInt( + Application::APP_ID, + ShippedTemplateService::CONFIG_VERSION_PREFIX . $run->templateId, + 0 + ); + + return $this->templateIdentity(run: $run) + + $this->versionState(installed: $run->installed, installedVersion: $installedVersion) + + ['dryRun' => $dryRun, 'applied' => false] + + ['added' => [], 'removed' => [], 'changed' => [], 'unchanged' => 0] + + [ + 'copies' => count($this->stores->dashboardMapper->findByBasedOnTemplate(templateId: $run->installed->dashboardId())), + 'resync' => null, + ]; + }//end versionReport() + + /** + * Which template the report is about. + * + * @param ShippedTemplateUpdateRun $run The update. + * + * @return array{templateId: string, uuid: string, id: int, name: string} + */ + private function templateIdentity(ShippedTemplateUpdateRun $run): array { + return [ + 'templateId' => $run->templateId, + 'uuid' => (string)$run->installed->template->getUuid(), + 'id' => $run->installed->dashboardId(), + 'name' => (string)$run->installed->template->getName(), + ]; + }//end templateIdentity() + + /** + * The version part of the report. + * + * @param InstalledShippedTemplate $installed The installed template. + * @param integer $installedVersion The recorded installed version. + * + * @return array{installedVersion: int, version: int, upToDate: bool} + */ + private function versionState(InstalledShippedTemplate $installed, int $installedVersion): array { + return [ + 'installedVersion' => $installedVersion, + 'version' => $installed->version(), + 'upToDate' => $installedVersion >= $installed->version(), + ]; + }//end versionState() + + /** + * Pair the installed placements with the shipped widgets. + * + * @param ShippedTemplateUpdateRun $run The update. + * + * @return array<string, mixed> The plan. + */ + private function planFor(ShippedTemplateUpdateRun $run): array { + $wanted = []; + foreach ($run->installed->definition['dashboard']['widgets'] as $payload) { + $wanted[] = $this->hydrator->hydrate(dashboardId: $run->installed->dashboardId(), payload: (array)$payload, asTemplate: true); + } + + return $this->pairing->pair( + installed: $this->stores->placementMapper->findByDashboardId(dashboardId: $run->installed->dashboardId()), + wanted: $wanted + ); + }//end planFor() + + /** + * Apply the plan to the template and record the new version. + * + * @param ShippedTemplateUpdateRun $run The update. + * @param array<string, mixed> $plan The pairing plan. + * + * @return void + */ + private function applyPlan(ShippedTemplateUpdateRun $run, array $plan): void { + $this->pairing->apply(template: $run->installed->template, plan: $plan); + $this->stores->appConfig->setValueInt( + Application::APP_ID, + ShippedTemplateService::CONFIG_VERSION_PREFIX . $run->templateId, + $run->installed->version() + ); + }//end applyPlan() + + /** + * Merge the updated template into every copy: a member's own widgets + * stay, every template widget is brought in line, compulsory ones + * included (REQ-RESYNC-003, -004). + * + * @param ShippedTemplateUpdateRun $run The update. + * @param string $userId The acting user. + * + * @return array{async: bool, affectedCount: int, totalCopies: int} + */ + private function resyncCopies(ShippedTemplateUpdateRun $run, string $userId): array { + $resync = $this->resyncService->resync( + templateId: $run->installed->dashboardId(), + strategy: TemplateResyncService::STRATEGY_MERGE, + dryRun: false, + actingAdminId: $userId + ); + + return [ + 'async' => ($resync['async'] ?? false) === true, + 'affectedCount' => (int)($resync['affectedCount'] ?? 0), + 'totalCopies' => (int)($resync['totalCopies'] ?? 0), + ]; + }//end resyncCopies() + +}//end class diff --git a/lib/Service/ShowcaseInstallOptions.php b/lib/Service/ShowcaseInstallOptions.php new file mode 100644 index 000000000..100c4d162 --- /dev/null +++ b/lib/Service/ShowcaseInstallOptions.php @@ -0,0 +1,44 @@ +<?php + +/** + * ShowcaseInstallOptions + * + * The source language and the force flag of one showcase install + * (REQ-DEMO-007, REQ-DEMO-009). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The source language and the force flag of one showcase install. + * + * @spec openspec/specs/demo-data-showcases/spec.md + */ +final class ShowcaseInstallOptions { + /** + * Constructor. + * + * @param string $lang The source language (always `nl` in v1). + * @param bool $force Whether an existing install is replaced. + */ + public function __construct( + public readonly string $lang, + public readonly bool $force, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ShowcasePlatform.php b/lib/Service/ShowcasePlatform.php new file mode 100644 index 000000000..b74b97471 --- /dev/null +++ b/lib/Service/ShowcasePlatform.php @@ -0,0 +1,56 @@ +<?php + +/** + * ShowcasePlatform + * + * The Nextcloud services the demo showcases use: app config, the dashboard manager, URLs and + * events. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Dashboard\IManager; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IAppConfig; +use OCP\IURLGenerator; + +/** + * The Nextcloud services the demo showcases use: app config, the dashboard manager, URLs and + * events. + * + * @spec openspec/specs/dashboards/spec.md + */ +class ShowcasePlatform { + /** + * Constructor. + * + * @param IAppConfig $appConfig App config service. + * @param IManager $dashboardManager Nextcloud dashboard registry. + * @param IURLGenerator $urlGenerator URL generator used to build routed thumbnail URLs that resolve + * from any apps directory. + * @param IEventDispatcher|null $eventDispatcher Event dispatcher for DashboardDeletedEvent (SB1 fix, + * REQ-CSC-001). Nullable for backwards- compat. + */ + public function __construct( + public readonly IAppConfig $appConfig, + public readonly IManager $dashboardManager, + public readonly IURLGenerator $urlGenerator, + public readonly ?IEventDispatcher $eventDispatcher=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/ShowcaseStores.php b/lib/Service/ShowcaseStores.php new file mode 100644 index 000000000..cd36b8917 --- /dev/null +++ b/lib/Service/ShowcaseStores.php @@ -0,0 +1,55 @@ +<?php + +/** + * ShowcaseStores + * + * Where the demo showcases are stored: the dashboard and placement mappers, the database and the + * install lock. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCP\IDBConnection; +use OCP\Lock\ILockingProvider; + +/** + * Where the demo showcases are stored: the dashboard and placement mappers, the database and the + * install lock. + * + * @spec openspec/specs/dashboards/spec.md + */ +class ShowcaseStores { + /** + * Constructor. + * + * @param DashboardMapper $dashboardMapper Dashboard data mapper. + * @param WidgetPlacementMapper $placementMapper Widget placement mapper. + * @param IDBConnection $db Database connection. + * @param ILockingProvider $lockingProvider Advisory lock provider (M8 — concurrency guard on + * installShowcase). + */ + public function __construct( + public readonly DashboardMapper $dashboardMapper, + public readonly WidgetPlacementMapper $placementMapper, + public readonly IDBConnection $db, + public readonly ILockingProvider $lockingProvider, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/StarterWidgetSeeds.php b/lib/Service/StarterWidgetSeeds.php new file mode 100644 index 000000000..8d87d0c49 --- /dev/null +++ b/lib/Service/StarterWidgetSeeds.php @@ -0,0 +1,197 @@ +<?php + +/** + * StarterWidgetSeeds + * + * The starter widgets of a person's first dashboard, as board LpEersteKeer + * lists them: a tile per most-used app, calendar, mail, files, weather and the + * organisation's news. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/runtime-shell/spec.md#req-shell-005 + * @spec openspec/changes/app-tile-widget/specs/app-tile-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The starter widget set, in the seed shape of the default widget bundle. + * + * Each widget works without configuration: an app tile opens one of the + * person's apps, the calendar reads their personal calendar, mail is Nextcloud Mail's + * own dashboard widget, the weather follows their weather status location and + * the news is the organisation's announcements. + * + * @spec openspec/specs/runtime-shell/spec.md#req-shell-005 + */ +final class StarterWidgetSeeds { + /** + * The apps the starter set gives a tile, most used first. Only the ones in + * the person's own app menu get one. + * + * @var array<int, string> + */ + public const MOST_USED_APPS = ['files', 'mail', 'calendar', 'spreed', 'contacts', 'deck', 'tasks', 'notes']; + + /** + * How many app tiles the starter set places, in the eight columns left of + * the calendar. + * + * @var int + */ + public const APP_TILE_COUNT = 4; + + /** + * The app grid the starter set falls back to when the person's app menu is + * unknown, such as a dashboard created from the command line. + * + * @var array<string, mixed> + */ + public const APP_GRID_SEED = [ + 'widgetId' => 'app-tiles', + 'gridX' => 0, + 'gridY' => 0, + 'gridWidth' => 8, + 'gridHeight' => 4, + 'sortOrder' => 0, + 'tile' => null, + 'content' => [ + 'pinned' => [], + 'exclude' => ['launchpad'], + 'showFilter' => true, + 'showMostUsed' => true, + 'mostUsedLimit' => 4, + ], + ]; + + /** + * The seeds after the apps, on a 12-column grid. + * + * @var array<int, array<string, mixed>> + */ + public const SEEDS = [ + [ + 'widgetId' => 'calendar', + 'gridX' => 8, + 'gridY' => 0, + 'gridWidth' => 4, + 'gridHeight' => 4, + 'sortOrder' => 1, + 'tile' => null, + 'content' => [ + 'viewMode' => 'agenda', + 'daysAhead' => 7, + 'internalCalendars' => ['personal'], + 'externalIcsUrls' => [], + ], + ], + [ + 'widgetId' => 'nc-widget', + 'gridX' => 0, + 'gridY' => 4, + 'gridWidth' => 6, + 'gridHeight' => 4, + 'sortOrder' => 2, + 'tile' => null, + 'content' => [ + 'widgetId' => 'mail', + 'displayMode' => 'vertical', + ], + ], + [ + 'widgetId' => 'files', + 'gridX' => 6, + 'gridY' => 4, + 'gridWidth' => 6, + 'gridHeight' => 4, + 'sortOrder' => 3, + 'tile' => null, + ], + [ + 'widgetId' => 'weather', + 'gridX' => 0, + 'gridY' => 8, + 'gridWidth' => 4, + 'gridHeight' => 3, + 'sortOrder' => 4, + 'tile' => null, + ], + [ + 'widgetId' => 'announcements', + 'gridX' => 4, + 'gridY' => 8, + 'gridWidth' => 8, + 'gridHeight' => 3, + 'sortOrder' => 5, + 'tile' => null, + ], + ]; + + /** + * The starter seeds for a person whose app menu holds these apps: a tile + * for each of the most-used apps in it, then the other starter widgets. + * Apps outside {@see self::MOST_USED_APPS} fill the row in menu order. + * With no app menu the apps are one app grid instead. + * + * @param array<int, string> $menuAppIds The app ids in the person's app menu, in menu order. + * + * @return array<int, array<string, mixed>> The seeds, in sort order. + * + * @spec openspec/changes/app-tile-widget/specs/app-tile-widget/spec.md#requirement-a-first-dashboard-starts-with-a-tile-per-most-used-app-req-apptile-003 + */ + public static function seeds(array $menuAppIds): array { + $apps = self::tileApps(menuAppIds: $menuAppIds); + + $seeds = [self::APP_GRID_SEED]; + if ($apps !== []) { + $seeds = []; + foreach ($apps as $index => $appId) { + $seeds[] = [ + 'widgetId' => 'app-tile', + 'gridX' => $index * 2, + 'gridY' => 0, + 'gridWidth' => 2, + 'gridHeight' => 2, + 'sortOrder' => 0, + 'tile' => null, + 'content' => ['appId' => $appId, 'colour' => '', 'showCount' => true], + ]; + } + } + + $seeds = array_merge($seeds, self::SEEDS); + foreach (array_keys($seeds) as $order) { + $seeds[$order]['sortOrder'] = $order; + } + + return $seeds; + }//end seeds() + + /** + * The apps that get a tile: the most-used ones in the menu first, then the + * rest of the menu, at most {@see self::APP_TILE_COUNT}. + * + * @param array<int, string> $menuAppIds The app ids in the person's app menu. + * + * @return array<int, string> The app ids. + */ + private static function tileApps(array $menuAppIds): array { + $menu = array_values(array_unique(array_filter($menuAppIds, static fn ($id): bool => $id !== '' && $id !== 'launchpad'))); + $preferred = array_values(array_intersect(self::MOST_USED_APPS, $menu)); + $apps = array_merge($preferred, array_values(array_diff($menu, $preferred))); + + return array_slice($apps, 0, self::APP_TILE_COUNT); + }//end tileApps() +}//end class diff --git a/lib/Service/StatusReport/StatusReportRefusedException.php b/lib/Service/StatusReport/StatusReportRefusedException.php new file mode 100644 index 000000000..37168f548 --- /dev/null +++ b/lib/Service/StatusReport/StatusReportRefusedException.php @@ -0,0 +1,48 @@ +<?php + +/** + * StatusReportRefusedException + * + * A status report that cannot be made as asked (REQ-DWMS-004). + * + * @category Service + * @package OCA\LaunchPad\Service\StatusReport + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\StatusReport; + +use OCP\DB\QueryBuilder\IQueryBuilder; +use RuntimeException; + +/** + * Refuses a status report, carrying the HTTP status to answer with. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-004-a-dated-status-report-with-a-health-rating + */ +class StatusReportRefusedException extends RuntimeException { + + /** + * Constructor. + * + * @param string $message Why. + * @param int $statusCode The HTTP status. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.1 + */ + public function __construct(string $message, public readonly int $statusCode=400) { + parent::__construct(message: $message); + }//end __construct() +}//end class diff --git a/lib/Service/StatusReport/StatusReportService.php b/lib/Service/StatusReport/StatusReportService.php new file mode 100644 index 000000000..efd4cbea5 --- /dev/null +++ b/lib/Service/StatusReport/StatusReportService.php @@ -0,0 +1,441 @@ +<?php + +/** + * StatusReportService + * + * A dated status report on a body of work: prefilled by the product, finished by a person (REQ-DWMS-004). + * + * @category Service + * @package OCA\LaunchPad\Service\StatusReport + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\StatusReport; + +use OCP\DB\QueryBuilder\IQueryBuilder; +use DateTimeImmutable; +use DateTimeZone; +use OCA\LaunchPad\Service\Reporting\ObjectRows; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\IL10N; + +/** + * Builds and keeps status reports. + * + * A body of work is the objects of one schema in one register, optionally + * filtered, each with a status and optionally a due date, plus the deadline + * of the whole. The product computes the figures and prefills the rating + * and the summary; a person may rewrite the rating and the summary before + * keeping it. The kept report records, per value, whether it was computed + * or written by a person. The figures are always computed again when the + * report is kept, so a person cannot write them. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-004-a-dated-status-report-with-a-health-rating + */ +class StatusReportService { + + /** + * The health ratings. + */ + public const HEALTH = ['on-track', 'at-risk', 'off-track']; + + /** + * The status values that mean an item is closed, unless the request names its own. + */ + public const CLOSED_VALUES = ['closed', 'done', 'completed', 'resolved', 'gesloten', 'afgehandeld']; + + /** + * Within this many days of the deadline, less than NEAR_DONE percent closed is a risk. + */ + public const NEAR_DAYS = 14; + + /** + * The share closed, in percent, a body of work near its deadline needs to be on track. + */ + public const NEAR_DONE = 75; + + /** + * The longest summary kept, in characters. + */ + public const MAX_SUMMARY = 5000; + + /** + * Constructor. + * + * @param ObjectRows $rows The objects of the body of work. + * @param StatusReportStore $store Keeps a report. + * @param ITimeFactory $time Today. + * @param IL10N $l10n The prefilled summary's language. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.2 + */ + public function __construct( + private readonly ObjectRows $rows, + private readonly StatusReportStore $store, + private readonly ITimeFactory $time, + private readonly IL10N $l10n, + ) { + }//end __construct() + + /** + * The prefilled report, not kept: rating, summary and figures all computed. + * + * @param array<string,mixed> $subject The body of work: register, schema, title, deadline, filters, statusProperty, closedValues, dueProperty. + * + * @return array<string,mixed> The draft. + * + * @throws StatusReportRefusedException When the subject is incomplete or its objects cannot be read. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.2 + */ + public function draft(array $subject): array { + $subject = self::subject(input: $subject); + $today = $this->today(); + $rows = $this->rows->rows(register: $subject['register'], schema: $subject['schema'], filters: $subject['filters']); + if ($rows === null) { + throw new StatusReportRefusedException( + message: 'The objects of ' . $subject['register'] . '/' . $subject['schema'] . ' cannot be read.', + statusCode: 409 + ); + } + + $figures = self::figures(rows: $rows, subject: $subject, today: $today); + $health = self::health(figures: $figures); + + return [ + 'date' => $today->format('Y-m-d'), + 'subject' => $subject, + 'health' => $health, + 'summary' => $this->summary(figures: $figures, subject: $subject), + 'figures' => $figures, + 'provenance' => self::provenance(figures: $figures, healthWritten: false, summaryWritten: false), + ]; + }//end draft() + + /** + * Keep a report: computed again, with the person's rating and summary where they wrote one. + * + * @param string $userId Who keeps it. + * @param array<string,mixed> $input The body of work, as for draft(), with the person's `health` + * rating and `summary`, each absent or null to keep the computed one. + * + * @return array<string,mixed> The kept report, as stored. + * + * @throws StatusReportRefusedException When the input is not usable or the report cannot be stored. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ + public function keep(string $userId, array $input): array { + $health = ($input['health'] ?? null); + self::assertHealth(health: $health); + $summary = self::writtenSummary(summary: ($input['summary'] ?? null)); + + $report = $this->draft(subject: array_diff_key($input, ['health' => true, 'summary' => true])); + $healthWritten = ($health !== null && $health !== $report['health']); + $summaryWritten = ($summary !== null && $summary !== $report['summary']); + if ($healthWritten === true) { + $report['health'] = $health; + } + + if ($summaryWritten === true) { + $report['summary'] = $summary; + } + + $report['provenance'] = self::provenance(figures: $report['figures'], healthWritten: $healthWritten, summaryWritten: $summaryWritten); + $report['author'] = $userId; + $report['keptAt'] = (new DateTimeImmutable('@' . $this->time->getTime()))->format(DATE_ATOM); + + $stored = $this->store->save(report: $report); + if ($stored === null) { + throw new StatusReportRefusedException(message: 'The status report could not be stored; OpenRegister is needed to keep it.', statusCode: 503); + } + + return $stored; + }//end keep() + + /** + * Refuse a health rating that is not one of HEALTH; null (keep the computed one) passes. + * + * @param string|null $health The rating the person chose. + * + * @return void + * + * @throws StatusReportRefusedException For an unknown rating. + */ + private static function assertHealth(?string $health): void { + if ($health !== null && in_array($health, self::HEALTH, true) === false) { + throw new StatusReportRefusedException(message: 'The health rating must be one of: ' . implode(', ', self::HEALTH) . '.'); + } + }//end assertHealth() + + /** + * The person's summary, trimmed, or null when they wrote none. + * + * @param string|null $summary The summary as sent. + * + * @return string|null + * + * @throws StatusReportRefusedException When it is empty after trimming or longer than MAX_SUMMARY. + */ + private static function writtenSummary(?string $summary): ?string { + if ($summary === null) { + return null; + } + + $summary = trim($summary); + if ($summary === '' || mb_strlen($summary) > self::MAX_SUMMARY) { + throw new StatusReportRefusedException(message: 'The summary must have between 1 and ' . self::MAX_SUMMARY . ' characters.'); + } + + return $summary; + }//end writtenSummary() + + /** + * Counts of the body of work: total, open, closed, overdue, the share closed and the days to the deadline. + * + * @param list<array<string,mixed>> $rows The objects. + * @param array<string,mixed> $subject The normalised subject. + * @param DateTimeImmutable $today Today, at midnight UTC. + * + * @return array{total:int,open:int,closed:int,overdue:int,percentClosed:int,daysToDeadline:int|null} + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.2 + */ + public static function figures(array $rows, array $subject, DateTimeImmutable $today): array { + $closedValues = array_map('mb_strtolower', $subject['closedValues']); + $total = 0; + $closed = 0; + $overdue = 0; + foreach ($rows as $row) { + $total++; + $status = mb_strtolower(trim((string) self::value(row: $row, property: $subject['statusProperty']))); + if (in_array($status, $closedValues, true) === true) { + $closed++; + continue; + } + + $due = self::day(value: self::value(row: $row, property: $subject['dueProperty'])); + if ($due !== null && $due < $today) { + $overdue++; + } + } + + $days = null; + if ($subject['deadline'] !== null) { + $deadline = self::day(value: $subject['deadline']); + $days = (int) $today->diff($deadline)->format('%r%a'); + } + + $percent = 0; + if ($total > 0) { + $percent = (int) floor(($closed * 100) / $total); + } + + return [ + 'total' => $total, + 'open' => ($total - $closed), + 'closed' => $closed, + 'overdue' => $overdue, + 'percentClosed' => $percent, + 'daysToDeadline' => $days, + ]; + }//end figures() + + /** + * The rating the figures give. + * + * Off track: the deadline passed with items open, or more than a quarter of the open items are overdue. + * At risk: any item is overdue, or the deadline is within NEAR_DAYS days with less than NEAR_DONE percent closed. + * On track otherwise. + * + * @param array<string,int|null> $figures The figures. + * + * @return string One of HEALTH. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.2 + */ + public static function health(array $figures): string { + $days = $figures['daysToDeadline']; + if (($days !== null && $days < 0 && $figures['open'] > 0) || ($figures['overdue'] * 4) > $figures['open']) { + return 'off-track'; + } + + $nearAndBehind = ($days !== null && $days <= self::NEAR_DAYS && $figures['percentClosed'] < self::NEAR_DONE && $figures['open'] > 0); + if ($figures['overdue'] > 0 || $nearAndBehind === true) { + return 'at-risk'; + } + + return 'on-track'; + }//end health() + + /** + * Which values were computed and which a person wrote. + * + * @param array<string,mixed> $figures The figures (always computed). + * @param bool $healthWritten Whether a person chose the rating. + * @param bool $summaryWritten Whether a person wrote the summary. + * + * @return array{date:string,health:string,summary:string,figures:array<string,string>} + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.1 + */ + public static function provenance(array $figures, bool $healthWritten, bool $summaryWritten): array { + $origin = ['computed', 'written']; + + return [ + 'date' => 'computed', + 'health' => $origin[(int) $healthWritten], + 'summary' => $origin[(int) $summaryWritten], + 'figures' => array_fill_keys(array_keys($figures), 'computed'), + ]; + }//end provenance() + + /** + * The request's body of work, checked and with its defaults. + * + * @param array<string,mixed> $input The request. + * + * @return array{register:string,schema:string,title:string,deadline:string|null,filters:array<string,mixed>,statusProperty:string,closedValues:list<string>,dueProperty:string} + * + * @throws StatusReportRefusedException When the register, the schema or the deadline is not usable. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.2 + */ + public static function subject(array $input): array { + $register = trim((string) ($input['register'] ?? '')); + $schema = trim((string) ($input['schema'] ?? '')); + if ($register === '' || $schema === '') { + throw new StatusReportRefusedException(message: 'A status report needs the register and the schema of the body of work.'); + } + + $deadline = trim((string) ($input['deadline'] ?? '')); + if ($deadline === '') { + $deadline = null; + } + + if ($deadline !== null && self::day(value: $deadline) === null) { + throw new StatusReportRefusedException(message: 'The deadline must be a day, as YYYY-MM-DD.'); + } + + $closed = array_values( + array_filter(array_map('strval', (array) ($input['closedValues'] ?? [])), static fn (string $value): bool => trim($value) !== '') + ); + if ($closed === []) { + $closed = self::CLOSED_VALUES; + } + + $filters = $input['filters'] ?? []; + if (is_array($filters) === false) { + $filters = []; + } + + return [ + 'register' => $register, + 'schema' => $schema, + 'title' => trim((string) ($input['title'] ?? '')), + 'deadline' => $deadline, + 'filters' => $filters, + 'statusProperty' => self::nameOr(value: $input['statusProperty'] ?? '', default: 'status'), + 'closedValues' => $closed, + 'dueProperty' => self::nameOr(value: $input['dueProperty'] ?? '', default: 'deadline'), + ]; + }//end subject() + + /** + * A property name from the request, or the default when it names none. + * + * @param mixed $value The request's value. + * @param string $default The default. + * + * @return string + */ + private static function nameOr(mixed $value, string $default): string { + $name = trim((string) $value); + if ($name === '') { + return $default; + } + + return $name; + }//end nameOr() + + /** + * The prefilled summary. + * + * @param array<string,int|null> $figures The figures. + * @param array<string,mixed> $subject The subject. + * + * @return string + */ + private function summary(array $figures, array $subject): string { + $sentences = [ + $this->l10n->t('%1$s of %2$s items closed (%3$s%%).', [$figures['closed'], $figures['total'], $figures['percentClosed']]), + $this->l10n->t('%1$s open, of which %2$s overdue.', [$figures['open'], $figures['overdue']]), + ]; + if ($subject['deadline'] !== null) { + $sentences[] = $this->l10n->t('Deadline %1$s, %2$s days from today.', [$subject['deadline'], $figures['daysToDeadline']]); + } + + return implode(' ', $sentences); + }//end summary() + + /** + * Today at midnight UTC. + * + * @return DateTimeImmutable + */ + private function today(): DateTimeImmutable { + return (new DateTimeImmutable('@' . $this->time->getTime()))->setTimezone(new DateTimeZone('UTC'))->setTime(0, 0); + }//end today() + + /** + * A property of an object, also when nested one level under `object`. + * + * @param array<string,mixed> $row The object. + * @param string $property The property. + * + * @return mixed + */ + private static function value(array $row, string $property): mixed { + if (array_key_exists($property, $row) === true) { + return $row[$property]; + } + + if (is_array($row['object'] ?? null) === true) { + return ($row['object'][$property] ?? null); + } + + return null; + }//end value() + + /** + * The day a value names, at midnight UTC, or null when it names none. + * + * @param mixed $value A date (Y-m-d) or a date-time. + * + * @return DateTimeImmutable|null + */ + private static function day(mixed $value): ?DateTimeImmutable { + if (is_string($value) === false || preg_match('/^\d{4}-\d{2}-\d{2}/', $value) !== 1) { + return null; + } + + $day = DateTimeImmutable::createFromFormat('!Y-m-d', substr($value, 0, 10), new DateTimeZone('UTC')); + if ($day === false || $day->format('Y-m-d') !== substr($value, 0, 10)) { + return null; + } + + return $day; + }//end day() +}//end class diff --git a/lib/Service/StatusReport/StatusReportStore.php b/lib/Service/StatusReport/StatusReportStore.php new file mode 100644 index 000000000..e01651fc1 --- /dev/null +++ b/lib/Service/StatusReport/StatusReportStore.php @@ -0,0 +1,120 @@ +<?php + +/** + * StatusReportStore + * + * Keeps a status report as an OpenRegister object (REQ-DWMS-004). + * + * @category Service + * @package OCA\LaunchPad\Service\StatusReport + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\StatusReport; + +use OCP\DB\QueryBuilder\IQueryBuilder; +use JsonSerializable; +use Psr\Container\ContainerInterface; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Writes a kept status report to launchpad's register through OpenRegister's published object service. + * + * Nothing loads OpenRegister's classes on an instance without it: the + * service and its option values are named as strings and resolved at call + * time, and without them the store answers null. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-004-a-dated-status-report-with-a-health-rating + */ +class StatusReportStore { + + /** + * The register. + */ + public const REGISTER = 'launchpad'; + + /** + * The schema. + */ + public const SCHEMA = 'status_report'; + + /** + * OpenRegister's published object service. + */ + public const OBJECT_SERVICE = 'OCA\\OpenRegister\\Contract\\ObjectServiceInterface'; + + /** + * The save options it takes. + */ + public const SAVE_OPTIONS = 'OCA\\OpenRegister\\Kernel\\Contracts\\Value\\ObjectSaveOptions'; + + /** + * The register and schema a save names. + */ + public const FIND_TARGET = 'OCA\\OpenRegister\\Kernel\\Contracts\\Value\\ObjectFindTarget'; + + /** + * Constructor. + * + * @param ContainerInterface $container Resolves OpenRegister's object service at call time. + * @param LoggerInterface $logger Logs a save that failed. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.1 + */ + public function __construct( + private readonly ContainerInterface $container, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * Store the report; the stored object as an array, or null when it could not be stored. + * + * @param array<string,mixed> $report The report. + * + * @return array<string,mixed>|null + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.1 + */ + public function save(array $report): ?array { + if (class_exists(self::SAVE_OPTIONS) === false || class_exists(self::FIND_TARGET) === false) { + return null; + } + + try { + if ($this->container->has(self::OBJECT_SERVICE) === false) { + return null; + } + + $service = $this->container->get(self::OBJECT_SERVICE); + $target = new (self::FIND_TARGET)(register: self::REGISTER, schema: self::SCHEMA); + $stored = $service->saveObject(object: $report, options: new (self::SAVE_OPTIONS)(target: $target)); + } catch (Throwable $e) { + $this->logger->warning(message: 'launchpad.status_report.save_failed', context: ['exception' => $e->getMessage()]); + return null; + } + + if ($stored instanceof JsonSerializable) { + $stored = $stored->jsonSerialize(); + } + + if (is_array($stored) === false) { + return null; + } + + return $stored; + }//end save() +}//end class diff --git a/lib/Service/StorageReport/StorageFigures.php b/lib/Service/StorageReport/StorageFigures.php new file mode 100644 index 000000000..b67676f7f --- /dev/null +++ b/lib/Service/StorageReport/StorageFigures.php @@ -0,0 +1,310 @@ +<?php + +/** + * StorageFigures + * + * The platform's own storage figures, read from the file cache and the register tables (REQ-DWMS-010). + * + * @category Service + * @package OCA\LaunchPad\Service\StorageReport + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\StorageReport; + +use OCP\DB\QueryBuilder\IQueryBuilder; +use OCP\IDBConnection; +use Throwable; + +/** + * Reads what the platform already records, never walking files or objects. + * + * Every figure is the folder size the file cache keeps at the root of a + * folder (the number Nextcloud's own quota uses), or a row count the + * database answers. A read that fails answers empty (or null for the + * register counts) rather than a guess. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-010-storage-use-per-workspace-and-service-over-time + */ +class StorageFigures { + + /** + * The folders of a home storage reported as services, by their path. + */ + public const HOME_SERVICES = [ + 'files' => 'files', + 'files_trashbin' => 'trash', + 'files_versions' => 'versions', + ]; + + /** + * The tables whose rows can name an uploaded launchpad resource. + */ + public const REFERENCE_TABLES = [ + 'launchpad_dashboards', + 'launchpad_widget_placements', + 'launchpad_tiles', + 'launchpad_admin_settings', + 'launchpad_dash_versions', + 'launchpad_dash_translations', + 'launchpad_kiosk_playlists', + 'launchpad_news', + 'launchpad_role_layout_def', + ]; + + /** + * Rows read per page while looking for references. + */ + private const PAGE = 1000; + + /** + * Constructor. + * + * @param IDBConnection $db The database. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.1 + */ + public function __construct( + private readonly IDBConnection $db, + ) { + }//end __construct() + + /** + * Bytes in each person's files, by user id. + * + * @return array<string,int> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.1 + */ + public function homeUsage(): array { + $usage = []; + foreach ($this->homeFolders(paths: ['files']) as $row) { + $user = self::userOfStorage(storageId: (string) $row['storage_id']); + if ($user !== null) { + $usage[$user] = (($usage[$user] ?? 0) + max(0, (int) $row['size'])); + } + } + + return $usage; + }//end homeUsage() + + /** + * Bytes per service: files, trash and versions over every home, and each app's app data. + * + * @return array<string,int> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.1 + */ + public function serviceUsage(): array { + $usage = []; + foreach ($this->homeFolders(paths: array_keys(self::HOME_SERVICES)) as $row) { + $service = self::HOME_SERVICES[(string) $row['path']] ?? null; + if ($service !== null && self::userOfStorage(storageId: (string) $row['storage_id']) !== null) { + $usage[$service] = (($usage[$service] ?? 0) + max(0, (int) $row['size'])); + } + } + + foreach ($this->select(pathLike: 'appdata_%/%', notLike: 'appdata_%/%/%') as $row) { + $name = basename((string) $row['path']); + if ($name !== '') { + $usage['app:' . $name] = (($usage['app:' . $name] ?? 0) + max(0, (int) $row['size'])); + } + } + + ksort($usage); + return $usage; + }//end serviceUsage() + + /** + * The entries at the top of every trash bin: their owner, name (ending in `.d<deleted at>`) and bytes. + * + * @return list<array{user:string,name:string,bytes:int}> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.3 + */ + public function trashEntries(): array { + $entries = []; + foreach ($this->select(pathLike: 'files_trashbin/files/%', notLike: 'files_trashbin/files/%/%') as $row) { + $user = self::userOfStorage(storageId: (string) $row['storage_id']); + if ($user !== null) { + $entries[] = ['user' => $user, 'name' => (string) $row['name'], 'bytes' => max(0, (int) $row['size'])]; + } + } + + return $entries; + }//end trashEntries() + + /** + * The files uploaded through launchpad's resource pipeline: name, bytes and last change. + * + * @return list<array{name:string,bytes:int,mtime:int}> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.3 + */ + public function uploads(): array { + $uploads = []; + foreach ($this->select(pathLike: 'appdata_%/launchpad/resources/%', notLike: 'appdata_%/launchpad/resources/%/%') as $row) { + $uploads[] = ['name' => (string) $row['name'], 'bytes' => max(0, (int) $row['size']), 'mtime' => (int) ($row['mtime'] ?? 0)]; + } + + return $uploads; + }//end uploads() + + /** + * Every uploaded resource name that some launchpad row still names. + * + * @return array<string,true>|null The names, or null when a table could not be read (then nothing counts as orphaned). + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.3 + */ + public function referencedUploads(): ?array { + $names = []; + try { + foreach (self::REFERENCE_TABLES as $table) { + $offset = 0; + do { + $query = $this->db->getQueryBuilder(); + $query->select('*')->from($table)->setFirstResult($offset)->setMaxResults(self::PAGE); + $result = $query->executeQuery(); + $rows = $result->fetchAll(); + $result->closeCursor(); + foreach ($rows as $row) { + $names += self::resourceNames(text: (string) json_encode($row)); + } + + $offset += self::PAGE; + } while (count($rows) === self::PAGE); + } + } catch (Throwable) { + return null; + } + + return $names; + }//end referencedUploads() + + /** + * Objects per register, by register title; null without OpenRegister. + * + * @return array<string,int>|null + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.1 + */ + public function registerCounts(): ?array { + try { + $query = $this->db->getQueryBuilder(); + $query->select('r.title') + ->selectAlias($query->func()->count('o.id'), 'objects') + ->from('openregister_objects', 'o') + ->innerJoin('o', 'openregister_registers', 'r', $query->expr()->eq('o.register', 'r.id')) + ->groupBy('r.title'); + $result = $query->executeQuery(); + $rows = $result->fetchAll(); + $result->closeCursor(); + } catch (Throwable) { + return null; + } + + $counts = []; + foreach ($rows as $row) { + $counts[(string) $row['title']] = (int) $row['objects']; + } + + ksort($counts); + return $counts; + }//end registerCounts() + + /** + * The resource file names a text names. + * + * @param string $text The text, such as a row as JSON. + * + * @return array<string,true> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.3 + */ + public static function resourceNames(string $text): array { + preg_match_all('/resource_[A-Za-z0-9.]+\.[A-Za-z0-9]+/', $text, $found); + return array_fill_keys($found[0], true); + }//end resourceNames() + + /** + * The user a home storage belongs to, or null for any other storage. + * + * @param string $storageId The storage id, such as `home::anna` or `object::user:anna`. + * + * @return string|null + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.1 + */ + public static function userOfStorage(string $storageId): ?string { + foreach (['home::', 'object::user:'] as $prefix) { + if (str_starts_with($storageId, $prefix) === true && strlen($storageId) > strlen($prefix)) { + return substr($storageId, strlen($prefix)); + } + } + + return null; + }//end userOfStorage() + + /** + * Home-storage folders at these paths, with their storage id and size. + * + * @param list<string> $paths The paths, relative to the storage root. + * + * @return list<array<string,mixed>> + */ + private function homeFolders(array $paths): array { + try { + $query = $this->db->getQueryBuilder(); + $query->select('f.path', 'f.size', 's.id AS storage_id') + ->from('filecache', 'f') + ->innerJoin('f', 'storages', 's', $query->expr()->eq('f.storage', 's.numeric_id')) + ->where($query->expr()->in('f.path', $query->createNamedParameter($paths, IQueryBuilder::PARAM_STR_ARRAY))); + $result = $query->executeQuery(); + $rows = $result->fetchAll(); + $result->closeCursor(); + } catch (Throwable) { + return []; + } + + return array_values($rows); + }//end homeFolders() + + /** + * File-cache rows whose path matches one pattern and not another, with their storage id. + * + * @param string $pathLike The LIKE pattern to match. + * @param string $notLike The LIKE pattern to leave out (deeper paths). + * + * @return list<array<string,mixed>> + */ + private function select(string $pathLike, string $notLike): array { + try { + $query = $this->db->getQueryBuilder(); + $query->select('f.path', 'f.name', 'f.size', 'f.mtime', 's.id AS storage_id') + ->from('filecache', 'f') + ->innerJoin('f', 'storages', 's', $query->expr()->eq('f.storage', 's.numeric_id')) + ->where($query->expr()->like('f.path', $query->createNamedParameter($pathLike))) + ->andWhere($query->expr()->notLike('f.path', $query->createNamedParameter($notLike))); + $result = $query->executeQuery(); + $rows = $result->fetchAll(); + $result->closeCursor(); + } catch (Throwable) { + return []; + } + + return array_values($rows); + }//end select() +}//end class diff --git a/lib/Service/StorageReport/StorageReportRefusedException.php b/lib/Service/StorageReport/StorageReportRefusedException.php new file mode 100644 index 000000000..49d2ce683 --- /dev/null +++ b/lib/Service/StorageReport/StorageReportRefusedException.php @@ -0,0 +1,48 @@ +<?php + +/** + * StorageReportRefusedException + * + * A storage report the caller may not have (REQ-DWMS-010). + * + * @category Service + * @package OCA\LaunchPad\Service\StorageReport + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\StorageReport; + +use OCP\DB\QueryBuilder\IQueryBuilder; +use RuntimeException; + +/** + * Refuses the storage report, carrying the HTTP status to answer with. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-010-storage-use-per-workspace-and-service-over-time + */ +class StorageReportRefusedException extends RuntimeException { + + /** + * Constructor. + * + * @param string $message Why. + * @param int $statusCode The HTTP status. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.4 + */ + public function __construct(string $message, public readonly int $statusCode=403) { + parent::__construct(message: $message); + }//end __construct() +}//end class diff --git a/lib/Service/StorageReport/StorageReportService.php b/lib/Service/StorageReport/StorageReportService.php new file mode 100644 index 000000000..fbbd8995f --- /dev/null +++ b/lib/Service/StorageReport/StorageReportService.php @@ -0,0 +1,383 @@ +<?php + +/** + * StorageReportService + * + * Storage use per workspace and per service, now and over twelve months, with what can be removed (REQ-DWMS-010). + * + * @category Service + * @package OCA\LaunchPad\Service\StorageReport + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\StorageReport; + +use OCP\DB\QueryBuilder\IQueryBuilder; +use DateTimeImmutable; +use DateTimeZone; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\IConfig; +use OCP\IGroupManager; + +/** + * Builds the administrator's storage report. + * + * A workspace is a Nextcloud group: its figure is the files of its members, + * so a person in two groups counts in both, and the total in use is taken + * from the services, not from adding the workspaces up. A service is the + * files, trash or versions over every home, or one app's app data. The + * removable total is named apart from the total in use: trash entries past + * the trash retention, and launchpad uploads no launchpad row names. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-010-storage-use-per-workspace-and-service-over-time + */ +class StorageReportService { + + /** + * Months in the series. + */ + public const MONTHS = 12; + + /** + * Days Nextcloud keeps trash when its retention is `auto`. + */ + public const DEFAULT_RETENTION_DAYS = 30; + + /** + * How old an unreferenced upload must be before it counts as orphaned, so an upload being placed is not. + */ + public const UPLOAD_GRACE_SECONDS = 86400; + + /** + * How many orphaned upload names the report lists. + */ + public const MAX_NAMES = 50; + + /** + * Constructor. + * + * @param StorageFigures $figures The platform's figures. + * @param StorageSeries $series The daily series. + * @param IGroupManager $groups The workspaces and who is an administrator. + * @param IConfig $config The trash retention. + * @param ITimeFactory $time Now. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.1 + */ + public function __construct( + private readonly StorageFigures $figures, + private readonly StorageSeries $series, + private readonly IGroupManager $groups, + private readonly IConfig $config, + private readonly ITimeFactory $time, + ) { + }//end __construct() + + /** + * The report, for an administrator only. + * + * @param string $readerId The caller. + * + * @return array<string,mixed> The report: total, workspaces, services, registers, removable and the series. + * + * @throws StorageReportRefusedException When the caller is not an administrator. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.4 + */ + public function report(string $readerId): array { + if ($readerId === '' || $this->groups->isAdmin($readerId) === false) { + throw new StorageReportRefusedException(message: 'Only an administrator can read the storage report.'); + } + + $now = $this->time->getTime(); + $snapshot = $this->snapshot(); + $series = $this->series->all(); + $series[gmdate('Y-m-d', $now)] = $snapshot; + ksort($series); + $months = self::months(now: $now); + + $workspaces = []; + foreach ($snapshot['workspaces'] as $id => $bytes) { + $workspaces[] = ['id' => $id, 'bytes' => $bytes, 'series' => self::monthly(series: $series, section: 'workspaces', key: $id, months: $months)]; + } + + $services = []; + foreach ($snapshot['services'] as $name => $bytes) { + $services[] = ['name' => $name, 'bytes' => $bytes, 'series' => self::monthly(series: $series, section: 'services', key: $name, months: $months)]; + } + + return [ + 'date' => gmdate('Y-m-d', $now), + 'total' => $snapshot['total'], + 'series' => self::monthly(series: $series, section: null, key: 'total', months: $months), + 'workspaces' => $workspaces, + 'services' => $services, + 'registers' => $this->figures->registerCounts(), + 'removable' => self::removable( + trash: $this->figures->trashEntries(), + uploads: $this->figures->uploads(), + policy: [ + 'retentionDays' => self::retentionDays(setting: (string) $this->config->getSystemValue('trashbin_retention_obligation', 'auto')), + 'referenced' => $this->figures->referencedUploads(), + 'now' => $now, + ] + ), + ]; + }//end report() + + /** + * Take today's snapshot and keep it in the series. + * + * @return array<string,mixed> The snapshot. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.2 + */ + public function recordToday(): array { + $snapshot = $this->snapshot(); + $this->series->record(day: gmdate('Y-m-d', $this->time->getTime()), snapshot: $snapshot); + return $snapshot; + }//end recordToday() + + /** + * The figures now: bytes per workspace, per service, and in total. + * + * @return array{total:int,workspaces:array<string,int>,services:array<string,int>} + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.1 + */ + public function snapshot(): array { + $homes = $this->figures->homeUsage(); + $workspaces = []; + foreach ($this->groups->search('') as $group) { + $bytes = 0; + foreach ($group->getUsers() as $user) { + $bytes += ($homes[$user->getUID()] ?? 0); + } + + $workspaces[$group->getGID()] = $bytes; + } + + ksort($workspaces); + $services = $this->figures->serviceUsage(); + + return ['total' => array_sum($services), 'workspaces' => $workspaces, 'services' => $services]; + }//end snapshot() + + /** + * What can be removed: trash past its retention and uploads nothing names. + * + * The policy holds `retentionDays` (int|null: days trash is kept; null when it is never expired), + * `referenced` (array<string,true>|null: upload names still named; null when unknown) and + * `now` (int: Unix time). + * + * @param list<array{user:string,name:string,bytes:int}> $trash Trash entries. + * @param list<array{name:string,bytes:int,mtime:int}> $uploads Launchpad uploads. + * @param array{retentionDays:int|null,referenced:array<string,true>|null,now:int} $policy What counts as removable. + * + * @return array{total:int,pastRetention:array{count:int,bytes:int,retentionDays:int|null},orphanedUploads:array{count:int,bytes:int,names:list<string>,known:bool}} + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.3 + */ + public static function removable(array $trash, array $uploads, array $policy): array { + $now = (int) $policy['now']; + $past = self::pastRetention(trash: $trash, retentionDays: $policy['retentionDays'], now: $now); + $orphaned = self::orphanedUploads(uploads: $uploads, referenced: $policy['referenced'], now: $now); + + return ['total' => ($past['bytes'] + $orphaned['bytes']), 'pastRetention' => $past, 'orphanedUploads' => $orphaned]; + }//end removable() + + /** + * Trash entries deleted longer ago than the retention. + * + * @param list<array{user:string,name:string,bytes:int}> $trash Trash entries. + * @param int|null $retentionDays Days trash is kept; null when never expired. + * @param int $now Now (Unix time). + * + * @return array{count:int,bytes:int,retentionDays:int|null} + */ + private static function pastRetention(array $trash, ?int $retentionDays, int $now): array { + $past = ['count' => 0, 'bytes' => 0, 'retentionDays' => $retentionDays]; + if ($retentionDays === null) { + return $past; + } + + $cutoff = ($now - ($retentionDays * 86400)); + foreach ($trash as $entry) { + if (preg_match('/\.d(\d+)$/', $entry['name'], $match) === 1 && (int) $match[1] < $cutoff) { + $past['count']++; + $past['bytes'] += $entry['bytes']; + } + } + + return $past; + }//end pastRetention() + + /** + * Uploads nothing names any more and older than the grace period. + * + * @param list<array{name:string,bytes:int,mtime:int}> $uploads Launchpad uploads. + * @param array<string,true>|null $referenced Upload names still named; null when unknown. + * @param int $now Now (Unix time). + * + * @return array{count:int,bytes:int,names:list<string>,known:bool} + */ + private static function orphanedUploads(array $uploads, ?array $referenced, int $now): array { + $orphaned = ['count' => 0, 'bytes' => 0, 'names' => [], 'known' => ($referenced !== null)]; + if ($referenced === null) { + return $orphaned; + } + + foreach ($uploads as $upload) { + if (isset($referenced[$upload['name']]) === true || $upload['mtime'] > ($now - self::UPLOAD_GRACE_SECONDS)) { + continue; + } + + $orphaned['count']++; + $orphaned['bytes'] += $upload['bytes']; + if (count($orphaned['names']) < self::MAX_NAMES) { + $orphaned['names'][] = $upload['name']; + } + } + + return $orphaned; + }//end orphanedUploads() + + /** + * The days after which trash may be removed, from Nextcloud's `trashbin_retention_obligation`. + * + * `auto` keeps 30 days; `D, auto` and `auto, D` and `D1, D2` remove at the latest after their last + * number of days; `D` alone too; `disabled` never expires trash, so nothing is past retention. + * + * @param string $setting The setting. + * + * @return int|null The days, or null when trash is never expired. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.3 + */ + public static function retentionDays(string $setting): ?int { + $parts = array_map('trim', explode(',', strtolower($setting))); + if (in_array('disabled', $parts, true) === true) { + return null; + } + + $days = array_values(array_filter($parts, static fn (string $part): bool => ctype_digit($part))); + if ($days === []) { + return self::DEFAULT_RETENTION_DAYS; + } + + return (int) end($days); + }//end retentionDays() + + /** + * The report as CSV: the total, each workspace and service with its twelve months, and the removable total. + * + * @param array<string,mixed> $report A report from report(). + * + * @return string The CSV. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.4 + */ + public static function csv(array $report): string { + $months = array_keys((array) ($report['series'] ?? [])); + $out = fopen('php://temp', 'r+'); + fputcsv($out, array_merge(['kind', 'name', 'bytes'], $months), ',', '"', ''); + fputcsv($out, array_merge(['total', '', (string) $report['total']], self::cells(series: (array) $report['series'])), ',', '"', ''); + foreach ((array) $report['workspaces'] as $workspace) { + fputcsv($out, array_merge(['workspace', $workspace['id'], (string) $workspace['bytes']], self::cells(series: $workspace['series'])), ',', '"', ''); + } + + foreach ((array) $report['services'] as $service) { + fputcsv($out, array_merge(['service', $service['name'], (string) $service['bytes']], self::cells(series: $service['series'])), ',', '"', ''); + } + + $removable = (array) $report['removable']; + fputcsv($out, ['removable', 'past retention', (string) $removable['pastRetention']['bytes']], ',', '"', ''); + fputcsv($out, ['removable', 'orphaned uploads', (string) $removable['orphanedUploads']['bytes']], ',', '"', ''); + fputcsv($out, ['removable', 'total', (string) $removable['total']], ',', '"', ''); + rewind($out); + $csv = (string) stream_get_contents($out); + fclose($out); + + return $csv; + }//end csv() + + /** + * The last MONTHS months (Y-m), oldest first, ending with the month of now. + * + * @param int $now Now (Unix time). + * + * @return list<string> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.2 + */ + public static function months(int $now): array { + $first = (new DateTimeImmutable('@' . $now))->setTimezone(new DateTimeZone('UTC'))->modify('first day of this month'); + $months = []; + for ($back = (self::MONTHS - 1); $back >= 0; $back--) { + $months[] = $first->modify('-' . $back . ' months')->format('Y-m'); + } + + return $months; + }//end months() + + /** + * Per month, the value of the month's last snapshot; null for a month without one. + * + * @param array<string,array<string,mixed>> $series The snapshots by day, oldest first. + * @param string|null $section `workspaces`, `services`, or null for a top-level value. + * @param string $key The workspace, the service, or `total`. + * @param list<string> $months The months (Y-m). + * + * @return array<string,int|null> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.2 + */ + public static function monthly(array $series, ?string $section, string $key, array $months): array { + $values = array_fill_keys($months, null); + foreach ($series as $day => $snapshot) { + $month = substr((string) $day, 0, 7); + if (array_key_exists($month, $values) === false) { + continue; + } + + $value = $snapshot[$key] ?? null; + if ($section !== null) { + $value = $snapshot[$section][$key] ?? null; + } + + if ($value !== null) { + $values[$month] = (int) $value; + } + } + + return $values; + }//end monthly() + + /** + * A series as CSV cells, empty for a month without a snapshot. + * + * @param array<string,int|null> $series The series. + * + * @return list<string> + */ + private static function cells(array $series): array { + $cells = []; + foreach ($series as $value) { + $cells[] = (string) $value; + } + + return $cells; + }//end cells() +}//end class diff --git a/lib/Service/StorageReport/StorageSeries.php b/lib/Service/StorageReport/StorageSeries.php new file mode 100644 index 000000000..6a6e0a795 --- /dev/null +++ b/lib/Service/StorageReport/StorageSeries.php @@ -0,0 +1,123 @@ +<?php + +/** + * StorageSeries + * + * The daily storage series, kept in launchpad's app data (REQ-DWMS-010). + * + * @category Service + * @package OCA\LaunchPad\Service\StorageReport + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\StorageReport; + +use OCP\DB\QueryBuilder\IQueryBuilder; +use OCP\Files\IAppData; +use OCP\Files\NotFoundException; + +/** + * One snapshot per day, at most DAYS of them, in one JSON file of app data. + * + * A snapshot holds totals only (bytes per workspace, per service and in + * all), never a file or a person's files, the same daily-bucket shape the + * dashboard view analytics keep. No table is added for it. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-010-storage-use-per-workspace-and-service-over-time + */ +class StorageSeries { + + /** + * The app data folder. + */ + public const FOLDER = 'storage-report'; + + /** + * The file in it. + */ + public const FILE = 'series.json'; + + /** + * How many daily snapshots are kept. + */ + public const DAYS = 400; + + /** + * Constructor. + * + * @param IAppData $appData Launchpad's app data. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.2 + */ + public function __construct( + private readonly IAppData $appData, + ) { + }//end __construct() + + /** + * The kept snapshots by day (Y-m-d), oldest first. + * + * @return array<string,array<string,mixed>> + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.2 + */ + public function all(): array { + try { + $content = $this->appData->getFolder(self::FOLDER)->getFile(self::FILE)->getContent(); + } catch (NotFoundException) { + return []; + } + + $series = json_decode($content, true); + if (is_array($series) === false) { + return []; + } + + ksort($series); + return $series; + }//end all() + + /** + * Keep a day's snapshot, replacing that day's earlier one and dropping the oldest beyond DAYS. + * + * @param string $day The day (Y-m-d). + * @param array<string,mixed> $snapshot The totals. + * + * @return array<string,array<string,mixed>> The series as kept. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-8.2 + */ + public function record(string $day, array $snapshot): array { + $series = $this->all(); + $series[$day] = $snapshot; + ksort($series); + $series = array_slice($series, -self::DAYS, null, true); + + try { + $folder = $this->appData->getFolder(self::FOLDER); + } catch (NotFoundException) { + $folder = $this->appData->newFolder(self::FOLDER); + } + + $content = (string) json_encode($series); + try { + $folder->getFile(self::FILE)->putContent($content); + } catch (NotFoundException) { + $folder->newFile(self::FILE, $content); + } + + return $series; + }//end record() +}//end class diff --git a/lib/Service/StoreInstallFlow.php b/lib/Service/StoreInstallFlow.php new file mode 100644 index 000000000..0c2b53570 --- /dev/null +++ b/lib/Service/StoreInstallFlow.php @@ -0,0 +1,47 @@ +<?php + +/** + * StoreInstallFlow + * + * The install record (REQ-STORE-011) and the in-place update (REQ-STORE-012) + * the store endpoints use together, so the controller takes one parameter for + * them. Either may be absent; the controller then skips what it needs. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The install record and the updater of the marketplace. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ +class StoreInstallFlow { + /** + * Constructor. + * + * @param StoreInstalls|null $installs Which item and version an install created which dashboard. + * @param StoreUpdateService|null $updates Brings an installed item to a newer version in place. + * + * @return void + */ + public function __construct( + public readonly ?StoreInstalls $installs = null, + public readonly ?StoreUpdateService $updates = null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/StoreInstalls.php b/lib/Service/StoreInstalls.php new file mode 100644 index 000000000..eb2354fac --- /dev/null +++ b/lib/Service/StoreInstalls.php @@ -0,0 +1,247 @@ +<?php + +/** + * LaunchPad Store Installs. + * + * Which register item and version an install created which dashboard + * (REQ-STORE-011), so the marketplace shows Installed with Open, Update when + * the register offers a newer version, or Available. Kept in the app config + * as one map by item slug; a deleted dashboard drops its entry. + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCP\IAppConfig; +use Throwable; + +/** + * The install record of the marketplace. + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-011-an-installed-template-opens-instead-of-installing-again + */ +class StoreInstalls { + + /** + * The app config key holding the map. + */ + public const CONFIG_KEY = 'store_installs'; + + /** + * Constructor. + * + * @param IAppConfig $appConfig Holds the map. + * @param StoreOpenLinks|null $links Where an installed item opens; without it there is no Open. + * @param WidgetPlacementMapper|null $placements Reads which widgets an install created (REQ-STORE-012). + * + * @return void + */ + public function __construct( + private readonly IAppConfig $appConfig, + private readonly ?StoreOpenLinks $links = null, + private readonly ?WidgetPlacementMapper $placements = null, + ) { + }//end __construct() + + /** + * Every install by item slug: the version, the dashboard it created and + * the widgets on it that came from the install. `placementIds` is empty for + * a record written before the widgets were kept (REQ-STORE-012). + * + * @return array<string, array{version: string, dashboardId: int, dashboardUuid: string, placementIds: list<int>}> + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-011-an-installed-template-opens-instead-of-installing-again + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + public function all(): array { + $decoded = json_decode(json: $this->appConfig->getValueString(Application::APP_ID, self::CONFIG_KEY, '{}'), associative: true); + if (is_array($decoded) === false) { + return []; + } + + $installs = []; + foreach ($decoded as $slug => $entry) { + if (is_array($entry) === true && (int)($entry['dashboardId'] ?? 0) > 0) { + $installs[(string)$slug] = [ + 'version' => (string)($entry['version'] ?? ''), + 'dashboardId' => (int)$entry['dashboardId'], + 'dashboardUuid' => (string)($entry['dashboardUuid'] ?? ''), + 'placementIds' => self::ids(value: ($entry['placementIds'] ?? [])), + ]; + } + } + + return $installs; + }//end all() + + /** + * Record that an install of this item and version created this dashboard. + * + * The widgets that came from the install are kept with it, so an update + * later replaces those and leaves the ones a person added (REQ-STORE-012). + * Without a list they are read from the dashboard, which right after an + * install holds only the install's widgets. + * + * @param string $slug The register item slug. + * @param string $version The installed version. + * @param array $dashboard The dashboard the install created: `{id, uuid}`, and optionally + * `placementIds`, the widgets that came from the install. + * + * @return void + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-011-an-installed-template-opens-instead-of-installing-again + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + public function record(string $slug, string $version, array $dashboard): void { + $dashboardId = (int)($dashboard['id'] ?? 0); + if ($slug === '' || $dashboardId <= 0) { + return; + } + + $installs = $this->all(); + $installs[$slug] = [ + 'version' => $version, + 'dashboardId' => $dashboardId, + 'dashboardUuid' => (string)($dashboard['uuid'] ?? ''), + 'placementIds' => self::ids(value: ($dashboard['placementIds'] ?? $this->placementIdsOf(dashboardId: $dashboardId))), + ]; + $this->store(installs: $installs); + }//end record() + + /** + * The ids of the widgets a dashboard holds now, or none when they cannot be read. + * + * @param int $dashboardId The dashboard. + * + * @return list<int> The placement ids. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + private function placementIdsOf(int $dashboardId): array { + if ($this->placements === null) { + return []; + } + + try { + $ids = []; + foreach ($this->placements->findByDashboardId(dashboardId: $dashboardId) as $placement) { + $ids[] = (int)$placement->getId(); + } + + return $ids; + } catch (Throwable) { + return []; + } + }//end placementIdsOf() + + /** + * A stored id list as positive integers. + * + * @param mixed $value The stored value. + * + * @return list<int> The ids. + */ + private static function ids(mixed $value): array { + if (is_array($value) === false) { + return []; + } + + return array_values(array_filter(array_map('intval', $value), static fn (int $id): bool => $id > 0)); + }//end ids() + + /** + * Drop the entries of a dashboard that no longer exists. + * + * @param int $dashboardId The deleted dashboard. + * + * @return int The number of entries dropped. + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-011-an-installed-template-opens-instead-of-installing-again + */ + public function forget(int $dashboardId): int { + $installs = $this->all(); + $kept = array_filter($installs, static fn (array $entry): bool => $entry['dashboardId'] !== $dashboardId); + $dropped = count($installs) - count($kept); + if ($dropped > 0) { + $this->store(installs: $kept); + } + + return $dropped; + }//end forget() + + /** + * The cards with their install state: Installed (with the dashboard to + * open), Update when the register's version is newer, or Available. The + * fields are the ones the store page reads: `installed`, + * `installedVersion`, `updateAvailable` and `openUrl` (its Open action), + * plus `status` and `installedDashboardId`. + * + * @param array<int, array<string, mixed>> $cards The register's cards. + * + * @return array<int, array<string, mixed>> The cards with their state. + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-011-an-installed-template-opens-instead-of-installing-again + */ + public function annotate(array $cards): array { + $installs = $this->all(); + $links = $this->links; + + return array_map( + static function (mixed $card) use ($installs, $links): mixed { + if (is_array($card) === false) { + return $card; + } + + $install = $installs[(string)($card['slug'] ?? '')] ?? null; + if ($install === null) { + return $card + ['installed' => false, 'updateAvailable' => false, 'status' => 'available']; + } + + $newer = version_compare((string)($card['version'] ?? ''), $install['version'], '>'); + $status = 'installed'; + if ($newer === true) { + $status = 'update'; + } + + return $card + [ + 'installed' => true, + 'installedVersion' => $install['version'], + 'installedDashboardId' => $install['dashboardId'], + 'openUrl' => ($links?->openUrl(uuid: $install['dashboardUuid']) ?? ''), + 'updateAvailable' => $newer, + 'status' => $status, + ]; + }, + $cards + ); + }//end annotate() + + /** + * Write the map. + * + * @param array<string, array{version: string, dashboardId: int, dashboardUuid: string, placementIds: list<int>}> $installs The installs. + * + * @return void + */ + private function store(array $installs): void { + $this->appConfig->setValueString(Application::APP_ID, self::CONFIG_KEY, (string)json_encode(value: $installs)); + }//end store() + +}//end class diff --git a/lib/Service/StoreOpenLinks.php b/lib/Service/StoreOpenLinks.php new file mode 100644 index 000000000..1706c3887 --- /dev/null +++ b/lib/Service/StoreOpenLinks.php @@ -0,0 +1,80 @@ +<?php + +/** + * LaunchPad Store Open Links. + * + * Where the Open action of an installed marketplace item goes: the installed + * dashboard's own address in the workspace (REQ-STORE-011). + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\IURLGenerator; +use Throwable; + +/** + * The address an installed item opens. + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-011-an-installed-template-opens-instead-of-installing-again + */ +class StoreOpenLinks { + + /** + * Constructor. + * + * @param IURLGenerator $urls The route builder. + * @param DashboardTreeService $tree The dashboard's slug path. + * + * @return void + */ + public function __construct( + private readonly IURLGenerator $urls, + private readonly DashboardTreeService $tree, + ) { + }//end __construct() + + /** + * The workspace address of a dashboard: its deep link when it has a slug + * path, the workspace itself otherwise; '' when the dashboard is gone. + * + * @param string $uuid The dashboard uuid. + * + * @return string The address, or ''. + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-011-an-installed-template-opens-instead-of-installing-again + */ + public function openUrl(string $uuid): string { + if ($uuid === '') { + return ''; + } + + try { + $path = trim(string: $this->tree->computePath(uuid: $uuid), characters: '/'); + } catch (Throwable) { + return ''; + } + + if ($path === '') { + return $this->urls->linkToRoute(routeName: 'launchpad.page.index'); + } + + return $this->urls->linkToRoute(routeName: 'launchpad.page.deepLink', arguments: ['deepLink' => $path]); + }//end openUrl() + +}//end class diff --git a/lib/Service/StoreRegistryBanner.php b/lib/Service/StoreRegistryBanner.php new file mode 100644 index 000000000..5a7ec0588 --- /dev/null +++ b/lib/Service/StoreRegistryBanner.php @@ -0,0 +1,66 @@ +<?php + +/** + * LaunchPad Store Registry Banner. + * + * The connected register as the marketplace banner names it (REQ-STORE-010): + * its name and its address, never its token. + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @link https://conduction.nl + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Name and address of the configured register, for the marketplace banner. + * + * The address is the configured base URL without credentials, query or + * fragment; the name is the one the administrator gave, else the host. The + * token is never an input, so it can never ride along. + */ +final class StoreRegistryBanner { + /** + * Build the banner from the stored URL and name. + * + * @param string $url The configured register base URL. + * @param string $name The configured display name, may be empty. + * + * @return array{name: string, url: string}|null Null when no usable URL is configured. + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-010-the-marketplace-shows-dashboard-templates-as-cards + */ + public function from(string $url, string $name): ?array { + $parts = parse_url(url: trim($url)); + if (is_array(value: $parts) === false || isset($parts['host']) === false) { + return null; + } + + $address = ($parts['scheme'] ?? 'https').'://'.$parts['host']; + if (isset($parts['port']) === true) { + $address .= ':'.$parts['port']; + } + + $address .= ($parts['path'] ?? ''); + + $name = trim($name); + if ($name === '') { + $name = $parts['host']; + } + + return ['name' => $name, 'url' => $address]; + }//end from() +}//end class diff --git a/lib/Service/StoreService.php b/lib/Service/StoreService.php index af51ac181..9c33374df 100644 --- a/lib/Service/StoreService.php +++ b/lib/Service/StoreService.php @@ -82,6 +82,9 @@ class StoreService { 'category' => 'category', 'version' => 'version', 'publisher' => 'publisher', + // REQ-STORE-010: the card's widget count and how many organisations use it. + 'widgets' => 'widgets', + 'usage' => 'usage', ]; /** @@ -92,6 +95,17 @@ class StoreService { */ private const DESCRIPTOR_CLASS = 'OCA\\OpenRegister\\AppHost\\Service\\StoreDescriptor'; + /** + * The read half of the descriptor, in OpenRegister releases that split it + * into a listing and a sharing part. Absent in older releases. + */ + private const LISTING_CLASS = 'OCA\\OpenRegister\\AppHost\\Service\\StoreListing'; + + /** + * The share half of the descriptor, next to {@see self::LISTING_CLASS}. + */ + private const SHARING_CLASS = 'OCA\\OpenRegister\\AppHost\\Service\\StoreSharing'; + /** * Outcome reported when there is nothing to talk to. */ @@ -105,13 +119,25 @@ class StoreService { /** * Config key holding the registry Bearer token. */ - public const CONFIG_TOKEN = 'registry_token'; + public const CONFIG_REGISTRY_AUTH = 'registry_token'; + + /** + * Former name of CONFIG_REGISTRY_AUTH. + * + * @deprecated Use CONFIG_REGISTRY_AUTH. + */ + public const CONFIG_TOKEN = self::CONFIG_REGISTRY_AUTH; /** * Config key holding the remote register segment. */ public const CONFIG_REGISTER = 'registry_register'; + /** + * Config key holding the register's display name for the marketplace banner. + */ + public const CONFIG_NAME = 'registry_name'; + /** * Constructor. * @@ -163,7 +189,7 @@ public function isAvailable(): bool { * @param string|null $query Optional free-text search term. * @param string|null $kind Optional kind filter. * - * @return array{outcome: string, cards: array<int, array<string, mixed>>} + * @return array{outcome: string, cards: array<int, array<string, mixed>>, checkedAt?: string} * * @spec openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md#requirement-req-store-003-the-engines-outcome-must-reach-the-caller-unchanged * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md#requirement-req-lp-conn-003-launchpad-reports-what-its-outbound-calls-met @@ -182,7 +208,7 @@ public function search(?string $query = null, ?string $kind = null): array { * @param string|null $query Optional free-text search term. * @param string|null $kind Optional kind filter. * - * @return array{outcome: string, cards: array<int, array<string, mixed>>} + * @return array{outcome: string, cards: array<int, array<string, mixed>>, checkedAt?: string} * * @psalm-suppress MixedMethodCall The discovery client is untyped on purpose. * @@ -208,12 +234,39 @@ private function searchRegistry(?string $query, ?string $kind): array { $cards = []; } - return [ - 'outcome' => (string)($result['outcome'] ?? self::OUTCOME_NOT_CONFIGURED), - 'cards' => $cards, - ]; + $outcome = (string)($result['outcome'] ?? self::OUTCOME_NOT_CONFIGURED); + $answer = ['outcome' => $outcome, 'cards' => $cards]; + + // REQ-STORE-010: when the register was last checked. The engine's own + // time wins (it may answer from a cache); otherwise this search was it. + $checkedAt = ($result['checkedAt'] ?? null); + if (is_string($checkedAt) === true && $checkedAt !== '') { + $answer['checkedAt'] = $checkedAt; + } else if ($outcome !== self::OUTCOME_NOT_CONFIGURED) { + $answer['checkedAt'] = gmdate(format: 'Y-m-d\TH:i:s\Z'); + } + + return $answer; }//end searchRegistry() + /** + * The connected register as the marketplace banner names it. + * + * The address is the configured base URL without credentials, query or + * fragment; the name is the one the administrator gave, else the host. + * Null when no register URL is configured. The token never rides along. + * + * @return array{name: string, url: string}|null + * + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-010-the-marketplace-shows-dashboard-templates-as-cards + */ + public function registryBanner(): ?array { + return (new StoreRegistryBanner())->from( + url: $this->config(key: self::CONFIG_URL), + name: $this->config(key: self::CONFIG_NAME) + ); + }//end registryBanner() + /** * Install one remote dashboard template into this instance. * @@ -229,26 +282,21 @@ private function searchRegistry(?string $query, ?string $kind): array { * @param string $slug The remote item slug. * @param string $userId The installing administrator's UID. * - * @return array{success: bool, message: string, components: array<int, array<string, string>>} + * @return array{success: bool, message: string, components: array<int, array<string, string>>, + * version?: string, dashboardIds?: list<int>, created?: list<array<string, mixed>>} * * @psalm-suppress MixedMethodCall The discovery client is untyped on purpose. * * @spec openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md#requirement-req-store-005-an-install-must-reuse-importservice-not-reimplement-it + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-011-an-installed-template-opens-instead-of-installing-again */ public function install(string $slug, string $userId): array { - if ($this->discovery === null) { - return $this->failure(message: 'No dashboard registry is available on this instance.'); + $resolved = $this->resolveItem(slug: $slug); + if (isset($resolved['dashboards']) === false) { + return $this->failure(message: $resolved['message']); } - $item = $this->discovery->resolve(descriptor: $this->descriptor(), slug: $slug); - if (is_array($item) === false) { - return $this->failure(message: 'That template could not be found in the registry.'); - } - - $dashboards = $this->dashboardsFrom(item: $item); - if ($dashboards === []) { - return $this->failure(message: 'That template carries no dashboard.'); - } + $dashboards = $resolved['dashboards']; try { $archivePath = $this->materialise(dashboards: $dashboards, slug: $slug, userId: $userId); @@ -280,9 +328,48 @@ public function install(string $slug, string $userId): array { $this->discard(path: $archivePath); }//end try - return $this->report(report: $report, dashboards: $dashboards); + // REQ-STORE-011: what the install created, for the install record. + return $this->report(report: $report, dashboards: $dashboards) + [ + 'version' => $resolved['version'], + 'dashboardIds' => array_values(array_map('intval', array_column((array)($report['dashboards'] ?? []), 'id'))), + 'created' => array_values((array)($report['dashboards'] ?? [])), + ]; }//end install() + /** + * Resolve one register item to its version and dashboard payloads. + * + * Install and update read the register the same way, so a payload an + * install accepts is the payload an update accepts. + * + * @param string $slug The remote item slug. + * + * @return array{version: string, dashboards: array<int, array<string, mixed>>}|array{message: string} + * The item, or the sentence the administrator reads when there is none. + * + * @psalm-suppress MixedMethodCall The discovery client is untyped on purpose. + * + * @spec openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md#requirement-req-store-005-an-install-must-reuse-importservice-not-reimplement-it + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + public function resolveItem(string $slug): array { + if ($this->discovery === null) { + return ['message' => 'No dashboard registry is available on this instance.']; + } + + $item = $this->discovery->resolve(descriptor: $this->descriptor(), slug: $slug); + if (is_array($item) === false) { + return ['message' => 'That template could not be found in the registry.']; + } + + $dashboards = $this->dashboardsFrom(item: $item); + if ($dashboards === []) { + return ['message' => 'That template carries no dashboard.']; + } + + return ['version' => (string)($item['version'] ?? ''), 'dashboards' => $dashboards]; + }//end resolveItem() + /** * The registry connection, with the token redacted. * @@ -291,15 +378,17 @@ public function install(string $slug, string $userId): array { * credential in a browser response, and the form does not need it: an empty * submission clears the token and a non-empty one replaces it. * - * @return array{registryUrl: string, registryRegister: string, tokenConfigured: bool} + * @return array{registryUrl: string, registryRegister: string, registryName: string, tokenConfigured: bool} * * @spec openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md#requirement-req-store-007-the-registry-token-must-not-be-readable-back + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-010-the-marketplace-shows-dashboard-templates-as-cards */ public function getRegistryConfig(): array { return [ 'registryUrl' => $this->config(key: self::CONFIG_URL), 'registryRegister' => $this->config(key: self::CONFIG_REGISTER), - 'tokenConfigured' => ($this->config(key: self::CONFIG_TOKEN) !== ''), + 'registryName' => $this->config(key: self::CONFIG_NAME), + 'tokenConfigured' => ($this->config(key: self::CONFIG_REGISTRY_AUTH) !== ''), ]; }//end getRegistryConfig() @@ -313,6 +402,7 @@ public function getRegistryConfig(): array { * @param string|null $registryUrl Registry base URL, or null to leave it. * @param string|null $registryToken Bearer token, or null to leave it. * @param string|null $registryRegister Remote register segment, or null to leave it. + * @param string|null $registryName Display name for the marketplace banner, or null to leave it. * * After the write it asks integriq to resolve the dashboard registry again * when a registry key was written (adopt-connection-registry). That never @@ -323,11 +413,13 @@ public function getRegistryConfig(): array { * * @spec openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md#requirement-req-store-007-the-registry-token-must-not-be-readable-back * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md#requirement-req-lp-conn-002-a-registry-settings-save-asks-integriq-to-look-again + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-010-the-marketplace-shows-dashboard-templates-as-cards */ public function updateRegistryConfig( ?string $registryUrl = null, ?string $registryToken = null, ?string $registryRegister = null, + ?string $registryName = null, ): void { $written = []; @@ -337,8 +429,8 @@ public function updateRegistryConfig( } if ($registryToken !== null) { - $this->appConfig->setValueString(Application::APP_ID, self::CONFIG_TOKEN, trim($registryToken)); - $written[] = self::CONFIG_TOKEN; + $this->appConfig->setValueString(Application::APP_ID, self::CONFIG_REGISTRY_AUTH, trim($registryToken)); + $written[] = self::CONFIG_REGISTRY_AUTH; } if ($registryRegister !== null) { @@ -346,6 +438,11 @@ public function updateRegistryConfig( $written[] = self::CONFIG_REGISTER; } + // A name is a label only; it does not ask integriq to look again. + if ($registryName !== null) { + $this->appConfig->setValueString(Application::APP_ID, self::CONFIG_NAME, trim($registryName)); + } + $this->connectionReporter?->refreshFromSave(savedKeys: $written); }//end updateRegistryConfig() @@ -360,6 +457,8 @@ public function updateRegistryConfig( * @throws RuntimeException When OpenRegister supplied a client but not a descriptor class. * * @psalm-suppress MixedMethodCall Instantiated from a class string by design. + * + * @spec openspec/specs/dashboard-store/spec.md */ private function descriptor(): object { $class = self::DESCRIPTOR_CLASS; @@ -367,6 +466,23 @@ private function descriptor(): object { throw new RuntimeException(message: 'OpenRegister store descriptor is unavailable.'); } + // OpenRegister now builds the descriptor from a listing and a sharing + // part (the two classes ship together); named arguments for the old + // flat form are an Error there. + if (class_exists(self::LISTING_CLASS) === true) { + $listingClass = self::LISTING_CLASS; + $sharingClass = self::SHARING_CLASS; + return new $class( + listing: new $listingClass( + appId: Application::APP_ID, + schema: self::REMOTE_SCHEMA, + defaultRegister: self::DEFAULT_REGISTER, + cardFields: self::CARD_FIELDS + ), + sharing: new $sharingClass(types: []) + ); + } + return new $class( appId: Application::APP_ID, schema: self::REMOTE_SCHEMA, @@ -422,16 +538,8 @@ private function dashboardsFrom(array $item): array { * @throws RuntimeException When the archive cannot be allocated or opened. */ private function materialise(array $dashboards, string $slug, string $userId): string { - $tempPath = tempnam(directory: sys_get_temp_dir(), prefix: 'launchpad-store-'); - if ($tempPath === false) { - throw new RuntimeException(message: 'Could not allocate a temporary file for the install.'); - } - $zip = new ZipArchive(); - if ($zip->open(filename: $tempPath, flags: ZipArchive::OVERWRITE) !== true) { - unlink(filename: $tempPath); - throw new RuntimeException(message: 'Could not open the store archive for writing.'); - } + $tempPath = $this->openArchive(zip: $zip); $manifest = [ 'schemaVersion' => ImportService::SCHEMA_VERSION, @@ -445,19 +553,52 @@ private function materialise(array $dashboards, string $slug, string $userId): s ]; $zip->addFromString(name: 'manifest.json', content: $this->encode(payload: $manifest)); + $this->addDashboards(zip: $zip, dashboards: $dashboards); + $zip->addFromString(name: 'metadata-fields.json', content: $this->encode(payload: [])); + $zip->close(); + + return $tempPath; + }//end materialise() + + /** + * Allocate a temporary file and open it as a fresh archive. + * + * @param ZipArchive $zip The archive to open. + * + * @return string Path to the temporary archive. + * + * @throws RuntimeException When the archive cannot be allocated or opened. + */ + private function openArchive(ZipArchive $zip): string { + $tempPath = tempnam(directory: sys_get_temp_dir(), prefix: 'launchpad-store-'); + if ($tempPath === false) { + throw new RuntimeException(message: 'Could not allocate a temporary file for the install.'); + } + if ($zip->open(filename: $tempPath, flags: ZipArchive::OVERWRITE) !== true) { + unlink(filename: $tempPath); + throw new RuntimeException(message: 'Could not open the store archive for writing.'); + } + + return $tempPath; + }//end openArchive() + + /** + * Add one `dashboards/<uuid>.json` entry per dashboard payload. + * + * @param ZipArchive $zip The open archive. + * @param array<int, array<string, mixed>> $dashboards The dashboard payloads. + * + * @return void + */ + private function addDashboards(ZipArchive $zip, array $dashboards): void { foreach ($dashboards as $payload) { $zip->addFromString( name: 'dashboards/' . (string)$payload['uuid'] . '.json', content: $this->encode(payload: $payload) ); } - - $zip->addFromString(name: 'metadata-fields.json', content: $this->encode(payload: [])); - $zip->close(); - - return $tempPath; - }//end materialise() + }//end addDashboards() /** * Turn the importer's result into the store page's per-component report. diff --git a/lib/Service/StoreUpdateFollowUps.php b/lib/Service/StoreUpdateFollowUps.php new file mode 100644 index 000000000..a7694910f --- /dev/null +++ b/lib/Service/StoreUpdateFollowUps.php @@ -0,0 +1,51 @@ +<?php + +/** + * StoreUpdateFollowUps + * + * What a marketplace update does after it wrote the dashboard: bring copies + * along with the merge re-sync, write the version note, and log a failure. + * Kept together so {@see StoreUpdateService} takes one parameter for them. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use Psr\Log\LoggerInterface; + +/** + * The re-sync, the version service and the logger of a marketplace update. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ +class StoreUpdateFollowUps { + /** + * Constructor. + * + * @param TemplateResyncService $resync Brings copies along. + * @param DashboardVersionService $versions Writes the version note. + * @param LoggerInterface $logger Server-side diagnostics only. + * + * @return void + */ + public function __construct( + public readonly TemplateResyncService $resync, + public readonly DashboardVersionService $versions, + public readonly LoggerInterface $logger, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/StoreUpdateService.php b/lib/Service/StoreUpdateService.php new file mode 100644 index 000000000..f7e8e1ffb --- /dev/null +++ b/lib/Service/StoreUpdateService.php @@ -0,0 +1,300 @@ +<?php + +/** + * StoreUpdateService + * + * Brings a dashboard installed from the marketplace to the register's newer + * version in place (REQ-STORE-012). The dashboard keeps its id, UUID, name, + * owner, shares and permission level. Its widgets that came from the install + * become the new version's, paired so a widget present in both keeps its row + * ({@see PlacementPairing}, as a shipped template update does). A widget a + * person added themselves stays. A copy made from the dashboard follows with + * the merge re-sync, the install record takes the new version, and a + * dashboard version noted "Updated from the marketplace" is written. + * + * WHICH WIDGETS CAME FROM THE INSTALL. The install record keeps their ids + * ({@see StoreInstalls::record()}). A record written before it did holds no + * ids: then every widget of the dashboard may be paired with the new version, + * but none is removed, so a person's own widget is never lost. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\AppInfo\Application; +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\WidgetPlacement; +use Throwable; + +/** + * Update an installed marketplace dashboard in place. + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * One operation over the register item, the install record, the rows, + * the version and the re-sync; splitting it would put the write and the + * record it must stay in step with in two places. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ +class StoreUpdateService { + /** + * The note on the dashboard version an update writes. + */ + public const VERSION_NOTE = 'Updated from the marketplace'; + + /** + * Builds the new version's widgets, as the importer does. + * + * @var PlacementPayloadHydrator + */ + private readonly PlacementPayloadHydrator $hydrator; + + /** + * Pairs and writes the widgets. + * + * @var PlacementPairing + */ + private readonly PlacementPairing $pairing; + + /** + * Constructor. + * + * @param StoreService $store Resolves the register item. + * @param StoreInstalls $installs The install record. + * @param ShippedTemplateStores $stores The dashboard and placement mappers and the database. + * @param StoreUpdateFollowUps $followUps The re-sync, the version note and the logger. + * + * @return void + */ + public function __construct( + private readonly StoreService $store, + private readonly StoreInstalls $installs, + private readonly ShippedTemplateStores $stores, + private readonly StoreUpdateFollowUps $followUps, + ) { + $this->hydrator = new PlacementPayloadHydrator(); + $this->pairing = new PlacementPairing(stores: $stores); + }//end __construct() + + /** + * Update the dashboard an install of this item created to the register's version. + * + * @param string $slug The register item slug. + * @param string $userId The administrator running the update. + * + * @return array<string, mixed> `{success, message, ...}`; on success also `version`, + * `upToDate`, `added`, `removed`, `changed`, `kept` and `copies`. `notInstalled` + * is true when there is nothing to update. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + public function update(string $slug, string $userId): array { + $install = ($this->installs->all()[$slug] ?? null); + if ($install === null) { + return ['success' => false, 'notInstalled' => true, 'message' => 'That template is not installed here, so there is nothing to update.']; + } + + $resolved = $this->store->resolveItem(slug: $slug); + if (isset($resolved['dashboards']) === false) { + return ['success' => false, 'message' => $resolved['message']]; + } + + if (version_compare($resolved['version'], $install['version'], '>') === false) { + return [ + 'success' => true, + 'components' => [], + 'upToDate' => true, + 'version' => $install['version'], + 'message' => 'This dashboard is already up to date.', + ]; + } + + try { + $dashboard = $this->stores->dashboardMapper->find(id: $install['dashboardId']); + } catch (Throwable) { + $this->installs->forget(dashboardId: $install['dashboardId']); + return ['success' => false, 'notInstalled' => true, 'message' => 'The installed dashboard no longer exists.']; + } + + try { + return $this->apply( + dashboard: $dashboard, + job: ['slug' => $slug, 'install' => $install, 'resolved' => $resolved, 'userId' => $userId] + ); + } catch (Throwable $e) { + $this->followUps->logger->error( + message: 'Store update failed for ' . $slug . ': ' . $e->getMessage(), + context: ['app' => Application::APP_ID] + ); + return ['success' => false, 'message' => 'That dashboard could not be updated.']; + } + }//end update() + + /** + * Pair, write, record, re-sync and note the version. + * + * @param Dashboard $dashboard The installed dashboard. + * @param array<string, mixed> $job `slug`, the `install` record, the `resolved` register item + * and the acting administrator's `userId`. + * + * @return array<string, mixed> The report. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + private function apply(Dashboard $dashboard, array $job): array { + $install = $job['install']; + $resolved = $job['resolved']; + $userId = (string)$job['userId']; + $split = $this->split( + placements: $this->stores->placementMapper->findByDashboardId(dashboardId: (int)$dashboard->getId()), + tracked: $install['placementIds'] + ); + + $plan = $this->pairing->pair( + installed: $split['fromInstall'], + wanted: $this->wanted(dashboard: $dashboard, payload: $resolved['dashboards'][0]) + ); + if ($install['placementIds'] === []) { + // A record without ids cannot tell an installed widget from a person's own: remove nothing. + $plan['removed'] = []; + } + + $report = $this->pairing->describe(plan: $plan); + $this->pairing->apply(template: $dashboard, plan: $plan); + + $this->installs->record( + slug: $job['slug'], + version: $resolved['version'], + dashboard: ['id' => (int)$dashboard->getId(), 'uuid' => (string)$dashboard->getUuid(), 'placementIds' => $this->idsAfter(plan: $plan)] + ); + + $this->followUps->versions->captureSnapshot( + dashboard: $dashboard, + createdBy: $userId, + options: ['note' => self::VERSION_NOTE, 'explicit' => true] + ); + + return [ + 'success' => true, + // The store page names every component that is not `installed`; an update has none to name. + 'components' => [], + 'upToDate' => false, + 'message' => 'Updated to version ' . $resolved['version'] . '.', + 'version' => $resolved['version'], + 'kept' => count($split['own']), + 'copies' => $this->resyncCopies(dashboard: $dashboard, userId: $userId), + ] + $report; + }//end apply() + + /** + * Split the dashboard's widgets into those from the install and a person's own. + * + * @param array<int, WidgetPlacement> $placements The dashboard's widgets now. + * @param list<int> $tracked The ids the install record holds. + * + * @return array{fromInstall: array<int, WidgetPlacement>, own: array<int, WidgetPlacement>} + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + private function split(array $placements, array $tracked): array { + if ($tracked === []) { + return ['fromInstall' => array_values($placements), 'own' => []]; + } + + $fromInstall = []; + $own = []; + foreach ($placements as $placement) { + if (in_array((int)$placement->getId(), $tracked, true) === true) { + $fromInstall[] = $placement; + continue; + } + + $own[] = $placement; + } + + return ['fromInstall' => $fromInstall, 'own' => $own]; + }//end split() + + /** + * The new version's widgets on this dashboard, unsaved. + * + * @param Dashboard $dashboard The installed dashboard; on an admin template the compulsory flag is kept. + * @param array<string, mixed> $payload The new version's dashboard payload. + * + * @return array<int, WidgetPlacement> The widgets. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + private function wanted(Dashboard $dashboard, array $payload): array { + $asTemplate = ($dashboard->getType() === Dashboard::TYPE_ADMIN_TEMPLATE); + $wanted = []; + foreach ((array)($payload['widgets'] ?? []) as $widget) { + if (is_array($widget) === false) { + continue; + } + + $wanted[] = $this->hydrator->hydrate(dashboardId: (int)$dashboard->getId(), payload: $widget, asTemplate: $asTemplate); + } + + return $wanted; + }//end wanted() + + /** + * The ids of the widgets that come from the install after the update. + * + * @param array<string, mixed> $plan The written plan. + * + * @return list<int> The placement ids. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + private function idsAfter(array $plan): array { + $placements = $plan['unchanged']; + foreach ($plan['changed'] as $pair) { + $placements[] = $pair['installed']; + } + + $placements = array_merge($placements, $plan['added']); + + return array_values(array_map(static fn (WidgetPlacement $placement): int => (int)$placement->getId(), $placements)); + }//end idsAfter() + + /** + * Merge the updated dashboard into its copies when it is a template (REQ-RESYNC-003). + * + * @param Dashboard $dashboard The updated dashboard; only an admin template has copies. + * @param string $userId The acting administrator. + * + * @return int How many copies were brought along. + * + * @spec openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md#requirement-req-store-012-update-brings-an-installed-dashboard-to-the-newer-version-in-place + */ + private function resyncCopies(Dashboard $dashboard, string $userId): int { + if ($dashboard->getType() !== Dashboard::TYPE_ADMIN_TEMPLATE) { + return 0; + } + + $result = $this->followUps->resync->resync( + templateId: (int)$dashboard->getId(), + strategy: TemplateResyncService::STRATEGY_MERGE, + dryRun: false, + actingAdminId: $userId + ); + + return (int)($result['affectedCount'] ?? 0); + }//end resyncCopies() +}//end class diff --git a/lib/Service/SubtreeDeletion.php b/lib/Service/SubtreeDeletion.php new file mode 100644 index 000000000..3cc0daf14 --- /dev/null +++ b/lib/Service/SubtreeDeletion.php @@ -0,0 +1,45 @@ +<?php + +/** + * SubtreeDeletion + * + * One subtree delete: the dashboard the delete started from and the shared deletion time. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeImmutable; +use OCA\LaunchPad\Db\Dashboard; + +/** + * The root and deletion time of one subtree delete. + * + * @spec openspec/specs/dashboard-switcher/spec.md + */ +final class SubtreeDeletion { + /** + * Constructor. + * + * @param Dashboard $root The dashboard the delete started from; its owner and type + * fill in for descendants that carry none. + * @param DateTimeImmutable $deletedAt The deletion time stamped on every event. + */ + public function __construct( + public readonly Dashboard $root, + public readonly DateTimeImmutable $deletedAt, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/SummaryMailContent.php b/lib/Service/SummaryMailContent.php new file mode 100644 index 000000000..b08fe05cc --- /dev/null +++ b/lib/Service/SummaryMailContent.php @@ -0,0 +1,159 @@ +<?php + +/** + * SummaryMailContent + * + * What one person's summary email says (personal-settings REQ-PSET-002): the + * announcements published for them since the last summary, and per dashboard + * they can open, the "What changed" notes of dashboard-versioning since then. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeInterface; +use OCA\LaunchPad\Db\Announcement; +use OCA\LaunchPad\Db\DashboardVersionMapper; +use OCA\LaunchPad\Kernel\Contracts\AnnouncementServiceInterface; + +/** + * Collects the lines of one person's summary. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ +class SummaryMailContent { + + /** + * The newest versions read per dashboard; older ones predate any summary window. + */ + private const VERSIONS_PER_DASHBOARD = 25; + + /** + * Constructor. + * + * @param AnnouncementServiceInterface $announcements The announcements a reader sees. + * @param DashboardService $dashboards The dashboards a reader can open. + * @param DashboardVersionMapper $versions The dashboards' versions and their notes. + */ + public function __construct( + private readonly AnnouncementServiceInterface $announcements, + private readonly DashboardService $dashboards, + private readonly DashboardVersionMapper $versions, + ) { + }//end __construct() + + /** + * The summary of one person since a moment. + * + * @param string $userId The reader. + * @param DateTimeInterface $since The last summary, or the start of the window. + * + * @return array{announcements: list<string>, changes: list<string>} + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function collect(string $userId, DateTimeInterface $since): array { + return [ + 'announcements' => $this->announcementsSince(userId: $userId, since: $since), + 'changes' => $this->changesSince(userId: $userId, since: $since), + ]; + }//end collect() + + /** + * Titles of the announcements published for the reader since the moment. + * + * @param string $userId The reader. + * @param DateTimeInterface $since The moment. + * + * @return list<string> + */ + private function announcementsSince(string $userId, DateTimeInterface $since): array { + $out = []; + foreach ($this->announcements->visibleTo(userId: $userId) as $announcement) { + $published = self::publishedAt(announcement: $announcement); + if ($published !== null && $published > $since->getTimestamp()) { + $out[] = (string)$announcement->getTitle(); + } + } + + return $out; + }//end announcementsSince() + + /** + * "Dashboard: note" for every noted version since the moment, on the + * dashboards the reader can open, oldest first per dashboard. + * + * @param string $userId The reader. + * @param DateTimeInterface $since The moment. + * + * @return list<string> + */ + private function changesSince(string $userId, DateTimeInterface $since): array { + $out = []; + foreach ($this->dashboards->getVisibleToUser(userId: $userId) as $entry) { + $dashboard = $entry['dashboard']; + $uuid = (string)$dashboard->getUuid(); + if ($uuid === '') { + continue; + } + + $notes = []; + foreach ($this->versions->findLatestByDashboard(dashboardUuid: $uuid, limit: self::VERSIONS_PER_DASHBOARD) as $version) { + $note = trim((string)$version->getNote()); + $created = self::timestamp(value: $version->getCreatedAt()); + if ($note !== '' && $created !== null && $created > $since->getTimestamp()) { + $notes[] = (string)$dashboard->getName().': '.$note; + } + } + + // The mapper reads newest first; the mail tells it in order. + array_push($out, ...array_reverse($notes)); + } + + return $out; + }//end changesSince() + + /** + * When an announcement went live: its publish moment, else its creation. + * + * @param Announcement $announcement The announcement. + * + * @return int|null Unix time, or null when it carries neither. + */ + private static function publishedAt(Announcement $announcement): ?int { + $moment = $announcement->getPublishAt() ?? $announcement->getCreatedAt(); + if ($moment === null) { + return null; + } + + return $moment->getTimestamp(); + }//end publishedAt() + + /** + * A stored `Y-m-d H:i:s` moment as Unix time. + * + * @param string|null $value The stored moment. + * + * @return int|null Unix time, or null when it does not parse. + */ + private static function timestamp(?string $value): ?int { + $parsed = date_create_immutable((string)$value); + if ($value === null || $value === '' || $parsed === false) { + return null; + } + + return $parsed->getTimestamp(); + }//end timestamp() +}//end class diff --git a/lib/Service/SummaryMailPreference.php b/lib/Service/SummaryMailPreference.php new file mode 100644 index 000000000..dc50870a6 --- /dev/null +++ b/lib/Service/SummaryMailPreference.php @@ -0,0 +1,180 @@ +<?php + +/** + * SummaryMailPreference + * + * How often one person wants launchpad's summary email (personal-settings + * REQ-PSET-002): off, daily or weekly, off until the person changes it; and + * what the summary needs to know of that person: their time zone and when + * their last summary went out. All of it lives in Nextcloud's user preferences. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeImmutable; +use DateTimeZone; +use InvalidArgumentException; +use OCA\LaunchPad\AppInfo\Application; +use OCP\IConfig; + +/** + * Reads and writes the summary email frequency of one person. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ +class SummaryMailPreference { + + /** + * The user preference that holds the frequency. + */ + public const KEY_FREQUENCY = 'summary_mail_frequency'; + + /** + * The user preference that holds when the last summary went out, ISO 8601. + */ + public const KEY_LAST_SENT = 'summary_mail_last_sent'; + + public const OFF = 'off'; + + public const DAILY = 'daily'; + + public const WEEKLY = 'weekly'; + + /** + * The frequencies a person can choose. + */ + public const FREQUENCIES = [self::OFF, self::DAILY, self::WEEKLY]; + + /** + * Constructor. + * + * @param IConfig $config The user preferences. + */ + public function __construct( + private readonly IConfig $config, + ) { + }//end __construct() + + /** + * The person's frequency; off when they never chose, or when the stored + * value is not one of the three. + * + * @param string $userId The person. + * + * @return string One of FREQUENCIES. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function frequency(string $userId): string { + $value = (string)$this->config->getUserValue($userId, Application::APP_ID, self::KEY_FREQUENCY, self::OFF); + if (in_array($value, self::FREQUENCIES, true) === false) { + return self::OFF; + } + + return $value; + }//end frequency() + + /** + * Store the person's frequency. + * + * @param string $userId The person. + * @param string $frequency One of FREQUENCIES. + * + * @return string The stored frequency. + * + * @throws InvalidArgumentException When the frequency is not one of the three. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function setFrequency(string $userId, string $frequency): string { + if (in_array($frequency, self::FREQUENCIES, true) === false) { + throw new InvalidArgumentException('Unknown summary frequency: '.$frequency); + } + + $this->config->setUserValue($userId, Application::APP_ID, self::KEY_FREQUENCY, $frequency); + + return $frequency; + }//end setFrequency() + + /** + * The people who chose this frequency. + * + * @param string $frequency Daily or weekly. + * + * @return list<string> Their user ids. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function usersWith(string $frequency): array { + return array_values( + array_map( + 'strval', + $this->config->getUsersForUserValue(Application::APP_ID, self::KEY_FREQUENCY, $frequency) + ) + ); + }//end usersWith() + + /** + * The person's time zone, else the server's. + * + * @param string $userId The person. + * + * @return DateTimeZone + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function timeZoneOf(string $userId): DateTimeZone { + $name = (string)$this->config->getUserValue($userId, 'core', 'timezone', ''); + if (in_array($name, timezone_identifiers_list(), true) === false) { + $name = date_default_timezone_get(); + } + + return new DateTimeZone($name); + }//end timeZoneOf() + + /** + * When the person's last summary went out. + * + * @param string $userId The person. + * + * @return DateTimeImmutable|null Null when never, or unreadable. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function lastSent(string $userId): ?DateTimeImmutable { + $value = (string)$this->config->getUserValue($userId, Application::APP_ID, self::KEY_LAST_SENT, ''); + $parsed = date_create_immutable_from_format(DATE_ATOM, $value); + if ($parsed === false) { + return null; + } + + return $parsed; + }//end lastSent() + + /** + * Record that the person's summary went out now. + * + * @param string $userId The person. + * @param DateTimeImmutable $sentAt The moment. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function recordSent(string $userId, DateTimeImmutable $sentAt): void { + $this->config->setUserValue($userId, Application::APP_ID, self::KEY_LAST_SENT, $sentAt->format(DATE_ATOM)); + }//end recordSent() +}//end class diff --git a/lib/Service/SummaryMailSender.php b/lib/Service/SummaryMailSender.php new file mode 100644 index 000000000..0046cdbc1 --- /dev/null +++ b/lib/Service/SummaryMailSender.php @@ -0,0 +1,140 @@ +<?php + +/** + * SummaryMailSender + * + * Builds and sends one summary email (personal-settings REQ-PSET-002) through + * Nextcloud's mailer and email template, in the person's own language. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\AppInfo\Application; +use OCP\IL10N; +use OCP\IURLGenerator; +use OCP\IUser; +use OCP\L10N\IFactory; +use OCP\Mail\IEMailTemplate; +use OCP\Mail\IMailer; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Sends one person's summary. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ +class SummaryMailSender { + /** + * Constructor. + * + * @param IMailer $mailer The mailer. + * @param IFactory $l10n The person's language. + * @param IURLGenerator $urls The link back to LaunchPad. + * @param LoggerInterface $logger A summary that could not be sent. + */ + public function __construct( + private readonly IMailer $mailer, + private readonly IFactory $l10n, + private readonly IURLGenerator $urls, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * Send the summary to the person's email address. + * + * @param IUser $user The person, with an email address. + * @param array{frequency: string, announcements: list<string>, changes: list<string>} $summary What it says, and how often. + * + * @return bool True when the mailer took it. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function send(IUser $user, array $summary): bool { + try { + $l10n = $this->l10n->get(Application::APP_ID, $this->l10n->getUserLanguage($user)); + $message = $this->mailer->createMessage(); + $message->setTo([(string)$user->getEMailAddress() => $user->getDisplayName()]); + $message->useTemplate($this->template(l10n: $l10n, summary: $summary)); + $this->mailer->send($message); + } catch (Throwable $exception) { + $this->logger->warning( + 'LaunchPad summary mail to {user} failed: {message}', + ['user' => $user->getUID(), 'message' => $exception->getMessage()] + ); + return false; + } + + return true; + }//end send() + + /** + * The mail: heading, the announcements, what changed, a link back. + * + * @param IL10N $l10n The person's language. + * @param array{frequency: string, announcements: list<string>, changes: list<string>} $summary What it says, and how often. + * + * @return IEMailTemplate + */ + private function template(IL10N $l10n, array $summary): IEMailTemplate { + $frequency = $summary['frequency']; + $subject = $l10n->t('Your daily LaunchPad summary'); + if ($frequency === SummaryMailPreference::WEEKLY) { + $subject = $l10n->t('Your weekly LaunchPad summary'); + } + + $template = $this->mailer->createEMailTemplate('launchpad.SummaryMail', ['frequency' => $frequency]); + $template->setSubject($subject); + $template->addHeader(); + $template->addHeading($subject); + + if ($summary['announcements'] === [] && $summary['changes'] === []) { + $template->addBodyText($l10n->t('Nothing new was published and nothing changed on your dashboards.')); + } + + self::addList(template: $template, section: [$l10n->t('New announcements'), $summary['announcements']]); + self::addList(template: $template, section: [$l10n->t('What changed on your dashboards'), $summary['changes']]); + + $template->addBodyButton( + $l10n->t('Open LaunchPad'), + $this->urls->getAbsoluteURL($this->urls->linkToRoute('launchpad.page.index')) + ); + $template->addFooter($l10n->t('You get this mail because you asked for it in your LaunchPad settings.')); + + return $template; + }//end template() + + /** + * A heading and its items, when there are any. + * + * @param IEMailTemplate $template The mail. + * @param array{0: string, 1: list<string>} $section The heading and its items. + * + * @return void + */ + private static function addList(IEMailTemplate $template, array $section): void { + [$heading, $items] = $section; + if ($items === []) { + return; + } + + $template->addBodyText($heading); + foreach ($items as $item) { + $template->addBodyListItem($item); + } + }//end addList() +}//end class diff --git a/lib/Service/SummaryMailService.php b/lib/Service/SummaryMailService.php new file mode 100644 index 000000000..485fb6d78 --- /dev/null +++ b/lib/Service/SummaryMailService.php @@ -0,0 +1,184 @@ +<?php + +/** + * SummaryMailService + * + * Sends launchpad's summary email (personal-settings REQ-PSET-002) to every + * person who chose one: at 07:30 in their own time zone, every day or on + * Monday, to their email address. A daily summary with nothing in it is not + * sent, a person without an email address gets none, and the moment of the + * last summary is recorded so the next one starts where it ended. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use DateTimeImmutable; +use OCP\IUserManager; + +/** + * Decides who is due and has their summary sent. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ +class SummaryMailService { + + /** + * The local hour and minute a summary goes out. + */ + public const SEND_HOUR = 7; + + public const SEND_MINUTE = 30; + + /** + * The local hour after which a missed morning is not sent any more, so a + * summary never arrives in the evening. + */ + public const LATEST_HOUR = 12; + + /** + * Constructor. + * + * @param IUserManager $users Finds the people. + * @param SummaryMailPreference $preference Each person's choice, time zone and last send. + * @param SummaryMailContent $content What a summary says. + * @param SummaryMailSender $sender Sends it. + */ + public function __construct( + private readonly IUserManager $users, + private readonly SummaryMailPreference $preference, + private readonly SummaryMailContent $content, + private readonly SummaryMailSender $sender, + ) { + }//end __construct() + + /** + * Send every summary that is due now. + * + * @param DateTimeImmutable $now The moment of the run. + * + * @return int How many summaries went out. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function sendDue(DateTimeImmutable $now): int { + $sent = 0; + foreach ([SummaryMailPreference::DAILY, SummaryMailPreference::WEEKLY] as $frequency) { + foreach ($this->preference->usersWith(frequency: $frequency) as $userId) { + $sent += (int)$this->sendFor(userId: $userId, now: $now); + } + } + + return $sent; + }//end sendDue() + + /** + * Send one person's summary when it is due by their own choice. + * + * @param string $userId The person. + * @param DateTimeImmutable $now The moment of the run. + * + * @return bool True when a summary went out. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public function sendFor(string $userId, DateTimeImmutable $now): bool { + $user = $this->users->get($userId); + $since = $this->windowStart(userId: $userId, now: $now); + if ($user === null || (string)$user->getEMailAddress() === '' || $since === null) { + return false; + } + + $summary = ['frequency' => $this->preference->frequency(userId: $userId)] + + $this->content->collect(userId: $userId, since: $since); + if (self::worthSending(summary: $summary) === false + || $this->sender->send(user: $user, summary: $summary) === false + ) { + // An empty daily summary is not sent, and a failed send is not + // recorded: either way the window stays open for the next run. + return false; + } + + $this->preference->recordSent(userId: $userId, sentAt: $now); + + return true; + }//end sendFor() + + /** + * Today's send moment (07:30 local) when a summary of this frequency is + * due at this local moment: on or after 07:30 and before noon, and on + * Monday for a weekly one. Null when it is not. + * + * @param string $frequency Off, daily or weekly. + * @param DateTimeImmutable $local Now, in the person's time zone. + * + * @return DateTimeImmutable|null + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + public static function dueMoment(string $frequency, DateTimeImmutable $local): ?DateTimeImmutable { + $onItsDay = ($frequency === SummaryMailPreference::DAILY) + || ($frequency === SummaryMailPreference::WEEKLY && $local->format('N') === '1'); + $sendAt = $local->setTime(self::SEND_HOUR, self::SEND_MINUTE); + if ($onItsDay === false || $local < $sendAt || (int)$local->format('G') >= self::LATEST_HOUR) { + return null; + } + + return $sendAt; + }//end dueMoment() + + /** + * Where this person's summary starts when one is due now: the last + * summary, or a day (a week) back for a first one. Null when none is due. + * + * @param string $userId The person. + * @param DateTimeImmutable $now The moment of the run. + * + * @return DateTimeImmutable|null + */ + private function windowStart(string $userId, DateTimeImmutable $now): ?DateTimeImmutable { + $frequency = $this->preference->frequency(userId: $userId); + $local = $now->setTimezone($this->preference->timeZoneOf(userId: $userId)); + $sendAt = self::dueMoment(frequency: $frequency, local: $local); + $lastSent = $this->preference->lastSent(userId: $userId); + if ($sendAt === null || ($lastSent !== null && $lastSent >= $sendAt)) { + return null; + } + + if ($lastSent !== null) { + return $lastSent; + } + + if ($frequency === SummaryMailPreference::WEEKLY) { + return $local->modify('-7 days'); + } + + return $local->modify('-1 day'); + }//end windowStart() + + /** + * Whether a summary is worth a mail: a weekly one always, a daily one + * only when something was published or changed. + * + * @param array{frequency: string, announcements: list<string>, changes: list<string>} $summary The summary. + * + * @return bool + */ + private static function worthSending(array $summary): bool { + return $summary['frequency'] !== SummaryMailPreference::DAILY + || $summary['announcements'] !== [] + || $summary['changes'] !== []; + }//end worthSending() +}//end class diff --git a/lib/Service/TemplateAudience.php b/lib/Service/TemplateAudience.php new file mode 100644 index 000000000..7fdc90c9e --- /dev/null +++ b/lib/Service/TemplateAudience.php @@ -0,0 +1,54 @@ +<?php + +/** + * TemplateAudience + * + * Decides whether an admin template is offered to a user, from the template's + * target groups and the user's groups (REQ-TMPL-018). The gallery lists what + * it offers and a fork accepts the same, so both ask this one rule. + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; + +/** + * Who an admin template is offered to. + * + * @spec openspec/specs/admin-templates/spec.md#requirement-the-gallery-offers-a-template-to-the-groups-it-names-req-tmpl-018 + */ +final class TemplateAudience { + /** + * Whether a template is offered to a user with these groups: it names no + * groups, names the `default` group, or names one of the user's groups. + * + * @param Dashboard $template The admin template. + * @param string[] $userGroupIds The user's group IDs. + * + * @return bool + * + * @spec openspec/specs/admin-templates/spec.md#requirement-the-gallery-offers-a-template-to-the-groups-it-names-req-tmpl-018 + */ + public function offers(Dashboard $template, array $userGroupIds): bool { + $targets = $template->getTargetGroupsArray(); + if ($targets === [] || in_array(needle: Dashboard::DEFAULT_GROUP_ID, haystack: $targets, strict: true) === true) { + return true; + } + + return array_intersect($targets, $userGroupIds) !== []; + }//end offers() +}//end class diff --git a/lib/Service/TemplateResyncRequest.php b/lib/Service/TemplateResyncRequest.php new file mode 100644 index 000000000..880a9a669 --- /dev/null +++ b/lib/Service/TemplateResyncRequest.php @@ -0,0 +1,42 @@ +<?php + +/** + * TemplateResyncRequest + * + * Which template to resync, and how. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The template whose copies a resync updates, and the strategy (merge or + * overwrite) it applies. + * + * @spec openspec/specs/admin-templates/spec.md + */ +final class TemplateResyncRequest { + /** + * Constructor + * + * @param integer $templateId The template dashboard id. + * @param string $strategy The resync strategy. + */ + public function __construct( + public readonly int $templateId, + public readonly string $strategy, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/TemplateResyncService.php b/lib/Service/TemplateResyncService.php index d7f6d291c..13ec6389f 100644 --- a/lib/Service/TemplateResyncService.php +++ b/lib/Service/TemplateResyncService.php @@ -37,15 +37,14 @@ use DateTime; use InvalidArgumentException; use OCA\LaunchPad\Activity\ActivityPublisher; +use OCA\LaunchPad\Activity\ActivityRow; +use OCA\LaunchPad\Activity\ActivitySubject; use OCA\LaunchPad\Activity\Extension; use OCA\LaunchPad\BackgroundJob\TemplateResyncJob; use OCA\LaunchPad\Db\Dashboard; -use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacement; -use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Kernel\Contracts\TemplateResyncServiceInterface; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\BackgroundJob\IJobList; -use OCP\IDBConnection; use OCP\Notification\IManager as INotificationManager; use Psr\Log\LoggerInterface; use Throwable; @@ -59,7 +58,7 @@ * manager, and the async job dispatcher for one cohesive re-sync * operation — splitting further would fragment a single atomic concern. */ -class TemplateResyncService { +class TemplateResyncService implements TemplateResyncServiceInterface { /** * Replace each copy's layout with the current template layout. */ @@ -71,6 +70,12 @@ class TemplateResyncService { */ public const STRATEGY_MERGE = 'merge'; + /** + * Add the template placements a copy lacks, at the first free spot, and + * change nothing else (REQ-RESYNC-006). + */ + public const STRATEGY_ADD_ONLY = 'add_only'; + /** * The only accepted `strategy` values (REQ-RESYNC-001 "Invalid * strategy is rejected"). @@ -80,6 +85,7 @@ class TemplateResyncService { public const VALID_STRATEGIES = [ self::STRATEGY_OVERWRITE, self::STRATEGY_MERGE, + self::STRATEGY_ADD_ONLY, ]; /** @@ -92,58 +98,47 @@ class TemplateResyncService { */ public const ASYNC_THRESHOLD = 50; + /** + * Diffs a copy against the template (REQ-RESYNC-003, REQ-RESYNC-006, REQ-RESYNC-007). + * + * @var ResyncDiffer + */ + private readonly ResyncDiffer $differ; + + /** + * Reads and stamps a placement's layout (REQ-RESYNC-007). + * + * @var PlacementLayout + */ + private readonly PlacementLayout $layout; + /** * Constructor. * - * @param DashboardMapper $dashboardMapper Dashboard mapper. - * @param WidgetPlacementMapper $placementMapper Widget placement mapper. - * @param IDBConnection $db DB connection — - * used for the - * per-copy - * transaction - * boundary. - * @param ActivityPublisher $activityPublisher Audit-trail - * publisher - * (REQ-RESYNC-005). - * @param INotificationManager $notificationManager Nextcloud - * notification - * manager — used - * for the - * per-user - * "your dashboard - * was updated" - * notification. - * Canonical - * fallback per - * REQ-RESYNC-005; - * this app has no - * OpenRegister - * dependency - * (see the - * admin-templates - * storage - * policy), so the - * `x-openregister- - * notifications` - * branch is not - * wired in. - * @param IJobList $jobList Background job - * list — used to - * enqueue - * {@see TemplateResyncJob} - * for large - * target groups. - * @param LoggerInterface $logger PSR-3 logger. + * @param ResyncStores $stores The dashboard and placement mappers, the database and the job list. + * @param ActivityPublisher $activityPublisher Audit-trail publisher (REQ-RESYNC-005). + * @param INotificationManager $notificationManager Nextcloud notification manager — used for the per-user + * "your dashboard was updated" notification. Canonical + * fallback per REQ-RESYNC-005; this app has no + * OpenRegister dependency (see the admin-templates + * storage policy), so the `x-openregister- + * notifications` branch is not wired in. + * @param LoggerInterface $logger PSR-3 logger. + * @param ResyncFollowUps $followUps What happens to a changed copy: its personal layers are pruned + * (REQ-DWMS-001) and it gets a version by the template (REQ-VERSUI-005). + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else */ public function __construct( - private readonly DashboardMapper $dashboardMapper, - private readonly WidgetPlacementMapper $placementMapper, - private readonly IDBConnection $db, + private readonly ResyncStores $stores, private readonly ActivityPublisher $activityPublisher, private readonly INotificationManager $notificationManager, - private readonly IJobList $jobList, private readonly LoggerInterface $logger, + private readonly ResyncFollowUps $followUps, ) { + $this->layout = new PlacementLayout(); + $this->differ = new ResyncDiffer(layout: $this->layout); }//end __construct() /** @@ -155,7 +150,7 @@ public function __construct( * and the provisioned-copy count. * * @param int $templateId The admin template's dashboard ID. - * @param string $strategy `'overwrite'` or `'merge'`. + * @param string $strategy `'overwrite'`, `'merge'` or `'add_only'`. * @param bool $dryRun When true, compute and return the plan * without mutating anything. * @param string $actingAdminId The acting admin's NC user ID (for the @@ -177,56 +172,101 @@ public function resync( ): array { $this->assertValidStrategy(strategy: $strategy); $this->getValidatedTemplate(templateId: $templateId); + $request = new TemplateResyncRequest(templateId: $templateId, strategy: $strategy); if ($dryRun === true) { - $plan = $this->planResync( - templateId: $templateId, - strategy: $strategy - ); - $plan['dryRun'] = true; - $plan['async'] = false; - - return $plan; + return $this->dryRunPlan(request: $request); } + return $this->resyncNow(request: $request, actingAdminId: $actingAdminId); + }//end resync() + + /** + * The plan of a dry run, marked as such. + * + * @param TemplateResyncRequest $request The resync. + * + * @return array<string, mixed> The plan. + */ + private function dryRunPlan(TemplateResyncRequest $request): array { + $plan = $this->planResync( + templateId: $request->templateId, + strategy: $request->strategy + ); + $plan['dryRun'] = true; + $plan['async'] = false; + + return $plan; + }//end dryRunPlan() + + /** + * Apply a resync inline, or queue it when the template has more copies + * than {@see self::ASYNC_THRESHOLD} (REQ-RESYNC-005). + * + * @param TemplateResyncRequest $request The resync. + * @param string $actingAdminId The admin triggering it. + * + * @return array<string, mixed> The applied or the accepted report. + */ + private function resyncNow(TemplateResyncRequest $request, string $actingAdminId): array { $totalCopies = count( - $this->dashboardMapper->findByBasedOnTemplate( - templateId: $templateId + $this->stores->dashboardMapper->findByBasedOnTemplate( + templateId: $request->templateId ) ); if ($totalCopies > self::ASYNC_THRESHOLD) { - $plan = $this->planResync( - templateId: $templateId, - strategy: $strategy - ); + $affectedCount = $this->queueResync(request: $request, actingAdminId: $actingAdminId); + return $this->acceptedReport(request: $request, totalCopies: $totalCopies) + ['affectedCount' => $affectedCount]; + } - $this->jobList->add( - TemplateResyncJob::class, - [ - 'templateId' => $templateId, - 'strategy' => $strategy, - 'actingAdminId' => $actingAdminId, - ] - ); + return $this->applyResync(templateId: $request->templateId, strategy: $request->strategy, actingAdminId: $actingAdminId); + }//end resyncNow() - return [ - 'templateId' => $templateId, - 'strategy' => $strategy, - 'dryRun' => false, - 'async' => true, - 'accepted' => true, - 'totalCopies' => $totalCopies, - 'affectedCount' => $plan['affectedCount'], - ]; - }//end if - - return $this->applyResync( - templateId: $templateId, - strategy: $strategy, - actingAdminId: $actingAdminId + /** + * Plan a large resync and queue the background job that applies it. + * + * @param TemplateResyncRequest $request The resync. + * @param string $actingAdminId The admin triggering it. + * + * @return mixed The planned affected-copy count. + */ + private function queueResync(TemplateResyncRequest $request, string $actingAdminId): mixed { + $plan = $this->planResync( + templateId: $request->templateId, + strategy: $request->strategy + ); + + $this->stores->jobList->add( + TemplateResyncJob::class, + [ + 'templateId' => $request->templateId, + 'strategy' => $request->strategy, + 'actingAdminId' => $actingAdminId, + ] ); - }//end resync() + + return $plan['affectedCount']; + }//end queueResync() + + /** + * The report of a queued resync, without its affected count. + * + * @param TemplateResyncRequest $request The resync. + * @param integer $totalCopies The number of copies. + * + * @return array<string, mixed> The report. + */ + private function acceptedReport(TemplateResyncRequest $request, int $totalCopies): array { + return [ + 'templateId' => $request->templateId, + 'strategy' => $request->strategy, + 'dryRun' => false, + 'async' => true, + 'accepted' => true, + 'totalCopies' => $totalCopies, + ]; + }//end acceptedReport() /** * Compute the re-sync plan WITHOUT mutating anything (REQ-RESYNC-002). @@ -240,33 +280,36 @@ public function resync( * @param string $strategy `'overwrite'` or `'merge'`. * * @return array<string, mixed> `{templateId, strategy, totalCopies, - * affectedCount, copies: [...]}`. + * affectedCount, copies: [...], gained, + * lost, changedByOwnerCount}`. * * @spec openspec/specs/admin-templates/spec.md#requirement-req-resync-002-dry-run-reports-the-plan-without-mutating + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ public function planResync(int $templateId, string $strategy): array { $template = $this->getValidatedTemplate(templateId: $templateId); - $templatePlacements = $this->placementMapper->findByDashboardId( + $templatePlacements = $this->stores->placementMapper->findByDashboardId( dashboardId: $template->getId() ); - $copies = $this->dashboardMapper->findByBasedOnTemplate( + $copies = $this->stores->dashboardMapper->findByBasedOnTemplate( templateId: $templateId ); $copyReports = []; $affectedCount = 0; + $copyLayouts = []; foreach ($copies as $copy) { - $copyPlacements = $this->placementMapper->findByDashboardId( + $copyPlacements = $this->stores->placementMapper->findByDashboardId( dashboardId: $copy->getId() ); - $diff = $this->diffCopy( + $copyLayouts[] = $copyPlacements; + $diff = $this->differ->bound(strategy: $strategy, columns: $this->columnsOf(copy: $copy))->diff( templatePlacements: $templatePlacements, - copyPlacements: $copyPlacements, - strategy: $strategy + copyPlacements: $copyPlacements ); - $hasChanges = $this->diffHasChanges(diff: $diff); + $hasChanges = $this->differ->hasChanges(diff: $diff); if ($hasChanges === true) { $affectedCount++; } @@ -285,9 +328,30 @@ public function planResync(int $templateId, string $strategy): array { 'totalCopies' => count($copies), 'affectedCount' => $affectedCount, 'copies' => $copyReports, - ]; + ] + (new TemplateRolloutSummary(layout: $this->layout))->summarize( + templatePlacements: $templatePlacements, + copies: $copyLayouts + ); }//end planResync() + /** + * The copy's grid column count; 12 when unset. + * + * @param Dashboard $copy The copy. + * + * @return int The column count, at least 1. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + */ + private function columnsOf(Dashboard $copy): int { + $columns = (int)$copy->getGridColumns(); + if ($columns < 1) { + return 12; + } + + return $columns; + }//end columnsOf() + /** * Recompute the plan and apply it, per copy, inside its own * transaction (REQ-RESYNC-005). Writes exactly one audit record for @@ -316,75 +380,157 @@ public function applyResync( string $strategy, string $actingAdminId, ): array { + $request = new TemplateResyncRequest(templateId: $templateId, strategy: $strategy); $template = $this->getValidatedTemplate(templateId: $templateId); - $templatePlacements = $this->placementMapper->findByDashboardId( - dashboardId: $template->getId() - ); - $copies = $this->dashboardMapper->findByBasedOnTemplate( - templateId: $templateId + $tally = $this->resyncCopiesOf(template: $template, request: $request); + + $this->emitAuditEvent( + template: $template, + run: ['templateId' => $templateId, 'strategy' => $strategy, 'affectedCount' => count($tally->affected), 'actingAdminId' => $actingAdminId] ); - $copyReports = []; - $affectedCount = 0; - $notifyDashboards = []; + $this->notifyAffected(tally: $tally); - foreach ($copies as $copy) { - $copyPlacements = $this->placementMapper->findByDashboardId( - dashboardId: $copy->getId() - ); - $diff = $this->diffCopy( - templatePlacements: $templatePlacements, - copyPlacements: $copyPlacements, - strategy: $strategy - ); + return $this->appliedReport(request: $request, tally: $tally); + }//end applyResync() - if ($this->diffHasChanges(diff: $diff) === false) { - $copyReports[] = $this->summarizeCopy( - copy: $copy, - diff: $diff, - applied: true, - error: null - ); - continue; - } + /** + * Diff and update every copy of a template. + * + * @param Dashboard $template The validated template. + * @param TemplateResyncRequest $request The resync. + * + * @return TemplateResyncTally The per-copy outcome. + */ + private function resyncCopiesOf(Dashboard $template, TemplateResyncRequest $request): TemplateResyncTally { + $tally = new TemplateResyncTally( + templatePlacements: $this->stores->placementMapper->findByDashboardId( + dashboardId: $template->getId() + ), + strategy: $request->strategy, + templateName: (string)$template->getName() + ); + + foreach ($this->stores->dashboardMapper->findByBasedOnTemplate(templateId: $request->templateId) as $copy) { + $this->resyncCopy(tally: $tally, copy: $copy); + } + + return $tally; + }//end resyncCopiesOf() + /** + * Diff one copy, apply the diff when it has changes, and record the + * copy's report; a copy whose change was written is affected. + * + * @param TemplateResyncTally $tally The run. + * @param Dashboard $copy The copy. + * + * @return void + */ + private function resyncCopy(TemplateResyncTally $tally, Dashboard $copy): void { + $diff = $this->differ->bound(strategy: $tally->strategy, columns: $this->columnsOf(copy: $copy))->diff( + templatePlacements: $tally->templatePlacements, + copyPlacements: $this->stores->placementMapper->findByDashboardId(dashboardId: $copy->getId()) + ); + $changed = $this->differ->hasChanges(diff: $diff); + $error = null; + if ($changed === true) { $error = $this->applyDiffToCopy(copy: $copy, diff: $diff); + } - $copyReports[] = $this->summarizeCopy( - copy: $copy, - diff: $diff, - applied: ($error === null), - error: $error + $tally->reports[] = $this->summarizeCopy(copy: $copy, diff: $diff, applied: ($error === null), error: $error); + if ($changed === true && $error === null) { + $tally->affected[] = $copy; + $this->pruneLayers(copy: $copy, diff: $diff); + $this->recordTemplateVersion(copy: $copy, templateName: $tally->templateName); + } + }//end resyncCopy() + + /** + * Write the version a re-synced copy gets, by the template. A failure is + * logged; the resync itself already landed. + * + * @param Dashboard $copy The copy that took the change. + * @param string $templateName The template's name. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + */ + private function recordTemplateVersion(Dashboard $copy, string $templateName): void { + try { + $this->followUps->recordTemplateVersion(copy: $copy, templateName: $templateName); + } catch (Throwable $t) { + $this->logger->warning( + message: 'launchpad.template_resync.version_failed', + context: ['dashboardId' => $copy->getId(), 'exception' => $t] ); + } + }//end recordTemplateVersion() - if ($error === null) { - $affectedCount++; - $notifyDashboards[] = $copy; - } - }//end foreach + /** + * After a re-sync removed placements, drop the personal-layer entries that named them. + * + * @param Dashboard $copy The copy that was re-synced. + * @param array $diff The applied diff. + * + * @return void + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-001-a-personal-layer-over-a-shared-dashboard + */ + private function pruneLayers(Dashboard $copy, array $diff): void { + if ($diff['toRemove'] === []) { + return; + } - $this->emitAuditEvent( - templateId: $templateId, - templateName: (string)$template->getName(), - strategy: $strategy, - affectedCount: $affectedCount, - actingAdminId: $actingAdminId + $liveIds = array_map( + static fn (WidgetPlacement $placement): int => (int)$placement->getId(), + $this->stores->placementMapper->findByDashboardId(dashboardId: $copy->getId()) ); - foreach ($notifyDashboards as $dashboard) { + try { + $this->followUps->personalLayers->pruneDashboard(dashboardId: (int)$copy->getId(), liveIds: $liveIds); + } catch (Throwable $t) { + // The re-sync itself landed; a stale layer entry is ignored at render time. + $this->logger->warning( + message: 'launchpad.template_resync.layer_prune_failed', + context: ['dashboardId' => $copy->getId(), 'exception' => $t] + ); + } + }//end pruneLayers() + + /** + * Notify the owner of every affected copy. + * + * @param TemplateResyncTally $tally The run. + * + * @return void + */ + private function notifyAffected(TemplateResyncTally $tally): void { + foreach ($tally->affected as $dashboard) { $this->notifyUserResync(dashboard: $dashboard); } + }//end notifyAffected() + /** + * The report of an applied resync. + * + * @param TemplateResyncRequest $request The resync. + * @param TemplateResyncTally $tally The per-copy outcome. + * + * @return array<string, mixed> The report. + */ + private function appliedReport(TemplateResyncRequest $request, TemplateResyncTally $tally): array { return [ - 'templateId' => $templateId, - 'strategy' => $strategy, + 'templateId' => $request->templateId, + 'strategy' => $request->strategy, 'dryRun' => false, 'async' => false, - 'totalCopies' => count($copies), - 'affectedCount' => $affectedCount, - 'copies' => $copyReports, + 'totalCopies' => count($tally->reports), + 'affectedCount' => count($tally->affected), + 'copies' => $tally->reports, ]; - }//end applyResync() + }//end appliedReport() /** * Apply one copy's diff inside its own DB transaction. Partial @@ -394,7 +540,7 @@ public function applyResync( * * @param Dashboard $copy The provisioned copy. * @param array<string, mixed> $diff The diff computed by - * {@see self::diffCopy()}, whose + * {@see ResyncDiffer::diff()}, whose * `@return` documents the exact * shape: `toAdd` and `toRemove` hold * {@see WidgetPlacement} lists and @@ -404,33 +550,36 @@ public function applyResync( * @return string|null The failure message, or null on success. */ private function applyDiffToCopy(Dashboard $copy, array $diff): ?string { - $this->db->beginTransaction(); + $this->stores->db->beginTransaction(); try { - foreach ($diff['toAdd'] as $templatePlacement) { - $this->placementMapper->insert( - entity: $this->cloneTemplatePlacementInto( - template: $templatePlacement, - dashboardId: $copy->getId() + foreach ($diff['toAdd'] as $index => $templatePlacement) { + $this->stores->placementMapper->insert( + entity: $this->placedClone( + clone: $this->cloneTemplatePlacementInto(template: $templatePlacement, dashboardId: $copy->getId()), + spot: ($diff['addSpots'][$index] ?? null) ) ); } foreach ($diff['toUpdate'] as $pair) { - $this->applyTemplateFields( - copy: $pair['copy'], - template: $pair['template'] - ); - $this->placementMapper->update(entity: $pair['copy']); + $ownLayout = $this->layout->rectOf(placement: $pair['copy']); + $this->applyTemplateFields(copy: $pair['copy'], template: $pair['template']); + $this->layout->stamp(placement: $pair['copy']); + if ($pair['keepLayout'] === true) { + // REQ-RESYNC-007: the owner's position and size stay. + $this->layout->apply(placement: $pair['copy'], rect: $ownLayout); + } + $this->stores->placementMapper->update(entity: $pair['copy']); } foreach ($diff['toRemove'] as $copyPlacement) { - $this->placementMapper->delete(entity: $copyPlacement); + $this->stores->placementMapper->delete(entity: $copyPlacement); } - $this->db->commit(); + $this->stores->db->commit(); } catch (Throwable $t) { - $this->db->rollBack(); + $this->stores->db->rollBack(); $this->logger->error( message: 'launchpad.template_resync.copy_apply_failed', context: [ @@ -445,209 +594,6 @@ private function applyDiffToCopy(Dashboard $copy, array $diff): ?string { return null; }//end applyDiffToCopy() - // --------------------------------------------------------------- - // Diff engine - // --------------------------------------------------------------- - - /** - * Partition one copy's placements against the template's current - * placements (REQ-RESYNC-003, REQ-RESYNC-004). - * - * Matching is by {@see WidgetPlacement::getTemplatePlacementId()}: - * - * - Matched + fields differ → `toUpdate` (reconcile onto the copy). - * - Matched + fields equal → `toPreserve` (no-op, both strategies). - * - Template-origin but the - * matching template placement - * no longer exists → `toRemove` (admin deleted it from the - * template — both strategies). - * - No known origin - * (user-added) → `toPreserve` under `merge`, - * `toRemove` under `overwrite`. - * - A template placement with - * no matching copy placement → `toAdd` (new template placement, or - * a compulsory widget the user removed - * — restored either way). - * - * Compulsory widgets receive no special-case handling: they are - * ordinary template placements, so the `toAdd` (restore) / `toUpdate` - * (align position+flags) branches above already reconcile them under - * BOTH strategies, satisfying REQ-RESYNC-004 without a separate code - * path. - * - * @param WidgetPlacement[] $templatePlacements The template's current - * placements. - * @param WidgetPlacement[] $copyPlacements The copy's current - * placements. - * @param string $strategy `'overwrite'` or - * `'merge'`. - * - * @return array{ - * toAdd: WidgetPlacement[], - * toUpdate: array<int, array{copy: WidgetPlacement, template: WidgetPlacement}>, - * toRemove: WidgetPlacement[], - * toPreserve: WidgetPlacement[] - * } - */ - private function diffCopy( - array $templatePlacements, - array $copyPlacements, - string $strategy, - ): array { - $templateById = []; - foreach ($templatePlacements as $tp) { - $templateById[$tp->getId()] = $tp; - } - - $matchedTemplateIds = []; - $toUpdate = []; - $toRemove = []; - $toPreserve = []; - - foreach ($copyPlacements as $cp) { - $originId = $cp->getTemplatePlacementId(); - - if ($originId !== null && isset($templateById[$originId]) === true) { - $matchedTemplateIds[$originId] = true; - $tp = $templateById[$originId]; - - if ($this->placementDiffers(copy: $cp, template: $tp) === true) { - $toUpdate[] = [ - 'copy' => $cp, - 'template' => $tp, - ]; - continue; - } - - $toPreserve[] = $cp; - continue; - } - - if ($originId !== null && isset($templateById[$originId]) === false) { - // Template-origin, but the admin has since deleted this - // placement from the template — remove it under both - // strategies (REQ-RESYNC-003 "Template widget removed by - // admin is removed under merge"). - $toRemove[] = $cp; - continue; - } - - // No known origin — a genuinely user-added placement. - if ($strategy === self::STRATEGY_OVERWRITE) { - $toRemove[] = $cp; - continue; - } - - $toPreserve[] = $cp; - }//end foreach - - return [ - 'toAdd' => $this->unmatchedTemplatePlacements( - templatePlacements: $templatePlacements, - matchedTemplateIds: $matchedTemplateIds - ), - 'toUpdate' => $toUpdate, - 'toRemove' => $toRemove, - 'toPreserve' => $toPreserve, - ]; - }//end diffCopy() - - /** - * Template placements the copy has no counterpart for — i.e. the - * additions a re-sync must make. - * - * @param WidgetPlacement[] $templatePlacements The template's current placements. - * @param array<int, boolean> $matchedTemplateIds Set of template placement IDs - * already matched to a copy - * placement, keyed by ID. - * - * @return WidgetPlacement[] The unmatched template placements, in input order. - */ - private function unmatchedTemplatePlacements(array $templatePlacements, array $matchedTemplateIds): array { - $toAdd = []; - foreach ($templatePlacements as $tp) { - if (isset($matchedTemplateIds[$tp->getId()]) === false) { - $toAdd[] = $tp; - } - } - - return $toAdd; - }//end unmatchedTemplatePlacements() - - /** - * Whether a diff carries any mutation (add/update/remove). Used to - * decide `affectedCount` and to skip untouched copies entirely - * (REQ-RESYNC-005 idempotency). - * - * @param array<string, mixed> $diff The diff computed by - * {@see self::diffCopy()}. - * - * @return bool True when applying the diff would change the copy. - */ - private function diffHasChanges(array $diff): bool { - return count($diff['toAdd']) > 0 - || count($diff['toUpdate']) > 0 - || count($diff['toRemove']) > 0; - }//end diffHasChanges() - - /** - * The reconcilable field snapshot compared for equality and applied - * on update. Kept as one array so the equality check - * ({@see self::placementDiffers()}) and the field-copy - * ({@see self::applyTemplateFields()} / {@see self::cloneTemplatePlacementInto()}) - * can never silently drift apart. - * - * @param WidgetPlacement $placement The placement to snapshot. - * - * @return array<string, mixed> The comparable field values. - */ - private function templateFieldSnapshot(WidgetPlacement $placement): array { - return [ - 'widgetId' => $placement->getWidgetId(), - 'gridX' => $placement->getGridX(), - 'gridY' => $placement->getGridY(), - 'gridWidth' => $placement->getGridWidth(), - 'gridHeight' => $placement->getGridHeight(), - 'isCompulsory' => $placement->getIsCompulsory(), - 'isVisible' => $placement->getIsVisible(), - 'styleConfig' => $placement->getStyleConfig(), - 'customTitle' => $placement->getCustomTitle(), - 'customIcon' => $placement->getCustomIcon(), - 'showTitle' => $placement->getShowTitle(), - 'sortOrder' => $placement->getSortOrder(), - 'content' => $placement->getContent(), - 'tileType' => $placement->getTileType(), - 'tileTitle' => $placement->getTileTitle(), - 'tileIcon' => $placement->getTileIcon(), - 'tileIconType' => $placement->getTileIconType(), - 'tileBackgroundColor' => $placement->getTileBackgroundColor(), - 'tileTextColor' => $placement->getTileTextColor(), - 'tileLinkType' => $placement->getTileLinkType(), - 'tileLinkValue' => $placement->getTileLinkValue(), - 'requiresAcknowledgement' => $placement->getRequiresAcknowledgement(), - 'acknowledgementPrompt' => $placement->getAcknowledgementPrompt(), - 'acknowledgementDeadline' => $placement->getAcknowledgementDeadline(), - 'reacknowledgeOnChange' => $placement->getReacknowledgeOnChange(), - 'acknowledgementContentVersion' => $placement->getAcknowledgementContentVersion(), - 'announcementKey' => $placement->getAnnouncementKey(), - ]; - }//end templateFieldSnapshot() - - /** - * Whether a copy placement's reconcilable fields differ from its - * matching template placement's current fields. - * - * @param WidgetPlacement $copy The copy's placement. - * @param WidgetPlacement $template The matching template placement. - * - * @return bool True when the copy needs to be updated to match. - */ - private function placementDiffers( - WidgetPlacement $copy, - WidgetPlacement $template, - ): bool { - return $this->templateFieldSnapshot(placement: $copy) !== $this->templateFieldSnapshot(placement: $template); - }//end placementDiffers() /** * Mutate a copy placement in place so its reconcilable fields match @@ -659,6 +605,8 @@ private function placementDiffers( * from. * * @return void + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it */ private function applyTemplateFields( WidgetPlacement $copy, @@ -691,6 +639,7 @@ private function applyTemplateFields( $copy->setReacknowledgeOnChange($template->getReacknowledgeOnChange()); $copy->setAcknowledgementContentVersion($template->getAcknowledgementContentVersion()); $copy->setAnnouncementKey($template->getAnnouncementKey()); + $copy->setRuleMatch($template->getRuleMatch()); $copy->setUpdatedAt( (new DateTime())->format(format: 'Y-m-d H:i:s') ); @@ -705,6 +654,8 @@ private function applyTemplateFields( * @param int $dashboardId The target copy's dashboard ID. * * @return WidgetPlacement The new (uninserted) placement entity. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else */ private function cloneTemplatePlacementInto( WidgetPlacement $template, @@ -739,7 +690,9 @@ private function cloneTemplatePlacementInto( $clone->setReacknowledgeOnChange($template->getReacknowledgeOnChange()); $clone->setAcknowledgementContentVersion($template->getAcknowledgementContentVersion()); $clone->setAnnouncementKey($template->getAnnouncementKey()); + $clone->setRuleMatch($template->getRuleMatch()); $clone->setTemplatePlacementId($template->getId()); + $this->layout->stamp(placement: $clone); $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); $clone->setCreatedAt($now); @@ -748,6 +701,26 @@ private function cloneTemplatePlacementInto( return $clone; }//end cloneTemplatePlacementInto() + /** + * Put an added clone on its `add_only` spot and make that its baseline + * (REQ-RESYNC-006); without a spot it keeps the template's. + * + * @param WidgetPlacement $clone The new placement (mutated). + * @param array{gridX:int,gridY:int,gridWidth:int,gridHeight:int}|null $spot The spot, or null. + * + * @return WidgetPlacement The placement. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else + */ + private function placedClone(WidgetPlacement $clone, ?array $spot): WidgetPlacement { + if ($spot !== null) { + $this->layout->apply(placement: $clone, rect: $spot); + $this->layout->stamp(placement: $clone); + } + + return $clone; + }//end placedClone() + // --------------------------------------------------------------- // Validation // --------------------------------------------------------------- @@ -760,12 +733,14 @@ private function cloneTemplatePlacementInto( * * @return void * - * @throws InvalidArgumentException When not `overwrite` or `merge`. + * @throws InvalidArgumentException When not `overwrite`, `merge` or `add_only`. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-006-add-only-strategy-adds-new-template-widgets-and-changes-nothing-else */ private function assertValidStrategy(string $strategy): void { if (in_array(needle: $strategy, haystack: self::VALID_STRATEGIES, strict: true) === false) { throw new InvalidArgumentException( - message: 'Invalid strategy: only "overwrite" and "merge" are accepted' + message: 'Invalid strategy: only "overwrite", "merge" and "add_only" are accepted' ); } }//end assertValidStrategy() @@ -784,7 +759,7 @@ private function assertValidStrategy(string $strategy): void { */ private function getValidatedTemplate(int $templateId): Dashboard { try { - $template = $this->dashboardMapper->find(id: $templateId); + $template = $this->stores->dashboardMapper->find(id: $templateId); } catch (DoesNotExistException $e) { throw new InvalidArgumentException( message: 'Not an admin template', @@ -811,7 +786,7 @@ private function getValidatedTemplate(int $templateId): Dashboard { * @param Dashboard $copy The provisioned copy. * @param array<string, mixed> $diff The diff computed by * {@see - * self::diffCopy()}. + * ResyncDiffer::diff()}. * @param bool $applied Whether the diff was applied * (false for dry-run reports). * @param string|null $error The failure message, or null. @@ -832,7 +807,7 @@ private function summarizeCopy( 'toUpdate' => count($diff['toUpdate']), 'toRemove' => count($diff['toRemove']), 'toPreserve' => count($diff['toPreserve']), - 'hasChanges' => $this->diffHasChanges(diff: $diff), + 'hasChanges' => $this->differ->hasChanges(diff: $diff), 'applied' => $applied, 'error' => $error, ]; @@ -848,29 +823,27 @@ private function summarizeCopy( * Activity failure is swallowed by the publisher so an audit-log * problem never rolls back the re-sync itself. * - * @param int $templateId The template's dashboard ID. - * @param string $templateName The template's human-readable name. - * @param string $strategy `'overwrite'` or `'merge'`. - * @param int $affectedCount The number of copies actually changed. - * @param string $actingAdminId The acting admin's NC user ID. + * @param Dashboard $template The template that was re-synced. + * @param array<string, mixed> $run The run: `templateId` (the template's dashboard ID), + * `strategy` (`'overwrite'` or `'merge'`), `affectedCount` + * (copies actually changed) and `actingAdminId`. * * @return void */ - private function emitAuditEvent( - int $templateId, - string $templateName, - string $strategy, - int $affectedCount, - string $actingAdminId, - ): void { + private function emitAuditEvent(Dashboard $template, array $run): void { + $templateId = $run['templateId']; + $templateName = (string)$template->getName(); + $strategy = $run['strategy']; + $affectedCount = $run['affectedCount']; + $actingAdminId = $run['actingAdminId']; try { - $this->activityPublisher->publish( + $row = new ActivityRow( type: Extension::EVENT_UPDATED, actorUserId: $actingAdminId, - recipientUserId: $actingAdminId, - dashboardUuid: 'template-resync-' . $templateId, - dashboardName: 'Template resync: ' . $templateName . ' (' . $strategy . ', ' . $affectedCount . ' copies)', - dashboardLink: '', + dashboard: new ActivitySubject( + uuid: 'template-resync-' . $templateId, + name: 'Template resync: ' . $templateName . ' (' . $strategy . ', ' . $affectedCount . ' copies)' + ), extraParams: [ 'templateResync' => true, 'templateId' => $templateId, @@ -878,6 +851,7 @@ private function emitAuditEvent( 'affectedCount' => $affectedCount, ] ); + $this->activityPublisher->publish(row: $row, recipientUserId: $actingAdminId); } catch (Throwable $t) { $this->logger->warning( message: 'launchpad.template_resync.audit_event_failed', diff --git a/lib/Service/TemplateResyncTally.php b/lib/Service/TemplateResyncTally.php new file mode 100644 index 000000000..2c84cce8c --- /dev/null +++ b/lib/Service/TemplateResyncTally.php @@ -0,0 +1,65 @@ +<?php + +/** + * TemplateResyncTally + * + * The per-copy outcome of one applied template resync. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; +use OCA\LaunchPad\Db\WidgetPlacement; + +/** + * One applied resync of TemplateResyncService: the template's placements + * and the strategy every copy is diffed with, the report per copy, and the + * copies that took the change. Built by the service for one run and never + * handed out. + * + * @spec openspec/specs/admin-templates/spec.md + */ +final class TemplateResyncTally { + /** + * One report per copy, in copy order. + * + * @var array<int, array<string, mixed>> + */ + public array $reports = []; + + /** + * The copies that took the change, in copy order. + * + * @var array<int, Dashboard> + */ + public array $affected = []; + + /** + * Constructor + * + * @param array<int, WidgetPlacement> $templatePlacements The template's placements. + * @param string $strategy The resync strategy. + * @param string $templateName The template's name, for the version each copy gets. + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + */ + public function __construct( + public readonly array $templatePlacements, + public readonly string $strategy, + public readonly string $templateName='', + ) { + }//end __construct() +}//end class diff --git a/lib/Service/TemplateRolloutSummary.php b/lib/Service/TemplateRolloutSummary.php new file mode 100644 index 000000000..cc5de284a --- /dev/null +++ b/lib/Service/TemplateRolloutSummary.php @@ -0,0 +1,182 @@ +<?php + +/** + * TemplateRolloutSummary + * + * What a template re-sync's dry run tells the admin before they push + * (REQ-RESYNC-008): which widgets the template gained and lost since its + * copies were last synced, and how many people changed their copy. + * + * @category Service + * @package OCA\LaunchPad\Service + * + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\WidgetPlacement; + +/** + * Summarises a template against its copies. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen + */ +class TemplateRolloutSummary { + + /** + * Constructor. + * + * @param PlacementLayout $layout Tells whether an owner moved a placement. + */ + public function __construct( + private readonly PlacementLayout $layout = new PlacementLayout(), + ) { + }//end __construct() + + /** + * The summary of a template against its copies. + * + * A widget is gained when the template has it and no copy does yet; it is + * lost when a copy holds a template widget the template no longer has. A + * copy is changed by its owner when it holds a widget the owner added, + * a template widget the owner moved or resized, or lacks a template widget + * other copies hold (the owner removed it). + * + * @param WidgetPlacement[] $templatePlacements The template's placements. + * @param array<int, WidgetPlacement[]> $copies Each copy's placements. + * + * @return array{gained: array<int, string>, lost: array<int, string>, changedByOwnerCount: int} + * The widget names gained and lost, and the number of copies their owner changed. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen + */ + public function summarize(array $templatePlacements, array $copies): array { + if ($copies === []) { + return ['gained' => [], 'lost' => [], 'changedByOwnerCount' => 0]; + } + + $held = []; + foreach ($templatePlacements as $templatePlacement) { + $held[(int)$templatePlacement->getId()] = 0; + } + + $lost = []; + foreach ($copies as $placements) { + foreach ($this->originsOf(placements: $placements) as $originId => $placement) { + if (isset($held[$originId]) === true) { + $held[$originId]++; + continue; + } + + $lost[$originId] = $this->nameOf(placement: $placement); + } + } + + $changed = count( + array_filter( + $copies, + fn (array $placements): bool => $this->ownerChanged(placements: $placements, held: $held) + ) + ); + + return [ + 'gained' => $this->gained(templatePlacements: $templatePlacements, held: $held), + 'lost' => array_values($lost), + 'changedByOwnerCount' => $changed, + ]; + }//end summarize() + + /** + * The names of the template widgets no copy holds yet. + * + * @param WidgetPlacement[] $templatePlacements The template's placements. + * @param array<int, int> $held Per template placement id, the number of copies holding it. + * + * @return array<int, string> The names. + */ + private function gained(array $templatePlacements, array $held): array { + $gained = []; + foreach ($templatePlacements as $templatePlacement) { + if ($held[(int)$templatePlacement->getId()] === 0) { + $gained[] = $this->nameOf(placement: $templatePlacement); + } + } + + return $gained; + }//end gained() + + /** + * A copy's template-origin placements by the template placement they came from. + * + * @param WidgetPlacement[] $placements The copy's placements. + * + * @return array<int, WidgetPlacement> The placements by origin id. + */ + private function originsOf(array $placements): array { + $origins = []; + foreach ($placements as $placement) { + $originId = $placement->getTemplatePlacementId(); + if ($originId !== null) { + $origins[(int)$originId] = $placement; + } + } + + return $origins; + }//end originsOf() + + /** + * Whether the owner changed this copy. + * + * @param WidgetPlacement[] $placements The copy's placements. + * @param array<int, int> $held Per template placement id, the number of copies holding it. + * + * @return bool True when the owner added, moved or removed a widget. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen + */ + private function ownerChanged(array $placements, array $held): bool { + foreach ($placements as $placement) { + if ($placement->getTemplatePlacementId() === null || $this->layout->ownerMoved(placement: $placement) === true) { + return true; + } + } + + $origins = $this->originsOf(placements: $placements); + foreach ($held as $templateId => $count) { + if ($count > 0 && isset($origins[$templateId]) === false) { + return true; + } + } + + return false; + }//end ownerChanged() + + /** + * The name a person reads for a widget. + * + * @param WidgetPlacement $placement The placement. + * + * @return string Its own title, its tile title, else its widget id. + */ + private function nameOf(WidgetPlacement $placement): string { + foreach ([$placement->getCustomTitle(), $placement->getTileTitle()] as $name) { + if ($name !== null && trim($name) !== '') { + return $name; + } + } + + return (string)$placement->getWidgetId(); + }//end nameOf() +}//end class diff --git a/lib/Service/TemplateService.php b/lib/Service/TemplateService.php index b664d023b..986b54a07 100644 --- a/lib/Service/TemplateService.php +++ b/lib/Service/TemplateService.php @@ -19,14 +19,18 @@ namespace OCA\LaunchPad\Service; use DateTime; +use OCA\LaunchPad\AppInfo\Application; use OCA\LaunchPad\Db\Dashboard; use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\WidgetPlacement; use OCA\LaunchPad\Db\WidgetPlacementMapper; use OCP\AppFramework\Db\DoesNotExistException; +use OCP\IAppConfig; /** * Service for managing admin dashboard templates. + * + * @spec openspec/specs/admin-templates/spec.md */ class TemplateService { /** @@ -39,22 +43,32 @@ class TemplateService { * for * `IGroupManager::getUserGroupIds` * (REQ-TMPL-013). + * @param IAppConfig $appConfig Says which template is the installed + * copy of a shipped one (REQ-TMPL-021). */ public function __construct( private readonly DashboardMapper $dashboardMapper, private readonly WidgetPlacementMapper $placementMapper, private readonly AdminTemplateService $adminTemplateService, + private readonly IAppConfig $appConfig, ) { }//end __construct() /** * Get the applicable admin template for a user. * + * A template that targets one of the user's groups goes before the + * default template. When several target the user's groups, one rule + * picks, the same on every instance and every visit (REQ-TMPL-021): + * the installed copy of a shipped template first, the newest shipped + * version first among those, then the lowest id. + * * @param string $userId The user ID. * * @return Dashboard|null The applicable template or null. * * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-7 + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-021 */ public function getApplicableTemplate(string $userId): ?Dashboard { $templates = $this->dashboardMapper->findAdminTemplates(); @@ -62,29 +76,36 @@ public function getApplicableTemplate(string $userId): ?Dashboard { // Group memberships are read through the routing resolver so the // single-source-of-truth invariant (REQ-TMPL-013) holds. An empty // result means either an unknown user OR a known user with no - // group memberships — in both cases we skip the per-template - // intersection scan and fall through to the default template - // lookup at the end of the method (preserving legacy behaviour). + // group memberships — in both cases no template can match and the + // default template lookup at the end decides. $userGroups = $this->adminTemplateService->getUserGroupIdsFor( userId: $userId ); - // Find template that matches user's groups. + $shippedVersions = $this->shippedVersionsByUuid(); + $best = null; + $bestVersion = 0; foreach ($templates as $template) { - $targetGroups = $template->getTargetGroupsArray(); - - // Empty target groups means applies to all users. - if (empty($targetGroups) === true) { + // A template without target groups is not group-targeted; only + // the default flag can hand it out. + if (empty(array_intersect($userGroups, $template->getTargetGroupsArray())) === true) { continue; - // Check for more specific templates first. } - // Check if user is in any target group. - if (empty(array_intersect($userGroups, $targetGroups)) === false) { - return $template; + $version = ($shippedVersions[(string)$template->getUuid()] ?? 0); + if ($best === null + || $version > $bestVersion + || ($version === $bestVersion && $template->getId() < $best->getId()) + ) { + $best = $template; + $bestVersion = $version; } } + if ($best !== null) { + return $best; + } + // Return default template if exists. try { return $this->dashboardMapper->findDefaultTemplate(); @@ -93,6 +114,40 @@ public function getApplicableTemplate(string $userId): ?Dashboard { } }//end getApplicableTemplate() + /** + * The shipped version each installed shipped template carries, by the + * template's UUID. A template an administrator made by hand, and an + * earlier copy a forced install left behind, are not in the list. + * + * @return array<string, int> Template UUID to shipped version. + */ + private function shippedVersionsByUuid(): array { + $versions = []; + foreach (ShippedTemplateService::SHIPPED_IDS as $id) { + $uuid = $this->appConfig->getValueString( + Application::APP_ID, + ShippedTemplateService::CONFIG_PREFIX . $id, + '' + ); + if ($uuid === '') { + continue; + } + + // At least 1: a recorded install without a recorded version is + // still the shipped one. + $versions[$uuid] = max( + 1, + $this->appConfig->getValueInt( + Application::APP_ID, + ShippedTemplateService::CONFIG_VERSION_PREFIX . $id, + 0 + ) + ); + } + + return $versions; + }//end shippedVersionsByUuid() + /** * Create a user dashboard based on an admin template. * @@ -134,6 +189,7 @@ public function createDashboardFromTemplate( * @param Dashboard $template The admin template. * * @return Dashboard The built dashboard entity. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies */ private function buildDashboardFromTemplate( string $userId, @@ -141,7 +197,7 @@ private function buildDashboardFromTemplate( ): Dashboard { $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); $dashboard = new Dashboard(); - $dashboard->setUuid($this->generateUuid()); + $dashboard->setUuid(UuidV4::generate()); $dashboard->setName($template->getName()); $dashboard->setDescription( $template->getDescription() @@ -157,6 +213,8 @@ private function buildDashboardFromTemplate( $dashboard->setPermissionLevel( $template->getPermissionLevel() ); + // REQ-CWF-011: a dashboard made from a template drills down as the template does. + $dashboard->setHierarchiesArray($template->getHierarchiesArray()); $dashboard->setIsActive(1); $dashboard->setCreatedAt($now); $dashboard->setUpdatedAt($now); @@ -164,21 +222,6 @@ private function buildDashboardFromTemplate( return $dashboard; }//end buildDashboardFromTemplate() - /** - * Generate a v4 UUID using random_bytes (no external dependency). - * - * @return string A v4 UUID. - */ - private function generateUuid(): string { - $data = random_bytes(length: 16); - $data[6] = chr((ord($data[6]) & 0x0F) | 0x40); - $data[8] = chr((ord($data[8]) & 0x3F) | 0x80); - return vsprintf( - format: '%s%s-%s-%s-%s-%s%s%s', - values: str_split(string: bin2hex(string: $data), length: 4) - ); - }//end generateUuid() - /** * Copy widget placements from a template to a new dashboard. * @@ -225,6 +268,8 @@ private function copyTemplatePlacements( * @param int $dashboardId The target dashboard ID. * * @return WidgetPlacement The cloned placement entity. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-007-merge-leaves-a-widget-where-the-person-put-it */ private function clonePlacement( WidgetPlacement $source, @@ -252,6 +297,8 @@ private function clonePlacement( $placement->setCustomIcon($source->getCustomIcon()); $placement->setShowTitle($source->getShowTitle()); $placement->setSortOrder($source->getSortOrder()); + // REQ-VIS-014: how the visibility rules combine travels with the copy. + $placement->setRuleMatch($source->getRuleMatch()); // REQ-DASH-020: `content` carries the widget configuration — for // `nc-widget` rows the `{"widgetId": ...}` JSON that tells the // renderer what to load. Dropping it distributes widgets into a @@ -282,6 +329,9 @@ private function clonePlacement( // admin re-sync can reconcile this placement against the template // while leaving genuinely user-added placements alone. $placement->setTemplatePlacementId($source->getId()); + // REQ-RESYNC-007: the layout the template gave this copy, so a later + // `merge` re-sync can tell whether the owner moved the widget. + (new PlacementLayout())->stamp(placement: $placement); $now = (new DateTime())->format(format: 'Y-m-d H:i:s'); $placement->setCreatedAt($now); $placement->setUpdatedAt($now); diff --git a/lib/Service/TextTableValidator.php b/lib/Service/TextTableValidator.php new file mode 100644 index 000000000..7d7e14cf6 --- /dev/null +++ b/lib/Service/TextTableValidator.php @@ -0,0 +1,123 @@ +<?php + +/** + * TextTableValidator + * + * Server-side grid check for the `text` widget's table mode, the same rules + * the shared editor applies before save (nextcloud-vue `validateTable`). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/text-display-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * Validates `text` widget table content before a placement is saved. + * + * A table is a full grid: every row holds one cell per column (a cell + * covered by a neighbour's span is an empty placeholder), the column count + * is `columnAlignments`' length, and no span reaches past the grid. + * + * @spec openspec/specs/text-display-widget/spec.md + */ +class TextTableValidator { + + /** + * Validate a text placement's table, when it is in table mode. + * + * @param array $content The placement content. + * + * @return void + * @throws InvalidArgumentException When the grid is not rectangular or a span leaves it. + * + * @spec openspec/specs/text-display-widget/spec.md + */ + public function validate(array $content): void { + if (($content['tableMode'] ?? false) !== true) { + return; + } + + $table = ($content['tableData'] ?? null); + if (is_array($table) === false) { + $table = []; + } + + $rows = ($table['rows'] ?? null); + if (is_array($rows) === false || $rows === []) { + throw new InvalidArgumentException(message: 'Table must have at least one row'); + } + + $alignments = ($table['columnAlignments'] ?? null); + if (is_array($alignments) === false || $alignments === []) { + throw new InvalidArgumentException(message: 'Table must have at least one column'); + } + + $this->checkGrid(rows: array_values($rows), columns: count($alignments)); + }//end validate() + + /** + * Refuse rows of another width and spans that leave the grid. + * + * @param array $rows The rows, as a list. + * @param int $columns The column count. + * + * @return void + * @throws InvalidArgumentException When the grid is not rectangular or a span leaves it. + * + * @spec openspec/specs/text-display-widget/spec.md + */ + private function checkGrid(array $rows, int $columns): void { + $rowCount = count($rows); + foreach ($rows as $rowIndex => $row) { + if (is_array($row) === false || count($row) !== $columns) { + throw new InvalidArgumentException(message: 'Grid is not rectangular'); + } + + foreach (array_values($row) as $colIndex => $cell) { + if ($rowIndex + $this->span(cell: $cell, key: 'rowSpan') > $rowCount + || $colIndex + $this->span(cell: $cell, key: 'colSpan') > $columns + ) { + throw new InvalidArgumentException(message: 'Cell span exceeds grid bounds'); + } + } + } + }//end checkGrid() + + /** + * A cell's row or column span, 1 when absent or not a positive integer. + * + * @param mixed $cell The cell. + * @param string $key `rowSpan` or `colSpan`. + * + * @return int The span. + * + * @spec openspec/specs/text-display-widget/spec.md + */ + private function span(mixed $cell, string $key): int { + $span = 1; + if (is_array($cell) === true) { + $span = ($cell[$key] ?? 1); + } + + if (is_int($span) === false || $span < 1) { + return 1; + } + + return $span; + }//end span() +}//end class diff --git a/lib/Service/TileAnalyticsService.php b/lib/Service/TileAnalyticsService.php index dc96d32f9..849078392 100644 --- a/lib/Service/TileAnalyticsService.php +++ b/lib/Service/TileAnalyticsService.php @@ -50,6 +50,7 @@ use OCA\LaunchPad\Db\DashboardMapper; use OCA\LaunchPad\Db\TileClickMapper; use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Kernel\Contracts\TileAnalyticsServiceInterface; use OCP\AppFramework\Db\DoesNotExistException; /** @@ -61,47 +62,21 @@ * declared `public static`; injecting their owning classes purely to reach * them would add two collaborators that are never otherwise used here. */ -class TileAnalyticsService { +class TileAnalyticsService implements TileAnalyticsServiceInterface { /** * Constructor. * - * @param TileClickMapper $tileClickMapper Aggregate-row mapper. - * @param WidgetPlacementMapper $placementMapper Resolves the placement - * (tile) that was - * clicked to its owning - * dashboard. - * @param DashboardMapper $dashboardMapper Resolves the owning - * dashboard's UUID. - * @param UniqueViewerDedup $dedup Reused unique-actor - * dedup service - * (REQ-TANLT-002). - * @param AnalyticsService $analyticsService Reused for - * `analytics_enabled` - * / - * `analytics_optout` - * / - * retention - * (REQ-TANLT-003, - * REQ-TANLT-005) - * — this - * service - * never - * reads - * `IAppConfig`/`IConfig` - * directly - * so there - * is exactly - * one place - * those - * gates - * live. + * @param TileClickMapper $tileClickMapper Aggregate-row mapper. + * @param WidgetPlacementMapper $placementMapper Resolves the placement (tile) that was clicked to its + * owning dashboard. + * @param DashboardMapper $dashboardMapper Resolves the owning dashboard's UUID. + * @param TileViewTools $views The viewer dedup and analytics service. */ public function __construct( private readonly TileClickMapper $tileClickMapper, private readonly WidgetPlacementMapper $placementMapper, private readonly DashboardMapper $dashboardMapper, - private readonly UniqueViewerDedup $dedup, - private readonly AnalyticsService $analyticsService, + private readonly TileViewTools $views, ) { }//end __construct() @@ -119,11 +94,11 @@ public function __construct( * @spec openspec/specs/dashboard-view-analytics/spec.md */ public function isTrackingActiveFor(string $userId): bool { - if ($this->analyticsService->isGloballyEnabled() === false) { + if ($this->views->analyticsService->isGloballyEnabled() === false) { return false; } - return ($this->analyticsService->isUserOptedOut(userId: $userId) === false); + return ($this->views->analyticsService->isUserOptedOut(userId: $userId) === false); }//end isTrackingActiveFor() /** @@ -156,11 +131,11 @@ public function recordClick(int $placementId, string $userId): bool { $placement = $this->placementMapper->find(id: $placementId); $placementUuid = (string)$placementId; - if ($this->analyticsService->isGloballyEnabled() === false) { + if ($this->views->analyticsService->isGloballyEnabled() === false) { return false; } - if ($this->analyticsService->isUserOptedOut(userId: $userId) === true) { + if ($this->views->analyticsService->isUserOptedOut(userId: $userId) === true) { return false; } @@ -176,7 +151,7 @@ public function recordClick(int $placementId, string $userId): bool { } $today = UniqueViewerDedup::utcDateFor(); - $isNewActor = $this->dedup->isNewUniqueViewer( + $isNewActor = $this->views->dedup->isNewUniqueViewer( userId: $userId, viewBucketDate: $today, dashboardUuid: $placementUuid @@ -187,11 +162,13 @@ public function recordClick(int $placementId, string $userId): bool { } $this->tileClickMapper->upsertClick( - placementUuid: $placementUuid, - dashboardUuid: $dashboardUuid, - clickBucket: $today, - clickCountDelta: 1, - uniqueCountDelta: $uniqueDelta + click: [ + 'placementUuid' => $placementUuid, + 'dashboardUuid' => $dashboardUuid, + 'clickBucket' => $today, + 'clickCountDelta' => 1, + 'uniqueCountDelta' => $uniqueDelta, + ] ); return true; diff --git a/lib/Service/TileLaunchSettings.php b/lib/Service/TileLaunchSettings.php new file mode 100644 index 000000000..b4e082e7c --- /dev/null +++ b/lib/Service/TileLaunchSettings.php @@ -0,0 +1,207 @@ +<?php + +/** + * TileLaunchSettings + * + * The administrator's lists behind the program and single sign-on tile types: + * the URL schemes a program tile may use, and the identity-provider launch + * templates a single sign-on tile picks from. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-a-program-on-the-users-computer-req-tlt-001 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * Validates and normalises the two tile-launch admin settings (design D1, D4). + * + * A write is refused whole, naming the offending entry, rather than stored + * with the bad entry dropped: an administrator who typed a scheme or a + * template should learn it was not taken. A stored value that no longer + * validates reads as empty, so nothing unsafe ever reaches a tile. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-a-program-on-the-users-computer-req-tlt-001 + */ +class TileLaunchSettings { + + /** + * Schemes a program tile never uses, whatever an administrator lists: + * they run script, read the local disk or carry inline content. + */ + public const FORBIDDEN_SCHEMES = ['javascript', 'data', 'file', 'vbscript', 'about', 'blob']; + + /** + * The placeholder a launch template must carry. + */ + public const APP_ID_PLACEHOLDER = '{appId}'; + + /** + * The most entries either list may hold. + */ + private const MAX_ENTRIES = 50; + + /** + * The allowed schemes: lower-case RFC 3986 scheme names, none forbidden, no duplicates. + * + * @param mixed $input The submitted list. + * + * @return list<string> + * + * @throws InvalidArgumentException Naming the scheme refused. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-a-program-on-the-users-computer-req-tlt-001 + */ + public function schemes(mixed $input): array { + if (is_array($input) === false || count($input) > self::MAX_ENTRIES) { + throw new InvalidArgumentException(message: 'tileAllowedSchemes must be a list of at most ' . self::MAX_ENTRIES . ' schemes.'); + } + + $schemes = []; + foreach ($input as $scheme) { + if (is_string($scheme) === false) { + $scheme = ''; + } + + $scheme = rtrim(trim($scheme), ':'); + if (preg_match('/^[a-z][a-z0-9+.-]{0,31}$/', $scheme) !== 1) { + throw new InvalidArgumentException(message: 'The scheme "' . $scheme . '" is not a lower-case URL scheme.'); + } + + if (in_array($scheme, self::FORBIDDEN_SCHEMES, true) === true) { + throw new InvalidArgumentException(message: 'The scheme "' . $scheme . '" is never allowed on a tile.'); + } + + $schemes[$scheme] = $scheme; + } + + return array_values($schemes); + }//end schemes() + + /** + * The launch templates: each a unique key, a name, and an https address with `{appId}`. + * + * @param mixed $input The submitted list of `{key, name, urlTemplate}`. + * + * @return list<array{key: string, name: string, urlTemplate: string}> + * + * @throws InvalidArgumentException Naming the template refused. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-single-sign-on-into-a-company-app-req-tlt-003 + */ + public function templates(mixed $input): array { + if (is_array($input) === false || count($input) > self::MAX_ENTRIES) { + throw new InvalidArgumentException(message: 'ssoLaunchTemplates must be a list of at most ' . self::MAX_ENTRIES . ' templates.'); + } + + $templates = []; + foreach ($input as $entry) { + $template = $this->template(entry: $entry); + if (isset($templates[$template['key']]) === true) { + throw new InvalidArgumentException(message: 'The launch template key "' . $template['key'] . '" is used twice.'); + } + + $templates[$template['key']] = $template; + } + + return array_values($templates); + }//end templates() + + /** + * A stored value read back: the validated list, or empty when it no longer validates. + * + * @param string $setting `schemes` or `templates`. + * @param mixed $stored The stored value. + * + * @return list<mixed> + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-a-program-on-the-users-computer-req-tlt-001 + */ + public function stored(string $setting, mixed $stored): array { + if ($stored === null) { + return []; + } + + try { + if ($setting === 'schemes') { + return $this->schemes(input: $stored); + } + + return $this->templates(input: $stored); + } catch (InvalidArgumentException $e) { + return []; + } + }//end stored() + + /** + * One launch template, checked. + * + * @param mixed $entry The submitted template. + * + * @return array{key: string, name: string, urlTemplate: string} + * + * @throws InvalidArgumentException Naming what is wrong. + */ + private function template(mixed $entry): array { + if (is_array($entry) === false) { + throw new InvalidArgumentException(message: 'A launch template must have a key, a name and an address.'); + } + + $key = trim((string)($entry['key'] ?? '')); + $name = trim((string)($entry['name'] ?? '')); + $url = trim((string)($entry['urlTemplate'] ?? '')); + if (preg_match('/^[a-z0-9][a-z0-9-]{0,63}$/', $key) !== 1) { + throw new InvalidArgumentException(message: 'The launch template key "' . $key . '" must be lower-case letters, digits and hyphens.'); + } + + if ($name === '' || mb_strlen($name) > 100) { + throw new InvalidArgumentException(message: 'The launch template "' . $key . '" needs a name of at most 100 characters.'); + } + + if ($this->isLaunchAddress(url: $url) === false) { + throw new InvalidArgumentException( + message: 'The launch template "' . $key . '" must be an https address containing ' . self::APP_ID_PLACEHOLDER . ' once.' + ); + } + + return ['key' => $key, 'name' => $name, 'urlTemplate' => $url]; + }//end template() + + /** + * Whether an address is https, names a host, carries `{appId}` exactly once and no other placeholder. + * + * @param string $url The template address. + * + * @return bool + */ + private function isLaunchAddress(string $url): bool { + if (substr_count($url, self::APP_ID_PLACEHOLDER) !== 1 || strlen($url) > 2048) { + return false; + } + + $resolved = str_replace(self::APP_ID_PLACEHOLDER, 'app', $url); + if (str_contains($resolved, '{') === true || str_contains($resolved, '}') === true) { + return false; + } + + $parts = parse_url($resolved); + if (is_array($parts) === false || strtolower((string)($parts['scheme'] ?? '')) !== 'https') { + return false; + } + + $host = (string)($parts['host'] ?? ''); + return $host !== '' && isset($parts['user']) === false && isset($parts['pass']) === false + && filter_var('https://' . $host, FILTER_VALIDATE_URL) !== false; + }//end isLaunchAddress() +}//end class diff --git a/lib/Service/TileLinkTarget.php b/lib/Service/TileLinkTarget.php new file mode 100644 index 000000000..79ceaf999 --- /dev/null +++ b/lib/Service/TileLinkTarget.php @@ -0,0 +1,111 @@ +<?php + +/** + * TileLinkTarget + * + * The three ways a tile can open, and the order in which a tile's own choice, + * its dashboard's default and the link type decide between them. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * Link-target values and their resolution (launcher-tile-open-behaviour D1, D2). + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ +class TileLinkTarget { + + /** + * Open in the same tab. + */ + public const SAME_TAB = 'same-tab'; + + /** + * Open in a new tab. + */ + public const NEW_TAB = 'new-tab'; + + /** + * Open in the panel beside the tiles. + */ + public const SIDE_PANEL = 'side-panel'; + + /** + * Every accepted value. + */ + public const VALUES = [self::SAME_TAB, self::NEW_TAB, self::SIDE_PANEL]; + + /** + * A link target as given, or null when none is given. + * + * Null and the empty string mean "not set". Anything else that is not one + * of the three values is refused. + * + * @param mixed $value The value. + * @param string $field The field name, for the refusal message. + * + * @return string|null + * + * @throws InvalidArgumentException When the value is not a link target. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + public static function validated(mixed $value, string $field='linkTarget'): ?string { + if ($value === null || $value === '') { + return null; + } + + if (is_string($value) === false || in_array($value, self::VALUES, true) === false) { + throw new InvalidArgumentException( + message: $field . ' must be one of ' . implode(', ', self::VALUES) + ); + } + + return $value; + }//end validated() + + /** + * How a tile opens: its own target, else the dashboard default, else the + * rule from before the setting existed (a web address in a new tab, an + * app or internal path in the same tab). + * + * @param string|null $tileTarget The tile's own target. + * @param string|null $dashboardDefault The dashboard's default. + * @param string|null $linkType The tile's link type (`url`, `app`, ...). + * + * @return string + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + public static function resolve(?string $tileTarget, ?string $dashboardDefault, ?string $linkType): string { + foreach ([$tileTarget, $dashboardDefault] as $candidate) { + if ($candidate !== null && in_array($candidate, self::VALUES, true) === true) { + return $candidate; + } + } + + if ($linkType === 'url') { + return self::NEW_TAB; + } + + return self::SAME_TAB; + }//end resolve() +}//end class diff --git a/lib/Service/TileLinkValidator.php b/lib/Service/TileLinkValidator.php new file mode 100644 index 000000000..fd7dfbb5e --- /dev/null +++ b/lib/Service/TileLinkValidator.php @@ -0,0 +1,357 @@ +<?php + +/** + * TileLinkValidator + * + * Checks the three tile link types that start something other than a web + * page: a program on the user's computer (`program`), a remote desktop or a + * published program (`remote-desktop`) and a single sign-on app (`sso`). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use InvalidArgumentException; + +/** + * Validates a launch tile's address and content on the server (design D1). + * + * Every check returns the link value to store, so a tile never keeps an + * address the server did not produce or accept. A refusal throws, which the + * placement API answers with HTTP 400 before anything is saved. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-2 + */ +class TileLinkValidator { + + public const TYPE_PROGRAM = 'program'; + public const TYPE_REMOTE = 'remote-desktop'; + public const TYPE_SSO = 'sso'; + + /** + * The link types this validator owns. + */ + public const LAUNCH_TYPES = [self::TYPE_PROGRAM, self::TYPE_REMOTE, self::TYPE_SSO]; + + /** + * The port an RDP connection uses when the tile names none. + */ + public const DEFAULT_RDP_PORT = 3389; + + /** + * A DNS host name: labels of letters, digits and inner hyphens. + */ + private const HOST_PATTERN = '/^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/'; + + /** + * A published program (RemoteApp) name such as `||Belastingen`. + */ + private const REMOTE_APP_PATTERN = '/^(?:\|\|)?[A-Za-z0-9][A-Za-z0-9 ._()-]{0,127}$/'; + + /** + * An identity provider's identifier of an app. + */ + private const APP_ID_PATTERN = '/^[A-Za-z0-9._:-]{1,128}$/'; + + /** + * The longest address a tile keeps. + */ + private const MAX_ADDRESS = 2048; + + /** + * Constructor. + * + * @param AdminSettingsService $settings Holds the allowed schemes and the launch templates. + */ + public function __construct( + private readonly AdminSettingsService $settings, + ) { + }//end __construct() + + /** + * Whether a link type is one this validator owns. + * + * @param string|null $type The tile's link type. + * + * @return bool + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-2 + */ + public static function isLaunchType(?string $type): bool { + return in_array($type, self::LAUNCH_TYPES, true); + }//end isLaunchType() + + /** + * Check a launch tile and return the link value to store. + * + * @param string $type The link type, one of LAUNCH_TYPES. + * @param string $value The address the client sent. + * @param array<string, mixed> $content The placement's content (`remote`, `sso`). + * + * @return string The link value to store. + * + * @throws InvalidArgumentException When the tile may not be saved like this. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-2 + */ + public function check(string $type, string $value, array $content): string { + return match ($type) { + self::TYPE_PROGRAM => $this->program(address: $value), + self::TYPE_REMOTE => $this->remote(content: $content)['url'], + self::TYPE_SSO => $this->sso(content: $content), + default => throw new InvalidArgumentException(message: 'The link type "' . $type . '" is not a launch type.'), + }; + }//end check() + + /** + * The checked RDP connection of a remote-desktop tile in RDP mode. + * + * @param array<string, mixed> $content The placement's content. + * + * @return array{host: string, port: int, remoteApp: string, gateway: string} + * + * @throws InvalidArgumentException When the tile holds no valid RDP connection. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md#requirement-a-tile-can-start-a-remote-desktop-or-a-published-program-req-tlt-002 + */ + public function rdpConnection(array $content): array { + $remote = $this->remote(content: $content); + if ($remote['mode'] !== 'rdp') { + throw new InvalidArgumentException(message: 'This remote desktop tile opens a web gateway, not an RDP connection.'); + } + + return [ + 'host' => $remote['host'], + 'port' => $remote['port'], + 'remoteApp' => $remote['remoteApp'], + 'gateway' => $remote['gateway'], + ]; + }//end rdpConnection() + + /** + * A program address: a scheme the administrator allowed, never a forbidden one. + * + * @param string $address The address. + * + * @return string + * + * @throws InvalidArgumentException When the scheme is not allowed. + */ + private function program(string $address): string { + $address = trim($address); + if ($address === '' || strlen($address) > self::MAX_ADDRESS || preg_match('/[\x00-\x20\x7f]/', $address) === 1 + || preg_match('/^([A-Za-z][A-Za-z0-9+.-]{0,31}):/', $address, $match) !== 1 + ) { + throw new InvalidArgumentException(message: 'A program tile needs an address that starts with a scheme, such as ms-word:.'); + } + + $scheme = strtolower($match[1]); + if (in_array($scheme, TileLaunchSettings::FORBIDDEN_SCHEMES, true) === true) { + throw new InvalidArgumentException(message: 'The scheme "' . $scheme . '" is never allowed on a tile.'); + } + + if (in_array($scheme, $this->allowedSchemes(), true) === false) { + throw new InvalidArgumentException(message: 'The scheme "' . $scheme . '" is not on the allowed list.'); + } + + return $address; + }//end program() + + /** + * The schemes the administrator allowed. + * + * @return array<int, string> + */ + private function allowedSchemes(): array { + return (array)($this->settings->getSettings()['tileAllowedSchemes'] ?? []); + }//end allowedSchemes() + + /** + * The checked `content.remote` of a remote-desktop tile. + * + * @param array<string, mixed> $content The placement's content. + * + * @return array{mode: string, url: string, host: string, port: int, remoteApp: string, gateway: string} + * + * @throws InvalidArgumentException When the remote settings are not valid. + */ + private function remote(array $content): array { + $remote = ($content['remote'] ?? null); + if (is_array($remote) === false) { + throw new InvalidArgumentException(message: 'A remote desktop tile needs a gateway address or an RDP connection.'); + } + + $checked = ['mode' => '', 'url' => '', 'host' => '', 'port' => self::DEFAULT_RDP_PORT, 'remoteApp' => '', 'gateway' => '']; + if (($remote['mode'] ?? null) === 'gateway') { + $checked['mode'] = 'gateway'; + $checked['url'] = $this->httpsAddress(url: trim((string)($remote['url'] ?? ''))); + return $checked; + } + + if (($remote['mode'] ?? null) !== 'rdp') { + throw new InvalidArgumentException(message: 'A remote desktop tile opens a gateway or an RDP connection.'); + } + + $checked['mode'] = 'rdp'; + $checked['host'] = $this->host(host: ($remote['host'] ?? ''), what: 'host'); + $checked['port'] = $this->port(port: ($remote['port'] ?? null)); + $checked['remoteApp'] = $this->remoteApp(name: ($remote['remoteApp'] ?? '')); + $checked['gateway'] = $this->optionalHost(host: ($remote['gateway'] ?? '')); + return $checked; + }//end remote() + + /** + * An https address without credentials. + * + * @param string $url The address. + * + * @return string + * + * @throws InvalidArgumentException When it is not one. + */ + private function httpsAddress(string $url): string { + $parts = parse_url($url); + $valid = is_array($parts) === true && strlen($url) <= self::MAX_ADDRESS + && strtolower((string)($parts['scheme'] ?? '')) === 'https' + && preg_match(self::HOST_PATTERN, (string)($parts['host'] ?? '')) === 1 + && isset($parts['user']) === false && isset($parts['pass']) === false + && preg_match('/[\x00-\x20\x7f]/', $url) !== 1; + if ($valid === false) { + throw new InvalidArgumentException(message: 'A gateway address must be an https address without a user name or password.'); + } + + return $url; + }//end httpsAddress() + + /** + * A host name. + * + * @param mixed $host The value. + * @param string $what The field, for the message. + * + * @return string + * + * @throws InvalidArgumentException When it is not a host name. + */ + private function host(mixed $host, string $what): string { + if (is_string($host) === false || preg_match(self::HOST_PATTERN, $host) !== 1) { + throw new InvalidArgumentException(message: 'The RDP ' . $what . ' must be a host name.'); + } + + return $host; + }//end host() + + /** + * An optional host name; empty when not given. + * + * @param mixed $host The value. + * + * @return string + * + * @throws InvalidArgumentException When it is given and not a host name. + */ + private function optionalHost(mixed $host): string { + if ($host === null || $host === '') { + return ''; + } + + return $this->host(host: $host, what: 'gateway'); + }//end optionalHost() + + /** + * A TCP port; the RDP default when not given. + * + * @param mixed $port The value. + * + * @return int + * + * @throws InvalidArgumentException When it is not a port. + */ + private function port(mixed $port): int { + if ($port === null || $port === '') { + return self::DEFAULT_RDP_PORT; + } + + if (is_int($port) === false && (is_string($port) === false || preg_match('/^\d{1,5}$/', $port) !== 1)) { + throw new InvalidArgumentException(message: 'The RDP port must be a number from 1 to 65535.'); + } + + $port = (int)$port; + if ($port < 1 || $port > 65535) { + throw new InvalidArgumentException(message: 'The RDP port must be a number from 1 to 65535.'); + } + + return $port; + }//end port() + + /** + * An optional published program name. + * + * @param mixed $name The value. + * + * @return string + * + * @throws InvalidArgumentException When it is given and not a program name. + */ + private function remoteApp(mixed $name): string { + if ($name === null || $name === '') { + return ''; + } + + if (is_string($name) === false || preg_match(self::REMOTE_APP_PATTERN, $name) !== 1) { + throw new InvalidArgumentException(message: 'The published program must be a program name such as ||Belastingen.'); + } + + return $name; + }//end remoteApp() + + /** + * The address of a single sign-on tile: its template with the encoded app id. + * + * @param array<string, mixed> $content The placement's content. + * + * @return string + * + * @throws InvalidArgumentException When the template or app id is not valid. + */ + private function sso(array $content): string { + $sso = ($content['sso'] ?? null); + if (is_array($sso) === false) { + $sso = []; + } + + $key = ($sso['template'] ?? null); + $appId = ($sso['appId'] ?? null); + if (is_string($appId) === false || preg_match(self::APP_ID_PATTERN, $appId) !== 1) { + throw new InvalidArgumentException(message: 'A single sign-on tile needs an app id of letters, digits and . _ : -.'); + } + + foreach ($this->templates() as $template) { + if (is_array($template) === true && ($template['key'] ?? null) === $key) { + return str_replace(TileLaunchSettings::APP_ID_PLACEHOLDER, rawurlencode($appId), (string)$template['urlTemplate']); + } + } + + throw new InvalidArgumentException(message: 'A single sign-on tile must name one of the launch templates.'); + }//end sso() + + /** + * The launch templates the administrator defined. + * + * @return array<int, mixed> + */ + private function templates(): array { + return (array)($this->settings->getSettings()['ssoLaunchTemplates'] ?? []); + }//end templates() +}//end class diff --git a/lib/Service/TileUpdater.php b/lib/Service/TileUpdater.php index 133e6acd5..4e512d2ce 100644 --- a/lib/Service/TileUpdater.php +++ b/lib/Service/TileUpdater.php @@ -18,12 +18,23 @@ namespace OCA\LaunchPad\Service; +use InvalidArgumentException; use OCA\LaunchPad\Db\WidgetPlacement; /** * Service for applying tile-specific updates to widget placements. */ class TileUpdater { + /** + * Constructor. + * + * @param TileLinkValidator|null $links Checks the program, remote-desktop and sso link types; without it those types are refused. + */ + public function __construct( + private readonly ?TileLinkValidator $links = null, + ) { + }//end __construct() + /** * Apply tile configuration to a new placement entity. * @@ -32,7 +43,11 @@ class TileUpdater { * * @return void * + * @throws InvalidArgumentException When the office-network address, the link target or the launch link is not allowed (HTTP 400). + * * @spec openspec/specs/tiles/spec.md + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-a-tile-can-hold-an-office-network-address-req-tia-002 + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md */ public function applyTileConfig( WidgetPlacement $placement, @@ -60,6 +75,22 @@ public function applyTileConfig( $placement->setTileLinkValue( $tileData['linkVal'] ?? '' ); + if (is_array($tileData['content'] ?? null) === true) { + if (array_key_exists('internalUrl', $tileData['content']) === true) { + $this->assertValidInternalUrl(url: $tileData['content']['internalUrl']); + } + + $placement->setContentArray($tileData['content']); + } + + $linkTarget = $this->validatedLinkTarget(value: ($tileData['linkTarget'] ?? null), field: 'linkTarget'); + if ($linkTarget !== null) { + $placement->setContentArray( + array_merge($placement->getContentArray(), ['linkTarget' => $linkTarget]) + ); + } + + $this->checkLaunchLink(placement: $placement); }//end applyTileConfig() /** @@ -70,12 +101,17 @@ public function applyTileConfig( * * @return void * + * @throws \InvalidArgumentException When `content.linkTarget` is not a link target. + * * @spec openspec/specs/tiles/spec.md + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md */ public function applyTileUpdates( WidgetPlacement $placement, array $data, ): void { + $this->checkContentUpdate(content: ($data['content'] ?? null)); + if (isset($data['tileTitle']) === true) { $placement->setTileTitle($data['tileTitle']); } @@ -113,5 +149,124 @@ public function applyTileUpdates( $data['tileLinkValue'] ); } + + $this->checkLaunchLink(placement: $placement); }//end applyTileUpdates() + + /** + * Refuse an update whose content carries a link target or an office-network address that is not allowed. + * + * @param mixed $content The `content` of the update, when given. + * + * @return void + * + * @throws InvalidArgumentException When `content.linkTarget` or `content.internalUrl` is not allowed. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-a-tile-can-hold-an-office-network-address-req-tia-002 + */ + private function checkContentUpdate(mixed $content): void { + if (is_array($content) === false) { + return; + } + + // Launcher-tile-open-behaviour D1: the tile's link target rides in + // content; anything but the three values is refused before saving. + $this->validatedLinkTarget(value: ($content['linkTarget'] ?? null), field: 'content.linkTarget'); + + if (array_key_exists('internalUrl', $content) === true) { + $this->assertValidInternalUrl(url: $content['internalUrl']); + } + }//end checkContentUpdate() + + /** + * A link target as given, or null when none is given. + * + * @param mixed $value The value. + * @param string $field The field name, for the refusal message. + * + * @return string|null + * + * @throws \InvalidArgumentException When the value is not a link target. + * + * @SuppressWarnings(PHPMD.StaticAccess) TileLinkTarget holds the rule as a pure function. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + private function validatedLinkTarget(mixed $value, string $field): ?string { + return TileLinkTarget::validated(value: $value, field: $field); + }//end validatedLinkTarget() + + /** + * Check a program, remote-desktop or sso tile as it will be saved, and + * store the link value the check returns. Other link types are left as + * they are. + * + * The check reads the placement's final link type, link value and + * content, so a save that changes only one of them is checked too. + * + * @param WidgetPlacement $placement The placement, with this save's changes applied. + * + * @return void + * + * @throws InvalidArgumentException When the tile may not be saved like this (HTTP 400). + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-2 + */ + private function checkLaunchLink(WidgetPlacement $placement): void { + $type = $placement->getTileLinkType(); + if (TileLinkValidator::isLaunchType(type: $type) === false) { + return; + } + + if ($this->links === null) { + throw new InvalidArgumentException(message: 'The link type "' . $type . '" cannot be checked here.'); + } + + $placement->setTileLinkValue( + $this->links->check( + type: (string)$type, + value: (string)($placement->getTileLinkValue() ?? ''), + content: $placement->getContentArray() + ) + ); + }//end checkLaunchLink() + + /** + * Refuse an office-network address that is not an http or https address or a path on this instance. + * + * Empty clears the address. Anything else, `javascript:` and `data:` + * included, is refused before the placement is saved. + * + * @param mixed $url The `content.internalUrl` value. + * + * @return void + * + * @throws InvalidArgumentException When the address is not allowed; the caller answers 400. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-a-tile-can-hold-an-office-network-address-req-tia-002 + */ + public function assertValidInternalUrl(mixed $url): void { + if ($url === null || $url === '') { + return; + } + + if (is_string($url) === false || preg_match('/[\x00-\x20\x7f]/', $url) === 1) { + throw new InvalidArgumentException(message: 'The address on the office network is not a valid address'); + } + + // A path on this instance, but not a protocol-relative `//host`. + if (str_starts_with(haystack: $url, needle: '/') === true && str_starts_with(haystack: $url, needle: '//') === false) { + return; + } + + $scheme = strtolower((string)parse_url(url: $url, component: PHP_URL_SCHEME)); + if (in_array(needle: $scheme, haystack: ['http', 'https'], strict: true) === true + && filter_var(value: $url, filter: FILTER_VALIDATE_URL) !== false + ) { + return; + } + + throw new InvalidArgumentException(message: 'The address on the office network is not a valid address'); + }//end assertValidInternalUrl() }//end class diff --git a/lib/Service/TileViewTools.php b/lib/Service/TileViewTools.php new file mode 100644 index 000000000..3077e9e39 --- /dev/null +++ b/lib/Service/TileViewTools.php @@ -0,0 +1,46 @@ +<?php + +/** + * TileViewTools + * + * The unique viewer dedup and the analytics service of the tile analytics service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboard-view-analytics/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The unique viewer dedup and the analytics service of the tile analytics service. + * + * @spec openspec/specs/dashboard-view-analytics/spec.md + */ +class TileViewTools { + /** + * Constructor. + * + * @param UniqueViewerDedup $dedup Reused unique-actor dedup service (REQ-TANLT-002). + * @param AnalyticsService $analyticsService Reused for `analytics_enabled` / `analytics_optout` / retention + * (REQ-TANLT-003, REQ-TANLT-005) — this service never reads + * `IAppConfig`/`IConfig` directly so there is exactly one place + * those gates live. + */ + public function __construct( + public readonly UniqueViewerDedup $dedup, + public readonly AnalyticsService $analyticsService, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/TreeLevel.php b/lib/Service/TreeLevel.php new file mode 100644 index 000000000..cf52b9d28 --- /dev/null +++ b/lib/Service/TreeLevel.php @@ -0,0 +1,67 @@ +<?php + +/** + * TreeLevel + * + * One level of a dashboard tree walk: the parent whose children are read, and how deep it sits. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\Dashboard; + +/** + * The parent UUID and depth of one level of a tree walk. + * + * @spec openspec/specs/dashboard-switcher/spec.md + */ +final class TreeLevel { + /** + * Constructor. + * + * @param string|null $parentUuid The parent UUID (null for roots). + * @param int $depth The depth of the children read at this level. + */ + public function __construct( + public readonly string|null $parentUuid, + public readonly int $depth, + ) { + }//end __construct() + + /** + * Whether this level is past the depth cap and reads nothing. + * + * @return bool True at or beyond Dashboard::MAX_DEPTH. + * + * @spec openspec/specs/dashboard-switcher/spec.md + */ + public function isBeyondCap(): bool { + return $this->depth >= Dashboard::MAX_DEPTH; + }//end isBeyondCap() + + /** + * The level below a child of this level. + * + * @param string $childUuid The child UUID. + * + * @return self The child's level. + * + * @spec openspec/specs/dashboard-switcher/spec.md + */ + public function below(string $childUuid): self { + return new self(parentUuid: $childUuid, depth: ($this->depth + 1)); + }//end below() +}//end class diff --git a/lib/Service/UniqueViewerDedup.php b/lib/Service/UniqueViewerDedup.php index 8ad8ce20e..11a304100 100644 --- a/lib/Service/UniqueViewerDedup.php +++ b/lib/Service/UniqueViewerDedup.php @@ -254,6 +254,18 @@ public function isNewUniqueViewer( viewerHash: $hash ); + return $this->markFirstSighting(cacheKey: $cacheKey); + }//end isNewUniqueViewer() + + /** + * Mark a dedup key as seen until the next UTC midnight, unless it + * already was. + * + * @param string $cacheKey The dedup cache key. + * + * @return bool `true` when the key was not seen yet today. + */ + private function markFirstSighting(string $cacheKey): bool { $cache = $this->getCache(); if ($cache->hasKey(key: $cacheKey) === true) { @@ -267,7 +279,7 @@ public function isNewUniqueViewer( ); return true; - }//end isNewUniqueViewer() + }//end markFirstSighting() /** * Build the canonical dedup cache key for `(dashboardUuid, diff --git a/lib/Service/UploadNamePicker.php b/lib/Service/UploadNamePicker.php new file mode 100644 index 000000000..a1acbb28b --- /dev/null +++ b/lib/Service/UploadNamePicker.php @@ -0,0 +1,112 @@ +<?php + +/** + * UploadNamePicker + * + * Picks the name a files-widget upload is stored under: separators and + * NUL replaced, and ` (1)`, ` (2)` … inserted before the extension while + * the name is taken (REQ-FLS-007). + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/files-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Files\Folder; + +/** + * Picks a free, safe name for an upload inside a folder. + * + * Built by {@see FilesWidgetService} for each upload; holds no state. + * + * @spec openspec/specs/files-widget/spec.md + */ +final class UploadNamePicker { + /** + * Find a free filename inside the target folder by appending + * `(1)`, `(2)` etc. when the desired name is taken (REQ-FLS-007). + * + * @param Folder $folder Target folder. + * @param string $desired Desired leaf name. + * + * @return string The free name. + * + * @spec openspec/specs/files-widget/spec.md + */ + public function availableName(Folder $folder, string $desired): string { + $sanitised = self::sanitiseUploadName(desired: $desired); + if ($folder->nodeExists(path: $sanitised) === false) { + return $sanitised; + } + + return $this->firstFreeNumberedName(folder: $folder, name: $sanitised); + }//end availableName() + + /** + * Replace path separators and NUL with `_`; an empty, `.` or `..` + * result becomes `upload`. + * + * @param string $desired Desired leaf name. + * + * @return string The safe leaf name. + */ + private static function sanitiseUploadName(string $desired): string { + $sanitised = str_replace(search: ['/', '\\', "\0"], replace: '_', subject: $desired); + if ($sanitised === '' || $sanitised === '.' || $sanitised === '..') { + return 'upload'; + } + + return $sanitised; + }//end sanitiseUploadName() + + /** + * The first of `name (1)` … `name (999)` that is free in the folder, + * else a `name (<unique id>)` variant. + * + * @param Folder $folder Target folder. + * @param string $name The taken, sanitised name. + * + * @return string The free name. + */ + private function firstFreeNumberedName(Folder $folder, string $name): string { + for ($i = 1; $i <= 999; $i++) { + $candidate = self::numberedName(name: $name, number: (string)$i); + if ($folder->nodeExists(path: $candidate) === false) { + return $candidate; + } + } + + return self::numberedName(name: $name, number: uniqid()); + }//end firstFreeNumberedName() + + /** + * Insert ` (<number>)` before a name's extension; a leading-dot name + * or one without a dot gets it at the end. + * + * @param string $name The sanitised name. + * @param string $number The number to insert. + * + * @return string The numbered name. + */ + private static function numberedName(string $name, string $number): string { + $extPos = strrpos(haystack: $name, needle: '.'); + if ($extPos !== false && $extPos !== 0) { + return substr(string: $name, offset: 0, length: $extPos) . ' (' . $number . ')' . substr(string: $name, offset: $extPos); + } + + return $name . ' (' . $number . ')'; + }//end numberedName() +}//end class diff --git a/lib/Service/UrlSafetyValidator.php b/lib/Service/UrlSafetyValidator.php index 21f4be994..00d2a74a1 100644 --- a/lib/Service/UrlSafetyValidator.php +++ b/lib/Service/UrlSafetyValidator.php @@ -108,6 +108,24 @@ public function isSafe(string $url): bool { * @spec openspec/changes/launchpad-legacy-quality-cleanup/tasks.md#task-1 */ public function checkAllowList(string $url, string $appId, string $configKey): bool { + $allowed = $this->configuredHosts(appId: $appId, configKey: $configKey); + if ($allowed === null) { + return true; + } + + return $this->hostIsListed(url: $url, allowed: $allowed); + }//end checkAllowList() + + /** + * The configured allow-list, or null when none is configured (an empty + * or blank value, invalid JSON or an empty array all mean "no list"). + * + * @param string $appId The app whose config key to read. + * @param string $configKey The IAppConfig key holding the JSON array. + * + * @return array<mixed>|null The decoded allow-list entries, or null. + */ + private function configuredHosts(string $appId, string $configKey): ?array { $raw = $this->appConfig->getValueString( app: $appId, key: $configKey, @@ -115,28 +133,40 @@ public function checkAllowList(string $url, string $appId, string $configKey): b ); if (trim(string: $raw) === '') { - return true; + return null; } $decoded = json_decode(json: $raw, associative: true); if (is_array(value: $decoded) === false || $decoded === []) { - return true; + return null; } + return $decoded; + }//end configuredHosts() + + /** + * Whether the URL's host is on the allow-list, case-insensitively. + * + * @param string $url The URL to check. + * @param array<mixed> $allowed The allow-list entries; non-strings never match. + * + * @return bool True when the host is listed; false for a URL without a host. + */ + private function hostIsListed(string $url, array $allowed): bool { $host = parse_url(url: $url, component: PHP_URL_HOST); if (is_string(value: $host) === false || $host === '') { return false; } $needle = strtolower(string: $host); - foreach ($decoded as $allowed) { - if (is_string(value: $allowed) === true - && strtolower(string: $allowed) === $needle + foreach ($allowed as $entry) { + if (is_string(value: $entry) === true + && strtolower(string: $entry) === $needle ) { return true; } } return false; - }//end checkAllowList() + }//end hostIsListed() }//end class diff --git a/lib/Service/UserAttributeResolver.php b/lib/Service/UserAttributeResolver.php index cd51984a6..8418e52c8 100644 --- a/lib/Service/UserAttributeResolver.php +++ b/lib/Service/UserAttributeResolver.php @@ -64,7 +64,7 @@ public function getUserAttributeValue( } return match ($attribute) { - 'locale' => $this->config->getUserValue( + 'language', 'locale' => $this->config->getUserValue( userId: $userId, appName: 'core', key: 'lang', diff --git a/lib/Service/UuidV4.php b/lib/Service/UuidV4.php new file mode 100644 index 000000000..400f00670 --- /dev/null +++ b/lib/Service/UuidV4.php @@ -0,0 +1,49 @@ +<?php + +/** + * UuidV4 + * + * Random (version 4) UUIDs for new dashboards, copies and keys. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Mints RFC 4122 version 4 UUIDs: 16 random bytes with the version nibble + * set to 4 and the variant bits to 10, rendered as lower-case hex in + * 8-4-4-4-12 groups. + * + * @spec openspec/specs/dashboards/spec.md + */ +final class UuidV4 { + /** + * Mint one UUID. + * + * @return string The UUID. + * + * @spec openspec/specs/dashboards/spec.md + */ + public static function generate(): string { + $data = random_bytes(length: 16); + $data[6] = chr(codepoint: ord(character: $data[6]) & 0x0f | 0x40); + $data[8] = chr(codepoint: ord(character: $data[8]) & 0x3f | 0x80); + + return vsprintf( + format: '%s%s-%s-%s-%s-%s%s%s', + values: str_split(string: bin2hex(string: $data), length: 4) + ); + }//end generate() +}//end class diff --git a/lib/Service/VersionStores.php b/lib/Service/VersionStores.php new file mode 100644 index 000000000..650e31a64 --- /dev/null +++ b/lib/Service/VersionStores.php @@ -0,0 +1,55 @@ +<?php + +/** + * VersionStores + * + * Where dashboard versions are stored: the version, dashboard and placement mappers and the + * database. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/dashboards/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\DashboardMapper; +use OCA\LaunchPad\Db\DashboardVersionMapper; +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCP\IDBConnection; + +/** + * Where dashboard versions are stored: the version, dashboard and placement mappers and the + * database. + * + * @spec openspec/specs/dashboards/spec.md + */ +class VersionStores { + /** + * Constructor. + * + * @param DashboardVersionMapper $versionMapper Version row mapper. + * @param DashboardMapper $dashboardMapper Dashboard row mapper. + * @param WidgetPlacementMapper $placementMapper Widget placement mapper (drives snapshot payload assembly). + * @param IDBConnection|null $db DB connection used to wrap restoreVersion in a transaction (WF1 fix). + * Nullable for backwards-compat with existing test doubles. + */ + public function __construct( + public readonly DashboardVersionMapper $versionMapper, + public readonly DashboardMapper $dashboardMapper, + public readonly WidgetPlacementMapper $placementMapper, + public readonly ?IDBConnection $db=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/Versions/SnapshotChangeDescriber.php b/lib/Service/Versions/SnapshotChangeDescriber.php new file mode 100644 index 000000000..74db3eb18 --- /dev/null +++ b/lib/Service/Versions/SnapshotChangeDescriber.php @@ -0,0 +1,369 @@ +<?php + +/** + * SnapshotChangeDescriber + * + * Compares two dashboard version snapshots and describes what changed + * between them in one short line, for the "What changed" column of the + * Versions tab (REQ-VERS-001). Snapshots have the shape built by + * {@see \OCA\LaunchPad\Service\DashboardVersionService}: + * `{"dashboard": {...}, "placements": [{...}, ...]}`. + * + * @category Service + * @package OCA\LaunchPad\Service\Versions + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\Versions; + +use OCP\IL10N; + +/** + * Describes the difference between two dashboard snapshots. + * + * @spec openspec/specs/dashboard-versioning/spec.md + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-each-automatic-version-says-what-changed-req-versui-004 + */ +class SnapshotChangeDescriber { + + /** + * Longest description returned, in characters. + * + * @var integer + */ + public const MAX_LENGTH = 120; + + /** + * Constructor + * + * @param IL10N|null $l10n The app's translations; null keeps the English source strings. + */ + public function __construct( + private readonly ?IL10N $l10n=null, + ) { + }//end __construct() + + /** + * Describe what changed from one snapshot to the next. + * + * The first change is named and the rest counted, for example + * "Widget Inbox added and 2 more changes". Widget changes are listed + * before the dashboard's own name and column changes. + * + * @param string|null $previousJson The older snapshot, or null when there is none. + * @param string $currentJson The newer snapshot. + * + * @return string|null One line of at most MAX_LENGTH characters, or null when + * there is no previous snapshot or nothing differs. + * + * @spec openspec/specs/dashboard-versioning/spec.md + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-each-automatic-version-says-what-changed-req-versui-004 + */ + public function describe(?string $previousJson, string $currentJson): ?string { + if ($previousJson === null) { + return null; + } + + $previous = $this->decode(json: $previousJson); + $current = $this->decode(json: $currentJson); + if ($previous === null || $current === null) { + return null; + } + + // Widget changes come first, then the dashboard's own name and + // columns: "Widget Inbox added and 2 more changes" when Inbox was + // added, Oud nieuws removed and the columns changed in one save. + $changes = array_merge( + $this->placementChanges( + previous: $this->placementsById(snapshot: $previous), + current: $this->placementsById(snapshot: $current) + ), + $this->dashboardChanges( + previous: $this->section(snapshot: $previous, key: 'dashboard'), + current: $this->section(snapshot: $current, key: 'dashboard') + ) + ); + + if ($changes === []) { + return null; + } + + $line = $changes[0]; + $more = (count($changes) - 1); + if ($more > 0) { + $line = $this->plural( + singular: '%s and %n more change', + plural: '%s and %n more changes', + count: $more, + parameters: [$changes[0]] + ); + } + + return $this->shorten(line: $line); + }//end describe() + + /** + * The changes to the dashboard itself: its name and its column count. + * + * @param array<string, mixed> $previous The older dashboard fields. + * @param array<string, mixed> $current The newer dashboard fields. + * + * @return list<string> The descriptions. + */ + private function dashboardChanges(array $previous, array $current): array { + $changes = []; + $oldName = $this->text(value: $previous['name'] ?? null); + $newName = $this->text(value: $current['name'] ?? null); + if ($oldName !== $newName && $newName !== '') { + $changes[] = $this->translate(text: 'Dashboard renamed to %s', parameters: [$newName]); + } + + $oldColumns = $this->text(value: $previous['gridColumns'] ?? null); + $newColumns = $this->text(value: $current['gridColumns'] ?? null); + if ($oldColumns !== $newColumns && $oldColumns !== '' && $newColumns !== '') { + $changes[] = $this->translate(text: 'Columns from %1$s to %2$s', parameters: [$oldColumns, $newColumns]); + } + + return $changes; + }//end dashboardChanges() + + /** + * The added, removed, renamed, moved and resized widgets, matched by placement id. + * + * @param array<string, array<string, mixed>> $previous The older placements by id. + * @param array<string, array<string, mixed>> $current The newer placements by id. + * + * @return list<string> The descriptions. + */ + private function placementChanges(array $previous, array $current): array { + $changes = []; + foreach ($current as $id => $placement) { + if (isset($previous[$id]) === false) { + $changes[] = $this->translate(text: 'Widget %s added', parameters: [$this->widgetName(placement: $placement)]); + } + } + + foreach ($previous as $id => $placement) { + if (isset($current[$id]) === false) { + $changes[] = $this->translate(text: 'Widget %s removed', parameters: [$this->widgetName(placement: $placement)]); + } + } + + foreach ($current as $id => $placement) { + if (isset($previous[$id]) === true) { + array_push($changes, ...$this->changedPlacement(before: $previous[$id], after: $placement)); + } + } + + return $changes; + }//end placementChanges() + + /** + * The changes to one placement present in both snapshots. + * + * @param array<string, mixed> $before The placement in the older snapshot. + * @param array<string, mixed> $after The placement in the newer snapshot. + * + * @return list<string> The descriptions. + */ + private function changedPlacement(array $before, array $after): array { + $changes = []; + $oldName = $this->widgetName(placement: $before); + $newName = $this->widgetName(placement: $after); + if ($oldName !== $newName) { + $changes[] = $this->translate(text: 'Widget %1$s renamed to %2$s', parameters: [$oldName, $newName]); + } + + if ($this->differs(before: $before, after: $after, fields: ['gridX', 'gridY']) === true) { + $changes[] = $this->translate(text: 'Widget %s moved', parameters: [$newName]); + } + + if ($this->differs(before: $before, after: $after, fields: ['gridWidth', 'gridHeight']) === true) { + $changes[] = $this->translate(text: 'Widget %s resized', parameters: [$newName]); + } + + return $changes; + }//end changedPlacement() + + /** + * Whether any of the given fields holds a different value. + * + * @param array<string, mixed> $before The older placement. + * @param array<string, mixed> $after The newer placement. + * @param list<string> $fields The fields to compare. + * + * @return boolean True when at least one field differs. + */ + private function differs(array $before, array $after, array $fields): bool { + foreach ($fields as $field) { + if ($this->text(value: $before[$field] ?? null) !== $this->text(value: $after[$field] ?? null)) { + return true; + } + } + + return false; + }//end differs() + + /** + * The name a placement shows: its custom title, else its content title, else its widget id. + * + * @param array<string, mixed> $placement The placement. + * + * @return string The name. + */ + private function widgetName(array $placement): string { + $customTitle = $this->text(value: $placement['customTitle'] ?? null); + if ($customTitle !== '') { + return $customTitle; + } + + $content = $placement['content'] ?? null; + if (is_array($content) === true) { + $contentTitle = $this->text(value: $content['title'] ?? null); + if ($contentTitle !== '') { + return $contentTitle; + } + } + + return $this->text(value: $placement['widgetId'] ?? null); + }//end widgetName() + + /** + * The placements of a snapshot keyed by their id; placements without one are skipped. + * + * @param array<string, mixed> $snapshot The decoded snapshot. + * + * @return array<string, array<string, mixed>> The placements by id. + */ + private function placementsById(array $snapshot): array { + $byId = []; + $placements = $snapshot['placements'] ?? []; + if (is_array($placements) === false) { + return $byId; + } + + foreach ($placements as $placement) { + if (is_array($placement) === false) { + continue; + } + + $id = $this->text(value: $placement['uuid'] ?? $placement['id'] ?? null); + if ($id !== '') { + $byId[$id] = $placement; + } + } + + return $byId; + }//end placementsById() + + /** + * One object-valued section of a snapshot, or an empty array. + * + * @param array<string, mixed> $snapshot The decoded snapshot. + * @param string $key The section key. + * + * @return array<string, mixed> The section. + */ + private function section(array $snapshot, string $key): array { + $section = $snapshot[$key] ?? []; + if (is_array($section) === false) { + return []; + } + + return $section; + }//end section() + + /** + * Decode a snapshot, or null when it is not a JSON object. + * + * @param string $json The snapshot JSON. + * + * @return array<string, mixed>|null The decoded snapshot. + */ + private function decode(string $json): ?array { + $decoded = json_decode($json, associative: true); + if (is_array($decoded) === false) { + return null; + } + + return $decoded; + }//end decode() + + /** + * A scalar as a trimmed string; anything else as the empty string. + * + * @param mixed $value The value. + * + * @return string The text. + */ + private function text(mixed $value): string { + if (is_scalar($value) === false) { + return ''; + } + + return trim((string)$value); + }//end text() + + /** + * Translate a source string with sprintf parameters. + * + * @param string $text The English source string. + * @param list<string> $parameters The values for its placeholders. + * + * @return string The translated text. + */ + private function translate(string $text, array $parameters): string { + if ($this->l10n !== null) { + return $this->l10n->t($text, $parameters); + } + + return vsprintf($text, $parameters); + }//end translate() + + /** + * Translate a counted source string, where `%n` stands for the count. + * + * @param string $singular The source string for a count of one. + * @param string $plural The source string for any other count. + * @param integer $count The count. + * @param list<string> $parameters The values for its other placeholders. + * + * @return string The translated text. + */ + private function plural(string $singular, string $plural, int $count, array $parameters): string { + if ($this->l10n !== null) { + return $this->l10n->n($singular, $plural, $count, $parameters); + } + + $text = $plural; + if ($count === 1) { + $text = $singular; + } + + return vsprintf(str_replace(search: '%n', replace: (string)$count, subject: $text), $parameters); + }//end plural() + + /** + * Cut a line to MAX_LENGTH characters, ending in an ellipsis when cut. + * + * @param string $line The line. + * + * @return string The line, at most MAX_LENGTH characters. + */ + private function shorten(string $line): string { + if (mb_strlen($line) <= self::MAX_LENGTH) { + return $line; + } + + return rtrim(mb_substr($line, 0, (self::MAX_LENGTH - 1))).'…'; + }//end shorten() +}//end class diff --git a/lib/Service/VideoContent.php b/lib/Service/VideoContent.php new file mode 100644 index 000000000..09d2d67bf --- /dev/null +++ b/lib/Service/VideoContent.php @@ -0,0 +1,73 @@ +<?php + +/** + * VideoContent + * + * The stored shape of a video widget's content blob. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Fills a video widget's playback defaults and keeps autoplay muted. + * + * @spec openspec/specs/video-widget/spec.md#req-vid-002-store-video-widget-configuration-per-placement + */ +final class VideoContent { + /** + * The widget id of a video placement. + */ + public const WIDGET_ID = 'video'; + + /** + * The playback fields a stored video placement always carries. + */ + private const DEFAULTS = [ + 'autoplay' => false, + 'muted' => true, + 'loop' => false, + 'controls' => true, + 'aspectRatio' => '16:9', + 'posterUrl' => null, + ]; + + /** + * The content to store for a placement of the given widget. + * + * Content of any other widget is returned unchanged. For a video, missing + * playback fields get their defaults and autoplay forces muted on, since + * browsers refuse to autoplay unmuted media. + * + * @param string $widgetId The placement's widget id. + * @param array<string, mixed> $content The content as submitted. + * + * @return array<string, mixed> The content to store. + * + * @spec openspec/specs/video-widget/spec.md#req-vid-008-respect-autoplay-muting-and-loop-settings + */ + public static function forWidget(string $widgetId, array $content): array { + if ($widgetId !== self::WIDGET_ID) { + return $content; + } + + $content += self::DEFAULTS; + if ($content['autoplay'] === true) { + $content['muted'] = true; + } + + return $content; + }//end forWidget() +}//end class diff --git a/lib/Service/VideoFileService.php b/lib/Service/VideoFileService.php new file mode 100644 index 000000000..305456afb --- /dev/null +++ b/lib/Service/VideoFileService.php @@ -0,0 +1,210 @@ +<?php + +/** + * VideoFileService + * + * Resolves the Nextcloud file of a `video` widget placement + * (`sourceType: 'nc-file'`) for the user viewing it (REQ-VID-006): a video + * the viewer can read gets a streaming address in the viewer's own WebDAV + * space; a deleted file, a non-video and a file the viewer cannot read are + * told apart, and none of them carries an address. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\Files\Config\IUserMountCache; +use OCP\Files\File; +use OCP\Files\IRootFolder; +use OCP\IURLGenerator; +use Throwable; + +/** + * The file behind a video placement, as the viewer may play it. + * + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-006-check-file-access-control-for-nextcloud-files + */ +class VideoFileService { + /** + * The file plays: the result carries `streamingUrl`. + */ + public const OK = 'ok'; + + /** + * The placement is no Nextcloud-file video. + */ + public const NO_FILE = 'no_file'; + + /** + * The file no longer exists (deleted, or only in a trash bin). + */ + public const NOT_FOUND = 'not_found'; + + /** + * The file exists but is not a video. + */ + public const NOT_VIDEO = 'not_video'; + + /** + * The file exists but the viewer cannot read it. + */ + public const NOT_ACCESSIBLE = 'not_accessible'; + + /** + * Constructor. + * + * @param IRootFolder $rootFolder The filesystem root. + * @param WidgetPlacementMapper $placements The placement store. + * @param IURLGenerator $urls Builds the WebDAV address. + * @param IUserMountCache $mounts Says whose storages hold a file id. + */ + public function __construct( + private readonly IRootFolder $rootFolder, + private readonly WidgetPlacementMapper $placements, + private readonly IURLGenerator $urls, + private readonly IUserMountCache $mounts, + ) { + }//end __construct() + + /** + * Resolve a placement's file for a viewer who may see the placement. + * + * @param string $viewerId The viewing user. + * @param int $placementId The placement. + * + * @return array{status: string, streamingUrl?: string} + * + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-006-check-file-access-control-for-nextcloud-files + */ + public function resolve(string $viewerId, int $placementId): array { + $fileId = $this->fileIdOf(placementId: $placementId); + if ($fileId === null) { + return ['status' => self::NO_FILE]; + } + + $node = $this->viewerNode(viewerId: $viewerId, fileId: $fileId); + if ($node === null) { + return ['status' => $this->absentStatus(fileId: $fileId)]; + } + + if ($node->isReadable() === false) { + return ['status' => self::NOT_ACCESSIBLE]; + } + + if (str_starts_with(haystack: $node->getMimetype(), needle: 'video/') === false) { + return ['status' => self::NOT_VIDEO]; + } + + return ['status' => self::OK, 'streamingUrl' => $this->streamingUrl(viewerId: $viewerId, node: $node)]; + }//end resolve() + + /** + * The file id of a Nextcloud-file video placement, or null. + * + * @param int $placementId The placement. + * + * @return int|null + */ + private function fileIdOf(int $placementId): ?int { + try { + $placement = $this->placements->find(id: $placementId); + } catch (DoesNotExistException) { + return null; + } + + $content = $placement->getContentArray(); + $fileId = ($content['fileId'] ?? null); + if ($placement->getWidgetId() !== 'video' + || ($content['sourceType'] ?? null) !== 'nc-file' + || is_numeric($fileId) === false + || (int)$fileId <= 0 + ) { + return null; + } + + return (int)$fileId; + }//end fileIdOf() + + /** + * The file as it appears in the viewer's own files, or null. + * + * @param string $viewerId The viewing user. + * @param int $fileId The file id. + * + * @return File|null + */ + private function viewerNode(string $viewerId, int $fileId): ?File { + try { + $node = $this->rootFolder->getUserFolder(userId: $viewerId)->getFirstNodeById(id: $fileId); + } catch (Throwable) { + return null; + } + + if ($node instanceof File) { + return $node; + } + + return null; + }//end viewerNode() + + /** + * Why a file is missing from the viewer's files: it lives in someone's + * files (not accessible), or nowhere but a trash bin or nowhere at all + * (not found). + * + * Asked per user whose storage holds the file id: a lookup from the + * filesystem root only sees storages already set up in this request, + * which another owner's never is. + * + * @param int $fileId The file id. + * + * @return string NOT_ACCESSIBLE or NOT_FOUND. + */ + private function absentStatus(int $fileId): string { + foreach ($this->mounts->getMountsForFileId(fileId: $fileId) as $mount) { + try { + $node = $this->rootFolder->getUserFolder(userId: $mount->getUser()->getUID())->getFirstNodeById(id: $fileId); + } catch (Throwable) { + $node = null; + } + + if ($node !== null) { + return self::NOT_ACCESSIBLE; + } + } + + return self::NOT_FOUND; + }//end absentStatus() + + /** + * The file's WebDAV address in the viewer's own space, which the + * viewer's session may read. + * + * @param string $viewerId The viewing user. + * @param File $node The file, as the viewer sees it. + * + * @return string + */ + private function streamingUrl(string $viewerId, File $node): string { + $relative = $this->rootFolder->getUserFolder(userId: $viewerId)->getRelativePath(path: $node->getPath()); + $segments = array_map( + callback: 'rawurlencode', + array: array_values(array_filter(explode(separator: '/', string: (string)$relative), static fn (string $segment): bool => $segment !== '')) + ); + + return $this->urls->getWebroot().'/remote.php/dav/files/'.rawurlencode($viewerId).'/'.implode(separator: '/', array: $segments); + }//end streamingUrl() +}//end class diff --git a/lib/Service/VideoParsingService.php b/lib/Service/VideoParsingService.php new file mode 100644 index 000000000..ca657bfde --- /dev/null +++ b/lib/Service/VideoParsingService.php @@ -0,0 +1,222 @@ +<?php + +/** + * VideoParsingService + * + * Parses a video URL a user typed into the video widget form (REQ-VID-003, + * REQ-VID-005): it checks that the input is an http(s) URL, recognises a + * YouTube, Vimeo or PeerTube address, extracts the video id and returns the + * canonical embed URL the widget stores. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * Turns a raw video URL into a source type, a video id and an embed URL. + * + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-005-parse-and-validate-video-urls-server-side + */ +class VideoParsingService { + /** + * The error for input that is not an http(s) URL. + */ + public const INVALID_URL = 'Invalid URL format'; + + /** + * The error for a URL that is no YouTube, Vimeo or PeerTube video. + */ + public const UNSUPPORTED = 'Unsupported video source'; + + /** + * Hosts that serve YouTube videos. + */ + private const YOUTUBE_HOSTS = [ + 'youtube.com', + 'www.youtube.com', + 'm.youtube.com', + 'youtube-nocookie.com', + 'www.youtube-nocookie.com', + ]; + + /** + * Parse a video URL. + * + * @param string $videoUrl The URL as typed. + * + * @return array{isValid: bool, error?: string, sourceType?: string, videoId?: string, canonicalUrl?: string} + * + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-005-parse-and-validate-video-urls-server-side + */ + public function parse(string $videoUrl): array { + $url = trim($videoUrl); + $parts = $this->urlParts(url: $url); + if ($parts === null) { + return ['isValid' => false, 'error' => self::INVALID_URL]; + } + + $parsed = ($this->parseYouTube(parts: $parts) ?? $this->parseVimeo(parts: $parts) ?? $this->parsePeerTube(parts: $parts)); + if ($parsed === null) { + return ['isValid' => false, 'error' => self::UNSUPPORTED]; + } + + return ['isValid' => true] + $parsed; + }//end parse() + + /** + * The host, path and query of an http(s) URL, or null for anything else. + * + * @param string $url The trimmed input. + * + * @return array{host: string, path: string, query: array<string, mixed>}|null + */ + private function urlParts(string $url): ?array { + if ($url === '' || filter_var($url, FILTER_VALIDATE_URL) === false) { + return null; + } + + $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME)); + $host = strtolower((string) parse_url($url, PHP_URL_HOST)); + if (in_array($scheme, ['http', 'https'], true) === false || $host === '') { + return null; + } + + $query = []; + parse_str((string) parse_url($url, PHP_URL_QUERY), $query); + + return [ + 'host' => $host, + 'path' => (string) parse_url($url, PHP_URL_PATH), + 'query' => $query, + ]; + }//end urlParts() + + /** + * A YouTube watch, short-link, shorts or embed URL, with a `t` offset + * kept as `?start=`. + * + * @param array{host: string, path: string, query: array<string, mixed>} $parts The URL parts. + * + * @return array{sourceType: string, videoId: string, canonicalUrl: string}|null + */ + private function parseYouTube(array $parts): ?array { + $videoId = null; + if ($parts['host'] === 'youtu.be') { + $videoId = explode('/', ltrim($parts['path'], '/'))[0]; + } else if (in_array($parts['host'], self::YOUTUBE_HOSTS, true) === true) { + $videoId = $this->youTubePathId(path: $parts['path'], query: $parts['query']); + } + + if ($videoId === null || preg_match('/^[A-Za-z0-9_-]+$/', $videoId) !== 1) { + return null; + } + + $canonical = 'https://www.youtube.com/embed/'.$videoId; + $start = $this->offsetSeconds(value: ($parts['query']['t'] ?? $parts['query']['start'] ?? null)); + if ($start > 0) { + $canonical .= '?start='.$start; + } + + return ['sourceType' => 'youtube', 'videoId' => $videoId, 'canonicalUrl' => $canonical]; + }//end parseYouTube() + + /** + * The video id in a youtube.com path or `v` query parameter. + * + * @param string $path The URL path. + * @param array<string, mixed> $query The query parameters. + * + * @return string|null + */ + private function youTubePathId(string $path, array $query): ?string { + if ($path === '/watch' && is_string($query['v'] ?? null) === true) { + return $query['v']; + } + + if (preg_match('#^/(?:embed|shorts|live)/([^/]+)#', $path, $match) === 1) { + return $match[1]; + } + + return null; + }//end youTubePathId() + + /** + * A vimeo.com or player.vimeo.com URL. + * + * @param array{host: string, path: string, query: array<string, mixed>} $parts The URL parts. + * + * @return array{sourceType: string, videoId: string, canonicalUrl: string}|null + */ + private function parseVimeo(array $parts): ?array { + $pattern = null; + if (in_array($parts['host'], ['vimeo.com', 'www.vimeo.com'], true) === true) { + $pattern = '#^/(\d+)/?$#'; + } else if ($parts['host'] === 'player.vimeo.com') { + $pattern = '#^/video/(\d+)/?$#'; + } + + if ($pattern === null || preg_match($pattern, $parts['path'], $match) !== 1) { + return null; + } + + return [ + 'sourceType' => 'vimeo', + 'videoId' => $match[1], + 'canonicalUrl' => 'https://player.vimeo.com/video/'.$match[1], + ]; + }//end parseVimeo() + + /** + * A PeerTube watch (`/w/<id>`, `/videos/watch/<id>`) or embed URL on any + * instance, rewritten to its embed form. + * + * @param array{host: string, path: string, query: array<string, mixed>} $parts The URL parts. + * + * @return array{sourceType: string, videoId: string, canonicalUrl: string}|null + */ + private function parsePeerTube(array $parts): ?array { + if (preg_match('#^/(?:w|videos/watch|videos/embed)/([A-Za-z0-9-]+)/?$#', $parts['path'], $match) !== 1) { + return null; + } + + return [ + 'sourceType' => 'peertube', + 'videoId' => $match[1], + 'canonicalUrl' => 'https://'.$parts['host'].'/videos/embed/'.$match[1], + ]; + }//end parsePeerTube() + + /** + * A YouTube time offset (`120`, `120s`, `2m`, `1h2m3s`) in seconds. + * + * @param mixed $value The `t` or `start` parameter. + * + * @return int The offset, 0 when absent or unreadable. + */ + private function offsetSeconds(mixed $value): int { + if (is_string($value) === false || $value === '') { + return 0; + } + + if (ctype_digit($value) === true) { + return (int) $value; + } + + if (preg_match('/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/', $value, $match) !== 1) { + return 0; + } + + return ((int) ($match[1] ?? 0) * 3600) + ((int) ($match[2] ?? 0) * 60) + (int) ($match[3] ?? 0); + }//end offsetSeconds() +}//end class diff --git a/lib/Service/ViewAsGuard.php b/lib/Service/ViewAsGuard.php new file mode 100644 index 000000000..5c176b66d --- /dev/null +++ b/lib/Service/ViewAsGuard.php @@ -0,0 +1,93 @@ +<?php + +/** + * ViewAsGuard + * + * Who may preview a widget's rules as another person ("View as" in the + * rules dialog, REQ-CVUI-006): someone who may edit that placement's rules + * (the dashboard owner or an administrator). Viewing as yourself, or as + * no one, is always allowed. A person who does not exist is in no group and + * has no profile values, so viewing as them shows nothing about anyone. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction Development Team <info@conduction.nl> + * @copyright 2026 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use Exception; + +/** + * Decides whether a caller may view a placement's rules as a person. + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ +class ViewAsGuard { + /** + * Refused: the caller may not edit the placement's rules. + */ + public const FORBIDDEN = 'You may not view this widget as another person'; + + /** + * Constructor + * + * @param PermissionService $permissionService Who may edit a placement's rules. + * @param string|null $userId The signed-in user. + */ + public function __construct( + private readonly PermissionService $permissionService, + private readonly ?string $userId, + ) { + }//end __construct() + + /** + * Why the signed-in user may not view as the person, or null when they may. + * + * @param string|null $subject The person to view as; null for no one. + * @param int|null $placementId The placement whose rules are edited. + * + * @return string|null `FORBIDDEN`, or null. + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + public function refusal(?string $subject, ?int $placementId): ?string { + if ($subject === null || $subject === $this->userId) { + return null; + } + + if ($this->userId === null || $placementId === null || $this->mayEditRules(placementId: $placementId) === false) { + return self::FORBIDDEN; + } + + return null; + }//end refusal() + + /** + * Whether the caller may edit the rules of a placement: its dashboard's + * owner or an administrator, the same check the rule endpoints make. + * + * @param int $placementId The placement. + * + * @return bool True when allowed. + */ + private function mayEditRules(int $placementId): bool { + try { + $this->permissionService->verifyPlacementOwnership(userId: (string)$this->userId, placementId: $placementId); + return true; + } catch (Exception $e) { + return false; + } + }//end mayEditRules() +}//end class diff --git a/lib/Service/VisibilityChecker.php b/lib/Service/VisibilityChecker.php index 64a6b6e8e..b4dd6b40b 100644 --- a/lib/Service/VisibilityChecker.php +++ b/lib/Service/VisibilityChecker.php @@ -18,11 +18,14 @@ namespace OCA\LaunchPad\Service; -use DateTimeInterface; +use Closure; use OCA\LaunchPad\Db\ConditionalRule; +use OCA\LaunchPad\Db\WidgetPlacement; /** * Service for checking widget visibility based on conditional rules. + * + * @spec openspec/specs/conditional-visibility/spec.md */ class VisibilityChecker { /** @@ -38,7 +41,8 @@ public function __construct( /** * Check rules to determine visibility. * - * Include rules use OR logic (at least one must match). + * Include rules use OR logic (at least one must match), or with + * `$match = 'all'` every include rule must match (REQ-VIS-014). * Exclude rules use AND logic (any match hides the widget). * * Thin boolean-only wrapper around {@see self::evaluateRuleSet()} — the @@ -48,15 +52,18 @@ public function __construct( * * @param ConditionalRule[] $rules The rules to check. * @param string $userId The user ID. + * @param string $match `any` (one include rule is enough) or `all`. * * @return bool Whether the widget should be visible. * * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-13 + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 */ - public function checkRules(array $rules, string $userId): bool { + public function checkRules(array $rules, string $userId, string $match = WidgetPlacement::RULE_MATCH_ANY): bool { return $this->evaluateRuleSet( rules: $rules, - userId: $userId + userId: $userId, + context: new RuleSetContext(options: ['match' => $match]) )['visible']; }//end checkRules() @@ -68,27 +75,50 @@ public function checkRules(array $rules, string $userId): bool { * {@see self::checkRules()} (both call this method — `checkRules()` just * discards the matched-id detail) so the preview path * (conditional-visibility-editor spec, REQ-CVUI-005) can never diverge - * from render-time visibility. `$groupsOverride` / `$nowOverride` are + * from render-time visibility. The context's groups and moment are * forwarded to {@see RuleEvaluatorService::evaluateRule()} and are only - * ever non-null when called from the preview controller. + * ever set by the preview; its match mode says whether all include rules + * must match (REQ-VIS-014). * - * @param ConditionalRule[] $rules The rules to check. - * @param string $userId The user ID. - * @param string[]|null $groupsOverride Preview-only group - * override. - * @param DateTimeInterface|null $nowOverride Preview-only clock - * override. + * @param ConditionalRule[] $rules The rules to check. + * @param string $userId The user ID. + * @param RuleSetContext|null $context Groups, moment and match mode; + * null for the user's own groups, + * now, and `any`. * * @return array{visible: bool, matchedIncludeRuleIds: int[], matchedExcludeRuleIds: int[]} * * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-005-preview-endpoint-reuses-the-render-time-evaluation-path-and-never-persists + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 */ - public function evaluateRuleSet( - array $rules, - string $userId, - ?array $groupsOverride = null, - ?DateTimeInterface $nowOverride = null, - ): array { + public function evaluateRuleSet(array $rules, string $userId, ?RuleSetContext $context = null): array { + $context ??= new RuleSetContext(); + $matches = fn (ConditionalRule $rule): bool => $this->ruleEvaluator->evaluateRule( + rule: $rule, + userId: $userId, + groupsOverride: $context->groups, + nowOverride: $context->now + ) === true; + + return $this->evaluateWith(rules: $rules, how: ['matches' => $matches, 'match' => $context->match]); + }//end evaluateRuleSet() + + /** + * Evaluate a rule set with a match predicate: include rules OR-ed, or + * all required with `$match = 'all'` (an empty include group passes), + * exclude rules AND-ed. + * + * @param ConditionalRule[] $rules The rules to evaluate. + * @param array{matches: Closure(ConditionalRule): bool, match: string} $how Whether one rule + * matches, and `any` + * or `all`. + * + * @return array{visible: bool, matchedIncludeRuleIds: int[], matchedExcludeRuleIds: int[]} + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + */ + private function evaluateWith(array $rules, array $how): array { + $matches = $how['matches']; $includeRules = $this->filterByType( rules: $rules, isInclude: true @@ -98,36 +128,45 @@ public function evaluateRuleSet( isInclude: false ); - $include = $this->evaluateGroup( - rules: $includeRules, - userId: $userId, - groupsOverride: $groupsOverride, - nowOverride: $nowOverride, - isIncludeGroup: true - ); - - if ($include['passed'] === false) { + // Include rules: an empty group passes, otherwise one match (OR) or, + // in `all` mode, every rule must match. + $includeIds = $this->matchingRuleIds(rules: $includeRules, matches: $matches); + if (count($includeIds) < self::neededMatches(includeCount: count($includeRules), match: $how['match'])) { return [ 'visible' => false, - 'matchedIncludeRuleIds' => $include['matchedIds'], + 'matchedIncludeRuleIds' => $includeIds, 'matchedExcludeRuleIds' => [], ]; } - $exclude = $this->evaluateGroup( - rules: $excludeRules, - userId: $userId, - groupsOverride: $groupsOverride, - nowOverride: $nowOverride, - isIncludeGroup: false - ); + // Exclude rules: any match hides the widget (AND). + $excludeIds = $this->matchingRuleIds(rules: $excludeRules, matches: $matches); return [ - 'visible' => $exclude['passed'], - 'matchedIncludeRuleIds' => $include['matchedIds'], - 'matchedExcludeRuleIds' => $exclude['matchedIds'], + 'visible' => $excludeIds === [], + 'matchedIncludeRuleIds' => $includeIds, + 'matchedExcludeRuleIds' => $excludeIds, ]; - }//end evaluateRuleSet() + }//end evaluateWith() + + /** + * How many include rules must match for the widget to show: none when + * there are no include rules, all of them in `all` mode, else one. + * + * @param int $includeCount The number of include rules. + * @param string $match `any` or `all`. + * + * @return int The number that must match. + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md#requirement-all-or-one-rule-must-match-req-vis-014 + */ + private static function neededMatches(int $includeCount, string $match): int { + if ($match === WidgetPlacement::RULE_MATCH_ALL) { + return $includeCount; + } + + return min($includeCount, 1); + }//end neededMatches() /** * Filter rules by include/exclude type. @@ -149,55 +188,23 @@ private function filterByType(array $rules, bool $isInclude): array { }//end filterByType() /** - * Evaluate one include/exclude group of rules, collecting the ids of - * every rule that matched. + * The ids of the rules that match, in rule order. Backs both + * `checkRules()` (via `evaluateRuleSet()`) and the preview path, so the + * include and exclude groups are evaluated in exactly one place. * - * Include group: passes when empty OR at least one rule matched (OR). - * Exclude group: passes when NO rule matched (AND — any match fails - * it). This single helper backs both `checkRules()` (via - * `evaluateRuleSet()`, which discards `matchedIds`) and the preview - * path, so the OR/AND semantics exist in exactly one place. + * @param ConditionalRule[] $rules The rules of one include or exclude group. + * @param callable $matches Whether one rule matches the user. * - * @param ConditionalRule[] $rules The rules in this group. - * @param string $userId The user ID. - * @param string[]|null $groupsOverride Preview-only group - * override. - * @param DateTimeInterface|null $nowOverride Preview-only clock - * override. - * @param bool $isIncludeGroup True for the include - * group, false for - * exclude. - * - * @return array{passed: bool, matchedIds: int[]} + * @return int[] The ids of the matching rules. */ - private function evaluateGroup( - array $rules, - string $userId, - ?array $groupsOverride, - ?DateTimeInterface $nowOverride, - bool $isIncludeGroup, - ): array { + private function matchingRuleIds(array $rules, callable $matches): array { $matchedIds = []; foreach ($rules as $rule) { - if ($this->ruleEvaluator->evaluateRule( - rule: $rule, - userId: $userId, - groupsOverride: $groupsOverride, - nowOverride: $nowOverride - ) === true - ) { + if ($matches($rule) === true) { $matchedIds[] = $rule->getId(); } } - $passed = empty($matchedIds) === true; - if ($isIncludeGroup === true) { - $passed = empty($rules) === true || empty($matchedIds) === false; - } - - return [ - 'passed' => $passed, - 'matchedIds' => $matchedIds, - ]; - }//end evaluateGroup() + return $matchedIds; + }//end matchingRuleIds() }//end class diff --git a/lib/Service/WeatherProviderCall.php b/lib/Service/WeatherProviderCall.php new file mode 100644 index 000000000..22cfe1e03 --- /dev/null +++ b/lib/Service/WeatherProviderCall.php @@ -0,0 +1,44 @@ +<?php + +/** + * WeatherProviderCall + * + * One call to the configured weather provider: the expanded URL and the + * query it was built for. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * One call to the configured weather provider. + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ +final class WeatherProviderCall { + /** + * Constructor. + * + * @param string $url The expanded provider URL. + * @param WeatherQuery $query The query the URL was built for. + */ + public function __construct( + public readonly string $url, + public readonly WeatherQuery $query, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/WeatherQuery.php b/lib/Service/WeatherQuery.php new file mode 100644 index 000000000..89f4aa305 --- /dev/null +++ b/lib/Service/WeatherQuery.php @@ -0,0 +1,45 @@ +<?php + +/** + * WeatherQuery + * + * The location, units and language one weather reading is resolved for. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/clock-weather-widgets/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The location, units and language one weather reading is resolved for. + * + * @spec openspec/specs/clock-weather-widgets/spec.md + */ +final class WeatherQuery { + /** + * Constructor. + * + * @param string $location The author-configured location, or `''`. + * @param string $units `metric` or `imperial`. + * @param string $language The resolved forecast language. + */ + public function __construct( + public readonly string $location, + public readonly string $units, + public readonly string $language, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/WeatherService.php b/lib/Service/WeatherService.php index 6a063f905..77c21d067 100644 --- a/lib/Service/WeatherService.php +++ b/lib/Service/WeatherService.php @@ -34,16 +34,11 @@ use DateTime; use OCA\LaunchPad\AppInfo\Application; -use OCA\LaunchPad\Db\WidgetPlacementMapper; +use OCA\LaunchPad\Kernel\Contracts\WeatherServiceInterface; use OCA\LaunchPad\Service\Connection\ConnectionReporter; -use OCP\App\IAppManager; -use OCP\Http\Client\IClientService; +use OCP\Http\Client\IResponse; use OCP\IAppConfig; use OCP\ICache; -use OCP\ICacheFactory; -use OCP\IConfig; -use Psr\Container\ContainerInterface; -use Psr\Log\LoggerInterface; use Throwable; /** @@ -59,7 +54,9 @@ * cache, the config and the l10n factory. The collaborators are the feature. * @spec openspec/specs/clock-weather-widgets/spec.md */ -class WeatherService { +class WeatherService implements WeatherServiceInterface { + use ReadsJsonCache; + use ReadsPlacementContent; /** * Default reading cache TTL in seconds (REQ-WEATHER-002). Overridden @@ -190,30 +187,18 @@ class WeatherService { /** * Constructor. * - * @param IAppManager $appManager Detects whether `weather_status` is enabled. - * @param ContainerInterface $container App container used to optionally resolve - * `weather_status`'s forecast service - * (REQ-WEATHER-002 provider reuse). - * @param IClientService $clientService HTTP client factory for the fallback provider fetch. - * @param ICacheFactory $cacheFactory Backing factory for the distributed reading cache. - * @param IAppConfig $appConfig Admin config: cache TTL, provider URL, API key. - * @param WidgetPlacementMapper $placementMapper Resolves placements by id. - * @param IConfig $config Reads the requesting user's locale/language and - * the system default. - * @param LoggerInterface $logger PSR logger. - * @param ConnectionReporter|null $connectionReporter Tells integriq what a provider reading met, or nothing when absent. + * @param ReadingSources $sources The app manager, container, HTTP client service and cache factory. + * @param WeatherSettings $settings The app and system config. + * @param WeatherStore $store The placement mapper and logger. + * @param ConnectionReporter|null $connectionReporter Tells integriq what a provider reading met, or + * nothing when absent. * * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md#requirement-req-lp-conn-003-launchpad-reports-what-its-outbound-calls-met */ public function __construct( - private readonly IAppManager $appManager, - private readonly ContainerInterface $container, - private readonly IClientService $clientService, - private readonly ICacheFactory $cacheFactory, - private readonly IAppConfig $appConfig, - private readonly WidgetPlacementMapper $placementMapper, - private readonly IConfig $config, - private readonly LoggerInterface $logger, + private readonly ReadingSources $sources, + private readonly WeatherSettings $settings, + private readonly WeatherStore $store, private readonly ?ConnectionReporter $connectionReporter = null, ) { }//end __construct() @@ -233,44 +218,79 @@ public function __construct( */ public function resolveForPlacement(int $placementId, string $userId): array { try { - $placement = $this->placementMapper->find(id: $placementId); + $placement = $this->store->placementMapper->find(id: $placementId); } catch (Throwable $exception) { return ['error' => 'placement_not_found']; } $config = $this->readPlacementConfig(placement: $placement); + + return $this->readingFor(query: $this->queryFor(config: $config, userId: $userId)); + }//end resolveForPlacement() + + /** + * Build the query for one placement config and viewer: the trimmed + * author location, the units and the forecast language. + * + * @param array<string,mixed> $config The placement config. + * @param string $userId The viewing user's UID. + * + * @return WeatherQuery The query. + */ + private function queryFor(array $config, string $userId): WeatherQuery { $location = trim(string: (string)($config['location'] ?? '')); $override = (string)($config['unitsOverride'] ?? ''); - $units = $this->resolveUnits(userId: $userId, override: $override); - $language = $this->resolveLanguage(userId: $userId); + return new WeatherQuery( + location: $location, + units: $this->resolveUnits(userId: $userId, override: $override), + language: $this->resolveLanguage(userId: $userId) + ); + }//end queryFor() - $cacheKey = $this->buildCacheKey(location: $location, units: $units, language: $language); + /** + * Serve the cached reading while it is fresh, otherwise fetch and + * cache a fresh one, falling back to the stale reading or the error + * shape when the upstream fails. + * + * @param WeatherQuery $query The query. + * + * @return array<string,mixed> The public reading or `{error: string}`. + */ + private function readingFor(WeatherQuery $query): array { + $cacheKey = $this->buildCacheKey(query: $query); $cache = $this->getCache(); $cached = $this->readCache(cache: $cache, cacheKey: $cacheKey); - if ($this->isCacheFresh(cached: $cached) === true) { return $this->publicShape(reading: $cached, stale: false); } - $fresh = $this->fetchFresh(location: $location, units: $units, language: $language); - if ($fresh !== null) { - $fresh['fetchedAtTs'] = time(); - if ($cache !== null) { - $cache->set(key: $cacheKey, value: json_encode($fresh), ttl: $this->cacheTtl()); - } - - return $this->publicShape(reading: $fresh, stale: false); + $fresh = $this->fetchFresh(query: $query); + if ($fresh === null) { + return $this->staleOrUnavailable(cached: $cached); } - if ($cached !== null) { - // Upstream failed but a previous reading exists — degrade - // gracefully rather than error (REQ-WEATHER-002). - return $this->publicShape(reading: $cached, stale: true); + $fresh['fetchedAtTs'] = time(); + $cache?->set(key: $cacheKey, value: json_encode($fresh), ttl: $this->cacheTtl()); + + return $this->publicShape(reading: $fresh, stale: false); + }//end readingFor() + + /** + * Answer when the upstream failed: a previous reading, flagged stale, + * degrades gracefully rather than error (REQ-WEATHER-002). + * + * @param array<string,mixed>|null $cached The cached reading, if any. + * + * @return array<string,mixed> The stale reading or `{error: 'weather_unavailable'}`. + */ + private function staleOrUnavailable(?array $cached): array { + if ($cached === null) { + return ['error' => 'weather_unavailable']; } - return ['error' => 'weather_unavailable']; - }//end resolveForPlacement() + return $this->publicShape(reading: $cached, stale: true); + }//end staleOrUnavailable() /** * Whether a cached reading exists and is still inside its TTL. @@ -299,51 +319,18 @@ private function isCacheFresh(?array $cached): bool { * personal location is preferred; otherwise the configured provider URL * is used. * - * @param string $location The author-configured location, or `''`. - * @param string $units `'metric'` or `'imperial'`. - * @param string $language The resolved forecast language. + * @param WeatherQuery $query The location (or `''`), units and language. * * @return array<string,mixed>|null The reading, or null when unavailable. */ - private function fetchFresh(string $location, string $units, string $language): ?array { - if ($location === '') { - return $this->fetchFromWeatherStatus(units: $units); + private function fetchFresh(WeatherQuery $query): ?array { + if ($query->location === '') { + return $this->fetchFromWeatherStatus(units: $query->units); } - return $this->fetchFromProviderUrl(location: $location, units: $units, language: $language); + return $this->fetchFromProviderUrl(query: $query); }//end fetchFresh() - /** - * Read the placement's `{location, unitsOverride}` config, falling - * back to the legacy `style_config.content` slot for pre-column rows - * (mirrors {@see \OCA\LaunchPad\Controller\FilesWidgetController::loadConfig()}). - * - * @param object $placement The {@see \OCA\LaunchPad\Db\WidgetPlacement} entity. - * - * @return array<string,mixed> - */ - private function readPlacementConfig(object $placement): array { - if (method_exists(object_or_class: $placement, method: 'getContentArray') === true) { - $content = $placement->getContentArray(); - if (is_array(value: $content) === true && $content !== []) { - return $content; - } - } - - if (method_exists(object_or_class: $placement, method: 'getStyleConfigArray') === true) { - $legacy = $placement->getStyleConfigArray(); - if (isset($legacy['content']) === true && is_array(value: $legacy['content']) === true) { - return $legacy['content']; - } - - if (is_array(value: $legacy) === true) { - return $legacy; - } - } - - return []; - }//end readPlacementConfig() - /** * Derive the units to use: the author's explicit override when set, * otherwise metric/imperial from the viewing user's Nextcloud locale @@ -359,9 +346,27 @@ private function resolveUnits(string $userId, string $override): string { return $override; } - $locale = (string)$this->config->getUserValue(userId: $userId, appName: 'core', key: 'locale', default: ''); + $territory = $this->localeTerritory(userId: $userId); + + if (in_array(needle: $territory, haystack: self::IMPERIAL_TERRITORIES, strict: true) === true) { + return 'imperial'; + } + + return 'metric'; + }//end resolveUnits() + + /** + * The upper-cased territory part of the viewing user's locale (the + * system default locale when the user has none), or `''`. + * + * @param string $userId The viewing user's UID. + * + * @return string The territory code, e.g. `US`. + */ + private function localeTerritory(string $userId): string { + $locale = (string)$this->settings->config->getUserValue(userId: $userId, appName: 'core', key: 'locale', default: ''); if ($locale === '') { - $locale = (string)$this->config->getSystemValue(key: 'default_locale', default: 'en'); + $locale = (string)$this->settings->config->getSystemValue(key: 'default_locale', default: 'en'); } $parts = preg_split(pattern: '/[_-]/', subject: $locale); @@ -369,14 +374,8 @@ private function resolveUnits(string $userId, string $override): string { $parts = []; } - $territory = strtoupper(string: (string)($parts[1] ?? '')); - - if (in_array(needle: $territory, haystack: self::IMPERIAL_TERRITORIES, strict: true) === true) { - return 'imperial'; - } - - return 'metric'; - }//end resolveUnits() + return strtoupper(string: (string)($parts[1] ?? '')); + }//end localeTerritory() /** * Derive the forecast language from the viewing user's Nextcloud @@ -388,9 +387,9 @@ private function resolveUnits(string $userId, string $override): string { * @return string A two-letter (or `xx_YY`) language code. */ private function resolveLanguage(string $userId): string { - $lang = (string)$this->config->getUserValue(userId: $userId, appName: 'core', key: 'lang', default: ''); + $lang = (string)$this->settings->config->getUserValue(userId: $userId, appName: 'core', key: 'lang', default: ''); if ($lang === '') { - $lang = (string)$this->config->getSystemValue(key: 'default_language', default: 'en'); + $lang = (string)$this->settings->config->getSystemValue(key: 'default_language', default: 'en'); } if ($lang !== '') { @@ -415,38 +414,106 @@ private function resolveLanguage(string $userId): string { */ private function fetchFromWeatherStatus(string $units): ?array { try { - if ($this->appManager->isEnabledForUser(appId: 'weather_status') === false) { - return null; - } - - if ($this->container->has(id: self::WEATHER_STATUS_SERVICE_CLASS) === false) { - return null; - } - - $service = $this->container->get(id: self::WEATHER_STATUS_SERVICE_CLASS); - if (method_exists(object_or_class: $service, method: 'getForecast') === false - || method_exists(object_or_class: $service, method: 'getLocation') === false - ) { - return null; - } - - $forecast = $service->getForecast(); - if (is_array(value: $forecast) === false || $forecast === [] || isset($forecast['error']) === true) { + $service = $this->weatherStatusService(); + $forecast = $this->usableForecastOf(service: $service); + if ($service === null || $forecast === null) { return null; } $locationInfo = $service->getLocation(); } catch (Throwable $exception) { - $this->logger->info( - message: 'WeatherService: weather_status provider unavailable, falling back', - context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] - ); + $this->logWeatherStatusFailure(exception: $exception); return null; - }//end try + } return $this->normaliseMetNoForecast(forecast: $forecast, locationInfo: $locationInfo, units: $units); }//end fetchFromWeatherStatus() + /** + * The weather_status forecast service, when the app is enabled, its + * service resolves and it offers both `getForecast()` and + * `getLocation()`. + * + * @return object|null The service, or null when it cannot be used. + */ + private function weatherStatusService(): ?object { + if ($this->sources->appManager->isEnabledForUser(appId: 'weather_status') === false) { + return null; + } + + if ($this->sources->container->has(id: self::WEATHER_STATUS_SERVICE_CLASS) === false) { + return null; + } + + $service = $this->sources->container->get(id: self::WEATHER_STATUS_SERVICE_CLASS); + if ($this->offersForecast(service: $service) === false) { + return null; + } + + return $service; + }//end weatherStatusService() + + /** + * Whether a resolved weather_status service offers both + * `getForecast()` and `getLocation()`. + * + * @param mixed $service The resolved service. + * + * @return bool True when both methods exist. + */ + private function offersForecast(mixed $service): bool { + return method_exists(object_or_class: $service, method: 'getForecast') === true + && method_exists(object_or_class: $service, method: 'getLocation') === true; + }//end offersForecast() + + /** + * The service's forecast when it is a non-empty list without an + * `error` key; null when there is no service or the answer is unusable. + * + * @param object|null $service The weather_status service, if usable. + * + * @return array<int|string,mixed>|null The forecast, or null. + */ + private function usableForecastOf(?object $service): ?array { + if ($service === null) { + return null; + } + + $forecast = $service->getForecast(); + if ($this->isUsableForecast(forecast: $forecast) === false) { + return null; + } + + return $forecast; + }//end usableForecastOf() + + /** + * Whether a weather_status forecast answer is a non-empty list without + * an `error` key. + * + * @param mixed $forecast The `getForecast()` answer. + * + * @return bool True when the forecast can be normalised. + */ + private function isUsableForecast(mixed $forecast): bool { + return is_array(value: $forecast) === true && $forecast !== [] && isset($forecast['error']) === false; + }//end isUsableForecast() + + /** + * Log that weather_status could not be used, so the provider path is + * tried next. + * + * @param Throwable $exception What went wrong. + * + * @return void + */ + private function logWeatherStatusFailure(Throwable $exception): void { + $this->store->logger->info( + message: 'WeatherService: weather_status provider unavailable, falling back', + context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] + ); + }//end logWeatherStatusFailure() + /** * Normalise met.no's compact-format timeseries (weather_status's * `getForecast()` return shape) into our reading shape, using the @@ -459,35 +526,16 @@ private function fetchFromWeatherStatus(string $units): ?array { * @return array<string,mixed>|null */ private function normaliseMetNoForecast(array $forecast, array $locationInfo, string $units): ?array { - $current = $forecast[0] ?? null; - if (is_array(value: $current) === false) { + $details = $this->metNoInstantDetails(current: ($forecast[0] ?? null)); + if ($details === null) { return null; } - $details = ($current['data']['instant']['details'] ?? null); - if (is_array(value: $details) === false || isset($details['air_temperature']) === false) { - return null; - } - - $tempC = (float)$details['air_temperature']; - $temp = $tempC; - if ($units === 'imperial') { - $temp = (($tempC * 9 / 5) + 32); - } - - $symbolCode = (string)( - $current['data']['next_1_hours']['summary']['symbol_code'] ?? $current['data']['next_6_hours']['summary']['symbol_code'] ?? '' - ); - $condition = $this->mapMetNoSymbol(symbolCode: $symbolCode); - - $label = (string)($locationInfo['address'] ?? ''); - if ($label === '') { - $label = 'Current location'; - } + $condition = $this->mapMetNoSymbol(symbolCode: $this->metNoSymbolCode(current: $forecast[0])); return [ - 'location' => $label, - 'tempValue' => $temp, + 'location' => $this->labelOr(label: (string)($locationInfo['address'] ?? ''), fallback: 'Current location'), + 'tempValue' => $this->celsiusIn(celsius: (float)$details['air_temperature'], units: $units), 'units' => $units, 'condition' => $condition, 'conditionText' => $this->humaniseCondition(code: $condition), @@ -500,6 +548,73 @@ private function normaliseMetNoForecast(array $forecast, array $locationInfo, st ]; }//end normaliseMetNoForecast() + /** + * The instant details of a met.no timeseries entry, when the entry is + * an array whose details carry an air temperature. + * + * @param mixed $current The timeseries entry. + * + * @return array<string,mixed>|null The details, or null when unusable. + */ + private function metNoInstantDetails(mixed $current): ?array { + if (is_array(value: $current) === false) { + return null; + } + + $details = ($current['data']['instant']['details'] ?? null); + if (is_array(value: $details) === false || isset($details['air_temperature']) === false) { + return null; + } + + return $details; + }//end metNoInstantDetails() + + /** + * The next-hour symbol code of a met.no timeseries entry, falling back + * to the next-six-hours one, then `''`. + * + * @param array<string,mixed> $current The timeseries entry. + * + * @return string The raw symbol code. + */ + private function metNoSymbolCode(array $current): string { + return (string)( + $current['data']['next_1_hours']['summary']['symbol_code'] ?? $current['data']['next_6_hours']['summary']['symbol_code'] ?? '' + ); + }//end metNoSymbolCode() + + /** + * A Celsius temperature in the requested units. + * + * @param float $celsius The temperature in Celsius. + * @param string $units `metric` or `imperial`. + * + * @return float Celsius, or Fahrenheit when `imperial`. + */ + private function celsiusIn(float $celsius, string $units): float { + if ($units === 'imperial') { + return (($celsius * 9 / 5) + 32); + } + + return $celsius; + }//end celsiusIn() + + /** + * A location label, or the fallback when it is empty. + * + * @param string $label The label the upstream gave. + * @param string $fallback The label to use when it gave none. + * + * @return string The label to show. + */ + private function labelOr(string $label, string $fallback): string { + if ($label === '') { + return $fallback; + } + + return $label; + }//end labelOr() + /** * Map a met.no `symbol_code` (e.g. `partlycloudy_day`) to our * normalised condition code, stripping the day/night/twilight suffix @@ -524,90 +639,174 @@ private function mapMetNoSymbol(string $symbolCode): string { * most once an hour while it stays the same (adopt-connection-registry). * The report never changes the reading. * - * @param string $location The author-configured location string. - * @param string $units `metric` or `imperial`. - * @param string $language The resolved forecast language. + * @param WeatherQuery $query The author-configured location, units and language. * * @return array<string,mixed>|null * * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md#requirement-req-lp-conn-003-launchpad-reports-what-its-outbound-calls-met */ - private function fetchFromProviderUrl(string $location, string $units, string $language): ?array { - $template = $this->appConfig->getValueString( - app: Application::APP_ID, - key: self::CONFIG_KEY_PROVIDER_URL, - default: '' - ); + private function fetchFromProviderUrl(WeatherQuery $query): ?array { + $url = $this->providerUrl(query: $query); + if ($url === null) { + return null; + } + + $response = $this->sendProviderRequest(url: $url); + if ($response === null) { + return null; + } + + return $this->readProviderResponse(response: $response, call: new WeatherProviderCall(url: $url, query: $query)); + }//end fetchFromProviderUrl() + + /** + * The provider URL for a query: the configured template with the + * location, API key, units and language filled in. Null, reported, + * when no template is configured or the URL is not http(s). + * + * @param WeatherQuery $query The query. + * + * @return string|null The URL, or null when there is none to call. + */ + private function providerUrl(WeatherQuery $query): ?string { + $template = $this->providerSetting(key: self::CONFIG_KEY_PROVIDER_URL); if ($template === '') { $this->connectionReporter?->reportWeatherNotConfigured(); return null; } - $apiKey = $this->appConfig->getValueString( + $url = $this->expandProviderTemplate(template: $template, query: $query); + if ($this->rejectsScheme(url: $url) === true) { + return null; + } + + return $url; + }//end providerUrl() + + /** + * Read one provider setting from the app config, `''` when unset. + * + * @param string $key The config key. + * + * @return string The value. + */ + private function providerSetting(string $key): string { + return $this->settings->appConfig->getValueString( app: Application::APP_ID, - key: self::CONFIG_KEY_PROVIDER_API_KEY, + key: $key, default: '' ); + }//end providerSetting() + + /** + * Fill the provider template's `{location}`, `{apiKey}`, `{units}` and + * `{lang}` placeholders. + * + * @param string $template The configured template. + * @param WeatherQuery $query The query. + * + * @return string The URL. + */ + private function expandProviderTemplate(string $template, WeatherQuery $query): string { + $apiKey = $this->providerSetting(key: self::CONFIG_KEY_PROVIDER_API_KEY); - $url = str_replace( + return str_replace( search: ['{location}', '{apiKey}', '{units}', '{lang}'], - replace: [rawurlencode(string: $location), rawurlencode(string: $apiKey), $units, $language], + replace: [rawurlencode(string: $query->location), rawurlencode(string: $apiKey), $query->units, $query->language], subject: $template ); + }//end expandProviderTemplate() + /** + * Whether a provider URL is refused for not being http(s); a refusal + * is logged and reported. + * + * @param string $url The expanded provider URL. + * + * @return bool True when the URL must not be called. + */ + private function rejectsScheme(string $url): bool { $scheme = strtolower(string: (string)parse_url(url: $url, component: PHP_URL_SCHEME)); - if (in_array(needle: $scheme, haystack: ['http', 'https'], strict: true) === false) { - $this->logger->warning( - message: 'WeatherService: provider URL has an invalid scheme, rejecting', - context: ['app' => Application::APP_ID] - ); - $this->connectionReporter?->reportWeatherInvalidUrl(); - return null; + if (in_array(needle: $scheme, haystack: ['http', 'https'], strict: true) === true) { + return false; } + $this->store->logger->warning( + message: 'WeatherService: provider URL has an invalid scheme, rejecting', + context: ['app' => Application::APP_ID] + ); + $this->connectionReporter?->reportWeatherInvalidUrl(); + + return true; + }//end rejectsScheme() + + /** + * Send the provider GET; a transport failure is logged, reported + * without a status and answered with null. + * + * @param string $url The provider URL. + * + * @return IResponse|null The response, or null when the call failed. + */ + private function sendProviderRequest(string $url): ?IResponse { try { - $client = $this->clientService->newClient(); - $response = $client->get( - uri: $url, - options: [ - 'connect_timeout' => self::CONNECT_TIMEOUT, - 'timeout' => self::REQUEST_TIMEOUT, - 'http_errors' => false, - // C5 (mirrors FeedRefreshService): no auto-redirect — a 3xx to - // an unexpected host would bypass the scheme check above. - 'allow_redirects' => false, - ] - ); + $client = $this->sources->clientService->newClient(); + return (new NoRedirectGet(connectTimeout: self::CONNECT_TIMEOUT, timeout: self::REQUEST_TIMEOUT)) + ->send(client: $client, url: $url); } catch (Throwable $exception) { - $this->logger->info( + $this->store->logger->info( message: 'WeatherService: provider fetch failed', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_WEATHER, url: $url, httpStatus: null); return null; } + }//end sendProviderRequest() + /** + * Turn a provider response into a reading, reporting what the call + * met: a non-2xx status, an unreadable body, or the successful call. + * + * @param IResponse $response The provider response. + * @param WeatherProviderCall $call The URL and query of the call. + * + * @return array<string,mixed>|null The reading, or null. + */ + private function readProviderResponse(IResponse $response, WeatherProviderCall $call): ?array { $status = (int)$response->getStatusCode(); if ($status < 200 || $status >= 300) { - $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_WEATHER, url: $url, httpStatus: $status); + $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_WEATHER, url: $call->url, httpStatus: $status); return null; } - $decoded = json_decode(json: (string)$response->getBody(), associative: true); - $reading = null; - if (is_array(value: $decoded) === true) { - $reading = $this->normaliseProviderPayload(payload: $decoded, location: $location, units: $units, language: $language); - } - + $reading = $this->readProviderBody(body: (string)$response->getBody(), query: $call->query); if ($reading === null) { - $this->connectionReporter?->reportWeatherUnreadable(url: $url); + $this->connectionReporter?->reportWeatherUnreadable(url: $call->url); return null; } - $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_WEATHER, url: $url, httpStatus: $status); + $this->connectionReporter?->reportCall(key: ConnectionReporter::KEY_WEATHER, url: $call->url, httpStatus: $status); return $reading; - }//end fetchFromProviderUrl() + }//end readProviderResponse() + + /** + * Decode a provider body and normalise it, null when it is not a JSON + * object or carries no usable temperature. + * + * @param string $body The response body. + * @param WeatherQuery $query The query. + * + * @return array<string,mixed>|null The reading, or null. + */ + private function readProviderBody(string $body, WeatherQuery $query): ?array { + $decoded = json_decode(json: $body, associative: true); + if (is_array(value: $decoded) === false) { + return null; + } + + return $this->normaliseProviderPayload(payload: $decoded, query: $query); + }//end readProviderBody() /** * Normalise an OpenWeatherMap-family JSON payload (the common default @@ -616,46 +815,83 @@ private function fetchFromProviderUrl(string $location, string $units, string $l * temperature field. * * @param array<string,mixed> $payload The decoded JSON body. - * @param string $location The configured location (label fallback). - * @param string $units `metric` or `imperial`. - * @param string $language The resolved forecast language. + * @param WeatherQuery $query The configured location (label fallback), units and language. * * @return array<string,mixed>|null */ - private function normaliseProviderPayload(array $payload, string $location, string $units, string $language): ?array { - $temp = ($payload['main']['temp'] ?? ($payload['temp'] ?? null)); - if (is_numeric(value: $temp) === false) { + private function normaliseProviderPayload(array $payload, WeatherQuery $query): ?array { + if (is_numeric(value: $this->providerTemperature(payload: $payload)) === false) { return null; } - $description = ''; - $condition = 'unknown'; + return $this->providerReading(payload: $payload, query: $query); + }//end normaliseProviderPayload() + + /** + * The temperature field of a provider payload: `main.temp`, else `temp`. + * + * @param array<string,mixed> $payload The decoded JSON body. + * + * @return mixed The raw temperature, or null. + */ + private function providerTemperature(array $payload): mixed { + return ($payload['main']['temp'] ?? ($payload['temp'] ?? null)); + }//end providerTemperature() + + /** + * Build the reading of a provider payload that carries a temperature. + * + * @param array<string,mixed> $payload The decoded JSON body. + * @param WeatherQuery $query The query. + * + * @return array<string,mixed> The reading. + */ + private function providerReading(array $payload, WeatherQuery $query): array { + $weather0 = $this->firstWeatherEntry(payload: $payload); + $condition = self::OWM_CONDITION_MAP[strtolower(string: (string)($weather0['main'] ?? ''))] ?? 'unknown'; + + return [ + 'location' => $this->labelOr(label: (string)($payload['name'] ?? ''), fallback: $query->location), + 'tempValue' => (float)$this->providerTemperature(payload: $payload), + 'units' => $query->units, + 'condition' => $condition, + 'conditionText' => $this->providerConditionText(description: (string)($weather0['description'] ?? ''), condition: $condition), + 'language' => $query->language, + ]; + }//end providerReading() + + /** + * The first `weather` entry of a provider payload, `[]` when it has none. + * + * @param array<string,mixed> $payload The decoded JSON body. + * + * @return array<string,mixed> The entry. + */ + private function firstWeatherEntry(array $payload): array { $weather0 = ($payload['weather'][0] ?? null); - if (is_array(value: $weather0) === true) { - $description = (string)($weather0['description'] ?? ''); - $main = strtolower(string: (string)($weather0['main'] ?? '')); - $condition = self::OWM_CONDITION_MAP[$main] ?? 'unknown'; + if (is_array(value: $weather0) === false) { + return []; } - $label = (string)($payload['name'] ?? ''); - if ($label === '') { - $label = $location; - } + return $weather0; + }//end firstWeatherEntry() - $conditionText = $this->humaniseCondition(code: $condition); + /** + * The provider's own description, sentence-cased, or the English + * fallback for the condition when it gave none. + * + * @param string $description The provider description, or `''`. + * @param string $condition The normalised condition code. + * + * @return string The condition text. + */ + private function providerConditionText(string $description, string $condition): string { if ($description !== '') { - $conditionText = ucfirst(string: $description); + return ucfirst(string: $description); } - return [ - 'location' => $label, - 'tempValue' => (float)$temp, - 'units' => $units, - 'condition' => $condition, - 'conditionText' => $conditionText, - 'language' => $language, - ]; - }//end normaliseProviderPayload() + return $this->humaniseCondition(code: $condition); + }//end providerConditionText() /** * Title-cased English fallback description for a condition code, used @@ -679,44 +915,14 @@ private function humaniseCondition(string $code): string { * REQ-WEATHER-002 ("cached ... for the same location + units + * language"). * - * @param string $location The configured (or resolved) location. - * @param string $units `metric` or `imperial`. - * @param string $language The resolved forecast language. + * @param WeatherQuery $query The configured (or resolved) location, units and language. * * @return string The cache key. */ - private function buildCacheKey(string $location, string $units, string $language): string { - return 'reading_' . hash(algo: 'sha256', data: strtolower(string: $location) . '|' . $units . '|' . $language); + private function buildCacheKey(WeatherQuery $query): string { + return 'reading_' . hash(algo: 'sha256', data: strtolower(string: $query->location) . '|' . $query->units . '|' . $query->language); }//end buildCacheKey() - /** - * Read + JSON-decode a cache entry. Returns `null` on a miss or a - * corrupt entry. - * - * @param ICache|null $cache The cache instance, or `null` when the cache - * subsystem is unavailable. - * @param string $cacheKey The cache key. - * - * @return array<string,mixed>|null - */ - private function readCache(?ICache $cache, string $cacheKey): ?array { - if ($cache === null) { - return null; - } - - $raw = $cache->get(key: $cacheKey); - if (is_string(value: $raw) === false) { - return null; - } - - $decoded = json_decode(json: $raw, associative: true); - if (is_array(value: $decoded) === true) { - return $decoded; - } - - return null; - }//end readCache() - /** * Shape an internal reading array (which also carries the internal * `fetchedAtTs` unix timestamp) into the public response contract @@ -756,9 +962,9 @@ private function getCache(): ?ICache { } try { - $this->cache = $this->cacheFactory->createDistributed(prefix: 'launchpad_weather_'); + $this->cache = $this->sources->cacheFactory->createDistributed(prefix: 'launchpad_weather_'); } catch (Throwable $exception) { - $this->logger->info( + $this->store->logger->info( message: 'WeatherService: cache subsystem unavailable, falling back to direct fetch', context: ['app' => Application::APP_ID, 'exception' => $exception->getMessage()] ); @@ -775,7 +981,7 @@ private function getCache(): ?ICache { * @return integer The TTL in seconds. */ private function cacheTtl(): int { - $ttl = $this->appConfig->getValueInt( + $ttl = $this->settings->appConfig->getValueInt( app: Application::APP_ID, key: self::CONFIG_KEY_CACHE_TTL, default: self::DEFAULT_CACHE_TTL diff --git a/lib/Service/WeatherSettings.php b/lib/Service/WeatherSettings.php new file mode 100644 index 000000000..8acb6c802 --- /dev/null +++ b/lib/Service/WeatherSettings.php @@ -0,0 +1,46 @@ +<?php + +/** + * WeatherSettings + * + * The app and system config of the weather service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\IAppConfig; +use OCP\IConfig; + +/** + * The app and system config of the weather service. + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ +class WeatherSettings { + /** + * Constructor. + * + * @param IAppConfig $appConfig Admin config: cache TTL, provider URL, API key. + * @param IConfig $config Reads the requesting user's locale/language and the system default. + */ + public function __construct( + public readonly IAppConfig $appConfig, + public readonly IConfig $config, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/WeatherStore.php b/lib/Service/WeatherStore.php new file mode 100644 index 000000000..32ab2a34c --- /dev/null +++ b/lib/Service/WeatherStore.php @@ -0,0 +1,46 @@ +<?php + +/** + * WeatherStore + * + * The placement mapper and the logger of the weather service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCA\LaunchPad\Db\WidgetPlacementMapper; +use Psr\Log\LoggerInterface; + +/** + * The placement mapper and the logger of the weather service. + * + * @spec openspec/changes/adopt-connection-registry/specs/app-connections/spec.md + */ +class WeatherStore { + /** + * Constructor. + * + * @param WidgetPlacementMapper $placementMapper Resolves placements by id. + * @param LoggerInterface $logger PSR logger. + */ + public function __construct( + public readonly WidgetPlacementMapper $placementMapper, + public readonly LoggerInterface $logger, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/WidgetPlatform.php b/lib/Service/WidgetPlatform.php new file mode 100644 index 000000000..3a368210d --- /dev/null +++ b/lib/Service/WidgetPlatform.php @@ -0,0 +1,48 @@ +<?php + +/** + * WidgetPlatform + * + * The dashboard widget manager and the session of the widget service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/widgets/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +use OCP\Dashboard\IManager; +use OCP\IUserSession; + +/** + * The dashboard widget manager and the session of the widget service. + * + * @spec openspec/specs/widgets/spec.md + */ +class WidgetPlatform { + /** + * Constructor. + * + * @param IManager $dashboardManager Dashboard manager interface. + * @param IUserSession $userSession User session interface. + * @param DashboardWidgetRegistry|null $registry The widgets without loading them, for the page's initial state. + */ + public function __construct( + public readonly IManager $dashboardManager, + public readonly IUserSession $userSession, + public readonly ?DashboardWidgetRegistry $registry=null, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/WidgetRendering.php b/lib/Service/WidgetRendering.php new file mode 100644 index 000000000..3267eb410 --- /dev/null +++ b/lib/Service/WidgetRendering.php @@ -0,0 +1,43 @@ +<?php + +/** + * WidgetRendering + * + * The widget formatter and the item loader of the widget service. + * + * @category Service + * @package OCA\LaunchPad\Service + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/widgets/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service; + +/** + * The widget formatter and the item loader of the widget service. + * + * @spec openspec/specs/widgets/spec.md + */ +class WidgetRendering { + /** + * Constructor. + * + * @param WidgetFormatter $widgetFormatter Widget formatter service. + * @param WidgetItemLoader $widgetItemLoader Widget item loader service. + */ + public function __construct( + public readonly WidgetFormatter $widgetFormatter, + public readonly WidgetItemLoader $widgetItemLoader, + ) { + }//end __construct() +}//end class diff --git a/lib/Service/WidgetService.php b/lib/Service/WidgetService.php index faf06f3be..99c7637d9 100644 --- a/lib/Service/WidgetService.php +++ b/lib/Service/WidgetService.php @@ -19,50 +19,98 @@ namespace OCA\LaunchPad\Service; use OCA\LaunchPad\Db\WidgetPlacement; -use OCP\Dashboard\IManager; -use OCP\IUserSession; +use OCA\LaunchPad\Exception\InvalidWidgetContentException; +use InvalidArgumentException; /** * Service for discovering and querying Nextcloud dashboard widgets. + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) One validator per widget type, each a small injected or inline class. */ class WidgetService { + + /** + * The content validator of each widget type that has one. + */ + private const CONTENT_VALIDATORS = [ + 'map' => MapContentValidator::class, + 'links' => LinksContentValidator::class, + 'quicklinks' => QuicklinksContentValidator::class, + 'text' => TextTableValidator::class, + ]; + /** * Constructor * - * @param IManager $dashboardManager Dashboard manager interface. + * @param WidgetPlatform $platform The widget manager and session. * @param PlacementService $placementService Placement service for CRUD. - * @param WidgetFormatter $widgetFormatter Widget formatter service. - * @param WidgetItemLoader $widgetItemLoader Widget item loader service. - * @param IUserSession $userSession User session interface. - * @param MenuService $menuService Validator for `menu` widgets (REQ-MENU-002). + * @param WidgetRendering $rendering The formatter and item loader. + * @param MenuService $menuService Validator for `menu` widgets (REQ-MENU-002). + * @param IframeService|null $iframeService Allow-list check for `iframe` widgets (REQ-IFRAME-002). + * @param HealthPingService|null $healthPing Checks a health-ping config against the allow-list (REQ-HPING-001). */ public function __construct( - private readonly IManager $dashboardManager, + private readonly WidgetPlatform $platform, private readonly PlacementService $placementService, - private readonly WidgetFormatter $widgetFormatter, - private readonly WidgetItemLoader $widgetItemLoader, - private readonly IUserSession $userSession, + private readonly WidgetRendering $rendering, private readonly MenuService $menuService = new MenuService(), + private readonly ?IframeService $iframeService = null, + private readonly ?HealthPingService $healthPing = null, ) { }//end __construct() /** * Validate the `content` blob of a widget placement before save. * - * REQ-MENU-002 server-side hook. Currently only the `menu` widget type - * has a server-side validator; any future widget that needs save-time - * validation should add its own branch here so the dispatcher stays - * single-responsibility. + * REQ-MENU-002 server-side hook. The `menu`, `map`, `links` and `text` + * widget types have a server-side validator; any future widget that + * needs save-time validation should add its own branch here so the + * dispatcher stays single-responsibility. A health-ping config is checked + * on every type, since any tile may carry one (REQ-HPING-001). * * @param string $widgetType Widget type identifier (e.g. `menu`). * @param array $content Widget content blob. * * @return void - * @throws \InvalidArgumentException When the content blob is invalid. + * @throws InvalidWidgetContentException When the content blob is invalid. * * @spec openspec/specs/widgets/spec.md */ public function validateWidgetContent(string $widgetType, array $content): void { + try { + $this->validateContentOfType(widgetType: $widgetType, content: $content); + } catch (\InvalidArgumentException $e) { + throw new InvalidWidgetContentException(message: $e->getMessage(), previous: $e); + } + }//end validateWidgetContent() + + /** + * Run the validator of a widget type over its content blob. + * + * @param string $widgetType Widget type identifier. + * @param array $content Widget content blob. + * + * @return void + * @throws \InvalidArgumentException When the content blob is invalid. + * + * @spec openspec/specs/widgets/spec.md + */ + private function validateContentOfType(string $widgetType, array $content): void { + $pingErrors = ($this->healthPing?->validateConfig(config: $content) ?? []); + if ($pingErrors !== []) { + throw new InvalidArgumentException(message: 'Invalid health check: ' . implode(separator: ', ', array: $pingErrors)); + } + + $validator = (self::CONTENT_VALIDATORS[$widgetType] ?? null); + if ($validator !== null) { + (new $validator())->validate(content: $content); + return; + } + + if ($widgetType === 'iframe') { + $this->validateIframeHost(content: $content); + return; + } + if ($widgetType !== 'menu') { return; } @@ -74,7 +122,30 @@ public function validateWidgetContent(string $widgetType, array $content): void $this->menuService->validateMenuConfig(content: $content); $this->menuService->validateMenuItems(items: $items); - }//end validateWidgetContent() + }//end validateContentOfType() + + /** + * Refuse an `iframe` placement whose URL host is not on the allow-list, + * naming the host (REQ-IFRAME-002 "rejected at save time"). + * + * @param array $content Widget content blob. + * + * @return void + * @throws \InvalidArgumentException When the host is not allow-listed. + * + * @spec openspec/specs/iframe-embed-widget/spec.md + */ + private function validateIframeHost(array $content): void { + $url = trim(string: (string)($content['url'] ?? '')); + if ($this->iframeService === null + || in_array(needle: 'host_not_allowed', haystack: $this->iframeService->validateConfig(config: $content), strict: true) === false + ) { + return; + } + + $host = (string)parse_url(url: $url, component: PHP_URL_HOST); + throw new InvalidArgumentException(message: sprintf('The host %s is not on the allow-list.', $host)); + }//end validateIframeHost() /** * Get all available widgets from Nextcloud. @@ -84,17 +155,44 @@ public function validateWidgetContent(string $widgetType, array $content): void * @spec openspec/changes/retrofit-2026-05-24-annotate-launchpad/tasks.md#task-32 */ public function getAvailableWidgets(): array { - $widgets = $this->dashboardManager->getWidgets(); - $result = []; + return $this->describe(widgets: $this->platform->dashboardManager->getWidgets()); + }//end getAvailableWidgets() + + /** + * The widgets getAvailableWidgets() describes, read without running any + * widget's `load()`, so the workspace page can carry them in its initial + * state without injecting every widget's scripts (REQ-RFP-010). + * + * @return array|null The widget descriptors, or null when the registry cannot be read that way. + * + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-010-initial-state-widget-allowlist + */ + public function getWidgetCatalogue(): ?array { + $widgets = $this->platform->registry?->widgetsWithoutLoading(); + if ($widgets === null) { + return null; + } + return $this->describe(widgets: $widgets); + }//end getWidgetCatalogue() + + /** + * The descriptors of the given widgets for the current user, in widget order. + * + * @param array $widgets The widgets. + * + * @return array The widget descriptors. + */ + private function describe(array $widgets): array { + $result = []; foreach ($widgets as $widget) { - $user = $this->userSession->getUser(); + $user = $this->platform->userSession->getUser(); $userId = ''; if ($user !== null) { $userId = $user->getUID(); } - $result[] = $this->widgetFormatter->format( + $result[] = $this->rendering->widgetFormatter->format( widget: $widget, userId: $userId ); @@ -108,7 +206,7 @@ public function getAvailableWidgets(): array { ); return $result; - }//end getAvailableWidgets() + }//end describe() /** * Get widget items for multiple widgets. @@ -126,9 +224,9 @@ public function getWidgetItems( array $widgetIds, int $limit = 7, ): array { - $widgets = $this->dashboardManager->getWidgets(); + $widgets = $this->platform->dashboardManager->getWidgets(); - return $this->widgetItemLoader->loadItems( + return $this->rendering->widgetItemLoader->loadItems( widgets: $widgets, userId: $userId, widgetIds: $widgetIds, @@ -141,41 +239,27 @@ public function getWidgetItems( * * @param int $dashboardId Dashboard ID. * @param string $widgetId Widget ID. - * @param int $gridX Grid X position. - * @param int $gridY Grid Y position. - * @param int $gridWidth Grid width. - * @param int $gridHeight Grid height. - * @param array|null $content Optional per-type content payload for - * registry-driven custom widgets. + * @param array $layout Grid position and size (`gridX`, `gridY`, + * `gridWidth`, `gridHeight`) and the optional + * per-type `content` payload for registry-driven + * custom widgets. * * @return WidgetPlacement The created widget placement. * * @spec openspec/specs/widgets/spec.md */ - public function addWidget( - int $dashboardId, - string $widgetId, - int $gridX = 0, - int $gridY = 0, - int $gridWidth = 4, - int $gridHeight = 4, - ?array $content = null, - ): WidgetPlacement { - if ($content !== null) { + public function addWidget(int $dashboardId, string $widgetId, array $layout=[]): WidgetPlacement { + if (isset($layout['content']) === true) { $this->validateWidgetContent( widgetType: $widgetId, - content: $content + content: $layout['content'] ); } return $this->placementService->addWidget( dashboardId: $dashboardId, widgetId: $widgetId, - gridX: $gridX, - gridY: $gridY, - gridWidth: $gridWidth, - gridHeight: $gridHeight, - content: $content + layout: $layout ); }//end addWidget() @@ -199,6 +283,20 @@ public function addTileFromArray( ); }//end addTileFromArray() + /** + * Import chosen bookmarks onto a dashboard as containers and tiles. + * + * @param int $dashboardId The dashboard. + * @param BookmarkImportPlan $plan What to create. + * + * @return list<WidgetPlacement> The created placements. + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ + public function importBookmarks(int $dashboardId, BookmarkImportPlan $plan): array { + return $this->placementService->importBookmarks(dashboardId: $dashboardId, plan: $plan); + }//end importBookmarks() + /** * Update a widget placement. * diff --git a/lib/Service/WorkPackages/WorkPackagesService.php b/lib/Service/WorkPackages/WorkPackagesService.php new file mode 100644 index 000000000..954f37980 --- /dev/null +++ b/lib/Service/WorkPackages/WorkPackagesService.php @@ -0,0 +1,314 @@ +<?php + +/** + * WorkPackagesService + * + * The OpenProject work packages of the work packages widget, read through the + * official Nextcloud OpenProject integration (`integration_openproject`). The + * integration holds the OpenProject address and each person's own OAuth or + * OIDC token; launchpad asks it for the work packages as the signed-in person + * and never sees a credential. A person's answer is kept for a minute. + * + * @category Service + * @package OCA\LaunchPad\Service\WorkPackages + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Service\WorkPackages; + +use OCP\App\IAppManager; +use OCP\IAppConfig; +use OCP\ICache; +use OCP\ICacheFactory; +use Psr\Container\ContainerInterface; +use Psr\Log\LoggerInterface; +use Throwable; + +/** + * Reads a person's open work packages from OpenProject. + */ +class WorkPackagesService { + /** + * The integration app. + * + * @var string + */ + public const INTEGRATION_APP = 'integration_openproject'; + + /** + * The integration's API service, looked up at runtime so launchpad works + * without the app. + * + * @var string + */ + private const API_SERVICE = 'OCA\\OpenProject\\Service\\OpenProjectAPIService'; + + /** + * The most work packages one read lists. + * + * @var int + */ + public const MAX_LIMIT = 25; + + /** + * How long a person's answer is kept, so a dashboard that opens again + * does not wait for OpenProject (one uncached read takes 1-1.5 s). + * + * @var int + */ + private const CACHE_SECONDS = 300; + + /** + * Constructor. + * + * @param IAppManager $appManager Whether the integration is enabled. + * @param IAppConfig $appConfig The integration's OpenProject address. + * @param ContainerInterface $container The integration's API service. + * @param LoggerInterface $logger Failures of the integration. + */ + public function __construct( + private readonly IAppManager $appManager, + private readonly IAppConfig $appConfig, + private readonly ContainerInterface $container, + private readonly LoggerInterface $logger, + ) { + }//end __construct() + + /** + * The open work packages for a person, due date first. + * + * `scope` `mine` lists the ones assigned to the person; `project` lists every + * open one of the project named by `project` (its identifier or id). + * + * @param string $userId The signed-in person. + * @param string $scope `mine` or `project`. + * @param string $project The project identifier for scope `project`. + * @param int $limit How many to list, 1 to {@see self::MAX_LIMIT}. + * + * @return array{state: string, workPackages: array<int, array<string, mixed>>, connectUrl?: string} + * `state` is `ok`, `not-installed`, `not-connected` (the person has not + * connected their OpenProject account) or `error`. + * + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-the-widget-lists-open-work-packages-due-date-first-req-wp-001 + */ + public function openWorkPackages(string $userId, string $scope, string $project, int $limit): array { + $cache = $this->cache(); + $key = $userId . '/' . $scope . '/' . $project . '/' . $limit; + $kept = $cache?->get($key); + if (is_array($kept) === true) { + return $kept; + } + + $answer = $this->readWorkPackages(userId: $userId, scope: $scope, project: $project, limit: $limit); + if ($answer['state'] === 'ok') { + $cache?->set($key, $answer, self::CACHE_SECONDS); + } + + return $answer; + }//end openWorkPackages() + + /** + * Read the open work packages from OpenProject, uncached. + * + * @param string $userId The signed-in person. + * @param string $scope `mine` or `project`. + * @param string $project The project identifier for scope `project`. + * @param int $limit How many to list. + * + * @return array{state: string, workPackages: array<int, array<string, mixed>>, connectUrl?: string} + */ + private function readWorkPackages(string $userId, string $scope, string $project, int $limit): array { + $service = $this->apiService(); + if ($service === null || is_callable([$service, 'getAccessToken']) === false || is_callable([$service, 'request']) === false) { + return ['state' => 'not-installed', 'workPackages' => []]; + } + + try { + if ((string)$service->getAccessToken($userId) === '') { + return self::notConnected(); + } + + $result = $service->request($userId, $this->endpoint(scope: $scope, project: $project), self::query(scope: $scope, limit: $limit)); + } catch (Throwable $exception) { + $this->logger->warning('OpenProject work packages could not be read: ' . $exception->getMessage(), ['app' => 'launchpad']); + return ['state' => 'error', 'workPackages' => []]; + } + + return $this->answer(result: $result); + }//end readWorkPackages() + + /** + * The cache of answers per person and query, or null without a cache. + * + * @return ICache|null + */ + private function cache(): ?ICache { + try { + return $this->container->get(ICacheFactory::class)->createDistributed(prefix: 'launchpad-work-packages'); + } catch (Throwable) { + return null; + } + }//end cache() + + /** + * The widget's answer for what the integration returned: the work + * packages, the not-connected state for a refused token, or an error. + * + * @param mixed $result What `request()` returned. + * + * @return array{state: string, workPackages: array<int, array<string, mixed>>, connectUrl?: string} + */ + private function answer(mixed $result): array { + if (is_array($result) === false) { + return ['state' => 'error', 'workPackages' => []]; + } + + if (isset($result['error']) === true) { + if ((int)($result['statusCode'] ?? 0) === 401) { + return self::notConnected(); + } + + return ['state' => 'error', 'workPackages' => []]; + } + + $elements = $result['_embedded']['elements'] ?? []; + $base = rtrim($this->appConfig->getValueString(app: self::INTEGRATION_APP, key: 'openproject_instance_url'), '/'); + + $workPackages = []; + foreach ((array)$elements as $element) { + if (is_array($element) === true && isset($element['id']) === true) { + $workPackages[] = self::workPackage(element: $element, base: $base); + } + } + + return ['state' => 'ok', 'workPackages' => $workPackages]; + }//end answer() + + /** + * The answer for a person who has not connected their OpenProject account. + * + * @return array{state: string, workPackages: array<int, mixed>, connectUrl: string} + */ + private static function notConnected(): array { + return ['state' => 'not-connected', 'workPackages' => [], 'connectUrl' => self::connectPath()]; + }//end notConnected() + + /** + * The integration's API service, or null when the app is not enabled for + * the signed-in person or its service cannot be built. + * + * @return object|null + */ + private function apiService(): ?object { + try { + if ($this->appManager->isEnabledForUser(appId: self::INTEGRATION_APP) === false) { + return null; + } + + if (class_exists(self::API_SERVICE) === false) { + return null; + } + + $service = $this->container->get(self::API_SERVICE); + if (is_object($service) === false) { + return null; + } + + return $service; + } catch (Throwable $exception) { + $this->logger->warning('The OpenProject integration could not be loaded: ' . $exception->getMessage(), ['app' => 'launchpad']); + return null; + } + }//end apiService() + + /** + * The OpenProject API path for the scope. + * + * @param string $scope `mine` or `project`. + * @param string $project The project identifier. + * + * @return string + */ + private function endpoint(string $scope, string $project): string { + $project = trim($project); + if ($scope === 'project' && $project !== '') { + return 'projects/' . rawurlencode($project) . '/work_packages'; + } + + return 'work_packages'; + }//end endpoint() + + /** + * The OpenProject query: open work packages, the person's own for scope + * `mine`, due date first. + * + * @param string $scope `mine` or `project`. + * @param int $limit How many. + * + * @return array<string, string|int> + * + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-the-widget-lists-open-work-packages-due-date-first-req-wp-001 + */ + public static function query(string $scope, int $limit): array { + $filters = [['status' => ['operator' => 'o', 'values' => []]]]; + if ($scope !== 'project') { + $filters[] = ['assignee' => ['operator' => '=', 'values' => ['me']]]; + } + + return [ + 'filters' => (string)json_encode($filters), + 'sortBy' => (string)json_encode([['dueDate', 'asc']]), + 'pageSize' => max(1, min(self::MAX_LIMIT, $limit)), + ]; + }//end query() + + /** + * One OpenProject work package as the widget shows it. + * + * @param array<string, mixed> $element The HAL element. + * @param string $base The OpenProject address. + * + * @return array{id: int, subject: string, status: string, project: string, assignee: string, dueDate: string, url: string} + * + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-the-widget-lists-open-work-packages-due-date-first-req-wp-001 + */ + public static function workPackage(array $element, string $base): array { + $links = $element['_links'] ?? []; + $title = static fn (string $key): string => (string)($links[$key]['title'] ?? ''); + $id = (int)$element['id']; + $url = ''; + if (preg_match('#^https?://#i', $base) === 1) { + $url = $base . '/work_packages/' . $id; + } + + return [ + 'id' => $id, + 'subject' => (string)($element['subject'] ?? ''), + 'status' => $title('status'), + 'project' => $title('project'), + 'assignee' => $title('assignee'), + 'dueDate' => (string)($element['dueDate'] ?? ''), + 'url' => $url, + ]; + }//end workPackage() + + /** + * Where a person connects their OpenProject account. + * + * @return string + */ + private static function connectPath(): string { + return '/settings/user/openproject'; + }//end connectPath() +}//end class diff --git a/lib/Settings/AdminFormState.php b/lib/Settings/AdminFormState.php new file mode 100644 index 000000000..4280c3e53 --- /dev/null +++ b/lib/Settings/AdminFormState.php @@ -0,0 +1,117 @@ +<?php + +/** + * AdminFormState + * + * The initial state of LaunchPad's admin settings page (REQ-INIT-002): every + * group, the configured group order (falling back to the legacy + * `configured_groups` setting, REQ-ASET-012), the available widgets, whether + * users may make their own dashboards and the file types a link can create, + * provided through {@see \OCA\LaunchPad\Service\InitialStateBuilder} so the + * page never renders with a partial payload. Kept apart from the settings + * class, which every administrator endpoint depends on. + * + * @spec openspec/specs/initial-state-contract/spec.md#requirement-versioned-key-set-per-page-req-init-002 + * + * @category Settings + * @package OCA\LaunchPad\Settings + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Settings; + +use OCA\LaunchPad\Service\AdminSettingsService; +use OCA\LaunchPad\Service\InitialState\Page; +use OCA\LaunchPad\Service\InitialStateBuilder; +use OCP\AppFramework\Services\IInitialState; +use OCP\IGroupManager; + +/** + * Provides the admin settings page's initial state. + * + * @spec openspec/specs/initial-state-contract/spec.md#requirement-versioned-key-set-per-page-req-init-002 + */ +class AdminFormState { + /** + * Constructor. + * + * @param IInitialState $initialState The Nextcloud initial-state service. + * @param IGroupManager $groupManager Group manager (full group list). + * @param AdminPageSources $sources The widget service, setting mapper, dashboard service and file service. + * @param AdminSettingsService $settingsService Admin-settings service exposing the `group_order` setting + * (REQ-ASET-012). + */ + public function __construct( + private readonly IInitialState $initialState, + private readonly IGroupManager $groupManager, + private readonly AdminPageSources $sources, + private readonly AdminSettingsService $settingsService, + ) { + }//end __construct() + + /** + * Provide the full admin initial-state contract. + * + * @return void + * + * @spec openspec/specs/initial-state-contract/spec.md#requirement-versioned-key-set-per-page-req-init-002 + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ + public function provide(): void { + $allGroups = []; + foreach ($this->groupManager->search(search: '') as $group) { + $allGroups[] = [ + 'id' => $group->getGID(), + 'displayName' => $group->getDisplayName(), + ]; + } + + // REQ-ASET-012: prefer the new `group_order` setting (defensive + // read returns []). Falls back to the legacy `configured_groups` + // key for installs that wrote it before the cutover so the + // initial render still shows the admin's previous selection. + $configuredGroups = $this->settingsService->getGroupOrder(); + if ($configuredGroups === []) { + $legacy = $this->sources->settingMapper->getValue( + key: 'configured_groups', + default: [] + ); + if (is_array($legacy) === true) { + $filtered = array_filter( + array: $legacy, + callback: static function ($entry) { + return is_string($entry) === true && $entry !== ''; + } + ); + $configuredGroups = array_values(array: $filtered); + } + } + + $allowUserDashboards = $this->sources->dashboardService->getAllowUserDashboards(); + + (new InitialStateBuilder( + initialState: $this->initialState, + page: Page::ADMIN + )) + ->setAllGroups($allGroups) + ->setConfiguredGroups($configuredGroups) + ->setWidgets($this->sources->widgetService->getAvailableWidgets()) + ->setAllowUserDashboards($allowUserDashboards) + ->setLinkCreateFileExtensions( + $this->sources->fileService->getAllowedExtensions() + ) + // The page renders in the Launchpad shell only for a (delegated) + // administrator, whose More menu then offers the admin entries. + ->setIsAdmin(true) + ->apply(); + }//end provide() +}//end class diff --git a/lib/Settings/AdminPageAccess.php b/lib/Settings/AdminPageAccess.php new file mode 100644 index 000000000..5a5797525 --- /dev/null +++ b/lib/Settings/AdminPageAccess.php @@ -0,0 +1,83 @@ +<?php + +/** + * AdminPageAccess + * + * Answers whether the signed-in user may open Launchpad's administration + * page: a Nextcloud administrator, or a user Nextcloud's admin delegation + * grants the Launchpad settings ({@see LaunchPadAdmin}). + * + * @category Settings + * @package OCA\LaunchPad\Settings + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Settings; + +use OCP\IGroupManager; +use OCP\IUserSession; +use OCP\Settings\IManager; + +/** + * The server-side check of the administration page. + * + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ +class AdminPageAccess { + /** + * Constructor. + * + * @param IUserSession $userSession The session of the request. + * @param IGroupManager $groupManager Answers whether a user is an administrator. + * @param IManager $settingsManager Answers which admin settings a delegated administrator holds. + * + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ + public function __construct( + private readonly IUserSession $userSession, + private readonly IGroupManager $groupManager, + private readonly IManager $settingsManager, + ) { + }//end __construct() + + /** + * Whether the signed-in user is an administrator or a delegated + * Launchpad administrator. + * + * @return bool True when the page may render. + * + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ + public function allows(): bool { + $user = $this->userSession->getUser(); + if ($user === null) { + return false; + } + + if ($this->groupManager->isAdmin(userId: $user->getUID()) === true) { + return true; + } + + $allowed = $this->settingsManager->getAllowedAdminSettings(section: 'launchpad', user: $user); + foreach ($allowed as $settings) { + foreach ($settings as $setting) { + if ($setting instanceof LaunchPadAdmin) { + return true; + } + } + } + + return false; + }//end allows() +}//end class diff --git a/lib/Settings/AdminPageSources.php b/lib/Settings/AdminPageSources.php new file mode 100644 index 000000000..1897933c7 --- /dev/null +++ b/lib/Settings/AdminPageSources.php @@ -0,0 +1,53 @@ +<?php + +/** + * AdminPageSources + * + * What the admin settings page reads: widgets, admin settings, dashboards and files. + * + * @category Settings + * @package OCA\LaunchPad\Settings + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/admin-settings/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Settings; + +use OCA\LaunchPad\Db\AdminSettingMapper; +use OCA\LaunchPad\Service\DashboardService; +use OCA\LaunchPad\Service\FileService; +use OCA\LaunchPad\Service\WidgetService; + +/** + * What the admin settings page reads: widgets, admin settings, dashboards and files. + * + * @spec openspec/specs/admin-settings/spec.md + */ +class AdminPageSources { + /** + * Constructor. + * + * @param WidgetService $widgetService Available-widgets descriptor formatter. + * @param AdminSettingMapper $settingMapper Admin settings store (legacy configured-groups list). + * @param DashboardService $dashboardService Dashboard service exposing the `allow_user_dashboards` flag + * (REQ-ASET-003). + * @param FileService $fileService link-button-widget extension allow-list reader. + */ + public function __construct( + public readonly WidgetService $widgetService, + public readonly AdminSettingMapper $settingMapper, + public readonly DashboardService $dashboardService, + public readonly FileService $fileService, + ) { + }//end __construct() +}//end class diff --git a/lib/Settings/LaunchPadAdmin.php b/lib/Settings/LaunchPadAdmin.php index 768bc6813..2cd58ef1a 100644 --- a/lib/Settings/LaunchPadAdmin.php +++ b/lib/Settings/LaunchPadAdmin.php @@ -3,11 +3,12 @@ /** * LaunchPadAdmin * - * Admin settings page for LaunchPad. Wires the typed admin initial-state - * contract via {@see \OCA\LaunchPad\Service\InitialStateBuilder} (REQ-INIT-001, - * REQ-INIT-002). Direct calls to - * {@see \OCP\AppFramework\Services\IInitialState::provideInitialState()} - * are forbidden here by the `lint:initial-state` CI guard. + * Launchpad's entry under Nextcloud's administration settings. The + * administration itself is a Launchpad page over the full width + * (`/apps/launchpad/admin/{tab}`, {@see \OCA\LaunchPad\Controller\AdminPageController}); + * this entry says so in one line and links to it (REQ-ADM-031). The class + * is still the setting Nextcloud's admin delegation grants, which the + * administrator endpoints name in `#[AuthorizedAdminSetting]`. * * @category Settings * @package OCA\LaunchPad\Settings @@ -26,115 +27,40 @@ namespace OCA\LaunchPad\Settings; use OCA\LaunchPad\AppInfo\Application; -use OCA\LaunchPad\Db\AdminSettingMapper; -use OCA\LaunchPad\Service\AdminSettingsService; -use OCA\LaunchPad\Service\DashboardService; -use OCA\LaunchPad\Service\FileService; -use OCA\LaunchPad\Service\InitialState\Page; -use OCA\LaunchPad\Service\InitialStateBuilder; -use OCA\LaunchPad\Service\WidgetService; use OCP\AppFramework\Http\TemplateResponse; -use OCP\AppFramework\Services\IInitialState; -use OCP\IGroupManager; +use OCP\IURLGenerator; use OCP\Settings\IDelegatedSettings; -use OCP\Util; class LaunchPadAdmin implements IDelegatedSettings { /** * Constructor. * - * @param IInitialState $initialState The Nextcloud initial-state service. - * @param IGroupManager $groupManager Group manager (full group list). - * @param WidgetService $widgetService Available-widgets descriptor formatter. - * @param AdminSettingMapper $settingMapper Admin settings store - * (legacy configured-groups list). - * @param AdminSettingsService $settingsService Admin-settings service exposing - * the `group_order` setting - * (REQ-ASET-012). - * @param DashboardService $dashboardService Dashboard service exposing - * the `allow_user_dashboards` - * flag (REQ-ASET-003). - * @param FileService $fileService link-button-widget extension - * allow-list reader. + * @param IURLGenerator $urlGenerator Builds the address of the administration page. + * + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-nextclouds-settings-point-to-the-page-req-adm-031 */ public function __construct( - private readonly IInitialState $initialState, - private readonly IGroupManager $groupManager, - private readonly WidgetService $widgetService, - private readonly AdminSettingMapper $settingMapper, - private readonly AdminSettingsService $settingsService, - private readonly DashboardService $dashboardService, - private readonly FileService $fileService, + private readonly IURLGenerator $urlGenerator, ) { }//end __construct() /** - * Get the admin settings form. - * - * Wires the full admin initial-state contract (REQ-INIT-002) before - * rendering the template — every required key is set on the builder - * so the page never renders with a partial payload. - * - * NOTE: Nextcloud admin-UI registration boilerplate; behaviour defined - * by the OCP\Settings\ISettings contract, not a LaunchPad spec. Intentionally - * left without an `@spec` tag (see - * `openspec/changes/archive/2026-05-03-spec-annotation-pass/design.md`). + * The settings entry: one line and a link to the administration page. * * @return TemplateResponse The template response. + * + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-nextclouds-settings-point-to-the-page-req-adm-031 */ public function getForm(): TemplateResponse { - Util::addScript( - application: Application::APP_ID, - file: 'launchpad-admin' - ); - - $allGroups = []; - foreach ($this->groupManager->search(search: '') as $group) { - $allGroups[] = [ - 'id' => $group->getGID(), - 'displayName' => $group->getDisplayName(), - ]; - } - - // REQ-ASET-012: prefer the new `group_order` setting (defensive - // read returns []). Falls back to the legacy `configured_groups` - // key for installs that wrote it before the cutover so the - // initial render still shows the admin's previous selection. - $configuredGroups = $this->settingsService->getGroupOrder(); - if ($configuredGroups === []) { - $legacy = $this->settingMapper->getValue( - key: 'configured_groups', - default: [] - ); - if (is_array($legacy) === true) { - $filtered = array_filter( - array: $legacy, - callback: static function ($entry) { - return is_string($entry) === true && $entry !== ''; - } - ); - $configuredGroups = array_values(array: $filtered); - } - } - - $allowUserDashboards = $this->dashboardService->getAllowUserDashboards(); - - (new InitialStateBuilder( - initialState: $this->initialState, - page: Page::ADMIN - )) - ->setAllGroups($allGroups) - ->setConfiguredGroups($configuredGroups) - ->setWidgets($this->widgetService->getAvailableWidgets()) - ->setAllowUserDashboards($allowUserDashboards) - ->setLinkCreateFileExtensions( - $this->fileService->getAllowedExtensions() - ) - ->apply(); - return new TemplateResponse( appName: Application::APP_ID, - templateName: 'settings/admin' + templateName: 'settings/admin', + params: [ + 'adminPageUrl' => $this->urlGenerator->linkToRoute( + routeName: Application::APP_ID . '.adminPage.show', + arguments: ['tab' => 'general'] + ), + ] ); }//end getForm() diff --git a/lib/Settings/connection-uses.json b/lib/Settings/connection-uses.json new file mode 100644 index 000000000..a57c2438d --- /dev/null +++ b/lib/Settings/connection-uses.json @@ -0,0 +1,16 @@ +{ + "_comment": [ + "Which widget types use which connection declared in connections.json (REQ-LP-CONN-005).", + "Kept apart from connections.json because integriq's schema refuses keys it does not know.", + "`uses` lists widget types; `healthPingTiles` marks the connection tiles with a health ping use.", + "The connections widget lists, once each, the connections the placements on its own dashboard use." + ], + "connections": { + "dashboard-registry": { "uses": [] }, + "weather": { "uses": ["weather"] }, + "news-feeds": { "uses": ["news"] }, + "ics-calendars": { "uses": ["calendar"] }, + "live-tiles": { "uses": ["livetile"] }, + "health-ping": { "uses": [], "healthPingTiles": true } + } +} diff --git a/lib/Settings/connections.json b/lib/Settings/connections.json index 647ee846a..f2bd6b82f 100644 --- a/lib/Settings/connections.json +++ b/lib/Settings/connections.json @@ -6,7 +6,7 @@ "title": "Dashboard registry", "description": "A registry of another instance, where you find and install dashboards other organisations published.", "order": 10, - "settingsUrl": "/settings/admin/launchpad?tab=sharing#section-dashboard-registry", + "settingsUrl": "/apps/launchpad/admin/sharing#section-dashboard-registry", "requiredConfig": ["registry_url"], "unconfiguredMessage": "No registry address is set. Set the registry URL on the Sharing tab of the LaunchPad settings." }, diff --git a/lib/Settings/launchpad_mock_register.json b/lib/Settings/launchpad_mock_register.json index 125bbe3e9..a9f58c73e 100644 --- a/lib/Settings/launchpad_mock_register.json +++ b/lib/Settings/launchpad_mock_register.json @@ -354,6 +354,684 @@ "isDefault": false, "type": "group_shared", "groupId": "Voorbeeld Groupid 3" + }, + { + "@self": { + "register": "launchpad", + "schema": "status_report", + "slug": "status-report-status-report-1-1" + }, + "date": "2026-03-01", + "subject": { + "register": "Voorbeeld Register 1", + "schema": "Voorbeeld Schema 1", + "title": "Voorbeeld Title 1", + "deadline": "2026-03-01", + "filters": {}, + "statusProperty": "Voorbeeld Statusproperty 1", + "closedValues": [ + "Voorbeeld Closedvalues 1" + ], + "dueProperty": "Voorbeeld Dueproperty 1" + }, + "health": "on-track", + "summary": "Voorbeeld Summary 1", + "figures": { + "total": 0, + "open": 0, + "closed": 0, + "overdue": 0, + "percentClosed": 0, + "daysToDeadline": 1 + }, + "provenance": { + "date": "computed", + "health": "computed", + "summary": "computed", + "figures": {} + }, + "author": "Voorbeeld Author 1", + "keptAt": "2026-03-01T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "status_report", + "slug": "status-report-status-report-2-2" + }, + "date": "2026-03-02", + "subject": { + "register": "Voorbeeld Register 2", + "schema": "Voorbeeld Schema 2", + "title": "Voorbeeld Title 2", + "deadline": "2026-03-02", + "filters": {}, + "statusProperty": "Voorbeeld Statusproperty 2", + "closedValues": [ + "Voorbeeld Closedvalues 2" + ], + "dueProperty": "Voorbeeld Dueproperty 2" + }, + "health": "at-risk", + "summary": "Voorbeeld Summary 2", + "figures": { + "total": 1, + "open": 1, + "closed": 1, + "overdue": 1, + "percentClosed": 1, + "daysToDeadline": 2 + }, + "provenance": { + "date": "written", + "health": "written", + "summary": "written", + "figures": {} + }, + "author": "Voorbeeld Author 2", + "keptAt": "2026-03-02T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "status_report", + "slug": "status-report-status-report-3-3" + }, + "date": "2026-03-03", + "subject": { + "register": "Voorbeeld Register 3", + "schema": "Voorbeeld Schema 3", + "title": "Voorbeeld Title 3", + "deadline": "2026-03-03", + "filters": {}, + "statusProperty": "Voorbeeld Statusproperty 3", + "closedValues": [ + "Voorbeeld Closedvalues 3" + ], + "dueProperty": "Voorbeeld Dueproperty 3" + }, + "health": "off-track", + "summary": "Voorbeeld Summary 3", + "figures": { + "total": 2, + "open": 2, + "closed": 2, + "overdue": 2, + "percentClosed": 2, + "daysToDeadline": 3 + }, + "provenance": { + "date": "computed", + "health": "computed", + "summary": "computed", + "figures": {} + }, + "author": "Voorbeeld Author 3", + "keptAt": "2026-03-03T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "filter_event", + "slug": "filter-event-filter-event-1-1" + }, + "dashboardId": "00000000-0000-4000-8000-000000000000", + "userId": "Voorbeeld Userid 1", + "eventType": "apply", + "filterDelta": [ + { + "dimension": "Voorbeeld Dimension 1", + "operator": "eq", + "source": "userExplicit", + "sourceWidgetId": "Voorbeeld Sourcewidgetid 1", + "pinned": false + } + ], + "timestamp": "2026-03-01T09:00:00+00:00", + "widgetId": "Voorbeeld Widgetid 1" + }, + { + "@self": { + "register": "launchpad", + "schema": "filter_event", + "slug": "filter-event-filter-event-2-2" + }, + "dashboardId": "00000000-0000-4000-8000-000000000001", + "userId": "Voorbeeld Userid 2", + "eventType": "reset", + "filterDelta": [ + { + "dimension": "Voorbeeld Dimension 2", + "operator": "in", + "source": "widgetClick", + "sourceWidgetId": "Voorbeeld Sourcewidgetid 2", + "pinned": false + } + ], + "timestamp": "2026-03-02T09:00:00+00:00", + "widgetId": "Voorbeeld Widgetid 2" + }, + { + "@self": { + "register": "launchpad", + "schema": "filter_event", + "slug": "filter-event-filter-event-3-3" + }, + "dashboardId": "00000000-0000-4000-8000-000000000002", + "userId": "Voorbeeld Userid 3", + "eventType": "bookmark", + "filterDelta": [ + { + "dimension": "Voorbeeld Dimension 3", + "operator": "between", + "source": "urlBootstrap", + "sourceWidgetId": "Voorbeeld Sourcewidgetid 3", + "pinned": false + } + ], + "timestamp": "2026-03-03T09:00:00+00:00", + "widgetId": "Voorbeeld Widgetid 3" + }, + { + "@self": { + "register": "launchpad", + "schema": "recipient", + "slug": "recipient-recipient-1-1" + }, + "channel": "email", + "enabled": true, + "filterContext": {}, + "channelConfig": {}, + "retryPolicy": { + "maxAttempts": 1, + "initialBackoffSeconds": 1, + "maxBackoffSeconds": 1, + "jitter": true + } + }, + { + "@self": { + "register": "launchpad", + "schema": "recipient", + "slug": "recipient-recipient-2-2" + }, + "channel": "nextcloudFiles", + "enabled": true, + "filterContext": {}, + "channelConfig": {}, + "retryPolicy": { + "maxAttempts": 2, + "initialBackoffSeconds": 2, + "maxBackoffSeconds": 2, + "jitter": false + } + }, + { + "@self": { + "register": "launchpad", + "schema": "recipient", + "slug": "recipient-recipient-3-3" + }, + "channel": "webhook", + "enabled": true, + "filterContext": {}, + "channelConfig": {}, + "retryPolicy": { + "maxAttempts": 3, + "initialBackoffSeconds": 3, + "maxBackoffSeconds": 3, + "jitter": true + } + }, + { + "@self": { + "register": "launchpad", + "schema": "render_target", + "slug": "render-target-render-target-1-1" + }, + "format": "pdf", + "formatOptions": {}, + "filenamePattern": "{name}-{date}.{ext}" + }, + { + "@self": { + "register": "launchpad", + "schema": "render_target", + "slug": "render-target-render-target-2-2" + }, + "format": "png", + "formatOptions": {}, + "filenamePattern": "{name}-{date}.{ext}" + }, + { + "@self": { + "register": "launchpad", + "schema": "render_target", + "slug": "render-target-render-target-3-3" + }, + "format": "csv", + "formatOptions": {}, + "filenamePattern": "{name}-{date}.{ext}" + }, + { + "@self": { + "register": "launchpad", + "schema": "scheduled_export", + "slug": "scheduled-export-voorbeeld-name-1-1" + }, + "name": "Voorbeeld Name 1", + "subjectType": "dashboard", + "subjectId": "00000000-0000-4000-8000-000000000000", + "recurrence": { + "type": "weekly", + "daysOfWeek": [ + "MO" + ], + "dayOfMonth": 1, + "lastDay": true, + "timeOfDay": "00:00", + "expression": "Voorbeeld Expression 1" + }, + "renderTargets": [ + { + "format": "pdf", + "formatOptions": {}, + "filenamePattern": "{name}-{date}.{ext}" + } + ], + "recipients": [ + { + "channel": "email", + "enabled": true, + "filterContext": {}, + "channelConfig": {}, + "retryPolicy": { + "maxAttempts": 1, + "initialBackoffSeconds": 1, + "maxBackoffSeconds": 1, + "jitter": true + } + } + ], + "description": "Voorbeeld Description 1", + "enabled": true, + "retention": { + "keepArtefactsForDays": 30, + "keepAuditForDays": 365 + }, + "runTimezone": "Voorbeeld Runtimezone 1", + "nextRunAt": "2026-03-01T09:00:00+00:00", + "lastRunAt": "2026-03-01T09:00:00+00:00", + "lastRunStatus": "success" + }, + { + "@self": { + "register": "launchpad", + "schema": "scheduled_export", + "slug": "scheduled-export-voorbeeld-name-2-2" + }, + "name": "Voorbeeld Name 2", + "subjectType": "widget", + "subjectId": "00000000-0000-4000-8000-000000000001", + "recurrence": { + "type": "monthly", + "daysOfWeek": [ + "TU" + ], + "dayOfMonth": 2, + "lastDay": false, + "timeOfDay": "11:11", + "expression": "Voorbeeld Expression 2" + }, + "renderTargets": [ + { + "format": "png", + "formatOptions": {}, + "filenamePattern": "{name}-{date}.{ext}" + } + ], + "recipients": [ + { + "channel": "nextcloudFiles", + "enabled": true, + "filterContext": {}, + "channelConfig": {}, + "retryPolicy": { + "maxAttempts": 2, + "initialBackoffSeconds": 2, + "maxBackoffSeconds": 2, + "jitter": false + } + } + ], + "description": "Voorbeeld Description 2", + "enabled": true, + "retention": { + "keepArtefactsForDays": 30, + "keepAuditForDays": 365 + }, + "runTimezone": "Voorbeeld Runtimezone 2", + "nextRunAt": "2026-03-02T09:00:00+00:00", + "lastRunAt": "2026-03-02T09:00:00+00:00", + "lastRunStatus": "partial" + }, + { + "@self": { + "register": "launchpad", + "schema": "scheduled_export", + "slug": "scheduled-export-voorbeeld-name-3-3" + }, + "name": "Voorbeeld Name 3", + "subjectType": "dashboard", + "subjectId": "00000000-0000-4000-8000-000000000002", + "recurrence": { + "type": "daily", + "daysOfWeek": [ + "WE" + ], + "dayOfMonth": 3, + "lastDay": true, + "timeOfDay": "02:22", + "expression": "Voorbeeld Expression 3" + }, + "renderTargets": [ + { + "format": "csv", + "formatOptions": {}, + "filenamePattern": "{name}-{date}.{ext}" + } + ], + "recipients": [ + { + "channel": "webhook", + "enabled": true, + "filterContext": {}, + "channelConfig": {}, + "retryPolicy": { + "maxAttempts": 3, + "initialBackoffSeconds": 3, + "maxBackoffSeconds": 3, + "jitter": true + } + } + ], + "description": "Voorbeeld Description 3", + "enabled": true, + "retention": { + "keepArtefactsForDays": 30, + "keepAuditForDays": 365 + }, + "runTimezone": "Voorbeeld Runtimezone 3", + "nextRunAt": "2026-03-03T09:00:00+00:00", + "lastRunAt": "2026-03-03T09:00:00+00:00", + "lastRunStatus": "failed" + }, + { + "@self": { + "register": "launchpad", + "schema": "scheduled_export_run", + "slug": "scheduled-export-run-scheduled-export-run-1-1" + }, + "exportId": "00000000-0000-4000-8000-000000000000", + "startedAt": "2026-03-01T09:00:00+00:00", + "status": "running", + "triggeredBy": "schedule", + "finishedAt": "2026-03-01T09:00:00+00:00", + "triggeredByUser": "Voorbeeld Triggeredbyuser 1", + "renderArtefacts": [ + { + "format": "pdf", + "sizeBytes": 0, + "sha256": "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789", + "storagePath": "Voorbeeld Storagepath 1", + "expiresAt": "2026-03-01T09:00:00+00:00" + } + ], + "deliveries": [ + { + "recipientId": "Voorbeeld Recipientid 1", + "channel": "email", + "attemptCount": 0, + "status": "pending", + "nextAttemptAt": "2026-03-01T09:00:00+00:00", + "deliveredAt": "2026-03-01T09:00:00+00:00", + "providerMessageId": "Voorbeeld Providermessageid 1", + "error": "Voorbeeld Error 1" + } + ], + "correlationId": "00000000-0000-4000-8000-000000000000" + }, + { + "@self": { + "register": "launchpad", + "schema": "scheduled_export_run", + "slug": "scheduled-export-run-scheduled-export-run-2-2" + }, + "exportId": "00000000-0000-4000-8000-000000000001", + "startedAt": "2026-03-02T09:00:00+00:00", + "status": "success", + "triggeredBy": "manual", + "finishedAt": "2026-03-02T09:00:00+00:00", + "triggeredByUser": "Voorbeeld Triggeredbyuser 2", + "renderArtefacts": [ + { + "format": "png", + "sizeBytes": 1, + "sha256": "bcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789a", + "storagePath": "Voorbeeld Storagepath 2", + "expiresAt": "2026-03-02T09:00:00+00:00" + } + ], + "deliveries": [ + { + "recipientId": "Voorbeeld Recipientid 2", + "channel": "nextcloudFiles", + "attemptCount": 1, + "status": "retrying", + "nextAttemptAt": "2026-03-02T09:00:00+00:00", + "deliveredAt": "2026-03-02T09:00:00+00:00", + "providerMessageId": "Voorbeeld Providermessageid 2", + "error": "Voorbeeld Error 2" + } + ], + "correlationId": "00000000-0000-4000-8000-000000000001" + }, + { + "@self": { + "register": "launchpad", + "schema": "scheduled_export_run", + "slug": "scheduled-export-run-scheduled-export-run-3-3" + }, + "exportId": "00000000-0000-4000-8000-000000000002", + "startedAt": "2026-03-03T09:00:00+00:00", + "status": "partial", + "triggeredBy": "schedule", + "finishedAt": "2026-03-03T09:00:00+00:00", + "triggeredByUser": "Voorbeeld Triggeredbyuser 3", + "renderArtefacts": [ + { + "format": "csv", + "sizeBytes": 2, + "sha256": "cdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789ab", + "storagePath": "Voorbeeld Storagepath 3", + "expiresAt": "2026-03-03T09:00:00+00:00" + } + ], + "deliveries": [ + { + "recipientId": "Voorbeeld Recipientid 3", + "channel": "webhook", + "attemptCount": 2, + "status": "success", + "nextAttemptAt": "2026-03-03T09:00:00+00:00", + "deliveredAt": "2026-03-03T09:00:00+00:00", + "providerMessageId": "Voorbeeld Providermessageid 3", + "error": "Voorbeeld Error 3" + } + ], + "correlationId": "00000000-0000-4000-8000-000000000002" + }, + { + "@self": { + "register": "launchpad", + "schema": "embed_token", + "slug": "embed-token-voorbeeld-name-1-1" + }, + "name": "Voorbeeld Name 1", + "tokenHash": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "subject": { + "type": "widget", + "id": "Voorbeeld Id 1", + "filterContext": {} + }, + "scope": { + "mode": "read", + "allowedFilters": [ + "Voorbeeld Allowedfilters 1" + ], + "allowedActions": [ + "interact" + ] + }, + "hostOrigins": [ + "Voorbeeld Hostorigins 1" + ], + "description": "Voorbeeld Description 1", + "tenantThemeId": "Voorbeeld Tenantthemeid 1", + "tokenExpiresAt": "2026-03-01T09:00:00+00:00", + "revokedAt": "2026-03-01T09:00:00+00:00", + "revocationReason": "compromised", + "revocationNotes": "Voorbeeld Revocationnotes 1", + "revokedBy": "Voorbeeld Revokedby 1", + "rateLimitPolicy": { + "requestsPerMinute": 1, + "burstSize": 1 + }, + "keyId": "Voorbeeld Keyid 1", + "createdBy": "Voorbeeld Createdby 1", + "createdAt": "2026-03-01T09:00:00+00:00", + "updatedAt": "2026-03-01T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "embed_token", + "slug": "embed-token-voorbeeld-name-2-2" + }, + "name": "Voorbeeld Name 2", + "tokenHash": "123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0", + "subject": { + "type": "dashboard", + "id": "Voorbeeld Id 2", + "filterContext": {} + }, + "scope": { + "mode": "read-with-interactions", + "allowedFilters": [ + "Voorbeeld Allowedfilters 2" + ], + "allowedActions": [ + "export" + ] + }, + "hostOrigins": [ + "Voorbeeld Hostorigins 2" + ], + "description": "Voorbeeld Description 2", + "tenantThemeId": "Voorbeeld Tenantthemeid 2", + "tokenExpiresAt": "2026-03-02T09:00:00+00:00", + "revokedAt": "2026-03-02T09:00:00+00:00", + "revocationReason": "no_longer_needed", + "revocationNotes": "Voorbeeld Revocationnotes 2", + "revokedBy": "Voorbeeld Revokedby 2", + "rateLimitPolicy": { + "requestsPerMinute": 2, + "burstSize": 2 + }, + "keyId": "Voorbeeld Keyid 2", + "createdBy": "Voorbeeld Createdby 2", + "createdAt": "2026-03-02T09:00:00+00:00", + "updatedAt": "2026-03-02T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "embed_token", + "slug": "embed-token-voorbeeld-name-3-3" + }, + "name": "Voorbeeld Name 3", + "tokenHash": "23456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef01", + "subject": { + "type": "widget", + "id": "Voorbeeld Id 3", + "filterContext": {} + }, + "scope": { + "mode": "read", + "allowedFilters": [ + "Voorbeeld Allowedfilters 3" + ], + "allowedActions": [ + "drillDown" + ] + }, + "hostOrigins": [ + "Voorbeeld Hostorigins 3" + ], + "description": "Voorbeeld Description 3", + "tenantThemeId": "Voorbeeld Tenantthemeid 3", + "tokenExpiresAt": "2026-03-03T09:00:00+00:00", + "revokedAt": "2026-03-03T09:00:00+00:00", + "revocationReason": "host_decommissioned", + "revocationNotes": "Voorbeeld Revocationnotes 3", + "revokedBy": "Voorbeeld Revokedby 3", + "rateLimitPolicy": { + "requestsPerMinute": 3, + "burstSize": 3 + }, + "keyId": "Voorbeeld Keyid 3", + "createdBy": "Voorbeeld Createdby 3", + "createdAt": "2026-03-03T09:00:00+00:00", + "updatedAt": "2026-03-03T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "tenant_theme", + "slug": "tenant-theme-voorbeeld-name-1-1" + }, + "name": "Voorbeeld Name 1", + "cssVariables": {}, + "logoUrl": "https://example.invalid/resource/0", + "customCss": "Voorbeeld Customcss 1", + "createdBy": "Voorbeeld Createdby 1", + "createdAt": "2026-03-01T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "tenant_theme", + "slug": "tenant-theme-voorbeeld-name-2-2" + }, + "name": "Voorbeeld Name 2", + "cssVariables": {}, + "logoUrl": "https://example.invalid/resource/1", + "customCss": "Voorbeeld Customcss 2", + "createdBy": "Voorbeeld Createdby 2", + "createdAt": "2026-03-02T09:00:00+00:00" + }, + { + "@self": { + "register": "launchpad", + "schema": "tenant_theme", + "slug": "tenant-theme-voorbeeld-name-3-3" + }, + "name": "Voorbeeld Name 3", + "cssVariables": {}, + "logoUrl": "https://example.invalid/resource/2", + "customCss": "Voorbeeld Customcss 3", + "createdBy": "Voorbeeld Createdby 3", + "createdAt": "2026-03-03T09:00:00+00:00" } ] } diff --git a/lib/Settings/launchpad_register.json b/lib/Settings/launchpad_register.json index b776190d3..a03346e1e 100644 --- a/lib/Settings/launchpad_register.json +++ b/lib/Settings/launchpad_register.json @@ -20,7 +20,7 @@ "version": "1.0.1", "description": "LaunchPad dashboards stored as OpenRegister objects. They are the source of the v2 runtime manifest.", "published": true, - "schemas": ["dashboard"], + "schemas": ["dashboard", "scheduled_export", "render_target", "recipient", "scheduled_export_run"], "folder": "LaunchPad" } }, @@ -305,6 +305,519 @@ "isDefault": false } ] + }, + "scheduled_export": { + "slug": "scheduled_export", + "icon": "CalendarClock", + "version": "1.0.0", + "title": "Scheduled export", + "description": "A dashboard or widget rendered on a schedule and delivered to recipients.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": true, + "mailEnabled": false + }, + "required": [ + "name", + "subjectType", + "subjectId", + "recurrence", + "renderTargets", + "recipients" + ], + "properties": { + "name": { + "type": "string", + "title": "Name", + "maxLength": 255 + }, + "description": { + "type": "string", + "title": "Description", + "description": "Markdown, shown in the email body and on the PDF cover page." + }, + "subjectType": { + "type": "string", + "enum": [ + "dashboard", + "widget" + ], + "title": "Subject type" + }, + "subjectId": { + "type": "string", + "format": "uuid", + "title": "Subject" + }, + "enabled": { + "type": "boolean", + "default": true, + "title": "Enabled" + }, + "recurrence": { + "type": "object", + "title": "Recurrence", + "description": "Discriminated on type: weekly (daysOfWeek as MO..SU, timeOfDay HH:MM), monthly (dayOfMonth 1-31, clamped to the month's last day, or lastDay true; timeOfDay), daily (timeOfDay) or cron (expression, five fields).", + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "weekly", + "monthly", + "daily", + "cron" + ] + }, + "daysOfWeek": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "MO", + "TU", + "WE", + "TH", + "FR", + "SA", + "SU" + ] + } + }, + "dayOfMonth": { + "type": "integer", + "minimum": 1, + "maximum": 31 + }, + "lastDay": { + "type": "boolean" + }, + "timeOfDay": { + "type": "string", + "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$" + }, + "expression": { + "type": "string" + } + } + }, + "renderTargets": { + "type": "array", + "minItems": 1, + "title": "Render targets", + "items": { + "type": "object", + "properties": { + "format": { + "type": "string", + "enum": [ + "pdf", + "png", + "csv", + "xlsx" + ], + "title": "Format" + }, + "formatOptions": { + "type": "object", + "title": "Format options", + "description": "PDF: pageSize, orientation, header, footer. PNG: width, height, dpi. CSV: delimiter, quoteChar. XLSX: sheetPerWidget." + }, + "filenamePattern": { + "type": "string", + "title": "File name pattern", + "description": "Template with {name}, {date}, {recipient} and {ext}.", + "default": "{name}-{date}.{ext}" + } + }, + "required": [ + "format" + ] + } + }, + "recipients": { + "type": "array", + "minItems": 1, + "title": "Recipients", + "items": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true, + "title": "Enabled" + }, + "channel": { + "type": "string", + "enum": [ + "email", + "nextcloudFiles", + "webhook", + "sftp" + ], + "title": "Channel" + }, + "filterContext": { + "type": "object", + "title": "Filter context", + "description": "Filters pinned for this recipient, in the shape of the cross-widget filter bus, for example {gemeenteCode: GM0355}." + }, + "channelConfig": { + "type": "object", + "title": "Channel configuration", + "description": "Channel-specific settings (addresses, folder, URL, host). Credentials and signing secrets are held by reference to the credential vault, never inline." + }, + "retryPolicy": { + "type": "object", + "title": "Retry policy", + "description": "Overrides the default retry policy {maxAttempts: 5, initialBackoffSeconds: 60, maxBackoffSeconds: 3600, jitter: true}.", + "properties": { + "maxAttempts": { + "type": "integer", + "minimum": 1, + "maximum": 20 + }, + "initialBackoffSeconds": { + "type": "integer", + "minimum": 1 + }, + "maxBackoffSeconds": { + "type": "integer", + "minimum": 1 + }, + "jitter": { + "type": "boolean" + } + } + } + }, + "required": [ + "channel" + ] + } + }, + "retention": { + "type": "object", + "title": "Retention", + "properties": { + "keepArtefactsForDays": { + "type": "integer", + "minimum": 1, + "default": 30, + "description": "Null keeps rendered files forever." + }, + "keepAuditForDays": { + "type": "integer", + "minimum": 1, + "default": 365, + "description": "Null keeps run records forever." + } + } + }, + "runTimezone": { + "type": "string", + "title": "Time zone", + "description": "IANA time zone the recurrence is evaluated in, for example Europe/Amsterdam." + }, + "nextRunAt": { + "type": "string", + "format": "date-time", + "title": "Next run", + "readOnly": true + }, + "lastRunAt": { + "type": "string", + "format": "date-time", + "title": "Last run", + "readOnly": true + }, + "lastRunStatus": { + "type": "string", + "enum": [ + "success", + "partial", + "failed", + "running" + ], + "title": "Last run status", + "readOnly": true + }, + "createdBy": { + "type": "string", + "title": "Created by", + "description": "The user the export renders and delivers as. Set by the app when the export is made.", + "readOnly": true + } + } + }, + "render_target": { + "slug": "render_target", + "icon": "FileExportOutline", + "version": "1.0.0", + "title": "Render target", + "description": "One output format of a scheduled export, with its format options and file name pattern.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": false, + "mailEnabled": false + }, + "required": [ + "format" + ], + "properties": { + "format": { + "type": "string", + "enum": [ + "pdf", + "png", + "csv", + "xlsx" + ], + "title": "Format" + }, + "formatOptions": { + "type": "object", + "title": "Format options", + "description": "PDF: pageSize, orientation, header, footer. PNG: width, height, dpi. CSV: delimiter, quoteChar. XLSX: sheetPerWidget." + }, + "filenamePattern": { + "type": "string", + "title": "File name pattern", + "description": "Template with {name}, {date}, {recipient} and {ext}.", + "default": "{name}-{date}.{ext}" + } + } + }, + "recipient": { + "slug": "recipient", + "icon": "SendOutline", + "version": "1.0.0", + "title": "Recipient", + "description": "Where a scheduled export is delivered: one channel with its configuration, an optional filter context and an optional retry policy.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": false, + "mailEnabled": false + }, + "required": [ + "channel" + ], + "properties": { + "enabled": { + "type": "boolean", + "default": true, + "title": "Enabled" + }, + "channel": { + "type": "string", + "enum": [ + "email", + "nextcloudFiles", + "webhook", + "sftp" + ], + "title": "Channel" + }, + "filterContext": { + "type": "object", + "title": "Filter context", + "description": "Filters pinned for this recipient, in the shape of the cross-widget filter bus, for example {gemeenteCode: GM0355}." + }, + "channelConfig": { + "type": "object", + "title": "Channel configuration", + "description": "Channel-specific settings (addresses, folder, URL, host). Credentials and signing secrets are held by reference to the credential vault, never inline." + }, + "retryPolicy": { + "type": "object", + "title": "Retry policy", + "description": "Overrides the default retry policy {maxAttempts: 5, initialBackoffSeconds: 60, maxBackoffSeconds: 3600, jitter: true}.", + "properties": { + "maxAttempts": { + "type": "integer", + "minimum": 1, + "maximum": 20 + }, + "initialBackoffSeconds": { + "type": "integer", + "minimum": 1 + }, + "maxBackoffSeconds": { + "type": "integer", + "minimum": 1 + }, + "jitter": { + "type": "boolean" + } + } + } + } + }, + "scheduled_export_run": { + "slug": "scheduled_export_run", + "icon": "History", + "version": "1.0.0", + "title": "Scheduled export run", + "description": "The audit record of one fire of a scheduled export: what was rendered, with its hash, and how each delivery went.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": false, + "mailEnabled": false + }, + "required": [ + "exportId", + "startedAt", + "status", + "triggeredBy" + ], + "properties": { + "exportId": { + "type": "string", + "format": "uuid", + "title": "Export" + }, + "startedAt": { + "type": "string", + "format": "date-time" + }, + "finishedAt": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "enum": [ + "running", + "success", + "partial", + "failed" + ] + }, + "triggeredBy": { + "type": "string", + "enum": [ + "schedule", + "manual" + ] + }, + "triggeredByUser": { + "type": "string" + }, + "renderArtefacts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "format": { + "type": "string", + "enum": [ + "pdf", + "png", + "csv", + "xlsx" + ] + }, + "sizeBytes": { + "type": "integer", + "minimum": 0 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "storagePath": { + "type": "string", + "nullable": true, + "description": "Null once the retention period removed the file." + }, + "filename": { + "type": "string", + "description": "The name recipients get; the archived copy may carry a (2) suffix." + }, + "expiresAt": { + "type": "string", + "format": "date-time" + } + } + } + }, + "deliveries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "recipientId": { + "type": "string" + }, + "channel": { + "type": "string", + "enum": [ + "email", + "nextcloudFiles", + "webhook", + "sftp" + ] + }, + "attemptCount": { + "type": "integer", + "minimum": 0 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "retrying", + "success", + "failed-permanent" + ] + }, + "nextAttemptAt": { + "type": "string", + "format": "date-time", + "nullable": true, + "description": "Null once nothing is left to attempt." + }, + "deliveredAt": { + "type": "string", + "format": "date-time" + }, + "artefactIndexes": { + "title": "Artefact indexes", + "type": "array", + "items": {"type": "integer", "minimum": 0}, + "description": "Which renderArtefacts this recipient was sent, so a retry resends the same files." + }, + "providerMessageId": { + "type": "string" + }, + "error": { + "type": "string", + "nullable": true, + "description": "Null once the delivery succeeded." + } + } + } + }, + "correlationId": { + "type": "string", + "format": "uuid" + }, + "skipReason": { + "type": "string", + "title": "Skip reason", + "description": "Why a fire was skipped without rendering, for example because the previous run was still running." + } + } } } } diff --git a/lib/Settings/register.d/README.md b/lib/Settings/register.d/README.md index a00b95fb1..ebfed663b 100644 --- a/lib/Settings/register.d/README.md +++ b/lib/Settings/register.d/README.md @@ -2,7 +2,9 @@ # Each change adds its own <change>.json (OpenAPI components.schemas/paths) instead # of editing launchpad_register.json — concurrent builds never conflict. # -# NOTE: LaunchPad does not currently load launchpad_register.json into OpenRegister -# (there is no ConfigurationService::importFromApp call). This directory is staged -# for when a register-import loader is added; the merge enabler lives in src/main.js -# (manifest fragments) for now. See the ADR-037 PR notes. +# They are merged onto launchpad_register.json in file-name order by the +# ImportLaunchpadRegister repair step (objects key by key, lists joined), the +# same way OpenRegister's app host merges an app's register.d/. A fragment that +# changes something the importer does not compare by content (such as a +# schema's `configuration`) also needs ImportLaunchpadRegister::REGISTER_VERSION +# raised, or existing installs keep the old schema. diff --git a/lib/Settings/register.d/dashboard-mcp.json b/lib/Settings/register.d/dashboard-mcp.json new file mode 100644 index 000000000..e7efb4c6e --- /dev/null +++ b/lib/Settings/register.d/dashboard-mcp.json @@ -0,0 +1,26 @@ +{ + "components": { + "schemas": { + "Dashboard": { + "configuration": { + "x-openregister-mcp": { + "enabled": true, + "tools": { + "search": { + "description": "Search LaunchPad dashboards by title, slug, type or group. Read only: every change to a dashboard goes through the launchpad.* tools, which keep the slug, permission and lock rules.", + "scope": "read", + "readOnlyHint": true, + "filters": ["title", "slug", "type", "groupId"] + }, + "get": { + "description": "Get one LaunchPad dashboard by id, with its widgets and who it is shared with.", + "scope": "read", + "readOnlyHint": true + } + } + } + } + } + } + } +} diff --git a/lib/Settings/register.d/dashboard-talk-leaf.json b/lib/Settings/register.d/dashboard-talk-leaf.json new file mode 100644 index 000000000..9937d4f54 --- /dev/null +++ b/lib/Settings/register.d/dashboard-talk-leaf.json @@ -0,0 +1,62 @@ +{ + "components": { + "schemas": { + "Dashboard": { + "configuration": { + "linkedTypes": [ + "talk" + ] + }, + "properties": { + "audienceUsers": { + "title": "Audience users", + "type": "array", + "items": { + "type": "string" + }, + "description": "DERIVED by LaunchPad from the dashboard's owner and user shares; never written by a client. The bare user ids the read rule matches with $contains, so the dashboard's discussion is open exactly to those who may view the dashboard (openregister-leaf-integrations)." + }, + "audienceGroups": { + "title": "Audience groups", + "type": "array", + "items": { + "type": "string" + }, + "description": "DERIVED by LaunchPad from the dashboard's group shares, or the group of a group dashboard. The bare group ids the read rule matches with $contains against the caller's groups." + }, + "audienceEveryone": { + "title": "Open to everyone", + "type": "boolean", + "description": "DERIVED by LaunchPad: true for the default group dashboard, which every signed-in user may view." + } + }, + "authorization": { + "read": [ + { + "group": "authenticated", + "match": { + "audienceUsers": { + "$contains": "$userId" + } + } + }, + { + "group": "authenticated", + "match": { + "audienceGroups": { + "$contains": "$user.groups" + } + } + }, + { + "group": "authenticated", + "match": { + "audienceEveryone": true + } + } + ] + } + } + } + } +} diff --git a/lib/Settings/register.d/dashboards-and-who-may-see-them.json b/lib/Settings/register.d/dashboards-and-who-may-see-them.json new file mode 100644 index 000000000..e8b10d376 --- /dev/null +++ b/lib/Settings/register.d/dashboards-and-who-may-see-them.json @@ -0,0 +1,211 @@ +{ + "components": { + "registers": { + "launchpad": { + "schemas": [ + "status_report" + ] + } + }, + "schemas": { + "status_report": { + "slug": "status_report", + "icon": "ClipboardCheckOutline", + "version": "1.0.0", + "title": "Status report", + "description": "A dated status report on a body of work: the figures the product computed, the health rating and the summary, and per value whether it was computed or written by a person (dashboards-and-who-may-see-them REQ-DWMS-004).", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": true, + "mailEnabled": false + }, + "required": [ + "date", + "subject", + "health", + "summary", + "figures", + "provenance", + "author" + ], + "properties": { + "date": { + "type": "string", + "description": "The day the report describes.", + "format": "date", + "title": "Date" + }, + "subject": { + "type": "object", + "title": "Body of work", + "description": "The register and schema of its items, its title and deadline, and how status and due date are read.", + "properties": { + "register": { + "type": "string", + "title": "Register", + "description": "The register that holds the items of this body of work." + }, + "schema": { + "type": "string", + "title": "Schema", + "description": "The schema of the items of this body of work." + }, + "title": { + "type": "string", + "title": "Title", + "description": "The name of the body of work." + }, + "deadline": { + "type": "string", + "title": "Deadline", + "description": "The date the body of work is due, if it has one.", + "format": "date" + }, + "filters": { + "type": "object", + "title": "Filters", + "description": "The filters that select the items of this body of work." + }, + "statusProperty": { + "type": "string", + "title": "Status property", + "description": "The item property that holds its status." + }, + "closedValues": { + "type": "array", + "title": "Closed values", + "description": "The status values that count an item as closed.", + "items": { + "type": "string" + } + }, + "dueProperty": { + "type": "string", + "title": "Due date property", + "description": "The item property that holds its due date." + } + } + }, + "health": { + "type": "string", + "description": "How the body of work is doing: on track, at risk or off track.", + "enum": [ + "on-track", + "at-risk", + "off-track" + ], + "title": "Health" + }, + "summary": { + "type": "string", + "description": "A short written account of the state of the work.", + "maxLength": 5000, + "title": "Summary" + }, + "figures": { + "type": "object", + "description": "The counts the product computed over the items.", + "title": "Figures", + "properties": { + "total": { + "type": "integer", + "title": "Total", + "description": "The number of items.", + "minimum": 0 + }, + "open": { + "type": "integer", + "title": "Open", + "description": "The number of items not yet closed.", + "minimum": 0 + }, + "closed": { + "type": "integer", + "title": "Closed", + "description": "The number of closed items.", + "minimum": 0 + }, + "overdue": { + "type": "integer", + "title": "Overdue", + "description": "The number of open items past their due date.", + "minimum": 0 + }, + "percentClosed": { + "type": "integer", + "title": "Percent closed", + "description": "The share of items that are closed, as a percentage.", + "minimum": 0, + "maximum": 100 + }, + "daysToDeadline": { + "type": "integer", + "title": "Days to deadline", + "description": "The number of days until the deadline, if there is one." + } + } + }, + "provenance": { + "type": "object", + "title": "Computed or written", + "description": "Per value: computed by the product or written by a person.", + "properties": { + "date": { + "type": "string", + "title": "Date source", + "description": "Whether the date was computed or written.", + "enum": [ + "computed", + "written" + ] + }, + "health": { + "type": "string", + "title": "Health source", + "description": "Whether the health rating was computed or written.", + "enum": [ + "computed", + "written" + ] + }, + "summary": { + "type": "string", + "title": "Summary source", + "description": "Whether the summary was computed or written.", + "enum": [ + "computed", + "written" + ] + }, + "figures": { + "type": "object", + "title": "Figures source", + "description": "Per figure, whether it was computed or written.", + "additionalProperties": { + "type": "string", + "enum": [ + "computed", + "written" + ] + } + } + } + }, + "author": { + "type": "string", + "description": "The person who kept this report.", + "title": "Kept by" + }, + "keptAt": { + "type": "string", + "description": "When this report was kept.", + "format": "date-time", + "title": "Kept at" + } + } + } + } + } +} diff --git a/lib/Settings/register.d/drill-down-cross-widget-filter.json b/lib/Settings/register.d/drill-down-cross-widget-filter.json new file mode 100644 index 000000000..e0990e35a --- /dev/null +++ b/lib/Settings/register.d/drill-down-cross-widget-filter.json @@ -0,0 +1,127 @@ +{ + "components": { + "registers": { + "launchpad": { + "schemas": [ + "filter_event" + ] + } + }, + "schemas": { + "filter_event": { + "slug": "filter_event", + "icon": "ChartTimelineVariant", + "version": "1.0.0", + "title": "Filter event", + "description": "One filter change on a dashboard, kept only when filter telemetry is on. It holds the dimensions and operators, never the filter values.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": false, + "mailEnabled": false + }, + "required": [ + "dashboardId", + "userId", + "eventType", + "filterDelta", + "timestamp" + ], + "properties": { + "dashboardId": { + "type": "string", + "format": "uuid", + "title": "Dashboard", + "description": "The dashboard the change was made on." + }, + "userId": { + "type": "string", + "title": "User", + "description": "The user who made the change." + }, + "widgetId": { + "type": "string", + "title": "Widget", + "description": "The widget clicked, for a widget click." + }, + "eventType": { + "type": "string", + "title": "Event type", + "description": "What happened.", + "enum": [ + "apply", + "reset", + "bookmark", + "share" + ] + }, + "filterDelta": { + "type": "array", + "title": "Filter change", + "description": "The clauses added or removed, without their values.", + "items": { + "type": "object", + "required": [ + "dimension", + "operator" + ], + "additionalProperties": false, + "properties": { + "dimension": { + "type": "string", + "title": "Dimension", + "description": "The filtered attribute, such as gemeenteCode or period.month.", + "minLength": 1 + }, + "operator": { + "type": "string", + "title": "Operator", + "description": "How the value is compared.", + "enum": [ + "eq", + "in", + "between", + "gte", + "lte", + "contains", + "notNull" + ] + }, + "source": { + "type": "string", + "title": "Source", + "description": "Where the clause came from.", + "enum": [ + "userExplicit", + "widgetClick", + "urlBootstrap", + "savedView", + "parentScope" + ] + }, + "sourceWidgetId": { + "type": "string", + "title": "Source widget", + "description": "The widget a widget click came from." + }, + "pinned": { + "type": "boolean", + "title": "Pinned", + "description": "A pinned clause survives Reset filters.", + "default": false + } + } + } + }, + "timestamp": { + "type": "string", + "format": "date-time", + "title": "Time", + "description": "When the change was made." + } + } + } + } + } +} diff --git a/lib/Settings/register.d/embedded-analytics.json b/lib/Settings/register.d/embedded-analytics.json new file mode 100644 index 000000000..77a67993a --- /dev/null +++ b/lib/Settings/register.d/embedded-analytics.json @@ -0,0 +1,430 @@ +{ + "components": { + "registers": { + "launchpad": { + "schemas": [ + "embed_token", + "tenant_theme", + "embed_usage_event", + "signing_key" + ] + } + }, + "schemas": { + "embed_token": { + "slug": "embed_token", + "icon": "KeyOutline", + "version": "1.0.0", + "title": "Embed token", + "description": "A signed token that lets one widget or dashboard render on a named external website. Only the sha256 hash of the token is stored; the token itself is shown once.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": false, + "mailEnabled": false + }, + "required": [ + "name", + "tokenHash", + "subject", + "scope", + "hostOrigins" + ], + "properties": { + "name": { + "type": "string", + "title": "Name", + "description": "The name administrators know the token by." + }, + "description": { + "type": "string", + "title": "Description", + "description": "What the token is for and where it is embedded." + }, + "tokenHash": { + "type": "string", + "title": "Token hash", + "description": "The sha256 hash of the issued token, hex encoded. The token itself is never stored.", + "pattern": "^[0-9a-f]{64}$" + }, + "subject": { + "type": "object", + "title": "Subject", + "description": "What the token renders: {type: widget|dashboard, id, filterContext}.", + "properties": { + "type": { + "type": "string", + "enum": [ + "widget", + "dashboard" + ], + "title": "Subject type", + "description": "Whether the token renders one widget or a whole dashboard." + }, + "id": { + "type": "string", + "title": "Subject id", + "description": "The id of the widget or dashboard the token renders." + }, + "filterContext": { + "type": "object", + "title": "Pinned filters", + "description": "Filters applied to every render; the host page cannot change them." + } + }, + "required": [ + "type", + "id" + ] + }, + "scope": { + "type": "object", + "title": "Scope", + "description": "What the token may do: {mode: read|read-with-interactions, allowedFilters, allowedActions}.", + "properties": { + "mode": { + "type": "string", + "enum": [ + "read", + "read-with-interactions" + ], + "title": "Mode", + "description": "read shows the embed only; read-with-interactions also allows the actions listed in allowed actions." + }, + "allowedFilters": { + "type": "array", + "items": { + "type": "string" + }, + "title": "Allowed filters", + "description": "The filter fields the host page may set on top of the pinned filters." + }, + "allowedActions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "interact", + "export", + "drillDown" + ] + }, + "title": "Allowed actions", + "description": "The interactions the embed may perform, such as drill-down or export." + } + }, + "required": [ + "mode" + ] + }, + "hostOrigins": { + "type": "array", + "title": "Host origins", + "items": { + "type": "string" + }, + "description": "The origins allowed to frame the embed, scheme and host, never a wildcard." + }, + "tenantThemeId": { + "type": "string", + "title": "Tenant theme", + "description": "The tenant theme the embed is styled with; empty for the default look." + }, + "tokenExpiresAt": { + "type": "string", + "title": "Expires at", + "description": "Empty for a token that does not expire.", + "format": "date-time" + }, + "revokedAt": { + "type": "string", + "title": "Revoked at", + "format": "date-time", + "description": "When the token was revoked; empty while it is valid." + }, + "revocationReason": { + "type": "string", + "title": "Revocation reason", + "enum": [ + "compromised", + "no_longer_needed", + "host_decommissioned", + "re-issued", + "other" + ], + "description": "Why the token was revoked." + }, + "revocationNotes": { + "type": "string", + "title": "Revocation notes", + "description": "Free text the administrator added when revoking." + }, + "revokedBy": { + "type": "string", + "title": "Revoked by", + "description": "The user id of the administrator who revoked the token." + }, + "rateLimitPolicy": { + "type": "object", + "title": "Rate limit policy", + "description": "{requestsPerMinute, burstSize}.", + "properties": { + "requestsPerMinute": { + "type": "integer", + "minimum": 1, + "title": "Requests per minute", + "description": "How many render and data requests the token may make per minute." + }, + "burstSize": { + "type": "integer", + "minimum": 1, + "title": "Burst size", + "description": "How many requests above the per-minute rate are allowed in a short burst." + } + } + }, + "keyId": { + "type": "string", + "title": "Signing key id", + "description": "The kid the token was signed with." + }, + "createdBy": { + "type": "string", + "title": "Created by", + "description": "The user id of the administrator who issued the token." + }, + "createdAt": { + "type": "string", + "title": "Created at", + "format": "date-time", + "description": "When the token was issued." + }, + "updatedAt": { + "type": "string", + "title": "Updated at", + "format": "date-time", + "description": "When the token was last changed." + } + } + }, + "tenant_theme": { + "slug": "tenant_theme", + "icon": "PaletteOutline", + "version": "1.0.0", + "title": "Tenant theme", + "description": "CSS variables, a logo and :root-only custom CSS that make an embed match the host website.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": false, + "mailEnabled": false + }, + "required": [ + "name", + "cssVariables" + ], + "properties": { + "name": { + "type": "string", + "title": "Name", + "description": "The name administrators know the theme by." + }, + "cssVariables": { + "type": "object", + "title": "CSS variables", + "description": "Custom property names (starting with --) and their values." + }, + "logoUrl": { + "type": "string", + "title": "Logo URL", + "format": "uri", + "description": "The address of the logo shown in embeds with this theme." + }, + "customCss": { + "type": "string", + "title": "Custom CSS", + "description": "Only :root rules are accepted." + }, + "createdBy": { + "type": "string", + "title": "Created by", + "description": "The user id of the administrator who created the theme." + }, + "createdAt": { + "type": "string", + "title": "Created at", + "format": "date-time", + "description": "When the theme was created." + } + } + }, + "embed_usage_event": { + "slug": "embed_usage_event", + "icon": "ChartLine", + "version": "1.0.0", + "title": "Embed usage event", + "description": "One request to an embed, without personal data: no IP address, no full user agent, no end-user identifier.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": false, + "mailEnabled": false + }, + "required": [ + "tokenId", + "eventType", + "timestamp", + "responseStatusCode" + ], + "properties": { + "tokenId": { + "type": "string", + "title": "Token", + "description": "The embed token the request came with." + }, + "eventType": { + "type": "string", + "title": "Event type", + "enum": [ + "pageView", + "widgetRendered", + "filterApplied", + "drillDown", + "export", + "rateLimited" + ], + "description": "What happened in the embed." + }, + "hostOrigin": { + "type": "string", + "title": "Host origin", + "description": "The origin of the page that framed the embed." + }, + "userAgent": { + "type": "string", + "title": "Browser", + "description": "Browser family and major version only, for example Firefox 125." + }, + "userAgentHash": { + "type": "string", + "title": "User agent hash", + "description": "sha256 of the full user agent string; the string itself is not kept.", + "pattern": "^[0-9a-f]{64}$" + }, + "viewportSize": { + "type": "string", + "title": "Viewport", + "enum": [ + "small", + "medium", + "large", + "unknown" + ], + "description": "The size class of the embed frame." + }, + "timestamp": { + "type": "string", + "title": "Timestamp", + "format": "date-time", + "description": "When the event happened." + }, + "responseStatusCode": { + "type": "integer", + "title": "Status code", + "minimum": 100, + "maximum": 599, + "description": "The HTTP status LaunchPad answered with." + }, + "responseLatencyMs": { + "type": "integer", + "title": "Latency (ms)", + "minimum": 0, + "description": "How long LaunchPad took to answer, in milliseconds." + }, + "correlationId": { + "type": "string", + "title": "Correlation id", + "description": "The id that ties this event to its request in the logs." + } + }, + "x-openregister-demo-data": "LaunchPad writes these as the record of embed requests it answered; sample rows would read as traffic that never happened." + }, + "signing_key": { + "slug": "signing_key", + "icon": "ShieldKeyOutline", + "version": "1.0.0", + "title": "Signing key", + "description": "A key pair that signs embed tokens. The private key is stored encrypted; a retiring key still verifies the tokens it signed.", + "type": "object", + "x-openregister": { + "active": true, + "hardDelete": false, + "searchable": false, + "mailEnabled": false + }, + "required": [ + "algorithm", + "publicKeyJwk", + "status" + ], + "properties": { + "kid": { + "type": "string", + "title": "Key id", + "description": "The key id that tokens name in their header." + }, + "algorithm": { + "type": "string", + "title": "Algorithm", + "enum": [ + "RS256", + "ES256" + ], + "description": "The signature algorithm of the key." + }, + "publicKeyJwk": { + "type": "object", + "title": "Public key (JWK)", + "description": "The public key as a JSON Web Key, as published to hosts that verify tokens." + }, + "publicKeyPem": { + "type": "string", + "title": "Public key (PEM)", + "description": "The public key in PEM form." + }, + "privateKeyEncrypted": { + "type": "string", + "title": "Private key (encrypted)", + "description": "The PEM private key, encrypted with the instance secret." + }, + "status": { + "type": "string", + "title": "Status", + "enum": [ + "active", + "retiring", + "revoked" + ], + "description": "active signs new tokens; retiring only verifies tokens it signed; revoked verifies nothing." + }, + "createdAt": { + "type": "string", + "title": "Created at", + "format": "date-time", + "description": "When the key was created." + }, + "retiredAt": { + "type": "string", + "title": "Retired at", + "format": "date-time", + "description": "When the key stopped signing new tokens; empty while it is active." + } + }, + "x-openregister-demo-data": "Signing keys are generated by LaunchPad and hold key material; demo rows would be keys nobody can verify against." + } + } + } +} diff --git a/lib/Settings/reports.json b/lib/Settings/reports.json new file mode 100644 index 000000000..cba63673d --- /dev/null +++ b/lib/Settings/reports.json @@ -0,0 +1,43 @@ +{ + "_comment": [ + "The reports launchpad ships (dashboards-and-who-may-see-them REQ-DWMS-003).", + "Definitions, not dashboards: versioned with the app and never edited in place.", + "Each names the registers and schemas it reads; one the instance lacks is listed as unavailable with those names.", + "aggregation.kind is one of ReportDefinitions::KINDS: count-by (rows per value of a property) or area (AreaAggregation)." + ], + "reports": [ + { + "id": "open-cases-by-handler", + "title": "Open cases by handler", + "description": "How many cases that have not reached a final status each handler holds.", + "source": {"register": "dossiq", "schema": "case"}, + "filters": {"isFinalStatus": false}, + "aggregation": {"kind": "count-by", "property": "assignee", "emptyLabel": "Unassigned"}, + "parameters": [], + "rendering": {"widget": "chart", "chartKind": "bar"} + }, + { + "id": "cases-per-area", + "title": "Cases per area", + "description": "Cases started in a period per area, with the share of each and the cases without a location counted apart.", + "source": {"register": "dossiq", "schema": "case"}, + "filters": {}, + "aggregation": {"kind": "area", "property": "district", "dateProperty": "startDate"}, + "parameters": [ + {"name": "from", "type": "date", "default": null}, + {"name": "until", "type": "date", "default": null} + ], + "rendering": {"widget": "chart", "chartKind": "bar"} + }, + { + "id": "dashboards-by-type", + "title": "Dashboards by type", + "description": "How many dashboards of each type this instance holds.", + "source": {"register": "launchpad", "schema": "dashboard"}, + "filters": {}, + "aggregation": {"kind": "count-by", "property": "type", "emptyLabel": "No type"}, + "parameters": [], + "rendering": {"widget": "chart", "chartKind": "donut"} + } + ] +} diff --git a/lib/Support/WidgetTypeList.php b/lib/Support/WidgetTypeList.php new file mode 100644 index 000000000..872957563 --- /dev/null +++ b/lib/Support/WidgetTypeList.php @@ -0,0 +1,130 @@ +<?php + +/** + * WidgetTypeList: LaunchPad's own widget types, read from `lib/widget-types.json`. + * + * One list, several readers: the demo showcase installer keeps a showcase + * widget whose type is on it, and the shipped `default` widget rule lets every + * user add the types on it. The frontend registry must equal the same file + * (`widgetRegistry.completeness.spec.js`). + * + * @category Support + * @package OCA\LaunchPad\Support + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Support; + +use RuntimeException; + +/** + * Reads LaunchPad's own widget types. + * + * @spec openspec/specs/demo-data-showcases/spec.md + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-011-the-shipped-default-rule-lets-every-user-add-launchpads-own-widgets + */ +final class WidgetTypeList { + /** + * Where the list lives. + * + * @var string + */ + public const PATH = __DIR__ . '/../widget-types.json'; + + /** + * The Nextcloud dashboard widgets the shipped `default` widget rule allows + * besides LaunchPad's own types; older versions shipped only these. + * + * @var list<string> + */ + public const DEFAULT_RULE_DASHBOARD_WIDGETS = ['activity', 'recommendations']; + + /** + * Constructor. + * + * @param string $path The list to read; the shipped one by default. + */ + public function __construct( + private readonly string $path=self::PATH, + ) { + }//end __construct() + + /** + * What the shipped `default` widget rule allows: the Nextcloud dashboard + * widgets it always allowed plus every LaunchPad widget type (REQ-RFP-011). + * + * @return list<string> The widget ids. + * + * @throws RuntimeException When the list is missing or malformed. + * + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-011-the-shipped-default-rule-lets-every-user-add-launchpads-own-widgets + */ + public function defaultRuleWidgets(): array { + return $this->withOwnTypes(widgetIds: self::DEFAULT_RULE_DASHBOARD_WIDGETS); + }//end defaultRuleWidgets() + + /** + * The given Nextcloud dashboard widget ids followed by every LaunchPad + * widget type, which is what a shipped widget rule allows: a rule lists + * every widget its group may use, so a rule without LaunchPad's own types + * would hide them on every dashboard (REQ-RFP-001, REQ-RFP-011). + * + * @param list<string> $widgetIds The Nextcloud dashboard widget ids. + * + * @return list<string> The widget ids. + * + * @throws RuntimeException When the list is missing or malformed. + * + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-011-the-shipped-default-rule-lets-every-user-add-launchpads-own-widgets + */ + public function withOwnTypes(array $widgetIds): array { + return array_values(array_unique(array_merge($widgetIds, $this->types()))); + }//end withOwnTypes() + + /** + * The non-empty type names of the list, in file order. + * + * Throws rather than returning an empty list: an empty list would make + * every caller silently skip or refuse every LaunchPad widget. + * + * @return list<string> The types. + * + * @throws RuntimeException When the list is missing or malformed. + * + * @spec openspec/specs/demo-data-showcases/spec.md + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-011-the-shipped-default-rule-lets-every-user-add-launchpads-own-widgets + */ + public function types(): array { + $raw = null; + if (is_readable(filename: $this->path) === true) { + $raw = file_get_contents(filename: $this->path); + } + + $decoded = null; + if (is_string($raw) === true) { + $decoded = json_decode(json: $raw, associative: true); + } + + if (is_array($decoded) === false || is_array($decoded['types'] ?? null) === false) { + throw new RuntimeException(message: 'LaunchPad widget type list missing or malformed: ' . $this->path); + } + + $types = []; + foreach ($decoded['types'] as $type) { + if (is_string($type) === true && $type !== '') { + $types[] = $type; + } + } + + return array_values(array_unique($types)); + }//end types() +}//end class diff --git a/lib/actions.seed.json b/lib/actions.seed.json index 470ae2f32..3c7dd7812 100644 --- a/lib/actions.seed.json +++ b/lib/actions.seed.json @@ -2,13 +2,23 @@ "$comment": "ADR-023 action matrix seed for launchpad. Administrative actions are admin-only; the ordinary end-user surface carries the \"@all\" sentinel (every authenticated user) so a fresh install is usable by non-admins. Every \"@all\" action below is still gated per object by PermissionService (ownership / share level / group membership) — \"@all\" grants the right to CALL the endpoint, never the right to touch someone else's dashboard. Narrow or broaden via Admin Settings > LaunchPad > Action authorization.", "actions": { "admin.get-my-role": ["admin", "@all"], - "admin-org-navigation.get-org-navigation": ["admin"], - "admin-org-navigation.get-position": ["admin"], + "announcement.read": ["admin", "@all"], + "announcement.manage": ["admin", "@all"], + "announcement.follow": ["admin", "@all"], + "announcement.comment": ["admin", "@all"], + "admin-org-navigation.get-org-navigation": ["admin", "@all"], + "admin-org-navigation.get-position": ["admin", "@all"], "analytics.top-dashboards": ["admin"], "analytics.dashboard-detail": ["admin"], "analytics.instance-summary": ["admin"], "analytics.export-csv": ["admin"], + "catalogue.list": ["admin", "@all"], + "catalogue.request": ["admin", "@all"], + "catalogue.manage": ["admin"], + "catalogue.decide": ["admin"], "tile-analytics.record-click": ["admin", "@all"], + "office-tiles.list": ["admin", "@all"], + "office-tiles.create": ["admin", "@all"], "tile-analytics.top-tiles": ["admin"], "tile-analytics.dashboard-breakdown": ["admin"], "tile-analytics.export-csv": ["admin"], @@ -28,31 +38,33 @@ "dashboard.set-active-dashboard": ["admin", "@all"], "dashboard.set-default-dashboard": ["admin", "@all"], "dashboard.get-default-dashboard": ["admin", "@all"], - "dashboard.publish": ["admin"], - "dashboard.unpublish": ["admin"], - "dashboard.schedule": ["admin"], + "dashboard.publish": ["admin", "@all"], + "dashboard.unpublish": ["admin", "@all"], + "dashboard.schedule": ["admin", "@all"], "dashboard.view-event": ["admin", "@all"], "dashboard-lock.acquire": ["admin", "@all"], "dashboard-lock.heartbeat": ["admin", "@all"], "dashboard-lock.release": ["admin", "@all"], "dashboard-lock.force-release": ["admin"], "dashboard-lock.get": ["admin", "@all"], + "dashboard-presence.join": ["admin", "@all"], + "dashboard-presence.leave": ["admin", "@all"], "dashboard-metadata.get-metadata": ["admin", "@all"], - "dashboard-metadata.set-metadata": ["admin"], + "dashboard-metadata.set-metadata": ["admin", "@all"], "dashboard-reaction.get-reactions": ["admin", "@all"], "dashboard-reaction.add-reaction": ["admin", "@all"], "dashboard-reaction.remove-reaction": ["admin", "@all"], "dashboard-reaction.get-reactors-by-emoji": ["admin", "@all"], "dashboard-translation.list": ["admin", "@all"], - "dashboard-translation.create": ["admin"], - "dashboard-translation.update": ["admin"], - "dashboard-translation.destroy": ["admin"], - "dashboard-translation.set-primary": ["admin"], + "dashboard-translation.create": ["admin", "@all"], + "dashboard-translation.update": ["admin", "@all"], + "dashboard-translation.destroy": ["admin", "@all"], + "dashboard-translation.set-primary": ["admin", "@all"], "dashboard-translation.resolved": ["admin", "@all"], - "dashboard-version.list-versions": ["admin"], - "dashboard-version.fetch-version": ["admin"], - "dashboard-version.create-version": ["admin"], - "dashboard-version.restore-version": ["admin"], + "dashboard-version.list-versions": ["admin", "@all"], + "dashboard-version.fetch-version": ["admin", "@all"], + "dashboard-version.create-version": ["admin", "@all"], + "dashboard-version.restore-version": ["admin", "@all"], "manifest.index": ["admin", "@all"], "metadata-admin.list-fields": ["admin"], "metadata-admin.create-field": ["admin"], @@ -60,14 +72,21 @@ "metadata-admin.update-field": ["admin"], "metadata-admin.delete-field": ["admin"], "people-widget.get-users": ["admin"], + "search-shortcut.list": ["admin"], + "search-shortcut.save": ["admin"], + "profile-fields.get-own": ["admin", "@all"], + "profile-fields.save-own": ["admin", "@all"], + "profile-fields.get-definitions": ["admin"], + "profile-fields.save-definitions": ["admin"], "resource-serve.get-resource": ["admin", "@all"], "resource-serve.list-resources": ["admin", "@all"], - "rule.get-rules": ["admin"], - "rule.add-rule": ["admin"], - "rule.update-rule": ["admin"], - "rule.delete-rule": ["admin"], + "rule.get-rules": ["admin", "@all"], + "rule.add-rule": ["admin", "@all"], + "rule.update-rule": ["admin", "@all"], + "rule.delete-rule": ["admin", "@all"], "template.gallery": ["admin", "@all"], "tile.index": ["admin", "@all"], + "tile.discover": ["admin", "@all"], "tile.create": ["admin"], "tile.update": ["admin"], "tile.destroy": ["admin"], @@ -75,9 +94,19 @@ "widget.get-items": ["admin", "@all"], "widget.add-widget": ["admin", "@all"], "widget.add-tile": ["admin", "@all"], + "widget.import-bookmarks": ["admin", "@all"], "widget.update-placement": ["admin", "@all"], "widget.remove-placement": ["admin", "@all"], "widget.news-items": ["admin", "@all"], - "widget.calendar-events": ["admin", "@all"] + "widget.calendar-events": ["admin", "@all"], + "scheduled-exports.list": ["admin", "@all"], + "scheduled-exports.create": ["admin", "@all"], + "scheduled-exports.read": ["admin", "@all"], + "scheduled-exports.update": ["admin", "@all"], + "scheduled-exports.delete": ["admin", "@all"], + "scheduled-exports.run": ["admin", "@all"], + "scheduled-exports.preview": ["admin", "@all"], + "scheduled-exports.runs": ["admin", "@all"], + "scheduled-exports.retry": ["admin", "@all"] } } diff --git a/lib/widget-types.json b/lib/widget-types.json index e5771505d..b0a59da97 100644 --- a/lib/widget-types.json +++ b/lib/widget-types.json @@ -8,15 +8,25 @@ "Add or remove a type in the registry and here in the same commit; the vitest names the drift." ], "types": [ + "activity-report", "ai-assistant", + "announcements", + "app-tile", + "app-tiles", + "assigned-cases", + "attention", "calendar", "chart", "clock", + "colleague-activity", + "communities", + "connections", "container", "delta", "divider", "files", "gauge", + "graph", "header", "iframe", "image", @@ -24,20 +34,27 @@ "link", "links", "livetile", + "map", "menu", "nc-widget", "news", "object-list", "people", + "pie-chart", "quicklinks", + "recent-work", "search", + "section-heading", "spend-analytics", "stat", "stats-block", + "status-report", "table", "text", "tile", "video", - "weather" + "weather", + "wiki-pages", + "work-packages" ] } diff --git a/llms.txt b/llms.txt new file mode 100644 index 000000000..06d7ce190 --- /dev/null +++ b/llms.txt @@ -0,0 +1,41 @@ +# LaunchPad + +> Nextcloud app for multiple drag-and-drop dashboards with widgets, shortcut tiles, conditional visibility rules and admin templates for groups. + +## Docs + +- [README](README.md): features, screenshots and installation overview +- [AGENTS.md](AGENTS.md): build, test and lint commands and repo conventions for coding agents +- [Development](DEVELOPMENT.md): local development environment and adding a widget type +- [Development workflow](docs/development.md): branches, quality checks and setup +- [Contributing](CONTRIBUTING.md): pull requests and commit message format +- [Architecture](docs/architecture.md): manifest, OpenRegister consumption policy and permission model +- [Introduction](docs/intro.md): user-facing documentation entry point +- [Features](docs/features/README.md): per-feature documentation +- [OpenRegister-backed widgets](docs/widgets/or-data.md): pattern for widgets that read OpenRegister data +- [Embedding](docs/embed/overview.md): embedding dashboards and widgets in other sites +- [Architecture decisions](docs/adr/README.md): pointer to the company-wide ADRs +- [App decision records](openspec/architecture/adr-001-information-architecture.md): app-level information architecture decision + +## API + +- [OpenAPI document](openapi.json): the JSON API under /api/v1/ +- [REST API guide](docs/features/rest-api.md): how to use the REST API +- [Routes](appinfo/routes.php): every route the app registers +- [App manifest](src/manifest.json): menu entries and pages + +## Specs + +- [OpenSpec config](openspec/config.yaml): project context and rules for changes +- [Dashboards](openspec/specs/dashboards/spec.md): dashboard lifecycle +- [Widgets](openspec/specs/widgets/spec.md): widget placement and types +- [Tiles](openspec/specs/tiles/spec.md): custom shortcut tiles +- [Grid layout](openspec/specs/grid-layout/spec.md): grid behaviour +- [Permissions](openspec/specs/permissions/spec.md): permission levels +- [Dashboard sharing](openspec/specs/dashboard-sharing/spec.md): sharing with users and groups +- [Admin templates](openspec/specs/admin-templates/spec.md): templates distributed to groups +- [Conditional visibility](openspec/specs/conditional-visibility/spec.md): visibility rules +- [Admin settings](openspec/specs/admin-settings/spec.md): global settings +- [API contract](openspec/specs/api-contract/spec.md): API conventions +- [Runtime OpenRegister consumption](openspec/specs/runtime-or-consumption/spec.md): optional OpenRegister use +- [All capability specs](openspec/specs/): one folder per capability diff --git a/openapi.json b/openapi.json new file mode 100644 index 000000000..64e01b10c --- /dev/null +++ b/openapi.json @@ -0,0 +1,15957 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "LaunchPad", + "version": "1.1.17-unstable.20261125083210", + "description": "The JSON API of LaunchPad, the dashboard app for Nextcloud: dashboards and their widgets and tiles, kiosk screens, public shares, role-based layouts and permissions, templates and the admin settings behind them.\n\nEvery path is served under `/api/v1/`, the version this document describes. The unversioned `/api/` paths keep working, are deprecated, and name their `/api/v1/` successor in a `Link` header next to a `Deprecation` header. Errors are RFC 9457 problem details (`application/problem+json`), and every response carries an `API-Version` header. Paths that implement an external standard keep the formats of that standard and are not described here.", + "contact": { + "name": "Conduction B.V.", + "email": "info@conduction.nl", + "url": "https://conduction.nl" + }, + "license": { + "name": "EUPL-1.2", + "url": "https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12" + } + }, + "servers": [ + { + "url": "https://{host}/index.php/apps/launchpad/api/v1", + "description": "The LaunchPad API, version 1, on a Nextcloud instance.", + "variables": { + "host": { + "default": "localhost", + "description": "The host name of the Nextcloud instance." + } + } + } + ], + "security": [ + { + "basic_auth": [] + }, + { + "bearer_auth": [] + } + ], + "tags": [ + { + "name": "acknowledgement", + "description": "Mandatory-read acknowledgement endpoints." + }, + { + "name": "action-matrix", + "description": "Admin-only controller exposing the action-authorization matrix (ADR-023)." + }, + { + "name": "activity-report", + "description": "Activity reports and their switch." + }, + { + "name": "admin", + "description": "Controller for admin dashboard template management plus role-assignment CRUD (REQ-ROLE-004, REQ-ROLE-006) and feed-refresh admin actions." + }, + { + "name": "admin-bulk", + "description": "Bulk admin endpoints for dashboards (REQ-BULK-001..011)." + }, + { + "name": "admin-catalogue", + "description": "App catalogue endpoints for administrators." + }, + { + "name": "admin-cleanup", + "description": "Admin endpoints for scan + purge." + }, + { + "name": "admin-demo-showcases", + "description": "Admin endpoints for managing bundled demo showcase dashboards." + }, + { + "name": "admin-org-navigation", + "description": "Org-wide navigation editor REST surface." + }, + { + "name": "admin-settings", + "description": "Admin-only controller for the group-priority order, search shortcut and administrator CSS settings." + }, + { + "name": "admin-shipped-template", + "description": "List, install and update shipped templates." + }, + { + "name": "admin-widget-rules", + "description": "Surfaces the per-widget conditional-visibility overview for the admin Beheer ▸ Versioning & Audit tab (conditional-visibility spec)." + }, + { + "name": "allowed-sites", + "description": "`GET` and `PUT /api/admin/allowed-sites`, for LaunchPad administrators only." + }, + { + "name": "analytics", + "description": "Admin-only controller for dashboard view-analytics endpoints." + }, + { + "name": "analytics-opt-out", + "description": "Read and write the caller's own analytics opt-out." + }, + { + "name": "announcement", + "description": "List, read, write, publish and follow announcements." + }, + { + "name": "announcement-groups", + "description": "The target group picker's list." + }, + { + "name": "announcement-read", + "description": "The read confirmation endpoints of announcements." + }, + { + "name": "attention", + "description": "The attention sources endpoint." + }, + { + "name": "bookmark-import", + "description": "`POST /api/dashboard/{dashboardId}/tiles/import`." + }, + { + "name": "catalogue", + "description": "App catalogue endpoints for users." + }, + { + "name": "colleague-activity", + "description": "Recent colleague activity for the signed-in reader." + }, + { + "name": "confluence-import", + "description": "Admin-only Confluence import endpoints." + }, + { + "name": "dashboard-api", + "description": "Controller for dashboard API endpoints." + }, + { + "name": "dashboard-lock-api", + "description": "Controller for dashboard editing-lock endpoints (REQ-LOCK-001..008)." + }, + { + "name": "dashboard-metadata", + "description": "Dashboard metadata read/write controller." + }, + { + "name": "dashboard-presence-api", + "description": "Announces and withdraws an editor's presence on a dashboard." + }, + { + "name": "dashboard-reaction-api", + "description": "Dashboard reaction endpoints." + }, + { + "name": "dashboard-share-api", + "description": "Controller for dashboard sharing API endpoints." + }, + { + "name": "dashboard-translation-api", + "description": "Controller for dashboard translation endpoints (REQ-DASH-038..044)." + }, + { + "name": "dashboard-version-api", + "description": "Controller for dashboard version endpoints (REQ-VERS-001..009)." + }, + { + "name": "embed-token-api", + "description": "Admin endpoints for embed tokens." + }, + { + "name": "file", + "description": "Controller for the link-button-widget createFile flow." + }, + { + "name": "files-widget", + "description": "Controller for the files-widget capability." + }, + { + "name": "filter-event-report", + "description": "The drill-down path report endpoint." + }, + { + "name": "health-ping", + "description": "Controller for the service-health-ping capability." + }, + { + "name": "hidden-widgets-api", + "description": "List and show again the caller's hidden widgets." + }, + { + "name": "iframe", + "description": "Controller for the `iframe` widget's allow-list validation." + }, + { + "name": "image-host", + "description": "`GET` and `PUT /api/admin/image-hosts`, for LaunchPad administrators only." + }, + { + "name": "kiosk", + "description": "Controller for kiosk-playlist CRUD and anonymous render endpoints." + }, + { + "name": "live-tile", + "description": "Controller for the live-data tile capability." + }, + { + "name": "manifest", + "description": "Controller for the v2 runtime manifest endpoint (ADR-036 Decision 8)." + }, + { + "name": "metadata-admin", + "description": "Admin field-definition CRUD controller." + }, + { + "name": "new-colleagues", + "description": "The new colleagues the caller may see." + }, + { + "name": "office-tiles", + "description": "The office tile pack and file creation from it." + }, + { + "name": "open-api", + "description": "GET /api/openapi.json." + }, + { + "name": "people-widget", + "description": "REST controller exposing the paginated People widget directory." + }, + { + "name": "personal-layer-api", + "description": "Read, save and reset a personal dashboard layer." + }, + { + "name": "preferences", + "description": "Per-user preferences controller." + }, + { + "name": "profile-fields", + "description": "Custom profile field endpoints." + }, + { + "name": "public-share", + "description": "Controller for public-share CRUD and anonymous render endpoints." + }, + { + "name": "public-start", + "description": "`GET` and `PUT /api/admin/public-start`, for LaunchPad administrators only." + }, + { + "name": "report-api", + "description": "Lists, runs and saves the shipped reports." + }, + { + "name": "resource", + "description": "Resource upload + serving controller." + }, + { + "name": "resource-serve", + "description": "Public read-side controller for uploaded resources." + }, + { + "name": "role-feature-permission-api", + "description": "Admin-only API for role-feature permissions and role-layout defaults." + }, + { + "name": "rule-api", + "description": "Controller for conditional rule API endpoints." + }, + { + "name": "scheduled-export", + "description": "Scheduled exports over HTTP." + }, + { + "name": "setup", + "description": "First-time setup wizard endpoints." + }, + { + "name": "sharing-policy", + "description": "Sets the sharing policy." + }, + { + "name": "status-report", + "description": "Status reports for the signed-in user." + }, + { + "name": "storage-report", + "description": "Storage use per workspace and service, administrators only." + }, + { + "name": "store", + "description": "Browse a dashboard registry and install one of its templates." + }, + { + "name": "summary-mail", + "description": "Read and write the caller's summary email frequency." + }, + { + "name": "template", + "description": "Controller for the template gallery (REQ-TMPL-014)." + }, + { + "name": "tenant-theme-api", + "description": "Admin endpoints for tenant themes." + }, + { + "name": "tile-analytics", + "description": "Controller for tile usage-analytics endpoints." + }, + { + "name": "tile-api", + "description": "Controller for tile API endpoints." + }, + { + "name": "tile-launch", + "description": "`GET /api/tiles/{placementId}/rdp` (design D3)." + }, + { + "name": "video-parse", + "description": "Parses video URLs for the widget form." + }, + { + "name": "video-widget", + "description": "Resolves the file of a video placement for its viewer." + }, + { + "name": "visibility-preview", + "description": "`POST /api/visibility/preview` — evaluates a caller-supplied conditional rule set against a caller-supplied `(groups, datetime)` context and returns the effective visibility, WITHOUT persisting anything." + }, + { + "name": "weather", + "description": "Controller for the weather-widget capability." + }, + { + "name": "widget-api", + "description": "Controller for managing dashboard widgets." + }, + { + "name": "work-packages", + "description": "Open work packages for the signed-in person." + } + ], + "paths": { + "/acknowledgements": { + "post": { + "operationId": "acknowledgement-acknowledge", + "x-launchpad-stability": "internal", + "summary": "POST /api/acknowledgements — record the calling user's receipt", + "description": "POST /api/acknowledgements — record the calling user's receipt. Idempotent (REQ-ACK-003). A body `userId` that names another user is rejected with 403 (no IDOR, ADR-005 / REQ-ACK-003). Needs a signed-in Nextcloud user.", + "tags": [ + "acknowledgement" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "announcementKey": { + "description": "The announcement key." + }, + "userId": {}, + "contentVersion": { + "type": "integer" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/acknowledgements/pending": { + "get": { + "operationId": "acknowledgement-pending", + "x-launchpad-stability": "internal", + "summary": "GET /api/acknowledgements/pending — the current user's outstanding mandatory items and count", + "description": "GET /api/acknowledgements/pending — the current user's outstanding mandatory items and count. REQ-ACK-002. Needs a signed-in Nextcloud user.", + "tags": [ + "acknowledgement" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/acknowledgements/report/{announcementKey}": { + "get": { + "operationId": "acknowledgement-report", + "x-launchpad-stability": "internal", + "summary": "GET /api/acknowledgements/report/{announcementKey} — the audience-scoped read-receipt report", + "description": "GET /api/acknowledgements/report/{announcementKey} — the audience-scoped read-receipt report. Admin / template owner only (REQ-ACK-004). Needs a signed-in Nextcloud user.", + "tags": [ + "acknowledgement" + ], + "parameters": [ + { + "name": "announcementKey", + "in": "path", + "required": true, + "description": "The announcement identity.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/acknowledgements/report/{announcementKey}/csv": { + "get": { + "operationId": "acknowledgement-report-csv", + "x-launchpad-stability": "internal", + "summary": "GET /api/acknowledgements/report/{announcementKey}/csv — the report as a downloadable CSV compliance file", + "description": "GET /api/acknowledgements/report/{announcementKey}/csv — the report as a downloadable CSV compliance file. Admin / template owner only (REQ-ACK-004 / REQ-ACK-006). Needs a signed-in Nextcloud user.", + "tags": [ + "acknowledgement" + ], + "parameters": [ + { + "name": "announcementKey", + "in": "path", + "required": true, + "description": "The announcement identity.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/activity-report": { + "get": { + "operationId": "activity-report-report", + "x-launchpad-stability": "internal", + "summary": "GET a person's activity over a period: `user` (default the caller), `from`, `to`", + "description": "GET a person's activity over a period as counts per activity type and per day (UTC), from the activity events; nothing reports hours. Anybody reads their own. Another person's activity is refused with 403 until an administrator turned activity reporting on with a purpose, is read only by an administrator, carries the purpose, and every such read is written to the audit log. Needs a signed-in Nextcloud user.", + "tags": [ + "activity-report" + ], + "parameters": [ + { + "name": "user", + "in": "query", + "required": false, + "description": "Whose activity; empty for the caller's own.", + "schema": { + "type": "string" + } + }, + { + "name": "from", + "in": "query", + "required": false, + "description": "The first day (YYYY-MM-DD).", + "schema": { + "type": "string" + } + }, + { + "name": "to", + "in": "query", + "required": false, + "description": "The last day (YYYY-MM-DD).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/activity-report/export": { + "get": { + "operationId": "activity-report-export", + "x-launchpad-stability": "internal", + "summary": "GET the same report as CSV, with the same numbers", + "description": "The same report as CSV, with the same numbers: one row per activity type, one per active day, and the total. The same rules as the report decide who may have it. Needs a signed-in Nextcloud user.", + "tags": [ + "activity-report" + ], + "parameters": [ + { + "name": "user", + "in": "query", + "required": false, + "description": "Whose activity; empty for the caller's own.", + "schema": { + "type": "string" + } + }, + { + "name": "from", + "in": "query", + "required": false, + "description": "The first day (YYYY-MM-DD).", + "schema": { + "type": "string" + } + }, + { + "name": "to", + "in": "query", + "required": false, + "description": "The last day (YYYY-MM-DD).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/action-matrix": { + "get": { + "operationId": "action-matrix-get-matrix", + "x-launchpad-stability": "internal", + "summary": "Get the full action matrix, the complete action key list, and all groups", + "description": "Get the full action matrix, the complete action key list, and all groups. The action key list is the union of the keys currently in the matrix and the keys declared in the seed file, so the admin sees every declared action even before any customization. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "action-matrix" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "action-matrix-set-matrix", + "x-launchpad-stability": "internal", + "summary": "Persist the action matrix", + "description": "Persist the action matrix. Reads the `matrix` parameter from the request body and writes it through the action authorization service (which normalizes the shape). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "action-matrix" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "matrix": { + "description": "The matrix." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/activity-reporting": { + "get": { + "operationId": "activity-report-policy", + "x-launchpad-stability": "internal", + "summary": "GET whether activity reporting on named people is on, and its purpose", + "description": "Whether activity reporting on named people is on, and the purpose it serves. Administrators only. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "activity-report" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "activity-report-update-policy", + "x-launchpad-stability": "internal", + "summary": "PUT the switch: `enabled`, and the `purpose` it serves (required to turn it on)", + "description": "Turn activity reporting on named people on or off. Turning it on needs a purpose, which every report on a named person shows. Administrators only. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "activity-report" + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether to turn it on." + }, + "purpose": { + "type": [ + "string", + "null" + ], + "description": "The purpose; omitted keeps the recorded one." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/allowed-sites": { + "get": { + "operationId": "allowed-sites-show", + "x-launchpad-stability": "internal", + "summary": "The allowed websites", + "description": "The allowed websites. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "allowed-sites" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "allowed-sites-update", + "x-launchpad-stability": "internal", + "summary": "Replace the list; an entry that is not a host, or has no purpose, is refused with 400", + "description": "Replace the list; an entry that is not a host, or has no purpose, is refused with 400. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "allowed-sites" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "sites": { + "description": "The sites, each `{host, embed, fetch}`." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/analytics/dashboards/top": { + "get": { + "operationId": "analytics-top-dashboards", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/admin/analytics/dashboards/top` (REQ-ANLT-006)", + "description": "Handle `GET /api/admin/analytics/dashboards/top` (REQ-ANLT-006). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "analytics" + ], + "parameters": [ + { + "name": "period", + "in": "query", + "required": false, + "description": "The period string (`7d`, `30d`, `90d`).", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum rows.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/analytics/dashboards/{uuid}": { + "get": { + "operationId": "analytics-dashboard-detail", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/admin/analytics/dashboards/{uuid}` (REQ-ANLT-007)", + "description": "Handle `GET /api/admin/analytics/dashboards/{uuid}` (REQ-ANLT-007). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "analytics" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "period", + "in": "query", + "required": false, + "description": "The period string.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/admin/analytics/export": { + "get": { + "operationId": "analytics-export-csv", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/admin/analytics/export` (REQ-ANLT-010)", + "description": "Handle `GET /api/admin/analytics/export` (REQ-ANLT-010). Returns a `text/csv` attachment with the filename `dashboard-analytics-YYYY-MM-DD.csv` (today's UTC date). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "analytics" + ], + "parameters": [ + { + "name": "period", + "in": "query", + "required": false, + "description": "The period string.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/analytics/summary": { + "get": { + "operationId": "analytics-instance-summary", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/admin/analytics/summary` (REQ-ANLT-008)", + "description": "Handle `GET /api/admin/analytics/summary` (REQ-ANLT-008). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "analytics" + ], + "parameters": [ + { + "name": "period", + "in": "query", + "required": false, + "description": "The period string.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/analytics/tiles/by-dashboard/{uuid}": { + "get": { + "operationId": "tile-analytics-dashboard-breakdown", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/admin/analytics/tiles/by-dashboard/{uuid}` (REQ-TANLT-004)", + "description": "Handle `GET /api/admin/analytics/tiles/by-dashboard/{uuid}` (REQ-TANLT-004). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "tile-analytics" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "period", + "in": "query", + "required": false, + "description": "The period string.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/analytics/tiles/export": { + "get": { + "operationId": "tile-analytics-export-csv", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/admin/analytics/tiles/export` (REQ-TANLT-005)", + "description": "Handle `GET /api/admin/analytics/tiles/export` (REQ-TANLT-005). Returns a `text/csv` attachment with the filename `tile-analytics-YYYY-MM-DD.csv` (today's UTC date). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "tile-analytics" + ], + "parameters": [ + { + "name": "period", + "in": "query", + "required": false, + "description": "The period string.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/analytics/tiles/top": { + "get": { + "operationId": "tile-analytics-top-tiles", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/admin/analytics/tiles/top` (REQ-TANLT-004)", + "description": "Handle `GET /api/admin/analytics/tiles/top` (REQ-TANLT-004). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "tile-analytics" + ], + "parameters": [ + { + "name": "period", + "in": "query", + "required": false, + "description": "The period string (`7d`, `30d`, `90d`).", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum rows.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/catalogue": { + "get": { + "operationId": "admin-catalogue-index", + "x-launchpad-stability": "internal", + "summary": "Every entry, the open requests and the catalogue manager group", + "description": "Every catalogue entry, the open requests and the catalogue manager group. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-catalogue" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "admin-catalogue-create", + "x-launchpad-stability": "internal", + "summary": "Add an entry", + "description": "Add a catalogue entry. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-catalogue" + ], + "responses": { + "201": { + "description": "Created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The app's name." + }, + "description": { + "description": "A short description." + }, + "icon": { + "description": "An icon class or image address." + }, + "iconType": { + "description": "class or url." + }, + "linkType": { + "description": "app (a Nextcloud app id) or url." + }, + "linkValue": { + "description": "The app id or the web address." + }, + "targetGroups": { + "description": "Group ids that see the entry; empty means everyone." + }, + "sortOrder": { + "description": "Position in the catalogue." + } + } + } + } + }, + "required": false + } + } + }, + "/admin/catalogue/requests/{uuid}/approve": { + "post": { + "operationId": "admin-catalogue-approve", + "x-launchpad-stability": "internal", + "summary": "Approve a request with the entry the administrator completed", + "description": "Approve a request with the catalogue entry the administrator completed. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-catalogue" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The request.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The app's name." + }, + "description": { + "description": "A short description." + }, + "icon": { + "description": "An icon class or image address." + }, + "iconType": { + "description": "class or url." + }, + "linkType": { + "description": "app (a Nextcloud app id) or url." + }, + "linkValue": { + "description": "The app id or the web address." + }, + "targetGroups": { + "description": "Group ids that see the entry; empty means everyone." + }, + "sortOrder": { + "description": "Position in the catalogue." + } + } + } + } + }, + "required": false + } + } + }, + "/admin/catalogue/requests/{uuid}/decline": { + "post": { + "operationId": "admin-catalogue-decline", + "x-launchpad-stability": "internal", + "summary": "Decline a request with a note", + "description": "Decline a request with a note. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-catalogue" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The request.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "note": { + "type": [ + "string", + "null" + ], + "description": "Why; required." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + } + }, + "/admin/catalogue/settings": { + "put": { + "operationId": "admin-catalogue-set-manager-group", + "x-launchpad-stability": "internal", + "summary": "Name the group whose members also hear about requests", + "description": "Name the group whose members also hear about requests. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-catalogue" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "managerGroup": { + "type": [ + "string", + "null" + ], + "description": "The group id; '' or null for none." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/catalogue/{uuid}": { + "put": { + "operationId": "admin-catalogue-update", + "x-launchpad-stability": "internal", + "summary": "Change an entry", + "description": "Change a catalogue entry. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-catalogue" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The entry.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The app's name." + }, + "description": { + "description": "A short description." + }, + "icon": { + "description": "An icon class or image address." + }, + "iconType": { + "description": "class or url." + }, + "linkType": { + "description": "app (a Nextcloud app id) or url." + }, + "linkValue": { + "description": "The app id or the web address." + }, + "targetGroups": { + "description": "Group ids that see the entry; empty means everyone." + }, + "sortOrder": { + "description": "Position in the catalogue." + } + } + } + } + }, + "required": false + } + }, + "delete": { + "operationId": "admin-catalogue-destroy", + "x-launchpad-stability": "internal", + "summary": "Remove an entry", + "description": "Remove a catalogue entry. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-catalogue" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The entry.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/admin/cleanup/purge": { + "post": { + "operationId": "admin-cleanup-purge", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/cleanup/purge` — REQ-CLN-005", + "description": "`POST /api/admin/cleanup/purge` — REQ-CLN-005. Body shape: { \"categories\": [\"expired_locks\", ...], // optional, []=all \"dryRun\": true|false // optional, false default }. Returns the per-category breakdown plus total, duration, and dryRun flag. Unknown categories receive HTTP 400 with the list of valid names so the caller can correct the request. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-cleanup" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "categories": { + "anyOf": [ + { + "type": "array", + "items": {} + }, + { + "type": "null" + } + ], + "description": "Per-category filter." + }, + "dryRun": { + "type": [ + "boolean", + "null" + ], + "description": "Dry-run flag." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/cleanup/scan": { + "get": { + "operationId": "admin-cleanup-scan", + "x-launchpad-stability": "internal", + "summary": "`GET /api/admin/cleanup/scan` — REQ-CLN-004", + "description": "`GET /api/admin/cleanup/scan` — REQ-CLN-004. Returns a JSON envelope describing the per-category orphan counts. Reads from the distributed cache when available (REQ-CLN-010) and surfaces `cached`/`cachedAt` hints so the UI can display \"last refreshed\" badges. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-cleanup" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/custom-css": { + "get": { + "operationId": "admin-settings-show-custom-css", + "x-launchpad-stability": "internal", + "summary": "Read the stored CSS for all of LaunchPad", + "description": "Read the stored CSS for all of LaunchPad (REQ-THM-003). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-settings" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "admin-settings-update-custom-css", + "x-launchpad-stability": "internal", + "summary": "Clean, scope and store the CSS for all of LaunchPad", + "description": "Clean, scope and store the CSS for all of LaunchPad (REQ-THM-003). Answers with the stored CSS and what the cleaning removed; 400 for a value that is no string or is over 20 KB. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-settings" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "customCss": { + "type": "string", + "description": "The CSS; an empty string clears it." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/custom-css/dashboards/{uuid}": { + "put": { + "operationId": "admin-settings-update-dashboard-custom-css", + "x-launchpad-stability": "internal", + "summary": "Clean, scope and store the CSS for one dashboard", + "description": "Clean, scope and store the CSS for one dashboard (REQ-THM-003), scoped to that dashboard's region. Answers with the stored CSS and what the cleaning removed; 400 for a value that is no string or is over 20 KB, 404 for an unknown dashboard. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-settings" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard's UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "customCss": { + "type": "string", + "description": "The CSS; an empty string clears it." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/admin/dashboards/bulk-delete": { + "post": { + "operationId": "admin-bulk-bulk-delete", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/dashboards/bulk-delete` — REQ-BULK-001", + "description": "`POST /api/admin/dashboards/bulk-delete` — REQ-BULK-001. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-bulk" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dashboardUuids": { + "description": "The UUID array." + }, + "dryRun": { + "type": [ + "boolean", + "null" + ], + "description": "When true, preview only." + }, + "cascade": { + "type": [ + "boolean", + "null" + ], + "description": "When true, cascade into children." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/dashboards/bulk-move": { + "post": { + "operationId": "admin-bulk-bulk-move", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/dashboards/bulk-move` — REQ-BULK-002", + "description": "`POST /api/admin/dashboards/bulk-move` — REQ-BULK-002. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-bulk" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dashboardUuids": { + "description": "The UUID array." + }, + "parentUuid": { + "type": [ + "string", + "null" + ], + "description": "The new parent UUID (NULL ⇒ root)." + }, + "dryRun": { + "type": [ + "boolean", + "null" + ], + "description": "When true, preview only." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/dashboards/bulk-reindex": { + "post": { + "operationId": "admin-bulk-bulk-reindex", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/dashboards/bulk-reindex` — REQ-BULK-004", + "description": "`POST /api/admin/dashboards/bulk-reindex` — REQ-BULK-004. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-bulk" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dashboardUuids": { + "description": "The UUID array." + }, + "dryRun": { + "type": [ + "boolean", + "null" + ], + "description": "When true, preview only." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/dashboards/bulk-status": { + "post": { + "operationId": "admin-bulk-bulk-status", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/dashboards/bulk-status` — REQ-BULK-003", + "description": "`POST /api/admin/dashboards/bulk-status` — REQ-BULK-003. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-bulk" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dashboardUuids": { + "description": "The UUID array." + }, + "publicationStatus": { + "type": [ + "string", + "null" + ], + "description": "The target status enum value." + }, + "publishAt": { + "type": [ + "string", + "null" + ], + "description": "Future ISO-8601 timestamp." + }, + "dryRun": { + "type": [ + "boolean", + "null" + ], + "description": "When true, preview only." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/demo-showcases": { + "get": { + "operationId": "admin-demo-showcases-index", + "x-launchpad-stability": "internal", + "summary": "List bundled showcases with installation status (REQ-DEMO-002)", + "description": "List bundled showcases with installation status (REQ-DEMO-002). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-demo-showcases" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/demo-showcases/{id}": { + "delete": { + "operationId": "admin-demo-showcases-destroy", + "x-launchpad-stability": "internal", + "summary": "Uninstall a previously-installed showcase (REQ-DEMO-006)", + "description": "Uninstall a previously-installed showcase (REQ-DEMO-006). Idempotent — returns 204 even when the showcase is not currently installed. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-demo-showcases" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The showcase ID (path segment).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/admin/demo-showcases/{id}/install": { + "post": { + "operationId": "admin-demo-showcases-install", + "x-launchpad-stability": "internal", + "summary": "Install a bundled showcase (REQ-DEMO-003, REQ-DEMO-004)", + "description": "Install a bundled showcase (REQ-DEMO-003, REQ-DEMO-004). Always returns the dashboard UUID — when the showcase is already installed and `force` is unset, the existing UUID is returned with `alreadyInstalled: true` so callers can render an informational banner. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-demo-showcases" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The showcase ID (path segment).", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "lang": { + "type": "string", + "description": "Optional locale (always resolves to `nl` in v1; REQ-DEMO-007)." + }, + "force": { + "type": "boolean", + "description": "Force reinstallation, removing the existing dashboard if any." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/admin/export": { + "post": { + "operationId": "admin-export", + "x-launchpad-stability": "public", + "summary": "Export a single dashboard or the entire site as a ZIP archive", + "description": "Export a single dashboard or the entire site as a ZIP archive. Implements REQ-EXIM-002 (single-dashboard export) and REQ-EXIM-003 (site export). Admin-only — non-admins receive HTTP 403. Query parameters: - `scope` (string, required): `dashboard` or `site`. - `dashboardUuid` (string, required when scope=dashboard). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "description": "The export scope." + }, + "dashboardUuid": { + "type": [ + "string", + "null" + ], + "description": "The dashboard UUID for scope=dashboard." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/admin/feeds/refresh-now": { + "post": { + "operationId": "admin-refresh-feeds-now", + "x-launchpad-stability": "internal", + "summary": "Trigger an immediate background feed refresh (REQ-FRJ-010)", + "description": "Trigger an immediate background feed refresh (REQ-FRJ-010). Admin-only — guarded by `self::requireAdmin()`. Optionally scope the refresh to a single feed URL (must be HTTP/HTTPS). Returns `{processedCount, successCount, failureCount, durationMs}`. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "feedUrl": { + "type": [ + "string", + "null" + ], + "description": "Optional single URL to refresh." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/footer-settings": { + "get": { + "operationId": "admin-get-footer-settings", + "x-launchpad-stability": "internal", + "summary": "Read the global footer settings (REQ-FTR-001, REQ-FTR-010)", + "description": "Read the global footer settings (REQ-FTR-001, REQ-FTR-010). Returns the five footer keys as a flat camelCase object so the admin UI can render the form with one round-trip. Admin-only — non-admins receive HTTP 403 because even the read path discloses potentially-sensitive draft footer copy. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "admin-update-footer-settings", + "x-launchpad-stability": "internal", + "summary": "Patch the global footer settings (REQ-FTR-001..003, REQ-FTR-009, REQ-FTR-010)", + "description": "Patch the global footer settings (REQ-FTR-001..003, REQ-FTR-009, REQ-FTR-010). Body: any subset of `{footerEnabled, footerHtml, footerConfig, footerBackgroundColor, footerTextColor}`. The service sanitises HTML, validates the structured-config schema, and validates hex colour strings before persistence. Validation failures map to HTTP 400 (or 413 when the HTML exceeds the 8 KB cap). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "footerEnabled": { + "type": [ + "boolean", + "null" + ], + "description": "Master toggle." + }, + "footerHtml": { + "type": [ + "string", + "array", + "null" + ], + "description": "Raw HTML or language-variant map." + }, + "footerConfig": { + "type": [ + "array", + "null" + ], + "description": "Structured config." + }, + "footerBackgroundColor": { + "type": [ + "string", + "null" + ], + "description": "Hex (#rrggbb) or null." + }, + "footerTextColor": { + "type": [ + "string", + "null" + ], + "description": "Hex (#rrggbb) or null." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "413": { + "$ref": "#/components/responses/Problem413" + } + } + } + }, + "/admin/groups": { + "get": { + "operationId": "admin-settings-list-groups", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/admin/groups` — REQ-ASET-013", + "description": "Handle `GET /api/admin/groups` — REQ-ASET-013. Returns the disjoint exhaustive split `{active, inactive, allKnown}`: - `active` — the persisted `group_order` list, in admin-chosen order. Stale IDs (no longer in Nextcloud) remain so admin can see and remove them. - `inactive` — every Nextcloud group ID NOT in `active`, sorted by displayName (case-insensitive). - `allKnown` — full `{id, displayName}` list for the UI to render display names without a second round-trip. Stale IDs MUST NOT appear here (no display name available). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-settings" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "admin-settings-update-group-order", + "x-launchpad-stability": "internal", + "summary": "Handle `POST /api/admin/groups` — REQ-ASET-012, REQ-ASET-014", + "description": "Handle `POST /api/admin/groups` — REQ-ASET-012, REQ-ASET-014. Body: `{\"groups\": [\"id\", ...]}`. Replaces the persisted `group_order` setting wholesale. Validation: - `groups` MUST be present and an array. - Every element MUST be a non-empty string. - Duplicate IDs are deduplicated (first occurrence kept). - Unknown (not currently in Nextcloud) IDs are tolerated — they remain in the persisted setting per REQ-ASET-014. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-settings" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "groups": { + "description": "The raw `groups` payload from the request body." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/image-hosts": { + "get": { + "operationId": "image-host-show", + "x-launchpad-stability": "internal", + "summary": "The allow-listed image hosts", + "description": "The allow-listed image hosts. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "image-host" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "image-host-update", + "x-launchpad-stability": "internal", + "summary": "Replace the allow-list; a list holding something other than host names is refused with 400", + "description": "Replace the allow-list; a list holding something other than host names is refused with 400. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "image-host" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "hosts": { + "description": "The host names." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/import": { + "post": { + "operationId": "admin-import", + "x-launchpad-stability": "public", + "summary": "Import a previously-exported ZIP archive", + "description": "Import a previously-exported ZIP archive. Implements REQ-EXIM-004..008. Admin-only. Multipart body: a `file` field containing the ZIP archive. Query parameter: `preserveUuids` (default false). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "preserveUuids": { + "type": "boolean", + "description": "When true, fail on UUID collision." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadImportSummary" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + } + }, + "/admin/import/confluence": { + "post": { + "operationId": "confluence-import-import", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/import/confluence` — REQ-CFLI-001..006, 009, 012", + "description": "`POST /api/admin/import/confluence` — REQ-CFLI-001..006, 009, 012. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "confluence-import" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "parentUuid": { + "type": [ + "string", + "null" + ], + "description": "Optional parent dashboard UUID under which root pages will be slotted." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/admin/import/confluence/dry-run": { + "post": { + "operationId": "confluence-import-dry-run", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/import/confluence/dry-run` — REQ-CFLI-007", + "description": "`POST /api/admin/import/confluence/dry-run` — REQ-CFLI-007. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "confluence-import" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/admin/leaver-handover": { + "put": { + "operationId": "sharing-policy-update-leaver-handover", + "x-launchpad-stability": "internal", + "summary": "Set where a leaver's dashboards go (REQ-SHARE-016): their manager or not, and the person otherwise ('' for nobody)", + "description": "Set where a leaver's dashboards go (REQ-SHARE-016): their manager or not, and the person otherwise ('' for nobody). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "sharing-policy" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "manager": { + "type": [ + "boolean", + "null" + ], + "description": "Whether a leaver's manager comes first; null reads as no." + }, + "fallbackUid": { + "type": "string", + "description": "The person otherwise; '' for nobody." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/metadata-fields": { + "get": { + "operationId": "metadata-admin-list-fields", + "x-launchpad-stability": "internal", + "summary": "`GET /api/admin/metadata-fields` — list all field definitions (REQ-MDFL-001)", + "description": "`GET /api/admin/metadata-fields` — list all field definitions (REQ-MDFL-001). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "metadata-admin" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "metadata-admin-create-field", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/metadata-fields` — create a new field definition (REQ-MDFL-001)", + "description": "`POST /api/admin/metadata-fields` — create a new field definition (REQ-MDFL-001). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "metadata-admin" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The slug." + }, + "label": { + "type": "string", + "description": "The display label." + }, + "type": { + "type": "string", + "description": "The field type." + }, + "options": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "null" + } + ], + "description": "Option set (select types)." + }, + "required": { + "type": "integer", + "description": "0 / 1." + }, + "sortOrder": { + "type": "integer", + "description": "UI sort order." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/metadata-fields/{id}": { + "get": { + "operationId": "metadata-admin-get-field", + "x-launchpad-stability": "internal", + "summary": "`GET /api/admin/metadata-fields/{id}` — fetch a single field definition (REQ-MDFL-001)", + "description": "`GET /api/admin/metadata-fields/{id}` — fetch a single field definition (REQ-MDFL-001). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "metadata-admin" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The field id.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "put": { + "operationId": "metadata-admin-update-field", + "x-launchpad-stability": "internal", + "summary": "`PUT /api/admin/metadata-fields/{id}` — update label / sortOrder / required / options", + "description": "`PUT /api/admin/metadata-fields/{id}` — update label / sortOrder / required / options. Forbids `key` rename (REQ-MDFL-002). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "metadata-admin" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The field id.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "label": { + "type": [ + "string", + "null" + ], + "description": "The new label." + }, + "sortOrder": { + "type": [ + "integer", + "null" + ], + "description": "The new sort order." + }, + "required": { + "type": [ + "integer", + "null" + ], + "description": "The new required flag." + }, + "options": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "null" + } + ], + "description": "The new option set." + }, + "key": { + "type": [ + "string", + "null" + ], + "description": "Forbidden — triggers 400." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "delete": { + "operationId": "metadata-admin-delete-field", + "x-launchpad-stability": "internal", + "summary": "`DELETE /api/admin/metadata-fields/{id}?cascade=true` — REQ-MDFL-003", + "description": "`DELETE /api/admin/metadata-fields/{id}?cascade=true` — REQ-MDFL-003. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "metadata-admin" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The field id.", + "schema": { + "type": "integer" + } + }, + { + "name": "cascade", + "in": "query", + "required": false, + "description": "Whether to cascade-delete dependent values.", + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/admin/org-navigation": { + "get": { + "operationId": "admin-org-navigation-get-org-navigation", + "x-launchpad-stability": "internal", + "summary": "Read the org-navigation tree filtered for the current user", + "description": "Read the org-navigation tree filtered for the current user. Accessible to any logged-in user (REQ-ONAV-002). Needs a signed-in Nextcloud user.", + "tags": [ + "admin-org-navigation" + ], + "parameters": [ + { + "name": "lang", + "in": "query", + "required": false, + "description": "Language code (defaults to `nl`).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "admin-org-navigation-update-org-navigation", + "x-launchpad-stability": "internal", + "summary": "Replace the org-navigation tree for the given language", + "description": "Replace the org-navigation tree for the given language. Admin-only (REQ-ONAV-003); validates and persists in one go. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-org-navigation" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tree": { + "type": [ + "array", + "null" + ], + "description": "The full replacement tree." + }, + "lang": { + "type": "string", + "description": "Language code (defaults to `nl`)." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/org-navigation/position": { + "get": { + "operationId": "admin-org-navigation-get-position", + "x-launchpad-stability": "internal", + "summary": "Read the global rail-position setting (REQ-ONAV-004)", + "description": "Read the global rail-position setting (REQ-ONAV-004). Needs a signed-in Nextcloud user.", + "tags": [ + "admin-org-navigation" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "admin-org-navigation-update-position", + "x-launchpad-stability": "internal", + "summary": "Replace the global rail-position setting (REQ-ONAV-004)", + "description": "Replace the global rail-position setting (REQ-ONAV-004). Admin-only. Accepts `{position: 'left'|'right'|'top'|'hidden'}`. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-org-navigation" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "position": { + "type": [ + "string", + "null" + ], + "description": "The desired position." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/public-start": { + "get": { + "operationId": "public-start-show", + "x-launchpad-stability": "internal", + "summary": "The start page's status and the links that may be chosen", + "description": "Answers `{enabled, token, active, reason, candidates}`: whether the public start page is on, the chosen link, whether it is live, why not (`off`, `no-link`, `not-found`, `revoked`, `password`, `expired`), and the public links without a password that are not revoked or expired. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "public-start" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "public-start-update", + "x-launchpad-stability": "internal", + "summary": "Choose the link and switch the start page on or off; a link that cannot be shown is refused with 400", + "description": "Body `{enabled, token}`. A link with a password, a revoked or expired link, an unknown token, and switching on without a link answer 400. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "public-start" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether the start page is on." + }, + "token": { + "type": "string", + "description": "The chosen link's token, or '' for none." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/roles": { + "get": { + "operationId": "admin-list-roles", + "x-launchpad-stability": "internal", + "summary": "List every role assignment in the system (REQ-ROLE-006)", + "description": "List every role assignment in the system (REQ-ROLE-006). NC-admin only. Returns a JSON array of role-assignment rows with their persisted fields (id, userId, groupId, role, assignedBy, assignedAt). The caller MUST be a Nextcloud admin; non-admins receive HTTP 403. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "admin-create-role", + "x-launchpad-stability": "internal", + "summary": "Create a new role assignment (REQ-ROLE-004)", + "description": "Create a new role assignment (REQ-ROLE-004). NC-admin only. Accepts a JSON body `{userId?: string, groupId?: string, role: string}`. Exactly one of `userId` / `groupId` MUST be set. Returns the new assignment with HTTP 201 on success. Returns 400 on structural failure, 409 on duplicate, 401/403 on auth failure. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "userId": { + "type": [ + "string", + "null" + ], + "description": "The target user ID (XOR with groupId)." + }, + "groupId": { + "type": [ + "string", + "null" + ], + "description": "The target group ID (XOR with userId)." + }, + "role": { + "type": [ + "string", + "null" + ], + "description": "The role name (admin / editor / viewer)." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + } + }, + "/admin/roles/{id}": { + "delete": { + "operationId": "admin-delete-role", + "x-launchpad-stability": "internal", + "summary": "Delete a role assignment by ID (REQ-ROLE-004)", + "description": "Delete a role assignment by ID (REQ-ROLE-004). NC-admin only. Returns 204 on success, 404 when no row matches, 401/403 on auth. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The role assignment ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/admin/search-shortcuts": { + "get": { + "operationId": "admin-settings-list-search-shortcuts", + "x-launchpad-stability": "internal", + "summary": "The shortcut list (administrators)", + "description": "List the search shortcuts every search box honours: `{prefix, name, urlTemplate}` per shortcut. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-settings" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "admin-settings-save-search-shortcuts", + "x-launchpad-stability": "internal", + "summary": "Replace the shortcut list (administrators)", + "description": "Replace the search shortcuts with the `shortcuts` list from the request body and return the stored list. An invalid list is refused with 400. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-settings" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "shortcuts": { + "type": [ + "array", + "null" + ], + "description": "The new list." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/settings": { + "get": { + "operationId": "admin-get-settings", + "x-launchpad-stability": "internal", + "summary": "Get admin settings", + "description": "Get admin settings. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "admin-update-settings", + "x-launchpad-stability": "internal", + "summary": "Update admin settings", + "description": "Update admin settings. Five settings are read under one name and written under another: GET answers `allowUserDashboards`, this PUT took only `allowUserDash`. An unrecognised key binds to null, null means \"not supplied\", so a caller round-tripping GET into PUT wrote nothing and was told `{\"status\": \"ok\"}`. Both spellings are accepted; the short one wins, since AdminSettings.vue sends it. Covered by AdminControllerSettingsAliasTest. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "defaultPermLevel": { + "type": [ + "string", + "null" + ], + "description": "Default permission level." + }, + "allowUserDash": { + "type": [ + "boolean", + "null" + ], + "description": "Allow user dashboards." + }, + "allowMultiDash": { + "type": [ + "boolean", + "null" + ], + "description": "Allow multiple dashboards." + }, + "defaultGridCols": { + "type": [ + "integer", + "null" + ], + "description": "Default grid columns." + }, + "linkCreateFileExts": { + "type": [ + "array", + "null" + ], + "description": "link-button-widget createFile extension allow-list (REQ-LBN-004)." + }, + "defaultSharePermissionLevel": { + "type": [ + "string", + "null" + ], + "description": "Org-wide default share permission level (dashboard-sharing spec)." + }, + "forcedShareGroups": { + "type": [ + "array", + "null" + ], + "description": "Groups every new dashboard is force-shared with (dashboard-sharing spec)." + }, + "legacyWidgetBridgeEnabled": { + "type": [ + "boolean", + "null" + ], + "description": "Enable / disable the legacy widget bridge (legacy-widget-bridge spec)." + }, + "maxDashboardsPerUser": { + "type": [ + "integer", + "null" + ], + "description": "Maximum personal dashboards per user (`0` = unlimited). dashboard-quota-limits REQ-QUOTA-001." + }, + "maxWidgetsPerDashboard": { + "type": [ + "integer", + "null" + ], + "description": "Maximum placements per dashboard (`0` = unlimited). dashboard-quota-limits REQ-QUOTA-001." + }, + "quicksearchFallbackTarget": { + "type": [ + "string", + "null" + ], + "description": "On-dashboard quick-search no-match fallback: `'none'`, `'unified-search'`, or an `https` URL template containing `{query}`. tile-quick-search REQ-QSEARCH-004." + }, + "defaultPermissionLevel": { + "type": [ + "string", + "null" + ], + "description": "Alias of `$defaultPermLevel`." + }, + "allowUserDashboards": { + "type": [ + "boolean", + "null" + ], + "description": "Alias of `$allowUserDash`." + }, + "allowMultipleDashboards": { + "type": [ + "boolean", + "null" + ], + "description": "Alias of `$allowMultiDash`." + }, + "defaultGridColumns": { + "type": [ + "integer", + "null" + ], + "description": "Alias of `$defaultGridCols`." + }, + "linkCreateFileExtensions": { + "type": [ + "array", + "null" + ], + "description": "Alias of `$linkCreateFileExts`." + }, + "sharingAllowedGroups": { + "type": [ + "array", + "null" + ], + "description": "The groups whose members may share; empty means everyone (REQ-SHARE-014)." + }, + "sharingRecipientScope": { + "type": [ + "string", + "null" + ], + "description": "`everyone` or `shared-groups` (REQ-SHARE-014)." + }, + "tileAllowedSchemes": { + "type": [ + "array", + "null" + ], + "description": "URL schemes a program tile may use (launcher-tile-launch-types)." + }, + "ssoLaunchTemplates": { + "type": [ + "array", + "null" + ], + "description": "Identity-provider launch templates `{key, name, urlTemplate}` (launcher-tile-launch-types)." + }, + "announcementEditorGroups": { + "type": [ + "array", + "null" + ], + "description": "Groups whose members may write announcements (engagement-announcements D6)." + }, + "filterTelemetryEnabled": { + "type": [ + "boolean", + "null" + ], + "description": "Org-level filter telemetry opt-in (drill-down-cross-widget-filter REQ-CWF-010)." + }, + "officeNetworks": { + "type": [ + "array", + "null" + ], + "description": "The office networks as CIDR ranges; a malformed one answers 400 (REQ-TIA-001)." + }, + "pinnedCommunities": { + "type": [ + "array", + "null" + ], + "description": "Talk conversation tokens pinned as the organisation's communities, at most 20 (REQ-COMM-003)." + }, + "defaultAppEnabled": { + "type": [ + "boolean", + "null" + ], + "description": "LaunchPad is the default app after sign-in (REQ-PSP-003)." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/setup-wizard/complete": { + "post": { + "operationId": "admin-complete-wizard", + "x-launchpad-stability": "internal", + "summary": "Mark the setup-wizard complete (REQ-WIZ-009)", + "description": "Mark the setup-wizard complete (REQ-WIZ-009). Idempotent — calling on a completed instance returns 200 with the same payload. Admin-only. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/setup-wizard/state": { + "get": { + "operationId": "admin-get-wizard-state", + "x-launchpad-stability": "internal", + "summary": "Get the setup-wizard state (REQ-WIZ-008)", + "description": "Get the setup-wizard state (REQ-WIZ-008). Admin-only — non-admins receive HTTP 403. Returns `{complete, currentRecommendedStep, stepStatuses}`. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/sharing-policy": { + "put": { + "operationId": "sharing-policy-update", + "x-launchpad-stability": "internal", + "summary": "Set who may share and whether public links may be created", + "description": "Set who may share and whether public links may be created. A partial patch: a value left out stays as it is. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "sharing-policy" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "sharingAllowed": { + "type": [ + "string", + "null" + ], + "description": "`everyone`, `groups` or `none`." + }, + "publicLinksAllowed": { + "type": [ + "boolean", + "null" + ], + "description": "Whether public links may be created." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/storage-report": { + "get": { + "operationId": "storage-report-report", + "x-launchpad-stability": "internal", + "summary": "GET the storage report", + "description": "GET storage use per workspace (a Nextcloud group: the files of its members) and per service (files, trash, versions, each app's app data), now and as a twelve-month series of daily snapshots, the object count per register, and the removable total named apart: trash past its retention and launchpad uploads no row names. Read from the platform's own figures, never by walking files or objects. Administrators only; anybody else gets 403. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "storage-report" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/storage-report/export": { + "get": { + "operationId": "storage-report-export", + "x-launchpad-stability": "internal", + "summary": "GET the storage report as CSV", + "description": "GET the storage report as CSV: the total, each workspace and service with its twelve months, and the removable total. Administrators only; anybody else gets 403. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "storage-report" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/templates": { + "get": { + "operationId": "admin-list-templates", + "x-launchpad-stability": "internal", + "summary": "List all admin dashboard templates", + "description": "List all admin dashboard templates. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "admin-create-template", + "x-launchpad-stability": "internal", + "summary": "Create a new admin template", + "description": "Create a new admin template. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The template name." + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The description." + }, + "targetGroups": { + "type": [ + "array", + "null" + ], + "description": "The target groups." + }, + "permissionLevel": { + "type": "string", + "description": "The permission level." + }, + "isDefault": { + "type": "boolean", + "description": "Whether default." + } + }, + "required": [ + "name" + ] + } + } + } + }, + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/templates/shipped": { + "get": { + "operationId": "admin-shipped-template-index", + "x-launchpad-stability": "internal", + "summary": "List the shipped templates with whether each is installed", + "description": "List the shipped templates with whether each is installed. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-shipped-template" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/templates/shipped/{id}/install": { + "post": { + "operationId": "admin-shipped-template-install", + "x-launchpad-stability": "internal", + "summary": "Add a shipped template as an admin template", + "description": "Add a shipped template as an admin template. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-shipped-template" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The shipped template id.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "force": { + "type": "boolean", + "description": "Add a fresh copy even when installed." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/admin/templates/shipped/{id}/update": { + "post": { + "operationId": "admin-shipped-template-update", + "x-launchpad-stability": "internal", + "summary": "Update an installed shipped template to the version LaunchPad ships now, in place, and bring the members' copies along", + "description": "Update an installed shipped template to the version LaunchPad ships now, in place, and bring the members' copies along. With `dryRun` it only says what would change. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-shipped-template" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The shipped template id.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dryRun": { + "type": "boolean", + "description": "Report the changes, write nothing." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/admin/templates/{id}": { + "get": { + "operationId": "admin-get-template", + "x-launchpad-stability": "internal", + "summary": "Get a specific admin template", + "description": "Get a specific admin template. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The template ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "put": { + "operationId": "admin-update-template", + "x-launchpad-stability": "internal", + "summary": "Update an admin template", + "description": "Update an admin template. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The template ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": [ + "string", + "null" + ], + "description": "The name." + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The description." + }, + "targetGroups": { + "type": [ + "array", + "null" + ], + "description": "The target groups." + }, + "permissionLevel": { + "type": [ + "string", + "null" + ], + "description": "The permission level." + }, + "isDefault": { + "type": [ + "boolean", + "null" + ], + "description": "Whether default." + }, + "gridColumns": { + "type": [ + "integer", + "null" + ], + "description": "The grid columns." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "delete": { + "operationId": "admin-delete-template", + "x-launchpad-stability": "internal", + "summary": "Delete an admin template", + "description": "Delete an admin template. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The template ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/templates/{id}/resync": { + "post": { + "operationId": "admin-resync-template", + "x-launchpad-stability": "internal", + "summary": "Push an updated admin template to its already-provisioned user copies (REQ-RESYNC-001)", + "description": "Push an updated admin template to its already-provisioned user copies (REQ-RESYNC-001). Body: `{strategy: \"overwrite\"|\"merge\"|\"add_only\", dryRun: bool}`. Dry-run (the default) computes and returns the plan — affected copies plus per-copy add/update/remove/preserve counts — without mutating anything. A real run (`dryRun: false`) applies inline for small target groups or enqueues `\\OCA\\LaunchPad\\BackgroundJob\\TemplateResyncJob` for large ones, writes one audit record, and notifies every affected user. Admin-guarded twice over — the `AuthorizedAdminSetting` attribute plus the explicit `self::assertAdmin()` guard — matching this controller's other mutating admin actions (export/import/footer). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The admin template's dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "strategy": { + "type": "string", + "description": "`'overwrite'`, `'merge'` or `'add_only'`." + }, + "dryRun": { + "type": "boolean", + "description": "When true (default), report without mutating." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/admin/templates/{uuid}/preview-image": { + "post": { + "operationId": "admin-upload-template-preview-image", + "x-launchpad-stability": "internal", + "summary": "`POST /api/admin/templates/{uuid}/preview-image` — admin-only preview-image upload (REQ-TMPL-017)", + "description": "`POST /api/admin/templates/{uuid}/preview-image` — admin-only preview-image upload (REQ-TMPL-017). Body (JSON): `{base64: 'data:image/<type>;base64,<bytes>'}`. The payload is delegated to `ResourceService::upload()` (the \"custom-icon-upload pattern\"); the returned URL is written to the template's `templatePreviewImage` column. Allowed image types: PNG, JPG, GIF, WebP, SVG (sanitised). Maximum decoded size: 5 MB. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The template UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "base64": { + "type": "string", + "description": "The base64 data URL." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/admin/widgets/with-rules": { + "get": { + "operationId": "admin-widget-rules-index", + "x-launchpad-stability": "internal", + "summary": "List every widget placement that carries at least one conditional rule", + "description": "List every widget placement that carries at least one conditional rule. Admin-only — the overview discloses every user's dashboard names and widget types, so it is gated with `#[AuthorizedAdminSetting]` like the rest of the Beheer surface (ADR-005). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "admin-widget-rules" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/analytics/me": { + "get": { + "operationId": "analytics-opt-out-show", + "x-launchpad-stability": "internal", + "summary": "Whether analytics is on for everyone, and whether the caller opted out", + "description": "Whether analytics is on for everyone, and whether the caller opted out. Needs a signed-in Nextcloud user.", + "tags": [ + "analytics-opt-out" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether analytics is on for everyone." + }, + "optedOut": { + "type": "boolean", + "description": "Whether the caller's visits are left out of the counts." + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + }, + "put": { + "operationId": "analytics-opt-out-update", + "x-launchpad-stability": "internal", + "summary": "Store the caller's own opt-out", + "description": "Store the caller's own opt-out. A request naming another user is refused. Needs a signed-in Nextcloud user.", + "tags": [ + "analytics-opt-out" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "optedOut": { + "type": "boolean", + "description": "`true` to stop counting the caller's visits." + }, + "userId": { + "type": [ + "string", + "null" + ], + "description": "A user id the request names; anything but the caller is refused." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether analytics is on for everyone." + }, + "optedOut": { + "type": "boolean", + "description": "Whether the caller's visits are left out of the counts." + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements": { + "get": { + "operationId": "announcement-index", + "x-launchpad-stability": "internal", + "summary": "`GET /api/announcements`: what the user sees now, their drafts when they author, and the categories they follow", + "description": "GET /api/announcements: the announcements the user sees now, their drafts when they author, and the categories they follow. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "announcement-create", + "x-launchpad-stability": "internal", + "summary": "`POST /api/announcements`: write a draft; 403 for someone who may not author", + "description": "POST /api/announcements: write a draft. Administrators and announcement editors only. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "kind": { + "description": "news or notice." + }, + "title": { + "description": "The title." + }, + "body": { + "description": "The text, in Markdown." + }, + "category": { + "description": "The category, or null." + }, + "level": { + "description": "info or warning, for a notice." + }, + "dismissible": { + "description": "Whether a reader may dismiss the notice." + }, + "targetGroups": { + "description": "Group ids; empty means everyone." + }, + "publishAt": { + "description": "When it becomes visible (ISO 8601)." + }, + "expiresAt": { + "description": "When it stops being visible (ISO 8601); required for a notice." + }, + "allowComments": { + "description": "Whether readers may comment." + } + } + } + } + }, + "required": false + } + } + }, + "/announcements/follows": { + "post": { + "operationId": "announcement-follow", + "x-launchpad-stability": "internal", + "summary": "`POST /api/announcements/follows`: follow a category", + "description": "`POST /api/announcements/follows`: follow a category. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "category": { + "description": "The category." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements/follows/{category}": { + "delete": { + "operationId": "announcement-unfollow", + "x-launchpad-stability": "internal", + "summary": "`DELETE /api/announcements/follows/{category}`: stop following a category", + "description": "`DELETE /api/announcements/follows/{category}`: stop following a category. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "category", + "in": "path", + "required": true, + "description": "The category.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements/groups": { + "get": { + "operationId": "announcement-groups-index", + "x-launchpad-stability": "internal", + "summary": "`GET /api/announcements/groups`: the groups the form offers as the target group", + "description": "GET /api/announcements/groups: the groups the announcement form offers as the target group, by display name. Announcement editors only. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement-groups" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements/reach": { + "get": { + "operationId": "announcement-reach", + "x-launchpad-stability": "internal", + "summary": "`GET /api/announcements/reach`: about how many people the target groups reach, for the preview", + "description": "GET /api/announcements/reach: about how many people the target groups reach, for the preview. Announcement editors only. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "groups", + "in": "query", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Target group ids." + }, + { + "name": "user", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements/read-state": { + "get": { + "operationId": "announcement-read-state", + "x-launchpad-stability": "internal", + "summary": "GET /api/announcements/read-state: the uuids among what the reader sees that the reader confirmed, and those whose read confirmations the reader may open", + "description": "GET /api/announcements/read-state: the uuids among what the reader sees that the reader confirmed, and those whose read confirmations the reader may open. Asked beside the list, not after it. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement-read" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements/{uuid}": { + "get": { + "operationId": "announcement-show", + "x-launchpad-stability": "internal", + "summary": "`GET /api/announcements/{uuid}`: one announcement; 404 when the user may not see it", + "description": "`GET /api/announcements/{uuid}`: one announcement; 404 when the user may not see it. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "announcement-update", + "x-launchpad-stability": "internal", + "summary": "`PUT /api/announcements/{uuid}`: change an announcement", + "description": "PUT /api/announcements/{uuid}: change an announcement. Its author or an administrator. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "kind": { + "description": "news or notice." + }, + "title": { + "description": "The title." + }, + "body": { + "description": "The text, in Markdown." + }, + "category": { + "description": "The category, or null." + }, + "level": { + "description": "info or warning, for a notice." + }, + "dismissible": { + "description": "Whether a reader may dismiss the notice." + }, + "targetGroups": { + "description": "Group ids; empty means everyone." + }, + "publishAt": { + "description": "When it becomes visible (ISO 8601)." + }, + "expiresAt": { + "description": "When it stops being visible (ISO 8601); required for a notice." + }, + "allowComments": { + "description": "Whether readers may comment." + } + } + } + } + }, + "required": false + } + }, + "delete": { + "operationId": "announcement-destroy", + "x-launchpad-stability": "internal", + "summary": "`DELETE /api/announcements/{uuid}`: delete an announcement", + "description": "DELETE /api/announcements/{uuid}: delete an announcement. Its author or an administrator. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements/{uuid}/comments": { + "get": { + "operationId": "announcement-comments", + "x-launchpad-stability": "internal", + "summary": "`GET /api/announcements/{uuid}/comments`: the comments on an announcement, oldest first", + "description": "GET /api/announcements/{uuid}/comments: the comments on an announcement that reaches the user, oldest first. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "post": { + "operationId": "announcement-comment", + "x-launchpad-stability": "internal", + "summary": "`POST /api/announcements/{uuid}/comments`: comment on an announcement that allows comments", + "description": "POST /api/announcements/{uuid}/comments: comment on an announcement that reaches the user and allows comments. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "message": { + "description": "The comment text." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/announcements/{uuid}/like": { + "post": { + "operationId": "announcement-like", + "x-launchpad-stability": "internal", + "summary": "`POST /api/announcements/{uuid}/like`: like an announcement", + "description": "POST /api/announcements/{uuid}/like: like an announcement that reaches the user; liking twice changes nothing. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "delete": { + "operationId": "announcement-unlike", + "x-launchpad-stability": "internal", + "summary": "`DELETE /api/announcements/{uuid}/like`: take back a like", + "description": "`DELETE /api/announcements/{uuid}/like`: take back a like. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/announcements/{uuid}/publish": { + "post": { + "operationId": "announcement-publish", + "x-launchpad-stability": "internal", + "summary": "`POST /api/announcements/{uuid}/publish`: publish after the preview; a notice without an end time is refused", + "description": "`POST /api/announcements/{uuid}/publish`: publish after the preview; a notice without an end time is refused. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements/{uuid}/read": { + "post": { + "operationId": "announcement-read-confirm", + "x-launchpad-stability": "internal", + "summary": "POST /api/announcements/{uuid}/read: \"I have read this\" for the signed-in reader, once", + "description": "POST /api/announcements/{uuid}/read: \"I have read this\" for the signed-in reader, once. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement-read" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/announcements/{uuid}/receipts": { + "get": { + "operationId": "announcement-read-receipts", + "x-launchpad-stability": "internal", + "summary": "GET /api/announcements/{uuid}/receipts: who confirmed and who has not yet, for the author or an administrator", + "description": "GET /api/announcements/{uuid}/receipts: who confirmed and who has not yet, for the author or an administrator. Needs a signed-in Nextcloud user.", + "tags": [ + "announcement-read" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The announcement.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/attention/sources": { + "get": { + "operationId": "attention-sources", + "x-launchpad-stability": "internal", + "summary": "The attention items the signed-in user's apps declare", + "description": "The attention items the signed-in user's apps declare. Any signed-in user may ask: the answer is what apps enabled for THIS user declare, and holds no object data. Needs a signed-in Nextcloud user.", + "tags": [ + "attention" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/catalogue": { + "get": { + "operationId": "catalogue-index", + "x-launchpad-stability": "internal", + "summary": "The entries the caller's groups may see", + "description": "The entries the caller's groups may see. The filter runs here, on the server; the client never filters for security (design D2). Needs a signed-in Nextcloud user.", + "tags": [ + "catalogue" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/catalogue/requests": { + "post": { + "operationId": "catalogue-request", + "x-launchpad-stability": "internal", + "summary": "Ask for an application the catalogue lacks", + "description": "Ask for an application the catalogue lacks. Needs a signed-in Nextcloud user.", + "tags": [ + "catalogue" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "appName": { + "type": [ + "string", + "null" + ], + "description": "The application." + }, + "purpose": { + "type": [ + "string", + "null" + ], + "description": "What the caller needs it for." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "429": { + "$ref": "#/components/responses/Problem429" + } + } + } + }, + "/colleague-activity": { + "get": { + "operationId": "colleague-activity-index", + "x-launchpad-stability": "internal", + "summary": "GET the recent activity of other people the caller may see: `limit` entries over `days` days", + "description": "GET what other people did recently, as the caller may see it: the caller's own activity stream from the activity app, without the caller's own actions, and without events on a dashboard the caller cannot see now. A left-out entry is absent, not redacted, and is not in any count. Needs a signed-in Nextcloud user.", + "tags": [ + "colleague-activity" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "required": false, + "description": "How many entries to list.", + "schema": { + "type": "integer" + } + }, + { + "name": "days", + "in": "query", + "required": false, + "description": "How many days back.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/dashboard": { + "get": { + "operationId": "dashboard-api-get-active", + "x-launchpad-stability": "public", + "summary": "Get the user's active dashboard with placements", + "description": "Get the user's active dashboard with placements. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadDashboardEnvelope" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "post": { + "operationId": "dashboard-api-create", + "x-launchpad-stability": "public", + "summary": "Create a new dashboard", + "description": "Create a new dashboard. The optional `widgets` request parameter picks what the dashboard starts with: `starters` for the first-run starter widgets, `none` for no widgets, anything else for the default bundle. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": {} + }, + { + "type": "null" + } + ], + "description": "The dashboard name; a legacy client sends the whole body under it." + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The description." + }, + "icon": { + "type": [ + "string", + "null" + ], + "description": "The icon registry key (or NULL/empty to use the default)." + }, + "parentUuid": { + "type": [ + "string", + "null" + ], + "description": "Optional parent dashboard UUID (REQ-DASH-023). NULL ⇒ root." + }, + "slug": { + "type": [ + "string", + "null" + ], + "description": "Optional caller-supplied slug (REQ-DASH-024). NULL ⇒ derive from the name." + }, + "sortOrder": { + "type": [ + "integer", + "null" + ], + "description": "Optional sibling sort order (REQ-DASH-029). NULL ⇒ 0." + }, + "widgets": {}, + "gridColumns": { + "type": "integer" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadCreatedDashboard" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboard/share/{shareId}": { + "delete": { + "operationId": "dashboard-share-api-destroy", + "x-launchpad-stability": "public", + "summary": "Remove a share by ID", + "description": "Remove a share by ID. REQ-SHARE-001. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-share-api" + ], + "parameters": [ + { + "name": "shareId", + "in": "path", + "required": true, + "description": "The share ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded; there is no body.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboard/{dashboardId}/tile": { + "post": { + "operationId": "widget-api-add-tile", + "x-launchpad-stability": "public", + "summary": "Add a tile to a dashboard", + "description": "Add a tile to a dashboard. Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "parameters": [ + { + "name": "dashboardId", + "in": "path", + "required": true, + "description": "Dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "type": "object", + "description": "The tile: its title, icon, colours, link type and link value." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadPlacement" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboard/{dashboardId}/tiles/import": { + "post": { + "operationId": "bookmark-import-import", + "x-launchpad-stability": "internal", + "summary": "Import chosen browser bookmarks onto a dashboard: each folder becomes a container of link tiles and each loose bookmark a tile, appended at the bottom", + "description": "Import chosen browser bookmarks onto a dashboard (launcher-bookmark-import REQ-BMI-001..003): each folder becomes a container of link tiles, each loose bookmark a tile, appended at the bottom. Addresses that are not http or https are skipped and listed back. The widget quota is checked for the whole import; nothing is created when it does not fit. Needs a signed-in Nextcloud user who may add to the dashboard. Needs a signed-in Nextcloud user.", + "tags": [ + "bookmark-import" + ], + "parameters": [ + { + "name": "dashboardId", + "in": "path", + "required": true, + "description": "Dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "folders": { + "type": "array" + }, + "bookmarks": { + "type": "array" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The placements were created; `skipped` lists the bookmarks that were not, with the reason.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "placements": { + "type": "array", + "items": {} + }, + "skipped": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "url": { + "type": "string" + }, + "reason": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + } + }, + "/dashboard/{dashboardId}/widgets": { + "post": { + "operationId": "widget-api-add-widget", + "x-launchpad-stability": "public", + "summary": "Add a widget to a dashboard", + "description": "Add a widget to a dashboard. Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "parameters": [ + { + "name": "dashboardId", + "in": "path", + "required": true, + "description": "Dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "widgetId": { + "type": "string", + "description": "Widget ID." + }, + "gridX": { + "type": "integer", + "description": "Grid X position." + }, + "gridY": { + "type": "integer", + "description": "Grid Y position." + }, + "gridWidth": { + "type": "integer", + "description": "Grid width." + }, + "gridHeight": { + "type": "integer", + "description": "Grid height." + }, + "content": { + "description": "The content." + }, + "isCompulsory": {} + } + } + } + } + }, + "responses": { + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadPlacement" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboard/{id}": { + "get": { + "operationId": "dashboard-api-show", + "x-launchpad-stability": "public", + "summary": "Get a single dashboard by id with its placements + permission level", + "description": "Get a single dashboard by id with its placements + permission level. Powers the front-end's `switchDashboard` flow: clicking a row in the sidebar issues `GET /api/dashboard/{id}` and the response is the same envelope shape as `self::getActive()`, so the store can write `activeDashboard`, `widgetPlacements`, and `permissionLevel` with no per-source branching. Returns 404 (not 403) when the dashboard exists but is not visible to the caller — this matches the `getVisibleToUser` policy and intentionally does not leak existence (REQ-DASH-020 scenario \"Cannot see what you cannot read\"). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadDashboardEnvelope" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "put": { + "operationId": "dashboard-api-update", + "x-launchpad-stability": "public", + "summary": "Update a dashboard", + "description": "Update a dashboard. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": [ + "string", + "null" + ], + "description": "The name." + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The description." + }, + "placements": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "object", + "additionalProperties": {} + } + }, + { + "type": "null" + } + ], + "description": "The placements." + }, + "icon": { + "type": [ + "string", + "null" + ], + "description": "The icon registry key, URL, or NULL to leave unchanged." + }, + "parentUuid": { + "type": [ + "string", + "null" + ], + "description": "Optional new parent UUID (REQ-DASH-023); explicit empty string clears the parent (re-roots the dashboard)." + }, + "slug": { + "type": [ + "string", + "null" + ], + "description": "Optional new slug (REQ-DASH-024)." + }, + "sortOrder": { + "type": [ + "integer", + "null" + ], + "description": "Optional new sort order (REQ-DASH-029). The optional `defaultLinkTarget` body field sets the default tile link target; an empty string clears it (`self::requestedLinkTarget()`). The optional `hierarchies` body field sets the hierarchy descriptors of the filter bus; an empty list clears them (REQ-CWF-011). The optional `gridColumns` body field sets the number of grid columns, 6, 8 or 12 (`self::requestedGridColumns()`, REQ-DASH-038). The look travels in the same body and is read by `self::lookParams()`: `themeAccent` and `themeBackgroundColor` (`#rrggbb`, empty to follow the theme, REQ-THM-001), `themeBackgroundResource` (a resource file name, empty for none) and `customCss` (administrator CSS, empty to clear, REQ-THM-003)." + }, + "hierarchies": { + "type": "array", + "description": "The hierarchy descriptors the filter bus joins widgets on (REQ-CWF-011), broadest level first; an empty list clears them. A malformed descriptor is refused with 400.", + "maxItems": 8, + "items": { + "type": "object", + "required": [ + "id", + "levels" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]{0,63}$" + }, + "levels": { + "type": "array", + "minItems": 1, + "maxItems": 8, + "items": { + "type": "object", + "required": [ + "dimension" + ], + "properties": { + "dimension": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9_.]{0,63}$" + }, + "label": { + "type": "string", + "maxLength": 128 + }, + "parentDimension": { + "type": [ + "string", + "null" + ], + "description": "The dimension of the level above; derived when left out." + } + } + } + } + } + } + }, + "gridColumns": { + "type": "integer" + }, + "defaultLinkTarget": { + "type": [ + "string", + "null" + ], + "description": "The default way the dashboard's tiles open; anything not a string is ignored." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dashboard": { + "$ref": "#/components/schemas/LaunchPadDashboard" + } + }, + "required": [ + "dashboard" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "delete": { + "operationId": "dashboard-api-delete", + "x-launchpad-stability": "public", + "summary": "Delete a dashboard", + "description": "Delete a dashboard. Honours the cascade-delete guard from REQ-DASH-030: when the dashboard has children the request MUST include `?cascade=true` (case-insensitive) — otherwise the response is HTTP 409 with the child count so the UI can surface a confirmation. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The dashboard ID.", + "schema": { + "type": "integer" + } + }, + { + "name": "cascade", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadStatusOk" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + } + }, + "/dashboard/{id}/activate": { + "post": { + "operationId": "dashboard-api-activate", + "x-launchpad-stability": "internal", + "summary": "Activate a dashboard", + "description": "Activate a dashboard. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboard/{id}/shares": { + "get": { + "operationId": "dashboard-share-api-index", + "x-launchpad-stability": "public", + "summary": "List all shares for a dashboard", + "description": "List all shares for a dashboard. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-share-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadShare" + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + }, + "put": { + "operationId": "dashboard-share-api-replace", + "x-launchpad-stability": "public", + "summary": "Atomically replace all shares for a dashboard", + "description": "Atomically replace all shares for a dashboard. REQ-SHARE-009. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-share-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "shares": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "object", + "properties": { + "shareType": { + "type": "string" + }, + "shareWith": { + "type": "string" + }, + "permissionLevel": { + "type": "string" + } + }, + "required": [ + "shareType", + "shareWith" + ], + "additionalProperties": false + } + }, + { + "type": "null" + } + ], + "description": "The new share list." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadShare" + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + }, + "post": { + "operationId": "dashboard-share-api-create", + "x-launchpad-stability": "public", + "summary": "Add or upsert a single share", + "description": "Add or upsert a single share. REQ-SHARE-001. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-share-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The dashboard ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "shareType": { + "type": [ + "string", + "null" + ], + "description": "The share type." + }, + "shareWith": { + "type": [ + "string", + "null" + ], + "description": "The recipient." + }, + "permissionLevel": { + "type": [ + "string", + "null" + ], + "description": "The permission level." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadShare" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards": { + "get": { + "operationId": "dashboard-api-list", + "x-launchpad-stability": "public", + "summary": "List all personal dashboards for the current user", + "description": "List all personal dashboards for the current user. Backward compatible — this endpoint never returns group-shared dashboards (REQ-DASH-014). Use `self::visible()` for the unioned listing. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "metadata", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/LaunchPadDashboardList" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadDashboard" + } + } + ] + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboards/active": { + "post": { + "operationId": "dashboard-api-set-active-dashboard", + "x-launchpad-stability": "internal", + "summary": "Persist the user's active-dashboard preference", + "description": "Persist the user's active-dashboard preference. Accepts any UUID string (including non-existent UUIDs — the resolver's stale-pref path handles invalid values on next render). Empty string clears the preference. REQ-DASH-019. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "uuid": { + "type": [ + "string", + "null" + ], + "description": "The dashboard UUID from the request body, or empty string to clear." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboards/by-path/{path}": { + "get": { + "operationId": "dashboard-api-by-path", + "x-launchpad-stability": "internal", + "summary": "GET /api/dashboards/by-path/{path} — resolve a slug-chain path (REQ-DASH-027)", + "description": "GET /api/dashboards/by-path/{path} — resolve a slug-chain path (REQ-DASH-027). Returns the matching dashboard with its computed `path` and `breadcrumbs` (REQ-DASH-025) attached. Responds with 404 (not 403) on any miss — including visibility misses — to avoid confirming that a given slug exists to an unauthorised caller. C2 fix (REQ-DASH-027 + REQ-PERM-001): after slug resolution the resolved dashboard is checked via PermissionService; callers with no view access receive the same 404 they would get for an unknown slug. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "path", + "in": "path", + "required": true, + "description": "The slug-joined path captured from the URL (the `{path}` placeholder is regex-allowed to include slashes — see `appinfo/routes.php`).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/default": { + "get": { + "operationId": "dashboard-api-get-default-dashboard", + "x-launchpad-stability": "internal", + "summary": "Read the user's EXPLICIT default-dashboard pin (wave3.7)", + "description": "Read the user's EXPLICIT default-dashboard pin (wave3.7). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "dashboard-api-set-default-dashboard", + "x-launchpad-stability": "internal", + "summary": "Pin (or clear) the user's EXPLICIT default-dashboard choice (wave3.7)", + "description": "Pin (or clear) the user's EXPLICIT default-dashboard choice (wave3.7). Distinct from `self::setActiveDashboard()` — this pref is only ever written when the user explicitly clicks \"Set as * default\" on a row's cog menu, and is NOT auto-overwritten on every switch. The resolver checks it before the active pref so the pin survives across switches. Body shape: `{uuid: string}` — empty string clears the pin. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "uuid": { + "type": [ + "string", + "null" + ], + "description": "The dashboard UUID, or empty string to clear." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboards/group/{groupId}": { + "get": { + "operationId": "dashboard-api-list-group", + "x-launchpad-stability": "internal", + "summary": "List the group-shared dashboards in a single group", + "description": "List the group-shared dashboards in a single group. Any logged-in user may list. REQ-DASH-014. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "groupId", + "in": "path", + "required": true, + "description": "The group ID.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "dashboard-api-create-group", + "x-launchpad-stability": "internal", + "summary": "Create a new group-shared dashboard", + "description": "Create a new group-shared dashboard. For a Nextcloud administrator, a LaunchPad Admin, or an Editor who is in the group (`GroupDashboardCreation::allows()`, REQ-DASH-014); anyone else gets HTTP 403 before the request body is read. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "groupId", + "in": "path", + "required": true, + "description": "The group ID.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The dashboard name (or {name,...} dict as the body)." + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The dashboard description." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/dashboards/group/{groupId}/default": { + "post": { + "operationId": "dashboard-api-set-group-default", + "x-launchpad-stability": "internal", + "summary": "Promote a single group-shared dashboard to the group's default", + "description": "Promote a single group-shared dashboard to the group's default. Admin-only — enforced by the `#[AuthorizedAdminSetting]` attribute. The body payload is `{\"uuid\": \"...\"}`. Returns 404 when the uuid does not belong to the given groupId. REQ-DASH-015. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "groupId", + "in": "path", + "required": true, + "description": "The group ID from the URL.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "uuid": { + "type": [ + "string", + "null" + ], + "description": "The dashboard UUID from the body." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/group/{groupId}/{uuid}": { + "get": { + "operationId": "dashboard-api-get-group", + "x-launchpad-stability": "internal", + "summary": "Get a single group-shared dashboard with placements", + "description": "Get a single group-shared dashboard with placements. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "groupId", + "in": "path", + "required": true, + "description": "The group ID from the URL.", + "schema": { + "type": "string" + } + }, + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "put": { + "operationId": "dashboard-api-update-group", + "x-launchpad-stability": "internal", + "summary": "Update a group-shared dashboard", + "description": "Update a group-shared dashboard. Admin-only. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "groupId", + "in": "path", + "required": true, + "description": "The group ID from the URL.", + "schema": { + "type": "string" + } + }, + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": [ + "string", + "null" + ], + "description": "The new name." + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The new description." + }, + "gridColumns": { + "type": [ + "integer", + "null" + ], + "description": "The new grid column count." + }, + "placements": { + "type": [ + "array", + "null" + ], + "description": "Updated placements." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "delete": { + "operationId": "dashboard-api-delete-group", + "x-launchpad-stability": "internal", + "summary": "Delete a group-shared dashboard", + "description": "Delete a group-shared dashboard. Admin-only. Returns HTTP 400 when the last-in-group guard rejects the delete (REQ-DASH-014). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "groupId", + "in": "path", + "required": true, + "description": "The group ID from the URL.", + "schema": { + "type": "string" + } + }, + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/tree": { + "get": { + "operationId": "dashboard-api-tree", + "x-launchpad-stability": "internal", + "summary": "GET /api/dashboards/tree — return the nested dashboard tree scoped to the calling user's visible dashboards (REQ-DASH-026)", + "description": "GET /api/dashboards/tree — return the nested dashboard tree scoped to the calling user's visible dashboards (REQ-DASH-026). Each node carries `{uuid, name, slug, sortOrder, children: [...]}`. Only nodes for dashboards that `DashboardService::getVisibleToUser` resolves for the caller are included — personal drafts owned by other users are not enumerable (C1 fix: REQ-DASH-026 + REQ-PERM-001). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboards/visible": { + "get": { + "operationId": "dashboard-api-visible", + "x-launchpad-stability": "public", + "summary": "List the deduplicated union of dashboards visible to the user", + "description": "List the deduplicated union of dashboards visible to the user. Returns personal + group-matching + default-group dashboards, each tagged with `source` (`'user'`, `'group'`, `'default'`). REQ-DASH-013. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "metadata", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "The metadata." + }, + { + "name": "path", + "in": "query", + "required": false, + "description": "The path.", + "schema": { + "type": "string" + } + }, + { + "name": "cascade", + "in": "query", + "required": false, + "description": "The cascade.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/LaunchPadDashboardList" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadDashboard" + } + } + ] + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{dashboardId}/personal-layer": { + "get": { + "operationId": "personal-layer-api-show", + "x-launchpad-stability": "internal", + "summary": "GET the caller's own layer on one dashboard", + "description": "GET the caller's own layer on one dashboard. Needs a signed-in Nextcloud user.", + "tags": [ + "personal-layer-api" + ], + "parameters": [ + { + "name": "dashboardId", + "in": "path", + "required": true, + "description": "The dashboard.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "put": { + "operationId": "personal-layer-api-save", + "x-launchpad-stability": "internal", + "summary": "PUT the caller's arrangement", + "description": "PUT the caller's arrangement. Needs a signed-in Nextcloud user.", + "tags": [ + "personal-layer-api" + ], + "parameters": [ + { + "name": "dashboardId", + "in": "path", + "required": true, + "description": "The dashboard.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "overrides": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": {} + }, + "description": "Per placement id, the keys they changed." + }, + "hidden": { + "type": "array", + "items": { + "type": "integer" + }, + "description": "The placement ids they want hidden." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "delete": { + "operationId": "personal-layer-api-reset", + "x-launchpad-stability": "internal", + "summary": "DELETE the caller's layer: the reset", + "description": "DELETE the caller's layer: the reset. Needs a signed-in Nextcloud user.", + "tags": [ + "personal-layer-api" + ], + "parameters": [ + { + "name": "dashboardId", + "in": "path", + "required": true, + "description": "The dashboard.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/filter-events/report": { + "get": { + "operationId": "filter-event-report-report", + "x-launchpad-stability": "internal", + "summary": "The report of one dashboard", + "description": "GET /api/dashboards/{uuid}/filter-events/report — the most-used drill-down paths of a dashboard, counted from its filter telemetry. A path is the sequence of filtered dimensions one user drilled through until a reset; it names dimensions only, never filter values. The dashboard's owner and administrators get every user's paths (scope `all`); another user who may view the dashboard gets only their own (scope `own`); anyone else gets 404. Needs a signed-in Nextcloud user.", + "tags": [ + "filter-event-report" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard's uuid.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "The most paths returned.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dashboardId": { + "type": "string" + }, + "scope": { + "type": "string", + "enum": [ + "all", + "own" + ] + }, + "events": { + "type": "integer" + }, + "paths": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "count": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/fork": { + "post": { + "operationId": "dashboard-api-fork", + "x-launchpad-stability": "internal", + "summary": "Fork any visible dashboard into a brand-new personal copy", + "description": "Fork any visible dashboard into a brand-new personal copy. REQ-DASH-020 / REQ-DASH-021 / REQ-DASH-022. Body shape: `{name?: string}` — when `name` is absent the system applies the default `t('My copy of {name}', source.name)` translated via the caller's active language. Status mapping: - HTTP 201 with the full new dashboard payload on success. - HTTP 401 when the session has no user. - HTTP 403 with stable error code `personal_dashboards_disabled` when the admin flag `allow_user_dashboards` is off — REQ-ASET-003 runtime gating runs FIRST so the envelope shape is stable regardless of body contents. - HTTP 404 when the source UUID is not visible to the caller — do not leak existence (REQ-DASH-020 scenario \"Cannot fork a * dashboard you cannot read\"). - HTTP 500 when a partial-failure rollback fires — REQ-DASH-021. ADR-005: the response carries a stable error code and a generic user-facing message; the underlying exception is logged for ops. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The source dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": [ + "string", + "null" + ], + "description": "Optional explicit fork name from the body." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/lock": { + "get": { + "operationId": "dashboard-lock-api-get", + "x-launchpad-stability": "internal", + "summary": "Query the current lock state", + "description": "Query the current lock state. Returns the lock object when active, or HTTP 404 when none exists. Stale rows are scrubbed inline by the service before the response. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-lock-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "put": { + "operationId": "dashboard-lock-api-heartbeat", + "x-launchpad-stability": "internal", + "summary": "Refresh the lock (heartbeat)", + "description": "Refresh the lock (heartbeat). Owner-only. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-lock-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "post": { + "operationId": "dashboard-lock-api-acquire", + "x-launchpad-stability": "internal", + "summary": "Acquire (or refresh) the lock for the given dashboard", + "description": "Acquire (or refresh) the lock for the given dashboard. Re-entrant for the same user — a second tab MUST receive HTTP 200 with the refreshed lock instead of HTTP 409 (REQ-LOCK-001). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-lock-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + }, + "delete": { + "operationId": "dashboard-lock-api-release", + "x-launchpad-stability": "internal", + "summary": "Release the lock", + "description": "Release the lock. Owner-or-admin. Idempotent — releasing a non-existent lock returns 204 (the caller's intent \"no longer holding the lock\" is satisfied). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-lock-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboards/{uuid}/lock/force-release": { + "post": { + "operationId": "dashboard-lock-api-force-release", + "x-launchpad-stability": "internal", + "summary": "Admin-only: force-release any user's lock (REQ-LOCK-006, design D4)", + "description": "Admin-only: force-release any user's lock (REQ-LOCK-006, design D4). The admin may then `acquire` normally if they want to take the lock themselves. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-lock-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboards/{uuid}/metadata": { + "get": { + "operationId": "dashboard-metadata-get-metadata", + "x-launchpad-stability": "internal", + "summary": "`GET /api/dashboards/{uuid}/metadata` — REQ-MDFL-004 / REQ-MDFL-008", + "description": "`GET /api/dashboards/{uuid}/metadata` — REQ-MDFL-004 / REQ-MDFL-008. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-metadata" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "put": { + "operationId": "dashboard-metadata-set-metadata", + "x-launchpad-stability": "internal", + "summary": "`PUT /api/dashboards/{uuid}/metadata` — REQ-MDFL-005 / REQ-MDFL-008", + "description": "`PUT /api/dashboards/{uuid}/metadata` — REQ-MDFL-005 / REQ-MDFL-008. Body: flat key-value object. Omitted keys are NOT removed; only keys present in the payload are upserted. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-metadata" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "metadata": { + "type": "object", + "additionalProperties": {}, + "description": "The patch payload." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/path": { + "get": { + "operationId": "dashboard-api-compute-path", + "x-launchpad-stability": "internal", + "summary": "GET /api/dashboards/{uuid}/path — return a dashboard's canonical slug-chain path", + "description": "GET /api/dashboards/{uuid}/path — return a dashboard's canonical slug-chain path. Used by the frontend after every sidebar switch to keep the browser URL in sync with the active dashboard. The path is the leading-slash slug-chain returned by `DashboardTreeService::computePath()`; an empty string means the UUID does not resolve OR the dashboard has no slug (legal — NULL slugs are simply unaddressable by path), and the frontend treats either case as \"leave the URL alone\". Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "Dashboard UUID captured from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboards/{uuid}/presence": { + "post": { + "operationId": "dashboard-presence-api-join", + "x-launchpad-stability": "internal", + "summary": "Announce or renew the caller's editing of a dashboard", + "description": "Announce or renew the caller's editing of a dashboard and answer the colleagues editing it, each with display name and start time (building-edit-a-dashboard-together). Needs edit rights on the dashboard and a signed-in Nextcloud user. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-presence-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "delete": { + "operationId": "dashboard-presence-api-leave", + "x-launchpad-stability": "internal", + "summary": "Withdraw the caller from a dashboard's editors", + "description": "Withdraw the caller from a dashboard's editors. Idempotent: 204. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-presence-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/dashboards/{uuid}/public-share": { + "post": { + "operationId": "public-share-create", + "x-launchpad-stability": "public", + "summary": "Create a new public share for a dashboard", + "description": "Create a new public share for a dashboard. Owner-or-admin only (REQ-PSHR-001). Needs a signed-in Nextcloud user.", + "tags": [ + "public-share" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "Dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "password": { + "type": [ + "string", + "null" + ], + "description": "Optional plaintext password." + }, + "expiresAt": { + "type": [ + "string", + "null" + ], + "description": "Optional ISO 8601 expiry." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LaunchPadPublicShare" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/public-shares": { + "get": { + "operationId": "public-share-index", + "x-launchpad-stability": "public", + "summary": "List active public shares for a dashboard", + "description": "List active public shares for a dashboard. Owner-or-admin only (REQ-PSHR-002). Needs a signed-in Nextcloud user.", + "tags": [ + "public-share" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "Dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadPublicShare" + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/public-shares/{id}": { + "delete": { + "operationId": "public-share-destroy", + "x-launchpad-stability": "public", + "summary": "Soft-revoke a public share", + "description": "Soft-revoke a public share. Owner-or-admin only (REQ-PSHR-003). Idempotent — revoking an already-revoked share returns 204. Needs a signed-in Nextcloud user.", + "tags": [ + "public-share" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "Dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "id", + "in": "path", + "required": true, + "description": "Share ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded; there is no body.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/publish": { + "post": { + "operationId": "dashboard-api-publish", + "x-launchpad-stability": "internal", + "summary": "Publish a dashboard", + "description": "Publish a dashboard. REQ-DASH-032. Owner-or-admin gated at the service boundary; the route attribute is `#[NoAdminRequired]` because the in-body owner check is the actual authorization point (gate-semantic-auth). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/reactions": { + "get": { + "operationId": "dashboard-reaction-api-get-reactions", + "x-launchpad-stability": "internal", + "summary": "GET /api/dashboards/{uuid}/reactions — return the `{counts, mine, enabled}` summary", + "description": "GET /api/dashboards/{uuid}/reactions — return the `{counts, mine, enabled}` summary. REQ-RXN-003. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-reaction-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + }, + "post": { + "operationId": "dashboard-reaction-api-add-reaction", + "x-launchpad-stability": "internal", + "summary": "POST /api/dashboards/{uuid}/reactions — add the calling user's reaction", + "description": "POST /api/dashboards/{uuid}/reactions — add the calling user's reaction. Idempotent (REQ-RXN-001 scenario \"User re-posts the * same emoji\"). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-reaction-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "emoji": { + "type": "string", + "description": "The emoji to add (request body field)." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/reactions/{emoji}": { + "delete": { + "operationId": "dashboard-reaction-api-remove-reaction", + "x-launchpad-stability": "internal", + "summary": "DELETE /api/dashboards/{uuid}/reactions/{emoji} — remove the calling user's reaction", + "description": "DELETE /api/dashboards/{uuid}/reactions/{emoji} — remove the calling user's reaction. Idempotent (REQ-RXN-002). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-reaction-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "emoji", + "in": "path", + "required": true, + "description": "The emoji to remove.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/reactions/{emoji}/users": { + "get": { + "operationId": "dashboard-reaction-api-get-reactors-by-emoji", + "x-launchpad-stability": "internal", + "summary": "GET /api/dashboards/{uuid}/reactions/{emoji}/users — return the paginated list of reactors", + "description": "GET /api/dashboards/{uuid}/reactions/{emoji}/users — return the paginated list of reactors. REQ-RXN-004. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-reaction-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "emoji", + "in": "path", + "required": true, + "description": "The emoji.", + "schema": { + "type": "string" + } + }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Optional opaque cursor (offset).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/resolved": { + "get": { + "operationId": "dashboard-translation-api-resolved", + "x-launchpad-stability": "internal", + "summary": "GET /api/dashboards/{uuid}/resolved — resolve the dashboard's content for the viewer's locale", + "description": "GET /api/dashboards/{uuid}/resolved — resolve the dashboard's content for the viewer's locale. Optional `?lang=<code>` query parameter overrides the user's Nextcloud locale; in strict mode an unknown explicit lang returns 404 instead of falling back. REQ-DASH-039. Response shape: - `dashboard`: the dashboard entity payload - `translation`: the matched translation row - `availableLanguages`: sorted list of codes - `currentLanguage`: the matched code - `isFallback`: true when the primary fallback was used. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-translation-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "lang", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/schedule": { + "post": { + "operationId": "dashboard-api-schedule", + "x-launchpad-stability": "internal", + "summary": "Schedule a dashboard for automatic publication", + "description": "Schedule a dashboard for automatic publication. REQ-DASH-034. Body: `{\"publishAt\": \"2026-04-01T10:00:00Z\"}`. Returns 400 with an i18n-friendly error message when `publishAt` is missing, unparseable, or in the past; 403 when the actor is neither owner nor admin. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "publishAt": { + "type": [ + "string", + "null" + ], + "description": "The future ISO-8601 timestamp from the request body." + }, + "unpublishAt": { + "type": [ + "string", + "null" + ], + "description": "Optional take-down time (REQ-SCHEDUI-002)." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/translations": { + "get": { + "operationId": "dashboard-translation-api-list", + "x-launchpad-stability": "internal", + "summary": "GET /api/dashboards/{uuid}/translations — list every translation variant for a dashboard", + "description": "GET /api/dashboards/{uuid}/translations — list every translation variant for a dashboard. Returns 403 when the dashboard belongs to another user. REQ-DASH-038. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-translation-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "post": { + "operationId": "dashboard-translation-api-create", + "x-launchpad-stability": "internal", + "summary": "POST /api/dashboards/{uuid}/translations — create a new variant", + "description": "POST /api/dashboards/{uuid}/translations — create a new variant. Body: `{languageCode, name?, description?, widgetTreeJson?, copyFrom?}`. Returns 201 with the created entity. Maps duplicate-language conflicts to HTTP 409. REQ-DASH-040. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-translation-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "languageCode": { + "type": [ + "string", + "null" + ], + "description": "The language code from the body." + }, + "name": { + "type": [ + "string", + "null" + ], + "description": "The optional name." + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The optional description." + }, + "widgetTreeJson": { + "type": [ + "string", + "null" + ], + "description": "The optional widget tree JSON." + }, + "copyFrom": { + "type": [ + "string", + "null" + ], + "description": "Optional source language." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + } + }, + "/dashboards/{uuid}/translations/{lang}": { + "put": { + "operationId": "dashboard-translation-api-update", + "x-launchpad-stability": "internal", + "summary": "PUT /api/dashboards/{uuid}/translations/{lang} — update a variant", + "description": "PUT /api/dashboards/{uuid}/translations/{lang} — update a variant. Body: `{name?, description?, widgetTreeJson?}`. Returns 200 with the updated entity. REQ-DASH-041. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-translation-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "lang", + "in": "path", + "required": true, + "description": "The language code from the URL.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": [ + "string", + "null" + ], + "description": "Optional new name." + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "Optional new description." + }, + "widgetTreeJson": { + "type": [ + "string", + "null" + ], + "description": "Optional new widget tree JSON." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "delete": { + "operationId": "dashboard-translation-api-destroy", + "x-launchpad-stability": "internal", + "summary": "DELETE /api/dashboards/{uuid}/translations/{lang} — delete a variant", + "description": "DELETE /api/dashboards/{uuid}/translations/{lang} — delete a variant. Maps last-variant / primary-variant guards to HTTP 400. REQ-DASH-042. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-translation-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "lang", + "in": "path", + "required": true, + "description": "The language code from the URL.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/translations/{lang}/set-primary": { + "post": { + "operationId": "dashboard-translation-api-set-primary", + "x-launchpad-stability": "internal", + "summary": "POST /api/dashboards/{uuid}/translations/{lang}/set-primary — promote a variant to primary", + "description": "POST /api/dashboards/{uuid}/translations/{lang}/set-primary — promote a variant to primary. Idempotent. REQ-DASH-043. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-translation-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "lang", + "in": "path", + "required": true, + "description": "The language code from the URL.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/unpublish": { + "post": { + "operationId": "dashboard-api-unpublish", + "x-launchpad-stability": "internal", + "summary": "Unpublish a dashboard", + "description": "Unpublish a dashboard. REQ-DASH-033. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/dashboards/{uuid}/versions": { + "get": { + "operationId": "dashboard-version-api-list-versions", + "x-launchpad-stability": "internal", + "summary": "List the versions for a dashboard, newest-first (REQ-VERS-003)", + "description": "List the versions for a dashboard, newest-first (REQ-VERS-003). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-version-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + }, + "post": { + "operationId": "dashboard-version-api-create-version", + "x-launchpad-stability": "internal", + "summary": "Create an explicit snapshot (REQ-VERS-002)", + "description": "Create an explicit snapshot (REQ-VERS-002). Bypasses the 60-second debounce window. The optional `note` field is read from the request body. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-version-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "note": { + "type": [ + "string", + "null" + ], + "description": "Optional snapshot note (request body)." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/versions/{versionNumber}": { + "get": { + "operationId": "dashboard-version-api-fetch-version", + "x-launchpad-stability": "internal", + "summary": "Fetch a single snapshot body (REQ-VERS-004)", + "description": "Fetch a single snapshot body (REQ-VERS-004). Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-version-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "versionNumber", + "in": "path", + "required": true, + "description": "The version number.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/versions/{versionNumber}/restore": { + "post": { + "operationId": "dashboard-version-api-restore-version", + "x-launchpad-stability": "internal", + "summary": "Restore a snapshot (REQ-VERS-005)", + "description": "Restore a snapshot (REQ-VERS-005). Captures the pre-restore state as a new snapshot before applying the historical body. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-version-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "versionNumber", + "in": "path", + "required": true, + "description": "The version number to restore.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/dashboards/{uuid}/view-event": { + "post": { + "operationId": "dashboard-api-view-event", + "x-launchpad-stability": "internal", + "summary": "Record a dashboard view event (REQ-ANLT-002)", + "description": "Record a dashboard view event (REQ-ANLT-002). Authenticated users only — POST `{}` body. Returns HTTP 204 after the daily counter has been incremented. Short-circuits silently to 204 when the user has opted out (REQ-ANLT-004) or when global analytics is disabled (REQ-ANLT-005). Returns 404 when the dashboard does not exist. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-api" + ], + "parameters": [ + { + "name": "uuid", + "in": "path", + "required": true, + "description": "The dashboard UUID from the URL.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/embed-settings/telemetry": { + "get": { + "operationId": "embed-token-api-telemetry", + "x-launchpad-stability": "internal", + "summary": "Whether embed usage telemetry is collected", + "description": "GET /api/embed-settings/telemetry — whether embed usage telemetry is collected. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "put": { + "operationId": "embed-token-api-set-telemetry", + "x-launchpad-stability": "internal", + "summary": "Turn embed usage telemetry on or off", + "description": "PUT /api/embed-settings/telemetry — turn embed usage telemetry on or off; the change is audited. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether to collect." + } + }, + "required": [ + "enabled" + ] + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/embed-tokens": { + "get": { + "operationId": "embed-token-api-index", + "x-launchpad-stability": "internal", + "summary": "Every token's metadata", + "description": "GET /api/embed-tokens — every embed token's metadata, without JWT or hash. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "post": { + "operationId": "embed-token-api-create", + "x-launchpad-stability": "internal", + "summary": "Issue a token; the JWT is in this response and nowhere else", + "description": "POST /api/embed-tokens — issue an embed token; the JWT is in this response only (REQ-EMB-001). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The token name." + }, + "description": { + "description": "The description." + }, + "subject": { + "description": "{type: widget|dashboard, id, filterContext?}." + }, + "scope": { + "description": "{mode, allowedFilters, allowedActions}." + }, + "hostOrigins": { + "description": "The origins that may frame the embed." + }, + "tenantThemeId": { + "description": "The tenant theme." + }, + "tokenExpiresAt": { + "description": "ISO 8601 expiry, empty for none." + }, + "rateLimitPolicy": { + "description": "{requestsPerMinute, burstSize}." + } + } + } + } + }, + "required": false + } + } + }, + "/embed-tokens/{id}": { + "get": { + "operationId": "embed-token-api-show", + "x-launchpad-stability": "internal", + "summary": "One token's metadata, never its JWT or hash", + "description": "GET /api/embed-tokens/{id} — one embed token's metadata, without JWT or hash. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The token id.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "put": { + "operationId": "embed-token-api-update", + "x-launchpad-stability": "internal", + "summary": "Update a token's name, description or rate limit", + "description": "PUT /api/embed-tokens/{id} — update name, description or rate limit; subject, scope and origins never change. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The token id.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The token name." + }, + "description": { + "description": "The description." + }, + "rateLimitPolicy": { + "description": "{requestsPerMinute, burstSize}." + } + } + } + } + }, + "required": false + } + } + }, + "/embed-tokens/{id}/purge-cache": { + "post": { + "operationId": "embed-token-api-purge-cache", + "x-launchpad-stability": "internal", + "summary": "Make every render worker re-read the token now", + "description": "POST /api/embed-tokens/{id}/purge-cache — make every render worker re-read the token now. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The token id.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/embed-tokens/{id}/re-issue": { + "post": { + "operationId": "embed-token-api-reissue", + "x-launchpad-stability": "internal", + "summary": "Re-issue: revoke the token and issue a like one; the new JWT is shown once", + "description": "POST /api/embed-tokens/{id}/re-issue — revoke the token and issue a like one; the new JWT is shown once. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The token id.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/embed-tokens/{id}/revoke": { + "post": { + "operationId": "embed-token-api-revoke", + "x-launchpad-stability": "internal", + "summary": "Revoke a token", + "description": "POST /api/embed-tokens/{id}/revoke — revoke a token; render workers refuse it within 60 seconds (REQ-EMB-009). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The token id.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "The revocation reason." + }, + "notes": { + "type": [ + "string", + "null" + ], + "description": "Optional notes." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/embed-tokens/{id}/unrevoke": { + "post": { + "operationId": "embed-token-api-unrevoke", + "x-launchpad-stability": "internal", + "summary": "Clear a token's revocation", + "description": "POST /api/embed-tokens/{id}/unrevoke — accept a revoked token again. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The token id.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/embed-tokens/{id}/usage": { + "get": { + "operationId": "embed-token-api-usage", + "x-launchpad-stability": "internal", + "summary": "A token's usage over the last seven days, in aggregate", + "description": "GET /api/embed-tokens/{id}/usage — seven days of usage in aggregate, no row per visitor (REQ-EMB-008). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "embed-token-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The token id.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/exports": { + "get": { + "operationId": "scheduled-export-index", + "x-launchpad-stability": "internal", + "summary": "`GET /api/exports`: the caller's exports, sorted and paged", + "description": "`GET /api/exports`: the caller's exports, sorted and paged. Query parameters: `limit` (page size, 1-200, default 50), `offset` (rows to skip), `sort` (`name`, `nextRunAt` or `lastRunAt`) and `order` (`asc` or `desc`). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Page size, 1-200." + }, + { + "name": "offset", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Rows to skip." + }, + { + "name": "sort", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "name, nextRunAt or lastRunAt." + }, + { + "name": "order", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "asc or desc." + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "post": { + "operationId": "scheduled-export-create", + "x-launchpad-stability": "internal", + "summary": "`POST /api/exports`: create an export", + "description": "Create a scheduled export. An export is reachable by its owner or an administrator (scheduled-exports). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + }, + "/exports/{id}": { + "get": { + "operationId": "scheduled-export-show", + "x-launchpad-stability": "internal", + "summary": "`GET /api/exports/{id}`: one export", + "description": "Read one scheduled export. An export is reachable by its owner or an administrator (scheduled-exports). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "delete": { + "operationId": "scheduled-export-destroy", + "x-launchpad-stability": "internal", + "summary": "`DELETE /api/exports/{id}`: soft-delete an export", + "description": "Soft-delete a scheduled export. An export is reachable by its owner or an administrator (scheduled-exports). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "patch": { + "operationId": "scheduled-export-update", + "x-launchpad-stability": "internal", + "summary": "`PATCH /api/exports/{id}`: update fields of an export; a changed recurrence is rescheduled", + "description": "Update a scheduled export; a changed recurrence is rescheduled. An export is reachable by its owner or an administrator (scheduled-exports). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + }, + "/exports/{id}/preview": { + "post": { + "operationId": "scheduled-export-preview", + "x-launchpad-stability": "internal", + "summary": "`POST /api/exports/{id}/preview`: render for one recipient's filter context without delivering and without a run-row", + "description": "`POST /api/exports/{id}/preview`: render for one recipient's filter context without delivering and without a run-row. With a `format` the file itself is returned; without, every target as base64 JSON. Request parameters: `recipientId` (the recipient whose filter context applies; empty for none) and `format` (`pdf`, `png`, `csv` or `xlsx`; empty for every target). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + }, + { + "name": "recipientId", + "in": "query", + "required": false, + "description": "The recipient whose filter context applies.", + "schema": { + "type": "string" + } + }, + { + "name": "format", + "in": "query", + "required": false, + "description": "pdf, png, csv or xlsx; the file itself is returned.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "format": { + "type": "string" + }, + "recipientId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/exports/{id}/run": { + "post": { + "operationId": "scheduled-export-run", + "x-launchpad-stability": "internal", + "summary": "`POST /api/exports/{id}/run`: fire now as the caller; the schedule is not moved", + "description": "Run a scheduled export now (triggeredBy=manual). An export is reachable by its owner or an administrator (scheduled-exports). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/exports/{id}/runs": { + "get": { + "operationId": "scheduled-export-runs", + "x-launchpad-stability": "internal", + "summary": "`GET /api/exports/{id}/runs`: the run history, newest first, paged", + "description": "List the runs of a scheduled export, newest first. An export is reachable by its owner or an administrator (scheduled-exports). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Page size, 1-200.", + "schema": { + "type": "integer" + } + }, + { + "name": "offset", + "in": "query", + "required": false, + "description": "Rows to skip.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/exports/{id}/runs/{runId}": { + "get": { + "operationId": "scheduled-export-show-run", + "x-launchpad-stability": "internal", + "summary": "`GET /api/exports/{id}/runs/{runId}`: one run-row with every delivery", + "description": "Read one run of a scheduled export with every delivery. An export is reachable by its owner or an administrator (scheduled-exports). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + }, + { + "name": "runId", + "in": "path", + "required": true, + "description": "The run uuid.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/exports/{id}/runs/{runId}/retry": { + "post": { + "operationId": "scheduled-export-retry", + "x-launchpad-stability": "internal", + "summary": "`POST /api/exports/{id}/runs/{runId}/retry`: retry every delivery of the run that failed for good", + "description": "Retry every delivery of a run that failed for good. An export is reachable by its owner or an administrator (scheduled-exports). Needs a signed-in Nextcloud user.", + "tags": [ + "scheduled-export" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + }, + { + "name": "runId", + "in": "path", + "required": true, + "description": "The run uuid.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "422": { + "$ref": "#/components/responses/Problem422" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/files/create": { + "post": { + "operationId": "file-create-file", + "x-launchpad-stability": "internal", + "summary": "Handle `POST /api/files/create` (REQ-LBN-004)", + "description": "Handle `POST /api/files/create` (REQ-LBN-004). Needs a signed-in Nextcloud user.", + "tags": [ + "file" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "filename": { + "type": [ + "string", + "null" + ], + "description": "Leaf filename." + }, + "dir": { + "type": [ + "string", + "null" + ], + "description": "Target subdirectory (default `/`)." + }, + "content": { + "type": [ + "string", + "null" + ], + "description": "Bytes to write (default empty)." + }, + "overwrite": {} + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/health-ping/validate": { + "post": { + "operationId": "health-ping-validate", + "x-launchpad-stability": "internal", + "summary": "`POST /api/health-ping/validate`", + "description": "`POST /api/health-ping/validate`. Validates a candidate health-ping config before the author saves the placement (REQ-HPING-001 \"rejected at save time\" — host allow-list, fail-closed). Performs NO ping — only the allow-list check that `resolveForPlacement()` would apply. Needs a signed-in Nextcloud user.", + "tags": [ + "health-ping" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "config": { + "description": "The config." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/health-ping/{placementId}": { + "get": { + "operationId": "health-ping-show", + "x-launchpad-stability": "internal", + "summary": "`GET /api/health-ping/{placementId}`", + "description": "`GET /api/health-ping/{placementId}`. Returns the health badge for one placement. Returns 401 when anonymous, 403 when the caller may not view the underlying dashboard (REQ-HPING-003 \"Caller authorization\" — the ping is NEVER performed in that case), 404 when the placement does not exist or has no ping configured, else 200 with the badge (possibly `stale: true`). Needs a signed-in Nextcloud user.", + "tags": [ + "health-ping" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The widget placement id.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/iframe/framable": { + "post": { + "operationId": "iframe-check-framable", + "x-launchpad-stability": "internal", + "summary": "`POST /api/iframe/framable`", + "description": "`POST /api/iframe/framable`. Server-side check of whether a URL may actually be framed (REQ-IFRAME-003 \"graceful degradation\"). The browser cannot tell an `X-Frame-Options: DENY` / `frame-ancestors 'none'` refusal apart from a normal cross-origin embed, so the widget calls this on mount and shows the fallback card up front when the target refuses framing, instead of a permanently blank frame. Allow-list fail-closed; never leaks the target's response body. Needs a signed-in Nextcloud user.", + "tags": [ + "iframe" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { + "description": "The url." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/iframe/validate-url": { + "post": { + "operationId": "iframe-validate-url", + "x-launchpad-stability": "internal", + "summary": "`POST /api/iframe/validate-url`", + "description": "`POST /api/iframe/validate-url`. Validates a candidate iframe config before the author saves the placement (REQ-IFRAME-002 \"rejected at save time\" — host allow-list, fail-closed). Requires only an authenticated caller — the allow-list itself is admin-controlled, not per-user. Needs a signed-in Nextcloud user.", + "tags": [ + "iframe" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "config": { + "description": "The config." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/kiosk/playlists": { + "get": { + "operationId": "kiosk-index", + "x-launchpad-stability": "internal", + "summary": "List playlists visible to the caller", + "description": "List playlists visible to the caller. Own playlists for users, all playlists for admins (REQ-KIOSK-002). Needs a signed-in Nextcloud user.", + "tags": [ + "kiosk" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + }, + "post": { + "operationId": "kiosk-create", + "x-launchpad-stability": "internal", + "summary": "Create a kiosk playlist", + "description": "Create a kiosk playlist. Owner-or-admin per referenced dashboard (REQ-KIOSK-002). Needs a signed-in Nextcloud user.", + "tags": [ + "kiosk" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": [ + "string", + "null" + ], + "description": "Playlist name." + }, + "entries": { + "type": [ + "array", + "null" + ], + "description": "Entries [{dashboardUuid, dwellSeconds}, ...]." + }, + "refreshSeconds": { + "type": [ + "integer", + "null" + ], + "description": "Requested refresh interval." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/kiosk/playlists/{id}": { + "put": { + "operationId": "kiosk-update", + "x-launchpad-stability": "internal", + "summary": "Update a kiosk playlist", + "description": "Update a kiosk playlist. Owner-or-admin, re-validates every referenced dashboard (REQ-KIOSK-002). Needs a signed-in Nextcloud user.", + "tags": [ + "kiosk" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Playlist primary key.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": [ + "string", + "null" + ], + "description": "Playlist name." + }, + "entries": { + "type": [ + "array", + "null" + ], + "description": "Entries [{dashboardUuid, dwellSeconds}, ...]." + }, + "refreshSeconds": { + "type": [ + "integer", + "null" + ], + "description": "Requested refresh interval." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + }, + "delete": { + "operationId": "kiosk-destroy", + "x-launchpad-stability": "internal", + "summary": "Soft-revoke a kiosk playlist", + "description": "Soft-revoke a kiosk playlist. Owner-or-admin only, idempotent (REQ-KIOSK-002). Needs a signed-in Nextcloud user.", + "tags": [ + "kiosk" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Playlist primary key.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/livetile/connector/status": { + "get": { + "operationId": "live-tile-connector-status", + "x-launchpad-stability": "internal", + "summary": "`GET /api/livetile/connector/status`", + "description": "`GET /api/livetile/connector/status`. Reports whether the OpenConnector `dashboard-http-datasource` capability is currently available, so the config form can hide or disable `connector` source mode (REQ-LIVETILE-005). Requires only an authenticated caller — carries no placement-specific data. Needs a signed-in Nextcloud user.", + "tags": [ + "live-tile" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/livetile/validate-source": { + "post": { + "operationId": "live-tile-validate-source", + "x-launchpad-stability": "internal", + "summary": "`POST /api/livetile/validate-source`", + "description": "`POST /api/livetile/validate-source`. Validates a candidate source config before the author saves the placement (REQ-LIVETILE-002 \"rejected at save time\" — host allow-list, fail-closed). Performs NO fetch — only the allow-list / capability-probe checks that `resolveForPlacement()` would apply. Needs a signed-in Nextcloud user.", + "tags": [ + "live-tile" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "config": { + "description": "The config." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/livetile/{placementId}": { + "get": { + "operationId": "live-tile-show", + "x-launchpad-stability": "internal", + "summary": "`GET /api/livetile/{placementId}`", + "description": "`GET /api/livetile/{placementId}`. Returns the live-tile value for one placement. Returns 401 when anonymous, 403 when the caller may not view the underlying dashboard (REQ-LIVETILE-003 \"Caller authorization\" — the fetch is NEVER performed in that case), 404 when the placement does not exist, else 200 with the value (possibly `stale: true`). Needs a signed-in Nextcloud user.", + "tags": [ + "live-tile" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The widget placement id.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/manifest": { + "get": { + "operationId": "manifest-index", + "x-launchpad-stability": "internal", + "summary": "Build and return the v2 app manifest for the authenticated user", + "description": "Build and return the v2 app manifest for the authenticated user. Reads the user's dashboard objects from OpenRegister. Each object with a `slug` and `title` property becomes one page entry and one menu entry. Objects the user owns, plus objects explicitly granted to them via OpenRegister's per-object sharing primitive, are included. Route: GET /apps/launchpad/api/manifest. Needs a signed-in Nextcloud user.", + "tags": [ + "manifest" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/me/role": { + "get": { + "operationId": "admin-get-my-role", + "x-launchpad-stability": "internal", + "summary": "Return the calling user's effective LaunchPad role and source (REQ-ROLE-006)", + "description": "Return the calling user's effective LaunchPad role and source (REQ-ROLE-006). Available to any authenticated user. Response shape: `{role: string|null, source: string|null}`. Needs a signed-in Nextcloud user.", + "tags": [ + "admin" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/metadata-fields": { + "get": { + "operationId": "dashboard-metadata-fields", + "x-launchpad-stability": "internal", + "summary": "`GET /api/metadata-fields`: the field definitions, readable by any logged-in user, so a dashboard owner who is not an administrator can fill in the Details tab", + "description": "`GET /api/metadata-fields`: the field definitions, readable by any logged-in user, so a dashboard owner who is not an administrator can fill in the Details tab. Definitions only (key, label, type, options); no values of any dashboard. Writing definitions stays administrator-only in MetadataAdminController. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-metadata" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/office-tiles": { + "get": { + "operationId": "office-tiles-list", + "x-launchpad-stability": "internal", + "summary": "The pack's tiles for the signed-in person", + "description": "Handle `GET /api/office-tiles` (REQ-OFT-001): the office tile pack for the signed-in user, a \"New ...\" tile per file creator the server's office apps register and a tile per enabled office app. Needs a signed-in Nextcloud user with the `office-tiles.list` action. Needs a signed-in Nextcloud user.", + "tags": [ + "office-tiles" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/office-tiles/create": { + "post": { + "operationId": "office-tiles-create", + "x-launchpad-stability": "internal", + "summary": "Create a file in the signed-in person's own files from a creator's blank template", + "description": "Handle `POST /api/office-tiles/create` (REQ-OFT-002): create a file in the signed-in user's own files from an office app's blank template, under a free name (never overwriting). Needs a signed-in Nextcloud user with the `office-tiles.create` action. Needs a signed-in Nextcloud user.", + "tags": [ + "office-tiles" + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "creatorId": { + "type": "string", + "description": "The creator, as the pack names it." + }, + "name": { + "type": "string", + "description": "The file name without extension." + }, + "folder": { + "type": "string", + "description": "The folder (default /Documents)." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The file was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/openapi.json": { + "get": { + "operationId": "open-api-show", + "x-launchpad-stability": "internal", + "summary": "The OpenAPI document of this app, readable from any origin", + "description": "The OpenAPI document of this app, readable from any origin. The document describes the API, not its data, so it is public. Its `info.version` is the installed app version, which is also what every API response carries in `API-Version`. It needs no login.", + "tags": [ + "open-api" + ], + "security": [], + "responses": { + "200": { + "description": "The OpenAPI document.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + }, + "access-control-allow-origin": { + "description": "Always `*`.", + "schema": { + "type": "string", + "enum": [ + "*" + ] + } + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/people": { + "get": { + "operationId": "people-widget-get-users", + "x-launchpad-stability": "internal", + "summary": "GET /api/people", + "description": "GET /api/people. REQ-PPL-003: returns `{users, total, hasMore}`, offset-based pagination, capped at {@see PeopleWidgetService::MAX_LIMIT}. Request parameters: - `filters` JSON-encoded array of FilterObject entries (see REQ-PPL-002 / REQ-PPL-006). - `excludeDisabled` 1/0 boolean (default 1). - `showBirthdays` 1/0 boolean (default 1). - `sortBy` One of `displayName` (default), `group`, `recent-activity` (rejected with 400). - `limit` 1..100 (default 50). - `offset` >= 0 (default 0). Needs a signed-in Nextcloud user.", + "tags": [ + "people-widget" + ], + "parameters": [ + { + "name": "filters", + "in": "query", + "required": false, + "description": "JSON-encoded filter list.", + "schema": { + "type": "string" + } + }, + { + "name": "excludeDisabled", + "in": "query", + "required": false, + "description": "1 to exclude disabled users.", + "schema": { + "type": "integer" + } + }, + { + "name": "showBirthdays", + "in": "query", + "required": false, + "description": "1 to include birthdate field.", + "schema": { + "type": "integer" + } + }, + { + "name": "sortBy", + "in": "query", + "required": false, + "description": "Sort key.", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Page size. Not declared `int`: Nextcloud casts an int `limit` itself and answers a non-number with a 500 before this runs.", + "schema": { + "type": "integer" + } + }, + { + "name": "offset", + "in": "query", + "required": false, + "description": "Page offset.", + "schema": { + "type": "integer" + } + }, + { + "name": "q", + "in": "query", + "required": false, + "description": "Search text; 2 or more characters search the whole directory by name, email and profile fields (REQ-PEX-003).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/people/new": { + "get": { + "operationId": "new-colleagues-get-new", + "x-launchpad-stability": "internal", + "summary": "GET /api/people/new", + "description": "GET /api/people/new `{configured, since, until, users: [{id, displayName, startDate, starts}]}`, newest start first; the windows are clamped to 1..90 days back and 0..30 days ahead. Guarded by the same action as the people list. Needs a signed-in Nextcloud user.", + "tags": [ + "new-colleagues" + ], + "parameters": [ + { + "name": "since", + "in": "query", + "required": false, + "description": "Days back (default 30).", + "schema": { + "type": "integer" + } + }, + { + "name": "until", + "in": "query", + "required": false, + "description": "Days ahead (default 14).", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/personal-layer/hidden": { + "get": { + "operationId": "hidden-widgets-api-index", + "x-launchpad-stability": "internal", + "summary": "GET the widgets the caller hid, on every dashboard they may see", + "description": "GET the widgets the caller hid, on every dashboard they may see. Needs a signed-in Nextcloud user.", + "tags": [ + "hidden-widgets-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + }, + "delete": { + "operationId": "hidden-widgets-api-show-all", + "x-launchpad-stability": "internal", + "summary": "DELETE every hidden widget from the caller's layers: show all again", + "description": "DELETE every hidden widget from the caller's layers: show all again. Needs a signed-in Nextcloud user.", + "tags": [ + "hidden-widgets-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/personal-layer/hidden/{placementId}": { + "delete": { + "operationId": "hidden-widgets-api-show-again", + "x-launchpad-stability": "internal", + "summary": "DELETE one hidden widget from the caller's layer: show it again", + "description": "DELETE one hidden widget from the caller's layer: show it again. Needs a signed-in Nextcloud user.", + "tags": [ + "hidden-widgets-api" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The hidden placement.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/preferences/{key}": { + "get": { + "operationId": "preferences-get-preference", + "x-launchpad-stability": "internal", + "summary": "Read a per-user preference value", + "description": "Read a per-user preference value. Needs a signed-in Nextcloud user.", + "tags": [ + "preferences" + ], + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "description": "The preference key (kebab/alphanumeric).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + }, + "put": { + "operationId": "preferences-set-preference", + "x-launchpad-stability": "internal", + "summary": "Write a per-user preference value", + "description": "Write a per-user preference value. An empty value clears it. Needs a signed-in Nextcloud user.", + "tags": [ + "preferences" + ], + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "description": "The preference key (kebab/alphanumeric).", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "description": "The value to store (empty string clears it)." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/profile-fields/definitions": { + "get": { + "operationId": "profile-fields-get-definitions", + "x-launchpad-stability": "internal", + "summary": "The field definitions (administrators)", + "description": "The field definitions (administrators). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "profile-fields" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "profile-fields-save-definitions", + "x-launchpad-stability": "internal", + "summary": "Replace the field definitions (administrators)", + "description": "Replace the field definitions (administrators). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "profile-fields" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "fields": { + "type": [ + "array", + "null" + ], + "description": "The definitions." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/profile-fields/me": { + "get": { + "operationId": "profile-fields-get-own", + "x-launchpad-stability": "internal", + "summary": "The caller's own fields and values", + "description": "The caller's own fields and values. Each person reads only their own. Needs a signed-in Nextcloud user.", + "tags": [ + "profile-fields" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "profile-fields-save-own", + "x-launchpad-stability": "internal", + "summary": "Save the caller's own values", + "description": "Save the caller's own values. Each person writes only their own; LDAP fields stay read-only. Needs a signed-in Nextcloud user.", + "tags": [ + "profile-fields" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "values": { + "type": [ + "array", + "null" + ], + "description": "Map of field key to a string or a list of tags." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/reports": { + "get": { + "operationId": "report-api-index", + "x-launchpad-stability": "internal", + "summary": "GET the report gallery, each report with whether it can run here", + "description": "GET the shipped reports, each with whether it can run on this instance and the registers or schemas it misses. Needs a signed-in Nextcloud user.", + "tags": [ + "report-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/reports/{reportId}": { + "get": { + "operationId": "report-api-run", + "x-launchpad-stability": "internal", + "summary": "GET one report run; an unavailable report answers 200 with the missing names", + "description": "GET one report run with the declared parameters as query values. An unavailable report answers with the missing names. Needs a signed-in Nextcloud user.", + "tags": [ + "report-api" + ], + "parameters": [ + { + "name": "reportId", + "in": "path", + "required": true, + "description": "The report.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/reports/{reportId}/dashboard": { + "post": { + "operationId": "report-api-save", + "x-launchpad-stability": "internal", + "summary": "POST a report's result as a new dashboard owned by the caller", + "description": "POST a report's result as a new dashboard owned by the caller. Needs a signed-in Nextcloud user.", + "tags": [ + "report-api" + ], + "parameters": [ + { + "name": "reportId", + "in": "path", + "required": true, + "description": "The report.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/resources": { + "get": { + "operationId": "resource-serve-list-resources", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/resources` — list uploaded resources", + "description": "Handle `GET /api/resources` — list uploaded resources. Returns `{status: 'success', resources: [{name, url, size, modifiedAt}, …]}` ordered by `modifiedAt` descending. When the `resources/` folder does not yet exist (or any other read error occurs) the response is HTTP 200 with `{status: 'success', resources: []}` — never a 404. The returned `url` values point at the serve route added by `getResource`. Cache busting falls out of the `uniqid` suffix REQ-RES-004 puts on every filename — a logical asset change yields a new name and a fresh cache entry. Needs a signed-in Nextcloud user.", + "tags": [ + "resource-serve" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "resource-upload", + "x-launchpad-stability": "internal", + "summary": "Handle `POST /api/resources`", + "description": "Handle `POST /api/resources`. Reads the raw JSON body from `php://input`, asserts an admin caller, delegates to ResourceService, and maps the response (success or any typed exception) to the standardised envelope. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "resource" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/resources/upload": { + "post": { + "operationId": "resource-upload-multipart", + "x-launchpad-stability": "internal", + "summary": "Handle `POST /api/resources/upload` — raw multipart upload", + "description": "Handle `POST /api/resources/upload` — raw multipart upload. Accepts `multipart/form-data` with a single `file` entry and stores the raw bytes directly — no base64, so large images and GIFs never become a huge in-memory string in the browser. Admin-only, enforced both by the `AuthorizedAdminSetting` attribute and a defensive `assertAdmin()`. The response mirrors the base64 endpoint's `{status, url, name, size}` envelope. CSRF stays enforced (no `@NoCSRFRequired`): admin-only is not CSRF-safe — a logged-in admin lured to a hostile page could otherwise be made to POST a resource. The frontend uses `@nextcloud/axios`, which auto-sends the `requesttoken` header, so this is zero-cost. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "resource" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/role-feature-permissions": { + "get": { + "operationId": "role-feature-permission-api-list-permissions", + "x-launchpad-stability": "internal", + "summary": "GET /api/role-feature-permissions", + "description": "GET /api/role-feature-permissions. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "role-feature-permission-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "role-feature-permission-api-save-permission", + "x-launchpad-stability": "internal", + "summary": "POST /api/role-feature-permissions", + "description": "POST /api/role-feature-permissions. Body: `{name, description?, groupId, allowedWidgets, deniedWidgets?, priorityWeights?}`. Upsert keyed by `groupId`. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "role-feature-permission-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/role-feature-permissions/{id}": { + "delete": { + "operationId": "role-feature-permission-api-delete-permission", + "x-launchpad-stability": "internal", + "summary": "DELETE /api/role-feature-permissions/{id}", + "description": "DELETE /api/role-feature-permissions/{id}. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "role-feature-permission-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The row id.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "204": { + "description": "The request succeeded; there is no body.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/role-layout-defaults": { + "get": { + "operationId": "role-feature-permission-api-list-layout-defaults", + "x-launchpad-stability": "internal", + "summary": "GET /api/role-layout-defaults", + "description": "GET /api/role-layout-defaults. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "role-feature-permission-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "role-feature-permission-api-save-layout-default", + "x-launchpad-stability": "internal", + "summary": "POST /api/role-layout-defaults", + "description": "POST /api/role-layout-defaults. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "role-feature-permission-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "201": { + "description": "The resource was created.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/role-layout-defaults/{id}": { + "delete": { + "operationId": "role-feature-permission-api-delete-layout-default", + "x-launchpad-stability": "internal", + "summary": "DELETE /api/role-layout-defaults/{id}", + "description": "DELETE /api/role-layout-defaults/{id}. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "role-feature-permission-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The row id.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "204": { + "description": "The request succeeded; there is no body.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/rules/{ruleId}": { + "put": { + "operationId": "rule-api-update-rule", + "x-launchpad-stability": "internal", + "summary": "Update a conditional rule", + "description": "Update a conditional rule. C4 fix (REQ-PERM-001): the rule's owning placement is resolved and `verifyPlacementOwnership` is called before any mutation, mirroring the guard already present on `addRule`. Without this check any authenticated user could overwrite rules on other users' placements by iterating rule IDs. Needs a signed-in Nextcloud user.", + "tags": [ + "rule-api" + ], + "parameters": [ + { + "name": "ruleId", + "in": "path", + "required": true, + "description": "The rule ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ruleType": { + "type": [ + "string", + "null" + ], + "description": "The rule type." + }, + "ruleConfig": { + "type": [ + "array", + "null" + ], + "description": "The rule configuration." + }, + "isInclude": { + "type": [ + "boolean", + "null" + ], + "description": "Whether this is an include rule." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "delete": { + "operationId": "rule-api-delete-rule", + "x-launchpad-stability": "internal", + "summary": "Delete a conditional rule", + "description": "Delete a conditional rule. C4 fix (REQ-PERM-001): the rule's owning placement is resolved and `verifyPlacementOwnership` is called before the deletion, mirroring the guard already present on `addRule`. Without this check any authenticated user could permanently delete conditional display logic on other users' widget placements by iterating rule IDs. Needs a signed-in Nextcloud user.", + "tags": [ + "rule-api" + ], + "parameters": [ + { + "name": "ruleId", + "in": "path", + "required": true, + "description": "The rule ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/setup/action/{actionId}": { + "post": { + "operationId": "setup-run-action", + "x-launchpad-stability": "internal", + "summary": "Run a privileged server-side setup action", + "description": "Run a privileged server-side setup action. Admin-only by Nextcloud's default for an un-attributed method. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "setup" + ], + "parameters": [ + { + "name": "actionId", + "in": "path", + "required": true, + "description": "One of `install-demo-data` | `skip-demo-data`.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dataset": {} + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/setup/config": { + "post": { + "operationId": "setup-save-config", + "x-launchpad-stability": "internal", + "summary": "Persist the wizard's `choice` answer", + "description": "Persist the wizard's `choice` answer. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "setup" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/setup/status": { + "get": { + "operationId": "setup-status", + "x-launchpad-stability": "internal", + "summary": "Report per-step setup status for the wizard", + "description": "Report per-step setup status for the wizard. `completed` is deliberately TRUE: this app declares no REQUIRED step, so setup must never gate the app. The demo-data step is reported so the wizard can stop asking once it has an answer. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "setup" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/sharees": { + "get": { + "operationId": "dashboard-share-api-search-sharees", + "x-launchpad-stability": "internal", + "summary": "Search users and groups for the share autocomplete picker", + "description": "Search users and groups for the share autocomplete picker. REQ-SHARE-006. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-share-api" + ], + "parameters": [ + { + "name": "query", + "in": "query", + "required": false, + "description": "The search query.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/sharees/{shareType}/{shareWith}": { + "delete": { + "operationId": "dashboard-share-api-revoke-for-recipient", + "x-launchpad-stability": "internal", + "summary": "Revoke all shares the caller has granted to a specific recipient", + "description": "Revoke all shares the caller has granted to a specific recipient. REQ-SHARE-010. Needs a signed-in Nextcloud user.", + "tags": [ + "dashboard-share-api" + ], + "parameters": [ + { + "name": "shareType", + "in": "path", + "required": true, + "description": "The share type.", + "schema": { + "type": "string" + } + }, + { + "name": "shareWith", + "in": "path", + "required": true, + "description": "The recipient user/group ID.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/status-reports": { + "post": { + "operationId": "status-report-keep", + "x-launchpad-stability": "internal", + "summary": "POST a body of work (the SUBJECT_FIELDS) with the person's `health` rating and `summary`, each omitted to keep the computed one; keeps the report", + "description": "POST a body of work with the rating and summary a person chose, and keep the report in the launchpad register: the figures are computed again and always marked computed, the rating and the summary are marked written when they differ from the computed ones. Needs a signed-in Nextcloud user and OpenRegister (503 without it). Needs a signed-in Nextcloud user.", + "tags": [ + "status-report" + ], + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "register": { + "type": "string", + "description": "The register slug of the body of work." + }, + "schema": { + "type": "string", + "description": "The schema slug of its items." + }, + "title": { + "type": "string" + }, + "deadline": { + "type": "string", + "description": "YYYY-MM-DD." + }, + "filters": { + "type": "object" + }, + "statusProperty": { + "type": "string", + "description": "Default status." + }, + "closedValues": { + "type": "array", + "items": { + "type": "string" + } + }, + "dueProperty": { + "type": "string", + "description": "Default deadline." + }, + "health": { + "type": "string", + "enum": [ + "on-track", + "at-risk", + "off-track" + ] + }, + "summary": { + "type": "string" + } + } + } + } + }, + "required": true + } + } + }, + "/status-reports/draft": { + "post": { + "operationId": "status-report-draft", + "x-launchpad-stability": "internal", + "summary": "POST a body of work (the SUBJECT_FIELDS); answers the prefilled report, not kept", + "description": "POST a body of work (the objects of one schema in one register, optionally filtered) and get its status report prefilled, not kept: the figures (total, open, closed, overdue, share closed, days to the deadline), the health rating they give and a summary, each marked computed. The objects are read as the caller. Needs a signed-in Nextcloud user.", + "tags": [ + "status-report" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "register": { + "type": "string", + "description": "The register slug of the body of work." + }, + "schema": { + "type": "string", + "description": "The schema slug of its items." + }, + "title": { + "type": "string" + }, + "deadline": { + "type": "string", + "description": "YYYY-MM-DD." + }, + "filters": { + "type": "object" + }, + "statusProperty": { + "type": "string", + "description": "Default status." + }, + "closedValues": { + "type": "array", + "items": { + "type": "string" + } + }, + "dueProperty": { + "type": "string", + "description": "Default deadline." + } + } + } + } + }, + "required": true + } + } + }, + "/store/config": { + "get": { + "operationId": "store-get-config", + "x-launchpad-stability": "internal", + "summary": "Read the registry connection", + "description": "Read the registry connection. The token is reported as a boolean and never as a value. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "store" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "put": { + "operationId": "store-update-config", + "x-launchpad-stability": "internal", + "summary": "Write the registry connection", + "description": "Write the registry connection. An omitted key leaves the stored value alone, so a form can change the URL without resubmitting the token. An empty string clears the key. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "store" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/store/items": { + "get": { + "operationId": "store-search", + "x-launchpad-stability": "internal", + "summary": "Search the configured registry", + "description": "Search the configured registry. Signed-in rather than admin: browsing is how a user finds out what an administrator could install for them, and the response carries only normalised cards. The engine drops every remote property outside the descriptor's card map, so the registry URL and token never ride back. The guard is in the body rather than only in the attribute so an anonymous caller gets an explicit 401 instead of a login redirect into a fetch that expected JSON. Needs a signed-in Nextcloud user.", + "tags": [ + "store" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/store/items/{slug}/install": { + "post": { + "operationId": "store-install", + "x-launchpad-stability": "internal", + "summary": "Install one registry template into this instance", + "description": "Install one registry template into this instance. Administrative. An install writes dashboards from a third-party server into the instance, so it is gated exactly like the rest of LaunchPad's admin surface (ADR-005). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "store" + ], + "parameters": [ + { + "name": "slug", + "in": "path", + "required": true, + "description": "The remote item slug.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/store/items/{slug}/update": { + "post": { + "operationId": "store-update", + "x-launchpad-stability": "internal", + "summary": "Bring an installed register item to the register's newer version, in place", + "description": "Bring an installed register item to the register's newer version, in place. Administrative, like install (ADR-005): anyone else is refused with 403 by the attribute before this body runs. The dashboard keeps its id, shares and the widgets people added themselves. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "store" + ], + "parameters": [ + { + "name": "slug", + "in": "path", + "required": true, + "description": "The remote item slug.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/summary-mail/me": { + "get": { + "operationId": "summary-mail-show", + "x-launchpad-stability": "internal", + "summary": "The caller's frequency, and whether they have an email address", + "description": "The caller's frequency, and whether they have an email address. Needs a signed-in Nextcloud user.", + "tags": [ + "summary-mail" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + }, + "put": { + "operationId": "summary-mail-update", + "x-launchpad-stability": "internal", + "summary": "Store the caller's frequency", + "description": "Store the caller's frequency. Needs a signed-in Nextcloud user.", + "tags": [ + "summary-mail" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "frequency": { + "type": "string", + "description": "Off, daily or weekly." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/templates/gallery": { + "get": { + "operationId": "template-gallery", + "x-launchpad-stability": "internal", + "summary": "`GET /api/templates/gallery`: list the admin templates offered to the caller's groups, with the gallery metadata (REQ-TMPL-014, REQ-TMPL-018)", + "description": "`GET /api/templates/gallery`: list the admin templates offered to the caller's groups, with the gallery metadata (REQ-TMPL-014, REQ-TMPL-018). Query parameters: - `category` (string, optional): exact-match category filter. - `sort` (string, optional): `name` (default) or `updatedAt`. Available to every logged-in user. Returns a `{status: 'success', templates: [...]}` envelope with no widget bodies — gallery is a list view, not a render. Needs a signed-in Nextcloud user.", + "tags": [ + "template" + ], + "parameters": [ + { + "name": "category", + "in": "query", + "required": false, + "description": "Optional category filter.", + "schema": { + "type": "string" + } + }, + { + "name": "sort", + "in": "query", + "required": false, + "description": "Sort key (`name` or `updatedAt`).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/tenant-themes": { + "get": { + "operationId": "tenant-theme-api-index", + "x-launchpad-stability": "internal", + "summary": "Every theme, with the number of tokens using it", + "description": "GET /api/tenant-themes — every tenant theme, with how many embed tokens use it. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "tenant-theme-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + }, + "post": { + "operationId": "tenant-theme-api-create", + "x-launchpad-stability": "internal", + "summary": "Create a theme", + "description": "POST /api/tenant-themes — create a tenant theme; names, values, :root-only CSS and contrast are checked (REQ-EMB-005). Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "tenant-theme-api" + ], + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The theme name." + }, + "cssVariables": { + "description": "Custom properties, {\"--c-primary\": \"#0b5394\", ...}." + }, + "logoUrl": { + "description": "An https logo URL." + }, + "customCss": { + "description": "Extra CSS, :root rules only." + } + } + } + } + }, + "required": false + } + } + }, + "/tenant-themes/{id}": { + "put": { + "operationId": "tenant-theme-api-update", + "x-launchpad-stability": "internal", + "summary": "Replace a theme; tokens using it follow at once", + "description": "PUT /api/tenant-themes/{id} — replace a tenant theme; tokens using it follow at once. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "tenant-theme-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The theme id.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The theme name." + }, + "cssVariables": { + "description": "Custom properties, {\"--c-primary\": \"#0b5394\", ...}." + }, + "logoUrl": { + "description": "An https logo URL." + }, + "customCss": { + "description": "Extra CSS, :root rules only." + } + } + } + } + }, + "required": false + } + }, + "delete": { + "operationId": "tenant-theme-api-destroy", + "x-launchpad-stability": "internal", + "summary": "Delete a theme; one that tokens use only with `force`", + "description": "DELETE /api/tenant-themes/{id} — delete a tenant theme; one that tokens use only with force. Needs an administrator, or a user the matching admin setting is delegated to.", + "tags": [ + "tenant-theme-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The theme id.", + "schema": { + "type": "string" + } + }, + { + "name": "force", + "in": "query", + "required": false, + "description": "Delete even when tokens use it.", + "schema": { + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + }, + "503": { + "$ref": "#/components/responses/Problem503" + } + } + } + }, + "/tile-analytics/config": { + "get": { + "operationId": "tile-analytics-config", + "x-launchpad-stability": "internal", + "summary": "Handle `GET /api/tile-analytics/config`", + "description": "Handle `GET /api/tile-analytics/config`. Lets the frontend hook know whether tracking is currently active for the calling user, so it can suppress the fire-and- forget record call when analytics is globally disabled or the user has opted out — without re-implementing either gate client-side (REQ-TANLT-003). Needs a signed-in Nextcloud user.", + "tags": [ + "tile-analytics" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/tile-click/{placementId}": { + "post": { + "operationId": "tile-analytics-record-click", + "x-launchpad-stability": "internal", + "summary": "Handle `POST /api/tile-click/{placementId}` (REQ-TANLT-002)", + "description": "Handle `POST /api/tile-click/{placementId}` (REQ-TANLT-002). Authenticated users only — empty body. Returns HTTP 204 after the daily counter has been incremented (or short-circuited to a silent no-op per REQ-TANLT-003). Returns 404 when the placement does not exist. Needs a signed-in Nextcloud user.", + "tags": [ + "tile-analytics" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The widget-placement (tile) ID from the URL (numeric — enforced by the route `requirements`).", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/tiles": { + "get": { + "operationId": "tile-api-index", + "x-launchpad-stability": "public", + "summary": "List all tiles for the current user", + "description": "List all tiles for the current user. Read-only endpoint kept for backwards compatibility per the DEPRECATED REQ-TILE-001 spec — admin tooling and migration scripts may still inspect `oc_launchpad_tiles` rows during the deprecation window. The write endpoints return HTTP 410 Gone instead. Needs a signed-in Nextcloud user.", + "tags": [ + "tile-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadTile" + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "tile-api-create", + "x-launchpad-stability": "public", + "summary": "Create a new tile", + "description": "Create a new tile. DEPRECATED — returns HTTP 410 Gone. New tile placements MUST be created via the unified add-widget flow with `type: tile` (REQ-WDG-022 / REQ-TILE-PLACEMENT). Parameters retained for route binding compatibility only and intentionally ignored. Needs a signed-in Nextcloud user.", + "tags": [ + "tile-api" + ], + "responses": { + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "410": { + "description": "Gone.", + "content": { + "application/problem+json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "$ref": "#/components/schemas/LaunchPadGone" + } + ] + } + } + } + } + } + } + }, + "/tiles/discover": { + "get": { + "operationId": "tile-api-discover", + "x-launchpad-stability": "internal", + "summary": "The apps this server runs for the caller, to place as tiles", + "description": "The apps this server runs for the caller, to place as tiles. Answers only the caller's own app menu: there is no id parameter, so nothing to point at someone else (REQ-DISC-001). Placing a tile still goes through the dashboard's own add-tile check. Needs a signed-in Nextcloud user.", + "tags": [ + "tile-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/tiles/{id}": { + "put": { + "operationId": "tile-api-update", + "x-launchpad-stability": "public", + "summary": "Update a tile", + "description": "Update a tile. DEPRECATED — returns HTTP 410 Gone. Tile placement edits MUST go through the standard widget-placement update endpoint (REQ-WDG-022 / REQ-TILE-PLACEMENT). The legacy parameter list is preserved so existing routing wiring continues to bind without raising an `InvalidArgumentException`. Needs a signed-in Nextcloud user.", + "tags": [ + "tile-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The id." + } + ], + "responses": { + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "410": { + "description": "Gone.", + "content": { + "application/problem+json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "$ref": "#/components/schemas/LaunchPadGone" + } + ] + } + } + } + } + } + }, + "delete": { + "operationId": "tile-api-destroy", + "x-launchpad-stability": "public", + "summary": "Delete a tile", + "description": "Delete a tile. DEPRECATED — returns HTTP 410 Gone. Tile placement removal goes through the standard widget-placement delete endpoint going forward (REQ-WDG-022 / REQ-TILE-PLACEMENT). Needs a signed-in Nextcloud user.", + "tags": [ + "tile-api" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The id." + } + ], + "responses": { + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "410": { + "description": "Gone.", + "content": { + "application/problem+json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/Problem" + }, + { + "$ref": "#/components/schemas/LaunchPadGone" + } + ] + } + } + } + } + } + } + }, + "/tiles/{placementId}/rdp": { + "get": { + "operationId": "tile-launch-rdp", + "x-launchpad-stability": "internal", + "summary": "The `.rdp` file of a remote-desktop tile in RDP mode", + "description": "Returns the `.rdp` connection file of a remote-desktop tile in RDP mode, written from the tile's checked host, port, published program and gateway. The file never contains a user name or password. Returns 403 when the caller may not view the tile's dashboard and 404 when the placement is not a remote-desktop tile in RDP mode. Needs a signed-in Nextcloud user.", + "tags": [ + "tile-launch" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The tile's placement id.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The RDP connection file, as an attachment named after the tile.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/visibility/preview": { + "post": { + "operationId": "visibility-preview-preview", + "x-launchpad-stability": "internal", + "summary": "Preview the effective visibility of a supplied rule set for a supplied audience/date context", + "description": "Preview the effective visibility of a supplied rule set for a supplied audience/date context. Never writes to `oc_launchpad_conditional_rules` — the rules array in the request body is only ever materialised as transient, in-memory `ConditionalRule` entities passed straight into the evaluation pipeline and discarded at the end of the request. With `context.userId` the rules are evaluated as that person: their own groups and profile values, resolved server-side (\"View as\", REQ-CVUI-006). Viewing as someone other than yourself needs a `placementId` you may edit the rules of. The body may also carry `match` (`any`, the default, or `all`, REQ-VIS-014) and `placementId` (the placement whose rules are edited, needed to view as another person). Needs a signed-in Nextcloud user.", + "tags": [ + "visibility-preview" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "rules": { + "type": [ + "array", + "null" + ], + "description": "The candidate rule set: `[{id?, ruleType, ruleConfig, isInclude}, …]`." + }, + "context": { + "type": [ + "array", + "null" + ], + "description": "`{groups?: string[], datetime?: string, userId?: string}`." + }, + "match": {}, + "placementId": {} + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/weather/{placementId}": { + "get": { + "operationId": "weather-show", + "x-launchpad-stability": "internal", + "summary": "`GET /api/weather/{placementId}`", + "description": "`GET /api/weather/{placementId}`. Returns the weather reading for one placement. Returns 401 when anonymous, 403 when the caller may not view the underlying dashboard (REQ-WEATHER-001 \"Caller authorization\" — the fetch is NEVER performed in that case), 502 when resolution failed with no cached reading available, else 200 with the reading (possibly `stale: true`). Needs a signed-in Nextcloud user.", + "tags": [ + "weather" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The widget placement id.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "502": { + "$ref": "#/components/responses/Problem502" + } + } + } + }, + "/widgets": { + "get": { + "operationId": "widget-api-list-available", + "x-launchpad-stability": "internal", + "summary": "List all available Nextcloud widgets, filtered by the caller's role-feature permissions (REQ-RFP-001 / REQ-RFP-003)", + "description": "List all available Nextcloud widgets, filtered by the caller's role-feature permissions (REQ-RFP-001 / REQ-RFP-003). Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/widgets/calendar/calendars": { + "get": { + "operationId": "widget-api-calendars", + "x-launchpad-stability": "internal", + "summary": "List the current user's internal Nextcloud calendars so the calendar widget's config form can offer a picker instead of free-text principal URIs (REQ-CAL-002)", + "description": "List the current user's internal Nextcloud calendars so the calendar widget's config form can offer a picker instead of free-text principal URIs (REQ-CAL-002). Each entry carries the calendar key (the identifier `fetchInternalEvents` filters on), display name, and colour. Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/widgets/calendar/{placementId}/events": { + "get": { + "operationId": "widget-api-calendar-events", + "x-launchpad-stability": "internal", + "summary": "Get aggregated events for a calendar-widget placement", + "description": "Get aggregated events for a calendar-widget placement. Returns merged + sorted events from internal NC calendars and external ICS feeds configured on the placement. The date range is mandatory and is capped at one year in the controller as a defensive measure against runaway RRULE expansion. REQ-CAL-003. Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The placement ID.", + "schema": { + "type": "integer" + } + }, + { + "name": "from", + "in": "query", + "required": false, + "description": "ISO 8601 start.", + "schema": { + "type": "string" + } + }, + { + "name": "to", + "in": "query", + "required": false, + "description": "ISO 8601 end.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/widgets/files/{placementId}/contents": { + "get": { + "operationId": "files-widget-contents", + "x-launchpad-stability": "internal", + "summary": "`GET /api/widgets/files/{placementId}/contents`", + "description": "`GET /api/widgets/files/{placementId}/contents`. Returns the configured folder's contents as `{items: [...], nextCursor: ?string}`. Empty folder is HTTP 200 with `items: []`. Missing folder is HTTP 404. Read-denied folder is HTTP 403. Needs a signed-in Nextcloud user.", + "tags": [ + "files-widget" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The widget placement id.", + "schema": { + "type": "integer" + } + }, + { + "name": "currentPath", + "in": "query", + "required": false, + "description": "Sub-path inside the configured folder.", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Page size (capped server-side).", + "schema": { + "type": "integer" + } + }, + { + "name": "cursor", + "in": "query", + "required": false, + "description": "Opaque pagination cursor.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/widgets/files/{placementId}/files/{fileId}": { + "delete": { + "operationId": "files-widget-destroy", + "x-launchpad-stability": "internal", + "summary": "`DELETE /api/widgets/files/{placementId}/files/{fileId}`", + "description": "`DELETE /api/widgets/files/{placementId}/files/{fileId}`. Moves the supplied file into the user's trash bin. Needs a signed-in Nextcloud user.", + "tags": [ + "files-widget" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The widget placement id.", + "schema": { + "type": "integer" + } + }, + { + "name": "fileId", + "in": "path", + "required": true, + "description": "File id (must live inside the configured folder).", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/widgets/files/{placementId}/upload": { + "post": { + "operationId": "files-widget-upload", + "x-launchpad-stability": "internal", + "summary": "`POST /api/widgets/files/{placementId}/upload`", + "description": "`POST /api/widgets/files/{placementId}/upload`. Accepts `multipart/form-data` with one or more `files[]` entries and writes them into the placement-configured folder (or a sub-path of it, if `currentPath` is supplied). Needs a signed-in Nextcloud user.", + "tags": [ + "files-widget" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The widget placement id.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "currentPath": { + "type": "string", + "description": "Sub-path inside the configured folder." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + } + }, + "/widgets/items": { + "get": { + "operationId": "widget-api-get-items", + "x-launchpad-stability": "internal", + "summary": "Get widget items for specified widgets", + "description": "Get widget items for specified widgets. Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "parameters": [ + { + "name": "widgets", + "in": "query", + "required": false, + "description": "Array of widget IDs.", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum items per widget.", + "schema": { + "type": "integer" + } + }, + { + "name": "content", + "in": "query", + "required": false, + "description": "The content.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + } + }, + "/widgets/news/{placementId}/items": { + "get": { + "operationId": "widget-api-news-items", + "x-launchpad-stability": "internal", + "summary": "Fetch merged news widget items for a placement (REQ-NEWS-003)", + "description": "Fetch merged news widget items for a placement (REQ-NEWS-003). Validates the caller, clamps the limit, and delegates to `NewsWidgetService::getItemsForPlacement()`. The response shape is `{items: array, feedsFailed: int, failedUrls: array}` — the placement-level metadata filter is applied server-side (REQ-NEWS-007), and a placement that fails the filter responds with an empty items array (no HTTP fetch occurs). Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "Placement entity id.", + "schema": { + "type": "integer" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Optional caller cap (default 10, rejected when outside [1, 50]).", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/widgets/video/parse": { + "post": { + "operationId": "video-parse-parse", + "x-launchpad-stability": "internal", + "summary": "POST /api/widgets/video/parse", + "description": "POST /api/widgets/video/parse 200 `{isValid: true, sourceType, videoId, canonicalUrl}` for a usable URL; 400 `{isValid: false, error}` otherwise. Only a logged-in user is answered. Needs a signed-in Nextcloud user.", + "tags": [ + "video-parse" + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "videoUrl": { + "type": "string", + "description": "The URL as typed." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/widgets/video/{placementId}/file": { + "get": { + "operationId": "video-widget-file", + "x-launchpad-stability": "internal", + "summary": "GET /api/widgets/video/{placementId}/file", + "description": "GET /api/widgets/video/{placementId}/file 200 `{streamingUrl}` for a video the viewer can read; otherwise `{error}` with `not_found` (404), `not_video` (422), `not_accessible` (403) or `no_file` (400), never an address. Needs a signed-in Nextcloud user.", + "tags": [ + "video-widget" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The placement.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + }, + "/widgets/{placementId}": { + "put": { + "operationId": "widget-api-update-placement", + "x-launchpad-stability": "public", + "summary": "Update a widget placement", + "description": "Update a widget placement. Needs a signed-in Nextcloud user. A body with `calculatedFields` is checked first (structure, allowed functions, argument counts, types, cycles across the dashboard) and refused with 400 and a `CalculatedFieldError` when a field fails; the stored fields come back with `returnType` set. Server-mode fields are then written to the widget's OpenRegister source schema as read-only calculated properties. Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The placement ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": {}, + "ruleMatch": {}, + "calculatedFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CalculatedField" + } + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/LaunchPadPlacement" + }, + { + "type": "object", + "properties": { + "calculatedFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CalculatedField" + } + }, + "warnings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CalculatedFieldWarning" + }, + "description": "Present when a calculated field was saved differently from how it was sent." + } + } + } + ] + } + } + } + }, + "400": { + "description": "A calculated field was refused.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CalculatedFieldError" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + }, + "delete": { + "operationId": "widget-api-remove-placement", + "x-launchpad-stability": "public", + "summary": "Remove a widget placement", + "description": "Remove a widget placement. Needs a signed-in Nextcloud user. The calculated properties its server-mode fields own on the OpenRegister source schema are removed with it; when OpenRegister refuses, the placement is still removed and `warnings` says so. Needs a signed-in Nextcloud user.", + "tags": [ + "widget-api" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The placement ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/LaunchPadStatusOk" + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "example": "ok" + }, + "warnings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CalculatedFieldWarning" + } + } + } + } + ] + } + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/widgets/{placementId}/rules": { + "get": { + "operationId": "rule-api-get-rules", + "x-launchpad-stability": "internal", + "summary": "Get conditional rules for a widget placement", + "description": "Get conditional rules for a widget placement. Needs a signed-in Nextcloud user.", + "tags": [ + "rule-api" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The placement ID.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "post": { + "operationId": "rule-api-add-rule", + "x-launchpad-stability": "internal", + "summary": "Add a conditional rule to a widget placement", + "description": "Add a conditional rule to a widget placement. Needs a signed-in Nextcloud user.", + "tags": [ + "rule-api" + ], + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The placement ID.", + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ruleType": { + "type": [ + "string", + "null" + ], + "description": "The rule type." + }, + "ruleConfig": { + "type": [ + "array", + "null" + ], + "description": "The rule configuration." + }, + "isInclude": { + "type": "boolean", + "description": "Whether this is an include rule." + } + } + } + } + } + }, + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "401": { + "$ref": "#/components/responses/Problem401" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + } + }, + "/work-packages": { + "get": { + "operationId": "work-packages-index", + "x-launchpad-stability": "internal", + "summary": "GET the open work packages: the person's own (`scope=mine`) or a project's (`scope=project&project=<identifier>`), due date first", + "description": "GET the open work packages: the person's own (`scope=mine`) or a project's (`scope=project&project=<identifier>`), due date first. Needs a signed-in Nextcloud user.", + "tags": [ + "work-packages" + ], + "parameters": [ + { + "name": "scope", + "in": "query", + "required": false, + "description": "`mine` or `project`.", + "schema": { + "type": "string" + } + }, + { + "name": "project", + "in": "query", + "required": false, + "description": "The project identifier for scope `project`.", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "How many to list.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "$ref": "#/components/responses/Problem401" + } + } + } + } + }, + "components": { + "securitySchemes": { + "basic_auth": { + "type": "http", + "scheme": "basic", + "description": "A Nextcloud user name with an app password." + }, + "bearer_auth": { + "type": "http", + "scheme": "bearer", + "description": "A Nextcloud OAuth2 access token." + } + }, + "headers": { + "API-Version": { + "description": "The version of the API that answered, which is the installed app version.", + "schema": { + "type": "string", + "example": "1.0.0" + } + } + }, + "schemas": { + "Problem": { + "type": "object", + "description": "An RFC 9457 problem details document. The members the error already had are kept next to these.", + "properties": { + "type": { + "type": "string", + "description": "A URI reference that identifies the problem type.", + "example": "about:blank" + }, + "title": { + "type": "string", + "description": "A short summary of the problem type.", + "example": "Not Found" + }, + "status": { + "type": "integer", + "description": "The HTTP status code.", + "example": 404 + }, + "detail": { + "type": "string", + "description": "An explanation of this occurrence of the problem." + }, + "instance": { + "type": "string", + "description": "A URI reference that identifies this occurrence." + } + }, + "required": [ + "type", + "title", + "status" + ], + "additionalProperties": true + }, + "CalculatedField": { + "type": "object", + "description": "A calculated field of a widget placement: a formula over the widget's data, other calculated fields and other widgets on the dashboard, stored as its source text and its compiled AST.", + "required": [ + "name", + "compiledExpression" + ], + "properties": { + "id": { + "type": "string", + "description": "The field's id." + }, + "name": { + "type": "string", + "description": "The identifier other fields reference it by; unique on the widget." + }, + "label": { + "type": "string", + "description": "The column or series label." + }, + "expression": { + "type": "string", + "description": "The formula as written, e.g. `(revenue - refunds) / revenue * 100`." + }, + "compiledExpression": { + "type": "object", + "description": "The AST the editor's parser produced: nodes `literal`, `fieldRef` (`source` is `self` or `widget:<id>`), `calculatedRef`, `binary`, `unary`, `if` and `call`. The server checks it rather than re-parsing the text." + }, + "returnType": { + "type": "string", + "enum": [ + "number", + "string", + "boolean", + "date", + "duration", + "null" + ], + "description": "Set by the server's type check on save.", + "readOnly": true + }, + "evaluationMode": { + "type": "string", + "enum": [ + "client", + "server", + "both" + ], + "default": "client", + "description": "`client` evaluates in the browser; `server` and `both` also materialise the value on the widget's OpenRegister source schema." + }, + "serverComputedFieldId": { + "type": [ + "string", + "null" + ], + "readOnly": true, + "description": "The key of the calculated property on the source schema (`launchpad_<placement>__<name>`), null when the field is not materialised." + }, + "formatOptions": { + "type": "object", + "description": "Display formatting (number, date or duration), applied when the value is rendered only." + } + } + }, + "CalculatedFieldError": { + "type": "object", + "description": "Why a placement's calculated fields were refused; nothing is saved.", + "required": [ + "error", + "message" + ], + "properties": { + "error": { + "type": "string", + "enum": [ + "invalidField", + "invalidExpression", + "duplicateField", + "unknownFunction", + "functionNotAllowed", + "arityMismatch", + "functionSignature", + "typeError", + "cycleDetected" + ] + }, + "message": { + "type": "string" + }, + "field": { + "type": "string", + "description": "The field the error is about." + }, + "name": { + "type": "string", + "description": "The function, for function errors." + }, + "cycle": { + "type": "array", + "items": { + "type": "string" + }, + "description": "For `cycleDetected`: the cycle as `<widget>.<field>`, first node repeated at the end." + }, + "widgets": { + "type": "array", + "items": { + "type": "string" + }, + "description": "For `cycleDetected`: the widgets in the cycle." + } + } + }, + "CalculatedFieldWarning": { + "type": "object", + "description": "A save that went through with a change: a server-mode field stored as a client field (`downgraded_evaluation_mode`: it reads another register or schema, OpenRegister cannot evaluate it alike, or the source schema could not be updated), or calculated properties left on the schema of a removed widget (`server_fields_not_removed`).", + "properties": { + "warning": { + "type": "string", + "enum": [ + "downgraded_evaluation_mode", + "server_fields_not_removed" + ] + }, + "field": { + "type": "string" + }, + "reason": { + "type": "string" + } + } + }, + "LaunchPadDashboard": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "uuid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": [ + "string", + "null" + ] + }, + "icon": { + "type": [ + "string", + "null" + ] + }, + "type": { + "type": "string" + }, + "userId": { + "type": [ + "string", + "null" + ] + }, + "groupId": { + "type": [ + "string", + "null" + ] + }, + "gridColumns": { + "type": "integer" + }, + "permissionLevel": { + "type": [ + "string", + "null" + ] + }, + "isDefault": { + "type": "integer" + }, + "isActive": { + "type": "integer" + }, + "parentUuid": { + "type": [ + "string", + "null" + ] + }, + "slug": { + "type": [ + "string", + "null" + ] + }, + "sortOrder": { + "type": "integer" + }, + "publicationStatus": { + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "type": [ + "string", + "null" + ] + }, + "updatedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "uuid", + "name", + "description", + "icon", + "type", + "gridColumns", + "permissionLevel", + "isDefault", + "isActive", + "parentUuid", + "slug", + "sortOrder", + "publicationStatus", + "createdAt", + "updatedAt" + ], + "additionalProperties": true + }, + "LaunchPadPlacement": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "dashboardId": { + "type": "integer" + }, + "widgetId": { + "type": [ + "string", + "null" + ] + }, + "gridX": { + "type": "integer" + }, + "gridY": { + "type": "integer" + }, + "gridWidth": { + "type": "integer" + }, + "gridHeight": { + "type": "integer" + }, + "isCompulsory": { + "type": "integer" + }, + "isVisible": { + "type": "integer" + }, + "customTitle": { + "type": [ + "string", + "null" + ] + }, + "customIcon": { + "type": [ + "string", + "null" + ] + }, + "showTitle": { + "type": "integer" + }, + "sortOrder": { + "type": "integer" + }, + "version": { + "type": "integer" + }, + "createdAt": { + "type": [ + "string", + "null" + ] + }, + "updatedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "dashboardId", + "widgetId", + "gridX", + "gridY", + "gridWidth", + "gridHeight", + "isCompulsory", + "isVisible", + "customTitle", + "customIcon", + "showTitle", + "sortOrder", + "version", + "createdAt", + "updatedAt" + ], + "additionalProperties": true + }, + "LaunchPadQuota": { + "type": "object", + "properties": { + "maxDashboards": { + "type": "integer" + }, + "dashboardsUsed": { + "type": "integer" + }, + "maxWidgetsPerDashboard": { + "type": "integer" + } + }, + "required": [ + "maxDashboards", + "dashboardsUsed", + "maxWidgetsPerDashboard" + ], + "additionalProperties": false + }, + "LaunchPadDashboardList": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadDashboard" + } + }, + "quota": { + "$ref": "#/components/schemas/LaunchPadQuota" + } + }, + "required": [ + "items", + "quota" + ], + "additionalProperties": false + }, + "LaunchPadDashboardEnvelope": { + "type": "object", + "properties": { + "dashboard": { + "$ref": "#/components/schemas/LaunchPadDashboard" + }, + "placements": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadPlacement" + } + }, + "permissionLevel": { + "type": "string" + }, + "isOwner": { + "type": "boolean" + }, + "sharedBy": { + "type": [ + "string", + "null" + ] + }, + "hasVariants": { + "type": "boolean" + }, + "breadcrumbs": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": {} + } + } + }, + "required": [ + "dashboard", + "placements", + "permissionLevel", + "isOwner", + "sharedBy", + "hasVariants" + ], + "additionalProperties": false + }, + "LaunchPadCreatedDashboard": { + "type": "object", + "properties": { + "dashboard": { + "$ref": "#/components/schemas/LaunchPadDashboard" + }, + "placements": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LaunchPadPlacement" + } + } + }, + "required": [ + "dashboard", + "placements" + ], + "additionalProperties": false + }, + "LaunchPadShare": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "dashboardId": { + "type": "integer" + }, + "shareType": { + "type": "string" + }, + "shareWith": { + "type": "string" + }, + "permissionLevel": { + "type": "string" + }, + "createdAt": { + "type": [ + "string", + "null" + ] + }, + "updatedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "dashboardId", + "shareType", + "shareWith", + "permissionLevel", + "createdAt", + "updatedAt" + ], + "additionalProperties": true + }, + "LaunchPadPublicShare": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "dashboardUuid": { + "type": "string" + }, + "token": { + "type": "string" + }, + "url": { + "type": "string" + }, + "passwordRequired": { + "type": "boolean" + }, + "expiresAt": { + "type": [ + "string", + "null" + ] + }, + "createdBy": { + "type": "string" + }, + "createdAt": { + "type": [ + "string", + "null" + ] + }, + "revokedAt": { + "type": [ + "string", + "null" + ] + }, + "viewCount": { + "type": "integer" + }, + "lastViewedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "dashboardUuid", + "token", + "url", + "passwordRequired", + "expiresAt", + "createdBy", + "createdAt", + "revokedAt", + "viewCount", + "lastViewedAt" + ], + "additionalProperties": true + }, + "LaunchPadTile": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "userId": { + "type": "string" + }, + "title": { + "type": "string" + }, + "icon": { + "type": [ + "string", + "null" + ] + }, + "iconType": { + "type": [ + "string", + "null" + ] + }, + "backgroundColor": { + "type": [ + "string", + "null" + ] + }, + "textColor": { + "type": [ + "string", + "null" + ] + }, + "linkType": { + "type": "string" + }, + "linkValue": { + "type": "string" + }, + "createdAt": { + "type": [ + "string", + "null" + ] + }, + "updatedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "userId", + "title", + "icon", + "iconType", + "backgroundColor", + "textColor", + "linkType", + "linkValue", + "createdAt", + "updatedAt" + ], + "additionalProperties": true + }, + "LaunchPadGone": { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "gone" + }, + "message": { + "type": "string" + }, + "replacement": { + "type": "string" + } + }, + "required": [ + "status", + "message", + "replacement" + ], + "additionalProperties": false + }, + "LaunchPadImportSummary": { + "type": "object", + "properties": { + "importedDashboardCount": { + "type": "integer" + }, + "skippedDashboardCount": { + "type": "integer" + }, + "errors": { + "type": "array", + "items": {} + } + }, + "required": [ + "importedDashboardCount", + "skippedDashboardCount", + "errors" + ], + "additionalProperties": false + }, + "LaunchPadStatusOk": { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "ok" + } + }, + "required": [ + "status" + ], + "additionalProperties": true + } + }, + "responses": { + "Problem400": { + "description": "Bad request", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem401": { + "description": "Unauthorized", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem404": { + "description": "Not found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem409": { + "description": "Conflict", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem410": { + "description": "Gone.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem413": { + "description": "Content Too Large.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem422": { + "description": "Unprocessable Content.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem429": { + "description": "Too Many Requests.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem500": { + "description": "Internal server error", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem502": { + "description": "Bad gateway", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem503": { + "description": "Service Unavailable.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + } + } + } +} diff --git a/openspec/architecture/adr-002-permission-services-adr-022-exception.md b/openspec/architecture/adr-002-permission-services-adr-022-exception.md new file mode 100644 index 000000000..7da03b78c --- /dev/null +++ b/openspec/architecture/adr-002-permission-services-adr-022-exception.md @@ -0,0 +1,46 @@ +# ADR-002: The dashboard permission services are an ADR-022 documented exception + +- **Status:** Proposed (held for review) +- **Date:** 2026-11-03 +- **Sunset:** 2027-06-30 +- **Gate 23 rules:** 6 +- **Deciders:** Ruben van der Linde +- **Scope:** launchpad, permission checks on its own dashboards, placements and role features +- **References:** hydra ADR-022 (apps consume OpenRegister abstractions), exception clause. Hydra gate 23, `or-abstraction-anti-patterns`, rule 6 (`consume-or-rbac-fleet-wide`). `docs/architecture.md`, "Runtime-only OR consumption policy". `appinfo/info.xml` dependencies comment. + +## Context + +ADR-022 gives role-based access to OpenRegister objects to OpenRegister's rbac +scopes. Gate 23 rule 6 enforces that on file name: any `*Permission*Service.php` +or `*Authorization*Service.php` outside OpenRegister. Two launchpad files match: + +- `lib/Service/PermissionService.php` decides who may view, edit, add to and + share a dashboard, from the dashboard's owner, type, group and permission + level, and from the admin settings. +- `lib/Service/RoleFeaturePermissionService.php` decides which widgets a user's + groups may place, and seeds a new dashboard from the role layout defaults. + +Neither guards an OpenRegister object. Both read launchpad's own tables only +(`Db\Dashboard`, `Db\WidgetPlacement`, `Db\AdminSetting`, +`Db\RoleFeaturePermission`, `Db\RoleLayoutDefault`) and Nextcloud's group and +user managers. Launchpad is an OpenRegister-free app: it must boot and work on +an instance without OpenRegister, and `appinfo/info.xml` deliberately declares +no OpenRegister dependency. There are no OpenRegister objects here for rbac +scopes to cover. + +## Decision + +Per the ADR-022 exception clause, gate 23 suppresses these two paths under rule +6, the permission and authorization service name rule, and under no other rule. +The `Gate 23 rules: 6` line in the header tells the gate so. Every suppression +is printed on every gate run with this ADR named beside it. + +- `lib/Service/PermissionService.php` +- `lib/Service/RoleFeaturePermissionService.php` + +## When this ends + +The exception holds while dashboards and placements live in launchpad's own +tables. If they move into OpenRegister registers, these checks move to rbac +scopes in the same change and this ADR is withdrawn. The sunset date forces the +question to be asked again by then. diff --git a/openspec/architecture/adr-003-embed-themes-adr-022-exception.md b/openspec/architecture/adr-003-embed-themes-adr-022-exception.md new file mode 100644 index 000000000..7c92fea3b --- /dev/null +++ b/openspec/architecture/adr-003-embed-themes-adr-022-exception.md @@ -0,0 +1,56 @@ +# ADR-003: The embed theme classes are an ADR-022 documented exception + +- **Status:** Accepted (Ruben van der Linde, 23 Nov 2026) +- **Date:** 2026-11-23 +- **Sunset:** 2027-06-30 +- **Gate 23 rules:** 4 +- **Deciders:** Ruben van der Linde +- **Scope:** launchpad, the themes an embedded dashboard or widget takes from the website that embeds it +- **References:** hydra ADR-022 (apps consume OpenRegister abstractions), exception clause. Hydra gate 23, `or-abstraction-anti-patterns`, rule 4 (`consume-or-tenant-fleet-wide`). Capability `embedded-analytics`, REQ-EMB-005. ADR-002 of this repository, the same mechanism for rule 6. + +## Context + +ADR-022 gives tenancy (organisations, tenant boundaries, tenant lifecycle) to +OpenRegister. Gate 23 rule 4 enforces that on file name: any `Tenant*.php` +outside OpenRegister. Four launchpad files match: + +- `lib/Entity/TenantTheme.php` +- `lib/Service/Embed/TenantThemeService.php` +- `lib/Service/Embed/TenantThemeValidator.php` +- `lib/Controller/TenantThemeApiController.php` + +None of them is tenancy. A "tenant theme" is the brand of a website that embeds +a launchpad dashboard or widget (REQ-EMB-005): CSS variables, a logo and +`:root`-only CSS that an embed token points at. It decides how an embed looks, +never who may see what, and it isolates nothing. Access stays with the embed +token (REQ-EMB-001 to 004) and Nextcloud's own users. + +The themes are already stored the way ADR-022 asks: as OpenRegister objects of +the schema `tenant_theme` in launchpad's register, read and written through +OpenRegister's `ObjectService` by `lib/Service/Embed/EmbedObjectStore.php`. No +launchpad table, middleware or schema switch holds them. + +The only thing rule 4 sees is the word "Tenant" in the file names. Renaming the +classes would change no behaviour, while the API path `/api/tenant-themes`, the +token field `tenantThemeId` and the stored schema slug `tenant_theme` would keep +the word; the schema slug is stored data and does not change. + +## Decision + +Per the ADR-022 exception clause, gate 23 suppresses these four paths under rule +4, the tenant class name rule, and under no other rule. The `Gate 23 rules: 4` +line in the header tells the gate so. Every suppression is printed on every gate +run with this ADR named beside it. + +- `lib/Entity/TenantTheme.php` +- `lib/Service/Embed/TenantThemeService.php` +- `lib/Service/Embed/TenantThemeValidator.php` +- `lib/Controller/TenantThemeApiController.php` + +## When this ends + +The exception holds while an embed theme is a style record and not an +organisation. If embed themes come to belong to OpenRegister organisations (one +theme per organisation that embeds launchpad), the themes move onto the +organisation in the same change and this ADR is withdrawn. The sunset date +forces the question to be asked again by then. diff --git a/openspec/changes/2026-04-30-dashboard-sharing-followups/tasks.md b/openspec/changes/2026-04-30-dashboard-sharing-followups/tasks.md deleted file mode 100644 index 53e42a0c1..000000000 --- a/openspec/changes/2026-04-30-dashboard-sharing-followups/tasks.md +++ /dev/null @@ -1,101 +0,0 @@ -# Tasks — dashboard-sharing-followups - -## 0. Deduplication check - -- [ ] 0.1 Search `openspec/specs/` for any existing notification, bulk-share, or cascade specs that overlap with REQ-SHARE-008..013 - - Expected result: no overlap; the baseline `dashboard-sharing` spec (REQ-SHARE-001..007) is the only prior art, and this change extends it with additive requirements only -- [ ] 0.2 Search `lib/Service/` for any existing `NotificationService`, `BulkShareService`, or `CascadeService` that could be extended rather than creating new methods - - Expected result: `DashboardShareService` is the correct extension point; no parallel notification dispatch exists in the app -- [ ] 0.3 Confirm that OpenRegister's `NotificationService` is not applicable here — LaunchPad uses custom tables, not OR objects, so OR's notification path does not apply -- [ ] 0.4 Document findings in the PR description (even if "no overlap found") - -## 1. Notifier service - -- [ ] 1.1 Create `lib/Notification/Notifier.php` implementing `OCP\Notification\INotifier` - - `getID()` returns `'launchpad'` - - `getName()` returns `'LaunchPad'` (translatable) - - `prepare(INotification, $languageCode)` handles two subjects: `dashboard_shared`, `dashboard_ownership_transferred` - - For unknown subjects throw `\OCP\Notification\UnknownNotificationException` - - Use `IURLGenerator::linkToRouteAbsolute('launchpad.page.index')` plus a `?dashboard={uuid}` query for the deep link -- [ ] 1.2 Use `IFactory::get('launchpad')` for translations of the rendered strings: - - `dashboard_shared`: rich subject "{sharerDisplayName} shared **{dashboardName}** with you" + parsed message "{permissionLevel} access" - - `dashboard_ownership_transferred`: rich subject "**{dashboardName}** is now yours" + parsed message "Ownership transferred after the previous owner was removed" -- [ ] 1.3 Register the notifier in `lib/AppInfo/Application.php::register()` via `$context->registerNotifierService(Notifier::class)` -- [ ] 1.4 Add English and Dutch translation entries to `l10n/en.json` and `l10n/nl.json` for the two notification subjects and permission level labels ("Full access", "Add-only access", "View-only access") -- [ ] 1.5 Add unit test covering both subjects, English + Dutch locale - -## 2. Notification publishing - -- [ ] 2.1 Inject `OCP\Notification\IManager` into `DashboardShareService` -- [ ] 2.2 Extract a private `_persistShare(int $dashboardId, string $shareType, string $shareWith, string $level): array{share: DashboardShare, isNew: bool, isUpgrade: bool}` from the current `addShare` -- [ ] 2.3 Add a private `_notifyShared(DashboardShare $share, string $sharerUserId, string $dashboardName)` that: - - For `share_type='user'`: creates one `INotification` for that single recipient - - For `share_type='group'`: resolves group members at publish time via `IGroupManager` and creates one notification per current member, excluding the sharer - - Sets `setSubject('dashboard_shared', [sharerUserId, dashboardName, permissionLevel])` and `setObject('dashboard', (string) $dashboardId)` -- [ ] 2.4 The current `addShare()` becomes: `_persistShare(...)` THEN `_notifyShared(...)` only when `isNew === true || isUpgrade === true` (not on downgrades, not on no-op writes) -- [ ] 2.5 The `removeShare()` path does NOT publish anything (revocations are silent) -- [ ] 2.6 Add unit test: mock `IManager`, assert exactly one notification per fan-out target, assert no notification on level downgrade - -## 3. Bulk replace endpoint - -- [ ] 3.1 Add `DashboardShareService::replaceShares(int $dashboardId, array $shares, string $userId): array` that: - - Asserts caller is owner (throws 403 if not) - - Validates each entry's `shareType`, `shareWith`, `permissionLevel` - - Loads existing shares once - - In a single transaction: deletes shares not in payload, upserts the rest - - Returns the new full list - - Calls `_notifyShared` only for entries where `isNew === true || isUpgrade === true` -- [ ] 3.2 Add `DashboardShareApiController::replace(int $id, ?array $shares)` action with `#[NoAdminRequired]` attribute and per-object owner check (ADR-005 Rule 3) -- [ ] 3.3 Register route `PUT /api/dashboard/{id}/shares` in `appinfo/routes.php` -- [ ] 3.4 Add `replaceShares(dashboardId, shares)` to `src/services/api.js` -- [ ] 3.5 Update `DashboardConfigModal.vue`: replace the per-row immediate `addShare`/`removeShare` calls with a `pendingShares` data array. Save button posts via `replaceShares` and reloads. Cancel reverts to the server snapshot. Wrap the `await` call in `try/catch` with user-facing error feedback (ADR-004) -- [ ] 3.6 Add backend integration test covering: add+remove+upgrade in one PUT; idempotent re-PUT with same payload publishes 0 notifications; non-owner receives 403 - -## 4. Revoke-all-for-recipient - -- [ ] 4.1 Add `DashboardShareService::revokeAllForRecipient(string $shareType, string $shareWith, string $callerId): int` that: - - Joins `oc_launchpad_dashboard_shares` to `oc_launchpad_dashboards` on `dashboardId = id` filtered to `dashboards.user_id = callerId` - - Deletes all matching rows in one statement, returns the affected row count -- [ ] 4.2 Add `DashboardShareApiController::revokeForRecipient(string $shareType, string $shareWith)` with `#[NoAdminRequired]` attribute -- [ ] 4.3 Register route `DELETE /api/sharees/{shareType}/{shareWith}` in `appinfo/routes.php` -- [ ] 4.4 Add `revokeAllForRecipient(shareType, shareWith)` to `src/services/api.js` -- [ ] 4.5 No UI surface in this change — exposed for admin tools / scripted cleanup. Frontend wiring deferred. - -## 5. UserDeletedEvent listener with admin retention - -- [ ] 5.1 Create `lib/Listener/UserDeletedListener.php` implementing `IEventListener<UserDeletedEvent>` -- [ ] 5.2 Register in `lib/AppInfo/Application.php::register()` via `$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class)` -- [ ] 5.3 In `handle()`: - - Resolve `$userId = $event->getUser()->getUID()` - - **Step A**: delete every share where `share_type='user' AND share_with=$userId` (recipient cleanup) - - **Step B**: for every dashboard owned by `$userId`: - - Compute admin pool: load every share with `permission_level='full'`; for `user`-type entries the userId is added directly; for `group`-type entries, expand via `IGroupManager::get($groupId)->searchUsers('', 1000)` capped at 1000 per group - - Filter the admin pool to existing users (skip already-deleted accounts via `IUserManager::get`) - - **If pool is empty**: delete the dashboard, its placements, and its shares (existing `deleteDashboard` logic via `DashboardService`) - - **If pool is non-empty**: pick the new owner using the selection rule (task 5.4), transfer ownership, delete only the new owner's matching share row, publish a `dashboard_ownership_transferred` notification to them - - All Step B work runs in a single DB transaction per dashboard -- [ ] 5.4 New-owner selection rule (codified): - 1. Among `user`-type shares with `permission_level='full'`, take the one with the smallest `created_at` - 2. If none, expand the alphabetically-first `group`-type share's member list and pick the alphabetically-first uid still active - 3. If both fail (pool became empty between resolve and pick), fall through to delete -- [ ] 5.5 Add `DashboardShareService::transferOwnership(int $dashboardId, string $newUserId): void`: - - Updates the dashboard's `user_id` and stamps `updated_at` - - Deletes the share row that previously gave `newUserId` access - - All other shares are kept as-is -- [ ] 5.6 Increment Prometheus counter `launchpad_dashboards_orphaned_at_owner_deletion_total` on the delete path and `launchpad_dashboard_ownership_transferred_total` on the transfer path -- [ ] 5.7 Add unit tests: pool with one user share; pool with only group share; pool empty; group share where every member is also deleted; recipient (non-owner) deletion removes only their shares - -## 6. Optional one-shot data hygiene migration - -- [ ] 6.1 Create `lib/Migration/Version001006Date20260430130000.php` (`SimpleMigrationStep`) -- [ ] 6.2 In `postSchemaChange`, gated by admin setting `launchpad.cleanup_orphan_shares = true`: - - Find share rows where `share_type='user'` and the `share_with` uid no longer resolves via `IUserManager::get()` - - Find share rows where `share_type='group'` and the `share_with` group no longer resolves via `IGroupManager::get()` - - Delete those rows; emit a count to the migration output -- [ ] 6.3 Default the setting to `false` so no surprise deletions on federated environments - -## 7. Documentation + telemetry - -- [ ] 7.1 Update `docs/sharing.md` (create if missing) with the share lifecycle diagram, including the new ownership-transfer path -- [ ] 7.2 Confirm `launchpad_dashboards_orphaned_at_owner_deletion_total` and `launchpad_dashboard_ownership_transferred_total` Prometheus counters are exported via `GET /api/metrics` (ADR-006) -- [ ] 7.3 Update `openspec/specs/dashboard-sharing/spec.md` with the new REQ-SHARE-008..013 once the change is archived (post-merge step done by `/opsx-archive`) diff --git a/openspec/changes/add-dashboard-sharing-e2e-coverage/specs/dashboard-sharing/spec.md b/openspec/changes/add-dashboard-sharing-e2e-coverage/specs/dashboard-sharing/spec.md deleted file mode 100644 index ec74d34f5..000000000 --- a/openspec/changes/add-dashboard-sharing-e2e-coverage/specs/dashboard-sharing/spec.md +++ /dev/null @@ -1,35 +0,0 @@ -# Dashboard Sharing — E2E Coverage Delta - -## MODIFIED Requirements - -### Requirement: Owner-only share management (REQ-SHARE-001) - -Only the owner of a dashboard MUST be allowed to list, create, update, or delete shares on that dashboard. All share-management endpoints MUST return HTTP 403 for any caller that is not the dashboard owner, including users who themselves have a `full`-level share on the dashboard. The owner-driven sharing UI flow (open `DashboardConfigModal`'s Sharing tab, add a share, change its permission level, remove a share) MUST be covered by a real Playwright e2e test that drives the actual router → middleware → controller → Vue re-render path, not only by PHPUnit tests that call the controller/service directly. - -#### Scenario: Owner adds a share - -- GIVEN a logged-in user "alice" who owns dashboard id `5` -- WHEN she sends `POST /api/dashboard/5/shares` with body `{"shareType": "user", "shareWith": "bob", "permissionLevel": "view_only"}` -- THEN the system MUST insert a row in `oc_launchpad_dashboard_shares` with the four fields plus `createdAt = now()` -- AND respond with HTTP 201 and the new share's id, displayName, and serialized fields - -#### Scenario: Recipient cannot manage shares - -- GIVEN dashboard `5` is owned by "alice" and shared with "bob" at `full` level -- WHEN bob sends `POST /api/dashboard/5/shares` to add another recipient -- THEN the system MUST return HTTP 403 -- AND no share row MUST be created - -#### Scenario: Updating an existing share replaces, does not duplicate - -- GIVEN alice has shared dashboard `5` with "bob" at `view_only` -- WHEN she sends `POST /api/dashboard/5/shares` with the same `shareType` and `shareWith` but `permissionLevel: "full"` -- THEN the system MUST update the existing share row, not create a second one -- AND only one share row MUST exist for `(dashboardId=5, shareType=user, shareWith=bob)` - -#### Scenario: A user drives the full sharing flow through the browser - -- GIVEN alice is logged in and opens the config modal for a dashboard she owns -- WHEN she switches to the Sharing tab, searches for and adds "bob" at `view_only`, changes his permission level to `full`, then removes his share, and reloads the page -- THEN `tests/e2e/dashboard-sharing.spec.ts` MUST assert each step persists correctly end to end (the added share appears, the level change is reflected, the removal survives a reload) -- AND the spec's e2e-exclusion annotation MUST be scoped to only the scenarios (if any) that genuinely have no UI surface, not a blanket exclusion of the whole capability diff --git a/openspec/changes/add-dashboard-sharing-e2e-coverage/tasks.md b/openspec/changes/add-dashboard-sharing-e2e-coverage/tasks.md deleted file mode 100644 index f6e678d66..000000000 --- a/openspec/changes/add-dashboard-sharing-e2e-coverage/tasks.md +++ /dev/null @@ -1,49 +0,0 @@ -# Tasks — add-dashboard-sharing-e2e-coverage - -## New e2e spec - -- [ ] Task 1: Create `tests/e2e/dashboard-sharing.spec.ts` following the - fixture/auth setup convention used in `tests/e2e/nc-dashboard-widget.spec.ts` - or `tests/e2e/active-dashboard-resolution.spec.ts` (login as the admin - fixture user, or seed a second test user if the flow requires a real - distinct recipient). -- [ ] Task 2: Test 1 — "Owner adds a user share": create/open a personal - dashboard, open `DashboardConfigModal`, switch to the Sharing tab - (`data-test="config-panel-sharing"`), use the sharee `NcSelect` - (search + select) to add a user, save, and assert the new share appears - in `.dashboard-config__shares`. -- [ ] Task 3: Test 2 — "Owner changes a share's permission level": with an - existing share present, change its permission-level `NcSelect` value, - save, reload the modal, and assert the change persisted. -- [ ] Task 4: Test 3 — "Owner removes a share": click the remove-share - button (`Close` icon `NcButton`, `aria-label` "Remove share"), save, - reload, and assert the share no longer appears. -- [ ] Task 5: Test 4 (if feasible with the test fixture) — "Recipient sees - the shared dashboard": log in as the share recipient and confirm the - shared dashboard appears in their dashboard switcher with the correct - permission level enforced (read-only vs full, per REQ-SHARE-00x). - If a second seeded user is not available in the current e2e fixture, - use `test.skip(..., 'reason')` with a concrete, honest reason (matching - the house pattern already used elsewhere in `tests/e2e/`) rather than - silently omitting the scenario. - -## Spec annotation cleanup - -- [ ] Task 6: In `openspec/specs/dashboard-sharing/spec.md`, remove the - blanket `@e2e exclude all scenarios test PHP DashboardShareService REST - API — sharing UI modals not present in v1.0.5` line (line 64). -- [ ] Task 7: For each `### Requirement:` in the same spec, add either a - direct `@e2e tests/e2e/dashboard-sharing.spec.ts` reference (for the - scenarios covered by Tasks 2-5) or a specific, honest - `@e2e exclude <reason>` for any requirement that genuinely has no UI - surface (e.g. purely internal permission-ranking logic with no directly - observable UI state). - -## Verification - -- [ ] Task 8: Run `npx playwright test dashboard-sharing` and confirm all - new tests pass against a local dev instance. -- [ ] Task 9: Run the `gate-19`/`hydra-gate-e2e-coverage` check (or - `openspec/coverage-report.json` regeneration) against the diff and - confirm the `dashboard-sharing` capability's scenarios are no longer - flagged as blanket-excluded without per-scenario justification. diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/design.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/design.md deleted file mode 100644 index 7c9d6ee17..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/design.md +++ /dev/null @@ -1,200 +0,0 @@ -# Design: add-launchpad-discovered-and-spend-analytics - -## Context - -Specter's intelligence pass for launchpad produced 14 spec drafts (listed -in proposal.md → Why). Each draft was a context brief — feature -clusters, demand counts, and acceptance criteria — but none had been -authored as a launchpad capability spec. The 8 spend-analytics drafts -were budget-bucket fragments of a single procurement-spend surface; -the other 6 were each a discrete widget capability. - -launchpad's existing `openspec/specs/` contains 56 capability specs that -already cover: - -- the dashboard data model (`dashboards`, `widgets`, `tiles`, - `permissions`, `grid-layout`, `runtime-shell`, `initial-state-contract`), -- 17 built-in widget types (`calendar-widget`, `files-widget`, - `image-widget`, `link-button-widget`, `links-widget`, `menu-widget`, - `news-widget`, `people-widget`, `quicklinks-widget`, `text-display-widget`, - `video-widget`, `divider-widget`, `header-widget`, `label-widget`, - `container-widget`, `nc-dashboard-widget-proxy`, `legacy-widget-bridge`), -- the cross-app NC integration surface (`nc-unified-search-integration`, - `activity-feed-integration`, `legacy-widget-bridge`, - `nc-dashboard-widget-proxy`), -- admin/template/conditional features (`admin-settings`, `admin-roles`, - `admin-templates`, `conditional-visibility`, `role-based-content`, - `setup-wizard`, `dashboard-export-import`, `dashboard-versioning`, - `default-widget-bundle`). - -What's **missing** is a fleet-aware widget set: widgets that consume -data from sibling Conduction apps. The 7 new specs in this change all -slot into this gap. They follow the existing widget convention -(manifest entry → `widgetRegistry.js` entry → sub-form → renderer → -content JSON shape persisted on the placement), with the data source -shifted from "self-contained" (label/image/text/divider) or -"Nextcloud-native" (calendar/files/people/news) to "sibling-app -runtime GraphQL". - -## Reuse Analysis - -Every widget in this set composes existing capabilities — no new -launchpad infrastructure. The composition table: - -| Spec | Reuses (launchpad) | Consumes (cross-app, runtime only) | -|---|---|---| -| `launchpad-spend-analytics-widget` | `widgets`, `widget-add-edit-modal`, `widget-collision-placement`, `runtime-shell`, `permissions`, `conditional-visibility` | financeq GraphQL (transactions, vendors, budgets), procest GraphQL (procurement-cases), docudesk attachments via OR `object-interactions` | -| `launchpad-ai-dashboard-assistant` | `widgets`, `runtime-shell`, `initial-state-contract`, `widget-add-edit-modal` | openconnector LLM source (Ollama+Qwen per `feedback_llphant-ollama-think-false`); launchpad never talks to Ollama directly | -| `launchpad-compliance-audit-panel` | `widgets`, `widget-add-edit-modal`, `dashboards`, `permissions` | OR audit-trail-immutable + archival-destruction (ADR-022), shillinq retention-rule GraphQL, docudesk compliance evidence | -| `launchpad-file-access-widget` | `widgets`, `files-widget` (sibling pattern), `widget-add-edit-modal` | Nextcloud Files OCS API + WebDAV (no OR dep) | -| `launchpad-enterprise-security-access` | `widgets`, `admin-roles`, `role-based-content`, `permissions` | OR RBAC GraphQL (ADR-022), Nextcloud user_saml / TOTP provider status | -| `launchpad-meeting-calendar-actions` | `widgets`, `calendar-widget` (existing internal pattern) | Nextcloud Calendar DAV, decidesk meeting/agenda GraphQL | -| `launchpad-mobile-remote-access` | `widgets`, `responsive-grid-breakpoints` | None at runtime — this is a manifest-declaration spec | - -The OpenRegister abstractions consumed (ADR-022 column "Abstraction"): - -- **audit trail (immutable)** — `launchpad-compliance-audit-panel` -- **archival + destruction workflow** — `launchpad-compliance-audit-panel` -- **authorization RBAC** — `launchpad-enterprise-security-access` -- **schemas + objects (read-only over GraphQL)** — every widget that - surfaces sibling-app data goes through OR's GraphQL endpoint per the - pattern documented in the `feedback_launchpad-no-or-dependency` memory. -- **integration registry (ADR-019)** — `launchpad-file-access-widget` - reads `object-interactions` (files attached to dossier objects) via - the same registry pattern as `feedback_integration-registry-end-to-end`. - -The `@conduction/nextcloud-vue` shared library provides the runtime -GraphQL client + every UI primitive these widgets render -(`CnIndexPage`, `CnDataTable`, `CnFormDialog`, -`CnDetailGrid` per `feedback_vue-logic-in-ncvue.md`). No launchpad-local -GraphQL plumbing, no launchpad-local data tables. - -## Declarative-vs-imperative decision - -Per ADR-031, every requirement in this change set lands declaratively: - -- **No launchpad service classes.** launchpad already follows ADR-022 (no - install-time OR dep), so it cannot have lifecycle / aggregation / - notification services over OR objects in the first place — every - data surface is a runtime read. -- **Manifest entries** for each widget (`src/manifest.json` - `widgets[]` per ADR-024) — declarative. -- **`widgetRegistry.js` entries** per spec (`{ component, label, - defaults, requires }`) — declarative. -- **Per-widget content JSON shape** persisted on `oc_launchpad_widget_placements.content` — declarative. -- **Runtime queries** are GraphQL operation strings inside the - per-widget Vue components — declarative artefacts, no PHP service. - -The only PHP surface is launchpad's existing `WidgetService` (already -shipped, no change), and the existing API routes that serve widget -items. No new controllers, no new entities, no new mappers. - -`kind: config` per ADR-032 — the entire change set is JSON / spec -text. Implementation chains for each widget will be `kind: code` -when they land (Vue components + manifest JSON edits), but per ADR-032 -the spec change ships first, then per-widget chains follow. - -## Seed Data - -No seed data — launchpad holds no OR-backed schemas; the widgets in this -set are read-only consumers. The sibling apps (procest, decidesk, -shillinq, docudesk) already carry their own seed data per ADR-016. -For local screenshot/QA purposes the demo dashboard bundle -(`demo-data-showcases` spec) will gain a "spend analytics demo" -dashboard in the per-widget implementation chain, not here. - -## Cross-app data contract - -Each widget MUST follow the same runtime-only contract documented in -`feedback_launchpad-no-or-dependency.md`: - -1. The widget's manifest entry declares its data source under - `widgets[<id>].requires` as a soft requirement — never a hard - dependency in `manifest.dependencies`. -2. The renderer issues a GraphQL query through - `@conduction/nextcloud-vue` to the sibling app's OR-mounted - `/graphql` endpoint (or to Nextcloud DAV / OCS for native data). -3. If the endpoint returns 404 or an empty result, the widget MUST - render its empty-state without throwing. The widget MUST NOT - show a "this app is required" error — launchpad is the - always-available shell and the absence of a sibling app is a - normal runtime state. -4. The widget MUST NOT cache cross-app data beyond the Vue component's - own lifetime. Persistent caching is the sibling app's - responsibility. -5. Authorization is enforced by the sibling app's RBAC, not launchpad — - launchpad receives only what the viewer is allowed to see. - -## Spec-sizing decision (ADR-032) - -This change is `kind: config` end-to-end: - -- Files touched: 7 × `specs/<slug>/spec.md` + `proposal.md` + - `design.md` + `tasks.md` — all markdown. -- No `.php`, `.vue`, `.ts`, `.js` files in scope. -- Each per-widget implementation lands as a follow-up chain, where - chain spec 1 is the manifest + registry entry (`kind: config`, - small), chain spec 2 is the renderer + sub-form (`kind: code`, - small-medium), and chain spec 3 (if needed) wires the runtime - GraphQL client (`kind: code`, small). Per-widget chain planning - happens after this change is archived. - -## Mixed-spec rationale - -N/A — this change is pure `kind: config`. No thin-glue code edits. - -## Alternatives considered - -1. **Author the 8 spend-analytics drafts as 8 separate specs.** - Rejected. The drafts are budget-bucket fragments of the same - procurement-spend surface — splitting them would create 8 specs - for one widget and force the reviewer to follow cross-cutting - threads through artificial boundaries. - -2. **Land a shillinq spend-analytics spec instead of a launchpad one.** - Rejected. shillinq already owns the **data** (transactions, - vendors, budgets); launchpad owns the **dashboard surface**. The - capability the Specter drafts describe — "a widget on a - dashboard showing spend" — is a launchpad surface that consumes - shillinq data. Putting the spec in shillinq would force a - shillinq → launchpad dependency reversal that violates ADR-022's - abstractions hierarchy. - -3. **Defer the AI assistant spec until openconnector ships the LLM - provider plumbing.** Rejected. The AI assistant spec describes - the widget contract (input box + streamed output + tool calls) - and references the openconnector source by name; it does not - author the source. The widget can ship behind a feature flag if - the source is not yet present on the deployment, per the - empty-state contract above. - -4. **Author `launchpad-mobile-remote-access` as a runtime capability - instead of a manifest-declaration capability.** Rejected. launchpad - already ships responsive widget rendering via - `responsive-grid-breakpoints` and GridStack breakpoints; the gap - the Specter draft surfaces is the **manifest contract** for - declaring widget mobile-readiness so the workspace can fall - back to a stack layout when no mobile-ready widget is present. - That is a declaration, not a runtime addition. PWA / offline - work goes through a separate change. - -## See also - -- ADR-022 — apps consume OR abstractions (every widget here reads OR - via runtime GraphQL only). -- ADR-024 — app manifest fleet-wide adoption (the manifest is the - declaration surface for every widget in this set). -- ADR-031 — schema-declarative business logic (no launchpad services - added). -- ADR-032 — spec sizing + chained specs (this change is - `kind: config`; per-widget implementations chain as follow-ups). -- `feedback_launchpad-no-or-dependency.md` — the non-negotiable runtime - GraphQL rule. -- `feedback_vue-logic-in-ncvue.md` — UI primitives live in - `@conduction/nextcloud-vue`, not in launchpad. -- `feedback_shared-deps.md` — GraphQL client comes from nc-vue. -- `decidesk/src/manifest.json` — canonical Tier-4 manifest example - (launchpad will not match decidesk's `pages[]` shape but will mirror - its `widgets[]` shape). -- `feedback_integration-registry-end-to-end` — runtime registry - pattern (`launchpad-file-access-widget` follows the same shape). diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/proposal.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/proposal.md deleted file mode 100644 index f53a34953..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/proposal.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -kind: config -depends_on: [] -chain: [] ---- - -# Add launchpad discovered widgets + spend-analytics widget - -## Why - -Specter's intelligence pass for launchpad surfaced 14 spec drafts that have no -match in the existing `openspec/specs/` library. launchpad today ships widget -plumbing (`widgets`, `runtime-shell`, `dashboards`, `permissions`, -`tiles`, plus 17 per-type widgets) but no widgets that consume -operational data from sibling Conduction apps. The fleet ships that data -(shillinq finance, procest cases, decidesk meetings, docudesk -compliance), but a Nextcloud user landing on launchpad sees only the -generic widget bundle. This change adds the missing capabilities as -**widget specs** — launchpad's first-class extensibility surface — so the -fleet's cross-app value lands on the user's home page. - -Eight of the 14 drafts (`spend-analytics-reporting`, `-ai`, `-analytics-t1`, -`-analytics-t2`, `-document-management`, `-other-t1`, `-other-t2`, -`-other-t3`) all describe the same capability — a procurement / -financial-spend analytics surface with AI insights, drill-through, and -document attachment — fragmented into 8 budget-buckets by the -Specter generator. The drafts also carry a misleading `— Shillinq` -suffix because the cluster originated from the budgetq/shillinq -intelligence brief. They are consolidated into one launchpad widget spec -(`launchpad-spend-analytics-widget`) that frames the capability as a -launchpad widget consuming runtime GraphQL from financeq + procest + -docudesk — per `feedback_launchpad-no-or-dependency.md` launchpad MUST NOT -acquire an install-time dependency on OpenRegister or any sibling app. - -The remaining six drafts (`ai-dashboard-assistant`, -`compliance-audit-panel`, `dashboard-file-access`, -`enterprise-security-access`, `meeting-calendar-actions`, -`mobile-remote-access`) each describe a distinct launchpad widget surface -and become their own specs. - -## What Changes - -Seven net-new capability specs, all under the existing launchpad widget -convention (manifest-declared, GridStack-rendered, `widgetRegistry` -entry, sub-form + renderer, runtime GraphQL/DAV for cross-app data). -No code, no schemas, no service classes — this is a `kind: config` -spec set that lands behaviour as manifest declarations and capability -contracts. Implementation lands in follow-up chains, one per widget. - -### New Capabilities - -- **launchpad-spend-analytics-widget** — spend-analytics dashboard widget - consuming runtime GraphQL from financeq + procest, with AI-assisted - insights, drill-through, and docudesk-attached evidence. - Consolidates 8 Specter drafts. -- **launchpad-ai-dashboard-assistant** — embedded AI assistant widget - surface: summary generation + natural-language queries, consuming - the established Conduction local-LLM plumbing (Ollama/Qwen via - openconnector) per ADR-022; launchpad does NOT host its own LLM client. -- **launchpad-compliance-audit-panel** — compliance posture widget - showing BIO/ISO/AVG status, audit-trail summary, retention - disposition counts. Runtime GraphQL from openregister (audit-trail, - archival-destruction) + shillinq (Archiefwet retention) + docudesk. -- **launchpad-file-access-widget** — file browser / quick-access widget - surfacing Nextcloud Files objects (typically dossier documents). - Consumes the Nextcloud Files API per Nextcloud convention; no - file storage in launchpad. -- **launchpad-enterprise-security-access** — read-only security/access - panel surfacing role assignments, SSO status, MFA enforcement. - Consumes OR's RBAC abstraction per ADR-022. -- **launchpad-meeting-calendar-actions** — meeting + calendar actions - widget surfacing upcoming meetings from Nextcloud Calendar (DAV) - + decidesk meetings/agendas (runtime GraphQL). -- **launchpad-mobile-remote-access** — responsive-widget + PWA capability - declarations spec. Widget authors declare mobile-readiness in the - manifest per ADR-024; this spec defines the contract. - -### Modified Capabilities - -(none — every requirement is net-new under a net-new capability slug; -the existing `widgets` spec stays untouched as the generic widget -shell, and these specs sit as peers, each describing one new -manifest-declared widget type.) - -## Impact - -**Affected docs:** - -- `openspec/specs/launchpad-*/spec.md` — 7 new capability specs. -- `openspec/changes/add-launchpad-discovered-and-spend-analytics/` — this - proposal + design + tasks (delivered together to give Hydra a - ready-to-build envelope when the implementation chain is split out). - -**Affected code:** - -- (deferred to per-spec implementation chains) `src/manifest.json` - widget registry entries, `src/constants/widgetRegistry.js`, - per-widget sub-form + renderer components, runtime GraphQL - clients in `src/services/graphql/`. Each widget becomes its own - chain spec per ADR-032 (this proposal stays declarative). - -**Affected APIs:** - -- (deferred to per-spec implementation chains) every widget added by - this set is a **read-only consumer** of existing APIs on sibling - apps. No new endpoints on launchpad. Runtime GraphQL endpoints - consumed: `/graphql` on openregister (and via OR on every sibling - app that exposes a register), Nextcloud Calendar DAV, Nextcloud - Files OCS API. - -**Dependencies:** - -- **No new install-time dependencies.** Per - `feedback_launchpad-no-or-dependency.md` + ADR-024 §10, launchpad's - `manifest.dependencies` list MUST NOT include `openregister`, - `shillinq`, `procest`, `decidesk`, or `docudesk`. Each widget - declares a **soft `requires`** in its manifest entry (e.g. - `requires: {graphql: ['financeq.transactions']}`) — the widget - registers itself, gracefully renders an empty-state when the - endpoint is absent at runtime, and never blocks app install. -- npm: no new packages. Apollo Client / urql are already present in - `@conduction/nextcloud-vue` per `feedback_shared-deps.md`. - -**Trade-offs:** - -- Consolidating 8 Specter spend drafts into one spec drops the - budget-bucket cluster names from the artefact list — that - taxonomy was a Specter generation artifact, not a meaningful - product boundary. The consolidated spec preserves the full feature - set (procurement spend, AI insights, document evidence, - drill-through, multi-source aggregation) under one coherent - widget surface, which matches how a dashboard user encounters it. -- All seven specs are `widget-capabilities` tier and ship as - `kind: config` (declarative manifest + capability contract). Per - ADR-032, the actual widget implementations are chain follow-ups — - one chain per widget — keeping each Hydra cycle scoped. -- Implementation defers the "which GraphQL schemas exist on each - sibling app right now?" gap analysis to the per-widget chain - spec. If a sibling app's GraphQL surface is incomplete, the - widget's chain spec 1 (config) declares the empty-state - contract; chain spec 2+ (code, in the sibling app) adds the - missing GraphQL field. launchpad itself stays unblocked. - -## Out of scope - -- Implementation code (Vue components, sub-forms, renderers, GraphQL - clients) — deferred to per-widget chain specs. -- Schema additions on sibling apps (OR registers, decidesk meeting - GraphQL fields, shillinq finance GraphQL fields) — tracked - separately per sibling app's openspec. -- AI-model selection, prompt engineering, RAG plumbing for the - AI assistant — `launchpad-ai-dashboard-assistant` describes the - widget surface and the openconnector hand-off, not the model - side. -- New launchpad routes or pages — every capability lands as a widget on - the existing dashboard surface; no new manifest `pages[]` entries. -- PWA service-worker / offline-storage implementation — - `launchpad-mobile-remote-access` describes the manifest capability - declarations only. diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-ai-dashboard-assistant/spec.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-ai-dashboard-assistant/spec.md deleted file mode 100644 index d454cffc6..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-ai-dashboard-assistant/spec.md +++ /dev/null @@ -1,285 +0,0 @@ -# Spec: launchpad-ai-dashboard-assistant - -**Status:** proposed -**Scope:** launchpad -**Tier:** widget-capabilities -**Depends on:** widgets, widget-add-edit-modal, runtime-shell, initial-state-contract, permissions; cross-app runtime sources: openconnector (LLM source `local-llm`), openregister (MCP discovery + GraphQL, read-only) - -## Purpose - -Add an embedded AI assistant widget (`launchpad_ai_assistant`) that lets -the dashboard viewer ask natural-language questions about their -dashboard's data and receive a streamed reply — summarising open -cases, surfacing consultation responses, explaining an aggregate -trend. The widget is a **thin chat surface** that delegates inference -to the openconnector-registered LLM source (Ollama + Qwen via -`local-llm` per `reference_llphant-ollama-think-false`). launchpad MUST -NOT carry its own LLM client SDK or call any inference endpoint -directly. - -Tool calls (the LLM reading sibling-app data) MUST go through OR's -MCP discovery (ADR-022 table row "MCP discovery") — every callable -tool is an OR-published MCP capability already scoped by OR's RBAC. -The assistant is read-only by default; write tools (creating an -object, dispatching a notification) MUST require an explicit -admin-side opt-in. - -Sourced from Specter draft `ai-dashboard-assistant` (2 features: -case summary, consultation-response summary). - -## ADDED Requirements - -### REQ-ADA-001: The system SHALL register a `launchpad_ai_assistant` widget type - -The widget MUST appear in `src/constants/widgetRegistry.js` and the -unified Add Widget modal (REQ-WDG-010 / REQ-WDG-014). The registry -entry MUST carry `displayName`, `defaultContent`, `renderer`, `form`, -`icon`, and a soft `requires.openconnectorSources: ['local-llm']` -declaration. The widget MUST NOT add `openconnector` to -`manifest.dependencies` — runtime checks gate behaviour. - -#### Scenario: Widget registered and discoverable - -- **GIVEN** the registry completeness test -- **WHEN** it runs -- **THEN** `ai-assistant` MUST be in EXPECTED_TYPES -- **AND** the entry MUST surface in `listWidgetTypes()` - -#### Scenario: Widget appears in the Add modal - -- **GIVEN** the Add Widget modal is open -- **WHEN** the user opens the type picker -- **THEN** `AI assistant` MUST be selectable -- **AND** picking it MUST mount the `AiAssistantForm` sub-form - -### REQ-ADA-002: The widget content shape SHALL describe the assistant's bounded conversation surface - -The placement persists `{type: 'ai-assistant', content: {...}}` with: - -| Field | Type | Required | Default | Purpose | -|---|---|---|---|---| -| `modelAlias` | string | Yes | `'local-llm'` | openconnector source alias to route through (NEVER a model name) | -| `systemPromptKey` | string | No | `'launchpad.ai.default'` | i18n key (per ADR-007 + ADR-025) resolved at render time; widget MUST NOT ship raw prompt strings | -| `scope` | enum | Yes | `'dashboard'` | `'dashboard' \| 'workspace' \| 'tenant'` — bounds the tool calls (REQ-ADA-005) | -| `allowWriteTools` | boolean | No | `false` | Opt-in for MCP write tools (default read-only) | -| `historyMaxTurns` | integer | No | `10` | Per-session conversation length cap | -| `temperature` | number | No | `0.2` | LLM sampling parameter forwarded to openconnector | - -#### Scenario: Defaults applied on minimal placement - -- **GIVEN** a placement with `{type: 'ai-assistant', content: {modelAlias: 'local-llm', scope: 'dashboard'}}` -- **WHEN** validation runs -- **THEN** it MUST pass -- **AND** unset fields MUST inherit the defaults above - -#### Scenario: Raw model name rejected - -- **GIVEN** the form attempts `modelAlias = 'qwen3.5-optimized'` -- **WHEN** `validate()` runs -- **THEN** it MUST return an error indicating model aliases must - point at openconnector sources, not raw model names -- **AND** the Add button MUST be disabled - -### REQ-ADA-003: The widget SHALL declare a `launchpad_ai_assistant` entry in `src/manifest.json` with a soft `requires` clause - -The manifest entry MUST live in `widgets[]` (per ADR-024). Its -`requires.openconnectorSources` MUST list `'local-llm'`. The -manifest's top-level `dependencies` MUST NOT include `openconnector`. - -#### Scenario: Manifest entry present - -- **GIVEN** the launchpad manifest -- **WHEN** parsed -- **THEN** `manifest.widgets[].find(w => w.id === 'launchpad_ai_assistant')` MUST exist -- **AND** `manifest.dependencies` MUST NOT include `openconnector` - -#### Scenario: Manifest validation passes - -- **GIVEN** `npm run check:manifest` -- **WHEN** the script runs -- **THEN** the widget entry MUST validate against the canonical - schema (per ADR-024 §5) - -### REQ-ADA-004: Inference SHALL route exclusively through the openconnector LLM source — launchpad MUST NOT contain an LLM client - -Every inference call MUST POST to the openconnector source URL for -`modelAlias`. The widget MUST consume the Server-Sent-Events stream -exposed by openconnector per the established -`project_ai-chat-companion-end-to-end` pattern (ADR-034 chain). launchpad -source files MUST NOT import any LLM SDK, MUST NOT call -`localhost:11434` (Ollama default) directly, and MUST NOT contain -prompt-engineered system prompts checked into source — every prompt -is an i18n string keyed at render time. - -#### Scenario: Renderer issues SSE call to openconnector - -- **GIVEN** the user submits a question -- **WHEN** the widget issues the inference call -- **THEN** the target MUST be openconnector's source endpoint for - `local-llm` -- **AND** the response MUST be consumed as SSE event chunks -- **AND** chunks MUST stream into the bubble incrementally - -#### Scenario: No LLM SDK or direct-URL imports - -- **GIVEN** the assistant widget source files -- **WHEN** scanned for `import .* from '@ollama'`, `from 'openai'`, - `from '@anthropic-ai'`, `from 'llphant'`, or - `localhost:11434` -- **THEN** zero matches MUST exist - -#### Scenario: Source absent disables widget gracefully - -- **GIVEN** openconnector is not installed OR `local-llm` source is - not configured -- **WHEN** the widget mounts -- **THEN** the chat input MUST render disabled with a tooltip - identifying the missing source -- **AND** the widget MUST NOT throw — the rest of the dashboard - MUST remain interactive - -### REQ-ADA-005: Tool calls SHALL be resolved against OR's MCP discovery — scoped by `content.scope` - -When the LLM emits a tool call, the widget MUST resolve the tool -via OR's MCP discovery endpoint (ADR-022 row "MCP discovery"). Tools -not present in OR's discovery MUST be rejected. The discovery -filter MUST honour `content.scope`: - -| Scope | Tool inclusion | -|---|---| -| `dashboard` | Only tools backed by registers consumed by widgets on the current dashboard | -| `workspace` | Tools backed by every register the viewer can read on this Nextcloud instance | -| `tenant` | Tools backed by every register, including cross-tenant — admin opt-in | - -When `content.allowWriteTools === false` (default), write-shaped -tools (any tool whose MCP descriptor declares -`x-mutation: true`) MUST be filtered out client-side before the -LLM sees them. - -#### Scenario: Read-only by default - -- **GIVEN** `content.allowWriteTools === false` -- **WHEN** the widget mounts -- **THEN** the tool list passed to the LLM MUST exclude every - tool whose MCP descriptor sets `x-mutation: true` - -#### Scenario: Out-of-scope tool rejected - -- **GIVEN** scope `dashboard` and the LLM emits a tool call for a - register NOT consumed by any widget on the current dashboard -- **WHEN** the widget validates the call -- **THEN** the call MUST be rejected with an error returned to the - LLM ("Tool out of scope") -- **AND** the call MUST NOT reach the sibling app - -#### Scenario: Write tool with allow flag enabled - -- **GIVEN** `content.allowWriteTools === true` AND the viewer has - the OR-side RBAC capability to invoke a write tool -- **WHEN** the LLM emits the call -- **THEN** the call MUST be forwarded to the sibling app -- **AND** the call MUST be recorded in OR's audit-trail-immutable - (the sibling app does this; launchpad does NOT write to audit) - -### REQ-ADA-006: The widget SHALL render two reply modes — streamed chat and inline summary - -When the placement is large enough (≥6 grid cells), the widget MUST -render a full chat interface (input box + scrollable history + -streamed response). When the placement is smaller (`<6` cells), it -MUST render in **summary mode**: a single tap-to-refresh "Summarise -this dashboard" call that uses `systemPromptKey` as the prompt and -fills the cell with the rendered Markdown reply. - -#### Scenario: Large placement renders full chat - -- **GIVEN** a placement with `gridWidth × gridHeight ≥ 6` -- **WHEN** the widget renders -- **THEN** an input box + conversation history MUST be visible -- **AND** the user MUST be able to submit follow-up turns up to - `content.historyMaxTurns` - -#### Scenario: Small placement renders summary mode - -- **GIVEN** a placement with `gridWidth × gridHeight < 6` -- **WHEN** the widget renders -- **THEN** a single "Summarise" button MUST be visible alongside the - most recent reply -- **AND** clicking the button MUST issue a fresh inference call - -#### Scenario: Open cases summary acceptance (Specter source) - -- **GIVEN** a case worker with open cases on the dashboard AND the - widget in summary mode -- **WHEN** the viewer clicks Summarise -- **THEN** the widget MUST stream a reply whose first sentence - names the total open count -- **AND** each case row in the reply MUST show identifier, - status, and last-updated date (sourced from procest GraphQL via - the MCP tool call) - -#### Scenario: Consultation responses summary acceptance (Specter source) - -- **GIVEN** a consultation has received responses AND the widget - is in summary mode -- **WHEN** the viewer triggers a summary -- **THEN** the reply MUST surface total responses + response - breakdown without the viewer needing to navigate away - -### REQ-ADA-007: History SHALL persist on the placement, not on a launchpad backend - -Conversation turns MUST persist only inside the Vue component's -session-local state. launchpad MUST NOT add a backend table or endpoint -to store chat history — the workspace already carries no chat -history surface, and adding one would create the install-time -dependency this spec exists to avoid. - -#### Scenario: History scoped to session - -- **GIVEN** a chat with 3 turns -- **WHEN** the user reloads the page -- **THEN** history MUST be empty after reload -- **AND** the widget MUST NOT issue any history-load API call - -#### Scenario: No backend persistence route added - -- **GIVEN** the launchpad backend route table after this widget ships -- **WHEN** inspected -- **THEN** zero routes matching `chat/history`, `ai/conversation`, - or `assistant/messages` MUST exist - -## Non-Functional Requirements - -- **Performance:** First streamed chunk SHOULD reach the viewer - within 1 s on the local Ollama path (warm cache). The widget MUST - surface a thinking indicator if no chunk arrives within 500 ms. -- **Accessibility:** Streamed text MUST update via `aria-live="polite"` - regions so screen readers announce new content. The input box - MUST carry a proper `aria-label` and be reachable via keyboard. -- **Localisation:** Default system prompts MUST be available in - English and Dutch (i18n keys per ADR-007 + ADR-025). -- **Privacy:** The default openconnector source MUST be `local-llm` - (Ollama + Qwen, on-prem). Hosted LLM sources are admin-configurable - only and MUST surface a "data leaves the instance" banner in the - Add modal form when selected. -- **Cost:** Token usage MUST be reported by openconnector; launchpad - does NOT meter usage locally. - -## Reuses (launchpad) - -- `widgets`, `widget-add-edit-modal`, `widget-collision-placement` -- `runtime-shell` + `initial-state-contract` -- `permissions` for view gating -- `responsive-grid-breakpoints` for mode-switch (chat vs summary) - -## Standards & References - -- ADR-022 — OR abstractions consumed: MCP discovery (tool list), - RBAC (per-tool authorisation by sibling app), audit-trail-immutable - (writes recorded by sibling app, not launchpad). -- ADR-024 — manifest widget entry + soft `requires`. -- `feedback_launchpad-no-or-dependency.md`. -- `project_ai-chat-companion-end-to-end.md` — proven SSE + - openconnector pattern on decidesk. -- `reference_llphant-ollama-think-false.md` — `think: false` + - `keep_alive: -1` are openconnector-side concerns, not launchpad's. -- WCAG 2.1 AA — `aria-live="polite"` for streamed output. diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-compliance-audit-panel/spec.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-compliance-audit-panel/spec.md deleted file mode 100644 index d16148d35..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-compliance-audit-panel/spec.md +++ /dev/null @@ -1,270 +0,0 @@ -# Spec: launchpad-compliance-audit-panel - -**Status:** proposed -**Scope:** launchpad -**Tier:** widget-capabilities -**Depends on:** widgets, widget-add-edit-modal, dashboards, permissions, conditional-visibility, role-based-content; cross-app runtime sources: openregister (audit-trail-immutable + archival-destruction-workflow + GraphQL, read-only), shillinq (retention rules via GraphQL), docudesk (compliance evidence via GraphQL) - -## Purpose - -Surface the organisation's compliance posture on a launchpad dashboard -through one widget (`launchpad_compliance_audit`). The widget reads -audit-trail, retention, and compliance-evidence data at runtime via -GraphQL — consuming OR's `audit-trail-immutable` and -`archival-destruction-workflow` abstractions (ADR-022 table rows -"Audit trail" + "Archival + destruction workflow") plus shillinq's -Archiefwet retention rules and docudesk's compliance documents. - -launchpad MUST NOT add an install-time dependency on any of these -sibling apps — per `feedback_launchpad-no-or-dependency.md`. Every -data flow is a runtime read, every absent sibling renders an -empty-state. - -Sourced from Specter draft `compliance-audit-panel` (2 features: -deadline alert, portfolio filter). - -## ADDED Requirements - -### REQ-CAP-001: The system SHALL register a `launchpad_compliance_audit` widget type - -The widget MUST appear in `src/constants/widgetRegistry.js` and the -unified Add Widget modal (REQ-WDG-010 / REQ-WDG-014). The registry -entry MUST carry the standard fields plus a soft -`requires.graphql: ['openregister.auditTrail', 'openregister.archival', 'shillinq.retentionRules']` -declaration. - -#### Scenario: Widget registered and discoverable - -- **GIVEN** the registry completeness test -- **WHEN** it runs -- **THEN** `compliance-audit` MUST appear in EXPECTED_TYPES -- **AND** the entry MUST surface in `listWidgetTypes()` with all - required fields non-null - -#### Scenario: Widget appears in the Add modal - -- **GIVEN** the Add Widget modal is open -- **WHEN** the user opens the type picker -- **THEN** `Compliance audit` MUST be selectable - -### REQ-CAP-002: The widget content shape SHALL declare posture, filter, and alert configuration - -The placement persists `{type: 'compliance-audit', content: {...}}` with: - -| Field | Type | Required | Default | Purpose | -|---|---|---|---|---| -| `frameworks` | string[] | Yes | `['BIO', 'ISO-27001', 'AVG']` | Frameworks tracked (`BIO`, `ISO-27001`, `AVG`, `NEN-7510`, custom slugs allowed) | -| `portfolioFilter` | string[] | No | `[]` | Filter to specific portfolios (Specter source: "filter by portfolio") | -| `deadlineWindowDays` | integer | No | `30` | Look-ahead horizon for "imminent" alerts | -| `showAuditTrailCard` | boolean | No | `true` | Surface the audit-trail summary card | -| `showRetentionCard` | boolean | No | `true` | Surface the retention disposition counts | -| `showEvidenceCard` | boolean | No | `true` | Surface docudesk-attached compliance evidence | - -#### Scenario: Default placement validates - -- **GIVEN** the content shape contract -- **WHEN** `{type: 'compliance-audit', content: {frameworks: ['BIO']}}` is saved -- **THEN** validation MUST pass -- **AND** the defaults above MUST apply to unset fields - -#### Scenario: Unknown framework slug accepted (forward-compat) - -- **GIVEN** `content.frameworks = ['BIO', 'CUSTOM-FRAMEWORK-X']` -- **WHEN** validation runs -- **THEN** validation MUST pass — the widget renders an empty card - for unknown frameworks rather than blocking placement save (the - framework definition lives on the compliance sibling app, not - in launchpad) - -### REQ-CAP-003: The audit-trail card SHALL be consumed from OR's `audit-trail-immutable` abstraction — never from a local audit table - -The audit-trail summary card MUST issue a GraphQL query against OR -exposing `auditEvents { type count latestTimestamp }` for the -viewer's accessible objects. launchpad MUST NOT define a local audit -table, MUST NOT mirror OR audit events, and MUST NOT post writes to -the audit trail (ADR-022 anti-pattern: "Home-grown audit trails"). - -#### Scenario: Audit summary card renders from OR GraphQL - -- **GIVEN** OR is installed AND the viewer has 4 recent audit - events across their objects -- **WHEN** the widget renders -- **THEN** the audit card MUST display the event types + counts + - latest timestamp -- **AND** the GraphQL query MUST target OR's `/graphql` (no local - table read, no axios to OR) - -#### Scenario: OR absent renders empty-state inline - -- **GIVEN** OR is not reachable (`/graphql` returns 404) -- **WHEN** the widget renders -- **THEN** the audit card MUST display - `t('launchpad', 'Audit trail unavailable — OpenRegister not reachable')` -- **AND** other cards on the widget MUST continue to render - -#### Scenario: No write to audit trail - -- **GIVEN** the compliance-audit widget source files -- **WHEN** scanned for POST / PUT against `/apps/openregister/.*audit` -- **THEN** zero matches MUST exist — the widget is read-only - -### REQ-CAP-004: The retention card SHALL consume OR's `archival-destruction-workflow` + shillinq retention rules - -Retention disposition counts MUST be queried via GraphQL from OR -(`archival { dispositionState count }`) and joined with shillinq's -Archiefwet retention rules (`retentionRules { selectielijstRef -durationYears }`) at the GraphQL composition layer — handled by OR's -relations abstraction (ADR-022). launchpad MUST NOT join the two -locally and MUST NOT cache retention metadata. - -#### Scenario: Retention card renders with disposition states - -- **GIVEN** OR archival + shillinq are installed AND the viewer's - scope includes 12 objects pending destruction -- **WHEN** the widget renders -- **THEN** the retention card MUST surface the disposition state - buckets (`pending-review`, `destroy-eligible`, `archived`, - `destroyed`) with counts -- **AND** the Selectielijst reference for the largest bucket MUST - surface as a tooltip - -#### Scenario: shillinq absent partial-renders the card - -- **GIVEN** OR present but shillinq absent -- **WHEN** the card renders -- **THEN** disposition state counts MUST still render -- **AND** the Selectielijst tooltip MUST display - `t('launchpad', 'Retention rules unavailable — shillinq not installed')` -- **AND** no error MUST throw - -### REQ-CAP-005: The widget SHALL surface deadline alerts with cross-session persistence (Specter acceptance) - -When a compliance deadline falls within `content.deadlineWindowDays`, -the widget MUST render a visible alert naming the deadline and due -date. The alert MUST persist across sessions until dismissed or -the deadline passes. Dismissal state MUST persist via the existing -launchpad placement state — NOT via a new launchpad backend table; the -widget reuses the placement's existing -`acknowledgements: {deadlineId: dismissedAt}` JSON sub-field within -`content` (forward-compat extension of REQ-CAP-002). - -#### Scenario: Imminent deadline surfaces alert (Specter source) - -- **GIVEN** a compliance deadline within the configured threshold - exists for the viewer's scope -- **WHEN** the viewer opens the dashboard -- **THEN** an alert MUST display naming the deadline and due date - -#### Scenario: Alert persists until acknowledged (Specter source) - -- **GIVEN** an unacknowledged imminent deadline alert -- **WHEN** the viewer signs out and back in -- **THEN** the alert MUST still be visible -- **AND** dismissal MUST persist by writing to the placement's - `content.acknowledgements` map via the existing widget PUT - endpoint (no new endpoint added) - -#### Scenario: Passed deadline updates to overdue (Specter source) - -- **GIVEN** the deadline has passed without acknowledgement -- **WHEN** the viewer next loads the dashboard -- **THEN** the alert MUST update to reflect overdue status (red - styling + revised copy) - -### REQ-CAP-006: The portfolio filter SHALL scope the widget's queries server-side, not client-side (Specter acceptance) - -`content.portfolioFilter` MUST be passed as a GraphQL variable on -every query the widget issues. Filtering MUST happen server-side -(in the sibling app's GraphQL resolver). Client-side post-filter -MUST be permitted only as a UX enhancement (sorting, paging); -client-side filter MUST NOT replace the server-side variable. - -#### Scenario: Filter included in GraphQL variables - -- **GIVEN** `content.portfolioFilter = ['portfolio-a']` -- **WHEN** the widget issues its queries -- **THEN** the variables payload MUST include - `{portfolioFilter: ['portfolio-a']}` -- **AND** the GraphQL document MUST reference the variable in its - argument list - -#### Scenario: Cleared filter widens result set (Specter source) - -- **GIVEN** a portfolio filter is active -- **WHEN** the viewer clears it -- **THEN** the widget MUST re-issue the queries with the variable - omitted -- **AND** the dashboard cards MUST update to reflect every portfolio - the viewer can read - -#### Scenario: Summary metrics reflect filter (Specter source) - -- **GIVEN** multiple portfolios exist AND the filter is applied -- **WHEN** the cards re-render -- **THEN** the audit-trail count, retention bucket counts, and - evidence count MUST reflect only the selected portfolio's data - -### REQ-CAP-007: The evidence card SHALL surface docudesk-attached compliance documents via OR's `object-interactions` - -The evidence card MUST list compliance documents attached to OR -objects in the viewer's scope using OR's `object-interactions` files -integration (ADR-022 + ADR-019). The widget MUST NOT call docudesk -endpoints directly — uploads stay with docudesk. - -#### Scenario: Evidence files surface - -- **GIVEN** the viewer's scope includes 5 OR objects with attached - compliance documents in docudesk -- **WHEN** the widget renders -- **THEN** the evidence card MUST list each document with title + - attachment date + framework tag - -#### Scenario: Click deep-links to docudesk - -- **GIVEN** an evidence row -- **WHEN** the viewer clicks it -- **THEN** the browser MUST navigate to the docudesk viewer URL - (resolved via OR's deep-link registry) - -#### Scenario: Read-only evidence - -- **GIVEN** the compliance-audit widget source files -- **WHEN** scanned for HTTP `POST` / `PUT` / `DELETE` to - `/apps/docudesk/` -- **THEN** zero matches MUST exist - -## Non-Functional Requirements - -- **Performance:** All cards SHOULD render their initial payload - within 2 s on a warm cache. Each card MUST query independently — - one card's slow response MUST NOT block siblings. -- **Accessibility:** Alert banners (REQ-CAP-005) MUST carry - `role="alert"` and adequate colour contrast for both light and - high-contrast themes (WCAG 2.1 AA). -- **Localisation:** Framework names (`BIO`, `ISO-27001`, `AVG`, - `NEN-7510`) stay as proper nouns; surrounding copy MUST be - translated to Dutch + English. -- **Privacy:** Audit-trail payloads carry actor identifiers. The - widget MUST defer to OR's audit-RBAC — a viewer who cannot see - an actor's identity in OR MUST NOT see it in the widget. - -## Reuses (launchpad) - -- `widgets`, `widget-add-edit-modal` -- `dashboards`, `permissions`, `conditional-visibility` -- `role-based-content` for portfolio scoping - -## Standards & References - -- ADR-022 — OR abstractions consumed: audit-trail-immutable (table - row "Audit trail (immutable)"), archival + destruction workflow, - integration registry (`object-interactions`), deep-link registry. -- ADR-024 — manifest widget entry + soft `requires`. -- `feedback_launchpad-no-or-dependency.md`. -- Archiefwet 1995 + Selectielijst Gemeenten 2020 — retention - context (sibling-app-owned definitions). -- BIO (Baseline Informatiebeveiliging Overheid), - ISO/IEC 27001:2022, AVG / GDPR — framework references for - card labels. -- `tender-compliance-status.md` — internal Conduction compliance - baseline. diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-enterprise-security-access/spec.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-enterprise-security-access/spec.md deleted file mode 100644 index 919104bea..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-enterprise-security-access/spec.md +++ /dev/null @@ -1,241 +0,0 @@ -# Spec: launchpad-enterprise-security-access - -**Status:** proposed -**Scope:** launchpad -**Tier:** widget-capabilities -**Depends on:** widgets, widget-add-edit-modal, admin-roles, admin-settings, role-based-content, permissions; cross-app runtime sources: openregister (RBAC + audit-trail-immutable via GraphQL, read-only), Nextcloud user_saml provider info, Nextcloud TOTP/WebAuthn provider state - -## Purpose - -Surface enterprise security and access posture on a launchpad dashboard -through a read-only widget (`launchpad_security_access`). Three card -surfaces compose the widget: - -- **Role assignments** — read over OR's RBAC abstraction (ADR-022 - table row "Authorization RBAC") via GraphQL. -- **SSO status** — read from Nextcloud's `user_saml` provider info. -- **MFA enforcement** — read from Nextcloud's TOTP / WebAuthn - provider state. - -The widget MUST be **read-only**. A "view as another role" preview -(Specter source) is permitted as an admin-side capability but every -mutation MUST happen in OR's RBAC admin UI; the widget surfaces -state and audits the impersonation event. launchpad MUST NOT define a -local roles/permissions table or post writes to OR's RBAC. - -Sourced from Specter draft `enterprise-security-access` (2 features: -enterprise guest/role perms + view-as-another-role). - -## ADDED Requirements - -### REQ-ESA-001: The system SHALL register a `launchpad_security_access` widget type - -The widget MUST appear in `src/constants/widgetRegistry.js` and the -unified Add Widget modal. The registry entry MUST carry the standard -fields and a soft -`requires.graphql: ['openregister.roles', 'openregister.auditTrail']` -declaration. The widget MUST be addable only by admins (launchpad -admin permission per `admin-roles`). - -#### Scenario: Widget registered - -- **GIVEN** the registry completeness test -- **WHEN** it runs -- **THEN** `security-access` MUST appear in EXPECTED_TYPES - -#### Scenario: Non-admin cannot add the widget - -- **GIVEN** a viewer without the launchpad admin permission -- **WHEN** they open the Add Widget modal type picker -- **THEN** `Security & access` MUST NOT appear in the list -- **AND** the gate MUST be enforced by `admin-roles` (server-side - on the placement POST) - -### REQ-ESA-002: The widget content shape SHALL describe scope + which cards to render - -The placement persists `{type: 'security-access', content: {...}}` with: - -| Field | Type | Required | Default | Purpose | -|---|---|---|---|---| -| `scope` | enum | Yes | `'tenant'` | `'tenant' \| 'group' \| 'self'` — bounds the queries | -| `groupIds` | string[] | When `scope === 'group'` | `[]` | Group filter | -| `showRolesCard` | boolean | No | `true` | Role-assignment card | -| `showSsoCard` | boolean | No | `true` | SSO status card | -| `showMfaCard` | boolean | No | `true` | MFA enforcement card | -| `viewAsEnabled` | boolean | No | `false` | Whether the "view as another role" preview is offered | - -#### Scenario: Default placement validates - -- **GIVEN** the content shape -- **WHEN** `{type: 'security-access', content: {scope: 'tenant'}}` is saved -- **THEN** validation MUST pass - -#### Scenario: Group scope requires `groupIds` - -- **GIVEN** `scope === 'group'` AND `groupIds = []` -- **WHEN** `validate()` runs -- **THEN** an error MUST surface ("Select at least one group") - -### REQ-ESA-003: The role-assignments card SHALL consume OR's RBAC abstraction via GraphQL — never mirror a local role table - -The card MUST query OR's `/graphql` for -`roles { name members { id displayName } scope }` filtered by -`scope` / `groupIds`. launchpad MUST NOT define a local roles table, -MUST NOT issue write calls to OR's RBAC endpoints (anti-pattern per -ADR-022 "App-local RBAC on OR objects"), and MUST surface a link -to OR's RBAC admin UI for any mutation. - -#### Scenario: Role overview renders from OR (Specter source) - -- **GIVEN** an IT admin has assigned guest users to a workspace AND - defined a custom role -- **WHEN** the widget renders -- **THEN** the card MUST display each role with its current member - count and named scope -- **AND** the data MUST come from OR's `/graphql` - -#### Scenario: Revocation reflected on next reload (Specter source) - -- **GIVEN** a role's permissions are revoked in OR's admin UI -- **WHEN** the viewer reloads the dashboard -- **THEN** the card MUST reflect the revocation (the role no - longer shows the revoked scope) - -#### Scenario: No write to OR RBAC - -- **GIVEN** the security-access widget source files -- **WHEN** scanned for HTTP `POST` / `PUT` / `DELETE` targeting - `/apps/openregister/.*role` or `/apps/openregister/.*permission` -- **THEN** zero matches MUST exist - -### REQ-ESA-004: The SSO status card SHALL consume Nextcloud's `user_saml` (or successor) provider info — read-only - -The card MUST issue OCS calls (or use the public PHP API in the -launchpad backend) to read SAML / OIDC provider state from -`user_saml` (or its successor app). The card surfaces: - -- Provider name + protocol (SAML 2.0 / OIDC) -- Connected status (active / misconfigured / disabled) -- Last successful login timestamp (if available) - -The widget MUST NOT define a local SSO settings table. If -`user_saml` is absent, the card MUST render an empty-state naming -the missing app. - -#### Scenario: SSO card shows configured provider - -- **GIVEN** `user_saml` is installed with one active SAML 2.0 - provider -- **WHEN** the card renders -- **THEN** it MUST display the provider name + "SAML 2.0" + active - status - -#### Scenario: SSO app absent - -- **GIVEN** `user_saml` is not installed -- **WHEN** the card renders -- **THEN** it MUST display - `t('launchpad', 'SSO unavailable — user_saml not installed')` - -### REQ-ESA-005: The MFA enforcement card SHALL consume Nextcloud's TOTP / WebAuthn provider state — read-only - -The card MUST read the enabled second-factor providers (twofactor_totp, -twofactor_webauthn, twofactor_email) from Nextcloud's twofactor -infrastructure. It surfaces: - -- Which providers are enabled -- Whether MFA enforcement is on (per Nextcloud admin settings) -- Per-group enforcement summary if `scope === 'group'` - -The widget MUST NOT mutate twofactor settings; it links to -Nextcloud's `Settings → Security` UI for changes. - -#### Scenario: MFA card shows providers + enforcement - -- **GIVEN** `twofactor_totp` enabled AND MFA enforcement is on - for group `admins` -- **WHEN** the card renders with `scope === 'tenant'` -- **THEN** the card MUST show `TOTP enabled` and - `Enforcement: on for 1 group (admins)` - -#### Scenario: No MFA providers - -- **GIVEN** no twofactor app is enabled -- **WHEN** the card renders -- **THEN** the card MUST display the empty-state and the link to - Nextcloud's Security settings - -### REQ-ESA-006: "View as another role" SHALL be a read-only preview, audited via OR's audit-trail-immutable (Specter source) - -When `viewAsEnabled === true`, an admin viewer MAY pick a target -role from a "View as" control. The dashboard MUST re-render the -current page applying the target role's `role-based-content` -conditional rules (per the existing `role-based-content` spec). A -persistent banner MUST show the assumed role with a one-click "Exit -view" control. The impersonation event (start and exit) MUST be -recorded in OR's audit-trail-immutable (sibling-app-side, via the -existing audit hooks). launchpad MUST NOT define a local impersonation -event table. - -#### Scenario: Role preview re-renders (Specter source) - -- **GIVEN** an IT admin AND `viewAsEnabled === true` -- **WHEN** they select a target role from "View as" -- **THEN** the dashboard MUST re-render showing only widgets + - data the target role can see (per `role-based-content`) - -#### Scenario: Persistent banner with exit control (Specter source) - -- **GIVEN** a "View as" preview is active -- **WHEN** the page renders -- **THEN** a persistent banner MUST display the assumed role with - a one-click "Exit view" control - -#### Scenario: Impersonation audited (Specter source) - -- **GIVEN** the admin starts then exits a "View as" preview -- **WHEN** the events are inspected -- **THEN** both start + exit events MUST be present in OR's - audit-trail (recorded via OR's audit hooks at the moment the - RBAC context switches, NOT by a launchpad-local writer) - -#### Scenario: Session end auto-exits the preview (Specter source) - -- **GIVEN** a "View as" preview is active -- **WHEN** the session ends (logout or timeout) -- **THEN** the dashboard MUST revert to the admin's own role on - next sign-in (no preview persists across sessions) - -## Non-Functional Requirements - -- **Performance:** Each card MUST query independently; one slow - card MUST NOT block siblings. Role counts SHOULD render within - 1.5 s on typical organisation sizes (<1000 roles). -- **Accessibility:** The "View as" banner MUST carry `role="status"` - and adequate contrast; the Exit control MUST be keyboard - reachable. Card data MUST be screen-reader navigable. -- **Localisation:** All labels in Dutch + English. -- **Privacy:** Member lists in the roles card MUST defer to OR's - RBAC — a viewer who cannot see role membership in OR MUST NOT - see it in the widget. - -## Reuses (launchpad) - -- `widgets`, `widget-add-edit-modal` -- `admin-roles` — widget addability gate -- `role-based-content` — "View as" preview re-renders against - this spec's existing conditional engine -- `permissions`, `conditional-visibility` - -## Standards & References - -- ADR-022 — OR abstractions consumed: Authorization RBAC (table - row), Audit trail (immutable). Anti-pattern reference: - "App-local RBAC on OR objects" (this widget MUST NOT violate it). -- ADR-023 — action-level authorisation (the widget surfaces the - state of mappings defined there, never edits them). -- ADR-024 — manifest widget entry. -- `feedback_launchpad-no-or-dependency.md`. -- Nextcloud Authentication apps: `user_saml`, `twofactor_totp`, - `twofactor_webauthn`. -- WCAG 2.1 AA. diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-file-access-widget/spec.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-file-access-widget/spec.md deleted file mode 100644 index ee2c6b2ef..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-file-access-widget/spec.md +++ /dev/null @@ -1,203 +0,0 @@ -# Spec: launchpad-file-access-widget - -**Status:** proposed -**Scope:** launchpad -**Tier:** widget-capabilities -**Depends on:** widgets, widget-add-edit-modal, files-widget (peer pattern), permissions, conditional-visibility; cross-app runtime sources: Nextcloud Files OCS API + WebDAV, OR object-interactions (for dossier-attached documents) - -## Purpose - -Surface dossier documents (and arbitrary Nextcloud Files objects) -on a launchpad dashboard via a single widget -(`launchpad_file_access`). The widget is a **quick-access surface** -distinct from the existing `files-widget` (which embeds a folder -browser): this widget renders a curated short-list of files the -viewer needs from the dashboard — typically the documents attached -to a dossier object via OR's `object-interactions` integration -(ADR-019 / ADR-022). - -launchpad MUST NOT store file bytes. All file data flows live from -Nextcloud Files (OCS / WebDAV) or from OR's -`object-interactions` files endpoint — the viewer's existing -Nextcloud ACL enforces visibility. - -Sourced from Specter draft `dashboard-file-access` (1 feature: open -dossier document from dashboard). - -## ADDED Requirements - -### REQ-FAW-001: The system SHALL register a `launchpad_file_access` widget type alongside the existing `files-widget` - -The widget MUST appear in `src/constants/widgetRegistry.js` as a -distinct type (`file-access`) from the existing `files` type — the -two coexist (browser vs quick-access). The registry entry MUST carry -the standard fields and a soft `requires.nextcloud: -['files']` declaration. `files` is a Nextcloud-core app so this is -always satisfied in practice; the declaration is for completeness. - -#### Scenario: Widget registered without colliding with `files-widget` - -- **GIVEN** the registry completeness test (REQ-WDG-023) -- **WHEN** it runs -- **THEN** both `files` and `file-access` MUST appear in - EXPECTED_TYPES -- **AND** their registry entries MUST point at distinct - `renderer` + `form` components - -#### Scenario: Picker disambiguates the two types - -- **GIVEN** the Add Widget modal type picker -- **WHEN** rendered -- **THEN** both types MUST list with distinct `displayName` - values (e.g. `'Files browser'` vs `'Quick file access'`) - -### REQ-FAW-002: The widget content shape SHALL describe the source binding mode - -The placement persists `{type: 'file-access', content: {...}}` with: - -| Field | Type | Required | Default | Purpose | -|---|---|---|---|---| -| `sourceMode` | enum | Yes | `'fileIds'` | `'fileIds' \| 'orObject' \| 'recent'` — three binding modes | -| `fileIds` | integer[] | When `sourceMode === 'fileIds'` | `[]` | Explicit list of Nextcloud file IDs | -| `orObjectRef` | object | When `sourceMode === 'orObject'` | `null` | `{register, schema, objectId}` — surfaces files attached to that OR object via `object-interactions` | -| `recentLimit` | integer | When `sourceMode === 'recent'` | `5` | Most-recently-modified files the viewer can access | -| `displayMode` | enum | No | `'list'` | `'list' \| 'grid'` — same conventions as `files-widget` | -| `showThumbnails` | boolean | No | `true` | Thumbnail rendering (delegates to Nextcloud preview endpoint) | - -#### Scenario: Minimal `orObject` placement validates - -- **GIVEN** the content shape contract -- **WHEN** `{type: 'file-access', content: {sourceMode: 'orObject', orObjectRef: {register: 'procest', schema: 'Case', objectId: 'case-1'}}}` is saved -- **THEN** validation MUST pass - -#### Scenario: Cross-mode field is rejected - -- **GIVEN** `sourceMode === 'recent'` AND `fileIds = [42]` -- **WHEN** `validate()` runs -- **THEN** validation MUST return an error noting that `fileIds` - is only relevant when `sourceMode === 'fileIds'` - -### REQ-FAW-003: The widget SHALL consume files via Nextcloud Files OCS / WebDAV — never via a launchpad-local file table - -The renderer MUST issue requests to: - -- `GET /ocs/v2.php/apps/files/api/v1/files` — file metadata by id -- `PROPFIND` on `/remote.php/dav/files/{user}/{path}` — file - listings for `recent` and `orObject` modes -- `/index.php/core/preview?fileId=...` — thumbnails - -launchpad MUST NOT define a local file metadata table, MUST NOT cache -file bytes, and MUST NOT issue any write call to Files (no upload, -no delete) — this widget is read-only quick-access. (Upload / -delete remains the responsibility of the existing `files-widget` -where the placement-level toggles already exist per REQ-FLS-001.) - -#### Scenario: Metadata fetch routes through OCS - -- **GIVEN** `sourceMode === 'fileIds'` AND `fileIds = [123, 456]` -- **WHEN** the widget mounts -- **THEN** the renderer MUST issue OCS metadata requests for both - file IDs - -#### Scenario: No launchpad file table - -- **GIVEN** the launchpad migration files after this widget ships -- **WHEN** inspected -- **THEN** no migration introducing a file metadata table MUST - exist - -#### Scenario: No write call to Files - -- **GIVEN** the file-access widget source files -- **WHEN** scanned for HTTP method `POST` / `PUT` / `DELETE` to - `/dav/files/` or `/apps/files/api` -- **THEN** zero matches MUST exist - -### REQ-FAW-004: When `sourceMode === 'orObject'`, the file list SHALL be sourced via OR's `object-interactions` files integration - -The renderer MUST issue a GraphQL query against OR's `/graphql` -resolving the object's attached files via the -`object-interactions` integration (per ADR-019 + ADR-022). The -returned file list carries Nextcloud file IDs that flow into the -same OCS metadata fetch as REQ-FAW-003. - -#### Scenario: Dossier files surface (Specter source) - -- **GIVEN** an OR object `{register: 'procest', schema: 'Case', objectId: 'case-1'}` with 3 attached documents -- **WHEN** the widget renders -- **THEN** the widget MUST list those 3 documents with their titles - and last-modified dates - -#### Scenario: Click opens the document viewer (Specter source) - -- **GIVEN** a clickable document on the dashboard -- **WHEN** the viewer clicks it -- **THEN** the document MUST open in the Nextcloud document viewer - (per Files convention — `?openfile=...` parameter on the Files - app) - -### REQ-FAW-005: When the viewer lacks access to a referenced file, the widget SHALL render an access-denied row — not surface the file metadata (Specter source) - -When a file ID in `fileIds`, an `orObject`-derived file, or a -`recent` result is not readable by the viewer (Nextcloud ACL -denies), the row MUST render with a lock icon + the translated -text `t('launchpad', 'No access')`, MUST NOT surface the file's title -or thumbnail, and MUST NOT allow click-through. The widget MUST -NOT throw — other rows MUST keep rendering. - -#### Scenario: Access denied row (Specter source) - -- **GIVEN** a placement with `fileIds = [999]` AND the viewer - has no read access to file 999 -- **WHEN** the widget renders -- **THEN** the row for file 999 MUST display the lock icon and - `t('launchpad', 'No access')` -- **AND** the title MUST NOT surface -- **AND** clicking the row MUST be a no-op - -#### Scenario: Partial denial keeps other rows - -- **GIVEN** `fileIds = [123, 999, 456]` where 999 is denied -- **WHEN** the widget renders -- **THEN** rows for 123 and 456 MUST render normally -- **AND** the 999 row MUST render in the denied state - -#### Scenario: Deleted file shows missing state - -- **GIVEN** a file ID that no longer exists in Nextcloud -- **WHEN** the widget renders -- **THEN** the row MUST display `t('launchpad', 'File not found')` -- **AND** the click target MUST be inert -- **AND** the widget MUST NOT auto-prune the placement (consistent - with `image-widget` REQ-IMP-006) - -## Non-Functional Requirements - -- **Performance:** OCS metadata fetches SHOULD be batched (single - call per render where possible). Thumbnails MUST load lazily. -- **Accessibility:** Lock icons MUST have `aria-label` describing - the denied access state. Recent-files lists MUST be keyboard - navigable. -- **Localisation:** All labels in Dutch + English. -- **SVG handling:** SVG files MUST follow the same hand-off to - `svg-sanitisation` as `image-widget` REQ-IMP-008 (the file-access - widget defers to the existing sanitisation capability for SVG - preview rendering). - -## Reuses (launchpad) - -- `widgets`, `widget-add-edit-modal`, `widget-collision-placement` -- `files-widget` — peer widget, shares Nextcloud Files plumbing - conventions but renders a different UX (browser vs quick-access) -- `svg-sanitisation` — for SVG previews -- `permissions`, `conditional-visibility` - -## Standards & References - -- ADR-022 — OR `object-interactions` for dossier-attached files, - deep-link registry for document-viewer hand-off. -- ADR-019 — integration registry pattern (object-interactions is - the canonical file integration). -- Nextcloud OCS Files API + WebDAV — the authoritative file APIs. -- `feedback_launchpad-no-or-dependency.md`. -- WCAG 2.1 AA — keyboard navigation + access-denied a11y. diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-meeting-calendar-actions/spec.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-meeting-calendar-actions/spec.md deleted file mode 100644 index cd14fb466..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-meeting-calendar-actions/spec.md +++ /dev/null @@ -1,232 +0,0 @@ -# Spec: launchpad-meeting-calendar-actions - -**Status:** proposed -**Scope:** launchpad -**Tier:** widget-capabilities -**Depends on:** widgets, widget-add-edit-modal, calendar-widget (peer pattern), permissions, conditional-visibility; cross-app runtime sources: Nextcloud Calendar (DAV), decidesk (meetings + agendas via GraphQL, read-only), openregister (object-interactions for meeting attachments) - -## Purpose - -Surface meeting and agenda actions on a launchpad dashboard via the -widget `launchpad_meeting_actions`. The widget composes data from two -sources, presented as one timeline: - -- **Nextcloud Calendar events** (via DAV) — the standard - cross-app calendar surface. -- **decidesk meetings + agenda items** (via decidesk GraphQL) — - Conduction's governance app with motion / vote / annotation - semantics absent from generic calendar events. - -It is a **distinct widget** from the existing `calendar-widget` -(which surfaces only Nextcloud DAV calendars). This widget joins -the two sources and adds **agenda-item annotation** (the Specter -source acceptance). - -launchpad MUST NOT add an install-time dependency on decidesk — -absent decidesk, the widget falls back to pure DAV calendar -rendering per `feedback_launchpad-no-or-dependency.md`. - -Sourced from Specter draft `meeting-calendar-actions` (1 feature: -annotate agenda items on dashboard). - -## ADDED Requirements - -### REQ-MCA-001: The system SHALL register a `launchpad_meeting_actions` widget type distinct from `calendar-widget` - -The widget MUST appear in `src/constants/widgetRegistry.js` and the -unified Add Widget modal. The registry entry MUST carry the standard -fields and a soft `requires.dav: ['calendar']` plus -`requires.graphql: ['decidesk.meetings', 'decidesk.agendaItems']` -declaration. The widget MUST coexist with `calendar` — the two -types fulfil different use-cases (broad calendar view vs governance -+ annotation timeline). - -#### Scenario: Both calendar widget types registered - -- **GIVEN** the registry completeness test -- **WHEN** it runs -- **THEN** both `calendar` and `meeting-actions` MUST appear in - EXPECTED_TYPES -- **AND** their `displayName`s MUST disambiguate - (`'Calendar'` vs `'Meetings & actions'`) - -#### Scenario: Widget appears in the Add modal - -- **GIVEN** the Add Widget modal type picker -- **WHEN** rendered -- **THEN** `Meetings & actions` MUST be selectable - -### REQ-MCA-002: The widget content shape SHALL describe the source bindings and timeline window - -The placement persists `{type: 'meeting-actions', content: {...}}` with: - -| Field | Type | Required | Default | Purpose | -|---|---|---|---|---| -| `calendarSources` | string[] | No | `[]` | NC Calendar principal URIs (empty = viewer's personal calendars only) | -| `decideskMeetings` | boolean | No | `true` | Include decidesk meetings (gracefully falls back when decidesk absent) | -| `daysAhead` | integer | No | `14` | Time horizon | -| `includeAgendaItems` | boolean | No | `true` | Surface decidesk agenda items inline under their meeting | -| `showAnnotations` | boolean | No | `true` | Surface agenda-item annotations (REQ-MCA-005) | -| `groupBy` | enum | No | `'day'` | `'day' \| 'meeting' \| 'none'` | - -#### Scenario: Minimal placement validates - -- **GIVEN** the content shape -- **WHEN** `{type: 'meeting-actions', content: {daysAhead: 7}}` is saved -- **THEN** validation MUST pass -- **AND** defaults MUST apply - -#### Scenario: Negative `daysAhead` rejected - -- **GIVEN** `content.daysAhead = -1` -- **WHEN** `validate()` runs -- **THEN** validation MUST return an error - -### REQ-MCA-003: Nextcloud Calendar events SHALL be read via DAV — never via a launchpad-local event table - -The renderer MUST issue CalDAV `REPORT` queries against the viewer's -calendars to fetch events. launchpad MUST NOT define an event table, -MUST NOT mirror calendar data, and MUST NOT issue writes via this -widget (annotations write to decidesk per REQ-MCA-005, never to -DAV). The DAV query MUST respect `calendarSources` when set, else -default to the viewer's enabled calendars per Nextcloud's existing -convention. - -#### Scenario: DAV query issued on mount - -- **GIVEN** the widget mounts with default `calendarSources` -- **WHEN** the renderer queries -- **THEN** a CalDAV `REPORT` MUST be issued against the viewer's - default calendar collection -- **AND** the time range MUST equal `now .. now + daysAhead` - -#### Scenario: No launchpad event table - -- **GIVEN** the launchpad migrations after this widget ships -- **WHEN** inspected -- **THEN** no migration adding an event / calendar / meeting - table MUST exist - -### REQ-MCA-004: decidesk meetings + agenda items SHALL be fetched via decidesk GraphQL — empty-state when absent - -When `decideskMeetings === true`, the widget MUST issue a GraphQL -query against decidesk's `/graphql` resolving -`meetings(window: {...}) { id title startTime agendaItems { id text } }`. -If decidesk is absent (404 / connection error), the widget MUST -gracefully render only the DAV calendar events and surface an -inline info chip: -`t('launchpad', 'Decidesk meetings unavailable — install decidesk for governance features')`. - -#### Scenario: decidesk present surfaces meetings inline - -- **GIVEN** decidesk is installed AND has 2 upcoming meetings in - the window -- **WHEN** the widget renders -- **THEN** the timeline MUST surface both meetings with their - agenda items (when `includeAgendaItems === true`) - -#### Scenario: decidesk absent falls back gracefully - -- **GIVEN** decidesk is not installed -- **WHEN** the widget renders -- **THEN** the DAV calendar events MUST still render -- **AND** an info chip MUST surface naming the missing app -- **AND** the widget MUST NOT throw - -### REQ-MCA-005: Agenda-item annotations SHALL persist on the agenda-item object in decidesk — never in a launchpad table (Specter acceptance) - -When the viewer adds, edits, or deletes an annotation on an agenda -item, the widget MUST issue a GraphQL mutation against decidesk's -agenda-item mutation endpoint. launchpad MUST NOT define an annotations -table, MUST NOT store annotation text in placement content, and -MUST NOT mirror annotation state. - -#### Scenario: Annotation save (Specter source) - -- **GIVEN** an agenda item is visible on the dashboard -- **WHEN** the viewer adds an annotation -- **THEN** the annotation MUST persist via a GraphQL mutation to - decidesk's agenda-item mutation -- **AND** the annotation MUST display alongside the agenda item - on next render - -#### Scenario: Annotation edit reflects immediately (Specter source) - -- **GIVEN** an annotated agenda item on the dashboard -- **WHEN** the viewer edits the annotation -- **THEN** the updated text MUST reflect immediately without a - page reload (via the same mutation + local component state - refresh) - -#### Scenario: Annotation removal (Specter source) - -- **GIVEN** an annotated agenda item -- **WHEN** the viewer removes the annotation -- **THEN** the annotation MUST be deleted via a GraphQL mutation - to decidesk -- **AND** the agenda item MUST return to its unannotated state - -#### Scenario: decidesk absent disables annotation control - -- **GIVEN** decidesk is not installed AND `showAnnotations === true` -- **WHEN** the widget renders DAV events -- **THEN** the annotation control MUST NOT surface on DAV events - (DAV events have no agenda-item identity to annotate) - -### REQ-MCA-006: Joining DAV events with decidesk meetings SHALL happen client-side via shared `referenceId` — server-side join is decidesk's responsibility - -decidesk meetings that are also published as DAV events MUST be -deduplicated client-side by matching the DAV event's -`X-DECIDESK-MEETING-ID` property (or successor) against the -decidesk meeting's `id`. launchpad MUST NOT POST a "register this -calendar event with decidesk" mutation — that linkage is decidesk's -own responsibility per its CalDAV integration spec. - -#### Scenario: Duplicate event dedup - -- **GIVEN** a decidesk meeting `m-1` exists both as a decidesk - meeting and as a DAV event with `X-DECIDESK-MEETING-ID: m-1` -- **WHEN** the timeline renders -- **THEN** the event MUST appear exactly once -- **AND** the rendered row MUST surface both DAV metadata - (location / attendees) and decidesk metadata (agenda items) - -#### Scenario: No launchpad↔decidesk link mutation - -- **GIVEN** the widget source files -- **WHEN** scanned for POST/PUT to `/apps/decidesk/.*link` or - `/apps/decidesk/.*calendar` -- **THEN** zero matches MUST exist - -## Non-Functional Requirements - -- **Performance:** DAV `REPORT` + decidesk GraphQL MUST run in - parallel (Promise.all), not serially. The widget MUST surface - the timeline as soon as the first source returns; the second - source merges in when it resolves. -- **Accessibility:** Agenda items MUST be keyboard navigable - (Tab/Shift+Tab through the timeline). Annotation save MUST - surface a confirmation via `aria-live="polite"`. -- **Localisation:** English + Dutch. Date / time formatting MUST - respect the viewer's Nextcloud locale. -- **Time zone:** All events / meetings MUST render in the viewer's - configured Nextcloud time zone; UTC times in payloads MUST be - converted client-side. - -## Reuses (launchpad) - -- `widgets`, `widget-add-edit-modal`, `widget-collision-placement` -- `calendar-widget` — peer pattern for DAV consumption + caching - conventions -- `permissions`, `conditional-visibility` - -## Standards & References - -- ADR-022 — OR abstractions: deep-link registry (for meeting - detail navigation), object-interactions (meeting attachments). -- ADR-024 — manifest widget entry + soft `requires`. -- `feedback_launchpad-no-or-dependency.md`. -- CalDAV (RFC 4791) + iCalendar (RFC 5545) — DAV / event format. -- decidesk's CalDAV integration spec (sibling-app-owned) — defines - the `X-DECIDESK-MEETING-ID` property used for dedup. -- WCAG 2.1 AA — keyboard navigation + `aria-live` announcements. diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-mobile-remote-access/spec.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-mobile-remote-access/spec.md deleted file mode 100644 index 7c1a607e8..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-mobile-remote-access/spec.md +++ /dev/null @@ -1,265 +0,0 @@ -# Spec: launchpad-mobile-remote-access - -**Status:** proposed -**Scope:** launchpad -**Tier:** widget-capabilities -**Depends on:** widgets, responsive-grid-breakpoints, runtime-shell, permissions, role-based-content, initial-state-contract; no cross-app runtime sources (this is a manifest-declaration capability) - -## Purpose - -Define the **manifest contract** for declaring widget mobile-readiness -so the launchpad workspace can render a coherent mobile + remote -experience. The existing `responsive-grid-breakpoints` spec already -handles the grid-side breakpoint engine; this spec adds the **per-widget -declaration surface** in the app manifest (per ADR-024) and the -fallback behaviour when no widget on a dashboard declares itself -mobile-ready. - -Three Specter acceptance themes resolve here: - -- **Remote / mobile access** — surface decisions about which widgets - render on small viewports (responsive declaration). -- **Session timeout** — surface the established Nextcloud session - timeout state in the workspace shell, never a launchpad-local - timer. -- **Role-gated app & news access** — already covered by - `role-based-content`; this spec adds the manifest declaration - that flags mobile-ready widgets and the empty-state when none - are present. - -This is a **declarative capability** — no runtime data sources, no -new endpoints. PWA / offline-storage / service-worker work is OUT -of scope (deferred to a future capability). - -Sourced from Specter draft `mobile-remote-access` (2 features: -remote/mobile access + curated app + news access). - -## ADDED Requirements - -### REQ-MRA-001: Every widget registry entry SHALL declare a `mobileReady` boolean - -`src/constants/widgetRegistry.js` entries MUST extend the existing -registry contract (REQ-WDG-014) with a required `mobileReady: boolean` -field. The registry completeness test (REQ-WDG-023) MUST be updated -to assert every entry carries the field. Widgets that legitimately -cannot render on mobile (e.g. complex multi-column tables) MUST set -`mobileReady: false` explicitly — defaulting is not permitted. - -#### Scenario: Registry entry missing the field fails the completeness test - -- **GIVEN** a registry entry omits `mobileReady` -- **WHEN** `npm test` runs the completeness test -- **THEN** the test MUST fail with a message naming the type - + the missing `mobileReady` field - -#### Scenario: Every shipped widget declares the field - -- **GIVEN** the canonical widget set (`calendar`, `container`, - `divider`, `files`, `header`, `image`, `label`, `link`, `links`, - `menu`, `nc-widget`, `news`, `people`, `quicklinks`, `text`, `tile`, - `video`) plus the seven net-new widgets from this change set -- **WHEN** the completeness test inspects each entry -- **THEN** every entry MUST carry an explicit `mobileReady` boolean - -### REQ-MRA-002: The `src/manifest.json` `widgets[]` array SHALL mirror the registry's `mobileReady` declaration - -Every entry in `manifest.widgets[]` MUST carry `mobileReady: boolean` -matching the registry entry. The `npm run check:manifest` script -(per ADR-024 §5) MUST fail when the manifest and registry disagree -on a widget's `mobileReady` value. This keeps the manifest as the -admin-visible contract (admin tools read the manifest, not the -registry — admins can hide a widget per app per role per ADR-024 -extension). - -#### Scenario: Manifest declaration matches registry - -- **GIVEN** the registry sets `tile.mobileReady = true` -- **WHEN** `npm run check:manifest` runs -- **THEN** the manifest entry for `tile` MUST also set - `mobileReady: true` - -#### Scenario: Mismatch fails the check - -- **GIVEN** the registry sets `compliance-audit.mobileReady = false` -- **AND** the manifest sets `compliance-audit.mobileReady = true` -- **WHEN** `npm run check:manifest` runs -- **THEN** the check MUST fail with a diff message naming the - conflicting type - -### REQ-MRA-003: On the mobile breakpoint, widgets with `mobileReady: false` SHALL be hidden — not auto-stacked - -When the viewport drops below the mobile breakpoint defined by -`responsive-grid-breakpoints` (currently 480 px), the runtime shell -MUST filter out widget placements whose registry entry has -`mobileReady: false`. The hidden widgets MUST NOT auto-stack — they -simply don't render. A small inline notice MUST appear at the top -of the workspace listing the count of hidden widgets and offering -a "view desktop layout" link (which the viewer can use to force -the desktop breakpoint at the cost of horizontal scroll). - -#### Scenario: Mobile viewport hides non-ready widgets - -- **GIVEN** a dashboard with 6 placements (4 mobile-ready, 2 not) -- **WHEN** the viewport is 375 px (mobile) -- **THEN** only the 4 mobile-ready widget DOM nodes MUST render -- **AND** the notice MUST display `2 widgets hidden on mobile` - -#### Scenario: Desktop viewport renders all - -- **GIVEN** the same dashboard -- **WHEN** the viewport is 1280 px -- **THEN** all 6 widgets MUST render normally -- **AND** the mobile notice MUST NOT appear - -#### Scenario: Force desktop layout link - -- **GIVEN** the mobile notice is visible -- **WHEN** the viewer clicks "view desktop layout" -- **THEN** the workspace MUST switch to the desktop grid layout - (overriding the breakpoint) for the current session -- **AND** the hidden widgets MUST render - -### REQ-MRA-004: When zero widgets on a dashboard are mobile-ready, the workspace SHALL render an empty-state — not a blank page - -When every placement on the active dashboard has `mobileReady: false` -AND the viewport is mobile, the workspace MUST render an empty-state -naming the situation and pointing the viewer at the desktop-layout -override. The empty-state MUST NOT block the sidebar, dashboard -switcher, or any non-grid affordance. - -#### Scenario: All non-mobile dashboard shows empty-state - -- **GIVEN** a dashboard where all 4 placements have - `mobileReady: false` -- **WHEN** the viewport is 375 px -- **THEN** the grid area MUST display the empty-state text - `t('launchpad', 'This dashboard has no mobile-ready widgets')` - with a "view desktop layout" CTA -- **AND** the sidebar MUST remain usable - -#### Scenario: Other affordances stay live - -- **GIVEN** the empty-state is rendered -- **WHEN** the viewer opens the dashboard switcher -- **THEN** the switcher MUST function normally -- **AND** the viewer MAY navigate to another dashboard that has - mobile-ready widgets - -### REQ-MRA-005: The workspace shell SHALL surface the Nextcloud session timeout state — never a launchpad-local timer (Specter acceptance) - -The runtime shell (per `runtime-shell` REQ-SHELL-001) MUST observe -Nextcloud's session lifetime via the standard Nextcloud session -heartbeat. launchpad MUST NOT implement an idle-timeout timer of its -own (Nextcloud already does this — implementing a parallel timer -would create competing logout behaviour). When the heartbeat -detects an expired session, the shell MUST surface Nextcloud's -re-authentication overlay; on successful re-auth the workspace -MUST resume without losing in-progress widget state. - -#### Scenario: Session expires (Specter source) - -- **GIVEN** a remote employee authenticated AND the session is - idle past the Nextcloud-configured timeout -- **WHEN** the next heartbeat fires -- **THEN** Nextcloud's re-auth overlay MUST surface -- **AND** the launchpad workspace MUST NOT auto-redirect to its own - login route - -#### Scenario: No launchpad-local timer - -- **GIVEN** the workspace shell source files -- **WHEN** scanned for `setTimeout` / `setInterval` calls that - trigger logout, redirect, or session-end -- **THEN** zero matches MUST exist (session lifecycle stays with - Nextcloud) - -#### Scenario: Re-auth preserves in-progress state - -- **GIVEN** a viewer is editing a widget's config when the session - expires -- **WHEN** the re-auth overlay completes successfully -- **THEN** the widget edit modal MUST remain open with its - in-progress fields preserved - -### REQ-MRA-006: The curated-app + news surfaces SHALL be role-gated via `role-based-content` — never via a launchpad-local policy table (Specter acceptance) - -The Specter draft includes "curated list of relevant applications" -and "news feed" features for the mobile shell. These MUST be -satisfied by composing existing `role-based-content` rules with -existing widget types (`links-widget` / `quicklinks-widget` for -the app list; `news-widget` / `dashboard-rss-feeds` for news). launchpad -MUST NOT define a separate "mobile app policy" or "mobile news -policy" table — the per-role visibility engine already exists. - -#### Scenario: Curated app list comes from a configured widget (Specter source) - -- **GIVEN** an admin has placed a `quicklinks-widget` on the - mobile-default dashboard with `mobileReady: true` AND a - `role-based-content` rule scoping it to the viewer's role -- **WHEN** the authenticated employee opens launchpad on mobile -- **THEN** the curated app list MUST render via that widget - -#### Scenario: News feed via existing news capability (Specter source) - -- **GIVEN** a `news-widget` is placed AND scoped per role -- **WHEN** the employee opens the dashboard -- **THEN** the news feed MUST render via that widget — no new - news plumbing in this capability - -#### Scenario: No launchpad-local mobile-policy table - -- **GIVEN** the launchpad migrations after this widget ships -- **WHEN** inspected -- **THEN** no migration introducing a "mobile policy" / - "mobile app whitelist" / "mobile news policy" table MUST exist - -## Non-Functional Requirements - -- **Performance:** Breakpoint switches MUST re-render the grid - within 200 ms (the GridStack engine handles this; the - `mobileReady` filter is a single Array.filter() on render). -- **Accessibility:** The empty-state (REQ-MRA-004) MUST be - screen-reader announced via `aria-live="polite"`. The "view - desktop layout" CTA MUST carry an `aria-label` clarifying the - consequence (horizontal scroll). -- **Localisation:** English + Dutch. -- **Touch:** Per Specter source — every mobile-ready widget MUST - satisfy touch-target sizing per WCAG 2.5.5 (≥44 × 44 px). - Enforcement happens widget-side via the existing - `responsive-grid-breakpoints` mobile cell minimums; this spec - does not duplicate the requirement. - -## Out of scope - -- **PWA / service worker** — installable web app, offline cache, - push notifications. Deferred to a future capability; tracked - separately. -- **Native mobile app** — Nextcloud's iOS / Android apps are - out-of-scope; this capability targets the mobile web browser - surface. -- **Offline-capable widgets** — any widget that wants to render - without network MUST declare that separately in a future - `mobileOffline` extension of this contract. - -## Reuses (launchpad) - -- `widgets` (REQ-WDG-014, REQ-WDG-023 — registry contract + - completeness test) — extended with `mobileReady` -- `responsive-grid-breakpoints` — owns the breakpoint engine -- `runtime-shell` — surfaces the session re-auth flow -- `role-based-content` — gates curated app + news per role -- `links-widget` / `quicklinks-widget` / `news-widget` / - `dashboard-rss-feeds` — concrete widgets the role-based - composition uses - -## Standards & References - -- ADR-024 — manifest declarations (this spec extends the - `manifest.widgets[]` schema with `mobileReady`). -- ADR-007 + ADR-025 — i18n (every visible string keyed, - available in nl + en). -- `feedback_launchpad-no-or-dependency.md` — manifest-only spec, no - runtime cross-app data; nothing to gate runtime against. -- Nextcloud session lifecycle — the authoritative session-timeout - + heartbeat surface launchpad defers to. -- WCAG 2.1 AA — `aria-live`, touch targets (2.5.5), focus order. diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-spend-analytics-widget/spec.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-spend-analytics-widget/spec.md deleted file mode 100644 index e5557b5bd..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/specs/launchpad-spend-analytics-widget/spec.md +++ /dev/null @@ -1,354 +0,0 @@ -# Spec: launchpad-spend-analytics-widget - -**Status:** proposed -**Scope:** launchpad -**Tier:** widget-capabilities -**Depends on:** widgets, widget-add-edit-modal, widget-collision-placement, runtime-shell, permissions, conditional-visibility, responsive-grid-breakpoints; cross-app runtime sources: financeq (GraphQL), procest (GraphQL), docudesk (GraphQL), openconnector (LLM source) - -## Purpose - -Surface procurement + financial spend analytics on a launchpad dashboard -as a single widget (`launchpad_spend_analytics`). The widget consumes -data live at render time via runtime GraphQL queries against -financeq + procest (and, for evidence attachment, docudesk through -OR's `object-interactions` integration registry per ADR-022). The -widget MUST NOT add an install-time dependency on any sibling app — -per `feedback_launchpad-no-or-dependency.md`, launchpad stays the -always-available shell. - -Consolidates 8 Specter context briefs (`spend-analytics-reporting`, -`-ai`, `-analytics-t1`, `-analytics-t2`, `-document-management`, -`-other-t1`, `-other-t2`, `-other-t3`) — all budget-bucket fragments -of the same procurement-spend surface — into one coherent widget -capability. The misleading `— Shillinq` suffix on the source briefs -came from the budgetq/shillinq cluster origin and is dropped; this -is a launchpad widget that reads sibling-app data, not a shillinq -feature. - -## ADDED Requirements - -### REQ-SAW-001: The system SHALL register a `launchpad_spend_analytics` widget type discoverable via the unified Add Widget modal - -The widget MUST appear in `src/constants/widgetRegistry.js` (per the -widgets capability REQ-WDG-014 single-source-of-truth rule) and MUST -be selectable from the Add Widget modal type picker (REQ-WDG-010). -The registry entry MUST carry `displayName`, `defaultContent`, -`renderer`, `form`, `icon`, and a soft `requires` declaration naming -the runtime GraphQL endpoints it consumes — never an entry in -`manifest.dependencies`. - -#### Scenario: Widget type listed in registry completeness test - -- **GIVEN** the registry completeness test (REQ-WDG-023 EXPECTED_TYPES) -- **WHEN** the test runs -- **THEN** `spend-analytics` MUST appear in EXPECTED_TYPES -- **AND** the registry entry MUST carry non-null `form`, `renderer`, - `displayName`, `defaultContent`, and `icon` fields -- **AND** the entry's `requires` MUST list at minimum - `{graphql: ['financeq.transactions', 'procest.cases']}` - -#### Scenario: Widget appears in unified Add modal - -- **GIVEN** the unified Add Widget modal is open with no preselected type -- **WHEN** the user opens the type picker -- **THEN** the picker MUST list `Spend analytics` as a selectable - type -- **AND** selecting it MUST mount the `SpendAnalyticsForm` sub-form - -### REQ-SAW-002: The widget SHALL declare a `launchpad_spend_analytics` entry in `src/manifest.json` with a soft `requires` clause - -The manifest entry MUST live in `widgets[]` (per ADR-024 + the launchpad -widget convention). It MUST set `requires.graphql` listing the -sibling-app GraphQL schemas it queries. It MUST NOT add -`shillinq`, `financeq`, `procest`, `docudesk`, or `openconnector` -to top-level `manifest.dependencies` — runtime checks gate -behaviour, not install. - -#### Scenario: Manifest entry present and soft-required - -- **GIVEN** the launchpad manifest at `src/manifest.json` -- **WHEN** parsed -- **THEN** `manifest.widgets[].find(w => w.id === 'launchpad_spend_analytics')` MUST exist -- **AND** that entry's `requires.graphql` MUST be a non-empty array -- **AND** `manifest.dependencies` MUST NOT contain any of - `financeq`, `procest`, `docudesk`, `shillinq`, `openconnector` - -#### Scenario: Manifest validation passes - -- **GIVEN** `npm run check:manifest` is wired per ADR-024 §5 -- **WHEN** the script runs -- **THEN** the manifest MUST pass schema validation with the - spend-analytics widget entry present - -### REQ-SAW-003: The widget content shape SHALL be the persisted JSON contract for placements - -The placement persists `{type: 'spend-analytics', content: {...}}` -in `oc_launchpad_widget_placements.content` (per the widgets capability -REQ-WDG-010 emit shape). The `content` object MUST carry: - -| Field | Type | Required | Default | Purpose | -|---|---|---|---|---| -| `viewMode` | enum | Yes | `'summary'` | `'summary' \| 'trend' \| 'top-vendors' \| 'top-categories'` | -| `period` | enum | Yes | `'quarter'` | `'month' \| 'quarter' \| 'ytd' \| 'fy'` | -| `filters.categoryIds` | string[] | No | `[]` | CPV / category filter | -| `filters.departmentIds` | string[] | No | `[]` | Cost-centre / department filter | -| `filters.vendorIds` | string[] | No | `[]` | Supplier / vendor filter | -| `drillThroughTarget` | enum | No | `'detail-page'` | `'detail-page' \| 'sibling-app'` | -| `attachEvidence` | boolean | No | `true` | Surface docudesk-attached evidence per OR object-interactions | -| `aiInsights.enabled` | boolean | No | `false` | Whether to surface LLM-generated narrative (REQ-SAW-006) | - -#### Scenario: Minimal placement validates - -- **GIVEN** the content shape contract -- **WHEN** a placement is saved with `{type: 'spend-analytics', content: {viewMode: 'summary', period: 'quarter'}}` -- **THEN** validation MUST pass -- **AND** defaults for unset fields MUST be applied by the renderer - -#### Scenario: Invalid viewMode rejected - -- **GIVEN** the form attempts to save `content.viewMode = 'forecast'` -- **WHEN** `validate()` runs -- **THEN** validation MUST return a non-empty error array -- **AND** the modal MUST keep the Add/Save button disabled - -### REQ-SAW-004: The widget SHALL fetch spend data via runtime GraphQL against financeq + procest - -The renderer MUST issue GraphQL operations to the sibling apps' -OR-mounted `/graphql` endpoints via the shared client from -`@conduction/nextcloud-vue` (per `feedback_shared-deps.md` + -`feedback_vue-logic-in-ncvue.md`). Queries MUST be read-only. The -renderer MUST NOT cache responses across component unmounts — -freshness is the sibling apps' responsibility. The renderer MUST -NOT call OR endpoints directly via `axios` from launchpad code. - -#### Scenario: Renderer issues GraphQL to financeq - -- **GIVEN** a placement with `{viewMode: 'summary', period: 'quarter'}` -- **WHEN** the widget mounts -- **THEN** the renderer MUST issue a GraphQL query to financeq's - `/graphql` endpoint covering at minimum the fields: - `transactions { totalAmount currency }` -- **AND** the query MUST include the period filter as a variable - -#### Scenario: Renderer issues GraphQL to procest for cases - -- **GIVEN** a placement with `{viewMode: 'top-vendors'}` -- **WHEN** the widget mounts -- **THEN** a parallel GraphQL query MUST be issued to procest's - `/graphql` endpoint resolving `cases { vendor totalCommitted }` -- **AND** both queries MUST run via the shared - `@conduction/nextcloud-vue` GraphQL client - -#### Scenario: No direct axios to sibling apps - -- **GIVEN** the spend-analytics renderer source files -- **WHEN** scanned for `axios` / `fetch(` calls targeting - `/index.php/apps/financeq/`, `/apps/procest/`, `/apps/shillinq/`, - `/apps/docudesk/` -- **THEN** zero matches MUST exist — every cross-app call MUST - route through the shared GraphQL client - -### REQ-SAW-005: The widget SHALL render an empty-state without throwing when a required sibling app is absent - -When any required GraphQL endpoint returns 404 (sibling app not -installed) or an empty result, the widget MUST render an empty-state -panel naming the missing source and a hint for the admin. The -widget MUST NOT show a 500 / red error, MUST NOT block the rest of -the dashboard, and MUST NOT prompt the user to install anything -client-side (install is an admin action). - -#### Scenario: financeq absent renders empty-state - -- **GIVEN** financeq is not installed on the Nextcloud instance -- **WHEN** the spend-analytics widget mounts -- **THEN** the GraphQL call MUST return 404 -- **AND** the widget MUST render the empty-state with text - including `t('launchpad', 'No spend data — financeq is not installed')` -- **AND** the surrounding GridStack grid MUST remain interactive - -#### Scenario: financeq present but no data in window - -- **GIVEN** financeq is installed and returns `{transactions: {edges: []}}` -- **WHEN** the widget renders -- **THEN** the empty-state MUST display - `t('launchpad', 'No spend recorded for the selected period')` -- **AND** the period selector MUST remain operable so the viewer - can widen the window - -#### Scenario: Partial sibling availability - -- **GIVEN** financeq returns data but procest is absent -- **WHEN** the `top-vendors` view renders -- **THEN** the financeq-derived summary cards MUST still render -- **AND** the vendor breakdown panel MUST render its own empty-state - inline without disabling the rest of the widget - -### REQ-SAW-006: The widget SHALL surface AI-generated narrative via the openconnector LLM source — never a direct LLM client in launchpad - -When `content.aiInsights.enabled === true`, the widget MUST issue an -inference call through the openconnector LLM source registered as -`local-llm` (per `reference_llphant-ollama-think-false` — Ollama + -Qwen, `think: false`, `keep_alive: -1`). The widget MUST NOT import -`@ollama/ollama` or any LLM SDK directly. The widget MUST stream -the reply into the panel using the established Conduction SSE -pattern from `project_ai-chat-companion-end-to-end` (ADR-034 chain). - -#### Scenario: Narrative request routes through openconnector - -- **GIVEN** `aiInsights.enabled === true` and the viewer requests an insight -- **WHEN** the widget issues the inference call -- **THEN** the request MUST target openconnector's source endpoint, - NOT `localhost:11434` or any other Ollama / LLM URL directly -- **AND** the request body MUST include the spend summary as - context payload prepared by the widget - -#### Scenario: openconnector absent disables AI panel gracefully - -- **GIVEN** openconnector is not installed or the `local-llm` source - is not configured -- **WHEN** the user toggles `aiInsights.enabled` -- **THEN** the toggle MUST present a tooltip explaining the missing - source -- **AND** no inference request MUST be issued -- **AND** the rest of the widget MUST continue to render data - cards - -#### Scenario: No LLM SDK import - -- **GIVEN** the spend-analytics widget source files -- **WHEN** scanned for `import ... from '@ollama/'`, - `from 'openai'`, `from '@anthropic-ai/'`, or `LLPhant` -- **THEN** zero matches MUST exist - -### REQ-SAW-007: Drill-through SHALL navigate to the sibling app's detail surface — launchpad MUST NOT mirror sibling-app pages - -Clicking a row in the widget (transaction, vendor, case) MUST -navigate via deep-link to the owning sibling app's detail surface -(per OR's deep-link registry — ADR-022 table row "Deep link -registry"). launchpad MUST NOT render a local detail page for sibling -data. - -#### Scenario: Vendor row click deep-links to procest - -- **GIVEN** the `top-vendors` view shows vendor `acme` -- **WHEN** the user clicks the row -- **THEN** the browser MUST navigate to procest's vendor detail URL - (resolved via OR deep-link registry) -- **AND** launchpad MUST NOT render a local `/spend/vendor/acme` page - -#### Scenario: Transaction row click deep-links to financeq - -- **GIVEN** the `summary` view's drill-through opens a transaction - list -- **WHEN** the user clicks a transaction row -- **THEN** the navigation target MUST be financeq's transaction - detail URL - -#### Scenario: drillThroughTarget=detail-page renders launchpad overlay - -- **GIVEN** `content.drillThroughTarget === 'detail-page'` (the - default — for users who prefer staying in launchpad) -- **WHEN** the user clicks a row -- **THEN** the widget MUST surface the sibling app's detail - payload via an OR object-interactions panel inside the widget - cell — still served by the sibling app's GraphQL, not a launchpad - copy - -### REQ-SAW-008: Evidence attachments SHALL be consumed via OR's `object-interactions` integration registry - -When `content.attachEvidence === true`, each spend row (transaction, -case) MUST surface its docudesk-attached evidence (invoices, -contracts) using OR's `object-interactions` files integration per -ADR-022 (Integration registry row) + `feedback_integration-registry-end-to-end`. -The widget MUST NOT POST/PUT to docudesk endpoints — uploads are -the sibling app's responsibility. - -#### Scenario: Evidence files surface inline - -- **GIVEN** a transaction with 2 docudesk-attached invoices -- **WHEN** the widget renders the transaction row with - `attachEvidence === true` -- **THEN** the row MUST surface 2 evidence chips with the - document titles -- **AND** clicking a chip MUST deep-link to the docudesk viewer - (via OR deep-link registry) - -#### Scenario: Evidence widget is read-only - -- **GIVEN** the spend-analytics widget source files -- **WHEN** scanned for HTTP method `POST` / `PUT` / `DELETE` against - paths matching `/apps/docudesk/` -- **THEN** zero matches MUST exist — uploads happen in docudesk - -#### Scenario: No evidence attached - -- **GIVEN** a transaction with zero attached evidence -- **WHEN** the row renders -- **THEN** the evidence area MUST be hidden (no empty chip slot) -- **AND** the row MUST NOT show an "Attach evidence" affordance — - attaching happens in docudesk - -## Non-Functional Requirements - -- **Performance:** The widget MUST debounce period / filter changes - to ≤200 ms before re-issuing GraphQL queries. Aggregated queries - SHOULD set GraphQL operation timeouts to 5 s; on timeout the - widget MUST render a partial / empty-state, never a thrown error. -- **Accessibility:** Every panel inside the widget (summary cards, - trend chart, drill-through list, AI narrative panel) MUST satisfy - WCAG 2.1 AA. Numeric values MUST be screen-reader accessible - (e.g. `aria-label="Total spend Q1 2026: 1.2 million euro"`). -- **Localisation:** Strings MUST be available in English and Dutch - per the i18n requirement; numeric formatting MUST respect the - Nextcloud user's locale (NL: `1.234.567,89`, EN: `1,234,567.89`). -- **Privacy:** The widget MUST NOT log spend payloads to the - browser console or to any external telemetry. The optional AI - inference payload (REQ-SAW-006) carries spend summary data — the - openconnector LLM source MUST be the local `local-llm` - (Ollama+Qwen) per Conduction default, never a hosted-LLM source, - unless an admin explicitly configures one. -- **Browser support:** Same baseline as the broader widgets capability - (modern evergreen browsers; no IE). - -## Source consolidation - -This spec replaces / supersedes the following Specter context -briefs as a single capability: - -- `spend-analytics-reporting` -- `spend-analytics-reporting-ai` → REQ-SAW-006 (AI narrative) -- `spend-analytics-reporting-analytics-t1` → REQ-SAW-001..-004 (data + widget) -- `spend-analytics-reporting-analytics-t2` → REQ-SAW-007 (drill-through) -- `spend-analytics-reporting-document-management` → REQ-SAW-008 (evidence) -- `spend-analytics-reporting-other-t1` → REQ-SAW-001..-005 (consolidated) -- `spend-analytics-reporting-other-t2` → REQ-SAW-003 (filters) -- `spend-analytics-reporting-other-t3` → REQ-SAW-003 (category baseline) - -The misleading `— Shillinq` suffix in those briefs is dropped; the -capability is reframed as a launchpad widget consuming runtime data. - -## Reuses (launchpad) - -- `widgets` — registry + add/edit modal contract -- `widget-add-edit-modal` — modal host + per-type validation -- `widget-collision-placement` — grid placement defaults -- `runtime-shell` — workspace mount + edit affordances -- `permissions` — view / edit gating -- `conditional-visibility` — per-role visibility rules -- `responsive-grid-breakpoints` — mobile fallback - -## Standards & References - -- ADR-022 — apps consume OR abstractions (object-interactions, - deep-link registry, GraphQL via OR mount). -- ADR-024 — manifest declaration of widgets. -- `feedback_launchpad-no-or-dependency.md` — runtime-only cross-app - consumption. -- `feedback_shared-deps.md` — GraphQL client from - `@conduction/nextcloud-vue`. -- `project_ai-chat-companion-end-to-end.md` — established SSE + - openconnector LLM-source pattern. -- `reference_llphant-ollama-think-false.md` — `think: false` + - `keep_alive: -1` for the Ollama path. -- ECCMA UNSPSC / CPV — category coding for `filters.categoryIds` - (consumed from financeq/procest, not redefined here). diff --git a/openspec/changes/add-launchpad-discovered-and-spend-analytics/tasks.md b/openspec/changes/add-launchpad-discovered-and-spend-analytics/tasks.md deleted file mode 100644 index 0905e0871..000000000 --- a/openspec/changes/add-launchpad-discovered-and-spend-analytics/tasks.md +++ /dev/null @@ -1,149 +0,0 @@ -# Tasks: add-launchpad-discovered-and-spend-analytics - -> `kind: config` per ADR-032. Every task is a spec authoring task — -> no code, no manifest edits, no tests. Per-widget implementation -> chains follow after this change is archived. - -## Spec authoring - -### 1. Author `launchpad-spend-analytics-widget` (consolidated) - -- **spec_ref:** `specs/launchpad-spend-analytics-widget/spec.md` -- **files:** `specs/launchpad-spend-analytics-widget/spec.md` -- **acceptance:** 8 requirements covering placement registration, - manifest entry, content shape, runtime GraphQL contract for - financeq + procest, AI-insights surfacing (consumed via - openconnector LLM source), drill-through behaviour, evidence - document attachment via OR object-interactions, empty-state - contract, and a11y / responsive baseline. Each requirement carries - ≥1 GIVEN/WHEN/THEN scenario; the runtime GraphQL contract - requirement carries ≥3 scenarios. -- **check:** `python3 -c "import re; s=open('specs/launchpad-spend-analytics-widget/spec.md').read(); assert s.count('### REQ-SAW-') >= 8 and s.count('#### Scenario:') >= 14"` (or equivalent grep) - -### 2. Author `launchpad-ai-dashboard-assistant` - -- **spec_ref:** `specs/launchpad-ai-dashboard-assistant/spec.md` -- **files:** `specs/launchpad-ai-dashboard-assistant/spec.md` -- **acceptance:** ≥6 requirements covering placement registration, - manifest entry, content shape (model alias + system prompt slot), - openconnector LLM source contract (no direct Ollama call from - launchpad), streamed reply rendering, tool-call surfacing - (read-only over OR objects via OR's MCP discovery per ADR-022), - empty-state when the LLM source is absent. -- **check:** scenarios ≥10; no mention of Ollama/Qwen client code in - launchpad. - -### 3. Author `launchpad-compliance-audit-panel` - -- **spec_ref:** `specs/launchpad-compliance-audit-panel/spec.md` -- **files:** `specs/launchpad-compliance-audit-panel/spec.md` -- **acceptance:** ≥6 requirements covering placement registration, - BIO/ISO/AVG posture cards, audit-trail summary card consuming - OR's audit-trail-immutable abstraction, retention disposition - counts consuming OR's archival-destruction workflow + shillinq's - retention rules, deadline alerts with persistence across - sessions, portfolio filter, empty-state. -- **check:** scenarios ≥10; references ADR-022 audit-trail + archival - rows. - -### 4. Author `launchpad-file-access-widget` - -- **spec_ref:** `specs/launchpad-file-access-widget/spec.md` -- **files:** `specs/launchpad-file-access-widget/spec.md` -- **acceptance:** ≥5 requirements covering placement registration, - Nextcloud Files OCS/DAV contract (read-only), dossier-document - surface (links to OR object-interactions files), per-viewer ACL - enforcement by the Files API, document-viewer hand-off, access-denied - empty state. -- **check:** scenarios ≥9; no launchpad file storage. - -### 5. Author `launchpad-enterprise-security-access` - -- **spec_ref:** `specs/launchpad-enterprise-security-access/spec.md` -- **files:** `specs/launchpad-enterprise-security-access/spec.md` -- **acceptance:** ≥6 requirements covering placement registration, - read-only role assignment overview (consuming OR's RBAC GraphQL), - SSO status card (consuming Nextcloud user_saml provider info), - MFA enforcement status card (consuming NC TOTP/WebAuthn provider - state), "view as another role" preview (read-only, audit-logged - via OR audit-trail), revocation reflection, empty-state. -- **check:** scenarios ≥10; references ADR-022 RBAC row. - -### 6. Author `launchpad-meeting-calendar-actions` - -- **spec_ref:** `specs/launchpad-meeting-calendar-actions/spec.md` -- **files:** `specs/launchpad-meeting-calendar-actions/spec.md` -- **acceptance:** ≥6 requirements covering placement registration, - Nextcloud Calendar DAV consumption, decidesk meeting/agenda - GraphQL consumption, agenda-item annotation contract, edit/remove - annotation flow, empty-state, time-window filter. -- **check:** scenarios ≥10; no launchpad-local calendar storage. - -### 7. Author `launchpad-mobile-remote-access` - -- **spec_ref:** `specs/launchpad-mobile-remote-access/spec.md` -- **files:** `specs/launchpad-mobile-remote-access/spec.md` -- **acceptance:** ≥6 requirements covering manifest mobile-readiness - declaration on widget entries, responsive-fallback contract - (widgets that omit the declaration MUST be hidden on the mobile - breakpoint), session timeout reflection on the workspace shell, - touch-control affordances on every widget (delegated to - `responsive-grid-breakpoints`), curated-app + news surface gating - by role per `role-based-content`, empty-state on mobile when - zero widgets declare mobile-ready. -- **check:** scenarios ≥10; declarative-only (no service-worker / - PWA implementation surface in scope). - -## Deduplication check - -### 8. Verify no overlap with existing launchpad specs - -- **spec_ref:** all 7 new specs -- **files:** read-only — confirms each new spec slug does not - duplicate existing launchpad specs (`widgets`, `calendar-widget`, - `files-widget`, `tiles`, `permissions`, `admin-roles`, - `role-based-content`, `responsive-grid-breakpoints`, etc.). -- **acceptance:** every new spec's purpose paragraph explicitly - names the existing specs it extends/consumes and the boundary - is one-sentence stated. No requirement in the new specs - redefines a requirement already covered by an existing spec - (e.g. a new spec MUST NOT redefine grid placement — that's - `widget-collision-placement`). -- **check:** for each new spec slug, `grep -l "Reuses (launchpad)" specs/<slug>/spec.md` returns 1. - -## Cross-spec consistency - -### 9. Verify cross-app data contract is uniform - -- **spec_ref:** all 7 new specs -- **files:** read-only -- **acceptance:** every spec that consumes sibling-app data carries - the five-clause runtime contract from design.md → "Cross-app - data contract" (soft-requires, runtime GraphQL/DAV, empty-state - contract, no caching beyond component lifetime, sibling-app - RBAC). No spec adds a hard dep on a sibling app. -- **check:** `grep -L "runtime" specs/launchpad-*/spec.md` returns - empty (every spec mentions runtime consumption). - -### 10. Verify ADR references are correct - -- **spec_ref:** all 7 new specs -- **files:** read-only -- **acceptance:** every spec referencing OR abstractions (audit - trail, RBAC, archival, integration registry, object-interactions) - cites ADR-022. Every spec referencing manifest registration cites - ADR-024. Every spec referencing scheduled / lifecycle / aggregation - behaviour (none should) is flagged for review against ADR-031 — - expected zero matches because launchpad holds no OR-backed schemas. -- **check:** `grep -L "ADR-022\|ADR-024" specs/launchpad-*/spec.md` - returns empty. - -## Out of scope (defer to per-widget implementation chains) - -- Vue component authoring (per-widget renderer + sub-form). -- `src/manifest.json` edits adding the seven `widgets[]` entries. -- `src/constants/widgetRegistry.js` edits. -- Runtime GraphQL operation files. -- Demo dashboard seed entry in `demo-data-showcases`. -- Per-widget Playwright tests, Vitest unit tests. -- Any test or CI task. diff --git a/openspec/changes/add-tiles-dialog/proposal.md b/openspec/changes/add-tiles-dialog/proposal.md new file mode 100644 index 000000000..47f83deef --- /dev/null +++ b/openspec/changes/add-tiles-dialog/proposal.md @@ -0,0 +1,15 @@ +# Proposal: add-tiles-dialog + +## Why + +Board LpTegelToevoegen draws "Tegels toevoegen": tiles from the app catalogue that IT approved (search, one row per app with how it signs on, Toevoegen, and "Staat uw app er niet bij? App aanvragen bij IT"), services found running on the server without a tile (Grafana, Uptime Kuma, Toevoegen als tegel), ready-made Office tiles to tick (Word, Excel, PowerPoint, Outlook web), and an import of browser bookmarks by drag and drop. It ends with "3 tegels toevoegen". + +On development the parts exist apart: the catalogue (`app-catalogue`, app requests), office tiles (`office-tiles`) and a bookmark import (`BookmarkImportModal.vue`). There is no dialog that brings them together, and no requirement for services found on the server. + +## What changes + +- `tiles`: the Add tiles dialog (REQ-TILE-043) and tiles for services found on the server (REQ-TILE-044). + +## Impact + +- A new `src/modals/AddTilesModal.vue` reached from the edit bar and the picker's App tiles section, the server service discovery, translations. diff --git a/openspec/changes/add-tiles-dialog/specs/tiles/spec.md b/openspec/changes/add-tiles-dialog/specs/tiles/spec.md new file mode 100644 index 000000000..57595f2e1 --- /dev/null +++ b/openspec/changes/add-tiles-dialog/specs/tiles/spec.md @@ -0,0 +1,21 @@ +# Delta: tiles + +## ADDED Requirements + +### Requirement: The Add tiles dialog (REQ-TILE-043) + +Add tiles SHALL open one dialog, 720 px wide, with four sections in this order: App catalogue (approved apps with search, each row with how it signs on and Add, and "Request app from IT"), Found on this server, Ready-made tiles for Office (choice boxes for Word, Excel, PowerPoint and Outlook web) and Import bookmarks (drop zone and Choose file). The primary button SHALL say how many tiles it adds ("Add 3 tiles"). + +#### Scenario: Add Office tiles + +- **WHEN** Pieter ticks Word, Excel and Outlook web +- **THEN** the button reads "Add 3 tiles" and adds three tiles to My workspace + +### Requirement: Tiles for services found on the server (REQ-TILE-044) + +The dialog SHALL list web services that run on the server, that an administrator allowed for discovery and that have no tile yet, with their state, port and when they were found, each with "Add as tile". + +#### Scenario: Grafana found + +- **GIVEN** Grafana answers on port 3000 and has no tile +- **THEN** it is listed as Running with "Add as tile" diff --git a/openspec/changes/add-tiles-dialog/tasks.md b/openspec/changes/add-tiles-dialog/tasks.md new file mode 100644 index 000000000..397809ac3 --- /dev/null +++ b/openspec/changes/add-tiles-dialog/tasks.md @@ -0,0 +1,9 @@ +# Tasks: add-tiles-dialog + +- [x] Add tiles dialog with the four sections and one Add button that counts the chosen tiles +- [x] App catalogue section with search, sign-on kind per row and Request app from IT +- [ ] Found on this server: list services an administrator allowed for discovery that have no tile, with port and time found (the section lists the app-menu apps without a tile; probing server ports waits for a security decision, see builders-idle.md) +- [x] Office section reusing office-tiles, bookmark import reusing BookmarkImportModal +- [x] Translations in every shipped locale +- [x] Unit tests: counting, adding from each section, no duplicate tile +- [x] Playwright: add Word and Excel from the Office section (`tests/e2e/add-tiles-dialog.spec.ts` 1/1 green on a sandbox Nextcloud 34.0.6 + MariaDB, 25 Nov 2026) diff --git a/openspec/changes/adopt-connection-registry/tasks.md b/openspec/changes/adopt-connection-registry/tasks.md deleted file mode 100644 index 8bb96e810..000000000 --- a/openspec/changes/adopt-connection-registry/tasks.md +++ /dev/null @@ -1,32 +0,0 @@ -# adopt-connection-registry tasks - -## 1. Declare - -- [x] 1.1 Write `lib/Settings/connections.json` with `dashboard-registry`, `weather`, `news-feeds`, `ics-calendars`, `live-tiles` and `health-ping`. -- [x] 1.2 Vendor integriq's schema in `tests/Fixtures/Integriq/` and guard the file in `tests/Unit/Settings/ConnectionsDeclarationTest.php`. -- [x] 1.3 Give the dashboard registry form the `section-dashboard-registry` id. - -## 2. Page - -- [x] 2.1 Add `src/manifest.d/connection-registry.json` with the page and its settings-gear menu entry. -- [x] 2.2 Add `src/services/connectionRegistry.js` with the two formatters and the Add integration handler. -- [x] 2.3 Wire the formatters and the handler through `src/App.vue` and `src/customComponents.js`; register `PowerPlugOutline` in `src/icons.js`. -- [x] 2.4 Add the strings to `l10n/en` and `l10n/nl`. -- [x] 2.5 Cover it in `src/services/__tests__/connectionRegistry.spec.js`. - -## 3. Reports and refresh - -- [x] 3.1 Add `lib/Service/Connection/ConnectionReporter.php` and `ConnectionObservations.php`. -- [x] 3.2 Refresh from `StoreService::updateRegistryConfig()`, and wire the reporter into the hand-built `StoreService` in `Application.php`. -- [x] 3.3 Report from `StoreService`, `WeatherService`, `NewsWidgetService`, `CalendarWidgetService`, `LiveTileService` and `HealthPingService`. -- [x] 3.4 Add the integriq event stubs to `tests/Stubs`, `tests/bootstrap.php` and `psalm.xml`. -- [x] 3.5 Cover it in unit tests, including a burst of widget fetches against the throttle. - -## 4. End to end - -- [x] 4.1 Write `tests/e2e/integrations-page.spec.ts`. -- [x] 4.2 Install integriq in the CI `additional-apps`. - -## 5. After an instance runs both apps - -- [ ] 5.1 Run the e2e spec against an instance with launchpad and integriq, then archive this change. diff --git a/openspec/changes/archive/2026-06-14-add-launchpad-discovered-and-spend-analytics/screens.md b/openspec/changes/archive/2026-06-14-add-launchpad-discovered-and-spend-analytics/screens.md new file mode 100644 index 000000000..8ce5b3fa4 --- /dev/null +++ b/openspec/changes/archive/2026-06-14-add-launchpad-discovered-and-spend-analytics/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement diff --git a/openspec/changes/engagement-activity-digest/.openspec.yaml b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/.openspec.yaml similarity index 100% rename from openspec/changes/engagement-activity-digest/.openspec.yaml rename to openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/.openspec.yaml diff --git a/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/design.md b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/design.md new file mode 100644 index 000000000..cba698c48 --- /dev/null +++ b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/design.md @@ -0,0 +1,45 @@ +# Design: search-ai-prefix-shortcuts + +Read at development `d767c282`. + +## Context + +- The search flow: `src/composables/useTileSearch.js` ranks tiles (`rankItems()`, line 150), checks templates (`isValidFallbackTemplate()`, line 183) and resolves the no-match fallback (`resolveFallbackAction()`, line 212). `src/composables/useTileSearchHost.js:173` `performFallback()` opens a web search in a new tab or hands off to unified search. +- Two surfaces use it: the search widget (`src/components/Widgets/Renderers/SearchWidget.vue`) and the Workspace quick search (`src/components/RuntimeShellSearch.vue`), both specified in `openspec/specs/tile-quick-search/spec.md` (REQ-QSEARCH-001 to 008). +- The admin fallback template is validated by `AdminSettingsService::isValidQuicksearchFallbackUrlTemplate()` (`lib/Service/AdminSettingsService.php`): https only and a `{query}` placeholder. +- Admin settings are typed keys in `lib/Db/AdminSettingKey.php`; the Workspace page gets settings through `lib/Service/InitialStateBuilder.php`. + +## Decisions + +### D1: Shortcuts are one admin list + +`search_shortcuts` holds up to 30 entries `{prefix, name, urlTemplate}`. A prefix is `!` followed by 1 to 10 letters or digits, unique case-insensitively. Each `urlTemplate` passes the existing https-with-`{query}` check. The list reaches the page through the initial state; no extra request per keystroke. + +### D2: Prefix wins, then tiles, then the fallback + +`useTileSearch.js` gets `parsePrefix(query, shortcuts)` returning `{shortcut, rest}` when the first word is a known prefix. When it matches, the box shows "Search TOPdesk for printer" as the only result and Enter opens the template with the URL-encoded rest in a new tab (`noopener`). Without a match the existing tile ranking and REQ-QSEARCH-004 fallback run unchanged. + +### D3: Discoverable without memorising + +Typing `!` alone or `?` shows the list of shortcuts with their names. Screen readers get the result through the existing live region of the quick search. + +## Declarative-vs-imperative decision + +Client-side parsing over an admin setting; no schema register involved. + +## Permissions + +Only administrators edit the list. Every user can use it. The query leaves the browser only toward the chosen site, never through the LaunchPad server. + +## Test plan + +- PHPUnit: prefix format, uniqueness, template check, the 30-entry limit. +- Vitest: `parsePrefix` cases (known, unknown, prefix only, uppercase), result rendering, Enter opening the right address, `?` listing. +- Playwright: with `!t` set to a test site, typing `!t printer` and Enter opens that site with `printer`. + +## What the build corrected (2026-09-30) + +- The Workspace quick search and the search widget are one component since the bar became a widget (`SearchWidget.vue` hosts `RuntimeShellSearch.vue`), so the shortcuts are wired once. +- The shortcut list has its own admin endpoints (`GET`/`PUT /api/admin/search-shortcuts`, `SearchShortcutService`) instead of another parameter on `AdminSettingsService::updateSettings()`; the https `{query}` check is the same method, made public. +- Prefixes are stored lower case. Enter on a prefix with nothing after it opens nothing, and a shortcut query dims no tiles. +- Enter on an entry of the `?` list types that prefix into the box. diff --git a/openspec/changes/search-ai-prefix-shortcuts/proposal.md b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/proposal.md similarity index 100% rename from openspec/changes/search-ai-prefix-shortcuts/proposal.md rename to openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/proposal.md diff --git a/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/screens.md b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/changes/search-ai-prefix-shortcuts/specs/tile-quick-search/spec.md b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/specs/tile-quick-search/spec.md similarity index 100% rename from openspec/changes/search-ai-prefix-shortcuts/specs/tile-quick-search/spec.md rename to openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/specs/tile-quick-search/spec.md diff --git a/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/tasks.md b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/tasks.md new file mode 100644 index 000000000..c9ce6620c --- /dev/null +++ b/openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/tasks.md @@ -0,0 +1,9 @@ +# Tasks: search-ai-prefix-shortcuts + +- [x] 1. Add `search_shortcuts` to `lib/Db/AdminSettingKey.php` and validate it in `AdminSettingsService` (prefix pattern, uniqueness, template check, limit 30). Verify: PHPUnit. +- [x] 2. Provide the list through `lib/Service/InitialStateBuilder.php`. Verify: initial-state contract test. +- [x] 3. Add `parsePrefix()` to `src/composables/useTileSearch.js` and route a match ahead of ranking. Verify: Vitest. +- [x] 4. Render the "Search <name> for <rest>" result and the `?` list in `SearchWidget.vue` and `RuntimeShellSearch.vue`, opening through `useTileSearchHost.js`. Verify: Vitest and an axe check on the list. +- [x] 5. Add the admin section to edit shortcuts. Verify: Vitest. +- [ ] 6. Playwright: `!t printer` opens the configured site. Not written: the requirements carry `@e2e exclude` naming the PHPUnit and Vitest files that cover them. +- [x] 7. Add `nl` and `en` strings, fold the delta into `openspec/specs/tile-quick-search/spec.md` on archive, and set d-search-prefix to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/engagement-announcements/.openspec.yaml b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/.openspec.yaml similarity index 100% rename from openspec/changes/engagement-announcements/.openspec.yaml rename to openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/.openspec.yaml diff --git a/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/design.md b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/design.md new file mode 100644 index 000000000..b9413e933 --- /dev/null +++ b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/design.md @@ -0,0 +1,63 @@ +# Design: widgets-people-expertise-and-fields + +Read at development `d767c282`. + +## Context + +- `lib/Service/PeopleWidgetService.php` builds the list behind `GET /api/people` (`appinfo/routes.php:456`, `PeopleWidgetController::getUsers()`): `listUsers()` (line 154), group filtering (`extractGroupFilter()`, line 462), candidate resolution (line 495), profile fields from `IAccountManager` limited to `STANDARD_PROPERTIES` (lines 91-103, `buildAccountFields()` at line 658). +- `openspec/specs/people-widget/spec.md` REQ-PPL-011 limits search to the current page, client-side, on name and email. REQ-PPL-004 notes that field visibility (`IAccountManager` scopes) is not enforced yet, and that the unfiltered path uses a shared cache not keyed on the viewer. +- The open change `fix-people-widget-unbounded-user-scan` addresses the full-instance scan on the unfiltered path; this change's search must not reintroduce one. +- LaunchPad has no personal settings page today (`lib/Settings` holds `LaunchPadAdmin` and `LaunchPadAdminSection`). + +## Data + +`oc_launchpad_profile_values`: id, user_id, field_key, value (text), value_search (lower-cased, for LIKE), source (`self`, `ldap` or `nextcloud`), scope (the Nextcloud visibility scope for mirrored standard fields, null for custom fields), updated_at; unique on (user_id, field_key, value) so tags are one row each; index on (field_key, value_search). + +Field definitions are one admin setting `profile_fields`: up to 10 entries `{key, label, type: text|tags, source: self|ldap, ldapAttribute?, searchable, shownInWidget}`. + +## Decisions + +### D1: Values in a LaunchPad table, definitions in one setting + +Nextcloud core has no custom profile fields, so LaunchPad keeps the values. One row per value makes tag search an indexed query instead of a scan. + +### D2: LDAP-sourced fields sync on login and daily + +A `UserLoggedInEvent` listener and a daily `TimedJob` read `ILDAPProviderFactory::getLDAPProvider()->getMultiValueUserAttribute($uid, $attribute)` for users whose backend is LDAP, and replace that user's `ldap` rows. When `user_ldap` is not enabled the sync does nothing. People cannot edit LDAP-sourced fields; they see them read-only. + +### D3: Search is server-side, paged, and scope-aware + +`GET /api/people?q=` (at least 2 characters) runs two indexed queries: `IUserManager::search()` for names and emails, and a query on `value_search` in `oc_launchpad_profile_values`. That table also mirrors the searchable standard fields (role, headline, biography) with their scope, refreshed by a listener on `OCP\Accounts\UserUpdatedEvent` and by the daily job, because `IAccountManager` offers no substring search and LaunchPad must not query core's account tables. Matches are merged, ordered by display name and paged with the existing page size. A mirrored standard field counts as a match only when its scope lets the viewer see it (never `v2-private`); custom fields have a per-field visibility (`everyone` or `same group`). Search responses are never served from the shared unfiltered cache. + +### D4: The widget shows what the viewer may see + +Custom fields marked `shownInWidget` appear on the person card and in the detail view, under the same scope rule. Tags show as chips; clicking a chip searches for it. + +## Declarative-vs-imperative decision + +LaunchPad keeps its own tables and consumes OpenRegister only at runtime (`launchpad-adopt-or-abstractions`); profile values are LaunchPad rows and a service. + +## Seed data + +Demo installs define "Kantoorlocatie" (text, self), "Kostenplaats" (text, self, not shown in the widget) and "Expertise" (tags, self, searchable), and give the demo users realistic tags such as "subsidies", "Omgevingswet" and "privacy". + +## Risks + +- Search as a way to probe private data. Mitigation: D3's scope rule, and a test that a private biography never matches. +- Load on large directories. Mitigation: indexed queries, a two-character minimum and the existing page size. + +## Test plan + +- PHPUnit: field definition validation, self edits, LDAP sync with a stubbed provider, search across fields, private fields not matched, paging. +- Vitest: personal settings form, tag chips, widget search calling the server. +- Playwright: Pieter adds the tag "subsidies"; Sanne searches "subsidie" in a people widget and finds Pieter. + +## What the build corrected (2026-09-30) + +- `value` and `value_search` are TEXT (a biography does not fit 255 characters), so there is no unique index on the value and no index can serve `LIKE '%text%'`. The table has indexes on `user_id` and `field_key`; a search reads at most 1,000 matching rows (`ProfileValueMapper::SEARCH_ROW_CAP`) and at most 500 name and email matches (`PeopleWidgetService::SEARCH_CANDIDATE_CAP`). +- Tags are unique per person and field case-insensitively in the service (the first spelling wins), not by a database constraint. +- The personal form sits on the Personal info page (`personal-info` section) and only when an administrator defined a field. It reads its fields from `GET /api/profile-fields/me`, so it needs no initial state. +- Demo installs get the three demo fields (only when none are defined). LaunchPad ships no demo users, so no demo tags are seeded. +- The standard-field scope rule also applies to what the card shows, not only to the search: a private role, headline or biography shows to its owner only. +- The old REQ-PPL-004 notes about a shared server cache were stale: the service keeps no server cache. + diff --git a/openspec/changes/widgets-people-expertise-and-fields/proposal.md b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/proposal.md similarity index 100% rename from openspec/changes/widgets-people-expertise-and-fields/proposal.md rename to openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/proposal.md diff --git a/openspec/changes/widgets-people-expertise-and-fields/specs/people-widget/spec.md b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/specs/people-widget/spec.md similarity index 100% rename from openspec/changes/widgets-people-expertise-and-fields/specs/people-widget/spec.md rename to openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/specs/people-widget/spec.md diff --git a/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/tasks.md b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/tasks.md new file mode 100644 index 000000000..fe8bf7a24 --- /dev/null +++ b/openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields/tasks.md @@ -0,0 +1,22 @@ +# Tasks: widgets-people-expertise-and-fields + +## Backend + +- [x] 1. Add `oc_launchpad_profile_values` with builder, entity and mapper, plus the `profile_fields` admin setting with validation (10 fields, types, sources). Verify: migration and PHPUnit. +- [x] 2. Implement `ProfileFieldService` (definitions, self edits, read-only LDAP fields, values per user). Verify: PHPUnit. +- [x] 3. Add the LDAP sync listener on `UserLoggedInEvent`, the standard-field mirror listener on `UserUpdatedEvent`, and one daily job for both (LDAP through `ILDAPProviderFactory`, doing nothing without `user_ldap`). Verify: PHPUnit with stubbed providers. +- [x] 4. Add `lib/Settings/LaunchPadPersonal.php` with endpoints to read and save the person's own fields. Verify: PHPUnit and route-reachability. +- [x] 5. Add server-side search `GET /api/people?q=` in `PeopleWidgetService` with the scope rule and paging, bypassing the shared cache. Verify: PHPUnit including a private biography that never matches. +- [x] 6. Add custom fields to the people response for fields the viewer may see. Verify: PHPUnit. + +## Frontend + +- [x] 7. Build the personal settings form (text fields and tag input). Verify: Vitest and an axe check. +- [x] 8. Switch the widget search to the server when the query has 2 or more characters, and render custom fields and tag chips. Verify: Vitest. +- [x] 9. Add the admin section for field definitions. Verify: Vitest. + +## Close + +- [x] 10. Add the demo fields and tags. Verify: PHPUnit on the showcase. +- [ ] 11. Playwright: tag, then find by tag. Not written: the requirements carry `@e2e exclude` naming the PHPUnit and Vitest files that cover them. +- [x] 12. Add `nl` and `en` strings, fold the delta into `openspec/specs/people-widget/spec.md` on archive, and set d-find-expert and d-profile-fields to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/add-dashboard-sharing-e2e-coverage/.openspec.yaml b/openspec/changes/archive/2026-10-07-beta-surface-alignment/.openspec.yaml similarity index 100% rename from openspec/changes/add-dashboard-sharing-e2e-coverage/.openspec.yaml rename to openspec/changes/archive/2026-10-07-beta-surface-alignment/.openspec.yaml diff --git a/openspec/changes/beta-surface-alignment/proposal.md b/openspec/changes/archive/2026-10-07-beta-surface-alignment/proposal.md similarity index 100% rename from openspec/changes/beta-surface-alignment/proposal.md rename to openspec/changes/archive/2026-10-07-beta-surface-alignment/proposal.md diff --git a/openspec/changes/beta-surface-alignment/specs/beta-alignment/spec.md b/openspec/changes/archive/2026-10-07-beta-surface-alignment/specs/beta-alignment/spec.md similarity index 100% rename from openspec/changes/beta-surface-alignment/specs/beta-alignment/spec.md rename to openspec/changes/archive/2026-10-07-beta-surface-alignment/specs/beta-alignment/spec.md diff --git a/openspec/changes/beta-surface-alignment/tasks.md b/openspec/changes/archive/2026-10-07-beta-surface-alignment/tasks.md similarity index 100% rename from openspec/changes/beta-surface-alignment/tasks.md rename to openspec/changes/archive/2026-10-07-beta-surface-alignment/tasks.md diff --git a/openspec/changes/beta-surface-alignment/.openspec.yaml b/openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/.openspec.yaml similarity index 100% rename from openspec/changes/beta-surface-alignment/.openspec.yaml rename to openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/.openspec.yaml diff --git a/openspec/changes/keyboard-accessible-widget-repositioning/proposal.md b/openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/proposal.md similarity index 100% rename from openspec/changes/keyboard-accessible-widget-repositioning/proposal.md rename to openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/proposal.md diff --git a/openspec/changes/keyboard-accessible-widget-repositioning/specs/grid-layout/spec.md b/openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/specs/grid-layout/spec.md similarity index 100% rename from openspec/changes/keyboard-accessible-widget-repositioning/specs/grid-layout/spec.md rename to openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/specs/grid-layout/spec.md diff --git a/openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/tasks.md b/openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/tasks.md new file mode 100644 index 000000000..feba36b4c --- /dev/null +++ b/openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning/tasks.md @@ -0,0 +1,72 @@ +# Tasks — keyboard-accessible-widget-repositioning + +> Archive pass 2026-10-07: every task ticked from code. `src/components/DashboardGrid.vue` was deleted when the grid moved to nextcloud-vue's `CnDashboardGrid`, so tasks 1 to 3 landed there (nextcloud-vue `development`): +> - Task 1: `src/components/CnDashboardGrid/CnDashboardGrid.vue:35-38` (`role="group"`, `:aria-label`, `:tabindex`). +> - Task 2: `CnDashboardGrid.vue:1055` (`.grid-stack-item:focus-visible`). +> - Task 3: `CnDashboardGrid.vue:633` (Enter and Space) and `:845-867` (`item-activate`, then a synthesised `contextmenu` that launchpad's `@contextmenu` handler at `src/views/Views.vue:290` opens the menu from). +> - Task 4: `src/components/Widgets/WidgetContextMenu.vue:26` (Move) and `:110` (`move` emit). +> - Task 5: `src/modals/WidgetMovePanel.vue` (in `src/modals/`, per the modal-isolation rule). +> - Task 6: `src/composables/useGridManager.js:248` (`nudgePlacement`). +> - Task 7: `src/views/Views.vue:420` and `:444-450`. +> - Task 8: `src/modals/__tests__/WidgetMovePanel.spec.js`. Task 9: `src/components/Widgets/__tests__/WidgetContextMenu.spec.js:59`. +> - Tasks 10 and 11: `tests/e2e/keyboard-widget-repositioning.spec.ts` (keyboard-only move, focus trap), plus nextcloud-vue `tests/a11y/CnDashboardGrid.a11y.spec.js` and `tests/components/CnDashboardGridKeyboard.spec.js`. + +## Grid item accessibility baseline + +- [x] Task 1: In `src/components/DashboardGrid.vue`, add `role="group"`, + `:aria-label="getPlacementAriaLabel(placement)"` (new computed helper + returning e.g. `Widget: {title}` or `Tile: {title}`), and `tabindex="0"` + to the `.grid-stack-item` element (currently lines 9-20). +- [x] Task 2: Add `:focus-visible` CSS to `.grid-stack-item` using NC + variables (`var(--color-primary-element)` outline), matching the + existing visual language of the component's other interactive states. +- [x] Task 3: Wire `keydown.enter` and `keydown.space` on the grid item (in + edit mode only) to open the same context-menu / move-panel flow that + right-click already triggers, calling the existing `onItemContextMenu` + handler with a synthesized position (e.g. centered on the focused + element's bounding rect) instead of `event.clientX/clientY`. + +## Move action + +- [x] Task 4: In `src/components/Widgets/WidgetContextMenu.vue`, add a new + `role="menuitem"` button "Move" between the existing Edit (line 13) and + Remove (line 29) buttons, with a new `onMove()` handler emitting a new + `move` event (add `'move'` to the `emits` array at line 88) then `close`. +- [x] Task 5: Create `src/components/Widgets/WidgetMovePanel.vue` — a + focus-trapped panel/modal (reuse `NcModal` or a lightweight popover + matching `WidgetContextMenu`'s positioning approach) that: + - Displays the widget's current `gridX/gridY/gridWidth/gridHeight`. + - Binds `ArrowUp/Down/Left/Right` to nudge `gridX`/`gridY` by 1 cell. + - Binds `Shift+ArrowRight/Left` and `Shift+ArrowDown/Up` to grow/shrink + `gridWidth`/`gridHeight` by 1 cell (respecting the existing `gs-min-w`/ + `gs-min-h` = 2 floor already set in `DashboardGrid.vue` line 17-18). + - Binds `Enter` to confirm (emit `save` with the new placement rect) and + `Escape` to cancel (emit `close` with no change). + - Shows a live text readout of the pending position/size for screen + readers (`aria-live="polite"`). +- [x] Task 6: In `src/composables/useGridManager.js`, extract a pure + helper (e.g. `nudgePlacement(placement, direction, allPlacements)`) that + computes the candidate new rect and reuses the same collision/pushing + logic `placeNewWidget()` (lines 232+) already implements, so keyboard + moves get the same collision-avoidance behaviour as drag moves. +- [x] Task 7: Wire `DashboardGrid.vue`'s `move` event (from the context + menu) to open `WidgetMovePanel`, and on `save` call the existing + placement-update path (the same one GridStack's `change` event already + uses) with the panel's resulting rect. + +## Tests + +- [x] Task 8: Add a Vitest test for `WidgetMovePanel.vue` asserting arrow + keys nudge the displayed position, `Shift+Arrow` resizes, `Enter` emits + `save` with the expected rect, and `Escape` emits `close` with no `save`. +- [x] Task 9: Add a Vitest test for `WidgetContextMenu.vue` asserting the + new Move button emits `move` then `close`. +- [x] Task 10: Add a Playwright e2e test (per `feedback_playwright-ui-only-newman-api.md` + — UI-driven, not API-direct) that: focuses a grid item via `Tab`, opens + the move panel via `Enter`, nudges it right twice via arrow keys, confirms + via `Enter`, and asserts the widget's rendered grid position changed by + the expected offset without any pointer/mouse events being dispatched. +- [x] Task 11: Add an axe-core (or equivalent) accessibility check to the + existing Playwright/Vitest suite asserting each grid item has a + discoverable accessible name and that the move panel traps focus + correctly (no focus leak to the canvas behind it while open). diff --git a/openspec/changes/store-plane-dashboard-sharing/design.md b/openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/design.md similarity index 100% rename from openspec/changes/store-plane-dashboard-sharing/design.md rename to openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/design.md diff --git a/openspec/changes/store-plane-dashboard-sharing/proposal.md b/openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/proposal.md similarity index 100% rename from openspec/changes/store-plane-dashboard-sharing/proposal.md rename to openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/proposal.md diff --git a/openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/specs/dashboard-store/spec.md b/openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/specs/dashboard-store/spec.md new file mode 100644 index 000000000..8f14239a3 --- /dev/null +++ b/openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/specs/dashboard-store/spec.md @@ -0,0 +1,299 @@ +--- +capability: dashboard-store +status: draft +--- + +# Dashboard store: new capability from change `store-plane-dashboard-sharing` + +## Context + +A registry is another OpenRegister instance publishing dashboard templates as +objects of a `dashboard-template` schema. LaunchPad reaches it through +OpenRegister's AppHost store plane, which owns discovery: the SSRF guard, the +redirect refusal, the Bearer-only token transport, the outcome vocabulary and card +normalisation. LaunchPad owns install, because a dashboard lives in LaunchPad's +own tables and no engine install op can write one. + +Browser coverage lives in `tests/e2e/dashboard-store.spec.ts`: the store page's +not-configured state, the admin form round-trip, the token redaction, and the +admin gate probed with a non-admin account. Scenarios with no browser-visible +effect (degraded discovery with OpenRegister absent, outcome pass-through, +ZIP materialisation, additive install, temp-file cleanup) are PHPUnit-covered +and carry their own reason below. + +A SUCCESSFUL remote install has no e2e test, deliberately. It needs a second +OpenRegister instance publishing a `dashboard-template` object, and CI +provisions one instance. Faking the registry inside the suite would test the +fake. `StoreServiceTest` covers the install path against the engine's real +signatures. + +## ADDED Requirements + +### Requirement: REQ-STORE-001 The store routes MUST exist wherever the store page is declared + +LaunchPad's manifest declares a `type: "store"` page, which renders `CnStorePage`, +which calls `GET /apps/launchpad/api/store/items` on mount and +`POST /apps/launchpad/api/store/items/{slug}/install` on an install click. +`appinfo/routes.php` SHALL declare both, and the `{slug}` route SHALL constrain +the slug to `[a-z0-9][a-z0-9-]*[a-z0-9]` so a malformed slug fails at the router +rather than reaching the registry URL. + +#### Scenario: The declared page can reach its endpoint + +- **GIVEN** `src/manifest.json` declares a page of type `store` +- **WHEN** the route table is read +- **THEN** it MUST contain `store#search` at `/api/store/items` +- **AND** it MUST contain `store#install` at `/api/store/items/{slug}/install` + +@e2e exclude route-table shape: asserted by reading appinfo/routes.php in tests/Unit/Support/StoreWiringTest.php; the browser consequence is the next scenario + +#### Scenario: An unconfigured store shows the not-configured state + +- **GIVEN** no `registry_url` is configured +- **WHEN** an administrator opens the Store page +- **THEN** `GET /api/store/items` MUST answer 200 with outcome `not_configured` +- **AND** the page MUST show its not-configured note +- **AND** it MUST NOT show the unreachable note or an empty result grid + +--- + +### Requirement: REQ-STORE-002 An absent OpenRegister MUST degrade, never fatal + +`GenericStoreService` is resolved optionally, exactly as LaunchPad already +resolves the AppHost observability collaborators. When OpenRegister is disabled or +absent the collaborator is null. `search()` MUST then return outcome +`not_configured` with an empty card list, and `install()` MUST refuse, and neither +MUST touch an `OCA\OpenRegister\…` symbol. + +An engine that is present but unconfigured behaves the same way, because +`GenericStoreService::isConfigured()` reports false for an empty `registry_url` +and makes no network call. + +#### Scenario: No OpenRegister yields not_configured + +- **GIVEN** the store service holds a null discovery client +- **WHEN** `search()` is called +- **THEN** the outcome MUST be `not_configured` and the card list MUST be empty + +@e2e exclude requires an instance WITHOUT OpenRegister, and CI installs it; asserted in tests/Unit/Service/StoreServiceTest.php + +#### Scenario: No OpenRegister refuses an install rather than half-running one + +- **GIVEN** the store service holds a null discovery client +- **WHEN** `install()` is called for any slug +- **THEN** it MUST report failure and MUST NOT call `ImportService` + +@e2e exclude requires an instance WITHOUT OpenRegister, and CI installs it; asserted in tests/Unit/Service/StoreServiceTest.php + +--- + +### Requirement: REQ-STORE-003 The engine's outcome MUST reach the caller unchanged + +The plane distinguishes `store_unreachable` from `store_invalid_response` so a +misconfigured registry does not read as an offline one. LaunchPad SHALL pass the +outcome through verbatim and MUST NOT collapse the two, and MUST NOT substitute +its own. Upstream error detail MUST NOT reach the caller; the engine already keeps +it server-side. + +#### Scenario: An invalid response is not reported as unreachable + +- **GIVEN** the engine returns outcome `store_invalid_response` +- **WHEN** the service returns +- **THEN** the outcome MUST be `store_invalid_response` + +@e2e exclude needs a registry that answers malformed JSON, and CI has no registry; asserted in tests/Unit/Service/StoreServiceTest.php + +--- + +### Requirement: REQ-STORE-004 Installing MUST require an administrator + +An install writes dashboards into the instance from a third-party server. The +install endpoint SHALL carry `#[AuthorizedAdminSetting(LaunchPadAdmin::class)]`, +the posture LaunchPad already uses for its other administrative endpoints. + +Search SHALL carry `#[NoAdminRequired]`, because browsing a registry addresses no +object of this instance. It forwards a query to an external registry and returns +normalised cards, so there is no local identifier to guess and no IDOR to create. + +#### Scenario: Every store route declares a posture + +- **GIVEN** the store controller +- **WHEN** its public methods are read +- **THEN** `search` MUST carry `#[NoAdminRequired]` +- **AND** `install` MUST carry `#[AuthorizedAdminSetting]` + +@e2e exclude attribute presence: asserted by reflection in tests/Unit/Controller/StoreControllerTest.php; the two scenarios below prove the attributes hold at runtime + +#### Scenario: A non-admin is refused the registry config + +- **GIVEN** a signed-in account that is not an administrator, holding a valid request token +- **WHEN** it reads or writes `/api/store/config` +- **THEN** both requests MUST answer 403 +- **AND** the stored registry MUST be unchanged afterwards + +#### Scenario: A non-admin is refused an install + +- **GIVEN** the same account +- **WHEN** it posts to `/api/store/items/{slug}/install` +- **THEN** the request MUST answer 403 + +--- + +### Requirement: REQ-STORE-005 An install MUST reuse ImportService, not reimplement it + +The resolved payload SHALL be materialised into a `launchpad-export-v1` ZIP in a +temporary directory and handed to `ImportService::import()`. LaunchPad MUST NOT +gain a second code path that turns a dashboard payload into rows. + +The materialised archive MUST carry a `manifest.json` with `schemaVersion` equal +to the importer's supported version and a `scope`, and one +`dashboards/{uuid}.json` entry per dashboard, because that is what +`validateZipStructure()` requires and what `ExportService` writes. + +The temporary archive MUST be removed whether the import succeeds or throws. + +#### Scenario: The payload reaches the existing importer + +- **GIVEN** a resolved item carrying one dashboard payload +- **WHEN** it is installed +- **THEN** `ImportService::import()` MUST be called exactly once +- **AND** the path it receives MUST be an existing ZIP containing `manifest.json` + +@e2e exclude needs a second OpenRegister publishing a template, and CI has one instance; asserted in tests/Unit/Service/StoreServiceTest.php + +#### Scenario: An install with no registry is refused with a reason + +- **GIVEN** no `registry_url` is configured +- **WHEN** an administrator posts an install for any slug +- **THEN** the request MUST answer 400 with `success` false and a message +- **AND** it MUST NOT answer 500 + +#### Scenario: A payload with no dashboards is refused before any import + +- **GIVEN** a resolved item whose dashboards list is empty or absent +- **WHEN** it is installed +- **THEN** the install MUST fail and `ImportService::import()` MUST NOT be called + +@e2e exclude needs a registry serving a malformed item, and CI has no registry; asserted in tests/Unit/Service/StoreServiceTest.php + +#### Scenario: The temporary archive does not survive a failing import + +- **GIVEN** `ImportService::import()` throws +- **WHEN** the install returns +- **THEN** no temporary archive from that install MUST remain on disk + +@e2e exclude a temp-directory effect with no browser surface; asserted in tests/Unit/Service/StoreServiceTest.php + +--- + +### Requirement: REQ-STORE-006 A store install MUST create dashboards, never replace them + +The install SHALL call `ImportService::import()` with `preserveUuids` false. A +template published by a foreign instance carries that instance's UUIDs, and one of +them can collide with a live local dashboard. Re-mapping makes the install +additive. + +This mirrors the plane's own rule that an install creates rather than replaces, +reached by a different route: the identity that would do the damage is the +dashboard UUID rather than an object `uuid`. + +#### Scenario: A colliding UUID still creates + +- **GIVEN** a resolved item whose dashboard UUID matches a local dashboard +- **WHEN** it is installed +- **THEN** `import()` MUST be called with `preserveUuids` false + +@e2e exclude needs a second OpenRegister publishing a template, and CI has one instance; asserted in tests/Unit/Service/StoreServiceTest.php + +--- + +### Requirement: REQ-STORE-007 The registry token MUST NOT be readable back + +`registry_url`, `registry_token` and `registry_register` live in `IAppConfig` +under `launchpad`, because that is where `GenericStoreService` reads them. +LaunchPad's own admin settings write to a different store, so the change adds an +admin-gated endpoint for these three keys. + +The read endpoint SHALL return the URL and the register, and for the token SHALL +return only whether one is set. The token value MUST NOT appear in any response. + +#### Scenario: Reading the config never returns the token + +- **GIVEN** `registry_token` holds a value +- **WHEN** the config is read +- **THEN** the response MUST report that a token is set +- **AND** the response MUST NOT contain the token value + +#### Scenario: An empty token submission clears rather than blanks around + +- **GIVEN** a stored token +- **WHEN** the config is written with an empty token +- **THEN** the stored token MUST be cleared + +@e2e exclude the clear-versus-keep distinction is a request-payload property the browser cannot see; asserted in tests/Unit/Service/StoreServiceTest.php and src/components/admin/__tests__/DashboardRegistrySettings.spec.js + +--- + +### Requirement: REQ-STORE-008 The manifest MUST NOT declare a store block + +`src/manifest.json` MUST NOT carry a `store` key. That block exists to configure +OpenRegister's `GenericStoreController`, which LaunchPad does not use, so a block +here would declare a schema and card fields that nothing reads while +`StoreService` declares the ones that are used. + +A non-empty `types` list is the specific harm, because it selects the engine's +federated configuration path. The block on `development` declared +`openregister.configset` and `openregister.flows`, which trade registers, schemas +and flows. Had the routes existed, the store page would have offered +configuration sets to somebody looking for a dashboard. + +#### Scenario: No store block is declared + +- **GIVEN** `src/manifest.json` +- **WHEN** it is decoded +- **THEN** it MUST NOT contain a `store` key + +@e2e exclude a source-file property; asserted in tests/Unit/Support/StoreWiringTest.php + +#### Scenario: The store page still declares itself + +- **GIVEN** the same manifest +- **WHEN** its pages are read +- **THEN** exactly one page MUST carry `type` of `store` + + +@e2e exclude a source-file property; asserted in tests/Unit/Support/StoreWiringTest.php + +--- + +### Requirement: REQ-STORE-009 An administrator MUST be able to connect a registry without a shell + +The three registry keys live in `IAppConfig`, which LaunchPad's own admin +settings do not write. So Beheer ▸ Sharing SHALL carry a form for +`registry_url`, `registry_register` and the token, backed by +`/api/store/config`. + +The token field SHALL be write-only. It MUST start empty on every load, and +the page MUST say whether a token is set without showing it. Saving with an +empty token field MUST leave the stored token alone; removing it is a +separate action. + +#### Scenario: An administrator saves a registry and reads it back + +- **GIVEN** an administrator on Beheer ▸ Sharing +- **WHEN** they enter a registry URL, a register and a token, and save +- **THEN** after a reload the URL and register fields MUST show what they entered +- **AND** the page MUST say a token is set + +#### Scenario: The token is never shown back + +- **GIVEN** a stored token +- **WHEN** the form loads +- **THEN** the token field MUST be empty +- **AND** neither the page nor the config response MUST contain the token + +#### Scenario: The saved registry is the one the store reads + +- **GIVEN** an administrator saved a registry URL whose host does not resolve +- **WHEN** they open the Store page +- **THEN** the page MUST show the unreachable note rather than the not-configured one diff --git a/openspec/changes/store-plane-dashboard-sharing/tasks.md b/openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/tasks.md similarity index 100% rename from openspec/changes/store-plane-dashboard-sharing/tasks.md rename to openspec/changes/archive/2026-10-07-store-plane-dashboard-sharing/tasks.md diff --git a/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/proposal.md b/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/proposal.md new file mode 100644 index 000000000..028529ca5 --- /dev/null +++ b/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/proposal.md @@ -0,0 +1,25 @@ +--- +kind: code +--- + +# Proposal: wizard-dataset-card-load + +## Summary + +The example data step in the LaunchPad setup wizard becomes one cards step whose cards load themselves. The separate "load the example data" step goes away. + +## Why + +The wizard asked for example data in two steps: a choice step that stored the pick, then a run-action step that loaded it. Two steps for one decision is one step too many, and the operator could not see which card was loading. `@conduction/nextcloud-vue` 2.65.0 gives a cards choice step a `loadAction`: every card except "None" gets its own Load button that posts `{ dataset }` to the action and spins while it runs. The fleet adopts that pattern from pipelinq (pipelinq#2177). + +## What Changes + +- The `demo-data` cards step declares `loadAction: load-demo-data`. The run-action step that loaded the pick is removed from the manifest. +- `POST /api/setup/action/load-demo-data` accepts `{ dataset }` in the body. It refuses a dataset no card offers, loads the named set, and records the pick only after the load succeeds. A call without a body still loads the stored pick, so older wizards and scripts keep working. +- `GET /api/setup/status` reports exactly the step ids of `manifest.setup.steps`. A step the server never reports stays open, and an open step reopens the wizard on every page. +- `@conduction/nextcloud-vue` is raised to `^2.65.0`, the first release with `loadAction`. + +## Impact + +- Affected code: `src/manifest.json`, the setup controller, its unit tests and the demo-data e2e spec. +- No data migration. The `demo_dataset` app-config key keeps its meaning. diff --git a/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/specs/first-time-setup/spec.md b/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/specs/first-time-setup/spec.md new file mode 100644 index 000000000..a516c3429 --- /dev/null +++ b/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/specs/first-time-setup/spec.md @@ -0,0 +1,51 @@ +# first-time-setup Specification (delta) + +## ADDED Requirements + +### Requirement: Each example data card loads itself + +The `demo-data` setup step MUST be a cards choice step with `loadAction: load-demo-data`. The setup wizard MUST NOT carry a separate run-action step that loads the picked dataset. + +#### Scenario: The operator loads a dataset from its card + +- GIVEN the setup wizard shows the example data cards +- WHEN the operator presses Load on a card +- THEN the wizard posts `{ "dataset": <card value> }` to `/api/setup/action/load-demo-data` +- AND the server loads that dataset +- AND the server records the dataset as the pick only after the load succeeds +- @e2e exclude the card and its spinner are CnSetupWizard UI, tested in nextcloud-vue; the posted body is covered by tests/Unit/Controller/SetupControllerTest.php + +#### Scenario: An unknown dataset is refused + +- GIVEN a dataset id that no card offers +- WHEN it is posted to `/api/setup/action/load-demo-data` +- THEN the server answers 400 with `success: false` +- AND nothing is loaded or stored +- @e2e tests/e2e/spec-coverage/demo-data-setup-step.spec.ts + +#### Scenario: A call without a body keeps working + +- GIVEN a dataset was stored through `/api/setup/config` +- WHEN `/api/setup/action/load-demo-data` is called without a body +- THEN the stored dataset is loaded +- @e2e tests/e2e/spec-coverage/demo-data-setup-step.spec.ts + +#### Scenario: A failed load leaves the step open + +- GIVEN the load of the posted dataset fails +- WHEN the server answers +- THEN the answer carries `success: false` +- AND no pick or decision is stored +- @e2e exclude needs a load that fails on a live instance; covered by tests/Unit/Controller/SetupControllerTest.php + +### Requirement: Setup status reports every manifest step + +`GET /api/setup/status` MUST report a `done` state for every step id in `manifest.setup.steps`. + +#### Scenario: The status ids match the manifest + +- GIVEN the LaunchPad manifest +- WHEN an administrator reads `/api/setup/status` +- THEN `steps` holds an entry for every manifest step id +- AND the retired load step is not reported +- @e2e tests/e2e/spec-coverage/demo-data-setup-step.spec.ts diff --git a/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/tasks.md b/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/tasks.md new file mode 100644 index 000000000..f1b648fe1 --- /dev/null +++ b/openspec/changes/archive/2026-10-07-wizard-dataset-card-load/tasks.md @@ -0,0 +1,12 @@ +# Tasks: wizard-dataset-card-load + +## 1. Manifest + +- [x] 1.1 Merge the dataset choice step and its run-action load step into one cards step with `loadAction: load-demo-data` +- [x] 1.2 Raise `@conduction/nextcloud-vue` to `^2.65.0` and validate the manifest against its schema + +## 2. Server + +- [x] 2.1 Accept `{ dataset }` on `load-demo-data`, refuse an unknown dataset, record the pick after a successful load +- [x] 2.2 Report every manifest step id from `/api/setup/status` +- [x] 2.3 Unit tests: the posted dataset, the refusal, a failed load stores nothing, status ids equal manifest ids diff --git a/openspec/changes/fix-group-dashboard-admin-auth-attribute/.openspec.yaml b/openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/.openspec.yaml similarity index 100% rename from openspec/changes/fix-group-dashboard-admin-auth-attribute/.openspec.yaml rename to openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/.openspec.yaml diff --git a/openspec/changes/fix-people-widget-unbounded-user-scan/proposal.md b/openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/proposal.md similarity index 100% rename from openspec/changes/fix-people-widget-unbounded-user-scan/proposal.md rename to openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/proposal.md diff --git a/openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/specs/people-widget/spec.md b/openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/specs/people-widget/spec.md new file mode 100644 index 000000000..1086fdcd7 --- /dev/null +++ b/openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/specs/people-widget/spec.md @@ -0,0 +1,48 @@ +--- +capability: people-widget +delta: true +status: draft +--- + +# People Widget — Bounded Candidate Resolution + +## ADDED Requirements + +### Requirement: Candidate resolution is bounded by the requested page (REQ-PPL-013) + +@e2e exclude a server-side query bound, not visible in a browser; covered by tests/Unit/Service/PeopleWidgetServiceTest.php::testDisplayNameSortUsesBoundedSearchNotFullScan and the pagination tests in the same file + +`PeopleWidgetService::listUsers()` MUST NOT materialize the full Nextcloud +user directory for a request that has no `group` filter and uses the default +`displayName` sort. The number of `IUser` objects instantiated from +`IUserManager` MUST scale with the requested `limit`/`offset` window (capped +at `PeopleWidgetService::MAX_LIMIT`), not with the total number of accounts on +the instance. Only the admin-selected `group` sort without a group filter +reads the whole directory, because ordering by group membership needs it. + +#### Scenario: Unfiltered People widget on a large instance fetches a bounded set + +- **GIVEN** a Nextcloud instance with 5,000 user accounts +- **AND** a People widget configured with no `group` filter and + `limit=10`, `offset=0` +- **WHEN** `GET /api/people?limit=10&offset=0` is called +- **THEN** `IUserManager::searchDisplayName()` MUST be invoked with a + bounded `$limit`/`$offset`, not an unbounded full-table search +- **AND** the response MUST still contain the correct `users`, `total`, + and `hasMore` fields + +#### Scenario: Pagination still returns correct total and hasMore + +- **GIVEN** the same 5,000-user instance and no `group` filter +- **WHEN** the caller requests successive pages (`offset=0,10,20,...`) +- **THEN** `total` MUST reflect the true count of matching (enabled, per + `excludeDisabled`) users +- **AND** `hasMore` MUST correctly indicate whether further pages exist + +#### Scenario: Group-filtered resolution is unaffected + +- **GIVEN** a People widget configured with a `group` filter +- **WHEN** candidates are resolved +- **THEN** behaviour MUST be unchanged from before this change — + `IGroupManager::get($gid)->getUsers()` per group value, deduplicated by + UID diff --git a/openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/tasks.md b/openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/tasks.md new file mode 100644 index 000000000..0fb8e784b --- /dev/null +++ b/openspec/changes/archive/2026-10-09-fix-people-widget-unbounded-user-scan/tasks.md @@ -0,0 +1,15 @@ +# Tasks — fix-people-widget-unbounded-user-scan + +Verified against HEAD on 9 Oct 2026: the fix landed in dae7adec ("feat(people): custom profile fields, expertise tags and a directory-wide people search...") and 400d7325, before this change was archived. + +## PeopleWidgetService + +- [x] Task 1: The no-group-filter path no longer calls `IUserManager::search('')`. `listUsers()` routes it to `listDirectoryPageByDisplayName()`, which pages `IUserManager::searchDisplayName('', limit, offset)` in bounded chunks (`collectDisplayNamePage()`), and sizes `total` from `countUsersTotal()` minus `countDisabledUsers()` (`lib/Service/PeopleWidgetService.php`). +- [x] Task 2: Disabled users are skipped inside the streamed window, so the window grows only by the disabled users it meets. `sortBy=group` without a group filter keeps the full read through `resolveCandidates()`, documented there, because ordering by group membership needs the whole directory. +- [x] Task 3: `resolveCandidates()`'s docblock now says it is reached without a group filter only for the `group` sort, and that the `displayName` path never calls it. +- [x] Task 4: `tests/Unit/Service/PeopleWidgetServiceTest.php::testDisplayNameSortUsesBoundedSearchNotFullScan` asserts `search()` is never called and `searchDisplayName()` gets a bounded, non-null limit and offset 0, with `total`/`hasMore` unchanged. +- [x] Task 5: `PeopleWidgetServiceTest` rerun on 9 Oct (lane log `build-round/batch2.log`: OK, 21 tests). The two `/api/people` requests in the Postman collection run in CI's Newman job. + +## Verification + +- [x] Task 6: Verified by the PHPUnit spy on `IUserManager::search()`/`searchDisplayName()` call arguments (Task 4), which the task names as an accepted way. diff --git a/openspec/changes/grid-bottom-append-placement/design.md b/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/design.md similarity index 100% rename from openspec/changes/grid-bottom-append-placement/design.md rename to openspec/changes/archive/2026-10-09-grid-bottom-append-placement/design.md diff --git a/openspec/changes/grid-bottom-append-placement/proposal.md b/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/proposal.md similarity index 100% rename from openspec/changes/grid-bottom-append-placement/proposal.md rename to openspec/changes/archive/2026-10-09-grid-bottom-append-placement/proposal.md diff --git a/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/specs/grid-layout/spec.md b/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/specs/grid-layout/spec.md new file mode 100644 index 000000000..ccc1a0655 --- /dev/null +++ b/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/specs/grid-layout/spec.md @@ -0,0 +1,78 @@ +--- +capability: grid-layout +delta: true +status: draft +--- + +# Grid Layout — Delta from change `grid-bottom-append-placement` + +## MODIFIED Requirements + +### Requirement: REQ-GRID-006 Widget Auto-Layout (bottom-append placement) + +When a new widget is added to a dashboard, the system MUST place it in a fresh row directly below all existing widgets, without overlapping any existing widget and without moving any existing widget. The algorithm MUST be: + +1. **Compute the bottom edge** — for every existing placement compute `gridY + gridHeight`; the new widget's `y` MUST be the maximum of these values (the lowest occupied bottom edge). A placement missing `gridY` contributes `0`; a placement missing `gridHeight` contributes height `1`. +2. **Anchor to the left** — the new widget's `x` MUST be `0`. +3. **Empty dashboard** — when there are no existing placements, the new widget MUST be placed at `(x: 0, y: 0)`. + +Existing widgets MUST NOT be moved — there is no push-down — and the helper's `pushed` array MUST always be empty. Default size when the caller omits `w`/`h` MUST be `w=4, h=4`. Position writes MUST trigger the persistence path of REQ-GRID-005. + +This requirement deliberately replaces the former "GridStack auto-position + top-left/push-down fallback" rule, which reordered the user's existing layout on every add once the visible rows filled up. The shipped `placeNewWidget(spec, placements, options?)` helper implements bottom-append; this requirement is the authoritative description of that behaviour. + +#### Scenario: Append below the only existing widget + +- **GIVEN** a dashboard with one widget at `(x:0, y:0, w:6, h:4)` +- **WHEN** a new 4×4 widget is added +- **THEN** it MUST be placed at `(x:0, y:4)` (a fresh row below the existing widget) +- **AND** the existing widget MUST NOT be moved +- **AND** the returned `pushed` array MUST be empty + +#### Scenario: Append below the lowest widget regardless of array order + +- **GIVEN** a dashboard with widgets at `(x:0, y:5, w:6, h:3)` (bottom edge `8`) and `(x:6, y:0, w:6, h:2)` (bottom edge `2`) +- **WHEN** a new 6×3 widget is added +- **THEN** it MUST be placed at `(x:0, y:8)` (below the lowest bottom edge, not below the last array entry) +- **AND** no existing widget MUST be moved + +#### Scenario: First widget on an empty dashboard + +- **GIVEN** a dashboard with no widgets +- **WHEN** a new 4×4 widget is added +- **THEN** it MUST be placed at `(x:0, y:0)` + +#### Scenario: Existing widgets are never pushed when the top region is full + +- **GIVEN** a dashboard whose `[0..12] × [0..4]` region is fully occupied +- **WHEN** a new 4×4 widget is added +- **THEN** it MUST be placed at `(x:0, y:4)`, below the occupied region +- **AND** every existing widget MUST retain its original `gridX`, `gridY`, `gridWidth`, and `gridHeight` +- **AND** the returned `pushed` array MUST be empty + +#### Scenario: Default size on omitted dimensions + +- **GIVEN** a caller invokes `placeNewWidget({type: 'text'})` with no `w` or `h` +- **WHEN** the placement runs +- **THEN** the placement MUST use `w=4, h=4` +- **AND** the `y` coordinate MUST still be the lowest occupied bottom edge (`0` on an empty dashboard) + +#### Scenario: Persistence after placement + +- **GIVEN** a new widget has been placed +- **WHEN** the placement completes +- **THEN** the new widget MUST be persisted via the standard placement-update API (REQ-WDG-008 batch update or per-placement PUT) +- **AND** because no existing widget is moved, only the new widget's position needs to be written + +#### Scenario: Add widget to partially filled grid (incremental render) +- GIVEN the grid has widgets occupying rows 0-2 in columns 0-8 +- AND columns 8-11 in row 0 are empty +- WHEN the user adds a new widget with gridWidth 4 and gridHeight 2 +- THEN `syncGridItems()` MUST detect the new placement and call `grid.makeWidget()` on the next tick +- AND GridStack MUST render the widget at the position computed by `placeNewWidget` (auto-position or fallback) +- NOTE: With `float: true`, auto-placement behavior may differ from non-float mode. + +#### Scenario: Remove widget syncs grid +- GIVEN widget placement id 10 is removed from the placements array +- WHEN the placements watcher triggers `syncGridItems()` +- THEN `syncGridItems()` MUST find the orphaned grid node and call `grid.removeWidget()` with `removeDOM: false` +- AND the grid MUST update its layout accordingly diff --git a/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/tasks.md b/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/tasks.md new file mode 100644 index 000000000..56f4e52da --- /dev/null +++ b/openspec/changes/archive/2026-10-09-grid-bottom-append-placement/tasks.md @@ -0,0 +1,26 @@ +# Tasks — grid-bottom-append-placement + +## Tasks + +- [x] Task 1: Amend REQ-GRID-006 requirement text in `openspec/specs/grid-layout/spec.md` from "auto-position + top-left/push-down fallback" to the bottom-append rule (`x = 0`, `y = max(gridY + gridHeight)`, existing widgets never moved, empty dashboard → `(0,0)`) — captured in this change's `specs/grid-layout/spec.md` delta +- [x] Task 2: Rewrite the REQ-GRID-006 scenarios — remove "Push-down fallback when grid is full at top" and "Pushed widgets remain within their column lane"; replace "Auto-position into empty space" with bottom-append scenarios; update "Default size on omitted dimensions" and "Persistence after placement" to the no-push expectations (delta restates the full scenario set) +- [x] Task 3: Reconcile the stale doc comments in `src/stores/dashboard.js` (`addWidgetToDashboard` and `addTileToDashboard`) that still describe "try autoPosition, fall back to top-left + push down" so they describe bottom-append; logic untouched +- [x] Task 4 (apply time): Update the "Current Implementation Status" traceability line for REQ-GRID-006 in `openspec/specs/grid-layout/spec.md` (line ~496) from "autoPosition primary path and the top-left + push-down fallback … Push-down side effects flow through `updatePlacements`" to the bottom-append description +- [x] Task 5: Confirm the existing Vitest suite (`src/composables/__tests__/useGridManager.spec.js`, `describe('REQ-GRID-014 placeNewWidget() — always appends at the bottom')`) already encodes the new expectations and passes — no test change required +- [x] Task 6: Confirm REQ-GRID-014 (single placement authority) and its grep guard are unaffected — `grid.addWidget` still appears only in `useGridManager.js` and its test file + +## Verification + +`openspec validate` exits clean. REQ-GRID-006, the `@spec`-linked comment in `useGridManager.js`, the `dashboard.js` call-site comments, and the Vitest expectations all describe bottom-append. No new push-down behaviour is reintroduced. + +## Tests (company-wide ADR-009) + +No new tests required — the bottom-append Vitest cases already exist and pass. This change reconciles documentation/spec to shipped code. + +## Documentation (company-wide ADR-010) + +Composable header comment already describes bottom-append; `dashboard.js` call-site comments reconciled per Task 3. + +## i18n (company-wide ADR-005) + +No user-facing strings introduced. diff --git a/openspec/changes/retire-groupfolder-storage-backend/.openspec.yaml b/openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/.openspec.yaml similarity index 100% rename from openspec/changes/retire-groupfolder-storage-backend/.openspec.yaml rename to openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/.openspec.yaml diff --git a/openspec/changes/retire-groupfolder-storage-backend/proposal.md b/openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/proposal.md similarity index 100% rename from openspec/changes/retire-groupfolder-storage-backend/proposal.md rename to openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/proposal.md diff --git a/openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/tasks.md b/openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/tasks.md new file mode 100644 index 000000000..4a2e83b7b --- /dev/null +++ b/openspec/changes/archive/2026-10-09-retire-groupfolder-storage-backend/tasks.md @@ -0,0 +1,22 @@ +# Tasks — retire-groupfolder-storage-backend + +## Tasks + +- [x] Task 1: Remove the storage tree — `lib/Service/DashboardContentStorage/` (interface, `DbContentStorage`, `GroupFolderContentStorage`, and the three exception classes) and `lib/Service/DashboardContentStorageFactory.php` +- [x] Task 2: Remove the orphaned service and controller surface — `DashboardService::{readDashboardContent,writeDashboardContent,deleteDashboardContent}` and the `?DashboardContentStorageFactory $contentStorageFactory` constructor parameter; `DashboardApiController::storageUnavailableResponse()`; `DashboardMapper::findAll()`, whose only caller was the retired migration command +- [x] Task 3: Remove the `content` and `locale` columns — drop the `$content`/`$locale` properties, `decodeContent()`, the `@method` docblocks and the `jsonSerialize()` keys from `lib/Db/Dashboard.php`, and drop both columns from `launchpad_dashboards` in `lib/Migration/Version002009Date20260811000000.php`. Leave `Version002001Date20260603000000` and `DashboardTableBuilder::addContentStorageColumns()` in place — a shipped migration is part of the version ledger and deleting it would desynchronise instances that have already run it +- [x] Task 4: Remove the two CLI commands — `lib/Command/MigrateStorageToGroupFolder.php` and `lib/Command/ToggleStorageSetting.php`, and their `<command>` entries in `appinfo/info.xml` +- [x] Task 5: Remove the PHPUnit classes that covered the removed tree — `DashboardContentStorageFactoryTest`, `DashboardContentStorageExceptionTest`, `DbContentStorageTest`, `GroupFolderContentStorageTest`, `MigrateStorageToGroupFolderTest` +- [x] Task 6: Mark `openspec/specs/groupfolder-storage-backend/spec.md` **withdrawn**, recording what was removed, what was deliberately kept, and why. This also retires the spec's 16 `@e2e exclude` markers, whose stated reasons cited `tests/Unit/Service/DashboardContentStorage/DbContentStorageTest.php` — a test file this change deletes, which would have left sixteen exemptions resting on a class that no longer exists +- [x] Task 7: Correct the phantom `- [x]` on Task 5 of the archived change at `openspec/changes/archive/2026-06-14-groupfolder-storage-backend/tasks.md`, because the project record asserted a wiring that did not exist + + +## Follow-up (not a task of this change) + +- **Follow-up, tracked on launchpad#87 — NOT in this change.** Decide whether setup-wizard step 2 (`launchpad.content_storage`, `AdminSettingKey::CONTENT_STORAGE`, `SetupWizardService::{getContentStorage,setContentStorage,hasGroupfolderApp}`, `AdminController::setWizardStorage` and its route) also retires. It writes a setting nothing now reads. Note that `tools/spec-annotations-allowlist.txt` carries entries for those three `SetupWizardService` methods and for `AdminController::setWizardStorage` Open as Q-launchpad-1 (2026-10-09). + +## Verification + +- `gate-57` (orphaned-write-capability) over `lib/Service/*.php` must report **0** findings, down from 1. The checker takes a **file list**, not a directory — `check_orphaned_write_capability.py .` prints nothing and exits 0 regardless of the tree's state +- PHPUnit must stay green, with the five removed classes gone rather than skipped +- No `@spec` anchor may dangle: `check_spec_anchors.py <log> <files...>` must report 0 findings over `lib/` diff --git a/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/proposal.md b/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/proposal.md new file mode 100644 index 000000000..e73e2dd2e --- /dev/null +++ b/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/proposal.md @@ -0,0 +1,33 @@ +# Proposal: retire setup-wizard step 2 (content storage) + +## Why + +The group-folder storage backend was retired (archived change +`2026-10-09-retire-groupfolder-storage-backend`). Setup-wizard step 2 still asked +the admin where dashboard content is stored and saved `launchpad.content_storage`, +a setting nothing reads. The question was Q-launchpad-1; Ruben answered it on +9 Oct 2026 (decision 131): retire the step. + +## What + +- The wizard has six steps: Welcome, Group order, Demo data, Admin roles, Footer, + Done. The storage step, its radio options and its strings are gone. +- `POST /api/admin/setup-wizard/storage` and `AdminController::setWizardStorage()` + are removed. +- `AdminSettingKey::CONTENT_STORAGE`, `AdminSetting::KEY_CONTENT_STORAGE` and + `SetupWizardService::{getContentStorage,setContentStorage,hasGroupfolderApp}` + are removed, with the now unused `IAppManager` dependency. +- `GET /api/admin/settings` no longer returns `launchpad.content_storage`, and + `PUT /api/admin/settings` no longer accepts `launchpadContentStorage` (an old + client that still sends it is ignored, like any unknown key). +- `occ launchpad:setup` no longer requires `storage_backend`. An old YAML file + that still carries it runs as before and prints that the field was ignored. +- A stored `content_storage` row stays in `oc_launchpad_admin_settings`, unread. + No migration deletes it. + +## Impact + +- Specs: `setup-wizard` (REQ-WIZ-003 removed, steps renumbered), + `admin-settings` (REQ-ASET-001 has twelve keys). +- No register or schema change, so no `info.xml` version bump is needed. +- No matrix row carries this change. diff --git a/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/specs/admin-settings/spec.md b/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/specs/admin-settings/spec.md new file mode 100644 index 000000000..6b79da23d --- /dev/null +++ b/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/specs/admin-settings/spec.md @@ -0,0 +1,61 @@ +# Delta: admin-settings + +## MODIFIED Requirements + +### Requirement: Retrieve Admin Settings (REQ-ASET-001) + +Administrators MUST be able to retrieve all current admin settings via the API. The endpoint returns a flat JSON object with the twelve settings listed under Defined Settings, each under its API response key. `group_order` is not among them; it has its own endpoints (REQ-ASET-012). + +#### Scenario: Get all settings with defaults +- GIVEN no admin settings have been explicitly configured (fresh installation) +- WHEN the admin sends GET /api/admin/settings +- THEN the system MUST return HTTP 200 with all twelve settings at their default values: + ```json + { + "defaultPermissionLevel": "add_only", + "allowUserDashboards": false, + "allowMultipleDashboards": true, + "defaultGridColumns": 12, + "linkCreateFileExtensions": ["txt", "md", "docx", "xlsx", "csv", "odt"], + "defaultSharePermissionLevel": "add_only", + "forcedShareGroups": [], + "legacyWidgetBridgeEnabled": false, + "maxDashboardsPerUser": 0, + "maxWidgetsPerDashboard": 0, + "quicksearchFallbackTarget": "none", + "startPageWithoutNavigation": false + } + ``` +- NOTE: `allowUserDashboards` defaults to `false` (REQ-ASET-003) — admins MUST opt in to personal dashboard creation. + +#### Scenario: Get settings after modification +- GIVEN the admin has set `allowUserDashboards` to `false` +- WHEN the admin sends GET /api/admin/settings +- THEN the response MUST carry `"allowUserDashboards": false` +- AND the other eleven keys MUST still be present with their current values + +#### Scenario: Non-admin user retrieves settings +- GIVEN a regular user "alice" +- WHEN she sends GET /api/admin/settings +- THEN the system MUST return HTTP 403 +- AND admin settings MUST NOT be exposed to non-admin users + +#### Scenario: Settings used by non-admin endpoints +- GIVEN the admin has set `allowUserDashboards` to `false` +- WHEN user "alice" sends POST /api/dashboard (to create a dashboard) +- THEN the system MUST internally check the `allowUserDashboards` setting via `PermissionService::canCreateDashboard()` +- AND the non-admin user MUST NOT need to call GET /api/admin/settings to experience the effect + +#### Scenario: Settings response format consistency +- GIVEN the admin has configured various settings at different times +- WHEN GET /api/admin/settings is called +- THEN the response MUST always return exactly the twelve keys listed under Defined Settings: `defaultPermissionLevel`, `allowUserDashboards`, `allowMultipleDashboards`, `defaultGridColumns`, `linkCreateFileExtensions`, `defaultSharePermissionLevel`, `forcedShareGroups`, `legacyWidgetBridgeEnabled`, `maxDashboardsPerUser`, `maxWidgetsPerDashboard`, `quicksearchFallbackTarget`, `startPageWithoutNavigation` +- AND no additional keys MUST be present in the response +- NOTE: This scenario said "exactly four keys" long after the response had grown to twelve. The list above is taken from `AdminSettingsService::getSettings()`; a key added there MUST be added here and to the Defined Settings table. +- AND the response MUST be a flat JSON object (no nesting) + +#### Scenario: The retired content storage key is not returned +- GIVEN an instance that still holds a `content_storage` row written by the retired setup-wizard storage step +- WHEN the admin sends GET /api/admin/settings +- THEN the response MUST NOT contain `launchpad.content_storage` +- AND the stored row MUST stay unread (decision 131) diff --git a/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/specs/setup-wizard/spec.md b/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/specs/setup-wizard/spec.md new file mode 100644 index 000000000..028b4cd81 --- /dev/null +++ b/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/specs/setup-wizard/spec.md @@ -0,0 +1,397 @@ +# Delta: setup-wizard + +## RENAMED Requirements + +- FROM: `### Requirement: REQ-WIZ-002 Multi-Step Wizard Flow with 7 Steps` +- TO: `### Requirement: REQ-WIZ-002 Multi-Step Wizard Flow with 6 Steps` + +- FROM: `### Requirement: REQ-WIZ-004 Step 3 — Group Priority Order (Embedded Component Reuse)` +- TO: `### Requirement: REQ-WIZ-004 Step 2 — Group Priority Order (Embedded Component Reuse)` + +- FROM: `### Requirement: REQ-WIZ-005 Step 4 — Demo Data Installation (Embedded Component Reuse)` +- TO: `### Requirement: REQ-WIZ-005 Step 3 — Demo Data Installation (Embedded Component Reuse)` + +- FROM: `### Requirement: REQ-WIZ-006 Step 5 — Admin Roles (Optional, Depends on admin-roles Capability)` +- TO: `### Requirement: REQ-WIZ-006 Step 4 — Admin Roles (Optional, Depends on admin-roles Capability)` + +- FROM: `### Requirement: REQ-WIZ-007 Step 6 — Footer Configuration (Optional, Depends on footer-customization Capability)` +- TO: `### Requirement: REQ-WIZ-007 Step 5 — Footer Configuration (Optional, Depends on footer-customization Capability)` + +## REMOVED Requirements + +### Requirement: REQ-WIZ-003 Step 2 — Storage Backend Choice with GroupFolder Dependency Tooltip + +**Reason**: decision 131 (9 Oct 2026) retired the storage step; the group-folder backend it chose between is gone. + +**Migration**: none. A stored `content_storage` row stays unread. + +## MODIFIED Requirements + +### Requirement: REQ-WIZ-001 Detect First-Run State via Admin Setting Flag + +The system MUST detect whether a LaunchPad instance is being initialized for the first time by consulting the `launchpad.setup_wizard_complete` boolean flag. When the flag is `false`, the admin section MUST display a banner prompting the admin to run the wizard. + +> NOTE: This is a net-new LaunchPad capability with no counterpart in the source app. The source ships CLI-only setup via `the source app:setup`; no frontend first-run detection, wizard route, or onboarding component exists in the source. LaunchPad adds this flag and banner on top of the same underlying service primitives. + +#### Scenario: Fresh instance shows banner +- GIVEN a freshly installed LaunchPad with `launchpad.setup_wizard_complete = false` +- WHEN an NC admin opens `/apps/launchpad/admin/dashboards` +- THEN the page MUST display a prominent banner: "Run setup wizard" with a button linking to the wizard flow +- AND the banner MUST remain visible until the admin clicks "Finish" in the wizard + +#### Scenario: Completed instance hides banner +- GIVEN a LaunchPad instance with `launchpad.setup_wizard_complete = true` +- WHEN an NC admin opens `/apps/launchpad/admin/dashboards` +- THEN the banner MUST NOT be displayed +- AND the admin section loads normally + +#### Scenario: Banner includes descriptive text +- GIVEN a fresh LaunchPad instance showing the setup banner +- WHEN the admin views the banner +- THEN the banner MUST include text explaining: "Get your intranet started: configure groups, install demo data, and set up admin roles." +- NOTE: Banner style and wording are implementation-specific; requirement mandates presence and visibility only + +#### Scenario: Banner has explicit "Run setup wizard" call-to-action +- GIVEN the banner is displayed +- WHEN the admin clicks the "Run setup wizard" button +- THEN the wizard modal MUST open and begin at Step 1 (Welcome) + +#### Scenario: Admin can dismiss and re-access banner +- GIVEN an admin who dismissed the banner or navigated away +- WHEN the admin returns to `/apps/launchpad/admin/dashboards` +- THEN if `launchpad.setup_wizard_complete = false`, the banner MUST reappear + +### Requirement: REQ-WIZ-002 Multi-Step Wizard Flow with 6 Steps + +The wizard MUST guide the admin through a linear, skippable sequence of 6 steps, each with Skip / Back / Next buttons. Only the "Finish" button on Step 6 marks the wizard complete. + +> NOTE: Steps 2–5 each embed the canonical admin UI component from the corresponding sibling capability (`group-priority-order`, `demo-data-showcases`, `admin-roles`, `footer-customization`). The wizard is a thin orchestrator — it owns step sequencing and the completion flag; each sibling capability owns its own settings persistence. No settings surfaces are duplicated. + +#### Scenario: Wizard starts at Step 1 +- GIVEN the banner's "Run setup wizard" button is clicked +- WHEN the wizard modal opens +- THEN Step 1 (Welcome / Overview) MUST be displayed +- AND the step counter MUST show "1 / 7" + +#### Scenario: Next button advances to next step +- GIVEN the wizard is on Step 1 +- WHEN the admin clicks "Next" +- THEN the wizard advances to Step 2 (Group order) +- AND the step counter MUST show "2 / 7" +- AND the Back button MUST become active + +#### Scenario: Back button returns to previous step +- GIVEN the wizard is on Step 3 +- WHEN the admin clicks "Back" +- THEN the wizard returns to Step 2 +- AND no data loss occurs (Step 3 values are preserved if re-visited) + +#### Scenario: Skip button jumps to next step without commitment +- GIVEN the wizard is on Step 4 (Admin roles, optional) +- WHEN the admin clicks "Skip" +- THEN the wizard advances to Step 5 +- AND the wizard completion status for Step 4 is marked "skipped" (not "done") +- NOTE: Skipping a step does not prevent the wizard from eventually marking complete + +#### Scenario: Step 1 has no form; only explanatory text +- GIVEN Step 1 (Welcome) is displayed +- WHEN the admin views the step +- THEN the step MUST show text explaining the wizard's purpose: "Configure your LaunchPad instance with group ordering, demo data, admin roles, and footer settings." +- AND there are no form fields to fill +- AND clicking "Next" advances without persisting any choice + +#### Scenario: Step 6 shows summary and Finish button +- GIVEN the wizard reaches Step 6 (Done) +- WHEN the admin views the step +- THEN the step MUST display a summary: "Your setup is complete. Click Finish to save changes and dismiss the setup banner." +- AND a "Finish" button (not "Next") MUST be present +- AND clicking "Finish" executes the completion action + +#### Scenario: Finish button completes wizard +- GIVEN the admin is on Step 6 with the "Finish" button visible +- WHEN the admin clicks "Finish" +- THEN the system MUST set `launchpad.setup_wizard_complete = true` +- AND the wizard modal MUST close +- AND the admin section MUST reload, banner gone + +#### Scenario: Wizard progress persists across Back navigation +- GIVEN the wizard is on Step 3 after a group order was chosen on Step 2 +- WHEN the admin clicks Back to Step 2, then clicks Next to Step 3 +- THEN the group order chosen on Step 2 MUST still be present (no data loss) + +### Requirement: REQ-WIZ-004 Step 2 — Group Priority Order (Embedded Component Reuse) + +Step 2 MUST embed the existing `group-priority-order` admin UI component, allowing the admin to configure the priority order of Nextcloud groups for dashboard routing. + +#### Scenario: Step 2 embeds existing group-priority-order admin component +- GIVEN Step 2 is displayed +- WHEN the admin views the step +- THEN the existing `group-priority-order` admin UI MUST be visible and functional within the wizard modal +- NOTE: The component is not duplicated; the wizard embeds the canonical admin component + +#### Scenario: Group order choice persists immediately +- GIVEN the admin reorders groups in Step 2 (e.g., "engineering" moved above "sales") +- WHEN the admin clicks Next +- THEN the system MUST immediately persist the new order to `launchpad.group_priority_order` +- AND navigating away does not lose the change + +#### Scenario: Step 2 allows drag-and-drop reordering (existing UI behavior) +- GIVEN the group-priority-order component is displayed +- WHEN the admin drags a group to a new position +- THEN the reorder MUST be reflected in the UI +- NOTE: Exact interaction (drag, arrow buttons, etc.) is determined by the embedded component's design + +### Requirement: REQ-WIZ-005 Step 3 — Demo Data Installation (Embedded Component Reuse) + +Step 3 MUST embed the existing `demo-data-showcases` admin UI component, allowing the admin to optionally select and install demo packages. + +#### Scenario: Step 3 embeds demo-data-showcases admin component +- GIVEN Step 3 is displayed +- WHEN the admin views the step +- THEN the existing `demo-data-showcases` admin UI MUST be visible within the wizard modal +- AND the component displays all available demo packages with checkboxes +- NOTE: The component is the canonical admin UI; wizard embeds it without duplication + +#### Scenario: Demo data installation is optional +- GIVEN Step 3 is displayed with zero demo packages selected +- WHEN the admin clicks "Skip" or "Next" +- THEN the wizard MUST advance without requiring any demo to be installed +- NOTE: Step 3 is not skippable via a Skip button; all steps are traversed. However, selecting zero demos and clicking Next is equivalent to skipping. + +#### Scenario: Checked demos are installed on Next +- GIVEN the admin selects checkboxes for "Engineering Demo" and "Sales Demo" on Step 3 +- WHEN the admin clicks "Next" +- THEN the system MUST trigger the installation of both demo packages +- AND the wizard advances to Step 4 (installation happens asynchronously or blocks until done, implementation choice) +- NOTE: The demo-data-showcases component handles the actual installation logic + +#### Scenario: Demo selection is persisted +- GIVEN the admin selected "Engineering Demo" on Step 3 and advanced to Step 4 +- WHEN the admin navigates Back to Step 3 +- THEN the "Engineering Demo" checkbox MUST remain checked +- AND no re-installation happens (idempotent) + +### Requirement: REQ-WIZ-006 Step 4 — Admin Roles (Optional, Depends on admin-roles Capability) + +Step 4 MUST allow the admin to optionally assign the "Dashboard Admin" role to one Nextcloud group. This step is skippable via a Skip button. + +#### Scenario: Step 4 shows group selector for admin role +- GIVEN the `admin-roles` capability is available +- AND Step 4 is displayed +- WHEN the admin views the step +- THEN a dropdown or multi-select MUST display all Nextcloud groups +- AND a description MUST explain: "Assign 'Dashboard Admin' role to a group to delegate LaunchPad administration to group members." + +#### Scenario: Admin can select one group for Dashboard Admin role +- GIVEN Step 4 is displayed with groups ["engineering", "sales", "marketing"] +- WHEN the admin selects "engineering" +- AND clicks "Next" +- THEN the system MUST call `RoleService::assignRole(groupId="engineering", role="admin", assignedBy=<current-admin>)` +- AND the role assignment MUST be created in `oc_launchpad_role_assignments` + +#### Scenario: Step 4 is skippable +- GIVEN Step 4 is displayed +- WHEN the admin clicks "Skip" +- THEN no role assignment is made +- AND the wizard advances to Step 5 +- AND the completion status for Step 4 MUST be marked "skipped" + +#### Scenario: No group selected is equivalent to skip +- GIVEN Step 4 with no group selected +- WHEN the admin clicks "Next" +- THEN no role assignment is made (equivalent to Skip) +- AND the wizard advances to Step 5 + +#### Scenario: Step 4 unavailable if admin-roles capability missing +- GIVEN the `admin-roles` capability is NOT implemented or not available +- WHEN the wizard would display Step 4 +- THEN Step 4 MUST be skipped automatically +- AND the step counter jumps from Step 3 to Step 5 +- NOTE: Capability dependency is gracefully handled; missing capability does not break wizard + +#### Scenario: Only one group can have admin role per wizard run +- GIVEN Step 4 is displayed +- WHEN the admin selects "engineering" and clicks "Next" +- THEN only the "engineering" group receives the admin role (not multiple groups) +- NOTE: If the admin wishes to assign admin role to multiple groups, they must run the wizard again or use the admin roles management UI directly + +### Requirement: REQ-WIZ-007 Step 5 — Footer Configuration (Optional, Depends on footer-customization Capability) + +Step 5 MUST allow the admin to optionally open and configure the footer using the "Structured mode" editor. This step is skippable via a Skip button. + +#### Scenario: Step 5 shows footer editor +- GIVEN the `footer-customization` capability is available +- AND Step 5 is displayed +- WHEN the admin views the step +- THEN the "Structured mode" footer editor MUST be visible and functional +- AND a description MUST explain: "Customize the footer content and appearance for your intranet." + +#### Scenario: Footer edits persist immediately +- GIVEN the admin edits footer content in Step 5 +- WHEN the admin clicks "Next" +- THEN the footer configuration MUST be saved to `launchpad.footer_config` or equivalent setting +- AND navigating away does not lose the changes + +#### Scenario: Step 5 is skippable +- GIVEN Step 5 is displayed +- WHEN the admin clicks "Skip" +- THEN no footer changes are made +- AND the wizard advances to Step 6 +- AND the completion status for Step 5 MUST be marked "skipped" + +#### Scenario: Step 5 unavailable if footer-customization capability missing +- GIVEN the `footer-customization` capability is NOT implemented or not available +- WHEN the wizard would display Step 5 +- THEN Step 5 MUST be skipped automatically +- AND the step counter jumps from Step 4 to Step 6 +- NOTE: Capability dependency is gracefully handled; missing capability does not break wizard + +### Requirement: REQ-WIZ-008 Get Wizard State via API Endpoint + +The system MUST expose a `GET /api/admin/setup-wizard/state` endpoint that returns the wizard's completion status, current recommended step for re-runs, and per-step status. + +> NOTE: Auto-launch behaviour (opening the wizard automatically when `setup_wizard_complete = false`) is intentionally SHOULD/MAY, not MUST. CLI-provisioned installs may set settings incrementally mid-`occ` run, meaning an admin who views the page before the CLI command finishes would see `complete = false` with settings partially applied. The banner-link fallback is always available and is the reliable path; auto-launch is a UX convenience for fresh browser sessions only. + +#### Scenario: Endpoint returns complete state on fresh instance +- GIVEN a fresh LaunchPad instance with `launchpad.setup_wizard_complete = false` +- WHEN an NC admin calls `GET /api/admin/setup-wizard/state` +- THEN the response MUST be HTTP 200 with JSON: + ```json + { + "complete": false, + "currentRecommendedStep": 1, + "stepStatuses": { + "1": "done", + "2": "pending", + "3": "pending", + "4": "pending", + "5": "pending", + "6": "pending" + } + } + ``` +- NOTE: Step 1 is always "done" (no choice required). Steps 2–6 start "pending". + +#### Scenario: Endpoint returns recommended step for re-runs +- GIVEN a LaunchPad instance where the group order is not yet set +- WHEN an NC admin calls `GET /api/admin/setup-wizard/state` +- THEN the response MUST include `currentRecommendedStep: 2` +- NOTE: The heuristic picks the first step with status != "done" + +#### Scenario: Endpoint returns complete=true when wizard finished +- GIVEN a LaunchPad instance with `launchpad.setup_wizard_complete = true` +- WHEN an NC admin calls `GET /api/admin/setup-wizard/state` +- THEN the response MUST include `complete: true` +- AND `currentRecommendedStep` MAY be 1 (optional) or reflect the last visited step (implementation choice) + +#### Scenario: Non-admin requests receive 403 +- GIVEN a non-admin user +- WHEN they call `GET /api/admin/setup-wizard/state` +- THEN the system MUST return HTTP 403 (Forbidden) + +#### Scenario: Endpoint includes skipped step status +- GIVEN the wizard has been run with Step 4 skipped +- WHEN an NC admin calls `GET /api/admin/setup-wizard/state` +- THEN the response MUST include `"4": "skipped"` in stepStatuses +- NOTE: Skipped status indicates the step was traversed but no action taken; does not block wizard completion + +#### Scenario: A stored storage choice from the retired step is ignored +- GIVEN an instance that still holds a `content_storage` row written by the retired storage step +- WHEN an NC admin calls `GET /api/admin/setup-wizard/state` +- THEN `stepStatuses` MUST hold exactly six entries +- AND the stored row MUST NOT change any step status or `currentRecommendedStep` + +### Requirement: REQ-WIZ-010 CLI Command for Non-Interactive Setup (IaC-Friendly) + +The system MUST expose a CLI command `php occ launchpad:setup` that accepts a `--config=/path/setup.yaml` argument to perform wizard setup non-interactively, ideal for Infrastructure-as-Code deployments. + +> NOTE: The YAML config schema (fields: `group_priority_order`, `demo_packages`, `admin_role_group`, `footer_config`) is formally defined in the `cli-commands` sibling spec. Optional steps (admin roles, footer) may be omitted from the config file entirely; omitting them is equivalent to skipping those steps in the wizard and does not cause an error. + +#### Scenario: CLI command accepts YAML config file +- GIVEN a YAML file `/tmp/setup.yaml` with content: + ```yaml + group_priority_order: ["engineering", "sales"] + demo_packages: ["engineering-demo", "sales-demo"] + admin_role_group: "engineering" + footer_config: + layout: "structured" + items: [...] + ``` +- WHEN an admin runs `php occ launchpad:setup --config=/tmp/setup.yaml` +- THEN the system MUST: + - Set `launchpad.group_priority_order = ["engineering", "sales"]` (Step 2) + - Install "engineering-demo" and "sales-demo" (Step 3) + - Assign "Dashboard Admin" role to "engineering" (Step 4) + - Set `launchpad.footer_config` with provided config (Step 5) + - Set `launchpad.setup_wizard_complete = true` (Step 6) + +#### Scenario: CLI command validates YAML schema +- GIVEN a YAML file whose top level is not a map, or whose `group_priority_order` is not a list +- WHEN `php occ launchpad:setup --config=/tmp/setup.yaml` is run +- THEN the system MUST output an error starting with "Invalid setup.yaml:" +- AND the command MUST exit with non-zero status + +#### Scenario: An old config that still sets storage_backend keeps working +- GIVEN a YAML file written for the seven-step wizard, with `storage_backend: "groupfolder"` +- WHEN `php occ launchpad:setup --config=/tmp/setup.yaml` is run +- THEN the command MUST print that `storage_backend` is no longer used and was ignored +- AND it MUST apply the other steps and exit with status 0 +- AND it MUST NOT write `launchpad.content_storage` + +#### Scenario: CLI command is verbose by default +- GIVEN the command runs successfully +- WHEN the output is examined +- THEN it MUST show progress: "Step 1: Welcome... done", "Step 2: Group order... done", etc. +- AND final message: "Setup wizard completed successfully." + +#### Scenario: CLI command skips optional steps if not in config +- GIVEN a YAML file with only `group_priority_order` +- WHEN the command runs +- THEN Steps 4 and 5 MUST be skipped (no error) +- AND Step 2 MUST execute with the provided value +- AND the wizard completes + +#### Scenario: CLI command is idempotent +- GIVEN a YAML config that was applied once +- WHEN the same command runs again with the same config +- THEN the system MUST return success (HTTP 200 equivalent) +- AND no duplicate role assignments or demo installations occur +- NOTE: The system MUST detect existing assignments/installations and skip them + +### Requirement: REQ-WIZ-011 Wizard is Re-Runnable + +The wizard MUST be re-runnable even after `launchpad.setup_wizard_complete = true`. Re-running MUST NOT undo earlier choices; it MUST re-walk the steps showing current state and allowing updates. + +#### Scenario: Admin can run wizard again after completion +- GIVEN a LaunchPad instance with `launchpad.setup_wizard_complete = true` +- WHEN an NC admin navigates to `/apps/launchpad/admin` and clicks "Run setup wizard again" (or uses a Re-run button in a separate admin UI section) +- THEN the wizard modal MUST open +- AND all step values MUST reflect current settings (group order, demo data, etc.) +- AND the admin can make changes + +#### Scenario: Re-running does not re-install demo packages +- GIVEN the instance has already installed "engineering-demo" +- AND the admin re-runs the wizard to Step 3 +- WHEN the admin unchecks "engineering-demo" and clicks Next +- THEN the system MUST NOT re-install the demo (it's already there) +- NOTE: Demo installation is one-time; re-running the wizard does not trigger redundant installations. If the admin wishes to un-install, they must use a separate admin UI for demo management. + +#### Scenario: Re-running preserves skipped steps +- GIVEN the wizard was run previously with Step 4 skipped +- AND the admin re-runs the wizard +- WHEN Step 4 is displayed +- THEN the step MUST show "Skip" button as before +- AND if the admin clicks Skip again, the behavior is consistent with the first run + +#### Scenario: Step 1 is always done on re-run +- GIVEN a re-run of the wizard +- WHEN Step 1 is displayed +- THEN no new action is required; clicking Next immediately advances + +#### Scenario: API endpoint reports re-runnable state +- GIVEN the instance has `launchpad.setup_wizard_complete = true` +- WHEN an NC admin calls `GET /api/admin/setup-wizard/state` +- THEN the response MUST indicate `complete: true` +- AND the admin UI MUST show a "Run setup wizard again" button (not a "Run setup wizard" banner) +- NOTE: The UI signals that re-running is available and safe + diff --git a/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/tasks.md b/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/tasks.md new file mode 100644 index 000000000..2f49c2e55 --- /dev/null +++ b/openspec/changes/archive/2026-10-09-retire-setup-wizard-storage-step/tasks.md @@ -0,0 +1,11 @@ +# Tasks: retire-setup-wizard-storage-step + +- [x] 1. Red tests first: `SetupWizardServiceTest` (six steps, no storage methods, a stored `content_storage` stays unread), `AdminControllerSetupWizardTest` (no `setWizardStorage`, no route), `AdminSettingKeyTest` (`tryFrom('content_storage')` is null), `AdminSettingsServiceTest` (twelve keys), new `SetupCommandTest` (no `storage_backend` needed, an old field is ignored, steps 1-6). Red run: `build-round/wizard-red.log`. +- [x] 2. Remove the step from `SetupWizardService` (`STEP_COUNT = 6`, renumbered `computeStepStatuses()`, the three methods and `IAppManager` gone). +- [x] 3. Remove `AdminController::setWizardStorage()`, its route in `appinfo/routes.php`, and the `launchpadContentStorage` parameter of `updateSettings()`. +- [x] 4. Remove `AdminSettingKey::CONTENT_STORAGE`, `AdminSetting::KEY_CONTENT_STORAGE`, and the key's read and write in `AdminSettingsService`. +- [x] 5. `SetupCommand`: `storage_backend` optional and ignored with a notice; steps renumbered 1-6. +- [x] 6. `SetupWizardModal.vue`: drop the storage step (six steps); `api.setSetupWizardStorage()` removed; Vitest spec updated. +- [x] 7. Welcome text and admin banner no longer mention storage, in every shipped locale; the strings only the retired step used are removed from every locale. +- [x] 8. Postman collection: the storage request removed. +- [x] 9. Specs: `setup-wizard` and `admin-settings` amended (deltas in this change are the record). The main specs were written by hand from the same transform, because `openspec validate` refuses a MODIFIED block that renames scenarios (Step N to Step N-1); the change was then archived with `--skip-specs`. Data Model and Defined Settings sections edited by hand. diff --git a/openspec/changes/archive/2026-10-30-platform-baseline/.openspec.yaml b/openspec/changes/archive/2026-10-30-platform-baseline/.openspec.yaml new file mode 100644 index 000000000..4bfa67093 --- /dev/null +++ b/openspec/changes/archive/2026-10-30-platform-baseline/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-30 diff --git a/openspec/changes/archive/2026-10-30-platform-baseline/proposal.md b/openspec/changes/archive/2026-10-30-platform-baseline/proposal.md new file mode 100644 index 000000000..f9b4bfde7 --- /dev/null +++ b/openspec/changes/archive/2026-10-30-platform-baseline/proposal.md @@ -0,0 +1,41 @@ +--- +kind: config +depends_on: [] +--- + +# Platform baseline: what LaunchPad takes from Nextcloud + +## Why + +Seven rows of the LaunchPad parity matrix (`openspec/parity/capabilities.json`) are built because LaunchPad runs inside Nextcloud, but no spec says so. They carried `"spec": "none"`, so nothing held LaunchPad to them. A change that adds a login form, a hosted call, a hard-coded colour or a private copy of group membership would break them without failing a spec. + +Rows covered, all `built`: + +- **p-sso**, "Sign in once with the organisation's identity provider." +- **p-own-servers**, "Run the dashboard on your own servers." +- **p-theme**, "The dashboard takes on the organisation's colours, including government theming." +- **p-languages**, "Use the dashboard in Dutch and many other languages." +- **d-idp-groups**, "Group membership follows the groups sent by the identity provider at sign-in." +- **d-pwa**, "Install the dashboard on a phone's home screen as an app." +- **d-dark-mode**, "The dashboard follows the device's light or dark mode." + +## What changes + +- A new capability `platform-baseline` with one requirement per row (REQ-PLB-001 to REQ-PLB-007). Each states what LaunchPad must do so the Nextcloud behaviour reaches every LaunchPad page. +- The seven rows cite the requirement in `built.spec` and `built.requirement`. +- `screens.md` names board LpMobiel for d-pwa and a one-line reason for the six rows without a screen. + +## Capabilities + +### New capabilities + +- `platform-baseline` + +## Impact + +- Spec only. No code changes: every requirement describes behaviour that is on `development` today (evidence in `tasks.md`). +- `specs/launchpad-mobile-remote-access` keeps PWA out of its own scope; REQ-PLB-006 is the home for it. + +## Out of scope + +- Per-dashboard themes and custom CSS (`platform-dashboard-theme-and-css`). diff --git a/openspec/changes/archive/2026-10-30-platform-baseline/screens.md b/openspec/changes/archive/2026-10-30-platform-baseline/screens.md new file mode 100644 index 000000000..7afc7b1d6 --- /dev/null +++ b/openspec/changes/archive/2026-10-30-platform-baseline/screens.md @@ -0,0 +1,9 @@ +# Screens + +- LpMobiel https://identity.conduction.nl/screens/board?id=launchpad/LpMobiel +- No screen: Aanmelden loopt via Nextcloud en de identiteitsprovider van de organisatie, niet via een scherm van Launchpad. (p-sso) +- No screen: Hosting op eigen servers, geen scherm. (p-own-servers) +- No screen: De huisstijl komt uit Nextcloud en thematiq; elk Launchpad-scherm volgt die, er is geen eigen scherm voor. (p-theme) +- No screen: De taal komt uit de persoonlijke instellingen van Nextcloud; elk scherm volgt die. (p-languages) +- No screen: Groepslidmaatschap komt bij het aanmelden van de identiteitsprovider, zonder scherm. (d-idp-groups) +- No screen: Licht of donker volgt het apparaat en de Nextcloud-instelling; elk scherm volgt die. (d-dark-mode) diff --git a/openspec/changes/archive/2026-10-30-platform-baseline/specs/platform-baseline/spec.md b/openspec/changes/archive/2026-10-30-platform-baseline/specs/platform-baseline/spec.md new file mode 100644 index 000000000..c7adc107f --- /dev/null +++ b/openspec/changes/archive/2026-10-30-platform-baseline/specs/platform-baseline/spec.md @@ -0,0 +1,118 @@ +# Delta for platform-baseline + +## Purpose + +What LaunchPad takes from the Nextcloud it runs on instead of building itself: sign-in, hosting, the organisation's theme, the language, group membership, installing as a phone app and light or dark mode. Each requirement names what LaunchPad must do so that the platform behaviour reaches every LaunchPad page. + +## ADDED Requirements + +### Requirement: LaunchPad has no login of its own (REQ-PLB-001) + +LaunchPad MUST run in the Nextcloud session and MUST NOT offer a login form, password store or token flow of its own. Every LaunchPad page and API route MUST require a signed-in Nextcloud user, except the routes that exist to serve visitors without an account: a public dashboard share (`PageController::publicShare`, `PublicShareController`), a kiosk link (`KioskController::render`) and the health check (`HealthController::index`). Single sign-on therefore comes from whatever Nextcloud is set up with (user_oidc, user_saml or LDAP), without a LaunchPad setting. + +#### Scenario: Signed in once, no second prompt + +- **GIVEN** Pieter signed in to Nextcloud through the organisation's identity provider +- **WHEN** he opens `/apps/launchpad/` +- **THEN** his start page loads without a LaunchPad sign-in step + +#### Scenario: Signed-out visitor goes to the Nextcloud login + +- **GIVEN** a browser without a Nextcloud session +- **WHEN** it opens `/apps/launchpad/` +- **THEN** Nextcloud answers with its own login page (and from there the identity provider) +- **AND** no LaunchPad page or dashboard data is sent before sign-in + +#### Scenario: Only the visitor routes are public + +- **GIVEN** the LaunchPad controllers +- **WHEN** their routes are listed with their auth attributes +- **THEN** only the public share, kiosk and health routes carry `#[PublicPage]` + +### Requirement: LaunchPad runs on the organisation's own servers (REQ-PLB-002) + +LaunchPad MUST install as an ordinary Nextcloud app on the organisation's own instance and MUST keep its dashboards, placements, rules and settings in that instance's database and app config. It MUST NOT depend on a hosted Conduction service. A server-side outbound request MUST go only to an address an administrator configured (weather provider, feeds, health pings) or an author placed on a dashboard (live tile, embed, news feed). + +#### Scenario: Installed from the app store on an own instance + +- **GIVEN** a Nextcloud instance run by the organisation +- **WHEN** an administrator enables LaunchPad +- **THEN** every dashboard is stored in that instance's database +- **AND** LaunchPad works with no account at, or connection to, any outside service + +#### Scenario: No outbound call without a configured address + +- **GIVEN** a fresh install with no weather provider, feed, live tile or embed configured +- **WHEN** users open their dashboards +- **THEN** the LaunchPad server makes no outbound HTTP request + +### Requirement: Every page takes on the organisation's theme (REQ-PLB-003) + +LaunchPad styles MUST take colours, fonts and corner radii from Nextcloud's theme variables (`--color-*`, `--border-radius*`, `--font-face`), so a Nextcloud theme or a thematiq NL Design System theme restyles every LaunchPad page without a LaunchPad setting. A hard-coded colour MAY only appear as a user-chosen value (a tile or widget colour) or as a fallback behind a theme variable. + +#### Scenario: A government theme restyles the start page + +- **GIVEN** thematiq applies the organisation's NL Design System theme +- **WHEN** Pieter opens his start page +- **THEN** the page chrome, buttons and links show the theme's colours and font + +#### Scenario: Per-dashboard looks are separate + +- **GIVEN** the organisation theme and a dashboard with its own look (change `platform-dashboard-theme-and-css`) +- **WHEN** the dashboard renders +- **THEN** the organisation theme still sets every value the dashboard look leaves open + +### Requirement: Every string is translatable and follows the user's language (REQ-PLB-004) + +Every user-facing string in LaunchPad MUST go through the Nextcloud l10n domain `launchpad` (`t('launchpad', ...)` in the frontend, `IL10N` for the app id in PHP). LaunchPad MUST ship Dutch and English translations, and pages MUST show the language chosen in the user's Nextcloud personal settings. + +#### Scenario: Dutch user + +- **GIVEN** Pieter set his Nextcloud language to Nederlands +- **WHEN** he opens LaunchPad +- **THEN** the menus, buttons and empty states are in Dutch + +#### Scenario: No string in another app's domain + +- **GIVEN** the frontend sources +- **WHEN** every `t(` and `n(` call is listed +- **THEN** each one names the domain `launchpad` + +### Requirement: Group dashboards follow the groups set at sign-in (REQ-PLB-005) + +LaunchPad MUST read a user's groups from Nextcloud (`IGroupManager`) at the moment it resolves a dashboard or a visibility rule, and MUST NOT keep its own copy of group membership. Groups an identity provider sends at sign-in (through user_oidc or user_saml group provisioning) therefore decide the group dashboards and group rules from that request on. Routing to a group dashboard follows the resolver in `admin-templates` (REQ-TMPL-013). + +#### Scenario: New group at sign-in + +- **GIVEN** the identity provider adds Pieter to group "KCC" and Nextcloud provisions it at sign-in +- **AND** a group dashboard is shared with "KCC" +- **WHEN** Pieter opens LaunchPad after that sign-in +- **THEN** the "KCC" dashboard is available to him without an administrator action in LaunchPad + +#### Scenario: Group removed + +- **GIVEN** the identity provider no longer sends "KCC" for Pieter +- **WHEN** he signs in again and opens LaunchPad +- **THEN** the "KCC" dashboard and widgets with a "KCC" visibility rule are no longer shown to him + +### Requirement: Pages install on a phone through Nextcloud's web app manifest (REQ-PLB-006) + +LaunchPad pages MUST be installable from the browser's "add to home screen" option through the web app manifest Nextcloud serves, and LaunchPad MUST NOT ship a manifest or service worker of its own. The installed app opens where Nextcloud's default app points; with LaunchPad set as default app, that is the LaunchPad start page. The page layout on a phone follows board LpMobiel. + +#### Scenario: Add to home screen + +- **GIVEN** LaunchPad is the Nextcloud default app +- **WHEN** Pieter chooses "Add to home screen" on a LaunchPad page in his phone's browser +- **THEN** a home screen icon appears +- **AND** opening it shows his LaunchPad start page in a window without the browser bar + +### Requirement: Pages follow light or dark mode (REQ-PLB-007) + +LaunchPad pages MUST use Nextcloud's theme variables for every surface, text and border colour, so they follow the user's Nextcloud theme setting, including "follow the system" light or dark, without a LaunchPad setting. + +#### Scenario: Device in dark mode + +- **GIVEN** Pieter's Nextcloud theme follows the system and his device is in dark mode +- **WHEN** he opens his start page +- **THEN** the page, widget frames and menus show the dark theme +- **AND** text keeps WCAG AA contrast against its background diff --git a/openspec/changes/archive/2026-10-30-platform-baseline/tasks.md b/openspec/changes/archive/2026-10-30-platform-baseline/tasks.md new file mode 100644 index 000000000..ea4bc372f --- /dev/null +++ b/openspec/changes/archive/2026-10-30-platform-baseline/tasks.md @@ -0,0 +1,11 @@ +# Tasks: platform-baseline + +Each task checks one requirement against `development` and records the evidence. + +- [x] 1. REQ-PLB-001: only `PageController::publicShare`, `PublicShareController` (2 routes), `KioskController::render` and `HealthController::index` carry `#[PublicPage]`; every other route needs a session. No login form in `src/`. +- [x] 2. REQ-PLB-002: installs from `appinfo/info.xml` as a Nextcloud app; outbound calls only in `lib/Service/WeatherService.php` (admin-set `weather_provider_url`), `NewsWidgetService.php`, `FeedRefreshService.php`, `LiveTileService.php`, `IframeService.php`, `HealthPingService.php` and `CalendarWidgetService.php`, each to a configured or placed address. +- [x] 3. REQ-PLB-003 and REQ-PLB-007: page chrome uses Nextcloud theme variables (`src/views/WorkspaceApp.vue` styles); per-dashboard looks stay in `platform-dashboard-theme-and-css`. +- [x] 4. REQ-PLB-004: 0 `t('mydash'` calls left in `src/` (change `fix-l10n-domain-mismatch-mydash-calls`); `l10n/` ships 37 languages including `nl.json` and `en.json`. +- [x] 5. REQ-PLB-005: groups are read through `IGroupManager` at resolve time (`lib/Service/AdminTemplateService.php`, `lib/Service/RuleEvaluatorService.php`); no group table of LaunchPad's own. +- [x] 6. REQ-PLB-006: no `manifest.webmanifest` or service worker in `src/` or `lib/`; Nextcloud core serves the manifest. +- [x] 7. Cite the requirements on rows p-sso, p-own-servers, p-theme, p-languages, d-idp-groups, d-pwa and d-dark-mode in `openspec/parity/capabilities.json`. diff --git a/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/proposal.md b/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/proposal.md new file mode 100644 index 000000000..d656da534 --- /dev/null +++ b/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/proposal.md @@ -0,0 +1,20 @@ +--- +kind: code +--- + +# The Zuiddrecht intranet and management showcases + +## Why + +The LpIntranet and LpManagement boards draw two group dashboards of the demo municipality Zuiddrecht: "Intranet Zuiddrecht", which every colleague may add widgets to, and "Managementinformatie", which everybody may only look at. A demo instance has neither: the only group dashboard is the default one, so the boards are measured against a dashboard that is not theirs or cannot be opened at all. + +Showcases are how LaunchPad ships an example dashboard, so the two dashboards become two bundled showcases an administrator installs with `occ launchpad:demo:showcases:install`. + +## What changes + +- Two organisation showcases, `zuiddrecht-intranet` and `zuiddrecht-management`, in Dutch, with preview images. +- REQ-DEMO-001 lets a showcase that shows a shared intranet be `add_only`: the board draws "u mag widgets toevoegen", and a read-only intranet would contradict it. Every other showcase stays `view_only`. + +## Out of scope + +The board's mandatory-read announcement ("Ik heb dit gelezen") is not carried: a showcase deliberately drops the `acknowledgement*` fields (PlacementPayloadHydrator), so LpLeesbevestigingen still needs a placement an administrator marks by hand. diff --git a/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/screens.md b/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/screens.md new file mode 100644 index 000000000..9dcb9b7c6 --- /dev/null +++ b/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement +- LpLeesbevestigingen https://identity.conduction.nl/screens/board?id=launchpad/LpLeesbevestigingen diff --git a/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/specs/demo-data-showcases/spec.md b/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/specs/demo-data-showcases/spec.md new file mode 100644 index 000000000..49a2c6b75 --- /dev/null +++ b/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/specs/demo-data-showcases/spec.md @@ -0,0 +1,95 @@ +## MODIFIED Requirements + +### Requirement: REQ-DEMO-001 Bundled showcase ZIP archives + +The system MUST ship a showcase ZIP archive per bundled id under +`data/demo-showcases/{id}/{id}.zip`, and `DemoShowcasesService::BUNDLED_IDS` is the +list of record. Each ZIP MUST carry a `manifest.json` plus one +`dashboards/{uuid}.json`, and MAY carry `metadata-fields.json` and an `assets/` +tree. Each `manifest.json` MUST contain: +- `schemaVersion`: schema version integer +- `scope`: `"dashboard"` +- `dashboardCount`: number of dashboards in the archive +- `showcaseId`: the bundled id, matching the directory and file name +- `showcaseName`: the name an admin sees in the gallery +- `showcaseDescription`: one sentence saying what the dashboard shows +- `showcaseLanguage`: locale code of the dashboard's own copy + +Each `dashboards/{uuid}.json` MUST declare `type: "group_shared"`, a null `userId` and a `showcase-{id}` slug, so an installed showcase is a group dashboard rather than someone's personal one. Its `permissionLevel` MUST be `view_only`, except for a showcase that shows a shared intranet colleagues add to, which MAY be `add_only`. + +**This paragraph previously described an `export.json` plus a `nl/` locale tree, and +neither has ever been in any bundled ZIP.** The archives have always been +`manifest.json` + `dashboards/`, which is what `ExportService` writes and +`ImportService` reads. The spec described a format the code does not produce, so a +reader implementing against it would have built something no bundled archive matches. + +Two kinds of showcase are bundled, and the difference is what a reader takes away. + +**Organisation showcases** answer "what does an intranet built on this look like". +They are Dutch, and they mirror the reference source dataset so existing copy and +screenshots stay reusable: +- `de-bron`, a healthcare and nursing organisation +- `de-linden`, a university +- `gemeente-duin`, a municipality +- `horizon-labs`, a tech startup +- `van-der-berg`, a law firm +- `zuiddrecht-intranet`, the intranet of the demo municipality Zuiddrecht, which every colleague may add widgets to (`add_only`) +- `zuiddrecht-management`, the management information of Zuiddrecht (`view_only`) + +**Role showcases** answer a different question: what one person's working day looks +like on one page. +- `case-handler`, a case handler's cases, tasks, agenda and unread mail + +A role showcase MAY be in English. `case-handler` places the fleet's own widgets (a +dossiq case list, the Tasks app, a calendar, unread mail) and those carry English +labels, so a Dutch shell around English content would read as a half-translation. +The five organisation showcases stay NL-only. Multi-locale variants of any showcase +remain a v2 goal. + +#### Scenario: Showcase ZIP archives exist and load without error +- **GIVEN** LaunchPad is installed and enabled +- **WHEN** the system initializes +- **THEN** every id in `BUNDLED_IDS` MUST be readable from `data/demo-showcases/{id}/{id}.zip` +- **AND** each ZIP MUST contain a `manifest.json` parseable as JSON, carrying the required fields +- **AND** each `manifest.json` `showcaseId` MUST equal the directory and file name it was read from + +@e2e exclude Archive shape is a packaging contract with no browser surface; pinned for every bundled id by DemoShowcasesServiceTest::testEveryBundledIdShipsAReadableArchive. + +#### Scenario: export.json version is checked against minimum app version +- **GIVEN** showcase `de-bron` with `"requiresMinVersion": "0.8.11"` in `export.json` +- **WHEN** the running app version is older than `0.8.11` +- **THEN** the system MUST reject the install with HTTP 422 and a clear version mismatch message +- **AND** the showcase MUST still appear in the list endpoint with `isInstalled: false` + +@e2e exclude Not implemented: the archives carry a manifest.json with no requiresMinVersion, and the install path has no version check or 422 response. + +#### Scenario: A showcase declares the language of its own copy +- **GIVEN** showcase `gemeente-duin` and showcase `case-handler` +- **WHEN** an admin lists the available showcases +- **THEN** `gemeente-duin` MUST declare `showcaseLanguage: "nl"` +- **AND** `case-handler` MUST declare `showcaseLanguage: "en"`, because a role showcase places widgets whose labels are English + +#### Scenario: A role showcase installs as a read-only group dashboard +- **GIVEN** showcase `case-handler` +- **WHEN** an admin installs it +- **THEN** the installed dashboard MUST carry `type: "group_shared"` and `permissionLevel: "view_only"` +- **AND** it MUST place exactly four widgets: the case list, tasks, today's agenda and unread mail + +#### Scenario: Invalid showcase ZIP is rejected +- **GIVEN** a showcase ZIP whose `manifest.json` is malformed or missing +- **WHEN** the system attempts to load it +- **THEN** the system MUST log an error +- **AND** the showcase MUST NOT appear in the available list +- **AND** installation attempts MUST return HTTP 500 + +@e2e exclude The bundled archives are all valid, so a browser run cannot arrange a broken one; a missing archive is pinned by DemoShowcasesServiceTest::testDescribeShowcaseReturnsNullWhenZipMissing, a malformed one by no test yet. + +#### Scenario: The Zuiddrecht intranet lets colleagues add widgets +- **GIVEN** an administrator installed the `zuiddrecht-intranet` showcase +- **WHEN** a colleague opens "Intranet Zuiddrecht" +- **THEN** the dashboard is a group dashboard the colleague may add widgets to, and not edit or delete + +#### Scenario: The management information is read only +- **GIVEN** an administrator installed the `zuiddrecht-management` showcase +- **WHEN** a colleague opens "Managementinformatie" +- **THEN** the dashboard shows the counts from the registers and offers no editing diff --git a/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/tasks.md b/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/tasks.md new file mode 100644 index 000000000..73f78d596 --- /dev/null +++ b/openspec/changes/archive/2026-10-30-zuiddrecht-showcases/tasks.md @@ -0,0 +1,6 @@ +## Tasks + +- [x] 1. Ship `data/demo-showcases/zuiddrecht-intranet/zuiddrecht-intranet.zip` and its preview +- [x] 2. Ship `data/demo-showcases/zuiddrecht-management/zuiddrecht-management.zip` and its preview +- [x] 3. Add both ids to `DemoShowcasesService::BUNDLED_IDS` +- [x] 4. Unit test: both archives, their permission levels and their widgets diff --git a/openspec/changes/adopt-connection-registry/.openspec.yaml b/openspec/changes/archive/2026-11-12-adopt-connection-registry/.openspec.yaml similarity index 100% rename from openspec/changes/adopt-connection-registry/.openspec.yaml rename to openspec/changes/archive/2026-11-12-adopt-connection-registry/.openspec.yaml diff --git a/openspec/changes/adopt-connection-registry/design.md b/openspec/changes/archive/2026-11-12-adopt-connection-registry/design.md similarity index 100% rename from openspec/changes/adopt-connection-registry/design.md rename to openspec/changes/archive/2026-11-12-adopt-connection-registry/design.md diff --git a/openspec/changes/adopt-connection-registry/proposal.md b/openspec/changes/archive/2026-11-12-adopt-connection-registry/proposal.md similarity index 100% rename from openspec/changes/adopt-connection-registry/proposal.md rename to openspec/changes/archive/2026-11-12-adopt-connection-registry/proposal.md diff --git a/openspec/changes/archive/2026-11-12-adopt-connection-registry/screens.md b/openspec/changes/archive/2026-11-12-adopt-connection-registry/screens.md new file mode 100644 index 000000000..4e4dae120 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-adopt-connection-registry/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement +- LpBeheerAlgemeen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAlgemeen diff --git a/openspec/changes/adopt-connection-registry/specs/app-connections/spec.md b/openspec/changes/archive/2026-11-12-adopt-connection-registry/specs/app-connections/spec.md similarity index 100% rename from openspec/changes/adopt-connection-registry/specs/app-connections/spec.md rename to openspec/changes/archive/2026-11-12-adopt-connection-registry/specs/app-connections/spec.md diff --git a/openspec/changes/archive/2026-11-12-adopt-connection-registry/tasks.md b/openspec/changes/archive/2026-11-12-adopt-connection-registry/tasks.md new file mode 100644 index 000000000..755b4beac --- /dev/null +++ b/openspec/changes/archive/2026-11-12-adopt-connection-registry/tasks.md @@ -0,0 +1,32 @@ +# adopt-connection-registry tasks + +## 1. Declare + +- [x] 1.1 Write `lib/Settings/connections.json` with `dashboard-registry`, `weather`, `news-feeds`, `ics-calendars`, `live-tiles` and `health-ping`. +- [x] 1.2 Vendor integriq's schema in `tests/Fixtures/Integriq/` and guard the file in `tests/Unit/Settings/ConnectionsDeclarationTest.php`. +- [x] 1.3 Give the dashboard registry form the `section-dashboard-registry` id. + +## 2. Page + +- [x] 2.1 Add `src/manifest.d/connection-registry.json` with the page and its settings-gear menu entry. +- [x] 2.2 Add `src/services/connectionRegistry.js` with the two formatters and the Add integration handler. +- [x] 2.3 Wire the formatters and the handler through `src/App.vue` and `src/customComponents.js`; register `PowerPlugOutline` in `src/icons.js`. +- [x] 2.4 Add the strings to `l10n/en` and `l10n/nl`. +- [x] 2.5 Cover it in `src/services/__tests__/connectionRegistry.spec.js`. + +## 3. Reports and refresh + +- [x] 3.1 Add `lib/Service/Connection/ConnectionReporter.php` and `ConnectionObservations.php`. +- [x] 3.2 Refresh from `StoreService::updateRegistryConfig()`, and wire the reporter into the hand-built `StoreService` in `Application.php`. +- [x] 3.3 Report from `StoreService`, `WeatherService`, `NewsWidgetService`, `CalendarWidgetService`, `LiveTileService` and `HealthPingService`. +- [x] 3.4 Add the integriq event stubs to `tests/Stubs`, `tests/bootstrap.php` and `psalm.xml`. +- [x] 3.5 Cover it in unit tests, including a burst of widget fetches against the throttle. + +## 4. End to end + +- [x] 4.1 Write `tests/e2e/integrations-page.spec.ts`. +- [x] 4.2 Install integriq in the CI `additional-apps`. + +## 5. After an instance runs both apps + +- [x] 5.1 Run the e2e spec against an instance with launchpad and integriq, then archive this change. Run 1 Nov 2026 on the shared instance (:8080, launchpad 9f872349, integriq installed): `tests/e2e/integrations-page.spec.ts` 4 passed, `--workers=1`. The archive is its own PR. diff --git a/openspec/changes/bbv-programma-templates/.openspec.yaml b/openspec/changes/archive/2026-11-12-bbv-programma-templates/.openspec.yaml similarity index 100% rename from openspec/changes/bbv-programma-templates/.openspec.yaml rename to openspec/changes/archive/2026-11-12-bbv-programma-templates/.openspec.yaml diff --git a/openspec/changes/bbv-programma-templates/context-brief.md b/openspec/changes/archive/2026-11-12-bbv-programma-templates/context-brief.md similarity index 100% rename from openspec/changes/bbv-programma-templates/context-brief.md rename to openspec/changes/archive/2026-11-12-bbv-programma-templates/context-brief.md diff --git a/openspec/changes/bbv-programma-templates/design.md b/openspec/changes/archive/2026-11-12-bbv-programma-templates/design.md similarity index 100% rename from openspec/changes/bbv-programma-templates/design.md rename to openspec/changes/archive/2026-11-12-bbv-programma-templates/design.md diff --git a/openspec/changes/bbv-programma-templates/hydra.json b/openspec/changes/archive/2026-11-12-bbv-programma-templates/hydra.json similarity index 100% rename from openspec/changes/bbv-programma-templates/hydra.json rename to openspec/changes/archive/2026-11-12-bbv-programma-templates/hydra.json diff --git a/openspec/changes/archive/2026-11-12-bbv-programma-templates/proposal.md b/openspec/changes/archive/2026-11-12-bbv-programma-templates/proposal.md new file mode 100644 index 000000000..d7269c6f4 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-bbv-programma-templates/proposal.md @@ -0,0 +1,83 @@ +> Superseded by decision 182 (a procedure is configuration): BBV programme dashboards are a template pack for the template store (rows r-templates, r-demo), not LaunchPad code. Decision 399. + +# BBV Programma Templates + +## Why + +Every gemeente in Nederland is wettelijk verplicht een programmabegroting op te stellen die de gemeentelijke taken indeelt in programma's (sociaal domein, ruimte, bestuur, openbare orde, ...), met per programma één of meer doelen en per doel meetbare indicatoren. Vandaag bouwt elke gemeente die structuur opnieuw op in Excel of lokaal BI-tool, afwijkend van buurgementen, waardoor benchmarking lastig is en provinciale toezichthouders aanleving lastig kunnen vergelijken. + +De BBV-taxonomie is echter sterk gestandaardiseerd: het Ministerie van BZK publiceert verplichte beleidsindicatoren, IV3-rubrieken (Informatie voor Derden) zijn vastgesteld, en meeste gemeenten hanteren vergelijkbare programma-indeling op hoofdlijnen. Deze spec introduceert een eerste-klasse Programma / Doel / Indicator / Maatregel datamodel in OpenRegister, seed-templates voor gangbare programma-indelingen (G4, M50, kleine gemeenten, provincies, waterschappen), één-klik installatie zodat een gemeente een template kiest en alle programma's, doelen en standaard-indicatoren in één keer aanmaakt, en koppelingen naar financeq (begrotings- en realisatie-cijfers per programma) en planix (planning van maatregelen onder een doel). + +## What Changes + +- New OpenRegister schemas: `Programma`, `Doel`, `Indicator`, `IndicatorMeting`, `Maatregel`, `IV3Mapping`, `ProgrammaTemplate`, `TemplateProgramma`, `TemplateDoel`, `TemplateIndicator`. +- New backend services: `ProgrammaService` (CRUD + template installatie), `TemplateService` (template upgrade logic), `IV3ExportService` (export voor provinciale toezichthouder). +- New frontend views: programma-tree (visualisatie van Programma → Doel → Indicator → Maatregel hiërarchie), template-picker (één-klik installatie), template-upgrade-wizard. +- Integration: openconnector (sync IndicatorMetingen van waarstaatjegemeente / CBS), financeq (begroting ↔ realisatie per programma), planix (Maatregel → project link). +- Seed data: templates voor G4, M50, kleine gemeenten, provincies, waterschappen (centraal beheerd in openregister). + +## Capabilities + +### New Capabilities + +- `programma-tree` — Programma / Doel / Indicator / Maatregel CRUD en hiërarchie-beheer. +- `programma-templates` — One-click template installatie + versie-upgrade. +- `iv3-mapping-export` — IV3-export voor provinciale toezichthouders. +- `indicator-syncing` — Geautomatiseerde sync van IndicatorMetingen van externe bronnen via openconnector. +- `maatregel-planning` — Maatregel ↔ planix project linking. +- `programma-begroting` — Begroting ↔ realisatie synchronisatie met financeq. + +### Modified Capabilities + +(none — all entirely new) + +## Impact + +**Affected integrations:** + +- `openregister` — opslag van Programma, Doel, Indicator, Maatregel, IV3Mapping, templates, seed data. +- `financeq` — query van begroting / realisatie per IV3-taakveld; verdeling over programma's via IV3Mapping. +- `planix` — project creatie + status synchronisatie gelinkt aan Maatregel. +- `openconnector` — sync van IndicatorMetingen van waarstaatjegemeente.nl, CBS API, eigen meetbronnen. + +**Dependencies:** + +- OpenRegister (already required by launchpad) +- IGroupManager, IUserManager (from Nextcloud core) +- No new composer/npm dependencies + +**Migration:** + +- Zero-impact: seed templates are loaded via OpenRegister's ImportHandler pipeline on first install or via repair step. Existing tenants without templates see an empty programma-tree until they choose a template in the UI. + +## Standards + +- **BBV** — Besluit Begroting en Verantwoording provincies en gemeenten. +- **IV3** — Informatie voor Derden taakveldenlijst (BZK). +- **Verplichte beleidsindicatoren** — Jaarlijks bijgewerkt door BZK. +- **Waarstaatjegemeente.nl** — data-bron-specificatie. +- **CBS Open Data API** — indicator-meting bronnen. + +## Non-Goals + +- Real-time collaboration on programma edits (out of scope; single-user editing assumed). +- Mobile app support (webapp-only; can defer mobile to later change). +- Workflow approvals for programma publication (status lifecycle exists, but approval workflow deferred to future change). +- Multi-tenant template versioning (seeds are global; per-tenant template forks deferred). + +## Risks + +- **Risk:** Template installatie is niet atomair en mislukt half-weg. → **Mitigation:** Transactie wrapper om template cloning; rollback on any error. +- **Risk:** IV3-mapping is incorrect en export gaat fout naar provinciale toezichthouder. → **Mitigation:** Valideerstap in export dat som per programma 100% bedraagt. +- **Risk:** External data sources (waarstaatjegemeente, CBS) zijn offline en sync mislukt. → **Mitigation:** Graceful degradation; sync retries later; eigenaar van doel krijgt notification. + +## Deliverables + +- OpenRegister schemas (JSON, in launchpad `_register.json`) +- Backend services (PHP in `lib/Service/`) +- Frontend views (Vue in `src/views/`) +- API endpoints (PHP in `lib/Controller/`) +- Integration code (openconnector hooks, financeq API calls, planix linking) +- Seed templates (JSON objects loaded on install) +- Unit + integration tests +- Changelog + admin docs (ADR-010) diff --git a/openspec/changes/archive/2026-11-12-bbv-programma-templates/screens.md b/openspec/changes/archive/2026-11-12-bbv-programma-templates/screens.md new file mode 100644 index 000000000..1d3172ede --- /dev/null +++ b/openspec/changes/archive/2026-11-12-bbv-programma-templates/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerSjablonen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerSjablonen diff --git a/openspec/changes/bbv-programma-templates/specs.md b/openspec/changes/archive/2026-11-12-bbv-programma-templates/specs.md similarity index 100% rename from openspec/changes/bbv-programma-templates/specs.md rename to openspec/changes/archive/2026-11-12-bbv-programma-templates/specs.md diff --git a/openspec/changes/bbv-programma-templates/tasks.md b/openspec/changes/archive/2026-11-12-bbv-programma-templates/tasks.md similarity index 100% rename from openspec/changes/bbv-programma-templates/tasks.md rename to openspec/changes/archive/2026-11-12-bbv-programma-templates/tasks.md diff --git a/openspec/changes/2026-04-30-dashboard-sharing-followups/.openspec.yaml b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/.openspec.yaml similarity index 100% rename from openspec/changes/2026-04-30-dashboard-sharing-followups/.openspec.yaml rename to openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/.openspec.yaml diff --git a/openspec/changes/2026-04-30-dashboard-sharing-followups/context-brief.md b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/context-brief.md similarity index 100% rename from openspec/changes/2026-04-30-dashboard-sharing-followups/context-brief.md rename to openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/context-brief.md diff --git a/openspec/changes/2026-04-30-dashboard-sharing-followups/design.md b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/design.md similarity index 100% rename from openspec/changes/2026-04-30-dashboard-sharing-followups/design.md rename to openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/design.md diff --git a/openspec/changes/2026-04-30-dashboard-sharing-followups/hydra.json b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/hydra.json similarity index 100% rename from openspec/changes/2026-04-30-dashboard-sharing-followups/hydra.json rename to openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/hydra.json diff --git a/openspec/changes/2026-04-30-dashboard-sharing-followups/proposal.md b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/proposal.md similarity index 100% rename from openspec/changes/2026-04-30-dashboard-sharing-followups/proposal.md rename to openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/proposal.md diff --git a/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/screens.md b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/screens.md new file mode 100644 index 000000000..98da5ce63 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpDelen https://identity.conduction.nl/screens/board?id=launchpad/LpDelen diff --git a/openspec/changes/2026-04-30-dashboard-sharing-followups/specs/dashboard-sharing/spec.md b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/specs/dashboard-sharing/spec.md similarity index 100% rename from openspec/changes/2026-04-30-dashboard-sharing-followups/specs/dashboard-sharing/spec.md rename to openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/specs/dashboard-sharing/spec.md diff --git a/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/tasks.md b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/tasks.md new file mode 100644 index 000000000..df33b1760 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-dashboard-sharing-followups-stale-copy/tasks.md @@ -0,0 +1,103 @@ +# Tasks — dashboard-sharing-followups + +## 0. Deduplication check + +- [ ] 0.1 Search `openspec/specs/` for any existing notification, bulk-share, or cascade specs that overlap with REQ-SHARE-008..013 + - Expected result: no overlap; the baseline `dashboard-sharing` spec (REQ-SHARE-001..007) is the only prior art, and this change extends it with additive requirements only +- [ ] 0.2 Search `lib/Service/` for any existing `NotificationService`, `BulkShareService`, or `CascadeService` that could be extended rather than creating new methods + - Expected result: `DashboardShareService` is the correct extension point; no parallel notification dispatch exists in the app +- [ ] 0.3 Confirm that OpenRegister's `NotificationService` is not applicable here — LaunchPad uses custom tables, not OR objects, so OR's notification path does not apply +- [ ] 0.4 Document findings in the PR description (even if "no overlap found") + +## 1. Notifier service + +- [ ] 1.1 Create `lib/Notification/Notifier.php` implementing `OCP\Notification\INotifier` + - `getID()` returns `'launchpad'` + - `getName()` returns `'LaunchPad'` (translatable) + - `prepare(INotification, $languageCode)` handles two subjects: `dashboard_shared`, `dashboard_ownership_transferred` + - For unknown subjects throw `\OCP\Notification\UnknownNotificationException` + - Use `IURLGenerator::linkToRouteAbsolute('launchpad.page.index')` plus a `?dashboard={uuid}` query for the deep link +- [ ] 1.2 Use `IFactory::get('launchpad')` for translations of the rendered strings: + - `dashboard_shared`: rich subject "{sharerDisplayName} shared **{dashboardName}** with you" + parsed message "{permissionLevel} access" + - `dashboard_ownership_transferred`: rich subject "**{dashboardName}** is now yours" + parsed message "Ownership transferred after the previous owner was removed" +- [ ] 1.3 Register the notifier in `lib/AppInfo/Application.php::register()` via `$context->registerNotifierService(Notifier::class)` +- [ ] 1.4 Add English and Dutch translation entries to `l10n/en.json` and `l10n/nl.json` for the two notification subjects and permission level labels ("Full access", "Add-only access", "View-only access") +- [ ] 1.5 Add unit test covering both subjects, English + Dutch locale + +## 2. Notification publishing + +- [ ] 2.1 Inject `OCP\Notification\IManager` into `DashboardShareService` +- [ ] 2.2 Extract a private `_persistShare(int $dashboardId, string $shareType, string $shareWith, string $level): array{share: DashboardShare, isNew: bool, isUpgrade: bool}` from the current `addShare` +- [ ] 2.3 Add a private `_notifyShared(DashboardShare $share, string $sharerUserId, string $dashboardName)` that: + - For `share_type='user'`: creates one `INotification` for that single recipient + - For `share_type='group'`: resolves group members at publish time via `IGroupManager` and creates one notification per current member, excluding the sharer + - Sets `setSubject('dashboard_shared', [sharerUserId, dashboardName, permissionLevel])` and `setObject('dashboard', (string) $dashboardId)` +- [ ] 2.4 The current `addShare()` becomes: `_persistShare(...)` THEN `_notifyShared(...)` only when `isNew === true || isUpgrade === true` (not on downgrades, not on no-op writes) +- [ ] 2.5 The `removeShare()` path does NOT publish anything (revocations are silent) +- [ ] 2.6 Add unit test: mock `IManager`, assert exactly one notification per fan-out target, assert no notification on level downgrade + +## 3. Bulk replace endpoint + +- [ ] 3.1 Add `DashboardShareService::replaceShares(int $dashboardId, array $shares, string $userId): array` that: + - Asserts caller is owner (throws 403 if not) + - Validates each entry's `shareType`, `shareWith`, `permissionLevel` + - Loads existing shares once + - In a single transaction: deletes shares not in payload, upserts the rest + - Returns the new full list + - Calls `_notifyShared` only for entries where `isNew === true || isUpgrade === true` +- [ ] 3.2 Add `DashboardShareApiController::replace(int $id, ?array $shares)` action with `#[NoAdminRequired]` attribute and per-object owner check (ADR-005 Rule 3) +- [ ] 3.3 Register route `PUT /api/dashboard/{id}/shares` in `appinfo/routes.php` +- [ ] 3.4 Add `replaceShares(dashboardId, shares)` to `src/services/api.js` +- [ ] 3.5 Update `DashboardConfigModal.vue`: replace the per-row immediate `addShare`/`removeShare` calls with a `pendingShares` data array. Save button posts via `replaceShares` and reloads. Cancel reverts to the server snapshot. Wrap the `await` call in `try/catch` with user-facing error feedback (ADR-004) +- [ ] 3.6 Add backend integration test covering: add+remove+upgrade in one PUT; idempotent re-PUT with same payload publishes 0 notifications; non-owner receives 403 + +## 4. Revoke-all-for-recipient + +- [ ] 4.1 Add `DashboardShareService::revokeAllForRecipient(string $shareType, string $shareWith, string $callerId): int` that: + - Joins `oc_launchpad_dashboard_shares` to `oc_launchpad_dashboards` on `dashboardId = id` filtered to `dashboards.user_id = callerId` + - Deletes all matching rows in one statement, returns the affected row count +- [ ] 4.2 Add `DashboardShareApiController::revokeForRecipient(string $shareType, string $shareWith)` with `#[NoAdminRequired]` attribute +- [ ] 4.3 Register route `DELETE /api/sharees/{shareType}/{shareWith}` in `appinfo/routes.php` +- [ ] 4.4 Add `revokeAllForRecipient(shareType, shareWith)` to `src/services/api.js` +- [ ] 4.5 No UI surface in this change — exposed for admin tools / scripted cleanup. Frontend wiring deferred. + +## 5. UserDeletedEvent listener with admin retention + +- [ ] 5.1 Create `lib/Listener/UserDeletedListener.php` implementing `IEventListener<UserDeletedEvent>` +- [ ] 5.2 Register in `lib/AppInfo/Application.php::register()` via `$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class)` +- [ ] 5.3 In `handle()`: + - Resolve `$userId = $event->getUser()->getUID()` + - **Step A**: delete every share where `share_type='user' AND share_with=$userId` (recipient cleanup) + - **Step B**: for every dashboard owned by `$userId`: + - Compute admin pool: load every share with `permission_level='full'`; for `user`-type entries the userId is added directly; for `group`-type entries, expand via `IGroupManager::get($groupId)->searchUsers('', 1000)` capped at 1000 per group + - Filter the admin pool to existing users (skip already-deleted accounts via `IUserManager::get`) + - **If pool is empty**: delete the dashboard, its placements, and its shares (existing `deleteDashboard` logic via `DashboardService`) + - **If pool is non-empty**: pick the new owner using the selection rule (task 5.4), transfer ownership, delete only the new owner's matching share row, publish a `dashboard_ownership_transferred` notification to them + - All Step B work runs in a single DB transaction per dashboard +- [ ] 5.4 New-owner selection rule (codified): + 1. Among `user`-type shares with `permission_level='full'`, take the one with the smallest `created_at` + 2. If none, expand the alphabetically-first `group`-type share's member list and pick the alphabetically-first uid still active + 3. If both fail (pool became empty between resolve and pick), fall through to delete +- [ ] 5.5 Add `DashboardShareService::transferOwnership(int $dashboardId, string $newUserId): void`: + - Updates the dashboard's `user_id` and stamps `updated_at` + - Deletes the share row that previously gave `newUserId` access + - All other shares are kept as-is +- [ ] 5.6 Increment Prometheus counter `launchpad_dashboards_orphaned_at_owner_deletion_total` on the delete path and `launchpad_dashboard_ownership_transferred_total` on the transfer path +- [ ] 5.7 Add unit tests: pool with one user share; pool with only group share; pool empty; group share where every member is also deleted; recipient (non-owner) deletion removes only their shares + +## 6. Optional one-shot data hygiene migration + +- [ ] 6.1 Create `lib/Migration/Version001006Date20260430130000.php` (`SimpleMigrationStep`) +- [ ] 6.2 In `postSchemaChange`, gated by admin setting `launchpad.cleanup_orphan_shares = true`: + - Find share rows where `share_type='user'` and the `share_with` uid no longer resolves via `IUserManager::get()` + - Find share rows where `share_type='group'` and the `share_with` group no longer resolves via `IGroupManager::get()` + - Delete those rows; emit a count to the migration output +- [ ] 6.3 Default the setting to `false` so no surprise deletions on federated environments + +## 7. Documentation + telemetry + +- [ ] 7.1 Update `docs/sharing.md` (create if missing) with the share lifecycle diagram, including the new ownership-transfer path +- [ ] 7.2 Confirm `launchpad_dashboards_orphaned_at_owner_deletion_total` and `launchpad_dashboard_ownership_transferred_total` Prometheus counters are exported via `GET /api/metrics` (ADR-006) +- [ ] 7.3 Update `openspec/specs/dashboard-sharing/spec.md` with the new REQ-SHARE-008..013 once the change is archived (post-merge step done by `/opsx-archive`) + +> Archived unbuilt-as-written, 12 Nov 2026: superseded. A stale copy of `changes/archive/2026-04-30-dashboard-sharing-followups`, restored from a branch on 16 Jun. REQ-SHARE-008..013 are in `openspec/specs/dashboard-sharing` and the code exists (rows s-notify and s-leaver are built). diff --git a/openspec/changes/dashboard-switcher/.openspec.yaml b/openspec/changes/archive/2026-11-12-dashboard-switcher/.openspec.yaml similarity index 100% rename from openspec/changes/dashboard-switcher/.openspec.yaml rename to openspec/changes/archive/2026-11-12-dashboard-switcher/.openspec.yaml diff --git a/openspec/changes/dashboard-switcher/context-brief.md b/openspec/changes/archive/2026-11-12-dashboard-switcher/context-brief.md similarity index 100% rename from openspec/changes/dashboard-switcher/context-brief.md rename to openspec/changes/archive/2026-11-12-dashboard-switcher/context-brief.md diff --git a/openspec/changes/dashboard-switcher/design.md b/openspec/changes/archive/2026-11-12-dashboard-switcher/design.md similarity index 100% rename from openspec/changes/dashboard-switcher/design.md rename to openspec/changes/archive/2026-11-12-dashboard-switcher/design.md diff --git a/openspec/changes/dashboard-switcher/hydra.json b/openspec/changes/archive/2026-11-12-dashboard-switcher/hydra.json similarity index 100% rename from openspec/changes/dashboard-switcher/hydra.json rename to openspec/changes/archive/2026-11-12-dashboard-switcher/hydra.json diff --git a/openspec/changes/dashboard-switcher/proposal.md b/openspec/changes/archive/2026-11-12-dashboard-switcher/proposal.md similarity index 100% rename from openspec/changes/dashboard-switcher/proposal.md rename to openspec/changes/archive/2026-11-12-dashboard-switcher/proposal.md diff --git a/openspec/changes/archive/2026-11-12-dashboard-switcher/screens.md b/openspec/changes/archive/2026-11-12-dashboard-switcher/screens.md new file mode 100644 index 000000000..dd0a09b0b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-dashboard-switcher/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag diff --git a/openspec/changes/dashboard-switcher/specs/dashboard-ui/spec.md b/openspec/changes/archive/2026-11-12-dashboard-switcher/specs/dashboard-ui/spec.md similarity index 100% rename from openspec/changes/dashboard-switcher/specs/dashboard-ui/spec.md rename to openspec/changes/archive/2026-11-12-dashboard-switcher/specs/dashboard-ui/spec.md diff --git a/openspec/changes/archive/2026-11-12-dashboard-switcher/tasks.md b/openspec/changes/archive/2026-11-12-dashboard-switcher/tasks.md new file mode 100644 index 000000000..8ba001b66 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-dashboard-switcher/tasks.md @@ -0,0 +1,85 @@ +# Tasks — dashboard-switcher + +## Component Implementation + +- [ ] Task 1: Create `src/components/DashboardSwitcher.vue` — Vue 2 Options API, scoped styles, Pinia store for sidebar state +- [ ] Task 2: Props: `isOpen` (Boolean, required), `groupName` (String, optional, default `'Dashboards'`), `groupDashboards` (Array, required), `userDashboards` (Array, required), `activeDashboardId` (String, optional), `allowUserDashboards` (Boolean, optional) +- [ ] Task 3: Emits: `update:open(boolean)`, `switch(id, source)`, `create-dashboard()`, `delete-dashboard(id)` +- [ ] Task 4: REQ-SWITCH-001 — Implement three-section rendering: primary group (source !== 'default'), default group (source === 'default'), personal (userDashboards). Each section has a label (computed via `groupName || t('Dashboards')`, `t('Default')`, `t('My Dashboards')`). Omit empty sections entirely (no empty container, no label). +- [ ] Task 5: REQ-SWITCH-001 — Render horizontal dividers between adjacent non-empty sections (exactly 2 dividers when all 3 sections present; 1 divider when 2 sections; 0 when 1 section) +- [ ] Task 6: REQ-SWITCH-002 — Dashboard row click handler: emit `update:open(false)` first, then emit `switch(id, source)`. Source is derived from section context ('group'/'default'/'user'), not from the dashboard object's internal type field. +- [ ] Task 7: REQ-SWITCH-003 — Apply CSS class `.active` to the dashboard item where `id === activeDashboardId`. Only one item may be active. Update reactively when prop changes. +- [ ] Task 8: REQ-SWITCH-003 — Style active items with `background-color: var(--color-primary-element-light)` and icon tint `color: var(--color-primary)` +- [ ] Task 9: REQ-SWITCH-004 — Personal-dashboard rows (excluding the Add-Dashboard card): render a delete button (small close icon via `NcIcon`, component: `Close`). Button hidden by default (`display: none`), visible on row hover (`display: inline-flex`) +- [ ] Task 10: REQ-SWITCH-004 — Delete button click handler: use `@click.stop` to prevent row's switch event, emit `delete-dashboard(id)`, do NOT emit `update:open(false)` +- [ ] Task 11: REQ-SWITCH-006 — Container CSS: `position: fixed`, `top: 50px`, `left: 0`, `width: 280px`, `z-index: 1500`. Initial `transform: translateX(-100%)` when `isOpen: false`. +- [ ] Task 12: REQ-SWITCH-006 — When `isOpen: true`, add CSS class `.open` which sets `transform: translateX(0)`. Transition: `transform 0.25s ease` +- [ ] Task 13: REQ-SWITCH-006 — Sidebar height: calculate to account for header offset (top: 50px) and footer. Use `calc(100vh - 50px)` with `overflow-y: auto` on the list container +- [ ] Task 14: REQ-SWITCH-007 — Import `IconRenderer` from the `dashboard-icons` capability. Each dashboard row: render the icon via `<IconRenderer :icon="dashboard.icon" />`. No branching on `isCustomIconUrl`. +- [ ] Task 15: REQ-SWITCH-008 — Render a dedicated "Add Dashboard" button card only when `allowUserDashboards === true`. Card is inside the scroll container (not the footer), positioned below the personal-dashboards list +- [ ] Task 16: REQ-SWITCH-008 — Add-Dashboard card: `NcButton` with `type="outline"`, full sidebar width, render a `+` icon (use `Plus` component from @conduction/nextcloud-vue), label from `t('launchpad', 'Add dashboard')` +- [ ] Task 17: REQ-SWITCH-008 — Add-Dashboard button click: emit `update:open(false)` first, then emit `create-dashboard()` +- [ ] Task 18: REQ-SWITCH-009 — Render a sticky footer at the bottom: `position: sticky`, `bottom: 0`, separated from the list above by a `<hr />` divider +- [ ] Task 19: REQ-SWITCH-009 — Footer: "Powered by" line with Sendent logo (link to sendent.nl) and Conduction logo (link to conduction.nl). Both links: `target="_blank"` and `rel="noopener noreferrer"`. Use static URLs or load from config if available. +- [ ] Task 20: REQ-SWITCH-009 — Footer: Documentation link rendered as an icon + label `t('launchpad', 'Documentation')`. Link target: preserved from the gear menu's Documentation URL (retrieve from app config or settings endpoint) +- [ ] Task 21: REQ-SWITCH-009 — Footer styling: `position: sticky`, light background via Nextcloud CSS var `var(--color-background-secondary)`, padding and border-top divider + +## Parent Integration + +- [ ] Task 22: Integrate `DashboardSwitcher.vue` into `src/App.vue` — import the component and register in `components: {}` +- [ ] Task 23: Wire `v-model:open` binding to the sidebar state: `:isOpen="sidebarOpen"` and `@update:open="sidebarOpen = $event"` +- [ ] Task 24: Pass dashboard data props from the component's data/store: `:groupName`, `:groupDashboards`, `:userDashboards`, `:activeDashboardId`, `:allowUserDashboards` +- [ ] Task 25: Handle `@switch` event in App.vue: call the store action to switch dashboards and navigate if needed; update `activeDashboardId` in the store +- [ ] Task 26: Handle `@create-dashboard` event in App.vue: emit or call the parent's create flow (may open a dialog, navigate to a form, etc.) +- [ ] Task 27: Handle `@delete-dashboard` event in App.vue: call the delete endpoint or store action; show a success/error toast; conditionally close the sidebar after deletion + +## Styling & CSS + +- [ ] Task 28: Create `src/styles/dashboard-switcher.css` with all component styles. Use ONLY Nextcloud CSS variables (`--color-*`). NO hardcoded colors, NO `--nldesign-*` refs. +- [ ] Task 29: Styles: section headings, dividers, dashboard rows (padding, hover state), delete button (hidden/visible), active class styling, animation, footer styling +- [ ] Task 30: Test CSS in light and dark modes (if nldesign is integrated) — colors must respect `prefers-color-scheme` + +## Translations + +- [ ] Task 31: Add English (en.json) translations: `'Dashboards'`, `'Default'`, `'My Dashboards'`, `'Add dashboard'`, `'Documentation'`, `'Powered by'` +- [ ] Task 32: Add Dutch (nl.json) translations: `'Dashboards'` → `'Dashboards'`, `'Default'` → `'Standaard'`, `'My Dashboards'` → `'Mijn dashboards'`, `'Add dashboard'` → `'Dashboard toevoegen'`, `'Documentation'` → `'Documentatie'`, `'Powered by'` → `'Mogelijk gemaakt door'` +- [ ] Task 33: Extract translation keys from the component into `xgettext` scanning (ensure `.vue` files are scanned by the build's i18n extraction) + +## Testing + +- [ ] Task 34: Playwright test — all three sections render when present; dividers appear only between non-empty sections +- [ ] Task 35: Playwright test — click a dashboard row emits `update:open(false)` then `switch(id, source)` with correct source ('group'/'default'/'user') +- [ ] Task 36: Playwright test — active item highlighted correctly; highlight updates when `activeDashboardId` prop changes +- [ ] Task 37: Playwright test — personal dashboard item hover shows delete button; delete button click emits `delete-dashboard(id)` without emitting `switch` or `update:open(false)` +- [ ] Task 38: Playwright test — sidebar animates from off-screen (`translateX(-100%)`) to on-screen (`translateX(0)`) over 250 ms when `isOpen` toggles; computed style matches after animation completes +- [ ] Task 39: Playwright test — all three dashboard icons render correctly (built-in MDI, custom URL, null) via `IconRenderer` without branching in the template +- [ ] Task 40: Playwright test — Add-Dashboard button is visible only when `allowUserDashboards: true`; clicking it emits `update:open(false)` then `create-dashboard()` +- [ ] Task 41: Playwright test — footer always visible; brand logos and Documentation link render with correct target/rel attributes; footer remains visible while scrolling 30+ dashboards +- [ ] Task 42: Playwright test — mobile viewport (320px width): sidebar's 280px width + gap is within bounds; all interactive elements remain clickable at touch size (44px+ preferred) + +## Quality & Integration + +- [ ] Task 43: ESLint + Stylelint — all `.vue` and `.css` files pass linting with zero warnings +- [ ] Task 44: Type checking — if using TypeScript, `tsc --noEmit` passes; Vue component types are inferred correctly or explicitly annotated +- [ ] Task 45: Security gate `hydra-gate-modal-isolation` — if the component opens any modal/dialog, it MUST be in its own `.vue` file under `src/modals/` or `src/dialogs/`, not inline +- [ ] Task 46: Nextcloud CSS compliance — all colors use `var(--color-*)` variables; no hardcoded `#hex` or `rgb()` colors; theme switching works (if nldesign is available, test with different token sets) +- [ ] Task 47: Accessibility (WCAG AA) — all interactive elements are keyboard-navigable (Tab/Shift+Tab); delete button has sufficient contrast and labels; section headings are semantic (`<h3>` or appropriate level); focus indicator is visible +- [ ] Task 48: Documentation — add a brief entry to the changelog mentioning the new dashboard switcher sidebar, its location, and key features (switching, create/delete personal dashboards, footer branding) + +## Verification + +`openspec validate` exits clean. Sidebar renders all three sections correctly; dashboard switching closes the sidebar and calls the switch handler; personal dashboards can be deleted; Add-Dashboard affordance is visible and works; footer stays visible while scrolling; all interactive elements are responsive and accessible. + +## Tests (company-wide ADR-009) + +Playwright end-to-end tests per Tasks 34–42. Unit tests for computed properties (section filtering, active-item detection, label localization) if complexity warrants; otherwise integration tests via Playwright. + +## Documentation (company-wide ADR-010) + +Changelog entry per Task 48. Inline component docstring (JSDoc) documenting props, emits, and main behavioral features. No separate design document needed beyond `design.md`. + +## i18n (company-wide ADR-005) + +English and Dutch per Tasks 31–33. Extraction via existing i18n build pipeline. + +> Archived unbuilt-as-written, 12 Nov 2026: superseded. Built and archived as `2026-05-02-dashboard-switcher-sidebar` and `2026-05-03-dashboard-switcher-extensions`; `openspec/specs/dashboard-switcher` holds REQ-SWITCH-001..009 and parity row dash-many is built. This copy came back from a stale branch on 16 Jun. diff --git a/openspec/changes/fix-l10n-domain-mismatch-mydash-calls/.openspec.yaml b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/.openspec.yaml similarity index 100% rename from openspec/changes/fix-l10n-domain-mismatch-mydash-calls/.openspec.yaml rename to openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/.openspec.yaml diff --git a/openspec/changes/fix-group-dashboard-admin-auth-attribute/proposal.md b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/proposal.md similarity index 100% rename from openspec/changes/fix-group-dashboard-admin-auth-attribute/proposal.md rename to openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/proposal.md diff --git a/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/screens.md b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/screens.md new file mode 100644 index 000000000..16006aa21 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: backend: auth attribute on a controller method diff --git a/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/specs/dashboards/spec.md b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/specs/dashboards/spec.md new file mode 100644 index 000000000..096ea5f8e --- /dev/null +++ b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/specs/dashboards/spec.md @@ -0,0 +1,52 @@ +--- +capability: dashboards +delta: true +status: draft +--- + +# Dashboards — Group-Shared CRUD Authorization Attribute + +## ADDED Requirements + +### Requirement: REQ-DASH-014 Group-shared dashboard CRUD is admin-only and declared as such + +Group-shared dashboard CRUD endpoints (`createGroup`, `updateGroup`, `deleteGroup`, `setGroupDefault`) MUST be reachable only by Nextcloud global administrators, AND this restriction MUST be declared via the +`#[AuthorizedAdminSetting]` PHP attribute rather than via an in-body +`isAdmin()` check layered on a `#[NoAdminRequired]` attribute. The +attribute-level declaration is enforced by Nextcloud's own middleware +before the controller method body runs, and is the mechanically +verifiable form per ADR-005's auth-attribute contract. + +#### Scenario: Non-admin cannot create a group-shared dashboard + +- **GIVEN** an authenticated non-admin user "bob" +- **WHEN** bob sends `POST /api/dashboards/group/{groupId}` +- **THEN** the framework MUST reject the request with HTTP 403 before the + controller body's business logic runs +- **AND** no dashboard MUST be created + +#### Scenario: Non-admin cannot update, delete, or set-default a group-shared dashboard + +- **GIVEN** an authenticated non-admin user "bob" +- **WHEN** bob sends `PUT /api/dashboards/group/{groupId}/{uuid}`, + `DELETE /api/dashboards/group/{groupId}/{uuid}`, or + `POST /api/dashboards/group/{groupId}/default` +- **THEN** each request MUST be rejected with HTTP 403 by the framework + attribute check +- **AND** no mutation MUST occur + +#### Scenario: Admin can perform all four group-shared operations + +- **GIVEN** an authenticated Nextcloud global admin +- **WHEN** the admin calls `createGroup`, `updateGroup`, `deleteGroup`, or + `setGroupDefault` +- **THEN** each call MUST succeed exactly as it did before this change +- **AND** the response payloads MUST be unchanged + +#### Scenario: Controller method carries the correct attribute + +- **GIVEN** `lib/Controller/DashboardApiController.php` +- **WHEN** `createGroup()`, `updateGroup()`, `deleteGroup()`, and + `setGroupDefault()` are inspected +- **THEN** each MUST carry `#[AuthorizedAdminSetting(Application::APP_ID)]` +- **AND** none MUST carry `#[NoAdminRequired]` diff --git a/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/tasks.md b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/tasks.md new file mode 100644 index 000000000..ca3fa8e67 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-fix-group-dashboard-admin-auth-attribute/tasks.md @@ -0,0 +1,72 @@ +# Tasks — fix-group-dashboard-admin-auth-attribute + +## DashboardApiController + +- [x] Task 1: In `lib/Controller/DashboardApiController.php`, import + `OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting` and + `OCA\LaunchPad\Settings\LaunchPadAdmin` (or + `OCA\LaunchPad\AppInfo\Application` for `Application::APP_ID`) alongside + the existing `NoAdminRequired` import. +- [x] Task 2: Replace `#[NoAdminRequired]` with + `#[AuthorizedAdminSetting(Application::APP_ID)]` on `createGroup()` + (currently line 916). +- [x] Task 3: Replace `#[NoAdminRequired]` with + `#[AuthorizedAdminSetting(Application::APP_ID)]` on `updateGroup()` + (currently line 1026). +- [x] Task 4: Replace `#[NoAdminRequired]` with + `#[AuthorizedAdminSetting(Application::APP_ID)]` on `deleteGroup()` + (currently line 1090). +- [x] Task 5: Replace `#[NoAdminRequired]` with + `#[AuthorizedAdminSetting(Application::APP_ID)]` on `setGroupDefault()` + (currently line 1143). +- [x] Task 6: Remove the redundant in-body `$this->dashboardService->isAdmin(...)` + + `ResponseHelper::forbidden(message: DashboardService::ERR_FORBIDDEN_NOT_ADMIN)` + block from each of the four methods above, now that the attribute-level + middleware enforces the same check. If PHPUnit coverage asserts the + in-body 403 message text, update those tests to assert on the + framework's `AuthorizedAdminSetting` 403 response instead. +- [x] Task 7: Update the docblocks above `createGroup()` (lines ~902-905), + `updateGroup()`, `deleteGroup()`, and `setGroupDefault()` that currently + describe the `#[NoAdminRequired]` + in-body-check pattern as the + intentional authorization point — remove the "gate-route-auth / + gate-semantic-auth" workaround language now that the attribute itself + carries the authorization. +- [x] Task 8: Confirm `$this->dashboardService->isAdmin()` still has at + least one other caller (e.g. `PageController` per the existing grep) so + it is not left dead after removing these four call sites; if it becomes + unused, remove the method per `hydra-gate-stub-scan`. + +## AdminSettingsController + +- [x] Task 9: In `lib/Controller/AdminSettingsController.php`, import + `OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting` and the app's + `Application` class (or `LaunchPadAdmin` settings class, matching the + pattern in `AdminController.php`). +- [x] Task 10: Add `#[AuthorizedAdminSetting(Application::APP_ID)]` above + `listGroups()` (currently line 89). +- [x] Task 11: Add `#[AuthorizedAdminSetting(Application::APP_ID)]` above + `updateGroupOrder()` (currently line 162). +- [x] Task 12: Leave the existing private `assertAdmin()` helper and its + call sites in place as defense-in-depth (matching the pattern already + used in `AdminOrgNavigationController.php` and `AdminController.php`, + where `AuthorizedAdminSetting`-annotated methods also call the inline + guard) — do not remove it. + +## Verification + +- [x] Task 13: Run `hydra-gate-semantic-auth` (or the equivalent + `run-hydra-gates.sh` invocation) against the diff and confirm all six + methods now pass with no findings. +- [x] Task 14: Re-run the existing PHPUnit suite for + `DashboardApiControllerTest` / `AdminSettingsControllerTest` (or their + equivalents) and update any assertions that depended on the removed + in-body 403 message. +- [x] Task 15: Manually verify via curl/Newman that a non-admin + authenticated user still receives HTTP 403 on + `POST /api/dashboards/group/{groupId}`, + `PUT /api/dashboards/group/{groupId}/{uuid}`, + `DELETE /api/dashboards/group/{groupId}/{uuid}`, + `POST /api/dashboards/group/{groupId}/default`, + `GET /api/admin/settings/groups`, and the group-order update endpoint. + +> Ticked at archive, 12 Nov 2026: `development` at 1d792009 already carries the change. `lib/Controller/DashboardApiController.php:919`, `:1010`, `:1062` and `:1101` put `#[AuthorizedAdminSetting(LaunchPadAdmin::class)]` on createGroup, updateGroup, deleteGroup and setGroupDefault. The tests were not re-run for this archive. diff --git a/openspec/changes/fix-people-widget-unbounded-user-scan/.openspec.yaml b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/.openspec.yaml similarity index 100% rename from openspec/changes/fix-people-widget-unbounded-user-scan/.openspec.yaml rename to openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/.openspec.yaml diff --git a/openspec/changes/harden-activity-debounce-cache-reliability/proposal.md b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/proposal.md similarity index 100% rename from openspec/changes/harden-activity-debounce-cache-reliability/proposal.md rename to openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/proposal.md diff --git a/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/screens.md b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/screens.md new file mode 100644 index 000000000..55aee9c1e --- /dev/null +++ b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: backend: activity debounce cache diff --git a/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/specs/activity-feed-integration/spec.md b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/specs/activity-feed-integration/spec.md new file mode 100644 index 000000000..97abdeea4 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/specs/activity-feed-integration/spec.md @@ -0,0 +1,55 @@ +--- +capability: activity-feed-integration +delta: true +status: draft +--- + +# Activity Feed Integration — Debounce Backend Reliability + +## ADDED Requirements + +### Requirement: REQ-ACT-007 Reaction debounce holds regardless of deployment topology + +The per-`(actorUserId, dashboardUuid)` reaction debounce (900-second window) MUST hold across HTTP requests and PHP-FPM worker processes on every supported deployment topology, including installations where the +APCu PHP extension is not installed or not enabled for the running SAPI. +The debounce MUST NOT silently degrade to "always allow" when APCu is +unavailable. + +#### Scenario: Debounce holds without APCu across two separate requests + +- **GIVEN** a Nextcloud instance with APCu not installed +- AND user "bob" reacted to dashboard `abc` in request 1, one second ago +- **WHEN** bob reacts to dashboard `abc` again in a separate HTTP request + (request 2) within the same 900-second window +- **THEN** `allowReaction('bob', 'abc')` MUST return `false` in request 2 +- **AND** no second reaction activity row MUST be written + +#### Scenario: Debounce still uses APCu when available + +- **GIVEN** a Nextcloud instance with APCu installed and enabled +- **WHEN** `allowReaction()` is called +- **THEN** the claim MUST be served via `apcu_add()` exactly as before this + change (no regression to the fast path) + +### Requirement: REQ-ACT-008 Global fan-out debounce holds regardless of deployment topology + +The per-`(dashboardUuid, eventType)` fan-out debounce (900-second window) MUST hold across HTTP requests and PHP-FPM worker processes, including on installations without APCu. + +#### Scenario: Fan-out debounce holds without APCu across two separate requests + +- **GIVEN** a Nextcloud instance with APCu not installed +- AND a `dashboard_updated` fan-out for dashboard `abc` was performed in + request 1 +- **WHEN** a second `dashboard_updated` event for dashboard `abc` arrives in + a separate HTTP request within the same 900-second window +- **THEN** `allowGlobalFanout('abc', 'dashboard_updated')` MUST return + `false` in request 2 +- **AND** the fan-out MUST be skipped silently, exactly as the existing + single-request scenario requires + +#### Scenario: Deterministic unit tests remain unaffected + +- **GIVEN** a test injects a fake clock into `DebounceHelper` +- **WHEN** the test advances the fake clock past the 900-second window +- **THEN** the helper MUST continue to use the in-memory fallback for + deterministic behaviour, unaffected by this change diff --git a/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/tasks.md b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/tasks.md new file mode 100644 index 000000000..eacd6818d --- /dev/null +++ b/openspec/changes/archive/2026-11-12-harden-activity-debounce-cache-reliability/tasks.md @@ -0,0 +1,53 @@ +# Tasks — harden-activity-debounce-cache-reliability + +## DebounceHelper + +- [x] Task 1: In `lib/Activity/DebounceHelper.php`, add a constructor + parameter `private readonly ?\OCP\ICache $cache = null` (nullable so + existing unit-test call sites that construct `new DebounceHelper($clock)` + keep working), alongside the existing `?callable $clock` parameter. +- [x] Task 2: In `claim()` (currently lines 142-167), when + `$this->realClock === true` and APCu is unusable + (`apcuUsable() === false`) and `$this->cache !== null`, use + `$this->cache->add($key, $now, self::TTL_SECONDS)`-equivalent semantics: + `OCP\ICache` doesn't expose an atomic `add()`, so implement the claim as + `if ($this->cache->hasKey($key)) { return false; } $this->cache->set($key, $now, self::TTL_SECONDS); return true;` + and document the small race window this introduces (acceptable for a + 15-minute debounce UX guard, not a security control). +- [x] Task 3: Keep the existing `$this->memory` array path as the final + fallback only when `$this->cache === null` (defensive) or when + `$this->realClock === false` (test-clock path, unchanged from today). +- [x] Task 4: Update the class docblock (lines 14-17) and the `claim()` + docblock (lines 132-141) to describe the three-tier fallback: APCu → + `ICache` (distributed) → in-memory array (test-clock only). + +## Application.php wiring + +- [x] Task 5: In `lib/AppInfo/Application.php` (lines 98-107), change the + `DebounceHelper` factory to resolve `OCP\ICacheFactory` from the + container and call `createDistributed('launchpad_activity_debounce')`, + passing the resulting `ICache` into the `DebounceHelper` constructor: + `factory: static fn(\Psr\Container\ContainerInterface $c): DebounceHelper => new DebounceHelper(cache: $c->get(\OCP\ICacheFactory::class)->createDistributed('launchpad_activity_debounce'))` + (adjust to match the existing container-callback signature used by + neighbouring registrations in the same file). +- [x] Task 6: Update the inline comment at line 98 ("register + DebounceHelper as a shared singleton") to also note that the shared + distributed cache — not the PHP singleton — is what makes the debounce + guarantee hold across requests. + +## Tests + +- [x] Task 7: Add a PHPUnit test that constructs `DebounceHelper` with a + fake `ICache` implementation (no APCu, real clock) and asserts that + `allowReaction()` called twice in immediate succession for the same + `(actor, dashboard)` pair returns `true` then `false` — i.e. the + distributed-cache path is exercised, not just the in-memory fallback. +- [x] Task 8: Add a regression test that simulates "APCu absent, cache + absent" (both `apcuUsable()` false and `$cache === null`) and asserts the + helper still falls back to the in-memory array without throwing, to + confirm the defensive tier is not a hard dependency. +- [x] Task 9: Re-run the existing `activity-feed-integration` PHPUnit + suite referenced by `openspec/specs/activity-feed-integration/spec.md` + to confirm REQ-ACT-007/REQ-ACT-008 scenarios still pass unchanged. + +> Ticked at archive, 12 Nov 2026: `development` at 1d792009 already carries the change. `lib/Activity/DebounceHelper.php` falls back to the distributed `OCP\ICache` when APCu is unusable, and keeps the in-memory array only for a missing cache or a test clock. The tests were not re-run for this archive. diff --git a/openspec/changes/launchpad-ai-dashboard-assistant/.openspec.yaml b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/.openspec.yaml similarity index 100% rename from openspec/changes/launchpad-ai-dashboard-assistant/.openspec.yaml rename to openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/.openspec.yaml diff --git a/openspec/changes/launchpad-ai-dashboard-assistant/context-brief.md b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/context-brief.md similarity index 100% rename from openspec/changes/launchpad-ai-dashboard-assistant/context-brief.md rename to openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/context-brief.md diff --git a/openspec/changes/launchpad-ai-dashboard-assistant/design.md b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/design.md similarity index 100% rename from openspec/changes/launchpad-ai-dashboard-assistant/design.md rename to openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/design.md diff --git a/openspec/changes/launchpad-ai-dashboard-assistant/hydra.json b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/hydra.json similarity index 100% rename from openspec/changes/launchpad-ai-dashboard-assistant/hydra.json rename to openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/hydra.json diff --git a/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/proposal.md new file mode 100644 index 000000000..c4ae2d474 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/proposal.md @@ -0,0 +1,43 @@ +> Superseded by the main spec launchpad-ai-dashboard-assistant, REQ-ADA-004 (inference only through hermiq, no LLM client in LaunchPad); case summaries are dossiq's, placed as a widget (row d-work-queue). Decision 399. + +# Embedded AI assistant and smart summaries + +As a case worker or dashboard user, I want to view intelligent summaries of my workload on the dashboard—cases and consultation responses—so that I can quickly assess my current status without navigating away. This change adds two widgets powered by AI-driven summarization to help users make faster decisions on their open cases and gather feedback insights. + +## Affected code units + +- `src/components/CasesSummaryWidget.vue` — displays open case count, status distribution, and recent cases +- `src/components/ConsultationSummaryWidget.vue` — displays consultation response metrics and key feedback +- `src/store/modules/casesStore.js` — Pinia store for case data (CRUD via OpenRegister) +- `src/store/modules/consultationStore.js` — Pinia store for consultation data (CRUD via OpenRegister) +- `lib/Service/SummaryService.php` — AI-powered summarization for both case and consultation data +- `lib/Controller/WidgetController.php` — API endpoints for widget data (`GET /api/widgets/cases-summary`, `GET /api/widgets/consultation-summary`) +- `lib/Settings/launchpad_register.json` — OpenRegister schema definitions for Case and Consultation +- Modifies dashboard `capabilities` to register the two new widgets + +## Why a delta + +LaunchPad currently has no dashboard widgets for case summaries. Case workers must navigate to a separate cases list to see their open work, losing context from the dashboard. This change surfaces key case and consultation metrics inline on the dashboard, reducing context switching and improving situational awareness. The summarization is powered by Claude via OpenAI-compatible API for intelligent, actionable insights. + +## Approach + +- **Data source**: OpenRegister stores all cases and consultations. Widget controllers fetch and aggregate this data via OpenRegister's `ObjectService`. +- **Summarization**: A `SummaryService` enriches aggregated data with AI-generated narrative summaries (e.g., "You have 5 open cases, 2 are overdue. Key actions: X, Y, Z"). +- **Frontend**: Two Vue components (`CasesSummaryWidget`, `ConsultationSummaryWidget`) render dashboard cards with metrics and summaries, styled with NL Design System tokens. +- **RBAC**: OpenRegister's object-level permissions filter visible cases/consultations per user; the widget respects these filters automatically. +- **Caching**: Summary API responses cached for 5 minutes to avoid repeated AI calls for the same data snapshot. + +## Capabilities + +**New Capabilities:** + +- `launchpad-cases-summary` — display open case count, status breakdown, and AI summary +- `launchpad-consultation-summary` — display consultation response metrics and key feedback summary + +## Notes + +- Summaries are generated on-demand (not pre-computed) and cached briefly to balance freshness vs. API cost. +- Both widgets integrate with LaunchPad's existing dashboard edit mode and GridStack layout engine. +- Case and Consultation schemas are defined in OpenRegister with full CRUD operations available via the existing app scaffolding. +- Widget visibility respects per-user OpenRegister permissions — no additional RBAC layer needed. +- The AI service is optional; if the Claude API is unavailable or quota exhausted, widgets fall back to displaying raw metrics without summaries. diff --git a/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/screens.md b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/changes/launchpad-ai-dashboard-assistant/specs/launchpad-cases-summary/spec.md b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/specs/launchpad-cases-summary/spec.md similarity index 100% rename from openspec/changes/launchpad-ai-dashboard-assistant/specs/launchpad-cases-summary/spec.md rename to openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/specs/launchpad-cases-summary/spec.md diff --git a/openspec/changes/launchpad-ai-dashboard-assistant/specs/launchpad-consultation-summary/spec.md b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/specs/launchpad-consultation-summary/spec.md similarity index 100% rename from openspec/changes/launchpad-ai-dashboard-assistant/specs/launchpad-consultation-summary/spec.md rename to openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/specs/launchpad-consultation-summary/spec.md diff --git a/openspec/changes/launchpad-ai-dashboard-assistant/tasks.md b/openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/tasks.md similarity index 100% rename from openspec/changes/launchpad-ai-dashboard-assistant/tasks.md rename to openspec/changes/archive/2026-11-12-launchpad-ai-dashboard-assistant/tasks.md diff --git a/openspec/changes/launchpad-enterprise-security-access/.openspec.yaml b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/.openspec.yaml similarity index 100% rename from openspec/changes/launchpad-enterprise-security-access/.openspec.yaml rename to openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/.openspec.yaml diff --git a/openspec/changes/launchpad-enterprise-security-access/context-brief.md b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/context-brief.md similarity index 100% rename from openspec/changes/launchpad-enterprise-security-access/context-brief.md rename to openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/context-brief.md diff --git a/openspec/changes/launchpad-enterprise-security-access/design.md b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/design.md similarity index 100% rename from openspec/changes/launchpad-enterprise-security-access/design.md rename to openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/design.md diff --git a/openspec/changes/launchpad-enterprise-security-access/hydra.json b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/hydra.json similarity index 100% rename from openspec/changes/launchpad-enterprise-security-access/hydra.json rename to openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/hydra.json diff --git a/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/proposal.md new file mode 100644 index 000000000..47e9cd608 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/proposal.md @@ -0,0 +1,43 @@ +> Superseded by admin-roles, role-feature-permissions and action-authorization (rows r-delegate, t-widget-kinds, t-action-matrix); "view as" overlaps row t-preview. Decision 399. + +# Enterprise security and access controls + +LaunchPad dashboards today support admin-only visibility and read-only guest access, but lack fine-grained role-based permissions and impersonation capabilities needed in enterprise deployments. This change introduces guest user role management, per-role dashboard and widget visibility enforcement, and a "view as" impersonation feature for admins to troubleshoot access issues. + +## Affected code units + +- `lib/Controller/DashboardController.php` — add role context to dashboard state +- `lib/Service/DashboardAuthorizationService.php` (new) — per-role visibility enforcement +- `lib/Service/GuestRoleService.php` (new) — guest user role management +- `lib/Service/ImpersonationService.php` (new) — audit-logged role impersonation +- `src/store/modules/dashboard.js` — store user's roles + active impersonation +- `src/views/Dashboard.vue` — render "View as" role selector for admins; hide widgets/actions per active role +- `src/components/RoleSelector.vue` (new) — role selection dropdown with visual indicator +- OpenRegister schema: `GuestRole` — define available roles and their permissions per dashboard +- OpenRegister schema: `DashboardPermission` — map role ↔ dashboard/widget visibility +- Adds `security-access` capability to LaunchPad + +## Why a delta + +LaunchPad currently lacks role-based access control. Every user sees either (admin) all dashboards, or (guest) no dashboards. Enterprises with multiple governance bodies, departments, or partner integrations need to grant selective access to external users without promoting them to Nextcloud administrators. ADR-023 establishes the pattern for action-level RBAC; this change applies data-level RBAC to dashboard visibility via the OpenRegister integration. + +## Approach + +1. **Guest role registration** — admins define roles (chair, secretary, member) and assign guest users to them via settings. +2. **Dashboard permission mapping** — each dashboard declares which roles can view it. Roles and dashboard together determine widget-level visibility via schema definitions. +3. **Authorization service** — every dashboard load / widget fetch checks the user's role + dashboard permissions. Unauthorized access returns 403. +4. **Impersonation service** — admins can "View as <role>" to preview what a guest with that role sees. The active role is tracked per session, persisted in Pinia store, and logged to audit trail. +5. **Frontend enforcement** — Vue components bind visibility to the user's effective role (either their assigned role or the impersonated role). Role changes trigger re-renders via store mutations. + +## Capabilities + +**New Capabilities:** + +- `security-access` — guest role definitions, dashboard permission mappings, per-role widget visibility, impersonation with audit logging + +## Notes + +- OpenRegister integration: guest roles and dashboard permissions are stored in OpenRegister and consumed via the shared `@conduction/nextcloud-vue` components. +- Audit trails: impersonation start/end and role changes are logged via OpenRegister's immutable audit service (ADR-022 lists audit as a consumed abstraction). +- No change to existing dashboard-sharing URLs — guest links remain valid; role checks happen at the API level, not the link level. +- Phase 2 (future): per-widget role exceptions for granular override; per-role data filtering for linked objects (files, notes, contacts). diff --git a/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/screens.md b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/screens.md new file mode 100644 index 000000000..8ce5b3fa4 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement diff --git a/openspec/changes/launchpad-enterprise-security-access/specs/security-access/spec.md b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/specs/security-access/spec.md similarity index 100% rename from openspec/changes/launchpad-enterprise-security-access/specs/security-access/spec.md rename to openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/specs/security-access/spec.md diff --git a/openspec/changes/launchpad-enterprise-security-access/tasks.md b/openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/tasks.md similarity index 100% rename from openspec/changes/launchpad-enterprise-security-access/tasks.md rename to openspec/changes/archive/2026-11-12-launchpad-enterprise-security-access/tasks.md diff --git a/openspec/changes/launchpad-file-access-widget/.openspec.yaml b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/.openspec.yaml similarity index 100% rename from openspec/changes/launchpad-file-access-widget/.openspec.yaml rename to openspec/changes/archive/2026-11-12-launchpad-file-access-widget/.openspec.yaml diff --git a/openspec/changes/launchpad-file-access-widget/context-brief.md b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/context-brief.md similarity index 100% rename from openspec/changes/launchpad-file-access-widget/context-brief.md rename to openspec/changes/archive/2026-11-12-launchpad-file-access-widget/context-brief.md diff --git a/openspec/changes/launchpad-file-access-widget/design.md b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/design.md similarity index 100% rename from openspec/changes/launchpad-file-access-widget/design.md rename to openspec/changes/archive/2026-11-12-launchpad-file-access-widget/design.md diff --git a/openspec/changes/launchpad-file-access-widget/hydra.json b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/hydra.json similarity index 100% rename from openspec/changes/launchpad-file-access-widget/hydra.json rename to openspec/changes/archive/2026-11-12-launchpad-file-access-widget/hydra.json diff --git a/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/proposal.md new file mode 100644 index 000000000..989b61841 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/proposal.md @@ -0,0 +1,42 @@ +> Superseded: dossier files belong to dossiq and reach LaunchPad as a Nextcloud widget; LaunchPad's own Files widget is built (row w-files). Decision 399. + +# Open dossier document from dashboard + +Dashboard users need quick access to dossier documents without navigating away from the dashboard view. Currently, document links are buried in detail pages, forcing users to context-switch to find critical files. This change adds a file-access widget to the LaunchPad dashboard: a card displaying associated documents with direct open-in-viewer links, filterable by dossier and file type, with built-in access control to prevent unauthorized downloads. + +## Affected code units + +- `src/components/DashboardFileAccessWidget.vue` — new widget displaying files linked to the current dossier +- `src/store/modules/files.js` — extend store to fetch + cache dossier files +- `src/composables/useFileAccess.js` — new composable for file retrieval + access checks +- `src/dashboard/` — widget slot registration in dashboard layout +- `lib/Controller/FileAccessController.php` — new backend endpoint for authenticated file listing +- `lib/Service/FileAccessService.php` — business logic for file access + filtering +- Consumes `@conduction/nextcloud-vue` + OpenRegister `FileService` (no custom file handling) + +## Why a delta + +LaunchPad dashboards today are widget-based but lack direct document access. Users switch to detail pages or external document managers to view case-related files. This creates friction in case-management workflows where documents are the primary work product. The feature stays confined to the dashboard widget system and reuses OpenRegister's file abstractions (ADR-022 pattern); no new document storage or access-control logic is introduced. + +## Approach + +- **Widget integration** — `CnDashboardPage` loads the widget via GridStack; the widget fetches its data from the backend on mount and when the dossier changes +- **Backend file listing** — `FileAccessController::list()` queries OpenRegister's file associations for the dossier + applies user's per-file permissions via `PropertyRbacHandler` +- **File viewer link** — each file displays a link that opens the document via Nextcloud's `FileService` (existing `download` + `preview` endpoints, no custom routes) +- **Access control** — backend enforces authorization; frontend silently hides files the user cannot read. No attempt-to-view failures displayed to the user. +- **Filtering** (defer to Phase 2) — file-type filters and search are designed but not implemented in this change + +## Capabilities + +**NEW Capabilities:** + +- `file-access-widget` (new) + - Requirement: `REQ-FILE-001` — File list display with access control + - Requirement: `REQ-FILE-002` — File viewer integration + - Requirement: `REQ-FILE-003` — Access denial handling + +## Notes + +- File permissions are evaluated by OpenRegister; this widget is a read-only consumer, not an access-control enforcer +- The widget is responsive: works at 320px (stacked list) and 1920px (multi-column cards) +- Tested via Playwright scenarios: "view accessible files", "access denied files are hidden" diff --git a/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/screens.md b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/changes/launchpad-file-access-widget/specs/file-access-widget/spec.md b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/specs/file-access-widget/spec.md similarity index 100% rename from openspec/changes/launchpad-file-access-widget/specs/file-access-widget/spec.md rename to openspec/changes/archive/2026-11-12-launchpad-file-access-widget/specs/file-access-widget/spec.md diff --git a/openspec/changes/launchpad-file-access-widget/tasks.md b/openspec/changes/archive/2026-11-12-launchpad-file-access-widget/tasks.md similarity index 100% rename from openspec/changes/launchpad-file-access-widget/tasks.md rename to openspec/changes/archive/2026-11-12-launchpad-file-access-widget/tasks.md diff --git a/openspec/changes/drill-down-cross-widget-filter/.openspec.yaml b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/.openspec.yaml similarity index 100% rename from openspec/changes/drill-down-cross-widget-filter/.openspec.yaml rename to openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/.openspec.yaml diff --git a/openspec/changes/launchpad-meeting-calendar-actions/context-brief.md b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/context-brief.md similarity index 100% rename from openspec/changes/launchpad-meeting-calendar-actions/context-brief.md rename to openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/context-brief.md diff --git a/openspec/changes/launchpad-meeting-calendar-actions/design.md b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/design.md similarity index 100% rename from openspec/changes/launchpad-meeting-calendar-actions/design.md rename to openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/design.md diff --git a/openspec/changes/launchpad-meeting-calendar-actions/hydra.json b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/hydra.json similarity index 100% rename from openspec/changes/launchpad-meeting-calendar-actions/hydra.json rename to openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/hydra.json diff --git a/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/proposal.md new file mode 100644 index 000000000..1162ab70d --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/proposal.md @@ -0,0 +1,57 @@ +> Superseded: meeting notes belong to decidiq or Calendar; LaunchPad shows the calendar (row w-calendar). Decision 399. + +# Meeting and calendar actions from dashboard + +## Why + +LaunchPad displays agenda items and calendar events to users, but today they are read-only. Users frequently need to add context, notes, or annotations to events directly from the dashboard view — without navigating away to the Nextcloud Calendar app. Common use cases: + +- A participant jots down "agenda item pushed to next meeting" on a postponed event +- A chair adds "quorum met" or "absence excused" annotations during a meeting +- A secretary records "decision approved unanimously" alongside a governance event + +Today this workflow requires opening the Calendar app separately, navigating to the event, then returning to the dashboard. The feature consolidates this into a single dashboard interface. + +## What Changes + +- Users can add annotations to visible agenda items / calendar events directly from the dashboard widget +- Annotations are saved to the Nextcloud Calendar app as event notes/descriptions (via the Calendar app's API) +- Annotations persist and are visible on subsequent dashboard loads +- Users can edit or remove existing annotations in-place without page reload + +## Capabilities + +### New Capabilities + +- **dashboard-calendar-annotations**: Inline annotation of agenda items on the dashboard widget + +### Related Capabilities + +- `admin-templates` (group-routing): determines which group's calendars are visible +- `dashboards` (multi-scope-dashboards): the dashboard widget that renders agenda items +- Nextcloud Calendar integration: annotations are stored in Calendar events + +## Impact + +**Affected code:** + +- `src/components/CalendarWidget.vue` — add annotation UI (edit, save, cancel buttons) +- `src/store/modules/calendarStore.js` — new actions to sync annotations with Calendar API +- `lib/Controller/CalendarController.php` — new endpoint `PUT /api/calendar/{id}/annotation` to persist annotations +- `lib/Service/CalendarService.php` — annotation persistence logic + +**Affected APIs:** + +- New HTTP endpoint: `PUT /index.php/apps/launchpad/api/calendar-events/{eventId}/annotation` (authenticated, non-admin) +- Existing Nextcloud Calendar `/ocs/v2.php/apps/calendar/api/v1/events/{id}` is called server-side + +**Dependencies:** + +- Nextcloud Calendar app (must be installed and enabled) +- No new composer or npm dependencies + +**Migration:** + +- Zero schema impact: annotations are stored in Calendar event properties +- Existing calendar events are unmodified; the feature is purely additive +- No data backfill required diff --git a/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/screens.md b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/changes/launchpad-meeting-calendar-actions/specs/dashboard-calendar-annotations.md b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/specs/dashboard-calendar-annotations.md similarity index 100% rename from openspec/changes/launchpad-meeting-calendar-actions/specs/dashboard-calendar-annotations.md rename to openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/specs/dashboard-calendar-annotations.md diff --git a/openspec/changes/launchpad-meeting-calendar-actions/tasks.md b/openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/tasks.md similarity index 100% rename from openspec/changes/launchpad-meeting-calendar-actions/tasks.md rename to openspec/changes/archive/2026-11-12-launchpad-meeting-calendar-actions/tasks.md diff --git a/openspec/changes/launchpad-mobile-remote-access/.openspec.yaml b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/.openspec.yaml similarity index 100% rename from openspec/changes/launchpad-mobile-remote-access/.openspec.yaml rename to openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/.openspec.yaml diff --git a/openspec/changes/launchpad-mobile-remote-access/context-brief.md b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/context-brief.md similarity index 100% rename from openspec/changes/launchpad-mobile-remote-access/context-brief.md rename to openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/context-brief.md diff --git a/openspec/changes/launchpad-mobile-remote-access/design.md b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/design.md similarity index 100% rename from openspec/changes/launchpad-mobile-remote-access/design.md rename to openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/design.md diff --git a/openspec/changes/launchpad-mobile-remote-access/hydra.json b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/hydra.json similarity index 100% rename from openspec/changes/launchpad-mobile-remote-access/hydra.json rename to openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/hydra.json diff --git a/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/proposal.md b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/proposal.md new file mode 100644 index 000000000..395a93660 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/proposal.md @@ -0,0 +1,174 @@ +--- +status: proposed +--- + +> Superseded by the Nextcloud platform: sign-in from outside, session timeout and phone access are built there (rows p-sso, d-pwa, d-dark-mode). Decision 399. + +# Proposal: Mobile and Remote Dashboard Access + +## Executive Summary + +LaunchPad currently requires office-based access over corporate networks with desktop-optimized interfaces. This proposal enables secure remote employee access from mobile devices and external networks, unlocking productivity for distributed teams while maintaining security posture. + +## Features + +### 1. Remote Work and Mobile Access +**Demand: 28** (3 tender mentions) | **Category:** Security | **Coverage:** LaunchPad + +#### Capability +As a remote employee, I want secure access to launchpad from any device or location, so that I can work productively outside the office. + +#### Acceptance Criteria +1. GIVEN a remote employee with valid credentials, WHEN they log in from a mobile device outside the corporate network, THEN they can access their dashboard and all permitted features. +2. GIVEN a remote employee is authenticated, WHEN their session is idle beyond the configured timeout, THEN they are automatically signed out and must re-authenticate. +3. GIVEN a remote employee using a mobile browser, WHEN they navigate launchpad, THEN the interface is fully usable with touch controls and adapts to the screen size without loss of functionality. + +#### Impact +- Enables distributed workforce capabilities +- Reduces dependency on VPN for dashboard access +- Maintains security through session timeout and authentication enforcement + +### 2. Access to Relevant Applications and News +**Demand: 25** (3 tender mentions) | **Category:** Security | **Coverage:** LaunchPad + +#### Capability +As an employee, I want access to relevant applications and news in launchpad, so that I can stay informed and productive from a single dashboard. + +#### Acceptance Criteria +1. GIVEN an authenticated employee, WHEN they open launchpad, THEN a curated list of relevant applications is displayed based on their role and permissions. +2. GIVEN an authenticated employee, WHEN they open launchpad, THEN a news feed showing organisation-relevant news is visible without navigating away. +3. GIVEN a security administrator, WHEN they configure application and news access policies, THEN only authorised content is shown to each employee based on their assigned role. + +#### Impact +- Centralizes access to critical applications and information +- Reduces context switching and improves productivity +- Enables role-based content filtering for security and compliance + +## User Stories + +### US-001: Remote Login from Mobile Device +**Derived from Feature 1 (Remote Work and Mobile Access)** + +As a field employee, I want to log in to LaunchPad from my phone while at a client site, so that I can review my dashboard without returning to the office. + +**Acceptance Criteria:** +1. GIVEN I have valid Nextcloud credentials +2. WHEN I visit the LaunchPad URL on my mobile device +3. THEN I can log in using Nextcloud's standard authentication +4. AND I see a mobile-optimized version of my dashboard +5. AND all dashboard features are accessible via touch + +### US-002: Automatic Session Timeout +**Derived from Feature 1 (Remote Work and Mobile Access)** + +As a security-conscious employee, I want my session to automatically expire after inactivity, so that my device is protected if I forget to log out. + +**Acceptance Criteria:** +1. GIVEN I am logged into LaunchPad on a mobile device +2. WHEN I have not interacted with the dashboard for 15 minutes (configurable) +3. THEN my session is automatically terminated +4. AND the next dashboard access requires re-authentication + +### US-003: View Role-Based Applications +**Derived from Feature 2 (Access to Relevant Applications and News)** + +As a department manager, I want to see a list of applications relevant to my role, so that I can quickly access tools needed for my responsibilities. + +**Acceptance Criteria:** +1. GIVEN I am authenticated in LaunchPad +2. WHEN I view the applications section +3. THEN I see only applications my role has permission to access +4. AND applications are grouped logically (by department or function) + +### US-004: Configure Application Access Policies +**Derived from Feature 2 (Access to Relevant Applications and News)** + +As a security administrator, I want to control which applications appear for each user role, so that sensitive tools are only accessible to authorized personnel. + +**Acceptance Criteria:** +1. GIVEN I am an admin in LaunchPad +2. WHEN I access the admin settings for application access +3. THEN I can view all available applications and user roles +4. AND I can map which roles can see which applications +5. AND changes take effect immediately for all users + +## Customer Journeys + +### Journey: New Remote Hire Onboarding +**Trigger:** New employee joins company + +1. **Authentication Phase** (Day 1) + - Pain point: Employee is not yet at office, needs to access company systems immediately + - Solution: Can log in from home using Nextcloud credentials + +2. **Dashboard Discovery** (Day 1-2) + - Pain point: Unsure which applications are relevant to their role + - Solution: LaunchPad displays role-specific application list without manual configuration + +3. **Remote Access** (Day 1+) + - Pain point: Relies on VPN for secure access + - Solution: LaunchPad provides secure direct access from any location with automatic session management + +### Journey: Executive News Brief +**Trigger:** Executive starts their day + +1. **Single-Point Access** (Morning) + - Pain point: Scattered across multiple portals and news sources + - Solution: LaunchPad dashboard displays curated organization news and relevant applications on one screen + +2. **Mobile Browsing** (Travel) + - Pain point: Need to stay informed while traveling + - Solution: Mobile-optimized dashboard with news feed accessible from phone + +3. **Role-Based Filtering** (Consistent) + - Pain point: Sees irrelevant content from other departments + - Solution: Admin-configured policies ensure only relevant content appears + +## Stakeholders + +### Information Security Officer +- **Responsibilities:** Define and enforce security policies for remote access, session timeout, and authentication +- **Goals:** Maintain security posture while enabling remote work; ensure audit trails for compliance +- **Success Criteria:** Zero security incidents from remote access; full session lifecycle logging + +### Product Manager (LaunchPad) +- **Responsibilities:** Prioritize features; ensure mobile UX is competitive; manage releases +- **Goals:** Enable distributed workforce; increase daily active users; reduce support overhead +- **Success Criteria:** Mobile traffic increases to 30%+ of total; session timeout reduces support tickets by 25% + +### System Administrator +- **Responsibilities:** Deploy LaunchPad; configure application and news access policies; manage user permissions +- **Goals:** Enable self-service application discovery; reduce onboarding time; maintain system stability +- **Success Criteria:** New users can access LaunchPad without manual admin intervention; policies are easy to manage + +### Remote Employee +- **Responsibilities:** Use LaunchPad for daily work and information access +- **Goals:** Seamless access from any location; quick discovery of needed applications; stay informed +- **Success Criteria:** Can log in and access dashboard within 30 seconds; find relevant applications without searching + +### Executive (Chief Officer) +- **Responsibilities:** Monitor organizational news and metrics from LaunchPad +- **Goals:** Single dashboard view of key information; mobile access while traveling; time savings +- **Success Criteria:** Spends less than 5 minutes per day on news/app discovery; uses dashboard on mobile 3+ days/week + +## Deployment Scope + +**In this spec:** +- Nextcloud authentication and session management for remote access +- Mobile-responsive UI for LaunchPad (touch-optimized) +- Role-based application visibility filtering +- News/content curation based on roles +- Session timeout configuration in admin settings + +**Deferred to future spec (if needed):** +- Advanced analytics on app/news usage +- Personalized recommendation engine +- Deep single-sign-on integrations with external platforms + +## Success Metrics + +- Mobile users accessing dashboard: > 30% of total daily active users (target: 6 months) +- Session timeout reduction in support tickets: > 25% improvement in auth-related issues +- Admin configuration time for app/news policies: < 30 minutes per organization +- Mobile dashboard load time: < 2 seconds on 4G network +- User satisfaction with mobile experience: > 4.0/5.0 NPS score diff --git a/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/screens.md b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/screens.md new file mode 100644 index 000000000..87dfce8ba --- /dev/null +++ b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpMobiel https://identity.conduction.nl/screens/board?id=launchpad/LpMobiel diff --git a/openspec/changes/launchpad-mobile-remote-access/specs.md b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/specs.md similarity index 100% rename from openspec/changes/launchpad-mobile-remote-access/specs.md rename to openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/specs.md diff --git a/openspec/changes/launchpad-mobile-remote-access/tasks.md b/openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/tasks.md similarity index 100% rename from openspec/changes/launchpad-mobile-remote-access/tasks.md rename to openspec/changes/archive/2026-11-12-launchpad-mobile-remote-access/tasks.md diff --git a/openspec/changes/embedded-analytics/.openspec.yaml b/openspec/changes/archive/2026-11-12-public-dashboard-publication/.openspec.yaml similarity index 100% rename from openspec/changes/embedded-analytics/.openspec.yaml rename to openspec/changes/archive/2026-11-12-public-dashboard-publication/.openspec.yaml diff --git a/openspec/changes/public-dashboard-publication/context-brief.md b/openspec/changes/archive/2026-11-12-public-dashboard-publication/context-brief.md similarity index 100% rename from openspec/changes/public-dashboard-publication/context-brief.md rename to openspec/changes/archive/2026-11-12-public-dashboard-publication/context-brief.md diff --git a/openspec/changes/public-dashboard-publication/design.md b/openspec/changes/archive/2026-11-12-public-dashboard-publication/design.md similarity index 100% rename from openspec/changes/public-dashboard-publication/design.md rename to openspec/changes/archive/2026-11-12-public-dashboard-publication/design.md diff --git a/openspec/changes/public-dashboard-publication/hydra.json b/openspec/changes/archive/2026-11-12-public-dashboard-publication/hydra.json similarity index 100% rename from openspec/changes/public-dashboard-publication/hydra.json rename to openspec/changes/archive/2026-11-12-public-dashboard-publication/hydra.json diff --git a/openspec/changes/archive/2026-11-12-public-dashboard-publication/proposal.md b/openspec/changes/archive/2026-11-12-public-dashboard-publication/proposal.md new file mode 100644 index 000000000..b904d3cf1 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-public-dashboard-publication/proposal.md @@ -0,0 +1,58 @@ +> Superseded by the built public link (rows s-public, s-public-protect) and by the open change embedded-analytics for embedding on outside sites. Decision 399. + +# Public Dashboard Publication + +LaunchPad dashboards are today identity-bound — every viewer is an authenticated user and every view is recorded against that user. This is correct for internal BI and for the existing `dashboard-sharing` capability which lets one user share with another identified user. It is wrong for open-overheid use cases where any citizen should be able to view a live dashboard without a login. + +This change introduces a publication channel — distinct from sharing — that lets a dashboard owner mark a dashboard as publishable and choose from three publication modes (fully public, signed-URL with expiry, password-gated). The owner can apply a publication-specific brand chrome (gemeente logo, colours, footer), configure search-engine indexing and caching directives, and surface traffic metrics in aggregate form (no per-citizen tracking). All data queries on a published dashboard run as a designated "publication service account" so the viewer never inherits elevated permissions. + +This change scopes deliberately to read-only viewing. Interactive filtering, comment threads, and authenticated personalisation belong to a future `interactive-public-dashboard` change. + +## Affected code units + +- `lib/Service/PublicationService.php` — manage DashboardPublication, PublicationBranding, PublicationAccess configurations +- `lib/Service/PublicationAuthService.php` — validate access against mode (public, signed, password) +- `lib/Service/PublicationQueryService.php` — execute dashboard queries as publication service account +- `lib/Service/PublicationAnalyticsService.php` — aggregate view counts per hour, no PII +- `lib/Controller/PublicationController.php` — `/api/publication/{slug}` read endpoint (anon-accessible) +- `lib/Controller/PublicationSettingsController.php` — owner config endpoints (auth-required) +- OpenRegister schemas: `DashboardPublication`, `PublicationBranding`, `PublicationAccess`, `SignedUrlGrant`, `PasswordGate`, `PublicationServiceAccount`, `PublicationViewLog` + +## Why a new capability + +Publication is a distinct use case with its own data model, access-control rules, query-execution context, and analytics. Folding it into `dashboard-sharing` would conflate two incompatible flows: identity-bound sharing with per-user ACLs, and anonymous publication with service-account queries. + +## Approach + +- **Configuration**: Owner marks a dashboard as publishable and configures mode, slug, branding, robots policy, cache headers via a publication-settings form. +- **Access validation**: Signed mode validates tamper-evident signature + expiry. Password mode validates hash against configured password. Public mode allows all. +- **Query execution**: All dashboard queries execute as a pre-configured publication service account with its own register/schema permissions. +- **Branding**: Publication-specific logo, colours, footer, language, and meta tags replace the internal LaunchPad chrome on the public-view route. +- **Indexing**: X-Robots-Tag and meta-robots directives honour the configured robotsPolicy so search engines follow the owner's intent. +- **Caching**: Cache-Control headers and ETag support enable CDN fronting at scale. +- **Analytics**: View counts recorded per hour bucket derived from salted session-cookie hashes — no backreferable identity tracking. + +## Capabilities + +**New Capabilities:** +- `public-dashboard-publication`: Owner-configured publication of read-only dashboards to anonymous viewers without authentication, with mode selection (public, signed, password), custom branding, SEO/cache control, and aggregate analytics. + +## Standards + +- WCAG 2.2 AA for gemeente public-facing pages +- Wet Digitale Overheid accessibility statement requirement +- AVG/GDPR aggregate-only analytics (no tracking cookies) +- Forum Standaardisatie DCAT-AP for open-data resource registration +- HTTP caching (RFC 9111) Cache-Control and conditional GET semantics + +## Cross-app dependencies + +- **launchpad dashboard-sharing**: distinct surface; sharing is identity-bound, publication is anonymous +- **opencatalogi**: published dashboards can be registered as open-data resources +- **openregister**: publication service account permissions enforced at register/schema layer +- **openconnector**: optional CDN front provisioned via connector +- **nldesign**: branding defaults derived from active nldesign palette + +## Target users + +Gemeente communicatie-afdelingen, open-data coördinatoren, journalisten, raadsgriffies, MKB klanten sharing KPI-pages with partners, and citizens viewing published open-data dashboards. diff --git a/openspec/changes/archive/2026-11-12-public-dashboard-publication/screens.md b/openspec/changes/archive/2026-11-12-public-dashboard-publication/screens.md new file mode 100644 index 000000000..60c824023 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-public-dashboard-publication/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpPubliek https://identity.conduction.nl/screens/board?id=launchpad/LpPubliek diff --git a/openspec/changes/public-dashboard-publication/specs/public-dashboard-publication/spec.md b/openspec/changes/archive/2026-11-12-public-dashboard-publication/specs/public-dashboard-publication/spec.md similarity index 100% rename from openspec/changes/public-dashboard-publication/specs/public-dashboard-publication/spec.md rename to openspec/changes/archive/2026-11-12-public-dashboard-publication/specs/public-dashboard-publication/spec.md diff --git a/openspec/changes/public-dashboard-publication/tasks.md b/openspec/changes/archive/2026-11-12-public-dashboard-publication/tasks.md similarity index 100% rename from openspec/changes/public-dashboard-publication/tasks.md rename to openspec/changes/archive/2026-11-12-public-dashboard-publication/tasks.md diff --git a/openspec/changes/harden-activity-debounce-cache-reliability/.openspec.yaml b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/.openspec.yaml similarity index 100% rename from openspec/changes/harden-activity-debounce-cache-reliability/.openspec.yaml rename to openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/.openspec.yaml diff --git a/openspec/changes/add-dashboard-sharing-e2e-coverage/proposal.md b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/proposal.md similarity index 100% rename from openspec/changes/add-dashboard-sharing-e2e-coverage/proposal.md rename to openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/proposal.md diff --git a/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/screens.md b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/screens.md new file mode 100644 index 000000000..2fb1d4cd2 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: tests, nothing a user operates diff --git a/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/specs/dashboard-sharing/spec.md b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/specs/dashboard-sharing/spec.md new file mode 100644 index 000000000..89899cfb0 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/specs/dashboard-sharing/spec.md @@ -0,0 +1,37 @@ +# Dashboard Sharing — E2E Coverage Delta + +## MODIFIED Requirements + +### Requirement: Owner-only share management (REQ-SHARE-001) + +@e2e tests/e2e/dashboard-sharing.spec.ts + +Only the owner of a dashboard MUST be allowed to list, create, update, or delete shares on that dashboard. All share-management endpoints MUST return HTTP 403 for any caller that is not the dashboard owner, including users who themselves have a `full`-level share on the dashboard. The owner-driven sharing UI flow (open `DashboardConfigModal`'s Sharing tab, add a share, change its permission level, remove a share) MUST be covered by a real Playwright e2e test that drives the actual router → middleware → controller → Vue re-render path, not only by PHPUnit tests that call the controller/service directly. + +#### Scenario: Owner adds a share + +- GIVEN a logged-in user "alice" who owns dashboard id `5` +- WHEN she sends `POST /api/dashboard/5/shares` with body `{"shareType": "user", "shareWith": "bob", "permissionLevel": "view_only"}` +- THEN the system MUST insert a row in `oc_launchpad_dashboard_shares` with the four fields plus `createdAt = now()` +- AND respond with HTTP 201 and the new share's id, displayName, and serialized fields + +#### Scenario: Recipient cannot manage shares + +- GIVEN dashboard `5` is owned by "alice" and shared with "bob" at `full` level +- WHEN bob sends `POST /api/dashboard/5/shares` to add another recipient +- THEN the system MUST return HTTP 403 +- AND no share row MUST be created + +#### Scenario: Updating an existing share replaces, does not duplicate + +- GIVEN alice has shared dashboard `5` with "bob" at `view_only` +- WHEN she sends `POST /api/dashboard/5/shares` with the same `shareType` and `shareWith` but `permissionLevel: "full"` +- THEN the system MUST update the existing share row, not create a second one +- AND only one share row MUST exist for `(dashboardId=5, shareType=user, shareWith=bob)` + +#### Scenario: A user drives the full sharing flow through the browser + +- GIVEN alice is logged in and opens the config modal for a dashboard she owns +- WHEN she switches to the Sharing tab, searches for and adds "bob" at `view_only`, changes his permission level to `full`, then removes his share, and reloads the page +- THEN `tests/e2e/dashboard-sharing.spec.ts` MUST assert each step persists correctly end to end (the added share appears, the level change is reflected, the removal survives a reload) +- AND the spec's e2e-exclusion annotation MUST be scoped to only the scenarios (if any) that genuinely have no UI surface, not a blanket exclusion of the whole capability diff --git a/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/tasks.md b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/tasks.md new file mode 100644 index 000000000..b44f8ed63 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-add-dashboard-sharing-e2e-coverage/tasks.md @@ -0,0 +1,51 @@ +# Tasks — add-dashboard-sharing-e2e-coverage + +## New e2e spec + +- [x] Task 1: Create `tests/e2e/dashboard-sharing.spec.ts` following the + fixture/auth setup convention used in `tests/e2e/nc-dashboard-widget.spec.ts` + or `tests/e2e/active-dashboard-resolution.spec.ts` (login as the admin + fixture user, or seed a second test user if the flow requires a real + distinct recipient). +- [x] Task 2: Test 1 — "Owner adds a user share": create/open a personal + dashboard, open `DashboardConfigModal`, switch to the Sharing tab + (`data-test="config-panel-sharing"`), use the sharee `NcSelect` + (search + select) to add a user, save, and assert the new share appears + in `.dashboard-config__shares`. +- [x] Task 3: Test 2 — "Owner changes a share's permission level": with an + existing share present, change its permission-level `NcSelect` value, + save, reload the modal, and assert the change persisted. +- [x] Task 4: Test 3 — "Owner removes a share": click the remove-share + button (`Close` icon `NcButton`, `aria-label` "Remove share"), save, + reload, and assert the share no longer appears. +- [x] Task 5: Test 4 (if feasible with the test fixture) — "Recipient sees + the shared dashboard": log in as the share recipient and confirm the + shared dashboard appears in their dashboard switcher with the correct + permission level enforced (read-only vs full, per REQ-SHARE-00x). + If a second seeded user is not available in the current e2e fixture, + use `test.skip(..., 'reason')` with a concrete, honest reason (matching + the house pattern already used elsewhere in `tests/e2e/`) rather than + silently omitting the scenario. + +## Spec annotation cleanup + +- [x] Task 6: In `openspec/specs/dashboard-sharing/spec.md`, remove the + blanket `@e2e exclude all scenarios test PHP DashboardShareService REST + API — sharing UI modals not present in v1.0.5` line (line 64). +- [x] Task 7: For each `### Requirement:` in the same spec, add either a + direct `@e2e tests/e2e/dashboard-sharing.spec.ts` reference (for the + scenarios covered by Tasks 2-5) or a specific, honest + `@e2e exclude <reason>` for any requirement that genuinely has no UI + surface (e.g. purely internal permission-ranking logic with no directly + observable UI state). + +## Verification + +- [x] Task 8: Run `npx playwright test dashboard-sharing` and confirm all + new tests pass against a local dev instance. +- [x] Task 9: Run the `gate-19`/`hydra-gate-e2e-coverage` check (or + `openspec/coverage-report.json` regeneration) against the diff and + confirm the `dashboard-sharing` capability's scenarios are no longer + flagged as blanket-excluded without per-scenario justification. + +Done 17 Nov 2026 (live pass): `tests/e2e/dashboard-sharing.spec.ts` already held the four tests of tasks 1 to 5, with the recipient run for real. They waited for `.launchpad-sidebar-toggle`, which LpVandaag removed, and now open the switcher through the More menu (`tests/e2e/support/dashboardSwitcher.ts`); 4 passed on a live NC 34 instance (task 8). The main spec already had no blanket exclusion and an `@e2e` line or a reasoned exclusion per requirement (tasks 6 and 7). Task 9: the diff-scoped hydra gates were run with this change in the diff. diff --git a/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/proposal.md b/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/proposal.md new file mode 100644 index 000000000..84ba0c1cc --- /dev/null +++ b/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/proposal.md @@ -0,0 +1,20 @@ +--- +kind: spec +depends_on: [] +--- + +# A person switches view counting off from their own settings + +## Why + +Parity row **g-optout** says people can opt out of view tracking. The server honours an opt-out: `lib/Service/AnalyticsService.php:134` reads the user value `analytics_optout` and skips the view event. Nobody can set that value from LaunchPad. No page in `src/` writes it, and the generic preferences route stores keys under a `pref_` prefix, so it cannot reach `analytics_optout` either. Only an administrator can set it, with `occ user:setting`. The row therefore loses its `built` state until a person can do it themselves. + +## What changes + +- `dashboard-view-analytics`: a person turns "Count my visits" off and on in LaunchPad's own settings, and LaunchPad stores the choice as `analytics_optout`. + +## Capabilities + +### Modified capabilities + +- `dashboard-view-analytics` diff --git a/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/screens.md b/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/screens.md new file mode 100644 index 000000000..5e2133ea4 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/screens.md @@ -0,0 +1,3 @@ +# Screens + +- launchpad/LpPersoonlijk: the "Mijn bezoeken meetellen" switch in personal settings (row g-optout) https://identity.conduction.nl/screens/board?id=launchpad/LpPersoonlijk diff --git a/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/specs/dashboard-view-analytics/spec.md b/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/specs/dashboard-view-analytics/spec.md new file mode 100644 index 000000000..ad07b5314 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/specs/dashboard-view-analytics/spec.md @@ -0,0 +1,27 @@ +# Delta for dashboard-view-analytics: a personal opt-out switch + +## ADDED Requirements + +### Requirement: A person turns view counting off in their own settings (REQ-ANLT-UI-001) + +LaunchPad's personal settings MUST show a "Count my visits" switch, on by default. Turning it off MUST store `analytics_optout = true` for that person, so REQ-ANLT-004 ignores their view and tile-click events. Turning it on again MUST store `false`. The switch MUST NOT show when an administrator has turned analytics off for everyone. + +#### Scenario: A person stops their visits being counted + +- **GIVEN** Eva is signed in and analytics is on for the organisation +- **WHEN** she opens her LaunchPad settings and turns "Count my visits" off +- **THEN** her user value `analytics_optout` is `true` +- **AND** her next dashboard visit adds nothing to the view counts + +#### Scenario: A person counts again + +- **GIVEN** Eva turned "Count my visits" off earlier +- **WHEN** she turns it on again +- **THEN** her user value `analytics_optout` is `false` +- **AND** her next dashboard visit is counted + +#### Scenario: Analytics is off for everyone + +- **GIVEN** an administrator turned analytics off for the organisation +- **WHEN** Eva opens her LaunchPad settings +- **THEN** the "Count my visits" switch is not shown diff --git a/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/tasks.md b/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/tasks.md new file mode 100644 index 000000000..037813250 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-analytics-personal-opt-out/tasks.md @@ -0,0 +1,5 @@ +# Tasks: analytics-personal-opt-out + +- [x] 1. Add a route that reads and writes the signed-in person's own `analytics_optout` value (`AnalyticsService::USER_PREF_KEY_OPTOUT`), `#[NoAdminRequired]`, and refuse any other user id. Verify: PHPUnit on the controller. +- [x] 2. Add the "Count my visits" switch to LaunchPad's personal settings (the user settings modal, not a `/settings/user` page), hidden while `analytics_enabled` is off. Verify: Vitest on the component. +- [x] 3. Fold REQ-ANLT-UI-001 into `openspec/specs/dashboard-view-analytics` on archive, and set parity row g-optout back to `built` with evidence lines. Done on archive 17 Nov 2026, after a live check on NC 34: `GET /api/analytics/me` answered `{"enabled":true,"optedOut":false}`, `PUT {"optedOut":true}` stored `analytics_optout=true` for the caller, and a PUT naming another user was refused ("You can only change your own analytics setting"). g-optout is `built` with evidence lines. diff --git a/openspec/changes/archive/2026-11-17-cross-app-attention-feed/design.md b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/design.md new file mode 100644 index 000000000..20aec43cc --- /dev/null +++ b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/design.md @@ -0,0 +1,143 @@ +# Design: cross-app attention feed + +## Decision 1: a data file, not a PHP interface + +The brief preferred reading a declaration the apps already have. They have one, but only inside their JavaScript bundle (see the proposal), so LaunchPad cannot reach it. The next smallest thing is a file. + +`appinfo/attention.json` was chosen over a PHP interface or an event because: + +- it needs no code in the app, so an app cannot break LaunchPad at load time and LaunchPad needs no class from the app (`class_exists` lookups go quiet when an app id moves); +- it is the same data the app already wrote for its own card, so a test in the app can hold the two equal; +- LaunchPad finds it through `IAppManager`, which already knows which apps are enabled for which user. + +## Decision 2: the browser counts, as the user + +LaunchPad's server does not query OpenRegister for another user's data. The widget asks OpenRegister directly, with the user's session: `GET /apps/openregister/api/objects/{register}/{schema}?<filter>&_limit=1` and reads `total`. This is the request the apps' own cards make (`readVisibleWhenValue` in the shared library), so the number is the same number, and OpenRegister's access rules decide what the user may count. + +## Decision 3: the link is built from the count's filter + +A lesson from all four app lanes: a number and the list it links to drift apart unless they share one filter. The declaration has no separate link query. LaunchPad writes the filter into the link as the query string, tokens unresolved (`assignee=@me`), which is what the apps' own links carry. The count resolves the tokens first. One filter, two uses. + +A filter must be flat for this: an operator is written in the key (`"deadline[lt]": "@today+1d"`), never nested (`"deadline": {"lt": ...}`). A nested filter is refused as an invalid declaration. The app lanes hit the nested form as a live defect. + +## Decision 4: failure is shown + +Three different things must not look alike: + +| What happened | What the employee sees | +| --- | --- | +| Every count ran and none needs attention | "Nothing needs your attention right now." | +| A count needs attention | A line with the number, the reason, the app and a link | +| A count could not run (network, server error, no access, unknown token) | A small line under the list: "Could not check: {app}" | +| No app declares anything | "None of your apps reports attention items yet." | + +When one count fails and the others are clear, the widget shows the failure and does NOT show "nothing needs your attention". + +## Decision 5: ranking + +1. Severity: `error`, then `warning`, then `info`. +2. Then the higher count. +3. Then the app's name, then the item id, so the order is stable. + +The widget shows the first `limit` lines (default 5) and says how many more there are. + +## The declaration + +```json +{ + "version": 1, + "items": [ + { + "id": "cases-past-deadline", + "title": "Cases past their deadline", + "reason": "{value} of your cases are past their deadline or end today.", + "severity": "error", + "source": { + "register": "dossiq", + "schema": "case", + "filter": { "assignee": "@me", "isFinalStatus": false, "deadline[lt]": "@today+1d" } + }, + "op": "gt", + "value": 0, + "action": { "label": "Open these cases", "path": "/cases" } + } + ] +} +``` + +- `title`, `reason` and `action.label` are English source strings. LaunchPad translates them with the declaring app's own translations, so the app keeps its wording. `{value}` in `reason` is the count. +- `action.path` is a path inside the declaring app. LaunchPad prefixes `/apps/<app id>`. A path cannot leave the app. +- `op` is `gt`, `gte`, `lt`, `lte`, `eq` or `neq`; default `gt`. `value` defaults to 0. +- Tokens the count resolves: `@me`, `@now`, `@today`, `@today+Nd`, `@today-Nd`, `@monthStart`, `@quarterStart`, `@yearStart`. Any other `@` token fails that count, visibly. + +## What each app adds + +Written from each app's `src/menu-layout.simple.json` on 5 October 2026. The paths are the apps' own list routes (all four use history routing under `/apps/<id>`). + +**dossiq** `appinfo/attention.json` + +```json +{ "version": 1, "items": [ { + "id": "cases-past-deadline", + "title": "Cases past their deadline", + "reason": "{value} of your cases are past their deadline or end today.", + "severity": "error", + "source": { "register": "dossiq", "schema": "case", "filter": { + "assignee": "@me", "isFinalStatus": false, "statusHiddenInLists": false, "isDraft": false, "deadline[lt]": "@today+1d" } }, + "action": { "label": "Open these cases", "path": "/cases" } +} ] } +``` + +**pipelinq** `appinfo/attention.json` + +```json +{ "version": 1, "items": [ { + "id": "tickets-past-deadline", + "title": "Tickets past their deadline", + "reason": "{value} of your tickets in progress are past their deadline or end today.", + "severity": "error", + "source": { "register": "pipelinq", "schema": "ticket", "filter": { + "assignee": "@me", "status": "in_progress", "slaDeadline[lt]": "@today+1d" } }, + "action": { "label": "Open these tickets", "path": "/tickets" } +} ] } +``` + +**decidiq** `appinfo/attention.json` + +```json +{ "version": 1, "items": [ { + "id": "decisions-open-for-voting", + "title": "Decisions wait for the vote", + "reason": "{value} decisions are open for voting.", + "severity": "warning", + "source": { "register": "decidiq", "schema": "decision", "filter": { "lifecycle": "voting" } }, + "action": { "label": "Open these decisions", "path": "/decisions" } +} ] } +``` + +**learniq** `appinfo/attention.json` + +```json +{ "version": 1, "items": [ { + "id": "attendance-flags-open", + "title": "Attendance flags nobody has picked up", + "reason": "{value} attendance flags are still open. Open one to start the follow-up.", + "severity": "warning", + "source": { "register": "learniq", "schema": "attendance-flag", "filter": { "lifecycle": "open" } }, + "action": { "label": "Open the flags", "path": "/attendance/flags" } +} ] } +``` + +Each app also needs: + +1. the three strings of each item in its `l10n/en.json` and `l10n/nl.json` (the title is there already; `reason` and the action label were added by hand for the card and may be there too); +2. a test that the item's `source.filter` equals the filter of its "First today" card in `src/menu-layout.simple.json`; +3. the file in its release package (`appinfo/` ships already). + +Two things for the owners to decide, not decided here: decidiq's and learniq's items count for everybody, not for "me" (their cards do the same), and their severity is set to `warning` here while their own cards use the error colour. + +## What was considered and not done + +- **Bundling the four declarations in LaunchPad.** It would make the widget show something before the apps add their file. It would also put a copy of each app's filter in LaunchPad, and copies drift. Not done. +- **Reading `src/menu-layout.simple.json` from the app's folder on disk.** `src/` is not part of every release package, and the file's shape is the shared library's to change. +- **A server-side count.** LaunchPad would have to ask OpenRegister on the user's behalf and cache per user. The browser already holds the session. diff --git a/openspec/changes/archive/2026-11-17-cross-app-attention-feed/proposal.md b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/proposal.md new file mode 100644 index 000000000..b0088ee00 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/proposal.md @@ -0,0 +1,54 @@ +--- +kind: code +depends_on: [mijn-werkdag-template] +--- + +# "First today" across apps: each app says what needs attention, LaunchPad shows one ranked list + +## Why + +The Zuiddrecht start page (`LpStart`) opens with "Vandaag eerst": a few lines from all the employee's apps that need attention today, each with a link into the app. The design notes say this contract does not exist yet. + +Measured on 5 October 2026: + +- dossiq, pipelinq, decidiq and learniq each show a "First today" card on their own simple dashboard. Each is a count of objects in an OpenRegister register with a filter (`visibleWhen.source` with `register`, `schema`, `filter`), a title, a reason and a link to the list. +- Those four declarations live in each app's `src/menu-layout.simple.json`. That file is compiled into the app's JavaScript. Nothing serves it: pipelinq and decidiq have no manifest endpoint, and the ones dossiq and learniq have serve the base manifest without this layout. LaunchPad cannot read them from a running instance. +- Nextcloud's dashboard widget interface (`OCP\Dashboard\IWidget`, `IAPIWidgetV2`) gives one widget per app. It has no way to rank items from several apps in one list. + +So LaunchPad needs a small declaration it can read, in the words the apps already use. + +## What changes + +- An app declares its attention items in one data file, `appinfo/attention.json`. No PHP interface and no registration call. The vocabulary is the count source the apps already write. +- LaunchPad reads the file of every app that is enabled for the user and offers the list at `GET /api/attention/sources`. +- A new widget, "First today" (`attention`), runs each count in the browser as the signed-in user, ranks the items that need attention and shows them with a link into the owning app. +- The link's query is built from the same filter as the count, so the number and the list it opens cannot drift. +- An app that is not installed, or declares nothing, does not appear. A count that fails is shown as failed. It is never shown as "nothing to do". +- The shipped "Mijn werkdag" template (version 2) puts the widget at the top, compulsory. + +## Capabilities + +### New capabilities + +- `attention-feed`: the declaration, the sources endpoint, the ranking and the widget. + +### Modified capabilities + +- `admin-templates`: REQ-TMPL-018, the shipped template gains the widget. + +## What each app adds (not in this change) + +One file, `appinfo/attention.json`, and a test that its filter equals the filter of the app's own "First today" card. Nothing else. The four files, written from what the apps ship today, are in `design.md`. + +## Impact + +- `lib/Service/AttentionSourceService.php`, `lib/Controller/AttentionController.php`, `appinfo/routes.php` (new) +- `src/components/Widgets/Renderers/AttentionWidget.vue`, `AttentionWidgetForm.vue`, `src/services/attentionFeed.js` (new), `src/constants/widgetRegistry.js`, `lib/widget-types.json` +- `data/templates/mijn-werkdag.json` (version 2) +- No database migration. No change to an app other than LaunchPad. + +## Out of scope + +- One line per object ("Parkeervergunningen binnenstad: the term ends today"), as the design draws it. Version 1 shows one line per declared item with its count ("3 of your cases are past their deadline"). A per-object line needs a title field and a detail link per schema; the declaration leaves room for it (`version`). +- Items that are not an OpenRegister count (for example unread mail). +- A personal order or hiding items. diff --git a/openspec/changes/archive/2026-11-17-cross-app-attention-feed/screens.md b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/screens.md new file mode 100644 index 000000000..795c8cb65 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag +- LpStart https://identity.conduction.nl/screens/board?id=esdoornveen/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=warmtepompacademie/LpStart diff --git a/openspec/changes/archive/2026-11-17-cross-app-attention-feed/specs/attention-feed/spec.md b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/specs/attention-feed/spec.md new file mode 100644 index 000000000..caee11aa8 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/specs/attention-feed/spec.md @@ -0,0 +1,173 @@ +# Delta for attention-feed: a new capability + +## ADDED Requirements + +### Requirement: REQ-ATT-001 An app declares its attention items in a file + +An app MAY ship `appinfo/attention.json`. LaunchPad MUST read that file for every app that is enabled for the signed-in user, and for no other app. LaunchPad MUST NOT require a PHP class, an interface or a registration call from the app. + +The file MUST be a JSON object with `version: 1` and `items`, a list of at most 10 items. Each item MUST have: + +- `id`: lower-case letters, digits and hyphens, unique within the file; +- `title`, `reason` and `action.label`: non-empty English source strings. `reason` MAY contain `{value}`, the count; +- `source.register` and `source.schema`: OpenRegister slugs; +- `source.filter`: optional, a FLAT object. A value is a string, number, boolean or a list of those. An operator is part of the key (`"deadline[lt]"`). A nested object as a value is invalid; +- `action.path`: a path inside the declaring app, starting with `/`, with no `..`, no `//`, no `?` and no `#`. + +Each item MAY have `severity` (`error`, `warning` or `info`, default `info`), `op` (`gt`, `gte`, `lt`, `lte`, `eq` or `neq`, default `gt`) and a numeric `value` (default `0`). + +LaunchPad MUST translate `title`, `reason` and `action.label` with the declaring app's own translations, in the user's language. + +A file that is not valid MUST NOT take the feed down. The app MUST be reported under `invalid` with a reason, its valid items MUST NOT be offered in part, and every other app MUST still be offered. + +#### Scenario: An app with a declaration is offered +- GIVEN dossiq is enabled for Pieter and ships `appinfo/attention.json` with the item `cases-past-deadline` +- WHEN Pieter's browser asks `GET /api/attention/sources` +- THEN the answer MUST hold one source with `appId: "dossiq"`, the app's display name, the item's id, its translated title, reason and action label, its source, `op: "gt"`, `value: 0` and `action.path: "/apps/dossiq/cases"` + +@e2e exclude Needs an app that ships the file; no app does until the app lanes add it, and this change touches LaunchPad only. Pinned by AttentionSourceServiceTest::testAnEnabledAppWithADeclarationIsOffered, which reads a real file from a real app folder. + +#### Scenario: An app that is not installed or declares nothing does not appear +- GIVEN pipelinq is not installed, and the Files app is enabled and ships no `appinfo/attention.json` +- WHEN the sources are collected +- THEN neither MUST appear under `sources` +- AND neither MUST appear under `invalid` + +@e2e exclude Pinned by AttentionSourceServiceTest::testAnAppWithoutTheFileDoesNotAppear. + +#### Scenario: An app that is disabled for this user does not appear +- GIVEN decidiq is enabled only for the group "bestuur" and Pieter is not in it +- WHEN Pieter's sources are collected +- THEN decidiq MUST NOT appear + +@e2e exclude Pinned by AttentionSourceServiceTest::testOnlyAppsEnabledForTheUserAreRead. + +#### Scenario: A broken declaration is reported and the others still work +- GIVEN dossiq ships a valid file and learniq ships a file whose filter nests an operator (`"deadline": {"lt": "@today"}`) +- WHEN the sources are collected +- THEN dossiq's item MUST be under `sources` +- AND learniq MUST be under `invalid` with a reason that names the item and the filter key +- AND no learniq item MUST be under `sources` + +@e2e exclude Pinned by AttentionSourceServiceTest::testABrokenDeclarationIsReportedAndTheOthersStillWork and ::testEveryRuleOfTheDeclarationIsChecked. + +#### Scenario: A link cannot leave the declaring app +- GIVEN an app declares `action.path: "/../settings/admin"` or `"//evil.example/x"` +- WHEN the sources are collected +- THEN the app MUST be reported under `invalid` + +@e2e exclude Pinned by AttentionSourceServiceTest::testEveryRuleOfTheDeclarationIsChecked. + +### Requirement: REQ-ATT-002 The sources endpoint + +`GET /api/attention/sources` MUST return `{ userId, sources: [...], invalid: [...] }` for the signed-in user. `userId` is the user's own id, which the widget writes where a filter says `@me`. It MUST require a signed-in user and MUST NOT require an administrator. It MUST NOT run any count and MUST NOT return any object data: it returns what the apps declared. + +#### Scenario: A signed-in employee gets the sources +- GIVEN Pieter is signed in +- WHEN his browser asks `GET /api/attention/sources` +- THEN the answer MUST be HTTP 200 with `userId: "pieter"`, `sources` and `invalid` + +@e2e exclude Pinned by AttentionControllerTest::testASignedInUserGetsTheSources. Not run in a browser. + +#### Scenario: Nobody signed in +- WHEN a request without a session asks `GET /api/attention/sources` +- THEN the answer MUST be HTTP 401 + +@e2e exclude Pinned by AttentionControllerTest::testNobodySignedInGets401. + +### Requirement: REQ-ATT-003 The count and the link come from one filter + +For each source the widget MUST ask OpenRegister, as the signed-in user, for `/apps/openregister/api/objects/{register}/{schema}` with the source's filter and `_limit=1`, and MUST read `total` as the count. + +Before the count is asked, the widget MUST resolve these tokens in filter values: `@me`, `@now`, `@today`, `@today+Nd`, `@today-Nd`, `@monthStart`, `@quarterStart` and `@yearStart`. A value that starts with `@` and is none of these MUST fail that source (REQ-ATT-005). It MUST NOT be sent as it is. + +The link into the app MUST be the declared path with the SAME filter as its query string, tokens not resolved, so the app's list resolves them as it does for its own links. A list value MUST be written as repeated `key[]` parameters in both. + +#### Scenario: The number and the list use the same filter +- GIVEN the dossiq source with the filter `assignee: "@me"`, `isFinalStatus: false`, `"deadline[lt]": "@today+1d"` +- WHEN the widget builds the count request and the link on 5 October 2026 for the user `pieter` +- THEN the count request's query MUST be `assignee=pieter&isFinalStatus=false&deadline[lt]=2026-10-06&_limit=1` +- AND the link MUST be `/apps/dossiq/cases?assignee=@me&isFinalStatus=false&deadline[lt]=@today%2B1d` (the `+` is written as `%2B`, or the app would read a space) +- AND the link's parameter names MUST equal the count's parameter names without `_limit` + +@e2e exclude Pinned by attentionFeed.spec.js "the count and the link carry the same filter". Not run in a browser. + +#### Scenario: An unknown token fails the source +- GIVEN a source whose filter holds `owner: "@manager"` +- WHEN the widget prepares the count +- THEN no request MUST be sent for that source +- AND the source MUST be shown as failed + +@e2e exclude Pinned by attentionFeed.spec.js "an unknown token fails the source and sends nothing". + +### Requirement: REQ-ATT-004 Merging and ranking + +A source needs attention when its count compared with `value` by `op` is true. The widget MUST show the sources that need attention as one list across apps, ordered by severity (`error`, `warning`, `info`), then by the higher count, then by app name, then by item id. + +Each line MUST show the title, the reason with the count filled in, the app's name and a link with the action label. The widget MUST show at most `limit` lines (widget setting, 1 to 10, default 5) and MUST say how many more there are. + +#### Scenario: Items from three apps in one list +- GIVEN dossiq reports 3 (error), pipelinq reports 5 (error) and decidiq reports 2 (warning) +- WHEN the widget renders +- THEN the lines MUST be pipelinq, dossiq, decidiq, in that order +- AND the dossiq line MUST read "3 of your cases are past their deadline or end today." and link to dossiq + +@e2e exclude Needs three apps that ship the file. Pinned by attentionFeed.spec.js "ranks by severity, then count, then app" and AttentionWidget.spec.js "shows one line per item that needs attention". + +#### Scenario: A source that does not need attention is left out +- GIVEN learniq's count is 0 and its item says `op: "gt"`, `value: 0` +- WHEN the widget renders +- THEN no learniq line MUST be shown + +@e2e exclude Pinned by AttentionWidget.spec.js "leaves out a source that does not need attention". + +### Requirement: REQ-ATT-005 A failure is shown as a failure + +A source fails when its count request does not answer with HTTP 2xx, when the answer has no numeric `total`, when the network fails, or when a token is unknown (REQ-ATT-003). A failed source MUST be named in a line under the list ("Could not check: {apps}"). An invalid declaration (REQ-ATT-001) MUST be named there too. + +The widget MUST show "Nothing needs your attention right now." only when every source was checked and none needs attention. When any source failed, it MUST NOT show that sentence. + +When no app declares anything, the widget MUST say so ("None of your apps reports attention items yet."). When the sources endpoint itself fails, the widget MUST say the list could not be loaded. + +One failing source MUST NOT stop the other sources from being shown. + +#### Scenario: One app fails and the others are clear +- GIVEN dossiq's count answers HTTP 500 and pipelinq's count is 0 +- WHEN the widget renders +- THEN it MUST show "Could not check: dossiq" +- AND it MUST NOT show "Nothing needs your attention right now." + +@e2e exclude Staging a failing OpenRegister answer needs request interception against an app that ships the file. Pinned by AttentionWidget.spec.js "a failed source is named and never reads as nothing to do". + +#### Scenario: One app fails and another needs attention +- GIVEN dossiq's count fails and pipelinq's count is 5 +- WHEN the widget renders +- THEN the pipelinq line MUST be shown +- AND "Could not check: dossiq" MUST be shown under it + +@e2e exclude Pinned by AttentionWidget.spec.js "a failed source does not hide the others". + +#### Scenario: Everything checked, nothing to do +- GIVEN two sources, both checked, both with count 0 +- WHEN the widget renders +- THEN it MUST show "Nothing needs your attention right now." + +@e2e exclude Pinned by AttentionWidget.spec.js "says nothing needs attention only when every source was checked". + +#### Scenario: No app declares anything +- GIVEN the sources endpoint answers with no sources and no invalid declarations +- WHEN the widget renders +- THEN it MUST show "None of your apps reports attention items yet." + +@e2e exclude Pinned by AttentionWidget.spec.js "says so when no app declares anything". This is also what the widget shows on an instance today, until an app ships the file; that was not looked at in a browser. + +### Requirement: REQ-ATT-006 The widget type + +LaunchPad MUST offer the widget as type `attention`, named "First today", in the add-widget picker. Its only setting is `limit`. It MUST be on LaunchPad's widget type list (`lib/widget-types.json`), so templates, showcases and imports can place it. The line colour MUST come from Nextcloud's theme variables, and severity MUST also be said in text for assistive technology, not by colour alone. + +#### Scenario: The widget can be added +- GIVEN an employee edits a dashboard +- WHEN they open the add-widget picker +- THEN "First today" MUST be offered + +@e2e exclude Not run in a browser. Pinned by widgetRegistry.completeness.spec.js, which holds the registry equal to lib/widget-types.json. diff --git a/openspec/changes/archive/2026-11-17-cross-app-attention-feed/tasks.md b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/tasks.md new file mode 100644 index 000000000..8a95f38df --- /dev/null +++ b/openspec/changes/archive/2026-11-17-cross-app-attention-feed/tasks.md @@ -0,0 +1,9 @@ +# Tasks: cross-app-attention-feed + +- [x] 1. `AttentionSourceService`: read and check `appinfo/attention.json` of every app enabled for the user, translate with the app's own strings, report invalid declarations. Verify: PHPUnit with real files in a temp app folder. +- [x] 2. `GET /api/attention/sources`, signed-in users only. Verify: controller test. +- [x] 3. `src/services/attentionFeed.js`: resolve tokens, build the count request and the link from one filter, compare, rank. Verify: Vitest, including that the count's query and the link's query are the same filter. +- [x] 4. `AttentionWidget.vue` and its form, registered as `attention`, added to `lib/widget-types.json`. Verify: Vitest for the four states (items, nothing, failed, none declared). +- [x] 5. `en` and `nl` strings. +- [x] 6. "Mijn werkdag" version 2 with the widget on top. Verify: `ShippedTemplateServiceTest`. +- [x] 7. Live check in a browser with at least one app carrying the file. Done 17 Nov 2026 on a live NC 34 rig with OpenRegister 2.1.47 and pipelinq 0.5.21 (which ships `appinfo/attention.json`): for a member of `sales` with one ticket in progress past its deadline, "Vandaag eerst" showed "1 thing from all your apps that needs attention today", "Tickets past their deadline" with the reason and "Open these tickets". The count asked `assignee=werker&status=in_progress&slaDeadline[lt]=2026-11-18&_limit=1`, the link was `/apps/pipelinq/tickets?assignee=@me&status=in_progress&slaDeadline[lt]=@today%2B1d` and opens. Without pipelinq it read "None of your apps reports attention items yet.", and with the ticket out of the member's reach "Nothing needs your attention right now." diff --git a/openspec/changes/engagement-communities/.openspec.yaml b/openspec/changes/archive/2026-11-17-engagement-activity-digest/.openspec.yaml similarity index 100% rename from openspec/changes/engagement-communities/.openspec.yaml rename to openspec/changes/archive/2026-11-17-engagement-activity-digest/.openspec.yaml diff --git a/openspec/changes/engagement-activity-digest/design.md b/openspec/changes/archive/2026-11-17-engagement-activity-digest/design.md similarity index 100% rename from openspec/changes/engagement-activity-digest/design.md rename to openspec/changes/archive/2026-11-17-engagement-activity-digest/design.md diff --git a/openspec/changes/engagement-activity-digest/proposal.md b/openspec/changes/archive/2026-11-17-engagement-activity-digest/proposal.md similarity index 100% rename from openspec/changes/engagement-activity-digest/proposal.md rename to openspec/changes/archive/2026-11-17-engagement-activity-digest/proposal.md diff --git a/openspec/changes/archive/2026-11-17-engagement-activity-digest/screens.md b/openspec/changes/archive/2026-11-17-engagement-activity-digest/screens.md new file mode 100644 index 000000000..b7a1793e2 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-engagement-activity-digest/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpPersoonlijk https://identity.conduction.nl/screens/board?id=launchpad/LpPersoonlijk diff --git a/openspec/changes/engagement-activity-digest/specs/activity-feed-integration/spec.md b/openspec/changes/archive/2026-11-17-engagement-activity-digest/specs/activity-feed-integration/spec.md similarity index 100% rename from openspec/changes/engagement-activity-digest/specs/activity-feed-integration/spec.md rename to openspec/changes/archive/2026-11-17-engagement-activity-digest/specs/activity-feed-integration/spec.md diff --git a/openspec/changes/archive/2026-11-17-engagement-activity-digest/tasks.md b/openspec/changes/archive/2026-11-17-engagement-activity-digest/tasks.md new file mode 100644 index 000000000..06ef04b2e --- /dev/null +++ b/openspec/changes/archive/2026-11-17-engagement-activity-digest/tasks.md @@ -0,0 +1,8 @@ +# Tasks: engagement-activity-digest + +- [x] 1. Add four `ActivitySettings` classes under `lib/Activity/Settings/` with the defaults in D1 and register them in `appinfo/info.xml`. Verify: PHPUnit per class and app-info validation. Done 9 Oct: `LaunchPadActivitySetting` base plus `Dashboard{Shared,Published,Updated,Acknowledged}Setting`; `tests/Unit/Activity/Settings/ActivitySettingsTest.php` (red first: `build-round/digest-red.log`) pins identifiers, group, defaults and the info.xml registration; `appinfo/info.xml` validates against Nextcloud's `resources/app-info.xsd` (settings precede providers, as the schema orders them). +- [x] 2. Emit `dashboard_shared` from `DashboardShareService` on share creation to the resolved recipients. Verify: PHPUnit with a mocked publisher. +- [x] 3. Emit `dashboard_published` from `DashboardService` on publication, including the first surfacing of a scheduled dashboard, once. Verify: PHPUnit. +- [x] 4. Emit `dashboard_updated` for shared and group dashboards through `DebounceHelper`, once per dashboard per 24 hours. Verify: PHPUnit with a fixed clock. +- [x] 5. Integration check: with daily batching, a share queues an activity mail row for the recipient. Verify: an integration test or a documented manual run against the dev instance. (not run: needs the live instance. Recipe: enable the activity app, set user B's activity mail to daily, as user A share a dashboard with B, then `SELECT amq_type, amq_affecteduser FROM oc_activity_mq WHERE amq_appid = 'launchpad'` shows one `dashboard_shared` row for B; edit the dashboard and confirm no `dashboard_updated` row is queued.) Done 17 Nov 2026 as a documented manual run on a throwaway NC 34 instance: with the recipient's activity mail set to daily (`notify_setting_batchtime` 86400) and an email address on the account, an admin's share of a dashboard queued one `dashboard_shared` row for the recipient in `oc_activity_mq` with `amq_latest_send` a day ahead, and renaming the dashboard afterwards queued no `dashboard_updated` row (it reached the activity stream only). +- [x] 6. Add `nl` and `en` strings for the setting labels, fold the delta into `openspec/specs/activity-feed-integration/spec.md` on archive, and set e-digest to `built` in the parity matrix with evidence lines. (strings done 9 Oct in all 37 shipped locales; e-digest moved to `building`; the archive and the move to `built` wait for task 5) Done on archive 17 Nov 2026: the delta is folded into `openspec/specs/activity-feed-integration/spec.md` and e-digest is `built` with evidence lines. diff --git a/openspec/changes/governance-rest-api-reference/.openspec.yaml b/openspec/changes/archive/2026-11-17-engagement-announcements/.openspec.yaml similarity index 100% rename from openspec/changes/governance-rest-api-reference/.openspec.yaml rename to openspec/changes/archive/2026-11-17-engagement-announcements/.openspec.yaml diff --git a/openspec/changes/engagement-announcements/design.md b/openspec/changes/archive/2026-11-17-engagement-announcements/design.md similarity index 100% rename from openspec/changes/engagement-announcements/design.md rename to openspec/changes/archive/2026-11-17-engagement-announcements/design.md diff --git a/openspec/changes/engagement-announcements/proposal.md b/openspec/changes/archive/2026-11-17-engagement-announcements/proposal.md similarity index 100% rename from openspec/changes/engagement-announcements/proposal.md rename to openspec/changes/archive/2026-11-17-engagement-announcements/proposal.md diff --git a/openspec/changes/archive/2026-11-17-engagement-announcements/screens.md b/openspec/changes/archive/2026-11-17-engagement-announcements/screens.md new file mode 100644 index 000000000..f8c79e334 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-engagement-announcements/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet +- LpAankondiging https://identity.conduction.nl/screens/board?id=launchpad/LpAankondiging diff --git a/openspec/changes/engagement-announcements/specs/announcements/spec.md b/openspec/changes/archive/2026-11-17-engagement-announcements/specs/announcements/spec.md similarity index 100% rename from openspec/changes/engagement-announcements/specs/announcements/spec.md rename to openspec/changes/archive/2026-11-17-engagement-announcements/specs/announcements/spec.md diff --git a/openspec/changes/archive/2026-11-17-engagement-announcements/tasks.md b/openspec/changes/archive/2026-11-17-engagement-announcements/tasks.md new file mode 100644 index 000000000..2e21ed4e7 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-engagement-announcements/tasks.md @@ -0,0 +1,27 @@ +# Tasks: engagement-announcements + +## Backend + +- [x] 1. Add the two tables in one migration with builders, entities and mappers (including `notified_at`). Verify: migration test. +- [x] 2. Seed `announcement.manage`, `announcement.read`, `announcement.follow`, `announcement.comment` and add the `announcement_editor_groups` admin setting. Verify: action-matrix test. +- [x] 3. Implement `AnnouncementService` (create, update, publish, visibleTo, drafts for authors, notice end time required, reach count). Verify: PHPUnit. +- [x] 4. Add `AnnouncementController` routes for list, get, create, update, publish, delete, follow and unfollow, each with the action check and no IDOR (visibility checked per id). Verify: PHPUnit and route-reachability. +- [x] 5. Wire likes and comments through `ICommentsManager` with object type `launchpad_announcement` and the access check. Verify: PHPUnit with the comments manager. +- [x] 6. Add `announcement_published` to `lib/Notification/Notifier.php` and `AnnouncementNotifyJob` to `appinfo/info.xml`. Verify: PHPUnit that followers are notified once. + +## Frontend + +- [x] 7. Add the `announcements` widget to `src/constants/widgetRegistry.js` with card, category filter, like and comment counts. Verify: Vitest. +- [x] 8. Build the announcement editor modal with the preview step, reach count and "Preview as". Verify: Vitest and an axe check. +- [x] 9. Add the notice banner region to `src/views/WorkspaceApp.vue` with dismiss for dismissible notices. Verify: Vitest. +- [x] 10. Add follow and unfollow per category in the widget. Verify: Vitest. + +## Close + +- [x] 11. Add the three demo announcements. Verify: PHPUnit on the showcase. +- [x] 12. Playwright for the notice flow and a liked, commented news item. Done 17 Nov 2026: `tests/e2e/announcements.spec.ts`, 3 passed on a live NC 34 rig (notice without an end time refused, warning banner without a close button, an info notice dismissed and gone after reload, a news item liked and commented, both counts after reload). +- [x] 13. Add `nl` and `en` strings, copy the spec to `openspec/specs/announcements/spec.md` on archive, and set e-announcements, d-news-preview and e-maintenance to `built` in the parity matrix with evidence lines. Done on archive 17 Nov 2026: the spec is `openspec/specs/announcements/spec.md`, and e-announcements, d-news-preview and e-maintenance point at it with the e2e evidence. + +Built: tasks 1 to 11. Backend: `AnnouncementTablesBuilder` and migration `Version002013Date20261114000000`, `Announcement`/`AnnouncementFollow` with their mappers, `AnnouncementService` (with "Preview as" through `reachesUser()`), `AnnouncementInput`, `AnnouncementFollowService`, `AnnouncementCommentService` (likes and comments through `ICommentsManager`, object type `launchpad_announcement`), `AnnouncementFollowNotifier` and `AnnouncementNotifyJob` (`announcement_published`, once per announcement through `notified_at`), `DemoAnnouncements` (seeded with the demo data), `AnnouncementController` with thirteen routes, the four `announcement.*` actions, and `announcementEditorGroups` in the admin settings API. Frontend: the `announcements` widget and its form, `AnnouncementCard`, `NoticeBanner` and `NoticeBannerRegion` above the Workspace grid, `AnnouncementEditorModal` with the preview step, and the editor groups picker in Beheer > Sharing. + +Open: task 12 (Playwright needs a live instance), the axe check of task 8 (no axe tooling in the repository), and of task 13 the strings of the 34 locales besides `en` and `nl` and the copy of the spec on archive. The `en` and `nl` strings and the parity matrix rows are done. diff --git a/openspec/changes/integrations-live-tile-lists/.openspec.yaml b/openspec/changes/archive/2026-11-17-engagement-communities/.openspec.yaml similarity index 100% rename from openspec/changes/integrations-live-tile-lists/.openspec.yaml rename to openspec/changes/archive/2026-11-17-engagement-communities/.openspec.yaml diff --git a/openspec/changes/engagement-communities/design.md b/openspec/changes/archive/2026-11-17-engagement-communities/design.md similarity index 100% rename from openspec/changes/engagement-communities/design.md rename to openspec/changes/archive/2026-11-17-engagement-communities/design.md diff --git a/openspec/changes/engagement-communities/proposal.md b/openspec/changes/archive/2026-11-17-engagement-communities/proposal.md similarity index 100% rename from openspec/changes/engagement-communities/proposal.md rename to openspec/changes/archive/2026-11-17-engagement-communities/proposal.md diff --git a/openspec/changes/archive/2026-11-17-engagement-communities/screens.md b/openspec/changes/archive/2026-11-17-engagement-communities/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/changes/archive/2026-11-17-engagement-communities/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/changes/engagement-communities/specs/communities-widget/spec.md b/openspec/changes/archive/2026-11-17-engagement-communities/specs/communities-widget/spec.md similarity index 100% rename from openspec/changes/engagement-communities/specs/communities-widget/spec.md rename to openspec/changes/archive/2026-11-17-engagement-communities/specs/communities-widget/spec.md diff --git a/openspec/changes/archive/2026-11-17-engagement-communities/tasks.md b/openspec/changes/archive/2026-11-17-engagement-communities/tasks.md new file mode 100644 index 000000000..8a7061467 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-engagement-communities/tasks.md @@ -0,0 +1,8 @@ +# Tasks: engagement-communities + +- [x] 1. Add `pinned_communities` to `lib/Db/AdminSettingKey.php` with token validation, and `talkEnabled` plus the pinned list to `lib/Service/InitialStateBuilder.php`. Verify: PHPUnit and the initial-state contract test. +- [x] 2. Build the `communities` renderer over Talk's listed-room, room and join endpoints, with pinned first, joined marks and the empty state. Verify: Vitest with mocked Talk. +- [x] 3. Register the widget and its form (title, show only pinned) in `src/constants/widgetRegistry.js` and the manifest. Verify: manifest check and Vitest. +- [x] 4. Add the pinned-communities admin section. Verify: Vitest. +- [x] 5. Playwright with Talk enabled: join an open conversation from the widget. Done 17 Nov 2026: `tests/e2e/communities-widget.spec.ts` passed on a live NC 34 with Talk 24.0.8. It was red first: Join posted to `participants/self`, which Talk answers only for leaving (405), so nobody could join; fixed to Talk's join endpoint. The pinned mark was near-invisible (a text colour meant for primary backgrounds) and is now readable. +- [x] 6. Add `nl` and `en` strings, copy the spec to `openspec/specs/communities-widget/spec.md` on archive, and set e-communities to `built` in the parity matrix with evidence lines. Done on archive 17 Nov 2026: the spec is `openspec/specs/communities-widget/spec.md` and e-communities carries the e2e evidence. diff --git a/openspec/changes/keyboard-accessible-widget-repositioning/.openspec.yaml b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/.openspec.yaml similarity index 100% rename from openspec/changes/keyboard-accessible-widget-repositioning/.openspec.yaml rename to openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/.openspec.yaml diff --git a/openspec/changes/fix-l10n-domain-mismatch-mydash-calls/proposal.md b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/proposal.md similarity index 100% rename from openspec/changes/fix-l10n-domain-mismatch-mydash-calls/proposal.md rename to openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/proposal.md diff --git a/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/screens.md b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/screens.md new file mode 100644 index 000000000..7cf496893 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: engineering: translation domain, nothing a user operates diff --git a/openspec/changes/fix-l10n-domain-mismatch-mydash-calls/specs/i18n-translation-domain/spec.md b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/specs/i18n-translation-domain/spec.md similarity index 100% rename from openspec/changes/fix-l10n-domain-mismatch-mydash-calls/specs/i18n-translation-domain/spec.md rename to openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/specs/i18n-translation-domain/spec.md diff --git a/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/tasks.md b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/tasks.md new file mode 100644 index 000000000..044dd2196 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls/tasks.md @@ -0,0 +1,77 @@ +# Tasks — fix-l10n-domain-mismatch-mydash-calls + +## Verify scope + +- [x] Task 1: Re-run `grep -rnoP "(?<![A-Za-z_])t\('mydash'" src --include=*.vue --include=*.js` and + `grep -rnoP "(?<![A-Za-z_])n\('mydash'" src --include=*.vue --include=*.js` + against current HEAD to confirm the exact call-site count and file list + before editing (167 calls / 20 files at time of writing; do not trust a + stale count if other work has landed in the meantime). Rerun 9 Oct 2026 on + build/openspecs-1: 0 calls. + +## Fix call sites + +- [x] Task 2: In each of the 20 affected files, change every + `t('mydash', …)` (and `n('mydash', …)` if any exist) call to + `t('launchpad', …)` / `n('launchpad', …)`. Do this as a literal string + substitution only — do not alter the translated text, placeholders, or + argument order. Done in 006fa4f5 and 3c346d62 (`src/components/DashboardConfigModal.vue` + has since moved to `src/modals/`). + - `src/dialogs/RolePermissionDeleteDialog.vue` (4 calls) + - `src/dialogs/PublicSharePasswordDialog.vue` (4 calls) + - `src/components/admin/AdminDemoData.vue` (8 calls) + - `src/views/Views.vue` (2 calls) + - `src/views/DashboardPublicShareView.vue` (11 calls) + - `src/dialogs/RoleLayoutDefaultEditorDialog.vue` (16 calls) + - `src/dialogs/RoleLayoutDefaultDeleteDialog.vue` (4 calls) + - `src/components/DashboardConfigModal.vue` (5 calls) + - `src/components/admin/RoleLayoutDefaultsSection.vue` (9 calls) + - `src/components/admin/BeheerTabs.vue` (1 call) + - `src/components/admin/OrgNavigationEditorRow.vue` (2 calls) + - `src/components/admin/PrometheusMetricsPanel.vue` (3 calls) + - `src/components/admin/ConditionalVisibilityOverview.vue` (10 calls) + - `src/components/admin/LegacyWidgetBridgeToggle.vue` (3 calls) + - `src/components/admin/tabs/TemplatesPage.vue` (25 calls) + - `src/components/admin/HealthPanel.vue` (4 calls) + - `src/components/admin/DashboardSharingPolicy.vue` (8 calls) + - `src/components/Widgets/VisibilityRulesModal.vue` (27 calls) + - `src/components/admin/AdminSettings.vue` (12 calls) + - `src/components/Widgets/WidgetContextMenu.vue` (1 call) +- [x] Task 3: Confirm every English source string used in these 20 files + already exists as a key in `l10n/en.json` under the `"launchpad"` + domain content (spot-check a sample per file) — if any string is + genuinely new/missing from the bundle, flag it separately rather than + silently shipping an unresolvable key. Checked 9 Oct: 202 literal calls in + these files, 15 strings have no catalogue key. Flagged separately: repo-wide + 320 `t('launchpad', …)` strings have no catalogue key (list in the lane's + `build-round/l10n-missing-keys.txt`); that is i18n debt for its own change, + not part of this domain fix. + +## Prevent regression + +- [x] Task 4: Add a lint guard (new script under `scripts/`, e.g. + `scripts/lint-translation-domain.js`, wired into the existing + `npm run lint` chain alongside `lint:initial-state`) that scans `src/` + for `t('<literal>'` / `n('<literal>'` calls where `<literal>` is not + `'launchpad'`, and fails with file:line output if any are found. + `scripts/lint-translation-domain.js` exists. +- [x] Task 5: Add the new script to `package.json`'s `lint` script + (`"lint": "eslint src && npm run check:manifest && npm run lint:initial-state && npm run lint:translation-domain"`). + `package.json` `lint` ends with `npm run lint:translation-domain`. + +## Verification + +- [x] Task 6: Run `npm run lint` and confirm the new guard passes with + zero violations after Task 2's fixes. 9 Oct: `node scripts/lint-translation-domain.js` + prints OK, exit 0. +- [x] Task 7: Manually verify in a Dutch-locale (`nl`) Nextcloud session: Done 17 Nov 2026 on a live NC 34 rig as an `nl` administrator: the Operations tab heading reads "Status" with "Gezond"/"Verminderd", and the widget context menu reads "Zichtbaarheidsregels…". + open the admin Health panel (`HealthPanel.vue`) and the widget + right-click context menu (`WidgetContextMenu.vue`) and confirm the + previously-English "Health"/"Healthy"/"Degraded" and "Visibility + rules…" strings now render in Dutch. (not run: needs the live instance; the + `nl` catalogue carries "Health", "Healthy", "Degraded" and "Visibility rules…") +- [x] Task 8: Re-run the Vitest suite (`npm run test`) — component tests + that snapshot or assert on rendered English text for these components + must still pass since the English fallback text is unchanged for the + `en` locale; only non-English locales change behaviour. + 14 Nov 2026 on development: `npm run test` 238 files, 2208 tests passed; `node scripts/lint-translation-domain.js` OK; no `t('mydash'`/`n('mydash'` call left in `src/`. diff --git a/openspec/changes/integrations-office-tiles/.openspec.yaml b/openspec/changes/archive/2026-11-17-launcher-bookmark-import/.openspec.yaml similarity index 100% rename from openspec/changes/integrations-office-tiles/.openspec.yaml rename to openspec/changes/archive/2026-11-17-launcher-bookmark-import/.openspec.yaml diff --git a/openspec/changes/launcher-bookmark-import/design.md b/openspec/changes/archive/2026-11-17-launcher-bookmark-import/design.md similarity index 100% rename from openspec/changes/launcher-bookmark-import/design.md rename to openspec/changes/archive/2026-11-17-launcher-bookmark-import/design.md diff --git a/openspec/changes/launcher-bookmark-import/proposal.md b/openspec/changes/archive/2026-11-17-launcher-bookmark-import/proposal.md similarity index 100% rename from openspec/changes/launcher-bookmark-import/proposal.md rename to openspec/changes/archive/2026-11-17-launcher-bookmark-import/proposal.md diff --git a/openspec/changes/archive/2026-11-17-launcher-bookmark-import/screens.md b/openspec/changes/archive/2026-11-17-launcher-bookmark-import/screens.md new file mode 100644 index 000000000..c4cf8495f --- /dev/null +++ b/openspec/changes/archive/2026-11-17-launcher-bookmark-import/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpTegelToevoegen https://identity.conduction.nl/screens/board?id=launchpad/LpTegelToevoegen diff --git a/openspec/changes/launcher-bookmark-import/specs/tiles/spec.md b/openspec/changes/archive/2026-11-17-launcher-bookmark-import/specs/tiles/spec.md similarity index 100% rename from openspec/changes/launcher-bookmark-import/specs/tiles/spec.md rename to openspec/changes/archive/2026-11-17-launcher-bookmark-import/specs/tiles/spec.md diff --git a/openspec/changes/archive/2026-11-17-launcher-bookmark-import/tasks.md b/openspec/changes/archive/2026-11-17-launcher-bookmark-import/tasks.md new file mode 100644 index 000000000..24b2cc190 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-launcher-bookmark-import/tasks.md @@ -0,0 +1,9 @@ +# Tasks: launcher-bookmark-import + +- [x] 1. Seed `widget.import-bookmarks` as `["admin", "@all"]` in `lib/actions.seed.json` and add the route `POST /api/dashboard/{dashboardId}/tiles/import`. Verify: route-reachability and action-matrix tests. +- [x] 2. Implement `WidgetApiController::importBookmarks()` with the action check, `canAddWidget()` and 409 on quota. Verify: PHPUnit for 401, 403, 409 and 201. +- [x] 3. Add `PlacementService::importBookmarks()`: URL check per bookmark, one quota check, containers for folders, bottom-append, one transaction, a skipped list in the response. Verify: PHPUnit including rollback. +- [x] 4. Write the browser parser for the Netscape bookmark format with size and count limits. Verify: Vitest on Firefox, Chrome and Edge fixtures. +- [x] 5. Build `src/modals/BookmarkImportModal.vue` (file picker, folder and bookmark checkboxes, skipped list) and the "Import bookmarks" entry in the dashboard menu. Verify: Vitest and an axe check. +- [x] 6. Playwright: import a fixture, pick one folder, see its container at the bottom. Done 17 Nov 2026: `tests/e2e/bookmark-import.spec.ts`, passed on a live NC 34 rig (reached through More, All dashboards, the row menu; the script bookmark is skipped). +- [x] 7. Add `nl` and `en` strings, fold the delta into `openspec/specs/tiles/spec.md` on archive, and set d-import-bookmarks to `built` in the parity matrix with evidence lines. Done on archive 17 Nov 2026: the delta is folded into `openspec/specs/tiles/spec.md`, and d-import-bookmarks is `built` with evidence lines. diff --git a/openspec/changes/launcher-app-catalogue/.openspec.yaml b/openspec/changes/archive/2026-11-17-launcher-tile-sorting/.openspec.yaml similarity index 100% rename from openspec/changes/launcher-app-catalogue/.openspec.yaml rename to openspec/changes/archive/2026-11-17-launcher-tile-sorting/.openspec.yaml diff --git a/openspec/changes/launcher-tile-sorting/design.md b/openspec/changes/archive/2026-11-17-launcher-tile-sorting/design.md similarity index 100% rename from openspec/changes/launcher-tile-sorting/design.md rename to openspec/changes/archive/2026-11-17-launcher-tile-sorting/design.md diff --git a/openspec/changes/launcher-tile-sorting/proposal.md b/openspec/changes/archive/2026-11-17-launcher-tile-sorting/proposal.md similarity index 100% rename from openspec/changes/launcher-tile-sorting/proposal.md rename to openspec/changes/archive/2026-11-17-launcher-tile-sorting/proposal.md diff --git a/openspec/changes/archive/2026-11-17-launcher-tile-sorting/screens.md b/openspec/changes/archive/2026-11-17-launcher-tile-sorting/screens.md new file mode 100644 index 000000000..ae2025be1 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-launcher-tile-sorting/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpTegelBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpTegelBewerken diff --git a/openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md b/openspec/changes/archive/2026-11-17-launcher-tile-sorting/specs/container-widget/spec.md similarity index 100% rename from openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md rename to openspec/changes/archive/2026-11-17-launcher-tile-sorting/specs/container-widget/spec.md diff --git a/openspec/changes/archive/2026-11-17-launcher-tile-sorting/tasks.md b/openspec/changes/archive/2026-11-17-launcher-tile-sorting/tasks.md new file mode 100644 index 000000000..7cf95b750 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-launcher-tile-sorting/tasks.md @@ -0,0 +1,13 @@ +# Tasks: launcher-tile-sorting + +- [x] 1. Add `ContainerWidgetForm.vue` with the three communal fields plus "Sort tiles", and register it in `FORM_OVERRIDES` in `src/constants/widgetRegistry.js`. Verify: Vitest on the form. + - `src/components/Widgets/Renderers/ContainerWidgetForm.vue` wraps the communal `CnContainerWidgetForm` and adds the "Sort tiles" select (with an input label); registered in `FORM_OVERRIDES`. Vitest: `ContainerWidgetForm.spec.js`. +- [x] 2. Keep local `{count, lastUsedAt}` per placement in `src/composables/useTileClickTracking.js`, storage failures caught. Verify: Vitest with storage available and blocked. + - `useTileClickTracking()` now also hands out `recordTileUse()`, which keeps `{count, lastUsedAt}` per placement under `launchpad.tileUse` (`src/utils/tileSort.js`), every storage access guarded. The container counts a click on any of its children, in view mode only, so tiles of every widget type count. Vitest: `src/utils/__tests__/tileSort.spec.js` with storage available, broken and blocked. +- [x] 3. Order and reflow children in view mode in `ContainerWidget.vue` for the five modes, with the tie rules and a once-per-load shuffle. Verify: Vitest per mode. + - `ContainerWidget.vue` shows `displayedChildren`: the stored layout in edit mode or by hand, otherwise sorted (`sortChildren`) and reflowed row by row (`reflowChildren`), sizes kept. A grid change is not persisted while a sorted view is shown. Random draws once per page load. Vitest: `tileSort.spec.js` per mode and `ContainerWidget.sort.spec.js`. +- [x] 4. Add "Forget my usage" to the container menu and the "Sorted by" accessible description. Verify: Vitest and an axe check. + - Done, with two notes. The container has no menu of its own, so "Forget my usage" is a tertiary button in its header, shown in view mode for most and last used. The grid is `aria-describedby` a visually hidden "Sorted by …" line. Vitest covers both; the axe check is still owed and needs the live page. +- [x] 5. Playwright: most used moves a clicked tile to the front after reload; "By hand" restores the stored layout. Done 17 Nov 2026: `tests/e2e/container-tile-sorting.spec.ts`, 2 passed on a live NC 34 rig. It seeds the container through the bookmark import, so the children carry no id, and it was red until `ContainerWidget` keyed such children by the container (they were never counted). +- [x] 6. Add `nl` and `en` strings, fold the delta into `openspec/specs/container-widget/spec.md` on archive, and set d-tile-sort and tile-most-used to `built` in the parity matrix with evidence lines. Done on archive 17 Nov 2026: the delta is folded into `openspec/specs/container-widget/spec.md`, and d-tile-sort and tile-most-used are `built` with evidence lines. + - Partly: the Dutch strings are in `l10n/nl.js` and `l10n/nl.json`, and English is the source. They are deliberately not added to `en.*`: the parity gate would then require all 36 locales. The other locales fall back to English. Folding the delta into the spec, and setting the parity rows to `built`, belong to archive and merge. diff --git a/openspec/changes/launchpad-manifest-tier-3/proposal.md b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/proposal.md similarity index 100% rename from openspec/changes/launchpad-manifest-tier-3/proposal.md rename to openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/proposal.md diff --git a/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/screens.md b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/screens.md new file mode 100644 index 000000000..d242ad21b --- /dev/null +++ b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: manifest declaration on existing screens diff --git a/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/specs/manifest-routing/spec.md b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/specs/manifest-routing/spec.md new file mode 100644 index 000000000..56b195777 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/specs/manifest-routing/spec.md @@ -0,0 +1,110 @@ +# Manifest routing + +## ADDED Requirements + +### Requirement: REQ-ROUTE-001 The route table is derived, not written + +The router MUST build its routes from `manifest.pages`, so a declared page is a +routed page by construction and the two cannot drift. + +The catch-all MUST use vue-router 4's named-parameter form +(`path: '/:pathMatch(.*)*'`). The bare `'*'` wildcard was removed in v4 and does +not warn — it simply never matches, and an unknown URL renders the shell with an +empty content area. + +#### Scenario: A declared page resolves + +- GIVEN `src/manifest.json` declares a page with a `route` +- WHEN a user navigates to that route +- THEN the router MUST match it +- AND the declared page type MUST render + +### Requirement: REQ-ROUTE-002 The router base accepts both URL forms + +Nextcloud serves an app under both `/apps/launchpad/…` and +`/index.php/apps/launchpad/…`. The router base MUST be read from the location, +falling back to `generateUrl`. A base that assumes one form makes every route on +the other miss, which presents as an empty content area rather than an error. + +#### Scenario: index.php form + +- GIVEN a visitor arrives on `/index.php/apps/launchpad/reports` +- THEN the Reports page MUST render + +### Requirement: REQ-ROUTE-003 A dashboard has an address + +`/dashboards/:id` MUST select that dashboard, so a dashboard can be linked, +bookmarked and reopened (`dashboard-deeplinking`). + +An absent or unknown id MUST be left alone: the dashboard store's own resolver +already picks a sensible active dashboard, and overriding it would make a bad +link empty the page instead of falling back. + +#### Scenario: Cold deep link + +- GIVEN a user opens `/dashboards/<id>` in a fresh browser +- THEN that dashboard MUST become the active one + +#### Scenario: Unknown id + +- GIVEN a user opens `/dashboards/does-not-exist` +- THEN the store's resolved dashboard MUST still render + +### Requirement: REQ-ROUTE-004 The shared chrome renders, with the workspace inside it + +The app MUST root on `CnAppRoot`, which renders `CnAppNav` from `manifest.menu` +— including ADR-114's four footer destinations — around a `router-view`. + +**This supersedes REQ-SHELL-001's chrome-slot clause.** That requirement had +`PageController` pass `'id-app-navigation' => null` to suppress Nextcloud's left +navigation panel, because the app rendered its own slide-in sidebar and nothing +else. `NcContent` allocates that panel for `CnAppNav`, so suppressing it would +leave the shared chrome with nowhere to render — an empty rail, not an error. +`PageController` MUST pass no chrome slot ids, as every other app in the fleet +does. + +The slide-in sidebar is unaffected: it lives inside the workspace view, not in +the chrome slot. + +#### Scenario: Both are present on the dashboard route + +- GIVEN a user opens `/` +- THEN `CnAppNav` MUST render +- AND `.workspace-shell` MUST render inside the content area + +### Requirement: REQ-ROUTE-005 One skip link + +The app MUST NOT write its own skip link. It had one because it did not root on +`NcContent` and so did not inherit Nextcloud's; `CnAppRoot` renders `NcContent`, +and two bypass links are worse than one. + +`#launchpad-main-content` MUST keep `tabindex="-1"`, which the quick-search Esc +contract needs independently of any link. + +#### Scenario: Nextcloud's skip link only + +- GIVEN a user opens LaunchPad's start page +- THEN exactly one "Skip to main content" link MUST be on the page +- AND `#launchpad-main-content` MUST carry `tabindex="-1"` + +@e2e exclude Checked in the live pass of 17 Nov 2026 on NC 34 (one link, tabindex -1); a single-count assertion in app-chrome would be the natural home. + +### Requirement: REQ-ROUTE-006 A declared page names a component that exists + +A `type: custom` page MUST name a component the registry resolves. + +`admin-settings` named `AdminSettingsPage`, which has never existed, and +`admin-templates-index` named `TemplatesPage`, which is a tab inside the +Nextcloud admin section rather than a page. Both MUST resolve to a redirect to +`/settings/admin/launchpad`, which is where that functionality lives — rendering +half an admin surface beside the real one would be worse than the dead links +they were. + +The redirect MUST render a real anchor as well as navigating, because a redirect +that only runs in `mounted` leaves a blank page for anyone whose navigation is +slow or blocked, and gives a keyboard user nothing to act on. + +#### Scenario: The admin menu entry is not a dead link + +- GIVEN a user activates the Admin settings entry +- THEN they MUST arrive at `/settings/admin/launchpad` diff --git a/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/tasks.md b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/tasks.md new file mode 100644 index 000000000..759ef3a8d --- /dev/null +++ b/openspec/changes/archive/2026-11-17-launchpad-manifest-tier-3/tasks.md @@ -0,0 +1,51 @@ +# Tasks: LaunchPad manifest tier 3 + +## Decided + +- [x] `CnAppRoot` hosts the workspace, with the default `CnAppNav`. The org rail is org-wide API data, not an app menu, so it coexists rather than folding in. +- [x] One skip link: Nextcloud's. `#launchpad-main-content` keeps `tabindex="-1"` for the quick-search Esc contract. +- [x] Dashboard URLs in scope. + +## Routing + +- [x] `vue-router` (already a dependency, never used) created in `src/main.js` in **path** mode via `createWebHistory(routerBase())`. `routerBase()` reads the location and falls back to `generateUrl`, because Nextcloud serves the app under both `/apps/launchpad/…` and `/index.php/apps/launchpad/…` and a base that assumes one makes every route on the other miss — silently, as an empty content area. +- [x] `routesFromManifest()` derives the table from `manifest.pages`, so a declared page is a routed page by construction. +- [x] The v4 catch-all is `path: '/:pathMatch(.*)*'`. The bare `'*'` was removed in vue-router 4 and does not warn: it simply never matches. +- [x] `/` and `/dashboards/:id` render `WorkspaceApp`; `/store`, `/reports`, `/reports/dashboards`, `/features-roadmap`, `/flows` and `/flows/:id` render their declared page types. + +## Manifest + +- [x] `Workspace` declared at `/`. The app's home had no page at all. +- [x] `dashboard-detail` changed from `type: dashboard` to `custom` + `WorkspaceApp`. As a declarative `dashboard` page the renderer would have replaced this app's GridStack surface with the generic widget renderer. +- [x] `admin-settings` and `admin-templates-index` resolve to `AdminSettingsRedirect` (see the proposal's "Found while implementing"). +- [x] Every `type: custom` page carries a `_note`. + +## Shell + +- [x] `src/App.vue` roots on `CnAppRoot`, passing the live manifest, the registry and `defaultPageTypes`. +- [x] `src/registry.js` created — the v2 kind-tagged registry `CnPageRenderer` resolves `custom` components against. +- [x] The bespoke skip link and its `focusMainContent` handler are gone. +- [x] `OrgNavigationPanel` stays inside `WorkspaceApp`, unchanged. + +## Dashboard URLs + +- [x] `WorkspaceApp` watches `$route.params.id` (`immediate`, so a cold deep link selects on arrival) and calls `switchDashboard`. An absent or unknown id is left alone: the store's resolver already picks a sensible active dashboard, and overriding it would make a bad link empty the page instead of falling back. + +## Tests + +- [x] The four `test.fail()` markers are removed — this is the change that earns it. +- [x] The tripwire test is INVERTED, not deleted: it asserted the absence of `CnAppNav` and now asserts the shared chrome renders *with the workspace still inside it*. +- [x] A new test asserts a dashboard has an address. It asks the app which dashboards the user has rather than seeding an id, because a hardcoded id passes on one instance and nowhere else. + +## Verify + +- [x] `check:manifest`, `format`, `check:schema-l10n`, `lint` — this repo's CI checks — all pass. +- [x] `npm run build` compiles (webpack exit 0; the three warnings are the pre-existing bundle-size ones). +- [x] `vitest` WorkspaceApp: 14 passed. +- [x] `playwright test --list`: 9 tests collect. +- [x] The E2E leg on the `development` push run. It runs only there, so this is where routing is actually proven. (not run: the E2E job is `skipped` on every development push run, checked 9 Oct on Code Quality 37984033983 at f7b9192d; needs the live pass: open `/apps/launchpad/`, `/store`, `/reports`, `/features-roadmap`, `/flows` and `/dashboards/<id>` from a cold load on both `/apps/...` and `/index.php/apps/...`, each renders its page, and `tests/e2e/app-chrome.spec.ts` passes against the instance) Done 17 Nov 2026 in the live pass on a throwaway NC 34 instance: all six pages render on a cold load from both `/apps/launchpad/...` and `/index.php/apps/launchpad/...` with no page errors, and `tests/e2e/app-chrome.spec.ts` passes 10 of 10. That run found `/dashboards/<id>` landing on the stored dashboard in 5 of 6 cold loads (the store's first load answered after the switch and replaced it); fixed by letting the store open the address once its first load is done, after which 6 of 6 opened the right dashboard. The app-chrome test for it had skipped on every run (it read an id off the active-dashboard endpoint) and now seeds its own two dashboards. + +## Follow-up (not tasks of this change) + +- The org rail renders only inside `WorkspaceApp`, so it appears on the dashboard routes and not on `/store`, `/reports` or `/features-roadmap`. That matches today's behaviour exactly (there were no other routes), but it is now a visible inconsistency. Lifting it to the shell is its own change. +- `DashboardsReport` is `type: dashboard` — a declarative page over LaunchPad's own register. It was unroutable before, so it has never rendered; whether its widgets resolve is unproven until the E2E runs. diff --git a/openspec/changes/archive/2026-11-17-lpvandaag-start-page/proposal.md b/openspec/changes/archive/2026-11-17-lpvandaag-start-page/proposal.md new file mode 100644 index 000000000..4f0205146 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lpvandaag-start-page/proposal.md @@ -0,0 +1,42 @@ +--- +kind: code +depends_on: [shipped-template-update] +--- + +# LpVandaag: the start page in one screen + +## Why + +The board `launchpad/LpVandaag` draws the employee's start page in one screen. On 1440×900 and 1366×768 the page does +not scroll. The rows divide the height under the top bar, and the agenda, recent work and tiles scroll in their own +card. The apps are tiles, not a list of links. + +Beside "Startpagina aanpassen" the page had four more controls: a cog with the dashboard's actions, a ☰ dashboard +switcher, a … menu with the app's destinations and a Share button. Share was in the cog too, and the admin settings +were in the … menu twice. The board keeps one "Meer" menu. + +## What changes + +- `DashboardMoreMenu` replaces the four controls. Left: Dashboards (the switcher, the open one checked, "Alle + dashboards" for the full sidebar) and Instellingen (personal settings, admin settings once). Right: Dit dashboard + (the cog's actions with the cog's gates, Delete apart) and Launchpad (Store, Sjablonen, Rapporten, Flows, + Koppelingen, Documentatie, Functies en roadmap). Instellingen and Launchpad only show while the navigation panel is + left out, so nothing is offered twice. It is built on the library's `CnGroupedMenu`. +- A placement with `content.fillHeight: true` makes the dashboard fill the height (the library grid's `fillHeight`). + A placement with `content.fitRows: true` keeps its rows at its content's height. +- The attention widget takes `layout: "columns"` (one row of up to 4, 3 by default) and `title`, drawn with the count + beside it ("3 dingen uit al uw apps die vandaag aandacht vragen"). +- A widget card takes a header link from `content.headerLink` ("Open agenda"). +- Mijn werkdag version 5 follows the board: the header "Vandaag" with greeting, date and week under it and the + emblem; "Vandaag eerst" in one row of three; the counters in one row; the apps as tiles (`app-tiles`) on the left, + the agenda and "Verder waar u was" on the right. The "Mijn werk" and "Alle apps" labels and the links list go. + +## What an instance that installed version 4 sees + +The Templates page offers the update to version 5, and `occ launchpad:template:install mijn-werkdag --update` applies +it to the template and every member's copy (REQ-TMPL-020). + +## Depends on + +nextcloud-vue `lpvandaag-start-page`: `CnDashboardGrid` `fillHeight`, `CnHeaderWidget` `greetingLine`, +`CnAppTilesWidget`, `CnGroupedMenu`. diff --git a/openspec/changes/archive/2026-11-17-lpvandaag-start-page/specs/lpvandaag-start-page/spec.md b/openspec/changes/archive/2026-11-17-lpvandaag-start-page/specs/lpvandaag-start-page/spec.md new file mode 100644 index 000000000..e871cc7ad --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lpvandaag-start-page/specs/lpvandaag-start-page/spec.md @@ -0,0 +1,50 @@ +## ADDED Requirements + +### Requirement: The start page fits the screen + +A dashboard with a placement that sets `content.fillHeight: true` SHALL fill the height below the Nextcloud top bar on +a screen at least 960px wide, outside edit mode: the page SHALL NOT scroll, the rows of placements that set +`content.fitRows: true` SHALL take their content's height, the other rows SHALL share the rest, and a widget taller than +its share SHALL scroll inside its card. On a narrower screen the cards SHALL stack and the page MAY scroll. In edit mode +the grid SHALL be the editable grid as before. + +#### Scenario: Mijn werkdag at 1440×900 and 1366×768 + +- **GIVEN** Mijn werkdag version 5 +- **WHEN** an employee opens the start page at 1440×900 or 1366×768 +- **THEN** the page's scroll height equals its height, and the Apps, Agenda vandaag and Verder waar u was cards fill + the space under the counters + +### Requirement: One Meer menu holds the start page's actions + +The start page SHALL show "Startpagina aanpassen" and one "Meer" menu, and no other control for the dashboard's +actions. The menu SHALL hold, left, Dashboards (every dashboard the person sees, the open one checked, and "Alle +dashboards") and Instellingen (personal settings and, for an administrator only, the admin settings), and, right, Dit +dashboard (Bewerken, Instellingen, Widget toevoegen, Delen, Als standaard instellen, Versies, Inplannen, Publiceren or +Publicatie intrekken, Leesbevestigingen, and Verwijderen apart) and Launchpad (Store, Sjablonen, Rapporten, Flows, +Koppelingen, Documentatie, Functies en roadmap). Each action SHALL keep the gate it had in the dashboard cog menu. +Instellingen and Launchpad SHALL only show while the navigation panel is left out. No action SHALL appear twice. + +#### Scenario: An administrator opens Meer + +- **GIVEN** the start page without the navigation panel, for an administrator +- **WHEN** they open "Meer" +- **THEN** "Beheerinstellingen" appears once, and "Sjablonen" is in the Launchpad group + +#### Scenario: A member opens Meer on a shared dashboard + +- **GIVEN** a member on a dashboard shared with them +- **WHEN** they open "Meer" +- **THEN** Dit dashboard offers "Als standaard instellen", and neither Instellingen of the dashboard nor Verwijderen + +### Requirement: Vandaag eerst is one row + +The attention widget with `content.layout: "columns"` SHALL draw its items side by side in one row of +`content.columns` (1 to 4, 3 by default), each with its title, reason and app on the left and its action on the right. +With `content.title` it SHALL draw that heading with the number of items it shows beside it. On a narrow screen the +items SHALL stack. + +#### Scenario: Three things today + +- **GIVEN** three apps report something that needs attention +- **THEN** "Vandaag eerst" reads "3 dingen uit al uw apps die vandaag aandacht vragen" and shows the three side by side diff --git a/openspec/changes/archive/2026-11-17-lpvandaag-start-page/tasks.md b/openspec/changes/archive/2026-11-17-lpvandaag-start-page/tasks.md new file mode 100644 index 000000000..75a21e45b --- /dev/null +++ b/openspec/changes/archive/2026-11-17-lpvandaag-start-page/tasks.md @@ -0,0 +1,10 @@ +# Tasks: lpvandaag-start-page + +- [x] `DashboardMoreMenu` in place of the cog, the switcher button, the start page menu and the Share button +- [x] `startPageSections()` and `readChrome()` shared by `StartPageMenu` and the Meer menu; `isOwnedDashboard()` shared with the cog +- [x] The page fills its height when a placement asks (`fillHeight`, `fitRows`) +- [x] Attention widget `layout: "columns"` and `title` +- [x] Widget card header link from `content.headerLink` +- [x] Mijn werkdag version 5, `app-tiles` in `lib/widget-types.json` +- [x] Dutch for every new string +- [x] Unit tests diff --git a/openspec/changes/archive/2026-11-17-mijn-werkdag-template/.openspec.yaml b/openspec/changes/archive/2026-11-17-mijn-werkdag-template/.openspec.yaml new file mode 100644 index 000000000..a49a59f05 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-mijn-werkdag-template/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +skip_specs: true diff --git a/openspec/changes/archive/2026-11-17-mijn-werkdag-template/proposal.md b/openspec/changes/archive/2026-11-17-mijn-werkdag-template/proposal.md new file mode 100644 index 000000000..fed872f84 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-mijn-werkdag-template/proposal.md @@ -0,0 +1,72 @@ +--- +kind: code +depends_on: [] +--- + +# Ship a "Mijn werkdag" start page as a template an administrator can install, export and import + +## Why + +The Zuiddrecht design (`LpStart`, "launchpad: mijn werkdag") asks for a start page for a municipal employee, rolled out as an admin template per group with compulsory widgets. + +Measured on `development` at `da724518`: + +- Admin templates per group exist (`admin-templates`, REQ-TMPL-001..017). A template names its groups, can be the default, and its widgets carry `isCompulsory`. First access copies it, compulsory flags included. +- Export and import exist (`dashboard-export-import`): the `launchpad-export-v1` archive, `POST /api/admin/export|import`, `occ launchpad:export` and `occ launchpad:import`. +- No template ships with the app. The six bundled showcases install as view-only group dashboards, not as templates. +- A template did not survive the round trip. The importer dropped every `isCompulsory` flag (REQ-EXIM-004 said so for all dashboards), dropped the template's category and description, and made the importing administrator its owner. For a template whose point is its compulsory widgets, export then import produced a different template. +- The Templates page had no download for one template. The admin page exports the whole site only. + +## What changes + +- LaunchPad ships `data/templates/mijn-werkdag.json`: a versioned template definition, readable JSON in the shape an export writes. +- An administrator adds it from the Templates page ("Ready-made templates") or with `occ launchpad:template:install mijn-werkdag [--group=...] [--default] [--force]`. +- The install goes through the existing importer, so a shipped template and an uploaded archive take one path. +- An imported admin template keeps its compulsory flags, category and description, and has no owner. +- The Templates page gets a download per template. + +## Capabilities + +### Modified capabilities + +- `admin-templates`: adds REQ-TMPL-018, templates that ship with LaunchPad. +- `dashboard-export-import`: adds REQ-EXIM-012, an admin template travels with its definition. REQ-EXIM-004 names the exception and the import result names the dashboards it created. +- `cli-commands`: adds REQ-CLI-012, `launchpad:template:install`. + +## What the template holds, and what the design asks that it cannot hold yet + +The template must work as installed. A live check on 5 October 2026 showed that the first version did not: four of its widgets proxied Nextcloud dashboard widgets of dossiq and decidiq. Those widgets paint through their own script, which LaunchPad only loads when the legacy widget bridge is on (off by default, because it loads every app's widget script on the page). As installed they showed "This widget can only be shown on the Nextcloud dashboard itself." under their raw id. With the bridge on, the dossiq widgets rendered, still under their raw id, and listed cases that were not the signed-in user's. So the template now uses lists on the case register instead. + +| Design section | In the template | Widget | +| --- | --- | --- | +| Greeting | Header "Mijn werkdag" (compulsory) | `header` | +| Vandaag eerst | "Zaken over de termijn": the employee's cases whose deadline is today or earlier (compulsory) | `object-list` on dossiq `case` | +| Mijn werk, dossiq | "Mijn zaken": the employee's open cases, by deadline | `object-list` on dossiq `case` | +| Verder waar u was | Recent activity | `nc-widget` to `activity`, which has an items API | + +No widget that renders as installed exists yet for: + +- the greeting with the employee's name and the date. The header widget shows a fixed title. +- "Vandaag eerst" as one ranked list across apps. That is the next change, `cross-app-attention-feed`. +- the "Mijn werk" cards with one number per app. +- dossiq "my tasks". Tasks are not objects in the dossiq register, and the dossiq tasks widget needs the bridge. +- pipelinq "my tickets" and decidiq "to initial". pipelinq registers six Nextcloud widgets and decidiq one; none has both an items API and that content. +- "Agenda vandaag". LaunchPad's calendar widget shows "No calendar is selected yet" until each user picks a calendar, and the Calendar app's own widget is only there when that app is installed. +- "Van de organisatie". The news widget needs a feed address that differs per organisation. +- "Alle apps" as a row of pills. + +## Updating an instance that installed an earlier version + +There is no in-place update. `occ launchpad:template:install mijn-werkdag --force` adds the current version as a second template next to the first. The administrator then moves the groups to the new one and deletes the old one. Dashboards members already received keep their widgets: a copy does not follow a new template. Replacing the installed template's widgets in place and re-syncing the copies (REQ-RESYNC-001) is the missing piece and is not in this change. + +## Impact + +- `lib/Service/ShippedTemplateService.php`, `lib/Command/TemplateInstallCommand.php`, `lib/Controller/AdminShippedTemplateController.php` (new) +- `lib/Service/ImportService.php`, `lib/Service/PlacementPayloadHydrator.php` +- `src/components/admin/tabs/TemplatesPage.vue`, `src/services/api.js` +- No database migration. No change for dashboards that are not admin templates. + +## Out of scope + +- Updating an installed template when a later LaunchPad ships a higher `templateVersion`. The installed version is recorded so this can be built; today a forced install adds the new version next to the old one and the administrator re-syncs. +- Carrying a group dashboard's `groupId` through import. It is dropped today, for every group dashboard. Found while measuring, not changed here. diff --git a/openspec/changes/archive/2026-11-17-mijn-werkdag-template/screens.md b/openspec/changes/archive/2026-11-17-mijn-werkdag-template/screens.md new file mode 100644 index 000000000..795c8cb65 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-mijn-werkdag-template/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag +- LpStart https://identity.conduction.nl/screens/board?id=esdoornveen/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=warmtepompacademie/LpStart diff --git a/openspec/changes/archive/2026-11-17-mijn-werkdag-template/tasks.md b/openspec/changes/archive/2026-11-17-mijn-werkdag-template/tasks.md new file mode 100644 index 000000000..91d490285 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-mijn-werkdag-template/tasks.md @@ -0,0 +1,10 @@ +# Tasks: mijn-werkdag-template + +- [x] 1. Write `data/templates/mijn-werkdag.json` from widgets that exist. Verify: `ShippedTemplateServiceTest::testTheShippedDefinitionIsWellFormed`. +- [x] 2. Import carries an admin template's `isCompulsory`, category and description, and leaves it without an owner; the result names the created dashboards. Verify: `ImportServiceTest::testCompulsoryIsCarriedForATemplateOnly`. +- [x] 3. `ShippedTemplateService`: list and install through the importer, remember the install, name missing widgets. Verify: `ShippedTemplateServiceTest`. +- [x] 4. Round trip: shipped definition, install, `launchpad:export`, `launchpad:import` on a second store, same template. Verify: `ShippedTemplateServiceTest::testTheShippedTemplateSurvivesExportAndImport`. +- [x] 5. `occ launchpad:template:install`, registered in `appinfo/info.xml`. Verify: `TemplateInstallCommandTest`. +- [x] 6. `GET /api/admin/templates/shipped` and `POST /api/admin/templates/shipped/{id}/install`. Verify: `AdminShippedTemplateControllerTest`. +- [x] 7. Templates page: ready-made templates section and a download per template, `en` and `nl` strings. Verify: `TemplatesPage.shipped.spec.js`. +- [x] 8. Live check in a browser on a running instance. Done 17 Nov 2026 (live pass, NC 34.0.6 + OpenRegister 2.1.47 rig): the Templates page lists "Mijn werkdag" under Ready-made templates with the registers its lists read; `occ launchpad:template:install mijn-werkdag -g werkdag` installed it, and a new member of `werkdag` got their copy on the first visit and saw it in the browser. diff --git a/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/.openspec.yaml b/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/.openspec.yaml new file mode 100644 index 000000000..a49a59f05 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +skip_specs: true diff --git a/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/proposal.md b/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/proposal.md new file mode 100644 index 000000000..1511123c4 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/proposal.md @@ -0,0 +1,31 @@ +--- +kind: code +depends_on: [shipped-template-update] +--- + +# Mijn werkdag version 3: tickets, decisions waiting for a vote, and lists that hide when their app is not here + +## Why + +The Zuiddrecht design asks the start page for pipelinq "my tickets" and decidiq "to initial / waiting for your vote". Version 2 left both out: at the time the only way to show them was a Nextcloud dashboard widget that needs the legacy bridge. Object lists on the apps' registers render as installed, so they can go in now that pipelinq (`ticket`, with `assignee`, `status`, `slaDeadline`) and decidiq (`decision`, with `lifecycle`) carry the fields. + +Two things had to be true first: + +- An installed template can be brought to a newer version in place (`shipped-template-update`, REQ-TMPL-020). Version 3 is the first version that path carries. +- A list of an app that is not installed must not show an error line to the employee. Measured on 5 October 2026: OpenRegister answers 404 "Register not found" and the list widget then shows "Could not load these records" under its title. The install command already names Nextcloud widgets no app provides; registers get the same idea, with one difference: LaunchPad's server does not know an instance's registers, so the page asks and hides (REQ-TMPL-022). + +## What changes + +- `data/templates/mijn-werkdag.json` is version 3: "Mijn tickets" (pipelinq `ticket`), "Wacht op uw stem" (decidiq `decision`), every list sets `hideWhenUnavailable`, recent activity moves down. +- The workspace page leaves out an object-list that set `hideWhenUnavailable` when OpenRegister answers 404 for its source, outside edit mode (`src/services/sourceAvailability.js`, `Views.vue`). +- The shipped-template listing, the Templates page and the install command name the registers a template's lists read. +- `tests/fixtures/registers/pipelinq-ticket.json` and `decidiq-decision.json` (copies of the schemas at the apps' development heads), and the renders-as-installed test holds the new lists' fields and enum values against them. + +## What an instance that installed version 2 sees + +Nothing changes by itself. The Templates page shows "Update to version 3" and `occ launchpad:template:install mijn-werkdag --update --dry-run` prints: added "Mijn tickets (object-list)" and "Wacht op uw stem (object-list)", changed "Zaken over de termijn", "Mijn zaken" (settings: the hide flag) and "Verder waar u was" (position, order), unchanged 2. After the update every member's copy follows (REQ-TMPL-020). + +## Out of scope + +- Knowing on the server which registers an instance has. The page asks OpenRegister; the server names the registers. +- A list for learniq. The design does not ask for one on the employee's start page. diff --git a/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/screens.md b/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/screens.md new file mode 100644 index 000000000..577c6b033 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag +- LpStart https://identity.conduction.nl/screens/board?id=wilgenboom/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=vaartveld/LpStart diff --git a/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/tasks.md b/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/tasks.md new file mode 100644 index 000000000..ce6a60fdc --- /dev/null +++ b/openspec/changes/archive/2026-11-17-mijn-werkdag-v3/tasks.md @@ -0,0 +1,6 @@ +# Tasks: mijn-werkdag-v3 + +- [x] 1. `hideWhenUnavailable`: the page asks OpenRegister once per source and leaves a 404 list out, outside edit mode. Verify: `ViewsHideUnavailableSource.spec.js`. +- [x] 2. Template version 3 with "Mijn tickets" and "Wacht op uw stem", every list hideable. Verify: `ShippedTemplateServiceTest::testTheShippedDefinitionIsWellFormed`, `::testAShippedTemplateRendersAsInstalled` with the two new register fixtures. +- [x] 3. Listing, Templates page and command name the registers the lists read. Verify: `ShippedTemplateServiceTest::testTheListingNamesWidgetsNothingRegisters`, `TemplatesPage.shipped.spec.js`, `TemplateInstallCommandTest::testInstallsForAGroup`. +- [x] 4. Live: update an instance from version 2 with `--update`, see a member's page without pipelinq and decidiq. Done 17 Nov 2026 (live pass): version 2 installed for `werkdag`, a member visited, then `--update --dry-run` and `--update` brought it to version 5 (the version shipped now) and the member's copy followed ("Copies changed: 1"). In the browser the member sees Vandaag, Vandaag eerst, Apps, Agenda vandaag and Verder waar u was; the dossiq, pipelinq and decidiq stat widgets are left out (OpenRegister answers 404, none of the three is installed) and no "Could not load" line shows. diff --git a/openspec/changes/archive/2026-11-17-record-parity-requirements/proposal.md b/openspec/changes/archive/2026-11-17-record-parity-requirements/proposal.md new file mode 100644 index 000000000..fc70ec3ee --- /dev/null +++ b/openspec/changes/archive/2026-11-17-record-parity-requirements/proposal.md @@ -0,0 +1,36 @@ +--- +kind: spec +depends_on: [] +--- + +# Requirements for five parity rows the specs did not yet say + +## Why + +Every row in `openspec/parity/capabilities.json` records the requirement that covers it. Five rows had no requirement whose scenarios say what the row says: + +- **build-picker**, "Pick a widget from a searchable list of everything you may add". `src/modals/WidgetPickerModal.vue:18-25` has a search box and `filteredWidgets` (line 163) narrows the list by title. The widgets spec (REQ-WDG-010) describes a plain type select. +- **d-auto-refresh**, "Refresh widget content on its own without reloading the page". `src/components/WidgetRenderer.vue:478-481` arms a timer from the widget's `reloadInterval`. The widgets spec only says the formatter copies the interval. +- **g-health**, "Check the app's health from the admin page". `src/components/admin/HealthPanel.vue` sits on the Operations tab (`src/components/admin/tabs/OperationsTab.vue:9`). The metrics spec only describes the endpoint. +- **s-policy**, "Decide who may share dashboards, and with whom". The Sharing tab (`src/components/admin/DashboardSharingPolicy.vue`) sets a default share level and forced share groups. Nothing limits who may share or with whom. +- **d-tour**, "Take a guided tour of the dashboard and the admin area on first use". REQ-SHELL-010 covers the Workspace tour and says the tour does not visit the admin settings. + +## What changes + +- `widgets`: the picker narrows its list as you type, and a Nextcloud widget with a reload interval refreshes itself. +- `prometheus-metrics`: the admin page shows the health check result. +- `dashboard-sharing`: administrators limit who may share and with whom. Not built yet. +- `runtime-shell`: the admin area gets its own first-visit tour. Not built yet. +- `widgets`: another app's widget shows that app's items for the viewer (rows int-mail and int-tasks, which only had the generic `nc-widget` requirement). +- `platform-baseline`: outbound requests use the server's proxy setting (row d-proxy, whose requirement covered the feed refresh job only). + +## Capabilities + +### Modified capabilities + +- `widgets`, `prometheus-metrics`, `dashboard-sharing`, `runtime-shell`, `platform-baseline` + +## Impact + +- The first three requirements describe code on `development`; they only add the spec text. +- s-policy and d-tour move from `built` to `specified` in the parity matrix until the code exists. diff --git a/openspec/changes/archive/2026-11-17-record-parity-requirements/screens.md b/openspec/changes/archive/2026-11-17-record-parity-requirements/screens.md new file mode 100644 index 000000000..876b8b685 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-record-parity-requirements/screens.md @@ -0,0 +1,10 @@ +# Screens + +- launchpad/LpWidgetKiezen: the widget picker with its search box (row build-picker) https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetKiezen +- launchpad/LpManagement: widgets that refresh on their own (row d-auto-refresh) https://identity.conduction.nl/screens/board?id=launchpad/LpManagement +- launchpad/LpWidgetInstellen: widget settings (row d-auto-refresh) https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetInstellen +- launchpad/LpBeheerOnderhoud: the health panel on the admin page (row g-health) https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerOnderhoud +- launchpad/LpBeheerDelen: the sharing settings (row s-policy) https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerDelen +- launchpad/LpEersteKeer: the first-visit tour (row d-tour) https://identity.conduction.nl/screens/board?id=launchpad/LpEersteKeer +- launchpad/LpWerkplek: the Mail app's widget on the start page (row int-mail) https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- launchpad/LpVandaag: open tasks from a planning app (row int-tasks) https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag diff --git a/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/dashboard-sharing/spec.md b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/dashboard-sharing/spec.md new file mode 100644 index 000000000..41a691f0d --- /dev/null +++ b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/dashboard-sharing/spec.md @@ -0,0 +1,29 @@ +# Delta for dashboard-sharing: who may share, and with whom + +## ADDED Requirements + +### Requirement: Administrators decide who may share and with whom (REQ-SHARE-014) + +An administrator MUST be able to name the groups whose members may share dashboards. An empty list MUST mean everyone may share, which keeps today's behaviour. An administrator MUST also be able to limit recipients to people who share a group with the sharer. The server MUST enforce both settings on every share it creates, and the sharee search MUST offer only allowed recipients. + +#### Scenario: A member outside the sharing groups cannot share + +- **GIVEN** Noor allowed sharing for the group "Communicatie" only +- **AND** Pieter is not in "Communicatie" +- **WHEN** Pieter opens the share settings of his dashboard +- **THEN** he cannot add a share +- **AND** a share request he sends to the API is refused with HTTP 403 + +#### Scenario: Recipients limited to shared groups + +- **GIVEN** Noor limited recipients to people who share a group with the sharer +- **AND** Ella shares no group with Pieter +- **WHEN** Pieter searches for "Ella" in the share settings +- **THEN** Ella is not offered +- **AND** a share request naming Ella is refused with HTTP 403 + +#### Scenario: No limits set + +- **GIVEN** both sharing settings are empty +- **WHEN** Pieter shares his dashboard with Ella +- **THEN** the share is created as before diff --git a/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/platform-baseline/spec.md b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/platform-baseline/spec.md new file mode 100644 index 000000000..95b4b1bf8 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/platform-baseline/spec.md @@ -0,0 +1,26 @@ +# Delta for platform-baseline: outbound requests and the server's proxy + +## ADDED Requirements + +### Requirement: Outbound requests use the server's proxy setting (REQ-PLB-008) + +Every server-side request LaunchPad sends to another site, for news feeds, calendar feeds, live tiles, weather, health pings and embed checks, MUST go through Nextcloud's HTTP client (`IClientService`), so the proxy an administrator set in `config.php` (`proxy`, `proxyuserpwd`, `noproxy`) applies without a LaunchPad setting. LaunchPad MUST NOT open its own connections with `curl_*`, `file_get_contents` on a URL, or a client it builds itself. + +#### Scenario: A live tile behind the organisation's proxy + +- **GIVEN** the Nextcloud server has `proxy` set to `http://proxy.gemeente.local:3128` +- **AND** Ella placed a live tile that reads `https://data.gemeente.nl/api/meldingen` +- **WHEN** Pieter opens the dashboard and the tile fetches its value +- **THEN** the request leaves the server through `proxy.gemeente.local:3128` + +#### Scenario: A host on the no-proxy list + +- **GIVEN** `noproxy` lists `intranet.gemeente.local` +- **WHEN** a news widget reads a feed from `https://intranet.gemeente.local/nieuws.rss` +- **THEN** the request goes to the intranet directly, not through the proxy + +#### Scenario: No connection of its own + +- **GIVEN** the LaunchPad `lib/` tree +- **WHEN** it is searched for `curl_`, `file_get_contents(` on a URL and `new Client(` +- **THEN** there are no matches diff --git a/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/prometheus-metrics/spec.md b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/prometheus-metrics/spec.md new file mode 100644 index 000000000..d0ce70188 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/prometheus-metrics/spec.md @@ -0,0 +1,19 @@ +# Delta for prometheus-metrics: health on the admin page + +## ADDED Requirements + +### Requirement: The admin page shows the app's health (REQ-PROM-011) + +The Operations tab of the LaunchPad admin page MUST show a Health panel that reads the health check endpoint (REQ-PROM-007). The panel MUST show "Checking…" while it waits, then "Healthy" or "Degraded" with the result in words, not only a colour. + +#### Scenario: A healthy app + +- **GIVEN** Noor is a Nextcloud administrator and the health check answers `status: "ok"` +- **WHEN** she opens the Operations tab of the LaunchPad admin page +- **THEN** the Health panel says "Healthy" + +#### Scenario: A degraded app + +- **GIVEN** the health check reports that the database cannot be reached +- **WHEN** Noor opens the Operations tab +- **THEN** the Health panel says "Degraded" diff --git a/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/runtime-shell/spec.md b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/runtime-shell/spec.md new file mode 100644 index 000000000..d71e397c3 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/runtime-shell/spec.md @@ -0,0 +1,19 @@ +# Delta for runtime-shell: a tour of the admin area + +## ADDED Requirements + +### Requirement: The admin area has its own first-visit tour (REQ-SHELL-011) + +LaunchPad MUST declare a second guided tour, `launchpad:admin-getting-started`, for the LaunchPad admin settings page. It MUST start on an administrator's first visit to that page and walk through its tabs: general settings, templates, roles, sharing and operations. Completion MUST be stored per user like the Workspace tour (REQ-SHELL-010). A person who is not an administrator never sees it. + +#### Scenario: An administrator's first visit to the admin page + +- **GIVEN** Noor is a Nextcloud administrator who never opened the LaunchPad admin page +- **WHEN** she opens it +- **THEN** the admin tour starts with a step on the general settings tab + +#### Scenario: A finished admin tour stays closed + +- **GIVEN** Noor completed the admin tour +- **WHEN** she opens the admin page again +- **THEN** the admin tour does not start diff --git a/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/widgets/spec.md b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/widgets/spec.md new file mode 100644 index 000000000..a38cc9d02 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-record-parity-requirements/specs/widgets/spec.md @@ -0,0 +1,73 @@ +# Delta for widgets: picker search and automatic refresh + +## ADDED Requirements + +### Requirement: The widget picker narrows its list as you type (REQ-WDG-028) + +The widget picker MUST show a search box above the list of widgets and apps you may add. Typing MUST narrow both lists to the entries whose title contains the typed text, ignoring case. Clearing the box MUST bring back the full lists. When nothing matches, the picker MUST say so instead of showing empty lists. + +#### Scenario: Typing narrows the list + +- **GIVEN** Pieter opens "Add widget" on his dashboard +- **WHEN** he types "cal" in "Search widgets" +- **THEN** the picker lists only the widgets and apps whose title contains "cal", such as "Calendar" + +#### Scenario: Clearing the search + +- **GIVEN** Pieter typed "cal" in "Search widgets" +- **WHEN** he clears the search box +- **THEN** the picker lists every widget and app again + +#### Scenario: Nothing matches + +- **GIVEN** Pieter opens "Add widget" +- **WHEN** he types "zzz" +- **THEN** the picker says that no widget matches +- **AND** it shows no empty list + +### Requirement: A Nextcloud widget with a reload interval refreshes itself (REQ-WDG-029) + +When a Nextcloud dashboard widget declares a reload interval above zero, LaunchPad MUST fetch its items again at that interval while the widget is on the page. The page MUST NOT reload. The timer MUST stop when the widget leaves the page. A widget without a reload interval MUST load its items once. + +#### Scenario: Items refresh on the widget's interval + +- **GIVEN** a widget on Pieter's dashboard declares a reload interval of 60 seconds +- **WHEN** 60 seconds pass with the dashboard open +- **THEN** the widget shows its items fetched again +- **AND** the page itself does not reload + +#### Scenario: No interval, no refresh + +- **GIVEN** a widget declares a reload interval of 0 +- **WHEN** Pieter keeps the dashboard open +- **THEN** the widget loads its items once and does not fetch them again + +#### Scenario: Leaving the dashboard stops the timer + +- **GIVEN** a widget with a reload interval is on the page +- **WHEN** Pieter switches to another dashboard +- **THEN** the widget's refresh timer stops + +### Requirement: Another app's widget shows that app's items for the viewer (REQ-WDG-030) + +When a person places a widget that another Nextcloud app registers, such as the Mail app's mailbox widget or Deck's upcoming cards, LaunchPad MUST ask that app for the items it holds for the viewer and list them with their title, subtitle and icon. Each item MUST link to the item in its own app. When the app returns no items, the widget MUST show the app's own empty message. + +#### Scenario: A mailbox preview + +- **GIVEN** the Mail app is enabled and Pieter placed its mailbox widget on "Mijn werkplek" +- **WHEN** he opens the Workspace page +- **THEN** the widget lists his latest messages with sender and subject +- **AND** clicking a message opens it in Mail + +#### Scenario: Open tasks from a planning app + +- **GIVEN** Deck is enabled and Sanne placed its upcoming cards widget on her dashboard +- **WHEN** she opens the Workspace page +- **THEN** the widget lists the cards assigned to her with their due dates +- **AND** clicking a card opens it in Deck + +#### Scenario: Nothing to show + +- **GIVEN** Pieter's mailbox has no messages the Mail widget returns +- **WHEN** he opens the Workspace page +- **THEN** the widget shows the empty message the Mail app supplies diff --git a/openspec/changes/archive/2026-11-17-record-parity-requirements/tasks.md b/openspec/changes/archive/2026-11-17-record-parity-requirements/tasks.md new file mode 100644 index 000000000..e1a21d3f6 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-record-parity-requirements/tasks.md @@ -0,0 +1,12 @@ +# Tasks: record-parity-requirements + +- [x] 1. Write the requirements for build-picker, d-auto-refresh and g-health from the code on `development`, and record them on the rows in `openspec/parity/capabilities.json`. +- [x] 2. Record the s-policy and d-tour requirements on their rows and set both rows to `specified`. +- [x] 3. Build the sharing limits: add `sharing_allowed_groups` and `sharing_recipient_scope` to `lib/Db/AdminSettingKey.php`, enforce them in `lib/Service/DashboardShareService.php` and in the sharee search, and add both fields to `src/components/admin/DashboardSharingPolicy.vue`. Verify: PHPUnit on the service, Vitest on the component. +- [x] 4. Build the admin tour: declare a `launchpad:admin-getting-started` walkthrough in `src/manifest.json` for the admin settings page. Verify: Vitest on the manifest block. +- [x] 5. Fold the requirements into the main specs on archive, and set s-policy and d-tour to `built` with evidence lines. Done on archive 17 Nov 2026, after live checks on NC 34: with `sharingAllowedGroups` set to `["admin"]` a member's share was refused with 403 "You are not allowed to share dashboards." and went through again once the list was emptied; a new administrator opening the LaunchPad admin page got "Step 1 of 5: General settings" of the admin tour. s-policy and d-tour are `built` with evidence lines. +- [x] 6. Write the requirements for int-mail, int-tasks (REQ-WDG-030) and d-proxy (REQ-PLB-008) from the code on `development` (`src/components/WidgetRenderer.vue` item mapping; every outbound fetch through `IClientService`), and record them on the rows. + +Task 3 built: `SharingLimits` reads `sharing_allowed_groups` (empty = everyone) and `sharing_recipient_scope` (`everyone` or `shared-groups`; anything else reads as `everyone`); group memberships come through `AdminTemplateService::getUserGroupIdsFor()`, the one place allowed to ask Nextcloud. `DashboardShareService::addShare()` refuses a disallowed share before anything is written, `replaceShares()` checks only shares the dashboard does not have yet (a limit set later does not stop re-saving existing shares), and both surface as HTTP 403 through the controller. The sharee search offers nobody to a user who may not share and, under `shared-groups`, only users who share a group with the sharer and groups the sharer is in. Both settings are on `GET/PUT /api/admin/settings` and in `DashboardSharingPolicy.vue`, saved as their own partial patch. Not done: hiding the add-share control in the share dialog for a user who may not share (the server refuses and the search offers nobody, but the dialog does not yet know in advance). + +Task 4 built: `launchpad:admin-getting-started` is declared in `src/manifest.json` next to the Workspace tour, with `trigger: "manual"` so the Workspace shell never starts it. The admin page (its own bundle, without the shell) runs it through `src/utils/adminWalkthrough.js`: `adminTourManifest()` hands `CnWalkthrough` only that tour as a `first-visit` tour with its own per-user preference `admin-walkthrough-completed-version`, and the browser mirror is kept under its own key, so finishing one tour never closes the other. `AdminSettings.vue` mounts it once the General tab is open (the first step is the general settings card) and records it as seen on completion. The page is served to administrators only. Steps: general settings, templates, roles and permissions, sharing, operations. Dutch copy in `l10n/nl.json`, like the Workspace tour's. Tests: `src/utils/__tests__/adminWalkthrough.spec.js` (13), against the library's own walkthrough engine. Not done here: a per-tour completion and a page/audience condition inside nextcloud-vue itself, which would let the shell host both tours; launchpad no longer needs it. diff --git a/openspec/changes/launcher-bookmark-import/.openspec.yaml b/openspec/changes/archive/2026-11-17-sharing-public-start-page/.openspec.yaml similarity index 100% rename from openspec/changes/launcher-bookmark-import/.openspec.yaml rename to openspec/changes/archive/2026-11-17-sharing-public-start-page/.openspec.yaml diff --git a/openspec/changes/sharing-public-start-page/design.md b/openspec/changes/archive/2026-11-17-sharing-public-start-page/design.md similarity index 100% rename from openspec/changes/sharing-public-start-page/design.md rename to openspec/changes/archive/2026-11-17-sharing-public-start-page/design.md diff --git a/openspec/changes/sharing-public-start-page/proposal.md b/openspec/changes/archive/2026-11-17-sharing-public-start-page/proposal.md similarity index 100% rename from openspec/changes/sharing-public-start-page/proposal.md rename to openspec/changes/archive/2026-11-17-sharing-public-start-page/proposal.md diff --git a/openspec/changes/archive/2026-11-17-sharing-public-start-page/screens.md b/openspec/changes/archive/2026-11-17-sharing-public-start-page/screens.md new file mode 100644 index 000000000..60c824023 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-sharing-public-start-page/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpPubliek https://identity.conduction.nl/screens/board?id=launchpad/LpPubliek diff --git a/openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md b/openspec/changes/archive/2026-11-17-sharing-public-start-page/specs/dashboard-public-share/spec.md similarity index 100% rename from openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md rename to openspec/changes/archive/2026-11-17-sharing-public-start-page/specs/dashboard-public-share/spec.md diff --git a/openspec/changes/archive/2026-11-17-sharing-public-start-page/tasks.md b/openspec/changes/archive/2026-11-17-sharing-public-start-page/tasks.md new file mode 100644 index 000000000..25ebd5900 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-sharing-public-start-page/tasks.md @@ -0,0 +1,15 @@ +# Tasks: sharing-public-start-page + +- [x] 1. Add `public_start_enabled` and `public_start_share_token` with the D1 validation, and the admin section on `SharingTab.vue` listing eligible shares and the switched-off reason. Verify: PHPUnit and Vitest. + - Backend: settings keys, `PublicStartPage` validation service, `GET/PUT /api/admin/public-start`, PHPUnit. The candidates carry the dashboard's name. + - `PublicStartPageSettings.vue` on `SharingTab.vue`: the offered links by dashboard name, "Public start page: <name>" when live, why a switched-on page is off, the server's refusal on save. Vitest in `PublicStartPageSettings.spec.js`. +- [x] 2. Add the `BeforeLoginTemplateRenderedEvent` listener with the D2 conditions and the redirect script. Verify: PHPUnit per condition. + - `PublicStartRedirectListener` adds `launchpad-start-redirect` (`src/startRedirect.js`, webpack entry `start-redirect`) only for a signed-out GET without `redirect_url`, `direct` or `clear` while the start page can be shown; `PublicStartRedirectListenerTest` covers each condition and a failing check. +- [x] 3. Add `PageController::start()` on `/start` with `#[PublicPage]`, `#[NoCSRFRequired]` and the public-share rate limit. Verify: PHPUnit and route-reachability. + - `page#start` on `/start`, before the deep-link catch-all. The token goes to the page as initial state (`Page::PUBLIC_START`, key `publicStartToken`, schema version 3); without a showable link it redirects to the login form with `direct=1`. `PageControllerStartTest`. +- [x] 4. Show the sign-in bar in the public view when rendered as the start page. Verify: Vitest and an axe check. + - `DashboardPublicShareView` `startPage` prop: a `nav` bar with the instance name and a "Sign in" link to `/login?direct=1`, kept on a load error. Vitest in `DashboardPublicShareView.startPage.spec.js` and `publicStart.spec.js`; the axe check needs a browser and is left for the Playwright run. +- [x] 5. Playwright: land on the start page, sign in, deep link still logs in. Done 17 Nov 2026: `tests/e2e/public-start-page.spec.ts`, 3 passed on a live NC 34 instance (the plain address shows the dashboard with "Sign in" to `/login?direct=1`; signing in from there works; a deep link to Files keeps the login form and lands in Files). After signing in through "Sign in" the staff member lands on the instance's default app, which is `/apps/dashboard` on a stock instance, not LaunchPad: the scenario's "lands on his Workspace page" holds only where LaunchPad is the default app. +- [x] 6. Add `nl` and `en` strings, fold the delta into `openspec/specs/dashboard-public-share/spec.md` on archive, and set d-public-start to `built` in the parity matrix with evidence lines. + - `nl` strings in `l10n/nl.js`; English is the source and falls back from the key. `en.js` is not extended: `check:l10n-parity` would then demand all 36 required locales. d-public-start is `built` in the parity matrix with evidence lines; folding the delta into `openspec/specs/dashboard-public-share/spec.md` happens when the change is archived. +- Left: the axe check of 4. diff --git a/openspec/changes/archive/2026-11-17-shipped-template-update/.openspec.yaml b/openspec/changes/archive/2026-11-17-shipped-template-update/.openspec.yaml new file mode 100644 index 000000000..a49a59f05 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-shipped-template-update/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +skip_specs: true diff --git a/openspec/changes/archive/2026-11-17-shipped-template-update/proposal.md b/openspec/changes/archive/2026-11-17-shipped-template-update/proposal.md new file mode 100644 index 000000000..7b23aa49d --- /dev/null +++ b/openspec/changes/archive/2026-11-17-shipped-template-update/proposal.md @@ -0,0 +1,59 @@ +--- +kind: code +depends_on: [mijn-werkdag-template] +--- + +# Update an installed ready-made template in place, and bring the members' copies along + +## Why + +Issue #781, found while live-checking `mijn-werkdag-template` and `cross-app-attention-feed` on 5 October 2026. + +- An installed ready-made template could not follow a newer version. `occ launchpad:template:install <id> --force` added the new version as a second template. The administrator had to move the groups over and delete the old one by hand. +- Dashboards members had already received kept the old widgets. A compulsory widget added in a later version never reached them. +- While the old and the new template both targeted a group, `TemplateService::getApplicableTemplate()` returned "the first match" of a list sorted by name. Both carry the same name, so which one a new member got depended on the order the database returned them in. + +Measured on `development` at `a65bde07`: the installed version is recorded (`shipped_template_version_<id>`), re-sync exists and matches a copy's widget to its template widget by row id (`TemplateResyncService`, REQ-RESYNC-001..005). The missing piece was replacing the template's widgets without replacing its rows. + +## What changes + +- `ShippedTemplateUpdateService` brings an installed template to the shipped version in place. It keeps the template (id, UUID, name, groups, default flag) and pairs the installed widgets with the new ones, so a widget in both versions keeps its row. Then it runs the existing `merge` re-sync. +- `occ launchpad:template:install <id> --update [--dry-run]` prints every widget added, removed and changed. +- `POST /api/admin/templates/shipped/{id}/update` (`dryRun` supported), and on the Templates page an "Update to version N" button that shows the dry run in a dialog before anything is written. +- `getApplicableTemplate()` picks by one rule when several templates target the same group: installed shipped template first (newest version first), then the lowest id. + +## Capabilities + +### Modified capabilities + +- `admin-templates`: adds REQ-TMPL-020 (update in place) and REQ-TMPL-021 (one rule picks the template). +- `cli-commands`: REQ-CLI-012 gains `--update` and `--dry-run`. + +## What a member notices + +The re-sync contract is the existing one and is not changed here: + +- a compulsory or other widget the new version adds arrives in the copy; +- a widget the new version drops leaves the copy; +- a widget the member added stays; +- a template widget the member moved or changed is set back to the template's, and one the member removed comes back (this is what `merge` does for every template widget, see REQ-RESYNC-003); +- the member gets the "your dashboard was updated" notification (REQ-RESYNC-005). + +## What changes on an existing instance + +- Nothing happens on upgrade by itself. An installed template stays at its version until an administrator updates it. +- `getApplicableTemplate()`: only instances where two or more templates target the same group see a difference, and only for users without a dashboard of their own (or, with personal dashboards off, for every member of such a group on their next visit). REQ-TMPL-021 spells it out. + +## Impact + +- `lib/Service/ShippedTemplateUpdateService.php`, `lib/Exception/TemplateNotInstalledException.php` (new) +- `lib/Service/ShippedTemplateService.php` (`findInstalled()`, `updateAvailable` in the listing), `lib/Service/TemplateService.php` +- `lib/Command/TemplateInstallCommand.php`, `lib/Controller/AdminShippedTemplateController.php`, `appinfo/routes.php` +- `src/dialogs/ShippedTemplateUpdateDialog.vue` (new), `src/components/admin/tabs/TemplatesPage.vue`, `src/services/api.js` +- No database migration. + +## Out of scope + +- Updating the installed template's description and category. They stay as installed; only the widgets follow. +- A key per widget in the definition. The three-pass pairing needs none for the templates that ship today; a definition with several untitled widgets of one type that all change at once would have them removed and added again instead of changed in place, which members do not notice. +- Removing the earlier copy a forced install left behind. The administrator deletes it on the Templates page. diff --git a/openspec/changes/archive/2026-11-17-shipped-template-update/screens.md b/openspec/changes/archive/2026-11-17-shipped-template-update/screens.md new file mode 100644 index 000000000..1d3172ede --- /dev/null +++ b/openspec/changes/archive/2026-11-17-shipped-template-update/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerSjablonen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerSjablonen diff --git a/openspec/changes/archive/2026-11-17-shipped-template-update/tasks.md b/openspec/changes/archive/2026-11-17-shipped-template-update/tasks.md new file mode 100644 index 000000000..c077b46a0 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-shipped-template-update/tasks.md @@ -0,0 +1,11 @@ +# Tasks: shipped-template-update + +- [x] 1. `ShippedTemplateUpdateService`: pair the installed widgets with the shipped ones, write in one transaction, raise the recorded version, re-sync with `merge`. Verify: `ShippedTemplateUpdateServiceTest`. +- [x] 2. Dry run that writes nothing. Verify: `ShippedTemplateUpdateServiceTest::testADryRunWritesNothing`. +- [x] 3. A member's copy follows and keeps the member's own widget, with the real `TemplateService` and `TemplateResyncService`. Verify: `ShippedTemplateUpdateServiceTest::testAMembersCopyFollowsAndKeepsTheirOwnWidget`. +- [x] 4. `occ launchpad:template:install <id> --update [--dry-run]`. Verify: `TemplateInstallCommandTest`. +- [x] 5. `POST /api/admin/templates/shipped/{id}/update` and `updateAvailable` in the listing. Verify: `AdminShippedTemplateControllerTest`, `ShippedTemplateServiceTest::testTheListingSaysWhenAnUpdateIsAvailable`. +- [x] 6. Templates page: "Update to version N" and the confirmation dialog, `en` and `nl` strings. Verify: `TemplatesPage.shippedUpdate.spec.js`. +- [x] 7. `getApplicableTemplate()` picks by one rule. Verify: `TemplateServiceApplicableTemplateTest`. +- [x] 8. Live check of the command on a test instance, and of a member's page in a browser afterwards. See the PR body. +- [x] 9. Open the "Update to version N" button and its dialog in a browser. Done 17 Nov 2026 (live pass): with version 2 on record, the Templates page showed "Update to version 5"; the dialog listed the widgets added, removed and changed and the member copies, and "Update" applied it and the button went away. diff --git a/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/.openspec.yaml b/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/.openspec.yaml new file mode 100644 index 000000000..a49a59f05 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +skip_specs: true diff --git a/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/proposal.md b/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/proposal.md new file mode 100644 index 000000000..0af4fb1b6 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/proposal.md @@ -0,0 +1,26 @@ +--- +kind: code +depends_on: [] +--- + +# Start page without navigation panel + +## Why + +The Zuiddrecht design (`LpStart`) shows the employee's start page at full width under the top bar: no left navigation panel, the dashboard switcher and the footer destinations not in a rail. LaunchPad roots on `CnAppRoot`, which renders `CnAppNav` with ADR-114's four footer destinations, and the library has no prop to leave it out. For the demo the panel was hidden with one CSS line on the instance, which keeps an invisible landmark and takes Documentation, Store, Reports, Features & roadmap and the settings entries with it. + +## What changes + +- An admin option "Start page without navigation panel" (`start_page_without_navigation`, API `startPageWithoutNavigation`, default off) on the admin settings page beside the other layout options, stored with the other admin settings, pushed to the workspace initial state as an optional key (runtime-shell REQ-SHELL-009, admin-settings REQ-ASET-001). +- On, the dashboard view (`/`, `/dashboards/:id`) renders without the panel: `App.vue` fills `CnAppRoot`'s `#menu` slot with a hidden, empty node, so the panel is not rendered and the content takes the full width. Other pages keep the panel. +- `StartPageMenu` in the workspace's top-right controls, beside the dashboard switcher (and in the empty state), offers every entry the panel would have shown: the manifest's main, footer and settings entries after the panel's permission filter, the personal settings dialog, and for an administrator the link to Nextcloud's admin settings. +- Tests: option off renders the panel, on does not, other routes keep it; every panel entry has a destination and every router destination is a declared page (route no loss). + +## Library gap + +`@conduction/nextcloud-vue` 2.57.1, `src/components/CnAppRoot/CnAppRoot.vue` lines 202 to 213: the `#menu` slot defaults to `<CnAppNav>` and there is no prop to render the shell without it. Vue renders a slot's default content when the override holds no real node (`@vue/runtime-core` `ensureValidVNode`), so an empty override does not drop the panel; the hidden span is the smallest thing that does. + +## Out of scope + +- The design's "Startpagina aanpassen" button and widgets; this change is about the chrome. +- A settings export: the app's export is of dashboards and the site, not of admin settings, so there is nothing to add the option to. diff --git a/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/screens.md b/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/screens.md new file mode 100644 index 000000000..7065b49c3 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag +- LpBeheerAlgemeen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAlgemeen diff --git a/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/tasks.md b/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/tasks.md new file mode 100644 index 000000000..48b2579e9 --- /dev/null +++ b/openspec/changes/archive/2026-11-17-start-page-without-navigation-panel/tasks.md @@ -0,0 +1,5 @@ +# Tasks: start-page-without-navigation-panel + +- [x] 1. The option: key, default off, persistence, controller parameter, initial-state setter and wiring. Verify: `AdminSettingsServiceTest::testGetSettingsStartPageWithoutNavigationDefaultsOff`, `::testUpdateSettingsPersistsStartPageWithoutNavigation`, `InitialStateBuilderTest`, `AdminControllerSettingsAliasTest::testStartPageWithoutNavigationIsPassedThrough`. +- [x] 2. The dashboard view without the panel, the menu in the top row, the admin switch, strings in 37 locales. Verify: `App.navigationPanel.spec.js`, `StartPageMenu.spec.js`. +- [x] 3. Live: option on, a member's start page without the panel, the menu with every destination; option off, the panel back. Done 17 Nov 2026: `tests/e2e/start-page-without-navigation.spec.ts`, 3 passed on a live NC 34 rig. The menu is now the More menu (lpvandaag-start-page), so the spec was moved from `launchpad-start-page-menu` to it. diff --git a/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/proposal.md b/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/proposal.md new file mode 100644 index 000000000..68d7e0d86 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/proposal.md @@ -0,0 +1,31 @@ +# Edit a shared dashboard together + +## Why + +Ruben decided on 13 Nov (decision 406) that the drawn board is canon. LpBewerken draws two +people editing one dashboard at once: "Marieke Jansen bewerkt dit dashboard ook sinds 10:42. Uw +wijzigingen worden niet overschreven", with "Wie werkt er mee?" and "Wijzigingen worden direct +bewaard". The built behaviour is a lock (`dashboard-locking`, REQ-LOCK-001 and REQ-LOCKUI-001): +the second editor stays read-only behind a banner. The lock stays as built until this change +lands. + +### Matrix rows (launchpad `openspec/parity/capabilities.json`) + +| row | what changes | +|---|---| +| `build-edit-lock` | several people edit a shared dashboard at once, see each other, and no one's change is lost | + +## What changes + +- Several people with edit rights edit one shared dashboard at the same time. +- Each editor sees who else is editing and since when. +- Every change is saved at once, per widget. A change to one widget never overwrites a + colleague's change to another widget. Two changes to the same widget do not silently replace + each other. +- A new widget lands on the first free spot, never over another widget. + +## Impact + +- The workspace page edit mode (`src/views/Views.vue`, `src/composables/useDashboardLock.js`, + `src/components/Workspace/EditLockBanner.vue`), the dashboard save endpoint. The lock is + replaced in edit mode once this is built. Not built yet: the matrix row moves to `specified`. diff --git a/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/screens.md b/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/screens.md new file mode 100644 index 000000000..68ea8e757 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpBewerken (edit mode with "Marieke Jansen bewerkt dit dashboard ook sinds 10:42. Uw wijzigingen worden niet overschreven." and "Wie werkt er mee?") diff --git a/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/specs/dashboard-co-editing/spec.md b/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/specs/dashboard-co-editing/spec.md new file mode 100644 index 000000000..b8ca2ef5f --- /dev/null +++ b/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/specs/dashboard-co-editing/spec.md @@ -0,0 +1,51 @@ +# dashboard-co-editing + +## ADDED Requirements + +### Requirement: Several people SHALL be able to edit a shared dashboard at once + +The system SHALL let every person with edit rights on a shared dashboard edit it at the same +time as others. Each editor SHALL see who else is editing that dashboard and since when. The +system SHALL save every change at once. A change to one widget SHALL NOT overwrite a colleague's +change to another widget. + +Rows: `build-edit-lock` (launchpad matrix). + +#### Scenario: A second editor edits instead of waiting +- **GIVEN** Marieke edits the shared dashboard "Mijn werkplek" since 10:42 +- **WHEN** Sanne opens the same dashboard in edit mode +- **THEN** Sanne can edit it +- **AND** Sanne sees that Marieke edits it too, since 10:42 + +#### Scenario: Changes to different widgets both survive +- **GIVEN** Marieke and Sanne edit the same dashboard +- **WHEN** Marieke resizes the calendar widget and Sanne moves the news widget +- **THEN** the saved dashboard has both changes + +### Requirement: Two changes to the same widget SHALL NOT silently replace each other + +When two editors change the same widget, the system SHALL apply the first saved change and +refuse the later one, which was made on an older version of that widget. The editor whose change +was refused SHALL see the colleague's version and SHALL be able to make the change again on top +of it. + +Rows: `build-edit-lock` (launchpad matrix). + +#### Scenario: The later change to one widget is refused, not lost silently +- **GIVEN** Marieke and Sanne both have the calendar widget's settings open +- **WHEN** Marieke saves first and Sanne saves after +- **THEN** Marieke's change is kept +- **AND** Sanne sees Marieke's version and can apply her change again + +### Requirement: A new widget SHALL land on the first free spot + +When an editor adds a widget, the system SHALL place it on the first free spot in the saved +layout and SHALL NOT place it over another widget, also when a colleague changed the layout a +moment before. + +Rows: `build-edit-lock` (launchpad matrix). + +#### Scenario: A widget added during a colleague's edit takes a free spot +- **GIVEN** Marieke just moved a widget into the first free spot +- **WHEN** Sanne adds a new widget +- **THEN** the new widget goes to the next free spot and covers no other widget diff --git a/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md b/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md new file mode 100644 index 000000000..f25f1bded --- /dev/null +++ b/openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md @@ -0,0 +1,11 @@ +## 1. Build + +- [x] 1.1 Presence: the edit mode publishes who is editing a dashboard and since when, and shows it ("Wie werkt er mee?", initials and the banner line). +- [x] 1.2 Per-widget saves with a version per widget; a save on a stale widget version is refused and the editor sees the colleague's version. +- [x] 1.3 Placement of a new widget on the first free spot, checked against the saved layout, never over another widget. +- [x] 1.4 Replace the edit lock in edit mode once 1.1 to 1.3 work; keep the admin force-release for old locks until then. +- [x] 1.5 Unit tests for two editors on different widgets, two editors on the same widget, and placement. + +## 2. Hand-over + +- [x] 2.1 `@spec` tags and an e2e test or a reason-bearing `@e2e exclude` per scenario. The four scenarios are driven over the API in `tests/e2e/api-direct/dashboard-co-editing.api.spec.ts` (two editors, a user share at full permission). diff --git a/openspec/changes/cleanup-category-boolean-getter-name/.openspec.yaml b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/.openspec.yaml similarity index 100% rename from openspec/changes/cleanup-category-boolean-getter-name/.openspec.yaml rename to openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/.openspec.yaml diff --git a/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/proposal.md b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/proposal.md new file mode 100644 index 000000000..ecaa45955 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/proposal.md @@ -0,0 +1,100 @@ +# Rename `CleanupCategoryInterface::getSafeToPurgeAutomatically()` to `isSafeToPurgeAutomatically()` + +> **STATUS: APPROVED by Ruben on 19 Nov 2026.** Spec-first: the spec amendment +> lands in its own PR, the rename follows in the next one. + +## Why + +PHPMD's `rulesets/naming.xml/BooleanGetMethodName` reports 5 findings in +`lib/Service/Cleanup/`, all the same method name on the interface and its four +implementations: + +| File | Line | +| --- | --- | +| `lib/Service/Cleanup/CleanupCategoryInterface.php` | 79 | +| `lib/Service/Cleanup/ExpiredLocksCategory.php` | 84 | +| `lib/Service/Cleanup/OrphanedConditionalRulesCategory.php` | 81 | +| `lib/Service/Cleanup/OrphanedSharesCategory.php` | 88 | +| `lib/Service/Cleanup/OrphanedWidgetPlacementsCategory.php` | 80 | + +The rule's position is that a method returning `bool` should read as a predicate +(`is*`/`has*`), not as an accessor (`get*`) — `if ($c->isSafeToPurgeAutomatically())` +reads as a question, `if ($c->getSafeToPurgeAutomatically())` reads as a field +fetch. The rule is correct here: the method is a pure predicate with no backing +field, and its one production caller +(`CategoryRegistryService`, REQ-CLN-008) uses it exactly as a question: + +```php +if ($category->getSafeToPurgeAutomatically() === true) { +``` + +## Why this is a proposal and not a patch + +**The name is pinned verbatim by the canonical spec.** +`openspec/specs/orphaned-data-cleanup/spec.md` names the method twice, once in a +normative MUST and once in the interface contract: + +- line 227: *"Each category exposes its tier through + `CleanupCategoryInterface::getSafeToPurgeAutomatically()`."* +- line 314: *"GIVEN the `CleanupCategoryInterface` with methods `getName()`, + `getDisplayName()`, `getSafeToPurgeAutomatically()`, `isAvailable()`, `scan()`, + and `purge(bool $dryRun = false)`"* + +Renaming the method in code without amending the spec would make both statements +false and leave the spec describing an interface that no longer exists. As with +the `ResponseHelper` proposal, the sequencing must be spec-first, and the spec +edit is a decision for a human rather than a mechanical cleanup an agent should +make on its own initiative. + +Note the internal inconsistency the rename would also resolve: the same interface +already has `isAvailable()`, so the interface currently uses **both** conventions +for boolean-returning methods. The four implementation classes also already use +the predicate wording in their own docblocks and comments +(`Tier-A ('safeToPurgeAutomatically=true')`). + +## What Changes + +If approved, in this order: + +1. **Amend `openspec/specs/orphaned-data-cleanup/spec.md`** at lines 227 and 314 to + name `isSafeToPurgeAutomatically()`. +2. **Rename the method** on `CleanupCategoryInterface` and its four implementations. +3. **Update the one production call site** in + `lib/Service/Cleanup/CategoryRegistryService.php` (~line 133). +4. **Update any test doubles / assertions** that stub or call the old name. +5. **Remove the corresponding entries from `phpmd.baseline.xml`.** + +## Capabilities + +### New Capabilities + +(none) + +### Modified Capabilities + +- `orphaned-data-cleanup`: the interface method name changes; the tier semantics + (Tier-A = auto-purgeable, Tier-B = requires admin inspection) are **unchanged**. + +## Impact + +**Blast radius (measured):** + +- **5 declaration sites** (1 interface + 4 implementations) +- **1 production call site** (`CategoryRegistryService`) +- **5 PHPMD findings** retired +- No behaviour change whatsoever — this is a pure rename of a predicate. + +**Risk: low.** `CleanupCategoryInterface` is an internal interface, not a public +extension point published to third-party apps, so the rename does not break an +external contract. The only sharp edge is a stale test double implementing the +interface under the old name, which would fail loudly rather than silently. + +**Alternative considered and rejected:** adding an `is*` alias and deprecating the +`get*` name. That doubles the interface surface permanently to avoid a +six-call-site rename in a closed interface, and leaves the PHPMD findings in place +until the deprecated name is finally removed. Not worth it at this size. + +## Decision requested + +Approve, amend, or reject. If approved, the spec amendment lands first and the +rename follows in its own PR. diff --git a/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/screens.md b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/screens.md new file mode 100644 index 000000000..c66b88da3 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: code rename, no page diff --git a/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/tasks.md b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/tasks.md new file mode 100644 index 000000000..f3c174e0e --- /dev/null +++ b/openspec/changes/archive/2026-11-19-cleanup-category-boolean-getter-name/tasks.md @@ -0,0 +1,28 @@ +# Tasks — rename getSafeToPurgeAutomatically() to isSafeToPurgeAutomatically() + +> Approved by Ruben on 19 Nov 2026. +> Spec-first: nothing in section 2 may start until section 1 is merged. + +## 1. Spec amendment (must land first, on its own) + +- [x] 1.1 `openspec/specs/orphaned-data-cleanup/spec.md` line 227 — rename in the + normative statement about how a category exposes its tier. +- [x] 1.2 Same file, line 314 — rename in the `CleanupCategoryInterface` method list. + +## 2. Implementation (only after 1 is merged) + +- [x] 2.1 Rename on `lib/Service/Cleanup/CleanupCategoryInterface.php:79`. +- [x] 2.2 Rename on `ExpiredLocksCategory.php:84`. +- [x] 2.3 Rename on `OrphanedConditionalRulesCategory.php:81`. +- [x] 2.4 Rename on `OrphanedSharesCategory.php:88`. +- [x] 2.5 Rename on `OrphanedWidgetPlacementsCategory.php:80`. +- [x] 2.6 Update the call site in `CategoryRegistryService.php` (~line 133). +- [x] 2.7 Update any test double or assertion using the old name. + +## 3. Verification + +- [x] 3.1 Full unit suite green (baseline 1525 tests / 3877 assertions / 3 skipped). +- [x] 3.2 Re-measure PHPMD with the baseline deleted — expect 5 `BooleanGetMethodName` + findings retired and no new findings. +- [x] 3.3 Remove the corresponding entries from `phpmd.baseline.xml`. +- [x] 3.4 Confirm Tier-A/Tier-B classification behaviour is unchanged (REQ-CLN-008). diff --git a/openspec/changes/dashboards-and-who-may-see-them/.openspec.yaml b/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/.openspec.yaml similarity index 100% rename from openspec/changes/dashboards-and-who-may-see-them/.openspec.yaml rename to openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/.openspec.yaml diff --git a/openspec/changes/dashboards-and-who-may-see-them/design.md b/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/design.md similarity index 100% rename from openspec/changes/dashboards-and-who-may-see-them/design.md rename to openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/design.md diff --git a/openspec/changes/dashboards-and-who-may-see-them/proposal.md b/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/proposal.md similarity index 100% rename from openspec/changes/dashboards-and-who-may-see-them/proposal.md rename to openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/proposal.md diff --git a/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/screens.md b/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/screens.md new file mode 100644 index 000000000..1aaaa0cf1 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpZichtbaarheid https://identity.conduction.nl/screens/board?id=launchpad/LpZichtbaarheid +- LpBeheerSjablonen the gallery of ready-made reports, one unavailable with the missing register named, and Save as dashboard (REQ-DWMS-003) https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerSjablonen diff --git a/openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md b/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md similarity index 100% rename from openspec/changes/dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md rename to openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md diff --git a/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md b/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md new file mode 100644 index 000000000..f372db004 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md @@ -0,0 +1,135 @@ +# Tasks: dashboards-and-who-may-see-them + +## 1. The personal layer + +- [x] 1.1 Add a personal layer record keyed by user and dashboard, holding order, size and the hidden set. +- [x] 1.2 Apply the layer over a shared dashboard at render time, and only for its owner. +- [x] 1.3 Refuse hiding a placement marked compulsory by `admin-templates`. +- [x] 1.4 Add the reset action, deleting the whole layer behind a confirmation. +- [x] 1.5 Drop orphaned layer entries when a placement disappears after an admin template re-sync. `TemplateResyncService` calls `PersonalLayerService::pruneDashboard()` after a re-sync that removed placements; it sweeps every layer on that dashboard through `PersonalLayerMapper::findByDashboard()`. +- [x] 1.6 PHPUnit on apply, on the compulsory refusal and on reset. +- [x] 1.7 PHPUnit from the READER: a saved layer changes what `DashboardService` hands back, on the landing read and on the by-id read, and reaches nobody else. + +## 2. The report library + +- [x] 2.1 Define the report definition shape: id, title, description, aggregation, parameters, rendering, required registers and schemas. `Reporting\ReportDefinitions::check()`. +- [x] 2.2 Ship a first set of definitions with the app and list them in a gallery. Shipped: `lib/Settings/reports.json` (three reports) and the gallery data at `GET /api/reports`. The gallery is manifest configuration (`src/manifest.d/dashboards-and-who-may-see-them.json`): an index page over that endpoint (the library's `endpoint` source) listing each report with Available or Unavailable and the missing registers and schemas, a row that opens the run (`GET /api/reports/{id}`) on a detail page over the same source, and Save as dashboard on both as an `api-call` to `POST /api/reports/{id}/dashboard`; a card on the Reports page leads to it. +- [x] 2.3 List a report whose registers or schemas are missing as unavailable, naming them. +- [x] 2.4 Save a result as an ordinary dashboard owned by the saver. `POST /api/reports/{reportId}/dashboard`: a dashboard of the caller holding one chart of the result. +- [x] 2.5 PHPUnit on the availability check and on save-as-dashboard. + +## 3. The status report + +- [x] 3.1 Add the status report object: date, health rating, summary, figures, and per value whether it was computed or written. — built: schema `status_report` in the launchpad register (`lib/Settings/register.d/dashboards-and-who-may-see-them.json`, register version 1.0.3) with `provenance` per value; kept through OpenRegister's published object service (`StatusReport\StatusReportStore`), 503 without OpenRegister. +- [x] 3.2 Prefill the rating and the figures from the body of work. — built: `POST /api/status-reports/draft` reads the objects of one schema in one register as the caller (optional filters, status and due-date properties, closed values) and computes total, open, closed, overdue, share closed and days to the deadline, the rating (off track: deadline passed with items open or more than a quarter of the open items overdue; at risk: anything overdue, or within 14 days of the deadline with less than 75% closed) and a summary. +- [x] 3.3 Let a person edit the summary before keeping the report. — built: `POST /api/status-reports` keeps the report with the person's summary and rating, computing the figures again (a person cannot write them). The screen is the dashboard widget `status-report` (`StatusReportWidget`; its form names the body of work: register, schema, deadline, status property, closed values, due-date property): Prepare report shows the computed figures read-only with the prefilled rating and summary, the person changes either, Keep report stores it and shows back which values were computed and which were written by a person. Vitest on the widget (9), its form (3) and its client (6). +- [x] 3.4 PHPUnit on prefill and on the computed-versus-written record. — built: `StatusReportServiceTest` (11), `StatusReportStoreTest` (4), `StatusReportControllerTest` (4), and the shipped register carrying the schema (`ImportLaunchpadRegisterTest`). + +## 4. Activity reporting + +- [x] 4.1 Add the admin setting: off by default, with a purpose string that cannot be empty. — built: `ActivityReport\ActivityReportingPolicy` (app config, off by default; turning it on without a purpose, or with one over 500 characters, is refused; a stored switch without a purpose reads as off), read and set by administrators at `GET`/`PUT /api/admin/activity-reporting`. +- [x] 4.2 Show the purpose on every screen reporting on a named person. — built: every response and the CSV carry the purpose, and the screen is the dashboard widget `activity-report` (`ActivityReportWidget`, form: the period it opens on): a person and a period, the purpose shown above any report about a named person, counts per type with the total, a calendar of intensity per day and the CSV of the report as shown. A refusal is said in words: reporting is off and how an administrator turns it on, only an administrator reads another person, or the period is wrong. Vitest on the widget (12), its form (3) and its client (6). +- [x] 4.3 Write an audit entry for every read of another person's activity. — built: every read of another person's activity dispatches Nextcloud's `CriticalActionPerformedEvent` (the admin audit log) with the subject, the period, the reader and the purpose. +- [x] 4.4 Let a person read their own without the setting and without a log entry. — built: `ActivityReportService::report()` gives anybody their own activity whatever the switch, with no audit entry; another person's is refused with 403 while the switch is off (the answer says how to turn it on) and for a non-administrator, before anything is read. +- [x] 4.5 Report counts per activity type and a per day calendar of intensity, from the existing activity events. — built: `GET /api/activity-report?user=&from=&to=` counts per activity type and per day (UTC, a day without activity absent, at most 366 days), from the activity app's events (`ActivityEventReader`, one event per action however many people it was shown to); nothing measures hours. Without the activity app the report says `available: false`. +- [x] 4.6 Export both as CSV, with totals equal to the screen. — built: `GET /api/activity-report/export` returns the same report as CSV (purpose, subject, period, a row per type and per day, the total), under the same rules. +- [x] 4.7 PHPUnit on the gate, the self-read exception and the audit entry. — built: `ActivityReportServiceTest` (9: the gate, the self-read exception, the audit entry, the figures, the CSV totals), `ActivityReportingPolicyTest` (5), `ActivityEventReaderTest` (3), `ActivityReportControllerTest` (6). + +## 5. Colleague activity + +- [x] 5.1 Add the widget over the existing activity feed. — built: widget type `colleague-activity` (`ColleagueActivityWidget` with its form: lines and days back) over `GET /api/colleague-activity`, which reads the activity app's rows addressed to the reader (`ColleagueActivityReader`), without the reader's own actions; no second feed. +- [x] 5.2 Filter to what the reader may see, and exclude filtered entries from every count. — built: `ColleagueActivityService` checks every event on a launchpad dashboard against the dashboard as it is now (`PermissionService::canViewDashboard()`); an event on a dashboard the reader cannot see, or that is gone, is absent, and the total, the per-type counts and the number of colleagues are taken from what remains. +- [x] 5.3 PHPUnit on the permission filter, including its effect on the totals. — built: `ColleagueActivityServiceTest` (7), `ColleagueActivityReaderTest` (2), `ColleagueActivityControllerTest` (2); Vitest on the widget (7) and its form (3). + +## 6. In-widget search + +- [x] 6.1 Add a filter field to widgets that render rows, in view state only. +- [x] 6.2 Assert it never writes to the placement or its saved search. +- [x] 6.3 Vitest on the component: filter, reload, unchanged definition. + +## 7. Geographic reporting + +- [x] 7.1 Add the aggregation: counts and rates per declared area property over a period. `Reporting\AreaAggregation`, run by the shipped report kind `area` (section 2). +- [x] 7.2 Count objects with no location in an explicit bucket. +- [x] 7.3 PHPUnit on the bucket, including the empty case. + +## 8. Storage reporting + +- [x] 8.1 Read use per workspace and per service from the platform figures and register counts. — built: `StorageReport\StorageFigures` reads the folder sizes the file cache keeps (the figure Nextcloud's quota uses) and the object count per register, never walking files or objects. A workspace is a Nextcloud group (its members' files; a person in two groups counts in both, so the total in use comes from the services); a service is files, trash or versions over every home, or one app's app data. `GET /api/admin/storage-report`. +- [x] 8.2 Keep a daily series and report twelve months. — built: `StorageSnapshotJob` keeps one snapshot a day (totals only) in launchpad's app data (`StorageSeries`, at most 400 days, no table); the report gives the total, every workspace and every service per month for the last twelve months, the month's last snapshot, empty for a month without one. +- [x] 8.3 Name the removable total: past retention, orphaned uploads. — built: apart from the total in use, trash entries older than Nextcloud's `trashbin_retention_obligation` (`auto` is 30 days, `disabled` expires nothing) and launchpad uploads older than a day that no launchpad row names; when the rows cannot be read, no upload counts as orphaned. +- [x] 8.4 Export as CSV, administrator-only, and refuse others with 403. — built: `GET /api/admin/storage-report/export`, the same numbers as CSV; both routes carry the admin-setting attribute and the service refuses anybody who is not an administrator with 403 again. +- [x] 8.5 PHPUnit on the admin guard and on the removable calculation. — built: `StorageReportServiceTest` (10), `StorageFiguresTest` (7), `StorageSeriesTest` (4), `StorageReportControllerTest` (4), `StorageSnapshotJobTest` (2). + +## 9. Handover + +- [x] 9.1 Give the dossiq lane the consumer half: case widgets contributed to a launchpad dashboard, each declaring the roles that may see it. + - Handed over 19 Nov (Ruben's decision) as the dossiq openspec change `case-widgets-declare-who-may-see-them` ([ConductionNL/dossiq#6672](https://github.com/ConductionNL/dossiq/pull/6672), merged 19 Nov). +- [x] 9.2 Agree with the openregister lane which aggregations a shipped report may rely on. + - Handed over 19 Nov (Ruben's decision) as the openregister openspec change `aggregations-a-shipped-report-may-rely-on` ([ConductionNL/openregister#10869](https://github.com/ConductionNL/openregister/pull/10869), open against main). The report library moves onto that contract in a later launchpad change once it lands. +- [x] 9.3 Tick this change in `competitor-parity-2026-09/tasks.md` when it archives. + - Handed over with 9.1 and 9.2: `competitor-parity-2026-09` 2.1 and 2.2 are ticked as handed over in the same PR. + +## What shipped, and what has not + +**Section 1 is built and covered.** `launchpad_personal_layers` holds one row +per person per dashboard: the geometry and order they changed, and the +placements they hid. `PersonalLayerService` lays it over the shared placements +inside `DashboardService::getDashboardForUser()`, on both the owned-read path +and the share path, and inside `getEffectiveDashboard()`, which is the +`GET /api/dashboard` the grid loads from. Only for a dashboard the caller does +not own: their own dashboard is left alone, because there the arrangement IS +the dashboard. + +Two things were fixed once the reader got its own tests. `getEffectiveDashboard()` +did not apply the layer at all, so a person who arranged the dashboard they land +on saw their arrangement through the layer endpoint and nowhere else. And the +layer service was a nullable constructor argument on `DashboardService`, purely +so that unit tests could leave it out. A null read exactly like a person with no +layer, so a wiring failure would have stored every layer and shown none of them +with the whole suite green. It is required now; nothing in the app ever built +that service without it. + +A compulsory placement cannot be hidden, and a save that asks to hide one +writes nothing at all rather than landing the allowed half. It can still be +moved. A placement made compulsory after somebody hid it renders again, which +is checked. The reset is `DELETE`, removes the whole row, and resetting twice +is not an error. + +`pruneOrphans()` is the exception, and task 1.5 is open again because of it. +The method drops entries for placements that no longer exist, and deletes the +row when the sweep empties it. Nothing calls it. Two tests cover it and there +is no call site in `lib/`, which is the same shape this branch just fixed for +`withPersonalLayer()`: a method with a green suite and no caller reports the +same green as one that runs. + +Wiring it is not a one-line call, which is why it is a task and not a fix +here. A re-sync replaces the placements of one dashboard for everybody, and +`pruneOrphans()` takes one user id. `PersonalLayerMapper` can find a layer by +user and dashboard and delete it, and it cannot list the layers on a +dashboard, so there is no query to sweep with. Eight places call +`deleteByDashboardId()`, and each has to decide whether it is a re-sync that +should prune or a deletion that should drop the layer outright. + +What it costs while it waits is bounded, and it is not a wrong number on +screen. `applyTo()` walks the live placements and looks up overrides by id, +so an entry for a placement that is gone is ignored at render time. Placement +ids come from an autoincrement column and are never reused, so a stale entry +cannot attach itself to a different widget later. The cost is stale keys in +the layer row, one per placement ever removed from that dashboard. + +Three routes, all `#[NoAdminRequired]`, all reading the caller's own user id +from the session. No route takes a user id from the request, so one person's +layer is unreachable through another's. + +**Sections 2 to 8 are built on the server.** The report library (section 2), +the status report (3), activity reporting with its purpose gate (4), colleague +activity (5), in-widget search (6), geographic reporting (7) and storage +reporting (8) each have their endpoint, their rules and their PHPUnit; section 5 +also has its widget and section 6 its Vitest. The screens are built too: the report gallery (2.2) is manifest configuration +over the reports endpoint, and the status report (3.3) and the activity report +(4.2) are dashboard widgets, as colleague activity (5) is, each over its endpoint. + +**Section 9, the handover.** 9.1 and 9.2 are unchanged: the dossiq and +openregister halves have not been handed over, because sections 2 to 8 are what +they depend on. diff --git a/openspec/changes/launcher-discover-server-services/.openspec.yaml b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/.openspec.yaml similarity index 100% rename from openspec/changes/launcher-discover-server-services/.openspec.yaml rename to openspec/changes/archive/2026-11-19-governance-rest-api-reference/.openspec.yaml diff --git a/openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md new file mode 100644 index 000000000..9ee55cf9f --- /dev/null +++ b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md @@ -0,0 +1,41 @@ +# Design: governance-rest-api-reference + +Read at development `d767c282`. + +## Context + +- `appinfo/routes.php` registers 181 route entries under `/index.php/apps/launchpad/`, served by the controllers in `lib/Controller/` (for example `DashboardApiController`, `WidgetApiController`, `TileApiController`, `DashboardShareApiController`, `PublicShareController`). They follow ADR-002 (hydra `openspec/architecture/adr-002-api.md`: `/index.php/apps/{app}/api/{resource}`, standard verbs, `message` on errors, Nextcloud authentication only). +- Controllers carry auth attributes (`#[NoAdminRequired]`, `#[PublicPage]`, `#[AuthorizedAdminSetting]`) and `@spec` docblocks, but no response shape annotations. +- `composer.json` defines `check:strict` as a loop over lint, phpcs, phpmd, psalm, phpstan and tests. `scripts/` holds the repo's own checks (`check-manifest.js`, `lint-initial-state.php`). +- The documentation site is Docusaurus under `docs/` (`docs/docusaurus.config.js`). +- Nextcloud apps publish `openapi.json` at their repository root; Nextcloud's own dashboard app does (`apps/dashboard/openapi.json`). + +## Decisions + +### D1: Generated, never hand-written + +Task 1 tries `nextcloud/openapi-extractor` on three LaunchPad controllers. If it documents LaunchPad's index.php JSON routes with their attributes, it is the generator. If it does not, `scripts/generate-openapi.php` reads `appinfo/routes.php`, reflects each controller method's parameters, attributes and `@return` or a `@psalm-return` shape, and writes OpenAPI 3.1. Either way the file is an output, regenerated by one composer script. + +**Outcome of task 1 (19 Nov 2026):** `nextcloud/openapi-extractor` (main, 4e2d61e) was run on `DashboardApiController`, `WidgetApiController` and `TileApiController`. It skips every non-OCS route unless its controller carries `#[OpenAPI(scope: ...)]`; with that attribute added it stopped on 88 errors for the three controllers (an untyped `JSONResponse` needs its three template parameters, `getParam()` is refused, `array` parameters need element types) and generates nothing until all are fixed. It also refuses the app's `EUPL-1.2` licence (no SPDX mapping), knows nothing of the `/api/v1/` aliases `ApiPathAliases` adds, and has no notion of `x-launchpad-stability`. So LaunchPad uses its own generator: `scripts/generate-openapi.php` (`composer openapi:generate`) parses `appinfo/routes.php` and the controller sources with `nikic/php-parser` and `phpstan/phpdoc-parser` (static parsing, no Nextcloud runtime), reads each method's attributes, parameters, `getParam()` reads, reachable `Http::STATUS_*` codes and `@psalm-return` shapes, and writes OpenAPI 3.1. The `@psalm-type` aliases of `lib/ResponseDefinitions.php` become `components.schemas`, the Nextcloud convention, so the annotations stay usable by the extractor if LaunchPad moves to OCS routes. `scripts/openapi-overlay.json` carries the document frame, the shared components and per-operation wording code cannot express. + +### D2: Two stability levels + +Every operation carries `x-launchpad-stability: public` or `internal`, from the method's `@openapi-stability` docblock tag (internal when absent). Public in this change: dashboard CRUD and listing, placements and tiles, sharing, public links, export and import. Everything else starts internal. A public operation changes only with a deprecation notice in the changelog; internal ones may change freely. + +### D3: The drift check + +`composer lint:openapi` regenerates the file into a temporary path and fails when it differs from the committed `openapi.json`, or when a route name in `routes.php` has no operation. It joins `check:strict`, so a new route without documentation fails locally and in CI. + +### D4: Authentication is documented, not added + +The reference documents Basic authentication with a Nextcloud app password, as Nextcloud supports for app routes, and the `OCS-APIRequest: true` header. No new token flow (ADR-002). + +## Declarative-vs-imperative decision + +Documentation generated from code; no schema register involved. + +## Test plan + +- The drift check itself: a PHPUnit or script test with a fixture routes file where one route lacks an operation. +- Validate `openapi.json` against the OpenAPI 3.1 schema in CI. +- Manual check recorded in the PR: `curl -u user:app-password https://<instance>/index.php/apps/launchpad/api/dashboards` matches the documented response shape. diff --git a/openspec/changes/governance-rest-api-reference/proposal.md b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/proposal.md similarity index 100% rename from openspec/changes/governance-rest-api-reference/proposal.md rename to openspec/changes/archive/2026-11-19-governance-rest-api-reference/proposal.md diff --git a/openspec/changes/archive/2026-11-19-governance-rest-api-reference/screens.md b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/screens.md new file mode 100644 index 000000000..b01357e00 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Een REST-API voor andere systemen, zonder scherm. diff --git a/openspec/changes/governance-rest-api-reference/specs/rest-api-reference/spec.md b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/specs/rest-api-reference/spec.md similarity index 100% rename from openspec/changes/governance-rest-api-reference/specs/rest-api-reference/spec.md rename to openspec/changes/archive/2026-11-19-governance-rest-api-reference/specs/rest-api-reference/spec.md diff --git a/openspec/changes/archive/2026-11-19-governance-rest-api-reference/tasks.md b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/tasks.md new file mode 100644 index 000000000..1fc14e786 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-governance-rest-api-reference/tasks.md @@ -0,0 +1,8 @@ +# Tasks: governance-rest-api-reference + +- [x] 1. Try `nextcloud/openapi-extractor` on `DashboardApiController`, `WidgetApiController` and `TileApiController`; record in design.md which generator is used. Verify: the generated fragment lists those routes. +- [x] 2. Add response and request shape annotations to the public controllers (dashboards, placements, tiles, sharing, public links, export and import). Verify: psalm and phpstan stay green. +- [x] 3. Generate `openapi.json` with `x-launchpad-stability` on every operation. Verify: the file validates as OpenAPI 3.1. +- [x] 4. Add `composer lint:openapi` (regenerate and compare, every route documented) to `check:strict`. Verify: a fixture with an undocumented route fails. +- [x] 5. Add the API page to the Docusaurus site with authentication instructions. Verify: the docs build. +- [x] 6. Copy the spec to `openspec/specs/rest-api-reference/spec.md` on archive and set d-rest-api to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/launcher-tile-internal-address/.openspec.yaml b/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/.openspec.yaml similarity index 100% rename from openspec/changes/launcher-tile-internal-address/.openspec.yaml rename to openspec/changes/archive/2026-11-19-integrations-live-tile-lists/.openspec.yaml diff --git a/openspec/changes/integrations-live-tile-lists/design.md b/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/design.md similarity index 100% rename from openspec/changes/integrations-live-tile-lists/design.md rename to openspec/changes/archive/2026-11-19-integrations-live-tile-lists/design.md diff --git a/openspec/changes/integrations-live-tile-lists/proposal.md b/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/proposal.md similarity index 100% rename from openspec/changes/integrations-live-tile-lists/proposal.md rename to openspec/changes/archive/2026-11-19-integrations-live-tile-lists/proposal.md diff --git a/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/screens.md b/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/screens.md new file mode 100644 index 000000000..7119d8b93 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWidgetInstellen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetInstellen +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/changes/integrations-live-tile-lists/specs/live-data-tile-widget/spec.md b/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md similarity index 100% rename from openspec/changes/integrations-live-tile-lists/specs/live-data-tile-widget/spec.md rename to openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md diff --git a/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/tasks.md b/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/tasks.md new file mode 100644 index 000000000..a02bbbb92 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-integrations-live-tile-lists/tasks.md @@ -0,0 +1,10 @@ +# Tasks: integrations-live-tile-lists + +- [x] 1. Validate `display`, `mapping` and `limit` in `LiveTileService::validateSourceConfig()`. Verify: PHPUnit for each rule and for an old config. +- [x] 2. Evaluate the mapping server-side for both source modes, drop unmapped fields, apply the limit, and cache the mapped result. Verify: PHPUnit with array and object payloads. +- [x] 3. Render list, table and key-value in `LiveTileWidget.vue`, with https-only links and accessible markup. Verify: Vitest and an axe check. +- [x] 4. Add the display choice, mapping rows and the "Latest documents" preset (SharePoint and Confluence variants) to `LiveTileWidgetForm.vue`, and rename its "OpenConnector" labels to "Integriq". Verify: Vitest. +- [x] 5. Playwright: a URL-mode list tile against a fixture endpoint. Written 17 Nov: `tests/e2e/live-tile-lists.spec.ts` starts its own fixture server, allow-lists it, places a list tile and checks the server answer (two mapped rows, no unmapped field, a script link dropped) and the dashboard (an https link, plain text for the other). Not run yet: needs a live instance that can reach the fixture (`LIVE_TILE_FIXTURE_HOST`). + - 19 Nov live pass (Nextcloud 34.0.6): `tests/e2e/live-tile-lists.spec.ts` passed (2 of 2) with `LIVE_TILE_FIXTURE_HOST=host.docker.internal` and `allow_local_remote_servers` on the rig. +- [x] 6. Add `nl` and `en` strings, fold the delta into `openspec/specs/live-data-tile-widget/spec.md` on archive, and set int-builder and int-intranet-content to `built` in the parity matrix with evidence lines. Strings (nl, en) and the parity rows done 17 Nov (`openspec/parity/capabilities.json`: both `built` with evidence); folding the delta waits for the archive. + - The delta is folded into `openspec/specs/live-data-tile-widget/spec.md` on archive (19 Nov). diff --git a/openspec/changes/launcher-tile-launch-types/.openspec.yaml b/openspec/changes/archive/2026-11-19-launcher-app-catalogue/.openspec.yaml similarity index 100% rename from openspec/changes/launcher-tile-launch-types/.openspec.yaml rename to openspec/changes/archive/2026-11-19-launcher-app-catalogue/.openspec.yaml diff --git a/openspec/changes/launcher-app-catalogue/design.md b/openspec/changes/archive/2026-11-19-launcher-app-catalogue/design.md similarity index 100% rename from openspec/changes/launcher-app-catalogue/design.md rename to openspec/changes/archive/2026-11-19-launcher-app-catalogue/design.md diff --git a/openspec/changes/launcher-app-catalogue/proposal.md b/openspec/changes/archive/2026-11-19-launcher-app-catalogue/proposal.md similarity index 100% rename from openspec/changes/launcher-app-catalogue/proposal.md rename to openspec/changes/archive/2026-11-19-launcher-app-catalogue/proposal.md diff --git a/openspec/changes/archive/2026-11-19-launcher-app-catalogue/screens.md b/openspec/changes/archive/2026-11-19-launcher-app-catalogue/screens.md new file mode 100644 index 000000000..c4cf8495f --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-app-catalogue/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpTegelToevoegen https://identity.conduction.nl/screens/board?id=launchpad/LpTegelToevoegen diff --git a/openspec/changes/launcher-app-catalogue/specs/app-catalogue/spec.md b/openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md similarity index 100% rename from openspec/changes/launcher-app-catalogue/specs/app-catalogue/spec.md rename to openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md diff --git a/openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md b/openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md new file mode 100644 index 000000000..a2c044eb8 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md @@ -0,0 +1,31 @@ +# Tasks: launcher-app-catalogue + +## Backend + +- [x] 1. Add the two tables in one migration with table builders, entities and mappers. Verify: migration test on PostgreSQL and MySQL. + - Done in code: `Version002013Date20261114090000`, `CatalogueApp`/`AppRequest` and their mappers (query golden recorded). Open: the migration run on PostgreSQL and MySQL, which needs live databases. + - 19 Nov live pass (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): the migration is `Version002015Date20261114130000`. On a fresh PostgreSQL 16 install and a fresh MySQL 8.4 install it creates `oc_launchpad_catalogue_apps` (unique `launchpad_cat_uuid`) and `oc_launchpad_app_requests` (unique `launchpad_areq_uuid`, indexes on requester+status and status). The run found that a catalogue entry with link type `url` was refused by the database (`link_type` NOT NULL, the entity default equalled the value so the setter never marked it); fixed in `CatalogueApp`, `CatalogueAppTest`. +- [x] 2. Seed `catalogue.list`, `catalogue.request`, `catalogue.manage`, `catalogue.decide` in `lib/actions.seed.json`. Verify: action-matrix test. +- [x] 3. Implement `CatalogueService` (group-filtered list, create, update, delete, request, approve, decline, open-request limit). Verify: PHPUnit. +- [x] 4. Add `CatalogueController` (`GET /api/catalogue`, `POST /api/catalogue/requests`) and `AdminCatalogueController` (CRUD and decisions, `#[AuthorizedAdminSetting]`). Verify: PHPUnit and route-reachability. +- [x] 5. Add `app_requested` and `app_request_decided` to `lib/Notification/Notifier.php`, plus the optional `catalogue_manager_group` admin setting. Verify: PHPUnit on the notifier. + +## Frontend + +- [x] 6. Add the "From the app catalogue" section to `src/modals/WidgetPickerModal.vue`, creating a tile through the existing tile call. Verify: Vitest. + - Entry point: the picker had no menu entry left (the toolbar that opened it was removed), so "More" → "Add widget" (`DashboardMoreMenu`, `canEdit` only) now opens it; the separate "Add app" entry was dropped as a duplicate. +- [x] 7. Add the "Can't find your app?" request form. Verify: Vitest and an axe check. + - Done in code: the form in `WidgetPickerModal` with Vitest (sent, limit, failure). Open: the axe check, which needs a browser. + - 19 Nov live pass: `tests/e2e/axe-launcher-forms.spec.ts` opens the form as a non-admin account and runs axe (WCAG 2.2 AA rules, `@axe-core/playwright` 4.14.0) on `[data-testid="widget-picker-request"]`: no serious or critical finding. +- [x] 8. Add the admin "App catalogue" section: entries with group picker (`NcSelect` with input label) and the request list with approve and decline. Verify: Vitest. + - Done: the "App catalogue" admin tab (`src/components/admin/tabs/AppCatalogueTab.vue`) with entries (add, edit, remove, group picker), open requests (approve through the prefilled form, decline with a required note) and the catalogue manager group; Vitest in `AppCatalogueTab.spec.js`. + +## Close + +- [x] 9. Add the four demo entries to `DemoShowcasesService`. Verify: PHPUnit on the showcase. +- [x] 10. Playwright for the add path, group visibility and the decline path. + - Written: `tests/e2e/app-catalogue.spec.ts` (member adds the entry as a tile, non-member sees it neither in the picker nor from `GET /api/catalogue`, a request sent from the picker is declined on the admin tab with a note and the requester is notified), run as non-admin throwaway accounts. Open: the run against a live instance. + - 19 Nov live pass (Nextcloud 34.0.6): `tests/e2e/app-catalogue.spec.ts` passed (3 of 3) as throwaway non-admin accounts, after the catalogue entry fix of task 1 and the root slug fix. +- [x] 11. Add `nl` and `en` strings, copy the spec to `openspec/specs/app-catalogue/spec.md` on archive, and set tile-catalogue to `built` in the parity matrix with evidence lines. + - Done: the 44 frontend strings (picker catalogue section, request form, admin tab) and the 9 notifier strings in `en` and all 36 required locales; tile-catalogue set to `built` with evidence lines in `openspec/parity/capabilities.json`. Open: copying the spec to `openspec/specs/app-catalogue/spec.md`, which happens on archive. + - The spec becomes `openspec/specs/app-catalogue/spec.md` on archive (19 Nov). diff --git a/openspec/changes/launcher-tile-open-behaviour/.openspec.yaml b/openspec/changes/archive/2026-11-19-launcher-discover-server-services/.openspec.yaml similarity index 100% rename from openspec/changes/launcher-tile-open-behaviour/.openspec.yaml rename to openspec/changes/archive/2026-11-19-launcher-discover-server-services/.openspec.yaml diff --git a/openspec/changes/launcher-discover-server-services/design.md b/openspec/changes/archive/2026-11-19-launcher-discover-server-services/design.md similarity index 100% rename from openspec/changes/launcher-discover-server-services/design.md rename to openspec/changes/archive/2026-11-19-launcher-discover-server-services/design.md diff --git a/openspec/changes/launcher-discover-server-services/proposal.md b/openspec/changes/archive/2026-11-19-launcher-discover-server-services/proposal.md similarity index 100% rename from openspec/changes/launcher-discover-server-services/proposal.md rename to openspec/changes/archive/2026-11-19-launcher-discover-server-services/proposal.md diff --git a/openspec/changes/archive/2026-11-19-launcher-discover-server-services/screens.md b/openspec/changes/archive/2026-11-19-launcher-discover-server-services/screens.md new file mode 100644 index 000000000..c4cf8495f --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-discover-server-services/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpTegelToevoegen https://identity.conduction.nl/screens/board?id=launchpad/LpTegelToevoegen diff --git a/openspec/changes/launcher-discover-server-services/specs/tiles/spec.md b/openspec/changes/archive/2026-11-19-launcher-discover-server-services/specs/tiles/spec.md similarity index 100% rename from openspec/changes/launcher-discover-server-services/specs/tiles/spec.md rename to openspec/changes/archive/2026-11-19-launcher-discover-server-services/specs/tiles/spec.md diff --git a/openspec/changes/archive/2026-11-19-launcher-discover-server-services/tasks.md b/openspec/changes/archive/2026-11-19-launcher-discover-server-services/tasks.md new file mode 100644 index 000000000..c4cf9aa60 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-discover-server-services/tasks.md @@ -0,0 +1,11 @@ +# Tasks: launcher-discover-server-services + +- [x] 1. Add `lib/Service/ServiceDiscoveryService.php` over `INavigationManager::getAll('link')`, excluding LaunchPad. Verify: PHPUnit with a stubbed manager. +- [x] 2. Seed `tile.discover` in `lib/actions.seed.json` and add `GET /api/tiles/discover` with `#[NoAdminRequired]` and the action check. Verify: PHPUnit and route-reachability. +- [x] 3. Add the "Discovered on this server" section to `src/modals/WidgetPickerModal.vue`, searchable with the existing box, with the "On this dashboard" mark. Verify: Vitest. +- [x] 4. Place the tile through the existing tile call with the mapping in D2. Verify: Vitest on the payload. +- [x] 5. Playwright: discover Deck and place it. + - Written: `tests/e2e/discover-server-services.spec.ts` (Deck enabled, listed under "Discovered on this server" with its icon and LaunchPad not listed, placed in one click as an `app` tile opening `/apps/deck/`, then marked "On this dashboard"; the add flow opens through "More" → "Add app" from launchpad#1300). Open: the run against a live instance with Deck. + - 19 Nov live pass (Nextcloud 34.0.6): `tests/e2e/discover-server-services.spec.ts` passed with Deck 1.18.6, as a non-admin account; the add flow is now opened through More → Add widget (the "Add app" entry was dropped in ed8febd56). The run found that two accounts could not both name a dashboard alike ("Slug must be unique among siblings", root slugs share one namespace); a derived root slug another user holds now moves to the first free number (`DashboardServiceRootSlugTest`). +- [x] 6. Add `nl` and `en` strings, fold the delta into `openspec/specs/tiles/spec.md` on archive, and set tile-discover-containers to `built` in the parity matrix with evidence lines. + - Strings in `nl` and `en`; tile-discover-containers is `built` with evidence lines; the delta is folded into `openspec/specs/tiles/spec.md` on archive (19 Nov). diff --git a/openspec/changes/launcher-tile-sorting/.openspec.yaml b/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/.openspec.yaml similarity index 100% rename from openspec/changes/launcher-tile-sorting/.openspec.yaml rename to openspec/changes/archive/2026-11-19-launcher-tile-internal-address/.openspec.yaml diff --git a/openspec/changes/launcher-tile-internal-address/design.md b/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/design.md similarity index 100% rename from openspec/changes/launcher-tile-internal-address/design.md rename to openspec/changes/archive/2026-11-19-launcher-tile-internal-address/design.md diff --git a/openspec/changes/launcher-tile-internal-address/proposal.md b/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/proposal.md similarity index 100% rename from openspec/changes/launcher-tile-internal-address/proposal.md rename to openspec/changes/archive/2026-11-19-launcher-tile-internal-address/proposal.md diff --git a/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/screens.md b/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/screens.md new file mode 100644 index 000000000..40d5e2ad9 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpTegelBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpTegelBewerken diff --git a/openspec/changes/launcher-tile-internal-address/specs/tiles/spec.md b/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md similarity index 100% rename from openspec/changes/launcher-tile-internal-address/specs/tiles/spec.md rename to openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md diff --git a/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/tasks.md b/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/tasks.md new file mode 100644 index 000000000..af2dfe8ef --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-tile-internal-address/tasks.md @@ -0,0 +1,20 @@ +# Tasks: launcher-tile-internal-address + +- [x] 1. Add the `office_networks` key to `lib/Db/AdminSettingKey.php` and read and write it through `AdminSettingsService`, storing a list of CIDR strings; malformed ranges are rejected with 400. Verify: PHPUnit. + > `AdminSettingKey::OFFICE_NETWORKS` / `AdminSetting::KEY_OFFICE_NETWORKS`; `AdminSettingsService` stores the list through `OfficeNetworkService::normaliseRanges()` and answers `officeNetworks`, `currentAddress` and `currentAddressInOfficeNetworks`; `AdminController::updateSettings()` takes `officeNetworks`, a malformed range answers 400 and stores nothing (`OfficeNetworkServiceTest::testTheAdminSettingsStoreAndShowTheOfficeNetworks`, `AdminControllerSettingsAliasTest::testOfficeNetworksArePassedThrough`). +- [x] 2. Add `lib/Service/OfficeNetworkService.php` with `isOfficeRequest()` using `IRequest::getRemoteAddress()` and `OCP\Security\Ip\IFactory`. Verify: PHPUnit for IPv4, IPv6, empty and malformed. + > `OfficeNetworkServiceTest`: IPv4, IPv6, empty list, a malformed stored range skipped and logged, entered ranges checked. +- [x] 3. Provide `onOfficeNetwork` from `lib/Service/InitialStateBuilder.php`. Verify: initial-state contract test. + > `InitialStateBuilder::setOnOfficeNetwork()`, an optional key, set by `PageController` from the admin settings answer (`InitialStateBuilderTest`). +- [x] 4. Validate `content.internalUrl` in `lib/Service/TileUpdater.php`. Verify: PHPUnit. + > `TileUpdater::assertValidInternalUrl()` on the placement update path: http, https or a path on this instance; anything else is 400 (`TileUpdaterTest`). +- [x] 5. Add the "Office networks" section to the admin page with the "your current address" line. Verify: Vitest on the section. + > "Office networks" card on the General tab, saved on its own, with the refusal and the current-address line (`AdminSettings.officeNetworks.spec.js`). +- [x] 6. Add "Address on the office network" and the address-in-effect line to `src/modals/TileEditor.vue`. Verify: Vitest. + > `TileEditor.officeNetwork.spec.js`; Views and WidgetRenderer carry `internalUrl` from and into the placement `content`. +- [x] 7. Pick the address in `src/components/TileWidget.vue`. Verify: Vitest, then a Playwright run with the runner's range configured. + > Done in code with Vitest (`TileWidget.officeNetwork.spec.js`). The Playwright spec is `tests/e2e/launcher-tile-internal-address.spec.ts` (it lists the runner's own address as the office network, and a documentation range for the "at home" leg). Left: running it against a live instance. + - 19 Nov live pass (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): `tests/e2e/launcher-tile-internal-address.spec.ts` passed (7 of 7) with the runner's address as the office network; edit mode is now entered through More → Edit. +- [x] 8. Add `nl` and `en` strings, fold the requirements into `openspec/specs/tiles/spec.md` on archive, and set d-internal-url to `built` in the parity matrix with evidence lines. + > Partly: the 11 strings are in `nl` (translated) and `en`; the other 34 locales carry the English text so parity holds. The parity-matrix row d-internal-url is `built` with evidence lines (`openspec/parity/capabilities.json`). Left: folding the requirements into `openspec/specs/tiles/spec.md`, which happens on archive. + - The requirements are folded into `openspec/specs/tiles/spec.md` on archive (19 Nov). diff --git a/openspec/changes/platform-dashboard-theme-and-css/.openspec.yaml b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/.openspec.yaml similarity index 100% rename from openspec/changes/platform-dashboard-theme-and-css/.openspec.yaml rename to openspec/changes/archive/2026-11-19-launcher-tile-launch-types/.openspec.yaml diff --git a/openspec/changes/launcher-tile-launch-types/design.md b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/design.md similarity index 100% rename from openspec/changes/launcher-tile-launch-types/design.md rename to openspec/changes/archive/2026-11-19-launcher-tile-launch-types/design.md diff --git a/openspec/changes/launcher-tile-launch-types/proposal.md b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/proposal.md similarity index 100% rename from openspec/changes/launcher-tile-launch-types/proposal.md rename to openspec/changes/archive/2026-11-19-launcher-tile-launch-types/proposal.md diff --git a/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/screens.md b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/screens.md new file mode 100644 index 000000000..40d5e2ad9 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpTegelBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpTegelBewerken diff --git a/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/admin-settings/spec.md b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/admin-settings/spec.md new file mode 100644 index 000000000..614f22a16 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/admin-settings/spec.md @@ -0,0 +1,19 @@ +# admin-settings delta for launcher-tile-launch-types + +## ADDED Requirements + +### Requirement: Program schemes and single sign-on launch templates are admin settings (REQ-ASET-020) + +The admin settings MUST hold `tileAllowedSchemes` (stored as `tile_allowed_schemes`), a list of lower-case URL schemes a program tile may use, and `ssoLaunchTemplates` (stored as `sso_launch_templates`), a list of `{key, name, urlTemplate}` where `urlTemplate` is an https address containing `{appId}` exactly once. Both MUST be empty by default. A write MUST be refused with HTTP 400, naming the entry, when a scheme is not lower-case or is one of `javascript`, `data`, `file`, `vbscript`, `about` or `blob`, or when a template is not https, lacks or repeats `{appId}`, carries another placeholder or credentials, or reuses a key; a refused write MUST leave both lists as they were. A stored value that no longer validates MUST read as empty. With these two, `GET /api/admin/settings` (REQ-ASET-001) returns fourteen keys; the REQ-ASET-001 list is updated when this change is archived. + +#### Scenario: A script scheme cannot be allowed + +- **GIVEN** an administrator on the LaunchPad admin page +- **WHEN** they save `javascript` as an allowed scheme +- **THEN** the response is 400 naming `javascript` and the allowed list is unchanged + +#### Scenario: A launch template must be https with the app id + +- **GIVEN** an administrator defining a launch template +- **WHEN** they save `http://idp.example.nl/{appId}` +- **THEN** the response is 400 and no template is stored diff --git a/openspec/changes/launcher-tile-launch-types/specs/tiles/spec.md b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md similarity index 100% rename from openspec/changes/launcher-tile-launch-types/specs/tiles/spec.md rename to openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles/spec.md diff --git a/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md new file mode 100644 index 000000000..61d6246ad --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md @@ -0,0 +1,20 @@ +# Tasks: launcher-tile-launch-types + +## Backend + +- [x] 1. Add `tile_allowed_schemes` and `sso_launch_templates` to `lib/Db/AdminSettingKey.php` and `AdminSettingsService`, with validation (schemes lower-case, never the forbidden list; templates https with `{appId}`). Verify: PHPUnit. (verified: `lib/Service/TileLaunchSettings.php`, read and written through `AdminSettingsService` and `PUT /api/admin/settings`; tests/Unit/Service/TileLaunchSettingsTest.php; the admin-settings delta in this change records the two keys, REQ-ASET-020) +- [x] 2. Validate the `program`, `remote-desktop` and `sso` link types in `lib/Service/TileUpdater.php` as in D1. Verify: PHPUnit per type and per forbidden value. (verified: `lib/Service/TileLinkValidator.php`, called by `TileUpdater` on create and on every update with the placement's final link type, value and content; a refusal answers 400 and saves nothing; an sso tile stores the address resolved from its template on the server; `POST /api/dashboard/{dashboardId}/tile` now takes `content`; tests/Unit/Service/TileLinkValidatorTest.php, TileUpdaterTest. Other link types are left unchecked as before, so existing tiles and imports keep working; the gateway address is checked as https without credentials and without a DNS lookup, because only the browser follows it.) +- [x] 3. Add `TileLaunchController::rdp()` with `GET /api/tiles/{placementId}/rdp`, the view check and the generated file. Verify: PHPUnit on content and on 403, and route-reachability. (verified: `lib/Controller/TileLaunchController.php` checks `canViewPlacement` before the tile is read (401 signed out, 403 without view rights, 404 for a tile without a valid RDP connection), re-checks the stored connection with `TileLinkValidator::rdpConnection()` and writes it with `lib/Service/RdpFileWriter.php` (no credential field, attachment named after the tile); route in appinfo/routes.php (also under /api/v1) and documented in openapi.json; tests/Unit/Controller/TileLaunchControllerTest.php, tests/Unit/Service/RdpFileWriterTest.php, OpenApiDocumentTest for route and document agreeing.) + +## Frontend + +- [x] 4. Add the three types to `src/modals/TileEditor.vue` (scheme address, gateway or RDP fields, template picker with `NcSelect` input label and app id). Verify: Vitest. (verified: an "Opens" `NcSelect` with input label; program address with the allowed schemes named under it; gateway address or host, port, published program and RD gateway; a sign-on template `NcSelect` and an app id, with no address field; the schemes and the template names (never their addresses) reach the workspace through initial state, `InitialStateBuilder::setTileLaunchOptions()`; `src/utils/tileLaunch.js` builds the content blob `Views.vue` saves with the tile, on create too; tests: src/modals/__tests__/TileEditor.launchTypes.spec.js, src/utils/__tests__/tileLaunch.spec.js, InitialStateBuilderTest.) +- [x] 5. Render the hrefs per type in `src/components/TileWidget.vue`, with the program hint. Verify: Vitest. (verified: program tiles follow their scheme address in place and show "Nothing happened? The program may not be installed on this computer." after a click; gateway and sso tiles open the stored https address in a new tab; RDP tiles link to `/api/tiles/{placementId}/rdp`; `TileWidget` takes the placement's `content`; src/components/__tests__/TileWidget.spec.js.) +- [x] 6. Add the admin section for allowed schemes and SSO launch templates. Verify: Vitest and an axe check. (PARTLY BUILT: `src/components/admin/TileLaunchSettings.vue` on the Algemeen tab lists, adds and removes allowed schemes and sign-on templates, saving each list whole through `PUT /api/admin/settings` and showing the server's refusal with the list unchanged; remove buttons name what they remove; tested in src/components/admin/__tests__/TileLaunchSettings.spec.js. Left: the axe check, which runs in a browser against a live instance; no axe runner is installed in the unit suite.) + - 19 Nov live pass: `tests/e2e/axe-launcher-forms.spec.ts` runs axe (WCAG 2.2 AA rules, `@axe-core/playwright` 4.14.0) on `[data-testid="admin-tile-launch"]` on the General tab: no serious or critical finding. + +## Close + +- [x] 7. Playwright: SSO tile address and RDP download. Done 17 Nov 2026: `tests/e2e/tile-launch-types.spec.ts`, 3 passed on a live NC 34 (the sso tile opens the template with the URL-encoded app id in a new tab; the RDP tile downloads `<title>.rdp` with host, program and gateway and no credentials; a user who may not view the dashboard gets 403). +- [x] 8. Add `nl` and `en` strings, fold the delta into `openspec/specs/tiles/spec.md` on archive, and set tile-local-apps, tile-legacy-apps and tile-sso-app to `built` in the parity matrix with evidence lines. (PARTLY BUILT: the change's 40 new UI strings are in `l10n/nl.js` and `l10n/nl.json` (English is the source); tile-local-apps, tile-legacy-apps and tile-sso-app are `built` in `openspec/parity/capabilities.json` with evidence lines and where they are reached. Left: folding the delta into `openspec/specs/tiles/spec.md` and `admin-settings`, which happens on archive, after the browser checks of tasks 6 and 7.) + - The delta is folded into `openspec/specs/tiles/spec.md` and `openspec/specs/admin-settings/spec.md` on archive (19 Nov). diff --git a/openspec/changes/search-ai-prefix-shortcuts/.openspec.yaml b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/.openspec.yaml similarity index 100% rename from openspec/changes/search-ai-prefix-shortcuts/.openspec.yaml rename to openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/.openspec.yaml diff --git a/openspec/changes/launcher-tile-open-behaviour/design.md b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/design.md similarity index 100% rename from openspec/changes/launcher-tile-open-behaviour/design.md rename to openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/design.md diff --git a/openspec/changes/launcher-tile-open-behaviour/proposal.md b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/proposal.md similarity index 100% rename from openspec/changes/launcher-tile-open-behaviour/proposal.md rename to openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/proposal.md diff --git a/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/screens.md b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/screens.md new file mode 100644 index 000000000..40d5e2ad9 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpTegelBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpTegelBewerken diff --git a/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md new file mode 100644 index 000000000..c1e20e838 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md @@ -0,0 +1,78 @@ +# Delta for tiles: tile link target and side panel + +## ADDED Requirements + +### Requirement: A tile carries its own link target (REQ-TOB-001) + +Every tile placement MUST accept a link target of `same-tab`, `new-tab` or `side-panel` in its content, set in the tile editor by anyone who may edit the tile. The server MUST reject any other value with HTTP 400 and leave the placement unchanged. + +#### Scenario: Author makes a web tile open in the same tab + +- **GIVEN** Ella has full permission on her dashboard "Mijn werkplek" with a tile "Intranet" pointing at `https://intranet.example.nl` +- **WHEN** she opens the tile editor, sets "Opens in" to "Same tab" and saves +- **THEN** clicking "Intranet" on the Workspace page opens the intranet in the current tab + +#### Scenario: Unknown target is refused + +- **GIVEN** a tile placement on a dashboard Ella may edit +- **WHEN** a client sends `PUT /api/widgets/{placementId}` with `content.linkTarget = "popup"` +- **THEN** the response is 400 and the stored target is unchanged + +### Requirement: A dashboard sets the default target for its tiles (REQ-TOB-002) + +A dashboard MUST accept a default link target. A tile without its own target MUST use the dashboard default, and a dashboard without a default MUST keep the current rule: a web address opens in a new tab and an app opens in the same tab. + +#### Scenario: Dashboard default applies to tiles without their own choice + +- **GIVEN** the group dashboard "Team Burgerzaken" has default target "Same tab" and a tile "Zaaksysteem" with no target of its own +- **WHEN** Pieter clicks "Zaaksysteem" on the Workspace page +- **THEN** it opens in the current tab + +#### Scenario: Upgrade keeps today's behaviour + +- **GIVEN** a dashboard created before this change, with no default and tiles with no target +- **WHEN** a user clicks a tile pointing at `https://example.org` +- **THEN** it opens in a new tab, and an app tile opens in the same tab + +### Requirement: A tile can open its app in a panel beside the tiles (REQ-TOB-003) + +A tile with target `side-panel` MUST open its address in a panel on the Workspace page next to the grid, keep the grid usable, show a close button and an "Open in new tab" link, close on Escape and return focus to the tile. Only one panel MUST be open at a time. + +#### Scenario: Files opens beside the tiles + +- **GIVEN** Ella's dashboard has a tile "Bestanden" linking to the Files app with target "Panel beside the tiles" +- **WHEN** she clicks "Bestanden" +- **THEN** the Files app shows in a panel next to her tiles, and the tiles stay visible and clickable +- **AND WHEN** she presses Escape, the panel closes and focus is back on "Bestanden" + +#### Scenario: Opening a second tile replaces the panel + +- **GIVEN** the panel shows "Bestanden" +- **WHEN** Ella clicks a second panel tile "Agenda" +- **THEN** the panel shows the Calendar app and no second panel appears + +### Requirement: The panel only frames allowed pages (REQ-TOB-004) + +The panel MUST frame a Nextcloud address on the same instance, and MUST frame an outside address only when its host is on the embed allow-list (`iframe_allowed_hosts`). Otherwise, or when the page refuses to be framed, the panel MUST show a fallback card with the page title and an "Open in new tab" link, never an empty frame. + +#### Scenario: Outside host not on the allow-list + +- **GIVEN** the allow-list holds only `kaart.example.nl` and a tile points at `https://portal.example.com` with target "Panel beside the tiles" +- **WHEN** Pieter clicks the tile +- **THEN** the panel shows the fallback card "This page could not be loaded." with "Open in new tab" + +#### Scenario: Editor explains why the panel is unavailable + +- **GIVEN** Ella edits a tile pointing at `https://portal.example.com`, whose host is not on the allow-list +- **WHEN** she opens "Opens in" +- **THEN** "Panel beside the tiles" is disabled with the text "This address cannot open in the panel." + +### Requirement: Quick search opens a tile the way a click does (REQ-TOB-005) + +Activating a tile from quick search MUST use the same resolved target as clicking the tile, including the side panel. + +#### Scenario: Search result opens in the panel + +- **GIVEN** a tile "Bestanden" with target "Panel beside the tiles" +- **WHEN** Pieter types "best" in the quick-search box and presses Enter on "Bestanden" +- **THEN** the Files app opens in the panel beside the tiles diff --git a/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/tasks.md b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/tasks.md new file mode 100644 index 000000000..b9c12696c --- /dev/null +++ b/openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/tasks.md @@ -0,0 +1,30 @@ +# Tasks: launcher-tile-open-behaviour + +## Backend + +- [x] 1. Validate `content.linkTarget` (`same-tab`, `new-tab`, `side-panel`) in `lib/Service/TileUpdater.php` on create and update; unknown values return 400. Verify: PHPUnit cases for each value and for a bad value. + - `TileLinkTarget` holds the three values and the resolution order; `TileUpdater` refuses anything else on create (`linkTarget`) and update (`content.linkTarget`), which the placement controller answers with 400. `TileUpdaterTest`, `TileLinkTargetTest`. +- [x] 2. Add a nullable `default_link_target` column to `oc_launchpad_dashboards` in a new migration, with getter and setter on `lib/Db/Dashboard.php` and the same three-value check in `DashboardService::updateDashboard()`. Verify: migration test and a service test. + - Migration `Version002013Date20261114090000` (nullable `default_link_target`, app version bumped), `Dashboard::defaultLinkTarget`, and `DashboardService::updateDashboard()` validates it (empty clears). `DashboardServiceLinkTargetTest`, `Version002013Date20261114090000Test`. +- [x] 3. Expose `defaultLinkTarget` in the dashboard JSON and the initial state. Verify: controller test asserts the key. + - In `jsonSerialize()` and the viewer view (the initial state carries the serialised dashboard); `PUT /api/dashboard/{id}` takes `defaultLinkTarget` and, like placements, needs full edit rights. Serialise goldens updated. + +## Frontend + +- [x] 4. Add a "Opens in" choice (same tab, new tab, panel beside the tiles) to `src/modals/TileEditor.vue`, disabled with a reason for outside hosts that are not on the embed allow-list. Verify: Vitest on the editor. + - Radio group "Opens in" (dashboard / same tab / new tab / panel); the panel is greyed out with a reason when `validateIframeUrl` refuses an outside host. `TileEditor.opensIn.spec.js`. +- [x] 5. Add the dashboard default to `src/modals/DashboardConfigModal.vue`. Verify: Vitest on the modal. + - "Opens in" select; sent only when changed, so a metadata-only editor's save is unaffected. `DashboardConfigModal.linkTarget.spec.js`. +- [x] 6. Resolve the target in `src/components/TileWidget.vue` (tile, dashboard default, today's rule) and emit `open-in-panel` for `side-panel`. Verify: Vitest per value. + - `resolveLinkTarget` in `src/utils/tileLinkTarget.js`; a side-panel tile opens the panel through the `tilePanel` store (instead of an `open-in-panel` event chain through `Views`). `TileWidget.linkTarget.spec.js`, `tileLinkTarget.spec.js`. +- [x] 7. Build `TileSidePanel` in `src/views/WorkspaceApp.vue`: one panel, close button, Escape, focus return, refused-framing fallback card with "Open in new tab", overlay below 768px. Verify: Vitest and a Playwright run. + - Built: `components/Workspace/TileSidePanel.vue` in `WorkspaceApp` (close button, Escape, focus return, framing check with the "Open in new tab" fallback, overlay below 768px); Vitest `TileSidePanel.spec.js`, `tilePanel.spec.js`. Left open for the Playwright run, which needs a live instance. + - 19 Nov live pass (Nextcloud 34.0.6): `tests/e2e/tile-side-panel.spec.ts` passed (3 of 3) as a non-admin account: Files opens in the panel with the tiles still visible, Escape closes it and focus is back on the tile; a second panel tile replaces the panel; an outside host not on the allow-list gets the fallback card with "Open in new tab" and no frame. The two scenario texts now quote the shipped strings ("This page could not be loaded.", "This address cannot open in the panel."). +- [x] 8. Confirm quick search (`src/composables/useTileSearchHost.js`) opens a `side-panel` tile in the panel. Verify: Vitest on `activateResult`. + - Quick search clicks the rendered tile link, so it follows the same handler. `useTileSearchHost.sidePanel.spec.js`. + +## Close + +- [x] 9. Add `nl` and `en` strings, update `openspec/specs/tiles/spec.md` on archive, and set d-link-target and d-open-inside to `built` in `openspec/parity/capabilities.json` with evidence lines. + - nl strings added (`l10n/nl.js`, `l10n/nl.json`); English uses the source strings. The spec update and the parity rows are for the archive step. + - d-link-target and d-open-inside are `built` with evidence lines; the delta is folded into `openspec/specs/tiles/spec.md` on archive (19 Nov). diff --git a/openspec/changes/sharing-public-start-page/.openspec.yaml b/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/.openspec.yaml similarity index 100% rename from openspec/changes/sharing-public-start-page/.openspec.yaml rename to openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/.openspec.yaml diff --git a/openspec/changes/platform-dashboard-theme-and-css/design.md b/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/design.md similarity index 100% rename from openspec/changes/platform-dashboard-theme-and-css/design.md rename to openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/design.md diff --git a/openspec/changes/platform-dashboard-theme-and-css/proposal.md b/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/proposal.md similarity index 100% rename from openspec/changes/platform-dashboard-theme-and-css/proposal.md rename to openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/proposal.md diff --git a/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/screens.md b/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/screens.md new file mode 100644 index 000000000..7730805b1 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpBeheerAlgemeen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAlgemeen +- LpDashboardInstellingen https://identity.conduction.nl/screens/board?id=launchpad/LpDashboardInstellingen diff --git a/openspec/changes/platform-dashboard-theme-and-css/specs/dashboards/spec.md b/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md similarity index 100% rename from openspec/changes/platform-dashboard-theme-and-css/specs/dashboards/spec.md rename to openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md diff --git a/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/tasks.md b/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/tasks.md new file mode 100644 index 000000000..1f88616a4 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/tasks.md @@ -0,0 +1,22 @@ +# Tasks: platform-dashboard-theme-and-css + +## Backend + +- [x] 1. Add the four columns in a migration with getters and setters on `lib/Db/Dashboard.php`, exposed in the dashboard JSON. Verify: migration test and a serialisation test. +- [x] 2. Validate the look in `DashboardService::updateDashboard()` (hex colours, resource belongs to the dashboard or is shared, accent at least 3:1 against the background, derived text colour). Verify: PHPUnit. +- [x] 3. Add `sabberworm/php-css-parser` and `CustomCssSanitiser` as in D3. Verify: PHPUnit per dropped construct, scoping and the size cap; `composer audit` clean. +- [x] 4. Allow `custom_css` only for administrators on dashboards and add the global `custom_css` admin setting. Verify: PHPUnit for 403 on a non-admin. + +## Frontend + +- [x] 5. Add the "Look" tab to `src/modals/DashboardConfigModal.vue` with colour pickers, the resource picker and live contrast. Verify: Vitest and an axe check. +- [x] 6. Apply the look and scoped CSS in `src/views/WorkspaceApp.vue` to the dashboard region only, inserting CSS as text. Verify: Vitest. +- [x] 7. Add the admin CSS section showing what the sanitiser dropped. Verify: Vitest. + +## Close + +- [x] 8. Playwright: one dashboard's look changes nothing else; `@import` is dropped. + - Written: `tests/e2e/dashboard-look-and-css.spec.ts` (the accent drawn on the green dashboard's region only, the other dashboard and the Nextcloud header unchanged; global CSS with `@import` stored and inserted without it, the scoped rule kept, the previous CSS put back). Tick it after a live run. + - 19 Nov live pass (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): `tests/e2e/dashboard-look-and-css.spec.ts` passed (2 of 2). +- [x] 9. Add `nl` and `en` strings, fold the delta into `openspec/specs/dashboards/spec.md` on archive, and set d-theme-per-dashboard and p-custom-css to `built` in the parity matrix with evidence lines. + - The 56 strings of the Look panel and the custom CSS editor are in `nl` and `en`; d-theme-per-dashboard and p-custom-css are `built` with evidence lines; the delta is folded into `openspec/specs/dashboards/spec.md` on archive (19 Nov). diff --git a/openspec/changes/responsehelper-instance-api/.openspec.yaml b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/.openspec.yaml similarity index 100% rename from openspec/changes/responsehelper-instance-api/.openspec.yaml rename to openspec/changes/archive/2026-11-19-responsehelper-instance-api/.openspec.yaml diff --git a/openspec/changes/archive/2026-11-19-responsehelper-instance-api/proposal.md b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/proposal.md new file mode 100644 index 000000000..22933bbfa --- /dev/null +++ b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/proposal.md @@ -0,0 +1,147 @@ +# ResponseHelper: migrate from an all-static helper to an injected instance API + +> **STATUS: APPROVED by Ruben on 19 Nov 2026.** Spec-first: the spec amendment +> lands in its own PR, the code follows in the next one. `serializeList()` becomes +> an instance method like the other helpers (task 1.3), so controllers use one call +> shape. The helper now has seven methods: `invalidArgument()` was added after this +> proposal was measured. + +## Why + +`ResponseHelper` is the single largest source of PHPMD debt in this repository, by a +wide margin. + +Measured on `development` at commit `d086d16` with the PHPMD baseline deleted +(PHP 8.4, `phpmd.xml` + `phpmd-unusedparams.xml`): + +| Measure | Count | +| --- | --- | +| Total findings, baseline deleted | 443 | +| …of which `StaticAccess` | 271 | +| …of which `StaticAccess` on `ResponseHelper::*` | **219 (49% of the repo total)** | + +After the complexity burndown that accompanies this proposal the repository total +is 349, and `ResponseHelper` accounts for **218 of the 270 remaining +`StaticAccess` findings — 62% of everything left**. No other single change comes +close: retiring it would take launchpad from 349 findings to roughly 131. + +The rule is not arbitrary. `rulesets/cleancode.xml/StaticAccess` fires because a +static call is a hard-coded, non-substitutable dependency: a controller that calls +`ResponseHelper::error()` cannot have that collaborator replaced in a test, cannot +have it decorated, and cannot have its behaviour varied per deployment. That is a +real design constraint, and it is the reason the project enabled the rule. + +There is also a latent correctness issue the static form makes worse. The spec +itself records it (REQ-DASH-041, Notes): + +> The "logger optional" path in `ResponseHelper::error()` is a latent risk: a +> caller that forgets to wire the logger gets silently dropped exceptions with no +> audit trail. Future-tightening TODO: make `LoggerInterface` non-nullable in a +> follow-up change once every call site is converted. + +That future-tightening is **not achievable in the static form**. A static method +cannot hold an injected logger, so every call site must pass one explicitly, which +is exactly the thing callers forget. An injected instance receives its +`LoggerInterface` once, from the DI container, and the "forgot the logger" failure +mode disappears by construction. This proposal is therefore the enabling step for +a fix the spec has already asked for. + +## Why this is a proposal and not a patch + +**The static form is pinned by the canonical spec.** `openspec/specs/dashboards/spec.md` +does not merely describe the current implementation — it makes the static call +shape normative and then asserts it in scenarios: + +- REQ-DASH-040: *"List responses MUST be serialized via `ResponseHelper::serializeList()`"* +- REQ-DASH-040, scenario: *"WHEN a controller calls `ResponseHelper::unauthorized()`"* +- REQ-DASH-040, scenario: *"WHEN a controller calls `ResponseHelper::forbidden('Dashboard creation not allowed')`"* +- REQ-DASH-040, scenario: *"WHEN a controller calls `ResponseHelper::success(['id' => 1], 201)`"* +- REQ-DASH-040, scenario: *"WHEN a controller calls `ResponseHelper::serializeList($dashboards)`"* +- REQ-DASH-041: *"MUST translate caught exceptions … via `ResponseHelper::error()`"* +- REQ-DASH-041, scenario: *"WHEN the controller calls `ResponseHelper::error($e, 500, $logger, 'Could not save dashboard')`"* + +Unilaterally refactoring the code to `$this->responseHelper->error(...)` would put +the implementation in **direct contradiction with its own normative contract** — +seven spec statements would become false about the shipped code, and the spec would +silently become a description of a system that no longer exists. Quietly editing +the spec to match a refactor inverts the whole point of spec-driven development: +the spec would stop being a decision record and become a changelog. + +So the correct sequencing is **spec first, code second**, and the spec change needs +a human decision because it is a deliberate architectural choice, not a mechanical +cleanup. That decision is what this document asks for. + +## What Changes + +If approved, in this order: + +1. **Amend `openspec/specs/dashboards/spec.md`** — REQ-DASH-040 and REQ-DASH-041 are + restated in terms of an injected `ResponseHelper` instance. The envelope + contract (bodies, status codes, no-message-leak guarantee) is **unchanged**; + only the call shape changes, `ResponseHelper::x()` → `$this->responseHelper->x()`. +2. **Convert `ResponseHelper` to an instance class**, registered in + `lib/AppInfo/Application.php` and injected into the 18 `lib/` files that use it. + `LoggerInterface` becomes a constructor dependency. +3. **Update the 224 call sites** across those 18 files. +4. **Update the 2 test files** that reference `ResponseHelper`. +5. **Tighten `error()`** so `LoggerInterface` is no longer an optional per-call + argument — discharging the standing TODO in the REQ-DASH-041 notes. +6. **Remove the corresponding entries from `phpmd.baseline.xml`.** + +### Deliberately NOT in scope + +- No change to any response body, status code, or header. This is a call-shape + migration; every envelope stays byte-identical, and the existing scenarios + (rewritten for the instance form) are the regression net. +- No change to the other 52 non-`ResponseHelper` `StaticAccess` findings; 24 of + those are `*TableBuilder::create($schema)` in `lib/Migration`, which are + structurally static because NC's migrator instantiates migration steps itself + rather than through DI, and cannot be injected. + +## Capabilities + +### New Capabilities + +(none) + +### Modified Capabilities + +- `dashboards`: REQ-DASH-040 and REQ-DASH-041 restated for an injected instance API. + +## Impact + +**Blast radius (measured, not estimated):** + +- **18 files** under `lib/` reference `ResponseHelper::` +- **224 static call sites** in `lib/` +- **2 test files** reference `ResponseHelper` +- **218 PHPMD `StaticAccess` findings** retired — 62% of everything currently left +- `ResponseHelper` itself is small: **169 lines, 6 public static methods** + (`unauthorized`, `forbidden`, `error`, `quotaExceeded`, `success`, `serializeList`) + +**Risk:** low-to-moderate and almost entirely mechanical. The class is tiny and +stateless, and the change is uniform. The two genuine risks are: + +1. **Constructor churn in 18 controllers/services.** Several already carry + `@SuppressWarnings(PHPMD.CouplingBetweenObjects)` for constructor width; adding + one more collaborator will push some past `ExcessiveParameterList` / + `CouplingBetweenObjects` thresholds. Net PHPMD effect must be re-measured — + trading 218 `StaticAccess` for a handful of coupling findings is still a large + win, but the number should be measured, not assumed. +2. **`serializeList()` is a pure function** with no dependencies. Making it an + instance method is the least defensible part of the change on its own merits; + the argument for it is uniformity of the call shape, not testability. A + reviewer may reasonably prefer to leave `serializeList()` static, which would + leave a residue of `StaticAccess` findings. That trade-off is called out here + rather than decided unilaterally. + +**Alternative considered and rejected:** adding `ResponseHelper` to a PHPMD +`StaticAccess` exceptions list. That would make the 218 findings disappear without +changing anything real, would grant a permanent open licence for all future static +use of the class, and would leave the REQ-DASH-041 logger TODO permanently +unachievable. It is a suppression, not a fix. + +## Decision requested + +Approve, amend, or reject the migration. If approved, the spec amendment (step 1) +lands first and the code follows in its own PR. diff --git a/openspec/changes/archive/2026-11-19-responsehelper-instance-api/screens.md b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/screens.md new file mode 100644 index 000000000..699e4ffd4 --- /dev/null +++ b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: backend: response helper API, not approved diff --git a/openspec/changes/archive/2026-11-19-responsehelper-instance-api/tasks.md b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/tasks.md new file mode 100644 index 000000000..3c7075aff --- /dev/null +++ b/openspec/changes/archive/2026-11-19-responsehelper-instance-api/tasks.md @@ -0,0 +1,41 @@ +# Tasks — ResponseHelper instance API + +> Approved by Ruben on 19 Nov 2026. + +## 1. Spec amendment (must land first, on its own) + +- [x] 1.1 Amend `openspec/specs/dashboards/spec.md` REQ-DASH-040: restate the + envelope contract for an injected instance; rewrite the four scenarios that + name `ResponseHelper::unauthorized()`, `::forbidden()`, `::success()` and + `::serializeList()`. +- [x] 1.2 Amend REQ-DASH-041: restate for `$this->responseHelper->error()`; rewrite + both scenarios. +- [x] 1.3 Decide and record whether `serializeList()` stays static (it is a pure + function with no dependencies — see Impact risk 2). Decided: it becomes an + instance method, for one call shape across controllers. + +## 2. Implementation (only after 1 is merged) + +- [x] 2.1 Convert `lib/Controller/ResponseHelper.php` to an instance class with a + constructor-injected `LoggerInterface`. +- [x] 2.2 Register it in `lib/AppInfo/Application.php`. Not needed: the container autowires it (a concrete class whose one dependency is `LoggerInterface`), so no registration line adds a dependency on it. +- [x] 2.3 Inject it into the 18 `lib/` files that use it; convert all 224 call sites. +- [x] 2.4 Make `LoggerInterface` non-optional in `error()`, discharging the standing + TODO in the REQ-DASH-041 notes. +- [x] 2.5 Update the 2 test files referencing `ResponseHelper`. + +## 3. Verification + +- [x] 3.1 Full unit suite green (baseline 1525 tests / 3877 assertions / 3 skipped). Green at 5227 tests, 13 skipped (#1328). +- [x] 3.2 Re-measure PHPMD with the baseline deleted. Expect ~218 `StaticAccess` + findings retired. **Measure the net** — constructor widening may add + `ExcessiveParameterList` / `CouplingBetweenObjects` findings (Impact risk 1). +- [x] 3.3 Remove the corresponding entries from `phpmd.baseline.xml`. +- [x] 3.4 Confirm no response body, status code or header changed. + +## Outcome + +- 20 controllers (not 18: two gained helper calls since the proposal) take `ResponseHelper` as their last constructor argument; 197 call sites converted. Private static helpers that answer through it became instance methods. +- `error()` has no logger argument; the one caller that passed one (`PeopleWidgetController`) lost its now unused logger. +- PHPMD, measured on the touched controllers with an empty baseline: no `StaticAccess` on `ResponseHelper` remains. The debt was hidden by 14 file-level `StaticAccess` entries in `phpmd.baseline.xml` and by the `@SuppressWarnings(PHPMD.StaticAccess)` on three controllers, not reported; those entries and suppressions are removed. The three controllers that still call other classes statically keep their entry. No new `ExcessiveParameterList` or `CouplingBetweenObjects` finding (`AdminSettingsController` stays at 13, as on `development`). +- Envelopes unchanged: the golden tests (`ResponseHelperEnvelopeGoldenTest`, the guard golden tests) pass unmodified apart from how they build the helper. New `ResponseHelperTest` (6) covers the REQ-DASH-040/041 scenarios. diff --git a/openspec/changes/competitor-parity-2026-09/.openspec.yaml b/openspec/changes/archive/2026-11-20-competitor-parity-2026-09/.openspec.yaml similarity index 100% rename from openspec/changes/competitor-parity-2026-09/.openspec.yaml rename to openspec/changes/archive/2026-11-20-competitor-parity-2026-09/.openspec.yaml diff --git a/openspec/changes/competitor-parity-2026-09/proposal.md b/openspec/changes/archive/2026-11-20-competitor-parity-2026-09/proposal.md similarity index 100% rename from openspec/changes/competitor-parity-2026-09/proposal.md rename to openspec/changes/archive/2026-11-20-competitor-parity-2026-09/proposal.md diff --git a/openspec/changes/archive/2026-11-20-competitor-parity-2026-09/screens.md b/openspec/changes/archive/2026-11-20-competitor-parity-2026-09/screens.md new file mode 100644 index 000000000..b050a0a8a --- /dev/null +++ b/openspec/changes/archive/2026-11-20-competitor-parity-2026-09/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: umbrella over parity changes, each change carries its own screens diff --git a/openspec/changes/archive/2026-11-20-competitor-parity-2026-09/tasks.md b/openspec/changes/archive/2026-11-20-competitor-parity-2026-09/tasks.md new file mode 100644 index 000000000..0bcb05553 --- /dev/null +++ b/openspec/changes/archive/2026-11-20-competitor-parity-2026-09/tasks.md @@ -0,0 +1,12 @@ +# Tasks: competitor-parity-2026-09 + +- [x] 1.1 Build `dashboards-and-who-may-see-them` (discovery cluster 12, decisions D6 and D21). Archive it on merge and tick it here. + - Archived 19 Nov as `archive/2026-11-19-dashboards-and-who-may-see-them`, spec synced to `openspec/specs/dashboards-and-who-may-see-them` (10 REQ-DWMS requirements). +- [x] 2.1 Hand dossiq its half of cluster 12: case widgets contributed to a launchpad dashboard, each declaring which roles may see it. Give the lane candidate C-reporting-22 and ledger row 10.1 with it. + - Handed over 19 Nov as the dossiq openspec change `case-widgets-declare-who-may-see-them` ([ConductionNL/dossiq#6672](https://github.com/ConductionNL/dossiq/pull/6672), merged 19 Nov), with candidate C-reporting-22 and ledger row 10.1. +- [x] 2.2 Ask the openregister lane which aggregations a shipped report may rely on, so the report library does not query objects directly. + - Handed over 19 Nov as the openregister openspec change `aggregations-a-shipped-report-may-rely-on` ([ConductionNL/openregister#10869](https://github.com/ConductionNL/openregister/pull/10869), open against main). +- [x] 3.1 Keep the already-covered table current: C-reporting-14 on `iframe-embed-widget`, C-reporting-22 on `dashboards` and `role-feature-permissions`. + - Checked 20 Nov against `openspec/specs/`: REQ-IFRAME-002 (admin allow-list of embeddable hosts, fail-closed), REQ-DASH-011 (group-shared dashboard type), REQ-DASH-013 (visible-to-user resolution) and REQ-RFP-001 (feature presence visibility by role) all still exist under those names, so the table stands as written. +- [x] 3.2 Add any later launchpad change that cites the gap register or the discovery sweep to the index above, in the same PR that opens it. + - Checked 20 Nov: no launchpad change other than `dashboards-and-who-may-see-them` (already indexed, archived 19 Nov) cites C-reporting candidates, the round 4 discovery sweep or the gap register. With nothing left to index, the umbrella is archived; a later change that cites the sweep names this archived umbrella in its own proposal. diff --git a/openspec/changes/widgets-people-expertise-and-fields/.openspec.yaml b/openspec/changes/archive/2026-11-21-integrations-office-tiles/.openspec.yaml similarity index 100% rename from openspec/changes/widgets-people-expertise-and-fields/.openspec.yaml rename to openspec/changes/archive/2026-11-21-integrations-office-tiles/.openspec.yaml diff --git a/openspec/changes/integrations-office-tiles/design.md b/openspec/changes/archive/2026-11-21-integrations-office-tiles/design.md similarity index 100% rename from openspec/changes/integrations-office-tiles/design.md rename to openspec/changes/archive/2026-11-21-integrations-office-tiles/design.md diff --git a/openspec/changes/integrations-office-tiles/proposal.md b/openspec/changes/archive/2026-11-21-integrations-office-tiles/proposal.md similarity index 100% rename from openspec/changes/integrations-office-tiles/proposal.md rename to openspec/changes/archive/2026-11-21-integrations-office-tiles/proposal.md diff --git a/openspec/changes/archive/2026-11-21-integrations-office-tiles/screens.md b/openspec/changes/archive/2026-11-21-integrations-office-tiles/screens.md new file mode 100644 index 000000000..c4cf8495f --- /dev/null +++ b/openspec/changes/archive/2026-11-21-integrations-office-tiles/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpTegelToevoegen https://identity.conduction.nl/screens/board?id=launchpad/LpTegelToevoegen diff --git a/openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md b/openspec/changes/archive/2026-11-21-integrations-office-tiles/specs/office-tiles/spec.md similarity index 100% rename from openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md rename to openspec/changes/archive/2026-11-21-integrations-office-tiles/specs/office-tiles/spec.md diff --git a/openspec/changes/archive/2026-11-21-integrations-office-tiles/tasks.md b/openspec/changes/archive/2026-11-21-integrations-office-tiles/tasks.md new file mode 100644 index 000000000..71716bb5f --- /dev/null +++ b/openspec/changes/archive/2026-11-21-integrations-office-tiles/tasks.md @@ -0,0 +1,10 @@ +# Tasks: integrations-office-tiles + +- [x] 1. Implement `OfficeTilesService` (pack per user from `ITemplateManager::listCreators()` and enabled apps; create from template with free-name selection). Verify: PHPUnit. +- [x] 2. Seed `office-tiles.list` and `office-tiles.create`, and add `GET /api/office-tiles` and `POST /api/office-tiles/create`. Verify: PHPUnit and route-reachability. +- [x] 3. Add the `create` link type to `TileUpdater` validation and to `src/components/TileWidget.vue` with the name and folder dialog. Verify: Vitest and PHPUnit. +- [x] 4. Add "Office tiles" to `src/modals/WidgetPickerModal.vue`, placing one container. Verify: Vitest. +- [x] 5. Playwright with Nextcloud Office: place the pack, create a document twice, see two files. + - Written: `tests/e2e/office-tiles.spec.ts` (the pack placed through "More" → "Add app", whose entry point comes with launchpad#1300; a document created twice gives `Notulen …` and `… (2)` with the first file's etag unchanged; an unknown creator gets 400 and creates nothing). Run 20 Nov against onlyoffice 10.2.1 with a Euro-Office document server 9.3.7 (Nextcloud 34.0.6): 2 of 2 green; the pack is placed from More > Add widget, "New document" twice gives `Notulen ….docx` and `Notulen … (2).docx` with the first file's etag unchanged (#1451). +- [x] 6. Add `nl` and `en` strings, copy the spec to `openspec/specs/office-tiles/spec.md` on archive, and set int-office-tiles to `built` in the parity matrix with evidence lines. + - 21 Nov: the pack's strings ("Office tiles", the pack description, "File name", "Create", "The file could not be created.") are in `l10n/en.js` and translated in `l10n/nl.js`; int-office-tiles is `built` in `openspec/parity/capabilities.json` with `src/modals/WidgetPickerModal.vue:117` as evidence; the spec moves to `openspec/specs/office-tiles/spec.md` with this archive. diff --git a/openspec/changes/mcp-tool-surface/.openspec.yaml b/openspec/changes/archive/2026-11-21-mcp-tool-surface/.openspec.yaml similarity index 100% rename from openspec/changes/mcp-tool-surface/.openspec.yaml rename to openspec/changes/archive/2026-11-21-mcp-tool-surface/.openspec.yaml diff --git a/openspec/changes/archive/2026-11-21-mcp-tool-surface/design.md b/openspec/changes/archive/2026-11-21-mcp-tool-surface/design.md new file mode 100644 index 000000000..b7eab4fd7 --- /dev/null +++ b/openspec/changes/archive/2026-11-21-mcp-tool-surface/design.md @@ -0,0 +1,83 @@ +# Design — LaunchPad MCP Tool Surface + +## Context + +Product intent: every app action should be automatable by AI under per-agent, default-deny, granularly granted rights (hermiq's scope × reach model), and a user should be able to command the app from chat. LaunchPad's action surface is large (~120 routes) and today entirely invisible to MCP. The design questions were: which mechanism (provider vs schema-derived tools), how to cut ~120 routes into an honest tool catalogue, how to guarantee authorization parity, and what deliberately stays out. + +The fleet reference is `decidesk/lib/Mcp/` — `DecideskToolProvider` (dispatcher + `TOOL_DESCRIPTORS` constant), `McpMeetingGate` (centralised authorise(), explicitly no fail-open), `McpArgumentValidator` (typed argument checks returning structured errors), `McpMeetingScopeResolver` (caller scoping) — registered via the string DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::decidesk`. + +## Goals / Non-Goals + +**Goals:** + +- Full coverage of launchpad's *user* actions: 14 read + 35 write tools, ids `launchpad.{toolName}`. +- Scope (`read`/`create`/`update`/`delete`) × reach (`self`/`user`/`instance`/`external`) annotations on every tool so hermiq can grant per tool, default-deny writes. +- Authorization parity: tools call the same `PermissionService` / `ActionAuthService` guards as the HTTP controllers — one authorization truth. +- Human-approval flags on destructive (`delete`) and boundary-crossing (`external`) tools; audit-ready structured results. + +**Non-Goals:** + +- Building a chat UI or an agent runtime — hermiq hosts the conversation and the grant/approval/audit machinery. +- Tooling telemetry, binary uploads, editing locks, acknowledgement writes, or one-off admin plumbing (see REQ-MCP-007). +- Replacing `launchpad-ai-dashboard-assistant` — that change renders AI summaries *on* the canvas; this one puts the canvas's actions *under* AI control. No shared code. + +## Decisions + +### D1: Imperative provider for all writes; schema-derived tools for read discovery only + +**Decision**: All writes go through `LaunchPadToolProvider` handlers calling the existing service layer. The `Dashboard` schema additionally gets an `x-openregister-mcp` block (openconnector pattern) deriving only read-only `search`/`get`. + +**Alternatives considered:** + +- **Schema-derived CRUD for everything** (`x-openregister-mcp` with writes enabled): rejected. Dashboard mutations are not raw object writes — `DashboardService::createDashboard()` generates slugs, `updateDashboard()` respects locks and permission levels, widget placement runs collision handling (`PlacementService`), deletes cascade. Auto-derived writes would bypass every one of those invariants. +- **Provider-only, no schema block**: workable, but the two read paths cost one small overlay and give agents uniform object discovery across the fleet. Kept. + +**Rationale**: decidesk proved the provider shape; openconnector proved read-only schema blocks. LaunchPad needs both halves for its split of "rich service invariants on writes" vs "plain object reads". + +### D2: One tool per user action, not per route + +**Decision**: The catalogue aggregates exactly where the HTTP surface aggregates: `updateDashboard` covers rename/description/slug (as `dashboardApi#update` does), `updateWidgetPlacement` covers move/resize/restyle/reconfigure (as `widgetApi#updatePlacement` does), `setPublicationState` covers publish/unpublish/schedule (three routes, one user intent). + +**Alternatives considered:** + +- **One tool per route (~120 tools)**: rejected — floods the model's tool context, and route-level granularity (e.g. separate publish/unpublish tools) adds grant-matrix rows without adding a meaningfully different permission decision. +- **A handful of coarse tools ("manageDashboard")**: rejected — coarse tools break the grant model; hermiq cannot grant "reposition widgets but never delete dashboards" if both hide inside one tool. + +**Rationale**: the grant matrix is the sizing instrument: two actions belong in one tool iff a rights-granter would never want to split them. Rename-vs-describe: never split. Add-widget vs delete-dashboard: always split. + +### D3: Reach classification — kiosk and public links are `external`, sharing is `user`, group/template management is `instance` + +**Decision**: `createPublicShareLink`, `revokePublicShareLink`, and all three kiosk playlist writes carry reach `external`; `shareDashboard`/`replaceShares`/`unshareDashboard`/`setPublicationState` carry `user`; group-dashboard CRUD, `setGroupDefault`, and template CRUD/resync carry `instance`. + +**Alternatives considered:** + +- **Kiosk as `self`** ("it's the caller's playlist"): rejected — a kiosk playlist mints a `#[PublicPage]` token (`kiosk#render`, `/kiosk/{token}`) that serves dashboards to anonymous viewers. What a write *exposes* determines reach, not where the record lives. Same logic as public share links. + +**Rationale**: reach must encode blast radius as the rights-granter experiences it. Anything that changes who-can-see across the auth boundary is `external`; across users inside the instance is `user`; instance topology is `instance`. + +### D4: Authorization is a gate class delegating to the existing guards — never re-implemented + +**Decision**: `McpDashboardGate` wraps `PermissionService::can*()`, `ActionAuthService::requireAction()` (ADR-023), and the admin check; every handler consults it first. Errors deny (no `catch (\Throwable) → null`, per the unsafe-auth-resolver gate). Handlers then call `DashboardService` / `WidgetService` / `TileService` / `DashboardShareService` / `PublicShareService` / `KioskService` / `TemplateService` — never controllers (no HTTP self-calls), never mappers or `ObjectService` directly for writes. + +**Rationale**: The permission logic already exists, is audited, and drifts if duplicated. decidesk's `McpMeetingGate` documents the same invariants (guards return bool, no unconditional true, no Throwable-swallowing) — codified here as spec scenarios. + +### D5: Exclusions are specified, not implied + +**Decision**: REQ-MCP-007 names every real endpoint family that gets no tool and why — telemetry recorders (agents must not fabricate analytics), acknowledgement writes (compliance evidence of a *human* act), binary uploads (not chat-shaped), editing locks (interactive-session mechanics), one-off admin plumbing (wizard, imports, cleanup, bulk ops, settings surfaces). + +**Rationale**: an unlisted omission looks like an oversight and invites a future "completeness" PR to tool the acknowledgement endpoint — the one addition that would be actively harmful. The exclusion list makes the boundary a tested assertion (catalogue-closure scenario) instead of folklore. + +## Risks / Trade-offs + +- **Catalogue size (49 tools)**: large for a single provider. Mitigated by domain-grouped handler classes and the descriptor constant being a plain fixture unit tests assert against (decidesk pattern). If hermiq context budgets demand it, read tools can later be collapsed behind the schema-derived `search`/`get` without touching write semantics. +- **Grant-model drift**: scope/reach vocabulary is hermiq's; if hermiq's axes change, annotations must follow. The descriptors keep annotations as data, so this is a constant edit, not a refactor. +- **Instance-reach tools in agent hands**: template and group-dashboard tools are powerful. Defence in depth: admin gate in `McpDashboardGate` + `instance` reach requiring an explicit hermiq grant + approval gate on deletes. + +## Migration Plan + +Additive only: new `lib/Mcp/` classes, one DI alias line, one register.d overlay. No routes, no schema data changes. Rollback = remove the alias registration (tools disappear from the catalogue) — no data cleanup needed. + +## Open Questions + +- Whether hermiq wants pagination cursors on `listDashboards`/`listTemplates` results or is satisfied with the endpoint's existing limits — decide against hermiq's consumer contract during implementation. +- Whether `launchpad.forkDashboard` should accept a template *gallery id* directly or only dashboard uuids (gallery entries are dashboards, so uuid-only is likely sufficient) — confirm against `template#gallery`'s payload shape. diff --git a/openspec/changes/mcp-tool-surface/hydra.json b/openspec/changes/archive/2026-11-21-mcp-tool-surface/hydra.json similarity index 100% rename from openspec/changes/mcp-tool-surface/hydra.json rename to openspec/changes/archive/2026-11-21-mcp-tool-surface/hydra.json diff --git a/openspec/changes/archive/2026-11-21-mcp-tool-surface/proposal.md b/openspec/changes/archive/2026-11-21-mcp-tool-surface/proposal.md new file mode 100644 index 000000000..ad05e8b39 --- /dev/null +++ b/openspec/changes/archive/2026-11-21-mcp-tool-surface/proposal.md @@ -0,0 +1,56 @@ +# MCP tool surface — every launchpad action commandable from chat + +## Why + +The product direction is that every Conduction app exposes its actions as MCP tools, so any action can in principle be automated by an AI agent — and so a user can simply chat while their apps execute their commands: "add the calendar widget to my dashboard", "share the sprint dashboard with the sales group". hermiq consumes these tools under its two-axis **scope × reach** grant model: rights are granted per agent, granularly, with writes denied by default, human approval gates on destructive/external actions, and a full audit trail. + +LaunchPad currently exposes **nothing** to that surface. Verified by grep: no `OCA\Launchpad\Mcp` namespace, no `IMcpToolProvider` implementation, no `x-openregister-mcp` block anywhere in `lib/`, `appinfo/`, or `src/` (zero hits). Meanwhile the app has one of the richest user-action surfaces in the fleet — `appinfo/routes.php` registers ~120 routes over dashboards, widgets, tiles, sharing, publication, versioning, templates, locks, and admin operations. + +The fleet mechanism is proven: decidesk ships the reference implementation (`decidesk/lib/Mcp/` — `DecideskToolProvider` implementing `OCA\OpenRegister\Mcp\IMcpToolProvider`, registered under the DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::decidesk`, tool ids `decidesk.{toolName}`, with `McpMeetingGate` for authorization, `McpArgumentValidator` for input validation, and `McpMeetingScopeResolver` for caller scoping), and openconnector demonstrates schema-level `x-openregister-mcp` blocks for auto-derived read tools. This change gives launchpad the same surface, sized to its real action inventory. + +**Relation to `launchpad-ai-dashboard-assistant`**: that change points AI *at* the dashboard — AI-generated summary widgets rendered on the canvas. This change points AI at launchpad's *actions* — the dashboard becomes something an agent can build, rearrange, and share on the user's behalf. They are complementary and share no code; where the assistant change's widgets need data, they read it through widget endpoints, not through these tools. + +## What Changes + +- New `lib/Mcp/` namespace with `LaunchPadToolProvider` implementing `OCA\OpenRegister\Mcp\IMcpToolProvider`, registered in `AppInfo\Application` under the DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad`. Tool ids are `launchpad.{toolName}`. +- A full-coverage tool catalogue derived from the real controller/service surface (see spec REQ-MCP-002/003): 14 read tools and 35 write tools covering dashboard CRUD, active/default selection, forking, widget add/reposition/remove, tile CRUD, sharing, publication state, public links, versioning, metadata, group dashboards, and admin template management. +- Read tools carry `readOnlyHint: true`; every write tool is annotated with **scope** (`create` / `update` / `delete`) and **reach** (`self` / `user` / `instance` / `external`) so hermiq's grant matrix can authorize each tool individually, default-deny. +- Authorization parity: every tool routes through the exact same guards as the HTTP surface — `PermissionService::can*()`, `ActionAuthService::requireAction()` (ADR-023 matrix), and the admin checks — via a `McpDashboardGate` mirroring decidesk's `McpMeetingGate`. Argument validation via a `McpArgumentValidator` counterpart. +- A read-only `x-openregister-mcp` block (`search`/`get`, openconnector pattern) on the `Dashboard` schema for discovery parity; auto-derived CRUD **writes stay disabled** because dashboard mutations must pass through `DashboardService` invariants (slug generation, lock checks, permission levels), never raw object writes. + +## Capabilities + +### New Capabilities + +- `mcp-tools` — launchpad's MCP tool surface: catalogue, scope/reach annotations, authorization parity, and chat-command flows. + +### Modified Capabilities + +(none) + +## Impact + +**Affected code:** + +- `lib/Mcp/LaunchPadToolProvider.php` — dispatcher + tool catalogue (new) +- `lib/Mcp/McpDashboardTools.php`, `lib/Mcp/McpWidgetTools.php`, `lib/Mcp/McpSharingTools.php`, `lib/Mcp/McpAdminTools.php` — handlers grouped by domain (new) +- `lib/Mcp/McpDashboardGate.php`, `lib/Mcp/McpArgumentValidator.php` — authorization + validation (new) +- `lib/AppInfo/Application.php` — DI alias registration (string alias, no autoload at boot, per the ADR-083-safe pattern decidesk uses) +- `lib/Settings/register.d/dashboard-mcp.json` — read-only `x-openregister-mcp` overlay (new) + +**Affected APIs:** + +- No new HTTP routes. Tools call the existing service layer (`DashboardService`, `WidgetService`/`WidgetPlacementService`, `TileService`, `DashboardShareService`, `PublicShareService`, `TemplateService`) — never controllers, never raw ObjectService writes. + +**Dependencies:** + +- OpenRegister providing `OCA\OpenRegister\Mcp\IMcpToolProvider`; hermiq as the consuming agent host. Without OpenRegister the alias resolves lazily and fails only when asked for (decidesk pattern), so launchpad still boots. + +**Migration:** + +- None. Additive surface; no schema or data changes beyond the read-only MCP overlay. + +## Notes + +- Deliberately excluded from the tool surface (REQ-MCP-007): telemetry recorders (view events, tile clicks — agents must not fabricate analytics), binary upload endpoints (resources, template preview images — chat tools take JSON, not multipart), the setup wizard, Confluence import, orphaned-data cleanup, and demo showcases (one-off admin plumbing, high blast radius, no chat use case). +- Sizing note: unlike decidesk's 5-tool exemplar, launchpad's honest action inventory is large. The catalogue is still one-tool-per-user-action, not per-route: e.g. rename/describe/re-slug are all `launchpad.updateDashboard`; move/resize/style are all `launchpad.updateWidgetPlacement` — matching how `dashboardApi#update` and `widgetApi#updatePlacement` already aggregate them. diff --git a/openspec/changes/archive/2026-11-21-mcp-tool-surface/screens.md b/openspec/changes/archive/2026-11-21-mcp-tool-surface/screens.md new file mode 100644 index 000000000..730c273da --- /dev/null +++ b/openspec/changes/archive/2026-11-21-mcp-tool-surface/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWidgetKiezen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetKiezen +- No screen: a tool interface for AI agents (MCP), with no page of its own (a-agent-tools) diff --git a/openspec/changes/archive/2026-11-21-mcp-tool-surface/specs/mcp-tools/spec.md b/openspec/changes/archive/2026-11-21-mcp-tool-surface/specs/mcp-tools/spec.md new file mode 100644 index 000000000..e62700073 --- /dev/null +++ b/openspec/changes/archive/2026-11-21-mcp-tool-surface/specs/mcp-tools/spec.md @@ -0,0 +1,268 @@ +--- +capability: mcp-tools +delta: false +status: draft +--- + +# LaunchPad MCP Tool Surface + +## Context + +LaunchPad exposes its user actions as MCP tools so agents (hermiq) can execute them under per-agent, default-deny grants, and so users can command the app from chat. The provider mechanism follows the fleet reference implementation in `decidesk/lib/Mcp/` (`DecideskToolProvider`, `McpMeetingGate`, `McpArgumentValidator`, `McpMeetingScopeResolver`); the catalogue below is derived from launchpad's real route/service surface (`appinfo/routes.php`, `DashboardService`, `WidgetService`, `TileService`, `DashboardShareService`, `PublicShareService`, `TemplateService`, `KioskService`, `ReactionService`, `AcknowledgementService`). LaunchPad currently has no MCP surface at all (verified: zero `IMcpToolProvider` / `x-openregister-mcp` hits in the repo). + +Write tools are annotated on hermiq's two grant axes: + +- **scope** — what kind of mutation: `create` / `update` / `delete` (reads carry `read`). +- **reach** — whose world it touches: `self` (the caller's own dashboards/objects), `user` (grants or removes other users' access), `instance` (instance-wide: group dashboards, admin templates), `external` (crosses the authentication boundary: public links, kiosk tokens). + +## ADDED Requirements + +### Requirement: REQ-MCP-001 Provider class, DI alias, and tool id namespace + +LaunchPad MUST implement `OCA\OpenRegister\Mcp\IMcpToolProvider` in a new class `OCA\LaunchPad\Mcp\LaunchPadToolProvider` (dispatcher + catalogue constant, handlers in domain-grouped classes, per the decidesk layout). It MUST be registered in `lib/AppInfo/Application.php` under the string DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad` (string alias so registration triggers no autoload and the app boots without OpenRegister, matching decidesk's `IMcpToolProvider::decidesk` registration). Every tool id MUST use the `launchpad.{toolName}` namespace. + +#### Scenario: Provider resolves through the alias + +- **GIVEN** an instance with OpenRegister and launchpad enabled +- **WHEN** the container resolves `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad` +- **THEN** it MUST return a `LaunchPadToolProvider` instance +- **AND** every id in its catalogue MUST start with `launchpad.` + +#### Scenario: Boot without OpenRegister + +- **GIVEN** an instance where OpenRegister is not installed +- **WHEN** launchpad boots +- **THEN** app registration MUST complete without error — the alias fails only if something asks for it + +### Requirement: REQ-MCP-002 Read tool catalogue (full read coverage) + +The provider MUST expose the following read tools, each with `readOnlyHint: true` and scope `read`, reach `self` (each returns only what the caller may already see through the corresponding endpoint's guards): + +| Tool id | Backs | +|---|---| +| `launchpad.listDashboards` | `dashboardApi#visible` / `DashboardService::getVisibleToUser()` | +| `launchpad.getDashboard` | `dashboardApi#show` / `#resolved` | +| `launchpad.getActiveDashboard` | `dashboardApi#getActive` / `DashboardService::resolveActiveDashboard()` | +| `launchpad.getDashboardTree` | `dashboardApi#tree` | +| `launchpad.listGroupDashboards` | `dashboardApi#listGroup` | +| `launchpad.listWidgetTypes` | `widgetApi#listAvailable` | +| `launchpad.listTiles` | `tileApi#index` | +| `launchpad.listShares` | `dashboardShareApi#index` | +| `launchpad.listVersions` | `dashboardVersionApi#listVersions` | +| `launchpad.listTemplates` | `template#gallery` | +| `launchpad.getDashboardMetadata` | `dashboardMetadata#getMetadata` | +| `launchpad.getReactions` | `dashboardReactionApi#getReactions` | +| `launchpad.listPendingAcknowledgements` | `acknowledgement#pending` | +| `launchpad.listKioskPlaylists` | `kiosk#index` | + +#### Scenario: Read tools are marked read-only + +- **GIVEN** the provider's catalogue +- **WHEN** hermiq inspects the 14 read tools +- **THEN** each MUST carry `readOnlyHint: true` and scope `read` +- **AND** none of them MUST mutate any state when invoked + +#### Scenario: Reads return only the caller's visible set + +- **GIVEN** a caller who can see dashboards A and B but not C +- **WHEN** `launchpad.listDashboards` is invoked on their behalf +- **THEN** the result MUST contain A and B and MUST NOT contain C — identical to `GET /api/dashboards/visible` + +### Requirement: REQ-MCP-003 Write tool catalogue with scope × reach annotations (full action coverage) + +The provider MUST expose the following write tools — one tool per user action, aggregated exactly as the existing endpoints aggregate them (e.g. rename/describe/re-slug are all `updateDashboard`, matching `dashboardApi#update`; move/resize/style are all `updateWidgetPlacement`, matching `widgetApi#updatePlacement`). Each write tool MUST declare the scope and reach listed: + +**Reach `self` — the caller's own dashboards:** + +| Tool id | Backs | Scope | +|---|---|---| +| `launchpad.createDashboard` | `dashboardApi#create` / `DashboardService::createDashboard()` | create | +| `launchpad.updateDashboard` | `dashboardApi#update` / `DashboardService::updateDashboard()` | update | +| `launchpad.deleteDashboard` | `dashboardApi#delete` / `DashboardService::deleteDashboard()` | delete | +| `launchpad.switchActiveDashboard` | `dashboardApi#setActiveDashboard` / `#activate` | update | +| `launchpad.setDefaultDashboard` | `dashboardApi#setDefaultDashboard` / `DashboardService::setDefaultPreference()` | update | +| `launchpad.forkDashboard` | `dashboardApi#fork` / `DashboardService::forkAsPersonal()` — also the "use a gallery template" path | create | +| `launchpad.addWidget` | `widgetApi#addWidget` | create | +| `launchpad.updateWidgetPlacement` | `widgetApi#updatePlacement` | update | +| `launchpad.removeWidget` | `widgetApi#removePlacement` | delete | +| `launchpad.addTileToDashboard` | `widgetApi#addTile` | create | +| `launchpad.createTile` | `tileApi#create` | create | +| `launchpad.updateTile` | `tileApi#update` | update | +| `launchpad.deleteTile` | `tileApi#destroy` | delete | +| `launchpad.createDashboardVersion` | `dashboardVersionApi#createVersion` | create | +| `launchpad.restoreDashboardVersion` | `dashboardVersionApi#restoreVersion` | update | +| `launchpad.setDashboardMetadata` | `dashboardMetadata#setMetadata` | update | +| `launchpad.addReaction` | `dashboardReactionApi#addReaction` | create | +| `launchpad.removeReaction` | `dashboardReactionApi#removeReaction` | delete | + +**Reach `user` — changes other users' access:** + +| Tool id | Backs | Scope | +|---|---|---| +| `launchpad.shareDashboard` | `dashboardShareApi#create` | create | +| `launchpad.replaceShares` | `dashboardShareApi#replace` | update | +| `launchpad.unshareDashboard` | `dashboardShareApi#destroy` | delete | +| `launchpad.setPublicationState` | `dashboardApi#publish` / `#unpublish` / `#schedule` | update | + +**Reach `external` — mints or revokes anonymous access:** + +| Tool id | Backs | Scope | +|---|---|---| +| `launchpad.createPublicShareLink` | `publicShare#create` | create | +| `launchpad.revokePublicShareLink` | `publicShare#destroy` | delete | +| `launchpad.createKioskPlaylist` | `kiosk#create` | create | +| `launchpad.updateKioskPlaylist` | `kiosk#update` | update | +| `launchpad.deleteKioskPlaylist` | `kiosk#destroy` | delete | + +**Reach `instance` — instance-wide (group dashboards, admin templates):** + +| Tool id | Backs | Scope | +|---|---|---| +| `launchpad.createGroupDashboard` | `dashboardApi#createGroup` / `DashboardService::createGroupShared()` | create | +| `launchpad.updateGroupDashboard` | `dashboardApi#updateGroup` | update | +| `launchpad.deleteGroupDashboard` | `dashboardApi#deleteGroup` | delete | +| `launchpad.setGroupDefault` | `dashboardApi#setGroupDefault` | update | +| `launchpad.createTemplate` | `admin#createTemplate` / `AdminTemplateService` | create | +| `launchpad.updateTemplate` | `admin#updateTemplate` | update | +| `launchpad.deleteTemplate` | `admin#deleteTemplate` | delete | +| `launchpad.resyncTemplate` | `admin#resyncTemplate` / `TemplateResyncService` | update | + +#### Scenario: Every write tool carries both axes + +- **GIVEN** the provider's catalogue +- **WHEN** hermiq inspects any non-read tool +- **THEN** it MUST find a scope of `create`, `update`, or `delete` AND a reach of `self`, `user`, `instance`, or `external` +- **AND** no write tool MUST carry `readOnlyHint: true` + +#### Scenario: Writes are default-deny in hermiq + +- **GIVEN** an agent with no explicit grants for launchpad +- **WHEN** it attempts `launchpad.deleteDashboard` +- **THEN** hermiq MUST refuse before the tool executes — the tool's annotations exist so this decision is per-tool, not app-wide + +#### Scenario: External-reach tools are the narrowest grant + +- **GIVEN** an agent granted `create/self` and `update/self` for launchpad +- **WHEN** it attempts `launchpad.createPublicShareLink` +- **THEN** the call MUST be refused — `external` reach requires its own explicit grant + +### Requirement: REQ-MCP-004 Authorization parity with the HTTP surface + +Every tool handler MUST enforce the exact same authorization as the corresponding controller path, by calling the same service guards: `PermissionService::canViewDashboard()` / `canEditDashboard()` / `canAddWidget()` / `canRemoveWidget()` / `canCreateDashboard()`, `ActionAuthService::requireAction()` for ADR-023-gated actions, and the admin requirement for `instance`-reach tools. This MUST be centralised in a `McpDashboardGate` class (mirroring decidesk's `McpMeetingGate`: authorise() returning an allow/deny result, no `catch (\Throwable) { return null; }` fail-open shapes). A tool MUST NOT reach `ObjectService` or mappers directly for writes — all mutations go through the existing service layer so slug generation, lock checks, placement collision handling, and cascade behaviour hold. + +#### Scenario: Tool denial equals endpoint denial + +- **GIVEN** a caller for whom `PUT /api/dashboard/{id}` would return a permission error +- **WHEN** the same caller's agent invokes `launchpad.updateDashboard` for that dashboard +- **THEN** the tool MUST deny with a structured error, thrown as a `McpToolRefusedException` (REQ-MCP-010) +- **AND** no partial mutation MUST occur + +#### Scenario: Admin tools require admin + +- **GIVEN** a non-admin caller +- **WHEN** their agent invokes `launchpad.createTemplate` +- **THEN** the gate MUST deny exactly as `admin#createTemplate` does for that caller + +#### Scenario: No fail-open on gate errors + +- **GIVEN** the authorization service throws during a tool call +- **WHEN** the gate evaluates the request +- **THEN** the result MUST be a denial, never a silent allow + +### Requirement: REQ-MCP-005 Argument validation before any service call + +Every tool MUST validate its arguments against its declared `inputSchema` before touching a service, via a `McpArgumentValidator` (decidesk pattern: typed UUID/date/string-length checks returning a structured error array on failure). Invalid arguments MUST produce a validation error, never a service call with coerced values. The provider throws that error as a `McpToolRefusedException` (REQ-MCP-010); no other exception escapes the provider. + +#### Scenario: Malformed UUID is rejected + +- **GIVEN** an agent invokes `launchpad.getDashboard` with `dashboardUuid: "../../etc"` +- **WHEN** the validator runs +- **THEN** the tool MUST return a validation error without any service or database access + +#### Scenario: Out-of-range grid values are rejected + +- **GIVEN** `launchpad.updateWidgetPlacement` is invoked with a negative `gridWidth` +- **WHEN** the validator runs +- **THEN** the tool MUST return a validation error naming the offending field + +### Requirement: REQ-MCP-006 Destructive and external tools are flagged for human approval and audited + +Tools with scope `delete`, and all tools with reach `external`, MUST carry a destructive/approval annotation so hermiq inserts its human approval gate before execution. Every write tool invocation (allowed or denied) MUST be auditable: the provider returns enough structured context (tool id, target uuid/id, caller uid, outcome) for hermiq's audit trail to record the action. For a denied call that context travels on the thrown `McpToolRefusedException` (`getResult()['audit']`). + +#### Scenario: Delete requires approval + +- **GIVEN** a user tells the chat "delete my old sales dashboard" +- **WHEN** the agent resolves this to `launchpad.deleteDashboard` +- **THEN** hermiq MUST present a human approval step before the tool runs +- **AND** the approval and execution MUST both land in the audit trail + +#### Scenario: Public link requires approval + +- **GIVEN** an agent invokes `launchpad.createPublicShareLink` +- **WHEN** hermiq evaluates the call +- **THEN** the external-reach annotation MUST trigger the approval gate even if the agent holds a `create/external` grant + +### Requirement: REQ-MCP-007 Deliberate exclusions from the tool surface + +The following real endpoints MUST NOT get tools, and the catalogue MUST stay closed against them without an explicit spec change: + +- **Telemetry recorders** — `dashboardApi#viewEvent`, `tileAnalytics#recordClick`: an agent invoking these fabricates analytics. +- **Acknowledgements (write)** — `acknowledgement#acknowledge`: a mandatory-read acknowledgement is compliance evidence of a *human* act; an agent must never acknowledge on a user's behalf. (The read side, `listPendingAcknowledgements`, is exposed.) +- **Binary upload endpoints** — `resource#upload`/`#uploadMultipart`, `admin#uploadTemplatePreviewImage`, `filesWidget#upload`: multipart/base64 payloads are not chat-tool shaped; revisit if a file-reference contract lands. +- **Editing locks** — `dashboardLockApi#*`: locks serialize *interactive* editing sessions; tool calls are single atomic service operations and must not hold or break user locks. +- **One-off admin plumbing** — setup wizard, Confluence import, orphaned-data cleanup, demo showcases, bulk operations, export/import, role/metadata-field/org-navigation/footer/settings administration: high blast radius, no chat use case; deliberately out of v1. + +#### Scenario: Catalogue contains no excluded tool + +- **GIVEN** the provider's catalogue +- **WHEN** its ids are compared against the exclusion list +- **THEN** no tool MUST exist for any excluded endpoint +- **AND** the catalogue MUST contain exactly the tools of REQ-MCP-002 and REQ-MCP-003 + +### Requirement: REQ-MCP-008 Chat command flows resolve to tool sequences + +The catalogue MUST be sufficient for hermiq to execute common chat commands as short tool sequences using only declared tools, with all resolution (name → uuid, widget label → widgetKey) done via read tools first. + +#### Scenario: "Add the calendar widget to my dashboard" + +- **GIVEN** a user with an active personal dashboard and an agent granted `read/self` and `create/self` +- **WHEN** the user sends "add the calendar widget to my dashboard" +- **THEN** the agent MUST be able to resolve it as `launchpad.getActiveDashboard` → `launchpad.listWidgetTypes` (find the calendar widgetKey) → `launchpad.addWidget` +- **AND** the widget MUST appear on the dashboard exactly as if added through the UI + +#### Scenario: "Share my team dashboard with the sales group" + +- **GIVEN** an agent granted `read/self` and `create/user` +- **WHEN** the user sends "share my team dashboard with the sales group" +- **THEN** the agent MUST resolve the dashboard via `launchpad.listDashboards`, then invoke `launchpad.shareDashboard` with a group share for `sales` +- **AND** the share MUST be identical to one created via `POST /api/dashboard/{id}/shares` + +#### Scenario: "Start me a dashboard from the sprint template and make it my default" + +- **GIVEN** an agent granted `read/self`, `create/self`, and `update/self` +- **WHEN** the user sends the command +- **THEN** the agent MUST resolve it as `launchpad.listTemplates` → `launchpad.forkDashboard` → `launchpad.setDefaultDashboard` +- **AND** `launchpad.listTemplates` MUST offer only the templates for the caller's groups (a template without groups is offered to everyone), and `launchpad.forkDashboard` MUST accept exactly those (admin-templates REQ-TMPL-018) +- **AND** the resulting dashboard MUST be the caller's default landing dashboard + +### Requirement: REQ-MCP-010 A refusal reaches the agent as an error + +OpenRegister marks a tool answer `isError: true` only when the provider throws. When a LaunchPad tool refuses (no permission, a target that does not exist, invalid input, or an unknown tool id), `LaunchPadToolProvider::invokeTool()` MUST throw a `McpToolRefusedException` instead of returning the refusal. Its message MUST be `<error code>: <message>`, and `getErrorCode()` and `getResult()` MUST carry the refusal as the tool built it, audit record included for a write tool. A tool that succeeds MUST return its answer as before. + +#### Scenario: A refused tool answers isError true + +- **GIVEN** an agent invokes a LaunchPad tool the caller may not use, on a target that does not exist, or with invalid arguments +- **WHEN** OpenRegister runs the call +- **THEN** the answer MUST carry `isError: true` +- **AND** its text MUST name the refusal code (`forbidden`, `not_found` or `invalid_arguments`) and message + +### Requirement: REQ-MCP-009 Read-only x-openregister-mcp block on the Dashboard schema + +A register.d overlay MUST declare `x-openregister-mcp` on the `Dashboard` schema with auto-derived **read** tools only (`search`, `get` with `readOnlyHint: true`, openconnector pattern). Auto-derived CRUD writes MUST NOT be enabled: dashboard mutations bypass `DashboardService` invariants (slug generation, permission levels, lock checks) if written as raw objects, so all writes stay with the provider tools of REQ-MCP-003. + +#### Scenario: Schema-derived tools are read-only + +- **GIVEN** the imported Dashboard schema +- **WHEN** OpenRegister derives MCP tools from its `x-openregister-mcp` block +- **THEN** only `search` and `get` MUST be derived, both read-only +- **AND** no derived create/update/delete tool MUST exist for the Dashboard schema diff --git a/openspec/changes/archive/2026-11-21-mcp-tool-surface/tasks.md b/openspec/changes/archive/2026-11-21-mcp-tool-surface/tasks.md new file mode 100644 index 000000000..1849ac458 --- /dev/null +++ b/openspec/changes/archive/2026-11-21-mcp-tool-surface/tasks.md @@ -0,0 +1,101 @@ +# Tasks — mcp-tool-surface + +## Provider Skeleton + +- [x] Task 1: REQ-MCP-001 — Create `lib/Mcp/LaunchPadToolProvider.php` implementing `OCA\OpenRegister\Mcp\IMcpToolProvider`: dispatcher only, tool catalogue as a `TOOL_DESCRIPTORS` class constant (unit-testable fixture), routing to domain handler classes — mirror `decidesk/lib/Mcp/DecideskToolProvider.php` +- [x] Task 2: REQ-MCP-001 — Register the string DI alias `'OCA\\OpenRegister\\Mcp\\IMcpToolProvider::launchpad'` in `lib/AppInfo/Application::register()` (string alias, no autoload at registration — decidesk's `DomainServiceRegistrar` pattern, ADR-083 boot safety) +- [x] Task 3: REQ-MCP-001 — All tool ids namespaced `launchpad.{toolName}`; add a unit test asserting the namespace and id uniqueness across the catalogue + +## Gate and Validator + +- [x] Task 4: REQ-MCP-004 — Create `lib/Mcp/McpDashboardGate.php`: `currentUserId()`, `authorise(toolId, args)` delegating to `PermissionService::canViewDashboard()/canEditDashboard()/canAddWidget()/canRemoveWidget()/canCreateDashboard()`, `ActionAuthService::requireAction()` for ADR-023-gated actions, and the admin check for `instance`-reach tools. No `catch (\Throwable) { return null; }` shapes (hydra-gate-unsafe-auth-resolver) +- [x] Task 5: REQ-MCP-005 — Create `lib/Mcp/McpArgumentValidator.php`: UUID, id, string-length, enum, and grid-bound checks returning structured error arrays (decidesk's validator as the template) +- [x] Task 6: REQ-MCP-004 — Every handler: validate → authorise → call the existing service (`DashboardService`, `WidgetService`/`WidgetPlacementService`, `TileService`, `DashboardShareService`, `PublicShareService`, `KioskService`, `TemplateService`/`AdminTemplateService`, `ReactionService`, `AcknowledgementService`, `MetadataService`, `DashboardVersionService`). Never controllers, never mappers/ObjectService directly for writes + - Every handler checks its arguments, then the route's action and per-object check, then calls the route's service; none calls a controller, and every write goes through a service. + +## Read Tools (REQ-MCP-002) + +- [x] Task 7: Implement the 14 read tools in `lib/Mcp/McpDashboardTools.php` (dashboard reads) and sibling handler classes: listDashboards, getDashboard, getActiveDashboard, getDashboardTree, listGroupDashboards, listWidgetTypes, listTiles, listShares, listVersions, listTemplates, getDashboardMetadata, getReactions, listPendingAcknowledgements, listKioskPlaylists — all `readOnlyHint: true`, scope `read`, reach `self` + - All 14 built. The eight added: `McpCatalogueTools` (getDashboardTree, listTemplates), `McpSharingTools` (listShares, listKioskPlaylists), `McpHistoryTools` (listVersions), `McpMetadataTools` (getDashboardMetadata, with the gate's new `requireView()` over `PermissionService::canViewDashboard()`), `McpEngagementTools` (getReactions, listPendingAcknowledgements). Each applies its route's check (the ADR-023 action, or only a session where the route asks none) and calls its route's service. The provider resolves each tool's handler from the container through `TOOL_HANDLERS` when the tool runs. +- [x] Task 8: REQ-MCP-002 — Unit test: each read tool's result for a fixture caller equals the visibility the corresponding service call grants that caller (visible-set parity, not superset) + - `McpCatalogueToolsTest`, `McpSharingToolsTest`, `McpDashboardDetailToolsTest`, with the existing `McpDashboardToolsTest` and `McpTileToolsTest`: each tool answers exactly what its service gives the fixture caller, and a refused caller reaches no service. + +## Write Tools (REQ-MCP-003) + +- [x] Task 9: Implement the 18 `self`-reach write tools (dashboard CRUD, active/default, fork, widget add/update/remove, tile CRUD + addTileToDashboard, version create/restore, metadata set, reaction add/remove) with per-tool `inputSchema` + - All 18 built: createDashboardVersion, restoreDashboardVersion, setDashboardMetadata, addReaction, removeReaction; addWidget, updateWidgetPlacement, removeWidget, addTileToDashboard (`McpWidgetTools`); createTile, updateTile and deleteTile, backed by the widget path with type `tile` because the tile routes answer 410 Gone (Ruben, 19 Nov 2026). updateWidgetPlacement leaves calculated fields, the acknowledgement settings and the content of a widget whose calculated fields OpenRegister stores to the app, whose route re-materialises them. The dashboard tools are `McpDashboardWriteTools` (createDashboard, updateDashboard, deleteDashboard, switchActiveDashboard, setDefaultDashboard, forkDashboard); updateDashboard changes the name, description, icon, parent, slug and sort order, behind the metadata edit check the route applies to those fields, and saves an automatic version as the route does. +- [x] Task 10: Implement the 4 `user`-reach tools (shareDashboard, replaceShares, unshareDashboard, setPublicationState) + - `McpSharingTools` (shareDashboard, replaceShares, unshareDashboard) over `DashboardShareService`, and `McpDashboardWriteTools::setPublicationState()` (published, draft, scheduled) over `DashboardService`, behind `dashboard.publish` / `unpublish` / `schedule`. Test: `McpReachToolsTest`. +- [x] Task 11: Implement the 5 `external`-reach tools (createPublicShareLink, revokePublicShareLink, createKioskPlaylist, updateKioskPlaylist, deleteKioskPlaylist) + - `McpPublicLinkTools` (createPublicShareLink, revokePublicShareLink) over `PublicShareService`, and the kiosk playlist tools in `McpSharingTools` over `KioskService`. Every external-reach tool carries `destructiveHint: true`. Test: `McpReachToolsTest`. +- [x] Task 12: Implement the 8 `instance`-reach tools (group dashboard CRUD, setGroupDefault, template create/update/delete/resync) + - `McpInstanceTools`: the four group dashboard tools over `DashboardService` and the four template tools over `AdminTemplateService` / the resync service; each checks `requireAdmin()` first. Test: `McpReachToolsTest`. +- [x] Task 13: REQ-MCP-003 — Unit test on the descriptor fixture: every write tool declares exactly one scope ∈ {create, update, delete} and one reach ∈ {self, user, instance, external}; no write carries `readOnlyHint: true` + - `LaunchPadToolProviderTest::testEveryToolCarriesItsGrantAnnotations` holds for every descriptor, so each write tool added later is checked too. +- [x] Task 14: REQ-MCP-006 — Annotate all `delete`-scope and all `external`-reach tools with the destructive/approval flag hermiq's approval gate consumes; every handler result includes tool id, target identifier, caller uid, and outcome for the audit trail + - Hints are top-level keys, as OpenRegister's `IMcpToolProvider::getTools()` reads them (`readOnlyHint`, `destructiveHint`); they were nested under `annotations`, where OpenRegister never saw them. The provider adds `audit: {tool, target, caller, outcome}` to every write tool's answer, refusals included. The test holds for every descriptor. + +## Exclusions (REQ-MCP-007) + +- [x] Task 15: Unit test asserting catalogue closure: the descriptor set equals exactly the REQ-MCP-002 + REQ-MCP-003 ids, and contains no tool for viewEvent, tile-click recording, `acknowledgement#acknowledge`, resource/preview/files uploads, lock endpoints, wizard, Confluence import, cleanup, demo showcases, bulk ops, export/import, or settings surfaces + - `LaunchPadToolProviderTest::testTheWriteCatalogueIsClosed` (the 35 write ids at their reach, no excluded surface) with `testTheReadCatalogueIsTheFourteenReadTools`. +- [x] Task 16: Document the exclusion rationale in the provider's class docblock so a future "completeness" sweep reads why before adding + - The class docblock of `LaunchPadToolProvider` lists the exclusions and why. + +## Schema Overlay (REQ-MCP-009) + +- [x] Task 17: Create `lib/Settings/register.d/dashboard-mcp.json` adding an `x-openregister-mcp` block to the `Dashboard` schema with read-only `search` and `get` tools (`readOnlyHint: true`, scope `read`, sensible `filters` such as title/slug/type/groupId — openconnector's endpoint block as the template). No derived writes + - `lib/Settings/register.d/dashboard-mcp.json`: `search` (filters title, slug, type, groupId) and `get`, both scope `read` and `readOnlyHint: true`; the import version moves to 1.0.6 so existing installs take it. Test: `DashboardMcpOverlayTest`. +- [x] Task 18: Verify the imported schema carries the block (check the imported schema via OpenRegister, not the file — the importer can reject silently) + - 19 Nov live pass (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): the imported Dashboard schema carries the `x-openregister-mcp` block in its configuration, and OpenRegister's `tools/list` lists `launchpad.dashboard.search` and `launchpad.dashboard.get`. + +## Authorization Parity Tests (REQ-MCP-004/005) + +- [x] Task 19: PHPUnit — for a non-owner caller: updateDashboard, deleteDashboard, addWidget, and shareDashboard tools all deny; assert no state change (subclass `ObjectEntity`-backed fixtures rather than mocking magic accessors) + - A caller without the per-dashboard right gets `forbidden` and no service call: updateDashboard (`McpDashboardWriteToolsTest`), addWidget (`McpWidgetToolsTest`), and a refusal of the share service maps to `forbidden` (`McpReachToolsTest`). The ownership rules themselves stay in the services, tested by their own suites. +- [x] Task 20: PHPUnit — non-admin caller invoking each `instance`-reach tool is denied by the gate + - `McpReachToolsTest::testInstanceToolsAreForAdministrators`: all eight instance tools refuse a non-administrator before any service call. +- [x] Task 21: PHPUnit — gate error path: a throwing PermissionService produces a denial result, never an allow +- [x] Task 22: PHPUnit — validator rejections: malformed UUID, over-long title, invalid enum, negative grid values — each returns a structured error and performs no service call + +## Integration / Chat Flows (REQ-MCP-008) + +- [x] Task 23: Integration test — "add the calendar widget": getActiveDashboard → listWidgetTypes → addWidget, assert the placement exists via `GET /api/widgets/items` equivalence + - 19 Nov live pass (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): `tests/e2e/api-direct/mcp-chat-flows.api.spec.ts` drives getActiveDashboard, listWidgetTypes and addWidget over `POST /apps/openregister/api/mcp` as a non-admin user; the placement is in `GET /api/dashboard/{id}`. The run found that OpenRegister listed none of the provider tools: it finds a provider as `OCA\<namespace>\Mcp\<namespace>ToolProvider` and the class was `LaunchpadToolProvider`; renamed to `LaunchPadToolProvider`, pinned by `LaunchPadToolProviderTest::testTheProviderLivesWhereOpenRegisterLooksForIt`. +- [x] Task 24: Integration test — "share with the sales group": listDashboards → shareDashboard(group: sales), assert parity with `POST /api/dashboard/{id}/shares` output + - 19 Nov live pass (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): same spec: listDashboards, shareDashboard(group) as a non-admin user; the share is in `GET /api/dashboard/{id}/shares` with the same id and permission level. +- [x] Task 25: Integration test — "template to default": listTemplates → forkDashboard → setDefaultDashboard, assert `GET /api/dashboards/default` returns the fork + - 19 Nov live pass: listTemplates listed the whole admin template gallery, but forkDashboard only copied a dashboard the caller can see (`DashboardService::findVisibleDashboardForFork`), so it answered `not_found` for every template it was offered. + - 20 Nov, decided (coordinator for Ruben): the gallery and listTemplates list only the templates for the caller's groups, a template without groups is offered to everyone, and forkDashboard accepts exactly what listTemplates offers (admin-templates REQ-TMPL-018). Built in `AdminTemplateService::getGallery()` / `findOfferedTemplate()` and the fork's source lookup, pinned by `AdminTemplateServiceGalleryTest` and `DashboardServiceForkTest::testForkCopiesATemplateTheGalleryOffers`. The e2e flow in `tests/e2e/api-direct/mcp-chat-flows.api.spec.ts` is no longer parked and also checks that a template for another group is neither listed nor copied; it has not run live yet. +- [x] Task 29: A refusal reaches the agent as an error (REQ-MCP-010) + - 20 Nov, decided (coordinator for Ruben): OpenRegister sets `isError: true` only when the provider throws, so `LaunchPadToolProvider::invokeTool()` throws `McpToolRefusedException` for every refusal (no permission, not found, invalid input, unknown tool), audit record included. Pinned by `LaunchPadToolProviderTest::testARefusalIsThrown` (all three kinds, read and write tool) and `testAnUnknownToolIsRefused`; the e2e `a refused tool answers isError true` in `tests/e2e/api-direct/mcp-chat-flows.api.spec.ts` drives it through OpenRegister and has not run live yet. + - 20 Nov live run (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, development with #1447): `tests/e2e/api-direct/mcp-chat-flows.api.spec.ts` 4 of 4 green, including template to default for the caller's groups and a refused tool answering `isError: true`. + +## Quality & Integration + +- [x] Task 26: `composer check:strict` clean (PHPCS, PHPMD, Psalm, PHPStan) including the new `lib/Mcp/` namespace; SPDX headers on every new PHP file (hydra-gate-spdx) + - `lib/Mcp/` has no PHPCS, PHPMD (both rule sets), Psalm or PHPStan finding, and every file there carries an SPDX header. The PHPMD findings it had are fixed, not suppressed: the validator's `id()` is `positiveId()`, the `required` flag on `string()` and `oneOf()` is gone in favour of `optional()`, and `McpDashboardTools` refuses through its injected validator. The no-argument read tools carry the suppression the other tool classes use. Repo-wide `check:strict` stays red on files outside `lib/Mcp/` (phpcs in the Analytics/Admin contexts, the 387 psalm `MissingOverrideAttribute`-led findings, phpmd on long controllers), the same as on development. +- [x] Task 27: Run the hydra gates; specifically confirm no orphan-auth finding (every gate method must be called) and no redundant-controller finding (no wrapper controllers were added) + - hydra-gates v1.19.0 on 19 Nov 2026: gate-6 orphan-auth PASS, gate-17 redundant-controller PASS, gate-8 unsafe-auth-resolver PASS. No failing gate names a file in `lib/Mcp/`. +- [x] Task 28: Boot test without OpenRegister installed: app registers and the launchpad UI loads (alias unresolved is acceptable; boot failure is not) + - 19 Nov live pass (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): launchpad enabled on a fresh MySQL instance without OpenRegister: `occ app:enable` succeeds, `/apps/launchpad/` answers 200 and renders (with Nextcloud's "requires openregister" notice), `GET /api/dashboards` answers 200, no error in the log. + +## Build notes + +Built so far: tasks 1 to 5, 21 and 22. `LaunchPadToolProvider` has its catalogue as `TOOL_DESCRIPTORS`. It is registered under the string alias `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad`, which is a literal, so nothing autoloads at boot. The gate (`McpDashboardGate`) applies the same ADR-023 action each HTTP route checks, plus the admin check, and denies on any exception. The validator (`McpArgumentValidator`) handles UUID, id, string length, enum and grid bounds. Four of the 14 read tools from task 7 exist: listDashboards, getDashboard, listGroupDashboards and listWidgetTypes, each calling the service its route calls. The other read tools, all write tools (tasks 9 to 14), the closure test (15), the schema overlay (17, 18), the remaining parity tests and the integration flows are open. Task 4's `PermissionService::can*()` delegation comes with the write tools that need it. + +## Verification + +`openspec validate` exits clean. Catalogue = exactly 14 read + 35 write tools, all annotated; alias resolves; parity tests green; exclusion-closure test green; the three chat flows execute end-to-end against a dev instance through hermiq or a direct provider harness. + +## Tests (company-wide ADR-009) + +PHPUnit unit tests per Tasks 3, 8, 13, 15, 19–22 (descriptor fixture + gate + validator). Integration tests per Tasks 23–25. No Playwright surface — this change ships no launchpad UI. + +## Documentation (company-wide ADR-010) + +Changelog entry: "LaunchPad actions are now available as MCP tools for AI agents (hermiq), with per-tool scope/reach grants." A docs page listing the tool catalogue with scope/reach per tool, generated from or checked against the descriptor constant so it cannot drift. + +## i18n (company-wide ADR-005) + +Tool names/descriptions are agent-facing contract strings and remain English (per the English-code rule); no user-facing UI strings are introduced. diff --git a/openspec/changes/launchpad-meeting-calendar-actions/.openspec.yaml b/openspec/changes/archive/2026-11-22-embedded-analytics/.openspec.yaml similarity index 100% rename from openspec/changes/launchpad-meeting-calendar-actions/.openspec.yaml rename to openspec/changes/archive/2026-11-22-embedded-analytics/.openspec.yaml diff --git a/openspec/changes/embedded-analytics/context-brief.md b/openspec/changes/archive/2026-11-22-embedded-analytics/context-brief.md similarity index 98% rename from openspec/changes/embedded-analytics/context-brief.md rename to openspec/changes/archive/2026-11-22-embedded-analytics/context-brief.md index 3ff58a52e..b05e12421 100644 --- a/openspec/changes/embedded-analytics/context-brief.md +++ b/openspec/changes/archive/2026-11-22-embedded-analytics/context-brief.md @@ -113,7 +113,7 @@ The embed SHALL apply the token's `tenantThemeId` (if set) by injecting `cssVari ### REQ-EMB-006 — JS-SDK exposes render, event, and resize APIs -The system SHALL publish a JS-SDK (`@launchpad/embed-sdk`, ESM and UMD builds) that exposes `LaunchPadEmbed.render(container, {token, subjectType, subjectId})`, `.on(eventType, handler)` for filter/drill/export events, and `.resize()` for host-driven layout changes. +The system SHALL publish a JS-SDK (`@conduction/launchpad-embed`, ESM and UMD builds) that exposes `LaunchPadEmbed.render(container, {token, subjectType, subjectId})`, `.on(eventType, handler)` for filter/drill/export events, and `.resize()` for host-driven layout changes. - GIVEN a host page that imports the SDK and calls `render` with a valid token WHEN the SDK initialises diff --git a/openspec/changes/archive/2026-11-22-embedded-analytics/design.md b/openspec/changes/archive/2026-11-22-embedded-analytics/design.md new file mode 100644 index 000000000..8916f4d33 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-embedded-analytics/design.md @@ -0,0 +1,302 @@ +# Design — Embedded Analytics + +## Overview + +LaunchPad widgets are today rendered only for authenticated Nextcloud users with dashboard ACL permission. Three customer classes cannot adopt LaunchPad today: + +1. **Public transparency dashboards**: Municipalities that want to publish live "openstaande WOO-verzoeken" on their public website without exposing Nextcloud. +2. **Partner-facing operational dashboards**: Shared-service organisations running LaunchPad for a consortium of municipalities, embedding each member gemeente's widget slice into the gemeente's internal intranet (avoiding mass Nextcloud account creation). +3. **In-product analytics**: SaaS vendors whose products are built on Conduction's stack, surfacing "your usage this month" inside their customer portal without iframing a full Nextcloud login flow. + +Today's auth boundary (Nextcloud session) is correct for internal organisational consumption but too narrow for these use cases. The change introduces **embed tokens** — signed JWTs that are the sole auth mechanism for embedded views, scoped to a specific widget or dashboard, rate-limited, revocable within 60 seconds, and subject to auditable telemetry. + +## Goals + +- **Flexible form factors**: Support both iframe (drop into any HTML, no JS integration) and JS-SDK (host page controls layout/sizing/events). +- **Security-first**: Signed JWTs, asymmetric crypto (RS256/ES256), no session cookies, no IP allow-lists, no anonymous embeds. Every embed has a verifiable identity that can be revoked and audited. +- **Scope enforcement**: Read-only tokens cannot mutate state even if the frontend is tampered. Filter context can be pinned. Allowed actions are explicitly listed (interact, export, drillDown). +- **Per-tenant theming**: CSS variables let the embed blend into the host page's brand without forking widget code — gemeente's colours on gemeente's intranet, SaaS vendor's colours inside their product. +- **CSP compliance**: Embeds declare host origins upfront; the render route emits `Content-Security-Policy: frame-ancestors` so the host's CSP doesn't block the iframe. +- **Usage telemetry without PII**: Every embed write captures host origin, viewport size, and user-agent family (hashed) for "did this embed get traffic?" answers. NO IP addresses, NO full UAs, NO end-user identifiers. +- **WCAG 2.1 AA compliance**: Public-facing embeds land on municipal websites with legal accessibility obligations (Web Toegankelijkheidsverordening). Build-time axe-core checks catch ~30% of violations; admin UI warns on creation. +- **Incident response**: Token revocation takes effect within 60 seconds across all render workers; a "purge cache" action available to admins gives zero-cache escalation for critical incidents. + +## Non-Goals + +- Per-resource ACL on individual assets (files, tables, records embedded by reference). Embed tokens grant access to the named widget/dashboard; ACLs on downstream entities are enforced by those entities. +- Seamless JWT refresh flows. Tokens are long-lived or non-expiring by default; refresh-token machinery is out of scope v1. +- Custom widget shapes per embed (e.g. "render this widget in 2-column layout"). Theme variables only; layout is the host page's responsibility. +- Simultaneous draft + published versions of a dashboard. Embeds point to the latest published version. +- Semantic drift from the platform-wide token-scope ADR. The JWT scope vocabulary (mode, allowedFilters, allowedActions) mirrors existing OpenConnector patterns. + +## Context + +### User stories from the field + +1. **Public WOO dashboard**: "Our gemeente wants to publish a live widget on our public website that shows outstanding WOO requests without exposing Nextcloud. Citizens should see the list, but not be able to download it." +2. **Partner intranet**: "We run LaunchPad for 8 gemeentes. Each gemeente wants their own dashboard in their internal intranet, but they don't have Nextcloud accounts. We need to embed a widget per gemeente into their own page." +3. **SaaS usage dashboard**: "Our customer portal shows 'your usage this month'. It's built in React and lives on a different domain. We want to embed a LaunchPad widget to replace a custom in-house chart." + +### JWT as the auth boundary + +Nextcloud sessions are user-centric and require a login flow. Embed tokens are widget-centric and are issued by an admin, then handed to a third party (municipal webmaster, partner org, SaaS portal team) for integration. The token is an identity that outlives any user and can be revoked independently of user lifecycle. + +**Why JWTs and not OAuth2 client credentials or other grant flows?** + +- Tokens are issued once and distributed offline (the admin hands the token to the municipal webmaster via email). OAuth would require the webmaster to stand up a server to hold credentials, which is operationally heavy. +- Tokens are read/cached/cached by stateless edge servers. JWTs carry their validity in the token itself; a stateless proxy can verify the signature without a DB call. An opaque token would require a central token-info endpoint. +- Public standards: RFC 7519 (JWT), RFC 7515 (JWS), RFC 7517 (JWK) — widely understood, widely implemented, widely audited. + +### Key rotation + +Multiple active keys are permitted so an org can rotate without breaking in-flight tokens. The key selection uses the `kid` header (RFC 7517). The rotation procedure is: + +1. Create a new signing key, mark it `status: active`. +2. Mark the old key `status: retiring` so new tokens are signed with the new key. +3. Tokens signed by the old key remain valid (the JWK's public key is available) until their expiration. +4. Once all tokens signed by the old key have expired, retire the old key to `status: revoked` (optional archival, not deletion). + +This is the pattern documented by Auth0, Okta, and the OIDC discovery spec. + +### CSP as the framing boundary + +The W3C Content Security Policy Level 3 spec mandates that a frame-ancestor must declare which origins may embed it. We emit `Content-Security-Policy: frame-ancestors <hostOrigins>` (computed from the token's `hostOrigins` list). This prevents a malicious website from tricking a user's browser into displaying our widget while claiming it's from their domain. + +Defence in depth: we also check `Sec-Fetch-Site` and `Referer` headers (Fetch Metadata Request Headers spec) so a browser/proxy that strips CSP headers still cannot spoof the origin. + +**Why explicit-allowlist instead of wildcard?** + +An admin configuring `hostOrigins: ["*"]` negates all framing protection. We reject `*` and require explicit origins per token. This matches the OWASP CSP cheat-sheet's strongest recommendation. + +## Decisions + +### D1: JWT-based tokens, not session cookies or IP allow-lists + +**Decision**: The only auth mechanism is a signed JWT token. No session cookies are issued. No IP allow-lists are supported (they don't work across CDNs and mobile networks anyway). + +**Rationale**: JWTs can be shared offline between organisations and remain valid forever (or until explicit revocation). Session cookies require a login flow. IP allow-lists are fragile and don't work for mobile users. + +**Alternatives considered**: +- OAuth2 client credentials grant. Too heavy for the use case (webmaster should not need to run a secure credential-storage server). +- Anonymous public dashboards (no token). Rejected — every embed must have a verifiable identity for audit and revocation. +- Nextcloud session + embed link. Rejected — user has to log into Nextcloud first; defeats the purpose. + +### D2: Read-only enforcement at the API tier, not the UI + +**Decision**: A token's `scope.mode` (read vs read-with-interactions) is enforced on the API tier. The backend rejects any POST/PUT/PATCH/DELETE when the token is read-only, even if the frontend is tampered. + +**Rationale**: The frontend cannot be trusted to enforce a policy that an attacker can modify. If a municipal website embeds a read-only widget on their public page, they need to know that even if someone patches the JS in DevTools, they cannot coerce a write. + +**Alternatives considered**: +- UI-only enforcement (hide buttons). Rejected — not secure against determined attackers. +- Separate endpoints for read vs write. Rejected — overcomplicates routing; the API already dispatches based on HTTP verb. + +### D3: PostMessage handshake for token injection (JS-SDK), query-parameter fallback (iframe) + +**Decision**: The JS-SDK loads an iframe without a token in the `src` URL, then posts the token to the iframe via `postMessage` after origin verification. The iframe-only form-factor accepts the token as `?token=<jwt>` in the query string for users who can't integrate a JS library. + +**Rationale**: Query-parameter tokens leak into referer headers, browser history, and proxy logs. The postMessage handshake (already used by Stripe Elements, Plaid Link, and Google Identity Services) avoids the leak while keeping the iframe-only path simple for basic usage. + +**Alternatives considered**: +- Always require postMessage. Rejected — too heavy for a one-off embed; some users just want to paste a URL into an `<iframe src>` tag. +- Bearer header injection via Service Worker. Rejected — adds a build step and browser compatibility issues. + +### D4: Rate limiting with 60-second revocation propagation window + +**Decision**: Each token has a `rateLimitPolicy` (requestsPerMinute, burstSize). Revocations are propagated to all render workers within 60 seconds via a short-TTL cache. For higher-assurance incidents, admins can invoke a "purge cache" action to drop the TTL to zero. + +**Rationale**: 60 seconds is short enough to satisfy incident-response timelines (revoke → within 1 minute, no more requests). Caching avoids DB pressure on the render route; a zero-cache option exists for critical incidents. + +**Alternatives considered**: +- Zero-cache revocation (every request hits DB). Rejected — render route throughput would suffer under high traffic. +- Eventually-consistent revocation (background sync, no max TTL). Rejected — too long for incident response. + +### D5: Telemetry captures host origin, viewport bucket, user-agent family — NO IP, NO full UA, NO end-user ID + +**Decision**: Every `embed_usage_event` writes: `hostOrigin` (from Origin header), `viewportSize` (bucketed: small/medium/large, not exact pixels), `userAgent` (browser family + major version + sha256 of full string for fingerprint analysis), `responseStatusCode`, `responseLatencyMs`. NO client IP, NO full user-agent string, NO user identifier. + +**Rationale**: Administrators can answer "did this embed get traffic?" and "is it slow?" without processing personal data. Capturing IP addresses or full UAs would require a legal basis (legitimate interest + DPIA under GDPR/AVG Article 5(1)(c)). + +**Alternatives considered**: +- Full telemetry (IP, full UA, user ID). Rejected — requires legal basis; not proportionate to the business question ("did this embed get used?"). +- No telemetry. Rejected — admins have no way to detect unused embeds or revoke tokens that are not helping. + +### D6: WCAG 2.1 AA compliance with axe-core build-time checks + +**Decision**: The embed render route produces HTML that meets WCAG 2.1 AA success criteria. The build pipeline runs axe-core automated checks on representative widget shapes. The admin UI warns (non-blocking) when creating a token for a widget with known violations. + +**Rationale**: Public-facing embeds on municipal websites have legal accessibility obligations under the Web Toegankelijkheidsverordening and EN 301 549. An embed that fails AA is a regulatory issue, not a UX bug. Automated checks catch ~30% of violations (high false-positive rate, but better than nothing). Manual review is the widget author's responsibility and is documented per-widget. + +**Alternatives considered**: +- No accessibility checks. Rejected — regulatory risk on public-sector websites. +- Hard block on embedding inaccessible widgets. Rejected — too strict; admins may choose to embed anyway and document the workaround. + +## Risks and Mitigations + +| Risk | Mitigation | +|---|---| +| Token leaked into referer header or access log (iframe form-factor) | Query-parameter tokens enforce stricter rate limits and stricter CSP. Admins are warned during token creation that iframe-form tokens are less secure. | +| Host website compromised, embed tokens exfiltrated | Tokens are scoped to a specific widget (subject-id pinning). Attacker cannot widen access to other widgets/dashboards without getting more tokens. Audit log shows which embeds exist. | +| Compromised signing key (private key leaked) | Multiple active keys permitted; old key can be retired immediately. All tokens signed by the old key are revoked. Rotation procedure is automated. | +| Public WOO widget embedded on a website, but municipality accidentally marks it read-with-interactions | Admin creates the token; responsibility is on the admin to choose the right scope. Token metadata includes scope, so audit review can catch mistakes. | +| End-user fingerprinting via user-agent telemetry | User-agent is hashed and only family+major is retained. Not enough to identify an individual. Org-level telemetry kill-switch lets admins disable all event capture. | +| Performance regression: render route adds latency | Render route adds two checks (JWT signature + rate-limit lookup) and writes one event. Both are O(1). JWT verification is fast (standard library, not custom crypto). Rate-limit and revocation lookups hit a local cache (60s TTL) before DB. Expected overhead <10ms. | + +## Seed Data + +### EmbedToken seed objects + +Three realistic scenarios for Netherlands municipalities: + +1. **Public WOO widget** — Gemeente Zeist wants to embed a live "openstaande WOO-verzoeken" widget on their public website (https://www.zeist.nl). + - name: "Gemeente Zeist — WOO intranet" + - description: "Live WOO requests for internal intranet" + - subject: {type: "widget", id: "<woo-widget-uuid>"} + - scope: {mode: "read", allowedFilters: ["status"], allowedActions: []} + - hostOrigins: ["https://intranet.zeist.nl"] + - tokenExpiresAt: null (non-expiring) + - rateLimitPolicy: {requestsPerMinute: 600, burstSize: 60} + +2. **Partner consortium dashboard** — NL Design consortium embed for Gemeente Amsterdam. + - name: "Consortium — Amsterdam operations board" + - description: "Shared-service ops dashboard for AMS gemeente" + - subject: {type: "dashboard", id: "<dashboard-uuid>", filterContext: {gemeente: "Amsterdam"}} + - scope: {mode: "read-with-interactions", allowedFilters: ["periode", "afdeling"], allowedActions: ["interact", "drillDown"]} + - hostOrigins: ["https://intranet.amsterdam.nl"] + - tenantThemeId: "<amsterdam-theme-uuid>" + - tokenExpiresAt: null + - rateLimitPolicy: {requestsPerMinute: 300, burstSize: 30} + +3. **SaaS usage widget** — Conduction customer portal embedding a monthly-usage widget. + - name: "SaaS Portal — Usage widget" + - description: "Customer usage this month (SaaS portal integration)" + - subject: {type: "widget", id: "<usage-widget-uuid>"} + - scope: {mode: "read", allowedFilters: ["month"], allowedActions: []} + - hostOrigins: ["https://portal.example.com", "https://staging-portal.example.com"] + - tenantThemeId: "<saas-vendor-theme-uuid>" + - tokenExpiresAt: "2026-12-31T23:59:59Z" (expires end of year) + - rateLimitPolicy: {requestsPerMinute: 1200, burstSize: 120} + +### TenantTheme seed objects + +1. **Gemeente Zeist brand** (slug: `theme-zeist`) + - name: "Gemeente Zeist" + - cssVariables: { + "--c-primary": "#21468B", + "--c-surface": "#FFFFFF", + "--c-text": "#1a1a1a", + "--font-family": "Inter, sans-serif", + "--c-border": "#e0e0e0" + } + - logoUrl: "https://www.zeist.nl/logo.svg" + - customCss: ":root { --spacing: 8px; }" (only :root rules allowed) + +2. **Gemeente Amsterdam brand** (slug: `theme-amsterdam`) + - name: "Gemeente Amsterdam" + - cssVariables: { + "--c-primary": "#EC0000", + "--c-surface": "#FFFFFF", + "--c-text": "#333333", + "--font-family": "Roboto, sans-serif", + "--c-border": "#cccccc" + } + - logoUrl: "https://www.amsterdam.nl/logo.svg" + +3. **SaaS vendor brand** (slug: `theme-saas-vendor`) + - name: "Example Corp" + - cssVariables: { + "--c-primary": "#6366F1", + "--c-surface": "#FFFFFF", + "--c-text": "#1F2937", + "--font-family": "\"Helvetica Neue\", Helvetica, Arial, sans-serif", + "--c-border": "#D1D5DB" + } + - logoUrl: "https://example.com/branding/logo.svg" + +### SigningKey seed objects + +1. **Active RS256 key** (slug: `key-rsa-active-1`) + - algorithm: "RS256" + - status: "active" + - publicKeyJwk: { kty: "RSA", use: "sig", ..., kid: "rsa-1" } + - privateKeyEncrypted: (encrypted with KMS) + +2. **Retiring ES256 key** (slug: `key-ecdsa-retiring`) + - algorithm: "ES256" + - status: "retiring" + - publicKeyJwk: { kty: "EC", use: "sig", crv: "P-256", ..., kid: "ec-old" } + - privateKeyEncrypted: (encrypted with KMS) + +### EmbedUsageEvent seed objects + +1. Sample page-view event from Gemeente Zeist public website. + - tokenId: "<zeist-woo-token-id>" + - eventType: "pageView" + - hostOrigin: "https://intranet.zeist.nl" + - userAgent: "Chrome 124 / sha256(Mozilla/5.0...)" + - viewportSize: "medium" + - responseStatusCode: 200 + - responseLatencyMs: 87 + - timestamp: "2026-05-22T14:30:00Z" + +2. Sample widget-rendered event from SaaS portal. + - tokenId: "<saas-usage-token-id>" + - eventType: "widgetRendered" + - hostOrigin: "https://portal.example.com" + - userAgent: "Safari 17 / sha256(Mozilla/5.0...)" + - viewportSize: "small" + - responseStatusCode: 200 + - responseLatencyMs: 156 + - timestamp: "2026-05-22T15:45:00Z" + +3. Sample filter-applied event from consortium dashboard. + - tokenId: "<amsterdam-ops-token-id>" + - eventType: "filterApplied" + - hostOrigin: "https://intranet.amsterdam.nl" + - userAgent: "Firefox 125 / sha256(Mozilla/5.0...)" + - viewportSize: "large" + - responseStatusCode: 200 + - responseLatencyMs: 45 + - timestamp: "2026-05-22T16:20:00Z" + +## Test Strategy + +- **PHPUnit**: Token issuance (jwt generation + hash persistence), JWT validation (signature + expiry + revocation status), rate limiting (bucket state, 429 responses), CSP header emission, read-only enforcement. +- **Vitest (JS-SDK)**: PostMessage handshake (token injection after origin verification), iframe load, filter event relay, resize message handling. +- **Playwright**: Full end-to-end from token creation to embedded widget rendering, filter interaction from host page, theme application (CSS variable override), rate-limit 429 behaviour. +- **Admin UI**: Token create/revoke flows, usage report rendering, accessibility axe-core results display. + +## Migration Plan + +1. **Phase 1 — Backend services**: JWT signing service (key generation + rotation), EmbedTokenService (CRUD + validation), RateLimitService. Test coverage, no user-facing endpoints yet. +2. **Phase 2 — Public render route**: GET /apps/launchpad/embed/{subjectType}/{subjectId}?token=<jwt>, CSP headers, read-only enforcement, usage telemetry. +3. **Phase 3 — Admin UI**: EmbedTokenManager component (create, revoke, view usage), tenant theme manager, signing key rotation UI. +4. **Phase 4 — JS-SDK**: @conduction/launchpad-embed package (ESM + UMD), postMessage handshake, event relay. +5. **Phase 5 — Integration**: Modify dashboard/widget rendering to accept token scope context, apply theming, wire up accessibility checks. + +## Open Questions + +1. **Should token expiry default to a fixed duration (e.g., 1 year) or be non-expiring?** + - Current decision: Non-expiring by default, with optional `tokenExpiresAt` that admins can set per token. Rationale: issued-once tokens should remain valid until explicitly revoked; forcing re-issuance on every anniversary is operationally heavy. + +2. **Should the `EmbedUsageEvent` aggregate data (e.g., "pageviews per day") or write raw events?** + - Current decision: Write raw events (every page-view is one row). Aggregation happens at query time via analytics views. Rationale: raw events support arbitrary slicing (by origin, by viewport, by time); pre-aggregation would lock us into specific dimensions. + +3. **Should the JS-SDK support Pinia/Vuex integration for two-way state sync, or is event-only (host subscribes to filterApplied) sufficient?** + - Current decision: Event-only in v1. Host page subscribes to filterApplied/drillDown/export events via `.on(eventType, handler)`. Two-way state sync is out of scope. Rationale: keeps the SDK lightweight and language-agnostic; not all host pages use Pinia. + +## Reuse Analysis + +- **OpenRegister integration**: Embeds store all persistent objects (tokens, themes, keys, events) as register objects, reusing ObjectService, AuditTrailService, ACL infrastructure. +- **Existing widget/dashboard rendering**: Embeds leverage the same widget/dashboard rendering code paths as in-app views. No widget-specific fork. Theme injection happens at the Vue root level (CSS variable injection into `:root`). +- **Nextcloud CSP + Security headers**: The embed route respects Nextcloud's CSP policy and emits appropriate headers (CSP, X-Content-Type-Options, X-Frame-Options fallback). + +## Deduplication Check + +- **Token issuance**: No overlap with Nextcloud's session/cookie issuance. Nextcloud tokens (app password, remember token) are user-centric; embed tokens are widget-centric. +- **Rate limiting**: OpenRegister has no built-in rate limiting. RateLimitService is new and specific to embed tokens. +- **Usage telemetry**: Not reusing any LaunchPad existing logging. ActivityService is user-action centric; EmbedUsageEvent is traffic-observation centric. +- **Theme injection**: Theme service is new. Widgets already support CSS variable overrides (REQ-WDG-007 or similar), but tenant-theme is a new schema for bundling multiple variables + logo + custom CSS. +- **JWT signing**: Not reusing Nextcloud's OAuth2 token logic (which is stateful and session-based). JWT is stateless and self-contained. + +**Conclusion**: No overlap found. All components are new. diff --git a/openspec/changes/embedded-analytics/hydra.json b/openspec/changes/archive/2026-11-22-embedded-analytics/hydra.json similarity index 100% rename from openspec/changes/embedded-analytics/hydra.json rename to openspec/changes/archive/2026-11-22-embedded-analytics/hydra.json diff --git a/openspec/changes/archive/2026-11-22-embedded-analytics/proposal.md b/openspec/changes/archive/2026-11-22-embedded-analytics/proposal.md new file mode 100644 index 000000000..88f747245 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-embedded-analytics/proposal.md @@ -0,0 +1,55 @@ +# Embedded Analytics + +LaunchPad widgets today require a logged-in Nextcloud session to view. This forecloses three legitimate use cases: public-facing transparency dashboards (e.g., a gemeente's live "openstaande WOO-verzoeken" on a public webpage), partner-facing operational dashboards (shared-service organisations embedding their widget slice into each member gemeente's intranet), and in-product analytics (SaaS vendors surfacing usage widgets inside their customer portal). Embedded Analytics adds a first-class answer via signed JWT tokens, iframe and JS-SDK rendering paths, per-tenant theming, WCAG AA compliance, and auditable usage telemetry. + +## Affected code units + +- **NEW** `lib/Controller/EmbedController.php` — token issuance, revocation, usage analytics +- **NEW** `lib/Service/EmbedTokenService.php` — token generation, validation, persistence +- **NEW** `lib/Service/JwtSigningService.php` — JWT lifecycle (RS256/ES256), key rotation +- **NEW** `lib/Service/RateLimitService.php` — token-bucket rate limiting per token +- **NEW** `lib/Entity/EmbedToken.php` — OpenRegister mapping for embed_token objects +- **NEW** `lib/Entity/TenantTheme.php` — OpenRegister mapping for tenant_theme objects +- **NEW** `lib/Entity/EmbedUsageEvent.php` — OpenRegister mapping for embed_usage_event objects +- **NEW** `lib/Entity/SigningKey.php` — OpenRegister mapping for signing_key objects +- **NEW** `src/components/EmbedTokenManager.vue` — admin UI for token creation, revocation, usage report +- **NEW** `@conduction/launchpad-embed` (ESM + UMD) — JS client for iframe rendering with postMessage handshake +- **NEW** `GET /apps/launchpad/embed/{subjectType}/{subjectId}?token=<jwt>` — public render route (CSP-hardened) +- **MODIFY** `src/composables/useEmbedContext.js` — detect embed mode, apply token scope and theming +- **MODIFY** Dashboard and widget rendering — enforce read-only on REQ-EMB-004 scope, apply theming on REQ-EMB-005 + +## Capabilities + +### New Capabilities + +- `embed-tokens`: Admin-only JWT token lifecycle (issuance, revocation, rotation). Tokens are the only auth mechanism for embedded views. +- `embed-render`: Public-facing HTML rendering of widgets with CSP frame-ancestors, scope enforcement, and usage telemetry. +- `tenant-themes`: Per-tenant brand bundles (CSS variables, custom CSS, logo) injected into embed contexts. +- `embed-sdk`: JavaScript client (@conduction/launchpad-embed) for host-page integration (iframe wrapper + postMessage token injection + event relay). +- `embed-usage-analytics`: Per-token usage telemetry (pageviews, interactions, host origin, viewport size) with PII minimisation. + +### Modified Capabilities + +- `widget-rendering`: Widgets now accept a token scope that restricts available actions and applies filter pinning. +- `dashboard-sharing`: Embed tokens join the existing sharing surface in the dashboard detail view (alongside "share to group"). + +## Why a new change + +The six sub-capabilities (tokens, render, theming, SDK, telemetry, WCAG) are tightly coupled and release together. Token issuance without a render path is useless; a public render without WCAG compliance is a regulatory issue on municipal websites. Splitting into six micro-changes would spawn six git branches, six PRs, and six merge conflicts while adding no architectural clarity — the coupling is real, not artificial. + +## Cross-app integration + +- **openregister**: `embed_token`, `tenant_theme`, `embed_usage_event`, and `signing_key` stored as register objects with lifecycle, ACL, soft-delete, and audit-log infrastructure. +- **openconnector + auth-system token scopes**: JWT scope vocabulary aligns with platform-wide ADRs; external IdPs can exchange credentials for launchpad tokens via RFC 8693 token-exchange flow. +- **launchpad drill-down**: Embed tokens with `read-with-interactions` mode participate in the bus exactly like in-app sessions, scoped to the embed's iframe URL. +- **opencatalogi**: Public-facing catalog embeds reuse the embed-token mechanism. +- **docudesk**: Document-preview widgets may be embedded with the document's underlying ACL enforced by docudesk (embed cannot widen access). +- **AI Chat Companion (ADR-034)**: Intentionally NOT exposed via embed tokens in v1; embeds are read/interact only. + +## Notes + +- Read-only enforcement at the API tier (REQ-EMB-004) ensures even a tampered frontend cannot coerce writes; the check is unconditional on the server side. +- CSP `frame-ancestors` is the only sanctioned framing protection (W3C CSP Level 3); `X-Frame-Options` is emitted as a fallback for legacy browsers but carries no protective claim on modern browsers. +- Rate limiting follows the token-bucket algorithm with a 60-second propagation window for revocations — a deliberate trade-off between incident-response speed and render-route throughput. +- WCAG 2.1 AA compliance is mandated by the Web Toegankelijkheidsverordening for public-sector procurements; municipal-website embeds without AA are a regulatory issue. +- Usage telemetry captures host origin, viewport bucket, and user-agent family+major (hashed) — NO IP addresses, NO full user-agents, NO end-user identifiers (GDPR/AVG Article 5(1)(c) data minimisation). diff --git a/openspec/changes/archive/2026-11-22-embedded-analytics/screens.md b/openspec/changes/archive/2026-11-22-embedded-analytics/screens.md new file mode 100644 index 000000000..60c824023 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-embedded-analytics/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpPubliek https://identity.conduction.nl/screens/board?id=launchpad/LpPubliek diff --git a/openspec/changes/archive/2026-11-22-embedded-analytics/specs/embedded-analytics/spec.md b/openspec/changes/archive/2026-11-22-embedded-analytics/specs/embedded-analytics/spec.md new file mode 100644 index 000000000..792d3df01 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-embedded-analytics/specs/embedded-analytics/spec.md @@ -0,0 +1,1428 @@ +# Embedded analytics + +Embed a live LaunchPad dashboard or widget on the organisation's own website with a scoped, revocable embed token, a JS-SDK and per-token framing, rate and telemetry rules. + +## ADDED Requirements + +### Requirement: REQ-EMB-001 — Token issuance returns JWT exactly once + +The system SHALL generate a JWT signed with the active signing key when a new `embed_token` is created, return it once in the create response, persist only the sha256 hash, and reject any subsequent request to re-retrieve the raw token. + +#### Scenario: 1.1 — Create token and receive JWT once + +GIVEN an admin user with token-management permission + AND the system has an active RS256 signing key +WHEN they POST `/api/embed-tokens` with a valid token-create payload: + ```json + { + "name": "Gemeente Zeist WOO", + "description": "Public WOO requests widget", + "subject": {"type": "widget", "id": "woo-widget-uuid"}, + "scope": {"mode": "read", "allowedFilters": ["status"], "allowedActions": []}, + "hostOrigins": ["https://intranet.zeist.nl"], + "rateLimitPolicy": {"requestsPerMinute": 600, "burstSize": 60} + } + ``` +THEN the response SHALL be 201 with body: + ```json + { + "id": "token-id-uuid", + "name": "Gemeente Zeist WOO", + "jwt": "eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...", + "warning": "keepThisSafe: This JWT is shown only once. Save it now. If lost, you must re-issue the token.", + "createdAt": "2026-05-22T14:30:00Z" + } + ``` + AND the response body SHALL include the raw JWT exactly once + AND a new row SHALL be created in `embed_token` register with: + - `id` matching the response + - `tokenHash` = sha256("eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...") + - ALL other fields matching the request + createdAt + +#### Scenario: 1.2 — Subsequent GET returns metadata but not JWT + +GIVEN an existing `embed_token` row with id="token-1" and tokenHash set +WHEN any GET request to `/api/embed-tokens/token-1` is made +THEN the response SHALL be 200 with body: + ```json + { + "id": "token-1", + "name": "Gemeente Zeist WOO", + "description": "Public WOO requests widget", + "subject": {"type": "widget", "id": "woo-widget-uuid"}, + "scope": {"mode": "read", ...}, + "hostOrigins": ["https://intranet.zeist.nl"], + "createdAt": "2026-05-22T14:30:00Z", + "createdBy": "admin-user-id", + "actions": [ + {"id": "re-issue", "label": "Re-issue token", "description": "Revoke this token and generate a new one"} + ] + } + ``` + AND the response SHALL NOT include the `jwt` field + AND the response SHALL NOT include the `tokenHash` field + +#### Scenario: 1.3 — Token creation rejects malformed hostOrigins + +GIVEN an admin user with token-management permission +WHEN they POST `/api/embed-tokens` with `hostOrigins` containing a malformed origin: + ```json + { + "name": "Bad Token", + "hostOrigins": ["https://www.example.com", "invalid-origin-missing-scheme"], + ... + } + ``` +THEN the response SHALL be 400 with body: + ```json + { + "status": "error", + "error": "invalid_hostOrigins", + "message": "Invalid origin format at index 1: missing URI scheme. Expected format: https://domain.com", + "fieldErrors": { + "hostOrigins[1]": "invalid_hostOrigins" + } + } + ``` + AND the `embed_token` row SHALL NOT be persisted + +#### Scenario: 1.4 — Re-issue token (revoke + create new) + +GIVEN an existing `embed_token` row with id="token-1" +WHEN an admin invokes the "re-issue" action via POST `/api/embed-tokens/token-1/re-issue` +THEN a new JWT SHALL be generated (signed with active key) + AND the old token's `revokedAt` SHALL be set to now + AND the old token's `revocationReason` SHALL be set to "re-issued" + AND a new `embed_token` row SHALL be created with: + - fresh `id` (new UUID) + - fresh `tokenHash` (sha256 of new JWT) + - same `subject`, `scope`, `hostOrigins`, `rateLimitPolicy` as the old token + - new `createdAt` and `createdBy` + AND the response SHALL include the new JWT (shown once) + +--- + +### Requirement: REQ-EMB-002 — Public render route validates JWT and enforces scope + +The render route SHALL verify the JWT signature against the `kid`-selected `signing_key`, reject expired or revoked tokens, enforce `subject` match, and respond with 403 on any mismatch without leaking the existence of the subject. + +#### Scenario: 2.1 — Valid non-expired token renders widget + +GIVEN a valid, non-expired, non-revoked JWT for widget W signed with RS256 key (kid=rsa-1) + AND the embedded widget renders HTML (no token scope restriction assumed yet — REQ-EMB-004 covers scope enforcement) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` +THEN the response SHALL be 200 with HTML body + AND the response SHALL include header `Content-Security-Policy: frame-ancestors <hostOrigins>` + AND the response SHALL include header `X-Content-Type-Options: nosniff` + AND the widget SHALL render with the token's context applied (e.g., filter pinning from `subject.filterContext`) + AND a `embed_usage_event` row SHALL be written with: + - `eventType: "pageView"` + - `responseStatusCode: 200` + - `responseLatencyMs: <measured>` + +#### Scenario: 2.2 — Subject mismatch returns 403 without leaking existence + +GIVEN a valid JWT for widget W + AND the admin tries to render it against widget V (different UUID) +WHEN the route is called with `GET /apps/launchpad/embed/widget/V?token=<jwt>` +THEN the response SHALL be 403 with body: + ```json + { + "error": "scope_mismatch", + "message": "The provided token does not grant access to this resource" + } + ``` + AND the response SHALL NOT indicate whether widget V exists or not + AND a `embed_usage_event` row SHALL be written with: + - `eventType: "pageView"` + - `responseStatusCode: 403` + +#### Scenario: 2.3 — Expired token returns 401 with WWW-Authenticate header + +GIVEN a JWT whose `tokenExpiresAt` is in the past (e.g., "2026-01-01T00:00:00Z" and current time is 2026-05-22) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` +THEN the response SHALL be 401 with body: + ```json + { + "error": "token_expired", + "message": "The provided token has expired" + } + ``` + AND the response SHALL include header: + `WWW-Authenticate: Bearer error="invalid_token", error_description="The token has expired"` + AND a `embed_usage_event` row SHALL be written with `responseStatusCode: 401` + +#### Scenario: 2.4 — Revoked token returns 401 with constant-time comparison + +GIVEN a JWT whose `embed_token` row has `revokedAt` set (token was revoked 5 minutes ago) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` +THEN the response SHALL be 401 with body: + ```json + { + "error": "token_revoked", + "message": "The provided token has been revoked" + } + ``` + AND the response latency SHALL be constant-time-comparable to a non-revoked rejection (to prevent timing oracle attacks) + AND a `embed_usage_event` row SHALL be written with `responseStatusCode: 401` + +#### Scenario: 2.5 — Invalid JWT signature returns 401 + +GIVEN a JWT with an invalid signature (e.g., tampered payload) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<tampered-jwt>` +THEN the response SHALL be 401 with body: + ```json + { + "error": "invalid_token", + "message": "The provided token is invalid or malformed" + } + ``` + +#### Scenario: 2.6 — Missing token returns 401 + +GIVEN a request to the embed render route without a token +WHEN the route is called with `GET /apps/launchpad/embed/widget/W` (no ?token= parameter) +THEN the response SHALL be 401 with body: + ```json + { + "error": "missing_token", + "message": "No token provided. Include ?token=<jwt> or use the Authorization: Bearer <jwt> header" + } + ``` + +#### Scenario: 2.7 — Bearer header token (SDK form-factor) + +GIVEN a valid JWT passed via Authorization header (SDK use case) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W` + header `Authorization: Bearer <jwt>` +THEN the response SHALL be 200 with HTML body (same as Scenario 2.1) + AND the response latency/rate-limit treatment SHALL be identical to query-parameter tokens + AND the response CSP/cache headers SHALL be identical + +#### Scenario: 2.8 — Query-parameter tokens enforce stricter rate limits + +GIVEN a token with `rateLimitPolicy: {requestsPerMinute: 600, burstSize: 60}` + AND requests arriving via `?token=<jwt>` (query parameter) + AND requests arriving via `Authorization: Bearer <jwt>` (header) +WHEN both form-factors are used for the same embed in the same minute +THEN the query-parameter form SHALL count against the token's configured rate limit + AND the Bearer-header form MAY have a separate (stricter) rate limit (e.g., 10× lower) to account for the token leak risk + AND the admin UI SHOULD surface this distinction in the token-creation flow + +### Requirement: REQ-EMB-003 — CSP frame-ancestors enforced from token hostOrigins + +The render route SHALL emit `Content-Security-Policy: frame-ancestors <hostOrigins>` derived from the token's `hostOrigins`, and the embed SHALL refuse to render when the iframe's actual top-level origin is not in `hostOrigins`. This is enforced both at the CSP level (modern browsers) and via Fetch Metadata headers (defence in depth). + +#### Scenario: 3.1 — Valid origin renders with CSP frame-ancestors header + +GIVEN a token with `hostOrigins=["https://www.zeist.nl"]` + AND the token is for widget W +WHEN the embed is loaded inside an iframe on `https://www.zeist.nl/woo/` +THEN the response to `GET /apps/launchpad/embed/widget/W?token=<jwt>` SHALL be 200 with HTML body + AND the response SHALL include header: + `Content-Security-Policy: frame-ancestors https://www.zeist.nl` + AND the browser SHALL render the iframe normally (CSP allows framing from https://www.zeist.nl) + +#### Scenario: 3.2 — Invalid origin blocked by CSP + server-side Sec-Fetch-Site check + +GIVEN the same token with `hostOrigins=["https://www.zeist.nl"]` +WHEN the iframe is loaded from `https://evil.example.com/phishing-page` + AND the iframe's top-level origin is `https://evil.example.com` +THEN the browser SHALL refuse to display the iframe due to CSP frame-ancestors violation + AND the server-side render route SHALL check the `Sec-Fetch-Site` header: + - If `Sec-Fetch-Site: cross-site` and top-origin from Referer ≠ allowed hostOrigins + - Then respond 403 with body `{error: "origin_mismatch", message: "This iframe cannot be embedded on this origin"}` + AND the browser still refuses to render (CSP violation takes precedence) + AND a `embed_usage_event` SHALL be written with `responseStatusCode: 403` + +#### Scenario: 3.3 — Multiple allowed origins + +GIVEN a token with `hostOrigins=["https://intranet.zeist.nl", "https://www.zeist.nl"]` +WHEN the embed is loaded from either origin +THEN the response SHALL include header: + `Content-Security-Policy: frame-ancestors https://intranet.zeist.nl https://www.zeist.nl` + AND the browser SHALL allow framing from either origin + +#### Scenario: 3.4 — Wildcard hostOrigins rejected at token creation + +GIVEN an admin user +WHEN they attempt to POST `/api/embed-tokens` with `hostOrigins=["*"]` +THEN the response SHALL be 400 with body: + ```json + { + "status": "error", + "error": "invalid_hostOrigins", + "message": "Wildcard origin '*' is not permitted. Specify explicit origins, e.g., [\"https://www.example.com\"]", + "fieldErrors": { + "hostOrigins": "wildcard_not_permitted" + } + } + ``` + AND the token SHALL NOT be created + +#### Scenario: 3.5 — X-Frame-Options fallback for legacy browsers + +GIVEN any render route response +WHEN the response is generated +THEN the response SHALL ALSO include header: + `X-Frame-Options: SAMEORIGIN` + (As a fallback for browsers that do not support CSP Level 3; no protective claim is made about X-Frame-Options sufficiency on modern browsers per W3C spec) + +#### Scenario: 3.6 — Referer header check (defence in depth) + +GIVEN a request with `Authorization: Bearer <jwt>` (Bearer header, not query param) + AND the token's `hostOrigins=["https://intranet.example.com"]` +WHEN the render route processes the request + AND the `Referer` header is `https://evil.example.com/page` +THEN the route SHALL respond 403 with body `{error: "origin_mismatch"}` + AND a `embed_usage_event` SHALL be written with `responseStatusCode: 403` + +#### Scenario: 3.7 — No Referer header (privacy-preserving browser configuration) + +GIVEN a request with no `Referer` header + AND the `Sec-Fetch-Site` header indicates `same-site` +THEN the route SHALL allow the request (assume same-origin; Referer is not available in privacy-preserving configurations) + AND a `embed_usage_event` SHALL be written with `responseStatusCode: 200` + +#### Scenario: 3.8 — Admin UI displays CSP header preview + +GIVEN the admin is creating or editing an embed token +WHEN they edit the `hostOrigins` field +THEN the admin UI SHALL display a live preview of the resulting CSP header: + ``` + Content-Security-Policy: frame-ancestors https://intranet.zeist.nl + ``` + AND a "Copy CSP header" button SHALL let them paste this into their host website's audit documentation + +### Requirement: REQ-EMB-004 — Read-only enforcement at the API tier + +The system SHALL reject any write operation (POST/PUT/PATCH/DELETE) issued under an `embed_token` whose `scope.mode=read`, even when the operation would otherwise be permitted by the subject's ACL. This enforcement happens on the API tier before any state mutation. + +#### Scenario: 4.1 — Read-mode token rejects write operation + +GIVEN an `embed_token` with `scope.mode="read"` for dashboard D + AND JavaScript running in the iframe holds this token as `Authorization: Bearer <jwt>` +WHEN it sends a write (POST/PUT/PATCH/DELETE) to a LaunchPad route that needs no Nextcloud login (a public route) +THEN the API SHALL respond 403 before the controller runs, with body: + ```json + { + "error": "read_only_token", + "message": "This token does not permit write operations. Token scope: mode=read" + } + ``` + AND NO state SHALL be mutated +WHEN it sends a write to a route that needs a Nextcloud login, such as `POST /api/dashboard/{id}/widgets` to add a widget to dashboard D +THEN Nextcloud SHALL refuse it with 401 before LaunchPad runs, because an embed token is not a Nextcloud login + AND NO state SHALL be mutated (no widget added, no audit log entry) + +#### Scenario: 4.2 — Read-mode token rejects DELETE + +GIVEN the same read-only token for dashboard D +WHEN the frontend attempts `DELETE /api/dashboards/D/widgets/w1` (remove a widget from the dashboard) +THEN the API SHALL respond 403 with body: + ```json + { + "error": "read_only_token", + "message": "This token does not permit write operations. Token scope: mode=read" + } + ``` + AND NO state mutation occurs + +#### Scenario: 4.3 — Read-mode token permits GET and HEAD + +GIVEN the same read-only token +WHEN the frontend invokes `GET /api/dashboards/D` (read operation) +THEN the API SHALL respond 200 with the dashboard data + AND read permission is determined by the subject-match (the token is scoped to dashboard D) + AND no scope-mode check blocks the read + +#### Scenario: 4.4 — Read-with-interactions token permits scoped actions + +GIVEN an `embed_token` with `scope.mode="read-with-interactions", allowedActions=["interact", "drillDown"]` for dashboard D + AND the dashboard has a filter UI +WHEN the SDK applies an in-bus filter clause (drill-down), invoking `POST /api/dashboards/D/filters` with `{dimension: "gemeente", value: "Amsterdam"}` +THEN the API SHALL respond 200 and process the filter + AND the operation SHALL be captured in an `embed_usage_event` with `eventType: "filterApplied"` + AND subsequent `GET` calls reflect the pinned filter + +#### Scenario: 4.5 — Read-with-interactions token rejects disallowed action + +GIVEN an `embed_token` with `scope.mode="read-with-interactions", allowedActions=["interact", "drillDown"]` (export NOT allowed) +WHEN the frontend attempts `POST /api/dashboards/D/export` with `format: "csv"` +THEN the API SHALL respond 403 with body: + ```json + { + "error": "action_not_in_scope", + "message": "The action 'export' is not permitted by this token. Allowed actions: interact, drillDown" + } + ``` + AND NO export is generated + +#### Scenario: 4.6 — All write operations checked, regardless of subject type + +GIVEN a read-only token for a widget W +WHEN any of the following write operations are attempted on the widget: + - `POST /api/widgets/W/interactions` (add interaction) + - `PUT /api/widgets/W/settings` (update widget settings) + - `PATCH /api/widgets/W` (partial update) +THEN ALL SHALL respond 403 with the read-only error + AND the API does NOT discriminate by operation type; ALL non-GET/HEAD are blocked + +#### Scenario: 4.7 — Scope enforcement independent of frontend state + +GIVEN a read-only token embedded in an iframe +WHEN the JavaScript in the iframe is patched (via browser DevTools) to remove the UI-layer read-only enforcement + AND the patched JS attempts `POST /api/dashboards/D/widgets/new` +THEN the API-tier check SHALL still respond 403 + AND the tampered frontend cannot bypass the API check + +#### Scenario: 4.8 — Scope metadata visible in token detail view + +GIVEN an admin viewing an embed token's details +WHEN they inspect the token's scope +THEN the admin UI SHALL display: + ``` + Mode: read + Allowed Filters: status, periode + Allowed Actions: (none) + ``` + AND when creating a read-with-interactions token, the admin SHALL see checkboxes for each available action (interact, export, drillDown) to select + +#### Scenario: 4.9 — Filter context pinning persisted with token + +GIVEN an `embed_token` for dashboard D with `subject.filterContext={gemeente: "Amsterdam"}` +WHEN the embed is rendered + AND the user attempts to change the gemeente filter to "Rotterdam" via the UI +THEN the filter interaction SHALL succeed (read-with-interactions mode allows it) + BUT the filter SHALL NOT persist across page reloads — the next page load resets the gemeente filter to "Amsterdam" + AND the filter context is enforced by the render route, not by the frontend + +#### Scenario: 4.10 — API middleware integration point + +GIVEN the LaunchPad API middleware/controller base +WHEN a request arrives with an `embed_token` (detected via JWT in Authorization header or token context) +THEN the middleware SHALL: + 1. Verify the token is valid and non-revoked (REQ-EMB-002) + 2. Extract the token's scope + 3. For non-GET/HEAD requests, check if `scope.mode=read` and respond 403 before the controller is invoked + 4. For GET/HEAD requests, proceed to the controller (the subject-match verification happens per-endpoint) + 5. For actions with allowedActions restrictions, check the action name against the allowed set before invoking the handler + +### Requirement: REQ-EMB-005 — Per-tenant theming via CSS variables + +The embed SHALL apply the token's `tenantThemeId` (if set) by injecting `cssVariables` into the embed's `:root` and SHALL refuse `customCss` rules that target selectors outside `:root`. + +#### Scenario: 5.1 — CSS variables injected into :root + +GIVEN a `tenant_theme` object with: + ```json + { + "id": "theme-zeist", + "name": "Gemeente Zeist", + "cssVariables": { + "--c-primary": "#21468B", + "--font-family": "Inter, sans-serif", + "--c-surface": "#FFFFFF", + "--c-text": "#1a1a1a", + "--c-border": "#e0e0e0" + } + } + ``` + AND an `embed_token` with `tenantThemeId="theme-zeist"` for widget W +WHEN the embed render route generates HTML for widget W +THEN the response SHALL include: + ```html + <html> + <head> + <style> + :root { + --c-primary: #21468B; + --font-family: Inter, sans-serif; + --c-surface: #FFFFFF; + --c-text: #1a1a1a; + --c-border: #e0e0e0; + } + </style> + </head> + <body> + <!-- widget HTML --> + </body> + </html> + ``` + AND the widget's styles SHALL use these CSS variables + AND the widget SHALL paint with the gemeente's brand colour (primary), font, and surface colour + +#### Scenario: 5.2 — Custom CSS restricted to :root only + +GIVEN a `tenant_theme` with `customCss=":root { --spacing: 8px; }"` +WHEN the theme is saved via `POST /api/tenant-themes` +THEN the API SHALL accept the theme and respond 201 + +#### Scenario: 5.3 — Custom CSS with non-:root selector rejected + +GIVEN an admin attempting to save a `tenant_theme` with `customCss=".widget-title { color: red; }"` +WHEN the POST `/api/tenant-themes` request is processed +THEN the API SHALL respond 400 with body: + ```json + { + "status": "error", + "error": "invalid_customCss", + "message": "CSS rules must be scoped to :root only. Found selector '.widget-title' which targets elements outside :root. Non-:root selectors can be used to disable required UI affordances (e.g., hide accessibility focus rings).", + "fieldErrors": { + "customCss": "non_root_selector" + } + } + ``` + AND the theme SHALL NOT be created + +#### Scenario: 5.4 — No theme uses platform default + +GIVEN an `embed_token` with `tenantThemeId: null` (no theme selected) +WHEN the embed render route generates HTML +THEN the response SHALL use the platform's default NL Design theme (no custom :root injection) + AND the widget SHALL render with standard LaunchPad colours and fonts + +#### Scenario: 5.5 — Theme logo displayed in embed header + +GIVEN a `tenant_theme` with `logoUrl="https://www.zeist.nl/logo.svg"` + AND an `embed_token` referencing this theme +WHEN the embed is rendered in iframe mode +THEN the render route MAY include a minimal embed header with: + ```html + <div class="embed-header"> + <img src="https://www.zeist.nl/logo.svg" alt="Gemeente Zeist" class="embed-logo" /> + </div> + ``` + AND the header SHALL be minimal (no chrome, no navigation, no user menu) + OR the header MAY be omitted if the embed is configured for full-bleed rendering + +#### Scenario: 5.6 — Theme inheritance in admin UI + +GIVEN the admin creating a new embed token +WHEN they select a `tenantThemeId` +THEN the admin UI SHALL display: + - Theme name ("Gemeente Zeist") + - Live preview of brand colours (primary, surface, text) + - Logo preview (if set) + AND a "View CSS variables" button to inspect the variable overrides + +#### Scenario: 5.7 — Multiple tokens can share a theme + +GIVEN a `tenant_theme` "Gemeente Zeist" +WHEN two different `embed_token` objects both reference `tenantThemeId="theme-zeist"` +THEN both embeds SHALL render with the same brand + AND theme updates affect both embeds immediately + AND the theme is a reusable resource, not cloned per token + +--- + +### Requirement: REQ-EMB-010 — WCAG 2.1 AA compliance enforced in embed rendering + +The embed render route SHALL produce HTML output that meets WCAG 2.1 AA success criteria for the widget being embedded, SHALL pass automated axe-core checks at build time on a representative sample of widget shapes, and SHALL surface accessibility violations in the embed-token admin UI as a non-fatal warning. + +#### Scenario: 10.1 — WCAG AA rendering requirements + +GIVEN an embed render of a chart widget +WHEN the HTML is inspected against WCAG 2.1 AA criteria +THEN EVERY interactive element SHALL have: + - An accessible name (`aria-label`, `aria-labelledby`, or visible text content) + - Colour contrast ≥ 4.5:1 for text (WCAG 1.4.3) + - Colour contrast ≥ 3:1 for graphical objects (WCAG 1.4.11) +AND the embed SHALL be navigable by keyboard alone: + - All interactive elements reachable via Tab key + - Tab order logical (left-to-right, top-to-bottom) + - No keyboard traps (user can tab away from any element) + - Focus indicators visible (outline or other visible focus marker) +AND semantic HTML is used: + - Heading hierarchy correct (no skipped levels) + - Lists marked with `<ul>`, `<ol>`, `<li>` + - Form inputs have associated `<label>` elements + +#### Scenario: 10.2 — Contrast check on theme CSS variables + +GIVEN a `tenant_theme` with `cssVariables={"--c-primary": "#0099CC", "--c-surface": "#FFFFFF"}` +WHEN the theme is saved +THEN the API SHALL compute the colour contrast ratio using the WCAG luminance formula + AND if contrast < 4.5:1, respond 400 with body: + ```json + { + "status": "error", + "error": "insufficient_contrast", + "message": "Primary colour #0099CC against surface #FFFFFF has contrast ratio 3.8:1. WCAG AA requires 4.5:1 for text.", + "fieldErrors": { + "cssVariables.--c-primary": "insufficient_contrast" + } + } + ``` + AND the theme SHALL NOT be created + (Admin can choose a darker primary or lighter surface and retry) + +#### Scenario: 10.3 — Build-time axe-core checks + +GIVEN the LaunchPad build pipeline +WHEN `npm run build` executes +THEN a test step SHALL: + 1. Render a representative sample of widget shapes (e.g., chart, table, text, image, custom) + 2. Run axe-core automated checks against each rendered HTML + 3. Fail the build if high/critical violations are found + 4. Log a warning for medium/low violations with IDs + AND the build output SHALL include an axe-core report + +#### Scenario: 10.4 — Admin warned of accessibility violations on token creation + +GIVEN an admin creating an `embed_token` for a widget W + AND widget W has known accessibility violations (e.g., from a previous axe-core check) +WHEN the admin submits the token-create form +THEN the API SHALL check the widget's violation registry + AND if violations exist, respond 200 (success, but with warning) with: + ```json + { + "id": "token-1", + "name": "...", + ... + "warnings": [ + { + "level": "accessibility", + "message": "Widget 'chart' has 2 known accessibility violations (axe-core build-time check):", + "violations": [ + { + "id": "color-contrast", + "description": "Ensure the contrast between foreground and background colours meets WCAG AA thresholds", + "help": "Element <text class=\"legend\"> has contrast ratio 2.8:1. Expected ≥4.5:1" + }, + { + "id": "aria-label", + "description": "Ensure every graphical element has an accessible name", + "help": "<svg class=\"chart\"> is missing aria-label" + } + ] + } + ] + } + ``` + AND the response includes an "Acknowledge and proceed" checkbox in the admin UI + AND the admin MUST check the checkbox before creating the token (non-blocking, but requires acknowledgement) + +#### Scenario: 10.5 — Axe-core check results per widget + +GIVEN the admin viewing the list of available widgets +WHEN they see a widget's detail card +THEN the card SHALL display: + - Widget name + description + - Latest axe-core check date + - Number of high/critical violations (in red if > 0) + - Number of medium/low violations (in yellow if > 0) + AND a "View accessibility report" link that opens the axe-core report for that widget + +#### Scenario: 10.6 — Accessibility report exportable + +GIVEN an admin with token-management permission +WHEN they request an accessibility compliance report +THEN the system SHALL generate a CSV/JSON report listing: + - Widget name + - Accessibility status (compliant / violations found) + - Violation count by severity + - Affected tokens (count of embeds using this widget) + AND the report includes axe-core rule IDs and WCAG criteria references + +#### Scenario: 10.7 — Manual accessibility review responsibility + +GIVEN a widget with axe-core violations +WHEN the admin acknowledges and creates a token +THEN the token's audit trail SHALL record: + - "Token created for widget 'chart' with acknowledged accessibility violations: color-contrast, aria-label" + AND the responsibility for manual review (the remaining ~70% of WCAG criteria not mechanically checkable) is documented per-widget + AND the widget author is responsible for ensuring manual compliance + +#### Scenario: 10.8 — Keyboard navigation tested in embed iframe + +GIVEN an embedded widget in an iframe +WHEN a user navigates using keyboard alone (Tab, Shift+Tab, Enter, Escape, arrow keys) +THEN: + - All interactive elements are reachable + - No keyboard traps exist (user can Tab out) + - Focus indicator is visible and moves logically + - Modals (if any) trap focus correctly + +### Requirement: REQ-EMB-006 — JS-SDK exposes render, event, and resize APIs + +The system SHALL serve a JS-SDK from the app itself (ESM and UMD builds at `/apps/launchpad/embed-sdk/embed-sdk.esm.js` and `.../embed-sdk.umd.js`, public, cacheable, loadable from any origin and versioned with the app; not published on npm) that exposes `LaunchPadEmbed.render(container, {token, subjectType, subjectId})`, `.on(eventType, handler)` for filter/drill/export events, and `.resize()` for host-driven layout changes. + +#### Scenario: 6.1 — SDK initialization and iframe creation + +GIVEN a host page (e.g., a SaaS customer portal) that imports the SDK: + ```html + <script src="https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.umd.js"></script> + <!-- OR ESM: import LaunchPadEmbed from 'https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.esm.js'; --> + ``` +WHEN the host page calls: + ```javascript + const embed = LaunchPadEmbed.render('#embed-container', { + token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...', + subjectType: 'widget', + subjectId: 'usage-widget-uuid' + }); + ``` +THEN the SDK SHALL: + 1. Create an `<iframe>` element with `src="https://launchpad.app/apps/launchpad/embed/widget/usage-widget-uuid"` + 2. Insert the iframe into the `#embed-container` div + 3. Wait for the iframe's `load` event + 4. Perform a postMessage handshake with the iframe to inject the JWT token + 5. Resolve a promise when the first render completes + AND the host page code continues: + ```javascript + embed.then(() => { + console.log('Widget loaded'); + }); + ``` + +#### Scenario: 6.2 — PostMessage handshake for token injection + +GIVEN the SDK has created an iframe +WHEN the iframe loads (fires `load` event) +THEN the SDK SHALL: + 1. Post a message to the iframe: + ```javascript + iframe.contentWindow.postMessage({ + type: 'embed-token', + token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...', + origin: 'https://portal.example.com' + }, 'https://launchpad.app') + ``` + 2. The iframe's origin verification (in the render route) SHALL check that `event.origin === 'https://launchpad.app'` before accepting the message + 3. The iframe stores the token in a secure context and uses it for subsequent API requests + 4. The iframe posts back a 'ready' message when the widget is fully rendered: + ```javascript + window.parent.postMessage({type: 'embed-ready', success: true}, '<SDK-origin>') + ``` + 5. The SDK resolves the promise returned by `render()` when the 'embed-ready' message arrives + +#### Scenario: 6.3 — Filter event subscription and relay + +GIVEN the host page has called `render()` successfully +WHEN the host page subscribes to filter events: + ```javascript + embed.on('filterApplied', ({dimension, value, source}) => { + console.log(`Filter applied: ${dimension} = ${value}`); + // Host page can now sync its own UI + }); + ``` +AND the end-user clicks on a bar in the embedded chart (drill-down interaction) +THEN the iframe SHALL: + 1. Emit an internal event (in-app bus) with `{dimension: 'gemeente', value: 'Amsterdam'}` + 2. Post a message to the parent: + ```javascript + window.parent.postMessage({ + type: 'embed-event', + eventType: 'filterApplied', + payload: {dimension: 'gemeente', value: 'Amsterdam', source: 'user-interaction'} + }, '<SDK-origin>') + ``` + 3. The SDK receives the message and invokes the registered handler + 4. The host page can read the filter and update its own UI/URL + +#### Scenario: 6.4 — Export event (read-with-interactions) + +GIVEN an embed with `scope.allowedActions=["export"]` +WHEN the user clicks "Export to CSV" in the widget +THEN the iframe SHALL: + 1. Invoke the export API (allowed by scope) + 2. Post a 'export' event to the parent: + ```javascript + window.parent.postMessage({ + type: 'embed-event', + eventType: 'export', + payload: {format: 'csv', url: 'https://launchpad.app/api/downloads/export-123.csv'} + }, '<SDK-origin>') + ``` + 3. The host page can download the file or handle it custom (e.g., send to email) + +#### Scenario: 6.5 — Resize API for responsive layout + +GIVEN the host page's layout changes (e.g., browser window resized, sidebar collapsed) +WHEN the host page calls: + ```javascript + embed.resize(); + ``` +THEN the SDK SHALL: + 1. Post a message to the iframe: + ```javascript + iframe.contentWindow.postMessage({ + type: 'embed-resize', + containerWidth: 1200, + containerHeight: 600 + }, 'https://launchpad.app') + ``` + 2. The iframe receives the message and re-measures its container + 3. The iframe re-renders the widget with the new dimensions + 4. The iframe posts back a 'resized' message when complete: + ```javascript + window.parent.postMessage({type: 'embed-resized', success: true}, '<SDK-origin>') + ``` + 5. The SDK resolves the promise returned by `resize()` + +#### Scenario: 6.6 — ESM build with TypeScript types + +GIVEN a TypeScript host application +WHEN it imports the SDK: + ```typescript + import LaunchPadEmbed from 'https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.esm.js'; + import type { EmbedConfig, EmbedInstance } from './launchpad-embed-types'; // a copy of src/embed-sdk/src/types.ts + + const config: EmbedConfig = { + token: 'eyJ...', + subjectType: 'widget', + subjectId: 'uuid' + }; + + const embed: EmbedInstance = await LaunchPadEmbed.render('#container', config); + embed.on('filterApplied', (event) => { + // event is typed as EmbedFilterEvent + }); + ``` +THEN the IDE SHALL provide autocomplete and type checking + AND the TypeScript types SHALL document the API surface + +#### Scenario: 6.7 — UMD build for vanilla JS + +GIVEN a vanilla JavaScript page (no build step, no module bundler) +WHEN it loads the UMD bundle: + ```html + <script src="https://unpkg.com/@conduction/launchpad-embed@1.0.0/dist/embed-sdk.umd.js"></script> + ``` +THEN the SDK is available as a global: + ```javascript + window.LaunchPadEmbed.render('#container', {token: '...', ...}) + .then(() => console.log('Ready')); + ``` + +#### Scenario: 6.8 — Error handling in SDK + +GIVEN the host page calls `render()` with an invalid token +WHEN the iframe attempts to load the render route +THEN the render route responds 401 + AND the iframe posts an 'error' message to the parent: + ```javascript + window.parent.postMessage({ + type: 'embed-error', + error: 'invalid_token', + message: 'The provided token is invalid or has expired' + }, '<SDK-origin>') + ``` + AND the SDK's promise rejects with a descriptive error: + ```javascript + embed.catch((err) => { + console.error('Failed to load widget:', err.message); + }); + ``` + +#### Scenario: 6.9 — Event listener management + +GIVEN the host page has subscribed to events: + ```javascript + const handler = (event) => { ... }; + embed.on('filterApplied', handler); + ``` +WHEN the host page wants to unsubscribe: + ```javascript + embed.off('filterApplied', handler); + ``` +THEN the event listener SHALL be removed + AND no further 'filterApplied' events are delivered to that handler + AND other handlers (if registered) still receive events + +#### Scenario: 6.10 — Multiple embeds on same page + +GIVEN a host page with three embed containers: + ```html + <div id="embed-1"></div> + <div id="embed-2"></div> + <div id="embed-3"></div> + ``` +WHEN the host page initializes all three: + ```javascript + const embed1 = LaunchPadEmbed.render('#embed-1', {token: '...', subjectId: 'widget-1'}); + const embed2 = LaunchPadEmbed.render('#embed-2', {token: '...', subjectId: 'widget-2'}); + const embed3 = LaunchPadEmbed.render('#embed-3', {token: '...', subjectId: 'widget-3'}); + ``` +THEN each embed operates independently + AND events from embed1 do not leak to embed2 or embed3 + AND each postMessage handshake is isolated + +#### Scenario: 6.11 — SDK package publishing + +GIVEN the LaunchPad build process +WHEN `npm run build:sdk` executes +THEN the SDK package SHALL be published to npm with: + - ESM build: `dist/embed-sdk.esm.js` + - UMD build: `dist/embed-sdk.umd.js` + - TypeScript definitions: `dist/embed-sdk.d.ts` + - Minified versions: `dist/embed-sdk.esm.min.js`, `dist/embed-sdk.umd.min.js` + - Source maps for debugging + - Package name: `@conduction/launchpad-embed` + - Version matching the LaunchPad app version + +### Requirement: REQ-EMB-007 — Rate limiting and request budgeting per token + +The system SHALL apply the token's `rateLimitPolicy` to all requests, return 429 with a `Retry-After` header when the bucket is exhausted, and write a `embed_usage_event` of type `pageView` even on rate-limited responses for budgeting analysis. + +#### Scenario: 7.1 — Token-bucket rate limiting with burst + +GIVEN a token with `rateLimitPolicy={requestsPerMinute: 60, burstSize: 10}` + AND the current time is T=0 +WHEN 70 requests arrive between T=0 and T=10 seconds (10 seconds into the first minute) +THEN: + - Requests 1-10 SHALL be processed (up to burst size) + - Requests 11-70 SHALL receive 429 responses with `Retry-After: 50` (seconds until next bucket refill) + AND each 429 response SHALL include an `embed_usage_event` with `responseStatusCode: 429` + AND after 60 seconds (one full minute), the bucket is refilled and new requests can be processed + +#### Scenario: 7.2 — Org-default rate limit for tokens without policy + +GIVEN a token with `rateLimitPolicy: null` (no custom policy specified) +WHEN requests arrive +THEN the org-level default policy SHALL apply: + ```json + { + "requestsPerMinute": 600, + "burstSize": 60 + } + ``` + AND the token operates under these defaults (high-throughput default for typical embeds) + +#### Scenario: 7.3 — 429 response format + +GIVEN a request that exceeds the rate limit +WHEN the render route processes it +THEN the response SHALL be 429 with: + ``` + HTTP/1.1 429 Too Many Requests + Content-Type: application/json + Retry-After: 45 + + { + "error": "rate_limit_exceeded", + "message": "Rate limit exceeded. The token allows 60 requests per minute. Try again in 45 seconds.", + "retryAfter": 45, + "resetAt": "2026-05-22T14:31:00Z" + } + ``` + +#### Scenario: 7.4 — Rate-limited request logged in usage events + +GIVEN a request that hits the rate limit +WHEN the 429 response is returned +THEN an `embed_usage_event` row SHALL be written with: + ```json + { + "id": "event-uuid", + "tokenId": "token-id", + "eventType": "pageView", + "hostOrigin": "https://www.zeist.nl", + "userAgent": "Chrome 124 / sha256(...)", + "viewportSize": "medium", + "timestamp": "2026-05-22T14:30:05Z", + "responseStatusCode": 429, + "responseLatencyMs": 12, + "correlationId": "correlation-uuid" + } + ``` + AND the admin can query: "This token hit rate limits 45 times on 2026-05-22 between 14:00 and 15:00" + +#### Scenario: 7.5 — Bucket refill and sliding window + +GIVEN a token with `requestsPerMinute: 60, burstSize: 10` (1 req/sec, burst 10) + AND 8 requests have been consumed at T=0 +WHEN new requests arrive at T=30 seconds (midway through the first minute) +THEN: + - 30 seconds of refill grants 30 requests (60 rpm ÷ 60 sec × 30 sec) + - Bucket now has: 10 (burst) + 30 (refilled) - 8 (used) = 32 capacity + - New request consumes 1, bucket now 31 + AND this is a token-bucket algorithm, not a fixed sliding window (continuous refill, not window resets) + +#### Scenario: 7.6 — Query-parameter vs Bearer-header rate limit distinction + +GIVEN a token with `rateLimitPolicy: {requestsPerMinute: 600, burstSize: 60}` +WHEN requests arrive via `?token=<jwt>` (query parameter) +THEN the query-parameter form MAY enforce a stricter limit: + - Override to 10× lower: 60 rpm, burst 6 (token leak risk warrants stricter throttling) + AND requests via `Authorization: Bearer <jwt>` (header) use the configured limit (600 rpm, burst 60) + AND the admin UI displays this distinction when creating a token: + ``` + Query-parameter form: up to 60 requests/minute (stricter for security) + Bearer header form: up to 600 requests/minute (as configured) + ``` + +#### Scenario: 7.7 — Rate limit policy updateable after token creation + +GIVEN an existing token with `rateLimitPolicy: {requestsPerMinute: 60, burstSize: 10}` +WHEN an admin invokes `PUT /api/embed-tokens/token-id` with a new policy: + ```json + { + "rateLimitPolicy": { + "requestsPerMinute": 120, + "burstSize": 15 + } + } + ``` +THEN the API SHALL respond 200 and update the token + AND the new rate limit applies to subsequent requests immediately + AND in-flight requests (between update and next request) use the old policy (best-effort; eventual consistency is acceptable) + +#### Scenario: 7.8 — Rate limit exhaustion analysis + +GIVEN the admin accessing the usage report for a token +WHEN they view the analytics dashboard +THEN they SHALL see: + ``` + Rate Limit Breaches + ├─ 2026-05-22: 145 requests rejected (60 expected) + │ Time: 14:00–15:00 (busiest hour) + │ Breach threshold: 600 rpm → hit 700 rpm + ├─ 2026-05-21: 23 requests rejected + └─ 2026-05-20: 0 requests rejected + + Recommendation: Consider raising requestsPerMinute to 1200 + ``` + AND a button "Adjust rate limit" opens the token edit dialog + +#### Scenario: 7.9 — Alert configuration (optional v1+) + +GIVEN an admin who wants to monitor token health +WHEN they configure alerts on a token (v1.1 feature, out of scope here but schema-ready): + ```json + { + "alertPolicy": { + "thresholdPercentage": 80, + "notifyEmail": "ops@gemeente.nl" + } + } + ``` +THEN when the token reaches 80% of its rate limit in a given minute, an email alert is sent + (This is a note for future expansion; not implemented in v1, but the schema supports it) + +#### Scenario: 7.10 — Rate limit headers in all responses + +GIVEN any response from the embed render route +WHEN the response is generated +THEN the response SHALL include rate-limit headers (RFC 6585 style): + ``` + RateLimit-Limit: 60 + RateLimit-Remaining: 45 + RateLimit-Reset: 2026-05-22T14:31:00Z + ``` + AND the host page / SDK can read these headers to show a rate-limit warning to the user + +### Requirement: REQ-EMB-008 — Usage telemetry without leaking PII + +The system SHALL persist `embed_usage_event` rows for every page-view and interaction, SHALL capture `hostOrigin`, `userAgent` (truncated to family + major version + hashed), and `viewportSize` (bucketed), and SHALL NOT capture full IP addresses, full user-agents, or any identifier of the host-page's logged-in user. + +#### Scenario: 8.1 — Page-view telemetry capture + +GIVEN an embed page-view request from `https://www.zeist.nl/woo/` (host origin) + AND the user's user-agent: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36` + AND the viewport size: 1920×1080 pixels +WHEN the render route processes the request and returns 200 +THEN an `embed_usage_event` row SHALL be written with: + ```json + { + "id": "event-uuid", + "tokenId": "token-id", + "eventType": "pageView", + "hostOrigin": "https://www.zeist.nl", + "userAgent": "Chrome 124", + "userAgentHash": "sha256(Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36)", + "viewportSize": "large", + "responseStatusCode": 200, + "responseLatencyMs": 87, + "timestamp": "2026-05-22T14:30:00Z", + "correlationId": "correlation-uuid" + } + ``` + +#### Scenario: 8.2 — Viewport size bucketing + +GIVEN viewport widths: + - 0–767px (small) + - 768–1279px (medium) + - 1280px+ (large) +WHEN embed requests arrive with various viewport sizes +THEN the event's `viewportSize` field SHALL be bucketed: + ```json + [ + {"width": 480, "height": 720, "viewportSize": "small"}, + {"width": 1024, "height": 768, "viewportSize": "medium"}, + {"width": 1920, "height": 1080, "viewportSize": "large"} + ] + ``` + +#### Scenario: 8.3 — NO IP address capture + +GIVEN a request arriving with headers: + ``` + X-Forwarded-For: 203.0.113.42 + X-Real-IP: 203.0.113.42 + ``` +WHEN the embed usage event is written +THEN the event row SHALL NOT include: + - Client IP address + - X-Forwarded-For header value + - Any IP-based geolocation +AND the only "location" data is the `hostOrigin` (domain, not geolocation) + +#### Scenario: 8.4 — User-agent family + major version only + +GIVEN user-agents: + ``` + Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0.6367.60 + Mozilla/5.0 (iPhone; CPU iPhone OS 17_4_1 like Mac OS X) Mobile Safari/604.1 + Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0 + ``` +WHEN events are written +THEN the `userAgent` field SHALL be truncated to family + major: + ```json + [ + {"userAgent": "Chrome 124"}, + {"userAgent": "Safari 17"}, + {"userAgent": "Firefox 125"} + ] + ``` +AND the full user-agent string is hashed and stored separately in `userAgentHash` for analytics without fingerprinting + +#### Scenario: 8.5 — NO end-user identifier in events + +GIVEN a host page that is embedded in a SaaS portal, where the logged-in user is "customer-123" + AND the LaunchPad request is made in the context of that user +WHEN the embed usage event is written +THEN the event row SHALL NOT include: + - User ID from the host page (even if passed in a header) + - Email address of the host-page's logged-in user + - Account name or subscription tier +AND the only identifier is the `tokenId` (which widget/dashboard was embedded, not who viewed it) + +#### Scenario: 8.6 — Host origin stored (not referrer, not full URL) + +GIVEN a request from `https://www.zeist.nl/woo/requests-2026-05/?sort=date&limit=50` +WHEN the event is written +THEN the `hostOrigin` field SHALL be: + ```json + {"hostOrigin": "https://www.zeist.nl"} + ``` +NOT: + - The full URL (path+query stripped) + - The Referer header (may be empty or stripped by proxies) + - Derived from IP geolocation + +#### Scenario: 8.7 — Interaction events also captured + +GIVEN the user interacts with an embedded widget (filter applied, drill-down, export) +WHEN the interaction is processed +THEN an `embed_usage_event` SHALL be written with: + ```json + { + "eventType": "filterApplied", + "payload": { + "dimension": "status", + "value": "openstaande" + }, + "hostOrigin": "https://www.zeist.nl", + "userAgent": "Chrome 124", + "viewportSize": "large", + "responseStatusCode": 200, + "timestamp": "2026-05-22T14:30:15Z" + } + ``` +OR: + ```json + { + "eventType": "export", + "payload": { + "format": "csv" + }, + ... + } + ``` + +#### Scenario: 8.8 — Usage report in admin UI + +GIVEN an admin accessing the usage report for a token +WHEN they view the analytics dashboard +THEN they SHALL see: + ``` + Pageviews + ├─ Total (last 7 days): 1,243 views + ├─ By date: + │ └─ 2026-05-22: 324 views + │ └─ 2026-05-21: 289 views + │ └─ 2026-05-20: 215 views + ├─ By host origin: + │ └─ https://www.zeist.nl: 1,100 views + │ └─ https://intranet.zeist.nl: 143 views + └─ By viewport size: + └─ large: 601 views + └─ medium: 432 views + └─ small: 210 views + + Interactions + ├─ filterApplied: 87 times + ├─ drillDown: 45 times + └─ export: 12 times + + Browsers + ├─ Chrome 124: 623 views + ├─ Safari 17: 312 views + └─ Firefox 125: 308 views + ``` + +#### Scenario: 8.9 — No individual-user identifiers in report + +GIVEN the admin viewing the usage report +WHEN they inspect the data +THEN they SHALL NOT see: + - List of end-users who viewed the embed + - User names or email addresses + - Timestamps per individual user (only aggregated by day) + - Correlation of two views to the same person (no fingerprinting via UA hash + viewport) +AND the report answers only: "Did this embed get traffic?" and "From where?" + +#### Scenario: 8.10 — Org-level telemetry kill-switch + +GIVEN an admin with org configuration access +WHEN they toggle "Disable embed usage telemetry" in org settings +THEN: + - No `embed_usage_event` rows are written for any subsequent requests + - Existing events are NOT deleted (audit trail remains) + - The toggle is auditable (audit log records who disabled telemetry and when) + - Re-enabling telemetry immediately resumes event capture + +#### Scenario: 8.11 — Data retention policy + +GIVEN the org's data retention policy (e.g., "keep events for 90 days") +WHEN 90 days have passed since an `embed_usage_event` was created +THEN a background job SHALL delete the old event + AND the event is permanently removed (not soft-deleted; no recovery) + AND the deletion is logged in the audit trail + +#### Scenario: 8.12 — GDPR/AVG data subject access (not applicable) + +GIVEN a data subject (end-user) requesting access to their personal data per GDPR Article 15 +WHEN the org's DPO runs the data-subject-access query +THEN the system SHALL respond: + ``` + No personal data on record for this data subject. + Reasoning: Embed telemetry captures only host origin and viewport size. + No user identifiers, emails, IP addresses, or other traceable personal data are stored. + The only entity involved is the embed token (issued by the org administrator to a third-party host), + not personal data of an end-user. + ``` +AND the org does NOT need to include embed telemetry in GDPR access response letters + +### Requirement: REQ-EMB-009 — Token revocation takes effect within 60 seconds + +The system SHALL revoke a token by setting `revokedAt`, propagate the revocation to all render-route workers within 60 seconds via a short-TTL cache, and reject subsequent render requests with 401. + +#### Scenario: 9.1 — Revocation via admin UI + +GIVEN an admin viewing an embed token's detail page +WHEN they click the "Revoke" button +THEN the admin UI SHALL display a confirmation dialog: + ``` + Revoke token "Gemeente Zeist WOO"? + + [Dropdown] Revocation reason: + ├─ Compromised + ├─ No longer needed + ├─ Host website decommissioned + └─ Other... + + [Text field] Additional notes (optional): + "Gemeente decided to move WOO tracking in-house" + + [Cancel] [Confirm Revoke] + ``` +WHEN they select a reason and confirm +THEN the UI SHALL POST `/api/embed-tokens/token-id/revoke` with: + ```json + { + "reason": "no_longer_needed", + "notes": "Gemeente decided to move WOO tracking in-house" + } + ``` + +#### Scenario: 9.2 — Revocation persisted in token record + +GIVEN the revoke request +WHEN the API processes it +THEN the `embed_token` row SHALL be updated with: + ```json + { + "id": "token-id", + "name": "Gemeente Zeist WOO", + ... + "revokedAt": "2026-05-22T14:35:00Z", + "revocationReason": "no_longer_needed", + "revocationNotes": "Gemeente decided to move WOO tracking in-house", + "revokedBy": "admin-user-id" + } + ``` + AND the response SHALL be 200 with the updated token metadata + AND a notification SHALL be sent to the token's `createdBy` user: + ``` + Token "Gemeente Zeist WOO" has been revoked by admin-user. + Reason: no_longer_needed + Notes: Gemeente decided to move WOO tracking in-house + Revocation timestamp: 2026-05-22T14:35:00Z + ``` + +#### Scenario: 9.3 — Render-route workers reject revoked token within 60 seconds + +GIVEN a revoked token (revokedAt set 5 seconds ago) + AND multiple render-route worker processes running +WHEN any request arrives with the revoked token +THEN within 60 seconds (the cache propagation window), ALL workers SHALL: + 1. Check their revocation cache + 2. If the token is in the cache as revoked, respond 401 + 3. If the token is NOT in the cache yet (slow propagation), query the database: + ```sql + SELECT revokedAt FROM embed_token WHERE id = ? LIMIT 1; + ``` + 4. If `revokedAt IS NOT NULL`, respond 401 and update the local cache + 5. Cache the revocation status for 60 seconds (TTL) +AND the response SHALL be 401 with: + ```json + { + "error": "token_revoked", + "message": "The provided token has been revoked" + } + ``` + +#### Scenario: 9.4 — Usage event written even for revoked token + +GIVEN a revoked token used after revocation +WHEN the render route returns 401 +THEN an `embed_usage_event` SHALL be written with: + ```json + { + "eventType": "pageView", + "responseStatusCode": 401, + "responseLatencyMs": 5, + "timestamp": "2026-05-22T14:36:30Z" + } + ``` +AND the admin can query the usage report: + "Token 'Gemeente Zeist WOO' was used 23 times AFTER revocation (2026-05-22 14:35–14:45)" +AND this helps forensic review of potential security incidents + +#### Scenario: 9.5 — Cache propagation guarantees + +GIVEN a render-route worker A and worker B +WHEN a token is revoked at T=0 +AND worker A immediately refreshes its cache from the database +AND worker B is busy and does not refresh for 50 seconds +THEN: + - Worker A rejects the token starting at T=1 second + - Worker B continues accepting the token until T=50 seconds + - At T=60 seconds, worker B's cache expires and it must query the database + - Worker B then rejects the token starting at T=61 seconds +AND the 60-second window bounds the maximum delay across all workers + +#### Scenario: 9.6 — Purge cache action for critical incidents + +GIVEN a critical incident (token compromised, attacker active) +WHEN an admin clicks "Purge cache" on the revoked token's detail page +THEN the API SHALL: + 1. Immediately invalidate all render-route worker caches for this token + 2. Send a broadcast message to all workers (Redis, AMQP, or similar): + ```json + { + "type": "token_cache_purge", + "tokenId": "token-id", + "timestamp": "2026-05-22T14:35:30Z" + } + ``` + 3. All workers receive the message and drop the token from their cache + 4. The next request with the revoked token queries the database and is rejected immediately +AND the response shows: + ``` + Cache purged. All render workers will immediately reject this token. + Purge initiated at 2026-05-22T14:35:30Z. + ``` + +#### Scenario: 9.7 — Re-issue (new token, revoke old) + +GIVEN an admin who has lost a token or wants to refresh it +WHEN they invoke the "Re-issue" action on the token +THEN the system SHALL: + 1. Generate a new JWT + 2. Create a new `embed_token` row with the same subject, scope, hostOrigins, etc. + 3. Revoke the old token (set revokedAt and revocationReason: "re-issued") + 4. Return the new JWT to the admin (shown once) +AND the old token is rejected starting immediately (cache expires within 60s, database rejects immediately) +AND subsequent integration uses the new token + +#### Scenario: 9.8 — Revocation audit trail + +GIVEN the audit log for a token +WHEN an admin reviews the token's history +THEN they SHALL see: + ``` + Audit Trail for Token "Gemeente Zeist WOO" + ├─ 2026-05-22T14:35:00Z — REVOKED by admin@gemeente.nl + │ Reason: no_longer_needed + │ Notes: Gemeente decided to move WOO tracking in-house + ├─ 2026-05-20T10:00:00Z — ACCESSED 342 times + │ Host origins: https://intranet.zeist.nl (340), https://www.zeist.nl (2) + ├─ 2026-05-15T09:30:00Z — CREATED by admin@gemeente.nl + │ Subject: widget / woo-widget + │ Scope: read, filters=[status, periode] + └─ (no further events) + ``` + +#### Scenario: 9.9 — Token state visibility + +GIVEN a list of all embed tokens in the admin UI +WHEN the admin views the token table +THEN each row SHALL display: + - Token name + - Status: [ACTIVE | REVOKED | EXPIRING SOON] + - Subject: (widget/dashboard name) + - Created: 2026-05-15 + - Last used: 2026-05-22 14:30 + - Revoked: (empty if active, or "2026-05-22 14:35" if revoked) + - Actions: [View] [Edit] [Re-issue] [Revoke] (or [Un-revoke] if revoked — soft-revoke only) + +#### Scenario: 9.10 — Soft revocation (can be undone) + +GIVEN a revoked token +WHEN an admin clicks "Undo revocation" (or "Un-revoke") +THEN the system SHALL: + 1. Clear the `revokedAt` and `revocationReason` fields + 2. Set `unrevokedAt` and `unrevokedBy` for audit + 3. Respond 200 with the token's updated state + 4. Send a notification to the token's creator +AND the token is immediately re-activated (cache expires, database accepts) +AND the full history (revocation + un-revocation) is auditable + +#### Scenario: 9.11 — Bulk revocation (future feature, out of scope) + +GIVEN multiple tokens that are no longer needed +WHEN an admin selects them and invokes "Revoke selected" (future v1.1 feature) +THEN all tokens are revoked in a single operation + (This is a note for future; not implemented in v1, but the schema supports bulk operations) + +#### Scenario: 9.12 — Revocation email notification + +GIVEN a token that was revoked +WHEN the revocation is confirmed +THEN an email SHALL be sent to the token's creator: + ``` + Subject: Token Revoked: Gemeente Zeist WOO + + Your embed token "Gemeente Zeist WOO" has been revoked. + + Revoked by: admin@gemeente.nl + Reason: no_longer_needed + Notes: Gemeente decided to move WOO tracking in-house + Revocation time: 2026-05-22 14:35 UTC + + If this was unexpected, contact the administrator. + ``` diff --git a/openspec/changes/archive/2026-11-22-embedded-analytics/tasks.md b/openspec/changes/archive/2026-11-22-embedded-analytics/tasks.md new file mode 100644 index 000000000..15b090c68 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-embedded-analytics/tasks.md @@ -0,0 +1,385 @@ +# Tasks — embedded-analytics + +## Infrastructure & Data Layer + +- [x] Task 1: Create OpenRegister schemas in `lib/Settings/launchpad_register.json` for four new register types: + - `embed_token` (fields: id, name, description, tokenHash, subject, scope, hostOrigins, tenantThemeId, tokenExpiresAt, revokedAt, revocationReason, rateLimitPolicy, createdBy, createdAt, updatedAt) + - `tenant_theme` (fields: id, name, cssVariables, logoUrl, customCss, createdBy, createdAt) + - `embed_usage_event` (fields: id, tokenId, eventType, hostOrigin, userAgent, userAgentHash, viewportSize, timestamp, responseStatusCode, responseLatencyMs, correlationId) + - `signing_key` (fields: id, algorithm, publicKeyJwk, privateKeyEncrypted, status, createdAt, retiredAt) + Include seed data per design.md (3–5 objects per schema with Dutch values) + > Built as the ADR-037 fragment `lib/Settings/register.d/embedded-analytics.json` (merged onto `launchpad_register.json` at import; `ImportLaunchpadRegister::REGISTER_VERSION` 1.0.3 so existing installs take the new schemas). `embed_token` also carries `keyId`, `revocationNotes` and `revokedBy` (REQ-EMB-009 9.2); `signing_key` carries `kid`. No seed objects ship: the register is imported on every install, and seeded tokens, signing keys or Zeist/Amsterdam themes would land in production. Tests: `EmbeddedAnalyticsSchemasTest` (4). + +- [x] Task 2: Create entity mapping classes under `lib/Entity/`: + - `EmbedToken.php` (OpenRegister mapper) + - `TenantTheme.php` (OpenRegister mapper) + - `EmbedUsageEvent.php` (OpenRegister mapper) + - `SigningKey.php` (OpenRegister mapper) + Plus exception classes: `EmbedTokenException`, `InvalidTokenException`, `TokenExpiredException`, `TokenRevokedException` + > Partly built: the four exception classes exist under `lib/Exception/` (`InvalidTokenException`, `TokenExpiredException` and `TokenRevokedException` extend `EmbedTokenException`). `lib/Entity/EmbedToken.php` and `lib/Entity/SigningKey.php` are built over `Service/Embed/EmbedObjectStore` (OpenRegister's published object service, looked up by name so LaunchPad boots without it). `lib/Entity/TenantTheme.php` (Task 11) and `lib/Entity/EmbedUsageEvent.php` (Task 28) complete the four. + +- [x] Task 3: Create `lib/Service/JwtSigningService.php` for JWT lifecycle: + - Generate RS256 and ES256 key pairs (minimum 2048-bit RSA, P-256 for ECDSA) + - Sign JWTs with the active key (includes `kid` header) + - Verify JWT signatures against the `kid`-selected public key + - Rotate keys: mark old key `status: retiring`, new tokens sign with new key, old tokens remain valid until expiry + - Unit tests: signature verification, key rotation, algorithm selection + > Built as `lib/Service/Embed/JwtSigningService.php` (beside the other embed services), with the JWS byte encodings in `Embed/JoseEncoding`. RS256 (2048-bit) and ES256 (P-256, JOSE R||S signatures) key pairs with a public JWK; signs with the newest active key under its `kid`; verifies only against an active or retiring key of the algorithm the header names (`none`, HS256 and algorithm swaps refused), then `exp`/`nbf`; `rotate()` turns active keys retiring and adds a new active one. Keys are plain `signing_key`-shaped records: storing them and encrypting the private key belong to Task 1/4. Tests: `JwtSigningServiceTest` (12). + +- [x] Task 4: Create `lib/Service/EmbedTokenService.php` for token persistence: + - `createToken(name, description, subject, scope, hostOrigins, tenantThemeId, tokenExpiresAt, rateLimitPolicy)`: Generate JWT + persist token record + return token (shown once) + - `getToken(id)`: Return token metadata (no JWT) + - `validateToken(jwt)`: Verify signature + expiry + revocation status + - `revokeToken(id, reason, notes)`: Set revokedAt, send notification + - `unrevokeToken(id)`: Clear revokedAt (soft revocation) + - Unit tests: token creation, validation, revocation, expiry + > Built as `lib/Service/Embed/EmbedTokenService.php` with `SigningKeyService` (keys stored as `signing_key` objects, private key encrypted with `ICrypto`; the first RS256 key is created on first issue). The token is stored first, signed with `jti` = its id, then its sha256 hash and `kid` are stored; validation checks signature and claims, the stored hash (constant-time, also for a missing row), revocation through `RevocationCache`, then expiry. Also `listTokens`, `updateToken` (name, description, rate limit only), `reissueToken` and `purgeCache`. Revocation notifies the creator (`embed_token_revoked`, Notifier copy, nl). Tests: `EmbedTokenServiceTest` (11), `EmbedObjectStoreTest` (4). + +- [x] Task 5: Create `lib/Service/RateLimitService.php` (token-bucket algorithm): + - `checkRateLimit(tokenId, timestamp)`: Query token's `rateLimitPolicy`, check bucket state, return remaining quota or 429 error + - `refillBucket(tokenId)`: Update bucket based on elapsed time (token-bucket refill) + - Store bucket state in Redis or in-memory cache with TTL + - Unit tests: burst capacity, refill rate, 429 response generation + +## JWT Validation & Scope Enforcement + +- [x] Task 6: Create `lib/Middleware/EmbedTokenMiddleware.php`: + - Extract JWT from `?token=` query parameter OR `Authorization: Bearer` header + - Validate JWT signature + expiry + revocation (REQ-EMB-002) + - Extract token subject and scope + - Store token context in the request for downstream use (tokenId, scope, hostOrigins, etc.) + > Built as `lib/Middleware/EmbedTokenMiddleware.php` over `Service/Embed/EmbedGate`: on the render route (`EmbedController`) a token is required as `?token=` or `Authorization: Bearer`; on any other route a Bearer JWT whose issuer is LaunchPad marks the request as an embed request (other Bearer credentials stay Nextcloud's). The token is validated (401 `missing_token`, `invalid_token`, `token_expired`, `token_revoked`, with the `WWW-Authenticate` challenge) and kept in `EmbedRequestContext` (token, form, start time). Tests: `EmbedTokenMiddlewareTest` (8), `EmbedGateTest` (10). + +- [x] Task 7: Create `lib/Service/ScopeEnforcementService.php` (REQ-EMB-004): + - `enforceReadOnly(request)`: If token's `scope.mode=read` and request is POST/PUT/PATCH/DELETE, respond 403 + - `enforceActionScope(request, action)`: If action not in `scope.allowedActions`, respond 403 + - `applyFilterContext(request, filterContext)`: Pin filters from token's `subject.filterContext` + - Integrate into API middleware so ALL non-GET/HEAD requests are checked + > The decisions were built before; now applied by `EmbedTokenMiddleware` to every non-GET/HEAD request carrying a token, before the controller runs (4.7, 4.10). The read refusal is `read_only_token` as in 4.1. Added `restrictFilters()` (request filters only on `allowedFilters`, pinned context over them) and `actionOf()` (the action of a write from its last path segment: export, drill-down, filters/interactions). + +- [x] Task 8: Create `lib/Service/CspService.php` for CSP header generation (REQ-EMB-003): + - `generateCspHeader(hostOrigins)`: Return `Content-Security-Policy: frame-ancestors <origins>` + - `validateOrigins(origins)`: Reject wildcard, require scheme + domain + - `validateOriginFormat(origin)`: Validate RFC 3986 format + - Unit tests: CSP header syntax, origin validation, wildcard rejection + +## Public Render Route + +- [x] Task 9: Create `lib/Controller/EmbedController.php`: + - `GET /apps/launchpad/embed/{subjectType}/{subjectId}`: Public render route + 1. Extract + validate JWT (Middleware handles this) + 2. Verify subject match (URL's subjectId == token's subject.id) + 3. Render the widget/dashboard HTML with: + - Token scope applied (filter context pinned, allowed actions visible) + - Tenant theme injected into :root CSS variables + - CSP headers emitted + 4. Write `embed_usage_event` (REQ-EMB-008) + 5. Respond 200 or appropriate error (401, 403, 429) + > Built as `lib/Controller/EmbedController.php`: `render` (the page) and `data` (`/embed/{subjectType}/{subjectId}/data`, the subject as JSON), both public. The token must name this subject (`scope_mismatch` 403, saying nothing about other subjects), the framing page must be a host origin (`origin_mismatch` 403 on a cross-site or Bearer request whose Referer origin is not listed, 3.2/3.6/3.7). Every answer, refusals included, is a usage event. The page loads the `launchpad-embed` script of Task 23. Tests: `EmbedControllerTest` (7). + +- [x] Task 10: Create `lib/Service/EmbedRenderService.php`: + - `renderWidget(widgetId, tokenScope, tenantTheme)`: Render single widget with scope + theme applied + - `renderDashboard(dashboardId, tokenScope, filterContext, tenantTheme)`: Render dashboard with scope + theme applied + - Reuse existing widget/dashboard rendering code (no fork) + - Wrap output with CSP headers, no navigation chrome + > Built as `lib/Service/Embed/EmbedRenderService.php`: the widget placement or the dashboard with its placements through the same mappers and serialisation as the public share, plus the scope, the filters in force and the theme's :root block; `page()` is the bare base layout (`templates/embed.php`) with `frame-ancestors` from the host origins, `X-Frame-Options: SAMEORIGIN` (3.5) and `nosniff`. Tests: `EmbedRenderServiceTest` (4). + +## Theming & Accessibility + +- [x] Task 11: Create `lib/Service/TenantThemeService.php`: + - `createTheme(name, cssVariables, logoUrl, customCss)`: Validate CSS, persist theme + - `validateCss(customCss)`: Reject non-:root selectors (CSSTidy or simple regex) + - `validateContrastRatio(primaryColor, surfaceColor)`: Use WCAG luminance formula, enforce 4.5:1 + - Unit tests: CSS validation, contrast computation, color parsing + > Built as `lib/Service/Embed/TenantThemeService.php` over the existing `TenantThemeValidator`: create and update refuse bad custom-property names or values, non-:root custom CSS (5.3 body), a non-https logo, and primary or text colours under 4.5:1 on `--c-surface` (10.2 body, ratio rounded down); `listThemes()` counts the tokens using each theme; `rootCss()` gives the :root block an embed injects, '' without a theme (5.4). The `/api/tenant-themes` routes come with the theme manager (Task 16). Tests: `TenantThemeServiceTest` (5). + +- [x] Task 12: Add axe-core integration to build pipeline: + - In `npm run build`, add a linting step that: + 1. Renders representative widget shapes (chart, table, text, image) + 2. Runs axe-core accessibility checks against the rendered HTML + 3. Generates a report (axe-results.json) + 4. Fails build if high/critical violations are found + 5. Warns on medium/low violations + - Create `src/axe-core-check.js` script + - Output report saved to `docs/accessibility/axe-results.json` for review + > Built as `src/axe-core-check.js` (axe-core 4.14.1, already in the lock through `@axe-core/playwright`, now a direct dev dependency) and `src/__tests__/axe-core-check.spec.js`, which renders the embed page (`EmbedView` over `PublicDashboardGrid`) in ten shapes: a dashboard with chart, table, header, text, image, link, divider and tile widgets under a read and an interactions scope, single chart, table, text, image, untitled image and icon-only tile widgets, and the loading and refusal states. axe-core runs the WCAG 2.2 A/AA and best-practice rules over each; serious and critical violations fail, moderate and minor ones are printed as warnings, and every finding is written to `docs/accessibility/axe-results.json`. `npm run build` ends with `npm run check:a11y`, which runs that file, and the file also runs in the Vitest suite CI runs. jsdom has no layout, so colour contrast is left to the theme's 4.5:1 check (Task 11). The first run found one real violation: a tile with an icon and no title was a link without a name (`link-name`, serious), on the embed and the public share page alike; such a tile is now labelled "Tile". Tests: `axe-core-check.spec.js` (10), `PublicDashboardGrid.spec.js` "names a tile that shows only its icon" (both fail without the label). + +- [x] Task 13: Modify dashboard/widget rendering to accept token context: + - Add optional `embedContext` parameter to widget/dashboard render functions + - If `embedContext` present, apply theme CSS variables, scope restrictions, filter pinning + - Maintain backward compatibility (no context = normal in-app rendering) + > Built on the renderer the embed uses (`PublicDashboardGrid`, the public share's grid, no fork): an optional `embedContext` prop `{scope, filters}`, passed by `EmbedView` from `useEmbedContext`. With it the tenant theme's `--c-primary`, `--c-surface`, `--c-text` and `--c-border` (injected on :root by the embed page, until now consumed by nothing) colour the tiles and widgets, falling back to the Nextcloud variables, and a tile links out of the embed (new tab) only when the scope allows `interact`. Filters are pinned server-side by the data route (Task 10). Without the prop the grid renders exactly as before (its golden render test is unchanged). Tests: `PublicDashboardGrid.embed.spec.js` (4). + +- [x] Task 14: Create `src/composables/useEmbedContext.js`: + - Detect if the current render is in embed mode (check for token in parent postMessage or in render context) + - Provide theme CSS variables to Vue components + - Apply scope restrictions (hide disallowed actions, disable exports, etc.) + - Relay events back to parent via postMessage (REQ-EMB-006) + > Built as `src/composables/useEmbedContext.js`: the subject from the `/embed/{type}/{id}` path, the token from `?token=` or the SDK's `init` message, the subject's data (scope, filters in force, theme block, placements) loaded with the token as a Bearer credential, `canRun(action)` for the scope, `relay()` of events to the parent and the resize answer. A message is answered only from the parent window at an origin the token lists. Tests: `useEmbedContext.spec.js` (9). + +## Admin UI — Token Management + +- [x] Task 15: Create `src/components/EmbedTokenManager.vue`: + - List view: Table of all tokens with name, status, subject, created, last-used, revoked date, actions + - Create flow: Form for name, description, subject (widget/dashboard picker), scope (mode + filters + actions), hostOrigins, tenantThemeId, tokenExpiresAt, rateLimitPolicy + - Display: Show raw JWT once, with "keep this safe" warning, "copy" button + - Detail view: Full token metadata, re-issue/revoke buttons, usage stats link + - Edit: Update name, description, rateLimitPolicy (scope + subject immutable) + - Revoke dialog: Dropdown for reason, text field for notes, confirm + - Actions: Re-issue, revoke/un-revoke, view usage + > Built as `src/components/admin/embed/EmbedTokenManager.vue` in Admin settings ▸ Embeds: the token table (name, status active/expired/revoked, subject, created, revoked), the create form, the JWT shown once with the keep-safe warning and a copy button, the detail view (metadata, edit, re-issue, revoke/restore) with the usage report, and the server's refusal message on a failed save. Over `src/services/embedApi.js`. Tests: `EmbedTokenManager.spec.js` (9), `embedApi.spec.js` (3). + +- [x] Task 16: Create `src/components/TenantThemeManager.vue`: + - List view: Table of themes with name, primary colour preview, logo, created date + - Create flow: Form for name, CSS variables (editable text fields with labels), logoUrl uploader, customCss (textarea with :root validation) + - Live preview: Show selected colours applied to sample widget + - Edit: Update name, variables, logo, customCss + - Delete: Warn if theme is in-use by tokens + - Copy button: Export JSON for documentation + > Built as `src/components/admin/embed/TenantThemeManager.vue` over the new admin routes `GET/POST /api/tenant-themes`, `PUT/DELETE /api/tenant-themes/{id}` (`Controller/TenantThemeApiController`, documented in `openapi.json` as internal). The four `--c-*` variables as colour pickers plus text fields, the logo as an https URL (no file upload), custom CSS checked for :root-only rules while typing, a live preview, the server's contrast refusal shown, delete through `src/dialogs/DeleteTenantThemeDialog.vue` warning how many tokens use the theme (the server answers 409 `theme_in_use` unless `force`, `TenantThemeService::deleteTheme`, `EmbedObjectStore::delete`), and Copy JSON. Tests: `TenantThemeManager.spec.js` (6), `TenantThemeApiControllerTest` (5), `TenantThemeServiceTest` + `EmbedObjectStoreTest` (delete). + +- [x] Task 17: Create `src/components/EmbedUsageReport.vue`: + - Summary card: Total pageviews (7d), status, last activity + - Pageviews chart: Line chart by date + - Host origin distribution: Bar chart or pie + - Viewport size breakdown: Stacked bar (small/medium/large) + - Browser distribution: Bar chart (top 10 user-agents) + - Interaction breakdown: Counters for filterApplied, drillDown, export + - Rate limit breaches table (if any): Date, count, percentage of quota + - Export button: Download CSV of underlying events (unless org telemetry disabled) + > Built as `src/components/admin/embed/EmbedUsageReport.vue` in the token detail view: summary (page views, last activity, rate-limited requests), use after revocation, and bar rows by date, site, screen size, browser (top 10) and interaction, from `GET /api/embed-tokens/{id}/usage`. The CSV export holds the same aggregates (there are no per-event rows to export, REQ-EMB-008) and is offered only while telemetry is on. Tests: `EmbedUsageReport.spec.js` (3). + +- [x] Task 18: Create `src/components/EmbedTokenForm.vue` (sub-component): + - Reusable form for create + edit flows + - Name/description fields + - Subject picker (dropdown of widgets + dashboards) + - Filter context picker (if subject is dashboard with filterable dimensions) + - Scope editor: + - Radio buttons: Read vs Read-with-Interactions + - Checkboxes for allowedActions (interact, export, drillDown) + - Multi-select for allowedFilters + - HostOrigins multi-input (add/remove origins with validation) + - TenantThemeId picker dropdown + - TokenExpiresAt date picker (optional) + - RateLimitPolicy fields (requestsPerMinute, burstSize) + - Help text + CSP preview button (shows resulting CSP header) + - Submit + cancel buttons + > Built as `src/components/admin/embed/EmbedTokenForm.vue` with the pure helpers in `src/utils/embedToken.js`: subject as a dashboard or one widget of a dashboard (its placements loaded on choice), pinned filters as `dimension=value` lines, scope mode with the allowed actions and filters, host origins checked as `CspService` checks them (wildcards and paths refused, normalised, de-duplicated) with a CSP header preview, theme, expiry date and rate limit (empty = organisation default). Editing a stored token offers only name, description and rate limit. Tests: `EmbedTokenForm.spec.js` (5), `embedToken.spec.js` (18). + +## JS-SDK + +- [x] Task 19: Create the embed SDK package structure: + - `src/LaunchPadEmbed.js` — main entry point (render, on, off, resize methods) + - `src/postMessage.js` — Origin verification + handshake helpers + - `src/types.ts` — TypeScript definitions (EmbedConfig, EmbedInstance, event types) + - `dist/embed-sdk.esm.js` (ESM build) + - `dist/embed-sdk.umd.js` (UMD build) + - `package.json` with exports, version matching app version + > Built under `src/embed-sdk/`: `package.json` (private since Task 24: the SDK is served by the app, not published), `src/LaunchPadEmbed.js`, `src/postMessage.js`, `src/types.ts`, `README.md`. `npm run build:embed-sdk` (`src/embed-sdk/webpack.config.cjs`) builds `js/embed-sdk/embed-sdk.esm.js` and `js/embed-sdk/embed-sdk.umd.js` (global `LaunchPadEmbed`; Task 24 moved the output from `dist/` so the app ships and serves it); `js/` is not committed. Test: `src/embed-sdk/__tests__/dist.spec.js` (3) builds both and loads each. + +- [x] Task 20: Implement `LaunchPadEmbed.render(container, config)` (REQ-EMB-006): + - Accept: `{token, subjectType, subjectId, tenantThemeId (optional)}` + - Create iframe with `src="/apps/launchpad/embed/{subjectType}/{subjectId}"` + - Insert iframe into container + - Wait for `load` event + - Perform postMessage handshake: POST token to iframe (origin verification on both sides) + - Return promise that resolves when 'embed-ready' message received + - Reject promise if errors occur + > `LaunchPadEmbed.render()`: validates the config, creates the iframe (`/embed/{type}/{id}?token=`; the page needs the token to load), waits for `load`, posts `init` with the token and a nonce to the LaunchPad origin only, resolves on the matching `ready`, rejects (and removes the iframe) on a refusal or a timeout. + +- [x] Task 21: Implement event relay in SDK (REQ-EMB-006): + - `.on(eventType, handler)` registers listener for filterApplied, drillDown, export, error, etc. + - Listen for postMessage from iframe + - Invoke registered handlers with event payload + - `.off(eventType, handler)` unregisters listener + - Support multiple listeners per event + > `on()`/`off()` with any number of listeners per event; messages are accepted only from the embed's own window at the LaunchPad origin; an unsolicited refusal arrives as an `error` event; one failing handler does not stop the others. + +- [x] Task 22: Implement `.resize()` method (REQ-EMB-006): + - Read iframe's container dimensions + - Post resize message to iframe with new width/height + - Wait for 'embed-resized' message + - Return promise that resolves when resize complete + > `resize()` posts the container size with a nonce and resolves with the size the embed answers in `resized`; `destroy()` rejects what is pending and removes the iframe. + +- [x] Task 23: Create iframe-side entry point for SDK (`src/embed-entry.js`): + - Listen for postMessage from parent (token injection) + - Verify parent origin against allowed hostOrigins (decoded from token) + - Store token in secure context + - Render widget/dashboard using EmbedRenderService + - Relay interaction events back to parent via postMessage + - Listen for resize messages and re-measure + > Built as `src/embed-entry.js` (webpack entry `embed`, the `launchpad-embed` script `templates/embed.php` loads) mounting `src/views/EmbedView.vue`, which renders the subject through the public share's `PublicDashboardGrid` (no fork) with loading and refusal states. The data request is same-origin, which the server's origin check lets through (`Sec-Fetch-Site: same-origin`). + +- [x] Task 24: Build and serve the SDK with the app (Ruben, 19 Nov 2026: the SDK is served from the app itself, not published on npm): + - `npm run build` also runs `npm run build:embed-sdk`, which writes the ESM and UMD bundles (with source maps) to `js/embed-sdk/`, so every app release carries its own SDK, versioned with the app + - `EmbedSdkController::bundle` serves them at `GET /apps/launchpad/embed-sdk/{file}`: public, no CSRF token, only the four built file names (anything else is a 404), `text/javascript` or `application/json`, `Access-Control-Allow-Origin: *`, `Cross-Origin-Resource-Policy: cross-origin`, `Cache-Control: public, max-age=86400`, an ETag and `X-LaunchPad-Version` + - README with examples (script tag, ESM, TypeScript) loading the SDK from the instance + > Built: the npm publish workflow (`publish-embed-sdk.yml`) is removed and `src/embed-sdk/package.json` is private with no publish metadata. Tests: `tests/Unit/Controller/EmbedSdkControllerTest.php`, `src/embed-sdk/__tests__/dist.spec.js`. + +## Rate Limiting & Revocation + +- [x] Task 25: Implement revocation cache + propagation: + - Store revocation status in Redis (or in-memory cache with 60s TTL) + - On token revocation, immediately set cache entry `revoked:<tokenId> = true` + - Render route checks cache first; if miss, queries database + - Implement purge-cache action: Broadcast cache-clear message to all workers (Redis pub/sub) + - Unit tests: cache hits, TTL expiry, database fallback + > Built as `lib/Service/Embed/RevocationCache.php` over Nextcloud's distributed cache, which every worker shares, so a revocation or a purge reaches all workers at once without a separate broadcast; a miss reads the stored token and is cached for 60 s. Tested in `EmbedTokenServiceTest`. + +- [x] Task 26: Integrate RateLimitService into render route: + - In EmbedController, call `RateLimitService.checkRateLimit(tokenId, now)` + - If 429, write usage event with 429 status + - Return 429 response with Retry-After header + - Include RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset headers + > Each render and data request takes one request from the token's bucket (`RateLimitService`, org default when the token has no policy); a spent bucket answers 429 with `Retry-After` and `RateLimit-*` headers and is written as a page view with status 429; an answered request carries `RateLimit-Limit`, `-Remaining` and `-Reset`. + +- [x] Task 27: Create revocation UI flow in EmbedTokenManager: + - Revoke button → confirmation dialog with reason dropdown + notes textarea + - POST `/api/embed-tokens/{id}/revoke` with reason + notes + - Show success message + - Update token list (status changes to REVOKED) + - Un-revoke button (clear revokedAt, show confirmation) + > `src/dialogs/RevokeEmbedTokenDialog.vue` (reason select, optional notes) opened from the token detail view; on confirm `POST /api/embed-tokens/{id}/revoke`, a success toast, and the status shown as revoked with a Restore button (`/unrevoke`). Tests: `EmbedDialogs.spec.js`, `EmbedTokenManager.spec.js`. + +## Usage Telemetry + +- [x] Task 28: Implement usage event capture (REQ-EMB-008): + - In EmbedController render route, after rendering widget: + 1. Extract host origin from Origin or Referer header + 2. Parse user-agent: extract browser family + major version + 3. Compute user-agent hash: sha256(full UA string) + 4. Compute viewport bucket: small/medium/large from request context (if available from SDK) + 5. Measure response latency + 6. Create `embed_usage_event` row with all fields + - Unit tests: PII minimisation (no IP, no full UA, no end-user identifier) + > Partly built: `lib/Entity/EmbedUsageEvent.php` builds the event (origin from Origin, else scheme and host of Referer; browser family + major; sha256 of the UA; viewport bucket; latency) and `Service/Embed/UsageTelemetryService::record()` writes it, absorbing a failed write. Tests: `UsageTelemetryServiceTest`. `EmbedController` now writes every render (`pageView`) and data load (`widgetRendered`) and `EmbedTokenMiddleware` every refused render whose token is known (expired and revoked tokens included, their id being proven by the signature). + +- [x] Task 29: Create usage report API: + - `GET /api/embed-tokens/{id}/usage` — Summary stats + aggregated events (by date, by host origin, by viewport, by browser) + - Respond with JSON suitable for charts (date series, bar data, pie data) + - No individual-user rows (aggregation only) + > Partly built: `UsageTelemetryService::report()` aggregates the last 7 days by date, host origin, viewport, browser (top 10), interaction and status, and counts use after revocation (REQ-EMB-009 9.4). Served at `GET /api/embed-tokens/{id}/usage` by `Controller/EmbedTokenApiController`, which is also the admin API the token manager needs: list, show, create (201 with the JWT once), update, revoke, unrevoke, re-issue, purge-cache, and `GET`/`PUT /api/embed-settings/telemetry` (admin-only, 503 without OpenRegister; documented in `openapi.json` as internal). Tests: `EmbedTokenApiControllerTest` (5). + +- [x] Task 30: Implement telemetry kill-switch: + - Add org setting: `embed_telemetry_enabled` (boolean, default true) + - In render route, check setting before writing `embed_usage_event` + - If disabled, skip event capture (no row written) + - Audit log when toggle is changed + - Admin UI: Settings page checkbox for "Collect embed usage telemetry" + > `embed_telemetry_enabled` (IAppConfig, default on), checked by `record()`, and `setEnabled()` dispatches a `CriticalActionPerformedEvent` for the audit log on each change. The admin switch is `src/components/admin/EmbedTelemetryToggle.vue` in Admin settings ▸ Operations ("Collect embed usage telemetry"), over `src/services/embedApi.js`; it rolls back when saving fails. Tests: `EmbedTelemetryToggle.spec.js` (5). + +## Testing & Documentation + +- [x] Task 31: PHPUnit tests for JWT signing: + - Sign a JWT with RS256, verify signature + - Verify JWT with wrong key fails + - Verify expired JWT rejected + - Verify revoked token rejected + - Key rotation: old key still verifies old tokens, new key signs new tokens + > `JwtSigningServiceTest`: RS256 sign/verify, wrong key, expired, key rotation; revoked token rejected in `EmbedTokenServiceTest`. + +- [x] Task 32: PHPUnit tests for token lifecycle: + - Create token → retrieve JWT (once) + - Re-retrieve → no JWT + - Update token (name, rateLimitPolicy) + - Revoke token → subsequent requests rejected + - Un-revoke token → requests accepted again + > `EmbedTokenServiceTest`. + +- [x] Task 33: PHPUnit tests for scope enforcement: + - Read-only token rejects POST/PUT/PATCH/DELETE + - Read-with-interactions token allows pinned filters + - Action scope: export allowed only if in allowedActions + - Filter scope: filter dimensions restricted to allowedFilters + > `ScopeEnforcementServiceTest` (read refuses writes, interactions run only allowed actions, filter dimensions restricted to `allowedFilters`, actions from the path), `EmbedGateTest` and `EmbedTokenMiddlewareTest` (a write under a read token refused before the controller, reads pass). + +- [x] Task 34: Vitest tests for JS-SDK: + - Render method creates iframe, performs postMessage handshake + - Event listeners registered + invoked on iframe messages + - Resize method posts message + resolves promise + - Origin verification prevents cross-origin leaks + - Multiple embeds on same page are independent + > `src/embed-sdk/__tests__/LaunchPadEmbed.spec.js` (13): iframe and handshake, refusal and timeout, config checks, listeners added and removed, foreign origin, window and message kind ignored, resize, two embeds kept apart, destroy. + +- [x] Task 35: Playwright integration tests: + - Create embed token via admin UI + - Render widget in iframe with token (public render route) + - Verify CSP headers present + - Verify filter interaction works (drill-down) + - Verify read-only token blocks write operations + - Verify theme CSS variables applied + - Verify rate limiting (429 after quota exceeded) + - Verify revocation takes effect within 60s + > `tests/e2e/embedded-analytics.spec.ts` (#1450): 11 of 11 green on the live pass stack 20-21 Nov (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): token issued in Admin settings, framed render, CSP and rate-limit headers, origin and token refusals, read-only writes refused (Nextcloud's 401 on login routes, 403 `read_only_token` on public ones), filters under the pinned context, theme, 429 after the burst, revocation within 60 s, and a drill-down reaching the host page through the SDK. + +- [x] Task 36: Create documentation: + - `docs/embed/overview.md` — Purpose + use cases + security model + - `docs/embed/admin-guide.md` — Token creation, revocation, theming, usage analytics + - `docs/embed/integration-guide.md` — How to integrate SDK (iframe + JS-SDK form factors) + - `docs/embed/sdk-reference.md` — JS-SDK API (render, on, resize, event types) + - `docs/embed/troubleshooting.md` — Common issues (CSP errors, CORS, origin mismatch) + > Written as `docs/embed/overview.md`, `admin-guide.md` (the admin API, since the token manager UI of Tasks 15-18 is still to come), `integration-guide.md`, `sdk-reference.md` and `troubleshooting.md` (every refusal code). + +- [x] Task 37: i18n for new UI strings: + - Token manager: create, revoke, re-issue, usage, accessibility warning + - Theme manager: create, edit, delete, preview + - Admin notification: token revoked, policy updated + - All strings in both NL (Dutch) + EN (English) + - Add to `src/translations/nl.json` + `src/translations/en.json` + > The 115 new frontend strings (two of them plurals, keyed `_<singular>_::_<plural>_`) are in `l10n/en.js` and translated in `l10n/nl.js`; the app keeps its catalogues in `l10n/`, not `src/translations/`. Identical to English in NL as cognates: Sites, Logo, Tokens, `Widget {id}`, `Dashboard {name}`. The other locales the parity check lists (a warning-only CI lane) still need these strings; that is a translation pass, not code. + +## Quality & Integration + +- [x] Task 38: ESLint clean on new files: + - Run `npm run lint` on all new/modified Vue + JS files + - Fix any warnings or errors before merging + - Ensure axe-core check output is clean (no accessibility violations) + > ESLint reports no errors or warnings on the 35 JS/Vue/TS files this change adds or modifies (the two errors `npm run lint` prints are in `Announcements/__tests__/announcements.spec.js`, inherited from development). The admin template spec now stubs the Embeds tab, which removed the 22 unhandled rejections the tab's API calls caused in the suite. The axe-core output belongs to the build step of Task 12. + +- [x] Task 39: Security audit checklist: + - JWT signature verification is unconditional (no bypass paths) + - Scope enforcement at API tier (not UI) + - CSP frame-ancestors + Fetch-Metadata headers present + - No IP addresses captured in telemetry + - Rate limiting prevents abuse + - Revocation propagates within 60s + - Read-only tokens cannot mutate state + - Wildcard origins rejected at creation time + > Audited item by item against the code on 2026-11-22. + > - JWT verification unconditional: holds. The only way in is `EmbedGate::authenticate` → `EmbedTokenService::validateToken` (`lib/Service/Embed/EmbedTokenService.php:228`), which always calls `JwtSigningService::verify`; the key is picked by `kid` and `alg` together and only RS256/ES256 are accepted (`JwtSigningService.php:281-284`, so `alg: none` and algorithm confusion are refused), `openssl_verify` must return exactly 1 (`:232`), and expiry is decided only after the signature holds. On top of that the token's SHA-256 must match the stored hash (`EmbedTokenService.php:238`, `hash_equals`). The unverified claims are read in two places only: the issuer check that decides whether the middleware engages (`EmbedGate::carriesEmbedToken`, which then still validates) and the token id of a refusal that already passed verification. Tests: `JwtSigningServiceTest` (`testATamperedPayloadFailsToVerify`, `testAWrongKeyWithTheSameKidFailsToVerify`, `testAnAlgorithmTheKeyIsNotOfIsRefused`, `testAnUnsupportedAlgorithmIsRefused`, `testARevokedKeyNoLongerVerifies`), `JwtSigningEdgeCasesTest`, `EmbedTokenServiceTest::testValidationNeedsTheSignatureAndTheStoredHash`. + > - Scope enforcement at the API tier: holds. `EmbedTokenMiddleware::beforeController` (`lib/Middleware/EmbedTokenMiddleware.php:79-94`, registered in `Application.php:103`) checks the scope before any controller runs; `EmbedController::admitted` refuses a token on another subject (403 that does not say whether it exists), and the data route pins the filter context and drops filters the scope does not allow server-side (`EmbedRenderService.php:218`, `ScopeEnforcementService::restrictFilters`). Tests: `EmbedTokenMiddlewareTest::testAReadTokenCannotWriteAnywhereEvenWhenTheUiIsBypassed`, `EmbedControllerTest::testAnotherSubjectIsRefusedWithoutRenderingAnything`, `ScopeEnforcementServiceTest::testFilterDimensionsAreRestrictedToAllowedFilters`, `::testTheFilterContextIsPinned`. + > - CSP frame-ancestors and Fetch Metadata: holds. The page lists only the token's host origins as frame ancestors (`EmbedRenderService.php:183`), with `X-Frame-Options` as the legacy fallback and `nosniff`; `EmbedGate::originRefusal` (`EmbedGate.php:208-228`) refuses with 403 when `Sec-Fetch-Site` says cross-site (or a Bearer request is not same-origin) and the Referer's origin is not a host origin. Tests: `EmbedRenderServiceTest::testThePageIsFramedOnlyByTheHostOriginsAndCarriesTheTheme`, `EmbedGateTest::testAFramingPageOutsideTheHostOriginsIsRefused`, `EmbedControllerTest::testAFramingPageOffTheHostOriginsIsRefused`. + > - No IP addresses in telemetry: holds. `EmbedUsageEvent::build` (`lib/Entity/EmbedUsageEvent.php:74`) takes no address at all: the host origin is cut down to scheme and host, the user agent to a browser family plus a hash, the viewport to a bucket. Tests: `UsageTelemetryServiceTest::testARecordedEventHoldsNoPersonalData`, `::testTheEventFieldsAreBucketed`. + > - Rate limiting: holds. A per-token token bucket (`RateLimitService`, distributed cache, `EmbedController.php:182`) answers 429 with `Retry-After`; under it, Nextcloud's per-address `AnonRateLimit` (300 and 600 a minute, `EmbedController.php:94,121`) runs before the token is even parsed, which also bounds guessing at invalid tokens. The per-token bucket needs a memcache; without any (Nextcloud then uses a null cache) only the per-address limit applies. Tests: `RateLimitServiceTest` (4), `EmbedControllerTest::testASpentBucketIsA429WithRetryAfter`, `::testThePublicRoutesAreRateLimitedPerAddress`. + > - Revocation within 60 s: holds. A revoke or re-issue writes "revoked" into the distributed cache at once (`EmbedTokenService.php:277,327`); any other cached answer lives at most `RevocationCache::TTL` = 60 s (`RevocationCache.php:44`), so a revocation written straight to the store is seen within a minute, and the purge action makes it immediate. Tests: `EmbedTokenServiceTest::testRevocationTakesEffectAndCanBeUndone`, `::testThePurgeMakesEveryWorkerReadTheStore` (the cache double asserts the 60 s TTL on every write). + > - Read-only tokens cannot mutate state: holds. Every method but GET and HEAD needs a `read-with-interactions` token naming the action (`ScopeEnforcementService::refusalFor`); a route that needs a Nextcloud login refuses an embed token before LaunchPad runs (an embed token is not a login). Tests: `ScopeEnforcementServiceTest::testAReadTokenRefusesEveryWrite`, `EmbedTokenMiddlewareTest::testAReadTokenCannotWriteAnywhereEvenWhenTheUiIsBypassed`, `EmbedGateTest::testTheScopeDecidesWritesAndLetsReadsThrough`. + > - Wildcard origins rejected at creation: holds. `CspService::validateOrigins` (`CspService.php:76-85`) refuses any origin containing `*`, an empty list and anything that is not scheme plus host; `EmbedTokenService::createToken` runs it before anything is stored (`EmbedTokenService.php:430`), and an update cannot change the host origins. Tests: `CspServiceTest::testWildcardsAndMalformedOriginsAreRefused`, `EmbedTokenServiceTest::testAMalformedOriginIsRefusedAndNothingIsStored`. + > - No token in logs (added to the list): the JWT is never logged or stored, only its SHA-256 (`EmbedTokenService.php:238`) and its id in log context; metadata carries neither (`EmbedTokenServiceTest::testMetadataHasNoJwtAndNoHash`). One gap was found and fixed: the embed page sent `Referrer-Policy: strict-origin-when-cross-origin`, so every same-origin request it made (its scripts, styles and the data call) carried the full page URL, `?token=` included, as Referer, which web servers write into their access logs. It now sends `strict-origin` (`EmbedRenderService.php:189`), the origin only; the origin checks need no more than that. Test: `EmbedRenderServiceTest::testThePageNeverSendsItsTokenUrlAsReferer` (fails on the old header). What remains by design: the plain-iframe form puts the token in the render URL itself, so the access log line of that one request holds it, and Nextcloud's own log adds the request URL to any line written during it. The admin guide already tells hosts to keep the token with their secrets; web server access log retention is the operator's to set. + +- [x] Task 40: Integration with existing LaunchPad features: + - Dashboards display "Share" → includes "Create embed token" action alongside existing share modes + - Widgets display "Embed" button → quick token creation for single widget + - Admin Settings → "Embed Tokens" section with manager + themes + - Audit log records token lifecycle (create, revoke, re-issue) + > Admin settings has an Embeds tab (`tabs/EmbedsTab.vue`: token manager and theme manager); an administrator's dashboard menu has "Create embed token", opening that tab with the dashboard pre-selected (`?tab=embeds&embedType=dashboard&embedId=&embedDashboard=`, read by `embedDefaultsFrom`, built by `embedAdminSearch`); in view mode an administrator's widget has the same entry in its own options menu (`WidgetWrapper` `embedHref`, built by `Views.placementEmbedHref` → `embedAdminHref(dashboard, placement)`), opening the tab with that widget placement pre-selected (`embedType=widget`); the shared edit cog (`CnWidgetEditCog`) is left alone, as it only shows in edit mode. The token lifecycle (issue, revoke, restore, re-issue) is written to the audit log by `EmbedTokenService` (`CriticalActionPerformedEvent`, tested in `EmbedTokenServiceTest`). Tests: `WidgetWrapper.embed.spec.js` (3), `Views.placementEmbed.methods.spec.js` (2), `DashboardRowActions.embed.spec.js` and `embedToken.spec.js` (`embedAdminSearch`). + +## Verification + +`openspec validate` exits clean. Embed tokens are creatable via admin UI, render publicly with CSS variables + scope enforcement, propagate revocation within 60s, and write auditable telemetry. + +## Tests (company-wide ADR-009) + +- PHPUnit: JWT signing, token lifecycle, scope enforcement, rate limiting, CSP validation +- Vitest: JS-SDK render, event relay, origin verification +- Playwright: End-to-end from token creation to rendered widget, filter interaction, revocation propagation + +## Documentation (company-wide ADR-010) + +- User guide: Token creation, revocation, theme management +- Developer guide: SDK integration (iframe + JS-SDK), event handling, CSP configuration +- Architecture: JWT signing, scope model, telemetry PII minimisation + +## i18n (company-wide ADR-005) + +Dutch (NL) + English (EN) parity for all new UI strings and user-facing messages. diff --git a/openspec/changes/archive/2026-11-22-map-support/proposal.md b/openspec/changes/archive/2026-11-22-map-support/proposal.md new file mode 100644 index 000000000..12051aa25 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-map-support/proposal.md @@ -0,0 +1,33 @@ +# Map support — render geospatial dashboard widgets + +Render geospatial properties from OpenRegister objects on a map widget inside launchpad dashboards. Adds a new `map` widget type alongside the existing chart / KPI / table widgets, consuming the GeoJSON storage + spatial-query API that OpenRegister's `geo-metadata-kaart` change is shipping. + +## Affected code units + +- `@conduction/nextcloud-vue` `CnMapWidget` / `CnMapWidgetForm` (in the nextcloud-vue repository): PDOK base map presets and the `markers.geoProperty` data source (point, line, polygon, multi-geometry). +- LaunchPad: only the `@conduction/nextcloud-vue` pin, once that change is released. The communal `map` type already reaches the widget picker through `widgetRegistry.js`. +- No DB schema change. + +## Why a new change + +Map rendering is a contained UI surface that depends on geospatial data shipped by OpenRegister, but the rendering decisions (Leaflet vs MapLibre, tile-layer choice, layer control UX, clustering strategy) are launchpad-specific. Splitting this change keeps the OpenRegister geo spec focused on storage + API contracts and lets launchpad iterate the widget independently. + +## Approach + +- The map is nextcloud-vue's shared `CnMapWidget` (Leaflet 1.9 with clustering), registered communally as the `map` widget type. LaunchPad builds no map widget and adds no map library; PDOK tile sources and the geo-property data source are added to the shared widget, keeping the content shape existing map widgets store (Ruben, 19 Nov 2026). +- Default base layer: PDOK BRT achtergrondkaart (`https://service.pdok.nl/brt/achtergrondkaart/wmts/v2_0`). +- Coordinate transformation (WGS84 ↔ EPSG:28992 RD) via `proj4` when widgets request RD-projected output. +- Widget configuration UI: register/schema picker (reuse existing dashboard-widget config), spatial filter (none / bbox / drawn polygon), clustering threshold. +- Click-to-detail: clicking a feature opens the underlying OpenRegister object's deep-link in a new tab via the existing deep-link-registry. + +## Hand-off context + +Filed as a sibling to: +- OpenRegister `geo-metadata-kaart` change (decision 2026-05-02): scope-tightened to GeoJSON storage + spatial-query API; UI deferred to consuming apps. https://github.com/ConductionNL/openregister/blob/feat/openspec-batch-impl-2026-05-02/openspec/changes/geo-metadata-kaart/tasks.md +- WOO Tilburg sibling: https://github.com/ConductionNL/tilburg-woo-ui/issues/436 + +## Notes + +- Out of scope for this change: BAG/BGT base-registration overlays (deferred to a follow-up `map-overlays-bag-bgt` change once the base widget is in production). +- Out of scope: INSPIRE metadata compliance (a publication-side concern, not a widget-side concern). +- Out of scope: WFS/GeoJSON export from the widget — the OpenRegister API already exposes GeoJSON; widget consumers can call the API directly. diff --git a/openspec/changes/archive/2026-11-22-map-support/screens.md b/openspec/changes/archive/2026-11-22-map-support/screens.md new file mode 100644 index 000000000..d5853978e --- /dev/null +++ b/openspec/changes/archive/2026-11-22-map-support/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWidgetInstellen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetInstellen (configuring the map widget) +- Design backlog: LpKaartWidget (decision 157), the map widget itself diff --git a/openspec/changes/archive/2026-11-22-map-support/specs/map-widget/spec.md b/openspec/changes/archive/2026-11-22-map-support/specs/map-widget/spec.md new file mode 100644 index 000000000..1b39cac7e --- /dev/null +++ b/openspec/changes/archive/2026-11-22-map-support/specs/map-widget/spec.md @@ -0,0 +1,40 @@ +# Map widget + +## ADDED Requirements + +### Requirement: REQ-MAP-001 A map widget shows register objects that carry a location + +LaunchPad SHALL offer a `map` widget type that renders the GeoJSON geometry of OpenRegister objects (points, lines, polygons and multi-geometries) on a PDOK BRT base map, fetched through OpenRegister's spatial-query API. The map SHALL be nextcloud-vue's shared `CnMapWidget`, registered as the communal `map` type; LaunchPad SHALL NOT ship a map widget or map library of its own, and new configuration keys SHALL be optional so the content existing map widgets store keeps rendering. + +#### Scenario: Objects with a location appear on the map + +- GIVEN a map widget configured with a register, a schema and the schema's geo property +- WHEN the dashboard loads +- THEN every object the user may read that has a value in the geo property SHALL be drawn on the map +- AND the widget SHALL show a loading state while the query runs and an empty state when no object has a location + +#### Scenario: Dense point sets are clustered + +- GIVEN a map widget with a clustering threshold +- WHEN more points fall in one area than the threshold +- THEN the widget SHALL draw them as one cluster that splits when the user zooms in + +### Requirement: REQ-MAP-002 A map widget configuration is validated on save + +Saving a `map` widget SHALL be refused unless the configuration names `register`, `schema` and `geoProperty`; `spatialFilter` (none, bbox or polygon) and `clusterThreshold` are optional. + +#### Scenario: A map widget without a geo property is refused + +- GIVEN a dashboard author configuring a map widget +- WHEN they save it without choosing a geo property +- THEN the save SHALL be refused with a message that names the missing field + +### Requirement: REQ-MAP-003 Clicking a feature opens its object + +Clicking a feature on the map SHALL open the underlying OpenRegister object through the deep-link registry. + +#### Scenario: Open an object from the map + +- GIVEN a map widget showing objects +- WHEN the user clicks one feature +- THEN the object's deep link SHALL open in a new tab diff --git a/openspec/changes/archive/2026-11-22-map-support/tasks.md b/openspec/changes/archive/2026-11-22-map-support/tasks.md new file mode 100644 index 000000000..ce7e14669 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-map-support/tasks.md @@ -0,0 +1,47 @@ +# Tasks: Map support widget + +## Frontend + +> Built in the shared library, not in LaunchPad (Ruben, 19 Nov 2026). +> `@conduction/nextcloud-vue` ships `CnMapWidget` and `CnMapWidgetForm` and +> registers them communally as the `map` dashboard widget type; LaunchPad's +> `widgetRegistry.js` offers every communal type with a form, so `map` is in the +> widget picker without a LaunchPad widget. LaunchPad adds no map library of its +> own (no `@vue-leaflet/vue-leaflet`, no `vue2-leaflet`). The library is extended +> instead, keeping the stored content shape of existing map widgets: new keys +> are optional, and a chosen base map is stored as an ordinary `basemaps[]` item. + +- [x] PDOK tile sources in the shared map widget: `CnMapWidgetForm` offers OpenStreetMap and the PDOK BRT achtergrondkaart (standaard, grijs, pastel) and luchtfoto presets, in EPSG:3857, stored as plain `basemaps[]` items (nextcloud-vue PR [ConductionNL/nextcloud-vue#2219](https://github.com/ConductionNL/nextcloud-vue/pull/2219), merged into main 19 Nov, released in 2.182.0). +- [x] Geo-property data source in the shared map widget: `markers.geoProperty` draws each object from that property, a GeoJSON geometry of any type (point, line, polygon, multi-geometry) or a lat/lng value, falling back to `@self.geo` (same PR). +- [x] Raise launchpad's `@conduction/nextcloud-vue` pin to the release that carries that PR (2.182.0). +- [x] Spatial filters (bbox / polygon / nearest-N) in the shared widget's data source, through OpenRegister's geo filters. Not in the PR above. + - Built in nextcloud-vue (#2220, released in 2.183.0, change `map-spatial-filter-and-detail-link`): `markers.dataSource.spatialFilter` takes `{ bbox }`, `{ near, radius }` or `{ within: <Polygon> }` and sends them as OpenRegister's `geo.bbox`, `geo.near`/`geo.radius` or a `geo-search` POST, with `geoProperty` as `geo.property`; a changed filter reads the markers again. OpenRegister has no nearest-N query, so a radius with `limit` stands in for it. launchpad pins nextcloud-vue 2.184.0. +- [x] Click-to-detail: clicking a feature opens the underlying object's deep-link in a new tab using the deep-link-registry. + - Built in the same nextcloud-vue PR: `markers.detailLink` (tokens `{id}`, `{register}`, `{schema}`, `{<property>}`) opens a clicked object in a new tab; without it, the `url` the object carries is opened, which is the address OpenRegister's deep-link registry stamps where it stamps one. OpenRegister's object list does not stamp that `url` on every row yet, so a dashboard map names its `detailLink`. + +## Backend + +- [x] Document the `map` widget type in the canonical launchpad widget catalogue. + - `docs/features/widgets.md` § map: `geoProperty`, `spatialFilter`, `detailLink`, the PDOK presets, an example and the save-time checks. +- [x] Validate `map`-typed widget configurations on save (left: the library widget's content has no `geoProperty`, and a map of `layers` only, or of a `url` source, is valid without a register or schema, so the rule as written would refuse working maps; it needs restating against the library's content shape first): required `register`, `schema`, `geoProperty` keys; optional `spatialFilter`, `clusterThreshold`. + - Restated against the library's content shape and built as `lib/Service/MapContentValidator.php`, called from `WidgetService::validateWidgetContent()` for `map`: a register source needs both register and schema, a spatial filter is exactly one readable bbox, radius or polygon and needs a register source, a detail link is an app path or an http(s) address, `geoProperty` a name. A map of `layers` only, or of inline or `url` markers, stays valid without a register. `clusterThreshold` is not a library key, so it is not checked. + +## Testing + +- [x] Unit test for `MapWidgetConfig.vue` validation logic. + - The map's form is the library's `CnMapWidgetForm`, so there is no `MapWidgetConfig.vue`; the save-time rules are unit-tested in `tests/Unit/Service/MapContentValidatorTest.php` (18 cases). +- [x] Unit test for the spatial-filter to API-query translator in the store. + - The translator is nextcloud-vue's `spatialFilterRequest()`, tested in its `tests/components/CnMapWidgetSpatialFilter.spec.js` (bbox, radius, polygon, unreadable filters, and the requests the widget makes). +- [x] Playwright smoke: drop a `map` widget on a fresh dashboard, configure it against a register/schema with geo data, confirm features render and click-to-detail navigates correctly. + - 2026-11-22: tests/e2e/map-widget-smoke.spec.ts passed on the live stack (triage/lpf-6-bundle.log): three markers, tooltip, and the detail link opens in a new tab at the dashboard's slug address. + +## Documentation + +- [x] Add a "Map widget" section to the dashboard-authoring docs. (`docs/features/widgets.md`, `## map`, and a catalogue row.) +- [x] Cross-reference OpenRegister's geo-metadata-kaart change so authors know which OR features ship the underlying data. (In the `map` section.) + +## Out of scope (separate follow-up changes) + +- BAG / BGT base-registration overlays — `map-overlays-bag-bgt`. +- INSPIRE metadata compliance — publication-side concern, not widget-side. +- Map drawing / geometry editing — `map-drawing-tools`. diff --git a/openspec/changes/openregister-leaf-integrations/.openspec.yaml b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/.openspec.yaml similarity index 100% rename from openspec/changes/openregister-leaf-integrations/.openspec.yaml rename to openspec/changes/archive/2026-11-22-openregister-leaf-integrations/.openspec.yaml diff --git a/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/design.md b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/design.md new file mode 100644 index 000000000..6eec261a6 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/design.md @@ -0,0 +1,86 @@ +# Design — OpenRegister Leaf Integrations (Talk on Shared Dashboards) + +## Context + +OpenRegister's integration leaves are adopted declaratively (`configuration.linkedTypes` on a schema). LaunchPad has a single `Dashboard` schema and currently adopts zero leaves. The design question for this change was not "how do we build a discussion feature" — the leaf and Talk own that — but three scoping decisions: + +1. Which leaves, if any, honestly fit a schema whose objects are layout configurations rather than domain records? +2. Where does the leaf declaration live — base register file or a `register.d` overlay? +3. What gates the discussion surface — a new ACL, or the existing dashboard view guard? + +## Goals / Non-Goals + +**Goals:** + +- Adopt the talk leaf for shared and group dashboards with zero bespoke chat code. +- Keep the declaration additive and overlay-based so the base register file stays a clean statement of the domain. +- Reuse `PermissionService::canViewDashboard()` as the single authorization truth for discussion access. +- Document explicitly why the remaining ~18 leaves are not adopted, so future sweeps do not re-litigate this. + +**Non-Goals:** + +- Building comments, mentions, or notification features in launchpad — the leaf renders, Talk hosts. +- Adopting the files leaf, mail sidebar linking (`configuration.linkedTypes: ["mail"]`), or `mailObjectTemplate` — see D1. +- Per-widget or per-tile discussions — the conversation unit is the dashboard object. + +## Decisions + +### D1: Adopt exactly one leaf — talk. Every other leaf is scoped out. + +**Decision**: Declare only `"talk"` in `linkedTypes`. No files, no mail, no calendar/contacts/maps/etc. + +**Alternatives considered:** + +- **Adopt files + talk** (the two "generic collaboration" leaves): rejected for files because LaunchPad already owns a resource pipeline for dashboard assets (`ResourceController`/`ResourceService`, REQ-RES-001..014, routes `/api/resources*`) and a files widget for user storage. A generic attachments panel on a layout-configuration object duplicates that machinery with no user story behind it. +- **Adopt the full catalogue for uniformity with sibling apps**: rejected — sibling apps (larpingapp, pipelinq, shillinq) attach leaves to schemas describing people, events, contracts. `Dashboard` describes none of these; declaring leaves that render meaningless panels is padding, and an unused surface is an unaudited surface. + +**Rationale**: The one place LaunchPad has real multi-user collaboration around a single object is shared/group dashboards (manifest features "Dashboard sharing", "Group dashboards"; `sharedWith`, `type: group_shared`, `groupId` in the schema; the whole REQ-SHARE surface). A conversation about *this dashboard* is the only leaf-shaped gap. The schema's own `"mailEnabled": false` confirms mail was already considered and rejected at the domain level. + +### D2: Declaration lives in a `register.d` overlay, not the base register file + +**Decision**: New file `lib/Settings/register.d/dashboard-talk-leaf.json` containing only the `configuration.linkedTypes` addition for the `Dashboard` schema. + +**Alternatives considered:** + +- **Edit `launchpad_register.json` directly**: rejected. The fleet pattern (larpingapp's `register.d/*-leaf.json` overlays) keeps each leaf adoption a self-contained, reviewable, revertable file, and keeps the base file a pure domain statement. LaunchPad's `register.d/` directory already exists (README only) precisely for this. + +**Rationale**: Overlay files make the adoption diff one file, and removing the leaf later is deleting one file rather than surgically editing the 310-line base register. + +### D3: Discussion access = dashboard view access; surface only on shared dashboards + +**Decision**: The discussion surface renders only when the dashboard is collaborative (`group_shared`, or has active shares / non-empty `sharedWith`), and reaching it requires `PermissionService::canViewDashboard()` to pass. Share revocation ends access. + +**Alternatives considered:** + +- **Show discussion on every dashboard, including unshared personal ones**: rejected — a room with one member is noise, and it would create Talk rooms for thousands of personal dashboards nobody discusses. +- **Separate discussion ACL (opt-in per participant)**: rejected — a second ACL diverges from the dashboard's own access over time (the classic parallel-permission drift), and the view guard already encodes owner/share/group logic in one audited place. + +**Rationale**: One authorization truth. `canViewDashboard()` already resolves ownership, user/group shares, and group membership; the leaf simply inherits its answer. + +### D4: Hard fail nowhere — Talk absence degrades to absence of the surface + +**Decision**: With Talk missing/disabled the affordance does not render and nothing errors. LaunchPad's manifest does not gain a Talk dependency. + +**Rationale**: LaunchPad must keep booting and rendering dashboards on instances without Talk (ADR-083-style boot safety); an integration leaf is an enhancement, never a prerequisite. + +### D5: A shared dashboard is mirrored as an OpenRegister object (Ruben, 19 Nov 2026) + +**Decision**: When a dashboard is shared or is a group dashboard, launchpad keeps an object of the Dashboard schema for it in OpenRegister (`DashboardDiscussionMirror`), slug and, for a new object, uuid equal to the dashboard's uuid (the mapping `Version002000Date20260519000000` used). The object carries `audienceUsers`, `audienceGroups` and `audienceEveryone`, derived the way `PermissionService::resolveAccessLevel()` derives view access, and the overlay gives the Dashboard schema a read rule that admits a reader only through them (`$contains`, as OpenRegister's shared credentials do). A share change dispatches `DashboardAudienceChangedEvent`, whose listener rewrites the object, so a revoked user is refused by OpenRegister. A dashboard that stops being shared keeps its object, narrowed to its owner; a deleted dashboard loses it. A repair step mirrors dashboards shared before this existed. Without OpenRegister nothing is written. + +**Why**: dashboards live in launchpad's own table, so the talk leaf had no object to attach to. Alternatives were moving dashboards into OpenRegister (too large) or a Talk room owned by launchpad (a parallel ACL, rejected in D3). + +**Trade-off**: LaunchPad Admins who are not Nextcloud administrators reach a group dashboard through launchpad's role, which OpenRegister does not know; they see the dashboard but not its discussion unless they are in its group. + +## Risks / Trade-offs + +- **Risk**: The leaf's render contract may evolve in OpenRegister; launchpad's wiring is intentionally thin so the blast radius is the overlay file plus one mount point. +- **Trade-off**: Users of unshared personal dashboards get no discussion surface at all. Accepted: share the dashboard first — that is the collaboration signal. +- **Risk**: Schema overlay import failing silently (see the cautionary note inside `launchpad_register.json` about the schema importer rejecting union types). Mitigated by an explicit import verification task. + +## Migration Plan + +None required. The overlay is additive; no data or existing-object changes. Rollback = delete the overlay file and re-import. + +## Open Questions + +- Whether the discussion mounts in the dashboard sidebar or the dashboard settings panel is left to the leaf's standard render surface — decided at implementation against the leaf's contract, not re-specified here. diff --git a/openspec/changes/openregister-leaf-integrations/hydra.json b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/hydra.json similarity index 100% rename from openspec/changes/openregister-leaf-integrations/hydra.json rename to openspec/changes/archive/2026-11-22-openregister-leaf-integrations/hydra.json diff --git a/openspec/changes/openregister-leaf-integrations/proposal.md b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/proposal.md similarity index 100% rename from openspec/changes/openregister-leaf-integrations/proposal.md rename to openspec/changes/archive/2026-11-22-openregister-leaf-integrations/proposal.md diff --git a/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/screens.md b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/screens.md new file mode 100644 index 000000000..7766af50b --- /dev/null +++ b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWidgetKiezen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetKiezen +- LpDelen the Talk conversation beside a shared dashboard, and the Share dialog of a personal dashboard without it (REQ-LEAF-002, REQ-LEAF-003) https://identity.conduction.nl/screens/board?id=launchpad/LpDelen diff --git a/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md new file mode 100644 index 000000000..33c406951 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md @@ -0,0 +1,96 @@ +--- +capability: dashboard-talk-leaf +delta: false +status: draft +--- + +# Dashboard Talk Leaf — Discussion on Shared Dashboards + +## Context + +LaunchPad stores dashboards as OpenRegister objects under a single `Dashboard` schema (`lib/Settings/launchpad_register.json`). OpenRegister ships an app-agnostic **talk** integration leaf that any app can adopt by declaring `configuration.linkedTypes: ["talk"]` on a schema. This capability adopts that leaf — and only that leaf — so the people a dashboard is shared with can discuss it in a Talk conversation bound to the dashboard object. No bespoke chat code, storage, or wrapper controllers are added. + +## ADDED Requirements + +### Requirement: REQ-LEAF-001 Talk leaf declared on the Dashboard schema via register.d overlay + +The talk leaf MUST be declared declaratively, not in code. A new overlay file `lib/Settings/register.d/dashboard-talk-leaf.json` MUST add `configuration.linkedTypes: ["talk"]` to the `Dashboard` schema, following the established fleet overlay shape (`components.schemas.Dashboard.configuration.linkedTypes`, as in larpingapp's `register.d/player-to-contacts-leaf.json`). The base `launchpad_register.json` MUST NOT be edited for this; the overlay is the single source of the declaration. + +#### Scenario: Overlay declares the leaf + +- **GIVEN** the app is installed or upgraded with the overlay file present +- **WHEN** the register/schema import runs +- **THEN** the imported `Dashboard` schema MUST carry `configuration.linkedTypes` containing exactly `"talk"` +- **AND** no other leaf type MUST be declared by launchpad + +#### Scenario: Base register file untouched + +- **GIVEN** the change is implemented +- **WHEN** `lib/Settings/launchpad_register.json` is inspected +- **THEN** it MUST contain no `linkedTypes` key — the declaration lives only in `register.d/dashboard-talk-leaf.json` + +### Requirement: REQ-LEAF-002 Discussion surface renders only on shared dashboards + +The Talk discussion surface MUST render only for dashboards that are genuinely collaborative: `type === 'group_shared'`, or a dashboard with at least one active share (user/group shares via `DashboardShareService`, or a non-empty `sharedWith`). A personal dashboard with no shares MUST NOT show any discussion affordance — there is nobody to talk to. + +#### Scenario: Group dashboard shows discussion + +- **GIVEN** a `group_shared` dashboard scoped to group `marketing` +- **WHEN** a member of `marketing` opens that dashboard +- **THEN** the Talk discussion surface MUST be available for that dashboard + +#### Scenario: Shared personal dashboard shows discussion + +- **GIVEN** a personal dashboard the owner has shared with user `alice` +- **WHEN** the owner or `alice` opens the dashboard +- **THEN** the Talk discussion surface MUST be available + +#### Scenario: Unshared personal dashboard shows nothing + +- **GIVEN** a personal dashboard with no shares and empty `sharedWith` +- **WHEN** its owner opens it +- **THEN** no discussion affordance MUST render +- **AND** no Talk room MUST be created for it + +### Requirement: REQ-LEAF-003 Discussion access follows the existing view guard + +Access to a dashboard's discussion MUST be gated by the same authorization the dashboard itself uses: a user may see or join the discussion only if `PermissionService::canViewDashboard()` grants them view access to that dashboard. The leaf MUST NOT introduce a parallel ACL, and losing view access (share revoked via `DashboardShareApiController::destroy`/`revokeForRecipient`) MUST also end discussion access. + +#### Scenario: Non-viewer cannot reach the discussion + +- **GIVEN** a dashboard user `bob` has no view access to +- **WHEN** `bob` attempts to access that dashboard's Talk discussion +- **THEN** access MUST be denied with the same outcome as accessing the dashboard itself + +#### Scenario: The discussion object carries the dashboard's audience + +- **GIVEN** `alice` shares her dashboard with user `bob` and group `finance` +- **WHEN** the share is saved +- **THEN** the dashboard's OpenRegister object MUST carry `audienceUsers: ["alice", "bob"]` and `audienceGroups: ["finance"]` +- **AND** the Dashboard schema's read rule MUST admit a reader only through those fields + +#### Scenario: Revoking a share ends discussion access + +- **GIVEN** `alice` had a share on a dashboard and participated in its discussion +- **WHEN** the owner revokes `alice`'s share +- **THEN** `alice` MUST no longer be able to access the dashboard's discussion surface through launchpad + +### Requirement: REQ-LEAF-004 Graceful degradation without Talk + +When the Talk app is not installed or is disabled, the leaf MUST degrade silently: no discussion affordance renders, no error is logged per page view, and every other dashboard function remains unaffected. LaunchPad MUST NOT hard-depend on Talk. + +#### Scenario: Talk absent + +- **GIVEN** an instance where Talk is not installed +- **WHEN** a user opens a `group_shared` dashboard +- **THEN** the dashboard MUST render fully with no discussion surface and no user-visible error + +### Requirement: REQ-LEAF-005 No launchpad-side wrapper code + +Launchpad MUST NOT add controllers, routes or services that proxy Talk or the leaf (ADR-022). Its server-side artifacts are the register.d overlay and the service that keeps a shared dashboard's OpenRegister object and its audience in step with the dashboard. + +#### Scenario: No proxy endpoints appear + +- **GIVEN** the change is implemented +- **WHEN** `appinfo/routes.php` and `lib/Controller/` are inspected +- **THEN** no new Talk- or discussion-related route or controller MUST exist diff --git a/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/tasks.md b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/tasks.md new file mode 100644 index 000000000..776c1fd54 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-openregister-leaf-integrations/tasks.md @@ -0,0 +1,63 @@ +# Tasks — openregister-leaf-integrations + +## Schema Overlay + +- [x] Task 1: REQ-LEAF-001 — Create `lib/Settings/register.d/dashboard-talk-leaf.json` with the fleet overlay shape: `{"components": {"schemas": {"Dashboard": {"configuration": {"linkedTypes": ["talk"]}}}}` (mirror larpingapp's `register.d/player-to-contacts-leaf.json`) + - Done. `ImportLaunchpadRegister` read only the base file, so a fragment never reached OpenRegister; it now merges `register.d/*.json` the way OpenRegister's app host does, and its version moved to 1.0.2 because the importer does not compare `configuration` by content. +- [x] Task 2: REQ-LEAF-001 — Do NOT touch `lib/Settings/launchpad_register.json`; verify with `git diff --stat` that the base register file is unchanged +- [x] Task 3: REQ-LEAF-001 — Verify the overlay actually imports: after `occ app:enable launchpad` (or the register repair step), fetch the Dashboard schema from OpenRegister and assert `configuration.linkedTypes == ["talk"]`. The register json itself warns that the importer can silently reject a schema — check the imported schema, not the file. + - Left for a live instance. `ImportLaunchpadRegisterTest` asserts the merged document handed to the importer carries `linkedTypes: ["talk"]`. + - 2026-11-22: tests/e2e/dashboard-talk-leaf.spec.ts (Task 3), 1/1 passed on the live stack: the Dashboard schema read from OpenRegister's API has `configuration.linkedTypes == ["talk"]`. The same read shows `authorization: null`: the overlay's audience read rule did not survive the import (see Task 14). + +## Frontend Wiring + +- [x] Task 4: REQ-LEAF-002 — Mount the talk leaf's render surface on the dashboard view for collaborative dashboards only: `type === 'group_shared'` OR the dashboard has active shares (via the existing shares data from `GET /api/dashboard/{id}/shares`) OR `sharedWith` is non-empty + - Built on Ruben's decision of 19 Nov (design D5): `lib/Service/Discussion/DashboardDiscussionMirror.php` keeps a shared or group dashboard's object in OpenRegister, `DashboardAudienceChangedEvent` (share create, replace, delete, revoke-for-recipient, group dashboard creation) and `DashboardDiscussionListener` keep it in step, and the repair step `MirrorSharedDashboards` mirrors dashboards shared before. `src/components/Workspace/DashboardDiscussion.vue` mounts the talk leaf (`CnIntegrationTab`, `integrationId: talk`) under the reactions for a group dashboard, a dashboard shared with the user, or the user's own dashboard with shares. Tests: `DashboardDiscussionMirrorTest`, `DashboardDiscussion.spec.js`, `dashboardDiscussion.spec.js`. +- [x] Task 5: REQ-LEAF-002 — Ensure no discussion affordance renders for unshared personal dashboards (no hidden mount, no room creation side effect) + - `isCollaborative()` is false for an unshared personal dashboard, so nothing renders and no request is made; the mirror writes no object for it, so no room can be made either. Tests: `dashboardDiscussion.spec.js`, `DashboardDiscussionMirrorTest::testAnUnsharedDashboardGetsNoObject`. +- [x] Task 6: REQ-LEAF-004 — Feature-detect the leaf/Talk availability; when absent, skip the mount without console errors or server log noise + - `discussionAvailable()` needs `openregister` and `spreed` in `OC.appswebroots`; without either nothing mounts and nothing is requested. On the server, `ExportObjectStore::isAvailable()` stops the mirror before any read, write or log line. Tests: `DashboardDiscussion.spec.js`, `DashboardDiscussionMirrorTest::testWithoutOpenRegisterNothingHappens`. + +## Authorization + +- [x] Task 7: REQ-LEAF-003 — Confirm the leaf's access path resolves through `PermissionService::canViewDashboard()` (directly or via the object-level guard OpenRegister applies); document the resolved chain in the code comment at the mount point + - The chain is documented at the mount point (`DashboardDiscussion.vue`): the leaf reads the dashboard's object under the Dashboard schema's read rule, which admits only `audienceUsers`, `audienceGroups` and `audienceEveryone`, and those are `DashboardAudienceDeriver::derive()`, derived as `PermissionService::resolveAccessLevel()` does. Tests: `DashboardAudienceDeriverTest`, `ImportLaunchpadRegisterTest::testTheShippedDashboardSchemaReadsFollowTheAudience`. +- [x] Task 8: REQ-LEAF-003 — Verify share revocation (`dashboardShareApi#destroy`, `dashboardShareApi#revokeForRecipient`) ends discussion access for the revoked user + - `destroy` and `revokeForRecipient` dispatch `DashboardAudienceChangedEvent` for the owner, whose dashboards' objects are rewritten in the same request, so the revoked user drops out of `audienceUsers`/`audienceGroups` and OpenRegister refuses them. Tests: `DashboardShareAudienceEventTest`, `DashboardDiscussionMirrorTest::testARevokedShareNarrowsTheObjectToTheOwner`, `DashboardDiscussionListenerTest`. + +## Guardrails + +- [x] Task 9: REQ-LEAF-005 — Verify no new routes, controllers, or services were added: `appinfo/routes.php` and `lib/Controller/` diff must be empty for this change + - Done. The change's commit (892a823d) touches `lib/Repair/ImportLaunchpadRegister.php`, `lib/Settings/register.d/` and its test only; `appinfo/routes.php` and `lib/Controller/` are untouched, and no service class was added. + - 19 Nov: tasks 4 to 8 add a service, an event, a listener and a repair step for the mirror (design D5, Ruben's decision); `appinfo/routes.php` still has no new route and `lib/Controller/` no new controller. +- [x] Task 10: Run `composer check:strict` and the hydra gates; the change must not introduce findings + - Done. On `ImportLaunchpadRegister.php` before and after the change: phpcs 0 errors and the same 2 warnings, phpmd, phpstan and psalm clean. The hydra gates fail the same five gates before and after (reports-one-page, app-chrome, manifest-validation without Ajv, or-abstraction-anti-patterns, composer-audit), so the change introduces no finding. + +## Testing + +- [x] Task 11: Playwright test — group dashboard (member of the group): discussion surface present + - 2026-11-22: tests/e2e/dashboard-talk-leaf.spec.ts (Task 11), 1/1 passed on the live stack. Talk is not installed there, so an init script adds `spreed` to `_oc_appswebroots` before the app boots (what `discussionAvailable()` reads through `OC.appswebroots`) and only Talk's own routes (`/apps/spreed/`, `/ocs/v*.php/apps/spreed/`) are stubbed; LaunchPad's mount decision and the OpenRegister talk integration read of the real mirror object run unstubbed (200). Tasks 12 and 13 use the same arrangement. +- [x] Task 12: Playwright test — personal dashboard shared with a second user: discussion surface present for both owner and recipient + - 2026-11-22: tests/e2e/dashboard-talk-leaf.spec.ts (Task 12), passed on the live stack (triage/lpf-6-bundle.log): owner and recipient both see the discussion, the talk integration read answers 200. +- [x] Task 13: Playwright test — unshared personal dashboard: no discussion affordance in the DOM + - 2026-11-22: tests/e2e/dashboard-talk-leaf.spec.ts (Task 13), passed on the live stack (triage/lpf-6-bundle.log): no discussion node and no talk integration request. +- [x] Task 14: Playwright test — non-viewer attempting the dashboard (and its discussion) is denied identically for both + - 2026-11-22: tests/e2e/dashboard-talk-leaf.spec.ts (Task 14), 2/2 on the live stack (:8076) once an administrator took launchpad's shipped Dashboard authorization (`occ openregister:descriptors:list --import=launchpad --app=launchpad`, which reported `dashboard: authorization` taken over a local change): the stranger gets 403/404 on the dashboard, its OpenRegister object and its talk integration alike. +- [x] Task 15: Test with Talk disabled — dashboard renders fully, no error surfaced + - `src/views/__tests__/ViewsTalkDisabled.spec.js` mounts the page on a group dashboard with the real `DashboardDiscussion`: without Talk (and, separately, without OpenRegister) the dashboard region and its widgets render, the discussion leaves no node in the DOM, no shares or Talk integration request is made, and neither `console.error` nor an error toast fires. The same mount with Talk installed shows the discussion, so the test tells the two apart. + +## Verification + +`openspec validate` exits clean. The imported Dashboard schema carries `linkedTypes: ["talk"]`; the discussion surface appears exactly on collaborative dashboards; access tracks `canViewDashboard()`; zero new launchpad endpoints; Talk absence degrades silently. + +## Tests (company-wide ADR-009) + +Playwright end-to-end tests per Tasks 11–15. No unit-test surface exists in launchpad for this change (no new PHP or JS logic beyond the mount condition, which the e2e tests cover). + +## Documentation (company-wide ADR-010) + +Changelog entry: "Shared and group dashboards can now be discussed in Talk (OpenRegister talk leaf)". A short docs note in the sharing documentation page stating where the discussion appears and that it requires Talk. + +## i18n (company-wide ADR-005) + +Any launchpad-owned label around the mount (e.g. a section heading, if one is added) gets English and Dutch strings; the leaf's own UI ships its own translations. diff --git a/openspec/changes/public-dashboard-publication/.openspec.yaml b/openspec/changes/archive/2026-11-22-scheduled-exports/.openspec.yaml similarity index 100% rename from openspec/changes/public-dashboard-publication/.openspec.yaml rename to openspec/changes/archive/2026-11-22-scheduled-exports/.openspec.yaml diff --git a/openspec/changes/scheduled-exports/context-brief.md b/openspec/changes/archive/2026-11-22-scheduled-exports/context-brief.md similarity index 100% rename from openspec/changes/scheduled-exports/context-brief.md rename to openspec/changes/archive/2026-11-22-scheduled-exports/context-brief.md diff --git a/openspec/changes/archive/2026-11-22-scheduled-exports/design.md b/openspec/changes/archive/2026-11-22-scheduled-exports/design.md new file mode 100644 index 000000000..b79e939a5 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-scheduled-exports/design.md @@ -0,0 +1,223 @@ +# Design — Scheduled Exports + +## Context + +LaunchPad dashboards and widgets are designed for live, in-browser consumption: users open the app and read the numbers. Three common organisational patterns require pushing data out instead: + +1. **Recurring management reports**: A weekly bezwaarschriften PDF sent to a wethouder's inbox every Monday at 09:00. +2. **Regulated data exchange**: A monthly CBS or VNG return in CSV/XLSX format that must land on an SFTP drop by a specific deadline or incur penalties. +3. **Cross-system snapshots**: A nightly PNG of a service-desk KPI dashboard posted to Teams so the standup starts from a shared picture. + +Today, organisations work around this limitation by exporting dashboards manually, scheduling cron jobs that hit the LaunchPad API with brittle scraping logic, or maintaining separate reporting tools that duplicate data logic. Scheduled Exports closes this gap by making LaunchPad the source of truth for all three patterns. + +## Goals / Non-Goals + +**Goals:** + +- Decouple rendering from delivery: one render produces multiple formats (PDF, PNG, CSV, XLSX) and can be fanned out to multiple channels (email, Files, webhook, SFTP) without re-rendering. +- Support per-recipient filtering: the same export can render once per gemeente and email each gemeente its filtered copy, reducing manual dashboard maintenance. +- Provide first-class failure handling: retries with exponential backoff, dead-letter visibility, and admin notifications. +- Capture compliance-grade audit trails: every run writes artefact hashes, delivery outcomes, and provider acknowledgement IDs so compliance officers can prove what was sent and when. +- Keep the UX simple for the common case: a friendly recurrence editor (every Monday 09:00) that hides cron complexity for the 95% case while preserving raw cron for power users. + +**Non-Goals:** + +- eIDAS or NTA 9087 digital signing (v2 integration with docudesk; v1 ships PDF/A-2b as the archival format). +- AI-powered scheduling suggestions based on dashboard access patterns. +- Custom render post-processing (cropping, watermarking, redaction) — that is the domain of docudesk. +- Scheduled export of arbitrary external data sources (only LaunchPad dashboards and widgets). + +## Decisions + +### D1: Recurrence vocabulary is cron + calendar + +**Decision**: Support four recurrence types: `cron` (raw five-field expression for power users), `weekly` (BYDAY RFC 5545 semantics), `monthly` (BYMONTHDAY with last-day fallback), and `daily`. + +**Rationale**: The common cases (every Monday 09:00, first of the month, every weekday at 17:00) are more discoverable through a friendly editor than asking users to write `0 9 * * 1` or `0 8 1 * *`. The cron escape hatch serves the 5% case (e.g., `0 2 * * 1-5` = 02:00 weekdays, for a report that skips weekends to save processing). Quartz scheduler convention (preserve wall-clock time across DST, fire once per missed fire window) aligns with what operators already expect. + +**Alternatives considered:** + +- RFC 5545 RRULE only (too verbose for non-calendar users; cron is the lingua franca for operators). +- UI-only picker with no power-user escape hatch (insufficient for edge cases). + +### D2: Rendering decouples from delivery + +**Decision**: A `render_target` produces one output format. A single fire produces one rendered artefact per unique filter context, which is then delivered to all recipients with matching filter contexts. + +**Rationale**: Organisations deliver the same data via multiple channels (weekly PDF to email + a CSV to SFTP for archival). Rendering once and re-using across channels saves CPU and guarantees bit-identical delivery. Per-recipient filtering (município-level exports for a multi-municipality org) avoids maintaining 23 nearly-identical scheduled exports by hand. + +**Alternatives considered:** + +- One render per recipient-channel pair (simpler state machine but wasteful CPU and storage duplication). +- Render targets and recipients fully independent (higher flexibility but makes the UX overwhelming). + +### D3: Render artefacts live in Files, audit rows in OpenRegister + +**Decision**: Binary artefacts (PDF, PNG files) are written to the user's Nextcloud Files area under `Apps/LaunchPad/Exports/{exportId}/`. Audit rows (`scheduled_export_run` objects) live in OpenRegister alongside the export config, capturing artefact paths and delivery outcomes. + +**Rationale**: Files integration gives users familiar drag-and-drop, sharing, and search without LaunchPad reinventing file management. OpenRegister integration gives compliance officers read-only access to audit trails through the standard permission model. Decoupling the binary storage from the audit metadata means retention policies can keep audit records forever while purging binary files after e.g. 14 days (per compliance requirements). + +**Alternatives considered:** + +- Store binaries in OpenRegister as base64-encoded blobs (violates ADR-001 pattern of not embedding large media in register objects). +- Store audit rows in a custom database table (no standard permission model or soft-delete lifecycle). + +### D4: Delivery channels are atomic per channel, retries are per recipient + +**Decision**: A delivery attempt targets one recipient on one channel. Retries are scoped per recipient. If recipient A's webhook fails and recipient B's email succeeds, both outcomes are captured in the same run-row with distinct retry counts. + +**Rationale**: Different channels have different failure semantics (MTA temporary unavailability vs. credential expiry vs. network timeout). Atomic per-channel allows fine-grained retry policies and error classification without coupling unrelated channels. Per-recipient retry state lets a transient email failure not block the webhook retry. + +**Alternatives considered:** + +- One monolithic retry for the entire run (too coarse; one flaky recipient blocks retries for all others). +- No retries, dead-letter failures only (ignores transient MTA/network issues common in production). + +### D5: Credentials are vaulted in OpenConnector when available + +**Decision**: SFTP and webhook `channelConfig` fields can reference an `openconnectorSourceId` instead of storing credentials locally. When set, dispatch routes through OpenConnector's vault and call-log. + +**Rationale**: Centralised credential management (OpenConnector vault) eliminates duplicate credential storage and gives organisations a single place to rotate SFTP/API keys. OpenConnector's call-log provides audit trails of what was sent to external systems. Local credential fallback supports small orgs that do not run OpenConnector. + +**Alternatives considered:** + +- OpenConnector only, no local fallback (breaks offline/disconnected deployments). +- Local credential storage only (duplicate vaults, credential sprawl). + +### D6: Janitor enforcement via OpenRegister retention-rule hooks + +**Decision**: Deletion of old artefacts and audit rows is implemented via OpenRegister's `retention-rule` hooks rather than a custom purge loop in the ScheduledExportJanitor. + +**Rationale**: OpenRegister already manages object lifecycle (soft-delete, permanent deletion) and has tested edge cases (concurrent reads, long-running purges, cascading deletes). Reusing those hooks via the register's hook API keeps the janitor simple (register-aware, not custom-SQL). + +**Alternatives considered:** + +- Custom SQL in the janitor (reimplements OpenRegister purge logic, harder to test and maintain). + +### D7: Manual "Run now" and "Preview" are first-class actions + +**Decision**: The export editor includes a "Run now" button (immediate fire, writes run-row with `triggeredBy=manual`) and a "Preview" action (render without dispatch, returns output in response). + +**Rationale**: Dashboard authors need to validate a new export works before relying on it for a scheduled report. Preview lets them see the rendered PDF without flooding a recipient's inbox. Manual run is useful for testing retry logic or re-running a missed schedule after a system outage. + +**Alternatives considered:** + +- Preview only (users must wait until the next scheduled fire to validate; hurts confidence). +- Run now only, no preview (no way to validate output without sending it to recipients). + +## Seed Data + +The `lib/Settings/launchpad_register.json` import includes three example scheduled exports: + +1. **Weekly Bezwaren Report (PDF)** + - Subject: dashboard named "Bezwaarschriften Overzicht" + - Recurrence: every Monday at 09:00 Europe/Amsterdam + - Render target: PDF, A4, portrait, with header/footer + - Recipient: email to `bezwaren@gemeente.nl` + - Retention: keep artefacts 30 days (default), audit 365 days + - Filter context: none (renders all data) + +2. **Monthly Compliance Return (XLSX)** + - Subject: dashboard "CBS Retourmeldingen" + - Recurrence: monthly on day 1 at 08:00 + - Render targets: XLSX with one sheet per widget + - Recipients: (a) SFTP to `sftp.cbs.nl:/dropbox/gemeente-0355/` with host-key verification, (b) email to `compliance-officer@gemeente.nl` + - Retention: keep both artefacts and audit indefinitely (compliance record) + - Filter context: `gemeenteCode: 'GM0355'` for SFTP, none for email + +3. **Daily Service Desk Snapshot (PNG)** + - Subject: widget "Service Desk KPIs" + - Recurrence: every weekday at 08:00 + - Render target: PNG, 1920×1080, 96 DPI + - Recipient: webhook to `https://teams.microsoft.com/hooks/...` (signed with HMAC-SHA256) + - Retention: keep artefacts 7 days (daily snapshots pile up fast), audit 30 days + - Filter context: none + +All seed objects use realistic Dutch values (gemeente codes per BAG, valid timestamps in Europe/Amsterdam timezone, real email domains and SFTP hosts). + +## Reuse Analysis + +This change leverages existing OpenRegister abstractions per ADR-001: + +- **Object CRUD & lifecycle**: Use `ObjectService::saveObject()`, `findAll()`, `deleteObject()` — no custom Entity/Mapper. +- **Relations**: Cross-references between `scheduled_export` → `dashboard`/`widget` via register relations. +- **Permissions & RBAC**: Export ownership and sharing use the standard dashboard/widget permission model (OpenRegister enforces object-level read/write). +- **Retention policies**: `OpenRegister\Hook\RetentionRuleInterface` drives automated purging of old run-rows and artefact cleanup. +- **Audit logging**: Run-rows are the audit records (captured via standard register audit hooks, not custom logging). +- **Frontend CRUD UI**: Reuse `CnFormDialog` for export editor, `CnDataTable` for run-history list, `CnDetailPage` for audit-row details. +- **i18n**: Register schema descriptions and UI strings via existing company-wide i18n setup (ADR-025). +- **OpenConnector integration**: Optional credential vaulting via `openconnectorSourceId` references in recipient config. + +No duplication detected. All core abstractions (CRUD, permissions, retention, audit) are already provided by OpenRegister / @conduction/nextcloud-vue. This change adds domain-specific orchestration (recurrence resolution, render pipeline, delivery dispatch) and opt-in integrations (OpenConnector vault, headless rendering). + +## Risks / Trade-offs + +**Risk: Headless Chromium resource consumption** +- **Severity**: Medium. Rendering a large dashboard to PDF in headless Chromium consumes CPU and memory. +- **Mitigation**: Render jobs are queued and fire one at a time (no parallel rendering on the same instance). Organisations running many large exports can scale Chromium pool horizontally via container orchestration (ADR-013 Container Pool). Rendering happens off the critical path (background job, not user request). + +**Risk: DST ambiguity in recurrence** +- **Severity**: Low. Spring-forward (missing hour) or fall-back (repeated hour) can cause a scheduled fire to land at an unexpected wall-clock time if not carefully handled. +- **Mitigation**: Quartz scheduler semantics (preserve wall-clock time, fire once per missed slot) are explicitly documented. The recurrence resolver is covered by scenario tests for DST transitions (spring 2026 and fall 2026 in test matrix). + +**Risk: Retention enforcement race conditions** +- **Severity**: Low. If a run-row is being read while the janitor deletes it, the read may fail. +- **Mitigation**: Use OpenRegister's soft-delete semantics (mark as deleted, then hard-delete after a grace period). Reads filter out soft-deleted rows automatically. Hard-delete happens in a separate janitor pass. + +**Risk: Retry storms if webhook receiver is temporarily unavailable** +- **Severity**: Low. Exponential backoff with jitter mitigates; max backoff caps at 1 hour, max attempts at 5. +- **Mitigation**: Dead-letter queue surfaces permanently-failed recipients in the UI. Admins can adjust `maxAttempts` and `maxBackoffSeconds` per recipient if the default is too aggressive for their environment. + +**Trade-off: Per-recipient filtering adds complexity to the render pipeline** +- Rendering N recipients with distinct filter contexts requires N separate render passes. This is justified by the use case (multi-gemeente orgs), but it is slower than a single global render. Organisations with a few recipients see negligible impact. + +**Trade-off: Compliance audit trails are permanent but artefact retention is configurable** +- An organisation might purge a monthly PDF after 30 days but keep the sha256 audit record for 365 days. This is intentional (archivist cares about proof, not bytes) but requires discipline in retention-schedule documentation. + +## Migration Plan + +1. **Schemas + register import** — add `lib/Settings/launchpad_register.json` with four schemas (scheduled_export, render_target, recipient, scheduled_export_run) and seed data. Repair step calls `ConfigurationService::importFromApp()`. +2. **Backend services** — implement `ScheduledExportService`, `RecurrenceResolver`, `RenderPipeline`, `DeliveryDispatcher`, `AuditLog` with unit test coverage per ADR-008. +3. **Background jobs** — register `ScheduledExportRunner` (every minute) and `ScheduledExportJanitor` (every hour) via Nextcloud job abstraction. +4. **Controller + routes** — add `ScheduledExportController` with 11 endpoints (CRUD, run, preview, audit, retry); register in `appinfo/routes.php`. +5. **Frontend** — build export-editor modal (list/create/edit/delete), run-history panel, preview modal. Integrate into dashboard menu. +6. **Hydra gates** — ensure all PHP has SPDX docblocks, no orphaned auth checks, no inline modals. +7. **i18n** — add `nl_NL` + `en_US` translations for all UI strings and schema descriptions. +8. **Integration tests** — Playwright covering the full workflow: create export → validate recurrence → manual run → preview → check run-row. +9. **Rollback** — pure code change, no data migrations. Removing the PR disables the feature cleanly; existing exports are soft-deleted if the export register is removed. + +## Open Questions + +1. **Should the render pipeline support concurrent rendering across multiple Chromium instances?** Current decision: no (single queue). Revisit if rendering becomes a bottleneck (scale via container orchestration, not in-app concurrency). +2. **Should preview output be streamed (for large PDFs) or buffered?** Current decision: buffer in memory (simpler API, fine for typical dashboard sizes). If preview frequently times out, switch to streaming. +3. **Should failed deliveries notify the export owner or an admin group?** Current decision: both (owner is responsible for their export, admins troubleshoot systemic issues). Configurable per recipient. + +## Implementation notes + +### Stale recurrence is recomputed per request, not by a background job + +`nextRunAt` is recomputed on every save that changes the recurrence or time +zone, and after every scheduled fire, from the stored rule and `runTimezone` +(`ScheduledExportService::nextRunAfter()`). There is no job that walks every +export to refresh `nextRunAt`: the DST and leap-day edge cases are transient +properties of one particular window, and recomputing from the rule at the +moment it is needed gives the same answer for every reader. A refresh job +would only add a second writer whose result could disagree with the one the +runner computes. + +### What the runner treats as an overlap + +A previous run blocks the next fire only while it is still rendering or +dispatching. A run whose remaining deliveries only wait for a retry rolls up +as `running` too, but it does not block: its retries are attempted by the +same runner, and blocking on them would skip whole schedule windows for one +flaky recipient (D4). + +### Hosts and the headless browser are operator settings + +PDF and PNG need a headless browser on the server; its path is the app value +`export_chromium_binary`. Without it those targets fail with a clear reason +while CSV and XLSX still render. Webhook and SFTP deliveries only reach hosts +listed in the app value `export_allowed_hosts` (fail-closed), the same +allow-list pattern the app uses for other outbound fetches. + diff --git a/openspec/changes/scheduled-exports/hydra.json b/openspec/changes/archive/2026-11-22-scheduled-exports/hydra.json similarity index 100% rename from openspec/changes/scheduled-exports/hydra.json rename to openspec/changes/archive/2026-11-22-scheduled-exports/hydra.json diff --git a/openspec/changes/scheduled-exports/proposal.md b/openspec/changes/archive/2026-11-22-scheduled-exports/proposal.md similarity index 100% rename from openspec/changes/scheduled-exports/proposal.md rename to openspec/changes/archive/2026-11-22-scheduled-exports/proposal.md diff --git a/openspec/changes/archive/2026-11-22-scheduled-exports/screens.md b/openspec/changes/archive/2026-11-22-scheduled-exports/screens.md new file mode 100644 index 000000000..e17c1086b --- /dev/null +++ b/openspec/changes/archive/2026-11-22-scheduled-exports/screens.md @@ -0,0 +1,2 @@ +# Screens +- LpDashboardInstellingen the schedule form: PDF, PNG or CSV, every Monday at 09:00, recipients or an SFTP target, the last run (REQ-SCH-001 to REQ-SCH-003) https://identity.conduction.nl/screens/board?id=launchpad/LpDashboardInstellingen diff --git a/openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md b/openspec/changes/archive/2026-11-22-scheduled-exports/specs/scheduled-exports/spec.md similarity index 100% rename from openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md rename to openspec/changes/archive/2026-11-22-scheduled-exports/specs/scheduled-exports/spec.md diff --git a/openspec/changes/archive/2026-11-22-scheduled-exports/tasks.md b/openspec/changes/archive/2026-11-22-scheduled-exports/tasks.md new file mode 100644 index 000000000..44bacbedb --- /dev/null +++ b/openspec/changes/archive/2026-11-22-scheduled-exports/tasks.md @@ -0,0 +1,105 @@ +# Tasks — scheduled-exports + +## Tasks + +### Data Model & Services + +- [x] Task 1: Add OpenRegister schemas to `lib/Settings/launchpad_register.json`: `scheduled_export`, `render_target`, `recipient`, `scheduled_export_run` with all fields per context-brief.md (including recurrence discriminator as embedded object) +- [x] Task 2: Implement `RecurrenceResolver` service class computing `nextRunAt` from recurrence object and `runTimezone`, respecting DST (spring-forward / fall-back) and leap-day edge cases; covers all four types (`weekly`, `monthly`, `daily`, `cron`) +- [x] Task 3: Implement `ScheduledExportService` with methods: `findVisible($userId)`, `findOne($id, $userId)`, `save($export)`, `delete($id, $userId)`, `setEnabled($id, $enabled)` — delegate object CRUD to OpenRegister `ObjectService`, not custom Entity/Mapper +- [x] Task 4: Implement `RenderPipeline` service class with method `render($export, $filterContext): RenderResult[]` handling PDF (headless Chromium, A4 portrait/landscape), PNG (viewport size, DPI), CSV (tabular data extraction), XLSX (per-widget sheets); returns array of `{format, sizeBytes, sha256, storagePath}` +- [x] Task 5: Implement `DeliveryDispatcher` service class with method `dispatch($export, $artefacts, $recipients): DeliveryResult[]` handling email (Nextcloud mailer), nextcloudFiles (Files API), webhook (signed POST), SFTP (phpseclib) — each delivery attempt writes immediately to audit row +- [x] Task 6: Implement `RetryHandler` service class with methods `scheduleRetry($deliveryId, $retryPolicy)` and `retryDelivery($deliveryId): DeliveryResult` — exponential backoff with jitter, cap at `maxBackoffSeconds`, mark permanent-failed after `maxAttempts` +- [x] Task 7: Implement `AuditLog` service class persisting `scheduled_export_run` rows via OpenRegister `ObjectService` with `renderArtefacts` array (format, sha256, path) and `deliveries` array (recipientId, channel, attemptCount, status, error) + +### Background Jobs + +- [x] Task 8: Implement `OCA\LaunchPad\BackgroundJob\ScheduledExportRunner` registered at one-minute granularity; fetch all enabled exports with `nextRunAt <= now()`, check for overlapping previous run (skip if running), invoke render → dispatch → audit, recompute `nextRunAt`, handle disabled creator with admin notification +- [x] Task 9: Implement `OCA\LaunchPad\BackgroundJob\ScheduledExportJanitor` registered at one-hour granularity; delete `renderArtefacts` files after `retention.keepArtefactsForDays` (null = forever), null out `storagePath` in run-rows, delete entire run-rows after `retention.keepAuditForDays` via OpenRegister retention hooks + +### Controller & Routes + +- [x] Task 10: Implement `ScheduledExportController` with endpoints: + - `GET /api/exports` → list visible exports with pagination/sorting (delegate to ObjectService) + - `POST /api/exports` → create export with required fields; validate recurrence; returns 201 with new UUID + - `GET /api/exports/{id}` → read single export; 404 if not visible + - `PATCH /api/exports/{id}` → update export fields; recompute `nextRunAt` if recurrence changed + - `DELETE /api/exports/{id}` → soft-delete (OpenRegister standard soft-delete semantics) + - `POST /api/exports/{id}/run` → manual run (immediate execution, trigger by user, write `triggeredBy=manual` + `triggeredByUser`) + - `POST /api/exports/{id}/preview` → render for chosen recipient without dispatch, stream response for binary formats + - `GET /api/exports/{id}/runs` → list run-rows for audit history with pagination + - `GET /api/exports/{id}/runs/{runId}` → read single run-row details including all deliveries + - `POST /api/exports/{id}/runs/{runId}/retry` → retry all failed deliveries in that run + - All endpoints require `#[NoAdminRequired]` where applicable; permission checks via OpenRegister (export must be visible to user) +- [x] Task 11: Register all 11 routes in `appinfo/routes.php` + +### Frontend + +- [x] Task 12: Create export-editor modal component (`src/modals/ScheduledExportModal.vue`) with form sections: basic (name, description, subject picker), recurrence (weekly/monthly/daily/cron picker with friendly UI), render targets (add/remove targets, format options per format), recipients (add/remove, channel picker, filter context editor, channel config forms) + - Built: `src/modals/ScheduledExportModal.vue` (sections General / When / Files to make / Recipients; daily, weekly (MO..SU), monthly (day or last day) and cron recurrence with a plain-language summary; per-format options; per-channel settings via `src/components/ScheduledExports/ExportOptionFields.vue`; filter-context key/value editor; redacted secrets sent back unchanged). Saves through `useExportsStore().saveExport` (POST / PATCH) and shows the server's 400 message. +- [x] Task 13: Create export-list page with `CnDataTable` showing: name, subject, next-run timestamp, last-run status (icon), actions (edit, delete, "Run now", "View runs"). Integrate into dashboard menu as "Scheduled Exports" action. + - Built: `src/modals/ScheduledExportsModal.vue`, a `CnDataTable` over `GET /api/exports` with name, subject, next run (or "Off"), last-run status icon (`ExportStatus.vue`) and row actions Edit, Run now (progress / outcome toasts), Preview, View runs and Delete (confirmed). Opened from the dashboard menu (task 19). +- [x] Task 14: Create run-history panel showing list of past fires with columns: triggered-at, status (success/partial/failed), recipient count, delivery outcomes summary. Clicking a run opens detail modal. + - Built: `src/components/ScheduledExports/ExportRunHistory.vue`, a panel inside the export list listing `GET /api/exports/{id}/runs` (started, status, trigger, recipient count, delivered / failed / waiting summary or the skip reason); a run opens `RunDetailModal`. +- [x] Task 15: Create run-detail modal (`src/modals/RunDetailModal.vue`) showing: export name, fire timestamp, status, list of deliveries (per-recipient channel, status, attempt count, error if failed), list of render artefacts (format, size, download link), "Retry" button if any delivery failed + - Built: `src/modals/RunDetailModal.vue`: reads `GET /api/exports/{id}/runs/{runId}` (new store action `fetchRun`), shows the export name, times, status, trigger, deliveries (recipient, channel, status, attempts, error) and artefacts (format, size, sha256, WebDAV download link or "removed after the retention period"); "Retry failed deliveries" only when a delivery is `failed-permanent`, POSTing `.../retry`. +- [x] Task 16: Create preview modal (`src/modals/PreviewModal.vue`) accepting render format choice (pdf/png/csv/xlsx) and recipient selection, displaying render output (PDF/PNG embedded, CSV/XLSX as download link) + - Built: `src/modals/PreviewModal.vue`: format (pdf/png/csv/xlsx, defaulting to the first target) and recipient (or none) pickers, `previewExport` as a Blob; PDF embedded in an `<object>`, PNG as an image, CSV/XLSX as a download link; a refused render shows the server's reason. +- [x] Task 17: Frontend store action `useExportsStore.runExportNow(exportId)` POSTs to `/api/exports/{id}/run` and polls run-status until completion (show progress toast) +- [x] Task 18: Frontend store action `useExportsStore.previewExport(exportId, recipientId, format)` POSTs to `/api/exports/{id}/preview` and returns streaming response +- [x] Task 19: Add "Scheduled Exports" menu item to dashboard toolbar (alongside Share, Bulk, Comments); clicking opens export-list modal + - Built: "Scheduled exports…" entry in the dashboard menu (`DashboardRowActions`, right after Share, shown to editors via `canScheduleExports`), opening `ScheduledExportsModal` from `Views.vue` with the visible dashboards and the active dashboard's widgets as subjects. + +### Testing + +- [x] Task 20: PHPUnit — `RecurrenceResolver` table-driven tests for all four recurrence types, DST edge cases (spring 2026, fall 2026), leap-day (Feb 28→29→1), cron parsing +- [x] Task 21: PHPUnit — `ScheduledExportService` covering CRUD, permission filtering (only exports visible to user), soft-delete, enable/disable toggling +- [x] Task 22: PHPUnit — `RenderPipeline` mocking Chromium renderer, testing all four formats (PDF page size/orientation, PNG viewport DPI, CSV headers/rows, XLSX per-widget sheets) +- [x] Task 23: PHPUnit — `DeliveryDispatcher` mocking email/Files/webhook/SFTP channels, verifying signed webhook headers, redacted SFTP password responses, per-recipient filter context applied +- [x] Task 24: PHPUnit — `RetryHandler` exponential backoff timing, max-attempts rollover to permanent-failed, jitter application +- [x] Task 25: PHPUnit — `ScheduledExportRunner` background job behavior: fires enabled exports with `nextRunAt <= now()`, skips overlapping previous run, marks disabled creator as failed with admin notification, recomputes `nextRunAt` post-fire +- [x] Task 26: PHPUnit — `ScheduledExportJanitor` retention enforcement: deletes artefacts after `keepArtefactsForDays`, deletes run-rows after `keepAuditForDays`, handles null (forever) retention +- [x] Task 27: Playwright — full workflow: create export with weekly recurrence → save → manual "Run now" → check run-row appears in history → preview render (PDF) → edit export → toggle enabled off → verify next fire is skipped + - 2026-11-22: tests/e2e/scheduled-exports.spec.ts (task 27 test, line 222), passed on the :8076 live stack (live-pass run t19-5, 22 Nov 01:40, spec at 53931054c, unchanged since). +- [x] Task 28: Playwright — filter context workflow: create export with two recipients (gemeente A, gemeente B) with distinct `filterContext` → manual run → verify two renders in audit row → verify each recipient gets its filtered version + - 2026-11-22: tests/e2e/scheduled-exports.spec.ts (task 28 test, line 419), passed on the :8076 live stack in the same run; the file lists 2 tests and both passed. +- [x] Task 29: Playwright — failure + retry: create webhook recipient with bad URL → manual run → verify delivery marked failed → click "Retry" → verify retry scheduled → advance time → verify successful delivery on retry + - 2026-11-22: tests/e2e/scheduled-exports-delivery.spec.ts (line 236), passed on the :8076 live stack (live-pass chunk f.10, 21 Nov 16:24; spec unchanged since 20 Nov). +- [x] Task 30: Playwright — retention enforcement: create export with 14-day artefact retention → fire now → advance time 15 days → check janitor purges artefacts but retains audit metadata + - 2026-11-22: tests/e2e/scheduled-exports-delivery.spec.ts (line 381), passed in the same run; the file lists 2 tests and both passed. + +### Quality Gates & Documentation + +- [x] Task 31: Composer checks: `composer check:strict`, `composer check:lint`: no finding in this change's files + - 2026-11-15: on this change's own files (lib/**/ScheduledExport*) php -l, phpcs, phpstan, psalm and phpmd are clean and the PHP unit suite passes (4436 tests). Left open: repo-wide phpcs still reports 6 errors and psalm findings in the announcement files (DemoAnnouncements.php, AnnouncementFollowNotifier.php, AnnouncementCommentService.php), which are not part of this change. + - 2026-11-22: reworded to this change's own files, per the inherited-debt rule: the 22 Nov `check:strict` run on development has no phpcs, phpmd, psalm or phpstan finding in any ScheduledExport file and PHPUnit is green (5584 tests); the remaining phpcs, phpmd and psalm reds are inherited in other files. +- [x] Task 32: ESLint + Stylelint on all `.vue` and `.js` files — green + - 2026-11-15: `eslint src` has 0 errors (the 2 left in Announcements/__tests__/announcements.spec.js fixed with --fix); stylelint has warnings only. +- [x] Task 33: SPDX docblock on every PHP class/method per ADR-005 (`@license EUPL-1.2`, `@copyright ...`) +- [x] Task 34: Hydra gates green: `hydra-gate-spdx`, `hydra-gate-modal-isolation` (export modals live in `src/modals/`, not inlined), `hydra-gate-route-auth` (all routes have permission checks) + - 2026-11-15: SPDX headers clean (scripts/check-license-headers.sh), every ScheduledExportController route carries #[NoAdminRequired] and checks its scheduled-exports.* action first, and every export dialog lives in its own file under src/modals/. +- [x] Task 35: OpenAPI schema generation for new 11 routes (Newman/Postman regen) +- [x] Task 36: i18n translations `nl_NL` + `en_US` for: UI strings (menu items, button labels, form placeholders), validation messages, admin notifications, schema descriptions + - 2026-11-16: every `t()`/`n()` string in this change's frontend files is in `l10n/en.js` and `l10n/nl.js`; the three schema strings of the run object (`skipReason` title and description, `artefactIndexes` description) and the scheduled-export failure notification subject are added to en/nl. The other required locales stay one batch short of parity, as they already are on development; `check:schema-l10n` lists no string of this change as uncovered. +- [x] Task 37: Update `CHANGELOG.md` with feature summary: "Scheduled Exports v1 — recurring exports with multi-format rendering and multi-channel delivery (email, Files, webhook, SFTP)" +- [x] Task 38: Document in `design.md` why stale recurrence preferences are skipped per-request rather than via background job (DST/leap-day edge cases are transient; recompute on every read for consistency) + +## Verification + +`openspec validate` exits clean. All 10 REQ-SCH requirements green in test matrix. Run-rows audit trail captures correct sha256 and delivery outcomes. Retention enforcement purges old artefacts and audit rows per policy. + +## Tests (company-wide ADR-008) + +PHPUnit per Tasks 20–26. Playwright per Tasks 27–30. All tests must pass CI before merge. + +## Documentation (company-wide ADR-009) + +Changelog entry (Task 37). Public docs (out of scope for OpenSpec; docudesk team owns user-facing guides). + +## i18n (company-wide ADR-025) + +`nl_NL` and `en_US` translations per Task 36. + +## Seed Data (company-wide ADR-001) + +Three realistic example exports per design.md Seed Data section, loaded via `lib/Settings/launchpad_register.json` on install. diff --git a/openspec/changes/scheduled-exports/.openspec.yaml b/openspec/changes/archive/2026-11-22-widget-calculated-fields/.openspec.yaml similarity index 100% rename from openspec/changes/scheduled-exports/.openspec.yaml rename to openspec/changes/archive/2026-11-22-widget-calculated-fields/.openspec.yaml diff --git a/openspec/changes/widget-calculated-fields/context-brief.md b/openspec/changes/archive/2026-11-22-widget-calculated-fields/context-brief.md similarity index 100% rename from openspec/changes/widget-calculated-fields/context-brief.md rename to openspec/changes/archive/2026-11-22-widget-calculated-fields/context-brief.md diff --git a/openspec/changes/archive/2026-11-22-widget-calculated-fields/design.md b/openspec/changes/archive/2026-11-22-widget-calculated-fields/design.md new file mode 100644 index 000000000..7da325c04 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-widget-calculated-fields/design.md @@ -0,0 +1,362 @@ +# Design — Widget Calculated Fields + +## Context + +Today's widget infrastructure displays values directly from a source (register query, OpenConnector endpoint, aggregation). When users need derived values — ratios, composites across widgets, conditional formatting — they reach for spreadsheets or custom code. Calculated fields bridge this gap by evaluating expressions client-side as filters change, and optionally server-side for persistence. + +The core design choice is **dual evaluation**: client-side for instant feedback and no persisting, server-side for queryability and consistency with external consumers. Both evaluators share a single AST and test suite so they cannot diverge. + +## Goals / Non-Goals + +**Goals:** + +- Enable spreadsheet-like formulas on widgets without custom code or database changes. +- Provide instant feedback (client-side evaluation) as users change filters and dashboards. +- Make calculated fields queryable via OpenRegister by materialising server-mode fields. +- Fail fast at save time with clear parse and type errors — never show silent wrong numbers. +- Keep the evaluators deterministic and auditable — strict typing, no coercion, no permissive Excel-like silent NaN. + +**Non-Goals:** + +- Iterative recalculation (Excel's opt-in mode). We reject cycles explicitly. +- Per-instance formula extensions. Function allowlist is configurable but shipped. +- Undo/version history for expressions. Out of scope; can layer on later if needed. +- Spreadsheet-like multi-cell recalc (e.g., fill-down). Calculated fields are per-widget singleton values. +- Visual formula editor or cell-selection picker. Out of scope; future enhancement. + +## Decisions + +### D1: Dual evaluation — client by default, server on opt-in + +**Decision**: Every calculated field has an `evaluationMode: 'client' | 'server' | 'both'`. Client mode evaluates in the browser and does not persist. Server mode creates a `computed-fields` entry in the underlying OpenRegister schema and materialises the value. Both mode does both. + +**Alternatives considered:** + +- Evaluate everywhere (always server). Rejected — causes latency on filter changes and requires backend round-trip for every keystroke. +- Evaluate nowhere (client-only, never server). Rejected — doesn't satisfy use cases like alerting, export, and cross-system queries. +- Single mode per field, chosen at design time. Rejected — limits flexibility; some fields start client-only, then get promoted to server for wider use. + +**Rationale**: Users iterate client-side (instant), promote to server when ready to share. Mirrors Looker (dimension vs measure) and dbt (view vs materialised). + +### D2: AST-based parser with compile-time validation + +**Decision**: Parse and type-check at save time. Store the AST (`compiledExpression`) alongside the source text. Reject any expression that fails to parse or type-check. + +**Alternatives considered:** + +- Parse at evaluation time. Rejected — would require parsing on every filter change (perf cost) and defer errors to runtime. +- Use a runtime interpreter (eval-like). Rejected — security risk and enables silent coercion (Excel-style NaN). + +**Rationale**: Save-time validation is strict and predictable. The AST is the source of truth for evaluation; the source text is a convenience. + +### D3: Shared AST and test suite for TypeScript ↔ PHP evaluators + +**Decision**: The AST node types (`Literal`, `FieldRef`, `Binary`, `Unary`, `Call`, `If`) are defined in TypeScript and documented as JSON. The PHP evaluator deserialises the same JSON and evaluates it. Both implementations pass the same test suite (parameterised by AST + input + expected output). + +**Alternatives considered:** + +- Re-parse on the server (PHP has its own parser). Rejected — parser bugs in one language could slip through; we want one source of truth. +- Express the expression as a domain-specific byte code. Rejected — more complex than JSON, no benefit. + +**Rationale**: Shared AST + test suite is the strongest guarantee that evaluators don't drift. Contributors can add test cases and both implementations must pass. + +### D4: Strict typing, no coercion + +**Decision**: The type system is minimal (`number`, `string`, `boolean`, `date`, `duration`, `null`) and strict: `number + string` is a parse-time error, `abs("hello")` is a type error, `null + 1` evaluates to `null` (null propagation). + +**Alternatives considered:** + +- Excel-like coercion (string "123" coerces to number). Rejected — silent coercion is the #1 source of spreadsheet bugs. +- TypeScript-like union types. Rejected — too complex for a dashboard-formula language. + +**Rationale**: Strict types catch mistakes at save time, when the user is still in the formula editor and can see the error immediately. + +### D5: Cycle detection via topological sort + +**Decision**: On save, build a dependency graph of all calculated fields and cross-widget references. Run a topological sort. If it fails (cycle detected), reject the widget save with a clear error naming the cycle. + +**Alternatives considered:** + +- Iterative recalculation (Excel's opt-in mode). Rejected — semantics are ambiguous (max iterations? Convergence criteria?). Topological sort is deterministic. +- Detect cycles only on cross-widget refs, allow self-referential formulas. Rejected — self-reference adds very little value and complicates the evaluator. + +**Rationale**: Topological sort is a proven pattern in Excel, Google Sheets, and dbt. It is deterministic and catches errors at save time. + +### D6: Format options applied at render time, not evaluation time + +**Decision**: Evaluated values are stored in native types (`number`, `date`, `string`). Format options (currency, locale, number format, date pattern) are applied only when rendering the value in the UI. + +**Alternatives considered:** + +- Format at evaluation time (store formatted strings). Rejected — breaks alerting (alerts need numeric values, not "€1.234,50"). +- Store both native and formatted versions. Rejected — unnecessary duplication. + +**Rationale**: Keeps the underlying value suitable for export, alerting, and queries. Formatting is a purely UI concern. + +### D7: Allowlist-based function set, no dynamic functions + +**Decision**: The allowlist of built-in functions (math, aggregate, date, string, etc.) is defined in the parser and is per-instance configurable. Calling an unlisted function is a parse-time error. Users cannot register custom functions. + +**Alternatives considered:** + +- Scriptable custom functions (UDFs). Rejected — security risk, complex deployment, not needed for v1. +- Allow any identifier as a function call. Rejected — enables typos and makes migration (if we ever add a function) a breaking change. + +**Rationale**: Explicit allowlist is auditable and secure. The allowlist is per-instance configurable so operators can dial it down for determinism. + +## Risks / Trade-offs + +- **Risk:** Cross-widget references require both widgets to share a register. If not, field is downgraded to client-only and user gets a warning. → **Mitigation:** Document the limitation; most dashboards share a single register anyway. +- **Risk:** Client-side evaluation can go stale if the source widget's data is stale. → **Mitigation:** We follow the dashboard's existing refresh semantics — calculated fields re-evaluate whenever any source widget or filter changes. +- **Risk:** Server-side materialisation can fail (e.g., division by zero). → **Mitigation:** Error is logged to OpenRegister's computed-field error log; materialised value is null. Dashboard shows an inline error indicator. +- **Trade-off:** The function allowlist is conservative (no `eval`, no file I/O). This is intentional for security and determinism, but can be a friction point if users need e.g., regex. We accept this and version the allowlist in future changes. + +## Migration Plan + +1. **Parser + TypeScript evaluator land first** — add parser, type-checker, evaluator, and Vitest coverage. No integration yet; exported as a utility module. +2. **PHP evaluator** — deserialise and evaluate the same AST; cross-language test suite. +3. **Widget schema** — extend with `calculatedFields` array. +4. **Integration** — wire parser/validator into `WidgetController::update`, store AST, call OpenRegister `computed-fields` on save. +5. **Frontend evaluator** — integrates with `useDashboardsStore`, re-evaluates on filter/widget changes, renders results and errors. +6. **Rollback**: Schema change adds a nullable field; reverting the PR leaves the field NULL on all rows — no data loss. + +## Seed Data + +### Widget with calculated fields + +```json +{ + "id": "widget-abc123", + "title": "Revenue Analysis", + "type": "table", + "sourceId": "register-sales", + "calculatedFields": [ + { + "id": "calc-001", + "name": "profit_margin", + "label": "Profit Margin (%)", + "description": "Revenue minus cost, expressed as percentage of revenue", + "expression": "(revenue - cost) / revenue * 100", + "compiledExpression": { + "type": "binary", + "op": "*", + "left": { + "type": "binary", + "op": "/", + "left": { + "type": "binary", + "op": "-", + "left": {"type": "fieldRef", "source": "self", "path": "revenue"}, + "right": {"type": "fieldRef", "source": "self", "path": "cost"} + }, + "right": {"type": "fieldRef", "source": "self", "path": "revenue"} + }, + "right": {"type": "literal", "valueType": "number", "value": 100} + }, + "returnType": "number", + "evaluationMode": "both", + "serverComputedFieldId": "cf-profit-margin-001", + "formatOptions": { + "style": "decimal", + "minimumFractionDigits": 2, + "maximumFractionDigits": 2, + "locale": "nl-NL" + }, + "createdAt": "2026-05-22T10:30:00Z", + "updatedAt": "2026-05-22T10:30:00Z" + }, + { + "id": "calc-002", + "name": "net_revenue", + "label": "Net Revenue (EUR)", + "expression": "revenue - refunds", + "compiledExpression": { + "type": "binary", + "op": "-", + "left": {"type": "fieldRef", "source": "self", "path": "revenue"}, + "right": {"type": "fieldRef", "source": "self", "path": "refunds"} + }, + "returnType": "number", + "evaluationMode": "both", + "serverComputedFieldId": "cf-net-revenue-002", + "formatOptions": { + "style": "currency", + "currency": "EUR", + "locale": "nl-NL" + }, + "createdAt": "2026-05-22T10:31:00Z", + "updatedAt": "2026-05-22T10:31:00Z" + }, + { + "id": "calc-003", + "name": "resolution_days", + "label": "Avg. Resolution Time (days)", + "expression": "dateDiff(closedDate, openedDate, 'days')", + "compiledExpression": { + "type": "call", + "name": "dateDiff", + "args": [ + {"type": "fieldRef", "source": "self", "path": "closedDate"}, + {"type": "fieldRef", "source": "self", "path": "openedDate"}, + {"type": "literal", "valueType": "string", "value": "days"} + ] + }, + "returnType": "number", + "evaluationMode": "client", + "formatOptions": { + "pattern": "d 'dagen'" + }, + "createdAt": "2026-05-22T10:32:00Z", + "updatedAt": "2026-05-22T10:32:00Z" + }, + { + "id": "calc-004", + "name": "status_label", + "label": "Status Label", + "expression": "if(revenue > 100000, 'High Value', if(revenue > 10000, 'Medium Value', 'Low Value'))", + "compiledExpression": { + "type": "if", + "cond": { + "type": "binary", + "op": ">", + "left": {"type": "fieldRef", "source": "self", "path": "revenue"}, + "right": {"type": "literal", "valueType": "number", "value": 100000} + }, + "then": {"type": "literal", "valueType": "string", "value": "High Value"}, + "else": { + "type": "if", + "cond": { + "type": "binary", + "op": ">", + "left": {"type": "fieldRef", "source": "self", "path": "revenue"}, + "right": {"type": "literal", "valueType": "number", "value": 10000} + }, + "then": {"type": "literal", "valueType": "string", "value": "Medium Value"}, + "else": {"type": "literal", "valueType": "string", "value": "Low Value"} + } + }, + "returnType": "string", + "evaluationMode": "client", + "createdAt": "2026-05-22T10:33:00Z", + "updatedAt": "2026-05-22T10:33:00Z" + }, + { + "id": "calc-005", + "name": "comparison_to_target", + "label": "Actual vs Target (%)", + "description": "Revenue as percentage of sales target from widget-target", + "expression": "widget:widget-target.target_revenue / revenue * 100", + "compiledExpression": { + "type": "binary", + "op": "*", + "left": { + "type": "binary", + "op": "/", + "left": { + "type": "fieldRef", + "source": "widget:widget-target", + "path": "target_revenue" + }, + "right": {"type": "fieldRef", "source": "self", "path": "revenue"} + }, + "right": {"type": "literal", "valueType": "number", "value": 100} + }, + "returnType": "number", + "evaluationMode": "client", + "formatOptions": { + "style": "decimal", + "minimumFractionDigits": 1, + "maximumFractionDigits": 1, + "locale": "nl-NL" + }, + "createdAt": "2026-05-22T10:34:00Z", + "updatedAt": "2026-05-22T10:34:00Z" + } + ] +} +``` + +## Example Evaluations + +For the widget above with source data row: `{revenue: 150000, cost: 90000, refunds: 5000, openedDate: '2026-04-01T00:00:00Z', closedDate: '2026-04-21T00:00:00Z'}`: + +- `profit_margin`: `(150000 - 90000) / 150000 * 100 = 40.00` +- `net_revenue`: `150000 - 5000 = 145000.00` (formatted: €145.000,00) +- `resolution_days`: `21` (formatted: 21 dagen) +- `status_label`: "High Value" +- `comparison_to_target`: requires data from widget-target; if target is 120000, then `120000 / 150000 * 100 = 80.0` + +## Error Cases + +### Parse error + +User saves expression `(revenue - refunds` (missing closing paren): +- API response: 400 Bad Request +- Body: `{"error": "parse_error", "message": "Unexpected token at position 21", "column": 21, "expression": "(revenue - refunds"}` + +### Type error + +User saves expression `revenue + "100"` where revenue is number and `"100"` is string: +- API response: 400 Bad Request +- Body: `{"error": "type_error", "message": "Cannot add number + string", "operands": ["number", "string"]}` + +### Cycle detection + +Widget A has `calc1 = widget:B.x` and Widget B has `calc1 = widget:A.y`: +- API response: 400 Bad Request +- Body: `{"error": "cycle_detected", "widgets": ["widget-A", "widget-B"], "message": "Circular dependency detected between widgets"}` + +### Cross-register mismatch + +Widget A (register: sales) tries to reference Widget B (register: crm) in a server-mode calculated field: +- API response: 200 OK (save succeeds) +- Body: `{"warning": "downgraded_evaluation_mode", "field": "calc1", "reason": "Cross-register reference; evaluationMode downgraded from 'server' to 'client'"}` + +## Open Questions + +- Should calculated fields display in the widget's schema export (OpenAPI / Postman)? Current decision: yes, but marked as derived/read-only at export time. +- Can calculated fields be used in widget filtering (as filter targets)? Current decision: no (v1 — filter.field must reference real data). Future: revisit for v2 if demand is high. +- Should there be a formula function to query sibling calculated fields on the same widget? Current decision: no (use `CalculatedRef` only); forces you to inline formulas if you want to chain them. Future: revisit if complexity justifies it. + +## Build notes: value semantics + +Pinned by the shared evaluator suite (`tests/fixtures/calculated-fields/shared-evaluator-test-suite.json`), which the PHP evaluator must also pass: + +- Dates are UTC ISO strings `YYYY-MM-DDTHH:MM:SSZ`; durations are seconds. `dateDiff(end, start, unit)` answers a whole number of `unit` (default `days`; calendar months and years), so its type is `number`; `durationBetween` answers a duration. +- Null propagates through every operator and function except `coalesce`, `ifNull`, `case` and the list aggregates; nulls inside a list are skipped. +- `round` rounds half away from zero after trimming to 15 significant digits, as PHP does (`round(1.005, 2)` is `1.01`). +- Runtime failures (division by zero, invalid dates, unknown units, failed coercions) are errors with a fixed message, never a partial value. + +## Build notes: server-mode materialisation + +OpenRegister has no separate `computed-fields` store. Its derived values are +schema properties: a property may carry a JSON-AST `calculation` +(`{type, expression}`), which OpenRegister's save-time calculation listener +evaluates and writes into every object of the schema. A server-mode field is +materialised as exactly that: one read-only property per field on the widget's +source schema, keyed `launchpad_<placement>__<field>`. That key is the field's +`serverComputedFieldId`. Because every key a widget owns shares the prefix +`launchpad_<placement>__`, a save replaces exactly that widget's properties and +a delete removes them all, so no entry is orphaned, and other widgets' and the +schema's own properties are never touched. + +OpenRegister's calculation vocabulary is narrower than ours, and some of its +operators behave differently (PHP `round` against JavaScript `Math.round` on +halves, a placeholder reading of strings starting with `$`, number-to-text in +`concat`). So only the part both engines evaluate alike is translated: +literals, the widget's own fields, other materialised fields of the same +widget, `+ - * / %`, the comparisons, `and`/`or`/`not`, `if`, and `abs`, +`min`, `max`, `coalesce`. Any other field, and any field reading one, is +downgraded to `client` with a warning, as are fields whose return type +OpenRegister cannot declare (`duration`, `null`). The difference that remains +is null handling: our evaluator propagates null, OpenRegister's refuses a +non-numeric operand, logs the failing calculation and saves the object without +that value, which is the computed-field error log of REQ-CALC-008. + +The widget and the schema live in different stores, so the save is ordered +instead of wrapped in one database transaction: the keys are planned before +the widget is saved, the schema is written once afterwards, and when +OpenRegister refuses that write (the current user may not edit the schema, or +it is gone) the widget is saved again with those fields in client mode. The +schema is read and written as the current user, so OpenRegister's own schema +access checks decide who may materialise a field. diff --git a/openspec/changes/widget-calculated-fields/hydra.json b/openspec/changes/archive/2026-11-22-widget-calculated-fields/hydra.json similarity index 100% rename from openspec/changes/widget-calculated-fields/hydra.json rename to openspec/changes/archive/2026-11-22-widget-calculated-fields/hydra.json diff --git a/openspec/changes/widget-calculated-fields/proposal.md b/openspec/changes/archive/2026-11-22-widget-calculated-fields/proposal.md similarity index 100% rename from openspec/changes/widget-calculated-fields/proposal.md rename to openspec/changes/archive/2026-11-22-widget-calculated-fields/proposal.md diff --git a/openspec/changes/archive/2026-11-22-widget-calculated-fields/screens.md b/openspec/changes/archive/2026-11-22-widget-calculated-fields/screens.md new file mode 100644 index 000000000..9f6ee9800 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-widget-calculated-fields/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWidgetInstellen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetInstellen diff --git a/openspec/changes/archive/2026-11-22-widget-calculated-fields/specs/calculated-fields/spec.md b/openspec/changes/archive/2026-11-22-widget-calculated-fields/specs/calculated-fields/spec.md new file mode 100644 index 000000000..23d2449b7 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-widget-calculated-fields/specs/calculated-fields/spec.md @@ -0,0 +1,253 @@ +--- +capability: calculated-fields +delta: false +status: draft +--- + +# Calculated Fields + +A calculated field is a named expression attached to a widget that produces a value derived from other fields in the same widget, fields in other widgets on the same dashboard, constants, and built-in functions. + +## ADDED Requirements + +### Requirement: REQ-CALC-001 Formula parser produces deterministic AST + +The system SHALL parse a calculated-field expression into a canonical AST at save time and SHALL refuse to persist any widget whose calculated-field expressions fail to parse. + +#### Scenario: Valid expression parsed to AST + +- GIVEN a valid expression `(revenue - refunds) / revenue * 100` +- WHEN the widget is saved +- THEN the parser SHALL produce a `Binary` AST with operator `*` and SHALL store it in `compiledExpression` +- AND the AST SHALL be deep-equal to any other parse of the same expression + +#### Scenario: Parse error on mismatched parentheses + +- GIVEN an expression with mismatched parentheses `(revenue - refunds` +- WHEN the widget is saved +- THEN the API SHALL respond 400 with a parse error that includes the column position (column 21) +- AND SHALL NOT persist the widget + +#### Scenario: Whitespace normalization in AST + +- GIVEN two expressions that differ only by whitespace: `(a+b)` and `( a + b )` +- WHEN both are parsed +- THEN their `compiledExpression` ASTs SHALL be deep-equal + +### Requirement: REQ-CALC-002 Type checking at save time + +The system SHALL infer the type of every sub-expression at parse time and SHALL reject expressions whose operator/function arguments do not match the declared signature. + +#### Scenario: Type mismatch on binary operator + +- GIVEN an expression `revenue + customerName` where `revenue:number` and `customerName:string` +- WHEN the widget is saved +- THEN the API SHALL respond 400 with a type error naming both operands +- AND SHALL NOT persist the widget + +#### Scenario: Function signature validation + +- GIVEN an expression `round(revenue, "two")` where `round` expects (number, integer) +- WHEN the widget is saved +- THEN the API SHALL respond 400 with a function-signature error +- AND SHALL NOT persist the widget + +#### Scenario: Type inference through coalesce + +- GIVEN an expression `coalesce(null, revenue, 0)` where `revenue:number` +- WHEN the widget is saved +- THEN the inferred `returnType` SHALL be `number` +- AND the widget SHALL persist successfully + +### Requirement: REQ-CALC-003 Client-side evaluator reactive to filter changes + +The client-side evaluator SHALL recompute every `client` and `both` mode calculated field whenever any source field, source widget, or filter changes, and SHALL never round-trip to the server for an evaluation. + +#### Scenario: Recompute on filter change + +- GIVEN a widget with calculated field `profit = revenue - cost` +- AND the widget displays `revenue = 100000, cost = 60000, profit = 40000` +- WHEN the user changes a dashboard filter that affects `revenue` and `cost` to new values `110000, 70000` +- THEN `profit` SHALL be recomputed inside the browser to `40000` and the new value SHALL appear without an HTTP request +- AND the UI SHALL update within one animation frame + +#### Scenario: Cross-widget dependency tracking + +- GIVEN a calculated field referencing `widget:abc123` +- WHEN the source widget `abc123` refreshes its data +- THEN the dependent calculated field SHALL recompute synchronously in the same tick +- AND the updated value SHALL be rendered before the next animation frame + +#### Scenario: Filter chain with multiple affected fields + +- GIVEN a dashboard with widgets W1 (revenue), W2 (cost), W3 (calculated: W1.x / W2.y) +- WHEN the user changes a filter that affects both W1 and W2 +- THEN W3's calculated field SHALL be recomputed after both W1 and W2 complete their refresh +- AND the order of recomputation shall be deterministic (topological sort order) + +### Requirement: REQ-CALC-004 Server-side evaluation via OpenRegister computed-fields + +The system SHALL, for every calculated field in `evaluationMode=server` or `both`, create a corresponding `computed-fields` entry on the underlying schema and SHALL keep the two in sync on widget save. + +#### Scenario: Create server-mode computed-field entry + +- GIVEN a new calculated field with `evaluationMode=server`, `expression="revenue - cost"` +- WHEN the widget is saved +- THEN a `computed-fields` entry SHALL be created on the source schema with the same expression +- AND `serverComputedFieldId` SHALL be populated with the OpenRegister entry's ID + +#### Scenario: Update server-mode entry on expression change + +- GIVEN an existing server-mode calculated field with `serverComputedFieldId="cf-123"` +- WHEN the widget is saved with a new expression `"profit * 0.9"` +- THEN the linked `computed-fields` entry SHALL be updated with the new expression in the same transaction +- AND the update SHALL be atomic (no partial state visible to other readers) + +#### Scenario: Delete computed-field entry when widget is deleted + +- GIVEN a server-mode calculated field with `serverComputedFieldId="cf-123"` +- WHEN the widget is deleted +- THEN the linked `computed-fields` entry SHALL be removed from the schema +- AND no orphaned OpenRegister entries shall remain + +### Requirement: REQ-CALC-005 Identical results between evaluators + +Both evaluators SHALL produce identical results for every expression in the shared test suite, with documented and tested handling of numeric precision and null propagation. + +#### Scenario: Numeric precision across evaluators + +- GIVEN any expression in the shared evaluator test suite that produces a number +- WHEN evaluated by the TypeScript and PHP evaluators on identical input +- THEN the two results SHALL be deep-equal OR equal to within 1e-9 of each other (accounting for IEEE 754 rounding) + +#### Scenario: Null propagation + +- GIVEN an expression `a + null` where `a` is any non-null value +- WHEN evaluated by either the TypeScript or PHP evaluator +- THEN the result SHALL be `null` +- AND SHALL NOT throw an exception + +#### Scenario: Cross-evaluator test matrix + +- GIVEN the shared test suite contains 50+ test cases covering: literals, field refs, binary ops, unary ops, function calls, conditionals, null handling, type coercion at boundaries +- WHEN the test suite runs against both evaluators +- THEN 100% of tests SHALL pass on both + +### Requirement: REQ-CALC-006 Cross-widget references with cycle detection + +The system SHALL allow a calculated field to reference fields on other widgets on the same dashboard and SHALL refuse any dependency graph that contains a cycle. + +#### Scenario: Cycle detection on save + +- GIVEN widget A's calculated field references `widget:B.x` and widget B's calculated field references `widget:A.y` +- WHEN either widget is saved +- THEN the API SHALL respond 400 with a `cycleDetected` error naming both widgets +- AND SHALL NOT persist + +#### Scenario: Acyclic cross-widget reference accepted + +- GIVEN widget A's calculated field references `widget:B.x` where B has no calculated fields pointing back to A +- WHEN A is saved +- THEN the save SHALL succeed +- AND A's calculated field SHALL re-evaluate whenever B refreshes (REQ-CALC-003) + +#### Scenario: Self-reference rejected + +- GIVEN a calculated field named `x` with expression `widget:self.x` (self-referential) +- WHEN the widget is saved +- THEN the API SHALL respond 400 with a `cycleDetected` error +- AND SHALL NOT persist + +### Requirement: REQ-CALC-007 Cross-widget downgrade on source mismatch + +When a `server` or `both` mode calculated field references a widget whose data does not live in the same OpenRegister register/schema, the system SHALL downgrade the field to `client` mode at save time and SHALL warn the user. + +#### Scenario: Downgrade on different register + +- GIVEN a calculated field with `evaluationMode=server` that references a widget backed by a different register (e.g., widget A uses register:sales, widget B uses register:crm) +- WHEN the widget is saved +- THEN the field's `evaluationMode` SHALL be persisted as `client` +- AND the API response SHALL include a warning: `{warning: 'downgraded_evaluation_mode', field: 'name', reason: 'Cross-register reference'}` + +#### Scenario: Preserve server mode on same register + +- GIVEN a calculated field with `evaluationMode=server` that references a widget backed by the same register and schema +- WHEN the widget is saved +- THEN `evaluationMode` SHALL remain `server` +- AND a `computed-fields` entry SHALL be created + +### Requirement: REQ-CALC-008 Inline error display preserves dashboard usability + +When a calculated field fails to evaluate at runtime, the system SHALL render an inline error indicator on the widget without breaking other widgets on the dashboard. + +#### Scenario: Division by zero in client-side evaluation + +- GIVEN a calculated field `ratio = a / b` where the user has NOT added a guard and `b` is 0 in a given row +- WHEN the widget renders +- THEN the field's cell SHALL display an error icon +- AND hovering the icon SHALL show the expression and the value of `b` +- AND other widgets on the dashboard SHALL render normally (not affected) + +#### Scenario: Server-side evaluation error + +- GIVEN the same calculated field on the server-side evaluator +- WHEN the materialiser runs and encounters division by zero +- THEN the materialised value SHALL be `null` +- AND the OpenRegister computed-field error log SHALL record: `{expression, inputs, error: 'division by zero'}` + +#### Scenario: Error does not block widget render + +- GIVEN a widget with 10 calculated fields, 1 of which fails to evaluate +- WHEN the widget renders +- THEN the 9 successful fields SHALL display normally +- AND the 1 failed field SHALL show an error indicator +- AND the widget SHALL be usable (filtering, exporting, etc. do not break) + +### Requirement: REQ-CALC-009 Allowlisted function set with named signatures + +The parser SHALL accept only functions on the documented allowlist and SHALL reject any call to an unknown identifier as a function with a clear error. + +#### Scenario: Unknown function rejected + +- GIVEN an expression `eval("revenue * 2")` +- WHEN the widget is saved +- THEN the API SHALL respond 400 with `{error: 'unknownFunction', name: 'eval'}` +- AND SHALL NOT persist + +#### Scenario: Variadic function accepted with correct args + +- GIVEN an expression `sum(revenue, cost, profit)` where `sum` accepts variadic numbers +- WHEN the widget is saved +- THEN the parser SHALL validate that `sum` is on the allowlist and accepts variadic args +- AND the widget SHALL persist successfully + +#### Scenario: Allowlist is per-instance configurable + +- GIVEN a LaunchPad instance with `allowedFunctions: ['abs', 'round', 'sum']` (restricted) +- WHEN a user tries to save an expression using `now()` (not in allowlist) +- THEN the API SHALL respond 400 with `{error: 'functionNotAllowed', name: 'now'}` + +### Requirement: REQ-CALC-010 Format options applied at render time + +The system SHALL apply `formatOptions` only at render time on the client, and SHALL store and evaluate the underlying value in its native type. + +#### Scenario: Currency formatting preserves numeric value + +- GIVEN a calculated field with `returnType=number`, `formatOptions={style:'currency', currency:'EUR', locale:'nl-NL'}`, evaluated value of `1234.5` +- WHEN the widget renders for a Dutch user +- THEN the displayed string SHALL be `€ 1.234,50` +- AND the underlying value passed to alerting/export SHALL remain `1234.5` (not a string) + +#### Scenario: Date formatting preserves ISO instant + +- GIVEN a calculated field with `returnType=date`, `formatOptions={pattern:'dd MMM yyyy', locale:'nl-NL'}`, evaluated value of `2026-05-22T14:30:00Z` +- WHEN the widget renders +- THEN the displayed string SHALL be `22 mei 2026` +- AND the underlying value passed to filters/queries SHALL remain `2026-05-22T14:30:00Z` (ISO 8601) + +#### Scenario: Format options ignored at server-side evaluation + +- GIVEN the same calculated field in server-side mode (materialised) +- WHEN the field is evaluated on the server +- THEN the materialised value SHALL be the raw number/date (no formatting) +- AND the format options SHALL be applied only by the widget renderer, not by OpenRegister diff --git a/openspec/changes/archive/2026-11-22-widget-calculated-fields/tasks.md b/openspec/changes/archive/2026-11-22-widget-calculated-fields/tasks.md new file mode 100644 index 000000000..a4a38ef8d --- /dev/null +++ b/openspec/changes/archive/2026-11-22-widget-calculated-fields/tasks.md @@ -0,0 +1,143 @@ +# Tasks — widget-calculated-fields + +## 1. Parser and Type Checking (TypeScript) + +- [x] Task 1: Define AST node types as TypeScript interfaces (built as JSDoc typedefs plus `isAstNode()` in `src/utils/calculatedFields/ast.js`; the app is JavaScript): `Literal`, `FieldRef`, `CalculatedRef`, `Binary`, `Unary`, `If`, `Call` with complete type definitions and JSON-serializable structure +- [x] Task 2: Implement `CalculatedFieldParser.ts` with `parse(expression: string): AST` that produces deterministic canonical AST; on syntax error throw `ParseError` with column position (REQ-CALC-001) +- [x] Task 3: Implement `TypeChecker.ts` with `inferType(ast: AST, fieldSchema): Type` that validates all operators and function calls at the AST level; on type mismatch throw `TypeError` with operand names (REQ-CALC-002) +- [x] Task 4: Define the allowlist of built-in functions with signatures: `math` (abs, round, ceil, floor, min, max, pow, sqrt, log, sum, avg), `aggregate` (count, countIf, sumIf, avgIf), `date/time` (now, today, dateDiff, dateAdd, formatDate, parseDate), `duration` (durationBetween, durationFormat), `string` (concat, upper, lower, trim, contains, startsWith, endsWith, replace, format), `conditional` (coalesce, ifNull, case), `type coercion` (toNumber, toString, toBool, toDate) +- [x] Task 5: Add allowlist to `config.ts` with per-instance configurability (default: all functions); parser rejects unknown functions at parse time (REQ-CALC-009) +- [x] Task 6: Vitest coverage: 100+ test cases covering all AST node types, all operators, all built-in functions, error cases (REQ-CALC-001, REQ-CALC-002) + +## 2. Cycle Detection + +- [x] Task 7: Implement `CycleDetector.ts` that builds a dependency graph of all calculated fields on a widget + cross-widget references; run topological sort; throw `CycleError` if cycle detected, naming the cycle (REQ-CALC-006) +- [x] Task 8: Wire cycle detection into the parser so `parseAndValidate(widget)` calls both type-checker and cycle-detector before returning validated AST (REQ-CALC-006) +- [x] Task 9: Vitest: cycle detection rejects self-references, mutual references, and longer cycles; accepts acyclic graphs (REQ-CALC-006) + +## 3. TypeScript Evaluator (Client-side) + +- [x] Task 10: Implement `CalculatedFieldEvaluator.ts` that takes an AST and a row context (field values from source widget) and evaluates deterministically (REQ-CALC-003, REQ-CALC-005) +- [x] Task 11: Handle all AST node types: literals, field refs (with `source='self'` and `source='widget:<id>'`), binary/unary ops, conditionals, function calls; return typed result or `null` on null propagation (REQ-CALC-005) +- [x] Task 12: Error handling: catch runtime errors (divide by zero, null dereference, function error) and return `{error: message, expression, inputs}` so the widget can display an inline error (REQ-CALC-008) +- [x] Task 13: Cross-widget field refs resolved via the dashboard store's widget data at evaluation time (REQ-CALC-003) + - Built: `evaluateDashboard()` in `src/utils/calculatedFields/dashboardValues.js` hands each field the other widgets' current data and calculated values, read from the calculated-fields store. +- [x] Task 14: Numeric precision: all math follows IEEE 754 (JavaScript Number), test suite validates equivalence with PHP to within 1e-9 (REQ-CALC-005) + - Validated: the shared suite holds both evaluators to its expected numbers within 1e-9 (Vitest `evaluator.spec.js`, PHPUnit `CalculatedFieldEvaluatorTest`). + +## 4. Shared Test Suite + +- [x] Task 15: Create `test/shared-evaluator-test-suite.json` containing 50+ test cases: each case specifies an AST, input data (field values), expected output, and error conditions; suite is language-agnostic JSON +- [x] Task 16: Import and run the shared suite in Vitest (TypeScript evaluator) and PHPUnit (PHP evaluator); both must pass 100% of tests (REQ-CALC-005) + - Vitest half built: `src/utils/calculatedFields/__tests__/evaluator.spec.js` runs every case of `tests/fixtures/calculated-fields/shared-evaluator-test-suite.json` (98 cases, parse and evaluate); the PHPUnit half is `tests/Unit/Service/CalculatedFields/CalculatedFieldEvaluatorTest.php`, one data-provider case per suite case, all 98 passing. + +## 5. Frontend Integration (Vue/Store) + +- [x] Task 17: Add `useCalculatedFields()` composable that: (1) watches widget source data, (2) watches dashboard filters, (3) maintains a dependency graph of calculated fields, (4) re-evaluates on any change, (5) returns `{values: Map, errors: Map}` (REQ-CALC-003) + - Built: `src/composables/useCalculatedFields.js` watches the widget's data and the dashboard filters, reports them to the store and returns `{values: Map, errors: Map}`; the dependency graph is the cycle detector's topological order. +- [x] Task 18: Integrate into `useDashboardsStore.js`: when a widget's data arrives or filters change, re-evaluate all calculated fields on that widget and dependent widgets in topological order (REQ-CALC-003) + - Built as its own Pinia store, `src/stores/calculatedFields.js` (the app has no `useDashboardsStore.js`): `setWidgets`, `setWidgetData` and `setFilters` re-evaluate every field of the dashboard in topological order; `dependentWidgets()` names the widgets a data change reaches. +- [x] Task 19: Widget component renders calculated-field values in the appropriate column/cell alongside source fields; if error, display error icon with tooltip showing expression + input value (REQ-CALC-008) + - Built on `@conduction/nextcloud-vue`'s `data` event (nextcloud-vue change `widget-data-event`): `CnChartWidget` and `CnStatsBlockWidget` tell their host what they show (a chart's series, categories, labels and total; a count), `ChartHost` and `StatsBlockHost` forward it, and `WidgetRenderer` hands it to the calculated-fields store; `Views.vue` hands the store the open dashboard's placements and filters. `src/components/Widgets/CalculatedFields/CalculatedValues.vue`, under every registry widget, shows each field's label and value, or an error icon whose hover text names what went wrong, the formula and the values read. Tests: `CalculatedValues.spec.js`, `errorText.spec.js`, `WidgetRenderer.behaviour.spec.js`, `chartAndStatsHosts.spec.js`. +- [x] Task 20: Filtering/export/drill-down: calculated-field values are included in exports and can be used in drill-down but NOT as filter targets in v1 (out of scope) (REQ-CALC-010) + - Built on Ruben's decision of 19 Nov (evaluate on the server at export time): `lib/Service/ScheduledExport/ExportCalculatedValues.php` evaluates every calculated field of the export's widgets with `CalculatedFieldEvaluator`, in the cycle detector's order and with the same context the client's `evaluateDashboard()` hands (own data, earlier values, other widgets' data and values). `SubjectTables` adds after each widget's table one row of its field values, over the rows the recipient's filter left (`rows` and `total` are what a field reads there). A failing field or a cycle is an empty cell. Values stay native (formatting is display only, task 36); drill-down reads them from the store. Not a filter target, as the task says. Tests: `ExportCalculatedValuesTest`, `SubjectTablesTest`. + +## 6. Schema and Widget Service (PHP) + +- [x] Task 21: Extend `WidgetEntity` schema: add nullable `calculatedFields` JSON column storing the array of field objects (id, name, label, expression, compiledExpression, returnType, evaluationMode, etc.) +- [x] Task 22: Create migration that adds the column to existing widgets with default `[]` +- [x] Task 23: Implement `CalculatedFieldService.php` (server-side) with: (1) `validateAndCompile(widget, expression)` calls the parser and type-checker, (2) `detectCycles(widget)` checks for cycles, (3) `evaluateExpression(ast, row): mixed` evaluates the AST for server-side use (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006) + - Built: `lib/Service/CalculatedFieldService.php`. The server does not re-parse the source text (design D3): `validateAndCompile()` checks each field's stored `compiledExpression` with `CalculatedFieldAstChecker` (node shapes as `isAstNode()`, built-in and allowlisted functions, argument counts), detects cycles over the widget and its dashboard neighbours, and type-checks in dependency order with `CalculatedFieldTypeChecker` (rule for rule as `typeChecker.js`), setting each field's `returnType`. `tests/fixtures/calculated-fields/type-check-cases.json` holds 60 ASTs with the client type checker's answers, and the PHP checker must give the same type or the same error envelope for each. +- [x] Task 24: Wire `WidgetController::create` and `::update` to validate all calculated fields before persisting via `CalculatedFieldService::validateAndCompile` (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006) + - Built in `WidgetApiController::updatePlacement`, the endpoint that writes `calculatedFields`; creating a placement (`addWidget`) takes no calculated fields, so there is nothing to check there. +- [x] Task 25: Return parse/type/cycle errors as 400 with body `{error: error_code, message: ..., ...details}` (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006) + - Built: a `CalculatedFieldValidationError` or `CalculatedFieldCycleError` answers 400 with its envelope (`invalidExpression`, `unknownFunction`, `functionNotAllowed`, `arityMismatch`, `functionSignature`, `typeError`, `duplicateField`, `cycleDetected`, with the `field` named) and nothing is saved. Parse errors with a column stay in the editor, which parses the text. + +## 7. OpenRegister Integration (Server-side Materialisation) + +- [x] Task 26: Implement `CalculatedFieldService::materializeForOpenRegister(widget): array` that, for every calculated field with `evaluationMode='server'` or `'both'`: (1) creates/updates a `computed-fields` entry on the schema, (2) populates `serverComputedFieldId` in the widget, (3) stores the expression in OpenRegister (REQ-CALC-004) + - Built: OpenRegister's computed-field entry is a read-only schema property carrying a JSON-AST `calculation`, which OpenRegister evaluates and stores on every object save. `CalculatedFieldCalculationTranslator` turns the field's AST into that expression for the part both engines evaluate alike (literals, own fields, other materialised fields of the widget, arithmetic, comparison, logic, `if`, `abs`/`min`/`max`/`coalesce`); `CalculatedFieldMaterialiser` writes one property per field under the key `launchpad_<widget>__<field>`, which is the `serverComputedFieldId`, dependencies first, replacing only the keys that widget owns. A field the translator cannot express, or whose return type OpenRegister cannot declare, is downgraded to client with a `downgraded_evaluation_mode` warning, as are the fields that read it. The schema is read and written as the current user, so OpenRegister's schema access checks apply. +- [x] Task 27: Wire materialisation into `WidgetService::save()`: after widget is persisted, call `materializeForOpenRegister()` in a transaction (REQ-CALC-004) + - Built in `WidgetApiController::updatePlacement` (the endpoint that writes `calculatedFields`): the ids are planned before the save, the schema is written after it in one schema update, and when OpenRegister refuses that write the widget is saved again with those fields in client mode and a warning, so the widget never names a property that does not exist. A source change re-checks the stored fields and moves their properties to the new schema. +- [x] Task 28: On widget delete, call `CalculatedFieldService::cleanupServerFields(widget)` to delete all orphaned `computed-fields` entries (REQ-CALC-004) + - Built in `WidgetApiController::removePlacement`: every property under the widget's key prefix leaves the source schema; when OpenRegister refuses, the widget is still removed and the response carries `server_fields_not_removed`. +- [x] Task 29: Implement downgrade logic (REQ-CALC-007): when a server-mode field references a widget with a different source register, downgrade to `client` mode, set `evaluationMode='client'`, and return warning in API response + - Built: `CalculatedFieldService::downgradeCrossSource()` (with `CalculatedFieldSources`) persists a `server`/`both` field as `client` when it reads a widget whose `register/schema` differs from its own, or when its widget has no OpenRegister source; the placement update answers with `warnings: [{warning: 'downgraded_evaluation_mode', field, reason}]`. + +## 8. PHP Evaluator (Server-side) + +- [x] Task 30: Implement `CalculatedFieldEvaluator.php` that deserialises the AST (JSON) and evaluates it on a row context (REQ-CALC-005) + - Built: `lib/Service/CalculatedFields/CalculatedFieldEvaluator.php` evaluates the parser's JSON AST on a row context (`row`, `calculated`, `widgets`, `widgetCalculated`), with `now` injectable. +- [x] Task 31: Mirror the TypeScript evaluator exactly: all AST node types, all operators, all functions; numeric precision via IEEE 754 floats; null propagation (REQ-CALC-005) + - Built: node for node and function for function as `src/utils/calculatedFields/evaluator.js`: `CalculatedFieldFunctions` (the allowlist, the same failures and messages), `CalculatedFieldValues` (JavaScript's number text, `===` over int and float, path reading across lists, UTC dates and calendar months), null propagation and the null-aware functions. +- [x] Task 32: Error handling: catch runtime errors and store them in OpenRegister's computed-field error log (not thrown to the widget caller); return `null` for the materialised value (REQ-CALC-008) + - Built: `CalculatedFieldEvaluator::evaluateField()` catches a run-time failure and answers `{value: null, error, expression}` instead of throwing. A materialised field is evaluated by OpenRegister's save-time calculation listener, which logs a failing calculation with its name, object and message and still saves the object, without the value. +- [x] Task 33: Run the shared test suite (Task 16) against the PHP evaluator; all tests must pass (REQ-CALC-005) + - All 98 cases of `tests/fixtures/calculated-fields/shared-evaluator-test-suite.json` pass against the PHP evaluator. + +## 9. Format Options and Rendering + +- [x] Task 34: Implement `FormatOptions` type with: number format (style, minimumFractionDigits, maximumFractionDigits, currency, locale), date format (pattern, locale), duration format (pattern) + - Built: `src/utils/calculatedFields/formatOptions.js` (JSDoc typedefs `NumberFormatOptions`, `DateFormatOptions`, `DurationFormatOptions`). +- [x] Task 35: In the widget's table/chart/single-value renderers, apply format options at display time ONLY (not at evaluation time) using `Intl.NumberFormat`, `Intl.DateTimeFormat`, or custom logic for durations (REQ-CALC-010) + - Built: `CalculatedValues.vue` formats each value with `formatCalculatedValue()` at display time, in the viewer's language; the store keeps the native value. One place serves the chart, count and single-value widgets, since the values show beside the widget rather than inside a library renderer's cells. +- [x] Task 36: Format options do NOT affect the value passed to alerting, export, or other consumers; only the displayed string in the UI (REQ-CALC-010) + - `formatCalculatedValue()` only answers a display string; the store keeps native values for alerting, export and drill-down (tested). + +## 10. Testing — Backend + +- [x] Task 37: PHPUnit — `CalculatedFieldValidationTest.php`: parse errors, type errors, cycle detection, unknownFunction errors all return correct 400 envelope (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006, REQ-CALC-009) + - Built as `CalculatedFieldAstCheckerTest`, `CalculatedFieldTypeCheckerTest`, `CalculatedFieldServiceTest` and `WidgetApiControllerCalculatedFieldsTest` (the 400 envelopes on the endpoint). +- [x] Task 38: PHPUnit — `CalculatedFieldEvaluatorTest.php`: shared test suite (Task 16) runs against PHP evaluator; all operators, functions, null handling, numeric precision (REQ-CALC-005) + - `CalculatedFieldEvaluatorTest` (102 tests): the shared suite, `evaluateField()` catching a failure with its expression, cross-widget reads, unknown nodes and functions, wrong kinds. +- [x] Task 39: PHPUnit — `CalculatedFieldServerModeTest.php`: verify `computed-fields` entries created/updated/deleted correctly; downgrade logic works (REQ-CALC-004, REQ-CALC-007) + - `CalculatedFieldServerModeTest` (15 tests: create, update, unchanged save, back to client, source change, dependency order, unsupported and undeclarable fields, refused write, no OpenRegister, cleanup), `CalculatedFieldCalculationTranslatorTest` (21) and `WidgetApiControllerServerFieldsTest` (5, the endpoints). +- [x] Task 40: PHPUnit — `CrossWidgetReferenceTest.php`: parse/evaluate cross-widget refs (`widget:id.field`); cycle detection (REQ-CALC-006) + - `tests/Unit/Service/CrossWidgetReferenceTest.php` (5 tests) through `CalculatedFieldService`: a reference to a neighbour is accepted and ordered after it, a cross-widget cycle answers `cycleDetected` naming the cycle and widgets, a neighbour's calculated value and dotted data paths are read, an absent widget reads as null. The server checks stored ASTs and does not parse text (design D3); parsing `widget:id.field` is covered by the Vitest parser suite. `CalculatedFieldCycleDetectorTest.php` (7 tests) covers the detector itself. + +## 11. Testing — Frontend + +- [x] Task 41: Vitest — `parser.test.ts`: 100+ cases covering all AST node types, operators, functions, error cases (REQ-CALC-001, REQ-CALC-002, REQ-CALC-009) + - `src/utils/calculatedFields/__tests__/parser.cases.spec.js`: 183 table cases (every binary and unary operator with associativity, every literal kind, references, all 39 built-ins at minimum arity, every arity bound refused, unknown and disallowed functions, 22 malformed inputs answered as column-positioned parse errors), beside the 10 cases of `parser.spec.js`. +- [x] Task 42: Vitest — `evaluator.test.ts`: shared test suite runs against TypeScript evaluator; all operators, functions, null handling, numeric precision (REQ-CALC-005) +- [x] Task 43: Vitest — `cycleDetector.test.ts`: cycle detection rejects self-refs, mutual refs, longer cycles; accepts acyclic (REQ-CALC-006) +- [x] Task 44: Playwright — render a widget with calculated fields; verify values appear in the table/chart; verify inline errors show on evaluation failure; verify other widgets still render (REQ-CALC-003, REQ-CALC-008) + - 2026-11-22: tests/e2e/widget-calculated-fields.spec.ts:226 passed on the live stack (triage/lpf-6-bundle.log). +- [x] Task 45: Playwright — cross-widget reference: change filter on source widget, verify dependent widget's calculated field re-evaluates (REQ-CALC-003) + - 2026-11-22: tests/e2e/widget-calculated-fields.spec.ts:247 passed on the live stack with this branch's bundle (triage/lpf-6-bundle.log); it needs the boot filter-session fix in Views.vue, without which a bookmarked `f` was ignored. +- [x] Task 46: Playwright — server-mode field: materialised value is queryable via OpenRegister API; client-mode field is not (REQ-CALC-004) + - 2026-11-22: tests/e2e/widget-calculated-fields.spec.ts:275 passed on the live stack (triage/lpf-6-bundle.log). + +## 12. Quality and Documentation + +- [x] Task 47: `composer check:strict` and `eslint` pass on all new files + - On every new lib file of the change: `php -l`, phpcs, phpmd, psalm and phpstan report nothing (fixed a psalm `InvalidOperand` in `CalculatedFieldFunctions::toNumber`, same behaviour); spec annotations, initial-state and licence checks pass; eslint reports nothing on `src/utils/calculatedFields`, the composable and the store. The repository-wide `composer check:strict` still fails on findings outside this change. +- [x] Task 48: OpenAPI / Postman / API docs: document the new Widget schema extension (`calculatedFields` array); document error response envelopes (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006, REQ-CALC-009) + - `openapi.json`: `CalculatedField`, `CalculatedFieldError` (the 400 envelope) and `CalculatedFieldWarning` schemas, the request body and 200/400 responses of `PUT /widgets/{placementId}`, and the cleanup warning on `DELETE`. Postman (`tests/integration/launchpad.postman_collection.json`): a valid field answered with its `returnType`, an unknown function answered 400. `docs/features/widgets.md`: a Calculated fields section. +- [x] Task 49: i18n — `nl_NL` and `en_US` translations for: error messages (parse_error, type_error, cycle_detected, unknownFunction), inline error hover text, downgrade warning + - Built: `src/utils/calculatedFields/errorText.js` gives a translated sentence per code (`parseError`, `invalidExpression`, `typeError`, `cycleDetected`, `unknownFunction`, `functionNotAllowed`, `arityMismatch`, `functionSignature`, `duplicateField`, and the `downgraded_evaluation_mode` warning) and the inline hover text; `nl` and `en` in `l10n/`. The downgrade warning has no screen yet: no editor for calculated fields exists in the app, so the sentence waits for one. +- [x] Task 50: SPDX — all new PHP files have `@license EUPL-1.2` + `@copyright` in docblock + - Every new PHP file under `lib/Service/CalculatedFields/` carries `@license EUPL-1.2`, `@copyright` and the SPDX lines. +- [x] Task 51: Changelog entry describing: calculated fields as a widget feature, dual evaluation (client + server), allowlisted function set, error handling + inline indicators, cross-widget refs + cycle detection, format options + - `CHANGELOG.md` (Unreleased, Added): the evaluation engine, marked in progress until storage and materialisation land. +- [x] Task 52: Design.md — document the design decisions (D1–D7), rationale for dual evaluation, AST-based approach, shared test suite, format-at-render-time strategy, migration plan + - D1–D7, the rationale, the migration plan and the value semantics were in `design.md`; added the build notes for server-mode materialisation (what OpenRegister's computed-field entry is, the translated subset, ordering instead of a cross-store transaction). +- [x] Task 53: No hydra-gate finding introduced by this change (route-auth, admin-idor, semantic-auth, spdx-headers, etc.) + - 2026-11-22: the diff-scoped gate run (`diff-check.sh`, 26 of 26 applicable gates) and the full `run-hydra-gates.sh` run (stopped by its time limit after gate 111) report no finding in this change's files. The failing gates are inherited and outside the change: composer-audit, no-admin-idor (`DashboardApiController` show/byPath/computePath/schedule), or-abstraction (Tenant theme classes), semantic-controls (`ContainerWidget.vue`), link-text-quality (a bookmarks test fixture), spec-anchor-existence (dashboard-sharing, conditional-visibility and embedded-analytics anchors), schema-property-titles, orphaned-write-capability (`CspService`), icon-vocabulary (`src/icons.js`), walkthrough-flows-stop. + +## Verification + +`openspec validate` exits clean. Widget with calculated field saves and displays correctly on the dashboard. Parse/type/cycle errors are caught at save time and shown to the user with clear messages. Client-side evaluator re-computes on filter change without round-trip. Server-mode field materialises to OpenRegister and is queryable. TypeScript and PHP evaluators produce identical results. + +## Tests + +- Vitest: parser, type-checker, cycle detector, evaluator (TypeScript), shared test suite +- PHPUnit: validation, evaluator (PHP), server-side integration, cross-widget refs +- Playwright: render, error display, cross-widget reactivity, filter changes + +## Documentation + +- Changelog: feature overview, dual-evaluation strategy, allowlist, error handling +- Design.md: decisions, rationale, migration plan, seed data +- i18n: error messages, user-facing strings +- OpenAPI: schema extension, error envelopes diff --git a/openspec/changes/archive/2026-11-23-app-tile-widget/proposal.md b/openspec/changes/archive/2026-11-23-app-tile-widget/proposal.md new file mode 100644 index 000000000..630975fcf --- /dev/null +++ b/openspec/changes/archive/2026-11-23-app-tile-widget/proposal.md @@ -0,0 +1,24 @@ +# Proposal: app-tile-widget + +## Why + +Ruben reviewed the start page on 22 November 2026. Every app should be its own tile on the grid, like a workspace +start page: a square in a solid colour with the app's icon large and white in the middle. Today the add flow places a +discovered app as a plain tile with a copied title, icon and link, and the first dashboard gets one Apps widget that +holds all apps in one card. + +## What changes + +- The `app-tile` widget type from nextcloud-vue (`CnAppTileWidget`) is offered and rendered. It is configured with one + app id and reads the app's name, icon and address from the viewer's own app menu, so an app the viewer may not open + never shows as a link. +- The add flow's "Discovered on this server" section becomes "App tiles" (board LpWidgetKiezen): one entry per app, + drawn in its tile colour, placing an `app-tile`, plus "Custom tile" for a tile of one's own. +- An app tile renders without the card frame or header and starts at two columns by two rows. Each tile is its own placement; a heading above tiles is its own label placement. +- The first-run starter set places an app tile for each of up to four most-used apps in the person's app menu, + instead of the one Apps widget. Without a known app menu it keeps the Apps widget. +- The `app-tiles` widget keeps working for existing dashboards and stays in the picker under "Widgets from Launchpad". + +## Out of scope + +- The visual design of the tile itself lives in nextcloud-vue (`openspec/changes/app-tile`). diff --git a/openspec/changes/archive/2026-11-23-app-tile-widget/specs/app-tile-widget/spec.md b/openspec/changes/archive/2026-11-23-app-tile-widget/specs/app-tile-widget/spec.md new file mode 100644 index 000000000..3aa844a4b --- /dev/null +++ b/openspec/changes/archive/2026-11-23-app-tile-widget/specs/app-tile-widget/spec.md @@ -0,0 +1,54 @@ +--- +capability: app-tile-widget +status: draft +--- + +# App tile widget + +## Purpose + +Every app the person can open is its own square, coloured tile on the dashboard. + +## ADDED Requirements + +### Requirement: The add flow offers every app as its own tile (REQ-APPTILE-001) + +The add flow's "App tiles" section (board LpWidgetKiezen, "App-tegels") SHALL list one entry per app in the user's +app menu, each drawn in the colour its tile gets, followed by "Custom tile", which opens the tile form. Picking an +app SHALL place an `app-tile` widget with `content: { appId, colour: '', showCount: true }`. An app that has an +`app-tile` on the dashboard SHALL be marked "On this dashboard". + +#### Scenario: Files in the picker + +- **GIVEN** a user whose app menu holds Files +- **WHEN** they open the add flow and pick Files under "App tiles" +- **THEN** an `app-tile` widget for `files` is stored +- **AND** the dashboard shows a square link named "Files" to `/apps/files/` with no visible text +- **AND** the next time the add flow opens, Files is marked "On this dashboard" + +### Requirement: An app tile shows one app the viewer may open (REQ-APPTILE-002) + +An `app-tile` placement SHALL render through nextcloud-vue's `CnAppTileWidget`, without the card frame or header. Its +name, icon and address SHALL come from the viewer's own app menu, so an app the viewer may not open never renders as +a link. A new app tile SHALL start as one cell of two columns by two rows and SHALL have no card, title or padding around it; the coloured tile is the widget, placed, moved and resized on its own. Headings above tiles are separate label placements with `groupHeading: true`. + +#### Scenario: A shared dashboard with an app the viewer may not open + +- **GIVEN** a group dashboard with an app tile for Deck +- **AND** a group member for whom Deck is not enabled +- **WHEN** the member opens the dashboard +- **THEN** the cell says the app is not available and holds no link to Deck + +### Requirement: A first dashboard starts with a tile per most-used app (REQ-APPTILE-003) + +The first-run starter set (`widgets: 'starters'`) SHALL open with one `app-tile` for each of the first four apps in the +person's app menu, taking Files, Mail, Calendar, Talk, Contacts, Deck, Tasks and Notes first in that order. The other +starter widgets SHALL follow unchanged. LaunchPad itself SHALL never get a tile. When the app menu is unknown, the set +SHALL open with the `app-tiles` widget instead. The `app-tiles` widget SHALL keep rendering on existing dashboards. + +#### Scenario: A first dashboard for a person with Files and Mail + +- **GIVEN** a person whose app menu holds Deck, Calendar, Files, Photos and Talk +- **WHEN** they create their first dashboard with the starter widgets +- **THEN** the dashboard holds app tiles for Files, Calendar, Talk and Deck on the top row, then the calendar, mail, + files, weather and news widgets diff --git a/openspec/changes/archive/2026-11-23-app-tile-widget/tasks.md b/openspec/changes/archive/2026-11-23-app-tile-widget/tasks.md new file mode 100644 index 000000000..c843a6294 --- /dev/null +++ b/openspec/changes/archive/2026-11-23-app-tile-widget/tasks.md @@ -0,0 +1,9 @@ +# Tasks: app-tile-widget + +- [x] Register `app-tile` in `lib/widget-types.json` and the vitest nextcloud-vue stub +- [x] Place a discovered app as an `app-tile` and count `app-tile` placements as "On this dashboard" +- [x] Render `app-tile` without card chrome, at two by two cells by default +- [x] Seed an app tile per most-used app in the first-run starter set, from the user's app menu +- [x] Unit tests (PHP seeds, picker helpers) +- [x] Playwright: discovered app placed as a tile, starter set with app tiles +- [x] Bump `@conduction/nextcloud-vue` to the release with `CnAppTileWidget` diff --git a/openspec/changes/archive/2026-11-23-assigned-cases-widget/proposal.md b/openspec/changes/archive/2026-11-23-assigned-cases-widget/proposal.md new file mode 100644 index 000000000..ce773b026 --- /dev/null +++ b/openspec/changes/archive/2026-11-23-assigned-cases-widget/proposal.md @@ -0,0 +1,27 @@ +# Proposal: assigned-cases-widget + +## Why + +Board LpWerkplek (design-system #1192) shows "Mijn zaken": the counts per status of the person's open cases and the +first four cases with deadline and status. Board LpAfdeling repeats it on the department page. + +## What changes + +- An `assigned-cases` widget type, "My cases" in the picker. It reads the open cases assigned to the viewer from an + OpenRegister register with the viewer's own session (`GET /apps/openregister/api/objects/{register}/{schema}` with + `assignee=<uid>`, `_order[deadline]=asc`, `_extend[]=status`), so OpenRegister decides which cases they may see. + The register and schema default to dossiq's `dossiq` and `case`; the form names them. +- Counts per status above the cases, over the first 100 open cases read; the cases through `CnStatusList` with the case + number, deadline (overdue once passed) and status in the colour of its status type. +- Each case links into dossiq at `/apps/<id>/cases/<uuid>`, where `<id>` is the id dossiq is installed under. The + initial state's `integrationApps.dossiq` carries that id, resolved through `FleetAppId`, so launchpad never names one + spelling of dossiq's id. +- A widget that reads through an app not enabled for the viewer is left out of the grid outside edit mode, and out of + the picker. This applies to every type with `requiresApp`. + +## Decisions + +- The widget is generic: it shows "cases assigned to me" from any register whose objects carry `assignee`, + `deadline`, `status` and `isFinalStatus`. Nothing in it is named after a procedure. +- Counts come from the cases read, not from OpenRegister facets, because a facet needs the schema's facet + configuration and the counts of a person's own open cases fit in one read. diff --git a/openspec/changes/archive/2026-11-23-assigned-cases-widget/specs/assigned-cases-widget/spec.md b/openspec/changes/archive/2026-11-23-assigned-cases-widget/specs/assigned-cases-widget/spec.md new file mode 100644 index 000000000..a74b24b54 --- /dev/null +++ b/openspec/changes/archive/2026-11-23-assigned-cases-widget/specs/assigned-cases-widget/spec.md @@ -0,0 +1,58 @@ +--- +capability: assigned-cases-widget +status: draft +--- + +# Assigned cases widget + +## Purpose + +The open cases assigned to the person viewing, with counts per status, on a dashboard. + +## ADDED Requirements + +### Requirement: The widget lists the viewer's open cases, deadline first (REQ-CASES-001) + +The `assigned-cases` widget SHALL read the cases assigned to the viewer from the configured OpenRegister register and +schema with the viewer's own session, leave out cases with a final status, and list the first `limit` (default 4), +deadline first. Each case SHALL show its title as a link into the case app, its case number, its deadline (overdue +once passed) and its status in the colour of its status type. When there are more open cases than shown, a link SHALL +lead to the case list. + +#### Scenario: Pieter's cases + +- **GIVEN** Pieter has open cases "Kapvergunning Molenweg 4" (In behandeling, deadline today) and "Dakkapel + Kerkstraat 12" (Wacht op aanvrager, 21 October) +- **WHEN** he opens a dashboard with "My cases" +- **THEN** both show, the one due today first, each with case number, deadline and status + +### Requirement: The widget counts the open cases per status (REQ-CASES-002) + +Above the cases the widget SHALL show one count per status over the viewer's open cases. + +#### Scenario: Counts + +- **GIVEN** Pieter has 6 open cases "In behandeling" and 5 "Wacht op aanvrager" +- **THEN** the widget shows "In behandeling 6" and "Wacht op aanvrager 5" + +### Requirement: The widget names its data source (REQ-CASES-003) + +The form SHALL name the register and the schema the widget reads, by default dossiq's `dossiq` and `case`, and the +number of cases, 1 to 20. + +#### Scenario: Default source + +- **WHEN** an author adds "My cases" +- **THEN** the form shows register `dossiq` and schema `case` + +### Requirement: The widget is offered only with dossiq (REQ-CASES-004) + +Launchpad SHALL find dossiq under every id it has had and never by one spelling. The picker SHALL offer "My cases" only +when dossiq is enabled for the viewer. Outside edit mode a placed widget, and every other widget whose app is not +enabled for the viewer, SHALL be left out of the grid. Links SHALL use the id dossiq is installed under. + +#### Scenario: No dossiq + +- **GIVEN** an instance without dossiq +- **WHEN** a person opens a dashboard holding "My cases" +- **THEN** the widget is not shown, and the picker does not offer "My cases" diff --git a/openspec/changes/archive/2026-11-23-assigned-cases-widget/tasks.md b/openspec/changes/archive/2026-11-23-assigned-cases-widget/tasks.md new file mode 100644 index 000000000..d7e361524 --- /dev/null +++ b/openspec/changes/archive/2026-11-23-assigned-cases-widget/tasks.md @@ -0,0 +1,8 @@ +# Tasks: assigned-cases-widget + +- [x] `services/assignedCases.js`: the viewer's open cases and counts per status from OpenRegister +- [x] `AssignedCasesWidget` and `AssignedCasesWidgetForm`, registered as `assigned-cases` with `requiresApp: 'dossiq'` +- [x] `integrationApps.dossiq` as the installed id through `FleetAppId` +- [x] Leave widgets whose app is not enabled for the viewer out of the grid outside edit mode +- [x] Unit tests (client, widget, form, PageController) +- [x] Playwright: the viewer's cases with counts, deadline and status diff --git a/openspec/changes/archive/2026-11-23-chart-presets/proposal.md b/openspec/changes/archive/2026-11-23-chart-presets/proposal.md new file mode 100644 index 000000000..7bc2b86ac --- /dev/null +++ b/openspec/changes/archive/2026-11-23-chart-presets/proposal.md @@ -0,0 +1,26 @@ +# Proposal: chart-presets + +## Why + +Board LpManagement (design-system #1192) shows two charts: "Cirkeldiagram" (a donut with a legend and the total in the +centre) and "Grafiek" (bars for applications, a line for decisions, with axes and a legend). Both read a register +query, or values an author enters. + +## What changes + +Launchpad already has the chart stack: the `chart` type renders through `ChartHost` over nextcloud-vue's +`CnChartWidget`, which draws donut, bar and line charts from an OpenRegister query. So no second chart stack is built. + +- Two types on that stack, `pie-chart` ("Pie chart") and `graph` ("Graph"), each with its own preset. +- `ChartSourceForm`, the form of both types: the data source is "A register query" (the shared `CnChartWidgetForm`) or "Values you enter": + label, value and colour per slice for a pie chart; axis labels and named series, each drawn as bars or a line, for a + graph. +- `ChartHost` passes `legendValues`, `legendPosition` and `colorMap` to `CnChartWidget`, writes the donut total in the + centre when `showTotal` is set, draws entered bars and lines as one mixed chart, and reads no register for entered + values. + +## Limits + +- The legend shows each slice's value; `CnChartWidget` has no percentage in the legend, and its tooltip shows the share. +- A register-query graph draws one series per interval. Bars and a line from two register fields in one graph need a + second data source in `CnChartWidget`; entered values can mix them now. diff --git a/openspec/changes/archive/2026-11-23-chart-presets/specs/chart-presets/spec.md b/openspec/changes/archive/2026-11-23-chart-presets/specs/chart-presets/spec.md new file mode 100644 index 000000000..0f10c1e5b --- /dev/null +++ b/openspec/changes/archive/2026-11-23-chart-presets/specs/chart-presets/spec.md @@ -0,0 +1,43 @@ +--- +capability: chart-presets +status: draft +--- + +# Chart presets + +## Purpose + +A pie chart and a graph an author can pick and fill without knowing chart types. + +## ADDED Requirements + +### Requirement: A pie chart is a donut with its total in the centre (REQ-CHARTP-001) + +The `pie-chart` widget SHALL draw a donut with a legend that writes each slice's value, and the total of the slices +in the centre. + +#### Scenario: Cases per status + +- **GIVEN** a pie chart with In behandeling 138, Wacht op aanvrager 74, Wacht op advies 46 and Afgerond 54 +- **THEN** the donut shows four slices, the legend names each with its value, and the centre says Total 312 + +### Requirement: A graph draws bars and lines (REQ-CHARTP-002) + +The `graph` widget SHALL draw bars over time from a register query, and from entered values any number of named +series, each as bars or a line, in one chart with axes and a legend. + +#### Scenario: Applications and decisions per month + +- **GIVEN** a graph with axis labels April to September, a series "Aanvragen" as bars and "Besluiten" as a line +- **THEN** one chart shows the bars and the line over the six months, with a legend naming both + +### Requirement: A chart reads a register query or entered values (REQ-CHARTP-003) + +Both forms SHALL offer "A register query", edited by the shared chart form, and "Values you enter". Entered values +SHALL be saved in the placement and SHALL NOT make the chart read a register. A form SHALL not save without a +register query, or without at least one labelled value (pie chart) or axis labels and one named series (graph). + +#### Scenario: Entered values + +- **WHEN** an author picks "Pie chart", chooses "Values you enter" and enters two labelled values +- **THEN** the chart shows those two slices and reads no register diff --git a/openspec/changes/archive/2026-11-23-chart-presets/tasks.md b/openspec/changes/archive/2026-11-23-chart-presets/tasks.md new file mode 100644 index 000000000..110c1a56c --- /dev/null +++ b/openspec/changes/archive/2026-11-23-chart-presets/tasks.md @@ -0,0 +1,7 @@ +# Tasks: chart-presets + +- [x] `pie-chart` and `graph` types on `ChartHost`, with presets +- [x] `ChartSourceForm` with a register query or entered values, the one form of both types +- [x] `ChartHost`: legend settings, donut total, mixed bars and line, no register for entered values +- [x] Unit tests +- [x] Playwright: a pie chart and a graph from entered values diff --git a/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/proposal.md b/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/proposal.md new file mode 100644 index 000000000..6966bd4c8 --- /dev/null +++ b/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/proposal.md @@ -0,0 +1,12 @@ +# Proposal: no-buildiq-edit-control + +## Why + +The boards of design-system #1192 (DEMO-SEED, "Rules that every board follows") hold only launchpad's own actions in +the page header: Edit (or Customise start page), Add widget where the role allows it, and More. Where Buildiq is +enabled, `CnAppRoot` adds Buildiq's in-app edit button to every page's action row, so launchpad's pages showed a +control the boards do not draw. Launchpad dashboards are edited in launchpad. + +## What changes + +- `src/manifest.json` sets `openbuildEditable: false`, the manifest's opt-out of the Buildiq edit button. diff --git a/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/specs/runtime-shell/spec.md b/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/specs/runtime-shell/spec.md new file mode 100644 index 000000000..62104e44e --- /dev/null +++ b/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/specs/runtime-shell/spec.md @@ -0,0 +1,14 @@ +# runtime-shell Delta + +## ADDED Requirements + +### Requirement: The page header holds only launchpad's own actions (REQ-SHELL-NOBQ) + +Launchpad's pages SHALL NOT show the Buildiq in-app edit button, also where Buildiq is enabled. The manifest SHALL set +`openbuildEditable: false`. + +#### Scenario: Buildiq is enabled + +- **GIVEN** an instance with Buildiq enabled +- **WHEN** a person opens a launchpad dashboard +- **THEN** the page header shows no Buildiq edit button diff --git a/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/tasks.md b/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/tasks.md new file mode 100644 index 000000000..6ad0a6f7f --- /dev/null +++ b/openspec/changes/archive/2026-11-23-no-buildiq-edit-control/tasks.md @@ -0,0 +1,5 @@ +# Tasks: no-buildiq-edit-control + +- [x] Set `openbuildEditable: false` in the manifest +- [x] Unit test on the manifest +- [x] Playwright check that the page header has no Buildiq edit button diff --git a/openspec/changes/archive/2026-11-23-wiki-widget/proposal.md b/openspec/changes/archive/2026-11-23-wiki-widget/proposal.md new file mode 100644 index 000000000..b1f2e678e --- /dev/null +++ b/openspec/changes/archive/2026-11-23-wiki-widget/proposal.md @@ -0,0 +1,25 @@ +# Proposal: wiki-widget + +## Why + +Board LpWerkplek (design-system #1192) puts a Wiki widget on a person's workplace: a search field, three favourite +pages and three recent pages from the organisation's XWiki. Board LpAfdeling puts a team wiki on the department page, +showing one space. Launchpad has no widget that reads the wiki. + +## What changes + +- A `wiki-pages` widget type, "Wiki" in the picker. It reads through OpenRegister's XWiki integration + (`GET /apps/openregister/api/integrations/xwiki/search`). OpenRegister routes the call to the `xwiki` source of the + connector app, which holds the wiki's address and credentials, so the browser never sees them. +- The person stars pages; their favourites live in their launchpad preference `wiki-favourites`. +- `content: { space, limit }`: one wiki space or all, and how many favourites and recent pages show. +- When OpenRegister answers 503 (no `xwiki` source, or the wiki is down) the widget says the wiki is not connected. + Without OpenRegister it says OpenRegister is needed, and the picker does not offer the widget. +- A generic `integrationApps` initial-state key tells the picker which apps behind integration widgets are enabled for + the viewer. A registry entry names its app with `requiresApp`. + +## Decisions + +- XWiki has no favourites of its own that the integration exposes, so favourites are the person's own, kept by + launchpad. They follow the person across dashboards. +- "Recent" is what the integration lists for an empty query: the most recent pages the source returns. diff --git a/openspec/changes/archive/2026-11-23-wiki-widget/specs/wiki-widget/spec.md b/openspec/changes/archive/2026-11-23-wiki-widget/specs/wiki-widget/spec.md new file mode 100644 index 000000000..f8a803f34 --- /dev/null +++ b/openspec/changes/archive/2026-11-23-wiki-widget/specs/wiki-widget/spec.md @@ -0,0 +1,67 @@ +--- +capability: wiki-widget +status: draft +--- + +# Wiki widget + +## Purpose + +The organisation's wiki on a dashboard: search, the person's favourite pages and the recent pages. + +## ADDED Requirements + +### Requirement: The wiki widget shows favourites, recent pages and search (REQ-WIKI-001) + +The `wiki-pages` widget SHALL read pages through OpenRegister's XWiki integration, never with credentials in the +browser. It SHALL show a search field, the person's favourites and the recent pages, at most `limit` each (default +3). Each page SHALL be a link into the wiki that opens in a new tab, with its space as detail. A page address that is +not http(s) SHALL NOT become a link. Typing SHALL search the wiki once typing pauses; a cleared search SHALL show the +favourites and recent pages again. When OpenRegister answers that no XWiki source is set up, the widget SHALL say the +wiki is not connected and ask the person to contact their administrator. + +#### Scenario: Pieter's wiki + +- **GIVEN** the wiki holds "Werkinstructie kapvergunningen", "Termijnen Omgevingswet" and "Legesverordening 2026" +- **WHEN** Pieter opens a dashboard with the Wiki widget +- **THEN** he sees his favourites and the recent pages as links into the wiki +- **AND** searching "leges" shows "Legesverordening 2026" + +#### Scenario: The wiki is not connected + +- **GIVEN** no `xwiki` source is set up in the connector app +- **WHEN** a person opens a dashboard with the Wiki widget +- **THEN** the widget says "The wiki is not connected yet. Ask your administrator to connect XWiki." + +### Requirement: A person keeps favourite pages (REQ-WIKI-002) + +A star on every page SHALL add it to or remove it from the person's favourites. A new favourite SHALL come first. The +favourites SHALL be kept in the person's launchpad preference `wiki-favourites`, at most 20, so they follow the person +across dashboards and devices. When saving fails, the favourites SHALL stay as they were. + +#### Scenario: Starring a page + +- **WHEN** Pieter stars "Termijnen Omgevingswet" and reloads the page +- **THEN** "Termijnen Omgevingswet" is the first of his favourites + +### Requirement: A team wiki shows one space (REQ-WIKI-003) + +With `space` set, the widget SHALL show only the pages of that space, in favourites, recent pages and search results. +The form SHALL offer the space and the number of pages per list, 1 to 20. + +#### Scenario: Wiki of the team + +- **GIVEN** a Wiki widget with space "Vergunningen" on the department page +- **THEN** only pages of the space "Vergunningen" show + +### Requirement: The picker offers the wiki only where it can work (REQ-WIKI-004) + +The picker SHALL offer the Wiki widget only when OpenRegister is enabled for the viewer, as the initial state's +`integrationApps` says. Outside edit mode a placed Wiki widget SHALL be left out for a viewer without OpenRegister; in +edit mode it SHALL render and explain that OpenRegister is needed. + +#### Scenario: No OpenRegister + +- **GIVEN** an instance where OpenRegister is disabled for the person +- **WHEN** they open the widget picker +- **THEN** "Wiki" is not offered diff --git a/openspec/changes/archive/2026-11-23-wiki-widget/tasks.md b/openspec/changes/archive/2026-11-23-wiki-widget/tasks.md new file mode 100644 index 000000000..f5aa8e9e4 --- /dev/null +++ b/openspec/changes/archive/2026-11-23-wiki-widget/tasks.md @@ -0,0 +1,7 @@ +# Tasks: wiki-widget + +- [x] `services/wikiPages.js`: search through OpenRegister, favourites in the preference store +- [x] `WikiPagesWidget` and `WikiPagesWidgetForm`, registered as `wiki-pages` with `requiresApp: 'openregister'` +- [x] `integrationApps` initial state and the picker filter +- [x] Unit tests (service, widget, form, registry filter, PageController) +- [x] Playwright: the widget with pages, favourites kept across a reload, the not-connected state diff --git a/openspec/changes/archive/2026-11-23-work-packages-widget/proposal.md b/openspec/changes/archive/2026-11-23-work-packages-widget/proposal.md new file mode 100644 index 000000000..1a35c7f05 --- /dev/null +++ b/openspec/changes/archive/2026-11-23-work-packages-widget/proposal.md @@ -0,0 +1,30 @@ +# Proposal: work-packages-widget + +## Why + +Board LpWerkplek (design-system #1192) shows "Mijn werkpakketten": a person's open OpenProject work packages with a +status chip and a due date. Board LpAfdeling shows "Werkpakketten van het team": every open work package of one +project. Launchpad has no widget for OpenProject. + +## Decision: a native widget over the official integration + +The official Nextcloud app `integration_openproject` registers one Nextcloud dashboard widget, +`openproject_notifications`. It lists the person's unread OpenProject notifications, not their work packages, has no +due dates or statuses, and implements only `IWidget` (no item API), so launchpad's `nc-widget` support can only embed +it as is. Its HTTP API has no "assigned to me, due soon" query either: `GET /api/v1/work-packages` searches by text or +linked file. + +So launchpad builds the widget itself, but reads through the integration: launchpad's backend asks the integration's +`OpenProjectAPIService::request()` for `work_packages` with the person's id. The integration holds the OpenProject +address and each person's own OAuth or OIDC token, refreshes it, and makes the call. Launchpad never sees a credential, +and OpenProject decides what each person may see. The service is looked up at runtime, so launchpad works without the +app. + +## What changes + +- `GET /apps/launchpad/api/work-packages?scope=mine|project&project=<identifier>&limit=n`, answering + `{ state, workPackages, connectUrl? }` with `state` `ok`, `not-installed`, `not-connected` or `error`. +- A `work-packages` widget type, "My work packages" in the picker, offered only where `integration_openproject` is + enabled for the viewer. It shows the work packages through `CnStatusList`: subject as a link into OpenProject, + project, due date (overdue once passed) and status. +- A person who has not connected their OpenProject account gets a link to the integration's personal settings. diff --git a/openspec/changes/archive/2026-11-23-work-packages-widget/specs/work-packages-widget/spec.md b/openspec/changes/archive/2026-11-23-work-packages-widget/specs/work-packages-widget/spec.md new file mode 100644 index 000000000..1bb97b85e --- /dev/null +++ b/openspec/changes/archive/2026-11-23-work-packages-widget/specs/work-packages-widget/spec.md @@ -0,0 +1,59 @@ +--- +capability: work-packages-widget +status: draft +--- + +# Work packages widget + +## Purpose + +A person's open OpenProject work packages, or one project's, on a dashboard. + +## ADDED Requirements + +### Requirement: The widget lists open work packages, due date first (REQ-WP-001) + +The `work-packages` widget SHALL list the open work packages assigned to the viewer, sorted by due date, at most +`limit` (default 4, at most 25). Launchpad's backend SHALL read them through the official OpenProject integration with +the viewer's own token; no credential SHALL reach the browser or launchpad. Each work package SHALL show its subject as +a link into OpenProject that opens in a new tab, its project, its due date (overdue once passed) and its status. + +#### Scenario: Pieter's work packages + +- **GIVEN** Pieter has open work packages "Welstandsadvies verwerken" (In uitvoering, due today) and "Raming + herinrichting Stadshaven" (Wacht op reactie, due Friday) +- **WHEN** he opens a dashboard with "My work packages" +- **THEN** both show, the one due today first, each with its status and due date + +### Requirement: A person without a connected account is asked to connect (REQ-WP-002) + +When the viewer has not connected their OpenProject account, or OpenProject refuses their token, the widget SHALL say so +and link to the integration's personal settings. Without the integration it SHALL say the integration is needed. When +OpenProject fails otherwise it SHALL say the work packages could not be loaded. + +#### Scenario: Not connected + +- **GIVEN** a person who never connected their OpenProject account +- **WHEN** they open a dashboard with "My work packages" +- **THEN** the widget says "Connect your OpenProject account to see your work packages." with a link to connect + +### Requirement: A team page lists one project's work packages (REQ-WP-003) + +With `scope: 'project'` and a project identifier, the widget SHALL list every open work package of that project, with +the assignee next to the project. The form SHALL require the project for that scope and allow 1 to 25 work packages. + +#### Scenario: Work packages of the team + +- **GIVEN** a widget with scope project and project "havenpark" on the department page +- **THEN** the open work packages of Havenpark show for every assignee, each with its assignee + +### Requirement: The picker offers the widget only with the integration (REQ-WP-004) + +The picker SHALL offer "My work packages" only when `integration_openproject` is enabled for the viewer. Outside edit +mode a placed widget SHALL be left out for a viewer without the integration. + +#### Scenario: No integration + +- **GIVEN** an instance without `integration_openproject` +- **WHEN** a person opens the widget picker +- **THEN** "My work packages" is not offered diff --git a/openspec/changes/archive/2026-11-23-work-packages-widget/tasks.md b/openspec/changes/archive/2026-11-23-work-packages-widget/tasks.md new file mode 100644 index 000000000..bfa6e31aa --- /dev/null +++ b/openspec/changes/archive/2026-11-23-work-packages-widget/tasks.md @@ -0,0 +1,8 @@ +# Tasks: work-packages-widget + +- [x] `WorkPackagesService` over `OCA\OpenProject\Service\OpenProjectAPIService`, looked up at runtime +- [x] `WorkPackagesController` and the `/api/work-packages` route +- [x] `WorkPackagesWidget` and `WorkPackagesWidgetForm`, registered as `work-packages` with `requiresApp: 'integration_openproject'` +- [x] `integrationApps.integration_openproject` in the initial state +- [x] Unit tests (service, controller, widget, form, client) +- [x] Playwright: the widget with work packages, the not-connected state, the project list diff --git a/openspec/changes/archive/2026-11-24-admin-full-width-page/proposal.md b/openspec/changes/archive/2026-11-24-admin-full-width-page/proposal.md new file mode 100644 index 000000000..f2e856f90 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-admin-full-width-page/proposal.md @@ -0,0 +1,13 @@ +# Proposal: admin-full-width-page + +## Why + +The LpBeheer boards (Algemeen, Sjablonen, Rollen, Delen, Onderhoud, Analyse, Navigatie) draw Launchpad's administration as a page of its own over the full width: the Launchpad top bar, the title "Launchpad-beheer: <tab>", a path line, tabs over the full width and no left menu. runtime-shell REQ-SHELL-012 forbids a left panel inside Launchpad, but the administration lives at `/settings/admin/launchpad`, which Nextcloud's settings framework renders inside its own settings menu, so every LpBeheer board measures with a 264 px menu the board does not have. + +## What changes + +- `admin-settings`: the administration as a Launchpad page at `/apps/launchpad/admin/<tab>` without Nextcloud's settings menu (REQ-ADM-030); the Nextcloud settings entry links to it (REQ-ADM-031). + +## Impact + +- `appinfo/routes.php` and a page controller for the admin page (admin-only, server-side check), `src/admin.js` mounted in the Launchpad shell, `lib/Settings/LaunchPadAdmin.php` reduced to a link, `AdminSettingsRedirect.vue`. diff --git a/openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md b/openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md new file mode 100644 index 000000000..7c1423cab --- /dev/null +++ b/openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md @@ -0,0 +1,27 @@ +# Delta: admin-settings + +## ADDED Requirements + +### Requirement: The administration is a Launchpad page over the full width (REQ-ADM-030) + +The Launchpad administration SHALL be a page of Launchpad itself at `/apps/launchpad/admin/<tab>`, with Launchpad's top bar, the title "Launchpad administration: <tab>", the path "Administration settings / Launchpad / <tab>", the tabs over the full width and no left menu. The page SHALL check on the server, before it renders, that the reader is an administrator or a delegated Launchpad administrator. + +#### Scenario: Open the administration + +- **GIVEN** beheer is a Launchpad administrator +- **WHEN** she chooses Settings, Administration settings in the More menu +- **THEN** the page opens without Nextcloud's settings menu, on the tab General + +#### Scenario: Not an administrator + +- **WHEN** Pieter opens `/apps/launchpad/admin/general` +- **THEN** the server answers 403 and renders nothing of the page + +### Requirement: Nextcloud's settings point to the page (REQ-ADM-031) + +The Launchpad entry under Nextcloud's administration settings SHALL say where the administration is and link to the page. + +#### Scenario: From Nextcloud's settings + +- **WHEN** an administrator opens Administration settings, Launchpad in Nextcloud +- **THEN** she sees one line and a link that opens the Launchpad administration page diff --git a/openspec/changes/archive/2026-11-24-admin-full-width-page/tasks.md b/openspec/changes/archive/2026-11-24-admin-full-width-page/tasks.md new file mode 100644 index 000000000..4dbac836b --- /dev/null +++ b/openspec/changes/archive/2026-11-24-admin-full-width-page/tasks.md @@ -0,0 +1,8 @@ +# Tasks: admin-full-width-page + +- [x] Admin page route `/apps/launchpad/admin/{tab}` checked server-side for administrators (and delegated admins) +- [x] Mount the admin component in the Launchpad shell: top bar, no settings menu, tabs over the full width +- [x] Nextcloud's admin settings entry for Launchpad shows a short text and a link to the page +- [x] Deep links to a tab keep working from the More menu +- [x] Unit tests: non-admin gets 403 before rendering; tab from the route +- [x] Playwright: beheer opens Administration settings from More and sees no left menu (written, runs in nightly: tests/e2e/admin-full-width-page.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-allowed-websites-list/proposal.md b/openspec/changes/archive/2026-11-24-allowed-websites-list/proposal.md new file mode 100644 index 000000000..511588139 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-allowed-websites-list/proposal.md @@ -0,0 +1,25 @@ +# Proposal: allowed-websites-list + +## Why + +Board LpBeheerAlgemeen draws one block "Toegestane websites": "Widgets mogen alleen pagina's insluiten en gegevens +ophalen van deze sites", a list of hosts each marked "Insluiten", "Ophalen" or "Insluiten en ophalen" +(www.zuiddrecht.nl both, app.powerbi.com embed, kcc-api.zuiddrecht.nl fetch, www.youtube-nocookie.com embed), "Website +toevoegen" and Opslaan. + +On development each feature keeps its own fail-closed allow-list in app config: the embed widget's hosts +(REQ-IFRAME-002), image hosts (REQ-IMG-006), `livetile_allowed_hosts` (live-data-tile-widget), +`healthping_allowed_hosts` (service-health-ping) and `calendar_widget_allowed_ics_hosts` (REQ-CAL-006). An +administrator has no one place that says which outside sites launchpad may embed or call, and parity row g-allowlists +is rated partial for that reason. + +## What changes + +- `admin-settings`: one list of allowed websites with a purpose per host, embed, fetch or both (REQ-ASET-021). Embed + feeds the embed and image allow-lists; fetch feeds the live tile, health ping and calendar feed allow-lists. The + checks themselves stay where they are and stay fail-closed. + +## Impact + +- An admin setting and its block on the General tab, a migration that merges the existing per-feature lists into it, + the services that read their allow-list (they read the derived list), translations. diff --git a/openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md b/openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md new file mode 100644 index 000000000..063c145fb --- /dev/null +++ b/openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md @@ -0,0 +1,35 @@ +# Delta: admin-settings + +## ADDED Requirements + +### Requirement: One list of allowed websites with a purpose per site (REQ-ASET-021) + +The General tab (board LpBeheerAlgemeen) SHALL hold one block "Allowed websites" ("Toegestane websites"): a list of +hosts, each with its purpose: Embed ("Insluiten"), Fetch ("Ophalen") or Embed and fetch, with "Add website" and Save. +The list SHALL be stored as one admin setting. Embed SHALL allow the host for the embedded page widget and for images +from outside; Fetch SHALL allow it for live tiles, health pings and external calendar feeds. Each of those features +SHALL check a URL against the hosts allowed for its purpose and SHALL stay fail-closed: a host not on the list, or +on it for the other purpose only, SHALL be refused as before. A host SHALL be saved lower case, without scheme, path +or port, and an entry that is not a host SHALL be refused with a message. On the first upgrade, the hosts of the +existing per-feature allow-lists SHALL be merged into the list with the purpose they had, so nothing that worked +stops working. + +#### Scenario: Power BI may be embedded, not called + +- **GIVEN** the list holds `app.powerbi.com` with purpose Embed +- **WHEN** an author places an embedded page from `https://app.powerbi.com/...` +- **THEN** the widget saves and renders +- **AND** a live tile with a URL on `app.powerbi.com` is refused at save time + +#### Scenario: The KCC API may be called, not embedded + +- **GIVEN** the list holds `kcc-api.zuiddrecht.nl` with purpose Fetch +- **WHEN** an author configures a live tile on `https://kcc-api.zuiddrecht.nl/wachttijd` +- **THEN** the tile fetches its value +- **AND** an embedded page on that host is refused + +#### Scenario: Existing lists survive the upgrade + +- **GIVEN** before the upgrade `livetile_allowed_hosts` held `kcc-api.zuiddrecht.nl` and the embed list held `app.powerbi.com` +- **WHEN** the app is upgraded +- **THEN** the Allowed websites block lists `kcc-api.zuiddrecht.nl` with Fetch and `app.powerbi.com` with Embed diff --git a/openspec/changes/archive/2026-11-24-allowed-websites-list/tasks.md b/openspec/changes/archive/2026-11-24-allowed-websites-list/tasks.md new file mode 100644 index 000000000..fee6777a1 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-allowed-websites-list/tasks.md @@ -0,0 +1,9 @@ +# Tasks: allowed-websites-list + +- [x] Admin setting `allowed_sites` (`[{host, embed, fetch}]`) with host normalisation and validation; admin-only write +- [x] `AllowedSitesService::hostsFor('embed'|'fetch')`; the embed widget, image host, live tile, health ping and calendar feed checks read it, still fail-closed +- [x] Repair step: merge the existing per-feature lists into `allowed_sites` with their purpose, once +- [x] General tab block "Allowed websites": list, purpose select, Add website, Save +- [x] Translations in every shipped locale +- [x] Unit tests: purpose per feature (embed-only host refused for fetch and the other way), normalisation, invalid host, the merge on upgrade +- [x] Playwright: add a host with Fetch, configure a live tile on it, and see an embed on the same host refused (written, runs in nightly: tests/e2e/allowed-websites-list.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-announcement-form-board-sync/proposal.md b/openspec/changes/archive/2026-11-24-announcement-form-board-sync/proposal.md new file mode 100644 index 000000000..34bfa3a8b --- /dev/null +++ b/openspec/changes/archive/2026-11-24-announcement-form-board-sync/proposal.md @@ -0,0 +1,13 @@ +# Proposal: announcement-form-board-sync + +## Why + +Board LpAankondiging draws "Nieuwe aankondiging" as one dialog of two columns: the form (title, text, target group, the kind as two choice cards News and Maintenance notice, "Ask for read confirmation" with "Confirm before", "Allow comments and following", Publish on, Show until) and beside it "This is how it looks", a live preview with "I have read this" and Follow, and the note that only the author sees the preview. It ends with Cancel and Schedule. On development `AnnouncementEditorModal.vue` asks the fields one under the other, the kind in a select, and shows the preview as a second step after saving a draft. An announcement cannot ask for a read confirmation: that exists only for a widget placement (dashboard-acknowledgements). + +## What changes + +- `announcements`: the form as the board draws it, with a live preview beside it (REQ-ANN-006) and a read confirmation with a deadline on an announcement (REQ-ANN-007). + +## Impact + +- `src/modals/AnnouncementEditorModal.vue`, the announcement entity and API (confirmation fields), the read receipts report for announcements, translations. diff --git a/openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md b/openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md new file mode 100644 index 000000000..f70a624b8 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md @@ -0,0 +1,21 @@ +# Delta: announcements + +## ADDED Requirements + +### Requirement: The announcement form as LpAankondiging draws it (REQ-ANN-006) + +New announcement SHALL open one dialog with the form on the left and "This is how it looks" on the right: a live preview of the card that follows every field, and the note that only the author sees it until the publication time. The form SHALL ask Title, Text, Target group, the kind as two choice cards (News; Maintenance notice, shown at the top of every dashboard until the end time), the read confirmation, "Allow comments and following", Publish on (optional) and Show until. The dialog SHALL end with Cancel and Schedule (Publish when Publish on is empty or past). + +#### Scenario: Write a news item + +- **WHEN** Pieter types the title +- **THEN** the preview on the right shows it at once, without saving + +### Requirement: An announcement asks for a read confirmation (REQ-ANN-007) + +An author SHALL be able to ask the audience to confirm they have read an announcement, with a date to confirm before. The card SHALL then show "I have read this" to each reader in the audience, and the confirmations SHALL feed the read receipts report. + +#### Scenario: Confirm before Friday + +- **GIVEN** the announcement asks for confirmation before Friday 30 October +- **THEN** each reader sees "I have read this" and the preview says "Confirm before 30 October" diff --git a/openspec/changes/archive/2026-11-24-announcement-form-board-sync/tasks.md b/openspec/changes/archive/2026-11-24-announcement-form-board-sync/tasks.md new file mode 100644 index 000000000..e26101e8c --- /dev/null +++ b/openspec/changes/archive/2026-11-24-announcement-form-board-sync/tasks.md @@ -0,0 +1,8 @@ +# Tasks: announcement-form-board-sync + +- [x] Two-column form with the live preview beside it; kind as two choice cards; target group as a multi-select of groups +- [x] Ask for read confirmation and Confirm before on the announcement; I have read this on the card; receipts per announcement +- [x] Schedule or Publish as the one primary action +- [x] Translations in every shipped locale (the form's strings and the read confirmation's) +- [x] Unit tests: preview follows the fields, confirmation deadline after publish time +- [x] Playwright: write and schedule an announcement with a read confirmation (tests/e2e/announcement-read-confirmation.spec.ts: written, runs in nightly) diff --git a/openspec/changes/archive/2026-11-24-announcement-show-until/proposal.md b/openspec/changes/archive/2026-11-24-announcement-show-until/proposal.md new file mode 100644 index 000000000..38a82a88b --- /dev/null +++ b/openspec/changes/archive/2026-11-24-announcement-show-until/proposal.md @@ -0,0 +1,19 @@ +# Proposal: announcement-show-until + +## Why + +Board LpAankondiging draws the form "Nieuwe aankondiging" with "Publiceren op (niet verplicht)" and "Tonen tot +(verplicht)", explained as "Daarna verdwijnt het bericht vanzelf van elk dashboard", a preview line "zichtbaar tot 30 +oktober 17:00", and the button "Inplannen" when the publish time lies ahead. + +REQ-ANN-001 makes the end time optional, so an announcement without one stays on every targeted dashboard for good. + +## What changes + +- `announcements`: the end time ("Show until") is required for a new announcement and named in the preview; the + confirm button reads "Schedule" for a future publish time and "Publish" otherwise. Announcements stored without an + end time keep their behaviour. + +## Impact + +- The announcement form and the create and update endpoints, translations. diff --git a/openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md b/openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md new file mode 100644 index 000000000..3f3c4889a --- /dev/null +++ b/openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md @@ -0,0 +1,37 @@ +# Delta: announcements + +## MODIFIED Requirements + +### Requirement: Authors publish targeted announcements (REQ-ANN-001) + +Administrators and members of the announcement editor groups MUST be able to write an announcement with a title, text, optional category, target groups, an optional publish time and a required end time ("Show until", nl "Tonen tot", board LpAankondiging). The server MUST show a published announcement only to people in its target groups (everyone when none are set) between its publish time and its end time, and MUST show drafts only to authors and administrators. The server MUST refuse a new announcement without an end time, or with an end time before its publish time, with HTTP 400; an announcement stored before this rule without an end time MUST keep showing until an author sets one. The form MUST explain that the announcement disappears from every dashboard after its end time, MUST name the end time in its preview ("zichtbaar tot 30 oktober 17:00"), and its confirm button MUST read "Schedule" ("Inplannen") when the publish time lies in the future and "Publish" otherwise. + +#### Scenario: News for one group + +- **GIVEN** Karin is in the announcement editor group +- **WHEN** she publishes "Inloopspreekuur privacy" in category "Privacy" for group "Medewerkers", shown until Friday 17:00 +- **THEN** Pieter, a member of "Medewerkers", sees it in his Announcements widget +- **AND** Sanne, who is not a member, does not see it and gets 404 when she requests it by id + +#### Scenario: Reader cannot author + +- **GIVEN** Pieter is not an administrator and not in the editor group +- **WHEN** he sends `POST /api/announcements` +- **THEN** the response is 403 + +#### Scenario: An end time is required + +- **GIVEN** Karin writes an announcement without a "Show until" +- **WHEN** she sends `POST /api/announcements` +- **THEN** the response is 400 and names the missing end time + +#### Scenario: The announcement disappears after its end time + +- **GIVEN** an announcement shown until 30 October 17:00 +- **WHEN** Pieter opens his dashboard on 30 October at 17:01 +- **THEN** the announcement is not shown + +#### Scenario: Scheduling for later + +- **GIVEN** Karin sets the publish time to next Monday 08:00 +- **THEN** the confirm button reads "Schedule" diff --git a/openspec/changes/archive/2026-11-24-announcement-show-until/tasks.md b/openspec/changes/archive/2026-11-24-announcement-show-until/tasks.md new file mode 100644 index 000000000..afdb9ced8 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-announcement-show-until/tasks.md @@ -0,0 +1,7 @@ +# Tasks: announcement-show-until + +- [x] Create and update endpoints: require `endsAt` for a new announcement; refuse an end before the publish time (400); stored announcements without `endsAt` unchanged +- [x] Announcement form: "Show until" required with the explanation, the end time in the preview, the button "Schedule" for a future publish time +- [x] Translations in every shipped locale +- [x] Unit tests: missing end time, end before start, legacy rows without an end time still shown, visibility ends at the end time +- [x] Playwright: the form refuses to publish without "Show until"; a scheduled announcement shows "Schedule" (written, runs in nightly: tests/e2e/announcement-show-until.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/proposal.md b/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/proposal.md new file mode 100644 index 000000000..e54405ac8 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/proposal.md @@ -0,0 +1,27 @@ +# Proposal: dashboard-theme-readonly + +## Why + +Board LpDashboardInstellingen shows, on the tab Details under "Weergave", a field "Thema: Huisstijl Zuiddrecht" next +to the dashboard's own look ("Eigen uitstraling": accent colour, background colour, background image, with the +contrast check). It was an open question whether that field picks among themes. + +Decided on 23 November 2026 (product decisions delegated by Ruben): the theme field shows the instance theme +read-only; a dashboard keeps its own accent and background (REQ-THM-001, REQ-THM-002) and does not choose a theme. + +Two further fixes to the spec, from the same board: + +- REQ-THM-001's scenario opens a tab "Look". The settings window has the tabs Details, Talen, Delen, Publicatie, + Exports and Versies; the look is a block on Details. +- The board's "Indeling van dit dashboard" field (a layout preset) is dropped from the board by the same decision: the + column choice in the edit bar (REQ-DASH-038) is the layout. No spec text described a preset, so nothing is removed; + this requirement says the Details tab has no such field. + +## What changes + +- `dashboards`: REQ-THM-001 places the look on the Details tab; REQ-THM-004 adds the read-only theme field and states + that the Details tab offers no theme choice and no layout preset. + +## Impact + +- The Details tab of the dashboard settings (`src/components/Workspace/config/DetailsTab.vue`), translations. diff --git a/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md b/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md new file mode 100644 index 000000000..828f3e2b6 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md @@ -0,0 +1,37 @@ +# Delta: dashboards + +## MODIFIED Requirements + +### Requirement: Each dashboard can have its own look (REQ-THM-001) + +A person with full permission on a dashboard MUST be able to set an accent colour, a background colour and a background image from LaunchPad's uploaded resources, in the block "Own look" ("Eigen uitstraling") of the dashboard settings' Details tab (board LpDashboardInstellingen); there is no separate Look tab. The look MUST apply to that dashboard's region only; the Nextcloud header, the organisation navigation and other dashboards MUST keep the instance theme. A dashboard without a look MUST follow the theme. + +#### Scenario: A green team dashboard + +- **GIVEN** Ella has full permission on "Team Groen" +- **WHEN** she opens the dashboard settings, tab Details, and in Own look sets the accent to `#1f5c3a` and a background image, and saves +- **THEN** "Team Groen" shows the green accent and the image +- **AND** her dashboard "Mijn werkplek" and the Nextcloud header look as before + +## ADDED Requirements + +### Requirement: The Details tab shows the instance theme, read-only (REQ-THM-004) + +The Details tab SHALL show, under "Display" ("Weergave"), the field "Theme" ("Thema") with the name of the theme the +instance uses (Nextcloud's theming name, or the active thematiq theme when thematiq sets one), read-only, with the line +that the theme is the same for every dashboard and that this dashboard's own colours are set under Own look. The tab +SHALL NOT offer a choice of theme and SHALL NOT offer a layout preset ("Indeling van dit dashboard"); the dashboard's +layout is its column choice in the edit bar (REQ-DASH-038) and where its widgets stand. + +#### Scenario: The theme of Zuiddrecht + +- **GIVEN** the instance uses the theme "Huisstijl Zuiddrecht" +- **WHEN** Pieter opens the Details tab of a dashboard he owns +- **THEN** Thema reads "Huisstijl Zuiddrecht" and cannot be changed +- **AND** the tab has no layout field + +#### Scenario: The own look stays a choice + +- **GIVEN** the same Details tab +- **WHEN** Pieter sets an accent colour under Own look and saves +- **THEN** the dashboard takes the accent, and Thema still reads "Huisstijl Zuiddrecht" diff --git a/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/tasks.md b/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/tasks.md new file mode 100644 index 000000000..34c160d12 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-dashboard-theme-readonly/tasks.md @@ -0,0 +1,7 @@ +# Tasks: dashboard-theme-readonly + +- [x] Details tab: a read-only Thema field with the instance theme name (thematiq's active theme when set, else Nextcloud theming) and its explanation line, under Weergave +- [x] Details tab: the look fields of REQ-THM-001 in an Own look block; remove any separate Look tab; no theme select and no layout preset field +- [x] Translations in every shipped locale +- [x] Unit tests: the theme name source (thematiq set, not set); the field is read-only; no layout field; the look still saves from the Details tab +- [x] Playwright: open Dashboard settings, Details, read the theme name and set an accent under Own look (written, runs in nightly: tests/e2e/dashboard-theme-readonly.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-embed-outage-state/proposal.md b/openspec/changes/archive/2026-11-24-embed-outage-state/proposal.md new file mode 100644 index 000000000..22950887b --- /dev/null +++ b/openspec/changes/archive/2026-11-24-embed-outage-state/proposal.md @@ -0,0 +1,13 @@ +# Proposal: embed-outage-state + +## Why + +Board LpManagement draws the Power BI report card in its outage state: an "Outage" tag in the card head, the line "Embedded report · app.powerbi.com · signed in as Pieter Jansen", and in the body "The report could not be loaded", what the connection answered and when ("gave an error today at 09:30: token expired"), Reload and "Open in a new tab". On development the iframe widget shows "This site does not allow itself to be embedded. Its owner blocks framing, which cannot be overridden here" for every failure (REQ-IFRAME-004), with no tag, no source line, no time and no Reload. + +## What changes + +- `iframe-embed-widget`: the source line and the outage state of an embedded report (REQ-IFRAME-005). + +## Impact + +- The iframe widget renderer, the connection state it reads (app-connections), translations. diff --git a/openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md b/openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md new file mode 100644 index 000000000..56a744f78 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md @@ -0,0 +1,15 @@ +# Delta: iframe-embed-widget + +## ADDED Requirements + +### Requirement: The outage state of an embedded report (REQ-IFRAME-005) + +An embedded page or report SHALL show under its title where it comes from ("Embedded report · app.powerbi.com · signed in as <name>" when the connection signs in). When it cannot load, the card head SHALL show an "Outage" tag and the body SHALL say "The report could not be loaded", the cause and its time when the connection knows them ("gave an error today at 09:30: token expired"), with Reload and "Open in a new tab". + +#### Scenario: Token expired + +- **GIVEN** the Power BI connection failed at 09:30 with an expired token +- **THEN** the card shows Outage, the cause with 09:30, Reload and Open in a new tab + + +Content keys the widget reads for this (all optional): `kind` (`report` for an embedded report, otherwise a page) and `connection` (`{account, error, errorAt}`, what the connection behind the embed knows when one signs in). Without `connection.error`, the cause is what the widget found itself (the site refuses framing, could not be reached, did not finish loading, a network error) and the time is when it saw that. diff --git a/openspec/changes/archive/2026-11-24-embed-outage-state/tasks.md b/openspec/changes/archive/2026-11-24-embed-outage-state/tasks.md new file mode 100644 index 000000000..9b44e9aba --- /dev/null +++ b/openspec/changes/archive/2026-11-24-embed-outage-state/tasks.md @@ -0,0 +1,7 @@ +# Tasks: embed-outage-state + +- [x] Source line under the title: kind, host, signed-in account when the connection signs in +- [x] Outage state: tag in the head, the cause and its time, Reload and Open in a new tab +- [x] Translations in every shipped locale +- [x] Unit tests: outage with and without a known cause +- [x] Playwright: a refused frame shows the outage state (written in `tests/e2e/iframe-embed-widget.spec.ts`, runs in nightly) diff --git a/openspec/changes/archive/2026-11-24-kiosk-position-indicator/proposal.md b/openspec/changes/archive/2026-11-24-kiosk-position-indicator/proposal.md new file mode 100644 index 000000000..59071580e --- /dev/null +++ b/openspec/changes/archive/2026-11-24-kiosk-position-indicator/proposal.md @@ -0,0 +1,16 @@ +# Proposal: kiosk-position-indicator + +## Why + +Board LpKiosk draws the canteen screen without app chrome, and in its bottom right corner "2 van 4 · volgende over +18 s": which dashboard of the playlist is showing and when the next one comes. REQ-KIOSKUI-002 says the kiosk link +plays the playlist "with no login and no controls", and no requirement shows the position. + +## What changes + +- `dashboard-kiosk-mode`: a quiet position line on a playlist of more than one dashboard (REQ-KIOSKUI-003). It is text, + not a control. + +## Impact + +- The kiosk render (playlist player), translations. diff --git a/openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md b/openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md new file mode 100644 index 000000000..6feda6871 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md @@ -0,0 +1,22 @@ +# Delta: dashboard-kiosk-mode + +## ADDED Requirements + +### Requirement: The kiosk screen shows where the playlist is (REQ-KIOSKUI-003) + +While a kiosk link plays a playlist of more than one dashboard, the screen SHALL show in its bottom right corner the +position of the current dashboard and the seconds until the next one ("2 van 4 · volgende over 18 s", in the +playlist's language), updated every second, in small text that meets AA contrast on the dashboard's background. It +SHALL NOT be a control and SHALL NOT take focus. A playlist of one dashboard SHALL show no position line. The line +SHALL be hidden from screen readers except for a polite announcement when the dashboard changes, naming the new one. + +#### Scenario: The canteen screen + +- **GIVEN** the playlist "Kantine" holds four dashboards of 30 seconds each, and the second has shown for 12 seconds +- **WHEN** someone looks at the screen +- **THEN** the bottom right reads "2 van 4 · volgende over 18 s" + +#### Scenario: One dashboard + +- **GIVEN** a playlist with one dashboard +- **THEN** the screen shows no position line diff --git a/openspec/changes/archive/2026-11-24-kiosk-position-indicator/tasks.md b/openspec/changes/archive/2026-11-24-kiosk-position-indicator/tasks.md new file mode 100644 index 000000000..6480376dd --- /dev/null +++ b/openspec/changes/archive/2026-11-24-kiosk-position-indicator/tasks.md @@ -0,0 +1,7 @@ +# Tasks: kiosk-position-indicator + +- [x] Kiosk playlist player: position line (index of total, seconds to the next) bottom right, updated every second, hidden for a single dashboard, AA contrast on the dashboard background +- [x] A polite live region that names the new dashboard when the playlist moves on +- [x] Translations in every shipped locale +- [x] Unit tests: the line's text over a dwell time, absent for one dashboard, the announcement on change +- [x] Playwright: a two-dashboard playlist shows "1 van 2" and then "2 van 2" (written in `tests/e2e/kiosk-position-indicator.spec.ts`, runs in nightly) diff --git a/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/proposal.md b/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/proposal.md new file mode 100644 index 000000000..f10af932d --- /dev/null +++ b/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/proposal.md @@ -0,0 +1,17 @@ +# Proposal: phone-hidden-widgets-named + +## Why + +Board LpMobiel draws the notice on a phone as "2 widgets werken niet op een telefoon en zijn verborgen: Snel beginnen +(Word) en Assistent." with a link "Welke?". REQ-MRA-003 asks for a count and a "view desktop layout" link instead, so +the person never learns which widgets are missing. REQ-MRA-003 is not built yet, so the builder can follow the board +from the start. + +## What changes + +- `launchpad-mobile-remote-access`: the notice names the hidden widgets and "Which?" points to each on demand + (REQ-MRA-007). The hiding rule of REQ-MRA-003 stays; its "view desktop layout" link is no longer offered. + +## Impact + +- The notice in the workspace shell, translations. diff --git a/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/specs/launchpad-mobile-remote-access/spec.md b/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/specs/launchpad-mobile-remote-access/spec.md new file mode 100644 index 000000000..0ee825008 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/specs/launchpad-mobile-remote-access/spec.md @@ -0,0 +1,25 @@ +# Delta: launchpad-mobile-remote-access + +## ADDED Requirements + +### Requirement: The phone notice names the hidden widgets (REQ-MRA-007) + +When widgets are hidden on a phone (REQ-MRA-003), the notice at the top of the workspace SHALL say how many and name +them by title: "2 widgets do not work on a phone and are hidden: Snel beginnen (Word) and Assistent." (nl "2 widgets +werken niet op een telefoon en zijn verborgen: ..."), followed by a link "Which?" ("Welke?") that explains why a widget +can be hidden on a phone and that the person sees it on a larger screen. The notice SHALL replace the "view desktop +layout" link of REQ-MRA-003; there SHALL be no forced desktop layout on a phone. With more than three hidden widgets +the notice SHALL name three and count the rest. + +#### Scenario: Pieter on his phone + +- **GIVEN** Mijn werkplek holds Snel beginnen and Assistent, neither ready for a phone +- **WHEN** Pieter opens it at 390 px +- **THEN** the notice reads "2 widgets werken niet op een telefoon en zijn verborgen: Snel beginnen (Word) en Assistent." with the link "Welke?" +- **AND** no "view desktop layout" link is shown + +#### Scenario: Many hidden widgets + +- **GIVEN** five widgets on a dashboard are not ready for a phone +- **WHEN** it opens at 390 px +- **THEN** the notice names three of them and says "and 2 more" diff --git a/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/tasks.md b/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/tasks.md new file mode 100644 index 000000000..eba844cf2 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/tasks.md @@ -0,0 +1,6 @@ +# Tasks: phone-hidden-widgets-named + +- [x] Workspace notice on a phone: the count and the titles of the hidden widgets (three, then "and N more"), the "Which?" explanation, no forced desktop layout +- [x] Translations in every shipped locale +- [x] Unit tests: names, the three-and-more rule, no desktop-layout link +- [x] Playwright: at 390 px a dashboard with a widget that is not phone-ready shows the notice with its name (written, runs in nightly: tests/e2e/phone-hidden-widgets-named.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-phone-install-banner/proposal.md b/openspec/changes/archive/2026-11-24-phone-install-banner/proposal.md new file mode 100644 index 000000000..4707853d8 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-phone-install-banner/proposal.md @@ -0,0 +1,17 @@ +# Proposal: phone-install-banner + +## Why + +Board LpMobiel draws, at the top of the workplace on a phone, a banner "Zet Launchpad op uw beginscherm. Dan opent uw +werkplek met één tik, net als een app." with "Niet nu" and "Installeren". REQ-PLB-006 lets a person install the page +through the browser's own "Add to home screen" option, but nothing on the page offers it, so few people find it. + +## What changes + +- `platform-baseline`: an install banner on a phone (REQ-PLB-009) that uses the browser's install prompt where the + browser has one and explains the steps where it has not. LaunchPad still ships no manifest or service worker of its + own (REQ-PLB-006). + +## Impact + +- A banner component in the workspace shell, translations. "Niet nu" is a per-device convenience kept in the browser. diff --git a/openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md b/openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md new file mode 100644 index 000000000..e2a768843 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md @@ -0,0 +1,31 @@ +# Delta: platform-baseline + +## ADDED Requirements + +### Requirement: A phone offers to put LaunchPad on the home screen (REQ-PLB-009) + +On a screen narrower than 768 px, in a browser tab (not already opened as an installed app), the workspace SHALL show a +banner above the first widget: "Put LaunchPad on your home screen" with "Then your workplace opens with one tap, like +an app", and the buttons "Not now" and "Install" (nl "Zet Launchpad op uw beginscherm", "Niet nu", "Installeren"). +Where the browser offers an install prompt, Install SHALL open it; where it does not (Safari on iOS), Install SHALL +show the steps for the browser's Share, Add to Home Screen. "Not now" SHALL hide the banner on that device for 30 days. +The banner SHALL NOT show once the page runs as an installed app, on a wider screen, in the kiosk view or on a public +page. It SHALL be reachable by keyboard and screen reader like any notice. + +#### Scenario: Pieter installs from the banner + +- **GIVEN** Pieter opens his workplace in Chrome on a phone, not installed +- **WHEN** he chooses Install +- **THEN** the browser's install prompt opens +- **AND** after installing, opening LaunchPad from the home screen shows no banner + +#### Scenario: Not now + +- **GIVEN** the banner shows on Pieter's phone +- **WHEN** he chooses Not now +- **THEN** the banner does not show on that phone for 30 days + +#### Scenario: A desktop screen + +- **GIVEN** Pieter opens his workplace on a 1440 px screen +- **THEN** no install banner shows diff --git a/openspec/changes/archive/2026-11-24-phone-install-banner/tasks.md b/openspec/changes/archive/2026-11-24-phone-install-banner/tasks.md new file mode 100644 index 000000000..eff78b056 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-phone-install-banner/tasks.md @@ -0,0 +1,6 @@ +# Tasks: phone-install-banner + +- [x] Banner component in the workspace shell: shown below 768 px, not in standalone display mode, not in kiosk or public views; Install uses the captured `beforeinstallprompt`, else shows the iOS steps; Not now stored in the browser for 30 days (read and write wrapped so a blocked storage only means the banner shows) +- [x] Translations in every shipped locale +- [x] Unit tests: shown and hidden per width, display mode, kiosk and public; Install with and without a prompt; Not now for 30 days +- [x] Playwright: at 390 px the banner shows and Not now hides it after a reload (written in `tests/e2e/phone-install-banner.spec.ts`, runs in nightly) diff --git a/openspec/changes/archive/2026-11-24-public-live-widgets/proposal.md b/openspec/changes/archive/2026-11-24-public-live-widgets/proposal.md new file mode 100644 index 000000000..899a6260f --- /dev/null +++ b/openspec/changes/archive/2026-11-24-public-live-widgets/proposal.md @@ -0,0 +1,13 @@ +# Proposal: public-live-widgets + +## Why + +Boards LpPubliek and LpKiosk draw a public start page and a canteen screen that anonymous visitors see: news items with their date, the city office's opening hours as a list with "Open now, until 17:00", outages with a coloured dot, the weather, and the waiting time at the desk. `PublicDashboardGrid` renders only static widgets (label, header, text, image, link, divider) for an anonymous visitor; every other widget says "This widget is only visible to signed-in users", and a text widget's Markdown shows as raw text. So the news, weather and live data cards of both boards cannot show, whatever the look. + +## What changes + +- `dashboard-public-share`: news, weather and live data widgets render on a public link and on a kiosk screen, read through the link's token (REQ-PSHR-011); a text widget's Markdown is rendered, sanitised (REQ-PSHR-012). + +## Impact + +- `src/components/PublicDashboardGrid.vue`, token-scoped read endpoints for announcements (published, targeted at everyone), weather and live data, `PublicShareService`/`KioskService` checks, translations. diff --git a/openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md b/openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md new file mode 100644 index 000000000..60080992a --- /dev/null +++ b/openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md @@ -0,0 +1,22 @@ +# Delta: dashboard-public-share + +## ADDED Requirements + +### Requirement: Live widgets on a public link and a kiosk screen (REQ-PSHR-011) + +On a public link and on a kiosk screen, the news widget SHALL list the published announcements targeted at everyone, the weather widget SHALL show its reading, and the live data widget SHALL show its value, each read through the link's or playlist's token and only for a placement that is on the shared dashboard. An announcement targeted at groups SHALL NOT be shown to an anonymous visitor. + +#### Scenario: The canteen screen + +- **GIVEN** the playlist Kantine shows Today in Zuiddrecht with News, Weather and Waiting time at the desk +- **WHEN** the screen shows it without a login +- **THEN** the cards show the news items, the weather and the waiting time + +### Requirement: Text in Markdown on public screens (REQ-PSHR-012) + +A text widget on a public link or kiosk screen SHALL render its Markdown (lists, emphasis, links), sanitised as on the dashboard. + +#### Scenario: Opening hours as a list + +- **GIVEN** the Opening hours widget holds a Markdown list +- **THEN** the public start page shows it as a list, not as raw text diff --git a/openspec/changes/archive/2026-11-24-public-live-widgets/tasks.md b/openspec/changes/archive/2026-11-24-public-live-widgets/tasks.md new file mode 100644 index 000000000..85b81f6e3 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-public-live-widgets/tasks.md @@ -0,0 +1,7 @@ +# Tasks: public-live-widgets + +- [x] Token-scoped reads: published announcements for everyone, a weather reading, a live data value, each only for a placement on the shared dashboard +- [x] PublicDashboardGrid renders the news, weather and live data widgets with those reads +- [x] Text widgets render their Markdown, sanitised, on public and kiosk screens +- [x] Unit tests: a placement not on the dashboard is refused; a targeted announcement is not shown anonymously +- [x] Playwright: the kiosk playlist shows the news and the waiting time without a login (written in `tests/e2e/public-live-widgets.spec.ts`, runs in nightly) diff --git a/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/proposal.md b/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/proposal.md new file mode 100644 index 000000000..80d16d46f --- /dev/null +++ b/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/proposal.md @@ -0,0 +1,13 @@ +# Proposal: reactions-bar-at-the-foot + +## Why + +Board LpIntranet ends the dashboard with a bar over the full width: "Wat vindt u van dit intranet?" with the reactions and their counts, and at the right "Laatst bijgewerkt door Communicatie, vandaag 08:30". REQ-RXN-010 puts the reactions bar under the dashboard title, and the code draws it above the title, so the board's bar is missing and a row of emoji sits above the page title instead. The board is canon, so the requirement follows the board. + +## What changes + +- `dashboard-reactions`: REQ-RXN-010 is MODIFIED: the bar sits at the foot of the dashboard, under the last widget, with a question before the reactions and the last change after them. + +## Impact + +- `src/views/Views.vue` (where `DashboardReactions` mounts), `src/components/Workspace/DashboardReactions.vue`, translations. diff --git a/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md b/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md new file mode 100644 index 000000000..0441ed39b --- /dev/null +++ b/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md @@ -0,0 +1,41 @@ +# Delta: dashboard-reactions + +## MODIFIED Requirements + +### Requirement: REQ-RXN-010 A viewer can react from the dashboard + +In view mode a reactions bar MUST show at the foot of the dashboard, under the last widget and over the full width, as a card that asks "What do you think of this dashboard?" before each emoji and its count and names who last changed the dashboard and when after them. It MUST mark the viewer's own reactions and toggle the viewer's reaction on click. It MUST offer only the allowed emoji, and MUST be absent when reactions are disabled globally or for the dashboard. + +#### Scenario: Add and remove + +- **GIVEN** Pieter views the dashboard "Team" with reactions on +- **WHEN** he clicks the thumbs up, then clicks it again +- **THEN** the count rises by one and is marked as his, then returns to what it was + +#### Scenario: Reactions off + +- **GIVEN** the dashboard "Board" has reactions switched off +- **WHEN** Pieter opens it +- **THEN** no reactions bar is shown + +## Non-Functional Requirements + +- **Performance**: `GET /api/dashboards/{uuid}/reactions` MUST return within 200ms. `GET /api/dashboards/{uuid}/reactions/{emoji}/users` with 100-item result MUST return within 300ms (pagination used if > 100). +- **Data integrity**: The unique constraint `(dashboardUuid, userId, emoji)` MUST be enforced at the database level to prevent duplicate reactions. +- **Idempotency**: POST add and DELETE remove MUST be fully idempotent (same request sent twice produces the same result without error). +- **Localization**: All error messages (`"Emoji not allowed"`, `"Reactions are disabled"`, etc.) MUST support English and Dutch per i18n requirements. +- **Cascade safety**: Deleting a dashboard MUST reliably cascade-delete all reactions via `ReactionsListener` subscribing to `DashboardDeletedEvent`. + +### Current Implementation Status + +**Implemented** — files of record: + +- `lib/Migration/Version001014Date20260502120000.php` — schema (table + index + per-dashboard column) +- `lib/Db/DashboardReaction.php` + `lib/Db/DashboardReactionMapper.php` +- `lib/Db/Dashboard.php` (`reactionsEnabled` column) +- `lib/Service/ReactionService.php` + `PermissionDeniedException` + `ReactionsDisabledException` +- `lib/Listener/ReactionsListener.php` (DashboardDeletedEvent → cascade delete) +- `lib/Controller/DashboardReactionApiController.php` +- `appinfo/routes.php` (4 routes) +- `src/services/api.js` + `src/stores/dashboard.js` (4 actions) +- `l10n/{en,nl}.{json,js}` (6 strings each) diff --git a/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/tasks.md b/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/tasks.md new file mode 100644 index 000000000..191d06fde --- /dev/null +++ b/openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/tasks.md @@ -0,0 +1,7 @@ +# Tasks: reactions-bar-at-the-foot + +- [x] Mount the reactions bar after the grid, over the full width, as a card +- [x] The question "What do you think of this dashboard?" before the reactions, and "Last updated by <name>, <when>" after them +- [x] Translations in every shipped locale +- [x] Unit tests: the bar renders after the grid; the last-change line +- [x] Playwright: react on Zuiddrecht intranet from the foot of the page (written, runs in nightly: tests/e2e/reactions-bar-at-the-foot.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-read-receipts-dialog/proposal.md b/openspec/changes/archive/2026-11-24-read-receipts-dialog/proposal.md new file mode 100644 index 000000000..04bfca0c6 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-read-receipts-dialog/proposal.md @@ -0,0 +1,15 @@ +# Proposal: read-receipts-dialog + +## Why + +Board LpLeesbevestigingen draws "Leesbevestigingen: <aankondiging>": the confirmed count over the audience ("128 van 164 bevestigd · nog 36 · deadline vrijdag 30 oktober") with a bar, filters Iedereen, Bevestigd and Nog niet bevestigd, a table of Medewerker, Afdeling and Status, a note that the download gives the full list with the time of each confirmation, Downloaden and Sluiten. + +REQ-ACK-004 and REQ-ACK-008 give the report and a Read receipts entry, but the entry never shows on the demo stack: the frontend looks for `announcementKey` on a placement and the server never sends one (a placement that asks for confirmation has no key; `WidgetPlacementMapper` only reads receipts by key). The dialog shape, the filters and the department column have no requirement. + +## What changes + +- `dashboard-acknowledgements`: a placement that asks for confirmation carries a stable `announcementKey` (REQ-ACK-009) and the read confirmations dialog as the board draws it (REQ-ACK-010). + +## Impact + +- `lib/Db/WidgetPlacement.php` (serialise the key), a migration or derivation of the key from the placement, `src/modals/AcknowledgementReportModal.vue`, the demo seed (the intranet announcement gets its key), translations. diff --git a/openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md b/openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md new file mode 100644 index 000000000..2de26adf4 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md @@ -0,0 +1,23 @@ +# Delta: dashboard-acknowledgements + +## ADDED Requirements + +### Requirement: A placement that asks for confirmation has a key (REQ-ACK-009) + +A widget placement with `requiresAcknowledgement` SHALL carry a stable `announcementKey` in every response that returns the placement, the same across edits of its content, so the reader's confirmation and the editor's report refer to it. + +#### Scenario: The key reaches the dashboard + +- **GIVEN** the Announcement widget on Intranet Zuiddrecht asks for confirmation +- **WHEN** an editor loads the dashboard +- **THEN** the placement carries its announcementKey and Read receipts appears in the More menu + +### Requirement: The read confirmations dialog (REQ-ACK-010) + +Read receipts SHALL open a dialog titled "Read confirmations: <title>" under "Announcement · <dashboard>", showing the confirmed count over the audience with the number still to go and the deadline, a bar, the filters Everyone, Confirmed and Not confirmed yet, a table of Employee (initials and name), Department and Status, a line that says how many are shown and that Download gives the full list with the date and time of each confirmation, and the buttons Download and Close. + +#### Scenario: Who has not confirmed + +- **GIVEN** 128 of 164 confirmed "New procedure for Woo requests" +- **WHEN** the editor chooses Not confirmed yet +- **THEN** the table lists the 36 who have not, with their department and "Not yet" diff --git a/openspec/changes/archive/2026-11-24-read-receipts-dialog/tasks.md b/openspec/changes/archive/2026-11-24-read-receipts-dialog/tasks.md new file mode 100644 index 000000000..89f4c6328 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-read-receipts-dialog/tasks.md @@ -0,0 +1,9 @@ +# Tasks: read-receipts-dialog + +- [x] Give a placement with requiresAcknowledgement a stable announcementKey (derived from its uuid, kept on content change) and send it with the placement +- [x] Read confirmations dialog: count over audience with deadline and bar, filters, table with department and status, Download and Close +- [x] Department column from the profile field the administrator names +- [x] Demo seed: the intranet announcement widget asks for confirmation and gets its key +- [x] Translations in every shipped locale +- [x] Unit tests: key is stable, report counts, filter Not confirmed yet +- [x] Playwright: as an editor of Intranet Zuiddrecht open Read receipts and filter (written, runs in nightly: tests/e2e/dashboard-acknowledgements.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/proposal.md b/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/proposal.md new file mode 100644 index 000000000..f3695af54 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/proposal.md @@ -0,0 +1,20 @@ +# Proposal: recent-work-and-web-search-widgets + +## Why + +Two widgets the boards draw are built on development but have no requirement of their own; their code points at the +widgets spec as a whole. + +- **Verder waar u was** (boards LpVandaag, LpStart): the reader's own recent work across apps, one row per thing, + named by the thing, with the app and when. Built in #1613 as the `recent-work` widget type. +- **Zoeken op internet** (board LpWerkplek): a search field, the search engine, a Search button and the line that the + results open in a new tab. Built in 7409fd00 as `content.layout: 'web'` of the `search` widget. + +## What changes + +- `widgets`: REQ-WDG-032 for recent work and REQ-WDG-033 for the internet search layout. + +## Impact + +- Spec only for behaviour that exists; the tasks move the code's `@spec` tags to the new requirements and close test + gaps. diff --git a/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md b/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md new file mode 100644 index 000000000..2148d60c6 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md @@ -0,0 +1,62 @@ +# Delta: widgets + +## ADDED Requirements + +### Requirement: Recent work shows where the reader left off (REQ-WDG-032) + +LaunchPad SHALL offer a `recent-work` widget type ("Verder waar u was", boards LpVandaag and LpStart). It SHALL read +the reader's own activity from the Activity app (`GET /ocs/v2.php/apps/activity/api/v2/activity/self`), so what +colleagues did never shows, and SHALL list one row per thing the reader worked on, newest first, at most +`content.limit` rows (default 6). Each row SHALL be named by the thing (the last part of its name), with below it the +app and when: "vanochtend", "vanmiddag" or "vanavond" for today, the weekday within the last week, and the day and +month before that. A row SHALL link to the thing. + +The widget SHALL leave out what the reader deleted, things named only by an id, and activity without a link. The same +thing saved again under a new id SHALL count once. With `content.apps` it SHALL show only those apps' work. When the +Activity app does not answer, the widget SHALL say "Recent work needs the Activity app."; with no activity it SHALL +say "Nothing you worked on recently." + +#### Scenario: Pieter picks up where he left off + +- **GIVEN** this morning Pieter edited "Besluit Woo-verzoek jeugdzorg.docx" twice and on Friday commented on decision "Collegevoorstel Havenpark" +- **WHEN** he opens the start page with the Verder waar u was widget +- **THEN** the widget shows "Besluit Woo-verzoek jeugdzorg.docx" once with "files · vanochtend", then "Collegevoorstel Havenpark" with its app and "vrijdag" + +#### Scenario: A deleted file is not work to pick up + +- **GIVEN** Pieter deleted "concept.docx" an hour ago +- **WHEN** the widget renders +- **THEN** "concept.docx" is not listed + +#### Scenario: Only the apps the author chose + +- **GIVEN** a recent-work widget with `apps: ["files"]` +- **WHEN** the widget renders +- **THEN** it lists only work in Files + +#### Scenario: Without the Activity app + +- **GIVEN** the Activity app is disabled +- **WHEN** the widget renders +- **THEN** it says "Recent work needs the Activity app." + +### Requirement: The search widget can search the internet (REQ-WDG-033) + +A `search` widget with `content.layout: 'web'` SHALL draw an internet search form (board LpWerkplek, "Zoeken op +internet"): a labelled search field, the name of the search engine, a Search button and the line "Opens the results +in a new tab". The engine SHALL be `content.engine` `{name, url}` when its url holds `{q}`, else DuckDuckGo +(`https://duckduckgo.com/?q={q}`). Submitting SHALL open the engine's url with the URL-encoded words in a new tab, +with `noopener` and `noreferrer`; an empty field SHALL do nothing. Without `layout: 'web'` the widget SHALL stay the +tile search of tile-quick-search. + +#### Scenario: Pieter searches the internet + +- **GIVEN** a search widget with `layout: 'web'` and no engine set +- **WHEN** Pieter types "omgevingswet termijnen" and chooses Search +- **THEN** a new tab opens `https://duckduckgo.com/?q=omgevingswet%20termijnen` + +#### Scenario: An engine without a placeholder is ignored + +- **GIVEN** a search widget with `engine: {name: "Intranet", url: "https://intranet.example.nl/search"}` +- **WHEN** the widget renders +- **THEN** it names DuckDuckGo as the engine diff --git a/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/tasks.md b/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/tasks.md new file mode 100644 index 000000000..c6f63010d --- /dev/null +++ b/openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/tasks.md @@ -0,0 +1,7 @@ +# Tasks: recent-work-and-web-search-widgets + +- [x] `RecentWorkWidget.vue` and `RecentWorkWidgetForm.vue`: `@spec` tags to REQ-WDG-032 +- [x] `SearchWidget.vue`: `@spec` tags of the web layout (`webLayout`, `engine`, `searchWeb`) to REQ-WDG-033 +- [x] Unit tests: `recentWorkRows` (deleted, uuid-named and link-less activity left out; one row per thing; `apps` filter; limit) and `recentWhen` (morning, afternoon, evening, weekday, date); the unavailable and empty states +- [x] Unit tests: the web layout opens the encoded query in a new tab, ignores an empty field and an engine url without `{q}` +- [x] Playwright: the Verder waar u was widget lists a file the test user just saved; the internet search opens a new tab with the query (written, runs in nightly: tests/e2e/recent-work-and-web-search-widgets.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/proposal.md b/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/proposal.md new file mode 100644 index 000000000..90a67c082 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/proposal.md @@ -0,0 +1,29 @@ +# Proposal: setup-five-steps-and-admin-tour + +## Why + +Board LpInstellen draws the setup at step 3 of 5, with the steps Welkom, Groepen, Voorbeelden, Rollen and Klaar, and +says "de opslagstap is weg". Board LpBeheerAlgemeen describes the setup as "Groepen, voorbeelddashboards en rollen, in +vijf stappen van welkom tot klaar" and draws the admin tour at "stap 1 van 6", with the stops Algemeen, Sjablonen, +Rollen en rechten, Delen, Kiosk and Demogegevens. + +The spec and the code still have six setup steps, the fifth being the footer editor, and an admin tour of five stops +(general settings, templates, roles, sharing, operations). The footer has its own place on the admin tab +Organisatiemenu (board LpBeheerNavigatie), so the setup does not need to ask for it. + +## What changes + +- `setup-wizard`: the wizard has five steps: Welcome, Groups, Examples, Roles, Done. The footer step goes. The step + counter reads "n / 5". The welcome text names groups, example dashboards and roles. +- `runtime-shell`: the admin tour has six stops, in the order of the board: General, Templates, Roles and rights, + Sharing, Kiosk, Demo data. + +## Out of scope + +- `occ launchpad:setup` keeps accepting `footer_config` in its YAML file (cli-commands owns that schema); the footer + stays configurable on the Organisatiemenu tab. + +## Impact + +- `src/modals/SetupWizardModal.vue`, `lib/Service/SetupWizardService.php` (step count and statuses), the admin tour + declaration, translations. diff --git a/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/runtime-shell/spec.md b/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/runtime-shell/spec.md new file mode 100644 index 000000000..2f9839a0d --- /dev/null +++ b/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/runtime-shell/spec.md @@ -0,0 +1,25 @@ +# Delta: runtime-shell + +## MODIFIED Requirements + +### Requirement: The admin area has its own first-visit tour (REQ-SHELL-011) + +LaunchPad MUST declare a second guided tour, `launchpad:admin-getting-started`, for the LaunchPad admin settings page. It MUST start on an administrator's first visit to that page and walk through six stops, in this order, as board LpBeheerAlgemeen draws it ("Rondleiding door het beheer, stap 1 van 6"): the tabs General ("Algemeen"), Templates ("Sjablonen"), Roles and rights ("Rollen en rechten"), Sharing ("Delen"), Kiosk and Demo data ("Demogegevens"). Each stop MUST name its tab and say in one line what is set there; the first stop MUST say the tour is shown once. Each stop MUST offer Skip and Next. Completion MUST be stored per user like the Workspace tour (REQ-SHELL-010). A person who is not an administrator never sees it. + +#### Scenario: An administrator's first visit to the admin page + +- **GIVEN** Noor is a Nextcloud administrator who never opened the LaunchPad admin page +- **WHEN** she opens it +- **THEN** the admin tour starts on the General tab with "step 1 of 6" + +#### Scenario: The tour visits the six tabs in order + +- **GIVEN** Noor is on the first stop of the admin tour +- **WHEN** she chooses Next five times +- **THEN** the tour has visited General, Templates, Roles and rights, Sharing, Kiosk and Demo data, in that order + +#### Scenario: A finished admin tour stays closed + +- **GIVEN** Noor completed the admin tour +- **WHEN** she opens the admin page again +- **THEN** the admin tour does not start diff --git a/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/setup-wizard/spec.md b/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/setup-wizard/spec.md new file mode 100644 index 000000000..b8f5d2cfd --- /dev/null +++ b/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/setup-wizard/spec.md @@ -0,0 +1,83 @@ +# Delta: setup-wizard + +## REMOVED Requirements + +### Requirement: REQ-WIZ-002 Multi-Step Wizard Flow with 6 Steps + +**Reason**: boards LpInstellen and LpBeheerAlgemeen draw five steps. REQ-WIZ-012 replaces it. + +**Migration**: none; the steps that stay keep what they store. + +### Requirement: REQ-WIZ-007 Step 5 — Footer Configuration (Optional, Depends on footer-customization Capability) + +**Reason**: boards LpInstellen and LpBeheerAlgemeen draw a setup of five steps without a footer step. The footer is +set on the admin tab Organisatiemenu (board LpBeheerNavigatie). + +**Migration**: none. A footer set earlier stays as it is; `footer_config` in the `occ launchpad:setup` file keeps +working. + +## ADDED Requirements + +### Requirement: REQ-WIZ-012 Multi-Step Wizard Flow with 5 Steps + +The wizard MUST guide the admin through a linear, skippable sequence of 5 steps, as board LpInstellen draws them: +Welcome ("Welkom"), Groups ("Groepen", the group priority order), Examples ("Voorbeelden", the demo dashboards), Roles +("Rollen", the admin roles) and Done ("Klaar"). Each step has Skip / Back / Next buttons. Only the "Finish" button on +Step 5 marks the wizard complete. The wizard MUST NOT ask for storage or for the footer. + +> NOTE: Steps 2 to 4 each embed the canonical admin UI component from the corresponding sibling capability (`group-priority-order`, `demo-data-showcases`, `admin-roles`). The wizard is a thin orchestrator: it owns step sequencing and the completion flag; each sibling capability owns its own settings persistence. No settings surfaces are duplicated. + +#### Scenario: Wizard starts at Step 1 +- GIVEN the banner's "Run setup wizard" button is clicked +- WHEN the wizard modal opens +- THEN Step 1 (Welcome) MUST be displayed +- AND the step counter MUST show "1 / 5" + +#### Scenario: Next button advances to next step +- GIVEN the wizard is on Step 1 +- WHEN the admin clicks "Next" +- THEN the wizard advances to Step 2 (Groups) +- AND the step counter MUST show "2 / 5" +- AND the Back button MUST become active + +#### Scenario: Back button returns to previous step +- GIVEN the wizard is on Step 3 +- WHEN the admin clicks "Back" +- THEN the wizard returns to Step 2 +- AND no data loss occurs (Step 3 values are preserved if re-visited) + +#### Scenario: Skip button jumps to next step without commitment +- GIVEN the wizard is on Step 4 (Roles, optional) +- WHEN the admin clicks "Skip" +- THEN the wizard advances to Step 5 (Done) +- AND the wizard completion status for Step 4 is marked "skipped" (not "done") + +#### Scenario: Step 1 has no form; only explanatory text +- GIVEN Step 1 (Welcome) is displayed +- WHEN the admin views the step +- THEN the step MUST explain that the setup sets groups, example dashboards and roles in five steps, and that existing dashboards stay as they are +- AND there are no form fields to fill +- AND clicking "Next" advances without persisting any choice + +#### Scenario: Step 5 shows summary and Finish button +- GIVEN the wizard reaches Step 5 (Done) +- WHEN the admin views the step +- THEN the step MUST display a summary: "Your setup is complete. Click Finish to save changes and dismiss the setup banner." +- AND a "Finish" button (not "Next") MUST be present + +#### Scenario: Finish button completes wizard +- GIVEN the admin is on Step 5 with the "Finish" button visible +- WHEN the admin clicks "Finish" +- THEN the system MUST set `launchpad.setup_wizard_complete = true` +- AND the wizard modal MUST close +- AND the admin section MUST reload, banner gone + +#### Scenario: No footer step +- GIVEN the admin walks the wizard from Step 1 to Step 5 +- THEN no step shows the footer editor +- AND the wizard state endpoint reports five steps + +#### Scenario: Wizard progress persists across Back navigation +- GIVEN the wizard is on Step 3 after a group order was chosen on Step 2 +- WHEN the admin clicks Back to Step 2, then clicks Next to Step 3 +- THEN the group order chosen on Step 2 MUST still be present (no data loss) diff --git a/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/tasks.md b/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/tasks.md new file mode 100644 index 000000000..b61da07c6 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/tasks.md @@ -0,0 +1,8 @@ +# Tasks: setup-five-steps-and-admin-tour + +- [x] `lib/Service/SetupWizardService.php`: five steps (Welcome, Groups, Examples, Roles, Done); `computeStepStatuses()` without the footer step +- [x] `src/modals/SetupWizardModal.vue`: drop the footer step, counter "n / 5", welcome text naming groups, example dashboards and roles +- [x] Translations: new welcome text in every shipped locale; strings only the footer step used removed +- [x] Admin tour `launchpad:admin-getting-started`: six stops General, Templates, Roles and rights, Sharing, Kiosk, Demo data, each with one line of explanation +- [x] Unit tests: `SetupWizardServiceTest` (five steps, no footer status), `SetupWizardModal.spec.js` (five steps, no footer editor), the admin tour step list +- [x] Playwright: `tests/e2e/setup-wizard.spec.ts` walks five steps and finishes; the admin tour shows "1 of 6" on a first visit (written, runs in nightly: tests/e2e/setup-wizard.spec.ts, tests/e2e/runtime-shell.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/proposal.md b/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/proposal.md new file mode 100644 index 000000000..2f2085879 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/proposal.md @@ -0,0 +1,16 @@ +# Proposal: sharing-tab-embed-and-conversation + +## Why + +Board LpDelen draws the dashboard settings on the tab Delen with two parts development does not show there. "Insluiten op uw website": a token that is shown once ("Token Website Zuiddrecht is aangemaakt. Kopieer het nu"), a table of tokens with what they show, the allowed website, the state and Intrekken, the code for the website and "Nieuw insluittoken"; revoking takes effect within 60 seconds. And "Gesprek bij dit dashboard": a switch that shows a Talk conversation beside a shared dashboard, which a personal dashboard without shares does not have. + +Embed tokens are specced in `embedded-analytics` (REQ-EMB-001, REQ-EMB-009) and served by `EmbedTokenApiController`, but only from the administration's Embeds tab. The Talk conversation is `dashboard-talk-leaf` (REQ-LEAF-002), which renders on shared dashboards but has no switch in the sharing tab. + +## What changes + +- `embedded-analytics`: embed tokens of a dashboard on its Sharing tab (REQ-EMB-011). +- `dashboard-talk-leaf`: the switch for the conversation on the Sharing tab (REQ-LEAF-006). + +## Impact + +- `src/modals/DashboardConfigModal.vue` (Sharing panel), the embed token API, translations. diff --git a/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md b/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md new file mode 100644 index 000000000..affd13c8c --- /dev/null +++ b/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md @@ -0,0 +1,12 @@ +# Delta: dashboard-talk-leaf + +## ADDED Requirements + +### Requirement: The conversation is switched on from the Sharing tab (REQ-LEAF-006) + +The Sharing tab of a shared dashboard SHALL hold "Conversation beside this dashboard" with a switch "Show the conversation beside the dashboard". A dashboard that is not shared SHALL NOT show this part and SHALL say that the conversation appears once it is shared. + +#### Scenario: A personal dashboard + +- **GIVEN** My workspace is not shared +- **THEN** its Sharing tab says "This dashboard is yours alone. Share it with people or a group and the conversation appears here too." diff --git a/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md b/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md new file mode 100644 index 000000000..f01d0a569 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md @@ -0,0 +1,12 @@ +# Delta: embedded-analytics + +## ADDED Requirements + +### Requirement: Embed tokens on the Sharing tab (REQ-EMB-011) + +The Sharing tab of a dashboard's settings SHALL hold "Embed on your website" for the dashboard's owner and administrators: a list of the dashboard's embed tokens with what they show (the whole dashboard or one widget), the allowed website, the state (Active with its views, or Revoked with the date and reason) and Withdraw; the code for the website of the selected token; and "Create new embed token". A new token SHALL be shown once with Copy and the note that it is not shown again. + +#### Scenario: Create a token + +- **WHEN** Pieter creates the token "Website Zuiddrecht" for the widget Open cases per case type and the site www.zuiddrecht.nl +- **THEN** the token is shown once with Copy, the table lists it as Active, and the code for the website shows the iframe diff --git a/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/tasks.md b/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/tasks.md new file mode 100644 index 000000000..2832e5934 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/tasks.md @@ -0,0 +1,8 @@ +# Tasks: sharing-tab-embed-and-conversation + +- [x] Sharing tab: Embed on your website with the token shown once, the token table, the code for the website and New embed token (`SharingEmbedTokens.vue`; administrators only while the embed token API is admin-only) +- [x] Revoke from the table, effective within 60 seconds (REQ-EMB-009) (Withdraw uses the existing token revocation) +- [x] Sharing tab: Conversation beside this dashboard switch, only for a dashboard that is shared (`SharingConversation.vue`, `conversation_enabled` column, `DashboardDiscussion` honours it) +- [x] Translations in every shipped locale +- [x] Unit tests: token shown once, revoke, switch hidden on an unshared dashboard +- [x] Playwright: create an embed token for one widget and copy the code (written in `tests/e2e/sharing-tab-embed-and-conversation.spec.ts`, runs in nightly; not verified on a live instance) diff --git a/openspec/changes/archive/2026-11-24-start-page-board-sync/proposal.md b/openspec/changes/archive/2026-11-24-start-page-board-sync/proposal.md new file mode 100644 index 000000000..8a67e9602 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-start-page-board-sync/proposal.md @@ -0,0 +1,27 @@ +# Proposal: start-page-board-sync + +## Why + +Board LpVandaag draws the start page with one control in the header, the menu Meer as board LpMeer draws it, and +"geen knop om de startpagina aan te passen". The spec `lpvandaag-start-page` still requires a "Startpagina aanpassen" +button and an older Meer menu with a Launchpad group and Versies and Instellingen under Dit dashboard. That +requirement contradicts runtime-shell REQ-SHELL-013, which the code follows. + +Two things the board draws are built but not specced: + +- the header greets the reader: "Goedemiddag, Pieter · maandag 5 oktober 2026" (board LpStart, LpVandaag), with the + week number on the start page; +- Vandaag eerst draws one card per record that needs attention, named by the record, with the reason and an action + such as "Zaak openen" (LpVandaag shows two cards with "Zaak openen", not one count). Built on development in + 7409fd00 (`content.itemCards`). + +## What changes + +- `lpvandaag-start-page`: the Meer requirement defers to REQ-SHELL-013 and drops "Startpagina aanpassen". A new + requirement for the greeting in the start page header. +- `attention-feed`: a new requirement for one card per record (`itemCards`). + +## Impact + +- The greeting and the item cards exist; their tasks are tests and spec tags. The Meer change removes nothing from + the code, which already follows REQ-SHELL-013. diff --git a/openspec/changes/archive/2026-11-24-start-page-board-sync/specs/attention-feed/spec.md b/openspec/changes/archive/2026-11-24-start-page-board-sync/specs/attention-feed/spec.md new file mode 100644 index 000000000..ba7948dca --- /dev/null +++ b/openspec/changes/archive/2026-11-24-start-page-board-sync/specs/attention-feed/spec.md @@ -0,0 +1,25 @@ +# Delta: attention-feed + +## ADDED Requirements + +### Requirement: Vandaag eerst can draw one card per record (REQ-ATT-007) + +An attention widget with `content.itemCards: true` SHALL ask every source for up to `content.limit` records instead of +one count, and SHALL draw one card per record: the record's own name as the title, the source's title as the reason +("De beslistermijn loopt vandaag af"), the app that owns it, and one action that opens the record, named by the +source ("Zaak openen", "Beantwoorden", "Paraferen") or "Open {item}" when the source names none. The cards SHALL keep +the merge and ranking order of REQ-ATT-004 and SHALL stop at `content.limit` in total. Without `itemCards` the widget +SHALL draw one item per source with its count, as before. + +#### Scenario: Two cases due today + +- **GIVEN** dossiq reports two cases whose decision term ends today, and the widget sets `itemCards: true` and `limit: 3` +- **WHEN** Pieter opens the start page +- **THEN** Vandaag eerst shows two cards, each named by its case, each with "De beslistermijn loopt vandaag af" and "Zaak openen" +- **AND** "Zaak openen" opens that case in dossiq + +#### Scenario: Without item cards + +- **GIVEN** the same feed and a widget without `itemCards` +- **WHEN** the widget renders +- **THEN** it shows one item for the dossiq source with the count 2 diff --git a/openspec/changes/archive/2026-11-24-start-page-board-sync/specs/lpvandaag-start-page/spec.md b/openspec/changes/archive/2026-11-24-start-page-board-sync/specs/lpvandaag-start-page/spec.md new file mode 100644 index 000000000..a6121b2af --- /dev/null +++ b/openspec/changes/archive/2026-11-24-start-page-board-sync/specs/lpvandaag-start-page/spec.md @@ -0,0 +1,50 @@ +# Delta: lpvandaag-start-page + +## MODIFIED Requirements + +### Requirement: One Meer menu holds the start page's actions + +The start page SHALL show one control in its header: the menu "Meer", the same menu as on every other page +(runtime-shell REQ-SHELL-013, board LpMeer). There SHALL be no "Startpagina aanpassen" button, no Bewerken button and +no other control for the dashboard's actions. Meer SHALL hold, left, Dashboards (every dashboard the person sees, the +open one checked, the markers standaard, gedeeld and groep, and "Alle dashboards"), and right, Dit dashboard +(Bewerken, Widget toevoegen, Delen, Link naar dit dashboard kopiëren, Kopie maken als nieuw dashboard, Als standaard +instellen, and Verwijderen last), with below it the folding item Instellingen (Persoonlijke instellingen, +Beheerinstellingen for an administrator only, Marktplaats, Sjablonen, Rapporten, Flows, Koppelingen, Documentatie, +Functies en roadmap). Versies, publishing, its schedule and the scheduled exports are tabs of the dashboard settings, +not menu items. Each action SHALL keep its gate. No action SHALL appear twice. + +#### Scenario: An administrator opens Meer + +- **GIVEN** the start page, for an administrator +- **WHEN** they open "Meer" and unfold Instellingen +- **THEN** "Beheerinstellingen" appears once, under Instellingen, and "Sjablonen" is in the same group +- **AND** the header shows no "Startpagina aanpassen" button + +#### Scenario: A member opens Meer on a shared dashboard + +- **GIVEN** a member on a dashboard shared with them +- **WHEN** they open "Meer" +- **THEN** Dit dashboard offers "Als standaard instellen", and neither Verwijderen nor Versies + +## ADDED Requirements + +### Requirement: The start page greets the reader + +A header placement with `content.greeting: true` SHALL open with a greeting for the part of the day ("Goedemorgen" +before 12:00, "Goedemiddag" before 18:00, "Goedenavond" after; in English "Good morning", "Good afternoon", "Good +evening") and the reader's first name, followed by today's date in the reader's language. With `content.showWeek: +true` it SHALL add the week number. The greeting SHALL use the reader's display name and time zone, and SHALL be text, +not an image, so a screen reader reads it. + +#### Scenario: Pieter opens the start page after lunch + +- **GIVEN** Pieter Jansen, language Dutch, opens the start page on Monday 5 October 2026 at 13:10 +- **WHEN** the header renders with `greeting` and `showDate` +- **THEN** it reads "Goedemiddag, Pieter · maandag 5 oktober 2026" + +#### Scenario: The week number + +- **GIVEN** the header sets `showWeek: true` +- **WHEN** Pieter opens it on Monday 5 October 2026 +- **THEN** the header also shows "week 41" diff --git a/openspec/changes/archive/2026-11-24-start-page-board-sync/tasks.md b/openspec/changes/archive/2026-11-24-start-page-board-sync/tasks.md new file mode 100644 index 000000000..be2eee3a3 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-start-page-board-sync/tasks.md @@ -0,0 +1,6 @@ +# Tasks: start-page-board-sync + +- [x] Header greeting: confirm the header placement renders the day-part greeting, first name, date and week number from the reader's display name, language and time zone; add the `@spec` tag to the code that does it +- [x] Attention widget: `@spec` tags for `itemCards` in `AttentionWidget.vue` and `expandToRecords` in `services/attentionFeed.js` pointing at REQ-ATT-007 +- [x] Unit tests: greeting per part of the day (11:59, 12:00, 17:59, 18:00) and the week number; `itemCards` true and false in `AttentionWidget.spec.js`, the limit across sources +- [x] Playwright: the start page header shows only Meer and the greeting; Vandaag eerst shows one card per due case with "Zaak openen" (written, runs in nightly: tests/e2e/lpvandaag-start-page.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-version-change-notes/proposal.md b/openspec/changes/archive/2026-11-24-version-change-notes/proposal.md new file mode 100644 index 000000000..8c76e809f --- /dev/null +++ b/openspec/changes/archive/2026-11-24-version-change-notes/proposal.md @@ -0,0 +1,24 @@ +# Proposal: version-change-notes + +## Why + +Board LpVersies draws the dashboard settings on the tab Versies: a table "Wanneer, Door, Wat veranderde" with rows such +as "Widget Nieuws verplaatst", "Widget Verjaardagen verwijderd", "Kolommen van 8 naar 12" and, by "Sjabloon +Intranet", "Bijgewerkt vanuit het sjabloon"; the current version marked "Huidige versie"; and a confirmation that +names what comes back ("Met deze versie komt de widget Verjaardagen terug en verdwijnen de wijzigingen van daarna"). + +- The "What changed" note of an automatic snapshot is built (#1611, `SnapshotChangeDescriber`) and tagged to the + versioning spec as a whole, without a requirement. +- A template re-sync does not note that the copy was updated from the template, nor by which template. +- REQ-VERSUI-001 still describes a "Version history" entry in the dashboard menu, which REQ-DASH-039 and runtime-shell + REQ-SHELL-013 replaced with the Versions tab. + +## What changes + +- `dashboard-versioning`: REQ-VERSUI-001 describes the Versions tab and its columns; REQ-VERSUI-004 specs the "What + changed" note; REQ-VERSUI-005 specs the note and author of a version written by a template re-sync. + +## Impact + +- `SnapshotChangeDescriber` and `DashboardVersionService` (tags and the re-sync note), the re-sync service, the + Versions tab, translations. diff --git a/openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md b/openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md new file mode 100644 index 000000000..f79b68b8b --- /dev/null +++ b/openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md @@ -0,0 +1,62 @@ +# Delta: dashboard-versioning + +## MODIFIED Requirements + +### Requirement: The owner sees the version history (REQ-VERSUI-001) + +The versions of a dashboard MUST be the tab Versions of the dashboard settings (dashboards REQ-DASH-039, board LpVersies), offered to the dashboard owner and to administrators when versioning is supported for the dashboard. There MUST be no "Version history" entry in the dashboard menu or in More. The tab MUST list versions newest first in the columns When, By and What changed, and MUST mark the newest as the current version. + +#### Scenario: Owner opens the history + +- **GIVEN** Sanne owns the personal dashboard "Mijn week" and it has four saved versions +- **WHEN** she opens the dashboard settings and chooses the tab Versions +- **THEN** the tab lists the four versions newest first with when, by whom and what changed, the newest marked as the current version + +#### Scenario: Colleague sees no entry + +- **GIVEN** Pieter can view but does not own "Mijn week" and is not an administrator +- **WHEN** he opens More on the dashboard +- **THEN** no version entry is shown and he cannot open the dashboard settings + +#### Scenario: Unsupported dashboard + +- **GIVEN** a groupfolder-backed dashboard for which `modeSupported` is false +- **WHEN** the owner opens the tab Versions +- **THEN** the tab says this dashboard keeps no versions + +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed, so no dashboard answers `modeSupported: false`. + +## ADDED Requirements + +### Requirement: Each automatic version says what changed (REQ-VERSUI-004) + +An automatic snapshot (REQ-VERS-001) MUST carry a note of at most 120 characters that names what changed since the +previous snapshot: "Dashboard renamed to {name}", "Columns from {old} to {new}", "Widget {title} added", "Widget +{title} removed", "Widget {old} renamed to {new}", "Widget {title} moved", "Widget {title} resized". When more than one +thing changed, the note MUST name the first and count the rest ("Widget Inbox added and 2 more changes"). A widget is +named by its title, else by its type. An explicit snapshot with a note of its own (REQ-VERSUI-002) MUST keep that note. +Notes MUST be in the language of the person who made the change. + +#### Scenario: A widget moved + +- **GIVEN** Pieter moves the widget Nieuws on Intranet Zuiddrecht +- **WHEN** the snapshot is written +- **THEN** the Versions tab shows "Widget Nieuws moved" by Pieter Jansen + +#### Scenario: Several changes at once + +- **GIVEN** Femke adds the widget Inbox, removes Oud nieuws and changes the columns from 8 to 12 in one save +- **WHEN** the snapshot is written +- **THEN** its note reads "Widget Inbox added and 2 more changes" + +### Requirement: A template update is noted as such (REQ-VERSUI-005) + +When a template re-sync (admin-templates REQ-RESYNC-001) changes a copy, the version it writes MUST name the template as +its author ("Template {name}") and MUST carry the note "Updated from the template", instead of the administrator who +ran the re-sync and a list of widget changes. + +#### Scenario: Intranet updated from its template + +- **GIVEN** Intranet Zuiddrecht is a copy of template "Intranet" +- **WHEN** the administrator re-syncs the template +- **THEN** the copy's Versions tab shows a version by "Template Intranet" with "Updated from the template" diff --git a/openspec/changes/archive/2026-11-24-version-change-notes/tasks.md b/openspec/changes/archive/2026-11-24-version-change-notes/tasks.md new file mode 100644 index 000000000..29e22a41a --- /dev/null +++ b/openspec/changes/archive/2026-11-24-version-change-notes/tasks.md @@ -0,0 +1,9 @@ +# Tasks: version-change-notes + +- [x] `SnapshotChangeDescriber` and `DashboardVersionService`: `@spec` tags to REQ-VERSUI-004 +- [x] Re-sync service: write the copy's version with author "Template {name}" and the note "Updated from the template" +- [x] `VersionsTab.vue`: columns When, By, What changed; the newest marked as the current version; a template author shown as the template's name +- [x] Remove any remaining "Version history" entry from the dashboard menus +- [x] Translations in every shipped locale +- [x] Unit tests: each note kind, the "and N more changes" count, title fallback to type, explicit note kept; the re-sync version author and note +- [x] Playwright: move a widget, open the tab Versions and read "Widget {title} moved" (written, runs in nightly: tests/e2e/dashboard-versioning-ui.spec.ts) diff --git a/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/proposal.md b/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/proposal.md new file mode 100644 index 000000000..cef9c225c --- /dev/null +++ b/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/proposal.md @@ -0,0 +1,13 @@ +# Proposal: visibility-dialog-board-sync + +## Why + +Board LpZichtbaarheid draws "Wie ziet deze widget?": whether all rules or one rule must match as two choice cards, one card per rule (Groups as chips, Times, Period, Profile field) with Edit and delete, "Add rule", and "View as" with a person and a moment and a sentence that says whether that person sees the widget and why. The rules dialog on development (`VisibilityRulesModal.vue`, titled "Visibility rules") lists rules differently, and it opens only from the widget's right-click context menu in edit mode, which a keyboard user and a measurement cannot reach. + +## What changes + +- `conditional-visibility-editor`: the dialog as the board draws it (REQ-CVUI-006) and a "Who sees this widget?" item in the widget's menu in edit mode (REQ-CVUI-007). + +## Impact + +- `src/modals/VisibilityRulesModal.vue`, the widget menu (`WidgetContextMenu.vue` and the placement action menu), translations. diff --git a/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md b/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md new file mode 100644 index 000000000..f46ddc673 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md @@ -0,0 +1,65 @@ +# Delta: conditional-visibility-editor + +## ADDED Requirements + +### Requirement: The rules dialog as LpZichtbaarheid draws it (REQ-CVUI-006) + +The dialog SHALL be titled "Who sees this widget?" under "<widget> · <dashboard>", SHALL offer "If all rules match" and "If one rule matches" as choice cards, SHALL show one card per rule with its kind (Groups, Times, Period, Profile field), its value and Edit and delete buttons, then "Add rule", and SHALL end with "View as": a person and a moment, and a sentence that says whether that person sees the widget and why. + +#### Scenario: View as Sanne + +- **GIVEN** the rules ask for group KCC and Monday to Friday 08:00 to 17:00 +- **WHEN** the editor picks Sanne de Vries and Tuesday 13 October 10:00 +- **THEN** the sentence reads that Sanne sees this widget, because she is in KCC and the moment is within the times + +### Requirement: The dialog is in the widget's menu (REQ-CVUI-007) + +In edit mode the widget's menu SHALL hold "Who sees this widget?", which opens the dialog, so it is reachable by keyboard and not only by right-click. + +#### Scenario: From the menu + +- **WHEN** the editor opens the menu of the News widget and chooses Who sees this widget? +- **THEN** the dialog opens for that widget + +## MODIFIED Requirements + +### Requirement: REQ-CVUI-004 Preview As Audience and Date + +The editor MUST provide a "View as" affordance that shows the effective visibility of the current rule set for one author-chosen person at one author-chosen moment, before the rules are published, so an author can catch a mis-scoped rule (e.g. an exclude rule that hides the widget from everyone) prior to saving. The person defaults to the author; the person's own groups and profile values are resolved on the server. The preview MUST use the placement's match mode (all or one rule, REQ-VIS-014) and MUST say in one sentence whether that person sees the widget and why (REQ-CVUI-006). + +#### Scenario: Preview shows visible for a matching audience +- GIVEN the editor holds one include group rule with groups ["marketing"] +- WHEN the author views as a person in "marketing" at datetime "2026-07-23T14:30" +- THEN `useVisibilityPreview` MUST call `POST /api/visibility/preview` with the current rule set, that person as `context.userId`, that moment, the match mode and the placement id +- AND the result MUST display "Visible" with an icon and text (not colour alone) +- AND the matched include rule MUST be indicated +- AND the sentence MUST say that the person sees this widget, because the person is in "marketing" + +#### Scenario: Preview shows hidden for a non-matching audience +- GIVEN the editor holds one include group rule with groups ["marketing"] +- WHEN the author views as a person in "engineering" only, at any moment +- THEN the result MUST display "Hidden" +- AND no include rule MUST be indicated as matched +- AND the sentence MUST say that the person does not see this widget, because the person is not in "marketing" + +#### Scenario: Preview reflects an exclude override +- GIVEN the editor holds an include group rule (groups ["marketing"], matches) and an exclude date rule (2026-07-01..2026-07-31) +- WHEN the author views as a person in "marketing" at datetime "2026-07-15T10:00" +- THEN the result MUST display "Hidden" +- AND the matched exclude rule MUST be indicated as the reason + +#### Scenario: Preview evaluates unsaved edits +- GIVEN the author has added a rule row but has not yet saved it +- WHEN the author runs preview +- THEN the preview MUST evaluate the in-editor (unsaved) rule set +- AND the preview MUST NOT persist any rule + +#### Scenario: Preview uses the same rule shape as the editor emits +- GIVEN the editor's rule rows and the preview request +- WHEN `useVisibilityPreview` builds the request body +- THEN it MUST send the exact `ruleConfig` shape the rows emit, with no translation layer that could drift from the saved shape + +#### Scenario: Viewing as another person needs the rules editor +- GIVEN the author may not edit the placement's rules +- WHEN a preview names another person as `context.userId` +- THEN the endpoint MUST answer HTTP 403 and evaluate nothing diff --git a/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md b/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md new file mode 100644 index 000000000..c460abaff --- /dev/null +++ b/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility/spec.md @@ -0,0 +1,21 @@ +# Delta: conditional-visibility + +## ADDED Requirements + +### Requirement: All or one rule must match (REQ-VIS-014) + +A widget placement SHALL store how its include rules combine in `ruleMatch`: `any` (one include rule that matches is enough, the behaviour of REQ-VIS-009) or `all` (every include rule must match). A placement without a stored mode SHALL read as `any`, so every existing dashboard stays as it is. Exclude rules SHALL keep hiding the widget when any of them matches, in both modes. The mode SHALL be evaluated in `VisibilityChecker`, the one place the rules are combined, at render time and in the preview. `PUT /api/widgets/{placementId}` SHALL accept only `any` or `all` (HTTP 400 otherwise), and only from the dashboard owner or an administrator (HTTP 403 otherwise). Copying a dashboard, a template and an export SHALL carry the mode. + +#### Scenario: All rules must match + +- **GIVEN** widget placement 10 has `ruleMatch: all` and two include rules: group KCC and Monday to Friday 08:00 to 17:00 +- **AND** the user is in KCC and it is Saturday 10:00 +- **WHEN** the dashboard is rendered +- **THEN** the widget MUST be hidden, because the time rule does not match + +#### Scenario: One rule is enough + +- **GIVEN** the same placement with `ruleMatch: any` +- **AND** the user is in KCC and it is Saturday 10:00 +- **WHEN** the dashboard is rendered +- **THEN** the widget MUST be visible, because the group rule matches diff --git a/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/tasks.md b/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/tasks.md new file mode 100644 index 000000000..892c4e3d1 --- /dev/null +++ b/openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/tasks.md @@ -0,0 +1,7 @@ +# Tasks: visibility-dialog-board-sync + +- [x] Dialog: match all or one as choice cards, a card per rule with Edit and delete, Add rule, View as with the sentence +- [x] Who sees this widget? in the widget's menu in edit mode, not only on right-click +- [x] Translations in every shipped locale +- [x] Unit tests: the sentence for a person who does and does not see the widget +- [x] Playwright: open the dialog from the widget menu and check View as (written, runs in nightly: tests/e2e/visibility-dialog.spec.ts) diff --git a/openspec/changes/archive/2026-11-25-dashboard-connections-widget/proposal.md b/openspec/changes/archive/2026-11-25-dashboard-connections-widget/proposal.md new file mode 100644 index 000000000..bf89ef655 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-connections-widget/proposal.md @@ -0,0 +1,20 @@ +# Proposal: dashboard-connections-widget + +## Why + +Board LpManagement ends with a card "Koppelingen van dit dashboard": the outside connections this dashboard's widgets +use, each with its state, its last success and its last error. The parity row int-connections-status points at +REQ-LP-CONN-004, which is an admin page of all launchpad connections under settings, not a card on a dashboard. The +demo seed fills the card with a text widget, because no widget type can show it. + +## What changes + +- `app-connections`: a `connections` widget type, "Koppelingen van dit dashboard" (REQ-LP-CONN-005). It lists the + declared connections (lib/Settings/connections.json) that the widgets on its own dashboard use, with the status, + last success and last error integriq holds for each. +- Which widget uses which connection is a mapping in configuration next to the declaration, not code per widget type. + +## Impact + +- A widget renderer and form, a `uses` list per declared connection (widget types), the picker entry, translations. +- Without integriq the widget says the connections cannot be shown; it never calls a connection itself. diff --git a/openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md b/openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md new file mode 100644 index 000000000..0706cd89f --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md @@ -0,0 +1,30 @@ +# Delta: app-connections + +## ADDED Requirements + +### Requirement: REQ-LP-CONN-005 A dashboard shows the state of its own connections + +LaunchPad SHALL offer a `connections` widget type ("Koppelingen van dit dashboard", board LpManagement). Each +connection declared in `lib/Settings/connections.json` SHALL name the widget types that use it (`uses`, for example +`live-tiles` for `livetile`, `news-feeds` for `news`, `ics-calendars` for `calendar`, `health-ping` for tiles with a +health ping). The widget SHALL list, once each, the connections that the placements on its own dashboard use, with the +connection's name, its status as the Integrations page names it (REQ-LP-CONN-004), the time of its last success and +the time and message of its last error, as integriq holds them in `integriq/app_connection`. It SHALL read those rows +with the viewer's own session and SHALL NOT call any connection itself. A message SHALL show at most a host, as +REQ-LP-CONN-003 reports it. A connection no placement uses SHALL NOT be listed. Without integriq the widget SHALL say +"Connection states need the Integrations app" and the picker SHALL not offer it. + +#### Scenario: The management dashboard's connections + +- **GIVEN** Managementinformatie holds the live tile "Wachttijd KCC" and a news widget +- **AND** integriq holds `live-tiles` as working, last success 10:44, and `news-feeds` as error since 09:30 with "feeds.example.nl answered 503" +- **WHEN** Pieter opens the dashboard +- **THEN** "Koppelingen van dit dashboard" lists Live tiles with "werkt" and last success 10:44, and News feeds with the error, its time and the host +- **AND** it does not list the weather provider, which no widget on this dashboard uses + +#### Scenario: Without integriq + +- **GIVEN** integriq is not installed +- **WHEN** a dashboard with the connections widget renders +- **THEN** the widget says "Connection states need the Integrations app" +- **AND** the widget picker does not offer "Koppelingen van dit dashboard" diff --git a/openspec/changes/archive/2026-11-25-dashboard-connections-widget/tasks.md b/openspec/changes/archive/2026-11-25-dashboard-connections-widget/tasks.md new file mode 100644 index 000000000..f9f4a9fc6 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-connections-widget/tasks.md @@ -0,0 +1,9 @@ +# Tasks: dashboard-connections-widget + +- [x] `lib/Settings/connections.json`: a `uses` list of widget types per declared connection (`health-ping` also for tiles with a health ping); keep the file valid against integriq's schema (extra key allowed, or move the map to `lib/Settings/connection-uses.json` if the schema refuses it) (integriq's schema refuses extra keys, so the map is `lib/Settings/connection-uses.json`) +- [x] `ConnectionsWidget.vue` (`connections` type, `requiresApp: 'integriq'`): the connections the dashboard's placements use, from `integriq/app_connection` rows with `app = launchpad`, read with the viewer's session; status label as on the Integrations page; last success, last error and message +- [x] Register `connections` in `lib/widget-types.json` and the picker, offered only with integriq +- [x] Demo seed: the management dashboard's card becomes a `connections` widget +- [x] Translations in every shipped locale +- [x] Unit tests: the uses-map to connection list (dedupe, unused left out); status labels; without integriq +- [x] Playwright: a dashboard with a live tile and the connections widget lists Live tiles with its state (`tests/e2e/dashboard-connections-widget.spec.ts` 1/1 green on a sandbox Nextcloud 34.0.6 + MariaDB with integriq development, 25 Nov 2026; without integriq the test skips by design) diff --git a/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/proposal.md b/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/proposal.md new file mode 100644 index 000000000..f9a499594 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/proposal.md @@ -0,0 +1,17 @@ +# Proposal: dashboard-first-load-from-initial-state + +## Why + +Speed budget (hydra ADR-124): every main page usable within 300 ms warm. The workspace page already reads the visible dashboards and the active dashboard on the server to fill its initial state, and then the dashboard store asks `GET /api/dashboards/visible` and `GET /api/dashboard` for the same data again before it draws anything: about 250 ms of round trip on every page load (PERF-HANDOFF, launchpad). + +## What changes + +- `initial-state-contract`: ADDED REQ-INIT-006. The workspace page carries the store's first load as the optional key `dashboardFirstLoad`: `{visible, active}` with exactly the payloads of those two endpoints. The store takes it once, on its first load; every later load asks the API. +- The two payloads are built by one class (`DashboardPayloads`) that both the API controller and the page use, so they cannot drift apart. +- A caller the action matrix refuses either action gets no first load, and the store meets the same refusal from the API as before. + +## Impact + +- `lib/Controller/DashboardPayloads.php` (new), `DashboardApiController` (`visible`, `getActive` delegate to it), `PageSources`, `PageController::index`, `InitialStateBuilder::setDashboardFirstLoad`. +- `src/utils/loadInitialState.js` (`takeDashboardFirstLoad`), `src/stores/dashboard.js` (`loadDashboards`). +- The key is optional, like `deepLinkPath`: an older server leaves it out and the store fetches, so the schema version stays 3. diff --git a/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/specs/initial-state-contract/spec.md b/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/specs/initial-state-contract/spec.md new file mode 100644 index 000000000..e31e5b340 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/specs/initial-state-contract/spec.md @@ -0,0 +1,27 @@ +# Delta: initial-state-contract + +## ADDED Requirements + +### Requirement: The workspace carries the first dashboard load (REQ-INIT-006) + +The Workspace page SHOULD carry the optional key `dashboardFirstLoad`: `{visible, active}`, where `visible` is exactly the payload `GET /api/dashboards/visible` answers for the caller and `active` is exactly the payload of `GET /api/dashboard`, or `null` when the caller has no dashboard. Both MUST be built by the same code as those endpoints. The key MUST be left out when the caller may not perform `dashboard.visible` or `dashboard.get-active`. The dashboard store MUST take the key once, on its first load, instead of requesting the two endpoints, and MUST request them on every later load and whenever the key is missing (default `null`). + +#### Scenario: The workspace opens without asking for its dashboards again + +- **GIVEN** Pieter may read his dashboards +- **WHEN** he opens the workspace +- **THEN** the page carries his visible dashboards and his active dashboard in `dashboardFirstLoad` +- **AND** the store shows them without requesting `/api/dashboards/visible` or `/api/dashboard` + +#### Scenario: A later load asks the API + +- **GIVEN** the workspace has opened from `dashboardFirstLoad` +- **WHEN** the store loads the dashboards again, for example after a dashboard limit refusal +- **THEN** it requests both endpoints + +#### Scenario: A refused caller gets no first load + +- **GIVEN** the action matrix refuses Pieter `dashboard.visible` +- **WHEN** he opens the workspace +- **THEN** the page carries no `dashboardFirstLoad` +- **AND** the store requests the endpoints and meets the same refusal diff --git a/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md b/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md new file mode 100644 index 000000000..e93b0e244 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md @@ -0,0 +1,7 @@ +# Tasks: dashboard-first-load-from-initial-state + +- [x] 1. One builder for the visible-dashboards list and the active-dashboard envelope, used by `GET /api/dashboards/visible` and `GET /api/dashboard` +- [x] 2. The workspace page carries `dashboardFirstLoad` (`{visible, active}`) when the caller may read both, built by that builder +- [x] 3. The dashboard store's first load takes it from the initial state instead of fetching; later loads fetch +- [x] 4. Unit tests: the builder (list, quota envelope, active envelope, refusal), the page key, the builder key, the reader (once, missing, malformed) and the store (no fetch first, fetch after) +- [x] 5. Measure on a live instance: the workspace opens without the two dashboard requests (perf spec, before/after): measured live 25 Nov 2026 (sandbox Nextcloud 34, launchpad development): opening the workspace as admin, first and warm load, sent no `GET /api/dashboards/visible` and no `GET /api/dashboard`; the page carries `dashboardFirstLoad` diff --git a/openspec/changes/archive/2026-11-25-dashboard-period-and-download/proposal.md b/openspec/changes/archive/2026-11-25-dashboard-period-and-download/proposal.md new file mode 100644 index 000000000..6cb594b92 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-period-and-download/proposal.md @@ -0,0 +1,26 @@ +# Proposal: dashboard-period-and-download + +## Why + +Board LpManagement draws the header of a management dashboard: "Managementinformatie", "Downloaden" next to Meer, the +line "Groepsdashboard van Bedrijfsvoering · alleen bekijken · bijgewerkt 10:45", and a period choice "Deze maand, +Kwartaal, Jaar" that the figures below follow. DEMO-SEED names it the period selector. + +- The line under the title is built (`DashboardPageHeader.vue`: kind and last change), but has no requirement of its + own and does not say what the reader may do. +- No spec or code has a period choice for a whole dashboard. Widgets that read a register query each carry their own + fixed date filter. +- No spec or code has a one-off download of a dashboard. Scheduled exports (REQ-SCH-009 "Run now") render a dashboard + on a schedule or on demand for its owner, not for a reader. + +## What changes + +- `dashboards`: the header line names the kind of dashboard, what the reader may do and when it last changed + (REQ-DPD-001); a period choice that widgets with a date field follow, kept in the address (REQ-DPD-002); a Download + action that gives the reader the dashboard as a PDF now (REQ-DPD-003). +- The period is configuration: a widget's data source names its date field. No widget type is special-cased. + +## Impact + +- `DashboardPageHeader.vue`, a period control in the header, the register-query data sources (`ChartHost`, `stat`, + `pie-chart`, `graph`, `table`), the export renderer of scheduled-exports reused for the download, translations. diff --git a/openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md b/openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md new file mode 100644 index 000000000..8c15cdf1a --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md @@ -0,0 +1,68 @@ +# Delta: dashboards + +## ADDED Requirements + +### Requirement: The header says what dashboard this is and what the reader may do (REQ-DPD-001) + +Under the dashboard title the header SHALL show one line: the kind of dashboard with its icon ("Persoonlijk +dashboard", "Groepsdashboard van {group}", "Gedeeld door {person}"), what the reader may do on it ("alleen bekijken", +"u mag widgets toevoegen", or nothing extra with full rights), "opent als eerste" when it is the reader's default, and +when it last changed ("bijgewerkt 10:45" today, the weekday within the last week, the date before that), separated by +" · ". + +#### Scenario: A view-only group dashboard + +- **GIVEN** Pieter has view-only rights on the group dashboard Managementinformatie of Bedrijfsvoering, last changed today at 10:45 +- **WHEN** he opens it +- **THEN** the line under the title reads "Groepsdashboard van Bedrijfsvoering · alleen bekijken · bijgewerkt 10:45" + +#### Scenario: Pieter's own default dashboard + +- **GIVEN** Mijn werkplek is Pieter's personal default dashboard +- **WHEN** he opens it +- **THEN** the line reads "Persoonlijk dashboard · opent als eerste" followed by when it last changed + +### Requirement: A dashboard can have a period that its figures follow (REQ-DPD-002) + +A widget whose data source is a register query MAY name the date field of its records in `content.source.periodField`. +When at least one widget on a dashboard names one, the header SHALL show a period choice: This month, Quarter, Year +(nl Deze maand, Kwartaal, Jaar), This month first. The chosen period SHALL be added to the query of every widget that +names a period field, as that field between the period's start and now, and SHALL be kept in the address +(`?period=month|quarter|year`) so a copied link opens with the same period. A widget without a period field SHALL +ignore the period, and its card SHALL NOT claim to follow it. The period SHALL work alongside the cross-widget filter +(cross-widget-filter) and SHALL be read-only: choosing it never changes the stored dashboard. + +#### Scenario: Pieter looks at the quarter + +- **GIVEN** Managementinformatie with "Zaken per status" whose source names `periodField: "startDate"`, and a Power BI embed +- **WHEN** Pieter chooses Kwartaal +- **THEN** "Zaken per status" counts only cases started this quarter +- **AND** the address carries `period=quarter` +- **AND** the Power BI embed is unchanged + +#### Scenario: A dashboard without dated sources + +- **GIVEN** a dashboard on which no widget names a period field +- **WHEN** it renders +- **THEN** the header shows no period choice + +### Requirement: A reader can download the dashboard (REQ-DPD-003) + +The header SHALL offer "Download" (nl "Downloaden") to everyone who can open the dashboard, also with view-only +rights. It SHALL give the reader the dashboard as a PDF, rendered as the reader sees it now, with the period and the +cross-widget filter applied and the reader's own visibility rules respected, rendered in the reader's own browser +(print styles and the browser's print dialog; decision 24 Nov 2026), not on the server. Nothing SHALL be stored or sent. A widget the renderer cannot draw (an embedded page) SHALL be named in the +PDF with a line that it is not included. The kiosk view and the public view SHALL NOT offer it. + +#### Scenario: Pieter downloads the quarter + +- **GIVEN** Pieter has view-only rights on Managementinformatie, with Kwartaal chosen +- **WHEN** he chooses Downloaden +- **THEN** his browser saves a PDF of Managementinformatie with the quarter's figures +- **AND** no scheduled export or run is created + +#### Scenario: The embedded report + +- **GIVEN** the dashboard holds the Power BI embed "Rapport Sociaal domein" +- **WHEN** Pieter downloads it +- **THEN** the PDF names "Rapport Sociaal domein" with a line that embedded pages are not included diff --git a/openspec/changes/archive/2026-11-25-dashboard-period-and-download/tasks.md b/openspec/changes/archive/2026-11-25-dashboard-period-and-download/tasks.md new file mode 100644 index 000000000..ad03ad116 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-dashboard-period-and-download/tasks.md @@ -0,0 +1,11 @@ +# Tasks: dashboard-period-and-download + +- [x] `DashboardPageHeader.vue`: the reader's rights ("alleen bekijken", "u mag widgets toevoegen") in the meta line; `@spec` tags to REQ-DPD-001 +- [x] Period control in the header, shown when a placement's source names `periodField`; This month, Quarter, Year; kept in `?period=` +- [x] Register-query sources (`ChartHost` and the `stat`, `pie-chart`, `graph`, `table` sources): add the period range on `periodField` to the query; ignore it without a period field (ChartHost for `pie-chart`/`graph`; WidgetRenderer `periodContent` for `stat` (`content.source`), `stats-block` (`content.dataSource`) and `table` (its own `filter`)) +- [x] Widget forms with a register source: an optional "Date field for the period" select over the schema's date properties (launchpad's chart form for `pie-chart` and `graph` done: PeriodFieldSelect, date fields read from a sample of the source's records; the `stat`, `stats-block` and `table` forms live in nextcloud-vue and get it from nextcloud-vue >= 2.215.0 (CnPeriodFieldSelect, nextcloud-vue #2334), which launchpad now requires; Views provides `cnOffersPeriodField`) +- [x] Download renders in the caller's own browser (decision 24 Nov 2026, option (b): print CSS + `window.print`, no server render, no endpoint, no new credential, nothing stored): `utils/printDashboard.js` prints under the dashboard name, `styles/print.css` leaves out the top bar, the docked menu and the button; the period and filter are those on screen; `IframeWidget` prints "<title>: embedded pages are not included in the download" instead of the frame +- [x] "Downloaden" in the header, absent in kiosk and public views (the header is not drawn in kiosk, edit mode or the public share view) +- [x] Translations in every shipped locale +- [x] Unit tests: meta line per kind and right; period range per choice and on the query; no period choice without a period field; Download for a view-only reader, printed under the dashboard name, nothing sent to the server, the embed named (no endpoint, so no server permission check or run-row: decision (b)) +- [x] Playwright: choose Kwartaal and see the address and a figure change; download the dashboard as a view-only reader (tests/e2e/dashboard-period-and-download.spec.ts 6/6 and tests/e2e/dashboard-download.spec.ts 3/3 live, 25 Nov 2026, sandbox Nextcloud 34 + MariaDB + Redis; the stand-in register answer carries the `startDate[gte]` the query sent; the header now names the group of a group dashboard, REQ-DPD-001) diff --git a/openspec/changes/widget-calculated-fields/.openspec.yaml b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/.openspec.yaml similarity index 100% rename from openspec/changes/widget-calculated-fields/.openspec.yaml rename to openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/.openspec.yaml diff --git a/openspec/changes/drill-down-cross-widget-filter/context-brief.md b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/context-brief.md similarity index 100% rename from openspec/changes/drill-down-cross-widget-filter/context-brief.md rename to openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/context-brief.md diff --git a/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/design.md b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/design.md new file mode 100644 index 000000000..bea62f52c --- /dev/null +++ b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/design.md @@ -0,0 +1,155 @@ +# Design — Drill-down Cross-widget Filter + +## Context + +LaunchPad dashboards today render each widget as an isolated island. A chart widget pulls its own data with its own filter context; clicking a bar either does nothing or drops the user into a separate list view. Every drill-down step requires reopening filter modals on three widgets, re-entering gemeentecode and wijkcode, and reconciling inevitable inconsistencies — "is this widget's 'older than 6 weeks' calculation the same as that one's?" The user mental model is simple ("show me bezwaren in Zeist, then Vollenhove, then open ones > 6 weeks") but the UI breaks it into three separate journeys through three separate modals. + +The OpenRegister API already supports multi-dimension filtering via `_filter` query parameters and uses composite indexes to serve them efficiently. The gap is in the dashboard host: no glue code detects clicks, no pub/sub layer coordinates subscribers, no URL encoding makes filtered views bookmarkable. This change adds that glue. + +## Goals / Non-Goals + +**Goals:** + +- Make filter state shared across the dashboard via a per-dashboard pub/sub bus. +- Declare widget compatibility (which dimensions a widget can publish/consume) via manifest, not runtime guesswork. +- Make filtered views bookmarkable and reproducible via URL encoding. +- Support drill-down hierarchies (gemeente → wijk → buurt) so a child-level click infers and applies ancestor filters. +- Resolve filter conflicts explicitly with audit trails, not silent overwrites. +- Allow users to save named filter combinations and apply them with one click. +- Measure which drill-down paths users exercise (opt-in telemetry, no PII). + +**Non-Goals:** + +- Rewrite the OpenRegister query layer. The bus translates to `_filter` parameters; OR's index strategy unchanged. +- Create a new visual filter builder / query-construction UI. Filtering happens via widget clicks (app-driven), not ad-hoc form building. +- Support cross-register filtering (e.g., filter one dashboard that pulls from Register A AND Register B). Scope is per-dashboard, per-register. +- Implement cross-user collaboration features (e.g., "user A applied a filter, broadcast to user B's dashboard"). Each user has their own filter bus; persistence happens via bookmarkable URLs and shared dashboards. +- Support stateful filter-history or "undo" beyond the browser's back button. + +## Decisions + +### D1: Pub/sub filter bus in the dashboard host, not a new query engine + +**Decision**: Implement a thin pub/sub layer in `src/composables/useFilterBus.js` that accepts `{dimension, operator, value}` clauses from widgets, applies conflict resolution, and broadcasts to subscribers. Clauses map to `_filter` query parameters on widget data fetches; no new OR query engine. + +**Alternatives considered:** + +- Push filter logic into OpenRegister. Rejected — OR is a generic query-execution service; dashboards are a higher-level application concern. Coupling filter logic to OR would either duplicate the logic in other OR clients or force those clients to live with dashboard-specific semantics. +- Use Pinia global store for filter state. Rejected — Pinia is great for component-level state, but filter state is tied to the URL and must survive page reloads. A composable that reads from/writes to the URL (via router) is the cleaner boundary. +- Implement a constraint-solver for conflict resolution (e.g., "common ancestor between two conflicting clauses, prefer the narrower scope"). Rejected — dramatically more complex, and last-write-wins with explicit audit is what collaborative tools (Tableau, Power BI, Kibana) actually do because it is predictable and undoable. + +**Rationale**: The bus is a glue layer between widgets and OR, not a new subsystem. Reusing OR's existing `_filter` parameter means no new indexes, no new query planner, and the same performance characteristics widgets already have for share-link filtering. + +### D2: Manifest declarations for dimension compatibility, not runtime detection + +**Decision**: Widget manifests include `publishes: [{dimension, operator, fromField}]` and `consumes: [{dimension, operator, intoFilter}]` arrays. The dashboard validates these at widget render time and surfaces mismatches (e.g., "this widget consumes 'wijkCode' but no hierarchy on this dashboard includes it") as non-fatal warnings. + +**Alternatives considered:** + +- Detect dimension compatibility at runtime (inspect widget data shape on first fetch). Rejected — the shape only arrives after the query runs; this delays the validation and couples the decision to the data. Manifest-based validation is immediate and testable. +- Use a TypeScript interface to encode allowed dimensions. Rejected — manifests need to be readable by dashboard operators who are not developers; JSON is more approachable than type interfaces. + +**Rationale**: Manifests are the source of truth for widget capabilities. Validation catches misconfigurations at dashboard-edit time ("you've added a widget that expects 'gemeenteCode' but your hierarchies don't mention it") and prevents silent failures at runtime. + +### D3: Declarative hierarchy model with parent-relationships + +**Decision**: Hierarchy descriptors live in the dashboard manifest and include ordered level arrays with explicit parent-relationships: `{id, levels: [{dimension, parentDimension, label}, ...]}`. When a wijk-level click arrives, the bus infers the ancestor gemeentecode and provincecode (parent-of-parent) from the CBS administrative hierarchy and applies them as `source=parentScope` clauses. + +**Alternatives considered:** + +- Hard-code the hierarchy in code (a switch statement per known hierarchy). Rejected — organisations with custom taxonomies can't use them without forking launchpad. Declarative JSON is extensible. +- Compute parent relationships at query time from the data (fetch all gemeentes for the clicked wijk, infer the gemeentecode). Rejected — adds latency and couples hierarchy to the data shape, making it brittle. +- Support arbitrary parent-relationships without inferring them (user manually clicks up the hierarchy). Rejected — the whole point of hierarchies is to make the breadcrumb and ancestor filters automatic. + +**Rationale**: CBS gemeentecodes and wijkcodes have stable, well-documented parent-relationships (wijk code WK0701001 → gemeente GM0701, which is always the first 4 digits). Declarative hierarchies make the relationships explicit, auditable, and extensible for non-standard taxonomies. + +### D4: URL encoding via base64url-compact-JSON, not parameter-per-clause + +**Decision**: Serialize the entire filter state to a single `?f=<base64url>` parameter using compact JSON keys (`d` for dimension, `o` for operator, `v` for value, `s` for source) to stay within typical 2 KB URL length limits. + +**Alternatives considered:** + +- One query parameter per clause: `?gemeenteCode=GM0355&status=open`. Rejected — dimensions with special characters or namespaced names (e.g., `period.month`, `custom.myTaxonomy`) become unreadable; query-parameter order is not guaranteed; dashboards with 10+ clauses exceed URL limits. +- Use a different encoding (gzip, base64 without url-safe alphabet). Rejected — base64url is what JWT, OAuth2 PKCE, and (for this exact purpose) Grafana use; it's a proven standard that doesn't require percent-encoding in URLs. + +**Rationale**: Grafana's `var-` parameters use the same approach and have solved the "dozens of clauses" problem. Base64url produces readable (if compact) URLs that can be copy-pasted, and compact JSON keys keep the size under typical proxy/browser limits. + +### D5: Last-write-wins conflict resolution with audit tooltips + +**Decision**: When a new clause for dimension X arrives and X already has an active clause, replace the old one silently or with a brief audit toast depending on the source transition (widget-click → widget-click: show toast; urlBootstrap → widget-click: silent, URL is transient). Show the old and new values (e.g., "Gemeente: Zeist → Houten"). + +**Alternatives considered:** + +- Merge clauses (e.g., if X is already filtered to a set, add the new value to the set). Rejected — this produces subtle wrong answers ("why is my widget showing both GM0355 and GM0344 when I only clicked one?") and is nearly impossible for users to understand or undo. +- Reject conflicting clauses with an error toast (prevent replacement). Rejected — blocks the user's navigation; they have no way to override except by clicking "Reset filters" and starting over. +- Support multi-value filters (e.g., `{op: 'in', value: [GM0355, GM0344]}`). Rejected — the UI would need a multi-select affordance for every click, which breaks the "tap-to-filter" pattern. Multi-select can be a separate "drill-up" feature later. + +**Rationale**: Collaborative tools (Tableau, Looker, Power BI) all use last-write-wins because it is predictable and debuggable — the user can see the change via the audit toast and undo by clicking elsewhere. Silent merges are the enemy of trust in analytics. + +### D6: Pinned clauses survive "Reset filters" + +**Decision**: Clauses marked `pinned: true` (set by org admins via dashboard config) are immutable. When "Reset filters" is invoked, unpinned clauses are cleared but pinned ones remain. When a new clause for a pinned dimension arrives, the publication is silently dropped with a console log (visible to developers, not users). + +**Alternatives considered:** + +- Allow users to unpin clauses individually. Rejected — pinned clauses are org-level policy ("always scope to current user's gemeente"); users should not override them. +- Show an error when a pinned clause can't be replaced. Rejected — noisy and confusing for users; a console message is sufficient for developer debugging. + +**Rationale**: Pinned clauses are the mechanism for org-scope constraints (e.g., "this dashboard always filters to the logged-in user's gemeente"). They need to survive user exploration (so the user can't accidentally scope up to provincial level) without being visible as a restriction in the UI. + +### D7: Saved views persist filter combinations in the register (withdrawn) + +**Withdrawn on 22 Nov 2026 (Ruben):** saved views make no sense in an app about boards; a board with its filters is the unit. REQ-CWF-009 is removed, and the saved-views UI and the `saved_view` schema with it. The text below is the original decision. + +**Decision**: Signed-in users with edit permission on a dashboard can save the current filter state as a named `saved_view` row in the launchpad register with fields `{id, dashboardId, name, description, filters, isShared, sharedWith, createdBy, createdAt}`. Saved views appear in a dropdown in the dashboard header; clicking one applies its clauses. + +**Alternatives considered:** + +- Store saved views in localStorage. Rejected — not shareable between users, no access control, lost on device change. +- Use a separate "views" register. Rejected — the launchpad register is the system of record for dashboard metadata; saved views are dashboard artifacts. + +**Rationale**: Register-backed persistence makes saved views shareable ("team lead creates 'Open bezwaren > 6w' and shares with the team") and auditable (who created the view, when) without introducing a new persistence tier. + +### D8: Telemetry is opt-in, records paths not values + +**Decision**: Org-level config flag controls telemetry. When enabled, `filter_event` rows record `{id, dashboardId, userId, widgetId, eventType, filterDelta, timestamp}` with `eventType` one of `apply` / `reset` / `bookmark` / `share`. The `filterDelta` records dimensions and operators, never filter values (which frequently are PII). + +**Alternatives considered:** + +- Record full filter values for perfect audit trails. Rejected — violates GDPR/AVG principle of data minimisation (NEN-ISO 27001:2022 control 5.34). Single-row filters are user lookups; if telemetry records `status=GM0355` the aggregated report is useless (no pattern) and retention is a liability. +- No telemetry at all. Rejected — orgs need to understand which drill-down paths users exercise to tune hierarchies and retire unused widgets. + +**Rationale**: Aggregate reports ("most-used paths: gemeente → wijk → buurt", "least-used widget: [name]") drive tuning; individual filter values do not. The org gets actionable insights without exposing sensitive data. + +### D9: 300 ms responsiveness bound for widget re-renders + +**Decision**: When a filter clause is published, all consuming widgets MUST re-render and reflect the new filter within 300 ms. If a widget's fetch takes longer, the widget shows a loading indicator (existing pattern in REQ-WDG-007). + +**Alternatives considered:** + +- No bound, let widgets re-render whenever their fetch completes. Rejected — on slow networks this creates confusing visual delays ("did my click do anything?"). +- 100 ms to match Nielsen's "feels instantaneous" threshold. Rejected — achievable only for in-memory caches; most widgets fetch from OR, which takes 150-250 ms on normal networks. 300 ms is the midpoint that launchpad consistently hits for drill-down queries (which narrow scope, hitting better-selectivity indexes). + +**Rationale**: Jakob Nielsen's responsiveness thresholds — below 100 ms feels instantaneous, 100–1000 ms feels direct, beyond 1 s users lose flow. 300 ms is what real-world widget fetches from OR can sustain without artificial delays. + +## Risks / Trade-offs + +- **Risk:** URL grows unbounded if users apply a dozen clauses. → **Mitigation:** Conservative 2 KB limit documented in user guides; dashboards that habitually exceed this are an indicator they're doing too much and should be split. Failure mode (URL too long) is self-evident. +- **Risk:** Hierarchy inference fails if a clicked value doesn't exist in the parent level (e.g., user clicks a wijk that belongs to no gemeente in the dashboard's data). → **Mitigation:** The click is rejected with a tooltip "no access to this scope" (REQ-CWF-004). This prevents orphaned hierarchies. +- **Risk:** Pinned clauses are confusing if the UI doesn't signal them clearly. → **Mitigation:** Active-filters panel shows pinned clauses with a lock icon and no remove button; the restriction is visible. +- **Trade-off:** Last-write-wins ignores nuance ("I wanted to add this clause, not replace"). → **Mitigation:** The audit toast is explicit; users can undo via the active-filters panel. +- **Trade-off:** Telemetry does not record which user clicked which filter, only the aggregate. → **Accepted:** Orgs get path usage without exposing user behavior; precise click attribution is not necessary for hierarchy tuning. + +## Migration Plan + +1. **Manifest schema + composables land first** — add `publishes`, `consumes`, `hierarchies` fields to widget manifests; implement `useFilterBus` and `useDashboardFilter` with unit tests. No UX change yet. +2. **Dashboard host integration** — update `Dashboard.vue` to instantiate the bus, render the active-filters panel, expose "Reset filters". Wire widget clicks to publish events. +3. **Widget adaptation** — update chart and table widgets to emit click events with dimension + value. No manifest changes needed for widgets already accepting `filterContext` prop. +4. **Register integration** — persist filter events to the register (REQ-CWF-010). +5. **Rollback:** Backend-persisted telemetry remains, but the filter bus ceases to function if the frontend is rolled back. This is acceptable because telemetry is only for analytics, not operational. + +## Open Questions + +- Should hierarchy resolution be modal (all levels must exist) or lenient (infer as far as possible)? → Decision: Lenient, with a console warning for missing parent levels, so dashboards with partial hierarchies still work. +- Is 300 ms the right responsiveness target? → Decision: Confirmed via testing on production OR cluster with typical network latencies; 250 ms would be unachievable, 400 ms feels sluggish. +- Should users be able to pin their own clauses, or only org admins? → Decision: Org admins only (via dashboard config). Users can save named views instead for personal filter preferences. diff --git a/openspec/changes/drill-down-cross-widget-filter/hydra.json b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/hydra.json similarity index 100% rename from openspec/changes/drill-down-cross-widget-filter/hydra.json rename to openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/hydra.json diff --git a/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/proposal.md b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/proposal.md new file mode 100644 index 000000000..ac2493615 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/proposal.md @@ -0,0 +1,49 @@ +# Drill-down Cross-widget Filter + +Cross-widget filtering closes the analytical workflow gap where each widget operates as a standalone island. Today, clicking a bar in one chart does nothing, forcing users to manually re-enter the same filter values into three different widgets, leading to inconsistencies and inefficiency. This change introduces a shared filter bus per dashboard that allows any widget to publish filter events (on click) and any widget to consume them (on render), enabling seamless drill-down exploration where all widgets stay synchronized through a single source of truth: the URL. + +The filter bus is built around five core principles. First, filter state is persisted in the URL as a bookmarkable, shareable snapshot — the same URL pasted elsewhere yields identical results. Second, widgets declare their publishing and consuming dimensions in their manifest, allowing the dashboard to validate compatibility statically and enable cross-widget interactions only where semantic links exist. Third, drill-down hierarchies are declarative, so clicking "Zeist" automatically narrows ancestor/descendant dimensions. Fourth, filter conflicts are resolved explicitly using last-write-wins per dimension, not silent merges, with audit tooltips so users understand what changed. Fifth, a single "Reset filters" action restores the unfiltered state, including the URL, ensuring users never get stranded. + +## Affected code units + +- `src/components/Dashboard.vue` — hosts the filter bus, renders active-filters panel, exposes "Reset filters" action +- `src/composables/useFilterBus.js` (new) — pub/sub implementation, dimension compatibility checking, hierarchy traversal +- `src/composables/useDashboardFilter.js` (new) — filter state serialization, URL encoding/decoding (base64url compact JSON) +- `src/components/widgets/ChartWidget.vue` + table widgets — accept `filterContext` prop (already passed for share-links), emit click events with dimension + value +- `lib/Register/DashboardFilterStateRegister.php` (new) — persists filter telemetry events +- Manifest schema: `widget.manifest.json` adds `publishes[]`, `consumes[]`, `hierarchies[]` fields per ADR-005 +- Adds new capability `cross-widget-filter` with requirements REQ-CWF-001 through REQ-CWF-011 (REQ-CWF-009, saved views, removed by decision on 22 Nov 2026) +- Modifies dashboard routing to inject filter state on initial load (REQ-CWF-003) + +## Why a new capability + +Filter-driven collaboration between widgets is a top-level analytical feature, not an internal refactor. It touches the widget manifest schema, the dashboard host render, the OpenRegister integration layer, and persistence tier. Owning it as its own capability gives: + +1. A clear contract of which dashboard dimensions participate in filtering +2. Audit-ready telemetry for understanding which drill-down paths users actually exercise +3. A testable boundary: widgets can be tested for filter conformance in isolation +4. Bookmarkable, reproducible views via URL — auditable for compliance scenarios + +## Approach + +- **Filter bus** — thin pub/sub layer in the dashboard host. Widgets publish `{dimension, operator, value, sourceWidgetId}`. The bus applies last-write-wins conflict resolution and broadcasts to consuming widgets. +- **Manifest integration** — widget manifests declare `publishes: [{dimension, operator, fromField}]` and `consumes: [{dimension, operator, intoFilter}]`. The dashboard validates at render time. +- **Hierarchy support** — dash manifest declares `hierarchies: [{id, levels: [{dimension, parentDimension, label}]}]`. When a wijk-level click arrives, the bus infers ancestor clauses (`source=parentScope`) and clears descendants. +- **URL persistence** — filter state serialized to `?f=<base64url>` parameter using compact JSON (`{d, o, v, s, w}` keys). Restores on page load with `source=urlBootstrap`. +- **Telemetry** — org-level opt-in flag. `filter_event` rows record apply/reset/bookmark/share events, dimension paths, and widget IDs (never filter values). Aggregate report shows most-used drill-down paths. +- **Conflict resolution** — new clause replacing an existing dimension shows a one-line audit toast (e.g., "Gemeente filter changed: Zeist → Houten"). Pinned clauses are immutable; replacements are silently dropped. +- **Reset action** — single button clears all non-pinned clauses and removes the `f` URL parameter. + +## Capabilities + +**New Capabilities:** + +- `cross-widget-filter` (adds REQ-CWF-001 through REQ-CWF-010) + +## Notes + +- The filter bus is opt-in per widget — widgets without `publishes`/`consumes` declarations continue to render with static filter context and do not participate. +- Existing widgets that already accept `filterContext` for share-links become instant bus participants with zero code change — they just need manifest updates. +- The bus translates clauses to OpenRegister `_filter` query parameters, reusing the existing index infrastructure; no new query engines. +- Hierarchy resolution (inferring ancestors from a child-level click) uses parent-relationships stable in the Dutch administrative model (wijk's first 4 digits are gemeentecode; gemeentecode's first 2 digits are provincecode). +- Filter values are never stored in telemetry — only operators, dimensions, and paths — for GDPR/privacy-by-design compliance (NEN-ISO 27001:2022 control 5.34). diff --git a/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/screens.md b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/screens.md new file mode 100644 index 000000000..bc444af05 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/screens.md @@ -0,0 +1,2 @@ +# Screens +- LpManagement a bar clicked in one widget, the filter chip with its clear action, which widgets follow the filter, and the filter in the address (REQ-CWF-001 to REQ-CWF-003) https://identity.conduction.nl/screens/board?id=launchpad/LpManagement diff --git a/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md new file mode 100644 index 000000000..e6091079d --- /dev/null +++ b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md @@ -0,0 +1,531 @@ +--- +capability: cross-widget-filter +status: draft +--- + +# Cross-Widget Filter — New capability from change `drill-down-cross-widget-filter` + +## Context + +This capability adds a shared filter bus to launchpad dashboards, allowing widgets to publish filter events (on click) and other widgets to consume them (on render). Filter state is persisted in the URL and optionally logged for aggregate telemetry. A dashboard with its filters is the unit a user keeps and shares; there are no saved views (REQ-CWF-009 was removed by decision on 22 Nov 2026). + +## ADDED Requirements + +### Requirement: REQ-CWF-001 Widget click publishes to the filter bus + +The dashboard SHALL detect clicks on chartable elements of bus-aware widgets and SHALL publish the corresponding filter clause to the bus, identifying the publishing widget so the click can be visually echoed back. + +#### Scenario: Bar chart click publishes a clause + +- **GIVEN** a bar chart widget A on a dashboard, with a `publishes` declaration of `{dimension: "gemeenteCode", operator: "eq", fromField: "category"}` +- **WHEN** the user clicks the bar labelled "Zeist" (gemeenteCode `GM0355`) +- **THEN** a filter clause `{dimension: "gemeenteCode", operator: "eq", value: "GM0355", source: "widgetClick", sourceWidgetId: A}` SHALL be added to the bus + +#### Scenario: Widget without publishes declaration does nothing + +- **GIVEN** a widget WITHOUT a `publishes` declaration +- **WHEN** the user clicks an element +- **THEN** no clause SHALL be added to the bus and the click MAY perform a widget-local action (e.g. open detail modal) + +#### Scenario: Clicking the same clause again removes it (toggle) + +- **GIVEN** the same bar is clicked a second time +- **WHEN** the bus already contains that exact clause sourced from the same widget +- **THEN** the clause SHALL be removed (toggle behaviour) and the URL SHALL be updated to reflect the cleared state + +--- + +### Requirement: REQ-CWF-002 All consuming widgets re-render on filter change + +The system SHALL recompute and re-render every widget whose `consumes` declaration matches one or more active filter dimensions, passing the merged filter context as a prop, within 300 ms of the click. + +#### Scenario: Selective widget re-render + +- **GIVEN** three widgets on a dashboard: A (publishes gemeenteCode), B (consumes gemeenteCode), C (does not consume gemeenteCode) +- **WHEN** the user clicks "Zeist" on A +- **THEN** A SHALL echo the selection visually, B SHALL re-render with `gemeenteCode=GM0355` applied, and C SHALL NOT re-render + +#### Scenario: New widget receives current filter state on mount + +- **GIVEN** a widget whose `consumes` declaration includes a dimension currently in the bus +- **WHEN** the widget mounts (or is dragged onto the dashboard) +- **THEN** it SHALL receive the current bus state on first render and SHALL NOT show a flash of unfiltered content + +--- + +### Requirement: REQ-CWF-003 URL encoding makes filtered views bookmarkable + +The system SHALL serialise the active filter state into a URL query parameter and SHALL restore the filter state on initial load when the parameter is present, producing the same view the URL-issuer saw. + +#### Scenario: URL encodes active filter state + +- **GIVEN** a dashboard with two active clauses (`gemeenteCode=GM0355`, `status=open`) +- **WHEN** the URL is copied +- **THEN** it SHALL contain a `?f=...` parameter encoding both clauses + +#### Scenario: Loading a bookmarked URL restores filter state + +- **GIVEN** that URL is pasted into a second browser by a second user with read access to the dashboard +- **WHEN** the page loads +- **THEN** both clauses SHALL be restored with `source=urlBootstrap` and the visible widgets SHALL reflect the filtered numbers without any user action + +#### Scenario: Malformed URL parameter does not crash + +- **GIVEN** a URL whose `f` parameter is malformed +- **WHEN** the page loads +- **THEN** the dashboard SHALL render with an empty filter state and SHALL log a single warning (no error toast on the user) + +--- + +### Requirement: REQ-CWF-004 Drill-down hierarchies update breadcrumb and descendant filters + +When a click publishes a clause for a dimension that is part of a `hierarchy_descriptor`, the system SHALL update the breadcrumb UI to show the active path and SHALL clear any descendant-level clauses from the bus before applying the new clause. The breadcrumb SHALL show one step per active level of each hierarchy, broadest first, as the level's label in the reader's language and its value ("Provincie PV26 > Gemeente GM0355 > Wijk WK035501"); each step above the deepest SHALL go back up to that level. A chart click names only the field the chart groups by, so the ancestor values SHALL be read from the clicked row when it carries them, and otherwise from one record of the clicked category in the chart's register and schema, in the record's field named like the ancestor's dimension; an ancestor that cannot be read is skipped with a console warning. + +#### Scenario: Drilling up clears descendant filters + +- **GIVEN** the `nl-administrative` hierarchy is active on a dashboard, with current clauses `gemeenteCode=GM0355` and `wijkCode=WK0355001` +- **WHEN** the user clicks "Provincie Utrecht" on a province-level widget (publishing `provincieCode=PV09`) +- **THEN** the bus SHALL contain only `{provincieCode=PV09}` (gemeente and wijk are cleared because they are descendants) and the breadcrumb SHALL show "Provincie Utrecht" + +#### Scenario: Drilling down infers ancestor filters + +- **GIVEN** the same dashboard with no active filters +- **WHEN** the user clicks a wijk on a wijk-level widget (publishing `wijkCode=WK0355001`) +- **THEN** the bus SHALL contain `{wijkCode=WK0355001}` AND the hierarchy resolver SHALL infer and add ancestor clauses (`gemeenteCode=GM0355`, `provincieCode=PV09`) marked with `source=parentScope` so the breadcrumb shows the full path + +#### Scenario: Going back up the breadcrumb clears the levels below + +- **GIVEN** the breadcrumb shows "Provincie PV26 > Gemeente GM0355 > Wijk WK035501" after a wijk click +- **WHEN** the user chooses the "Provincie PV26" step +- **THEN** the gemeente and wijk clauses SHALL be cleared (pinned ones stay), the provincie clause SHALL stay as the user's own (`source=userExplicit`), the breadcrumb SHALL show "Provincie PV26", and a later click on a wijk in another gemeente SHALL replace the provincie and gemeente with that wijk's ancestors + +#### Scenario: Permission-denied on hierarchy level + +- **GIVEN** a click on a hierarchy level the user has no permission for (e.g. a gemeenteCode their role doesn't expose) +- **WHEN** the click is processed +- **THEN** the publication SHALL be rejected, the widget SHALL show a tooltip explaining "no access to this scope", and the bus SHALL NOT be mutated + +--- + +### Requirement: REQ-CWF-005 Filter conflict resolution is last-write-wins per dimension + +When a new clause is published for a dimension that already has an active clause from a different source or operator, the system SHALL replace (not append) the existing clause and SHALL show a one-line audit tooltip indicating which previous clause was replaced. + +#### Scenario: Widget-click replaces widget-click + +- **GIVEN** an active clause `{gemeenteCode=GM0355, source=widgetClick}` from widget A +- **WHEN** widget B publishes `{gemeenteCode=GM0344, source=widgetClick}` +- **THEN** the bus SHALL contain only the new clause from B, widget A SHALL update its visual echo to deselect GM0355, and a brief toast SHALL indicate "Gemeente filter changed from Zeist to Houten" + +#### Scenario: Widget-click silently replaces URL-bootstrap + +- **GIVEN** an active clause sourced from `urlBootstrap` +- **WHEN** a widget-click clause for the same dimension arrives +- **THEN** the widget-click clause SHALL replace the URL-bootstrap one with no toast (URL bootstrap is treated as a transient initial state, not a deliberate user choice) + +#### Scenario: Pinned clause cannot be replaced + +- **GIVEN** an active `pinned: true` clause +- **WHEN** a clause for the same dimension arrives from any source +- **THEN** the pinned clause SHALL NOT be replaced and the new publication SHALL be silently dropped with a one-line console log (so a developer can see why their click did not stick) + +--- + +### Requirement: REQ-CWF-006 Reset filters clears all non-pinned clauses + +The dashboard SHALL expose a "Reset filters" action that clears every non-pinned clause from the bus and SHALL update the URL to remove the `f` parameter. + +#### Scenario: Reset clears non-pinned clauses, keeps pinned + +- **GIVEN** a dashboard with five active clauses, one of which is pinned +- **WHEN** the user invokes "Reset filters" +- **THEN** four clauses SHALL be removed, the pinned clause SHALL remain, the URL SHALL be updated, and every consuming widget SHALL re-render with the reduced filter context + +#### Scenario: Reset on empty bus is a no-op + +- **GIVEN** a dashboard with no active clauses +- **WHEN** "Reset filters" is invoked +- **THEN** the action SHALL be a no-op (no URL change, no widget re-render, no telemetry event) so accidental double-clicks do not produce noise + +--- + +### Requirement: REQ-CWF-007 Filter stack UI shows every active clause with its source + +The dashboard SHALL render a compact "Active filters" panel listing every active clause with its dimension label, value, source widget (when applicable), and an individual remove-action; the panel SHALL collapse when empty. + +#### Scenario: Active filters panel shows all clauses with source + +- **GIVEN** three active clauses (one from a widget click, one from URL bootstrap, one pinned by the org) +- **WHEN** the panel is rendered +- **THEN** it SHALL show three chips with distinct visual treatment per source (e.g. widget-click chips show the source widget's name, pinned chips show a lock icon and have no remove-action) + +#### Scenario: Remove single clause from panel + +- **GIVEN** the user clicks the remove-action on a single chip +- **WHEN** the click is processed +- **THEN** only that clause SHALL be removed, the URL SHALL be updated, and the originating widget (if any) SHALL update its visual echo to deselect + +--- + +### Requirement: REQ-CWF-008 Widget manifest declares publishes/consumes; dashboard validates compatibility + +The widget loader SHALL read `publishes` and `consumes` from the widget manifest and the dashboard SHALL refuse to render a widget whose manifest declares dimensions inconsistent with the dashboard's hierarchy descriptors, surfacing the mismatch in the widget config UI. + +#### Scenario: Consuming dimension not in dashboard hierarchies + +- **GIVEN** a widget manifest declaring `consumes: [{dimension: "wijkCode"}]` on a dashboard whose hierarchy descriptors do not include `wijkCode` +- **WHEN** the widget is added to the dashboard +- **THEN** the widget config UI SHALL show a non-fatal warning ("This widget consumes 'wijkCode' but no hierarchy on this dashboard publishes it") and the widget SHALL render as a non-bus-participant + +#### Scenario: Publishing from missing field + +- **GIVEN** a widget manifest declaring `publishes: [{dimension: "gemeenteCode", fromField: "missingField"}]` where `missingField` is not in the widget's data shape +- **WHEN** the widget renders +- **THEN** the dashboard SHALL log a manifest-validation error and disable bus participation for that widget (no clicks publish) + +--- + +### Requirement: REQ-CWF-010 Telemetry of filter usage is opt-in and aggregated + +When org-level telemetry is enabled, the system SHALL persist `filter_event` rows for `apply` / `reset` / `bookmark` / `share` events with no PII beyond the user id, and SHALL expose an aggregate report ("most-used drill-down paths per dashboard") to dashboard owners. + +#### Scenario: Telemetry disabled (default) + +- **GIVEN** telemetry is disabled (default) +- **WHEN** any filter event occurs +- **THEN** no `filter_event` row SHALL be written + +#### Scenario: Filter apply event is recorded + +- **GIVEN** telemetry is enabled and a user clicks a wijk on widget A +- **WHEN** the click is processed +- **THEN** a `filter_event` row SHALL be written with `eventType=apply`, the wijk clause delta, `widgetId=A`, and the user id, AND the URL/share event SHALL NOT be conflated with the click event (two separate rows) + +#### Scenario: Bookmark event on page load + +- **GIVEN** telemetry is enabled and an authenticated user opens a bookmarked URL +- **WHEN** the page loads +- **THEN** exactly one row SHALL be written with `eventType=bookmark` and the full clause set as the delta + +--- + +### Requirement: REQ-CWF-011 A dashboard stores its hierarchies + +A dashboard SHALL store its `hierarchies` (a list of hierarchy_descriptor objects) and return them on every read of the dashboard, so the filter bus of every viewer joins widgets on them without any per-page configuration. An owner or editor SHALL pick the hierarchies in the dashboard settings from the shipped presets; the `nl-administrative` preset (province > municipality > district > neighbourhood: `provincieCode` > `gemeenteCode` > `wijkCode` > `buurtCode`) SHALL be one of them. The dashboard API SHALL validate every descriptor before it stores it. + +#### Scenario: An owner picks the nl-administrative preset + +- **GIVEN** a dashboard without hierarchies and its owner in the dashboard settings +- **WHEN** the owner picks the "Dutch administrative areas" preset and saves +- **THEN** the dashboard SHALL store the `nl-administrative` descriptor with the levels `provincieCode`, `gemeenteCode`, `wijkCode` and `buurtCode`, every later read of the dashboard SHALL return it, and the dashboard's filter bus SHALL be rebuilt on it + +#### Scenario: Stored hierarchies put consuming widgets on the bus + +- **GIVEN** a dashboard that stores the `nl-administrative` hierarchy, a chart that publishes `gemeenteCode` and a chart that consumes `gemeenteCode` +- **WHEN** a viewer opens the dashboard and clicks a gemeente on the publishing chart +- **THEN** the consuming chart SHALL refetch with the clicked gemeente as its filter, with no hierarchy added to the dashboard anywhere but in its stored settings + +#### Scenario: A malformed descriptor is refused + +- **GIVEN** an update whose `hierarchies` is not a list, or holds a descriptor without an `id`, without levels, with a level without a `dimension`, with a dimension used twice, or with a `parentDimension` that is not the level above +- **WHEN** the update is sent to the dashboard API +- **THEN** the API SHALL answer 400 with a message naming the problem and SHALL store nothing of the update + +#### Scenario: A viewer cannot change the hierarchies + +- **GIVEN** a user who may view but not edit a dashboard +- **WHEN** that user sends an update with `hierarchies` +- **THEN** the API SHALL refuse it as it refuses a layout change, and the stored hierarchies SHALL stay as they were + +#### Scenario: Copies keep the hierarchies + +- **GIVEN** a dashboard or admin template that stores the `nl-administrative` hierarchy +- **WHEN** a user forks it as a personal copy, a dashboard is made from the template, or the dashboard is exported and imported again +- **THEN** the copy SHALL store the same hierarchies, so its filter bus joins widgets as the original's does; a malformed list in an imported archive SHALL be left out without failing the import + +#### Scenario: Clearing the hierarchies + +- **GIVEN** a dashboard that stores the `nl-administrative` hierarchy +- **WHEN** the owner removes it in the settings and saves (an update with `hierarchies: []`) +- **THEN** the dashboard SHALL store no hierarchies, reads SHALL return `hierarchies: []`, and widgets that consume a hierarchy dimension SHALL leave the bus with the REQ-CWF-008 warning + +--- + +## Data Model + +### dashboard_filter_state + +Holds the active filter set for a dashboard view. The URL is the system of record; the shape is not stored in the register. + +- `dashboardId` (UUID) — references a dashboard +- `filters` (array of filter_clause objects) — active clauses +- `appliedAt` (ISO timestamp) — for telemetry + +#### Seed Data + +```json +{ + "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", + "filters": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "value": "GM0355", + "source": "widgetClick", + "sourceWidgetId": "w-chart-gemeenten" + }, + { + "dimension": "status", + "operator": "eq", + "value": "open", + "source": "widgetClick", + "sourceWidgetId": "w-chip-status" + }, + { + "dimension": "ageInDays", + "operator": "gte", + "value": 42, + "source": "userExplicit", + "pinned": true + } + ], + "appliedAt": "2026-05-22T14:35:00Z" +} +``` + +### filter_clause + +Describes one active filter. Keyed in compact form for URL encoding as `{d, o, v, s, w, p}`. + +- `dimension` (string, e.g. `gemeenteCode`, `wijkCode`, `period.month`) — the filtered attribute +- `operator` (enum: `eq`, `in`, `between`, `gte`, `lte`, `contains`, `notNull`) — comparison operator +- `value` (scalar, array, or `[low, high]` tuple) — depends on operator; never stored in telemetry +- `source` (enum: `userExplicit`, `widgetClick`, `urlBootstrap`, `savedView`, `parentScope`) — origin; `savedView` is no longer written but still decodes, so a link copied while saved views existed keeps its filters +- `sourceWidgetId` (UUID, nullable) — set when `source=widgetClick` +- `pinned` (boolean, default false) — pinned clauses survive "Reset filters" + +#### Seed Data + +```json +[ + { + "dimension": "gemeenteCode", + "operator": "eq", + "value": "GM0355", + "source": "widgetClick", + "sourceWidgetId": "w-chart-gemeenten" + }, + { + "dimension": "wijkCode", + "operator": "in", + "value": ["WK0355001", "WK0355002"], + "source": "widgetClick", + "sourceWidgetId": "w-map-wijken" + }, + { + "dimension": "ageInDays", + "operator": "gte", + "value": 42, + "source": "userExplicit", + "pinned": true + } +] +``` + +### dimension_descriptor + +Lives in the widget manifest and declares what a widget can publish and consume. + +- `publishes` (array of objects) — describes what a click on a particular column/series/cell publishes + - `dimension` (string) — the dimension published + - `operator` (enum) — typically `eq` for categorical clicks, can be `between` for range selections + - `fromField` (string) — the data field that supplies the value (e.g. `category`, `date`) +- `consumes` (array of objects) — describes which incoming dimensions narrow this widget's query + - `dimension` (string) — the dimension consumed + - `operator` (enum) — filtering operator the widget applies + - `intoFilter` (string, nullable) — the parameter name to pass to the data source (e.g. `_filter[gemeenteCode]`) +- `hierarchies` (array of hierarchy_descriptor objects) — see below + +#### Seed Data + +```json +{ + "publishes": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "fromField": "category" + } + ], + "consumes": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "intoFilter": "_filter[gemeenteCode]" + }, + { + "dimension": "status", + "operator": "eq", + "intoFilter": "_filter[status]" + } + ], + "hierarchies": [ + { + "id": "nl-administrative", + "levels": [ + { + "dimension": "provincieCode", + "label": "Provincie" + }, + { + "dimension": "gemeenteCode", + "label": "Gemeente", + "parentDimension": "provincieCode" + }, + { + "dimension": "wijkCode", + "label": "Wijk", + "parentDimension": "gemeenteCode" + } + ] + } + ] +} +``` + +### hierarchy_descriptor + +Declares a drill-down chain for inferring ancestor and descendant relationships. + +- `id` (string, e.g. `nl-administrative`, `temporal-iso8601`) — unique identifier +- `levels` (ordered array) — hierarchy levels from broadest to finest + - `dimension` (string) — the dimension at this level + - `label` (string, i18n key) — human-readable label for breadcrumb + - `parentDimension` (string, nullable) — the dimension that is the parent level + +#### Seed Data + +```json +[ + { + "id": "nl-administrative", + "levels": [ + { + "dimension": "provincieCode", + "label": "hierarchy.level.province", + "parentDimension": null + }, + { + "dimension": "gemeenteCode", + "label": "hierarchy.level.municipality", + "parentDimension": "provincieCode" + }, + { + "dimension": "wijkCode", + "label": "hierarchy.level.district", + "parentDimension": "gemeenteCode" + }, + { + "dimension": "buurtCode", + "label": "hierarchy.level.neighbourhood", + "parentDimension": "wijkCode" + } + ] + }, + { + "id": "temporal-iso8601", + "levels": [ + { + "dimension": "period.year", + "label": "hierarchy.level.year" + }, + { + "dimension": "period.quarter", + "label": "hierarchy.level.quarter", + "parentDimension": "period.year" + }, + { + "dimension": "period.month", + "label": "hierarchy.level.month", + "parentDimension": "period.quarter" + }, + { + "dimension": "period.week", + "label": "hierarchy.level.week", + "parentDimension": "period.month" + } + ] + } +] +``` + +### filter_event + +Telemetry row written when an opt-in dashboard has telemetry enabled (org-level setting, default off). Records dimension and operator changes, not filter values (which may be PII). + +- `id` (UUID) — primary key +- `dashboardId` (UUID) — references the dashboard +- `userId` (UUID) — authenticated user +- `widgetId` (UUID, nullable) — set for widget-click events +- `eventType` (enum: `apply`, `reset`, `bookmark`, `share`) — event classification +- `filterDelta` (array of filter_clause objects) — the clauses added/removed by this event (no values) +- `timestamp` (ISO timestamp) — when the event occurred + +#### Seed Data + +```json +[ + { + "id": "fe-001", + "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", + "userId": "u-caseworker-01", + "widgetId": "w-chart-gemeenten", + "eventType": "apply", + "filterDelta": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "source": "widgetClick", + "sourceWidgetId": "w-chart-gemeenten" + } + ], + "timestamp": "2026-05-22T14:35:00Z" + }, + { + "id": "fe-002", + "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", + "userId": "u-caseworker-01", + "widgetId": "w-map-wijken", + "eventType": "apply", + "filterDelta": [ + { + "dimension": "wijkCode", + "operator": "eq", + "source": "widgetClick", + "sourceWidgetId": "w-map-wijken" + } + ], + "timestamp": "2026-05-22T14:35:45Z" + }, + { + "id": "fe-003", + "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", + "userId": "u-caseworker-02", + "widgetId": null, + "eventType": "bookmark", + "filterDelta": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "source": "urlBootstrap" + }, + { + "dimension": "status", + "operator": "eq", + "source": "urlBootstrap" + } + ], + "timestamp": "2026-05-22T15:10:00Z" + } +] +``` diff --git a/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md new file mode 100644 index 000000000..e90d0cf3e --- /dev/null +++ b/openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md @@ -0,0 +1,162 @@ +# Tasks — drill-down-cross-widget-filter + +## Tasks + +### Core Filter Bus Implementation + +- [x] Task 1: Create `src/composables/useFilterBus.js` with the pub/sub implementation. Export a composable that manages the filter state, accepts `publish(clause)` calls, and broadcasts to subscribers. Implement internal `_applyConflictResolution(newClause)` that enforces last-write-wins per dimension and tracks audit info (old value, new value, source transition). Inline comment linking REQ-CWF-001 through REQ-CWF-005. + +- [x] Task 2: Implement hierarchy resolution in `useFilterBus.js`. Add `_resolveHierarchy(clause, dashboardHierarchies)` that detects when a published clause belongs to a hierarchy level, infers ancestor clauses (marked `source=parentScope`) from the administrative/temporal hierarchy, and clears any descendant clauses currently in the bus. Handle missing parent levels gracefully with a console warning. Link REQ-CWF-004. + +- [x] Task 3: Create `src/composables/useDashboardFilter.js` with URL serialization/deserialization. Export `serializeFilterState(clauses): string` (returns base64url-encoded compact JSON with keys `d, o, v, s, w, p`) and `deserializeFilterState(param): {clauses, error}`. Implement lenient parsing (malformed param logs warning, returns empty clauses). Link REQ-CWF-003. + +- [x] Task 4: Integrate the filter bus into `src/components/Dashboard.vue`. Instantiate `useFilterBus()` on mount, hydrate from URL parameter via `useDashboardFilter()` on initial load (mark restored clauses with `source=urlBootstrap`), and sync the bus to the URL whenever the filter state changes (debounced 500ms to avoid excessive URL rewrites). Link REQ-CWF-003. + - Done in `src/views/Views.vue` through `src/composables/useDashboardFilterSession.js` (one bus per open dashboard, its `hierarchies`; the first dashboard of a page load reads `?f=` as `urlBootstrap`, a switch starts empty) and `src/composables/useFilterUrlSync.js` (500 ms debounce, `replaceState` so filtering is not navigation, `f` removed for an empty bus). The bus is provided to the widgets as `dashboardFilterBus`. Tests: `useFilterUrlSync.spec.js`, `useDashboardFilterSession.spec.js`. + +- [x] Task 5: Render the "Active filters" panel in `Dashboard.vue` header. For each active clause, render a chip with dimension label, value, and source icon (widget name for `widgetClick`, lock for `pinned`, none for `userExplicit`). Add a remove-button for non-pinned clauses. Pinned clauses show a lock icon and no remove-button. Panel collapses when empty. Link REQ-CWF-007. + - Done as `src/components/Workspace/ActiveFiltersPanel.vue` under the breadcrumb: a chip per clause with its level label (from the hierarchy, else the dimension), its value, the widget's title for a widget click, a lock and no remove button for a pinned clause; absent while the bus is empty. Test: `ActiveFiltersPanel.spec.js`. + +- [x] Task 6: Add "Reset filters" button to the dashboard header in `Dashboard.vue`. Invoke callback that clears all non-pinned clauses from the bus, updates the URL (removes `f` parameter), and triggers widget re-renders. No-op when the bus is already empty (no telemetry, no URL change). Link REQ-CWF-006. + - Done in the panel: "Reset filters" clears every non-pinned clause and the URL sync drops `f`; it only shows when something would be cleared, and the bus's `reset()` changes nothing and tells nobody on an empty bus, so there is no URL write. Widgets re-render once they consume the bus (Tasks 7 and 10). + +### Widget Integration + +- [x] Task 7: Update `src/components/widgets/ChartWidget.vue` (and analogous table/list widgets) to accept `filterContext` prop (already passed from dashboard for share-links; no change needed). Emit a `filter-published` event on chartable element click (bar, row, cell) with payload `{dimension, operator, value}`. The dashboard's bus subscriber listens for this event and calls `bus.publish()`. Link REQ-CWF-001, REQ-CWF-002. + - Done in `src/components/Widgets/Renderers/ChartHost.vue` on `@conduction/nextcloud-vue` 2.182.0, whose `CnChartWidget` takes `selectable` and emits `select` with the grouped field and the raw key (nextcloud-vue change `chart-widget-select-event`). A chart that declares `publishes` and is on the bus is selectable; a pick publishes a `widgetClick` clause per dimension published from the picked field (`publishedClauses()` in `src/utils/widgetBusConsumption.js`), with the picked row so ancestors are inferred. A replaced filter from another widget shows a toast naming the level and both values (REQ-CWF-005), and a refused scope a warning. Table and list widgets are library widgets with no launchpad host; they join when the library emits a pick. Tests: `chartAndStatsHosts.spec.js`, `widgetBusConsumption.spec.js`. + +- [x] Task 8: Update widget manifest schema to include `publishes`, `consumes`, and `hierarchies` arrays. For existing chart and table widgets, populate `consumes` with the dimensions they accept in `filterContext`. For "click-enabled" widgets (charts with drill-down configured), populate `publishes` with the clickable dimensions. Hierarchies are inherited from the dashboard config. Link REQ-CWF-008. + - Done as placement content declarations next to the `dataSource` (top level or under `props`): `consumes` (a dimension, or `{dimension, field}` for the data field it filters) and `publishes` (`{dimension, fromField}`); hierarchies stay the dashboard's own. Read by `busDeclarationsOf()` in `src/utils/widgetBusConsumption.js`. No shipped dashboard declares hierarchies yet, so no shipped chart is given declarations: a consumed dimension outside every hierarchy keeps a widget off the bus (REQ-CWF-008). Table and list widgets are library widgets with no host in launchpad; they join once the library passes a filter through. Test: `widgetBusConsumption.spec.js`. + +- [x] Task 9: Implement widget manifest validation in `Dashboard.vue` on render. Read widget's `publishes` and `consumes` declarations; cross-reference against the dashboard's hierarchy descriptors. Surface non-fatal warnings in the widget config UI if a consuming dimension is not in any dashboard hierarchy, or if a publishing dimension's `fromField` is not in the widget's data shape. Log validation errors to console. Link REQ-CWF-008. + - Built: `validateBusDeclarations()` checks each chart's `publishes` and `consumes` against the dashboard's hierarchies, and `ChartHost` logs every finding and keeps the chart off the bus. The widget dialog shows them: nextcloud-vue's `CnAddWidgetModal` takes `notices` (change `add-widget-modal-notices`, #2222, released in 2.185.0), and `Views.vue` passes `busNotices()` (`src/utils/widgetBusNotices.js`) for the widget being edited, a warning per consumed dimension no hierarchy publishes and an error per published field the data lacks. The widget still renders. Tests: `widgetBusNotices.spec.js`, `Views.customWidgetNotices.spec.js`, `widgetBusDeclarations.spec.js`. + - Partly done: the check is `validateBusDeclarations()` (Task 21), and `ChartHost.vue` runs it on render against the dashboard's hierarchies: a chart whose declarations do not fit stays off the bus and its findings are logged to the console. Left: showing the findings in the widget config UI. + +- [x] Task 10: Ensure all consuming widgets re-render within 300ms of a filter change (REQ-CWF-002). When the bus publishes a new clause, compute the set of consuming widgets (those whose `consumes` includes that dimension), trigger their `refetch()` methods (standard in REQ-WDG-006), and await the promise. If a fetch exceeds 300ms, the widget's existing loading indicator (REQ-WDG-007) kicks in. Profile on a representative local stack (volume recorded) to confirm the 300ms bound is met for typical drill-down queries (narrower scope, better selectivity). Link REQ-CWF-002. Measured 25 Nov 2026 on the sandbox reference stack (nginx, php-fpm with opcache, MariaDB, APCu local cache, Redis locking; Nextcloud 34.0.6, OpenRegister main), 50,000 `cwf-melding` objects, 12 drill-downs per chart kind, tests/e2e/cross-widget-filter-performance.spec.ts: ApexCharts bars click to every consumer re-rendered median 203-207 ms, p95 241-250 ms, wijk click to E p95 187-197 ms; bar-list median 148 ms, p95 162-188 ms; server time per filtered request median 53-64 ms, p95 61-85 ms; bus heap overhead for 110 charts 0.3 MB (bound 1 MB). Two of three runs 3/3 green; the first run had one bar-list wijk click at 412 ms (server 60 ms, so client side) out of 12, the other 35 under 200 ms. + - Measured 21 Nov on a local stack (50,000 OpenRegister objects in register `cwf-perf`, 12 provinces, 342 gemeenten, 3,073 wijken; OpenRegister 2.2.0-dev, PostgreSQL 16.15, Nextcloud 34; data set `tests/e2e/support/cwfPerfSeed.ts`) by `tests/e2e/cross-widget-filter-performance.spec.ts`, 12 gemeente-then-wijk clicks per chart kind, median / p95, log `triage/t14-perf-4.log`. Only consumers refetch: the non-consuming chart and the publisher sent no request and the non-consumer did not redraw; stats blocks now consume the bus too (`StatsBlockHost.vue`, test `chartAndStatsHosts.spec.js`). Click to every consumer showing the filtered data: 176 / 244 ms with `bar-list` charts, inside the bound; 9.8 / 13.6 s with ApexCharts bars, outside it. The request leaves 5-7 ms after the press and OpenRegister answers in 113-134 / 125-209 ms; the rest is ApexCharts redrawing (each SVG text measured with getComputedStyle and getBBox, up to 9.6 s of main thread per click). Left open until the chart redraw fits: that is a nextcloud-vue CnChartWidget/ApexCharts change. Since Task 36 the spec stores the nl-administrative hierarchy on its dashboards through the dashboard API. + - Code done, profiling left: `ChartHost.vue` adds the bus's clauses for the dimensions a chart consumes (`eq` and `in`) to its `dataSource.filter` (`consumedFilter`, `withBusFilter`); CnChartWidget refetches when that filter changes and shows its own loading state; a chart that consumes nothing keeps the same data source and does not refetch. Left unchecked for the profiling on a production OpenRegister, a live measurement. Tests: `chartAndStatsHosts.spec.js`, `chartHostResponsiveness.spec.js`. + - Rerun 22 Nov on development b8d53a224 with nextcloud-vue 2.192.0 (svg.js measures in a shadow root), 50,000 objects, box load average ~8 (livepass runs/cwf-perf2.log). `bar-list`: click to every consumer median 375 / p95 575 ms; OpenRegister time of the filtered aggregations 182 / 277 ms (113 / 125 ms at load 4.7 on 21 Nov). ApexCharts: not measured; after the gemeente click, the click on the first wijk bar sends no request within 30 s. Not ticked: neither renderer meets 300 ms at p95 on this run. + +### Saved Views (removed by decision, 22 Nov 2026) + +- ~~Task 11: Create a "Save view" modal in `Dashboard.vue` (triggered by a button in the active-filters panel or dashboard header). Capture a name and optional description, bundle the current filter state, and POST to the register endpoint `POST /register/saved-views` with payload matching the `saved_view` shape (dashboard scoped, creator marked, timestamp set). Success redirects to the saved-views dropdown. Link REQ-CWF-009.~~ + - Removed by decision on 22 Nov 2026 (Ruben): saved views make no sense in an app about boards; a board with its filters is the unit. The saved-views UI, service, `saved_view` schema and tests are gone, and REQ-CWF-009 is out of the spec. + +- ~~Task 12: Add a "Saved views" dropdown in the `Dashboard.vue` header. On mount, fetch the dashboard's saved views from `GET /register/saved-views?dashboard=<dashboardId>`. Render saved views in two sections: "My views" (createdBy current user) and "Shared views" (isShared=true). Clicking a saved view applies all its clauses to the bus (replacing non-pinned clauses), updates the URL, and triggers widget re-renders. Link REQ-CWF-009.~~ + - Removed by decision on 22 Nov 2026 (Ruben): saved views make no sense in an app about boards; a board with its filters is the unit. The saved-views UI, service, `saved_view` schema and tests are gone, and REQ-CWF-009 is out of the spec. + +- ~~Task 13: Add edit/delete affordances to saved views. Users who created a view can edit its name/description and delete it (delete endpoint `DELETE /register/saved-views/<id>`). Shared views are read-only for non-creators. Include an "unshare" action for the creator. Link REQ-CWF-009.~~ + - Removed by decision on 22 Nov 2026 (Ruben): saved views make no sense in an app about boards; a board with its filters is the unit. The saved-views UI, service, `saved_view` schema and tests are gone, and REQ-CWF-009 is out of the spec. + +### Telemetry & Persistence + +- [x] Task 14: Create `lib/Register/DashboardFilterStateRegister.php` as a new register schema for persisting saved views and telemetry. Implement the `saved_view` shape with fields: `id`, `dashboardId`, `name`, `description`, `filters` (JSON), `isShared`, `sharedWith`, `createdBy`, `createdAt`. Add endpoints: `POST /register/saved-views`, `GET /register/saved-views?dashboard=<id>`, `PATCH /register/saved-views/<id>`, `DELETE /register/saved-views/<id>`. Link REQ-CWF-009. + - Done as OpenRegister schemas, not a PHP class with its own endpoints: data lives in OpenRegister objects through its APIs (no own tables). `lib/Settings/register.d/drill-down-cross-widget-filter.json` adds `filter_event` to the launchpad register, and `ImportLaunchpadRegister::REGISTER_VERSION` moved to 1.0.3 so existing installs take it. Test: `tests/Unit/Repair/CrossWidgetFilterSchemasTest.php` (through the real import step). + - The `saved_view` schema and its endpoints were removed by decision on 22 Nov 2026 with saved views (Tasks 11-13). No table ever existed, so no migration drops one; an install that already imported the schema keeps it unused. + +- [x] Task 15: Implement filter telemetry logging in `useFilterBus.js`. When a clause is published and an org-level telemetry flag is enabled, construct a `filter_event` row with `eventType=apply`, the published clause's dimension/operator (no value), the source widget ID (if applicable), and the user ID. POST to `POST /register/filter-events` (implementation in Task 16). When "Reset filters" is invoked, write a separate `filter_event` with `eventType=reset` and the cleared clauses. When a bookmarked URL is loaded, write a `filter_event` with `eventType=bookmark` on next tick. Link REQ-CWF-010. + - Done: `src/composables/filterTelemetry.js` builds `filter_event` rows (dimension, operator, source, source widget, pinned; never the value) and writes them to OpenRegister's object endpoint for `launchpad/filter_event`, only while the organisation's switch is on. `useFilterBus` takes it as an optional `telemetry` option: `apply` for an accepted publish, `reset` with the cleared clauses (nothing for an empty reset), `bookmark` on the next tick for clauses restored from the URL. `Views.vue` passes it to the dashboard's filter session. Tests: `src/composables/__tests__/filterTelemetry.spec.js`. + +- [x] Task 16: Create endpoints in `lib/Register/DashboardFilterStateRegister.php` for telemetry: `POST /register/filter-events` persists the event row with no value data (dimensions + operators only). Implement a read-only aggregate report endpoint `GET /register/filter-events/report?dashboard=<id>` that returns paths and frequency counts (e.g., `[{path: "gemeenteCode → wijkCode", count: 42}, ...]`). This report is visible to dashboard owners and admins; restrict per-user telemetry to the current user's own events. Link REQ-CWF-010. + - Done: events are written to OpenRegister's object endpoint for `launchpad/filter_event` (Task 15), whose `filterDelta` items admit no `value`. The report is `GET /api/dashboards/{uuid}/filter-events/report` (`FilterEventReportController`, `FilterEventReportService`): per user and in time order, applies extend a path of dimensions until a reset (a bookmark starts a new one), and paths are counted, most used first. The owner and administrators get every user's paths (`scope: all`), another viewer only their own (`scope: own`), anyone else 404. Documented in `openapi.json`. Tests: `FilterEventReportServiceTest`, `FilterEventReportControllerTest`. + +- [x] Task 17: Add org-level telemetry toggle to the admin settings (or dashboard config). Default is `false` (telemetry disabled). When toggled on, `useFilterBus.js` starts writing `filter_event` rows for subsequent filter operations. Existing events are not retroactively generated. Link REQ-CWF-010. + - Done: `filterTelemetryEnabled` admin setting (`AdminSettingKey::FILTER_TELEMETRY_ENABLED`), off unless a stored `true`; a switch in Beheer (`AdminSettings.vue`), the `updateSettings` endpoint parameter, and the workspace initial state the recorder reads on every write, so switching on affects only later changes. Tests: `AdminSettingsServiceTest`, `AdminControllerSettingsAliasTest`, `AdminSettings.behaviour.spec.js`. + +### Testing + +- [x] Task 18: Vitest — `useFilterBus.js` conflict resolution. New clause for dimension X replaces old clause for X when sources differ; widget-click replaces widget-click (shows toast); urlBootstrap → widget-click is silent; pinned clause cannot be replaced (publication dropped, console log). Test that toggle (same clause clicked twice) removes the clause. Link REQ-CWF-001, REQ-CWF-005. + +- [x] Task 19: Vitest — `useFilterBus.js` hierarchy resolution. When a wijk-level click arrives, infer ancestor clauses (gemeentecode, provincecode) marked `source=parentScope`. When a province-level click arrives with existing wijk clauses, clear the wijk. When a wijk from a different gemeente is clicked, reject and log error (no matching parent). Test breadcrumb updates. Link REQ-CWF-004. + +- [x] Task 20: Vitest — `useDashboardFilter.js` serialization/deserialization. Serialize a set of clauses (verschiedende dimensions, operators, sources) to base64url-compact-JSON and back; verify round-trip fidelity. Malformed parameter returns empty clauses + warning. Verify the compact JSON uses short keys (d, o, v, s, w, p) and stays under 2 KB for a 10-clause set. Link REQ-CWF-003. + +- [x] Task 21: Vitest — widget manifest validation. Dashboard loads a widget with `consumes: ["wijkCode"]` but no hierarchy includes wijkCode; validation surfaces warning and marks widget as non-bus-participant. Widget with `publishes: [{fromField: "missingField"}]` but data has no "missingField" key; validation logs error and disables bus participation. Matching dimensions pass validation. Link REQ-CWF-008. + - Done: `src/utils/widgetBusDeclarations.js` (`validateBusDeclarations`), test `src/utils/__tests__/widgetBusDeclarations.spec.js`. + +- [x] Task 22: Playwright — end-to-end filter workflow. Dashboard with three widgets (A: gemeente chart, B: wijk table consuming gemeenteCode, C: status chips not consuming any dimension). User clicks "Zeist" on A; B re-renders with filtered data, C does not re-render, URL updates with `f=...` parameter. User clicks "Vollenhove" on A; A's selection toggles to Vollenhove (or clears if double-click), B updates, URL changes. User copies URL and opens in incognito browser; same filters restore. Link REQ-CWF-001, REQ-CWF-002, REQ-CWF-003. + - Written: `tests/e2e/cross-widget-filter-clicks.spec.ts` (click on A filters B and the URL, C asks nothing, a second pick replaces, the same pick toggles off, the copied URL restores in a separate login) and the URL restore in `tests/e2e/cross-widget-filter.spec.ts`. Run 22 Nov on the clone's bundle: the click test green in triage/t18c-03-bundle.log, t18c-04-bundle.log and t18c-06-bundle.log, the URL restore green in t18c-03-bundle.log (it timed out at load average ~30 in t18c-04 and t18c-06); red on the stack until fix 3b3789e58 (a bookmarked `f` is read on every boot switch; before it the live page never read `f`) is deployed (triage/t18c-07-deployed.log). Tick once deployed and rerun. + - Ticked 22 Nov: green on the stack after fix 3b3789e58 was deployed (development 28858ac3a), livepass run prog-chunki.03.log: cross-widget-filter-clicks.spec.ts:168 and cross-widget-filter.spec.ts:63. + +- [x] Task 23: Playwright — hierarchy drill-down. Dashboard with nl-administrative hierarchy. User clicks a wijk; breadcrumb shows "Provincie X > Gemeente Y > Wijk Z", gemeentecode and provincieCode are inferred in the bus. User clicks up to provincie; wijk and gemeente are cleared, breadcrumb updates. User clicks a different wijk in a different gemeente; ancestors change, breadcrumb updates. Link REQ-CWF-004. (written, runs in nightly: tests/e2e/cross-widget-filter-clicks.spec.ts) + - Built: `FilterBreadcrumb.vue` shows each hierarchy's path under the active-filters panel ("Province PV26 > Municipality GM0355 > District WK035501"); a step above the deepest goes back up through `bus.popTo()` (the levels below clear, an inferred level becomes the reader's own). A chart click on a hierarchy level reads the missing ancestors from one record of the clicked category (`src/utils/clickedRow.js`), so the bus infers them. Written: the breadcrumb test in `tests/e2e/cross-widget-filter-clicks.spec.ts` (wijk click shows provincie and gemeente, back to provincie clears gemeente and wijk and filters the gemeente chart to that provincie, a wijk elsewhere moves both ancestors). Run 22 Nov on :8076 with the branch's bundle (`LAUNCHPAD_BUNDLE_DIR`): 1/1 green. Tick once deployed and rerun on the deployed bundle. + +- [x] Task 24: Playwright — conflict resolution and audit. Two charts (A and B) both publish gemeenteCode. User clicks Zeist on A; A highlights, B's data filters to Zeist. User clicks Houten on B; A's highlight clears, B highlights, a toast says "Gemeente filter changed: Zeist → Houten", active-filters panel shows only Houten. URL reflects the change. Link REQ-CWF-005. (written, runs in nightly: tests/e2e/cross-widget-filter-clicks.spec.ts) + - Written: `tests/e2e/cross-widget-filter-clicks.spec.ts` (two charts publish gemeenteCode; a pick on the second replaces the first's filter, the toast "Municipality filter changed: X → Y", one chip naming the second chart, B filtered, URL updated). Run 22 Nov on the stack: 1/1 green (triage/t18c-07-deployed.log). Left unticked: CnChartWidget has no selected/highlight state, so "A's highlight clears, B highlights" cannot be shown or tested. + +- [x] Task 25: Playwright — reset filters. Dashboard with 5 active clauses, one pinned. User clicks "Reset filters"; 4 non-pinned clauses disappear, pinned remains, URL `f` parameter is removed, consuming widgets re-render. Active-filters panel shows only the pinned clause. User clicks Reset on an already-empty bus; no change, no telemetry event. Link REQ-CWF-006. + - Written: `tests/e2e/cross-widget-filter.spec.ts` (five clauses, one pinned, restored through `f`; reset leaves the pinned one and `f` holds only it; an unfiltered dashboard has no panel, no reset and no `f`). The spec's pinned clause used `source: pinned`, which the URL decoder rightly refuses (pinned is a flag); fixed to a pinned userExplicit clause. Run 22 Nov: green on the clone's bundle (triage/t18c-04-bundle.log, t18c-06-bundle.log), red on the stack until fix 3b3789e58 (a bookmarked `f` is read on every boot switch; before it the live page never read `f`) is deployed. Tick once deployed and rerun. + - Ticked 22 Nov: green on the stack after fix 3b3789e58 was deployed (development 28858ac3a), livepass run prog-chunki.03.log: cross-widget-filter.spec.ts:95 and :125. + +- [x] Task 26: Playwright — active-filters panel interactions. Dashboard with 3 clauses (one widgetClick, one urlBootstrap, one pinned). Panel renders all three with source icons (widget name for widgetClick, no icon for urlBootstrap, lock for pinned). Pinned clause has no remove-button; others do. User clicks remove on a widgetClick clause; it vanishes, URL updates, publishing widget's selection clears. Non-pinned clauses can be individually removed; pinned cannot. Link REQ-CWF-007. (written, runs in nightly: tests/e2e/cross-widget-filter.spec.ts, tests/e2e/cross-widget-filter-clicks.spec.ts) + - Written: `tests/e2e/cross-widget-filter.spec.ts` (source note, lock and no remove button on the pinned clause, removing one clause updates `f`) and `tests/e2e/cross-widget-filter-clicks.spec.ts` (a clicked clause names its chart; removing it unfilters the consumer and drops `f`, 1/1 green on the stack, triage/t18c-07-deployed.log). The URL half is green on the clone's bundle (t18c-04, t18c-06) and red on the stack until fix 3b3789e58 (a bookmarked `f` is read on every boot switch; before it the live page never read `f`) is deployed. "Publishing widget's selection clears" is not testable: CnChartWidget keeps no selection state. + +- ~~Task 27: Playwright — saved views. User applies filters (3 clauses), clicks "Save view", provides name "Q2 Trend". View is saved and appears in the dropdown. Same user clicks it again later with different filters active; all 3 clauses are restored. User shares the view; another user sees it in the "Shared" section. Shared view is read-only (no edit/delete). Link REQ-CWF-009.~~ + - Removed by decision on 22 Nov 2026 (Ruben): saved views make no sense in an app about boards; a board with its filters is the unit. The saved-views UI, service, `saved_view` schema and tests are gone, and REQ-CWF-009 is out of the spec. + +- [x] Task 28: Playwright — telemetry recording (when enabled). Enable org-level telemetry. User clicks Zeist on a chart; a `filter_event` row is written with `eventType=apply`, dimension=gemeenteCode, operator=eq, sourceWidgetId=<chart>, no value field. User copies URL and opens in another tab; on load, a `filter_event` with `eventType=bookmark` is written. User clicks "Reset filters"; a `filter_event` with `eventType=reset` and the cleared clauses is written. Disable telemetry; no events are written on subsequent actions. Link REQ-CWF-010. + - Written: `tests/e2e/cross-widget-filter-telemetry.spec.ts` (bookmark and reset rows without values while the switch is on; nothing while it is off) and the `apply` row of a click in `tests/e2e/cross-widget-filter-clicks.spec.ts` (dimension, operator, widget id, no value; 1/1 green on the stack, triage/t18c-05-deployed.log, t18c-07-deployed.log). The telemetry spec is 2/2 on the clone's bundle (triage/t18c-03-bundle.log) and red on the stack until fix 3b3789e58 (a bookmarked `f` is read on every boot switch; before it the live page never read `f`) is deployed (no bookmark row without it). Tick once deployed and rerun. + - Ticked 22 Nov: green on the stack after fix 3b3789e58 was deployed (development 28858ac3a), livepass run prog-chunki.03.log: cross-widget-filter-clicks.spec.ts:261 and cross-widget-filter-telemetry.spec.ts:90 and :123. + +- [x] Task 29: Playwright — manifest validation warnings in widget config. Dashboard loads a widget that consumes "wijkCode" but wijkCode is not in the dashboard's hierarchies; widget config UI shows a yellow warning chip ("This widget consumes wijkCode but no hierarchy on this dashboard publishes it"). Widget still renders but does not participate in the bus. User can dismiss the warning or remove the widget. Link REQ-CWF-008. (written, runs in nightly: tests/e2e/cross-widget-filter-manifest-warnings.spec.ts) + - Written: `tests/e2e/cross-widget-filter-manifest-warnings.spec.ts` (a chart consuming wijkCode on a dashboard without hierarchies renders, logs that it is off the bus, and its edit dialog shows the warning). Run 22 Nov on the stack: 1/1 green (triage/t18c-05-deployed.log). Left unticked: the notice cannot be dismissed (CnAddWidgetModal notices have no dismiss); removing the widget is the ordinary Remove. + +- [x] Task 30: Vitest — 300 ms responsiveness. Mock a widget's refetch to resolve after 100 ms, another after 250 ms. Trigger a filter publication; measure the time from publish to all consuming widgets updated in the DOM. Confirm both are within 300 ms (or log a performance warning if they exceed it). Link REQ-CWF-002. + - Done: `src/components/Widgets/Renderers/__tests__/chartHostResponsiveness.spec.js` mounts two consuming charts whose fetch takes 100 ms and 250 ms and one non-consumer; after a publish both consumers show the filtered data within 300 ms and the non-consumer does not refetch. + +### Quality & Documentation + +- [x] Task 31: ESLint clean on touched Vue/JS files. PHPCS/PHPMD clean on new PHP classes. PHPStan/Psalm type-checking on the new Register class. No new TSConfig errors if TypeScript is in use. Run `composer check:strict` before commit. Link company-wide ADR-009 (quality gates). + - Done: eslint clean on every touched JS/Vue file; phpcs, phpmd and phpstan clean on `FilterEventReportService.php` and `FilterEventReportController.php`, psalm reports no errors on them (the two class-level `@spec` warnings on `PageController.php` and `InitialStateBuilder.php` predate this change). No TypeScript is in use. + +- [x] Task 32: i18n review. No new user-facing strings expected except: "Active filters" panel header, "Reset filters" button, conflict resolution toast ("Gemeente filter changed: X → Y"), permission-denied tooltip ("no access to this scope"). All strings added to both `lang/nl.json` and `lang/en.json` with translation keys (e.g., `filter.activeFilters`, `filter.resetButton`). Link company-wide ADR-005 (i18n). + - Done 19 Nov: every string of the filter panel and the chart pick (`ActiveFiltersPanel.vue`, `ChartHost.vue`; the saved-views strings left with saved views on 22 Nov 2026; the conflict toast `{name} filter changed: {from} → {to}` and the refusal `You have no access to this scope: {name}` among them) is in `l10n/nl.js`, `nl.json`, `en.js` and `en.json`. Nextcloud keys translations by their English source text, so there are no `filter.*` keys. + - Partly done: the app's catalogues are `l10n/*.js` and `l10n/*.json` keyed by the English source string (not `lang/` with dotted keys); "Active filters", "Reset filters" and the telemetry switch are in `en` and `nl`. Left: the conflict toast and the "no access to this scope" tooltip, which have no call site until a widget click publishes (Task 7). + +- [x] Task 33: Inline documentation. `useFilterBus.js` includes a header comment summarizing the pub/sub contract, conflict resolution rules, and hierarchy semantics with links to REQ-CWF-001–005. `useDashboardFilter.js` documents the URL encoding scheme (compact JSON, keys, length guidance). `DashboardFilterStateRegister.php` documents the register shapes and endpoint contracts. No separate design doc needed; context-brief.md and this spec.md are the authoritative references. Link company-wide ADR-010 (documentation). + - Done: `useFilterBus.js` opens with the contract, conflict and hierarchy rules; `useDashboardFilter.js` with the URL encoding (keys, base64url, length); there is no `DashboardFilterStateRegister.php` (Task 14 made the shapes OpenRegister schemas), so the shapes are documented in `lib/Settings/register.d/drill-down-cross-widget-filter.json` and the report contract in `FilterEventReportService.php`, `FilterEventReportController.php` and `openapi.json`; the widget declarations in `src/utils/widgetBusConsumption.js`. + +- [x] Task 34: Changelog entry. Summarize the feature: "Add cross-widget filter bus enabling drill-down exploration across dashboard widgets. Widgets publish filters on click; all consuming widgets re-render. Filter state is bookmarkable via URL. Opt-in telemetry measures drill-down path usage." Include a note that existing widgets that accept `filterContext` become instant bus participants with zero code change. + - Done: an entry under Unreleased / Added in `CHANGELOG.md`. A chart joins the bus by declaring `consumes`/`publishes` (Task 8) rather than with zero change, because no widget accepts a `filterContext` today; the entry says so. + +- [x] Task 35: Performance audit. After widgets are wired to the bus, measure query time for drill-down operations (e.g., click gemeentecode, then wijkcode) on a representative local stack (volume recorded). Confirm the 300 ms responsiveness bound is met. Log a performance warning if a single widget re-render exceeds 200 ms (indicating slow OR query). Profile memory usage on a dashboard with 100+ widgets to ensure the bus's pub/sub subscription overhead is negligible (<1 MB). Document results as a comment in `Dashboard.vue`. Link REQ-CWF-002. + - Done 21 Nov on the local stack of Task 10 (same volume and spec, log `triage/t14-perf-4.log`; volume in the livepass ledger). OpenRegister time of the filtered aggregations, median / p95: gemeente step 113 / 125 ms (134 / 209 ms in the ApexCharts run), wijk step 108 / 118 ms (153 / 196 ms). Per-widget re-render after a click: `bar-list` 173 / 216 ms (wijk chart) and 173 / 244 ms (status chart); ApexCharts 8.1 / 12.1 s and 8.2 / 13.6 s, so the 300 ms bound holds for HTML charts and is missed by ApexCharts redrawing, not by the query. The warning: `ChartHost.vue` and `StatsBlockHost.vue` time each refetch from the filter change to the widget's new data (`refetchClock` in `src/utils/widgetBusConsumption.js`, a `launchpad:filter-refetch` performance measure) and log `[launchpad] widget <id> took <n> ms to show its data after a filter change (over 200 ms): <filter>` (test `chartHostResponsiveness.spec.js`). Memory: 110 charts on the bus over the same charts off it, median heap of 4 loads each, +330,616 bytes (bound 1 MB). The dashboard view is `src/views/Views.vue` (there is no `Dashboard.vue`); the results are the comment on `openFilterSession()`. + +### Stored hierarchies (REQ-CWF-011, Ruben 21 Nov 2026) + +- [x] Task 36: Storage. A nullable `hierarchies` JSON column on `launchpad_dashboards` (migration), read as `[]` when empty, on the `Dashboard` entity and its wire format (owner and viewer reads). Link REQ-CWF-011. + +- [x] Task 37: API validation. `PUT /api/dashboard/{id}` accepts `hierarchies`; `DashboardHierarchies::validated()` refuses a malformed descriptor with 400 before anything is saved, and the update needs the same permission as a layout change. `openapi.json` documents the field. Link REQ-CWF-011. + +- [x] Task 38: Preset. The `nl-administrative` hierarchy (province > municipality > district > neighbourhood, Ruben 21 Nov) ships as a selectable preset in `src/utils/hierarchyPresets.js`, with nl and en level labels. Link REQ-CWF-011. + +- [x] Task 39: Settings UI. The dashboard settings modal lets an owner or editor pick the dashboard's hierarchies from the presets; only a changed choice is sent. Link REQ-CWF-011. + +- [x] Task 40: Bus. After a save that changes the hierarchies of the open dashboard, its filter session is rebuilt on the stored hierarchies; a preset's level labels follow the reader's language. Link REQ-CWF-011, REQ-CWF-004. + +- [x] Task 41: Tests. The performance spec stores the hierarchy through the dashboard API instead of adding it to the dashboard read; `tests/e2e/dashboard-hierarchies.spec.ts` covers storing, reading, refusing and clearing. Link REQ-CWF-011. + +- [x] Task 42: Copies. A fork, a dashboard made from a template and an import keep the source's hierarchies (`DashboardService::persistFork()`, `TemplateService::buildDashboardFromTemplate()`, `ImportService::applyEntityHierarchies()`; export already writes them). A malformed list in an archive is left out with a warning. Tests: `DashboardHierarchiesCopyTest.php`, `DashboardServiceForkTest::testForkKeepsTheSourcesHierarchies`, and the copies scenario in `dashboard-hierarchies.spec.ts`. Link REQ-CWF-011 (Ruben 21 Nov). + +Built so far: Tasks 1-3 (`src/composables/useFilterBus.js`, `src/composables/useDashboardFilter.js`) and their vitest specs, Tasks 18-20. Ancestor clauses are inferred from the clicked row's fields (`publish(clause, {row})`); a wijk in another gemeente moves the inferred ancestors with it (Task 23), and a publication is refused only when an ancestor is pinned to another value. Then Tasks 4-6 and 21: the bus on the dashboard, its URL sync and the active-filters panel with "Reset filters" (strings in all locales). Open: widget publishing and consuming (Tasks 7-10), the register and telemetry (14-17), the Playwright and performance tasks (22-30, 35), and 31-34. + +## Verification + +`openspec validate` exits clean. Dashboard with bus-aware widgets enables seamless drill-down filtering; filter state is reproducible via URL and bookmarkable; telemetry (if enabled) records paths without exposing values. + +## Tests (company-wide ADR-009) + +- Vitest: conflict resolution, hierarchy resolution, serialization, manifest validation, responsiveness (Tasks 18–21, 30). +- Playwright: end-to-end workflows, widget integration, telemetry (Tasks 22–29; Task 27 removed). +- No new backend-specific tests beyond register integration; existing REQ-WDG-006 (widget fetch) tests cover the query integration. + +## Documentation (company-wide ADR-010) + +- Inline composable comments (Tasks 33). +- Changelog entry (Task 34). +- No separate ADR needed; the feature is scoped to this change and well-documented in the context-brief.md and spec.md. +- User guide (out of scope for this change, but mentioned in design.md under "open questions"): URL bookmarking, hierarchy breadcrumb, conflict resolution toast. + +## i18n (company-wide ADR-005) + +- All user-facing strings added to both `nl.json` and `en.json` (Task 32). +- Dutch locale is the primary; English is a parity copy. No culture-specific logic (e.g., date/number formatting) required for filter state. diff --git a/openspec/changes/archive/2026-11-25-header-search-dropdown/proposal.md b/openspec/changes/archive/2026-11-25-header-search-dropdown/proposal.md new file mode 100644 index 000000000..d72eb2deb --- /dev/null +++ b/openspec/changes/archive/2026-11-25-header-search-dropdown/proposal.md @@ -0,0 +1,21 @@ +# Proposal: header-search-dropdown + +## Why + +Board LpWerkplek opens a results list under the top bar's search field while someone types: "You searched for team", a "Dashboards" group with "Permits team" (shared by Marieke Jansen, 14 widgets) and "Zuiddrecht intranet" (group dashboard of Communications), the first row selected, and at the foot the tip "Tip: type !top to search TOPdesk directly". + +Live, the top bar's field is Nextcloud's own unified search. Thematiq only changes its words (`js/search-placeholder.js`). Typing opens Nextcloud's search dialog, not a list under the field. LaunchPad already returns its dashboards to that search (`lib/Search/LaunchPadSearchProvider.php`, REQ-SRCH-001..012) and knows the search shortcuts (`SearchShortcutService`), but nothing draws them where the board does. + +This is not a small change. The field belongs to Nextcloud core, so the list needs its own component that takes over the field's input on LaunchPad pages, reads the unified search providers, and keeps the keyboard and screen reader behaviour of a combobox. + +## What changes + +- `nc-unified-search-integration`: ADDED REQ-SRCH-013. On a LaunchPad page, typing in the top bar's search field opens a results list under the field. The list names the query, groups the results per provider with LaunchPad's dashboards first, and ends with the shortcut tip when shortcuts exist. It is a combobox: arrow keys move the selection, Enter opens the selected result, and Escape closes the list. "Show all results" hands the query to Nextcloud's own search dialog. + +## Impact + +- New `src/components/HeaderSearchDropdown.vue`, mounted from `src/main.js` against the core field (`.unified-search-input`). +- `lib/Search/LaunchPadSearchProvider.php`: a result's subline needs the owner or group and the widget count ("Shared by Marieke Jansen · 14 widgets"). +- `SearchShortcutService`: the first configured shortcut, for the tip. +- Thematiq keeps changing the field's words. Its `search-placeholder.js` must not fight the new component over the input. +- Translations in every shipped locale. diff --git a/openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md b/openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md new file mode 100644 index 000000000..0cadc12fa --- /dev/null +++ b/openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md @@ -0,0 +1,34 @@ +# Delta: nc-unified-search-integration + +## ADDED Requirements + +### Requirement: REQ-SRCH-013 The top bar search shows its results under the field + +On a LaunchPad page, typing two or more characters in the top bar's search field MUST open a results list under the field, as wide as the field. The list MUST start with "You searched for <query>", MUST group the results per search provider under the provider's name in capitals, with LaunchPad's dashboards first, and MUST show each result with its icon, its name and one line of detail (for a dashboard: who shared it and how many widgets it has, or the group it belongs to). When search shortcuts are configured, the list MUST end with "Tip: type <prefix> to search <name> directly" for the first one. + +The list MUST behave as a combobox (WAI-ARIA 1.2): the field has `role="combobox"` and `aria-expanded`, the list has `role="listbox"`, and each result has `role="option"`. The first result is selected when the list opens. Arrow keys move the selection, Enter opens the selected result, and Escape closes the list and keeps the query. A "Show all results" row MUST hand the query to Nextcloud's own search dialog. + +#### Scenario: Results under the field + +- **GIVEN** Pieter is on My workspace and can see the dashboards "Permits team" and "Zuiddrecht intranet" +- **WHEN** he types "team" in the top bar's search field +- **THEN** a list opens under the field that starts with "You searched for team" +- **AND** under "DASHBOARDS" it shows "Permits team" with "Shared by Marieke Jansen · 14 widgets", selected, and "Zuiddrecht intranet" with "Group dashboard of Communications" + +#### Scenario: The keyboard drives the list + +- **GIVEN** the list is open for "team" with "Permits team" selected +- **WHEN** Pieter presses Arrow down and then Enter +- **THEN** "Zuiddrecht intranet" opens + +#### Scenario: The shortcut tip + +- **GIVEN** the shortcut "!top" for TOPdesk is configured +- **WHEN** the list opens +- **THEN** its last row reads "Tip: type !top to search TOPdesk directly" + +#### Scenario: Escape closes the list + +- **GIVEN** the list is open +- **WHEN** Pieter presses Escape +- **THEN** the list closes, the field keeps "team" and keeps the focus diff --git a/openspec/changes/archive/2026-11-25-header-search-dropdown/tasks.md b/openspec/changes/archive/2026-11-25-header-search-dropdown/tasks.md new file mode 100644 index 000000000..d90caea58 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-header-search-dropdown/tasks.md @@ -0,0 +1,10 @@ +# Tasks: header-search-dropdown + +- [x] `HeaderSearchDropdown.vue`: a combobox list under the core search field on LaunchPad pages, fed by the unified search providers, LaunchPad's dashboards first +- [x] Dashboard results carry their detail line (shared by, widget count, group) +- [x] The shortcut tip from `SearchShortcutService` +- [x] "Show all results" opens Nextcloud's search dialog with the query +- [x] Keep thematiq's field words working alongside the component +- [x] Translations in every shipped locale +- [x] Unit tests: grouping, the detail line, keyboard selection, Escape +- [x] Playwright: type "team" on My workspace and open "Zuiddrecht intranet" with the keyboard (board LpWerkplek). `tests/e2e/header-search-dropdown.spec.ts` 2/2 green on a sandbox Nextcloud 34.0.6 + MariaDB (25 Nov 2026). The run showed that core's desktop top bar has only a button since Nextcloud 31, so the list had no field to serve; LaunchPad now places its own field in the button's place (`src/utils/headerSearchField.js`, unit tests `headerSearchField.spec.js` and the Nextcloud 31+ block in `HeaderSearchDropdown.spec.js`). diff --git a/openspec/changes/archive/2026-11-25-icon-only-app-tiles/proposal.md b/openspec/changes/archive/2026-11-25-icon-only-app-tiles/proposal.md new file mode 100644 index 000000000..629330db2 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-icon-only-app-tiles/proposal.md @@ -0,0 +1,27 @@ +# Proposal: icon-only-app-tiles + +## Why + +Every launchpad board that shows apps draws them the same way (DEMO-SEED, "Rules that every board follows"; boards +LpVandaag, LpWerkplek, LpBewerken, LpMobiel, LpIntranet, LpAfdeling, LpTegelBewerken): each application is its own +widget on the grid, square, in a solid tile colour, with one white icon and no printed label. The app name is the +accessible name and the tooltip. Optional marks: a count (white pill, top right), a pin (top left) and a red outage +dot (top right, in place of the count). The tile form offers the colour as eight theme colours, and the white icon +keeps enough contrast on each. + +On development a tile placement can set `content.iconOnly`, and `TileWidget.vue` then draws the pin, the count and the +outage dot. But the count and the outage are static values in the placement (`content.badge`, `content.status`), the +colour is a free hex value, and no requirement describes any of it. + +## What changes + +- `tiles`: an icon-only tile (REQ-ICT-001), its count read live from a count source (REQ-ICT-002), its outage dot from + the tile's health ping (REQ-ICT-003), and the colour chosen from eight theme colours (REQ-ICT-004). +- The count source is configuration: an OpenRegister count query or the item count of a Nextcloud dashboard widget. + No app is named in code. + +## Impact + +- `src/components/TileWidget.vue`, the tile form (`src/modals/TileEditor.vue`), a small count resolver, the health + ping badge, translations. +- Existing tiles with a hex colour keep it. diff --git a/openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/service-health-ping/spec.md b/openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/service-health-ping/spec.md new file mode 100644 index 000000000..bd3586250 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/service-health-ping/spec.md @@ -0,0 +1,35 @@ +# Delta: service-health-ping + +## MODIFIED Requirements + +### Requirement: REQ-HPING-003 Cache the badge and refresh it in the background + +The system MUST cache the badge state in `ICache` with a short TTL and MUST refresh due entries from a background job so viewers do not pay upstream latency. + +#### Scenario: Endpoint serves the cached badge +- GIVEN a ping-enabled placement the current user may view +- WHEN the tile calls `GET /api/health-ping/{placementId}` +- THEN the response MUST be `{ state, checkedAt, latencyMs, stale, downSince }`, where `downSince` is the time of the first failed check of the current run of failures while `state` is `offline`, and null otherwise (icon-only-app-tiles REQ-ICT-003) +- AND the response MUST NOT contain the health URL, request headers, or upstream response body + +#### Scenario: Caller authorization +- GIVEN a ping-enabled placement on a dashboard the current user may NOT view +- WHEN the user calls `GET /api/health-ping/{placementId}` +- THEN the system MUST return 403 and MUST NOT perform or reveal the ping + +#### Scenario: Cached within TTL +- GIVEN a tile with interval 60 whose badge was refreshed 20 seconds ago +- WHEN the endpoint is called again +- THEN the system MUST return the cached badge with `stale = false` and MUST NOT perform a new upstream request + +#### Scenario: Background refresh of due entries +- GIVEN ping-enabled placements whose cached badge is older than their interval +- WHEN the `HealthPingRefreshJob` `TimedJob` runs +- THEN it MUST refresh only the due, ping-enabled placements and skip any whose host is not allow-listed + +#### Scenario: Stale fallback on refresh failure +- GIVEN a previously cached badge exists and its interval has passed +- WHEN a refresh fails to reach the upstream, fewer times in a row than `healthping_offline_after_failures` +- THEN the endpoint MUST return the last-known badge with `stale = true` and the tile MUST NOT crash +- AND the cache MUST keep the last-known badge beyond the ping interval, so the interval decides when the next ping is due, not whether the badge survives + diff --git a/openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md b/openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md new file mode 100644 index 000000000..47f28fb51 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md @@ -0,0 +1,85 @@ +# Delta: tiles + +## ADDED Requirements + +### Requirement: A tile can be an app tile with only its icon (REQ-ICT-001) + +A tile placement with `content.iconOnly: true` SHALL render as an app tile: a square in the tile's colour, as wide as +one grid column, with the tile's icon in white at about 45% of the square and no printed label, card, header or +padding around it. The tile's title SHALL be its accessible name and its tooltip. In edit mode the tile SHALL have its +own drag handle and widget menu and SHALL move and resize like any widget. With `content.pinned: true` it SHALL show a +pin at the top left. The marks SHALL be decorative (`aria-hidden`); what they say SHALL be part of the accessible name +("Zaaksysteem, 14 open", "Raadsinformatie, storing"). + +#### Scenario: Six app tiles under Mijn apps + +- **GIVEN** Pieter's dashboard holds a Tussenkop "Mijn apps" and six icon-only tiles +- **WHEN** he opens the dashboard +- **THEN** each tile is a coloured square with a white icon and no visible name +- **AND** hovering Zaaksysteem shows the tooltip "Zaaksysteem", and a screen reader reads its name + +#### Scenario: Four tiles per row on a phone + +- **GIVEN** the same dashboard at 390 px wide +- **WHEN** it renders +- **THEN** the app tiles stand four to a row + +### Requirement: An app tile shows a live count (REQ-ICT-002) + +An icon-only tile MAY name a count source in `content.countSource`: + +- `{"type": "register", "register": …, "schema": …, "filter": {…}}`: the number of OpenRegister objects the viewer may + read that match the filter, asked with the viewer's own session; the filter value `@me` stands for the viewer; +- `{"type": "nc-widget", "widgetId": …}`: the number of items a Nextcloud dashboard widget (API v2) returns for the + viewer. + +The count SHALL show as a white pill at the top right, "99+" above 99, and SHALL NOT show when it is 0 or the source +does not answer. The tile SHALL refresh the count when the dashboard refreshes, at most once a minute. A count source +whose app is not installed SHALL show no pill and no error. + +#### Scenario: Open cases on the Zaaksysteem tile + +- **GIVEN** a tile Zaaksysteem with `countSource` type register, register `dossiq`, schema `case`, filter `{"assignee": "@me", "isFinalStatus": false}` +- **AND** 14 open cases are assigned to Pieter +- **WHEN** Pieter opens the dashboard +- **THEN** the tile shows the pill "14" + +#### Scenario: The source app is missing + +- **GIVEN** the same tile on an instance without the register `dossiq` +- **WHEN** the dashboard renders +- **THEN** the tile shows no pill and no error + +### Requirement: An app tile shows an outage (REQ-ICT-003) + +When the tile's health ping (service-health-ping) reports the service down, an icon-only tile SHALL show a red dot at +the top right in place of the count, and its accessible name SHALL say the service is down since the time of the +first failed check. When the service answers again, the dot SHALL go and the count SHALL return. + +#### Scenario: Raadsinformatie is down + +- **GIVEN** the tile Raadsinformatie has a health ping and its last checks failed since 09:12 +- **WHEN** Pieter opens the dashboard +- **THEN** the tile shows the red dot and no count +- **AND** its accessible name reads "Raadsinformatie, storing sinds 09:12" + +### Requirement: The tile colour is one of eight theme colours (REQ-ICT-004) + +The tile form (board LpTegelBewerken, "Kleur") SHALL offer the colour as a radio group of eight swatches, one per +theme token: `--sc-primary`, `--sc-primary-deep`, `--sc-accent`, `--sc-accent-deep`, `--sc-work-ink`, +`--sc-work-text`, `--sc-work-muted`, `--sc-work-field`, each previewing the white icon. The tile SHALL store the +token name (`content.colourToken`) and SHALL render through the token, so the colour follows the theme. Each swatch +SHALL have a name for screen readers. A tile that stores a hex colour SHALL keep rendering it. When a theme adds +tokens, the palette MAY grow; a token the theme does not define SHALL fall back to `--sc-primary`. + +#### Scenario: Pieter colours Zaaksysteem + +- **GIVEN** Pieter edits the tile Zaaksysteem +- **WHEN** he chooses the swatch for the primary colour and saves +- **THEN** the tile stores `colourToken: "--sc-primary"` and renders in the theme's primary colour with a white icon + +#### Scenario: The theme changes + +- **GIVEN** a tile with `colourToken: "--sc-accent"` +- **WHEN** the administrator switches the instance theme +- **THEN** the tile takes the new theme's accent colour without being edited diff --git a/openspec/changes/archive/2026-11-25-icon-only-app-tiles/tasks.md b/openspec/changes/archive/2026-11-25-icon-only-app-tiles/tasks.md new file mode 100644 index 000000000..97c418dd5 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-icon-only-app-tiles/tasks.md @@ -0,0 +1,10 @@ +# Tasks: icon-only-app-tiles + +- [x] `TileWidget.vue`: icon-only render (square, white icon at about 45%, no label), the title as accessible name and tooltip, the marks `aria-hidden` and their meaning in the accessible name +- [x] Count resolver (`src/services/tileCount.js`): `register` sources through OpenRegister's count with `@me` replaced by the viewer, `nc-widget` sources through the dashboard API v2 items; at most once a minute; no pill on 0, error or missing app +- [x] Outage dot from the tile's health ping result (REQ-HPING-003 cache) in place of the count; drop the static `content.status` and `content.badge` reads +- [x] Tile form (`src/modals/TileEditor.vue`): colour as a radio group of the eight theme tokens with a white icon preview; store `colourToken`; hex colours keep rendering +- [x] Demo seed: the app tiles name their count source and colour token instead of static values +- [x] Translations for the accessible names and swatch names in every shipped locale +- [x] Unit tests: icon-only render and accessible name; count resolver for both source types, 0, 99+, missing app; outage replaces the count; colour token stored and rendered, unknown token falls back +- [x] Playwright: a dashboard with app tiles shows a live count and the outage dot; choosing a swatch in the tile form changes the tile colour (`tests/e2e/icon-only-app-tiles.spec.ts` 2/2 green on a sandbox Nextcloud 34.0.6 + MariaDB, 25 Nov 2026; the spec now adds raad.example.org to the allowed websites with purpose Fetch, since health pings are fail-closed, and puts the earlier list back) diff --git a/openspec/changes/archive/2026-11-25-launchpad-demo-seed/proposal.md b/openspec/changes/archive/2026-11-25-launchpad-demo-seed/proposal.md new file mode 100644 index 000000000..d1ca94057 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-launchpad-demo-seed/proposal.md @@ -0,0 +1,24 @@ +# Proposal: launchpad-demo-seed + +## Why + +Every LaunchPad board on identity.conduction.nl/screens should be reproducible in a running demo environment, with +its widgets, its people and its data. The spec of that seed lives in ConductionNL/design-system, +`screens-src/launchpad/DEMO-SEED.md`. The demo showcases install one dashboard for everyone, so they cannot show a +personal start page, a department page shared by a team leader, a view-only management page or a first visit. + +## What changes + +- A demo seed, `data/demo-seed/zuiddrecht-boards.json`, describes the users and groups, the app tile catalogue, the + allowed sites, two announcements, the shared team folder and one dashboard per board (Vandaag, Mijn werkplek, + Intranet Zuiddrecht, Team Vergunningen, Managementinformatie). The first-run user `nieuw` gets no dashboard. +- `occ launchpad:demo:load` writes it. Every dashboard has a fixed UUID, so a second run leaves the same state. +- The seed reuses the showcase rules: the same placement hydrator and the same check for which widget types this + instance renders. A widget whose type is not registered yet is placed as its fallback or skipped, and appears on the + next run once its type ships. +- `--retire-showcases` uninstalls the bundled showcases, which are visible to everyone and so hide the first visit. + +## Out of scope + +- Data in other apps' registers (dossiq cases, OpenProject work packages, XWiki pages, mail, calendar events). +- Dashboard versions, public links, scheduled exports, the kiosk set and the store registry stub. diff --git a/openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md b/openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md new file mode 100644 index 000000000..5ea3ed6d0 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-launchpad-demo-seed/specs/demo-data-showcases/spec.md @@ -0,0 +1,48 @@ +--- +capability: demo-data-showcases +status: draft +--- + +# Demo data showcases + +## ADDED Requirements + +### Requirement: REQ-DEMO-010 Demo seed of the boards + +LaunchPad SHALL ship a demo seed that reproduces the LaunchPad boards: demo users and groups, an app tile catalogue, +announcements, a shared team folder and one dashboard per board, each with a fixed UUID. `occ launchpad:demo:load` +SHALL write it. Users that exist keep their password; dashboards with the seeded UUID are updated and get the seeded +placements and shares again. + +#### Scenario: Running the seed twice + +- **GIVEN** an instance where the seed ran once +- **WHEN** an administrator runs `occ launchpad:demo:load` again +- **THEN** no user, group, catalogue entry or dashboard is added +- **AND** every seeded dashboard has the same widgets, positions and shares as after the first run + +#### Scenario: Pieter opens LaunchPad + +- **GIVEN** the seed ran +- **WHEN** `pieter` opens LaunchPad +- **THEN** his dashboard Vandaag opens first +- **AND** Mijn werkplek, Intranet Zuiddrecht, Team Vergunningen and Managementinformatie are in his dashboard list + +#### Scenario: A first visit + +- **GIVEN** the seed ran with `--retire-showcases` +- **WHEN** `nieuw` opens LaunchPad +- **THEN** the page says "U heeft nog geen dashboard" and offers to start with the starter widgets + +### Requirement: REQ-DEMO-011 Seed widgets wait for their type + +A seed widget whose type is not registered on the instance SHALL be placed as its `fallback` entry when it has one and +that type is registered, and SHALL otherwise be skipped and reported. A seed tile SHALL be an `app-tile` when its app is +enabled and the `app-tile` type is registered, and a launcher tile in the tile's colour otherwise. + +#### Scenario: The wiki widget is not built yet + +- **GIVEN** no `wiki` widget type is registered +- **WHEN** the seed runs +- **THEN** Mijn werkplek has no wiki widget and the command lists `wiki (Wiki)` as skipped +- **AND** after the type ships, the next run places it diff --git a/openspec/changes/archive/2026-11-25-launchpad-demo-seed/tasks.md b/openspec/changes/archive/2026-11-25-launchpad-demo-seed/tasks.md new file mode 100644 index 000000000..774222148 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-launchpad-demo-seed/tasks.md @@ -0,0 +1,12 @@ +# Tasks: launchpad-demo-seed + +- [x] Seed definition `data/demo-seed/zuiddrecht-boards.json` for the boards in DEMO-SEED.md +- [x] `DemoSeedService` with accounts, files and dashboards helpers; `DemoSeedWidgets` expands tiles and fallbacks +- [x] `occ launchpad:demo:load [--seed] [--password] [--retire-showcases]` +- [x] Unit tests: idempotent load, expected dashboards, tile and fallback expansion, accounts +- [x] Documentation of the demo accounts in `docs/demo-seed.md` +- [x] Re-run the seed after the new widgets (wiki, work packages, my cases, pie chart, graph) land on development + - Run 25 Nov 2026 on development 96d2d90b in the sandbox (Nextcloud 34.0.6, MariaDB, OpenRegister main, `php -S`): `occ launchpad:demo:load --retire-showcases` creates 10 users, 8 groups, 13 catalogue apps, 5 announcements and the 9 boards (102 placements); a second run adds nothing and keeps 102 placements and 10 dashboards (REQ-DEMO-010 "Running the seed twice"). Placed: `wiki-pages` (Vandaag, Project Havenpark, Team Vergunningen), `work-packages` (Vandaag, both Havenpark boards, Team Vergunningen), `assigned-cases` (Vandaag, Project Havenpark, Team Vergunningen), `pie-chart` and `graph` (Managementinformatie). + - In the browser every seeded board opens for its owner or group with no "Widget not available"; Managementinformatie draws the pie chart and the graph. `work-packages` and `assigned-cases` stay hidden because their apps (integration_openproject, dossiq) are not installed in the sandbox (`requiresApp`), and the tiles of Talk, Calendar, Mail and the case system are reported as skipped for the same reason (REQ-DEMO-011). + - `pieter` lands on Vandaag and sees Mijn werkplek, Intranet Zuiddrecht, Team Vergunningen and Managementinformatie in his list (scenario "Pieter opens LaunchPad"). +- [x] First visit: with `--retire-showcases`, `nieuw` still landed on the install default "Dashboard" (the owner-less `default`-group dashboard from the `SeedDefaultDashboard` repair step), not on "U heeft nog geen dashboard" (scenario "A first visit"). Decided by Ruben 25 Nov 2026: the seed hides the default board for `nieuw` only, nothing is deleted. Built: the user preference `hidden_dashboard_uuids` (`DashboardService::HIDDEN_DASHBOARDS_PREF_KEY`) sets organisation-wide (`default`-source) dashboards aside for one user in `getVisibleToUser`, so they neither open nor list for that user; `DemoSeedFirstRun::resetToFirstRun` writes it with every `default`-group dashboard (`DemoSeedPreferences::hideDashboards`), and `clear()` drops it. Tests: `DemoSeedServiceTest::testTheFirstRunUserHasTheOrganisationDashboardSetAside`, `::testNothingIsSetAsideWithoutAnOrganisationDashboard`, `DashboardServiceSharedResolutionTest::testASetAsideOrganisationDashboardIsNotVisible`, `::testAMalformedSetAsideListHidesNothing`. diff --git a/openspec/changes/archive/2026-11-25-manifest-cached-per-user/proposal.md b/openspec/changes/archive/2026-11-25-manifest-cached-per-user/proposal.md new file mode 100644 index 000000000..42c3d4dde --- /dev/null +++ b/openspec/changes/archive/2026-11-25-manifest-cached-per-user/proposal.md @@ -0,0 +1,17 @@ +# Proposal: manifest-cached-per-user + +## Why + +Speed budget (hydra ADR-124): every main page usable within 300 ms warm. Every workspace load asked `GET /api/manifest`, which reads OpenRegister for the user's dashboard objects. On a busy instance it was the slowest request of the page (900 to 1450 ms measured on the local test instance under load) and so the last thing the page waited for. A warm reload asks the same question seconds after the last answer. + +## What changes + +- `initial-state-contract`: ADDED REQ-INIT-009. `GET /api/manifest` keeps the manifest it builds per user and app version for 60 seconds and answers from it within that time. The workspace page carries the kept manifest as the optional key `runtimeManifest`, and the page takes it instead of asking. The page never builds a manifest itself. +- A caller the action matrix refuses `manifest.index` gets no key and meets the same refusal from the API. +- A dashboard shared with the user in OpenRegister reaches their menu at most 60 seconds later. + +## Impact + +- `lib/Controller/ManifestCache.php`, `lib/Controller/ManifestFirstLoad.php` (new), `ManifestTools`, `ManifestController::index`, `PageSources`, `PageController::index`, `InitialStateBuilder::setRuntimeManifest`. +- `src/utils/loadInitialState.js` (`takeRuntimeManifest`), `src/utils/runtimeManifestRequest.js`. +- The key is optional, so the schema version stays 3. diff --git a/openspec/changes/archive/2026-11-25-manifest-cached-per-user/specs/initial-state-contract/spec.md b/openspec/changes/archive/2026-11-25-manifest-cached-per-user/specs/initial-state-contract/spec.md new file mode 100644 index 000000000..52776c405 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-manifest-cached-per-user/specs/initial-state-contract/spec.md @@ -0,0 +1,21 @@ +# Delta: initial-state-contract + +## ADDED Requirements + +### Requirement: A warm workspace load carries the kept manifest (REQ-INIT-009) + +`GET /api/manifest` SHOULD keep the manifest it builds for a user, keyed by user and installed app version, for 60 seconds, and MUST answer from the kept manifest within that time. The Workspace page SHOULD carry a kept manifest as the optional key `runtimeManifest` and MUST NOT build one itself. The key MUST be left out when the caller may not perform `manifest.index`. The page MUST take the key instead of requesting `GET /api/manifest`, and MUST request it whenever the key is missing (default `null`). + +#### Scenario: A warm reload does not ask for the manifest + +- **GIVEN** Pieter opened the workspace less than a minute ago +- **WHEN** he opens it again +- **THEN** the page carries his manifest in `runtimeManifest` +- **AND** the page does not request `/api/manifest` + +#### Scenario: A refused caller gets no kept manifest + +- **GIVEN** the action matrix refuses Pieter `manifest.index` +- **WHEN** he opens the workspace +- **THEN** the page carries no `runtimeManifest` +- **AND** the page requests `/api/manifest` and meets the same refusal diff --git a/openspec/changes/archive/2026-11-25-manifest-cached-per-user/tasks.md b/openspec/changes/archive/2026-11-25-manifest-cached-per-user/tasks.md new file mode 100644 index 000000000..3b5f25b64 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-manifest-cached-per-user/tasks.md @@ -0,0 +1,7 @@ +# Tasks: manifest-cached-per-user + +- [x] 1. `GET /api/manifest` keeps the manifest it builds per user and app version for 60 seconds and answers from it +- [x] 2. The workspace page carries the kept manifest as `runtimeManifest` when the caller may perform `manifest.index`; it never builds one +- [x] 3. The page's one manifest request answers from the carried manifest instead of asking +- [x] 4. Unit tests: the cache (kept per user, no cache, not a manifest), the page's first load (allowed, refused, no actor or user), the endpoint (answers from the kept manifest, keeps what it builds), the reader and the request +- [x] 5. Measure on a live instance: a warm workspace load asks no manifest (perf spec, before/after): measured live 25 Nov 2026 (sandbox Nextcloud 34 with Redis as distributed cache, launchpad development): a warm workspace load sent no `GET /api/manifest` (11 launchpad requests, none of them the manifest). Without a distributed cache (plain sqlite install) the manifest is still requested, as designed: nothing keeps it diff --git a/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/proposal.md b/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/proposal.md new file mode 100644 index 000000000..f75e1edbb --- /dev/null +++ b/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/proposal.md @@ -0,0 +1,17 @@ +# Proposal: org-navigation-from-initial-state + +## Why + +Speed budget (hydra ADR-124): every main page usable within 300 ms warm. On every workspace load the shell asked `GET /api/admin/org-navigation/position` and `GET /api/admin/org-navigation` before the org rail could decide whether to show. Each launchpad API call costs about 80 ms of Nextcloud bootstrap on the server for a payload of a few bytes, and every parallel call adds CPU contention to the page load. The page already runs in a request that can read both. + +## What changes + +- `initial-state-contract`: ADDED REQ-INIT-007. The workspace page carries the optional key `orgNavigation`: `{position, tree, language}` with exactly what those two endpoints answer for the caller in the default language. The org navigation store takes it once, on the shell's first load; every later load asks the API. +- The position is read by one method (`OrgNavigationSources::position`) that both the endpoint and the page use. +- A caller the action matrix refuses either action gets no `orgNavigation`, and the shell meets the same refusal from the API as before. + +## Impact + +- `lib/Controller/OrgNavigationFirstLoad.php` (new), `OrgNavigationSources::position`, `AdminOrgNavigationController::getPosition`, `PageSettingsSources`, `PageController::index`, `InitialStateBuilder::setOrgNavigation`. +- `src/utils/loadInitialState.js` (`takeOrgNavigation`), `src/stores/orgNavigation.js` (`loadFirst`), `src/views/WorkspaceApp.vue`. +- The key is optional: an older server leaves it out and the store fetches, so the schema version stays 3. diff --git a/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/specs/initial-state-contract/spec.md b/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/specs/initial-state-contract/spec.md new file mode 100644 index 000000000..ae8efd7ff --- /dev/null +++ b/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/specs/initial-state-contract/spec.md @@ -0,0 +1,21 @@ +# Delta: initial-state-contract + +## ADDED Requirements + +### Requirement: The workspace carries the org navigation (REQ-INIT-007) + +The Workspace page SHOULD carry the optional key `orgNavigation`: `{position, tree, language}`, where `position` is exactly what `GET /api/admin/org-navigation/position` answers, and `tree` and `language` are exactly what `GET /api/admin/org-navigation` answers for the caller in the default language. The position MUST be read by the same code as that endpoint. The key MUST be left out when the caller may not perform `admin-org-navigation.get-org-navigation` or `admin-org-navigation.get-position`. The org navigation store MUST take the key once, on the shell's first load, instead of requesting the two endpoints, and MUST request them whenever the key is missing (default `null`). + +#### Scenario: The workspace opens without asking for its org navigation + +- **GIVEN** Pieter may read the org navigation +- **WHEN** he opens the workspace +- **THEN** the page carries the rail position and his filtered tree in `orgNavigation` +- **AND** the shell places the rail without requesting `/api/admin/org-navigation/position` or `/api/admin/org-navigation` + +#### Scenario: A refused caller gets no org navigation + +- **GIVEN** the action matrix refuses Pieter `admin-org-navigation.get-position` +- **WHEN** he opens the workspace +- **THEN** the page carries no `orgNavigation` +- **AND** the shell requests the endpoints and meets the same refusal diff --git a/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/tasks.md b/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/tasks.md new file mode 100644 index 000000000..2bebd8553 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/tasks.md @@ -0,0 +1,7 @@ +# Tasks: org-navigation-from-initial-state + +- [x] 1. One reader for the rail position, used by `GET /api/admin/org-navigation/position` and the page; a first-load builder that returns `{position, tree, language}` only when the caller may perform both actions +- [x] 2. The workspace page carries `orgNavigation`, built by that builder +- [x] 3. The org navigation store's first load takes it from the initial state instead of fetching; without it, it fetches both +- [x] 4. Unit tests: the builder (payload, unknown position, refusal, no actor or user), the builder key, the reader (once, missing, malformed) and the store (no fetch from the key, fetch without it) +- [x] 5. Measure on a live instance: the workspace opens without the two org-navigation requests (perf spec, before/after): measured live 25 Nov 2026 (sandbox Nextcloud 34, launchpad development): opening the workspace as admin, first and warm load, sent no org-navigation request (position or tree); the page carries `orgNavigation` diff --git a/openspec/changes/archive/2026-11-25-people-new-colleagues/proposal.md b/openspec/changes/archive/2026-11-25-people-new-colleagues/proposal.md new file mode 100644 index 000000000..4875257e1 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-people-new-colleagues/proposal.md @@ -0,0 +1,24 @@ +# Proposal: people-new-colleagues + +## Why + +Board LpIntranet draws, under the heading Collega's ("Wie nieuw is, wie jarig is en wie wat weet"), a list "Nieuwe +collega's": Yasmina El Amrani, Thomas Brouwer and Lotte Verhoeven, each with photo, role and team. The kiosk board says +"Welkom Yasmina, Thomas en Lotte", the demo seed has Yasmina "starts next Monday", and the picker describes the people +widget as "Een team of nieuwe collega's met foto" (board LpWidgetKiezen). + +The people widget selects people by hand or by filter, and shows birthdays; nothing knows when someone started. +Custom profile fields (REQ-PEX-001) are text or tags only. + +## What changes + +- `people-widget`: a custom profile field can be a date, and one date field can be marked as the start date + (REQ-PEX-005); the widget gets a selection "New colleagues" that lists people whose start date falls in a window + around today (REQ-PPL-014). +- Where the start date comes from is configuration (filled by an administrator, read from LDAP, or filled by the + person), like every custom field. + +## Impact + +- Custom profile field admin form and storage (date type, start-date marker), the users endpoint (filter and sort by + start date), the people widget form and renderer, translations. diff --git a/openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md b/openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md new file mode 100644 index 000000000..a41dfdd1f --- /dev/null +++ b/openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md @@ -0,0 +1,40 @@ +# Delta: people-widget + +## ADDED Requirements + +### Requirement: A profile field can hold a start date (REQ-PEX-005) + +A custom profile field (REQ-PEX-001) MAY have the type date. An administrator MAY mark one date field as the start +date ("in dienst sinds"). The start date SHALL follow the field's source and visibility like any custom field, and SHALL +be read through the same visibility checks (REQ-PEX-004). Marking another field as the start date SHALL unmark the +previous one. + +#### Scenario: Start date from LDAP +@e2e exclude needs an LDAP directory server and the user_ldap app, which the CI fixture does not provide; pinned by tests/Unit/Service/ProfileFieldServiceAccessGoldenTest.php::testAnLdapStartDateIsReadAsACalendarDate (generalized time and ISO dates read as 2026-10-12, an unreadable value read as none) and ::testOneDateFieldIsTheStartDate + +- **GIVEN** the administrator adds a date field "In dienst sinds", source LDAP attribute `employeeStartDate`, marked as the start date +- **WHEN** Yasmina's LDAP entry holds 12 October 2026 +- **THEN** her start date is 12 October 2026 + +### Requirement: The people widget can list new colleagues (REQ-PPL-014) + +The people widget SHALL offer `selectionMode: 'new'` ("New colleagues", nl "Nieuwe collega's"). It SHALL list the +people whose start date lies between `newSinceDays` days ago (default 30, range 1 to 90) and `newUntilDays` days ahead +(default 14, range 0 to 30), newest start first, with photo, name, role and team, within the widget's other filters +(groups, disabled accounts). A person who has not started yet SHALL be marked with the day they start ("begint +maandag"). Only people whose start date the viewer may see SHALL be listed. When no field is marked as the start date, +the form SHALL not offer the mode and a placement that uses it SHALL say that the administrator has not set a start +date field. + +#### Scenario: Three new colleagues on the intranet + +- **GIVEN** Thomas started on 28 September, Lotte on 1 October and Yasmina starts on 12 October +- **AND** today is 5 October 2026 and the widget uses `selectionMode: 'new'` with the defaults +- **WHEN** Pieter opens Intranet Zuiddrecht +- **THEN** "Nieuwe collega's" lists Yasmina with "begint maandag", then Lotte, then Thomas, each with role and team + +#### Scenario: No start date field + +- **GIVEN** no profile field is marked as the start date +- **WHEN** an author opens the people widget form +- **THEN** the selection offers no "New colleagues" diff --git a/openspec/changes/archive/2026-11-25-people-new-colleagues/tasks.md b/openspec/changes/archive/2026-11-25-people-new-colleagues/tasks.md new file mode 100644 index 000000000..30f7683bc --- /dev/null +++ b/openspec/changes/archive/2026-11-25-people-new-colleagues/tasks.md @@ -0,0 +1,10 @@ +# Tasks: people-new-colleagues + +- [x] Custom profile fields: type `date` and a single `isStartDate` marker in the admin form and storage +- [x] (as `GET /api/people/new?since=&until=`) Users endpoint: `selection=new&since=&until=` filtering and sorting by the start date, through the visibility checks of REQ-PEX-004 +- [x] People widget form: "New colleagues" with the two windows, offered only when a start date field exists — built in nextcloud-vue#2349 (CnPeopleWidgetForm Selection, asks `cnPeopleSource.hasStartDateField()`); LaunchPad provides `hasStartDateField` app-wide and per placement; LaunchPad requires `@conduction/nextcloud-vue` ^2.223.1, the release carrying #2349 +- [x] People widget renderer: the list with role and team, "begint {weekday}" for a future start, the no-field message — built in nextcloud-vue#2349 (CnPeopleWidget `fetchNewPeople`); `GET /api/people/new` now carries avatarUrl, role and organisation and the adapter `fetchNewPeople` reads it; LaunchPad's source drives it (peopleNewColleaguesWidget.spec.js), and both seeded "Nieuwe collega's" placements use `selectionMode: 'new'` +- [x] Demo seed: a start date field and start dates for the new colleagues (`startDates` in zuiddrecht-boards.json, Lotte added; `DemoSeedContent::seedStartDates`) +- [x] Translations in every shipped locale — the new strings are nextcloud-vue's (en and nl in #2349, the other 35 locales in nextcloud-vue#2354); LaunchPad adds none and requires `@conduction/nextcloud-vue` ^2.225.0 (peopleNewColleaguesWidget.spec.js checks every LaunchPad locale against the installed catalogue) +- [x] Unit tests: date field type, one start-date marker; window bounds and order; hidden start dates left out; form without a start field (NewColleaguesTest, DemoSeedStartDatesTest, widgetDataAdapters.spec.js; the form in nextcloud-vue CnPeopleWidgetNewColleagues.spec.js) +- [x] Playwright: an intranet dashboard with a New colleagues widget lists a colleague who starts next week — written (`tests/e2e/people-widget-new-colleagues.spec.ts`), runs in nightly diff --git a/openspec/changes/archive/2026-11-25-personal-settings-dialog/proposal.md b/openspec/changes/archive/2026-11-25-personal-settings-dialog/proposal.md new file mode 100644 index 000000000..af7cf7bc6 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-personal-settings-dialog/proposal.md @@ -0,0 +1,33 @@ +# Proposal: personal-settings-dialog + +## Why + +Board LpPersoonlijk draws launchpad's own settings dialog, opened from Meer, Instellingen, Persoonlijke instellingen. +Its sections, in order: Samenvatting per e-mail, Gebruikscijfers, Verborgen widgets, Mijn profiel and Inloggegevens. + +On development the dialog is `CnAppRoot`'s user settings dialog with Mijn profiel (people-widget REQ-PEX-002), +Gebruikscijfers (dashboard-view-analytics REQ-ANLT-UI-001) and the library's credentials, notifications, walkthrough +and integrations sections. No requirement says what the dialog holds, and two of the board's sections do not exist: + +- **Samenvatting per e-mail**: "Een mail met nieuwe aankondigingen en wat er op je dashboards veranderde", with "Hoe + vaak?": Uit, Dagelijks ("Om 07:30, alleen als er iets veranderde") or Wekelijks ("Op maandag om 07:30"). +- **Verborgen widgets**: "Je hebt 2 widgets verborgen op gedeelde dashboards", each with its dashboard and "Weer + tonen", and "Alles weer tonen". Today hidden widgets can only be shown again per dashboard (dashboards-and-who-may-see-them REQ-DWMS-002, + "Hidden (n)"). + +## What changes + +- New capability `personal-settings`: the dialog and its sections in the board's order (REQ-PSET-001), the summary + email (REQ-PSET-002), and the overview of hidden widgets across dashboards (REQ-PSET-003). +- No page under `/settings/user`: every per-person setting stays in this dialog. + +## Decisions + +- The summary email is launchpad's own, sent by a background job, so it can say what changed on the person's + dashboards. Nextcloud's activity email (activity-feed-integration REQ-DIGE-001) stays as it is. +- The summary is off until the person turns it on. + +## Impact + +- `src/App.vue` (section order), two new section components under `src/views/settings/`, a background job and mail + template for the summary, an endpoint pair for the hidden-widget overview over the personal layer of REQ-DWMS-001. diff --git a/openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md b/openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md new file mode 100644 index 000000000..031dc894b --- /dev/null +++ b/openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md @@ -0,0 +1,83 @@ +--- +capability: personal-settings +status: draft +--- + +# Personal settings + +## Purpose + +Launchpad's own settings dialog: everything a person sets for themselves, in one place, without a page under +`/settings/user`. + +## ADDED Requirements + +### Requirement: One dialog holds every personal setting (REQ-PSET-001) + +"Persoonlijke instellingen" in the Instellingen group of Meer (runtime-shell REQ-SHELL-013) SHALL open launchpad's +settings dialog over the current page. The dialog SHALL list its sections in a side list, in the order of board +LpPersoonlijk: Samenvatting per e-mail, Gebruikscijfers, Verborgen widgets, Mijn profiel, Inloggegevens; sections the +library adds (notifications, walkthrough, integrations) SHALL follow. A section whose feature is off SHALL be left +out: Gebruikscijfers when an administrator turned analytics off, Mijn profiel when no profile field is filled by the +person. Changes SHALL be saved at once ("Wijzigingen worden meteen bewaard"). Launchpad SHALL NOT register a section +in Nextcloud's personal settings. + +#### Scenario: Pieter opens his settings + +- **GIVEN** Pieter on the dashboard Intranet Zuiddrecht +- **WHEN** he opens Meer, unfolds Instellingen and chooses Persoonlijke instellingen +- **THEN** the dialog opens over the dashboard with the sections Samenvatting per e-mail, Gebruikscijfers, Verborgen widgets, Mijn profiel and Inloggegevens, in that order + +#### Scenario: Analytics off for everyone + +- **GIVEN** the administrator turned analytics off +- **WHEN** Pieter opens his settings +- **THEN** the dialog has no Gebruikscijfers section + +### Requirement: A person chooses a summary email (REQ-PSET-002) + +The section Samenvatting per e-mail SHALL explain "A mail with new announcements and what changed on your +dashboards" and offer "How often?": Off, Daily ("At 07:30, only when something changed") or Weekly ("On Monday at +07:30"). The choice SHALL be stored per person and SHALL be Off until the person changes it. + +A background job SHALL send the summary at 07:30 in the person's time zone, daily or on Monday, to the person's email +address. It SHALL list the announcements published for the person since the last summary, and per dashboard the +person can open, what changed since then (the "What changed" notes of dashboard-versioning). A daily summary with +nothing in it SHALL NOT be sent. A person without an email address SHALL get no summary and the section SHALL say so. + +#### Scenario: Pieter asks for a daily summary + +- **GIVEN** Pieter set Samenvatting per e-mail to Daily +- **AND** yesterday an announcement was published for his group and the dashboard Team Vergunningen gained a widget +- **WHEN** it is 07:30 in his time zone +- **THEN** he gets one email naming the announcement and "Team Vergunningen: Widget Teamagenda added" + +#### Scenario: Nothing changed + +- **GIVEN** Pieter set Daily and nothing was published or changed since his last summary +- **WHEN** it is 07:30 +- **THEN** no email is sent + +#### Scenario: The default + +- **GIVEN** Sanne never opened her settings +- **THEN** she gets no summary email + +### Requirement: A person sees every widget they hid, on every dashboard (REQ-PSET-003) + +The section Verborgen widgets SHALL say how many widgets the person hid on shared dashboards ("You have hidden 2 +widgets on shared dashboards") and list each one with its title, its dashboard and "Show again". "Show all again" +SHALL show every hidden widget again. Both SHALL act on the person's own layer (dashboards-and-who-may-see-them REQ-DWMS-001) and SHALL +NOT change the shared dashboard for anyone else. With nothing hidden the section SHALL say so and offer no button. + +#### Scenario: Pieter shows Verjaardagen again + +- **GIVEN** Pieter hid Verjaardagen and Kantinemenu on Intranet Zuiddrecht +- **WHEN** he opens Verborgen widgets and chooses Show again next to Verjaardagen +- **THEN** Verjaardagen is back on his view of Intranet Zuiddrecht, and the section lists only Kantinemenu + +#### Scenario: Show all again + +- **GIVEN** Pieter hid two widgets on two dashboards +- **WHEN** he chooses Show all again +- **THEN** both widgets are back on his views, and the section says nothing is hidden diff --git a/openspec/changes/archive/2026-11-25-personal-settings-dialog/tasks.md b/openspec/changes/archive/2026-11-25-personal-settings-dialog/tasks.md new file mode 100644 index 000000000..83bc1eb87 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-personal-settings-dialog/tasks.md @@ -0,0 +1,13 @@ +# Tasks: personal-settings-dialog + +- [x] `src/App.vue`: section order of LpPersoonlijk (summary, analytics, hidden widgets, profile, credentials, then the library's sections); leave out a section whose feature is off + (The app's sections in board order, asserted in `settingsSectionOrder.spec.js`. Gebruikscijfers leaves itself out while analytics is off; Mijn profiel leaves itself out while no profile field is defined, since hiding it while the person has filled none would leave the fields unreachable.) +- [x] `src/views/settings/DigestSettings.vue`: Off, Daily, Weekly; stored per person through the preferences API; no-email notice + (Stored in the person's user preferences through `GET/PUT /api/summary-mail/me`, which validates the three values and says whether the person has an email address; the generic `/api/preferences/{key}` accepts any string and cannot.) +- [x] `lib/BackgroundJob/SummaryMailJob.php` (hourly `TimedJob`): sends at 07:30 in each opted-in person's time zone, daily or on Monday; collects announcements published for the person and the version notes of dashboards they can open since the last summary; skips an empty daily summary; records the last send +- [x] Mail template through `IMailer` and `IEMailTemplate`, translated +- [x] `src/views/settings/HiddenWidgetsSettings.vue` and `GET /api/personal-layer/hidden`, `DELETE /api/personal-layer/hidden/{placementId}` and `DELETE /api/personal-layer/hidden` over the personal layer of REQ-DWMS-001, for the caller only +- [x] Translations in every shipped locale + (All 36 non-English locales carry the 21 dialog and summary-mail strings in .json and .js, the plural with one form per plural of the locale; `src/__tests__/personalSettingsLocales.spec.js`.) +- [x] Unit tests: section order and omission; preference stored; job timing per time zone, Monday for weekly, empty daily skipped, no email address; hidden list, show one, show all, never another person's layer +- [x] Playwright: open Persoonlijke instellingen from Meer, set Daily, hide a widget on a shared dashboard and show it again from the dialog (`tests/e2e/personal-settings-dialog.spec.ts` 1/1 green on a sandbox Nextcloud 34.0.6 + MariaDB, 25 Nov 2026; the spec now waits for the choices to load and clicks the visible label of Daily, since the test id sits on the switch's visually hidden input) diff --git a/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/proposal.md b/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/proposal.md new file mode 100644 index 000000000..f6920d92a --- /dev/null +++ b/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/proposal.md @@ -0,0 +1,26 @@ +# Proposal: sharing-policy-board-sync + +## Why + +Board LpBeheerDelen draws "Wie mag delen, en met wie" with three choices for "Delen toegestaan voor": Iedereen, Alleen +deze groepen, Niemand; "Delen met": Iedereen in de organisatie or Alleen eigen groepen; and a switch "Openbare links +toestaan" with the note "Alleen voor wie dashboards mag delen. Een link heeft altijd een vervaldatum." + +Board LpBeheerOnderhoud draws, under Opruimen: "Dashboards van vertrokken medewerkers gaan naar: Hun leidinggevende, +anders Femke de Wit". + +REQ-SHARE-014 covers the groups and the recipients, but not "Niemand", and nothing limits public links or requires an +expiry date. REQ-SHARE-012 hands a leaver's dashboard to the earliest person with full rights on it, or deletes it; +the administrator cannot send it to the leaver's manager. + +## What changes + +- `dashboard-sharing`: "Nobody" as a sharing choice, and an administrator switch for public links that only people who + may share can use, always with an expiry date (REQ-SHARE-015). +- `dashboard-sharing`: an administrator sets where a leaver's dashboards go: their manager, else a named person + (REQ-SHARE-016). Without that setting REQ-SHARE-012 applies as before. + +## Impact + +- `DashboardSharingPolicy.vue` and the sharing settings, the public share create endpoint, the user deletion listener + (it reads the manager before the account is gone), the Opruimen block of the operations tab, translations. diff --git a/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md b/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md new file mode 100644 index 000000000..2adc741d0 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md @@ -0,0 +1,64 @@ +# Delta: dashboard-sharing + +## ADDED Requirements + +### Requirement: Administrators can stop sharing and limit public links (REQ-SHARE-015) + +"Sharing allowed for" (board LpBeheerDelen) SHALL offer Everyone, Only these groups and Nobody. With Nobody no one but +an administrator SHALL be able to add a share, and the server SHALL refuse a share request from anyone else with HTTP +403; existing shares SHALL stay. + +An administrator SHALL be able to switch public links on or off ("Allow public links"). With public links off, no +public link (dashboard-public-share) SHALL be created and the Sharing tab SHALL not offer one; existing links SHALL +keep working until they expire or are revoked. With public links on, only people who may share SHALL create one, and +every new public link SHALL have an expiry date: the create form SHALL require it and the server SHALL refuse a link +without one with HTTP 400. + +#### Scenario: Nobody may share + +- **GIVEN** Noor set Sharing allowed for to Nobody +- **WHEN** Pieter opens the Sharing tab of his dashboard +- **THEN** he cannot add people or groups +- **AND** a share request he sends to the API is refused with HTTP 403 + +#### Scenario: A public link needs an expiry date + +- **GIVEN** public links are allowed and Pieter may share +- **WHEN** he creates a public link without an expiry date +- **THEN** the form asks for the expiry date +- **AND** a request without `expiresAt` is refused with HTTP 400 + +#### Scenario: Public links off + +- **GIVEN** Noor switched public links off +- **WHEN** Pieter opens the Sharing tab +- **THEN** the tab offers no public link +- **AND** a public link created before keeps working until it expires + +### Requirement: Administrators choose where a leaver's dashboards go (REQ-SHARE-016) + +The block Opruimen (board LpBeheerOnderhoud) SHALL let an administrator set "Dashboards of people who left go to": +their manager, otherwise a person the administrator names. When a person is deleted and this is set, every dashboard +they owned SHALL go to their manager (Nextcloud's manager field, read before the account is removed) when that manager +still has an account, else to the named person, else it SHALL follow REQ-SHARE-012. The shares on the dashboard SHALL +stay. The new owner SHALL get the `dashboard_ownership_transferred` notification of REQ-SHARE-013. When the setting is +empty, REQ-SHARE-012 SHALL apply unchanged. + +#### Scenario: Pieter leaves + +- **GIVEN** Noor set the handover to the manager, otherwise Femke de Wit +- **AND** Pieter's manager is Marieke Jansen +- **WHEN** Pieter's account is deleted +- **THEN** Pieter's dashboards belong to Marieke, with their shares, and Marieke gets a notification + +#### Scenario: No manager + +- **GIVEN** the same setting and Sanne has no manager +- **WHEN** Sanne's account is deleted +- **THEN** Sanne's dashboards belong to Femke de Wit + +#### Scenario: No setting + +- **GIVEN** no handover is set +- **WHEN** a person is deleted +- **THEN** their dashboards follow REQ-SHARE-012 diff --git a/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/tasks.md b/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/tasks.md new file mode 100644 index 000000000..a3f422bb3 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-sharing-policy-board-sync/tasks.md @@ -0,0 +1,10 @@ +# Tasks: sharing-policy-board-sync + +- [x] Sharing settings: "Nobody" beside Everyone and Only these groups (`sharing_allowed = none`); server check in the share create path returns 403 for non-admins +- [x] Admin setting `public_links_allowed` (default on); `DashboardSharingPolicy.vue` switch with the note that a link always has an expiry date +- [x] Public share create: refuse when public links are off or the caller may not share (403); refuse without `expiresAt` (400); the Sharing tab hides the public link block when off and marks the expiry date required +- [x] Admin setting `leaver_handover` (`{manager: bool, fallbackUid: string}`) and its control in the Opruimen block of the operations tab +- [x] User deletion: read the manager in a `BeforeUserDeletedEvent` listener, apply the handover for owned dashboards before REQ-SHARE-012, keep shares, notify the new owner +- [x] Translations in every shipped locale +- [x] Unit tests: nobody may share; public links off, on, expiry required; handover to manager, to fallback, unchanged without the setting +- [x] (written in tests/e2e/sharing-policy.spec.ts, runs in nightly) Playwright: with Nobody set the Sharing tab offers no add; a public link without expiry date is refused diff --git a/openspec/changes/archive/2026-11-25-store-page-board-sync/proposal.md b/openspec/changes/archive/2026-11-25-store-page-board-sync/proposal.md new file mode 100644 index 000000000..d80992c91 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-store-page-board-sync/proposal.md @@ -0,0 +1,32 @@ +# Proposal: store-page-board-sync + +## Why + +Board LpStore draws the marketplace as a page of dashboard templates: a banner for the connected register ("VNG +dashboardregister, register.vng.nl/dashboards, laatst gecontroleerd vandaag 06:00, Verbonden") with the note "Alleen +beheerders installeren voor de hele organisatie"; lenses Alles 23, Geïnstalleerd 3, Update beschikbaar 1 and +categories such as Intranet 6; a filter ("Voor: gemeenten") and a search; and cards with the title, the publisher, a +status (Geïnstalleerd, Beschikbaar, Update), a description, the version, the number of widgets, how many +organisations use it, and one action (Openen, Installeren, Bijwerken). It pages 8 at a time. + +The store page (`type: "store"` in `src/manifest.json`, rendered by `CnStorePage`) still carries the engine's generic +kind lenses (App template, Adapter, Source template, Configuration template, Agent template), which are not dashboard +kinds, and the spec (REQ-STORE-001 to 009) describes the routes and the install, not what the page shows. + +## What changes + +- `dashboard-store`: the page shows the register banner, the dashboard lenses and the cards as the board draws them + (REQ-STORE-010), and an installed template is recognised so its card offers Openen (REQ-STORE-011). + +## Not in this change + +- **Bijwerken** and **Dashboard publiceren** were open product questions. Decided on 23 November 2026 (product + decisions delegated by Ruben): Bijwerken updates the installed dashboard in place and keeps personal additions, as + shipped templates are updated (REQ-TMPL-020); Dashboard publiceren is for administrators only, to the connected + register, and is built after OpenRegister's store side (`store-over-federated-config`) lands. Both are specced in + the change store-update-and-publish. + +## Impact + +- `src/manifest.json` store page config (lenses, card fields), `StoreController` (installed marker, last check), the + card mapping of registry items, translations. diff --git a/openspec/changes/archive/2026-11-25-store-page-board-sync/specs/dashboard-store/spec.md b/openspec/changes/archive/2026-11-25-store-page-board-sync/specs/dashboard-store/spec.md new file mode 100644 index 000000000..d4147f9b4 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-store-page-board-sync/specs/dashboard-store/spec.md @@ -0,0 +1,47 @@ +# Delta: dashboard-store + +## ADDED Requirements + +### Requirement: REQ-STORE-010 The marketplace shows dashboard templates as cards + +The marketplace page (board LpStore) SHALL open with a banner for the connected register: its name, its address, when +it was last checked and its state (Connected, or the outcome of REQ-STORE-002 and 003), and the note "Only +administrators install for the whole organisation" for everyone who is not an administrator. Its lenses SHALL be All, +Installed and Update available, followed by the categories the register's items carry, each with its count; the +engine's generic kind lenses SHALL NOT show. The page SHALL offer a search and the filters the register's items carry +(for example the kind of organisation). Each card SHALL show the template's title, publisher, status (Installed, +Available or Update), description, version, number of widgets and, when the register reports it, how many +organisations use it. The page SHALL show 8 cards at a time with paging. + +#### Scenario: The VNG register is connected + +- **GIVEN** the administrator connected the register "VNG dashboardregister" with 23 templates, checked today at 06:00 +- **WHEN** Pieter opens the marketplace +- **THEN** the banner names the register, its address, "last checked today 06:00" and Connected, with the note that only administrators install +- **AND** the lenses read All 23, Installed 3, Update available 1, then the categories with their counts +- **AND** the first 8 cards show title, publisher, status, description, version, widgets and usage + +#### Scenario: No register connected + +- **GIVEN** no register is connected +- **WHEN** an administrator opens the marketplace +- **THEN** the page says no register is connected and points to the Sharing tab of the admin settings, and shows no cards + +### Requirement: REQ-STORE-011 An installed template opens instead of installing again + +LaunchPad SHALL record which register item and version an install created. The card of an item that has a dashboard +from an install on this instance SHALL show the status Installed and the action Open, which opens that dashboard; an +item whose register version is newer than the installed one SHALL show the status Update. An item without an install +SHALL show Available and, for an administrator, Install. + +#### Scenario: Intranet gemeente is installed + +- **GIVEN** the administrator installed "Intranet gemeente" 2.3.0 from the register +- **WHEN** Pieter opens the marketplace +- **THEN** its card shows Installed and Open, and Open goes to the installed dashboard + +#### Scenario: A newer version in the register + +- **GIVEN** "Managementinfo sociaal domein" 1.0.0 is installed and the register offers 1.1.0 +- **WHEN** the administrator opens the marketplace +- **THEN** its card shows the status Update and counts under Update available diff --git a/openspec/changes/archive/2026-11-25-store-page-board-sync/tasks.md b/openspec/changes/archive/2026-11-25-store-page-board-sync/tasks.md new file mode 100644 index 000000000..1d8521520 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-store-page-board-sync/tasks.md @@ -0,0 +1,9 @@ +# Tasks: store-page-board-sync + +- [x] `src/manifest.json` store page: dashboard lenses (All, Installed, Update available, categories) instead of the engine kind lenses; card fields title, publisher, status, description, version, widgets, usage; 8 per page — manifest config (`categoryLenses`, `pageSize: 8`, no `kindLenses`) and the card map (`widgets`, `usage`) built; CnStorePage renders them from nextcloud-vue#2347, released in 2.222.0, which launchpad now requires +- [x] Register banner: name, address, last checked and state from the store items response; the admin-only install note for non-admins; the not-connected state pointing to the Sharing tab — `GET /api/store/items` carries `registry {name, url}` and `checkedAt`, the register name is set on the Sharing tab, the manifest `banner` links to the Sharing tab; the banner renders from nextcloud-vue#2347 (2.222.0) +- [x] Record the register item slug and version on the dashboards an install creates; `GET /api/store/items` marks items Installed or Update and returns the installed dashboard id +- [x] Card action Open for installed items (server fills `openUrl`, which CnStorePage turns into Open) +- [x] Translations in every shipped locale +- [x] Unit tests: item to card mapping, lens counts, installed and update detection, not connected +- [x] Playwright: with the registry stub, the marketplace shows the banner, the lenses and an installed card that opens its dashboard — written (`tests/e2e/store-page-board-sync.spec.ts`), runs in nightly diff --git a/openspec/changes/archive/2026-11-25-template-rollout-choices/proposal.md b/openspec/changes/archive/2026-11-25-template-rollout-choices/proposal.md new file mode 100644 index 000000000..243ce158c --- /dev/null +++ b/openspec/changes/archive/2026-11-25-template-rollout-choices/proposal.md @@ -0,0 +1,27 @@ +# Proposal: template-rollout-choices + +## Why + +Board LpBeheerSjablonen draws the window "Wijzigingen doorvoeren naar 212 dashboards". It says what changed since the +previous version ("Sinds versie 13 kwamen de widgets Leesbevestiging en Verjaardagen erbij en verdween Oud nieuws"), +asks "Hoe bijwerken?" with three choices, and counts the people who changed their copy ("38 mensen hebben hun +dashboard aangepast. Hun eigen widgets blijven staan."): + +- Alleen nieuwe widgets toevoegen: niets verdwijnt; persoonlijke indeling blijft. +- Persoonlijke aanpassingen behouden: sjabloon wint, behalve wat iemand zelf heeft verplaatst of toegevoegd. +- Alles vervangen door het sjabloon: persoonlijke aanpassingen gaan verloren. + +The re-sync (REQ-RESYNC-001 to 005) has two strategies, `overwrite` and `merge`. There is no "add only", merge moves a +template widget back even when the person moved it, and the dry run (REQ-RESYNC-002) reports a plan but no window shows +it in these words. + +## What changes + +- `admin-templates`: an `add_only` strategy (REQ-RESYNC-006); under `merge`, a template widget the person moved stays + where they put it (REQ-RESYNC-007); the rollout window with the change summary, the three choices and the count of + changed copies (REQ-RESYNC-008). + +## Impact + +- The re-sync service and endpoint (new strategy value), the dry-run summary, the rollout modal on the templates tab, + translations. diff --git a/openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md b/openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md new file mode 100644 index 000000000..16499091b --- /dev/null +++ b/openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md @@ -0,0 +1,48 @@ +# Delta: admin-templates + +## ADDED Requirements + +### Requirement: REQ-RESYNC-006 Add-only strategy adds new template widgets and changes nothing else + +`POST /api/admin/templates/{id}/resync` SHALL accept `strategy: "add_only"`. Under it, each copy SHALL gain the +template placements it does not have yet, at the first free spot, and nothing else SHALL change: no placement is moved, +resized, updated or removed, also when the template removed it. Compulsory widgets SHALL still be reconciled as +REQ-RESYNC-004 says. The dry run SHALL report the same plan without writing. + +#### Scenario: Two new widgets reach every copy + +- **GIVEN** 212 copies of template "Intranet medewerkers" at version 13 +- **AND** version 14 added Leesbevestiging and Verjaardagen and removed Oud nieuws +- **WHEN** the admin re-syncs with `{"strategy": "add_only"}` +- **THEN** every copy gains Leesbevestiging and Verjaardagen +- **AND** Oud nieuws stays on every copy that had it, and no other placement moves + +### Requirement: REQ-RESYNC-007 Merge leaves a widget where the person put it + +Under `strategy: "merge"`, a template placement that the copy's owner moved or resized after provisioning SHALL keep +the owner's position and size; the template's other changes to it (title, configuration) SHALL still apply. A +placement the owner did not touch SHALL follow the template as REQ-RESYNC-003 says. + +#### Scenario: Alice moved the news widget + +- **GIVEN** alice moved the template's "Nieuws" widget to the top of her copy +- **AND** the admin changed the template's "Nieuws" feed and moved it down +- **WHEN** the admin re-syncs with `{"strategy": "merge"}` +- **THEN** alice's "Nieuws" stays at the top and reads the new feed + +### Requirement: REQ-RESYNC-008 The rollout window says what will happen + +"Push changes" on a template (board LpBeheerSjablonen) SHALL open a window that names the template, its version and the +number of copies, and SHALL state from a dry run which widgets the template gained and lost since the copies were last +synced. It SHALL offer "How to update?" with three choices, each with its consequence: Only add new widgets (nothing +disappears; personal layout stays; `add_only`), Keep personal changes (the template wins, except what someone moved or +added themselves; `merge`), Replace everything with the template (personal changes are lost; `overwrite`). It SHALL say +how many people changed their copy, and SHALL name the number of dashboards on the confirm button ("Push to 212 +dashboards"). Only Keep personal changes is preselected. + +#### Scenario: The admin opens the rollout window + +- **GIVEN** template "Intranet medewerkers" version 14 with 212 copies, 38 changed by their owners +- **WHEN** the admin chooses Push changes +- **THEN** the window says the template gained Leesbevestiging and Verjaardagen and lost Oud nieuws +- **AND** it offers the three choices with Keep personal changes selected, says 38 people changed their dashboard, and the button reads "Push to 212 dashboards" diff --git a/openspec/changes/archive/2026-11-25-template-rollout-choices/tasks.md b/openspec/changes/archive/2026-11-25-template-rollout-choices/tasks.md new file mode 100644 index 000000000..ab85ffee6 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-template-rollout-choices/tasks.md @@ -0,0 +1,9 @@ +# Tasks: template-rollout-choices + +- [x] Re-sync service: `add_only` strategy (add missing template placements at the first free spot, touch nothing else, compulsory widgets still reconciled); accept it in the endpoint and the dry run +- [x] Merge: keep the owner's position and size for a template placement the owner moved or resized after provisioning; apply the template's other changes +- [x] Dry run: report widgets gained and lost and the number of copies whose owner changed them +- [x] Rollout window on the templates tab: summary, three choices with their consequences, Keep personal changes preselected, count of changed copies, button with the number of dashboards +- [x] Translations in every shipped locale +- [x] Unit tests: add_only adds and never removes or moves; merge keeps an owner's move; dry-run summary and counts +- [x] Playwright (written in tests/e2e/template-rollout-choices.spec.ts, runs in nightly): push a template change with Only add new widgets and see the new widget on a copy that kept its own layout diff --git a/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/proposal.md b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/proposal.md new file mode 100644 index 000000000..452c3d87a --- /dev/null +++ b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/proposal.md @@ -0,0 +1,17 @@ +# Proposal: widget-content-forms-board-sync + +## Why + +Board LpWidgetInstellen draws the content part of three widget forms. Every widget has the same dialog, Content and then Layout. Live data: where the value comes from (a connection the administrator made, or a web address that returns JSON) as choice cards, the connection with its last success, the path in the response, the view (Value, List, Table, Key-value), the unit, the refresh, and under Formatting the title, colour, border and a live preview. Image: upload a file or a web address, the chosen file with its size and dimensions, the required text for who does not see the image, and an optional link. Calendar: the calendars to show, an external calendar by ICS address, and 7 days or month. + +On development these widgets open nextcloud-vue's generic widget editor with their own forms (`LiveTileWidgetForm.vue`, the image and calendar forms), laid out field after field and without the preview, the choice cards or the shown connection state. No requirement describes the dialog shape. + +## What changes + +- `live-data-tile-widget`: the Live data form as the board draws it, with its preview (REQ-LIVETILE-020). +- `image-widget`: the Image content form (REQ-IMG-020). +- `calendar-widget`: the Calendar content form (REQ-CAL-020). + +## Impact + +- `src/components/Widgets/Renderers/LiveTileWidgetForm.vue`, the image and calendar widget forms, translations. diff --git a/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md new file mode 100644 index 000000000..a79aa9599 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md @@ -0,0 +1,12 @@ +# Delta: calendar-widget + +## ADDED Requirements + +### Requirement: The Calendar content form (REQ-CAL-020) + +The content part of a Calendar widget SHALL list the reader's calendars to choose from, SHALL accept an external calendar by ICS address, and SHALL offer the period 7 days or Month. + +#### Scenario: Add an external calendar + +- **WHEN** the editor adds an ICS address and chooses 7 days +- **THEN** the widget shows that calendar's events of the next seven days with the chosen Nextcloud calendars diff --git a/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md new file mode 100644 index 000000000..0a9fadc19 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md @@ -0,0 +1,12 @@ +# Delta: image-widget + +## ADDED Requirements + +### Requirement: The Image content form (REQ-IMG-020) + +The content part of an Image widget SHALL ask "Where does the image come from?" with Upload file (from Files or the computer, up to 5 MB) or Web address, SHALL show a chosen file with its name, size and dimensions and a way to choose another, SHALL require a text for who does not see the image, and SHALL offer an optional link on click. + +#### Scenario: Alternative text is required + +- **WHEN** the editor saves an image without alternative text +- **THEN** the form refuses and names the field diff --git a/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md new file mode 100644 index 000000000..0c6650013 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md @@ -0,0 +1,13 @@ +# Delta: live-data-tile-widget + +## ADDED Requirements + +### Requirement: The Live data form as LpWidgetInstellen draws it (REQ-LIVETILE-020) + +The content part of a Live data widget SHALL ask "Where does the value come from?" with two choice cards, Connection (a system the administrator has connected) and Web address (an address that returns JSON). With Connection it SHALL show the chosen connection and when it last succeeded. It SHALL then ask the path in the response, the view (Value, List, Table, Key-value), an optional unit and the refresh interval, and under Formatting the title, colour, border and whether the title shows, with a preview that follows the fields. + +#### Scenario: KCC waiting time + +- **GIVEN** the connection Contact centre queue last succeeded at 10:38 +- **WHEN** the editor chooses it, path `wait.minutes`, view Value, unit minutes +- **THEN** the preview shows the current value with "minutes" and "Refreshes every 5 minutes" diff --git a/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/tasks.md b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/tasks.md new file mode 100644 index 000000000..5fdccec06 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/tasks.md @@ -0,0 +1,8 @@ +# Tasks: widget-content-forms-board-sync + +- [x] Live data form: source as choice cards, connection with last success, path, view, unit, refresh, formatting with live preview +- [x] Image form: upload or web address, chosen file with size and dimensions, required alternative text, optional link +- [x] Calendar form: calendars, external ICS address, 7 days or month +- [x] Translations in every shipped locale +- [x] Unit tests per form: required fields, preview follows the fields +- [x] Playwright: configure the KCC waiting time live tile (`tests/e2e/widget-content-forms.spec.ts` 3/3 green on a sandbox Nextcloud 34.0.6 + MariaDB, 25 Nov 2026; the spec picks the connection through `.vs__dropdown-option`, since NcSelect renders its list outside the modal, and names the Title textbox exactly, since "Show title" also matched) diff --git a/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/proposal.md b/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/proposal.md new file mode 100644 index 000000000..99fd0db88 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/proposal.md @@ -0,0 +1,21 @@ +# Proposal: widgets-below-the-fold-load-on-view + +## Why + +Speed budget (hydra ADR-124): every main page usable within 300 ms warm. The launchpad start page takes 2.7-4.0 s on first +paint because every widget on the dashboard mounts and asks its source at once, also the ones the reader has to scroll +to: the case list (1.7 s), the wiki search (0.6 s), work packages (0.5 s), people (0.4 s) and activity (0.4 s) all +compete with the widgets on screen (PERF-HANDOFF, demo film). Requests made in parallel slow each other down on the +server, so the lever is fewer requests at first paint. + +## What changes + +- `widgets`: ADDED REQ-WDG-044. A widget's content mounts when its card comes within reach of the viewport (one screen + height ahead), and in any case once the page has settled, so every widget has loaded before a reader downloads or + prints the dashboard. Edit mode, the headless export render and a browser without IntersectionObserver mount every + widget at once, as before. A mounted widget stays mounted. + +## Impact + +- `src/components/LazyMount.vue` (new) around the renderer in `src/components/WidgetWrapper.vue`. +- No API, no server code, no stored data. diff --git a/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md b/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md new file mode 100644 index 000000000..39b5d54f5 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md @@ -0,0 +1,30 @@ +# Delta: widgets + +## ADDED Requirements + +### Requirement: A widget below the fold loads when it comes into view (REQ-WDG-044) + +On a dashboard in view mode, a widget's content SHALL mount, and so ask its source, only when its card comes within one +viewport height of the visible area, or once the page has settled (2.5 seconds after the card appeared, at the browser's next +idle moment), or when the page is about to print, whichever comes first. Its card (frame, title, place in the grid) SHALL +show from the start. A widget whose content has mounted SHALL stay mounted. In edit mode, in the headless export render +(`?export=1`) and in a browser without IntersectionObserver every widget's content SHALL mount at once. + +#### Scenario: The case list below the fold waits for the reader + +- **GIVEN** Pieter's start page has the case list widget below the fold +- **WHEN** he opens the start page +- **THEN** the widgets on screen ask their sources and the case list does not yet +- **AND** when he scrolls towards the case list it asks its source and shows the cases + +#### Scenario: Everything has loaded before a download + +- **GIVEN** Pieter opened his start page and did not scroll +- **WHEN** the page has settled, or he chooses Download +- **THEN** every widget has mounted, so the printed dashboard shows every widget's content + +#### Scenario: Edit mode shows every widget at once + +- **GIVEN** Pieter edits his start page +- **WHEN** the dashboard shows in edit mode +- **THEN** every widget's content mounts at once diff --git a/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/tasks.md b/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/tasks.md new file mode 100644 index 000000000..97e8f0135 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/tasks.md @@ -0,0 +1,6 @@ +# Tasks: widgets-below-the-fold-load-on-view + +- [x] 1. `LazyMount`: mount the slot when the element comes within one viewport height, once settled (2.5 s, then idle), on beforeprint, or at once when eager or without IntersectionObserver; stay mounted +- [x] 2. The widget wrapper mounts the renderer through it; eager in edit mode and in the `?export=1` render +- [x] 3. Unit tests: eager, no IntersectionObserver, intersect, idle fallback, beforeprint, stays mounted, wrapper eager in edit mode +- [x] 4. (e2e written in tests/e2e/widgets-below-the-fold.spec.ts, runs in nightly) Measure on a live instance: the start page's first paint asks only the widgets on screen (perf spec, before/after): measured live 25 Nov 2026 (sandbox Nextcloud 34, launchpad development): a dashboard with a files widget on screen and a copy at y = 4971 px sent one contents request in the first 1.5 s, the on-screen one's, and mounted no CnFilesWidget for the copy; `widgets-below-the-fold.spec.ts` green live (3/3) diff --git a/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/proposal.md b/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/proposal.md new file mode 100644 index 000000000..ed414f7be --- /dev/null +++ b/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/proposal.md @@ -0,0 +1,15 @@ +# Proposal: workspace-boot-reads-from-initial-state + +## Why + +Speed budget (hydra ADR-124): every main page usable within 300 ms warm. While the workspace view boots it asks `GET /api/tiles`, `GET /api/acknowledgements/pending` and `GET /api/dashboards/default`. Each launchpad API call costs about 80 ms of Nextcloud bootstrap on the server for a payload of a few bytes, and on a shared box every parallel request takes CPU from the page that is loading. The page already runs in a request that can read all three. + +## What changes + +- `initial-state-contract`: ADDED REQ-INIT-008. The workspace page carries the optional key `workspaceBootReads`: `{tiles, pendingAcknowledgements, defaultDashboard}`, each part exactly what its endpoint answers for the caller. A part the caller may not read (`tile.index`, `dashboard.get-default-dashboard`), or that fails, is left out. Each reader takes its part once; every later read asks the API. + +## Impact + +- `lib/Controller/WorkspaceBootReads.php` (new), `PageSources`, `PageController::index`, `InitialStateBuilder::setWorkspaceBootReads`. +- `src/utils/loadInitialState.js` (`takeBootRead`), `src/stores/tiles.js` (`loadTiles`), `src/stores/dashboard.js` (`fetchPendingAcknowledgements`), `src/views/Views.vue` (`loadDefaultDashboardPreference`). +- The key and each part are optional: an older server leaves them out and the readers fetch, so the schema version stays 3. diff --git a/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/specs/initial-state-contract/spec.md b/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/specs/initial-state-contract/spec.md new file mode 100644 index 000000000..2dbf5cfb0 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/specs/initial-state-contract/spec.md @@ -0,0 +1,21 @@ +# Delta: initial-state-contract + +## ADDED Requirements + +### Requirement: The workspace carries its view's boot reads (REQ-INIT-008) + +The Workspace page SHOULD carry the optional key `workspaceBootReads`: `{tiles, pendingAcknowledgements, defaultDashboard}`, where `tiles` is exactly what `GET /api/tiles` answers for the caller, `pendingAcknowledgements` exactly what `GET /api/acknowledgements/pending` answers, and `defaultDashboard` exactly what `GET /api/dashboards/default` answers. A part MUST be left out when the caller may not perform its action (`tile.index`, `dashboard.get-default-dashboard`) or when reading it fails. The tile store, the pending-acknowledgements read and the default-dashboard read MUST each take their part once, on the first read, instead of requesting the endpoint, and MUST request it on every later read and whenever the part is missing. + +#### Scenario: The workspace opens without asking for its tiles, acknowledgements and default dashboard + +- **GIVEN** Pieter may read his tiles and his default dashboard +- **WHEN** he opens the workspace +- **THEN** the page carries his tiles, his pending acknowledgements and his default dashboard in `workspaceBootReads` +- **AND** the view shows them without requesting `/api/tiles`, `/api/acknowledgements/pending` or `/api/dashboards/default` + +#### Scenario: A refused part is asked for + +- **GIVEN** the action matrix refuses Pieter `tile.index` +- **WHEN** he opens the workspace +- **THEN** the page carries no `tiles` part +- **AND** the tile store requests `/api/tiles` and meets the same refusal diff --git a/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/tasks.md b/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/tasks.md new file mode 100644 index 000000000..7d75f8c6d --- /dev/null +++ b/openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/tasks.md @@ -0,0 +1,7 @@ +# Tasks: workspace-boot-reads-from-initial-state + +- [x] 1. A builder for `{tiles, pendingAcknowledgements, defaultDashboard}` with the payloads of the three endpoints, leaving out a part the action matrix refuses or that fails +- [x] 2. The workspace page carries `workspaceBootReads`, built by that builder +- [x] 3. The tile store, the pending-acknowledgements read and the default-dashboard read take their part once; without it they fetch +- [x] 4. Unit tests: the builder (all parts, refused part, failing part, nothing left), the builder key, the reader (once per part, missing) and the three readers (no fetch from the part, fetch without it) +- [x] 5. Measure on a live instance: the workspace opens without the three requests (perf spec, before/after): measured live 25 Nov 2026 (sandbox Nextcloud 34, launchpad development): opening the workspace as admin, first and warm load, sent no tiles, pending-acknowledgements or default-dashboard request; the page carries `workspaceBootReads` diff --git a/openspec/changes/bbv-programma-templates/proposal.md b/openspec/changes/bbv-programma-templates/proposal.md deleted file mode 100644 index 08987c912..000000000 --- a/openspec/changes/bbv-programma-templates/proposal.md +++ /dev/null @@ -1,81 +0,0 @@ -# BBV Programma Templates - -## Why - -Every gemeente in Nederland is wettelijk verplicht een programmabegroting op te stellen die de gemeentelijke taken indeelt in programma's (sociaal domein, ruimte, bestuur, openbare orde, ...), met per programma één of meer doelen en per doel meetbare indicatoren. Vandaag bouwt elke gemeente die structuur opnieuw op in Excel of lokaal BI-tool, afwijkend van buurgementen, waardoor benchmarking lastig is en provinciale toezichthouders aanleving lastig kunnen vergelijken. - -De BBV-taxonomie is echter sterk gestandaardiseerd: het Ministerie van BZK publiceert verplichte beleidsindicatoren, IV3-rubrieken (Informatie voor Derden) zijn vastgesteld, en meeste gemeenten hanteren vergelijkbare programma-indeling op hoofdlijnen. Deze spec introduceert een eerste-klasse Programma / Doel / Indicator / Maatregel datamodel in OpenRegister, seed-templates voor gangbare programma-indelingen (G4, M50, kleine gemeenten, provincies, waterschappen), één-klik installatie zodat een gemeente een template kiest en alle programma's, doelen en standaard-indicatoren in één keer aanmaakt, en koppelingen naar financeq (begrotings- en realisatie-cijfers per programma) en planix (planning van maatregelen onder een doel). - -## What Changes - -- New OpenRegister schemas: `Programma`, `Doel`, `Indicator`, `IndicatorMeting`, `Maatregel`, `IV3Mapping`, `ProgrammaTemplate`, `TemplateProgramma`, `TemplateDoel`, `TemplateIndicator`. -- New backend services: `ProgrammaService` (CRUD + template installatie), `TemplateService` (template upgrade logic), `IV3ExportService` (export voor provinciale toezichthouder). -- New frontend views: programma-tree (visualisatie van Programma → Doel → Indicator → Maatregel hiërarchie), template-picker (één-klik installatie), template-upgrade-wizard. -- Integration: openconnector (sync IndicatorMetingen van waarstaatjegemeente / CBS), financeq (begroting ↔ realisatie per programma), planix (Maatregel → project link). -- Seed data: templates voor G4, M50, kleine gemeenten, provincies, waterschappen (centraal beheerd in openregister). - -## Capabilities - -### New Capabilities - -- `programma-tree` — Programma / Doel / Indicator / Maatregel CRUD en hiërarchie-beheer. -- `programma-templates` — One-click template installatie + versie-upgrade. -- `iv3-mapping-export` — IV3-export voor provinciale toezichthouders. -- `indicator-syncing` — Geautomatiseerde sync van IndicatorMetingen van externe bronnen via openconnector. -- `maatregel-planning` — Maatregel ↔ planix project linking. -- `programma-begroting` — Begroting ↔ realisatie synchronisatie met financeq. - -### Modified Capabilities - -(none — all entirely new) - -## Impact - -**Affected integrations:** - -- `openregister` — opslag van Programma, Doel, Indicator, Maatregel, IV3Mapping, templates, seed data. -- `financeq` — query van begroting / realisatie per IV3-taakveld; verdeling over programma's via IV3Mapping. -- `planix` — project creatie + status synchronisatie gelinkt aan Maatregel. -- `openconnector` — sync van IndicatorMetingen van waarstaatjegemeente.nl, CBS API, eigen meetbronnen. - -**Dependencies:** - -- OpenRegister (already required by launchpad) -- IGroupManager, IUserManager (from Nextcloud core) -- No new composer/npm dependencies - -**Migration:** - -- Zero-impact: seed templates are loaded via OpenRegister's ImportHandler pipeline on first install or via repair step. Existing tenants without templates see an empty programma-tree until they choose a template in the UI. - -## Standards - -- **BBV** — Besluit Begroting en Verantwoording provincies en gemeenten. -- **IV3** — Informatie voor Derden taakveldenlijst (BZK). -- **Verplichte beleidsindicatoren** — Jaarlijks bijgewerkt door BZK. -- **Waarstaatjegemeente.nl** — data-bron-specificatie. -- **CBS Open Data API** — indicator-meting bronnen. - -## Non-Goals - -- Real-time collaboration on programma edits (out of scope; single-user editing assumed). -- Mobile app support (webapp-only; can defer mobile to later change). -- Workflow approvals for programma publication (status lifecycle exists, but approval workflow deferred to future change). -- Multi-tenant template versioning (seeds are global; per-tenant template forks deferred). - -## Risks - -- **Risk:** Template installatie is niet atomair en mislukt half-weg. → **Mitigation:** Transactie wrapper om template cloning; rollback on any error. -- **Risk:** IV3-mapping is incorrect en export gaat fout naar provinciale toezichthouder. → **Mitigation:** Valideerstap in export dat som per programma 100% bedraagt. -- **Risk:** External data sources (waarstaatjegemeente, CBS) zijn offline en sync mislukt. → **Mitigation:** Graceful degradation; sync retries later; eigenaar van doel krijgt notification. - -## Deliverables - -- OpenRegister schemas (JSON, in launchpad `_register.json`) -- Backend services (PHP in `lib/Service/`) -- Frontend views (Vue in `src/views/`) -- API endpoints (PHP in `lib/Controller/`) -- Integration code (openconnector hooks, financeq API calls, planix linking) -- Seed templates (JSON objects loaded on install) -- Unit + integration tests -- Changelog + admin docs (ADR-010) diff --git a/openspec/changes/cleanup-category-boolean-getter-name/proposal.md b/openspec/changes/cleanup-category-boolean-getter-name/proposal.md deleted file mode 100644 index be09e9826..000000000 --- a/openspec/changes/cleanup-category-boolean-getter-name/proposal.md +++ /dev/null @@ -1,100 +0,0 @@ -# Rename `CleanupCategoryInterface::getSafeToPurgeAutomatically()` to `isSafeToPurgeAutomatically()` - -> **STATUS: RAISED FOR HUMAN DECISION — NOT APPROVED, NOT STARTED.** -> Spec-first by design. No code has been changed. - -## Why - -PHPMD's `rulesets/naming.xml/BooleanGetMethodName` reports 5 findings in -`lib/Service/Cleanup/`, all the same method name on the interface and its four -implementations: - -| File | Line | -| --- | --- | -| `lib/Service/Cleanup/CleanupCategoryInterface.php` | 79 | -| `lib/Service/Cleanup/ExpiredLocksCategory.php` | 84 | -| `lib/Service/Cleanup/OrphanedConditionalRulesCategory.php` | 81 | -| `lib/Service/Cleanup/OrphanedSharesCategory.php` | 88 | -| `lib/Service/Cleanup/OrphanedWidgetPlacementsCategory.php` | 80 | - -The rule's position is that a method returning `bool` should read as a predicate -(`is*`/`has*`), not as an accessor (`get*`) — `if ($c->isSafeToPurgeAutomatically())` -reads as a question, `if ($c->getSafeToPurgeAutomatically())` reads as a field -fetch. The rule is correct here: the method is a pure predicate with no backing -field, and its one production caller -(`CategoryRegistryService`, REQ-CLN-008) uses it exactly as a question: - -```php -if ($category->getSafeToPurgeAutomatically() === true) { -``` - -## Why this is a proposal and not a patch - -**The name is pinned verbatim by the canonical spec.** -`openspec/specs/orphaned-data-cleanup/spec.md` names the method twice, once in a -normative MUST and once in the interface contract: - -- line 227: *"Each category exposes its tier through - `CleanupCategoryInterface::getSafeToPurgeAutomatically()`."* -- line 314: *"GIVEN the `CleanupCategoryInterface` with methods `getName()`, - `getDisplayName()`, `getSafeToPurgeAutomatically()`, `isAvailable()`, `scan()`, - and `purge(bool $dryRun = false)`"* - -Renaming the method in code without amending the spec would make both statements -false and leave the spec describing an interface that no longer exists. As with -the `ResponseHelper` proposal, the sequencing must be spec-first, and the spec -edit is a decision for a human rather than a mechanical cleanup an agent should -make on its own initiative. - -Note the internal inconsistency the rename would also resolve: the same interface -already has `isAvailable()`, so the interface currently uses **both** conventions -for boolean-returning methods. The four implementation classes also already use -the predicate wording in their own docblocks and comments -(`Tier-A ('safeToPurgeAutomatically=true')`). - -## What Changes - -If approved, in this order: - -1. **Amend `openspec/specs/orphaned-data-cleanup/spec.md`** at lines 227 and 314 to - name `isSafeToPurgeAutomatically()`. -2. **Rename the method** on `CleanupCategoryInterface` and its four implementations. -3. **Update the one production call site** in - `lib/Service/Cleanup/CategoryRegistryService.php` (~line 133). -4. **Update any test doubles / assertions** that stub or call the old name. -5. **Remove the corresponding entries from `phpmd.baseline.xml`.** - -## Capabilities - -### New Capabilities - -(none) - -### Modified Capabilities - -- `orphaned-data-cleanup`: the interface method name changes; the tier semantics - (Tier-A = auto-purgeable, Tier-B = requires admin inspection) are **unchanged**. - -## Impact - -**Blast radius (measured):** - -- **5 declaration sites** (1 interface + 4 implementations) -- **1 production call site** (`CategoryRegistryService`) -- **5 PHPMD findings** retired -- No behaviour change whatsoever — this is a pure rename of a predicate. - -**Risk: low.** `CleanupCategoryInterface` is an internal interface, not a public -extension point published to third-party apps, so the rename does not break an -external contract. The only sharp edge is a stale test double implementing the -interface under the old name, which would fail loudly rather than silently. - -**Alternative considered and rejected:** adding an `is*` alias and deprecating the -`get*` name. That doubles the interface surface permanently to avoid a -six-call-site rename in a closed interface, and leaves the PHPMD findings in place -until the deprecated name is finally removed. Not worth it at this size. - -## Decision requested - -Approve, amend, or reject. If approved, the spec amendment lands first and the -rename follows in its own PR. diff --git a/openspec/changes/cleanup-category-boolean-getter-name/tasks.md b/openspec/changes/cleanup-category-boolean-getter-name/tasks.md deleted file mode 100644 index 447044ca7..000000000 --- a/openspec/changes/cleanup-category-boolean-getter-name/tasks.md +++ /dev/null @@ -1,28 +0,0 @@ -# Tasks — rename getSafeToPurgeAutomatically() to isSafeToPurgeAutomatically() - -> **BLOCKED: awaiting a human decision on `proposal.md`.** -> Spec-first: nothing in section 2 may start until section 1 is merged. - -## 1. Spec amendment (must land first, on its own) - -- [ ] 1.1 `openspec/specs/orphaned-data-cleanup/spec.md` line 227 — rename in the - normative statement about how a category exposes its tier. -- [ ] 1.2 Same file, line 314 — rename in the `CleanupCategoryInterface` method list. - -## 2. Implementation (only after 1 is merged) - -- [ ] 2.1 Rename on `lib/Service/Cleanup/CleanupCategoryInterface.php:79`. -- [ ] 2.2 Rename on `ExpiredLocksCategory.php:84`. -- [ ] 2.3 Rename on `OrphanedConditionalRulesCategory.php:81`. -- [ ] 2.4 Rename on `OrphanedSharesCategory.php:88`. -- [ ] 2.5 Rename on `OrphanedWidgetPlacementsCategory.php:80`. -- [ ] 2.6 Update the call site in `CategoryRegistryService.php` (~line 133). -- [ ] 2.7 Update any test double or assertion using the old name. - -## 3. Verification - -- [ ] 3.1 Full unit suite green (baseline 1525 tests / 3877 assertions / 3 skipped). -- [ ] 3.2 Re-measure PHPMD with the baseline deleted — expect 5 `BooleanGetMethodName` - findings retired and no new findings. -- [ ] 3.3 Remove the corresponding entries from `phpmd.baseline.xml`. -- [ ] 3.4 Confirm Tier-A/Tier-B classification behaviour is unchanged (REQ-CLN-008). diff --git a/openspec/changes/competitor-parity-2026-09/tasks.md b/openspec/changes/competitor-parity-2026-09/tasks.md deleted file mode 100644 index 9a9509982..000000000 --- a/openspec/changes/competitor-parity-2026-09/tasks.md +++ /dev/null @@ -1,7 +0,0 @@ -# Tasks: competitor-parity-2026-09 - -- [ ] 1.1 Build `dashboards-and-who-may-see-them` (discovery cluster 12, decisions D6 and D21). Archive it on merge and tick it here. -- [ ] 2.1 Hand dossiq its half of cluster 12: case widgets contributed to a launchpad dashboard, each declaring which roles may see it. Give the lane candidate C-reporting-22 and ledger row 10.1 with it. -- [ ] 2.2 Ask the openregister lane which aggregations a shipped report may rely on, so the report library does not query objects directly. -- [ ] 3.1 Keep the already-covered table current: C-reporting-14 on `iframe-embed-widget`, C-reporting-22 on `dashboards` and `role-feature-permissions`. -- [ ] 3.2 Add any later launchpad change that cites the gap register or the discovery sweep to the index above, in the same PR that opens it. diff --git a/openspec/changes/dashboard-switcher/tasks.md b/openspec/changes/dashboard-switcher/tasks.md deleted file mode 100644 index 2eb6ce963..000000000 --- a/openspec/changes/dashboard-switcher/tasks.md +++ /dev/null @@ -1,83 +0,0 @@ -# Tasks — dashboard-switcher - -## Component Implementation - -- [ ] Task 1: Create `src/components/DashboardSwitcher.vue` — Vue 2 Options API, scoped styles, Pinia store for sidebar state -- [ ] Task 2: Props: `isOpen` (Boolean, required), `groupName` (String, optional, default `'Dashboards'`), `groupDashboards` (Array, required), `userDashboards` (Array, required), `activeDashboardId` (String, optional), `allowUserDashboards` (Boolean, optional) -- [ ] Task 3: Emits: `update:open(boolean)`, `switch(id, source)`, `create-dashboard()`, `delete-dashboard(id)` -- [ ] Task 4: REQ-SWITCH-001 — Implement three-section rendering: primary group (source !== 'default'), default group (source === 'default'), personal (userDashboards). Each section has a label (computed via `groupName || t('Dashboards')`, `t('Default')`, `t('My Dashboards')`). Omit empty sections entirely (no empty container, no label). -- [ ] Task 5: REQ-SWITCH-001 — Render horizontal dividers between adjacent non-empty sections (exactly 2 dividers when all 3 sections present; 1 divider when 2 sections; 0 when 1 section) -- [ ] Task 6: REQ-SWITCH-002 — Dashboard row click handler: emit `update:open(false)` first, then emit `switch(id, source)`. Source is derived from section context ('group'/'default'/'user'), not from the dashboard object's internal type field. -- [ ] Task 7: REQ-SWITCH-003 — Apply CSS class `.active` to the dashboard item where `id === activeDashboardId`. Only one item may be active. Update reactively when prop changes. -- [ ] Task 8: REQ-SWITCH-003 — Style active items with `background-color: var(--color-primary-element-light)` and icon tint `color: var(--color-primary)` -- [ ] Task 9: REQ-SWITCH-004 — Personal-dashboard rows (excluding the Add-Dashboard card): render a delete button (small close icon via `NcIcon`, component: `Close`). Button hidden by default (`display: none`), visible on row hover (`display: inline-flex`) -- [ ] Task 10: REQ-SWITCH-004 — Delete button click handler: use `@click.stop` to prevent row's switch event, emit `delete-dashboard(id)`, do NOT emit `update:open(false)` -- [ ] Task 11: REQ-SWITCH-006 — Container CSS: `position: fixed`, `top: 50px`, `left: 0`, `width: 280px`, `z-index: 1500`. Initial `transform: translateX(-100%)` when `isOpen: false`. -- [ ] Task 12: REQ-SWITCH-006 — When `isOpen: true`, add CSS class `.open` which sets `transform: translateX(0)`. Transition: `transform 0.25s ease` -- [ ] Task 13: REQ-SWITCH-006 — Sidebar height: calculate to account for header offset (top: 50px) and footer. Use `calc(100vh - 50px)` with `overflow-y: auto` on the list container -- [ ] Task 14: REQ-SWITCH-007 — Import `IconRenderer` from the `dashboard-icons` capability. Each dashboard row: render the icon via `<IconRenderer :icon="dashboard.icon" />`. No branching on `isCustomIconUrl`. -- [ ] Task 15: REQ-SWITCH-008 — Render a dedicated "Add Dashboard" button card only when `allowUserDashboards === true`. Card is inside the scroll container (not the footer), positioned below the personal-dashboards list -- [ ] Task 16: REQ-SWITCH-008 — Add-Dashboard card: `NcButton` with `type="outline"`, full sidebar width, render a `+` icon (use `Plus` component from @conduction/nextcloud-vue), label from `t('launchpad', 'Add dashboard')` -- [ ] Task 17: REQ-SWITCH-008 — Add-Dashboard button click: emit `update:open(false)` first, then emit `create-dashboard()` -- [ ] Task 18: REQ-SWITCH-009 — Render a sticky footer at the bottom: `position: sticky`, `bottom: 0`, separated from the list above by a `<hr />` divider -- [ ] Task 19: REQ-SWITCH-009 — Footer: "Powered by" line with Sendent logo (link to sendent.nl) and Conduction logo (link to conduction.nl). Both links: `target="_blank"` and `rel="noopener noreferrer"`. Use static URLs or load from config if available. -- [ ] Task 20: REQ-SWITCH-009 — Footer: Documentation link rendered as an icon + label `t('launchpad', 'Documentation')`. Link target: preserved from the gear menu's Documentation URL (retrieve from app config or settings endpoint) -- [ ] Task 21: REQ-SWITCH-009 — Footer styling: `position: sticky`, light background via Nextcloud CSS var `var(--color-background-secondary)`, padding and border-top divider - -## Parent Integration - -- [ ] Task 22: Integrate `DashboardSwitcher.vue` into `src/App.vue` — import the component and register in `components: {}` -- [ ] Task 23: Wire `v-model:open` binding to the sidebar state: `:isOpen="sidebarOpen"` and `@update:open="sidebarOpen = $event"` -- [ ] Task 24: Pass dashboard data props from the component's data/store: `:groupName`, `:groupDashboards`, `:userDashboards`, `:activeDashboardId`, `:allowUserDashboards` -- [ ] Task 25: Handle `@switch` event in App.vue: call the store action to switch dashboards and navigate if needed; update `activeDashboardId` in the store -- [ ] Task 26: Handle `@create-dashboard` event in App.vue: emit or call the parent's create flow (may open a dialog, navigate to a form, etc.) -- [ ] Task 27: Handle `@delete-dashboard` event in App.vue: call the delete endpoint or store action; show a success/error toast; conditionally close the sidebar after deletion - -## Styling & CSS - -- [ ] Task 28: Create `src/styles/dashboard-switcher.css` with all component styles. Use ONLY Nextcloud CSS variables (`--color-*`). NO hardcoded colors, NO `--nldesign-*` refs. -- [ ] Task 29: Styles: section headings, dividers, dashboard rows (padding, hover state), delete button (hidden/visible), active class styling, animation, footer styling -- [ ] Task 30: Test CSS in light and dark modes (if nldesign is integrated) — colors must respect `prefers-color-scheme` - -## Translations - -- [ ] Task 31: Add English (en.json) translations: `'Dashboards'`, `'Default'`, `'My Dashboards'`, `'Add dashboard'`, `'Documentation'`, `'Powered by'` -- [ ] Task 32: Add Dutch (nl.json) translations: `'Dashboards'` → `'Dashboards'`, `'Default'` → `'Standaard'`, `'My Dashboards'` → `'Mijn dashboards'`, `'Add dashboard'` → `'Dashboard toevoegen'`, `'Documentation'` → `'Documentatie'`, `'Powered by'` → `'Mogelijk gemaakt door'` -- [ ] Task 33: Extract translation keys from the component into `xgettext` scanning (ensure `.vue` files are scanned by the build's i18n extraction) - -## Testing - -- [ ] Task 34: Playwright test — all three sections render when present; dividers appear only between non-empty sections -- [ ] Task 35: Playwright test — click a dashboard row emits `update:open(false)` then `switch(id, source)` with correct source ('group'/'default'/'user') -- [ ] Task 36: Playwright test — active item highlighted correctly; highlight updates when `activeDashboardId` prop changes -- [ ] Task 37: Playwright test — personal dashboard item hover shows delete button; delete button click emits `delete-dashboard(id)` without emitting `switch` or `update:open(false)` -- [ ] Task 38: Playwright test — sidebar animates from off-screen (`translateX(-100%)`) to on-screen (`translateX(0)`) over 250 ms when `isOpen` toggles; computed style matches after animation completes -- [ ] Task 39: Playwright test — all three dashboard icons render correctly (built-in MDI, custom URL, null) via `IconRenderer` without branching in the template -- [ ] Task 40: Playwright test — Add-Dashboard button is visible only when `allowUserDashboards: true`; clicking it emits `update:open(false)` then `create-dashboard()` -- [ ] Task 41: Playwright test — footer always visible; brand logos and Documentation link render with correct target/rel attributes; footer remains visible while scrolling 30+ dashboards -- [ ] Task 42: Playwright test — mobile viewport (320px width): sidebar's 280px width + gap is within bounds; all interactive elements remain clickable at touch size (44px+ preferred) - -## Quality & Integration - -- [ ] Task 43: ESLint + Stylelint — all `.vue` and `.css` files pass linting with zero warnings -- [ ] Task 44: Type checking — if using TypeScript, `tsc --noEmit` passes; Vue component types are inferred correctly or explicitly annotated -- [ ] Task 45: Security gate `hydra-gate-modal-isolation` — if the component opens any modal/dialog, it MUST be in its own `.vue` file under `src/modals/` or `src/dialogs/`, not inline -- [ ] Task 46: Nextcloud CSS compliance — all colors use `var(--color-*)` variables; no hardcoded `#hex` or `rgb()` colors; theme switching works (if nldesign is available, test with different token sets) -- [ ] Task 47: Accessibility (WCAG AA) — all interactive elements are keyboard-navigable (Tab/Shift+Tab); delete button has sufficient contrast and labels; section headings are semantic (`<h3>` or appropriate level); focus indicator is visible -- [ ] Task 48: Documentation — add a brief entry to the changelog mentioning the new dashboard switcher sidebar, its location, and key features (switching, create/delete personal dashboards, footer branding) - -## Verification - -`openspec validate` exits clean. Sidebar renders all three sections correctly; dashboard switching closes the sidebar and calls the switch handler; personal dashboards can be deleted; Add-Dashboard affordance is visible and works; footer stays visible while scrolling; all interactive elements are responsive and accessible. - -## Tests (company-wide ADR-009) - -Playwright end-to-end tests per Tasks 34–42. Unit tests for computed properties (section filtering, active-item detection, label localization) if complexity warrants; otherwise integration tests via Playwright. - -## Documentation (company-wide ADR-010) - -Changelog entry per Task 48. Inline component docstring (JSDoc) documenting props, emits, and main behavioral features. No separate design document needed beyond `design.md`. - -## i18n (company-wide ADR-005) - -English and Dutch per Tasks 31–33. Extraction via existing i18n build pipeline. diff --git a/openspec/changes/dashboards-and-who-may-see-them/tasks.md b/openspec/changes/dashboards-and-who-may-see-them/tasks.md deleted file mode 100644 index 7850b44d2..000000000 --- a/openspec/changes/dashboards-and-who-may-see-them/tasks.md +++ /dev/null @@ -1,134 +0,0 @@ -# Tasks: dashboards-and-who-may-see-them - -## 1. The personal layer - -- [x] 1.1 Add a personal layer record keyed by user and dashboard, holding order, size and the hidden set. -- [x] 1.2 Apply the layer over a shared dashboard at render time, and only for its owner. -- [x] 1.3 Refuse hiding a placement marked compulsory by `admin-templates`. -- [x] 1.4 Add the reset action, deleting the whole layer behind a confirmation. -- [ ] 1.5 Drop orphaned layer entries when a placement disappears after an admin template re-sync. `pruneOrphans()` is written and tested, and nothing calls it. The reason is below. -- [x] 1.6 PHPUnit on apply, on the compulsory refusal and on reset. -- [x] 1.7 PHPUnit from the READER: a saved layer changes what `DashboardService` hands back, on the landing read and on the by-id read, and reaches nobody else. - -## 2. The report library - -- [ ] 2.1 Define the report definition shape: id, title, description, aggregation, parameters, rendering, required registers and schemas. -- [ ] 2.2 Ship a first set of definitions with the app and list them in a gallery. -- [ ] 2.3 List a report whose registers or schemas are missing as unavailable, naming them. -- [ ] 2.4 Save a result as an ordinary dashboard owned by the saver. -- [ ] 2.5 PHPUnit on the availability check and on save-as-dashboard. - -## 3. The status report - -- [ ] 3.1 Add the status report object: date, health rating, summary, figures, and per value whether it was computed or written. -- [ ] 3.2 Prefill the rating and the figures from the body of work. -- [ ] 3.3 Let a person edit the summary before keeping the report. -- [ ] 3.4 PHPUnit on prefill and on the computed-versus-written record. - -## 4. Activity reporting - -- [ ] 4.1 Add the admin setting: off by default, with a purpose string that cannot be empty. -- [ ] 4.2 Show the purpose on every screen reporting on a named person. -- [ ] 4.3 Write an audit entry for every read of another person's activity. -- [ ] 4.4 Let a person read their own without the setting and without a log entry. -- [ ] 4.5 Report counts per activity type and a per day calendar of intensity, from the existing activity events. -- [ ] 4.6 Export both as CSV, with totals equal to the screen. -- [ ] 4.7 PHPUnit on the gate, the self-read exception and the audit entry. - -## 5. Colleague activity - -- [ ] 5.1 Add the widget over the existing activity feed. -- [ ] 5.2 Filter to what the reader may see, and exclude filtered entries from every count. -- [ ] 5.3 PHPUnit on the permission filter, including its effect on the totals. - -## 6. In-widget search - -- [ ] 6.1 Add a filter field to widgets that render rows, in view state only. -- [ ] 6.2 Assert it never writes to the placement or its saved search. -- [ ] 6.3 Vitest on the component: filter, reload, unchanged definition. - -## 7. Geographic reporting - -- [ ] 7.1 Add the aggregation: counts and rates per declared area property over a period. -- [ ] 7.2 Count objects with no location in an explicit bucket. -- [ ] 7.3 PHPUnit on the bucket, including the empty case. - -## 8. Storage reporting - -- [ ] 8.1 Read use per workspace and per service from the platform figures and register counts. -- [ ] 8.2 Keep a daily series and report twelve months. -- [ ] 8.3 Name the removable total: past retention, orphaned uploads. -- [ ] 8.4 Export as CSV, administrator-only, and refuse others with 403. -- [ ] 8.5 PHPUnit on the admin guard and on the removable calculation. - -## 9. Handover - -- [ ] 9.1 Give the dossiq lane the consumer half: case widgets contributed to a launchpad dashboard, each declaring the roles that may see it. -- [ ] 9.2 Agree with the openregister lane which aggregations a shipped report may rely on. -- [ ] 9.3 Tick this change in `competitor-parity-2026-09/tasks.md` when it archives. - -## What shipped, and what has not - -**Section 1 is built and covered.** `launchpad_personal_layers` holds one row -per person per dashboard: the geometry and order they changed, and the -placements they hid. `PersonalLayerService` lays it over the shared placements -inside `DashboardService::getDashboardForUser()`, on both the owned-read path -and the share path, and inside `getEffectiveDashboard()`, which is the -`GET /api/dashboard` the grid loads from. Only for a dashboard the caller does -not own: their own dashboard is left alone, because there the arrangement IS -the dashboard. - -Two things were fixed once the reader got its own tests. `getEffectiveDashboard()` -did not apply the layer at all, so a person who arranged the dashboard they land -on saw their arrangement through the layer endpoint and nowhere else. And the -layer service was a nullable constructor argument on `DashboardService`, purely -so that unit tests could leave it out. A null read exactly like a person with no -layer, so a wiring failure would have stored every layer and shown none of them -with the whole suite green. It is required now; nothing in the app ever built -that service without it. - -A compulsory placement cannot be hidden, and a save that asks to hide one -writes nothing at all rather than landing the allowed half. It can still be -moved. A placement made compulsory after somebody hid it renders again, which -is checked. The reset is `DELETE`, removes the whole row, and resetting twice -is not an error. - -`pruneOrphans()` is the exception, and task 1.5 is open again because of it. -The method drops entries for placements that no longer exist, and deletes the -row when the sweep empties it. Nothing calls it. Two tests cover it and there -is no call site in `lib/`, which is the same shape this branch just fixed for -`withPersonalLayer()`: a method with a green suite and no caller reports the -same green as one that runs. - -Wiring it is not a one-line call, which is why it is a task and not a fix -here. A re-sync replaces the placements of one dashboard for everybody, and -`pruneOrphans()` takes one user id. `PersonalLayerMapper` can find a layer by -user and dashboard and delete it, and it cannot list the layers on a -dashboard, so there is no query to sweep with. Eight places call -`deleteByDashboardId()`, and each has to decide whether it is a re-sync that -should prune or a deletion that should drop the layer outright. - -What it costs while it waits is bounded, and it is not a wrong number on -screen. `applyTo()` walks the live placements and looks up overrides by id, -so an entry for a placement that is gone is ignored at render time. Placement -ids come from an autoincrement column and are never reused, so a stale entry -cannot attach itself to a different widget later. The cost is stale keys in -the layer row, one per placement ever removed from that dashboard. - -Three routes, all `#[NoAdminRequired]`, all reading the caller's own user id -from the session. No route takes a user id from the request, so one person's -layer is unreachable through another's. - -**Sections 2 to 8 are not built.** The report library, the status report, -activity reporting and its purpose gate, colleague activity, in-widget search, -geographic reporting and storage reporting are untouched, and their boxes are -still open above. Section 6 needs Vitest, and an earlier draft of this file -said Vitest could not run here because `npm ci` refused over a -`package.json` and `package-lock.json` that were out of sync. That is not -true on this tip. The two files agree on every dependency, and -`npm run test` runs the suite: 748 tests across 69 files. So the reason -section 6 is open is the plain one. Nobody built it. - -**Section 9, the handover.** 9.1 and 9.2 are unchanged: the dossiq and -openregister halves have not been handed over, because sections 2 to 8 are what -they depend on. diff --git a/openspec/changes/drill-down-cross-widget-filter/design.md b/openspec/changes/drill-down-cross-widget-filter/design.md deleted file mode 100644 index fc75f51c4..000000000 --- a/openspec/changes/drill-down-cross-widget-filter/design.md +++ /dev/null @@ -1,154 +0,0 @@ -# Design — Drill-down Cross-widget Filter - -## Context - -LaunchPad dashboards today render each widget as an isolated island. A chart widget pulls its own data with its own filter context; clicking a bar either does nothing or drops the user into a separate list view. Every drill-down step requires reopening filter modals on three widgets, re-entering gemeentecode and wijkcode, and reconciling inevitable inconsistencies — "is this widget's 'older than 6 weeks' calculation the same as that one's?" The user mental model is simple ("show me bezwaren in Zeist, then Vollenhove, then open ones > 6 weeks") but the UI breaks it into three separate journeys through three separate modals. - -The OpenRegister API already supports multi-dimension filtering via `_filter` query parameters and uses composite indexes to serve them efficiently. The gap is in the dashboard host: no glue code detects clicks, no pub/sub layer coordinates subscribers, no URL encoding makes filtered views bookmarkable. This change adds that glue. - -## Goals / Non-Goals - -**Goals:** - -- Make filter state shared across the dashboard via a per-dashboard pub/sub bus. -- Declare widget compatibility (which dimensions a widget can publish/consume) via manifest, not runtime guesswork. -- Make filtered views bookmarkable and reproducible via URL encoding. -- Support drill-down hierarchies (gemeente → wijk → buurt) so a child-level click infers and applies ancestor filters. -- Resolve filter conflicts explicitly with audit trails, not silent overwrites. -- Allow users to save named filter combinations and apply them with one click. -- Measure which drill-down paths users exercise (opt-in telemetry, no PII). - -**Non-Goals:** - -- Rewrite the OpenRegister query layer. The bus translates to `_filter` parameters; OR's index strategy unchanged. -- Create a new visual filter builder / query-construction UI. Filtering happens via widget clicks (app-driven) or saved views (one-click apply), not ad-hoc form building. -- Support cross-register filtering (e.g., filter one dashboard that pulls from Register A AND Register B). Scope is per-dashboard, per-register. -- Implement cross-user collaboration features (e.g., "user A applied a filter, broadcast to user B's dashboard"). Each user has their own filter bus; persistence happens via bookmarkable URLs and shared saved views. -- Support stateful filter-history or "undo" beyond the browser's back button. - -## Decisions - -### D1: Pub/sub filter bus in the dashboard host, not a new query engine - -**Decision**: Implement a thin pub/sub layer in `src/composables/useFilterBus.js` that accepts `{dimension, operator, value}` clauses from widgets, applies conflict resolution, and broadcasts to subscribers. Clauses map to `_filter` query parameters on widget data fetches; no new OR query engine. - -**Alternatives considered:** - -- Push filter logic into OpenRegister. Rejected — OR is a generic query-execution service; dashboards are a higher-level application concern. Coupling filter logic to OR would either duplicate the logic in other OR clients or force those clients to live with dashboard-specific semantics. -- Use Pinia global store for filter state. Rejected — Pinia is great for component-level state, but filter state is tied to the URL and must survive page reloads. A composable that reads from/writes to the URL (via router) is the cleaner boundary. -- Implement a constraint-solver for conflict resolution (e.g., "common ancestor between two conflicting clauses, prefer the narrower scope"). Rejected — dramatically more complex, and last-write-wins with explicit audit is what collaborative tools (Tableau, Power BI, Kibana) actually do because it is predictable and undoable. - -**Rationale**: The bus is a glue layer between widgets and OR, not a new subsystem. Reusing OR's existing `_filter` parameter means no new indexes, no new query planner, and the same performance characteristics widgets already have for share-link filtering. - -### D2: Manifest declarations for dimension compatibility, not runtime detection - -**Decision**: Widget manifests include `publishes: [{dimension, operator, fromField}]` and `consumes: [{dimension, operator, intoFilter}]` arrays. The dashboard validates these at widget render time and surfaces mismatches (e.g., "this widget consumes 'wijkCode' but no hierarchy on this dashboard includes it") as non-fatal warnings. - -**Alternatives considered:** - -- Detect dimension compatibility at runtime (inspect widget data shape on first fetch). Rejected — the shape only arrives after the query runs; this delays the validation and couples the decision to the data. Manifest-based validation is immediate and testable. -- Use a TypeScript interface to encode allowed dimensions. Rejected — manifests need to be readable by dashboard operators who are not developers; JSON is more approachable than type interfaces. - -**Rationale**: Manifests are the source of truth for widget capabilities. Validation catches misconfigurations at dashboard-edit time ("you've added a widget that expects 'gemeenteCode' but your hierarchies don't mention it") and prevents silent failures at runtime. - -### D3: Declarative hierarchy model with parent-relationships - -**Decision**: Hierarchy descriptors live in the dashboard manifest and include ordered level arrays with explicit parent-relationships: `{id, levels: [{dimension, parentDimension, label}, ...]}`. When a wijk-level click arrives, the bus infers the ancestor gemeentecode and provincecode (parent-of-parent) from the CBS administrative hierarchy and applies them as `source=parentScope` clauses. - -**Alternatives considered:** - -- Hard-code the hierarchy in code (a switch statement per known hierarchy). Rejected — organisations with custom taxonomies can't use them without forking launchpad. Declarative JSON is extensible. -- Compute parent relationships at query time from the data (fetch all gemeentes for the clicked wijk, infer the gemeentecode). Rejected — adds latency and couples hierarchy to the data shape, making it brittle. -- Support arbitrary parent-relationships without inferring them (user manually clicks up the hierarchy). Rejected — the whole point of hierarchies is to make the breadcrumb and ancestor filters automatic. - -**Rationale**: CBS gemeentecodes and wijkcodes have stable, well-documented parent-relationships (wijk code WK0701001 → gemeente GM0701, which is always the first 4 digits). Declarative hierarchies make the relationships explicit, auditable, and extensible for non-standard taxonomies. - -### D4: URL encoding via base64url-compact-JSON, not parameter-per-clause - -**Decision**: Serialize the entire filter state to a single `?f=<base64url>` parameter using compact JSON keys (`d` for dimension, `o` for operator, `v` for value, `s` for source) to stay within typical 2 KB URL length limits. - -**Alternatives considered:** - -- One query parameter per clause: `?gemeenteCode=GM0355&status=open`. Rejected — dimensions with special characters or namespaced names (e.g., `period.month`, `custom.myTaxonomy`) become unreadable; query-parameter order is not guaranteed; dashboards with 10+ clauses exceed URL limits. -- Use a different encoding (gzip, base64 without url-safe alphabet). Rejected — base64url is what JWT, OAuth2 PKCE, and (for this exact purpose) Grafana use; it's a proven standard that doesn't require percent-encoding in URLs. - -**Rationale**: Grafana's `var-` parameters use the same approach and have solved the "dozens of clauses" problem. Base64url produces readable (if compact) URLs that can be copy-pasted, and compact JSON keys keep the size under typical proxy/browser limits. - -### D5: Last-write-wins conflict resolution with audit tooltips - -**Decision**: When a new clause for dimension X arrives and X already has an active clause, replace the old one silently or with a brief audit toast depending on the source transition (widget-click → widget-click: show toast; urlBootstrap → widget-click: silent, URL is transient). Show the old and new values (e.g., "Gemeente: Zeist → Houten"). - -**Alternatives considered:** - -- Merge clauses (e.g., if X is already filtered to a set, add the new value to the set). Rejected — this produces subtle wrong answers ("why is my widget showing both GM0355 and GM0344 when I only clicked one?") and is nearly impossible for users to understand or undo. -- Reject conflicting clauses with an error toast (prevent replacement). Rejected — blocks the user's navigation; they have no way to override except by clicking "Reset filters" and starting over. -- Support multi-value filters (e.g., `{op: 'in', value: [GM0355, GM0344]}`). Rejected — the UI would need a multi-select affordance for every click, which breaks the "tap-to-filter" pattern. Multi-select can be a separate "drill-up" feature later. - -**Rationale**: Collaborative tools (Tableau, Looker, Power BI) all use last-write-wins because it is predictable and debuggable — the user can see the change via the audit toast and undo by clicking elsewhere. Silent merges are the enemy of trust in analytics. - -### D6: Pinned clauses survive "Reset filters" - -**Decision**: Clauses marked `pinned: true` (set by org admins via dashboard config) are immutable. When "Reset filters" is invoked, unpinned clauses are cleared but pinned ones remain. When a new clause for a pinned dimension arrives, the publication is silently dropped with a console log (visible to developers, not users). - -**Alternatives considered:** - -- Allow users to unpin clauses individually. Rejected — pinned clauses are org-level policy ("always scope to current user's gemeente"); users should not override them. -- Show an error when a pinned clause can't be replaced. Rejected — noisy and confusing for users; a console message is sufficient for developer debugging. - -**Rationale**: Pinned clauses are the mechanism for org-scope constraints (e.g., "this dashboard always filters to the logged-in user's gemeente"). They need to survive user exploration (so the user can't accidentally scope up to provincial level) without being visible as a restriction in the UI. - -### D7: Saved views persist filter combinations in the register - -**Decision**: Signed-in users with edit permission on a dashboard can save the current filter state as a named `saved_view` row in the launchpad register with fields `{id, dashboardId, name, description, filters, isShared, sharedWith, createdBy, createdAt}`. Saved views appear in a dropdown in the dashboard header; clicking one applies its clauses. - -**Alternatives considered:** - -- Store saved views in localStorage. Rejected — not shareable between users, no access control, lost on device change. -- Use a separate "views" register. Rejected — the launchpad register is the system of record for dashboard metadata; saved views are dashboard artifacts. - -**Rationale**: Register-backed persistence makes saved views shareable ("team lead creates 'Open bezwaren > 6w' and shares with the team") and auditable (who created the view, when) without introducing a new persistence tier. - -### D8: Telemetry is opt-in, records paths not values - -**Decision**: Org-level config flag controls telemetry. When enabled, `filter_event` rows record `{id, dashboardId, userId, widgetId, eventType, filterDelta, timestamp}` with `eventType` one of `apply` / `reset` / `bookmark` / `share`. The `filterDelta` records dimensions and operators, never filter values (which frequently are PII). - -**Alternatives considered:** - -- Record full filter values for perfect audit trails. Rejected — violates GDPR/AVG principle of data minimisation (NEN-ISO 27001:2022 control 5.34). Single-row filters are user lookups; if telemetry records `status=GM0355` the aggregated report is useless (no pattern) and retention is a liability. -- No telemetry at all. Rejected — orgs need to understand which drill-down paths users exercise to tune hierarchies and retire unused widgets. - -**Rationale**: Aggregate reports ("most-used paths: gemeente → wijk → buurt", "least-used widget: [name]") drive tuning; individual filter values do not. The org gets actionable insights without exposing sensitive data. - -### D9: 300 ms responsiveness bound for widget re-renders - -**Decision**: When a filter clause is published, all consuming widgets MUST re-render and reflect the new filter within 300 ms. If a widget's fetch takes longer, the widget shows a loading indicator (existing pattern in REQ-WDG-007). - -**Alternatives considered:** - -- No bound, let widgets re-render whenever their fetch completes. Rejected — on slow networks this creates confusing visual delays ("did my click do anything?"). -- 100 ms to match Nielsen's "feels instantaneous" threshold. Rejected — achievable only for in-memory caches; most widgets fetch from OR, which takes 150-250 ms on normal networks. 300 ms is the midpoint that launchpad consistently hits for drill-down queries (which narrow scope, hitting better-selectivity indexes). - -**Rationale**: Jakob Nielsen's responsiveness thresholds — below 100 ms feels instantaneous, 100–1000 ms feels direct, beyond 1 s users lose flow. 300 ms is what real-world widget fetches from OR can sustain without artificial delays. - -## Risks / Trade-offs - -- **Risk:** URL grows unbounded if users apply a dozen clauses. → **Mitigation:** Conservative 2 KB limit documented in user guides; dashboards that habitually exceed this are an indicator they're doing too much and should be split. Failure mode (URL too long) is self-evident. -- **Risk:** Hierarchy inference fails if a clicked value doesn't exist in the parent level (e.g., user clicks a wijk that belongs to no gemeente in the dashboard's data). → **Mitigation:** The click is rejected with a tooltip "no access to this scope" (REQ-CWF-004). This prevents orphaned hierarchies. -- **Risk:** Pinned clauses are confusing if the UI doesn't signal them clearly. → **Mitigation:** Active-filters panel shows pinned clauses with a lock icon and no remove button; the restriction is visible. -- **Trade-off:** Last-write-wins ignores nuance ("I wanted to add this clause, not replace"). → **Mitigation:** The audit toast is explicit; users can undo via the active-filters panel. -- **Trade-off:** Telemetry does not record which user clicked which filter, only the aggregate. → **Accepted:** Orgs get path usage without exposing user behavior; precise click attribution is not necessary for hierarchy tuning. - -## Migration Plan - -1. **Manifest schema + composables land first** — add `publishes`, `consumes`, `hierarchies` fields to widget manifests; implement `useFilterBus` and `useDashboardFilter` with unit tests. No UX change yet. -2. **Dashboard host integration** — update `Dashboard.vue` to instantiate the bus, render the active-filters panel, expose "Reset filters". Wire widget clicks to publish events. -3. **Widget adaptation** — update chart and table widgets to emit click events with dimension + value. No manifest changes needed for widgets already accepting `filterContext` prop. -4. **Saved views UI** — add dropdown in dashboard header; "Save view" modal on the active-filters panel. -5. **Register integration** — persist saved views and filter events to the register (REQ-CWF-009 + REQ-CWF-010). -6. **Rollback:** Backend-persisted saved views and telemetry remain, but the filter bus ceases to function if the frontend is rolled back. This is acceptable because saved views are standalone (can be manually applied via the register) and telemetry is only for analytics, not operational. - -## Open Questions - -- Should hierarchy resolution be modal (all levels must exist) or lenient (infer as far as possible)? → Decision: Lenient, with a console warning for missing parent levels, so dashboards with partial hierarchies still work. -- Is 300 ms the right responsiveness target? → Decision: Confirmed via testing on production OR cluster with typical network latencies; 250 ms would be unachievable, 400 ms feels sluggish. -- Should users be able to pin their own clauses, or only org admins? → Decision: Org admins only (via dashboard config). Users can save named views instead for personal filter preferences. diff --git a/openspec/changes/drill-down-cross-widget-filter/proposal.md b/openspec/changes/drill-down-cross-widget-filter/proposal.md deleted file mode 100644 index ccab180e3..000000000 --- a/openspec/changes/drill-down-cross-widget-filter/proposal.md +++ /dev/null @@ -1,50 +0,0 @@ -# Drill-down Cross-widget Filter - -Cross-widget filtering closes the analytical workflow gap where each widget operates as a standalone island. Today, clicking a bar in one chart does nothing, forcing users to manually re-enter the same filter values into three different widgets, leading to inconsistencies and inefficiency. This change introduces a shared filter bus per dashboard that allows any widget to publish filter events (on click) and any widget to consume them (on render), enabling seamless drill-down exploration where all widgets stay synchronized through a single source of truth: the URL. - -The filter bus is built around five core principles. First, filter state is persisted in the URL as a bookmarkable, shareable snapshot — the same URL pasted elsewhere yields identical results. Second, widgets declare their publishing and consuming dimensions in their manifest, allowing the dashboard to validate compatibility statically and enable cross-widget interactions only where semantic links exist. Third, drill-down hierarchies are declarative, so clicking "Zeist" automatically narrows ancestor/descendant dimensions. Fourth, filter conflicts are resolved explicitly using last-write-wins per dimension, not silent merges, with audit tooltips so users understand what changed. Fifth, a single "Reset filters" action restores the unfiltered state, including the URL, ensuring users never get stranded. - -## Affected code units - -- `src/components/Dashboard.vue` — hosts the filter bus, renders active-filters panel, exposes "Reset filters" action -- `src/composables/useFilterBus.js` (new) — pub/sub implementation, dimension compatibility checking, hierarchy traversal -- `src/composables/useDashboardFilter.js` (new) — filter state serialization, URL encoding/decoding (base64url compact JSON) -- `src/components/widgets/ChartWidget.vue` + table widgets — accept `filterContext` prop (already passed for share-links), emit click events with dimension + value -- `lib/Register/DashboardFilterStateRegister.php` (new) — persists saved views and filter telemetry events -- Manifest schema: `widget.manifest.json` adds `publishes[]`, `consumes[]`, `hierarchies[]` fields per ADR-005 -- Adds new capability `cross-widget-filter` with requirements REQ-CWF-001 through REQ-CWF-010 -- Modifies dashboard routing to inject filter state on initial load (REQ-CWF-003) - -## Why a new capability - -Filter-driven collaboration between widgets is a top-level analytical feature, not an internal refactor. It touches the widget manifest schema, the dashboard host render, the OpenRegister integration layer, and persistence tier. Owning it as its own capability gives: - -1. A clear contract of which dashboard dimensions participate in filtering -2. Audit-ready telemetry for understanding which drill-down paths users actually exercise -3. A testable boundary: widgets can be tested for filter conformance in isolation -4. Bookmarkable, reproducible views via URL — auditable for compliance scenarios - -## Approach - -- **Filter bus** — thin pub/sub layer in the dashboard host. Widgets publish `{dimension, operator, value, sourceWidgetId}`. The bus applies last-write-wins conflict resolution and broadcasts to consuming widgets. -- **Manifest integration** — widget manifests declare `publishes: [{dimension, operator, fromField}]` and `consumes: [{dimension, operator, intoFilter}]`. The dashboard validates at render time. -- **Hierarchy support** — dash manifest declares `hierarchies: [{id, levels: [{dimension, parentDimension, label}]}]`. When a wijk-level click arrives, the bus infers ancestor clauses (`source=parentScope`) and clears descendants. -- **URL persistence** — filter state serialized to `?f=<base64url>` parameter using compact JSON (`{d, o, v, s, w}` keys). Restores on page load with `source=urlBootstrap`. -- **Saved views** — users with edit permission save the current filter set as a named view in the register; the dropdown applies them with one click, replacing non-pinned clauses. -- **Telemetry** — org-level opt-in flag. `filter_event` rows record apply/reset/bookmark/share events, dimension paths, and widget IDs (never filter values). Aggregate report shows most-used drill-down paths. -- **Conflict resolution** — new clause replacing an existing dimension shows a one-line audit toast (e.g., "Gemeente filter changed: Zeist → Houten"). Pinned clauses are immutable; replacements are silently dropped. -- **Reset action** — single button clears all non-pinned clauses and removes the `f` URL parameter. - -## Capabilities - -**New Capabilities:** - -- `cross-widget-filter` (adds REQ-CWF-001 through REQ-CWF-010) - -## Notes - -- The filter bus is opt-in per widget — widgets without `publishes`/`consumes` declarations continue to render with static filter context and do not participate. -- Existing widgets that already accept `filterContext` for share-links become instant bus participants with zero code change — they just need manifest updates. -- The bus translates clauses to OpenRegister `_filter` query parameters, reusing the existing index infrastructure; no new query engines. -- Hierarchy resolution (inferring ancestors from a child-level click) uses parent-relationships stable in the Dutch administrative model (wijk's first 4 digits are gemeentecode; gemeentecode's first 2 digits are provincecode). -- Filter values are never stored in telemetry — only operators, dimensions, and paths — for GDPR/privacy-by-design compliance (NEN-ISO 27001:2022 control 5.34). diff --git a/openspec/changes/drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md b/openspec/changes/drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md deleted file mode 100644 index e545a49de..000000000 --- a/openspec/changes/drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md +++ /dev/null @@ -1,579 +0,0 @@ ---- -capability: cross-widget-filter -status: draft ---- - -# Cross-Widget Filter — New capability from change `drill-down-cross-widget-filter` - -## Context - -This capability adds a shared filter bus to launchpad dashboards, allowing widgets to publish filter events (on click) and other widgets to consume them (on render). Filter state is persisted in the URL, made available via saved views, and optionally logged for aggregate telemetry. - -## NEW Requirements - -### Requirement: REQ-CWF-001 Widget click publishes to the filter bus - -The dashboard SHALL detect clicks on chartable elements of bus-aware widgets and SHALL publish the corresponding filter clause to the bus, identifying the publishing widget so the click can be visually echoed back. - -#### Scenario: Bar chart click publishes a clause - -- **GIVEN** a bar chart widget A on a dashboard, with a `publishes` declaration of `{dimension: "gemeenteCode", operator: "eq", fromField: "category"}` -- **WHEN** the user clicks the bar labelled "Zeist" (gemeenteCode `GM0355`) -- **THEN** a filter clause `{dimension: "gemeenteCode", operator: "eq", value: "GM0355", source: "widgetClick", sourceWidgetId: A}` SHALL be added to the bus - -#### Scenario: Widget without publishes declaration does nothing - -- **GIVEN** a widget WITHOUT a `publishes` declaration -- **WHEN** the user clicks an element -- **THEN** no clause SHALL be added to the bus and the click MAY perform a widget-local action (e.g. open detail modal) - -#### Scenario: Clicking the same clause again removes it (toggle) - -- **GIVEN** the same bar is clicked a second time -- **WHEN** the bus already contains that exact clause sourced from the same widget -- **THEN** the clause SHALL be removed (toggle behaviour) and the URL SHALL be updated to reflect the cleared state - ---- - -### Requirement: REQ-CWF-002 All consuming widgets re-render on filter change - -The system SHALL recompute and re-render every widget whose `consumes` declaration matches one or more active filter dimensions, passing the merged filter context as a prop, within 300 ms of the click. - -#### Scenario: Selective widget re-render - -- **GIVEN** three widgets on a dashboard: A (publishes gemeenteCode), B (consumes gemeenteCode), C (does not consume gemeenteCode) -- **WHEN** the user clicks "Zeist" on A -- **THEN** A SHALL echo the selection visually, B SHALL re-render with `gemeenteCode=GM0355` applied, and C SHALL NOT re-render - -#### Scenario: New widget receives current filter state on mount - -- **GIVEN** a widget whose `consumes` declaration includes a dimension currently in the bus -- **WHEN** the widget mounts (or is dragged onto the dashboard) -- **THEN** it SHALL receive the current bus state on first render and SHALL NOT show a flash of unfiltered content - ---- - -### Requirement: REQ-CWF-003 URL encoding makes filtered views bookmarkable - -The system SHALL serialise the active filter state into a URL query parameter and SHALL restore the filter state on initial load when the parameter is present, producing the same view the URL-issuer saw. - -#### Scenario: URL encodes active filter state - -- **GIVEN** a dashboard with two active clauses (`gemeenteCode=GM0355`, `status=open`) -- **WHEN** the URL is copied -- **THEN** it SHALL contain a `?f=...` parameter encoding both clauses - -#### Scenario: Loading a bookmarked URL restores filter state - -- **GIVEN** that URL is pasted into a second browser by a second user with read access to the dashboard -- **WHEN** the page loads -- **THEN** both clauses SHALL be restored with `source=urlBootstrap` and the visible widgets SHALL reflect the filtered numbers without any user action - -#### Scenario: Malformed URL parameter does not crash - -- **GIVEN** a URL whose `f` parameter is malformed -- **WHEN** the page loads -- **THEN** the dashboard SHALL render with an empty filter state and SHALL log a single warning (no error toast on the user) - ---- - -### Requirement: REQ-CWF-004 Drill-down hierarchies update breadcrumb and descendant filters - -When a click publishes a clause for a dimension that is part of a `hierarchy_descriptor`, the system SHALL update the breadcrumb UI to show the active path and SHALL clear any descendant-level clauses from the bus before applying the new clause. - -#### Scenario: Drilling up clears descendant filters - -- **GIVEN** the `nl-administrative` hierarchy is active on a dashboard, with current clauses `gemeenteCode=GM0355` and `wijkCode=WK0355001` -- **WHEN** the user clicks "Provincie Utrecht" on a province-level widget (publishing `provincieCode=PV09`) -- **THEN** the bus SHALL contain only `{provincieCode=PV09}` (gemeente and wijk are cleared because they are descendants) and the breadcrumb SHALL show "Provincie Utrecht" - -#### Scenario: Drilling down infers ancestor filters - -- **GIVEN** the same dashboard with no active filters -- **WHEN** the user clicks a wijk on a wijk-level widget (publishing `wijkCode=WK0355001`) -- **THEN** the bus SHALL contain `{wijkCode=WK0355001}` AND the hierarchy resolver SHALL infer and add ancestor clauses (`gemeenteCode=GM0355`, `provincieCode=PV09`) marked with `source=parentScope` so the breadcrumb shows the full path - -#### Scenario: Permission-denied on hierarchy level - -- **GIVEN** a click on a hierarchy level the user has no permission for (e.g. a gemeenteCode their role doesn't expose) -- **WHEN** the click is processed -- **THEN** the publication SHALL be rejected, the widget SHALL show a tooltip explaining "no access to this scope", and the bus SHALL NOT be mutated - ---- - -### Requirement: REQ-CWF-005 Filter conflict resolution is last-write-wins per dimension - -When a new clause is published for a dimension that already has an active clause from a different source or operator, the system SHALL replace (not append) the existing clause and SHALL show a one-line audit tooltip indicating which previous clause was replaced. - -#### Scenario: Widget-click replaces widget-click - -- **GIVEN** an active clause `{gemeenteCode=GM0355, source=widgetClick}` from widget A -- **WHEN** widget B publishes `{gemeenteCode=GM0344, source=widgetClick}` -- **THEN** the bus SHALL contain only the new clause from B, widget A SHALL update its visual echo to deselect GM0355, and a brief toast SHALL indicate "Gemeente filter changed from Zeist to Houten" - -#### Scenario: Widget-click silently replaces URL-bootstrap - -- **GIVEN** an active clause sourced from `urlBootstrap` -- **WHEN** a widget-click clause for the same dimension arrives -- **THEN** the widget-click clause SHALL replace the URL-bootstrap one with no toast (URL bootstrap is treated as a transient initial state, not a deliberate user choice) - -#### Scenario: Pinned clause cannot be replaced - -- **GIVEN** an active `pinned: true` clause -- **WHEN** a clause for the same dimension arrives from any source -- **THEN** the pinned clause SHALL NOT be replaced and the new publication SHALL be silently dropped with a one-line console log (so a developer can see why their click did not stick) - ---- - -### Requirement: REQ-CWF-006 Reset filters clears all non-pinned clauses - -The dashboard SHALL expose a "Reset filters" action that clears every non-pinned clause from the bus and SHALL update the URL to remove the `f` parameter. - -#### Scenario: Reset clears non-pinned clauses, keeps pinned - -- **GIVEN** a dashboard with five active clauses, one of which is pinned -- **WHEN** the user invokes "Reset filters" -- **THEN** four clauses SHALL be removed, the pinned clause SHALL remain, the URL SHALL be updated, and every consuming widget SHALL re-render with the reduced filter context - -#### Scenario: Reset on empty bus is a no-op - -- **GIVEN** a dashboard with no active clauses -- **WHEN** "Reset filters" is invoked -- **THEN** the action SHALL be a no-op (no URL change, no widget re-render, no telemetry event) so accidental double-clicks do not produce noise - ---- - -### Requirement: REQ-CWF-007 Filter stack UI shows every active clause with its source - -The dashboard SHALL render a compact "Active filters" panel listing every active clause with its dimension label, value, source widget (when applicable), and an individual remove-action; the panel SHALL collapse when empty. - -#### Scenario: Active filters panel shows all clauses with source - -- **GIVEN** three active clauses (one from a widget click, one from URL bootstrap, one pinned by the org) -- **WHEN** the panel is rendered -- **THEN** it SHALL show three chips with distinct visual treatment per source (e.g. widget-click chips show the source widget's name, pinned chips show a lock icon and have no remove-action) - -#### Scenario: Remove single clause from panel - -- **GIVEN** the user clicks the remove-action on a single chip -- **WHEN** the click is processed -- **THEN** only that clause SHALL be removed, the URL SHALL be updated, and the originating widget (if any) SHALL update its visual echo to deselect - ---- - -### Requirement: REQ-CWF-008 Widget manifest declares publishes/consumes; dashboard validates compatibility - -The widget loader SHALL read `publishes` and `consumes` from the widget manifest and the dashboard SHALL refuse to render a widget whose manifest declares dimensions inconsistent with the dashboard's hierarchy descriptors, surfacing the mismatch in the widget config UI. - -#### Scenario: Consuming dimension not in dashboard hierarchies - -- **GIVEN** a widget manifest declaring `consumes: [{dimension: "wijkCode"}]` on a dashboard whose hierarchy descriptors do not include `wijkCode` -- **WHEN** the widget is added to the dashboard -- **THEN** the widget config UI SHALL show a non-fatal warning ("This widget consumes 'wijkCode' but no hierarchy on this dashboard publishes it") and the widget SHALL render as a non-bus-participant - -#### Scenario: Publishing from missing field - -- **GIVEN** a widget manifest declaring `publishes: [{dimension: "gemeenteCode", fromField: "missingField"}]` where `missingField` is not in the widget's data shape -- **WHEN** the widget renders -- **THEN** the dashboard SHALL log a manifest-validation error and disable bus participation for that widget (no clicks publish) - ---- - -### Requirement: REQ-CWF-009 Saved views persist named filter combinations - -The system SHALL allow users with edit permission on a dashboard to save the current filter state as a named view, list saved views in a dashboard-header dropdown, and apply a saved view with one click. - -#### Scenario: Save current filter state as named view - -- **GIVEN** a dashboard with three active clauses -- **WHEN** the user invokes "Save view" and provides the name "Open bezwaren Zeist 6w+" -- **THEN** a `saved_view` row SHALL be persisted with those three clauses, scoped to that dashboard, and the saved view SHALL appear in the header dropdown - -#### Scenario: Apply saved view - -- **GIVEN** a saved view with five clauses -- **WHEN** a user with view permission on the dashboard selects it from the dropdown -- **THEN** all current non-pinned clauses SHALL be replaced with the saved view's clauses and the URL SHALL update accordingly - -#### Scenario: Shared saved views appear for other users - -- **GIVEN** a saved view marked `isShared: true` -- **WHEN** a different user with view permission opens the dashboard -- **THEN** the saved view SHALL appear in their dropdown (under a "Shared" section) and SHALL be applicable but not editable by them - ---- - -### Requirement: REQ-CWF-010 Telemetry of filter usage is opt-in and aggregated - -When org-level telemetry is enabled, the system SHALL persist `filter_event` rows for `apply` / `reset` / `bookmark` / `share` events with no PII beyond the user id, and SHALL expose an aggregate report ("most-used drill-down paths per dashboard") to dashboard owners. - -#### Scenario: Telemetry disabled (default) - -- **GIVEN** telemetry is disabled (default) -- **WHEN** any filter event occurs -- **THEN** no `filter_event` row SHALL be written - -#### Scenario: Filter apply event is recorded - -- **GIVEN** telemetry is enabled and a user clicks a wijk on widget A -- **WHEN** the click is processed -- **THEN** a `filter_event` row SHALL be written with `eventType=apply`, the wijk clause delta, `widgetId=A`, and the user id, AND the URL/share event SHALL NOT be conflated with the click event (two separate rows) - -#### Scenario: Bookmark event on page load - -- **GIVEN** telemetry is enabled and an authenticated user opens a bookmarked URL -- **WHEN** the page loads -- **THEN** exactly one row SHALL be written with `eventType=bookmark` and the full clause set as the delta - ---- - -## Data Model - -### dashboard_filter_state - -Holds the active filter set for a dashboard view. In steady state, the URL is the system of record; saved views persist this shape to the register. - -- `id` (UUID, nullable) — set only for saved views -- `dashboardId` (UUID) — references a dashboard -- `name` (string, nullable) — set only for saved views -- `filters` (array of filter_clause objects) — active clauses -- `appliedAt` (ISO timestamp) — for telemetry - -#### Seed Data - -```json -{ - "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", - "name": "Open bezwaren Zeist > 6w", - "filters": [ - { - "dimension": "gemeenteCode", - "operator": "eq", - "value": "GM0355", - "source": "widgetClick", - "sourceWidgetId": "w-chart-gemeenten" - }, - { - "dimension": "status", - "operator": "eq", - "value": "open", - "source": "widgetClick", - "sourceWidgetId": "w-chip-status" - }, - { - "dimension": "ageInDays", - "operator": "gte", - "value": 42, - "source": "userExplicit", - "pinned": true - } - ], - "appliedAt": "2026-05-22T14:35:00Z" -} -``` - -### filter_clause - -Describes one active filter. Keyed in compact form for URL encoding as `{d, o, v, s, w, p}`. - -- `dimension` (string, e.g. `gemeenteCode`, `wijkCode`, `period.month`) — the filtered attribute -- `operator` (enum: `eq`, `in`, `between`, `gte`, `lte`, `contains`, `notNull`) — comparison operator -- `value` (scalar, array, or `[low, high]` tuple) — depends on operator; never stored in telemetry -- `source` (enum: `userExplicit`, `widgetClick`, `urlBootstrap`, `savedView`, `parentScope`) — origin -- `sourceWidgetId` (UUID, nullable) — set when `source=widgetClick` -- `pinned` (boolean, default false) — pinned clauses survive "Reset filters" - -#### Seed Data - -```json -[ - { - "dimension": "gemeenteCode", - "operator": "eq", - "value": "GM0355", - "source": "widgetClick", - "sourceWidgetId": "w-chart-gemeenten" - }, - { - "dimension": "wijkCode", - "operator": "in", - "value": ["WK0355001", "WK0355002"], - "source": "widgetClick", - "sourceWidgetId": "w-map-wijken" - }, - { - "dimension": "ageInDays", - "operator": "gte", - "value": 42, - "source": "userExplicit", - "pinned": true - } -] -``` - -### dimension_descriptor - -Lives in the widget manifest and declares what a widget can publish and consume. - -- `publishes` (array of objects) — describes what a click on a particular column/series/cell publishes - - `dimension` (string) — the dimension published - - `operator` (enum) — typically `eq` for categorical clicks, can be `between` for range selections - - `fromField` (string) — the data field that supplies the value (e.g. `category`, `date`) -- `consumes` (array of objects) — describes which incoming dimensions narrow this widget's query - - `dimension` (string) — the dimension consumed - - `operator` (enum) — filtering operator the widget applies - - `intoFilter` (string, nullable) — the parameter name to pass to the data source (e.g. `_filter[gemeenteCode]`) -- `hierarchies` (array of hierarchy_descriptor objects) — see below - -#### Seed Data - -```json -{ - "publishes": [ - { - "dimension": "gemeenteCode", - "operator": "eq", - "fromField": "category" - } - ], - "consumes": [ - { - "dimension": "gemeenteCode", - "operator": "eq", - "intoFilter": "_filter[gemeenteCode]" - }, - { - "dimension": "status", - "operator": "eq", - "intoFilter": "_filter[status]" - } - ], - "hierarchies": [ - { - "id": "nl-administrative", - "levels": [ - { - "dimension": "provincieCode", - "label": "Provincie" - }, - { - "dimension": "gemeenteCode", - "label": "Gemeente", - "parentDimension": "provincieCode" - }, - { - "dimension": "wijkCode", - "label": "Wijk", - "parentDimension": "gemeenteCode" - } - ] - } - ] -} -``` - -### hierarchy_descriptor - -Declares a drill-down chain for inferring ancestor and descendant relationships. - -- `id` (string, e.g. `nl-administrative`, `temporal-iso8601`) — unique identifier -- `levels` (ordered array) — hierarchy levels from broadest to finest - - `dimension` (string) — the dimension at this level - - `label` (string, i18n key) — human-readable label for breadcrumb - - `parentDimension` (string, nullable) — the dimension that is the parent level - -#### Seed Data - -```json -[ - { - "id": "nl-administrative", - "levels": [ - { - "dimension": "provincieCode", - "label": "hierarchy.level.province", - "parentDimension": null - }, - { - "dimension": "gemeenteCode", - "label": "hierarchy.level.municipality", - "parentDimension": "provincieCode" - }, - { - "dimension": "wijkCode", - "label": "hierarchy.level.district", - "parentDimension": "gemeenteCode" - }, - { - "dimension": "buurtCode", - "label": "hierarchy.level.neighbourhood", - "parentDimension": "wijkCode" - } - ] - }, - { - "id": "temporal-iso8601", - "levels": [ - { - "dimension": "period.year", - "label": "hierarchy.level.year" - }, - { - "dimension": "period.quarter", - "label": "hierarchy.level.quarter", - "parentDimension": "period.year" - }, - { - "dimension": "period.month", - "label": "hierarchy.level.month", - "parentDimension": "period.quarter" - }, - { - "dimension": "period.week", - "label": "hierarchy.level.week", - "parentDimension": "period.month" - } - ] - } -] -``` - -### saved_view - -Persisted named filter combination, scoped to a dashboard. - -- `id` (UUID) — primary key -- `dashboardId` (UUID) — references the dashboard -- `name` (string) — user-visible name -- `description` (string, nullable) — optional explanation -- `filters` (array of filter_clause objects) — the saved filter set -- `isShared` (boolean) — whether other users can apply this view -- `sharedWith` (array of user/group IDs, nullable) — explicit share list (used only if `isShared=true`) -- `createdBy` (UUID) — user who created this view -- `createdAt` (ISO timestamp) — creation timestamp - -#### Seed Data - -```json -[ - { - "id": "sv-001", - "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", - "name": "Open bezwaren Zeist > 6w", - "description": "All open complaints in Zeist older than 6 weeks", - "filters": [ - { - "dimension": "gemeenteCode", - "operator": "eq", - "value": "GM0355", - "source": "savedView" - }, - { - "dimension": "status", - "operator": "eq", - "value": "open", - "source": "savedView" - }, - { - "dimension": "ageInDays", - "operator": "gte", - "value": 42, - "source": "savedView" - } - ], - "isShared": true, - "sharedWith": null, - "createdBy": "u-analyst-01", - "createdAt": "2026-05-15T10:00:00Z" - }, - { - "id": "sv-002", - "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", - "name": "2026 Q2 Trend by Wijk", - "description": "Filter to 2026 Q2 aggregated by wijk within the user's gemeente", - "filters": [ - { - "dimension": "period.quarter", - "operator": "eq", - "value": "2026-Q2", - "source": "savedView" - } - ], - "isShared": false, - "sharedWith": null, - "createdBy": "u-manager-01", - "createdAt": "2026-05-20T14:22:00Z" - } -] -``` - -### filter_event - -Telemetry row written when an opt-in dashboard has telemetry enabled (org-level setting, default off). Records dimension and operator changes, not filter values (which may be PII). - -- `id` (UUID) — primary key -- `dashboardId` (UUID) — references the dashboard -- `userId` (UUID) — authenticated user -- `widgetId` (UUID, nullable) — set for widget-click events -- `eventType` (enum: `apply`, `reset`, `bookmark`, `share`) — event classification -- `filterDelta` (array of filter_clause objects) — the clauses added/removed by this event (no values) -- `timestamp` (ISO timestamp) — when the event occurred - -#### Seed Data - -```json -[ - { - "id": "fe-001", - "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", - "userId": "u-caseworker-01", - "widgetId": "w-chart-gemeenten", - "eventType": "apply", - "filterDelta": [ - { - "dimension": "gemeenteCode", - "operator": "eq", - "source": "widgetClick", - "sourceWidgetId": "w-chart-gemeenten" - } - ], - "timestamp": "2026-05-22T14:35:00Z" - }, - { - "id": "fe-002", - "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", - "userId": "u-caseworker-01", - "widgetId": "w-map-wijken", - "eventType": "apply", - "filterDelta": [ - { - "dimension": "wijkCode", - "operator": "eq", - "source": "widgetClick", - "sourceWidgetId": "w-map-wijken" - } - ], - "timestamp": "2026-05-22T14:35:45Z" - }, - { - "id": "fe-003", - "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", - "userId": "u-caseworker-02", - "widgetId": null, - "eventType": "bookmark", - "filterDelta": [ - { - "dimension": "gemeenteCode", - "operator": "eq", - "source": "urlBootstrap" - }, - { - "dimension": "status", - "operator": "eq", - "source": "urlBootstrap" - } - ], - "timestamp": "2026-05-22T15:10:00Z" - } -] -``` diff --git a/openspec/changes/drill-down-cross-widget-filter/tasks.md b/openspec/changes/drill-down-cross-widget-filter/tasks.md deleted file mode 100644 index b22ffc944..000000000 --- a/openspec/changes/drill-down-cross-widget-filter/tasks.md +++ /dev/null @@ -1,107 +0,0 @@ -# Tasks — drill-down-cross-widget-filter - -## Tasks - -### Core Filter Bus Implementation - -- [ ] Task 1: Create `src/composables/useFilterBus.js` with the pub/sub implementation. Export a composable that manages the filter state, accepts `publish(clause)` calls, and broadcasts to subscribers. Implement internal `_applyConflictResolution(newClause)` that enforces last-write-wins per dimension and tracks audit info (old value, new value, source transition). Inline comment linking REQ-CWF-001 through REQ-CWF-005. - -- [ ] Task 2: Implement hierarchy resolution in `useFilterBus.js`. Add `_resolveHierarchy(clause, dashboardHierarchies)` that detects when a published clause belongs to a hierarchy level, infers ancestor clauses (marked `source=parentScope`) from the administrative/temporal hierarchy, and clears any descendant clauses currently in the bus. Handle missing parent levels gracefully with a console warning. Link REQ-CWF-004. - -- [ ] Task 3: Create `src/composables/useDashboardFilter.js` with URL serialization/deserialization. Export `serializeFilterState(clauses): string` (returns base64url-encoded compact JSON with keys `d, o, v, s, w, p`) and `deserializeFilterState(param): {clauses, error}`. Implement lenient parsing (malformed param logs warning, returns empty clauses). Link REQ-CWF-003. - -- [ ] Task 4: Integrate the filter bus into `src/components/Dashboard.vue`. Instantiate `useFilterBus()` on mount, hydrate from URL parameter via `useDashboardFilter()` on initial load (mark restored clauses with `source=urlBootstrap`), and sync the bus to the URL whenever the filter state changes (debounced 500ms to avoid excessive URL rewrites). Link REQ-CWF-003. - -- [ ] Task 5: Render the "Active filters" panel in `Dashboard.vue` header. For each active clause, render a chip with dimension label, value, and source icon (widget name for `widgetClick`, lock for `pinned`, none for `userExplicit`). Add a remove-button for non-pinned clauses. Pinned clauses show a lock icon and no remove-button. Panel collapses when empty. Link REQ-CWF-007. - -- [ ] Task 6: Add "Reset filters" button to the dashboard header in `Dashboard.vue`. Invoke callback that clears all non-pinned clauses from the bus, updates the URL (removes `f` parameter), and triggers widget re-renders. No-op when the bus is already empty (no telemetry, no URL change). Link REQ-CWF-006. - -### Widget Integration - -- [ ] Task 7: Update `src/components/widgets/ChartWidget.vue` (and analogous table/list widgets) to accept `filterContext` prop (already passed from dashboard for share-links; no change needed). Emit a `filter-published` event on chartable element click (bar, row, cell) with payload `{dimension, operator, value}`. The dashboard's bus subscriber listens for this event and calls `bus.publish()`. Link REQ-CWF-001, REQ-CWF-002. - -- [ ] Task 8: Update widget manifest schema to include `publishes`, `consumes`, and `hierarchies` arrays. For existing chart and table widgets, populate `consumes` with the dimensions they accept in `filterContext`. For "click-enabled" widgets (charts with drill-down configured), populate `publishes` with the clickable dimensions. Hierarchies are inherited from the dashboard config. Link REQ-CWF-008. - -- [ ] Task 9: Implement widget manifest validation in `Dashboard.vue` on render. Read widget's `publishes` and `consumes` declarations; cross-reference against the dashboard's hierarchy descriptors. Surface non-fatal warnings in the widget config UI if a consuming dimension is not in any dashboard hierarchy, or if a publishing dimension's `fromField` is not in the widget's data shape. Log validation errors to console. Link REQ-CWF-008. - -- [ ] Task 10: Ensure all consuming widgets re-render within 300ms of a filter change (REQ-CWF-002). When the bus publishes a new clause, compute the set of consuming widgets (those whose `consumes` includes that dimension), trigger their `refetch()` methods (standard in REQ-WDG-006), and await the promise. If a fetch exceeds 300ms, the widget's existing loading indicator (REQ-WDG-007) kicks in. Profile on the production OR cluster to confirm the 300ms bound is met for typical drill-down queries (narrower scope, better selectivity). Link REQ-CWF-002. - -### Saved Views - -- [ ] Task 11: Create a "Save view" modal in `Dashboard.vue` (triggered by a button in the active-filters panel or dashboard header). Capture a name and optional description, bundle the current filter state, and POST to the register endpoint `POST /register/saved-views` with payload matching the `saved_view` shape (dashboard scoped, creator marked, timestamp set). Success redirects to the saved-views dropdown. Link REQ-CWF-009. - -- [ ] Task 12: Add a "Saved views" dropdown in the `Dashboard.vue` header. On mount, fetch the dashboard's saved views from `GET /register/saved-views?dashboard=<dashboardId>`. Render saved views in two sections: "My views" (createdBy current user) and "Shared views" (isShared=true). Clicking a saved view applies all its clauses to the bus (replacing non-pinned clauses), updates the URL, and triggers widget re-renders. Link REQ-CWF-009. - -- [ ] Task 13: Add edit/delete affordances to saved views. Users who created a view can edit its name/description and delete it (delete endpoint `DELETE /register/saved-views/<id>`). Shared views are read-only for non-creators. Include an "unshare" action for the creator. Link REQ-CWF-009. - -### Telemetry & Persistence - -- [ ] Task 14: Create `lib/Register/DashboardFilterStateRegister.php` as a new register schema for persisting saved views and telemetry. Implement the `saved_view` shape with fields: `id`, `dashboardId`, `name`, `description`, `filters` (JSON), `isShared`, `sharedWith`, `createdBy`, `createdAt`. Add endpoints: `POST /register/saved-views`, `GET /register/saved-views?dashboard=<id>`, `PATCH /register/saved-views/<id>`, `DELETE /register/saved-views/<id>`. Link REQ-CWF-009. - -- [ ] Task 15: Implement filter telemetry logging in `useFilterBus.js`. When a clause is published and an org-level telemetry flag is enabled, construct a `filter_event` row with `eventType=apply`, the published clause's dimension/operator (no value), the source widget ID (if applicable), and the user ID. POST to `POST /register/filter-events` (implementation in Task 16). When "Reset filters" is invoked, write a separate `filter_event` with `eventType=reset` and the cleared clauses. When a bookmarked URL is loaded, write a `filter_event` with `eventType=bookmark` on next tick. Link REQ-CWF-010. - -- [ ] Task 16: Create endpoints in `lib/Register/DashboardFilterStateRegister.php` for telemetry: `POST /register/filter-events` persists the event row with no value data (dimensions + operators only). Implement a read-only aggregate report endpoint `GET /register/filter-events/report?dashboard=<id>` that returns paths and frequency counts (e.g., `[{path: "gemeenteCode → wijkCode", count: 42}, ...]`). This report is visible to dashboard owners and admins; restrict per-user telemetry to the current user's own events. Link REQ-CWF-010. - -- [ ] Task 17: Add org-level telemetry toggle to the admin settings (or dashboard config). Default is `false` (telemetry disabled). When toggled on, `useFilterBus.js` starts writing `filter_event` rows for subsequent filter operations. Existing events are not retroactively generated. Link REQ-CWF-010. - -### Testing - -- [ ] Task 18: Vitest — `useFilterBus.js` conflict resolution. New clause for dimension X replaces old clause for X when sources differ; widget-click replaces widget-click (shows toast); urlBootstrap → widget-click is silent; pinned clause cannot be replaced (publication dropped, console log). Test that toggle (same clause clicked twice) removes the clause. Link REQ-CWF-001, REQ-CWF-005. - -- [ ] Task 19: Vitest — `useFilterBus.js` hierarchy resolution. When a wijk-level click arrives, infer ancestor clauses (gemeentecode, provincecode) marked `source=parentScope`. When a province-level click arrives with existing wijk clauses, clear the wijk. When a wijk from a different gemeente is clicked, reject and log error (no matching parent). Test breadcrumb updates. Link REQ-CWF-004. - -- [ ] Task 20: Vitest — `useDashboardFilter.js` serialization/deserialization. Serialize a set of clauses (verschiedende dimensions, operators, sources) to base64url-compact-JSON and back; verify round-trip fidelity. Malformed parameter returns empty clauses + warning. Verify the compact JSON uses short keys (d, o, v, s, w, p) and stays under 2 KB for a 10-clause set. Link REQ-CWF-003. - -- [ ] Task 21: Vitest — widget manifest validation. Dashboard loads a widget with `consumes: ["wijkCode"]` but no hierarchy includes wijkCode; validation surfaces warning and marks widget as non-bus-participant. Widget with `publishes: [{fromField: "missingField"}]` but data has no "missingField" key; validation logs error and disables bus participation. Matching dimensions pass validation. Link REQ-CWF-008. - -- [ ] Task 22: Playwright — end-to-end filter workflow. Dashboard with three widgets (A: gemeente chart, B: wijk table consuming gemeenteCode, C: status chips not consuming any dimension). User clicks "Zeist" on A; B re-renders with filtered data, C does not re-render, URL updates with `f=...` parameter. User clicks "Vollenhove" on A; A's selection toggles to Vollenhove (or clears if double-click), B updates, URL changes. User copies URL and opens in incognito browser; same filters restore. Link REQ-CWF-001, REQ-CWF-002, REQ-CWF-003. - -- [ ] Task 23: Playwright — hierarchy drill-down. Dashboard with nl-administrative hierarchy. User clicks a wijk; breadcrumb shows "Provincie X > Gemeente Y > Wijk Z", gemeentecode and provincieCode are inferred in the bus. User clicks up to provincie; wijk and gemeente are cleared, breadcrumb updates. User clicks a different wijk in a different gemeente; ancestors change, breadcrumb updates. Link REQ-CWF-004. - -- [ ] Task 24: Playwright — conflict resolution and audit. Two charts (A and B) both publish gemeenteCode. User clicks Zeist on A; A highlights, B's data filters to Zeist. User clicks Houten on B; A's highlight clears, B highlights, a toast says "Gemeente filter changed: Zeist → Houten", active-filters panel shows only Houten. URL reflects the change. Link REQ-CWF-005. - -- [ ] Task 25: Playwright — reset filters. Dashboard with 5 active clauses, one pinned. User clicks "Reset filters"; 4 non-pinned clauses disappear, pinned remains, URL `f` parameter is removed, consuming widgets re-render. Active-filters panel shows only the pinned clause. User clicks Reset on an already-empty bus; no change, no telemetry event. Link REQ-CWF-006. - -- [ ] Task 26: Playwright — active-filters panel interactions. Dashboard with 3 clauses (one widgetClick, one urlBootstrap, one pinned). Panel renders all three with source icons (widget name for widgetClick, no icon for urlBootstrap, lock for pinned). Pinned clause has no remove-button; others do. User clicks remove on a widgetClick clause; it vanishes, URL updates, publishing widget's selection clears. Non-pinned clauses can be individually removed; pinned cannot. Link REQ-CWF-007. - -- [ ] Task 27: Playwright — saved views. User applies filters (3 clauses), clicks "Save view", provides name "Q2 Trend". View is saved and appears in the dropdown. Same user clicks it again later with different filters active; all 3 clauses are restored. User shares the view; another user sees it in the "Shared" section. Shared view is read-only (no edit/delete). Link REQ-CWF-009. - -- [ ] Task 28: Playwright — telemetry recording (when enabled). Enable org-level telemetry. User clicks Zeist on a chart; a `filter_event` row is written with `eventType=apply`, dimension=gemeenteCode, operator=eq, sourceWidgetId=<chart>, no value field. User copies URL and opens in another tab; on load, a `filter_event` with `eventType=bookmark` is written. User clicks "Reset filters"; a `filter_event` with `eventType=reset` and the cleared clauses is written. Disable telemetry; no events are written on subsequent actions. Link REQ-CWF-010. - -- [ ] Task 29: Playwright — manifest validation warnings in widget config. Dashboard loads a widget that consumes "wijkCode" but wijkCode is not in the dashboard's hierarchies; widget config UI shows a yellow warning chip ("This widget consumes wijkCode but no hierarchy on this dashboard publishes it"). Widget still renders but does not participate in the bus. User can dismiss the warning or remove the widget. Link REQ-CWF-008. - -- [ ] Task 30: Vitest — 300 ms responsiveness. Mock a widget's refetch to resolve after 100 ms, another after 250 ms. Trigger a filter publication; measure the time from publish to all consuming widgets updated in the DOM. Confirm both are within 300 ms (or log a performance warning if they exceed it). Link REQ-CWF-002. - -### Quality & Documentation - -- [ ] Task 31: ESLint clean on touched Vue/JS files. PHPCS/PHPMD clean on new PHP classes. PHPStan/Psalm type-checking on the new Register class. No new TSConfig errors if TypeScript is in use. Run `composer check:strict` before commit. Link company-wide ADR-009 (quality gates). - -- [ ] Task 32: i18n review. No new user-facing strings expected except: "Active filters" panel header, "Reset filters" button, conflict resolution toast ("Gemeente filter changed: X → Y"), permission-denied tooltip ("no access to this scope"), "Save view" modal title, "Saved views" dropdown label, and the "Shared" section in the dropdown. All strings added to both `lang/nl.json` and `lang/en.json` with translation keys (e.g., `filter.activeFilters`, `filter.resetButton`). Link company-wide ADR-005 (i18n). - -- [ ] Task 33: Inline documentation. `useFilterBus.js` includes a header comment summarizing the pub/sub contract, conflict resolution rules, and hierarchy semantics with links to REQ-CWF-001–005. `useDashboardFilter.js` documents the URL encoding scheme (compact JSON, keys, length guidance). `DashboardFilterStateRegister.php` documents the register shapes and endpoint contracts. No separate design doc needed; context-brief.md and this spec.md are the authoritative references. Link company-wide ADR-010 (documentation). - -- [ ] Task 34: Changelog entry. Summarize the feature: "Add cross-widget filter bus enabling drill-down exploration across dashboard widgets. Widgets publish filters on click; all consuming widgets re-render. Filter state is bookmarkable via URL and saveable as named views. Opt-in telemetry measures drill-down path usage." Include a note that existing widgets that accept `filterContext` become instant bus participants with zero code change. - -- [ ] Task 35: Performance audit. After widgets are wired to the bus, measure query time for drill-down operations (e.g., click gemeentecode, then wijkcode) on the production OR cluster. Confirm the 300 ms responsiveness bound is met. Log a performance warning if a single widget re-render exceeds 200 ms (indicating slow OR query). Profile memory usage on a dashboard with 100+ widgets to ensure the bus's pub/sub subscription overhead is negligible (<1 MB). Document results as a comment in `Dashboard.vue`. Link REQ-CWF-002. - -## Verification - -`openspec validate` exits clean. Dashboard with bus-aware widgets enables seamless drill-down filtering; filter state is reproducible via URL and bookmarkable; saved views work end-to-end; telemetry (if enabled) records paths without exposing values. - -## Tests (company-wide ADR-009) - -- Vitest: conflict resolution, hierarchy resolution, serialization, manifest validation, responsiveness (Tasks 18–21, 30). -- Playwright: end-to-end workflows, widget integration, saved views, telemetry (Tasks 22–29). -- No new backend-specific tests beyond register integration; existing REQ-WDG-006 (widget fetch) tests cover the query integration. - -## Documentation (company-wide ADR-010) - -- Inline composable comments (Tasks 33). -- Changelog entry (Task 34). -- No separate ADR needed; the feature is scoped to this change and well-documented in the context-brief.md and spec.md. -- User guide (out of scope for this change, but mentioned in design.md under "open questions"): URL bookmarking, saved views, hierarchy breadcrumb, conflict resolution toast. - -## i18n (company-wide ADR-005) - -- All user-facing strings added to both `nl.json` and `en.json` (Task 32). -- Dutch locale is the primary; English is a parity copy. No culture-specific logic (e.g., date/number formatting) required for filter state. diff --git a/openspec/changes/e2e-coverage-programme/.openspec.yaml b/openspec/changes/e2e-coverage-programme/.openspec.yaml index 515eaae39..c1b279b94 100644 --- a/openspec/changes/e2e-coverage-programme/.openspec.yaml +++ b/openspec/changes/e2e-coverage-programme/.openspec.yaml @@ -1,2 +1,3 @@ schema: spec-driven created: 2026-09-11 +skip_specs: true diff --git a/openspec/changes/e2e-coverage-programme/screens.md b/openspec/changes/e2e-coverage-programme/screens.md new file mode 100644 index 000000000..2fb1d4cd2 --- /dev/null +++ b/openspec/changes/e2e-coverage-programme/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: tests, nothing a user operates diff --git a/openspec/changes/e2e-coverage-programme/tasks.md b/openspec/changes/e2e-coverage-programme/tasks.md index adcb81bec..387d770fb 100644 --- a/openspec/changes/e2e-coverage-programme/tasks.md +++ b/openspec/changes/e2e-coverage-programme/tasks.md @@ -13,105 +13,341 @@ Counts are scenarios, and scenarios cited by a Playwright test, measured on `dev 8 specs, 343 scenarios. -- [ ] 1.1 `admin-settings`: 83 scenarios, 2 cited, blanket. Access requirements in progress 2026-09-11. Its settings-behaviour scenarios stay open under this task. -- [ ] 1.2 `admin-roles`: 55 scenarios, 0 cited, blanket. In progress 2026-09-11. -- [ ] 1.3 `conditional-visibility`: 49 scenarios, 0 cited, blanket. In progress 2026-09-11. -- [ ] 1.4 `permissions`: 42 scenarios, 0 cited, blanket. In progress 2026-09-11, with `admin-roles` and the access requirements of `admin-settings`. -- [ ] 1.5 `dashboard-public-share`: 38 scenarios, 25 cited. In progress 2026-09-11. -- [ ] 1.6 `dashboard-sharing`: 34 scenarios, 10 cited. In progress 2026-09-11. Supersedes `add-dashboard-sharing-e2e-coverage`. -- [ ] 1.7 `role-feature-permissions`: 27 scenarios, 0 cited. Queued 2026-09-11, after the permissions PR. +- [x] 1.1 `admin-settings`: 83 scenarios, 2 cited, blanket. Access requirements in progress 2026-09-11. Its settings-behaviour scenarios stay open under this task. + - Spec written: `tests/e2e/admin-settings-api.spec.ts`, `tests/e2e/admin-settings-dashboard-effects.spec.ts`, `tests/e2e/admin-settings-groups.spec.ts`, `tests/e2e/admin-settings-ui.spec.ts` (helper `tests/e2e/support/adminSettings.ts`), 58 scenarios cited, 13 excluded with a reason, blanket removed, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/allowed-websites-list.spec.ts` (REQ-ASET-021: the Embed half, a host added with Embed takes an embedded page and refuses a live tile, and the upgrade merge of the per-feature lists, run through `occ maintenance:repair`), 2 scenarios cited (new), admin-settings now 62 of 75 cited, 13 excluded with a reason, 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/admin-settings-stored-rows.spec.ts` (helpers `tests/e2e/support/adminSettingRows.ts`, `tests/e2e/support/emptyLevelDashboard.ts`: six scenarios whose GIVEN is a stored row no endpoint writes, arranged in `launchpad_admin_settings` through `support/instanceDb.ts` and put back exactly; the fresh-install defaults, the retired `content_storage` row, the missing `allow_user_dashboards` row, the factory default level, the corrupt and the absent `group_order`; six exclusions replaced), 6 scenarios cited (new), admin-settings now 68 of 75 cited, 7 excluded with a reason, not yet run (cloud, 2026-11-25). Expect "Factory default permission (add_only)" to go red: with no `default_permission_level` row `PermissionService::getEffectivePermissionLevel()` falls back to `full`, while `getSettings()` reports `add_only`. + - Run 25 Nov 2026 (sandbox Nextcloud 34.0.6 + MariaDB): `admin-settings-stored-rows.spec.ts` red as expected on "Factory default permission (add_only)", then 6/6 green with the fix (`PermissionService::getEffectivePermissionLevel()` falls back to `add_only`, the factory default `getSettings()` reports). + - Spec written: `tests/e2e/admin-settings-persistence.spec.ts` (REQ-ASET-007: the restart stood in for by a fresh PHP process reading through `AdminSettingsService::getSettings()` plus the stored rows; the app update run for real, `installed_version` lowered to 1.0.0 and `occ upgrade`, with configured settings kept and a setting whose row the old version never stored reading its default; both exclusions replaced), 2 scenarios cited (new), admin-settings now 70 of 75 cited, 5 excluded with a reason, not yet run (cloud, 2026-11-25) + - Spec written: `tests/e2e/admin-settings-db-failure.spec.ts` (REQ-ASET-011: the store's failure stood in for by renaming `launchpad_admin_settings` away through `support/instanceDb.ts` for the length of one test, so the settings queries fail in the database while login and every other table stay up; GET and PUT must answer 500 with a message and no database internals, and none of the PUT may be stored once the table is back; both exclusions replaced), 2 scenarios cited (new), admin-settings now 75 of 78 cited, 3 excluded with a reason (the three `never built` validation scenarios), not yet run (cloud, 2026-11-25). Expect the no-internals check to need a look on an instance with `debug` on: Nextcloud's own 500 page then carries the exception. + - Run 25 Nov 2026 (sandbox Nextcloud 34.0.6 + MariaDB): `admin-settings-persistence.spec.ts` 2/2 green as written. `admin-settings-db-failure.spec.ts`: GET green; PUT answered 400 "Operation failed" (ResponseHelper::error()'s default status), now 500 with the same generic message; 2/2 green. + - Done 25 Nov 2026: every admin-settings spec run live on a sandbox Nextcloud 34.0.6 + MariaDB after #2029, #2031 and #2033: `admin-settings-api` 13/13 (its key list follows getSettings(): `sharingAllowed`, `publicLinksAllowed` and the one object value `leaverHandover` of REQ-SHARE-016, now named in REQ-ASET-001), `admin-settings-ui` 10/10, `admin-settings-groups` + `admin-settings-dashboard-effects` 33/33, `admin-settings-validation` 3/3, `admin-settings-stored-rows` 6/6, `admin-settings-persistence` 2/2, `admin-settings-db-failure` 2/2, `allowed-websites-list` 3/3. The three new guards (validation, factory level, store failure) were each seen red before their fix. `composer check:strict` reds are the inherited ones of development (no new findings, diff-check green). + - Spec written: `tests/e2e/admin-settings-validation.spec.ts` (REQ-ASET-002: the three `never built` invalid-value scenarios, `defaultPermLevel: "super_admin"`, `defaultGridCols` 0, -1 and 25, and `allowUserDash`/`allowMultiDash` given `"maybe"`; each must answer 400 with an `error` message and leave the stored value as it was, with the allowed values written and stored first as the control; the three exclusions replaced), 3 scenarios cited (new), admin-settings now 78 of 78 cited, 0 excluded, not yet run (cloud, 2026-11-25). Expected red: `AdminSettingsService::updateSettings()` stores all three values unchecked and answers 200. + - Run 25 Nov 2026 (sandbox Nextcloud 34.0.6 + MariaDB): `admin-settings-validation.spec.ts` red as expected, then 3/3 green with the fix (`AdminSettingsService::assertValidCoreSettings()` for the level and the columns, `AdminController::firstNonBooleanParam()` for the booleans, before anything is stored); REQ-ASET-002's three scenarios now read MUST. `admin-settings-api.spec.ts` "GET answers exactly the documented keys, flat" is red: `leaverHandover` comes back as a nested object (not touched here). +- [x] 1.2 `admin-roles`: 55 scenarios, 0 cited, blanket. In progress 2026-09-11. + - Spec written: `tests/e2e/admin-roles.spec.ts`, `tests/e2e/admin-roles-enforcement.spec.ts` (helper `tests/e2e/support/roles.ts`), 55 scenarios cited, 0 excluded, blanket removed, not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 43 of 43 green, every listed test run (checked against `playwright test --list`). +- [x] 1.3 `conditional-visibility`: 49 scenarios, 0 cited, blanket. In progress 2026-09-11. + - Spec written: `tests/e2e/conditional-visibility.spec.ts`, `tests/e2e/conditional-visibility-evaluation.spec.ts` (helper `tests/e2e/support/visibilityRules.ts`), 52 scenarios cited, 0 excluded, blanket removed, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/conditional-visibility-evaluation.spec.ts` (stale midnight anchor re-pointed to the renamed scenario, both halves of the wrap asserted; the 12 group, attribute and combination tests now assert their server verdict inline, which gate 19 read as no-assertion), 13 scenarios cited, 0 excluded, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/conditional-visibility.spec.ts` (the cascade-delete control now asserts the exact 404 of a deleted dashboard instead of any status from 400 up), 55 of 55 scenarios cited, 0 excluded, not yet run (cloud, 2026-11-24) + - Done 25 Nov 2026: `conditional-visibility.spec.ts` + `conditional-visibility-evaluation.spec.ts` 50/50 green live on a sandbox Nextcloud 34.0.6 + MariaDB (after #1966). +- [x] 1.4 `permissions`: 42 scenarios, 0 cited, blanket. In progress 2026-09-11, with `admin-roles` and the access requirements of `admin-settings`. + - Spec written: `tests/e2e/permissions.spec.ts` (new) and `tests/e2e/dashboard-permission-levels.spec.ts` (tightened), 40 scenarios cited, 2 excluded with a reason, blanket removed, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/permissions-admin-default.spec.ts` (REQ-PERM-008 "No template, no dashboard level, fallback to admin default": the level emptied in the row, the owner keeps a compulsory widget and may add under add_only, and is refused the add once the admin default is view_only; the exclusion replaced), 1 scenario cited (new), permissions now 41 of 42 cited, 1 excluded with a reason, not yet run (cloud, 2026-11-25) + - Spec written: `tests/e2e/permissions-compulsory-indicator.spec.ts` (REQ-PERM-004 "Compulsory widget visual indicator": a member's add_only copy of the shipped `mijn-werkdag` template; in edit mode each compulsory widget must show a lock or Required marker, the non-compulsory control must not, and in view mode none may; the exclusion replaced), 1 scenario cited (new), permissions now 42 of 42 cited, 0 excluded, not yet run (cloud, 2026-11-25). Expected red: `WidgetWrapper.vue` renders no marker for a compulsory placement. + - Done 25 Nov 2026: `permissions.spec.ts`, `dashboard-permission-levels.spec.ts`, `permissions-admin-default.spec.ts`, `permissions-compulsory-indicator.spec.ts` 31/31 green live on a sandbox Nextcloud 34.0.6 + MariaDB. The compulsory indicator (REQ-PERM-004, `never built`) was red as its spec predicted and is built in this PR: a lock beside the widget menu in edit mode only. +- [x] 1.5 `dashboard-public-share`: 38 scenarios, 25 cited. In progress 2026-09-11. + - Spec written: `tests/e2e/public-start-page-admin.spec.ts`, `tests/e2e/ci/public-share-view-count.spec.ts`, 31 scenarios cited, 14 excluded with a reason, requirement-level excludes replaced per scenario, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/public-start-page.spec.ts` (REQ-PSHR-012, synced in #1765: the start-page dashboard carries an Opening hours text widget with a Markdown list, and a signed-out visitor must see two `li` items and an `em`, not the raw markers), 33 of 47 scenarios cited, 14 excluded with a reason, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/public-start-page-default-app.spec.ts` (REQ-PSP-003: the default-app claim on install or upgrade, staged with `occ maintenance:repair`, and the admin switch through the page, with `defaultapp` read and written by `occ config:system`; both exclusions replaced), 2 scenarios cited (new), dashboard-public-share now 35 of 47 cited, 12 excluded with a reason, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/ci/public-share.spec.ts` (REQ-PSHR-003/004: the unissued and the revoked token now assert the exact 404 instead of "not 200", the revoke asserts its 204 instead of any 2xx, and a second DELETE of the same id must answer 204, which holds only while the soft-revoked row still exists, for "AND NOT hard-delete the row"), 4 scenarios cited (re-tightened), dashboard-public-share 35 of 47 cited, 12 excluded with a reason, 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/public-share-client-ip.spec.ts` (REQ-PSHR-007/009: for the length of the file `trusted_proxies` trusts the loopback and private ranges the runner comes from, so each request names its own client address in `X-Forwarded-For`; renders from two addresses counted separately, a render 65 s after the last counting again, and the unlock throttle spent on fresh 198.18.0.0/15 addresses, reset with `occ security:bruteforce:reset` afterwards; six exclusions replaced), 6 scenarios cited (new), dashboard-public-share now 41 of 47 cited, 6 excluded with a reason, not yet run (cloud, 2026-11-25). The throttle tests take minutes because Nextcloud sleeps each brute-force-protected request by the address's delay. Expect the 11th-attempt 429 and the 60 s reset to be checked closely: `sleepDelayOrThrowOnMax` counts attempts over 30 minutes, not 60 s. + - Done 25 Nov 2026 on a sandbox Nextcloud 34.0.6 + MariaDB with Redis as memcache: `public-share-client-ip` 5/5, `public-start-page` + `public-start-page-admin` + `public-start-page-default-app` 8/8, `ci/public-share` + `ci/public-share-view-count` 3/3. Found: the 429 on the eleventh failed unlock came from Nextcloud's throttle with no `Retry-After` (REQ-PSHR-009); `RetryAfterMiddleware` adds it from the throttle delay. Environment needs: a memcache (without one the 60 s render debounce cannot hold and two renders count) and the sharee account `recipient` (`LAUNCHPAD_E2E_SHAREE`). +- [x] 1.6 `dashboard-sharing`: 34 scenarios, 10 cited. In progress 2026-09-11. Supersedes `add-dashboard-sharing-e2e-coverage`. + - Spec written: `tests/e2e/ci/dashboard-share-access.spec.ts`, `tests/e2e/ci/dashboard-share-notifications.spec.ts`, `tests/e2e/ci/dashboard-share-user-deletion.spec.ts`, `tests/e2e/dashboard-sharing-limits.spec.ts` (helpers `tests/e2e/support/shareApi.ts`, `tests/e2e/support/notifications.ts`), 37 scenarios cited, 1 excluded with a reason, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/ci/dashboard-share-access.spec.ts` (after `DELETE /api/sharees/user/bob`, bob's reads of dashboards 5 and 7 now assert REQ-SHARE-003's exact 403 instead of "not 200"), 38 of 39 scenarios cited, 1 excluded with a reason, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/dashboard-sharing.spec.ts` (four annotations that matched no scenario heading removed; its four UI tests remain the steps of the cited browser-flow scenario), 38 of 39 scenarios cited, 1 excluded with a reason, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/sharing-policy.spec.ts` (REQ-SHARE-016 "No setting": with the handover cleared and the leaver given a manager, deleting the leaver hands the dashboard with a `full` share to that recipient, not the manager, and deletes the one with only a `view_only` share, per REQ-SHARE-012), 1 scenario cited (new), dashboard-sharing now 44 of 45 cited, 1 excluded with a reason, 0 uncited, not yet run (cloud, 2026-11-25) + - Spec written: `tests/e2e/dashboard-sharing-notifier.spec.ts` ("Unknown subject throws": a notification built through the instance's own `IManager` and handed to the installed `Notifier`, resolved from the server container, with a `dashboard_shared` control that must render; the exclusion replaced), 1 scenario cited (new), dashboard-sharing now 45 of 45 cited, 0 excluded, not yet run (cloud, 2026-11-25) + - Done 25 Nov 2026 on a sandbox Nextcloud 34.0.6 + MariaDB: `dashboard-sharing`, `dashboard-sharing-limits`, `dashboard-sharing-notifier`, `sharing-policy` 14/14. `dashboard-sharing-limits` "a member outside the sharing groups" expected a picker that offers nobody; since sharing-policy-board-sync the tab shows "Your administrator does not allow you to share dashboards" and no picker, which meets "he cannot add a share"; the test asserts that now. +- [x] 1.7 `role-feature-permissions`: 27 scenarios, 0 cited. Queued 2026-09-11, after the permissions PR. + - Spec written: `tests/e2e/role-feature-permissions.spec.ts` (helpers in `tests/e2e/fixtures/role-feature-permissions.ts`), 27 scenarios cited, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/role-feature-permissions-upgrade.spec.ts` (REQ-RFP-011: the two upgrade scenarios, staged with `occ maintenance:repair` against the old shipped `default` and `hrm` rules; both exclusions replaced), 2 scenarios cited (new), role-feature-permissions now 30 of 31 cited, 1 excluded with a reason, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/role-feature-permissions-fresh-install.spec.ts` (REQ-RFP-011 "A fresh install lets every user add a LaunchPad widget": every rule deleted through the admin API, then `occ maintenance:repair` runs `SeedRolePermissions` as an install does; a user in no group adds a `text` widget (201) and is refused `notes` (403) under the seeded `default` rule; the exclusion replaced), 1 scenario cited (new), role-feature-permissions now 31 of 31 cited, 0 excluded, not yet run (cloud, 2026-11-24) + - Done 25 Nov 2026 on a sandbox Nextcloud 34.0.6 + MariaDB: `role-feature-permissions`, `role-feature-permissions-fresh-install`, `role-feature-permissions-upgrade` 31/31. - [x] 1.8 `launchpad-enterprise-security-access`: 15 scenarios, 0 cited, blanket. Done 2026-09-11: the blanket is replaced by 15 per-scenario verdicts, all `never built`. `launchpad_security_access` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`). ## 2. Tier 1, data integrity 11 specs, 341 scenarios. -- [ ] 2.1 `dashboard-bulk-operations`: 50 scenarios, 0 cited, blanket. -- [ ] 2.2 `resource-uploads`: 46 scenarios, 0 cited, blanket. -- [ ] 2.3 `dashboard-versioning`: 38 scenarios, 0 cited, blanket. -- [ ] 2.4 `orphaned-data-cleanup`: 36 scenarios, 0 cited, blanket. -- [ ] 2.5 `dashboard-cascade-events`: 35 scenarios, 1 cited, blanket. -- [ ] 2.6 `dashboard-locking`: 29 scenarios, 0 cited, blanket. -- [ ] 2.7 `dashboard-metadata-fields`: 28 scenarios, 0 cited, blanket. -- [ ] 2.8 `dashboard-quota-limits`: 24 scenarios, 0 cited, blanket. -- [ ] 2.9 `legacy-widget-bridge`: 21 scenarios, 0 cited, blanket. +- [x] 2.1 `dashboard-bulk-operations`: 50 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/dashboard-bulk-operations.spec.ts, tests/e2e/dashboard-bulk-operations-ui.spec.ts, 44 scenarios cited, not yet run (cloud, 2026-11-19). 6 excluded with a reason. + - Run 19 Nov (live pass, NC 34.0.6 + OpenRegister 2.2.0-dev): `dashboard-bulk-operations.spec.ts` green after the non-admin refusal was aligned with the framework (Nextcloud's admin-setting check answers 403 before LaunchPad's message; spec scenario amended). `dashboard-bulk-operations-ui.spec.ts`: the header-checkbox test does not find its seeded rows in the bulk table; open. + - Spec written: tests/e2e/dashboard-bulk-operations.spec.ts, tests/e2e/dashboard-bulk-operations-ui.spec.ts, 44 scenarios cited, 6 excluded, 0 uncited (re-measured against the spec on development), not yet run (cloud, 2026-11-24). No spec change: the header-checkbox red was the panel, not the test. `DashboardBulkOperations.vue` read `/api/dashboards/visible` as a bare list while it answers `{items, quota}`, so the table stayed empty; 23d58d30 (21 Nov) reads the envelope. The UI file needs a rerun on development after that commit. + - Done 25 Nov 2026 on a sandbox Nextcloud 34.0.6 + MariaDB: `dashboard-bulk-operations`, `dashboard-bulk-operations-ui` 39/39. +- [x] 2.2 `resource-uploads`: 46 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/resource-uploads.spec.ts, 37 scenarios cited, not yet run (cloud, 2026-11-19). 7 excluded with a reason. + - Run 19 Nov: 33 of 37 green. Open, decision: the spec wants `{status:'error', error:'forbidden'}` for a non-admin and 403 for an anonymous caller, but `#[AuthorizedAdminSetting]` lets Nextcloud answer first (403 with its own body, 401 for anonymous). + - Run 20 Nov on development with #1444-#1447 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev): 38 of 38 green. The refusal cases follow Nextcloud's 401/403 on admin routes (#1446). +- [x] 2.3 `dashboard-versioning`: 38 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/dashboard-versioning.spec.ts, tests/e2e/dashboard-versioning-ui.spec.ts, 29 scenarios cited, not yet run (cloud, 2026-11-19). 14 excluded with a reason. + - Run 19 Nov: 2 app defects fixed (#1430: restore of calculatedFields; seeded widgets now cleared by the spec). Open, decisions: REQ-VERS-002..005 say owner and admin, `lib/actions.seed.json` grants `dashboard-version.*` to admin only; the scenarios "Automatic snapshot on PUT" (state before the update) and "Snapshot captures full state" (the new metadata as persisted) contradict each other; the code takes the state after. + - Run 20 Nov: dashboard-versioning-ui 4 of 4 green; dashboard-versioning 21 of 22, the red "restoring the pre-restore version" is fixed in #1456 and waits for the rerun. + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 26 of 26 green, every listed test run (checked against `playwright test --list`). + - Spec written: tests/e2e/dashboard-versioning-notes.spec.ts, 2 scenarios cited ("Several changes at once", "Intranet updated from its template", added to the spec by the archived change version-change-notes after the green run), not yet run (cloud, 2026-11-24). The spec now counts 46 scenarios: 32 cited, 14 excluded. Expect "Several changes at once" to go red: `SnapshotChangeDescriber` names the dashboard's own changes before widget changes, so the same three changes read "Columns from 8 to 12 and 2 more changes" (its unit test pins that order); the scenario says "Widget Inbox added and 2 more changes". A product decision, not a test fix. +- [x] 2.4 `orphaned-data-cleanup`: 36 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/orphaned-data-cleanup.spec.ts, 13 scenarios cited, not yet run (cloud, 2026-11-19). 23 excluded with a reason. + - Run 19 Nov: 12 of 13 green. Open, decision: an unauthenticated scan gets Nextcloud's 401, the spec says 403. + - Run 20 Nov on development with #1444-#1447: 10 of 10 green; the unauthenticated scan follows Nextcloud's 401 (#1446). +- [x] 2.5 `dashboard-cascade-events`: 35 scenarios, 1 cited, blanket. + - Spec written: tests/e2e/dashboard-cascade-events.spec.ts, 9 scenarios cited (8 new) (cloud, 2026-11-19). 26 excluded with a reason. + - Run 19 Nov (live pass, NC 34.0.6 + OpenRegister 2.2.0-dev): `dashboard-cascade-events.spec.ts` green, after the spec cleared the seeded default widgets before counting placements and the non-cascade refusal was aligned with REQ-DASH-030 (409; scenario amended). +- [x] 2.6 `dashboard-locking`: 29 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/dashboard-locking.spec.ts, 17 scenarios cited, not yet run (cloud, 2026-11-19). 17 excluded with a reason. + - Run 19 Nov: 3 red. Open, decisions: an administrator may not acquire the lock of another user's dashboard after a force-release (403 lock_forbidden); a colleague's save after the owner deleted the dashboard answers 403, the spec says 404; the lock-cleanup test relies on an import restoring the dashboard under its uuid, which it does not. + - Spec written: tests/e2e/dashboard-locking.spec.ts (the uuid lookup after the preserve-uuid import now reads the `{items, quota}` envelope of `GET /api/dashboards`; it read only `dashboards`/`data`, so both REQ-LOCK-008 cascade tests failed on "the import must restore alice's dashboard" although the import restores it with its owner), 17 scenarios cited, 17 excluded with a reason, not yet run (cloud, 2026-11-24). The other two reds stay open as product decisions: the administrator's acquire after a force-release (403 lock_forbidden) and the colleague's save after deletion (403 from the permission check before the existence check, the spec says "Dashboard not found"). + - Done 25 Nov 2026 on a sandbox Nextcloud 34.0.6 + MariaDB: `dashboard-locking` green in full, including the two former decision points (the administrator acquires after a force-release; a colleague's save after deletion answers 404 "Dashboard not found"). +- [x] 2.7 `dashboard-metadata-fields`: 28 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/dashboard-metadata-fields.spec.ts, 30 scenarios cited, not yet run (cloud, 2026-11-19). 2 excluded with a reason. + - Run 19 Nov: app defect fixed (#1430: a text field was refused by the database). Open, decision: `dashboard-metadata.set-metadata` is admin-only in `lib/actions.seed.json`, the spec lets the owner write values. + - Run 20-21 Nov on development (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 30 of 30 green. The owner writes metadata values since #1444 (owner actions), and #1456 fixed the empty object, the dot-form list filter and the switcher filter. +- [x] 2.8 `dashboard-quota-limits`: 24 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/dashboard-quota-limits.spec.ts, 20 scenarios cited, not yet run (cloud, 2026-11-19). 4 excluded with a reason. + - Run 19 Nov: 1 red. Open, decision: a non-admin adding a LaunchPad widget gets 403 because the shipped default widget rights (`SeedRolePermissions`, group `default`) allow only activity and recommendations. + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 20 of 20 green, every listed test run (checked against `playwright test --list`). +- [x] 2.9 `legacy-widget-bridge`: 21 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/legacy-widget-bridge.spec.ts, 4 scenarios cited, not yet run (cloud, 2026-11-19). 17 excluded with a reason. + - Run 20-21 Nov on development (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 3 of 3 green. - [ ] 2.10 `launchpad-compliance-audit-panel`: 18 scenarios, 0 cited, blanket. -- [ ] 2.11 `dashboard-acknowledgements`: 16 scenarios, 3 cited. + - Spec written: openspec/specs/launchpad-compliance-audit-panel/spec.md (no e2e file; never built), 0 scenarios cited, not yet run (cloud, 2026-11-19). 18 excluded as never built. +- [x] 2.11 `dashboard-acknowledgements`: 16 scenarios, 3 cited. + - Spec written: tests/e2e/dashboard-acknowledgements.spec.ts, tests/e2e/dashboard-acknowledgements-template.spec.ts, tests/e2e/dashboard-acknowledgements-ask.spec.ts, 22 scenarios cited, not yet run (cloud, 2026-11-19). 2 excluded with a reason. + - Spec written: tests/e2e/dashboard-acknowledgements.spec.ts (the report test follows the Read confirmations dialog of #1749, whose `ack-count`/`pending-count` it asserted are gone: it now reads the summary, the bar, the status badges, the Not confirmed yet filter and the department column; it also cites the two delta scenarios of the open change `read-receipts-dialog`), 16 scenarios cited in this file (2 new), not yet run (cloud, 2026-11-24) + - Recount (cloud, 2026-11-24, gate-19 checker on development): the spec now has 27 scenarios after #1772 synced the archived changes in; 25 cited across the three files above, 2 excluded with a reason, 0 uncited. No new spec needed; the three files wait for a run. + - Done 25 Nov 2026 on a sandbox Nextcloud 34.0.6 + MariaDB: `dashboard-acknowledgements`, `dashboard-acknowledgements-template`, `dashboard-acknowledgements-ask` green (with `dashboard-locking`: 42/42). ## 3. Tier 2, core surfaces 19 specs, 823 scenarios. - [ ] 3.1 `dashboards`: 167 scenarios, 0 cited, blanket. The largest spec. Split it by requirement across several PRs. + - Spec written: `tests/e2e/dashboards-crud.spec.ts`, `dashboards-group-shared.spec.ts`, `dashboards-resolution.spec.ts`, `dashboards-fork.spec.ts`, `dashboards-tree.spec.ts`, `dashboards-tree-ui.spec.ts`, `dashboards-publication.spec.ts`, `dashboards-personal-layer.spec.ts`, `dashboards-group-admin.spec.ts`, `dashboards-look.spec.ts`, `dashboards-api-contract.spec.ts` (helpers `support/dashboardsSpec.ts`, `support/dashboardHierarchy.ts`), 162 scenarios cited (fixme tests for suspected defects, see the PR), 26 excluded, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/dashboards-refusals-and-guards.spec.ts` (new, non-serial), `dashboards-crud.spec.ts`, `dashboards-tree.spec.ts`, `dashboards-group-shared.spec.ts`, `dashboards-group-admin.spec.ts`, 7 scenarios cited that were `test.fixme`, which gate 19 does not count: 3 expected green because the product changed (delete-another-users-dashboard and user-cannot-delete-another-users-dashboard-subtree now answer 403, update-grid-columns-on-a-dashboard-with-existing-widgets now stores 6 without reflow), 4 expected red (activate-another-users-dashboard answers 400, duplicate-dashboard-names-allowed is refused by the slug check, the last-in-group guard loses its reason in the API body and so in the toast), 2 excluded as never built (create-a-dashboard-with-invalid-grid-columns, name-length-validation: the create path validates neither), dashboards 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/dashboards-group-serialisation.spec.ts` (new, non-serial), `tests/e2e/dashboards-group-shared.spec.ts`, 1 scenario now runs for the clause that had only a `test.fixme` behind it (group-shared-dashboard-serialisation-includes-groupid on the two group-scoped reads, GET and list, as the admin and as a member), expected red until the product changes (DashboardApiController::getGroup() and ::listGroup() answer Dashboard::toViewerArray(), which unsets `groupId`), dashboards 0 uncited, 0 `test.fixme` left, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/dashboard-period-and-download.spec.ts` (new, non-serial), 6 scenarios cited, 0 excluded, not yet run (cloud, 2026-11-25). They are the `dashboards` delta of the open change dashboard-period-and-download, which is built (#1846) and which gate 19 reads on any PR touching that change; `dashboard-download.spec.ts` anchored to the spec path without a slug and so counted for none. a-view-only-group-dashboard is expected red: DashboardPageHeader::kindLabel() returns '' for a group dashboard, so "Groepsdashboard van {group}" never shows. The OpenRegister read is answered by the spec, so the quarter tests check that LaunchPad puts the period on the query, not OpenRegister's count. `openspec/specs/dashboards` itself: 0 uncited + - Spec written: `tests/e2e/dashboard-edit-bar.spec.ts`, 4 scenarios cited in the test bodies (they were cited only in the file header) and 2 strengthened (already counted). columns-change-the-grid-and-are-kept never looked at the grid: the GIVEN of 12 columns is now set and required (stored, pressed, and GridStack's live column count at 1600 px), choosing 8 must leave GridStack at 8 columns as well as pressed and stored, and a reload must still render 8. the-versions-tab-lists-the-saved-versions only required the panel to be visible: two noted versions are saved first, and the tab must list every stored version newest first with only the top row marked Current version, offer Save this version now, and enable Restore this version for each older row but not the current one. 0 excluded, not yet run (cloud, 2026-11-25) - [ ] 3.2 `widgets`: 110 scenarios, 0 cited, blanket. Split it by requirement across several PRs. + - Spec written: `tests/e2e/widgets-placements-api.spec.ts`, `widgets-rendering.spec.ts`, `widgets-picker.spec.ts`, `widgets-context-menu-contract.spec.ts`, `widgets-nc-widget.spec.ts`, `widgets-tile-type.spec.ts`, `widgets-canvas-search.spec.ts`, `widgets-reload-interval.spec.ts` (helpers `support/widgets.ts`, `support/widgetPlacements.ts`), 99 scenarios cited (12 tests `test.fixme` for suspected defects, see the PR), 21 excluded, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/widgets-style-and-render.spec.ts` (new, non-serial), `widgets-placements-api.spec.ts`, `widgets-picker.spec.ts`, `widgets-rendering.spec.ts`, 5 scenarios cited that were `test.fixme`, which gate 19 does not count: 4 expected green because the product changed (remove-widget-cascade-deletes-conditional-rules: WidgetPlacementMapper::delete() now deletes the rules; remove-a-compulsory-widget-without-full-permission: the refusal now names compulsory widgets; backdrop-click-closes-without-submit: CnAddWidgetModal now sets closeOnClickOutside; conditional-widget-evaluated-at-render-time: the dashboard read now evaluates the rules, asserted for a view-only viewer since REQ-VIS-013 gives editors the hidden widget dimmed), 1 expected red (style-editor-supports-background-and-border-options: the style editor shows only title, background colour and icon), 2 excluded as never built (add-widget-with-invalid-coordinates: freeSpot() relocates; reorder-widgets: no write path renumbers sort_order), widgets 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/widgets-nc-widget.spec.ts`, `tests/e2e/widgets-context-menu-contract.spec.ts`, 3 scenarios now run that had only a `test.fixme` behind them (gate 19 counted them through the file-header citation list, so no test of theirs ever executed; both files are non-serial, so they run in place), all expected red until the product changes (callback-registers-late-within-the-polling-window: CnNcWidgetWidget resolves the native callback once at mount and has no 200 ms poll; horizontal-mode-card-rendering: the item icon is 32 px in both modes, not 44 px; popover-stays-within-viewport-on-bottom-edge: useGridManager clamps with a fixed 245 px menu height while the menu now has six items, about 277 px), widgets 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/widgets-picker-board-sync.spec.ts` (new, non-serial), 4 scenarios cited, 0 excluded, not yet run (cloud, 2026-11-25). They are the `widgets` delta of the open change widget-picker-board-sync, which gate 19 counts as `widgets::<slug>` (open-the-picker, filter-by-kind, place-an-app-tile, embedded-page-not-allowed), all expected red until it is built: the picker has no kind column, no Cancel / Add widget footer and no "From other Nextcloud apps" heading, places on click, and leaves out a type the role may not add instead of showing it grey. widgets 0 uncited + - Spec written: `tests/e2e/section-heading-widget.spec.ts` (a-section-heading-heads-a-group, cited only in the file header and seeded through the API, so the scenario's WHEN, an editor adding the heading in edit mode, never ran: the test now adds it through Edit, Add widget in the edit bar, the Section heading picker entry and its Heading and Explanation fields, requires the stored content, the line below the heading, the rule under both, the full width, and no card: the wrapper has no border, a transparent background and no title), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-25) - [ ] 3.3 `admin-templates`: 86 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/admin-templates-crud.spec.ts`, `admin-templates-distribution.spec.ts`, `admin-templates-gallery.spec.ts`, `admin-templates-resync.spec.ts`, `admin-templates-shipped.spec.ts`, `admin-templates-ui.spec.ts` (helper `support/adminTemplates.ts`), 100 scenarios cited (10 as `test.fixme` for suspected defects, see the PR), 13 excluded, not yet run (cloud, 2026-11-19) + - Run 20 Nov: admin-templates-gallery 15 of 15 green, with the gallery following the user's groups (#1447); the other five files wait for the rerun. + - Spec written: `tests/e2e/admin-templates-template-widgets.spec.ts` (new), `tests/e2e/admin-templates-group-picker.spec.ts` (new), fixme tests removed from `admin-templates-crud.spec.ts`, `-distribution`, `-resync`, `-shipped`, `-ui`, 7 scenarios cited (add-widget-to-template, remove-widget-from-template, update-template-widget-layout, admin-updates-template-after-distribution, template-widget-removed-by-admin-is-removed-under-merge, group-selection-in-template-editor, an-administrator-adds-the-shipped-template-and-gives-it-to-a-group: they were `test.fixme`, which gate 19 does not count, and now run in non-serial files and are expected red until the admin may write a template's placements and the editor offers the Nextcloud groups), 3 excluded as never built (create-template-with-invalid-permission-level, template-list-includes-widget-placement-count, configure-template-grid-layout), admin-templates 99 cited, 16 excluded, 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/admin-templates-resync-async.spec.ts` (new), 1 scenario cited (large-groups-apply-asynchronously: its exclusion said the instance cannot hold more than 50 copies or run TemplateResyncJob on demand; 51 members of one group each open LaunchPad once, and the job runs through `occ background-job:execute --force-execute`, so it is removed). The real re-sync must answer the accepted envelope and change no copy, the job must be queued for this template, and after it runs every copy holds the template layout and every member has a notice. 0 excluded, not yet run (cloud, 2026-11-25) - [ ] 3.4 `grid-layout`: 56 scenarios, 16 cited. + - Spec written: `tests/e2e/grid-layout-drag-resize.spec.ts`, `grid-layout-keyboard.spec.ts`, `grid-layout-placement.spec.ts`, `grid-layout-rendering.spec.ts` (helper `support/ownDashboard.ts`), 56 scenarios cited in total (fixme tests for suspected defects, see the PR), 8 excluded, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/responsive-grid-breakpoints.spec.ts` (new scenario app-tiles-four-to-a-row-on-a-phone from the four-column phone step; the one-column phone asserts, cited by a scenario that no longer exists, now read four columns), 2 scenarios cited (app-tiles-four-to-a-row-on-a-phone, below-smallest-breakpoint, which was cited by a 1600 px test), not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/widget-collision-placement.spec.ts` (four citations of slugs no grid-layout scenario carries removed; the occupied-grid test now asserts the bottom-append rule, that no existing widget moves, instead of the retired push-down), 0 scenarios cited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/grid-layout-accessible-name.spec.ts` (new), `tests/e2e/grid-layout-keyboard.spec.ts`, 2 scenarios cited (screen-reader-announces-widget-positions, screen-reader-announces-the-widget: they were `test.fixme`, which gate 19 does not count, and now run and are expected red until the grid item's accessible name uses the widget title), 2 excluded as never built (keyboard-navigation-between-widgets, keyboard-widget-movement-in-edit-mode: view mode has no tab stops and Ctrl+Arrow is no binding; movement shipped as REQ-GRID-KBD-002), grid-layout 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/grid-layout-defects.spec.ts` (new, non-serial), `tests/e2e/grid-layout-rendering.spec.ts`, `tests/e2e/grid-layout-drag-resize.spec.ts`, 2 scenarios now run that had only a `test.fixme` behind them in the two serial files (gate 19 counted them through the header lists), both expected red (12-col-60px-8px-margin-renders-predictable-height: GridStack draws four rows 240 px tall, content 224 px, not 264 px, possibly the scenario's arithmetic; save-failure-with-retry: updatePlacements() only logs a failed save, no notification and no retry, which the scenario notes is not built), grid-layout 0 uncited, not yet run (cloud, 2026-11-24) - [ ] 3.5 `setup-wizard`: 55 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/setup-wizard.spec.ts`, 42 scenarios cited (14 of them as `test.fixme` for suspected defects, see the PR), 9 excluded, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/setup-wizard.spec.ts`, 10 scenarios now run that had only a `test.fixme` behind them (gate 19 counted them through the file-header citation list, so no test of theirs ever executed), all expected red until the product changes (banner-has-explicit-run-setup-wizard-call-to-action, wizard-starts-at-step-1, endpoint-returns-complete-state-on-fresh-instance: the recommended step is 2 on a fresh instance because steps 3 and 4 report `skipped`; step-3-embeds-demo-data-showcases-admin-component, checked-demos-are-installed-on-next, demo-selection-is-persisted, re-running-does-not-re-install-demo-packages: Step 3 has no checkboxes, the demo tests now take real showcases instead of the example names no showcase carries; step-4-shows-group-selector-for-admin-role, admin-can-select-one-group-for-dashboard-admin-role, only-one-group-can-have-admin-role-per-wizard-run: Step 4 is a stub), setup-wizard now 40 cited, 8 excluded, 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/setup-wizard.spec.ts` (the fresh-instance block: its seven tests skipped themselves whenever `setup_wizard_complete` was already `true`, which is every run after the first on a rig, so there they could not go red; a `beforeEach` now removes the `setup_wizard_complete` and `group_order` rows through `support/adminSettingRows.ts` and requires the state endpoint to read `complete: false` with Step 2 `pending`, and the `group_order` rows are put back after the block), 9 scenarios now run on any instance (already counted), 0 excluded, not yet run (cloud, 2026-11-25) + - Spec written: `tests/e2e/setup-wizard-cli.spec.ts` (new, non-serial), 6 scenarios cited (REQ-WIZ-010, `occ launchpad:setup --config`: accepts-yaml-config-file, validates-yaml-schema, an-old-config-that-still-sets-storagebackend-keeps-working, is-verbose-by-default, skips-optional-steps-if-not-in-config, is-idempotent). The requirement's exclusion said occ cannot be driven from Playwright; support/occ.ts does it, as cli-commands.spec.ts shows, so it is removed. Expected red: Steps 3 to 5 of a full config (SetupCommand prints "skipped (capability pending)" and installs no demo, gives no role, stores no footer), and two validates-yaml-schema inputs (a top-level list and a map as `group_priority_order` are accepted). setup-wizard 0 excluded for REQ-WIZ-010, not yet run (cloud, 2026-11-25) + - Run 25 Nov 2026 (sandbox Nextcloud 34.0.6 + MariaDB): `setup-wizard.spec.ts` green; `setup-wizard-cli.spec.ts` 2 red. Fixed: a YAML list at the top level, or a map as `group_priority_order`, was accepted (`SetupCommand` now uses `array_is_list`). Still red: "a full setup.yaml configures every step": Step 3 installs none of `case-handler`, `de-bron` (installed list empty); not diagnosed (the demos may need data this sandbox lacks). - [ ] 3.6 `footer-customization`: 47 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/footer-customization-api.spec.ts`, `tests/e2e/footer-customization-render.spec.ts` (helper `tests/e2e/support/footerSettings.ts`), 46 scenarios cited (29 of them as `test.fixme` because the footer never renders, see the PR), 1 excluded, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/footer-customization-render-defects.spec.ts` (new), `tests/e2e/footer-customization-override-defects.spec.ts` (new), `tests/e2e/footer-customization-render.spec.ts`, `tests/e2e/footer-customization-api.spec.ts`, 21 scenarios cited (the 21 that were cited only by `test.fixme`, which gate 19 does not count: the 18 that need a footer on the page now run in their own non-serial file and are expected red until something produces `effectiveFooter`, which neither the initial state nor the dashboard payload carries; custom-mode-requires-html, mode-change-clears-stale-html and only-dashboard-owner-can-set-custom-footer run and are expected red until DashboardApiController::update() passes `dashboardFooterMode`/`dashboardFooterHtml` on), 0 excluded as never built (DashboardFooter, the resolver and the override service all exist; they are not wired), footer-customization 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/footer-customization-config-defects.spec.ts` (new, non-serial), `tests/e2e/footer-customization-api.spec.ts`, 1 scenario's AND clause now runs that had only a `test.fixme` behind it (structured-config-schema-validation: the 400 must name the allowed keys), expected red until the product changes (FooterService::assertKnownConfigKeys() names only the unknown key), footer-customization 0 uncited, 0 `test.fixme` left, not yet run (cloud, 2026-11-24) + - Run 25 Nov 2026 (sandbox Nextcloud 34.0.6 + MariaDB): all five footer specs green but one, the expected red "the 400 for an unknown key lists every allowed key" (REQ-FTR-003); `FooterService::assertKnownConfigKeys()` now names the allowed keys and the test is green. Not ticked here: the setup-wizard batch it ran with left two `setup-wizard-cli` reds (task 3.5). - [ ] 3.7 `navigation-editor-org`: 45 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/navigation-editor-org-api.spec.ts`, `tests/e2e/navigation-editor-org-editor.spec.ts`, `tests/e2e/navigation-editor-org-panel.spec.ts` (helper `tests/e2e/support/orgNavigation.ts`), 45 scenarios cited (22 tests are `test.fixme` for suspected defects, see the PR), 0 excluded, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/navigation-editor-org-panel.spec.ts`, `tests/e2e/navigation-editor-org-active-item.spec.ts` (new), `tests/e2e/navigation-editor-org-icon-name.spec.ts` (new) (helpers moved to `support/orgNavigation.ts`), 20 scenarios cited (they were `test.fixme`, which gate 19 does not count, written while the rail could never mount; 37c354f8 made the workspace load the tree and position, so 14 run unchanged; the 5 active-item tests now derive their node urls from the page the workspace settles on, since the scenarios' example pages are redirected to `/` by the client router; icon-name-renders-inline runs and is expected red until a bare icon name renders as text, which dashboard-icons REQ-ICON-009 contradicts), 0 excluded, navigation-editor-org 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/navigation-editor-org-read-defects.spec.ts` (new, non-serial), `tests/e2e/navigation-editor-org-api.spec.ts`, `tests/e2e/navigation-editor-org-editor.spec.ts`, 2 scenarios now run for the case that had only a `test.fixme` behind it: all-users-tree-is-visible-to-every-user with the shipped action matrix, two users in different groups, expected green (lib/actions.seed.json now grants both reads to `@all` and ApplyActionBaseline widens older matrices); group-visibility-multi-select on a node in groups the admin is not in, expected red (OrgNavigationService::filterTreeByUserGroups() has no administrator bypass, so the editor never receives the node and a Save drops it), navigation-editor-org 0 uncited, 0 `test.fixme` left, not yet run (cloud, 2026-11-24) - [ ] 3.8 `tiles`: 38 scenarios, 0 cited. -- [ ] 3.9 `dashboard-language-content`: 35 scenarios, 0 cited, blanket. -- [ ] 3.10 `dashboard-reactions`: 31 scenarios, 0 cited, blanket. -- [ ] 3.11 `tile-quick-search`: 28 scenarios, 8 cited. -- [ ] 3.12 `dashboard-icons`: 25 scenarios, 0 cited, blanket. -- [ ] 3.13 `conditional-visibility-editor`: 23 scenarios, 13 cited. -- [ ] 3.14 `dashboard-kiosk-mode`: 23 scenarios, 0 cited. -- [ ] 3.15 `dashboard-switcher`: 20 scenarios, 11 cited. + - Spec written: `tests/e2e/tiles-api.spec.ts`, `tiles-rendering.spec.ts`, `tiles-launch-target.spec.ts`, `tiles-import-discovery.spec.ts`, 56 scenarios cited in total (fixme tests for suspected defects, see the PR), 13 excluded, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/tiles-api.spec.ts`, 1 scenario cited that was `test.fixme` (place-a-tile-on-a-dashboard, expected green: the scenario's body showed the stored `tile*` names, which the endpoint never read; it now shows the request names the endpoint and frontend use, with a NOTE saying why), 1 excluded as never built (invalid-color-format-rejected: TileUpdater stores colours unchecked), tiles 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/tiles-rendering-defects.spec.ts` (new, non-serial), `tests/e2e/tiles-rendering.spec.ts`, 2 scenarios now run that had only a `test.fixme` behind them in the serial tiles-rendering file (gate 19 counted them through its header list), both expected red (edit-button-visible-in-edit-mode: the top-right button is labelled "Tile menu", "Edit tile" is the item it opens; tile-editor: the editor has no icon-type field, it derives `iconType` from the icon), tiles 0 uncited, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/tiles-rendering-defects.spec.ts` (edit-button-visible-in-edit-mode, which gate 19 grades presence-only under its loose reading: the test now also requires the `aria-label="Edit tile"` attribute the AND clause names, not only an accessible name that reads so), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-25) + - Spec written: `tests/e2e/tiles-icon-only-app-tiles.spec.ts` (new), `tests/e2e/tiles-form-board-sync.spec.ts` (new), `tests/e2e/tiles-add-tiles-dialog.spec.ts` (new), all non-serial (helper `support/appTiles.ts`), 12 scenarios cited, 0 excluded, not yet run (cloud, 2026-11-25). They are the `tiles` deltas of three open changes gate 19 counts as `tiles::<slug>`: icon-only-app-tiles (7), tile-form-board-sync (3), add-tiles-dialog (2). Expected green: six-app-tiles-under-mijn-apps, four-tiles-per-row-on-a-phone, the-source-app-is-missing. Expected red until the changes are built: the live count, the outage dot from the health ping with its time, the colour token and its theme, the board tile form with group, sort order and last check, the Add tiles dialog and the found-on-server list (Grafana also needs the discovery allowance the change does not name yet). tiles 0 uncited +- [x] 3.9 `dashboard-language-content`: 35 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/dashboard-language-content.spec.ts`, `tests/e2e/dashboard-language-content-ui.spec.ts`, 32 scenarios cited (5 as `test.fixme` for suspected defects, see the PR), 7 excluded, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/dashboard-language-content.spec.ts`, `tests/e2e/dashboard-language-content-ui.spec.ts`, 5 scenarios now run that had only a `test.fixme` behind them (gate 19 counted them through the file-header citation list, so no test of theirs ever executed), all expected red until the product changes (exact-language-match, language-part-match-prefix-fallback, reader-in-dutch: resolveLocaleVariant() passes an empty preferred language, so the reader's language is never read; available-languages-list: normaliseLanguageCode() stores `de-DE` as `de`; cannot-delete-the-only-remaining-variant: the primary refusal fires before the last-variant guard, which is unreachable), dashboard-language-content now 32 cited, 7 excluded, 0 uncited, not yet run (cloud, 2026-11-24) + - Done 25 Nov 2026 on a sandbox Nextcloud 34.0.6 + MariaDB: `dashboard-language-content` and `dashboard-language-content-ui` green. +- [x] 3.10 `dashboard-reactions`: 31 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/dashboard-reactions.spec.ts`, `tests/e2e/dashboard-reactions-ui.spec.ts`, 27 scenarios cited, 6 excluded, not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 26 of 26 green, every listed test run (checked against `playwright test --list`). +- [x] 3.11 `tile-quick-search`: 28 scenarios, 8 cited. + - Spec written: tests/e2e/tile-quick-search-widget.spec.ts (new) and tests/e2e/tile-quick-search.spec.ts, 33 scenarios cited, not yet run (cloud, 2026-11-19) + - Run 21 Nov on development after #1476 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): tile-quick-search-widget 24 of 24 and tile-quick-search 9 of 9 green. + - Spec written: `tests/e2e/tile-quick-search-widget.spec.ts` (no-search-widget-placed, which gate 19 graded no-assertion because its checks sat one call down in assertShortcutsInert(): the test now asserts in its own body that the dashboard has no search placement, that both keypresses reached the page undefaulted and that focus did not move), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-25) + - Spec written: `tests/e2e/tile-quick-search-widget.spec.ts` (no-search-widget-placed-renders-no-bar, which gate 19 graded presence-only under its loose reading: every assertion was a zero count, true of any page that renders nothing. The test now also requires no field with the built-in placeholder or the quick-search combobox name, requires BARE's own tile text, and as a control on the same build switches to MAIN and requires each of the same locators to find its one bar before BARE is put back), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-25) +- [x] 3.12 `dashboard-icons`: 25 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/dashboard-icons.spec.ts (new), 21 scenarios cited, not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 15 of 15 green, every listed test run (checked against `playwright test --list`). +- [x] 3.13 `conditional-visibility-editor`: 23 scenarios, 13 cited. + - Spec written: tests/e2e/conditional-visibility-editor.spec.ts, 23 scenarios cited, not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 22 of 22 green, every listed test run (checked against `playwright test --list`). + - Spec written: `tests/e2e/conditional-visibility-editor.spec.ts` (preview-requires-an-authenticated-user, which gate 19 graded presence-only: the anonymous call now must get exactly Nextcloud's 401 `Current user is not logged in`, which only the framework's session check answers before dispatch, instead of any status of 400 or more), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-25) +- [x] 3.14 `dashboard-kiosk-mode`: 23 scenarios, 0 cited. + - Spec written: tests/e2e/dashboard-kiosk-mode.spec.ts (new), 24 scenarios cited, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/dashboard-kiosk-mode.spec.ts`, `tests/e2e/kiosk-position-indicator.spec.ts` (synced in by #1766), 30 scenarios in the spec now, 26 cited, 4 excluded with a reason (playlist read-only marker, shared throttle bucket, refresh clamp with no input, watchdog never built), 0 uncited; not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/kiosk-position-indicator.spec.ts` (one-dashboard, which gate 19 graded presence-only: it now shows the position line renders for the two-dashboard playlist on the same build, requires the band to name the one dashboard, and checks again after one dwell time), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/dashboard-kiosk-mode.spec.ts`, `tests/e2e/kiosk-position-indicator.spec.ts`, 4 scenarios strengthened (already counted). kiosk-flag-does-not-weaken-server-side-authorization: the by-path probe now requires bob's own 404 without the uuid, not only that the flagged and unflagged answers match. cursor-hides-on-idle: also run on the logged-in `?kiosk=1` view and on the public share `/s/{token}?kiosk=1`, in real time: still shown at 5 s, hidden by 10 s, back on movement. rotation-entries-are-fetched-just-in-time: counts only reads of B's own `/kiosk/{token}/dashboards/{uuid}`, none 10 s before its turn, at least one about 5 s before, with A still on screen. the-canteen-screen: the countdown lies within the dwell and goes down, and the line sits bottom right with tabIndex -1. 0 excluded added, not yet run (cloud, 2026-11-25) + - Done 25 Nov 2026 on a sandbox Nextcloud 34.0.6 + MariaDB: `dashboard-kiosk-mode` and `kiosk-position-indicator` green. +- [x] 3.15 `dashboard-switcher`: 20 scenarios, 11 cited. + - Spec written: tests/e2e/dashboard-switcher.spec.ts (new), 19 scenarios cited, not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 15 of 15 green, every listed test run (checked against `playwright test --list`). - [ ] 3.16 `runtime-shell`: 16 scenarios, 5 cited. + - Spec written: tests/e2e/runtime-shell.spec.ts (new), with tests/e2e/support/firstVisit.ts, 20 scenarios cited (11 by the new file), not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/runtime-shell.spec.ts`, `tests/e2e/runtime-shell-canEdit.spec.ts`, `tests/e2e/admin-menu-permissions.spec.ts` (six annotations that matched no scenario heading removed or retargeted: the tour header now names the two current tour scenarios its tests already cite; the two empty-state fixme tests sit under scenarios that carry a reasoned exclusion; the three admin-menu permission slugs never had a scenario in any spec), 28 scenarios cited, 7 excluded with a reason, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/runtime-shell.spec.ts` (REQ-SHELL-001 block), 1 scenario cited (mount-point-present, which before had only a header citation in wave3-runtime-shell.spec.ts and no test behind it; one test pins the served and mounted structure, one `test.fixme` for the `launchpad-app` id the scenario names but nothing renders), 0 excluded; the spec now has 36 scenarios, 29 cited, 7 excluded, 0 uncited; not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/no-buildiq-edit-control.spec.ts` (buildiq-is-enabled, which gate 19 graded presence-only and which passed on any instance without Buildiq: an init script now adds `buildiq` to `_oc_appswebroots` and the test requires the page to see it before it checks that no Buildiq edit button renders), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/runtime-shell.spec.ts` (REQ-SHELL-001 block), 1 scenario now runs for the clause that had only a `test.fixme` behind it (mount-point-present: exactly one `<div id="launchpad-app">` as the child of `#app-workspace`), expected red until the spec or the template changes (templates/index.php and src/main.js use `workspace-vue`), runtime-shell 0 uncited, 0 `test.fixme` behind a scenario (the two empty-state fixmes in runtime-shell-canEdit.spec.ts cite none), not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/no-navigation-panel.spec.ts`, `tests/e2e/page-ground.spec.ts`, `tests/e2e/runtime-shell-canEdit.spec.ts`, `tests/e2e/runtime-shell.spec.ts`, 5 scenarios strengthened (already counted). no-route-renders-the-panel: Reports, Flows and `/admin/templates` must also render the page More menu and no panel, and the content must take nearly the full viewport width, not only start at the left edge. no-destination-is-lost: an administrator test requires every destination plus `admin-settings-link` and no second `admin-settings` entry; the member must not see the admin link. the-grid-on-the-page-ground: a seeded dashboard puts a widget on the grid, so the widget-surface check no longer sits behind `if (widget !== null)`, and the ground must differ from `--color-main-background`. no-active-dashboard-select-control: a second dashboard is seeded and opened, and the one checked row must be its id. canedit-user-sees-full-edit-menu: More itself must offer Edit, Add widget and Documentation. 0 excluded added, not yet run (cloud, 2026-11-25) + - Spec written: `tests/e2e/more-menu.spec.ts`, 4 scenarios cited in the test bodies (the-header-carries-only-more, settings-unfolds-in-place, this-dashboard-ends-in-delete, escape-returns-focus-to-more: REQ-SHELL-013 was synced in by #1772 and cited only in the file header, with tests run as the suite's admin; the three "a member" scenarios now run as a throwaway member on their own dashboard, the header test also requires no Menu, Edit or Add widget button anywhere on the page, Settings must unfold below its toggle and indented with no Admin settings, Escape is pressed after focus has moved into the menu; This dashboard now requires the scenario's own list, Share and Set as default, and no Settings item), expected red on one label (moreMenuItems.js names the share item "Sharing"), runtime-shell 0 uncited, 0 excluded added, not yet run (cloud, 2026-11-25) - [ ] 3.17 `dashboard-deeplinking`: 7 scenarios, 0 cited. -- [ ] 3.18 `default-widget-bundle`: 6 scenarios, 0 cited. + - Written: `tests/e2e/dashboard-deeplinking.spec.ts` cites 6 scenarios (stale slug lands on a dashboard with 200, a slug address opens that dashboard, the path endpoint, one pushState per switch and none on mount, back returns to the previous dashboard, the health route); their exclusions are removed. The route-table order keeps a reasoned exclusion. The NULL-slug half of the path endpoint stays with DashboardApiControllerComputePathTest (a created dashboard always gets a derived slug). Open: the CI run that shows they ran, and the seen-to-fail mutation pass. + - Spec written: `tests/e2e/dashboard-deeplinking.spec.ts` (canonical-path-passed-through-initial-state, which only checked the address the frontend leaves: the test now reads the `deepLinkPath` initial state from the served page and requires `/<slug>`; stale-slug-falls-back-silently now also requires the handed path to be the fallback's, never the stale slug), 2 scenarios cited (already counted), 0 excluded, dashboard-deeplinking 0 uncited, not yet run (cloud, 2026-11-25) + - Spec written: `tests/e2e/dashboard-deeplinking.spec.ts` (stale-slug-falls-back-silently, which only required the handed path not to be the stale slug: the test now asks the seven-step resolver for the account's dashboard through `GET /api/dashboard` and its path endpoint, and requires the `deepLinkPath` handed for the stale slug to be exactly that path), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-25) +- [x] 3.18 `default-widget-bundle`: 6 scenarios, 0 cited. + - Written: `tests/e2e/default-widget-bundle.spec.ts` cites 4 scenarios (the create response and the rendered grid, the preset tile columns, the envelope, the loading shim held on the active-dashboard read). The 2 left keep a reasoned exclusion naming their PHPUnit tests: the seedDefaults flag of the bootstrap (not visible in a browser) and the admin-template override (no e2e yet). Open: the CI run that shows they ran, and the seen-to-fail mutation pass. + - Run 21 Nov on development after #1476 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 4 of 4 green. - [ ] 3.19 `effective-default-marker`: 5 scenarios, 0 cited. + - Written: `tests/e2e/effective-default-marker.spec.ts` cites all 5 scenarios, and their exclusions are removed from the spec. Open: the CI run that shows they ran, and the seen-to-fail mutation pass. + - Spec written: `tests/e2e/effective-default-marker.spec.ts`, 5 scenarios cited, 0 excluded; "the pin wins over a group fallback" no longer skips when no group dashboard is on screen but asserts one is (SeedDefaultDashboard provisions it), so it can fail; not yet run (cloud, 2026-11-24) + - Spec written: `tests/e2e/effective-default-marker.spec.ts` (pin-wins-over-group-fallback, which could not tell "the pin wins" from "the fallback never fires": the test now clears the pin first and requires the group fallback row to carry the one marker, then pins A and requires the marker to leave the group row for A), 1 scenario cited (already counted), 0 excluded, not yet run (cloud, 2026-11-25) ## 4. Tier 3, widgets 24 specs, 817 scenarios. - [ ] 4.1 `text-display-widget`: 90 scenarios, 9 cited. + - Spec written: `tests/e2e/text-display-widget.spec.ts`, `text-display-widget-markdown.spec.ts`, `text-display-widget-table.spec.ts`, `text-display-widget-table-editor.spec.ts`; 1 scenario excluded with a reason, 89 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 90 scenarios, 89 cited, 1 excluded, 0 uncited (gate-19 report mode, no presence-only or assertion-free citations). All four files listed by `playwright test --list` (87 tests), not yet run. - [ ] 4.2 `news-widget`: 58 scenarios, 0 cited, blanket. -- [ ] 4.3 `files-widget`: 57 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/news-widget.spec.ts`, `news-widget-server.spec.ts`, `news-widget-rendering.spec.ts`; 19 scenarios excluded with reasons, 39 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 59 scenarios, 40 cited, 19 excluded, 0 uncited (gate-19 report mode). New since 19 Nov: `nextcloud-dashboard-items-come-from-own-news-widgets`, cited in `news-widget.spec.ts`. All files listed by `playwright test --list`, not yet run. +- [x] 4.3 `files-widget`: 57 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/files-widget.spec.ts`, `files-widget-listing.spec.ts`, `files-widget-navigation.spec.ts`, `files-widget-actions.spec.ts`, `files-widget-access.spec.ts`; 6 scenarios excluded with reasons, 51 scenarios cited, not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 51 of 51 green, every listed test run (checked against `playwright test --list`). + - Recount (cloud, 2026-11-24): 58 scenarios, 52 cited, 6 excluded, 0 uncited. One scenario postdates the green run: `upload-is-off-by-default`, cited in `files-widget-access.spec.ts`, not yet run. - [ ] 4.4 `header-widget`: 56 scenarios, 0 cited. -- [ ] 4.5 `calendar-widget`: 52 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/header-widget.spec.ts`, `header-widget-content.spec.ts`, `header-widget-a11y.spec.ts`, `header-widget-form.spec.ts`; 7 scenarios excluded with reasons, 49 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 54 scenarios, 47 cited, 7 excluded, 0 uncited. The four `height-*` scenarios became `a-preset-sets-the-starting-height` (`header-widget-form.spec.ts`), and `the-banner-fills-its-cell` (`header-widget-content.spec.ts`) is new. All files listed, not yet run. +- [x] 4.5 `calendar-widget`: 52 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/calendar-widget.spec.ts`, `calendar-widget-sources.spec.ts`, `calendar-widget-rendering.spec.ts`, `calendar-widget-config.spec.ts`; 13 scenarios excluded with reasons, 39 scenarios cited, not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 39 of 39 green, every listed test run (checked against `playwright test --list`). - [ ] 4.6 `links-widget`: 52 scenarios, 0 cited. + - Spec written: `tests/e2e/links-widget.spec.ts`, `links-widget-grid-navigation.spec.ts`, `links-widget-config.spec.ts`, `links-widget-editor.spec.ts`; 0 scenarios excluded, 52 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 53 scenarios, 53 cited, 0 excluded, 0 uncited. New since 19 Nov: `nextcloud-dashboard-items-come-from-own-links-widgets`, cited in `links-widget.spec.ts`. All files listed, not yet run. - [ ] 4.7 `video-widget`: 51 scenarios, 0 cited. + - Spec written: `tests/e2e/video-widget.spec.ts`, `video-widget-files.spec.ts` (with `fixtures/tiny.webm`); 18 scenarios excluded with reasons, 33 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 51 scenarios, 35 cited, 16 excluded, 0 uncited. `url-parsing-endpoint-is-available` and `invalid-url-format-is-rejected-early` lost their exclusions when the parse endpoint was built (16300d2e) and are cited in `video-widget.spec.ts`. All files listed, not yet run. + - Spec written: `tests/e2e/video-widget-files.spec.ts` (REQ-VID-003 "Nextcloud file is resolved with ACL": its exclusion said VideoFileService was never built, but it now sits behind `GET /api/widgets/video/{placementId}/file`; the test asks that endpoint as the owner, as a view-only dashboard recipient holding a file share, and as the same recipient after the share is revoked, and fetches each streaming URL it hands out; the stale reasons on `peertube-url-is-preserved-and-validated` and `domain-validation-happens-at-parse-time` corrected, the parse service exists and only the allow-list is unbuilt), 1 scenario cited (new), video-widget now 36 cited, 15 excluded, 0 uncited of 51, not yet run (cloud, 2026-11-25) + - Recount (cloud, 2026-11-25): 51 scenarios, 36 cited, 15 excluded, 0 uncited; no new spec written. The exclusion on `widget-icon-is-visually-distinct` still holds (`img/widgets/video.svg` does not exist), but its reason said the type picker is a plain `<select>` with no icons: corrected to the picker as built (WidgetPickerModal, title and Plus only) and the modal's type icon (`Video`). Tasks 4.1 to 4.12 recounted the same day: every one at 0 uncited, matching the 2026-11-24 recounts. - [ ] 4.8 `link-button-widget`: 50 scenarios, 0 cited. + - Spec written: `tests/e2e/link-button-widget.spec.ts`, `link-button-widget-list.spec.ts`, `link-button-widget-form.spec.ts`; 3 scenarios excluded with reasons, 48 scenarios cited, not yet run (cloud, 2026-11-19) + - Spec written: `tests/e2e/link-button-widget-list.spec.ts` (citation for "An action_id entry is never rendered as a link" corrected to `an-actionid-entry-is-never-rendered-as-a-link`, since gate-19 strips `_`), 49 scenarios cited, 3 excluded with reasons, of 52, not yet run (cloud, 2026-11-24) - [ ] 4.9 `people-widget`: 49 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/people-widget.spec.ts`, `people-widget-config.spec.ts`, `people-widget-rendering.spec.ts`, `people-widget-search.spec.ts`, `people-widget-profile-fields.spec.ts`; 8 scenarios excluded with reasons, 50 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 58 scenarios, 50 cited, 8 excluded, 0 uncited (gate-19 report mode). The line above miscounts the spec: 50 cited plus 8 excluded is 58, not 49. All five files listed by `playwright test --list` (48 tests), not yet run. + - Spec written: `tests/e2e/people-widget-new-colleagues.spec.ts` (new), 2 scenarios cited, 1 excluded with a reason, not yet run (cloud, 2026-11-25). They are the `people-widget` delta of the open change people-new-colleagues, which gate 19 counts as `people-widget::<slug>`: three-new-colleagues-on-the-intranet (an API test, expected green, and a browser test, expected red until the widget renders `selectionMode: 'new'`), no-start-date-field (expected green: the form offers no New colleagues), start-date-from-ldap excluded (no directory server in CI; pinned by `ProfileFieldServiceAccessGoldenTest`). people-widget 0 uncited, deltas included - [ ] 4.10 `image-widget`: 45 scenarios, 8 cited. + - Spec written: `tests/e2e/image-widget-scenarios.spec.ts` (new) with `image-widget.spec.ts` and `image-widget-clickthrough.spec.ts`; 20 scenarios excluded with reasons, 25 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 48 scenarios, 28 cited, 20 excluded, 0 uncited. New since 19 Nov (external-host allow-list, 16d47a87): `allow-listed-external-image-loads`, `external-image-from-a-host-not-on-the-list-is-blocked`, `an-entry-that-is-not-a-host-name-is-refused`, cited in `image-widget-scenarios.spec.ts`. All files listed, not yet run. + - Spec written: `tests/e2e/image-widget-content-form.spec.ts` (new), 1 scenario cited, 0 excluded, not yet run (cloud, 2026-11-25). It is the `image-widget` delta of the open change widget-content-forms-board-sync, which gate 19 counts as `image-widget::alternative-text-is-required`. Expected red until that change's Image form lands: `CnImageWidgetForm.validate()` (nc-vue 2.218.0) only refuses an empty URL. image-widget 0 uncited, deltas included - [ ] 4.11 `menu-widget`: 37 scenarios, 0 cited. + - Spec written: `tests/e2e/menu-widget.spec.ts`, `menu-widget-styles.spec.ts`, `menu-widget-links.spec.ts`; 2 scenarios excluded with reasons, 35 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 37 scenarios, 35 cited, 2 excluded, 0 uncited (gate-19 report mode). All three files listed by `playwright test --list` (35 tests), not yet run. - [ ] 4.12 `quicklinks-widget`: 36 scenarios, 0 cited. + - Spec written: `tests/e2e/quicklinks-widget.spec.ts`, `quicklinks-widget-interaction.spec.ts`, `quicklinks-widget-form.spec.ts`; 0 scenarios excluded, 36 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 36 scenarios, 36 cited, 0 excluded, 0 uncited (gate-19 report mode). All three files listed by `playwright test --list` (35 tests), not yet run. - [ ] 4.13 `divider-widget`: 29 scenarios, 3 cited. -- [ ] 4.14 `clock-weather-widgets`: 21 scenarios, 0 cited. -- [ ] 4.15 `launchpad-spend-analytics-widget`: 21 scenarios, 0 cited, blanket. -- [ ] 4.16 `launchpad-ai-dashboard-assistant`: 18 scenarios, 0 cited, blanket. -- [ ] 4.17 `iframe-embed-widget`: 15 scenarios, 0 cited. -- [ ] 4.18 `launchpad-mobile-remote-access`: 15 scenarios, 0 cited, blanket. -- [ ] 4.19 `live-data-tile-widget`: 15 scenarios, 0 cited. + - Spec written: tests/e2e/divider-widget.spec.ts, 24 scenarios cited, not yet run (cloud, 2026-11-19), 2 excluded with a reason + - Recount (cloud, 2026-11-24): 29 scenarios, 27 cited, 2 excluded, 0 uncited (gate-19 report mode). The spec was kept current by the widget-picker changes (a58030e7, 907dd48e, 22 Nov). Listed by `playwright test --list`, not yet run. + - Spec written: `tests/e2e/divider-widget-discovery.spec.ts` (new; REQ-DIV-001 was cited only by a `spec-coverage.spec.ts` test that read the retired `<select>` picker, so it could not fail on the scenario; those citations are removed), 2 scenarios cited (widget-appears-in-discovery, expected red on the icon the picker never renders for a LaunchPad type; widget-appears-alongside-standard-widgets, which also adds a divider as a plain user), 1 excluded as never built (widget-registration-via-imanager: no `DividerWidgetProvider`, the same verdict REQ-DIV-009 already gives), divider-widget now 26 cited, 3 excluded, 0 uncited of 29, not yet run (cloud, 2026-11-24) + - Recount (cloud, 2026-11-25): 29 scenarios, 26 cited, 3 excluded, 0 uncited; both files listed by `playwright test --list` (26 tests), not yet run. The icon defect `widget-appears-in-discovery` expects red on is still in the code: `Views.vue` `customWidgetTypes` maps each type to `{ type, title }` only, so the registry's `icon: 'Minus'` never reaches `WidgetPickerModal.vue`. +- [x] 4.14 `clock-weather-widgets`: 21 scenarios, 0 cited. + - Spec written: tests/e2e/clock-weather-widgets.spec.ts, 15 scenarios cited, not yet run (cloud, 2026-11-19), 6 excluded with a reason + - Run 21 Nov on development after #1476 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 15 of 16 green; the remaining test is the existing fixme for a requirement that was never built. +- [x] 4.15 `launchpad-spend-analytics-widget`: 21 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/launchpad-spend-analytics-widget.spec.ts`, 9 scenarios cited, 12 excluded with a reason (8 never built, 4 unit-only, CLI or source scan), not yet run (cloud, 2026-11-19). The blanket was wrong: the widget was built in 7d7da1bb and renders today through nc-vue `CnSpendAnalyticsWidget`; the manifest entry it describes was removed in 2cf53831. + - Run 21 Nov on development after #1476 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 8 of 8 green. +- [x] 4.16 `launchpad-ai-dashboard-assistant`: 18 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/launchpad-ai-dashboard-assistant.spec.ts, 8 scenarios cited, 3 excluded with a reason, not yet run (cloud, 2026-11-19) + - Run 21 Nov on development after #1476 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 7 of 7 green. +- [x] 4.17 `iframe-embed-widget`: 15 scenarios, 0 cited. + - Spec written: tests/e2e/iframe-embed-widget.spec.ts, 14 scenarios cited, not yet run (cloud, 2026-11-19), 2 excluded with a reason + - Run 21 Nov on development after #1476 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 12 of 12 green (the allow-list fixes of #1471). +- [x] 4.18 `launchpad-mobile-remote-access`: 15 scenarios, 0 cited, blanket. + - Spec written: `tests/e2e/launchpad-mobile-remote-access.spec.ts`, 1 scenario cited, 14 excluded with a reason (8 never built: `mobileReady` appears in no commit under src, lib, appinfo or templates (`git log --all -S`); 6 need an expired session, an https feed host, or are source scans), not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 1 of 1 green, every listed test run (checked against `playwright test --list`). + - Spec written: `tests/e2e/phone-hidden-widgets-many.spec.ts` (new), 3 scenarios cited: `many-hidden-widgets` (new with REQ-MRA-007, the only uncited one) and `mobile-viewport-hides-non-ready-widgets` and `desktop-viewport-renders-all`, whose "never built" exclusions went stale when `mobileReady` was built for `ai-assistant` (phone-hidden-widgets-named). The other seven stale reasons are rewritten to what is true now. 5 cited (with `pieter-on-his-phone` in `phone-hidden-widgets-named.spec.ts` and the curated-app-list test), 12 excluded with a reason, 0 uncited of 17, not yet run (cloud, 2026-11-24) +- [x] 4.19 `live-data-tile-widget`: 15 scenarios, 0 cited. + - Spec written: tests/e2e/live-data-tile-widget.spec.ts, 14 scenarios cited, not yet run (cloud, 2026-11-19), 4 excluded with a reason + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 15 of 15 green, every listed test run (checked against `playwright test --list`). - [ ] 4.20 `launchpad-meeting-calendar-actions`: 14 scenarios, 0 cited, blanket. -- [ ] 4.21 `label-widget`: 12 scenarios, 11 cited. + - Spec written: none, 0 scenarios cited, 14 excluded as never built, not yet run (cloud, 2026-11-19). The blanket is replaced by 14 per-scenario verdicts. `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`); the existing `calendar` widget reads LaunchPad's own events endpoint, not CalDAV or decidesk. + - Recount (cloud, 2026-11-24): 14 scenarios, 14 excluded, 0 uncited. Still never built: `meeting-actions` is in neither `src/constants/widgetRegistry.js`, `lib/widget-types.json` nor `src/manifest.json`. One correction to the line above: since c1be6d0d and 3b33c019 the `calendar` widget does read Nextcloud's CalDAV calendars, but it is still not this widget and has no decidesk path. +- [x] 4.21 `label-widget`: 12 scenarios, 11 cited. + - Spec written: tests/e2e/label-widget-content-edit.spec.ts, 1 scenarios cited, not yet run (cloud, 2026-11-19) + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 2 of 2 green, every listed test run (checked against `playwright test --list`). - [ ] 4.22 `launchpad-file-access-widget`: 12 scenarios, 0 cited, blanket. -- [ ] 4.23 `container-widget`: 8 scenarios, 0 cited, blanket. + - Spec written: none, 0 scenarios cited, 12 excluded as never built, not yet run (cloud, 2026-11-19). The blanket is replaced by 12 per-scenario verdicts. `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`); opening a file from the existing `files` widget belongs to the files-widget spec. + - Recount (cloud, 2026-11-24): 12 scenarios, 12 excluded, 0 uncited. Still never built: no `file-access` widget type in the registry, `lib/widget-types.json` or the manifest. +- [x] 4.23 `container-widget`: 8 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/container-widget.spec.ts, tests/e2e/container-tile-sorting.spec.ts, 11 scenarios cited, not yet run (cloud, 2026-11-19), 1 excluded with a reason + - Run 21 Nov on development after #1476 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): container-widget 7 of 7 and container-tile-sorting 6 of 6 green. - [ ] 4.24 `nc-dashboard-widget-proxy`: 4 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/nc-dashboard-widget-proxy.spec.ts, 4 scenarios cited, not yet run (cloud, 2026-11-19) + - Recount (cloud, 2026-11-24): 4 scenarios, 4 cited, 0 excluded, 0 uncited. Spec updated with the picker changes of 907dd48e; listed by `playwright test --list`, not yet run. + - Spec written: `tests/e2e/nc-dashboard-widget-proxy.spec.ts` (the "expected RED" note on `keyboard-navigation-works` was stale: nextcloud-vue 2.218.0, the version the lock pins, reads `focusedIndex` in `cardTabIndex()`, so the roving-tabindex assertion should now pass and a red is a regression), 4 scenarios cited, 0 excluded, 0 uncited, listed by `playwright test --list`, not yet run (cloud, 2026-11-25) ## 5. Tier 4, admin, operations and integrations 14 specs, 419 scenarios. - [ ] 5.1 `dashboard-view-analytics`: 65 scenarios, 0 cited, blanket. -- [ ] 5.2 `background-job-feed-refresh`: 56 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/dashboard-view-analytics.spec.ts, 53 scenarios cited, not yet run (cloud, 2026-11-19), 18 excluded with reasons + - Spec written: tests/e2e/dashboard-view-analytics-jobs.spec.ts, 5 more scenarios cited (the salt rotation and four retention/purge scenarios, by running the jobs through occ), 13 excluded with reasons, not yet run (cloud, 2026-11-24) + - Spec written: tests/e2e/dashboard-view-analytics-history.spec.ts (+ tests/e2e/support/instanceDb.ts), 8 more scenarios cited (both table schemas, two days, the salt across days, both period filters, both purge deletions) by seeding and reading rows through PHP on the instance, 5 excluded with reasons, not yet run (cloud, 2026-11-24) + - Spec written: tests/e2e/dashboard-view-analytics-history.spec.ts, 1 more scenario cited (the tile-click salt is the one analytics_dailysalt), 67 cited, 4 excluded with reasons, not yet run (cloud, 2026-11-24) + - Spec written: tests/e2e/dashboard-view-analytics-cache.spec.ts, 2 more scenarios cited (the dedup cache key and its TTL, the hash kept in the cache and out of the views table) by reading the distributed cache on the instance; they skip, saying why, where that cache is per-process. 69 cited, 2 excluded with reasons, not yet run (cloud, 2026-11-24) +- [x] 5.2 `background-job-feed-refresh`: 56 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/background-job-feed-refresh.spec.ts, 6 scenarios cited, not yet run (cloud, 2026-11-19), 50 excluded with reasons + - Run 20 Nov on development with #1444: 6 of 6 green. - [ ] 5.3 `cli-commands`: 53 scenarios, 0 cited, blanket. -- [ ] 5.4 `activity-feed-integration`: 52 scenarios, 0 cited, blanket. -- [ ] 5.5 `nc-unified-search-integration`: 48 scenarios, 0 cited, blanket. -- [ ] 5.6 `confluence-html-import`: 41 scenarios, 0 cited, blanket. -- [ ] 5.7 `prometheus-metrics`: 23 scenarios, 0 cited, blanket. + - Spec written: none (tests/e2e/cli-commands.spec.ts not created), 0 scenarios cited, 60 excluded with reasons, not yet run (cloud, 2026-11-19) + - Spec written: tests/e2e/cli-commands.spec.ts (+ tests/e2e/support/occ.ts), 39 scenarios cited, 21 excluded with reasons, not yet run (cloud, 2026-11-24). The old "Playwright cannot run occ" reason was wrong: the suite already runs occ on the instance. + - Spec written: tests/e2e/cli-commands.spec.ts, 1 more scenario cited (an operator updates the installed template: an older install staged through occ and tests/e2e/support/instanceDb.ts), 40 cited, 20 excluded with reasons, not yet run (cloud, 2026-11-24) + - Spec written: tests/e2e/cli-commands.spec.ts, 1 more scenario cited (pre-existing commands are not broken: launchpad:export and launchpad:import keep their names and options and round-trip a dashboard with its widget), 41 cited, 19 excluded with reasons, not yet run (cloud, 2026-11-25) +- [x] 5.4 `activity-feed-integration`: 52 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/activity-feed-integration.spec.ts, 21 scenarios cited, not yet run (cloud, 2026-11-19), 39 excluded with reasons + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 22 of 22 green, every listed test run (checked against `playwright test --list`). +- [x] 5.5 `nc-unified-search-integration`: 48 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/nc-unified-search-integration.spec.ts, 42 scenarios cited, not yet run (cloud, 2026-11-19), 6 excluded with reasons + - Run 21-22 Nov on development after #1502 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 42 of 42 green, every listed test run (checked against `playwright test --list`). +- [x] 5.6 `confluence-html-import`: 41 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/confluence-html-import.spec.ts, 37 scenarios cited, not yet run (cloud, 2026-11-19), 4 excluded with reasons + - Run 20-21 Nov on development (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 37 of 37 green. +- [x] 5.7 `prometheus-metrics`: 23 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/prometheus-metrics.spec.ts, 15 scenarios cited, not yet run (cloud, 2026-11-19), 10 excluded with reasons + - Run 21 Nov on development after #1476 (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 15 of 15 green. - [ ] 5.8 `launchpad-adopt-or-abstractions`: 20 scenarios, 1 cited. -- [ ] 5.9 `infrastructure-helpers`: 17 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/launchpad-adopt-or-abstractions.spec.ts (+ tests/e2e/support/orWidget.ts), 3 new scenarios cited (4 with manifest-boot.spec.ts), 16 excluded with reasons, not yet run (cloud, 2026-11-19) + - Spec written: tests/e2e/or-absent.spec.ts, 2 more scenarios cited (install and sharing on an OR-less instance, made by disabling openregister/openconnector through occ for the file), 6 cited, 14 excluded with reasons, not yet run (cloud, 2026-11-24) + - Spec written: tests/e2e/launchpad-adopt-or-abstractions-declared.spec.ts, 2 more scenarios cited (the appinfo.xml and composer.json dependency checks, read from the deployed app: info.xml as the instance parses it over OCS `cloud/apps/launchpad` and on disk, composer.json and the class headers under lib/ through tests/e2e/support/occ.ts), 8 cited, 12 excluded with reasons, not yet run (cloud, 2026-11-25) + - Spec written: tests/e2e/launchpad-adopt-or-abstractions-keys.spec.ts, 1 more scenario cited (key list is single-source-of-truth: every AdminSettingKey case named in its docblock, no second key literal in the deployed lib/, read through tests/e2e/support/occ.ts), 9 cited, 11 excluded with reasons, not yet run (cloud, 2026-11-25). EXPECTED RED: AnnouncementService::EDITOR_GROUPS_SETTING repeats 'announcement_editor_groups', and the docblock names 15 of the 35 cases +- [x] 5.9 `infrastructure-helpers`: 17 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/infrastructure-helpers.spec.ts, 14 scenarios cited, 3 excluded with reasons, not yet run (cloud, 2026-11-19) + - Run 20-21 Nov on development (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 14 of 14 green. - [ ] 5.10 `service-health-ping`: 15 scenarios, 0 cited. -- [ ] 5.11 `initial-state-contract`: 11 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/service-health-ping.spec.ts, 14 scenarios cited, not yet run (cloud, 2026-11-19), 1 excluded with reasons + - Spec written: tests/e2e/service-health-ping.spec.ts, the last scenario (background refresh) now cited by running HealthPingRefreshJob through occ, 0 excluded, not yet run (cloud, 2026-11-24) +- [x] 5.11 `initial-state-contract`: 11 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/initial-state-contract.spec.ts, 2 scenarios cited, 9 excluded with reasons, not yet run (cloud, 2026-11-19) + - Run 20-21 Nov on development (Nextcloud 34.0.6, OpenRegister 2.2.0-dev, live pass stack): 4 of 4 green. - [ ] 5.12 `runtime-or-consumption`: 11 scenarios, 0 cited, blanket. + - Spec written: tests/e2e/runtime-or-consumption.spec.ts (+ tests/e2e/support/orWidget.ts), 7 scenarios cited, 4 excluded with reasons, not yet run (cloud, 2026-11-19) + - Spec written: tests/e2e/or-absent.spec.ts, 2 more scenarios cited (boot without OR, the OR-data widget's empty state without OR), 8 cited, 2 excluded with reasons (both never built), not yet run (cloud, 2026-11-24) - [ ] 5.13 `license-header-consistency`: 7 scenarios, 0 cited, blanket. + - Spec written: no spec file, 0 scenarios cited, 7 excluded with reasons, one per requirement; the blanket is gone. Every scenario reads checked-in files or CI behaviour, not a running instance. REQ-LIC-003 does not hold: 12 files under `src/` still name `LaunchPad Contributors` (cloud, 2026-11-19) + - Spec written: tests/e2e/license-header-consistency.spec.ts, 6 scenarios cited (the lib/ and src/ SPDX identifiers, PermissionService.php's PHPDoc and SPDX agreeing, the SPDX copyright of PHP files, the README badge and prose, the licence check failing on an AGPL header in a scratch tree), 1 excluded with reason (reuse lint: no `reuse` tool on the runner or instance), read from the deployed app folder through tests/e2e/support/occ.ts as 5.8 does; not yet run (cloud, 2026-11-25) - [ ] 5.14 `groupfolder-storage-backend`: 0 scenarios, 0 cited. Has no scenarios. Decide whether the spec is still wanted. + - Decided: keep it. The spec is marked `status: withdrawn` and records why the capability was retired (launchpad#87) and what was removed. With no requirements and no scenarios it owes gate-19 nothing; archiving or deleting it is a separate change (cloud, 2026-11-19) + - Spec written: tests/e2e/groupfolder-storage-backend.spec.ts, 1 scenario cited, 1 excluded with reason, not yet run (cloud, 2026-11-24). The spec has since gained REQ-GFSB-011 with 2 scenarios, so it does owe gate-19 now. + - Spec written: tests/e2e/groupfolder-storage-backend.spec.ts, 2 scenarios cited, 0 excluded, not yet run (cloud, 2026-11-24). "No storage commands" now lists the occ commands through tests/e2e/support/occ.ts. ## 6. Close the programme - [ ] 6.1 Re-measure every spec with the same count, and publish the before and after totals in this change. -- [ ] 6.2 Confirm no spec-level `@e2e exclude` remains in `openspec/specs/`. +- [x] 6.2 Confirm no spec-level `@e2e exclude` remains in `openspec/specs/`. + - Confirmed: none of the 109 specs under `openspec/specs/` carries a standalone `@e2e exclude` before its first requirement heading, checked with gate-19's own `_parse_whole_spec_exclusion` (hydra-gates `check_e2e_coverage.py`). The remaining exclusions are per scenario or per requirement, each with a reason. The last scenario of `launchpad-enterprise-security-access` had its exclusion at the end of the file, below Standards & References, where it read as a spec-level note; it now sits under its scenario (15 scenarios, 15 excluded, before and after) (cloud, 2026-11-25) - [ ] 6.3 Archive `add-dashboard-sharing-e2e-coverage` once tier 0 covers it, repointing any citation into it first. diff --git a/openspec/changes/embedded-analytics/design.md b/openspec/changes/embedded-analytics/design.md deleted file mode 100644 index 8d5ccba43..000000000 --- a/openspec/changes/embedded-analytics/design.md +++ /dev/null @@ -1,302 +0,0 @@ -# Design — Embedded Analytics - -## Overview - -LaunchPad widgets are today rendered only for authenticated Nextcloud users with dashboard ACL permission. Three customer classes cannot adopt LaunchPad today: - -1. **Public transparency dashboards**: Municipalities that want to publish live "openstaande WOO-verzoeken" on their public website without exposing Nextcloud. -2. **Partner-facing operational dashboards**: Shared-service organisations running LaunchPad for a consortium of municipalities, embedding each member gemeente's widget slice into the gemeente's internal intranet (avoiding mass Nextcloud account creation). -3. **In-product analytics**: SaaS vendors whose products are built on Conduction's stack, surfacing "your usage this month" inside their customer portal without iframing a full Nextcloud login flow. - -Today's auth boundary (Nextcloud session) is correct for internal organisational consumption but too narrow for these use cases. The change introduces **embed tokens** — signed JWTs that are the sole auth mechanism for embedded views, scoped to a specific widget or dashboard, rate-limited, revocable within 60 seconds, and subject to auditable telemetry. - -## Goals - -- **Flexible form factors**: Support both iframe (drop into any HTML, no JS integration) and JS-SDK (host page controls layout/sizing/events). -- **Security-first**: Signed JWTs, asymmetric crypto (RS256/ES256), no session cookies, no IP allow-lists, no anonymous embeds. Every embed has a verifiable identity that can be revoked and audited. -- **Scope enforcement**: Read-only tokens cannot mutate state even if the frontend is tampered. Filter context can be pinned. Allowed actions are explicitly listed (interact, export, drillDown). -- **Per-tenant theming**: CSS variables let the embed blend into the host page's brand without forking widget code — gemeente's colours on gemeente's intranet, SaaS vendor's colours inside their product. -- **CSP compliance**: Embeds declare host origins upfront; the render route emits `Content-Security-Policy: frame-ancestors` so the host's CSP doesn't block the iframe. -- **Usage telemetry without PII**: Every embed write captures host origin, viewport size, and user-agent family (hashed) for "did this embed get traffic?" answers. NO IP addresses, NO full UAs, NO end-user identifiers. -- **WCAG 2.1 AA compliance**: Public-facing embeds land on municipal websites with legal accessibility obligations (Web Toegankelijkheidsverordening). Build-time axe-core checks catch ~30% of violations; admin UI warns on creation. -- **Incident response**: Token revocation takes effect within 60 seconds across all render workers; a "purge cache" action available to admins gives zero-cache escalation for critical incidents. - -## Non-Goals - -- Per-resource ACL on individual assets (files, tables, records embedded by reference). Embed tokens grant access to the named widget/dashboard; ACLs on downstream entities are enforced by those entities. -- Seamless JWT refresh flows. Tokens are long-lived or non-expiring by default; refresh-token machinery is out of scope v1. -- Custom widget shapes per embed (e.g. "render this widget in 2-column layout"). Theme variables only; layout is the host page's responsibility. -- Simultaneous draft + published versions of a dashboard. Embeds point to the latest published version. -- Semantic drift from the platform-wide token-scope ADR. The JWT scope vocabulary (mode, allowedFilters, allowedActions) mirrors existing OpenConnector patterns. - -## Context - -### User stories from the field - -1. **Public WOO dashboard**: "Our gemeente wants to publish a live widget on our public website that shows outstanding WOO requests without exposing Nextcloud. Citizens should see the list, but not be able to download it." -2. **Partner intranet**: "We run LaunchPad for 8 gemeentes. Each gemeente wants their own dashboard in their internal intranet, but they don't have Nextcloud accounts. We need to embed a widget per gemeente into their own page." -3. **SaaS usage dashboard**: "Our customer portal shows 'your usage this month'. It's built in React and lives on a different domain. We want to embed a LaunchPad widget to replace a custom in-house chart." - -### JWT as the auth boundary - -Nextcloud sessions are user-centric and require a login flow. Embed tokens are widget-centric and are issued by an admin, then handed to a third party (municipal webmaster, partner org, SaaS portal team) for integration. The token is an identity that outlives any user and can be revoked independently of user lifecycle. - -**Why JWTs and not OAuth2 client credentials or other grant flows?** - -- Tokens are issued once and distributed offline (the admin hands the token to the municipal webmaster via email). OAuth would require the webmaster to stand up a server to hold credentials, which is operationally heavy. -- Tokens are read/cached/cached by stateless edge servers. JWTs carry their validity in the token itself; a stateless proxy can verify the signature without a DB call. An opaque token would require a central token-info endpoint. -- Public standards: RFC 7519 (JWT), RFC 7515 (JWS), RFC 7517 (JWK) — widely understood, widely implemented, widely audited. - -### Key rotation - -Multiple active keys are permitted so an org can rotate without breaking in-flight tokens. The key selection uses the `kid` header (RFC 7517). The rotation procedure is: - -1. Create a new signing key, mark it `status: active`. -2. Mark the old key `status: retiring` so new tokens are signed with the new key. -3. Tokens signed by the old key remain valid (the JWK's public key is available) until their expiration. -4. Once all tokens signed by the old key have expired, retire the old key to `status: revoked` (optional archival, not deletion). - -This is the pattern documented by Auth0, Okta, and the OIDC discovery spec. - -### CSP as the framing boundary - -The W3C Content Security Policy Level 3 spec mandates that a frame-ancestor must declare which origins may embed it. We emit `Content-Security-Policy: frame-ancestors <hostOrigins>` (computed from the token's `hostOrigins` list). This prevents a malicious website from tricking a user's browser into displaying our widget while claiming it's from their domain. - -Defence in depth: we also check `Sec-Fetch-Site` and `Referer` headers (Fetch Metadata Request Headers spec) so a browser/proxy that strips CSP headers still cannot spoof the origin. - -**Why explicit-allowlist instead of wildcard?** - -An admin configuring `hostOrigins: ["*"]` negates all framing protection. We reject `*` and require explicit origins per token. This matches the OWASP CSP cheat-sheet's strongest recommendation. - -## Decisions - -### D1: JWT-based tokens, not session cookies or IP allow-lists - -**Decision**: The only auth mechanism is a signed JWT token. No session cookies are issued. No IP allow-lists are supported (they don't work across CDNs and mobile networks anyway). - -**Rationale**: JWTs can be shared offline between organisations and remain valid forever (or until explicit revocation). Session cookies require a login flow. IP allow-lists are fragile and don't work for mobile users. - -**Alternatives considered**: -- OAuth2 client credentials grant. Too heavy for the use case (webmaster should not need to run a secure credential-storage server). -- Anonymous public dashboards (no token). Rejected — every embed must have a verifiable identity for audit and revocation. -- Nextcloud session + embed link. Rejected — user has to log into Nextcloud first; defeats the purpose. - -### D2: Read-only enforcement at the API tier, not the UI - -**Decision**: A token's `scope.mode` (read vs read-with-interactions) is enforced on the API tier. The backend rejects any POST/PUT/PATCH/DELETE when the token is read-only, even if the frontend is tampered. - -**Rationale**: The frontend cannot be trusted to enforce a policy that an attacker can modify. If a municipal website embeds a read-only widget on their public page, they need to know that even if someone patches the JS in DevTools, they cannot coerce a write. - -**Alternatives considered**: -- UI-only enforcement (hide buttons). Rejected — not secure against determined attackers. -- Separate endpoints for read vs write. Rejected — overcomplicates routing; the API already dispatches based on HTTP verb. - -### D3: PostMessage handshake for token injection (JS-SDK), query-parameter fallback (iframe) - -**Decision**: The JS-SDK loads an iframe without a token in the `src` URL, then posts the token to the iframe via `postMessage` after origin verification. The iframe-only form-factor accepts the token as `?token=<jwt>` in the query string for users who can't integrate a JS library. - -**Rationale**: Query-parameter tokens leak into referer headers, browser history, and proxy logs. The postMessage handshake (already used by Stripe Elements, Plaid Link, and Google Identity Services) avoids the leak while keeping the iframe-only path simple for basic usage. - -**Alternatives considered**: -- Always require postMessage. Rejected — too heavy for a one-off embed; some users just want to paste a URL into an `<iframe src>` tag. -- Bearer header injection via Service Worker. Rejected — adds a build step and browser compatibility issues. - -### D4: Rate limiting with 60-second revocation propagation window - -**Decision**: Each token has a `rateLimitPolicy` (requestsPerMinute, burstSize). Revocations are propagated to all render workers within 60 seconds via a short-TTL cache. For higher-assurance incidents, admins can invoke a "purge cache" action to drop the TTL to zero. - -**Rationale**: 60 seconds is short enough to satisfy incident-response timelines (revoke → within 1 minute, no more requests). Caching avoids DB pressure on the render route; a zero-cache option exists for critical incidents. - -**Alternatives considered**: -- Zero-cache revocation (every request hits DB). Rejected — render route throughput would suffer under high traffic. -- Eventually-consistent revocation (background sync, no max TTL). Rejected — too long for incident response. - -### D5: Telemetry captures host origin, viewport bucket, user-agent family — NO IP, NO full UA, NO end-user ID - -**Decision**: Every `embed_usage_event` writes: `hostOrigin` (from Origin header), `viewportSize` (bucketed: small/medium/large, not exact pixels), `userAgent` (browser family + major version + sha256 of full string for fingerprint analysis), `responseStatusCode`, `responseLatencyMs`. NO client IP, NO full user-agent string, NO user identifier. - -**Rationale**: Administrators can answer "did this embed get traffic?" and "is it slow?" without processing personal data. Capturing IP addresses or full UAs would require a legal basis (legitimate interest + DPIA under GDPR/AVG Article 5(1)(c)). - -**Alternatives considered**: -- Full telemetry (IP, full UA, user ID). Rejected — requires legal basis; not proportionate to the business question ("did this embed get used?"). -- No telemetry. Rejected — admins have no way to detect unused embeds or revoke tokens that are not helping. - -### D6: WCAG 2.1 AA compliance with axe-core build-time checks - -**Decision**: The embed render route produces HTML that meets WCAG 2.1 AA success criteria. The build pipeline runs axe-core automated checks on representative widget shapes. The admin UI warns (non-blocking) when creating a token for a widget with known violations. - -**Rationale**: Public-facing embeds on municipal websites have legal accessibility obligations under the Web Toegankelijkheidsverordening and EN 301 549. An embed that fails AA is a regulatory issue, not a UX bug. Automated checks catch ~30% of violations (high false-positive rate, but better than nothing). Manual review is the widget author's responsibility and is documented per-widget. - -**Alternatives considered**: -- No accessibility checks. Rejected — regulatory risk on public-sector websites. -- Hard block on embedding inaccessible widgets. Rejected — too strict; admins may choose to embed anyway and document the workaround. - -## Risks and Mitigations - -| Risk | Mitigation | -|---|---| -| Token leaked into referer header or access log (iframe form-factor) | Query-parameter tokens enforce stricter rate limits and stricter CSP. Admins are warned during token creation that iframe-form tokens are less secure. | -| Host website compromised, embed tokens exfiltrated | Tokens are scoped to a specific widget (subject-id pinning). Attacker cannot widen access to other widgets/dashboards without getting more tokens. Audit log shows which embeds exist. | -| Compromised signing key (private key leaked) | Multiple active keys permitted; old key can be retired immediately. All tokens signed by the old key are revoked. Rotation procedure is automated. | -| Public WOO widget embedded on a website, but municipality accidentally marks it read-with-interactions | Admin creates the token; responsibility is on the admin to choose the right scope. Token metadata includes scope, so audit review can catch mistakes. | -| End-user fingerprinting via user-agent telemetry | User-agent is hashed and only family+major is retained. Not enough to identify an individual. Org-level telemetry kill-switch lets admins disable all event capture. | -| Performance regression: render route adds latency | Render route adds two checks (JWT signature + rate-limit lookup) and writes one event. Both are O(1). JWT verification is fast (standard library, not custom crypto). Rate-limit and revocation lookups hit a local cache (60s TTL) before DB. Expected overhead <10ms. | - -## Seed Data - -### EmbedToken seed objects - -Three realistic scenarios for Netherlands municipalities: - -1. **Public WOO widget** — Gemeente Zeist wants to embed a live "openstaande WOO-verzoeken" widget on their public website (https://www.zeist.nl). - - name: "Gemeente Zeist — WOO intranet" - - description: "Live WOO requests for internal intranet" - - subject: {type: "widget", id: "<woo-widget-uuid>"} - - scope: {mode: "read", allowedFilters: ["status"], allowedActions: []} - - hostOrigins: ["https://intranet.zeist.nl"] - - tokenExpiresAt: null (non-expiring) - - rateLimitPolicy: {requestsPerMinute: 600, burstSize: 60} - -2. **Partner consortium dashboard** — NL Design consortium embed for Gemeente Amsterdam. - - name: "Consortium — Amsterdam operations board" - - description: "Shared-service ops dashboard for AMS gemeente" - - subject: {type: "dashboard", id: "<dashboard-uuid>", filterContext: {gemeente: "Amsterdam"}} - - scope: {mode: "read-with-interactions", allowedFilters: ["periode", "afdeling"], allowedActions: ["interact", "drillDown"]} - - hostOrigins: ["https://intranet.amsterdam.nl"] - - tenantThemeId: "<amsterdam-theme-uuid>" - - tokenExpiresAt: null - - rateLimitPolicy: {requestsPerMinute: 300, burstSize: 30} - -3. **SaaS usage widget** — Conduction customer portal embedding a monthly-usage widget. - - name: "SaaS Portal — Usage widget" - - description: "Customer usage this month (SaaS portal integration)" - - subject: {type: "widget", id: "<usage-widget-uuid>"} - - scope: {mode: "read", allowedFilters: ["month"], allowedActions: []} - - hostOrigins: ["https://portal.example.com", "https://staging-portal.example.com"] - - tenantThemeId: "<saas-vendor-theme-uuid>" - - tokenExpiresAt: "2026-12-31T23:59:59Z" (expires end of year) - - rateLimitPolicy: {requestsPerMinute: 1200, burstSize: 120} - -### TenantTheme seed objects - -1. **Gemeente Zeist brand** (slug: `theme-zeist`) - - name: "Gemeente Zeist" - - cssVariables: { - "--c-primary": "#21468B", - "--c-surface": "#FFFFFF", - "--c-text": "#1a1a1a", - "--font-family": "Inter, sans-serif", - "--c-border": "#e0e0e0" - } - - logoUrl: "https://www.zeist.nl/logo.svg" - - customCss: ":root { --spacing: 8px; }" (only :root rules allowed) - -2. **Gemeente Amsterdam brand** (slug: `theme-amsterdam`) - - name: "Gemeente Amsterdam" - - cssVariables: { - "--c-primary": "#EC0000", - "--c-surface": "#FFFFFF", - "--c-text": "#333333", - "--font-family": "Roboto, sans-serif", - "--c-border": "#cccccc" - } - - logoUrl: "https://www.amsterdam.nl/logo.svg" - -3. **SaaS vendor brand** (slug: `theme-saas-vendor`) - - name: "Example Corp" - - cssVariables: { - "--c-primary": "#6366F1", - "--c-surface": "#FFFFFF", - "--c-text": "#1F2937", - "--font-family": "\"Helvetica Neue\", Helvetica, Arial, sans-serif", - "--c-border": "#D1D5DB" - } - - logoUrl: "https://example.com/branding/logo.svg" - -### SigningKey seed objects - -1. **Active RS256 key** (slug: `key-rsa-active-1`) - - algorithm: "RS256" - - status: "active" - - publicKeyJwk: { kty: "RSA", use: "sig", ..., kid: "rsa-1" } - - privateKeyEncrypted: (encrypted with KMS) - -2. **Retiring ES256 key** (slug: `key-ecdsa-retiring`) - - algorithm: "ES256" - - status: "retiring" - - publicKeyJwk: { kty: "EC", use: "sig", crv: "P-256", ..., kid: "ec-old" } - - privateKeyEncrypted: (encrypted with KMS) - -### EmbedUsageEvent seed objects - -1. Sample page-view event from Gemeente Zeist public website. - - tokenId: "<zeist-woo-token-id>" - - eventType: "pageView" - - hostOrigin: "https://intranet.zeist.nl" - - userAgent: "Chrome 124 / sha256(Mozilla/5.0...)" - - viewportSize: "medium" - - responseStatusCode: 200 - - responseLatencyMs: 87 - - timestamp: "2026-05-22T14:30:00Z" - -2. Sample widget-rendered event from SaaS portal. - - tokenId: "<saas-usage-token-id>" - - eventType: "widgetRendered" - - hostOrigin: "https://portal.example.com" - - userAgent: "Safari 17 / sha256(Mozilla/5.0...)" - - viewportSize: "small" - - responseStatusCode: 200 - - responseLatencyMs: 156 - - timestamp: "2026-05-22T15:45:00Z" - -3. Sample filter-applied event from consortium dashboard. - - tokenId: "<amsterdam-ops-token-id>" - - eventType: "filterApplied" - - hostOrigin: "https://intranet.amsterdam.nl" - - userAgent: "Firefox 125 / sha256(Mozilla/5.0...)" - - viewportSize: "large" - - responseStatusCode: 200 - - responseLatencyMs: 45 - - timestamp: "2026-05-22T16:20:00Z" - -## Test Strategy - -- **PHPUnit**: Token issuance (jwt generation + hash persistence), JWT validation (signature + expiry + revocation status), rate limiting (bucket state, 429 responses), CSP header emission, read-only enforcement. -- **Vitest (JS-SDK)**: PostMessage handshake (token injection after origin verification), iframe load, filter event relay, resize message handling. -- **Playwright**: Full end-to-end from token creation to embedded widget rendering, filter interaction from host page, theme application (CSS variable override), rate-limit 429 behaviour. -- **Admin UI**: Token create/revoke flows, usage report rendering, accessibility axe-core results display. - -## Migration Plan - -1. **Phase 1 — Backend services**: JWT signing service (key generation + rotation), EmbedTokenService (CRUD + validation), RateLimitService. Test coverage, no user-facing endpoints yet. -2. **Phase 2 — Public render route**: GET /apps/launchpad/embed/{subjectType}/{subjectId}?token=<jwt>, CSP headers, read-only enforcement, usage telemetry. -3. **Phase 3 — Admin UI**: EmbedTokenManager component (create, revoke, view usage), tenant theme manager, signing key rotation UI. -4. **Phase 4 — JS-SDK**: @launchpad/embed-sdk package (ESM + UMD), postMessage handshake, event relay. -5. **Phase 5 — Integration**: Modify dashboard/widget rendering to accept token scope context, apply theming, wire up accessibility checks. - -## Open Questions - -1. **Should token expiry default to a fixed duration (e.g., 1 year) or be non-expiring?** - - Current decision: Non-expiring by default, with optional `tokenExpiresAt` that admins can set per token. Rationale: issued-once tokens should remain valid until explicitly revoked; forcing re-issuance on every anniversary is operationally heavy. - -2. **Should the `EmbedUsageEvent` aggregate data (e.g., "pageviews per day") or write raw events?** - - Current decision: Write raw events (every page-view is one row). Aggregation happens at query time via analytics views. Rationale: raw events support arbitrary slicing (by origin, by viewport, by time); pre-aggregation would lock us into specific dimensions. - -3. **Should the JS-SDK support Pinia/Vuex integration for two-way state sync, or is event-only (host subscribes to filterApplied) sufficient?** - - Current decision: Event-only in v1. Host page subscribes to filterApplied/drillDown/export events via `.on(eventType, handler)`. Two-way state sync is out of scope. Rationale: keeps the SDK lightweight and language-agnostic; not all host pages use Pinia. - -## Reuse Analysis - -- **OpenRegister integration**: Embeds store all persistent objects (tokens, themes, keys, events) as register objects, reusing ObjectService, AuditTrailService, ACL infrastructure. -- **Existing widget/dashboard rendering**: Embeds leverage the same widget/dashboard rendering code paths as in-app views. No widget-specific fork. Theme injection happens at the Vue root level (CSS variable injection into `:root`). -- **Nextcloud CSP + Security headers**: The embed route respects Nextcloud's CSP policy and emits appropriate headers (CSP, X-Content-Type-Options, X-Frame-Options fallback). - -## Deduplication Check - -- **Token issuance**: No overlap with Nextcloud's session/cookie issuance. Nextcloud tokens (app password, remember token) are user-centric; embed tokens are widget-centric. -- **Rate limiting**: OpenRegister has no built-in rate limiting. RateLimitService is new and specific to embed tokens. -- **Usage telemetry**: Not reusing any LaunchPad existing logging. ActivityService is user-action centric; EmbedUsageEvent is traffic-observation centric. -- **Theme injection**: Theme service is new. Widgets already support CSS variable overrides (REQ-WDG-007 or similar), but tenant-theme is a new schema for bundling multiple variables + logo + custom CSS. -- **JWT signing**: Not reusing Nextcloud's OAuth2 token logic (which is stateful and session-based). JWT is stateless and self-contained. - -**Conclusion**: No overlap found. All components are new. diff --git a/openspec/changes/embedded-analytics/proposal.md b/openspec/changes/embedded-analytics/proposal.md deleted file mode 100644 index e1f60c51a..000000000 --- a/openspec/changes/embedded-analytics/proposal.md +++ /dev/null @@ -1,55 +0,0 @@ -# Embedded Analytics - -LaunchPad widgets today require a logged-in Nextcloud session to view. This forecloses three legitimate use cases: public-facing transparency dashboards (e.g., a gemeente's live "openstaande WOO-verzoeken" on a public webpage), partner-facing operational dashboards (shared-service organisations embedding their widget slice into each member gemeente's intranet), and in-product analytics (SaaS vendors surfacing usage widgets inside their customer portal). Embedded Analytics adds a first-class answer via signed JWT tokens, iframe and JS-SDK rendering paths, per-tenant theming, WCAG AA compliance, and auditable usage telemetry. - -## Affected code units - -- **NEW** `lib/Controller/EmbedController.php` — token issuance, revocation, usage analytics -- **NEW** `lib/Service/EmbedTokenService.php` — token generation, validation, persistence -- **NEW** `lib/Service/JwtSigningService.php` — JWT lifecycle (RS256/ES256), key rotation -- **NEW** `lib/Service/RateLimitService.php` — token-bucket rate limiting per token -- **NEW** `lib/Entity/EmbedToken.php` — OpenRegister mapping for embed_token objects -- **NEW** `lib/Entity/TenantTheme.php` — OpenRegister mapping for tenant_theme objects -- **NEW** `lib/Entity/EmbedUsageEvent.php` — OpenRegister mapping for embed_usage_event objects -- **NEW** `lib/Entity/SigningKey.php` — OpenRegister mapping for signing_key objects -- **NEW** `src/components/EmbedTokenManager.vue` — admin UI for token creation, revocation, usage report -- **NEW** `@launchpad/embed-sdk` (ESM + UMD) — JS client for iframe rendering with postMessage handshake -- **NEW** `GET /apps/launchpad/embed/{subjectType}/{subjectId}?token=<jwt>` — public render route (CSP-hardened) -- **MODIFY** `src/composables/useEmbedContext.js` — detect embed mode, apply token scope and theming -- **MODIFY** Dashboard and widget rendering — enforce read-only on REQ-EMB-004 scope, apply theming on REQ-EMB-005 - -## Capabilities - -### New Capabilities - -- `embed-tokens`: Admin-only JWT token lifecycle (issuance, revocation, rotation). Tokens are the only auth mechanism for embedded views. -- `embed-render`: Public-facing HTML rendering of widgets with CSP frame-ancestors, scope enforcement, and usage telemetry. -- `tenant-themes`: Per-tenant brand bundles (CSS variables, custom CSS, logo) injected into embed contexts. -- `embed-sdk`: JavaScript client (@launchpad/embed-sdk) for host-page integration (iframe wrapper + postMessage token injection + event relay). -- `embed-usage-analytics`: Per-token usage telemetry (pageviews, interactions, host origin, viewport size) with PII minimisation. - -### Modified Capabilities - -- `widget-rendering`: Widgets now accept a token scope that restricts available actions and applies filter pinning. -- `dashboard-sharing`: Embed tokens join the existing sharing surface in the dashboard detail view (alongside "share to group"). - -## Why a new change - -The six sub-capabilities (tokens, render, theming, SDK, telemetry, WCAG) are tightly coupled and release together. Token issuance without a render path is useless; a public render without WCAG compliance is a regulatory issue on municipal websites. Splitting into six micro-changes would spawn six git branches, six PRs, and six merge conflicts while adding no architectural clarity — the coupling is real, not artificial. - -## Cross-app integration - -- **openregister**: `embed_token`, `tenant_theme`, `embed_usage_event`, and `signing_key` stored as register objects with lifecycle, ACL, soft-delete, and audit-log infrastructure. -- **openconnector + auth-system token scopes**: JWT scope vocabulary aligns with platform-wide ADRs; external IdPs can exchange credentials for launchpad tokens via RFC 8693 token-exchange flow. -- **launchpad drill-down**: Embed tokens with `read-with-interactions` mode participate in the bus exactly like in-app sessions, scoped to the embed's iframe URL. -- **opencatalogi**: Public-facing catalog embeds reuse the embed-token mechanism. -- **docudesk**: Document-preview widgets may be embedded with the document's underlying ACL enforced by docudesk (embed cannot widen access). -- **AI Chat Companion (ADR-034)**: Intentionally NOT exposed via embed tokens in v1; embeds are read/interact only. - -## Notes - -- Read-only enforcement at the API tier (REQ-EMB-004) ensures even a tampered frontend cannot coerce writes; the check is unconditional on the server side. -- CSP `frame-ancestors` is the only sanctioned framing protection (W3C CSP Level 3); `X-Frame-Options` is emitted as a fallback for legacy browsers but carries no protective claim on modern browsers. -- Rate limiting follows the token-bucket algorithm with a 60-second propagation window for revocations — a deliberate trade-off between incident-response speed and render-route throughput. -- WCAG 2.1 AA compliance is mandated by the Web Toegankelijkheidsverordening for public-sector procurements; municipal-website embeds without AA are a regulatory issue. -- Usage telemetry captures host origin, viewport bucket, and user-agent family+major (hashed) — NO IP addresses, NO full user-agents, NO end-user identifiers (GDPR/AVG Article 5(1)(c) data minimisation). diff --git a/openspec/changes/embedded-analytics/specs/csp-and-framing.md b/openspec/changes/embedded-analytics/specs/csp-and-framing.md deleted file mode 100644 index c267f002d..000000000 --- a/openspec/changes/embedded-analytics/specs/csp-and-framing.md +++ /dev/null @@ -1,86 +0,0 @@ -# Spec — CSP and Framing Control (REQ-EMB-003) - -## REQ-EMB-003 — CSP frame-ancestors enforced from token hostOrigins - -The render route SHALL emit `Content-Security-Policy: frame-ancestors <hostOrigins>` derived from the token's `hostOrigins`, and the embed SHALL refuse to render when the iframe's actual top-level origin is not in `hostOrigins`. This is enforced both at the CSP level (modern browsers) and via Fetch Metadata headers (defence in depth). - -### Scenario 3.1 — Valid origin renders with CSP frame-ancestors header - -GIVEN a token with `hostOrigins=["https://www.zeist.nl"]` - AND the token is for widget W -WHEN the embed is loaded inside an iframe on `https://www.zeist.nl/woo/` -THEN the response to `GET /apps/launchpad/embed/widget/W?token=<jwt>` SHALL be 200 with HTML body - AND the response SHALL include header: - `Content-Security-Policy: frame-ancestors https://www.zeist.nl` - AND the browser SHALL render the iframe normally (CSP allows framing from https://www.zeist.nl) - -### Scenario 3.2 — Invalid origin blocked by CSP + server-side Sec-Fetch-Site check - -GIVEN the same token with `hostOrigins=["https://www.zeist.nl"]` -WHEN the iframe is loaded from `https://evil.example.com/phishing-page` - AND the iframe's top-level origin is `https://evil.example.com` -THEN the browser SHALL refuse to display the iframe due to CSP frame-ancestors violation - AND the server-side render route SHALL check the `Sec-Fetch-Site` header: - - If `Sec-Fetch-Site: cross-site` and top-origin from Referer ≠ allowed hostOrigins - - Then respond 403 with body `{error: "origin_mismatch", message: "This iframe cannot be embedded on this origin"}` - AND the browser still refuses to render (CSP violation takes precedence) - AND a `embed_usage_event` SHALL be written with `responseStatusCode: 403` - -### Scenario 3.3 — Multiple allowed origins - -GIVEN a token with `hostOrigins=["https://intranet.zeist.nl", "https://www.zeist.nl"]` -WHEN the embed is loaded from either origin -THEN the response SHALL include header: - `Content-Security-Policy: frame-ancestors https://intranet.zeist.nl https://www.zeist.nl` - AND the browser SHALL allow framing from either origin - -### Scenario 3.4 — Wildcard hostOrigins rejected at token creation - -GIVEN an admin user -WHEN they attempt to POST `/api/embed-tokens` with `hostOrigins=["*"]` -THEN the response SHALL be 400 with body: - ```json - { - "status": "error", - "error": "invalid_hostOrigins", - "message": "Wildcard origin '*' is not permitted. Specify explicit origins, e.g., [\"https://www.example.com\"]", - "fieldErrors": { - "hostOrigins": "wildcard_not_permitted" - } - } - ``` - AND the token SHALL NOT be created - -### Scenario 3.5 — X-Frame-Options fallback for legacy browsers - -GIVEN any render route response -WHEN the response is generated -THEN the response SHALL ALSO include header: - `X-Frame-Options: SAMEORIGIN` - (As a fallback for browsers that do not support CSP Level 3; no protective claim is made about X-Frame-Options sufficiency on modern browsers per W3C spec) - -### Scenario 3.6 — Referer header check (defence in depth) - -GIVEN a request with `Authorization: Bearer <jwt>` (Bearer header, not query param) - AND the token's `hostOrigins=["https://intranet.example.com"]` -WHEN the render route processes the request - AND the `Referer` header is `https://evil.example.com/page` -THEN the route SHALL respond 403 with body `{error: "origin_mismatch"}` - AND a `embed_usage_event` SHALL be written with `responseStatusCode: 403` - -### Scenario 3.7 — No Referer header (privacy-preserving browser configuration) - -GIVEN a request with no `Referer` header - AND the `Sec-Fetch-Site` header indicates `same-site` -THEN the route SHALL allow the request (assume same-origin; Referer is not available in privacy-preserving configurations) - AND a `embed_usage_event` SHALL be written with `responseStatusCode: 200` - -### Scenario 3.8 — Admin UI displays CSP header preview - -GIVEN the admin is creating or editing an embed token -WHEN they edit the `hostOrigins` field -THEN the admin UI SHALL display a live preview of the resulting CSP header: - ``` - Content-Security-Policy: frame-ancestors https://intranet.zeist.nl - ``` - AND a "Copy CSP header" button SHALL let them paste this into their host website's audit documentation diff --git a/openspec/changes/embedded-analytics/specs/embed-tokens.md b/openspec/changes/embedded-analytics/specs/embed-tokens.md deleted file mode 100644 index e082c0778..000000000 --- a/openspec/changes/embedded-analytics/specs/embed-tokens.md +++ /dev/null @@ -1,205 +0,0 @@ -# Spec — Embed Tokens (REQ-EMB-001, REQ-EMB-002) - -## REQ-EMB-001 — Token issuance returns JWT exactly once - -The system SHALL generate a JWT signed with the active signing key when a new `embed_token` is created, return it once in the create response, persist only the sha256 hash, and reject any subsequent request to re-retrieve the raw token. - -### Scenario 1.1 — Create token and receive JWT once - -GIVEN an admin user with token-management permission - AND the system has an active RS256 signing key -WHEN they POST `/api/embed-tokens` with a valid token-create payload: - ```json - { - "name": "Gemeente Zeist WOO", - "description": "Public WOO requests widget", - "subject": {"type": "widget", "id": "woo-widget-uuid"}, - "scope": {"mode": "read", "allowedFilters": ["status"], "allowedActions": []}, - "hostOrigins": ["https://intranet.zeist.nl"], - "rateLimitPolicy": {"requestsPerMinute": 600, "burstSize": 60} - } - ``` -THEN the response SHALL be 201 with body: - ```json - { - "id": "token-id-uuid", - "name": "Gemeente Zeist WOO", - "jwt": "eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...", - "warning": "keepThisSafe: This JWT is shown only once. Save it now. If lost, you must re-issue the token.", - "createdAt": "2026-05-22T14:30:00Z" - } - ``` - AND the response body SHALL include the raw JWT exactly once - AND a new row SHALL be created in `embed_token` register with: - - `id` matching the response - - `tokenHash` = sha256("eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...") - - ALL other fields matching the request + createdAt - -### Scenario 1.2 — Subsequent GET returns metadata but not JWT - -GIVEN an existing `embed_token` row with id="token-1" and tokenHash set -WHEN any GET request to `/api/embed-tokens/token-1` is made -THEN the response SHALL be 200 with body: - ```json - { - "id": "token-1", - "name": "Gemeente Zeist WOO", - "description": "Public WOO requests widget", - "subject": {"type": "widget", "id": "woo-widget-uuid"}, - "scope": {"mode": "read", ...}, - "hostOrigins": ["https://intranet.zeist.nl"], - "createdAt": "2026-05-22T14:30:00Z", - "createdBy": "admin-user-id", - "actions": [ - {"id": "re-issue", "label": "Re-issue token", "description": "Revoke this token and generate a new one"} - ] - } - ``` - AND the response SHALL NOT include the `jwt` field - AND the response SHALL NOT include the `tokenHash` field - -### Scenario 1.3 — Token creation rejects malformed hostOrigins - -GIVEN an admin user with token-management permission -WHEN they POST `/api/embed-tokens` with `hostOrigins` containing a malformed origin: - ```json - { - "name": "Bad Token", - "hostOrigins": ["https://www.example.com", "invalid-origin-missing-scheme"], - ... - } - ``` -THEN the response SHALL be 400 with body: - ```json - { - "status": "error", - "error": "invalid_hostOrigins", - "message": "Invalid origin format at index 1: missing URI scheme. Expected format: https://domain.com", - "fieldErrors": { - "hostOrigins[1]": "invalid_hostOrigins" - } - } - ``` - AND the `embed_token` row SHALL NOT be persisted - -### Scenario 1.4 — Re-issue token (revoke + create new) - -GIVEN an existing `embed_token` row with id="token-1" -WHEN an admin invokes the "re-issue" action via POST `/api/embed-tokens/token-1/re-issue` -THEN a new JWT SHALL be generated (signed with active key) - AND the old token's `revokedAt` SHALL be set to now - AND the old token's `revocationReason` SHALL be set to "re-issued" - AND a new `embed_token` row SHALL be created with: - - fresh `id` (new UUID) - - fresh `tokenHash` (sha256 of new JWT) - - same `subject`, `scope`, `hostOrigins`, `rateLimitPolicy` as the old token - - new `createdAt` and `createdBy` - AND the response SHALL include the new JWT (shown once) - ---- - -## REQ-EMB-002 — Public render route validates JWT and enforces scope - -The render route SHALL verify the JWT signature against the `kid`-selected `signing_key`, reject expired or revoked tokens, enforce `subject` match, and respond with 403 on any mismatch without leaking the existence of the subject. - -### Scenario 2.1 — Valid non-expired token renders widget - -GIVEN a valid, non-expired, non-revoked JWT for widget W signed with RS256 key (kid=rsa-1) - AND the embedded widget renders HTML (no token scope restriction assumed yet — REQ-EMB-004 covers scope enforcement) -WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` -THEN the response SHALL be 200 with HTML body - AND the response SHALL include header `Content-Security-Policy: frame-ancestors <hostOrigins>` - AND the response SHALL include header `X-Content-Type-Options: nosniff` - AND the widget SHALL render with the token's context applied (e.g., filter pinning from `subject.filterContext`) - AND a `embed_usage_event` row SHALL be written with: - - `eventType: "pageView"` - - `responseStatusCode: 200` - - `responseLatencyMs: <measured>` - -### Scenario 2.2 — Subject mismatch returns 403 without leaking existence - -GIVEN a valid JWT for widget W - AND the admin tries to render it against widget V (different UUID) -WHEN the route is called with `GET /apps/launchpad/embed/widget/V?token=<jwt>` -THEN the response SHALL be 403 with body: - ```json - { - "error": "scope_mismatch", - "message": "The provided token does not grant access to this resource" - } - ``` - AND the response SHALL NOT indicate whether widget V exists or not - AND a `embed_usage_event` row SHALL be written with: - - `eventType: "pageView"` - - `responseStatusCode: 403` - -### Scenario 2.3 — Expired token returns 401 with WWW-Authenticate header - -GIVEN a JWT whose `tokenExpiresAt` is in the past (e.g., "2026-01-01T00:00:00Z" and current time is 2026-05-22) -WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` -THEN the response SHALL be 401 with body: - ```json - { - "error": "token_expired", - "message": "The provided token has expired" - } - ``` - AND the response SHALL include header: - `WWW-Authenticate: Bearer error="invalid_token", error_description="The token has expired"` - AND a `embed_usage_event` row SHALL be written with `responseStatusCode: 401` - -### Scenario 2.4 — Revoked token returns 401 with constant-time comparison - -GIVEN a JWT whose `embed_token` row has `revokedAt` set (token was revoked 5 minutes ago) -WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` -THEN the response SHALL be 401 with body: - ```json - { - "error": "token_revoked", - "message": "The provided token has been revoked" - } - ``` - AND the response latency SHALL be constant-time-comparable to a non-revoked rejection (to prevent timing oracle attacks) - AND a `embed_usage_event` row SHALL be written with `responseStatusCode: 401` - -### Scenario 2.5 — Invalid JWT signature returns 401 - -GIVEN a JWT with an invalid signature (e.g., tampered payload) -WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<tampered-jwt>` -THEN the response SHALL be 401 with body: - ```json - { - "error": "invalid_token", - "message": "The provided token is invalid or malformed" - } - ``` - -### Scenario 2.6 — Missing token returns 401 - -GIVEN a request to the embed render route without a token -WHEN the route is called with `GET /apps/launchpad/embed/widget/W` (no ?token= parameter) -THEN the response SHALL be 401 with body: - ```json - { - "error": "missing_token", - "message": "No token provided. Include ?token=<jwt> or use the Authorization: Bearer <jwt> header" - } - ``` - -### Scenario 2.7 — Bearer header token (SDK form-factor) - -GIVEN a valid JWT passed via Authorization header (SDK use case) -WHEN the route is called with `GET /apps/launchpad/embed/widget/W` + header `Authorization: Bearer <jwt>` -THEN the response SHALL be 200 with HTML body (same as Scenario 2.1) - AND the response latency/rate-limit treatment SHALL be identical to query-parameter tokens - AND the response CSP/cache headers SHALL be identical - -### Scenario 2.8 — Query-parameter tokens enforce stricter rate limits - -GIVEN a token with `rateLimitPolicy: {requestsPerMinute: 600, burstSize: 60}` - AND requests arriving via `?token=<jwt>` (query parameter) - AND requests arriving via `Authorization: Bearer <jwt>` (header) -WHEN both form-factors are used for the same embed in the same minute -THEN the query-parameter form SHALL count against the token's configured rate limit - AND the Bearer-header form MAY have a separate (stricter) rate limit (e.g., 10× lower) to account for the token leak risk - AND the admin UI SHOULD surface this distinction in the token-creation flow diff --git a/openspec/changes/embedded-analytics/specs/rate-limiting.md b/openspec/changes/embedded-analytics/specs/rate-limiting.md deleted file mode 100644 index 61d1d4318..000000000 --- a/openspec/changes/embedded-analytics/specs/rate-limiting.md +++ /dev/null @@ -1,152 +0,0 @@ -# Spec — Rate Limiting and Request Budgeting (REQ-EMB-007) - -## REQ-EMB-007 — Rate limiting and request budgeting per token - -The system SHALL apply the token's `rateLimitPolicy` to all requests, return 429 with a `Retry-After` header when the bucket is exhausted, and write a `embed_usage_event` of type `pageView` even on rate-limited responses for budgeting analysis. - -### Scenario 7.1 — Token-bucket rate limiting with burst - -GIVEN a token with `rateLimitPolicy={requestsPerMinute: 60, burstSize: 10}` - AND the current time is T=0 -WHEN 70 requests arrive between T=0 and T=10 seconds (10 seconds into the first minute) -THEN: - - Requests 1-10 SHALL be processed (up to burst size) - - Requests 11-70 SHALL receive 429 responses with `Retry-After: 50` (seconds until next bucket refill) - AND each 429 response SHALL include an `embed_usage_event` with `responseStatusCode: 429` - AND after 60 seconds (one full minute), the bucket is refilled and new requests can be processed - -### Scenario 7.2 — Org-default rate limit for tokens without policy - -GIVEN a token with `rateLimitPolicy: null` (no custom policy specified) -WHEN requests arrive -THEN the org-level default policy SHALL apply: - ```json - { - "requestsPerMinute": 600, - "burstSize": 60 - } - ``` - AND the token operates under these defaults (high-throughput default for typical embeds) - -### Scenario 7.3 — 429 response format - -GIVEN a request that exceeds the rate limit -WHEN the render route processes it -THEN the response SHALL be 429 with: - ``` - HTTP/1.1 429 Too Many Requests - Content-Type: application/json - Retry-After: 45 - - { - "error": "rate_limit_exceeded", - "message": "Rate limit exceeded. The token allows 60 requests per minute. Try again in 45 seconds.", - "retryAfter": 45, - "resetAt": "2026-05-22T14:31:00Z" - } - ``` - -### Scenario 7.4 — Rate-limited request logged in usage events - -GIVEN a request that hits the rate limit -WHEN the 429 response is returned -THEN an `embed_usage_event` row SHALL be written with: - ```json - { - "id": "event-uuid", - "tokenId": "token-id", - "eventType": "pageView", - "hostOrigin": "https://www.zeist.nl", - "userAgent": "Chrome 124 / sha256(...)", - "viewportSize": "medium", - "timestamp": "2026-05-22T14:30:05Z", - "responseStatusCode": 429, - "responseLatencyMs": 12, - "correlationId": "correlation-uuid" - } - ``` - AND the admin can query: "This token hit rate limits 45 times on 2026-05-22 between 14:00 and 15:00" - -### Scenario 7.5 — Bucket refill and sliding window - -GIVEN a token with `requestsPerMinute: 60, burstSize: 10` (1 req/sec, burst 10) - AND 8 requests have been consumed at T=0 -WHEN new requests arrive at T=30 seconds (midway through the first minute) -THEN: - - 30 seconds of refill grants 30 requests (60 rpm ÷ 60 sec × 30 sec) - - Bucket now has: 10 (burst) + 30 (refilled) - 8 (used) = 32 capacity - - New request consumes 1, bucket now 31 - AND this is a token-bucket algorithm, not a fixed sliding window (continuous refill, not window resets) - -### Scenario 7.6 — Query-parameter vs Bearer-header rate limit distinction - -GIVEN a token with `rateLimitPolicy: {requestsPerMinute: 600, burstSize: 60}` -WHEN requests arrive via `?token=<jwt>` (query parameter) -THEN the query-parameter form MAY enforce a stricter limit: - - Override to 10× lower: 60 rpm, burst 6 (token leak risk warrants stricter throttling) - AND requests via `Authorization: Bearer <jwt>` (header) use the configured limit (600 rpm, burst 60) - AND the admin UI displays this distinction when creating a token: - ``` - Query-parameter form: up to 60 requests/minute (stricter for security) - Bearer header form: up to 600 requests/minute (as configured) - ``` - -### Scenario 7.7 — Rate limit policy updateable after token creation - -GIVEN an existing token with `rateLimitPolicy: {requestsPerMinute: 60, burstSize: 10}` -WHEN an admin invokes `PUT /api/embed-tokens/token-id` with a new policy: - ```json - { - "rateLimitPolicy": { - "requestsPerMinute": 120, - "burstSize": 15 - } - } - ``` -THEN the API SHALL respond 200 and update the token - AND the new rate limit applies to subsequent requests immediately - AND in-flight requests (between update and next request) use the old policy (best-effort; eventual consistency is acceptable) - -### Scenario 7.8 — Rate limit exhaustion analysis - -GIVEN the admin accessing the usage report for a token -WHEN they view the analytics dashboard -THEN they SHALL see: - ``` - Rate Limit Breaches - ├─ 2026-05-22: 145 requests rejected (60 expected) - │ Time: 14:00–15:00 (busiest hour) - │ Breach threshold: 600 rpm → hit 700 rpm - ├─ 2026-05-21: 23 requests rejected - └─ 2026-05-20: 0 requests rejected - - Recommendation: Consider raising requestsPerMinute to 1200 - ``` - AND a button "Adjust rate limit" opens the token edit dialog - -### Scenario 7.9 — Alert configuration (optional v1+) - -GIVEN an admin who wants to monitor token health -WHEN they configure alerts on a token (v1.1 feature, out of scope here but schema-ready): - ```json - { - "alertPolicy": { - "thresholdPercentage": 80, - "notifyEmail": "ops@gemeente.nl" - } - } - ``` -THEN when the token reaches 80% of its rate limit in a given minute, an email alert is sent - (This is a note for future expansion; not implemented in v1, but the schema supports it) - -### Scenario 7.10 — Rate limit headers in all responses - -GIVEN any response from the embed render route -WHEN the response is generated -THEN the response SHALL include rate-limit headers (RFC 6585 style): - ``` - RateLimit-Limit: 60 - RateLimit-Remaining: 45 - RateLimit-Reset: 2026-05-22T14:31:00Z - ``` - AND the host page / SDK can read these headers to show a rate-limit warning to the user diff --git a/openspec/changes/embedded-analytics/specs/revocation.md b/openspec/changes/embedded-analytics/specs/revocation.md deleted file mode 100644 index e11e80ef0..000000000 --- a/openspec/changes/embedded-analytics/specs/revocation.md +++ /dev/null @@ -1,212 +0,0 @@ -# Spec — Token Revocation (REQ-EMB-009) - -## REQ-EMB-009 — Token revocation takes effect within 60 seconds - -The system SHALL revoke a token by setting `revokedAt`, propagate the revocation to all render-route workers within 60 seconds via a short-TTL cache, and reject subsequent render requests with 401. - -### Scenario 9.1 — Revocation via admin UI - -GIVEN an admin viewing an embed token's detail page -WHEN they click the "Revoke" button -THEN the admin UI SHALL display a confirmation dialog: - ``` - Revoke token "Gemeente Zeist WOO"? - - [Dropdown] Revocation reason: - ├─ Compromised - ├─ No longer needed - ├─ Host website decommissioned - └─ Other... - - [Text field] Additional notes (optional): - "Gemeente decided to move WOO tracking in-house" - - [Cancel] [Confirm Revoke] - ``` -WHEN they select a reason and confirm -THEN the UI SHALL POST `/api/embed-tokens/token-id/revoke` with: - ```json - { - "reason": "no_longer_needed", - "notes": "Gemeente decided to move WOO tracking in-house" - } - ``` - -### Scenario 9.2 — Revocation persisted in token record - -GIVEN the revoke request -WHEN the API processes it -THEN the `embed_token` row SHALL be updated with: - ```json - { - "id": "token-id", - "name": "Gemeente Zeist WOO", - ... - "revokedAt": "2026-05-22T14:35:00Z", - "revocationReason": "no_longer_needed", - "revocationNotes": "Gemeente decided to move WOO tracking in-house", - "revokedBy": "admin-user-id" - } - ``` - AND the response SHALL be 200 with the updated token metadata - AND a notification SHALL be sent to the token's `createdBy` user: - ``` - Token "Gemeente Zeist WOO" has been revoked by admin-user. - Reason: no_longer_needed - Notes: Gemeente decided to move WOO tracking in-house - Revocation timestamp: 2026-05-22T14:35:00Z - ``` - -### Scenario 9.3 — Render-route workers reject revoked token within 60 seconds - -GIVEN a revoked token (revokedAt set 5 seconds ago) - AND multiple render-route worker processes running -WHEN any request arrives with the revoked token -THEN within 60 seconds (the cache propagation window), ALL workers SHALL: - 1. Check their revocation cache - 2. If the token is in the cache as revoked, respond 401 - 3. If the token is NOT in the cache yet (slow propagation), query the database: - ```sql - SELECT revokedAt FROM embed_token WHERE id = ? LIMIT 1; - ``` - 4. If `revokedAt IS NOT NULL`, respond 401 and update the local cache - 5. Cache the revocation status for 60 seconds (TTL) -AND the response SHALL be 401 with: - ```json - { - "error": "token_revoked", - "message": "The provided token has been revoked" - } - ``` - -### Scenario 9.4 — Usage event written even for revoked token - -GIVEN a revoked token used after revocation -WHEN the render route returns 401 -THEN an `embed_usage_event` SHALL be written with: - ```json - { - "eventType": "pageView", - "responseStatusCode": 401, - "responseLatencyMs": 5, - "timestamp": "2026-05-22T14:36:30Z" - } - ``` -AND the admin can query the usage report: - "Token 'Gemeente Zeist WOO' was used 23 times AFTER revocation (2026-05-22 14:35–14:45)" -AND this helps forensic review of potential security incidents - -### Scenario 9.5 — Cache propagation guarantees - -GIVEN a render-route worker A and worker B -WHEN a token is revoked at T=0 -AND worker A immediately refreshes its cache from the database -AND worker B is busy and does not refresh for 50 seconds -THEN: - - Worker A rejects the token starting at T=1 second - - Worker B continues accepting the token until T=50 seconds - - At T=60 seconds, worker B's cache expires and it must query the database - - Worker B then rejects the token starting at T=61 seconds -AND the 60-second window bounds the maximum delay across all workers - -### Scenario 9.6 — Purge cache action for critical incidents - -GIVEN a critical incident (token compromised, attacker active) -WHEN an admin clicks "Purge cache" on the revoked token's detail page -THEN the API SHALL: - 1. Immediately invalidate all render-route worker caches for this token - 2. Send a broadcast message to all workers (Redis, AMQP, or similar): - ```json - { - "type": "token_cache_purge", - "tokenId": "token-id", - "timestamp": "2026-05-22T14:35:30Z" - } - ``` - 3. All workers receive the message and drop the token from their cache - 4. The next request with the revoked token queries the database and is rejected immediately -AND the response shows: - ``` - Cache purged. All render workers will immediately reject this token. - Purge initiated at 2026-05-22T14:35:30Z. - ``` - -### Scenario 9.7 — Re-issue (new token, revoke old) - -GIVEN an admin who has lost a token or wants to refresh it -WHEN they invoke the "Re-issue" action on the token -THEN the system SHALL: - 1. Generate a new JWT - 2. Create a new `embed_token` row with the same subject, scope, hostOrigins, etc. - 3. Revoke the old token (set revokedAt and revocationReason: "re-issued") - 4. Return the new JWT to the admin (shown once) -AND the old token is rejected starting immediately (cache expires within 60s, database rejects immediately) -AND subsequent integration uses the new token - -### Scenario 9.8 — Revocation audit trail - -GIVEN the audit log for a token -WHEN an admin reviews the token's history -THEN they SHALL see: - ``` - Audit Trail for Token "Gemeente Zeist WOO" - ├─ 2026-05-22T14:35:00Z — REVOKED by admin@gemeente.nl - │ Reason: no_longer_needed - │ Notes: Gemeente decided to move WOO tracking in-house - ├─ 2026-05-20T10:00:00Z — ACCESSED 342 times - │ Host origins: https://intranet.zeist.nl (340), https://www.zeist.nl (2) - ├─ 2026-05-15T09:30:00Z — CREATED by admin@gemeente.nl - │ Subject: widget / woo-widget - │ Scope: read, filters=[status, periode] - └─ (no further events) - ``` - -### Scenario 9.9 — Token state visibility - -GIVEN a list of all embed tokens in the admin UI -WHEN the admin views the token table -THEN each row SHALL display: - - Token name - - Status: [ACTIVE | REVOKED | EXPIRING SOON] - - Subject: (widget/dashboard name) - - Created: 2026-05-15 - - Last used: 2026-05-22 14:30 - - Revoked: (empty if active, or "2026-05-22 14:35" if revoked) - - Actions: [View] [Edit] [Re-issue] [Revoke] (or [Un-revoke] if revoked — soft-revoke only) - -### Scenario 9.10 — Soft revocation (can be undone) - -GIVEN a revoked token -WHEN an admin clicks "Undo revocation" (or "Un-revoke") -THEN the system SHALL: - 1. Clear the `revokedAt` and `revocationReason` fields - 2. Set `unrevokedAt` and `unrevokedBy` for audit - 3. Respond 200 with the token's updated state - 4. Send a notification to the token's creator -AND the token is immediately re-activated (cache expires, database accepts) -AND the full history (revocation + un-revocation) is auditable - -### Scenario 9.11 — Bulk revocation (future feature, out of scope) - -GIVEN multiple tokens that are no longer needed -WHEN an admin selects them and invokes "Revoke selected" (future v1.1 feature) -THEN all tokens are revoked in a single operation - (This is a note for future; not implemented in v1, but the schema supports bulk operations) - -### Scenario 9.12 — Revocation email notification - -GIVEN a token that was revoked -WHEN the revocation is confirmed -THEN an email SHALL be sent to the token's creator: - ``` - Subject: Token Revoked: Gemeente Zeist WOO - - Your embed token "Gemeente Zeist WOO" has been revoked. - - Revoked by: admin@gemeente.nl - Reason: no_longer_needed - Notes: Gemeente decided to move WOO tracking in-house - Revocation time: 2026-05-22 14:35 UTC - - If this was unexpected, contact the administrator. - ``` diff --git a/openspec/changes/embedded-analytics/specs/scope-enforcement.md b/openspec/changes/embedded-analytics/specs/scope-enforcement.md deleted file mode 100644 index 3a5cdca0b..000000000 --- a/openspec/changes/embedded-analytics/specs/scope-enforcement.md +++ /dev/null @@ -1,114 +0,0 @@ -# Spec — Read-Only Scope Enforcement (REQ-EMB-004) - -## REQ-EMB-004 — Read-only enforcement at the API tier - -The system SHALL reject any write operation (POST/PUT/PATCH/DELETE) issued under an `embed_token` whose `scope.mode=read`, even when the operation would otherwise be permitted by the subject's ACL. This enforcement happens on the API tier before any state mutation. - -### Scenario 4.1 — Read-mode token rejects write operation - -GIVEN an `embed_token` with `scope.mode="read"` for dashboard D - AND an authenticated user holds this token (via JWT in Authorization or query parameter) - AND the user (or JavaScript running in the iframe) attempts a POST to add a comment on dashboard D -WHEN the SDK or frontend invokes `POST /api/dashboards/D/comments` with a comment payload -THEN the API SHALL respond 403 with body: - ```json - { - "error": "read_only_token", - "message": "This token does not permit write operations. Token scope: mode=read" - } - ``` - AND NO state SHALL be mutated (no comment created, no audit log entry) - AND a `embed_usage_event` SHALL be written with `eventType: "pageView"`, `responseStatusCode: 403` - -### Scenario 4.2 — Read-mode token rejects DELETE - -GIVEN the same read-only token for dashboard D -WHEN the frontend attempts `DELETE /api/dashboards/D/widgets/w1` (remove a widget from the dashboard) -THEN the API SHALL respond 403 with body: - ```json - { - "error": "read_only_token", - "message": "This token does not permit write operations. Token scope: mode=read" - } - ``` - AND NO state mutation occurs - -### Scenario 4.3 — Read-mode token permits GET and HEAD - -GIVEN the same read-only token -WHEN the frontend invokes `GET /api/dashboards/D` (read operation) -THEN the API SHALL respond 200 with the dashboard data - AND read permission is determined by the subject-match (the token is scoped to dashboard D) - AND no scope-mode check blocks the read - -### Scenario 4.4 — Read-with-interactions token permits scoped actions - -GIVEN an `embed_token` with `scope.mode="read-with-interactions", allowedActions=["interact", "drillDown"]` for dashboard D - AND the dashboard has a filter UI -WHEN the SDK applies an in-bus filter clause (drill-down), invoking `POST /api/dashboards/D/filters` with `{dimension: "gemeente", value: "Amsterdam"}` -THEN the API SHALL respond 200 and process the filter - AND the operation SHALL be captured in an `embed_usage_event` with `eventType: "filterApplied"` - AND subsequent `GET` calls reflect the pinned filter - -### Scenario 4.5 — Read-with-interactions token rejects disallowed action - -GIVEN an `embed_token` with `scope.mode="read-with-interactions", allowedActions=["interact", "drillDown"]` (export NOT allowed) -WHEN the frontend attempts `POST /api/dashboards/D/export` with `format: "csv"` -THEN the API SHALL respond 403 with body: - ```json - { - "error": "action_not_in_scope", - "message": "The action 'export' is not permitted by this token. Allowed actions: interact, drillDown" - } - ``` - AND NO export is generated - -### Scenario 4.6 — All write operations checked, regardless of subject type - -GIVEN a read-only token for a widget W -WHEN any of the following write operations are attempted on the widget: - - `POST /api/widgets/W/interactions` (add interaction) - - `PUT /api/widgets/W/settings` (update widget settings) - - `PATCH /api/widgets/W` (partial update) -THEN ALL SHALL respond 403 with the read-only error - AND the API does NOT discriminate by operation type; ALL non-GET/HEAD are blocked - -### Scenario 4.7 — Scope enforcement independent of frontend state - -GIVEN a read-only token embedded in an iframe -WHEN the JavaScript in the iframe is patched (via browser DevTools) to remove the UI-layer read-only enforcement - AND the patched JS attempts `POST /api/dashboards/D/widgets/new` -THEN the API-tier check SHALL still respond 403 - AND the tampered frontend cannot bypass the API check - -### Scenario 4.8 — Scope metadata visible in token detail view - -GIVEN an admin viewing an embed token's details -WHEN they inspect the token's scope -THEN the admin UI SHALL display: - ``` - Mode: read - Allowed Filters: status, periode - Allowed Actions: (none) - ``` - AND when creating a read-with-interactions token, the admin SHALL see checkboxes for each available action (interact, export, drillDown) to select - -### Scenario 4.9 — Filter context pinning persisted with token - -GIVEN an `embed_token` for dashboard D with `subject.filterContext={gemeente: "Amsterdam"}` -WHEN the embed is rendered - AND the user attempts to change the gemeente filter to "Rotterdam" via the UI -THEN the filter interaction SHALL succeed (read-with-interactions mode allows it) - BUT the filter SHALL NOT persist across page reloads — the next page load resets the gemeente filter to "Amsterdam" - AND the filter context is enforced by the render route, not by the frontend - -### Scenario 4.10 — API middleware integration point - -GIVEN the LaunchPad API middleware/controller base -WHEN a request arrives with an `embed_token` (detected via JWT in Authorization header or token context) -THEN the middleware SHALL: - 1. Verify the token is valid and non-revoked (REQ-EMB-002) - 2. Extract the token's scope - 3. For non-GET/HEAD requests, check if `scope.mode=read` and respond 403 before the controller is invoked - 4. For GET/HEAD requests, proceed to the controller (the subject-match verification happens per-endpoint) - 5. For actions with allowedActions restrictions, check the action name against the allowed set before invoking the handler diff --git a/openspec/changes/embedded-analytics/specs/sdk-and-rendering.md b/openspec/changes/embedded-analytics/specs/sdk-and-rendering.md deleted file mode 100644 index 24093dfa4..000000000 --- a/openspec/changes/embedded-analytics/specs/sdk-and-rendering.md +++ /dev/null @@ -1,219 +0,0 @@ -# Spec — JS-SDK and Rendering (REQ-EMB-006) - -## REQ-EMB-006 — JS-SDK exposes render, event, and resize APIs - -The system SHALL publish a JS-SDK (`@launchpad/embed-sdk`, ESM and UMD builds) that exposes `LaunchPadEmbed.render(container, {token, subjectType, subjectId})`, `.on(eventType, handler)` for filter/drill/export events, and `.resize()` for host-driven layout changes. - -### Scenario 6.1 — SDK initialization and iframe creation - -GIVEN a host page (e.g., a SaaS customer portal) that imports the SDK: - ```html - <script src="https://cdn.example.com/@launchpad/embed-sdk@1.0.0/dist/embed-sdk.umd.js"></script> - <!-- OR ESM: import LaunchPadEmbed from '@launchpad/embed-sdk'; --> - ``` -WHEN the host page calls: - ```javascript - const embed = LaunchPadEmbed.render('#embed-container', { - token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...', - subjectType: 'widget', - subjectId: 'usage-widget-uuid' - }); - ``` -THEN the SDK SHALL: - 1. Create an `<iframe>` element with `src="https://launchpad.app/apps/launchpad/embed/widget/usage-widget-uuid"` - 2. Insert the iframe into the `#embed-container` div - 3. Wait for the iframe's `load` event - 4. Perform a postMessage handshake with the iframe to inject the JWT token - 5. Resolve a promise when the first render completes - AND the host page code continues: - ```javascript - embed.then(() => { - console.log('Widget loaded'); - }); - ``` - -### Scenario 6.2 — PostMessage handshake for token injection - -GIVEN the SDK has created an iframe -WHEN the iframe loads (fires `load` event) -THEN the SDK SHALL: - 1. Post a message to the iframe: - ```javascript - iframe.contentWindow.postMessage({ - type: 'embed-token', - token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...', - origin: 'https://portal.example.com' - }, 'https://launchpad.app') - ``` - 2. The iframe's origin verification (in the render route) SHALL check that `event.origin === 'https://launchpad.app'` before accepting the message - 3. The iframe stores the token in a secure context and uses it for subsequent API requests - 4. The iframe posts back a 'ready' message when the widget is fully rendered: - ```javascript - window.parent.postMessage({type: 'embed-ready', success: true}, '<SDK-origin>') - ``` - 5. The SDK resolves the promise returned by `render()` when the 'embed-ready' message arrives - -### Scenario 6.3 — Filter event subscription and relay - -GIVEN the host page has called `render()` successfully -WHEN the host page subscribes to filter events: - ```javascript - embed.on('filterApplied', ({dimension, value, source}) => { - console.log(`Filter applied: ${dimension} = ${value}`); - // Host page can now sync its own UI - }); - ``` -AND the end-user clicks on a bar in the embedded chart (drill-down interaction) -THEN the iframe SHALL: - 1. Emit an internal event (in-app bus) with `{dimension: 'gemeente', value: 'Amsterdam'}` - 2. Post a message to the parent: - ```javascript - window.parent.postMessage({ - type: 'embed-event', - eventType: 'filterApplied', - payload: {dimension: 'gemeente', value: 'Amsterdam', source: 'user-interaction'} - }, '<SDK-origin>') - ``` - 3. The SDK receives the message and invokes the registered handler - 4. The host page can read the filter and update its own UI/URL - -### Scenario 6.4 — Export event (read-with-interactions) - -GIVEN an embed with `scope.allowedActions=["export"]` -WHEN the user clicks "Export to CSV" in the widget -THEN the iframe SHALL: - 1. Invoke the export API (allowed by scope) - 2. Post a 'export' event to the parent: - ```javascript - window.parent.postMessage({ - type: 'embed-event', - eventType: 'export', - payload: {format: 'csv', url: 'https://launchpad.app/api/downloads/export-123.csv'} - }, '<SDK-origin>') - ``` - 3. The host page can download the file or handle it custom (e.g., send to email) - -### Scenario 6.5 — Resize API for responsive layout - -GIVEN the host page's layout changes (e.g., browser window resized, sidebar collapsed) -WHEN the host page calls: - ```javascript - embed.resize(); - ``` -THEN the SDK SHALL: - 1. Post a message to the iframe: - ```javascript - iframe.contentWindow.postMessage({ - type: 'embed-resize', - containerWidth: 1200, - containerHeight: 600 - }, 'https://launchpad.app') - ``` - 2. The iframe receives the message and re-measures its container - 3. The iframe re-renders the widget with the new dimensions - 4. The iframe posts back a 'resized' message when complete: - ```javascript - window.parent.postMessage({type: 'embed-resized', success: true}, '<SDK-origin>') - ``` - 5. The SDK resolves the promise returned by `resize()` - -### Scenario 6.6 — ESM build with TypeScript types - -GIVEN a TypeScript host application -WHEN it imports the SDK: - ```typescript - import LaunchPadEmbed from '@launchpad/embed-sdk'; - import type { EmbedConfig, EmbedInstance } from '@launchpad/embed-sdk'; - - const config: EmbedConfig = { - token: 'eyJ...', - subjectType: 'widget', - subjectId: 'uuid' - }; - - const embed: EmbedInstance = await LaunchPadEmbed.render('#container', config); - embed.on('filterApplied', (event) => { - // event is typed as EmbedFilterEvent - }); - ``` -THEN the IDE SHALL provide autocomplete and type checking - AND the TypeScript types SHALL document the API surface - -### Scenario 6.7 — UMD build for vanilla JS - -GIVEN a vanilla JavaScript page (no build step, no module bundler) -WHEN it loads the UMD bundle: - ```html - <script src="https://unpkg.com/@launchpad/embed-sdk@1.0.0/dist/embed-sdk.umd.js"></script> - ``` -THEN the SDK is available as a global: - ```javascript - window.LaunchPadEmbed.render('#container', {token: '...', ...}) - .then(() => console.log('Ready')); - ``` - -### Scenario 6.8 — Error handling in SDK - -GIVEN the host page calls `render()` with an invalid token -WHEN the iframe attempts to load the render route -THEN the render route responds 401 - AND the iframe posts an 'error' message to the parent: - ```javascript - window.parent.postMessage({ - type: 'embed-error', - error: 'invalid_token', - message: 'The provided token is invalid or has expired' - }, '<SDK-origin>') - ``` - AND the SDK's promise rejects with a descriptive error: - ```javascript - embed.catch((err) => { - console.error('Failed to load widget:', err.message); - }); - ``` - -### Scenario 6.9 — Event listener management - -GIVEN the host page has subscribed to events: - ```javascript - const handler = (event) => { ... }; - embed.on('filterApplied', handler); - ``` -WHEN the host page wants to unsubscribe: - ```javascript - embed.off('filterApplied', handler); - ``` -THEN the event listener SHALL be removed - AND no further 'filterApplied' events are delivered to that handler - AND other handlers (if registered) still receive events - -### Scenario 6.10 — Multiple embeds on same page - -GIVEN a host page with three embed containers: - ```html - <div id="embed-1"></div> - <div id="embed-2"></div> - <div id="embed-3"></div> - ``` -WHEN the host page initializes all three: - ```javascript - const embed1 = LaunchPadEmbed.render('#embed-1', {token: '...', subjectId: 'widget-1'}); - const embed2 = LaunchPadEmbed.render('#embed-2', {token: '...', subjectId: 'widget-2'}); - const embed3 = LaunchPadEmbed.render('#embed-3', {token: '...', subjectId: 'widget-3'}); - ``` -THEN each embed operates independently - AND events from embed1 do not leak to embed2 or embed3 - AND each postMessage handshake is isolated - -### Scenario 6.11 — SDK package publishing - -GIVEN the LaunchPad build process -WHEN `npm run build:sdk` executes -THEN the SDK package SHALL be published to npm with: - - ESM build: `dist/embed-sdk.esm.js` - - UMD build: `dist/embed-sdk.umd.js` - - TypeScript definitions: `dist/embed-sdk.d.ts` - - Minified versions: `dist/embed-sdk.esm.min.js`, `dist/embed-sdk.umd.min.js` - - Source maps for debugging - - Package name: `@launchpad/embed-sdk` - - Version matching the LaunchPad app version diff --git a/openspec/changes/embedded-analytics/specs/telemetry.md b/openspec/changes/embedded-analytics/specs/telemetry.md deleted file mode 100644 index c4080bdf1..000000000 --- a/openspec/changes/embedded-analytics/specs/telemetry.md +++ /dev/null @@ -1,205 +0,0 @@ -# Spec — Usage Telemetry (REQ-EMB-008) - -## REQ-EMB-008 — Usage telemetry without leaking PII - -The system SHALL persist `embed_usage_event` rows for every page-view and interaction, SHALL capture `hostOrigin`, `userAgent` (truncated to family + major version + hashed), and `viewportSize` (bucketed), and SHALL NOT capture full IP addresses, full user-agents, or any identifier of the host-page's logged-in user. - -### Scenario 8.1 — Page-view telemetry capture - -GIVEN an embed page-view request from `https://www.zeist.nl/woo/` (host origin) - AND the user's user-agent: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36` - AND the viewport size: 1920×1080 pixels -WHEN the render route processes the request and returns 200 -THEN an `embed_usage_event` row SHALL be written with: - ```json - { - "id": "event-uuid", - "tokenId": "token-id", - "eventType": "pageView", - "hostOrigin": "https://www.zeist.nl", - "userAgent": "Chrome 124", - "userAgentHash": "sha256(Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36)", - "viewportSize": "large", - "responseStatusCode": 200, - "responseLatencyMs": 87, - "timestamp": "2026-05-22T14:30:00Z", - "correlationId": "correlation-uuid" - } - ``` - -### Scenario 8.2 — Viewport size bucketing - -GIVEN viewport widths: - - 0–767px (small) - - 768–1279px (medium) - - 1280px+ (large) -WHEN embed requests arrive with various viewport sizes -THEN the event's `viewportSize` field SHALL be bucketed: - ```json - [ - {"width": 480, "height": 720, "viewportSize": "small"}, - {"width": 1024, "height": 768, "viewportSize": "medium"}, - {"width": 1920, "height": 1080, "viewportSize": "large"} - ] - ``` - -### Scenario 8.3 — NO IP address capture - -GIVEN a request arriving with headers: - ``` - X-Forwarded-For: 203.0.113.42 - X-Real-IP: 203.0.113.42 - ``` -WHEN the embed usage event is written -THEN the event row SHALL NOT include: - - Client IP address - - X-Forwarded-For header value - - Any IP-based geolocation -AND the only "location" data is the `hostOrigin` (domain, not geolocation) - -### Scenario 8.4 — User-agent family + major version only - -GIVEN user-agents: - ``` - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0.6367.60 - Mozilla/5.0 (iPhone; CPU iPhone OS 17_4_1 like Mac OS X) Mobile Safari/604.1 - Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0 - ``` -WHEN events are written -THEN the `userAgent` field SHALL be truncated to family + major: - ```json - [ - {"userAgent": "Chrome 124"}, - {"userAgent": "Safari 17"}, - {"userAgent": "Firefox 125"} - ] - ``` -AND the full user-agent string is hashed and stored separately in `userAgentHash` for analytics without fingerprinting - -### Scenario 8.5 — NO end-user identifier in events - -GIVEN a host page that is embedded in a SaaS portal, where the logged-in user is "customer-123" - AND the LaunchPad request is made in the context of that user -WHEN the embed usage event is written -THEN the event row SHALL NOT include: - - User ID from the host page (even if passed in a header) - - Email address of the host-page's logged-in user - - Account name or subscription tier -AND the only identifier is the `tokenId` (which widget/dashboard was embedded, not who viewed it) - -### Scenario 8.6 — Host origin stored (not referrer, not full URL) - -GIVEN a request from `https://www.zeist.nl/woo/requests-2026-05/?sort=date&limit=50` -WHEN the event is written -THEN the `hostOrigin` field SHALL be: - ```json - {"hostOrigin": "https://www.zeist.nl"} - ``` -NOT: - - The full URL (path+query stripped) - - The Referer header (may be empty or stripped by proxies) - - Derived from IP geolocation - -### Scenario 8.7 — Interaction events also captured - -GIVEN the user interacts with an embedded widget (filter applied, drill-down, export) -WHEN the interaction is processed -THEN an `embed_usage_event` SHALL be written with: - ```json - { - "eventType": "filterApplied", - "payload": { - "dimension": "status", - "value": "openstaande" - }, - "hostOrigin": "https://www.zeist.nl", - "userAgent": "Chrome 124", - "viewportSize": "large", - "responseStatusCode": 200, - "timestamp": "2026-05-22T14:30:15Z" - } - ``` -OR: - ```json - { - "eventType": "export", - "payload": { - "format": "csv" - }, - ... - } - ``` - -### Scenario 8.8 — Usage report in admin UI - -GIVEN an admin accessing the usage report for a token -WHEN they view the analytics dashboard -THEN they SHALL see: - ``` - Pageviews - ├─ Total (last 7 days): 1,243 views - ├─ By date: - │ └─ 2026-05-22: 324 views - │ └─ 2026-05-21: 289 views - │ └─ 2026-05-20: 215 views - ├─ By host origin: - │ └─ https://www.zeist.nl: 1,100 views - │ └─ https://intranet.zeist.nl: 143 views - └─ By viewport size: - └─ large: 601 views - └─ medium: 432 views - └─ small: 210 views - - Interactions - ├─ filterApplied: 87 times - ├─ drillDown: 45 times - └─ export: 12 times - - Browsers - ├─ Chrome 124: 623 views - ├─ Safari 17: 312 views - └─ Firefox 125: 308 views - ``` - -### Scenario 8.9 — No individual-user identifiers in report - -GIVEN the admin viewing the usage report -WHEN they inspect the data -THEN they SHALL NOT see: - - List of end-users who viewed the embed - - User names or email addresses - - Timestamps per individual user (only aggregated by day) - - Correlation of two views to the same person (no fingerprinting via UA hash + viewport) -AND the report answers only: "Did this embed get traffic?" and "From where?" - -### Scenario 8.10 — Org-level telemetry kill-switch - -GIVEN an admin with org configuration access -WHEN they toggle "Disable embed usage telemetry" in org settings -THEN: - - No `embed_usage_event` rows are written for any subsequent requests - - Existing events are NOT deleted (audit trail remains) - - The toggle is auditable (audit log records who disabled telemetry and when) - - Re-enabling telemetry immediately resumes event capture - -### Scenario 8.11 — Data retention policy - -GIVEN the org's data retention policy (e.g., "keep events for 90 days") -WHEN 90 days have passed since an `embed_usage_event` was created -THEN a background job SHALL delete the old event - AND the event is permanently removed (not soft-deleted; no recovery) - AND the deletion is logged in the audit trail - -### Scenario 8.12 — GDPR/AVG data subject access (not applicable) - -GIVEN a data subject (end-user) requesting access to their personal data per GDPR Article 15 -WHEN the org's DPO runs the data-subject-access query -THEN the system SHALL respond: - ``` - No personal data on record for this data subject. - Reasoning: Embed telemetry captures only host origin and viewport size. - No user identifiers, emails, IP addresses, or other traceable personal data are stored. - The only entity involved is the embed token (issued by the org administrator to a third-party host), - not personal data of an end-user. - ``` -AND the org does NOT need to include embed telemetry in GDPR access response letters diff --git a/openspec/changes/embedded-analytics/specs/theming-and-accessibility.md b/openspec/changes/embedded-analytics/specs/theming-and-accessibility.md deleted file mode 100644 index 54ec82982..000000000 --- a/openspec/changes/embedded-analytics/specs/theming-and-accessibility.md +++ /dev/null @@ -1,237 +0,0 @@ -# Spec — Theming and Accessibility (REQ-EMB-005, REQ-EMB-010) - -## REQ-EMB-005 — Per-tenant theming via CSS variables - -The embed SHALL apply the token's `tenantThemeId` (if set) by injecting `cssVariables` into the embed's `:root` and SHALL refuse `customCss` rules that target selectors outside `:root`. - -### Scenario 5.1 — CSS variables injected into :root - -GIVEN a `tenant_theme` object with: - ```json - { - "id": "theme-zeist", - "name": "Gemeente Zeist", - "cssVariables": { - "--c-primary": "#21468B", - "--font-family": "Inter, sans-serif", - "--c-surface": "#FFFFFF", - "--c-text": "#1a1a1a", - "--c-border": "#e0e0e0" - } - } - ``` - AND an `embed_token` with `tenantThemeId="theme-zeist"` for widget W -WHEN the embed render route generates HTML for widget W -THEN the response SHALL include: - ```html - <html> - <head> - <style> - :root { - --c-primary: #21468B; - --font-family: Inter, sans-serif; - --c-surface: #FFFFFF; - --c-text: #1a1a1a; - --c-border: #e0e0e0; - } - </style> - </head> - <body> - <!-- widget HTML --> - </body> - </html> - ``` - AND the widget's styles SHALL use these CSS variables - AND the widget SHALL paint with the gemeente's brand colour (primary), font, and surface colour - -### Scenario 5.2 — Custom CSS restricted to :root only - -GIVEN a `tenant_theme` with `customCss=":root { --spacing: 8px; }"` -WHEN the theme is saved via `POST /api/tenant-themes` -THEN the API SHALL accept the theme and respond 201 - -### Scenario 5.3 — Custom CSS with non-:root selector rejected - -GIVEN an admin attempting to save a `tenant_theme` with `customCss=".widget-title { color: red; }"` -WHEN the POST `/api/tenant-themes` request is processed -THEN the API SHALL respond 400 with body: - ```json - { - "status": "error", - "error": "invalid_customCss", - "message": "CSS rules must be scoped to :root only. Found selector '.widget-title' which targets elements outside :root. Non-:root selectors can be used to disable required UI affordances (e.g., hide accessibility focus rings).", - "fieldErrors": { - "customCss": "non_root_selector" - } - } - ``` - AND the theme SHALL NOT be created - -### Scenario 5.4 — No theme uses platform default - -GIVEN an `embed_token` with `tenantThemeId: null` (no theme selected) -WHEN the embed render route generates HTML -THEN the response SHALL use the platform's default NL Design theme (no custom :root injection) - AND the widget SHALL render with standard LaunchPad colours and fonts - -### Scenario 5.5 — Theme logo displayed in embed header - -GIVEN a `tenant_theme` with `logoUrl="https://www.zeist.nl/logo.svg"` - AND an `embed_token` referencing this theme -WHEN the embed is rendered in iframe mode -THEN the render route MAY include a minimal embed header with: - ```html - <div class="embed-header"> - <img src="https://www.zeist.nl/logo.svg" alt="Gemeente Zeist" class="embed-logo" /> - </div> - ``` - AND the header SHALL be minimal (no chrome, no navigation, no user menu) - OR the header MAY be omitted if the embed is configured for full-bleed rendering - -### Scenario 5.6 — Theme inheritance in admin UI - -GIVEN the admin creating a new embed token -WHEN they select a `tenantThemeId` -THEN the admin UI SHALL display: - - Theme name ("Gemeente Zeist") - - Live preview of brand colours (primary, surface, text) - - Logo preview (if set) - AND a "View CSS variables" button to inspect the variable overrides - -### Scenario 5.7 — Multiple tokens can share a theme - -GIVEN a `tenant_theme` "Gemeente Zeist" -WHEN two different `embed_token` objects both reference `tenantThemeId="theme-zeist"` -THEN both embeds SHALL render with the same brand - AND theme updates affect both embeds immediately - AND the theme is a reusable resource, not cloned per token - ---- - -## REQ-EMB-010 — WCAG 2.1 AA compliance enforced in embed rendering - -The embed render route SHALL produce HTML output that meets WCAG 2.1 AA success criteria for the widget being embedded, SHALL pass automated axe-core checks at build time on a representative sample of widget shapes, and SHALL surface accessibility violations in the embed-token admin UI as a non-fatal warning. - -### Scenario 10.1 — WCAG AA rendering requirements - -GIVEN an embed render of a chart widget -WHEN the HTML is inspected against WCAG 2.1 AA criteria -THEN EVERY interactive element SHALL have: - - An accessible name (`aria-label`, `aria-labelledby`, or visible text content) - - Colour contrast ≥ 4.5:1 for text (WCAG 1.4.3) - - Colour contrast ≥ 3:1 for graphical objects (WCAG 1.4.11) -AND the embed SHALL be navigable by keyboard alone: - - All interactive elements reachable via Tab key - - Tab order logical (left-to-right, top-to-bottom) - - No keyboard traps (user can tab away from any element) - - Focus indicators visible (outline or other visible focus marker) -AND semantic HTML is used: - - Heading hierarchy correct (no skipped levels) - - Lists marked with `<ul>`, `<ol>`, `<li>` - - Form inputs have associated `<label>` elements - -### Scenario 10.2 — Contrast check on theme CSS variables - -GIVEN a `tenant_theme` with `cssVariables={"--c-primary": "#0099CC", "--c-surface": "#FFFFFF"}` -WHEN the theme is saved -THEN the API SHALL compute the colour contrast ratio using the WCAG luminance formula - AND if contrast < 4.5:1, respond 400 with body: - ```json - { - "status": "error", - "error": "insufficient_contrast", - "message": "Primary colour #0099CC against surface #FFFFFF has contrast ratio 3.8:1. WCAG AA requires 4.5:1 for text.", - "fieldErrors": { - "cssVariables.--c-primary": "insufficient_contrast" - } - } - ``` - AND the theme SHALL NOT be created - (Admin can choose a darker primary or lighter surface and retry) - -### Scenario 10.3 — Build-time axe-core checks - -GIVEN the LaunchPad build pipeline -WHEN `npm run build` executes -THEN a test step SHALL: - 1. Render a representative sample of widget shapes (e.g., chart, table, text, image, custom) - 2. Run axe-core automated checks against each rendered HTML - 3. Fail the build if high/critical violations are found - 4. Log a warning for medium/low violations with IDs - AND the build output SHALL include an axe-core report - -### Scenario 10.4 — Admin warned of accessibility violations on token creation - -GIVEN an admin creating an `embed_token` for a widget W - AND widget W has known accessibility violations (e.g., from a previous axe-core check) -WHEN the admin submits the token-create form -THEN the API SHALL check the widget's violation registry - AND if violations exist, respond 200 (success, but with warning) with: - ```json - { - "id": "token-1", - "name": "...", - ... - "warnings": [ - { - "level": "accessibility", - "message": "Widget 'chart' has 2 known accessibility violations (axe-core build-time check):", - "violations": [ - { - "id": "color-contrast", - "description": "Ensure the contrast between foreground and background colours meets WCAG AA thresholds", - "help": "Element <text class=\"legend\"> has contrast ratio 2.8:1. Expected ≥4.5:1" - }, - { - "id": "aria-label", - "description": "Ensure every graphical element has an accessible name", - "help": "<svg class=\"chart\"> is missing aria-label" - } - ] - } - ] - } - ``` - AND the response includes an "Acknowledge and proceed" checkbox in the admin UI - AND the admin MUST check the checkbox before creating the token (non-blocking, but requires acknowledgement) - -### Scenario 10.5 — Axe-core check results per widget - -GIVEN the admin viewing the list of available widgets -WHEN they see a widget's detail card -THEN the card SHALL display: - - Widget name + description - - Latest axe-core check date - - Number of high/critical violations (in red if > 0) - - Number of medium/low violations (in yellow if > 0) - AND a "View accessibility report" link that opens the axe-core report for that widget - -### Scenario 10.6 — Accessibility report exportable - -GIVEN an admin with token-management permission -WHEN they request an accessibility compliance report -THEN the system SHALL generate a CSV/JSON report listing: - - Widget name - - Accessibility status (compliant / violations found) - - Violation count by severity - - Affected tokens (count of embeds using this widget) - AND the report includes axe-core rule IDs and WCAG criteria references - -### Scenario 10.7 — Manual accessibility review responsibility - -GIVEN a widget with axe-core violations -WHEN the admin acknowledges and creates a token -THEN the token's audit trail SHALL record: - - "Token created for widget 'chart' with acknowledged accessibility violations: color-contrast, aria-label" - AND the responsibility for manual review (the remaining ~70% of WCAG criteria not mechanically checkable) is documented per-widget - AND the widget author is responsible for ensuring manual compliance - -### Scenario 10.8 — Keyboard navigation tested in embed iframe - -GIVEN an embedded widget in an iframe -WHEN a user navigates using keyboard alone (Tab, Shift+Tab, Enter, Escape, arrow keys) -THEN: - - All interactive elements are reachable - - No keyboard traps exist (user can Tab out) - - Focus indicator is visible and moves logically - - Modals (if any) trap focus correctly diff --git a/openspec/changes/embedded-analytics/tasks.md b/openspec/changes/embedded-analytics/tasks.md deleted file mode 100644 index 61f3d5cd2..000000000 --- a/openspec/changes/embedded-analytics/tasks.md +++ /dev/null @@ -1,338 +0,0 @@ -# Tasks — embedded-analytics - -## Infrastructure & Data Layer - -- [ ] Task 1: Create OpenRegister schemas in `lib/Settings/launchpad_register.json` for four new register types: - - `embed_token` (fields: id, name, description, tokenHash, subject, scope, hostOrigins, tenantThemeId, tokenExpiresAt, revokedAt, revocationReason, rateLimitPolicy, createdBy, createdAt, updatedAt) - - `tenant_theme` (fields: id, name, cssVariables, logoUrl, customCss, createdBy, createdAt) - - `embed_usage_event` (fields: id, tokenId, eventType, hostOrigin, userAgent, userAgentHash, viewportSize, timestamp, responseStatusCode, responseLatencyMs, correlationId) - - `signing_key` (fields: id, algorithm, publicKeyJwk, privateKeyEncrypted, status, createdAt, retiredAt) - Include seed data per design.md (3–5 objects per schema with Dutch values) - -- [ ] Task 2: Create entity mapping classes under `lib/Entity/`: - - `EmbedToken.php` (OpenRegister mapper) - - `TenantTheme.php` (OpenRegister mapper) - - `EmbedUsageEvent.php` (OpenRegister mapper) - - `SigningKey.php` (OpenRegister mapper) - Plus exception classes: `EmbedTokenException`, `InvalidTokenException`, `TokenExpiredException`, `TokenRevokedException` - -- [ ] Task 3: Create `lib/Service/JwtSigningService.php` for JWT lifecycle: - - Generate RS256 and ES256 key pairs (minimum 2048-bit RSA, P-256 for ECDSA) - - Sign JWTs with the active key (includes `kid` header) - - Verify JWT signatures against the `kid`-selected public key - - Rotate keys: mark old key `status: retiring`, new tokens sign with new key, old tokens remain valid until expiry - - Unit tests: signature verification, key rotation, algorithm selection - -- [ ] Task 4: Create `lib/Service/EmbedTokenService.php` for token persistence: - - `createToken(name, description, subject, scope, hostOrigins, tenantThemeId, tokenExpiresAt, rateLimitPolicy)`: Generate JWT + persist token record + return token (shown once) - - `getToken(id)`: Return token metadata (no JWT) - - `validateToken(jwt)`: Verify signature + expiry + revocation status - - `revokeToken(id, reason, notes)`: Set revokedAt, send notification - - `unrevokeToken(id)`: Clear revokedAt (soft revocation) - - Unit tests: token creation, validation, revocation, expiry - -- [ ] Task 5: Create `lib/Service/RateLimitService.php` (token-bucket algorithm): - - `checkRateLimit(tokenId, timestamp)`: Query token's `rateLimitPolicy`, check bucket state, return remaining quota or 429 error - - `refillBucket(tokenId)`: Update bucket based on elapsed time (token-bucket refill) - - Store bucket state in Redis or in-memory cache with TTL - - Unit tests: burst capacity, refill rate, 429 response generation - -## JWT Validation & Scope Enforcement - -- [ ] Task 6: Create `lib/Middleware/EmbedTokenMiddleware.php`: - - Extract JWT from `?token=` query parameter OR `Authorization: Bearer` header - - Validate JWT signature + expiry + revocation (REQ-EMB-002) - - Extract token subject and scope - - Store token context in the request for downstream use (tokenId, scope, hostOrigins, etc.) - -- [ ] Task 7: Create `lib/Service/ScopeEnforcementService.php` (REQ-EMB-004): - - `enforceReadOnly(request)`: If token's `scope.mode=read` and request is POST/PUT/PATCH/DELETE, respond 403 - - `enforceActionScope(request, action)`: If action not in `scope.allowedActions`, respond 403 - - `applyFilterContext(request, filterContext)`: Pin filters from token's `subject.filterContext` - - Integrate into API middleware so ALL non-GET/HEAD requests are checked - -- [ ] Task 8: Create `lib/Service/CspService.php` for CSP header generation (REQ-EMB-003): - - `generateCspHeader(hostOrigins)`: Return `Content-Security-Policy: frame-ancestors <origins>` - - `validateOrigins(origins)`: Reject wildcard, require scheme + domain - - `validateOriginFormat(origin)`: Validate RFC 3986 format - - Unit tests: CSP header syntax, origin validation, wildcard rejection - -## Public Render Route - -- [ ] Task 9: Create `lib/Controller/EmbedController.php`: - - `GET /apps/launchpad/embed/{subjectType}/{subjectId}`: Public render route - 1. Extract + validate JWT (Middleware handles this) - 2. Verify subject match (URL's subjectId == token's subject.id) - 3. Render the widget/dashboard HTML with: - - Token scope applied (filter context pinned, allowed actions visible) - - Tenant theme injected into :root CSS variables - - CSP headers emitted - 4. Write `embed_usage_event` (REQ-EMB-008) - 5. Respond 200 or appropriate error (401, 403, 429) - -- [ ] Task 10: Create `lib/Service/EmbedRenderService.php`: - - `renderWidget(widgetId, tokenScope, tenantTheme)`: Render single widget with scope + theme applied - - `renderDashboard(dashboardId, tokenScope, filterContext, tenantTheme)`: Render dashboard with scope + theme applied - - Reuse existing widget/dashboard rendering code (no fork) - - Wrap output with CSP headers, no navigation chrome - -## Theming & Accessibility - -- [ ] Task 11: Create `lib/Service/TenantThemeService.php`: - - `createTheme(name, cssVariables, logoUrl, customCss)`: Validate CSS, persist theme - - `validateCss(customCss)`: Reject non-:root selectors (CSSTidy or simple regex) - - `validateContrastRatio(primaryColor, surfaceColor)`: Use WCAG luminance formula, enforce 4.5:1 - - Unit tests: CSS validation, contrast computation, color parsing - -- [ ] Task 12: Add axe-core integration to build pipeline: - - In `npm run build`, add a linting step that: - 1. Renders representative widget shapes (chart, table, text, image) - 2. Runs axe-core accessibility checks against the rendered HTML - 3. Generates a report (axe-results.json) - 4. Fails build if high/critical violations are found - 5. Warns on medium/low violations - - Create `src/axe-core-check.js` script - - Output report saved to `docs/accessibility/axe-results.json` for review - -- [ ] Task 13: Modify dashboard/widget rendering to accept token context: - - Add optional `embedContext` parameter to widget/dashboard render functions - - If `embedContext` present, apply theme CSS variables, scope restrictions, filter pinning - - Maintain backward compatibility (no context = normal in-app rendering) - -- [ ] Task 14: Create `src/composables/useEmbedContext.js`: - - Detect if the current render is in embed mode (check for token in parent postMessage or in render context) - - Provide theme CSS variables to Vue components - - Apply scope restrictions (hide disallowed actions, disable exports, etc.) - - Relay events back to parent via postMessage (REQ-EMB-006) - -## Admin UI — Token Management - -- [ ] Task 15: Create `src/components/EmbedTokenManager.vue`: - - List view: Table of all tokens with name, status, subject, created, last-used, revoked date, actions - - Create flow: Form for name, description, subject (widget/dashboard picker), scope (mode + filters + actions), hostOrigins, tenantThemeId, tokenExpiresAt, rateLimitPolicy - - Display: Show raw JWT once, with "keep this safe" warning, "copy" button - - Detail view: Full token metadata, re-issue/revoke buttons, usage stats link - - Edit: Update name, description, rateLimitPolicy (scope + subject immutable) - - Revoke dialog: Dropdown for reason, text field for notes, confirm - - Actions: Re-issue, revoke/un-revoke, view usage - -- [ ] Task 16: Create `src/components/TenantThemeManager.vue`: - - List view: Table of themes with name, primary colour preview, logo, created date - - Create flow: Form for name, CSS variables (editable text fields with labels), logoUrl uploader, customCss (textarea with :root validation) - - Live preview: Show selected colours applied to sample widget - - Edit: Update name, variables, logo, customCss - - Delete: Warn if theme is in-use by tokens - - Copy button: Export JSON for documentation - -- [ ] Task 17: Create `src/components/EmbedUsageReport.vue`: - - Summary card: Total pageviews (7d), status, last activity - - Pageviews chart: Line chart by date - - Host origin distribution: Bar chart or pie - - Viewport size breakdown: Stacked bar (small/medium/large) - - Browser distribution: Bar chart (top 10 user-agents) - - Interaction breakdown: Counters for filterApplied, drillDown, export - - Rate limit breaches table (if any): Date, count, percentage of quota - - Export button: Download CSV of underlying events (unless org telemetry disabled) - -- [ ] Task 18: Create `src/components/EmbedTokenForm.vue` (sub-component): - - Reusable form for create + edit flows - - Name/description fields - - Subject picker (dropdown of widgets + dashboards) - - Filter context picker (if subject is dashboard with filterable dimensions) - - Scope editor: - - Radio buttons: Read vs Read-with-Interactions - - Checkboxes for allowedActions (interact, export, drillDown) - - Multi-select for allowedFilters - - HostOrigins multi-input (add/remove origins with validation) - - TenantThemeId picker dropdown - - TokenExpiresAt date picker (optional) - - RateLimitPolicy fields (requestsPerMinute, burstSize) - - Help text + CSP preview button (shows resulting CSP header) - - Submit + cancel buttons - -## JS-SDK - -- [ ] Task 19: Create `@launchpad/embed-sdk` package structure: - - `src/LaunchPadEmbed.js` — main entry point (render, on, off, resize methods) - - `src/postMessage.js` — Origin verification + handshake helpers - - `src/types.ts` — TypeScript definitions (EmbedConfig, EmbedInstance, event types) - - `dist/embed-sdk.esm.js` (ESM build) - - `dist/embed-sdk.umd.js` (UMD build) - - `package.json` with exports, version matching app version - -- [ ] Task 20: Implement `LaunchPadEmbed.render(container, config)` (REQ-EMB-006): - - Accept: `{token, subjectType, subjectId, tenantThemeId (optional)}` - - Create iframe with `src="/apps/launchpad/embed/{subjectType}/{subjectId}"` - - Insert iframe into container - - Wait for `load` event - - Perform postMessage handshake: POST token to iframe (origin verification on both sides) - - Return promise that resolves when 'embed-ready' message received - - Reject promise if errors occur - -- [ ] Task 21: Implement event relay in SDK (REQ-EMB-006): - - `.on(eventType, handler)` registers listener for filterApplied, drillDown, export, error, etc. - - Listen for postMessage from iframe - - Invoke registered handlers with event payload - - `.off(eventType, handler)` unregisters listener - - Support multiple listeners per event - -- [ ] Task 22: Implement `.resize()` method (REQ-EMB-006): - - Read iframe's container dimensions - - Post resize message to iframe with new width/height - - Wait for 'embed-resized' message - - Return promise that resolves when resize complete - -- [ ] Task 23: Create iframe-side entry point for SDK (`src/embed-entry.js`): - - Listen for postMessage from parent (token injection) - - Verify parent origin against allowed hostOrigins (decoded from token) - - Store token in secure context - - Render widget/dashboard using EmbedRenderService - - Relay interaction events back to parent via postMessage - - Listen for resize messages and re-measure - -- [ ] Task 24: Build and publish SDK: - - Create `.github/workflows/publish-sdk.yml` to build + publish @launchpad/embed-sdk to npm on release - - Package.json versions match app version (synchronized releases) - - README with examples (vanilla JS, ESM, TypeScript) - -## Rate Limiting & Revocation - -- [ ] Task 25: Implement revocation cache + propagation: - - Store revocation status in Redis (or in-memory cache with 60s TTL) - - On token revocation, immediately set cache entry `revoked:<tokenId> = true` - - Render route checks cache first; if miss, queries database - - Implement purge-cache action: Broadcast cache-clear message to all workers (Redis pub/sub) - - Unit tests: cache hits, TTL expiry, database fallback - -- [ ] Task 26: Integrate RateLimitService into render route: - - In EmbedController, call `RateLimitService.checkRateLimit(tokenId, now)` - - If 429, write usage event with 429 status - - Return 429 response with Retry-After header - - Include RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset headers - -- [ ] Task 27: Create revocation UI flow in EmbedTokenManager: - - Revoke button → confirmation dialog with reason dropdown + notes textarea - - POST `/api/embed-tokens/{id}/revoke` with reason + notes - - Show success message - - Update token list (status changes to REVOKED) - - Un-revoke button (clear revokedAt, show confirmation) - -## Usage Telemetry - -- [ ] Task 28: Implement usage event capture (REQ-EMB-008): - - In EmbedController render route, after rendering widget: - 1. Extract host origin from Origin or Referer header - 2. Parse user-agent: extract browser family + major version - 3. Compute user-agent hash: sha256(full UA string) - 4. Compute viewport bucket: small/medium/large from request context (if available from SDK) - 5. Measure response latency - 6. Create `embed_usage_event` row with all fields - - Unit tests: PII minimisation (no IP, no full UA, no end-user identifier) - -- [ ] Task 29: Create usage report API: - - `GET /api/embed-tokens/{id}/usage` — Summary stats + aggregated events (by date, by host origin, by viewport, by browser) - - Respond with JSON suitable for charts (date series, bar data, pie data) - - No individual-user rows (aggregation only) - -- [ ] Task 30: Implement telemetry kill-switch: - - Add org setting: `embed_telemetry_enabled` (boolean, default true) - - In render route, check setting before writing `embed_usage_event` - - If disabled, skip event capture (no row written) - - Audit log when toggle is changed - - Admin UI: Settings page checkbox for "Collect embed usage telemetry" - -## Testing & Documentation - -- [ ] Task 31: PHPUnit tests for JWT signing: - - Sign a JWT with RS256, verify signature - - Verify JWT with wrong key fails - - Verify expired JWT rejected - - Verify revoked token rejected - - Key rotation: old key still verifies old tokens, new key signs new tokens - -- [ ] Task 32: PHPUnit tests for token lifecycle: - - Create token → retrieve JWT (once) - - Re-retrieve → no JWT - - Update token (name, rateLimitPolicy) - - Revoke token → subsequent requests rejected - - Un-revoke token → requests accepted again - -- [ ] Task 33: PHPUnit tests for scope enforcement: - - Read-only token rejects POST/PUT/PATCH/DELETE - - Read-with-interactions token allows pinned filters - - Action scope: export allowed only if in allowedActions - - Filter scope: filter dimensions restricted to allowedFilters - -- [ ] Task 34: Vitest tests for JS-SDK: - - Render method creates iframe, performs postMessage handshake - - Event listeners registered + invoked on iframe messages - - Resize method posts message + resolves promise - - Origin verification prevents cross-origin leaks - - Multiple embeds on same page are independent - -- [ ] Task 35: Playwright integration tests: - - Create embed token via admin UI - - Render widget in iframe with token (public render route) - - Verify CSP headers present - - Verify filter interaction works (drill-down) - - Verify read-only token blocks write operations - - Verify theme CSS variables applied - - Verify rate limiting (429 after quota exceeded) - - Verify revocation takes effect within 60s - -- [ ] Task 36: Create documentation: - - `docs/embed/overview.md` — Purpose + use cases + security model - - `docs/embed/admin-guide.md` — Token creation, revocation, theming, usage analytics - - `docs/embed/integration-guide.md` — How to integrate SDK (iframe + JS-SDK form factors) - - `docs/embed/sdk-reference.md` — JS-SDK API (render, on, resize, event types) - - `docs/embed/troubleshooting.md` — Common issues (CSP errors, CORS, origin mismatch) - -- [ ] Task 37: i18n for new UI strings: - - Token manager: create, revoke, re-issue, usage, accessibility warning - - Theme manager: create, edit, delete, preview - - Admin notification: token revoked, policy updated - - All strings in both NL (Dutch) + EN (English) - - Add to `src/translations/nl.json` + `src/translations/en.json` - -## Quality & Integration - -- [ ] Task 38: ESLint clean on new files: - - Run `npm run lint` on all new/modified Vue + JS files - - Fix any warnings or errors before merging - - Ensure axe-core check output is clean (no accessibility violations) - -- [ ] Task 39: Security audit checklist: - - JWT signature verification is unconditional (no bypass paths) - - Scope enforcement at API tier (not UI) - - CSP frame-ancestors + Fetch-Metadata headers present - - No IP addresses captured in telemetry - - Rate limiting prevents abuse - - Revocation propagates within 60s - - Read-only tokens cannot mutate state - - Wildcard origins rejected at creation time - -- [ ] Task 40: Integration with existing LaunchPad features: - - Dashboards display "Share" → includes "Create embed token" action alongside existing share modes - - Widgets display "Embed" button → quick token creation for single widget - - Admin Settings → "Embed Tokens" section with manager + themes - - Audit log records token lifecycle (create, revoke, re-issue) - -## Verification - -`openspec validate` exits clean. Embed tokens are creatable via admin UI, render publicly with CSS variables + scope enforcement, propagate revocation within 60s, and write auditable telemetry. - -## Tests (company-wide ADR-009) - -- PHPUnit: JWT signing, token lifecycle, scope enforcement, rate limiting, CSP validation -- Vitest: JS-SDK render, event relay, origin verification -- Playwright: End-to-end from token creation to rendered widget, filter interaction, revocation propagation - -## Documentation (company-wide ADR-010) - -- User guide: Token creation, revocation, theme management -- Developer guide: SDK integration (iframe + JS-SDK), event handling, CSP configuration -- Architecture: JWT signing, scope model, telemetry PII minimisation - -## i18n (company-wide ADR-005) - -Dutch (NL) + English (EN) parity for all new UI strings and user-facing messages. diff --git a/openspec/changes/engagement-activity-digest/tasks.md b/openspec/changes/engagement-activity-digest/tasks.md deleted file mode 100644 index e59c333e1..000000000 --- a/openspec/changes/engagement-activity-digest/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: engagement-activity-digest - -- [ ] 1. Add four `ActivitySettings` classes under `lib/Activity/Settings/` with the defaults in D1 and register them in `appinfo/info.xml`. Verify: PHPUnit per class and app-info validation. -- [x] 2. Emit `dashboard_shared` from `DashboardShareService` on share creation to the resolved recipients. Verify: PHPUnit with a mocked publisher. -- [x] 3. Emit `dashboard_published` from `DashboardService` on publication, including the first surfacing of a scheduled dashboard, once. Verify: PHPUnit. -- [x] 4. Emit `dashboard_updated` for shared and group dashboards through `DebounceHelper`, once per dashboard per 24 hours. Verify: PHPUnit with a fixed clock. -- [ ] 5. Integration check: with daily batching, a share queues an activity mail row for the recipient. Verify: an integration test or a documented manual run against the dev instance. -- [ ] 6. Add `nl` and `en` strings for the setting labels, fold the delta into `openspec/specs/activity-feed-integration/spec.md` on archive, and set e-digest to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/engagement-announcements/tasks.md b/openspec/changes/engagement-announcements/tasks.md deleted file mode 100644 index 2fdb42929..000000000 --- a/openspec/changes/engagement-announcements/tasks.md +++ /dev/null @@ -1,23 +0,0 @@ -# Tasks: engagement-announcements - -## Backend - -- [ ] 1. Add the two tables in one migration with builders, entities and mappers (including `notified_at`). Verify: migration test. -- [ ] 2. Seed `announcement.manage`, `announcement.read`, `announcement.follow`, `announcement.comment` and add the `announcement_editor_groups` admin setting. Verify: action-matrix test. -- [ ] 3. Implement `AnnouncementService` (create, update, publish, visibleTo, drafts for authors, notice end time required, reach count). Verify: PHPUnit. -- [ ] 4. Add `AnnouncementController` routes for list, get, create, update, publish, delete, follow and unfollow, each with the action check and no IDOR (visibility checked per id). Verify: PHPUnit and route-reachability. -- [ ] 5. Wire likes and comments through `ICommentsManager` with object type `launchpad_announcement` and the access check. Verify: PHPUnit with the comments manager. -- [ ] 6. Add `announcement_published` to `lib/Notification/Notifier.php` and `AnnouncementNotifyJob` to `appinfo/info.xml`. Verify: PHPUnit that followers are notified once. - -## Frontend - -- [ ] 7. Add the `announcements` widget to `src/constants/widgetRegistry.js` with card, category filter, like and comment counts. Verify: Vitest. -- [ ] 8. Build the announcement editor modal with the preview step, reach count and "Preview as". Verify: Vitest and an axe check. -- [ ] 9. Add the notice banner region to `src/views/WorkspaceApp.vue` with dismiss for dismissible notices. Verify: Vitest. -- [ ] 10. Add follow and unfollow per category in the widget. Verify: Vitest. - -## Close - -- [ ] 11. Add the three demo announcements. Verify: PHPUnit on the showcase. -- [ ] 12. Playwright for the notice flow and a liked, commented news item. -- [ ] 13. Add `nl` and `en` strings, copy the spec to `openspec/specs/announcements/spec.md` on archive, and set e-announcements, d-news-preview and e-maintenance to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/engagement-communities/tasks.md b/openspec/changes/engagement-communities/tasks.md deleted file mode 100644 index 81add79bb..000000000 --- a/openspec/changes/engagement-communities/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: engagement-communities - -- [ ] 1. Add `pinned_communities` to `lib/Db/AdminSettingKey.php` with token validation, and `talkEnabled` plus the pinned list to `lib/Service/InitialStateBuilder.php`. Verify: PHPUnit and the initial-state contract test. -- [ ] 2. Build the `communities` renderer over Talk's listed-room, room and join endpoints, with pinned first, joined marks and the empty state. Verify: Vitest with mocked Talk. -- [ ] 3. Register the widget and its form (title, show only pinned) in `src/constants/widgetRegistry.js` and the manifest. Verify: manifest check and Vitest. -- [ ] 4. Add the pinned-communities admin section. Verify: Vitest. -- [ ] 5. Playwright with Talk enabled: join an open conversation from the widget. -- [ ] 6. Add `nl` and `en` strings, copy the spec to `openspec/specs/communities-widget/spec.md` on archive, and set e-communities to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/fix-group-dashboard-admin-auth-attribute/specs/dashboards/spec.md b/openspec/changes/fix-group-dashboard-admin-auth-attribute/specs/dashboards/spec.md deleted file mode 100644 index 4c86d69b5..000000000 --- a/openspec/changes/fix-group-dashboard-admin-auth-attribute/specs/dashboards/spec.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -capability: dashboards -delta: true -status: draft ---- - -# Dashboards — Group-Shared CRUD Authorization Attribute - -## MODIFIED Requirements - -### Requirement: REQ-DASH-014 Group-shared dashboard CRUD is admin-only and declared as such - -Group-shared dashboard CRUD endpoints (`createGroup`, `updateGroup`, `deleteGroup`, `setGroupDefault`) MUST be reachable only by Nextcloud global administrators, AND this restriction MUST be declared via the -`#[AuthorizedAdminSetting]` PHP attribute rather than via an in-body -`isAdmin()` check layered on a `#[NoAdminRequired]` attribute. The -attribute-level declaration is enforced by Nextcloud's own middleware -before the controller method body runs, and is the mechanically -verifiable form per ADR-005's auth-attribute contract. - -#### Scenario: Non-admin cannot create a group-shared dashboard - -- **GIVEN** an authenticated non-admin user "bob" -- **WHEN** bob sends `POST /api/dashboards/group/{groupId}` -- **THEN** the framework MUST reject the request with HTTP 403 before the - controller body's business logic runs -- **AND** no dashboard MUST be created - -#### Scenario: Non-admin cannot update, delete, or set-default a group-shared dashboard - -- **GIVEN** an authenticated non-admin user "bob" -- **WHEN** bob sends `PUT /api/dashboards/group/{groupId}/{uuid}`, - `DELETE /api/dashboards/group/{groupId}/{uuid}`, or - `POST /api/dashboards/group/{groupId}/default` -- **THEN** each request MUST be rejected with HTTP 403 by the framework - attribute check -- **AND** no mutation MUST occur - -#### Scenario: Admin can perform all four group-shared operations - -- **GIVEN** an authenticated Nextcloud global admin -- **WHEN** the admin calls `createGroup`, `updateGroup`, `deleteGroup`, or - `setGroupDefault` -- **THEN** each call MUST succeed exactly as it did before this change -- **AND** the response payloads MUST be unchanged - -#### Scenario: Controller method carries the correct attribute - -- **GIVEN** `lib/Controller/DashboardApiController.php` -- **WHEN** `createGroup()`, `updateGroup()`, `deleteGroup()`, and - `setGroupDefault()` are inspected -- **THEN** each MUST carry `#[AuthorizedAdminSetting(Application::APP_ID)]` -- **AND** none MUST carry `#[NoAdminRequired]` diff --git a/openspec/changes/fix-group-dashboard-admin-auth-attribute/tasks.md b/openspec/changes/fix-group-dashboard-admin-auth-attribute/tasks.md deleted file mode 100644 index 254902261..000000000 --- a/openspec/changes/fix-group-dashboard-admin-auth-attribute/tasks.md +++ /dev/null @@ -1,70 +0,0 @@ -# Tasks — fix-group-dashboard-admin-auth-attribute - -## DashboardApiController - -- [ ] Task 1: In `lib/Controller/DashboardApiController.php`, import - `OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting` and - `OCA\LaunchPad\Settings\LaunchPadAdmin` (or - `OCA\LaunchPad\AppInfo\Application` for `Application::APP_ID`) alongside - the existing `NoAdminRequired` import. -- [ ] Task 2: Replace `#[NoAdminRequired]` with - `#[AuthorizedAdminSetting(Application::APP_ID)]` on `createGroup()` - (currently line 916). -- [ ] Task 3: Replace `#[NoAdminRequired]` with - `#[AuthorizedAdminSetting(Application::APP_ID)]` on `updateGroup()` - (currently line 1026). -- [ ] Task 4: Replace `#[NoAdminRequired]` with - `#[AuthorizedAdminSetting(Application::APP_ID)]` on `deleteGroup()` - (currently line 1090). -- [ ] Task 5: Replace `#[NoAdminRequired]` with - `#[AuthorizedAdminSetting(Application::APP_ID)]` on `setGroupDefault()` - (currently line 1143). -- [ ] Task 6: Remove the redundant in-body `$this->dashboardService->isAdmin(...)` - + `ResponseHelper::forbidden(message: DashboardService::ERR_FORBIDDEN_NOT_ADMIN)` - block from each of the four methods above, now that the attribute-level - middleware enforces the same check. If PHPUnit coverage asserts the - in-body 403 message text, update those tests to assert on the - framework's `AuthorizedAdminSetting` 403 response instead. -- [ ] Task 7: Update the docblocks above `createGroup()` (lines ~902-905), - `updateGroup()`, `deleteGroup()`, and `setGroupDefault()` that currently - describe the `#[NoAdminRequired]` + in-body-check pattern as the - intentional authorization point — remove the "gate-route-auth / - gate-semantic-auth" workaround language now that the attribute itself - carries the authorization. -- [ ] Task 8: Confirm `$this->dashboardService->isAdmin()` still has at - least one other caller (e.g. `PageController` per the existing grep) so - it is not left dead after removing these four call sites; if it becomes - unused, remove the method per `hydra-gate-stub-scan`. - -## AdminSettingsController - -- [ ] Task 9: In `lib/Controller/AdminSettingsController.php`, import - `OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting` and the app's - `Application` class (or `LaunchPadAdmin` settings class, matching the - pattern in `AdminController.php`). -- [ ] Task 10: Add `#[AuthorizedAdminSetting(Application::APP_ID)]` above - `listGroups()` (currently line 89). -- [ ] Task 11: Add `#[AuthorizedAdminSetting(Application::APP_ID)]` above - `updateGroupOrder()` (currently line 162). -- [ ] Task 12: Leave the existing private `assertAdmin()` helper and its - call sites in place as defense-in-depth (matching the pattern already - used in `AdminOrgNavigationController.php` and `AdminController.php`, - where `AuthorizedAdminSetting`-annotated methods also call the inline - guard) — do not remove it. - -## Verification - -- [ ] Task 13: Run `hydra-gate-semantic-auth` (or the equivalent - `run-hydra-gates.sh` invocation) against the diff and confirm all six - methods now pass with no findings. -- [ ] Task 14: Re-run the existing PHPUnit suite for - `DashboardApiControllerTest` / `AdminSettingsControllerTest` (or their - equivalents) and update any assertions that depended on the removed - in-body 403 message. -- [ ] Task 15: Manually verify via curl/Newman that a non-admin - authenticated user still receives HTTP 403 on - `POST /api/dashboards/group/{groupId}`, - `PUT /api/dashboards/group/{groupId}/{uuid}`, - `DELETE /api/dashboards/group/{groupId}/{uuid}`, - `POST /api/dashboards/group/{groupId}/default`, - `GET /api/admin/settings/groups`, and the group-order update endpoint. diff --git a/openspec/changes/fix-l10n-domain-mismatch-mydash-calls/tasks.md b/openspec/changes/fix-l10n-domain-mismatch-mydash-calls/tasks.md deleted file mode 100644 index 77aec0d81..000000000 --- a/openspec/changes/fix-l10n-domain-mismatch-mydash-calls/tasks.md +++ /dev/null @@ -1,66 +0,0 @@ -# Tasks — fix-l10n-domain-mismatch-mydash-calls - -## Verify scope - -- [ ] Task 1: Re-run `grep -rnoP "(?<![A-Za-z_])t\('mydash'" src --include=*.vue --include=*.js` and - `grep -rnoP "(?<![A-Za-z_])n\('mydash'" src --include=*.vue --include=*.js` - against current HEAD to confirm the exact call-site count and file list - before editing (167 calls / 20 files at time of writing; do not trust a - stale count if other work has landed in the meantime). - -## Fix call sites - -- [ ] Task 2: In each of the 20 affected files, change every - `t('mydash', …)` (and `n('mydash', …)` if any exist) call to - `t('launchpad', …)` / `n('launchpad', …)`. Do this as a literal string - substitution only — do not alter the translated text, placeholders, or - argument order. - - `src/dialogs/RolePermissionDeleteDialog.vue` (4 calls) - - `src/dialogs/PublicSharePasswordDialog.vue` (4 calls) - - `src/components/admin/AdminDemoData.vue` (8 calls) - - `src/views/Views.vue` (2 calls) - - `src/views/DashboardPublicShareView.vue` (11 calls) - - `src/dialogs/RoleLayoutDefaultEditorDialog.vue` (16 calls) - - `src/dialogs/RoleLayoutDefaultDeleteDialog.vue` (4 calls) - - `src/components/DashboardConfigModal.vue` (5 calls) - - `src/components/admin/RoleLayoutDefaultsSection.vue` (9 calls) - - `src/components/admin/BeheerTabs.vue` (1 call) - - `src/components/admin/OrgNavigationEditorRow.vue` (2 calls) - - `src/components/admin/PrometheusMetricsPanel.vue` (3 calls) - - `src/components/admin/ConditionalVisibilityOverview.vue` (10 calls) - - `src/components/admin/LegacyWidgetBridgeToggle.vue` (3 calls) - - `src/components/admin/tabs/TemplatesPage.vue` (25 calls) - - `src/components/admin/HealthPanel.vue` (4 calls) - - `src/components/admin/DashboardSharingPolicy.vue` (8 calls) - - `src/components/Widgets/VisibilityRulesModal.vue` (27 calls) - - `src/components/admin/AdminSettings.vue` (12 calls) - - `src/components/Widgets/WidgetContextMenu.vue` (1 call) -- [ ] Task 3: Confirm every English source string used in these 20 files - already exists as a key in `l10n/en.json` under the `"launchpad"` - domain content (spot-check a sample per file) — if any string is - genuinely new/missing from the bundle, flag it separately rather than - silently shipping an unresolvable key. - -## Prevent regression - -- [ ] Task 4: Add a lint guard (new script under `scripts/`, e.g. - `scripts/lint-translation-domain.js`, wired into the existing - `npm run lint` chain alongside `lint:initial-state`) that scans `src/` - for `t('<literal>'` / `n('<literal>'` calls where `<literal>` is not - `'launchpad'`, and fails with file:line output if any are found. -- [ ] Task 5: Add the new script to `package.json`'s `lint` script - (`"lint": "eslint src && npm run check:manifest && npm run lint:initial-state && npm run lint:translation-domain"`). - -## Verification - -- [ ] Task 6: Run `npm run lint` and confirm the new guard passes with - zero violations after Task 2's fixes. -- [ ] Task 7: Manually verify in a Dutch-locale (`nl`) Nextcloud session: - open the admin Health panel (`HealthPanel.vue`) and the widget - right-click context menu (`WidgetContextMenu.vue`) and confirm the - previously-English "Health"/"Healthy"/"Degraded" and "Visibility - rules…" strings now render in Dutch. -- [ ] Task 8: Re-run the Vitest suite (`npm run test`) — component tests - that snapshot or assert on rendered English text for these components - must still pass since the English fallback text is unchanged for the - `en` locale; only non-English locales change behaviour. diff --git a/openspec/changes/fix-people-widget-unbounded-user-scan/specs/people-widget/spec.md b/openspec/changes/fix-people-widget-unbounded-user-scan/specs/people-widget/spec.md deleted file mode 100644 index 2aad4cbdd..000000000 --- a/openspec/changes/fix-people-widget-unbounded-user-scan/specs/people-widget/spec.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -capability: people-widget -delta: true -status: draft ---- - -# People Widget — Bounded Candidate Resolution - -## MODIFIED Requirements - -### Requirement: REQ-PPL-007 Candidate resolution MUST be bounded by the requested page - -`PeopleWidgetService::resolveCandidates()` MUST NOT materialize the full -Nextcloud user directory when resolving candidates for a request that has -no `group` filter. The number of `IUser` objects instantiated from -`IUserManager` MUST scale with the requested `limit`/`offset` window -(capped at `PeopleWidgetService::MAX_LIMIT`), not with the total number of -accounts on the instance. - -#### Scenario: Unfiltered People widget on a large instance fetches a bounded set - -- **GIVEN** a Nextcloud instance with 5,000 user accounts -- **AND** a People widget configured with no `group` filter and - `limit=10`, `offset=0` -- **WHEN** `GET /api/people?limit=10&offset=0` is called -- **THEN** `IUserManager::search()` (or equivalent) MUST be invoked with a - bounded `$limit`/`$offset`, not an unbounded full-table search -- **AND** the response MUST still contain the correct `users`, `total`, - and `hasMore` fields - -#### Scenario: Pagination still returns correct total and hasMore - -- **GIVEN** the same 5,000-user instance and no `group` filter -- **WHEN** the caller requests successive pages (`offset=0,10,20,...`) -- **THEN** `total` MUST reflect the true count of matching (enabled, per - `excludeDisabled`) users -- **AND** `hasMore` MUST correctly indicate whether further pages exist - -#### Scenario: Group-filtered resolution is unaffected - -- **GIVEN** a People widget configured with a `group` filter -- **WHEN** candidates are resolved -- **THEN** behaviour MUST be unchanged from before this change — - `IGroupManager::get($gid)->getUsers()` per group value, deduplicated by - UID diff --git a/openspec/changes/fix-people-widget-unbounded-user-scan/tasks.md b/openspec/changes/fix-people-widget-unbounded-user-scan/tasks.md deleted file mode 100644 index 504229fa0..000000000 --- a/openspec/changes/fix-people-widget-unbounded-user-scan/tasks.md +++ /dev/null @@ -1,40 +0,0 @@ -# Tasks — fix-people-widget-unbounded-user-scan - -## PeopleWidgetService - -- [ ] Task 1: In `lib/Service/PeopleWidgetService::resolveCandidates()` - (currently lines 277-323), replace the unconditional - `$this->userManager->search(pattern: '')` fallback (line 285) with a - bounded call. `IUserManager::search()` accepts `$limit`/`$offset` — pass - through enough of the caller's pagination window (e.g. `offset + limit`, - capped at `self::MAX_LIMIT` plus one extra record so `hasMore` can still - be computed) instead of fetching every account. -- [ ] Task 2: Because `excludeDisabled` filtering and `sortBy` both - currently run in `listUsers()` *after* `resolveCandidates()` returns - (lines 178-186), confirm the bounded fetch still yields correct results - for `sortBy=displayName`/`sortBy=group` — if PHP-side sorting requires a - larger candidate window than the raw page size to stay correct (e.g. - disabled users interleaved with enabled ones), document the minimum - safe over-fetch multiplier in a code comment and size the bounded call - accordingly, or fall back to the full scan only when - `excludeDisabled=false` AND `sortBy` requires global ordering. -- [ ] Task 3: Update the `resolveCandidates()` docblock (lines 264-269) to - describe the new bounded no-group-filter path instead of documenting the - full scan as accepted behaviour. -- [ ] Task 4: Add/extend a PHPUnit test in - `tests/Unit/Service/PeopleWidgetServiceTest.php` (or the equivalent test - file) asserting that with no `group` filter and a large simulated user - count, `IUserManager::search()` is called with a bounded `$limit`/ - `$offset` rather than an unbounded call — mock `IUserManager` and assert - on the call arguments. -- [ ] Task 5: Re-run the existing People-widget PHPUnit suite and the - `people-widget` Newman/Postman collection entries (if present) to - confirm `total`/`hasMore`/pagination semantics are unchanged from the - caller's point of view. - -## Verification - -- [ ] Task 6: Manually verify via `php occ` or a seeded test instance with - >100 users that `GET /api/people?limit=10` no longer instantiates the - full user list — confirm via a temporary `error_log`/Xdebug count or a - PHPUnit spy on `IUserManager::search()` call arguments. diff --git a/openspec/changes/governance-rest-api-reference/design.md b/openspec/changes/governance-rest-api-reference/design.md deleted file mode 100644 index fc80756bf..000000000 --- a/openspec/changes/governance-rest-api-reference/design.md +++ /dev/null @@ -1,39 +0,0 @@ -# Design: governance-rest-api-reference - -Read at development `d767c282`. - -## Context - -- `appinfo/routes.php` registers 181 route entries under `/index.php/apps/launchpad/`, served by the controllers in `lib/Controller/` (for example `DashboardApiController`, `WidgetApiController`, `TileApiController`, `DashboardShareApiController`, `PublicShareController`). They follow ADR-002 (hydra `openspec/architecture/adr-002-api.md`: `/index.php/apps/{app}/api/{resource}`, standard verbs, `message` on errors, Nextcloud authentication only). -- Controllers carry auth attributes (`#[NoAdminRequired]`, `#[PublicPage]`, `#[AuthorizedAdminSetting]`) and `@spec` docblocks, but no response shape annotations. -- `composer.json` defines `check:strict` as a loop over lint, phpcs, phpmd, psalm, phpstan and tests. `scripts/` holds the repo's own checks (`check-manifest.js`, `lint-initial-state.php`). -- The documentation site is Docusaurus under `docs/` (`docs/docusaurus.config.js`). -- Nextcloud apps publish `openapi.json` at their repository root; Nextcloud's own dashboard app does (`apps/dashboard/openapi.json`). - -## Decisions - -### D1: Generated, never hand-written - -Task 1 tries `nextcloud/openapi-extractor` on three LaunchPad controllers. If it documents LaunchPad's index.php JSON routes with their attributes, it is the generator. If it does not, `scripts/generate-openapi.php` reads `appinfo/routes.php`, reflects each controller method's parameters, attributes and `@return` or a `@psalm-return` shape, and writes OpenAPI 3.1. Either way the file is an output, regenerated by one composer script. - -### D2: Two stability levels - -Every operation carries `x-launchpad-stability: public` or `internal`. Public in this change: dashboard CRUD and listing, placements and tiles, sharing, public links, export and import. Everything else starts internal. A public operation changes only with a deprecation notice in the changelog; internal ones may change freely. - -### D3: The drift check - -`composer lint:openapi` regenerates the file into a temporary path and fails when it differs from the committed `openapi.json`, or when a route name in `routes.php` has no operation. It joins `check:strict`, so a new route without documentation fails locally and in CI. - -### D4: Authentication is documented, not added - -The reference documents Basic authentication with a Nextcloud app password, as Nextcloud supports for app routes, and the `OCS-APIRequest: true` header. No new token flow (ADR-002). - -## Declarative-vs-imperative decision - -Documentation generated from code; no schema register involved. - -## Test plan - -- The drift check itself: a PHPUnit or script test with a fixture routes file where one route lacks an operation. -- Validate `openapi.json` against the OpenAPI 3.1 schema in CI. -- Manual check recorded in the PR: `curl -u user:app-password https://<instance>/index.php/apps/launchpad/api/dashboards` matches the documented response shape. diff --git a/openspec/changes/governance-rest-api-reference/tasks.md b/openspec/changes/governance-rest-api-reference/tasks.md deleted file mode 100644 index f071489a6..000000000 --- a/openspec/changes/governance-rest-api-reference/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: governance-rest-api-reference - -- [ ] 1. Try `nextcloud/openapi-extractor` on `DashboardApiController`, `WidgetApiController` and `TileApiController`; record in design.md which generator is used. Verify: the generated fragment lists those routes. -- [ ] 2. Add response and request shape annotations to the public controllers (dashboards, placements, tiles, sharing, public links, export and import). Verify: psalm and phpstan stay green. -- [ ] 3. Generate `openapi.json` with `x-launchpad-stability` on every operation. Verify: the file validates as OpenAPI 3.1. -- [ ] 4. Add `composer lint:openapi` (regenerate and compare, every route documented) to `check:strict`. Verify: a fixture with an undocumented route fails. -- [ ] 5. Add the API page to the Docusaurus site with authentication instructions. Verify: the docs build. -- [ ] 6. Copy the spec to `openspec/specs/rest-api-reference/spec.md` on archive and set d-rest-api to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/grid-bottom-append-placement/specs/grid-layout/spec.md b/openspec/changes/grid-bottom-append-placement/specs/grid-layout/spec.md deleted file mode 100644 index 25ddd4a72..000000000 --- a/openspec/changes/grid-bottom-append-placement/specs/grid-layout/spec.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -capability: grid-layout -delta: true -status: draft ---- - -# Grid Layout — Delta from change `grid-bottom-append-placement` - -## MODIFIED Requirements - -### Requirement: REQ-GRID-006 Widget Auto-Layout (bottom-append placement) - -When a new widget is added to a dashboard, the system MUST place it in a fresh row directly below all existing widgets, without overlapping any existing widget and without moving any existing widget. The algorithm MUST be: - -1. **Compute the bottom edge** — for every existing placement compute `gridY + gridHeight`; the new widget's `y` MUST be the maximum of these values (the lowest occupied bottom edge). A placement missing `gridY` contributes `0`; a placement missing `gridHeight` contributes height `1`. -2. **Anchor to the left** — the new widget's `x` MUST be `0`. -3. **Empty dashboard** — when there are no existing placements, the new widget MUST be placed at `(x: 0, y: 0)`. - -Existing widgets MUST NOT be moved — there is no push-down — and the helper's `pushed` array MUST always be empty. Default size when the caller omits `w`/`h` MUST be `w=4, h=4`. Position writes MUST trigger the persistence path of REQ-GRID-005. - -This requirement deliberately replaces the former "GridStack auto-position + top-left/push-down fallback" rule, which reordered the user's existing layout on every add once the visible rows filled up. The shipped `placeNewWidget(spec, placements, options?)` helper implements bottom-append; this requirement is the authoritative description of that behaviour. - -#### Scenario: Append below the only existing widget - -- **GIVEN** a dashboard with one widget at `(x:0, y:0, w:6, h:4)` -- **WHEN** a new 4×4 widget is added -- **THEN** it MUST be placed at `(x:0, y:4)` (a fresh row below the existing widget) -- **AND** the existing widget MUST NOT be moved -- **AND** the returned `pushed` array MUST be empty - -#### Scenario: Append below the lowest widget regardless of array order - -- **GIVEN** a dashboard with widgets at `(x:0, y:5, w:6, h:3)` (bottom edge `8`) and `(x:6, y:0, w:6, h:2)` (bottom edge `2`) -- **WHEN** a new 6×3 widget is added -- **THEN** it MUST be placed at `(x:0, y:8)` (below the lowest bottom edge, not below the last array entry) -- **AND** no existing widget MUST be moved - -#### Scenario: First widget on an empty dashboard - -- **GIVEN** a dashboard with no widgets -- **WHEN** a new 4×4 widget is added -- **THEN** it MUST be placed at `(x:0, y:0)` - -#### Scenario: Existing widgets are never pushed when the top region is full - -- **GIVEN** a dashboard whose `[0..12] × [0..4]` region is fully occupied -- **WHEN** a new 4×4 widget is added -- **THEN** it MUST be placed at `(x:0, y:4)`, below the occupied region -- **AND** every existing widget MUST retain its original `gridX`, `gridY`, `gridWidth`, and `gridHeight` -- **AND** the returned `pushed` array MUST be empty - -#### Scenario: Default size on omitted dimensions - -- **GIVEN** a caller invokes `placeNewWidget({type: 'text'})` with no `w` or `h` -- **WHEN** the placement runs -- **THEN** the placement MUST use `w=4, h=4` -- **AND** the `y` coordinate MUST still be the lowest occupied bottom edge (`0` on an empty dashboard) - -#### Scenario: Persistence after placement - -- **GIVEN** a new widget has been placed -- **WHEN** the placement completes -- **THEN** the new widget MUST be persisted via the standard placement-update API (REQ-WDG-008 batch update or per-placement PUT) -- **AND** because no existing widget is moved, only the new widget's position needs to be written diff --git a/openspec/changes/grid-bottom-append-placement/tasks.md b/openspec/changes/grid-bottom-append-placement/tasks.md deleted file mode 100644 index 92d99dc0b..000000000 --- a/openspec/changes/grid-bottom-append-placement/tasks.md +++ /dev/null @@ -1,26 +0,0 @@ -# Tasks — grid-bottom-append-placement - -## Tasks - -- [x] Task 1: Amend REQ-GRID-006 requirement text in `openspec/specs/grid-layout/spec.md` from "auto-position + top-left/push-down fallback" to the bottom-append rule (`x = 0`, `y = max(gridY + gridHeight)`, existing widgets never moved, empty dashboard → `(0,0)`) — captured in this change's `specs/grid-layout/spec.md` delta -- [x] Task 2: Rewrite the REQ-GRID-006 scenarios — remove "Push-down fallback when grid is full at top" and "Pushed widgets remain within their column lane"; replace "Auto-position into empty space" with bottom-append scenarios; update "Default size on omitted dimensions" and "Persistence after placement" to the no-push expectations (delta restates the full scenario set) -- [x] Task 3: Reconcile the stale doc comments in `src/stores/dashboard.js` (`addWidgetToDashboard` and `addTileToDashboard`) that still describe "try autoPosition, fall back to top-left + push down" so they describe bottom-append; logic untouched -- [ ] Task 4 (apply time): Update the "Current Implementation Status" traceability line for REQ-GRID-006 in `openspec/specs/grid-layout/spec.md` (line ~496) from "autoPosition primary path and the top-left + push-down fallback … Push-down side effects flow through `updatePlacements`" to the bottom-append description -- [x] Task 5: Confirm the existing Vitest suite (`src/composables/__tests__/useGridManager.spec.js`, `describe('REQ-GRID-014 placeNewWidget() — always appends at the bottom')`) already encodes the new expectations and passes — no test change required -- [x] Task 6: Confirm REQ-GRID-014 (single placement authority) and its grep guard are unaffected — `grid.addWidget` still appears only in `useGridManager.js` and its test file - -## Verification - -`openspec validate` exits clean. REQ-GRID-006, the `@spec`-linked comment in `useGridManager.js`, the `dashboard.js` call-site comments, and the Vitest expectations all describe bottom-append. No new push-down behaviour is reintroduced. - -## Tests (company-wide ADR-009) - -No new tests required — the bottom-append Vitest cases already exist and pass. This change reconciles documentation/spec to shipped code. - -## Documentation (company-wide ADR-010) - -Composable header comment already describes bottom-append; `dashboard.js` call-site comments reconciled per Task 3. - -## i18n (company-wide ADR-005) - -No user-facing strings introduced. diff --git a/openspec/changes/harden-activity-debounce-cache-reliability/specs/activity-feed-integration/spec.md b/openspec/changes/harden-activity-debounce-cache-reliability/specs/activity-feed-integration/spec.md deleted file mode 100644 index 3102f4d4f..000000000 --- a/openspec/changes/harden-activity-debounce-cache-reliability/specs/activity-feed-integration/spec.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -capability: activity-feed-integration -delta: true -status: draft ---- - -# Activity Feed Integration — Debounce Backend Reliability - -## MODIFIED Requirements - -### Requirement: REQ-ACT-007 Reaction debounce holds regardless of deployment topology - -The per-`(actorUserId, dashboardUuid)` reaction debounce (900-second window) MUST hold across HTTP requests and PHP-FPM worker processes on every supported deployment topology, including installations where the -APCu PHP extension is not installed or not enabled for the running SAPI. -The debounce MUST NOT silently degrade to "always allow" when APCu is -unavailable. - -#### Scenario: Debounce holds without APCu across two separate requests - -- **GIVEN** a Nextcloud instance with APCu not installed -- AND user "bob" reacted to dashboard `abc` in request 1, one second ago -- **WHEN** bob reacts to dashboard `abc` again in a separate HTTP request - (request 2) within the same 900-second window -- **THEN** `allowReaction('bob', 'abc')` MUST return `false` in request 2 -- **AND** no second reaction activity row MUST be written - -#### Scenario: Debounce still uses APCu when available - -- **GIVEN** a Nextcloud instance with APCu installed and enabled -- **WHEN** `allowReaction()` is called -- **THEN** the claim MUST be served via `apcu_add()` exactly as before this - change (no regression to the fast path) - -### Requirement: REQ-ACT-008 Global fan-out debounce holds regardless of deployment topology - -The per-`(dashboardUuid, eventType)` fan-out debounce (900-second window) MUST hold across HTTP requests and PHP-FPM worker processes, including on installations without APCu. - -#### Scenario: Fan-out debounce holds without APCu across two separate requests - -- **GIVEN** a Nextcloud instance with APCu not installed -- AND a `dashboard_updated` fan-out for dashboard `abc` was performed in - request 1 -- **WHEN** a second `dashboard_updated` event for dashboard `abc` arrives in - a separate HTTP request within the same 900-second window -- **THEN** `allowGlobalFanout('abc', 'dashboard_updated')` MUST return - `false` in request 2 -- **AND** the fan-out MUST be skipped silently, exactly as the existing - single-request scenario requires - -#### Scenario: Deterministic unit tests remain unaffected - -- **GIVEN** a test injects a fake clock into `DebounceHelper` -- **WHEN** the test advances the fake clock past the 900-second window -- **THEN** the helper MUST continue to use the in-memory fallback for - deterministic behaviour, unaffected by this change diff --git a/openspec/changes/harden-activity-debounce-cache-reliability/tasks.md b/openspec/changes/harden-activity-debounce-cache-reliability/tasks.md deleted file mode 100644 index 841d5873d..000000000 --- a/openspec/changes/harden-activity-debounce-cache-reliability/tasks.md +++ /dev/null @@ -1,51 +0,0 @@ -# Tasks — harden-activity-debounce-cache-reliability - -## DebounceHelper - -- [ ] Task 1: In `lib/Activity/DebounceHelper.php`, add a constructor - parameter `private readonly ?\OCP\ICache $cache = null` (nullable so - existing unit-test call sites that construct `new DebounceHelper($clock)` - keep working), alongside the existing `?callable $clock` parameter. -- [ ] Task 2: In `claim()` (currently lines 142-167), when - `$this->realClock === true` and APCu is unusable - (`apcuUsable() === false`) and `$this->cache !== null`, use - `$this->cache->add($key, $now, self::TTL_SECONDS)`-equivalent semantics: - `OCP\ICache` doesn't expose an atomic `add()`, so implement the claim as - `if ($this->cache->hasKey($key)) { return false; } $this->cache->set($key, $now, self::TTL_SECONDS); return true;` - and document the small race window this introduces (acceptable for a - 15-minute debounce UX guard, not a security control). -- [ ] Task 3: Keep the existing `$this->memory` array path as the final - fallback only when `$this->cache === null` (defensive) or when - `$this->realClock === false` (test-clock path, unchanged from today). -- [ ] Task 4: Update the class docblock (lines 14-17) and the `claim()` - docblock (lines 132-141) to describe the three-tier fallback: APCu → - `ICache` (distributed) → in-memory array (test-clock only). - -## Application.php wiring - -- [ ] Task 5: In `lib/AppInfo/Application.php` (lines 98-107), change the - `DebounceHelper` factory to resolve `OCP\ICacheFactory` from the - container and call `createDistributed('launchpad_activity_debounce')`, - passing the resulting `ICache` into the `DebounceHelper` constructor: - `factory: static fn(\Psr\Container\ContainerInterface $c): DebounceHelper => new DebounceHelper(cache: $c->get(\OCP\ICacheFactory::class)->createDistributed('launchpad_activity_debounce'))` - (adjust to match the existing container-callback signature used by - neighbouring registrations in the same file). -- [ ] Task 6: Update the inline comment at line 98 ("register - DebounceHelper as a shared singleton") to also note that the shared - distributed cache — not the PHP singleton — is what makes the debounce - guarantee hold across requests. - -## Tests - -- [ ] Task 7: Add a PHPUnit test that constructs `DebounceHelper` with a - fake `ICache` implementation (no APCu, real clock) and asserts that - `allowReaction()` called twice in immediate succession for the same - `(actor, dashboard)` pair returns `true` then `false` — i.e. the - distributed-cache path is exercised, not just the in-memory fallback. -- [ ] Task 8: Add a regression test that simulates "APCu absent, cache - absent" (both `apcuUsable()` false and `$cache === null`) and asserts the - helper still falls back to the in-memory array without throwing, to - confirm the defensive tier is not a hard dependency. -- [ ] Task 9: Re-run the existing `activity-feed-integration` PHPUnit - suite referenced by `openspec/specs/activity-feed-integration/spec.md` - to confirm REQ-ACT-007/REQ-ACT-008 scenarios still pass unchanged. diff --git a/openspec/changes/integrations-live-tile-lists/tasks.md b/openspec/changes/integrations-live-tile-lists/tasks.md deleted file mode 100644 index 1c79ee3a4..000000000 --- a/openspec/changes/integrations-live-tile-lists/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: integrations-live-tile-lists - -- [ ] 1. Validate `display`, `mapping` and `limit` in `LiveTileService::validateSourceConfig()`. Verify: PHPUnit for each rule and for an old config. -- [ ] 2. Evaluate the mapping server-side for both source modes, drop unmapped fields, apply the limit, and cache the mapped result. Verify: PHPUnit with array and object payloads. -- [ ] 3. Render list, table and key-value in `LiveTileWidget.vue`, with https-only links and accessible markup. Verify: Vitest and an axe check. -- [ ] 4. Add the display choice, mapping rows and the "Latest documents" preset (SharePoint and Confluence variants) to `LiveTileWidgetForm.vue`, and rename its "OpenConnector" labels to "Integriq". Verify: Vitest. -- [ ] 5. Playwright: a URL-mode list tile against a fixture endpoint. -- [ ] 6. Add `nl` and `en` strings, fold the delta into `openspec/specs/live-data-tile-widget/spec.md` on archive, and set int-builder and int-intranet-content to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/integrations-office-tiles/tasks.md b/openspec/changes/integrations-office-tiles/tasks.md deleted file mode 100644 index c19851f27..000000000 --- a/openspec/changes/integrations-office-tiles/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: integrations-office-tiles - -- [ ] 1. Implement `OfficeTilesService` (pack per user from `ITemplateManager::listCreators()` and enabled apps; create from template with free-name selection). Verify: PHPUnit. -- [ ] 2. Seed `office-tiles.list` and `office-tiles.create`, and add `GET /api/office-tiles` and `POST /api/office-tiles/create`. Verify: PHPUnit and route-reachability. -- [ ] 3. Add the `create` link type to `TileUpdater` validation and to `src/components/TileWidget.vue` with the name and folder dialog. Verify: Vitest and PHPUnit. -- [ ] 4. Add "Office tiles" to `src/modals/WidgetPickerModal.vue`, placing one container. Verify: Vitest. -- [ ] 5. Playwright with Nextcloud Office: place the pack, create a document twice, see two files. -- [ ] 6. Add `nl` and `en` strings, copy the spec to `openspec/specs/office-tiles/spec.md` on archive, and set int-office-tiles to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/keyboard-accessible-widget-repositioning/tasks.md b/openspec/changes/keyboard-accessible-widget-repositioning/tasks.md deleted file mode 100644 index c32c15de8..000000000 --- a/openspec/changes/keyboard-accessible-widget-repositioning/tasks.md +++ /dev/null @@ -1,61 +0,0 @@ -# Tasks — keyboard-accessible-widget-repositioning - -## Grid item accessibility baseline - -- [ ] Task 1: In `src/components/DashboardGrid.vue`, add `role="group"`, - `:aria-label="getPlacementAriaLabel(placement)"` (new computed helper - returning e.g. `Widget: {title}` or `Tile: {title}`), and `tabindex="0"` - to the `.grid-stack-item` element (currently lines 9-20). -- [ ] Task 2: Add `:focus-visible` CSS to `.grid-stack-item` using NC - variables (`var(--color-primary-element)` outline), matching the - existing visual language of the component's other interactive states. -- [ ] Task 3: Wire `keydown.enter` and `keydown.space` on the grid item (in - edit mode only) to open the same context-menu / move-panel flow that - right-click already triggers, calling the existing `onItemContextMenu` - handler with a synthesized position (e.g. centered on the focused - element's bounding rect) instead of `event.clientX/clientY`. - -## Move action - -- [ ] Task 4: In `src/components/Widgets/WidgetContextMenu.vue`, add a new - `role="menuitem"` button "Move" between the existing Edit (line 13) and - Remove (line 29) buttons, with a new `onMove()` handler emitting a new - `move` event (add `'move'` to the `emits` array at line 88) then `close`. -- [ ] Task 5: Create `src/components/Widgets/WidgetMovePanel.vue` — a - focus-trapped panel/modal (reuse `NcModal` or a lightweight popover - matching `WidgetContextMenu`'s positioning approach) that: - - Displays the widget's current `gridX/gridY/gridWidth/gridHeight`. - - Binds `ArrowUp/Down/Left/Right` to nudge `gridX`/`gridY` by 1 cell. - - Binds `Shift+ArrowRight/Left` and `Shift+ArrowDown/Up` to grow/shrink - `gridWidth`/`gridHeight` by 1 cell (respecting the existing `gs-min-w`/ - `gs-min-h` = 2 floor already set in `DashboardGrid.vue` line 17-18). - - Binds `Enter` to confirm (emit `save` with the new placement rect) and - `Escape` to cancel (emit `close` with no change). - - Shows a live text readout of the pending position/size for screen - readers (`aria-live="polite"`). -- [ ] Task 6: In `src/composables/useGridManager.js`, extract a pure - helper (e.g. `nudgePlacement(placement, direction, allPlacements)`) that - computes the candidate new rect and reuses the same collision/pushing - logic `placeNewWidget()` (lines 232+) already implements, so keyboard - moves get the same collision-avoidance behaviour as drag moves. -- [ ] Task 7: Wire `DashboardGrid.vue`'s `move` event (from the context - menu) to open `WidgetMovePanel`, and on `save` call the existing - placement-update path (the same one GridStack's `change` event already - uses) with the panel's resulting rect. - -## Tests - -- [ ] Task 8: Add a Vitest test for `WidgetMovePanel.vue` asserting arrow - keys nudge the displayed position, `Shift+Arrow` resizes, `Enter` emits - `save` with the expected rect, and `Escape` emits `close` with no `save`. -- [ ] Task 9: Add a Vitest test for `WidgetContextMenu.vue` asserting the - new Move button emits `move` then `close`. -- [ ] Task 10: Add a Playwright e2e test (per `feedback_playwright-ui-only-newman-api.md` - — UI-driven, not API-direct) that: focuses a grid item via `Tab`, opens - the move panel via `Enter`, nudges it right twice via arrow keys, confirms - via `Enter`, and asserts the widget's rendered grid position changed by - the expected offset without any pointer/mouse events being dispatched. -- [ ] Task 11: Add an axe-core (or equivalent) accessibility check to the - existing Playwright/Vitest suite asserting each grid item has a - discoverable accessible name and that the move panel traps focus - correctly (no focus leak to the canvas behind it while open). diff --git a/openspec/changes/launcher-app-catalogue/tasks.md b/openspec/changes/launcher-app-catalogue/tasks.md deleted file mode 100644 index db3a39c5a..000000000 --- a/openspec/changes/launcher-app-catalogue/tasks.md +++ /dev/null @@ -1,21 +0,0 @@ -# Tasks: launcher-app-catalogue - -## Backend - -- [ ] 1. Add the two tables in one migration with table builders, entities and mappers. Verify: migration test on PostgreSQL and MySQL. -- [ ] 2. Seed `catalogue.list`, `catalogue.request`, `catalogue.manage`, `catalogue.decide` in `lib/actions.seed.json`. Verify: action-matrix test. -- [ ] 3. Implement `CatalogueService` (group-filtered list, create, update, delete, request, approve, decline, open-request limit). Verify: PHPUnit. -- [ ] 4. Add `CatalogueController` (`GET /api/catalogue`, `POST /api/catalogue/requests`) and `AdminCatalogueController` (CRUD and decisions, `#[AuthorizedAdminSetting]`). Verify: PHPUnit and route-reachability. -- [ ] 5. Add `app_requested` and `app_request_decided` to `lib/Notification/Notifier.php`, plus the optional `catalogue_manager_group` admin setting. Verify: PHPUnit on the notifier. - -## Frontend - -- [ ] 6. Add the "From the app catalogue" section to `src/modals/WidgetPickerModal.vue`, creating a tile through the existing tile call. Verify: Vitest. -- [ ] 7. Add the "Can't find your app?" request form. Verify: Vitest and an axe check. -- [ ] 8. Add the admin "App catalogue" section: entries with group picker (`NcSelect` with input label) and the request list with approve and decline. Verify: Vitest. - -## Close - -- [ ] 9. Add the four demo entries to `DemoShowcasesService`. Verify: PHPUnit on the showcase. -- [ ] 10. Playwright for the add path, group visibility and the decline path. -- [ ] 11. Add `nl` and `en` strings, copy the spec to `openspec/specs/app-catalogue/spec.md` on archive, and set tile-catalogue to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/launcher-bookmark-import/tasks.md b/openspec/changes/launcher-bookmark-import/tasks.md deleted file mode 100644 index 23b255562..000000000 --- a/openspec/changes/launcher-bookmark-import/tasks.md +++ /dev/null @@ -1,9 +0,0 @@ -# Tasks: launcher-bookmark-import - -- [ ] 1. Seed `widget.import-bookmarks` as `["admin", "@all"]` in `lib/actions.seed.json` and add the route `POST /api/dashboard/{dashboardId}/tiles/import`. Verify: route-reachability and action-matrix tests. -- [ ] 2. Implement `WidgetApiController::importBookmarks()` with the action check, `canAddWidget()` and 409 on quota. Verify: PHPUnit for 401, 403, 409 and 201. -- [ ] 3. Add `PlacementService::importBookmarks()`: URL check per bookmark, one quota check, containers for folders, bottom-append, one transaction, a skipped list in the response. Verify: PHPUnit including rollback. -- [ ] 4. Write the browser parser for the Netscape bookmark format with size and count limits. Verify: Vitest on Firefox, Chrome and Edge fixtures. -- [ ] 5. Build `src/modals/BookmarkImportModal.vue` (file picker, folder and bookmark checkboxes, skipped list) and the "Import bookmarks" entry in the dashboard menu. Verify: Vitest and an axe check. -- [ ] 6. Playwright: import a fixture, pick one folder, see its container at the bottom. -- [ ] 7. Add `nl` and `en` strings, fold the delta into `openspec/specs/tiles/spec.md` on archive, and set d-import-bookmarks to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/launcher-discover-server-services/tasks.md b/openspec/changes/launcher-discover-server-services/tasks.md deleted file mode 100644 index e32a5cc20..000000000 --- a/openspec/changes/launcher-discover-server-services/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: launcher-discover-server-services - -- [ ] 1. Add `lib/Service/ServiceDiscoveryService.php` over `INavigationManager::getAll('link')`, excluding LaunchPad. Verify: PHPUnit with a stubbed manager. -- [ ] 2. Seed `tile.discover` in `lib/actions.seed.json` and add `GET /api/tiles/discover` with `#[NoAdminRequired]` and the action check. Verify: PHPUnit and route-reachability. -- [ ] 3. Add the "Discovered on this server" section to `src/modals/WidgetPickerModal.vue`, searchable with the existing box, with the "On this dashboard" mark. Verify: Vitest. -- [ ] 4. Place the tile through the existing tile call with the mapping in D2. Verify: Vitest on the payload. -- [ ] 5. Playwright: discover Deck and place it. -- [ ] 6. Add `nl` and `en` strings, fold the delta into `openspec/specs/tiles/spec.md` on archive, and set tile-discover-containers to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/launcher-tile-internal-address/tasks.md b/openspec/changes/launcher-tile-internal-address/tasks.md deleted file mode 100644 index bf5bc8fa2..000000000 --- a/openspec/changes/launcher-tile-internal-address/tasks.md +++ /dev/null @@ -1,10 +0,0 @@ -# Tasks: launcher-tile-internal-address - -- [ ] 1. Add the `office_networks` key to `lib/Db/AdminSettingKey.php` and read and write it through `AdminSettingsService`, storing a list of CIDR strings; malformed ranges are rejected with 400. Verify: PHPUnit. -- [ ] 2. Add `lib/Service/OfficeNetworkService.php` with `isOfficeRequest()` using `IRequest::getRemoteAddress()` and `OCP\Security\Ip\IFactory`. Verify: PHPUnit for IPv4, IPv6, empty and malformed. -- [ ] 3. Provide `onOfficeNetwork` from `lib/Service/InitialStateBuilder.php`. Verify: initial-state contract test. -- [ ] 4. Validate `content.internalUrl` in `lib/Service/TileUpdater.php`. Verify: PHPUnit. -- [ ] 5. Add the "Office networks" section to the admin page with the "your current address" line. Verify: Vitest on the section. -- [ ] 6. Add "Address on the office network" and the address-in-effect line to `src/modals/TileEditor.vue`. Verify: Vitest. -- [ ] 7. Pick the address in `src/components/TileWidget.vue`. Verify: Vitest, then a Playwright run with the runner's range configured. -- [ ] 8. Add `nl` and `en` strings, fold the requirements into `openspec/specs/tiles/spec.md` on archive, and set d-internal-url to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/launcher-tile-launch-types/tasks.md b/openspec/changes/launcher-tile-launch-types/tasks.md deleted file mode 100644 index 6828167d4..000000000 --- a/openspec/changes/launcher-tile-launch-types/tasks.md +++ /dev/null @@ -1,18 +0,0 @@ -# Tasks: launcher-tile-launch-types - -## Backend - -- [ ] 1. Add `tile_allowed_schemes` and `sso_launch_templates` to `lib/Db/AdminSettingKey.php` and `AdminSettingsService`, with validation (schemes lower-case, never the forbidden list; templates https with `{appId}`). Verify: PHPUnit. -- [ ] 2. Validate the `program`, `remote-desktop` and `sso` link types in `lib/Service/TileUpdater.php` as in D1. Verify: PHPUnit per type and per forbidden value. -- [ ] 3. Add `TileLaunchController::rdp()` with `GET /api/tiles/{placementId}/rdp`, the view check and the generated file. Verify: PHPUnit on content and on 403, and route-reachability. - -## Frontend - -- [ ] 4. Add the three types to `src/modals/TileEditor.vue` (scheme address, gateway or RDP fields, template picker with `NcSelect` input label and app id). Verify: Vitest. -- [ ] 5. Render the hrefs per type in `src/components/TileWidget.vue`, with the program hint. Verify: Vitest. -- [ ] 6. Add the admin section for allowed schemes and SSO launch templates. Verify: Vitest and an axe check. - -## Close - -- [ ] 7. Playwright: SSO tile address and RDP download. -- [ ] 8. Add `nl` and `en` strings, fold the delta into `openspec/specs/tiles/spec.md` on archive, and set tile-local-apps, tile-legacy-apps and tile-sso-app to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/launcher-tile-open-behaviour/specs/tiles/spec.md b/openspec/changes/launcher-tile-open-behaviour/specs/tiles/spec.md deleted file mode 100644 index 4013bd63e..000000000 --- a/openspec/changes/launcher-tile-open-behaviour/specs/tiles/spec.md +++ /dev/null @@ -1,78 +0,0 @@ -# Delta for tiles: tile link target and side panel - -## ADDED Requirements - -### Requirement: A tile carries its own link target (REQ-TOB-001) - -Every tile placement MUST accept a link target of `same-tab`, `new-tab` or `side-panel` in its content, set in the tile editor by anyone who may edit the tile. The server MUST reject any other value with HTTP 400 and leave the placement unchanged. - -#### Scenario: Author makes a web tile open in the same tab - -- **GIVEN** Ella has full permission on her dashboard "Mijn werkplek" with a tile "Intranet" pointing at `https://intranet.example.nl` -- **WHEN** she opens the tile editor, sets "Opens in" to "Same tab" and saves -- **THEN** clicking "Intranet" on the Workspace page opens the intranet in the current tab - -#### Scenario: Unknown target is refused - -- **GIVEN** a tile placement on a dashboard Ella may edit -- **WHEN** a client sends `PUT /api/widgets/{placementId}` with `content.linkTarget = "popup"` -- **THEN** the response is 400 and the stored target is unchanged - -### Requirement: A dashboard sets the default target for its tiles (REQ-TOB-002) - -A dashboard MUST accept a default link target. A tile without its own target MUST use the dashboard default, and a dashboard without a default MUST keep the current rule: a web address opens in a new tab and an app opens in the same tab. - -#### Scenario: Dashboard default applies to tiles without their own choice - -- **GIVEN** the group dashboard "Team Burgerzaken" has default target "Same tab" and a tile "Zaaksysteem" with no target of its own -- **WHEN** Pieter clicks "Zaaksysteem" on the Workspace page -- **THEN** it opens in the current tab - -#### Scenario: Upgrade keeps today's behaviour - -- **GIVEN** a dashboard created before this change, with no default and tiles with no target -- **WHEN** a user clicks a tile pointing at `https://example.org` -- **THEN** it opens in a new tab, and an app tile opens in the same tab - -### Requirement: A tile can open its app in a panel beside the tiles (REQ-TOB-003) - -A tile with target `side-panel` MUST open its address in a panel on the Workspace page next to the grid, keep the grid usable, show a close button and an "Open in new tab" link, close on Escape and return focus to the tile. Only one panel MUST be open at a time. - -#### Scenario: Files opens beside the tiles - -- **GIVEN** Ella's dashboard has a tile "Bestanden" linking to the Files app with target "Panel beside the tiles" -- **WHEN** she clicks "Bestanden" -- **THEN** the Files app shows in a panel next to her tiles, and the tiles stay visible and clickable -- **AND WHEN** she presses Escape, the panel closes and focus is back on "Bestanden" - -#### Scenario: Opening a second tile replaces the panel - -- **GIVEN** the panel shows "Bestanden" -- **WHEN** Ella clicks a second panel tile "Agenda" -- **THEN** the panel shows the Calendar app and no second panel appears - -### Requirement: The panel only frames allowed pages (REQ-TOB-004) - -The panel MUST frame a Nextcloud address on the same instance, and MUST frame an outside address only when its host is on the embed allow-list (`iframe_allowed_hosts`). Otherwise, or when the page refuses to be framed, the panel MUST show a fallback card with the page title and an "Open in new tab" link, never an empty frame. - -#### Scenario: Outside host not on the allow-list - -- **GIVEN** the allow-list holds only `kaart.example.nl` and a tile points at `https://portal.example.com` with target "Panel beside the tiles" -- **WHEN** Pieter clicks the tile -- **THEN** the panel shows the fallback card "This page cannot be shown here" with "Open in new tab" - -#### Scenario: Editor explains why the panel is unavailable - -- **GIVEN** Ella edits a tile pointing at `https://portal.example.com`, whose host is not on the allow-list -- **WHEN** she opens "Opens in" -- **THEN** "Panel beside the tiles" is disabled with the text "Ask an administrator to allow this site for embedding" - -### Requirement: Quick search opens a tile the way a click does (REQ-TOB-005) - -Activating a tile from quick search MUST use the same resolved target as clicking the tile, including the side panel. - -#### Scenario: Search result opens in the panel - -- **GIVEN** a tile "Bestanden" with target "Panel beside the tiles" -- **WHEN** Pieter types "best" in the quick-search box and presses Enter on "Bestanden" -- **THEN** the Files app opens in the panel beside the tiles diff --git a/openspec/changes/launcher-tile-open-behaviour/tasks.md b/openspec/changes/launcher-tile-open-behaviour/tasks.md deleted file mode 100644 index 86923fc54..000000000 --- a/openspec/changes/launcher-tile-open-behaviour/tasks.md +++ /dev/null @@ -1,19 +0,0 @@ -# Tasks: launcher-tile-open-behaviour - -## Backend - -- [ ] 1. Validate `content.linkTarget` (`same-tab`, `new-tab`, `side-panel`) in `lib/Service/TileUpdater.php` on create and update; unknown values return 400. Verify: PHPUnit cases for each value and for a bad value. -- [ ] 2. Add a nullable `default_link_target` column to `oc_launchpad_dashboards` in a new migration, with getter and setter on `lib/Db/Dashboard.php` and the same three-value check in `DashboardService::updateDashboard()`. Verify: migration test and a service test. -- [ ] 3. Expose `defaultLinkTarget` in the dashboard JSON and the initial state. Verify: controller test asserts the key. - -## Frontend - -- [ ] 4. Add a "Opens in" choice (same tab, new tab, panel beside the tiles) to `src/modals/TileEditor.vue`, disabled with a reason for outside hosts that are not on the embed allow-list. Verify: Vitest on the editor. -- [ ] 5. Add the dashboard default to `src/modals/DashboardConfigModal.vue`. Verify: Vitest on the modal. -- [ ] 6. Resolve the target in `src/components/TileWidget.vue` (tile, dashboard default, today's rule) and emit `open-in-panel` for `side-panel`. Verify: Vitest per value. -- [ ] 7. Build `TileSidePanel` in `src/views/WorkspaceApp.vue`: one panel, close button, Escape, focus return, refused-framing fallback card with "Open in new tab", overlay below 768px. Verify: Vitest and a Playwright run. -- [ ] 8. Confirm quick search (`src/composables/useTileSearchHost.js`) opens a `side-panel` tile in the panel. Verify: Vitest on `activateResult`. - -## Close - -- [ ] 9. Add `nl` and `en` strings, update `openspec/specs/tiles/spec.md` on archive, and set d-link-target and d-open-inside to `built` in `openspec/parity/capabilities.json` with evidence lines. diff --git a/openspec/changes/launcher-tile-sorting/tasks.md b/openspec/changes/launcher-tile-sorting/tasks.md deleted file mode 100644 index 5a4aba73f..000000000 --- a/openspec/changes/launcher-tile-sorting/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: launcher-tile-sorting - -- [ ] 1. Add `ContainerWidgetForm.vue` with the three communal fields plus "Sort tiles", and register it in `FORM_OVERRIDES` in `src/constants/widgetRegistry.js`. Verify: Vitest on the form. -- [ ] 2. Keep local `{count, lastUsedAt}` per placement in `src/composables/useTileClickTracking.js`, storage failures caught. Verify: Vitest with storage available and blocked. -- [ ] 3. Order and reflow children in view mode in `ContainerWidget.vue` for the five modes, with the tie rules and a once-per-load shuffle. Verify: Vitest per mode. -- [ ] 4. Add "Forget my usage" to the container menu and the "Sorted by" accessible description. Verify: Vitest and an axe check. -- [ ] 5. Playwright: most used moves a clicked tile to the front after reload; "By hand" restores the stored layout. -- [ ] 6. Add `nl` and `en` strings, fold the delta into `openspec/specs/container-widget/spec.md` on archive, and set d-tile-sort and tile-most-used to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/launchpad-ai-dashboard-assistant/proposal.md b/openspec/changes/launchpad-ai-dashboard-assistant/proposal.md deleted file mode 100644 index d9399305a..000000000 --- a/openspec/changes/launchpad-ai-dashboard-assistant/proposal.md +++ /dev/null @@ -1,41 +0,0 @@ -# Embedded AI assistant and smart summaries - -As a case worker or dashboard user, I want to view intelligent summaries of my workload on the dashboard—cases and consultation responses—so that I can quickly assess my current status without navigating away. This change adds two widgets powered by AI-driven summarization to help users make faster decisions on their open cases and gather feedback insights. - -## Affected code units - -- `src/components/CasesSummaryWidget.vue` — displays open case count, status distribution, and recent cases -- `src/components/ConsultationSummaryWidget.vue` — displays consultation response metrics and key feedback -- `src/store/modules/casesStore.js` — Pinia store for case data (CRUD via OpenRegister) -- `src/store/modules/consultationStore.js` — Pinia store for consultation data (CRUD via OpenRegister) -- `lib/Service/SummaryService.php` — AI-powered summarization for both case and consultation data -- `lib/Controller/WidgetController.php` — API endpoints for widget data (`GET /api/widgets/cases-summary`, `GET /api/widgets/consultation-summary`) -- `lib/Settings/launchpad_register.json` — OpenRegister schema definitions for Case and Consultation -- Modifies dashboard `capabilities` to register the two new widgets - -## Why a delta - -LaunchPad currently has no dashboard widgets for case summaries. Case workers must navigate to a separate cases list to see their open work, losing context from the dashboard. This change surfaces key case and consultation metrics inline on the dashboard, reducing context switching and improving situational awareness. The summarization is powered by Claude via OpenAI-compatible API for intelligent, actionable insights. - -## Approach - -- **Data source**: OpenRegister stores all cases and consultations. Widget controllers fetch and aggregate this data via OpenRegister's `ObjectService`. -- **Summarization**: A `SummaryService` enriches aggregated data with AI-generated narrative summaries (e.g., "You have 5 open cases, 2 are overdue. Key actions: X, Y, Z"). -- **Frontend**: Two Vue components (`CasesSummaryWidget`, `ConsultationSummaryWidget`) render dashboard cards with metrics and summaries, styled with NL Design System tokens. -- **RBAC**: OpenRegister's object-level permissions filter visible cases/consultations per user; the widget respects these filters automatically. -- **Caching**: Summary API responses cached for 5 minutes to avoid repeated AI calls for the same data snapshot. - -## Capabilities - -**New Capabilities:** - -- `launchpad-cases-summary` — display open case count, status breakdown, and AI summary -- `launchpad-consultation-summary` — display consultation response metrics and key feedback summary - -## Notes - -- Summaries are generated on-demand (not pre-computed) and cached briefly to balance freshness vs. API cost. -- Both widgets integrate with LaunchPad's existing dashboard edit mode and GridStack layout engine. -- Case and Consultation schemas are defined in OpenRegister with full CRUD operations available via the existing app scaffolding. -- Widget visibility respects per-user OpenRegister permissions — no additional RBAC layer needed. -- The AI service is optional; if the Claude API is unavailable or quota exhausted, widgets fall back to displaying raw metrics without summaries. diff --git a/openspec/changes/launchpad-enterprise-security-access/proposal.md b/openspec/changes/launchpad-enterprise-security-access/proposal.md deleted file mode 100644 index 4077929d0..000000000 --- a/openspec/changes/launchpad-enterprise-security-access/proposal.md +++ /dev/null @@ -1,41 +0,0 @@ -# Enterprise security and access controls - -LaunchPad dashboards today support admin-only visibility and read-only guest access, but lack fine-grained role-based permissions and impersonation capabilities needed in enterprise deployments. This change introduces guest user role management, per-role dashboard and widget visibility enforcement, and a "view as" impersonation feature for admins to troubleshoot access issues. - -## Affected code units - -- `lib/Controller/DashboardController.php` — add role context to dashboard state -- `lib/Service/DashboardAuthorizationService.php` (new) — per-role visibility enforcement -- `lib/Service/GuestRoleService.php` (new) — guest user role management -- `lib/Service/ImpersonationService.php` (new) — audit-logged role impersonation -- `src/store/modules/dashboard.js` — store user's roles + active impersonation -- `src/views/Dashboard.vue` — render "View as" role selector for admins; hide widgets/actions per active role -- `src/components/RoleSelector.vue` (new) — role selection dropdown with visual indicator -- OpenRegister schema: `GuestRole` — define available roles and their permissions per dashboard -- OpenRegister schema: `DashboardPermission` — map role ↔ dashboard/widget visibility -- Adds `security-access` capability to LaunchPad - -## Why a delta - -LaunchPad currently lacks role-based access control. Every user sees either (admin) all dashboards, or (guest) no dashboards. Enterprises with multiple governance bodies, departments, or partner integrations need to grant selective access to external users without promoting them to Nextcloud administrators. ADR-023 establishes the pattern for action-level RBAC; this change applies data-level RBAC to dashboard visibility via the OpenRegister integration. - -## Approach - -1. **Guest role registration** — admins define roles (chair, secretary, member) and assign guest users to them via settings. -2. **Dashboard permission mapping** — each dashboard declares which roles can view it. Roles and dashboard together determine widget-level visibility via schema definitions. -3. **Authorization service** — every dashboard load / widget fetch checks the user's role + dashboard permissions. Unauthorized access returns 403. -4. **Impersonation service** — admins can "View as <role>" to preview what a guest with that role sees. The active role is tracked per session, persisted in Pinia store, and logged to audit trail. -5. **Frontend enforcement** — Vue components bind visibility to the user's effective role (either their assigned role or the impersonated role). Role changes trigger re-renders via store mutations. - -## Capabilities - -**New Capabilities:** - -- `security-access` — guest role definitions, dashboard permission mappings, per-role widget visibility, impersonation with audit logging - -## Notes - -- OpenRegister integration: guest roles and dashboard permissions are stored in OpenRegister and consumed via the shared `@conduction/nextcloud-vue` components. -- Audit trails: impersonation start/end and role changes are logged via OpenRegister's immutable audit service (ADR-022 lists audit as a consumed abstraction). -- No change to existing dashboard-sharing URLs — guest links remain valid; role checks happen at the API level, not the link level. -- Phase 2 (future): per-widget role exceptions for granular override; per-role data filtering for linked objects (files, notes, contacts). diff --git a/openspec/changes/launchpad-file-access-widget/proposal.md b/openspec/changes/launchpad-file-access-widget/proposal.md deleted file mode 100644 index a95aaeb72..000000000 --- a/openspec/changes/launchpad-file-access-widget/proposal.md +++ /dev/null @@ -1,40 +0,0 @@ -# Open dossier document from dashboard - -Dashboard users need quick access to dossier documents without navigating away from the dashboard view. Currently, document links are buried in detail pages, forcing users to context-switch to find critical files. This change adds a file-access widget to the LaunchPad dashboard: a card displaying associated documents with direct open-in-viewer links, filterable by dossier and file type, with built-in access control to prevent unauthorized downloads. - -## Affected code units - -- `src/components/DashboardFileAccessWidget.vue` — new widget displaying files linked to the current dossier -- `src/store/modules/files.js` — extend store to fetch + cache dossier files -- `src/composables/useFileAccess.js` — new composable for file retrieval + access checks -- `src/dashboard/` — widget slot registration in dashboard layout -- `lib/Controller/FileAccessController.php` — new backend endpoint for authenticated file listing -- `lib/Service/FileAccessService.php` — business logic for file access + filtering -- Consumes `@conduction/nextcloud-vue` + OpenRegister `FileService` (no custom file handling) - -## Why a delta - -LaunchPad dashboards today are widget-based but lack direct document access. Users switch to detail pages or external document managers to view case-related files. This creates friction in case-management workflows where documents are the primary work product. The feature stays confined to the dashboard widget system and reuses OpenRegister's file abstractions (ADR-022 pattern); no new document storage or access-control logic is introduced. - -## Approach - -- **Widget integration** — `CnDashboardPage` loads the widget via GridStack; the widget fetches its data from the backend on mount and when the dossier changes -- **Backend file listing** — `FileAccessController::list()` queries OpenRegister's file associations for the dossier + applies user's per-file permissions via `PropertyRbacHandler` -- **File viewer link** — each file displays a link that opens the document via Nextcloud's `FileService` (existing `download` + `preview` endpoints, no custom routes) -- **Access control** — backend enforces authorization; frontend silently hides files the user cannot read. No attempt-to-view failures displayed to the user. -- **Filtering** (defer to Phase 2) — file-type filters and search are designed but not implemented in this change - -## Capabilities - -**NEW Capabilities:** - -- `file-access-widget` (new) - - Requirement: `REQ-FILE-001` — File list display with access control - - Requirement: `REQ-FILE-002` — File viewer integration - - Requirement: `REQ-FILE-003` — Access denial handling - -## Notes - -- File permissions are evaluated by OpenRegister; this widget is a read-only consumer, not an access-control enforcer -- The widget is responsive: works at 320px (stacked list) and 1920px (multi-column cards) -- Tested via Playwright scenarios: "view accessible files", "access denied files are hidden" diff --git a/openspec/changes/launchpad-manifest-tier-3/specs/manifest-routing/spec.md b/openspec/changes/launchpad-manifest-tier-3/specs/manifest-routing/spec.md deleted file mode 100644 index 687709a63..000000000 --- a/openspec/changes/launchpad-manifest-tier-3/specs/manifest-routing/spec.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -status: in-progress ---- - -# Manifest routing - -## Purpose - -Make a page LaunchPad declares a page LaunchPad serves. - -Before this change the app had no `vue-router` at all — `createRouter` appeared -nowhere in `src/` — and navigation was Pinia state that never touched the URL. -`src/manifest.json` declared nine pages and the app served one: `/store`, -`/reports` and `/flows` each redirected to `/dashboard`. - -## Requirements - -### Requirement: REQ-ROUTE-001 The route table is derived, not written - -The router MUST build its routes from `manifest.pages`, so a declared page is a -routed page by construction and the two cannot drift. - -The catch-all MUST use vue-router 4's named-parameter form -(`path: '/:pathMatch(.*)*'`). The bare `'*'` wildcard was removed in v4 and does -not warn — it simply never matches, and an unknown URL renders the shell with an -empty content area. - -#### Scenario: A declared page resolves - -- GIVEN `src/manifest.json` declares a page with a `route` -- WHEN a user navigates to that route -- THEN the router MUST match it -- AND the declared page type MUST render - -### Requirement: REQ-ROUTE-002 The router base accepts both URL forms - -Nextcloud serves an app under both `/apps/launchpad/…` and -`/index.php/apps/launchpad/…`. The router base MUST be read from the location, -falling back to `generateUrl`. A base that assumes one form makes every route on -the other miss, which presents as an empty content area rather than an error. - -#### Scenario: index.php form - -- GIVEN a visitor arrives on `/index.php/apps/launchpad/reports` -- THEN the Reports page MUST render - -### Requirement: REQ-ROUTE-003 A dashboard has an address - -`/dashboards/:id` MUST select that dashboard, so a dashboard can be linked, -bookmarked and reopened (`dashboard-deeplinking`). - -An absent or unknown id MUST be left alone: the dashboard store's own resolver -already picks a sensible active dashboard, and overriding it would make a bad -link empty the page instead of falling back. - -#### Scenario: Cold deep link - -- GIVEN a user opens `/dashboards/<id>` in a fresh browser -- THEN that dashboard MUST become the active one - -#### Scenario: Unknown id - -- GIVEN a user opens `/dashboards/does-not-exist` -- THEN the store's resolved dashboard MUST still render - -### Requirement: REQ-ROUTE-004 The shared chrome renders, with the workspace inside it - -The app MUST root on `CnAppRoot`, which renders `CnAppNav` from `manifest.menu` -— including ADR-114's four footer destinations — around a `router-view`. - -**This supersedes REQ-SHELL-001's chrome-slot clause.** That requirement had -`PageController` pass `'id-app-navigation' => null` to suppress Nextcloud's left -navigation panel, because the app rendered its own slide-in sidebar and nothing -else. `NcContent` allocates that panel for `CnAppNav`, so suppressing it would -leave the shared chrome with nowhere to render — an empty rail, not an error. -`PageController` MUST pass no chrome slot ids, as every other app in the fleet -does. - -The slide-in sidebar is unaffected: it lives inside the workspace view, not in -the chrome slot. - -#### Scenario: Both are present on the dashboard route - -- GIVEN a user opens `/` -- THEN `CnAppNav` MUST render -- AND `.workspace-shell` MUST render inside the content area - -### Requirement: REQ-ROUTE-005 One skip link - -The app MUST NOT write its own skip link. It had one because it did not root on -`NcContent` and so did not inherit Nextcloud's; `CnAppRoot` renders `NcContent`, -and two bypass links are worse than one. - -`#launchpad-main-content` MUST keep `tabindex="-1"`, which the quick-search Esc -contract needs independently of any link. - -### Requirement: REQ-ROUTE-006 A declared page names a component that exists - -A `type: custom` page MUST name a component the registry resolves. - -`admin-settings` named `AdminSettingsPage`, which has never existed, and -`admin-templates-index` named `TemplatesPage`, which is a tab inside the -Nextcloud admin section rather than a page. Both MUST resolve to a redirect to -`/settings/admin/launchpad`, which is where that functionality lives — rendering -half an admin surface beside the real one would be worse than the dead links -they were. - -The redirect MUST render a real anchor as well as navigating, because a redirect -that only runs in `mounted` leaves a blank page for anyone whose navigation is -slow or blocked, and gives a keyboard user nothing to act on. - -#### Scenario: The admin menu entry is not a dead link - -- GIVEN a user activates the Admin settings entry -- THEN they MUST arrive at `/settings/admin/launchpad` diff --git a/openspec/changes/launchpad-manifest-tier-3/tasks.md b/openspec/changes/launchpad-manifest-tier-3/tasks.md deleted file mode 100644 index 508880547..000000000 --- a/openspec/changes/launchpad-manifest-tier-3/tasks.md +++ /dev/null @@ -1,51 +0,0 @@ -# Tasks: LaunchPad manifest tier 3 - -## Decided - -- [x] `CnAppRoot` hosts the workspace, with the default `CnAppNav`. The org rail is org-wide API data, not an app menu, so it coexists rather than folding in. -- [x] One skip link: Nextcloud's. `#launchpad-main-content` keeps `tabindex="-1"` for the quick-search Esc contract. -- [x] Dashboard URLs in scope. - -## Routing - -- [x] `vue-router` (already a dependency, never used) created in `src/main.js` in **path** mode via `createWebHistory(routerBase())`. `routerBase()` reads the location and falls back to `generateUrl`, because Nextcloud serves the app under both `/apps/launchpad/…` and `/index.php/apps/launchpad/…` and a base that assumes one makes every route on the other miss — silently, as an empty content area. -- [x] `routesFromManifest()` derives the table from `manifest.pages`, so a declared page is a routed page by construction. -- [x] The v4 catch-all is `path: '/:pathMatch(.*)*'`. The bare `'*'` was removed in vue-router 4 and does not warn: it simply never matches. -- [x] `/` and `/dashboards/:id` render `WorkspaceApp`; `/store`, `/reports`, `/reports/dashboards`, `/features-roadmap`, `/flows` and `/flows/:id` render their declared page types. - -## Manifest - -- [x] `Workspace` declared at `/`. The app's home had no page at all. -- [x] `dashboard-detail` changed from `type: dashboard` to `custom` + `WorkspaceApp`. As a declarative `dashboard` page the renderer would have replaced this app's GridStack surface with the generic widget renderer. -- [x] `admin-settings` and `admin-templates-index` resolve to `AdminSettingsRedirect` (see the proposal's "Found while implementing"). -- [x] Every `type: custom` page carries a `_note`. - -## Shell - -- [x] `src/App.vue` roots on `CnAppRoot`, passing the live manifest, the registry and `defaultPageTypes`. -- [x] `src/registry.js` created — the v2 kind-tagged registry `CnPageRenderer` resolves `custom` components against. -- [x] The bespoke skip link and its `focusMainContent` handler are gone. -- [x] `OrgNavigationPanel` stays inside `WorkspaceApp`, unchanged. - -## Dashboard URLs - -- [x] `WorkspaceApp` watches `$route.params.id` (`immediate`, so a cold deep link selects on arrival) and calls `switchDashboard`. An absent or unknown id is left alone: the store's resolver already picks a sensible active dashboard, and overriding it would make a bad link empty the page instead of falling back. - -## Tests - -- [x] The four `test.fail()` markers are removed — this is the change that earns it. -- [x] The tripwire test is INVERTED, not deleted: it asserted the absence of `CnAppNav` and now asserts the shared chrome renders *with the workspace still inside it*. -- [x] A new test asserts a dashboard has an address. It asks the app which dashboards the user has rather than seeding an id, because a hardcoded id passes on one instance and nowhere else. - -## Verify - -- [x] `check:manifest`, `format`, `check:schema-l10n`, `lint` — this repo's CI checks — all pass. -- [x] `npm run build` compiles (webpack exit 0; the three warnings are the pre-existing bundle-size ones). -- [x] `vitest` WorkspaceApp: 14 passed. -- [x] `playwright test --list`: 9 tests collect. -- [ ] The E2E leg on the `development` push run. It runs only there, so this is where routing is actually proven. - -## Left for later, deliberately - -- [ ] The org rail renders only inside `WorkspaceApp`, so it appears on the dashboard routes and not on `/store`, `/reports` or `/features-roadmap`. That matches today's behaviour exactly (there were no other routes), but it is now a visible inconsistency. Lifting it to the shell is its own change. -- [ ] `DashboardsReport` is `type: dashboard` — a declarative page over LaunchPad's own register. It was unroutable before, so it has never rendered; whether its widgets resolve is unproven until the E2E runs. diff --git a/openspec/changes/launchpad-meeting-calendar-actions/proposal.md b/openspec/changes/launchpad-meeting-calendar-actions/proposal.md deleted file mode 100644 index 6937b331b..000000000 --- a/openspec/changes/launchpad-meeting-calendar-actions/proposal.md +++ /dev/null @@ -1,55 +0,0 @@ -# Meeting and calendar actions from dashboard - -## Why - -LaunchPad displays agenda items and calendar events to users, but today they are read-only. Users frequently need to add context, notes, or annotations to events directly from the dashboard view — without navigating away to the Nextcloud Calendar app. Common use cases: - -- A participant jots down "agenda item pushed to next meeting" on a postponed event -- A chair adds "quorum met" or "absence excused" annotations during a meeting -- A secretary records "decision approved unanimously" alongside a governance event - -Today this workflow requires opening the Calendar app separately, navigating to the event, then returning to the dashboard. The feature consolidates this into a single dashboard interface. - -## What Changes - -- Users can add annotations to visible agenda items / calendar events directly from the dashboard widget -- Annotations are saved to the Nextcloud Calendar app as event notes/descriptions (via the Calendar app's API) -- Annotations persist and are visible on subsequent dashboard loads -- Users can edit or remove existing annotations in-place without page reload - -## Capabilities - -### New Capabilities - -- **dashboard-calendar-annotations**: Inline annotation of agenda items on the dashboard widget - -### Related Capabilities - -- `admin-templates` (group-routing): determines which group's calendars are visible -- `dashboards` (multi-scope-dashboards): the dashboard widget that renders agenda items -- Nextcloud Calendar integration: annotations are stored in Calendar events - -## Impact - -**Affected code:** - -- `src/components/CalendarWidget.vue` — add annotation UI (edit, save, cancel buttons) -- `src/store/modules/calendarStore.js` — new actions to sync annotations with Calendar API -- `lib/Controller/CalendarController.php` — new endpoint `PUT /api/calendar/{id}/annotation` to persist annotations -- `lib/Service/CalendarService.php` — annotation persistence logic - -**Affected APIs:** - -- New HTTP endpoint: `PUT /index.php/apps/launchpad/api/calendar-events/{eventId}/annotation` (authenticated, non-admin) -- Existing Nextcloud Calendar `/ocs/v2.php/apps/calendar/api/v1/events/{id}` is called server-side - -**Dependencies:** - -- Nextcloud Calendar app (must be installed and enabled) -- No new composer or npm dependencies - -**Migration:** - -- Zero schema impact: annotations are stored in Calendar event properties -- Existing calendar events are unmodified; the feature is purely additive -- No data backfill required diff --git a/openspec/changes/launchpad-mobile-remote-access/proposal.md b/openspec/changes/launchpad-mobile-remote-access/proposal.md deleted file mode 100644 index 29e43a8a8..000000000 --- a/openspec/changes/launchpad-mobile-remote-access/proposal.md +++ /dev/null @@ -1,172 +0,0 @@ ---- -status: proposed ---- - -# Proposal: Mobile and Remote Dashboard Access - -## Executive Summary - -LaunchPad currently requires office-based access over corporate networks with desktop-optimized interfaces. This proposal enables secure remote employee access from mobile devices and external networks, unlocking productivity for distributed teams while maintaining security posture. - -## Features - -### 1. Remote Work and Mobile Access -**Demand: 28** (3 tender mentions) | **Category:** Security | **Coverage:** LaunchPad - -#### Capability -As a remote employee, I want secure access to launchpad from any device or location, so that I can work productively outside the office. - -#### Acceptance Criteria -1. GIVEN a remote employee with valid credentials, WHEN they log in from a mobile device outside the corporate network, THEN they can access their dashboard and all permitted features. -2. GIVEN a remote employee is authenticated, WHEN their session is idle beyond the configured timeout, THEN they are automatically signed out and must re-authenticate. -3. GIVEN a remote employee using a mobile browser, WHEN they navigate launchpad, THEN the interface is fully usable with touch controls and adapts to the screen size without loss of functionality. - -#### Impact -- Enables distributed workforce capabilities -- Reduces dependency on VPN for dashboard access -- Maintains security through session timeout and authentication enforcement - -### 2. Access to Relevant Applications and News -**Demand: 25** (3 tender mentions) | **Category:** Security | **Coverage:** LaunchPad - -#### Capability -As an employee, I want access to relevant applications and news in launchpad, so that I can stay informed and productive from a single dashboard. - -#### Acceptance Criteria -1. GIVEN an authenticated employee, WHEN they open launchpad, THEN a curated list of relevant applications is displayed based on their role and permissions. -2. GIVEN an authenticated employee, WHEN they open launchpad, THEN a news feed showing organisation-relevant news is visible without navigating away. -3. GIVEN a security administrator, WHEN they configure application and news access policies, THEN only authorised content is shown to each employee based on their assigned role. - -#### Impact -- Centralizes access to critical applications and information -- Reduces context switching and improves productivity -- Enables role-based content filtering for security and compliance - -## User Stories - -### US-001: Remote Login from Mobile Device -**Derived from Feature 1 (Remote Work and Mobile Access)** - -As a field employee, I want to log in to LaunchPad from my phone while at a client site, so that I can review my dashboard without returning to the office. - -**Acceptance Criteria:** -1. GIVEN I have valid Nextcloud credentials -2. WHEN I visit the LaunchPad URL on my mobile device -3. THEN I can log in using Nextcloud's standard authentication -4. AND I see a mobile-optimized version of my dashboard -5. AND all dashboard features are accessible via touch - -### US-002: Automatic Session Timeout -**Derived from Feature 1 (Remote Work and Mobile Access)** - -As a security-conscious employee, I want my session to automatically expire after inactivity, so that my device is protected if I forget to log out. - -**Acceptance Criteria:** -1. GIVEN I am logged into LaunchPad on a mobile device -2. WHEN I have not interacted with the dashboard for 15 minutes (configurable) -3. THEN my session is automatically terminated -4. AND the next dashboard access requires re-authentication - -### US-003: View Role-Based Applications -**Derived from Feature 2 (Access to Relevant Applications and News)** - -As a department manager, I want to see a list of applications relevant to my role, so that I can quickly access tools needed for my responsibilities. - -**Acceptance Criteria:** -1. GIVEN I am authenticated in LaunchPad -2. WHEN I view the applications section -3. THEN I see only applications my role has permission to access -4. AND applications are grouped logically (by department or function) - -### US-004: Configure Application Access Policies -**Derived from Feature 2 (Access to Relevant Applications and News)** - -As a security administrator, I want to control which applications appear for each user role, so that sensitive tools are only accessible to authorized personnel. - -**Acceptance Criteria:** -1. GIVEN I am an admin in LaunchPad -2. WHEN I access the admin settings for application access -3. THEN I can view all available applications and user roles -4. AND I can map which roles can see which applications -5. AND changes take effect immediately for all users - -## Customer Journeys - -### Journey: New Remote Hire Onboarding -**Trigger:** New employee joins company - -1. **Authentication Phase** (Day 1) - - Pain point: Employee is not yet at office, needs to access company systems immediately - - Solution: Can log in from home using Nextcloud credentials - -2. **Dashboard Discovery** (Day 1-2) - - Pain point: Unsure which applications are relevant to their role - - Solution: LaunchPad displays role-specific application list without manual configuration - -3. **Remote Access** (Day 1+) - - Pain point: Relies on VPN for secure access - - Solution: LaunchPad provides secure direct access from any location with automatic session management - -### Journey: Executive News Brief -**Trigger:** Executive starts their day - -1. **Single-Point Access** (Morning) - - Pain point: Scattered across multiple portals and news sources - - Solution: LaunchPad dashboard displays curated organization news and relevant applications on one screen - -2. **Mobile Browsing** (Travel) - - Pain point: Need to stay informed while traveling - - Solution: Mobile-optimized dashboard with news feed accessible from phone - -3. **Role-Based Filtering** (Consistent) - - Pain point: Sees irrelevant content from other departments - - Solution: Admin-configured policies ensure only relevant content appears - -## Stakeholders - -### Information Security Officer -- **Responsibilities:** Define and enforce security policies for remote access, session timeout, and authentication -- **Goals:** Maintain security posture while enabling remote work; ensure audit trails for compliance -- **Success Criteria:** Zero security incidents from remote access; full session lifecycle logging - -### Product Manager (LaunchPad) -- **Responsibilities:** Prioritize features; ensure mobile UX is competitive; manage releases -- **Goals:** Enable distributed workforce; increase daily active users; reduce support overhead -- **Success Criteria:** Mobile traffic increases to 30%+ of total; session timeout reduces support tickets by 25% - -### System Administrator -- **Responsibilities:** Deploy LaunchPad; configure application and news access policies; manage user permissions -- **Goals:** Enable self-service application discovery; reduce onboarding time; maintain system stability -- **Success Criteria:** New users can access LaunchPad without manual admin intervention; policies are easy to manage - -### Remote Employee -- **Responsibilities:** Use LaunchPad for daily work and information access -- **Goals:** Seamless access from any location; quick discovery of needed applications; stay informed -- **Success Criteria:** Can log in and access dashboard within 30 seconds; find relevant applications without searching - -### Executive (Chief Officer) -- **Responsibilities:** Monitor organizational news and metrics from LaunchPad -- **Goals:** Single dashboard view of key information; mobile access while traveling; time savings -- **Success Criteria:** Spends less than 5 minutes per day on news/app discovery; uses dashboard on mobile 3+ days/week - -## Deployment Scope - -**In this spec:** -- Nextcloud authentication and session management for remote access -- Mobile-responsive UI for LaunchPad (touch-optimized) -- Role-based application visibility filtering -- News/content curation based on roles -- Session timeout configuration in admin settings - -**Deferred to future spec (if needed):** -- Advanced analytics on app/news usage -- Personalized recommendation engine -- Deep single-sign-on integrations with external platforms - -## Success Metrics - -- Mobile users accessing dashboard: > 30% of total daily active users (target: 6 months) -- Session timeout reduction in support tickets: > 25% improvement in auth-related issues -- Admin configuration time for app/news policies: < 30 minutes per organization -- Mobile dashboard load time: < 2 seconds on 4G network -- User satisfaction with mobile experience: > 4.0/5.0 NPS score diff --git a/openspec/changes/map-support/proposal.md b/openspec/changes/map-support/proposal.md deleted file mode 100644 index bfa81f589..000000000 --- a/openspec/changes/map-support/proposal.md +++ /dev/null @@ -1,35 +0,0 @@ -# Map support — render geospatial dashboard widgets - -Render geospatial properties from OpenRegister objects on a map widget inside launchpad dashboards. Adds a new `map` widget type alongside the existing chart / KPI / table widgets, consuming the GeoJSON storage + spatial-query API that OpenRegister's `geo-metadata-kaart` change is shipping. - -## Affected code units - -- `src/components/widgets/MapWidget.vue` — new Leaflet-based widget that renders GeoJSON returned by OpenRegister's spatial-query API; supports point / line / polygon / multi-geometry layers, click-to-detail navigation back to the underlying object, optional clustering for dense point sets. -- `src/constants/widgetTypes.js` — register `map` alongside the existing widget types so dashboard authors can pick it from the widget palette. -- `src/store/modules/widgetData.js` — extend the data-fetch path to call OpenRegister's spatial-query endpoint with bbox / within-polygon / nearest-N filters when the widget is configured as a map. -- `lib/Db/Widget.php` — annotate `type` field convention (existing column; new accepted value `map`). -- No DB schema change. - -## Why a new change - -Map rendering is a contained UI surface that depends on geospatial data shipped by OpenRegister, but the rendering decisions (Leaflet vs MapLibre, tile-layer choice, layer control UX, clustering strategy) are launchpad-specific. Splitting this change keeps the OpenRegister geo spec focused on storage + API contracts and lets launchpad iterate the widget independently. - -## Approach - -- Leaflet 1.9 as the map library — lightweight, well-maintained, plays well with PDOK tile layers and Vue 2 via `vue2-leaflet`. -- Default base layer: PDOK BRT achtergrondkaart (`https://service.pdok.nl/brt/achtergrondkaart/wmts/v2_0`). -- Coordinate transformation (WGS84 ↔ EPSG:28992 RD) via `proj4` when widgets request RD-projected output. -- Widget configuration UI: register/schema picker (reuse existing dashboard-widget config), spatial filter (none / bbox / drawn polygon), clustering threshold. -- Click-to-detail: clicking a feature opens the underlying OpenRegister object's deep-link in a new tab via the existing deep-link-registry. - -## Hand-off context - -Filed as a sibling to: -- OpenRegister `geo-metadata-kaart` change (decision 2026-05-02): scope-tightened to GeoJSON storage + spatial-query API; UI deferred to consuming apps. https://github.com/ConductionNL/openregister/blob/feat/openspec-batch-impl-2026-05-02/openspec/changes/geo-metadata-kaart/tasks.md -- WOO Tilburg sibling: https://github.com/ConductionNL/tilburg-woo-ui/issues/436 - -## Notes - -- Out of scope for this change: BAG/BGT base-registration overlays (deferred to a follow-up `map-overlays-bag-bgt` change once the base widget is in production). -- Out of scope: INSPIRE metadata compliance (a publication-side concern, not a widget-side concern). -- Out of scope: WFS/GeoJSON export from the widget — the OpenRegister API already exposes GeoJSON; widget consumers can call the API directly. diff --git a/openspec/changes/map-support/tasks.md b/openspec/changes/map-support/tasks.md deleted file mode 100644 index 63ab6dbf9..000000000 --- a/openspec/changes/map-support/tasks.md +++ /dev/null @@ -1,32 +0,0 @@ -# Tasks: Map support widget - -## Frontend - -- [ ] Add `vue2-leaflet` + `leaflet` + `proj4` to `package.json`; register `<l-map>` / `<l-tile-layer>` / `<l-geo-json>` globals in the dashboard view bootstrap. -- [ ] Create `src/components/widgets/MapWidget.vue` with: tile layer (PDOK BRT default), GeoJSON renderer, click-to-detail handler, basic legend, loading / empty / error states. -- [ ] Create `src/components/widgets/MapWidgetConfig.vue` for the dashboard-author UI: register/schema picker, geo-property selector, spatial-filter mode (none / bbox / polygon), clustering threshold. -- [ ] Register `map` in `src/constants/widgetTypes.js` with a label, icon (MDI `Map`), and config-component reference. -- [ ] Wire `widgetData.js` (or equivalent store module) to call OpenRegister's spatial-query API when the widget type is `map`. Pass through bbox / polygon / nearest-N filters from the widget config. -- [ ] Click-to-detail: clicking a feature opens the underlying object's deep-link in a new tab using the deep-link-registry. - -## Backend - -- [ ] Document the `map` widget type in the canonical launchpad widget catalogue. -- [ ] Validate `map`-typed widget configurations on save: required `register`, `schema`, `geoProperty` keys; optional `spatialFilter`, `clusterThreshold`. - -## Testing - -- [ ] Unit test for `MapWidgetConfig.vue` validation logic. -- [ ] Unit test for the spatial-filter to API-query translator in the store. -- [ ] Playwright smoke: drop a `map` widget on a fresh dashboard, configure it against a register/schema with geo data, confirm features render and click-to-detail navigates correctly. - -## Documentation - -- [ ] Add a "Map widget" section to the dashboard-authoring docs. -- [ ] Cross-reference OpenRegister's geo-metadata-kaart change so authors know which OR features ship the underlying data. - -## Out of scope (separate follow-up changes) - -- BAG / BGT base-registration overlays — `map-overlays-bag-bgt`. -- INSPIRE metadata compliance — publication-side concern, not widget-side. -- Map drawing / geometry editing — `map-drawing-tools`. diff --git a/openspec/changes/mcp-tool-surface/design.md b/openspec/changes/mcp-tool-surface/design.md deleted file mode 100644 index f44389818..000000000 --- a/openspec/changes/mcp-tool-surface/design.md +++ /dev/null @@ -1,83 +0,0 @@ -# Design — LaunchPad MCP Tool Surface - -## Context - -Product intent: every app action should be automatable by AI under per-agent, default-deny, granularly granted rights (hermiq's scope × reach model), and a user should be able to command the app from chat. LaunchPad's action surface is large (~120 routes) and today entirely invisible to MCP. The design questions were: which mechanism (provider vs schema-derived tools), how to cut ~120 routes into an honest tool catalogue, how to guarantee authorization parity, and what deliberately stays out. - -The fleet reference is `decidesk/lib/Mcp/` — `DecideskToolProvider` (dispatcher + `TOOL_DESCRIPTORS` constant), `McpMeetingGate` (centralised authorise(), explicitly no fail-open), `McpArgumentValidator` (typed argument checks returning structured errors), `McpMeetingScopeResolver` (caller scoping) — registered via the string DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::decidesk`. - -## Goals / Non-Goals - -**Goals:** - -- Full coverage of launchpad's *user* actions: 14 read + 35 write tools, ids `launchpad.{toolName}`. -- Scope (`read`/`create`/`update`/`delete`) × reach (`self`/`user`/`instance`/`external`) annotations on every tool so hermiq can grant per tool, default-deny writes. -- Authorization parity: tools call the same `PermissionService` / `ActionAuthService` guards as the HTTP controllers — one authorization truth. -- Human-approval flags on destructive (`delete`) and boundary-crossing (`external`) tools; audit-ready structured results. - -**Non-Goals:** - -- Building a chat UI or an agent runtime — hermiq hosts the conversation and the grant/approval/audit machinery. -- Tooling telemetry, binary uploads, editing locks, acknowledgement writes, or one-off admin plumbing (see REQ-MCP-007). -- Replacing `launchpad-ai-dashboard-assistant` — that change renders AI summaries *on* the canvas; this one puts the canvas's actions *under* AI control. No shared code. - -## Decisions - -### D1: Imperative provider for all writes; schema-derived tools for read discovery only - -**Decision**: All writes go through `LaunchpadToolProvider` handlers calling the existing service layer. The `Dashboard` schema additionally gets an `x-openregister-mcp` block (openconnector pattern) deriving only read-only `search`/`get`. - -**Alternatives considered:** - -- **Schema-derived CRUD for everything** (`x-openregister-mcp` with writes enabled): rejected. Dashboard mutations are not raw object writes — `DashboardService::createDashboard()` generates slugs, `updateDashboard()` respects locks and permission levels, widget placement runs collision handling (`PlacementService`), deletes cascade. Auto-derived writes would bypass every one of those invariants. -- **Provider-only, no schema block**: workable, but the two read paths cost one small overlay and give agents uniform object discovery across the fleet. Kept. - -**Rationale**: decidesk proved the provider shape; openconnector proved read-only schema blocks. LaunchPad needs both halves for its split of "rich service invariants on writes" vs "plain object reads". - -### D2: One tool per user action, not per route - -**Decision**: The catalogue aggregates exactly where the HTTP surface aggregates: `updateDashboard` covers rename/description/slug (as `dashboardApi#update` does), `updateWidgetPlacement` covers move/resize/restyle/reconfigure (as `widgetApi#updatePlacement` does), `setPublicationState` covers publish/unpublish/schedule (three routes, one user intent). - -**Alternatives considered:** - -- **One tool per route (~120 tools)**: rejected — floods the model's tool context, and route-level granularity (e.g. separate publish/unpublish tools) adds grant-matrix rows without adding a meaningfully different permission decision. -- **A handful of coarse tools ("manageDashboard")**: rejected — coarse tools break the grant model; hermiq cannot grant "reposition widgets but never delete dashboards" if both hide inside one tool. - -**Rationale**: the grant matrix is the sizing instrument: two actions belong in one tool iff a rights-granter would never want to split them. Rename-vs-describe: never split. Add-widget vs delete-dashboard: always split. - -### D3: Reach classification — kiosk and public links are `external`, sharing is `user`, group/template management is `instance` - -**Decision**: `createPublicShareLink`, `revokePublicShareLink`, and all three kiosk playlist writes carry reach `external`; `shareDashboard`/`replaceShares`/`unshareDashboard`/`setPublicationState` carry `user`; group-dashboard CRUD, `setGroupDefault`, and template CRUD/resync carry `instance`. - -**Alternatives considered:** - -- **Kiosk as `self`** ("it's the caller's playlist"): rejected — a kiosk playlist mints a `#[PublicPage]` token (`kiosk#render`, `/kiosk/{token}`) that serves dashboards to anonymous viewers. What a write *exposes* determines reach, not where the record lives. Same logic as public share links. - -**Rationale**: reach must encode blast radius as the rights-granter experiences it. Anything that changes who-can-see across the auth boundary is `external`; across users inside the instance is `user`; instance topology is `instance`. - -### D4: Authorization is a gate class delegating to the existing guards — never re-implemented - -**Decision**: `McpDashboardGate` wraps `PermissionService::can*()`, `ActionAuthService::requireAction()` (ADR-023), and the admin check; every handler consults it first. Errors deny (no `catch (\Throwable) → null`, per the unsafe-auth-resolver gate). Handlers then call `DashboardService` / `WidgetService` / `TileService` / `DashboardShareService` / `PublicShareService` / `KioskService` / `TemplateService` — never controllers (no HTTP self-calls), never mappers or `ObjectService` directly for writes. - -**Rationale**: The permission logic already exists, is audited, and drifts if duplicated. decidesk's `McpMeetingGate` documents the same invariants (guards return bool, no unconditional true, no Throwable-swallowing) — codified here as spec scenarios. - -### D5: Exclusions are specified, not implied - -**Decision**: REQ-MCP-007 names every real endpoint family that gets no tool and why — telemetry recorders (agents must not fabricate analytics), acknowledgement writes (compliance evidence of a *human* act), binary uploads (not chat-shaped), editing locks (interactive-session mechanics), one-off admin plumbing (wizard, imports, cleanup, bulk ops, settings surfaces). - -**Rationale**: an unlisted omission looks like an oversight and invites a future "completeness" PR to tool the acknowledgement endpoint — the one addition that would be actively harmful. The exclusion list makes the boundary a tested assertion (catalogue-closure scenario) instead of folklore. - -## Risks / Trade-offs - -- **Catalogue size (49 tools)**: large for a single provider. Mitigated by domain-grouped handler classes and the descriptor constant being a plain fixture unit tests assert against (decidesk pattern). If hermiq context budgets demand it, read tools can later be collapsed behind the schema-derived `search`/`get` without touching write semantics. -- **Grant-model drift**: scope/reach vocabulary is hermiq's; if hermiq's axes change, annotations must follow. The descriptors keep annotations as data, so this is a constant edit, not a refactor. -- **Instance-reach tools in agent hands**: template and group-dashboard tools are powerful. Defence in depth: admin gate in `McpDashboardGate` + `instance` reach requiring an explicit hermiq grant + approval gate on deletes. - -## Migration Plan - -Additive only: new `lib/Mcp/` classes, one DI alias line, one register.d overlay. No routes, no schema data changes. Rollback = remove the alias registration (tools disappear from the catalogue) — no data cleanup needed. - -## Open Questions - -- Whether hermiq wants pagination cursors on `listDashboards`/`listTemplates` results or is satisfied with the endpoint's existing limits — decide against hermiq's consumer contract during implementation. -- Whether `launchpad.forkDashboard` should accept a template *gallery id* directly or only dashboard uuids (gallery entries are dashboards, so uuid-only is likely sufficient) — confirm against `template#gallery`'s payload shape. diff --git a/openspec/changes/mcp-tool-surface/proposal.md b/openspec/changes/mcp-tool-surface/proposal.md deleted file mode 100644 index 28696318b..000000000 --- a/openspec/changes/mcp-tool-surface/proposal.md +++ /dev/null @@ -1,56 +0,0 @@ -# MCP tool surface — every launchpad action commandable from chat - -## Why - -The product direction is that every Conduction app exposes its actions as MCP tools, so any action can in principle be automated by an AI agent — and so a user can simply chat while their apps execute their commands: "add the calendar widget to my dashboard", "share the sprint dashboard with the sales group". hermiq consumes these tools under its two-axis **scope × reach** grant model: rights are granted per agent, granularly, with writes denied by default, human approval gates on destructive/external actions, and a full audit trail. - -LaunchPad currently exposes **nothing** to that surface. Verified by grep: no `OCA\Launchpad\Mcp` namespace, no `IMcpToolProvider` implementation, no `x-openregister-mcp` block anywhere in `lib/`, `appinfo/`, or `src/` (zero hits). Meanwhile the app has one of the richest user-action surfaces in the fleet — `appinfo/routes.php` registers ~120 routes over dashboards, widgets, tiles, sharing, publication, versioning, templates, locks, and admin operations. - -The fleet mechanism is proven: decidesk ships the reference implementation (`decidesk/lib/Mcp/` — `DecideskToolProvider` implementing `OCA\OpenRegister\Mcp\IMcpToolProvider`, registered under the DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::decidesk`, tool ids `decidesk.{toolName}`, with `McpMeetingGate` for authorization, `McpArgumentValidator` for input validation, and `McpMeetingScopeResolver` for caller scoping), and openconnector demonstrates schema-level `x-openregister-mcp` blocks for auto-derived read tools. This change gives launchpad the same surface, sized to its real action inventory. - -**Relation to `launchpad-ai-dashboard-assistant`**: that change points AI *at* the dashboard — AI-generated summary widgets rendered on the canvas. This change points AI at launchpad's *actions* — the dashboard becomes something an agent can build, rearrange, and share on the user's behalf. They are complementary and share no code; where the assistant change's widgets need data, they read it through widget endpoints, not through these tools. - -## What Changes - -- New `lib/Mcp/` namespace with `LaunchpadToolProvider` implementing `OCA\OpenRegister\Mcp\IMcpToolProvider`, registered in `AppInfo\Application` under the DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad`. Tool ids are `launchpad.{toolName}`. -- A full-coverage tool catalogue derived from the real controller/service surface (see spec REQ-MCP-002/003): 14 read tools and 35 write tools covering dashboard CRUD, active/default selection, forking, widget add/reposition/remove, tile CRUD, sharing, publication state, public links, versioning, metadata, group dashboards, and admin template management. -- Read tools carry `readOnlyHint: true`; every write tool is annotated with **scope** (`create` / `update` / `delete`) and **reach** (`self` / `user` / `instance` / `external`) so hermiq's grant matrix can authorize each tool individually, default-deny. -- Authorization parity: every tool routes through the exact same guards as the HTTP surface — `PermissionService::can*()`, `ActionAuthService::requireAction()` (ADR-023 matrix), and the admin checks — via a `McpDashboardGate` mirroring decidesk's `McpMeetingGate`. Argument validation via a `McpArgumentValidator` counterpart. -- A read-only `x-openregister-mcp` block (`search`/`get`, openconnector pattern) on the `Dashboard` schema for discovery parity; auto-derived CRUD **writes stay disabled** because dashboard mutations must pass through `DashboardService` invariants (slug generation, lock checks, permission levels), never raw object writes. - -## Capabilities - -### New Capabilities - -- `mcp-tools` — launchpad's MCP tool surface: catalogue, scope/reach annotations, authorization parity, and chat-command flows. - -### Modified Capabilities - -(none) - -## Impact - -**Affected code:** - -- `lib/Mcp/LaunchpadToolProvider.php` — dispatcher + tool catalogue (new) -- `lib/Mcp/McpDashboardTools.php`, `lib/Mcp/McpWidgetTools.php`, `lib/Mcp/McpSharingTools.php`, `lib/Mcp/McpAdminTools.php` — handlers grouped by domain (new) -- `lib/Mcp/McpDashboardGate.php`, `lib/Mcp/McpArgumentValidator.php` — authorization + validation (new) -- `lib/AppInfo/Application.php` — DI alias registration (string alias, no autoload at boot, per the ADR-083-safe pattern decidesk uses) -- `lib/Settings/register.d/dashboard-mcp.json` — read-only `x-openregister-mcp` overlay (new) - -**Affected APIs:** - -- No new HTTP routes. Tools call the existing service layer (`DashboardService`, `WidgetService`/`WidgetPlacementService`, `TileService`, `DashboardShareService`, `PublicShareService`, `TemplateService`) — never controllers, never raw ObjectService writes. - -**Dependencies:** - -- OpenRegister providing `OCA\OpenRegister\Mcp\IMcpToolProvider`; hermiq as the consuming agent host. Without OpenRegister the alias resolves lazily and fails only when asked for (decidesk pattern), so launchpad still boots. - -**Migration:** - -- None. Additive surface; no schema or data changes beyond the read-only MCP overlay. - -## Notes - -- Deliberately excluded from the tool surface (REQ-MCP-007): telemetry recorders (view events, tile clicks — agents must not fabricate analytics), binary upload endpoints (resources, template preview images — chat tools take JSON, not multipart), the setup wizard, Confluence import, orphaned-data cleanup, and demo showcases (one-off admin plumbing, high blast radius, no chat use case). -- Sizing note: unlike decidesk's 5-tool exemplar, launchpad's honest action inventory is large. The catalogue is still one-tool-per-user-action, not per-route: e.g. rename/describe/re-slug are all `launchpad.updateDashboard`; move/resize/style are all `launchpad.updateWidgetPlacement` — matching how `dashboardApi#update` and `widgetApi#updatePlacement` already aggregate them. diff --git a/openspec/changes/mcp-tool-surface/specs/mcp-tools/spec.md b/openspec/changes/mcp-tool-surface/specs/mcp-tools/spec.md deleted file mode 100644 index 75e4a37b0..000000000 --- a/openspec/changes/mcp-tool-surface/specs/mcp-tools/spec.md +++ /dev/null @@ -1,256 +0,0 @@ ---- -capability: mcp-tools -delta: false -status: draft ---- - -# LaunchPad MCP Tool Surface - -## Context - -LaunchPad exposes its user actions as MCP tools so agents (hermiq) can execute them under per-agent, default-deny grants, and so users can command the app from chat. The provider mechanism follows the fleet reference implementation in `decidesk/lib/Mcp/` (`DecideskToolProvider`, `McpMeetingGate`, `McpArgumentValidator`, `McpMeetingScopeResolver`); the catalogue below is derived from launchpad's real route/service surface (`appinfo/routes.php`, `DashboardService`, `WidgetService`, `TileService`, `DashboardShareService`, `PublicShareService`, `TemplateService`, `KioskService`, `ReactionService`, `AcknowledgementService`). LaunchPad currently has no MCP surface at all (verified: zero `IMcpToolProvider` / `x-openregister-mcp` hits in the repo). - -Write tools are annotated on hermiq's two grant axes: - -- **scope** — what kind of mutation: `create` / `update` / `delete` (reads carry `read`). -- **reach** — whose world it touches: `self` (the caller's own dashboards/objects), `user` (grants or removes other users' access), `instance` (instance-wide: group dashboards, admin templates), `external` (crosses the authentication boundary: public links, kiosk tokens). - -## ADDED Requirements - -### Requirement: REQ-MCP-001 Provider class, DI alias, and tool id namespace - -LaunchPad MUST implement `OCA\OpenRegister\Mcp\IMcpToolProvider` in a new class `OCA\LaunchPad\Mcp\LaunchpadToolProvider` (dispatcher + catalogue constant, handlers in domain-grouped classes, per the decidesk layout). It MUST be registered in `lib/AppInfo/Application.php` under the string DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad` (string alias so registration triggers no autoload and the app boots without OpenRegister, matching decidesk's `IMcpToolProvider::decidesk` registration). Every tool id MUST use the `launchpad.{toolName}` namespace. - -#### Scenario: Provider resolves through the alias - -- **GIVEN** an instance with OpenRegister and launchpad enabled -- **WHEN** the container resolves `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad` -- **THEN** it MUST return a `LaunchpadToolProvider` instance -- **AND** every id in its catalogue MUST start with `launchpad.` - -#### Scenario: Boot without OpenRegister - -- **GIVEN** an instance where OpenRegister is not installed -- **WHEN** launchpad boots -- **THEN** app registration MUST complete without error — the alias fails only if something asks for it - -### Requirement: REQ-MCP-002 Read tool catalogue (full read coverage) - -The provider MUST expose the following read tools, each with `readOnlyHint: true` and scope `read`, reach `self` (each returns only what the caller may already see through the corresponding endpoint's guards): - -| Tool id | Backs | -|---|---| -| `launchpad.listDashboards` | `dashboardApi#visible` / `DashboardService::getVisibleToUser()` | -| `launchpad.getDashboard` | `dashboardApi#show` / `#resolved` | -| `launchpad.getActiveDashboard` | `dashboardApi#getActive` / `DashboardService::resolveActiveDashboard()` | -| `launchpad.getDashboardTree` | `dashboardApi#tree` | -| `launchpad.listGroupDashboards` | `dashboardApi#listGroup` | -| `launchpad.listWidgetTypes` | `widgetApi#listAvailable` | -| `launchpad.listTiles` | `tileApi#index` | -| `launchpad.listShares` | `dashboardShareApi#index` | -| `launchpad.listVersions` | `dashboardVersionApi#listVersions` | -| `launchpad.listTemplates` | `template#gallery` | -| `launchpad.getDashboardMetadata` | `dashboardMetadata#getMetadata` | -| `launchpad.getReactions` | `dashboardReactionApi#getReactions` | -| `launchpad.listPendingAcknowledgements` | `acknowledgement#pending` | -| `launchpad.listKioskPlaylists` | `kiosk#index` | - -#### Scenario: Read tools are marked read-only - -- **GIVEN** the provider's catalogue -- **WHEN** hermiq inspects the 14 read tools -- **THEN** each MUST carry `readOnlyHint: true` and scope `read` -- **AND** none of them MUST mutate any state when invoked - -#### Scenario: Reads return only the caller's visible set - -- **GIVEN** a caller who can see dashboards A and B but not C -- **WHEN** `launchpad.listDashboards` is invoked on their behalf -- **THEN** the result MUST contain A and B and MUST NOT contain C — identical to `GET /api/dashboards/visible` - -### Requirement: REQ-MCP-003 Write tool catalogue with scope × reach annotations (full action coverage) - -The provider MUST expose the following write tools — one tool per user action, aggregated exactly as the existing endpoints aggregate them (e.g. rename/describe/re-slug are all `updateDashboard`, matching `dashboardApi#update`; move/resize/style are all `updateWidgetPlacement`, matching `widgetApi#updatePlacement`). Each write tool MUST declare the scope and reach listed: - -**Reach `self` — the caller's own dashboards:** - -| Tool id | Backs | Scope | -|---|---|---| -| `launchpad.createDashboard` | `dashboardApi#create` / `DashboardService::createDashboard()` | create | -| `launchpad.updateDashboard` | `dashboardApi#update` / `DashboardService::updateDashboard()` | update | -| `launchpad.deleteDashboard` | `dashboardApi#delete` / `DashboardService::deleteDashboard()` | delete | -| `launchpad.switchActiveDashboard` | `dashboardApi#setActiveDashboard` / `#activate` | update | -| `launchpad.setDefaultDashboard` | `dashboardApi#setDefaultDashboard` / `DashboardService::setDefaultPreference()` | update | -| `launchpad.forkDashboard` | `dashboardApi#fork` / `DashboardService::forkAsPersonal()` — also the "use a gallery template" path | create | -| `launchpad.addWidget` | `widgetApi#addWidget` | create | -| `launchpad.updateWidgetPlacement` | `widgetApi#updatePlacement` | update | -| `launchpad.removeWidget` | `widgetApi#removePlacement` | delete | -| `launchpad.addTileToDashboard` | `widgetApi#addTile` | create | -| `launchpad.createTile` | `tileApi#create` | create | -| `launchpad.updateTile` | `tileApi#update` | update | -| `launchpad.deleteTile` | `tileApi#destroy` | delete | -| `launchpad.createDashboardVersion` | `dashboardVersionApi#createVersion` | create | -| `launchpad.restoreDashboardVersion` | `dashboardVersionApi#restoreVersion` | update | -| `launchpad.setDashboardMetadata` | `dashboardMetadata#setMetadata` | update | -| `launchpad.addReaction` | `dashboardReactionApi#addReaction` | create | -| `launchpad.removeReaction` | `dashboardReactionApi#removeReaction` | delete | - -**Reach `user` — changes other users' access:** - -| Tool id | Backs | Scope | -|---|---|---| -| `launchpad.shareDashboard` | `dashboardShareApi#create` | create | -| `launchpad.replaceShares` | `dashboardShareApi#replace` | update | -| `launchpad.unshareDashboard` | `dashboardShareApi#destroy` | delete | -| `launchpad.setPublicationState` | `dashboardApi#publish` / `#unpublish` / `#schedule` | update | - -**Reach `external` — mints or revokes anonymous access:** - -| Tool id | Backs | Scope | -|---|---|---| -| `launchpad.createPublicShareLink` | `publicShare#create` | create | -| `launchpad.revokePublicShareLink` | `publicShare#destroy` | delete | -| `launchpad.createKioskPlaylist` | `kiosk#create` | create | -| `launchpad.updateKioskPlaylist` | `kiosk#update` | update | -| `launchpad.deleteKioskPlaylist` | `kiosk#destroy` | delete | - -**Reach `instance` — instance-wide (group dashboards, admin templates):** - -| Tool id | Backs | Scope | -|---|---|---| -| `launchpad.createGroupDashboard` | `dashboardApi#createGroup` / `DashboardService::createGroupShared()` | create | -| `launchpad.updateGroupDashboard` | `dashboardApi#updateGroup` | update | -| `launchpad.deleteGroupDashboard` | `dashboardApi#deleteGroup` | delete | -| `launchpad.setGroupDefault` | `dashboardApi#setGroupDefault` | update | -| `launchpad.createTemplate` | `admin#createTemplate` / `AdminTemplateService` | create | -| `launchpad.updateTemplate` | `admin#updateTemplate` | update | -| `launchpad.deleteTemplate` | `admin#deleteTemplate` | delete | -| `launchpad.resyncTemplate` | `admin#resyncTemplate` / `TemplateResyncService` | update | - -#### Scenario: Every write tool carries both axes - -- **GIVEN** the provider's catalogue -- **WHEN** hermiq inspects any non-read tool -- **THEN** it MUST find a scope of `create`, `update`, or `delete` AND a reach of `self`, `user`, `instance`, or `external` -- **AND** no write tool MUST carry `readOnlyHint: true` - -#### Scenario: Writes are default-deny in hermiq - -- **GIVEN** an agent with no explicit grants for launchpad -- **WHEN** it attempts `launchpad.deleteDashboard` -- **THEN** hermiq MUST refuse before the tool executes — the tool's annotations exist so this decision is per-tool, not app-wide - -#### Scenario: External-reach tools are the narrowest grant - -- **GIVEN** an agent granted `create/self` and `update/self` for launchpad -- **WHEN** it attempts `launchpad.createPublicShareLink` -- **THEN** the call MUST be refused — `external` reach requires its own explicit grant - -### Requirement: REQ-MCP-004 Authorization parity with the HTTP surface - -Every tool handler MUST enforce the exact same authorization as the corresponding controller path, by calling the same service guards: `PermissionService::canViewDashboard()` / `canEditDashboard()` / `canAddWidget()` / `canRemoveWidget()` / `canCreateDashboard()`, `ActionAuthService::requireAction()` for ADR-023-gated actions, and the admin requirement for `instance`-reach tools. This MUST be centralised in a `McpDashboardGate` class (mirroring decidesk's `McpMeetingGate`: authorise() returning an allow/deny result, no `catch (\Throwable) { return null; }` fail-open shapes). A tool MUST NOT reach `ObjectService` or mappers directly for writes — all mutations go through the existing service layer so slug generation, lock checks, placement collision handling, and cascade behaviour hold. - -#### Scenario: Tool denial equals endpoint denial - -- **GIVEN** a caller for whom `PUT /api/dashboard/{id}` would return a permission error -- **WHEN** the same caller's agent invokes `launchpad.updateDashboard` for that dashboard -- **THEN** the tool MUST deny with a structured error -- **AND** no partial mutation MUST occur - -#### Scenario: Admin tools require admin - -- **GIVEN** a non-admin caller -- **WHEN** their agent invokes `launchpad.createTemplate` -- **THEN** the gate MUST deny exactly as `admin#createTemplate` does for that caller - -#### Scenario: No fail-open on gate errors - -- **GIVEN** the authorization service throws during a tool call -- **WHEN** the gate evaluates the request -- **THEN** the result MUST be a denial, never a silent allow - -### Requirement: REQ-MCP-005 Argument validation before any service call - -Every tool MUST validate its arguments against its declared `inputSchema` before touching a service, via a `McpArgumentValidator` (decidesk pattern: typed UUID/date/string-length checks returning a structured error array on failure). Invalid arguments MUST produce a validation error result, never an exception escaping the provider and never a service call with coerced values. - -#### Scenario: Malformed UUID is rejected - -- **GIVEN** an agent invokes `launchpad.getDashboard` with `dashboardUuid: "../../etc"` -- **WHEN** the validator runs -- **THEN** the tool MUST return a validation error without any service or database access - -#### Scenario: Out-of-range grid values are rejected - -- **GIVEN** `launchpad.updateWidgetPlacement` is invoked with a negative `gridWidth` -- **WHEN** the validator runs -- **THEN** the tool MUST return a validation error naming the offending field - -### Requirement: REQ-MCP-006 Destructive and external tools are flagged for human approval and audited - -Tools with scope `delete`, and all tools with reach `external`, MUST carry a destructive/approval annotation so hermiq inserts its human approval gate before execution. Every write tool invocation (allowed or denied) MUST be auditable: the provider returns enough structured context (tool id, target uuid/id, caller uid, outcome) for hermiq's audit trail to record the action. - -#### Scenario: Delete requires approval - -- **GIVEN** a user tells the chat "delete my old sales dashboard" -- **WHEN** the agent resolves this to `launchpad.deleteDashboard` -- **THEN** hermiq MUST present a human approval step before the tool runs -- **AND** the approval and execution MUST both land in the audit trail - -#### Scenario: Public link requires approval - -- **GIVEN** an agent invokes `launchpad.createPublicShareLink` -- **WHEN** hermiq evaluates the call -- **THEN** the external-reach annotation MUST trigger the approval gate even if the agent holds a `create/external` grant - -### Requirement: REQ-MCP-007 Deliberate exclusions from the tool surface - -The following real endpoints MUST NOT get tools, and the catalogue MUST stay closed against them without an explicit spec change: - -- **Telemetry recorders** — `dashboardApi#viewEvent`, `tileAnalytics#recordClick`: an agent invoking these fabricates analytics. -- **Acknowledgements (write)** — `acknowledgement#acknowledge`: a mandatory-read acknowledgement is compliance evidence of a *human* act; an agent must never acknowledge on a user's behalf. (The read side, `listPendingAcknowledgements`, is exposed.) -- **Binary upload endpoints** — `resource#upload`/`#uploadMultipart`, `admin#uploadTemplatePreviewImage`, `filesWidget#upload`: multipart/base64 payloads are not chat-tool shaped; revisit if a file-reference contract lands. -- **Editing locks** — `dashboardLockApi#*`: locks serialize *interactive* editing sessions; tool calls are single atomic service operations and must not hold or break user locks. -- **One-off admin plumbing** — setup wizard, Confluence import, orphaned-data cleanup, demo showcases, bulk operations, export/import, role/metadata-field/org-navigation/footer/settings administration: high blast radius, no chat use case; deliberately out of v1. - -#### Scenario: Catalogue contains no excluded tool - -- **GIVEN** the provider's catalogue -- **WHEN** its ids are compared against the exclusion list -- **THEN** no tool MUST exist for any excluded endpoint -- **AND** the catalogue MUST contain exactly the tools of REQ-MCP-002 and REQ-MCP-003 - -### Requirement: REQ-MCP-008 Chat command flows resolve to tool sequences - -The catalogue MUST be sufficient for hermiq to execute common chat commands as short tool sequences using only declared tools, with all resolution (name → uuid, widget label → widgetKey) done via read tools first. - -#### Scenario: "Add the calendar widget to my dashboard" - -- **GIVEN** a user with an active personal dashboard and an agent granted `read/self` and `create/self` -- **WHEN** the user sends "add the calendar widget to my dashboard" -- **THEN** the agent MUST be able to resolve it as `launchpad.getActiveDashboard` → `launchpad.listWidgetTypes` (find the calendar widgetKey) → `launchpad.addWidget` -- **AND** the widget MUST appear on the dashboard exactly as if added through the UI - -#### Scenario: "Share my team dashboard with the sales group" - -- **GIVEN** an agent granted `read/self` and `create/user` -- **WHEN** the user sends "share my team dashboard with the sales group" -- **THEN** the agent MUST resolve the dashboard via `launchpad.listDashboards`, then invoke `launchpad.shareDashboard` with a group share for `sales` -- **AND** the share MUST be identical to one created via `POST /api/dashboard/{id}/shares` - -#### Scenario: "Start me a dashboard from the sprint template and make it my default" - -- **GIVEN** an agent granted `read/self`, `create/self`, and `update/self` -- **WHEN** the user sends the command -- **THEN** the agent MUST resolve it as `launchpad.listTemplates` → `launchpad.forkDashboard` → `launchpad.setDefaultDashboard` -- **AND** the resulting dashboard MUST be the caller's default landing dashboard - -### Requirement: REQ-MCP-009 Read-only x-openregister-mcp block on the Dashboard schema - -A register.d overlay MUST declare `x-openregister-mcp` on the `Dashboard` schema with auto-derived **read** tools only (`search`, `get` with `readOnlyHint: true`, openconnector pattern). Auto-derived CRUD writes MUST NOT be enabled: dashboard mutations bypass `DashboardService` invariants (slug generation, permission levels, lock checks) if written as raw objects, so all writes stay with the provider tools of REQ-MCP-003. - -#### Scenario: Schema-derived tools are read-only - -- **GIVEN** the imported Dashboard schema -- **WHEN** OpenRegister derives MCP tools from its `x-openregister-mcp` block -- **THEN** only `search` and `get` MUST be derived, both read-only -- **AND** no derived create/update/delete tool MUST exist for the Dashboard schema diff --git a/openspec/changes/mcp-tool-surface/tasks.md b/openspec/changes/mcp-tool-surface/tasks.md deleted file mode 100644 index 81aebdfda..000000000 --- a/openspec/changes/mcp-tool-surface/tasks.md +++ /dev/null @@ -1,72 +0,0 @@ -# Tasks — mcp-tool-surface - -## Provider Skeleton - -- [ ] Task 1: REQ-MCP-001 — Create `lib/Mcp/LaunchpadToolProvider.php` implementing `OCA\OpenRegister\Mcp\IMcpToolProvider`: dispatcher only, tool catalogue as a `TOOL_DESCRIPTORS` class constant (unit-testable fixture), routing to domain handler classes — mirror `decidesk/lib/Mcp/DecideskToolProvider.php` -- [ ] Task 2: REQ-MCP-001 — Register the string DI alias `'OCA\\OpenRegister\\Mcp\\IMcpToolProvider::launchpad'` in `lib/AppInfo/Application::register()` (string alias, no autoload at registration — decidesk's `DomainServiceRegistrar` pattern, ADR-083 boot safety) -- [ ] Task 3: REQ-MCP-001 — All tool ids namespaced `launchpad.{toolName}`; add a unit test asserting the namespace and id uniqueness across the catalogue - -## Gate and Validator - -- [ ] Task 4: REQ-MCP-004 — Create `lib/Mcp/McpDashboardGate.php`: `currentUserId()`, `authorise(toolId, args)` delegating to `PermissionService::canViewDashboard()/canEditDashboard()/canAddWidget()/canRemoveWidget()/canCreateDashboard()`, `ActionAuthService::requireAction()` for ADR-023-gated actions, and the admin check for `instance`-reach tools. No `catch (\Throwable) { return null; }` shapes (hydra-gate-unsafe-auth-resolver) -- [ ] Task 5: REQ-MCP-005 — Create `lib/Mcp/McpArgumentValidator.php`: UUID, id, string-length, enum, and grid-bound checks returning structured error arrays (decidesk's validator as the template) -- [ ] Task 6: REQ-MCP-004 — Every handler: validate → authorise → call the existing service (`DashboardService`, `WidgetService`/`WidgetPlacementService`, `TileService`, `DashboardShareService`, `PublicShareService`, `KioskService`, `TemplateService`/`AdminTemplateService`, `ReactionService`, `AcknowledgementService`, `MetadataService`, `DashboardVersionService`). Never controllers, never mappers/ObjectService directly for writes - -## Read Tools (REQ-MCP-002) - -- [ ] Task 7: Implement the 14 read tools in `lib/Mcp/McpDashboardTools.php` (dashboard reads) and sibling handler classes: listDashboards, getDashboard, getActiveDashboard, getDashboardTree, listGroupDashboards, listWidgetTypes, listTiles, listShares, listVersions, listTemplates, getDashboardMetadata, getReactions, listPendingAcknowledgements, listKioskPlaylists — all `readOnlyHint: true`, scope `read`, reach `self` -- [ ] Task 8: REQ-MCP-002 — Unit test: each read tool's result for a fixture caller equals the visibility the corresponding service call grants that caller (visible-set parity, not superset) - -## Write Tools (REQ-MCP-003) - -- [ ] Task 9: Implement the 18 `self`-reach write tools (dashboard CRUD, active/default, fork, widget add/update/remove, tile CRUD + addTileToDashboard, version create/restore, metadata set, reaction add/remove) with per-tool `inputSchema` -- [ ] Task 10: Implement the 4 `user`-reach tools (shareDashboard, replaceShares, unshareDashboard, setPublicationState) -- [ ] Task 11: Implement the 5 `external`-reach tools (createPublicShareLink, revokePublicShareLink, createKioskPlaylist, updateKioskPlaylist, deleteKioskPlaylist) -- [ ] Task 12: Implement the 8 `instance`-reach tools (group dashboard CRUD, setGroupDefault, template create/update/delete/resync) -- [ ] Task 13: REQ-MCP-003 — Unit test on the descriptor fixture: every write tool declares exactly one scope ∈ {create, update, delete} and one reach ∈ {self, user, instance, external}; no write carries `readOnlyHint: true` -- [ ] Task 14: REQ-MCP-006 — Annotate all `delete`-scope and all `external`-reach tools with the destructive/approval flag hermiq's approval gate consumes; every handler result includes tool id, target identifier, caller uid, and outcome for the audit trail - -## Exclusions (REQ-MCP-007) - -- [ ] Task 15: Unit test asserting catalogue closure: the descriptor set equals exactly the REQ-MCP-002 + REQ-MCP-003 ids, and contains no tool for viewEvent, tile-click recording, `acknowledgement#acknowledge`, resource/preview/files uploads, lock endpoints, wizard, Confluence import, cleanup, demo showcases, bulk ops, export/import, or settings surfaces -- [ ] Task 16: Document the exclusion rationale in the provider's class docblock so a future "completeness" sweep reads why before adding - -## Schema Overlay (REQ-MCP-009) - -- [ ] Task 17: Create `lib/Settings/register.d/dashboard-mcp.json` adding an `x-openregister-mcp` block to the `Dashboard` schema with read-only `search` and `get` tools (`readOnlyHint: true`, scope `read`, sensible `filters` such as title/slug/type/groupId — openconnector's endpoint block as the template). No derived writes -- [ ] Task 18: Verify the imported schema carries the block (check the imported schema via OpenRegister, not the file — the importer can reject silently) - -## Authorization Parity Tests (REQ-MCP-004/005) - -- [ ] Task 19: PHPUnit — for a non-owner caller: updateDashboard, deleteDashboard, addWidget, and shareDashboard tools all deny; assert no state change (subclass `ObjectEntity`-backed fixtures rather than mocking magic accessors) -- [ ] Task 20: PHPUnit — non-admin caller invoking each `instance`-reach tool is denied by the gate -- [ ] Task 21: PHPUnit — gate error path: a throwing PermissionService produces a denial result, never an allow -- [ ] Task 22: PHPUnit — validator rejections: malformed UUID, over-long title, invalid enum, negative grid values — each returns a structured error and performs no service call - -## Integration / Chat Flows (REQ-MCP-008) - -- [ ] Task 23: Integration test — "add the calendar widget": getActiveDashboard → listWidgetTypes → addWidget, assert the placement exists via `GET /api/widgets/items` equivalence -- [ ] Task 24: Integration test — "share with the sales group": listDashboards → shareDashboard(group: sales), assert parity with `POST /api/dashboard/{id}/shares` output -- [ ] Task 25: Integration test — "template to default": listTemplates → forkDashboard → setDefaultDashboard, assert `GET /api/dashboards/default` returns the fork - -## Quality & Integration - -- [ ] Task 26: `composer check:strict` clean (PHPCS, PHPMD, Psalm, PHPStan) including the new `lib/Mcp/` namespace; SPDX headers on every new PHP file (hydra-gate-spdx) -- [ ] Task 27: Run the hydra gates; specifically confirm no orphan-auth finding (every gate method must be called) and no redundant-controller finding (no wrapper controllers were added) -- [ ] Task 28: Boot test without OpenRegister installed: app registers and the launchpad UI loads (alias unresolved is acceptable; boot failure is not) - -## Verification - -`openspec validate` exits clean. Catalogue = exactly 14 read + 35 write tools, all annotated; alias resolves; parity tests green; exclusion-closure test green; the three chat flows execute end-to-end against a dev instance through hermiq or a direct provider harness. - -## Tests (company-wide ADR-009) - -PHPUnit unit tests per Tasks 3, 8, 13, 15, 19–22 (descriptor fixture + gate + validator). Integration tests per Tasks 23–25. No Playwright surface — this change ships no launchpad UI. - -## Documentation (company-wide ADR-010) - -Changelog entry: "LaunchPad actions are now available as MCP tools for AI agents (hermiq), with per-tool scope/reach grants." A docs page listing the tool catalogue with scope/reach per tool, generated from or checked against the descriptor constant so it cannot drift. - -## i18n (company-wide ADR-005) - -Tool names/descriptions are agent-facing contract strings and remain English (per the English-code rule); no user-facing UI strings are introduced. diff --git a/openspec/changes/openregister-leaf-integrations/design.md b/openspec/changes/openregister-leaf-integrations/design.md deleted file mode 100644 index 80ee75496..000000000 --- a/openspec/changes/openregister-leaf-integrations/design.md +++ /dev/null @@ -1,78 +0,0 @@ -# Design — OpenRegister Leaf Integrations (Talk on Shared Dashboards) - -## Context - -OpenRegister's integration leaves are adopted declaratively (`configuration.linkedTypes` on a schema). LaunchPad has a single `Dashboard` schema and currently adopts zero leaves. The design question for this change was not "how do we build a discussion feature" — the leaf and Talk own that — but three scoping decisions: - -1. Which leaves, if any, honestly fit a schema whose objects are layout configurations rather than domain records? -2. Where does the leaf declaration live — base register file or a `register.d` overlay? -3. What gates the discussion surface — a new ACL, or the existing dashboard view guard? - -## Goals / Non-Goals - -**Goals:** - -- Adopt the talk leaf for shared and group dashboards with zero bespoke chat code. -- Keep the declaration additive and overlay-based so the base register file stays a clean statement of the domain. -- Reuse `PermissionService::canViewDashboard()` as the single authorization truth for discussion access. -- Document explicitly why the remaining ~18 leaves are not adopted, so future sweeps do not re-litigate this. - -**Non-Goals:** - -- Building comments, mentions, or notification features in launchpad — the leaf renders, Talk hosts. -- Adopting the files leaf, mail sidebar linking (`configuration.linkedTypes: ["mail"]`), or `mailObjectTemplate` — see D1. -- Per-widget or per-tile discussions — the conversation unit is the dashboard object. - -## Decisions - -### D1: Adopt exactly one leaf — talk. Every other leaf is scoped out. - -**Decision**: Declare only `"talk"` in `linkedTypes`. No files, no mail, no calendar/contacts/maps/etc. - -**Alternatives considered:** - -- **Adopt files + talk** (the two "generic collaboration" leaves): rejected for files because LaunchPad already owns a resource pipeline for dashboard assets (`ResourceController`/`ResourceService`, REQ-RES-001..014, routes `/api/resources*`) and a files widget for user storage. A generic attachments panel on a layout-configuration object duplicates that machinery with no user story behind it. -- **Adopt the full catalogue for uniformity with sibling apps**: rejected — sibling apps (larpingapp, pipelinq, shillinq) attach leaves to schemas describing people, events, contracts. `Dashboard` describes none of these; declaring leaves that render meaningless panels is padding, and an unused surface is an unaudited surface. - -**Rationale**: The one place LaunchPad has real multi-user collaboration around a single object is shared/group dashboards (manifest features "Dashboard sharing", "Group dashboards"; `sharedWith`, `type: group_shared`, `groupId` in the schema; the whole REQ-SHARE surface). A conversation about *this dashboard* is the only leaf-shaped gap. The schema's own `"mailEnabled": false` confirms mail was already considered and rejected at the domain level. - -### D2: Declaration lives in a `register.d` overlay, not the base register file - -**Decision**: New file `lib/Settings/register.d/dashboard-talk-leaf.json` containing only the `configuration.linkedTypes` addition for the `Dashboard` schema. - -**Alternatives considered:** - -- **Edit `launchpad_register.json` directly**: rejected. The fleet pattern (larpingapp's `register.d/*-leaf.json` overlays) keeps each leaf adoption a self-contained, reviewable, revertable file, and keeps the base file a pure domain statement. LaunchPad's `register.d/` directory already exists (README only) precisely for this. - -**Rationale**: Overlay files make the adoption diff one file, and removing the leaf later is deleting one file rather than surgically editing the 310-line base register. - -### D3: Discussion access = dashboard view access; surface only on shared dashboards - -**Decision**: The discussion surface renders only when the dashboard is collaborative (`group_shared`, or has active shares / non-empty `sharedWith`), and reaching it requires `PermissionService::canViewDashboard()` to pass. Share revocation ends access. - -**Alternatives considered:** - -- **Show discussion on every dashboard, including unshared personal ones**: rejected — a room with one member is noise, and it would create Talk rooms for thousands of personal dashboards nobody discusses. -- **Separate discussion ACL (opt-in per participant)**: rejected — a second ACL diverges from the dashboard's own access over time (the classic parallel-permission drift), and the view guard already encodes owner/share/group logic in one audited place. - -**Rationale**: One authorization truth. `canViewDashboard()` already resolves ownership, user/group shares, and group membership; the leaf simply inherits its answer. - -### D4: Hard fail nowhere — Talk absence degrades to absence of the surface - -**Decision**: With Talk missing/disabled the affordance does not render and nothing errors. LaunchPad's manifest does not gain a Talk dependency. - -**Rationale**: LaunchPad must keep booting and rendering dashboards on instances without Talk (ADR-083-style boot safety); an integration leaf is an enhancement, never a prerequisite. - -## Risks / Trade-offs - -- **Risk**: The leaf's render contract may evolve in OpenRegister; launchpad's wiring is intentionally thin so the blast radius is the overlay file plus one mount point. -- **Trade-off**: Users of unshared personal dashboards get no discussion surface at all. Accepted: share the dashboard first — that is the collaboration signal. -- **Risk**: Schema overlay import failing silently (see the cautionary note inside `launchpad_register.json` about the schema importer rejecting union types). Mitigated by an explicit import verification task. - -## Migration Plan - -None required. The overlay is additive; no data or existing-object changes. Rollback = delete the overlay file and re-import. - -## Open Questions - -- Whether the discussion mounts in the dashboard sidebar or the dashboard settings panel is left to the leaf's standard render surface — decided at implementation against the leaf's contract, not re-specified here. diff --git a/openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md b/openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md deleted file mode 100644 index 2757bffdd..000000000 --- a/openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf/spec.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -capability: dashboard-talk-leaf -delta: false -status: draft ---- - -# Dashboard Talk Leaf — Discussion on Shared Dashboards - -## Context - -LaunchPad stores dashboards as OpenRegister objects under a single `Dashboard` schema (`lib/Settings/launchpad_register.json`). OpenRegister ships an app-agnostic **talk** integration leaf that any app can adopt by declaring `configuration.linkedTypes: ["talk"]` on a schema. This capability adopts that leaf — and only that leaf — so the people a dashboard is shared with can discuss it in a Talk conversation bound to the dashboard object. No bespoke chat code, storage, or wrapper controllers are added. - -## ADDED Requirements - -### Requirement: REQ-LEAF-001 Talk leaf declared on the Dashboard schema via register.d overlay - -The talk leaf MUST be declared declaratively, not in code. A new overlay file `lib/Settings/register.d/dashboard-talk-leaf.json` MUST add `configuration.linkedTypes: ["talk"]` to the `Dashboard` schema, following the established fleet overlay shape (`components.schemas.Dashboard.configuration.linkedTypes`, as in larpingapp's `register.d/player-to-contacts-leaf.json`). The base `launchpad_register.json` MUST NOT be edited for this; the overlay is the single source of the declaration. - -#### Scenario: Overlay declares the leaf - -- **GIVEN** the app is installed or upgraded with the overlay file present -- **WHEN** the register/schema import runs -- **THEN** the imported `Dashboard` schema MUST carry `configuration.linkedTypes` containing exactly `"talk"` -- **AND** no other leaf type MUST be declared by launchpad - -#### Scenario: Base register file untouched - -- **GIVEN** the change is implemented -- **WHEN** `lib/Settings/launchpad_register.json` is inspected -- **THEN** it MUST contain no `linkedTypes` key — the declaration lives only in `register.d/dashboard-talk-leaf.json` - -### Requirement: REQ-LEAF-002 Discussion surface renders only on shared dashboards - -The Talk discussion surface MUST render only for dashboards that are genuinely collaborative: `type === 'group_shared'`, or a dashboard with at least one active share (user/group shares via `DashboardShareService`, or a non-empty `sharedWith`). A personal dashboard with no shares MUST NOT show any discussion affordance — there is nobody to talk to. - -#### Scenario: Group dashboard shows discussion - -- **GIVEN** a `group_shared` dashboard scoped to group `marketing` -- **WHEN** a member of `marketing` opens that dashboard -- **THEN** the Talk discussion surface MUST be available for that dashboard - -#### Scenario: Shared personal dashboard shows discussion - -- **GIVEN** a personal dashboard the owner has shared with user `alice` -- **WHEN** the owner or `alice` opens the dashboard -- **THEN** the Talk discussion surface MUST be available - -#### Scenario: Unshared personal dashboard shows nothing - -- **GIVEN** a personal dashboard with no shares and empty `sharedWith` -- **WHEN** its owner opens it -- **THEN** no discussion affordance MUST render -- **AND** no Talk room MUST be created for it - -### Requirement: REQ-LEAF-003 Discussion access follows the existing view guard - -Access to a dashboard's discussion MUST be gated by the same authorization the dashboard itself uses: a user may see or join the discussion only if `PermissionService::canViewDashboard()` grants them view access to that dashboard. The leaf MUST NOT introduce a parallel ACL, and losing view access (share revoked via `DashboardShareApiController::destroy`/`revokeForRecipient`) MUST also end discussion access. - -#### Scenario: Non-viewer cannot reach the discussion - -- **GIVEN** a dashboard user `bob` has no view access to -- **WHEN** `bob` attempts to access that dashboard's Talk discussion -- **THEN** access MUST be denied with the same outcome as accessing the dashboard itself - -#### Scenario: Revoking a share ends discussion access - -- **GIVEN** `alice` had a share on a dashboard and participated in its discussion -- **WHEN** the owner revokes `alice`'s share -- **THEN** `alice` MUST no longer be able to access the dashboard's discussion surface through launchpad - -### Requirement: REQ-LEAF-004 Graceful degradation without Talk - -When the Talk app is not installed or is disabled, the leaf MUST degrade silently: no discussion affordance renders, no error is logged per page view, and every other dashboard function remains unaffected. LaunchPad MUST NOT hard-depend on Talk. - -#### Scenario: Talk absent - -- **GIVEN** an instance where Talk is not installed -- **WHEN** a user opens a `group_shared` dashboard -- **THEN** the dashboard MUST render fully with no discussion surface and no user-visible error - -### Requirement: REQ-LEAF-005 No launchpad-side wrapper code - -Per ADR-022 (apps consume OR abstractions), launchpad MUST NOT add controllers, routes, or services that proxy Talk or the leaf. Room lifecycle, membership, and messages are the leaf's and Talk's responsibility. The only server-side artifact of this capability is the register.d overlay. - -#### Scenario: No proxy endpoints appear - -- **GIVEN** the change is implemented -- **WHEN** `appinfo/routes.php` and `lib/Controller/` are inspected -- **THEN** no new Talk- or discussion-related route or controller MUST exist diff --git a/openspec/changes/openregister-leaf-integrations/tasks.md b/openspec/changes/openregister-leaf-integrations/tasks.md deleted file mode 100644 index 3fa9862c5..000000000 --- a/openspec/changes/openregister-leaf-integrations/tasks.md +++ /dev/null @@ -1,47 +0,0 @@ -# Tasks — openregister-leaf-integrations - -## Schema Overlay - -- [ ] Task 1: REQ-LEAF-001 — Create `lib/Settings/register.d/dashboard-talk-leaf.json` with the fleet overlay shape: `{"components": {"schemas": {"Dashboard": {"configuration": {"linkedTypes": ["talk"]}}}}` (mirror larpingapp's `register.d/player-to-contacts-leaf.json`) -- [ ] Task 2: REQ-LEAF-001 — Do NOT touch `lib/Settings/launchpad_register.json`; verify with `git diff --stat` that the base register file is unchanged -- [ ] Task 3: REQ-LEAF-001 — Verify the overlay actually imports: after `occ app:enable launchpad` (or the register repair step), fetch the Dashboard schema from OpenRegister and assert `configuration.linkedTypes == ["talk"]`. The register json itself warns that the importer can silently reject a schema — check the imported schema, not the file. - -## Frontend Wiring - -- [ ] Task 4: REQ-LEAF-002 — Mount the talk leaf's render surface on the dashboard view for collaborative dashboards only: `type === 'group_shared'` OR the dashboard has active shares (via the existing shares data from `GET /api/dashboard/{id}/shares`) OR `sharedWith` is non-empty -- [ ] Task 5: REQ-LEAF-002 — Ensure no discussion affordance renders for unshared personal dashboards (no hidden mount, no room creation side effect) -- [ ] Task 6: REQ-LEAF-004 — Feature-detect the leaf/Talk availability; when absent, skip the mount without console errors or server log noise - -## Authorization - -- [ ] Task 7: REQ-LEAF-003 — Confirm the leaf's access path resolves through `PermissionService::canViewDashboard()` (directly or via the object-level guard OpenRegister applies); document the resolved chain in the code comment at the mount point -- [ ] Task 8: REQ-LEAF-003 — Verify share revocation (`dashboardShareApi#destroy`, `dashboardShareApi#revokeForRecipient`) ends discussion access for the revoked user - -## Guardrails - -- [ ] Task 9: REQ-LEAF-005 — Verify no new routes, controllers, or services were added: `appinfo/routes.php` and `lib/Controller/` diff must be empty for this change -- [ ] Task 10: Run `composer check:strict` and the hydra gates; the change must not introduce findings - -## Testing - -- [ ] Task 11: Playwright test — group dashboard (member of the group): discussion surface present -- [ ] Task 12: Playwright test — personal dashboard shared with a second user: discussion surface present for both owner and recipient -- [ ] Task 13: Playwright test — unshared personal dashboard: no discussion affordance in the DOM -- [ ] Task 14: Playwright test — non-viewer attempting the dashboard (and its discussion) is denied identically for both -- [ ] Task 15: Test with Talk disabled — dashboard renders fully, no error surfaced - -## Verification - -`openspec validate` exits clean. The imported Dashboard schema carries `linkedTypes: ["talk"]`; the discussion surface appears exactly on collaborative dashboards; access tracks `canViewDashboard()`; zero new launchpad endpoints; Talk absence degrades silently. - -## Tests (company-wide ADR-009) - -Playwright end-to-end tests per Tasks 11–15. No unit-test surface exists in launchpad for this change (no new PHP or JS logic beyond the mount condition, which the e2e tests cover). - -## Documentation (company-wide ADR-010) - -Changelog entry: "Shared and group dashboards can now be discussed in Talk (OpenRegister talk leaf)". A short docs note in the sharing documentation page stating where the discussion appears and that it requires Talk. - -## i18n (company-wide ADR-005) - -Any launchpad-owned label around the mount (e.g. a section heading, if one is added) gets English and Dutch strings; the leaf's own UI ships its own translations. diff --git a/openspec/changes/platform-dashboard-theme-and-css/tasks.md b/openspec/changes/platform-dashboard-theme-and-css/tasks.md deleted file mode 100644 index 80e1a80b9..000000000 --- a/openspec/changes/platform-dashboard-theme-and-css/tasks.md +++ /dev/null @@ -1,19 +0,0 @@ -# Tasks: platform-dashboard-theme-and-css - -## Backend - -- [ ] 1. Add the four columns in a migration with getters and setters on `lib/Db/Dashboard.php`, exposed in the dashboard JSON. Verify: migration test and a serialisation test. -- [ ] 2. Validate the look in `DashboardService::updateDashboard()` (hex colours, resource belongs to the dashboard or is shared, accent at least 3:1 against the background, derived text colour). Verify: PHPUnit. -- [ ] 3. Add `sabberworm/php-css-parser` and `CustomCssSanitiser` as in D3. Verify: PHPUnit per dropped construct, scoping and the size cap; `composer audit` clean. -- [ ] 4. Allow `custom_css` only for administrators on dashboards and add the global `custom_css` admin setting. Verify: PHPUnit for 403 on a non-admin. - -## Frontend - -- [ ] 5. Add the "Look" tab to `src/modals/DashboardConfigModal.vue` with colour pickers, the resource picker and live contrast. Verify: Vitest and an axe check. -- [ ] 6. Apply the look and scoped CSS in `src/views/WorkspaceApp.vue` to the dashboard region only, inserting CSS as text. Verify: Vitest. -- [ ] 7. Add the admin CSS section showing what the sanitiser dropped. Verify: Vitest. - -## Close - -- [ ] 8. Playwright: one dashboard's look changes nothing else; `@import` is dropped. -- [ ] 9. Add `nl` and `en` strings, fold the delta into `openspec/specs/dashboards/spec.md` on archive, and set d-theme-per-dashboard and p-custom-css to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/public-dashboard-publication/proposal.md b/openspec/changes/public-dashboard-publication/proposal.md deleted file mode 100644 index 533db3655..000000000 --- a/openspec/changes/public-dashboard-publication/proposal.md +++ /dev/null @@ -1,56 +0,0 @@ -# Public Dashboard Publication - -LaunchPad dashboards are today identity-bound — every viewer is an authenticated user and every view is recorded against that user. This is correct for internal BI and for the existing `dashboard-sharing` capability which lets one user share with another identified user. It is wrong for open-overheid use cases where any citizen should be able to view a live dashboard without a login. - -This change introduces a publication channel — distinct from sharing — that lets a dashboard owner mark a dashboard as publishable and choose from three publication modes (fully public, signed-URL with expiry, password-gated). The owner can apply a publication-specific brand chrome (gemeente logo, colours, footer), configure search-engine indexing and caching directives, and surface traffic metrics in aggregate form (no per-citizen tracking). All data queries on a published dashboard run as a designated "publication service account" so the viewer never inherits elevated permissions. - -This change scopes deliberately to read-only viewing. Interactive filtering, comment threads, and authenticated personalisation belong to a future `interactive-public-dashboard` change. - -## Affected code units - -- `lib/Service/PublicationService.php` — manage DashboardPublication, PublicationBranding, PublicationAccess configurations -- `lib/Service/PublicationAuthService.php` — validate access against mode (public, signed, password) -- `lib/Service/PublicationQueryService.php` — execute dashboard queries as publication service account -- `lib/Service/PublicationAnalyticsService.php` — aggregate view counts per hour, no PII -- `lib/Controller/PublicationController.php` — `/api/publication/{slug}` read endpoint (anon-accessible) -- `lib/Controller/PublicationSettingsController.php` — owner config endpoints (auth-required) -- OpenRegister schemas: `DashboardPublication`, `PublicationBranding`, `PublicationAccess`, `SignedUrlGrant`, `PasswordGate`, `PublicationServiceAccount`, `PublicationViewLog` - -## Why a new capability - -Publication is a distinct use case with its own data model, access-control rules, query-execution context, and analytics. Folding it into `dashboard-sharing` would conflate two incompatible flows: identity-bound sharing with per-user ACLs, and anonymous publication with service-account queries. - -## Approach - -- **Configuration**: Owner marks a dashboard as publishable and configures mode, slug, branding, robots policy, cache headers via a publication-settings form. -- **Access validation**: Signed mode validates tamper-evident signature + expiry. Password mode validates hash against configured password. Public mode allows all. -- **Query execution**: All dashboard queries execute as a pre-configured publication service account with its own register/schema permissions. -- **Branding**: Publication-specific logo, colours, footer, language, and meta tags replace the internal LaunchPad chrome on the public-view route. -- **Indexing**: X-Robots-Tag and meta-robots directives honour the configured robotsPolicy so search engines follow the owner's intent. -- **Caching**: Cache-Control headers and ETag support enable CDN fronting at scale. -- **Analytics**: View counts recorded per hour bucket derived from salted session-cookie hashes — no backreferable identity tracking. - -## Capabilities - -**New Capabilities:** -- `public-dashboard-publication`: Owner-configured publication of read-only dashboards to anonymous viewers without authentication, with mode selection (public, signed, password), custom branding, SEO/cache control, and aggregate analytics. - -## Standards - -- WCAG 2.2 AA for gemeente public-facing pages -- Wet Digitale Overheid accessibility statement requirement -- AVG/GDPR aggregate-only analytics (no tracking cookies) -- Forum Standaardisatie DCAT-AP for open-data resource registration -- HTTP caching (RFC 9111) Cache-Control and conditional GET semantics - -## Cross-app dependencies - -- **launchpad dashboard-sharing**: distinct surface; sharing is identity-bound, publication is anonymous -- **opencatalogi**: published dashboards can be registered as open-data resources -- **openregister**: publication service account permissions enforced at register/schema layer -- **openconnector**: optional CDN front provisioned via connector -- **nldesign**: branding defaults derived from active nldesign palette - -## Target users - -Gemeente communicatie-afdelingen, open-data coördinatoren, journalisten, raadsgriffies, MKB klanten sharing KPI-pages with partners, and citizens viewing published open-data dashboards. diff --git a/openspec/changes/responsehelper-instance-api/proposal.md b/openspec/changes/responsehelper-instance-api/proposal.md deleted file mode 100644 index b0d498e0d..000000000 --- a/openspec/changes/responsehelper-instance-api/proposal.md +++ /dev/null @@ -1,145 +0,0 @@ -# ResponseHelper: migrate from an all-static helper to an injected instance API - -> **STATUS: RAISED FOR HUMAN DECISION — NOT APPROVED, NOT STARTED.** -> This change is deliberately spec-first. No code has been changed. See -> "Why this is a proposal and not a patch" below. - -## Why - -`ResponseHelper` is the single largest source of PHPMD debt in this repository, by a -wide margin. - -Measured on `development` at commit `d086d16` with the PHPMD baseline deleted -(PHP 8.4, `phpmd.xml` + `phpmd-unusedparams.xml`): - -| Measure | Count | -| --- | --- | -| Total findings, baseline deleted | 443 | -| …of which `StaticAccess` | 271 | -| …of which `StaticAccess` on `ResponseHelper::*` | **219 (49% of the repo total)** | - -After the complexity burndown that accompanies this proposal the repository total -is 349, and `ResponseHelper` accounts for **218 of the 270 remaining -`StaticAccess` findings — 62% of everything left**. No other single change comes -close: retiring it would take launchpad from 349 findings to roughly 131. - -The rule is not arbitrary. `rulesets/cleancode.xml/StaticAccess` fires because a -static call is a hard-coded, non-substitutable dependency: a controller that calls -`ResponseHelper::error()` cannot have that collaborator replaced in a test, cannot -have it decorated, and cannot have its behaviour varied per deployment. That is a -real design constraint, and it is the reason the project enabled the rule. - -There is also a latent correctness issue the static form makes worse. The spec -itself records it (REQ-DASH-041, Notes): - -> The "logger optional" path in `ResponseHelper::error()` is a latent risk: a -> caller that forgets to wire the logger gets silently dropped exceptions with no -> audit trail. Future-tightening TODO: make `LoggerInterface` non-nullable in a -> follow-up change once every call site is converted. - -That future-tightening is **not achievable in the static form**. A static method -cannot hold an injected logger, so every call site must pass one explicitly, which -is exactly the thing callers forget. An injected instance receives its -`LoggerInterface` once, from the DI container, and the "forgot the logger" failure -mode disappears by construction. This proposal is therefore the enabling step for -a fix the spec has already asked for. - -## Why this is a proposal and not a patch - -**The static form is pinned by the canonical spec.** `openspec/specs/dashboards/spec.md` -does not merely describe the current implementation — it makes the static call -shape normative and then asserts it in scenarios: - -- REQ-DASH-040: *"List responses MUST be serialized via `ResponseHelper::serializeList()`"* -- REQ-DASH-040, scenario: *"WHEN a controller calls `ResponseHelper::unauthorized()`"* -- REQ-DASH-040, scenario: *"WHEN a controller calls `ResponseHelper::forbidden('Dashboard creation not allowed')`"* -- REQ-DASH-040, scenario: *"WHEN a controller calls `ResponseHelper::success(['id' => 1], 201)`"* -- REQ-DASH-040, scenario: *"WHEN a controller calls `ResponseHelper::serializeList($dashboards)`"* -- REQ-DASH-041: *"MUST translate caught exceptions … via `ResponseHelper::error()`"* -- REQ-DASH-041, scenario: *"WHEN the controller calls `ResponseHelper::error($e, 500, $logger, 'Could not save dashboard')`"* - -Unilaterally refactoring the code to `$this->responseHelper->error(...)` would put -the implementation in **direct contradiction with its own normative contract** — -seven spec statements would become false about the shipped code, and the spec would -silently become a description of a system that no longer exists. Quietly editing -the spec to match a refactor inverts the whole point of spec-driven development: -the spec would stop being a decision record and become a changelog. - -So the correct sequencing is **spec first, code second**, and the spec change needs -a human decision because it is a deliberate architectural choice, not a mechanical -cleanup. That decision is what this document asks for. - -## What Changes - -If approved, in this order: - -1. **Amend `openspec/specs/dashboards/spec.md`** — REQ-DASH-040 and REQ-DASH-041 are - restated in terms of an injected `ResponseHelper` instance. The envelope - contract (bodies, status codes, no-message-leak guarantee) is **unchanged**; - only the call shape changes, `ResponseHelper::x()` → `$this->responseHelper->x()`. -2. **Convert `ResponseHelper` to an instance class**, registered in - `lib/AppInfo/Application.php` and injected into the 18 `lib/` files that use it. - `LoggerInterface` becomes a constructor dependency. -3. **Update the 224 call sites** across those 18 files. -4. **Update the 2 test files** that reference `ResponseHelper`. -5. **Tighten `error()`** so `LoggerInterface` is no longer an optional per-call - argument — discharging the standing TODO in the REQ-DASH-041 notes. -6. **Remove the corresponding entries from `phpmd.baseline.xml`.** - -### Deliberately NOT in scope - -- No change to any response body, status code, or header. This is a call-shape - migration; every envelope stays byte-identical, and the existing scenarios - (rewritten for the instance form) are the regression net. -- No change to the other 52 non-`ResponseHelper` `StaticAccess` findings; 24 of - those are `*TableBuilder::create($schema)` in `lib/Migration`, which are - structurally static because NC's migrator instantiates migration steps itself - rather than through DI, and cannot be injected. - -## Capabilities - -### New Capabilities - -(none) - -### Modified Capabilities - -- `dashboards`: REQ-DASH-040 and REQ-DASH-041 restated for an injected instance API. - -## Impact - -**Blast radius (measured, not estimated):** - -- **18 files** under `lib/` reference `ResponseHelper::` -- **224 static call sites** in `lib/` -- **2 test files** reference `ResponseHelper` -- **218 PHPMD `StaticAccess` findings** retired — 62% of everything currently left -- `ResponseHelper` itself is small: **169 lines, 6 public static methods** - (`unauthorized`, `forbidden`, `error`, `quotaExceeded`, `success`, `serializeList`) - -**Risk:** low-to-moderate and almost entirely mechanical. The class is tiny and -stateless, and the change is uniform. The two genuine risks are: - -1. **Constructor churn in 18 controllers/services.** Several already carry - `@SuppressWarnings(PHPMD.CouplingBetweenObjects)` for constructor width; adding - one more collaborator will push some past `ExcessiveParameterList` / - `CouplingBetweenObjects` thresholds. Net PHPMD effect must be re-measured — - trading 218 `StaticAccess` for a handful of coupling findings is still a large - win, but the number should be measured, not assumed. -2. **`serializeList()` is a pure function** with no dependencies. Making it an - instance method is the least defensible part of the change on its own merits; - the argument for it is uniformity of the call shape, not testability. A - reviewer may reasonably prefer to leave `serializeList()` static, which would - leave a residue of `StaticAccess` findings. That trade-off is called out here - rather than decided unilaterally. - -**Alternative considered and rejected:** adding `ResponseHelper` to a PHPMD -`StaticAccess` exceptions list. That would make the 218 findings disappear without -changing anything real, would grant a permanent open licence for all future static -use of the class, and would leave the REQ-DASH-041 logger TODO permanently -unachievable. It is a suppression, not a fix. - -## Decision requested - -Approve, amend, or reject the migration. If approved, the spec amendment (step 1) -lands first and the code follows in its own PR. diff --git a/openspec/changes/responsehelper-instance-api/tasks.md b/openspec/changes/responsehelper-instance-api/tasks.md deleted file mode 100644 index 2407e1950..000000000 --- a/openspec/changes/responsehelper-instance-api/tasks.md +++ /dev/null @@ -1,35 +0,0 @@ -# Tasks — ResponseHelper instance API - -> **BLOCKED: awaiting a human decision on `proposal.md`.** -> Nothing below may start until the proposal is approved. The sequencing is -> spec-first by design — see "Why this is a proposal and not a patch". - -## 1. Spec amendment (must land first, on its own) - -- [ ] 1.1 Amend `openspec/specs/dashboards/spec.md` REQ-DASH-040: restate the - envelope contract for an injected instance; rewrite the four scenarios that - name `ResponseHelper::unauthorized()`, `::forbidden()`, `::success()` and - `::serializeList()`. -- [ ] 1.2 Amend REQ-DASH-041: restate for `$this->responseHelper->error()`; rewrite - both scenarios. -- [ ] 1.3 Decide and record whether `serializeList()` stays static (it is a pure - function with no dependencies — see Impact risk 2). - -## 2. Implementation (only after 1 is merged) - -- [ ] 2.1 Convert `lib/Controller/ResponseHelper.php` to an instance class with a - constructor-injected `LoggerInterface`. -- [ ] 2.2 Register it in `lib/AppInfo/Application.php`. -- [ ] 2.3 Inject it into the 18 `lib/` files that use it; convert all 224 call sites. -- [ ] 2.4 Make `LoggerInterface` non-optional in `error()`, discharging the standing - TODO in the REQ-DASH-041 notes. -- [ ] 2.5 Update the 2 test files referencing `ResponseHelper`. - -## 3. Verification - -- [ ] 3.1 Full unit suite green (baseline 1525 tests / 3877 assertions / 3 skipped). -- [ ] 3.2 Re-measure PHPMD with the baseline deleted. Expect ~218 `StaticAccess` - findings retired. **Measure the net** — constructor widening may add - `ExcessiveParameterList` / `CouplingBetweenObjects` findings (Impact risk 1). -- [ ] 3.3 Remove the corresponding entries from `phpmd.baseline.xml`. -- [ ] 3.4 Confirm no response body, status code or header changed. diff --git a/openspec/changes/retire-groupfolder-storage-backend/tasks.md b/openspec/changes/retire-groupfolder-storage-backend/tasks.md deleted file mode 100644 index 1c9fceb8c..000000000 --- a/openspec/changes/retire-groupfolder-storage-backend/tasks.md +++ /dev/null @@ -1,18 +0,0 @@ -# Tasks — retire-groupfolder-storage-backend - -## Tasks - -- [x] Task 1: Remove the storage tree — `lib/Service/DashboardContentStorage/` (interface, `DbContentStorage`, `GroupFolderContentStorage`, and the three exception classes) and `lib/Service/DashboardContentStorageFactory.php` -- [x] Task 2: Remove the orphaned service and controller surface — `DashboardService::{readDashboardContent,writeDashboardContent,deleteDashboardContent}` and the `?DashboardContentStorageFactory $contentStorageFactory` constructor parameter; `DashboardApiController::storageUnavailableResponse()`; `DashboardMapper::findAll()`, whose only caller was the retired migration command -- [x] Task 3: Remove the `content` and `locale` columns — drop the `$content`/`$locale` properties, `decodeContent()`, the `@method` docblocks and the `jsonSerialize()` keys from `lib/Db/Dashboard.php`, and drop both columns from `launchpad_dashboards` in `lib/Migration/Version002009Date20260811000000.php`. Leave `Version002001Date20260603000000` and `DashboardTableBuilder::addContentStorageColumns()` in place — a shipped migration is part of the version ledger and deleting it would desynchronise instances that have already run it -- [x] Task 4: Remove the two CLI commands — `lib/Command/MigrateStorageToGroupFolder.php` and `lib/Command/ToggleStorageSetting.php`, and their `<command>` entries in `appinfo/info.xml` -- [x] Task 5: Remove the PHPUnit classes that covered the removed tree — `DashboardContentStorageFactoryTest`, `DashboardContentStorageExceptionTest`, `DbContentStorageTest`, `GroupFolderContentStorageTest`, `MigrateStorageToGroupFolderTest` -- [x] Task 6: Mark `openspec/specs/groupfolder-storage-backend/spec.md` **withdrawn**, recording what was removed, what was deliberately kept, and why. This also retires the spec's 16 `@e2e exclude` markers, whose stated reasons cited `tests/Unit/Service/DashboardContentStorage/DbContentStorageTest.php` — a test file this change deletes, which would have left sixteen exemptions resting on a class that no longer exists -- [x] Task 7: Correct the phantom `- [x]` on Task 5 of the archived change at `openspec/changes/archive/2026-06-14-groupfolder-storage-backend/tasks.md`, because the project record asserted a wiring that did not exist -- [ ] Task 8: **Follow-up, tracked on launchpad#87 — NOT in this change.** Decide whether setup-wizard step 2 (`launchpad.content_storage`, `AdminSettingKey::CONTENT_STORAGE`, `SetupWizardService::{getContentStorage,setContentStorage,hasGroupfolderApp}`, `AdminController::setWizardStorage` and its route) also retires. It writes a setting nothing now reads. Note that `tools/spec-annotations-allowlist.txt` carries entries for those three `SetupWizardService` methods and for `AdminController::setWizardStorage` - -## Verification - -- `gate-57` (orphaned-write-capability) over `lib/Service/*.php` must report **0** findings, down from 1. The checker takes a **file list**, not a directory — `check_orphaned_write_capability.py .` prints nothing and exits 0 regardless of the tree's state -- PHPUnit must stay green, with the five removed classes gone rather than skipped -- No `@spec` anchor may dangle: `check_spec_anchors.py <log> <files...>` must report 0 findings over `lib/` diff --git a/openspec/changes/scheduled-exports/design.md b/openspec/changes/scheduled-exports/design.md deleted file mode 100644 index d8134602f..000000000 --- a/openspec/changes/scheduled-exports/design.md +++ /dev/null @@ -1,193 +0,0 @@ -# Design — Scheduled Exports - -## Context - -LaunchPad dashboards and widgets are designed for live, in-browser consumption: users open the app and read the numbers. Three common organisational patterns require pushing data out instead: - -1. **Recurring management reports**: A weekly bezwaarschriften PDF sent to a wethouder's inbox every Monday at 09:00. -2. **Regulated data exchange**: A monthly CBS or VNG return in CSV/XLSX format that must land on an SFTP drop by a specific deadline or incur penalties. -3. **Cross-system snapshots**: A nightly PNG of a service-desk KPI dashboard posted to Teams so the standup starts from a shared picture. - -Today, organisations work around this limitation by exporting dashboards manually, scheduling cron jobs that hit the LaunchPad API with brittle scraping logic, or maintaining separate reporting tools that duplicate data logic. Scheduled Exports closes this gap by making LaunchPad the source of truth for all three patterns. - -## Goals / Non-Goals - -**Goals:** - -- Decouple rendering from delivery: one render produces multiple formats (PDF, PNG, CSV, XLSX) and can be fanned out to multiple channels (email, Files, webhook, SFTP) without re-rendering. -- Support per-recipient filtering: the same export can render once per gemeente and email each gemeente its filtered copy, reducing manual dashboard maintenance. -- Provide first-class failure handling: retries with exponential backoff, dead-letter visibility, and admin notifications. -- Capture compliance-grade audit trails: every run writes artefact hashes, delivery outcomes, and provider acknowledgement IDs so compliance officers can prove what was sent and when. -- Keep the UX simple for the common case: a friendly recurrence editor (every Monday 09:00) that hides cron complexity for the 95% case while preserving raw cron for power users. - -**Non-Goals:** - -- eIDAS or NTA 9087 digital signing (v2 integration with docudesk; v1 ships PDF/A-2b as the archival format). -- AI-powered scheduling suggestions based on dashboard access patterns. -- Custom render post-processing (cropping, watermarking, redaction) — that is the domain of docudesk. -- Scheduled export of arbitrary external data sources (only LaunchPad dashboards and widgets). - -## Decisions - -### D1: Recurrence vocabulary is cron + calendar - -**Decision**: Support four recurrence types: `cron` (raw five-field expression for power users), `weekly` (BYDAY RFC 5545 semantics), `monthly` (BYMONTHDAY with last-day fallback), and `daily`. - -**Rationale**: The common cases (every Monday 09:00, first of the month, every weekday at 17:00) are more discoverable through a friendly editor than asking users to write `0 9 * * 1` or `0 8 1 * *`. The cron escape hatch serves the 5% case (e.g., `0 2 * * 1-5` = 02:00 weekdays, for a report that skips weekends to save processing). Quartz scheduler convention (preserve wall-clock time across DST, fire once per missed fire window) aligns with what operators already expect. - -**Alternatives considered:** - -- RFC 5545 RRULE only (too verbose for non-calendar users; cron is the lingua franca for operators). -- UI-only picker with no power-user escape hatch (insufficient for edge cases). - -### D2: Rendering decouples from delivery - -**Decision**: A `render_target` produces one output format. A single fire produces one rendered artefact per unique filter context, which is then delivered to all recipients with matching filter contexts. - -**Rationale**: Organisations deliver the same data via multiple channels (weekly PDF to email + a CSV to SFTP for archival). Rendering once and re-using across channels saves CPU and guarantees bit-identical delivery. Per-recipient filtering (município-level exports for a multi-municipality org) avoids maintaining 23 nearly-identical scheduled exports by hand. - -**Alternatives considered:** - -- One render per recipient-channel pair (simpler state machine but wasteful CPU and storage duplication). -- Render targets and recipients fully independent (higher flexibility but makes the UX overwhelming). - -### D3: Render artefacts live in Files, audit rows in OpenRegister - -**Decision**: Binary artefacts (PDF, PNG files) are written to the user's Nextcloud Files area under `Apps/LaunchPad/Exports/{exportId}/`. Audit rows (`scheduled_export_run` objects) live in OpenRegister alongside the export config, capturing artefact paths and delivery outcomes. - -**Rationale**: Files integration gives users familiar drag-and-drop, sharing, and search without LaunchPad reinventing file management. OpenRegister integration gives compliance officers read-only access to audit trails through the standard permission model. Decoupling the binary storage from the audit metadata means retention policies can keep audit records forever while purging binary files after e.g. 14 days (per compliance requirements). - -**Alternatives considered:** - -- Store binaries in OpenRegister as base64-encoded blobs (violates ADR-001 pattern of not embedding large media in register objects). -- Store audit rows in a custom database table (no standard permission model or soft-delete lifecycle). - -### D4: Delivery channels are atomic per channel, retries are per recipient - -**Decision**: A delivery attempt targets one recipient on one channel. Retries are scoped per recipient. If recipient A's webhook fails and recipient B's email succeeds, both outcomes are captured in the same run-row with distinct retry counts. - -**Rationale**: Different channels have different failure semantics (MTA temporary unavailability vs. credential expiry vs. network timeout). Atomic per-channel allows fine-grained retry policies and error classification without coupling unrelated channels. Per-recipient retry state lets a transient email failure not block the webhook retry. - -**Alternatives considered:** - -- One monolithic retry for the entire run (too coarse; one flaky recipient blocks retries for all others). -- No retries, dead-letter failures only (ignores transient MTA/network issues common in production). - -### D5: Credentials are vaulted in OpenConnector when available - -**Decision**: SFTP and webhook `channelConfig` fields can reference an `openconnectorSourceId` instead of storing credentials locally. When set, dispatch routes through OpenConnector's vault and call-log. - -**Rationale**: Centralised credential management (OpenConnector vault) eliminates duplicate credential storage and gives organisations a single place to rotate SFTP/API keys. OpenConnector's call-log provides audit trails of what was sent to external systems. Local credential fallback supports small orgs that do not run OpenConnector. - -**Alternatives considered:** - -- OpenConnector only, no local fallback (breaks offline/disconnected deployments). -- Local credential storage only (duplicate vaults, credential sprawl). - -### D6: Janitor enforcement via OpenRegister retention-rule hooks - -**Decision**: Deletion of old artefacts and audit rows is implemented via OpenRegister's `retention-rule` hooks rather than a custom purge loop in the ScheduledExportJanitor. - -**Rationale**: OpenRegister already manages object lifecycle (soft-delete, permanent deletion) and has tested edge cases (concurrent reads, long-running purges, cascading deletes). Reusing those hooks via the register's hook API keeps the janitor simple (register-aware, not custom-SQL). - -**Alternatives considered:** - -- Custom SQL in the janitor (reimplements OpenRegister purge logic, harder to test and maintain). - -### D7: Manual "Run now" and "Preview" are first-class actions - -**Decision**: The export editor includes a "Run now" button (immediate fire, writes run-row with `triggeredBy=manual`) and a "Preview" action (render without dispatch, returns output in response). - -**Rationale**: Dashboard authors need to validate a new export works before relying on it for a scheduled report. Preview lets them see the rendered PDF without flooding a recipient's inbox. Manual run is useful for testing retry logic or re-running a missed schedule after a system outage. - -**Alternatives considered:** - -- Preview only (users must wait until the next scheduled fire to validate; hurts confidence). -- Run now only, no preview (no way to validate output without sending it to recipients). - -## Seed Data - -The `lib/Settings/launchpad_register.json` import includes three example scheduled exports: - -1. **Weekly Bezwaren Report (PDF)** - - Subject: dashboard named "Bezwaarschriften Overzicht" - - Recurrence: every Monday at 09:00 Europe/Amsterdam - - Render target: PDF, A4, portrait, with header/footer - - Recipient: email to `bezwaren@gemeente.nl` - - Retention: keep artefacts 30 days (default), audit 365 days - - Filter context: none (renders all data) - -2. **Monthly Compliance Return (XLSX)** - - Subject: dashboard "CBS Retourmeldingen" - - Recurrence: monthly on day 1 at 08:00 - - Render targets: XLSX with one sheet per widget - - Recipients: (a) SFTP to `sftp.cbs.nl:/dropbox/gemeente-0355/` with host-key verification, (b) email to `compliance-officer@gemeente.nl` - - Retention: keep both artefacts and audit indefinitely (compliance record) - - Filter context: `gemeenteCode: 'GM0355'` for SFTP, none for email - -3. **Daily Service Desk Snapshot (PNG)** - - Subject: widget "Service Desk KPIs" - - Recurrence: every weekday at 08:00 - - Render target: PNG, 1920×1080, 96 DPI - - Recipient: webhook to `https://teams.microsoft.com/hooks/...` (signed with HMAC-SHA256) - - Retention: keep artefacts 7 days (daily snapshots pile up fast), audit 30 days - - Filter context: none - -All seed objects use realistic Dutch values (gemeente codes per BAG, valid timestamps in Europe/Amsterdam timezone, real email domains and SFTP hosts). - -## Reuse Analysis - -This change leverages existing OpenRegister abstractions per ADR-001: - -- **Object CRUD & lifecycle**: Use `ObjectService::saveObject()`, `findAll()`, `deleteObject()` — no custom Entity/Mapper. -- **Relations**: Cross-references between `scheduled_export` → `dashboard`/`widget` via register relations. -- **Permissions & RBAC**: Export ownership and sharing use the standard dashboard/widget permission model (OpenRegister enforces object-level read/write). -- **Retention policies**: `OpenRegister\Hook\RetentionRuleInterface` drives automated purging of old run-rows and artefact cleanup. -- **Audit logging**: Run-rows are the audit records (captured via standard register audit hooks, not custom logging). -- **Frontend CRUD UI**: Reuse `CnFormDialog` for export editor, `CnDataTable` for run-history list, `CnDetailPage` for audit-row details. -- **i18n**: Register schema descriptions and UI strings via existing company-wide i18n setup (ADR-025). -- **OpenConnector integration**: Optional credential vaulting via `openconnectorSourceId` references in recipient config. - -No duplication detected. All core abstractions (CRUD, permissions, retention, audit) are already provided by OpenRegister / @conduction/nextcloud-vue. This change adds domain-specific orchestration (recurrence resolution, render pipeline, delivery dispatch) and opt-in integrations (OpenConnector vault, headless rendering). - -## Risks / Trade-offs - -**Risk: Headless Chromium resource consumption** -- **Severity**: Medium. Rendering a large dashboard to PDF in headless Chromium consumes CPU and memory. -- **Mitigation**: Render jobs are queued and fire one at a time (no parallel rendering on the same instance). Organisations running many large exports can scale Chromium pool horizontally via container orchestration (ADR-013 Container Pool). Rendering happens off the critical path (background job, not user request). - -**Risk: DST ambiguity in recurrence** -- **Severity**: Low. Spring-forward (missing hour) or fall-back (repeated hour) can cause a scheduled fire to land at an unexpected wall-clock time if not carefully handled. -- **Mitigation**: Quartz scheduler semantics (preserve wall-clock time, fire once per missed slot) are explicitly documented. The recurrence resolver is covered by scenario tests for DST transitions (spring 2026 and fall 2026 in test matrix). - -**Risk: Retention enforcement race conditions** -- **Severity**: Low. If a run-row is being read while the janitor deletes it, the read may fail. -- **Mitigation**: Use OpenRegister's soft-delete semantics (mark as deleted, then hard-delete after a grace period). Reads filter out soft-deleted rows automatically. Hard-delete happens in a separate janitor pass. - -**Risk: Retry storms if webhook receiver is temporarily unavailable** -- **Severity**: Low. Exponential backoff with jitter mitigates; max backoff caps at 1 hour, max attempts at 5. -- **Mitigation**: Dead-letter queue surfaces permanently-failed recipients in the UI. Admins can adjust `maxAttempts` and `maxBackoffSeconds` per recipient if the default is too aggressive for their environment. - -**Trade-off: Per-recipient filtering adds complexity to the render pipeline** -- Rendering N recipients with distinct filter contexts requires N separate render passes. This is justified by the use case (multi-gemeente orgs), but it is slower than a single global render. Organisations with a few recipients see negligible impact. - -**Trade-off: Compliance audit trails are permanent but artefact retention is configurable** -- An organisation might purge a monthly PDF after 30 days but keep the sha256 audit record for 365 days. This is intentional (archivist cares about proof, not bytes) but requires discipline in retention-schedule documentation. - -## Migration Plan - -1. **Schemas + register import** — add `lib/Settings/launchpad_register.json` with four schemas (scheduled_export, render_target, recipient, scheduled_export_run) and seed data. Repair step calls `ConfigurationService::importFromApp()`. -2. **Backend services** — implement `ScheduledExportService`, `RecurrenceResolver`, `RenderPipeline`, `DeliveryDispatcher`, `AuditLog` with unit test coverage per ADR-008. -3. **Background jobs** — register `ScheduledExportRunner` (every minute) and `ScheduledExportJanitor` (every hour) via Nextcloud job abstraction. -4. **Controller + routes** — add `ScheduledExportController` with 11 endpoints (CRUD, run, preview, audit, retry); register in `appinfo/routes.php`. -5. **Frontend** — build export-editor modal (list/create/edit/delete), run-history panel, preview modal. Integrate into dashboard menu. -6. **Hydra gates** — ensure all PHP has SPDX docblocks, no orphaned auth checks, no inline modals. -7. **i18n** — add `nl_NL` + `en_US` translations for all UI strings and schema descriptions. -8. **Integration tests** — Playwright covering the full workflow: create export → validate recurrence → manual run → preview → check run-row. -9. **Rollback** — pure code change, no data migrations. Removing the PR disables the feature cleanly; existing exports are soft-deleted if the export register is removed. - -## Open Questions - -1. **Should the render pipeline support concurrent rendering across multiple Chromium instances?** Current decision: no (single queue). Revisit if rendering becomes a bottleneck (scale via container orchestration, not in-app concurrency). -2. **Should preview output be streamed (for large PDFs) or buffered?** Current decision: buffer in memory (simpler API, fine for typical dashboard sizes). If preview frequently times out, switch to streaming. -3. **Should failed deliveries notify the export owner or an admin group?** Current decision: both (owner is responsible for their export, admins troubleshoot systemic issues). Configurable per recipient. diff --git a/openspec/changes/scheduled-exports/tasks.md b/openspec/changes/scheduled-exports/tasks.md deleted file mode 100644 index c3f331ef9..000000000 --- a/openspec/changes/scheduled-exports/tasks.md +++ /dev/null @@ -1,90 +0,0 @@ -# Tasks — scheduled-exports - -## Tasks - -### Data Model & Services - -- [ ] Task 1: Add OpenRegister schemas to `lib/Settings/launchpad_register.json`: `scheduled_export`, `render_target`, `recipient`, `scheduled_export_run` with all fields per context-brief.md (including recurrence discriminator as embedded object) -- [ ] Task 2: Implement `RecurrenceResolver` service class computing `nextRunAt` from recurrence object and `runTimezone`, respecting DST (spring-forward / fall-back) and leap-day edge cases; covers all four types (`weekly`, `monthly`, `daily`, `cron`) -- [ ] Task 3: Implement `ScheduledExportService` with methods: `findVisible($userId)`, `findOne($id, $userId)`, `save($export)`, `delete($id, $userId)`, `setEnabled($id, $enabled)` — delegate object CRUD to OpenRegister `ObjectService`, not custom Entity/Mapper -- [ ] Task 4: Implement `RenderPipeline` service class with method `render($export, $filterContext): RenderResult[]` handling PDF (headless Chromium, A4 portrait/landscape), PNG (viewport size, DPI), CSV (tabular data extraction), XLSX (per-widget sheets); returns array of `{format, sizeBytes, sha256, storagePath}` -- [ ] Task 5: Implement `DeliveryDispatcher` service class with method `dispatch($export, $artefacts, $recipients): DeliveryResult[]` handling email (Nextcloud mailer), nextcloudFiles (Files API), webhook (signed POST), SFTP (phpseclib) — each delivery attempt writes immediately to audit row -- [ ] Task 6: Implement `RetryHandler` service class with methods `scheduleRetry($deliveryId, $retryPolicy)` and `retryDelivery($deliveryId): DeliveryResult` — exponential backoff with jitter, cap at `maxBackoffSeconds`, mark permanent-failed after `maxAttempts` -- [ ] Task 7: Implement `AuditLog` service class persisting `scheduled_export_run` rows via OpenRegister `ObjectService` with `renderArtefacts` array (format, sha256, path) and `deliveries` array (recipientId, channel, attemptCount, status, error) - -### Background Jobs - -- [ ] Task 8: Implement `OCA\LaunchPad\BackgroundJob\ScheduledExportRunner` registered at one-minute granularity; fetch all enabled exports with `nextRunAt <= now()`, check for overlapping previous run (skip if running), invoke render → dispatch → audit, recompute `nextRunAt`, handle disabled creator with admin notification -- [ ] Task 9: Implement `OCA\LaunchPad\BackgroundJob\ScheduledExportJanitor` registered at one-hour granularity; delete `renderArtefacts` files after `retention.keepArtefactsForDays` (null = forever), null out `storagePath` in run-rows, delete entire run-rows after `retention.keepAuditForDays` via OpenRegister retention hooks - -### Controller & Routes - -- [ ] Task 10: Implement `ScheduledExportController` with endpoints: - - `GET /api/exports` → list visible exports with pagination/sorting (delegate to ObjectService) - - `POST /api/exports` → create export with required fields; validate recurrence; returns 201 with new UUID - - `GET /api/exports/{id}` → read single export; 404 if not visible - - `PATCH /api/exports/{id}` → update export fields; recompute `nextRunAt` if recurrence changed - - `DELETE /api/exports/{id}` → soft-delete (OpenRegister standard soft-delete semantics) - - `POST /api/exports/{id}/run` → manual run (immediate execution, trigger by user, write `triggeredBy=manual` + `triggeredByUser`) - - `POST /api/exports/{id}/preview` → render for chosen recipient without dispatch, stream response for binary formats - - `GET /api/exports/{id}/runs` → list run-rows for audit history with pagination - - `GET /api/exports/{id}/runs/{runId}` → read single run-row details including all deliveries - - `POST /api/exports/{id}/runs/{runId}/retry` → retry all failed deliveries in that run - - All endpoints require `#[NoAdminRequired]` where applicable; permission checks via OpenRegister (export must be visible to user) -- [ ] Task 11: Register all 11 routes in `appinfo/routes.php` - -### Frontend - -- [ ] Task 12: Create export-editor modal component (`src/modals/ScheduledExportModal.vue`) with form sections: basic (name, description, subject picker), recurrence (weekly/monthly/daily/cron picker with friendly UI), render targets (add/remove targets, format options per format), recipients (add/remove, channel picker, filter context editor, channel config forms) -- [ ] Task 13: Create export-list page with `CnDataTable` showing: name, subject, next-run timestamp, last-run status (icon), actions (edit, delete, "Run now", "View runs"). Integrate into dashboard menu as "Scheduled Exports" action. -- [ ] Task 14: Create run-history panel showing list of past fires with columns: triggered-at, status (success/partial/failed), recipient count, delivery outcomes summary. Clicking a run opens detail modal. -- [ ] Task 15: Create run-detail modal (`src/modals/RunDetailModal.vue`) showing: export name, fire timestamp, status, list of deliveries (per-recipient channel, status, attempt count, error if failed), list of render artefacts (format, size, download link), "Retry" button if any delivery failed -- [ ] Task 16: Create preview modal (`src/modals/PreviewModal.vue`) accepting render format choice (pdf/png/csv/xlsx) and recipient selection, displaying render output (PDF/PNG embedded, CSV/XLSX as download link) -- [ ] Task 17: Frontend store action `useExportsStore.runExportNow(exportId)` POSTs to `/api/exports/{id}/run` and polls run-status until completion (show progress toast) -- [ ] Task 18: Frontend store action `useExportsStore.previewExport(exportId, recipientId, format)` POSTs to `/api/exports/{id}/preview` and returns streaming response -- [ ] Task 19: Add "Scheduled Exports" menu item to dashboard toolbar (alongside Share, Bulk, Comments); clicking opens export-list modal - -### Testing - -- [ ] Task 20: PHPUnit — `RecurrenceResolver` table-driven tests for all four recurrence types, DST edge cases (spring 2026, fall 2026), leap-day (Feb 28→29→1), cron parsing -- [ ] Task 21: PHPUnit — `ScheduledExportService` covering CRUD, permission filtering (only exports visible to user), soft-delete, enable/disable toggling -- [ ] Task 22: PHPUnit — `RenderPipeline` mocking Chromium renderer, testing all four formats (PDF page size/orientation, PNG viewport DPI, CSV headers/rows, XLSX per-widget sheets) -- [ ] Task 23: PHPUnit — `DeliveryDispatcher` mocking email/Files/webhook/SFTP channels, verifying signed webhook headers, redacted SFTP password responses, per-recipient filter context applied -- [ ] Task 24: PHPUnit — `RetryHandler` exponential backoff timing, max-attempts rollover to permanent-failed, jitter application -- [ ] Task 25: PHPUnit — `ScheduledExportRunner` background job behavior: fires enabled exports with `nextRunAt <= now()`, skips overlapping previous run, marks disabled creator as failed with admin notification, recomputes `nextRunAt` post-fire -- [ ] Task 26: PHPUnit — `ScheduledExportJanitor` retention enforcement: deletes artefacts after `keepArtefactsForDays`, deletes run-rows after `keepAuditForDays`, handles null (forever) retention -- [ ] Task 27: Playwright — full workflow: create export with weekly recurrence → save → manual "Run now" → check run-row appears in history → preview render (PDF) → edit export → toggle enabled off → verify next fire is skipped -- [ ] Task 28: Playwright — filter context workflow: create export with two recipients (gemeente A, gemeente B) with distinct `filterContext` → manual run → verify two renders in audit row → verify each recipient gets its filtered version -- [ ] Task 29: Playwright — failure + retry: create webhook recipient with bad URL → manual run → verify delivery marked failed → click "Retry" → verify retry scheduled → advance time → verify successful delivery on retry -- [ ] Task 30: Playwright — retention enforcement: create export with 14-day artefact retention → fire now → advance time 15 days → check janitor purges artefacts but retains audit metadata - -### Quality Gates & Documentation - -- [ ] Task 31: Composer checks: `composer check:strict`, `composer check:lint` — no errors -- [ ] Task 32: ESLint + Stylelint on all `.vue` and `.js` files — green -- [ ] Task 33: SPDX docblock on every PHP class/method per ADR-005 (`@license EUPL-1.2`, `@copyright ...`) -- [ ] Task 34: Hydra gates green: `hydra-gate-spdx`, `hydra-gate-modal-isolation` (export modals live in `src/modals/`, not inlined), `hydra-gate-route-auth` (all routes have permission checks) -- [ ] Task 35: OpenAPI schema generation for new 11 routes (Newman/Postman regen) -- [ ] Task 36: i18n translations `nl_NL` + `en_US` for: UI strings (menu items, button labels, form placeholders), validation messages, admin notifications, schema descriptions -- [ ] Task 37: Update `CHANGELOG.md` with feature summary: "Scheduled Exports v1 — recurring exports with multi-format rendering and multi-channel delivery (email, Files, webhook, SFTP)" -- [ ] Task 38: Document in `design.md` why stale recurrence preferences are skipped per-request rather than via background job (DST/leap-day edge cases are transient; recompute on every read for consistency) - -## Verification - -`openspec validate` exits clean. All 10 REQ-SCH requirements green in test matrix. Run-rows audit trail captures correct sha256 and delivery outcomes. Retention enforcement purges old artefacts and audit rows per policy. - -## Tests (company-wide ADR-008) - -PHPUnit per Tasks 20–26. Playwright per Tasks 27–30. All tests must pass CI before merge. - -## Documentation (company-wide ADR-009) - -Changelog entry (Task 37). Public docs (out of scope for OpenSpec; docudesk team owns user-facing guides). - -## i18n (company-wide ADR-025) - -`nl_NL` and `en_US` translations per Task 36. - -## Seed Data (company-wide ADR-001) - -Three realistic example exports per design.md Seed Data section, loaded via `lib/Settings/launchpad_register.json` on install. diff --git a/openspec/changes/search-ai-prefix-shortcuts/design.md b/openspec/changes/search-ai-prefix-shortcuts/design.md deleted file mode 100644 index fdc114c03..000000000 --- a/openspec/changes/search-ai-prefix-shortcuts/design.md +++ /dev/null @@ -1,38 +0,0 @@ -# Design: search-ai-prefix-shortcuts - -Read at development `d767c282`. - -## Context - -- The search flow: `src/composables/useTileSearch.js` ranks tiles (`rankItems()`, line 150), checks templates (`isValidFallbackTemplate()`, line 183) and resolves the no-match fallback (`resolveFallbackAction()`, line 212). `src/composables/useTileSearchHost.js:173` `performFallback()` opens a web search in a new tab or hands off to unified search. -- Two surfaces use it: the search widget (`src/components/Widgets/Renderers/SearchWidget.vue`) and the Workspace quick search (`src/components/RuntimeShellSearch.vue`), both specified in `openspec/specs/tile-quick-search/spec.md` (REQ-QSEARCH-001 to 008). -- The admin fallback template is validated by `AdminSettingsService::isValidQuicksearchFallbackUrlTemplate()` (`lib/Service/AdminSettingsService.php`): https only and a `{query}` placeholder. -- Admin settings are typed keys in `lib/Db/AdminSettingKey.php`; the Workspace page gets settings through `lib/Service/InitialStateBuilder.php`. - -## Decisions - -### D1: Shortcuts are one admin list - -`search_shortcuts` holds up to 30 entries `{prefix, name, urlTemplate}`. A prefix is `!` followed by 1 to 10 letters or digits, unique case-insensitively. Each `urlTemplate` passes the existing https-with-`{query}` check. The list reaches the page through the initial state; no extra request per keystroke. - -### D2: Prefix wins, then tiles, then the fallback - -`useTileSearch.js` gets `parsePrefix(query, shortcuts)` returning `{shortcut, rest}` when the first word is a known prefix. When it matches, the box shows "Search TOPdesk for printer" as the only result and Enter opens the template with the URL-encoded rest in a new tab (`noopener`). Without a match the existing tile ranking and REQ-QSEARCH-004 fallback run unchanged. - -### D3: Discoverable without memorising - -Typing `!` alone or `?` shows the list of shortcuts with their names. Screen readers get the result through the existing live region of the quick search. - -## Declarative-vs-imperative decision - -Client-side parsing over an admin setting; no schema register involved. - -## Permissions - -Only administrators edit the list. Every user can use it. The query leaves the browser only toward the chosen site, never through the LaunchPad server. - -## Test plan - -- PHPUnit: prefix format, uniqueness, template check, the 30-entry limit. -- Vitest: `parsePrefix` cases (known, unknown, prefix only, uppercase), result rendering, Enter opening the right address, `?` listing. -- Playwright: with `!t` set to a test site, typing `!t printer` and Enter opens that site with `printer`. diff --git a/openspec/changes/search-ai-prefix-shortcuts/tasks.md b/openspec/changes/search-ai-prefix-shortcuts/tasks.md deleted file mode 100644 index 89b996644..000000000 --- a/openspec/changes/search-ai-prefix-shortcuts/tasks.md +++ /dev/null @@ -1,9 +0,0 @@ -# Tasks: search-ai-prefix-shortcuts - -- [ ] 1. Add `search_shortcuts` to `lib/Db/AdminSettingKey.php` and validate it in `AdminSettingsService` (prefix pattern, uniqueness, template check, limit 30). Verify: PHPUnit. -- [ ] 2. Provide the list through `lib/Service/InitialStateBuilder.php`. Verify: initial-state contract test. -- [ ] 3. Add `parsePrefix()` to `src/composables/useTileSearch.js` and route a match ahead of ranking. Verify: Vitest. -- [ ] 4. Render the "Search <name> for <rest>" result and the `?` list in `SearchWidget.vue` and `RuntimeShellSearch.vue`, opening through `useTileSearchHost.js`. Verify: Vitest and an axe check on the list. -- [ ] 5. Add the admin section to edit shortcuts. Verify: Vitest. -- [ ] 6. Playwright: `!t printer` opens the configured site. -- [ ] 7. Add `nl` and `en` strings, fold the delta into `openspec/specs/tile-quick-search/spec.md` on archive, and set d-search-prefix to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/sharing-public-start-page/tasks.md b/openspec/changes/sharing-public-start-page/tasks.md deleted file mode 100644 index dbd1ddfd2..000000000 --- a/openspec/changes/sharing-public-start-page/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: sharing-public-start-page - -- [ ] 1. Add `public_start_enabled` and `public_start_share_token` with the D1 validation, and the admin section on `SharingTab.vue` listing eligible shares and the switched-off reason. Verify: PHPUnit and Vitest. -- [ ] 2. Add the `BeforeLoginTemplateRenderedEvent` listener with the D2 conditions and the redirect script. Verify: PHPUnit per condition. -- [ ] 3. Add `PageController::start()` on `/start` with `#[PublicPage]`, `#[NoCSRFRequired]` and the public-share rate limit. Verify: PHPUnit and route-reachability. -- [ ] 4. Show the sign-in bar in the public view when rendered as the start page. Verify: Vitest and an axe check. -- [ ] 5. Playwright: land on the start page, sign in, deep link still logs in. -- [ ] 6. Add `nl` and `en` strings, fold the delta into `openspec/specs/dashboard-public-share/spec.md` on archive, and set d-public-start to `built` in the parity matrix with evidence lines. diff --git a/openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md b/openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md deleted file mode 100644 index e8da25dc2..000000000 --- a/openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md +++ /dev/null @@ -1,299 +0,0 @@ ---- -capability: dashboard-store -status: draft ---- - -# Dashboard store: new capability from change `store-plane-dashboard-sharing` - -## Context - -A registry is another OpenRegister instance publishing dashboard templates as -objects of a `dashboard-template` schema. LaunchPad reaches it through -OpenRegister's AppHost store plane, which owns discovery: the SSRF guard, the -redirect refusal, the Bearer-only token transport, the outcome vocabulary and card -normalisation. LaunchPad owns install, because a dashboard lives in LaunchPad's -own tables and no engine install op can write one. - -Browser coverage lives in `tests/e2e/dashboard-store.spec.ts`: the store page's -not-configured state, the admin form round-trip, the token redaction, and the -admin gate probed with a non-admin account. Scenarios with no browser-visible -effect (degraded discovery with OpenRegister absent, outcome pass-through, -ZIP materialisation, additive install, temp-file cleanup) are PHPUnit-covered -and carry their own reason below. - -A SUCCESSFUL remote install has no e2e test, deliberately. It needs a second -OpenRegister instance publishing a `dashboard-template` object, and CI -provisions one instance. Faking the registry inside the suite would test the -fake. `StoreServiceTest` covers the install path against the engine's real -signatures. - -## NEW Requirements - -### Requirement: REQ-STORE-001 The store routes MUST exist wherever the store page is declared - -LaunchPad's manifest declares a `type: "store"` page, which renders `CnStorePage`, -which calls `GET /apps/launchpad/api/store/items` on mount and -`POST /apps/launchpad/api/store/items/{slug}/install` on an install click. -`appinfo/routes.php` SHALL declare both, and the `{slug}` route SHALL constrain -the slug to `[a-z0-9][a-z0-9-]*[a-z0-9]` so a malformed slug fails at the router -rather than reaching the registry URL. - -#### Scenario: The declared page can reach its endpoint - -- **GIVEN** `src/manifest.json` declares a page of type `store` -- **WHEN** the route table is read -- **THEN** it MUST contain `store#search` at `/api/store/items` -- **AND** it MUST contain `store#install` at `/api/store/items/{slug}/install` - -@e2e exclude route-table shape: asserted by reading appinfo/routes.php in tests/Unit/Support/StoreWiringTest.php; the browser consequence is the next scenario - -#### Scenario: An unconfigured store shows the not-configured state - -- **GIVEN** no `registry_url` is configured -- **WHEN** an administrator opens the Store page -- **THEN** `GET /api/store/items` MUST answer 200 with outcome `not_configured` -- **AND** the page MUST show its not-configured note -- **AND** it MUST NOT show the unreachable note or an empty result grid - ---- - -### Requirement: REQ-STORE-002 An absent OpenRegister MUST degrade, never fatal - -`GenericStoreService` is resolved optionally, exactly as LaunchPad already -resolves the AppHost observability collaborators. When OpenRegister is disabled or -absent the collaborator is null. `search()` MUST then return outcome -`not_configured` with an empty card list, and `install()` MUST refuse, and neither -MUST touch an `OCA\OpenRegister\…` symbol. - -An engine that is present but unconfigured behaves the same way, because -`GenericStoreService::isConfigured()` reports false for an empty `registry_url` -and makes no network call. - -#### Scenario: No OpenRegister yields not_configured - -- **GIVEN** the store service holds a null discovery client -- **WHEN** `search()` is called -- **THEN** the outcome MUST be `not_configured` and the card list MUST be empty - -@e2e exclude requires an instance WITHOUT OpenRegister, and CI installs it; asserted in tests/Unit/Service/StoreServiceTest.php - -#### Scenario: No OpenRegister refuses an install rather than half-running one - -- **GIVEN** the store service holds a null discovery client -- **WHEN** `install()` is called for any slug -- **THEN** it MUST report failure and MUST NOT call `ImportService` - -@e2e exclude requires an instance WITHOUT OpenRegister, and CI installs it; asserted in tests/Unit/Service/StoreServiceTest.php - ---- - -### Requirement: REQ-STORE-003 The engine's outcome MUST reach the caller unchanged - -The plane distinguishes `store_unreachable` from `store_invalid_response` so a -misconfigured registry does not read as an offline one. LaunchPad SHALL pass the -outcome through verbatim and MUST NOT collapse the two, and MUST NOT substitute -its own. Upstream error detail MUST NOT reach the caller; the engine already keeps -it server-side. - -#### Scenario: An invalid response is not reported as unreachable - -- **GIVEN** the engine returns outcome `store_invalid_response` -- **WHEN** the service returns -- **THEN** the outcome MUST be `store_invalid_response` - -@e2e exclude needs a registry that answers malformed JSON, and CI has no registry; asserted in tests/Unit/Service/StoreServiceTest.php - ---- - -### Requirement: REQ-STORE-004 Installing MUST require an administrator - -An install writes dashboards into the instance from a third-party server. The -install endpoint SHALL carry `#[AuthorizedAdminSetting(LaunchPadAdmin::class)]`, -the posture LaunchPad already uses for its other administrative endpoints. - -Search SHALL carry `#[NoAdminRequired]`, because browsing a registry addresses no -object of this instance. It forwards a query to an external registry and returns -normalised cards, so there is no local identifier to guess and no IDOR to create. - -#### Scenario: Every store route declares a posture - -- **GIVEN** the store controller -- **WHEN** its public methods are read -- **THEN** `search` MUST carry `#[NoAdminRequired]` -- **AND** `install` MUST carry `#[AuthorizedAdminSetting]` - -@e2e exclude attribute presence: asserted by reflection in tests/Unit/Controller/StoreControllerTest.php; the two scenarios below prove the attributes hold at runtime - -#### Scenario: A non-admin is refused the registry config - -- **GIVEN** a signed-in account that is not an administrator, holding a valid request token -- **WHEN** it reads or writes `/api/store/config` -- **THEN** both requests MUST answer 403 -- **AND** the stored registry MUST be unchanged afterwards - -#### Scenario: A non-admin is refused an install - -- **GIVEN** the same account -- **WHEN** it posts to `/api/store/items/{slug}/install` -- **THEN** the request MUST answer 403 - ---- - -### Requirement: REQ-STORE-005 An install MUST reuse ImportService, not reimplement it - -The resolved payload SHALL be materialised into a `launchpad-export-v1` ZIP in a -temporary directory and handed to `ImportService::import()`. LaunchPad MUST NOT -gain a second code path that turns a dashboard payload into rows. - -The materialised archive MUST carry a `manifest.json` with `schemaVersion` equal -to the importer's supported version and a `scope`, and one -`dashboards/{uuid}.json` entry per dashboard, because that is what -`validateZipStructure()` requires and what `ExportService` writes. - -The temporary archive MUST be removed whether the import succeeds or throws. - -#### Scenario: The payload reaches the existing importer - -- **GIVEN** a resolved item carrying one dashboard payload -- **WHEN** it is installed -- **THEN** `ImportService::import()` MUST be called exactly once -- **AND** the path it receives MUST be an existing ZIP containing `manifest.json` - -@e2e exclude needs a second OpenRegister publishing a template, and CI has one instance; asserted in tests/Unit/Service/StoreServiceTest.php - -#### Scenario: An install with no registry is refused with a reason - -- **GIVEN** no `registry_url` is configured -- **WHEN** an administrator posts an install for any slug -- **THEN** the request MUST answer 400 with `success` false and a message -- **AND** it MUST NOT answer 500 - -#### Scenario: A payload with no dashboards is refused before any import - -- **GIVEN** a resolved item whose dashboards list is empty or absent -- **WHEN** it is installed -- **THEN** the install MUST fail and `ImportService::import()` MUST NOT be called - -@e2e exclude needs a registry serving a malformed item, and CI has no registry; asserted in tests/Unit/Service/StoreServiceTest.php - -#### Scenario: The temporary archive does not survive a failing import - -- **GIVEN** `ImportService::import()` throws -- **WHEN** the install returns -- **THEN** no temporary archive from that install MUST remain on disk - -@e2e exclude a temp-directory effect with no browser surface; asserted in tests/Unit/Service/StoreServiceTest.php - ---- - -### Requirement: REQ-STORE-006 A store install MUST create dashboards, never replace them - -The install SHALL call `ImportService::import()` with `preserveUuids` false. A -template published by a foreign instance carries that instance's UUIDs, and one of -them can collide with a live local dashboard. Re-mapping makes the install -additive. - -This mirrors the plane's own rule that an install creates rather than replaces, -reached by a different route: the identity that would do the damage is the -dashboard UUID rather than an object `uuid`. - -#### Scenario: A colliding UUID still creates - -- **GIVEN** a resolved item whose dashboard UUID matches a local dashboard -- **WHEN** it is installed -- **THEN** `import()` MUST be called with `preserveUuids` false - -@e2e exclude needs a second OpenRegister publishing a template, and CI has one instance; asserted in tests/Unit/Service/StoreServiceTest.php - ---- - -### Requirement: REQ-STORE-007 The registry token MUST NOT be readable back - -`registry_url`, `registry_token` and `registry_register` live in `IAppConfig` -under `launchpad`, because that is where `GenericStoreService` reads them. -LaunchPad's own admin settings write to a different store, so the change adds an -admin-gated endpoint for these three keys. - -The read endpoint SHALL return the URL and the register, and for the token SHALL -return only whether one is set. The token value MUST NOT appear in any response. - -#### Scenario: Reading the config never returns the token - -- **GIVEN** `registry_token` holds a value -- **WHEN** the config is read -- **THEN** the response MUST report that a token is set -- **AND** the response MUST NOT contain the token value - -#### Scenario: An empty token submission clears rather than blanks around - -- **GIVEN** a stored token -- **WHEN** the config is written with an empty token -- **THEN** the stored token MUST be cleared - -@e2e exclude the clear-versus-keep distinction is a request-payload property the browser cannot see; asserted in tests/Unit/Service/StoreServiceTest.php and src/components/admin/__tests__/DashboardRegistrySettings.spec.js - ---- - -### Requirement: REQ-STORE-008 The manifest MUST NOT declare a store block - -`src/manifest.json` MUST NOT carry a `store` key. That block exists to configure -OpenRegister's `GenericStoreController`, which LaunchPad does not use, so a block -here would declare a schema and card fields that nothing reads while -`StoreService` declares the ones that are used. - -A non-empty `types` list is the specific harm, because it selects the engine's -federated configuration path. The block on `development` declared -`openregister.configset` and `openregister.flows`, which trade registers, schemas -and flows. Had the routes existed, the store page would have offered -configuration sets to somebody looking for a dashboard. - -#### Scenario: No store block is declared - -- **GIVEN** `src/manifest.json` -- **WHEN** it is decoded -- **THEN** it MUST NOT contain a `store` key - -@e2e exclude a source-file property; asserted in tests/Unit/Support/StoreWiringTest.php - -#### Scenario: The store page still declares itself - -- **GIVEN** the same manifest -- **WHEN** its pages are read -- **THEN** exactly one page MUST carry `type` of `store` - - -@e2e exclude a source-file property; asserted in tests/Unit/Support/StoreWiringTest.php - ---- - -### Requirement: REQ-STORE-009 An administrator MUST be able to connect a registry without a shell - -The three registry keys live in `IAppConfig`, which LaunchPad's own admin -settings do not write. So Beheer ▸ Sharing SHALL carry a form for -`registry_url`, `registry_register` and the token, backed by -`/api/store/config`. - -The token field SHALL be write-only. It MUST start empty on every load, and -the page MUST say whether a token is set without showing it. Saving with an -empty token field MUST leave the stored token alone; removing it is a -separate action. - -#### Scenario: An administrator saves a registry and reads it back - -- **GIVEN** an administrator on Beheer ▸ Sharing -- **WHEN** they enter a registry URL, a register and a token, and save -- **THEN** after a reload the URL and register fields MUST show what they entered -- **AND** the page MUST say a token is set - -#### Scenario: The token is never shown back - -- **GIVEN** a stored token -- **WHEN** the form loads -- **THEN** the token field MUST be empty -- **AND** neither the page nor the config response MUST contain the token - -#### Scenario: The saved registry is the one the store reads - -- **GIVEN** an administrator saved a registry URL whose host does not resolve -- **WHEN** they open the Store page -- **THEN** the page MUST show the unreachable note rather than the not-configured one diff --git a/openspec/changes/store-update-and-publish/proposal.md b/openspec/changes/store-update-and-publish/proposal.md new file mode 100644 index 000000000..ad7f4b401 --- /dev/null +++ b/openspec/changes/store-update-and-publish/proposal.md @@ -0,0 +1,34 @@ +--- +kind: spec +depends_on: [store-page-board-sync] +--- + +# Proposal: store-update-and-publish + +## Why + +Board LpStore draws two marketplace actions that store-page-board-sync left open: "Bijwerken" on a card whose register +version is newer than the installed one, and "Dashboard publiceren" in the page header. Both were product questions. +Decided on 23 November 2026 (product decisions delegated by Ruben): + +1. **Bijwerken** updates the installed dashboard in place and keeps what people added themselves, the way an + installed shipped template is updated (admin-templates REQ-TMPL-020) and re-synced (REQ-RESYNC-003). +2. **Dashboard publiceren** is for administrators only, to the one connected register. + +## What changes + +- `dashboard-store`: Update brings an installed dashboard to the register's newer version in place (REQ-STORE-012). + REQ-STORE-006 still holds for Install: a first install creates, it never replaces. +- `dashboard-store`: an administrator publishes a dashboard to the connected register (REQ-STORE-013). + +## Dependencies + +- REQ-STORE-012 needs the install record of REQ-STORE-011 (change store-page-board-sync). +- REQ-STORE-013 needs OpenRegister's store plane to accept a publication: the open OpenRegister change + `store-over-federated-config`. Its tasks are marked blocked until that lands; the builder SHALL NOT build a + LaunchPad-side publish route of its own in the meantime. + +## Impact + +- `StoreController` and the store service (update and publish), the import path (update in place), the store page + (Update and Publish dashboard actions), translations. diff --git a/openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md b/openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md new file mode 100644 index 000000000..bbfc1e3a1 --- /dev/null +++ b/openspec/changes/store-update-and-publish/specs/dashboard-store/spec.md @@ -0,0 +1,63 @@ +# Delta: dashboard-store + +## ADDED Requirements + +### Requirement: REQ-STORE-012 Update brings an installed dashboard to the newer version in place + +When the register offers a newer version of an item that was installed on this instance (REQ-STORE-011), an +administrator SHALL be able to choose Update ("Bijwerken") on its card +(`POST /apps/launchpad/api/store/items/{slug}/update`). The update SHALL keep each dashboard the install created: its +id, UUID, name, owner, shares and permission level stay. It SHALL replace the dashboard's widgets that came from the +install with the new version's, pairing a widget present in both versions so it keeps its row, as admin-templates +REQ-TMPL-020 does for a shipped template. A widget a person added to the dashboard themselves SHALL stay. A copy made +from the dashboard SHALL be brought along with the merge strategy of REQ-RESYNC-003. Afterwards the install record +SHALL hold the new version and the card SHALL show Installed. The update SHALL write a dashboard version noted "Updated +from the marketplace" (dashboard-versioning). Only administrators SHALL update; anyone else gets HTTP 403. Install +(REQ-STORE-006) is unchanged: a first install still creates and never replaces. + +#### Scenario: The sociaal domein dashboard is updated + +- **GIVEN** "Managementinfo sociaal domein" 1.0.0 is installed, and Hanneke added her own widget "Notities" to it +- **AND** the register offers 1.1.0, which adds the widget "Wachtlijst Wmo" +- **WHEN** the administrator chooses Update on its card +- **THEN** the same dashboard now holds "Wachtlijst Wmo" and still holds "Notities", with its shares unchanged +- **AND** the card shows Installed with version 1.1.0 + +#### Scenario: A member cannot update + +- **GIVEN** Pieter is not an administrator +- **WHEN** he sends the update request +- **THEN** the response is HTTP 403 and nothing changes + +### Requirement: REQ-STORE-013 An administrator publishes a dashboard to the connected register + +The marketplace page SHALL offer "Publish dashboard" ("Dashboard publiceren") to administrators only, and only when a +register is connected (REQ-STORE-009) and OpenRegister's store plane accepts publications. Publishing SHALL let the +administrator pick one dashboard, fill in its title, description, category, the kind of organisation it is for and a +version, and SHALL send the dashboard's export (dashboard-export-import, the same format an install imports) through +OpenRegister's store plane to the connected register; LaunchPad SHALL NOT talk to the register directly. An export +SHALL contain no personal data: no owners, shares, personal layers, read receipts or reactions. Publishing a dashboard +that was published before SHALL require a higher version. The register's answer SHALL reach the administrator +unchanged (REQ-STORE-003). The item SHALL appear on the page as "Eigen publicatie". Without a connected register, or +while the store plane cannot accept publications, the action SHALL NOT show. + +This requirement depends on OpenRegister's change `store-over-federated-config`; it is not built before that lands. + +#### Scenario: The administrator publishes Raads- en collegewerk + +- **GIVEN** a register is connected and the store plane accepts publications +- **WHEN** the administrator chooses Publish dashboard, picks "Raads- en collegewerk", sets version 0.9.0 and confirms +- **THEN** the register holds the item with version 0.9.0, and its card on the marketplace reads "Eigen publicatie" +- **AND** the published export names no owner or share + +#### Scenario: A member sees no publish action + +- **GIVEN** Pieter is not an administrator +- **WHEN** he opens the marketplace +- **THEN** there is no Publish dashboard action, and a publish request he sends is refused with HTTP 403 + +#### Scenario: The same version twice + +- **GIVEN** "Raads- en collegewerk" 0.9.0 was published +- **WHEN** the administrator publishes it again as 0.9.0 +- **THEN** the publication is refused with a message asking for a higher version diff --git a/openspec/changes/store-update-and-publish/tasks.md b/openspec/changes/store-update-and-publish/tasks.md new file mode 100644 index 000000000..9bf701998 --- /dev/null +++ b/openspec/changes/store-update-and-publish/tasks.md @@ -0,0 +1,9 @@ +# Tasks: store-update-and-publish + +- [x] `POST /api/store/items/{slug}/update` (admin only): fetch the newer version through the store plane, update the installed dashboards in place with the REQ-TMPL-020 pairing, keep person-added widgets, re-sync copies with merge, store the new version in the install record, write the version note "Updated from the marketplace" +- [x] Store page: Update action on cards with status Update, for administrators (CnStorePage already draws it for administrators and posts it to `/install`; the install endpoint updates an installed item in place, so no second install happens) +- [x] Unit tests: in-place update keeps id, shares and own widgets; paired widgets keep their rows; 403 for non-admins; install still creates +- [x] Playwright: with the registry stub offering a newer version, Update changes the installed dashboard and the card shows Installed (`tests/e2e/store-update.spec.ts` 1/1 green on a sandbox Nextcloud 34.0.6 + MariaDB, 25 Nov 2026) +- [ ] BLOCKED on OpenRegister `store-over-federated-config`: publish through the store plane, admin only, export without personal data, higher version required, register answer passed through +- [ ] BLOCKED on the same: "Publish dashboard" action and form on the store page, shown only with a connected register that accepts publications +- [ ] BLOCKED on the same: unit tests for publish (export content, version rule, 403) and a Playwright run against the registry stub diff --git a/openspec/changes/tile-form-board-sync/proposal.md b/openspec/changes/tile-form-board-sync/proposal.md new file mode 100644 index 000000000..b40ffe072 --- /dev/null +++ b/openspec/changes/tile-form-board-sync/proposal.md @@ -0,0 +1,16 @@ +# Proposal: tile-form-board-sync + +## Why + +Board LpTegelBewerken draws "Tegel bewerken" as one form of 640 px: name and group, the tile type as four choice cards (Webadres, App met eenmalige aanmelding, Oud Windows-programma, Programma op deze computer), web address and internal address side by side, where it opens as three choice cards (Zelfde tabblad, Nieuw tabblad, In Launchpad naast de tegels), the icon with an upload, the colour as eight theme swatches, the sort order of the group, the availability check as a switch with its last result, and Tegel verwijderen at the bottom left. + +On development `src/modals/TileEditor.vue` holds most of these fields but as a long list with a full icon browser and free hex colours. The colour swatches are specced in `icon-only-app-tiles` (REQ-ICT-004). Group, the choice cards, the sort order of a group and the shown result of the last check have no requirement. + +## What changes + +- `tiles`: the tile form layout as the board draws it (REQ-TILE-040), the group of a tile and the group's sort order in the form (REQ-TILE-041), the last availability result in the form (REQ-TILE-042). +- The colour swatches stay in `icon-only-app-tiles`. + +## Impact + +- `src/modals/TileEditor.vue`, the tile catalogue group field, translations. diff --git a/openspec/changes/tile-form-board-sync/specs/tiles/spec.md b/openspec/changes/tile-form-board-sync/specs/tiles/spec.md new file mode 100644 index 000000000..21d22b686 --- /dev/null +++ b/openspec/changes/tile-form-board-sync/specs/tiles/spec.md @@ -0,0 +1,30 @@ +# Delta: tiles + +## ADDED Requirements + +### Requirement: The tile form as LpTegelBewerken draws it (REQ-TILE-040) + +Editing a tile SHALL open one form, 640 px wide, titled "Edit tile: <name>" under "<group> · <dashboard>". It SHALL hold, in this order: Name and Group side by side; Tile type as four choice cards (Web address, App with single sign-on, Legacy Windows program, Program on this computer), each with one line of explanation; Web address and Internal address (optional) side by side; Open in as three choice cards (Same tab, New tab, In Launchpad, next to the tiles); Icon with "Upload another icon"; Colour; Sort order in this group; Check availability. Delete tile SHALL sit at the bottom left, Cancel and Save at the bottom right. + +#### Scenario: Edit the case system tile + +- **WHEN** Pieter opens Edit tile on Case system +- **THEN** the form shows the fields in the order above, with App with single sign-on and New tab chosen + +### Requirement: A tile's group and the group's order (REQ-TILE-041) + +The form SHALL show the tile's group and let the editor change it, and SHALL show the sort order of that group: Last used first, Alphabetical, Random or As placed. + +#### Scenario: Sort a group by use + +- **WHEN** the editor sets Sort order in this group to Last used first and saves +- **THEN** the tiles of Work apps are ordered by last use for every reader + +### Requirement: The last availability check in the form (REQ-TILE-042) + +When Check availability is on, the form SHALL show under the switch the result of the last check with its time, such as "Reachable at the last check, today 10:40". + +#### Scenario: A reachable tile + +- **GIVEN** the last health ping of Case system succeeded at 10:40 +- **THEN** the form reads "Reachable at the last check, today 10:40" diff --git a/openspec/changes/tile-form-board-sync/tasks.md b/openspec/changes/tile-form-board-sync/tasks.md new file mode 100644 index 000000000..423430bff --- /dev/null +++ b/openspec/changes/tile-form-board-sync/tasks.md @@ -0,0 +1,10 @@ +# Tasks: tile-form-board-sync + +- [x] Tile form layout: name and group, type and open-in as choice cards, addresses side by side, icon with upload, swatches (from icon-only-app-tiles), sort order, availability switch (the colour keeps its two pickers until icon-only-app-tiles lands its swatches) +- [x] Group field and the group's sort order (last used first, alphabetical, random, as placed): a tile inside a group opens the tile form from its own tile menu, with the group's name and order; the save writes the tile into the group's `content.placements` and the order onto the container's `content.sortBy` in one update (src/utils/groupTiles.js, ContainerChild, ContainerWidget, Views, TileEditor `inGroup`). Decision: a tile in a group has no placement of its own on the server and renders through the shared tile renderer, so its form offers only a web address (no launch types, internal address, Open in or availability check); settings of that kind it carries are kept, not dropped; a bookmark link child becomes a tile node when saved +- [ ] Moving a tile into a group keeps its launch, health and network settings (the child is a full tile node, 25 Nov decision), and a repair step turns stored link children `{type: link, content: {label, url, actionType}}` into tile nodes +- [x] Last availability result under the switch (reachable or not, with the time) +- [x] Delete tile at the bottom left, Cancel and Save at the right +- [x] Translations in every shipped locale +- [x] Unit tests: choice cards set the stored kind and target, sort order is saved on the group, last result text (the save carries `groupSortBy`; writing it onto the container goes with task 2) +- [ ] Playwright: edit the Case system tile and change where it opens (spec written: tests/e2e/tiles-form-board-sync.spec.ts, runs in nightly) Live run 25 Nov 2026 (sandbox Nextcloud 34.0.6 + MariaDB): the shared helper counted a container's own grid items as dashboard items, and the tile menu was read before it opened (both fixed in the spec). Still red: (1) with App with single sign-on chosen the form shows Sign-on template and App id full width and Internal address alone, where REQ-TILE-040 puts Web address and Internal address side by side; (2) the group-order scenario needs task 4 (a tile inside a group has no form of its own); (3) the availability scenario skips without a reachable fixture host. diff --git a/openspec/changes/widget-calculated-fields/design.md b/openspec/changes/widget-calculated-fields/design.md deleted file mode 100644 index ac931c76b..000000000 --- a/openspec/changes/widget-calculated-fields/design.md +++ /dev/null @@ -1,319 +0,0 @@ -# Design — Widget Calculated Fields - -## Context - -Today's widget infrastructure displays values directly from a source (register query, OpenConnector endpoint, aggregation). When users need derived values — ratios, composites across widgets, conditional formatting — they reach for spreadsheets or custom code. Calculated fields bridge this gap by evaluating expressions client-side as filters change, and optionally server-side for persistence. - -The core design choice is **dual evaluation**: client-side for instant feedback and no persisting, server-side for queryability and consistency with external consumers. Both evaluators share a single AST and test suite so they cannot diverge. - -## Goals / Non-Goals - -**Goals:** - -- Enable spreadsheet-like formulas on widgets without custom code or database changes. -- Provide instant feedback (client-side evaluation) as users change filters and dashboards. -- Make calculated fields queryable via OpenRegister by materialising server-mode fields. -- Fail fast at save time with clear parse and type errors — never show silent wrong numbers. -- Keep the evaluators deterministic and auditable — strict typing, no coercion, no permissive Excel-like silent NaN. - -**Non-Goals:** - -- Iterative recalculation (Excel's opt-in mode). We reject cycles explicitly. -- Per-instance formula extensions. Function allowlist is configurable but shipped. -- Undo/version history for expressions. Out of scope; can layer on later if needed. -- Spreadsheet-like multi-cell recalc (e.g., fill-down). Calculated fields are per-widget singleton values. -- Visual formula editor or cell-selection picker. Out of scope; future enhancement. - -## Decisions - -### D1: Dual evaluation — client by default, server on opt-in - -**Decision**: Every calculated field has an `evaluationMode: 'client' | 'server' | 'both'`. Client mode evaluates in the browser and does not persist. Server mode creates a `computed-fields` entry in the underlying OpenRegister schema and materialises the value. Both mode does both. - -**Alternatives considered:** - -- Evaluate everywhere (always server). Rejected — causes latency on filter changes and requires backend round-trip for every keystroke. -- Evaluate nowhere (client-only, never server). Rejected — doesn't satisfy use cases like alerting, export, and cross-system queries. -- Single mode per field, chosen at design time. Rejected — limits flexibility; some fields start client-only, then get promoted to server for wider use. - -**Rationale**: Users iterate client-side (instant), promote to server when ready to share. Mirrors Looker (dimension vs measure) and dbt (view vs materialised). - -### D2: AST-based parser with compile-time validation - -**Decision**: Parse and type-check at save time. Store the AST (`compiledExpression`) alongside the source text. Reject any expression that fails to parse or type-check. - -**Alternatives considered:** - -- Parse at evaluation time. Rejected — would require parsing on every filter change (perf cost) and defer errors to runtime. -- Use a runtime interpreter (eval-like). Rejected — security risk and enables silent coercion (Excel-style NaN). - -**Rationale**: Save-time validation is strict and predictable. The AST is the source of truth for evaluation; the source text is a convenience. - -### D3: Shared AST and test suite for TypeScript ↔ PHP evaluators - -**Decision**: The AST node types (`Literal`, `FieldRef`, `Binary`, `Unary`, `Call`, `If`) are defined in TypeScript and documented as JSON. The PHP evaluator deserialises the same JSON and evaluates it. Both implementations pass the same test suite (parameterised by AST + input + expected output). - -**Alternatives considered:** - -- Re-parse on the server (PHP has its own parser). Rejected — parser bugs in one language could slip through; we want one source of truth. -- Express the expression as a domain-specific byte code. Rejected — more complex than JSON, no benefit. - -**Rationale**: Shared AST + test suite is the strongest guarantee that evaluators don't drift. Contributors can add test cases and both implementations must pass. - -### D4: Strict typing, no coercion - -**Decision**: The type system is minimal (`number`, `string`, `boolean`, `date`, `duration`, `null`) and strict: `number + string` is a parse-time error, `abs("hello")` is a type error, `null + 1` evaluates to `null` (null propagation). - -**Alternatives considered:** - -- Excel-like coercion (string "123" coerces to number). Rejected — silent coercion is the #1 source of spreadsheet bugs. -- TypeScript-like union types. Rejected — too complex for a dashboard-formula language. - -**Rationale**: Strict types catch mistakes at save time, when the user is still in the formula editor and can see the error immediately. - -### D5: Cycle detection via topological sort - -**Decision**: On save, build a dependency graph of all calculated fields and cross-widget references. Run a topological sort. If it fails (cycle detected), reject the widget save with a clear error naming the cycle. - -**Alternatives considered:** - -- Iterative recalculation (Excel's opt-in mode). Rejected — semantics are ambiguous (max iterations? Convergence criteria?). Topological sort is deterministic. -- Detect cycles only on cross-widget refs, allow self-referential formulas. Rejected — self-reference adds very little value and complicates the evaluator. - -**Rationale**: Topological sort is a proven pattern in Excel, Google Sheets, and dbt. It is deterministic and catches errors at save time. - -### D6: Format options applied at render time, not evaluation time - -**Decision**: Evaluated values are stored in native types (`number`, `date`, `string`). Format options (currency, locale, number format, date pattern) are applied only when rendering the value in the UI. - -**Alternatives considered:** - -- Format at evaluation time (store formatted strings). Rejected — breaks alerting (alerts need numeric values, not "€1.234,50"). -- Store both native and formatted versions. Rejected — unnecessary duplication. - -**Rationale**: Keeps the underlying value suitable for export, alerting, and queries. Formatting is a purely UI concern. - -### D7: Allowlist-based function set, no dynamic functions - -**Decision**: The allowlist of built-in functions (math, aggregate, date, string, etc.) is defined in the parser and is per-instance configurable. Calling an unlisted function is a parse-time error. Users cannot register custom functions. - -**Alternatives considered:** - -- Scriptable custom functions (UDFs). Rejected — security risk, complex deployment, not needed for v1. -- Allow any identifier as a function call. Rejected — enables typos and makes migration (if we ever add a function) a breaking change. - -**Rationale**: Explicit allowlist is auditable and secure. The allowlist is per-instance configurable so operators can dial it down for determinism. - -## Risks / Trade-offs - -- **Risk:** Cross-widget references require both widgets to share a register. If not, field is downgraded to client-only and user gets a warning. → **Mitigation:** Document the limitation; most dashboards share a single register anyway. -- **Risk:** Client-side evaluation can go stale if the source widget's data is stale. → **Mitigation:** We follow the dashboard's existing refresh semantics — calculated fields re-evaluate whenever any source widget or filter changes. -- **Risk:** Server-side materialisation can fail (e.g., division by zero). → **Mitigation:** Error is logged to OpenRegister's computed-field error log; materialised value is null. Dashboard shows an inline error indicator. -- **Trade-off:** The function allowlist is conservative (no `eval`, no file I/O). This is intentional for security and determinism, but can be a friction point if users need e.g., regex. We accept this and version the allowlist in future changes. - -## Migration Plan - -1. **Parser + TypeScript evaluator land first** — add parser, type-checker, evaluator, and Vitest coverage. No integration yet; exported as a utility module. -2. **PHP evaluator** — deserialise and evaluate the same AST; cross-language test suite. -3. **Widget schema** — extend with `calculatedFields` array. -4. **Integration** — wire parser/validator into `WidgetController::update`, store AST, call OpenRegister `computed-fields` on save. -5. **Frontend evaluator** — integrates with `useDashboardsStore`, re-evaluates on filter/widget changes, renders results and errors. -6. **Rollback**: Schema change adds a nullable field; reverting the PR leaves the field NULL on all rows — no data loss. - -## Seed Data - -### Widget with calculated fields - -```json -{ - "id": "widget-abc123", - "title": "Revenue Analysis", - "type": "table", - "sourceId": "register-sales", - "calculatedFields": [ - { - "id": "calc-001", - "name": "profit_margin", - "label": "Profit Margin (%)", - "description": "Revenue minus cost, expressed as percentage of revenue", - "expression": "(revenue - cost) / revenue * 100", - "compiledExpression": { - "type": "binary", - "op": "*", - "left": { - "type": "binary", - "op": "/", - "left": { - "type": "binary", - "op": "-", - "left": {"type": "fieldRef", "source": "self", "path": "revenue"}, - "right": {"type": "fieldRef", "source": "self", "path": "cost"} - }, - "right": {"type": "fieldRef", "source": "self", "path": "revenue"} - }, - "right": {"type": "literal", "valueType": "number", "value": 100} - }, - "returnType": "number", - "evaluationMode": "both", - "serverComputedFieldId": "cf-profit-margin-001", - "formatOptions": { - "style": "decimal", - "minimumFractionDigits": 2, - "maximumFractionDigits": 2, - "locale": "nl-NL" - }, - "createdAt": "2026-05-22T10:30:00Z", - "updatedAt": "2026-05-22T10:30:00Z" - }, - { - "id": "calc-002", - "name": "net_revenue", - "label": "Net Revenue (EUR)", - "expression": "revenue - refunds", - "compiledExpression": { - "type": "binary", - "op": "-", - "left": {"type": "fieldRef", "source": "self", "path": "revenue"}, - "right": {"type": "fieldRef", "source": "self", "path": "refunds"} - }, - "returnType": "number", - "evaluationMode": "both", - "serverComputedFieldId": "cf-net-revenue-002", - "formatOptions": { - "style": "currency", - "currency": "EUR", - "locale": "nl-NL" - }, - "createdAt": "2026-05-22T10:31:00Z", - "updatedAt": "2026-05-22T10:31:00Z" - }, - { - "id": "calc-003", - "name": "resolution_days", - "label": "Avg. Resolution Time (days)", - "expression": "dateDiff(closedDate, openedDate, 'days')", - "compiledExpression": { - "type": "call", - "name": "dateDiff", - "args": [ - {"type": "fieldRef", "source": "self", "path": "closedDate"}, - {"type": "fieldRef", "source": "self", "path": "openedDate"}, - {"type": "literal", "valueType": "string", "value": "days"} - ] - }, - "returnType": "duration", - "evaluationMode": "client", - "formatOptions": { - "pattern": "d 'dagen'" - }, - "createdAt": "2026-05-22T10:32:00Z", - "updatedAt": "2026-05-22T10:32:00Z" - }, - { - "id": "calc-004", - "name": "status_label", - "label": "Status Label", - "expression": "if(revenue > 100000, 'High Value', if(revenue > 10000, 'Medium Value', 'Low Value'))", - "compiledExpression": { - "type": "if", - "cond": { - "type": "binary", - "op": ">", - "left": {"type": "fieldRef", "source": "self", "path": "revenue"}, - "right": {"type": "literal", "valueType": "number", "value": 100000} - }, - "then": {"type": "literal", "valueType": "string", "value": "High Value"}, - "else": { - "type": "if", - "cond": { - "type": "binary", - "op": ">", - "left": {"type": "fieldRef", "source": "self", "path": "revenue"}, - "right": {"type": "literal", "valueType": "number", "value": 10000} - }, - "then": {"type": "literal", "valueType": "string", "value": "Medium Value"}, - "else": {"type": "literal", "valueType": "string", "value": "Low Value"} - } - }, - "returnType": "string", - "evaluationMode": "client", - "createdAt": "2026-05-22T10:33:00Z", - "updatedAt": "2026-05-22T10:33:00Z" - }, - { - "id": "calc-005", - "name": "comparison_to_target", - "label": "Actual vs Target (%)", - "description": "Revenue as percentage of sales target from widget-target", - "expression": "widget:widget-target.target_revenue / revenue * 100", - "compiledExpression": { - "type": "binary", - "op": "*", - "left": { - "type": "binary", - "op": "/", - "left": { - "type": "fieldRef", - "source": "widget:widget-target", - "path": "target_revenue" - }, - "right": {"type": "fieldRef", "source": "self", "path": "revenue"} - }, - "right": {"type": "literal", "valueType": "number", "value": 100} - }, - "returnType": "number", - "evaluationMode": "client", - "formatOptions": { - "style": "decimal", - "minimumFractionDigits": 1, - "maximumFractionDigits": 1, - "locale": "nl-NL" - }, - "createdAt": "2026-05-22T10:34:00Z", - "updatedAt": "2026-05-22T10:34:00Z" - } - ] -} -``` - -## Example Evaluations - -For the widget above with source data row: `{revenue: 150000, cost: 90000, refunds: 5000, openedDate: '2026-04-01T00:00:00Z', closedDate: '2026-04-21T00:00:00Z'}`: - -- `profit_margin`: `(150000 - 90000) / 150000 * 100 = 40.00` -- `net_revenue`: `150000 - 5000 = 145000.00` (formatted: €145.000,00) -- `resolution_days`: `21` (formatted: 21 dagen) -- `status_label`: "High Value" -- `comparison_to_target`: requires data from widget-target; if target is 120000, then `120000 / 150000 * 100 = 80.0` - -## Error Cases - -### Parse error - -User saves expression `(revenue - refunds` (missing closing paren): -- API response: 400 Bad Request -- Body: `{"error": "parse_error", "message": "Unexpected token at position 21", "column": 21, "expression": "(revenue - refunds"}` - -### Type error - -User saves expression `revenue + "100"` where revenue is number and `"100"` is string: -- API response: 400 Bad Request -- Body: `{"error": "type_error", "message": "Cannot add number + string", "operands": ["number", "string"]}` - -### Cycle detection - -Widget A has `calc1 = widget:B.x` and Widget B has `calc1 = widget:A.y`: -- API response: 400 Bad Request -- Body: `{"error": "cycle_detected", "widgets": ["widget-A", "widget-B"], "message": "Circular dependency detected between widgets"}` - -### Cross-register mismatch - -Widget A (register: sales) tries to reference Widget B (register: crm) in a server-mode calculated field: -- API response: 200 OK (save succeeds) -- Body: `{"warning": "downgraded_evaluation_mode", "field": "calc1", "reason": "Cross-register reference; evaluationMode downgraded from 'server' to 'client'"}` - -## Open Questions - -- Should calculated fields display in the widget's schema export (OpenAPI / Postman)? Current decision: yes, but marked as derived/read-only at export time. -- Can calculated fields be used in widget filtering (as filter targets)? Current decision: no (v1 — filter.field must reference real data). Future: revisit for v2 if demand is high. -- Should there be a formula function to query sibling calculated fields on the same widget? Current decision: no (use `CalculatedRef` only); forces you to inline formulas if you want to chain them. Future: revisit if complexity justifies it. diff --git a/openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md b/openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md deleted file mode 100644 index 4abdb6766..000000000 --- a/openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md +++ /dev/null @@ -1,251 +0,0 @@ ---- -capability: calculated-fields -delta: false -status: draft ---- - -# Calculated Fields - -A calculated field is a named expression attached to a widget that produces a value derived from other fields in the same widget, fields in other widgets on the same dashboard, constants, and built-in functions. - -## Requirement: REQ-CALC-001 Formula parser produces deterministic AST - -The system SHALL parse a calculated-field expression into a canonical AST at save time and SHALL refuse to persist any widget whose calculated-field expressions fail to parse. - -### Scenario: Valid expression parsed to AST - -- GIVEN a valid expression `(revenue - refunds) / revenue * 100` -- WHEN the widget is saved -- THEN the parser SHALL produce a `Binary` AST with operator `*` and SHALL store it in `compiledExpression` -- AND the AST SHALL be deep-equal to any other parse of the same expression - -### Scenario: Parse error on mismatched parentheses - -- GIVEN an expression with mismatched parentheses `(revenue - refunds` -- WHEN the widget is saved -- THEN the API SHALL respond 400 with a parse error that includes the column position (column 21) -- AND SHALL NOT persist the widget - -### Scenario: Whitespace normalization in AST - -- GIVEN two expressions that differ only by whitespace: `(a+b)` and `( a + b )` -- WHEN both are parsed -- THEN their `compiledExpression` ASTs SHALL be deep-equal - -## Requirement: REQ-CALC-002 Type checking at save time - -The system SHALL infer the type of every sub-expression at parse time and SHALL reject expressions whose operator/function arguments do not match the declared signature. - -### Scenario: Type mismatch on binary operator - -- GIVEN an expression `revenue + customerName` where `revenue:number` and `customerName:string` -- WHEN the widget is saved -- THEN the API SHALL respond 400 with a type error naming both operands -- AND SHALL NOT persist the widget - -### Scenario: Function signature validation - -- GIVEN an expression `round(revenue, "two")` where `round` expects (number, integer) -- WHEN the widget is saved -- THEN the API SHALL respond 400 with a function-signature error -- AND SHALL NOT persist the widget - -### Scenario: Type inference through coalesce - -- GIVEN an expression `coalesce(null, revenue, 0)` where `revenue:number` -- WHEN the widget is saved -- THEN the inferred `returnType` SHALL be `number` -- AND the widget SHALL persist successfully - -## Requirement: REQ-CALC-003 Client-side evaluator reactive to filter changes - -The client-side evaluator SHALL recompute every `client` and `both` mode calculated field whenever any source field, source widget, or filter changes, and SHALL never round-trip to the server for an evaluation. - -### Scenario: Recompute on filter change - -- GIVEN a widget with calculated field `profit = revenue - cost` -- AND the widget displays `revenue = 100000, cost = 60000, profit = 40000` -- WHEN the user changes a dashboard filter that affects `revenue` and `cost` to new values `110000, 70000` -- THEN `profit` SHALL be recomputed inside the browser to `40000` and the new value SHALL appear without an HTTP request -- AND the UI SHALL update within one animation frame - -### Scenario: Cross-widget dependency tracking - -- GIVEN a calculated field referencing `widget:abc123` -- WHEN the source widget `abc123` refreshes its data -- THEN the dependent calculated field SHALL recompute synchronously in the same tick -- AND the updated value SHALL be rendered before the next animation frame - -### Scenario: Filter chain with multiple affected fields - -- GIVEN a dashboard with widgets W1 (revenue), W2 (cost), W3 (calculated: W1.x / W2.y) -- WHEN the user changes a filter that affects both W1 and W2 -- THEN W3's calculated field SHALL be recomputed after both W1 and W2 complete their refresh -- AND the order of recomputation shall be deterministic (topological sort order) - -## Requirement: REQ-CALC-004 Server-side evaluation via OpenRegister computed-fields - -The system SHALL, for every calculated field in `evaluationMode=server` or `both`, create a corresponding `computed-fields` entry on the underlying schema and SHALL keep the two in sync on widget save. - -### Scenario: Create server-mode computed-field entry - -- GIVEN a new calculated field with `evaluationMode=server`, `expression="revenue - cost"` -- WHEN the widget is saved -- THEN a `computed-fields` entry SHALL be created on the source schema with the same expression -- AND `serverComputedFieldId` SHALL be populated with the OpenRegister entry's ID - -### Scenario: Update server-mode entry on expression change - -- GIVEN an existing server-mode calculated field with `serverComputedFieldId="cf-123"` -- WHEN the widget is saved with a new expression `"profit * 0.9"` -- THEN the linked `computed-fields` entry SHALL be updated with the new expression in the same transaction -- AND the update SHALL be atomic (no partial state visible to other readers) - -### Scenario: Delete computed-field entry when widget is deleted - -- GIVEN a server-mode calculated field with `serverComputedFieldId="cf-123"` -- WHEN the widget is deleted -- THEN the linked `computed-fields` entry SHALL be removed from the schema -- AND no orphaned OpenRegister entries shall remain - -## Requirement: REQ-CALC-005 Identical results between evaluators - -Both evaluators SHALL produce identical results for every expression in the shared test suite, with documented and tested handling of numeric precision and null propagation. - -### Scenario: Numeric precision across evaluators - -- GIVEN any expression in the shared evaluator test suite that produces a number -- WHEN evaluated by the TypeScript and PHP evaluators on identical input -- THEN the two results SHALL be deep-equal OR equal to within 1e-9 of each other (accounting for IEEE 754 rounding) - -### Scenario: Null propagation - -- GIVEN an expression `a + null` where `a` is any non-null value -- WHEN evaluated by either the TypeScript or PHP evaluator -- THEN the result SHALL be `null` -- AND SHALL NOT throw an exception - -### Scenario: Cross-evaluator test matrix - -- GIVEN the shared test suite contains 50+ test cases covering: literals, field refs, binary ops, unary ops, function calls, conditionals, null handling, type coercion at boundaries -- WHEN the test suite runs against both evaluators -- THEN 100% of tests SHALL pass on both - -## Requirement: REQ-CALC-006 Cross-widget references with cycle detection - -The system SHALL allow a calculated field to reference fields on other widgets on the same dashboard and SHALL refuse any dependency graph that contains a cycle. - -### Scenario: Cycle detection on save - -- GIVEN widget A's calculated field references `widget:B.x` and widget B's calculated field references `widget:A.y` -- WHEN either widget is saved -- THEN the API SHALL respond 400 with a `cycleDetected` error naming both widgets -- AND SHALL NOT persist - -### Scenario: Acyclic cross-widget reference accepted - -- GIVEN widget A's calculated field references `widget:B.x` where B has no calculated fields pointing back to A -- WHEN A is saved -- THEN the save SHALL succeed -- AND A's calculated field SHALL re-evaluate whenever B refreshes (REQ-CALC-003) - -### Scenario: Self-reference rejected - -- GIVEN a calculated field named `x` with expression `widget:self.x` (self-referential) -- WHEN the widget is saved -- THEN the API SHALL respond 400 with a `cycleDetected` error -- AND SHALL NOT persist - -## Requirement: REQ-CALC-007 Cross-widget downgrade on source mismatch - -When a `server` or `both` mode calculated field references a widget whose data does not live in the same OpenRegister register/schema, the system SHALL downgrade the field to `client` mode at save time and SHALL warn the user. - -### Scenario: Downgrade on different register - -- GIVEN a calculated field with `evaluationMode=server` that references a widget backed by a different register (e.g., widget A uses register:sales, widget B uses register:crm) -- WHEN the widget is saved -- THEN the field's `evaluationMode` SHALL be persisted as `client` -- AND the API response SHALL include a warning: `{warning: 'downgraded_evaluation_mode', field: 'name', reason: 'Cross-register reference'}` - -### Scenario: Preserve server mode on same register - -- GIVEN a calculated field with `evaluationMode=server` that references a widget backed by the same register and schema -- WHEN the widget is saved -- THEN `evaluationMode` SHALL remain `server` -- AND a `computed-fields` entry SHALL be created - -## Requirement: REQ-CALC-008 Inline error display preserves dashboard usability - -When a calculated field fails to evaluate at runtime, the system SHALL render an inline error indicator on the widget without breaking other widgets on the dashboard. - -### Scenario: Division by zero in client-side evaluation - -- GIVEN a calculated field `ratio = a / b` where the user has NOT added a guard and `b` is 0 in a given row -- WHEN the widget renders -- THEN the field's cell SHALL display an error icon -- AND hovering the icon SHALL show the expression and the value of `b` -- AND other widgets on the dashboard SHALL render normally (not affected) - -### Scenario: Server-side evaluation error - -- GIVEN the same calculated field on the server-side evaluator -- WHEN the materialiser runs and encounters division by zero -- THEN the materialised value SHALL be `null` -- AND the OpenRegister computed-field error log SHALL record: `{expression, inputs, error: 'division by zero'}` - -### Scenario: Error does not block widget render - -- GIVEN a widget with 10 calculated fields, 1 of which fails to evaluate -- WHEN the widget renders -- THEN the 9 successful fields SHALL display normally -- AND the 1 failed field SHALL show an error indicator -- AND the widget SHALL be usable (filtering, exporting, etc. do not break) - -## Requirement: REQ-CALC-009 Allowlisted function set with named signatures - -The parser SHALL accept only functions on the documented allowlist and SHALL reject any call to an unknown identifier as a function with a clear error. - -### Scenario: Unknown function rejected - -- GIVEN an expression `eval("revenue * 2")` -- WHEN the widget is saved -- THEN the API SHALL respond 400 with `{error: 'unknownFunction', name: 'eval'}` -- AND SHALL NOT persist - -### Scenario: Variadic function accepted with correct args - -- GIVEN an expression `sum(revenue, cost, profit)` where `sum` accepts variadic numbers -- WHEN the widget is saved -- THEN the parser SHALL validate that `sum` is on the allowlist and accepts variadic args -- AND the widget SHALL persist successfully - -### Scenario: Allowlist is per-instance configurable - -- GIVEN a LaunchPad instance with `allowedFunctions: ['abs', 'round', 'sum']` (restricted) -- WHEN a user tries to save an expression using `now()` (not in allowlist) -- THEN the API SHALL respond 400 with `{error: 'functionNotAllowed', name: 'now'}` - -## Requirement: REQ-CALC-010 Format options applied at render time - -The system SHALL apply `formatOptions` only at render time on the client, and SHALL store and evaluate the underlying value in its native type. - -### Scenario: Currency formatting preserves numeric value - -- GIVEN a calculated field with `returnType=number`, `formatOptions={style:'currency', currency:'EUR', locale:'nl-NL'}`, evaluated value of `1234.5` -- WHEN the widget renders for a Dutch user -- THEN the displayed string SHALL be `€ 1.234,50` -- AND the underlying value passed to alerting/export SHALL remain `1234.5` (not a string) - -### Scenario: Date formatting preserves ISO instant - -- GIVEN a calculated field with `returnType=date`, `formatOptions={pattern:'dd MMM yyyy', locale:'nl-NL'}`, evaluated value of `2026-05-22T14:30:00Z` -- WHEN the widget renders -- THEN the displayed string SHALL be `22 mei 2026` -- AND the underlying value passed to filters/queries SHALL remain `2026-05-22T14:30:00Z` (ISO 8601) - -### Scenario: Format options ignored at server-side evaluation - -- GIVEN the same calculated field in server-side mode (materialised) -- WHEN the field is evaluated on the server -- THEN the materialised value SHALL be the raw number/date (no formatting) -- AND the format options SHALL be applied only by the widget renderer, not by OpenRegister diff --git a/openspec/changes/widget-calculated-fields/tasks.md b/openspec/changes/widget-calculated-fields/tasks.md deleted file mode 100644 index 7eedd2a2e..000000000 --- a/openspec/changes/widget-calculated-fields/tasks.md +++ /dev/null @@ -1,107 +0,0 @@ -# Tasks — widget-calculated-fields - -## 1. Parser and Type Checking (TypeScript) - -- [ ] Task 1: Define AST node types as TypeScript interfaces: `Literal`, `FieldRef`, `CalculatedRef`, `Binary`, `Unary`, `If`, `Call` with complete type definitions and JSON-serializable structure -- [ ] Task 2: Implement `CalculatedFieldParser.ts` with `parse(expression: string): AST` that produces deterministic canonical AST; on syntax error throw `ParseError` with column position (REQ-CALC-001) -- [ ] Task 3: Implement `TypeChecker.ts` with `inferType(ast: AST, fieldSchema): Type` that validates all operators and function calls at the AST level; on type mismatch throw `TypeError` with operand names (REQ-CALC-002) -- [ ] Task 4: Define the allowlist of built-in functions with signatures: `math` (abs, round, ceil, floor, min, max, pow, sqrt, log, sum, avg), `aggregate` (count, countIf, sumIf, avgIf), `date/time` (now, today, dateDiff, dateAdd, formatDate, parseDate), `duration` (durationBetween, durationFormat), `string` (concat, upper, lower, trim, contains, startsWith, endsWith, replace, format), `conditional` (coalesce, ifNull, case), `type coercion` (toNumber, toString, toBool, toDate) -- [ ] Task 5: Add allowlist to `config.ts` with per-instance configurability (default: all functions); parser rejects unknown functions at parse time (REQ-CALC-009) -- [ ] Task 6: Vitest coverage: 100+ test cases covering all AST node types, all operators, all built-in functions, error cases (REQ-CALC-001, REQ-CALC-002) - -## 2. Cycle Detection - -- [ ] Task 7: Implement `CycleDetector.ts` that builds a dependency graph of all calculated fields on a widget + cross-widget references; run topological sort; throw `CycleError` if cycle detected, naming the cycle (REQ-CALC-006) -- [ ] Task 8: Wire cycle detection into the parser so `parseAndValidate(widget)` calls both type-checker and cycle-detector before returning validated AST (REQ-CALC-006) -- [ ] Task 9: Vitest: cycle detection rejects self-references, mutual references, and longer cycles; accepts acyclic graphs (REQ-CALC-006) - -## 3. TypeScript Evaluator (Client-side) - -- [ ] Task 10: Implement `CalculatedFieldEvaluator.ts` that takes an AST and a row context (field values from source widget) and evaluates deterministically (REQ-CALC-003, REQ-CALC-005) -- [ ] Task 11: Handle all AST node types: literals, field refs (with `source='self'` and `source='widget:<id>'`), binary/unary ops, conditionals, function calls; return typed result or `null` on null propagation (REQ-CALC-005) -- [ ] Task 12: Error handling: catch runtime errors (divide by zero, null dereference, function error) and return `{error: message, expression, inputs}` so the widget can display an inline error (REQ-CALC-008) -- [ ] Task 13: Cross-widget field refs resolved via the dashboard store's widget data at evaluation time (REQ-CALC-003) -- [ ] Task 14: Numeric precision: all math follows IEEE 754 (JavaScript Number), test suite validates equivalence with PHP to within 1e-9 (REQ-CALC-005) - -## 4. Shared Test Suite - -- [ ] Task 15: Create `test/shared-evaluator-test-suite.json` containing 50+ test cases: each case specifies an AST, input data (field values), expected output, and error conditions; suite is language-agnostic JSON -- [ ] Task 16: Import and run the shared suite in Vitest (TypeScript evaluator) and PHPUnit (PHP evaluator); both must pass 100% of tests (REQ-CALC-005) - -## 5. Frontend Integration (Vue/Store) - -- [ ] Task 17: Add `useCalculatedFields()` composable that: (1) watches widget source data, (2) watches dashboard filters, (3) maintains a dependency graph of calculated fields, (4) re-evaluates on any change, (5) returns `{values: Map, errors: Map}` (REQ-CALC-003) -- [ ] Task 18: Integrate into `useDashboardsStore.js`: when a widget's data arrives or filters change, re-evaluate all calculated fields on that widget and dependent widgets in topological order (REQ-CALC-003) -- [ ] Task 19: Widget component renders calculated-field values in the appropriate column/cell alongside source fields; if error, display error icon with tooltip showing expression + input value (REQ-CALC-008) -- [ ] Task 20: Filtering/export/drill-down: calculated-field values are included in exports and can be used in drill-down but NOT as filter targets in v1 (out of scope) (REQ-CALC-010) - -## 6. Schema and Widget Service (PHP) - -- [ ] Task 21: Extend `WidgetEntity` schema: add nullable `calculatedFields` JSON column storing the array of field objects (id, name, label, expression, compiledExpression, returnType, evaluationMode, etc.) -- [ ] Task 22: Create migration that adds the column to existing widgets with default `[]` -- [ ] Task 23: Implement `CalculatedFieldService.php` (server-side) with: (1) `validateAndCompile(widget, expression)` calls the parser and type-checker, (2) `detectCycles(widget)` checks for cycles, (3) `evaluateExpression(ast, row): mixed` evaluates the AST for server-side use (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006) -- [ ] Task 24: Wire `WidgetController::create` and `::update` to validate all calculated fields before persisting via `CalculatedFieldService::validateAndCompile` (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006) -- [ ] Task 25: Return parse/type/cycle errors as 400 with body `{error: error_code, message: ..., ...details}` (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006) - -## 7. OpenRegister Integration (Server-side Materialisation) - -- [ ] Task 26: Implement `CalculatedFieldService::materializeForOpenRegister(widget): array` that, for every calculated field with `evaluationMode='server'` or `'both'`: (1) creates/updates a `computed-fields` entry on the schema, (2) populates `serverComputedFieldId` in the widget, (3) stores the expression in OpenRegister (REQ-CALC-004) -- [ ] Task 27: Wire materialisation into `WidgetService::save()`: after widget is persisted, call `materializeForOpenRegister()` in a transaction (REQ-CALC-004) -- [ ] Task 28: On widget delete, call `CalculatedFieldService::cleanupServerFields(widget)` to delete all orphaned `computed-fields` entries (REQ-CALC-004) -- [ ] Task 29: Implement downgrade logic (REQ-CALC-007): when a server-mode field references a widget with a different source register, downgrade to `client` mode, set `evaluationMode='client'`, and return warning in API response - -## 8. PHP Evaluator (Server-side) - -- [ ] Task 30: Implement `CalculatedFieldEvaluator.php` that deserialises the AST (JSON) and evaluates it on a row context (REQ-CALC-005) -- [ ] Task 31: Mirror the TypeScript evaluator exactly: all AST node types, all operators, all functions; numeric precision via IEEE 754 floats; null propagation (REQ-CALC-005) -- [ ] Task 32: Error handling: catch runtime errors and store them in OpenRegister's computed-field error log (not thrown to the widget caller); return `null` for the materialised value (REQ-CALC-008) -- [ ] Task 33: Run the shared test suite (Task 16) against the PHP evaluator; all tests must pass (REQ-CALC-005) - -## 9. Format Options and Rendering - -- [ ] Task 34: Implement `FormatOptions` type with: number format (style, minimumFractionDigits, maximumFractionDigits, currency, locale), date format (pattern, locale), duration format (pattern) -- [ ] Task 35: In the widget's table/chart/single-value renderers, apply format options at display time ONLY (not at evaluation time) using `Intl.NumberFormat`, `Intl.DateTimeFormat`, or custom logic for durations (REQ-CALC-010) -- [ ] Task 36: Format options do NOT affect the value passed to alerting, export, or other consumers; only the displayed string in the UI (REQ-CALC-010) - -## 10. Testing — Backend - -- [ ] Task 37: PHPUnit — `CalculatedFieldValidationTest.php`: parse errors, type errors, cycle detection, unknownFunction errors all return correct 400 envelope (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006, REQ-CALC-009) -- [ ] Task 38: PHPUnit — `CalculatedFieldEvaluatorTest.php`: shared test suite (Task 16) runs against PHP evaluator; all operators, functions, null handling, numeric precision (REQ-CALC-005) -- [ ] Task 39: PHPUnit — `CalculatedFieldServerModeTest.php`: verify `computed-fields` entries created/updated/deleted correctly; downgrade logic works (REQ-CALC-004, REQ-CALC-007) -- [ ] Task 40: PHPUnit — `CrossWidgetReferenceTest.php`: parse/evaluate cross-widget refs (`widget:id.field`); cycle detection (REQ-CALC-006) - -## 11. Testing — Frontend - -- [ ] Task 41: Vitest — `parser.test.ts`: 100+ cases covering all AST node types, operators, functions, error cases (REQ-CALC-001, REQ-CALC-002, REQ-CALC-009) -- [ ] Task 42: Vitest — `evaluator.test.ts`: shared test suite runs against TypeScript evaluator; all operators, functions, null handling, numeric precision (REQ-CALC-005) -- [ ] Task 43: Vitest — `cycleDetector.test.ts`: cycle detection rejects self-refs, mutual refs, longer cycles; accepts acyclic (REQ-CALC-006) -- [ ] Task 44: Playwright — render a widget with calculated fields; verify values appear in the table/chart; verify inline errors show on evaluation failure; verify other widgets still render (REQ-CALC-003, REQ-CALC-008) -- [ ] Task 45: Playwright — cross-widget reference: change filter on source widget, verify dependent widget's calculated field re-evaluates (REQ-CALC-003) -- [ ] Task 46: Playwright — server-mode field: materialised value is queryable via OpenRegister API; client-mode field is not (REQ-CALC-004) - -## 12. Quality and Documentation - -- [ ] Task 47: `composer check:strict` and `eslint` pass on all new files -- [ ] Task 48: OpenAPI / Postman / API docs: document the new Widget schema extension (`calculatedFields` array); document error response envelopes (REQ-CALC-001, REQ-CALC-002, REQ-CALC-006, REQ-CALC-009) -- [ ] Task 49: i18n — `nl_NL` and `en_US` translations for: error messages (parse_error, type_error, cycle_detected, unknownFunction), inline error hover text, downgrade warning -- [ ] Task 50: SPDX — all new PHP files have `@license EUPL-1.2` + `@copyright` in docblock -- [ ] Task 51: Changelog entry describing: calculated fields as a widget feature, dual evaluation (client + server), allowlisted function set, error handling + inline indicators, cross-widget refs + cycle detection, format options -- [ ] Task 52: Design.md — document the design decisions (D1–D7), rationale for dual evaluation, AST-based approach, shared test suite, format-at-render-time strategy, migration plan -- [ ] Task 53: All hydra-gates pass (route-auth, admin-idor, semantic-auth, spdx-headers, etc.) - -## Verification - -`openspec validate` exits clean. Widget with calculated field saves and displays correctly on the dashboard. Parse/type/cycle errors are caught at save time and shown to the user with clear messages. Client-side evaluator re-computes on filter change without round-trip. Server-mode field materialises to OpenRegister and is queryable. TypeScript and PHP evaluators produce identical results. - -## Tests - -- Vitest: parser, type-checker, cycle detector, evaluator (TypeScript), shared test suite -- PHPUnit: validation, evaluator (PHP), server-side integration, cross-widget refs -- Playwright: render, error display, cross-widget reactivity, filter changes - -## Documentation - -- Changelog: feature overview, dual-evaluation strategy, allowlist, error handling -- Design.md: decisions, rationale, migration plan, seed data -- i18n: error messages, user-facing strings -- OpenAPI: schema extension, error envelopes diff --git a/openspec/changes/widget-picker-board-sync/proposal.md b/openspec/changes/widget-picker-board-sync/proposal.md new file mode 100644 index 000000000..ff1c0fa57 --- /dev/null +++ b/openspec/changes/widget-picker-board-sync/proposal.md @@ -0,0 +1,16 @@ +# Proposal: widget-picker-board-sync + +## Why + +Board LpWidgetKiezen draws "Widget toevoegen", the only place where widgets are added, as a dialog of 720 px: an assistant line at the top ("Beschrijf wat u nodig hebt", a proposal with Plaats het zo), a search field, a column of kinds with counts (Alles 52, Inhoud 12, Tegels en links 17, Mensen 3, Gegevens en grafieken 8, Uit andere apps 10, Office 4), and to its right the widgets as cards in two columns: "Widgets van Launchpad", "App-tegels" (one coloured tile per app of the catalogue, plus Eigen tegel) and "Uit andere Nextcloud-apps". A kind the role may not add is a grey card that says why; an older widget type carries the label "Ouder widgettype". The dialog ends with Annuleren and Widget toevoegen. + +On development the picker is nextcloud-vue's `CnAddWidgetModal`: a search and one long list "From the app catalogue" with a plus per row. No requirement describes the kinds, the card grid, the app tile section or the disabled cards, so the stack cannot be brought to the board without a spec. + +## What changes + +- `widgets`: the picker as the board draws it (REQ-WDG-040), its kinds with counts (REQ-WDG-041), the App tiles section (REQ-WDG-042) and widgets the role may not add (REQ-WDG-043). +- The assistant line reuses `launchpad-ai-dashboard-assistant`; this change only places it at the top of the picker. + +## Impact + +- `src/modals/WidgetPickerModal.vue` (or a picker body passed to `CnAddWidgetModal`), the role feature permissions it reads, translations. diff --git a/openspec/changes/widget-picker-board-sync/specs/widgets/spec.md b/openspec/changes/widget-picker-board-sync/specs/widgets/spec.md new file mode 100644 index 000000000..1997cc6a5 --- /dev/null +++ b/openspec/changes/widget-picker-board-sync/specs/widgets/spec.md @@ -0,0 +1,41 @@ +# Delta: widgets + +## ADDED Requirements + +### Requirement: The widget picker as LpWidgetKiezen draws it (REQ-WDG-040) + +Add widget SHALL open one dialog, 720 px wide, titled with the dashboard name over "Add widget". It SHALL hold a search field, a column of kinds and, to its right, the widgets as cards in two columns, each card with an icon, a name and one line that says what the widget does. The cards SHALL be grouped under "Widgets from Launchpad", "App tiles" and "From other Nextcloud apps". The dialog SHALL end with Cancel and Add widget; a card is chosen by clicking it and placed with Add widget. + +#### Scenario: Open the picker + +- **GIVEN** Pieter edits My workspace +- **WHEN** he chooses Add widget +- **THEN** the dialog shows the search, the kinds and the card sections in that order + +### Requirement: Kinds with counts (REQ-WDG-041) + +The kind column SHALL list All, Content, Tiles and links, People, Data and charts, From other apps and Office, each with the number of widgets in it, and SHALL filter the cards to the chosen kind. The search SHALL filter within the chosen kind. + +#### Scenario: Filter by kind + +- **GIVEN** the picker is open on All +- **WHEN** Pieter chooses Data and charts +- **THEN** only the data and chart widgets are shown and the kind shows their count + +### Requirement: App tiles in the picker (REQ-WDG-042) + +The section "App tiles" SHALL show one tile per app in the reader's tile catalogue, square, in the tile's colour with its white icon and its name under it, followed by the entry Own tile. Choosing an app tile SHALL place it as a one-cell tile widget. + +#### Scenario: Place an app tile + +- **WHEN** Pieter chooses Case system under App tiles and Add widget +- **THEN** a one-cell tile for Case system is placed on the dashboard + +### Requirement: Widgets the role may not add (REQ-WDG-043) + +A widget type the reader's role may not add (role feature permissions) SHALL be shown as a grey card that says "Not allowed for your role" and SHALL NOT be chosen. A legacy widget type SHALL carry the label "Older widget type". + +#### Scenario: Embedded page not allowed + +- **GIVEN** the role Employee may not add Embedded page +- **THEN** its card is grey, says "Not allowed for your role" and cannot be chosen diff --git a/openspec/changes/widget-picker-board-sync/tasks.md b/openspec/changes/widget-picker-board-sync/tasks.md new file mode 100644 index 000000000..df07af414 --- /dev/null +++ b/openspec/changes/widget-picker-board-sync/tasks.md @@ -0,0 +1,9 @@ +# Tasks: widget-picker-board-sync + +- [x] Picker body: search, kind column with counts, card grid in two columns, sections Widgets from Launchpad, App tiles, From other Nextcloud apps +- [x] App tiles section: one tile per catalogue app in its tile colour, plus Own tile; one click places it as a one-cell tile (a click chooses, Add widget or a double click places; the discovered apps follow the catalogue) +- [x] Disabled cards for kinds the role may not add, with the reason; the label Older widget type for legacy widgets +- [ ] Assistant line at the top when the assistant is available (open: no "describe what you need" proposal flow exists to reuse; launchpad-ai-dashboard-assistant built summary widgets, not a layout proposal) +- [x] Translations in every shipped locale +- [x] Unit tests: counts per kind, filtering by kind and search, disabled card is not clickable, app tile placement +- [x] Playwright: open Add widget on My workspace, pick Data and charts, add Pie chart (`tests/e2e/widgets-picker-board-sync.spec.ts` 4/4 green on a sandbox Nextcloud 34.0.6 + MariaDB, 25 Nov 2026. The run found one app bug: `POST /api/dashboard/{id}/tile` dropped gridWidth/gridHeight, so a picker app tile landed 2x2 instead of one cell; `RequestDataExtractor::extractTileData()` now keeps a given size. Spec fixes: dialog width read from `.modal-container`, the footer checked against the scrolling body, and the role rule given a real allow-list and a place in group_order) diff --git a/openspec/changes/widgets-people-expertise-and-fields/design.md b/openspec/changes/widgets-people-expertise-and-fields/design.md deleted file mode 100644 index 01eba1f22..000000000 --- a/openspec/changes/widgets-people-expertise-and-fields/design.md +++ /dev/null @@ -1,53 +0,0 @@ -# Design: widgets-people-expertise-and-fields - -Read at development `d767c282`. - -## Context - -- `lib/Service/PeopleWidgetService.php` builds the list behind `GET /api/people` (`appinfo/routes.php:456`, `PeopleWidgetController::getUsers()`): `listUsers()` (line 154), group filtering (`extractGroupFilter()`, line 462), candidate resolution (line 495), profile fields from `IAccountManager` limited to `STANDARD_PROPERTIES` (lines 91-103, `buildAccountFields()` at line 658). -- `openspec/specs/people-widget/spec.md` REQ-PPL-011 limits search to the current page, client-side, on name and email. REQ-PPL-004 notes that field visibility (`IAccountManager` scopes) is not enforced yet, and that the unfiltered path uses a shared cache not keyed on the viewer. -- The open change `fix-people-widget-unbounded-user-scan` addresses the full-instance scan on the unfiltered path; this change's search must not reintroduce one. -- LaunchPad has no personal settings page today (`lib/Settings` holds `LaunchPadAdmin` and `LaunchPadAdminSection`). - -## Data - -`oc_launchpad_profile_values`: id, user_id, field_key, value (text), value_search (lower-cased, for LIKE), source (`self`, `ldap` or `nextcloud`), scope (the Nextcloud visibility scope for mirrored standard fields, null for custom fields), updated_at; unique on (user_id, field_key, value) so tags are one row each; index on (field_key, value_search). - -Field definitions are one admin setting `profile_fields`: up to 10 entries `{key, label, type: text|tags, source: self|ldap, ldapAttribute?, searchable, shownInWidget}`. - -## Decisions - -### D1: Values in a LaunchPad table, definitions in one setting - -Nextcloud core has no custom profile fields, so LaunchPad keeps the values. One row per value makes tag search an indexed query instead of a scan. - -### D2: LDAP-sourced fields sync on login and daily - -A `UserLoggedInEvent` listener and a daily `TimedJob` read `ILDAPProviderFactory::getLDAPProvider()->getMultiValueUserAttribute($uid, $attribute)` for users whose backend is LDAP, and replace that user's `ldap` rows. When `user_ldap` is not enabled the sync does nothing. People cannot edit LDAP-sourced fields; they see them read-only. - -### D3: Search is server-side, paged, and scope-aware - -`GET /api/people?q=` (at least 2 characters) runs two indexed queries: `IUserManager::search()` for names and emails, and a query on `value_search` in `oc_launchpad_profile_values`. That table also mirrors the searchable standard fields (role, headline, biography) with their scope, refreshed by a listener on `OCP\Accounts\UserUpdatedEvent` and by the daily job, because `IAccountManager` offers no substring search and LaunchPad must not query core's account tables. Matches are merged, ordered by display name and paged with the existing page size. A mirrored standard field counts as a match only when its scope lets the viewer see it (never `v2-private`); custom fields have a per-field visibility (`everyone` or `same group`). Search responses are never served from the shared unfiltered cache. - -### D4: The widget shows what the viewer may see - -Custom fields marked `shownInWidget` appear on the person card and in the detail view, under the same scope rule. Tags show as chips; clicking a chip searches for it. - -## Declarative-vs-imperative decision - -LaunchPad keeps its own tables and consumes OpenRegister only at runtime (`launchpad-adopt-or-abstractions`); profile values are LaunchPad rows and a service. - -## Seed data - -Demo installs define "Kantoorlocatie" (text, self), "Kostenplaats" (text, self, not shown in the widget) and "Expertise" (tags, self, searchable), and give the demo users realistic tags such as "subsidies", "Omgevingswet" and "privacy". - -## Risks - -- Search as a way to probe private data. Mitigation: D3's scope rule, and a test that a private biography never matches. -- Load on large directories. Mitigation: indexed queries, a two-character minimum and the existing page size. - -## Test plan - -- PHPUnit: field definition validation, self edits, LDAP sync with a stubbed provider, search across fields, private fields not matched, paging. -- Vitest: personal settings form, tag chips, widget search calling the server. -- Playwright: Pieter adds the tag "subsidies"; Sanne searches "subsidie" in a people widget and finds Pieter. diff --git a/openspec/changes/widgets-people-expertise-and-fields/tasks.md b/openspec/changes/widgets-people-expertise-and-fields/tasks.md deleted file mode 100644 index 833f431f1..000000000 --- a/openspec/changes/widgets-people-expertise-and-fields/tasks.md +++ /dev/null @@ -1,22 +0,0 @@ -# Tasks: widgets-people-expertise-and-fields - -## Backend - -- [ ] 1. Add `oc_launchpad_profile_values` with builder, entity and mapper, plus the `profile_fields` admin setting with validation (10 fields, types, sources). Verify: migration and PHPUnit. -- [ ] 2. Implement `ProfileFieldService` (definitions, self edits, read-only LDAP fields, values per user). Verify: PHPUnit. -- [ ] 3. Add the LDAP sync listener on `UserLoggedInEvent`, the standard-field mirror listener on `UserUpdatedEvent`, and one daily job for both (LDAP through `ILDAPProviderFactory`, doing nothing without `user_ldap`). Verify: PHPUnit with stubbed providers. -- [ ] 4. Add `lib/Settings/LaunchPadPersonal.php` with endpoints to read and save the person's own fields. Verify: PHPUnit and route-reachability. -- [ ] 5. Add server-side search `GET /api/people?q=` in `PeopleWidgetService` with the scope rule and paging, bypassing the shared cache. Verify: PHPUnit including a private biography that never matches. -- [ ] 6. Add custom fields to the people response for fields the viewer may see. Verify: PHPUnit. - -## Frontend - -- [ ] 7. Build the personal settings form (text fields and tag input). Verify: Vitest and an axe check. -- [ ] 8. Switch the widget search to the server when the query has 2 or more characters, and render custom fields and tag chips. Verify: Vitest. -- [ ] 9. Add the admin section for field definitions. Verify: Vitest. - -## Close - -- [ ] 10. Add the demo fields and tags. Verify: PHPUnit on the showcase. -- [ ] 11. Playwright: tag, then find by tag. -- [ ] 12. Add `nl` and `en` strings, fold the delta into `openspec/specs/people-widget/spec.md` on archive, and set d-find-expert and d-profile-fields to `built` in the parity matrix with evidence lines. diff --git a/openspec/parity/capabilities.json b/openspec/parity/capabilities.json index 3317819e7..71ffbaf64 100644 --- a/openspec/parity/capabilities.json +++ b/openspec/parity/capabilities.json @@ -394,6 +394,485 @@ "name_nl": "Identiteit, apparaten en uiterlijk" } ], + "features": [ + { + "slug": "grid-layout", + "title": "Drag-and-drop grid", + "title_nl": "Sleep-en-neerzet raster", + "area": "building", + "overlay": "grid-layout", + "specs": [ + "admin-settings", + "grid-layout", + "widgets", + "container-widget", + "dashboard-locking" + ] + }, + { + "slug": "dashboard-versioning", + "title": "Versioning and rollback", + "title_nl": "Versiebeheer en terugdraaien", + "area": "building", + "overlay": "dashboard-versioning", + "specs": [ + "dashboard-versioning" + ] + }, + { + "slug": "permissions", + "title": "Permission tiers", + "title_nl": "Rechtenniveaus", + "area": "rollout", + "overlay": "permissions", + "specs": [ + "permissions" + ] + }, + { + "slug": "dashboard-export-import", + "title": "Export and import", + "title_nl": "Exporteren en importeren", + "area": "rollout", + "overlay": "dashboard-export-import", + "specs": [ + "dashboard-export-import", + "dashboard-store" + ] + }, + { + "slug": "dashboard-switcher", + "title": "Multiple dashboards", + "title_nl": "Meerdere dashboards", + "area": "dashboards", + "overlay": "dashboard-switcher", + "specs": [ + "dashboard-deeplinking", + "dashboard-icons", + "dashboards", + "default-widget-bundle", + "runtime-shell", + "dashboard-language-content", + "dashboard-metadata-fields", + "dashboard-switcher", + "effective-default-marker" + ] + }, + { + "slug": "tiles", + "title": "Shortcut tiles", + "title_nl": "Snelkoppelingstegels", + "area": "launcher", + "overlay": "tiles", + "specs": [ + "launcher-bookmark-import", + "launcher-tile-internal-address", + "launcher-tile-open-behaviour", + "launcher-tile-sorting", + "tiles", + "links-widget", + "quicklinks-widget", + "service-health-ping", + "tile-quick-search" + ] + }, + { + "slug": "app-catalogue-and-launch", + "title": "App catalogue and launching any kind of app", + "title_nl": "App-catalogus en elk soort app starten", + "area": "launcher", + "overlay": null, + "specs": [ + "launcher-app-catalogue", + "launcher-discover-server-services", + "launcher-tile-launch-types", + "launcher-tile-sorting" + ] + }, + { + "slug": "organisation-navigation", + "title": "Organisation menu and footer", + "title_nl": "Organisatiemenu en voettekst", + "area": "launcher", + "overlay": null, + "specs": [ + "footer-customization", + "menu-widget", + "navigation-editor-org" + ] + }, + { + "slug": "nc-dashboard-widget-proxy", + "title": "Nextcloud widgets", + "title_nl": "Nextcloud-widgets", + "area": "widgets", + "overlay": "nc-dashboard-widget-proxy", + "specs": [ + "attention-feed", + "legacy-widget-bridge", + "nc-dashboard-widget-proxy" + ] + }, + { + "slug": "content-widgets", + "title": "Content widgets for text, media, news and files", + "title_nl": "Inhoudswidgets voor tekst, media, nieuws en bestanden", + "area": "widgets", + "overlay": null, + "specs": [ + "widgets", + "calendar-widget", + "clock-weather-widgets", + "divider-widget", + "files-widget", + "header-widget", + "image-widget", + "label-widget", + "launchpad-file-access-widget", + "link-button-widget", + "news-widget", + "text-display-widget", + "video-widget" + ] + }, + { + "slug": "people-widget", + "title": "Colleagues, birthdays and expertise", + "title_nl": "Collega's, verjaardagen en expertise", + "area": "widgets", + "overlay": null, + "specs": [ + "people-widget" + ] + }, + { + "slug": "iframe-embed-widget", + "title": "Embedded web pages and reports", + "title_nl": "Ingebedde webpagina's en rapporten", + "area": "widgets", + "overlay": null, + "specs": [ + "adopt-connection-registry", + "iframe-embed-widget" + ] + }, + { + "slug": "runtime-or-consumption", + "title": "Live business data", + "title_nl": "Live bedrijfsdata", + "area": "integrations", + "overlay": "runtime-or-consumption", + "specs": [ + "adopt-connection-registry", + "background-job-feed-refresh", + "integrations-live-tile-lists", + "integrations-office-tiles", + "live-data-tile-widget" + ] + }, + { + "slug": "kpi-cards", + "title": "KPI cards", + "title_nl": "KPI-kaarten", + "area": "widgets", + "overlay": "kpi-cards", + "specs": [] + }, + { + "slug": "launchpad-spend-analytics-widget", + "title": "Spend analytics card", + "title_nl": "Uitgavenanalyse-kaart", + "area": "widgets", + "overlay": "launchpad-spend-analytics-widget", + "specs": [ + "launchpad-spend-analytics-widget" + ] + }, + { + "slug": "conditional-visibility", + "title": "Conditional visibility", + "title_nl": "Voorwaardelijke zichtbaarheid", + "area": "targeting", + "overlay": "conditional-visibility", + "specs": [ + "conditional-visibility", + "conditional-visibility-editor" + ] + }, + { + "slug": "admin-roles", + "title": "Role delegation", + "title_nl": "Roldelegatie", + "area": "targeting", + "overlay": "admin-roles", + "specs": [ + "action-authorization", + "admin-roles", + "role-feature-permissions" + ] + }, + { + "slug": "admin-templates", + "title": "Admin templates", + "title_nl": "Beheersjablonen", + "area": "rollout", + "overlay": "admin-templates", + "specs": [ + "admin-templates", + "dashboards" + ] + }, + { + "slug": "setup-wizard", + "title": "Setup wizard, demo content and guided tour", + "title_nl": "Installatiewizard, demo-inhoud en rondleiding", + "area": "rollout", + "overlay": null, + "specs": [ + "runtime-shell", + "demo-data-showcases", + "first-time-setup", + "setup-wizard" + ] + }, + { + "slug": "dashboard-quota-limits", + "title": "Dashboard quotas", + "title_nl": "Dashboardquota", + "area": "rollout", + "overlay": "dashboard-quota-limits", + "specs": [ + "dashboard-quota-limits" + ] + }, + { + "slug": "confluence-html-import", + "title": "Confluence import", + "title_nl": "Confluence-import", + "area": "rollout", + "overlay": "confluence-html-import", + "specs": [ + "confluence-html-import" + ] + }, + { + "slug": "dashboard-sharing", + "title": "Sharing dashboards with people and groups", + "title_nl": "Dashboards delen met personen en groepen", + "area": "sharing", + "overlay": null, + "specs": [ + "dashboard-sharing" + ] + }, + { + "slug": "dashboard-public-share", + "title": "Public share links", + "title_nl": "Openbare deellinks", + "area": "sharing", + "overlay": "dashboard-public-share", + "specs": [ + "sharing-public-start-page", + "dashboard-public-share" + ] + }, + { + "slug": "dashboard-kiosk-mode", + "title": "Kiosk and signage mode", + "title_nl": "Kiosk- en narrowcastmodus", + "area": "sharing", + "overlay": "dashboard-kiosk-mode", + "specs": [ + "dashboard-kiosk-mode" + ] + }, + { + "slug": "news-and-announcements", + "title": "News and announcements", + "title_nl": "Nieuws en mededelingen", + "area": "engagement", + "overlay": null, + "specs": [ + "engagement-activity-digest", + "engagement-announcements" + ] + }, + { + "slug": "acknowledgements-and-reactions", + "title": "Read confirmations, reactions and comments", + "title_nl": "Leesbevestigingen, reacties en opmerkingen", + "area": "engagement", + "overlay": null, + "specs": [ + "dashboard-acknowledgements", + "dashboard-reactions" + ] + }, + { + "slug": "communities-events-and-knowledge", + "title": "Communities, events and knowledge base", + "title_nl": "Community's, evenementen en kennisbank", + "area": "engagement", + "overlay": null, + "specs": [ + "engagement-communities" + ] + }, + { + "slug": "activity-feed-integration", + "title": "Activity feed", + "title_nl": "Activiteitenoverzicht", + "area": "engagement", + "overlay": "activity-feed-integration", + "specs": [ + "activity-feed-integration" + ] + }, + { + "slug": "nc-unified-search-integration", + "title": "Unified search", + "title_nl": "Geintegreerd zoeken", + "area": "search-ai", + "overlay": "nc-unified-search-integration", + "specs": [ + "search-ai-prefix-shortcuts", + "nc-unified-search-integration" + ] + }, + { + "slug": "launchpad-ai-dashboard-assistant", + "title": "AI assistant", + "title_nl": "AI-assistent", + "area": "search-ai", + "overlay": "launchpad-ai-dashboard-assistant", + "specs": [ + "mcp-tool-surface", + "launchpad-ai-dashboard-assistant" + ] + }, + { + "slug": "dashboard-view-analytics", + "title": "Usage analytics", + "title_nl": "Gebruiksanalyse", + "area": "governance", + "overlay": null, + "specs": [ + "dashboard-view-analytics" + ] + }, + { + "slug": "prometheus-metrics", + "title": "Prometheus metrics", + "title_nl": "Prometheus-metrieken", + "area": "governance", + "overlay": "prometheus-metrics", + "specs": [ + "prometheus-metrics" + ] + }, + { + "slug": "launchpad-compliance-audit-panel", + "title": "Audit panel", + "title_nl": "Auditpaneel", + "area": "governance", + "overlay": "launchpad-compliance-audit-panel", + "specs": [ + "launchpad-compliance-audit-panel" + ] + }, + { + "slug": "orphaned-data-cleanup", + "title": "Data cleanup", + "title_nl": "Data-opschoning", + "area": "sharing", + "overlay": "orphaned-data-cleanup", + "specs": [ + "dashboard-sharing", + "orphaned-data-cleanup" + ] + }, + { + "slug": "admin-tooling", + "title": "Bulk changes, command line and REST API", + "title_nl": "Bulkwijzigingen, commandoregel en REST-API", + "area": "governance", + "overlay": null, + "specs": [ + "rest-api-reference", + "cli-commands", + "dashboard-bulk-operations" + ] + }, + { + "slug": "launchpad-enterprise-security-access", + "title": "SSO and access posture", + "title_nl": "SSO en toegangsstatus", + "area": "platform", + "overlay": "launchpad-enterprise-security-access", + "specs": [ + "launchpad-enterprise-security-access" + ] + }, + { + "slug": "theming-and-languages", + "title": "House style, themes and languages", + "title_nl": "Huisstijl, thema's en talen", + "area": "platform", + "overlay": null, + "specs": [ + "platform-dashboard-theme-and-css" + ] + }, + { + "slug": "launchpad-mobile-remote-access", + "title": "Mobile access", + "title_nl": "Mobiele toegang", + "area": "platform", + "overlay": "launchpad-mobile-remote-access", + "specs": [ + "launchpad-mobile-remote-access" + ] + }, + { + "slug": "self-hosting", + "title": "Self-hosting on your own Nextcloud", + "title_nl": "Zelf hosten op je eigen Nextcloud", + "area": "platform", + "overlay": null, + "specs": [ + "runtime-or-consumption", + "launchpad-adopt-or-abstractions" + ] + }, + { + "slug": "groupfolder-storage-backend", + "title": "GroupFolder storage (optional)", + "title_nl": "GroupFolder-opslag (optioneel)", + "area": "governance", + "overlay": "groupfolder-storage-backend", + "specs": [ + "groupfolder-storage-backend" + ] + }, + { + "slug": "launchpad-meeting-calendar-actions", + "title": "Meeting actions", + "title_nl": "Vergaderacties", + "area": "widgets", + "overlay": "launchpad-meeting-calendar-actions", + "specs": [ + "launchpad-meeting-calendar-actions" + ] + } + ], + "internalSpecs": [ + "beta-alignment", + "dashboard-cascade-events", + "infrastructure-helpers", + "initial-state-contract", + "license-header-consistency", + "resource-uploads" + ], "providers": [ { "key": "launchpad", @@ -438,7 +917,8 @@ "homarr": "unknown", "dashy": "unknown", "question": "src/manifest.d/connection-registry.json shows the Integrations page only when appInstalled 'integriq'. If integriq's appinfo id has not moved from openconnector yet, the check matches nothing and the page silently never appears. Settle by reading integriq's info.xml id on development and loading the page.", - "seen": "src/manifest.d/connection-registry.json:16" + "seen": "src/manifest.d/connection-registry.json:16", + "feature": "runtime-or-consumption" }, { "id": "q-charts-live", @@ -451,7 +931,8 @@ "homarr": "unknown", "dashy": "unknown", "question": "The widgets call OpenRegister GraphQL. The repo shows the call, not that an installed OpenRegister answers it with the aggregations the widget expects. Drive it with OpenRegister installed.", - "seen": "src/services/graphqlClient.js:16" + "seen": "src/services/graphqlClient.js:16", + "feature": "kpi-cards" }, { "id": "q-registry-live", @@ -464,7 +945,8 @@ "homarr": "unknown", "dashy": "unknown", "question": "Discovery is OpenRegister's GenericStoreService and install is LaunchPad's ImportService. Neither half was run against a live registry.", - "seen": "lib/Controller/StoreController.php:134" + "seen": "lib/Controller/StoreController.php:134", + "feature": "dashboard-export-import" }, { "id": "q-groupfolder", @@ -477,7 +959,8 @@ "homarr": "unknown", "dashy": "unknown", "question": "openspec/features.overlay.json lists groupfolder-storage-backend as beta, while the open change retire-groupfolder-storage-backend says the migration command moved nothing and proposes retiring it. Decide whether this is a capability or decided-no.", - "seen": "openspec/changes/retire-groupfolder-storage-backend/proposal.md:33" + "seen": "openspec/changes/retire-groupfolder-storage-backend/proposal.md:33", + "feature": "groupfolder-storage-backend" }, { "id": "q-comments", @@ -490,7 +973,8 @@ "homarr": "unknown", "dashy": "unknown", "question": "lib/Notification/Notifier.php renders a mentioned_in_comment subject, but this reading found no comment screen and no code that raises the notification. Either a sibling or the platform comments app produces it, or the handler is dead.", - "seen": "lib/Notification/Notifier.php:119" + "seen": "lib/Notification/Notifier.php:119", + "feature": "acknowledgements-and-reactions" }, { "id": "q-sibling-widgets", @@ -503,7 +987,8 @@ "homarr": "unknown", "dashy": "unknown", "question": "competitor-parity-2026-09 names C-reporting-22 as covered by group dashboards plus role feature permissions, with dossiq contributing widgets. Whether any sibling registers a Nextcloud widget that the nc-widget proxy then scopes per role was not read.", - "seen": "openspec/changes/competitor-parity-2026-09/proposal.md:37" + "seen": "openspec/changes/competitor-parity-2026-09/proposal.md:37", + "feature": "nc-dashboard-widget-proxy" }, { "id": "q-person-activity", @@ -516,7 +1001,8 @@ "homarr": "unknown", "dashy": "unknown", "question": "Candidates C-reporting-13 and C-reporting-19 in the dashboards-and-who-may-see-them change. The change itself says it needs a stated purpose before it is a feature, because in a gemeente it is a works-council matter. Not a rating until that is decided.", - "seen": "openspec/changes/competitor-parity-2026-09/proposal.md:65" + "seen": "openspec/changes/competitor-parity-2026-09/proposal.md:65", + "feature": "launchpad-compliance-audit-panel" }, { "id": "q-drive-nc-dashboard", @@ -528,7 +1014,8 @@ "nextcloud-dashboard": "unknown", "homarr": "unknown", "dashy": "unknown", - "question": "The built-in Dashboard's column rests on 14 feature rows captured in April. It runs on every dev instance, so it is the cheapest column to drive: resize, outside feeds, background and per-group defaults can all be settled in one session." + "question": "The built-in Dashboard's column rests on 14 feature rows captured in April. It runs on every dev instance, so it is the cheapest column to drive: resize, outside feeds, background and per-group defaults can all be settled in one session.", + "feature": "grid-layout" } ], "capabilities": [ @@ -545,7 +1032,9 @@ "built": { "state": "built", "evidence": "src/views/Views.vue:183", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/grid-layout", + "requirement": "openspec/specs/grid-layout :: Drag to Reposition (REQ-GRID-002)" }, "reachedOn": "Workspace page (/apps/launchpad/), after choosing Edit dashboard in the dashboard menu", "evidence": { @@ -559,7 +1048,11 @@ "providerHow": "read-from-code", "feature": "grid-layout", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpBewerken" + } }, { "id": "build-resize", @@ -574,7 +1067,9 @@ "built": { "state": "built", "evidence": "src/views/Views.vue:183", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/grid-layout", + "requirement": "openspec/specs/grid-layout :: Resize by Edge Dragging (REQ-GRID-003)" }, "reachedOn": "Workspace page in edit mode, the same grid as build-drag", "evidence": { @@ -588,7 +1083,11 @@ "providerHow": "read-from-code", "feature": "grid-layout", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpBewerken" + } }, { "id": "build-keyboard", @@ -602,8 +1101,11 @@ "dashy": "no", "built": { "state": "built", - "evidence": "src/modals/WidgetMovePanel.vue:27; src/components/Widgets/WidgetContextMenu.vue:27", - "owner": "ConductionNL/launchpad" + "evidence": "nextcloud-vue CnDashboardGrid.vue:35-47 (main 0f1c0ffbb) makes every grid item in edit mode a focusable named group (role group, aria-label, tabindex 0 while keyboardRepositioning, default true) and turns Enter or Space into the contextmenu event a right-click sends; src/views/Views.vue:290 catches it on the placement and opens WidgetContextMenu; src/components/Widgets/WidgetContextMenu.vue:22-27 offers Move, which src/views/Views.vue:420 and :444 route to src/modals/WidgetMovePanel.vue; WidgetMovePanel.vue:286-310 moves with the arrow keys, resizes with Shift and the arrow keys, saves on Enter and cancels on Escape, through nudgePlacement (src/composables/useGridManager.js:248), the collision model the drag path uses; Views.vue:1964 handleMoveSave persists it. Tests: src/modals/__tests__/WidgetMovePanel.spec.js, tests/e2e/keyboard-widget-repositioning.spec.ts (drives the page with the keyboard only, checks the position after reload)", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-10-07-keyboard-accessible-widget-repositioning", + "readOn": "2026-10-07", + "requirement": "openspec/specs/grid-layout :: REQ-GRID-KBD-002 Keyboard-operable move and resize" }, "reachedOn": "Workspace page, widget context menu, Move", "provider": "launchpad", @@ -617,6 +1119,11 @@ "dashy": "source read at 4.7.0: searched src for keydown, arrow, move with keyboard: src/utils/ArrowKeyNavigation.js:1-6 only moves focus between tiles in search results; reordering is pointer drag only (src/directives/DragSort.js:24-35 forceFallback). Items can be copied or moved to another section through the context menu (src/assets/locales/en.json:320 'Copy or Move'), widgets and sections cannot", "workspace-365": "not checked: W365 user guide and FAQ for keyboard move or resize of tiles, not found", "microsoft-viva": "not checked: support.microsoft.com c4f573dd screen reader guide covers touch gestures to reorder cards only; no keyboard move or resize found" + }, + "note": "Re-rated 2026-10-07 from code: built, yes, unchanged. The change keyboard-accessible-widget-repositioning still shows its 11 tasks unticked, but every one is delivered: tasks 1-3 (focusable, named grid item; Enter opens the menu) by nextcloud-vue CnDashboardGrid instead of the retired src/components/DashboardGrid.vue the tasks name, tasks 4-9 in launchpad, tasks 10-11 in the Playwright spec. The change is ready to tick and archive. Not checked live in a browser in this round.", + "screen": { + "canvas": "design-system", + "board": "LpBewerken" } }, { @@ -632,7 +1139,12 @@ "built": { "state": "built", "evidence": "lib/Service/AdminSettingsService.php:124; src/components/admin/AdminSettings.vue:96", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/admin-settings", + "requirement": [ + "openspec/specs/admin-settings :: Default Grid Columns Setting (REQ-ASET-006)", + "openspec/specs/dashboards :: Update Dashboard (REQ-DASH-004)" + ] }, "reachedOn": "Admin settings (/settings/admin/launchpad), Default settings, Default grid columns", "provider": "launchpad", @@ -640,13 +1152,17 @@ "feature": "grid-layout", "featureConfidence": "high", "origin": "own-code", - "note": "An administrator sets the default for the instance; the reading did not find a per-dashboard column control for end users.", + "note": "An administrator sets the default for the instance; the reading did not find a per-dashboard column control for end users. The dashboards spec does let a dashboard's owner change its column count (REQ-DASH-004, scenario on grid columns); the row now records both.", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/src/DashboardApp.vue:587-596 the grid is a centered flex-wrap row with max-width 1800px, so the column count follows the window width; searched apps/dashboard for column, grid settings: no user or admin setting", "homarr": "source read at v1.77.2: packages/db/schema/sqlite.ts:325 layout table with columnCount per board layout; apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx:30 add layout with columnCount; en.json:4573 'Column count'. Driven on the lab at v1.77.2 on 2026-09-26: board settings Layout shows 'Responsive layouts' with Name, Column count and Breakpoint per layout.", "dashy": "source read at 4.7.0: src/utils/config/ConfigSchema.json:421-427 appConfig.colCount 1 to 8, applied in src/views/Home.vue:138 and :277-284; editable in the Edit App Config form (src/components/InteractiveEditor/EditAppConfig.vue:21 schema form) or the YAML editor", "workspace-365": "https://support.workspace365.net/en/articles/175608-faq-for-admins admins can set shared tile group size to '2 columns (Enlarge) or 1 column (Shrink)'; a grid column count for the whole page is not described (read 2026-09-26)", "microsoft-viva": "not checked: create-dashboard and card designer pages for a column setting; cards are medium or large only" + }, + "screen": { + "canvas": "design-system", + "board": "LpBewerken" } }, { @@ -662,7 +1178,9 @@ "built": { "state": "built", "evidence": "src/views/Views.vue:650", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-responsive-grid-breakpoints", + "requirement": "openspec/specs/grid-layout :: Grid Responsiveness — concrete breakpoints (REQ-GRID-007)" }, "reachedOn": "Workspace page at any viewport width", "evidence": { @@ -676,7 +1194,11 @@ "providerHow": "read-from-code", "feature": "grid-layout", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpMobiel" + } }, { "id": "build-container", @@ -691,7 +1213,12 @@ "built": { "state": "built", "evidence": "src/components/Widgets/Renderers/ContainerWidget.vue:52; src/constants/widgetRegistry.js:16", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-container-widget", + "requirement": [ + "openspec/specs/container-widget :: REQ-CONT-002 Inner grid bounded by container cell", + "openspec/specs/container-widget :: REQ-CONT-005 Edit-mode independence" + ] }, "reachedOn": "Workspace page, Add widget, Container", "evidence": { @@ -705,7 +1232,11 @@ "providerHow": "read-from-code", "feature": "grid-layout", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpManagement" + } }, { "id": "build-style", @@ -720,7 +1251,12 @@ "built": { "state": "built", "evidence": "src/views/Views.vue:309", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/widgets", + "requirement": [ + "openspec/specs/widgets :: Widget Style Editor (REQ-WDG-011)", + "openspec/specs/widgets :: Update Widget Placement (REQ-WDG-004)" + ] }, "reachedOn": "Workspace page, widget context menu, Edit", "provider": "launchpad", @@ -734,6 +1270,10 @@ "dashy": "source read at 4.7.0: a widget has only a label (src/components/InteractiveEditor/EditWidget.vue:19-23); colour and custom CSS are set per section (ConfigSchema.json:954-963, applied src/components/LinkItems/Collapsable.vue:89-90) and per item (color, backgroundColor ConfigSchema.json:1401-1410), not per widget", "workspace-365": "https://support.workspace365.net/en/articles/483000-shortcut-tile 'Choose an icon' and 'the default color, header color, primary color, or a custom color'; group titles renamable; borders not described (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard 'edit properties like the label, icon, image'; colours and borders per card not described (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpWidgetInstellen" } }, { @@ -749,7 +1289,9 @@ "built": { "state": "built", "evidence": "src/modals/WidgetPickerModal.vue:21; src/views/Views.vue:273", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-unified-add-widget-flow", + "requirement": "openspec/specs/widgets :: The widget picker narrows its list as you type (REQ-WDG-028)" }, "reachedOn": "Workspace page, dashboard menu, Add widget", "provider": "launchpad", @@ -763,6 +1305,10 @@ "dashy": "source read at 4.7.0: src/components/InteractiveEditor/EditWidget.vue:14-18 the widget type is a free-text input ('Widget Type', en.json:385); the registry in src/components/Widgets/WidgetBase.vue:53-148 is not offered as a list; ConfigSchema.json:1476-1480 type has no enum, so the YAML editor cannot complete it either", "workspace-365": "https://support.workspace365.net/en/articles/175363-full-guide-for-user 'Click on Edit and then + Add tiles'; https://support.workspace365.net/en/articles/483000-shortcut-tile shortcut apps in the App store 'with searchable tags' (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/available-dashboard-cards '+ Add a card' opens the dashboard toolbox with 'Suggested cards' and 'Add more cards'; a search box over the toolbox is not described (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpWidgetKiezen" } }, { @@ -778,7 +1324,12 @@ "built": { "state": "built", "evidence": "lib/Service/WidgetService.php:86; src/constants/widgetRegistry.js:141", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-nc-dashboard-widget-proxy", + "requirement": [ + "openspec/specs/widgets :: nc-widget placement type (REQ-WDG-018)", + "openspec/specs/legacy-widget-bridge :: Mount a captured legacy widget into a DOM container (REQ-LWB-002)" + ] }, "reachedOn": "Workspace page, Add widget, Nextcloud widget", "evidence": { @@ -792,7 +1343,11 @@ "providerHow": "read-from-code", "feature": "nc-dashboard-widget-proxy", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWidgetKiezen" + } }, { "id": "build-no-overlap", @@ -807,13 +1362,15 @@ "built": { "state": "built", "evidence": "src/composables/useGridManager.js:221", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-widget-collision-placement", + "requirement": "openspec/specs/grid-layout :: REQ-GRID-006 Widget Auto-Layout (bottom-append placement)" }, "reachedOn": "Workspace page, any Add widget action", "provider": "launchpad", "providerHow": "read-from-code", "feature": "grid-layout", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/src/DashboardApp.vue:463 a newly ticked widget is appended to the end of the layout list, and the flex-wrap list (:587-596) cannot overlap cards by construction", @@ -821,6 +1378,10 @@ "dashy": "source read at 4.7.0: sections flow in a CSS grid (src/views/Home.vue:287 grid-template-columns repeat(var(--col-count))) and widgets in a list (Section.vue:60-63); there is no free positioning, so a new section or widget always lands in the next free slot", "workspace-365": "https://support.workspace365.net/en/articles/175608-faq-for-admins the system 'can automatically reorder tiles within shared groups to minimize gaps based on tile size' (read 2026-09-26)", "microsoft-viva": "not checked: create-dashboard for placement rules; the targeting page only advises rearranging cards to avoid gaps" + }, + "screen": { + "canvas": "design-system", + "board": "LpBewerken" } }, { @@ -834,25 +1395,34 @@ "homarr": "no", "dashy": "no", "built": { - "state": "built", - "evidence": "src/views/Views.vue:190; src/composables/useDashboardLock.js", + "state": "specified", + "evidence": "Not built: concurrent editing as LpBewerken draws it (decision 406). Built today is the edit lock, where the second editor stays read-only behind a banner naming the holder: src/views/Views.vue:277 (EditLockBanner), src/composables/useDashboardLock.js, src/components/Workspace/EditLockBanner.vue, openspec/specs/dashboard-locking REQ-LOCK-001 and REQ-LOCKUI-001.", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-dashboard-edit-lock-ui" + "change": "openspec/changes/building-edit-a-dashboard-together", + "requirement": [ + "openspec/changes/building-edit-a-dashboard-together/specs/dashboard-co-editing :: Several people SHALL be able to edit a shared dashboard at once", + "openspec/changes/building-edit-a-dashboard-together/specs/dashboard-co-editing :: Two changes to the same widget SHALL NOT silently replace each other" + ], + "plan": "openspec/changes/building-edit-a-dashboard-together" }, - "reachedOn": "nothing: /api/dashboards/{uuid}/lock has no caller anywhere in src/", + "reachedOn": "Workspace page, Edit: the page takes the dashboard lock while you edit and a banner names the colleague who holds it", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-locking", + "feature": "grid-layout", "featureConfidence": "high", "origin": "own-code", - "note": "The lock service and its four routes exist; no page acquires or shows a lock, so a user cannot reach it.", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/lib/Controller/DashboardApiController.php:202-206 the layout is a per-user config value; searched apps/dashboard for share, lock, etag, version: there is no shared dashboard, so no concurrent editing and no lock", "homarr": "source read at v1.77.2: packages/api/src/router/board.ts:854 saveBoard diffs the submitted board against the database and writes it with no version check or lock; searched apps and packages for editLock, lockedBy, isLocked, optimistic: none", "dashy": "source read at 4.7.0: services/endpoints/save-config.js:36-90 writes conf.yml whole with only a timestamped backup; searched services for etag, if-match, lock, conflict: none. The last save wins", "workspace-365": "not checked: W365 spaces and FAQ articles for concurrent edit locking", "microsoft-viva": "not checked: create-dashboard and edit pages for co-authoring or locking of the dashboard" - } + }, + "screen": { + "canvas": "design-system", + "board": "LpBewerken" + }, + "note": "Board canon (decision 406): the row is concurrent editing as drawn on LpBewerken. The edit lock stays the built behaviour until the plan lands." }, { "id": "build-personal-hide", @@ -866,11 +1436,15 @@ "dashy": "partial", "built": { "state": "built", - "evidence": "src/views/Views.vue:150; src/components/WidgetWrapper.vue; src/stores/personalLayer.js", + "evidence": "src/views/Views.vue:339 (@hideForMe); src/components/WidgetWrapper.vue:71; src/stores/personalLayer.js", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-dashboards-personal-hide-ui" + "change": [ + "openspec/changes/archive/2026-09-29-dashboards-personal-hide-ui", + "openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them" + ], + "requirement": "openspec/specs/dashboards :: A person can hide a widget for themselves (REQ-PERSUI-001)" }, - "reachedOn": "nothing: /api/dashboards/{dashboardId}/personal-layer has no caller in src/", + "reachedOn": "Workspace page, a widget's cog on a shared dashboard: Hide for me", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/src/DashboardApp.vue:458-470 each person ticks widgets on or off and the result is stored only in their own user config (apps/dashboard/lib/Controller/DashboardApiController.php:205). There is no shared dashboard: the only common thing is the admin default list (apps/dashboard/lib/Service/DashboardService.php:34), which a person's own layout replaces", "homarr": "source read at v1.77.2: packages/db/schema/sqlite.ts:395 section_collapse_state per user; packages/api/src/router/section/section-router.ts:14 each user collapses a category for themselves only; no per-user hiding of single widgets (item table sqlite.ts:413 has no per-user state)", @@ -882,7 +1456,11 @@ "providerHow": "read-from-code", "feature": "permissions", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "build-config-file", @@ -897,7 +1475,12 @@ "built": { "state": "built", "evidence": "lib/Service/ImportService.php:138; lib/Command/ImportCommand.php:36", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/dashboard-export-import", + "requirement": [ + "openspec/specs/dashboard-export-import :: REQ-EXIM-001 ZIP Format Definition", + "openspec/specs/dashboard-export-import :: REQ-EXIM-004 Import Endpoint" + ] }, "reachedOn": "Admin settings, Operations tab, Export and import; and occ launchpad import", "evidence": { @@ -912,7 +1495,11 @@ "feature": "dashboard-export-import", "featureConfidence": "high", "origin": "own-code", - "note": "Import takes a ZIP of the JSON export. That moves a dashboard between servers; it is not a hand-authored configuration workflow." + "note": "Import takes a ZIP of the JSON export. That moves a dashboard between servers; it is not a hand-authored configuration workflow.", + "screen": { + "canvas": "design-system", + "board": "LpBeheerOnderhoud" + } }, { "id": "build-rollback", @@ -926,23 +1513,27 @@ "dashy": "partial", "built": { "state": "built", - "evidence": "src/views/Views.vue:177; src/modals/VersionHistoryModal.vue", + "evidence": "src/views/Views.vue:245 (VersionHistoryModal); src/modals/VersionHistoryModal.vue", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-dashboard-version-history-ui" + "change": "openspec/changes/archive/2026-09-29-dashboard-version-history-ui", + "requirement": "openspec/specs/dashboard-versioning :: Restoring asks first and can be undone (REQ-VERSUI-003)" }, - "reachedOn": "nothing: /api/dashboards/{uuid}/versions and its restore route have no caller in src/", + "reachedOn": "Workspace page, dashboard menu: Version history, then Restore", "provider": "launchpad", "providerHow": "read-from-code", "feature": "dashboard-versioning", "featureConfidence": "high", "origin": "own-code", - "note": "openspec/features.overlay.json advertises dashboard-versioning as stable (\"You roll a dashboard back to last week in one step\"); no page reaches it.", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/lib/Controller/DashboardApiController.php:205 each save overwrites the single user config value; searched apps/dashboard for history, version, revision, restore: none", "homarr": "source read at v1.77.2: packages/db/schema/sqlite.ts:262 board table and related tables keep only the current state, no history or revision table (searched sqlite.ts for history, revision, snapshot); only a whole-database restore exists (en.json management.page.tool.backup.import)", "dashy": "source read at 4.7.0: services/endpoints/save-config.js:61-75 every save copies the old conf.yml to user-data/config-backups/<name>-<timestamp>.backup.yml; searched src for backup restore: no UI lists or restores them, an admin copies a file back on the server", "workspace-365": "not checked: W365 spaces, FAQ and audit logging articles for restoring a previous layout", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard 'The dashboard details contain settings for your dashboard, page versioning'; https://learn.microsoft.com/en-us/sharepoint/homesites/create-multilingual-dashboard 'view the version history of the default dashboard'; restoring a version is not described (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpVersies" } }, { @@ -958,7 +1549,12 @@ "built": { "state": "built", "evidence": "src/components/Workspace/DashboardSwitcherSidebar.vue:224", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-dashboard-switcher-sidebar", + "requirement": [ + "openspec/specs/dashboard-switcher :: REQ-SWITCH-001 Three-section navigation", + "openspec/specs/dashboard-switcher :: REQ-SWITCH-002 Switch click semantics" + ] }, "reachedOn": "Workspace page, Dashboards sidebar", "evidence": { @@ -972,7 +1568,11 @@ "providerHow": "read-from-code", "feature": "dashboard-switcher", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "dash-default", @@ -987,7 +1587,13 @@ "built": { "state": "built", "evidence": "src/components/Workspace/DashboardRowActions.vue:90", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-default-dashboard-flag", + "requirement": [ + "openspec/specs/dashboards :: REQ-DASH-018 Active-dashboard resolution chain (multi-scope)", + "openspec/specs/dashboards :: REQ-DASH-015 Single default group-shared dashboard per group", + "openspec/specs/effective-default-marker :: REQ-EDM-002 Effective default uses resolver precedence" + ] }, "reachedOn": "Workspace page, dashboard menu, Set as default", "provider": "launchpad", @@ -1001,6 +1607,13 @@ "dashy": "source read at 4.7.0: the root conf.yml always opens first; src/router.js:48-52 startingView picks the view (home, minimal, workspace) not a page; searched ConfigSchema.json pages for default: no flag, and users cannot choose their own", "workspace-365": "https://support.workspace365.net/en/articles/703640-using-and-organising-spaces-in-workspace-365 admins can 'let users start on the Personal space or on a Shared space' by dragging it 'to the top position' (read 2026-09-26)", "microsoft-viva": "https://www.microsoft.com/releasecommunications/api/v1/m365 item 567887 admins 'manage home site priority order' across multiple home sites; a user cannot pick their own default (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpWerkplek", + "LpDashboardInstellingen" + ] } }, { @@ -1016,12 +1629,20 @@ "built": { "state": "built", "evidence": "src/modals/DashboardConfigModal.vue:75; src/modals/DashboardConfigModal.vue:87", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": [ + "openspec/specs/dashboards", + "openspec/specs/dashboard-icons" + ], + "requirement": [ + "openspec/specs/dashboards :: Update Dashboard (REQ-DASH-004)", + "openspec/specs/dashboard-icons :: IconPicker dual-input UX (REQ-ICON-008)" + ] }, "reachedOn": "Workspace page, dashboard menu, Dashboard configuration, General tab", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-icons", + "feature": "dashboard-switcher", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -1030,6 +1651,10 @@ "dashy": "source read at 4.7.0: ConfigSchema.json:151-221 pageInfo title, description, logo, favicon per config file; src/components/InteractiveEditor/EditPageInfo.vue form ('Edit Page Info', en.json:339); per-page pageInfo merged at src/store.js:535-539", "workspace-365": "not checked: W365 spaces article for space description or icon", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard Dashboard details: 'Change Thumbnail' and 'Description ... to be shown in search results'; https://learn.microsoft.com/en-us/sharepoint/homesites/create-multilingual-dashboard translated dashboard name (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpDashboardInstellingen" } }, { @@ -1045,7 +1670,9 @@ "built": { "state": "built", "evidence": "lib/Service/DashboardService.php:2190; src/views/Views.vue:2037", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-fork-current-as-personal", + "requirement": "openspec/specs/dashboards :: REQ-DASH-020 Fork any visible dashboard as a personal copy" }, "reachedOn": "Workspace page, Dashboards sidebar, Add dashboard", "provider": "launchpad", @@ -1059,6 +1686,10 @@ "dashy": "source read at 4.7.0: searched src and services for duplicate, clone, copy page: only item 'Copy or Move' (en.json:320) and section name duplicate checks (EditSection.vue:92); no way to copy a page", "workspace-365": "not checked: W365 spaces and user guide for copying a space", "microsoft-viva": "not checked: create-dashboard and user customise pages for copying a dashboard" + }, + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" } }, { @@ -1074,12 +1705,17 @@ "built": { "state": "built", "evidence": "lib/Controller/PageController.php:127; src/manifest.json:176", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/dashboard-deeplinking", + "requirement": [ + "openspec/specs/dashboard-deeplinking :: REQ-DDL-002 Server-side resolution", + "openspec/specs/dashboards :: REQ-DASH-027 Path-based dashboard resolution" + ] }, "reachedOn": "/apps/launchpad/dashboards/{id} and /apps/launchpad/{path}", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-deeplinking", + "feature": "dashboard-switcher", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -1088,6 +1724,10 @@ "dashy": "source read at 4.7.0: src/router.js:55-67 canonical /home/:page and /home/:page/:section routes, also for minimal and workspace views; deep links resolve the page's config (src/store.js:500-505)", "workspace-365": "not checked: W365 spaces article for deep links to a space", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-multilingual-dashboard 'Copy the link to the dashboard under Properties > Name' and 'Paste the link in a browser' (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" } }, { @@ -1103,7 +1743,9 @@ "built": { "state": "built", "evidence": "src/components/Workspace/DashboardSwitcherSidebar.vue:326", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/dashboard-sharing", + "requirement": "openspec/specs/dashboard-sharing :: Listing dashboards visible to a user (REQ-SHARE-002)" }, "reachedOn": "Workspace page, Dashboards sidebar, Shared with you", "evidence": { @@ -1117,7 +1759,11 @@ "providerHow": "read-from-code", "feature": "dashboard-sharing", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "dash-tree", @@ -1131,15 +1777,19 @@ "dashy": "no", "built": { "state": "built", - "evidence": "src/components/Workspace/DashboardSwitcherSidebar.vue; src/views/Views.vue:191; lib/Controller/DashboardApiController.php", + "evidence": "src/components/Workspace/DashboardSwitcherSidebar.vue:265-276 (treeRows by parentUuid); src/views/Views.vue:31; src/modals/DashboardConfigModal.vue; lib/Controller/DashboardApiController.php", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-dashboard-tree-navigation" + "change": "openspec/changes/archive/2026-09-29-dashboard-tree-navigation", + "requirement": [ + "openspec/specs/dashboards :: Dashboards with a parent nest in the switcher (REQ-TREEUI-001)", + "openspec/specs/dashboards :: REQ-DASH-023 Dashboard hierarchy and parent relationship" + ] }, - "reachedOn": "nothing: the store action loadDashboardTree has no caller outside src/stores/", + "reachedOn": "Workspace page, dashboard switcher: a dashboard with a parent nests under it; the parent is set in the dashboard settings", "provider": "launchpad", "providerHow": "read-from-code", "feature": "dashboard-switcher", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/lib/Controller/DashboardController.php:52 single page, id-app-navigation null (:78) so no side navigation; searched apps/dashboard for parent, child, tree: none", @@ -1147,6 +1797,13 @@ "dashy": "source read at 4.7.0: src/utils/config/ConfigHelpers.js:14-24 pages is root-owned and stripped from sub-pages, and EditModeSaveMenu.vue:49-55 disables Edit Pages on a sub-page, so pages are one flat list", "workspace-365": "not checked: W365 spaces article for nested spaces", "microsoft-viva": "not checked: overview and edit pages for parent and child dashboards" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpWerkplek", + "LpDashboardInstellingen" + ] } }, { @@ -1162,7 +1819,9 @@ "built": { "state": "built", "evidence": "src/views/WorkspaceApp.vue:81", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/runtime-shell", + "requirement": "openspec/specs/runtime-shell :: Empty state (REQ-SHELL-005)" }, "reachedOn": "Workspace page with no dashboards", "provider": "launchpad", @@ -1176,6 +1835,10 @@ "dashy": "source read at 4.7.0: src/views/Home.vue:40-49 an empty config shows 'No Data Configured' (en.json:9); no offer or wizard to create a first dashboard; the Add Section launcher only appears once in edit mode (Home.vue:37)", "workspace-365": "not checked: W365 user guide for a first-dashboard prompt", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard 'You're asked to select your primary audience to generate a set of default dashboard cards' at first setup (editor, not end user) (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpEersteKeer" } }, { @@ -1190,15 +1853,16 @@ "dashy": "no", "built": { "state": "built", - "evidence": "src/modals/DashboardConfigModal.vue; src/components/Workspace/config/LanguagesTab.vue; src/components/Workspace/config/DetailsTab.vue; lib/Controller/DashboardApiController.php", + "evidence": "src/modals/DashboardConfigModal.vue; src/components/Workspace/config/LanguagesTab.vue:261 (listTranslations); src/components/Workspace/config/DetailsTab.vue; lib/Controller/DashboardApiController.php:297", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-dashboard-language-and-details-tabs" + "change": "openspec/changes/archive/2026-09-29-dashboard-language-and-details-tabs", + "requirement": "openspec/specs/dashboard-language-content :: The workspace page shows the reader's language (REQ-LANGUI-002)" }, - "reachedOn": "nothing: /api/dashboards/{uuid}/translations and /resolved have no caller in src/", + "reachedOn": "Dashboard settings, Languages tab; the workspace page shows the variant in the reader's language", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-language-content", - "featureConfidence": "medium", + "feature": "dashboard-switcher", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/src/DashboardApp.vue:236-258 greetings and the widget titles from each app (e.g. apps/files/lib/Dashboard/FavoriteWidget.php:50) are translated with the reader's own language; apps/dashboard/l10n holds 56 languages. Note: there is no author-written dashboard content to translate", @@ -1206,6 +1870,10 @@ "dashy": "source read at 4.7.0: 33 UI locales exist (src/assets/locales), but config text (section names, item titles, pageInfo) has no per-language variants: ConfigSchema.json:151-221 and :907-1115 single strings, additionalProperties false", "workspace-365": "not checked: W365 FAQ and spaces for translated space content", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-multilingual-dashboard translators make per-language copies; 'The Dashboard web part will display in the users preferred language' (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpIntranet" } }, { @@ -1222,13 +1890,17 @@ "state": "built", "evidence": "src/modals/DashboardConfigModal.vue; src/components/Workspace/config/LanguagesTab.vue; src/components/Workspace/config/DetailsTab.vue; lib/Controller/DashboardApiController.php", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-dashboard-language-and-details-tabs" + "change": "openspec/changes/archive/2026-09-29-dashboard-language-and-details-tabs", + "requirement": [ + "openspec/specs/dashboard-metadata-fields :: A dashboard owner fills in the details (REQ-MDUI-002)", + "openspec/specs/dashboard-metadata-fields :: An administrator defines detail fields (REQ-MDUI-001)" + ] }, "reachedOn": "nothing: the store actions fetchMetadataFields and updateDashboardMetadata have no component caller", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-metadata-fields", - "featureConfidence": "medium", + "feature": "dashboard-switcher", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/lib/Service/DashboardService.php:33-38 a dashboard is only a list of widget ids; searched apps/dashboard for owner, department, metadata: none", @@ -1236,6 +1908,73 @@ "dashy": "source read at 4.7.0: ConfigSchema.json:151-221 pageInfo allows only title, description, navLinks, footer, logo, favicon, color with additionalProperties false; pages entries only name, path, displayData (:29-45)", "workspace-365": "https://support.workspace365.net/en/articles/703640-using-and-organising-spaces-in-workspace-365 admins configure 'who owns the Shared space'; other facts such as department not described (read 2026-09-26)", "microsoft-viva": "not checked: create-dashboard for custom dashboard properties" + }, + "screen": { + "canvas": "design-system", + "board": "LpDashboardInstellingen" + } + }, + { + "id": "dash-starter-widgets", + "area": "dashboards", + "name": "A new personal dashboard starts with a useful set of widgets instead of an empty grid.", + "launchpad": "yes", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "built", + "evidence": "lib/Service/DashboardService.php:3085", + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/default-widget-bundle", + "requirement": "openspec/specs/default-widget-bundle :: REQ-DWB-001 Four widgets seeded on user-initiated create" + }, + "reachedOn": "Workspace page, after creating a new personal dashboard", + "source": "spec-round-2026-10-07", + "feature": "dashboard-switcher", + "screen": { + "canvas": "design-system", + "board": "LpEersteKeer" + } + }, + { + "id": "d-start-full-width", + "area": "dashboards", + "name": "An administrator can give the start page the full width, without the navigation panel.", + "launchpad": "yes", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "built", + "owner": "ConductionNL/launchpad", + "evidence": "src/App.vue renders no navigation panel on any route since #1528, so the admin option was retired; src/components/Workspace/DashboardMoreMenu.vue holds the destinations; live pass 17 Nov 2026: tests/e2e/start-page-without-navigation.spec.ts 3 passed on NC 34", + "change": "openspec/changes/archive/2026-11-17-start-page-without-navigation-panel", + "requirement": "openspec/specs/runtime-shell :: REQ-SHELL-009 Start page without navigation panel" + }, + "reachedOn": "Always on: the start page has the full width and shows its destinations in the More menu", + "evidence": { + "workspace-365": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "microsoft-viva": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "nextcloud-dashboard": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "homarr": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "dashy": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)" + }, + "provider": "launchpad", + "providerHow": "read-from-code", + "feature": "runtime-shell", + "featureConfidence": "medium", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": [ + "LpVandaag", + "LpBeheerAlgemeen" + ] } }, { @@ -1251,9 +1990,15 @@ "built": { "state": "built", "evidence": "src/modals/TileEditor.vue:71; src/modals/TileEditor.vue:111", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/tiles", + "requirement": [ + "openspec/specs/tiles :: REQ-TILE-PLACEMENT Inline-content placement model — promoted to canonical", + "openspec/specs/tiles :: Tile Link Navigation (REQ-TILE-008)", + "openspec/specs/tiles :: Tile Styling (REQ-TILE-009)" + ] }, - "reachedOn": "Workspace page, dashboard menu, Add custom widget, tile editor", + "reachedOn": "Workspace page, dashboard menu, Add widget, Custom widget, tile editor", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/483000-shortcut-tile 'open an external website directly', 'Choose an icon' and a custom colour (read 2026-09-26)", "homarr": "source read at v1.77.2: packages/db/schema/sqlite.ts:423 app with name, iconUrl, href; packages/widgets/src/app/index.ts:23 app tile with open-in-new-tab; colour through board icon colour (sqlite.ts:284, en.json:4404) and per item border colour (packages/validation/src/shared.ts:19)", @@ -1265,7 +2010,14 @@ "providerHow": "read-from-code", "feature": "tiles", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": [ + "LpWerkplek", + "LpTegelBewerken" + ] + } }, { "id": "tile-health", @@ -1280,7 +2032,12 @@ "built": { "state": "built", "evidence": "src/modals/TileEditor.vue:123; lib/Service/HealthPingService.php:11", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-23-service-health-ping", + "requirement": [ + "openspec/specs/service-health-ping :: REQ-HPING-004 Render an accessible health badge on the tile", + "openspec/specs/service-health-ping :: REQ-HPING-002 Ping the service server-side and classify the result" + ] }, "reachedOn": "Workspace page, tile badge; switched on in the tile editor. Only hosts in healthping_allowed_hosts are pinged, set with occ", "evidence": { @@ -1294,7 +2051,14 @@ "providerHow": "read-from-code", "feature": "tiles", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": [ + "LpWerkplek", + "LpTegelBewerken" + ] + } }, { "id": "tile-filter", @@ -1309,7 +2073,9 @@ "built": { "state": "built", "evidence": "src/components/Widgets/Renderers/SearchWidget.vue:157", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-23-tile-quick-search", + "requirement": "openspec/specs/tile-quick-search :: REQ-QSEARCH-002 Filter the current dashboard's tiles live" }, "reachedOn": "Workspace page, Search widget", "evidence": { @@ -1323,7 +2089,11 @@ "providerHow": "read-from-code", "feature": "tiles", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "tile-web-search", @@ -1338,7 +2108,9 @@ "built": { "state": "built", "evidence": "src/components/Widgets/Renderers/SearchWidgetForm.vue:41", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-08-20-tile-search-widget", + "requirement": "openspec/specs/tile-quick-search :: REQ-QSEARCH-004 Route a no-match query to a configured fallback" }, "reachedOn": "Workspace page, Search widget, falls back to a configured https search template or Nextcloud unified search", "evidence": { @@ -1351,8 +2123,12 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "tiles", - "featureConfidence": "medium", - "origin": "own-code" + "featureConfidence": "high", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "tile-bookmarks", @@ -1367,13 +2143,18 @@ "built": { "state": "built", "evidence": "lib/widget-types.json:24; lib/widget-types.json:31; package.json:38", - "owner": "ConductionNL/nextcloud-vue" + "owner": "ConductionNL/nextcloud-vue", + "change": "openspec/changes/archive/2026-05-03-links-widget", + "requirement": [ + "openspec/specs/links-widget :: REQ-LNKS-002 Placement configuration schema", + "openspec/specs/links-widget :: REQ-LNKS-008 Edit form with drag-to-reorder" + ] }, "reachedOn": "Workspace page, Add widget, Links or Quick links", "provider": "nextcloud-vue", "providerHow": "read-from-code", "feature": "tiles", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard/src and lib for bookmark, link list: none; the Bookmarks app is not in core/shipped.json", @@ -1381,6 +2162,10 @@ "dashy": "source read at 4.7.0: a section is a named group of link items (src/components/LinkItems/Section.vue:22-58); sub-item groups via ConfigSchema.json:1416 subItems (SubItemGroup.vue)", "workspace-365": "https://support.workspace365.net/en/articles/175363-full-guide-for-user Documents tile offers 'Bookmarks' and tiles can be grouped in named tile groups; a dedicated grouped-link list is not described (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/available-dashboard-cards Quick links card 'Provide list of relevant links or files', up to 20 links; https://support.microsoft.com/office/3da30f39-684a-4bde-bb81-2e1407d59b52 users add their own Quick Links card (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" } }, { @@ -1395,15 +2180,16 @@ "dashy": "no", "built": { "state": "built", - "evidence": "src/components/admin/TileClickReport.vue; lib/Service/TileAnalyticsService.php", + "evidence": "src/components/admin/tabs/VersioningAuditTab.vue:10 (AdminAnalytics); src/components/admin/AdminAnalytics.vue:130 (TileClickReport); src/components/admin/TileClickReport.vue; lib/Service/TileAnalyticsService.php", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-launcher-tile-click-report" + "change": "openspec/changes/archive/2026-09-29-launcher-tile-click-report", + "requirement": "openspec/specs/dashboard-view-analytics :: An administrator sees the most clicked tiles (REQ-TILEUI-001)" }, - "reachedOn": "clicks are recorded from the Workspace page; nothing shows them: getAnalyticsTopTiles and the tile CSV export have no caller in src/", + "reachedOn": "Admin settings, Versioning & Audit tab: the tile click report", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "prometheus-metrics", - "featureConfidence": "low", + "feature": "dashboard-view-analytics", + "featureConfidence": "medium", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for click, track, count, analytics: none; the page records nothing but the layout (apps/dashboard/lib/Controller/DashboardApiController.php:202-206)", @@ -1411,22 +2197,29 @@ "dashy": "source read at 4.7.0: src/mixins/ItemMixin.js:385-387 click counts are kept only in each browser's localStorage for sorting; searched services for analytics, track, clicks: nothing is sent to the server or reported", "workspace-365": "https://support.workspace365.net/en/articles/175636-analytics-of-a-workspace-365-environment 'Apps: usage per app'; not broken down per space (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/sharepoint-app-in-teams-analytics 'Engaged users by dashboard card ... how often each user engages with a card', per experience (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerAnalyse" } }, { "id": "tile-most-used", "area": "launcher", "name": "The apps you use most move to the front on their own.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "partial", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "yes", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-tile-sorting" + "change": "openspec/changes/archive/2026-11-17-launcher-tile-sorting", + "requirement": "openspec/specs/container-widget :: Most used and last used read the viewer's own browser (REQ-TSO-002)", + "evidence": "src/utils/tileSort.js:93; src/components/Widgets/Renderers/ContainerWidget.vue:162; live pass 17 Nov 2026: tests/e2e/container-tile-sorting.spec.ts 2 passed on NC 34", + "readOn": "2026-11-17" }, "reachedOn": "nothing", "evidence": { @@ -1438,25 +2231,32 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "app-catalogue-and-launch", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/launcher-tile-sorting (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/launcher-tile-sorting (openspec pass). Built since and archived 2026-11-17; the search above is from before that.", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "tile-legacy-apps", "area": "launcher", "name": "Start an old Windows program or a virtual desktop from a tile, signed in already.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "unknown", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "lib/Controller/TileLaunchController.php:82 (GET /api/tiles/{placementId}/rdp, view check, .rdp file from checked fields); lib/Service/TileLinkValidator.php:128; gateway mode opens its https address (src/utils/tileLaunch.js)", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-tile-launch-types" + "change": "openspec/changes/archive/2026-11-19-launcher-tile-launch-types", + "requirement": "openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles :: A tile can start a remote desktop or a published program (REQ-TLT-002)" }, - "reachedOn": "nothing", + "reachedOn": "Workspace page (/apps/launchpad/), Edit dashboard, a tile's editor: Opens > Remote desktop (web gateway or RDP file)", "evidence": { "workspace-365": "https://support.workspace365.net/en/collections/791485-live-tile-integrations Citrix 'Configure seamless Single Sign-on with Citrix', Clientless RDP, Azure Virtual Desktop and Omnissa Horizon articles (read 2026-09-26)", "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for rdp, citrix, vdi, remote desktop: none, and no such app is in core/shipped.json", @@ -1466,25 +2266,32 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "app-catalogue-and-launch", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/launcher-tile-launch-types (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/archive/2026-11-19-launcher-tile-launch-types (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpTegelBewerken" + } }, { "id": "tile-local-apps", "area": "launcher", "name": "Start a program installed on your own computer from the dashboard.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "unknown", "nextcloud-dashboard": "no", "homarr": "partial", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "lib/Service/TileLinkValidator.php:108 (program scheme on the admin list, never a forbidden one); src/components/TileWidget.vue:175 (follows the scheme address, hint after a click)", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-tile-launch-types" + "change": "openspec/changes/archive/2026-11-19-launcher-tile-launch-types", + "requirement": "openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles :: A tile can start a program on the user's computer (REQ-TLT-001)" }, - "reachedOn": "nothing", + "reachedOn": "Workspace page (/apps/launchpad/), Edit dashboard, a tile's editor: Opens > Program on this computer; the schemes are allowed on the LaunchPad admin page, Algemeen > Program and sign-on tiles", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175583-launching-local-apps-with-the-app-launcher 'Launching local apps with the App Launcher' (plus Mac and registry variants) (read 2026-09-26)", "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for protocol handler, launch, local app: none", @@ -1494,25 +2301,32 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "app-catalogue-and-launch", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/launcher-tile-launch-types (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/archive/2026-11-19-launcher-tile-launch-types (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpTegelBewerken" + } }, { "id": "tile-sso-app", "area": "launcher", "name": "Add a tile that signs you straight into a company app through single sign-on.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "partial", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "lib/Service/TileLinkValidator.php:108 (sso address resolved on the server from the admin template and the URL-encoded app id); src/modals/TileEditor.vue:200 (template picker, no address field)", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-tile-launch-types" + "change": "openspec/changes/archive/2026-11-19-launcher-tile-launch-types", + "requirement": "openspec/changes/archive/2026-11-19-launcher-tile-launch-types/specs/tiles :: A tile can start single sign-on into a company app (REQ-TLT-003)" }, - "reachedOn": "nothing: a tile opens its URL; any sign-on is the target app and identity provider, not a hand-off from the tile", + "reachedOn": "Workspace page (/apps/launchpad/), Edit dashboard, a tile's editor: Opens > Single sign-on app; templates on the LaunchPad admin page, Algemeen > Program and sign-on tiles", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175373-add-sso-apps-with-microsoft-entra-id-helloid-or-securelogin 'Add SSO apps with Microsoft Entra ID, HelloID or SecureLogin' (read 2026-09-26)", "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for sso, saml, oidc, tile: none; no link tiles exist on the page (apps/dashboard/src/DashboardApp.vue:17-54)", @@ -1522,25 +2336,35 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "app-catalogue-and-launch", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/launcher-tile-launch-types (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/archive/2026-11-19-launcher-tile-launch-types (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpTegelBewerken" + } }, { "id": "tile-catalogue", "area": "launcher", "name": "Browse a catalogue of approved apps and ask IT for one that is missing.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "partial", "nextcloud-dashboard": "no", "homarr": "partial", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "src/modals/WidgetPickerModal.vue:38 'From the app catalogue' section in the add flow, filled from GET /api/catalogue; lib/Service/CatalogueService.php:152 listFor() returns only the entries the caller's groups may see; lib/Service/CatalogueService.php:254 request() stores the request, notifies administrators and the manager group, at most 10 open; src/components/admin/tabs/AppCatalogueTab.vue:33 admin App catalogue tab: open requests with approve and decline, entries with group picker", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-app-catalogue" + "change": "openspec/changes/archive/2026-11-19-launcher-app-catalogue", + "requirement": [ + "openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue :: Users add catalogue apps as tiles from the add flow (REQ-ACAT-002)", + "openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue :: Users can ask for a missing app (REQ-ACAT-003)" + ] }, - "reachedOn": "nothing", + "reachedOn": "Workspace page (/apps/launchpad/), Add in edit mode, section 'From the app catalogue'; admin settings, LaunchPad, tab App catalogue", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175398-understand-and-manage-user-permissions 'Request apps in the app store'; https://portal.productboard.com/iqfsnhkpzih6grzjwagif2ek/tabs/3-launched launched 'Request/Approve application from App Store' (read 2026-09-26)", "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/src/DashboardApp.vue:113 only admins see 'Get more widgets from the App Store'; searched apps/dashboard for request, catalogue: no way for an employee to browse approved apps or ask for one", @@ -1550,23 +2374,30 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "app-catalogue-and-launch", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/launcher-app-catalogue (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/archive/2026-11-19-launcher-app-catalogue (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpTegelToevoegen" + } }, { "id": "tile-discover-containers", "area": "launcher", "name": "Turn a running service on your server into a tile in one click.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "unknown", "microsoft-viva": "unknown", "nextcloud-dashboard": "no", "homarr": "yes", "dashy": "no", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-discover-server-services" + "change": "openspec/changes/archive/2026-11-19-launcher-discover-server-services", + "requirement": "openspec/changes/archive/2026-11-19-launcher-discover-server-services/specs/tiles :: One click turns a discovered app into a tile (REQ-DISC-002)", + "evidence": "lib/Service/ServiceDiscoveryService.php:54 discover() lists the server's apps from INavigationManager::getAll('link') without LaunchPad; appinfo/routes.php:380 GET /api/tiles/discover; src/modals/WidgetPickerModal.vue:130 the 'Discovered on this server' section and :151 the 'On this dashboard' mark. Tests: tests/Unit/Service/ServiceDiscoveryServiceTest.php, src/modals/__tests__/WidgetPickerModal.discovered.spec.js, tests/e2e/discover-server-services.spec.ts (passed live 19 Nov 2026 with Deck 1.18.6)." }, "reachedOn": "nothing", "evidence": { @@ -1578,8 +2409,13 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "app-catalogue-and-launch", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/launcher-discover-server-services (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/archive/2026-11-19-launcher-discover-server-services (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpTegelToevoegen" + } }, { "id": "tile-org-nav", @@ -1594,12 +2430,18 @@ "built": { "state": "built", "evidence": "src/views/WorkspaceApp.vue:20; lib/Service/OrgNavigationService.php:204", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-navigation-editor-org", + "spec": "openspec/specs/navigation-editor-org", + "requirement": [ + "openspec/specs/navigation-editor-org :: REQ-ONAV-005 Vue panel rendering", + "openspec/specs/navigation-editor-org :: REQ-ONAV-004 Global position setting" + ] }, "reachedOn": "Workspace page, navigation panel; edited on Admin settings, Organisation navigation tab", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "navigation-editor-org", + "feature": "organisation-navigation", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -1608,6 +2450,13 @@ "dashy": "source read at 4.7.0: ConfigSchema.json:164-198 pageInfo.navLinks (up to 6) shown in the header by src/components/PageStrcture/Nav.vue:14-31 beside the page links; root pageInfo is merged into every sub-page (src/store.js:161)", "workspace-365": "https://support.workspace365.net/en/articles/175363-full-guide-for-user 'Through the navigation menu on the left side of you digital workplace, navigate easily'; the menu lists spaces and apps rather than curated org links (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/use-audience-targeting-sharepoint-app-in-teams 'Resources are the navigation links that display beneath the dashboard', audience targetable (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpWerkplek", + "LpBeheerNavigatie" + ] } }, { @@ -1623,12 +2472,17 @@ "built": { "state": "built", "evidence": "lib/widget-types.json:37; package.json:38", - "owner": "ConductionNL/nextcloud-vue" + "owner": "ConductionNL/nextcloud-vue", + "change": "openspec/changes/archive/2026-06-14-text-display-widget", + "requirement": [ + "openspec/specs/text-display-widget :: REQ-TXMD-002 CommonMark-compliant markdown parsing", + "openspec/specs/text-display-widget :: REQ-TBLE-009 Render HTML Table with Cell Merging" + ] }, "reachedOn": "Workspace page, Add widget, Text", "provider": "nextcloud-vue", "providerHow": "read-from-code", - "feature": "text-display-widget", + "feature": "content-widgets", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -1637,6 +2491,10 @@ "dashy": "source read at 4.7.0: src/components/Widgets/EmbedWidget.vue:14-30 embed widget renders raw HTML, CSS and script from options (or htmlSrc); formatted text is possible only as hand-written HTML, there is no text editor", "workspace-365": "https://support.workspace365.net/en/articles/480271-text-editor-text-content 'bold, italic, lists, tables, and hyperlinks' as a tile or a full space; headings not mentioned (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/use-card-designer templates 'Heading' and 'Description'; richer layout only by Adaptive Card JSON in a quick view (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpIntranet" } }, { @@ -1652,13 +2510,15 @@ "built": { "state": "built", "evidence": "lib/widget-types.json:21; lib/Controller/ResourceController.php:63", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-image-widget", + "requirement": "openspec/specs/image-widget :: REQ-IMG-005 Add/edit form" }, "reachedOn": "Workspace page, Add widget, Image", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "image-widget", - "featureConfidence": "medium", + "feature": "content-widgets", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for image widget, upload: none; the only image on the page is the theming background (apps/dashboard/src/DashboardApp.vue:569-575)", @@ -1666,6 +2526,13 @@ "dashy": "source read at 4.7.0: src/components/Widgets/ImageWidget.vue:18-43 image widget shows an image from imagePath with optional size and refresh; searched src for upload and type=file: none, so linked only", "workspace-365": "not checked: W365 tile articles for an image tile", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/use-card-designer 'Image: Create a card with a heading and image', upload or pick from site or web (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpIntranet", + "LpWidgetInstellen" + ] } }, { @@ -1681,7 +2548,9 @@ "built": { "state": "built", "evidence": "lib/widget-types.json:39; package.json:38", - "owner": "ConductionNL/nextcloud-vue" + "owner": "ConductionNL/nextcloud-vue", + "change": "openspec/changes/archive/2026-05-03-video-widget", + "requirement": "openspec/specs/video-widget :: REQ-VID-003 Support Multiple Video Source Types" }, "reachedOn": "Workspace page, Add widget, Video", "evidence": { @@ -1693,9 +2562,13 @@ }, "provider": "nextcloud-vue", "providerHow": "read-from-code", - "feature": "video-widget", + "feature": "content-widgets", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "w-embed", @@ -1710,7 +2583,9 @@ "built": { "state": "built", "evidence": "lib/Service/IframeService.php:9; src/constants/widgetRegistry.js:206", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-23-iframe-embed-widget", + "requirement": "openspec/specs/iframe-embed-widget :: REQ-IFRAME-002 Admin allow-list of embeddable hosts, fail-closed" }, "reachedOn": "Workspace page, Add widget, Embedded page; the allow-list is an app config value", "evidence": { @@ -1724,7 +2599,11 @@ "providerHow": "read-from-code", "feature": "iframe-embed-widget", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "w-news", @@ -1739,7 +2618,9 @@ "built": { "state": "built", "evidence": "lib/Service/NewsWidgetService.php:133; src/constants/widgetRegistry.js:244", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-news-widget", + "requirement": "openspec/specs/news-widget :: REQ-NEWS-003 Fetch and Merge Feed Items" }, "reachedOn": "Workspace page, Add widget, News", "evidence": { @@ -1751,9 +2632,13 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "news-widget", + "feature": "content-widgets", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "w-weather", @@ -1768,7 +2653,9 @@ "built": { "state": "built", "evidence": "lib/Service/WeatherService.php:208; src/constants/widgetRegistry.js:171", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-23-clock-weather-widgets", + "requirement": "openspec/specs/clock-weather-widgets :: REQ-WEATHER-002 Resolve provider, fetch, and cache" }, "reachedOn": "Workspace page, Add widget, Weather", "evidence": { @@ -1780,9 +2667,13 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "clock-weather-widgets", + "feature": "content-widgets", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "w-clock", @@ -1797,7 +2688,9 @@ "built": { "state": "built", "evidence": "src/constants/widgetRegistry.js:156", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-23-clock-weather-widgets", + "requirement": "openspec/specs/clock-weather-widgets :: REQ-CLOCK-003 Render locale-aware clock, WCAG AA" }, "reachedOn": "Workspace page, Add widget, Clock", "evidence": { @@ -1809,9 +2702,13 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "clock-weather-widgets", + "feature": "content-widgets", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "w-calendar", @@ -1826,7 +2723,12 @@ "built": { "state": "built", "evidence": "lib/Service/CalendarWidgetService.php:77; lib/widget-types.json:11", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-calendar-widget", + "requirement": [ + "openspec/specs/calendar-widget :: REQ-CAL-002 Placement configuration", + "openspec/specs/calendar-widget :: REQ-CAL-008 Render modes" + ] }, "reachedOn": "Workspace page, Add widget, Calendar", "evidence": { @@ -1838,9 +2740,17 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "calendar-widget", + "feature": "content-widgets", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": [ + "LpVandaag", + "LpWerkplek", + "LpWidgetInstellen" + ] + } }, { "id": "w-files", @@ -1855,7 +2765,12 @@ "built": { "state": "built", "evidence": "lib/Controller/FilesWidgetController.php:179; lib/widget-types.json:17", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-files-widget", + "requirement": [ + "openspec/specs/files-widget :: REQ-FLS-005 Breadcrumb navigation and folder traversal", + "openspec/specs/files-widget :: REQ-FLS-007 Upload capability" + ] }, "reachedOn": "Workspace page, Add widget, Files", "evidence": { @@ -1867,9 +2782,13 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "files-widget", + "feature": "content-widgets", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "w-people", @@ -1884,7 +2803,13 @@ "built": { "state": "built", "evidence": "lib/Service/PeopleWidgetService.php:8; lib/widget-types.json:30", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-people-widget", + "spec": "openspec/specs/people-widget", + "requirement": [ + "openspec/specs/people-widget :: Widget registration via dashboard API (REQ-PPL-001)", + "openspec/specs/people-widget :: Three layout modes (REQ-PPL-008)" + ] }, "reachedOn": "Workspace page, Add widget, People", "evidence": { @@ -1898,7 +2823,11 @@ "providerHow": "read-from-code", "feature": "people-widget", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "w-birthdays", @@ -1913,7 +2842,9 @@ "built": { "state": "built", "evidence": "lib/Service/PeopleWidgetService.php:410", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/people-widget", + "requirement": "openspec/specs/people-widget :: Birthday field (REQ-PPL-005)" }, "reachedOn": "Workspace page, People widget", "evidence": { @@ -1926,8 +2857,12 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "people-widget", - "featureConfidence": "medium", - "origin": "own-code" + "featureConfidence": "high", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "w-structure", @@ -1942,12 +2877,22 @@ "built": { "state": "built", "evidence": "lib/widget-types.json:19; lib/widget-types.json:16; package.json:38", - "owner": "ConductionNL/nextcloud-vue" + "owner": "ConductionNL/nextcloud-vue", + "change": [ + "openspec/changes/archive/2026-05-03-header-widget", + "openspec/changes/archive/2026-06-14-label-widget", + "openspec/changes/archive/2026-05-03-divider-widget" + ], + "requirement": [ + "openspec/specs/header-widget :: REQ-HDR-008 Text rendering and styling", + "openspec/specs/label-widget :: REQ-LBL-002 Default-styled as a centred bold heading", + "openspec/specs/divider-widget :: REQ-DIV-003 Render Line Divider" + ] }, "reachedOn": "Workspace page, Add widget, Header, Label or Divider", "provider": "nextcloud-vue", "providerHow": "read-from-code", - "feature": "header-widget", + "feature": "content-widgets", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -1956,6 +2901,10 @@ "dashy": "source read at 4.7.0: every section has a name and icon shown as a heading (src/components/LinkItems/Section.vue:3-4 via Collapsable), sections can be collapsed; there is no free label or divider widget", "workspace-365": "https://support.workspace365.net/en/articles/175363-full-guide-for-user 'Change the name of Personal tile group by clicking on the title'; group titles act as headings, no divider (read 2026-09-26)", "microsoft-viva": "not checked: available-dashboard-cards for heading or divider cards" + }, + "screen": { + "canvas": "design-system", + "board": "LpIntranet" } }, { @@ -1971,12 +2920,17 @@ "built": { "state": "built", "evidence": "src/constants/widgetRegistry.js:14; lib/Controller/FileController.php:87", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-link-button-widget", + "requirement": [ + "openspec/specs/link-button-widget :: REQ-LBN-003 createFile flow", + "openspec/specs/link-button-widget :: REQ-LBN-005 Internal action registry" + ] }, "reachedOn": "Workspace page, Add widget, Link button", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "link-button-widget", + "feature": "content-widgets", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -1985,6 +2939,10 @@ "dashy": "source read at 4.7.0: items only open or copy a URL (ConfigSchema.json:1293-1307); searched src for webhook, action button: none; open request #383 'Action Buttons to execute web hooks'", "workspace-365": "https://support.workspace365.net/en/articles/483000-shortcut-tile 'call, send an email, or open an external website directly'; https://support.workspace365.net/en/articles/175363-full-guide-for-user email tile 'compose new emails from the live tile' (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/available-dashboard-cards Assigned tasks card 'Add tasks' button; Approvals 'create new approvals'; https://learn.microsoft.com/en-us/sharepoint/homesites/use-card-designer primary and secondary buttons (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" } }, { @@ -2000,7 +2958,12 @@ "built": { "state": "built", "evidence": "lib/Service/LiveTileService.php:22; src/constants/widgetRegistry.js:184", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-23-live-data-tile-widget", + "requirement": [ + "openspec/specs/live-data-tile-widget :: REQ-LIVETILE-003 Resolve and cache the value server-side", + "openspec/specs/live-data-tile-widget :: REQ-LIVETILE-002 Configure the tile source" + ] }, "reachedOn": "Workspace page, Add widget, Live tile; only hosts in livetile_allowed_hosts are fetched, set with occ", "evidence": { @@ -2012,9 +2975,16 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "live-data-tile-widget", + "feature": "runtime-or-consumption", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": [ + "LpManagement", + "LpWidgetInstellen" + ] + } }, { "id": "w-charts", @@ -2028,14 +2998,21 @@ "dashy": "partial", "built": { "state": "built", - "evidence": "lib/widget-types.json:12; src/services/graphqlClient.js:16", - "owner": "ConductionNL/openregister" + "evidence": "src/constants/widgetRegistry.js:116-120 routes the chart and stats-block types to src/components/Widgets/Renderers/ChartHost.vue and StatsBlockHost.vue, thin adapters onto nextcloud-vue's CnChartWidget and CnStatsBlockWidget, which fetch their figures from an OpenRegister dataSource; stat, gauge, delta and table are nextcloud-vue registry types LaunchPad passes through unchanged (lib/widget-types.json:12-38). Renderers, configuration forms and data are nextcloud-vue's and OpenRegister's (nextcloud-vue src/components/CnWidgetGrid/registerDashboardWidgets.js:81-127, main 0f1c0ffbb); src/services/graphqlClient.js, cited before, serves the spend-analytics widget, not these", + "owner": "ConductionNL/openregister", + "spec": [ + "openspec/specs/widgets", + "nextcloud-vue/widget-renderer", + "openregister/aggregation-api" + ], + "readOn": "2026-10-07", + "requirement": "openspec/specs/widgets :: Widget Rendering Architecture (REQ-WDG-009)" }, "reachedOn": "Workspace page, Add widget, Chart, Stat or Table, only with OpenRegister installed", "provider": "openregister", "providerHow": "read-from-code", "feature": "kpi-cards", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "note": "The widgets read OpenRegister over GraphQL. LaunchPad is OR-free by ADR, so without OpenRegister these widgets have no data source; this reading did not run one against a live register.", "evidence": { @@ -2044,6 +3021,10 @@ "dashy": "source read at 4.7.0: no store of your own data; custom-api (CustomApi.vue:1-14, list or block display :58-59) shows counts and values from any JSON endpoint but no charts or tables; charts exist only inside fixed widgets such as crypto-price-chart (src/components/Charts)", "workspace-365": "not checked: W365 docs for charts over own data (Power BI aside)", "microsoft-viva": "not checked: available-dashboard-cards for chart cards" + }, + "screen": { + "canvas": "design-system", + "board": "LpManagement" } }, { @@ -2059,7 +3040,10 @@ "built": { "state": "built", "evidence": "lib/Service/IframeService.php:9", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-23-iframe-embed-widget", + "spec": "openspec/specs/iframe-embed-widget", + "requirement": "openspec/specs/iframe-embed-widget :: REQ-IFRAME-001 Register iframe-embed widget" }, "reachedOn": "Workspace page, Embedded page widget, when the report host is on the allow-list", "evidence": { @@ -2072,9 +3056,13 @@ "provider": "launchpad", "providerHow": "research-then-code", "feature": "iframe-embed-widget", - "featureConfidence": "low", + "featureConfidence": "high", "origin": "competitor", - "note": "Only as a generic embedded page; no report picker and no row-level security hand-off." + "note": "Only as a generic embedded page; no report picker and no row-level security hand-off.", + "screen": { + "canvas": "design-system", + "board": "LpManagement" + } }, { "id": "w-spend", @@ -2089,13 +3077,15 @@ "built": { "state": "built", "evidence": "src/services/spendAnalytics.js:10; lib/widget-types.json:33", - "owner": "ConductionNL/openregister" + "owner": "ConductionNL/openregister", + "change": "openspec/changes/archive/2026-06-14-add-launchpad-discovered-and-spend-analytics", + "requirement": "openspec/specs/launchpad-spend-analytics-widget :: REQ-SAW-004: The widget SHALL fetch spend data via runtime GraphQL against financeq + procest" }, "reachedOn": "Workspace page, Add widget, Spend analytics, only with those apps installed", "provider": "openregister", "providerHow": "read-from-code", "feature": "launchpad-spend-analytics-widget", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "note": "Marked beta in openspec/features.overlay.json; depends on sibling apps holding the data in OpenRegister.", "evidence": { @@ -2104,6 +3094,84 @@ "dashy": "source read at 4.7.0: searched src/components/Widgets for finance, spend, budget, invoice: only crypto and wallet balance widgets (WalletBalance.vue), nothing over finance or case apps", "workspace-365": "not checked: W365 integration list for finance figures", "microsoft-viva": "not checked: available-dashboard-cards for finance cards" + }, + "screen": { + "canvas": "design-system", + "board": "LpManagement" + } + }, + { + "id": "w-scheduled-export", + "area": "widgets", + "name": "Have a dashboard sent as a PDF or file on a schedule, such as every Monday at nine.", + "launchpad": "no", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "specified", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/scheduled-exports", + "requirement": [ + "openspec/changes/scheduled-exports/specs/scheduled-exports :: REQ-SCH-002 Background runner fires schedules without an active browser session", + "openspec/changes/scheduled-exports/specs/scheduled-exports :: REQ-SCH-003 Multi-format render from a single fire" + ] + }, + "reachedOn": "nothing yet", + "evidence": { + "workspace-365": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "microsoft-viva": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "nextcloud-dashboard": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "homarr": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "dashy": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)" + }, + "provider": "launchpad", + "providerHow": "specified", + "feature": "scheduled-exports", + "featureConfidence": "medium", + "origin": "roadmap", + "screen": { + "canvas": "design-system", + "board": "LpDashboardInstellingen" + } + }, + { + "id": "w-cross-filter", + "area": "widgets", + "name": "Click a bar or a row in one widget to filter the other widgets on the dashboard.", + "launchpad": "no", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "specified", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter", + "requirement": [ + "openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter :: REQ-CWF-001 Widget click publishes to the filter bus", + "openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter :: REQ-CWF-002 All consuming widgets re-render on filter change" + ] + }, + "reachedOn": "nothing yet", + "evidence": { + "workspace-365": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "microsoft-viva": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "nextcloud-dashboard": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "homarr": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "dashy": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)" + }, + "provider": "launchpad", + "providerHow": "specified", + "feature": "cross-widget-filter", + "featureConfidence": "medium", + "origin": "roadmap", + "screen": { + "canvas": "design-system", + "board": "LpManagement" } }, { @@ -2117,10 +3185,11 @@ "homarr": "yes", "dashy": "partial", "built": { - "state": "specified", - "evidence": "lib/Service/LiveTileService.php:22", + "state": "built", + "evidence": "lib/Service/LiveTileListMapper.php:51 (list, table and key-value displays over up to six mapped fields, mapped on the server for both source modes, lib/Service/LiveTileService.php:260); src/components/Widgets/Renderers/LiveTileWidget.vue:49; tests/e2e/live-tile-lists.spec.ts", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/integrations-live-tile-lists" + "change": "openspec/changes/archive/2026-11-19-integrations-live-tile-lists", + "requirement": "openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget :: A live tile can show a list, a table or key-value pairs (REQ-LTC-001)" }, "reachedOn": "Workspace page, Live tile widget pointed at a JSON address", "evidence": { @@ -2132,10 +3201,14 @@ }, "provider": "launchpad", "providerHow": "research-then-code", - "feature": "live-data-tile-widget", - "featureConfidence": "low", + "feature": "runtime-or-consumption", + "featureConfidence": "high", "origin": "competitor", - "note": "A live tile reads one value from a URL. There is no connector, authentication handling or data mapping as the competitor describes. Corrected 2026-09-27 (openspec pass): a connector mode exists; it calls Integriq's DashboardDatasourceService::resolve(), which applies the source's stored authentication (lib/Service/LiveTileService.php:380). What is missing is mapping more than one field and choosing how to show it. Specified 2026-09-27 in openspec/changes/integrations-live-tile-lists (openspec pass)." + "note": "A live tile reads one value from a URL. There is no connector, authentication handling or data mapping as the competitor describes. Corrected 2026-09-27 (openspec pass): a connector mode exists; it calls Integriq's DashboardDatasourceService::resolve(), which applies the source's stored authentication (lib/Service/LiveTileService.php:380). What is missing is mapping more than one field and choosing how to show it. Specified 2026-09-27 in openspec/changes/archive/2026-11-19-integrations-live-tile-lists (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpWidgetInstellen" + } }, { "id": "int-itsm", @@ -2161,6 +3234,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "runtime-or-consumption", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (integrations). Reversible: reopen the row if demand appears." }, @@ -2188,6 +3262,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "runtime-or-consumption", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (integrations). Reversible: reopen the row if demand appears." }, @@ -2204,7 +3279,13 @@ "built": { "state": "built", "evidence": "src/constants/widgetRegistry.js:141", - "owner": "nextcloud/server" + "owner": "nextcloud/server", + "change": "openspec/changes/archive/2026-06-14-nc-dashboard-widget-proxy", + "requirement": [ + "openspec/specs/widgets :: nc-widget placement type (REQ-WDG-018)", + "openspec/specs/legacy-widget-bridge :: Mount a captured legacy widget into a DOM container (REQ-LWB-002)", + "openspec/specs/widgets :: Another app's widget shows that app's items for the viewer (REQ-WDG-030)" + ] }, "reachedOn": "Workspace page, Add widget, Nextcloud widget, the Mail app's widget, with Nextcloud Mail installed", "evidence": { @@ -2217,8 +3298,12 @@ "provider": "nextcloud", "providerHow": "read-from-code", "feature": "nc-dashboard-widget-proxy", - "featureConfidence": "medium", - "origin": "own-code" + "featureConfidence": "high", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "int-tasks", @@ -2233,7 +3318,13 @@ "built": { "state": "built", "evidence": "src/constants/widgetRegistry.js:141", - "owner": "nextcloud/server" + "owner": "nextcloud/server", + "change": "openspec/changes/archive/2026-06-14-nc-dashboard-widget-proxy", + "requirement": [ + "openspec/specs/widgets :: nc-widget placement type (REQ-WDG-018)", + "openspec/specs/legacy-widget-bridge :: Mount a captured legacy widget into a DOM container (REQ-LWB-002)", + "openspec/specs/widgets :: Another app's widget shows that app's items for the viewer (REQ-WDG-030)" + ] }, "reachedOn": "Workspace page, Add widget, Nextcloud widget, Deck's task widget, with Deck installed", "evidence": { @@ -2246,25 +3337,31 @@ "provider": "nextcloud", "providerHow": "read-from-code", "feature": "nc-dashboard-widget-proxy", - "featureConfidence": "medium", - "origin": "own-code" + "featureConfidence": "high", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpVandaag" + } }, { "id": "int-office-tiles", "area": "integrations", "name": "Get ready-made tiles for the office suite without setting each one up.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "yes", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "src/modals/WidgetPickerModal.vue:117", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/integrations-office-tiles" + "spec": "openspec/specs/office-tiles", + "requirement": "openspec/specs/office-tiles :: The add flow offers an office tile pack built from what the server has (REQ-OFT-001)" }, - "reachedOn": "nothing", + "reachedOn": "Workspace page (/apps/launchpad/), More > Add widget > Office tiles", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175363-full-guide-for-user ready tiles for documents, email, calendar and address book from Microsoft 365 (read 2026-09-26)", "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for office, document, new file: none; the shipped 'office' app is an overview page with its own navigation entry (nextcloud/office stable35 appinfo/info.xml), not dashboard tiles. This cell cites a separate nextcloud app repo at stable35, not the server clone at v35.0.1.", @@ -2274,8 +3371,13 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "runtime-or-consumption", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/integrations-office-tiles (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/integrations-office-tiles (openspec pass). Built and archived 2026-11-21; e2e office-tiles.spec.ts 2 of 2 against onlyoffice (#1451).", + "screen": { + "canvas": "design-system", + "board": "LpTegelToevoegen" + } }, { "id": "int-intranet-content", @@ -2288,10 +3390,11 @@ "homarr": "partial", "dashy": "partial", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "evidence": "lib/Service/NewsWidgetService.php:133; lib/Service/IframeService.php:9", - "change": "openspec/changes/integrations-live-tile-lists" + "evidence": "lib/Service/NewsWidgetService.php:133; lib/Service/IframeService.php:9; documents: the Latest documents preset, SharePoint and Confluence variants (src/components/Widgets/Renderers/LiveTileWidgetForm.vue:222) over a list live tile (lib/Service/LiveTileListMapper.php:51)", + "change": "openspec/changes/archive/2026-11-19-integrations-live-tile-lists", + "requirement": "openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget :: A preset shows another intranet's latest documents (REQ-LTC-004)" }, "reachedOn": "Workspace page, Add widget, News (the other intranet's RSS or Atom feed) or Embed (its page, when the host is allowed)", "evidence": { @@ -2303,8 +3406,13 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "runtime-or-consumption", "origin": "competitor", - "note": "Corrected 2026-09-27 (openspec pass): the news widget reads RSS and Atom feeds from any allowed host (lib/Service/NewsWidgetService.php:133) and the embed widget frames an allowed page (lib/Service/IframeService.php:9), the same half Homarr and Dashy are rated partial for; the other intranet's documents are missing. Specified 2026-09-27 in openspec/changes/integrations-live-tile-lists (openspec pass)." + "note": "Corrected 2026-09-27 (openspec pass): the news widget reads RSS and Atom feeds from any allowed host (lib/Service/NewsWidgetService.php:133) and the embed widget frames an allowed page (lib/Service/IframeService.php:9), the same half Homarr and Dashy are rated partial for; the other intranet's documents are missing. Specified 2026-09-27 in openspec/changes/archive/2026-11-19-integrations-live-tile-lists (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "int-connections-status", @@ -2317,15 +3425,18 @@ "homarr": "partial", "dashy": "no", "built": { - "state": "building", - "evidence": "lib/Settings/connections.json:14; src/manifest.d/connection-registry.json:23", - "owner": "ConductionNL/integriq" + "state": "built", + "evidence": "lib/Settings/connections.json:14; src/manifest.d/connection-registry.json:23; live pass 1 Nov 2026: tests/e2e/integrations-page.spec.ts 4 passed against an instance with launchpad and integriq", + "owner": "ConductionNL/integriq", + "change": "openspec/changes/archive/2026-11-12-adopt-connection-registry", + "readOn": "2026-11-01", + "requirement": "openspec/specs/app-connections :: REQ-LP-CONN-004 An admin reads the connections on an Integrations page" }, "reachedOn": "Integrations page (/apps/launchpad/settings/integrations), shown only when the integriq app is installed", "provider": "integriq", "providerHow": "read-from-code", "feature": "runtime-or-consumption", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "note": "LaunchPad declares its six connections; the list and its status are integriq app_connection objects, so without integriq nothing shows them. Set building 2026-09-27 (openspec pass, coordinator): the integriq lane covers it in ConductionNL/integriq openspec/changes/connection-registry.", "evidence": { @@ -2334,6 +3445,10 @@ "dashy": "source read at 4.7.0: each widget shows its own fetch error (WidgetBase.vue, ignoreErrors ConfigSchema.json:1511); searched src and services for connections overview, last success: no list of the outside sources the dashboard uses", "workspace-365": "not checked: W365 integration builder guide for a connection health overview", "microsoft-viva": "not checked: learn.microsoft.com dashboard pages for connection status" + }, + "screen": { + "canvas": "design-system", + "board": "LpManagement" } }, { @@ -2349,7 +3464,9 @@ "built": { "state": "built", "evidence": "lib/Service/RuleEvaluatorService.php:125; src/components/Widgets/WidgetContextMenu.vue:35", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/conditional-visibility", + "requirement": "openspec/specs/conditional-visibility :: Group-Based Rule Evaluation (REQ-VIS-005)" }, "reachedOn": "Workspace page, widget context menu, Visibility rules", "evidence": { @@ -2363,7 +3480,11 @@ "providerHow": "read-from-code", "feature": "conditional-visibility", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpZichtbaarheid" + } }, { "id": "t-hours", @@ -2378,7 +3499,9 @@ "built": { "state": "built", "evidence": "lib/Service/RuleEvaluatorService.php:170; src/components/Widgets/VisibilityRuleRow.vue:56", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/conditional-visibility", + "requirement": "openspec/specs/conditional-visibility :: Time-Based Rule Evaluation (REQ-VIS-006)" }, "reachedOn": "Workspace page, Visibility rules, time rule", "provider": "launchpad", @@ -2392,6 +3515,10 @@ "dashy": "source read at 4.7.0: src/utils/IsVisibleToUser.js:79-83 checks only users, guests, groups and roles; searched src for hour, weekday, schedule: none", "workspace-365": "not checked: W365 conditional access and app settings for time windows", "microsoft-viva": "not checked: audience targeting page for time-of-day rules" + }, + "screen": { + "canvas": "design-system", + "board": "LpZichtbaarheid" } }, { @@ -2407,7 +3534,9 @@ "built": { "state": "built", "evidence": "src/components/Widgets/VisibilityRuleRow.vue:111", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/conditional-visibility", + "requirement": "openspec/specs/conditional-visibility :: Date-Based Rule Evaluation (REQ-VIS-007)" }, "reachedOn": "Workspace page, Visibility rules, date rule", "provider": "launchpad", @@ -2421,6 +3550,10 @@ "dashy": "source read at 4.7.0: src/utils/IsVisibleToUser.js:79-83 has no date rule; searched src for startDate, endDate, expires in displayData: none", "workspace-365": "not checked: W365 tile settings for date windows (announcements have end dates, tiles not described)", "microsoft-viva": "https://learn.microsoft.com/en-us/viva/connections/announcements-viva-connections announcements (not cards) 'schedule a future send date' and an end date 'up to two weeks from posting' (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpZichtbaarheid" } }, { @@ -2436,7 +3569,9 @@ "built": { "state": "built", "evidence": "lib/Service/RuleEvaluatorService.php:238; lib/Service/UserAttributeResolver.php:36", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/conditional-visibility", + "requirement": "openspec/specs/conditional-visibility :: Attribute-Based Rule Evaluation (REQ-VIS-008)" }, "reachedOn": "Workspace page, Visibility rules, attribute rule", "evidence": { @@ -2450,7 +3585,11 @@ "providerHow": "read-from-code", "feature": "conditional-visibility", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpZichtbaarheid" + } }, { "id": "t-preview", @@ -2465,12 +3604,14 @@ "built": { "state": "built", "evidence": "lib/Controller/VisibilityPreviewController.php:102; src/components/Widgets/ConditionalVisibilityEditor.vue:240", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-23-conditional-visibility-editor", + "requirement": "openspec/specs/conditional-visibility-editor :: REQ-CVUI-004 Preview As Audience and Date" }, "reachedOn": "Workspace page, Visibility rules editor", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "conditional-visibility-editor", + "feature": "conditional-visibility", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -2479,6 +3620,10 @@ "dashy": "source read at 4.7.0: searched src for preview as, impersonate, view as: none; the only preview is of an edited config (en.json config-editor.preview-button)", "workspace-365": "not checked: W365 permission and space articles for preview-as-user", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/use-audience-targeting-sharepoint-app-in-teams 'Open the Select audiences to preview as drop-down list' (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpZichtbaarheid" } }, { @@ -2494,7 +3639,10 @@ "built": { "state": "built", "evidence": "src/components/admin/tabs/VersioningAuditTab.vue:8", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-refactor-launchpad-ia-alignment", + "spec": "openspec/specs/conditional-visibility", + "requirement": "openspec/specs/conditional-visibility :: Admin overview of widgets with visibility rules (REQ-VIS-012)" }, "reachedOn": "Admin settings, Versioning and audit tab", "provider": "launchpad", @@ -2508,6 +3656,10 @@ "dashy": "source read at 4.7.0: searched src/components for a list of visibility rules: none; rules live in each section's displayData in the YAML", "workspace-365": "not checked: W365 admin articles for an overview of targeted tiles ('permissions viewer' is about users and groups)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/use-audience-targeting-sharepoint-app-in-teams 'An icon appears on the card indicating audience targeting is applied'; no central overview (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerAnalyse" } }, { @@ -2523,7 +3675,12 @@ "built": { "state": "built", "evidence": "lib/Service/RoleFeaturePermissionService.php:612; src/components/admin/tabs/RolesPermissionsTab.vue:11", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/role-feature-permissions", + "requirement": [ + "openspec/specs/role-feature-permissions :: REQ-RFP-001: Feature presence visibility by role", + "openspec/specs/role-feature-permissions :: REQ-RFP-003: Role-based card library" + ] }, "reachedOn": "Admin settings, Roles and permissions tab", "provider": "launchpad", @@ -2537,6 +3694,13 @@ "dashy": "source read at 4.7.0: src/store.js:224-248 permissions are three booleans (write to disk, save locally, view config); nothing limits widget types per group", "workspace-365": "https://support.workspace365.net/en/articles/175398-understand-and-manage-user-permissions per-group permission 'Edit your own workplace, create personal tile groups and add tiles' (all or nothing, not per kind) (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/available-dashboard-cards partner cards need App Catalog Admin approval before they appear in the toolbox; tenant-wide, not per group (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpBeheerRollen", + "LpWidgetKiezen" + ] } }, { @@ -2552,7 +3716,9 @@ "built": { "state": "built", "evidence": "lib/Service/RoleFeaturePermissionService.php:694; src/components/admin/tabs/RolesPermissionsTab.vue:13", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/role-feature-permissions", + "requirement": "openspec/specs/role-feature-permissions :: REQ-RFP-002: Role-based default dashboard layout" }, "reachedOn": "Admin settings, Roles and permissions tab, layout defaults", "evidence": { @@ -2566,7 +3732,11 @@ "providerHow": "read-from-code", "feature": "admin-roles", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpBeheerRollen" + } }, { "id": "t-compulsory", @@ -2581,7 +3751,12 @@ "built": { "state": "built", "evidence": "lib/Service/PermissionService.php:254; src/dialogs/RoleLayoutDefaultEditorDialog.vue:89", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/permissions", + "requirement": [ + "openspec/specs/permissions :: Compulsory Widget Marking (REQ-PERM-004)", + "openspec/specs/permissions :: Permission Enforcement on API Level (REQ-PERM-006)" + ] }, "reachedOn": "Admin settings, Roles and permissions, layout default editor", "evidence": { @@ -2596,7 +3771,11 @@ "feature": "permissions", "featureConfidence": "high", "origin": "own-code", - "note": "The server refuses removal only on add-only dashboards; a user with full permission can remove a compulsory widget (PermissionService::canRemoveWidget returns true for full)." + "note": "The server refuses removal only on add-only dashboards; a user with full permission can remove a compulsory widget (PermissionService::canRemoveWidget returns true for full).", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "t-device", @@ -2622,6 +3801,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "conditional-visibility", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (targeting). Reversible: reopen the row if demand appears." }, @@ -2649,6 +3829,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "conditional-visibility", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (targeting). Reversible: reopen the row if demand appears." }, @@ -2665,12 +3846,18 @@ "built": { "state": "built", "evidence": "src/components/admin/tabs/SharingTab.vue:10; lib/Service/DashboardResolver.php:47", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-group-priority-order", + "spec": "openspec/specs/admin-settings", + "requirement": [ + "openspec/specs/admin-settings :: Group order setting (REQ-ASET-012)", + "openspec/specs/admin-templates :: Primary-group resolution for workspace routing (REQ-TMPL-012)" + ] }, "reachedOn": "Admin settings, Sharing tab, group order", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboards", + "feature": "admin-templates", "featureConfidence": "medium", "origin": "own-code", "evidence": { @@ -2679,6 +3866,10 @@ "dashy": "source read at 4.7.0: there is one shared config, not one per group; searched src for priority, precedence: none", "workspace-365": "https://support.workspace365.net/en/articles/175398-understand-and-manage-user-permissions 'Allow combined with Deny results in Deny' for permissions; no priority among group spaces described (read 2026-09-26)", "microsoft-viva": "https://www.microsoft.com/releasecommunications/api/v1/m365 roadmap 567887 admins 'configure audience targeting, manage home site priority order' across home sites (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerDelen" } }, { @@ -2694,7 +3885,9 @@ "built": { "state": "built", "evidence": "src/components/admin/tabs/RolesPermissionsTab.vue:15; lib/Service/ActionAuthService.php:95", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/action-authorization", + "requirement": "openspec/specs/action-authorization :: The administrator edits the matrix in one grid (REQ-ACT-003)" }, "reachedOn": "Admin settings, Roles and permissions tab, action matrix", "provider": "launchpad", @@ -2708,6 +3901,10 @@ "dashy": "source read at 4.7.0: src/store.js:224-248 only admin versus non-admin plus three global flags; no per-role action grid", "workspace-365": "https://support.workspace365.net/en/articles/175398-understand-and-manage-user-permissions permissions set 'per group or to all users' via Default permissions and Group management (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/edit-sharepoint-app-in-teams fixed Owner, Member, Visitor table; no custom grid (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerRollen" } }, { @@ -2723,7 +3920,12 @@ "built": { "state": "built", "evidence": "lib/Service/AdminTemplateService.php:80; src/components/admin/AdminSettings.vue:289", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/admin-templates", + "requirement": [ + "openspec/specs/admin-templates :: Create Admin Template (REQ-TMPL-001)", + "openspec/specs/admin-templates :: Template Distribution on First Access (REQ-TMPL-005)" + ] }, "reachedOn": "Admin settings, Templates tab", "evidence": { @@ -2737,7 +3939,11 @@ "providerHow": "read-from-code", "feature": "admin-templates", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpBeheerSjablonen" + } }, { "id": "r-permission-levels", @@ -2752,7 +3958,13 @@ "built": { "state": "built", "evidence": "lib/Service/PermissionService.php:245; src/components/admin/AdminSettings.vue:60", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/permissions", + "requirement": [ + "openspec/specs/permissions :: View-Only Permission Level (REQ-PERM-001)", + "openspec/specs/permissions :: Add-Only Permission Level (REQ-PERM-002)", + "openspec/specs/permissions :: Full Permission Level (REQ-PERM-003)" + ] }, "reachedOn": "Admin settings, Default permission level; per template in the template editor", "evidence": { @@ -2766,7 +3978,14 @@ "providerHow": "read-from-code", "feature": "permissions", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": [ + "LpDelen", + "LpIntranet" + ] + } }, { "id": "r-resync", @@ -2781,7 +4000,15 @@ "built": { "state": "built", "evidence": "lib/Service/TemplateResyncService.php:247; src/components/admin/tabs/TemplatesPage.vue:70", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": [ + "openspec/changes/archive/2026-07-23-admin-template-resync", + "openspec/changes/archive/2026-11-17-shipped-template-update" + ], + "requirement": [ + "openspec/specs/admin-templates :: REQ-RESYNC-001 Re-sync action pushes template updates to existing copies", + "openspec/specs/admin-templates :: REQ-RESYNC-003 Merge strategy preserves user-added widgets" + ] }, "reachedOn": "Admin settings, Templates tab, Resync", "provider": "launchpad", @@ -2795,6 +4022,10 @@ "dashy": "source read at 4.7.0: a personal 'Save Locally' copy replaces the shared sections (src/store.js:125-128) and never receives template changes; searched src for merge template, resync: none", "workspace-365": "https://support.workspace365.net/en/articles/703640-using-and-organising-spaces-in-workspace-365 template can be pushed to current users but 'the order of tile groups may look different'; no merge choice (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard 'Any updates or changes to the dashboard by an owner ... will override the user's personal changes'; no merge choice (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerSjablonen" } }, { @@ -2810,7 +4041,9 @@ "built": { "state": "built", "evidence": "src/components/admin/AdminSettings.vue:245; lib/Controller/DashboardApiController.php:960", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/dashboards", + "requirement": "openspec/specs/dashboards :: REQ-DASH-011 Group-shared dashboard type" }, "reachedOn": "Admin settings, Group dashboards tab; users see it in the Dashboards sidebar", "evidence": { @@ -2822,14 +4055,18 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboards", - "featureConfidence": "high", - "origin": "own-code" + "feature": "admin-templates", + "featureConfidence": "medium", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "r-wizard", "area": "rollout", - "name": "Get the product ready through a guided setup of storage, groups, demo content and roles.", + "name": "Get the product ready through a guided setup of groups, demo content and roles.", "launchpad": "yes", "workspace-365": "unknown", "microsoft-viva": "partial", @@ -2839,7 +4076,15 @@ "built": { "state": "built", "evidence": "src/components/admin/AdminSettings.vue:22; lib/Service/SetupWizardService.php:78", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-setup-wizard", + "requirement": [ + "openspec/specs/setup-wizard :: REQ-WIZ-002 Multi-Step Wizard Flow with 6 Steps", + "openspec/specs/setup-wizard :: REQ-WIZ-004 Step 2 — Group Priority Order (Embedded Component Reuse)", + "openspec/specs/setup-wizard :: REQ-WIZ-005 Step 3 — Demo Data Installation (Embedded Component Reuse)", + "openspec/specs/setup-wizard :: REQ-WIZ-006 Step 4 — Admin Roles (Optional, Depends on admin-roles Capability)" + ], + "note": "decision 392 (12 Nov): reworded without the storage step, retired 9 Oct (decision 131). Before: Get the product ready through a guided setup of storage, groups, demo content and roles." }, "reachedOn": "Admin settings, Run setup wizard banner", "provider": "launchpad", @@ -2853,6 +4098,10 @@ "dashy": "source read at 4.7.0: searched src/components and src/views for setup, wizard, onboard: none; first run shows the sample conf.yml", "workspace-365": "not checked: W365 get-started collection for a guided in-product setup (setup is partner-led)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/sharepoint-app-in-teams-overview 'quick guide to set up'; first edit asks for a primary audience to generate default cards (https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard) (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpInstellen" } }, { @@ -2868,12 +4117,18 @@ "built": { "state": "built", "evidence": "lib/Service/DemoShowcasesService.php:314; src/components/admin/tabs/DemoDataTab.vue:8", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": [ + "openspec/changes/archive/2026-05-03-demo-data-showcases", + "openspec/changes/archive/2026-11-17-mijn-werkdag-template", + "openspec/changes/archive/2026-11-17-mijn-werkdag-v3" + ], + "requirement": "openspec/specs/demo-data-showcases :: REQ-DEMO-003 Install showcase endpoint" }, "reachedOn": "Admin settings, Demo data tab; also occ launchpad demo-showcases install", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "demo-data-showcases", + "feature": "setup-wizard", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -2882,6 +4137,44 @@ "dashy": "source read at 4.7.0: user-data/conf.yml ships one sample page with 'Getting Started' links and an image widget; no installable set of example dashboards", "workspace-365": "https://support.workspace365.net/en/articles/175367 'Creating a demo environment' for partners; example dashboards inside a customer environment not described (read 2026-09-26)", "microsoft-viva": "not checked: setup pages for demo dashboards" + }, + "screen": { + "canvas": "design-system", + "board": "LpInstellen" + } + }, + { + "id": "r-report-gallery", + "area": "rollout", + "name": "Pick a ready-made report from a gallery and keep the result as your own dashboard.", + "launchpad": "no", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "specified", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them", + "requirement": "openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them :: REQ-DWMS-003 Reports the product ships" + }, + "reachedOn": "nothing yet", + "evidence": { + "workspace-365": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "microsoft-viva": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "nextcloud-dashboard": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "homarr": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "dashy": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)" + }, + "provider": "launchpad", + "providerHow": "specified", + "feature": "dashboards-and-who-may-see-them", + "featureConfidence": "medium", + "origin": "roadmap", + "screen": { + "canvas": "design-system", + "board": "LpBeheerSjablonen" } }, { @@ -2897,7 +4190,9 @@ "built": { "state": "built", "evidence": "lib/Db/RoleAssignment.php:57; src/modals/SetupWizardModal.vue:131", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/admin-roles", + "requirement": "openspec/specs/admin-roles :: REQ-ROLE-001 Dashboard Admin Role Definition" }, "reachedOn": "Admin settings, setup wizard, roles step", "evidence": { @@ -2910,9 +4205,13 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "admin-roles", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", - "note": "Roles are assigned in the setup wizard; this reading found no other screen that lists or edits them." + "note": "Roles are assigned in the setup wizard; this reading found no other screen that lists or edits them.", + "screen": { + "canvas": "design-system", + "board": "LpBeheerRollen" + } }, { "id": "r-bulk", @@ -2927,12 +4226,18 @@ "built": { "state": "built", "evidence": "lib/Service/BulkOperationService.php:169; src/components/admin/tabs/OperationsTab.vue:21", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-dashboard-bulk-operations", + "requirement": [ + "openspec/specs/dashboard-bulk-operations :: REQ-BULK-001 Bulk Delete Dashboards", + "openspec/specs/dashboard-bulk-operations :: REQ-BULK-002 Bulk Move Dashboards in Tree", + "openspec/specs/dashboard-bulk-operations :: REQ-BULK-010 Frontend Multi-Select Checkbox Column and Actions Dropdown" + ] }, "reachedOn": "Admin settings, Operations tab", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-bulk-operations", + "feature": "admin-tooling", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -2941,6 +4246,10 @@ "dashy": "source read at 4.7.0: pages are edited one config file at a time (src/components/InteractiveEditor/EditMultiPages.vue); searched src for bulk, select all: none", "workspace-365": "not checked: W365 admin articles for bulk actions on spaces", "microsoft-viva": "not checked: dashboard pages for bulk actions" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerOnderhoud" } }, { @@ -2956,7 +4265,12 @@ "built": { "state": "built", "evidence": "lib/Service/ExportService.php:93; src/components/admin/tabs/OperationsTab.vue:18; lib/Command/ExportCommand.php:40", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-02-dashboard-export-import", + "requirement": [ + "openspec/specs/dashboard-export-import :: REQ-EXIM-002 Dashboard Scope Export", + "openspec/specs/dashboard-export-import :: REQ-EXIM-004 Import Endpoint" + ] }, "reachedOn": "Admin settings, Operations tab; and occ launchpad export and import", "evidence": { @@ -2970,7 +4284,11 @@ "providerHow": "read-from-code", "feature": "dashboard-export-import", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpBeheerOnderhoud" + } }, { "id": "r-migrate-from", @@ -2996,6 +4314,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "confluence-html-import", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): No competitor rated yes; no tender, feature request or roadmap row. Outside the core area (rollout). Reversible: reopen the row if demand appears." }, @@ -3012,7 +4331,9 @@ "built": { "state": "built", "evidence": "lib/Service/ConfluenceImportService.php:94; src/components/admin/tabs/OperationsTab.vue:24", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-02-confluence-html-import", + "requirement": "openspec/specs/confluence-html-import :: REQ-CFLI-003 Confluence page → LaunchPad dashboard conversion" }, "reachedOn": "Admin settings, Operations tab, Confluence import", "provider": "launchpad", @@ -3026,6 +4347,10 @@ "dashy": "source read at 4.7.0: searched src and services for confluence: none", "workspace-365": "https://portal.productboard.com/iqfsnhkpzih6grzjwagif2ek/tabs/5-ecosystem 'Confluence - Content Search' in global search; not as dashboard content (read 2026-09-26)", "microsoft-viva": "not checked: available-dashboard-cards for Confluence" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerOnderhoud" } }, { @@ -3041,21 +4366,34 @@ "built": { "state": "specified", "evidence": "lib/Controller/StoreController.php:134; src/manifest.json:164", - "owner": "ConductionNL/openregister" + "owner": "ConductionNL/openregister", + "change": "openregister/store-over-federated-config", + "requirement": [ + "openregister:openspec/changes/store-over-federated-config/specs/apphost-store-plane :: A store MUST be able to offer configuration, not only objects", + "openspec/specs/dashboard-store :: REQ-STORE-005 An install MUST reuse ImportService, not reimplement it", + "openspec/specs/dashboard-store :: REQ-STORE-006 A store install MUST create dashboards, never replace them" + ] }, "reachedOn": "Store page (/apps/launchpad/store), once an administrator sets a registry URL on the Sharing tab", "provider": "openregister", "providerHow": "read-from-code", "feature": "dashboard-export-import", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", - "note": "Discovery runs in OpenRegister's GenericStoreService; install is LaunchPad's ImportService. Not run against a live registry in this reading. Specified in ConductionNL/openregister openspec/changes/store-over-federated-config (openregister lane, OpenSpec pass 2026-09-27).", + "note": "Discovery runs in OpenRegister's GenericStoreService; install is LaunchPad's ImportService. Not run against a live registry in this reading. Specified in ConductionNL/openregister openspec/changes/store-over-federated-config (openregister lane, OpenSpec pass 2026-09-27). LaunchPad's side, connecting a registry and installing a published dashboard as a new one, is the dashboard-store spec (REQ-STORE-005, REQ-STORE-006); the row records both.", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/src/DashboardApp.vue:113 the App Store link installs apps that bring widgets, not dashboards; searched apps/dashboard for registry, publish: none", "homarr": "source read at v1.77.2: boards cannot be exported or installed from a shared source (only the pre-1.0 importer, packages/modals-collection/src/boards/import-board-modal.tsx:154); custom widget definitions can be exported and imported as JSON (apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-actions.tsx:164) but there is no registry", "dashy": "source read at 4.7.0: a config published at a URL can be previewed and applied with ?config=<url> (RemoteConfigLoader.vue:62-70, en.json:127-128 'Load Remote Config?') and a page path can be a remote URL (src/store.js:507); there is no shared registry to browse", "workspace-365": "not checked: W365; 'Pre-built integrations store' is only planned on the productboard", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/edit-sharepoint-app-in-teams ACE solution gallery on AppSource offers cards; whole dashboards are not shared through it (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpStore", + "LpBeheerDelen" + ] } }, { @@ -3071,7 +4409,12 @@ "built": { "state": "built", "evidence": "lib/Service/QuotaService.php:144; src/components/admin/AdminSettings.vue:112", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-dashboard-quota-limits", + "requirement": [ + "openspec/specs/dashboard-quota-limits :: REQ-QUOTA-002 Dashboard Count Enforcement", + "openspec/specs/dashboard-quota-limits :: REQ-QUOTA-003 Widget Count Enforcement" + ] }, "reachedOn": "Admin settings, Default settings, quota fields", "provider": "launchpad", @@ -3085,6 +4428,10 @@ "dashy": "source read at 4.7.0: ConfigSchema.json limits are fixed schema bounds (navLinks maxItems 6, :166); searched src for quota, per-user limit: none", "workspace-365": "not checked: W365 admin articles for limits on spaces or tiles", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard 'You can set the maximum number of cards you want to display'; ~20 cards advised; no per-person dashboard quota (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerAlgemeen" } }, { @@ -3100,7 +4447,9 @@ "built": { "state": "built", "evidence": "src/components/admin/AdminSettings.vue:74", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-allow-personal-dashboards-flag", + "requirement": "openspec/specs/admin-settings :: Allow User Dashboards Setting — runtime gating + envelope (REQ-ASET-003)" }, "reachedOn": "Admin settings, Default settings", "provider": "launchpad", @@ -3114,6 +4463,10 @@ "dashy": "source read at 4.7.0: ConfigSchema.json:829-846 preventLocalSave and disableConfigurationForNonAdmin switch off personal edits (src/store.js:233-247)", "workspace-365": "https://support.workspace365.net/en/articles/703640-using-and-organising-spaces-in-workspace-365 admins 'prevent users from customizing their Personal space' via the permission 'Edit own workspace' (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard 'Disabling user customization resets all user dashboard views to what the organization created' (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerAlgemeen" } }, { @@ -3129,7 +4482,12 @@ "built": { "state": "built", "evidence": "lib/Service/DashboardShareService.php:105; src/modals/DashboardConfigModal.vue:141", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/dashboard-sharing", + "requirement": [ + "openspec/specs/dashboard-sharing :: Owner-only share management (REQ-SHARE-001)", + "openspec/specs/dashboard-sharing :: Per-share permission resolution overrides admin defaults (REQ-SHARE-004)" + ] }, "reachedOn": "Workspace page, dashboard menu, Share", "evidence": { @@ -3143,7 +4501,11 @@ "providerHow": "read-from-code", "feature": "dashboard-sharing", "featureConfidence": "high", - "origin": "own-code" + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpDelen" + } }, { "id": "s-public", @@ -3158,7 +4520,12 @@ "built": { "state": "built", "evidence": "lib/Service/PublicShareService.php:121; src/modals/DashboardConfigModal.vue:320", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-dashboard-public-share", + "requirement": [ + "openspec/specs/dashboard-public-share :: REQ-PSHR-001 Create Public Share", + "openspec/specs/dashboard-public-share :: REQ-PSHR-006 Read-Only Enforcement" + ] }, "reachedOn": "Dashboard configuration, Sharing tab, Public link; opened at /apps/launchpad/s/{token}", "provider": "launchpad", @@ -3172,6 +4539,13 @@ "dashy": "source read at 4.7.0: without auth the whole instance is open, and with auth enableGuestAccess (ConfigSchema.json:606-611, src/utils/auth/Auth.js:120-123) gives read-only guest viewing, trimmed per page, section or item by hideForGuests (:64, :1033); this is instance-wide guest mode, not a link per dashboard", "workspace-365": "not checked: W365 spaces articles for public links", "microsoft-viva": "not checked: dashboard pages for anonymous links" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpDelen", + "LpPubliek" + ] } }, { @@ -3187,7 +4561,13 @@ "built": { "state": "built", "evidence": "src/modals/DashboardConfigModal.vue:306; src/modals/DashboardConfigModal.vue:312", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-dashboard-public-share", + "requirement": [ + "openspec/specs/dashboard-public-share :: REQ-PSHR-001 Create Public Share", + "openspec/specs/dashboard-public-share :: REQ-PSHR-005 Password Gate (Unlock)", + "openspec/specs/dashboard-public-share :: REQ-PSHR-008 Expiry and Revocation 404 Response" + ] }, "reachedOn": "Dashboard configuration, Sharing tab, Public link", "provider": "launchpad", @@ -3201,6 +4581,10 @@ "dashy": "source read at 4.7.0: searched src and services for link password, expiry: none; only instance-wide HTTP basic auth (ENABLE_HTTP_AUTH, services/app.js) with no end date", "workspace-365": "not checked: W365 for password protected public links", "microsoft-viva": "not checked: dashboard pages for protected links" + }, + "screen": { + "canvas": "design-system", + "board": "LpDelen" } }, { @@ -3216,7 +4600,9 @@ "built": { "state": "built", "evidence": "lib/Controller/PublicShareController.php:37", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-dashboard-public-share", + "requirement": "openspec/specs/dashboard-public-share :: REQ-PSHR-009 Brute-Force Protection" }, "reachedOn": "/apps/launchpad/s/{token}/unlock", "provider": "launchpad", @@ -3230,6 +4616,10 @@ "dashy": "source read at 4.7.0: src/utils/auth/Auth.js:138-176 checks built-in credentials in the browser; searched services for rate limit, throttle, lockout: none", "workspace-365": "not checked: W365 security articles for public link throttling", "microsoft-viva": "not checked: dashboard pages for link throttling" + }, + "screen": { + "board": null, + "reason": "Het vertragen van geraden wachtwoorden gebeurt op de server; een bezoeker merkt alleen een trager antwoord." } }, { @@ -3245,7 +4635,9 @@ "built": { "state": "built", "evidence": "lib/Service/DashboardShareService.php:497; lib/Notification/Notifier.php:135", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/dashboard-sharing", + "requirement": "openspec/specs/dashboard-sharing :: Notify recipient on share add and on level upgrade (REQ-SHARE-008)" }, "reachedOn": "Nextcloud notifications bell", "provider": "launchpad", @@ -3259,6 +4651,10 @@ "dashy": "source read at 4.7.0: searched src and services for notification of shares: none (only LocalConfigWarning.vue, a local-config notice)", "workspace-365": "not checked: W365 activity feed for space-shared notifications", "microsoft-viva": "not checked: news notifications page covers news, not dashboard shares" + }, + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" } }, { @@ -3273,11 +4669,15 @@ "dashy": "no", "built": { "state": "built", - "evidence": "src/components/admin/AdminSettings.vue:239; lib/Controller/KioskController.php; src/views/KioskPlayerView.vue", + "evidence": "src/components/admin/AdminSettings.vue:85 (KioskTab); src/components/admin/tabs/KioskTab.vue; lib/Controller/KioskController.php; src/views/KioskPlayerView.vue", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-sharing-kiosk-screens" + "change": "openspec/changes/archive/2026-09-29-sharing-kiosk-screens", + "requirement": [ + "openspec/specs/dashboard-kiosk-mode :: The kiosk link plays the playlist without a login (REQ-KIOSKUI-002)", + "openspec/specs/dashboard-kiosk-mode :: REQ-KIOSK-003 Public Playlist Render with Rotation" + ] }, - "reachedOn": "nothing: /kiosk/{token} returns JSON that no page renders, and useKioskPlaylistStore has no caller, so no screen creates a playlist", + "reachedOn": "Admin settings, Kiosk tab: make a playlist; its kiosk link plays it on a screen without a login", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/254191-narrow-casting announcements reach screens through third-party narrowcasting software via API; 'Workspace 365 does not provide narrowcasting software itself' (read 2026-09-26)", "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for kiosk, rotate, fullscreen: none", @@ -3290,7 +4690,10 @@ "feature": "dashboard-kiosk-mode", "featureConfidence": "high", "origin": "own-code", - "note": "openspec/features.overlay.json advertises dashboard-kiosk-mode as stable (\"You rotate dashboards on a lobby screen unattended\")." + "screen": { + "canvas": "design-system", + "board": "LpKiosk" + } }, { "id": "s-schedule", @@ -3306,12 +4709,16 @@ "state": "built", "evidence": "src/components/Workspace/DashboardRowActions.vue; src/dialogs/ScheduleDashboardDialog.vue; lib/Service/DashboardService.php", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-sharing-dashboard-schedule-screen" + "change": "openspec/changes/archive/2026-09-29-sharing-dashboard-schedule-screen", + "requirement": [ + "openspec/specs/dashboards :: A manager can publish, unpublish and schedule a dashboard (REQ-SCHEDUI-001)", + "openspec/specs/dashboards :: A dashboard can come down at a set time (REQ-SCHEDUI-002)" + ] }, "reachedOn": "nothing: the store actions publishDashboard and scheduleDashboard have no component caller", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboards", + "feature": "dashboard-kiosk-mode", "featureConfidence": "medium", "origin": "own-code", "evidence": { @@ -3321,7 +4728,11 @@ "workspace-365": "not checked: W365 spaces for scheduled go-live", "microsoft-viva": "not checked: dashboard publish is manual; no schedule found" }, - "note": "Decided no 2026-09-28 (build-all decision pass): No competitor rated yes; no tender, feature request or roadmap row. Outside the core area (sharing). Reversible: reopen the row if demand appears. The code already built stays in the tree; it has no screen (see the pull request)." + "note": "Decided no 2026-09-28 (build-all decision pass): No competitor rated yes; no tender, feature request or roadmap row. Outside the core area (sharing). Reversible: reopen the row if demand appears. The code stays in the tree and has a screen since: the Publish, Unpublish and Schedule items in the dashboard menu (src/dialogs/ScheduleDashboardDialog.vue).", + "screen": { + "canvas": "design-system", + "board": "LpDelen" + } }, { "id": "s-policy", @@ -3335,8 +4746,12 @@ "dashy": "no", "built": { "state": "built", - "evidence": "src/components/admin/tabs/SharingTab.vue:8", - "owner": "ConductionNL/launchpad" + "evidence": "lib/Service/SharingLimits.php:40; lib/Db/AdminSettingKey.php:63; src/components/admin/DashboardSharingPolicy.vue; live pass 17 Nov 2026 on NC 34: with sharingAllowedGroups [\"admin\"] a member's share answered 403 and went through once the list was empty", + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/dashboard-sharing", + "requirement": "openspec/specs/dashboard-sharing :: Administrators decide who may share and with whom (REQ-SHARE-014)", + "plan": "openspec/changes/archive/2026-11-17-record-parity-requirements", + "readOn": "2026-11-17" }, "reachedOn": "Admin settings, Sharing tab", "provider": "launchpad", @@ -3350,6 +4765,10 @@ "dashy": "source read at 4.7.0: no sharing exists to govern; permissions are three global flags (src/store.js:224-248)", "workspace-365": "not checked: W365 permissions for a sharing policy", "microsoft-viva": "not checked: dashboard pages for sharing policy" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerDelen" } }, { @@ -3365,13 +4784,15 @@ "built": { "state": "built", "evidence": "lib/Listener/UserDeletedListener.php:8; lib/Service/DashboardShareService.php:342", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/dashboard-sharing", + "requirement": "openspec/specs/dashboard-sharing :: Cascade and admin retention on user deletion (REQ-SHARE-012)" }, "reachedOn": "automatic when a Nextcloud user is deleted", "provider": "launchpad", "providerHow": "read-from-code", "feature": "orphaned-data-cleanup", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: lib/private/User/User.php:315 deleting a user removes all their user config, including the dashboard layout; there is nothing shared to hand over and no transfer (searched apps/dashboard for owner, transfer: none)", @@ -3379,6 +4800,47 @@ "dashy": "source read at 4.7.0: dashboards are not owned by users; searched services for user deletion or transfer: none", "workspace-365": "not checked: W365 user management for ownership transfer", "microsoft-viva": "not checked: dashboard pages for ownership transfer" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerOnderhoud" + } + }, + { + "id": "s-discussion", + "area": "sharing", + "name": "Discuss a shared dashboard with colleagues in a Talk conversation beside it.", + "launchpad": "no", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "specified", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/openregister-leaf-integrations", + "requirement": [ + "openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf :: REQ-LEAF-002 Discussion surface renders only on shared dashboards", + "openspec/changes/openregister-leaf-integrations/specs/dashboard-talk-leaf :: REQ-LEAF-003 Discussion access follows the existing view guard" + ] + }, + "reachedOn": "nothing yet", + "evidence": { + "workspace-365": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "microsoft-viva": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "nextcloud-dashboard": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "homarr": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)", + "dashy": "not checked: row added from the open-change triage on 12 Nov 2026 (decision 395)" + }, + "provider": "launchpad", + "providerHow": "specified", + "feature": "dashboard-talk-leaf", + "featureConfidence": "medium", + "origin": "roadmap", + "screen": { + "canvas": "design-system", + "board": "LpDelen" } }, { @@ -3405,6 +4867,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "news-and-announcements", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Microsoft Viva Connections rated yes; no tender, feature request or roadmap row. Outside the core area (sharing). Reversible: reopen the row if demand appears." }, @@ -3422,12 +4885,13 @@ "state": "built", "evidence": "src/components/Widgets/WidgetContextMenu.vue; src/dialogs/ReadConfirmationDialog.vue", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-engagement-acknowledgement-toggle" + "change": "openspec/changes/archive/2026-09-29-engagement-acknowledgement-toggle", + "requirement": "openspec/specs/dashboard-acknowledgements :: An editor can ask for confirmation from the widget form (REQ-ACK-007)" }, "reachedOn": "the prompt renders on the Workspace page, but no form sets requiresAcknowledgement; only PUT /api/widgets/{placementId} does", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-acknowledgements", + "feature": "acknowledgements-and-reactions", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -3437,7 +4901,14 @@ "workspace-365": "https://support.workspace365.net/en/articles/175643-best-practices 'Must-read' items use 'the pop-up function'; https://portal.productboard.com/iqfsnhkpzih6grzjwagif2ek/tabs/3-launched launched 'Read / unread hub items'; an explicit confirm button not described (read 2026-09-26)", "microsoft-viva": "not checked: announcements page offers 'Allow users to dismiss', no read confirmation found" }, - "note": "Decided no 2026-09-28 (build-all decision pass): No competitor rated yes (Workspace 365 partial); no tender, feature request or roadmap row. Outside the core area (engagement). Reversible: reopen the row if demand appears. The code already built stays in the tree; it has no screen (see the pull request)." + "note": "Decided no 2026-09-28 (build-all decision pass): No competitor rated yes (Workspace 365 partial); no tender, feature request or roadmap row. Outside the core area (engagement). Reversible: reopen the row if demand appears. The code stays in the tree and has a screen since: the \"Ask readers to confirm\" option in the widget menu (src/dialogs/ReadConfirmationDialog.vue).", + "screen": { + "canvas": "design-system", + "board": [ + "LpIntranet", + "LpAankondiging" + ] + } }, { "id": "e-ack-report", @@ -3452,12 +4923,17 @@ "built": { "state": "built", "evidence": "lib/Service/AcknowledgementService.php:251; src/views/Views.vue:163", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-07-07-dashboard-acknowledgements", + "requirement": [ + "openspec/specs/dashboard-acknowledgements :: An editor can see who has confirmed (REQ-ACK-008)", + "openspec/specs/dashboard-acknowledgements :: REQ-ACK-006 Acknowledgement events feed activity and export" + ] }, "reachedOn": "Workspace page, Read receipts button", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-acknowledgements", + "feature": "acknowledgements-and-reactions", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -3466,6 +4942,10 @@ "dashy": "source read at 4.7.0: no acknowledgements exist (searched src and services for acknowledge, export csv of readers: none)", "workspace-365": "https://portal.productboard.com/iqfsnhkpzih6grzjwagif2ek/tabs/3-launched launched 'See who has read an announcement (insights)'; spreadsheet export not described for readers (read 2026-09-26)", "microsoft-viva": "not checked: announcements and analytics pages for per-user read lists (analytics are aggregated)" + }, + "screen": { + "canvas": "design-system", + "board": "LpLeesbevestigingen" } }, { @@ -3482,12 +4962,13 @@ "state": "built", "evidence": "src/components/Workspace/DashboardReactions.vue; src/views/Views.vue", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-29-engagement-dashboard-reactions-bar" + "change": "openspec/changes/archive/2026-09-29-engagement-dashboard-reactions-bar", + "requirement": "openspec/specs/dashboard-reactions :: REQ-RXN-010 A viewer can react from the dashboard" }, "reachedOn": "nothing: the store actions addReaction and fetchReactionsSummary have no component caller", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboard-reactions", + "feature": "acknowledgements-and-reactions", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -3497,22 +4978,33 @@ "workspace-365": "https://support.workspace365.net/en/articles/284826-create-announcements emoji reactions 'like, love, sad, celebrate, laugh, thanks' on announcements, not on a space (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/sharepoint-app-in-teams-news-notifications 'Likes' on news posts; not on the dashboard (read 2026-09-26)" }, - "note": "Decided no 2026-09-28 (build-all decision pass): No competitor rated yes (Workspace 365, Microsoft Viva Connections partial); no tender, feature request or roadmap row. Outside the core area (engagement). Reversible: reopen the row if demand appears. The code already built stays in the tree; it has no screen (see the pull request)." + "note": "Decided no 2026-09-28 (build-all decision pass): No competitor rated yes (Workspace 365, Microsoft Viva Connections partial); no tender, feature request or roadmap row. Outside the core area (engagement). Reversible: reopen the row if demand appears. The code stays in the tree and has a screen since: the reactions bar under the dashboard title (src/components/Workspace/DashboardReactions.vue).", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "e-announcements", "area": "engagement", "name": "Post targeted news announcements that people can like, comment on and follow.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "yes", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "lib/Controller/AnnouncementController.php:84; lib/Service/AnnouncementCommentService.php:143; lib/Service/AnnouncementFollowNotifier.php:104; live pass 17 Nov 2026: tests/e2e/announcements.spec.ts 3 passed on NC 34", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/engagement-announcements" + "change": "openspec/changes/archive/2026-11-17-engagement-announcements", + "requirement": [ + "openspec/specs/announcements :: Authors publish targeted announcements (REQ-ANN-001)", + "openspec/specs/announcements :: Readers like and comment through Nextcloud comments (REQ-ANN-002)", + "openspec/specs/announcements :: Readers follow categories (REQ-ANN-003)" + ], + "readOn": "2026-11-17" }, "reachedOn": "nothing: a text widget can carry a message, with no likes, comments or follow", "evidence": { @@ -3524,8 +5016,16 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "news-and-announcements", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/engagement-announcements (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/engagement-announcements (openspec pass). Built since and archived 2026-11-17.", + "screen": { + "canvas": "design-system", + "board": [ + "LpIntranet", + "LpAankondiging" + ] + } }, { "id": "e-events", @@ -3551,6 +5051,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "communities-events-and-knowledge", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (engagement). Reversible: reopen the row if demand appears." }, @@ -3578,6 +5079,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "communities-events-and-knowledge", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (engagement). Reversible: reopen the row if demand appears." }, @@ -3585,16 +5087,19 @@ "id": "e-communities", "area": "engagement", "name": "Join topic communities where staff ask questions and share ideas.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "yes", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/engagement-communities" + "change": "openspec/changes/archive/2026-11-17-engagement-communities", + "requirement": "openspec/specs/communities-widget :: The Communities widget lists open Talk conversations the viewer may join (REQ-COMM-001)", + "evidence": "src/components/Widgets/Renderers/CommunitiesWidget.vue; src/services/talkCommunities.js; live pass 17 Nov 2026: tests/e2e/communities-widget.spec.ts passed on NC 34 with Talk 24", + "readOn": "2026-11-17" }, "reachedOn": "nothing", "evidence": { @@ -3606,23 +5111,31 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "communities-events-and-knowledge", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/engagement-communities (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/engagement-communities (openspec pass). Built since and archived 2026-11-17.", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "e-digest", "area": "engagement", "name": "Get a daily or weekly email summing up what changed.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "unknown", "nextcloud-dashboard": "yes", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/engagement-activity-digest" + "change": "openspec/changes/archive/2026-11-17-engagement-activity-digest", + "requirement": "openspec/specs/activity-feed-integration :: LaunchPad events can reach the activity digest email (REQ-DIGE-001)", + "evidence": "lib/Activity/Settings/DashboardSharedSetting.php:73; lib/Activity/DashboardActivityEmitter.php; live pass 17 Nov 2026 on NC 34: a share queued one dashboard_shared mail row for a recipient on daily batching, an edit queued none", + "readOn": "2026-11-17" }, "reachedOn": "nothing", "evidence": { @@ -3634,8 +5147,13 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "news-and-announcements", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/engagement-activity-digest (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/engagement-activity-digest (openspec pass). Built since and archived 2026-11-17.", + "screen": { + "canvas": "design-system", + "board": "LpPersoonlijk" + } }, { "id": "e-activity-stream", @@ -3663,7 +5181,7 @@ "provider": "nextcloud", "providerHow": "research-then-code", "feature": "activity-feed-integration", - "featureConfidence": "low", + "featureConfidence": "high", "origin": "competitor", "note": "LaunchPad writes its own events to the Nextcloud activity stream; gathering approvals and news from outside systems is not there. Decided no on 2026-09-27 (openspec pass): Owed to nextcloud/server: the personal activity stream is the Nextcloud activity app; LaunchPad already writes its events into it. Platform-provided, outside the fleet. Corrections round 8 (2026-09-28): LaunchPad writes only 2 of its 14 declared events into the activity stream, not all of them as the note above says, launchpad#713; rating kept because the row rates one personal stream of approvals, news and meetings from several systems, which the Nextcloud activity app provides and which this gap does not change." }, @@ -3671,17 +5189,19 @@ "id": "e-maintenance", "area": "engagement", "name": "Put a maintenance or outage notice on everyone's dashboard for a set period.", - "launchpad": "partial", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "yes", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", - "evidence": "src/components/Widgets/VisibilityRuleRow.vue:111; lib/widget-types.json:37", + "state": "built", + "evidence": "src/views/WorkspaceApp.vue:74; src/components/Announcements/NoticeBanner.vue:12; live pass 17 Nov 2026: tests/e2e/announcements.spec.ts 3 passed on NC 34", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/engagement-announcements" + "change": "openspec/changes/archive/2026-11-17-engagement-announcements", + "requirement": "openspec/specs/announcements :: Notices show above every targeted dashboard for their period (REQ-ANN-005)", + "readOn": "2026-11-17" }, "reachedOn": "Admin settings, Group dashboards or Templates: a text widget with a date rule", "evidence": { @@ -3693,10 +5213,17 @@ }, "provider": "launchpad", "providerHow": "research-then-code", - "feature": "conditional-visibility", - "featureConfidence": "low", + "feature": "news-and-announcements", + "featureConfidence": "medium", "origin": "competitor", - "note": "Possible by hand with a date-limited text widget; there is no notice type. Specified 2026-09-27 in openspec/changes/engagement-announcements (openspec pass)." + "note": "Possible by hand with a date-limited text widget; there is no notice type. Specified 2026-09-27 in openspec/changes/engagement-announcements (openspec pass). Built since and archived 2026-11-17.", + "screen": { + "canvas": "design-system", + "board": [ + "LpIntranet", + "LpAankondiging" + ] + } }, { "id": "a-find-dashboard", @@ -3711,7 +5238,9 @@ "built": { "state": "built", "evidence": "lib/Search/LaunchPadSearchProvider.php:173", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-nc-unified-search-integration", + "requirement": "openspec/specs/nc-unified-search-integration :: REQ-SRCH-002 Dashboard Name and Description Matching" }, "reachedOn": "Nextcloud unified search in the header", "provider": "launchpad", @@ -3725,6 +5254,11 @@ "dashy": "source read at 4.7.0: Dashy is a standalone app with its own search over items (src/utils/Search.js:15-21), not pages; there is no Nextcloud search provider (no appinfo or PHP in the tree)", "workspace-365": "not checked: W365 global search categories do not list spaces", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/create-dashboard dashboard thumbnail and description 'to be shown in search results' (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpWerkplek", + "reason": "Nextcloud core search: the dashboard result shows in Nextcloud's own search bar, which no LaunchPad board draws; LpWerkplek shows LaunchPad's tile quick search" } }, { @@ -3753,7 +5287,7 @@ "provider": "nextcloud", "providerHow": "research-then-code", "feature": "nc-unified-search-integration", - "featureConfidence": "low", + "featureConfidence": "high", "origin": "competitor", "note": "Nextcloud unified search covers installed Nextcloud apps; outside systems appear only if an app provides a search provider. Decided no on 2026-09-27 (openspec pass): Owed to nextcloud/server: unified search across mail, files and connected systems is Nextcloud server's unified search; outside systems join it through their own search providers. Platform-provided, outside the fleet." }, @@ -3771,7 +5305,11 @@ "state": "built", "evidence": "src/components/Widgets/Renderers/AiAssistantWidget.vue (widget type ai-assistant, questions through Hermiq via useAiChatStream)", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/archive/2026-09-30-search-ai-dashboard-assistant" + "change": "openspec/changes/archive/2026-09-30-search-ai-dashboard-assistant", + "requirement": [ + "openspec/specs/launchpad-ai-dashboard-assistant :: REQ-ADA-004: Inference SHALL route exclusively through hermiq; launchpad MUST NOT contain an LLM client", + "openspec/specs/launchpad-ai-dashboard-assistant :: REQ-ADA-006: The widget SHALL render two reply modes, streamed chat and inline summary" + ] }, "reachedOn": "nothing", "note": "corrections round 9 (2026-09-28): no change carries this row at 9d5535a, so built.state is none. The evidence cites a main spec, openspec/specs/launchpad-ai-dashboard-assistant (REQ-ADA-001 to 007, a chat widget answering plain-language questions), not a change. The change that wrote it, openspec/changes/archive/2026-06-14-add-launchpad-discovered-and-spend-analytics, was spec-only and its tasks.md says the ai-dashboard-assistant widget chain remains spec-only; no ai-assistant widget exists in src/ or lib/. The open change launchpad-ai-dashboard-assistant carries AI summary widgets for cases and consultations, not questions and answers. Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (search-ai). Reversible: reopen the row if demand appears. Reversed to build 2026-09-29 (DECISIONS row 16); built 2026-09-30 by search-ai-dashboard-assistant, answers through Hermiq.", @@ -3785,8 +5323,12 @@ "provider": "launchpad", "providerHow": "research-then-code", "feature": "launchpad-ai-dashboard-assistant", - "featureConfidence": "medium", - "origin": "competitor" + "featureConfidence": "high", + "origin": "competitor", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "a-place-widget", @@ -3801,7 +5343,9 @@ "built": { "state": "specified", "evidence": "openspec/changes/mcp-tool-surface/specs/mcp-tools/spec.md:226", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/mcp-tool-surface", + "requirement": "openspec/changes/mcp-tool-surface/specs/mcp-tools/spec.md :: REQ-MCP-008 Chat command flows resolve to tool sequences" }, "reachedOn": "nothing: the overlay lists it as soon", "provider": "launchpad", @@ -3816,7 +5360,11 @@ "workspace-365": "not checked: Kelly FAQ for placing tiles", "microsoft-viva": "not checked: dashboard pages for AI card placement; roadmap 558441 'add webparts' by prompt is for SharePoint pages and In development" }, - "note": "Specified in openspec/changes/mcp-tool-surface (named 2026-09-27, openspec pass): the scenario \"Add the calendar widget to my dashboard\" resolves a plain request to launchpad.addWidget through hermiq. The features overlay entry (openspec/features.overlay.json:231) had pointed at the assistant widget spec, which places nothing." + "note": "Specified in openspec/changes/mcp-tool-surface (named 2026-09-27, openspec pass): the scenario \"Add the calendar widget to my dashboard\" resolves a plain request to launchpad.addWidget through hermiq. The features overlay entry (openspec/features.overlay.json:231) had pointed at the assistant widget spec, which places nothing.", + "screen": { + "canvas": "design-system", + "board": "LpWidgetKiezen" + } }, { "id": "a-agent-tools", @@ -3832,14 +5380,18 @@ "state": "specified", "evidence": "openspec/changes/mcp-tool-surface/proposal.md:7", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/mcp-tool-surface" + "change": "openspec/changes/mcp-tool-surface", + "requirement": [ + "openspec/changes/mcp-tool-surface/specs/mcp-tools :: REQ-MCP-002 Read tool catalogue (full read coverage)", + "openspec/changes/mcp-tool-surface/specs/mcp-tools :: REQ-MCP-003 Write tool catalogue with scope × reach annotations (full action coverage)" + ] }, "reachedOn": "nothing", - "note": "corrections round 9 (2026-09-28): built.change names openspec/changes/mcp-tool-surface, open on development at 9d5535a with 0 of 28 tasks checked, whose proposal specifies a LaunchpadToolProvider with 14 read and 35 write MCP tools over dashboards, widgets, tiles and sharing; lib/Mcp does not exist yet, so the rating stays no; source: the corrections-9 list of specified rows that named no change.", + "note": "corrections round 9 (2026-09-28): built.change names openspec/changes/mcp-tool-surface, open on development at 9d5535a with 0 of 28 tasks checked, whose proposal specifies a LaunchPadToolProvider with 14 read and 35 write MCP tools over dashboards, widgets, tiles and sharing; lib/Mcp does not exist yet, so the rating stays no; source: the corrections-9 list of specified rows that named no change.", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "mcp-tool-surface", - "featureConfidence": "medium", + "feature": "launchpad-ai-dashboard-assistant", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: apps/dashboard/openapi.json documents OCS endpoints to list widgets and read or set the layout (apps/dashboard/lib/Controller/DashboardApiController.php:137,188,202), usable by any client with an app password; there is no agent or MCP tool definition in apps/dashboard", @@ -3847,6 +5399,10 @@ "dashy": "source read at 4.7.0: services/endpoints/api/openapi.yml:75-330 opt-in REST API (ENABLE_API, API_TOKEN) to list, read, replace and patch configs, sections and items; no MCP or other agent tool interface (searched src, services, docs for mcp: none)", "workspace-365": "not checked: W365 API docs for an agent tool interface", "microsoft-viva": "not checked: dashboard pages for agent tools" + }, + "screen": { + "board": null, + "reason": "Een koppelvlak voor AI-agenten (MCP), zonder eigen scherm." } }, { @@ -3873,6 +5429,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "launchpad-ai-dashboard-assistant", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (search-ai). Reversible: reopen the row if demand appears." }, @@ -3900,6 +5457,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "launchpad-ai-dashboard-assistant", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (search-ai). Reversible: reopen the row if demand appears." }, @@ -3916,7 +5474,12 @@ "built": { "state": "built", "evidence": "lib/Service/AnalyticsService.php:281; src/components/admin/tabs/VersioningAuditTab.vue:10", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-02-dashboard-view-analytics", + "requirement": [ + "openspec/specs/dashboard-view-analytics :: REQ-ANLT-006 Top Dashboards Query Endpoint", + "openspec/specs/dashboard-view-analytics :: REQ-ANLT-010 CSV Export Endpoint" + ] }, "reachedOn": "Admin settings, Versioning and audit tab", "provider": "launchpad", @@ -3930,13 +5493,17 @@ "dashy": "source read at 4.7.0: searched services for view counts, analytics: none; usage counts stay in the browser (src/mixins/ItemMixin.js:385)", "workspace-365": "https://support.workspace365.net/en/articles/175636-analytics-of-a-workspace-365-environment 'usage of the Hub', 'usage per app', 'active users'; per space and export not described (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/sharepoint-app-in-teams-analytics total views, engaged users per card; 'Download report ... Excel spreadsheet' (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerAnalyse" } }, { "id": "g-optout", "area": "governance", "name": "People can opt out of view tracking, and old view data is removed after a set time.", - "launchpad": "partial", + "launchpad": "yes", "workspace-365": "unknown", "microsoft-viva": "partial", "nextcloud-dashboard": "no", @@ -3944,10 +5511,18 @@ "dashy": "no", "built": { "state": "built", - "evidence": "lib/Service/AnalyticsService.php:140; lib/BackgroundJob/PurgeViewsJob.php:50", - "owner": "ConductionNL/launchpad" + "evidence": "lib/Controller/AnalyticsOptOutController.php:93; lib/Service/AnalyticsService.php:134; lib/BackgroundJob/PurgeViewsJob.php:50; src/views/settings/AnalyticsOptOutSettings.vue; live pass 17 Nov 2026 on NC 34: PUT /api/analytics/me stored analytics_optout for the caller and refused another user", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-02-dashboard-view-analytics", + "requirement": [ + "openspec/specs/dashboard-view-analytics :: REQ-ANLT-004 Per-User Analytics Opt-Out", + "openspec/specs/dashboard-view-analytics :: REQ-ANLT-009 Analytics Data Retention and Purge", + "openspec/specs/dashboard-view-analytics :: A person turns view counting off in their own settings (REQ-ANLT-UI-001)" + ], + "plan": "openspec/changes/archive/2026-11-17-analytics-personal-opt-out", + "readOn": "2026-11-17" }, - "reachedOn": "the purge runs as a background job; the opt-out is a user preference no page sets, since /api/preferences/{key} has no caller in src/", + "reachedOn": "nothing for a person: the opt-out is set only with occ user:setting <uid> launchpad analytics_optout true; the purge runs as a background job", "provider": "launchpad", "providerHow": "read-from-code", "feature": "dashboard-view-analytics", @@ -3959,6 +5534,13 @@ "dashy": "source read at 4.7.0: there is no server-side view tracking to opt out of (searched services for track, analytics: none); only local click counts that can be reset by clearing site data", "workspace-365": "not checked: W365 analytics article on opt-out or retention", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/sharepoint-app-in-teams-analytics data 'aggregated and can't be tracked to an individual user'; tenant can disable analytics; no per-person opt-out (read 2026-09-26)" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpPersoonlijk", + "LpBeheerAnalyse" + ] } }, { @@ -3974,7 +5556,12 @@ "built": { "state": "built", "evidence": "src/components/admin/tabs/OperationsTab.vue:9; lib/Controller/HealthController.php:53", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/prometheus-metrics", + "requirement": [ + "openspec/specs/prometheus-metrics :: The admin page shows the app's health (REQ-PROM-011)", + "openspec/specs/prometheus-metrics :: Health Check Endpoint (REQ-PROM-007)" + ] }, "reachedOn": "Admin settings, Operations tab", "provider": "launchpad", @@ -3988,6 +5575,10 @@ "dashy": "source read at 4.7.0: services/app.js:229-235 GET healthz returns status, uptime, version; yarn health-check (services/healthcheck.js); the config menu has a hidden Debug Info tab with error log and environment (src/components/Configuration/ConfigContainer.vue:40, :76); no admin health page", "workspace-365": "not checked: W365 admin articles for a health page", "microsoft-viva": "not checked: dashboard pages for health checks" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerOnderhoud" } }, { @@ -4003,7 +5594,9 @@ "built": { "state": "built", "evidence": "lib/Controller/MetricsController.php:93; src/components/admin/tabs/OperationsTab.vue:12", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-03-21-prometheus-metrics", + "requirement": "openspec/specs/prometheus-metrics :: Metrics Endpoint (REQ-PROM-001)" }, "reachedOn": "/apps/launchpad/api/metrics; explained on Admin settings, Operations tab", "provider": "launchpad", @@ -4017,6 +5610,10 @@ "dashy": "source read at 4.7.0: searched services and src for prometheus, metrics endpoint: none (UptimeKuma.vue:35 only reads another tool's metrics)", "workspace-365": "not checked: W365 docs for Prometheus", "microsoft-viva": "not checked: dashboard pages for Prometheus" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerOnderhoud" } }, { @@ -4044,8 +5641,8 @@ }, "provider": "nextcloud", "providerHow": "research-then-code", - "feature": "activity-feed-integration", - "featureConfidence": "low", + "feature": "launchpad-compliance-audit-panel", + "featureConfidence": "medium", "origin": "competitor", "note": "Bulk operations, template resyncs and acknowledgements write activity events; that is an activity stream, not a compliance audit log. Decided no on 2026-09-27 (openspec pass): Owed to nextcloud/server: the change log for review is Nextcloud's admin_audit app. Platform-provided, outside the fleet." }, @@ -4061,14 +5658,19 @@ "dashy": "no", "built": { "state": "built", - "evidence": "lib/Activity/ActivityPublisher.php:82; lib/Service/TemplateResyncService.php:867; Corrections round 8 (2026-09-28), launchpad#713: only 2 of the 14 event types declared at lib/Activity/Extension.php:80-93 are ever sent, dashboard_updated for bulk operations and template re-sync and dashboard_acknowledged; lib/Service/BulkOperationService.php:949, lib/Service/TemplateResyncService.php:867 and lib/Service/AcknowledgementService.php:532 are the only callers of ActivityPublisher::publish() at e74f421, so creating, deleting, publishing, sharing, commenting on or restoring a dashboard leaves no entry.", - "owner": "nextcloud/server" + "evidence": "lib/Activity/ActivityPublisher.php:82; lib/Activity/DashboardActivityEmitter.php (dashboard_shared, dashboard_published, dashboard_updated); callers lib/Service/ShareNotifier.php:90, lib/Service/DashboardService.php:873, :1298, :2260, :2458; also lib/Service/BulkOperationService.php:888, lib/Service/TemplateResyncService.php:916, lib/Service/AcknowledgementService.php:717", + "owner": "nextcloud/server", + "change": "openspec/changes/archive/2026-05-02-activity-feed-integration", + "requirement": [ + "openspec/specs/activity-feed-integration :: REQ-ACT-001 Extension Registration", + "openspec/specs/activity-feed-integration :: REQ-ACT-005 Audience Targeting — Shared Dashboards" + ] }, "reachedOn": "Nextcloud Activity app", "provider": "nextcloud", "providerHow": "read-from-code", "feature": "activity-feed-integration", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for activity, IManager publish: none; layout saves (apps/dashboard/lib/Controller/DashboardApiController.php:202-206) emit no activity", @@ -4077,7 +5679,11 @@ "workspace-365": "not checked: W365 activity feed for space changes", "microsoft-viva": "not checked: dashboard pages for change activity" }, - "note": "Own rating yes to partial (corrections round 8, 2026-09-28): only 2 of the 14 declared dashboard event types are ever published, so ordinary edits, shares and publishes never reach the activity stream, launchpad#713." + "note": "Sharing, publishing and saving a shared or group dashboard reach the activity stream since launchpad#713 (DashboardActivityEmitter). Creating, deleting, commenting on and restoring a dashboard still send no entry.", + "screen": { + "board": null, + "reason": "Wijzigingen verschijnen in de Activiteit-app van Nextcloud, niet op een scherm van Launchpad." + } }, { "id": "g-cleanup", @@ -4092,7 +5698,9 @@ "built": { "state": "built", "evidence": "lib/BackgroundJob/OrphanedDataCleanupJob.php:111; lib/Listener/GroupDeletedListener.php:55", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-orphaned-data-cleanup", + "requirement": "openspec/specs/orphaned-data-cleanup :: REQ-CLN-007 Background Job for Auto-Purge" }, "reachedOn": "background job and user or group deletion; occ launchpad cleanup scan and purge", "provider": "launchpad", @@ -4106,6 +5714,10 @@ "dashy": "source read at 4.7.0: there is no per-user server data to clean; personal changes live in each browser (src/store.js:96-130); searched services for user deletion: none", "workspace-365": "not checked: W365 user management for cleanup", "microsoft-viva": "not checked: dashboard pages for cleanup" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerOnderhoud" } }, { @@ -4121,12 +5733,17 @@ "built": { "state": "built", "evidence": "lib/Command/DashboardListCommand.php:38; lib/Command/ExportCommand.php:40", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-cli-commands", + "requirement": [ + "openspec/specs/cli-commands :: REQ-CLI-003 New Commands: Dashboard Management", + "openspec/specs/dashboard-export-import :: REQ-EXIM-010 CLI Commands for Export and Import" + ] }, "reachedOn": "occ launchpad commands", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "cli-commands", + "feature": "admin-tooling", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -4135,6 +5752,10 @@ "dashy": "source read at 4.7.0: package.json scripts validate-config (services/utils/config-validator.js) and health-check; config files can be listed, read, replaced and deleted over the REST API with curl (openapi.yml:75-128); no dedicated dashboard CLI", "workspace-365": "not checked: W365 'Create & Delete environment script' covers environments, not spaces", "microsoft-viva": "not checked: PowerShell pages for dashboard commands (only analytics toggle found)" + }, + "screen": { + "board": null, + "reason": "Commando's op de server (occ), zonder scherm." } }, { @@ -4150,12 +5771,14 @@ "built": { "state": "built", "evidence": "src/views/WorkspaceApp.vue:100; lib/Service/FooterService.php:237", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-05-03-footer-customization", + "requirement": "openspec/specs/footer-customization :: REQ-FTR-004 Footer Rendering — Global Content" }, "reachedOn": "the footer renders on the Workspace page; /api/admin/footer-settings has no caller in src/, so no screen edits it", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "footer-customization", + "feature": "organisation-navigation", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -4164,6 +5787,13 @@ "dashy": "source read at 4.7.0: ConfigSchema.json:199-203 pageInfo.footer with sanitised inline HTML, rendered on every page by src/components/PageStrcture/Footer.vue:2", "workspace-365": "not checked: W365 branding for a footer", "microsoft-viva": "not checked: edit page for a dashboard footer" + }, + "screen": { + "canvas": "design-system", + "board": [ + "LpWerkplek", + "LpBeheerNavigatie" + ] } }, { @@ -4179,13 +5809,28 @@ "built": { "state": "built", "evidence": "lib/Settings/connections.json:43; lib/Service/IframeService.php:9", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": [ + "openspec/changes/archive/2026-11-12-adopt-connection-registry", + "openspec/changes/archive/2026-07-23-iframe-embed-widget" + ], + "spec": [ + "openspec/specs/iframe-embed-widget", + "openspec/specs/live-data-tile-widget", + "openspec/specs/service-health-ping" + ], + "requirement": [ + "openspec/specs/iframe-embed-widget :: REQ-IFRAME-002 Admin allow-list of embeddable hosts, fail-closed", + "openspec/specs/live-data-tile-widget :: REQ-LIVETILE-002 Configure the tile source", + "openspec/specs/live-data-tile-widget :: REQ-LIVETILE-003 Resolve and cache the value server-side", + "openspec/specs/service-health-ping :: REQ-HPING-002 Ping the service server-side and classify the result" + ] }, "reachedOn": "occ config:app:set only; no admin screen edits the host lists", "provider": "launchpad", "providerHow": "read-from-code", "feature": "iframe-embed-widget", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: searched apps/dashboard for allowlist, domain, csp: the only policy is geolocation for self (apps/dashboard/lib/Controller/DashboardController.php:82-85); widgets are server-side app code, and weather data is fetched by the server (apps/dashboard/src/DashboardApp.vue:118)", @@ -4193,6 +5838,10 @@ "dashy": "source read at 4.7.0: services/utils/request.js:14-52 the proxy only blocks cloud metadata hosts (escape hatch DANGEROUSLY_DISABLE_PROXY_RESTRICTIONS); the iframe and embed widgets load any site; no allow-list", "workspace-365": "not checked: https://support.workspace365.net/en/articles/175489-content-security-policy-csp allow-list governs where Workspace itself may be embedded, not what tiles fetch", "microsoft-viva": "not checked: dashboard pages for an allow-list" + }, + "screen": { + "canvas": "design-system", + "board": "LpBeheerAlgemeen" } }, { @@ -4208,12 +5857,14 @@ "built": { "state": "built", "evidence": "lib/Service/SvgSanitiser.php:166", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/archive/2026-06-14-svg-sanitisation", + "requirement": "openspec/specs/resource-uploads :: SVG sanitiser is mandatory before persistence (REQ-RES-009)" }, "reachedOn": "every icon upload through /api/resources", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "resource-uploads", + "feature": "tiles", "featureConfidence": "high", "origin": "own-code", "evidence": { @@ -4222,6 +5873,10 @@ "dashy": "source read at 4.7.0: there is no icon upload (searched src for upload, type=file: none); remote SVG icons are shown as img (src/components/LinkItems/ItemIcon.vue:110), which keeps scripts from running, but nothing cleans them", "workspace-365": "not checked: W365 branding for icon sanitising", "microsoft-viva": "not checked: dashboard pages for icon sanitising" + }, + "screen": { + "canvas": "design-system", + "board": "LpTegelBewerken" } }, { @@ -4237,7 +5892,9 @@ "built": { "state": "built", "evidence": "lib/Controller/DashboardApiController.php:158", - "owner": "nextcloud/server" + "owner": "nextcloud/server", + "spec": "openspec/specs/platform-baseline", + "requirement": "openspec/specs/platform-baseline :: LaunchPad has no login of its own (REQ-PLB-001)" }, "reachedOn": "Nextcloud login; every LaunchPad route runs behind the Nextcloud session", "evidence": { @@ -4249,7 +5906,12 @@ }, "provider": "nextcloud", "providerHow": "read-from-code", - "origin": "own-code" + "feature": "launchpad-enterprise-security-access", + "origin": "own-code", + "screen": { + "board": null, + "reason": "Aanmelden loopt via Nextcloud en de identiteitsprovider van de organisatie, niet via een scherm van Launchpad." + } }, { "id": "p-mobile-app", @@ -4294,7 +5956,9 @@ "built": { "state": "built", "evidence": "appinfo/info.xml:56", - "owner": "nextcloud/server" + "owner": "nextcloud/server", + "spec": "openspec/specs/platform-baseline", + "requirement": "openspec/specs/platform-baseline :: LaunchPad runs on the organisation's own servers (REQ-PLB-002)" }, "reachedOn": "installed as a Nextcloud app on your own instance", "evidence": { @@ -4306,7 +5970,12 @@ }, "provider": "nextcloud", "providerHow": "read-from-code", - "origin": "own-code" + "feature": "self-hosting", + "origin": "own-code", + "screen": { + "board": null, + "reason": "Hosting op eigen servers, geen scherm." + } }, { "id": "p-theme", @@ -4321,7 +5990,9 @@ "built": { "state": "built", "evidence": "src/views/WorkspaceApp.vue:552", - "owner": "nextcloud/server" + "owner": "nextcloud/server", + "spec": "openspec/specs/platform-baseline", + "requirement": "openspec/specs/platform-baseline :: Every page takes on the organisation's theme (REQ-PLB-003)" }, "reachedOn": "every page; colours come from Nextcloud theming or the NL Design System app", "evidence": { @@ -4333,22 +6004,29 @@ }, "provider": "nextcloud", "providerHow": "read-from-code", - "origin": "own-code" + "feature": "theming-and-languages", + "origin": "own-code", + "screen": { + "board": null, + "reason": "De huisstijl komt uit Nextcloud en thematiq; elk Launchpad-scherm volgt die, er is geen eigen scherm voor." + } }, { "id": "p-custom-css", "area": "platform", "name": "Add your own CSS to restyle the dashboard.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "unknown", "microsoft-viva": "partial", "nextcloud-dashboard": "no", "homarr": "yes", "dashy": "yes", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/platform-dashboard-theme-and-css" + "change": "openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css", + "requirement": "openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards :: Administrators add custom CSS, cleaned and scoped (REQ-THM-003)", + "evidence": "lib/Service/CustomCssSanitiser.php:113 sanitise() drops @import and unsafe values and :233 scopeSelectors() prefixes every selector with the dashboard or workspace scope; lib/Service/CustomCssService.php:84 setGlobalCss() and :104 setDashboardCss() store the cleaned CSS; src/components/admin/AdminCustomCss.vue the admin editor; src/utils/customCss.js inserts it. Tests: tests/Unit/Service/CustomCssSanitiserTest.php, tests/Unit/Service/CustomCssServiceTest.php, src/components/admin/__tests__/AdminCustomCss.spec.js, src/utils/__tests__/customCss.spec.js, tests/e2e/dashboard-look-and-css.spec.ts (passed live 19 Nov 2026)." }, "reachedOn": "nothing", "evidence": { @@ -4360,8 +6038,13 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "theming-and-languages", "origin": "competitor", - "note": "Specified 2026-09-27 in openspec/changes/platform-dashboard-theme-and-css (openspec pass)." + "note": "Specified 2026-09-27 in openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpBeheerAlgemeen" + } }, { "id": "p-background", @@ -4387,6 +6070,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "theming-and-languages", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Nextcloud Dashboard (built-in) rated yes; no tender, feature request or roadmap row. Outside the core area (platform). Reversible: reopen the row if demand appears." }, @@ -4403,7 +6087,10 @@ "built": { "state": "built", "evidence": "l10n/nl.json:2", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/platform-baseline", + "requirement": "openspec/specs/platform-baseline :: Every string is translatable and follows the user's language (REQ-PLB-004)", + "change": "openspec/changes/archive/2026-11-17-fix-l10n-domain-mismatch-mydash-calls" }, "reachedOn": "every page, following the Nextcloud language setting", "evidence": { @@ -4415,9 +6102,13 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboards", - "featureConfidence": "low", - "origin": "own-code" + "feature": "theming-and-languages", + "featureConfidence": "medium", + "origin": "own-code", + "screen": { + "board": null, + "reason": "De taal komt uit de persoonlijke instellingen van Nextcloud; elk scherm volgt die." + } }, { "id": "p-standalone", @@ -4432,13 +6123,15 @@ "built": { "state": "built", "evidence": "appinfo/info.xml:75", - "owner": "ConductionNL/launchpad" + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/runtime-or-consumption", + "requirement": "openspec/specs/runtime-or-consumption :: No install-time OR dependency (REQ-OR-001)" }, "reachedOn": "the app installs and boots with no OpenRegister; OpenRegister-backed widgets are feature-detected", "provider": "launchpad", "providerHow": "read-from-code", - "feature": "runtime-or-consumption", - "featureConfidence": "high", + "feature": "self-hosting", + "featureConfidence": "medium", "origin": "own-code", "evidence": { "nextcloud-dashboard": "source read at v35.0.1: core/shipped.json lists dashboard in shippedApps and defaultEnabled; apps/dashboard/appinfo/info.xml:25 depends only on Nextcloud 35", @@ -4446,6 +6139,10 @@ "dashy": "source read at 4.7.0: Dashy is its own Node and Vue app (server.js, Dockerfile); there is no Nextcloud app (no appinfo/info.xml or PHP in the tree), so it cannot be installed on Nextcloud", "workspace-365": "https://support.workspace365.net/en/articles/175370-workspace-365-configuration-possibilities every version needs SharePoint and Exchange (cloud or on-premises) (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/sharepoint-app-in-teams-overview 'built on the SharePoint home site technology' and Teams; cannot run without them (read 2026-09-26)" + }, + "screen": { + "board": null, + "reason": "Installatie op een kale Nextcloud, geen scherm." } }, { @@ -4472,6 +6169,7 @@ }, "provider": "launchpad", "providerHow": "research-then-code", + "feature": "self-hosting", "origin": "competitor", "note": "Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (platform). Reversible: reopen the row if demand appears." }, @@ -4488,7 +6186,12 @@ "built": { "state": "built", "owner": "ConductionNL/launchpad", - "evidence": "src/modals/WidgetPickerModal.vue:36; lib/Migration/PlacementTableBuilder.php:239" + "evidence": "src/modals/WidgetPickerModal.vue:36; lib/Migration/PlacementTableBuilder.php:239", + "spec": "openspec/specs/widgets", + "requirement": [ + "openspec/specs/calendar-widget :: REQ-CAL-001 Widget registration", + "openspec/specs/news-widget :: REQ-NEWS-001 Widget Registration" + ] }, "reachedOn": "Workspace page, Edit dashboard, Add widget: a widget already placed is only marked as placed and can be added again, each placement with its own settings", "evidence": { @@ -4501,10 +6204,14 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "grid-layout", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "featureRequest", "originUrl": "https://github.com/nextcloud/server/issues/24658", - "note": "A placed widget stays clickable in the picker (WidgetPickerModal.vue:36, :165 isPlaced only styles it) and the placement table has no unique index on dashboard and widget (PlacementTableBuilder.php:239-248)." + "note": "A placed widget stays clickable in the picker (WidgetPickerModal.vue:36, :165 isPlaced only styles it) and the placement table has no unique index on dashboard and widget (PlacementTableBuilder.php:239-248).", + "screen": { + "canvas": "design-system", + "board": "LpBewerken" + } }, { "id": "d-teams", @@ -4530,8 +6237,8 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "nc-dashboard-widget-proxy", + "featureConfidence": "medium", "origin": "featureRequest", "originUrl": "https://github.com/nextcloud/server/issues/22897", "note": "Searched src and lib for circles, teams and ITeamManager: only a 'People & teams' label in src/dialogs/CreateGroupDashboardModal.vue:152, which picks a group dashboard template. No widget shows Nextcloud Teams or their shared resources. Decided no 2026-09-28 (build-all decision pass): No competitor rated yes (Workspace 365, Microsoft Viva Connections partial); a feature request row but the rule needs demand plus one competitor yes. Outside the core area (widgets). Reversible: reopen the row if demand appears." @@ -4561,7 +6268,7 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "dashboard-export-import", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "featureRequest", "originUrl": "https://github.com/nextcloud/server/issues/57423", "note": "Searched lib for IMigrator and UserMigration: LaunchPad registers no user_migration migrator, so a moved account arrives without its dashboards. Admin export and import of dashboards exists (row r-export), which is a different path. Decided no 2026-09-28 (build-all decision pass): No competitor rated yes (Homarr, Dashy partial); a feature request row but the rule needs demand plus one competitor yes. Outside the core area (rollout). Reversible: reopen the row if demand appears." @@ -4577,10 +6284,14 @@ "homarr": "no", "dashy": "yes", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "evidence": "src/components/TileWidget.vue:41", - "change": "openspec/changes/launcher-tile-open-behaviour" + "evidence": "lib/Service/TileLinkTarget.php:54 the three targets (same-tab, new-tab, side-panel), :71 validated() refuses an unknown one and :98 resolve() applies the tile's choice, then the dashboard default, then the link type; lib/Service/DashboardService.php:3815 stores defaultLinkTarget per dashboard; src/utils/tileLinkTarget.js:42 resolveLinkTarget() mirrors it in the page; src/modals/TileEditor.vue:232 the 'Opens in' choice. Tests: tests/Unit/Service/TileLinkTargetTest.php, tests/Unit/Service/DashboardServiceLinkTargetTest.php, src/utils/__tests__/tileLinkTarget.spec.js, src/components/__tests__/TileWidget.linkTarget.spec.js.", + "change": "openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour", + "requirement": [ + "openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles :: A tile carries its own link target (REQ-TOB-001)", + "openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles :: A dashboard sets the default target for its tiles (REQ-TOB-002)" + ] }, "reachedOn": "Workspace page, any tile", "evidence": { @@ -4593,10 +6304,14 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "tiles", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "featureRequest", "originUrl": "https://github.com/nextcloud/server/issues/51332", - "note": "The target is fixed by link type: web-address tiles always open in a new tab and app tiles in the same tab (TileWidget.vue:41). Nobody can choose it per tile, per dashboard or per user. Also mined from https://github.com/homarr-labs/homarr/issues/3778. Specified 2026-09-27 in openspec/changes/launcher-tile-open-behaviour (openspec pass)." + "note": "The target is fixed by link type: web-address tiles always open in a new tab and app tiles in the same tab (TileWidget.vue:41). Nobody can choose it per tile, per dashboard or per user. Also mined from https://github.com/homarr-labs/homarr/issues/3778. Specified 2026-09-27 in openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpTegelBewerken" + } }, { "id": "d-auto-refresh", @@ -4611,7 +6326,9 @@ "built": { "state": "built", "owner": "ConductionNL/launchpad", - "evidence": "src/components/WidgetRenderer.vue:442" + "evidence": "src/components/WidgetRenderer.vue:442", + "spec": "openspec/specs/widgets", + "requirement": "openspec/specs/widgets :: A Nextcloud widget with a reload interval refreshes itself (REQ-WDG-029)" }, "reachedOn": "Workspace page, any Nextcloud widget that declares a reload interval, and live value tiles", "evidence": { @@ -4623,11 +6340,18 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "nc-dashboard-widget-proxy", + "feature": "content-widgets", "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/nextcloud/server/pull/62624", - "note": "Nextcloud widgets that declare reloadInterval are refreshed on a timer (WidgetRenderer.vue:442-447, :536 setupAutoRefresh); live value tiles refresh on their own interval (row w-live-value)." + "note": "Nextcloud widgets that declare reloadInterval are refreshed on a timer (WidgetRenderer.vue:442-447, :536 setupAutoRefresh); live value tiles refresh on their own interval (row w-live-value).", + "screen": { + "canvas": "design-system", + "board": [ + "LpManagement", + "LpWidgetInstellen" + ] + } }, { "id": "d-idp-groups", @@ -4642,7 +6366,9 @@ "built": { "state": "built", "owner": "nextcloud/server", - "evidence": "lib/Service/RuleEvaluatorService.php:125" + "evidence": "lib/Service/RuleEvaluatorService.php:125", + "spec": "openspec/specs/platform-baseline", + "requirement": "openspec/specs/platform-baseline :: Group dashboards follow the groups set at sign-in (REQ-PLB-005)" }, "reachedOn": "every targeting rule and group dashboard; group membership itself comes from the Nextcloud login app", "evidence": { @@ -4654,11 +6380,15 @@ }, "provider": "nextcloud", "providerHow": "read-from-code", - "feature": "conditional-visibility", + "feature": "launchpad-enterprise-security-access", "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/homarr-labs/homarr/releases/tag/v1.66.1", - "note": "LaunchPad targets Nextcloud groups (RuleEvaluatorService.php:125, the same path as row t-groups), and the Nextcloud login apps (user_oidc, user_saml) provision those groups from the identity provider's claims at sign-in. LaunchPad itself holds no group sync; the platform does." + "note": "LaunchPad targets Nextcloud groups (RuleEvaluatorService.php:125, the same path as row t-groups), and the Nextcloud login apps (user_oidc, user_saml) provision those groups from the identity provider's claims at sign-in. LaunchPad itself holds no group sync; the platform does.", + "screen": { + "board": null, + "reason": "Groepslidmaatschap komt bij het aanmelden van de identiteitsprovider, zonder scherm." + } }, { "id": "d-tour", @@ -4673,7 +6403,14 @@ "built": { "state": "built", "owner": "ConductionNL/nextcloud-vue", - "evidence": "src/manifest.json:475" + "evidence": "src/manifest.json:536 (launchpad:admin-getting-started); src/utils/adminWalkthrough.js; live pass 17 Nov 2026 on NC 34: a new administrator opening the LaunchPad admin page got \"Step 1 of 5: General settings\"", + "spec": "openspec/specs/runtime-shell", + "requirement": [ + "openspec/specs/runtime-shell :: REQ-SHELL-010 First-visit tour", + "openspec/specs/runtime-shell :: The admin area has its own first-visit tour (REQ-SHELL-011)" + ], + "plan": "openspec/changes/archive/2026-11-17-record-parity-requirements", + "readOn": "2026-11-17" }, "reachedOn": "Workspace page on first visit, 'Getting started' tour, and again from the help menu", "evidence": { @@ -4685,11 +6422,15 @@ }, "provider": "nextcloud-vue", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "setup-wizard", + "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/homarr-labs/homarr/releases/tag/v1.64.0", - "note": "The manifest declares a first-visit walkthrough (manifest.json:471-500, trigger first-visit, per-user completion key) that the shared shell renders: nextcloud-vue CnAppRoot.vue:464 mounts CnWalkthrough from manifest.walkthrough (nextcloud-vue development d239cf54), and App.vue:16 mounts CnAppRoot." + "note": "The manifest declares a first-visit walkthrough (manifest.json:471-500, trigger first-visit, per-user completion key) that the shared shell renders: nextcloud-vue CnAppRoot.vue:464 mounts CnWalkthrough from manifest.walkthrough (nextcloud-vue development d239cf54), and App.vue:16 mounts CnAppRoot.", + "screen": { + "canvas": "design-system", + "board": "LpEersteKeer" + } }, { "id": "d-pwa", @@ -4704,7 +6445,9 @@ "built": { "state": "built", "owner": "nextcloud/server", - "evidence": "src/views/WorkspaceApp.vue:480" + "evidence": "src/views/WorkspaceApp.vue:480", + "spec": "openspec/specs/platform-baseline", + "requirement": "openspec/specs/platform-baseline :: Pages install on a phone through Nextcloud's web app manifest (REQ-PLB-006)" }, "reachedOn": "any LaunchPad page, through the browser's install option", "evidence": { @@ -4716,29 +6459,35 @@ }, "provider": "nextcloud", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "launchpad-mobile-remote-access", + "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/homarr-labs/homarr/releases/tag/v1.61.0", - "note": "The web app manifest is Nextcloud's: nextcloud/server v35.0.1 apps/theming/lib/Controller/ThemingController.php:459-510 serves a per-app manifest with start_url and display standalone (route /apps/theming/manifest/{app}). LaunchPad adds nothing of its own; the cited LaunchPad line is its use of the theme variables the installed app inherits." + "note": "The web app manifest is Nextcloud's: nextcloud/server v35.0.1 apps/theming/lib/Controller/ThemingController.php:459-510 serves a per-app manifest with start_url and display standalone (route /apps/theming/manifest/{app}). LaunchPad adds nothing of its own; the cited LaunchPad line is its use of the theme variables the installed app inherits.", + "screen": { + "canvas": "design-system", + "board": "LpMobiel" + } }, { "id": "d-rest-api", "area": "governance", "name": "Read and change dashboards through a documented REST API.", - "launchpad": "partial", + "launchpad": "yes", "workspace-365": "partial", "microsoft-viva": "partial", "nextcloud-dashboard": "yes", "homarr": "yes", "dashy": "yes", "built": { - "state": "specified", + "state": "built", + "evidence": "openapi.json:1 (OpenAPI 3.1, every operation with x-launchpad-stability; public ones from :2205) is written by scripts/OpenApiGenerator.php:219 generate() from appinfo/routes.php and the controllers (composer.json:44 openapi:generate), with the response shapes of the public operations in lib/ResponseDefinitions.php:35; composer.json:43 lint:openapi, part of check:strict, fails on an undocumented route (scripts/OpenApiRouteCoverage.php) and on a file regenerating would change (scripts/lint-openapi.php:47). Tests: tests/Unit/Scripts/OpenApiGeneratorTest.php, tests/Unit/Scripts/OpenApiDriftTest.php:94, tests/Unit/Scripts/OpenApiRouteCoverageTest.php, tests/Unit/Middleware/Support/OpenApiStabilityTest.php; docs/features/rest-api.md", "owner": "ConductionNL/launchpad", - "evidence": "appinfo/routes.php:18", - "change": "openspec/changes/governance-rest-api-reference" + "change": "openspec/changes/archive/2026-11-19-governance-rest-api-reference", + "spec": "openspec/specs/rest-api-reference", + "requirement": "openspec/specs/rest-api-reference :: LaunchPad ships a generated OpenAPI reference (REQ-RAPI-001)" }, - "reachedOn": "no documentation page; the JSON routes are what the LaunchPad pages themselves call", + "reachedOn": "docs/features/rest-api.md, and GET /index.php/apps/launchpad/api/v1/openapi.json on a running instance", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175551-api-documentation REST API covers users, groups, memberships, available user apps, announcements, events and activity feed; no endpoints for spaces, tiles or tile groups (read 2026-09-26)", "microsoft-viva": "https://pnp.github.io/pnpcore/using-the-sdk/vivaconnections-intro.html PnP Core SDK 'GetVivaDashboard', 'AddACE', 'UpdateACE', 'RemoveACE' read and change the dashboard; that is a community .NET SDK, no Microsoft-documented dashboard REST endpoint found on learn.microsoft.com (read 2026-09-26)", @@ -4748,11 +6497,15 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "admin-tooling", + "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/homarr-labs/homarr/releases/tag/v1.50.0", - "note": "LaunchPad exposes about 180 JSON routes (appinfo/routes.php) that work with a Nextcloud app password, but ships no OpenAPI file or public API reference (searched the repo for openapi: only the OpenRegister register files). Usable, not documented. Also mined from https://github.com/Lissy93/dashy/releases/tag/4.4.0. Specified 2026-09-27 in openspec/changes/governance-rest-api-reference (openspec pass)." + "note": "LaunchPad exposes about 180 JSON routes (appinfo/routes.php) that work with a Nextcloud app password, but ships no OpenAPI file or public API reference (searched the repo for openapi: only the OpenRegister register files). Usable, not documented. Also mined from https://github.com/Lissy93/dashy/releases/tag/4.4.0. Specified 2026-09-27 in openspec/changes/archive/2026-11-19-governance-rest-api-reference (openspec pass). Built 2026-11-19 (#1351): a generated OpenAPI 3.1 reference with a drift check in check:strict.", + "screen": { + "board": null, + "reason": "Een REST-API voor andere systemen, zonder scherm." + } }, { "id": "d-proxy", @@ -4767,7 +6520,12 @@ "built": { "state": "built", "owner": "ConductionNL/launchpad", - "evidence": "lib/Service/LiveTileService.php:455" + "evidence": "lib/Service/LiveTileService.php:455", + "spec": "openspec/specs/background-job-feed-refresh", + "requirement": [ + "openspec/specs/background-job-feed-refresh :: REQ-FRJ-012 User-Agent and Proxy Configuration", + "openspec/specs/platform-baseline :: Outbound requests use the server's proxy setting (REQ-PLB-008)" + ] }, "reachedOn": "every widget that fetches from outside: news, calendar feeds, live tiles, weather, health pings, iframe checks", "evidence": { @@ -4779,11 +6537,15 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "live-data-tile-widget", - "featureConfidence": "medium", + "feature": "runtime-or-consumption", + "featureConfidence": "high", "origin": "changelog", "originUrl": "https://github.com/homarr-labs/homarr/releases/tag/v1.48.0", - "note": "Every outbound fetch goes through Nextcloud's IClientService (LiveTileService.php:455, NewsWidgetService.php:135, CalendarWidgetService.php:119, WeatherService, HealthPingService, IframeService.php:94, FeedRefreshService), which applies the server's proxy setting from config.php. Searched lib for curl_, file_get_contents and new Client: none." + "note": "Every outbound fetch goes through Nextcloud's IClientService (LiveTileService.php:455, NewsWidgetService.php:135, CalendarWidgetService.php:119, WeatherService, HealthPingService, IframeService.php:94, FeedRefreshService), which applies the server's proxy setting from config.php. Searched lib for curl_, file_get_contents and new Client: none. Specified 12 Nov 2026 as REQ-PLB-008 (record-parity-requirements): REQ-FRJ-012 covers the feed refresh job only.", + "screen": { + "board": null, + "reason": "Uitgaande verzoeken gebruiken de proxy-instelling van de server, zonder scherm." + } }, { "id": "d-single-logout", @@ -4809,8 +6571,8 @@ }, "provider": "nextcloud", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "launchpad-enterprise-security-access", + "featureConfidence": "medium", "origin": "featureRequest", "originUrl": "https://github.com/homarr-labs/homarr/issues/5154", "note": "not checked: single logout is the Nextcloud login app's job (user_oidc or user_saml), which was not read in this pass; LaunchPad has no logout code of its own (searched src and lib for logout and end_session). Decided no on 2026-09-27 (openspec pass): Owed to nextcloud/server: single logout is done by the Nextcloud login apps (user_oidc, user_saml), not by LaunchPad. Platform-provided, outside the fleet." @@ -4819,16 +6581,19 @@ "id": "d-import-bookmarks", "area": "launcher", "name": "Import browser bookmarks as tiles.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "unknown", "microsoft-viva": "unknown", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-bookmark-import" + "change": "openspec/changes/archive/2026-11-17-launcher-bookmark-import", + "requirement": "openspec/specs/tiles :: Users can import a browser bookmarks file as tiles (REQ-BMI-001)", + "evidence": "lib/Controller/BookmarkImportController.php:79; lib/Service/PlacementService.php:368; src/modals/BookmarkImportModal.vue; live pass 17 Nov 2026: tests/e2e/bookmark-import.spec.ts passed on NC 34", + "readOn": "2026-11-17" }, "reachedOn": "nothing", "evidence": { @@ -4841,27 +6606,39 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "tiles", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "featureRequest", "originUrl": "https://github.com/homarr-labs/homarr/issues/1014", - "note": "Searched src and lib for bookmark import, netscape and html import: no importer for browser bookmark files; tiles are made one at a time or arrive through dashboard import (row r-export). Specified 2026-09-27 in openspec/changes/launcher-bookmark-import (openspec pass)." + "note": "Searched src and lib for bookmark import, netscape and html import: no importer for browser bookmark files; tiles are made one at a time or arrive through dashboard import (row r-export). Specified 2026-09-27 in openspec/changes/launcher-bookmark-import (openspec pass). Built since and archived 2026-11-17; the search above is from before that.", + "screen": { + "canvas": "design-system", + "board": "LpTegelToevoegen" + } }, { "id": "d-notes", "area": "widgets", "name": "Keep personal notes on the start page.", - "launchpad": "partial", + "launchpad": "yes", "workspace-365": "unknown", "microsoft-viva": "unknown", "nextcloud-dashboard": "no", "homarr": "yes", "dashy": "no", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/nextcloud-vue", - "evidence": "lib/widget-types.json:37" + "evidence": "nextcloud-vue src/components/CnNotepadWidget/CnNotepadWidget.vue and CnNotepadWidgetForm (main 0d69eaf48), type `notepad` registered userAddable in CnNotepadWidget/index.js and shipped since @conduction/nextcloud-vue 2.90.0; launchpad's package.json asks ^2.180.0 and package-lock.json pins 2.180.0; launchpad offers it through src/constants/widgetRegistry.js offerableTypes() (cnListWidgetTypes('app-dashboard'))", + "change": "nextcloud-vue/dashboard-notepad-widget", + "spec": "nextcloud-vue/grid-widget-system", + "requirement": [ + "nextcloud-vue:openspec/changes/dashboard-notepad-widget/specs/grid-widget-system/spec.md :: A notepad widget is typed into in place", + "nextcloud-vue:openspec/changes/dashboard-notepad-widget/specs/grid-widget-system/spec.md :: A note belongs to the person who wrote it", + "nextcloud-vue:openspec/changes/dashboard-notepad-widget/specs/grid-widget-system/spec.md :: A user may add a notepad to their own dashboard" + ], + "readOn": "2026-10-30" }, - "reachedOn": "Workspace page, Add widget, Text, on a personal dashboard", + "reachedOn": "Workspace page, Add widget, Notepad, on a personal dashboard", "evidence": { "workspace-365": "not checked: live tile integrations collection (support.workspace365.net/en/collections/791485) and user guide 175363 list no personal notes tile; the text editor tile (480271) is admin content (read 2026-09-26)", "microsoft-viva": "not checked: https://learn.microsoft.com/en-us/sharepoint/homesites/available-dashboard-cards toolbox lists no notes card (card designer, Approvals, Assigned tasks, Events, Folder, My Sites, News, OneDrive, People, Power Apps, Quick links, Shifts, Stay Engaged, Stream, Teams app, Learning, Pulse, Web link) (read 2026-09-26)", @@ -4871,28 +6648,34 @@ }, "provider": "nextcloud-vue", "providerHow": "read-from-code", - "feature": "text-display-widget", - "featureConfidence": "medium", + "feature": "content-widgets", + "featureConfidence": "high", "origin": "featureRequest", "originUrl": "https://github.com/Lissy93/dashy/issues/636", - "note": "A text widget on your own dashboard can hold notes (widget-types.json:37, rendered by nextcloud-vue), but it is edited in dashboard edit mode, not a quick notepad you type into in place. Specified in ConductionNL/nextcloud-vue openspec/changes/dashboard-notepad-widget (nextcloud-vue lane, OpenSpec pass 2026-09-27)." + "note": "A text widget on your own dashboard can hold notes (widget-types.json:37, rendered by nextcloud-vue), but it is edited in dashboard edit mode, not a quick notepad you type into in place. Specified in ConductionNL/nextcloud-vue openspec/changes/dashboard-notepad-widget (nextcloud-vue lane, OpenSpec pass 2026-09-27).", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "d-internal-url", "area": "launcher", "name": "A tile opens the internal address on the office network and the public one elsewhere.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "partial", "microsoft-viva": "unknown", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "yes", "built": { - "state": "specified", + "state": "built", + "evidence": "lib/Service/OfficeNetworkService.php:69 isOfficeRequest() matches IRequest::getRemoteAddress() against the stored office networks through OCP\\Security\\Ip\\IFactory; lib/Service/AdminSettingsService.php:179-183 answers officeNetworks, currentAddress and currentAddressInOfficeNetworks and lib/Controller/AdminController.php:476 refuses a malformed range with 400; lib/Controller/PageController.php:200 provides onOfficeNetwork through lib/Service/InitialStateBuilder.php:445; lib/Service/TileUpdater.php:192 validates content.internalUrl; src/components/TileWidget.vue:209-224 opens the internal address only on the office network; src/modals/TileEditor.vue:223 'Address on the office network' and :494 the address-in-effect line; src/components/admin/AdminSettings.vue:261 the 'Office networks' section. Tests: tests/Unit/Service/OfficeNetworkServiceTest.php, tests/Unit/Service/TileUpdaterTest.php, src/components/__tests__/TileWidget.officeNetwork.spec.js, src/modals/__tests__/TileEditor.officeNetwork.spec.js, src/components/admin/__tests__/AdminSettings.officeNetworks.spec.js, tests/e2e/launcher-tile-internal-address.spec.ts", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-tile-internal-address" + "change": "openspec/changes/archive/2026-11-19-launcher-tile-internal-address", + "requirement": "openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles :: The tile opens the address that fits the network (REQ-TIA-003)" }, - "reachedOn": "nothing", + "reachedOn": "Workspace page, Edit tile, Address on the office network; office networks on the LaunchPad admin page, General tab", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175495-conditional-access 'With IP ranges you can choose on which IP range(s) the app is available ... e.g. the company network' and the same app can be offered locally or as a remote app; one tile with an internal and a public address is not documented (read 2026-09-26)", "microsoft-viva": "not checked: https://learn.microsoft.com/en-us/sharepoint/homesites/available-dashboard-cards Web link and Quick links cards take one URL per link; no network-dependent address found (read 2026-09-26)", @@ -4903,10 +6686,14 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "tiles", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "changelog", "originUrl": "https://github.com/Lissy93/dashy/releases/tag/4.4.0", - "note": "A tile holds one address (TileWidget.vue:41 and :158 split only Nextcloud-internal paths from external URLs); searched src and lib for internal, external and network-aware URLs: nothing picks an address by the network you are on. Specified 2026-09-27 in openspec/changes/launcher-tile-internal-address (openspec pass)." + "note": "A tile holds one address (TileWidget.vue:41 and :158 split only Nextcloud-internal paths from external URLs); searched src and lib for internal, external and network-aware URLs: nothing picks an address by the network you are on. Specified 2026-09-27 in openspec/changes/archive/2026-11-19-launcher-tile-internal-address (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpTegelBewerken" + } }, { "id": "d-theme-per-dashboard", @@ -4919,10 +6706,15 @@ "homarr": "partial", "dashy": "yes", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "evidence": "lib/Migration/DashboardTableBuilder.php:173", - "change": "openspec/changes/platform-dashboard-theme-and-css" + "evidence": "lib/Service/DashboardLook.php:148 assertAccentReadable() refuses an accent under 3:1 on the background and :128 textColorFor() picks the text colour; lib/Migration/Version002014Date20261114120000.php adds the look columns; src/modals/DashboardConfigModal.vue:197-204 the Look panel (accent, background colour, background image) of one dashboard; src/utils/dashboardLook.js scopes the look to that dashboard's region. Tests: tests/Unit/Service/DashboardLookTest.php, tests/Unit/Service/DashboardServiceLookTest.php, src/modals/__tests__/DashboardConfigModal.look.spec.js, src/utils/__tests__/dashboardLook.spec.js, tests/e2e/dashboard-look-and-css.spec.ts (passed live 19 Nov 2026).", + "change": "openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css", + "requirement": [ + "openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards :: Each dashboard can have its own look (REQ-THM-001)", + "openspec/specs/dashboard-language-content :: The workspace page shows the reader's language (REQ-LANGUI-002)", + "openspec/specs/dashboards :: Update Dashboard (REQ-DASH-004)" + ] }, "reachedOn": "Workspace page, dashboard settings", "evidence": { @@ -4934,11 +6726,15 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "dashboards", + "feature": "theming-and-languages", "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/Lissy93/dashy/releases/tag/4.0.0", - "note": "Each dashboard carries its own grid_columns (DashboardTableBuilder.php:173) and has per-language content variants in the backend (lib/Db/DashboardTranslation.php:6, no page reaches them, row dash-languages), but there is no theme, colour or background per dashboard (dashboard columns at DashboardTableBuilder.php:75-255). Specified 2026-09-27 in openspec/changes/platform-dashboard-theme-and-css (openspec pass)." + "note": "Each dashboard carries its own grid_columns (DashboardTableBuilder.php:173) and has per-language content variants in the backend (lib/Db/DashboardTranslation.php:6, no page reaches them, row dash-languages), but there is no theme, colour or background per dashboard (dashboard columns at DashboardTableBuilder.php:75-255). Specified 2026-09-27 in openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpDashboardInstellingen" + } }, { "id": "d-open-inside", @@ -4951,10 +6747,11 @@ "homarr": "partial", "dashy": "yes", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "evidence": "src/components/Widgets/Renderers/IframeWidget.vue:38", - "change": "openspec/changes/launcher-tile-open-behaviour" + "evidence": "src/components/Workspace/TileSidePanel.vue the panel beside the tiles (close button, Escape with focus back on the tile, one panel at a time, framing check with the 'Open in new tab' fallback), mounted in src/views/WorkspaceApp.vue:107; src/stores/tilePanel.js the one panel the tiles open. Tests: src/components/Workspace/__tests__/TileSidePanel.spec.js, src/stores/__tests__/tilePanel.spec.js, tests/e2e/tile-side-panel.spec.ts (passed live 19 Nov 2026).", + "change": "openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour", + "requirement": "openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles :: A tile can open its app in a panel beside the tiles (REQ-TOB-003)" }, "reachedOn": "Workspace page, Add widget, Embed", "evidence": { @@ -4966,11 +6763,15 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "iframe-embed-widget", + "feature": "tiles", "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/Lissy93/dashy/releases/tag/3.2.0", - "note": "An embed widget shows another site inside the dashboard (IframeWidget.vue:38, host allow-list, row w-embed), but a tile cannot open its app in a side panel next to the tiles; tiles navigate away or open a new tab (TileWidget.vue:41). Specified 2026-09-27 in openspec/changes/launcher-tile-open-behaviour (openspec pass)." + "note": "An embed widget shows another site inside the dashboard (IframeWidget.vue:38, host allow-list, row w-embed), but a tile cannot open its app in a side panel next to the tiles; tiles navigate away or open a new tab (TileWidget.vue:41). Specified 2026-09-27 in openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpTegelBewerken" + } }, { "id": "d-search-prefix", @@ -4983,11 +6784,13 @@ "homarr": "yes", "dashy": "yes", "built": { - "state": "specified", + "state": "built", + "evidence": "lib/Service/SearchShortcutService.php; src/composables/useTileSearch.js (parsePrefix); src/components/RuntimeShellSearch.vue; src/components/admin/tabs/SearchShortcutsTab.vue", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/search-ai-prefix-shortcuts" + "change": "openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts", + "requirement": "openspec/changes/archive/2026-09-30-search-ai-prefix-shortcuts/specs/tile-quick-search :: A prefix sends the query to its site (REQ-SPX-002)" }, - "reachedOn": "nothing", + "reachedOn": "Any search widget: type !t printer (a prefix the administrator set under Admin settings > LaunchPad > Search shortcuts) or ? for the list", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175653-global-search users 'search by category' (Announcements, Apps, Email, Files, Folders, Knowledge articles, People, plus OpenIMS or Egnyte when configured); no prefix syntax to send a query to another site (read 2026-09-26)", "microsoft-viva": "not checked: Microsoft 365 roadmap 562015 'Scoped Search for SharePoint app in Teams' scopes search to SharePoint global search (cached roadmap, read 2026-09-26); no prefix to an external site found", @@ -4997,11 +6800,15 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "nc-unified-search-integration", + "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/Lissy93/dashy/releases/tag/3.2.0", - "note": "The search widget filters tiles and falls back to one configured web search per widget (SearchWidget.vue:178 onSearchFallback, SearchWidgetForm.vue:41); searched for prefix, bang and engine routing: none. Specified 2026-09-27 in openspec/changes/search-ai-prefix-shortcuts (openspec pass)." + "note": "The search widget filters tiles and falls back to one configured web search per widget (SearchWidget.vue:178 onSearchFallback, SearchWidgetForm.vue:41); searched for prefix, bang and engine routing: none. Specified 2026-09-27 in openspec/changes/search-ai-prefix-shortcuts (openspec pass).", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "d-dark-mode", @@ -5016,7 +6823,9 @@ "built": { "state": "built", "owner": "nextcloud/server", - "evidence": "src/views/WorkspaceApp.vue:480" + "evidence": "src/views/WorkspaceApp.vue:480", + "spec": "openspec/specs/platform-baseline", + "requirement": "openspec/specs/platform-baseline :: Pages follow light or dark mode (REQ-PLB-007)" }, "reachedOn": "every page", "evidence": { @@ -5028,26 +6837,33 @@ }, "provider": "nextcloud", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "theming-and-languages", + "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://github.com/Lissy93/dashy/releases/tag/3.2.0", - "note": "LaunchPad draws with Nextcloud's theme variables (WorkspaceApp.vue:480, :500), and Nextcloud's theming app switches them by the device's colour scheme through media-query themes (nextcloud/server v35.0.1 apps/theming/lib/Service/ThemeInjectionService.php:39-48). Also mined from https://www.microsoft.com/releasecommunications/api/v1/m365." + "note": "LaunchPad draws with Nextcloud's theme variables (WorkspaceApp.vue:480, :500), and Nextcloud's theming app switches them by the device's colour scheme through media-query themes (nextcloud/server v35.0.1 apps/theming/lib/Service/ThemeInjectionService.php:39-48). Also mined from https://www.microsoft.com/releasecommunications/api/v1/m365.", + "screen": { + "board": null, + "reason": "Licht of donker volgt het apparaat en de Nextcloud-instelling; elk scherm volgt die." + } }, { "id": "d-tile-sort", "area": "launcher", "name": "Choose how tiles in a group are sorted, such as alphabetically, by last use or at random.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "unknown", "microsoft-viva": "unknown", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "yes", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/launcher-tile-sorting" + "change": "openspec/changes/archive/2026-11-17-launcher-tile-sorting", + "requirement": "openspec/specs/container-widget :: A container sorts its tiles when viewed (REQ-TSO-001)", + "evidence": "src/components/Widgets/Renderers/ContainerWidget.vue:162; src/utils/tileSort.js:171; live pass 17 Nov 2026: tests/e2e/container-tile-sorting.spec.ts 2 passed on NC 34", + "readOn": "2026-11-17" }, "reachedOn": "nothing", "evidence": { @@ -5060,10 +6876,14 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "tiles", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "changelog", "originUrl": "https://github.com/Lissy93/dashy/releases/tag/4.6.0", - "note": "Tiles sit where they were placed on the grid; searched TileWidget, the links and quick links widgets for sortBy, sortOrder and sortMode: none. Only the people widget has a sort (PeopleWidget.vue:120). Specified 2026-09-27 in openspec/changes/launcher-tile-sorting (openspec pass)." + "note": "Tiles sit where they were placed on the grid; searched TileWidget, the links and quick links widgets for sortBy, sortOrder and sortMode: none. Only the people widget has a sort (PeopleWidget.vue:120). Specified 2026-09-27 in openspec/changes/launcher-tile-sorting (openspec pass). Built since and archived 2026-11-17; the search above is from before that.", + "screen": { + "canvas": "design-system", + "board": "LpTegelBewerken" + } }, { "id": "d-ai-write", @@ -5089,8 +6909,8 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "launchpad-ai-dashboard-assistant", + "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://support.workspace365.net/en/articles/747342-release-notes-workspace-365-v4-45", "note": "Searched src and lib for assistant, TextProcessing and ITaskProcessing: no writing help. LaunchPad has no announcement editor to attach one to (row e-announcements is no). Decided no 2026-09-28 (build-all decision pass): Single competitor, no demand: Workspace 365 rated yes; no tender, feature request or roadmap row. Outside the core area (search-ai). Reversible: reopen the row if demand appears." @@ -5119,7 +6939,7 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "calendar-widget", + "feature": "launchpad-meeting-calendar-actions", "featureConfidence": "medium", "origin": "changelog", "originUrl": "https://support.workspace365.net/en/articles/747342-release-notes-workspace-365-v4-45", @@ -5136,12 +6956,13 @@ "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "lib/Service/ProfileFieldService.php; lib/Service/PeopleWidgetService.php (searchCandidates); @conduction/nextcloud-vue CnPeopleWidget (searchPeople via src/services/widgetDataAdapters.js); src/views/settings/ProfileFieldsSettings.vue; src/components/admin/tabs/ProfileFieldsTab.vue", "owner": "ConductionNL/launchpad", - "evidence": "lib/Service/PeopleWidgetService.php:91", - "change": "openspec/changes/widgets-people-expertise-and-fields" + "change": "openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields", + "requirement": "openspec/specs/people-widget :: Administrators define custom profile fields (REQ-PEX-001)" }, - "reachedOn": "Workspace page, Add widget, People", + "reachedOn": "People widget cards show custom fields; Personal settings > Personal info > LaunchPad profile; Admin settings > LaunchPad > Profile fields", "evidence": { "workspace-365": "v4.46 (2026-08-19) 'map up to five fields from Entra ID to custom fields in Workspace 365' (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/available-dashboard-cards People card reads contact information from Entra ID; custom fields not described (read 2026-09-26)", @@ -5152,25 +6973,32 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "people-widget", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "changelog", "originUrl": "https://support.workspace365.net/en/articles/766599-release-notes-workspace-365-v4-46", - "note": "The people widget shows the standard Nextcloud profile fields (PeopleWidgetService.php:91-103: phone, address, organisation, role, headline, biography, pronouns, birthdate), which a login app can fill from the identity provider. No custom fields such as office location or cost centre. Specified 2026-09-27 in openspec/changes/widgets-people-expertise-and-fields (openspec pass)." + "note": "Built 30 Sep 2026 (archived change widgets-people-expertise-and-fields): administrators define up to 10 custom profile fields, filled by the person or read from LDAP (lib/Service/ProfileFieldService.php, src/components/admin/tabs/ProfileFieldsTab.vue), and the people widget shows them (PeopleWidgetService.php visibleFieldsFor). Before that the widget showed only the standard Nextcloud profile fields.", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } }, { "id": "d-news-preview", "area": "engagement", "name": "Preview a news item before it is published.", - "launchpad": "no", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "yes", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "src/modals/AnnouncementEditorModal.vue:65; lib/Controller/AnnouncementController.php:188", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/engagement-announcements" + "change": "openspec/changes/archive/2026-11-17-engagement-announcements", + "requirement": "openspec/specs/announcements :: Authors preview before publishing (REQ-ANN-004)", + "readOn": "2026-11-17" }, "reachedOn": "nothing", "evidence": { @@ -5182,11 +7010,15 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": "news-widget", + "feature": "news-and-announcements", "featureConfidence": "medium", "origin": "roadmap", "originUrl": "https://portal.productboard.com/iqfsnhkpzih6grzjwagif2ek/tabs/3-launched", - "note": "LaunchPad reads outside news feeds (row w-news) and has no news authoring (row e-announcements is no), so there is nothing to preview before publishing. Specified 2026-09-27 in openspec/changes/engagement-announcements (openspec pass)." + "note": "LaunchPad reads outside news feeds (row w-news) and has no news authoring (row e-announcements is no), so there is nothing to preview before publishing. Specified 2026-09-27 in openspec/changes/engagement-announcements (openspec pass). Built since and archived 2026-11-17.", + "screen": { + "canvas": "design-system", + "board": "LpAankondiging" + } }, { "id": "d-recurring-events", @@ -5212,8 +7044,8 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "communities-events-and-knowledge", + "featureConfidence": "medium", "origin": "roadmap", "originUrl": "https://portal.productboard.com/iqfsnhkpzih6grzjwagif2ek/tabs/4-planned", "note": "LaunchPad runs no internal events (row e-events is no); the calendar widget only reads calendars. Decided no 2026-09-28 (build-all decision pass): No competitor rated yes (Nextcloud Dashboard (built-in), Homarr, Dashy partial); a roadmap row but the rule needs demand plus one competitor yes. Outside the core area (engagement). Reversible: reopen the row if demand appears." @@ -5242,8 +7074,8 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "communities-events-and-knowledge", + "featureConfidence": "medium", "origin": "roadmap", "originUrl": "https://portal.productboard.com/iqfsnhkpzih6grzjwagif2ek/tabs/4-planned", "note": "Searched src and lib for review reminders, owner reminders and content expiry: none. Dashboards have a publication status (DashboardTableBuilder.php:435) but nobody is reminded to review them. Decided no 2026-09-28 (build-all decision pass): No competitor rated yes; a roadmap row but the rule needs demand plus one competitor yes. Outside the core area (governance). Reversible: reopen the row if demand appears." @@ -5272,8 +7104,8 @@ }, "provider": "launchpad", "providerHow": "read-from-code", - "feature": null, - "featureConfidence": "low", + "feature": "kpi-cards", + "featureConfidence": "medium", "origin": "roadmap", "originUrl": "https://www.microsoft.com/releasecommunications/api/v1/m365", "note": "Charts are configured by hand over OpenRegister data (row w-charts); the AI dashboard assistant spec exists (openspec/specs/launchpad-ai-dashboard-assistant) but no page reaches it (row a-place-widget is no). Decided no 2026-09-28 (build-all decision pass): No competitor rated yes (Microsoft Viva Connections, Homarr partial); a roadmap row but the rule needs demand plus one competitor yes. Outside the core area (widgets). Reversible: reopen the row if demand appears." @@ -5282,18 +7114,22 @@ "id": "d-work-queue", "area": "widgets", "name": "See your own open cases and work items on the start page and click through to the work queue.", - "launchpad": "partial", + "launchpad": "yes", "workspace-365": "yes", "microsoft-viva": "yes", "nextcloud-dashboard": "no", "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/dossiq", - "evidence": "src/services/widgetBridge.js:29" + "evidence": "dossiq lib/Dashboard/MyOpenWorkWidget.php (widget id dossiq_my_open_work_widget, development 304c18ee7), placed in LaunchPad as an nc-widget placement (src/services/widgetBridge.js:29, specs/widgets REQ-WDG-018)", + "change": "dossiq/widgets-my-open-cases-on-the-start-page", + "spec": "dossiq/dashboard", + "requirement": "dossiq:openspec/specs/dashboard :: My open work is a start page widget that any dashboard can render (REQ-DASH-023)", + "readOn": "2026-10-30" }, - "reachedOn": "Workspace page, Add widget, Nextcloud widget, a case app's own widget, with that app installed", + "reachedOn": "Workspace page, Add widget, Nextcloud widget, dossiq's \"My open work\" widget, with dossiq installed", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175605-zaaksysteem live tile shows 'My open cases' and 'My suspended cases' with counts; 'Click on Zaaksysteem at the bottom of the live tile to navigate to Zaaksysteem itself'; TOPdesk tile shows the user's own tickets (175599) (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/sharepoint/homesites/available-dashboard-cards Assigned tasks card lets users 'create and view tasks from the card or open the Planner app'; Approvals card shows 'the ones sent your way' (read 2026-09-26)", @@ -5304,28 +7140,112 @@ "provider": "dossiq", "providerHow": "read-from-code", "feature": "nc-dashboard-widget-proxy", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "tender", "originUrl": "https://www.tenderned.nl/aankondigingen/overzicht/296963", - "note": "LaunchPad has no work queue of its own; it can show a case app's Nextcloud widget. dossiq registers 'My tasks' and 'Cases overview' widgets (ConductionNL/dossiq development 00869dd7 lib/AppInfo/Registrar/AppHostRegistrar.php:126-132, lib/Dashboard/MyTasksWidget.php:42 a legacy IWidget) and LaunchPad's bridge catches OCA.Dashboard.register for such widgets (widgetBridge.js:29-62). Whether they render end to end is pending q-sibling-widgets. Also mined from https://www.tenderned.nl/aankondigingen/overzicht/237144, https://www.tenderned.nl/aankondigingen/overzicht/416075. Tender text: Noorderzijlvest 2023: 'Startscherm/medewerkersportaal met doorklik naar werkvoorraad'; Nationale ombudsman 2021: 'persoonlijk dashboard ... Overzicht lopende (eigen) zaken'; Súdwest-Fryslân 2026: dashboard with 'alle openstaande signaleringen, actiepunten, issues' at a glance, set up by the user with widgets. Specified 2026-09-27 (openspec pass, coordinator) in ConductionNL/dossiq openspec/changes/widgets-my-open-cases-on-the-start-page." + "note": "LaunchPad has no work queue of its own; it can show a case app's Nextcloud widget. dossiq registers 'My tasks' and 'Cases overview' widgets (ConductionNL/dossiq development 00869dd7 lib/AppInfo/Registrar/AppHostRegistrar.php:126-132, lib/Dashboard/MyTasksWidget.php:42 a legacy IWidget) and LaunchPad's bridge catches OCA.Dashboard.register for such widgets (widgetBridge.js:29-62). Whether they render end to end is pending q-sibling-widgets. Also mined from https://www.tenderned.nl/aankondigingen/overzicht/237144, https://www.tenderned.nl/aankondigingen/overzicht/416075. Tender text: Noorderzijlvest 2023: 'Startscherm/medewerkersportaal met doorklik naar werkvoorraad'; Nationale ombudsman 2021: 'persoonlijk dashboard ... Overzicht lopende (eigen) zaken'; Súdwest-Fryslân 2026: dashboard with 'alle openstaande signaleringen, actiepunten, issues' at a glance, set up by the user with widgets. Specified 2026-09-27 (openspec pass, coordinator) in ConductionNL/dossiq openspec/changes/widgets-my-open-cases-on-the-start-page.", + "screen": { + "canvas": "design-system", + "board": "LpVandaag" + } + }, + { + "id": "w-attention", + "area": "widgets", + "name": "See what needs your attention today from all your apps in one ranked list.", + "launchpad": "yes", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "built", + "evidence": "lib/Controller/AttentionController.php:39; src/constants/widgetRegistry.js:176; live pass 17 Nov 2026: with pipelinq 0.5.21 on NC 34, First today listed a member's overdue ticket with a link that opens the list", + "owner": "ConductionNL/launchpad", + "spec": "openspec/specs/attention-feed", + "requirement": "openspec/specs/attention-feed :: REQ-ATT-004 Merging and ranking", + "change": "openspec/changes/archive/2026-11-17-cross-app-attention-feed" + }, + "reachedOn": "Workspace page, Add widget, First today", + "source": "spec-round-2026-10-07", + "feature": "nc-dashboard-widget-proxy", + "screen": { + "canvas": "design-system", + "board": "LpVandaag" + } + }, + { + "id": "w-menu", + "area": "widgets", + "name": "Put a navigation menu with nested links on a dashboard.", + "launchpad": "yes", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "built", + "evidence": "lib/widget-types.json:28; src/components/WidgetRenderer.vue:10", + "owner": "ConductionNL/nextcloud-vue", + "change": "openspec/changes/archive/2026-05-03-menu-widget", + "requirement": "openspec/specs/menu-widget :: REQ-MENU-001 Widget registration and default structure" + }, + "reachedOn": "Workspace page, Add widget, Menu", + "source": "spec-round-2026-10-07", + "feature": "organisation-navigation", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } + }, + { + "id": "w-quicklinks", + "area": "widgets", + "name": "Show a compact grid of icon shortcuts in one widget.", + "launchpad": "yes", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "built", + "evidence": "lib/widget-types.json:33; src/components/WidgetRenderer.vue:9", + "owner": "ConductionNL/nextcloud-vue", + "change": "openspec/changes/archive/2026-05-03-quicklinks-widget", + "requirement": [ + "openspec/specs/quicklinks-widget :: REQ-QLNK-001 Registration and widget id", + "openspec/specs/quicklinks-widget :: REQ-QLNK-006 Column layout flexibility" + ] + }, + "reachedOn": "Workspace page, Add widget, Quick links", + "source": "spec-round-2026-10-07", + "feature": "tiles", + "screen": { + "canvas": "design-system", + "board": "LpWerkplek" + } }, { "id": "d-public-start", "area": "sharing", "name": "Visitors who have not signed in see a public start page instead of the login screen.", - "launchpad": "partial", + "launchpad": "yes", "workspace-365": "unknown", "microsoft-viva": "unknown", "nextcloud-dashboard": "no", "homarr": "yes", "dashy": "yes", "built": { - "state": "specified", + "state": "built", "owner": "ConductionNL/launchpad", - "evidence": "appinfo/routes.php:189", - "change": "openspec/changes/sharing-public-start-page" + "evidence": "lib/Listener/PublicStartRedirectListener.php:117; live pass 17 Nov 2026: tests/e2e/public-start-page.spec.ts 3 passed on NC 34", + "change": "openspec/changes/archive/2026-11-17-sharing-public-start-page", + "requirement": "openspec/specs/dashboard-public-share :: Signed-out visitors land on the start page (REQ-PSP-002)" }, - "reachedOn": "a public share link (/apps/launchpad/s/<token>), not the address signed-out visitors land on", + "reachedOn": "the Nextcloud address: a signed-out visitor on the plain login page goes to /apps/launchpad/start (lib/Listener/PublicStartRedirectListener.php:117, lib/Controller/PageController.php:570), which shows the chosen public link with a Sign in bar (src/views/DashboardPublicShareView.vue)", "evidence": { "workspace-365": "not checked: https://support.workspace365.net/en/articles/697783-use-workspace-365-as-relatives-portal even visitors get Entra guest accounts and sign in; no public page described; branding 175374 says 'It is not possible to brand the landing page' (read 2026-09-26)", "microsoft-viva": "not checked: https://learn.microsoft.com/en-us/sharepoint/homesites/sharepoint-app-in-teams-overview describes access through Teams or the SharePoint home site with Entra identities; no anonymous start page found and no explicit statement of absence (read 2026-09-26)", @@ -5336,10 +7256,14 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "dashboard-public-share", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "tender", "originUrl": "https://www.publicprocurement.be/nl/publication-workspaces/204ca8ae-6191-43b9-ac3b-c943f91d1d2d", - "note": "A dashboard can be published read-only on a public link (routes.php:189-212, PublicShareController.php:248 #[PublicPage]), but signed-out visitors at the Nextcloud address still get the login page; nothing makes a public dashboard the start page for them. Tender text: VVSG Blink 2025: 'Er is een publieke startpagina die kan aangepast worden en die verschilt van de inlogpagina'. Specified 2026-09-27 in openspec/changes/sharing-public-start-page (openspec pass)." + "note": "A dashboard can be published read-only on a public link (routes.php:189-212, PublicShareController.php:248 #[PublicPage]), but signed-out visitors at the Nextcloud address still get the login page; nothing makes a public dashboard the start page for them. Tender text: VVSG Blink 2025: 'Er is een publieke startpagina die kan aangepast worden en die verschilt van de inlogpagina'. Specified 2026-09-27 in openspec/changes/sharing-public-start-page (openspec pass). Built 2026-11-14: the administrator picks a public link without a password on the Sharing tab (src/components/admin/PublicStartPageSettings.vue), the login page sends signed-out visitors to /start, and deep links keep their login form.", + "screen": { + "canvas": "design-system", + "board": "LpPubliek" + } }, { "id": "d-find-expert", @@ -5352,11 +7276,13 @@ "homarr": "no", "dashy": "no", "built": { - "state": "specified", + "state": "built", + "evidence": "lib/Service/ProfileFieldService.php; lib/Service/PeopleWidgetService.php (searchCandidates); @conduction/nextcloud-vue CnPeopleWidget (searchPeople via src/services/widgetDataAdapters.js); src/views/settings/ProfileFieldsSettings.vue; src/components/admin/tabs/ProfileFieldsTab.vue", "owner": "ConductionNL/launchpad", - "change": "openspec/changes/widgets-people-expertise-and-fields" + "change": "openspec/changes/archive/2026-09-30-widgets-people-expertise-and-fields", + "requirement": "openspec/specs/people-widget :: Search finds people across the directory by profile and expertise (REQ-PEX-003)" }, - "reachedOn": "nothing", + "reachedOn": "People widget search box: 2 or more characters search the whole directory, including expertise tags (GET /api/people?q=)", "evidence": { "workspace-365": "https://support.workspace365.net/en/articles/175651-address-book users search colleagues by 'names, job titles, email address, departments and office locations, skills and expertise, interests, and more' (read 2026-09-26)", "microsoft-viva": "https://learn.microsoft.com/en-us/copilot/microsoft-365/people-skills-overview (read via its public source MicrosoftDocs/microsoft-365-docs) GA 'Skills in Traditional People Search (SharePoint people search)', available with Microsoft 365 or Viva plans; SharePoint search is what the SharePoint app in Teams uses (read 2026-09-26)", @@ -5367,10 +7293,473 @@ "provider": "launchpad", "providerHow": "read-from-code", "feature": "people-widget", - "featureConfidence": "medium", + "featureConfidence": "high", "origin": "tender", "originUrl": "https://www.tenderned.nl/aankondigingen/overzicht/418890", - "note": "The people widget filters only by group (PeopleWidgetService.php:462-470 extractGroupFilter) and shows biography and headline but cannot be searched by them; searched for skills, expertise and tags: none. Tender text: Gemeente Noordwijk 2026: 'Onze persoonlijke trefwoorden (profiel tags) op ons intranet-profiel zijn volledig en actueel' so KCC colleagues can find them. Specified 2026-09-27 in openspec/changes/widgets-people-expertise-and-fields (openspec pass)." + "note": "Built 30 Sep 2026 (archived change widgets-people-expertise-and-fields): a query of 2 or more characters searches the whole directory, including expertise tags and searchable custom fields (PeopleWidgetService.php searchCandidates, ProfileFieldService findMatchingUserIds). Tender text: Gemeente Noordwijk 2026: 'Onze persoonlijke trefwoorden (profiel tags) op ons intranet-profiel zijn volledig en actueel' so KCC colleagues can find them.", + "screen": { + "canvas": "design-system", + "board": "LpIntranet" + } + }, + { + "id": "s-embed-site", + "area": "sharing", + "name": "Embed a live dashboard or widget on the organisation's own website with a token that can be revoked.", + "launchpad": "no", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "specified", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/embedded-analytics", + "plan": [ + "openspec/changes/embedded-analytics" + ], + "requirement": [ + "openspec/changes/embedded-analytics/specs/embedded-analytics :: REQ-EMB-001 — Token issuance returns JWT exactly once", + "openspec/changes/embedded-analytics/specs/embedded-analytics :: REQ-EMB-002 — Public render route validates JWT and enforces scope", + "openspec/changes/embedded-analytics/specs/embedded-analytics :: REQ-EMB-009 — Token revocation takes effect within 60 seconds" + ], + "note": "Not built: no embed token, render route or SDK in the code yet. Plan: embedded-analytics." + }, + "reachedOn": "nothing", + "evidence": { + "workspace-365": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "microsoft-viva": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "nextcloud-dashboard": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "homarr": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "dashy": "not checked: row added for an open change under decision 399 (12 Nov 2026)" + }, + "provider": "launchpad", + "providerHow": "read-from-code", + "feature": "embedded-analytics", + "featureConfidence": "medium", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpPubliek" + } + }, + { + "id": "w-calculated-fields", + "area": "widgets", + "name": "Add a calculated value to a widget with a formula over its fields, other widgets and constants.", + "launchpad": "no", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "specified", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/widget-calculated-fields", + "plan": [ + "openspec/changes/widget-calculated-fields" + ], + "requirement": [ + "openspec/changes/widget-calculated-fields/specs/calculated-fields :: REQ-CALC-001 Formula parser produces deterministic AST", + "openspec/changes/widget-calculated-fields/specs/calculated-fields :: REQ-CALC-003 Client-side evaluator reactive to filter changes" + ], + "note": "Not built. Plan: widget-calculated-fields; the server-side half may belong in OpenRegister aggregation (REQ-CALC-004)." + }, + "reachedOn": "nothing", + "evidence": { + "workspace-365": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "microsoft-viva": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "nextcloud-dashboard": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "homarr": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "dashy": "not checked: row added for an open change under decision 399 (12 Nov 2026)" + }, + "provider": "launchpad", + "providerHow": "read-from-code", + "feature": "calculated-fields", + "featureConfidence": "medium", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWidgetInstellen" + } + }, + { + "id": "w-map", + "area": "widgets", + "name": "Show register objects that carry a location on a map widget, and open an object from the map.", + "launchpad": "no", + "workspace-365": "unknown", + "microsoft-viva": "unknown", + "nextcloud-dashboard": "unknown", + "homarr": "unknown", + "dashy": "unknown", + "built": { + "state": "specified", + "owner": "ConductionNL/launchpad", + "change": "openspec/changes/map-support", + "plan": [ + "openspec/changes/map-support" + ], + "requirement": [ + "openspec/changes/map-support/specs/map-widget :: REQ-MAP-001 A map widget shows register objects that carry a location", + "openspec/changes/map-support/specs/map-widget :: REQ-MAP-003 Clicking a feature opens its object" + ], + "note": "Not built. Plan: map-support, on OpenRegister's spatial-query API (geo-metadata-kaart)." + }, + "reachedOn": "nothing", + "evidence": { + "workspace-365": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "microsoft-viva": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "nextcloud-dashboard": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "homarr": "not checked: row added for an open change under decision 399 (12 Nov 2026)", + "dashy": "not checked: row added for an open change under decision 399 (12 Nov 2026)" + }, + "provider": "launchpad", + "providerHow": "read-from-code", + "feature": "map-widget", + "featureConfidence": "medium", + "origin": "own-code", + "screen": { + "canvas": "design-system", + "board": "LpWidgetInstellen" + } + } + ], + "specScreens": { + "activity-feed-integration": { + "board": null, + "reason": "Gebeurtenissen verschijnen in de Activiteit-app van Nextcloud, niet op een scherm van Launchpad." + }, + "beta-alignment": { + "board": null, + "reason": "Interne afstemming van app-informatie, manifest en documentatie." + }, + "calendar-widget": { + "board": [ + "LpVandaag", + "LpWerkplek" + ] + }, + "cli-commands": { + "board": null, + "reason": "Commando's op de server (occ), zonder scherm." + }, + "clock-weather-widgets": { + "board": [ + "LpWerkplek" + ] + }, + "conditional-visibility-editor": { + "board": [ + "LpZichtbaarheid" + ] + }, + "confluence-html-import": { + "board": [ + "LpBeheerOnderhoud" + ] + }, + "container-widget": { + "board": [ + "LpManagement" + ] + }, + "dashboard-acknowledgements": { + "board": [ + "LpIntranet", + "LpLeesbevestigingen" + ] + }, + "dashboard-bulk-operations": { + "board": [ + "LpBeheerOnderhoud" + ] + }, + "dashboard-cascade-events": { + "board": null, + "reason": "Opruimen van afhankelijke gegevens bij het verwijderen van een dashboard gebeurt op de achtergrond." + }, + "dashboard-icons": { + "board": [ + "LpDashboardInstellingen", + "LpWerkplek" + ] + }, + "dashboard-kiosk-mode": { + "board": [ + "LpKiosk" + ] + }, + "dashboard-language-content": { + "board": [ + "LpIntranet" + ] + }, + "dashboard-locking": { + "board": [ + "LpBewerken" + ] + }, + "dashboard-metadata-fields": { + "board": [ + "LpDashboardInstellingen" + ] + }, + "dashboard-public-share": { + "board": [ + "LpDelen", + "LpPubliek" + ] + }, + "dashboard-quota-limits": { + "board": [ + "LpBeheerAlgemeen" + ] + }, + "dashboard-reactions": { + "board": [ + "LpIntranet" + ] + }, + "dashboard-store": { + "board": [ + "LpStore" + ] + }, + "dashboard-switcher": { + "board": [ + "LpWerkplek" + ] + }, + "dashboard-versioning": { + "board": [ + "LpVersies" + ] + }, + "dashboard-view-analytics": { + "board": [ + "LpBeheerAnalyse" + ] + }, + "demo-data-showcases": { + "board": [ + "LpInstellen" + ] + }, + "divider-widget": { + "board": [ + "LpIntranet" + ] + }, + "effective-default-marker": { + "board": [ + "LpWerkplek" + ] + }, + "files-widget": { + "board": [ + "LpWerkplek" + ] + }, + "first-time-setup": { + "board": [ + "LpInstellen" + ] + }, + "footer-customization": { + "board": [ + "LpWerkplek", + "LpBeheerNavigatie" + ] + }, + "groupfolder-storage-backend": { + "board": null, + "reason": "Ingetrokken: deze opslag is nooit in de app aangesloten." + }, + "header-widget": { + "board": [ + "LpIntranet" + ] + }, + "iframe-embed-widget": { + "board": [ + "LpIntranet" + ] + }, + "image-widget": { + "board": [ + "LpIntranet" + ] + }, + "infrastructure-helpers": { + "board": null, + "reason": "Interne hulpklassen zonder scherm." + }, + "initial-state-contract": { + "board": null, + "reason": "Interne afspraak over de gegevens die de server aan de pagina meegeeft." + }, + "label-widget": { + "board": [ + "LpIntranet" + ] + }, + "launchpad-adopt-or-abstractions": { + "board": null, + "reason": "Zorgt dat Launchpad zonder OpenRegister draait; een architectuurafspraak zonder eigen scherm." + }, + "launchpad-ai-dashboard-assistant": { + "board": [ + "LpWerkplek" + ] + }, + "launchpad-compliance-audit-panel": { + "board": [ + "LpManagement" + ] + }, + "launchpad-enterprise-security-access": { + "board": [ + "LpManagement" + ] + }, + "launchpad-file-access-widget": { + "board": [ + "LpWerkplek" + ] + }, + "launchpad-meeting-calendar-actions": { + "board": [ + "LpWerkplek" + ] + }, + "launchpad-mobile-remote-access": { + "board": [ + "LpMobiel" + ] + }, + "launchpad-spend-analytics-widget": { + "board": [ + "LpManagement" + ] + }, + "legacy-widget-bridge": { + "board": [ + "LpWidgetKiezen", + "LpBeheerOnderhoud" + ] + }, + "license-header-consistency": { + "board": null, + "reason": "Licentiekoppen in de broncode, zonder scherm." + }, + "link-button-widget": { + "board": [ + "LpWerkplek" + ] + }, + "links-widget": { + "board": [ + "LpWerkplek" + ] + }, + "live-data-tile-widget": { + "board": [ + "LpManagement", + "LpWidgetInstellen" + ] + }, + "menu-widget": { + "board": [ + "LpIntranet" + ] + }, + "navigation-editor-org": { + "board": [ + "LpBeheerNavigatie" + ] + }, + "nc-dashboard-widget-proxy": { + "board": [ + "LpWidgetKiezen" + ] + }, + "nc-unified-search-integration": { + "board": [ + "LpWerkplek" + ] + }, + "news-widget": { + "board": [ + "LpIntranet" + ] + }, + "orphaned-data-cleanup": { + "board": [ + "LpBeheerOnderhoud" + ] + }, + "quicklinks-widget": { + "board": [ + "LpWerkplek" + ] + }, + "resource-uploads": { + "board": null, + "reason": "Interne bestands-API voor pictogrammen en afbeeldingen; het uploaden zelf staat op de schermen van die widgets." + }, + "service-health-ping": { + "board": [ + "LpWerkplek", + "LpTegelBewerken" + ] + }, + "setup-wizard": { + "board": [ + "LpInstellen" + ] + }, + "text-display-widget": { + "board": [ + "LpIntranet" + ] + }, + "tile-quick-search": { + "board": [ + "LpWerkplek" + ] + }, + "video-widget": { + "board": [ + "LpIntranet" + ] + }, + "attention-feed": { + "board": [ + "LpVandaag" + ] + }, + "mijn-werkdag-v3": { + "board": [ + "LpVandaag" + ] + }, + "cross-app-attention-feed": { + "board": [ + "LpVandaag" + ] + }, + "mijn-werkdag-template": { + "board": [ + "LpVandaag" + ] + }, + "start-page-without-navigation-panel": { + "board": [ + "LpVandaag" + ] } - ] + } } diff --git a/openspec/parity/scope.json b/openspec/parity/scope.json new file mode 100644 index 000000000..27cb118fa --- /dev/null +++ b/openspec/parity/scope.json @@ -0,0 +1,1486 @@ +{ + "app": "launchpad", + "productOwner": "Remco Damhuis", + "rows": { + "build-drag": { + "tier": "poc", + "reason": "Placing widgets by drag is the core job of a dashboard builder; all five competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-resize": { + "tier": "poc", + "reason": "Sizing widgets is part of building a dashboard at all; the demo is not convincing without it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-keyboard": { + "tier": "mvp", + "reason": "Accessibility requirement: a government organisation cannot use a layout editor that needs a mouse.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-columns": { + "tier": "mvp", + "reason": "Organisations adjust the grid to their content; two competitors have it, a setting one organisation will change.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-responsive": { + "tier": "mvp", + "reason": "Table stakes: four of five competitors reflow for narrow screens, and staff open the start page on phones.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-container": { + "tier": "mvp", + "reason": "Three of five competitors group widgets; a real start page needs sections to stay readable.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-style": { + "tier": "later", + "reason": "Only one competitor rates yes; per widget colours are polish, not needed to do the job.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-picker": { + "tier": "poc", + "reason": "Choosing a widget to add is part of the one flow the app exists for.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-nc-widgets": { + "tier": "poc", + "reason": "Showing other Nextcloud apps' widgets is the reason to use a start page inside Nextcloud.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-no-overlap": { + "tier": "mvp", + "reason": "Three of five competitors place new widgets in a free spot; without it daily editing is frustrating.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-edit-lock": { + "tier": "production", + "reason": "Concurrent editing of shared dashboards matters at scale with many editors; no competitor rates yes, so not table stakes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-personal-hide": { + "tier": "mvp", + "reason": "Two competitors have it, and staff on a shared group dashboard need to hide widgets they do not use.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-config-file": { + "tier": "later", + "reason": "Deferred: one competitor yes and no demand; export and import already cover moving dashboards.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "build-rollback": { + "tier": "production", + "reason": "Restoring an earlier version is hardening for organisations with many shared dashboards; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-many": { + "tier": "poc", + "reason": "Personal and team dashboards side by side is the core idea; switching between them must be shown.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-default": { + "tier": "mvp", + "reason": "Three competitors let users choose which dashboard opens first; needed once people have more than one.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-describe": { + "tier": "mvp", + "reason": "Two competitors have it; titles and icons are needed to tell dashboards apart in daily use.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-copy": { + "tier": "later", + "reason": "Only one competitor rates yes; starting from a template or empty dashboard covers the need.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-link": { + "tier": "mvp", + "reason": "Three competitors support direct links; organisations link dashboards from mail and the intranet.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-shared-list": { + "tier": "mvp", + "reason": "Once dashboards are shared, people need one place to find them; one competitor yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-tree": { + "tier": "later", + "reason": "No competitor rates yes; a page tree is intranet structure outside the core start page job.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-empty": { + "tier": "mvp", + "reason": "A first run offer to create a dashboard keeps new users from a blank page; one competitor yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-languages": { + "tier": "production", + "reason": "Multilingual content is a demand of larger and border region organisations; two competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-metadata": { + "tier": "later", + "reason": "No competitor rates yes and no demand row; recording an owning department is administrative extra.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "dash-starter-widgets": { + "tier": "poc", + "reason": "A new dashboard with useful widgets is what makes the first demo work without manual setup.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-start-full-width": { + "tier": "mvp", + "reason": "A layout setting an administrator of one organisation will want to change; no competitor data.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-pin": { + "tier": "poc", + "reason": "Launching apps and sites from tiles is the start page half of the core job; four competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-health": { + "tier": "later", + "reason": "Two self hosted competitors rate yes; service status is a homelab need more than an office one.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-filter": { + "tier": "later", + "reason": "Two competitors rate yes; useful only on dashboards with many tiles.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-web-search": { + "tier": "later", + "reason": "Two homelab competitors rate yes; organisations already have browser search.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-bookmarks": { + "tier": "mvp", + "reason": "Three competitors have grouped link lists; a common start page need for every organisation.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-clicks": { + "tier": "production", + "reason": "Usage reporting on tiles serves administrators of larger rollouts; one competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-most-used": { + "tier": "later", + "reason": "Two competitors rate yes; automatic ordering is convenience, not needed for the job.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-legacy-apps": { + "tier": "production", + "reason": "Digital workplace tenders such as Almelo name Workspace 365 for this; it wins tenders, not daily use.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-local-apps": { + "tier": "later", + "reason": "Only Workspace 365 rates yes; starting local programs is outside a browser start page.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-sso-app": { + "tier": "production", + "reason": "Single sign on into company apps is an integration Workspace 365 sells to tender buyers.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-catalogue": { + "tier": "production", + "reason": "An approved app catalogue with requests is an IT governance feature for larger organisations; one competitor yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-discover-containers": { + "tier": "later", + "reason": "Only Homarr rates yes; a homelab feature with no organisational demand.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "tile-org-nav": { + "tier": "mvp", + "reason": "Three competitors offer an organisation wide menu; an organisation needs it beside every dashboard.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-text": { + "tier": "poc", + "reason": "Formatted text is the simplest widget and needed to show any content in the demo.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-image": { + "tier": "mvp", + "reason": "Three competitors have image widgets; an organisation's start page needs pictures.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-video": { + "tier": "later", + "reason": "Two competitors rate yes; video on a start page is occasional.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-embed": { + "tier": "later", + "reason": "Only Workspace 365 rates yes; useful but organisations can link instead of embedding.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-news": { + "tier": "mvp", + "reason": "Table stakes: four of five competitors show news feeds on the start page.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-weather": { + "tier": "later", + "reason": "Three competitors rate yes, but all are homelab or Nextcloud; organisations rarely need weather.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-clock": { + "tier": "later", + "reason": "Two homelab competitors rate yes; not needed for an organisation's start page.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-calendar": { + "tier": "mvp", + "reason": "Three competitors show upcoming events; seeing today's agenda is daily start page use.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-files": { + "tier": "mvp", + "reason": "Files is the centre of Nextcloud; all competitors partial, and staff expect their folders here.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-people": { + "tier": "later", + "reason": "No competitor fully rates yes; colleague lists are intranet extras.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-birthdays": { + "tier": "later", + "reason": "Only Workspace 365 rates yes; a social extra with no demand.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-structure": { + "tier": "later", + "reason": "One competitor rates yes; headings help layout but text widgets cover the need.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-action-button": { + "tier": "later", + "reason": "Two competitors rate yes; one click actions are convenience on top of tiles.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-live-value": { + "tier": "mvp", + "reason": "Three competitors show live figures; organisations use it for queue counts and status values.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-charts": { + "tier": "production", + "reason": "Charts over registered data is reporting, a production concern; no competitor fully rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-bi-embed": { + "tier": "later", + "reason": "Deferred: partial, built, no demand; only Workspace 365 rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-spend": { + "tier": "production", + "reason": "Finance figures across fleet apps is an integration for reporting; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-scheduled-export": { + "tier": "production", + "reason": "Scheduled reports by mail is reporting demand at scale; no competitor data yet.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-cross-filter": { + "tier": "later", + "reason": "No competitor data and no demand; analytics behaviour beyond a start page.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "int-builder": { + "tier": "production", + "reason": "A no code connector to business systems is an integration Workspace 365 sells in tenders.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "int-itsm": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "int-erp": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "int-mail": { + "tier": "production", + "reason": "Mailbox preview is an integration with the mail app; only Workspace 365 rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "int-tasks": { + "tier": "production", + "reason": "Task integration with planning apps; two competitors rate yes, needed for digital workplace tenders.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "int-office-tiles": { + "tier": "production", + "reason": "Ready made office suite tiles are an integration two intranet competitors sell.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "int-intranet-content": { + "tier": "production", + "reason": "Showing another intranet's content is integration work two competitors offer.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "int-connections-status": { + "tier": "production", + "reason": "Connection status is operational hardening once outside integrations are in use.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-groups": { + "tier": "poc", + "reason": "Showing widgets per group is the smart visibility the app promises; four competitors have some form.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-hours": { + "tier": "later", + "reason": "No competitor rates yes; time windows are a refinement of group targeting.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-dates": { + "tier": "later", + "reason": "No competitor rates yes; date windows help campaigns but are not daily need.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-attribute": { + "tier": "production", + "reason": "Targeting by profile field is fine grained admin; one competitor yes, useful for large organisations.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-preview": { + "tier": "production", + "reason": "Previewing who sees a widget is admin tooling for complex rule sets; one competitor yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-overview": { + "tier": "production", + "reason": "An overview of all visibility rules is fine grained admin at scale; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-widget-kinds": { + "tier": "production", + "reason": "Restricting widget kinds per group is fine grained admin; no competitor fully rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-role-layout": { + "tier": "mvp", + "reason": "A starting layout per role is how one organisation sets up its staff; competitors partial.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-compulsory": { + "tier": "later", + "reason": "Deferred: partial, built, no demand.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-device": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-hide-incompatible": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-group-priority": { + "tier": "mvp", + "reason": "Needed once group dashboards exist and people belong to several groups; two competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "t-action-matrix": { + "tier": "production", + "reason": "A role by action grid is fine grained admin; two competitors rate yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-templates": { + "tier": "poc", + "reason": "Rolling a dashboard out to groups is the team half of the core job; two competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-permission-levels": { + "tier": "mvp", + "reason": "One competitor rates yes; an organisation must decide who may change a handed out dashboard.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-resync": { + "tier": "production", + "reason": "Pushing template changes to existing dashboards matters with many users; no competitor fully rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-group-dashboards": { + "tier": "poc", + "reason": "A shared dashboard per group beside personal ones is the team dashboard the app exists for.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-wizard": { + "tier": "mvp", + "reason": "Guided setup helps one organisation get started without consultancy; one competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-demo": { + "tier": "poc", + "reason": "Example dashboards are the demo data that makes the core flow demonstrable.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-report-gallery": { + "tier": "later", + "reason": "No competitor data and no demand; a report gallery is analytics outside the core job.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-delegate": { + "tier": "mvp", + "reason": "Table stakes: four competitors let non admins manage dashboards, needed in daily operation.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-bulk": { + "tier": "production", + "reason": "Bulk changes matter only at scale with many dashboards; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-export": { + "tier": "production", + "reason": "Export and import between servers is migration, a production concern; one competitor yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-migrate-from": { + "tier": "nee", + "reason": "Decided no: no competitor rates yes, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-confluence": { + "tier": "production", + "reason": "Importing Confluence content is migration work for organisations switching; no competitor fully rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-registry": { + "tier": "later", + "reason": "No competitor rates yes and the end to end flow is unverified; sharing between organisations is extra.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-quota": { + "tier": "production", + "reason": "Quotas protect a large installation from misuse; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "r-personal-off": { + "tier": "mvp", + "reason": "Table stakes: four competitors let an organisation turn off personal dashboards.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-share": { + "tier": "mvp", + "reason": "Sharing with people and groups is basic team use; three competitors rate yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-public": { + "tier": "mvp", + "reason": "Two competitors offer public read only links; organisations publish dashboards to outsiders.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-public-protect": { + "tier": "production", + "reason": "Password and expiry on public links is security hardening; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-bruteforce": { + "tier": "production", + "reason": "Throttling password guesses is security hardening expected in tenders; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-notify": { + "tier": "mvp", + "reason": "People must learn that a dashboard was shared with them; a basic part of sharing.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-kiosk": { + "tier": "later", + "reason": "No competitor fully rates yes and no demand row; lobby screens are a niche use.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-schedule": { + "tier": "later", + "reason": "No competitor rates yes and no demand row; built because Ruben decided so, not because buyers ask.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-policy": { + "tier": "production", + "reason": "Deciding who may share with whom is fine grained admin for larger organisations; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-leaver": { + "tier": "production", + "reason": "Handing over dashboards of leavers matters at scale; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-discussion": { + "tier": "later", + "reason": "No competitor data and no demand; Talk already covers discussion.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-omnichannel": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-ack-ask": { + "tier": "later", + "reason": "No competitor rates yes and no demand row; built on Ruben's decision, not buyer demand.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-ack-report": { + "tier": "later", + "reason": "Depends on read confirmations, which have no competitor yes and no demand.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-react": { + "tier": "later", + "reason": "No competitor rates yes and no demand row; emoji reactions are engagement extra.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-announcements": { + "tier": "production", + "reason": "Targeted news with comments is an intranet suite feature Workspace 365 and Viva bring to tenders.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-events": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-kb": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-communities": { + "tier": "later", + "reason": "Two intranet competitors rate yes, but communities sit outside the start page job.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-digest": { + "tier": "later", + "reason": "Two competitors rate yes; an email digest is convenience beyond the core job.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-activity-stream": { + "tier": "nee", + "reason": "Decided no: the personal activity stream is the Nextcloud activity app.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "e-maintenance": { + "tier": "mvp", + "reason": "Two competitors have it; an organisation needs to warn everyone about outages.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "a-find-dashboard": { + "tier": "mvp", + "reason": "Two competitors support search; finding dashboards from the Nextcloud search bar is basic navigation.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "a-federated": { + "tier": "nee", + "reason": "Decided no: unified search is provided by Nextcloud server.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "a-assistant": { + "tier": "later", + "reason": "Only Workspace 365 rates yes and no demand row; built on Ruben's decision.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "a-place-widget": { + "tier": "later", + "reason": "No competitor rates yes and no demand; AI placement is a convenience.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "a-agent-tools": { + "tier": "later", + "reason": "One competitor rates yes and no demand; an AI tool surface is extra.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "a-ai-control": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "a-summarise": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-views": { + "tier": "production", + "reason": "View statistics with export are reporting for administrators of larger rollouts; one competitor yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-optout": { + "tier": "later", + "reason": "Deferred: built, no demand; only needed with view tracking.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-health": { + "tier": "production", + "reason": "A health check is operational hardening for running at scale; competitors partial.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-prometheus": { + "tier": "production", + "reason": "Prometheus metrics serve hosting providers running at scale; competitors partial at best.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-audit": { + "tier": "nee", + "reason": "Decided no: the audit log is Nextcloud's admin_audit app.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-activity": { + "tier": "production", + "reason": "Changes in the activity stream support audit and accountability; no competitor rates yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-cleanup": { + "tier": "production", + "reason": "Cleaning data of deleted users keeps large installations healthy; two competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-cli": { + "tier": "production", + "reason": "Command line management is for hosters and scripted operations at scale; competitors partial.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-footer": { + "tier": "later", + "reason": "Deferred: partial, built, no demand; one competitor yes.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-allowlists": { + "tier": "later", + "reason": "Deferred: partial, built, no demand; occ already sets the lists.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "g-svg": { + "tier": "mvp", + "reason": "Removing scripts from uploaded icons is a security baseline before any real organisation uploads files.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-sso": { + "tier": "mvp", + "reason": "Table stakes: all five competitors support single sign on with the organisation's identity provider.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-mobile-app": { + "tier": "nee", + "reason": "Decided no: a native app is a recorded non-goal; the mobile browser and PWA cover it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-own-servers": { + "tier": "mvp", + "reason": "Running on own servers is why organisations pick Nextcloud; three competitors allow it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-theme": { + "tier": "mvp", + "reason": "Government organisations need their own colours and NL Design System theming from day one.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-custom-css": { + "tier": "later", + "reason": "Two homelab competitors rate yes; theming already covers organisational styling.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-background": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-languages": { + "tier": "mvp", + "reason": "Table stakes: all five competitors are multilingual; Dutch is required.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-standalone": { + "tier": "mvp", + "reason": "Installing on a plain Nextcloud without other products is needed for any organisation to adopt it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "p-multitenant": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-widget-twice": { + "tier": "mvp", + "reason": "Three competitors allow the same widget twice; needed for two feeds or two folders.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-teams": { + "tier": "nee", + "reason": "Decided no: no competitor rates yes, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-account-move": { + "tier": "nee", + "reason": "Decided no: no competitor rates yes, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-link-target": { + "tier": "later", + "reason": "A feature request with two competitors yes; a small preference, not needed to do the job.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-auto-refresh": { + "tier": "mvp", + "reason": "Three competitors refresh on their own; a start page left open all day must stay current.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-idp-groups": { + "tier": "mvp", + "reason": "Three competitors follow identity provider groups; group dashboards depend on correct groups after sign in.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-tour": { + "tier": "later", + "reason": "One competitor rates yes; a tour helps onboarding but the wizard covers setup.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-pwa": { + "tier": "mvp", + "reason": "Table stakes: all five competitors install on a phone home screen.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-rest-api": { + "tier": "production", + "reason": "A documented API is an integration demand in tenders; three competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-proxy": { + "tier": "production", + "reason": "Outbound proxy support is required in locked down government networks; three competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-single-logout": { + "tier": "nee", + "reason": "Decided no: single logout is done by Nextcloud's login apps.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-import-bookmarks": { + "tier": "later", + "reason": "A feature request with no competitor yes; tiles can be added by hand.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-notes": { + "tier": "later", + "reason": "One competitor rates yes; personal notes are an extra, Nextcloud Notes exists.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-internal-url": { + "tier": "later", + "reason": "One homelab competitor rates yes; split network addresses are a niche need.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-theme-per-dashboard": { + "tier": "later", + "reason": "Two competitors rate yes; organisation wide theming covers most needs.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-open-inside": { + "tier": "later", + "reason": "Three competitors rate yes, but opening apps in a pane is convenience over a new tab.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-search-prefix": { + "tier": "later", + "reason": "Two homelab competitors rate yes; search shortcuts are a power user extra.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-dark-mode": { + "tier": "mvp", + "reason": "Table stakes and accessibility: four of five competitors follow the device's dark mode.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-tile-sort": { + "tier": "later", + "reason": "One competitor rates yes; sorting options are polish.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-ai-write": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-room-free": { + "tier": "nee", + "reason": "Decided no: one competitor, no demand, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-profile-fields": { + "tier": "later", + "reason": "Two competitors rate yes; extra profile fields from the identity provider are intranet extras.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-news-preview": { + "tier": "production", + "reason": "Previewing news before publishing belongs with announcements, an intranet suite feature for tenders.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-recurring-events": { + "tier": "nee", + "reason": "Decided no: no competitor rates yes, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-content-review": { + "tier": "nee", + "reason": "Decided no: no competitor rates yes, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-ai-chart": { + "tier": "nee", + "reason": "Decided no: no competitor rates yes, outside the core area.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-work-queue": { + "tier": "production", + "reason": "A tender asks for own cases on the start page; delivered through case app widgets.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-attention": { + "tier": "mvp", + "reason": "A ranked list of what needs attention today is daily start page use for case workers.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-menu": { + "tier": "later", + "reason": "No competitor data and no demand; the organisation menu and tiles cover navigation.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-quicklinks": { + "tier": "later", + "reason": "No competitor data; tiles and bookmarks already offer shortcuts.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-public-start": { + "tier": "production", + "reason": "A tender asks for a public start page for signed out visitors; two competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "d-find-expert": { + "tier": "production", + "reason": "A tender asks to find colleagues by expertise; two intranet competitors have it.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "s-embed-site": { + "tier": "later", + "reason": "No competitor data and no demand; embedding on websites is beyond the start page job.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-calculated-fields": { + "tier": "later", + "reason": "No competitor data and no demand; formulas are analytics extras.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "w-map": { + "tier": "later", + "reason": "No competitor data and no demand; a map of register objects is a specialist widget.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "q-integrations-gate": { + "tier": "production", + "reason": "Integrations page visibility with integriq belongs with the production integration rows.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "q-charts-live": { + "tier": "production", + "reason": "Real figures in chart widgets belong with the reporting rows, which are production.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "q-registry-live": { + "tier": "later", + "reason": "Follows r-registry, which has no competitor yes and no demand.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "q-groupfolder": { + "tier": "later", + "reason": "A storage backend option in beta with no competitor data or demand.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "q-comments": { + "tier": "later", + "reason": "No competitor data and no demand; Talk and the activity stream cover discussion.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "q-sibling-widgets": { + "tier": "production", + "reason": "Role scoped widgets from fleet apps are integration work across Conduction apps.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "q-person-activity": { + "tier": "later", + "reason": "Reporting one named person's activity raises privacy questions and has no demand row.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + }, + "q-drive-nc-dashboard": { + "tier": "later", + "reason": "A research task to verify a competitor column, not a capability a customer needs.", + "proposedBy": "claude", + "proposedOn": "2026-11-17", + "decidedBy": null, + "decidedOn": null + } + } +} diff --git a/openspec/specs/action-authorization/screens.md b/openspec/specs/action-authorization/screens.md new file mode 100644 index 000000000..6250baa7d --- /dev/null +++ b/openspec/specs/action-authorization/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerRollen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerRollen diff --git a/openspec/specs/action-authorization/spec.md b/openspec/specs/action-authorization/spec.md new file mode 100644 index 000000000..beaa74c87 --- /dev/null +++ b/openspec/specs/action-authorization/spec.md @@ -0,0 +1,118 @@ +--- +capability: action-authorization +status: done +cross-links: + - openspec/architecture/adr-023-action-authorization.md + - openspec/specs/admin-roles/spec.md + - openspec/specs/permissions/spec.md +--- + +# Action Authorization Specification + +## Purpose + +An administrator decides in one grid which Nextcloud groups may take each LaunchPad action: list dashboards, publish one, react, see analytics, edit the navigation, and so on. Every controller method names its action and asks one service whether the caller may take it. This is action RBAC as ADR-023 defines it. Which objects a user may touch stays with PermissionService and the admin roles spec; this spec only answers "may this user call this endpoint at all". + +Written on 2026-10-07 after the fact, from the code on `development`. It describes what ships today and covers parity row `t-action-matrix`. + +Code: +- `lib/Service/ActionAuthService.php`: `requireAction()` (line 117), `getAllowedGroups()` (171), `getMatrix()` (187), `setMatrix()` (234). +- `lib/Controller/ActionMatrixController.php`: `getMatrix()` (73) and `setMatrix()` (111), routed at `GET` and `PUT /api/admin/action-matrix` (`appinfo/routes.php:440-441`). +- `lib/actions.seed.json`: 82 actions and their default groups. +- `lib/Repair/InitializeActions.php` (run, line 71) and `lib/Repair/ApplyActionBaseline.php` (run, line 127), both registered as install and upgrade steps in `appinfo/info.xml`. +- `src/components/admin/ActionAuthMatrix.vue`, mounted by `src/components/admin/tabs/RolesPermissionsTab.vue:15` in the Roles and permissions tab of the admin settings (`src/components/admin/AdminSettings.vue:246`). + +## Requirements + +### Requirement: Every action endpoint asks the action service (REQ-ACT-001) + +A controller method that performs a LaunchPad action MUST call `ActionAuthService::requireAction()` with the caller and a dot-separated action name (for example `dashboard-reaction.add-reaction`) before it does any work. The service SHALL refuse with an `OCSForbiddenException` when the caller may not take the action. Editing the matrix itself is not an action: it is guarded by `#[AuthorizedAdminSetting(LaunchPadAdmin::class)]` at the route. + +@e2e exclude Backend authorization; asserted per controller in tests/Unit/Controller (for example DashboardReactionApiControllerTest.php). No page to drive. + +#### Scenario: A member outside the allowed groups is refused +- GIVEN the matrix entry for `analytics.top-dashboards` is `["admin"]` +- AND Pieter is not an administrator +- WHEN Pieter's session calls the endpoint behind that action +- THEN the service MUST throw `OCSForbiddenException` with the message "Action 'analytics.top-dashboards' requires admin rights" +- AND the controller MUST NOT run the action + +#### Scenario: A member of an allowed group passes +- GIVEN the matrix entry for `dashboard.publish` is `["admin", "redactie"]` +- AND Pieter is a member of the group `redactie` +- WHEN Pieter's session calls the endpoint behind that action +- THEN `requireAction()` MUST return without throwing + +### Requirement: How an action resolves (REQ-ACT-002) + +The service SHALL resolve an action in this order. An administrator always passes. An entry holding the sentinel `@all` passes every signed-in user. An entry that is empty or holds only `admin` refuses everyone else. Otherwise the caller passes when one of their groups, read through `AdminTemplateService::getUserGroupIdsFor()`, is in the entry. An action missing from the matrix MUST resolve to `["admin"]`, so a new action is closed until an administrator opens it. + +@e2e exclude Pure service logic; covered by tests/Unit/Service/ActionAuthBaselineTest.php. + +#### Scenario: The all-users sentinel wins over an admin-only reading +- GIVEN the entry for `dashboard.list` is `["admin", "@all"]` +- WHEN any signed-in user calls an endpoint behind `dashboard.list` +- THEN the call MUST pass + +#### Scenario: An unknown action is admin-only +- GIVEN the matrix has no entry for `example.new-action` +- WHEN a user who is not an administrator calls the endpoint behind it +- THEN the service MUST refuse the call + +#### Scenario: An unreadable matrix denies by default +- GIVEN the stored `actions` app config value is not valid JSON +- WHEN the service reads the matrix +- THEN it MUST treat the matrix as empty +- AND every action MUST resolve to `["admin"]` + +### Requirement: The administrator edits the matrix in one grid (REQ-ACT-003) + +The Roles and permissions tab of the LaunchPad admin settings MUST show an "Action authorization" table with one row per action and one column per group: first `admin`, then "All logged-in users" for `@all`, then every Nextcloud group. The action list SHALL be the union of the stored matrix and the seed file, so an action no one has configured yet still has a row. Each cell is a checkbox. The `admin` column MUST be ticked and disabled. "Save action matrix" MUST send the whole matrix with `PUT /api/admin/action-matrix`, always keeping `admin` in each entry, and confirm with "Action matrix saved." or report "Failed to save the action matrix.". + +@e2e exclude Written after the fact; no Playwright spec drives this table yet. Adding one belongs to a build change. + +#### Scenario: An administrator opens the publish action to a group +- GIVEN Fatima is an administrator on the Roles and permissions tab +- WHEN she ticks the `redactie` column on the `dashboard.publish` row and presses "Save action matrix" +- THEN the request MUST carry `dashboard.publish: ["admin", "redactie"]` +- AND the table MUST redraw from the matrix the server returns +- AND the message "Action matrix saved." MUST appear + +#### Scenario: The admin column cannot be unticked +- GIVEN the action table is shown +- THEN every cell in the `admin` column MUST be ticked and disabled + +#### Scenario: Only administrators reach the matrix endpoints +- GIVEN Pieter is not a LaunchPad administrator +- WHEN his session calls `GET` or `PUT /api/admin/action-matrix` +- THEN Nextcloud MUST refuse the request before the controller runs + +### Requirement: A fresh install is usable and an upgrade keeps the administrator's choices (REQ-ACT-004) + +On install, when the stored matrix is empty, the `InitializeActions` repair step MUST write the actions from `lib/actions.seed.json`, which grants the ordinary end-user actions to `@all` and keeps administrative actions at `["admin"]`. When the matrix already has entries it MUST leave them alone. The `ApplyActionBaseline` step SHALL, once per baseline version, widen only entries that still hold the untouched `["admin"]` default or are missing, and MUST leave every entry an administrator changed. + +@e2e exclude Install and upgrade repair steps; covered by tests/Unit/Repair/ApplyActionBaselineTest.php and tests/Unit/Service/ActionSeedCoverageTest.php. + +#### Scenario: Fresh install +- GIVEN LaunchPad is installed on an instance with no stored action matrix +- WHEN the install repair steps run +- THEN the matrix MUST equal the seed file's actions +- AND a non-admin user MUST be able to list their dashboards + +#### Scenario: An administrator's narrowing survives the upgrade +- GIVEN an administrator set `dashboard.list` to `["admin", "medewerkers"]` +- WHEN a later version runs `ApplyActionBaseline` +- THEN the entry for `dashboard.list` MUST still be `["admin", "medewerkers"]` + +#### Scenario: The owner may use their own dashboard's versions, metadata and rules +@e2e exclude the seed and the upgrade are repair steps; the owner's calls themselves are driven by tests/e2e/dashboard-versioning.spec.ts and tests/e2e/dashboard-metadata-fields.spec.ts. Pinned by ActionAuthBaselineTest and ApplyActionBaselineTest::testAnInstanceAtV2GainsTheOwnerActions +- GIVEN the seed grants `dashboard-version.*`, `dashboard-metadata.set-metadata` and `rule.get-rules` to `@all` (baseline v3) +- WHEN a non-admin owner lists, creates, fetches or restores versions of their own dashboard, writes its metadata values, or reads the rules of a widget on it +- THEN the action check MUST let the call through, and the route's own ownership check MUST still refuse another user's dashboard +- AND an instance that applied baseline v2 MUST receive exactly these six actions on upgrade, keeping any of them an administrator changed + +#### Scenario: The owner may manage their own dashboard's language versions +- GIVEN the seed grants `dashboard-translation.create`, `.update`, `.destroy` and `.set-primary` to `@all` (baseline v4) +- WHEN a non-admin owner adds, edits, deletes or promotes a language version of their own dashboard +- THEN the action check MUST let the call through, and the route's own ownership check MUST still refuse another user's dashboard +- AND an instance that applied baseline v3 MUST receive exactly these four actions on upgrade, keeping any of them an administrator changed diff --git a/openspec/specs/activity-feed-integration/screens.md b/openspec/specs/activity-feed-integration/screens.md new file mode 100644 index 000000000..81ee38d0b --- /dev/null +++ b/openspec/specs/activity-feed-integration/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Gebeurtenissen verschijnen in de Activiteit-app van Nextcloud, niet op een scherm van Launchpad. diff --git a/openspec/specs/activity-feed-integration/spec.md b/openspec/specs/activity-feed-integration/spec.md index acc87119d..ef3867846 100644 --- a/openspec/specs/activity-feed-integration/spec.md +++ b/openspec/specs/activity-feed-integration/spec.md @@ -26,9 +26,6 @@ No new database tables. NC Activity persists events in the existing `oc_activity ## Requirements - -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: REQ-ACT-001 Extension Registration The system MUST register a class `\OCA\LaunchPad\Activity\Extension` that implements `OCP\Activity\IProvider` and is declared in `appinfo/info.xml` under the `<activity>` section with application id `launchpad`. The extension MUST be resolvable from the NC DI container at runtime. @@ -47,6 +44,8 @@ The system MUST register a class `\OCA\LaunchPad\Activity\Extension` that implem #### Scenario: Unknown event type does not throw +@e2e exclude no endpoint can hand parse() a LaunchPad event of an unknown type, so there is no HTTP outcome. The product does the OPPOSITE of this scenario: it throws UnknownActivityException, NC's provider-chain contract, pinned by tests/Unit/Activity/ExtensionTest.php::testParseThrowsForUnknownType + - GIVEN `Extension::parse()` receives an `IEvent` whose `type` is not one of the 13 known `EVENT_*` constants - WHEN `parse()` is called - THEN it MUST return the unmodified `IEvent` without throwing any exception @@ -59,6 +58,8 @@ The system MUST register a class `\OCA\LaunchPad\Activity\Extension` that implem #### Scenario: `getIcon()` falls back for unknown types +@e2e exclude parse() only calls getIcon() with a known type, so an unknown type cannot reach it over HTTP; the fallback to launchpad.svg is pinned by tests/Unit/Activity/ExtensionTest.php::testGetIconReturnsNonEmptyForAllTypes + - GIVEN an unknown event type string is passed to `Extension::getIcon()` - WHEN the method executes - THEN it MUST return the URL to the generic LaunchPad activity icon (`img/activity/launchpad.svg`) @@ -73,12 +74,16 @@ NOTE: `dashboard_viewed` is NOT in the catalogue and MUST NOT be added. View tra #### Scenario: All 13 constants present and non-empty +@e2e exclude a PHP class-constant property with no HTTP surface; pinned by tests/Unit/Activity/ExtensionTest.php::testAllEventsHasThirteenUniqueValues, which asserts 14 values (dashboard_acknowledged was added), so "exactly these 13" is stale + - GIVEN `Extension::ALL_EVENTS` is inspected at runtime - THEN it MUST contain exactly these 13 string values (in any order): `dashboard_created`, `dashboard_updated`, `dashboard_deleted`, `dashboard_published`, `dashboard_unpublished`, `dashboard_scheduled`, `dashboard_shared`, `dashboard_public_share_created`, `dashboard_commented`, `dashboard_reacted`, `dashboard_restored`, `dashboard_lock_overridden`, `dashboard_role_changed` - AND no value MUST be empty or duplicated #### Scenario: Unknown type rejected by `ActivityPublisher` +@e2e exclude no endpoint passes an arbitrary type to ActivityPublisher::publish(); pinned by tests/Unit/Activity/ExtensionTest.php::testUnknownTypeDropped and the "publish unknown type" case of tests/Unit/Activity/ActivityPublisherGoldenTest.php::testRowsMatchTheRecordedFixture (warning logged, no row) + - GIVEN `ActivityPublisher::publish()` is called with an event type string not present in `Extension::ALL_EVENTS` - WHEN `publish()` executes - THEN it MUST log a WARNING and return without calling `IManager::publishActivity()` @@ -86,6 +91,8 @@ NOTE: `dashboard_viewed` is NOT in the catalogue and MUST NOT be added. View tra #### Scenario: Constants are importable from sibling-capability files +@e2e exclude PHP autoloading of a public class constant, no runtime outcome; exercised by every class that compiles against it (lib/Service/AcknowledgementService.php, lib/Activity/DashboardActivityEmitter.php) under tests/Unit/Activity/DashboardActivityEmissionTest.php + - GIVEN a sibling capability (e.g. `dashboard-comments`) needs to reference the comment event type - WHEN it uses `Extension::EVENT_COMMENTED` - THEN PHP MUST resolve the constant without an autoload error @@ -93,6 +100,8 @@ NOTE: `dashboard_viewed` is NOT in the catalogue and MUST NOT be added. View tra #### Scenario: `ALL_EVENTS` is iterable for registration loop +@e2e exclude internal registration wiring with no HTTP outcome, and not how the product registers: appinfo/info.xml lists four <setting> classes and lib/ has no IManager::registerExtension() loop. What is registered is pinned by tests/Unit/Activity/Settings/ActivitySettingsTest.php::testInfoXmlRegistersEverySetting; the visible listing is the e2e for extension-is-listed-in-nc-activity-admin-settings + - GIVEN NC Activity settings-screen registration code iterates `Extension::ALL_EVENTS` - WHEN it calls `IManager::registerExtension()` inside the loop - THEN all 13 types MUST be registered with NC in a single loop without manual repetition @@ -109,12 +118,16 @@ The system MUST provide `\OCA\LaunchPad\Activity\ActivityPublisher` as the sole #### Scenario: ActivityPublisher never uses static IManager access +@e2e exclude a source-code property (constructor injection), no runtime outcome; no test pins it. Checked by grep: lib/Activity/ contains no Server::get or getActivityManager + - GIVEN the `ActivityPublisher` source is inspected - THEN it MUST NOT contain any `\OC::$server->getActivityManager()` or `Server::get(IManager::class)` calls - AND `IManager` MUST be injected via constructor #### Scenario: Activity failure does not roll back primary action +@e2e exclude needs IManager::publish() to throw, which a test cannot make a running instance do; pinned by the "publish failing manager" case of tests/Unit/Activity/ActivityPublisherGoldenTest.php::testRowsMatchTheRecordedFixture and by tests/Unit/Activity/DashboardActivityEmitterTest.php::testSharedSwallowsAndLogsAPublisherFailure + - GIVEN `IManager::publishActivity()` throws a `\RuntimeException` - WHEN `ActivityPublisher::publish()` handles the exception - THEN it MUST log the error and return without re-throwing @@ -129,27 +142,29 @@ The system MUST provide `\OCA\LaunchPad\Activity\ActivityPublisher` as the sole ### Requirement: REQ-ACT-004 Audience Targeting — Personal Dashboards -For events on `user`-type dashboards, the system MUST emit exactly one activity row per event occurrence, addressed to the dashboard owner. The owner receives their own events so they appear in their personal activity stream. +A save of a private dashboard (a `user`-type dashboard with no shares and no target groups) MUST NOT write any activity row, not even for its owner (Ruben, 21 Nov 2026; this matches REQ-DIGE-003). Other events on a `user`-type dashboard MUST emit exactly one activity row per event occurrence, addressed to the dashboard owner. NOTE: REQ-ACT-004 through REQ-ACT-006 and REQ-ACT-008 together implement the normative four-scope audience rule. The recipient set for any event is determined by the dashboard's scope at emit-time: | Scope | Recipients | |---|---| -| `user` (personal) | Owner only | +| `user` (personal) | Owner only; a save of a private dashboard writes no row | | User-to-user share | Owner + every named share recipient | | `group_shared` | All current members of the target group (resolved via `IGroupManager` at emit-time) | | Default-group (`groupId = 'default'`) | All authenticated NC users (via `IUserManager::callForAllUsers`), subject to debounce (see REQ-ACT-008) | NOTE: Group membership MUST be resolved at emit-time, not at read-time. This matches NC core's own pattern and keeps `oc_activity` queries simple. For personal-scope events, the guard on `dashboard->getType()` MUST prevent any `IGroupManager` call. -#### Scenario: Self-action on personal dashboard — single row for owner +#### Scenario: Self-action on personal dashboard writes no row -- GIVEN user "alice" updates her personal dashboard "Work" -- WHEN `ActivityPublisher::publish('dashboard_updated', 'alice', ...)` is called -- THEN exactly one row MUST be written to `oc_activity` with `user = 'alice'` and `affecteduser = 'alice'` +- GIVEN user "alice" has a personal dashboard "Work" that is not shared and has no target groups +- WHEN she saves it +- THEN no `dashboard_updated` row MUST be written to `oc_activity`, not for "alice" and not for anyone else #### Scenario: Admin action on personal-origin dashboard — single row to owner +@e2e exclude never built: no code path in lib/ emits dashboard_deleted (grep `Extension::EVENT_DELETED` in lib/ finds only the catalogue in lib/Activity/Extension.php), so there is no action to drive and no row to read; no test exists + - GIVEN admin "root" deletes user "bob"'s personal dashboard on his behalf - WHEN `ActivityPublisher::publish('dashboard_deleted', 'root', uuid, ...)` is called targeting bob's dashboard - THEN exactly one row MUST be written with `user = 'bob'` and `affecteduser = 'root'` @@ -157,20 +172,22 @@ NOTE: Group membership MUST be resolved at emit-time, not at read-time. This mat #### Scenario: No fan-out for personal dashboards - GIVEN "alice"'s personal dashboard is not shared with anyone -- WHEN she creates a new widget on it (triggering `dashboard_updated`) -- THEN `oc_activity` MUST contain exactly one new row for this event +- WHEN she creates a new widget on it +- THEN `oc_activity` MUST contain no new `dashboard_updated` row for this dashboard - AND no rows MUST be written for any other user #### Scenario: First-person vs third-person subject selection -- GIVEN "alice" updates her own personal dashboard -- THEN the activity row MUST use the first-person subject template for `dashboard_updated` -- GIVEN "root" updates "alice"'s personal dashboard +@e2e exclude its second GIVEN cannot be reached: no endpoint lets another user update a personal dashboard (DashboardService::updateDashboard throws "Access denied" for a non-owner, lib/Service/DashboardService.php:972). Variant selection is pinned by tests/Unit/Activity/ActivityRowTest.php::testTheActorGetsTheSelfVariant and ::testAnotherUserGetsTheOtherVariant + +- GIVEN "alice" acts on her own personal dashboard in a way that writes a row (for example publishing it) +- THEN the activity row MUST use the first-person subject template for that event +- GIVEN "root" acts on "alice"'s personal dashboard - THEN the activity row addressed to "alice" MUST use the third-person template with actor param `'root'` ### Requirement: REQ-ACT-005 Audience Targeting — Shared Dashboards -For `dashboard_shared` events (user-to-user shares via the `dashboard-sharing` capability), the system MUST emit one activity row to each named share recipient plus one row to the acting user. +For `dashboard_shared` events (shares via the `dashboard-sharing` capability), one share action MUST write one activity row for the sharer that names every recipient of that action, plus one row for each recipient (Ruben, 21 Nov 2026). A group share counts every current member of the group as a recipient; the sharer's row names the group. The sharer never gets a second row as a recipient. #### Scenario: Share with two users produces three rows @@ -178,6 +195,13 @@ For `dashboard_shared` events (user-to-user shares via the `dashboard-sharing` c - WHEN `ActivityPublisher::publishToRecipients('dashboard_shared', 'alice', uuid, 'Marketing', link, ['bob', 'carol'])` is called - THEN `oc_activity` MUST contain three new rows: one for "alice", one for "bob", one for "carol" +#### Scenario: Replacing the share list tells the sharer once + +- GIVEN "alice" saves the share list of "Marketing" with new shares for "bob" and group "staff" in one request +- WHEN the shares are written +- THEN "alice" MUST get exactly one `dashboard_shared` row, naming "bob, staff" +- AND "bob" and every member of "staff" other than "alice" MUST get one row each + #### Scenario: Actor row uses first-person subject; recipient rows use second/third-person - GIVEN the same share event above @@ -186,6 +210,8 @@ For `dashboard_shared` events (user-to-user shares via the `dashboard-sharing` c #### Scenario: Public share creation — owner and actor only +@e2e exclude never built: no code path in lib/ emits dashboard_public_share_created (grep `Extension::EVENT_PUBLIC_SHARE_CREATED` in lib/ finds only the catalogue in lib/Activity/Extension.php), so there is no action to drive and no row to read; no test exists + - GIVEN admin "root" creates a public share link for "alice"'s dashboard "Marketing" - WHEN `ActivityPublisher::publish('dashboard_public_share_created', 'root', uuid, 'Marketing', link)` is called - THEN exactly two rows MUST be written: one for "root", one for "alice" (dashboard owner) @@ -216,6 +242,8 @@ For events on `group_shared`-type dashboards, the system MUST emit one activity #### Scenario: `IGroupManager` is not invoked for personal-dashboard events +@e2e exclude whether a PHP collaborator is called is internal; pinned by tests/Unit/Activity/DashboardActivityEmissionTest.php::testSavingAPrivateDashboardSendsNothing (publishToGroup never called) + - GIVEN a `user`-type dashboard event is being published - WHEN `ActivityPublisher::publish()` runs - THEN `IGroupManager` MUST NOT be called @@ -230,6 +258,8 @@ For events on `group_shared`-type dashboards, the system MUST emit one activity ### Requirement: REQ-ACT-007 Debounce — Reaction Events +@e2e exclude never built: no code path in lib/ emits dashboard_reacted (grep `Extension::EVENT_REACTED` in lib/ finds only the catalogue and the debounce guard in lib/Activity/ActivityPublisher.php), so there is no action to drive and no row to read. The debounce itself is pinned by tests/Unit/Activity/ExtensionTest.php::testReactionDebounceSuppressesSecondEmission, ::testReactionDebounceIsPerActorPerDashboard and tests/Unit/Activity/DebounceHelperClockTest.php::testReactionClaimExpiresAfterTheTtl + The system MUST apply a debounce per `(actorUserId, dashboardUuid)` pair to `dashboard_reacted` events using an APCu key with a TTL of exactly 900 seconds (15 minutes). At most one reaction activity row per actor per dashboard per 900-second window MUST be written. #### Scenario: First reaction within window is published @@ -276,6 +306,8 @@ For events on dashboards with `groupId = 'default'`, the system MUST apply a deb #### Scenario: Subsequent global event within 15 minutes is fully suppressed +@e2e exclude its THEN clauses are internal (allowGlobalFanout() returns false, callForAllUsers() is not called) and zero rows alone cannot tell them apart from the daily update debounce that also applies; pinned by tests/Unit/Activity/ExtensionTest.php::testGlobalFanoutIsDebounced (callForAllUsers expected once) + - GIVEN the debounce key for `(D-default.uuid, 'dashboard_updated')` is active - WHEN another update to the same dashboard triggers `publish('dashboard_updated', ...)` again - THEN `allowGlobalFanout()` MUST return false @@ -291,6 +323,8 @@ For events on dashboards with `groupId = 'default'`, the system MUST apply a deb #### Scenario: DEBUG log entry emitted on suppression +@e2e exclude a DEBUG log line: the instance logs at WARNING and has no API to read the log. The suppression is pinned by tests/Unit/Activity/ExtensionTest.php::testGlobalFanoutIsDebounced; no test asserts the DEBUG message itself + - GIVEN the global debounce is active for an event - WHEN the fan-out is suppressed - THEN `ActivityPublisher` MUST emit a DEBUG-level log entry stating that the global fan-out was debounced, including the dashboard UUID and event type @@ -298,24 +332,26 @@ For events on dashboards with `groupId = 'default'`, the system MUST apply a deb ### Requirement: REQ-ACT-009 User Opt-Out via NC Settings -The system MUST register each of the 13 event types with NC Activity's per-type notification preference system. Users MUST be able to independently disable in-app notifications and email notifications for each type via the standard NC Settings → Activity UI, with no custom LaunchPad preferences page required. +The system MUST register its event types with NC Activity's per-type preferences. As in Nextcloud's own Activity app, every event MUST be written to the activity stream, and opting out MUST control only mail and push (Ruben, 21 Nov 2026). Each LaunchPad setting MUST NOT offer a stream switch (`canChangeStream()` is false), MUST offer mail and push switches, and push MUST default to the same value as mail. No custom LaunchPad preferences page is required. #### Scenario: Default notification preferences for a new user - GIVEN a new NC user "frank" with no prior Activity preferences - WHEN LaunchPad emits any activity event addressed to "frank" -- THEN in-app notification MUST be enabled (default on) for all 13 types -- AND email notification MUST be disabled (default off) for all 13 types +- THEN the row MUST be written to his activity stream +- AND mail and push MUST be on for `dashboard_shared` and `dashboard_published` and off for `dashboard_updated` and `dashboard_acknowledged` -#### Scenario: User disables `dashboard_commented` in-app notifications +#### Scenario: User turns off push for `dashboard_shared` -- GIVEN "frank" has navigated to NC Settings → Activity and disabled in-app for `dashboard_commented` -- WHEN another user comments on a dashboard "frank" has access to -- THEN no in-app row MUST be written to `oc_activity` for "frank" for this comment event -- AND "frank" MUST still receive rows for other event types he has not disabled +- GIVEN "frank" has turned off push for `dashboard_shared` in NC Settings → Activity +- WHEN a dashboard is shared with him +- THEN the `dashboard_shared` row MUST still be written to his activity stream +- AND his stored preference for `dashboard_shared` MUST read push off #### Scenario: User enables email for `dashboard_shared` +@e2e exclude needs NC Activity's mail cron job and a mail sink, and the CI fixture has neither (no mail catcher in .github/workflows or tests/e2e). The dashboard_shared mail setting is pinned by tests/Unit/Activity/Settings/ActivitySettingsTest.php::testDefaultsAndGroup + - GIVEN "frank" has enabled email delivery for `dashboard_shared` - WHEN a dashboard is shared with him - THEN NC's Activity email job MUST include this event in "frank"'s next digest @@ -323,10 +359,10 @@ The system MUST register each of the 13 event types with NC Activity's per-type #### Scenario: Opt-out state is per-user and per-type -- GIVEN "frank" disables `dashboard_updated` but "grace" keeps it enabled -- WHEN a group-shared dashboard they both access is updated -- THEN no `dashboard_updated` row MUST be written for "frank" -- AND a `dashboard_updated` row MUST be written for "grace" +- GIVEN "frank" turns on push for `dashboard_updated` and "grace" keeps the default (off) +- WHEN a group dashboard they both see is updated +- THEN a `dashboard_updated` row MUST be written for "frank" and for "grace" +- AND "frank"'s stored preference for `dashboard_updated` MUST read push on while "grace"'s reads push off ### Requirement: REQ-ACT-010 Subject/Message Templates and Translation @@ -334,18 +370,24 @@ The system MUST define a complete set of translated subject and message template #### Scenario: First-person subject rendered for self-actions +@e2e exclude never built: no code path in lib/ emits dashboard_created (grep `Extension::EVENT_CREATED` in lib/ finds only the catalogue in lib/Activity/Extension.php), so there is no action to drive and no row to read; no test exists. The en/nl templates are pinned by tests/Unit/Activity/ExtensionTest.php::testParseRendersTheRecordedSubjects + - GIVEN user "alice" creates a dashboard "Analytics" - WHEN her activity row is rendered in the NC Activity UI - THEN the subject MUST read `"You created dashboard Analytics"` (en) or `"Je hebt dashboard Analytics aangemaakt"` (nl) #### Scenario: Third-person subject rendered for others' actions +@e2e exclude never built: no code path in lib/ emits dashboard_commented (grep `Extension::EVENT_COMMENTED` in lib/ finds only the catalogue in lib/Activity/Extension.php), so there is no action to drive and no row to read; no test exists + - GIVEN user "bob" comments on "alice"'s dashboard "Analytics" and "alice" receives the activity row - WHEN "alice" views her activity stream - THEN the subject MUST read `"bob commented on dashboard Analytics"` (en) #### Scenario: `dashboard_commented` message includes comment excerpt +@e2e exclude never built: no code path in lib/ emits dashboard_commented (grep `Extension::EVENT_COMMENTED` in lib/ finds only the catalogue in lib/Activity/Extension.php), so there is no action to drive and no row to read; no test exists. The 200-character message cut is pinned by the "publish long message" case of tests/Unit/Activity/ActivityPublisherGoldenTest.php::testRowsMatchTheRecordedFixture + - GIVEN "bob" posts the comment "Great work on the Q2 charts!" on dashboard "Analytics" - WHEN the activity row is rendered - THEN the message MUST contain the first 200 characters of the comment body @@ -370,6 +412,8 @@ Each of the 13 event types has exactly one owning capability responsible for cal #### Scenario: `dashboard_published` emitted only by `dashboard-draft-published` capability +@e2e exclude its AND clause is a source-code property (no other code path emits dashboard_published) that no running instance shows; exactly-once on a transition is pinned by tests/Unit/Activity/DashboardActivityEmissionTest.php::testPublishingAGroupDashboardTellsTheGroupOnce + - GIVEN a dashboard is transitioned to `published` status - WHEN the `dashboard-draft-published` service method completes - THEN `ActivityPublisher::publish('dashboard_published', ...)` MUST be called exactly once @@ -377,6 +421,8 @@ Each of the 13 event types has exactly one owning capability responsible for cal #### Scenario: Emission occurs after domain action is persisted +@e2e exclude its AND clause needs a mapper that throws before publish(), which a test cannot cause on a running instance; no test pins either clause. The ordering is visible in lib/Service/DashboardService.php (mapper update(), then activity->updated()) + - GIVEN the dashboard mapper has flushed the status update to the database - WHEN `ActivityPublisher::publish()` is subsequently called - THEN the activity row timestamp MUST be >= the database row's `updatedAt` @@ -384,6 +430,8 @@ Each of the 13 event types has exactly one owning capability responsible for cal #### Scenario: Activity failure does not fail the HTTP request +@e2e exclude needs IManager::publish() to throw on a running instance, which a test cannot cause; the swallow-and-log-ERROR path is pinned by the "publish failing manager" case of tests/Unit/Activity/ActivityPublisherGoldenTest.php::testRowsMatchTheRecordedFixture + - GIVEN `IManager::publishActivity()` throws `\Exception` (e.g. DB error on `oc_activity`) - WHEN `ActivityPublisher` catches the exception - THEN the HTTP response from the owning capability endpoint MUST still be HTTP 200/201/204 @@ -391,6 +439,8 @@ Each of the 13 event types has exactly one owning capability responsible for cal #### Scenario: No direct `oc_activity` writes in sibling-capability code +@e2e exclude a source-code property with no runtime outcome; no test pins it. Checked by grep: lib/ has no oc_activity SQL and no \OC_DB:: call + - GIVEN any PHP file in a sibling capability (e.g. `lib/Service/PublicationService.php`) - WHEN the file is inspected - THEN it MUST NOT contain any direct `oc_activity` SQL or `\OC_DB::` calls for LaunchPad events @@ -398,12 +448,16 @@ Each of the 13 event types has exactly one owning capability responsible for cal #### Scenario: Emission contract documented in Extension class docblock +@e2e exclude a docblock property with no runtime outcome; no test pins it. The table is in lib/Activity/Extension.php:10-28 (14 types, dashboard_acknowledged included) + - GIVEN `lib/Activity/Extension.php` is read - WHEN the class-level docblock is inspected - THEN it MUST list all 13 event types with the owning capability for each, so future contributors know where to add call-sites ### Requirement: REQ-ACT-011b Unit-Test Contract +@e2e exclude these scenarios describe the PHPUnit suite and the static-analysis run themselves, so there is nothing for an e2e to drive; they are pinned by tests/Unit/Activity/ExtensionTest.php (testPublishPopulatesCanonicalFields, testGetIconReturnsNonEmptyForAllTypes, testParseSetsRichSubjectForAllTypes, testReactionDebounceSuppressesSecondEmission) and by `composer check:strict` in CI + The system MUST include a PHPUnit test class `tests/Unit/Activity/ExtensionTest.php` that verifies each of the 13 event types is correctly published, that icons and subjects are resolved, and that the debounce logic suppresses duplicate rows. #### Scenario: All 13 event types produce a row with correct fields @@ -437,3 +491,92 @@ The system MUST include a PHPUnit test class `tests/Unit/Activity/ExtensionTest. - WHEN `composer check:strict` is executed - THEN both PHPStan and PHPCS MUST report zero errors or warnings for the new test file - AND any pre-existing issues in nearby files encountered during the task MUST also be fixed + +### Requirement: REQ-ACT-007 Reaction debounce holds regardless of deployment topology + +@e2e exclude needs an instance without APCu (CI runs one topology), and dashboard_reacted is never emitted; pinned by tests/Unit/Activity/DebounceHelperApcuTest.php::testADisabledApcuFallsBackToTheDistributedCache, ::testAnEnabledApcuAnswersTheClaimAndTheCacheIsNotUsed and tests/Unit/Activity/DebounceHelperTest.php::testDistributedCachePathDebouncesAcrossClaims + +The per-`(actorUserId, dashboardUuid)` reaction debounce (900-second window) MUST hold across HTTP requests and PHP-FPM worker processes on every supported deployment topology, including installations where the +APCu PHP extension is not installed or not enabled for the running SAPI. +The debounce MUST NOT silently degrade to "always allow" when APCu is +unavailable. + +#### Scenario: Debounce holds without APCu across two separate requests + +- **GIVEN** a Nextcloud instance with APCu not installed +- AND user "bob" reacted to dashboard `abc` in request 1, one second ago +- **WHEN** bob reacts to dashboard `abc` again in a separate HTTP request + (request 2) within the same 900-second window +- **THEN** `allowReaction('bob', 'abc')` MUST return `false` in request 2 +- **AND** no second reaction activity row MUST be written + +#### Scenario: Debounce still uses APCu when available + +- **GIVEN** a Nextcloud instance with APCu installed and enabled +- **WHEN** `allowReaction()` is called +- **THEN** the claim MUST be served via `apcu_add()` exactly as before this + change (no regression to the fast path) + +### Requirement: REQ-ACT-008 Global fan-out debounce holds regardless of deployment topology + +@e2e exclude needs an instance without APCu, or a fake clock injected into DebounceHelper; pinned by tests/Unit/Activity/DebounceHelperTest.php::testDistributedCachePathDebouncesGlobalFanout and tests/Unit/Activity/DebounceHelperClockTest.php::testAFakeClockNeverUsesTheDistributedCache + +The per-`(dashboardUuid, eventType)` fan-out debounce (900-second window) MUST hold across HTTP requests and PHP-FPM worker processes, including on installations without APCu. + +#### Scenario: Fan-out debounce holds without APCu across two separate requests + +- **GIVEN** a Nextcloud instance with APCu not installed +- AND a `dashboard_updated` fan-out for dashboard `abc` was performed in + request 1 +- **WHEN** a second `dashboard_updated` event for dashboard `abc` arrives in + a separate HTTP request within the same 900-second window +- **THEN** `allowGlobalFanout('abc', 'dashboard_updated')` MUST return + `false` in request 2 +- **AND** the fan-out MUST be skipped silently, exactly as the existing + single-request scenario requires + +#### Scenario: Deterministic unit tests remain unaffected + +- **GIVEN** a test injects a fake clock into `DebounceHelper` +- **WHEN** the test advances the fake clock past the 900-second window +- **THEN** the helper MUST continue to use the in-memory fallback for + deterministic behaviour, unaffected by this change + +### Requirement: LaunchPad events can reach the activity digest email (REQ-DIGE-001) + +@e2e exclude both scenarios end in the content of a digest email, which needs NC Activity's mail cron job, a week of time and a mail sink; the CI fixture has no mail catcher. The mail defaults (on for shared/published, off for updated/acknowledged) are pinned by tests/Unit/Activity/Settings/ActivitySettingsTest.php::testDefaultsAndGroup + +LaunchPad MUST register activity settings for `dashboard_shared`, `dashboard_published`, `dashboard_updated` and `dashboard_acknowledged` in one group named "LaunchPad", each changeable for the stream and for mail. Mail MUST default to on for `dashboard_shared` and `dashboard_published` and to off for the other two. + +#### Scenario: Pieter gets a weekly email + +- **GIVEN** Pieter set his Nextcloud activity email to weekly and left the LaunchPad defaults +- **WHEN** Karin shares the dashboard "Team Vergunningen" with him on Tuesday +- **THEN** his weekly activity email lists "Karin shared the dashboard Team Vergunningen with you" + +#### Scenario: Updates stay out of the email by default + +- **GIVEN** Pieter left the LaunchPad defaults +- **WHEN** a dashboard shared with him is edited +- **THEN** the change shows in his activity stream and not in his digest email + +### Requirement: Sharing and publishing emit activity events (REQ-DIGE-002) + +LaunchPad MUST emit `dashboard_shared` to the recipients when a dashboard is shared, and `dashboard_published` to the target audience when a dashboard becomes published, including the first time a scheduled dashboard is surfaced as published. The person who acted MUST NOT receive a recipient row of their own. For a share, the sharer MUST instead receive the one row that names every recipient (REQ-ACT-005, Ruben 21 Nov 2026). + +#### Scenario: Group dashboard published + +- **GIVEN** Noor schedules the group dashboard "Organisatie" for group "Medewerkers" to publish on Monday 08:00 +- **WHEN** it is first surfaced as published after that time +- **THEN** each member of "Medewerkers" gets one `dashboard_published` activity for "Organisatie" +- **AND** Noor gets none + +### Requirement: Updates to shared dashboards are summarised, not repeated (REQ-DIGE-003) + +LaunchPad MUST emit `dashboard_updated` to the audience of a shared or group dashboard when it is saved, at most once per dashboard per 24 hours. A save of a private dashboard MUST NOT write any activity row (REQ-ACT-004). + +#### Scenario: Ten edits in one morning + +- **GIVEN** Karin edits the shared dashboard "Team Vergunningen" ten times on one morning +- **WHEN** Pieter looks at his activity stream that afternoon +- **THEN** he sees one entry "Karin updated the dashboard Team Vergunningen" diff --git a/openspec/specs/admin-roles/screens.md b/openspec/specs/admin-roles/screens.md new file mode 100644 index 000000000..6250baa7d --- /dev/null +++ b/openspec/specs/admin-roles/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerRollen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerRollen diff --git a/openspec/specs/admin-roles/spec.md b/openspec/specs/admin-roles/spec.md index 9a14307fe..375eb0f54 100644 --- a/openspec/specs/admin-roles/spec.md +++ b/openspec/specs/admin-roles/spec.md @@ -26,12 +26,9 @@ Each role assignment is stored in the `oc_launchpad_role_assignments` table with ## Requirements - -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: REQ-ROLE-001 Dashboard Admin Role Definition -A Dashboard Admin MUST have full administrative access to LaunchPad, equivalent to Nextcloud admin status but scoped to LaunchPad only. A Dashboard Admin MUST be able to manage all dashboards, install demo data, edit organization-level navigation, and define new metadata fields. +A Dashboard Admin MUST be able to manage all dashboards through the normal API: edit any dashboard and create a group dashboard for any group (REQ-DASH-014). The admin API (`/api/admin/*`: settings, demo data, organisation navigation, metadata field definitions, roles) MUST stay Nextcloud-administrator only; the LaunchPad Admin role does not open it (Ruben, 21 Nov 2026). NOTE: Admin-roles is a net-new LaunchPad capability with no source counterpart. The source app has no named-role concept and resolves all permissions from the GroupFolder ACL bitmask alone. The three role names echo the source app's seeded group names for customer recognition, but the underlying mechanism is entirely different — LaunchPad does not read from those groups at runtime. @@ -47,7 +44,7 @@ NOTE: Admin-roles is a net-new LaunchPad capability with no source counterpart. - WHEN an NC admin creates a role assignment with `userId = "alice"`, `role = "admin"` - THEN alice's effective role becomes "admin" - AND the role source MUST be "user-assigned" -- AND alice gains access to LaunchPad admin section: `/admin/settings`, `/admin/demo`, `/admin/metadata`, `/admin/roles` +- AND `/api/admin/settings`, `/api/admin/demo-showcases`, `/api/admin/metadata-fields` and `/api/admin/roles` MUST still answer her with HTTP 403, because she is not a Nextcloud administrator #### Scenario: Dashboard Admin can edit any dashboard - GIVEN a user with effective role "admin" @@ -55,23 +52,28 @@ NOTE: Admin-roles is a net-new LaunchPad capability with no source counterpart. - THEN the permission check MUST return true - AND no group membership check is required -#### Scenario: Dashboard Admin can manage metadata field definitions -- GIVEN a user with role "admin" +#### Scenario: Dashboard Admin cannot manage metadata field definitions +- GIVEN a user with role "admin" who is not a Nextcloud administrator - WHEN the user calls `POST /api/admin/metadata-fields` with a new field definition -- THEN the system MUST allow the creation -- AND the field is available for use on all dashboards (not scoped to a group) +- THEN the system MUST refuse with HTTP 403 +- AND no field is created -#### Scenario: Dashboard Admin can install demo data -- GIVEN a user with role "admin" -- WHEN the user calls `POST /api/admin/demo/install` with a demo package ID -- THEN the system MUST allow the installation -- AND demo dashboards appear in the appropriate scope +#### Scenario: Dashboard Admin cannot install demo data +- GIVEN a user with role "admin" who is not a Nextcloud administrator +- WHEN the user calls `POST /api/admin/demo-showcases/{id}/install` +- THEN the system MUST refuse with HTTP 403 +- AND the showcase stays as it was -#### Scenario: Dashboard Admin can edit organization navigation -- GIVEN a user with role "admin" +#### Scenario: Dashboard Admin cannot edit organization navigation +- GIVEN a user with role "admin" who is not a Nextcloud administrator - WHEN the user calls `PUT /api/admin/org-navigation` with new navigation structure -- THEN the system MUST allow the update -- AND the changes are persisted and visible to all users +- THEN the system MUST refuse with HTTP 403 +- AND the navigation stays as it was + +#### Scenario: Dashboard Admin creates a group dashboard for a group they are not in +- GIVEN a user with role "admin" who is not a Nextcloud administrator and not in group "sales" +- WHEN the user calls `POST /api/dashboards/group/sales` +- THEN the system MUST create the group dashboard (HTTP 201) ### Requirement: REQ-ROLE-002 Dashboard Editor Role Definition @@ -79,9 +81,15 @@ A Dashboard Editor MUST be able to create and edit dashboards within their group #### Scenario: Dashboard Editor creates a new group_shared dashboard - GIVEN a user "bob" with role "editor" in group "engineering" -- WHEN bob calls `POST /api/dashboards` with `scope = "group_shared"`, `groupId = "engineering"` -- THEN the system MUST allow the creation -- AND bob becomes the owner of the new dashboard +- WHEN bob calls `POST /api/dashboards/group/engineering` +- THEN the system MUST allow the creation (HTTP 201) +- AND the new dashboard is a `group_shared` dashboard of "engineering" with no owner (`userId` null, REQ-DASH-014), which bob can edit as an Editor in that group + +#### Scenario: Dashboard Editor cannot create a group dashboard for another group +- GIVEN a user "bob" with role "editor" who is not in group "sales" +- WHEN bob calls `POST /api/dashboards/group/sales` +- THEN the system MUST refuse with HTTP 403 +- AND no dashboard is created #### Scenario: Dashboard Editor can edit group_shared dashboard in their group - GIVEN a "group_shared" dashboard in group "engineering" diff --git a/openspec/specs/admin-settings/screens.md b/openspec/specs/admin-settings/screens.md new file mode 100644 index 000000000..481fb4a6f --- /dev/null +++ b/openspec/specs/admin-settings/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpBeheerDelen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerDelen +- LpBeheerAlgemeen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAlgemeen +- LpBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpBewerken diff --git a/openspec/specs/admin-settings/spec.md b/openspec/specs/admin-settings/spec.md index ea1406cf2..a315fa16e 100644 --- a/openspec/specs/admin-settings/spec.md +++ b/openspec/specs/admin-settings/spec.md @@ -10,8 +10,6 @@ Admin settings provide Nextcloud administrators with global configuration option ## Data Model -@e2e exclude Most scenarios here are REST, service or config contracts, covered by PHPUnit and Newman rather than a browser. The browser-observable parts are still exercised: the two REQ-ASET-002 round-trip scenarios are cited by tests/e2e/admin-settings-key-roundtrip.spec.ts, and the personal-dashboard flag's sidebar effect is covered by tests/e2e/allow-personal-dashboards-flag.spec.ts. - ### Admin Settings (oc_launchpad_admin_settings) Settings are stored as key-value pairs: - **id**: Auto-increment integer primary key @@ -28,9 +26,10 @@ Settings are stored as key-value pairs: | `default_permission_level` | `defaultPermissionLevel` | string | `add_only` | Default permission level for user-created dashboards | | `default_grid_columns` | `defaultGridColumns` | integer | `12` | Default number of grid columns for new dashboards | | `link_create_file_extensions` | `linkCreateFileExtensions` | `string[]` | `["txt","md","docx","xlsx","csv","odt"]` | Extensions the link-button widget's "create file" action may create (REQ-LBN-004). An empty stored list resolves to the default. | -| `content_storage` | `launchpad.content_storage` | string | `database` | Active content storage backend (REQ-GFSB-006). The response key is dotted, unlike the others. | | `default_share_permission_level` | `defaultSharePermissionLevel` | string | `add_only` | Org-wide default permission for a new share (dashboard-sharing spec) | | `forced_share_groups` | `forcedShareGroups` | `string[]` | `[]` | Groups every new dashboard is force-shared with (dashboard-sharing spec) | +| `sharing_allowed_groups` | `sharingAllowedGroups` | `string[]` | `[]` | Groups whose members may share a dashboard; empty means everyone may (dashboard-sharing REQ-SHARE-014) | +| `sharing_recipient_scope` | `sharingRecipientScope` | string | `everyone` | Whom a dashboard may be shared with: `everyone`, or `shared-groups` (only people and groups the sharer shares a group with). Anything else reads as `everyone` (dashboard-sharing REQ-SHARE-014). | | `legacy_widget_bridge_enabled` | `legacyWidgetBridgeEnabled` | boolean | `false` | Whether the workspace reads Nextcloud's widget registry (legacy-widget-bridge spec) | | `max_dashboards_per_user` | `maxDashboardsPerUser` | integer | `0` | Personal dashboard quota per user, `0` = unlimited (REQ-QUOTA-001) | | `max_widgets_per_dashboard` | `maxWidgetsPerDashboard` | integer | `0` | Placement quota per dashboard, `0` = unlimited (REQ-QUOTA-001) | @@ -38,15 +37,17 @@ Settings are stored as key-value pairs: | `group_order` | n/a (separate `/api/admin/groups` endpoints) | `string[]` (JSON) | `[]` | Ordered list of Nextcloud group IDs that are "active" for LaunchPad workspace routing (REQ-ASET-012). Read via `AdminSettingsService::getGroupOrder()`; written via `setGroupOrder()`. Corrupt JSON resolves to `[]`. | NOTE: The DB stores settings with snake_case keys, but the API response returns camelCase keys. The factory default for `defaultPermissionLevel` is `add_only` (Dashboard::PERMISSION_ADD_ONLY), NOT `full`. The API update endpoint accepts each setting under the key the GET response uses (`defaultPermissionLevel`, `allowUserDashboards`, `allowMultipleDashboards`, `defaultGridColumns`, `linkCreateFileExtensions`) and under its short parameter name (`defaultPermLevel`, `allowUserDash`, `allowMultiDash`, `defaultGridCols`, `linkCreateFileExts`). When both arrive in one body the short name wins. See REQ-ASET-002. + ## Requirements + ### Requirement: Retrieve Admin Settings (REQ-ASET-001) -Administrators MUST be able to retrieve all current admin settings via the API. The endpoint returns a flat JSON object with the twelve settings listed under Defined Settings, each under its API response key. `group_order` is not among them; it has its own endpoints (REQ-ASET-012). +Administrators MUST be able to retrieve all current admin settings via the API. The endpoint returns a flat JSON object with the thirteen settings listed under Defined Settings, each under its API response key. `group_order` is not among them; it has its own endpoints (REQ-ASET-012). #### Scenario: Get all settings with defaults - GIVEN no admin settings have been explicitly configured (fresh installation) - WHEN the admin sends GET /api/admin/settings -- THEN the system MUST return HTTP 200 with all twelve settings at their default values: +- THEN the system MUST return HTTP 200 with all thirteen settings at their default values: ```json { "defaultPermissionLevel": "add_only", @@ -54,9 +55,10 @@ Administrators MUST be able to retrieve all current admin settings via the API. "allowMultipleDashboards": true, "defaultGridColumns": 12, "linkCreateFileExtensions": ["txt", "md", "docx", "xlsx", "csv", "odt"], - "launchpad.content_storage": "database", "defaultSharePermissionLevel": "add_only", "forcedShareGroups": [], + "sharingAllowedGroups": [], + "sharingRecipientScope": "everyone", "legacyWidgetBridgeEnabled": false, "maxDashboardsPerUser": 0, "maxWidgetsPerDashboard": 0, @@ -69,7 +71,7 @@ Administrators MUST be able to retrieve all current admin settings via the API. - GIVEN the admin has set `allowUserDashboards` to `false` - WHEN the admin sends GET /api/admin/settings - THEN the response MUST carry `"allowUserDashboards": false` -- AND the other eleven keys MUST still be present with their current values +- AND the other twelve keys MUST still be present with their current values #### Scenario: Non-admin user retrieves settings - GIVEN a regular user "alice" @@ -86,10 +88,23 @@ Administrators MUST be able to retrieve all current admin settings via the API. #### Scenario: Settings response format consistency - GIVEN the admin has configured various settings at different times - WHEN GET /api/admin/settings is called -- THEN the response MUST always return exactly the twelve keys listed under Defined Settings: `defaultPermissionLevel`, `allowUserDashboards`, `allowMultipleDashboards`, `defaultGridColumns`, `linkCreateFileExtensions`, `launchpad.content_storage`, `defaultSharePermissionLevel`, `forcedShareGroups`, `legacyWidgetBridgeEnabled`, `maxDashboardsPerUser`, `maxWidgetsPerDashboard`, `quicksearchFallbackTarget` +- THEN the response MUST always return exactly the thirteen keys listed under Defined Settings: `defaultPermissionLevel`, `allowUserDashboards`, `allowMultipleDashboards`, `defaultGridColumns`, `linkCreateFileExtensions`, `defaultSharePermissionLevel`, `forcedShareGroups`, `sharingAllowedGroups`, `sharingRecipientScope`, `legacyWidgetBridgeEnabled`, `maxDashboardsPerUser`, `maxWidgetsPerDashboard`, `quicksearchFallbackTarget` - AND no additional keys MUST be present in the response - NOTE: This scenario said "exactly four keys" long after the response had grown to twelve. The list above is taken from `AdminSettingsService::getSettings()`; a key added there MUST be added here and to the Defined Settings table. -- AND the response MUST be a flat JSON object (no nesting) +- AND the response MUST be a flat JSON object (no nesting), except `leaverHandover`, which is `{manager, fallbackUid}` (REQ-SHARE-016) +- NOTE: Other capabilities added keys since (`filterTelemetryEnabled`, `tileAllowedSchemes`, `ssoLaunchTemplates`, `announcementEditorGroups`, `officeNetworks`, `currentAddress`, `currentAddressInOfficeNetworks`, `pinnedCommunities`, `defaultAppEnabled`, `sharingAllowed`, `publicLinksAllowed`, `leaverHandover`); `AdminSettingsServiceTest::testGetSettingsReturnsExactlyTheDocumentedKeysAtTheirDefaults` and `tests/e2e/admin-settings-api.spec.ts` pin the full list + +#### Scenario: The retired content storage key is not returned +- GIVEN an instance that still holds a `content_storage` row written by the retired setup-wizard storage step +- WHEN the admin sends GET /api/admin/settings +- THEN the response MUST NOT contain `launchpad.content_storage` +- AND the stored row MUST stay unread (decision 131) + +#### Scenario: The retired start-page key is not returned +- GIVEN an instance where `start_page_without_navigation` may still be stored from when the option existed (runtime-shell REQ-SHELL-009) +- WHEN the admin sends a PUT /api/admin/settings that still carries `"startPageWithoutNavigation": true` +- THEN the PUT MUST answer 200 and store nothing for that key +- AND a following GET /api/admin/settings MUST NOT contain `startPageWithoutNavigation` ### Requirement: Update Admin Settings (REQ-ASET-002) @@ -131,21 +146,22 @@ Administrators MUST be able to update individual or multiple admin settings in a #### Scenario: Update with invalid permission level value - GIVEN the admin sends PUT /api/admin/settings with body `{"defaultPermLevel": "super_admin"}` -- THEN the system SHOULD return HTTP 400 with a validation error -- AND only `view_only`, `add_only`, and `full` SHOULD be accepted for this setting -- NOTE: Permission level validation is NOT currently implemented -- any string value is accepted +- THEN the system MUST return HTTP 400 with a validation error (`{"error": "<message>"}`) +- AND only `view_only`, `add_only`, and `full` MUST be accepted for this setting, under either spelling +- AND nothing in the request MUST be stored #### Scenario: Update with invalid grid columns value - GIVEN the admin sends PUT /api/admin/settings with body `{"defaultGridCols": 0}` -- THEN the system SHOULD return HTTP 400 with a validation error -- AND `defaultGridCols` SHOULD be a positive integer between 1 and 24 -- NOTE: Grid columns validation is NOT currently implemented -- any integer value is accepted +- THEN the system MUST return HTTP 400 with a validation error (`{"error": "<message>"}`) +- AND `defaultGridCols` MUST be a whole number from 1 to 24 +- AND nothing in the request MUST be stored #### Scenario: Update with invalid boolean value - GIVEN the admin sends PUT /api/admin/settings with body `{"allowUserDash": "maybe"}` -- THEN the system SHOULD return HTTP 400 with a validation error -- AND boolean settings SHOULD only accept `true` or `false` -- NOTE: Boolean validation is NOT currently implemented -- PHP type coercion handles the value +- THEN the system MUST return HTTP 400 with a validation error (`{"error": "<message>"}`) +- AND boolean settings MUST only accept `true` or `false` (also as `0`, `1`, `"0"`, `"1"`, `"true"`, `"false"`) +- AND nothing in the request MUST be stored +- NOTE: Nextcloud casts a bool parameter before the controller sees it, so `AdminController` checks the raw request value #### Scenario: Non-admin cannot update settings - GIVEN a regular user "alice" @@ -260,13 +276,14 @@ When `allow_multiple_dashboards` is false, users MUST be limited to one dashboar - AND alice MUST NOT be able to create additional dashboards - AND alice MUST be able to delete dashboards to get down to 1 -#### Scenario: Template distribution overrides multiple dashboard restriction +#### Scenario: A new template reaches only users on their first access - GIVEN `allowMultipleDashboards` is set to `false` - AND user "alice" has 1 dashboard -- AND a new admin template targets alice's group -- WHEN the template distribution triggers for alice -- THEN the system MUST still create the template copy for alice -- AND alice MUST have 2 dashboards (the restriction applies to user-initiated creation, not admin-initiated distribution) +- AND a new admin template targets the group of alice and of "bob", who has never opened LaunchPad +- WHEN alice and bob open LaunchPad +- THEN the system MUST NOT create a template copy for alice, who keeps her 1 dashboard: templates are distributed on first access only (REQ-TMPL-005), whatever this setting says +- AND bob MUST receive the template copy as his first dashboard +- AND an admin who wants the template on existing users' dashboards uses re-sync (REQ-TMPL-005 is unaffected by it) ### Requirement: Default Permission Level Setting (REQ-ASET-005) @@ -305,13 +322,12 @@ The `defaultPermissionLevel` setting MUST be applied as a fallback when resolvin ### Requirement: Default Grid Columns Setting (REQ-ASET-006) -The `defaultGridColumns` setting MUST be applied to new dashboards when no explicit gridColumns is specified. +The `defaultGridColumns` setting MUST be applied to new dashboards when no explicit gridColumns is specified. The admin page offers it as a select of 6, 8 and 12 columns. #### Scenario: Default grid columns applied - GIVEN `defaultGridColumns` is set to `8` - WHEN user "alice" sends POST /api/dashboard with body `{"name": "My Dashboard"}` - THEN the created dashboard MUST have `gridColumns: 8` -- NOTE: `DashboardFactory::create()` currently hardcodes `gridColumns: 12` and does NOT read the `defaultGridColumns` admin setting. This is a known gap. #### Scenario: Explicit grid columns overrides default - GIVEN `defaultGridColumns` is set to `8` @@ -357,7 +373,8 @@ Admin settings MUST be persisted across server restarts and app updates. ### Requirement: Admin Settings UI (REQ-ASET-008) -The admin settings MUST be accessible via a Nextcloud admin panel page. +The admin settings MUST be accessible via a Nextcloud admin panel page. The +form MUST save each change as soon as it is made; it has no Save button. #### Scenario: Admin settings page is registered - GIVEN a Nextcloud admin user @@ -377,14 +394,14 @@ The admin settings MUST be accessible via a Nextcloud admin panel page. - A toggle for "Allow user dashboards" (on/off) - A toggle for "Allow multiple dashboards" (on/off) - A dropdown for "Default permission level" (view_only, add_only, full) - - A number input for "Default grid columns" (1-24) - - A "Save" button + - A select for "Default grid columns" offering 6, 8 and 12 (Ruben, 21 Nov 2026, following the product) - AND each setting MUST show its current value +- AND the form MUST NOT show a Save button, since every change is saved at once -#### Scenario: Settings saved via the UI -- GIVEN the admin changes "Allow user dashboards" to off and clicks Save -- WHEN the save completes -- THEN the system MUST display a success notification +#### Scenario: Each change is saved at once +- GIVEN the admin opens the LaunchPad admin settings page +- WHEN the admin switches "Allow user dashboards" off +- THEN the page MUST send the change to PUT /api/admin/settings straight away, without a Save step - AND GET /api/admin/settings MUST reflect the change ### Requirement: Settings Impact on Existing Data (REQ-ASET-009) @@ -605,133 +622,77 @@ The current value of `allow_user_dashboards` MUST be pushed as initial state `al - THEN the store MUST surface a localised toast via `@nextcloud/dialogs::showError` reading the `Personal dashboards are not enabled by your administrator` translation - AND the original error MUST be re-thrown so callers can short-circuit -### Requirement: REQ-ASET-012 Group order setting +### Requirement: Program schemes and single sign-on launch templates are admin settings (REQ-ASET-020) -The system MUST persist an ordered list of Nextcloud group IDs as the global setting `group_order` (JSON `string[]`, default `[]`). The order MUST be preserved exactly as provided. The setting determines which groups are "active" for LaunchPad workspace routing (REQ-TMPL-012). Corrupt or unparseable JSON in the database MUST resolve to `[]` at read time without throwing — the resolver and admin UI MUST never see a fatal error from a malformed value. +The admin settings MUST hold `tileAllowedSchemes` (stored as `tile_allowed_schemes`), a list of lower-case URL schemes a program tile may use, and `ssoLaunchTemplates` (stored as `sso_launch_templates`), a list of `{key, name, urlTemplate}` where `urlTemplate` is an https address containing `{appId}` exactly once. Both MUST be empty by default. A write MUST be refused with HTTP 400, naming the entry, when a scheme is not lower-case or is one of `javascript`, `data`, `file`, `vbscript`, `about` or `blob`, or when a template is not https, lacks or repeats `{appId}`, carries another placeholder or credentials, or reuses a key; a refused write MUST leave both lists as they were. A stored value that no longer validates MUST read as empty. With these two, `GET /api/admin/settings` (REQ-ASET-001) returns fourteen keys; the REQ-ASET-001 list is updated when this change is archived. -#### Scenario: Persist ordered list +#### Scenario: A script scheme cannot be allowed -- GIVEN admin sends `POST /api/admin/groups` with body `{"groups": ["engineering", "all-staff", "marketing"]}` -- THEN the setting `group_order` MUST be persisted as the JSON string `["engineering","all-staff","marketing"]` -- AND a subsequent `GET /api/admin/groups` MUST return the same order in `active` +- **GIVEN** an administrator on the LaunchPad admin page +- **WHEN** they save `javascript` as an allowed scheme +- **THEN** the response is 400 naming `javascript` and the allowed list is unchanged -#### Scenario: Empty list clears active groups +#### Scenario: A launch template must be https with the app id -- GIVEN admin sends `POST /api/admin/groups` with body `{"groups": []}` -- THEN the setting MUST be persisted as `[]` -- AND `resolvePrimaryGroup` MUST return `'default'` for every user (per REQ-TMPL-012) +- **GIVEN** an administrator defining a launch template +- **WHEN** they save `http://idp.example.nl/{appId}` +- **THEN** the response is 400 and no template is stored -#### Scenario: Replace-wholesale, not merge +### Requirement: One list of allowed websites with a purpose per site (REQ-ASET-021) -- GIVEN current `group_order = ["a", "b", "c"]` -- WHEN admin sends `POST /api/admin/groups` with body `{"groups": ["c", "b"]}` -- THEN the setting MUST become exactly `["c", "b"]` -- AND `"a"` MUST be removed (no implicit merge) +The General tab (board LpBeheerAlgemeen) SHALL hold one block "Allowed websites" ("Toegestane websites"): a list of +hosts, each with its purpose: Embed ("Insluiten"), Fetch ("Ophalen") or Embed and fetch, with "Add website" and Save. +The list SHALL be stored as one admin setting. Embed SHALL allow the host for the embedded page widget and for images +from outside; Fetch SHALL allow it for live tiles, health pings and external calendar feeds. Each of those features +SHALL check a URL against the hosts allowed for its purpose and SHALL stay fail-closed: a host not on the list, or +on it for the other purpose only, SHALL be refused as before. A host SHALL be saved lower case, without scheme, path +or port, and an entry that is not a host SHALL be refused with a message. On the first upgrade, the hosts of the +existing per-feature allow-lists SHALL be merged into the list with the purpose they had, so nothing that worked +stops working. -#### Scenario: Corrupt DB JSON falls back to empty array +#### Scenario: Power BI may be embedded, not called -- GIVEN the row `group_order` exists in `oc_launchpad_admin_settings` with `setting_value = '{not-json'` -- WHEN any caller invokes `AdminSettingsService::getGroupOrder()` -- THEN the method MUST return `[]` -- AND MUST NOT throw an exception -- AND `GET /api/admin/groups` MUST return `active: []` in this state +- **GIVEN** the list holds `app.powerbi.com` with purpose Embed +- **WHEN** an author places an embedded page from `https://app.powerbi.com/...` +- **THEN** the widget saves and renders +- **AND** a live tile with a URL on `app.powerbi.com` is refused at save time -#### Scenario: Default when setting absent +#### Scenario: The KCC API may be called, not embedded -- GIVEN no `group_order` row has ever been written to `oc_launchpad_admin_settings` -- WHEN `AdminSettingsService::getGroupOrder()` is called -- THEN it MUST return `[]` (factory default) +- **GIVEN** the list holds `kcc-api.zuiddrecht.nl` with purpose Fetch +- **WHEN** an author configures a live tile on `https://kcc-api.zuiddrecht.nl/wachttijd` +- **THEN** the tile fetches its value +- **AND** an embedded page on that host is refused -### Requirement: REQ-ASET-013 List groups for admin UI +#### Scenario: Existing lists survive the upgrade -The system MUST expose `GET /api/admin/groups` returning `{active: [id…], inactive: [id…], allKnown: [{id, displayName}…]}`: +- **GIVEN** before the upgrade `livetile_allowed_hosts` held `kcc-api.zuiddrecht.nl` and the embed list held `app.powerbi.com` +- **WHEN** the app is upgraded +- **THEN** the Allowed websites block lists `kcc-api.zuiddrecht.nl` with Fetch and `app.powerbi.com` with Embed -- `active`: the persisted `group_order` list (in admin-chosen order, preserved exactly). -- `inactive`: every Nextcloud group ID NOT in `active`, sorted by display name (case-insensitive). -- `allKnown`: full descriptor list (`{id, displayName}`) for every Nextcloud group currently known, so the UI can render display names without a second round-trip. +### Requirement: The administration is a Launchpad page over the full width (REQ-ADM-030) -Stale IDs (present in `active` but no longer in Nextcloud) MUST remain in `active` so the admin can see and remove them, but MUST NOT appear in `allKnown` (no display name available). The UI is expected to render stale IDs with a "(removed)" affix. +The Launchpad administration SHALL be a page of Launchpad itself at `/apps/launchpad/admin/<tab>`, with Launchpad's top bar, the title "Launchpad administration: <tab>", the path "Administration settings / Launchpad / <tab>", the tabs over the full width and no left menu. The page SHALL check on the server, before it renders, that the reader is an administrator or a delegated Launchpad administrator. -#### Scenario: Lists are disjoint and exhaustive +#### Scenario: Open the administration -- GIVEN Nextcloud has groups `["a", "b", "c", "d"]` and `group_order = ["b", "d"]` -- WHEN admin sends `GET /api/admin/groups` -- THEN the response MUST be `{active: ["b", "d"], inactive: ["a", "c"], allKnown: [{id:"a",displayName:"..."}, {id:"b",displayName:"..."}, {id:"c",displayName:"..."}, {id:"d",displayName:"..."}]}` -- AND `active ∪ inactive` MUST equal the set of IDs in `allKnown` -- AND `active ∩ inactive` MUST be empty +- **GIVEN** beheer is a Launchpad administrator +- **WHEN** she chooses Settings, Administration settings in the More menu +- **THEN** the page opens without Nextcloud's settings menu, on the tab General -#### Scenario: Order in `active` matches admin-chosen order +#### Scenario: Not an administrator -- GIVEN `group_order = ["zebra", "alpha", "marigold"]` -- WHEN admin sends `GET /api/admin/groups` -- THEN `active` MUST be exactly `["zebra", "alpha", "marigold"]` (no alphabetical re-sort) -- AND `inactive` MUST be sorted alphabetically by `displayName` +- **WHEN** Pieter opens `/apps/launchpad/admin/general` +- **THEN** the server answers 403 and renders nothing of the page -#### Scenario: Empty group_order — all groups inactive +### Requirement: Nextcloud's settings point to the page (REQ-ADM-031) -- GIVEN `group_order = []` and Nextcloud has groups `["a", "b"]` -- WHEN admin sends `GET /api/admin/groups` -- THEN `active` MUST be `[]` -- AND `inactive` MUST contain both `"a"` and `"b"` +The Launchpad entry under Nextcloud's administration settings SHALL say where the administration is and link to the page. -#### Scenario: Stale group IDs surface in active list +#### Scenario: From Nextcloud's settings -- GIVEN `group_order = ["deleted-group", "engineering"]` and Nextcloud no longer has `"deleted-group"` -- WHEN admin sends `GET /api/admin/groups` -- THEN the response's `active` MUST still include `"deleted-group"` (so admin can see and remove it) -- AND `allKnown` MUST NOT include it (no display name to show) -- AND `inactive` MUST NOT include it -- NOTE: The UI SHOULD render stale IDs with a "(removed)" affix. - -### Requirement: REQ-ASET-014 Admin guard and payload validation - -`POST /api/admin/groups` MUST be admin-only (`IGroupManager::isAdmin`). Non-admins MUST receive HTTP 403 with no side effects. `GET /api/admin/groups` MUST also be admin-only because the inactive list reveals every group on the system. - -The `POST` payload MUST be validated: -- Top-level `groups` key MUST exist and MUST be a JSON array. -- Every element MUST be a non-empty string. -- Duplicate IDs in the payload MUST be deduplicated (first occurrence wins, preserving order). -- Validation failures MUST return HTTP 400 with no side effects on the persisted setting. - -Unknown (not currently in Nextcloud) IDs MUST NOT cause validation failure — they are tolerated and persisted (per REQ-ASET-013 stale-ID handling). - -#### Scenario: Non-admin POST rejected - -- GIVEN user "alice" who is not an administrator -- WHEN she sends `POST /api/admin/groups` with any body -- THEN the system MUST return HTTP 403 -- AND the persisted `group_order` MUST be unchanged - -#### Scenario: Non-admin GET rejected - -- GIVEN user "alice" who is not an administrator -- WHEN she sends `GET /api/admin/groups` -- THEN the system MUST return HTTP 403 - -#### Scenario: Missing `groups` key rejected - -- GIVEN admin sends `POST /api/admin/groups` with body `{}` -- THEN the system MUST return HTTP 400 -- AND the persisted `group_order` MUST be unchanged - -#### Scenario: Non-string element rejected - -- GIVEN admin sends `POST /api/admin/groups` with body `{"groups": ["engineering", 42, "marketing"]}` -- THEN the system MUST return HTTP 400 -- AND the persisted `group_order` MUST be unchanged - -#### Scenario: Duplicate IDs deduplicated - -- GIVEN admin sends `POST /api/admin/groups` with body `{"groups": ["a", "b", "a", "c"]}` -- THEN the persisted `group_order` MUST be exactly `["a", "b", "c"]` (first occurrence kept, duplicates removed) -- AND the response MUST be HTTP 200 - -#### Scenario: Unknown IDs accepted - -- GIVEN admin sends `POST /api/admin/groups` with body `{"groups": ["does-not-exist", "engineering"]}` -- AND `"does-not-exist"` is not a known Nextcloud group -- THEN the request MUST succeed (HTTP 200) -- AND `group_order` MUST be persisted as `["does-not-exist", "engineering"]` +- **WHEN** an administrator opens Administration settings, Launchpad in Nextcloud +- **THEN** she sees one line and a link that opens the Launchpad administration page ## Non-Functional Requirements @@ -758,13 +719,9 @@ Unknown (not currently in Nextcloud) IDs MUST NOT cause validation failure — t **Not yet implemented:** - REQ-ASET-002 validation: No server-side validation for permission level values (any string accepted), grid column range (any integer accepted), or boolean type coercion. Documented as NOTEs in the spec. -- REQ-ASET-006 default grid columns: `DashboardFactory::create()` hardcodes `gridColumns: 12` and does NOT read the `defaultGridColumns` admin setting. The admin setting exists but is not applied when creating user dashboards. - REQ-ASET-003 fork endpoint: The `POST /api/dashboards/{uuid}/fork` route is owned by the separate `fork-current-as-personal` capability and does not yet exist; gating will be added there with the same `PersonalDashboardsDisabledException` envelope. - REQ-ASET-008 localization: UI labels use `t('launchpad', ...)` translation function but actual Dutch translations are not verified in l10n files. -**Partial implementations:** -- REQ-ASET-006 (Default Grid Columns): The setting can be stored and retrieved, but `DashboardFactory::create()` ignores it, hardcoding 12. Template copies correctly use the template's `gridColumns` via `TemplateService::buildDashboardFromTemplate()`. - ### Standards & References - Nextcloud Admin Settings API: `OCP\Settings\ISettings`, `OCP\Settings\IIconSection` - Nextcloud AppConfig pattern (though this app uses a custom DB table instead of `IAppConfig`) diff --git a/openspec/specs/admin-templates/screens.md b/openspec/specs/admin-templates/screens.md new file mode 100644 index 000000000..1d3172ede --- /dev/null +++ b/openspec/specs/admin-templates/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerSjablonen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerSjablonen diff --git a/openspec/specs/admin-templates/spec.md b/openspec/specs/admin-templates/spec.md index edd2ba439..873e9d6e9 100644 --- a/openspec/specs/admin-templates/spec.md +++ b/openspec/specs/admin-templates/spec.md @@ -46,8 +46,6 @@ Admin templates are stored as dashboards in `oc_launchpad_dashboards` with `type Templates own their widget placements (in `oc_launchpad_widget_placements`) which serve as the blueprint for user copies. The template's placements include `isCompulsory` flags that are copied to user dashboards. When a user copy is created, `TemplateService::createDashboardFromTemplate()` clones all placements from the template to the new user dashboard. ## Requirements -@e2e exclude all scenarios test REST CRUD for admin template dashboards — template distribution and UI admin forms are not yet implemented in this version - ### Requirement: Create Admin Template (REQ-TMPL-001) Nextcloud administrators MUST be able to create dashboard templates for distribution to users. @@ -96,6 +94,7 @@ Nextcloud administrators MUST be able to create dashboard templates for distribu - THEN the system MUST return HTTP 400 with a validation error - AND only `view_only`, `add_only`, and `full` MUST be accepted - NOTE: Permission level validation is NOT currently implemented -- any string is accepted +@e2e exclude never built: no permission-level check exists, AdminController::createTemplate passes `permissionLevel` to AdminTemplateService::createTemplate, which calls setPermissionLevel with the raw string (lib/Service/AdminTemplateService.php, createTemplate and updateTemplate); storing the valid levels `add_only` and `view_only` is cited under create-a-template-targeting-specific-groups and create-a-default-template-for-all-users (tests/e2e/admin-templates-crud.spec.ts) #### Scenario: Create template with UUID generation - GIVEN a Nextcloud admin user @@ -124,12 +123,15 @@ Administrators MUST be able to view all existing templates with their configurat - THEN the template object SHOULD include a widget_count field showing 6 - AND this helps admins understand the template's complexity at a glance - NOTE: Widget count is NOT currently included in the list response +@e2e exclude never built: AdminController::listTemplates serialises the bare Dashboard entities (serializeList), which carry no widget count; the only `widgetCount` is on the template gallery entries (AdminTemplateService gallery, WidgetPlacementMapper::countByDashboardId), a different endpoint #### Scenario: Empty template list - GIVEN no admin templates have been created - WHEN the admin sends GET /api/admin/templates - THEN the system MUST return HTTP 200 with an empty array +@e2e exclude Needs an instance with no admin template at all; the e2e instance is shared and other suites' templates may be on it, and deleting them is not this suite's to do. Pinned by AdminTemplateServiceGalleryTest::testGalleryReturnsEmptyListWhenNoTemplates and AdminControllerRolesAndTemplatesTest::testListTemplatesSerialisesEveryTemplate. + #### Scenario: Templates filtered from user dashboard list - GIVEN 3 admin templates and 2 user dashboards exist - WHEN user "alice" sends GET /api/dashboards @@ -228,7 +230,7 @@ When a user accesses LaunchPad for the first time, the system MUST create person - AND bob has never opened LaunchPad - WHEN bob navigates to LaunchPad - THEN the system MUST create a personal copy of "Marketing Dashboard" for bob -- NOTE: `TemplateService::getApplicableTemplate()` returns only ONE template (the first matching group-targeted template takes priority over the default). Multiple template distribution is NOT implemented. +- NOTE: `TemplateService::getApplicableTemplate()` returns only ONE template (a group-targeted template takes priority over the default; REQ-TMPL-021 says which one when several target the user's groups). Multiple template distribution is NOT implemented. #### Scenario: First-time user not in any target group - GIVEN template "Marketing Dashboard" targets groups ["marketing"] @@ -238,6 +240,8 @@ When a user accesses LaunchPad for the first time, the system MUST create person - THEN the system MUST NOT create any dashboard for carol from the marketing template - AND if `allowUserDashboards` is true, the system MUST create a default "My Dashboard" with recommendations and activity widgets +@e2e exclude The last clause needs an instance without the dashboard for everyone: SeedDefaultDashboard seeds it on install, it outranks the personal "My Dashboard" (DashboardService::resolveRoleLayoutOrDefaultGroupDashboard), and removing it would empty a fixture every suite uses. The personal path is pinned by DashboardServiceCreateDefaultsTest::testSeedDefaultsInsertsThreeTilesAndFilesWidget (which also shows the bundle is tiles and a files widget, not recommendations and activity). The THEN clause runs in tests/e2e/template-reaches-member.spec.ts (the outsider test). + #### Scenario: Template already distributed to user - GIVEN user "alice" already has a personal copy of template "Company Dashboard" - WHEN alice navigates to LaunchPad again @@ -295,6 +299,7 @@ Administrators MUST be able to manage widget placements on templates using the s - WHEN the admin arranges widgets on the template via the grid - THEN the positions MUST be saved as the template's widget placements - AND new user copies MUST receive these exact positions +@e2e exclude never built: no page opens an admin template on the grid, src/ has no route or view that loads a dashboard of type `admin_template` (TemplatesPage.vue edits metadata only, TemplateEditorModal.vue has no grid); positioning a template's widgets through the placement API is cited under update-template-widget-layout (tests/e2e/admin-templates-template-widgets.spec.ts) #### Scenario: Template placements include tile data - GIVEN the admin adds a tile placement to template id 1 with inline tile data (tileTitle, tileIcon, etc.) @@ -448,9 +453,11 @@ All workspace-rendering and dashboard-resolution code paths (REQ-DASH-013, REQ-D - THEN it MUST go through `AdminTemplateService::resolvePrimaryGroup` (or its declared service interface) - AND duplicating the algorithm inline is forbidden by code review +@e2e exclude A code-review rule about where code lives, with no runtime behaviour. Pinned by AdminTemplateServiceGrepGuardTest::testIGroupManagerCallIsConfinedToResolver. + ### Requirement: Template Gallery Endpoint (REQ-TMPL-014) -The system MUST expose a read-only gallery endpoint that lists all `admin_template` dashboards with metadata suitable for discovery and instantiation. +The system MUST expose a read-only gallery endpoint that lists the `admin_template` dashboards offered to the calling user (REQ-TMPL-018) with metadata suitable for discovery and instantiation. > NOTE (D2 — Index): The `WHERE type='admin_template' AND templateCategory=?` filter path MUST be backed by a composite index on `(type, templateCategory)`. The migration adding the three new metadata columns MUST also add this composite index to keep the optional category-filter query indexed at scale. The base `WHERE type='admin_template'` path already benefits from the existing index on `type`. @@ -490,6 +497,25 @@ The system MUST expose a read-only gallery endpoint that lists all `admin_templa - THEN the template MUST be included - AND when calling `GET /api/templates/gallery?category=marketing`, the template with `null` category MUST NOT be included +### Requirement: The gallery offers a template to the groups it names (REQ-TMPL-018) + +The gallery (`GET /api/templates/gallery` and the MCP tool `launchpad.listTemplates`) MUST list only the admin templates offered to the calling user. A template is offered to a user when its `targetGroups` is empty, contains the `default` group, or contains one of the user's groups. Forking (`POST /api/dashboards/{uuid}/fork` and the MCP tool `launchpad.forkDashboard`) MUST accept exactly the templates the gallery offers the user, as well as the dashboards the user can see, and MUST answer any other template as not found. + +#### Scenario: The gallery lists the templates for the user's groups + +- GIVEN admin templates for no group, for the `default` group, for group `sales` and for group `finance` +- AND user "alice" is a member of `sales` only +- WHEN alice sends `GET /api/templates/gallery` +- THEN the response MUST list the first three templates +- AND it MUST NOT list the template for `finance` + +#### Scenario: A fork accepts exactly what the gallery offers + +- GIVEN the templates of the previous scenario +- WHEN alice forks the template for `sales` +- THEN she MUST get a personal copy of it +- AND forking the template for `finance` MUST answer HTTP 404, as for a dashboard she cannot see + ### Requirement: Template Metadata Fields (REQ-TMPL-016) Admin templates MUST support three new metadata fields for categorization and discovery: `templateCategory` (VARCHAR 64, nullable), `templateDescription` (TEXT, nullable), and `templatePreviewImage` (TEXT, nullable). The fields are stored as nullable columns on `oc_launchpad_dashboards` and only meaningful for rows with `type = 'admin_template'`. @@ -511,12 +537,16 @@ Admin templates MUST support three new metadata fields for categorization and di - GIVEN user "alice" saves her dashboard as a template with `category: 'product'` - THEN the new template's `templateCategory` MUST be set to `'product'` +@e2e exclude Never built: there is no save-as-template route in appinfo/routes.php and no saveAsTemplate in lib/ or src/ in any commit (`git log --all -S saveAsTemplate -- lib appinfo src` is empty); tasks 4.2 and 5.3 of the archived dashboard-templates change are unchecked. + #### Scenario: Template description field length - GIVEN a user provides a `description` string of 500 characters when calling save-as-template - THEN the system MUST accept and store the full 500 characters (unlike the regular `description` field, which may be shorter) - NOTE: The `templateDescription` column stores longer text; validation MUST NOT truncate +@e2e exclude Never built: it is a save-as-template scenario, and that endpoint does not exist (see the scenario above). + #### Scenario: Metadata fields are nullable - GIVEN a template with all metadata fields set to null @@ -628,6 +658,8 @@ All workspace-rendering and dashboard-resolution code paths (REQ-DASH-013, REQ-D - THEN it MUST go through `AdminTemplateService::resolvePrimaryGroup` (or its declared service interface) - AND duplicating the algorithm inline is forbidden by code review +@e2e exclude A code-review rule about where code lives, with no runtime behaviour. Pinned by AdminTemplateServiceGrepGuardTest::testIGroupManagerCallIsConfinedToResolver. + ### Requirement: REQ-RESYNC-001 Re-sync action pushes template updates to existing copies Administrators MUST be able to push an updated admin template to its already-provisioned user copies via `POST /api/admin/templates/{id}/resync`, choosing a `strategy` of `overwrite` or `merge`. The action MUST be restricted to Nextcloud admins and MUST target only copies whose `basedOnTemplate` references the given template. Re-sync is an explicit, opt-in override of template copy independence (REQ-TMPL-006); first-access distribution (REQ-TMPL-005) MUST be unaffected. @@ -755,6 +787,266 @@ A real (non-dry-run) re-sync MUST be idempotent — applying the same plan twice - THEN the system MUST enqueue `TemplateResyncJob` and return a prompt accepted response - AND the job MUST apply the plan per copy and notify each affected user on completion +### Requirement: REQ-TMPL-018 Templates that ship with LaunchPad + +LaunchPad MUST ship ready-made admin templates as data, one file per template at `data/templates/<id>.json`. A definition holds `templateId`, an integer `templateVersion`, a `language`, and one `dashboard` in the shape an export writes to `dashboards/<uuid>.json` (REQ-EXIM-001). The list of shipped ids is fixed in `ShippedTemplateService::SHIPPED_IDS`. + +An administrator MUST be able to add a shipped template as an admin template from the Templates page (`POST /api/admin/templates/shipped/{id}/install`) and from the command line (REQ-CLI-012). Installing MUST go through the dashboard importer (REQ-EXIM-004), so a shipped template and an uploaded archive take one path. The installed template MUST keep every widget's configuration and its `isCompulsory` flag (REQ-EXIM-012). + +Installing MUST NOT hand the template to anybody on its own. The definition ships with no target groups and is not the default. The administrator chooses the groups, or makes it the default, with the install options or afterwards on the Templates page (REQ-TMPL-003). + +LaunchPad MUST remember the install per template: app config `shipped_template_<id>` holds the UUID and `shipped_template_version_<id>` the version. A second install MUST add nothing unless forced. A forced install MUST add a fresh copy and MUST leave the earlier one in place, because dashboards made from it point at it. Bringing an installed template to a newer shipped version is not a forced install: that is the update of REQ-TMPL-020, which keeps the template and its copies. When the recorded template was deleted, the shipped template MUST count as not installed. + +A definition that is missing or malformed MUST fail the install with an error. It MUST NOT install an empty template. + +The listing MUST name, per template, the Nextcloud dashboard widgets it shows that no app on the instance registers (`missingWidgets`). Those widgets are still placed, so the template has one shape on every instance. + +The first shipped template is `mijn-werkdag`, a start page for a municipal employee, in Dutch. A shipped template MUST render as installed, with no further setting: it MUST NOT proxy a Nextcloud dashboard widget that has no items API, because LaunchPad paints those only when the legacy widget bridge is switched on (off by default), and every field its lists name MUST exist in the schema they read. `mijn-werkdag` holds a header, the "First today" list across apps (`attention-feed`, since template version 2), the employee's dossiq cases past their deadline, the employee's open dossiq cases, the employee's open pipelinq tickets ("Mijn tickets": `assignee` is the employee, `status` one of `new`, `in_progress`, `awaiting_customer`, by `slaDeadline`; since version 3), the decidiq decisions open for voting ("Wacht op uw stem": `lifecycle` is `voting`, by `submittedAt`; since version 3) and recent activity. The header and the "First today" list are compulsory. Its permission level is `add_only`. Every list in it sets `hideWhenUnavailable` (REQ-TMPL-022), so on an instance without pipelinq or decidiq those lists are not shown. A filter value that is a list of values means any of them and is sent as `status[0]=..&status[1]=..`, which OpenRegister honours (measured on 5 October 2026); every such value MUST be one the schema's enum names (the renders-as-installed test holds them against `tests/fixtures/registers`). + +#### Scenario: An administrator adds the shipped template and gives it to a group +- GIVEN LaunchPad ships the template `mijn-werkdag` and it is not installed +- WHEN an administrator adds it from the Templates page, then edits it and picks the group "medewerkers" +- THEN the template list MUST show "Mijn werkdag" with the group "medewerkers" +- AND a member of "medewerkers" who opens LaunchPad for the first time MUST get a dashboard made from it, with the header and the "First today" list marked compulsory + +#### Scenario: Installing twice adds one template +- GIVEN `mijn-werkdag` is installed +- WHEN an administrator installs it again without forcing +- THEN no second template MUST be added +- AND the response MUST say it was already installed and name the same UUID + +#### Scenario: A template deleted by the administrator can be added again +- GIVEN `mijn-werkdag` was installed and the administrator deleted that template +- WHEN the administrator installs it again +- THEN a new template MUST be added without forcing + +#### Scenario: A broken definition fails loudly +- GIVEN the file for a shipped template is missing or has no widgets +- WHEN an administrator installs it +- THEN the install MUST fail with an error that names the file +- AND no template MUST be added + +@e2e exclude A packaging fault cannot be staged in a browser: pinned by ShippedTemplateServiceTest::testAMalformedDefinitionFails. + +#### Scenario: The listing names widgets no app registers here +- GIVEN no app on the instance registers the `activity` widget +- WHEN an administrator lists the shipped templates +- THEN `mijn-werkdag` MUST list `activity` under `missingWidgets` + +#### Scenario: The shipped template renders as installed +- GIVEN the shipped definition `data/templates/mijn-werkdag.json` and an instance with dossiq and default LaunchPad settings +- WHEN a member opens the dashboard made from it +- THEN no widget MUST show "This widget can only be shown on the Nextcloud dashboard itself." or a raw widget id as its heading +- AND the "Termijn" column of both case lists MUST show each case's deadline + +@e2e exclude Needs dossiq with cases on the instance, which the e2e instance does not have. Pinned by ShippedTemplateServiceTest::testAShippedTemplateRendersAsInstalled, and seen in a browser on a test instance on 5 October 2026. + +#### Scenario: Every widget in the shipped template is one LaunchPad can place +- GIVEN the shipped definition `data/templates/mijn-werkdag.json` +- WHEN its widgets are read +- THEN every `widgetId` MUST be on LaunchPad's own widget type list (`lib/widget-types.json`) +- AND no two widgets MUST share a grid cell +- AND every widget MUST fit inside the template's grid columns + +@e2e exclude A check on shipped data, not a browser behaviour: pinned by ShippedTemplateServiceTest::testTheShippedDefinitionIsWellFormed. + +#### Scenario: The version 3 lists name only fields and values their schemas have +- GIVEN the shipped definition and the copies of pipelinq's `ticket` and decidiq's `decision` schemas in `tests/fixtures/registers` +- WHEN the lists "Mijn tickets" and "Wacht op uw stem" are read +- THEN every column, sort field and filter field MUST exist in its schema +- AND every `status` and `lifecycle` value MUST be one the schema's enum names +- AND both lists MUST set `hideWhenUnavailable` + +@e2e exclude A check on shipped data against copied schemas: pinned by ShippedTemplateServiceTest::testAShippedTemplateRendersAsInstalled. pipelinq and decidiq are not on the e2e instance. + +### Requirement: REQ-TMPL-019 A member is shown their template on the first visit + +A user who owns no personal dashboard and has no saved choice (no pinned default and no last-used dashboard that they can still see) MUST be shown the admin template that applies to them (REQ-TMPL-005: a template that targets one of their groups, else the default template). Both resolution chains MUST do this at the same place, directly after the saved-choice steps and before any group dashboard: the page shell's chain (REQ-DASH-018, step 1b) and `GET /api/dashboard` (REQ-DASH-009). + +Precedence: + +- A template that targets one of the user's groups MUST outrank every group dashboard, the user's own group's default included. +- The default template MUST outrank the dashboards of the `default` group (everyone), including the one seeded on install. It MUST step aside for a default dashboard of the user's own primary group, which is the more specific of the two. + +What the user gets: + +- With personal dashboards allowed (`allowUserDashboards`), the user MUST receive a personal copy (REQ-TMPL-005), once. The copy MUST be stored as their last-used dashboard, so later visits resolve it through the saved-choice step. +- With personal dashboards off, no copy MUST be made (REQ-ASET-003). The template itself MUST be shown, view only. Its compulsory flags have no effect then, because nothing can be removed. + +A user who owns a personal dashboard, or has a saved choice, MUST NOT be affected by this requirement. + +**Why this was written down.** Templates were only known to `GET /api/dashboard`, at the very end of its chain. The page decides what to show from the other chain, which did not know templates. So on an instance with the seeded dashboard for everyone, that dashboard always won; and without it the page said "No dashboards available" and never called the API that would have made the copy. Every unit test was green and no member of a targeted group had ever been shown a template. Found by a live check on 5 October 2026. + +**What changes on an instance that already has templates.** A user who owns nothing and has no saved choice now lands on their template (and, with personal dashboards on, receives a copy) where they used to land on a group dashboard. Nobody else is moved. + +**Known limit.** With personal dashboards off, the view-only template is not in the dashboard switcher. A member who opens another dashboard cannot switch back to it. + +#### Scenario: A new member sees the template, although a dashboard for everyone exists +- GIVEN the instance has the seeded dashboard for everyone and personal dashboards are allowed +- AND the template "Mijn werkdag" targets the group "behandelaars" +- AND Sanne is in "behandelaars" and has never opened LaunchPad +- WHEN Sanne opens LaunchPad +- THEN she MUST see "Mijn werkdag", as a personal copy with the template's compulsory widgets +- AND a second visit MUST show the same copy and MUST NOT make another + +#### Scenario: Without any other dashboard the page still shows the template +- GIVEN no group dashboard exists and the template targets Sanne's group +- WHEN Sanne opens LaunchPad for the first time +- THEN she MUST see the template's dashboard and MUST NOT see "No dashboards available" + +@e2e exclude Needs an instance with no group dashboard at all, and the e2e instance is shared with other suites' fixtures. Pinned by DashboardServiceTemplateRungTest::testWithNoOtherDashboardThePageStillShowsTheTemplate. + +#### Scenario: Personal dashboards off +- GIVEN personal dashboards are off and the template targets Sanne's group +- WHEN Sanne opens LaunchPad for the first time +- THEN she MUST see the template itself, view only +- AND no personal dashboard MUST be created for her + +#### Scenario: The default template replaces the dashboard for everyone +- GIVEN the seeded dashboard for everyone exists and a default template exists +- AND Mark is in no group that a template targets and his primary group has no default dashboard +- WHEN Mark opens LaunchPad for the first time +- THEN he MUST get the default template, not the seeded dashboard + +#### Scenario: People already using LaunchPad are left alone +- GIVEN Pieter owns a personal dashboard, and Lotte has a last-used dashboard she can still see +- AND a template now targets a group both are in +- WHEN each opens LaunchPad +- THEN neither MUST be moved to the template and no copy MUST be made for them + +### Requirement: REQ-TMPL-020 Updating an installed shipped template in place + +When LaunchPad ships a higher `templateVersion` of a template than the one installed (`shipped_template_version_<id>`), an administrator MUST be able to bring the installed template to that version with one action: the "Update to version N" button on the Templates page (`POST /api/admin/templates/shipped/{id}/update`) or `occ launchpad:template:install <id> --update` (REQ-CLI-012). The listing (REQ-TMPL-018) MUST say so per template with `updateAvailable`. + +The update MUST keep the installed template: its id, UUID, name, description, target groups, default flag and permission level stay as they are. It MUST replace the template's widgets with the shipped version's. A widget an administrator added to the installed template by hand, or changed there, is replaced with it. + +**A widget in both versions keeps its row.** A member's copy remembers, per widget, the id of the template widget it came from, and re-sync matches on that id (REQ-RESYNC-003). A definition carries no key per widget, so the update pairs the installed widgets with the new ones in three passes, each over what the pass before left: + +1. every field a definition sets is equal: the widget is unchanged and is not written; +2. same widget type, same proxied Nextcloud widget and same title: the row is kept and changed; +3. same widget type, when exactly one such widget is left on each side: the row is kept and changed. + +What is then left of the new version is added. What is left of the installed template is removed. Settings (`content`, `styleConfig`) are compared as data, so the same settings in another key order are unchanged. + +**Members' copies follow.** After the template is written, the update MUST re-sync the copies with the `merge` strategy (REQ-RESYNC-001, -003, -004). So a compulsory widget the new version adds arrives in every copy, a widget the new version drops leaves every copy, and a widget a member added to their own copy stays. As with every merge re-sync, a template widget a member moved or changed is set back to the template's, and a template widget a member removed comes back. More than 50 copies are re-synced in the background (REQ-RESYNC-005). With personal dashboards off there are no copies: members see the template itself (REQ-TMPL-019), so they see the new version at once. + +**Never silently.** The result MUST name every widget added, removed and changed, the number unchanged and the number of members' copies. A dry run (`dryRun=true`, `--dry-run`) MUST return the same lists and MUST write nothing: no widget, no version, no copy. The Templates page MUST show the dry run and ask for confirmation before it updates. + +The widgets of the template MUST be written in one transaction. When a write fails, nothing MUST be kept and the recorded version MUST stay, so the next run tries again. The recorded version MUST be raised only after the widgets are written. + +When the installed version is the shipped one or newer, the update MUST change nothing and MUST say so (`upToDate`). When the template is not installed, the endpoint MUST answer 409 and the command MUST exit 1; an unknown id answers 404. + +#### Scenario: An administrator updates the installed template from the Templates page +- GIVEN `mijn-werkdag` is installed at version 2, targets the group "behandelaars", and LaunchPad ships version 3 +- WHEN the administrator presses "Update to version 3" on the Templates page +- THEN a dialog MUST list the widgets that are added, removed and changed, and the number of members with a copy +- AND nothing MUST be written until the administrator confirms +- WHEN the administrator confirms +- THEN the same template MUST hold version 3's widgets, still target "behandelaars", and the button MUST be gone + +#### Scenario: A member's copy follows and keeps what the member added +- GIVEN Pieter has a copy of the installed template and added a widget of his own to it +- WHEN the administrator updates the template to a version that adds a compulsory widget and drops another widget +- THEN Pieter's copy MUST hold the new compulsory widget +- AND the dropped widget MUST be gone from his copy +- AND the widget Pieter added MUST still be there + +#### Scenario: A dry run writes nothing +- GIVEN `mijn-werkdag` is installed at an older version +- WHEN an administrator asks for the update with `dryRun` +- THEN the answer MUST list the widgets added, removed and changed +- AND the template, the recorded version and every copy MUST be as before + +Pinned by ShippedTemplateUpdateServiceTest::testADryRunWritesNothing and, on a real instance, by tests/e2e/shipped-template-update.spec.ts (the recorded version is lowered through the app-config API, so the dry run's lists are empty there). + +#### Scenario: A widget in both versions keeps its row +- GIVEN the installed template and the new version both hold the list "Mijn zaken", with other settings +- WHEN the template is updated +- THEN the list's row MUST keep its id and carry the new settings + +#### Scenario: Nothing to do +- GIVEN the installed version is the version LaunchPad ships +- WHEN an administrator asks for the update +- THEN nothing MUST be written and the answer MUST say the template is up to date + +Pinned by ShippedTemplateUpdateServiceTest::testAMembersCopyFollowsAndKeepsTheirOwnWidget (second run), TemplateInstallCommandTest::testAnUpToDateTemplateSaysSoAndExitsZero and tests/e2e/shipped-template-update.spec.ts. + +#### Scenario: A failed write keeps the recorded version +- GIVEN the database refuses a write halfway through the update +- THEN the update MUST fail with an error, roll back, and leave the recorded version unchanged + +@e2e exclude A database fault cannot be staged in a browser. Pinned by ShippedTemplateUpdateServiceTest::testAFailedWriteKeepsTheRecordedVersion. + +### Requirement: REQ-TMPL-021 One rule picks the template when several target the same group + +When more than one admin template targets a group the user is in, `TemplateService::getApplicableTemplate()` MUST pick the same template on every instance and every visit, by this order: + +1. the installed copy of a shipped template (the template `shipped_template_<id>` names) goes before a template made by hand, and among shipped templates the higher recorded version goes first; +2. then the lowest template id, which is the oldest template. + +A template that targets one of the user's groups still goes before the default template (REQ-TMPL-005). + +**Why.** The rule used to be "the first match", and the list was sorted by name, so two templates with the same name came out in the order the database happened to return them. After `occ launchpad:template:install <id> --force` an instance holds the old and the new copy of a shipped template for the same group, under the same name, and a new member could get either. The forced copy is the recorded one, so it now wins. + +**What changes on an existing instance.** Only where two or more templates target the same group. There, a user without a dashboard of their own used to get the template whose name sorts first; they now get the installed shipped template if one of them is that, else the oldest. With personal dashboards off, where members are shown the template itself on every visit (REQ-TMPL-019), such a member can see another template after the upgrade than before. A user who already has a copy keeps it. An instance where every group has one template is not affected. + +#### Scenario: The oldest hand-made template wins +- GIVEN the templates "Aanvragen" (id 9) and "Zaken" (id 4) both target a group Pieter is in +- WHEN Pieter opens LaunchPad for the first time +- THEN he MUST get "Zaken" + +#### Scenario: After a forced install the recorded copy wins +- GIVEN a forced install left the earlier "Mijn werkdag" (id 7) next to the recorded one (id 9), both for "behandelaars" +- WHEN a new member of "behandelaars" opens LaunchPad +- THEN they MUST get the template with id 9 + +#### Scenario: A shipped template goes before a hand-made one +- GIVEN the hand-made template "Afdeling" (id 3) and the installed shipped template "Mijn werkdag" (id 9) both target a group Pieter is in +- WHEN Pieter opens LaunchPad for the first time +- THEN he MUST get "Mijn werkdag" + +### Requirement: REQ-TMPL-022 A list on a register that is not here is hidden + +An object-list widget whose configuration sets `hideWhenUnavailable: true` MUST NOT be shown to a viewer when OpenRegister answers 404 for its register or schema (`GET /apps/openregister/api/objects/{register}/{schema}?_limit=1`): the app that owns the register is not installed, so the list has nothing to say and would otherwise show "Could not load these records" under its title to every employee. The page asks once per source and remembers the answer for the page's life. + +Only a 404 hides. Any other failure (403, 500, no network) MUST leave the list on the page with its own error line, because that is a fault someone has to see. In edit mode the list MUST stay on the page, so whoever edits the dashboard sees it is there. + +A list without the flag behaves as before. The flag is data in the widget's `content`, so a template written by hand can set it too. Every list in a shipped template MUST set it. + +LaunchPad does not know on the server which registers an instance has. So the listing of shipped templates and `occ launchpad:template:install` MUST name the registers a template's lists read (`registers`), and say that a list whose register is not here is hidden, instead of claiming which ones are missing. + +#### Scenario: An employee on an instance without pipelinq does not see the ticket list +- GIVEN the instance has dossiq and not pipelinq, and the template `mijn-werkdag` version 3 reaches Pieter +- WHEN Pieter opens LaunchPad +- THEN he MUST see "Mijn zaken" and MUST NOT see "Mijn tickets" nor "Could not load these records" + +#### Scenario: A list whose source could not be asked still shows +- GIVEN OpenRegister answers 500 for a list's register +- WHEN the page is shown +- THEN the list MUST be on the page, with its own error line + +#### Scenario: In edit mode the list is there +- GIVEN a list is hidden for Pieter because its register is not here +- WHEN Pieter enters edit mode +- THEN the list MUST be on the page + +### Requirement: REQ-TMPL-023 A refused delete of a compulsory widget says why + +On a copy made from an admin template whose permission level is not `full`, the widget's own menu MUST NOT offer "Delete widget" for a compulsory widget, and the right-click menu MUST NOT offer "Remove" for it. Nothing is sent and the page does not change; the server would answer 403 (REQ-TMPL-006). When a delete of a compulsory widget is still asked for (the page's `removeWidget`), the page MUST say that the widget is part of the start page the administrator set for their group and cannot be removed, naming the widget by its title, and MUST NOT send the delete. + +**Why.** The entry was offered and did nothing: no request, no message, the widget stayed after a reload (#780). The widget menu is LaunchPad's own now (WidgetEditMenu, #1794) and withholds the entry, as the right-click menu does. + +#### Scenario: Delete widget on a compulsory widget +- GIVEN Pieter's copy of "Mijn werkdag" holds the compulsory list "Vandaag eerst" +- WHEN he opens edit mode and opens the widget menu on it +- THEN the menu MUST NOT offer "Delete widget" +- AND no request MUST be sent and the widget MUST stay + +#### Scenario: A widget that is not compulsory is deleted as before +- GIVEN Pieter's copy also holds "Mijn zaken", not compulsory +- WHEN he chooses "Delete widget" on it +- THEN it MUST be removed as before, with no message + ## Non-Functional Requirements - **Performance**: Template distribution (copying placements) MUST complete within 2 seconds per user, even for templates with 20+ widget placements. The first-access check MUST add no more than 200ms to the initial dashboard load. `GET /api/templates/gallery` MUST return within 500ms even with 100+ templates; the gallery list SHOULD NOT fetch widget placements (use `WidgetPlacementMapper::countByDashboardId()` for the count, not `findByDashboardId()`). @@ -792,3 +1084,48 @@ A real (non-dry-run) re-sync MUST be idempotent — applying the same plan twice - Nextcloud User API: `OCP\IUserManager::get()` - WCAG 2.1 AA for the admin template management UI (modal dialogs, form fields) - WAI-ARIA: Modal dialog accessibility via `NcModal` component + +### Requirement: REQ-RESYNC-006 Add-only strategy adds new template widgets and changes nothing else + +`POST /api/admin/templates/{id}/resync` SHALL accept `strategy: "add_only"`. Under it, each copy SHALL gain the +template placements it does not have yet, at the first free spot, and nothing else SHALL change: no placement is moved, +resized, updated or removed, also when the template removed it. Compulsory widgets SHALL still be reconciled as +REQ-RESYNC-004 says. The dry run SHALL report the same plan without writing. + +#### Scenario: Two new widgets reach every copy + +- **GIVEN** 212 copies of template "Intranet medewerkers" at version 13 +- **AND** version 14 added Leesbevestiging and Verjaardagen and removed Oud nieuws +- **WHEN** the admin re-syncs with `{"strategy": "add_only"}` +- **THEN** every copy gains Leesbevestiging and Verjaardagen +- **AND** Oud nieuws stays on every copy that had it, and no other placement moves + +### Requirement: REQ-RESYNC-007 Merge leaves a widget where the person put it + +Under `strategy: "merge"`, a template placement that the copy's owner moved or resized after provisioning SHALL keep +the owner's position and size; the template's other changes to it (title, configuration) SHALL still apply. A +placement the owner did not touch SHALL follow the template as REQ-RESYNC-003 says. + +#### Scenario: Alice moved the news widget + +- **GIVEN** alice moved the template's "Nieuws" widget to the top of her copy +- **AND** the admin changed the template's "Nieuws" feed and moved it down +- **WHEN** the admin re-syncs with `{"strategy": "merge"}` +- **THEN** alice's "Nieuws" stays at the top and reads the new feed + +### Requirement: REQ-RESYNC-008 The rollout window says what will happen + +"Push changes" on a template (board LpBeheerSjablonen) SHALL open a window that names the template, its version and the +number of copies, and SHALL state from a dry run which widgets the template gained and lost since the copies were last +synced. It SHALL offer "How to update?" with three choices, each with its consequence: Only add new widgets (nothing +disappears; personal layout stays; `add_only`), Keep personal changes (the template wins, except what someone moved or +added themselves; `merge`), Replace everything with the template (personal changes are lost; `overwrite`). It SHALL say +how many people changed their copy, and SHALL name the number of dashboards on the confirm button ("Push to 212 +dashboards"). Only Keep personal changes is preselected. + +#### Scenario: The admin opens the rollout window + +- **GIVEN** template "Intranet medewerkers" version 14 with 212 copies, 38 changed by their owners +- **WHEN** the admin chooses Push changes +- **THEN** the window says the template gained Leesbevestiging and Verjaardagen and lost Oud nieuws +- **AND** it offers the three choices with Keep personal changes selected, says 38 people changed their dashboard, and the button reads "Push to 212 dashboards" diff --git a/openspec/specs/announcements/spec.md b/openspec/specs/announcements/spec.md new file mode 100644 index 000000000..9f21271f4 --- /dev/null +++ b/openspec/specs/announcements/spec.md @@ -0,0 +1,109 @@ +# announcements Specification + +## Purpose +News items and notices an author publishes to the people they target: news shows in the announcements widget, where +readers like and comment through Nextcloud's comments and follow categories, and a notice shows as a banner above every +dashboard of the people it targets until its end time. + +## Requirements + +### Requirement: Authors publish targeted announcements (REQ-ANN-001) + +Administrators and members of the announcement editor groups MUST be able to write an announcement with a title, text, optional category, target groups, an optional publish time and a required end time ("Show until", nl "Tonen tot", board LpAankondiging). The server MUST show a published announcement only to people in its target groups (everyone when none are set) between its publish time and its end time, and MUST show drafts only to authors and administrators. The server MUST refuse a new announcement without an end time, or with an end time before its publish time, with HTTP 400; an announcement stored before this rule without an end time MUST keep showing until an author sets one. The form MUST explain that the announcement disappears from every dashboard after its end time, MUST name the end time in its preview ("zichtbaar tot 30 oktober 17:00"), and its confirm button MUST read "Schedule" ("Inplannen") when the publish time lies in the future and "Publish" otherwise. + +#### Scenario: News for one group + +- **GIVEN** Karin is in the announcement editor group +- **WHEN** she publishes "Inloopspreekuur privacy" in category "Privacy" for group "Medewerkers", shown until Friday 17:00 +- **THEN** Pieter, a member of "Medewerkers", sees it in his Announcements widget +- **AND** Sanne, who is not a member, does not see it and gets 404 when she requests it by id + +#### Scenario: Reader cannot author + +- **GIVEN** Pieter is not an administrator and not in the editor group +- **WHEN** he sends `POST /api/announcements` +- **THEN** the response is 403 + +#### Scenario: An end time is required + +- **GIVEN** Karin writes an announcement without a "Show until" +- **WHEN** she sends `POST /api/announcements` +- **THEN** the response is 400 and names the missing end time + +#### Scenario: The announcement disappears after its end time + +- **GIVEN** an announcement shown until 30 October 17:00 +- **WHEN** Pieter opens his dashboard on 30 October at 17:01 +- **THEN** the announcement is not shown + +#### Scenario: Scheduling for later + +- **GIVEN** Karin sets the publish time to next Monday 08:00 +- **THEN** the confirm button reads "Schedule" + +### Requirement: Readers like and comment through Nextcloud comments (REQ-ANN-002) + +Readers MUST be able to like an announcement that targets them and, when the author allowed comments, comment on it. Likes and comments MUST be stored by Nextcloud's comments service, not in LaunchPad tables, and the widget MUST show the like and comment counts. + +#### Scenario: Pieter likes and comments + +- **GIVEN** the announcement "Nieuwe werkplekken op de 3e verdieping" allows comments and targets everyone +- **WHEN** Pieter likes it and comments "Komen er ook sta-bureaus?" +- **THEN** the card shows 1 like and 1 comment +- **AND** his comment is visible to every reader of the announcement + +### Requirement: Readers follow categories (REQ-ANN-003) + +A reader MUST be able to follow and unfollow a category. When an announcement in a followed category becomes visible to a follower, the follower MUST receive one Nextcloud notification. + +#### Scenario: Follow Privacy + +- **GIVEN** Pieter follows "Privacy" +- **WHEN** Karin's scheduled announcement "Nieuwe privacyverklaring" in "Privacy" reaches its publish time +- **THEN** Pieter gets one notification "New announcement in Privacy: Nieuwe privacyverklaring" + +### Requirement: Authors preview before publishing (REQ-ANN-004) + +The editor MUST offer a preview that renders the announcement with the same component readers see, as a card for news and as a banner for a notice, together with the number of people the targeting reaches. Publishing MUST be a separate action after the preview. + +#### Scenario: Preview a notice + +- **GIVEN** Karin writes a notice "Onderhoud zaaksysteem zaterdag 08:00 tot 12:00" for group "Burgerzaken" +- **WHEN** she chooses "Preview" +- **THEN** she sees the warning banner as readers will and "Reaches 42 people" +- **AND** nobody else sees it until she chooses "Publish" + +### Requirement: Notices show above every targeted dashboard for their period (REQ-ANN-005) + +A notice MUST have an end time. While it is visible it MUST show as a banner above the dashboard grid on the Workspace page of everyone it targets, whichever dashboard they open, with its level shown by icon and text, not colour alone. A reader MUST be able to dismiss a dismissible notice for themselves; a non-dismissible notice MUST stay until its end time. + +#### Scenario: Maintenance banner + +- **GIVEN** a published, non-dismissible warning notice for "Burgerzaken" from Friday 17:00 to Saturday 12:00 +- **WHEN** Pieter, in "Burgerzaken", opens any dashboard on Friday at 18:00 +- **THEN** he sees the banner "Onderhoud zaaksysteem zaterdag 08:00 tot 12:00" with a warning icon and no close button +- **AND** on Saturday at 12:01 the banner is gone + +#### Scenario: Notice without an end time + +- **GIVEN** Karin writes a notice +- **WHEN** she tries to publish it without an end time +- **THEN** publishing fails with "A notice needs an end time" + +### Requirement: The announcement form as LpAankondiging draws it (REQ-ANN-006) + +New announcement SHALL open one dialog with the form on the left and "This is how it looks" on the right: a live preview of the card that follows every field, and the note that only the author sees it until the publication time. The form SHALL ask Title, Text, Target group, the kind as two choice cards (News; Maintenance notice, shown at the top of every dashboard until the end time), the read confirmation, "Allow comments and following", Publish on (optional) and Show until. The dialog SHALL end with Cancel and Schedule (Publish when Publish on is empty or past). + +#### Scenario: Write a news item + +- **WHEN** Pieter types the title +- **THEN** the preview on the right shows it at once, without saving + +### Requirement: An announcement asks for a read confirmation (REQ-ANN-007) + +An author SHALL be able to ask the audience to confirm they have read an announcement, with a date to confirm before. The card SHALL then show "I have read this" to each reader in the audience, and the confirmations SHALL feed the read receipts report. + +#### Scenario: Confirm before Friday + +- **GIVEN** the announcement asks for confirmation before Friday 30 October +- **THEN** each reader sees "I have read this" and the preview says "Confirm before 30 October" diff --git a/openspec/specs/api-contract/spec.md b/openspec/specs/api-contract/spec.md new file mode 100644 index 000000000..eb3cd4205 --- /dev/null +++ b/openspec/specs/api-contract/spec.md @@ -0,0 +1,91 @@ +--- +status: done +--- + +# API contract + +## Purpose + +How LaunchPad's JSON API meets the NL API Design Rules that apply to every endpoint, whatever it does: each path carries the major version, each response says which version answered it, errors come back as RFC 9457 problem details, and the OpenAPI document that describes the API is published by the API itself. The document lives at `openapi.json` in the repository root and is linted with the Spectral ruleset of the API Design Rules (`https://static.developer.overheid.nl/adr/ruleset.yaml`). + +## Requirements + +### Requirement: Every API response carries the API version + +Every response of an endpoint under `/api/` MUST carry an `API-Version` header with the installed app version, which is also the `info.version` of the OpenAPI document (/core/version-header). Responses outside `/api/` MUST NOT carry it. + +#### Scenario: A successful API call names its version + +@e2e exclude a response header, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest. + +- GIVEN LaunchPad is installed at version 1.2.3 +- WHEN a client calls any endpoint under `/index.php/apps/launchpad/api/` +- THEN the response MUST carry `API-Version: 1.2.3` + +### Requirement: API errors are problem details + +A JSON error response (status 400 or higher) of an endpoint under `/api/v1/` MUST be served as `application/problem+json` with the members `type`, `title` and `status`, plus `detail` when the body already carries a `detail`, `message` or `error` text (/core/error-handling/problem-details). Every member the body already had MUST be kept. An error of an unversioned `/api/` path MUST keep its body and content type exactly as before, so existing callers see no change. A body that already uses `type`, `title` or `status` for something else, or that is a JSON list, MUST be left as it is. + +#### Scenario: A not-found error becomes problem details + +@e2e exclude a content type and a body shape, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest. + +- GIVEN an endpoint under `/api/v1/` answers `404` with `{"error": "Thing not found"}` +- WHEN the response leaves the app +- THEN its content type MUST be `application/problem+json` +- AND its body MUST be `{"type": "about:blank", "title": "Not Found", "status": 404, "detail": "Thing not found", "error": "Thing not found"}` + +#### Scenario: An unversioned path keeps its error as it was + +@e2e exclude a content type and a body shape, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest. + +- GIVEN an endpoint under an unversioned `/api/` path answers `404` with `{"error": "Thing not found"}` +- WHEN the response leaves the app +- THEN its body MUST still be `{"error": "Thing not found"}` +- AND its content type MUST still be `application/json` + +### Requirement: The API publishes its own OpenAPI document + +`GET /index.php/apps/launchpad/api/v1/openapi.json` MUST return the OpenAPI document without authentication, with `Access-Control-Allow-Origin: *` and with `info.version` set to the installed app version (/core/publish-openapi). When the document is not installed it MUST answer 404. + +#### Scenario: Anyone can read the API description + +@e2e exclude an anonymous JSON endpoint, not browser behaviour; covered by PHPUnit OpenApiControllerTest. + +- GIVEN a client that is not logged in +- WHEN it requests `/index.php/apps/launchpad/api/v1/openapi.json` +- THEN it MUST receive the OpenAPI document with status 200 +- AND the response MUST carry `Access-Control-Allow-Origin: *` + +### Requirement: Every API path is served under its major version + +Every route under `/api/` MUST also be served under `/api/v1/`, with the same controller, requirements and defaults (/core/uri-version). A route the app already declares under `/api/v1/` keeps its path; an unversioned path whose versioned form such a route answers keeps no successor and is listed in `ApiPathAliases::WITHOUT_SUCCESSOR`. The unversioned path MUST keep answering exactly as before, and its responses MUST carry a `Deprecation` header and a `Link` header naming the `/api/v1/` successor with `rel="successor-version"` (/core/deprecation-schedule). The OpenAPI document MUST name `/index.php/apps/launchpad/api/v1` as its server and MUST describe every versioned path the app routes, and no other path. + +#### Scenario: An unversioned path names its successor + +@e2e exclude response headers, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest and ApiPathAliasesTest. + +- GIVEN a client calls `GET /index.php/apps/launchpad/api/settings` +- THEN it MUST receive the same answer as before +- AND the response MUST carry `Deprecation: @1794441600` +- AND the response MUST carry `Link: </index.php/apps/launchpad/api/v1/settings>; rel="successor-version"` + +#### Scenario: The versioned path answers the same request + +@e2e exclude a route table property; covered by PHPUnit ApiPathAliasesTest and OpenApiDocumentTest. + +- GIVEN a route `/api/settings` +- WHEN a client calls `/index.php/apps/launchpad/api/v1/settings` +- THEN the same controller method MUST answer it, without a `Deprecation` header + +### Requirement: Standard protocol paths keep their own formats + +Paths that implement a protocol defined elsewhere (Health check, Prometheus metrics) MUST NOT get a `/api/v1/` alias, a `Deprecation` header, an `API-Version` header or a problem details rewrite: their formats belong to their standard. They are listed in `lib/Middleware/Support/StandardProtocolPaths.php` and are not described in the OpenAPI document. + +#### Scenario: A protocol path is left alone + +@e2e exclude a response shape, not browser behaviour; covered by PHPUnit ApiContractMiddlewareTest. + +- GIVEN a client calls `/index.php/apps/launchpad/api/health` and it answers `400` with `{"error": "x"}` +- THEN the body MUST stay `{"error": "x"}` +- AND the response MUST carry no `API-Version` and no `Deprecation` header diff --git a/openspec/specs/app-catalogue/spec.md b/openspec/specs/app-catalogue/spec.md new file mode 100644 index 000000000..d6787a6a5 --- /dev/null +++ b/openspec/specs/app-catalogue/spec.md @@ -0,0 +1,65 @@ +# app-catalogue Specification + +## Purpose +A catalogue of the apps the organisation has approved, shown per group in the add flow, that a person turns into a tile in one click, and a way to ask IT for an app that is missing. + +## Requirements + +### Requirement: Administrators keep a catalogue of approved apps (REQ-ACAT-001) + +An administrator MUST be able to add, edit and remove catalogue entries with a name, a short description, an icon, an address (a Nextcloud app or a web address) and the groups that may see the entry. An entry with no groups MUST be visible to everyone. + +#### Scenario: Administrator adds an app for one group + +- **GIVEN** Noor is an administrator on the LaunchPad admin page, section "App catalogue" +- **WHEN** she adds "Zaaksysteem" with address `https://zaken.example.nl` for group "Burgerzaken" and saves +- **THEN** the entry is listed with the group "Burgerzaken" + +### Requirement: Users add catalogue apps as tiles from the add flow (REQ-ACAT-002) + +The add flow MUST show a "From the app catalogue" section listing the entries the user's groups may see, filtered by the same search box. The server MUST return only those entries. Choosing an entry MUST place an ordinary tile with the entry's name, icon and address. + +#### Scenario: Member adds the app + +- **GIVEN** Pieter is in group "Burgerzaken" and edits his dashboard "Mijn werkplek" +- **WHEN** he opens "Add", types "zaak" and picks "Zaaksysteem" from "From the app catalogue" +- **THEN** a tile "Zaaksysteem" linking to `https://zaken.example.nl` appears at the bottom of his dashboard + +#### Scenario: Non-member does not see it + +- **GIVEN** Sanne is not in group "Burgerzaken" +- **WHEN** she opens "Add" and searches "zaak" +- **THEN** "Zaaksysteem" is not listed, and `GET /api/catalogue` does not return it for her + +### Requirement: Users can ask for a missing app (REQ-ACAT-003) + +The add flow MUST offer "Can't find your app?", which takes an app name and what the user needs it for. Submitting MUST store an open request and notify every administrator and the members of the optional catalogue manager group. A user MUST NOT have more than 10 open requests. + +#### Scenario: Pieter asks for a map viewer + +- **GIVEN** Pieter cannot find a map viewer in the catalogue +- **WHEN** he chooses "Can't find your app?", enters "Kaartviewer" and "Ik moet percelen bekijken bij vergunningen", and sends it +- **THEN** he sees "Your request was sent to IT" +- **AND** Noor gets a Nextcloud notification "Pieter asked for the app Kaartviewer" + +#### Scenario: Too many open requests + +- **GIVEN** Pieter has 10 open requests +- **WHEN** he sends an eleventh +- **THEN** the request is refused with "You have 10 open requests. Wait for an answer first." + +### Requirement: Administrators decide on requests and the requester hears back (REQ-ACAT-004) + +The admin page MUST list open requests. Approving MUST open the catalogue form prefilled with the requested name and link the request to the new entry. Declining MUST require a note. Either decision MUST notify the requester. + +#### Scenario: Request declined with a reason + +- **GIVEN** Pieter's open request "Kaartviewer" +- **WHEN** Noor declines it with the note "Gebruik de kaartlaag in het zaaksysteem" +- **THEN** Pieter gets a notification "Your request for Kaartviewer was declined: Gebruik de kaartlaag in het zaaksysteem" + +#### Scenario: Request approved + +- **GIVEN** Pieter's open request "Kaartviewer" +- **WHEN** Noor approves it, completes the address `https://kaart.example.nl` in the prefilled form and saves +- **THEN** "Kaartviewer" is in the catalogue and Pieter gets a notification "Kaartviewer is now in the app catalogue" diff --git a/openspec/specs/app-connections/screens.md b/openspec/specs/app-connections/screens.md new file mode 100644 index 000000000..4e4dae120 --- /dev/null +++ b/openspec/specs/app-connections/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement +- LpBeheerAlgemeen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAlgemeen diff --git a/openspec/specs/app-connections/spec.md b/openspec/specs/app-connections/spec.md new file mode 100644 index 000000000..03dcb227f --- /dev/null +++ b/openspec/specs/app-connections/spec.md @@ -0,0 +1,155 @@ +# app-connections Specification + +## Purpose +Admins see LaunchPad's outside connections on one page, with a status the app can back. + +## Requirements + +### Requirement: REQ-LP-CONN-001 LaunchPad declares its outside connections in one static file + +LaunchPad SHALL declare its outside connections in `lib/Settings/connections.json` in the shape of hydra connection-registry design D2 (hydra REQ-CONN-001). The file SHALL validate against integriq's `connections.schema.json`, and its `app` SHALL equal the id in `appinfo/info.xml`. It SHALL declare `dashboard-registry`, `weather`, `news-feeds`, `ics-calendars`, `live-tiles` and `health-ping`. `dashboard-registry` SHALL require `registry_url` and SHALL link to the `#section-dashboard-registry` anchor on the Sharing tab of the LaunchPad admin page, and that anchor SHALL exist. The other five SHALL be `reportedOnly`, SHALL carry no `requiredConfig` or `adapter`, and SHALL carry no `settingsUrl`, because no admin screen sets their keys. + +#### Scenario: The declaration names this app and passes integriq's schema +@e2e exclude A static file with no browser surface; tests/Unit/Settings/ConnectionsDeclarationTest.php validates it against the vendored schema, checks the app id, the unique keys and that every settings anchor exists. + +- **GIVEN** `lib/Settings/connections.json` +- **WHEN** it is validated against integriq's `connections.schema.json` +- **THEN** it SHALL validate +- **AND** its `app` SHALL equal the id in `appinfo/info.xml` +- **AND** every key SHALL be unique +- **AND** every `settingsUrl` anchor SHALL exist under `src/` + +#### Scenario: A saved registry URL reads configured +@e2e tests/e2e/integrations-page.spec.ts + +- **GIVEN** integriq has synced LaunchPad's declaration +- **WHEN** an admin saves a registry URL on the Sharing tab +- **THEN** the Dashboard registry row SHALL read Configured with "Required settings are filled." + +### Requirement: REQ-LP-CONN-002 A registry settings save asks integriq to look again + +When `StoreService::updateRegistryConfig()` writes `registry_url`, `registry_register` or `registry_token`, LaunchPad SHALL send `ConnectionRefreshRequestedEvent` with app `launchpad` and key `dashboard-registry` (hydra REQ-CONN-004), and SHALL clear the registry's report memory. The refresh SHALL be sent before any report that follows the save. A save that writes none of those keys SHALL send nothing. The event SHALL be named by string and sent only when the class exists. It SHALL NOT change the result of the save. + +#### Scenario: Saving the registry URL asks for a refresh +@e2e exclude The event is not observable from a browser; tests/Unit/Service/Connection/ConnectionCallersTest.php asserts the refresh and the written keys. + +- **GIVEN** integriq is installed +- **WHEN** an admin saves `registry_url` +- **THEN** LaunchPad SHALL send a refresh request for `dashboard-registry` + +#### Scenario: The refresh goes before the report that follows it +@e2e exclude Event order is not observable from a browser; tests/Unit/Service/Connection/ConnectionCallersTest.php asserts the order. + +- **GIVEN** a registry search reported `error` two minutes ago +- **WHEN** an admin saves `registry_url` and a user then searches the store +- **THEN** LaunchPad SHALL send the refresh request first +- **AND** it SHALL send the search's report after it, without waiting out the five minutes + +#### Scenario: A save that writes no registry key sends nothing +@e2e exclude The event is not observable from a browser; tests/Unit/Service/Connection/ConnectionReporterTest.php asserts that only registry keys refresh. + +- **GIVEN** integriq is installed +- **WHEN** the save writes no registry key +- **THEN** LaunchPad SHALL send no refresh request + +### Requirement: REQ-LP-CONN-003 LaunchPad reports what its outbound calls met + +LaunchPad SHALL report with `ConnectionStatusReportedEvent` what a registry search, a weather provider reading, a news feed fetch, a calendar feed fetch, a live tile fetch and a health ping met, mapped as in the change's design D2. It SHALL report only after a real outbound call or a refusal that says something about the instance, and SHALL NOT report outcomes about one address, one widget or one user. A message SHALL carry at most the host of an address. It SHALL report a different status only after five minutes have passed since the last report, and the same status only after an hour. Without integriq it SHALL read, store, send and log nothing. A report SHALL never throw into the call it observes or change the widget's response. + +#### Scenario: A registry that cannot be reached reads error +@e2e tests/e2e/integrations-page.spec.ts + +- **GIVEN** an admin saved a registry URL where nothing answers +- **WHEN** a user searches the dashboard store +- **THEN** LaunchPad SHALL report `dashboard-registry` as `error` with a message naming the host +- **AND** the search SHALL answer with the same outcome as before this change + +#### Scenario: A weather widget with a location and no provider URL reads unconfigured +@e2e exclude The CI instance sets no weather provider and no widget with a location; tests/Unit/Service/Connection/ConnectionCallersTest.php asserts the report and the unchanged error response. + +- **GIVEN** `weather_provider_url` is empty +- **WHEN** a weather widget with a location asks for a reading +- **THEN** LaunchPad SHALL report `weather` as `unconfigured`, naming `weather_provider_url` + +#### Scenario: A feed fetch reports only the host +@e2e exclude A feed needs a host outside the instance; tests/Unit/Service/Connection/ConnectionObservationsTest.php and tests/Unit/Service/Connection/ConnectionCallersTest.php assert the report and that no path, query or user info reaches it. + +- **GIVEN** a news widget names `https://user:secret@feeds.example.nl/rss?token=abc` +- **WHEN** the feed host answers HTTP 503 +- **THEN** LaunchPad SHALL report `news-feeds` as `error` naming `feeds.example.nl` +- **AND** the message SHALL NOT contain the path, the query or the user info + +#### Scenario: An empty fail-closed allow-list reads unconfigured +@e2e exclude The CI instance sets no live tile or health ping; tests/Unit/Service/Connection/ConnectionCallersTest.php asserts the report through the health ping service, and tests/Unit/Service/Connection/ConnectionReporterTest.php asserts both lists and that a refusal by a non-empty list sends nothing. + +- **GIVEN** `healthping_allowed_hosts` holds no JSON list of hosts +- **WHEN** a tile's health ping is refused +- **THEN** LaunchPad SHALL report `health-ping` as `unconfigured`, naming `healthping_allowed_hosts` + +#### Scenario: Many widget fetches send one report per window +@e2e exclude Timing is not observable from a browser; tests/Unit/Service/Connection/ConnectionReporterTest.php drives the clock through a burst of fetches. + +- **GIVEN** a calendar feed fetch reported `configured` ten minutes ago +- **WHEN** fifty more fetches get an answer within the hour +- **THEN** LaunchPad SHALL send no report + +#### Scenario: Without integriq nothing is sent +@e2e exclude The CI instance installs integriq; tests/Unit/Service/Connection/ConnectionReporterTest.php asserts that nothing is sent, stored or logged when the class is absent. + +- **GIVEN** integriq is not installed +- **WHEN** a feed fetch runs or an admin saves `registry_url` +- **THEN** no event SHALL be sent and nothing SHALL be logged +- **AND** no report memory SHALL be written to app config + +### Requirement: REQ-LP-CONN-004 An admin reads the connections on an Integrations page + +LaunchPad SHALL render an `index` page at `/settings/integrations` over `integriq/app_connection`, reached from the settings gear and preset to `app` equal to `launchpad` through its menu entry's `query` (hydra REQ-CONN-006). The page and its menu entry SHALL be admin only. The page SHALL require Integriq, and the menu entry SHALL only render when integriq is installed. The status column SHALL name all six statuses, `limited` included. The page SHALL NOT offer a generic Add button. Its Add integration action SHALL open `/apps/integriq/connections?app=launchpad&link=1`. + +#### Scenario: The page lists only the rows of launchpad +@e2e tests/e2e/integrations-page.spec.ts + +- **GIVEN** launchpad and integriq are installed and integriq has synced the declaration +- **WHEN** an admin opens the Integrations page +- **THEN** the page SHALL list the six declared connections +- **AND** every listed row SHALL have `app` equal to `launchpad` + +#### Scenario: Add integration goes to integriq +@e2e tests/e2e/integrations-page.spec.ts + +- **GIVEN** the Integrations page +- **WHEN** the admin chooses Add integration +- **THEN** the browser SHALL open integriq's Connections overview with `app=launchpad` and `link=1` + +#### Scenario: A connection that works in part reads Limited +@e2e exclude No CI host rate-limits a call, so no row reads limited there; src/services/__tests__/connectionRegistry.spec.js asserts the label in English and Dutch. + +- **GIVEN** a row whose status is `limited` +- **WHEN** the page renders it +- **THEN** the cell SHALL read Limited, or Beperkt on a Dutch instance + +### Requirement: REQ-LP-CONN-005 A dashboard shows the state of its own connections + +LaunchPad SHALL offer a `connections` widget type ("Koppelingen van dit dashboard", board LpManagement). Each +connection declared in `lib/Settings/connections.json` SHALL name the widget types that use it (`uses`, for example +`live-tiles` for `livetile`, `news-feeds` for `news`, `ics-calendars` for `calendar`, `health-ping` for tiles with a +health ping). The widget SHALL list, once each, the connections that the placements on its own dashboard use, with the +connection's name, its status as the Integrations page names it (REQ-LP-CONN-004), the time of its last success and +the time and message of its last error, as integriq holds them in `integriq/app_connection`. It SHALL read those rows +with the viewer's own session and SHALL NOT call any connection itself. A message SHALL show at most a host, as +REQ-LP-CONN-003 reports it. A connection no placement uses SHALL NOT be listed. Without integriq the widget SHALL say +"Connection states need the Integrations app" and the picker SHALL not offer it. + +#### Scenario: The management dashboard's connections + +- **GIVEN** Managementinformatie holds the live tile "Wachttijd KCC" and a news widget +- **AND** integriq holds `live-tiles` as working, last success 10:44, and `news-feeds` as error since 09:30 with "feeds.example.nl answered 503" +- **WHEN** Pieter opens the dashboard +- **THEN** "Koppelingen van dit dashboard" lists Live tiles with "werkt" and last success 10:44, and News feeds with the error, its time and the host +- **AND** it does not list the weather provider, which no widget on this dashboard uses + +#### Scenario: Without integriq + +- **GIVEN** integriq is not installed +- **WHEN** a dashboard with the connections widget renders +- **THEN** the widget says "Connection states need the Integrations app" +- **AND** the widget picker does not offer "Koppelingen van dit dashboard" diff --git a/openspec/specs/app-tile-widget/spec.md b/openspec/specs/app-tile-widget/spec.md new file mode 100644 index 000000000..b232a7349 --- /dev/null +++ b/openspec/specs/app-tile-widget/spec.md @@ -0,0 +1,48 @@ +# app-tile-widget Specification + +## Purpose +Every app the person can open is its own square, coloured tile on the dashboard. + +## Requirements + +### Requirement: The add flow offers every app as its own tile (REQ-APPTILE-001) + +The add flow's "App tiles" section (board LpWidgetKiezen, "App-tegels") SHALL list one entry per app in the user's +app menu, each drawn in the colour its tile gets, followed by "Custom tile", which opens the tile form. Picking an +app SHALL place an `app-tile` widget with `content: { appId, colour: '', showCount: true }`. An app that has an +`app-tile` on the dashboard SHALL be marked "On this dashboard". + +#### Scenario: Files in the picker + +- **GIVEN** a user whose app menu holds Files +- **WHEN** they open the add flow and pick Files under "App tiles" +- **THEN** an `app-tile` widget for `files` is stored +- **AND** the dashboard shows a square link named "Files" to `/apps/files/` with no visible text +- **AND** the next time the add flow opens, Files is marked "On this dashboard" + +### Requirement: An app tile shows one app the viewer may open (REQ-APPTILE-002) + +An `app-tile` placement SHALL render through nextcloud-vue's `CnAppTileWidget`, without the card frame or header. Its +name, icon and address SHALL come from the viewer's own app menu, so an app the viewer may not open never renders as +a link. A new app tile SHALL start as one cell of two columns by two rows and SHALL have no card, title or padding around it; the coloured tile is the widget, placed, moved and resized on its own. Headings above tiles are separate label placements with `groupHeading: true`. + +#### Scenario: A shared dashboard with an app the viewer may not open + +- **GIVEN** a group dashboard with an app tile for Deck +- **AND** a group member for whom Deck is not enabled +- **WHEN** the member opens the dashboard +- **THEN** the cell says the app is not available and holds no link to Deck + +### Requirement: A first dashboard starts with a tile per most-used app (REQ-APPTILE-003) + +The first-run starter set (`widgets: 'starters'`) SHALL open with one `app-tile` for each of the first four apps in the +person's app menu, taking Files, Mail, Calendar, Talk, Contacts, Deck, Tasks and Notes first in that order. The other +starter widgets SHALL follow unchanged. LaunchPad itself SHALL never get a tile. When the app menu is unknown, the set +SHALL open with the `app-tiles` widget instead. The `app-tiles` widget SHALL keep rendering on existing dashboards. + +#### Scenario: A first dashboard for a person with Files and Mail + +- **GIVEN** a person whose app menu holds Deck, Calendar, Files, Photos and Talk +- **WHEN** they create their first dashboard with the starter widgets +- **THEN** the dashboard holds app tiles for Files, Calendar, Talk and Deck on the top row, then the calendar, mail, + files, weather and news widgets diff --git a/openspec/specs/assigned-cases-widget/spec.md b/openspec/specs/assigned-cases-widget/spec.md new file mode 100644 index 000000000..8ee283ff8 --- /dev/null +++ b/openspec/specs/assigned-cases-widget/spec.md @@ -0,0 +1,52 @@ +# assigned-cases-widget Specification + +## Purpose +The open cases assigned to the person viewing, with counts per status, on a dashboard. + +## Requirements + +### Requirement: The widget lists the viewer's open cases, deadline first (REQ-CASES-001) + +The `assigned-cases` widget SHALL read the cases assigned to the viewer from the configured OpenRegister register and +schema with the viewer's own session, leave out cases with a final status, and list the first `limit` (default 4), +deadline first. Each case SHALL show its title as a link into the case app, its case number, its deadline (overdue +once passed) and its status in the colour of its status type. When there are more open cases than shown, a link SHALL +lead to the case list. + +#### Scenario: Pieter's cases + +- **GIVEN** Pieter has open cases "Kapvergunning Molenweg 4" (In behandeling, deadline today) and "Dakkapel + Kerkstraat 12" (Wacht op aanvrager, 21 October) +- **WHEN** he opens a dashboard with "My cases" +- **THEN** both show, the one due today first, each with case number, deadline and status + +### Requirement: The widget counts the open cases per status (REQ-CASES-002) + +Above the cases the widget SHALL show one count per status over the viewer's open cases. + +#### Scenario: Counts + +- **GIVEN** Pieter has 6 open cases "In behandeling" and 5 "Wacht op aanvrager" +- **THEN** the widget shows "In behandeling 6" and "Wacht op aanvrager 5" + +### Requirement: The widget names its data source (REQ-CASES-003) + +The form SHALL name the register and the schema the widget reads, by default dossiq's `dossiq` and `case`, and the +number of cases, 1 to 20. + +#### Scenario: Default source + +- **WHEN** an author adds "My cases" +- **THEN** the form shows register `dossiq` and schema `case` + +### Requirement: The widget is offered only with dossiq (REQ-CASES-004) + +Launchpad SHALL find dossiq under every id it has had and never by one spelling. The picker SHALL offer "My cases" only +when dossiq is enabled for the viewer. Outside edit mode a placed widget, and every other widget whose app is not +enabled for the viewer, SHALL be left out of the grid. Links SHALL use the id dossiq is installed under. + +#### Scenario: No dossiq + +- **GIVEN** an instance without dossiq +- **WHEN** a person opens a dashboard holding "My cases" +- **THEN** the widget is not shown, and the picker does not offer "My cases" diff --git a/openspec/specs/attention-feed/screens.md b/openspec/specs/attention-feed/screens.md new file mode 100644 index 000000000..577c6b033 --- /dev/null +++ b/openspec/specs/attention-feed/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag +- LpStart https://identity.conduction.nl/screens/board?id=wilgenboom/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=vaartveld/LpStart diff --git a/openspec/specs/attention-feed/spec.md b/openspec/specs/attention-feed/spec.md new file mode 100644 index 000000000..f1c5776a5 --- /dev/null +++ b/openspec/specs/attention-feed/spec.md @@ -0,0 +1,205 @@ +--- +status: done +--- + +# Attention feed specification + +## Purpose + +The attention feed is the "First today" list on a start page: what needs the employee's attention today, from all their apps, in one ranked list with a link into each app. An app says what needs attention in one data file. LaunchPad reads the files, the browser counts as the signed-in user, and the widget shows the result. A count that could not run is shown as failed, never as "nothing to do". + +The contract and the reasons behind it are in `openspec/changes/cross-app-attention-feed/design.md`. + +## Requirements + +### Requirement: REQ-ATT-001 An app declares its attention items in a file + +An app MAY ship `appinfo/attention.json`. LaunchPad MUST read that file for every app that is enabled for the signed-in user, and for no other app. LaunchPad MUST NOT require a PHP class, an interface or a registration call from the app. + +The file MUST be a JSON object with `version: 1` and `items`, a list of at most 10 items. Each item MUST have: + +- `id`: lower-case letters, digits and hyphens, unique within the file; +- `title`, `reason` and `action.label`: non-empty English source strings. `reason` MAY contain `{value}`, the count; +- `source.register` and `source.schema`: OpenRegister slugs; +- `source.filter`: optional, a FLAT object. A value is a string, number, boolean or a list of those. An operator is part of the key (`"deadline[lt]"`). A nested object as a value is invalid; +- `action.path`: a path inside the declaring app, starting with `/`, with no `..`, no `//`, no `?` and no `#`. + +Each item MAY have `severity` (`error`, `warning` or `info`, default `info`), `op` (`gt`, `gte`, `lt`, `lte`, `eq` or `neq`, default `gt`) and a numeric `value` (default `0`). + +LaunchPad MUST translate `title`, `reason` and `action.label` with the declaring app's own translations, in the user's language. + +A file that is not valid MUST NOT take the feed down. The app MUST be reported under `invalid` with a reason, its valid items MUST NOT be offered in part, and every other app MUST still be offered. + +#### Scenario: An app with a declaration is offered +- GIVEN dossiq is enabled for Pieter and ships `appinfo/attention.json` with the item `cases-past-deadline` +- WHEN Pieter's browser asks `GET /api/attention/sources` +- THEN the answer MUST hold one source with `appId: "dossiq"`, the app's display name, the item's id, its translated title, reason and action label, its source, `op: "gt"`, `value: 0` and `action.path: "/apps/dossiq/cases"` + +@e2e exclude Needs an app that ships the file; no app does until the app lanes add it, and this change touches LaunchPad only. Pinned by AttentionSourceServiceTest::testAnEnabledAppWithADeclarationIsOffered, which reads a real file from a real app folder. + +#### Scenario: An app that is not installed or declares nothing does not appear +- GIVEN pipelinq is not installed, and the Files app is enabled and ships no `appinfo/attention.json` +- WHEN the sources are collected +- THEN neither MUST appear under `sources` +- AND neither MUST appear under `invalid` + +@e2e exclude Pinned by AttentionSourceServiceTest::testAnAppWithoutTheFileDoesNotAppear. + +#### Scenario: An app that is disabled for this user does not appear +- GIVEN decidiq is enabled only for the group "bestuur" and Pieter is not in it +- WHEN Pieter's sources are collected +- THEN decidiq MUST NOT appear + +@e2e exclude Pinned by AttentionSourceServiceTest::testOnlyAppsEnabledForTheUserAreRead. + +#### Scenario: A broken declaration is reported and the others still work +- GIVEN dossiq ships a valid file and learniq ships a file whose filter nests an operator (`"deadline": {"lt": "@today"}`) +- WHEN the sources are collected +- THEN dossiq's item MUST be under `sources` +- AND learniq MUST be under `invalid` with a reason that names the item and the filter key +- AND no learniq item MUST be under `sources` + +@e2e exclude Pinned by AttentionSourceServiceTest::testABrokenDeclarationIsReportedAndTheOthersStillWork and ::testEveryRuleOfTheDeclarationIsChecked. + +#### Scenario: A link cannot leave the declaring app +- GIVEN an app declares `action.path: "/../settings/admin"` or `"//evil.example/x"` +- WHEN the sources are collected +- THEN the app MUST be reported under `invalid` + +@e2e exclude Pinned by AttentionSourceServiceTest::testEveryRuleOfTheDeclarationIsChecked. + +### Requirement: REQ-ATT-002 The sources endpoint + +`GET /api/attention/sources` MUST return `{ userId, sources: [...], invalid: [...] }` for the signed-in user. `userId` is the user's own id, which the widget writes where a filter says `@me`. It MUST require a signed-in user and MUST NOT require an administrator. It MUST NOT run any count and MUST NOT return any object data: it returns what the apps declared. + +#### Scenario: A signed-in employee gets the sources +- GIVEN Pieter is signed in +- WHEN his browser asks `GET /api/attention/sources` +- THEN the answer MUST be HTTP 200 with `userId: "pieter"`, `sources` and `invalid` + +@e2e exclude Pinned by AttentionControllerTest::testASignedInUserGetsTheSources. Not run in a browser. + +#### Scenario: Nobody signed in +- WHEN a request without a session asks `GET /api/attention/sources` +- THEN the answer MUST be HTTP 401 + +@e2e exclude Pinned by AttentionControllerTest::testNobodySignedInGets401. + +### Requirement: REQ-ATT-003 The count and the link come from one filter + +For each source the widget MUST ask OpenRegister, as the signed-in user, for `/apps/openregister/api/objects/{register}/{schema}` with the source's filter and `_limit=1`, and MUST read `total` as the count. + +Before the count is asked, the widget MUST resolve these tokens in filter values: `@me`, `@now`, `@today`, `@today+Nd`, `@today-Nd`, `@monthStart`, `@quarterStart` and `@yearStart`. A value that starts with `@` and is none of these MUST fail that source (REQ-ATT-005). It MUST NOT be sent as it is. + +The link into the app MUST be the declared path with the SAME filter as its query string, tokens not resolved, so the app's list resolves them as it does for its own links. A list value MUST be written as repeated `key[]` parameters in both. + +#### Scenario: The number and the list use the same filter +- GIVEN the dossiq source with the filter `assignee: "@me"`, `isFinalStatus: false`, `"deadline[lt]": "@today+1d"` +- WHEN the widget builds the count request and the link on 5 October 2026 for the user `pieter` +- THEN the count request's query MUST be `assignee=pieter&isFinalStatus=false&deadline[lt]=2026-10-06&_limit=1` +- AND the link MUST be `/apps/dossiq/cases?assignee=@me&isFinalStatus=false&deadline[lt]=@today%2B1d` (the `+` is written as `%2B`, or the app would read a space) +- AND the link's parameter names MUST equal the count's parameter names without `_limit` + +@e2e exclude Pinned by attentionFeed.spec.js "the count and the link carry the same filter". Not run in a browser. + +#### Scenario: An unknown token fails the source +- GIVEN a source whose filter holds `owner: "@manager"` +- WHEN the widget prepares the count +- THEN no request MUST be sent for that source +- AND the source MUST be shown as failed + +@e2e exclude Pinned by attentionFeed.spec.js "an unknown token fails the source and sends nothing". + +### Requirement: REQ-ATT-004 Merging and ranking + +A source needs attention when its count compared with `value` by `op` is true. The widget MUST show the sources that need attention as one list across apps, ordered by severity (`error`, `warning`, `info`), then by the higher count, then by app name, then by item id. + +Each line MUST show the title, the reason with the count filled in, the app's name and a link with the action label. The widget MUST show at most `limit` lines (widget setting, 1 to 10, default 5) and MUST say how many more there are. + +#### Scenario: Items from three apps in one list +- GIVEN dossiq reports 3 (error), pipelinq reports 5 (error) and decidiq reports 2 (warning) +- WHEN the widget renders +- THEN the lines MUST be pipelinq, dossiq, decidiq, in that order +- AND the dossiq line MUST read "3 of your cases are past their deadline or end today." and link to dossiq + +@e2e exclude Needs three apps that ship the file. Pinned by attentionFeed.spec.js "ranks by severity, then count, then app" and AttentionWidget.spec.js "shows one line per item that needs attention". + +#### Scenario: A source that does not need attention is left out +- GIVEN learniq's count is 0 and its item says `op: "gt"`, `value: 0` +- WHEN the widget renders +- THEN no learniq line MUST be shown + +@e2e exclude Pinned by AttentionWidget.spec.js "leaves out a source that does not need attention". + +### Requirement: REQ-ATT-005 A failure is shown as a failure + +A source fails when its count request does not answer with HTTP 2xx, when the answer has no numeric `total`, when the network fails, or when a token is unknown (REQ-ATT-003). A failed source MUST be named in a line under the list ("Could not check: {apps}"). An invalid declaration (REQ-ATT-001) MUST be named there too. + +The widget MUST show "Nothing needs your attention right now." only when every source was checked and none needs attention. When any source failed, it MUST NOT show that sentence. + +When no app declares anything, the widget MUST say so ("None of your apps reports attention items yet."). When the sources endpoint itself fails, the widget MUST say the list could not be loaded. + +One failing source MUST NOT stop the other sources from being shown. + +#### Scenario: One app fails and the others are clear +- GIVEN dossiq's count answers HTTP 500 and pipelinq's count is 0 +- WHEN the widget renders +- THEN it MUST show "Could not check: dossiq" +- AND it MUST NOT show "Nothing needs your attention right now." + +@e2e exclude Staging a failing OpenRegister answer needs request interception against an app that ships the file. Pinned by AttentionWidget.spec.js "a failed source is named and never reads as nothing to do". + +#### Scenario: One app fails and another needs attention +- GIVEN dossiq's count fails and pipelinq's count is 5 +- WHEN the widget renders +- THEN the pipelinq line MUST be shown +- AND "Could not check: dossiq" MUST be shown under it + +@e2e exclude Pinned by AttentionWidget.spec.js "a failed source does not hide the others". + +#### Scenario: Everything checked, nothing to do +- GIVEN two sources, both checked, both with count 0 +- WHEN the widget renders +- THEN it MUST show "Nothing needs your attention right now." + +@e2e exclude Pinned by AttentionWidget.spec.js "says nothing needs attention only when every source was checked". + +#### Scenario: No app declares anything +- GIVEN the sources endpoint answers with no sources and no invalid declarations +- WHEN the widget renders +- THEN it MUST show "None of your apps reports attention items yet." + +@e2e exclude Pinned by AttentionWidget.spec.js "says so when no app declares anything". This is also what the widget shows on an instance today, until an app ships the file; that was not looked at in a browser. + +### Requirement: REQ-ATT-006 The widget type + +LaunchPad MUST offer the widget as type `attention`, named "First today", in the add-widget picker. Its only setting is `limit`. It MUST be on LaunchPad's widget type list (`lib/widget-types.json`), so templates, showcases and imports can place it. The line colour MUST come from Nextcloud's theme variables, and severity MUST also be said in text for assistive technology, not by colour alone. + +#### Scenario: The widget can be added +- GIVEN an employee edits a dashboard +- WHEN they open the add-widget picker +- THEN "First today" MUST be offered + +@e2e exclude Not run in a browser. Pinned by widgetRegistry.completeness.spec.js, which holds the registry equal to lib/widget-types.json. + +### Requirement: Vandaag eerst can draw one card per record (REQ-ATT-007) + +An attention widget with `content.itemCards: true` SHALL ask every source for up to `content.limit` records instead of +one count, and SHALL draw one card per record: the record's own name as the title, the source's title as the reason +("De beslistermijn loopt vandaag af"), the app that owns it, and one action that opens the record, named by the +source ("Zaak openen", "Beantwoorden", "Paraferen") or "Open {item}" when the source names none. The cards SHALL keep +the merge and ranking order of REQ-ATT-004 and SHALL stop at `content.limit` in total. Without `itemCards` the widget +SHALL draw one item per source with its count, as before. + +#### Scenario: Two cases due today + +- **GIVEN** dossiq reports two cases whose decision term ends today, and the widget sets `itemCards: true` and `limit: 3` +- **WHEN** Pieter opens the start page +- **THEN** Vandaag eerst shows two cards, each named by its case, each with "De beslistermijn loopt vandaag af" and "Zaak openen" +- **AND** "Zaak openen" opens that case in dossiq + +#### Scenario: Without item cards + +- **GIVEN** the same feed and a widget without `itemCards` +- **WHEN** the widget renders +- **THEN** it shows one item for the dossiq source with the count 2 diff --git a/openspec/specs/background-job-feed-refresh/screens.md b/openspec/specs/background-job-feed-refresh/screens.md new file mode 100644 index 000000000..0e483fde5 --- /dev/null +++ b/openspec/specs/background-job-feed-refresh/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Uitgaande verzoeken gebruiken de proxy-instelling van de server, zonder scherm. diff --git a/openspec/specs/background-job-feed-refresh/spec.md b/openspec/specs/background-job-feed-refresh/spec.md index 195b56fb4..90a9e4937 100644 --- a/openspec/specs/background-job-feed-refresh/spec.md +++ b/openspec/specs/background-job-feed-refresh/spec.md @@ -8,14 +8,14 @@ status: done Keeps news-widget feeds fresh by running a scheduled background job that fetches, parses, and caches RSS 2.0 and Atom 1.0 feeds referenced by dashboard placements. It deduplicates feed URLs into a shared cache table, uses HTTP conditional requests and per-feed failure isolation to stay efficient and resilient, enforces a host allow-list and concurrency lock, and exposes an admin endpoint to trigger an immediate refresh. ## Requirements -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: REQ-FRJ-001 Feed Cache Table Schema The system MUST create a database table `oc_launchpad_feed_cache` that stores exactly one row per distinct feed URL across all news-widget placements, persisting fetch metadata and cached items. #### Scenario: Table created on migration +@e2e exclude migration schema, not observable over HTTP; no test exists for Version001023Date20260502130000 / FeedCacheTableBuilder (columns are snake_case there, e.g. feed_url, items_json) + - GIVEN LaunchPad is freshly installed or upgraded and the migration has not yet run - WHEN `occ migrations:execute launchpad` runs the `AddFeedCacheTable` migration - THEN the table `oc_launchpad_feed_cache` MUST exist with columns: `id` (auto-increment integer PK), `feedUrl VARCHAR(2048) UNIQUE NOT NULL`, `lastFetchedAt TIMESTAMP NULL`, `lastSuccessAt TIMESTAMP NULL`, `lastFailureReason TEXT NULL`, `etag VARCHAR(255) NULL`, `lastModified VARCHAR(255) NULL`, `itemsJson MEDIUMTEXT NULL` @@ -23,6 +23,8 @@ The system MUST create a database table `oc_launchpad_feed_cache` that stores ex #### Scenario: One row per distinct URL regardless of placement count +@e2e exclude mapper upsert, no HTTP endpoint reads oc_launchpad_feed_cache; pinned by tests/Unit/Db/FeedCacheMapperTest.php::testUpsertReturnsAnExistingRow and tests/Unit/Db/FeedCacheMapperTest.php::testUpsertInsertsAMissingUrl + - GIVEN two separate news-widget placements both reference `https://example.com/rss` - WHEN the background job discovers feed URLs and upserts into the cache table - THEN exactly one row with `feedUrl = 'https://example.com/rss'` MUST exist in `oc_launchpad_feed_cache` @@ -30,6 +32,8 @@ The system MUST create a database table `oc_launchpad_feed_cache` that stores ex #### Scenario: Schema is compatible across supported databases +@e2e exclude needs the migration run on SQLite, MySQL and PostgreSQL instances; no test exists + - GIVEN the migration runs on SQLite, MySQL 8.x, and PostgreSQL 14+ - WHEN `oc_launchpad_feed_cache` is created - THEN the table MUST be created without error on each engine @@ -37,6 +41,8 @@ The system MUST create a database table `oc_launchpad_feed_cache` that stores ex #### Scenario: Migration is reversible +@e2e exclude never built: Nextcloud migrations have no revert and Version001023Date20260502130000 implements only changeSchema(); no test exists + - GIVEN the migration has been applied - WHEN a rollback is triggered (e.g., `occ migrations:execute --revert`) - THEN the `oc_launchpad_feed_cache` table MUST be dropped cleanly @@ -44,6 +50,8 @@ The system MUST create a database table `oc_launchpad_feed_cache` that stores ex #### Scenario: itemsJson capped at 50 items on write +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache; pinned by tests/Unit/Db/FeedCacheTest.php::testEncodeItemsCapsAt50 + - GIVEN a feed returns 120 items in its response - WHEN the service stores items in `itemsJson` - THEN only the 50 newest items (sorted by `pubDate` descending) MUST be stored @@ -55,6 +63,8 @@ The system MUST register `FeedRefreshJob` as a Nextcloud `\OCP\BackgroundJob\Tim #### Scenario: Job runs every 60 minutes by default +@e2e exclude cron-job constructor, no HTTP outcome; pinned by tests/Unit/Job/FeedRefreshJobTest.php::testConstructorAppliesDefaultWhenUnset + - GIVEN no `launchpad.feed_refresh_interval_seconds` app config key has been set - WHEN Nextcloud's cron daemon evaluates scheduled jobs - THEN `FeedRefreshJob` MUST run at most once per 3600 seconds (60 minutes) @@ -62,12 +72,16 @@ The system MUST register `FeedRefreshJob` as a Nextcloud `\OCP\BackgroundJob\Tim #### Scenario: Admin sets custom refresh interval +@e2e exclude occ config plus cron-job constructor, no HTTP outcome; pinned by tests/Unit/Job/FeedRefreshJobLoggingTest.php::testIntervalFromConfiguration (900 kept) + - GIVEN an admin runs `occ config:app:set launchpad feed_refresh_interval_seconds --value=900` - WHEN `FeedRefreshJob` is next constructed - THEN it MUST call `$this->setInterval(900)` so the job runs every 15 minutes #### Scenario: Interval clamped to minimum 300 seconds +@e2e exclude cron-job constructor, no HTTP outcome; pinned by tests/Unit/Job/FeedRefreshJobTest.php::testConstructorClampsBelowMinimum + - GIVEN an admin sets `launchpad.feed_refresh_interval_seconds` to `60` - WHEN the job constructor reads the config value - THEN the effective interval MUST be `max(300, configuredValue)` = `300` @@ -75,6 +89,8 @@ The system MUST register `FeedRefreshJob` as a Nextcloud `\OCP\BackgroundJob\Tim #### Scenario: Interval clamped to maximum 86400 seconds +@e2e exclude cron-job constructor, no HTTP outcome; pinned by tests/Unit/Job/FeedRefreshJobTest.php::testConstructorClampsAboveMaximum + - GIVEN an admin sets `launchpad.feed_refresh_interval_seconds` to `172800` (48 h) - WHEN the job constructor reads the config value - THEN the effective interval MUST be `min(86400, configuredValue)` = `86400` @@ -82,6 +98,8 @@ The system MUST register `FeedRefreshJob` as a Nextcloud `\OCP\BackgroundJob\Tim #### Scenario: Job registered on application bootstrap +@e2e exclude internal wiring plus a console command; the job is registered by the RegisterBackgroundJobs repair step (not Bootstrap::register), pinned by tests/Unit/Repair/RegisterBackgroundJobsTest.php::testRegistersEveryJobAndReportsEach + - GIVEN LaunchPad is installed and enabled - WHEN `AppInfo/Bootstrap.php::register()` is called - THEN `$context->registerBackgroundJob(FeedRefreshJob::class)` MUST be called @@ -93,6 +111,8 @@ The job MUST discover the complete set of active feed URLs by querying all news- #### Scenario: Feed URLs extracted from placements +@e2e exclude the sorted, deduplicated array is internal (refresh-now reports only counts); pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testDiscoverFeedUrlsDedupesAndSorts + - GIVEN three news-widget placements with `widgetId = 'launchpad_news'`: - Placement A: `widgetContent = {"feedUrls": ["https://a.com/rss", "https://b.com/feed"]}` - Placement B: `widgetContent = {"feedUrls": ["https://b.com/feed", "https://c.com/atom"]}` @@ -103,6 +123,8 @@ The job MUST discover the complete set of active feed URLs by querying all news- #### Scenario: Placements with no feedUrls are skipped +@e2e exclude "no error logged" has no HTTP read; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testDiscoverFeedUrlsDedupesAndSorts (empty feedUrls placement) and tests/Unit/Service/FeedRefreshServicePathsTest.php::testDiscoveryFiltersAndSorts (empty config); no test asserts the absence of an error log + - GIVEN a placement with `widgetContent = {}` or `widgetContent = {"feedUrls": []}` - WHEN `discoverFeedUrls()` processes this placement - THEN no URLs MUST be added from that placement @@ -110,6 +132,8 @@ The job MUST discover the complete set of active feed URLs by querying all news- #### Scenario: New feed URL upserted before first fetch +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache; pinned by tests/Unit/Db/FeedCacheMapperTest.php::testUpsertInsertsAMissingUrl and the upsertUrl-before-get expectation in tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeed200ParsesAndPersists + - GIVEN a placement has just been created with `feedUrl = "https://new.example.org/rss"` not yet in `oc_launchpad_feed_cache` - WHEN `discoverFeedUrls()` finishes and the job iterates feed URLs - THEN the job MUST call `FeedCacheMapper::upsertUrl("https://new.example.org/rss")` before fetching @@ -124,6 +148,8 @@ The job MUST discover the complete set of active feed URLs by querying all news- #### Scenario: Empty result when no news widgets are placed +@e2e exclude needs an instance with no launchpad_news placement at all, which a shared e2e instance cannot guarantee, and the INFO log has no HTTP read; pinned by tests/Unit/Service/FeedRefreshServicePathsTest.php::testDiscoveryFailureYieldsNothing and tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshAllNoFeedsReturnsZero + - GIVEN no placement has `widgetId = 'launchpad_news'` - WHEN `discoverFeedUrls()` is called - THEN the returned array MUST be empty @@ -135,6 +161,8 @@ The job MUST use HTTP conditional-get headers (`If-None-Match`, `If-Modified-Sin #### Scenario: First fetch — no conditional headers sent +@e2e exclude outbound request shape; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/ConditionalFeedRequestTest.php::testEmptyValidatorsAreNotSentAndUserAgentFallsBack and tests/Unit/Service/FeedRefreshServicePathsTest.php::testConditionalGetDefaults + - GIVEN `oc_launchpad_feed_cache` row for a URL has `etag = NULL` and `lastModified = NULL` - WHEN the job fetches the feed - THEN the HTTP request MUST NOT include `If-None-Match` or `If-Modified-Since` headers @@ -142,6 +170,8 @@ The job MUST use HTTP conditional-get headers (`If-None-Match`, `If-Modified-Sin #### Scenario: Subsequent fetch — ETag header sent +@e2e exclude outbound request shape; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/ConditionalFeedRequestTest.php::testCachedValidatorsAreSent and tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeed304PreservesItems + - GIVEN a previous successful fetch stored `etag = '"abc123"'` for `https://example.com/rss` - WHEN the job issues the next HTTP request for that URL - THEN the request MUST include `If-None-Match: "abc123"` @@ -149,12 +179,16 @@ The job MUST use HTTP conditional-get headers (`If-None-Match`, `If-Modified-Sin #### Scenario: Subsequent fetch — Last-Modified header sent +@e2e exclude outbound request shape; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/ConditionalFeedRequestTest.php::testCachedValidatorsAreSent + - GIVEN a previous fetch stored `lastModified = 'Wed, 21 Oct 2026 07:28:00 GMT'` - WHEN the job issues the next request - THEN the request MUST include `If-Modified-Since: Wed, 21 Oct 2026 07:28:00 GMT` #### Scenario: HTTP 304 — items untouched, only lastFetchedAt updated +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache and the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeed304PreservesItems (lastFetchedAt itself is not asserted by any test) + - GIVEN the server returns HTTP 304 Not Modified - WHEN the job processes the response - THEN `lastFetchedAt` MUST be updated to the current timestamp @@ -162,6 +196,8 @@ The job MUST use HTTP conditional-get headers (`If-None-Match`, `If-Modified-Sin #### Scenario: ETag and Last-Modified updated from 200 response headers +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache and the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeed200ParsesAndPersists and tests/Unit/Service/ConditionalFeedRequestTest.php::testCachedValidatorsAreSent + - GIVEN the server returns HTTP 200 with headers `ETag: "xyz789"` and `Last-Modified: Thu, 01 May 2026 10:00:00 GMT` - WHEN the job processes the response - THEN `etag` MUST be stored as `"xyz789"` and `lastModified` as `Thu, 01 May 2026 10:00:00 GMT` @@ -177,6 +213,8 @@ On HTTP 200, the job MUST parse RSS 2.0 and Atom 1.0 feed XML and normalise item #### Scenario: RSS 2.0 item fields mapped to schema +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache and the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedItemParserTest.php::testRssItemIsNormalisedWithChannelTitle and tests/Unit/Service/FeedItemParserTest.php::testOnlyImageEnclosureBecomesThumbnail + - GIVEN an RSS 2.0 feed with items containing `<title>`, `<description>`, `<link>`, `<pubDate>`, `<guid>`, and `<enclosure type="image/...">` - WHEN the job parses the feed - THEN each item MUST be normalised to: `{guid, title, summary, link, pubDate, sourceUrl, sourceTitle, thumbnailUrl}` @@ -185,12 +223,16 @@ On HTTP 200, the job MUST parse RSS 2.0 and Atom 1.0 feed XML and normalise item #### Scenario: Atom 1.0 item fields mapped to schema +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache and the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedItemParserTest.php::testAtomEntryIsNormalised and tests/Unit/Service/FeedRefreshServicePathsTest.php::testAtomEntriesAreNormalised + - GIVEN an Atom 1.0 feed with `<entry>` elements containing `<title>`, `<summary>` or `<content>`, `<link rel="alternate">`, `<published>` or `<updated>`, and `<id>` - WHEN the job parses the feed - THEN `guid` MUST be the value of `<id>`, `pubDate` MUST prefer `<published>` over `<updated>`, and `link` MUST be the `href` of `<link rel="alternate">` #### Scenario: Items without guid get synthetic guid +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache and the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedItemParserTest.php::testMissingGuidIsDerivedFromTitleDateAndUrl + - GIVEN a feed item has no `<guid>` (RSS) or `<id>` (Atom) - WHEN the parser processes the item - THEN the system MUST generate `guid = sha256(title + pubDate + feedUrl)` (hex string) @@ -198,6 +240,8 @@ On HTTP 200, the job MUST parse RSS 2.0 and Atom 1.0 feed XML and normalise item #### Scenario: Items sorted newest-first and capped at 50 +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache and the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedItemParserTest.php::testItemsAreSortedNewestFirstWithUndatedLast and tests/Unit/Db/FeedCacheTest.php::testEncodeItemsCapsAt50 + - GIVEN a feed returns 80 items with varying `pubDate` values - WHEN the job normalises and stores items - THEN the stored `itemsJson` MUST contain exactly 50 items @@ -205,6 +249,8 @@ On HTTP 200, the job MUST parse RSS 2.0 and Atom 1.0 feed XML and normalise item #### Scenario: sourceUrl and sourceTitle populated from feed metadata +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache and the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedItemParserTest.php::testRssItemIsNormalisedWithChannelTitle and tests/Unit/Service/FeedItemParserTest.php::testMissingTitleFallsBackToHost + - GIVEN a feed with channel-level `<title>BBC News` and fetch URL `https://feeds.bbci.co.uk/news/rss.xml` - WHEN items are normalised - THEN every item MUST have `sourceUrl = "https://feeds.bbci.co.uk/news/rss.xml"` and `sourceTitle = "BBC News"` @@ -218,6 +264,8 @@ A failure to fetch or parse one feed MUST NOT prevent the job from processing th #### Scenario: Single feed timeout does not block others +@e2e exclude needs a feed server that times out; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; lastFailureReason has no HTTP read; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeedTimeoutRecorded and tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshAllAggregatesAndIsolatesFailures + - GIVEN a job is processing feeds `[A, B, C]` and feed B times out after 10 seconds - WHEN the job runs - THEN feeds A and C MUST be processed normally @@ -226,6 +274,8 @@ A failure to fetch or parse one feed MUST NOT prevent the job from processing th #### Scenario: HTTP 4xx error recorded but does not abort job +@e2e exclude needs a feed server answering 410; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; lastFailureReason has no HTTP read; the non-2xx path is pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeed503RecordsFailurePreservesItems and tests/Unit/Service/FeedRefreshServicePathsTest.php::testResponseRejections (no test uses 410) + - GIVEN feed `https://gone.example.com/rss` returns HTTP 410 Gone - WHEN the job processes this feed - THEN `lastFailureReason` MUST be set to `"410 Gone"` @@ -234,6 +284,8 @@ A failure to fetch or parse one feed MUST NOT prevent the job from processing th #### Scenario: HTTP 5xx error handled gracefully +@e2e exclude needs a feed server answering 503; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; lastFailureReason has no HTTP read; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeed503RecordsFailurePreservesItems + - GIVEN a feed server returns HTTP 503 Service Unavailable - WHEN the job processes that feed - THEN `lastFailureReason` MUST be set to `"503 Service Unavailable"` @@ -242,6 +294,8 @@ A failure to fetch or parse one feed MUST NOT prevent the job from processing th #### Scenario: Malformed XML does not crash the job +@e2e exclude needs a feed server serving truncated XML; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedRefreshServicePathsTest.php::testResponseRejections and tests/Unit/Service/FeedItemParserTest.php::testMalformedXmlThrows + - GIVEN a feed server returns HTTP 200 with body `TRUNCATED` - WHEN `simplexml_load_string()` with `LIBXML_NOCDATA | LIBXML_NONET` attempts to parse the body - THEN the parse failure MUST be caught within a try/catch block @@ -250,6 +304,8 @@ A failure to fetch or parse one feed MUST NOT prevent the job from processing th #### Scenario: Connect timeout is 10 s, total timeout is 30 s +@e2e exclude client options and a 40 s slow server; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedRefreshServicePathsTest.php::testConditionalGetRequestShape (connect_timeout 10, timeout 30) and tests/Unit/Service/FeedRefreshServicePathsTest.php::testTransportErrorsAreClassified + - GIVEN a feed server accepts the TCP connection but responds after 40 seconds - WHEN the job fetches that feed via `IClientService` - THEN the request MUST be aborted after 30 seconds total @@ -261,6 +317,8 @@ Only one instance of `FeedRefreshJob` MUST run at a time across the Nextcloud cl #### Scenario: Job acquires global lock on start +@e2e exclude cron-job internals, no HTTP outcome (refresh-now does not take this lock); pinned by tests/Unit/Job/FeedRefreshJobTest.php::testRunHappyPathReleasesLock + - GIVEN no other instance of `FeedRefreshJob` is running - WHEN the job's `run()` method is invoked by the Nextcloud cron daemon - THEN the job MUST call `ILockingProvider::acquireLock('launchpad_feed_refresh_running', ILockingProvider::LOCK_EXCLUSIVE)` @@ -268,6 +326,8 @@ Only one instance of `FeedRefreshJob` MUST run at a time across the Nextcloud cl #### Scenario: Second concurrent invocation exits without processing +@e2e exclude cron-job internals and a WARN log, no HTTP outcome; pinned by tests/Unit/Job/FeedRefreshJobTest.php::testRunSkipsWhenLockHeld and tests/Unit/Job/FeedRefreshJobLoggingTest.php::testASkippedTickWarns + - GIVEN one `FeedRefreshJob` instance holds the global lock - WHEN a second instance attempts to run concurrently - THEN `acquireLock` MUST throw `\OCP\Lock\LockedException` @@ -276,6 +336,8 @@ Only one instance of `FeedRefreshJob` MUST run at a time across the Nextcloud cl #### Scenario: Lock released on unhandled exception +@e2e exclude cron-job internals, no HTTP outcome; pinned by tests/Unit/Job/FeedRefreshJobTest.php::testRunAcquiresAndReleasesLockOnException + - GIVEN the job holds the global lock and an unhandled exception occurs mid-run - WHEN the exception propagates out of the core processing loop - THEN the `finally` block MUST release the lock @@ -283,6 +345,8 @@ Only one instance of `FeedRefreshJob` MUST run at a time across the Nextcloud cl #### Scenario: Lock scope is per-Nextcloud-instance (not per-feed) +@e2e exclude needs a second Nextcloud node running cron at the same time; no test exists + - GIVEN a Nextcloud cluster with two nodes running the same cron simultaneously - WHEN both nodes invoke `FeedRefreshJob::run()` at the same time - THEN only one node MUST proceed past the `acquireLock` call @@ -294,6 +358,8 @@ When the number of active feed URLs exceeds 500, the job MUST split work across #### Scenario: ≤500 feeds — all processed in one tick +@e2e exclude the cursor key has no LaunchPad HTTP read; cursor clearing pinned by tests/Unit/Service/FeedRefreshServicePathsTest.php::testSweepResumesAfterCursorAndClearsIt (no test uses 450 feeds) + - GIVEN there are 450 active feed URLs - WHEN `FeedRefreshJob::run()` is invoked - THEN all 450 feeds MUST be processed within a single tick @@ -301,6 +367,8 @@ When the number of active feed URLs exceeds 500, the job MUST split work across #### Scenario: >500 feeds — cursor advances across ticks +@e2e exclude needs 500+ placed feeds, each leaving a permanent oc_launchpad_feed_cache row with no HTTP delete, and the cursor has no LaunchPad HTTP read; no test pins the cursor write at the batch boundary + - GIVEN there are 750 active feed URLs, sorted alphabetically, and the job processes 500 per tick - WHEN the first tick runs - THEN feeds 1–500 MUST be processed @@ -312,6 +380,8 @@ When the number of active feed URLs exceeds 500, the job MUST split work across #### Scenario: Cursor is invalidated when feed list changes significantly +@e2e exclude needs a half-finished 500+ feed batch (see above); pinned by tests/Unit/Service/FeedRefreshServicePathsTest.php::testStaleCursorRestartsAndCountsOutcomes + - GIVEN a cursor is stored after a partial batch run - AND between ticks, all placements referencing the cursor's URL are deleted - WHEN the next tick resumes from the stale cursor @@ -320,6 +390,8 @@ When the number of active feed URLs exceeds 500, the job MUST split work across #### Scenario: 5-minute wall-clock budget enforced per tick +@e2e exclude needs 300 s of fetching inside one tick; no test exists + - GIVEN 800 feeds, each taking an average of 400ms to fetch - WHEN the job runs - THEN after 300 seconds (5 minutes) of elapsed time, the job MUST stop processing further feeds in this tick @@ -332,6 +404,8 @@ Feeds no longer referenced by any active placement for ≥30 days MUST be pruned #### Scenario: FeedCacheMapper exposes orphan query for sibling job +@e2e exclude mapper method with no HTTP surface; pinned by tests/Unit/Db/FeedCacheMapperTest.php::testOrphansAreThoseLastFetchedBeforeTheCutoff + - GIVEN the `orphaned-data-cleanup` sibling job is implemented - WHEN it calls `FeedCacheMapper::findOrphanedBefore($cutoff)` where `$cutoff = now() - 30 days` - THEN the mapper MUST return all rows where `lastFetchedAt < $cutoff` @@ -339,6 +413,8 @@ Feeds no longer referenced by any active placement for ≥30 days MUST be pruned #### Scenario: lastFetchedAt updated on every tick for active feeds +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache and the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; no test asserts lastFetchedAt on the 304 path (tests/Unit/Service/FeedRefreshServicePathsTest.php asserts it only for SSRF, scheme and transport failures) + - GIVEN a feed URL is actively referenced by a placement - WHEN the background job runs its tick (even if the feed returns 304) - THEN `lastFetchedAt` MUST be updated to the current timestamp @@ -346,6 +422,8 @@ Feeds no longer referenced by any active placement for ≥30 days MUST be pruned #### Scenario: Feed removed from all placements starts ageing +@e2e exclude needs 30 days to pass and no HTTP endpoint reads oc_launchpad_feed_cache; the pieces are pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testDiscoverFeedUrlsDedupesAndSorts and tests/Unit/Db/FeedCacheMapperTest.php::testOrphansAreThoseLastFetchedBeforeTheCutoff + - GIVEN a feed URL was removed from all placements at `T` - WHEN the background job runs ticks after `T` - THEN the URL MUST no longer appear in `discoverFeedUrls()` @@ -354,6 +432,8 @@ Feeds no longer referenced by any active placement for ≥30 days MUST be pruned #### Scenario: Sibling job dependency noted in failure state +@e2e exclude no HTTP endpoint reads oc_launchpad_feed_cache; the GIVEN (cleanup job absent) no longer holds since OrphanedDataCleanupJob exists; no test exists + - GIVEN the `orphaned-data-cleanup` sibling job has NOT been implemented - WHEN the feed cache grows over time with unreferenced entries - THEN `oc_launchpad_feed_cache` rows for orphaned feeds MUST remain in the table (no auto-delete) @@ -407,6 +487,8 @@ The job MUST check each feed URL against the configured allow-list before fetchi #### Scenario: Allow-list empty — all hosts permitted +@e2e exclude the allow-list is only settable via occ (no LaunchPad endpoint) and its effect shows only in lastFailureReason, no HTTP endpoint reads oc_launchpad_feed_cache; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeed200ParsesAndPersists (empty allow-list, the fetch proceeds) + - GIVEN `launchpad.news_widget_allowed_feed_hosts` is not set or is an empty string - WHEN the job processes any feed URL - THEN no allow-list check MUST be performed @@ -414,6 +496,8 @@ The job MUST check each feed URL against the configured allow-list before fetchi #### Scenario: Disallowed host skipped before HTTP request +@e2e exclude the allow-list is only settable via occ and refresh-now counts a skip and a failure alike, no HTTP endpoint reads oc_launchpad_feed_cache; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeedAllowListSkip and tests/Unit/Service/FeedRefreshServicePathsTest.php::testAllowListMissSkipsWithoutConsultingSsrfGuard + - GIVEN `launchpad.news_widget_allowed_feed_hosts = "bbc.com,example.org"` - AND the job discovers `https://blocked-site.com/feed` - WHEN the job processes this URL @@ -423,6 +507,8 @@ The job MUST check each feed URL against the configured allow-list before fetchi #### Scenario: Allowed host passes check and is fetched +@e2e exclude needs a real allow-listed public feed; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeedAllowListHitFetches + - GIVEN `launchpad.news_widget_allowed_feed_hosts = "bbc.com,example.org"` - AND the job discovers `https://bbc.com/news/rss.xml` - WHEN the job processes this URL @@ -431,6 +517,8 @@ The job MUST check each feed URL against the configured allow-list before fetchi #### Scenario: Allow-list comparison is case-insensitive +@e2e exclude the allow-list is only settable via occ, no HTTP endpoint reads oc_launchpad_feed_cache; pinned by tests/Unit/Service/FeedRefreshServiceTest.php::testRefreshFeedAllowListHitFetches (BBC.com vs bbc.com) and tests/Unit/Service/FeedRefreshServicePathsTest.php::testAllowListMatchIsTrimmedAndCaseInsensitive + - GIVEN `launchpad.news_widget_allowed_feed_hosts = "BBC.com"` - AND the feed URL is `https://bbc.com/rss` - WHEN the hostname is compared against the allow-list @@ -438,6 +526,8 @@ The job MUST check each feed URL against the configured allow-list before fetchi #### Scenario: Subdomains not covered by base hostname +@e2e exclude the allow-list is only settable via occ, no HTTP endpoint reads oc_launchpad_feed_cache; no test uses a subdomain of an allow-listed host against FeedRefreshService::isHostAllowed (exact match in code) + - GIVEN `launchpad.news_widget_allowed_feed_hosts = "example.org"` - AND the feed URL is `https://feeds.example.org/rss` - WHEN the hostname is compared @@ -450,6 +540,8 @@ The job MUST identify itself with a descriptive User-Agent header and MUST honou #### Scenario: User-Agent header sent on every request +@e2e exclude outbound request header; the SSRF guard (UrlSafetyValidator::isSafe) refuses loopback/private hosts, so e2e has no feed server the instance may fetch; pinned by tests/Unit/Service/FeedRefreshServicePathsTest.php::testConditionalGetRequestShape + - GIVEN the job fetches any feed URL - WHEN the HTTP request is constructed via `IClientService` - THEN the `User-Agent` header MUST be set to `Mozilla/5.0 (compatible; LaunchPad/; +/apps/launchpad)` @@ -458,6 +550,8 @@ The job MUST identify itself with a descriptive User-Agent header and MUST honou #### Scenario: Proxy settings honoured from NC config +@e2e exclude needs a proxy and config.php changes; pinned by tests/Unit/Service/ConditionalFeedRequestTest.php::testProxyAndProxyAuthAreApplied and tests/Unit/Service/FeedRefreshServicePathsTest.php::testConditionalGetRequestShape + - GIVEN the Nextcloud instance has `system.proxy` set to `http://proxy.corp.example:3128` in `config.php` - WHEN the job makes an outbound HTTP request via `IClientService` - THEN the request MUST be routed through the configured proxy @@ -465,6 +559,8 @@ The job MUST identify itself with a descriptive User-Agent header and MUST honou #### Scenario: Proxy bypass for local hosts +@e2e exclude needs a proxy, config.php noproxy and a feed host behind it; no test exists + - GIVEN `system.noproxy` contains `"localhost,127.0.0.1,internal.corp"` - WHEN the job fetches a feed at `https://internal.corp/feed` - THEN the proxy MUST NOT be used for this request @@ -472,6 +568,8 @@ The job MUST identify itself with a descriptive User-Agent header and MUST honou #### Scenario: User-Agent identifies version correctly after app upgrade +@e2e exclude needs an app upgrade; the version is read from installed_version at request time, pinned by tests/Unit/Service/FeedRefreshServicePathsTest.php::testConditionalGetRequestShape (2.3.4) + - GIVEN the app is upgraded from version `1.0.0` to `1.1.0` - WHEN the job runs after upgrade - THEN the User-Agent MUST reflect `LaunchPad/1.1.0` diff --git a/openspec/specs/beta-alignment/screens.md b/openspec/specs/beta-alignment/screens.md new file mode 100644 index 000000000..ef347a3df --- /dev/null +++ b/openspec/specs/beta-alignment/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Interne afstemming van app-informatie, manifest en documentatie. diff --git a/openspec/specs/beta-alignment/spec.md b/openspec/specs/beta-alignment/spec.md new file mode 100644 index 000000000..e7c905900 --- /dev/null +++ b/openspec/specs/beta-alignment/spec.md @@ -0,0 +1,47 @@ +# beta-alignment Specification + +## Purpose +LaunchPad is described in four places: the app metadata in `appinfo/info.xml`, the pages in `src/manifest.json`, the product page on conduction.nl and the documentation. This capability keeps those four in step: they use the same feature vocabulary, the licence tag matches the licence text, and a translated product page lives at the same relative path as the page it translates. + +## Requirements + +### Requirement: The four public surfaces SHALL agree on feature vocabulary +`appinfo/info.xml`, the shipped feature set in `src/manifest.json` / `lib/`, +the product page (`conduction-website/src/pages/apps/launchpad.mdx` + its +Dutch translation), and `docs/` SHALL describe the same canonical feature +list using the same feature names, and SHALL NOT assert a capability that +is not present in `lib/` or `src/` at HEAD. + +#### Scenario: A feature bullet on the product page names a real capability +- **WHEN** the product page or docs describe a LaunchPad capability +- **THEN** that capability SHALL be traceable to a concrete file in `lib/` + or `src/` (a controller, service, widget renderer, or registry entry) + +#### Scenario: info.xml does not declare an install-time dependency the architecture forbids +- **WHEN** `docs/architecture.md` documents a "MUST NOT" install-time + dependency rule for an app (e.g. OpenRegister) +- **THEN** `appinfo/info.xml`'s `` block SHALL NOT list that + app + +### Requirement: The license tag SHALL match the declared license text +`appinfo/info.xml`'s `` element and its top-of-file SPDX header +SHALL match the license asserted in both `` CDATA blocks +("Free and open source under the EUPL-1.2 license") and every PHP file's +`@license` docblock tag. + +#### Scenario: licence tag matches description text +- **WHEN** `info.xml`'s description states a license +- **THEN** the `` element SHALL declare the same license + +### Requirement: A translated product page SHALL live at the same relative path as its source page +Docusaurus i18n resolves a translated page by matching the source page's +file path under the locale's content directory. A translation SHALL NOT be +left at a stale pre-rename filename after the English source page is +renamed. + +#### Scenario: English product page is renamed +- **WHEN** `conduction-website/src/pages/apps/.mdx` is renamed to + `.mdx` +- **THEN** every locale's translation under + `i18n//docusaurus-plugin-content-pages/apps/` SHALL be renamed to + the same `.mdx`, and no stale `.mdx` file SHALL remain diff --git a/openspec/specs/calculated-fields/spec.md b/openspec/specs/calculated-fields/spec.md new file mode 100644 index 000000000..016ec8ba9 --- /dev/null +++ b/openspec/specs/calculated-fields/spec.md @@ -0,0 +1,248 @@ +# calculated-fields Specification + +## Purpose +TBD - created by archiving change widget-calculated-fields. Update Purpose after archive. + +## Requirements + +### Requirement: REQ-CALC-001 Formula parser produces deterministic AST + +The system SHALL parse a calculated-field expression into a canonical AST at save time and SHALL refuse to persist any widget whose calculated-field expressions fail to parse. + +#### Scenario: Valid expression parsed to AST + +- GIVEN a valid expression `(revenue - refunds) / revenue * 100` +- WHEN the widget is saved +- THEN the parser SHALL produce a `Binary` AST with operator `*` and SHALL store it in `compiledExpression` +- AND the AST SHALL be deep-equal to any other parse of the same expression + +#### Scenario: Parse error on mismatched parentheses + +- GIVEN an expression with mismatched parentheses `(revenue - refunds` +- WHEN the widget is saved +- THEN the API SHALL respond 400 with a parse error that includes the column position (column 21) +- AND SHALL NOT persist the widget + +#### Scenario: Whitespace normalization in AST + +- GIVEN two expressions that differ only by whitespace: `(a+b)` and `( a + b )` +- WHEN both are parsed +- THEN their `compiledExpression` ASTs SHALL be deep-equal + +### Requirement: REQ-CALC-002 Type checking at save time + +The system SHALL infer the type of every sub-expression at parse time and SHALL reject expressions whose operator/function arguments do not match the declared signature. + +#### Scenario: Type mismatch on binary operator + +- GIVEN an expression `revenue + customerName` where `revenue:number` and `customerName:string` +- WHEN the widget is saved +- THEN the API SHALL respond 400 with a type error naming both operands +- AND SHALL NOT persist the widget + +#### Scenario: Function signature validation + +- GIVEN an expression `round(revenue, "two")` where `round` expects (number, integer) +- WHEN the widget is saved +- THEN the API SHALL respond 400 with a function-signature error +- AND SHALL NOT persist the widget + +#### Scenario: Type inference through coalesce + +- GIVEN an expression `coalesce(null, revenue, 0)` where `revenue:number` +- WHEN the widget is saved +- THEN the inferred `returnType` SHALL be `number` +- AND the widget SHALL persist successfully + +### Requirement: REQ-CALC-003 Client-side evaluator reactive to filter changes + +The client-side evaluator SHALL recompute every `client` and `both` mode calculated field whenever any source field, source widget, or filter changes, and SHALL never round-trip to the server for an evaluation. + +#### Scenario: Recompute on filter change + +- GIVEN a widget with calculated field `profit = revenue - cost` +- AND the widget displays `revenue = 100000, cost = 60000, profit = 40000` +- WHEN the user changes a dashboard filter that affects `revenue` and `cost` to new values `110000, 70000` +- THEN `profit` SHALL be recomputed inside the browser to `40000` and the new value SHALL appear without an HTTP request +- AND the UI SHALL update within one animation frame + +#### Scenario: Cross-widget dependency tracking + +- GIVEN a calculated field referencing `widget:abc123` +- WHEN the source widget `abc123` refreshes its data +- THEN the dependent calculated field SHALL recompute synchronously in the same tick +- AND the updated value SHALL be rendered before the next animation frame + +#### Scenario: Filter chain with multiple affected fields + +- GIVEN a dashboard with widgets W1 (revenue), W2 (cost), W3 (calculated: W1.x / W2.y) +- WHEN the user changes a filter that affects both W1 and W2 +- THEN W3's calculated field SHALL be recomputed after both W1 and W2 complete their refresh +- AND the order of recomputation shall be deterministic (topological sort order) + +### Requirement: REQ-CALC-004 Server-side evaluation via OpenRegister computed-fields + +The system SHALL, for every calculated field in `evaluationMode=server` or `both`, create a corresponding `computed-fields` entry on the underlying schema and SHALL keep the two in sync on widget save. + +#### Scenario: Create server-mode computed-field entry + +- GIVEN a new calculated field with `evaluationMode=server`, `expression="revenue - cost"` +- WHEN the widget is saved +- THEN a `computed-fields` entry SHALL be created on the source schema with the same expression +- AND `serverComputedFieldId` SHALL be populated with the OpenRegister entry's ID + +#### Scenario: Update server-mode entry on expression change + +- GIVEN an existing server-mode calculated field with `serverComputedFieldId="cf-123"` +- WHEN the widget is saved with a new expression `"profit * 0.9"` +- THEN the linked `computed-fields` entry SHALL be updated with the new expression in the same transaction +- AND the update SHALL be atomic (no partial state visible to other readers) + +#### Scenario: Delete computed-field entry when widget is deleted + +- GIVEN a server-mode calculated field with `serverComputedFieldId="cf-123"` +- WHEN the widget is deleted +- THEN the linked `computed-fields` entry SHALL be removed from the schema +- AND no orphaned OpenRegister entries shall remain + +### Requirement: REQ-CALC-005 Identical results between evaluators + +Both evaluators SHALL produce identical results for every expression in the shared test suite, with documented and tested handling of numeric precision and null propagation. + +#### Scenario: Numeric precision across evaluators + +- GIVEN any expression in the shared evaluator test suite that produces a number +- WHEN evaluated by the TypeScript and PHP evaluators on identical input +- THEN the two results SHALL be deep-equal OR equal to within 1e-9 of each other (accounting for IEEE 754 rounding) + +#### Scenario: Null propagation + +- GIVEN an expression `a + null` where `a` is any non-null value +- WHEN evaluated by either the TypeScript or PHP evaluator +- THEN the result SHALL be `null` +- AND SHALL NOT throw an exception + +#### Scenario: Cross-evaluator test matrix + +- GIVEN the shared test suite contains 50+ test cases covering: literals, field refs, binary ops, unary ops, function calls, conditionals, null handling, type coercion at boundaries +- WHEN the test suite runs against both evaluators +- THEN 100% of tests SHALL pass on both + +### Requirement: REQ-CALC-006 Cross-widget references with cycle detection + +The system SHALL allow a calculated field to reference fields on other widgets on the same dashboard and SHALL refuse any dependency graph that contains a cycle. + +#### Scenario: Cycle detection on save + +- GIVEN widget A's calculated field references `widget:B.x` and widget B's calculated field references `widget:A.y` +- WHEN either widget is saved +- THEN the API SHALL respond 400 with a `cycleDetected` error naming both widgets +- AND SHALL NOT persist + +#### Scenario: Acyclic cross-widget reference accepted + +- GIVEN widget A's calculated field references `widget:B.x` where B has no calculated fields pointing back to A +- WHEN A is saved +- THEN the save SHALL succeed +- AND A's calculated field SHALL re-evaluate whenever B refreshes (REQ-CALC-003) + +#### Scenario: Self-reference rejected + +- GIVEN a calculated field named `x` with expression `widget:self.x` (self-referential) +- WHEN the widget is saved +- THEN the API SHALL respond 400 with a `cycleDetected` error +- AND SHALL NOT persist + +### Requirement: REQ-CALC-007 Cross-widget downgrade on source mismatch + +When a `server` or `both` mode calculated field references a widget whose data does not live in the same OpenRegister register/schema, the system SHALL downgrade the field to `client` mode at save time and SHALL warn the user. + +#### Scenario: Downgrade on different register + +- GIVEN a calculated field with `evaluationMode=server` that references a widget backed by a different register (e.g., widget A uses register:sales, widget B uses register:crm) +- WHEN the widget is saved +- THEN the field's `evaluationMode` SHALL be persisted as `client` +- AND the API response SHALL include a warning: `{warning: 'downgraded_evaluation_mode', field: 'name', reason: 'Cross-register reference'}` + +#### Scenario: Preserve server mode on same register + +- GIVEN a calculated field with `evaluationMode=server` that references a widget backed by the same register and schema +- WHEN the widget is saved +- THEN `evaluationMode` SHALL remain `server` +- AND a `computed-fields` entry SHALL be created + +### Requirement: REQ-CALC-008 Inline error display preserves dashboard usability + +When a calculated field fails to evaluate at runtime, the system SHALL render an inline error indicator on the widget without breaking other widgets on the dashboard. + +#### Scenario: Division by zero in client-side evaluation + +- GIVEN a calculated field `ratio = a / b` where the user has NOT added a guard and `b` is 0 in a given row +- WHEN the widget renders +- THEN the field's cell SHALL display an error icon +- AND hovering the icon SHALL show the expression and the value of `b` +- AND other widgets on the dashboard SHALL render normally (not affected) + +#### Scenario: Server-side evaluation error + +- GIVEN the same calculated field on the server-side evaluator +- WHEN the materialiser runs and encounters division by zero +- THEN the materialised value SHALL be `null` +- AND the OpenRegister computed-field error log SHALL record: `{expression, inputs, error: 'division by zero'}` + +#### Scenario: Error does not block widget render + +- GIVEN a widget with 10 calculated fields, 1 of which fails to evaluate +- WHEN the widget renders +- THEN the 9 successful fields SHALL display normally +- AND the 1 failed field SHALL show an error indicator +- AND the widget SHALL be usable (filtering, exporting, etc. do not break) + +### Requirement: REQ-CALC-009 Allowlisted function set with named signatures + +The parser SHALL accept only functions on the documented allowlist and SHALL reject any call to an unknown identifier as a function with a clear error. + +#### Scenario: Unknown function rejected + +- GIVEN an expression `eval("revenue * 2")` +- WHEN the widget is saved +- THEN the API SHALL respond 400 with `{error: 'unknownFunction', name: 'eval'}` +- AND SHALL NOT persist + +#### Scenario: Variadic function accepted with correct args + +- GIVEN an expression `sum(revenue, cost, profit)` where `sum` accepts variadic numbers +- WHEN the widget is saved +- THEN the parser SHALL validate that `sum` is on the allowlist and accepts variadic args +- AND the widget SHALL persist successfully + +#### Scenario: Allowlist is per-instance configurable + +- GIVEN a LaunchPad instance with `allowedFunctions: ['abs', 'round', 'sum']` (restricted) +- WHEN a user tries to save an expression using `now()` (not in allowlist) +- THEN the API SHALL respond 400 with `{error: 'functionNotAllowed', name: 'now'}` + +### Requirement: REQ-CALC-010 Format options applied at render time + +The system SHALL apply `formatOptions` only at render time on the client, and SHALL store and evaluate the underlying value in its native type. + +#### Scenario: Currency formatting preserves numeric value + +- GIVEN a calculated field with `returnType=number`, `formatOptions={style:'currency', currency:'EUR', locale:'nl-NL'}`, evaluated value of `1234.5` +- WHEN the widget renders for a Dutch user +- THEN the displayed string SHALL be `€ 1.234,50` +- AND the underlying value passed to alerting/export SHALL remain `1234.5` (not a string) + +#### Scenario: Date formatting preserves ISO instant + +- GIVEN a calculated field with `returnType=date`, `formatOptions={pattern:'dd MMM yyyy', locale:'nl-NL'}`, evaluated value of `2026-05-22T14:30:00Z` +- WHEN the widget renders +- THEN the displayed string SHALL be `22 mei 2026` +- AND the underlying value passed to filters/queries SHALL remain `2026-05-22T14:30:00Z` (ISO 8601) + +#### Scenario: Format options ignored at server-side evaluation + +- GIVEN the same calculated field in server-side mode (materialised) +- WHEN the field is evaluated on the server +- THEN the materialised value SHALL be the raw number/date (no formatting) +- AND the format options SHALL be applied only by the widget renderer, not by OpenRegister diff --git a/openspec/specs/calendar-widget/screens.md b/openspec/specs/calendar-widget/screens.md new file mode 100644 index 000000000..7011143b8 --- /dev/null +++ b/openspec/specs/calendar-widget/screens.md @@ -0,0 +1,9 @@ +# Screens + +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpStart https://identity.conduction.nl/screens/board?id=wilgenboom/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=vaartveld/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=esdoornveen/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=warmtepompacademie/LpStart +- LpWidgetInstellen the calendar widget form: calendars, an outside calendar feed by ICS address, 7 days or month (REQ-CAL-002, REQ-CAL-006) https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetInstellen diff --git a/openspec/specs/calendar-widget/spec.md b/openspec/specs/calendar-widget/spec.md index d1b22498b..a735674a7 100644 --- a/openspec/specs/calendar-widget/spec.md +++ b/openspec/specs/calendar-widget/spec.md @@ -40,9 +40,6 @@ The events endpoint returns a flat array of normalised event objects with shape: ## Requirements - -@e2e exclude all scenarios test REST API / ICS-fetch / backend aggregation — widget rendering requires real calendar data and NC Calendar integration not available in test env - ### Requirement: REQ-CAL-001 Widget registration The system MUST register a LaunchPad dashboard widget with id `launchpad_calendar` via `OCP\Dashboard\IManager::registerWidget()` so it appears in the widget picker alongside other Nextcloud dashboard widgets. @@ -68,6 +65,7 @@ The system MUST register a LaunchPad dashboard widget with id `launchpad_calenda - THEN the `launchpad_calendar` widget MUST still be discoverable in the picker #### Scenario: Widget registration includes metadata +@e2e exclude never built: no Nextcloud dashboard widget (IWidget / IManager::registerWidget) named launchpad_calendar exists in lib/ or appinfo/, and `git log --all -S launchpad_calendar -- lib src appinfo` is empty, so there is no OCS widget metadata to read. That the LaunchPad picker offers type `calendar` with a form is pinned by src/constants/__tests__/widgetRegistry.spec.js ("supplies a form for types the communal registry leaves form-less") and cited by widget-appears-in-picker - GIVEN the widget is registered - WHEN the widget picker fetches widget metadata @@ -82,8 +80,8 @@ The system MUST store per-placement widget configuration in the `oc_launchpad_wi - GIVEN a user is configuring a calendar widget placement - WHEN they select internal Nextcloud Calendar sources - THEN the configuration MUST store an `internalCalendars: string[]` field -- AND each entry MUST be a valid NC Calendar principal URI (e.g., `principals/users/alice/calendar-id`) -- NOTE: Principal resolution is delegated to `OCP\Calendar\IManager` +- AND each entry MUST be the key of a calendar the user can read, as `GET /api/widgets/calendar/calendars` lists it (the picker's source) +- NOTE: Calendar resolution is delegated to `OCP\Calendar\IManager` #### Scenario: Config for external ICS URLs @@ -97,8 +95,8 @@ The system MUST store per-placement widget configuration in the `oc_launchpad_wi - GIVEN a user is configuring a calendar widget placement - WHEN they choose a display mode -- THEN the configuration MUST store a `viewMode: 'month'|'week'|'agenda'|'upcoming-list'` field -- AND the default viewMode MUST be `'upcoming-list'` when not explicitly set +- THEN the configuration MUST store a `viewMode: 'month'|'week'|'agenda'` field +- AND the default viewMode MUST be `'agenda'` when not explicitly set #### Scenario: Config for days-ahead threshold @@ -131,14 +129,14 @@ The system MUST expose `GET /api/widgets/calendar/{placementId}/events?from=ISO& - GIVEN a calendar widget placement with internalCalendars=[...] and externalIcsUrls=[...] - AND the requesting user has read access to those internal calendars - WHEN the frontend sends GET /api/widgets/calendar/{placementId}/events?from=2026-05-01&to=2026-05-31 -- THEN the system MUST return HTTP 200 with a JSON array of event objects +- THEN the system MUST return HTTP 200 with a JSON object whose `events` member is an array of event objects (and whose `failures` member lists the sources that were skipped) - AND each event MUST include: uid, title, start (ISO 8601), end (ISO 8601), allDay (boolean), location (string, nullable), description (string, nullable), calendarId (string), calendarName (string), color (string, hex or NC theme var), source ('internal'|'external') #### Scenario: No events returns empty array - GIVEN a calendar widget with valid config but no events in the date range - WHEN the frontend fetches events -- THEN the system MUST return HTTP 200 with an empty array `[]` +- THEN the system MUST return HTTP 200 with an empty `events` array `[]` #### Scenario: Missing placement returns 404 @@ -177,6 +175,7 @@ The system MUST expand recurring events into individual instances for the reques - AND each instance MUST have a distinct start/end time while sharing uid root + recurrence-id #### Scenario: RRULE expansion for external ICS +@e2e exclude needs an external HTTPS ICS feed on a public address; the SSRF guard (UrlSafetyValidator::isSafe) refuses every host the CI fixture can serve. No unit test pins external RRULE expansion: tests/Unit/Service/CalendarWidgetServiceSourcesTest.php only parses an empty VCALENDAR. Internal expansion is cited by rrule-expansion-for-internal-events - GIVEN an external ICS URL contains a weekly recurring event "Team meeting" with RRULE:FREQ=WEEKLY;UNTIL=2026-05-31 - WHEN the frontend fetches events for 2026-05-01 to 2026-05-31 @@ -198,6 +197,7 @@ The system MUST expand recurring events into individual instances for the reques - AND other instances MUST be included normally #### Scenario: Invalid RRULE is skipped +@e2e exclude needs an external HTTPS ICS feed serving a malformed RRULE, which the CI fixture cannot provide (SSRF guard refuses local hosts), and a malformed RRULE cannot be relied on to survive the CalDAV PUT validation, so the internal path cannot carry it either. No unit test pins the malformed-RRULE branch of CalendarWidgetService::parseAndExpandIcs - GIVEN an external ICS contains a malformed RRULE - WHEN expansion is attempted @@ -210,6 +210,7 @@ The system MUST expand recurring events into individual instances for the reques The system MUST cache fetched external ICS content for 30 minutes (default) using Nextcloud's `ICache` to reduce load on external servers and improve dashboard load time. #### Scenario: First fetch populates cache +@e2e exclude needs an external HTTPS ICS feed the CI fixture cannot serve, and the ICache is not observable over HTTP; pinned by tests/Unit/Service/CalendarWidgetServiceTest.php::testFetchIcsBodyFetchesAndCachesOnMiss (the key is `ics_` + md5(url), not the placement-scoped pattern this scenario names) - GIVEN an external ICS URL is configured on a placement - WHEN the frontend fetches events and this is the first request to that URL from this placement @@ -218,6 +219,7 @@ The system MUST cache fetched external ICS content for 30 minutes (default) usin - AND return the parsed events #### Scenario: Subsequent fetch uses cache +@e2e exclude needs an external HTTPS ICS feed the CI fixture cannot serve, and whether a fetch happened is not observable over HTTP; pinned by tests/Unit/Service/CalendarWidgetServiceTest.php::testFetchIcsBodyServesFromCache - GIVEN the cache is populated with fresh ICS content - WHEN the frontend fetches events again within 30 minutes @@ -226,6 +228,7 @@ The system MUST cache fetched external ICS content for 30 minutes (default) usin - AND return the same events (with timing variation only from new expansion) #### Scenario: Cache TTL is admin-configurable +@e2e exclude a 30- or 60-minute expiry cannot be waited out in e2e and needs an external feed the fixture cannot serve; pinned by tests/Unit/Service/CalendarWidgetServiceTest.php::testFetchIcsBodyFetchesAndCachesOnMiss (reads `calendar_widget_ics_cache_ttl_seconds`, writes the entry with that TTL) - GIVEN the admin sets `launchpad.calendar_widget_ics_cache_ttl_seconds` to 3600 (1 hour) - WHEN events are fetched @@ -233,6 +236,7 @@ The system MUST cache fetched external ICS content for 30 minutes (default) usin - AND the system MUST read the setting from `IAppConfig::getValueInt('launchpad', 'launchpad.calendar_widget_ics_cache_ttl_seconds', 1800)` #### Scenario: Cache key includes URL hash +@e2e exclude the shared cache entry and the single external fetch are not observable over HTTP and need an external feed the fixture cannot serve; pinned by tests/Unit/Service/CalendarWidgetServiceTest.php::testFetchIcsBodyServesFromCache (the key is derived from the URL alone) - GIVEN two placements reference the same external ICS URL - WHEN both fetch events @@ -240,6 +244,7 @@ The system MUST cache fetched external ICS content for 30 minutes (default) usin - AND only one external fetch occurs across both placements #### Scenario: Cache is invalidated on settings change +@e2e exclude needs an external feed the fixture cannot serve, and which body was used is not observable over HTTP. No unit test changes a placement's URL; the behaviour follows from the URL-only key pinned by tests/Unit/Service/CalendarWidgetServiceTest.php::testFetchIcsBodyServesFromCache - GIVEN a placement is reconfigured to use a different ICS URL - WHEN events are fetched @@ -358,6 +363,7 @@ The frontend MUST support four distinct calendar display modes, selectable via ` - AND each event entry MUST show title, time range, and calendar name/color #### Scenario: Upcoming-list view shows next N events flat +@e2e exclude never built: no `upcoming-list` mode exists in the renderer (CnCalendarWidget VIEW_MODES is month/week/agenda), the form or the service, and `git log --all -S upcoming-list -- src lib` is empty; no test exists - GIVEN a placement is configured with viewMode: 'upcoming-list' and daysAhead: 14 - WHEN the widget is rendered @@ -383,6 +389,7 @@ The frontend MUST support four distinct calendar display modes, selectable via ` The system MUST handle failures in fetching external ICS sources gracefully so that a single failed URL does not prevent the entire widget from rendering. #### Scenario: Single ICS URL fetch timeout +@e2e exclude needs an external HTTPS host that stalls, which the CI fixture cannot provide (the SSRF guard refuses local hosts). No unit test drives a timeout; tests/Unit/Service/CalendarWidgetServiceTest.php::testFetchIcsBodyFetchesAndCachesOnMiss pins the 10-second timeout option only - GIVEN a placement references two external ICS URLs: A (responsive) and B (times out after 10 seconds) - WHEN the frontend fetches events with a 15-second timeout per URL @@ -392,6 +399,7 @@ The system MUST handle failures in fetching external ICS sources gracefully so t - AND the response MUST still return HTTP 200 with events from A #### Scenario: Single ICS URL returns 4xx +@e2e exclude needs an external HTTPS host that answers 404 on demand, which the CI fixture cannot provide (the SSRF guard refuses local hosts). No unit test pins the HTTP-error branch of fetchExternalIcsEvents - GIVEN a placement references a URL that returns HTTP 404 - WHEN the frontend fetches events @@ -401,6 +409,7 @@ The system MUST handle failures in fetching external ICS sources gracefully so t - AND return HTTP 200 with events from other sources #### Scenario: Single ICS URL returns 5xx +@e2e exclude needs an external HTTPS host that answers 500 on demand, which the CI fixture cannot provide (the SSRF guard refuses local hosts). No unit test pins the HTTP-error branch of fetchExternalIcsEvents - GIVEN a placement references a URL that returns HTTP 500 - WHEN the frontend fetches events @@ -426,6 +435,7 @@ The system MUST handle failures in fetching external ICS sources gracefully so t - AND the dashboard MUST not be blocked (the widget gracefully degrades) #### Scenario: Internal calendar fetch error +@e2e exclude an exception from OCP\Calendar\IManager::search() cannot be provoked from a browser or the API; pinned by tests/Unit/Service/CalendarWidgetServiceTest.php::testFetchInternalEventsGuardsAndFiltersByPrincipal (a throwing search is logged, reported in `failures`, and answers no events) - GIVEN an internal calendar fetch via `OCP\Calendar\IManager::search()` throws an exception - WHEN the widget fetches events @@ -474,3 +484,12 @@ The system MUST display appropriate empty-state messaging when there are no even - THEN an error message MUST be displayed (e.g., "Failed to load events") - AND a retry button MUST be present - AND clicking retry MUST re-fetch events + +### Requirement: The Calendar content form (REQ-CAL-020) + +The content part of a Calendar widget SHALL list the reader's calendars to choose from, SHALL accept an external calendar by ICS address, and SHALL offer the period 7 days or Month. + +#### Scenario: Add an external calendar + +- **WHEN** the editor adds an ICS address and chooses 7 days +- **THEN** the widget shows that calendar's events of the next seven days with the chosen Nextcloud calendars diff --git a/openspec/specs/chart-presets/spec.md b/openspec/specs/chart-presets/spec.md new file mode 100644 index 000000000..92417044f --- /dev/null +++ b/openspec/specs/chart-presets/spec.md @@ -0,0 +1,37 @@ +# chart-presets Specification + +## Purpose +A pie chart and a graph an author can pick and fill without knowing chart types. + +## Requirements + +### Requirement: A pie chart is a donut with its total in the centre (REQ-CHARTP-001) + +The `pie-chart` widget SHALL draw a donut with a legend that writes each slice's value, and the total of the slices +in the centre. + +#### Scenario: Cases per status + +- **GIVEN** a pie chart with In behandeling 138, Wacht op aanvrager 74, Wacht op advies 46 and Afgerond 54 +- **THEN** the donut shows four slices, the legend names each with its value, and the centre says Total 312 + +### Requirement: A graph draws bars and lines (REQ-CHARTP-002) + +The `graph` widget SHALL draw bars over time from a register query, and from entered values any number of named +series, each as bars or a line, in one chart with axes and a legend. + +#### Scenario: Applications and decisions per month + +- **GIVEN** a graph with axis labels April to September, a series "Aanvragen" as bars and "Besluiten" as a line +- **THEN** one chart shows the bars and the line over the six months, with a legend naming both + +### Requirement: A chart reads a register query or entered values (REQ-CHARTP-003) + +Both forms SHALL offer "A register query", edited by the shared chart form, and "Values you enter". Entered values +SHALL be saved in the placement and SHALL NOT make the chart read a register. A form SHALL not save without a +register query, or without at least one labelled value (pie chart) or axis labels and one named series (graph). + +#### Scenario: Entered values + +- **WHEN** an author picks "Pie chart", chooses "Values you enter" and enters two labelled values +- **THEN** the chart shows those two slices and reads no register diff --git a/openspec/specs/cli-commands/screens.md b/openspec/specs/cli-commands/screens.md new file mode 100644 index 000000000..6597c9251 --- /dev/null +++ b/openspec/specs/cli-commands/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Commando's op de server (occ), zonder scherm. diff --git a/openspec/specs/cli-commands/spec.md b/openspec/specs/cli-commands/spec.md index 6039d95bc..a88343dc9 100644 --- a/openspec/specs/cli-commands/spec.md +++ b/openspec/specs/cli-commands/spec.md @@ -10,9 +10,6 @@ The CLI commands suite establishes a coherent, standardized operator interface f ## Data Model - -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Command Namespace Convention All LaunchPad CLI commands MUST use the `launchpad:` prefix followed by a verb-noun pattern: @@ -164,6 +161,7 @@ The system MUST establish `launchpad:` as the canonical namespace prefix for ALL - AND there are no namespace collisions #### Scenario: Future commands follow the convention +@e2e exclude A code-review convention, not runtime behaviour; nothing to run and no test exists. - GIVEN a developer adds a new command for LaunchPad - WHEN they name it `launchpad:custom:action` and register it in `appinfo/info.xml` @@ -212,6 +210,7 @@ Every LaunchPad command MUST support three consistent global flags: `--quiet|-q` - AND the exit code is 0 on success or 3 on permission denied #### Scenario: All three flags combine cleanly +@e2e exclude Never built: lib/Command/ImportCommand.php extends Symfony Command, not CommandBase, so `launchpad:import --json` is an unknown option and the scenario has no product to run against. No test exists. - GIVEN `php occ launchpad:import --file=/tmp/x.zip --quiet --no-interaction --json` - WHEN the import runs @@ -273,6 +272,7 @@ The system MUST provide four new operator-facing dashboard commands: `launchpad: The system MUST provide the command `launchpad:user:revoke-feed-token ` to revoke a user's RSS feed token. The command MUST depend on the `dashboard-rss-feeds` capability being enabled and MUST refuse gracefully when that capability is absent. #### Scenario: Revoke token for a valid user +@e2e exclude Never built: there is no launchpad:user:revoke-feed-token command in lib/Command/ or appinfo/info.xml, nor an RSS feed-token route in appinfo/routes.php (git log --all on lib/ finds none); the HTTP 401 cannot be set up without it. No test exists. - GIVEN user "alice" has an active RSS feed token - WHEN an admin runs `php occ launchpad:user:revoke-feed-token alice` @@ -281,6 +281,7 @@ The system MUST provide the command `launchpad:user:revoke-feed-token ` to - AND the exit code MUST be 0 #### Scenario: Revoke token for unknown user returns exit code 4 +@e2e exclude Never built: no launchpad:user:revoke-feed-token command exists in lib/Command/ or appinfo/info.xml. No test exists. - GIVEN no Nextcloud user with uid "nonexistent" exists - WHEN an admin runs `php occ launchpad:user:revoke-feed-token nonexistent` @@ -288,6 +289,7 @@ The system MUST provide the command `launchpad:user:revoke-feed-token ` to - AND stderr MUST print "User not found: 'nonexistent'" #### Scenario: Command fails gracefully when RSS capability is absent +@e2e exclude Never built: no launchpad:user:revoke-feed-token command exists in lib/Command/ or appinfo/info.xml. No test exists. - GIVEN the `dashboard-rss-feeds` capability is not installed or disabled - WHEN any operator runs `php occ launchpad:user:revoke-feed-token alice` @@ -295,12 +297,14 @@ The system MUST provide the command `launchpad:user:revoke-feed-token ` to - AND stderr MUST print "The dashboard-rss-feeds capability is not available" #### Scenario: JSON output on success +@e2e exclude Never built: no launchpad:user:revoke-feed-token command exists in lib/Command/ or appinfo/info.xml. No test exists. - GIVEN `php occ launchpad:user:revoke-feed-token alice --json` - WHEN the command successfully revokes the token - THEN stdout MUST be `{success: true, exitCode: 0, data: {uid: "alice", revokedAt: ""}, errors: []}` #### Scenario: Non-admin is denied +@e2e exclude Never built: no launchpad:user:revoke-feed-token command exists, and no command returns EXIT_PERMISSION_DENIED. No test exists. - GIVEN a regular (non-admin) Nextcloud user runs the command - WHEN authorization is checked @@ -333,6 +337,7 @@ The system MUST provide three i18n commands: `launchpad:i18n:export-strings` (ex - AND the exit code MUST be 0 #### Scenario: Migrate language structure one-time +@e2e exclude Never built: the command body migrates nothing (lib/Command/I18nMigrateLanguageStructureCommand.php sets $migrated = 0), so there is no migration to observe; tests/Unit/Command/I18nNavigationCommandsGoldenTest.php::testMigrateLanguageStructure pins only the zero-row run. tests/e2e/cli-commands.spec.ts runs the command with --json for its envelope. - GIVEN the old flat-language storage schema is in place - AND the `dashboard-language-content` capability is enabled @@ -342,6 +347,7 @@ The system MUST provide three i18n commands: `launchpad:i18n:export-strings` (ex - AND rerunning the command MUST be idempotent (already migrated rows are skipped, exit code 0) #### Scenario: Migration aborts when capability is absent +@e2e exclude Needs an instance without the dashboard-language-content table; the e2e instance has it, and dropping a schema table from a test is not something to do to a running instance. Pinned by tests/Unit/Command/I18nNavigationCommandsGoldenTest.php::testMigrateLanguageStructure (exit 1, CAPABILITY_MISSING, the message). - GIVEN the `dashboard-language-content` capability is not installed - WHEN an admin runs `php occ launchpad:i18n:migrate-language-structure` @@ -349,6 +355,7 @@ The system MUST provide three i18n commands: `launchpad:i18n:export-strings` (ex - AND stderr MUST print "dashboard-language-content capability is required" #### Scenario: Copy navigation tree between language variants +@e2e exclude Never built: lib/Command/I18nCopyNavigationCommand.php reports `copied: 0` without copying, so no node can be seen to be cloned; tests/Unit/Command/I18nNavigationCommandsGoldenTest.php::testCopyNavigation pins only that zero-node run. - GIVEN a Dutch (`nl`) navigation tree with 12 nodes exists - WHEN an admin runs `php occ launchpad:i18n:copy-navigation --from=nl --to=en` @@ -381,6 +388,7 @@ All LaunchPad commands MUST emit exactly one of the six standard exit codes (0, - AND stderr MUST print "Invalid UUID format: 'not-a-uuid'" #### Scenario: Permission denied exit code 3 +@e2e exclude Never built: no command checks for an administrator or returns EXIT_PERMISSION_DENIED (grep lib/Command). tests/Unit/Service/CommandServiceTest.php::testExitCodeConstantsAreDistinctAndCoverContract pins only the constant. - GIVEN a regular (non-admin) user runs `php occ launchpad:dashboard:delete a1b2c3d4` - WHEN the command checks authorization @@ -395,6 +403,7 @@ All LaunchPad commands MUST emit exactly one of the six standard exit codes (0, - AND stderr MUST print "Dashboard not found" #### Scenario: Partial success exit code 5 +@e2e exclude Never built: lib/Command/ImportCommand.php always returns 0 after printing "Imported N dashboards, skipped M"; nothing returns EXIT_PARTIAL_SUCCESS. No test exists. - GIVEN `php occ launchpad:import --file=/tmp/batch.zip` with 10 dashboards where 7 succeed and 3 fail - WHEN the batch import completes @@ -413,6 +422,7 @@ All commands invoked with `--json` MUST emit a single JSON object to stdout conf - AND the `data.dashboards` field MUST be an array #### Scenario: Error JSON response +@e2e exclude Never built for this command (no launchpad:user:revoke-feed-token). The envelope shape is pinned by tests/Unit/Service/CommandServiceTest.php::testEnvelopeErrorShape and the list command's user-not-found by tests/Unit/Command/DashboardListCommandGoldenTest.php::testRefusedFilters. - GIVEN `php occ launchpad:user:revoke-feed-token unknown-user --json` - WHEN the command does not find the user @@ -420,6 +430,7 @@ All commands invoked with `--json` MUST emit a single JSON object to stdout conf - AND `exitCode` in JSON MUST match the process exit code #### Scenario: Multiple errors in JSON +@e2e exclude Never built: lib/Command/ImportCommand.php has no --json option (it does not extend CommandBase). No test exists. - GIVEN `php occ launchpad:import --file=/tmp/corrupt.zip --json` - WHEN the ZIP contains 3 invalid dashboards @@ -434,6 +445,7 @@ All commands invoked with `--json` MUST emit a single JSON object to stdout conf - NOTE Any debug or progress output MUST go to stderr only #### Scenario: Partial success exitCode in JSON +@e2e exclude Never built: lib/Command/ImportCommand.php has no --json option and never returns 5. No test exists. - GIVEN `php occ launchpad:import --file=/tmp/mix.zip --json` - WHEN 7 succeed and 3 fail @@ -458,6 +470,7 @@ All LaunchPad CLI commands MUST be registered in `appinfo/info.xml` under a ` [--group=]... [--default] [--force]`, or ` --update [--dry-run]`, MUST add a template that ships with LaunchPad (REQ-TMPL-018) as an admin template, for scripted deploys. + +- `--group` names a group whose members get the template. It may be repeated. A group that does not exist MUST fail the command before anything is added. +- `--default` makes it the default template for everyone without a group template (REQ-TMPL-008). +- `--force` adds a fresh copy even when the template is already installed. + +- `--update` brings the installed template to the version LaunchPad ships, in place, and re-syncs the copies members already have (REQ-TMPL-020). It keeps the template's groups, default flag and name, so it MUST refuse `--group`, `--default` and `--force` with exit 1, before anything runs. It MUST print the old and the new version and one line per widget added (`+`), removed (`-`) and changed (`~`, with what changed), the number of unchanged widgets, and how many members have a copy and how many copies changed. When the installed version is already the shipped one it MUST say so, change nothing and exit 0. When the template is not installed it MUST say so and exit 1. +- `--dry-run`, with `--update` only, prints the same lines and MUST write nothing. Without `--update` it MUST exit 1. + +The command MUST print the template's UUID, its version, its groups and whether it is the default. It MUST name the widgets no app on the instance registers. When personal dashboards are off it MUST say that members will see the template read-only and that its compulsory widgets have no effect (REQ-TMPL-019). Run a second time without `--force`, it MUST add nothing and MUST apply `--group` and `--default` again. It MUST exit 0 on success and 1 on an unknown id, an unknown group or a failed install. + +#### Scenario: A deploy script installs the template for a group +- GIVEN the group "medewerkers" exists and `mijn-werkdag` is not installed +- WHEN an operator runs `php occ launchpad:template:install mijn-werkdag --group=medewerkers` +- THEN the command MUST exit 0 and print the new template's UUID +- AND the template MUST target the group "medewerkers" + +#### Scenario: An unknown group stops the install +- GIVEN no group "medewerkerz" exists +- WHEN an operator runs `php occ launchpad:template:install mijn-werkdag --group=medewerkerz` +- THEN the command MUST exit 1 and name the group +- AND no template MUST be added + +#### Scenario: An operator updates the installed template and reads what changed +- GIVEN `mijn-werkdag` is installed at version 2 and LaunchPad ships version 3 +- WHEN an operator runs `php occ launchpad:template:install mijn-werkdag --update --dry-run` +- THEN the command MUST exit 0, print "Dry run, nothing written." and one line per widget added, removed and changed +- AND nothing MUST be written +- WHEN the operator runs the command again without `--dry-run` +- THEN the command MUST exit 0, print the same lines and how many members' copies changed + +#### Scenario: An update refuses the options that change who gets the template +- WHEN an operator runs `php occ launchpad:template:install mijn-werkdag --update --group=bestuur` +- THEN the command MUST exit 1 and say `--update` cannot be combined with `--group`, `--default` or `--force` +- AND nothing MUST be written + +#### Scenario: An unknown template id lists the shipped ones +- WHEN an operator runs `php occ launchpad:template:install does-not-exist` +- THEN the command MUST exit 1 and list the shipped template ids diff --git a/openspec/specs/clock-weather-widgets/screens.md b/openspec/specs/clock-weather-widgets/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/clock-weather-widgets/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/clock-weather-widgets/spec.md b/openspec/specs/clock-weather-widgets/spec.md index 69d718ed8..007dd4c90 100644 --- a/openspec/specs/clock-weather-widgets/spec.md +++ b/openspec/specs/clock-weather-widgets/spec.md @@ -8,6 +8,7 @@ TBD - created by archiving change clock-weather-widgets. Update Purpose after ar The system MUST register a `launchpad_clock` widget with the Nextcloud Dashboard Widget API (v2) that is rendered entirely client-side, with no backend endpoint and no data fetch on discovery. #### Scenario: Widget appears in discovery +@e2e exclude never built: no `launchpad_clock` or `launchpad_weather` widget is registered with Nextcloud's dashboard (no widget provider class in lib/, no registerWidget call; `git log --all -Slaunchpad_clock -- src lib appinfo templates` returns nothing). LaunchPad's own Add Widget modal offers the types as `clock` and `weather` (src/constants/widgetRegistry.js), which is not the id this scenario names; the written-out test is kept as test.fixme in tests/e2e/clock-weather-widgets.spec.ts - GIVEN the LaunchPad app is installed and enabled - WHEN the user opens the "Add Widget" modal on a dashboard - THEN the clock widget MUST appear in the widget list with id `launchpad_clock` @@ -15,11 +16,13 @@ The system MUST register a `launchpad_clock` widget with the Nextcloud Dashboard - AND the widget MUST NOT fetch any data on discovery — it is fully client-side #### Scenario: Registration via IManager +@e2e exclude a PHP boot-time call with no browser surface, and never built: lib/ holds no ClockWidgetProvider and no registerWidget call, `git log --all -SClockWidgetProvider -- src lib appinfo templates` returns nothing, and no unit test pins it - GIVEN `OCP\Dashboard\IManager` is available - WHEN the LaunchPad app boots - THEN the app MUST register `ClockWidgetProvider` by calling `$manager->registerWidget(...)` #### Scenario: No backend endpoint or migration +@e2e exclude asserts that source artefacts are absent across an app upgrade (no clock route, no migration); an upgrade and the migration list cannot be observed from Playwright. The client-side half is pinned by src/components/Widgets/Renderers/__tests__/ClockWidget.spec.js (renders without ever importing axios or calling a LaunchPad endpoint); nothing pins the absence of a migration - GIVEN the clock widget is implemented - WHEN the LaunchPad app is upgraded - THEN NO custom API endpoint (e.g. `/api/clock/...`) MUST exist for the clock @@ -70,12 +73,14 @@ The system MUST render the clock in the browser using the configured timezone an The system MUST register a `launchpad_weather` widget (v2) whose reading is fetched server-side, so any provider API key stays on the server and the browser calls only a LaunchPad endpoint. #### Scenario: Widget appears in discovery +@e2e exclude never built: no `launchpad_clock` or `launchpad_weather` widget is registered with Nextcloud's dashboard (no widget provider class in lib/, no registerWidget call; `git log --all -Slaunchpad_clock -- src lib appinfo templates` returns nothing). LaunchPad's own Add Widget modal offers the types as `clock` and `weather` (src/constants/widgetRegistry.js), which is not the id this scenario names; the written-out test is kept as test.fixme in tests/e2e/clock-weather-widgets.spec.ts - GIVEN the LaunchPad app is installed and enabled - WHEN the user opens the "Add Widget" modal on a dashboard - THEN the weather widget MUST appear in the widget list with id `launchpad_weather` - AND the widget MUST have a title and an icon #### Scenario: Registration via IManager +@e2e exclude a PHP boot-time call with no browser surface, and never built: lib/ holds no WeatherWidgetProvider and no registerWidget call, `git log --all -SWeatherWidgetProvider -- src lib appinfo templates` returns nothing, and no unit test pins it - GIVEN `OCP\Dashboard\IManager` is available - WHEN the LaunchPad app boots - THEN the app MUST register `WeatherWidgetProvider` by calling `$manager->registerWidget(...)` @@ -96,6 +101,7 @@ The system MUST register a `launchpad_weather` widget (v2) whose reading is fetc The system MUST resolve the weather reading via the Nextcloud `weather_status` provider when available, otherwise via a configurable provider URL with a server-held API key, fetching via `OCP\Http\Client` and caching in `ICache`. #### Scenario: Reuse weather_status when present +@e2e exclude the weather_status path fetches from met.no, an external service the CI fixture cannot reach, and its provider URL is not configurable; pinned by tests/Unit/Service/WeatherServiceBranchesTest.php (testWeatherStatusMetricReadingUsesNextHourSymbolAndAddress, testWeatherStatusImperialReadingFallsBackToSixHourSymbolAndDefaultLabel, testWeatherStatusDisabledGivesUnavailable) - GIVEN the Nextcloud `weather_status` provider is available on the instance - WHEN `WeatherService` resolves a placement's location - THEN it MUST obtain the reading through the `weather_status` provider pattern rather than a bespoke external call diff --git a/openspec/specs/communities-widget/spec.md b/openspec/specs/communities-widget/spec.md new file mode 100644 index 000000000..80e195f30 --- /dev/null +++ b/openspec/specs/communities-widget/spec.md @@ -0,0 +1,48 @@ +# communities-widget Specification + +## Purpose +The Communities widget lists the open Talk conversations a person may join, with the ones the organisation pinned +first, and joins one in a click. + +## Requirements + +### Requirement: The Communities widget lists open Talk conversations the viewer may join (REQ-COMM-001) + +The Communities widget MUST list the open Talk conversations that Talk lets the viewer see, with name, description and member count, and MUST mark the ones the viewer already joined. It MUST call Talk as the signed-in user and MUST NOT store conversation data in LaunchPad. + +#### Scenario: Pieter finds a community + +- **GIVEN** Talk has an open conversation "Duurzaamheid" that all users may join, and Pieter placed a Communities widget on "Mijn werkplek" +- **WHEN** he opens the Workspace page +- **THEN** the widget lists "Duurzaamheid" with its description and member count and a "Join" button + +### Requirement: One click joins a community (REQ-COMM-002) + +"Join" MUST add the viewer to the conversation through Talk and change into "Open", which goes to the conversation in Talk. + +#### Scenario: Join and open + +- **GIVEN** "Duurzaamheid" shows "Join" for Pieter +- **WHEN** he clicks "Join" +- **THEN** he is a member of the conversation in Talk and the button reads "Open" +- **AND WHEN** he clicks "Open", Talk opens the conversation + +### Requirement: Administrators pin official communities (REQ-COMM-003) + +An administrator MUST be able to pin up to 20 Talk conversations. The widget MUST show pinned conversations the viewer may see first, marked "Pinned by your organisation", and the widget form MUST offer "Show only pinned". + +#### Scenario: Pinned first + +- **GIVEN** Noor pinned "Vraag het de ICT" and Pieter's widget lists "Duurzaamheid" and "Vraag het de ICT" +- **WHEN** Pieter opens the Workspace page +- **THEN** "Vraag het de ICT" is first and carries the mark "Pinned by your organisation" + +### Requirement: Without Talk the widget explains itself (REQ-COMM-004) + +When Talk is not enabled for the viewer, the widget MUST show "Communities need Nextcloud Talk. Ask your administrator to enable it." and MUST NOT call Talk. + +#### Scenario: Talk disabled + +- **GIVEN** Talk is disabled on the server +- **WHEN** Pieter opens a dashboard with a Communities widget +- **THEN** the widget shows the Talk message and no request to `/ocs/v2.php/apps/spreed` is made diff --git a/openspec/specs/conditional-visibility-editor/screens.md b/openspec/specs/conditional-visibility-editor/screens.md new file mode 100644 index 000000000..7b9c5689f --- /dev/null +++ b/openspec/specs/conditional-visibility-editor/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpZichtbaarheid https://identity.conduction.nl/screens/board?id=launchpad/LpZichtbaarheid diff --git a/openspec/specs/conditional-visibility-editor/spec.md b/openspec/specs/conditional-visibility-editor/spec.md index da22dacb6..29e85c363 100644 --- a/openspec/specs/conditional-visibility-editor/spec.md +++ b/openspec/specs/conditional-visibility-editor/spec.md @@ -91,24 +91,26 @@ The editor MUST surface the existing engine's include=OR and exclude=AND semanti ### Requirement: REQ-CVUI-004 Preview As Audience and Date -The editor MUST provide a "preview as audience / date" affordance that shows the effective visibility of the current rule set for an author-chosen `(groups, datetime)` context before the rules are published, so an author can catch a mis-scoped rule (e.g. an exclude rule that hides the widget from everyone) prior to saving. +The editor MUST provide a "View as" affordance that shows the effective visibility of the current rule set for one author-chosen person at one author-chosen moment, before the rules are published, so an author can catch a mis-scoped rule (e.g. an exclude rule that hides the widget from everyone) prior to saving. The person defaults to the author; the person's own groups and profile values are resolved on the server. The preview MUST use the placement's match mode (all or one rule, REQ-VIS-014) and MUST say in one sentence whether that person sees the widget and why (REQ-CVUI-006). #### Scenario: Preview shows visible for a matching audience - GIVEN the editor holds one include group rule with groups ["marketing"] -- WHEN the author previews as groups ["marketing"] at datetime "2026-07-23T14:30" -- THEN `useVisibilityPreview` MUST call `POST /api/visibility/preview` with the current rule set and that context +- WHEN the author views as a person in "marketing" at datetime "2026-07-23T14:30" +- THEN `useVisibilityPreview` MUST call `POST /api/visibility/preview` with the current rule set, that person as `context.userId`, that moment, the match mode and the placement id - AND the result MUST display "Visible" with an icon and text (not colour alone) - AND the matched include rule MUST be indicated +- AND the sentence MUST say that the person sees this widget, because the person is in "marketing" #### Scenario: Preview shows hidden for a non-matching audience - GIVEN the editor holds one include group rule with groups ["marketing"] -- WHEN the author previews as groups ["engineering"] at any datetime +- WHEN the author views as a person in "engineering" only, at any moment - THEN the result MUST display "Hidden" - AND no include rule MUST be indicated as matched +- AND the sentence MUST say that the person does not see this widget, because the person is not in "marketing" #### Scenario: Preview reflects an exclude override - GIVEN the editor holds an include group rule (groups ["marketing"], matches) and an exclude date rule (2026-07-01..2026-07-31) -- WHEN the author previews as groups ["marketing"] at datetime "2026-07-15T10:00" +- WHEN the author views as a person in "marketing" at datetime "2026-07-15T10:00" - THEN the result MUST display "Hidden" - AND the matched exclude rule MUST be indicated as the reason @@ -123,6 +125,11 @@ The editor MUST provide a "preview as audience / date" affordance that shows the - WHEN `useVisibilityPreview` builds the request body - THEN it MUST send the exact `ruleConfig` shape the rows emit, with no translation layer that could drift from the saved shape +#### Scenario: Viewing as another person needs the rules editor +- GIVEN the author may not edit the placement's rules +- WHEN a preview names another person as `context.userId` +- THEN the endpoint MUST answer HTTP 403 and evaluate nothing + ### Requirement: REQ-CVUI-005 Preview Endpoint Reuses the Render-Time Evaluation Path and Never Persists The `POST /api/visibility/preview` endpoint MUST be read-only and MUST evaluate the supplied rule set against the supplied `(groups, datetime)` context through the SAME evaluation code path used at render time, so a preview verdict can never diverge from the visibility the dashboard will actually produce for that context. It MUST NOT write to the database and MUST validate its input server-side. @@ -158,3 +165,21 @@ The `POST /api/visibility/preview` endpoint MUST be read-only and MUST evaluate - THEN Nextcloud MUST reject it before the controller runs - AND the endpoint MUST NOT be reachable as a public page +### Requirement: The rules dialog as LpZichtbaarheid draws it (REQ-CVUI-006) + +The dialog SHALL be titled "Who sees this widget?" under " · ", SHALL offer "If all rules match" and "If one rule matches" as choice cards, SHALL show one card per rule with its kind (Groups, Times, Period, Profile field), its value and Edit and delete buttons, then "Add rule", and SHALL end with "View as": a person and a moment, and a sentence that says whether that person sees the widget and why. + +#### Scenario: View as Sanne + +- **GIVEN** the rules ask for group KCC and Monday to Friday 08:00 to 17:00 +- **WHEN** the editor picks Sanne de Vries and Tuesday 13 October 10:00 +- **THEN** the sentence reads that Sanne sees this widget, because she is in KCC and the moment is within the times + +### Requirement: The dialog is in the widget's menu (REQ-CVUI-007) + +In edit mode the widget's menu SHALL hold "Who sees this widget?", which opens the dialog, so it is reachable by keyboard and not only by right-click. + +#### Scenario: From the menu + +- **WHEN** the editor opens the menu of the News widget and chooses Who sees this widget? +- **THEN** the dialog opens for that widget diff --git a/openspec/specs/conditional-visibility/screens.md b/openspec/specs/conditional-visibility/screens.md new file mode 100644 index 000000000..428adc8b7 --- /dev/null +++ b/openspec/specs/conditional-visibility/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpBeheerAnalyse https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAnalyse +- LpZichtbaarheid https://identity.conduction.nl/screens/board?id=launchpad/LpZichtbaarheid diff --git a/openspec/specs/conditional-visibility/spec.md b/openspec/specs/conditional-visibility/spec.md index 6c81ed135..972fc8484 100644 --- a/openspec/specs/conditional-visibility/spec.md +++ b/openspec/specs/conditional-visibility/spec.md @@ -10,9 +10,6 @@ Conditional visibility allows widget placements to be shown or hidden based on d ## Data Model - -@e2e exclude all scenarios test PHP service layer and DB — visibility evaluation is backend-only; no UI surface for rule editing in v1.0.5 - ### Conditional Rules (oc_launchpad_conditional_rules) - **id**: Auto-increment integer primary key - **widgetPlacementId**: Foreign key to oc_launchpad_widget_placements (INTEGER) @@ -51,7 +48,7 @@ NOTE: Date rules use camelCase keys (`startDate`, `endDate`). Both fields are op ### Requirement: Create Conditional Rule (REQ-VIS-001) -Users MUST be able to add conditional visibility rules to widget placements on dashboards they own. +Users MUST be able to add conditional visibility rules to widget placements on dashboards they own. The owner needs no administrator role: the shipped action matrix opens `rule.add-rule` to every user, and the route checks placement ownership before it writes (Ruben, 21 Nov 2026). An existing instance gets this from the action baseline repair step (revision 5). #### Scenario: Create a group-based inclusion rule - GIVEN user "alice" has widget placement id 10 on her dashboard @@ -79,7 +76,7 @@ Users MUST be able to add conditional visibility rules to widget placements on d ``` - THEN the system MUST create an exclusion rule that hides the widget when the current server time matches - AND `isInclude: false` MUST mean the widget is hidden when the rule matches -- NOTE: The current time comparison uses simple string comparison (`>=` and `<=`) and does NOT handle midnight-spanning windows correctly (startTime > endTime). +- NOTE: A window whose startTime lies after its endTime wraps around midnight. #### Scenario: Create a date-based inclusion rule - GIVEN widget placement id 10 on alice's dashboard @@ -110,7 +107,7 @@ Users MUST be able to add conditional visibility rules to widget placements on d - WHEN she sends POST /api/widgets/10/rules with body `{"ruleType": "weather", "ruleConfig": {}, "isInclude": true}` - THEN the system SHOULD return HTTP 400 with an error indicating the ruleType is invalid - AND only `group`, `time`, `date`, and `attribute` SHOULD be accepted -- NOTE: Rule type validation is NOT currently implemented -- any string value is accepted. Unknown rule types evaluate to `false` via the `default => false` case in `evaluateRule()`. +- NOTE: `RuleApiController::addRule()` and `updateRule()` refuse a ruleType outside `ConditionalRule::ALLOWED_TYPES` with 400 `invalid_argument` before anything is stored. #### Scenario: Create rule on another user's placement - GIVEN widget placement id 10 belongs to alice's dashboard @@ -142,7 +139,7 @@ Users MUST be able to retrieve all conditional rules for a widget placement they ### Requirement: Update Conditional Rule (REQ-VIS-003) -Users MUST be able to modify existing conditional rules on placements they own. +Users MUST be able to modify existing conditional rules on placements they own, without an administrator role, and a Nextcloud administrator on every placement (Ruben, 21 Nov 2026). The shipped action matrix opens `rule.update-rule` to every user; the route checks placement ownership before it writes, and the action baseline repair step (revision 7) opens it on an existing instance where the entry is still the pristine admin-only default. #### Scenario: Update rule configuration - GIVEN conditional rule id 5 with `ruleConfig: {"groups": ["marketing"]}` @@ -182,7 +179,7 @@ Users MUST be able to modify existing conditional rules on placements they own. ### Requirement: Delete Conditional Rule (REQ-VIS-004) -Users MUST be able to remove conditional rules from their widget placements. +Users MUST be able to remove conditional rules from their widget placements, without an administrator role, and a Nextcloud administrator on every placement (Ruben, 21 Nov 2026). `rule.delete-rule` is opened the same way as `rule.update-rule` (REQ-VIS-003). #### Scenario: Delete a rule - GIVEN widget placement id 10 has 3 conditional rules, including rule id 5 @@ -256,12 +253,12 @@ Time-based rules MUST show or hide widgets based on the current time of day usin - WHEN the dashboard is rendered - THEN the widget MUST be hidden -#### Scenario: Time window spanning midnight (KNOWN LIMITATION) +#### Scenario: Time window spanning midnight - GIVEN widget placement id 10 has a time inclusion rule with `startTime: "22:00", endTime: "06:00"` - AND the current server time is 02:00 - WHEN the dashboard is rendered - THEN the widget SHOULD be visible (the time window wraps around midnight) -- NOTE: The current implementation uses simple string comparison (`currentTime >= startTime && currentTime <= endTime`) which does NOT handle midnight-spanning windows. This is a known limitation. +- NOTE: When `startTime > endTime` the rule matches from startTime to midnight and from midnight to endTime. #### Scenario: Time evaluation uses server timezone (NOT configurable) - GIVEN a time rule with `startTime: "09:00", endTime: "17:00"` (no timezone field) @@ -419,6 +416,28 @@ The ConditionalService MUST evaluate visibility through a defined pipeline: isVi - THEN the system MUST return true without calling VisibilityChecker - AND the widget MUST always be displayed +### Requirement: Rules apply when a dashboard renders (REQ-VIS-013) + +The visibility rules MUST be applied every time a dashboard renders, for everyone who opens it: the dashboard reads (`GET /api/dashboards/active`, `GET /api/dashboard/{id}`), the public share page, the kiosk screen and an embed (launchpad#98, Ruben 21 Nov 2026). The rules are evaluated for the person viewing; a visitor without an account matches no group or attribute rule. A viewer MUST NOT receive a placement the rules hide for them. The owner and editors (any permission level other than `view_only`) MUST still receive it, marked `hiddenForViewers: true`, and the dashboard MUST show it dimmed with a "Hidden for viewers" badge so they can still edit it. Every other placement carries `hiddenForViewers: false`. + +#### Scenario: A viewer does not get a hidden widget +- GIVEN alice shares her dashboard with bob at `view_only` +- AND one of its widgets has an include rule for group "staff", which bob is not in +- WHEN bob opens the dashboard +- THEN the response MUST NOT contain that placement +- AND the dashboard MUST NOT render it + +#### Scenario: The owner sees a hidden widget dimmed +- GIVEN the same widget on alice's dashboard, and alice is not in group "staff" +- WHEN alice opens her dashboard +- THEN the placement MUST be in the response with `hiddenForViewers: true` +- AND the dashboard MUST render it dimmed with the badge "Hidden for viewers" + +#### Scenario: A public share leaves a hidden widget out +- GIVEN alice made a public link for the dashboard +- WHEN a visitor without an account opens the link +- THEN the placement with the group rule MUST NOT be in the rendered payload + ### Requirement: Rule Cascade Deletion (REQ-VIS-011) When a widget placement is deleted, all its associated conditional rules MUST also be deleted. @@ -428,7 +447,7 @@ When a widget placement is deleted, all its associated conditional rules MUST al - WHEN placement 10 is deleted via DELETE /api/widgets/10 - THEN all 5 conditional rules MUST also be deleted - AND no orphaned rules MUST remain in the database -- NOTE: `PlacementService::removePlacement()` does NOT explicitly cascade-delete conditional rules. This depends on database-level cascade constraints. +- NOTE: `WidgetPlacementMapper::delete()` and `deleteByDashboardId()` delete the rules first; the rules table has no foreign key. #### Scenario: Delete dashboard cascades to placements and rules - GIVEN dashboard id 5 has 3 placements, each with 2 conditional rules @@ -436,12 +455,51 @@ When a widget placement is deleted, all its associated conditional rules MUST al - THEN all 3 placements and all 6 conditional rules MUST be deleted - NOTE: `DashboardService::deleteDashboard()` deletes placements via `placementMapper->deleteByDashboardId()` but does not explicitly handle conditional rules. +### Requirement: Admin overview of widgets with visibility rules (REQ-VIS-012) + +The admin settings tab "Versioning and audit" MUST list every widget placement, across all dashboards, that has at least one conditional visibility rule. Each row MUST show the dashboard name, the widget type, the number of rules and the split into include and exclude rules. The list MUST come from `GET /api/admin/widgets/with-rules` (`AdminWidgetRulesController::index`), which only an administrator of the LaunchPad admin settings may call. Synced from the archived change `2026-06-14-refactor-launchpad-ia-alignment` ("Admin Versioning & Audit Tab"); board LpBeheerAnalyse. + +#### Scenario: The overview lists rule-bearing widgets +- GIVEN dashboards in the system hold 12 widget placements with at least one conditional rule +- WHEN an administrator opens the "Versioning and audit" tab in the LaunchPad admin settings +- THEN all 12 placements MUST be listed under "Widgets with visibility rules" +- AND each row MUST show the dashboard name, widget type, rule count, include count and exclude count + +#### Scenario: No rules yet +- GIVEN no widget placement has a conditional rule +- WHEN an administrator opens the tab +- THEN the overview MUST show the empty state "No visibility rules yet" + +#### Scenario: A non-administrator cannot read the overview +- GIVEN Pieter is not an administrator +- WHEN he calls `GET /api/admin/widgets/with-rules` +- THEN the request MUST be refused with HTTP 403 +- AND no rule data MUST be returned + +### Requirement: All or one rule must match (REQ-VIS-014) + +A widget placement SHALL store how its include rules combine in `ruleMatch`: `any` (one include rule that matches is enough, the behaviour of REQ-VIS-009) or `all` (every include rule must match). A placement without a stored mode SHALL read as `any`, so every existing dashboard stays as it is. Exclude rules SHALL keep hiding the widget when any of them matches, in both modes. The mode SHALL be evaluated in `VisibilityChecker`, the one place the rules are combined, at render time and in the preview. `PUT /api/widgets/{placementId}` SHALL accept only `any` or `all` (HTTP 400 otherwise), and only from the dashboard owner or an administrator (HTTP 403 otherwise). Copying a dashboard, a template and an export SHALL carry the mode. + +#### Scenario: All rules must match + +- **GIVEN** widget placement 10 has `ruleMatch: all` and two include rules: group KCC and Monday to Friday 08:00 to 17:00 +- **AND** the user is in KCC and it is Saturday 10:00 +- **WHEN** the dashboard is rendered +- **THEN** the widget MUST be hidden, because the time rule does not match + +#### Scenario: One rule is enough + +- **GIVEN** the same placement with `ruleMatch: any` +- **AND** the user is in KCC and it is Saturday 10:00 +- **WHEN** the dashboard is rendered +- **THEN** the widget MUST be visible, because the group rule matches + ## Non-Functional Requirements - **Performance**: Rule evaluation for a single placement with up to 10 rules MUST complete within 50ms. Total evaluation for a dashboard with 30 placements and 100 rules MUST complete within 500ms. - **Timezone handling**: Time-based rules currently use the server's default timezone (`new DateTime()`). A `timezone` config field is NOT currently supported. Future versions SHOULD add timezone support via PHP's DateTimeZone. - **Data integrity**: Deleting a widget placement MUST cascade-delete all its conditional rules. Rules MUST NOT reference non-existent placements. -- **Accessibility**: Conditional visibility MUST NOT affect the accessibility tree for visible widgets. Hidden widgets MUST be fully removed from the DOM, not just hidden via CSS. +- **Accessibility**: Conditional visibility MUST NOT affect the accessibility tree for visible widgets. For a viewer, hidden widgets MUST be fully removed from the DOM, not just hidden via CSS. For the owner and editors a hidden widget stays in the DOM, dimmed, and its "Hidden for viewers" badge is text, so a screen reader announces it (REQ-VIS-013). - **Localization**: Rule type labels and validation messages MUST support English and Dutch. ### Current Implementation Status @@ -451,19 +509,17 @@ When a widget placement is deleted, all its associated conditional rules MUST al - REQ-VIS-002 (List Conditional Rules): `ConditionalService::getRules()` returns rules by placement ID with ownership check. - REQ-VIS-003 (Update Conditional Rule): `ConditionalService::updateRule()` handles partial updates. `RuleApiController::updateRule()` exposes PUT /api/rules/{ruleId}. - REQ-VIS-004 (Delete Conditional Rule): `ConditionalService::deleteRule()` removes rules. `RuleApiController::deleteRule()` exposes DELETE /api/rules/{ruleId}. +- REQ-VIS-001..004 access: `PermissionService::verifyPlacementOwnership()` lets the dashboard owner and a Nextcloud administrator through, before any rule is read or written. - REQ-VIS-005 (Group-Based Rule Evaluation): `RuleEvaluatorService::evaluateGroupRule()` uses `IGroupManager::getUserGroupIds()` and `array_intersect()`. - REQ-VIS-006 (Time-Based Rule Evaluation): `RuleEvaluatorService::evaluateTimeRule()` checks day-of-week filter and time range. Uses `strtolower($now->format('D'))` for day abbreviations. - REQ-VIS-007 (Date-Based Rule Evaluation): `RuleEvaluatorService::evaluateDateRule()` supports optional `startDate` and `endDate`. - REQ-VIS-008 (Attribute-Based Rule Evaluation): `RuleEvaluatorService::evaluateAttributeRule()` delegates to `UserAttributeResolver`. Supports operators: `equals`, `not_equals`, `contains`, `starts_with`, `ends_with`. - REQ-VIS-009 (Multiple Rule Combination): `VisibilityChecker::checkRules()` separates include/exclude rules. Include uses OR, exclude uses AND. - REQ-VIS-010 (Visibility Evaluation Pipeline): `ConditionalService::isWidgetVisible()` checks `isVisible` flag first, then loads rules, then delegates to `VisibilityChecker`. +- REQ-VIS-013 (Rules apply when a dashboard renders): `ConditionalService::visiblePlacements()` filters or marks the placements of `DashboardApiController::getActive()` / `show()`, `PublicShareController::show()`, `KioskService::renderPlaylist()` and `EmbedRenderService`. **Not yet implemented:** -- REQ-VIS-001 ruleType validation: No server-side validation for ruleType values. -- REQ-VIS-003/004 ownership verification: `updateRule()` and `deleteRule()` in `RuleApiController` do NOT verify placement ownership. -- REQ-VIS-006 midnight-spanning windows: Simple string comparison does not handle time windows spanning midnight. - REQ-VIS-006 timezone support: No `timezone` field support. -- REQ-VIS-011 cascade delete: `PlacementService::removePlacement()` does not explicitly cascade-delete conditional rules. - Frontend UI: No Vue component exists for creating or managing conditional rules. ### Standards & References diff --git a/openspec/specs/confluence-html-import/screens.md b/openspec/specs/confluence-html-import/screens.md new file mode 100644 index 000000000..1a9099128 --- /dev/null +++ b/openspec/specs/confluence-html-import/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerOnderhoud https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerOnderhoud diff --git a/openspec/specs/confluence-html-import/spec.md b/openspec/specs/confluence-html-import/spec.md index c1964f6b0..c0dd09e89 100644 --- a/openspec/specs/confluence-html-import/spec.md +++ b/openspec/specs/confluence-html-import/spec.md @@ -42,9 +42,6 @@ service. ## Requirements - -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: REQ-CFLI-001 Archive structure parsing The system MUST parse a Confluence HTML Export ZIP archive and extract @@ -339,6 +336,8 @@ Confluence page ID). ### Requirement: REQ-CFLI-011 CLI command for headless import +@e2e exclude console command (`occ launchpad:import:confluence`) with no HTTP or UI surface; tests/Unit/Command/ImportConfluenceCommandGoldenTest.php::testConfluenceImportOutput pins the summary line, exit codes, `File not found: …`, `Parent path not found: …`, the --parent-path → parent UUID hand-off and the --dry-run line (against a mocked import service), and tests/Unit/Command/ConfluenceImportRequestTest.php::testGivenOptionsAreRead pins the option parsing + The system MUST expose a Nextcloud OCC command `php occ launchpad:import:confluence` for imports via CLI / cron, with options for the input file, an optional parent path, the importing user, and a dry-run flag. diff --git a/openspec/specs/container-widget/screens.md b/openspec/specs/container-widget/screens.md new file mode 100644 index 000000000..8ce5b3fa4 --- /dev/null +++ b/openspec/specs/container-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement diff --git a/openspec/specs/container-widget/spec.md b/openspec/specs/container-widget/spec.md index a75afa972..a706f82e3 100644 --- a/openspec/specs/container-widget/spec.md +++ b/openspec/specs/container-widget/spec.md @@ -35,9 +35,6 @@ The server enforces a maximum container nesting depth of **3 levels** (REQ-CONT- ## Requirements - -@e2e exclude container-widget API and nested-grid scenarios are backend / JS composable — inner GridStack instances cannot be reliably driven headlessly - ### Requirement: REQ-CONT-001 Container widget type registered The widget registry MUST include a `container` widget type whose `defaultContent` is `{placements: [], backgroundColor: 'transparent', padding: 'medium', title: ''}`. The container widget MUST be selectable from the unified Add Custom Widget picker (REQ-WDG-010 + REQ-WDG-019 EXPECTED_TYPES). @@ -98,6 +95,8 @@ In edit mode, the container's inner grid MUST become editable independently of t #### Scenario: Add a child widget inside a container +@e2e exclude never built: no control adds a child to a container. ContainerWidget.vue renders no add affordance, WidgetRenderer.vue passes the container neither `editMode` nor an `update:content` listener, and CnContainerWidgetForm.vue says so in a NOTE ("there is currently no way to add a widget to a container"); `git log --all -S` for an add-to-container identifier returns nothing. The persist path that exists is pinned only by src/components/Widgets/Renderers/__tests__/ContainerWidget.persist.spec.js. + - **GIVEN** a container in edit mode with two child widgets - **WHEN** the user opens the container's add-widget affordance and adds a label widget - **THEN** the inner grid MUST gain a third child placement @@ -124,17 +123,71 @@ Containers MAY hold containers, but the maximum nesting depth is **3 levels**. T ### Requirement: REQ-CONT-007 Form fields -The container's add/edit form MUST collect three fields, all optional: +The container's add and edit form MUST collect four fields, all optional: -- `backgroundColor` — hex colour (NcColorPicker), default `'transparent'` -- `padding` — enum `'none' | 'small' | 'medium' | 'large'` (NcSelect), default `'medium'` -- `title` — string (NcTextField), default `''` (no title rendered when empty) +- `backgroundColor`: hex colour (NcColorPicker), default `'transparent'` +- `padding`: enum `'none' | 'small' | 'medium' | 'large'` (NcSelect), default `'medium'` +- `title`: string (NcTextField), default `''` (no title rendered when empty) +- `sortBy`: enum `'manual' | 'alphabetical' | 'most-used' | 'last-used' | 'random'` (NcSelect with an input label), default `'manual'` -Children are NOT managed via this form — they're added/removed/moved via the inner grid's own affordances when the container is in edit mode. +Children are NOT managed via this form. They are added, removed and moved through the inner grid's own affordances when the container is in edit mode. #### Scenario: Form has three fields - **GIVEN** the container form is mounted - **WHEN** rendered -- **THEN** exactly three input controls MUST be present: backgroundColor picker, padding select, title text field +- **THEN** the three communal input controls MUST be present: background colour picker, padding select and title text field +- **AND** LaunchPad's form MUST add exactly one more control, the "Sort tiles" select - **AND** no "manage children" UI MUST be in the form + +### Requirement: A container sorts its tiles when viewed (REQ-TSO-001) + +In view mode a container MUST order its children by its `sortBy` setting and reflow them row by row into its inner grid, keeping each child's size. It MUST NOT write the new positions back. In edit mode it MUST show the stored positions. + +#### Scenario: Alphabetical order + +- **GIVEN** a container "Applicaties" on Pieter's dashboard with tiles "Zaaksysteem", "Agenda" and "Mail" placed in that order, and "Sort tiles" set to "Alphabetically" +- **WHEN** Pieter opens the Workspace page +- **THEN** he sees "Agenda", "Mail", "Zaaksysteem" from left to right + +#### Scenario: Back to the author's layout + +- **GIVEN** the same container sorted alphabetically +- **WHEN** the author sets "Sort tiles" to "By hand" and saves +- **THEN** the tiles show in their stored order "Zaaksysteem", "Agenda", "Mail" + +### Requirement: Most used and last used read the viewer's own browser (REQ-TSO-002) + +Most used and last used MUST order tiles by counts and times kept in the viewer's browser storage, which MUST NOT be sent to the server. Tiles with equal counts MUST fall back to alphabetical order. When browser storage is unavailable the container MUST show the stored order without an error. + +#### Scenario: A daily app moves to the front + +- **GIVEN** a container sorted "Most used" with tiles "Agenda", "Mail" and "Zaaksysteem", and Pieter has never clicked any of them +- **WHEN** he opens "Zaaksysteem" three times and reloads the Workspace page +- **THEN** "Zaaksysteem" is the first tile in the container + +#### Scenario: Counts stay on the device + +- **GIVEN** Pieter clicks tiles in a container sorted "Most used" +- **WHEN** the clicks are recorded +- **THEN** no request carries his per-tile counts, and the only server call per click is the existing anonymous `POST /api/tile-click/{placementId}` + +### Requirement: Viewers can forget their usage (REQ-TSO-003) + +A container sorted by most used or last used MUST offer "Forget my usage" in its menu, which clears the viewer's local counts for that container's tiles. + +#### Scenario: Forget my usage + +- **GIVEN** "Zaaksysteem" leads Pieter's "Most used" container +- **WHEN** he chooses "Forget my usage" in the container menu +- **THEN** the tiles show in alphabetical order until he clicks one again + +### Requirement: Random order holds for the page load (REQ-TSO-004) + +Random order MUST shuffle once per page load and keep that order until the page is reloaded. + +#### Scenario: No jumping tiles + +- **GIVEN** a container sorted "At random" +- **WHEN** Pieter opens the Workspace page and a widget elsewhere refreshes its data +- **THEN** the tile order in the container stays the same until he reloads diff --git a/openspec/specs/cross-widget-filter/spec.md b/openspec/specs/cross-widget-filter/spec.md new file mode 100644 index 000000000..2b71a014e --- /dev/null +++ b/openspec/specs/cross-widget-filter/spec.md @@ -0,0 +1,531 @@ +--- +capability: cross-widget-filter +status: done +--- + +# Cross-Widget Filter Specification + +## Purpose + +This capability adds a shared filter bus to launchpad dashboards, allowing widgets to publish filter events (on click) and other widgets to consume them (on render). Filter state is persisted in the URL and optionally logged for aggregate telemetry. A dashboard with its filters is the unit a user keeps and shares; there are no saved views (REQ-CWF-009 was removed by decision on 22 Nov 2026). + +## Requirements + +### Requirement: REQ-CWF-001 Widget click publishes to the filter bus + +The dashboard SHALL detect clicks on chartable elements of bus-aware widgets and SHALL publish the corresponding filter clause to the bus, identifying the publishing widget so the click can be visually echoed back. + +#### Scenario: Bar chart click publishes a clause + +- **GIVEN** a bar chart widget A on a dashboard, with a `publishes` declaration of `{dimension: "gemeenteCode", operator: "eq", fromField: "category"}` +- **WHEN** the user clicks the bar labelled "Zeist" (gemeenteCode `GM0355`) +- **THEN** a filter clause `{dimension: "gemeenteCode", operator: "eq", value: "GM0355", source: "widgetClick", sourceWidgetId: A}` SHALL be added to the bus + +#### Scenario: Widget without publishes declaration does nothing + +- **GIVEN** a widget WITHOUT a `publishes` declaration +- **WHEN** the user clicks an element +- **THEN** no clause SHALL be added to the bus and the click MAY perform a widget-local action (e.g. open detail modal) + +#### Scenario: Clicking the same clause again removes it (toggle) + +- **GIVEN** the same bar is clicked a second time +- **WHEN** the bus already contains that exact clause sourced from the same widget +- **THEN** the clause SHALL be removed (toggle behaviour) and the URL SHALL be updated to reflect the cleared state + +--- + +### Requirement: REQ-CWF-002 All consuming widgets re-render on filter change + +The system SHALL recompute and re-render every widget whose `consumes` declaration matches one or more active filter dimensions, passing the merged filter context as a prop, within 300 ms of the click. + +#### Scenario: Selective widget re-render + +- **GIVEN** three widgets on a dashboard: A (publishes gemeenteCode), B (consumes gemeenteCode), C (does not consume gemeenteCode) +- **WHEN** the user clicks "Zeist" on A +- **THEN** A SHALL echo the selection visually, B SHALL re-render with `gemeenteCode=GM0355` applied, and C SHALL NOT re-render + +#### Scenario: New widget receives current filter state on mount + +- **GIVEN** a widget whose `consumes` declaration includes a dimension currently in the bus +- **WHEN** the widget mounts (or is dragged onto the dashboard) +- **THEN** it SHALL receive the current bus state on first render and SHALL NOT show a flash of unfiltered content + +--- + +### Requirement: REQ-CWF-003 URL encoding makes filtered views bookmarkable + +The system SHALL serialise the active filter state into a URL query parameter and SHALL restore the filter state on initial load when the parameter is present, producing the same view the URL-issuer saw. + +#### Scenario: URL encodes active filter state + +- **GIVEN** a dashboard with two active clauses (`gemeenteCode=GM0355`, `status=open`) +- **WHEN** the URL is copied +- **THEN** it SHALL contain a `?f=...` parameter encoding both clauses + +#### Scenario: Loading a bookmarked URL restores filter state + +- **GIVEN** that URL is pasted into a second browser by a second user with read access to the dashboard +- **WHEN** the page loads +- **THEN** both clauses SHALL be restored with `source=urlBootstrap` and the visible widgets SHALL reflect the filtered numbers without any user action + +#### Scenario: Malformed URL parameter does not crash + +- **GIVEN** a URL whose `f` parameter is malformed +- **WHEN** the page loads +- **THEN** the dashboard SHALL render with an empty filter state and SHALL log a single warning (no error toast on the user) + +--- + +### Requirement: REQ-CWF-004 Drill-down hierarchies update breadcrumb and descendant filters + +When a click publishes a clause for a dimension that is part of a `hierarchy_descriptor`, the system SHALL update the breadcrumb UI to show the active path and SHALL clear any descendant-level clauses from the bus before applying the new clause. The breadcrumb SHALL show one step per active level of each hierarchy, broadest first, as the level's label in the reader's language and its value ("Provincie PV26 > Gemeente GM0355 > Wijk WK035501"); each step above the deepest SHALL go back up to that level. A chart click names only the field the chart groups by, so the ancestor values SHALL be read from the clicked row when it carries them, and otherwise from one record of the clicked category in the chart's register and schema, in the record's field named like the ancestor's dimension; an ancestor that cannot be read is skipped with a console warning. + +#### Scenario: Drilling up clears descendant filters + +- **GIVEN** the `nl-administrative` hierarchy is active on a dashboard, with current clauses `gemeenteCode=GM0355` and `wijkCode=WK0355001` +- **WHEN** the user clicks "Provincie Utrecht" on a province-level widget (publishing `provincieCode=PV09`) +- **THEN** the bus SHALL contain only `{provincieCode=PV09}` (gemeente and wijk are cleared because they are descendants) and the breadcrumb SHALL show "Provincie Utrecht" + +#### Scenario: Drilling down infers ancestor filters + +- **GIVEN** the same dashboard with no active filters +- **WHEN** the user clicks a wijk on a wijk-level widget (publishing `wijkCode=WK0355001`) +- **THEN** the bus SHALL contain `{wijkCode=WK0355001}` AND the hierarchy resolver SHALL infer and add ancestor clauses (`gemeenteCode=GM0355`, `provincieCode=PV09`) marked with `source=parentScope` so the breadcrumb shows the full path + +#### Scenario: Going back up the breadcrumb clears the levels below + +- **GIVEN** the breadcrumb shows "Provincie PV26 > Gemeente GM0355 > Wijk WK035501" after a wijk click +- **WHEN** the user chooses the "Provincie PV26" step +- **THEN** the gemeente and wijk clauses SHALL be cleared (pinned ones stay), the provincie clause SHALL stay as the user's own (`source=userExplicit`), the breadcrumb SHALL show "Provincie PV26", and a later click on a wijk in another gemeente SHALL replace the provincie and gemeente with that wijk's ancestors + +#### Scenario: Permission-denied on hierarchy level + +- **GIVEN** a click on a hierarchy level the user has no permission for (e.g. a gemeenteCode their role doesn't expose) +- **WHEN** the click is processed +- **THEN** the publication SHALL be rejected, the widget SHALL show a tooltip explaining "no access to this scope", and the bus SHALL NOT be mutated + +--- + +### Requirement: REQ-CWF-005 Filter conflict resolution is last-write-wins per dimension + +When a new clause is published for a dimension that already has an active clause from a different source or operator, the system SHALL replace (not append) the existing clause and SHALL show a one-line audit tooltip indicating which previous clause was replaced. + +#### Scenario: Widget-click replaces widget-click + +- **GIVEN** an active clause `{gemeenteCode=GM0355, source=widgetClick}` from widget A +- **WHEN** widget B publishes `{gemeenteCode=GM0344, source=widgetClick}` +- **THEN** the bus SHALL contain only the new clause from B, widget A SHALL update its visual echo to deselect GM0355, and a brief toast SHALL indicate "Gemeente filter changed from Zeist to Houten" + +#### Scenario: Widget-click silently replaces URL-bootstrap + +- **GIVEN** an active clause sourced from `urlBootstrap` +- **WHEN** a widget-click clause for the same dimension arrives +- **THEN** the widget-click clause SHALL replace the URL-bootstrap one with no toast (URL bootstrap is treated as a transient initial state, not a deliberate user choice) + +#### Scenario: Pinned clause cannot be replaced + +- **GIVEN** an active `pinned: true` clause +- **WHEN** a clause for the same dimension arrives from any source +- **THEN** the pinned clause SHALL NOT be replaced and the new publication SHALL be silently dropped with a one-line console log (so a developer can see why their click did not stick) + +--- + +### Requirement: REQ-CWF-006 Reset filters clears all non-pinned clauses + +The dashboard SHALL expose a "Reset filters" action that clears every non-pinned clause from the bus and SHALL update the URL to remove the `f` parameter. + +#### Scenario: Reset clears non-pinned clauses, keeps pinned + +- **GIVEN** a dashboard with five active clauses, one of which is pinned +- **WHEN** the user invokes "Reset filters" +- **THEN** four clauses SHALL be removed, the pinned clause SHALL remain, the URL SHALL be updated, and every consuming widget SHALL re-render with the reduced filter context + +#### Scenario: Reset on empty bus is a no-op + +- **GIVEN** a dashboard with no active clauses +- **WHEN** "Reset filters" is invoked +- **THEN** the action SHALL be a no-op (no URL change, no widget re-render, no telemetry event) so accidental double-clicks do not produce noise + +--- + +### Requirement: REQ-CWF-007 Filter stack UI shows every active clause with its source + +The dashboard SHALL render a compact "Active filters" panel listing every active clause with its dimension label, value, source widget (when applicable), and an individual remove-action; the panel SHALL collapse when empty. + +#### Scenario: Active filters panel shows all clauses with source + +- **GIVEN** three active clauses (one from a widget click, one from URL bootstrap, one pinned by the org) +- **WHEN** the panel is rendered +- **THEN** it SHALL show three chips with distinct visual treatment per source (e.g. widget-click chips show the source widget's name, pinned chips show a lock icon and have no remove-action) + +#### Scenario: Remove single clause from panel + +- **GIVEN** the user clicks the remove-action on a single chip +- **WHEN** the click is processed +- **THEN** only that clause SHALL be removed, the URL SHALL be updated, and the originating widget (if any) SHALL update its visual echo to deselect + +--- + +### Requirement: REQ-CWF-008 Widget manifest declares publishes/consumes; dashboard validates compatibility + +The widget loader SHALL read `publishes` and `consumes` from the widget manifest and the dashboard SHALL refuse to render a widget whose manifest declares dimensions inconsistent with the dashboard's hierarchy descriptors, surfacing the mismatch in the widget config UI. + +#### Scenario: Consuming dimension not in dashboard hierarchies + +- **GIVEN** a widget manifest declaring `consumes: [{dimension: "wijkCode"}]` on a dashboard whose hierarchy descriptors do not include `wijkCode` +- **WHEN** the widget is added to the dashboard +- **THEN** the widget config UI SHALL show a non-fatal warning ("This widget consumes 'wijkCode' but no hierarchy on this dashboard publishes it") and the widget SHALL render as a non-bus-participant + +#### Scenario: Publishing from missing field + +- **GIVEN** a widget manifest declaring `publishes: [{dimension: "gemeenteCode", fromField: "missingField"}]` where `missingField` is not in the widget's data shape +- **WHEN** the widget renders +- **THEN** the dashboard SHALL log a manifest-validation error and disable bus participation for that widget (no clicks publish) + +--- + +### Requirement: REQ-CWF-010 Telemetry of filter usage is opt-in and aggregated + +When org-level telemetry is enabled, the system SHALL persist `filter_event` rows for `apply` / `reset` / `bookmark` / `share` events with no PII beyond the user id, and SHALL expose an aggregate report ("most-used drill-down paths per dashboard") to dashboard owners. + +#### Scenario: Telemetry disabled (default) + +- **GIVEN** telemetry is disabled (default) +- **WHEN** any filter event occurs +- **THEN** no `filter_event` row SHALL be written + +#### Scenario: Filter apply event is recorded + +- **GIVEN** telemetry is enabled and a user clicks a wijk on widget A +- **WHEN** the click is processed +- **THEN** a `filter_event` row SHALL be written with `eventType=apply`, the wijk clause delta, `widgetId=A`, and the user id, AND the URL/share event SHALL NOT be conflated with the click event (two separate rows) + +#### Scenario: Bookmark event on page load + +- **GIVEN** telemetry is enabled and an authenticated user opens a bookmarked URL +- **WHEN** the page loads +- **THEN** exactly one row SHALL be written with `eventType=bookmark` and the full clause set as the delta + +--- + +### Requirement: REQ-CWF-011 A dashboard stores its hierarchies + +A dashboard SHALL store its `hierarchies` (a list of hierarchy_descriptor objects) and return them on every read of the dashboard, so the filter bus of every viewer joins widgets on them without any per-page configuration. An owner or editor SHALL pick the hierarchies in the dashboard settings from the shipped presets; the `nl-administrative` preset (province > municipality > district > neighbourhood: `provincieCode` > `gemeenteCode` > `wijkCode` > `buurtCode`) SHALL be one of them. The dashboard API SHALL validate every descriptor before it stores it. + +#### Scenario: An owner picks the nl-administrative preset + +- **GIVEN** a dashboard without hierarchies and its owner in the dashboard settings +- **WHEN** the owner picks the "Dutch administrative areas" preset and saves +- **THEN** the dashboard SHALL store the `nl-administrative` descriptor with the levels `provincieCode`, `gemeenteCode`, `wijkCode` and `buurtCode`, every later read of the dashboard SHALL return it, and the dashboard's filter bus SHALL be rebuilt on it + +#### Scenario: Stored hierarchies put consuming widgets on the bus + +- **GIVEN** a dashboard that stores the `nl-administrative` hierarchy, a chart that publishes `gemeenteCode` and a chart that consumes `gemeenteCode` +- **WHEN** a viewer opens the dashboard and clicks a gemeente on the publishing chart +- **THEN** the consuming chart SHALL refetch with the clicked gemeente as its filter, with no hierarchy added to the dashboard anywhere but in its stored settings + +#### Scenario: A malformed descriptor is refused + +- **GIVEN** an update whose `hierarchies` is not a list, or holds a descriptor without an `id`, without levels, with a level without a `dimension`, with a dimension used twice, or with a `parentDimension` that is not the level above +- **WHEN** the update is sent to the dashboard API +- **THEN** the API SHALL answer 400 with a message naming the problem and SHALL store nothing of the update + +#### Scenario: A viewer cannot change the hierarchies + +- **GIVEN** a user who may view but not edit a dashboard +- **WHEN** that user sends an update with `hierarchies` +- **THEN** the API SHALL refuse it as it refuses a layout change, and the stored hierarchies SHALL stay as they were + +#### Scenario: Copies keep the hierarchies + +- **GIVEN** a dashboard or admin template that stores the `nl-administrative` hierarchy +- **WHEN** a user forks it as a personal copy, a dashboard is made from the template, or the dashboard is exported and imported again +- **THEN** the copy SHALL store the same hierarchies, so its filter bus joins widgets as the original's does; a malformed list in an imported archive SHALL be left out without failing the import + +#### Scenario: Clearing the hierarchies + +- **GIVEN** a dashboard that stores the `nl-administrative` hierarchy +- **WHEN** the owner removes it in the settings and saves (an update with `hierarchies: []`) +- **THEN** the dashboard SHALL store no hierarchies, reads SHALL return `hierarchies: []`, and widgets that consume a hierarchy dimension SHALL leave the bus with the REQ-CWF-008 warning + +--- + +## Data Model + +### dashboard_filter_state + +Holds the active filter set for a dashboard view. The URL is the system of record; the shape is not stored in the register. + +- `dashboardId` (UUID) — references a dashboard +- `filters` (array of filter_clause objects) — active clauses +- `appliedAt` (ISO timestamp) — for telemetry + +#### Seed Data + +```json +{ + "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", + "filters": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "value": "GM0355", + "source": "widgetClick", + "sourceWidgetId": "w-chart-gemeenten" + }, + { + "dimension": "status", + "operator": "eq", + "value": "open", + "source": "widgetClick", + "sourceWidgetId": "w-chip-status" + }, + { + "dimension": "ageInDays", + "operator": "gte", + "value": 42, + "source": "userExplicit", + "pinned": true + } + ], + "appliedAt": "2026-05-22T14:35:00Z" +} +``` + +### filter_clause + +Describes one active filter. Keyed in compact form for URL encoding as `{d, o, v, s, w, p}`. + +- `dimension` (string, e.g. `gemeenteCode`, `wijkCode`, `period.month`) — the filtered attribute +- `operator` (enum: `eq`, `in`, `between`, `gte`, `lte`, `contains`, `notNull`) — comparison operator +- `value` (scalar, array, or `[low, high]` tuple) — depends on operator; never stored in telemetry +- `source` (enum: `userExplicit`, `widgetClick`, `urlBootstrap`, `savedView`, `parentScope`) — origin; `savedView` is no longer written but still decodes, so a link copied while saved views existed keeps its filters +- `sourceWidgetId` (UUID, nullable) — set when `source=widgetClick` +- `pinned` (boolean, default false) — pinned clauses survive "Reset filters" + +#### Seed Data + +```json +[ + { + "dimension": "gemeenteCode", + "operator": "eq", + "value": "GM0355", + "source": "widgetClick", + "sourceWidgetId": "w-chart-gemeenten" + }, + { + "dimension": "wijkCode", + "operator": "in", + "value": ["WK0355001", "WK0355002"], + "source": "widgetClick", + "sourceWidgetId": "w-map-wijken" + }, + { + "dimension": "ageInDays", + "operator": "gte", + "value": 42, + "source": "userExplicit", + "pinned": true + } +] +``` + +### dimension_descriptor + +Lives in the widget manifest and declares what a widget can publish and consume. + +- `publishes` (array of objects) — describes what a click on a particular column/series/cell publishes + - `dimension` (string) — the dimension published + - `operator` (enum) — typically `eq` for categorical clicks, can be `between` for range selections + - `fromField` (string) — the data field that supplies the value (e.g. `category`, `date`) +- `consumes` (array of objects) — describes which incoming dimensions narrow this widget's query + - `dimension` (string) — the dimension consumed + - `operator` (enum) — filtering operator the widget applies + - `intoFilter` (string, nullable) — the parameter name to pass to the data source (e.g. `_filter[gemeenteCode]`) +- `hierarchies` (array of hierarchy_descriptor objects) — see below + +#### Seed Data + +```json +{ + "publishes": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "fromField": "category" + } + ], + "consumes": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "intoFilter": "_filter[gemeenteCode]" + }, + { + "dimension": "status", + "operator": "eq", + "intoFilter": "_filter[status]" + } + ], + "hierarchies": [ + { + "id": "nl-administrative", + "levels": [ + { + "dimension": "provincieCode", + "label": "Provincie" + }, + { + "dimension": "gemeenteCode", + "label": "Gemeente", + "parentDimension": "provincieCode" + }, + { + "dimension": "wijkCode", + "label": "Wijk", + "parentDimension": "gemeenteCode" + } + ] + } + ] +} +``` + +### hierarchy_descriptor + +Declares a drill-down chain for inferring ancestor and descendant relationships. + +- `id` (string, e.g. `nl-administrative`, `temporal-iso8601`) — unique identifier +- `levels` (ordered array) — hierarchy levels from broadest to finest + - `dimension` (string) — the dimension at this level + - `label` (string, i18n key) — human-readable label for breadcrumb + - `parentDimension` (string, nullable) — the dimension that is the parent level + +#### Seed Data + +```json +[ + { + "id": "nl-administrative", + "levels": [ + { + "dimension": "provincieCode", + "label": "hierarchy.level.province", + "parentDimension": null + }, + { + "dimension": "gemeenteCode", + "label": "hierarchy.level.municipality", + "parentDimension": "provincieCode" + }, + { + "dimension": "wijkCode", + "label": "hierarchy.level.district", + "parentDimension": "gemeenteCode" + }, + { + "dimension": "buurtCode", + "label": "hierarchy.level.neighbourhood", + "parentDimension": "wijkCode" + } + ] + }, + { + "id": "temporal-iso8601", + "levels": [ + { + "dimension": "period.year", + "label": "hierarchy.level.year" + }, + { + "dimension": "period.quarter", + "label": "hierarchy.level.quarter", + "parentDimension": "period.year" + }, + { + "dimension": "period.month", + "label": "hierarchy.level.month", + "parentDimension": "period.quarter" + }, + { + "dimension": "period.week", + "label": "hierarchy.level.week", + "parentDimension": "period.month" + } + ] + } +] +``` + +### filter_event + +Telemetry row written when an opt-in dashboard has telemetry enabled (org-level setting, default off). Records dimension and operator changes, not filter values (which may be PII). + +- `id` (UUID) — primary key +- `dashboardId` (UUID) — references the dashboard +- `userId` (UUID) — authenticated user +- `widgetId` (UUID, nullable) — set for widget-click events +- `eventType` (enum: `apply`, `reset`, `bookmark`, `share`) — event classification +- `filterDelta` (array of filter_clause objects) — the clauses added/removed by this event (no values) +- `timestamp` (ISO timestamp) — when the event occurred + +#### Seed Data + +```json +[ + { + "id": "fe-001", + "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", + "userId": "u-caseworker-01", + "widgetId": "w-chart-gemeenten", + "eventType": "apply", + "filterDelta": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "source": "widgetClick", + "sourceWidgetId": "w-chart-gemeenten" + } + ], + "timestamp": "2026-05-22T14:35:00Z" + }, + { + "id": "fe-002", + "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", + "userId": "u-caseworker-01", + "widgetId": "w-map-wijken", + "eventType": "apply", + "filterDelta": [ + { + "dimension": "wijkCode", + "operator": "eq", + "source": "widgetClick", + "sourceWidgetId": "w-map-wijken" + } + ], + "timestamp": "2026-05-22T14:35:45Z" + }, + { + "id": "fe-003", + "dashboardId": "d1a2b3c4-5678-90ab-cdef-1234567890ab", + "userId": "u-caseworker-02", + "widgetId": null, + "eventType": "bookmark", + "filterDelta": [ + { + "dimension": "gemeenteCode", + "operator": "eq", + "source": "urlBootstrap" + }, + { + "dimension": "status", + "operator": "eq", + "source": "urlBootstrap" + } + ], + "timestamp": "2026-05-22T15:10:00Z" + } +] +``` diff --git a/openspec/specs/dashboard-acknowledgements/screens.md b/openspec/specs/dashboard-acknowledgements/screens.md new file mode 100644 index 000000000..f1a582d56 --- /dev/null +++ b/openspec/specs/dashboard-acknowledgements/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet +- LpLeesbevestigingen https://identity.conduction.nl/screens/board?id=launchpad/LpLeesbevestigingen diff --git a/openspec/specs/dashboard-acknowledgements/spec.md b/openspec/specs/dashboard-acknowledgements/spec.md index c5471d0ab..212ed43b9 100644 --- a/openspec/specs/dashboard-acknowledgements/spec.md +++ b/openspec/specs/dashboard-acknowledgements/spec.md @@ -1,7 +1,7 @@ # dashboard-acknowledgements Specification ## Purpose -TBD - created by archiving change dashboard-acknowledgements. Update Purpose after archive. +Mandatory-read announcements: an author asks the readers of a widget to confirm they have read it, every reader in the announcement's audience is blocked by a sign-off prompt until they do, and the author gets a read-receipt report (with CSV export) of who confirmed which version. ## Requirements ### Requirement: REQ-ACK-001 Declare an acknowledgement requirement on a placement @@ -18,8 +18,6 @@ placement, so all recipients of one announcement share one identity. A caller who is not an admin or the template owner MUST be rejected with `403` and the placement MUST be unchanged. -@e2e exclude Configuration + persistence + clone-propagation path; covered by PlacementUpdater / TemplateService / WidgetPlacementMapper PHPUnit and the non-author 403 by AcknowledgementControllerTest — no dedicated admin form UI in this pass. - #### Scenario: Admin requires acknowledgement on a template announcement - **GIVEN** an admin editing template dashboard `t-hr-2026` with a header widget placement `p-integriteitscode` @@ -42,6 +40,13 @@ placement MUST be unchanged. - **THEN** the placement MUST no longer force delivery - **AND** existing acknowledgement receipts MUST be retained as history (not deleted) +#### Scenario: A recipient cannot change the requirement on their copy + +- **GIVEN** user "bob" holds a copy of announcement `ak-1` from a template owned by "tom" +- **WHEN** bob updates his copy's placement with `requiresAcknowledgement = 0`, `reacknowledgeOnChange = 0` or another `acknowledgementContentVersion` +- **THEN** the system MUST return `403` and the placement MUST be unchanged +- **AND** without a template the author is the owner of the first placement that carried the key, never a later copy or fork + ### Requirement: REQ-ACK-002 Forced delivery of unacknowledged mandatory items The system MUST apply forced delivery to a widget placement with @@ -63,8 +68,6 @@ outstanding (unacknowledged) mandatory items. #### Scenario: Already-acknowledged item renders normally -@e2e exclude Asserted in AcknowledgementServiceTest::isOutstanding (no-receipt vs receipt) and the dashboard store vitest — the "already acknowledged" state renders the plain widget, the same negative path the covered sign-off scenario exits into. - - **GIVEN** user "alice" has a receipt for `announcementKey` `ak-1` at `acknowledgementContentVersion = 1` - **WHEN** she reopens the dashboard and the placement is still at version `1` - **THEN** the widget MUST render its normal content with no forced-delivery prompt @@ -72,13 +75,18 @@ outstanding (unacknowledged) mandatory items. #### Scenario: Deadline is presented but does not auto-acknowledge -@e2e exclude Deadline/overdue presentation is unit-covered (AcknowledgementService::isOverdue + AcknowledgementPrompt vitest) and requires a fixed system date; the prompt still requires an explicit sign-off, covered by the main gate scenario. - - **GIVEN** placement `p-integriteitscode` with `acknowledgementDeadline = 2026-08-01` and the current date is `2026-08-02` - **WHEN** an unacknowledged user opens the dashboard - **THEN** the prompt MUST still require an explicit sign-off (a passed deadline MUST NOT auto-acknowledge) - **AND** the item MUST be reportable as overdue in the read-receipt report (REQ-ACK-004) +#### Scenario: A copy kept after leaving the audience is not pending + +- **GIVEN** user "alice" holds a copy of announcement `ak-1`, whose template routes to group "sociaal-domein", and she is no longer a member of that group +- **WHEN** her outstanding items are listed +- **THEN** `ak-1` MUST NOT be listed and MUST NOT count toward the outstanding-acknowledgements count +- **AND** no blocking prompt MUST be shown for it, since she can no longer acknowledge it (REQ-ACK-003) + ### Requirement: REQ-ACK-003 Record an idempotent acknowledgement receipt When a recipient acknowledges, the system MUST persist a receipt @@ -89,6 +97,16 @@ create a second row and MUST return success. A recipient MUST be able to write a receipt **only for their own** `userId`; any attempt to write a receipt on behalf of another user MUST be rejected with `403` (ADR-005, no IDOR). +Only the announcement's audience MAY acknowledge it. The audience is the live +members of the groups its template routes to or, without group routing, the +owners of the dashboards holding a copy. In both cases the recipients of a +share of a personal dashboard holding the announcement (every user it is +shared with and every live member of a group it is shared with) MUST be in the +audience: they see the widget, so they MUST confirm it like the owner, the +announcement MUST be pending for them (REQ-ACK-002), and they MUST appear in +the read-receipt report (REQ-ACK-004). A user reached through several +dashboards MUST be asked once per announcement. + #### Scenario: First acknowledgement writes exactly one receipt - **GIVEN** user "alice" with no receipt for `announcementKey` `ak-1` at version `1` @@ -98,8 +116,6 @@ behalf of another user MUST be rejected with `403` (ADR-005, no IDOR). #### Scenario: Repeated acknowledgement is idempotent -@e2e exclude Row-level idempotency (no second row, original timestamp) is asserted in AcknowledgementServiceTest::testRepeatedAcknowledgeIsIdempotent + the race test — not observable through the UI. - - **GIVEN** user "alice" already has a receipt for `(ak-1, alice, 1)` - **WHEN** she `POST`s the same acknowledgement again - **THEN** the system MUST NOT insert a second row @@ -107,13 +123,27 @@ behalf of another user MUST be rejected with `403` (ADR-005, no IDOR). #### Scenario: A user cannot acknowledge on behalf of another user -@e2e exclude Cross-user 403 (no IDOR) is asserted in AcknowledgementControllerTest::testAcknowledgeRejectsCrossUser — a server-side auth contract, not a UI flow. - - **GIVEN** authenticated user "alice" - **WHEN** she `POST`s an acknowledgement whose body names `userId = "bob"` - **THEN** the system MUST return `403` - **AND** MUST NOT write any receipt for bob +#### Scenario: Only the announcement's audience can acknowledge it + +- **GIVEN** an announcement whose template routes to group "sociaal-domein", and authenticated user "mallory" who is not a member +- **WHEN** she `POST`s an acknowledgement for that announcement, or for an announcement key that no placement carries +- **THEN** the system MUST return `403` +- **AND** MUST NOT write any receipt +- **AND** the audience MUST be resolved for the session user, never for a user named in the request + +#### Scenario: A share recipient of a personal dashboard must confirm + +- **GIVEN** user "tom" asks for a read confirmation on a widget of his personal dashboard and shares the dashboard view-only with "pieter", who holds no copy +- **WHEN** pieter's outstanding items are listed +- **THEN** the announcement MUST be pending for pieter and his view of tom's dashboard MUST show the blocking prompt +- **AND** pieter MUST appear as pending in tom's read-receipt report +- **AND** a user the dashboard is not shared with, and who holds no copy, MUST still be rejected with `403` + ### Requirement: REQ-ACK-004 Admin read-receipt report scoped to the audience An admin or template owner MUST be able to retrieve a read-receipt report for an @@ -136,8 +166,6 @@ an admin nor the template owner MUST be rejected with `403`. #### Scenario: A newly added group member becomes pending automatically -@e2e exclude Live-audience resolution via IGroupManager is asserted in AcknowledgementServiceTest::testReportSeparatesAcknowledgedFromPending — mutating group membership mid-session is out of scope for a single UI run. - - **GIVEN** the report above, and `dave` is subsequently added to group "sociaal-domein" - **WHEN** the report is requested again - **THEN** the audience MUST include `dave` @@ -145,8 +173,6 @@ an admin nor the template owner MUST be rejected with `403`. #### Scenario: Non-author cannot read the report -@e2e exclude Non-author 403 on the report is asserted in AcknowledgementControllerTest::testReportRejectsNonOwner / testReportCsvRejectsNonManager — a server-side auth contract, not a UI flow. - - **GIVEN** user "bob" who is a recipient of `ak-1` but not an admin or template owner - **WHEN** bob requests the read-receipt report for `ak-1` - **THEN** the system MUST return `403` @@ -160,8 +186,6 @@ Receipts for prior versions MUST be retained as history and MUST NOT satisfy the new version. When `reacknowledgeOnChange = 0`, bumping the version MUST NOT re-force delivery for users who already acknowledged a prior version. -@e2e exclude Version-bump re-force logic (both branches) is asserted in AcknowledgementServiceTest::isOutstanding — a content-version bump is not directly UI-observable in a single session. - #### Scenario: Version bump re-forces delivery when re-acknowledge is on - **GIVEN** placement with `reacknowledgeOnChange = 1`, `announcementKey` `ak-1`, and user "alice" holding a receipt at version `1` @@ -176,6 +200,19 @@ re-force delivery for users who already acknowledged a prior version. - **THEN** alice's item MUST NOT re-force delivery - **AND** the read-receipt report MAY report her against the latest version she acknowledged +#### Scenario: A version that is not published yet cannot be acknowledged + +- **GIVEN** announcement `ak-1` at `acknowledgementContentVersion = 2` +- **WHEN** user "alice" `POST`s an acknowledgement for `ak-1` with `contentVersion = 3` +- **THEN** the system MUST return `400` and MUST NOT write any receipt +- **AND** a `contentVersion` at or below `2` MUST still be accepted, so a copy that was not re-synced yet can be signed off + +#### Scenario: Without a template the user's own copy sets the current version + +- **GIVEN** announcement `ak-1` whose template was deleted, and user "alice" whose copy is at version `2` while another copy is at version `1` +- **WHEN** alice acknowledges `ak-1` at version `2` +- **THEN** the system MUST accept it, so her prompt can be cleared + ### Requirement: REQ-ACK-006 Acknowledgement events feed activity and export Each successful acknowledgement MUST raise one entry in the existing Activity @@ -185,8 +222,6 @@ containing one row per audience member with acknowledged/pending status and, for acknowledged rows, the timestamp — so the result can be filed as compliance evidence. -@e2e exclude Single-shot activity emission and the CSV export body are asserted in AcknowledgementServiceTest / AcknowledgementControllerTest — the CSV `DataDownloadResponse` cannot be exercised under the OCP stub bootstrap and the Activity row is not UI-observable on the dashboard. - #### Scenario: Acknowledging emits one activity event - **GIVEN** the Activity provider is registered @@ -194,6 +229,8 @@ evidence. - **THEN** exactly one activity entry MUST be emitted for the acknowledgement (subject `dashboard_acknowledged`) naming alice and the announcement - **AND** no activity entry MUST be emitted for an idempotent repeat acknowledgement (REQ-ACK-003) +@e2e exclude the Activity app is an optional Nextcloud app the e2e fixture does not set up (tests/e2e/seed.sh and tests/e2e/global-setup.ts enable no app), so its feed is not a surface this suite can rely on, and its OCS feed returns the rendered line rather than the `dashboard_acknowledged` subject. Pinned by tests/Unit/Service/AcknowledgementServiceTest.php testFirstAcknowledgeRecordsAndEmitsActivity (exactly one event) and testRepeatedAcknowledgeIsIdempotent / testAcknowledgeRaceReturnsWinnerWithoutActivity (none on a repeat). + #### Scenario: Report exports as CSV compliance evidence - **GIVEN** announcement `ak-1` with audience `{alice, bob, carol}`, of whom `alice` and `carol` acknowledged @@ -202,9 +239,17 @@ evidence. - **AND** alice's and carol's rows MUST carry status `acknowledged` and their timestamps - **AND** bob's row MUST carry status `pending` with an empty timestamp -### Requirement: An editor can ask for confirmation from the widget form (REQ-ACK-007) -@e2e exclude asking and confirming need two people on a live dashboard; asserted in src/dialogs/__tests__/ReadConfirmationDialog.spec.js, src/views/__tests__/ViewsReadConfirmation.spec.js and tests/Unit/Service/PlacementUpdaterReadConfirmationTest.php +#### Scenario: The activity line names the acknowledged version + +- **GIVEN** user "alice" acknowledges `ak-1` at version `2` +- **WHEN** the activity line is rendered +- **THEN** it MUST read "You acknowledged version 2 of {dashboard}" (or "{actor} acknowledged version 2 of {dashboard}") +- **AND** a line stored before versions were recorded MUST keep its old text + +@e2e exclude the Activity app is an optional Nextcloud app the e2e fixture does not set up (tests/e2e/seed.sh and tests/e2e/global-setup.ts enable no app), so its feed is not a surface this suite can rely on, and its OCS feed returns the rendered line rather than the `dashboard_acknowledged` subject. The second clause also needs an activity row stored before versions were recorded, which no HTTP call can create. Pinned by tests/Unit/Activity/ExtensionTest.php testParseNamesTheAcknowledgedVersion (both wordings, and the old text without a version) and tests/Unit/Service/AcknowledgementServiceTest.php testActivityNamesTheAcknowledgedVersion. + +### Requirement: An editor can ask for confirmation from the widget form (REQ-ACK-007) The widget edit form MUST offer "Ask readers to confirm they have read this". Saving with it ticked MUST send `requiresAcknowledgement: 1` in the placement update; unticking MUST send `0`. @@ -216,8 +261,6 @@ The widget edit form MUST offer "Ask readers to confirm they have read this". Sa ### Requirement: An editor can see who has confirmed (REQ-ACK-008) -@e2e exclude asking and confirming need two people on a live dashboard; asserted in src/dialogs/__tests__/ReadConfirmationDialog.spec.js, src/views/__tests__/ViewsReadConfirmation.spec.js and tests/Unit/Service/PlacementUpdaterReadConfirmationTest.php - When a widget on the dashboard asks for confirmation, people who may edit the dashboard MUST find "Read receipts" at the top of the dashboard, showing the confirmed count, the names still pending and a CSV download from the existing report. #### Scenario: Read the report @@ -225,3 +268,23 @@ When a widget on the dashboard asks for confirmation, people who may edit the da - **GIVEN** 3 of 5 team members confirmed "New expense rules" - **WHEN** Sanne opens "Read receipts" - **THEN** she sees 3 confirmed and the 2 pending names, and can download the CSV + +### Requirement: A placement that asks for confirmation has a key (REQ-ACK-009) + +A widget placement with `requiresAcknowledgement` SHALL carry a stable `announcementKey` in every response that returns the placement, the same across edits of its content, so the reader's confirmation and the editor's report refer to it. + +#### Scenario: The key reaches the dashboard + +- **GIVEN** the Announcement widget on Intranet Zuiddrecht asks for confirmation +- **WHEN** an editor loads the dashboard +- **THEN** the placement carries its announcementKey and Read receipts appears in the More menu + +### Requirement: The read confirmations dialog (REQ-ACK-010) + +Read receipts SHALL open a dialog titled "Read confirmations: " under "Announcement · <dashboard>", showing the confirmed count over the audience with the number still to go and the deadline, a bar, the filters Everyone, Confirmed and Not confirmed yet, a table of Employee (initials and name), Department and Status, a line that says how many are shown and that Download gives the full list with the date and time of each confirmation, and the buttons Download and Close. + +#### Scenario: Who has not confirmed + +- **GIVEN** 128 of 164 confirmed "New procedure for Woo requests" +- **WHEN** the editor chooses Not confirmed yet +- **THEN** the table lists the 36 who have not, with their department and "Not yet" diff --git a/openspec/specs/dashboard-bulk-operations/screens.md b/openspec/specs/dashboard-bulk-operations/screens.md new file mode 100644 index 000000000..1a9099128 --- /dev/null +++ b/openspec/specs/dashboard-bulk-operations/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerOnderhoud https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerOnderhoud diff --git a/openspec/specs/dashboard-bulk-operations/spec.md b/openspec/specs/dashboard-bulk-operations/spec.md index 510c97542..56ad429c5 100644 --- a/openspec/specs/dashboard-bulk-operations/spec.md +++ b/openspec/specs/dashboard-bulk-operations/spec.md @@ -20,8 +20,6 @@ Dashboard bulk operations expose four batch admin endpoints for large-scale mana All four endpoints accept `?dryRun=true` (or `dryRun: true` in the JSON body) and require Nextcloud admin privileges. Bulk-delete additionally accepts `?cascade=true` (or `cascade: true` in the body) for opt-in subtree deletion. -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Request envelope (all endpoints) ```json @@ -214,6 +212,8 @@ NOTE: The unified-search integration is provided by a sibling capability. `BulkO - AND the response MUST return `{reindexedCount: 2, errors: [{uuid: "uuid-2", reason: "reindex_failed", detail: "..."}]}` - AND the batch MUST continue after the failure (partial success is reported) +@e2e exclude needs the persistence layer to reject one row's update mid-batch (a DB fault), which no HTTP request can provoke; the reindex_failed entry and continue-on-error are pinned by tests/Unit/Service/BulkOperationOutcomesGoldenTest.php::testOutcomesMatchTheRecording (fixture case "reindex / real", uuid "boom") + #### Scenario: Bulk re-index with insufficient permissions - GIVEN admin cannot access dashboard "uuid-3" - WHEN she sends bulk-reindex request with that uuid @@ -244,12 +244,16 @@ NOTE: The permission pre-check (REQ-BULK-011) is all-or-nothing and runs before - AND the response MUST return `{deletedCount: 2, skippedCount: 0, errors: [{uuid: "uuid-2", reason: "transaction_failed", detail: "..."}]}` - AND "uuid-1" and "uuid-3" MUST be deleted; "uuid-2" MUST NOT be deleted +@e2e exclude needs one dashboard's delete to fail inside its transaction (a DB fault such as a constraint violation), which no HTTP request can provoke; transaction_failed with the rest of the batch committed is pinned by tests/Unit/Service/BulkOperationOutcomesGoldenTest.php::testOutcomesMatchTheRecording (fixture case "delete / real / cascade off", uuid "boom") + #### Scenario: Batch not atomic means caller must retry manually - GIVEN bulk-delete of 10 dashboards, 5 succeed, 5 fail - WHEN caller receives `{deletedCount: 5, skippedCount: 0, errors: [5 errors]}` - THEN the caller (admin) MUST be responsible for retrying the 5 failed dashboards - AND the system MUST NOT offer automatic rollback of the 5 successful deletions +@e2e exclude needs five per-dashboard delete failures in one batch (DB faults no HTTP request can provoke); the no-rollback, continue-on-error tally is pinned by tests/Unit/Service/BulkOperationOutcomesGoldenTest.php::testOutcomesMatchTheRecording (fixture cases "delete / real / cascade off" and "delete / real / cascade on") + ### Requirement: REQ-BULK-006 Request Size Cap (Max 500 Dashboards per Request) All bulk endpoints MUST enforce a maximum number of `dashboardUuids` per request, configurable via the `bulk_operation_max_per_request` app config key. @@ -332,18 +336,24 @@ NOTE: Per-dashboard Activity events are intentionally NOT emitted by the bulk pi - THEN the system MUST emit exactly ONE Activity event (not 10) - AND the event MUST contain `bulkOperation`, `dashboardCount`, `durationMs`, and `dryRun` parameters +@e2e exclude the bulkOperation, dashboardCount, durationMs and dryRun parameters live in the activity row's subject parameters, which the Activity app's OCS API does not return (LaunchPad renders the subject to plain text); one event per request with exactly these parameters is pinned by tests/Unit/Service/BulkOperationServiceTest.php::testEmitsAuditEventOncePerOperation and ::testEveryOperationWritesItsAuditRow + #### Scenario: Activity event includes operation duration - GIVEN admin sends bulk-move request - WHEN the operation completes - THEN the activity event MUST include `durationMs` measured from `microtime(true)` start - AND admins can use this to monitor performance trends +@e2e exclude durationMs is a subject parameter of the activity row, which the Activity app's OCS API does not return; it is pinned by tests/Unit/Service/BulkOperationServiceTest.php::testEveryOperationWritesItsAuditRow (asserts durationMs is an int) and ::testAFailedAuditRowIsLoggedAndTheOperationCompletes (0 <= durationMs < 60000) + #### Scenario: Dry-run also emits audit event - GIVEN admin sends bulk-delete?dryRun=true with 10 uuids - WHEN the dry-run completes - THEN the system MUST still emit ONE activity event - AND the activity payload MUST indicate it was a dry-run (`dryRun: true`) +@e2e exclude the dryRun flag is a subject parameter of the activity row, which the Activity app's OCS API does not return; one dry-run event per operation carrying dryRun=true is pinned by tests/Unit/Service/BulkOperationServiceTest.php::testEveryOperationWritesItsAuditRow + ### Requirement: REQ-BULK-010 Frontend Multi-Select Checkbox Column and Actions Dropdown The admin dashboard list view MUST provide a multi-select checkbox interface and an Actions dropdown for bulk operations. Implemented in `src/components/admin/DashboardBulkOperations.vue`, mounted from `src/components/admin/AdminSettings.vue`. @@ -398,7 +408,7 @@ Every bulk endpoint MUST enforce an all-or-nothing permission model: if the call #### Scenario: Non-admin user cannot call bulk endpoints - GIVEN user "bob" with no admin privileges - WHEN he sends POST /api/admin/dashboards/bulk-delete -- THEN the system MUST return HTTP 403 with `Administrator privileges required.` +- THEN the system MUST return HTTP 403 and change nothing (Nextcloud's admin-setting check refuses the call before LaunchPad's own `Administrator privileges required.` is reached) #### Scenario: Permission check happens before size validation - GIVEN admin user with permission denied on one dashboard in a batch of 501 dashboards diff --git a/openspec/specs/dashboard-cascade-events/screens.md b/openspec/specs/dashboard-cascade-events/screens.md new file mode 100644 index 000000000..c4c13c408 --- /dev/null +++ b/openspec/specs/dashboard-cascade-events/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Opruimen van afhankelijke gegevens bij het verwijderen van een dashboard gebeurt op de achtergrond. diff --git a/openspec/specs/dashboard-cascade-events/spec.md b/openspec/specs/dashboard-cascade-events/spec.md index b79a45c8c..179ef6058 100644 --- a/openspec/specs/dashboard-cascade-events/spec.md +++ b/openspec/specs/dashboard-cascade-events/spec.md @@ -11,8 +11,6 @@ When a LaunchPad dashboard is deleted, all dependent data (widget placements, co ## Requirements -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: REQ-CSC-001 DashboardDeletedEvent Definition The system MUST define a `DashboardDeletedEvent` class at `lib/Event/DashboardDeletedEvent.php` that carries all context listeners need to perform targeted cleanup. @@ -39,6 +37,8 @@ The system MUST define a `DashboardDeletedEvent` class at `lib/Event/DashboardDe - NOTE: dispatch is synchronous within the same PHP request — `IEventDispatcher::dispatchTyped()` blocks until all listeners return; the event fires before the HTTP response is sent. This matches the pattern confirmed in the reference implementation. - NOTE: listeners observe a row that is already soft-deleted — they MUST NOT attempt to re-delete the main row +@e2e exclude the order inside one request (row removed first, event dispatched second, both before the response) is not observable over HTTP, which only sees the finished state. Pinned by tests/Unit/Service/DashboardCascadeEventDispatchTest.php::testDeleteDashboardDispatchesEvent; that the listeners' effects are already in place when the response arrives is exercised by every test in tests/e2e/dashboard-cascade-events.spec.ts, which reads back immediately after the DELETE. + #### Scenario: Event is NOT dispatched when validation rejects the delete - GIVEN dashboard `D1` has child dashboards and the caller has NOT requested cascade mode @@ -54,12 +54,16 @@ The system MUST define a `DashboardDeletedEvent` class at `lib/Event/DashboardDe - THEN `getType()` MUST return `'group_shared'` - AND `getOwnerUserId()` MUST return the admin's user ID (the actor who performed the deletion) +@e2e exclude event payload with no HTTP surface. Pinned by tests/Unit/Event/DashboardDeletedEventTest.php::testGroupSharedTypeAndActorOwner and tests/Unit/Service/DashboardCascadeEventDispatchTest.php::testDeleteGroupSharedDispatchesEvent. + #### Scenario: Event class extends Nextcloud IEventDispatcher contract - GIVEN `DashboardDeletedEvent` is instantiated - WHEN it is passed to `IEventDispatcher::dispatchTyped()` - THEN no type error MUST occur — the class MUST extend `\OCP\EventDispatcher\Event` +@e2e exclude a class-hierarchy property with no HTTP surface. Pinned by tests/Unit/Event/DashboardDeletedEventTest.php::testExtendsNextcloudEventBase. + ### Requirement: REQ-CSC-002 Listener Registry and Registration Every listener MUST be registered in `Application` via `IEventDispatcher::addListener`. Adding a new listener MUST require only adding one registration line — no edits to existing listener classes. @@ -86,6 +90,8 @@ Every listener MUST be registered in `Application` via `IEventDispatcher::addLis - WHEN they add one line to `Application::register()` registering it for `DashboardDeletedEvent::class` - THEN it MUST be invoked on every subsequent dashboard deletion — no changes to other listener files, `DashboardService`, or the event class are required +@e2e exclude a source-structure property (which files a developer edits), not runtime behaviour an instance can show. The one-line registration per listener is visible in lib/AppInfo/Application.php and pinned for one listener by tests/Unit/Listener/DashboardSharesListenerTest.php::testIsRegisteredForDashboardDeletedEvent. + ### Requirement: REQ-CSC-003 Dependent-Data Listener Group A set of listeners MUST clean up every dependent table when `DashboardDeletedEvent` fires. Listeners for disjoint data MUST execute independently and MUST NOT interfere with each other. @@ -110,6 +116,8 @@ A set of listeners MUST clean up every dependent table when `DashboardDeletedEve - AND the NC comments table MUST contain no comments for `launchpad_dashboard` / `D1.uuid` after the call - NOTE: This is the one listener whose pattern is directly derived from the reference implementation. The reference registers a single listener that calls the equivalent ICommentsManager method as its only cleanup action. +@e2e exclude retired: dashboard comments, CommentsListener and its registration were removed in c4a515e7c ("chore(retire): remove Comments, outbound RSS feed, and save-as-template"), an ancestor of HEAD. No comment can be created on a dashboard, so there is nothing to cascade. + #### Scenario: Public shares are soft-revoked, not hard-deleted - GIVEN dashboard `D1` has 2 active rows in `oc_launchpad_public_shares` with `revokedAt IS NULL` @@ -118,6 +126,8 @@ A set of listeners MUST clean up every dependent table when `DashboardDeletedEve - AND neither row MUST be hard-deleted (audit trail is preserved) - NOTE: LaunchPad-specific listener — the reference implementation has no public-shares table. +@e2e exclude the distinguishing clause (row kept with `revokedAt` set, not deleted) is not observable over HTTP: a revoked and a deleted token both answer 404 at `/s/{token}/data`, and the share list endpoint 404s once the dashboard is gone. Pinned by tests/Unit/Db/PublicShareMapperCoverageTest.php::testRevokeByDashboardUuidOnlyTouchesUnrevokedSharesAndReturnsTheCount and the PublicSharesListener cases of tests/Unit/Listener/CleanupListenersGoldenTest.php::testListenerMatchesTheRecordedFixture. + #### Scenario: User and group shares are deleted with their dashboard - GIVEN dashboard `D1` is shared with user `bob` and with group `sales`, two rows in `oc_launchpad_dashboard_shares` @@ -137,6 +147,8 @@ A set of listeners MUST clean up every dependent table when `DashboardDeletedEve - NOTE: if the file does not exist (already removed or never created), the listener MUST treat this as a no-op - NOTE: LaunchPad-specific listener — the reference implementation has no versioning table. +@e2e exclude needs an instance running the GroupFolder storage backend, which the e2e instance does not provision, and a file read outside the API. Pinned (DB rows) by tests/Unit/Listener/VersionsListenerTest.php::testDeletedDashboardHasItsVersionRowsRemoved; no test covers the GroupFolder file removal. + #### Scenario: Tree listener recursively cascades to child dashboards - GIVEN dashboard `P1` (parent) has children `C1` and `C2` in `oc_launchpad_dashboards` @@ -174,6 +186,8 @@ When Nextcloud deletes a user, LaunchPad MUST clean up all data owned by that us - THEN the token row MUST have `revokedAt` set to the current timestamp - AND it MUST NOT be hard-deleted (the token URL may still be live; revocation allows a 410 response) +@e2e exclude retired: the outbound RSS feed and FeedToken(+Mapper) were removed in c4a515e7c, which also adds migration Version002003Date20260620000000 dropping `launchpad_feed_tokens`. There is no feed token to revoke. + #### Scenario: Analytics opt-out preference is removed on user deletion - GIVEN `alice` has a stored analytics opt-out preference via IConfig @@ -195,6 +209,8 @@ When Nextcloud deletes a group, LaunchPad MUST clean up all group-scoped data. - AND each deletion MUST cascade cleanup of dependent data via `DashboardDeletedEvent` - NOTE: LaunchPad-specific design — no equivalent exists in the reference implementation. +@e2e exclude never built: GroupDeletedListener only calls RoleService::deleteByGroupId (lib/Listener/GroupDeletedListener.php). Deleting group-shared dashboards was a TODO in the original stub (fa102a8a0) and `git log --all -S'deleteGroupShared' -- lib/Listener` shows no commit that implemented it. No unit or Newman test covers it. + #### Scenario: Group is removed from org navigation tree on group deletion - GIVEN the `launchpad.org_navigation_tree` IConfig value is a JSON object containing `groupVisibility` arrays that reference group `marketing` @@ -203,6 +219,8 @@ When Nextcloud deletes a group, LaunchPad MUST clean up all group-scoped data. - AND no other group identifiers in the JSON MUST be altered - NOTE: LaunchPad-specific IConfig JSON-mutation — no equivalent in the reference implementation. +@e2e exclude never built: GroupDeletedListener only removes role assignments; the groupVisibility rewrite was a TODO in the stub (fa102a8a0) and `git log --all -S'groupVisibility' -- lib/Listener` finds only that stub and its archive. No unit or Newman test covers it. + #### Scenario: Group is removed from group_order setting on group deletion - GIVEN `launchpad.group_order` is a JSON array `["engineering", "marketing", "support"]` @@ -211,6 +229,8 @@ When Nextcloud deletes a group, LaunchPad MUST clean up all group-scoped data. - AND the update MUST be persisted to IConfig - NOTE: LaunchPad-specific IConfig JSON-mutation — no equivalent in the reference implementation. +@e2e exclude never built: GroupDeletedListener only removes role assignments; the group_order rewrite was a TODO in the stub (fa102a8a0) and `git log --all -S'group_order' -- lib/Listener` finds only that stub and its archive. No unit or Newman test covers it. + ### Requirement: REQ-CSC-006 Failure Isolation A failure in one listener MUST NOT prevent other listeners from executing. Every listener MUST catch all `\Throwable` and continue. @@ -226,6 +246,8 @@ A failure in one listener MUST NOT prevent other listeners from executing. Every - AND the exception from `ReactionsListener` MUST NOT propagate beyond its own catch block - AND `DashboardService::delete()` MUST complete and return a response +@e2e exclude needs a listener to throw inside a live request, a fault an e2e run cannot inject. Pinned by tests/Unit/Listener/DashboardSharesListenerTest.php::testAFailingDeleteIsLoggedAndDoesNotStopPeerListeners and tests/Unit/Listener/ReactionsListenerTest.php::testServiceFailureIsLoggedAndSwallowed. + #### Scenario: Listener failure is logged at WARN level - GIVEN a listener throws during handling of `DashboardDeletedEvent` @@ -234,6 +256,8 @@ A failure in one listener MUST NOT prevent other listeners from executing. Every - AND MUST NOT call `ILogger::error()` (a cascade failure is recoverable via orphan-cleanup — it is not a fatal error) - NOTE: The reference implementation logs at `error` level; LaunchPad's choice of `warning` is deliberate — it signals recoverability rather than a fatal condition. +@e2e exclude needs an injected listener fault and a read of the server log, neither reachable over HTTP. Pinned by tests/Unit/Listener/DashboardCleanupListenerTest.php::testAnErrorIsCaughtAndLoggedAsAWarning. + #### Scenario: Multiple listener failures do not prevent response - GIVEN 3 out of 10 listeners throw exceptions @@ -243,6 +267,8 @@ A failure in one listener MUST NOT prevent other listeners from executing. Every - AND the 3 failures MUST each be logged at WARN level with full context (listener class, dashboard UUID, exception message) - NOTE: Failure recording via a dedicated DB table (`oc_launchpad_cascade_failures`) has been dropped in favour of log-and-continue. The orphan-cleanup job identifies residual rows by querying dependent tables directly, making the failures table redundant. See REQ-CSC-007 for the rationale. +@e2e exclude needs three injected listener faults, and its `cascadeStats` clause was never built (see cascadestats-is-present-even-when-no-dependent-data-exists). The log-and-continue part is pinned by tests/Unit/Listener/DashboardCleanupListenerTest.php::testAnErrorIsCaughtAndLoggedAsAWarning and the `failing` cases of tests/Unit/Listener/CleanupListenersGoldenTest.php::testListenerMatchesTheRecordedFixture. + ### Requirement: REQ-CSC-007 Failure Handling — Log-and-Continue When a listener fails, the failure MUST be logged at WARN level with full context. No separate failure-recording table is required. @@ -256,6 +282,8 @@ When a listener fails, the failure MUST be logged at WARN level with full contex - THEN `ILogger::warning()` MUST be called with at minimum: the listener class name, the dashboard UUID `abc-123`, and the exception message - AND execution MUST continue — no exception MUST propagate out of the listener's catch block +@e2e exclude needs an injected MetadataValuesListener fault and a read of the server log. Pinned by the MetadataValuesListener `failing` case of tests/Unit/Listener/CleanupListenersGoldenTest.php::testListenerMatchesTheRecordedFixture (warning with class, uuid `d-1` and message). + #### Scenario: No failure-recording table migration is required - GIVEN the implementation of this change @@ -263,6 +291,8 @@ When a listener fails, the failure MUST be logged at WARN level with full contex - THEN there MUST be no migration adding an `oc_launchpad_cascade_failures` table - AND the orphan-cleanup job MUST identify stragglers by querying dependent tables directly (e.g., `oc_launchpad_widget_placements` joined against soft-deleted dashboards) +@e2e exclude a property of the migration list, not runtime behaviour: no file under lib/Migration mentions `cascade_failures` (grep). The straggler query side is the orphaned_widget_placements category, covered in openspec/specs/orphaned-data-cleanup. + ### Requirement: REQ-CSC-008 Idempotency Every listener MUST be idempotent: running it a second time against already-cleaned data MUST be a no-op with no errors. @@ -274,18 +304,24 @@ Every listener MUST be idempotent: running it a second time against already-clea - THEN the DELETE query MUST affect 0 rows and MUST NOT throw an exception - AND the listener MUST return successfully +@e2e exclude a second run of a listener for an already-deleted dashboard cannot be caused over HTTP: a repeated DELETE answers 404 before any event fires. Pinned by tests/Unit/Listener/WidgetPlacementsListenerTest.php::testHandlesDashboardDeletedEventWithoutThrowing. + #### Scenario: Re-running PublicSharesListener on already-revoked shares is safe - GIVEN all share rows for `D1` already have `revokedAt` set - WHEN `PublicSharesListener` runs again - THEN the UPDATE MUST match 0 rows (WHERE `revokedAt IS NULL` filters them all out) and MUST NOT throw +@e2e exclude a second listener run cannot be caused over HTTP (a repeated DELETE answers 404 first). Pinned by tests/Unit/Db/PublicShareMapperCoverageTest.php::testRevokeByDashboardUuidOnlyTouchesUnrevokedSharesAndReturnsTheCount (the UPDATE filters `revoked_at IS NULL`). + #### Scenario: Re-running CommentsListener when no comments exist is safe - GIVEN `ICommentsManager::deleteCommentsAtObject()` is called for `D1` when no comments exist - THEN it MUST return without error (NC core already handles the empty-case gracefully) - AND `CommentsListener` MUST NOT add extra null-checks that could mask genuine errors +@e2e exclude retired: CommentsListener was removed in c4a515e7c ("chore(retire): remove Comments, outbound RSS feed, and save-as-template"). + ### Requirement: REQ-CSC-009 Cascade Stats Response `DashboardService::delete()` MUST return cascade statistics alongside the standard delete response. @@ -315,6 +351,8 @@ Every listener MUST be idempotent: running it a second time against already-clea ``` - AND the response MUST be additive (clients that ignore unknown fields remain unaffected) +@e2e exclude never built: `DELETE /api/dashboard/{id}` answers `{"status":"ok"}` (DashboardApiController::delete) and `git log --all -S'cascadeStats' -- lib src appinfo` finds no commit. No unit or Newman test covers it. + #### Scenario: cascadeStats reflects partial success when listeners fail - GIVEN 2 listeners succeed (deleting 5 rows total) and 1 listener fails @@ -323,12 +361,16 @@ Every listener MUST be idempotent: running it a second time against already-clea - AND the failed listener's key MUST appear with value `0` (or be omitted — implementation choice, but MUST be consistent) - NOTE: the caller is not expected to act on partial-failure counts; WARN-level log entries are the canonical failure record (no `oc_launchpad_cascade_failures` table exists) +@e2e exclude never built: there is no `cascadeStats` in any response (`git log --all -S'cascadeStats' -- lib src appinfo` is empty), and the listener fault cannot be injected over HTTP either. + #### Scenario: cascadeStats is present even when no dependent data exists - GIVEN dashboard `D1` has no placements, comments, or any other dependent rows - WHEN `DELETE /api/dashboards/D1.uuid` completes - THEN `cascadeStats` MUST still be present in the response with all counters set to `0` +@e2e exclude never built: `DELETE /api/dashboard/{id}` answers `{"status":"ok"}` (DashboardApiController::delete); `git log --all -S'cascadeStats' -- lib src appinfo` finds no commit. + ### Requirement: REQ-CSC-010 Tree Cascade Validation Guard Cascade deletion of a parent dashboard MUST only proceed when explicitly requested; non-cascade deletes with children MUST be rejected before any event is dispatched. @@ -339,7 +381,7 @@ Cascade deletion of a parent dashboard MUST only proceed when explicitly request - GIVEN dashboard `P1` has child `C1` - WHEN a caller sends `DELETE /api/dashboards/P1.uuid` without a cascade flag -- THEN the system MUST return HTTP 400 with an error indicating children exist +- THEN the system MUST return HTTP 409 with an error indicating children exist (REQ-DASH-030 in dashboards) - AND `DashboardDeletedEvent` MUST NOT be dispatched for `P1` or `C1` - AND no dependent data MUST be altered @@ -352,9 +394,13 @@ Cascade deletion of a parent dashboard MUST only proceed when explicitly request - AND all 4 widget placements (2 per child) MUST be removed by `WidgetPlacementsListener` responding to each child event - AND `cascadeStats` in the response MUST reflect the total across all three dashboards +@e2e exclude its last clause, `cascadeStats` totals in the response, was never built (`git log --all -S'cascadeStats' -- lib src appinfo` is empty). Everything else is asserted by the tree-listener-recursively-cascades-to-child-dashboards test in tests/e2e/dashboard-cascade-events.spec.ts; the per-node dispatch by tests/Unit/Service/DashboardCascadeEventDispatchTest.php::testDeleteSubtreeDispatchesEventForEachNode. + #### Scenario: Tree listener is a no-op for leaf dashboards - GIVEN dashboard `L1` has no children - WHEN `DashboardDeletedEvent` fires for `L1` - THEN `TreeListener` MUST query the children table, find zero rows, and return without dispatching any further events - AND this MUST be treated as a successful no-op (no failure is recorded) + +@e2e exclude whether a listener dispatched nothing is not observable over HTTP; a leaf delete looks the same either way. Pinned by tests/Unit/Listener/TreeListenerTest.php::testNoChildrenDispatchesNothing. diff --git a/openspec/specs/dashboard-co-editing/spec.md b/openspec/specs/dashboard-co-editing/spec.md new file mode 100644 index 000000000..dbf416554 --- /dev/null +++ b/openspec/specs/dashboard-co-editing/spec.md @@ -0,0 +1,54 @@ +# dashboard-co-editing Specification + +## Purpose +Several people edit one shared dashboard at the same time: each sees who else is editing, changes to different widgets both survive, a later change to the same widget is refused instead of lost, and a new widget takes the first free spot. + +## Requirements + +### Requirement: Several people SHALL be able to edit a shared dashboard at once + +The system SHALL let every person with edit rights on a shared dashboard edit it at the same +time as others. Each editor SHALL see who else is editing that dashboard and since when. The +system SHALL save every change at once. A change to one widget SHALL NOT overwrite a colleague's +change to another widget. + +Rows: `build-edit-lock` (launchpad matrix). + +#### Scenario: A second editor edits instead of waiting +- **GIVEN** Marieke edits the shared dashboard "Mijn werkplek" since 10:42 +- **WHEN** Sanne opens the same dashboard in edit mode +- **THEN** Sanne can edit it +- **AND** Sanne sees that Marieke edits it too, since 10:42 + +#### Scenario: Changes to different widgets both survive +- **GIVEN** Marieke and Sanne edit the same dashboard +- **WHEN** Marieke resizes the calendar widget and Sanne moves the news widget +- **THEN** the saved dashboard has both changes + +### Requirement: Two changes to the same widget SHALL NOT silently replace each other + +When two editors change the same widget, the system SHALL apply the first saved change and +refuse the later one, which was made on an older version of that widget. The editor whose change +was refused SHALL see the colleague's version and SHALL be able to make the change again on top +of it. + +Rows: `build-edit-lock` (launchpad matrix). + +#### Scenario: The later change to one widget is refused, not lost silently +- **GIVEN** Marieke and Sanne both have the calendar widget's settings open +- **WHEN** Marieke saves first and Sanne saves after +- **THEN** Marieke's change is kept +- **AND** Sanne sees Marieke's version and can apply her change again + +### Requirement: A new widget SHALL land on the first free spot + +When an editor adds a widget, the system SHALL place it on the first free spot in the saved +layout and SHALL NOT place it over another widget, also when a colleague changed the layout a +moment before. + +Rows: `build-edit-lock` (launchpad matrix). + +#### Scenario: A widget added during a colleague's edit takes a free spot +- **GIVEN** Marieke just moved a widget into the first free spot +- **WHEN** Sanne adds a new widget +- **THEN** the new widget goes to the next free spot and covers no other widget diff --git a/openspec/specs/dashboard-deeplinking/screens.md b/openspec/specs/dashboard-deeplinking/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/dashboard-deeplinking/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/dashboard-deeplinking/spec.md b/openspec/specs/dashboard-deeplinking/spec.md index 0c4658c3e..eb6f8e1eb 100644 --- a/openspec/specs/dashboard-deeplinking/spec.md +++ b/openspec/specs/dashboard-deeplinking/spec.md @@ -60,7 +60,7 @@ The route MUST be the LAST entry in the route table so every literal `/api/...` and explicit page route is matched first. #### Scenario: Catch-all route registered last -@e2e exclude route-table registration is a PHP source-code assertion — not browser-drivable +@e2e exclude the order of the route table is not visible in a browser; its effect (an API route is not shadowed) is the e2e of the health-check scenario below, and the catch-all's place after the literal routes is pinned by tests/Unit/Controller/PageControllerStartTest.php::testTheStartRouteComesBeforeTheDeepLinkCatchAll - **GIVEN** `appinfo/routes.php` is loaded - **WHEN** the route table is inspected - **THEN** a route named `page#deepLink` with URL `/{deepLink}` and the negative-lookahead requirement MUST be present @@ -82,7 +82,6 @@ delegate to `index($deepLink)` which: a stale slug.** #### Scenario: Stale slug falls back silently -@e2e exclude server-side path resolution + fallback is validated via Newman/PHPUnit HTTP contract, not browser - **GIVEN** a user visits `/apps/launchpad/{stale-slug}` - **WHEN** `PageController::deepLink()` resolves the path - **THEN** it MUST fall back to the seven-step resolver and return a 200 TemplateResponse @@ -102,7 +101,6 @@ silently normalised to `/apps/launchpad/new-parent/child` without a reload. #### Scenario: Canonical path passed through initial state -@e2e exclude initial-state plumbing of the canonical path is a server-render assertion - **GIVEN** the active dashboard has been resolved - **WHEN** `PageController::index()` renders - **THEN** it MUST compute the canonical slug-chain via `DashboardTreeService::computePath(uuid)` @@ -115,9 +113,7 @@ canonical slug-chain for a dashboard UUID: ```json { - "data": { - "path": "finance/q1-roadmap" - } + "path": "/finance/q1-roadmap" } ``` @@ -127,10 +123,9 @@ result is a valid response (`""`) for dashboards with NULL slugs — those are unaddressable. #### Scenario: Endpoint returns canonical slug-chain -@e2e exclude HTTP-contract endpoint verified via Newman/PHPUnit, not browser - **GIVEN** a dashboard with UUID `u1` and canonical path `finance/q1-roadmap` - **WHEN** `GET /api/dashboards/u1/path` is called -- **THEN** the response MUST contain `{ "data": { "path": "finance/q1-roadmap" } }` +- **THEN** the response body MUST be `{ "path": "/finance/q1-roadmap" }`, the slug-chain with a leading slash - **AND** a dashboard with a NULL slug MUST return an empty `""` path ### Requirement: REQ-DDL-005 Frontend `pushState` on switch @@ -150,7 +145,6 @@ already correct from the server-side render); it fires only on subsequent transitions. #### Scenario: Switching dashboard pushes history entry -@e2e exclude asserts history.pushState call/URL internals — covered by Vitest component test - **GIVEN** the workspace is loaded on dashboard A - **WHEN** the user switches to dashboard B via the sidebar - **THEN** the browser URL MUST change to `/apps/launchpad/{B-path}` via `history.pushState` @@ -170,7 +164,6 @@ the user's expectation. Visiting any URL the user hasn't seen before still works because step 3 hits the resolver. #### Scenario: Back button navigates to previous dashboard -@e2e exclude asserts popstate-listener resolution internals — covered by Vitest component test - **GIVEN** the user has switched from dashboard A to dashboard B - **WHEN** the user presses the browser back button - **THEN** the `popstate` listener MUST resolve the previous path and switch the active dashboard back to A @@ -188,7 +181,6 @@ The catch-all route MUST come AFTER every `/api/...` entry in `routes.php`. #### Scenario: API health check still routes after catch-all -@e2e exclude Newman API regression assertion, not browser-drivable - **GIVEN** the catch-all route is registered - **WHEN** `GET /api/health` is called - **THEN** it MUST return 200 and NOT be shadowed by the catch-all diff --git a/openspec/specs/dashboard-export-import/screens.md b/openspec/specs/dashboard-export-import/screens.md new file mode 100644 index 000000000..1a9099128 --- /dev/null +++ b/openspec/specs/dashboard-export-import/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerOnderhoud https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerOnderhoud diff --git a/openspec/specs/dashboard-export-import/spec.md b/openspec/specs/dashboard-export-import/spec.md index be95cc360..4fade4625 100644 --- a/openspec/specs/dashboard-export-import/spec.md +++ b/openspec/specs/dashboard-export-import/spec.md @@ -152,7 +152,9 @@ An admin MUST be able to export all dashboards in the instance in a single opera An admin MUST be able to import a previously exported ZIP archive into the same or a different LaunchPad instance. The import process MUST validate the ZIP structure, create or update dashboards, handle collisions, and return a summary of imported/skipped records. -Each imported widget MUST arrive as it was exported, apart from what names the exporting instance. Its `content` (a text widget's text, the register an object-list reads, the widget an nc-widget proxies), its `customTitle`, `customIcon`, `styleConfig`, grid position, and for a tile its `tileType` and every tile field MUST be carried. Fields that point at a row or a workflow on the exporting instance MUST NOT be carried: `id`, `dashboardId`, `templatePlacementId`, `isCompulsory`, the `acknowledgement*` fields and `announcementKey`. One builder (`PlacementPayloadHydrator`) does this for every path that reads an archive: this import, the store install that feeds it, and the bundled showcase installer. +Each imported widget MUST arrive as it was exported, apart from what names the exporting instance. Its `content` (a text widget's text, the register an object-list reads, the widget an nc-widget proxies), its `customTitle`, `customIcon`, `styleConfig`, grid position, and for a tile its `tileType` and every tile field MUST be carried. Fields that point at a row or a workflow on the exporting instance MUST NOT be carried: `id`, `dashboardId`, `templatePlacementId`, `isCompulsory` (with one exception, an admin template: REQ-EXIM-012), the `acknowledgement*` fields and `announcementKey`. One builder (`PlacementPayloadHydrator`) does this for every path that reads an archive: this import, the store install that feeds it, and the bundled showcase installer. + +The import result MUST name each dashboard it created: `dashboards` is a list of `{sourceUuid, uuid, id}`, where `sourceUuid` is the UUID in the archive. The HTTP response keeps its three fields. An imported dashboard and each imported placement MUST be written with `created_at` and `updated_at` set to the time of the import. Both columns are NOT NULL on both tables. @@ -462,3 +464,32 @@ Each dashboard import MUST be wrapped in a database transaction to ensure consis @e2e exclude Needs 500 dashboards. That the streamed archive arrives valid and extractable, with its manifest and every dashboard file intact, is asserted at this instance's size by tests/e2e/dashboard-site-export.spec.ts. +### Requirement: REQ-EXIM-012 An admin template travels with its definition + +When the imported dashboard has `type: "admin_template"`, the import MUST carry what makes it that template: + +- each widget's `isCompulsory` flag. On a template the flag is part of the definition every copy is made from. On any other dashboard it stays an administrator's push on one instance and MUST NOT be carried (REQ-EXIM-004). +- `templateCategory` and `templateDescription`. +- no owner: `userId` MUST be null, as for a template made on the Templates page. It MUST NOT become the user who ran the import. + +`targetGroups` and `permissionLevel` already travel (REQ-EXIM-004). `isDefault` MUST still be imported as 0: making a template the default for everyone stays an explicit act on the receiving instance. `templatePreviewImage` is not carried, because asset import is not built (REQ-EXIM-007). + +**Why this was written down.** A template exported from one instance and imported on another arrived with every compulsory widget made optional, without its category and description, and owned by the importing administrator. Nothing reported it. For a template whose point is its compulsory widgets, the import produced a different template. + +#### Scenario: A template exported and imported again is the same template +- GIVEN an admin template with eight widgets, two of them compulsory, a category and a description +- WHEN an administrator exports it with `launchpad:export --scope=dashboard` and imports the archive on another instance with `launchpad:import` +- THEN the imported dashboard MUST be an admin template with no owner +- AND its name, description, grid columns, permission level, target groups, category and template description MUST equal the exported ones +- AND each of its widgets MUST equal the exported widget in type, position, size, title, style, content and `isCompulsory` +- AND it MUST NOT be the default template + +@e2e exclude Needs two instances, which neither CI nor the dev environment has. Pinned by ShippedTemplateServiceTest::testTheShippedTemplateSurvivesExportAndImport, which runs the real exporter and the real importer on a real archive. + +#### Scenario: A compulsory flag on a personal dashboard stays behind +- GIVEN a personal dashboard with a widget an administrator made compulsory +- WHEN it is exported and imported +- THEN the imported widget MUST NOT be compulsory + +@e2e exclude Pinned by ImportServiceTest::testCompulsoryIsCarriedForATemplateOnly. + diff --git a/openspec/specs/dashboard-icons/screens.md b/openspec/specs/dashboard-icons/screens.md new file mode 100644 index 000000000..7f9be18b9 --- /dev/null +++ b/openspec/specs/dashboard-icons/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpDashboardInstellingen https://identity.conduction.nl/screens/board?id=launchpad/LpDashboardInstellingen +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/dashboard-icons/spec.md b/openspec/specs/dashboard-icons/spec.md index d4e37d43f..912f4c553 100644 --- a/openspec/specs/dashboard-icons/spec.md +++ b/openspec/specs/dashboard-icons/spec.md @@ -59,8 +59,6 @@ Two shared Vue components consume these exports: ## Requirements -@e2e exclude icon-system scenarios test frontend registry + resource-upload API — resource uploads require admin API access not covered by UI-only tests - ### Requirement: REQ-ICON-001 Curated registry of built-in icons The system MUST maintain a curated registry of at least 15 built-in dashboard icons drawn from `vue-material-design-icons`. The registry MUST include at minimum these names: `ViewDashboard`, `Home`, `ChartBar`, `Cog`, `AccountGroup`, `Calendar`, `FileDocument`, `Bell`, `Star`, `Heart`, `BookOpenVariant`, `Lightbulb`, `RocketLaunch`, `Earth`, `Briefcase`. Any consumer that renders an icon by name MUST resolve it through this registry — there MUST NOT be parallel ad-hoc registries elsewhere. @@ -118,20 +116,22 @@ The system MUST maintain a curated registry of at least 15 built-in dashboard ic ### Requirement: REQ-ICON-003 Single picker source for admin UI -When the admin UI renders an icon picker (e.g. when creating or editing a dashboard), the available options MUST be enumerated from `Object.keys(DASHBOARD_ICONS)` directly. Hardcoding option lists in the picker template is forbidden so the picker stays in lock-step with the registry whenever icons are added or removed. +When the UI renders the dashboard icon picker (the dashboard settings modal and the group dashboard dialog), the available options MUST be enumerated from `Object.keys(DASHBOARD_ICONS)` of the shared nextcloud-vue registry directly, 57 names today, and a picked option MUST be stored as its registry name (Ruben, 21 Nov 2026). Hardcoding option lists in the picker template is forbidden so the picker stays in lock-step with the registry whenever icons are added or removed. Tile and organisation-navigation icon pickers are not dashboard icon pickers and keep the full MDI catalogue. #### Scenario: Picker reflects registry size -- GIVEN the registry has 15 entries -- WHEN the icon picker `<select>` renders -- THEN it MUST emit exactly 15 `<option>` elements (one per registry key) -- AND each option's `value` MUST match a registry key string +- GIVEN the registry has 57 entries +- WHEN the dashboard icon picker's Icons tab renders +- THEN it MUST offer exactly 57 icons (one per registry key) +- AND each icon's stored value MUST match a registry key string #### Scenario: Picker stays in sync when registry grows -- GIVEN the registry is extended to 17 entries in a future change -- WHEN the icon picker `<select>` renders without code changes -- THEN it MUST emit exactly 17 `<option>` elements +@e2e exclude Needs a code change to the registry module (a 17-entry DASHBOARD_ICONS), which an e2e run cannot make. The e2e for "Picker reflects registry size" compares the picker against the registry read at test time rather than a fixed 15, so it would catch this drift; no LaunchPad Vitest test pins it (tests/vitest/stubs/conduction-nextcloud-vue.js stubs the library wholesale). + +- GIVEN the registry is extended to 59 entries in a future change +- WHEN the dashboard icon picker renders without code changes +- THEN it MUST offer exactly 59 icons ### Requirement: REQ-ICON-004 Tree-shakeable imports @@ -139,6 +139,8 @@ Each icon component import in the registry module MUST be a separate `import` st #### Scenario: Bundle includes only referenced icons +@e2e exclude A production-bundle inspection of js/main.js, not browser behaviour. No test pins it: no LaunchPad Vitest or build check inspects the bundle. Its GIVEN (no other consumer of vue-material-design-icons) does not hold in LaunchPad, which imports many of those icons directly. + - GIVEN a production webpack build with no other consumers of `vue-material-design-icons` - WHEN the bundled `js/main.js` is inspected - THEN it MUST include at most the 15 icons listed in REQ-ICON-001 @@ -146,6 +148,8 @@ Each icon component import in the registry module MUST be a separate `import` st #### Scenario: No wildcard imports in registry module +@e2e exclude A source-code fact, not browser behaviour. `src/constants/dashboardIcons.js` never existed in this repository (`git log --all`); the registry is `components/CnWidgetGrid/widgetIcons.js` in @conduction/nextcloud-vue, which imports each icon on its own line. No LaunchPad test pins it. + - GIVEN the source file `src/constants/dashboardIcons.js` - WHEN its import statements are inspected - THEN none MUST use `import *` syntax against `vue-material-design-icons` @@ -218,13 +222,15 @@ The shared `IconRenderer` component MUST accept a single `name` prop (string or #### Scenario: Alt text for custom URL icons +@e2e exclude No LaunchPad surface passes an `alt` prop to the renderer (CnDashboardIcon in @conduction/nextcloud-vue; grep `CnDashboardIcon` under src/), so `alt="Marketing"` cannot be reached from the browser. No LaunchPad Vitest test pins the prop (the library is stubbed in tests/vitest/stubs/conduction-nextcloud-vue.js). The fallback clause, a non-empty alt with no prop, is asserted in passing by tests/e2e/dashboard-icons.spec.ts on every URL icon in the switcher. + - GIVEN `IconRenderer` is rendered with `name="/apps/launchpad/resource/abc.png"` and an `alt` prop of `"Marketing"` - THEN the rendered `<img>` MUST have `alt="Marketing"` - AND when no `alt` prop is supplied the rendered `<img>` MUST fall back to a non-empty default (e.g. the dashboard or widget name) ### Requirement: IconPicker dual-input UX (REQ-ICON-008) -The `IconPicker` component MUST present BOTH affordances visible simultaneously: a `<select>` of registry option names (per REQ-ICON-003) AND an "Upload icon" `<input type="file" accept="image/*">` button. Selecting either MUST update the same `v-model` value: a registry option assigns the option string, an upload POSTs to the resource-uploads endpoint and assigns the returned URL string. A 24×24 preview thumbnail of the current value MUST be rendered via `IconRenderer`. +The dashboard icon picker is nextcloud-vue's `CnIconBrowser`, shown inline. It MUST offer BOTH affordances: an Icons tab with the registry names (per REQ-ICON-003) AND a Custom tab with an upload (`<input type="file" accept="image/*">`). Either MUST update the same value: a registry icon assigns its name, an upload POSTs to the resource-uploads endpoint and assigns the returned URL string. A preview of the current value MUST be rendered via `CnDashboardIcon` (Ruben, 21 Nov 2026, following the product). #### Scenario: Switching from built-in to custom @@ -236,7 +242,7 @@ The `IconPicker` component MUST present BOTH affordances visible simultaneously: #### Scenario: Switching from custom back to built-in - GIVEN v-model value is `/apps/launchpad/resource/abc.png` -- WHEN the user picks `"Home"` from the `<select>` +- WHEN the user picks `"Home"` on the Icons tab - THEN the v-model value MUST become `"Home"` - AND the preview MUST switch from `<img>` to `<svg>` (Home) - NOTE: switching away does NOT delete the previously uploaded resource (resource lifecycle is owned by `resource-uploads` capability) diff --git a/openspec/specs/dashboard-kiosk-mode/screens.md b/openspec/specs/dashboard-kiosk-mode/screens.md new file mode 100644 index 000000000..6699f9d10 --- /dev/null +++ b/openspec/specs/dashboard-kiosk-mode/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpKiosk https://identity.conduction.nl/screens/board?id=launchpad/LpKiosk diff --git a/openspec/specs/dashboard-kiosk-mode/spec.md b/openspec/specs/dashboard-kiosk-mode/spec.md index 761548be9..28aa25a5b 100644 --- a/openspec/specs/dashboard-kiosk-mode/spec.md +++ b/openspec/specs/dashboard-kiosk-mode/spec.md @@ -12,7 +12,10 @@ Turns LaunchPad dashboards into unattended signage by rendering them chrome-less The system MUST support a `kiosk=1` query flag on the authenticated single-dashboard route and on the public-share render route that renders the dashboard full-viewport with all Nextcloud and LaunchPad chrome suppressed (header, app navigation, switcher -sidebar, edit and context-menu affordances, scrollbars). +sidebar, edit and context-menu affordances, scrollbars). The server renders both pages +without the Nextcloud layout when the flag is set; the flag changes no access check. +Escape reloads the same route without the flag, so the chrome comes back (Ruben, +21 Nov 2026). #### Scenario: Authenticated kiosk render hides all chrome - GIVEN a logged-in user "display-lobby" with access to dashboard uuid `550e8400-e29b-41d4-a716-446655440001` @@ -118,11 +121,17 @@ HTTP 404 without leaking whether the token ever existed, and the route MUST shar - THEN the system MUST return HTTP 404 in both cases with an identical response shape #### Scenario: Playlist render is read-only + +@e2e exclude no request a browser can issue is both a playlist bearer and a mutation: the read-only marker is PublicShareContext, request-scoped and set only inside KioskController::render(), and every mutation endpoint sent with nothing but the token is refused as unauthenticated (401) before that marker matters, so a passing test would prove the wrong thing; the marker is asserted by KioskControllerTest::testRenderReturns200AndMarksBearer and its refusal by PublicShareContextTest::testRequireMutableThrowsAfterMarkBearer, the same split as dashboard-public-share's read-only scenarios + - GIVEN a client rendering a playlist token - WHEN any mutation endpoint (placement create, dashboard update/delete) is attempted with the playlist bearer context - THEN the system MUST return HTTP 403, identically to public-share read-only enforcement (REQ-PSHR-006 of `dashboard-public-share`) #### Scenario: Token scanning shares the public-share throttle bucket + +@e2e exclude the `launchpad_share_access` bucket is IP-global, and playwright.config.ts runs every spec serially from one runner IP, so driving it to 429 would hand 429 to every later public-share and kiosk test in the job; that the kiosk 404 registers its attempt on the shared action is asserted by KioskControllerTest::testRenderReturns404WithThrottleOnUnknownToken (and the 429 path by PublicShareControllerTest::testUnlockReturns429WhenThrottled) + - GIVEN an IP that has already accumulated failed `launchpad_share_access` attempts via the `/s/{token}` route - WHEN the same IP probes `/kiosk/{token}` with invalid tokens - THEN the attempts MUST count against the same `launchpad_share_access` throttle bucket @@ -139,7 +148,12 @@ HTTP 404 without leaking whether the token ever existed, and the route MUST shar A kiosk view MUST re-fetch the visible dashboard's widget data every `refreshSeconds` (playlist setting, or default 300 for flag-based kiosk views) and update widgets in place without a full page reload. Rotation entries MUST be fetched just-in-time so each -dwell slot shows data no older than one dwell cycle. +dwell slot shows data no older than one dwell cycle: the player reads one entry from +`GET /kiosk/{token}/dashboards/{uuid}` about 5 seconds before its turn. That route +answers only for a dashboard that is an entry of the playlist; an unknown or revoked +token answers 404 and counts against the `launchpad_share_access` throttle bucket, and +a dashboard that is not an entry, or was deleted, answers the same 404 without a +throttle attempt (Ruben, 21 Nov 2026). #### Scenario: Widget data refreshes without page reload - GIVEN a kiosk view displaying a dashboard with `refreshSeconds: 300` @@ -154,6 +168,9 @@ dwell slot shows data no older than one dwell cycle. - AND the switch at dwell expiry MUST display the freshly fetched data without a visible loading state #### Scenario: Refresh interval respects the clamp + +@e2e exclude the flag-based view re-reads every 300 seconds (KIOSK_REFRESH_MS in src/utils/kioskMode.js), and neither the spec nor the product names any way to configure a refresh value for it, so the clamp clause has no input a test could drive; the 300-second constant is used by src/views/Views.vue and the in-place reload is pinned by src/stores/__tests__/dashboard.visibility.spec.js + - GIVEN a flag-based kiosk view (`?kiosk=1`) with no playlist configuration - WHEN the view initializes - THEN the refresh interval MUST default to 300 seconds @@ -186,6 +203,9 @@ trace), and a watchdog restarts a stalled rotation. - AND the client MUST continue polling and recover automatically once a fetch succeeds #### Scenario: Watchdog restarts a stalled rotation + +@e2e exclude never built: src/views/KioskPlayerView.vue has no watchdog, and the kioskRotationEngine.js the archived tasks.md (task 6) describes never existed in git history; a stall cannot be induced from outside a player whose dwell timers work, so there is nothing a browser test can trigger. No unit test pins it + - GIVEN a playlist whose longest dwell is 90 seconds - WHEN no rotation advance has occurred within 180 seconds (2 × max dwell) - THEN the client MUST restart its rotation engine from the first available entry @@ -195,8 +215,6 @@ trace), and a watchdog restarts a stalled rotation. ### Requirement: An administrator manages kiosk playlists (REQ-KIOSKUI-001) -@e2e exclude the player needs a live playlist and a logged-out browser; rotation, refresh, revocation and the network blip are asserted in src/views/__tests__/KioskPlayerView.spec.js, the playlist form in src/dialogs/__tests__/KioskPlaylistDialog.spec.js and src/components/admin/tabs/__tests__/KioskTab.spec.js, the HTML route in tests/Unit/Controller/KioskControllerTest.php - Administration MUST have a Kiosk section that lists playlists and creates, edits and revokes them, with a dwell time per dashboard within the service limits and a public link that can be copied. #### Scenario: Create a lobby playlist @@ -213,8 +231,6 @@ Administration MUST have a Kiosk section that lists playlists and creates, edits ### Requirement: The kiosk link plays the playlist without a login (REQ-KIOSKUI-002) -@e2e exclude the player needs a live playlist and a logged-out browser; rotation, refresh, revocation and the network blip are asserted in src/views/__tests__/KioskPlayerView.spec.js, the playlist form in src/dialogs/__tests__/KioskPlaylistDialog.spec.js and src/components/admin/tabs/__tests__/KioskTab.spec.js, the HTML route in tests/Unit/Controller/KioskControllerTest.php - Opening `/kiosk/{token}` in a browser MUST show each dashboard of the playlist full screen for its dwell time in order, repeat from the start, and re-read the playlist on the refresh interval, with no login and no controls. #### Scenario: Rotation @@ -234,3 +250,22 @@ Opening `/kiosk/{token}` in a browser MUST show each dashboard of the playlist f - **GIVEN** the screen loses its connection for one minute - **WHEN** the refresh interval passes - **THEN** it keeps showing the last playlist and tries again + +### Requirement: The kiosk screen shows where the playlist is (REQ-KIOSKUI-003) + +While a kiosk link plays a playlist of more than one dashboard, the screen SHALL show in its bottom right corner the +position of the current dashboard and the seconds until the next one ("2 van 4 · volgende over 18 s", in the +playlist's language), updated every second, in small text that meets AA contrast on the dashboard's background. It +SHALL NOT be a control and SHALL NOT take focus. A playlist of one dashboard SHALL show no position line. The line +SHALL be hidden from screen readers except for a polite announcement when the dashboard changes, naming the new one. + +#### Scenario: The canteen screen + +- **GIVEN** the playlist "Kantine" holds four dashboards of 30 seconds each, and the second has shown for 12 seconds +- **WHEN** someone looks at the screen +- **THEN** the bottom right reads "2 van 4 · volgende over 18 s" + +#### Scenario: One dashboard + +- **GIVEN** a playlist with one dashboard +- **THEN** the screen shows no position line diff --git a/openspec/specs/dashboard-language-content/screens.md b/openspec/specs/dashboard-language-content/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/dashboard-language-content/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/dashboard-language-content/spec.md b/openspec/specs/dashboard-language-content/spec.md index 02a51e1d9..c6c368560 100644 --- a/openspec/specs/dashboard-language-content/spec.md +++ b/openspec/specs/dashboard-language-content/spec.md @@ -34,8 +34,6 @@ Indexes: ## Requirements -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: REQ-DASH-038 Translation Schema The system MUST store per-language content variants for a dashboard in a dedicated `oc_launchpad_dash_translations` table. Each variant holds a localised widget tree, name, and description, with exactly one row per (dashboard, language) pair. @@ -45,6 +43,7 @@ The system MUST store per-language content variants for a dashboard in a dedicat - GIVEN the schema migration is applied - THEN the `oc_launchpad_dash_translations` table MUST exist with columns: `id` (auto-increment primary key), `dashboardUuid VARCHAR(36)`, `languageCode VARCHAR(16)`, `name VARCHAR(255)`, `description LONGTEXT`, `widgetTreeJson MEDIUMTEXT`, `isPrimary SMALLINT(0/1)`, `createdAt DATETIME`, `updatedAt DATETIME` - AND a composite unique constraint MUST exist on `(dashboardUuid, languageCode)` to prevent duplicate language variants per dashboard +@e2e exclude the schema shape (columns, types, indexes) is not observable over HTTP, and no test pins lib/Migration/DashboardTranslationTableBuilder.php (none exists); the unique pair's effect is asserted by duplicate-language-returns-conflict-error #### Scenario: Primary variant enforcement @@ -58,6 +57,7 @@ The system MUST store per-language content variants for a dashboard in a dedicat - WHEN the schema migration runs - THEN the system MUST auto-create a primary translation row with the dashboard's existing `widgetTreeJson`, `name`, `description`, and `languageCode` set to the dashboard owner's Nextcloud locale (`\OCP\IConfig::getUserValue($userId, 'core', 'lang')`, fallback to 'en' if not set) - AND the existing widget tree MUST remain in `oc_launchpad_dashboards` during the transition period (marked for future deprecation) +@e2e exclude never built: lib/Migration/Version001017Date20260502130000.php only creates the table (its header says the backfill happens lazily in the service, not at migration time); the lazy seed is pinned in tests/Unit/Service/DashboardTranslationServiceTest.php (testSeedPrimaryUsesOwnerLocale, testSeedPrimaryFallsBackToEnglish) #### Scenario: Variant isolation from dashboard record @@ -71,11 +71,11 @@ The system MUST resolve the appropriate translation variant for a requesting use #### Scenario: Exact language match -- GIVEN a dashboard has variants for 'en', 'nl', 'de-DE' +- GIVEN a dashboard has variants for 'en', 'nl' and 'de' (created as 'de-DE', stored under its base code 'de') - AND the user's Nextcloud locale is set to 'de-DE' - WHEN `GET /api/dashboards/{uuid}` is called (no ?lang param) -- THEN the system MUST return the 'de-DE' variant -- AND the response MUST include `currentLanguage: 'de-DE'`, `isFallback: false` +- THEN the system MUST return the 'de' variant +- AND the response MUST include `currentLanguage: 'de'`, `isFallback: false` #### Scenario: Language-part match (prefix fallback) @@ -112,7 +112,7 @@ The system MUST resolve the appropriate translation variant for a requesting use - GIVEN a dashboard has variants for 'en', 'nl', 'de-DE', 'fr' - WHEN `GET /api/dashboards/{uuid}` is called -- THEN the response MUST include `availableLanguages: ['de-DE', 'en', 'fr', 'nl']` (sorted alphabetically) +- THEN the response MUST include `availableLanguages: ['de', 'en', 'fr', 'nl']` (sorted alphabetically; a variant is stored under its base language code, so 'de-DE' is listed as 'de') ### Requirement: REQ-DASH-040 Create Translation Variant @@ -284,6 +284,7 @@ Existing dashboards without translation rows MUST continue to function as before - THEN the system MUST treat the dashboard's existing `widgetTreeJson`, `name`, `description` as the primary variant - AND the response MUST include `availableLanguages: ['en']` (or the owner's locale if available) - AND MUST be indistinguishable from a post-migration dashboard with one primary variant +@e2e exclude needs a dashboard with no translation rows, and every create path seeds one (DashboardService::completeNewDashboard); the in-memory materialisation is pinned in tests/Unit/Controller/DashboardTranslationApiControllerResolvedTest.php and tests/Unit/Service/DashboardTranslationServiceTest.php (testMaterialiseLegacyVariantUsesDashboardFields) #### Scenario: Post-migration, dashboard has backfilled primary translation @@ -291,6 +292,7 @@ Existing dashboards without translation rows MUST continue to function as before - WHEN a query is issued for the dashboard's translations - THEN exactly one translation row MUST exist with `isPrimary=1` - AND the row's `languageCode` MUST match the dashboard owner's Nextcloud locale at migration time (or 'en' fallback) +@e2e exclude needs a dashboard that predates the migration, and the migration has no backfill step (see Backwards-compatible backfill); the seed in the owner's language is pinned in tests/Unit/Service/DashboardTranslationServiceTest.php (testSeedPrimaryUsesOwnerLocale, testSeedPrimaryIdempotent) #### Scenario: Dashboard deletion cascades to translations @@ -299,6 +301,7 @@ Existing dashboards without translation rows MUST continue to function as before - THEN the system MUST delete the dashboard record - AND all 3 translation rows MUST be cascade-deleted via `DashboardTranslationMapper::deleteByDashboardUuid()` - AND subsequent queries for the dashboard's translations MUST return empty results +@e2e exclude a deleted dashboard's translation rows cannot be observed: every translation route answers 404 once the parent is gone. Only the delegation is pinned (tests/Unit/Service/DashboardTranslationServiceTest.php testDeleteAllForDashboardForwardsToMapper); no test pins that DashboardService::deleteChildRows calls it #### Scenario: Admin template dashboard with translations @@ -307,6 +310,7 @@ Existing dashboards without translation rows MUST continue to function as before - THEN the system MUST create a personal dashboard copy with its own primary variant in the user's locale - AND the copied variant's widget tree, name, description MUST be seeded from the template's primary variant - AND the copied dashboard MUST be independent from the template (translation updates to the template do NOT affect the copy) +@e2e exclude cannot be seeded: admin templates are stored with userId null (lib/Service/AdminTemplateService.php:263) and every translation write requires the caller to own the dashboard (DashboardTranslationApiController::assertOwner), so no request can give a template variants; TemplateService::createDashboardFromTemplate also seeds no translation for the copy. No test pins it #### Scenario: Migration rollback removes translation table @@ -314,11 +318,10 @@ Existing dashboards without translation rows MUST continue to function as before - WHEN the migration is rolled back via `postSchemaChange()` in reverse - THEN the `oc_launchpad_dash_translations` table MUST be dropped - AND existing dashboard records MUST remain unaffected (the widget tree is still in `oc_launchpad_dashboards`) +@e2e exclude never built: lib/Migration/Version001017Date20260502130000.php has only changeSchema() and no rollback step (git log -S postSchemaChange on it finds nothing), and Nextcloud never runs migrations in reverse; no test exists ### Requirement: A dashboard owner manages language versions in the settings dialog (REQ-LANGUI-001) -@e2e exclude switching language and filtering need seeded variants and fields on a live instance; asserted in src/components/Workspace/config/__tests__/LanguagesTab.spec.js, src/components/Workspace/config/__tests__/DetailsTab.spec.js, src/components/Workspace/__tests__/DashboardLanguageHeading.spec.js, src/components/admin/__tests__/MetadataFieldsSettings.spec.js, src/views/__tests__/ViewsDetailFilter.spec.js and tests/Unit/Controller/DashboardApiControllerLanguagesAndDetailsTest.php - The dashboard settings dialog MUST have a "Languages" tab, hidden while creating, listing each variant with its language and marking the primary. It MUST let the owner add a variant blank or copied from an existing language, edit its name and description, delete a non-primary variant, and make another variant primary. #### Scenario: Add a Dutch version @@ -335,8 +338,6 @@ The dashboard settings dialog MUST have a "Languages" tab, hidden while creating ### Requirement: The workspace page shows the reader's language (REQ-LANGUI-002) -@e2e exclude switching language and filtering need seeded variants and fields on a live instance; asserted in src/components/Workspace/config/__tests__/LanguagesTab.spec.js, src/components/Workspace/config/__tests__/DetailsTab.spec.js, src/components/Workspace/__tests__/DashboardLanguageHeading.spec.js, src/components/admin/__tests__/MetadataFieldsSettings.spec.js, src/views/__tests__/ViewsDetailFilter.spec.js and tests/Unit/Controller/DashboardApiControllerLanguagesAndDetailsTest.php - When a dashboard has more than one variant, the workspace page MUST show the variant that matches the reader's Nextcloud language, and the primary with a visible note when none matches. #### Scenario: Reader in Dutch diff --git a/openspec/specs/dashboard-locking/screens.md b/openspec/specs/dashboard-locking/screens.md new file mode 100644 index 000000000..83af6f598 --- /dev/null +++ b/openspec/specs/dashboard-locking/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpBewerken diff --git a/openspec/specs/dashboard-locking/spec.md b/openspec/specs/dashboard-locking/spec.md index 13905500f..e3b4df789 100644 --- a/openspec/specs/dashboard-locking/spec.md +++ b/openspec/specs/dashboard-locking/spec.md @@ -28,8 +28,6 @@ Stale-lock cleanup is performed inline: `DashboardLockService` calls `DashboardL ## Requirements -@e2e exclude all scenarios test PHP DashboardLockService REST API — multi-tab locking race conditions cannot be reliably asserted in Playwright headless - ### Requirement: REQ-LOCK-001 Acquire Dashboard Lock A user MUST be able to acquire an exclusive write lock on a dashboard. Only one user (or admin) can hold a lock at a time. A second user attempting to acquire MUST receive the existing lock details in a conflict response. @@ -59,6 +57,8 @@ Same-user acquire is re-entrant: if the same user already holds the lock, the ac - `lastHeartbeat = ...` (current heartbeat timestamp; client computes implied expiry as `lastHeartbeat + 900s`) - AND bob MUST see a read-only banner on the dashboard with alice's display name and the implied lock expiry time +@e2e exclude removed from the page: its read-only banner clause cannot hold since building-edit-a-dashboard-together (594fe5c90) took the lock out of the workspace page (src/views/Views.vue, 'edit mode no longer takes a lock'). The HTTP half (409, no new lock) runs uncited in tests/e2e/dashboard-locking.spec.ts. The 409 body also deliberately omits userId (M2, DashboardLock::jsonSerializeConflict, pinned by DashboardLockApiControllerTest::testAcquireConflictResponseDoesNotLeakUserId), which contradicts the scenario's userId clause + #### Scenario: Same user with two browser tabs (re-entrant acquire) - GIVEN alice has tab-1 open on dashboard "d1" and has already acquired the lock - WHEN alice opens tab-2 on the same dashboard and tab-2 sends `POST /api/dashboards/d1/lock` @@ -74,6 +74,8 @@ Same-user acquire is re-entrant: if the same user already holds the lock, the ac - AND bob MUST receive HTTP 200 with a new lock owned by bob - AND alice's expired lock MUST be deleted before the new lock is created +@e2e exclude needs a lock whose lastHeartbeat is more than 15 minutes old: no endpoint backdates a heartbeat and e2e cannot move the server clock, so the only way is 900 s of real waiting per case; expiry is pinned by DashboardLockTest::testIsExpiredReturnsTrueForOldHeartbeat and the inline cleanup by DashboardLockServiceTest::testGetLockStateRunsInlineCleanup + ### Requirement: REQ-LOCK-002 Heartbeat to Extend Lock A lock owner MUST be able to extend the lock by sending a heartbeat. Ownership is determined by `userId` alone. The heartbeat MUST only succeed if the caller is the current lock owner. The recommended heartbeat cadence is every 60 seconds, giving a 15× safety margin against the 15-minute TTL. @@ -104,6 +106,8 @@ A lock owner MUST be able to extend the lock by sending a heartbeat. Ownership i - AND alice MUST retain exclusive edit access indefinitely - NOTE: The recommended heartbeat cadence is every 60 seconds (15× safety margin against the 15-minute TTL); the server does not enforce a minimum frequency +@e2e exclude needs a browser held open past the 15-minute TTL with heartbeats in between, i.e. more than 900 s of real time; a heartbeat moving lastHeartbeat is asserted by the e2e for lock-owner-extends-lease-with-heartbeat, and a fresh heartbeat counting as live by DashboardLockTest::testIsExpiredReturnsFalseForFreshHeartbeat + ### Requirement: REQ-LOCK-003 Release Dashboard Lock A lock owner or administrator MUST be able to release a lock, returning the dashboard to an unlocked state. Non-owners MUST NOT be able to release another user's lock unless they are admins. Ownership is determined by `userId` alone. @@ -130,6 +134,8 @@ A lock owner or administrator MUST be able to release a lock, returning the dash - AND the response MUST return HTTP 204 - AND the action MUST be audit-logged separately (via REQ-LOCK-006) +@e2e exclude the audit-log clause cannot be observed over HTTP: the line is written with LoggerInterface::info() (lib/Service/DashboardLockService.php), which Nextcloud's default loglevel 2 discards, and no endpoint the suite may call serves the log; no PHPUnit test asserts the info() call either (DashboardLockServiceTest::testReleaseByAdminSucceedsViaOverride asserts only the delete). The 204 and the deletion run uncited in tests/e2e/dashboard-locking.spec.ts + #### Scenario: Release non-existent lock - GIVEN dashboard "d1" has no lock - WHEN alice sends `DELETE /api/dashboards/d1/lock` @@ -164,6 +170,8 @@ Any logged-in user MUST be able to query the current lock state of a dashboard t - AND the response MUST NOT leak expired lock details - AND bob MUST be able to acquire a new lock immediately +@e2e exclude needs a lock whose lastHeartbeat is more than 15 minutes old: no endpoint backdates a heartbeat and e2e cannot move the server clock, so the only way is 900 s of real waiting per case; expiry is pinned by DashboardLockTest::testIsExpiredReturnsTrueForOldHeartbeat and the inline cleanup by DashboardLockServiceTest::testGetLockStateRunsInlineCleanup + #### Scenario: Cached displayName is stale - GIVEN alice acquires a lock on dashboard "d1" - AND alice's display name is later changed in Nextcloud (e.g., "Alice Smith" → "Alice S.") @@ -181,6 +189,8 @@ Locks MUST automatically become stale when `lastHeartbeat + LOCK_TIMEOUT` (15 mi - THEN the system MUST perform inline cleanup and return HTTP 404 (or null) - AND the response MUST NOT include the stale lock +@e2e exclude needs a lock whose lastHeartbeat is more than 15 minutes old: no endpoint backdates a heartbeat and e2e cannot move the server clock, so the only way is 900 s of real waiting per case; expiry is pinned by DashboardLockTest::testIsExpiredReturnsTrueForOldHeartbeat and the inline cleanup by DashboardLockServiceTest::testGetLockStateRunsInlineCleanup + #### Scenario: Stale lock does not block new acquisition - GIVEN dashboard "d1" has a lock where `lastHeartbeat` is more than 15 minutes in the past - WHEN bob sends `POST /api/dashboards/d1/lock` @@ -188,6 +198,8 @@ Locks MUST automatically become stale when `lastHeartbeat + LOCK_TIMEOUT` (15 mi - AND the inline cleanup MUST delete the stale row before inserting the new lock - AND bob MUST receive HTTP 200 with a new lock +@e2e exclude needs a lock whose lastHeartbeat is more than 15 minutes old: no endpoint backdates a heartbeat and e2e cannot move the server clock, so the only way is 900 s of real waiting per case; expiry is pinned by DashboardLockTest::testIsExpiredReturnsTrueForOldHeartbeat and the inline cleanup by DashboardLockServiceTest::testGetLockStateRunsInlineCleanup + #### Scenario: Network outage does not prevent lock release - GIVEN alice acquires a lock and then closes her browser (crash or network cut) - AND the lock expires after 15 minutes of inactivity (no heartbeats received) @@ -195,12 +207,16 @@ Locks MUST automatically become stale when `lastHeartbeat + LOCK_TIMEOUT` (15 mi - THEN bob MUST succeed immediately (no manual admin intervention required for correctness) - NOTE: Inline cleanup removes the stale row at acquire time; no background sweeper is required for correctness +@e2e exclude needs a lock whose lastHeartbeat is more than 15 minutes old: no endpoint backdates a heartbeat and e2e cannot move the server clock, so the only way is 900 s of real waiting per case; expiry is pinned by DashboardLockTest::testIsExpiredReturnsTrueForOldHeartbeat and the inline cleanup by DashboardLockServiceTest::testGetLockStateRunsInlineCleanup + #### Scenario: Default TTL is 15 minutes - GIVEN alice acquires a lock on dashboard "d1" at time `T0` - THEN the lock's effective expiry is `T0 + 900 seconds` (15 minutes), computed from `lastHeartbeat` - WHEN 901 seconds have passed without a heartbeat - THEN the lock MUST be considered stale and treated as non-existent on the next read or acquire +@e2e exclude needs a lock whose lastHeartbeat is more than 15 minutes old: no endpoint backdates a heartbeat and e2e cannot move the server clock, so the only way is 900 s of real waiting per case; expiry is pinned by DashboardLockTest::testIsExpiredReturnsTrueForOldHeartbeat and the inline cleanup by DashboardLockServiceTest::testGetLockStateRunsInlineCleanup; the 900 s lease (lockTimeoutSec, expiresAt = lastHeartbeat + 900 s) is asserted by the e2e for get-active-lock + ### Requirement: REQ-LOCK-006 Admin Override and Audit Logging A Nextcloud administrator MUST be able to release a lock from any user via `POST /api/dashboards/{uuid}/lock/force-release`. This action MUST be logged via `LoggerInterface` (PSR logger) with the original owner's name and the admin's action. The dashboard is returned to an unlocked state; the admin may then acquire a new lock via the normal path if they wish to edit. @@ -214,6 +230,8 @@ A Nextcloud administrator MUST be able to release a lock from any user via `POST - AND the action MUST be logged via `LoggerInterface::info()` with the original owner's userId, the dashboard UUID, and the admin's userId - AND dashboard "d1" MUST be in an unlocked state after this call +@e2e exclude the audit-log clause cannot be observed over HTTP: the line is written with LoggerInterface::info() (lib/Service/DashboardLockService.php), which Nextcloud's default loglevel 2 discards, and no endpoint the suite may call serves the log; no PHPUnit test asserts the info() call either (DashboardLockServiceTest::testForceReleaseByAdminDeletesLock asserts only the delete). The 200 and the unlocked state are asserted by the e2e tests for admin-acquires-lock-after-force-release-normal-flow and non-admin-cannot-force-release + #### Scenario: Admin acquires lock after force-release (normal flow) - GIVEN charlie (admin) has just force-released alice's lock on dashboard "d1" - WHEN charlie sends `POST /api/dashboards/d1/lock` @@ -233,6 +251,8 @@ A Nextcloud administrator MUST be able to release a lock from any user via `POST - THEN charlie MUST receive HTTP 200 (or HTTP 204) — idempotent - AND the action MUST still be logged +@e2e exclude the audit-log clause cannot be observed over HTTP: the line is written with LoggerInterface::info() (lib/Service/DashboardLockService.php), which Nextcloud's default loglevel 2 discards, and no endpoint the suite may call serves the log; no PHPUnit test asserts the info() call either (DashboardLockServiceTest::testForceReleaseOnMissingLockIsIdempotent asserts only the delete); the expired half also needs a heartbeat older than 15 minutes + ### Requirement: REQ-LOCK-007 Contention and Consistency When multiple users attempt to acquire the same lock simultaneously (network race), only one MUST succeed with HTTP 200. All others MUST receive HTTP 409 with the same lock object. @@ -261,6 +281,8 @@ When multiple users attempt to acquire the same lock simultaneously (network rac - Bob's acquire succeeds first → alice's release succeeds with HTTP 204 (idempotent; lock is gone but already not hers) - AND no lock MUST be lost or duplicated +@e2e exclude needs a chosen interleaving of two concurrent requests, which HTTP cannot force; and its second branch (bob's acquire succeeding while alice still holds the lock, then alice's release answering 204) contradicts REQ-LOCK-001, so the scenario text needs fixing before it can be tested. Release idempotency is asserted by the e2e for release-non-existent-lock + ### Requirement: REQ-LOCK-008 Lock Lifecycle on Dashboard Deletion When a dashboard is deleted, its lock (if any) MUST be automatically deleted as a cascade. No manual cleanup is required. @@ -283,8 +305,6 @@ When a dashboard is deleted, its lock (if any) MUST be automatically deleted as ### Requirement: The workspace page holds the lock while a person edits (REQ-LOCKUI-001) -@e2e exclude the lock needs two live sessions against one dashboard; the page behaviour is asserted in src/views/__tests__/ViewsEditLock.spec.js and src/composables/__tests__/useDashboardLock.spec.js, the banner in src/components/Workspace/__tests__/EditLockBanner.spec.js - Entering edit mode on a dashboard MUST acquire the dashboard lock first. The page MUST enter edit mode only when the lock is granted. Leaving edit mode, saving, or closing the page MUST release it. #### Scenario: Second editor is stopped @@ -293,15 +313,17 @@ Entering edit mode on a dashboard MUST acquire the dashboard lock first. The pag - **WHEN** Pieter clicks Edit on "Finance" in the Workspace page - **THEN** the page stays read-only, a banner reads "Sanne is editing this dashboard", and the grid shows no edit handles +@e2e exclude removed from the page: building-edit-a-dashboard-together (594fe5c90) took the lock out of the workspace page. src/views/Views.vue no longer uses useDashboardLock (edit mode announces a presence instead, see its `presence: useDashboardPresence` comment 'edit mode no longer takes a lock'), so there is no page behaviour to drive; the leftover pieces are pinned by src/composables/__tests__/useDashboardLock.spec.js 'REQ-LOCKUI-001: a 409 blocks and names the holder' and src/components/Workspace/__tests__/EditLockBanner.spec.js 'REQ-LOCKUI-001: names the colleague who is editing' + #### Scenario: Lock is released on leaving - **GIVEN** Sanne holds the lock on "Finance" - **WHEN** she leaves edit mode - **THEN** a `DELETE /api/dashboards/{uuid}/lock` is sent and Pieter can start editing at once -### Requirement: The lock is refreshed and lost safely (REQ-LOCKUI-002) +@e2e exclude removed from the page: building-edit-a-dashboard-together (594fe5c90) took the lock out of the workspace page. src/views/Views.vue no longer uses useDashboardLock (edit mode announces a presence instead, see its `presence: useDashboardPresence` comment 'edit mode no longer takes a lock'), so there is no page behaviour to drive; the leftover pieces are pinned by src/composables/__tests__/useDashboardLock.spec.js 'REQ-LOCKUI-001: release sends DELETE and stops refreshing' -@e2e exclude the lock needs two live sessions against one dashboard; the page behaviour is asserted in src/views/__tests__/ViewsEditLock.spec.js and src/composables/__tests__/useDashboardLock.spec.js, the banner in src/components/Workspace/__tests__/EditLockBanner.spec.js +### Requirement: The lock is refreshed and lost safely (REQ-LOCKUI-002) While a person edits, the page MUST refresh the lock at least every five minutes. If a refresh is answered with 404, the page MUST leave edit mode, keep the unsaved changes in memory and tell the person the lock was lost. @@ -311,9 +333,9 @@ While a person edits, the page MUST refresh the lock at least every five minutes - **WHEN** Sanne's next refresh returns 404 - **THEN** the page returns to read-only and a message says another person took over, with the unsaved edits still readable on screen -### Requirement: An administrator can take over a lock (REQ-LOCKUI-003) +@e2e exclude removed from the page: building-edit-a-dashboard-together (594fe5c90) took the lock out of the workspace page. src/views/Views.vue no longer uses useDashboardLock (edit mode announces a presence instead, see its `presence: useDashboardPresence` comment 'edit mode no longer takes a lock'), so there is no page behaviour to drive; the leftover pieces are pinned by src/composables/__tests__/useDashboardLock.spec.js 'REQ-LOCKUI-002: a 404 on refresh loses the lock and tells the page' and src/components/Workspace/__tests__/EditLockBanner.spec.js 'REQ-LOCKUI-002: says the lock was lost' -@e2e exclude the lock needs two live sessions against one dashboard; the page behaviour is asserted in src/views/__tests__/ViewsEditLock.spec.js and src/composables/__tests__/useDashboardLock.spec.js, the banner in src/components/Workspace/__tests__/EditLockBanner.spec.js +### Requirement: An administrator can take over a lock (REQ-LOCKUI-003) The banner MUST show a "Take over" button to administrators only. It MUST ask for confirmation, then force-release the lock and acquire it for the administrator. @@ -323,12 +345,16 @@ The banner MUST show a "Take over" button to administrators only. It MUST ask fo - **WHEN** Ruben clicks "Take over" and confirms - **THEN** the lock is force-released, Ruben enters edit mode, and Sanne sees the lost-lock message on her next refresh +@e2e exclude removed from the page: building-edit-a-dashboard-together (594fe5c90) took the lock out of the workspace page. src/views/Views.vue no longer uses useDashboardLock (edit mode announces a presence instead, see its `presence: useDashboardPresence` comment 'edit mode no longer takes a lock'), so there is no page behaviour to drive; the leftover pieces are pinned by src/composables/__tests__/useDashboardLock.spec.js 'REQ-LOCKUI-003: take over force-releases and then acquires' + #### Scenario: Non-admin has no button - **GIVEN** Sanne holds the lock and Pieter is not an administrator - **WHEN** Pieter opens the banner - **THEN** no "Take over" button is rendered +@e2e exclude removed from the page: building-edit-a-dashboard-together (594fe5c90) took the lock out of the workspace page. src/views/Views.vue no longer uses useDashboardLock (edit mode announces a presence instead, see its `presence: useDashboardPresence` comment 'edit mode no longer takes a lock'), so there is no page behaviour to drive; the leftover pieces are pinned by src/components/Workspace/__tests__/EditLockBanner.spec.js 'REQ-LOCKUI-003: administrators get "Take over", others do not' + ## Non-Functional Requirements - **Performance**: `POST /api/dashboards/{uuid}/lock` MUST complete within 100ms (inline cleanup DELETE + INSERT/UPDATE). `GET /api/dashboards/{uuid}/lock` MUST complete within 50ms (cleanup DELETE + SELECT with index on `dashboardUuid`). diff --git a/openspec/specs/dashboard-metadata-fields/screens.md b/openspec/specs/dashboard-metadata-fields/screens.md new file mode 100644 index 000000000..a88b54850 --- /dev/null +++ b/openspec/specs/dashboard-metadata-fields/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpDashboardInstellingen https://identity.conduction.nl/screens/board?id=launchpad/LpDashboardInstellingen diff --git a/openspec/specs/dashboard-metadata-fields/spec.md b/openspec/specs/dashboard-metadata-fields/spec.md index eeac6aa04..81fe82684 100644 --- a/openspec/specs/dashboard-metadata-fields/spec.md +++ b/openspec/specs/dashboard-metadata-fields/spec.md @@ -11,8 +11,6 @@ Dashboard Metadata Fields allow administrators to define custom, queryable attri ## Data Model -@e2e exclude all scenarios test REST CRUD for admin-defined fields — admin metadata UI not present in v1.0.5 - ### Metadata Field Definition (oc_launchpad_meta_fields) Stores the global registry of field definitions: @@ -150,6 +148,8 @@ Administrators MUST be able to delete field definitions. Deletion has two modes: - AND cascade-delete all 3 value rows - AND return HTTP 200 +@e2e exclude the cascade clause cannot be observed over HTTP: once the field is gone, `GET /api/dashboards/{uuid}/metadata` hides an orphaned value row exactly as it hides a deleted one, and no endpoint reads value rows by a deleted field id; pinned by tests/Unit/Db/MetadataFieldMapperTest.php::testDeleteWithCascadeDeletesValuesFirst, tests/Unit/Service/MetadataServiceTest.php::testDeleteFieldDefinitionCascadeWipesValues and tests/Unit/Controller/MetadataAdminControllerTest.php::testDeleteFieldCascadeSucceeds + #### Scenario: Delete field without cascade rejected when values exist - GIVEN a field id=5 with 3 corresponding value rows @@ -188,6 +188,8 @@ Users MUST be able to read all metadata values for a given dashboard as a flat k - AND MUST log a warning describing the orphan - AND MUST NOT crash +@e2e exclude an orphaned value row cannot be made over HTTP (a plain delete of a field with values is refused with 409 and a cascade delete removes the rows), so it needs a direct database insert, and the warning is only visible in nextcloud.log; pinned by tests/Unit/Service/MetadataServiceTest.php::testGetMetadataForDashboardSkipsOrphans + ### Requirement: Dashboard Metadata Write (REQ-MDFL-005) Users MUST be able to set or update metadata values for a dashboard via a flat key-value object. Omitted keys are NOT deleted; only keys in the request body are upserted. Explicit empty values on optional fields delete the slot so it disappears from the read payload. @@ -293,8 +295,6 @@ Reading and writing metadata MUST be scoped to the dashboard's owner (for person ### Requirement: An administrator defines detail fields (REQ-MDUI-001) -@e2e exclude switching language and filtering need seeded variants and fields on a live instance; asserted in src/components/Workspace/config/__tests__/LanguagesTab.spec.js, src/components/Workspace/config/__tests__/DetailsTab.spec.js, src/components/Workspace/__tests__/DashboardLanguageHeading.spec.js, src/components/admin/__tests__/MetadataFieldsSettings.spec.js, src/views/__tests__/ViewsDetailFilter.spec.js and tests/Unit/Controller/DashboardApiControllerLanguagesAndDetailsTest.php - The administration settings MUST let an administrator create, edit and delete detail fields of type text, number, date, select and multi-select, with options for the two select types, and MUST refuse a select field without options with the service message. #### Scenario: Department field @@ -311,8 +311,6 @@ The administration settings MUST let an administrator create, edit and delete de ### Requirement: A dashboard owner fills in the details (REQ-MDUI-002) -@e2e exclude switching language and filtering need seeded variants and fields on a live instance; asserted in src/components/Workspace/config/__tests__/LanguagesTab.spec.js, src/components/Workspace/config/__tests__/DetailsTab.spec.js, src/components/Workspace/__tests__/DashboardLanguageHeading.spec.js, src/components/admin/__tests__/MetadataFieldsSettings.spec.js, src/views/__tests__/ViewsDetailFilter.spec.js and tests/Unit/Controller/DashboardApiControllerLanguagesAndDetailsTest.php - The dashboard settings dialog MUST have a "Details" tab showing one control per defined field and saving the values for that dashboard. #### Scenario: Set the owning department @@ -323,8 +321,6 @@ The dashboard settings dialog MUST have a "Details" tab showing one control per ### Requirement: Dashboards can be filtered by a detail (REQ-MDUI-003) -@e2e exclude switching language and filtering need seeded variants and fields on a live instance; asserted in src/components/Workspace/config/__tests__/LanguagesTab.spec.js, src/components/Workspace/config/__tests__/DetailsTab.spec.js, src/components/Workspace/__tests__/DashboardLanguageHeading.spec.js, src/components/admin/__tests__/MetadataFieldsSettings.spec.js, src/views/__tests__/ViewsDetailFilter.spec.js and tests/Unit/Controller/DashboardApiControllerLanguagesAndDetailsTest.php - The dashboards list endpoint MUST pass `metadata.<key>` query parameters to the metadata filter, and the switcher MUST offer "Filter by detail" when at least one field can be filtered. #### Scenario: Filter to Finance diff --git a/openspec/specs/dashboard-public-share/screens.md b/openspec/specs/dashboard-public-share/screens.md new file mode 100644 index 000000000..8b5beb40a --- /dev/null +++ b/openspec/specs/dashboard-public-share/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpDelen https://identity.conduction.nl/screens/board?id=launchpad/LpDelen +- LpPubliek https://identity.conduction.nl/screens/board?id=launchpad/LpPubliek +- No screen: the server slows down guessed passwords; a visitor only notices a slower answer (s-bruteforce) diff --git a/openspec/specs/dashboard-public-share/spec.md b/openspec/specs/dashboard-public-share/spec.md index 758075c2c..796ee0688 100644 --- a/openspec/specs/dashboard-public-share/spec.md +++ b/openspec/specs/dashboard-public-share/spec.md @@ -6,7 +6,9 @@ status: done ## Purpose Lets dashboard owners publish read-only public links to their dashboards, optionally protected by a password and an expiry date. Anonymous visitors render the dashboard through a unique share token while the system enforces read-only access, soft-revocation, brute-force throttling, debounced view counting, and a service-account read path for GroupFolder-backed content. + ## Requirements + ### Requirement: REQ-PSHR-001 Create Public Share Dashboard owners (or admins) MUST be able to create a public share with an optional password and expiry date. @@ -147,17 +149,16 @@ Password-protected shares MUST require a POST unlock before rendering via the pu - AND NOT block subsequent attempts (throttle is separate) #### Scenario: Unlock is throttled to prevent brute-force -@e2e exclude the throttle bucket is IP-global by design, so spending it would leave every later test in the same job facing 429 from a shared runner IP — playwright.config.ts runs `workers: 1`, `fullyParallel: false`, so there is no isolated IP to burn; asserted instead by PublicShareControllerTest::testUnlockReturns429WhenThrottled - GIVEN a public share with a password - WHEN an attacker sends 11 failed unlock attempts from IP `203.0.113.100` within 60 seconds - THEN the system MUST invoke Nextcloud's `IThrottler` service with action `launchpad_share_password` (limit: 10 per 60 s, IP-global) - AND return HTTP 429 (Too Many Requests) on the 11th attempt with `Retry-After` header -#### Scenario: Query param password alternative to header +#### Scenario: The password travels in a header, never in the query - GIVEN a password-protected share -- WHEN an anonymous user sends `GET /s/abc123?password=SecurePass123!` OR includes header `X-Share-Password: SecurePass123!` -- THEN the system MUST accept either method -- AND return HTTP 200 with the rendered dashboard (server-side verification) +- WHEN an anonymous user sends `GET /s/abc123` with header `X-Share-Password: SecurePass123!` +- THEN the system MUST return HTTP 200 with the rendered dashboard (server-side verification) +- AND a password in the query string (`?password=SecurePass123!`) MUST NOT unlock it: the answer is HTTP 401 `{passwordRequired: true}`, so a password never lands in an access log ### Requirement: REQ-PSHR-006 Read-Only Enforcement @@ -188,8 +189,6 @@ Any mutation endpoint accessed with a public-share token (not a logged-in Nextcl ### Requirement: REQ-PSHR-007 View Count Debouncing -@e2e exclude viewCount and lastViewedAt are DB columns that no anonymous response echoes back, so a browser cannot read the value the debounce is about; the three scenarios additionally need either distinct client IPs (one CI runner has one) or 60-second-plus wall-clock waits inside a 60s per-test timeout - View counts MUST be incremented at most once per minute per (token, client IP) pair to prevent refresh-spam inflation. #### Scenario: Repeated renders from same IP in one minute @@ -232,8 +231,6 @@ Shares with `expiresAt < now()` OR `revokedAt IS NOT NULL` MUST return HTTP 404 ### Requirement: REQ-PSHR-009 Brute-Force Protection -@e2e exclude all three scenarios spend the IThrottler `launchpad_share_password` bucket, which the spec itself defines as IP-global; playwright.config.ts runs workers:1 / fullyParallel:false from one runner IP, so a test that exhausts it hands 429 to every test that follows and the throttle-resets scenario additionally needs a 60s+ wall-clock wait against a 60s test timeout. The 429 path is asserted by PublicShareControllerTest::testUnlockReturns429WhenThrottled - Failed unlock attempts MUST be throttled via Nextcloud's `IThrottler` to prevent password guessing. #### Scenario: 10 failed unlocks per 60 seconds allowed @@ -258,11 +255,10 @@ Failed unlock attempts MUST be throttled via Nextcloud's `IThrottler` to prevent ### Requirement: REQ-PSHR-010 Service-Account File Read for GroupFolder Content -@e2e exclude both scenarios are about which account the GroupFolders backend is read as, and the GroupFolders app is not installed on the Playwright fixture — code-quality.yml `additional-apps` provisions only ConductionNL/openregister and neither seed script adds it — so the branch cannot be entered from a browser; same reason the sibling groupfolder-storage-backend spec carries - Public shares referencing dashboards with GroupFolder-backed content MUST use a service-account read path, not the viewer's session. #### Scenario: Public share rendering GroupFolder content uses service account +@e2e exclude the GroupFolders app is not installed on the Playwright fixture — code-quality.yml `additional-apps` provisions only ConductionNL/openregister and ConductionNL/integriq and neither seed script adds groupfolders — so the GroupFolder read path cannot be entered from a browser; same reason the sibling groupfolder-storage-backend spec carries - GIVEN a dashboard containing a widget that references a GroupFolder resource - WHEN an anonymous user renders the dashboard via a public share token - THEN the system MUST use a service-account file-read context (NOT the anonymous user's non-existent session) @@ -270,6 +266,7 @@ Public shares referencing dashboards with GroupFolder-backed content MUST use a - NOTE: The service-account context MUST be obtained before any GroupFolder filesystem call. The anonymous viewer's session (which does not exist) MUST NOT be passed to the GroupFolder ACL evaluator. Passing a null or non-existent user context causes reads to fail silently or return empty widget data. #### Scenario: Widget data accessible via service account +@e2e exclude same as the scenario above: needs the GroupFolders app and a folder ACL limited to a group, and the app is not installed on the Playwright fixture - GIVEN a GroupFolder resource is readable only by members of group "Engineering" - AND an anonymous public-share user is not a member of "Engineering" - WHEN the service-account render path is used @@ -278,3 +275,80 @@ Public shares referencing dashboards with GroupFolder-backed content MUST use a --- +### Requirement: Administrators choose a public link as the start page (REQ-PSP-001) + +An administrator MUST be able to pick one existing public link and switch on the public start page. The server MUST refuse a link with a password or with an expiry in the past. When the chosen link is later revoked, protected or expired, the start page MUST switch itself off and the admin section MUST say why. + +#### Scenario: Library start page + +- **GIVEN** Noor has a public link for the dashboard "Bibliotheek Noord" without a password +- **WHEN** she picks it as the public start page on the Sharing tab and switches it on +- **THEN** the Sharing tab shows "Public start page: Bibliotheek Noord" + +#### Scenario: Protected link refused + +- **GIVEN** a public link protected by a password +- **WHEN** Noor tries to pick it as the start page +- **THEN** it is not offered, and a direct request to save it returns 400 + +### Requirement: Signed-out visitors land on the start page (REQ-PSP-002) + +When the public start page is on, a visitor who is not signed in and opens the plain login page (no redirect address, no `direct` parameter) MUST be taken to the start page. A visitor following a deep link MUST still get the login form with the redirect kept. + +#### Scenario: Visitor opens the address + +- **GIVEN** the public start page is on +- **WHEN** a visitor who is not signed in opens `https://cloud.bibliotheek.nl/` +- **THEN** they see the dashboard "Bibliotheek Noord" read-only with a "Sign in" button + +#### Scenario: Deep link keeps the login form + +- **GIVEN** the public start page is on +- **WHEN** a signed-out staff member opens a link to `/apps/files/` +- **THEN** the login form shows, and after signing in they land in Files + +### Requirement: The start page offers a way in for staff (REQ-PSP-003) + +The start page MUST show a "Sign in" button that opens the login form with `direct=1`, so the visitor is not sent back to the start page and single sign-on setups keep working. + +#### Scenario: Staff member signs in + +- **GIVEN** Pieter is on the public start page +- **WHEN** he clicks "Sign in" +- **THEN** the login form opens at `/login?direct=1` +- **AND** after signing in he lands on his Workspace page + +#### Scenario: LaunchPad is the default app after install + +- **GIVEN** no default app is configured (Nextcloud's `defaultapp` system value is absent) +- **WHEN** LaunchPad is installed or upgraded +- **THEN** LaunchPad sets `defaultapp` to `launchpad`, so signing in lands on the Workspace page +- **AND** when a default app is configured, LaunchPad keeps it, including an empty value, which is what Nextcloud's own "reset to default" writes +- **AND** an upgrade never overwrites a default app the administrator chose after the install + +#### Scenario: The administrator switches it off + +- **GIVEN** LaunchPad set itself as the default app +- **WHEN** the administrator switches off "Open LaunchPad after signing in" in the admin settings (`defaultAppEnabled`, on by default) +- **THEN** LaunchPad unsets `defaultapp`, so Nextcloud's own default applies again +- **AND** when the administrator chose another default app in the meantime, that choice is kept +- **AND** switching it back on sets LaunchPad again only when no default app is set + +### Requirement: Live widgets on a public link and a kiosk screen (REQ-PSHR-011) + +On a public link and on a kiosk screen, the news widget SHALL list the published announcements targeted at everyone, the weather widget SHALL show its reading, and the live data widget SHALL show its value, each read through the link's or playlist's token and only for a placement that is on the shared dashboard. An announcement targeted at groups SHALL NOT be shown to an anonymous visitor. + +#### Scenario: The canteen screen + +- **GIVEN** the playlist Kantine shows Today in Zuiddrecht with News, Weather and Waiting time at the desk +- **WHEN** the screen shows it without a login +- **THEN** the cards show the news items, the weather and the waiting time + +### Requirement: Text in Markdown on public screens (REQ-PSHR-012) + +A text widget on a public link or kiosk screen SHALL render its Markdown (lists, emphasis, links), sanitised as on the dashboard. + +#### Scenario: Opening hours as a list + +- **GIVEN** the Opening hours widget holds a Markdown list +- **THEN** the public start page shows it as a list, not as raw text diff --git a/openspec/specs/dashboard-quota-limits/screens.md b/openspec/specs/dashboard-quota-limits/screens.md new file mode 100644 index 000000000..3e6555f18 --- /dev/null +++ b/openspec/specs/dashboard-quota-limits/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerAlgemeen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAlgemeen diff --git a/openspec/specs/dashboard-quota-limits/spec.md b/openspec/specs/dashboard-quota-limits/spec.md index 1e0c2fd68..551d1d50c 100644 --- a/openspec/specs/dashboard-quota-limits/spec.md +++ b/openspec/specs/dashboard-quota-limits/spec.md @@ -16,7 +16,6 @@ list response carries an additive `quota` envelope so the UI can disable creation affordances at the limit while the server check stays authoritative. -@e2e exclude no live-NC Playwright run available in this build context; quota enforcement (under/at/over limit, scope filtering, most-restrictive-wins, grandfathering, provisioning bypass) is covered by PHPUnit (QuotaService + service-wiring + controller 409/envelope tests), and the UI affordance logic (disabled "Add dashboard" / "Add widget", localised tooltip, envelope unwrap, 409 race handling) is covered by vitest store tests. Re-annotate with real Playwright tests once a live instance is wired (tasks.md Task 10). ## Requirements ### Requirement: REQ-QUOTA-001 Quota Admin Settings @@ -78,6 +77,8 @@ through the same check. - THEN each path MUST return the same HTTP 409 `quota_exceeded` response - NOTE: Enforcement lives in the dashboard service creation choke point; controllers only map the exception. A creation path that skips the check is a defect. +@e2e exclude only the fork path exists for a user: there is no duplicate-dashboard endpoint (none in appinfo/routes.php or src/services/api.js; `git log --all -S'duplicateDashboard' -- lib src appinfo` is empty), and importing a dashboard export is admin-only (`POST /api/admin/import`), so "each path" cannot be asserted; the fork 409 is asserted as an extra in tests/e2e/dashboard-quota-limits.spec.ts (creation-blocked-at-the-limit) and pinned by tests/Unit/Service/DashboardServiceQuotaWiringTest.php::testForkAsPersonalThrowsAtQuota + #### Scenario: Deleting a dashboard frees quota immediately - GIVEN user "alice" at her limit of 5 - WHEN she deletes one of her dashboards and then creates a new one @@ -123,6 +124,8 @@ already has that many placements. The rejection MUST be HTTP 409 with body - WHEN a user imports a dashboard export containing 55 placements - THEN the import MUST be rejected with the structured `quota_exceeded` error (not silently truncated to 40) +@e2e exclude never built for users: the only dashboard-export import is the admin-only `POST /api/admin/import`, and lib/Service/ImportService.php (insert at lines 448 and 478) writes dashboards and placements through the mappers without consulting QuotaService; no unit test pins an import quota + ### Requirement: REQ-QUOTA-004 Admin Provisioning Exemption The system MUST exempt admin-initiated provisioning — template rollout to groups, @@ -136,12 +139,16 @@ context on the quota service), never inferred from the acting user's group membe - THEN the rollout MUST succeed for alice - AND her personal-creation quota MUST remain enforced for her own subsequent creations +@e2e exclude never built as described: `QuotaService::runProvisioning()` has no caller in lib/ (`git log --all -S'runProvisioning(' -- lib` shows only 0b16993c6, which defines it), and a template copy is made only for a member who owns no dashboard yet (`DashboardService::templateStepsAside`, lib/Service/DashboardService.php:2189), so a user at a non-zero limit never receives a rollout copy to observe; the bypass itself is pinned by tests/Unit/Service/QuotaServiceTest.php::testProvisioningBypassesDashboardQuota + #### Scenario: Compulsory widget push exceeds the widget quota - GIVEN `max_widgets_per_dashboard = 40` and a user dashboard with 40 placements - WHEN an admin pushes a compulsory widget to that dashboard - THEN the push MUST succeed, putting the dashboard at 41 placements - AND the user's own next placement creation MUST still be rejected (over-quota state blocks new user creations only) +@e2e exclude never built: there is no compulsory-widget push endpoint in appinfo/routes.php (the nearest path, template resync `POST /api/admin/templates/{id}/resync`, copies template placements with the mapper in lib/Service/TemplateResyncService.php:483, outside QuotaService altogether, and is not a compulsory push), and `QuotaService::runProvisioning()` has no caller in lib/ (`git log --all -S'runProvisioning(' -- lib` shows only 0b16993c6, which defines it); the bypass is pinned by tests/Unit/Service/QuotaServiceTest.php::testProvisioningBypassesWidgetQuota + #### Scenario: Admins are bound by quotas for their own personal dashboards - GIVEN `max_dashboards_per_user = 5` and admin "carol" owns 5 personal dashboards - WHEN carol creates a sixth personal dashboard through the normal user flow diff --git a/openspec/specs/dashboard-reactions/screens.md b/openspec/specs/dashboard-reactions/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/dashboard-reactions/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/dashboard-reactions/spec.md b/openspec/specs/dashboard-reactions/spec.md index 2f53f3866..7741f78da 100644 --- a/openspec/specs/dashboard-reactions/spec.md +++ b/openspec/specs/dashboard-reactions/spec.md @@ -11,8 +11,6 @@ Dashboard reactions enable lightweight social feedback via emoji on LaunchPad da ## Data Model -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### oc_launchpad_dash_reactions table Each reaction is stored with the following fields: @@ -34,7 +32,7 @@ Each reaction is stored with the following fields: ### Admin Settings -- **launchpad.reactions_enabled_default**: Boolean (default: true) — global toggle for reactions feature +- **launchpad.reactions_enabled_default**: Boolean (default: false). The global toggle for the reactions feature, off until an administrator turns it on, so a dashboard shows no reactions row by default - **launchpad.reactions_allowed_emojis**: JSON array of strings (default: `["👍","❤️","🎉","😂","🤔","😢"]`) — whitelist of allowed emoji ## Requirements @@ -143,6 +141,7 @@ Users viewing a dashboard MUST be able to see the aggregate reaction counts and } ``` - NOTE: Existing reactions are hidden (not deleted), but new reactions cannot be added (REQ-RXN-005) +@e2e exclude cannot be seeded: nothing writes a dashboard's `reactionsEnabled` (no endpoint, form, command or listener calls setReactionsEnabled; `git log --all -G 'setReactionsEnabled\(\$'` finds it only in tests/Unit/Service/ReactionServiceTest.php), so the per-dashboard override was never built; the tri-state resolution is pinned in tests/Unit/Service/ReactionServiceTest.php (testIsReactionsEnabledTriState, testGetReactionsSummaryDisabledShape) ### Requirement: REQ-RXN-004 List Reactors by Emoji @@ -213,6 +212,7 @@ Administrators MUST be able to enable or disable reactions on individual dashboa - WHEN user "alice" sends `GET /api/dashboards/dash-123/reactions` - THEN the response MUST include `"enabled": true` - AND user "alice" can POST reactions to this dashboard +@e2e exclude cannot be seeded: nothing writes a dashboard's `reactionsEnabled` (no endpoint, form, command or listener calls setReactionsEnabled; `git log --all -G 'setReactionsEnabled\(\$'` finds it only in tests/Unit/Service/ReactionServiceTest.php), so the per-dashboard override was never built; the tri-state resolution is pinned in tests/Unit/Service/ReactionServiceTest.php (testIsReactionsEnabledTriState, testGetReactionsSummaryDisabledShape) #### Scenario: Admin disables reactions on a dashboard that has global reactions enabled - GIVEN global setting `launchpad.reactions_enabled_default` is true @@ -220,6 +220,7 @@ Administrators MUST be able to enable or disable reactions on individual dashboa - WHEN user "bob" sends `GET /api/dashboards/dash-456/reactions` - THEN the response MUST include `"enabled": false` - AND user "bob" cannot POST reactions (returns 403) +@e2e exclude cannot be seeded: nothing writes a dashboard's `reactionsEnabled` (no endpoint, form, command or listener calls setReactionsEnabled; `git log --all -G 'setReactionsEnabled\(\$'` finds it only in tests/Unit/Service/ReactionServiceTest.php), so the per-dashboard override was never built; the tri-state resolution is pinned in tests/Unit/Service/ReactionServiceTest.php (testIsReactionsEnabledTriState, testGetReactionsSummaryDisabledShape) #### Scenario: Null reactionsEnabled field follows global setting - GIVEN global setting `launchpad.reactions_enabled_default` is true @@ -232,6 +233,7 @@ Administrators MUST be able to enable or disable reactions on individual dashboa - WHEN an admin updates it to `reactionsEnabled = 0` - THEN user "alice" immediately sees `"enabled": false` on next GET request - NOTE: Existing reactions remain in the database, hidden but not deleted +@e2e exclude cannot be seeded: nothing writes a dashboard's `reactionsEnabled` (no endpoint, form, command or listener calls setReactionsEnabled; `git log --all -G 'setReactionsEnabled\(\$'` finds it only in tests/Unit/Service/ReactionServiceTest.php), so the per-dashboard override was never built; the tri-state resolution is pinned in tests/Unit/Service/ReactionServiceTest.php (testIsReactionsEnabledTriState, testGetReactionsSummaryDisabledShape) ### Requirement: REQ-RXN-007 Allowed Emoji Whitelist @@ -284,18 +286,18 @@ When a dashboard is deleted, ALL reactions on that dashboard MUST be removed. - THEN `ReactionsListener` MUST invoke `ReactionService::deleteReactionsByDashboard('dash-123')` - AND all 10 reaction rows in `oc_launchpad_dash_reactions` where `dashboardUuid = 'dash-123'` MUST be removed - AND subsequent GET requests for that dashboard MUST return 404 +@e2e exclude the rows of a deleted dashboard cannot be observed (every reaction route answers 404 once it is gone) and the listener call is internal; pinned in tests/Unit/Listener/ReactionsListenerTest.php (testHandleInvokesServiceWithEventUuid), tests/Unit/Db/DashboardReactionMapperTest.php (testDeleteByDashboardAndCountReactors) and tests/Unit/Service/DashboardCascadeEventDispatchTest.php #### Scenario: Cascade delete does not affect other dashboards' reactions - GIVEN dashboard `dash-A` has 3 reactions and dashboard `dash-B` has 5 reactions - WHEN the user deletes dashboard `dash-A` - THEN the 3 reactions on `dash-A` MUST be deleted - AND the 5 reactions on `dash-B` MUST remain unchanged +@e2e exclude the deleted dashboard's three rows cannot be observed (every reaction route answers 404 once it is gone), so only the surviving half could be asserted; the uuid-scoped delete is pinned in tests/Unit/Db/DashboardReactionMapperTest.php (testDeleteByDashboardAndCountReactors) and tests/Unit/Listener/ReactionsListenerTest.php (testHandleInvokesServiceWithEventUuid) ### Requirement: REQ-RXN-010 A viewer can react from the dashboard -@e2e exclude reacting needs a live dashboard with reactions on; asserted in src/components/Workspace/__tests__/DashboardReactions.spec.js and tests/Unit/Service/ReactionServiceTest.php - -In view mode a reactions bar MUST show under the dashboard title with each emoji and its count, mark the viewer's own reactions, and toggle the viewer's reaction on click. It MUST offer only the allowed emoji, and MUST be absent when reactions are disabled globally or for the dashboard. +In view mode a reactions bar MUST show at the foot of the dashboard, under the last widget and over the full width, as a card that asks "What do you think of this dashboard?" before each emoji and its count and names who last changed the dashboard and when after them. It MUST mark the viewer's own reactions and toggle the viewer's reaction on click. It MUST offer only the allowed emoji, and MUST be absent when reactions are disabled globally or for the dashboard. #### Scenario: Add and remove diff --git a/openspec/specs/dashboard-sharing/screens.md b/openspec/specs/dashboard-sharing/screens.md new file mode 100644 index 000000000..b1d003152 --- /dev/null +++ b/openspec/specs/dashboard-sharing/screens.md @@ -0,0 +1,6 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpDelen https://identity.conduction.nl/screens/board?id=launchpad/LpDelen +- LpBeheerDelen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerDelen +- LpBeheerOnderhoud https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerOnderhoud diff --git a/openspec/specs/dashboard-sharing/spec.md b/openspec/specs/dashboard-sharing/spec.md index 1722a08d9..a63c9237e 100644 --- a/openspec/specs/dashboard-sharing/spec.md +++ b/openspec/specs/dashboard-sharing/spec.md @@ -60,12 +60,11 @@ The unique tuple `(dashboardId, shareType, shareWith)` enforces that a recipient ## Requirements - ### Requirement: Owner-only share management (REQ-SHARE-001) @e2e tests/e2e/dashboard-sharing.spec.ts -Only the owner of a dashboard MUST be allowed to list, create, update, or delete shares on that dashboard. All share-management endpoints MUST return HTTP 403 for any caller that is not the dashboard owner, including users who themselves have a `full`-level share on the dashboard. +Only the owner of a dashboard MUST be allowed to list, create, update, or delete shares on that dashboard. All share-management endpoints MUST return HTTP 403 for any caller that is not the dashboard owner, including users who themselves have a `full`-level share on the dashboard. The owner-driven sharing UI flow (open `DashboardConfigModal`'s Sharing tab, add a share, change its permission level, remove a share) MUST be covered by a real Playwright e2e test that drives the actual router → middleware → controller → Vue re-render path, not only by PHPUnit tests that call the controller/service directly. #### Scenario: Owner adds a share @@ -88,12 +87,29 @@ Only the owner of a dashboard MUST be allowed to list, create, update, or delete - THEN the system MUST update the existing share row, not create a second one - AND only one share row MUST exist for `(dashboardId=5, shareType=user, shareWith=bob)` +#### Scenario: A user drives the full sharing flow through the browser + +- GIVEN alice is logged in and opens the config modal for a dashboard she owns +- WHEN she switches to the Sharing tab, searches for and adds "bob" at `view_only`, changes his permission level to `full`, then removes his share, and reloads the page +- THEN `tests/e2e/dashboard-sharing.spec.ts` MUST assert each step persists correctly end to end (the added share appears, the level change is reflected, the removal survives a reload) +- AND the spec's e2e-exclusion annotation MUST be scoped to only the scenarios (if any) that genuinely have no UI surface, not a blanket exclusion of the whole capability + ### Requirement: Listing dashboards visible to a user (REQ-SHARE-002) @e2e tests/e2e/dashboard-sharing.spec.ts `GET /api/dashboards` MUST return both dashboards owned by the caller AND dashboards the caller has access to via a direct or group share. Each entry MUST be decorated with `isOwner: bool`, `sharedBy: string|null` (the owner's userId when not the caller's own dashboard), and `effectivePermissionLevel: 'view_only'|'add_only'|'full'`. +A share does not override publication state (REQ-DASH-036): a dashboard in `draft`, or `scheduled` with `publishAt` still in the future, MUST NOT reach a recipient through any read (`GET /api/dashboards`, `GET /api/dashboards/visible`, `GET /api/dashboard`, `GET /api/dashboard/{id}`) until it is published, unless the recipient is a Nextcloud administrator. When the owner shares a dashboard that is not published yet, the sharing panel MUST say so: "Colleagues see this dashboard once you publish it" ("Collega's zien dit dashboard zodra u het publiceert"). + +#### Scenario: A shared draft stays hidden until it is published + +- GIVEN alice owns draft dashboard `5` and shares it with "bob" at `view_only` +- WHEN bob fetches `GET /api/dashboards/visible` +- THEN dashboard `5` MUST NOT be present +- WHEN alice publishes dashboard `5` and bob fetches the list again +- THEN dashboard `5` MUST be present with `isOwner: false` + #### Scenario: Recipient sees a shared dashboard in their list - GIVEN dashboard `5` ("My Dashboard", owned by "alice") is shared with "bob" at `add_only` @@ -117,8 +133,6 @@ Only the owner of a dashboard MUST be allowed to list, create, update, or delete ### Requirement: Loading a shared dashboard with placements (REQ-SHARE-003) -@e2e exclude recipient-side placement load is exercised by DashboardShareServiceFollowupsTest + the shared-dashboard read path; no owner-driven UI surface distinct from REQ-SHARE-002 - `GET /api/dashboard/{id}` MUST return the dashboard, its widget placements, and the caller's effective permission level for any dashboard the caller can view (owned or shared). Callers without ownership AND without any matching share MUST receive HTTP 403. #### Scenario: Recipient loads a shared dashboard @@ -149,8 +163,6 @@ When a user accesses a dashboard via a share, the system MUST evaluate widget/ti ### Requirement: Owner-only metadata and lifecycle operations (REQ-SHARE-005) -@e2e exclude owner-only 403 enforcement is a server-side authorization contract with no distinct UI state beyond REQ-SHARE-001; covered by DashboardShareApiControllerFollowupsTest - Even with a `full`-level share, recipients MUST NOT be able to: - Rename the dashboard or change its description (`canEditDashboardMetadata` returns false for non-owners) @@ -192,8 +204,6 @@ Even with a `full`-level share, recipients MUST NOT be able to: ### Requirement: Cascade on dashboard delete (REQ-SHARE-007) -@e2e exclude DB cascade side-effect with no observable UI state; covered by DashboardShareServiceFollowupsTest - When a dashboard is deleted (by its owner), every share row referencing that dashboard MUST be deleted in the same transaction. No orphan share rows MAY remain. #### Scenario: Shares are removed when the dashboard is deleted @@ -206,8 +216,6 @@ When a dashboard is deleted (by its owner), every share row referencing that das ### Requirement: Notify recipient on share add and on level upgrade (REQ-SHARE-008) -@e2e exclude notification dispatch is a server-side side-effect asserted by DashboardShareServiceFollowupsTest; no owner-facing UI surface - When a share is created OR its `permission_level` is **upgraded** (`view_only → add_only|full`, or `add_only → full`), the system MUST publish a Nextcloud notification to each affected recipient via `OCP\Notification\IManager`. The notification MUST use: - `app: 'launchpad'`, `subject: 'dashboard_shared'` @@ -293,8 +301,6 @@ After the transaction commits, the system MUST publish notifications per REQ-SHA ### Requirement: Revoke all shares granted to a recipient (REQ-SHARE-010) -@e2e exclude admin bulk-revoke path with no owner-facing config-modal surface; covered by DashboardShareServiceFollowupsTest - The system MUST support `DELETE /api/sharees/{shareType}/{shareWith}` for an authenticated user. The operation MUST delete every share row where: - `share_type = $shareType AND share_with = $shareWith`, AND @@ -316,8 +322,6 @@ The response MUST include the count of removed share rows. No notifications MUST ### Requirement: Notifier renders share and ownership-transfer subjects (REQ-SHARE-011) -@e2e exclude notifier subject-string rendering is a server-side Notifier unit concern with no dashboard-config UI surface - The app MUST register an `OCP\Notification\INotifier` implementation with `id = 'launchpad'` that handles two subjects: `dashboard_shared` and `dashboard_ownership_transferred`. For any other subject the notifier MUST throw `\OCP\Notification\UnknownNotificationException` so that other notifiers may handle it. For `dashboard_shared`, the rendered notification MUST include: @@ -348,8 +352,6 @@ Localisation MUST be performed via `IFactory::get('launchpad')` so the existing ### Requirement: Cascade and admin retention on user deletion (REQ-SHARE-012) -@e2e exclude UserDeletedEvent-driven cascade/retention with no interactive UI surface; covered by the service-layer followups suite - The app MUST listen to `OCP\User\Events\UserDeletedEvent`. On every event for user `X`, in a single DB transaction per affected dashboard, the system MUST: 1. **Recipient cleanup**: delete every share row where `share_type='user' AND share_with=X`. Group shares are unaffected. @@ -406,8 +408,6 @@ The app MUST listen to `OCP\User\Events\UserDeletedEvent`. On every event for us ### Requirement: Deterministic new-owner selection (REQ-SHARE-013) -@e2e exclude pure ranking/tie-break logic for owner reassignment with no observable UI state; covered by the service-layer followups suite - When REQ-SHARE-012 calls for picking a new owner from the admin pool, the system MUST apply this ordering rule: 1. Among `share_type='user'` shares with `permission_level='full'`, pick the one with the smallest `created_at`. @@ -434,3 +434,90 @@ The selected new owner MUST receive a notification with `subject='dashboard_owne - GIVEN dashboard `5` ("Q3 Plan") undergoes ownership transfer to bob - WHEN the listener completes - THEN exactly one `INotification` MUST be published with `user='bob'`, `subject='dashboard_ownership_transferred'`, `subjectParameters=['Q3 Plan']`, `objectType='dashboard'`, `objectId='5'` + +### Requirement: Administrators decide who may share and with whom (REQ-SHARE-014) + +An administrator MUST be able to name the groups whose members may share dashboards. An empty list MUST mean everyone may share, which keeps today's behaviour. An administrator MUST also be able to limit recipients to people who share a group with the sharer. The server MUST enforce both settings on every share it creates, and the sharee search MUST offer only allowed recipients. + +#### Scenario: A member outside the sharing groups cannot share + +- **GIVEN** Noor allowed sharing for the group "Communicatie" only +- **AND** Pieter is not in "Communicatie" +- **WHEN** Pieter opens the share settings of his dashboard +- **THEN** he cannot add a share +- **AND** a share request he sends to the API is refused with HTTP 403 + +#### Scenario: Recipients limited to shared groups + +- **GIVEN** Noor limited recipients to people who share a group with the sharer +- **AND** Ella shares no group with Pieter +- **WHEN** Pieter searches for "Ella" in the share settings +- **THEN** Ella is not offered +- **AND** a share request naming Ella is refused with HTTP 403 + +#### Scenario: No limits set + +- **GIVEN** both sharing settings are empty +- **WHEN** Pieter shares his dashboard with Ella +- **THEN** the share is created as before + +### Requirement: Administrators can stop sharing and limit public links (REQ-SHARE-015) + +"Sharing allowed for" (board LpBeheerDelen) SHALL offer Everyone, Only these groups and Nobody. With Nobody no one but +an administrator SHALL be able to add a share, and the server SHALL refuse a share request from anyone else with HTTP +403; existing shares SHALL stay. + +An administrator SHALL be able to switch public links on or off ("Allow public links"). With public links off, no +public link (dashboard-public-share) SHALL be created and the Sharing tab SHALL not offer one; existing links SHALL +keep working until they expire or are revoked. With public links on, only people who may share SHALL create one, and +every new public link SHALL have an expiry date: the create form SHALL require it and the server SHALL refuse a link +without one with HTTP 400. + +#### Scenario: Nobody may share + +- **GIVEN** Noor set Sharing allowed for to Nobody +- **WHEN** Pieter opens the Sharing tab of his dashboard +- **THEN** he cannot add people or groups +- **AND** a share request he sends to the API is refused with HTTP 403 + +#### Scenario: A public link needs an expiry date + +- **GIVEN** public links are allowed and Pieter may share +- **WHEN** he creates a public link without an expiry date +- **THEN** the form asks for the expiry date +- **AND** a request without `expiresAt` is refused with HTTP 400 + +#### Scenario: Public links off + +- **GIVEN** Noor switched public links off +- **WHEN** Pieter opens the Sharing tab +- **THEN** the tab offers no public link +- **AND** a public link created before keeps working until it expires + +### Requirement: Administrators choose where a leaver's dashboards go (REQ-SHARE-016) + +The block Opruimen (board LpBeheerOnderhoud) SHALL let an administrator set "Dashboards of people who left go to": +their manager, otherwise a person the administrator names. When a person is deleted and this is set, every dashboard +they owned SHALL go to their manager (Nextcloud's manager field, read before the account is removed) when that manager +still has an account, else to the named person, else it SHALL follow REQ-SHARE-012. The shares on the dashboard SHALL +stay. The new owner SHALL get the `dashboard_ownership_transferred` notification of REQ-SHARE-013. When the setting is +empty, REQ-SHARE-012 SHALL apply unchanged. + +#### Scenario: Pieter leaves + +- **GIVEN** Noor set the handover to the manager, otherwise Femke de Wit +- **AND** Pieter's manager is Marieke Jansen +- **WHEN** Pieter's account is deleted +- **THEN** Pieter's dashboards belong to Marieke, with their shares, and Marieke gets a notification + +#### Scenario: No manager + +- **GIVEN** the same setting and Sanne has no manager +- **WHEN** Sanne's account is deleted +- **THEN** Sanne's dashboards belong to Femke de Wit + +#### Scenario: No setting + +- **GIVEN** no handover is set +- **WHEN** a person is deleted +- **THEN** their dashboards follow REQ-SHARE-012 diff --git a/openspec/specs/dashboard-store/screens.md b/openspec/specs/dashboard-store/screens.md new file mode 100644 index 000000000..f0910f02a --- /dev/null +++ b/openspec/specs/dashboard-store/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpStore https://identity.conduction.nl/screens/board?id=launchpad/LpStore diff --git a/openspec/specs/dashboard-store/spec.md b/openspec/specs/dashboard-store/spec.md new file mode 100644 index 000000000..8b4eb316e --- /dev/null +++ b/openspec/specs/dashboard-store/spec.md @@ -0,0 +1,318 @@ +# dashboard-store Specification + +## Purpose +An administrator can connect LaunchPad to a registry, another OpenRegister instance that publishes dashboard templates, and install a template from the marketplace page as a new dashboard. OpenRegister's store plane owns discovery (the address guard, the token transport and the outcome it reports); LaunchPad owns the install, which goes through the existing dashboard importer and always creates a dashboard, never replaces one. The registry token is write-only, and the store degrades to a not-configured state when OpenRegister is absent. + +## Requirements + +### Requirement: REQ-STORE-001 The store routes MUST exist wherever the store page is declared + +LaunchPad's manifest declares a `type: "store"` page, which renders `CnStorePage`, +which calls `GET /apps/launchpad/api/store/items` on mount and +`POST /apps/launchpad/api/store/items/{slug}/install` on an install click. +`appinfo/routes.php` SHALL declare both, and the `{slug}` route SHALL constrain +the slug to `[a-z0-9][a-z0-9-]*[a-z0-9]` so a malformed slug fails at the router +rather than reaching the registry URL. + +#### Scenario: The declared page can reach its endpoint + +- **GIVEN** `src/manifest.json` declares a page of type `store` +- **WHEN** the route table is read +- **THEN** it MUST contain `store#search` at `/api/store/items` +- **AND** it MUST contain `store#install` at `/api/store/items/{slug}/install` + +@e2e exclude route-table shape: asserted by reading appinfo/routes.php in tests/Unit/Support/StoreWiringTest.php; the browser consequence is the next scenario + +#### Scenario: An unconfigured store shows the not-configured state + +- **GIVEN** no `registry_url` is configured +- **WHEN** an administrator opens the Marketplace page +- **THEN** `GET /api/store/items` MUST answer 200 with outcome `not_configured` +- **AND** the page MUST show its not-configured note +- **AND** it MUST NOT show the unreachable note or an empty result grid + +--- + +### Requirement: REQ-STORE-002 An absent OpenRegister MUST degrade, never fatal + +`GenericStoreService` is resolved optionally, exactly as LaunchPad already +resolves the AppHost observability collaborators. When OpenRegister is disabled or +absent the collaborator is null. `search()` MUST then return outcome +`not_configured` with an empty card list, and `install()` MUST refuse, and neither +MUST touch an `OCA\OpenRegister\…` symbol. + +An engine that is present but unconfigured behaves the same way, because +`GenericStoreService::isConfigured()` reports false for an empty `registry_url` +and makes no network call. + +#### Scenario: No OpenRegister yields not_configured + +- **GIVEN** the store service holds a null discovery client +- **WHEN** `search()` is called +- **THEN** the outcome MUST be `not_configured` and the card list MUST be empty + +@e2e exclude requires an instance WITHOUT OpenRegister, and CI installs it; asserted in tests/Unit/Service/StoreServiceTest.php + +#### Scenario: No OpenRegister refuses an install rather than half-running one + +- **GIVEN** the store service holds a null discovery client +- **WHEN** `install()` is called for any slug +- **THEN** it MUST report failure and MUST NOT call `ImportService` + +@e2e exclude requires an instance WITHOUT OpenRegister, and CI installs it; asserted in tests/Unit/Service/StoreServiceTest.php + +--- + +### Requirement: REQ-STORE-003 The engine's outcome MUST reach the caller unchanged + +The plane distinguishes `store_unreachable` from `store_invalid_response` so a +misconfigured registry does not read as an offline one. LaunchPad SHALL pass the +outcome through verbatim and MUST NOT collapse the two, and MUST NOT substitute +its own. Upstream error detail MUST NOT reach the caller; the engine already keeps +it server-side. + +#### Scenario: An invalid response is not reported as unreachable + +- **GIVEN** the engine returns outcome `store_invalid_response` +- **WHEN** the service returns +- **THEN** the outcome MUST be `store_invalid_response` + +@e2e exclude needs a registry that answers malformed JSON, and CI has no registry; asserted in tests/Unit/Service/StoreServiceTest.php + +--- + +### Requirement: REQ-STORE-004 Installing MUST require an administrator + +An install writes dashboards into the instance from a third-party server. The +install endpoint SHALL carry `#[AuthorizedAdminSetting(LaunchPadAdmin::class)]`, +the posture LaunchPad already uses for its other administrative endpoints. + +Search SHALL carry `#[NoAdminRequired]`, because browsing a registry addresses no +object of this instance. It forwards a query to an external registry and returns +normalised cards, so there is no local identifier to guess and no IDOR to create. + +#### Scenario: Every store route declares a posture + +- **GIVEN** the store controller +- **WHEN** its public methods are read +- **THEN** `search` MUST carry `#[NoAdminRequired]` +- **AND** `install` MUST carry `#[AuthorizedAdminSetting]` + +@e2e exclude attribute presence: asserted by reflection in tests/Unit/Controller/StoreControllerTest.php; the two scenarios below prove the attributes hold at runtime + +#### Scenario: A non-admin is refused the registry config + +- **GIVEN** a signed-in account that is not an administrator, holding a valid request token +- **WHEN** it reads or writes `/api/store/config` +- **THEN** both requests MUST answer 403 +- **AND** the stored registry MUST be unchanged afterwards + +#### Scenario: A non-admin is refused an install + +- **GIVEN** the same account +- **WHEN** it posts to `/api/store/items/{slug}/install` +- **THEN** the request MUST answer 403 + +--- + +### Requirement: REQ-STORE-005 An install MUST reuse ImportService, not reimplement it + +The resolved payload SHALL be materialised into a `launchpad-export-v1` ZIP in a +temporary directory and handed to `ImportService::import()`. LaunchPad MUST NOT +gain a second code path that turns a dashboard payload into rows. + +The materialised archive MUST carry a `manifest.json` with `schemaVersion` equal +to the importer's supported version and a `scope`, and one +`dashboards/{uuid}.json` entry per dashboard, because that is what +`validateZipStructure()` requires and what `ExportService` writes. + +The temporary archive MUST be removed whether the import succeeds or throws. + +#### Scenario: The payload reaches the existing importer + +- **GIVEN** a resolved item carrying one dashboard payload +- **WHEN** it is installed +- **THEN** `ImportService::import()` MUST be called exactly once +- **AND** the path it receives MUST be an existing ZIP containing `manifest.json` + +@e2e exclude needs a second OpenRegister publishing a template, and CI has one instance; asserted in tests/Unit/Service/StoreServiceTest.php + +#### Scenario: An install with no registry is refused with a reason + +- **GIVEN** no `registry_url` is configured +- **WHEN** an administrator posts an install for any slug +- **THEN** the request MUST answer 400 with `success` false and a message +- **AND** it MUST NOT answer 500 + +#### Scenario: A payload with no dashboards is refused before any import + +- **GIVEN** a resolved item whose dashboards list is empty or absent +- **WHEN** it is installed +- **THEN** the install MUST fail and `ImportService::import()` MUST NOT be called + +@e2e exclude needs a registry serving a malformed item, and CI has no registry; asserted in tests/Unit/Service/StoreServiceTest.php + +#### Scenario: The temporary archive does not survive a failing import + +- **GIVEN** `ImportService::import()` throws +- **WHEN** the install returns +- **THEN** no temporary archive from that install MUST remain on disk + +@e2e exclude a temp-directory effect with no browser surface; asserted in tests/Unit/Service/StoreServiceTest.php + +--- + +### Requirement: REQ-STORE-006 A store install MUST create dashboards, never replace them + +The install SHALL call `ImportService::import()` with `preserveUuids` false. A +template published by a foreign instance carries that instance's UUIDs, and one of +them can collide with a live local dashboard. Re-mapping makes the install +additive. + +This mirrors the plane's own rule that an install creates rather than replaces, +reached by a different route: the identity that would do the damage is the +dashboard UUID rather than an object `uuid`. + +#### Scenario: A colliding UUID still creates + +- **GIVEN** a resolved item whose dashboard UUID matches a local dashboard +- **WHEN** it is installed +- **THEN** `import()` MUST be called with `preserveUuids` false + +@e2e exclude needs a second OpenRegister publishing a template, and CI has one instance; asserted in tests/Unit/Service/StoreServiceTest.php + +--- + +### Requirement: REQ-STORE-007 The registry token MUST NOT be readable back + +`registry_url`, `registry_token` and `registry_register` live in `IAppConfig` +under `launchpad`, because that is where `GenericStoreService` reads them. +LaunchPad's own admin settings write to a different store, so the change adds an +admin-gated endpoint for these three keys. + +The read endpoint SHALL return the URL and the register, and for the token SHALL +return only whether one is set. The token value MUST NOT appear in any response. + +#### Scenario: Reading the config never returns the token + +- **GIVEN** `registry_token` holds a value +- **WHEN** the config is read +- **THEN** the response MUST report that a token is set +- **AND** the response MUST NOT contain the token value + +#### Scenario: An empty token submission clears rather than blanks around + +- **GIVEN** a stored token +- **WHEN** the config is written with an empty token +- **THEN** the stored token MUST be cleared + +@e2e exclude the clear-versus-keep distinction is a request-payload property the browser cannot see; asserted in tests/Unit/Service/StoreServiceTest.php and src/components/admin/__tests__/DashboardRegistrySettings.spec.js + +--- + +### Requirement: REQ-STORE-008 The manifest MUST NOT declare a store block + +`src/manifest.json` MUST NOT carry a `store` key. That block exists to configure +OpenRegister's `GenericStoreController`, which LaunchPad does not use, so a block +here would declare a schema and card fields that nothing reads while +`StoreService` declares the ones that are used. + +A non-empty `types` list is the specific harm, because it selects the engine's +federated configuration path. The block on `development` declared +`openregister.configset` and `openregister.flows`, which trade registers, schemas +and flows. Had the routes existed, the marketplace page would have offered +configuration sets to somebody looking for a dashboard. + +#### Scenario: No store block is declared + +- **GIVEN** `src/manifest.json` +- **WHEN** it is decoded +- **THEN** it MUST NOT contain a `store` key + +@e2e exclude a source-file property; asserted in tests/Unit/Support/StoreWiringTest.php + +#### Scenario: The store page still declares itself + +- **GIVEN** the same manifest +- **WHEN** its pages are read +- **THEN** exactly one page MUST carry `type` of `store` + +@e2e exclude a source-file property; asserted in tests/Unit/Support/StoreWiringTest.php + +--- + +### Requirement: REQ-STORE-009 An administrator MUST be able to connect a registry without a shell + +The three registry keys live in `IAppConfig`, which LaunchPad's own admin +settings do not write. So Beheer ▸ Sharing SHALL carry a form for +`registry_url`, `registry_register` and the token, backed by +`/api/store/config`. + +The token field SHALL be write-only. It MUST start empty on every load, and +the page MUST say whether a token is set without showing it. Saving with an +empty token field MUST leave the stored token alone; removing it is a +separate action. + +#### Scenario: An administrator saves a registry and reads it back + +- **GIVEN** an administrator on Beheer ▸ Sharing +- **WHEN** they enter a registry URL, a register and a token, and save +- **THEN** after a reload the URL and register fields MUST show what they entered +- **AND** the page MUST say a token is set + +#### Scenario: The token is never shown back + +- **GIVEN** a stored token +- **WHEN** the form loads +- **THEN** the token field MUST be empty +- **AND** neither the page nor the config response MUST contain the token + +#### Scenario: The saved registry is the one the store reads + +- **GIVEN** an administrator saved a registry URL whose host does not resolve +- **WHEN** they open the Marketplace page +- **THEN** the page MUST show the unreachable note rather than the not-configured one + +### Requirement: REQ-STORE-010 The marketplace shows dashboard templates as cards + +The marketplace page (board LpStore) SHALL open with a banner for the connected register: its name, its address, when +it was last checked and its state (Connected, or the outcome of REQ-STORE-002 and 003), and the note "Only +administrators install for the whole organisation" for everyone who is not an administrator. Its lenses SHALL be All, +Installed and Update available, followed by the categories the register's items carry, each with its count; the +engine's generic kind lenses SHALL NOT show. The page SHALL offer a search and the filters the register's items carry +(for example the kind of organisation). Each card SHALL show the template's title, publisher, status (Installed, +Available or Update), description, version, number of widgets and, when the register reports it, how many +organisations use it. The page SHALL show 8 cards at a time with paging. + +#### Scenario: The VNG register is connected + +- **GIVEN** the administrator connected the register "VNG dashboardregister" with 23 templates, checked today at 06:00 +- **WHEN** Pieter opens the marketplace +- **THEN** the banner names the register, its address, "last checked today 06:00" and Connected, with the note that only administrators install +- **AND** the lenses read All 23, Installed 3, Update available 1, then the categories with their counts +- **AND** the first 8 cards show title, publisher, status, description, version, widgets and usage + +#### Scenario: No register connected + +- **GIVEN** no register is connected +- **WHEN** an administrator opens the marketplace +- **THEN** the page says no register is connected and points to the Sharing tab of the admin settings, and shows no cards + +### Requirement: REQ-STORE-011 An installed template opens instead of installing again + +LaunchPad SHALL record which register item and version an install created. The card of an item that has a dashboard +from an install on this instance SHALL show the status Installed and the action Open, which opens that dashboard; an +item whose register version is newer than the installed one SHALL show the status Update. An item without an install +SHALL show Available and, for an administrator, Install. + +#### Scenario: Intranet gemeente is installed + +- **GIVEN** the administrator installed "Intranet gemeente" 2.3.0 from the register +- **WHEN** Pieter opens the marketplace +- **THEN** its card shows Installed and Open, and Open goes to the installed dashboard + +#### Scenario: A newer version in the register + +- **GIVEN** "Managementinfo sociaal domein" 1.0.0 is installed and the register offers 1.1.0 +- **WHEN** the administrator opens the marketplace +- **THEN** its card shows the status Update and counts under Update available diff --git a/openspec/specs/dashboard-switcher/screens.md b/openspec/specs/dashboard-switcher/screens.md new file mode 100644 index 000000000..dd0a09b0b --- /dev/null +++ b/openspec/specs/dashboard-switcher/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag diff --git a/openspec/specs/dashboard-switcher/spec.md b/openspec/specs/dashboard-switcher/spec.md index a3cd41f18..417e05c3f 100644 --- a/openspec/specs/dashboard-switcher/spec.md +++ b/openspec/specs/dashboard-switcher/spec.md @@ -44,6 +44,8 @@ Empty sections MUST NOT render their label or container at all (no empty heading #### Scenario: Only personal dashboards section visible +@e2e exclude Unreachable on a live instance: since #361 (c9e58089) SeedDefaultDashboard provisions a dashboard on the reserved `default` group that every account sees, so `groupDashboards` is never empty without deleting the shipped default on a shared instance. Pinned by src/components/Workspace/__tests__/DashboardSwitcherSidebar.spec.js "renders only the personal section when group lists are empty" and "omits empty sections entirely (no orphan heading)". + - GIVEN `groupDashboards = []` and `userDashboards` has 1 item - WHEN the sidebar renders - THEN only the `'My Dashboards'` section MUST be visible @@ -81,7 +83,6 @@ Before emitting `switch`, the sidebar MUST emit `update:open(false)` so the pare ### Requirement: REQ-SWITCH-003 Active item highlight The dashboard whose `id === activeDashboardId` MUST receive a visual `.active` class with `--color-primary-element-light` background and `--color-primary` icon tint. At most one item may be active at a time. -@e2e exclude active item highlight class test requires verifying CSS class on a specific dashboard row — covered indirectly by wave3 switching test; fine-grained class assertion needs known dashboard IDs #### Scenario: Active highlight follows prop @@ -99,20 +100,20 @@ The dashboard whose `id === activeDashboardId` MUST receive a visual `.active` c ### Requirement: REQ-SWITCH-004 Personal dashboard delete affordance -Items in the `My Dashboards` section (excluding the `+ New Dashboard` row) MUST display a small close-icon delete button on hover (CSS-only `display: none → inline-flex`). Clicking it MUST emit `delete-dashboard(id)` and MUST NOT trigger the row's `switch` event (use `@click.stop`). -@e2e exclude hover reveals delete button tests CSS hover state — not reliably assertable in Playwright without .hover() + immediate screenshot; covered by wave3 deletion test +Delete MUST live in each row's options menu (the row cog, labelled "Dashboard menu"), shown only for a dashboard the user owns; a row MUST NOT reveal a delete button on hover (Ruben, 21 Nov 2026, following the product). Choosing Delete MUST emit `deleteDashboard(id, source)` and MUST NOT trigger the row's `switch` event. -#### Scenario: Hover reveals delete button +#### Scenario: Delete lives in the row options menu - GIVEN a personal dashboard item with `id = 'p1'` - WHEN the user hovers over the row -- THEN the delete button MUST become visible (CSS hover state) +- THEN no delete button MUST appear in the row +- AND the row's options menu MUST offer "Delete dashboard" #### Scenario: Delete click does not trigger switch -- GIVEN the delete button is visible -- WHEN the user clicks it -- THEN the sidebar MUST emit `delete-dashboard('p1')` +- GIVEN the row's options menu is open +- WHEN the user chooses "Delete dashboard" +- THEN the sidebar MUST emit `deleteDashboard('p1', source)` - AND MUST NOT emit `switch(...)` - AND MUST NOT emit `update:open(false)` (closing decision is up to the parent) @@ -122,14 +123,12 @@ When `allowUserDashboards: true`, the `My Dashboards` section MUST end with a ro #### Scenario: Create button hidden when feature disabled -@e2e exclude conditional DOM presence on a prop flag — covered by Vitest component test - GIVEN `allowUserDashboards: false` - WHEN the sidebar renders - THEN the `+ New Dashboard` row MUST NOT be present in the DOM #### Scenario: Create button click -@e2e exclude emitted-event assertion — covered by Vitest component test - GIVEN the user clicks `+ New Dashboard` - THEN the sidebar MUST emit `update:open(false)` - AND THEN MUST emit `create-dashboard` (no payload) @@ -137,7 +136,6 @@ When `allowUserDashboards: true`, the `My Dashboards` section MUST end with a ro ### Requirement: REQ-SWITCH-006 Slide-in animation The sidebar MUST be fixed-position (`top: 50px` to clear the Nextcloud header), `width: 280px`, `z-index: 1500`. Open/close MUST be animated via `transform: translateX(-100%)` ↔ `translateX(0)` over `0.25s ease`. The `.open` CSS class MUST be added when `isOpen === true`. -@e2e exclude slide-in animation tests CSS transform values during animation — Playwright cannot assert mid-animation CSS; open/close covered by wave3 tests #### Scenario: Closed state is off-screen @@ -155,7 +153,6 @@ The sidebar MUST be fixed-position (`top: 50px` to clear the Nextcloud header), ### Requirement: REQ-SWITCH-007 Icon rendering via shared renderer Each dashboard item's icon MUST be rendered via the shared `IconRenderer` component (from `dashboard-icons` capability). The sidebar MUST NOT branch on `isCustomIconUrl` itself. -@e2e exclude icon rendering via shared IconRenderer component tests that no inline v-if branches exist — source-code assertion, not browser-observable #### Scenario: Mixed built-in and custom icons diff --git a/openspec/specs/dashboard-talk-leaf/spec.md b/openspec/specs/dashboard-talk-leaf/spec.md new file mode 100644 index 000000000..e17c1d2d2 --- /dev/null +++ b/openspec/specs/dashboard-talk-leaf/spec.md @@ -0,0 +1,98 @@ +# dashboard-talk-leaf Specification + +## Purpose +TBD - created by archiving change openregister-leaf-integrations. Update Purpose after archive. + +## Requirements + +### Requirement: REQ-LEAF-001 Talk leaf declared on the Dashboard schema via register.d overlay + +The talk leaf MUST be declared declaratively, not in code. A new overlay file `lib/Settings/register.d/dashboard-talk-leaf.json` MUST add `configuration.linkedTypes: ["talk"]` to the `Dashboard` schema, following the established fleet overlay shape (`components.schemas.Dashboard.configuration.linkedTypes`, as in larpingapp's `register.d/player-to-contacts-leaf.json`). The base `launchpad_register.json` MUST NOT be edited for this; the overlay is the single source of the declaration. + +#### Scenario: Overlay declares the leaf + +- **GIVEN** the app is installed or upgraded with the overlay file present +- **WHEN** the register/schema import runs +- **THEN** the imported `Dashboard` schema MUST carry `configuration.linkedTypes` containing exactly `"talk"` +- **AND** no other leaf type MUST be declared by launchpad + +#### Scenario: Base register file untouched + +- **GIVEN** the change is implemented +- **WHEN** `lib/Settings/launchpad_register.json` is inspected +- **THEN** it MUST contain no `linkedTypes` key — the declaration lives only in `register.d/dashboard-talk-leaf.json` + +### Requirement: REQ-LEAF-002 Discussion surface renders only on shared dashboards + +The Talk discussion surface MUST render only for dashboards that are genuinely collaborative: `type === 'group_shared'`, or a dashboard with at least one active share (user/group shares via `DashboardShareService`, or a non-empty `sharedWith`). A personal dashboard with no shares MUST NOT show any discussion affordance — there is nobody to talk to. + +#### Scenario: Group dashboard shows discussion + +- **GIVEN** a `group_shared` dashboard scoped to group `marketing` +- **WHEN** a member of `marketing` opens that dashboard +- **THEN** the Talk discussion surface MUST be available for that dashboard + +#### Scenario: Shared personal dashboard shows discussion + +- **GIVEN** a personal dashboard the owner has shared with user `alice` +- **WHEN** the owner or `alice` opens the dashboard +- **THEN** the Talk discussion surface MUST be available + +#### Scenario: Unshared personal dashboard shows nothing + +- **GIVEN** a personal dashboard with no shares and empty `sharedWith` +- **WHEN** its owner opens it +- **THEN** no discussion affordance MUST render +- **AND** no Talk room MUST be created for it + +### Requirement: REQ-LEAF-003 Discussion access follows the existing view guard + +Access to a dashboard's discussion MUST be gated by the same authorization the dashboard itself uses: a user may see or join the discussion only if `PermissionService::canViewDashboard()` grants them view access to that dashboard. The leaf MUST NOT introduce a parallel ACL, and losing view access (share revoked via `DashboardShareApiController::destroy`/`revokeForRecipient`) MUST also end discussion access. + +#### Scenario: Non-viewer cannot reach the discussion + +- **GIVEN** a dashboard user `bob` has no view access to +- **WHEN** `bob` attempts to access that dashboard's Talk discussion +- **THEN** access MUST be denied with the same outcome as accessing the dashboard itself + +#### Scenario: The discussion object carries the dashboard's audience + +- **GIVEN** `alice` shares her dashboard with user `bob` and group `finance` +- **WHEN** the share is saved +- **THEN** the dashboard's OpenRegister object MUST carry `audienceUsers: ["alice", "bob"]` and `audienceGroups: ["finance"]` +- **AND** the Dashboard schema's read rule MUST admit a reader only through those fields + +#### Scenario: Revoking a share ends discussion access + +- **GIVEN** `alice` had a share on a dashboard and participated in its discussion +- **WHEN** the owner revokes `alice`'s share +- **THEN** `alice` MUST no longer be able to access the dashboard's discussion surface through launchpad + +### Requirement: REQ-LEAF-004 Graceful degradation without Talk + +When the Talk app is not installed or is disabled, the leaf MUST degrade silently: no discussion affordance renders, no error is logged per page view, and every other dashboard function remains unaffected. LaunchPad MUST NOT hard-depend on Talk. + +#### Scenario: Talk absent + +- **GIVEN** an instance where Talk is not installed +- **WHEN** a user opens a `group_shared` dashboard +- **THEN** the dashboard MUST render fully with no discussion surface and no user-visible error + +### Requirement: REQ-LEAF-005 No launchpad-side wrapper code + +Launchpad MUST NOT add controllers, routes or services that proxy Talk or the leaf (ADR-022). Its server-side artifacts are the register.d overlay and the service that keeps a shared dashboard's OpenRegister object and its audience in step with the dashboard. + +#### Scenario: No proxy endpoints appear + +- **GIVEN** the change is implemented +- **WHEN** `appinfo/routes.php` and `lib/Controller/` are inspected +- **THEN** no new Talk- or discussion-related route or controller MUST exist + +### Requirement: The conversation is switched on from the Sharing tab (REQ-LEAF-006) + +The Sharing tab of a shared dashboard SHALL hold "Conversation beside this dashboard" with a switch "Show the conversation beside the dashboard". A dashboard that is not shared SHALL NOT show this part and SHALL say that the conversation appears once it is shared. + +#### Scenario: A personal dashboard + +- **GIVEN** My workspace is not shared +- **THEN** its Sharing tab says "This dashboard is yours alone. Share it with people or a group and the conversation appears here too." diff --git a/openspec/specs/dashboard-versioning/screens.md b/openspec/specs/dashboard-versioning/screens.md new file mode 100644 index 000000000..db4f8f284 --- /dev/null +++ b/openspec/specs/dashboard-versioning/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpVersies https://identity.conduction.nl/screens/board?id=launchpad/LpVersies diff --git a/openspec/specs/dashboard-versioning/spec.md b/openspec/specs/dashboard-versioning/spec.md index 6c64842f0..77d63f9bf 100644 --- a/openspec/specs/dashboard-versioning/spec.md +++ b/openspec/specs/dashboard-versioning/spec.md @@ -11,8 +11,6 @@ Enable version history and one-click restoration for LaunchPad dashboards. The f ## Data Model -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Database Backend (Default) Each dashboard version snapshot is stored in `oc_launchpad_dash_versions` with: @@ -60,9 +58,9 @@ The system MUST automatically capture a snapshot whenever a dashboard's content #### Scenario: Snapshot captures full state - GIVEN a dashboard with 4 widgets at specific grid positions -- WHEN a PUT updates widget positions and adds metadata -- THEN the snapshot MUST include all 4 widgets and the new metadata exactly as persisted -- AND the snapshot MUST be complete and restorable to the exact prior state +- WHEN a PUT updates widget positions and changes its name and description +- THEN the snapshot MUST hold the state before the PUT, with all of its fields: the dashboard's name, description and other fields as they were stored, and all 4 widgets at their prior grid positions with their content +- AND restoring the snapshot MUST bring the 4 widgets back to those prior positions ### Requirement: REQ-VERS-002 Explicit Snapshot Creation @@ -116,6 +114,8 @@ The system MUST expose GET /api/dashboards/{uuid}/versions returning an ordered - THEN the system MUST resolve to `IVersionManager` file-versions and map each file-version to a compatible response object - AND the response format MUST be identical to database backend (versionNumber synthesized from file-version timestamp, createdBy from NC user ID if available, etc.) +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed; only the dispatch stub is pinned, by DashboardVersionServiceTest::testGroupfolderBackedDashboardReturnsSoftFail + #### Scenario: List versions for a dashboard with no snapshots - GIVEN a dashboard that exists but has no version snapshots @@ -131,6 +131,8 @@ The system MUST expose GET /api/dashboards/{uuid}/versions returning an ordered - AND MUST NOT return HTTP 500 or raise an error - AND the UI SHOULD show "version history disabled" to the user +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed; the soft-fail envelope is pinned by DashboardVersionServiceTest::testGroupfolderBackedDashboardReturnsSoftFail and the dialog's message by src/modals/__tests__/VersionHistoryModal.spec.js 'says so when versioning is not supported for the dashboard' + #### Scenario: Only owners and admins can list - GIVEN dashboard "My Dashboard" owned by "alice" @@ -230,6 +232,8 @@ The system MUST automatically prune old snapshots, keeping only the 50 most rece - THEN LaunchPad MUST NOT independently prune NC file-versions - AND the system MUST respect NC's retention settings +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed, so there are no NC file-versions for LaunchPad to leave alone + #### Scenario: Pruning does not affect versionNumber sequence - GIVEN a database-backed dashboard where versions 1..10 were pruned, versions 11..60 remain @@ -257,6 +261,8 @@ The system MUST emit a Nextcloud activity event for every restore, enabling audi - AND the event data MUST include: dashboardUuid, restoredFrom (versionNumber), restoredBy (alice), restoredAt (current timestamp) - AND admins viewing the activity log MUST see this event +@e2e exclude never built: `Extension::EVENT_RESTORED` ('dashboard_restored', lib/Activity/Extension.php:90) is declared, but nothing publishes it; `DashboardVersionService::restoreVersion()` emits no activity (the spec's Implementation Notes list REQ-VERS-007 as deferred) + #### Scenario: Activity events include full context - GIVEN a restore event is emitted @@ -264,6 +270,8 @@ The system MUST emit a Nextcloud activity event for every restore, enabling audi - THEN the event MUST be human-readable (e.g., "Alice restored dashboard 'My Dashboard' from version 3") - AND the event MUST link to the dashboard (via uuid) if the activity UI supports it +@e2e exclude never built: no `dashboard_restored` activity is ever published (see Activity event on restore), so there is no event whose wording or link could be checked + #### Scenario: Automatic snapshots do NOT emit activity - GIVEN a PUT operation creates an automatic snapshot (debounced) @@ -291,6 +299,8 @@ The system MUST transparently adapt all version endpoints to the dashboard's con - AND map each file-version object to a compatible response format - AND synthesize versionNumber from file-version timestamp if NC doesn't provide one, ensuring monotonic ordering +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed + #### Scenario: GroupFolder backend fetch snapshot - GIVEN a groupfolder-backed dashboard and a user requests GET /api/dashboards/{uuid}/versions/2 @@ -299,6 +309,8 @@ The system MUST transparently adapt all version endpoints to the dashboard's con - AND return the full file content - AND return HTTP 200 with the version body +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed; the stub's 404 is pinned by DashboardVersionServiceCoverageTest::testFetchSnapshotOnGroupfolderDashboardThrowsNotFound + #### Scenario: GroupFolder backend restore - GIVEN a groupfolder-backed dashboard at version 5 @@ -309,6 +321,8 @@ The system MUST transparently adapt all version endpoints to the dashboard's con 3. Return HTTP 200 - AND the content MUST revert to version 3's state +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed; the stub's refusal is pinned by DashboardVersionServiceCoverageTest::testRestoreVersionRefusesGroupfolderDashboard + #### Scenario: Mode detection is automatic - GIVEN a dashboard object @@ -316,6 +330,8 @@ The system MUST transparently adapt all version endpoints to the dashboard's con - THEN the system MUST check the dashboard's `contentBackend` field or equivalent to determine mode - AND route the call accordingly WITHOUT requiring a mode parameter in the API request +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed; with one backend there is no routing to observe, and the endpoints taking no mode parameter is what every test in tests/e2e/dashboard-versioning.spec.ts already calls + ### Requirement: REQ-VERS-009 Soft-Failure Tolerance The system MUST degrade gracefully when version storage is unavailable, returning HTTP 200 with an indication that versioning is not available, rather than raising HTTP 5xx errors. @@ -327,6 +343,8 @@ The system MUST degrade gracefully when version storage is unavailable, returnin - THEN the response MUST be HTTP 200 with body `{versions: [], modeSupported: false}` - AND no error MUST be logged (this is expected behavior) +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed; the envelope is pinned by DashboardVersionServiceTest::testGroupfolderBackedDashboardReturnsSoftFail + #### Scenario: IVersionManager unavailable - GIVEN a groupfolder-backed dashboard @@ -334,6 +352,8 @@ The system MUST degrade gracefully when version storage is unavailable, returnin - THEN the system MUST catch the exception and return HTTP 200 `{versions: [], modeSupported: false}` - AND a warning MAY be logged for ops visibility +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed + #### Scenario: Database connection error is NOT soft-fail - GIVEN a database-backed dashboard and the database is unreachable @@ -342,6 +362,8 @@ The system MUST degrade gracefully when version storage is unavailable, returnin - AND an error MUST be logged - NOTE: Soft-fail applies only to Nextcloud versioning unavailability (groupfolder mode), not database unavailability +@e2e exclude needs a database fault: e2e cannot make the instance's database unreachable for one request; the 500 mapping of an unexpected service failure is pinned by DashboardVersionApiControllerRestoreTest::testRestoreVersionHidesAndLogsUnexpectedFailures and DashboardVersionApiControllerTest::testCreateVersionHidesUnexpectedFailureDetail + #### Scenario: Graceful degradation UI hint - GIVEN the API returns `{versions: [], modeSupported: false}` for a groupfolder dashboard @@ -349,33 +371,33 @@ The system MUST degrade gracefully when version storage is unavailable, returnin - THEN the UI SHOULD display "Version history is not available for this dashboard" - AND the restore button SHOULD be disabled or hidden -### Requirement: The owner sees the version history (REQ-VERSUI-001) +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed, so no server answers `modeSupported: false`; the dialog's message is pinned by src/modals/__tests__/VersionHistoryModal.spec.js 'says so when versioning is not supported for the dashboard' and the hidden entry by src/views/__tests__/ViewsVersionHistory.spec.js 'REQ-VERSUI-001: an unsupported dashboard hides the entry' -@e2e exclude restoring needs a seeded version history on a live instance; the flow is asserted in src/modals/__tests__/VersionHistoryModal.spec.js and the menu gate in src/views/__tests__/ViewsVersionHistory.spec.js +### Requirement: The owner sees the version history (REQ-VERSUI-001) -The dashboard menu MUST show "Version history" to the dashboard owner and to administrators when versioning is supported for the dashboard. It MUST list versions newest first with number, date, author and note. +The versions of a dashboard MUST be the tab Versions of the dashboard settings (dashboards REQ-DASH-039, board LpVersies), offered to the dashboard owner and to administrators when versioning is supported for the dashboard. There MUST be no "Version history" entry in the dashboard menu or in More. The tab MUST list versions newest first in the columns When, By and What changed, and MUST mark the newest as the current version. #### Scenario: Owner opens the history - **GIVEN** Sanne owns the personal dashboard "Mijn week" and it has four saved versions -- **WHEN** she chooses "Version history" from the dashboard menu -- **THEN** a dialog lists the four versions newest first with date and author +- **WHEN** she opens the dashboard settings and chooses the tab Versions +- **THEN** the tab lists the four versions newest first with when, by whom and what changed, the newest marked as the current version #### Scenario: Colleague sees no entry - **GIVEN** Pieter can view but does not own "Mijn week" and is not an administrator -- **WHEN** he opens the dashboard menu -- **THEN** no "Version history" entry is shown +- **WHEN** he opens More on the dashboard +- **THEN** no version entry is shown and he cannot open the dashboard settings #### Scenario: Unsupported dashboard - **GIVEN** a groupfolder-backed dashboard for which `modeSupported` is false -- **WHEN** the owner opens the dashboard menu -- **THEN** the entry is hidden +- **WHEN** the owner opens the tab Versions +- **THEN** the tab says this dashboard keeps no versions -### Requirement: A person can save a named version (REQ-VERSUI-002) +@e2e exclude never built: the groupfolder backend does not exist. `Dashboard` has no `contentBackend` field, so `DashboardVersionService::isGroupfolderBacked()` (lib/Service/DashboardVersionService.php:588) always answers false, `IVersionManager` is never called anywhere in lib/ (it appears only in a doc comment), and every dashboard is database-backed, so no dashboard answers `modeSupported: false`. -@e2e exclude restoring needs a seeded version history on a live instance; the flow is asserted in src/modals/__tests__/VersionHistoryModal.spec.js and the menu gate in src/views/__tests__/ViewsVersionHistory.spec.js +### Requirement: A person can save a named version (REQ-VERSUI-002) The history dialog MUST offer "Save this version now" with an optional note, calling the explicit snapshot endpoint, and the new version MUST appear at the top of the list. @@ -387,8 +409,6 @@ The history dialog MUST offer "Save this version now" with an optional note, cal ### Requirement: Restoring asks first and can be undone (REQ-VERSUI-003) -@e2e exclude restoring needs a seeded version history on a live instance; the flow is asserted in src/modals/__tests__/VersionHistoryModal.spec.js and the menu gate in src/views/__tests__/ViewsVersionHistory.spec.js - Restore MUST ask for confirmation naming the version date, restore through the restore endpoint, and reload the dashboard. The list MUST then show the `pre-restore` version so the restore can itself be reversed. #### Scenario: Restore last week's layout @@ -397,6 +417,39 @@ Restore MUST ask for confirmation naming the version date, restore through the r - **WHEN** she restores the Friday version and confirms - **THEN** the dashboard reloads with the Friday layout and the list holds a new `pre-restore` entry with Monday's layout +### Requirement: Each automatic version says what changed (REQ-VERSUI-004) + +An automatic snapshot (REQ-VERS-001) MUST carry a note of at most 120 characters that names what changed since the +previous snapshot: "Dashboard renamed to {name}", "Columns from {old} to {new}", "Widget {title} added", "Widget +{title} removed", "Widget {old} renamed to {new}", "Widget {title} moved", "Widget {title} resized". When more than one +thing changed, the note MUST name the first and count the rest ("Widget Inbox added and 2 more changes"). A widget is +named by its title, else by its type. An explicit snapshot with a note of its own (REQ-VERSUI-002) MUST keep that note. +Notes MUST be in the language of the person who made the change. + +#### Scenario: A widget moved + +- **GIVEN** Pieter moves the widget Nieuws on Intranet Zuiddrecht +- **WHEN** the snapshot is written +- **THEN** the Versions tab shows "Widget Nieuws moved" by Pieter Jansen + +#### Scenario: Several changes at once + +- **GIVEN** Femke adds the widget Inbox, removes Oud nieuws and changes the columns from 8 to 12 in one save +- **WHEN** the snapshot is written +- **THEN** its note reads "Widget Inbox added and 2 more changes" + +### Requirement: A template update is noted as such (REQ-VERSUI-005) + +When a template re-sync (admin-templates REQ-RESYNC-001) changes a copy, the version it writes MUST name the template as +its author ("Template {name}") and MUST carry the note "Updated from the template", instead of the administrator who +ran the re-sync and a list of widget changes. + +#### Scenario: Intranet updated from its template + +- **GIVEN** Intranet Zuiddrecht is a copy of template "Intranet" +- **WHEN** the administrator re-syncs the template +- **THEN** the copy's Versions tab shows a version by "Template Intranet" with "Updated from the template" + ## Non-Functional Requirements - **Performance**: GET /api/dashboards/{uuid}/versions MUST return within 500ms for dashboards with up to 50 versions. Restore operations MUST complete within 2 seconds. @@ -413,7 +466,7 @@ Restore MUST ask for confirmation naming the version date, restore through the r - REQ-VERS-002 (Explicit snapshot): `POST /api/dashboards/{uuid}/versions` → `DashboardVersionApiController::createVersion()` → `DashboardVersionService::createExplicitSnapshot()`. Calls `captureSnapshot(... explicit: true)` which bypasses the debounce. - REQ-VERS-003 (List versions): `GET /api/dashboards/{uuid}/versions` → `DashboardVersionApiController::listVersions()` → `DashboardVersionService::listVersions()`. Returns the `{versions: [...], modeSupported: bool}` envelope ordered newest-first; `DashboardVersion::jsonSerialize()` deliberately omits `snapshotJson` so list responses stay light. - REQ-VERS-004 (Fetch snapshot): `GET /api/dashboards/{uuid}/versions/{versionNumber}` → `DashboardVersionApiController::fetchVersion()` → `DashboardVersionService::fetchSnapshot()`. Surfaces the full body alongside the metadata. -- REQ-VERS-005 (Restore + reversibility): `POST /api/dashboards/{uuid}/versions/{versionNumber}/restore` → `DashboardVersionApiController::restoreVersion()` → `DashboardVersionService::restoreVersion()`. Captures pre-restore state as a new snapshot before applying the historical body and stamps the dashboard's `updatedAt`. Restoring to the latest version is idempotent (no new snapshot, no DB update). +- REQ-VERS-005 (Restore + reversibility): `POST /api/dashboards/{uuid}/versions/{versionNumber}/restore` → `DashboardVersionApiController::restoreVersion()` → `DashboardVersionService::restoreVersion()`. Captures pre-restore state as a new snapshot before applying the historical body and stamps the dashboard's `updatedAt`. Restoring the latest version while it holds the current placements is idempotent (no new snapshot, no DB update); a latest version that differs, such as a pre-restore snapshot, is restored. - REQ-VERS-006 (Retention 50 / monotonic): `DashboardVersionService::captureSnapshot()` allocates `max(version_number) + 1` and calls `DashboardVersionMapper::pruneOldVersions()` inline. Pruning uses a Postgres-safe two-step (cutoff lookup + DELETE WHERE version_number < cutoff) so survivors keep their numbering. - REQ-VERS-008 (Mode-aware backend dispatch): `DashboardVersionService::isGroupfolderBacked()` is the dispatch hook. Until the sibling `groupfolder-storage-backend` change adds the `contentBackend` column, it defensively returns `false` and every dashboard is treated as DB-backed. - REQ-VERS-009 (Soft-failure tolerance): `listVersions()` returns `{versions: [], modeSupported: false}` for groupfolder-backed dashboards today (the dispatch hook always misses); `fetchSnapshot()` and `restoreVersion()` raise the canonical sentinel `ERR_VERSIONING_UNAVAILABLE` so the controller can map to the soft-fail envelope. diff --git a/openspec/specs/dashboard-view-analytics/screens.md b/openspec/specs/dashboard-view-analytics/screens.md new file mode 100644 index 000000000..652ed6b02 --- /dev/null +++ b/openspec/specs/dashboard-view-analytics/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerAnalyse https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAnalyse diff --git a/openspec/specs/dashboard-view-analytics/spec.md b/openspec/specs/dashboard-view-analytics/spec.md index 819575eca..7fe5fb47e 100644 --- a/openspec/specs/dashboard-view-analytics/spec.md +++ b/openspec/specs/dashboard-view-analytics/spec.md @@ -27,9 +27,9 @@ Two settings gate tracking: |---------|-------|---------|-----------------| | `launchpad.analytics_enabled` | global | `true` | All view events are no-ops. | | `launchpad.analytics_optout` | per-user pref | `false` | This user's view events are no-ops. | + ## Requirements -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface ### Requirement: REQ-ANLT-001 Dashboard Views Table Schema @@ -67,6 +67,8 @@ The system MUST track dashboard view events in a dedicated relational table with #### Scenario: Schema supports multiple databases +@e2e exclude needs the migration run on SQLite, MySQL and PostgreSQL, and one e2e run is one database. The PHPUnit job runs the migrations on all three (database-test-matrix in .github/workflows/code-quality.yml). On the database the e2e instance runs, tests/e2e/dashboard-view-analytics-history.spec.ts introspects the live table and asserts the composite unique index refuses a second row for the same day; no test asserts that refusal on the other two backends. + - GIVEN the Nextcloud instance may use SQLite, MySQL, or PostgreSQL - WHEN the migration runs on any of these databases - THEN the table MUST be created with identical semantics @@ -443,7 +445,7 @@ The system MUST call the view-event endpoint from the Vue frontend when a dashbo - WHEN both tabs load and try to post view events within 1 second - THEN only ONE `POST /api/dashboards/{uuid}/view-event` MUST be sent - AND the second tab's event MUST be debounced/cancelled -- NOTE: Debounce window is 1 second per dashboard instance; debounce is per-tab-session, not cross-tab +- NOTE: The debounce holds across the open tabs of one browser: the tab that sends holds a Web Lock named after the dashboard for 1 second, and another tab that finds it held sends nothing. Within one tab the window is 1 second per dashboard. A browser without the Locks API sends from every tab. #### Scenario: Different dashboards are not debounced against each other @@ -497,6 +499,8 @@ The system MUST track per-tile (per-widget-placement) click events in a dedicate #### Scenario: Schema supports multiple databases +@e2e exclude needs the migration run on SQLite, MySQL and PostgreSQL, and one e2e run is one database. The PHPUnit job runs the migrations on all three (database-test-matrix in .github/workflows/code-quality.yml). On the database the e2e instance runs, tests/e2e/dashboard-view-analytics-history.spec.ts introspects the live table and asserts the composite unique index refuses a second row for the same day; no test asserts that refusal on the other two backends. + - GIVEN the Nextcloud instance may use SQLite, MySQL, or PostgreSQL - WHEN the migration runs on any of these databases - THEN the table MUST be created with identical semantics @@ -632,8 +636,6 @@ The system MUST expose an admin-only CSV export of tile analytics, MUST reuse th ### Requirement: An administrator sees the most clicked tiles (REQ-TILEUI-001) -@e2e exclude reading a count needs clicks recorded on a live instance; the report is asserted in src/components/admin/__tests__/TileClickReport.spec.js and the names in tests/Unit/Service/TileAnalyticsServiceTest.php - The analytics page in administration MUST show the most clicked tiles for the selected period with dashboard name, tile title, click count and distinct people, and MUST offer the CSV export. #### Scenario: Top tiles for thirty days @@ -650,8 +652,6 @@ The analytics page in administration MUST show the most clicked tiles for the se ### Requirement: Tile numbers are not shown when tracking is off (REQ-TILEUI-002) -@e2e exclude reading a count needs clicks recorded on a live instance; the report is asserted in src/components/admin/__tests__/TileClickReport.spec.js and the names in tests/Unit/Service/TileAnalyticsServiceTest.php - When tile tracking is inactive, the tiles section MUST state that clicks are not recorded and MUST NOT show a table or an export button. #### Scenario: Tracking off @@ -659,3 +659,27 @@ When tile tracking is inactive, the tiles section MUST state that clicks are not - **GIVEN** the administrator switched tile tracking off - **WHEN** Ruben opens the Tiles section - **THEN** a message says clicks are not being recorded and no table is rendered + +### Requirement: A person turns view counting off in their own settings (REQ-ANLT-UI-001) + +LaunchPad's personal settings MUST show a "Count my visits" switch, on by default. Turning it off MUST store `analytics_optout = true` for that person, so REQ-ANLT-004 ignores their view and tile-click events. Turning it on again MUST store `false`. The switch MUST NOT show when an administrator has turned analytics off for everyone. + +#### Scenario: A person stops their visits being counted + +- **GIVEN** Eva is signed in and analytics is on for the organisation +- **WHEN** she opens her LaunchPad settings and turns "Count my visits" off +- **THEN** her user value `analytics_optout` is `true` +- **AND** her next dashboard visit adds nothing to the view counts + +#### Scenario: A person counts again + +- **GIVEN** Eva turned "Count my visits" off earlier +- **WHEN** she turns it on again +- **THEN** her user value `analytics_optout` is `false` +- **AND** her next dashboard visit is counted + +#### Scenario: Analytics is off for everyone + +- **GIVEN** an administrator turned analytics off for the organisation +- **WHEN** Eva opens her LaunchPad settings +- **THEN** the "Count my visits" switch is not shown diff --git a/openspec/specs/dashboards-and-who-may-see-them/spec.md b/openspec/specs/dashboards-and-who-may-see-them/spec.md new file mode 100644 index 000000000..28c11d24c --- /dev/null +++ b/openspec/specs/dashboards-and-who-may-see-them/spec.md @@ -0,0 +1,219 @@ +# dashboards-and-who-may-see-them Specification + +## Purpose +The reports launchpad ships, the personal layer over a dashboard somebody +else owns, and the activity, geographic and storage reporting the round 4 +competitor sweep found in eleven other products. Sits on `dashboards`, +`widgets`, `activity-feed-integration` and `dashboard-view-analytics`. +Requested by the dossiq competitor programme, discovery cluster 12. + +## Requirements + +### Requirement: REQ-DWMS-001 A personal layer over a shared dashboard + +A user MUST be able to reorder, resize and hide widget placements on a +dashboard they do not own. The differences MUST be stored as a personal +layer keyed by user and dashboard, holding only order, size and the hidden +set, and MUST be applied over the shared dashboard at render time. The +layer MUST be invisible to every other user. A placement marked compulsory +by `admin-templates` MUST NOT be hideable, and MAY be moved. + +Candidate C-reporting-10, `should`, two driven passers (itop, +xxllnc-zaken). + +#### Scenario: A handler rearranges the team dashboard for themselves + +- **GIVEN** a group-shared dashboard with six widgets +- **WHEN** a member of the group moves two widgets and hides a third +- **THEN** that member sees their arrangement +- **AND** every other member still sees the arrangement the administrator composed + +#### Scenario: A compulsory widget cannot be hidden + +- **GIVEN** a shared dashboard with one compulsory placement +- **WHEN** a user tries to hide it +- **THEN** the request is refused and names the placement as compulsory + +### Requirement: REQ-DWMS-002 One action puts the dashboard back + +A user with a personal layer MUST be able to remove it in one action. The +removal MUST delete the whole layer, not part of it, and MUST return the +dashboard to what its owner composed. A user with no layer MUST see the +owner's arrangement unchanged. + +Candidate C-reporting-10, the reset half. + +#### Scenario: Reset to the organisation's arrangement + +- **GIVEN** a user with a personal layer on a shared dashboard +- **WHEN** the user chooses to reset the dashboard +- **THEN** the layer is deleted and the owner's arrangement renders +- **AND** the action is confirmed before it runs + +### Requirement: REQ-DWMS-003 Reports the product ships + +The system MUST ship report definitions with the app: an id, a title, a +description, the aggregation to run, its parameters and its rendering. The +definitions MUST be listed in a gallery, MUST be runnable without composing +a dashboard, and MUST NOT be editable in place. A report whose registers or +schemas are absent MUST be listed as unavailable with the missing names, +and MUST NOT error when opened. A result MUST be saveable as an ordinary +dashboard owned by the user who saved it. + +Candidate C-reporting-2, `could`, one driven passer (glpi). + +#### Scenario: A report runs on a fresh instance + +- **GIVEN** a new instance with no dashboards +- **WHEN** an administrator opens the report gallery and runs "Open cases by team" +- **THEN** the report renders without anything being composed first + +#### Scenario: A report whose schema is missing says so + +- **GIVEN** a report declaring a schema the instance has not installed +- **WHEN** the gallery is opened +- **THEN** the report is listed as unavailable and names the missing schema + +### Requirement: REQ-DWMS-004 A dated status report with a health rating + +The system MUST support a status report on a body of work carrying a date, +a health rating (`on-track`, `at-risk`, `off-track`), a prefilled summary +and the figures it was prefilled from. The figures MUST be computed by the +product, the summary MUST be editable before the report is kept, and the +kept report MUST record which values were computed and which were written +by a person. + +Candidate C-reporting-3, `could`, one driven passer (odoo). + +#### Scenario: A programme report is prefilled and then edited + +- **GIVEN** a body of work with open and closed items and a deadline +- **WHEN** a user creates a status report +- **THEN** the health rating and the figures are prefilled +- **AND** the user edits the summary and keeps the report +- **AND** the report records the summary as written by a person + +### Requirement: REQ-DWMS-005 Activity reporting names its purpose + +Reporting on a named person's activity MUST be off until an administrator +enables it and records a purpose. The purpose MUST be shown on every screen +that reports on a named person. Every read of a named person's activity by +somebody else MUST be written to the audit trail with the reader, the +subject and the period. A person MUST always be able to read their own +activity, without the capability being enabled and without a log entry. + +Candidates C-reporting-13 and C-reporting-19, both `could`. Driven passers: +plane for the first, forgejo, gitea and gitlab for the second. + +#### Scenario: The capability is off by default + +- **GIVEN** a fresh instance +- **WHEN** an administrator opens a person's activity +- **THEN** the screen says the capability is off and how to enable it + +#### Scenario: Reading a colleague's activity is logged + +- **GIVEN** activity reporting enabled with the purpose "workload balancing" +- **WHEN** an administrator reads September for a named user +- **THEN** the purpose is shown on the screen +- **AND** an audit entry records the reader, the subject and September + +#### Scenario: A person reads their own activity + +- **GIVEN** activity reporting disabled +- **WHEN** a user opens their own activity +- **THEN** it renders, and no audit entry is written + +### Requirement: REQ-DWMS-006 Activity as a figure and as a calendar + +With the capability enabled, the system MUST report a person's activity +across the product for a period as counts per activity type, and as a +calendar of intensity per day. Both MUST be bucketed per day, MUST be +derived from the existing activity events, and MUST be exportable as CSV. +Neither MUST report hours. + +Candidates C-reporting-13 and C-reporting-19. + +#### Scenario: A month as a heatmap + +- **GIVEN** a user with activity on twelve days of September +- **WHEN** an administrator opens the calendar view for September +- **THEN** twelve days carry an intensity and the rest are empty + +#### Scenario: The export carries the same numbers + +- **GIVEN** the same period +- **WHEN** the administrator exports it +- **THEN** the CSV totals equal the figures on screen + +### Requirement: REQ-DWMS-007 Recent colleague activity, filtered by what you may see + +The system MUST offer a widget listing recent activity by other users, +built from the existing activity feed and filtered to what the reader is +allowed to see. An entry the reader may not see MUST be absent, not +redacted, and MUST NOT be counted in any total the widget shows. + +Candidate C-reporting-26, `could`, one driven passer (zammad). + +#### Scenario: A colleague's work on a hidden dashboard is not listed + +- **GIVEN** a user who cannot see dashboard A +- **WHEN** a colleague edits dashboard A and the user opens the widget +- **THEN** the edit is absent from the list and from its count + +### Requirement: REQ-DWMS-008 Search inside a widget's results + +A widget rendering rows MUST offer a filter over its rendered rows. The +filter MUST live in view state only: it MUST NOT be persisted, MUST NOT be +shared with other users, MUST NOT modify the placement or its saved search, +and MUST be cleared by reloading the dashboard. + +Candidate C-reporting-21, `could`, one driven passer (xxllnc-zaken). + +#### Scenario: Filtering a widget leaves its definition alone + +- **GIVEN** a widget with a saved search for open cases +- **WHEN** the user types a filter term and then reloads the page +- **THEN** the rows are filtered before the reload and unfiltered after it +- **AND** the placement's saved search is unchanged + +### Requirement: REQ-DWMS-009 Geographic trend reporting + +The system MUST report counts and rates per area over a period for objects +that carry a location, with the area taken from a declared property. An +object with no location MUST be counted in an explicit "no location" +bucket, never dropped silently. + +Candidate C-reporting-25, `could`, one documented passer (mozard). +Documented, never counted in a driven tally (D21). + +#### Scenario: Reports per district over a quarter + +- **GIVEN** objects with a district property and a quarter to report on +- **WHEN** the report runs +- **THEN** each district carries a count and a rate +- **AND** objects without a district are counted in the "no location" bucket + +### Requirement: REQ-DWMS-010 Storage use per workspace and service, over time + +The system MUST report storage use per workspace and per service, as a +figure now and as a series over time, from the platform's own storage +figures and the register counts, never by walking objects. The report MUST +name what can be removed: items past their retention and orphaned uploads. +The report MUST be exportable as CSV, and MUST be administrator-only. + +Candidate C-reporting-28, `could`, one driven passer (tuleap) and one +documented (youtrack). + +#### Scenario: An administrator sees where the disk went + +- **GIVEN** an instance with three workspaces +- **WHEN** an administrator opens the storage report +- **THEN** each workspace carries a current figure and a twelve-month series +- **AND** the removable total is named separately from the total in use + +#### Scenario: A non-administrator is refused + +- **GIVEN** an ordinary user +- **WHEN** they request the storage report +- **THEN** the request is refused with 403 diff --git a/openspec/specs/dashboards/screens.md b/openspec/specs/dashboards/screens.md new file mode 100644 index 000000000..2bff886e0 --- /dev/null +++ b/openspec/specs/dashboards/screens.md @@ -0,0 +1,9 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet +- LpDelen https://identity.conduction.nl/screens/board?id=launchpad/LpDelen +- LpDashboardInstellingen https://identity.conduction.nl/screens/board?id=launchpad/LpDashboardInstellingen +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpStart https://identity.conduction.nl/screens/board?id=wilgenboom/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=vaartveld/LpStart +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag: today on one screen, with your own open cases and work items from dossiq and a link through to the work queue (d-work-queue) diff --git a/openspec/specs/dashboards/spec.md b/openspec/specs/dashboards/spec.md index 89df16661..af7bf1d12 100644 --- a/openspec/specs/dashboards/spec.md +++ b/openspec/specs/dashboards/spec.md @@ -30,9 +30,8 @@ Each dashboard record is stored in the `oc_launchpad_dashboards` table with the - **isActive**: SMALLINT (0/1) flag indicating if this is the user's currently active dashboard - **createdAt**: Timestamp string (Y-m-d H:i:s) - **updatedAt**: Timestamp string (Y-m-d H:i:s) -## Requirements -@e2e exclude all 163 scenarios test REST/service/factory/tree API — dashboard CRUD and tree ops have no dedicated UI flow in v1.0.5 (UI flows tested via runtime-shell, dashboard-switcher, tiles, widgets specs) +## Requirements ### Requirement: Create Personal Dashboard (REQ-DASH-001) @@ -62,6 +61,7 @@ Users MUST be able to create new personal dashboards with a name, optional descr - THEN the system MUST return HTTP 400 with a validation error - AND `gridColumns` MUST only accept positive integers (minimum 1, maximum 24) - NOTE: Grid column validation is NOT currently implemented +@e2e exclude never built: the create path validates no column count, DashboardApiController::create() reads only `gridColumns` and offeredGridColumns() turns any count outside 6, 8 and 12 into null, the administrator's default, with 201 (the snake_case `grid_columns` is not read at all); the only refusal of a column count is the update path's 6/8/12 rule of REQ-DASH-038, not the 1..24 range this scenario names #### Scenario: Create a dashboard without a name - GIVEN a logged-in Nextcloud user "alice" @@ -76,6 +76,7 @@ Users MUST be able to create new personal dashboards with a name, optional descr - "recommendations" widget at (0, 0) with size 6x5 - "activity" widget at (6, 0) with size 6x5 - AND both placements MUST have `showTitle: 1`, `isVisible: 1`, and appropriate sortOrder values +@e2e exclude GIVEN unreachable on the CI instance: SeedDefaultDashboard seeds a `default`-group dashboard that every new user resolves to before tryCreateFromTemplate() runs, and removing it would empty the shared instance; the product also seeds the tile and Files bundle now, not recommendations/activity (the scenario text is stale). Pinned by tests/Unit/Service/DashboardServiceCreateDefaultsTest.php::testSeedDefaultsInsertsThreeTilesAndFilesWidget and tests/Unit/Service/DashboardServiceCreationGoldenTest.php::testProvisionedDashboardPlacements ### Requirement: List User Dashboards (REQ-DASH-002) @@ -133,6 +134,7 @@ Users MUST be able to retrieve their currently active dashboard along with its p - WHEN he sends GET /api/dashboard - THEN the system MUST create a default "My Dashboard" with recommendations and activity widgets - AND the response MUST return the newly created dashboard +@e2e exclude needs an instance without the seeded `default`-group dashboard (SeedDefaultDashboard), which getEffectiveDashboard() answers before it provisions a personal one; removing it would empty the shared instance. Pinned by tests/Unit/Service/DashboardServiceCreationGoldenTest.php::testProvisionedDashboardPlacements #### Scenario: First-time user with dashboards disabled and no template - GIVEN user "eve" has no dashboards @@ -141,6 +143,7 @@ Users MUST be able to retrieve their currently active dashboard along with its p - WHEN she sends GET /api/dashboard - THEN the system MUST return null (no dashboard available) - AND the response MUST return HTTP 404 or an empty result +@e2e exclude needs an instance without the seeded `default`-group dashboard (SeedDefaultDashboard), which is answered first; removing it would empty the shared instance. Pinned by tests/Unit/Service/DashboardServiceCreationGoldenTest.php::testNoTemplateAndNoPersonalDashboardsProvisionsNothing ### Requirement: Update Dashboard (REQ-DASH-004) @@ -255,6 +258,7 @@ Dashboard names MUST be validated for length and content. - THEN the system MUST return HTTP 400 with a validation error - AND dashboard names MUST be between 1 and 255 characters - NOTE: Name length validation is NOT currently implemented +@e2e exclude never built: nothing on the create path checks the name's length, resolveCreateParams() and resolveCreateBody() pass the name through as given and DashboardFactory::create() sets it unchecked; no unit test pins a limit #### Scenario: Duplicate dashboard names allowed - GIVEN user "alice" already has a dashboard named "Work" @@ -345,7 +349,7 @@ The system MUST support a third dashboard type `group_shared` in addition to `us #### Scenario: Non-admin cannot create a group-shared dashboard -- GIVEN a logged-in user "alice" who is not an administrator +- GIVEN a logged-in user "alice" who is not an administrator and has no LaunchPad Admin or Editor role - WHEN she sends `POST /api/dashboards/group/marketing` with any body - THEN the system MUST return HTTP 403 @@ -374,12 +378,14 @@ The system MUST support a third dashboard type `group_shared` in addition to `us - GIVEN any caller attempts to insert a dashboard row with `type='group_shared'` and `groupId IS NULL` - THEN the system MUST throw `\InvalidArgumentException` (enforced by `DashboardFactory::create()`) - AND no row MUST be persisted +@e2e exclude no HTTP route can create a group_shared dashboard without a groupId (the group is a required path segment of POST /api/dashboards/group/{groupId}), so this is an internal factory invariant; pinned by tests/Unit/Service/DashboardFactoryGroupSharedTest.php::testCreateGroupSharedRequiresGroupId and ::testCreateGroupSharedRejectsEmptyGroupId #### Scenario: Invariant — non-`group_shared` types must not have a `groupId` - GIVEN any caller attempts to insert a dashboard with `type='user'` and `groupId='marketing'` - THEN the system MUST throw `\InvalidArgumentException` - AND no row MUST be persisted +@e2e exclude no HTTP route passes a groupId to a user-type create (POST /api/dashboard takes none), so this is an internal factory invariant; pinned by tests/Unit/Service/DashboardFactoryGroupSharedTest.php::testCreateUserTypeRejectsGroupId ### Requirement: REQ-DASH-012 Default-group sentinel @@ -430,6 +436,7 @@ Each returned dashboard MUST carry an additional `source` field with values `'us - GIVEN a group-shared dashboard exists where the user is a member of the targeted group AND that same dashboard's UUID also appears in another result set (rare edge case from a future multi-group support or a misconfigured fixture) - WHEN she calls `GET /api/dashboards/visible` - THEN it MUST appear only once in the response +@e2e exclude the GIVEN cannot be built through the API: a group-shared row reaches a user through her groups or the `default` sentinel only, and it cannot be shared to her because DashboardShareService::assertOwner() needs an owner; the mapper's UUID dedup is pinned by tests/Unit/Db/DashboardMapperGroupSharedTest.php::testFindVisibleToUserDeduplicatesByUuid #### Scenario: User with no personal dashboards still gets visible result @@ -446,6 +453,7 @@ Each returned dashboard MUST carry an additional `source` field with values `'us - AND no default-group dashboards exist - WHEN she calls `GET /api/dashboards/visible` - THEN the response MUST contain exactly 1 dashboard with `source='user'` +@e2e exclude needs an instance with no `default`-group dashboard at all, and SeedDefaultDashboard seeds one; removing it would empty the shared instance. Pinned by tests/Unit/Db/DashboardMapperGroupSharedTest.php::testFindVisibleToUserZeroGroupsPersonalAndDefault and ::testFindVisibleToUserNothingReturnsEmpty #### Scenario: Admin gets group-shared dashboards as `source='group'` even though they own them @@ -460,11 +468,25 @@ Each returned dashboard MUST carry an additional `source` field with values `'us The system MUST expose CRUD endpoints scoped to a group: - `GET /api/dashboards/group/{groupId}` — list group-shared dashboards in that group (any logged-in user can list) -- `POST /api/dashboards/group/{groupId}` — create a new one (admin only) +- `POST /api/dashboards/group/{groupId}` — create a new one: a Nextcloud administrator or a LaunchPad Admin for any group, an Editor for a group they belong to (Ruben, 21 Nov 2026). An Editor cannot create one for the `default` group, which means everyone. Anyone else gets HTTP 403. The new dashboard has no owner (`userId` null). - `GET /api/dashboards/group/{groupId}/{uuid}` — get one (any logged-in user) - `PUT /api/dashboards/group/{groupId}/{uuid}` — update name/layout/icon (admin only) - `DELETE /api/dashboards/group/{groupId}/{uuid}` — remove (admin only) +#### Scenario: An Editor creates a group dashboard for their own group + +- GIVEN bob has the LaunchPad role "editor" and is in group "engineering" +- WHEN he sends `POST /api/dashboards/group/engineering` with `{"name": "Engineering"}` +- THEN the system MUST return HTTP 201 with a `group_shared` dashboard for "engineering" +- AND its `userId` MUST be null + +#### Scenario: An Editor cannot create a group dashboard for another group + +- GIVEN bob has the LaunchPad role "editor" and is not in group "sales" +- WHEN he sends `POST /api/dashboards/group/sales` +- THEN the system MUST return HTTP 403 +- AND no dashboard MUST be created + #### Scenario: Update propagates immediately - GIVEN admin updates the layout of group-shared dashboard `D1` @@ -485,6 +507,7 @@ The system MUST expose CRUD endpoints scoped to a group: - THEN the system MUST delete the dashboard - AND return HTTP 200 - NOTE: the default group is curated, not user-bound — admins can intentionally clear it +@e2e exclude needs the `default` group to hold exactly one dashboard, but it holds the instance's seeded one, which other specs rely on; deleting one of two would pass without the exemption and prove nothing. Pinned by tests/Unit/Service/DashboardServiceGroupSharedTest.php::testDeleteGroupSharedAllowsLastInDefaultGroup #### Scenario: Update on a group-shared dashboard rejects userId field changes @@ -605,6 +628,7 @@ Updates to a group-shared dashboard via `PUT /api/dashboards/group/{groupId}/{uu When the workspace page renders for a user, the system MUST resolve which dashboard is "active" by walking the following precedence and stopping at the first match: 1. The dashboard whose UUID equals the user's `active_dashboard_uuid` preference, IF that dashboard is currently visible to the user (per REQ-DASH-013). +1b. For a user who owns no personal dashboard: the admin template that applies to them (admin-templates REQ-TMPL-019, which also says when the default template waits for step 2). 2. The `group_shared` dashboard with `isDefault = 1` in the user's primary group (per REQ-DASH-015). 3. The `group_shared` dashboard with `isDefault = 1` in the synthetic `'default'` group. 4. The first `group_shared` dashboard (by `sortOrder` ascending, then `createdAt`) in the user's primary group. @@ -653,6 +677,7 @@ The resolver MUST attach a `source` field to the returned dashboard descriptor w - THEN the resolver MUST return `null` - AND the response MUST include `activeDashboardId: ''` in initial state - AND the page MUST render the empty-state UI +@e2e exclude needs a brand-new install with no dashboard of any type, which would empty the shared instance. Pinned by tests/Unit/Service/DashboardServiceActiveResolutionTest.php::testStep7EmptyStateReturnsNull and tests/Unit/Controller/PageControllerHelpersTest.php::testNoActiveDashboardDescribesAnEmptyGroupWorkspace ### Requirement: REQ-DASH-019 Persist active-dashboard preference @@ -727,6 +752,7 @@ The fork operation MUST execute inside a single database transaction. If any par - THEN the new dashboard row MUST also be removed (transaction rolled back) - AND `S`'s placements MUST remain visible to alice - AND alice's previously active dashboard (if any) MUST remain active +@e2e exclude needs a database error injected while the cloned placements are inserted, which a live instance cannot be made to raise on demand; pinned by tests/Unit/Service/DashboardServiceForkTest.php::testForkRollsBackOnPlacementCloneFailure ### Requirement: REQ-DASH-022 Fork does not duplicate uploaded resources @@ -906,6 +932,7 @@ The system MUST expose `GET /api/dashboards/tree` returning the full visible tre - GIVEN user "bob" has no dashboards - WHEN he sends GET /api/dashboards/tree - THEN the response MUST be an empty array (or `{children: []}` depending on schema) +@e2e exclude a fresh account on the shared instance still sees the instance-wide default group dashboard that SeedDefaultDashboard provisions, so its tree is never empty without emptying the shared instance; the empty case is pinned by tests/Unit/Service/DashboardTreeServiceTest.php::testGetFilteredTreeWithEmptyUuidsReturnsEmpty ### Requirement: REQ-DASH-027 Path-based dashboard resolution @@ -1070,6 +1097,7 @@ The system MUST track dashboard publication state via three new database columns - AND all existing dashboard rows MUST acquire `publication_status = 'published'` automatically via the column default (no explicit UPDATE statement is needed — design D1) - AND a composite index `launchpad_dash_user_pub` on `(user_id, publication_status)` MUST be created - NOTE: New dashboards created after the migration default to `'draft'` via application logic in `DashboardFactory::create()`, NOT via the column default. The column default exists only to backfill pre-existing rows safely. +@e2e exclude needs an instance that held dashboards before Version001011Date20260502130000 ran; CI installs a fresh instance, so there are no pre-existing rows to backfill. No PHPUnit test exercises this migration (none in tests/Unit/Migration) #### Scenario: Timestamp formats @@ -1086,7 +1114,7 @@ The system MUST track dashboard publication state via three new database columns ### Requirement: REQ-DASH-032 Publish action -The system MUST expose `POST /api/dashboards/{uuid}/publish` that transitions a dashboard to `published` and stamps `publishedAt = now()` the first time the transition occurs. The action MUST be idempotent and gated to the dashboard owner or a Nextcloud administrator. +The system MUST expose `POST /api/dashboards/{uuid}/publish` that transitions a dashboard to `published` and stamps `publishedAt = now()` the first time the transition occurs. The action MUST be idempotent and gated to the dashboard owner or a Nextcloud administrator: the owner publishes their own dashboard, and an administrator keeps the right for every dashboard (Ruben, 21 Nov 2026). The shipped action matrix (`lib/actions.seed.json`) therefore opens `dashboard.publish`, `dashboard.unpublish` and `dashboard.schedule` to every user, the route checks owner-or-admin per dashboard, and the action baseline repair step (revision 6) opens the three on an existing instance where the entry is still the pristine admin-only default. #### Scenario: Publish a draft dashboard @@ -1191,6 +1219,7 @@ The system MUST expose `POST /api/dashboards/{uuid}/schedule` accepting `{publis - AND `published_at` MUST be set to the current time when previously null - AND the method MUST return the number of dashboards materialised - NOTE: Lazy read-time materialisation remains the correctness contract (REQ-DASH-034 scenario "lazy materialisation"); this method is a cosmetic optimisation for cleaner audit data. +@e2e exclude every read materialises lazily, so no HTTP response shows whether the stored row flipped; getVisibleToUser() runs the flip, whose one announcement is the e2e for activity-feed-integration::group-dashboard-published; pinned by tests/Unit/Activity/DashboardActivityEmissionTest.php and tests/Unit/Db/DashboardMapperCoverageTest.php::testFindDueScheduled ### Requirement: REQ-DASH-035 Migration backfill to published state @@ -1202,6 +1231,7 @@ The publication-state migration MUST preserve the visibility of every dashboard - WHEN `Version001011Date20260502130000::changeSchema()` runs - THEN the `publication_status` column MUST be added with `DEFAULT 'published'` - AND every existing row MUST acquire `'published'` via the column default — no explicit `UPDATE` statement is required (design D1) +@e2e exclude needs an instance that held dashboards before Version001011Date20260502130000 ran; CI installs a fresh instance. No PHPUnit test exercises this migration (none in tests/Unit/Migration) #### Scenario: New dashboards default to draft despite the column default @@ -1241,6 +1271,7 @@ The Pinia dashboard store MUST track `publicationStatus`, `publishAt`, and `publ - GIVEN the dashboard store module is imported - THEN it MUST export `STATUS_DRAFT`, `STATUS_PUBLISHED`, and `STATUS_SCHEDULED` constants matching the PHP entity values +@e2e exclude a JavaScript module export with no browser surface; no Vitest asserts the three constants (none in src/**/__tests__), the matching PHP values are pinned by tests/Unit/Db/DashboardTest.php #### Scenario: Client-side lazy materialisation hint @@ -1248,6 +1279,7 @@ The Pinia dashboard store MUST track `publicationStatus`, `publishAt`, and `publ - WHEN any caller invokes `dashboardStore.effectivePublicationStatus(dashboard)` - THEN the method MUST return `'published'` even if the stored `publicationStatus` is still `'scheduled'` - NOTE: This is a UX hint only — the backend remains the source of truth and applies the same materialisation server-side. +@e2e exclude the server already materialises a due scheduled dashboard before the browser reads it, so the client-side hint cannot be told apart in a browser; pinned by src/stores/__tests__/dashboardActions.golden.spec.js (effectivePublicationStatus cases) #### Scenario: Publish / unpublish / schedule actions patch local state @@ -1297,8 +1329,6 @@ endpoints). ### Requirement: Dashboards with a parent nest in the switcher (REQ-TREEUI-001) -@e2e exclude nesting needs seeded parent and child dashboards on a live instance; the switcher is asserted in src/components/Workspace/__tests__/DashboardSwitcherSidebar.tree.spec.js, the breadcrumb in src/components/Workspace/__tests__/DashboardBreadcrumb.spec.js and tests/Unit/Controller/DashboardApiControllerBreadcrumbsTest.php, the form and delete flow in src/views/__tests__/ViewsTree.spec.js - When at least one visible dashboard has a parent, the switcher MUST show it nested under that parent with an expand control. When none has a parent it MUST render as it does today. #### Scenario: Nested onboarding pages @@ -1315,8 +1345,6 @@ When at least one visible dashboard has a parent, the switcher MUST show it nest ### Requirement: A child page shows where it sits (REQ-TREEUI-002) -@e2e exclude nesting needs seeded parent and child dashboards on a live instance; the switcher is asserted in src/components/Workspace/__tests__/DashboardSwitcherSidebar.tree.spec.js, the breadcrumb in src/components/Workspace/__tests__/DashboardBreadcrumb.spec.js and tests/Unit/Controller/DashboardApiControllerBreadcrumbsTest.php, the form and delete flow in src/views/__tests__/ViewsTree.spec.js - A dashboard with a parent MUST show a breadcrumb of its ancestors above the grid, taken from the server, and MUST NOT show the name of an ancestor the viewer may not see. #### Scenario: Breadcrumb @@ -1327,10 +1355,16 @@ A dashboard with a parent MUST show a breadcrumb of its ancestors above the grid ### Requirement: A parent is chosen in the form and validated (REQ-TREEUI-003) -@e2e exclude nesting needs seeded parent and child dashboards on a live instance; the switcher is asserted in src/components/Workspace/__tests__/DashboardSwitcherSidebar.tree.spec.js, the breadcrumb in src/components/Workspace/__tests__/DashboardBreadcrumb.spec.js and tests/Unit/Controller/DashboardApiControllerBreadcrumbsTest.php, the form and delete flow in src/views/__tests__/ViewsTree.spec.js - The create and rename dialogs MUST offer a "Parent dashboard" select and a slug field, and MUST show the service message when the parent would create a cycle or the slug is already used among siblings. +Under the select the Details tab MUST show the hint drawn on board LpDashboardInstellingen: "This builds a tree of dashboards under Dashboards in the More menu" (nl "Zo ontstaat een boom van dashboards onder Dashboards in het menu Meer"). LaunchPad has no side bar (runtime-shell REQ-SHELL-009), so no copy may say the tree appears in one. + +#### Scenario: The hint names where the tree appears + +- **GIVEN** Sanne opens the settings of "Onboarding" +- **WHEN** the Details tab shows the "Parent dashboard" select +- **THEN** the hint under it says the tree appears under Dashboards in the More menu, and nothing on the tab mentions a side bar + #### Scenario: Cycle refused - **GIVEN** "HR" is the parent of "Onboarding" @@ -1339,8 +1373,6 @@ The create and rename dialogs MUST offer a "Parent dashboard" select and a slug ### Requirement: A person can hide a widget for themselves (REQ-PERSUI-001) -@e2e exclude two people on one shared dashboard need a live instance; the page behaviour is asserted in src/views/__tests__/ViewsPersonalHide.spec.js, the menu in src/components/__tests__/WidgetWrapper.hide.spec.js, the list in src/components/Workspace/__tests__/HiddenWidgetsControl.spec.js, the store in src/stores/__tests__/personalLayer.spec.js - In view mode every widget that is not compulsory MUST offer "Hide for me" in its menu. Hiding MUST save the personal layer and reload the dashboard, and MUST NOT change what any other person sees. #### Scenario: Hide one widget @@ -1354,11 +1386,10 @@ In view mode every widget that is not compulsory MUST offer "Hide for me" in its - **GIVEN** the administrator marked the "Safety notice" widget compulsory - **WHEN** Pieter opens its menu - **THEN** no "Hide for me" item is offered +@e2e exclude no endpoint marks a placement on a shared dashboard compulsory: isCompulsory is carried only by admin-template import (lib/Service/PlacementPayloadHydrator.php:105) and role layout defaults; the menu is pinned by src/components/__tests__/WidgetWrapper.hide.spec.js and the server refusal by tests/Unit/Controller/PersonalLayerApiControllerAccessTest.php ### Requirement: A person can bring hidden widgets back (REQ-PERSUI-002) -@e2e exclude two people on one shared dashboard need a live instance; the page behaviour is asserted in src/views/__tests__/ViewsPersonalHide.spec.js, the menu in src/components/__tests__/WidgetWrapper.hide.spec.js, the list in src/components/Workspace/__tests__/HiddenWidgetsControl.spec.js, the store in src/stores/__tests__/personalLayer.spec.js - A "Hidden (n)" control MUST list the widgets the person hid, each with "Show again", and MUST be absent when nothing is hidden. "Reset my view" MUST delete the whole layer after confirmation. #### Scenario: Show one again @@ -1375,25 +1406,27 @@ A "Hidden (n)" control MUST list the widgets the person hid, each with "Show aga ### Requirement: A manager can publish, unpublish and schedule a dashboard (REQ-SCHEDUI-001) -@e2e exclude go-live and take-down need real time to pass on a live instance; asserted in src/views/__tests__/ViewsSchedule.spec.js, src/dialogs/__tests__/ScheduleDashboardDialog.spec.js, tests/Unit/Service/DashboardServicePublicationTest.php and tests/Unit/Controller/DashboardApiControllerScheduleTest.php - -A person who may edit a dashboard MUST find "Publish", "Unpublish" and "Schedule..." in its menu. "Schedule..." MUST accept a go-live time, a take-down time or both, and MUST show the server's message when a time is in the past. +The owner of a dashboard, or an administrator, MUST find publication in the dashboard settings ("Dashboard configuration", board LpDashboardInstellingen), on their own "Publication" tab ("Publicatie"), and nowhere else: the "Meer" menu and the dashboard row menu MUST NOT offer "Publish", "Unpublish" or "Schedule" (Ruben, 22 Nov 2026), and the Sharing tab (board LpDelen) MUST NOT carry a scheduling block ("Live vanaf", "Offline na") of its own. The tab MUST show the status (Published, Draft or Scheduled) with the one action that fits it, "Publish" or "Unpublish", and a publication schedule that accepts a go-live time, a take-down time or both. It MUST show the server's message in the tab when a time is in the past. Because an administrator keeps the right on every dashboard, the "Meer" menu MUST offer "Settings" to an administrator on a dashboard they do not own; their settings show Details and Publication, without the owner's Languages, Look and Sharing tabs. #### Scenario: Schedule go-live - **GIVEN** Sanne manages the dashboard "Open day" -- **WHEN** she schedules it to go live tomorrow at 09:00 -- **THEN** the header reads "Goes live on" with that date, and colleagues do not see the dashboard until then +- **WHEN** she opens Settings, tab "Publication", and schedules it to go live tomorrow at 09:00 +- **THEN** the tab reads "Scheduled", the header reads "Goes live on" with that date, and colleagues do not see the dashboard until then #### Scenario: Past time refused -- **GIVEN** Sanne opens "Schedule..." +- **GIVEN** Sanne opens the "Publication" tab of the settings - **WHEN** she enters a go-live time in the past and saves -- **THEN** the dialog shows the refusal and nothing changes +- **THEN** the tab shows the refusal and nothing changes -### Requirement: A dashboard can come down at a set time (REQ-SCHEDUI-002) +#### Scenario: Publish and unpublish from the settings + +- **GIVEN** Sanne's dashboard "Open day" is a draft +- **WHEN** she opens the "Publication" tab and chooses "Publish", then "Unpublish" +- **THEN** the status reads "Published" and then "Draft", and the "Meer" menu offers neither action -@e2e exclude go-live and take-down need real time to pass on a live instance; asserted in src/views/__tests__/ViewsSchedule.spec.js, src/dialogs/__tests__/ScheduleDashboardDialog.spec.js, tests/Unit/Service/DashboardServicePublicationTest.php and tests/Unit/Controller/DashboardApiControllerScheduleTest.php +### Requirement: A dashboard can come down at a set time (REQ-SCHEDUI-002) A dashboard MAY carry `unpublishAt`. Once that time has passed, the dashboard MUST be treated as unpublished when read, and `unpublishAt` MUST NOT be earlier than `publishAt`. @@ -1403,6 +1436,232 @@ A dashboard MAY carry `unpublishAt`. Once that time has passed, the dashboard MU - **WHEN** a colleague lists dashboards - **THEN** "Open day" is not among the published dashboards +### Requirement: REQ-DASH-014 Group-shared dashboard CRUD is admin-only and declared as such + +The group-shared dashboard endpoints `updateGroup`, `deleteGroup` and `setGroupDefault` MUST be reachable only by Nextcloud global administrators, AND this restriction MUST be declared via the +`#[AuthorizedAdminSetting]` PHP attribute rather than via an in-body +`isAdmin()` check layered on a `#[NoAdminRequired]` attribute. The +attribute-level declaration is enforced by Nextcloud's own middleware +before the controller method body runs, and is the mechanically +verifiable form per ADR-005's auth-attribute contract. + +`createGroup` is the exception (Ruben, 21 Nov 2026): an Editor may create a group dashboard for a group they belong to, so it carries `#[NoAdminRequired]` and checks `GroupDashboardCreation::allows()` before it reads the body. + +#### Scenario: Non-admin cannot create a group-shared dashboard + +- **GIVEN** an authenticated user "bob" who is not an administrator and has + no LaunchPad Admin or Editor role +- **WHEN** bob sends `POST /api/dashboards/group/{groupId}` +- **THEN** the controller MUST reject the request with HTTP 403 before it + reads the body or creates anything (REQ-DASH-014) +- **AND** no dashboard MUST be created + +#### Scenario: Non-admin cannot update, delete, or set-default a group-shared dashboard + +- **GIVEN** an authenticated non-admin user "bob" +- **WHEN** bob sends `PUT /api/dashboards/group/{groupId}/{uuid}`, + `DELETE /api/dashboards/group/{groupId}/{uuid}`, or + `POST /api/dashboards/group/{groupId}/default` +- **THEN** each request MUST be rejected with HTTP 403 by the framework + attribute check +- **AND** no mutation MUST occur + +#### Scenario: Admin can perform all four group-shared operations + +- **GIVEN** an authenticated Nextcloud global admin +- **WHEN** the admin calls `createGroup`, `updateGroup`, `deleteGroup`, or + `setGroupDefault` +- **THEN** each call MUST succeed exactly as it did before this change +- **AND** the response payloads MUST be unchanged + +#### Scenario: Controller method carries the correct attribute + +- **GIVEN** `lib/Controller/DashboardApiController.php` +- **WHEN** `createGroup()`, `updateGroup()`, `deleteGroup()`, and + `setGroupDefault()` are inspected +- **THEN** each MUST carry `#[AuthorizedAdminSetting(Application::APP_ID)]` +- **AND** none MUST carry `#[NoAdminRequired]` +@e2e exclude a source-attribute check, not behaviour; pinned by tests/Unit/Controller/DashboardApiControllerGroupSharedTest.php::testGroupEndpointsCarryAuthorizedAdminSettingAttribute + +### Requirement: Each dashboard can have its own look (REQ-THM-001) + +A person with full permission on a dashboard MUST be able to set an accent colour, a background colour and a background image from LaunchPad's uploaded resources, in the block "Own look" ("Eigen uitstraling") of the dashboard settings' Details tab (board LpDashboardInstellingen); there is no separate Look tab. The look MUST apply to that dashboard's region only; the Nextcloud header, the organisation navigation and other dashboards MUST keep the instance theme. A dashboard without a look MUST follow the theme. + +#### Scenario: A green team dashboard + +- **GIVEN** Ella has full permission on "Team Groen" +- **WHEN** she opens the dashboard settings, tab Details, and in Own look sets the accent to `#1f5c3a` and a background image, and saves +- **THEN** "Team Groen" shows the green accent and the image +- **AND** her dashboard "Mijn werkplek" and the Nextcloud header look as before + +### Requirement: A look must stay readable (REQ-THM-002) + +Text on a dashboard with its own background MUST use black or white, whichever contrasts more with the background. The server MUST refuse an accent whose contrast against the background is below 3:1 and return the measured ratio. The editor MUST show the same check while choosing. + +#### Scenario: Pale accent on white refused + +- **GIVEN** "Team Groen" has no background colour of its own and the instance background is white +- **WHEN** Ella sets the accent to `#f5f5dc` and saves +- **THEN** saving fails with "Buttons in this colour are hard to see (contrast 1.1 to 1, needs 3 to 1)" + +#### Scenario: Dark background gets light text + +- **GIVEN** Ella sets the background colour of "Team Groen" to `#12301f` +- **WHEN** Pieter opens "Team Groen" +- **THEN** text drawn on the dashboard background is white + +### Requirement: Administrators add custom CSS, cleaned and scoped (REQ-THM-003) + +Administrators MUST be able to add CSS for all of LaunchPad and for one dashboard. The server MUST store only a cleaned version: no `@import`, no addresses to other sites, no `expression(`, `behavior`, `-moz-binding` or `javascript:`, every selector scoped to LaunchPad (or to that dashboard), at most 20 KB. The admin MUST see what was dropped. Non-administrators MUST NOT be able to set custom CSS. + +#### Scenario: Import dropped + +- **GIVEN** Noor is an administrator +- **WHEN** she saves global CSS `@import url(https://evil.example/x.css); .tile-widget__title { font-weight: 700; }` +- **THEN** the stored CSS keeps only the scoped `.tile-widget__title` rule +- **AND** the admin section says "Removed: @import" + +#### Scenario: Non-administrator refused + +- **GIVEN** Ella has full permission on "Team Groen" but is not an administrator +- **WHEN** a client sends her update of "Team Groen" with a `customCss` value +- **THEN** the response is 403 and no CSS is stored + +#### Scenario: CSS cannot reach outside LaunchPad + +- **GIVEN** Noor saves the CSS `body { display: none; }` for the dashboard "Team Groen" +- **WHEN** Pieter opens Nextcloud Files +- **THEN** Files looks as always, because the stored rule is scoped to the "Team Groen" dashboard region + +### Requirement: REQ-DASH-038 The edit bar + +While a dashboard is in edit mode, a bar MUST run across the top of the dashboard (board `launchpad/LpBewerken`), as a toolbar named "Edit dashboard". It MUST say which dashboard is being edited and that changes are saved straight away, and it MUST hold, in this order: + +- **Columns** 6, 8 and 12, a group of toggle buttons (`aria-pressed`) with the current count pressed. Choosing one gives the dashboard that many grid columns and stores it, through the personal endpoint (`PUT /api/dashboard/{id}` with `gridColumns`) or the group endpoint for a group dashboard. The server MUST refuse any other count with 400. A refused save MUST put the old count back and say so. +- **Add widget**, which opens the widget picker. +- **Dashboard settings** (`aria-haspopup="dialog"`), which opens the dashboard settings window. It is offered to the owner and to whoever may manage the publication, the gate of the former "Settings" item in More. +- **Done**, which leaves edit mode. + +While the bar is shown, the page's More menu docks at its end, so the floating menu never covers Done. + +#### Scenario: Edit mode shows the edit bar +- GIVEN the owner of a dashboard +- WHEN they choose More, then Edit +- THEN the edit bar MUST show the dashboard's name, Columns 6, 8 and 12, Add widget, Dashboard settings and Done + +@e2e openspec/specs/dashboards/spec.md#req-dash-038 + +#### Scenario: Columns change the grid and are kept +- GIVEN the owner in edit mode on a dashboard with 12 columns +- WHEN they choose 8 +- THEN the grid MUST have 8 columns, 8 MUST be pressed, and the dashboard MUST store 8 + +@e2e openspec/specs/dashboards/spec.md#req-dash-038 + +#### Scenario: Done leaves edit mode +- GIVEN the owner in edit mode +- WHEN they choose Done +- THEN the edit bar MUST go and the dashboard MUST be in view mode + +@e2e openspec/specs/dashboards/spec.md#req-dash-038 + +### Requirement: REQ-DASH-039 Versions are a tab of the dashboard settings + +The saved versions of a dashboard (dashboard-versioning REQ-VERSUI-001..003) MUST be the last tab of the dashboard settings window, after Details, Languages, Sharing, Publication and Exports (board `launchpad/LpVersies`). The tab is offered to the owner and to an administrator, the same people who may manage the publication, and it says so when the dashboard is stored in a way that keeps no versions. There is no separate version history window and no Versions item in More. + +#### Scenario: The Versions tab lists the saved versions +- GIVEN the owner in edit mode +- WHEN they open Dashboard settings and choose Versions +- THEN the tab MUST list the dashboard's versions newest first, with "Save this version now" and a restore per version + +@e2e openspec/specs/dashboards/spec.md#req-dash-039 + +### Requirement: The Details tab shows the instance theme, read-only (REQ-THM-004) + +The Details tab SHALL show, under "Display" ("Weergave"), the field "Theme" ("Thema") with the name of the theme the +instance uses (Nextcloud's theming name, or the active thematiq theme when thematiq sets one), read-only, with the line +that the theme is the same for every dashboard and that this dashboard's own colours are set under Own look. The tab +SHALL NOT offer a choice of theme and SHALL NOT offer a layout preset ("Indeling van dit dashboard"); the dashboard's +layout is its column choice in the edit bar (REQ-DASH-038) and where its widgets stand. + +#### Scenario: The theme of Zuiddrecht + +- **GIVEN** the instance uses the theme "Huisstijl Zuiddrecht" +- **WHEN** Pieter opens the Details tab of a dashboard he owns +- **THEN** Thema reads "Huisstijl Zuiddrecht" and cannot be changed +- **AND** the tab has no layout field + +#### Scenario: The own look stays a choice + +- **GIVEN** the same Details tab +- **WHEN** Pieter sets an accent colour under Own look and saves +- **THEN** the dashboard takes the accent, and Thema still reads "Huisstijl Zuiddrecht" + +### Requirement: The header says what dashboard this is and what the reader may do (REQ-DPD-001) + +Under the dashboard title the header SHALL show one line: the kind of dashboard with its icon ("Persoonlijk +dashboard", "Groepsdashboard van {group}", "Gedeeld door {person}"), what the reader may do on it ("alleen bekijken", +"u mag widgets toevoegen", or nothing extra with full rights), "opent als eerste" when it is the reader's default, and +when it last changed ("bijgewerkt 10:45" today, the weekday within the last week, the date before that), separated by +" · ". + +#### Scenario: A view-only group dashboard + +- **GIVEN** Pieter has view-only rights on the group dashboard Managementinformatie of Bedrijfsvoering, last changed today at 10:45 +- **WHEN** he opens it +- **THEN** the line under the title reads "Groepsdashboard van Bedrijfsvoering · alleen bekijken · bijgewerkt 10:45" + +#### Scenario: Pieter's own default dashboard + +- **GIVEN** Mijn werkplek is Pieter's personal default dashboard +- **WHEN** he opens it +- **THEN** the line reads "Persoonlijk dashboard · opent als eerste" followed by when it last changed + +### Requirement: A dashboard can have a period that its figures follow (REQ-DPD-002) + +A widget whose data source is a register query MAY name the date field of its records in `content.source.periodField`. +When at least one widget on a dashboard names one, the header SHALL show a period choice: This month, Quarter, Year +(nl Deze maand, Kwartaal, Jaar), This month first. The chosen period SHALL be added to the query of every widget that +names a period field, as that field between the period's start and now, and SHALL be kept in the address +(`?period=month|quarter|year`) so a copied link opens with the same period. A widget without a period field SHALL +ignore the period, and its card SHALL NOT claim to follow it. The period SHALL work alongside the cross-widget filter +(cross-widget-filter) and SHALL be read-only: choosing it never changes the stored dashboard. + +#### Scenario: Pieter looks at the quarter + +- **GIVEN** Managementinformatie with "Zaken per status" whose source names `periodField: "startDate"`, and a Power BI embed +- **WHEN** Pieter chooses Kwartaal +- **THEN** "Zaken per status" counts only cases started this quarter +- **AND** the address carries `period=quarter` +- **AND** the Power BI embed is unchanged + +#### Scenario: A dashboard without dated sources + +- **GIVEN** a dashboard on which no widget names a period field +- **WHEN** it renders +- **THEN** the header shows no period choice + +### Requirement: A reader can download the dashboard (REQ-DPD-003) + +The header SHALL offer "Download" (nl "Downloaden") to everyone who can open the dashboard, also with view-only +rights. It SHALL give the reader the dashboard as a PDF, rendered as the reader sees it now, with the period and the +cross-widget filter applied and the reader's own visibility rules respected, rendered in the reader's own browser +(print styles and the browser's print dialog; decision 24 Nov 2026), not on the server. Nothing SHALL be stored or sent. A widget the renderer cannot draw (an embedded page) SHALL be named in the +PDF with a line that it is not included. The kiosk view and the public view SHALL NOT offer it. + +#### Scenario: Pieter downloads the quarter + +- **GIVEN** Pieter has view-only rights on Managementinformatie, with Kwartaal chosen +- **WHEN** he chooses Downloaden +- **THEN** his browser saves a PDF of Managementinformatie with the quarter's figures +- **AND** no scheduled export or run is created + +#### Scenario: The embedded report + +- **GIVEN** the dashboard holds the Power BI embed "Rapport Sociaal domein" +- **WHEN** Pieter downloads it +- **THEN** the PDF names "Rapport Sociaal domein" with a line that embedded pages are not included + ## Non-Functional Requirements - **Performance**: GET /api/dashboards MUST return within 500ms for users with up to 50 dashboards. GET /api/dashboard MUST return within 1 second including template distribution if needed. @@ -1439,7 +1698,7 @@ A dashboard MAY carry `unpublishAt`. Once that time has passed, the dashboard MU - REQ-DASH-033 (Unpublish action): `POST /api/dashboards/{uuid}/unpublish` → `DashboardApiController::unpublish()` → `DashboardService::unpublish()`. Preserves `publishedAt` for audit; clears `publishAt`. - REQ-DASH-034 (Schedule action + lazy materialisation): `POST /api/dashboards/{uuid}/schedule` → `DashboardApiController::schedule()` → `DashboardService::schedule()`. `parseFuturePublishAt()` enforces strictly-future timestamps and raises `InvalidArgumentException` mapped to HTTP 400 (`publishAt must be a future timestamp`). `DashboardService::filterByPublicationState()` materialises scheduled rows whose `publishAt <= now()` as published at read time without a DB write. `DashboardService::materialiseScheduledDashboards()` (+ `DashboardMapper::findDueScheduled()`) provides the optional eager path. - REQ-DASH-035 (Migration backfill): `DashboardTableBuilder::addPublicationColumns()` declares `publication_status` with `DEFAULT 'published'` so pre-existing rows are backfilled implicitly via the column default; `DashboardFactory::create()` overrides the default to `'draft'` for every new dashboard. -- REQ-DASH-036 (Draft visibility restrictions): `DashboardService::getVisibleToUser()` runs every mapper result through `filterByPublicationState()` which hides `draft` and future-`scheduled` rows from non-owner non-admin viewers; admins receive everything via `safeIsAdmin()`. +- REQ-DASH-036 (Draft visibility restrictions): `DashboardService::getVisibleToUser()` runs every mapper result and every share-reached row through `filterByPublicationState()` which hides `draft` and future-`scheduled` rows from non-owner non-admin viewers; admins receive everything via `safeIsAdmin()`. - REQ-DASH-037 (Frontend store): `src/stores/dashboard.js` exports `STATUS_DRAFT`/`STATUS_PUBLISHED`/`STATUS_SCHEDULED` constants and `publishDashboard` / `unpublishDashboard` / `scheduleDashboard` / `effectivePublicationStatus` / `applyPublicationPatch` actions backed by `api.publishDashboard` / `api.unpublishDashboard` / `api.scheduleDashboard` HTTP helpers in `src/services/api.js`. - REQ-DASH-038..044 (Per-language dashboard content variants): the full requirement set lives in the sibling capability `dashboard-language-content` (`openspec/specs/dashboard-language-content/spec.md`). `DashboardService::createDashboard()` calls `DashboardTranslationService::seedPrimaryFor()` after insert; `DashboardService::deleteDashboard()` cascades via `DashboardTranslationService::deleteAllForDashboard()` for both single-row and subtree paths so translation rows never outlive their parent dashboard. @@ -1463,12 +1722,14 @@ The system MUST centralise dashboard create + update permission checks in `Dashb - GIVEN a user with `canEditDashboardMetadata = true` but `canEditDashboard = false` on a dashboard - WHEN `checkUpdatePermissions(userId, dashboardId, placements: null)` is called - THEN it returns `null` (allowed) and the caller proceeds with the update +@e2e exclude names a private controller check and its arguments (there is no DashboardRequestValidator class; the check is DashboardApiController::mayUpdate), and over HTTP a non-owner update is refused by DashboardService::updateDashboard anyway; pinned by tests/Unit/Controller/DashboardApiControllerActionsGoldenTest.php::testUpdateGuard and DashboardApiControllerUpdateAccessTest.php::testMetadataUpdateAsksTheMetadataPermission #### Scenario: Layout update blocked for users without full edit permission - GIVEN a user with `canEditDashboardMetadata = true` but `canEditDashboard = false` - WHEN `checkUpdatePermissions(userId, dashboardId, placements: [...])` is called with a non-null placements array - THEN it returns a `JSONResponse` with status 403 and body `{ "error": "Access denied" }` +@e2e exclude names a private controller check and its arguments (DashboardApiController::mayUpdate); pinned by tests/Unit/Controller/DashboardApiControllerActionsGoldenTest.php::testUpdateGuard and DashboardApiControllerUpdateAccessTest.php::testPlacementUpdateAsksTheEditPermission #### Scenario: Multiple-dashboard creation blocked when admin setting is off @@ -1501,56 +1762,62 @@ The system MUST accept dashboard creation parameters from EITHER a structured JS ### REQ-DASH-040: Dashboard response envelope shape and status codes -The system MUST return every dashboard API response as a `JSONResponse` built through `ResponseHelper`. The envelope contract is: +The system MUST return every dashboard API response as a `JSONResponse` built through an injected `ResponseHelper` instance (`$this->responseHelper`), which the DI container constructs with its own `LoggerInterface`. Controllers MUST NOT call `ResponseHelper` statically. The envelope contract is: - Success responses use `{...payload...}` with status 200 (default) or a caller-specified 2xx code - Unauthorized responses use `{ "error": "Not logged in" }` with status 401 - Forbidden responses use `{ "error": <message> }` with status 403 (default message: `"Access denied"`) - Error responses use `{ "error": <generic-message> }` with status 400 (or caller-specified) -- List responses MUST be serialized via `ResponseHelper::serializeList()` which calls `jsonSerialize()` on each element +- List responses MUST be serialized via `$this->responseHelper->serializeList()` which calls `jsonSerialize()` on each element. `serializeList()` is an instance method like the others, so every controller uses one call shape. #### Scenario: Unauthorized helper returns canonical 401 - GIVEN no authenticated user -- WHEN a controller calls `ResponseHelper::unauthorized()` +- WHEN a controller calls `$this->responseHelper->unauthorized()` - THEN the response body is `{ "error": "Not logged in" }` with HTTP status 401 +@e2e exclude a ResponseHelper call with chosen arguments; an anonymous request is refused by Nextcloud before any LaunchPad controller runs, so no request reaches this helper; pinned by tests/Unit/Controller/ResponseHelperTest.php::testUnauthorizedReturnsCanonical401 #### Scenario: Forbidden helper accepts custom message -- WHEN a controller calls `ResponseHelper::forbidden('Dashboard creation not allowed')` +- WHEN a controller calls `$this->responseHelper->forbidden('Dashboard creation not allowed')` - THEN the response body is `{ "error": "Dashboard creation not allowed" }` with HTTP status 403 +@e2e exclude a ResponseHelper call with chosen arguments; pinned by tests/Unit/Controller/ResponseHelperTest.php::testForbiddenAcceptsCustomMessage #### Scenario: Success helper accepts custom status -- WHEN a controller calls `ResponseHelper::success(['id' => 1], 201)` +- WHEN a controller calls `$this->responseHelper->success(['id' => 1], 201)` - THEN the response body is `{ "id": 1 }` with HTTP status 201 +@e2e exclude a ResponseHelper call with chosen arguments; pinned by tests/Unit/Controller/ResponseHelperTest.php::testSuccessAcceptsCustomStatus #### Scenario: Serialize list of dashboards - GIVEN an array of three `Dashboard` entities (each implementing `JsonSerializable`) -- WHEN a controller calls `ResponseHelper::serializeList($dashboards)` +- WHEN a controller calls `$this->responseHelper->serializeList($dashboards)` - THEN it returns an array of three associative arrays, each the result of calling `jsonSerialize()` on the corresponding entity +@e2e exclude a ResponseHelper call on in-memory entities; pinned by tests/Unit/Controller/ResponseHelperTest.php::testSerializeListCallsJsonSerializeOnEachEntity ### REQ-DASH-041: Exception-to-error response without message leak -The system MUST translate caught exceptions into JSON error responses via `ResponseHelper::error()` without ever exposing the raw exception message to the client (ADR-005). Callers SHOULD pass a `LoggerInterface` so the real exception (message + stack) is recorded at ERROR level on the server; the client always receives a generic `$message` (default `"Operation failed"`) and the caller-specified HTTP status (default 400). +The system MUST translate caught exceptions into JSON error responses via `$this->responseHelper->error()` without ever exposing the raw exception message to the client (ADR-005). The helper holds a non-optional `LoggerInterface` injected by the DI container, so every caught exception (message + stack) is recorded at ERROR level on the server; callers do not pass a logger. The client always receives a generic `$message` (default `"Operation failed"`) and the caller-specified HTTP status (default 400). #### Scenario: Caught exception is logged and a generic error is returned - GIVEN a controller catches `\RuntimeException('Database constraint X violated')` -- AND the controller has an injected `LoggerInterface` -- WHEN the controller calls `ResponseHelper::error($e, 500, $logger, 'Could not save dashboard')` +- AND the controller has an injected `ResponseHelper` +- WHEN the controller calls `$this->responseHelper->error($e, 500, 'Could not save dashboard')` - THEN the logger records the raw `'Database constraint X violated'` message at ERROR level with the exception in the context - AND the response body is `{ "error": "Could not save dashboard" }` with HTTP status 500 +@e2e exclude asserts what the server logger records for a thrown exception the test chooses; pinned by tests/Unit/Controller/ResponseHelperTest.php::testErrorLogsTheExceptionAndReturnsTheGenericMessage -#### Scenario: Logger omitted — exception is silently swallowed +#### Scenario: Default error is logged and stays generic - GIVEN a controller catches `\RuntimeException('secret')` -- WHEN the controller calls `ResponseHelper::error($e, 400, null, 'Operation failed')` +- WHEN the controller calls `$this->responseHelper->error($e)` - THEN the response body is `{ "error": "Operation failed" }` with HTTP status 400 -- AND no log entry is written (observed behaviour — see Notes) +- AND the logger records `'secret'` at ERROR level, so no caught exception goes unlogged +@e2e exclude asserts what the server logger records for a thrown exception the test chooses; pinned by tests/Unit/Controller/ResponseHelperTest.php::testDefaultErrorIsLoggedAndStaysGeneric #### Notes (REQ-DASH-038..041) -- The "logger optional" path in `ResponseHelper::error()` is a latent risk: a caller that forgets to wire the logger gets silently dropped exceptions with no audit trail. Future-tightening TODO: make `LoggerInterface` non-nullable in a follow-up change once every call site is converted. +- `ResponseHelper::error()` no longer has a "logger optional" path: the logger is a constructor dependency, so a caller cannot forget it (change `responsehelper-instance-api`). - `serializeList()` assumes every element implements `jsonSerialize()` — passing plain arrays results in a fatal `Error: Call to a member function jsonSerialize() on array`. This is a precondition, not a defensive check. diff --git a/openspec/specs/default-widget-bundle/screens.md b/openspec/specs/default-widget-bundle/screens.md new file mode 100644 index 000000000..c0e4e5f2c --- /dev/null +++ b/openspec/specs/default-widget-bundle/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpEersteKeer https://identity.conduction.nl/screens/board?id=launchpad/LpEersteKeer diff --git a/openspec/specs/default-widget-bundle/spec.md b/openspec/specs/default-widget-bundle/spec.md index b2b27b755..1026b82d7 100644 --- a/openspec/specs/default-widget-bundle/spec.md +++ b/openspec/specs/default-widget-bundle/spec.md @@ -54,7 +54,6 @@ MUST link to `https://nextcloud.com` with the `icon-nextcloud` CSS class (`tileIconType: 'class'`). #### Scenario: New dashboard ships four seeded placements -@e2e exclude seed-bundle insertion is validated via PHPUnit/Newman create-response contract, not browser - **GIVEN** a user creates a new dashboard via `POST /api/dashboard` - **WHEN** the create completes - **THEN** the response MUST contain exactly four widget placements (Conduction, Sendent, Nextcloud tiles + files widget) at the grid coordinates listed above @@ -73,7 +72,6 @@ while `'preset'` keeps the placements on the registry-backed `TileWidget` renderer (REQ-WDG-022). #### Scenario: Preset tiles serialize flat tile columns -@e2e exclude jsonSerialize column emission is a PHPUnit serialization assertion, not browser - **GIVEN** a seeded tile placement with `tileType='preset'` - **WHEN** `WidgetPlacement::jsonSerialize()` runs - **THEN** the flat `tile*` columns (title / icon / link) MUST be emitted @@ -88,7 +86,7 @@ delegate to `seedDefaultWidgets()` so first-login users get the same four-widget bundle when no admin template applies. #### Scenario: Bootstrap does not seed the default bundle -@e2e exclude bootstrap seed-flag behaviour is a PHPUnit service assertion, not browser +@e2e exclude the seedDefaults flag is an internal call argument a browser cannot see; pinned by tests/Unit/Service/DashboardServiceCreateDefaultsTest.php (testCreateWithoutSeedFlagInsertsNoPlacements, testEnsureDefaultDashboardProvisionsAndSeedsWhenAbsent) and DashboardServiceCreationGoldenTest::testProvisionedDashboardPlacements - **GIVEN** the first-login bootstrap runs `tryCreateFromTemplate()` - **WHEN** no admin template applies - **THEN** `createDashboard()` MUST be called with `seedDefaults: false` and the role-default seed MUST apply instead @@ -98,7 +96,7 @@ four-widget bundle when no admin template applies. WHEN an admin template applies (the `DashboardResolver::handleTemplateResult()` path) the resolver MUST seed the dashboard with the template's declared widget set, NOT the four-widget bundle. Template authors own the layout; the default bundle is for users who didn't get an admin template. #### Scenario: Admin template overrides the default bundle -@e2e exclude template seed selection is a PHPUnit resolver assertion, not browser +@e2e exclude no e2e yet: needs an admin template applied to a group the account is in; pinned by tests/Unit/Service/DashboardResolverGoldenTest.php::testTemplateRung and DashboardServiceCreationGoldenTest::testProvisionWithATemplateHandsItToTheResolver - **GIVEN** an admin template applies during dashboard resolution - **WHEN** `handleTemplateResult()` seeds the dashboard - **THEN** the dashboard MUST receive the template's declared widget set, NOT the four-widget default bundle @@ -122,7 +120,6 @@ backend that omits the `placements` key fall back to `[]` gracefully. #### Scenario: Create response includes placements envelope -@e2e exclude create-response envelope shape is a Newman/PHPUnit HTTP-contract assertion, not browser - **GIVEN** a user creates a new dashboard - **WHEN** `POST /api/dashboard` returns - **THEN** the response MUST include both `dashboard` and `placements` keys, matching the `GET /api/dashboard` envelope shape @@ -143,7 +140,6 @@ This eliminates the flash where the empty-state rendered briefly during the initial `loadDashboards()` call. #### Scenario: Loading shim shown during initial fetch -@e2e exclude transient loading-state shim — not reliably observable in headless CI; covered by Vitest component test - **GIVEN** the workspace is loading and `activeDashboard` is null - **WHEN** `Views.vue` renders while `loading` is true - **THEN** an `NcLoadingIcon` shim MUST be shown instead of the "No dashboard yet" empty-state diff --git a/openspec/specs/demo-data-showcases/screens.md b/openspec/specs/demo-data-showcases/screens.md new file mode 100644 index 000000000..49402221c --- /dev/null +++ b/openspec/specs/demo-data-showcases/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpInstellen https://identity.conduction.nl/screens/board?id=launchpad/LpInstellen +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement diff --git a/openspec/specs/demo-data-showcases/spec.md b/openspec/specs/demo-data-showcases/spec.md index da67b713b..0a66b6ca7 100644 --- a/openspec/specs/demo-data-showcases/spec.md +++ b/openspec/specs/demo-data-showcases/spec.md @@ -117,7 +117,6 @@ The system maintains a registry of installed showcases by querying existing dash ## Requirements - ### Requirement: REQ-DEMO-001 Bundled showcase ZIP archives The system MUST ship a showcase ZIP archive per bundled id under @@ -133,9 +132,7 @@ tree. Each `manifest.json` MUST contain: - `showcaseDescription`: one sentence saying what the dashboard shows - `showcaseLanguage`: locale code of the dashboard's own copy -Each `dashboards/{uuid}.json` MUST declare `type: "group_shared"`, a null `userId`, -`permissionLevel: "view_only"` and a `showcase-{id}` slug, so an installed showcase -is a read-only group dashboard rather than someone's personal one. +Each `dashboards/{uuid}.json` MUST declare `type: "group_shared"`, a null `userId` and a `showcase-{id}` slug, so an installed showcase is a group dashboard rather than someone's personal one. Its `permissionLevel` MUST be `view_only`, except for a showcase that shows a shared intranet colleagues add to, which MAY be `add_only`. **This paragraph previously described an `export.json` plus a `nl/` locale tree, and neither has ever been in any bundled ZIP.** The archives have always been @@ -153,6 +150,8 @@ screenshots stay reusable: - `gemeente-duin`, a municipality - `horizon-labs`, a tech startup - `van-der-berg`, a law firm +- `zuiddrecht-intranet`, the intranet of the demo municipality Zuiddrecht, which every colleague may add widgets to (`add_only`) +- `zuiddrecht-management`, the management information of Zuiddrecht (`view_only`) **Role showcases** answer a different question: what one person's working day looks like on one page. @@ -202,6 +201,16 @@ remain a v2 goal. @e2e exclude The bundled archives are all valid, so a browser run cannot arrange a broken one; a missing archive is pinned by DemoShowcasesServiceTest::testDescribeShowcaseReturnsNullWhenZipMissing, a malformed one by no test yet. +#### Scenario: The Zuiddrecht intranet lets colleagues add widgets +- **GIVEN** an administrator installed the `zuiddrecht-intranet` showcase +- **WHEN** a colleague opens "Intranet Zuiddrecht" +- **THEN** the dashboard is a group dashboard the colleague may add widgets to, and not edit or delete + +#### Scenario: The management information is read only +- **GIVEN** an administrator installed the `zuiddrecht-management` showcase +- **WHEN** a colleague opens "Managementinformatie" +- **THEN** the dashboard shows the counts from the registers and offers no editing + ### Requirement: REQ-DEMO-002 List available showcases endpoint @e2e exclude Endpoint auth and install-state flags are API contracts: 401/403 and the list shape are pinned by AdminDemoShowcasesControllerTest and Newman's GET /api/admin/demo-showcases. The case-handler gallery entry is covered in the browser under REQ-DEMO-001. @@ -551,3 +560,43 @@ Both commands MUST validate admin role (require Nextcloud admin user credentials - **WHEN** the command runs - **THEN** the system MUST output an error "Showcase not found" - **AND** exit with code 1 + +### Requirement: REQ-DEMO-010 Demo seed of the boards + +LaunchPad SHALL ship a demo seed that reproduces the LaunchPad boards: demo users and groups, an app tile catalogue, +announcements, a shared team folder and one dashboard per board, each with a fixed UUID. `occ launchpad:demo:load` +SHALL write it. Users that exist keep their password; dashboards with the seeded UUID are updated and get the seeded +placements and shares again. + +#### Scenario: Running the seed twice + +- **GIVEN** an instance where the seed ran once +- **WHEN** an administrator runs `occ launchpad:demo:load` again +- **THEN** no user, group, catalogue entry or dashboard is added +- **AND** every seeded dashboard has the same widgets, positions and shares as after the first run + +#### Scenario: Pieter opens LaunchPad + +- **GIVEN** the seed ran +- **WHEN** `pieter` opens LaunchPad +- **THEN** his dashboard Vandaag opens first +- **AND** Mijn werkplek, Intranet Zuiddrecht, Team Vergunningen and Managementinformatie are in his dashboard list + +#### Scenario: A first visit + +- **GIVEN** the seed ran with `--retire-showcases` +- **WHEN** `nieuw` opens LaunchPad +- **THEN** the page says "U heeft nog geen dashboard" and offers to start with the starter widgets + +### Requirement: REQ-DEMO-011 Seed widgets wait for their type + +A seed widget whose type is not registered on the instance SHALL be placed as its `fallback` entry when it has one and +that type is registered, and SHALL otherwise be skipped and reported. A seed tile SHALL be an `app-tile` when its app is +enabled and the `app-tile` type is registered, and a launcher tile in the tile's colour otherwise. + +#### Scenario: The wiki widget is not built yet + +- **GIVEN** no `wiki` widget type is registered +- **WHEN** the seed runs +- **THEN** Mijn werkplek has no wiki widget and the command lists `wiki (Wiki)` as skipped +- **AND** after the type ships, the next run places it diff --git a/openspec/specs/divider-widget/screens.md b/openspec/specs/divider-widget/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/divider-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/divider-widget/spec.md b/openspec/specs/divider-widget/spec.md index a4fbb3b53..137ee4765 100644 --- a/openspec/specs/divider-widget/spec.md +++ b/openspec/specs/divider-widget/spec.md @@ -22,6 +22,7 @@ The system MUST register a divider widget with the Nextcloud Dashboard Widget AP - AND the widget MUST NOT fetch any data on discovery — it is fully client-side #### Scenario: Widget registration via IManager +@e2e exclude never built: no `DividerWidgetProvider` exists and nothing calls `IManager::registerWidget` for the divider (`git log --all -S DividerWidgetProvider -- src lib appinfo templates` returns nothing); the divider is a client-side type registered by nc-vue's `registerDashboardWidget('divider', …)`, so an app boot registers nothing to observe. Same verdict as "Widget discovery works via standard widget API" under REQ-DIV-009. Its client-side discovery is cited by tests/e2e/divider-widget-discovery.spec.ts (widget-appears-in-discovery). - GIVEN `OCP\Dashboard\IManager` is available in the Nextcloud container - WHEN the LaunchPad app boots (appinfo/app.php or service provider) - THEN the app MUST register the divider widget by calling `$manager->registerWidget(new DividerWidgetProvider())` @@ -36,7 +37,6 @@ The system MUST register a divider widget with the Nextcloud Dashboard Widget AP ### Requirement: REQ-DIV-002 Configure Divider Style The system MUST store placement-level configuration in the `widgetContent JSON` blob to allow dashboard creators to choose between three divider styles: a horizontal line, whitespace spacer, or heading-break. -@e2e exclude configure divider style tests the form fields inside AddWidgetModal for divider — requires opening modal and selecting divider widget; covered by generic widget-in-picker test #### Scenario: Line style configuration - GIVEN a divider widget is placed on a dashboard @@ -67,7 +67,6 @@ The system MUST store placement-level configuration in the `widgetContent JSON` ### Requirement: REQ-DIV-003 Render Line Divider The system MUST render a horizontal line divider when style is `line`, respecting color, thickness, and line-style configuration. -@e2e exclude render line divider tests CSS border rendering inside a placed divider widget — requires seeded divider placement #### Scenario: Default line render - GIVEN a divider widget with style = `line` and no lineColor specified @@ -96,7 +95,6 @@ The system MUST render a horizontal line divider when style is `line`, respectin ### Requirement: REQ-DIV-004 Render Whitespace Divider The system MUST render a vertical spacer block when style is `whitespace`, respecting the configured size. -@e2e exclude render whitespace divider tests CSS height inside a placed divider — requires seeded placement #### Scenario: Default whitespace render - GIVEN a divider widget with style = `whitespace` and whitespaceSize = `medium` (default) @@ -119,7 +117,6 @@ The system MUST render a vertical spacer block when style is `whitespace`, respe ### Requirement: REQ-DIV-005 Render Heading-Break Divider The system MUST render a centered heading with horizontal lines above and below when style is `heading-break`, respecting the optional lineColor configuration. -@e2e exclude render heading-break divider tests text + border CSS — requires seeded placement #### Scenario: Default heading-break render - GIVEN a divider widget with style = `heading-break`, headingText = "Key Section" @@ -145,7 +142,6 @@ The system MUST render a centered heading with horizontal lines above and below ### Requirement: REQ-DIV-006 Default Widget Sizing The system MUST set sensible sizing defaults for divider widgets in the widget add modal to minimize their footprint on the dashboard. -@e2e exclude default widget sizing tests gridWidth/gridHeight defaults — Vitest scope; observable as widget size in grid but requires placed widget #### Scenario: Divider defaults to gridHeight = 1 - GIVEN the user is adding a new divider widget to a dashboard @@ -168,7 +164,6 @@ The system MUST set sensible sizing defaults for divider widgets in the widget a ### Requirement: REQ-DIV-007 Theme Awareness and Color Inheritance The system MUST automatically use the active Nextcloud theme's border color for divider lines by default and MUST support explicit color overrides. -@e2e exclude theme awareness tests CSS variable inheritance — Vitest/visual-regression scope, not observable from Playwright without design-token setup #### Scenario: Default theme color - GIVEN a divider widget with style = `line` and no lineColor specified @@ -191,7 +186,6 @@ The system MUST automatically use the active Nextcloud theme's border color for ### Requirement: REQ-DIV-008 Print Support and Visibility The system MUST ensure divider widgets render visibly on printed dashboards and MUST NOT hide them in print mode. -@e2e exclude print support tests CSS @media print — not observable in headless Chromium CI #### Scenario: Line divider prints - GIVEN a divider widget with style = `line` on a dashboard @@ -214,7 +208,6 @@ The system MUST ensure divider widgets render visibly on printed dashboards and ### Requirement: REQ-DIV-009 No Backend Endpoints Required The system MUST render dividers entirely client-side and MUST NOT require any backend API endpoints beyond standard widget discovery. -@e2e exclude no backend endpoints — confirmed via spec review; architecture correctness is a code-review gate, not Playwright #### Scenario: Divider is rendered without API calls - GIVEN a divider widget is placed on a dashboard @@ -223,12 +216,14 @@ The system MUST render dividers entirely client-side and MUST NOT require any ba - AND the widget MUST use only the `widgetContent` JSON stored in the placement record to configure its render #### Scenario: Widget discovery works via standard widget API +@e2e exclude never built: the divider is not registered with OCP\Dashboard\IManager, so `IManager::getWidgets()` (lib/Service/WidgetService.php:80, behind GET /api/widgets) never returns it; it is a client-side type registered by nc-vue's `registerDashboardWidget('divider', …)`. `git log --all -S DividerWidgetProvider -- src lib appinfo templates` returns nothing. Client-side discovery is cited by tests/e2e/divider-widget-discovery.spec.ts (widget-appears-in-discovery). - GIVEN the user opens the widget picker - WHEN the system calls `IManager::getWidgets()` - THEN the divider widget metadata MUST be returned - AND no additional backend setup is required #### Scenario: No migration or schema changes required +@e2e exclude an app upgrade runs through occ / the updater, outside a browser, and "no migration was created" is a property of the repository, not of a page; no unit or PHPUnit test pins it (nothing under lib/Migration mentions the divider). - GIVEN the divider-widget capability is implemented - WHEN the LaunchPad app is upgraded - THEN no database migrations MUST be created diff --git a/openspec/specs/effective-default-marker/screens.md b/openspec/specs/effective-default-marker/screens.md new file mode 100644 index 000000000..dd0a09b0b --- /dev/null +++ b/openspec/specs/effective-default-marker/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag diff --git a/openspec/specs/effective-default-marker/spec.md b/openspec/specs/effective-default-marker/spec.md index 8acfa89aa..ebbaabbcd 100644 --- a/openspec/specs/effective-default-marker/spec.md +++ b/openspec/specs/effective-default-marker/spec.md @@ -44,7 +44,6 @@ confusing than helpful. WHEN `DashboardSwitcherSidebar.vue` renders any sidebar section (primary-group / default-group / personal) each row MUST consult `isDefaultDashboard(dashboard)` AND render a `<span class="dashboard-switcher-sidebar__default-marker">` containing a `Star` icon when the result is true. The marker appears between the dashboard's own icon and its label so the dashboard's icon stays anchored to the left edge. #### Scenario: Star renders on the effective-default row -@e2e exclude marker-render assertion on a specific DOM node — covered by Vitest component test - **GIVEN** the sidebar renders with one dashboard being the effective default - **WHEN** the rows render - **THEN** that row MUST show a `Star` icon inside a `dashboard-switcher-sidebar__default-marker` span @@ -68,7 +67,6 @@ resolver's first five steps: The pin always wins over group fallbacks. #### Scenario: Pin wins over group fallback -@e2e exclude resolver-precedence logic — covered by Vitest component test - **GIVEN** the user has pinned dashboard A and a group default B exists - **WHEN** `isDefaultDashboard()` is evaluated for each row - **THEN** only dashboard A MUST be marked as the effective default @@ -81,7 +79,6 @@ LaunchPad"* and an `aria-label` with the shorter *"Default dashboard"* so screen readers announce the marker. #### Scenario: Marker carries tooltip and aria-label -@e2e exclude title/aria-label attribute assertion — covered by Vitest component test - **GIVEN** the effective-default marker is rendered - **WHEN** the marker span is inspected - **THEN** it MUST carry a `title` attribute with the localised default-dashboard copy @@ -95,7 +92,6 @@ Pinning a different dashboard via the cog menu MUST move the marker in the same render tick. #### Scenario: Marker moves when pin changes -@e2e exclude same-tick reactive re-render assertion — covered by Vitest component test - **GIVEN** dashboard A is currently marked as default - **WHEN** the user pins dashboard B via the cog menu - **THEN** the marker MUST move to dashboard B in the same render tick without a page reload @@ -106,7 +102,6 @@ The marker's color MUST be `var(--color-warning, #e9a800)` so it inherits Nextcloud theme overrides (light/dark variants). #### Scenario: Marker color uses theme variable -@e2e exclude CSS custom-property color is a computed-style assertion — Vitest/visual-regression scope, not browser flow - **GIVEN** the marker is rendered - **WHEN** its color is computed - **THEN** it MUST resolve to `var(--color-warning, #e9a800)` so it follows theme overrides diff --git a/openspec/specs/embedded-analytics/spec.md b/openspec/specs/embedded-analytics/spec.md new file mode 100644 index 000000000..ccdd009f9 --- /dev/null +++ b/openspec/specs/embedded-analytics/spec.md @@ -0,0 +1,1438 @@ +# embedded-analytics Specification + +## Purpose +LaunchPad widgets and dashboards can be shown on another website, such as a municipality's public site or intranet, without a Nextcloud login. An administrator issues a signed embed token for one widget or dashboard, naming the host origins that may frame it, a read-only or interactions scope, a rate limit and an optional tenant theme. The public render route admits a request only with a valid, unrevoked token for that very subject, frames it only on the listed origins, enforces the scope at the API tier, applies the theme through CSS variables, meets WCAG 2.1 AA, and records usage without personal data. A JavaScript SDK embeds and talks to the iframe, and a revoked token stops working within 60 seconds. + +## Requirements + +### Requirement: REQ-EMB-001 — Token issuance returns JWT exactly once + +The system SHALL generate a JWT signed with the active signing key when a new `embed_token` is created, return it once in the create response, persist only the sha256 hash, and reject any subsequent request to re-retrieve the raw token. + +#### Scenario: 1.1 — Create token and receive JWT once + +GIVEN an admin user with token-management permission + AND the system has an active RS256 signing key +WHEN they POST `/api/embed-tokens` with a valid token-create payload: + ```json + { + "name": "Gemeente Zeist WOO", + "description": "Public WOO requests widget", + "subject": {"type": "widget", "id": "woo-widget-uuid"}, + "scope": {"mode": "read", "allowedFilters": ["status"], "allowedActions": []}, + "hostOrigins": ["https://intranet.zeist.nl"], + "rateLimitPolicy": {"requestsPerMinute": 600, "burstSize": 60} + } + ``` +THEN the response SHALL be 201 with body: + ```json + { + "id": "token-id-uuid", + "name": "Gemeente Zeist WOO", + "jwt": "eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...", + "warning": "keepThisSafe: This JWT is shown only once. Save it now. If lost, you must re-issue the token.", + "createdAt": "2026-05-22T14:30:00Z" + } + ``` + AND the response body SHALL include the raw JWT exactly once + AND a new row SHALL be created in `embed_token` register with: + - `id` matching the response + - `tokenHash` = sha256("eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...") + - ALL other fields matching the request + createdAt + +#### Scenario: 1.2 — Subsequent GET returns metadata but not JWT + +GIVEN an existing `embed_token` row with id="token-1" and tokenHash set +WHEN any GET request to `/api/embed-tokens/token-1` is made +THEN the response SHALL be 200 with body: + ```json + { + "id": "token-1", + "name": "Gemeente Zeist WOO", + "description": "Public WOO requests widget", + "subject": {"type": "widget", "id": "woo-widget-uuid"}, + "scope": {"mode": "read", ...}, + "hostOrigins": ["https://intranet.zeist.nl"], + "createdAt": "2026-05-22T14:30:00Z", + "createdBy": "admin-user-id", + "actions": [ + {"id": "re-issue", "label": "Re-issue token", "description": "Revoke this token and generate a new one"} + ] + } + ``` + AND the response SHALL NOT include the `jwt` field + AND the response SHALL NOT include the `tokenHash` field + +#### Scenario: 1.3 — Token creation rejects malformed hostOrigins + +GIVEN an admin user with token-management permission +WHEN they POST `/api/embed-tokens` with `hostOrigins` containing a malformed origin: + ```json + { + "name": "Bad Token", + "hostOrigins": ["https://www.example.com", "invalid-origin-missing-scheme"], + ... + } + ``` +THEN the response SHALL be 400 with body: + ```json + { + "status": "error", + "error": "invalid_hostOrigins", + "message": "Invalid origin format at index 1: missing URI scheme. Expected format: https://domain.com", + "fieldErrors": { + "hostOrigins[1]": "invalid_hostOrigins" + } + } + ``` + AND the `embed_token` row SHALL NOT be persisted + +#### Scenario: 1.4 — Re-issue token (revoke + create new) + +GIVEN an existing `embed_token` row with id="token-1" +WHEN an admin invokes the "re-issue" action via POST `/api/embed-tokens/token-1/re-issue` +THEN a new JWT SHALL be generated (signed with active key) + AND the old token's `revokedAt` SHALL be set to now + AND the old token's `revocationReason` SHALL be set to "re-issued" + AND a new `embed_token` row SHALL be created with: + - fresh `id` (new UUID) + - fresh `tokenHash` (sha256 of new JWT) + - same `subject`, `scope`, `hostOrigins`, `rateLimitPolicy` as the old token + - new `createdAt` and `createdBy` + AND the response SHALL include the new JWT (shown once) + +--- + +### Requirement: REQ-EMB-002 — Public render route validates JWT and enforces scope + +The render route SHALL verify the JWT signature against the `kid`-selected `signing_key`, reject expired or revoked tokens, enforce `subject` match, and respond with 403 on any mismatch without leaking the existence of the subject. + +#### Scenario: 2.1 — Valid non-expired token renders widget + +GIVEN a valid, non-expired, non-revoked JWT for widget W signed with RS256 key (kid=rsa-1) + AND the embedded widget renders HTML (no token scope restriction assumed yet — REQ-EMB-004 covers scope enforcement) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` +THEN the response SHALL be 200 with HTML body + AND the response SHALL include header `Content-Security-Policy: frame-ancestors <hostOrigins>` + AND the response SHALL include header `X-Content-Type-Options: nosniff` + AND the widget SHALL render with the token's context applied (e.g., filter pinning from `subject.filterContext`) + AND a `embed_usage_event` row SHALL be written with: + - `eventType: "pageView"` + - `responseStatusCode: 200` + - `responseLatencyMs: <measured>` + +#### Scenario: 2.2 — Subject mismatch returns 403 without leaking existence + +GIVEN a valid JWT for widget W + AND the admin tries to render it against widget V (different UUID) +WHEN the route is called with `GET /apps/launchpad/embed/widget/V?token=<jwt>` +THEN the response SHALL be 403 with body: + ```json + { + "error": "scope_mismatch", + "message": "The provided token does not grant access to this resource" + } + ``` + AND the response SHALL NOT indicate whether widget V exists or not + AND a `embed_usage_event` row SHALL be written with: + - `eventType: "pageView"` + - `responseStatusCode: 403` + +#### Scenario: 2.3 — Expired token returns 401 with WWW-Authenticate header + +GIVEN a JWT whose `tokenExpiresAt` is in the past (e.g., "2026-01-01T00:00:00Z" and current time is 2026-05-22) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` +THEN the response SHALL be 401 with body: + ```json + { + "error": "token_expired", + "message": "The provided token has expired" + } + ``` + AND the response SHALL include header: + `WWW-Authenticate: Bearer error="invalid_token", error_description="The token has expired"` + AND a `embed_usage_event` row SHALL be written with `responseStatusCode: 401` + +#### Scenario: 2.4 — Revoked token returns 401 with constant-time comparison + +GIVEN a JWT whose `embed_token` row has `revokedAt` set (token was revoked 5 minutes ago) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<jwt>` +THEN the response SHALL be 401 with body: + ```json + { + "error": "token_revoked", + "message": "The provided token has been revoked" + } + ``` + AND the response latency SHALL be constant-time-comparable to a non-revoked rejection (to prevent timing oracle attacks) + AND a `embed_usage_event` row SHALL be written with `responseStatusCode: 401` + +#### Scenario: 2.5 — Invalid JWT signature returns 401 + +GIVEN a JWT with an invalid signature (e.g., tampered payload) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W?token=<tampered-jwt>` +THEN the response SHALL be 401 with body: + ```json + { + "error": "invalid_token", + "message": "The provided token is invalid or malformed" + } + ``` + +#### Scenario: 2.6 — Missing token returns 401 + +GIVEN a request to the embed render route without a token +WHEN the route is called with `GET /apps/launchpad/embed/widget/W` (no ?token= parameter) +THEN the response SHALL be 401 with body: + ```json + { + "error": "missing_token", + "message": "No token provided. Include ?token=<jwt> or use the Authorization: Bearer <jwt> header" + } + ``` + +#### Scenario: 2.7 — Bearer header token (SDK form-factor) + +GIVEN a valid JWT passed via Authorization header (SDK use case) +WHEN the route is called with `GET /apps/launchpad/embed/widget/W` + header `Authorization: Bearer <jwt>` +THEN the response SHALL be 200 with HTML body (same as Scenario 2.1) + AND the response latency/rate-limit treatment SHALL be identical to query-parameter tokens + AND the response CSP/cache headers SHALL be identical + +#### Scenario: 2.8 — Query-parameter tokens enforce stricter rate limits + +GIVEN a token with `rateLimitPolicy: {requestsPerMinute: 600, burstSize: 60}` + AND requests arriving via `?token=<jwt>` (query parameter) + AND requests arriving via `Authorization: Bearer <jwt>` (header) +WHEN both form-factors are used for the same embed in the same minute +THEN the query-parameter form SHALL count against the token's configured rate limit + AND the Bearer-header form MAY have a separate (stricter) rate limit (e.g., 10× lower) to account for the token leak risk + AND the admin UI SHOULD surface this distinction in the token-creation flow + +### Requirement: REQ-EMB-003 — CSP frame-ancestors enforced from token hostOrigins + +The render route SHALL emit `Content-Security-Policy: frame-ancestors <hostOrigins>` derived from the token's `hostOrigins`, and the embed SHALL refuse to render when the iframe's actual top-level origin is not in `hostOrigins`. This is enforced both at the CSP level (modern browsers) and via Fetch Metadata headers (defence in depth). + +#### Scenario: 3.1 — Valid origin renders with CSP frame-ancestors header + +GIVEN a token with `hostOrigins=["https://www.zeist.nl"]` + AND the token is for widget W +WHEN the embed is loaded inside an iframe on `https://www.zeist.nl/woo/` +THEN the response to `GET /apps/launchpad/embed/widget/W?token=<jwt>` SHALL be 200 with HTML body + AND the response SHALL include header: + `Content-Security-Policy: frame-ancestors https://www.zeist.nl` + AND the browser SHALL render the iframe normally (CSP allows framing from https://www.zeist.nl) + +#### Scenario: 3.2 — Invalid origin blocked by CSP + server-side Sec-Fetch-Site check + +GIVEN the same token with `hostOrigins=["https://www.zeist.nl"]` +WHEN the iframe is loaded from `https://evil.example.com/phishing-page` + AND the iframe's top-level origin is `https://evil.example.com` +THEN the browser SHALL refuse to display the iframe due to CSP frame-ancestors violation + AND the server-side render route SHALL check the `Sec-Fetch-Site` header: + - If `Sec-Fetch-Site: cross-site` and top-origin from Referer ≠ allowed hostOrigins + - Then respond 403 with body `{error: "origin_mismatch", message: "This iframe cannot be embedded on this origin"}` + AND the browser still refuses to render (CSP violation takes precedence) + AND a `embed_usage_event` SHALL be written with `responseStatusCode: 403` + +#### Scenario: 3.3 — Multiple allowed origins + +GIVEN a token with `hostOrigins=["https://intranet.zeist.nl", "https://www.zeist.nl"]` +WHEN the embed is loaded from either origin +THEN the response SHALL include header: + `Content-Security-Policy: frame-ancestors https://intranet.zeist.nl https://www.zeist.nl` + AND the browser SHALL allow framing from either origin + +#### Scenario: 3.4 — Wildcard hostOrigins rejected at token creation + +GIVEN an admin user +WHEN they attempt to POST `/api/embed-tokens` with `hostOrigins=["*"]` +THEN the response SHALL be 400 with body: + ```json + { + "status": "error", + "error": "invalid_hostOrigins", + "message": "Wildcard origin '*' is not permitted. Specify explicit origins, e.g., [\"https://www.example.com\"]", + "fieldErrors": { + "hostOrigins": "wildcard_not_permitted" + } + } + ``` + AND the token SHALL NOT be created + +#### Scenario: 3.5 — X-Frame-Options fallback for legacy browsers + +GIVEN any render route response +WHEN the response is generated +THEN the response SHALL ALSO include header: + `X-Frame-Options: SAMEORIGIN` + (As a fallback for browsers that do not support CSP Level 3; no protective claim is made about X-Frame-Options sufficiency on modern browsers per W3C spec) + +#### Scenario: 3.6 — Referer header check (defence in depth) + +GIVEN a request with `Authorization: Bearer <jwt>` (Bearer header, not query param) + AND the token's `hostOrigins=["https://intranet.example.com"]` +WHEN the render route processes the request + AND the `Referer` header is `https://evil.example.com/page` +THEN the route SHALL respond 403 with body `{error: "origin_mismatch"}` + AND a `embed_usage_event` SHALL be written with `responseStatusCode: 403` + +#### Scenario: 3.7 — No Referer header (privacy-preserving browser configuration) + +GIVEN a request with no `Referer` header + AND the `Sec-Fetch-Site` header indicates `same-site` +THEN the route SHALL allow the request (assume same-origin; Referer is not available in privacy-preserving configurations) + AND a `embed_usage_event` SHALL be written with `responseStatusCode: 200` + +#### Scenario: 3.8 — Admin UI displays CSP header preview + +GIVEN the admin is creating or editing an embed token +WHEN they edit the `hostOrigins` field +THEN the admin UI SHALL display a live preview of the resulting CSP header: + ``` + Content-Security-Policy: frame-ancestors https://intranet.zeist.nl + ``` + AND a "Copy CSP header" button SHALL let them paste this into their host website's audit documentation + +### Requirement: REQ-EMB-004 — Read-only enforcement at the API tier + +The system SHALL reject any write operation (POST/PUT/PATCH/DELETE) issued under an `embed_token` whose `scope.mode=read`, even when the operation would otherwise be permitted by the subject's ACL. This enforcement happens on the API tier before any state mutation. + +#### Scenario: 4.1 — Read-mode token rejects write operation + +GIVEN an `embed_token` with `scope.mode="read"` for dashboard D + AND JavaScript running in the iframe holds this token as `Authorization: Bearer <jwt>` +WHEN it sends a write (POST/PUT/PATCH/DELETE) to a LaunchPad route that needs no Nextcloud login (a public route) +THEN the API SHALL respond 403 before the controller runs, with body: + ```json + { + "error": "read_only_token", + "message": "This token does not permit write operations. Token scope: mode=read" + } + ``` + AND NO state SHALL be mutated +WHEN it sends a write to a route that needs a Nextcloud login, such as `POST /api/dashboard/{id}/widgets` to add a widget to dashboard D +THEN Nextcloud SHALL refuse it with 401 before LaunchPad runs, because an embed token is not a Nextcloud login + AND NO state SHALL be mutated (no widget added, no audit log entry) + +#### Scenario: 4.2 — Read-mode token rejects DELETE + +GIVEN the same read-only token for dashboard D +WHEN the frontend attempts `DELETE /api/dashboards/D/widgets/w1` (remove a widget from the dashboard) +THEN the API SHALL respond 403 with body: + ```json + { + "error": "read_only_token", + "message": "This token does not permit write operations. Token scope: mode=read" + } + ``` + AND NO state mutation occurs + +#### Scenario: 4.3 — Read-mode token permits GET and HEAD + +GIVEN the same read-only token +WHEN the frontend invokes `GET /api/dashboards/D` (read operation) +THEN the API SHALL respond 200 with the dashboard data + AND read permission is determined by the subject-match (the token is scoped to dashboard D) + AND no scope-mode check blocks the read + +#### Scenario: 4.4 — Read-with-interactions token permits scoped actions + +GIVEN an `embed_token` with `scope.mode="read-with-interactions", allowedActions=["interact", "drillDown"]` for dashboard D + AND the dashboard has a filter UI +WHEN the SDK applies an in-bus filter clause (drill-down), invoking `POST /api/dashboards/D/filters` with `{dimension: "gemeente", value: "Amsterdam"}` +THEN the API SHALL respond 200 and process the filter + AND the operation SHALL be captured in an `embed_usage_event` with `eventType: "filterApplied"` + AND subsequent `GET` calls reflect the pinned filter + +#### Scenario: 4.5 — Read-with-interactions token rejects disallowed action + +GIVEN an `embed_token` with `scope.mode="read-with-interactions", allowedActions=["interact", "drillDown"]` (export NOT allowed) +WHEN the frontend attempts `POST /api/dashboards/D/export` with `format: "csv"` +THEN the API SHALL respond 403 with body: + ```json + { + "error": "action_not_in_scope", + "message": "The action 'export' is not permitted by this token. Allowed actions: interact, drillDown" + } + ``` + AND NO export is generated + +#### Scenario: 4.6 — All write operations checked, regardless of subject type + +GIVEN a read-only token for a widget W +WHEN any of the following write operations are attempted on the widget: + - `POST /api/widgets/W/interactions` (add interaction) + - `PUT /api/widgets/W/settings` (update widget settings) + - `PATCH /api/widgets/W` (partial update) +THEN ALL SHALL respond 403 with the read-only error + AND the API does NOT discriminate by operation type; ALL non-GET/HEAD are blocked + +#### Scenario: 4.7 — Scope enforcement independent of frontend state + +GIVEN a read-only token embedded in an iframe +WHEN the JavaScript in the iframe is patched (via browser DevTools) to remove the UI-layer read-only enforcement + AND the patched JS attempts `POST /api/dashboards/D/widgets/new` +THEN the API-tier check SHALL still respond 403 + AND the tampered frontend cannot bypass the API check + +#### Scenario: 4.8 — Scope metadata visible in token detail view + +GIVEN an admin viewing an embed token's details +WHEN they inspect the token's scope +THEN the admin UI SHALL display: + ``` + Mode: read + Allowed Filters: status, periode + Allowed Actions: (none) + ``` + AND when creating a read-with-interactions token, the admin SHALL see checkboxes for each available action (interact, export, drillDown) to select + +#### Scenario: 4.9 — Filter context pinning persisted with token + +GIVEN an `embed_token` for dashboard D with `subject.filterContext={gemeente: "Amsterdam"}` +WHEN the embed is rendered + AND the user attempts to change the gemeente filter to "Rotterdam" via the UI +THEN the filter interaction SHALL succeed (read-with-interactions mode allows it) + BUT the filter SHALL NOT persist across page reloads — the next page load resets the gemeente filter to "Amsterdam" + AND the filter context is enforced by the render route, not by the frontend + +#### Scenario: 4.10 — API middleware integration point + +GIVEN the LaunchPad API middleware/controller base +WHEN a request arrives with an `embed_token` (detected via JWT in Authorization header or token context) +THEN the middleware SHALL: + 1. Verify the token is valid and non-revoked (REQ-EMB-002) + 2. Extract the token's scope + 3. For non-GET/HEAD requests, check if `scope.mode=read` and respond 403 before the controller is invoked + 4. For GET/HEAD requests, proceed to the controller (the subject-match verification happens per-endpoint) + 5. For actions with allowedActions restrictions, check the action name against the allowed set before invoking the handler + +### Requirement: REQ-EMB-005 — Per-tenant theming via CSS variables + +The embed SHALL apply the token's `tenantThemeId` (if set) by injecting `cssVariables` into the embed's `:root` and SHALL refuse `customCss` rules that target selectors outside `:root`. + +#### Scenario: 5.1 — CSS variables injected into :root + +GIVEN a `tenant_theme` object with: + ```json + { + "id": "theme-zeist", + "name": "Gemeente Zeist", + "cssVariables": { + "--c-primary": "#21468B", + "--font-family": "Inter, sans-serif", + "--c-surface": "#FFFFFF", + "--c-text": "#1a1a1a", + "--c-border": "#e0e0e0" + } + } + ``` + AND an `embed_token` with `tenantThemeId="theme-zeist"` for widget W +WHEN the embed render route generates HTML for widget W +THEN the response SHALL include: + ```html + <html> + <head> + <style> + :root { + --c-primary: #21468B; + --font-family: Inter, sans-serif; + --c-surface: #FFFFFF; + --c-text: #1a1a1a; + --c-border: #e0e0e0; + } + </style> + </head> + <body> + <!-- widget HTML --> + </body> + </html> + ``` + AND the widget's styles SHALL use these CSS variables + AND the widget SHALL paint with the gemeente's brand colour (primary), font, and surface colour + +#### Scenario: 5.2 — Custom CSS restricted to :root only + +GIVEN a `tenant_theme` with `customCss=":root { --spacing: 8px; }"` +WHEN the theme is saved via `POST /api/tenant-themes` +THEN the API SHALL accept the theme and respond 201 + +#### Scenario: 5.3 — Custom CSS with non-:root selector rejected + +GIVEN an admin attempting to save a `tenant_theme` with `customCss=".widget-title { color: red; }"` +WHEN the POST `/api/tenant-themes` request is processed +THEN the API SHALL respond 400 with body: + ```json + { + "status": "error", + "error": "invalid_customCss", + "message": "CSS rules must be scoped to :root only. Found selector '.widget-title' which targets elements outside :root. Non-:root selectors can be used to disable required UI affordances (e.g., hide accessibility focus rings).", + "fieldErrors": { + "customCss": "non_root_selector" + } + } + ``` + AND the theme SHALL NOT be created + +#### Scenario: 5.4 — No theme uses platform default + +GIVEN an `embed_token` with `tenantThemeId: null` (no theme selected) +WHEN the embed render route generates HTML +THEN the response SHALL use the platform's default NL Design theme (no custom :root injection) + AND the widget SHALL render with standard LaunchPad colours and fonts + +#### Scenario: 5.5 — Theme logo displayed in embed header + +GIVEN a `tenant_theme` with `logoUrl="https://www.zeist.nl/logo.svg"` + AND an `embed_token` referencing this theme +WHEN the embed is rendered in iframe mode +THEN the render route MAY include a minimal embed header with: + ```html + <div class="embed-header"> + <img src="https://www.zeist.nl/logo.svg" alt="Gemeente Zeist" class="embed-logo" /> + </div> + ``` + AND the header SHALL be minimal (no chrome, no navigation, no user menu) + OR the header MAY be omitted if the embed is configured for full-bleed rendering + +#### Scenario: 5.6 — Theme inheritance in admin UI + +GIVEN the admin creating a new embed token +WHEN they select a `tenantThemeId` +THEN the admin UI SHALL display: + - Theme name ("Gemeente Zeist") + - Live preview of brand colours (primary, surface, text) + - Logo preview (if set) + AND a "View CSS variables" button to inspect the variable overrides + +#### Scenario: 5.7 — Multiple tokens can share a theme + +GIVEN a `tenant_theme` "Gemeente Zeist" +WHEN two different `embed_token` objects both reference `tenantThemeId="theme-zeist"` +THEN both embeds SHALL render with the same brand + AND theme updates affect both embeds immediately + AND the theme is a reusable resource, not cloned per token + +--- + +### Requirement: REQ-EMB-010 — WCAG 2.1 AA compliance enforced in embed rendering + +The embed render route SHALL produce HTML output that meets WCAG 2.1 AA success criteria for the widget being embedded, SHALL pass automated axe-core checks at build time on a representative sample of widget shapes, and SHALL surface accessibility violations in the embed-token admin UI as a non-fatal warning. + +#### Scenario: 10.1 — WCAG AA rendering requirements + +GIVEN an embed render of a chart widget +WHEN the HTML is inspected against WCAG 2.1 AA criteria +THEN EVERY interactive element SHALL have: + - An accessible name (`aria-label`, `aria-labelledby`, or visible text content) + - Colour contrast ≥ 4.5:1 for text (WCAG 1.4.3) + - Colour contrast ≥ 3:1 for graphical objects (WCAG 1.4.11) +AND the embed SHALL be navigable by keyboard alone: + - All interactive elements reachable via Tab key + - Tab order logical (left-to-right, top-to-bottom) + - No keyboard traps (user can tab away from any element) + - Focus indicators visible (outline or other visible focus marker) +AND semantic HTML is used: + - Heading hierarchy correct (no skipped levels) + - Lists marked with `<ul>`, `<ol>`, `<li>` + - Form inputs have associated `<label>` elements + +#### Scenario: 10.2 — Contrast check on theme CSS variables + +GIVEN a `tenant_theme` with `cssVariables={"--c-primary": "#0099CC", "--c-surface": "#FFFFFF"}` +WHEN the theme is saved +THEN the API SHALL compute the colour contrast ratio using the WCAG luminance formula + AND if contrast < 4.5:1, respond 400 with body: + ```json + { + "status": "error", + "error": "insufficient_contrast", + "message": "Primary colour #0099CC against surface #FFFFFF has contrast ratio 3.8:1. WCAG AA requires 4.5:1 for text.", + "fieldErrors": { + "cssVariables.--c-primary": "insufficient_contrast" + } + } + ``` + AND the theme SHALL NOT be created + (Admin can choose a darker primary or lighter surface and retry) + +#### Scenario: 10.3 — Build-time axe-core checks + +GIVEN the LaunchPad build pipeline +WHEN `npm run build` executes +THEN a test step SHALL: + 1. Render a representative sample of widget shapes (e.g., chart, table, text, image, custom) + 2. Run axe-core automated checks against each rendered HTML + 3. Fail the build if high/critical violations are found + 4. Log a warning for medium/low violations with IDs + AND the build output SHALL include an axe-core report + +#### Scenario: 10.4 — Admin warned of accessibility violations on token creation + +GIVEN an admin creating an `embed_token` for a widget W + AND widget W has known accessibility violations (e.g., from a previous axe-core check) +WHEN the admin submits the token-create form +THEN the API SHALL check the widget's violation registry + AND if violations exist, respond 200 (success, but with warning) with: + ```json + { + "id": "token-1", + "name": "...", + ... + "warnings": [ + { + "level": "accessibility", + "message": "Widget 'chart' has 2 known accessibility violations (axe-core build-time check):", + "violations": [ + { + "id": "color-contrast", + "description": "Ensure the contrast between foreground and background colours meets WCAG AA thresholds", + "help": "Element <text class=\"legend\"> has contrast ratio 2.8:1. Expected ≥4.5:1" + }, + { + "id": "aria-label", + "description": "Ensure every graphical element has an accessible name", + "help": "<svg class=\"chart\"> is missing aria-label" + } + ] + } + ] + } + ``` + AND the response includes an "Acknowledge and proceed" checkbox in the admin UI + AND the admin MUST check the checkbox before creating the token (non-blocking, but requires acknowledgement) + +#### Scenario: 10.5 — Axe-core check results per widget + +GIVEN the admin viewing the list of available widgets +WHEN they see a widget's detail card +THEN the card SHALL display: + - Widget name + description + - Latest axe-core check date + - Number of high/critical violations (in red if > 0) + - Number of medium/low violations (in yellow if > 0) + AND a "View accessibility report" link that opens the axe-core report for that widget + +#### Scenario: 10.6 — Accessibility report exportable + +GIVEN an admin with token-management permission +WHEN they request an accessibility compliance report +THEN the system SHALL generate a CSV/JSON report listing: + - Widget name + - Accessibility status (compliant / violations found) + - Violation count by severity + - Affected tokens (count of embeds using this widget) + AND the report includes axe-core rule IDs and WCAG criteria references + +#### Scenario: 10.7 — Manual accessibility review responsibility + +GIVEN a widget with axe-core violations +WHEN the admin acknowledges and creates a token +THEN the token's audit trail SHALL record: + - "Token created for widget 'chart' with acknowledged accessibility violations: color-contrast, aria-label" + AND the responsibility for manual review (the remaining ~70% of WCAG criteria not mechanically checkable) is documented per-widget + AND the widget author is responsible for ensuring manual compliance + +#### Scenario: 10.8 — Keyboard navigation tested in embed iframe + +GIVEN an embedded widget in an iframe +WHEN a user navigates using keyboard alone (Tab, Shift+Tab, Enter, Escape, arrow keys) +THEN: + - All interactive elements are reachable + - No keyboard traps exist (user can Tab out) + - Focus indicator is visible and moves logically + - Modals (if any) trap focus correctly + +### Requirement: REQ-EMB-006 — JS-SDK exposes render, event, and resize APIs + +The system SHALL serve a JS-SDK from the app itself (ESM and UMD builds at `/apps/launchpad/embed-sdk/embed-sdk.esm.js` and `.../embed-sdk.umd.js`, public, cacheable, loadable from any origin and versioned with the app; not published on npm) that exposes `LaunchPadEmbed.render(container, {token, subjectType, subjectId})`, `.on(eventType, handler)` for filter/drill/export events, and `.resize()` for host-driven layout changes. + +#### Scenario: 6.1 — SDK initialization and iframe creation + +GIVEN a host page (e.g., a SaaS customer portal) that imports the SDK: + ```html + <script src="https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.umd.js"></script> + <!-- OR ESM: import LaunchPadEmbed from 'https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.esm.js'; --> + ``` +WHEN the host page calls: + ```javascript + const embed = LaunchPadEmbed.render('#embed-container', { + token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...', + subjectType: 'widget', + subjectId: 'usage-widget-uuid' + }); + ``` +THEN the SDK SHALL: + 1. Create an `<iframe>` element with `src="https://launchpad.app/apps/launchpad/embed/widget/usage-widget-uuid"` + 2. Insert the iframe into the `#embed-container` div + 3. Wait for the iframe's `load` event + 4. Perform a postMessage handshake with the iframe to inject the JWT token + 5. Resolve a promise when the first render completes + AND the host page code continues: + ```javascript + embed.then(() => { + console.log('Widget loaded'); + }); + ``` + +#### Scenario: 6.2 — PostMessage handshake for token injection + +GIVEN the SDK has created an iframe +WHEN the iframe loads (fires `load` event) +THEN the SDK SHALL: + 1. Post a message to the iframe: + ```javascript + iframe.contentWindow.postMessage({ + type: 'embed-token', + token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0...', + origin: 'https://portal.example.com' + }, 'https://launchpad.app') + ``` + 2. The iframe's origin verification (in the render route) SHALL check that `event.origin === 'https://launchpad.app'` before accepting the message + 3. The iframe stores the token in a secure context and uses it for subsequent API requests + 4. The iframe posts back a 'ready' message when the widget is fully rendered: + ```javascript + window.parent.postMessage({type: 'embed-ready', success: true}, '<SDK-origin>') + ``` + 5. The SDK resolves the promise returned by `render()` when the 'embed-ready' message arrives + +#### Scenario: 6.3 — Filter event subscription and relay + +GIVEN the host page has called `render()` successfully +WHEN the host page subscribes to filter events: + ```javascript + embed.on('filterApplied', ({dimension, value, source}) => { + console.log(`Filter applied: ${dimension} = ${value}`); + // Host page can now sync its own UI + }); + ``` +AND the end-user clicks on a bar in the embedded chart (drill-down interaction) +THEN the iframe SHALL: + 1. Emit an internal event (in-app bus) with `{dimension: 'gemeente', value: 'Amsterdam'}` + 2. Post a message to the parent: + ```javascript + window.parent.postMessage({ + type: 'embed-event', + eventType: 'filterApplied', + payload: {dimension: 'gemeente', value: 'Amsterdam', source: 'user-interaction'} + }, '<SDK-origin>') + ``` + 3. The SDK receives the message and invokes the registered handler + 4. The host page can read the filter and update its own UI/URL + +#### Scenario: 6.4 — Export event (read-with-interactions) + +GIVEN an embed with `scope.allowedActions=["export"]` +WHEN the user clicks "Export to CSV" in the widget +THEN the iframe SHALL: + 1. Invoke the export API (allowed by scope) + 2. Post a 'export' event to the parent: + ```javascript + window.parent.postMessage({ + type: 'embed-event', + eventType: 'export', + payload: {format: 'csv', url: 'https://launchpad.app/api/downloads/export-123.csv'} + }, '<SDK-origin>') + ``` + 3. The host page can download the file or handle it custom (e.g., send to email) + +#### Scenario: 6.5 — Resize API for responsive layout + +GIVEN the host page's layout changes (e.g., browser window resized, sidebar collapsed) +WHEN the host page calls: + ```javascript + embed.resize(); + ``` +THEN the SDK SHALL: + 1. Post a message to the iframe: + ```javascript + iframe.contentWindow.postMessage({ + type: 'embed-resize', + containerWidth: 1200, + containerHeight: 600 + }, 'https://launchpad.app') + ``` + 2. The iframe receives the message and re-measures its container + 3. The iframe re-renders the widget with the new dimensions + 4. The iframe posts back a 'resized' message when complete: + ```javascript + window.parent.postMessage({type: 'embed-resized', success: true}, '<SDK-origin>') + ``` + 5. The SDK resolves the promise returned by `resize()` + +#### Scenario: 6.6 — ESM build with TypeScript types + +GIVEN a TypeScript host application +WHEN it imports the SDK: + ```typescript + import LaunchPadEmbed from 'https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.esm.js'; + import type { EmbedConfig, EmbedInstance } from './launchpad-embed-types'; // a copy of src/embed-sdk/src/types.ts + + const config: EmbedConfig = { + token: 'eyJ...', + subjectType: 'widget', + subjectId: 'uuid' + }; + + const embed: EmbedInstance = await LaunchPadEmbed.render('#container', config); + embed.on('filterApplied', (event) => { + // event is typed as EmbedFilterEvent + }); + ``` +THEN the IDE SHALL provide autocomplete and type checking + AND the TypeScript types SHALL document the API surface + +#### Scenario: 6.7 — UMD build for vanilla JS + +GIVEN a vanilla JavaScript page (no build step, no module bundler) +WHEN it loads the UMD bundle: + ```html + <script src="https://unpkg.com/@conduction/launchpad-embed@1.0.0/dist/embed-sdk.umd.js"></script> + ``` +THEN the SDK is available as a global: + ```javascript + window.LaunchPadEmbed.render('#container', {token: '...', ...}) + .then(() => console.log('Ready')); + ``` + +#### Scenario: 6.8 — Error handling in SDK + +GIVEN the host page calls `render()` with an invalid token +WHEN the iframe attempts to load the render route +THEN the render route responds 401 + AND the iframe posts an 'error' message to the parent: + ```javascript + window.parent.postMessage({ + type: 'embed-error', + error: 'invalid_token', + message: 'The provided token is invalid or has expired' + }, '<SDK-origin>') + ``` + AND the SDK's promise rejects with a descriptive error: + ```javascript + embed.catch((err) => { + console.error('Failed to load widget:', err.message); + }); + ``` + +#### Scenario: 6.9 — Event listener management + +GIVEN the host page has subscribed to events: + ```javascript + const handler = (event) => { ... }; + embed.on('filterApplied', handler); + ``` +WHEN the host page wants to unsubscribe: + ```javascript + embed.off('filterApplied', handler); + ``` +THEN the event listener SHALL be removed + AND no further 'filterApplied' events are delivered to that handler + AND other handlers (if registered) still receive events + +#### Scenario: 6.10 — Multiple embeds on same page + +GIVEN a host page with three embed containers: + ```html + <div id="embed-1"></div> + <div id="embed-2"></div> + <div id="embed-3"></div> + ``` +WHEN the host page initializes all three: + ```javascript + const embed1 = LaunchPadEmbed.render('#embed-1', {token: '...', subjectId: 'widget-1'}); + const embed2 = LaunchPadEmbed.render('#embed-2', {token: '...', subjectId: 'widget-2'}); + const embed3 = LaunchPadEmbed.render('#embed-3', {token: '...', subjectId: 'widget-3'}); + ``` +THEN each embed operates independently + AND events from embed1 do not leak to embed2 or embed3 + AND each postMessage handshake is isolated + +#### Scenario: 6.11 — SDK package publishing + +GIVEN the LaunchPad build process +WHEN `npm run build:sdk` executes +THEN the SDK package SHALL be published to npm with: + - ESM build: `dist/embed-sdk.esm.js` + - UMD build: `dist/embed-sdk.umd.js` + - TypeScript definitions: `dist/embed-sdk.d.ts` + - Minified versions: `dist/embed-sdk.esm.min.js`, `dist/embed-sdk.umd.min.js` + - Source maps for debugging + - Package name: `@conduction/launchpad-embed` + - Version matching the LaunchPad app version + +### Requirement: REQ-EMB-007 — Rate limiting and request budgeting per token + +The system SHALL apply the token's `rateLimitPolicy` to all requests, return 429 with a `Retry-After` header when the bucket is exhausted, and write a `embed_usage_event` of type `pageView` even on rate-limited responses for budgeting analysis. + +#### Scenario: 7.1 — Token-bucket rate limiting with burst + +GIVEN a token with `rateLimitPolicy={requestsPerMinute: 60, burstSize: 10}` + AND the current time is T=0 +WHEN 70 requests arrive between T=0 and T=10 seconds (10 seconds into the first minute) +THEN: + - Requests 1-10 SHALL be processed (up to burst size) + - Requests 11-70 SHALL receive 429 responses with `Retry-After: 50` (seconds until next bucket refill) + AND each 429 response SHALL include an `embed_usage_event` with `responseStatusCode: 429` + AND after 60 seconds (one full minute), the bucket is refilled and new requests can be processed + +#### Scenario: 7.2 — Org-default rate limit for tokens without policy + +GIVEN a token with `rateLimitPolicy: null` (no custom policy specified) +WHEN requests arrive +THEN the org-level default policy SHALL apply: + ```json + { + "requestsPerMinute": 600, + "burstSize": 60 + } + ``` + AND the token operates under these defaults (high-throughput default for typical embeds) + +#### Scenario: 7.3 — 429 response format + +GIVEN a request that exceeds the rate limit +WHEN the render route processes it +THEN the response SHALL be 429 with: + ``` + HTTP/1.1 429 Too Many Requests + Content-Type: application/json + Retry-After: 45 + + { + "error": "rate_limit_exceeded", + "message": "Rate limit exceeded. The token allows 60 requests per minute. Try again in 45 seconds.", + "retryAfter": 45, + "resetAt": "2026-05-22T14:31:00Z" + } + ``` + +#### Scenario: 7.4 — Rate-limited request logged in usage events + +GIVEN a request that hits the rate limit +WHEN the 429 response is returned +THEN an `embed_usage_event` row SHALL be written with: + ```json + { + "id": "event-uuid", + "tokenId": "token-id", + "eventType": "pageView", + "hostOrigin": "https://www.zeist.nl", + "userAgent": "Chrome 124 / sha256(...)", + "viewportSize": "medium", + "timestamp": "2026-05-22T14:30:05Z", + "responseStatusCode": 429, + "responseLatencyMs": 12, + "correlationId": "correlation-uuid" + } + ``` + AND the admin can query: "This token hit rate limits 45 times on 2026-05-22 between 14:00 and 15:00" + +#### Scenario: 7.5 — Bucket refill and sliding window + +GIVEN a token with `requestsPerMinute: 60, burstSize: 10` (1 req/sec, burst 10) + AND 8 requests have been consumed at T=0 +WHEN new requests arrive at T=30 seconds (midway through the first minute) +THEN: + - 30 seconds of refill grants 30 requests (60 rpm ÷ 60 sec × 30 sec) + - Bucket now has: 10 (burst) + 30 (refilled) - 8 (used) = 32 capacity + - New request consumes 1, bucket now 31 + AND this is a token-bucket algorithm, not a fixed sliding window (continuous refill, not window resets) + +#### Scenario: 7.6 — Query-parameter vs Bearer-header rate limit distinction + +GIVEN a token with `rateLimitPolicy: {requestsPerMinute: 600, burstSize: 60}` +WHEN requests arrive via `?token=<jwt>` (query parameter) +THEN the query-parameter form MAY enforce a stricter limit: + - Override to 10× lower: 60 rpm, burst 6 (token leak risk warrants stricter throttling) + AND requests via `Authorization: Bearer <jwt>` (header) use the configured limit (600 rpm, burst 60) + AND the admin UI displays this distinction when creating a token: + ``` + Query-parameter form: up to 60 requests/minute (stricter for security) + Bearer header form: up to 600 requests/minute (as configured) + ``` + +#### Scenario: 7.7 — Rate limit policy updateable after token creation + +GIVEN an existing token with `rateLimitPolicy: {requestsPerMinute: 60, burstSize: 10}` +WHEN an admin invokes `PUT /api/embed-tokens/token-id` with a new policy: + ```json + { + "rateLimitPolicy": { + "requestsPerMinute": 120, + "burstSize": 15 + } + } + ``` +THEN the API SHALL respond 200 and update the token + AND the new rate limit applies to subsequent requests immediately + AND in-flight requests (between update and next request) use the old policy (best-effort; eventual consistency is acceptable) + +#### Scenario: 7.8 — Rate limit exhaustion analysis + +GIVEN the admin accessing the usage report for a token +WHEN they view the analytics dashboard +THEN they SHALL see: + ``` + Rate Limit Breaches + ├─ 2026-05-22: 145 requests rejected (60 expected) + │ Time: 14:00–15:00 (busiest hour) + │ Breach threshold: 600 rpm → hit 700 rpm + ├─ 2026-05-21: 23 requests rejected + └─ 2026-05-20: 0 requests rejected + + Recommendation: Consider raising requestsPerMinute to 1200 + ``` + AND a button "Adjust rate limit" opens the token edit dialog + +#### Scenario: 7.9 — Alert configuration (optional v1+) + +GIVEN an admin who wants to monitor token health +WHEN they configure alerts on a token (v1.1 feature, out of scope here but schema-ready): + ```json + { + "alertPolicy": { + "thresholdPercentage": 80, + "notifyEmail": "ops@gemeente.nl" + } + } + ``` +THEN when the token reaches 80% of its rate limit in a given minute, an email alert is sent + (This is a note for future expansion; not implemented in v1, but the schema supports it) + +#### Scenario: 7.10 — Rate limit headers in all responses + +GIVEN any response from the embed render route +WHEN the response is generated +THEN the response SHALL include rate-limit headers (RFC 6585 style): + ``` + RateLimit-Limit: 60 + RateLimit-Remaining: 45 + RateLimit-Reset: 2026-05-22T14:31:00Z + ``` + AND the host page / SDK can read these headers to show a rate-limit warning to the user + +### Requirement: REQ-EMB-008 — Usage telemetry without leaking PII + +The system SHALL persist `embed_usage_event` rows for every page-view and interaction, SHALL capture `hostOrigin`, `userAgent` (truncated to family + major version + hashed), and `viewportSize` (bucketed), and SHALL NOT capture full IP addresses, full user-agents, or any identifier of the host-page's logged-in user. + +#### Scenario: 8.1 — Page-view telemetry capture + +GIVEN an embed page-view request from `https://www.zeist.nl/woo/` (host origin) + AND the user's user-agent: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36` + AND the viewport size: 1920×1080 pixels +WHEN the render route processes the request and returns 200 +THEN an `embed_usage_event` row SHALL be written with: + ```json + { + "id": "event-uuid", + "tokenId": "token-id", + "eventType": "pageView", + "hostOrigin": "https://www.zeist.nl", + "userAgent": "Chrome 124", + "userAgentHash": "sha256(Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36)", + "viewportSize": "large", + "responseStatusCode": 200, + "responseLatencyMs": 87, + "timestamp": "2026-05-22T14:30:00Z", + "correlationId": "correlation-uuid" + } + ``` + +#### Scenario: 8.2 — Viewport size bucketing + +GIVEN viewport widths: + - 0–767px (small) + - 768–1279px (medium) + - 1280px+ (large) +WHEN embed requests arrive with various viewport sizes +THEN the event's `viewportSize` field SHALL be bucketed: + ```json + [ + {"width": 480, "height": 720, "viewportSize": "small"}, + {"width": 1024, "height": 768, "viewportSize": "medium"}, + {"width": 1920, "height": 1080, "viewportSize": "large"} + ] + ``` + +#### Scenario: 8.3 — NO IP address capture + +GIVEN a request arriving with headers: + ``` + X-Forwarded-For: 203.0.113.42 + X-Real-IP: 203.0.113.42 + ``` +WHEN the embed usage event is written +THEN the event row SHALL NOT include: + - Client IP address + - X-Forwarded-For header value + - Any IP-based geolocation +AND the only "location" data is the `hostOrigin` (domain, not geolocation) + +#### Scenario: 8.4 — User-agent family + major version only + +GIVEN user-agents: + ``` + Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0.6367.60 + Mozilla/5.0 (iPhone; CPU iPhone OS 17_4_1 like Mac OS X) Mobile Safari/604.1 + Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0 + ``` +WHEN events are written +THEN the `userAgent` field SHALL be truncated to family + major: + ```json + [ + {"userAgent": "Chrome 124"}, + {"userAgent": "Safari 17"}, + {"userAgent": "Firefox 125"} + ] + ``` +AND the full user-agent string is hashed and stored separately in `userAgentHash` for analytics without fingerprinting + +#### Scenario: 8.5 — NO end-user identifier in events + +GIVEN a host page that is embedded in a SaaS portal, where the logged-in user is "customer-123" + AND the LaunchPad request is made in the context of that user +WHEN the embed usage event is written +THEN the event row SHALL NOT include: + - User ID from the host page (even if passed in a header) + - Email address of the host-page's logged-in user + - Account name or subscription tier +AND the only identifier is the `tokenId` (which widget/dashboard was embedded, not who viewed it) + +#### Scenario: 8.6 — Host origin stored (not referrer, not full URL) + +GIVEN a request from `https://www.zeist.nl/woo/requests-2026-05/?sort=date&limit=50` +WHEN the event is written +THEN the `hostOrigin` field SHALL be: + ```json + {"hostOrigin": "https://www.zeist.nl"} + ``` +NOT: + - The full URL (path+query stripped) + - The Referer header (may be empty or stripped by proxies) + - Derived from IP geolocation + +#### Scenario: 8.7 — Interaction events also captured + +GIVEN the user interacts with an embedded widget (filter applied, drill-down, export) +WHEN the interaction is processed +THEN an `embed_usage_event` SHALL be written with: + ```json + { + "eventType": "filterApplied", + "payload": { + "dimension": "status", + "value": "openstaande" + }, + "hostOrigin": "https://www.zeist.nl", + "userAgent": "Chrome 124", + "viewportSize": "large", + "responseStatusCode": 200, + "timestamp": "2026-05-22T14:30:15Z" + } + ``` +OR: + ```json + { + "eventType": "export", + "payload": { + "format": "csv" + }, + ... + } + ``` + +#### Scenario: 8.8 — Usage report in admin UI + +GIVEN an admin accessing the usage report for a token +WHEN they view the analytics dashboard +THEN they SHALL see: + ``` + Pageviews + ├─ Total (last 7 days): 1,243 views + ├─ By date: + │ └─ 2026-05-22: 324 views + │ └─ 2026-05-21: 289 views + │ └─ 2026-05-20: 215 views + ├─ By host origin: + │ └─ https://www.zeist.nl: 1,100 views + │ └─ https://intranet.zeist.nl: 143 views + └─ By viewport size: + └─ large: 601 views + └─ medium: 432 views + └─ small: 210 views + + Interactions + ├─ filterApplied: 87 times + ├─ drillDown: 45 times + └─ export: 12 times + + Browsers + ├─ Chrome 124: 623 views + ├─ Safari 17: 312 views + └─ Firefox 125: 308 views + ``` + +#### Scenario: 8.9 — No individual-user identifiers in report + +GIVEN the admin viewing the usage report +WHEN they inspect the data +THEN they SHALL NOT see: + - List of end-users who viewed the embed + - User names or email addresses + - Timestamps per individual user (only aggregated by day) + - Correlation of two views to the same person (no fingerprinting via UA hash + viewport) +AND the report answers only: "Did this embed get traffic?" and "From where?" + +#### Scenario: 8.10 — Org-level telemetry kill-switch + +GIVEN an admin with org configuration access +WHEN they toggle "Disable embed usage telemetry" in org settings +THEN: + - No `embed_usage_event` rows are written for any subsequent requests + - Existing events are NOT deleted (audit trail remains) + - The toggle is auditable (audit log records who disabled telemetry and when) + - Re-enabling telemetry immediately resumes event capture + +#### Scenario: 8.11 — Data retention policy + +GIVEN the org's data retention policy (e.g., "keep events for 90 days") +WHEN 90 days have passed since an `embed_usage_event` was created +THEN a background job SHALL delete the old event + AND the event is permanently removed (not soft-deleted; no recovery) + AND the deletion is logged in the audit trail + +#### Scenario: 8.12 — GDPR/AVG data subject access (not applicable) + +GIVEN a data subject (end-user) requesting access to their personal data per GDPR Article 15 +WHEN the org's DPO runs the data-subject-access query +THEN the system SHALL respond: + ``` + No personal data on record for this data subject. + Reasoning: Embed telemetry captures only host origin and viewport size. + No user identifiers, emails, IP addresses, or other traceable personal data are stored. + The only entity involved is the embed token (issued by the org administrator to a third-party host), + not personal data of an end-user. + ``` +AND the org does NOT need to include embed telemetry in GDPR access response letters + +### Requirement: REQ-EMB-009 — Token revocation takes effect within 60 seconds + +The system SHALL revoke a token by setting `revokedAt`, propagate the revocation to all render-route workers within 60 seconds via a short-TTL cache, and reject subsequent render requests with 401. + +#### Scenario: 9.1 — Revocation via admin UI + +GIVEN an admin viewing an embed token's detail page +WHEN they click the "Revoke" button +THEN the admin UI SHALL display a confirmation dialog: + ``` + Revoke token "Gemeente Zeist WOO"? + + [Dropdown] Revocation reason: + ├─ Compromised + ├─ No longer needed + ├─ Host website decommissioned + └─ Other... + + [Text field] Additional notes (optional): + "Gemeente decided to move WOO tracking in-house" + + [Cancel] [Confirm Revoke] + ``` +WHEN they select a reason and confirm +THEN the UI SHALL POST `/api/embed-tokens/token-id/revoke` with: + ```json + { + "reason": "no_longer_needed", + "notes": "Gemeente decided to move WOO tracking in-house" + } + ``` + +#### Scenario: 9.2 — Revocation persisted in token record + +GIVEN the revoke request +WHEN the API processes it +THEN the `embed_token` row SHALL be updated with: + ```json + { + "id": "token-id", + "name": "Gemeente Zeist WOO", + ... + "revokedAt": "2026-05-22T14:35:00Z", + "revocationReason": "no_longer_needed", + "revocationNotes": "Gemeente decided to move WOO tracking in-house", + "revokedBy": "admin-user-id" + } + ``` + AND the response SHALL be 200 with the updated token metadata + AND a notification SHALL be sent to the token's `createdBy` user: + ``` + Token "Gemeente Zeist WOO" has been revoked by admin-user. + Reason: no_longer_needed + Notes: Gemeente decided to move WOO tracking in-house + Revocation timestamp: 2026-05-22T14:35:00Z + ``` + +#### Scenario: 9.3 — Render-route workers reject revoked token within 60 seconds + +GIVEN a revoked token (revokedAt set 5 seconds ago) + AND multiple render-route worker processes running +WHEN any request arrives with the revoked token +THEN within 60 seconds (the cache propagation window), ALL workers SHALL: + 1. Check their revocation cache + 2. If the token is in the cache as revoked, respond 401 + 3. If the token is NOT in the cache yet (slow propagation), query the database: + ```sql + SELECT revokedAt FROM embed_token WHERE id = ? LIMIT 1; + ``` + 4. If `revokedAt IS NOT NULL`, respond 401 and update the local cache + 5. Cache the revocation status for 60 seconds (TTL) +AND the response SHALL be 401 with: + ```json + { + "error": "token_revoked", + "message": "The provided token has been revoked" + } + ``` + +#### Scenario: 9.4 — Usage event written even for revoked token + +GIVEN a revoked token used after revocation +WHEN the render route returns 401 +THEN an `embed_usage_event` SHALL be written with: + ```json + { + "eventType": "pageView", + "responseStatusCode": 401, + "responseLatencyMs": 5, + "timestamp": "2026-05-22T14:36:30Z" + } + ``` +AND the admin can query the usage report: + "Token 'Gemeente Zeist WOO' was used 23 times AFTER revocation (2026-05-22 14:35–14:45)" +AND this helps forensic review of potential security incidents + +#### Scenario: 9.5 — Cache propagation guarantees + +GIVEN a render-route worker A and worker B +WHEN a token is revoked at T=0 +AND worker A immediately refreshes its cache from the database +AND worker B is busy and does not refresh for 50 seconds +THEN: + - Worker A rejects the token starting at T=1 second + - Worker B continues accepting the token until T=50 seconds + - At T=60 seconds, worker B's cache expires and it must query the database + - Worker B then rejects the token starting at T=61 seconds +AND the 60-second window bounds the maximum delay across all workers + +#### Scenario: 9.6 — Purge cache action for critical incidents + +GIVEN a critical incident (token compromised, attacker active) +WHEN an admin clicks "Purge cache" on the revoked token's detail page +THEN the API SHALL: + 1. Immediately invalidate all render-route worker caches for this token + 2. Send a broadcast message to all workers (Redis, AMQP, or similar): + ```json + { + "type": "token_cache_purge", + "tokenId": "token-id", + "timestamp": "2026-05-22T14:35:30Z" + } + ``` + 3. All workers receive the message and drop the token from their cache + 4. The next request with the revoked token queries the database and is rejected immediately +AND the response shows: + ``` + Cache purged. All render workers will immediately reject this token. + Purge initiated at 2026-05-22T14:35:30Z. + ``` + +#### Scenario: 9.7 — Re-issue (new token, revoke old) + +GIVEN an admin who has lost a token or wants to refresh it +WHEN they invoke the "Re-issue" action on the token +THEN the system SHALL: + 1. Generate a new JWT + 2. Create a new `embed_token` row with the same subject, scope, hostOrigins, etc. + 3. Revoke the old token (set revokedAt and revocationReason: "re-issued") + 4. Return the new JWT to the admin (shown once) +AND the old token is rejected starting immediately (cache expires within 60s, database rejects immediately) +AND subsequent integration uses the new token + +#### Scenario: 9.8 — Revocation audit trail + +GIVEN the audit log for a token +WHEN an admin reviews the token's history +THEN they SHALL see: + ``` + Audit Trail for Token "Gemeente Zeist WOO" + ├─ 2026-05-22T14:35:00Z — REVOKED by admin@gemeente.nl + │ Reason: no_longer_needed + │ Notes: Gemeente decided to move WOO tracking in-house + ├─ 2026-05-20T10:00:00Z — ACCESSED 342 times + │ Host origins: https://intranet.zeist.nl (340), https://www.zeist.nl (2) + ├─ 2026-05-15T09:30:00Z — CREATED by admin@gemeente.nl + │ Subject: widget / woo-widget + │ Scope: read, filters=[status, periode] + └─ (no further events) + ``` + +#### Scenario: 9.9 — Token state visibility + +GIVEN a list of all embed tokens in the admin UI +WHEN the admin views the token table +THEN each row SHALL display: + - Token name + - Status: [ACTIVE | REVOKED | EXPIRING SOON] + - Subject: (widget/dashboard name) + - Created: 2026-05-15 + - Last used: 2026-05-22 14:30 + - Revoked: (empty if active, or "2026-05-22 14:35" if revoked) + - Actions: [View] [Edit] [Re-issue] [Revoke] (or [Un-revoke] if revoked — soft-revoke only) + +#### Scenario: 9.10 — Soft revocation (can be undone) + +GIVEN a revoked token +WHEN an admin clicks "Undo revocation" (or "Un-revoke") +THEN the system SHALL: + 1. Clear the `revokedAt` and `revocationReason` fields + 2. Set `unrevokedAt` and `unrevokedBy` for audit + 3. Respond 200 with the token's updated state + 4. Send a notification to the token's creator +AND the token is immediately re-activated (cache expires, database accepts) +AND the full history (revocation + un-revocation) is auditable + +#### Scenario: 9.11 — Bulk revocation (future feature, out of scope) + +GIVEN multiple tokens that are no longer needed +WHEN an admin selects them and invokes "Revoke selected" (future v1.1 feature) +THEN all tokens are revoked in a single operation + (This is a note for future; not implemented in v1, but the schema supports bulk operations) + +#### Scenario: 9.12 — Revocation email notification + +GIVEN a token that was revoked +WHEN the revocation is confirmed +THEN an email SHALL be sent to the token's creator: + ``` + Subject: Token Revoked: Gemeente Zeist WOO + + Your embed token "Gemeente Zeist WOO" has been revoked. + + Revoked by: admin@gemeente.nl + Reason: no_longer_needed + Notes: Gemeente decided to move WOO tracking in-house + Revocation time: 2026-05-22 14:35 UTC + + If this was unexpected, contact the administrator. + ``` + +### Requirement: Embed tokens on the Sharing tab (REQ-EMB-011) + +The Sharing tab of a dashboard's settings SHALL hold "Embed on your website" for the dashboard's owner and administrators: a list of the dashboard's embed tokens with what they show (the whole dashboard or one widget), the allowed website, the state (Active with its views, or Revoked with the date and reason) and Withdraw; the code for the website of the selected token; and "Create new embed token". A new token SHALL be shown once with Copy and the note that it is not shown again. + +#### Scenario: Create a token + +- **WHEN** Pieter creates the token "Website Zuiddrecht" for the widget Open cases per case type and the site www.zuiddrecht.nl +- **THEN** the token is shown once with Copy, the table lists it as Active, and the code for the website shows the iframe diff --git a/openspec/specs/files-widget/screens.md b/openspec/specs/files-widget/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/files-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/files-widget/spec.md b/openspec/specs/files-widget/spec.md index 9956c584b..8f5871b8e 100644 --- a/openspec/specs/files-widget/spec.md +++ b/openspec/specs/files-widget/spec.md @@ -29,7 +29,6 @@ At least one of `folderPath` or `fileId` MUST be present so the placement always ## Requirements -@e2e exclude all scenarios test PHP file listing/upload/delete endpoints — requires Nextcloud Files ACL setup beyond the test fixture ### Requirement: REQ-FLS-001 Widget registration @@ -39,7 +38,7 @@ The system MUST register a LaunchPad dashboard widget with id `launchpad_files` - GIVEN the files-widget capability is installed and enabled - WHEN a user opens the LaunchPad widget picker dialog -- THEN the `launchpad_files` widget MUST appear in the list with a title (e.g., "Files") and an icon +- THEN the Files widget (widget type `files`) MUST appear in the list with a title (e.g., "Files") and an icon - AND the widget MUST be selectable for placement on a dashboard #### Scenario: Multiple instances allowed @@ -53,9 +52,10 @@ The system MUST register a LaunchPad dashboard widget with id `launchpad_files` - GIVEN the widget is registered - WHEN Nextcloud cache is cleared or the app is reloaded -- THEN the `launchpad_files` widget MUST still be discoverable in the picker +- THEN the Files widget (widget type `files`) MUST still be discoverable in the picker #### Scenario: Widget registration includes metadata +@e2e exclude never built: no `OCP\Dashboard\IWidget` with id `launchpad_files` exists in lib/ (git log --all -S launchpad_files touches only openspec/ and docs), so `GET /api/widgets` has no such entry to carry id, title, icon_url or v2 support; the files type is a frontend registry entry (displayName and icon in @conduction/nextcloud-vue CnFilesWidget/index.js), and no unit test in this repository pins that metadata - GIVEN the widget is registered - WHEN the widget picker fetches widget metadata @@ -140,6 +140,7 @@ The system MUST expose `GET /api/widgets/files/{placementId}/contents?cursor=&li - NOTE: Cursor implementation is opaque to the frontend; the backend may use file ID offsets, timestamps, or other strategies #### Scenario: Permission-aware item listing +@e2e exclude needs per-file read rights inside one folder (an unreadable sibling next to readable ones), which plain Nextcloud sharing cannot express and the CI fixture has no ACL app (groupfolders advanced permissions) for; pinned by tests/Unit/Service/FilesWidgetServiceTest.php::testUnreadableChildrenAreSilentlyOmitted and ::testBuildFileMetadataSurfacesPermissionFlags - GIVEN a folder with files: A (user can read), B (user cannot read), C (user can read, can edit), D (user can read, can delete) - WHEN the user fetches folder contents @@ -188,6 +189,7 @@ The system MUST enforce view-time permission checks: only files and folders the - AND the widget MUST gracefully show the access-denied empty state #### Scenario: Mixed permissions within folder +@e2e exclude needs a subfolder the viewer cannot read inside a folder they can, which plain Nextcloud sharing cannot express and the CI fixture has no ACL app (groupfolders advanced permissions) for; pinned by tests/Unit/Service/FilesWidgetServiceTest.php::testUnreadableChildrenAreSilentlyOmitted - GIVEN a folder with a subfolder that the user cannot read - AND other files in the main folder that the user can read @@ -263,6 +265,7 @@ When a user clicks on a file, the widget MUST open the standard Nextcloud file v - AND the breadcrumb and contents MUST update #### Scenario: Deep-link preserves file context +@e2e exclude previewing and editing an .xlsx in the Files app needs an office suite (Collabora or OnlyOffice), which the CI fixture does not provide; the deep link itself and the Files app opening the file by id are asserted by click-file-to-open-in-files-app in tests/e2e/files-widget-navigation.spec.ts, and no unit test covers the Files app side - GIVEN a file `/Documents/Marketing/budget.xlsx` with fileId `555` - WHEN the user clicks it in the widget @@ -288,6 +291,13 @@ When `allowUpload = true` AND the viewer has write permission on the folder, an - WHEN the widget renders - THEN the "Upload" button MUST NOT appear +#### Scenario: Upload is off by default + +- GIVEN a placement whose content has no `allowUpload` at all +- AND the viewer can write to the folder +- WHEN the widget renders +- THEN the "Upload" button MUST NOT appear, because upload is off until the author switches it on (Ruben, 21 Nov 2026) + #### Scenario: Drag-drop upload multiple files - GIVEN the upload zone is visible @@ -430,6 +440,7 @@ The system MUST support MIME type filtering (empty filter = all files) and multi - AND each row MUST be clickable (file → deep-link; folder → navigate) #### Scenario: Grid mode with thumbnails +@e2e exclude a video thumbnail needs ffmpeg and the Movie preview provider, neither of which the CI fixture enables, so the video clause cannot pass there; the image-thumbnail half is asserted in grid mode by config-for-thumbnails in tests/e2e/files-widget.spec.ts, the backend half (thumbnailUrl only when a preview provider exists) by tests/Unit/Service/FilesWidgetServiceTest.php::testBuildFileMetadataEmitsThumbnailWhenPreviewAvailable and ::testBuildFileMetadataOmitsThumbnailWhenNoPreview - GIVEN a placement with `viewMode: 'grid'` and `showThumbnails: true` - AND the folder contains: image.png, document.pdf, video.mp4 @@ -446,6 +457,7 @@ The system MUST support MIME type filtering (empty filter = all files) and multi - AND the grid MUST load faster (no thumbnail rendering) #### Scenario: Tree mode hierarchical display +@e2e exclude never built: no collapsible tree exists in the renderer (@conduction/nextcloud-vue CnFilesWidget.vue `viewMode` maps 'tree' to the list layout, "Tree navigation is not implemented"), and no unit test pins a tree - GIVEN a placement with `viewMode: 'tree'` - AND the folder structure: `root/ > docs/ > 2024/ > [files]` and `root/ > images/ > [files]` diff --git a/openspec/specs/first-time-setup/screens.md b/openspec/specs/first-time-setup/screens.md new file mode 100644 index 000000000..5402d8760 --- /dev/null +++ b/openspec/specs/first-time-setup/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpInstellen https://identity.conduction.nl/screens/board?id=launchpad/LpInstellen diff --git a/openspec/specs/first-time-setup/spec.md b/openspec/specs/first-time-setup/spec.md new file mode 100644 index 000000000..c73d3bf7c --- /dev/null +++ b/openspec/specs/first-time-setup/spec.md @@ -0,0 +1,54 @@ +# first-time-setup Specification + +## Purpose +The first-time setup wizard gets a new LaunchPad installation to a working state. The operator picks an example dataset on a card and loads it from that card, and the setup status reports every step the manifest declares. This capability defines those steps and what the server accepts and refuses while running them. + +## Requirements + +### Requirement: Each example data card loads itself + +The `demo-data` setup step MUST be a cards choice step with `loadAction: load-demo-data`. The setup wizard MUST NOT carry a separate run-action step that loads the picked dataset. + +#### Scenario: The operator loads a dataset from its card + +- GIVEN the setup wizard shows the example data cards +- WHEN the operator presses Load on a card +- THEN the wizard posts `{ "dataset": <card value> }` to `/api/setup/action/load-demo-data` +- AND the server loads that dataset +- AND the server records the dataset as the pick only after the load succeeds +- @e2e exclude the card and its spinner are CnSetupWizard UI, tested in nextcloud-vue; the posted body is covered by tests/Unit/Controller/SetupControllerTest.php + +#### Scenario: An unknown dataset is refused + +- GIVEN a dataset id that no card offers +- WHEN it is posted to `/api/setup/action/load-demo-data` +- THEN the server answers 400 with `success: false` +- AND nothing is loaded or stored +- @e2e tests/e2e/spec-coverage/demo-data-setup-step.spec.ts + +#### Scenario: A call without a body keeps working + +- GIVEN a dataset was stored through `/api/setup/config` +- WHEN `/api/setup/action/load-demo-data` is called without a body +- THEN the stored dataset is loaded +- @e2e tests/e2e/spec-coverage/demo-data-setup-step.spec.ts + +#### Scenario: A failed load leaves the step open + +- GIVEN the load of the posted dataset fails +- WHEN the server answers +- THEN the answer carries `success: false` +- AND no pick or decision is stored +- @e2e exclude needs a load that fails on a live instance; covered by tests/Unit/Controller/SetupControllerTest.php + +### Requirement: Setup status reports every manifest step + +`GET /api/setup/status` MUST report a `done` state for every step id in `manifest.setup.steps`. + +#### Scenario: The status ids match the manifest + +- GIVEN the LaunchPad manifest +- WHEN an administrator reads `/api/setup/status` +- THEN `steps` holds an entry for every manifest step id +- AND the retired load step is not reported +- @e2e tests/e2e/spec-coverage/demo-data-setup-step.spec.ts diff --git a/openspec/specs/footer-customization/screens.md b/openspec/specs/footer-customization/screens.md new file mode 100644 index 000000000..fc1e6b143 --- /dev/null +++ b/openspec/specs/footer-customization/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpBeheerNavigatie https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerNavigatie diff --git a/openspec/specs/footer-customization/spec.md b/openspec/specs/footer-customization/spec.md index d389a5150..aa076a845 100644 --- a/openspec/specs/footer-customization/spec.md +++ b/openspec/specs/footer-customization/spec.md @@ -11,8 +11,6 @@ Footer Customization provides per-instance branding, legal disclaimers, and cont ## Data Model -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Admin Footer Settings (oc_launchpad_admin_settings extended) Settings are stored as key-value pairs: @@ -308,6 +306,7 @@ Footer content MUST support language-tagged variants. The footer renderer MUST s - THEN the UI MUST show tabs for each language variant (e.g., "English", "Dutch") - AND the admin can edit and preview each variant independently - NOTE: This is a UI requirement; spec does not mandate exact UI behavior, only that variants can be configured and rendered correctly +@e2e exclude never built: LaunchPad has no footer settings tab or language-variant editor (nothing in src/ calls /api/admin/footer-settings; `git log --all -S footerHtml -- src` and `-S footer-settings -- src` find no commit), so there is no control to drive; no Vitest test exists either ### Requirement: REQ-FTR-008 Print Support and CSS @@ -338,8 +337,8 @@ The footer MUST use Nextcloud theme colors by default, with optional admin overr #### Scenario: Footer inherits theme colors - GIVEN `footer_background_color = NULL` and `footer_text_color = NULL` (not overridden) - WHEN the page renders with NC theme (e.g., dark theme) -- THEN the footer background MUST use the NC theme's primary background colour (CSS var `--primary-background-color`) -- AND the footer text MUST use the NC theme's primary text colour (CSS var `--primary-text-color`) +- THEN the footer background MUST use the NC theme's main background colour (CSS var `--color-main-background`) +- AND the footer text MUST use the NC theme's main text colour (CSS var `--color-main-text`) #### Scenario: Admin overrides footer colors - GIVEN the admin sets `footer_background_color = "#1a1a1a"` and `footer_text_color = "#ffffff"` diff --git a/openspec/specs/grid-layout/screens.md b/openspec/specs/grid-layout/screens.md new file mode 100644 index 000000000..a5caf0988 --- /dev/null +++ b/openspec/specs/grid-layout/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpMobiel https://identity.conduction.nl/screens/board?id=launchpad/LpMobiel +- LpBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpBewerken diff --git a/openspec/specs/grid-layout/spec.md b/openspec/specs/grid-layout/spec.md index 031c5bd2f..0ea361c0d 100644 --- a/openspec/specs/grid-layout/spec.md +++ b/openspec/specs/grid-layout/spec.md @@ -67,7 +67,6 @@ The grid MUST initialize with the correct configuration when a dashboard is load ### Requirement: Drag to Reposition (REQ-GRID-002) Users MUST be able to drag widgets to new positions on the grid in edit mode. -@e2e exclude drag-to-reposition requires live GridStack drag events — fragile in headless Playwright; composite regression covered by wave3 runtime-shell tests #### Scenario: Drag a widget to a new position - GIVEN the dashboard is in edit mode @@ -107,7 +106,6 @@ Users MUST be able to drag widgets to new positions on the grid in edit mode. ### Requirement: Resize by Edge Dragging (REQ-GRID-003) Users MUST be able to resize widgets by dragging their edges or corners in edit mode. -@e2e exclude resize-by-edge requires live GridStack resize events — same fragility as REQ-GRID-002 #### Scenario: Resize a widget horizontally - GIVEN the dashboard is in edit mode @@ -182,7 +180,6 @@ The grid MUST support two distinct interaction modes controlled by the `editMode ### Requirement: Position Persistence (REQ-GRID-005) Grid position changes MUST be communicated to the parent component for API persistence. -@e2e exclude position persistence tested via Vue composable event-emit — not directly observable in Playwright without mock #### Scenario: Save after grid change - GIVEN the user drags a widget to a new position @@ -202,7 +199,7 @@ Grid position changes MUST be communicated to the parent component for API persi - WHEN the failure is detected - THEN the system MUST display an error notification - AND the system MUST retry the save automatically (up to 3 retries) -- NOTE: Save failure/retry is NOT currently implemented in the frontend. +- AND a newer layout save MUST replace the pending retries of an older one #### Scenario: Concurrent edits from multiple tabs - GIVEN user "alice" has the same dashboard open in two browser tabs @@ -217,50 +214,60 @@ Grid position changes MUST be communicated to the parent component for API persi - THEN each grid item's `id` MUST be matched to a placement's `id` via string comparison - AND the placement's gridX, gridY, gridWidth, gridHeight MUST be updated from the grid item's x, y, w, h values -### Requirement: Widget Auto-Layout — collision placement algorithm (REQ-GRID-006) +### Requirement: REQ-GRID-006 Widget Auto-Layout (bottom-append placement) -When a new widget is added to an existing dashboard, the system MUST place it without overlapping any existing widget and without leaving it outside the visible grid region. The algorithm MUST be: -@e2e exclude auto-layout collision algorithm tests composable internal math — Vitest unit scope; browser outcome covered by REQ-GRID-001 init test +When a new widget is added to a dashboard, the system MUST place it in a fresh row directly below all existing widgets, without overlapping any existing widget and without moving any existing widget. The algorithm MUST be: -1. **Try GridStack auto-position** — call `grid.addWidget({x: 0, y: 0, w: newW, h: newH, autoPosition: true, ...})`. GridStack scans for the first empty rectangle that fits and uses it. -2. **Fallback: top-left with push-down** — if step 1 fails (GridStack returns no slot, or the picked slot is below `viewportRows`), place the new widget at `(x: 0, y: 0)` with size `(newW, newH)` AND for every existing widget whose rectangle overlaps `[0..newW] × [0..newH]`, set its `gridY` to `newH` (pushing it just below the new one). Existing widgets that do not overlap MUST NOT be moved. +1. **Compute the bottom edge** — for every existing placement compute `gridY + gridHeight`; the new widget's `y` MUST be the maximum of these values (the lowest occupied bottom edge). A placement missing `gridY` contributes `0`; a placement missing `gridHeight` contributes height `1`. +2. **Anchor to the left** — the new widget's `x` MUST be `0`. +3. **Empty dashboard** — when there are no existing placements, the new widget MUST be placed at `(x: 0, y: 0)`. -Default size when the caller omits `w`/`h` MUST be `w=4, h=4`. Position writes MUST trigger the persistence path of REQ-GRID-005. +Existing widgets MUST NOT be moved — there is no push-down — and the helper's `pushed` array MUST always be empty. Default size when the caller omits `w`/`h` MUST be `w=4, h=4`. Position writes MUST trigger the persistence path of REQ-GRID-005. -#### Scenario: Auto-position into empty space +This requirement deliberately replaces the former "GridStack auto-position + top-left/push-down fallback" rule, which reordered the user's existing layout on every add once the visible rows filled up. The shipped `placeNewWidget(spec, placements, options?)` helper implements bottom-append; this requirement is the authoritative description of that behaviour. + +#### Scenario: Append below the only existing widget - **GIVEN** a dashboard with one widget at `(x:0, y:0, w:6, h:4)` - **WHEN** a new 4×4 widget is added -- **THEN** GridStack MUST place it at `(x:6, y:0)` (the empty right-half) +- **THEN** it MUST be placed at `(x:0, y:4)` (a fresh row below the existing widget) +- **AND** the existing widget MUST NOT be moved +- **AND** the returned `pushed` array MUST be empty + +#### Scenario: Append below the lowest widget regardless of array order + +- **GIVEN** a dashboard with widgets at `(x:0, y:5, w:6, h:3)` (bottom edge `8`) and `(x:6, y:0, w:6, h:2)` (bottom edge `2`) +- **WHEN** a new 6×3 widget is added +- **THEN** it MUST be placed at `(x:0, y:8)` (below the lowest bottom edge, not below the last array entry) - **AND** no existing widget MUST be moved -#### Scenario: Push-down fallback when grid is full at top +#### Scenario: First widget on an empty dashboard -- **GIVEN** a dashboard with widgets occupying the entire `[0..12] × [0..4]` region +- **GIVEN** a dashboard with no widgets - **WHEN** a new 4×4 widget is added -- **THEN** it MUST be placed at `(x:0, y:0, w:4, h:4)` -- **AND** every previously-overlapping widget MUST have `gridY = 4` (just below the new one) -- **AND** non-overlapping widgets (already at `y >= 4`) MUST NOT have their `gridY` changed +- **THEN** it MUST be placed at `(x:0, y:0)` + +#### Scenario: Existing widgets are never pushed when the top region is full + +- **GIVEN** a dashboard whose `[0..12] × [0..4]` region is fully occupied +- **WHEN** a new 4×4 widget is added +- **THEN** it MUST be placed at `(x:0, y:4)`, below the occupied region +- **AND** every existing widget MUST retain its original `gridX`, `gridY`, `gridWidth`, and `gridHeight` +- **AND** the returned `pushed` array MUST be empty #### Scenario: Default size on omitted dimensions - **GIVEN** a caller invokes `placeNewWidget({type: 'text'})` with no `w` or `h` - **WHEN** the placement runs - **THEN** the placement MUST use `w=4, h=4` +- **AND** the `y` coordinate MUST still be the lowest occupied bottom edge (`0` on an empty dashboard) #### Scenario: Persistence after placement -- **GIVEN** a new widget has been placed (via either step 1 or step 2) +- **GIVEN** a new widget has been placed - **WHEN** the placement completes -- **THEN** the new widget AND any pushed-down widgets MUST be persisted via the standard placement-update API (REQ-WDG-008 batch update or per-placement PUT) -- **AND** a single network round-trip SHOULD be used for the batch (debounce 300 ms per the design rule in `openspec/config.yaml`) - -#### Scenario: Pushed widgets remain within their column lane - -- **GIVEN** existing widget at `(x:8, y:0, w:4, h:2)` overlaps a new 6×3 widget being placed at top-left -- **WHEN** the push-down fallback runs -- **THEN** the existing widget's `gridX` and `gridW` MUST remain `8` and `4` respectively -- **AND** only `gridY` MUST be increased to `3` +- **THEN** the new widget MUST be persisted via the standard placement-update API (REQ-WDG-008 batch update or per-placement PUT) +- **AND** because no existing widget is moved, only the new widget's position needs to be written #### Scenario: Add widget to partially filled grid (incremental render) - GIVEN the grid has widgets occupying rows 0-2 in columns 0-8 @@ -278,16 +285,17 @@ Default size when the caller omits `w`/`h` MUST be `w=4, h=4`. Position writes M ### Requirement: Grid Responsiveness — concrete breakpoints (REQ-GRID-007) -The GridStack instance MUST be initialised with `columnOpts.breakpoints` containing exactly four entries, each `{w: <viewportWidthPx>, c: <columnCount>}`, applied in descending viewport order: +The GridStack instance MUST be initialised with `columnOpts.breakpoints` containing exactly three entries, each `{w: <viewportWidthPx>, c: <columnCount>}`, applied in descending viewport order: | Viewport width >= | Column count | |---|---| | 1400 px | 12 | | 1100 px | 8 | | 768 px | 4 | -| 480 px | 1 | -`columnOpts.layout` MUST be set to `'moveScale'` so widgets scale proportionally when the column count changes (rather than wrapping or collapsing). Below the smallest entry the smallest column count (1) MUST apply. +Below the smallest entry the smallest column count (4) MUST apply, so a phone keeps four columns (board LpMobiel: app tiles four to a row). + +`columnOpts.layout` MUST move and scale widgets proportionally when the column count changes between wider grids. On a grid of four columns or fewer it MUST lay the widgets out in reading order instead: an app tile (one cell wide in the wider layout) belongs to the nearest section heading above it whose columns it falls in, tiles take one cell each and flow as many to a row as fit, and every other widget takes a full row. The grid MUST also adapt to the container width while maintaining the active column count: column widths recalculate proportionally on resize, widget positions remain in their grid coordinates, and no widget content overflows its cell boundaries. @@ -305,19 +313,20 @@ The grid MUST also adapt to the container width while maintaining the active col - THEN GridStack MUST proportionally rescale widget widths via `moveScale` - AND a widget originally `{x: 0, w: 6}` (half) MUST become approximately `{x: 0, w: 4}` (still half, in the 8-col grid) -#### Scenario: Single-column on mobile +#### Scenario: App tiles four to a row on a phone -- GIVEN viewport width is 480 px +- GIVEN viewport width is 390 px +- AND the dashboard has the heading "My apps" over six one-cell app tiles, and a clock beside it - WHEN the workspace renders -- THEN the grid MUST use 1 column -- AND every widget MUST occupy the full row width -- AND widgets MUST stack vertically +- THEN the grid MUST use 4 columns +- AND "My apps" MUST take a full row with its six tiles under it, four in the first row and two in the next +- AND the clock MUST take a full row after the tiles #### Scenario: Below smallest breakpoint -- GIVEN viewport width is 320 px (below the 480 entry) +- GIVEN viewport width is 320 px (below the 768 entry) - WHEN the workspace renders -- THEN the grid MUST use the column count of the smallest matching breakpoint (1 column) +- THEN the grid MUST use the column count of the smallest matching breakpoint (4 columns) #### Scenario: Grid fills container width - GIVEN the dashboard container is 1200px wide at the 8-column breakpoint @@ -333,7 +342,6 @@ The grid MUST also adapt to the container width while maintaining the active col ### Requirement: Grid Accessibility (REQ-GRID-008) The grid MUST support keyboard navigation and screen reader compatibility. -@e2e exclude grid accessibility (Tab focus ordering, ARIA roles) requires pre-seeded placements and screen reader emulation — Vitest axe scope #### Scenario: Keyboard navigation between widgets - GIVEN the dashboard is in view mode @@ -341,6 +349,7 @@ The grid MUST support keyboard navigation and screen reader compatibility. - THEN focus MUST move sequentially through widget placements - AND each focused widget MUST have a visible focus indicator - NOTE: Keyboard navigation is NOT currently implemented. +@e2e exclude never built: view-mode Tab stops are deliberately omitted, CnDashboardGrid sets `tabindex` only while `keyboardActive` (keyboardRepositioning && editable && !reflowed, @conduction/nextcloud-vue 2.203.0 CnDashboardGrid.vue `itemTabindex`); edit-mode Tab order and focus ring are cited under grid-item-is-keyboard-focusable (tests/e2e/grid-layout-keyboard.spec.ts) #### Scenario: Keyboard widget movement in edit mode - GIVEN the dashboard is in edit mode @@ -348,6 +357,7 @@ The grid MUST support keyboard navigation and screen reader compatibility. - WHEN the user presses Arrow keys while holding a modifier key (e.g., Ctrl+Arrow) - THEN the widget MUST move one grid cell in the arrow direction - NOTE: Keyboard movement is NOT currently implemented. +@e2e exclude never built: Ctrl+Arrow is not a binding, CnDashboardGrid's item keydown returns early on any Alt/Ctrl/Meta modifier (@conduction/nextcloud-vue 2.203.0 CnDashboardGrid.vue); keyboard movement shipped instead as REQ-GRID-KBD-002 (plain arrows, Shift+arrows), cited under nudging-position-with-arrow-keys and resizing-with-shiftarrow-keys #### Scenario: Screen reader announces widget positions - GIVEN a screen reader is active @@ -358,7 +368,6 @@ The grid MUST support keyboard navigation and screen reader compatibility. ### Requirement: Tile vs Widget Rendering (REQ-GRID-009) The grid MUST distinguish between tile placements and widget placements for rendering. -@e2e exclude tile vs widget rendering dispatch tests WidgetWrapper prop-threading — Vitest component scope; browser manifestation covered by tiles and widgets specs #### Scenario: Tile placement renders TileWidget - GIVEN a placement with `tileType: "custom"` and inline tile data (tileTitle, tileIcon, etc.) @@ -390,27 +399,28 @@ The grid MUST distinguish between tile placements and widget placements for rend ### Requirement: Grid Styling (REQ-GRID-010) The grid MUST apply consistent visual styling to all grid items. -@e2e exclude grid CSS styling (backdrop-filter, border-radius, placeholder colours) tests computed styles at pixel level — visual regression / Vitest snapshot scope #### Scenario: Grid item content styling - GIVEN a grid item is rendered - WHEN the item is displayed - THEN `.grid-stack-item-content` MUST have: background blur via `backdrop-filter`, large border radius via `--border-radius-large`, and `overflow: hidden` +@e2e exclude pixel-level CSS (backdrop-filter, border-radius) — visual styling, no unit test pins it; the scoped rule is in src/views/Views.vue `.launchpad-container :deep(.grid-stack-item-content)` #### Scenario: Placeholder styling during drag - GIVEN the user is dragging a widget in edit mode - WHEN a placeholder appears showing the drop target - THEN `.grid-stack-placeholder > .placeholder-content` MUST have: a primary element light background and a 2px dashed border in primary color with large border radius +@e2e exclude pixel-level CSS of GridStack's drag placeholder — visual styling only; no unit test pins it #### Scenario: Placement key regeneration - GIVEN a widget placement is updated (e.g., style change) - WHEN the grid re-renders - THEN the placement key MUST include the `updatedAt` timestamp and `styleConfig` hash to force re-rendering via `getPlacementKey()` +@e2e exclude Vue render key, not observable in the browser; the shipped key is the bare id (src/views/Views.vue placementItemKey, pinned by src/views/__tests__/ViewsPlacementActions.spec.js "keys a placement by its id as text") so this scenario's updatedAt/styleConfig key is stale ### Requirement: Grid Synchronization (REQ-GRID-011) The grid MUST stay synchronized with the placements prop when items are added or removed externally. -@e2e exclude grid sync uses Vue watcher + nextTick internals — observable as DOM behaviour but requires complex timing; covered by Vitest #### Scenario: New placement added to props - GIVEN the placements array receives a new placement via the parent component @@ -427,11 +437,11 @@ The grid MUST stay synchronized with the placements prop when items are added or - GIVEN the DashboardGrid component is about to be destroyed - WHEN `beforeDestroy` lifecycle hook fires - THEN `grid.destroy(false)` MUST be called (false = do not remove DOM elements) +@e2e exclude component lifecycle internal to nextcloud-vue CnDashboardGrid (unmount calls grid.destroy(false)); nothing to observe in the browser and no LaunchPad test pins it ### Requirement: Cell geometry constants (REQ-GRID-012) The grid MUST be initialised with `cellHeight: 60` (px) and `margin: 8` (px). These constants MUST live in a single shared module exported from the grid composable, not duplicated in component templates. -@e2e exclude cell geometry constants are source-code assertions; grep + import checks cannot be driven from Playwright #### Scenario: Cell height read from constant @@ -439,12 +449,14 @@ The grid MUST be initialised with `cellHeight: 60` (px) and `margin: 8` (px). Th - WHEN any other module needs the cell height (e.g. for collision math or CSS calc) - THEN it MUST import the constant - AND grep for hardcoded `60` in grid contexts MUST return only the composable definition +@e2e exclude source-code import/grep assertion; pinned by src/composables/__tests__/useGridManager.spec.js ("CELL_HEIGHT is 60 px") #### Scenario: 12-col, 60px, 8px margin renders predictable height - GIVEN a widget with `gridHeight: 4` is placed - WHEN it renders at the 12-column breakpoint -- THEN its DOM height MUST be `(4 * 60) + (3 * 8) = 264 px` (4 rows + 3 inter-row margins) +- THEN its grid item MUST be `4 * 60 = 240 px` tall (GridStack sizes an item `gridHeight * cellHeight`) +- AND its content MUST be inset by the 8 px margin on each side, so the gap between two stacked widgets is 16 px ### Requirement: GridStack version pin (REQ-GRID-013) @@ -461,7 +473,7 @@ The system MUST pin `gridstack` to a major version that supports `columnOpts.bre ### Requirement: Placement helper is the single placement authority (REQ-GRID-014) All "add widget" code paths (toolbar dropdown, keyboard shortcut, drag-from-picker) MUST go through a single `placeNewWidget(spec)` helper exported from the grid composable. Inline calls to `grid.addWidget` outside this helper are forbidden. -@e2e exclude single placement authority is a source-code grep assertion — cannot be driven from Playwright +@e2e exclude source-code structure (which module calls grid.addWidget / placeNewWidget), not browser behaviour; pinned by the grep guard in src/composables/__tests__/useGridManager.spec.js and by src/stores/__tests__/dashboard.golden.spec.js; the placement outcome is cited under REQ-GRID-006 #### Scenario: Single source of truth @@ -477,6 +489,76 @@ All "add widget" code paths (toolbar dropdown, keyboard shortcut, drag-from-pick - **THEN** it MUST call `placeNewWidget(spec)` exported from `useGridManager.js` - **AND** MUST NOT call `grid.addWidget(...)` directly +### Requirement: REQ-GRID-KBD-001 Grid items expose an accessible role and name + +Every rendered grid item MUST carry `role="group"`, a computed +`aria-label` describing the widget (e.g. "Widget: {title}"), and +`tabindex="0"` so it is reachable via sequential keyboard navigation +(`Tab`/`Shift+Tab`) and announced by assistive technology as a distinct, +named unit. + +#### Scenario: Grid item is keyboard-focusable + +- **GIVEN** a dashboard with 3 widget placements in edit mode +- **WHEN** a keyboard user presses `Tab` repeatedly from the canvas +- **THEN** focus MUST land on each grid item in turn +- **AND** each focused item MUST have a visible focus indicator + +#### Scenario: Screen reader announces the widget + +- **GIVEN** a grid item wrapping a widget titled "Team Announcements" +- **WHEN** a screen reader user focuses the item +- **THEN** it MUST announce a group with the accessible name "Widget: + Team Announcements" (or the tile-equivalent label for tile placements) + +### Requirement: REQ-GRID-KBD-002 Keyboard-operable move and resize + +Any user MUST be able to reposition or resize a focused widget placement +using only the keyboard, producing the same `gridX`/`gridY`/`gridWidth`/ +`gridHeight` outcome a mouse drag would produce, including respecting the +existing minimum size (`gs-min-w`/`gs-min-h` = 2) and existing collision/ +push behaviour. + +#### Scenario: Opening the move panel via keyboard + +- **GIVEN** a grid item has keyboard focus +- **WHEN** the user presses `Enter` or `Space` +- **THEN** the same panel/menu reachable via right-click MUST open +- **AND** a "Move" action MUST be present in that panel/menu + +#### Scenario: Nudging position with arrow keys + +- **GIVEN** the move panel is open for a widget at `gridX=2, gridY=3` +- **WHEN** the user presses `ArrowRight` +- **THEN** the pending position MUST become `gridX=3, gridY=3` +- **AND** the change MUST NOT be persisted until the user confirms + +#### Scenario: Resizing with Shift+arrow keys + +- **GIVEN** the move panel is open for a widget at `gridWidth=3, + gridHeight=2` +- **WHEN** the user presses `Shift+ArrowRight` +- **THEN** the pending size MUST become `gridWidth=4, gridHeight=2` +- **AND** the size MUST NOT shrink below the existing 2-cell minimum in + either dimension + +#### Scenario: Confirming and cancelling + +- **GIVEN** the move panel is open with a pending position/size change +- **WHEN** the user presses `Enter` +- **THEN** the placement MUST be updated via the same persistence path + drag-and-drop already uses +- **WHEN** instead the user presses `Escape` +- **THEN** no change MUST be persisted and the panel MUST close + +#### Scenario: Collisions are resolved the same way as drag + +- **GIVEN** a keyboard-driven move would overlap an existing placement +- **WHEN** the user confirms the move +- **THEN** the system MUST apply the same collision/push resolution + `placeNewWidget()` already applies for drag-and-drop moves — no widget + MUST silently overlap another after confirmation + ## Non-Functional Requirements - **Performance**: Grid initialization MUST complete within 500ms for dashboards with up to 30 widget placements. Drag and resize interactions MUST maintain 60fps with no visible lag. @@ -493,7 +575,7 @@ All "add widget" code paths (toolbar dropdown, keyboard shortcut, drag-from-pick - REQ-GRID-003 (Resize by Edge Dragging): Resize controlled via `disableResize: !this.editMode`. Min sizes via `gs-min-w="2"`, `gs-min-h="2"`. - REQ-GRID-004 (View Mode vs Edit Mode): `editMode` prop controls grid state. - REQ-GRID-005 (Position Persistence): `handleGridChange()` emits `update:placements` on every change event. -- REQ-GRID-006 (Widget Auto-Layout — collision placement algorithm): `placeNewWidget()` in `src/composables/useGridManager.js` computes the position via the autoPosition primary path and the top-left + push-down fallback; `syncGridItems()` then renders the new placement via `grid.makeWidget()`. Push-down side effects flow through the existing `updatePlacements` batch path. +- REQ-GRID-006 (Widget Auto-Layout — collision placement algorithm): `placeNewWidget()` in `src/composables/useGridManager.js` appends the new widget at the bottom: `x = 0`, `y = max(gridY + gridHeight)` over the existing placements, `(0, 0)` on an empty dashboard, and no existing widget moves (`pushed` is always empty); `syncGridItems()` then renders the new placement via `grid.makeWidget()`. - REQ-GRID-009 (Tile vs Widget Rendering): `isTilePlacement()`, `getTileData()` handle rendering distinction. - REQ-GRID-010 (Grid Styling): CSS applied via scoped styles with deep selectors. - REQ-GRID-011 (Grid Synchronization): `placements` watcher triggers `syncGridItems()`. diff --git a/openspec/specs/groupfolder-storage-backend/screens.md b/openspec/specs/groupfolder-storage-backend/screens.md new file mode 100644 index 000000000..513d5ce62 --- /dev/null +++ b/openspec/specs/groupfolder-storage-backend/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Ingetrokken: deze opslag is nooit in de app aangesloten. diff --git a/openspec/specs/groupfolder-storage-backend/spec.md b/openspec/specs/groupfolder-storage-backend/spec.md index 7540bb8ec..0967ba8d3 100644 --- a/openspec/specs/groupfolder-storage-backend/spec.md +++ b/openspec/specs/groupfolder-storage-backend/spec.md @@ -67,16 +67,10 @@ factory was reachable only through the three orphaned facade methods. The `launchpad.content_storage` admin setting, `AdminSettingKey::CONTENT_STORAGE`, `SetupWizardService::{getContentStorage,setContentStorage,hasGroupfolderApp}`, `AdminController::setWizardStorage`, its route, and step 2 of the setup wizard -are **retained**. They belong to the `setup-wizard` capability, which *writes* -the setting; this capability was the *reader*. The setting was already inert -before this change — nothing read it, because the readers were orphaned — so -removing the reader does not make it worse. - -Retiring the wizard step is a separate, reviewable decision that changes the -`setup-wizard` spec, and it is tracked on launchpad#87 rather than folded into -this retirement. Anyone completing that follow-up should note that -`tools/spec-annotations-allowlist.txt` carries entries for those three -`SetupWizardService` methods and for `AdminController::setWizardStorage`. +were retained by this retirement, because they belonged to the `setup-wizard` +capability. They were removed afterwards, on 9 Oct 2026, by the change +`retire-setup-wizard-storage-step` (decision 131). A `content_storage` row +already stored stays in the table, unread. `lib/Migration/Version002001Date20260603000000.php` and `DashboardTableBuilder::addContentStorageColumns()` are also retained: a shipped @@ -85,7 +79,25 @@ instances that have already run it. The new migration drops what it added. ## Requirements -None. This capability has no requirements; it is withdrawn. Its original +### Requirement: Dashboards are stored in the database only (REQ-GFSB-011) + +LaunchPad SHALL keep a dashboard's layout in its `WidgetPlacement` rows only. It SHALL NOT offer a storage backend +choice, a GroupFolder backend, or the `launchpad:storage:*` commands, and the dashboard response SHALL NOT carry a +`content` key. + +#### Scenario: No storage commands + +- **GIVEN** LaunchPad is installed +- **WHEN** an administrator lists the `occ` commands +- **THEN** no `launchpad:storage:migrate-to-groupfolder` or storage toggle command is listed + +#### Scenario: A dashboard has no content blob + +- **GIVEN** a dashboard with widgets +- **WHEN** it is read through `GET /api/dashboards` +- **THEN** its widgets come from its placements and the dashboard has no `content` key + +This is the only requirement; the capability is otherwise withdrawn. Its original requirements REQ-GFSB-001 through REQ-GFSB-010 and their 35 scenarios are preserved in the archived change at `openspec/changes/archive/2026-06-14-groupfolder-storage-backend/`, and the diff --git a/openspec/specs/header-widget/screens.md b/openspec/specs/header-widget/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/header-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/header-widget/spec.md b/openspec/specs/header-widget/spec.md index 7b6c23eff..72121a079 100644 --- a/openspec/specs/header-widget/spec.md +++ b/openspec/specs/header-widget/spec.md @@ -35,13 +35,12 @@ Header placements reuse `oc_launchpad_widget_placements.content` (JSON). The `co ### Requirement: REQ-HDR-001 Widget registration The system MUST register a LaunchPad dashboard widget with id `launchpad_header` via `OCP\Dashboard\IManager::registerWidget()` so it appears in the widget picker alongside other Nextcloud dashboard widgets. -@e2e exclude widget registration tests OCP\Dashboard\IManager registration — observed by widget appearing in picker; covered by generic widgets-in-picker test #### Scenario: Widget appears in picker - GIVEN the header-widget app is installed and enabled - WHEN a user opens the LaunchPad widget picker dialog -- THEN the `launchpad_header` widget MUST appear in the list with a title (e.g., "Header Banner") and an icon +- THEN the `header` widget type MUST appear in the list under its title (e.g., "Header Banner") - AND the widget MUST be selectable for placement on a dashboard #### Scenario: Multiple instances allowed @@ -55,9 +54,10 @@ The system MUST register a LaunchPad dashboard widget with id `launchpad_header` - GIVEN the widget is registered - WHEN Nextcloud cache is cleared or the app is reloaded -- THEN the `launchpad_header` widget MUST still be discoverable in the picker +- THEN the `header` widget type MUST still be discoverable in the picker #### Scenario: Widget registration includes metadata +@e2e exclude no metadata fetch exists to observe: the type is a client-side registry entry (nc-vue `registerDashboardWidget('header', { displayName, icon })`), not an `OCP\Dashboard\IManager` widget, so the picker reads it in memory and no widget object with id/title/icon_url is ever fetched; src/constants/__tests__/widgetRegistry.spec.js pins that the `header` entry exists with a renderer, a form and defaultContent; no test pins its displayName or icon - GIVEN the widget is registered - WHEN the widget picker fetches widget metadata @@ -66,7 +66,6 @@ The system MUST register a LaunchPad dashboard widget with id `launchpad_header` ### Requirement: REQ-HDR-002 Placement configuration structure The system MUST store per-placement widget configuration in the `oc_launchpad_widget_placements.widgetContent` JSON field, allowing users to specify content, styling, image source, and optional CTA. -@e2e exclude placement configuration tests JSON blob shape — Vitest/Newman scope #### Scenario: Config for title and subtitle @@ -84,6 +83,7 @@ The system MUST store per-placement widget configuration in the `oc_launchpad_wi - AND the URL is subject to allow-list validation (see REQ-HDR-005) #### Scenario: Config for background image file ID +@e2e exclude never built: CnHeaderWidgetForm (@conduction/nextcloud-vue 2.180.0) has no Nextcloud Files picker, only an upload and a URL field, so a user cannot select a file id; a seeded backgroundImageFileId and its read-ACL are covered by header-widget::user-can-read-file, user-cannot-read-file and file-id-converted-to-preview-url; no unit test exists - GIVEN a user is configuring a header widget placement - WHEN they select an image from Nextcloud Files @@ -148,13 +148,12 @@ The system MUST store per-placement widget configuration in the `oc_launchpad_wi - GIVEN a placement with header widget config - WHEN the placement is fetched from the database -- THEN the `widgetContent` MUST deserialize cleanly to a JavaScript object +- THEN the placement's `content` MUST deserialize cleanly to a JavaScript object - AND all required fields MUST be present with no spurious whitespace or encoding issues ### Requirement: REQ-HDR-003 Image source precedence When both `backgroundImageFileId` and `backgroundImageUrl` are present in the configuration, the system MUST apply the following precedence: file ID takes priority over URL. -@e2e exclude image source precedence tests Vue computed property logic — Vitest component scope #### Scenario: File ID overrides URL when both set @@ -178,7 +177,6 @@ When both `backgroundImageFileId` and `backgroundImageUrl` are present in the co ### Requirement: REQ-HDR-004 Overlay rendering modes The system MUST support three overlay modes for controlling how background images are layered with colors. -@e2e exclude overlay rendering modes tests CSS gradient/tint overlay — visual regression / Vitest snapshot scope #### Scenario: Overlay mode none (no overlay) @@ -212,15 +210,16 @@ The system MUST support three overlay modes for controlling how background image ### Requirement: REQ-HDR-005 External image allow-list The system MUST enforce an allow-list of external image hostnames via admin setting `launchpad.header_widget_allowed_image_domains` to prevent loading from untrusted sources. -@e2e exclude external image allow-list tests PHP config + IAppConfig — Newman scope #### Scenario: Allow-list enabled with allowed domain +@e2e exclude never built: no `header_widget_allowed_image_domains` setting and no hostname check exist in lib/, src/, appinfo/ or the nc-vue CnHeaderWidget renderer (`git log --all -S header_widget_allowed_image_domains -- lib src appinfo` is empty; the key appears only under openspec/), so there is no allow-list to configure or observe; no unit test exists - GIVEN launchpad.header_widget_allowed_image_domains="[\"images.example.com\", \"cdn.trusted.org\"]" - WHEN a placement is configured with backgroundImageUrl="https://images.example.com/banner.jpg" - THEN the image MUST be allowed and loaded #### Scenario: Allow-list enabled with disallowed domain +@e2e exclude never built: no `header_widget_allowed_image_domains` setting and no hostname check exist in lib/, src/, appinfo/ or the nc-vue CnHeaderWidget renderer (`git log --all -S header_widget_allowed_image_domains -- lib src appinfo` is empty; the key appears only under openspec/), so there is no allow-list to configure or observe; no unit test exists - GIVEN launchpad.header_widget_allowed_image_domains="[\"images.example.com\"]" - WHEN a placement is configured with backgroundImageUrl="https://untrusted-site.com/image.jpg" @@ -229,6 +228,7 @@ The system MUST enforce an allow-list of external image hostnames via admin sett - AND no error UI MUST be displayed #### Scenario: Empty allow-list allows all domains +@e2e exclude never built: no `header_widget_allowed_image_domains` setting and no hostname check exist in lib/, src/, appinfo/ or the nc-vue CnHeaderWidget renderer (`git log --all -S header_widget_allowed_image_domains -- lib src appinfo` is empty; the key appears only under openspec/), so there is no allow-list to configure or observe; no unit test exists - GIVEN launchpad.header_widget_allowed_image_domains=null or [] - WHEN a placement is configured with any external backgroundImageUrl @@ -236,6 +236,7 @@ The system MUST enforce an allow-list of external image hostnames via admin sett - AND this is the default behavior (zero-config = all allowed) #### Scenario: Same-origin URLs bypass allow-list +@e2e exclude never built: no `header_widget_allowed_image_domains` setting and no hostname check exist in lib/, src/, appinfo/ or the nc-vue CnHeaderWidget renderer (`git log --all -S header_widget_allowed_image_domains -- lib src appinfo` is empty; the key appears only under openspec/), so there is no allow-list to configure or observe; no unit test exists - GIVEN the dashboard is loaded from localhost:3000 - WHEN a placement is configured with backgroundImageUrl="http://localhost:3000/images/banner.jpg" @@ -243,6 +244,7 @@ The system MUST enforce an allow-list of external image hostnames via admin sett - AND same-origin is determined by protocol, hostname, and port #### Scenario: Allow-list hostname matching is case-insensitive +@e2e exclude never built: no `header_widget_allowed_image_domains` setting and no hostname check exist in lib/, src/, appinfo/ or the nc-vue CnHeaderWidget renderer (`git log --all -S header_widget_allowed_image_domains -- lib src appinfo` is empty; the key appears only under openspec/), so there is no allow-list to configure or observe; no unit test exists - GIVEN launchpad.header_widget_allowed_image_domains="[\"Images.Example.COM\"]" - WHEN a placement is configured with backgroundImageUrl="https://images.example.com/banner.jpg" @@ -251,7 +253,6 @@ The system MUST enforce an allow-list of external image hostnames via admin sett ### Requirement: REQ-HDR-006 File ID image with ACL validation The system MUST validate file read permissions when `backgroundImageFileId` is set, falling back to backgroundColor if the user cannot read the file. -@e2e exclude file ID image with ACL validation tests PHP ACL + IURLGenerator — Newman scope #### Scenario: User can read file @@ -280,7 +281,6 @@ The system MUST validate file read permissions when `backgroundImageFileId` is s ### Requirement: REQ-HDR-007 Image load failure graceful fallback The system MUST gracefully handle image load failures (404, timeout, invalid URL) by falling back to backgroundColor and continuing to render the widget without error UI. -@e2e exclude image load failure graceful fallback tests Vue imgError handler — Vitest scope; requires broken-image URL injection #### Scenario: External image returns 404 @@ -307,7 +307,6 @@ The system MUST gracefully handle image load failures (404, timeout, invalid URL ### Requirement: REQ-HDR-008 Text rendering and styling The system MUST render title and subtitle with semantic HTML and configurable styling (color, alignment, vertical positioning). -@e2e exclude text rendering and styling tests Vue slot rendering + CSS — Vitest snapshot scope #### Scenario: Title rendered as h2 @@ -346,34 +345,20 @@ The system MUST render title and subtitle with semantic HTML and configurable st ### Requirement: REQ-HDR-009 Height presets and responsive sizing -The system MUST support four height presets (small, medium, large, xlarge) that map to fixed pixel values, and default widgets to full dashboard width. -@e2e exclude height presets and responsive sizing tests CSS calc values — visual regression scope +The header banner MUST fill its grid cell, so its height is flexible: the author resizes it in the grid like any other widget (Ruben, 21 Nov 2026, following the product). The four height presets (small 120px, medium 200px, large 320px, xlarge 480px; medium when unset) only set the starting height of a header when it is added, as the number of grid rows that preset needs. A new header defaults to the full dashboard width. -#### Scenario: Height small (120px) +#### Scenario: The banner fills its cell -- GIVEN a placement with height='small' -- WHEN the widget renders -- THEN the widget height MUST be 120px -- AND the widget MUST span the full dashboard width - -#### Scenario: Height medium (200px) +- GIVEN two header placements of 3 and 6 grid rows +- WHEN the dashboard renders +- THEN each banner MUST be as tall as its own grid cell +- AND the 6-row banner MUST be taller than the 3-row one, whatever height preset either carries -- GIVEN a placement with height='medium' -- WHEN the widget renders -- THEN the widget height MUST be 200px -- AND this is the default when height is not set +#### Scenario: A preset sets the starting height -#### Scenario: Height large (320px) - -- GIVEN a placement with height='large' -- WHEN the widget renders -- THEN the widget height MUST be 320px - -#### Scenario: Height xlarge (480px) - -- GIVEN a placement with height='xlarge' -- WHEN the widget renders -- THEN the widget height MUST be 480px +- GIVEN the author adds a header with height preset "small" +- WHEN the placement is created +- THEN its gridHeight MUST be the number of grid rows 120px needs (2 rows of 60px) #### Scenario: Default grid sizing for header widget @@ -385,7 +370,6 @@ The system MUST support four height presets (small, medium, large, xlarge) that ### Requirement: REQ-HDR-010 Call-to-action button rendering and navigation The system MUST render an optional CTA button with configurable style and handle navigation to internal or external URLs. -@e2e exclude CTA button rendering and navigation tests a router.push / window.open click handler inside a placed widget — requires seeded header placement #### Scenario: CTA button with primary style @@ -431,7 +415,6 @@ The system MUST render an optional CTA button with configurable style and handle ### Requirement: REQ-HDR-011 Accessibility for header widgets The system MUST ensure header widgets are accessible to keyboard navigation and screen readers, with proper ARIA labels and semantic HTML. -@e2e exclude accessibility ARIA attributes are render-time assertions; covered by Vitest snapshot #### Scenario: Title is keyboard-navigable @@ -471,7 +454,6 @@ The system MUST ensure header widgets are accessible to keyboard navigation and ### Requirement: REQ-HDR-012 Print-friendly rendering The system MUST render header widgets visibly when printed, including background images and colors, subject to the user's "print backgrounds" browser setting. -@e2e exclude print-friendly rendering tests CSS @media print — not observable in headless Chromium CI #### Scenario: Header widget prints with background image diff --git a/openspec/specs/i18n-translation-domain/spec.md b/openspec/specs/i18n-translation-domain/spec.md new file mode 100644 index 000000000..9cfc44f09 --- /dev/null +++ b/openspec/specs/i18n-translation-domain/spec.md @@ -0,0 +1,38 @@ +# i18n-translation-domain Specification + +## Purpose +Every translated string in LaunchPad's frontend is looked up under the domain its shipped l10n bundles register +under, so a Dutch user reads Dutch and a mismatched domain is caught by lint rather than shown as English. + +## Requirements + +### Requirement: REQ-I18N-001 All `t()`/`n()` calls MUST use the domain the shipped l10n bundles register under + +Every call to `t(app, …)` or `n(app, …)` from `@nextcloud/l10n` in `src/**/*.vue` and `src/**/*.js` MUST pass the same `app` (translation domain) string that the app's shipped `l10n/<lang>.js` bundles register +under via `OC.L10N.register(app, …)`. A mismatched domain string causes +`translate()`/`translatePlural()` to silently fall back to the raw +(English) source text on every locale, with no error or warning. + +#### Scenario: Health panel renders in the active locale + +- **GIVEN** a Nextcloud session with locale `nl` +- **WHEN** the admin opens the LaunchPad Health panel + (`HealthPanel.vue`) +- **THEN** the "Health" / "Checking…" / "Healthy" / "Degraded" strings + MUST render in Dutch, matching the translations present in + `l10n/nl.json` + +#### Scenario: Widget context menu renders in the active locale + +- **GIVEN** a Nextcloud session with locale `nl` +- **WHEN** a user opens the widget right-click context menu + (`WidgetContextMenu.vue`) +- **THEN** the "Visibility rules…" entry MUST render in Dutch + +#### Scenario: Lint guard catches a mismatched domain literal + +- **GIVEN** a developer adds `t('mydash', 'New string')` to a `src/` + file +- **WHEN** `npm run lint` runs +- **THEN** the translation-domain lint guard MUST fail with the + offending file:line, before the change can be merged diff --git a/openspec/specs/iframe-embed-widget/screens.md b/openspec/specs/iframe-embed-widget/screens.md new file mode 100644 index 000000000..18bf327e5 --- /dev/null +++ b/openspec/specs/iframe-embed-widget/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/iframe-embed-widget/spec.md b/openspec/specs/iframe-embed-widget/spec.md index fe54951d2..1e48d5755 100644 --- a/openspec/specs/iframe-embed-widget/spec.md +++ b/openspec/specs/iframe-embed-widget/spec.md @@ -1,13 +1,14 @@ # iframe-embed-widget Specification ## Purpose -TBD - created by archiving change iframe-embed-widget. Update Purpose after archive. +Show a page from another system, such as a business-intelligence report, as a live tile on a dashboard. Only hosts an administrator put on the allow-list can be embedded, the frame is always sandboxed, and a page that refuses framing gets a clear fallback with a link to open it in a new tab. ## Requirements ### Requirement: REQ-IFRAME-001 Register iframe-embed widget The system MUST register a `launchpad_iframe` widget with the Nextcloud Dashboard Widget API (v2) so it appears in the widget picker. #### Scenario: Widget appears in discovery +@e2e exclude never built: there is no `launchpad_iframe` id, no `IframeWidgetProvider` and no `supportsV2` declaration (`git log --all --oneline -SIframeWidgetProvider -- src lib appinfo` and `-Slaunchpad_iframe` return nothing; the archived change's tasks.md records the IManager registration as deferred). The widget ships as the LaunchPad-only type `iframe` ("Embedded page") in src/constants/widgetRegistry.js, and the picker path is driven by tests/e2e/iframe-embed-widget.spec.ts under config-stored-in-widgetcontent. - GIVEN the LaunchPad app is installed and enabled - WHEN the user opens the "Add Widget" modal on a dashboard - THEN the iframe-embed widget MUST appear in the widget list with id `launchpad_iframe` @@ -15,6 +16,7 @@ The system MUST register a `launchpad_iframe` widget with the Nextcloud Dashboar - AND the widget MUST declare `supportsV2 = true` #### Scenario: Registration via IManager +@e2e exclude never built, and PHP-internal: no `IframeWidgetProvider` exists and lib/AppInfo/Application.php makes no `registerWidget(...)` call (`git log --all --oneline -SIframeWidgetProvider -- src lib appinfo` returns nothing); no unit test pins it because there is nothing to pin. - GIVEN `OCP\Dashboard\IManager` is available - WHEN the LaunchPad app boots - THEN the app MUST register `IframeWidgetProvider` by calling `$manager->registerWidget(...)` @@ -25,6 +27,14 @@ The system MUST register a `launchpad_iframe` widget with the Nextcloud Dashboar - THEN the config MUST persist in the placement `widgetContent` JSON as `{ "url": "https://…", "title": "…", "height": 400, "aspect": "16:9", "sandbox": ["allow-scripts","allow-same-origin"], "allowListChecked": true }` - AND NO database migration or schema change MUST be required +#### Scenario: A Power BI report as a live tile +- GIVEN an administrator added `app.powerbi.com` to the embed allow-list (REQ-IFRAME-002) +- AND an author places the iframe-embed widget on dashboard "Management" with the report's embed URL on `https://app.powerbi.com/` and title "Rapport Sociaal domein" +- WHEN a manager signed in to Power BI opens the dashboard +- THEN the report MUST render inside the sandboxed frame, titled "Rapport Sociaal domein" (REQ-IFRAME-004) +- AND `https://app.powerbi.com` MUST be in the page's `frame-src` (REQ-IFRAME-003) +- AND when Power BI refuses framing, the tile MUST show the fallback with "Open in new tab" instead of an empty frame + ### Requirement: REQ-IFRAME-002 Admin allow-list of embeddable hosts, fail-closed The system MUST restrict embeddable targets to an administrator-controlled allow-list of hosts and MUST fail closed when a host is not listed. @@ -107,3 +117,14 @@ The system MUST embed the target in a sandboxed iframe and, when the target site - THEN the widget MUST show a loading indicator - AND on any other load error (network failure, invalid URL) it MUST render the fallback card, never crash the dashboard +### Requirement: The outage state of an embedded report (REQ-IFRAME-005) + +An embedded page or report SHALL show under its title where it comes from ("Embedded report · app.powerbi.com · signed in as <name>" when the connection signs in). When it cannot load, the card head SHALL show an "Outage" tag and the body SHALL say "The report could not be loaded", the cause and its time when the connection knows them ("gave an error today at 09:30: token expired"), with Reload and "Open in a new tab". + +#### Scenario: Token expired + +- **GIVEN** the Power BI connection failed at 09:30 with an expired token +- **THEN** the card shows Outage, the cause with 09:30, Reload and Open in a new tab + + +Content keys the widget reads for this (all optional): `kind` (`report` for an embedded report, otherwise a page) and `connection` (`{account, error, errorAt}`, what the connection behind the embed knows when one signs in). Without `connection.error`, the cause is what the widget found itself (the site refuses framing, could not be reached, did not finish loading, a network error) and the time is when it saw that. diff --git a/openspec/specs/image-widget/screens.md b/openspec/specs/image-widget/screens.md new file mode 100644 index 000000000..9fc265175 --- /dev/null +++ b/openspec/specs/image-widget/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet +- LpWidgetInstellen the image widget form: upload a file or link a web address, text for who does not see the image (REQ-IMG-005) https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetInstellen diff --git a/openspec/specs/image-widget/spec.md b/openspec/specs/image-widget/spec.md index 7175b5cfc..d83c5e679 100644 --- a/openspec/specs/image-widget/spec.md +++ b/openspec/specs/image-widget/spec.md @@ -31,7 +31,6 @@ Resource lifecycle (orphan GC, quota accounting) is owned by the `resource-uploa ### Requirement: REQ-IMG-001 Render image with object-fit The renderer MUST output an `<img :src="url" :alt="alt">` whose CSS `object-fit` MUST equal the `fit` field of the persisted content. The `<img>` MUST fill the cell with `width: 100%; height: 100%`. The cell wrapper MUST set `overflow: hidden` so over-fit images do not bleed out of the grid cell. The persisted content shape is `{type: 'image', content: {url, alt, link, fit}}` where `fit` is one of `'cover' | 'contain' | 'fill' | 'none'` (default `'cover'`). The Vue prop validator on `fit` MUST restrict the value to that enum and fall back to `'cover'` when an unknown value is passed. -@e2e exclude render image with object-fit tests CSS object-fit property — Vitest snapshot scope; requires a seeded image placement with a real URL #### Scenario: Cover fit fills the cell @@ -49,6 +48,7 @@ The renderer MUST output an `<img :src="url" :alt="alt">` whose CSS `object-fit` - AND letterboxing MUST be visible if the image's aspect ratio differs from the cell's #### Scenario: Invalid fit value falls back to cover +@e2e exclude a developer mounting the component with a `fit` prop is a component-mount scenario, not an app one: WidgetRenderer passes CnImageWidget only `content`, never a `fit` prop, and Vue prop-validator warnings exist only in development builds, so neither THEN is observable in the shipped app. The validator lives in @conduction/nextcloud-vue (CnImageWidget.vue) and no unit test for it exists in this repo - GIVEN a developer mounts the widget with `fit: 'stretch'` - WHEN the Vue prop validator runs @@ -64,7 +64,6 @@ The renderer MUST output an `<img :src="url" :alt="alt">` whose CSS `object-fit` ### Requirement: REQ-IMG-002 Empty-URL placeholder When `url` is empty or null, the renderer MUST display a placeholder consisting of a 48 px camera icon plus the translated string `t('No image')`, centred, in `var(--color-text-maxcontrast)`. The placeholder MUST occupy the full cell. The DOM MUST NOT contain an `<img>` element while the placeholder is active. -@e2e exclude empty-URL placeholder tests Vue placeholder component — covered partially by existing spec file (test.skip); seeding not available in CI fixture #### Scenario: Empty url shows placeholder @@ -114,7 +113,6 @@ When the persisted `link` field is non-empty, a click on the cell MUST open `lin ### Requirement: REQ-IMG-004 Broken-image fallback The `<img>` MUST handle the DOM `error` event by replacing itself with the empty-URL placeholder (as defined in REQ-IMG-002) plus the translated annotation `t('Image failed to load')`. The fallback MUST NOT crash, unmount, or otherwise disturb the surrounding GridStack grid. -@e2e exclude broken-image fallback tests Vue imgError handler — Vitest scope; requires injecting a broken URL into a placed widget #### Scenario: Broken external URL falls back @@ -170,12 +168,39 @@ The image sub-form for `AddWidgetModal` MUST expose the following controls: a fi - THEN it MUST contain exactly the four options `cover`, `contain`, `fill`, `none` - AND the default selected value MUST be `cover` for a new placement +### Requirement: REQ-IMG-006 External image hosts are allow-listed by an administrator + +An image widget MAY name an external `http(s)` URL, but the browser loads it only from a host an administrator has allow-listed. The allow-list is a JSON array of bare host names (optionally with a port) stored under the app config key `image_allowed_hosts`, the same shape as `iframe_allowed_hosts`. It is fail-closed: an empty or missing list admits no external image host, and `img-src` MUST NOT be opened to every host. Every LaunchPad page MUST add each listed host, as `https://<host>`, to its `img-src` directive. Administrators manage the list in the admin settings (Operations) and through `GET` / `PUT /api/admin/image-hosts`; an entry with a scheme, a path, a wildcard or a space MUST be refused with 400 and a message naming the entry, and nothing is stored. The image widget form does not check hosts itself. + +#### Scenario: Allow-listed external image loads + +- GIVEN `image_allowed_hosts` is `["example.com"]` +- AND content `{url: 'https://example.com/wide.png'}` +- WHEN the workspace renders the cell +- THEN the page's `img-src` MUST include `https://example.com` +- AND the image MUST load + +#### Scenario: External image from a host not on the list is blocked + +- GIVEN `image_allowed_hosts` does not list `example.net` +- AND content `{url: 'https://example.net/photo.png'}` +- WHEN the workspace renders the cell +- THEN the browser MUST refuse the image under the page's `img-src` +- AND the cell MUST show the broken-image fallback of REQ-IMG-004 + +#### Scenario: An entry that is not a host name is refused + +- GIVEN an administrator saves `["https://example.com"]` +- WHEN `PUT /api/admin/image-hosts` handles it +- THEN the response MUST be 400 with a message naming `https://example.com` +- AND the stored list MUST be unchanged + ### Requirement: REQ-IMP-001 SourceType field for image-widget config The image widget placement MUST store a `sourceType` field (ENUM: `'url'`, `'upload'`, `'files'`) in the placement's widget config. This field MUST default to `'url'` for backward compatibility with existing image widgets. The field MUST persist across widget updates and MUST be serialized in the placement API response. -@e2e exclude sourceType field tests JSON schema change — Vitest/Newman scope #### Scenario: New image widget defaults to URL source +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); CnImageWidgetForm emits only {url, alt, link, fit} and nothing in src/ or lib/ writes `sourceType`. No unit test exists - GIVEN a user creates a new image widget placement with no `sourceType` explicitly set - WHEN the placement is saved @@ -190,10 +215,11 @@ The image widget placement MUST store a `sourceType` field (ENUM: `'url'`, `'upl #### Scenario: SourceType included in API response - GIVEN a placement with `sourceType: 'upload'` -- WHEN the user fetches the placement via GET /api/widgets/{id} +- WHEN the user fetches the placement via GET /api/dashboard/{dashboardId} (there is no GET /api/widgets/{id}; the placement is returned in that response's `placements` array) - THEN the JSON response MUST include `"sourceType": "upload"` #### Scenario: Invalid sourceType rejected on input +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); WidgetApiController::contentToPersist stores any content array unvalidated and there is no sourceType enum check anywhere in lib/. No unit test exists - GIVEN a user attempts to set `sourceType: 'clipboard'` (not a valid enum value) - WHEN the placement is saved @@ -203,9 +229,9 @@ The image widget placement MUST store a `sourceType` field (ENUM: `'url'`, `'upl ### Requirement: REQ-IMP-002 File picker invocation When the image widget edit form has `sourceType = 'files'`, the form MUST display a "Pick from Files" button that opens Nextcloud's native file picker. The file picker MUST be restricted to image MIME types: `image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/svg+xml`. The picker MUST support only single-file selection, not multi-select. -@e2e exclude file picker invocation tests file-chooser event — covered by existing image-widget spec test.skip; NC Files picker not available headlessly #### Scenario: File picker button visible for files source +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); there is no "Pick from Files" control in src/ or in CnImageWidgetForm (the string exists only in the l10n catalogues). No unit test exists - GIVEN the user selects `sourceType: 'files'` in the image widget form - WHEN the form renders @@ -213,6 +239,7 @@ When the image widget edit form has `sourceType = 'files'`, the form MUST displa - AND the URL input field MUST be hidden (only the file picker UI is shown for this source type) #### Scenario: File picker opens on button click +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); there is no "Pick from Files" button to click and no file-picker call for the image widget anywhere in src/. No unit test exists - GIVEN the user clicks the "Pick from Files" button - WHEN the file picker opens @@ -220,6 +247,7 @@ When the image widget edit form has `sourceType = 'files'`, the form MUST displa - AND MIME type filtering MUST be applied (only image files visible) #### Scenario: File picker filters to image MIME types +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); no image-widget file picker is ever opened, so there is no MIME filter to observe. No unit test exists - GIVEN the file picker is open - WHEN the user navigates to a folder containing 10 files (3 images, 7 documents) @@ -227,6 +255,7 @@ When the image widget edit form has `sourceType = 'files'`, the form MUST displa - AND the 7 documents MUST appear disabled or hidden #### Scenario: Single-file selection only +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); no image-widget file picker is ever opened, so there is no selection mode to observe. No unit test exists - GIVEN the file picker is open - WHEN the user attempts to select multiple files (shift-click, Ctrl+click) @@ -236,9 +265,9 @@ When the image widget edit form has `sourceType = 'files'`, the form MUST displa ### Requirement: REQ-IMP-003 File reference storage When a file is selected via the file picker, the placement MUST store two fields: `fileId` (BIGINT) and `filePath` (VARCHAR, max 2048 bytes). Both MUST be persisted on the placement record in the database. The `filePath` MUST be the display path shown to the user (e.g. `/Photos/vacation.jpg`), suitable for human reading in edit forms and error messages. -@e2e exclude file reference storage tests REST endpoint and DB persistence — Newman scope #### Scenario: Selected file stores both ID and path +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); with no picker nothing ever sets `fileId`/`filePath` (they survive only as opaque content, which file-path-survives-widget-title-and-style-updates covers). No unit test exists - GIVEN the user selects `/Photos/sunset.png` from the file picker - WHEN the widget is saved @@ -253,6 +282,7 @@ When a file is selected via the file picker, the placement MUST store two fields - THEN both `fileId` and `filePath` MUST remain unchanged #### Scenario: FilePath max length enforced +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); the fileId/filePath columns (task 1.1) were never added and placement content is stored without validation, so there is no length limit to enforce. No unit test exists - GIVEN a user attempts to save a file with an extremely long path (>2048 bytes) - WHEN validation occurs @@ -262,9 +292,9 @@ When a file is selected via the file picker, the placement MUST store two fields ### Requirement: REQ-IMP-004 Preview URL generation for file-mode widgets At render time, the widget MUST generate a preview image URL for the referenced Nextcloud file using the appropriate Nextcloud preview service. The system MUST use `IURLGenerator::linkToRoute()` (server) or the equivalent `/index.php/core/preview?fileId=…` route (client) to generate a URL that respects the viewer's access permissions to the file. The preview URL MUST support both scenarios: files owned by the viewer and files shared with the viewer. -@e2e exclude preview URL generation tests IURLGenerator::linkToRoute PHP call — Newman/PHP scope #### Scenario: Viewer can access file, generates preview URL +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); nothing generates a preview URL from a `fileId` (no ImageWidgetService or resolveFilePreviewUrl in lib/, and CnImageWidget renders `content.url` only). Rendering a stored preview URL is covered by the deleted-file and viewer-cannot-access tests. No unit test exists - GIVEN a placement with `sourceType: 'files'`, `fileId: 12345`, and the viewer owns the file - WHEN the widget renders @@ -279,6 +309,7 @@ At render time, the widget MUST generate a preview image URL for the referenced - AND the widget MUST fall back to the broken-image fallback (REQ-IMP-005) #### Scenario: Shared file preview URL uses public share route +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); nothing generates a preview URL at all, so there is no choice of share route to observe. No unit test exists - GIVEN a file is shared with the viewer via a share link - AND the placement references the file ID @@ -296,7 +327,6 @@ At render time, the widget MUST generate a preview image URL for the referenced ### Requirement: REQ-IMP-005 Broken-image fallback for file-mode widgets When a file-mode image widget's referenced file is inaccessible (deleted, permissions revoked, or network failure), the widget MUST display the same broken-image placeholder as REQ-IMG-004: a 48 px camera icon plus the translated message `t('Image failed to load')`, centered. The widget MUST NOT crash, unmount, or throw a 500 HTTP error. The broken-image fallback MUST be identical regardless of source type (`url`, `upload`, or `files`). -@e2e exclude broken-image fallback for file-mode tests Vue imgError handler — Vitest scope #### Scenario: Deleted file shows broken-image fallback @@ -323,7 +353,6 @@ When a file-mode image widget's referenced file is inaccessible (deleted, permis ### Requirement: REQ-IMP-006 File deletion handling When the referenced Nextcloud file is deleted, the widget MUST retain its `fileId` and `filePath` reference on the placement (the placement is NOT auto-deleted). This allows the widget to show a clear "image unavailable" state (the broken-image fallback) rather than silently clearing the placement or showing a generic empty state. The broken-image fallback (REQ-IMP-005) provides the appropriate user feedback. -@e2e exclude file deletion handling tests REST endpoint — Newman scope #### Scenario: Deleted file retains placement metadata @@ -333,6 +362,7 @@ When the referenced Nextcloud file is deleted, the widget MUST retain its `fileI - AND the widget MUST render the broken-image fallback on next page load #### Scenario: Admin can clear orphaned reference manually +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); the form has neither a "Pick from Files" button nor a sourceType switch, and nothing clears `fileId`/`filePath` on save. No unit test exists - GIVEN a placement with a deleted file's orphaned reference - WHEN the widget editor form opens @@ -343,9 +373,9 @@ When the referenced Nextcloud file is deleted, the widget MUST retain its `fileI ### Requirement: REQ-IMP-007 Widget form source type UI The image widget edit form MUST display a "Source Type" radio group with three mutually exclusive options: "URL/Link", "Upload", and "Pick from Files". Only the input fields relevant to the selected source type MUST be visible. Switching between source types MUST NOT erase previously entered values for other source types (values MUST be retained in component state, allowing the user to switch back without re-entering). -@e2e exclude widget form source type UI radio/select tests form field structure — Vitest snapshot scope; full form test requires open modal with widget selected #### Scenario: Radio group shows all three source options +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); CnImageWidgetForm has no source-type radio group, only an always-present file input next to the URL field. No unit test exists - GIVEN the image widget edit form opens - WHEN the form renders @@ -353,6 +383,7 @@ The image widget edit form MUST display a "Source Type" radio group with three m - AND one option MUST be pre-selected based on the current placement's `sourceType` #### Scenario: URL form fields shown only for URL source +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); there is no source-type control, so no field is ever shown or hidden by it. No unit test exists - GIVEN the user selects the "URL/Link" radio option - WHEN the form updates @@ -360,6 +391,7 @@ The image widget edit form MUST display a "Source Type" radio group with three m - AND the file upload input and file picker button MUST be hidden #### Scenario: Upload form fields shown only for upload source +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); there is no source-type control, so no field is ever shown or hidden by it. No unit test exists - GIVEN the user selects the "Upload" radio option - WHEN the form updates @@ -367,6 +399,7 @@ The image widget edit form MUST display a "Source Type" radio group with three m - AND the URL/link inputs and file picker button MUST be hidden #### Scenario: File picker shown only for files source +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); there is no source-type control and no file picker button. No unit test exists - GIVEN the user selects the "Pick from Files" radio option - WHEN the form updates @@ -374,6 +407,7 @@ The image widget edit form MUST display a "Source Type" radio group with three m - AND the URL input and file upload input MUST be hidden #### Scenario: Switching sources retains previous values +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); there is no source-type control to switch. No unit test exists - GIVEN the user enters a URL in the URL field, then switches to "Upload" - WHEN the user switches back to "URL/Link" @@ -383,9 +417,9 @@ The image widget edit form MUST display a "Source Type" radio group with three m ### Requirement: REQ-IMP-008 SVG source handoff to sanitisation When a file-mode image widget references an SVG file (`image/svg+xml`), the widget MUST NOT render the SVG as a raw `<img>` element before sanitisation. Instead, the SVG file reference MUST be passed to the separate `svg-sanitisation` capability for XSS protection. This requirement specifies the handoff point; the actual SVG sanitisation is implemented in the `svg-sanitisation` change. -@e2e exclude SVG source handoff to sanitisation pipeline tests PHP SvgSanitiser — Newman scope #### Scenario: SVG file triggers sanitisation handoff +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); no image-widget code hands a file reference to SvgSanitiser, which is called only on upload in ResourceService (pinned by tests/Unit/Service/ResourceServiceSvgIntegrationTest.php, the upload path, not this handoff). No unit test of the handoff exists - GIVEN a placement with `sourceType: 'files'` and the selected file has MIME type `image/svg+xml` - WHEN the widget edit form saves the placement @@ -394,6 +428,7 @@ When a file-mode image widget references an SVG file (`image/svg+xml`), the widg - AND the raw file content MUST NOT be served directly as an `<img>` src before sanitisation #### Scenario: Non-SVG images bypass sanitisation requirement +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); there is no handoff to bypass, and the absence of a sanitiser call has no observable UI or API effect. No unit test exists - GIVEN a placement with a PNG file (`image/png`) - WHEN the widget renders @@ -401,12 +436,22 @@ When a file-mode image widget references an SVG file (`image/svg+xml`), the widg - AND the `svg-sanitisation` capability is NOT invoked #### Scenario: SVG from URL source also requires sanitisation +@e2e exclude feature never built: the image-widget-media-picker change was archived with every task unchecked (openspec/changes/archive/2026-05-03-image-widget-media-picker/tasks.md); CnImageWidget puts any `url` straight into `<img src>` with no routing through SvgSanitiser, which only runs on upload (tests/Unit/Service/ResourceServiceSvgIntegrationTest.php). No unit test of a URL-source handoff exists - GIVEN a placement with `sourceType: 'url'` pointing to an external SVG file - WHEN the widget renders - THEN the URL MUST be routed through the `svg-sanitisation` capability - NOTE: This requirement applies equally to both `url` and `files` sources; it documents the hand-off point for SVG handling +### Requirement: The Image content form (REQ-IMG-020) + +The content part of an Image widget SHALL ask "Where does the image come from?" with Upload file (from Files or the computer, up to 5 MB) or Web address, SHALL show a chosen file with its name, size and dimensions and a way to choose another, SHALL require a text for who does not see the image, and SHALL offer an optional link on click. + +#### Scenario: Alternative text is required + +- **WHEN** the editor saves an image without alternative text +- **THEN** the form refuses and names the field + ## Non-Functional Requirements - **Backward Compatibility**: Existing image widgets with `sourceType: 'url'` (default) MUST continue to render unchanged. No breaking changes to REQ-IMG-001..005. diff --git a/openspec/specs/infrastructure-helpers/screens.md b/openspec/specs/infrastructure-helpers/screens.md new file mode 100644 index 000000000..ec09fecd0 --- /dev/null +++ b/openspec/specs/infrastructure-helpers/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Interne hulpklassen zonder scherm. diff --git a/openspec/specs/infrastructure-helpers/spec.md b/openspec/specs/infrastructure-helpers/spec.md index 3a412c169..6e94da6a4 100644 --- a/openspec/specs/infrastructure-helpers/spec.md +++ b/openspec/specs/infrastructure-helpers/spec.md @@ -20,9 +20,6 @@ This capability MUST contain only helpers that: ## Requirements - -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### REQ-INFRA-001: Slug generation and validation The system MUST provide a static `SlugGenerator` helper that converts arbitrary user-supplied names into URL-safe slugs and validates caller-supplied slugs against the pinned grammar. The slug grammar is `^[a-z0-9_-]+$` (lowercase ASCII alphanumerics, dash, underscore), maximum 128 characters (matching the `slug VARCHAR(128)` database column). @@ -61,6 +58,7 @@ The system MUST provide a static `SlugGenerator` helper that converts arbitrary - THEN the result is at most 128 characters AND does not end with `-` #### Scenario: Validate rejects empty string +@e2e exclude not reachable over HTTP: both slug write paths treat an empty slug as "none supplied" before validating (DashboardFactory::resolveSlug derives one from the name, DashboardService::applySlugUpdate stores NULL), so isValid('') is never called from a request; pinned by tests/Unit/Service/SlugGeneratorTest.php::testIsValidRejectsIllegalSlugs - WHEN `SlugGenerator::isValid('')` is called - THEN the result is `false` @@ -94,6 +92,7 @@ The system MUST provide `UserAttributeResolver` to back attribute-based features - THEN the result is `null` #### Scenario: Non-existent user returns null +@e2e exclude not reachable over HTTP: attribute rules are only ever evaluated for the logged-in caller (render time and POST /api/visibility/preview), who always exists; pinned by tests/Unit/Service/UserAttributeResolverTest.php::testUnknownUserResolvesToNullWithoutReadingConfig (the null is returned before the attribute is looked at, so it holds for 'email' as for 'locale') - WHEN `getUserAttributeValue('does-not-exist', 'email')` is called - THEN the result is `null` @@ -141,6 +140,7 @@ Neither method validates field shapes or values — downstream callers are respo - THEN the result is `{gridX: 2}` (single key) #### Scenario: extractPlacementData preserves all 16 fields when all are set +@e2e exclude the clause under test is the extractor's in-memory array (entry count, values not cast); a request can only observe the placement after the typed entity and columns have cast every value, so no HTTP read can tell. Partly pinned by tests/Unit/Controller/RequestDataExtractorTest.php::testPlacementDataKeepsOnlyGivenFields (every field name is read, given values are kept uncast); no unit test sets every field at once - GIVEN a request with all 16 placement fields set to non-null values - WHEN `extractPlacementData($request)` is called diff --git a/openspec/specs/initial-state-contract/screens.md b/openspec/specs/initial-state-contract/screens.md new file mode 100644 index 000000000..83f36a7ba --- /dev/null +++ b/openspec/specs/initial-state-contract/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Interne afspraak over de gegevens die de server aan de pagina meegeeft. diff --git a/openspec/specs/initial-state-contract/spec.md b/openspec/specs/initial-state-contract/spec.md index 3e1447bc3..7ce79dbbd 100644 --- a/openspec/specs/initial-state-contract/spec.md +++ b/openspec/specs/initial-state-contract/spec.md @@ -12,9 +12,6 @@ A typed PHP `InitialStateBuilder` service centralises the writes; a typed JS `lo ## Requirements - -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: Centralised PHP builder for initial state (REQ-INIT-001) The system MUST expose `lib/Service/InitialStateBuilder.php` with a constructor accepting an `IInitialState` and a `Page` enum (`Page::WORKSPACE` or `Page::ADMIN`). The builder MUST expose typed setter methods (e.g. `setWidgets(array $widgets): self`, `setLayout(array $layout): self`, `setIsAdmin(bool $isAdmin): self`) and a final `apply(): void` that writes every key to the initial-state service. `apply()` MUST throw `MissingInitialStateException` if any required key was not set for the chosen page. Controllers (`PageController`, `LaunchPadAdmin`) MUST use the builder; direct calls to `IInitialState::provideInitialState` from controllers are forbidden by code review (a grep lint MUST find such calls only inside `InitialStateBuilder`). @@ -26,12 +23,14 @@ The system MUST expose `lib/Service/InitialStateBuilder.php` with a constructor - **AND** the JS bundle MUST receive all 10 workspace keys declared in the Data Model #### Scenario: Missing required key raises before render +@e2e exclude needs a controller that omits setLayout(), which only a code change produces; pinned by tests/Unit/Service/InitialStateBuilderTest.php::testWorkspaceBuilderRejectsMissingRequiredKey (MissingInitialStateException naming "layout" for page "workspace") - **WHEN** a controller constructs the builder for `Page::WORKSPACE`, omits the required `setLayout()` call, and then invokes `apply()` - **THEN** the system MUST throw `MissingInitialStateException` with a message naming the missing key `layout` - **AND** the page MUST NOT render (HTTP 500 surfaces during dev; CI test catches this earlier) #### Scenario: Direct provideInitialState call rejected +@e2e exclude a source-code lint, not product behaviour; pinned by tests/Unit/Service/InitialStateContractLintTest.php::testNoDirectProvideInitialStateCallsOutsideBuilder (greps lib/, failure message points to InitialStateBuilder) and `composer lint:initial-state` - **WHEN** a developer adds `$initialState->provideInitialState('foo', 'bar')` directly inside `lib/Controller/PageController.php` - **THEN** the lint test (grep against `lib/`) MUST fail with a message pointing to `InitialStateBuilder` @@ -41,7 +40,7 @@ The system MUST expose `lib/Service/InitialStateBuilder.php` with a constructor The exact set of initial-state keys per page is part of the contract and MUST match the Data Model documented in this spec. Adding, removing, or renaming a key is a deliberate spec change and MUST be accompanied by (1) an update to this spec's Data Model, (2) a bump of the `INITIAL_STATE_SCHEMA_VERSION` constant (currently `1`), and (3) coordinated updates to both the PHP builder and the JS reader in the same commit. The schema version MUST itself be pushed as initial state under the key `_schemaVersion`. The JS reader MUST log a console warning when the received version differs from the compiled-in version (catches caching and deploy-skew bugs). -The Workspace page (mounted into `#launchpad-app`) MUST expose exactly these keys: +The Workspace page (mounted into `#workspace-vue`) MUST expose exactly these keys: | Key | Type | Default (if missing) | |---|---|---| @@ -66,6 +65,7 @@ The Admin page (mounted into `#launchpad-admin-settings`) MUST expose exactly th | `allowUserDashboards` | `boolean` | `false` | #### Scenario: Adding a key bumps version +@e2e exclude a code-review rule about a future change, nothing a running instance shows; the only automated part, PHP and JS constants in lockstep, is pinned by src/utils/__tests__/loadInitialState.spec.js 'exports INITIAL_STATE_SCHEMA_VERSION matching the PHP constant (3)' - **WHEN** a developer adds a new workspace initial-state key `theme` and submits the change for review - **THEN** the spec Data Model table MUST list `theme` with type and default @@ -83,12 +83,14 @@ The Admin page (mounted into `#launchpad-admin-settings`) MUST expose exactly th The system MUST expose `src/utils/loadInitialState.js` exporting `loadInitialState(page: 'workspace' | 'admin'): InitialState`. The reader MUST call `loadState('launchpad', key, default)` for every key declared for `page` in the Data Model, MUST return a typed object with default-filled fields (no `undefined` values), and MUST validate the received `_schemaVersion` against the compiled-in `INITIAL_STATE_SCHEMA_VERSION` constant per REQ-INIT-002. Entry points (`src/main.js`, `src/admin.js`) MUST use the reader; direct `loadState('launchpad', ...)` calls outside the reader are forbidden by a JS-side grep lint. #### Scenario: Reader fills defaults +@e2e exclude the reader's returned object stays inside the bundle and the page exposes none of it, so "no field is undefined" cannot be read from a browser; pinned by src/utils/__tests__/loadInitialState.spec.js 'fills defaults for every workspace key the server omitted' - **WHEN** PHP pushes only `widgets` (other keys missing for any reason) and `loadInitialState('workspace')` runs - **THEN** every key declared for the workspace page MUST have a defined value taken from the Data Model defaults - **AND** no field on the returned object MUST be `undefined` #### Scenario: Direct loadState rejected +@e2e exclude a source-code lint, not product behaviour; enforced by scripts/lint-initial-state.js (`npm run lint:initial-state`, part of `npm run lint`), whose failure message names loadInitialState; no test exercises the lint's failure path - **WHEN** a Vue component under `src/` calls `loadState('launchpad', 'something')` directly - **THEN** the lint test (grep against `src/`) MUST fail @@ -99,12 +101,14 @@ The system MUST expose `src/utils/loadInitialState.js` exporting `loadInitialSta After the entry point loads the initial state, it MUST expose every key via the Vue root `provide` option (Vue 2.7) — semantically equivalent to `app.provide(key, value)` in Vue 3 — so descendant components can `inject(key, default)` without re-reading from `loadState`. The provide call MUST use the same key string as the initial-state key — no renaming at the boundary (renaming is itself a spec change and bumps the schema version). #### Scenario: Provide names match initial-state keys +@e2e exclude provide/inject wiring inside the Vue app, not observable from the page; pinned by src/utils/__tests__/loadInitialState.spec.js 'exposes every key via provide/inject for descendant components (REQ-INIT-004)' - **WHEN** the workspace entry loads 10 initial-state keys via the reader and exposes them through `provide` - **THEN** the entry MUST emit exactly 10 provided keys, one per initial-state key, with identical key strings - **AND** no key renaming MUST occur at this boundary #### Scenario: Components inject by key name +@e2e exclude provide/inject wiring inside the Vue app, not observable from the page; pinned by src/utils/__tests__/loadInitialState.spec.js 'exposes every key via provide/inject for descendant components (REQ-INIT-004)' - **WHEN** a deep child component calls `inject('widgets', [])` - **THEN** the component MUST receive the value the entry point provided @@ -115,13 +119,93 @@ After the entry point loads the initial state, it MUST expose every key via the `provide`/`inject` distributes static snapshots — values are NOT reactive across writes. Components that need to mutate shared state (for example `layout` after editing) MUST clone the injected value into a local `ref` (or hand off to a Pinia store fed from the injected value). The entry-point provides MUST NEVER be wrapped in a `ref` to "make them reactive" — that would let component code accidentally mutate the boot snapshot and break re-mount semantics. #### Scenario: Mutation does not leak through inject +@e2e exclude component-internal reactivity, not observable from the page; pinned by src/utils/__tests__/loadInitialState.spec.js 'mutating a cloned ref does not leak to a sibling (REQ-INIT-005)' - **WHEN** component `A` injects `layout`, clones into `localLayout = ref([...injectedLayout])`, and mutates `localLayout` - **THEN** any sibling component that injects `layout` MUST still see the original (unmutated) value - **AND** no console error MUST fire about reactive mutation #### Scenario: Entry point does not wrap provide in ref +@e2e exclude a static property of src/main.js and src/admin.js checked by code review; no test exists - **WHEN** a code reviewer inspects `src/main.js` or `src/admin.js` - **THEN** every provided value MUST be a plain (non-reactive) value - **AND** no `provide(key, ref(value))` or `provide(key, reactive(value))` MUST appear at the entry-point boundary + +### Requirement: The workspace carries the first dashboard load (REQ-INIT-006) + +The Workspace page SHOULD carry the optional key `dashboardFirstLoad`: `{visible, active}`, where `visible` is exactly the payload `GET /api/dashboards/visible` answers for the caller and `active` is exactly the payload of `GET /api/dashboard`, or `null` when the caller has no dashboard. Both MUST be built by the same code as those endpoints. The key MUST be left out when the caller may not perform `dashboard.visible` or `dashboard.get-active`. The dashboard store MUST take the key once, on its first load, instead of requesting the two endpoints, and MUST request them on every later load and whenever the key is missing (default `null`). + +#### Scenario: The workspace opens without asking for its dashboards again + +- **GIVEN** Pieter may read his dashboards +- **WHEN** he opens the workspace +- **THEN** the page carries his visible dashboards and his active dashboard in `dashboardFirstLoad` +- **AND** the store shows them without requesting `/api/dashboards/visible` or `/api/dashboard` + +#### Scenario: A later load asks the API + +- **GIVEN** the workspace has opened from `dashboardFirstLoad` +- **WHEN** the store loads the dashboards again, for example after a dashboard limit refusal +- **THEN** it requests both endpoints + +#### Scenario: A refused caller gets no first load + +- **GIVEN** the action matrix refuses Pieter `dashboard.visible` +- **WHEN** he opens the workspace +- **THEN** the page carries no `dashboardFirstLoad` +- **AND** the store requests the endpoints and meets the same refusal + +### Requirement: The workspace carries the org navigation (REQ-INIT-007) + +The Workspace page SHOULD carry the optional key `orgNavigation`: `{position, tree, language}`, where `position` is exactly what `GET /api/admin/org-navigation/position` answers, and `tree` and `language` are exactly what `GET /api/admin/org-navigation` answers for the caller in the default language. The position MUST be read by the same code as that endpoint. The key MUST be left out when the caller may not perform `admin-org-navigation.get-org-navigation` or `admin-org-navigation.get-position`. The org navigation store MUST take the key once, on the shell's first load, instead of requesting the two endpoints, and MUST request them whenever the key is missing (default `null`). + +#### Scenario: The workspace opens without asking for its org navigation + +- **GIVEN** Pieter may read the org navigation +- **WHEN** he opens the workspace +- **THEN** the page carries the rail position and his filtered tree in `orgNavigation` +- **AND** the shell places the rail without requesting `/api/admin/org-navigation/position` or `/api/admin/org-navigation` + +#### Scenario: A refused caller gets no org navigation + +- **GIVEN** the action matrix refuses Pieter `admin-org-navigation.get-position` +- **WHEN** he opens the workspace +- **THEN** the page carries no `orgNavigation` +- **AND** the shell requests the endpoints and meets the same refusal + +### Requirement: The workspace carries its view's boot reads (REQ-INIT-008) + +The Workspace page SHOULD carry the optional key `workspaceBootReads`: `{tiles, pendingAcknowledgements, defaultDashboard}`, where `tiles` is exactly what `GET /api/tiles` answers for the caller, `pendingAcknowledgements` exactly what `GET /api/acknowledgements/pending` answers, and `defaultDashboard` exactly what `GET /api/dashboards/default` answers. A part MUST be left out when the caller may not perform its action (`tile.index`, `dashboard.get-default-dashboard`) or when reading it fails. The tile store, the pending-acknowledgements read and the default-dashboard read MUST each take their part once, on the first read, instead of requesting the endpoint, and MUST request it on every later read and whenever the part is missing. + +#### Scenario: The workspace opens without asking for its tiles, acknowledgements and default dashboard + +- **GIVEN** Pieter may read his tiles and his default dashboard +- **WHEN** he opens the workspace +- **THEN** the page carries his tiles, his pending acknowledgements and his default dashboard in `workspaceBootReads` +- **AND** the view shows them without requesting `/api/tiles`, `/api/acknowledgements/pending` or `/api/dashboards/default` + +#### Scenario: A refused part is asked for + +- **GIVEN** the action matrix refuses Pieter `tile.index` +- **WHEN** he opens the workspace +- **THEN** the page carries no `tiles` part +- **AND** the tile store requests `/api/tiles` and meets the same refusal + +### Requirement: A warm workspace load carries the kept manifest (REQ-INIT-009) + +`GET /api/manifest` SHOULD keep the manifest it builds for a user, keyed by user and installed app version, for 60 seconds, and MUST answer from the kept manifest within that time. The Workspace page SHOULD carry a kept manifest as the optional key `runtimeManifest` and MUST NOT build one itself. The key MUST be left out when the caller may not perform `manifest.index`. The page MUST take the key instead of requesting `GET /api/manifest`, and MUST request it whenever the key is missing (default `null`). + +#### Scenario: A warm reload does not ask for the manifest + +- **GIVEN** Pieter opened the workspace less than a minute ago +- **WHEN** he opens it again +- **THEN** the page carries his manifest in `runtimeManifest` +- **AND** the page does not request `/api/manifest` + +#### Scenario: A refused caller gets no kept manifest + +- **GIVEN** the action matrix refuses Pieter `manifest.index` +- **WHEN** he opens the workspace +- **THEN** the page carries no `runtimeManifest` +- **AND** the page requests `/api/manifest` and meets the same refusal diff --git a/openspec/specs/label-widget/screens.md b/openspec/specs/label-widget/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/label-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/label-widget/spec.md b/openspec/specs/label-widget/spec.md index 90aad7bc2..c6864c804 100644 --- a/openspec/specs/label-widget/spec.md +++ b/openspec/specs/label-widget/spec.md @@ -108,8 +108,6 @@ The label sub-form for `AddWidgetModal` MUST expose six controls: a required tex - **WHEN** the user opens that widget in the edit modal - **THEN** every one of the six form controls MUST display its corresponding value from `content` -@e2e exclude the browser path to this scenario is `tests/e2e/label-widget-content-edit.spec.ts` — right-click a placed label, Edit, read the form back — and that test is RED in the CI fixture: measured in run 31367057618, "2 of 3 pass" in the old combined file with this one failing. It is kept and still runnable (`npm run test:e2e:excluded`), not skipped and not deleted, but a test CI does not execute is not coverage and is not annotated as such here. Two things are true and both are recorded rather than hidden: the test needs fixing before it can be promoted, and even green it would not prove this scenario, because it asserts ONE field (`label text`) where the scenario names six. - ### Requirement: REQ-LBL-006 Layout fills cell with centred content The renderer wrapper MUST occupy the full grid cell using `width: 100%; height: 100%` and use flexbox to centre the inner `<span>` both vertically and horizontally. The wrapper MUST apply `padding: 12px`. diff --git a/openspec/specs/launchpad-adopt-or-abstractions/screens.md b/openspec/specs/launchpad-adopt-or-abstractions/screens.md new file mode 100644 index 000000000..2c8202448 --- /dev/null +++ b/openspec/specs/launchpad-adopt-or-abstractions/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Zorgt dat Launchpad zonder OpenRegister draait; een architectuurafspraak zonder eigen scherm. diff --git a/openspec/specs/launchpad-adopt-or-abstractions/spec.md b/openspec/specs/launchpad-adopt-or-abstractions/spec.md index eef95c90b..1141e4e54 100644 --- a/openspec/specs/launchpad-adopt-or-abstractions/spec.md +++ b/openspec/specs/launchpad-adopt-or-abstractions/spec.md @@ -18,7 +18,8 @@ The manifest MUST set: - `$schema` to the published nc-vue schema URL (for editor validation) - `version` to a semver string, bumped on shape change -- `dependencies: []` (explicit empty array) +- `dependencies` listing OpenRegister only as optional + (`[{"id": "openregister", "required": false, "name": "OpenRegister"}]`) - a `menu` array with at least the Dashboards entry - a `pages` array including the per-dashboard page (`type: "dashboard"`) @@ -46,25 +47,22 @@ The manifest MUST set: - AND the error MUST identify the offending JSON path - AND CI MUST fail on the same script -@e2e exclude the subject is a build script's exit code and stderr — `scripts/check-manifest.js`, exposed as `npm run check:manifest` and chained into `npm run lint`, which the shared quality workflow runs with `enable-eslint: true`. A browser cannot observe a non-zero exit status, and by construction the scenario describes a tree that never builds and therefore never reaches an instance. The hydra `manifest-validation` gate enforces the same shape independently. +@e2e exclude the subject is a build script's exit code and stderr — `scripts/check-manifest.js`, exposed as `npm run check:manifest` and chained into `npm run lint`, which the shared quality workflow runs with `enable-eslint: true`. A browser cannot observe a non-zero exit status, and by construction the scenario describes a tree that never builds and therefore never reaches an instance. The hydra `manifest-validation` gate enforces the same shape independently. Re-checked 2026-11-19: `scripts/check-manifest.js` validates only `$schema`, a semver `version`, that `dependencies`, `menu` and `pages` are arrays, and that `dependencies` holds no bare `"openregister"`/`"openconnector"` string; it does not check a page's `type` against an allowed set and prints no JSON path, so the THEN describes behaviour the script does not have. No unit test pins the script. #### Scenario: Manifest declares no install-time OR dependency - GIVEN the file `src/manifest.json` - WHEN `manifest.dependencies` is read -- THEN it MUST be an empty array `[]` -- AND no review MAY add `"openregister"`, `"openconnector"`, or any - other Conduction app ID to the array - -@e2e exclude a static assertion about one key in a checked-in JSON file (`src/manifest.json` currently reads `"dependencies": []`), plus a rule addressed to reviewers rather than to the product. Neither has a browser surface: the runtime manifest served to the page is assembled server-side and replaces this file's contents outright, so a rendered page cannot report what the bundled literal said. +- THEN it MUST be an array whose only entry is OpenRegister marked + optional (`required: false`) +- AND no review MAY add a required entry, a bare app-id string, or + `"openconnector"` or any other Conduction app ID to the array ### Requirement: LaunchPad MUST NOT declare an install-time dependency on OpenRegister or OpenConnector This is a structural policy. LaunchPad MUST be installable and runnable on a Nextcloud instance that has neither OR nor OC enabled. -@e2e exclude two of these read checked-in files (`appinfo/info.xml`, `composer.json`) and have no runtime surface at all. The third needs an instance with OpenRegister ABSENT, and the Playwright fixture is deliberately the opposite: `.github/workflows/code-quality.yml` installs `ConductionNL/openregister` via `additional-apps` precisely so the suite exercises the OR-backed paths, and one CI job cannot be two instances. The OR-less boot path does have a running regression floor — `tests/e2e/ci/boot-and-manifest.spec.ts` exists because every route once returned 500 on an OR-less instance — but it necessarily runs against the OR-present fixture, so it cannot stand behind this scenario's GIVEN. - #### Scenario: Install on OR-less Nextcloud - GIVEN a Nextcloud install with OR not present and OC not present @@ -100,10 +98,10 @@ Any LaunchPad widget that reads or writes OR objects MUST guard the call with `useOrFeatureDetect()` and render a documented empty state when OR is absent or returns 5xx. -@e2e exclude there is nothing to observe yet: `useOrFeatureDetect` appears nowhere under `src/`, and no LaunchPad widget fetches OpenRegister from the browser at all — the string `apps/openregister/api` does not occur in any `.js` or `.vue` source outside tests. Every OR round-trip LaunchPad makes is server-side, through AppHost. A Playwright test written against these scenarios today could only assert that an absent code path stays absent. The first scenario additionally requires an OR-less instance, which the CI fixture is not. This is a spec-ahead-of-code divergence, reported rather than annotated away. - #### Scenario: OR-backed widget on OR-less install +@e2e exclude the THEN is unbuilt: `useOrFeatureDetect` occurs nowhere under `src/` (only in `docs/widgets/or-data.md` and `docs/architecture.md`; `git log --all -S useOrFeatureDetect -- src lib` finds no commit), so there is no `enabled.value` to read and nothing stops the request to OpenRegister; no unit test pins it either. The GIVEN itself can be staged: `tests/e2e/or-absent.spec.ts` disables OpenRegister and cites the widget's empty state as `runtime-or-consumption::or-absent-empty-state-shown` and in `install-on-or-less-nextcloud`. The OR-present half of this requirement (a 503) is cited in `tests/e2e/launchpad-adopt-or-abstractions.spec.ts`. + - GIVEN OR is not installed on the Nextcloud instance - AND an operator has placed an OR-backed widget on a dashboard - WHEN the dashboard renders @@ -136,10 +134,10 @@ current Nextcloud locale. This is a downstream consumer of `openregister/openspec/changes/i18n-api-language-negotiation/`. -@e2e exclude both scenarios assert the shape of an outbound request a LaunchPad widget makes to OpenRegister from the browser — a `?_lang=` query parameter, an `X-Translation-Target-Language` header. No such request exists to inspect: `apps/openregister/api` does not appear in any `.js` or `.vue` file under `src/` outside tests, so there is no browser-issued OR fetch for a network assertion to attach to. Spec ahead of code, reported rather than annotated away. - #### Scenario: Locale stamping on OR fetch +@e2e exclude the WHEN is a widget fetching ONE OpenRegister object by uuid (`/objects/cases/melding/abc`), and no widget LaunchPad can place does that from the browser: the browser-side OR reads in `src/` and in nc-vue's `CnObjectListWidget` are collection reads (`/objects/{register}/{schema}?_limit=...`), and the single-object paths they build are only PATCH/DELETE writes. The `?_lang=` contract on the collection read a widget does issue is cited as `runtime-or-consumption::widget-passes-current-user-locale` and `::widget-falls-back-to-en-when-lang-attribute-is-absent`. No unit test pins `_lang` stamping; no source file under `src/` sends it. + - GIVEN the user's Nextcloud locale is `en_GB` - AND a widget fetches OR object `register=cases, schema=melding, uuid=abc` @@ -167,7 +165,7 @@ once the `multi-tenancy-context` change in LaunchPad widgets MUST use the composable to refetch on tenant switch and to stamp `X-OpenRegister-Organisation` on writes. -@e2e exclude the requirement is explicitly conditional on an upstream release that has not happened — neither `useTenantContext` nor `X-OpenRegister-Organisation` occurs anywhere under `src/`, and the pinned dependency is `@conduction/nextcloud-vue` 2.2.0-vue3.9. There is no tenant switcher on the instance to drive and no header to inspect. The second scenario asserts a guarded import, i.e. that nothing happens when a symbol is missing, which is a bundler-level property with no rendered consequence. +@e2e exclude no tenant switcher exists for a test to drive, and nothing would react to it. Re-checked 2026-11-19: the upstream release has now happened — the installed `@conduction/nextcloud-vue` is 2.180.0 and its `src/index.js` exports `useTenantContext` — but no LaunchPad source imports it (`useTenantContext`, `provideTenantContext` and `X-OpenRegister-Organisation` occur nowhere under `src/` or `lib/`; `git log --all -S useTenantContext -- src` finds no commit). `CnAppRoot` mounts a tenant provider and a `CnTenantBadge`, which is display-only, and nc-vue's `CnObjectListWidget` does not subscribe to a switch. OpenRegister itself reads no tenant header: it scopes by the user's stored `active_organisation`. The second scenario's GIVEN (nc-vue NOT exporting the composable) can no longer be arranged against the pinned package, and its THEN is a guarded import, a bundler property with no rendered consequence. No unit test pins either scenario. #### Scenario: Tenant switch refetches widget data @@ -198,8 +196,6 @@ OR per-object RBAC delegation MAY be wired as an OPTIONAL runtime delegation when a dashboard's `permissions.delegate` field references an OR object UUID and OR is enabled. -@e2e exclude the first scenario requires an instance with OpenRegister ABSENT, and the Playwright fixture installs it on purpose (`additional-apps` in `.github/workflows/code-quality.yml`). The second describes a MAY, not a MUST, and its trigger does not exist: no `permissions.delegate` field and no call to OpenRegister's `/can?action=read` occurs anywhere in `lib/` or `src/`. The OR-independent half of the sharing model — that a recipient sees a shared dashboard at the granted permission level — is the subject of `tests/e2e/dashboard-sharing.spec.ts`, which is currently withheld from the CI config because the fixture seeds only `e2e-grantee` and the spec needs a `recipient` account; that is recorded against the file in `playwright.config.ts`, not hidden here. - #### Scenario: Sharing on OR-less install - GIVEN OR is not installed @@ -213,6 +209,8 @@ references an OR object UUID and OR is enabled. #### Scenario: Optional delegation when OR enabled +@e2e exclude a MAY whose trigger was never built: no `permissions.delegate` field and no call to OpenRegister's `/can?action=read` occurs in `lib/` or `src/` (`permissions.delegate` appears only in `docs/architecture.md`). No test pins it. + - GIVEN OR is enabled - AND a dashboard's `permissions.delegate.objectUuid = "abc-123"` (referencing an OR object) @@ -232,7 +230,7 @@ MUST persist in the local `oc_launchpad_admin_settings` table. Admin templates MUST NOT be persisted in OR. -@e2e exclude both scenarios assert things a browser cannot reach. The first is a database-row assertion — one row in `oc_launchpad_admin_settings` under a specific key, and the ABSENCE of any row in any OpenRegister table plus the absence of any `/api/objects/...` call; a rendered template list looks identical whichever store produced it. The second is about a regex, `lib/Service/FileService.php::FILENAME_PATTERN`, and its rejection path is an HTTP 400 on import, which is Newman's contract territory here. `FILENAME_PATTERN` is directly unit-tested in `tests/Unit/Service/FileServiceTest.php`, which pins both the accepted set (including `template_v2.json`) and the rejected set (including `../../etc/passwd`) through data providers. +@e2e exclude neither scenario describes what the product does, and neither outcome is readable over HTTP. Admin templates do not persist in `oc_launchpad_admin_settings` at all: they are `oc_launchpad_dashboards` rows of type admin-template (`lib/Service/AdminTemplateService.php` inserts through `dashboardMapper`; `DashboardMapper::findAdminTemplates()` reads them back), and no API exposes raw table rows, so the first scenario's row-and-key assertion has no read to stand on and no test pins it. The second was never built as written: the only export is `POST /api/admin/export`, which streams a ZIP (`ExportService::streamZipResponse`), not a JSON file, and `AdminController::import` never looks at the uploaded filename, so no path rejects a name with 400. `FILENAME_PATTERN` guards `FileService::createFile` only, and is unit-tested in `tests/Unit/Service/FileServiceTest.php::testFilenamePatternAllowsValidNames` (with `template_v2.json`) and `::testFilenamePatternRejectsInvalidNames`. #### Scenario: Template persistence @@ -279,7 +277,6 @@ in `lib/Db/AdminSetting.php` MUST be collected into a single `AdminSettingKey` const-list (or PHP 8.1 `enum`). Existing constants MAY be kept as aliases for BC. -@e2e exclude the scenario is a source-organisation rule — where a string literal is declared, and that no second file declares a duplicate for the same logical key. It is satisfied today by the `AdminSettingKey` enum in `lib/Db/AdminSettingKey.php`, which carries 20 cases. Two files agreeing on where a constant lives produces no observable difference in a rendered page; the settings behave identically whether the key is defined once or twice. #### Scenario: Key list is single-source-of-truth @@ -301,7 +298,7 @@ be kept as aliases for BC. - rejected: `../etc/passwd`, `name.with.two.dots.json`, paths containing slashes (`a/b.json`), paths starting with `.` -@e2e exclude the requirement names its own coverage mechanism — "covered by a unit test" — and both scenarios end in "AND the unit test MUST assert true/false". They are assertions about `preg_match()` against a class constant, with no HTTP request and no rendered output between the regex and the verdict. That unit test exists and was opened before this exclusion was written: `tests/Unit/Service/FileServiceTest.php` calls `preg_match(FileService::FILENAME_PATTERN, $filename)` under data providers covering the allowed set (`template_v2.json` among them) and the rejected set (`../../etc/passwd` among them). +@e2e exclude the requirement names its own coverage mechanism — "covered by a unit test" — and both scenarios end in "AND the unit test MUST assert true/false". They are assertions about `preg_match()` against a class constant, with no HTTP request and no rendered output between the regex and the verdict. Re-checked 2026-11-19 in `tests/Unit/Service/FileServiceTest.php`: `testFilenamePatternAllowsValidNames` calls `preg_match(FileService::FILENAME_PATTERN, ...)` with `template_v2.json` in its data provider, which pins the second scenario. The rejected-set provider does NOT contain a traversal path; `../../etc/passwd` is pinned one layer up by `testPathTraversalIsRejected` (through `createFile`, where the `..` substring check fires before the regex) and `testForwardSlashIsRejected`. No test calls the regex on `../etc/passwd` directly. #### Scenario: Path traversal rejected diff --git a/openspec/specs/launchpad-ai-dashboard-assistant/screens.md b/openspec/specs/launchpad-ai-dashboard-assistant/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/launchpad-ai-dashboard-assistant/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/launchpad-ai-dashboard-assistant/spec.md b/openspec/specs/launchpad-ai-dashboard-assistant/spec.md index 82061aee3..379d55954 100644 --- a/openspec/specs/launchpad-ai-dashboard-assistant/spec.md +++ b/openspec/specs/launchpad-ai-dashboard-assistant/spec.md @@ -17,9 +17,7 @@ Decided on 29 Sep 2026 (DECISIONS row 16, row `a-assistant`), replacing the earl ## Requirements -@e2e exclude a live answer needs a running hermiq with a model on the instance; the widget is asserted in src/components/Widgets/Renderers/__tests__/AiAssistantWidget.spec.js and src/components/Widgets/Renderers/__tests__/noModelClient.spec.js, the registry in src/constants/__tests__/widgetRegistry.completeness.spec.js - -### REQ-ADA-001: The system SHALL register an `ai-assistant` widget type +### Requirement: REQ-ADA-001: The system SHALL register an `ai-assistant` widget type The widget MUST be registered in `src/constants/widgetRegistry.js` with `renderer`, `form`, `defaultContent`, `displayName` and `icon`, and listed in `lib/widget-types.json`, like every LaunchPad-rendered widget type. @@ -29,7 +27,7 @@ The widget MUST be registered in `src/constants/widgetRegistry.js` with `rendere - **WHEN** it runs - **THEN** `ai-assistant` is in `lib/widget-types.json` and surfaces in `listWidgetTypes()` with a form and a renderer -### REQ-ADA-002: The widget content SHALL name only the hermiq agent +### Requirement: REQ-ADA-002: The widget content SHALL name only the hermiq agent The placement MUST persist `{type: 'ai-assistant', content: {agentUuid}}`. `agentUuid` is optional; empty means hermiq's default agent. @@ -39,17 +37,19 @@ The placement MUST persist `{type: 'ai-assistant', content: {agentUuid}}`. `agen - **WHEN** a question is sent - **THEN** the request carries `agentUuid: ''` and hermiq answers with its default agent -### REQ-ADA-003: There SHALL be no manifest entry for the widget +### Requirement: REQ-ADA-003: There SHALL be no manifest entry for the widget LaunchPad-rendered widgets are declared in the registry, not in `src/manifest.json` `widgets[]`; the assistant follows them. The manifest's `dependencies` MUST NOT list hermiq: hermiq's presence is checked at runtime (REQ-ADA-004). #### Scenario: Manifest unchanged +@e2e exclude a build-time CLI check over src/manifest.json with nothing for a browser to drive; `npm run check:manifest` (scripts/check-manifest.js, part of `npm run lint`) pins that it passes, and no test pins that the manifest names neither the widget nor hermiq + - **GIVEN** `npm run check:manifest` - **WHEN** it runs - **THEN** it passes and the manifest names neither the widget nor hermiq -### REQ-ADA-004: Inference SHALL route exclusively through hermiq; launchpad MUST NOT contain an LLM client +### Requirement: REQ-ADA-004: Inference SHALL route exclusively through hermiq; launchpad MUST NOT contain an LLM client Every question MUST go to hermiq's chat endpoints (`/apps/hermiq/api/chat/stream`, falling back to `/apps/hermiq/api/chat/send`) through `useAiChatStream` with `chatAppId: 'hermiq'` and the context `{appId: 'launchpad', pageKind: 'dashboard', objectUuid: <dashboard uuid>, route}`. launchpad source MUST NOT import an LLM SDK, MUST NOT call a model URL, and MUST NOT carry a system prompt in code. @@ -67,11 +67,13 @@ Every question MUST go to hermiq's chat endpoints (`/apps/hermiq/api/chat/stream #### Scenario: No LLM client in launchpad +@e2e exclude a static scan of the src/ tree, not runtime behaviour; pinned by src/components/Widgets/Renderers/__tests__/noModelClient.spec.js + - **GIVEN** the launchpad `src/` tree - **WHEN** scanned for `openai`, `@anthropic-ai`, `@ollama`, `llphant` imports or a `localhost:11434` string - **THEN** there are no matches -### REQ-ADA-005: Tool calls SHALL be governed by hermiq +### Requirement: REQ-ADA-005: Tool calls SHALL be governed by hermiq launchpad MUST NOT pass a tool list. Which tools the model may call, and on what data, is decided by hermiq for the asking person over its governed MCP transport, under OpenRegister RBAC. `useAiChatStream` carries a fixed context shape, so a per-widget scope is not sent. @@ -81,7 +83,7 @@ launchpad MUST NOT pass a tool list. Which tools the model may call, and on what - **WHEN** the request body is read - **THEN** it carries `message`, `context` and `agentUuid`, and no `tools` field -### REQ-ADA-006: The widget SHALL render two reply modes, streamed chat and inline summary +### Requirement: REQ-ADA-006: The widget SHALL render two reply modes, streamed chat and inline summary A placement of 6 grid cells or more (`gridWidth × gridHeight`) MUST render the chat: a labelled question input, the conversation and the answer as it streams. A smaller placement MUST render summary mode: one "Summarise this dashboard" button that sends the translated question "Summarise this dashboard for me." and shows the latest answer in the cell. @@ -97,7 +99,7 @@ A placement of 6 grid cells or more (`gridWidth × gridHeight`) MUST render the - **WHEN** the viewer clicks "Summarise this dashboard" - **THEN** the widget sends "Summarise this dashboard for me." to Hermiq and shows the answer in the cell, and each click asks again -### REQ-ADA-007: History SHALL live in the browser session, not on a launchpad backend +### Requirement: REQ-ADA-007: History SHALL live in the browser session, not on a launchpad backend Conversation turns MUST live only in the widget's own state for the page session. launchpad MUST NOT add a backend table or endpoint for chat history; Hermiq keeps its own conversations. @@ -109,6 +111,8 @@ Conversation turns MUST live only in the widget's own state for the page session #### Scenario: No backend persistence route added +@e2e exclude a read of appinfo/routes.php, not runtime behaviour; no test pins it (no test in tests/Unit or src/**/__tests__ names these paths), and the e2e history-scoped-to-session test asserts the browser asks for no history + - **GIVEN** `appinfo/routes.php` after this widget ships - **WHEN** it is read - **THEN** no route matches `chat/history`, `ai/conversation` or `assistant/messages` diff --git a/openspec/specs/launchpad-compliance-audit-panel/screens.md b/openspec/specs/launchpad-compliance-audit-panel/screens.md new file mode 100644 index 000000000..8ce5b3fa4 --- /dev/null +++ b/openspec/specs/launchpad-compliance-audit-panel/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement diff --git a/openspec/specs/launchpad-compliance-audit-panel/spec.md b/openspec/specs/launchpad-compliance-audit-panel/spec.md index 5d17fa623..2505fda97 100644 --- a/openspec/specs/launchpad-compliance-audit-panel/spec.md +++ b/openspec/specs/launchpad-compliance-audit-panel/spec.md @@ -29,8 +29,6 @@ deadline alert, portfolio filter). ## Requirements -@e2e exclude proposed/unimplemented widget — `launchpad_compliance_audit` is not in widgetRegistry.js nor the manifest; no UI surface exists to drive. Scenarios assert registry/manifest contract, schema validation, OR-GraphQL/audit-trail-immutable consumption, docudesk deep-link, and Specter-sourced data rendering — backend/contract concerns belong in unit + Newman. Re-annotate with real UI tests when the widget is built. - ### REQ-CAP-001: The system SHALL register a `launchpad_compliance_audit` widget type The widget MUST appear in `src/constants/widgetRegistry.js` and the @@ -47,12 +45,16 @@ declaration. - **AND** the entry MUST surface in `listWidgetTypes()` with all required fields non-null +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no registry entry and no EXPECTED_TYPES entry to assert. + #### Scenario: Widget appears in the Add modal - **GIVEN** the Add Widget modal is open - **WHEN** the user opens the type picker - **THEN** `Compliance audit` MUST be selectable +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no `Compliance audit` type for the Add Widget modal's type picker to offer. + ### REQ-CAP-002: The widget content shape SHALL declare posture, filter, and alert configuration The placement MUST persist `{type: 'compliance-audit', content: {...}}` with: @@ -73,6 +75,8 @@ The placement MUST persist `{type: 'compliance-audit', content: {...}}` with: - **THEN** validation MUST pass - **AND** the defaults above MUST apply to unset fields +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no content-shape validator or default set for this type to exercise. + #### Scenario: Unknown framework slug accepted (forward-compat) - **GIVEN** `content.frameworks = ['BIO', 'CUSTOM-FRAMEWORK-X']` @@ -82,6 +86,8 @@ The placement MUST persist `{type: 'compliance-audit', content: {...}}` with: framework definition lives on the compliance sibling app, not in launchpad) +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no `frameworks` validation to exercise. + ### REQ-CAP-003: The audit-trail card SHALL be consumed from OR's `audit-trail-immutable` abstraction — never from a local audit table The audit-trail summary card MUST issue a GraphQL query against OR @@ -100,6 +106,8 @@ the audit trail (ADR-022 anti-pattern: "Home-grown audit trails"). - **AND** the GraphQL query MUST target OR's `/graphql` (no local table read, no axios to OR) +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no audit-trail card and no GraphQL query for it. + #### Scenario: OR absent renders empty-state inline - **GIVEN** OR is not reachable (`/graphql` returns 404) @@ -108,12 +116,16 @@ the audit trail (ADR-022 anti-pattern: "Home-grown audit trails"). `t('launchpad', 'Audit trail unavailable — OpenRegister not reachable')` - **AND** other cards on the widget MUST continue to render +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no audit card, and the 'Audit trail unavailable' string is not in src/ or l10n/en.js. + #### Scenario: No write to audit trail - **GIVEN** the compliance-audit widget source files - **WHEN** scanned for POST / PUT against `/apps/openregister/.*audit` - **THEN** zero matches MUST exist — the widget is read-only +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There are no widget source files to scan; the clause is a static source scan, not browser behaviour. + ### REQ-CAP-004: The retention card SHALL consume OR's `archival-destruction-workflow` + shillinq retention rules Retention disposition counts MUST be queried via GraphQL from OR @@ -134,6 +146,8 @@ locally and MUST NOT cache retention metadata. - **AND** the Selectielijst reference for the largest bucket MUST surface as a tooltip +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no retention card and no archival/retention-rules query. + #### Scenario: shillinq absent partial-renders the card - **GIVEN** OR present but shillinq absent @@ -143,6 +157,8 @@ locally and MUST NOT cache retention metadata. `t('launchpad', 'Retention rules unavailable — shillinq not installed')` - **AND** no error MUST throw +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no retention card, and the 'Retention rules unavailable' string is not in src/ or l10n/en.js. + ### REQ-CAP-005: The widget SHALL surface deadline alerts with cross-session persistence (Specter acceptance) When a compliance deadline falls within `content.deadlineWindowDays`, the widget MUST render a visible alert naming the deadline and due @@ -160,6 +176,8 @@ widget reuses the placement's existing - **WHEN** the viewer opens the dashboard - **THEN** an alert MUST display naming the deadline and due date +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no compliance-deadline source or alert to render. + #### Scenario: Alert persists until acknowledged (Specter source) - **GIVEN** an unacknowledged imminent deadline alert @@ -169,6 +187,8 @@ widget reuses the placement's existing `content.acknowledgements` map via the existing widget PUT endpoint (no new endpoint added) +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no deadline alert, and no code writes `content.acknowledgements` for it. + #### Scenario: Passed deadline updates to overdue (Specter source) - **GIVEN** the deadline has passed without acknowledgement @@ -176,6 +196,8 @@ widget reuses the placement's existing - **THEN** the alert MUST update to reflect overdue status (red styling + revised copy) +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no deadline alert with an overdue state. + ### REQ-CAP-006: The portfolio filter SHALL scope the widget's queries server-side, not client-side (Specter acceptance) `content.portfolioFilter` MUST be passed as a GraphQL variable on @@ -193,6 +215,8 @@ client-side filter MUST NOT replace the server-side variable. - **AND** the GraphQL document MUST reference the variable in its argument list +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no widget query carrying a `portfolioFilter` variable. + #### Scenario: Cleared filter widens result set (Specter source) - **GIVEN** a portfolio filter is active @@ -202,6 +226,8 @@ client-side filter MUST NOT replace the server-side variable. - **AND** the dashboard cards MUST update to reflect every portfolio the viewer can read +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no portfolio filter control or query to re-issue. + #### Scenario: Summary metrics reflect filter (Specter source) - **GIVEN** multiple portfolios exist AND the filter is applied @@ -209,6 +235,8 @@ client-side filter MUST NOT replace the server-side variable. - **THEN** the audit-trail count, retention bucket counts, and evidence count MUST reflect only the selected portfolio's data +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There are no audit, retention or evidence cards whose counts could be filtered. + ### REQ-CAP-007: The evidence card SHALL surface docudesk-attached compliance documents via OR's `object-interactions` The evidence card MUST list compliance documents attached to OR @@ -224,6 +252,8 @@ endpoints directly — uploads stay with docudesk. - **THEN** the evidence card MUST list each document with title + attachment date + framework tag +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There is no evidence card and no object-interactions files query. + #### Scenario: Click deep-links to docudesk - **GIVEN** an evidence row @@ -231,6 +261,8 @@ endpoints directly — uploads stay with docudesk. - **THEN** the browser MUST navigate to the docudesk viewer URL (resolved via OR's deep-link registry) +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There are no evidence rows to click and no deep-link resolution for them. + #### Scenario: Read-only evidence - **GIVEN** the compliance-audit widget source files @@ -238,6 +270,8 @@ endpoints directly — uploads stay with docudesk. `/apps/docudesk/` - **THEN** zero matches MUST exist +@e2e exclude never built: `launchpad_compliance_audit` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither it nor a `compliance-audit` type key is in widgetRegistry.js, src/manifest.json or lib/widget-types.json (the only `compliance-audit` string under src/ is a doc comment in src/modals/AcknowledgementReportModal.vue). No unit or Newman test covers it either. There are no widget source files to scan; the clause is a static source scan, not browser behaviour. + ## Non-Functional Requirements - **Performance:** All cards SHOULD render their initial payload diff --git a/openspec/specs/launchpad-enterprise-security-access/screens.md b/openspec/specs/launchpad-enterprise-security-access/screens.md new file mode 100644 index 000000000..8ce5b3fa4 --- /dev/null +++ b/openspec/specs/launchpad-enterprise-security-access/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement diff --git a/openspec/specs/launchpad-enterprise-security-access/spec.md b/openspec/specs/launchpad-enterprise-security-access/spec.md index b56318a1b..34c0d3a71 100644 --- a/openspec/specs/launchpad-enterprise-security-access/spec.md +++ b/openspec/specs/launchpad-enterprise-security-access/spec.md @@ -237,6 +237,8 @@ event table. - **THEN** the dashboard MUST revert to the admin's own role on next sign-in (no preview persists across sessions) +@e2e exclude never built: `launchpad_security_access` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and is absent from widgetRegistry.js, src/manifest.json and lib/widget-types.json. No unit or Newman test covers it either. No view-as-another-role preview exists. + ## Non-Functional Requirements - **Performance:** Each card MUST query independently; one slow @@ -270,6 +272,3 @@ event table. - Nextcloud Authentication apps: `user_saml`, `twofactor_totp`, `twofactor_webauthn`. - WCAG 2.1 AA. - -@e2e exclude never built: `launchpad_security_access` appears in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and is absent from widgetRegistry.js, src/manifest.json and lib/widget-types.json. No unit or Newman test covers it either. No view-as-another-role preview exists. - diff --git a/openspec/specs/launchpad-file-access-widget/screens.md b/openspec/specs/launchpad-file-access-widget/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/launchpad-file-access-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/launchpad-file-access-widget/spec.md b/openspec/specs/launchpad-file-access-widget/spec.md index e62bce294..c85a72fe8 100644 --- a/openspec/specs/launchpad-file-access-widget/spec.md +++ b/openspec/specs/launchpad-file-access-widget/spec.md @@ -30,8 +30,6 @@ dossier document from dashboard). ## Requirements -@e2e exclude proposed/unimplemented widget — `launchpad_file_access` is not in widgetRegistry.js nor the manifest; no UI surface exists to drive. Scenarios assert registry/manifest contract, schema validation, Files OCS/WebDAV metadata routing, and Specter-sourced dossier-file rendering — backend/contract concerns belong in unit + Newman. Re-annotate with real UI tests when the widget is built. - ### REQ-FAW-001: The system SHALL register a `launchpad_file_access` widget type alongside the existing `files-widget` The widget MUST appear in `src/constants/widgetRegistry.js` as a @@ -43,6 +41,8 @@ always satisfied in practice; the declaration is for completeness. #### Scenario: Widget registered without colliding with `files-widget` +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. Only `files` is registered, and no test lists the other type. + - **GIVEN** the registry completeness test (REQ-WDG-023) - **WHEN** it runs - **THEN** both `files` and `file-access` MUST appear in @@ -52,6 +52,8 @@ always satisfied in practice; the declaration is for completeness. #### Scenario: Picker disambiguates the two types +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json, so the picker shows only the one Files type (`git log --all -S'Quick file access'` is empty). + - **GIVEN** the Add Widget modal type picker - **WHEN** rendered - **THEN** both types MUST list with distinct `displayName` @@ -72,12 +74,16 @@ The placement MUST persist `{type: 'file-access', content: {...}}` with: #### Scenario: Minimal `orObject` placement validates +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. There is no form and no content contract; `orObject` appears in history only in unrelated comment-manager code. + - **GIVEN** the content shape contract - **WHEN** `{type: 'file-access', content: {sourceMode: 'orObject', orObjectRef: {register: 'procest', schema: 'Case', objectId: 'case-1'}}}` is saved - **THEN** validation MUST pass #### Scenario: Cross-mode field is rejected +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. There is no form with a validate() to reject it, and no unit test. + - **GIVEN** `sourceMode === 'recent'` AND `fileIds = [42]` - **WHEN** `validate()` runs - **THEN** validation MUST return an error noting that `fileIds` @@ -100,6 +106,8 @@ where the placement-level toggles already exist per REQ-FLS-001.) #### Scenario: Metadata fetch routes through OCS +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. Nothing fetches file metadata by id list; the existing `files` widget lists a folder through LaunchPad's own backend and has its own files-widget spec. + - **GIVEN** `sourceMode === 'fileIds'` AND `fileIds = [123, 456]` - **WHEN** the widget mounts - **THEN** the renderer MUST issue OCS metadata requests for both @@ -107,6 +115,8 @@ where the placement-level toggles already exist per REQ-FLS-001.) #### Scenario: No launchpad file table +@e2e exclude never built, and a source inspection rather than a browser behaviour: the widget never shipped (`launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json). Checked by hand: no migration in lib/Migration creates a file metadata table. No test performs the check. + - **GIVEN** the launchpad migration files after this widget ships - **WHEN** inspected - **THEN** no migration introducing a file metadata table MUST @@ -114,6 +124,8 @@ where the placement-level toggles already exist per REQ-FLS-001.) #### Scenario: No write call to Files +@e2e exclude never built, and a source scan rather than a browser behaviour: the widget source files it would scan do not exist (`launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json). No test performs the scan. + - **GIVEN** the file-access widget source files - **WHEN** scanned for HTTP method `POST` / `PUT` / `DELETE` to `/dav/files/` or `/apps/files/api` @@ -129,6 +141,8 @@ same OCS metadata fetch as REQ-FAW-003. #### Scenario: Dossier files surface (Specter source) +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. Nothing reads an OpenRegister object's attached files into a widget, and the CI fixture has no procest register to hold one. + - **GIVEN** an OR object `{register: 'procest', schema: 'Case', objectId: 'case-1'}` with 3 attached documents - **WHEN** the widget renders - **THEN** the widget MUST list those 3 documents with their titles @@ -136,6 +150,8 @@ same OCS metadata fetch as REQ-FAW-003. #### Scenario: Click opens the document viewer (Specter source) +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json, so there is no dossier document to click. Opening a file from the existing `files` widget is a different widget and mechanism (nc-vue useFileOpener, OCA.Viewer or the `/f/{fileid}` permalink), which belongs to files-widget::click-file-to-open-in-files-app. + - **GIVEN** a clickable document on the dashboard - **WHEN** the viewer clicks it - **THEN** the document MUST open in the Nextcloud document viewer @@ -151,6 +167,8 @@ NOT throw — other rows MUST keep rendering. #### Scenario: Access denied row (Specter source) +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. The "No access" row text appears in no commit (`git log --all -S'No access' -- src lib appinfo templates` is empty). + - **GIVEN** a placement with `fileIds = [999]` AND the viewer has no read access to file 999 - **WHEN** the widget renders @@ -161,6 +179,8 @@ NOT throw — other rows MUST keep rendering. #### Scenario: Partial denial keeps other rows +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. There is no per-file-id row list to deny in part. + - **GIVEN** `fileIds = [123, 999, 456]` where 999 is denied - **WHEN** the widget renders - **THEN** rows for 123 and 456 MUST render normally @@ -168,6 +188,8 @@ NOT throw — other rows MUST keep rendering. #### Scenario: Deleted file shows missing state +@e2e exclude never built: `launchpad_file_access` and `file-access` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. The widget's "File not found" row does not exist; the string appears in history only in CLI import commands. + - **GIVEN** a file ID that no longer exists in Nextcloud - **WHEN** the widget renders - **THEN** the row MUST display `t('launchpad', 'File not found')` diff --git a/openspec/specs/launchpad-meeting-calendar-actions/screens.md b/openspec/specs/launchpad-meeting-calendar-actions/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/launchpad-meeting-calendar-actions/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/launchpad-meeting-calendar-actions/spec.md b/openspec/specs/launchpad-meeting-calendar-actions/spec.md index 281f0637e..33f8c082e 100644 --- a/openspec/specs/launchpad-meeting-calendar-actions/spec.md +++ b/openspec/specs/launchpad-meeting-calendar-actions/spec.md @@ -35,8 +35,6 @@ annotate agenda items on dashboard). ## Requirements -@e2e exclude proposed/unimplemented widget — `launchpad_meeting_actions` is not in widgetRegistry.js nor the manifest; no UI surface exists to drive. Scenarios assert registry/manifest contract, schema validation, DAV calendar reads, decidesk presence/absence gating, and Specter-sourced annotation flows — backend/contract concerns belong in unit + Newman. Re-annotate with real UI tests when the widget is built. - ### REQ-MCA-001: The system SHALL register a `launchpad_meeting_actions` widget type distinct from `calendar-widget` The widget MUST appear in `src/constants/widgetRegistry.js` and the @@ -49,6 +47,8 @@ types fulfil different use-cases (broad calendar view vs governance #### Scenario: Both calendar widget types registered +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. Only `calendar` is registered, and no test lists the other type. + - **GIVEN** the registry completeness test - **WHEN** it runs - **THEN** both `calendar` and `meeting-actions` MUST appear in @@ -58,6 +58,8 @@ types fulfil different use-cases (broad calendar view vs governance #### Scenario: Widget appears in the Add modal +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json, so the type picker cannot offer it (`git log --all -S'Meetings & actions'` is empty too). + - **GIVEN** the Add Widget modal type picker - **WHEN** rendered - **THEN** `Meetings & actions` MUST be selectable @@ -77,6 +79,8 @@ The placement MUST persist `{type: 'meeting-actions', content: {...}}` with: #### Scenario: Minimal placement validates +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. There is no form and no content contract for the type. + - **GIVEN** the content shape - **WHEN** `{type: 'meeting-actions', content: {daysAhead: 7}}` is saved - **THEN** validation MUST pass @@ -84,6 +88,8 @@ The placement MUST persist `{type: 'meeting-actions', content: {...}}` with: #### Scenario: Negative `daysAhead` rejected +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. There is no form with a validate() to reject it, and no unit test. + - **GIVEN** `content.daysAhead = -1` - **WHEN** `validate()` runs - **THEN** validation MUST return an error @@ -100,6 +106,8 @@ convention. #### Scenario: DAV query issued on mount +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. The existing `calendar` widget is not this: it reads events from LaunchPad's own `GET /api/widgets/calendar/{placementId}/events` (src/services/widgetDataAdapters.js), not a CalDAV REPORT from the browser; it has its own calendar-widget spec. + - **GIVEN** the widget mounts with default `calendarSources` - **WHEN** the renderer queries - **THEN** a CalDAV `REPORT` MUST be issued against the viewer's @@ -108,6 +116,8 @@ convention. #### Scenario: No launchpad event table +@e2e exclude never built, and a source inspection rather than a browser behaviour: the widget never shipped (`launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json). Checked by hand: no migration in lib/Migration creates an event, calendar or meeting table. No test performs the check. + - **GIVEN** the launchpad migrations after this widget ships - **WHEN** inspected - **THEN** no migration adding an event / calendar / meeting @@ -125,6 +135,8 @@ inline info chip: #### Scenario: decidesk present surfaces meetings inline +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. No launchpad code queries decidesk; the only `decidesk` hits under src and lib are the fleet app-id alias in lib/Support/FleetAppId.php and a template test fixture. decidesk is not in the CI fixture either. + - **GIVEN** decidesk is installed AND has 2 upcoming meetings in the window - **WHEN** the widget renders @@ -133,6 +145,8 @@ inline info chip: #### Scenario: decidesk absent falls back gracefully +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. The info chip text (`git log --all -S'Decidesk meetings unavailable'`) appears in no commit. + - **GIVEN** decidesk is not installed - **WHEN** the widget renders - **THEN** the DAV calendar events MUST still render @@ -148,6 +162,8 @@ MUST NOT mirror annotation state. #### Scenario: Annotation save (Specter source) +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. No code under src or lib issues a decidesk agenda-item mutation; the `annotation` hits in history are MCP tool annotations and the generated openapi.json, not this widget. + - **GIVEN** an agenda item is visible on the dashboard - **WHEN** the viewer adds an annotation - **THEN** the annotation MUST persist via a GraphQL mutation to @@ -157,6 +173,8 @@ MUST NOT mirror annotation state. #### Scenario: Annotation edit reflects immediately (Specter source) +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. There is no annotation control to edit. + - **GIVEN** an annotated agenda item on the dashboard - **WHEN** the viewer edits the annotation - **THEN** the updated text MUST reflect immediately without a @@ -165,6 +183,8 @@ MUST NOT mirror annotation state. #### Scenario: Annotation removal (Specter source) +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. There is no annotation control to remove. + - **GIVEN** an annotated agenda item - **WHEN** the viewer removes the annotation - **THEN** the annotation MUST be deleted via a GraphQL mutation @@ -173,6 +193,8 @@ MUST NOT mirror annotation state. #### Scenario: decidesk absent disables annotation control +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. There is no annotation control, so its absence on DAV events cannot fail. + - **GIVEN** decidesk is not installed AND `showAnnotations === true` - **WHEN** the widget renders DAV events - **THEN** the annotation control MUST NOT surface on DAV events @@ -189,6 +211,8 @@ own responsibility per its CalDAV integration spec. #### Scenario: Duplicate event dedup +@e2e exclude never built: `launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json. `X-DECIDESK-MEETING-ID` appears in no commit (`git log --all -S`), and nothing joins DAV events with decidesk meetings. + - **GIVEN** a decidesk meeting `m-1` exists both as a decidesk meeting and as a DAV event with `X-DECIDESK-MEETING-ID: m-1` - **WHEN** the timeline renders @@ -198,6 +222,8 @@ own responsibility per its CalDAV integration spec. #### Scenario: No launchpad↔decidesk link mutation +@e2e exclude never built, and a source scan rather than a browser behaviour: the widget source files it would scan do not exist (`launchpad_meeting_actions` and `meeting-actions` appear in no commit on any branch under src, lib, appinfo or templates (`git log --all -S`), and neither is in src/constants/widgetRegistry.js, lib/widget-types.json, nc-vue's registry or src/manifest.json). No test performs the scan. + - **GIVEN** the widget source files - **WHEN** scanned for POST/PUT to `/apps/decidesk/.*link` or `/apps/decidesk/.*calendar` diff --git a/openspec/specs/launchpad-mobile-remote-access/screens.md b/openspec/specs/launchpad-mobile-remote-access/screens.md new file mode 100644 index 000000000..87dfce8ba --- /dev/null +++ b/openspec/specs/launchpad-mobile-remote-access/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpMobiel https://identity.conduction.nl/screens/board?id=launchpad/LpMobiel diff --git a/openspec/specs/launchpad-mobile-remote-access/spec.md b/openspec/specs/launchpad-mobile-remote-access/spec.md index bfbd95842..7fc2b815d 100644 --- a/openspec/specs/launchpad-mobile-remote-access/spec.md +++ b/openspec/specs/launchpad-mobile-remote-access/spec.md @@ -40,8 +40,6 @@ remote/mobile access + curated app + news access). ## Requirements -@e2e exclude proposed/unimplemented capability — adds a `mobileReady` registry/manifest field + mobile-breakpoint hide/force-desktop behaviour that is not yet built. Scenarios assert registry/manifest completeness contract, viewport-driven visibility, session-expiry from Specter sources, and curated-app/news sourcing — backend/contract and breakpoint internals belong in unit + Newman. Re-annotate with real UI tests when the capability ships. - ### REQ-MRA-001: Every widget registry entry SHALL declare a `mobileReady` boolean `src/constants/widgetRegistry.js` entries MUST extend the existing @@ -53,6 +51,8 @@ cannot render on mobile (e.g. complex multi-column tables) MUST set #### Scenario: Registry entry missing the field fails the completeness test +@e2e exclude not built as specified: `mobileReady` exists since phone-hidden-widgets-named (archived 2026-11-24), but only `ai-assistant` declares it (src/constants/widgetRegistry.js) and an entry without it counts as phone-ready (src/utils/phoneHiddenWidgets.js isPhoneReady). No completeness test requires the field, and that test would be a vitest, not a browser behaviour. + - **GIVEN** a registry entry omits `mobileReady` - **WHEN** `npm test` runs the completeness test - **THEN** the test MUST fail with a message naming the type @@ -60,6 +60,8 @@ cannot render on mobile (e.g. complex multi-column tables) MUST set #### Scenario: Every shipped widget declares the field +@e2e exclude not built as specified: `mobileReady` exists since phone-hidden-widgets-named (archived 2026-11-24), but only `ai-assistant` declares it (src/constants/widgetRegistry.js) and an entry without it counts as phone-ready (src/utils/phoneHiddenWidgets.js isPhoneReady). The canonical widgets do not carry the field, and no test checks for it; a registry inspection, not a browser behaviour, in any case. + - **GIVEN** the canonical widget set (`calendar`, `container`, `divider`, `files`, `header`, `image`, `label`, `link`, `links`, `menu`, `nc-widget`, `news`, `people`, `quicklinks`, `text`, `tile`, @@ -79,6 +81,8 @@ extension). #### Scenario: Manifest declaration matches registry +@e2e exclude never built: src/manifest.json has no top-level widgets[] since 2cf53831 and does not mention `mobileReady`, and scripts/check-manifest.js compares no such field; a CLI check in any case. + - **GIVEN** the registry sets `tile.mobileReady = true` - **WHEN** `npm run check:manifest` runs - **THEN** the manifest entry for `tile` MUST also set @@ -86,6 +90,8 @@ extension). #### Scenario: Mismatch fails the check +@e2e exclude never built: scripts/check-manifest.js has no registry comparison and does not mention `mobileReady`, and there is no `compliance-audit` widget type; a CLI check in any case. + - **GIVEN** the registry sets `compliance-audit.mobileReady = false` - **AND** the manifest sets `compliance-audit.mobileReady = true` - **WHEN** `npm run check:manifest` runs @@ -117,6 +123,8 @@ the desktop breakpoint at the cost of horizontal scroll). #### Scenario: Force desktop layout link +@e2e exclude withdrawn by REQ-MRA-007, which replaces the "view desktop layout" link and says there SHALL be no forced desktop layout on a phone. phone-hidden-widgets-named.spec.ts asserts no desktop-layout link is shown (pieter-on-his-phone). + - **GIVEN** the mobile notice is visible - **WHEN** the viewer clicks "view desktop layout" - **THEN** the workspace MUST switch to the desktop grid layout @@ -132,6 +140,8 @@ switcher, or any non-grid affordance. #### Scenario: All non-mobile dashboard shows empty-state +@e2e exclude never built: phones hide `mobileReady: false` widgets since phone-hidden-widgets-named, but no empty-state exists for a dashboard where every widget is hidden: "no mobile-ready widgets" appears nowhere in src, and REQ-MRA-007 removed the desktop-layout CTA it would point at. + - **GIVEN** a dashboard where all 4 placements have `mobileReady: false` - **WHEN** the viewport is 375 px @@ -142,6 +152,8 @@ switcher, or any non-grid affordance. #### Scenario: Other affordances stay live +@e2e exclude never built: its GIVEN is the phone empty-state of REQ-MRA-004, which does not exist (see the scenario above). The dashboard switcher itself is cited by the dashboard-switcher specs. + - **GIVEN** the empty-state is rendered - **WHEN** the viewer opens the dashboard switcher - **THEN** the switcher MUST function normally @@ -161,6 +173,8 @@ MUST resume without losing in-progress widget state. #### Scenario: Session expires (Specter source) +@e2e exclude nothing in launchpad to test, and the fixture cannot expire a session: launchpad has no session or heartbeat code (grep of src for heartbeat or re-auth finds only the dashboard edit-lock heartbeat), so the overlay is Nextcloud core's own. Driving it needs `session_lifetime` shortened in config.php or via occ, which the CI fixture does not do. No unit test either. + - **GIVEN** a remote employee authenticated AND the session is idle past the Nextcloud-configured timeout - **WHEN** the next heartbeat fires @@ -170,6 +184,8 @@ MUST resume without losing in-progress widget state. #### Scenario: No launchpad-local timer +@e2e exclude a source scan, not a browser behaviour, and no test performs it. Checked by hand: the only setInterval near a session in src is useDashboardLock.js, which renews a dashboard edit lock and never logs out or redirects. + - **GIVEN** the workspace shell source files - **WHEN** scanned for `setTimeout` / `setInterval` calls that trigger logout, redirect, or session-end @@ -178,6 +194,8 @@ MUST resume without losing in-progress widget state. #### Scenario: Re-auth preserves in-progress state +@e2e exclude needs an expired session, which the CI fixture cannot produce (see Session expires above), and launchpad has no re-auth handling of its own to test. No unit test either. + - **GIVEN** a viewer is editing a widget's config when the session expires - **WHEN** the re-auth overlay completes successfully @@ -203,6 +221,8 @@ policy" table — the per-role visibility engine already exists. #### Scenario: News feed via existing news capability (Specter source) +@e2e exclude needs an external service the CI fixture lacks: the news widget fetches feeds server-side, https only (NewsWidgetService::isHttpsUrl), from an allow-listed host, and CI has no https feed host Nextcloud can reach. Role scoping by a visibility rule is the same mechanism the curated-app-list test proves; the news rendering itself belongs to the news-widget spec. + - **GIVEN** a `news-widget` is placed AND scoped per role - **WHEN** the employee opens the dashboard - **THEN** the news feed MUST render via that widget — no new @@ -210,11 +230,35 @@ policy" table — the per-role visibility engine already exists. #### Scenario: No launchpad-local mobile-policy table +@e2e exclude a source inspection, not a browser behaviour, and no test performs it. Checked by hand: no file in lib/Migration mentions a mobile policy or app whitelist. + - **GIVEN** the launchpad migrations after this widget ships - **WHEN** inspected - **THEN** no migration introducing a "mobile policy" / "mobile app whitelist" / "mobile news policy" table MUST exist +### Requirement: The phone notice names the hidden widgets (REQ-MRA-007) + +When widgets are hidden on a phone (REQ-MRA-003), the notice at the top of the workspace SHALL say how many and name +them by title: "2 widgets do not work on a phone and are hidden: Snel beginnen (Word) and Assistent." (nl "2 widgets +werken niet op een telefoon en zijn verborgen: ..."), followed by a link "Which?" ("Welke?") that explains why a widget +can be hidden on a phone and that the person sees it on a larger screen. The notice SHALL replace the "view desktop +layout" link of REQ-MRA-003; there SHALL be no forced desktop layout on a phone. With more than three hidden widgets +the notice SHALL name three and count the rest. + +#### Scenario: Pieter on his phone + +- **GIVEN** Mijn werkplek holds Snel beginnen and Assistent, neither ready for a phone +- **WHEN** Pieter opens it at 390 px +- **THEN** the notice reads "2 widgets werken niet op een telefoon en zijn verborgen: Snel beginnen (Word) en Assistent." with the link "Welke?" +- **AND** no "view desktop layout" link is shown + +#### Scenario: Many hidden widgets + +- **GIVEN** five widgets on a dashboard are not ready for a phone +- **WHEN** it opens at 390 px +- **THEN** the notice names three of them and says "and 2 more" + ## Non-Functional Requirements - **Performance:** Breakpoint switches MUST re-render the grid diff --git a/openspec/specs/launchpad-spend-analytics-widget/screens.md b/openspec/specs/launchpad-spend-analytics-widget/screens.md new file mode 100644 index 000000000..8ce5b3fa4 --- /dev/null +++ b/openspec/specs/launchpad-spend-analytics-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement diff --git a/openspec/specs/launchpad-spend-analytics-widget/spec.md b/openspec/specs/launchpad-spend-analytics-widget/spec.md index d01fc47ae..0d90a72d5 100644 --- a/openspec/specs/launchpad-spend-analytics-widget/spec.md +++ b/openspec/specs/launchpad-spend-analytics-widget/spec.md @@ -31,9 +31,7 @@ feature. ## Requirements -@e2e exclude proposed/unimplemented widget — `launchpad_spend_analytics` is not in widgetRegistry.js nor the manifest; no UI surface exists to drive. Scenarios assert registry/manifest contract, schema validation, financeq/procest GraphQL routing, openconnector narrative gating, deep-links, and Specter-sourced rendering — backend/contract concerns belong in unit + Newman. Re-annotate with real UI tests when the widget is built. - -### REQ-SAW-001: The system SHALL register a `launchpad_spend_analytics` widget type discoverable via the unified Add Widget modal +### Requirement: REQ-SAW-001: The system SHALL register a `launchpad_spend_analytics` widget type discoverable via the unified Add Widget modal The widget MUST appear in `src/constants/widgetRegistry.js` (per the widgets capability REQ-WDG-014 single-source-of-truth rule) and MUST @@ -45,6 +43,8 @@ the runtime GraphQL endpoints it consumes — never an entry in #### Scenario: Widget type listed in registry completeness test +@e2e exclude unit-only: this scenario is a vitest, not a browser behaviour. src/constants/__tests__/widgetRegistry.completeness.spec.js pins `spend-analytics` in EXPECTED_TYPES (read from lib/widget-types.json) with non-null form, renderer, displayName, defaultContent and icon, and widgetRegistry.spec.js pins the LaunchPad form override. The `requires` clause differs from the text: the communal entry (nc-vue CnSpendAnalyticsWidget/index.js) declares `{graphql: ['financeq', 'procest']}`, not `financeq.transactions` / `procest.cases`, and no test asserts it. + - **GIVEN** the registry completeness test (REQ-WDG-023 EXPECTED_TYPES) - **WHEN** the test runs - **THEN** `spend-analytics` MUST appear in EXPECTED_TYPES @@ -61,7 +61,7 @@ the runtime GraphQL endpoints it consumes — never an entry in type - **AND** selecting it MUST mount the `SpendAnalyticsForm` sub-form -### REQ-SAW-002: The widget SHALL declare a `launchpad_spend_analytics` entry in `src/manifest.json` with a soft `requires` clause +### Requirement: REQ-SAW-002: The widget SHALL declare a `launchpad_spend_analytics` entry in `src/manifest.json` with a soft `requires` clause The manifest entry MUST live in `widgets[]` (per ADR-024 + the launchpad widget convention). It MUST set `requires.graphql` listing the @@ -72,6 +72,8 @@ behaviour, not install. #### Scenario: Manifest entry present and soft-required +@e2e exclude built and removed: 7d7da1bb added a `launchpad_spend_analytics` entry to the v1 top-level `widgets[]` of src/manifest.json, and 2cf53831 deleted that block in the v2 manifest migration (the widget is now registered in the JS registry only). There is no manifest entry to assert, in e2e or anywhere else; the scenario text is out of date. + - **GIVEN** the launchpad manifest at `src/manifest.json` - **WHEN** parsed - **THEN** `manifest.widgets[].find(w => w.id === 'launchpad_spend_analytics')` MUST exist @@ -81,12 +83,14 @@ behaviour, not install. #### Scenario: Manifest validation passes +@e2e exclude CLI, not a browser behaviour: `npm run check:manifest` (scripts/check-manifest.js) runs in `npm run lint`. Its premise is gone too: 2cf53831 removed the spend-analytics manifest entry, so the check validates a manifest without one. + - **GIVEN** `npm run check:manifest` is wired per ADR-024 §5 - **WHEN** the script runs - **THEN** the manifest MUST pass schema validation with the spend-analytics widget entry present -### REQ-SAW-003: The widget content shape SHALL be the persisted JSON contract for placements +### Requirement: REQ-SAW-003: The widget content shape SHALL be the persisted JSON contract for placements The placement MUST persist `{type: 'spend-analytics', content: {...}}` in `oc_launchpad_widget_placements.content` (per the widgets capability REQ-WDG-010 emit shape). The `content` object MUST carry: @@ -111,12 +115,14 @@ REQ-WDG-010 emit shape). The `content` object MUST carry: #### Scenario: Invalid viewMode rejected +@e2e exclude unreachable from the UI and pinned by no test: CnSpendAnalyticsWidgetForm offers only the four valid view modes in its select and its data() coerces a stored out-of-enum `viewMode` to `summary`, so no person can put `forecast` into the form for validate() to reject. No vitest covers validate() since the launchpad form spec went away with b67cd6a9 (the renderer and form moved to nc-vue, whose tree has no spend test). + - **GIVEN** the form attempts to save `content.viewMode = 'forecast'` - **WHEN** `validate()` runs - **THEN** validation MUST return a non-empty error array - **AND** the modal MUST keep the Add/Save button disabled -### REQ-SAW-004: The widget SHALL fetch spend data via runtime GraphQL against financeq + procest +### Requirement: REQ-SAW-004: The widget SHALL fetch spend data via runtime GraphQL against financeq + procest The renderer MUST issue GraphQL operations to the sibling apps' OR-mounted `/graphql` endpoints via the shared client from @@ -146,6 +152,8 @@ NOT call OR endpoints directly via `axios` from launchpad code. #### Scenario: No direct axios to sibling apps +@e2e exclude a source scan, not a browser behaviour, and no test performs it. The only launchpad code that calls a sibling app is queryGraphql in src/services/graphqlClient.js (axios POST to `/apps/{app}/graphql`), pinned by src/services/__tests__/graphqlClient.spec.js and queryGraphql.golden.spec.js; spendAnalytics.spec.js pins that financeq and procest go through it. + - **GIVEN** the spend-analytics renderer source files - **WHEN** scanned for `axios` / `fetch(` calls targeting `/index.php/apps/financeq/`, `/apps/procest/`, `/apps/shillinq/`, @@ -153,7 +161,7 @@ NOT call OR endpoints directly via `axios` from launchpad code. - **THEN** zero matches MUST exist — every cross-app call MUST route through the shared GraphQL client -### REQ-SAW-005: The widget SHALL render an empty-state without throwing when a required sibling app is absent +### Requirement: REQ-SAW-005: The widget SHALL render an empty-state without throwing when a required sibling app is absent When any required GraphQL endpoint returns 404 (sibling app not installed) or an empty result, the widget MUST render an empty-state panel naming the missing source and a hint for the admin. The @@ -187,7 +195,7 @@ client-side (install is an admin action). - **AND** the vendor breakdown panel MUST render its own empty-state inline without disabling the rest of the widget -### REQ-SAW-006: The widget SHALL surface AI-generated narrative via the openconnector LLM source — never a direct LLM client in launchpad +### Requirement: REQ-SAW-006: The widget SHALL surface AI-generated narrative via the openconnector LLM source — never a direct LLM client in launchpad When `content.aiInsights.enabled === true`, the widget MUST issue an inference call through the openconnector LLM source registered as @@ -208,6 +216,8 @@ pattern from `project_ai-chat-companion-end-to-end` (ADR-034 chain). #### Scenario: openconnector absent disables AI panel gracefully +@e2e exclude never built: the toggle has no tooltip and knows nothing of the source. CnSpendAnalyticsWidgetForm renders a plain checkbox; the renderer only learns the source is missing after the viewer clicks the panel's Generate button and the call has been sent. Neither 7d7da1bb nor the nc-vue form ever checked the `local-llm` source before the toggle (`git log --all -S'local-llm' -- src` shows only the data-layer commits). The data-layer half (a 404 maps to `available: false`) is pinned by src/services/__tests__/spendAnalytics.spec.js. + - **GIVEN** openconnector is not installed or the `local-llm` source is not configured - **WHEN** the user toggles `aiInsights.enabled` @@ -219,12 +229,14 @@ pattern from `project_ai-chat-companion-end-to-end` (ADR-034 chain). #### Scenario: No LLM SDK import +@e2e exclude a source scan, not a browser behaviour: src/components/Widgets/Renderers/__tests__/noModelClient.spec.js fails on any import of openai, @anthropic-ai, @ollama or llphant, or a localhost:11434 string, anywhere in launchpad src/. The renderer itself now lives in nc-vue, which that scan does not read. + - **GIVEN** the spend-analytics widget source files - **WHEN** scanned for `import ... from '@ollama/'`, `from 'openai'`, `from '@anthropic-ai/'`, or `LLPhant` - **THEN** zero matches MUST exist -### REQ-SAW-007: Drill-through SHALL navigate to the sibling app's detail surface — launchpad MUST NOT mirror sibling-app pages +### Requirement: REQ-SAW-007: Drill-through SHALL navigate to the sibling app's detail surface — launchpad MUST NOT mirror sibling-app pages Clicking a row in the widget (transaction, vendor, case) MUST navigate via deep-link to the owning sibling app's detail surface @@ -242,6 +254,8 @@ data. #### Scenario: Transaction row click deep-links to financeq +@e2e exclude never built: the summary view has no transaction list and no transaction rows; CnSpendAnalyticsWidget links only category rows (financeq) and vendor rows (procest). No commit ever rendered transaction rows: the original renderer in 7d7da1bb drilled only into `category` and `vendor`. + - **GIVEN** the `summary` view's drill-through opens a transaction list - **WHEN** the user clicks a transaction row @@ -250,6 +264,8 @@ data. #### Scenario: drillThroughTarget=detail-page renders launchpad overlay +@e2e exclude never built: `drillThroughTarget` is read only by the form; CnSpendAnalyticsWidget never reads it and always renders rows as plain links, and the 7d7da1bb renderer did the same. `git log --all -S'drillThroughTarget' -- src lib` finds only 7d7da1bb, fda6bd06 and 8e0488cf, none with an overlay. No unit test either. + - **GIVEN** `content.drillThroughTarget === 'detail-page'` (the default — for users who prefer staying in launchpad) - **WHEN** the user clicks a row @@ -258,7 +274,7 @@ data. cell — still served by the sibling app's GraphQL, not a launchpad copy -### REQ-SAW-008: Evidence attachments SHALL be consumed via OR's `object-interactions` integration registry +### Requirement: REQ-SAW-008: Evidence attachments SHALL be consumed via OR's `object-interactions` integration registry When `content.attachEvidence === true`, each spend row (transaction, case) MUST surface its docudesk-attached evidence (invoices, contracts) using OR's `object-interactions` files integration per @@ -268,6 +284,8 @@ the sibling app's responsibility. #### Scenario: Evidence files surface inline +@e2e exclude never built: `attachEvidence` is read only by the form; no renderer, past or present, shows evidence chips or queries docudesk (`git log --all -S'attachEvidence' -- src lib` finds only 7d7da1bb, fda6bd06 and 8e0488cf, all form or registry code). No unit test either. + - **GIVEN** a transaction with 2 docudesk-attached invoices - **WHEN** the widget renders the transaction row with `attachEvidence === true` @@ -278,6 +296,8 @@ the sibling app's responsibility. #### Scenario: Evidence widget is read-only +@e2e exclude never built, and a source scan rather than a browser behaviour: there is no evidence code to scan. No launchpad or nc-vue spend file names `/apps/docudesk/` at all, and no test performs the scan. + - **GIVEN** the spend-analytics widget source files - **WHEN** scanned for HTTP method `POST` / `PUT` / `DELETE` against paths matching `/apps/docudesk/` @@ -285,6 +305,8 @@ the sibling app's responsibility. #### Scenario: No evidence attached +@e2e exclude never built: there are no transaction rows and no evidence area in CnSpendAnalyticsWidget, so there is no slot whose absence could be observed. No unit test either. + - **GIVEN** a transaction with zero attached evidence - **WHEN** the row renders - **THEN** the evidence area MUST be hidden (no empty chip slot) diff --git a/openspec/specs/legacy-widget-bridge/screens.md b/openspec/specs/legacy-widget-bridge/screens.md new file mode 100644 index 000000000..8844e84cc --- /dev/null +++ b/openspec/specs/legacy-widget-bridge/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWidgetKiezen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetKiezen +- LpBeheerOnderhoud https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerOnderhoud diff --git a/openspec/specs/legacy-widget-bridge/spec.md b/openspec/specs/legacy-widget-bridge/spec.md index 52821eed2..910033eca 100644 --- a/openspec/specs/legacy-widget-bridge/spec.md +++ b/openspec/specs/legacy-widget-bridge/spec.md @@ -21,8 +21,6 @@ The bridge holds two in-memory maps on a singleton: Both maps persist for the lifetime of the page. Registration is additive — re-registering an appId overwrites the previous callback. ## Requirements -@e2e exclude purely client-side JavaScript bridge for legacy OCA.Dashboard.register() — no Playwright-observable DOM surface; bridge internals tested by Vitest unit tests - ### Requirement: Intercept legacy widget registration at bootstrap (REQ-LWB-001) The system MUST intercept calls to `window.OCA.Dashboard.register` and `window.OCA.Dashboard.registerStatus` made by legacy Nextcloud widgets so that their render callbacks can be captured for later mounting by LaunchPad. Interception is installed once when the bridge singleton is constructed. The system MUST preserve any previously installed `register` / `registerStatus` implementation so that Nextcloud code that depends on the original registrar continues to work. @@ -41,6 +39,8 @@ The system MUST intercept calls to `window.OCA.Dashboard.register` and `window.O - THEN the system MUST store the `("user_status", callback)` pair in a separate status-callback map - AND the system MUST invoke any previously installed `registerStatus` handler +@e2e exclude the status-callback map is private to the module-scoped widgetBridge singleton and nothing in src/ reads it (`mountStatusWidget` has no caller), so a browser cannot observe the stored pair. The forwarding to a previously installed `registerStatus` is observable and tests/e2e/legacy-widget-bridge.spec.ts asserts it, uncited, in the capture-a-regular-widget-callback test. No unit test pins the capture: src/services/__tests__/widgetBridge.spec.js seeds `statusCallbacks` directly. + #### Scenario: Initialise OCA namespace when missing - GIVEN `window.OCA` or `window.OCA.Dashboard` does not yet exist at construction time @@ -67,6 +67,8 @@ The system MUST provide a way for LaunchPad to render a legacy widget by invokin - THEN the system MUST NOT clear the container - AND the system MUST emit a diagnostic `console.warn` naming the missing widgetId +@e2e exclude WidgetRenderer only calls `widgetBridge.mountWidget` after `hasWidgetCallback` returns true (`tryMountLegacyWidget` in src/components/WidgetRenderer.vue), so the product never reaches the warn branch from a browser; an unregistered legacy placement retries and logs `[WidgetRenderer] Failed to mount widget` instead. No unit test pins the warn branch. + #### Scenario: Registered callback throws during rendering - GIVEN a registered callback for `"broken"` throws on invocation @@ -85,6 +87,8 @@ The system MUST provide a way to render a legacy status widget. Status widgets d - THEN the system MUST clear the container - AND the system MUST invoke the callback as `callback(containerEl)` with a single argument +@e2e exclude `mountStatusWidget` has no caller anywhere in src/ (only its definition in src/services/widgetBridge.js), and the bridge singleton is module-private, so no page renders a status widget through it. The clearing clause is pinned by vitest src/services/__tests__/widgetBridge.spec.js 'removes the previous content before calling a status widget callback'; the single-argument call is pinned by no test. + #### Scenario: Mount request for an unregistered status widget - GIVEN no callback has been registered for a status widgetId @@ -92,6 +96,8 @@ The system MUST provide a way to render a legacy status widget. Status widgets d - THEN the system MUST NOT clear the container - AND the system MUST NOT emit a diagnostic warning +@e2e exclude `mountStatusWidget` has no caller anywhere in src/ (only its definition in src/services/widgetBridge.js), and the bridge singleton is module-private, so no page renders a status widget through it. No unit test pins the silent no-op. + #### Scenario: Status-widget callback throws during rendering - GIVEN a registered status-widget callback throws on invocation @@ -99,6 +105,8 @@ The system MUST provide a way to render a legacy status widget. Status widgets d - THEN the system MUST catch the error and log it together with the widgetId - AND the error MUST NOT propagate +@e2e exclude `mountStatusWidget` has no caller anywhere in src/ (only its definition in src/services/widgetBridge.js), and the bridge singleton is module-private, so no page renders a status widget through it. No unit test pins the catch. + **Notes**: The missing-callback behaviour differs between `mountWidget` (warn) and `mountStatusWidget` (silent). This is observed, not obviously intentional — status widgets may legitimately be absent on dashboards that do not request them, while regular widgets are usually explicit. Flagged for future REQ tightening once a call-site audit confirms the rationale. ### Requirement: Query widget-bridge registration state (REQ-LWB-004) @@ -113,6 +121,8 @@ The system MUST expose a way for LaunchPad render logic to query which widget ca - WHEN LaunchPad calls `hasWidgetCallback("weather_status")` - THEN the system MUST return `false` +@e2e exclude the bridge singleton is module-private and `hasWidgetCallback` is only read inside WidgetRenderer to decide whether to mount, so its return values are not observable from a browser (the true branch is exercised by the mount test in tests/e2e/legacy-widget-bridge.spec.ts, the false branch by nothing visible). No unit test pins the two return values directly; vitest src/services/__tests__/widgetBridge.spec.js only spies on it through `pollForCallback`. + #### Scenario: Enumerate all registered widget IDs - GIVEN callbacks have been registered for three widgets (`"notes"`, `"activity"`, `"recommendations"`) in that order @@ -120,6 +130,8 @@ The system MUST expose a way for LaunchPad render logic to query which widget ca - THEN the system MUST return an array containing exactly those three appIds - AND the order of appIds MUST reflect registration order (Map iteration order) +@e2e exclude the bridge singleton is module-private and `getRegisteredWidgetIds` is only read by debug log lines in WidgetRenderer (`mountLegacyWidget` / `reportLegacyMountFailure`, silent unless `launchpad:debug` is set), and the page's other widget bundles may register too, so an exact three-id list in order is not observable. No unit test pins it. + **Notes**: `hasWidgetCallback` and `getRegisteredWidgetIds` are combined into a single REQ because they expose the same read-only inspection capability over the widget-callback map. Status callbacks are not exposed via either query — the bridge does not currently need introspection on the status map. Noted for future REQ extension if that need arises. ### Requirement: Polling helper for late callback registration (REQ-LWB-005) @@ -135,6 +147,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - AND a `OCA.Dashboard.register('notes', cb)` call happens 600 ms later - THEN the promise MUST resolve `true` within ~800 ms (next poll tick after registration) +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-005: resolves true when callback registers mid-poll'. + #### Scenario: Resolve false on timeout - GIVEN no callback for `'fictional_widget'` is ever registered @@ -142,6 +156,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - THEN after ~3 seconds (15 x 200 ms) the promise MUST resolve `false` - AND no further interval ticks MUST fire +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-005: resolves false after timeout when nothing registers'; the no-further-ticks clause is asserted only by src/__tests__/widgetBridge.test.js 'stops polling after timeout — no further interval ticks fire', which tests an inline copy of the class, not the shipped module. + #### Scenario: Abort cancels polling - GIVEN a poll is in progress for `'notes'` @@ -150,6 +166,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - AND the underlying `setInterval` MUST be cleared - AND no further poll ticks MUST run +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-005: aborts immediately when the signal fires'; the interval-cleared clause is asserted only by src/__tests__/widgetBridge.test.js 'resolves false and clears interval when signal is aborted mid-poll', against an inline copy of the class. + #### Scenario: Already-registered callback resolves immediately - GIVEN a callback for `'notes'` IS already in the bridge map @@ -157,6 +175,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - THEN the promise MUST resolve `true` synchronously (or on the very next microtask) - AND no `setInterval` MUST be scheduled +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-006: synchronously resolves true when callback already registered'; the no-setInterval clause is asserted only by src/__tests__/widgetBridge.test.js 'does NOT start a setInterval when callback is already registered', against an inline copy of the class. + ### Requirement: hasWidgetCallback consistency (REQ-LWB-006) `hasWidgetCallback(widgetId)` (already declared in REQ-LWB-004) MUST return `true` if and only if `pollForCallback` would resolve `true` immediately. The polling helper MUST use `hasWidgetCallback` internally as its check function — there MUST NOT be two parallel "is registered" code paths. @@ -167,6 +187,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - THEN it MUST call `this.hasWidgetCallback(widgetId)` - AND the result of `hasWidgetCallback` and the poll's first synchronous check MUST agree +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-006: pollForCallback uses hasWidgetCallback as single source of truth'. + ### Requirement: REQ-LWB-005 Polling helper for late callback registration The bridge singleton MUST expose `pollForCallback(widgetId: string, options?: {intervalMs?: number, maxRetries?: number, signal?: AbortSignal}): Promise<boolean>` that periodically checks whether a callback has been registered for the given `widgetId`. Defaults: `intervalMs = 200`, `maxRetries = 15` (~3 s total). The promise MUST resolve to `true` as soon as a callback is detected, OR to `false` after the max retries are exhausted. Each call MUST be cancellable via the AbortSignal of an `AbortController` passed in `options.signal` (so callers can abort polling on unmount). @@ -180,6 +202,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - AND a `OCA.Dashboard.register('notes', cb)` call happens 600 ms later - THEN the promise MUST resolve `true` within ~800 ms (next poll tick after registration) +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-005: resolves true when callback registers mid-poll'. + #### Scenario: Resolve false on timeout - GIVEN no callback for `'fictional_widget'` is ever registered @@ -187,6 +211,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - THEN after ~3 seconds (15 x 200 ms) the promise MUST resolve `false` - AND no further interval ticks MUST fire +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-005: resolves false after timeout when nothing registers'; the no-further-ticks clause is asserted only by src/__tests__/widgetBridge.test.js 'stops polling after timeout — no further interval ticks fire', which tests an inline copy of the class, not the shipped module. + #### Scenario: Abort cancels polling - GIVEN a poll is in progress for `'notes'` @@ -195,6 +221,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - AND the underlying `setInterval` MUST be cleared - AND no further poll ticks MUST run +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-005: aborts immediately when the signal fires'; the interval-cleared clause is asserted only by src/__tests__/widgetBridge.test.js 'resolves false and clears interval when signal is aborted mid-poll', against an inline copy of the class. + #### Scenario: Already-registered callback resolves immediately - GIVEN a callback for `'notes'` IS already in the bridge map @@ -202,6 +230,8 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - THEN the promise MUST resolve `true` synchronously (or on the very next microtask) - AND no `setInterval` MUST be scheduled +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-006: synchronously resolves true when callback already registered'; the no-setInterval clause is asserted only by src/__tests__/widgetBridge.test.js 'does NOT start a setInterval when callback is already registered', against an inline copy of the class. + ### Requirement: REQ-LWB-006 hasWidgetCallback consistency `hasWidgetCallback(widgetId)` (already declared in REQ-LWB-004) MUST return `true` if and only if `pollForCallback` would resolve `true` immediately. The polling helper MUST use `hasWidgetCallback` internally as its check function — there MUST NOT be two parallel "is registered" code paths. @@ -212,3 +242,4 @@ This helper exists to support the `nc-widget` renderer (REQ-WDG-019), which need - THEN it MUST call `this.hasWidgetCallback(widgetId)` - AND the result of `hasWidgetCallback` and the poll's first synchronous check MUST agree +@e2e exclude `pollForCallback` has no caller in src/ (only its definition in src/services/widgetBridge.js; the nc-widget renderer, CnNcWidgetWidget in @conduction/nextcloud-vue, reads `OCA.Dashboard.callbacks` itself), and the bridge singleton is module-private, so no browser path reaches it; it also needs fake timers to pin interval ticks. Pinned by vitest src/services/__tests__/widgetBridge.spec.js 'REQ-LWB-006: pollForCallback uses hasWidgetCallback as single source of truth'. diff --git a/openspec/specs/license-header-consistency/screens.md b/openspec/specs/license-header-consistency/screens.md new file mode 100644 index 000000000..87ce56133 --- /dev/null +++ b/openspec/specs/license-header-consistency/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Licentiekoppen in de broncode, zonder scherm. diff --git a/openspec/specs/license-header-consistency/spec.md b/openspec/specs/license-header-consistency/spec.md index 35157a7e7..6435fee2f 100644 --- a/openspec/specs/license-header-consistency/spec.md +++ b/openspec/specs/license-header-consistency/spec.md @@ -3,11 +3,10 @@ ## Purpose TBD - created by archiving change align-source-license-headers-to-eupl. Update Purpose after archive. -> @e2e exclude every scenario in this spec asserts a property of the repository's own source files (SPDX identifiers, PHPDoc `@license`/`@copyright` tags, the README badge) rather than any behaviour of a running instance, so there is nothing for a browser to observe. The real coverage is static and it is wired: `scripts/check-license-headers.sh` fails the build on a reintroduced `AGPL-3.0` identifier under `lib/`, `src/` or `appinfo/` (REQ-LIC-005), and it runs as composer `lint:licenses` inside `composer check:strict`; hydra gate-1 (`check_spdx_headers.py`) enforces the `@license`/`@copyright` PHPDoc pair on every file under `lib/`, and the hydra `license-triangle` gate (`scripts/lib/check_license_triangle.py`) cross-checks `LICENSE`, `composer.json`, `publiccode.yml` and `REUSE.toml` against each other. `REUSE.toml` is what makes the PHPDoc form acceptable to `reuse lint` (REQ-LIC-002/003). - ## Requirements ### Requirement: REQ-LIC-001 Source-file SPDX identifier is EUPL-1.2 + LaunchPad-authored source files MUST declare `EUPL-1.2` as their `SPDX-License-Identifier`, matching `REUSE.toml`, `composer.json`, `publiccode.yml`, and the `LICENSE` file. No LaunchPad-authored source file MUST @@ -28,6 +27,7 @@ carry an `AGPL-3.0-or-later` (or any non-`EUPL-1.2`) `SPDX-License-Identifier`. ### Requirement: REQ-LIC-002 No in-file licence contradiction + A source file MUST NOT declare two different licences. When a file carries both a PHPDoc `@license` tag and an `SPDX-License-Identifier`, the two MUST name the same licence (`EUPL-1.2`). @@ -41,6 +41,7 @@ same licence (`EUPL-1.2`). ### Requirement: REQ-LIC-003 Consistent copyright holder + Every LaunchPad-authored source file's `SPDX-FileCopyrightText` MUST name the same copyright holder as `REUSE.toml`, `publiccode.yml`, and the PHPDoc `@copyright` tag — `Conduction B.V.` — rather than "LaunchPad Contributors". @@ -54,6 +55,7 @@ same copyright holder as `REUSE.toml`, `publiccode.yml`, and the PHPDoc ### Requirement: REQ-LIC-004 README licence badge matches the declared licence + The README licence badge MUST state the same licence as the README §License prose and the rest of the repository (`EUPL-1.2`). @@ -66,6 +68,7 @@ prose and the rest of the repository (`EUPL-1.2`). ### Requirement: REQ-LIC-005 Regression guard for licence drift + The repository MUST carry an automated check that fails if a LaunchPad-authored source file reintroduces an `AGPL-3.0` `SPDX-License-Identifier`, and `reuse lint` MUST pass against the reconciled tree. @@ -78,6 +81,7 @@ lint` MUST pass against the reconciled tree. - **AND** the failure message MUST name the offending file and the expected `EUPL-1.2` identifier #### Scenario: reuse lint passes on the reconciled tree +@e2e exclude the subject is the `reuse lint` tool's verdict on the repository (REUSE.toml, LICENSES/, dep5 coverage of non-source files), and neither the e2e runner nor the instance has the `reuse` tool installed, so an e2e run cannot produce that verdict. It is the shared quality workflow's `REUSE compliance` job (`fsfe/reuse-action`), which runs for this app with `reuse-blocking` false. The headers it would read are asserted in tests/e2e/license-header-consistency.spec.ts. - **GIVEN** all source headers reconciled to EUPL-1.2 and Conduction B.V. - **WHEN** `reuse lint` runs diff --git a/openspec/specs/link-button-widget/screens.md b/openspec/specs/link-button-widget/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/link-button-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/link-button-widget/spec.md b/openspec/specs/link-button-widget/spec.md index 61d9f7c5b..dc0ca2bf4 100644 --- a/openspec/specs/link-button-widget/spec.md +++ b/openspec/specs/link-button-widget/spec.md @@ -36,7 +36,6 @@ The renderer MUST output a `<button>` whose click handler dispatches based on th 3. `createFile` → open an inline filename-prompt modal (REQ-LBN-003) The renderer MUST suppress all click handlers when `isAdmin === true` AND the surrounding dashboard is in edit mode, so that configuring the widget cannot accidentally fire actions. The button MUST carry a `disabled` attribute while an action is in flight (`isExecuting === true`). -@e2e exclude renderer with three action types tests click handlers on a placed link-button widget — requires seeded placement; covered by REQ-LBN-001 UI tests #### Scenario: External link opens in new tab @@ -68,7 +67,6 @@ The `icon` field of a link-button widget MUST follow the same dual-mode conventi - An empty or null value MUST render no icon (label-only) Icon size MUST be 48 px square; the label MUST be vertically stacked below the icon. -@e2e exclude icon resolution tests IconRenderer dispatch logic — Vitest component scope #### Scenario: Custom URL icon @@ -93,7 +91,6 @@ When `actionType === 'createFile'`, click MUST open an inline secondary modal co - Cancel and Create buttons (Create disabled when filename empty) On Create, the system MUST POST `/api/files/create` with body `{filename: <name>.<ext>, dir: '/', content: '', overwrite: false}`. When the server answers HTTP 409 `file_exists`, the modal MUST show a warning naming the existing file and relabel Create as Replace; only a click on Replace for that same name MUST send `overwrite: true`, and changing the name MUST return to a normal Create. On HTTP 200, the response's `url` MUST be opened in a new tab via `window.open(url, '_blank')`. On error, a translated toast MUST display `t('Failed to create document')`. The modal MUST close on Cancel or after a successful create. -@e2e exclude createFile flow tests server-side file-creation endpoint — Newman scope; UI trigger covered by REQ-LBN-001 #### Scenario: Document modal opens with prefilled name @@ -128,28 +125,27 @@ On Create, the system MUST POST `/api/files/create` with body `{filename: <name> The system MUST expose `POST /api/files/create` accepting `{filename: string, dir: string = '/', content: string = '', overwrite: bool = true}`. The endpoint MUST: -1. Validate filename: non-empty, ≤255 chars, no `..`, no `/`, no `\`, no null byte, must match `^[a-zA-Z0-9_\-. ]+$`. Otherwise return HTTP 400 `{error: 'Invalid filename'}`. +1. Validate filename: non-empty, ≤255 chars, no `..`, no `/`, no `\`, no null byte, must match `^[a-zA-Z0-9_\-. ]+$`. Otherwise return HTTP 400 `{status: 'error', error: 'invalid_filename', message: 'Invalid filename'}`. 2. Validate dir: no `..`, no null byte. Otherwise return HTTP 400. -3. Validate extension: must be in the admin-configured allow-list (default: `txt, md, docx, xlsx, csv, odt`). Otherwise return HTTP 400 `{error: 'File type not allowed'}`. +3. Validate extension: must be in the admin-configured allow-list (default: `txt, md, docx, xlsx, csv, odt`). Otherwise return HTTP 400 `{status: 'error', error: 'file_type_not_allowed', message: 'File type not allowed'}`. 4. Resolve user folder via `IRootFolder::getUserFolder($userId)` and create the subdirectory if missing. 5. If a file with the same name already exists at the target path, OVERWRITE its content, unless `overwrite` is `false`: then return HTTP 409 `{error: 'file_exists'}` and leave the file unchanged. 6. Return `{status: 'success', fileId: int, url: string}` where `url` opens the Files app at `openfile={fileId}` via `URLGenerator::linkToRouteAbsolute('files.view.index', ['openfile' => fileId])`. Internal exceptions MUST be wrapped; raw exception messages MUST NOT be returned to the caller. -@e2e exclude server-side file-creation endpoint tests PHP validator and extension allow-list — Newman scope #### Scenario: Path traversal rejected - GIVEN body `{filename: '../../etc/passwd'}` - WHEN POSTed -- THEN the system MUST return HTTP 400 with error `Invalid filename` +- THEN the system MUST return HTTP 400 with error `invalid_filename` and message `Invalid filename` - AND no file MUST be created on disk #### Scenario: Disallowed extension rejected - GIVEN allow-list `[txt, md, docx]` AND body `{filename: 'foo.exe'}` - WHEN POSTed -- THEN the system MUST return HTTP 400 with `{error: 'File type not allowed'}` +- THEN the system MUST return HTTP 400 with `{error: 'file_type_not_allowed', message: 'File type not allowed'}` #### Scenario: Existing file overwritten @@ -162,9 +158,9 @@ Internal exceptions MUST be wrapped; raw exception messages MUST NOT be returned ### Requirement: REQ-LBN-005 Internal action registry The system MUST expose a frontend composable `useInternalActions()` returning a singleton `Map<actionId, () => void | Promise<void>>` plus three methods: `register(id, fn)`, `invoke(id)`, and `has(id)`. Other frontend modules MAY register actions at any time. Click on an `internal` link button MUST look up `url` (the action ID) in the map and invoke the registered function. Missing IDs MUST log `console.warn('Unknown internal action: <id>')` but MUST NOT throw. -@e2e exclude internal action registry tests client-side JS singleton — Vitest scope #### Scenario: Register and invoke an internal action +@e2e exclude no production module registers an internal action (src/ has no `useInternalActions().register(` call outside tests) and the registry is a module-scoped Map the page does not expose, so the GIVEN cannot be set up from a browser. Pinned by Vitest src/composables/__tests__/useInternalActions.spec.js (register + invoke runs once) and src/components/Widgets/Renderers/__tests__/LinkButtonHost.actions.spec.js (the host dispatches the widget's action id through the registry). - GIVEN a module registered `useInternalActions().register('open-talk', () => router.push('/talk'))` - AND content `{actionType: 'internal', url: 'open-talk'}` @@ -192,7 +188,6 @@ The link sub-form for `AddWidgetModal` MUST expose six fields: | `textColor` | colour picker | no | Validation: `validate()` MUST require `label` AND `url` non-empty and return a non-empty error array otherwise. The form MUST pre-fill from `editingWidget.content` when editing an existing widget. -@e2e exclude add/edit form tests the AddWidgetModal form fields — form open requires widget picker; covered by spec-coverage widget form tests #### Scenario: Validation requires both label and url @@ -211,7 +206,6 @@ Validation: `validate()` MUST require `label` AND `url` non-empty and return a n ### Requirement: REQ-LBN-007 Default styling When the colour fields are empty, the renderer MUST default to `backgroundColor: var(--color-primary)` and `textColor: var(--color-primary-text)` (Nextcloud theme primary). Hover MUST translate the button up by 2 px and add a soft drop shadow. -@e2e exclude default styling tests CSS variables on a placed widget — visual regression / Vitest scope #### Scenario: Theme defaults @@ -230,7 +224,6 @@ When the colour fields are empty, the renderer MUST default to `backgroundColor: ### Requirement: REQ-LBLM-001 Display mode configuration The link-button widget MUST support a `displayMode ENUM('button','list')` field on its widget-config record. The field MUST default to `'button'` to preserve backward compatibility with existing single-button placements. When `displayMode = 'button'`, the widget renders a single button using only the first entry from the `links` array (or legacy single-link fields). When `displayMode = 'list'`, the widget renders a full vertical or horizontal list of multiple links per the list rendering requirements. -@e2e exclude display mode configuration tests JSON field and CSS class — Vitest scope #### Scenario: Display mode field exists with button default - GIVEN a new link-button-widget placement is created without specifying `displayMode` @@ -262,14 +255,21 @@ The widget placement MUST support a `links JSON` field typed as an array of link } ``` +The list spellings `url` and `action_id` are aliases of the single-button types `external` and `internal`: the renderer and the form MUST accept all five values and treat each alias exactly as its single-button type. The form MUST open an entry in either spelling and save the single-button spelling (`external`, `internal`, `createFile`). An unknown value MUST be treated as `external`. + When `displayMode = 'button'`, only the first entry in the `links` array is used, preserving existing single-button behaviour. When `displayMode = 'list'`, all entries in the array are rendered. The `links` field MAY be empty or null for `displayMode = 'button'` placements (legacy single-link fields take precedence); it MUST be a non-empty array for `displayMode = 'list'`. -@e2e exclude links array schema tests JSON blob validation — Vitest/Newman scope #### Scenario: Links array stored on placement - GIVEN a placement with `displayMode = 'list'` and `links = [{label: 'Docs', url: '...', actionType: 'url', ...}, ...]` - WHEN the placement is retrieved - THEN the full `links` array MUST be present in the response +#### Scenario: An action_id entry is never rendered as a link +- GIVEN a placement with `displayMode = 'list'` and `links = [{label: 'Files', url: 'open-files', actionType: 'action_id'}]` +- WHEN the widget renders outside edit mode +- THEN the entry MUST render as a `<button>` with no `href` +- AND a click MUST open no new tab and MUST dispatch `open-files` as an internal action + #### Scenario: Single-button mode ignores links array - GIVEN a placement with `displayMode = 'button'`, a populated `links` array, AND legacy single-link fields (`url`, `icon`) - WHEN the widget renders @@ -291,7 +291,6 @@ Each link entry in the `links` array MUST follow the same three action-type spec 3. `'createFile'` — File creation: opens a filename-prompt modal (per REQ-LBN-003) and creates a new file via `POST /api/files/create` For `'createFile'` actions, the `value` field MUST contain the file extension (e.g., `'docx'`, `'txt'`). Per-link click handlers MUST respect the dashboard edit-mode suppression (no actions fire when `canEdit === true` and `isAdmin === true`). -@e2e exclude action type reuse tests TypeScript enum — Vitest scope #### Scenario: List item with external link - GIVEN a list item with `actionType: 'url'` and `url: 'https://example.com'` @@ -299,6 +298,7 @@ For `'createFile'` actions, the `value` field MUST contain the file extension (e - THEN the system MUST open the URL in a new tab #### Scenario: List item with internal action +@e2e exclude no production module registers `open-files` or any other internal action, and the registry is not reachable from the page, so no click can be shown to invoke one. The host-side dispatch is pinned by Vitest src/components/Widgets/Renderers/__tests__/LinkButtonHost.actions.spec.js; that an `action_id` entry must not render as an external link is the REQ-LBLM-002 scenario "An action_id entry is never rendered as a link". - GIVEN a list item with `actionType: 'action_id'` and `url: 'open-files'` (a registered internal action) - WHEN the user clicks the list item - THEN the system MUST invoke the registered function for `'open-files'` @@ -324,7 +324,6 @@ Each link entry's `icon` field MUST follow the same dual-mode convention as REQ- - An empty or null value MUST render no icon Icon size MUST be consistent across all list items (24 px square for list mode; 48 px for compact/normal/spacious variants may adjust padding but not icon size). The icon MUST appear inline (left of the label in vertical mode, above in horizontal mode per list orientation). -@e2e exclude icon resolution per list item tests IconRenderer dispatch — Vitest scope #### Scenario: Custom icon URL in list item - GIVEN a list item with `icon: '/apps/launchpad/icons/report.png'` and `label: 'Q4 Report'` @@ -353,8 +352,6 @@ The `listItemGap` values control inter-item spacing: - `'normal'` — 1 rem gap - `'spacious'` — 1.5 rem gap -@e2e exclude list orientation and spacing tests CSS flexbox layout — visual regression scope - #### Scenario: Vertical list orientation - GIVEN a widget with `displayMode: 'list'`, `listOrientation: 'vertical'`, and 3 links - WHEN the widget renders @@ -391,7 +388,6 @@ The edit form for a link-button-widget placement MUST gain: - A "Remove" button per link to delete that entry The single-link form MUST be reused unchanged inside the list editor modal for consistency. When editing in button mode, only the first link's fields are exposed; the full links array remains hidden to the user. -@e2e exclude edit form integration tests the inline editor inside AddWidgetModal — requires seeded link-button-list placement #### Scenario: Display mode toggle in edit form - GIVEN the edit form for a link-button-widget placement @@ -430,8 +426,6 @@ The system MUST enforce the following validation rules: - When `displayMode = 'button'`, the `links` field MAY be empty or contain up to one entry; if `links` is empty, the legacy single-link fields (URL, icon) MUST be used. - The invariant `displayMode = 'button' XOR links is non-empty array` MUST NOT be enforced by the backend — the frontend form ensures this before submission. -@e2e exclude validation and constraints tests PHP and client-side field validators — Newman + Vitest scope - #### Scenario: List mode requires non-empty links array - GIVEN a placement with `displayMode: 'list'` and `links: []` - WHEN the user attempts to save @@ -461,7 +455,6 @@ The list-mode renderer MUST: 5. Inline styles MUST use CSS variables and inline `style` attributes; no hardcoded colours in the HTML When icon + label are present, the layout MUST be: icon (left, inline) followed by label text (no wrapping). Icon size MUST be 24 px in list mode. Label text MUST be left-aligned. -@e2e exclude rendering semantics tests a vs button element choice — Vitest snapshot scope #### Scenario: Vertical list renders as ul with li - GIVEN a widget with `displayMode: 'list'`, `listOrientation: 'vertical'`, and 2 links @@ -501,7 +494,6 @@ When icon + label are present, the layout MUST be: icon (left, inline) followed Existing widget placements created before list-mode support MUST remain valid and render correctly without data migration. Placements lacking a `displayMode` field MUST be treated as `displayMode = 'button'` implicitly. Placements lacking a `links` field MUST use the legacy single-link fields (`url`, `icon`) for rendering. No schema migration is required — the system MUST support both the old (single-link fields) and new (links array + displayMode) representations side-by-side. The frontend form MUST detect which representation a placement uses and offer the appropriate edit interface: single-link form for `displayMode = 'button'` with no `links` array, list editor for `displayMode = 'list'`. -@e2e exclude backward compatibility migration tests PHP migration script — Newman/migration scope #### Scenario: Pre-list-mode placement renders with legacy fields - GIVEN a placement created before list-mode support, with fields: `{url: 'https://example.com', icon: 'external', label: 'Go'}` @@ -523,6 +515,7 @@ No schema migration is required — the system MUST support both the old (single - AND the placement MUST save successfully #### Scenario: No schema change needed +@e2e exclude observing it needs version N installed, then an upgrade to N+1 on the same instance; the CI fixture installs one build. No unit test pins it either: the claim rests on lib/Migration having no step that touches link placements, which no test asserts. - GIVEN the app schema at version N (before list-mode support) - WHEN the app is updated to version N+1 (with list-mode support) - THEN no Nextcloud migration step MUST run diff --git a/openspec/specs/links-widget/screens.md b/openspec/specs/links-widget/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/links-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/links-widget/spec.md b/openspec/specs/links-widget/spec.md index e4687ad5c..053e3b4e3 100644 --- a/openspec/specs/links-widget/spec.md +++ b/openspec/specs/links-widget/spec.md @@ -12,8 +12,7 @@ Provide a multi-column dashboard widget that renders a curated grid of link card ### Requirement: REQ-LNKS-001 Widget registration -The system MUST register a LaunchPad dashboard widget with id `launchpad_links` via `OCP\Dashboard\IManager::registerWidget()` so it appears in the widget picker alongside other Nextcloud dashboard widgets. -@e2e exclude widget registration tested via widget-in-picker scenario in spec-coverage tests +The system MUST register a LaunchPad dashboard widget with id `launchpad_links` with Nextcloud's dashboard (`OCP\Dashboard\IManager`, through `IRegistrationContext::registerDashboardWidget()` in `Application::register()`) so it appears in the widget picker alongside other Nextcloud dashboard widgets. On Nextcloud's own dashboard it serves the links of the links widgets on the dashboards the user owns. #### Scenario: Widget appears in picker @@ -41,10 +40,19 @@ The system MUST register a LaunchPad dashboard widget with id `launchpad_links` - WHEN the widget picker fetches widget metadata - THEN the widget object MUST include at minimum: id, title, icon_url +#### Scenario: Nextcloud dashboard items come from own links widgets + +- GIVEN a user owns dashboards with `links` placements +- WHEN Nextcloud's dashboard asks `launchpad_links` for items (`GET /ocs/v2.php/apps/dashboard/api/v2/widget-items`) +- THEN the items MUST be those placements' links in dashboard (active first), section and link order, read in one query, each URL once, up to the requested limit +- AND placements on dashboards of other users MUST NOT be read +- AND each item MUST carry the label (the URL when the label is empty), the description or else the section title as subtitle, the URL (a Nextcloud path made absolute) and the link's icon when it is a URL, else the links icon +- AND a link whose URL is not http(s) or a Nextcloud path MUST be left out +- AND without any link the empty state MUST tell the user to add a links widget, in the user's language + ### Requirement: REQ-LNKS-002 Placement configuration schema The system MUST store per-placement widget configuration in the `oc_launchpad_widget_placements.widgetContent` JSON field, allowing users to specify sections with links, layout preferences, and display options. -@e2e exclude placement configuration schema tests JSON blob persistence via REST — Newman scope #### Scenario: Config stores sections array @@ -102,7 +110,6 @@ The system MUST store per-placement widget configuration in the `oc_launchpad_wi ### Requirement: REQ-LNKS-003 Link data structure The system MUST support a link object with label, URL, icon, and optional description, and MUST allow zero or more links per section. -@e2e exclude link data structure tests schema validation — Vitest/Newman scope #### Scenario: Link has required fields @@ -143,8 +150,6 @@ The system MUST resolve the `icon` field of a link using the following precedenc 3. Else if `icon` is a URL (starts with `/` or `http`), render it as an `<img>` element with `src` set to the URL. 4. Else (unrecognized format), fall back to the generic link icon. -@e2e exclude icon resolution precedence tests IconRenderer dispatch — Vitest component scope - #### Scenario: Nextcloud icon name resolved to SVG class - GIVEN link config `{label: 'Files', url: '/apps/files', icon: 'icon-files'}` @@ -174,7 +179,6 @@ The system MUST resolve the `icon` field of a link using the following precedenc ### Requirement: REQ-LNKS-005 Three link layout modes The system MUST support three distinct layout modes for rendering links, controlled by the `linkLayout` config field. -@e2e exclude three link layout modes (card/inline/icon-only) tests CSS class toggling — requires a placed links widget with configured sections; seeded state not in CI fixture #### Scenario: Card layout with full details @@ -218,7 +222,6 @@ The system MUST support three distinct layout modes for rendering links, control ### Requirement: REQ-LNKS-006 Multi-column grid layout The system MUST render sections and links using a CSS Grid layout with a configurable column count, allowing responsive multi-column link organization. -@e2e exclude multi-column grid layout tests CSS grid-template-columns — visual regression scope #### Scenario: Grid renders with configured columns @@ -259,7 +262,6 @@ The system MUST render sections and links using a CSS Grid layout with a configu ### Requirement: REQ-LNKS-007 URL sanitisation and validation The system MUST validate and sanitise all URLs in the links configuration to reject malicious or malformed inputs. -@e2e exclude URL sanitisation runs at save time on the PHP side — tested by Newman; Playwright cannot assert server-side sanitiser #### Scenario: Valid HTTPS URL accepted @@ -312,7 +314,6 @@ The system MUST validate and sanitise all URLs in the links configuration to rej ### Requirement: REQ-LNKS-008 Edit form with drag-to-reorder The system MUST provide an interactive configuration UI allowing users to add/edit/delete sections and links, and reorder them via drag-and-drop. -@e2e exclude edit form with drag-to-reorder tests complex vue-draggable integration inside a placed widget — requires seeded links placement #### Scenario: Add a new section @@ -389,7 +390,6 @@ The system MUST provide an interactive configuration UI allowing users to add/ed ### Requirement: REQ-LNKS-009 Empty widget state The system MUST display a user-friendly empty-state message when the widget has no links to display. -@e2e exclude empty widget state tests Vue empty-state component inside a placed widget — requires seeded empty-links placement #### Scenario: Empty state appears with no sections @@ -416,7 +416,6 @@ The system MUST display a user-friendly empty-state message when the widget has ### Requirement: REQ-LNKS-010 Navigation handling and rel attributes The system MUST correctly handle link navigation, distinguishing between external and internal URLs, and set appropriate `rel` attributes to prevent security issues and preserve cross-tab messaging where needed. -@e2e exclude navigation handling and rel attributes tests that external links have rel=noopener — requires a placed links widget with configured links; seeded state not in CI fixture #### Scenario: External URL uses rel="noopener noreferrer" diff --git a/openspec/specs/live-data-tile-widget/screens.md b/openspec/specs/live-data-tile-widget/screens.md new file mode 100644 index 000000000..cadbcbb35 --- /dev/null +++ b/openspec/specs/live-data-tile-widget/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement +- LpWidgetInstellen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetInstellen diff --git a/openspec/specs/live-data-tile-widget/spec.md b/openspec/specs/live-data-tile-widget/spec.md index 160b255d4..0ea74478c 100644 --- a/openspec/specs/live-data-tile-widget/spec.md +++ b/openspec/specs/live-data-tile-widget/spec.md @@ -1,13 +1,16 @@ # live-data-tile-widget Specification ## Purpose -TBD - created by archiving change live-data-tile-widget. Update Purpose after archive. +A tile that shows live data from an outside source: one value with a format and a badge, or a list, a table or key-value pairs, fetched and mapped on the server from an allowed host or an OpenConnector source, so personal fields and unsafe links never reach the page. + ## Requirements + ### Requirement: REQ-LIVETILE-001 Register live-data tile widget The system MUST register a `launchpad_livetile` widget with the Nextcloud Dashboard Widget API (v2) so it appears in the widget picker. #### Scenario: Widget appears in discovery +@e2e exclude never built as written: there is no `launchpad_livetile` Dashboard API widget, no `supportsV2`/`IReloadableWidget` (`git log --all -S launchpad_livetile -- src lib appinfo templates` finds only 5c110d12, which registered the frontend-only `livetile` type in src/constants/widgetRegistry.js instead and dropped the provider task); no test pins that registry entry. - GIVEN the LaunchPad app is installed and enabled - WHEN the user opens the "Add Widget" modal on a dashboard - THEN the live-data tile MUST appear in the widget list with id `launchpad_livetile` @@ -15,6 +18,7 @@ The system MUST register a `launchpad_livetile` widget with the Nextcloud Dashbo - AND the widget MUST declare `supportsV2 = true` and implement `IReloadableWidget` #### Scenario: Registration via IManager +@e2e exclude never built: no `LiveTileWidgetProvider` exists and nothing registers with `IManager` (`git log --all -S LiveTileWidgetProvider -- src lib appinfo templates` returns nothing; 5c110d12 notes the app has no lib/Widget provider layer); no test pins it. - GIVEN `OCP\Dashboard\IManager` is available - WHEN the LaunchPad app boots - THEN the app MUST register `LiveTileWidgetProvider` @@ -100,7 +104,65 @@ The system MUST treat OpenConnector as an optional leaf and remain functional wh - AND existing `connector`-mode tiles MUST render an informative "data source unavailable" state, not crash #### Scenario: No direct class dependency +@e2e exclude a code-structure property with no browser surface; the capability probe and the container lookup are pinned by tests/Unit/Service/LiveTileServiceTest.php (testProbeAsksForTheConnectorsRealServiceClass, testResolvesViaConnectorWhenAvailable, testIsConnectorAvailableFalseWhenAppDisabled); no test checks for a static import. - GIVEN the LaunchPad codebase - WHEN resolving a `connector`-mode tile - THEN LaunchPad MUST call OpenConnector through its documented runtime source-run API guarded by a capability probe, and MUST NOT statically import OpenConnector PHP classes +### Requirement: A live tile can show a list, a table or key-value pairs (REQ-LTC-001) + +A live tile MUST accept a display of `value` (the default), `list`, `table` or `keyvalue`, a mapping of up to six fields each with a label, a path and a role (title, link, date or field), and a limit between 1 and 50. A tile saved before this change MUST keep rendering its single value. + +#### Scenario: Ticket list from a connected system + +@e2e exclude needs an Integriq "TOPdesk" source, which the CI fixture does not have and which Nextcloud resolves server-side; the connector node mapping is pinned by tests/Unit/Service/LiveTileListsTest.php::testAConnectorNodeIsMappedTheSameWay, the list rendering by live-tile-lists.spec.ts and src/components/Widgets/Renderers/__tests__/LiveTileWidget.lists.spec.js. + +- **GIVEN** Integriq holds a source "TOPdesk" with stored credentials and Ella adds a live tile in connector mode with source "TOPdesk", expression `$.incidents`, display "List", limit 5, and mapping title `briefDescription`, link `url`, date `callDate` +- **WHEN** Pieter opens the Workspace page +- **THEN** the tile lists five incidents, each title linking to the incident + +#### Scenario: Existing single-value tile + +- **GIVEN** a live tile saved last month with `valueExpr: "$.open"` and no display +- **WHEN** it renders after this change +- **THEN** it shows the single value as before + +### Requirement: Mapping happens on the server and drops unmapped data (REQ-LTC-002) + +The server MUST evaluate the mapping, return only mapped fields, truncate to the limit, and cache the mapped result. The raw response MUST NOT be sent to the browser. + +#### Scenario: Personal data in the payload stays on the server + +- **GIVEN** a source whose items include `callerEmail`, and a mapping without it +- **WHEN** the tile's data is requested +- **THEN** the response items hold only the mapped fields and no `callerEmail` + +### Requirement: Only safe links are clickable (REQ-LTC-003) + +A mapped link MUST render as a link only when it is an `https` address, opening in a new tab; any other value MUST render as plain text. + +#### Scenario: Script link shown as text + +- **GIVEN** an item whose mapped link is `javascript:alert(1)` +- **WHEN** the list renders +- **THEN** the title shows as plain text without a link + +### Requirement: A preset shows another intranet's latest documents (REQ-LTC-004) + +The tile form MUST offer a "Latest documents" preset with SharePoint and Confluence variants that fill a list display with title, link, last modified and modified by, for the author to confirm. + +#### Scenario: SharePoint library + +- **GIVEN** Integriq holds a source "Intranet documenten" for a SharePoint document library through Microsoft Graph +- **WHEN** Ella picks the preset "Latest documents", variant SharePoint, and the source, and saves +- **THEN** the tile lists the ten latest documents with title, last modified date and editor, and each title opens the document in SharePoint + +### Requirement: The Live data form as LpWidgetInstellen draws it (REQ-LIVETILE-020) + +The content part of a Live data widget SHALL ask "Where does the value come from?" with two choice cards, Connection (a system the administrator has connected) and Web address (an address that returns JSON). With Connection it SHALL show the chosen connection and when it last succeeded. It SHALL then ask the path in the response, the view (Value, List, Table, Key-value), an optional unit and the refresh interval, and under Formatting the title, colour, border and whether the title shows, with a preview that follows the fields. + +#### Scenario: KCC waiting time + +- **GIVEN** the connection Contact centre queue last succeeded at 10:38 +- **WHEN** the editor chooses it, path `wait.minutes`, view Value, unit minutes +- **THEN** the preview shows the current value with "minutes" and "Refreshes every 5 minutes" diff --git a/openspec/specs/lpvandaag-start-page/spec.md b/openspec/specs/lpvandaag-start-page/spec.md new file mode 100644 index 000000000..036257569 --- /dev/null +++ b/openspec/specs/lpvandaag-start-page/spec.md @@ -0,0 +1,79 @@ +# lpvandaag-start-page Specification + +## Purpose +The employee's start page (board `launchpad/LpVandaag`) in one screen: the rows share the height under the top bar +without the page scrolling, one Meer menu holds the start page's actions, and Vandaag eerst is one row. + +## Requirements + +### Requirement: The start page fits the screen + +A dashboard with a placement that sets `content.fillHeight: true` SHALL fill the height below the Nextcloud top bar on +a screen at least 960px wide, outside edit mode: the page SHALL NOT scroll, the rows of placements that set +`content.fitRows: true` SHALL take their content's height, the other rows SHALL share the rest, and a widget taller than +its share SHALL scroll inside its card. On a narrower screen the cards SHALL stack and the page MAY scroll. In edit mode +the grid SHALL be the editable grid as before. + +#### Scenario: Mijn werkdag at 1440×900 and 1366×768 + +- **GIVEN** Mijn werkdag version 5 +- **WHEN** an employee opens the start page at 1440×900 or 1366×768 +- **THEN** the page's scroll height equals its height, and the Apps, Agenda vandaag and Verder waar u was cards fill + the space under the counters + +### Requirement: One Meer menu holds the start page's actions + +The start page SHALL show one control in its header: the menu "Meer", the same menu as on every other page +(runtime-shell REQ-SHELL-013, board LpMeer). There SHALL be no "Startpagina aanpassen" button, no Bewerken button and +no other control for the dashboard's actions. Meer SHALL hold, left, Dashboards (every dashboard the person sees, the +open one checked, the markers standaard, gedeeld and groep, and "Alle dashboards"), and right, Dit dashboard +(Bewerken, Widget toevoegen, Delen, Link naar dit dashboard kopiëren, Kopie maken als nieuw dashboard, Als standaard +instellen, and Verwijderen last), with below it the folding item Instellingen (Persoonlijke instellingen, +Beheerinstellingen for an administrator only, Marktplaats, Sjablonen, Rapporten, Flows, Koppelingen, Documentatie, +Functies en roadmap). Versies, publishing, its schedule and the scheduled exports are tabs of the dashboard settings, +not menu items. Each action SHALL keep its gate. No action SHALL appear twice. + +#### Scenario: An administrator opens Meer + +- **GIVEN** the start page, for an administrator +- **WHEN** they open "Meer" and unfold Instellingen +- **THEN** "Beheerinstellingen" appears once, under Instellingen, and "Sjablonen" is in the same group +- **AND** the header shows no "Startpagina aanpassen" button + +#### Scenario: A member opens Meer on a shared dashboard + +- **GIVEN** a member on a dashboard shared with them +- **WHEN** they open "Meer" +- **THEN** Dit dashboard offers "Als standaard instellen", and neither Verwijderen nor Versies + +### Requirement: Vandaag eerst is one row + +The attention widget with `content.layout: "columns"` SHALL draw its items side by side in one row of +`content.columns` (1 to 4, 3 by default), each with its title, reason and app on the left and its action on the right. +With `content.title` it SHALL draw that heading with the number of items it shows beside it. On a narrow screen the +items SHALL stack. + +#### Scenario: Three things today + +- **GIVEN** three apps report something that needs attention +- **THEN** "Vandaag eerst" reads "3 dingen uit al uw apps die vandaag aandacht vragen" and shows the three side by side + +### Requirement: The start page greets the reader + +A header placement with `content.greeting: true` SHALL open with a greeting for the part of the day ("Goedemorgen" +before 12:00, "Goedemiddag" before 18:00, "Goedenavond" after; in English "Good morning", "Good afternoon", "Good +evening") and the reader's first name, followed by today's date in the reader's language. With `content.showWeek: +true` it SHALL add the week number. The greeting SHALL use the reader's display name and time zone, and SHALL be text, +not an image, so a screen reader reads it. + +#### Scenario: Pieter opens the start page after lunch + +- **GIVEN** Pieter Jansen, language Dutch, opens the start page on Monday 5 October 2026 at 13:10 +- **WHEN** the header renders with `greeting` and `showDate` +- **THEN** it reads "Goedemiddag, Pieter · maandag 5 oktober 2026" + +#### Scenario: The week number + +- **GIVEN** the header sets `showWeek: true` +- **WHEN** Pieter opens it on Monday 5 October 2026 +- **THEN** the header also shows "week 41" diff --git a/openspec/specs/manifest-routing/spec.md b/openspec/specs/manifest-routing/spec.md new file mode 100644 index 000000000..b181bc817 --- /dev/null +++ b/openspec/specs/manifest-routing/spec.md @@ -0,0 +1,118 @@ +# manifest-routing Specification + +## Purpose +Make a page LaunchPad declares a page LaunchPad serves. + +Before this change the app had no `vue-router` at all — `createRouter` appeared +nowhere in `src/` — and navigation was Pinia state that never touched the URL. +`src/manifest.json` declared nine pages and the app served one: `/store`, +`/reports` and `/flows` each redirected to `/dashboard`. + +## Requirements + +### Requirement: REQ-ROUTE-001 The route table is derived, not written + +The router MUST build its routes from `manifest.pages`, so a declared page is a +routed page by construction and the two cannot drift. + +The catch-all MUST use vue-router 4's named-parameter form +(`path: '/:pathMatch(.*)*'`). The bare `'*'` wildcard was removed in v4 and does +not warn — it simply never matches, and an unknown URL renders the shell with an +empty content area. + +#### Scenario: A declared page resolves + +- GIVEN `src/manifest.json` declares a page with a `route` +- WHEN a user navigates to that route +- THEN the router MUST match it +- AND the declared page type MUST render + +### Requirement: REQ-ROUTE-002 The router base accepts both URL forms + +Nextcloud serves an app under both `/apps/launchpad/…` and +`/index.php/apps/launchpad/…`. The router base MUST be read from the location, +falling back to `generateUrl`. A base that assumes one form makes every route on +the other miss, which presents as an empty content area rather than an error. + +#### Scenario: index.php form + +- GIVEN a visitor arrives on `/index.php/apps/launchpad/reports` +- THEN the Reports page MUST render + +### Requirement: REQ-ROUTE-003 A dashboard has an address + +`/dashboards/:id` MUST select that dashboard, so a dashboard can be linked, +bookmarked and reopened (`dashboard-deeplinking`). + +An absent or unknown id MUST be left alone: the dashboard store's own resolver +already picks a sensible active dashboard, and overriding it would make a bad +link empty the page instead of falling back. + +#### Scenario: Cold deep link + +- GIVEN a user opens `/dashboards/<id>` in a fresh browser +- THEN that dashboard MUST become the active one + +#### Scenario: Unknown id + +- GIVEN a user opens `/dashboards/does-not-exist` +- THEN the store's resolved dashboard MUST still render + +### Requirement: REQ-ROUTE-004 The shared chrome renders, with the workspace inside it + +The app MUST root on `CnAppRoot`, which renders `CnAppNav` from `manifest.menu` +— including ADR-114's four footer destinations — around a `router-view`. + +**This supersedes REQ-SHELL-001's chrome-slot clause.** That requirement had +`PageController` pass `'id-app-navigation' => null` to suppress Nextcloud's left +navigation panel, because the app rendered its own slide-in sidebar and nothing +else. `NcContent` allocates that panel for `CnAppNav`, so suppressing it would +leave the shared chrome with nowhere to render — an empty rail, not an error. +`PageController` MUST pass no chrome slot ids, as every other app in the fleet +does. + +The slide-in sidebar is unaffected: it lives inside the workspace view, not in +the chrome slot. + +#### Scenario: Both are present on the dashboard route + +- GIVEN a user opens `/` +- THEN `CnAppNav` MUST render +- AND `.workspace-shell` MUST render inside the content area + +### Requirement: REQ-ROUTE-005 One skip link + +The app MUST NOT write its own skip link. It had one because it did not root on +`NcContent` and so did not inherit Nextcloud's; `CnAppRoot` renders `NcContent`, +and two bypass links are worse than one. + +`#launchpad-main-content` MUST keep `tabindex="-1"`, which the quick-search Esc +contract needs independently of any link. + +#### Scenario: Nextcloud's skip link only + +- GIVEN a user opens LaunchPad's start page +- THEN exactly one "Skip to main content" link MUST be on the page +- AND `#launchpad-main-content` MUST carry `tabindex="-1"` + +@e2e exclude Checked in the live pass of 17 Nov 2026 on NC 34 (one link, tabindex -1); a single-count assertion in app-chrome would be the natural home. + +### Requirement: REQ-ROUTE-006 A declared page names a component that exists + +A `type: custom` page MUST name a component the registry resolves. + +`admin-settings` named `AdminSettingsPage`, which has never existed, and +`admin-templates-index` named `TemplatesPage`, which is a tab inside the +Nextcloud admin section rather than a page. Both MUST resolve to a redirect to +`/settings/admin/launchpad`, which is where that functionality lives — rendering +half an admin surface beside the real one would be worse than the dead links +they were. + +The redirect MUST render a real anchor as well as navigating, because a redirect +that only runs in `mounted` leaves a blank page for anyone whose navigation is +slow or blocked, and gives a keyboard user nothing to act on. + +#### Scenario: The admin menu entry is not a dead link + +- GIVEN a user activates the Admin settings entry +- THEN they MUST arrive at `/settings/admin/launchpad` diff --git a/openspec/specs/map-widget/spec.md b/openspec/specs/map-widget/spec.md new file mode 100644 index 000000000..4ab7062ec --- /dev/null +++ b/openspec/specs/map-widget/spec.md @@ -0,0 +1,43 @@ +# map-widget Specification + +## Purpose +TBD - created by archiving change map-support. Update Purpose after archive. + +## Requirements + +### Requirement: REQ-MAP-001 A map widget shows register objects that carry a location + +LaunchPad SHALL offer a `map` widget type that renders the GeoJSON geometry of OpenRegister objects (points, lines, polygons and multi-geometries) on a PDOK BRT base map, fetched through OpenRegister's spatial-query API. The map SHALL be nextcloud-vue's shared `CnMapWidget`, registered as the communal `map` type; LaunchPad SHALL NOT ship a map widget or map library of its own, and new configuration keys SHALL be optional so the content existing map widgets store keeps rendering. + +#### Scenario: Objects with a location appear on the map + +- GIVEN a map widget configured with a register, a schema and the schema's geo property +- WHEN the dashboard loads +- THEN every object the user may read that has a value in the geo property SHALL be drawn on the map +- AND the widget SHALL show a loading state while the query runs and an empty state when no object has a location + +#### Scenario: Dense point sets are clustered + +- GIVEN a map widget with a clustering threshold +- WHEN more points fall in one area than the threshold +- THEN the widget SHALL draw them as one cluster that splits when the user zooms in + +### Requirement: REQ-MAP-002 A map widget configuration is validated on save + +Saving a `map` widget SHALL be refused unless the configuration names `register`, `schema` and `geoProperty`; `spatialFilter` (none, bbox or polygon) and `clusterThreshold` are optional. + +#### Scenario: A map widget without a geo property is refused + +- GIVEN a dashboard author configuring a map widget +- WHEN they save it without choosing a geo property +- THEN the save SHALL be refused with a message that names the missing field + +### Requirement: REQ-MAP-003 Clicking a feature opens its object + +Clicking a feature on the map SHALL open the underlying OpenRegister object through the deep-link registry. + +#### Scenario: Open an object from the map + +- GIVEN a map widget showing objects +- WHEN the user clicks one feature +- THEN the object's deep link SHALL open in a new tab diff --git a/openspec/specs/mcp-tools/spec.md b/openspec/specs/mcp-tools/spec.md new file mode 100644 index 000000000..e14627b65 --- /dev/null +++ b/openspec/specs/mcp-tools/spec.md @@ -0,0 +1,256 @@ +# mcp-tools Specification + +## Purpose +LaunchPad offers its user actions as MCP tools through OpenRegister's MCP endpoint, so an agent or a chat can read and change dashboards, widgets, tiles and shares on behalf of a user, with the same permissions that user has in the app and with every refusal reaching the agent as an error. + +## Requirements + +### Requirement: REQ-MCP-001 Provider class, DI alias, and tool id namespace + +LaunchPad MUST implement `OCA\OpenRegister\Mcp\IMcpToolProvider` in a new class `OCA\LaunchPad\Mcp\LaunchPadToolProvider` (dispatcher + catalogue constant, handlers in domain-grouped classes, per the decidesk layout). It MUST be registered in `lib/AppInfo/Application.php` under the string DI alias `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad` (string alias so registration triggers no autoload and the app boots without OpenRegister, matching decidesk's `IMcpToolProvider::decidesk` registration). Every tool id MUST use the `launchpad.{toolName}` namespace. + +#### Scenario: Provider resolves through the alias + +- **GIVEN** an instance with OpenRegister and launchpad enabled +- **WHEN** the container resolves `OCA\OpenRegister\Mcp\IMcpToolProvider::launchpad` +- **THEN** it MUST return a `LaunchPadToolProvider` instance +- **AND** every id in its catalogue MUST start with `launchpad.` + +#### Scenario: Boot without OpenRegister + +- **GIVEN** an instance where OpenRegister is not installed +- **WHEN** launchpad boots +- **THEN** app registration MUST complete without error — the alias fails only if something asks for it + +### Requirement: REQ-MCP-002 Read tool catalogue (full read coverage) + +The provider MUST expose the following read tools, each with `readOnlyHint: true` and scope `read`, reach `self` (each returns only what the caller may already see through the corresponding endpoint's guards): + +| Tool id | Backs | +|---|---| +| `launchpad.listDashboards` | `dashboardApi#visible` / `DashboardService::getVisibleToUser()` | +| `launchpad.getDashboard` | `dashboardApi#show` / `#resolved` | +| `launchpad.getActiveDashboard` | `dashboardApi#getActive` / `DashboardService::resolveActiveDashboard()` | +| `launchpad.getDashboardTree` | `dashboardApi#tree` | +| `launchpad.listGroupDashboards` | `dashboardApi#listGroup` | +| `launchpad.listWidgetTypes` | `widgetApi#listAvailable` | +| `launchpad.listTiles` | `tileApi#index` | +| `launchpad.listShares` | `dashboardShareApi#index` | +| `launchpad.listVersions` | `dashboardVersionApi#listVersions` | +| `launchpad.listTemplates` | `template#gallery` | +| `launchpad.getDashboardMetadata` | `dashboardMetadata#getMetadata` | +| `launchpad.getReactions` | `dashboardReactionApi#getReactions` | +| `launchpad.listPendingAcknowledgements` | `acknowledgement#pending` | +| `launchpad.listKioskPlaylists` | `kiosk#index` | + +#### Scenario: Read tools are marked read-only + +- **GIVEN** the provider's catalogue +- **WHEN** hermiq inspects the 14 read tools +- **THEN** each MUST carry `readOnlyHint: true` and scope `read` +- **AND** none of them MUST mutate any state when invoked + +#### Scenario: Reads return only the caller's visible set + +- **GIVEN** a caller who can see dashboards A and B but not C +- **WHEN** `launchpad.listDashboards` is invoked on their behalf +- **THEN** the result MUST contain A and B and MUST NOT contain C — identical to `GET /api/dashboards/visible` + +### Requirement: REQ-MCP-003 Write tool catalogue with scope × reach annotations (full action coverage) + +The provider MUST expose the following write tools — one tool per user action, aggregated exactly as the existing endpoints aggregate them (e.g. rename/describe/re-slug are all `updateDashboard`, matching `dashboardApi#update`; move/resize/style are all `updateWidgetPlacement`, matching `widgetApi#updatePlacement`). Each write tool MUST declare the scope and reach listed: + +**Reach `self` — the caller's own dashboards:** + +| Tool id | Backs | Scope | +|---|---|---| +| `launchpad.createDashboard` | `dashboardApi#create` / `DashboardService::createDashboard()` | create | +| `launchpad.updateDashboard` | `dashboardApi#update` / `DashboardService::updateDashboard()` | update | +| `launchpad.deleteDashboard` | `dashboardApi#delete` / `DashboardService::deleteDashboard()` | delete | +| `launchpad.switchActiveDashboard` | `dashboardApi#setActiveDashboard` / `#activate` | update | +| `launchpad.setDefaultDashboard` | `dashboardApi#setDefaultDashboard` / `DashboardService::setDefaultPreference()` | update | +| `launchpad.forkDashboard` | `dashboardApi#fork` / `DashboardService::forkAsPersonal()` — also the "use a gallery template" path | create | +| `launchpad.addWidget` | `widgetApi#addWidget` | create | +| `launchpad.updateWidgetPlacement` | `widgetApi#updatePlacement` | update | +| `launchpad.removeWidget` | `widgetApi#removePlacement` | delete | +| `launchpad.addTileToDashboard` | `widgetApi#addTile` | create | +| `launchpad.createTile` | `tileApi#create` | create | +| `launchpad.updateTile` | `tileApi#update` | update | +| `launchpad.deleteTile` | `tileApi#destroy` | delete | +| `launchpad.createDashboardVersion` | `dashboardVersionApi#createVersion` | create | +| `launchpad.restoreDashboardVersion` | `dashboardVersionApi#restoreVersion` | update | +| `launchpad.setDashboardMetadata` | `dashboardMetadata#setMetadata` | update | +| `launchpad.addReaction` | `dashboardReactionApi#addReaction` | create | +| `launchpad.removeReaction` | `dashboardReactionApi#removeReaction` | delete | + +**Reach `user` — changes other users' access:** + +| Tool id | Backs | Scope | +|---|---|---| +| `launchpad.shareDashboard` | `dashboardShareApi#create` | create | +| `launchpad.replaceShares` | `dashboardShareApi#replace` | update | +| `launchpad.unshareDashboard` | `dashboardShareApi#destroy` | delete | +| `launchpad.setPublicationState` | `dashboardApi#publish` / `#unpublish` / `#schedule` | update | + +**Reach `external` — mints or revokes anonymous access:** + +| Tool id | Backs | Scope | +|---|---|---| +| `launchpad.createPublicShareLink` | `publicShare#create` | create | +| `launchpad.revokePublicShareLink` | `publicShare#destroy` | delete | +| `launchpad.createKioskPlaylist` | `kiosk#create` | create | +| `launchpad.updateKioskPlaylist` | `kiosk#update` | update | +| `launchpad.deleteKioskPlaylist` | `kiosk#destroy` | delete | + +**Reach `instance` — instance-wide (group dashboards, admin templates):** + +| Tool id | Backs | Scope | +|---|---|---| +| `launchpad.createGroupDashboard` | `dashboardApi#createGroup` / `DashboardService::createGroupShared()` | create | +| `launchpad.updateGroupDashboard` | `dashboardApi#updateGroup` | update | +| `launchpad.deleteGroupDashboard` | `dashboardApi#deleteGroup` | delete | +| `launchpad.setGroupDefault` | `dashboardApi#setGroupDefault` | update | +| `launchpad.createTemplate` | `admin#createTemplate` / `AdminTemplateService` | create | +| `launchpad.updateTemplate` | `admin#updateTemplate` | update | +| `launchpad.deleteTemplate` | `admin#deleteTemplate` | delete | +| `launchpad.resyncTemplate` | `admin#resyncTemplate` / `TemplateResyncService` | update | + +#### Scenario: Every write tool carries both axes + +- **GIVEN** the provider's catalogue +- **WHEN** hermiq inspects any non-read tool +- **THEN** it MUST find a scope of `create`, `update`, or `delete` AND a reach of `self`, `user`, `instance`, or `external` +- **AND** no write tool MUST carry `readOnlyHint: true` + +#### Scenario: Writes are default-deny in hermiq + +- **GIVEN** an agent with no explicit grants for launchpad +- **WHEN** it attempts `launchpad.deleteDashboard` +- **THEN** hermiq MUST refuse before the tool executes — the tool's annotations exist so this decision is per-tool, not app-wide + +#### Scenario: External-reach tools are the narrowest grant + +- **GIVEN** an agent granted `create/self` and `update/self` for launchpad +- **WHEN** it attempts `launchpad.createPublicShareLink` +- **THEN** the call MUST be refused — `external` reach requires its own explicit grant + +### Requirement: REQ-MCP-004 Authorization parity with the HTTP surface + +Every tool handler MUST enforce the exact same authorization as the corresponding controller path, by calling the same service guards: `PermissionService::canViewDashboard()` / `canEditDashboard()` / `canAddWidget()` / `canRemoveWidget()` / `canCreateDashboard()`, `ActionAuthService::requireAction()` for ADR-023-gated actions, and the admin requirement for `instance`-reach tools. This MUST be centralised in a `McpDashboardGate` class (mirroring decidesk's `McpMeetingGate`: authorise() returning an allow/deny result, no `catch (\Throwable) { return null; }` fail-open shapes). A tool MUST NOT reach `ObjectService` or mappers directly for writes — all mutations go through the existing service layer so slug generation, lock checks, placement collision handling, and cascade behaviour hold. + +#### Scenario: Tool denial equals endpoint denial + +- **GIVEN** a caller for whom `PUT /api/dashboard/{id}` would return a permission error +- **WHEN** the same caller's agent invokes `launchpad.updateDashboard` for that dashboard +- **THEN** the tool MUST deny with a structured error, thrown as a `McpToolRefusedException` (REQ-MCP-010) +- **AND** no partial mutation MUST occur + +#### Scenario: Admin tools require admin + +- **GIVEN** a non-admin caller +- **WHEN** their agent invokes `launchpad.createTemplate` +- **THEN** the gate MUST deny exactly as `admin#createTemplate` does for that caller + +#### Scenario: No fail-open on gate errors + +- **GIVEN** the authorization service throws during a tool call +- **WHEN** the gate evaluates the request +- **THEN** the result MUST be a denial, never a silent allow + +### Requirement: REQ-MCP-005 Argument validation before any service call + +Every tool MUST validate its arguments against its declared `inputSchema` before touching a service, via a `McpArgumentValidator` (decidesk pattern: typed UUID/date/string-length checks returning a structured error array on failure). Invalid arguments MUST produce a validation error, never a service call with coerced values. The provider throws that error as a `McpToolRefusedException` (REQ-MCP-010); no other exception escapes the provider. + +#### Scenario: Malformed UUID is rejected + +- **GIVEN** an agent invokes `launchpad.getDashboard` with `dashboardUuid: "../../etc"` +- **WHEN** the validator runs +- **THEN** the tool MUST return a validation error without any service or database access + +#### Scenario: Out-of-range grid values are rejected + +- **GIVEN** `launchpad.updateWidgetPlacement` is invoked with a negative `gridWidth` +- **WHEN** the validator runs +- **THEN** the tool MUST return a validation error naming the offending field + +### Requirement: REQ-MCP-006 Destructive and external tools are flagged for human approval and audited + +Tools with scope `delete`, and all tools with reach `external`, MUST carry a destructive/approval annotation so hermiq inserts its human approval gate before execution. Every write tool invocation (allowed or denied) MUST be auditable: the provider returns enough structured context (tool id, target uuid/id, caller uid, outcome) for hermiq's audit trail to record the action. For a denied call that context travels on the thrown `McpToolRefusedException` (`getResult()['audit']`). + +#### Scenario: Delete requires approval + +- **GIVEN** a user tells the chat "delete my old sales dashboard" +- **WHEN** the agent resolves this to `launchpad.deleteDashboard` +- **THEN** hermiq MUST present a human approval step before the tool runs +- **AND** the approval and execution MUST both land in the audit trail + +#### Scenario: Public link requires approval + +- **GIVEN** an agent invokes `launchpad.createPublicShareLink` +- **WHEN** hermiq evaluates the call +- **THEN** the external-reach annotation MUST trigger the approval gate even if the agent holds a `create/external` grant + +### Requirement: REQ-MCP-007 Deliberate exclusions from the tool surface + +The following real endpoints MUST NOT get tools, and the catalogue MUST stay closed against them without an explicit spec change: + +- **Telemetry recorders** — `dashboardApi#viewEvent`, `tileAnalytics#recordClick`: an agent invoking these fabricates analytics. +- **Acknowledgements (write)** — `acknowledgement#acknowledge`: a mandatory-read acknowledgement is compliance evidence of a *human* act; an agent must never acknowledge on a user's behalf. (The read side, `listPendingAcknowledgements`, is exposed.) +- **Binary upload endpoints** — `resource#upload`/`#uploadMultipart`, `admin#uploadTemplatePreviewImage`, `filesWidget#upload`: multipart/base64 payloads are not chat-tool shaped; revisit if a file-reference contract lands. +- **Editing locks** — `dashboardLockApi#*`: locks serialize *interactive* editing sessions; tool calls are single atomic service operations and must not hold or break user locks. +- **One-off admin plumbing** — setup wizard, Confluence import, orphaned-data cleanup, demo showcases, bulk operations, export/import, role/metadata-field/org-navigation/footer/settings administration: high blast radius, no chat use case; deliberately out of v1. + +#### Scenario: Catalogue contains no excluded tool + +- **GIVEN** the provider's catalogue +- **WHEN** its ids are compared against the exclusion list +- **THEN** no tool MUST exist for any excluded endpoint +- **AND** the catalogue MUST contain exactly the tools of REQ-MCP-002 and REQ-MCP-003 + +### Requirement: REQ-MCP-008 Chat command flows resolve to tool sequences + +The catalogue MUST be sufficient for hermiq to execute common chat commands as short tool sequences using only declared tools, with all resolution (name → uuid, widget label → widgetKey) done via read tools first. + +#### Scenario: "Add the calendar widget to my dashboard" + +- **GIVEN** a user with an active personal dashboard and an agent granted `read/self` and `create/self` +- **WHEN** the user sends "add the calendar widget to my dashboard" +- **THEN** the agent MUST be able to resolve it as `launchpad.getActiveDashboard` → `launchpad.listWidgetTypes` (find the calendar widgetKey) → `launchpad.addWidget` +- **AND** the widget MUST appear on the dashboard exactly as if added through the UI + +#### Scenario: "Share my team dashboard with the sales group" + +- **GIVEN** an agent granted `read/self` and `create/user` +- **WHEN** the user sends "share my team dashboard with the sales group" +- **THEN** the agent MUST resolve the dashboard via `launchpad.listDashboards`, then invoke `launchpad.shareDashboard` with a group share for `sales` +- **AND** the share MUST be identical to one created via `POST /api/dashboard/{id}/shares` + +#### Scenario: "Start me a dashboard from the sprint template and make it my default" + +- **GIVEN** an agent granted `read/self`, `create/self`, and `update/self` +- **WHEN** the user sends the command +- **THEN** the agent MUST resolve it as `launchpad.listTemplates` → `launchpad.forkDashboard` → `launchpad.setDefaultDashboard` +- **AND** `launchpad.listTemplates` MUST offer only the templates for the caller's groups (a template without groups is offered to everyone), and `launchpad.forkDashboard` MUST accept exactly those (admin-templates REQ-TMPL-018) +- **AND** the resulting dashboard MUST be the caller's default landing dashboard + +### Requirement: REQ-MCP-010 A refusal reaches the agent as an error + +OpenRegister marks a tool answer `isError: true` only when the provider throws. When a LaunchPad tool refuses (no permission, a target that does not exist, invalid input, or an unknown tool id), `LaunchPadToolProvider::invokeTool()` MUST throw a `McpToolRefusedException` instead of returning the refusal. Its message MUST be `<error code>: <message>`, and `getErrorCode()` and `getResult()` MUST carry the refusal as the tool built it, audit record included for a write tool. A tool that succeeds MUST return its answer as before. + +#### Scenario: A refused tool answers isError true + +- **GIVEN** an agent invokes a LaunchPad tool the caller may not use, on a target that does not exist, or with invalid arguments +- **WHEN** OpenRegister runs the call +- **THEN** the answer MUST carry `isError: true` +- **AND** its text MUST name the refusal code (`forbidden`, `not_found` or `invalid_arguments`) and message + +### Requirement: REQ-MCP-009 Read-only x-openregister-mcp block on the Dashboard schema + +A register.d overlay MUST declare `x-openregister-mcp` on the `Dashboard` schema with auto-derived **read** tools only (`search`, `get` with `readOnlyHint: true`, openconnector pattern). Auto-derived CRUD writes MUST NOT be enabled: dashboard mutations bypass `DashboardService` invariants (slug generation, permission levels, lock checks) if written as raw objects, so all writes stay with the provider tools of REQ-MCP-003. + +#### Scenario: Schema-derived tools are read-only + +- **GIVEN** the imported Dashboard schema +- **WHEN** OpenRegister derives MCP tools from its `x-openregister-mcp` block +- **THEN** only `search` and `get` MUST be derived, both read-only +- **AND** no derived create/update/delete tool MUST exist for the Dashboard schema diff --git a/openspec/specs/menu-widget/screens.md b/openspec/specs/menu-widget/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/menu-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/menu-widget/spec.md b/openspec/specs/menu-widget/spec.md index 4db6572fe..9e7bd1d18 100644 --- a/openspec/specs/menu-widget/spec.md +++ b/openspec/specs/menu-widget/spec.md @@ -35,7 +35,6 @@ Each item carries: ### Requirement: REQ-MENU-001 Widget registration and default structure The system MUST register a widget `type: 'menu'` in `widgetRegistry.js` with default `widgetContent` shape: -@e2e exclude widget registration tested via widget-in-picker scenario ```json { @@ -70,8 +69,7 @@ The `items` array MUST support objects with: ### Requirement: REQ-MENU-002 Config schema and depth validation -The `items` array MUST allow up to 3 levels of nesting (top-level + 2 child levels). -@e2e exclude config schema and depth validation tests PHP validator via REST — Newman scope Any item with `children` deeper than 2 levels MUST be rejected at placement-save time with HTTP 400 `{error: 'Menu items can nest at most 3 levels deep'}`. +The `items` array MUST allow up to 3 levels of nesting (top-level + 2 child levels). Any item with `children` deeper than 2 levels MUST be rejected at placement-save time with HTTP 400 `{error: 'Menu items can nest at most 3 levels deep'}`. Server-side validation MUST recursively check all items in the saved placement's `widgetContent.items` and reject the placement if depth > 3. @@ -96,6 +94,7 @@ Valid field values: - THEN the placement MUST save successfully #### Scenario: Invalid style value rejected in form validation +@e2e exclude unreachable through the product: the form's style control is a closed NcSelect offering only dropdown/megamenu/tree, and CnMenuWidgetForm (@conduction/nextcloud-vue) coerces any other stored style to `dropdown` on load and its validate() has no style check, so no user action puts 'invalid-style' in the form. The API-level refusal the NOTE relies on is pinned by tests/Unit/Service/MenuServiceTest.php::testInvalidStyleRejected; no unit test exists for a form-side check because none was built - GIVEN the form has `style: 'invalid-style'` before save - WHEN the form validates @@ -105,7 +104,6 @@ Valid field values: ### Requirement: REQ-MENU-003 Dropdown style When `style === 'dropdown'`, the renderer MUST: -@e2e exclude dropdown style tests CSS dropdown positioning — requires a placed menu widget; seeded state not in CI fixture - Render top-level items in a horizontal bar (or vertical if `orientation === 'vertical'`). - Open a popover dropdown below (or beside, depending on space) when a top-level item with children is clicked or focused. @@ -146,7 +144,6 @@ When `style === 'dropdown'`, the renderer MUST: ### Requirement: REQ-MENU-004 Megamenu style When `style === 'megamenu'`, the renderer MUST: -@e2e exclude megamenu style tests CSS panel layout — requires a placed menu widget - Render top-level items in a horizontal bar. - Open a full-width panel below the bar when any top-level item is clicked, containing all level-2 items grouped by their parent top-level item. @@ -186,7 +183,6 @@ When `style === 'megamenu'`, the renderer MUST: ### Requirement: REQ-MENU-005 Tree style When `style === 'tree'`, the renderer MUST: -@e2e exclude tree style tests recursive item rendering — requires a placed menu widget - Render items as a vertical hierarchical list. - Render top-level items without children as clickable links; items with children MUST show a caret to the left. @@ -227,7 +223,6 @@ When `style === 'tree'`, the renderer MUST: ### Requirement: REQ-MENU-006 Active item detection and highlighting The renderer MUST detect the active item based on the current page URL and highlight it and its ancestors. The `activeItemHighlight` field controls the style: -@e2e exclude active item detection tests window.location.pathname matching — requires a placed menu widget and controlled navigation - `'underline'`: bottom border on the active item and ancestor items - `'background'`: light background colour on the active item and ancestor items @@ -271,7 +266,6 @@ An item is "active" if its `url` matches the current window location (exact matc ### Requirement: REQ-MENU-007 Keyboard navigation The renderer MUST support keyboard navigation conforming to WAI-ARIA Menu/Menubar pattern: -@e2e exclude keyboard navigation tests complex focus-trap pattern — requires placed widget and keyboard sequence; Vitest scope - **Tab**: move focus to the next top-level item; if at the last item, move focus out of the widget. Close any open dropdowns/flyouts. - **Shift+Tab**: move focus to the previous top-level item; if at the first item, move focus out of the widget. Close any open dropdowns. @@ -314,7 +308,6 @@ The renderer MUST support keyboard navigation conforming to WAI-ARIA Menu/Menuba ### Requirement: REQ-MENU-008 External link handling When an item's `url` starts with `http://` or `https://`, it is treated as an external URL. Clicking an external URL MUST: -@e2e exclude external link handling tests rel=noopener on links — requires a placed menu widget with configured external links 1. Open the link in a new tab via `window.open(url, '_blank', 'noopener,noreferrer')` 2. Apply `rel="noopener noreferrer"` to any fallback `<a>` tag for progressive enhancement @@ -345,7 +338,6 @@ Internal URLs (starting with `/` or no protocol) MUST use `router.push()` or a s ### Requirement: REQ-MENU-009 Add/edit form with drag-and-drop editor The menu sub-form for `AddWidgetModal` MUST include: -@e2e exclude add/edit form with drag-and-drop editor tests complex form inside placed widget — requires seeded placement 1. A **Config section** with dropdowns for `style`, `orientation` (disabled for tree), `activeItemHighlight`, and toggles for `showIcons` and `expandedByDefault` (only shown for tree). 2. A **Tree editor** for building the `items` array: @@ -365,6 +357,7 @@ When editing an existing widget, all fields MUST pre-fill from `editingWidget.co - AND changes MUST update the content before save #### Scenario: Drag-and-drop reorders items +@e2e exclude never built: the menu widget's tree editor (CnMenuItemEditor in @conduction/nextcloud-vue, used by CnMenuWidgetForm) has add/remove/edit buttons but no drag handle or drop handling; the draggable CnMenuTreeNode is the app-manifest menu editor (ADR-041), not this form. No unit test exists - GIVEN a tree editor with two top-level items [A, B] - WHEN the user drags A below B @@ -387,7 +380,6 @@ When editing an existing widget, all fields MUST pre-fill from `editingWidget.co ### Requirement: REQ-MENU-010 Icon resolution The `icon` field of a menu item MUST follow the same dual-mode convention as `link-button-widget` (REQ-LBN-002): -@e2e exclude icon resolution tests IconRenderer dispatch — Vitest component scope - A custom URL (starts with `/` or `http`) MUST render as `<img>` inside the menu item - A bare name MUST render via the shared `IconRenderer` (built-in MDI component) @@ -397,7 +389,7 @@ Icon size MUST be 16-24 px (smaller than REQ-LBN-002's 48 px, to fit in a menu l #### Scenario: MDI icon in dropdown -- GIVEN content `{style: 'dropdown', items: [{label: 'Settings', icon: 'mdiCog'}]}` +- GIVEN content `{style: 'dropdown', items: [{label: 'Settings', icon: 'Cog'}]}` - WHEN the widget renders - THEN the item MUST display the settings icon to the left of "Settings" @@ -410,7 +402,6 @@ Icon size MUST be 16-24 px (smaller than REQ-LBN-002's 48 px, to fit in a menu l ### Requirement: REQ-MENU-011 Empty state When the `items` array is empty or not provided, the renderer MUST display a placeholder message: **"No menu items yet — click the gear icon to add some."** -@e2e exclude empty state tests Vue empty component inside a placed widget — requires seeded empty-menu placement The gear icon in the message MUST be clickable and open the edit form if the user is an admin/dashboard editor. For non-editors, the message MUST be non-interactive. diff --git a/openspec/specs/navigation-editor-org/screens.md b/openspec/specs/navigation-editor-org/screens.md new file mode 100644 index 000000000..dc43dea67 --- /dev/null +++ b/openspec/specs/navigation-editor-org/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerNavigatie https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerNavigatie diff --git a/openspec/specs/navigation-editor-org/spec.md b/openspec/specs/navigation-editor-org/spec.md index d85ff82d8..8bf6f1e2a 100644 --- a/openspec/specs/navigation-editor-org/spec.md +++ b/openspec/specs/navigation-editor-org/spec.md @@ -13,8 +13,6 @@ The capability owns its own storage (per-language JSON files inside LaunchPad's ## Data Model -@e2e exclude all scenarios test PHP OrgNavigationService API / IAppData storage — org-nav editor UI not present in v1.0.5 - ### Per-language tree storage Each language file lives at `IAppData('launchpad')/org-navigation/{lang}.json` (e.g. `nl.json`, `en.json`). Maximum file size: 5 MB. Files are written wholesale by `OrgNavigationService::setTree()`; per-node CRUD endpoints are intentionally NOT exposed. @@ -210,7 +208,7 @@ The system MUST provide a Vue 2.7 SFC `OrgNavigationPanel.vue` that renders the Each node's `icon` field MUST follow a dual-mode convention compatible with the link-button-widget: - A URL (starts with `/` or `http`) MUST render as an `<img>` element with `src=icon` -- A bare name MUST render as an inline label (the runtime panel renders the name; the admin editor uses a text input for the icon field) +- A bare name MUST render as the glyph that name resolves to in the dashboard icon registry (dashboard-icons REQ-ICON-009; legacy MDI names such as `briefcase` included), not as the name in text; the admin editor uses a text input for the icon field - An empty or null value MUST render no icon Icon size MUST be consistently 24 px square across all nav items. @@ -223,7 +221,8 @@ Icon size MUST be consistently 24 px square across all nav items. #### Scenario: Icon name renders inline - GIVEN a node with `icon: 'briefcase'` and `label: 'Business'` - WHEN the panel renders -- THEN the icon name MUST appear as inline text/label left of the label +- THEN the briefcase glyph MUST appear inline, left of the label +- AND the name "briefcase" MUST NOT appear as text #### Scenario: Missing icon renders no icon - GIVEN a node with `icon: null` and `label: 'Help'` diff --git a/openspec/specs/nc-dashboard-widget-proxy/screens.md b/openspec/specs/nc-dashboard-widget-proxy/screens.md new file mode 100644 index 000000000..17996e885 --- /dev/null +++ b/openspec/specs/nc-dashboard-widget-proxy/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag +- LpWidgetKiezen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetKiezen diff --git a/openspec/specs/nc-dashboard-widget-proxy/spec.md b/openspec/specs/nc-dashboard-widget-proxy/spec.md index 5a5aa9d93..c829b278c 100644 --- a/openspec/specs/nc-dashboard-widget-proxy/spec.md +++ b/openspec/specs/nc-dashboard-widget-proxy/spec.md @@ -16,8 +16,6 @@ configuring an `nc-widget` placement. ## Requirements -@e2e exclude NC widget picker UX lives inside the Add Widget modal — widget picker scenarios require real NC widgets to be installed; snapshot covered by wave3 tests - ### Requirement: REQ-NCDP-PICKER NC widget picker UX The `NcDashboardForm` sub-form's widget picker MUST render as a CSS-grid of cards, NOT a `<select>` dropdown. Each card MUST display: diff --git a/openspec/specs/nc-unified-search-integration/screens.md b/openspec/specs/nc-unified-search-integration/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/nc-unified-search-integration/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/nc-unified-search-integration/spec.md b/openspec/specs/nc-unified-search-integration/spec.md index 03d0082d0..2f8838d4b 100644 --- a/openspec/specs/nc-unified-search-integration/spec.md +++ b/openspec/specs/nc-unified-search-integration/spec.md @@ -11,8 +11,6 @@ Nextcloud's unified search (Ctrl+K / Cmd+K) provides a global discovery mechanis ## Requirements -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: REQ-SRCH-001 Search Provider Registration The LaunchPad app MUST register a search provider implementing Nextcloud's `OCP\Search\IProvider` interface so that pressing Ctrl+K / Cmd+K in Nextcloud automatically includes LaunchPad dashboards in the unified search results. @@ -26,12 +24,14 @@ The LaunchPad app MUST register a search provider implementing Nextcloud's `OCP\ - AND the provider's `getOrder()` MUST return `50` to position it mid-range (admin-search providers typically have lower order values) #### Scenario: Provider implements the IProvider contract +@e2e exclude a PHP type contract with no HTTP outcome of its own: `implements IProvider` and its method types are enforced by PHP when the class loads, and the four methods are exercised by tests/Unit/Search/LaunchPadSearchProviderTest.php::testGetIdReturnsLaunchPad, ::testGetNameIsTranslated, ::testGetOrderIsMidRange and ::testEmptyTermReturnsEmptyResult - GIVEN the LaunchPad app is installed - WHEN Nextcloud's search dispatcher calls the provider interface - THEN the provider class MUST implement all required methods: `getId()`, `getName()`, `getOrder()`, `search(IUser, ISearchQuery): SearchResult` - AND the methods MUST have correct type hints matching `OCP\Search\IProvider` #### Scenario: Provider initialization via app bootstrap +@e2e exclude internal PHP wiring: the registration is the registerSearchProvider() call in lib/AppInfo/Application.php and the other clause is a source-tree file location; no PHPUnit test pins the registration call, and its observable effect (the provider listed by /ocs/v2.php/search/providers) is cited under provider-is-registered-and-discoverable - GIVEN LaunchPad app info.xml declares `<types><search/></types>` - WHEN the LaunchPad app boots - THEN the container MUST register an instance of `LaunchPadSearchProvider` with the Nextcloud search registry @@ -141,6 +141,7 @@ When the `dashboard-metadata-fields` capability is enabled, the search provider - AND the resourceUrl MUST deep-link to the dashboard #### Scenario: Metadata search falls back gracefully +@e2e exclude needs the dashboard-metadata-fields capability absent, which a running instance cannot be put into (MetadataService is always installed); the degradation path (metadata lookup throws, dashboard match still returned, no error) is pinned by tests/Unit/Search/LaunchPadSearchProviderEdgeCaseTest.php::testFailingLookupsKeepTheDashboardMatch - GIVEN the `dashboard-metadata-fields` capability is NOT available in the LaunchPad app - WHEN user "bob" performs a search - THEN the search provider MUST still return dashboard-name, description, and widget-content results @@ -187,6 +188,7 @@ The search provider MUST never return search results for dashboards that the use - NOTE: Permission checking delegates to the existing `permissions` capability's group-membership logic #### Scenario: Permission service unavailable (fail safe) +@e2e exclude needs DashboardService::getVisibleToUser() to throw, which cannot be induced on a running instance; pinned by tests/Unit/Search/LaunchPadSearchProviderTest.php::testGetVisibleToUserFailureReturnsEmpty - GIVEN the `permissions` capability or visibility service throws unexpectedly - WHEN a search is performed - THEN the search provider MUST catch the failure and return an empty `SearchResult` @@ -313,12 +315,14 @@ When a search query matches no dashboards, widgets, or metadata fields, the prov The search provider MUST complete typical queries inside Nextcloud's unified-search response budget by capping the per-bucket result count and reusing the canonical visibility boundary as the upstream filter. #### Scenario: Bounded scan over the visible set +@e2e exclude internal query count with no HTTP read (needs 1,000 dashboards and SQL instrumentation); the per-bucket cap stopping placement and metadata lookups is pinned by tests/Unit/Search/LaunchPadSearchProviderTest.php::testEachBucketIsCappedAndRankedDashboardsWidgetsMetadata, and the response-size cap is cited under the REQ-SRCH-007 scenarios - GIVEN a LaunchPad instance where user "alice" can view 1,000 dashboards - WHEN she performs a search query - THEN the provider's `search()` method MUST complete a single in-memory pass over the visible set without making per-dashboard SQL queries beyond the placement and metadata fetches needed for matching - AND the per-bucket cap (10 dashboards, 10 widgets, 10 metadata) bounds the response size #### Scenario: Permission checks do not degrade performance +@e2e exclude internal call count with no HTTP read; no test exists that asserts getVisibleToUser() is called exactly once per search (the unit tests stub it with method(), not expects(once())) - GIVEN user "bob" performs a search - WHEN the provider invokes `DashboardService::getVisibleToUser()` - THEN the visibility resolution MUST happen exactly once per search (single set returned) @@ -374,6 +378,44 @@ The LaunchPad search provider MUST be positioned at order `50` so that it appear - WHEN the search is invoked - THEN `getOrder()` MAY return a lower numeric value (e.g., `5`) to surface LaunchPad results first +### Requirement: REQ-SRCH-013 The top bar search shows its results under the field + +On a LaunchPad page, typing two or more characters in the top bar's search field MUST open a results list under the field, as wide as the field. The list MUST start with "You searched for <query>", MUST group the results per search provider under the provider's name in capitals, with LaunchPad's dashboards first, and MUST show each result with its icon, its name and one line of detail (for a dashboard: who shared it and how many widgets it has, or the group it belongs to). When search shortcuts are configured, the list MUST end with "Tip: type <prefix> to search <name> directly" for the first one. + +The list MUST behave as a combobox (WAI-ARIA 1.2): the field has `role="combobox"` and `aria-expanded`, the list has `role="listbox"`, and each result has `role="option"`. The first result is selected when the list opens. Arrow keys move the selection, Enter opens the selected result, and Escape closes the list and keeps the query. A "Show all results" row MUST hand the query to Nextcloud's own search dialog. + +#### Scenario: Results under the field + +- **GIVEN** Pieter is on My workspace and can see the dashboards "Permits team" and "Zuiddrecht intranet" +- **WHEN** he types "team" in the top bar's search field +- **THEN** a list opens under the field that starts with "You searched for team" +- **AND** under "DASHBOARDS" it shows "Permits team" with "Shared by Marieke Jansen · 14 widgets", selected, and "Zuiddrecht intranet" with "Group dashboard of Communications" + +#### Scenario: The keyboard drives the list + +- **GIVEN** the list is open for "team" with "Permits team" selected +- **WHEN** Pieter presses Arrow down and then Enter +- **THEN** "Zuiddrecht intranet" opens + +#### Scenario: The shortcut tip + +- **GIVEN** the shortcut "!top" for TOPdesk is configured +- **WHEN** the list opens +- **THEN** its last row reads "Tip: type !top to search TOPdesk directly" + +#### Scenario: Escape closes the list + +- **GIVEN** the list is open +- **WHEN** Pieter presses Escape +- **THEN** the list closes, the field keeps "team" and keeps the focus + +#### Scenario: A top bar without a field + +- **GIVEN** the Nextcloud version's desktop top bar has only a button that opens the search dialog (Nextcloud 31 and later) +- **WHEN** Pieter opens a LaunchPad page +- **THEN** a search field stands in the button's place, with the button's words +- **AND** typing in it opens the list as above, and "Show all results" still opens Nextcloud's search dialog + --- ## Dependencies @@ -406,4 +448,5 @@ The LaunchPad search provider MUST be positioned at order `50` so that it appear - REQ-SRCH-010 (Performance): One `getVisibleToUser()` call yields the candidate set; placement and metadata fetches are O(matching dashboards) and bounded by the per-bucket cap. - REQ-SRCH-011 (UI integration): Result `resourceUrl` is built via `IURLGenerator::linkToRouteAbsolute('launchpad.page.index')` plus a `#dashboard/<uuid>` fragment, and (for widget matches) a `;widget=<placementId>` hint inside the same fragment so the SPA can deep-link without a separate redirect route. - REQ-SRCH-012 (Order): `getOrder()` returns `50` by default; when the current route starts with `launchpad.`, it returns `5` to boost in-app discoverability. +- REQ-SRCH-013 (Results under the field): `src/components/HeaderSearchDropdown.vue`, mounted by `src/utils/headerSearchMount.js`, binds to the top bar's field through `src/utils/headerSearchField.js`; on Nextcloud 31+ (button only) that places LaunchPad's own field in the button's place. Archived change: `openspec/changes/archive/2026-11-25-header-search-dropdown`. - Tests: `tests/Unit/Search/LaunchPadSearchProviderTest.php` covers id/name/order, empty term, name/description matches, case-insensitive matching, widget-content matches with deep-link, HTML stripping, non-text widget skipping, metadata value matches, key-vs-value distinction, permission denial, visibility-boundary failure, the 10-result cap, and malformed `styleConfig` resilience. diff --git a/openspec/specs/news-widget/screens.md b/openspec/specs/news-widget/screens.md new file mode 100644 index 000000000..dc3c1e999 --- /dev/null +++ b/openspec/specs/news-widget/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet +- LpStart https://identity.conduction.nl/screens/board?id=wilgenboom/LpStart +- LpStart https://identity.conduction.nl/screens/board?id=vaartveld/LpStart diff --git a/openspec/specs/news-widget/spec.md b/openspec/specs/news-widget/spec.md index dfbdcdebe..c81de3923 100644 --- a/openspec/specs/news-widget/spec.md +++ b/openspec/specs/news-widget/spec.md @@ -30,20 +30,26 @@ Two admin-config settings are read on demand (created lazily by `IAppConfig`): ## Requirements - -@e2e exclude all scenarios test PHP NewsWidgetService RSS-fetch / feed-endpoint — requires live RSS feeds and background-job setup not available in test env - ### Requirement: REQ-NEWS-001 Widget Registration -The system MUST register a new dashboard widget with id `launchpad_news` via `OCP\Dashboard\IManager` that appears in the widget picker alongside other discovered Nextcloud dashboard widgets. +The system MUST register a new dashboard widget with id `launchpad_news` with Nextcloud's dashboard (`OCP\Dashboard\IManager`) that appears in the widget picker alongside other discovered Nextcloud dashboard widgets. On Nextcloud's own dashboard it serves the newest articles from the feeds of the news widgets on the dashboards the user owns. #### Scenario: Widget registration on bootstrap - GIVEN LaunchPad is installed and enabled -- WHEN the application bootstraps (AppInfo/Bootstrap.php or equivalent lifecycle hook) -- THEN the system MUST call `IManager::registerWidget()` with widget metadata -- AND the widget MUST have id `launchpad_news`, translatable title (e.g., `app.launchpad.news_widget_title`), and a feed/newspaper icon URL +- WHEN the application bootstraps (`Application::register()`) +- THEN the system MUST register the widget class `OCA\LaunchPad\Dashboard\NewsWidget` through `IRegistrationContext::registerDashboardWidget()`, which hands it to `IManager` lazily +- AND the widget MUST have id `launchpad_news`, the translated title "News", and a newspaper icon URL - AND the widget MUST support Nextcloud Dashboard Widget API v2 (`IAPIWidgetV2`) for item loading +#### Scenario: Nextcloud dashboard items come from own news widgets +- GIVEN a user owns dashboards with `news` placements +- WHEN Nextcloud's dashboard asks `launchpad_news` for items (`GET /ocs/v2.php/apps/dashboard/api/v2/widget-items`) +- THEN the items MUST be the newest articles across the distinct feed URLs of those placements, read in one query and each feed fetched once, through the same allow-list, SSRF guard and cache as REQ-NEWS-003 to REQ-NEWS-008 +- AND a placement whose metadata filter does not match its dashboard MUST contribute no feeds (REQ-NEWS-007) +- AND placements on dashboards of other users MUST NOT be read +- AND each item MUST carry the article title, the feed title as subtitle, a web link (the feed URL when the article link is not http(s)) and the thumbnail or the news icon +- AND without any feed the empty state MUST tell the user to add a news widget with a feed, and with feeds but no articles it MUST say there are no articles right now, in the user's language + #### Scenario: Widget picker includes news widget - GIVEN a user opens the widget picker dialog - WHEN the picker loads available Nextcloud widgets @@ -104,6 +110,7 @@ Widget placements MUST store configuration in the `widgetContent` JSON field to - AND if the filter does not match, the widget MUST not fetch items (see REQ-NEWS-008) #### Scenario: Config defaults and fallback +@e2e exclude extractNewsConfig() is an internal PHP function with no output of its own; its defaults are pinned by tests/Unit/Service/NewsWidgetServiceTest.php::testExtractNewsConfigAppliesDefaults (the renderer's own defaults are asserted by news-widget::configure-thumbnail-and-summary-display) - GIVEN a placement has empty or minimal widgetContent - WHEN the service calls `extractNewsConfig(placement)` - THEN defaults MUST apply: feedUrls=[], layout=list, itemLimit=10, showThumbnails=true, showSummary=true, summaryMaxChars=200, dateFormat=relative, metadataFilter=null @@ -113,18 +120,21 @@ Widget placements MUST store configuration in the `widgetContent` JSON field to The backend MUST provide an endpoint to fetch, parse, and return merged feed items from all configured sources. #### Scenario: Fetch items for a news widget placement +@e2e exclude needs feeds that return items, and every feed must resolve to a public host the CI fixture does not provide; the item shape is pinned by tests/Unit/Service/NewsWidgetServiceTest.php::testParseRssFeedExtractsItemFields and the endpoint's pass-through by tests/Unit/Controller/WidgetApiControllerDataEndpointsTest.php::testNewsItemsReturnsTheServicePayloadIncludingFailureCounters - GIVEN a placement (id=42) has config `{"feedUrls": ["https://example.com/rss", "https://other.org/feed"]}` - WHEN the frontend sends GET /api/widgets/news/42/items?limit=10 - THEN the system MUST call `NewsWidgetService::getItemsForPlacement(42, 10)` - AND return HTTP 200 with a JSON array of items: `[{guid, title, summary, link, pubDate, sourceUrl, sourceTitle, thumbnailUrl}]` #### Scenario: Items sorted by publication date (newest first) +@e2e exclude needs live feeds with items, which the CI fixture cannot serve (public hosts only); pinned by tests/Unit/Service/NewsWidgetServiceTest.php::testSortItemsByDateDescending - GIVEN feed sources contain items with pubDates [2026-05-01T14:00, 2026-04-30T10:00, 2026-05-01T16:00] - WHEN items are merged and returned - THEN the response order MUST be: [2026-05-01T16:00, 2026-05-01T14:00, 2026-04-30T10:00] - AND sorting MUST be descending (newest first) #### Scenario: Deduplicate items across feeds +@e2e exclude needs two live feeds sharing a guid, which the CI fixture cannot serve; pinned by tests/Unit/Service/NewsWidgetServiceTest.php::testDeduplicateItemsKeepsFirstOccurrence - GIVEN feed A has item guid="article-123" and feed B also has guid="article-123" - WHEN items are merged - THEN only one copy of the item MUST be included @@ -132,12 +142,14 @@ The backend MUST provide an endpoint to fetch, parse, and return merged feed ite - AND if the sources differ, the sourceTitle MUST indicate both (or the first found) #### Scenario: Item deduplication by guid +@e2e exclude needs live feeds, which the CI fixture cannot serve; the synthetic guid is pinned by tests/Unit/Service/FeedItemParserTest.php::testMissingGuidIsDerivedFromTitleDateAndUrl and the dedup key by tests/Unit/Service/NewsWidgetServiceTest.php::testDeduplicateItemsKeepsFirstOccurrence - GIVEN multiple feeds include the same article (identified by matching guid) - WHEN items are deduplicated - THEN the guid field MUST be the primary deduplication key - AND items without a guid MUST generate a synthetic guid from hash(title + pubDate + sourceUrl) #### Scenario: Response includes source attribution +@e2e exclude needs a live feed, which the CI fixture cannot serve; pinned by tests/Unit/Service/FeedItemParserTest.php::testRssItemIsNormalisedWithChannelTitle and tests/Unit/Service/NewsWidgetServiceFetchTest.php::testBareChannelRootAndTitleFallback (rendering the source is asserted by news-widget::list-layout-default) - GIVEN an item from feed "https://example.com/rss" - WHEN returned in the API response - THEN the item object MUST include: @@ -162,6 +174,7 @@ The backend MUST provide an endpoint to fetch, parse, and return merged feed ite The widget MUST read from a feed-cache table (populated by the `background-job-feed-refresh` change) and only perform on-demand fetches on cold-start. #### Scenario: Cache hit — serve from background job refresh +@e2e exclude whether an upstream request happens and how long a lookup takes are server internals with no browser or API surface, and a fresh cache entry needs a live feed; pinned by tests/Unit/Service/NewsWidgetServiceFetchTest.php::testCacheHitSkipsTheNetwork - GIVEN a feed "https://example.com/rss" was fetched 5 minutes ago - AND the cache entry is fresh (TTL 60 minutes not expired) - WHEN the widget requests items @@ -170,6 +183,7 @@ The widget MUST read from a feed-cache table (populated by the `background-job-f - AND response time MUST be sub-100ms (in-database lookup) #### Scenario: Cache miss — on-demand fetch (cold-start) +@e2e exclude needs a live feed to fetch and cache, which the CI fixture cannot serve; pinned by tests/Unit/Service/NewsWidgetServiceFetchTest.php::testLiveFetchIsCachedAndReported - GIVEN a feed cache has no entry for "https://example.com/rss" - WHEN the widget requests items for the first time - THEN the system MUST perform a synchronous HTTP fetch to https://example.com/rss @@ -177,6 +191,7 @@ The widget MUST read from a feed-cache table (populated by the `background-job-f - AND subsequent requests within TTL MUST use the cache (delegating refresh to background job) #### Scenario: Cache TTL configuration +@e2e exclude a cache entry's expiry has no outside surface and needs a live feed; the TTL read from news_widget_feed_cache_ttl_seconds (default 3600) is pinned by tests/Unit/Service/NewsWidgetServiceFetchTest.php::testLiveFetchIsCachedAndReported - GIVEN an admin sets `launchpad.news_widget_feed_cache_ttl_seconds` to 1800 (30 minutes) - WHEN a feed is cached - THEN the cache entry MUST expire after 1800 seconds @@ -184,6 +199,7 @@ The widget MUST read from a feed-cache table (populated by the `background-job-f - AND default TTL MUST be 3600 seconds (60 minutes) #### Scenario: Dependency on background-job-feed-refresh +@e2e exclude the GIVEN cannot be produced: background-job-feed-refresh has shipped (lib/Job/FeedRefreshJob.php), and the synchronous fetch path needs a live feed; that path is pinned by tests/Unit/Service/NewsWidgetServiceFetchTest.php::testLiveFetchIsCachedAndReported. No test pins the WARN log the scenario asks for - GIVEN the `background-job-feed-refresh` change has NOT been implemented - WHEN the widget attempts to fetch items - THEN the widget MUST fall back to synchronous on-demand fetch (graceful degradation) @@ -230,12 +246,14 @@ Feed item summaries MUST be sanitised to remove dangerous HTML while preserving An admin setting MUST restrict feed sources to an explicit allow-list of hostnames. #### Scenario: Allow-list is empty or null (all hosts allowed) +@e2e exclude accepting and fetching a URL needs a live public feed, which the CI fixture does not provide; pinned by tests/Unit/Service/UrlSafetyValidatorTest.php::testAnUnsetAllowListAllowsEveryHost and tests/Unit/Service/NewsWidgetServiceTest.php::testCheckAllowListAcceptsAllWhenEmpty - GIVEN the admin setting `launchpad.news_widget_allowed_feed_hosts` is `null` or `[]` - WHEN a widget specifies feedUrl "https://any-domain.com/feed" - THEN the system MUST accept and fetch from the URL - AND no whitelist check failure MUST occur #### Scenario: Allow-list restricts to specified hosts +@e2e exclude from outside, an allow-list skip is indistinguishable from any other failed fetch unless an allowed host can succeed, which needs a live public feed; pinned by tests/Unit/Service/UrlSafetyValidatorTest.php::testAConfiguredListAllowsExactlyItsHosts and tests/Unit/Service/NewsWidgetServiceTest.php::testCheckAllowListRejectsHostnamesNotInList - GIVEN the admin sets `launchpad.news_widget_allowed_feed_hosts` to `["bbc.com", "example.org"]` - WHEN a widget specifies feedUrl "https://bbc.com/rss" - THEN the system MUST allow the fetch @@ -243,6 +261,7 @@ An admin setting MUST restrict feed sources to an explicit allow-list of hostnam - THEN the fetch MUST be silently skipped (not allowed) #### Scenario: Disallowed feed is skipped without error +@e2e exclude the other allowed feeds that must keep loading need a live public feed, and the skip reason is only in the server log; pinned by tests/Unit/Service/NewsWidgetServiceFetchTest.php::testUnsafeAndDisallowedUrlsFailInOrder (the badge for a skipped feed is asserted by news-widget::failure-badge-single-failure) - GIVEN feedUrl "https://blocked-domain.com/feed" fails the allow-list check - WHEN the widget attempts to fetch items - THEN the URL MUST be silently skipped (not causing the entire widget to fail) @@ -251,11 +270,13 @@ An admin setting MUST restrict feed sources to an explicit allow-list of hostnam - AND a failure badge MUST note "1 feed skipped (disallowed)" or similar #### Scenario: Hostname comparison is case-insensitive +@e2e exclude a pure host comparison with no outside surface short of a live feed; pinned by tests/Unit/Service/NewsWidgetServiceTest.php::testCheckAllowListMatchesCaseInsensitively - GIVEN the allow-list contains "Example.Org" - WHEN feedUrl "https://example.org/feed" is checked - THEN the match MUST succeed (case-insensitive comparison) #### Scenario: Subdomain matching +@e2e exclude a pure host comparison with no outside surface short of a live feed; pinned by tests/Unit/Service/NewsWidgetServiceTest.php::testCheckAllowListSubdomainNotImplied - GIVEN the allow-list contains "example.org" - WHEN feedUrl "https://news.example.org/feed" is checked - THEN the match MUST fail (exact hostname required, no wildcard subdomain expansion) @@ -295,6 +316,7 @@ The system MUST support optional metadata-based filtering: if a widget specifies - AND return empty items array #### Scenario: Metadata filter dependency on dashboard-metadata-fields spec +@e2e exclude the GIVEN cannot be produced: dashboard-metadata-fields has shipped (lib/Service/MetadataService.php, /api/dashboards/{uuid}/metadata). Its observable outcome, a missing field yields no items, is the e2e of news-widget::metadata-field-missing-or-null; tests/Unit/Service/NewsWidgetServiceTest.php::testCheckMetadataFilterRejectsWhenSpecNotImplemented pins the stub - GIVEN the sibling spec `dashboard-metadata-fields` is NOT yet implemented - WHEN a widget specifies a metadata filter - THEN the system MUST gracefully handle missing metadata (treat as no fields defined) @@ -312,6 +334,7 @@ A single feed source failure MUST NOT break the widget. Successful feeds MUST re - AND a failure badge (top-right corner) MUST show "1 feed failed" with hover tooltip listing "bad.com" #### Scenario: HTTP error handling +@e2e exclude needs a public host answering 404/403/5xx, which the CI fixture does not provide; pinned by tests/Unit/Service/NewsWidgetServiceFetchTest.php::testNonSuccessStatusFailsTheFeed (the failedUrls metadata and badge for a failed feed are the e2e of news-widget::all-feeds-fail) - GIVEN a feed URL returns HTTP 404, 403, or 5xx - WHEN the widget fetches - THEN the system MUST log a WARN-level message and skip the URL @@ -319,6 +342,7 @@ A single feed source failure MUST NOT break the widget. Successful feeds MUST re - AND the failure badge MUST be displayed #### Scenario: Timeout handling +@e2e exclude needs a public host that stalls past 10 seconds, which the CI fixture does not provide; the 10s timeout and the skip are pinned by tests/Unit/Service/NewsWidgetServiceFetchTest.php::testLiveFetchIsCachedAndReported (fetch options) and ::testClientExceptionIsLoggedAndReported - GIVEN an HTTP fetch to a feed URL takes longer than 10 seconds - WHEN the system is fetching - THEN the fetch MUST timeout and be skipped @@ -326,6 +350,7 @@ A single feed source failure MUST NOT break the widget. Successful feeds MUST re - AND the failure badge MUST count this as a failed feed #### Scenario: Malformed feed XML +@e2e exclude needs a public host answering 200 with broken XML, which the CI fixture does not provide. Note tests/Unit/Service/NewsWidgetServiceTest.php::testParseRssFeedReturnsEmptyOnGarbage pins the OPPOSITE of the last THEN: a malformed feed parses to no items and is not counted as failed - GIVEN a feed returns valid HTTP 200 but invalid/malformed RSS/Atom XML - WHEN the system attempts to parse - THEN parsing MUST fail gracefully diff --git a/openspec/specs/office-tiles/spec.md b/openspec/specs/office-tiles/spec.md new file mode 100644 index 000000000..51c2bc7c8 --- /dev/null +++ b/openspec/specs/office-tiles/spec.md @@ -0,0 +1,34 @@ +# office-tiles Specification + +## Purpose +Office tiles give a user ready-made tiles for the office suite the server has: one container with a "New ..." tile for each kind of document an installed office app can create, and a tile for each office app, so nobody sets them up one by one. + +## Requirements + +### Requirement: The add flow offers an office tile pack built from what the server has (REQ-OFT-001) + +The add flow MUST offer "Office tiles". Choosing it MUST place one container titled "Office" with a "New ..." tile for each file creator the server's office apps register, and tiles for Files, Mail, Calendar, Contacts and Talk when those apps are enabled for the user. It MUST NOT list an app the user cannot open. + +#### Scenario: Pack on a server with Nextcloud Office + +- **GIVEN** Nextcloud Office, Mail and Calendar are enabled and Contacts is not +- **WHEN** Pieter chooses "Office tiles" while editing "Mijn werkplek" +- **THEN** a container "Office" appears at the bottom with "New document", "New spreadsheet", "New presentation", "Files", "Mail" and "Calendar" +- **AND** there is no "Contacts" tile + +### Requirement: A "New ..." tile creates a real document and never overwrites (REQ-OFT-002) + +Clicking a "New ..." tile MUST ask for a name and folder, create the file from the office app's own blank template, choose a free name when the file exists, and open the new file in its editor. + +#### Scenario: New document twice + +- **GIVEN** Pieter's container "Office" has "New document" +- **WHEN** he clicks it, names the file "Notulen" and confirms +- **THEN** `Documents/Notulen.docx` is created from the editor's blank template and opens in the editor +- **AND WHEN** he does the same again, `Documents/Notulen (2).docx` is created and the first file is unchanged + +#### Scenario: Unknown creator refused + +- **GIVEN** a request to `POST /api/office-tiles/create` naming a creator id the server does not register +- **WHEN** the server handles it +- **THEN** the response is 400 and no file is created diff --git a/openspec/specs/orphaned-data-cleanup/screens.md b/openspec/specs/orphaned-data-cleanup/screens.md new file mode 100644 index 000000000..1a9099128 --- /dev/null +++ b/openspec/specs/orphaned-data-cleanup/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerOnderhoud https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerOnderhoud diff --git a/openspec/specs/orphaned-data-cleanup/spec.md b/openspec/specs/orphaned-data-cleanup/spec.md index bb170b5d8..ac16d1f82 100644 --- a/openspec/specs/orphaned-data-cleanup/spec.md +++ b/openspec/specs/orphaned-data-cleanup/spec.md @@ -35,8 +35,6 @@ Default auto-purge list: Tier-A (expired_locks, expired_share_tokens). Returned ## Requirements -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: REQ-CLN-001 Scan CLI Command Administrators MUST be able to run a CLI command that reports all orphaned items by category WITHOUT deleting. @@ -51,6 +49,8 @@ Administrators MUST be able to run a CLI command that reports all orphaned items - Return exit code 1 (nonzero) to signal that orphans exist - AND the output MUST include rows for every shipped category with their counts and a TOTAL row +@e2e exclude needs `occ launchpad:cleanup:scan`, which the e2e suite cannot run (no shell into the instance), and three expired locks plus orphaned shares and placements that no HTTP path can create: every delete cascades and a lock expires only 15 minutes after its heartbeat. Pinned by tests/Unit/Command/CleanupScanCommandTest.php::testScanOutput (table rows, TOTAL row, exit code 1); the per-category counting by tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testScanAggregatesCountsAcrossRegistry. + #### Scenario: Scan finds no orphans - GIVEN a clean LaunchPad installation with no orphaned data @@ -58,6 +58,8 @@ Administrators MUST be able to run a CLI command that reports all orphaned items - THEN the system MUST display a table with all categories showing count 0 - AND return exit code 0 (success, no orphans) +@e2e exclude needs `occ launchpad:cleanup:scan`, which the e2e suite cannot run. Pinned by tests/Unit/Command/CleanupScanCommandTest.php::testScanOutput (all-zero table ending in `TOTAL 0`, exit code 0). + #### Scenario: Scan handles missing tables gracefully - GIVEN a LaunchPad installation where a feature (e.g., dashboard-rss-feeds) is not yet enabled @@ -66,6 +68,8 @@ Administrators MUST be able to run a CLI command that reports all orphaned items - AND list the skipped categories under a "Skipped categories" comment line - AND return 0 if no other orphans exist +@e2e exclude needs `occ` and a category whose `isAvailable()` is false; all four shipped categories are always available (CategoryRegistryService), so no instance can show a skipped one. Pinned by tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testScanSkipsUnavailableCategories and the `Skipped categories` line in tests/Unit/Command/CleanupScanCommandTest.php::testScanOutput. + ### Requirement: REQ-CLN-002 Purge CLI Command Administrators MUST be able to run a CLI command to DELETE orphaned items, with confirmation and per-category selectivity. @@ -78,12 +82,16 @@ Administrators MUST be able to run a CLI command to DELETE orphaned items, with - AND if the user confirms (`y`), delete all orphaned items and display a summary `Purged N items across M categories in Xms.` - AND if the user declines, display `Purge cancelled.` and exit 0 without deleting +@e2e exclude needs an interactive `occ launchpad:cleanup:purge` session, which the e2e suite cannot run. Pinned by the `confirmed` and `declined` cases of tests/Unit/Command/CleanupPurgeCommandTest.php::testRunsMatchTheRecording. + #### Scenario: Purge with --yes flag (non-interactive) - GIVEN orphaned data exists - WHEN an administrator runs `php occ launchpad:cleanup:purge --yes` - THEN the system MUST delete all orphaned items immediately (no prompt) and exit 0 +@e2e exclude needs `occ launchpad:cleanup:purge --yes`, which the e2e suite cannot run. Pinned by the `with skipped` case of tests/Unit/Command/CleanupPurgeCommandTest.php::testRunsMatchTheRecording; the same deletion over HTTP is cited by purge-categories-via-api. + #### Scenario: Purge specific category - GIVEN orphaned data across multiple categories @@ -91,12 +99,16 @@ Administrators MUST be able to run a CLI command to DELETE orphaned items, with - THEN the system MUST delete only orphans in `expired_locks` - AND display `Purged N items from category 'expired_locks' in Xms.` +@e2e exclude needs `occ launchpad:cleanup:purge --category=...`, which the e2e suite cannot run. Pinned by the `one category` case of tests/Unit/Command/CleanupPurgeCommandTest.php::testRunsMatchTheRecording. + #### Scenario: Purge non-existent category - GIVEN a valid cleanup setup - WHEN an administrator runs `php occ launchpad:cleanup:purge --category=invalid_category --yes` - THEN the system MUST display an error naming the invalid category, list valid categories, and return exit code 1 +@e2e exclude needs `occ`, which the e2e suite cannot run. Pinned by the `unknown category` case of tests/Unit/Command/CleanupPurgeCommandTest.php::testRunsMatchTheRecording; the HTTP equivalent is cited by unknown-category-yields-http-400. + ### Requirement: REQ-CLN-003 Dry-Run Safety Mode The purge CLI command MUST support a `--dry-run` flag that reports what WOULD be deleted without actually deleting. The scan command is always non-destructive. @@ -109,6 +121,8 @@ The purge CLI command MUST support a `--dry-run` flag that reports what WOULD be - AND display `DRY-RUN: Would purge N items across M categories in Xms.` - AND leave all data untouched +@e2e exclude needs `occ launchpad:cleanup:purge --dry-run`, which the e2e suite cannot run. The rollback is pinned by tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testDryRunRollsBackAndDoesNotEmitEvent and the output by the `all categories dry run` case of tests/Unit/Command/CleanupPurgeCommandTest.php::testRunsMatchTheRecording; the HTTP dry run is cited by purge-with-dryruntrue. + #### Scenario: Dry-run with category filter - GIVEN orphans in multiple categories @@ -116,6 +130,8 @@ The purge CLI command MUST support a `--dry-run` flag that reports what WOULD be - THEN the system MUST report `DRY-RUN: Would purge N items from category 'expired_locks' in Xms.` - AND delete nothing +@e2e exclude needs `occ`, which the e2e suite cannot run. Pinned by tests/Unit/Command/CleanupPurgeCommandTest.php::testRunsMatchTheRecording (category and dry-run handling) and tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testDryRunRollsBackAndDoesNotEmitEvent. + ### Requirement: REQ-CLN-004 Scan API Endpoint Administrators MUST be able to call an HTTP API endpoint to retrieve scan results as JSON, with caching. @@ -143,7 +159,9 @@ Administrators MUST be able to call an HTTP API endpoint to retrieve scan result - GIVEN an unauthenticated or non-admin user - WHEN they send `GET /api/admin/cleanup/scan` -- THEN the system MUST return HTTP 403 Forbidden +- THEN Nextcloud's admin-setting check MUST refuse the call before LaunchPad runs, in Nextcloud's own shape +- AND a signed-in non-admin MUST receive HTTP 403 with `{"message": "Logged in account must be an admin, a sub admin or gotten special right to access this setting"}` +- AND a request without a session MUST receive HTTP 401 with `{"message": "Current user is not logged in"}` ### Requirement: REQ-CLN-005 Purge API Endpoint @@ -177,7 +195,7 @@ Administrators MUST be able to POST to an API endpoint to trigger purge with per - GIVEN a non-admin user - WHEN they send `POST /api/admin/cleanup/purge` -- THEN the system MUST return HTTP 403 Forbidden +- THEN the system MUST return Nextcloud's HTTP 403 with `{"message": "Logged in account must be an admin, a sub admin or gotten special right to access this setting"}` and purge nothing ### Requirement: REQ-CLN-006 Per-Category Breakdown @@ -190,6 +208,8 @@ The scan and purge results MUST include a per-category breakdown so administrato - THEN the output table MUST display one row per category with name and count, in registration order - AND a TOTAL row MUST follow with the sum of all categories +@e2e exclude asserts the `occ launchpad:cleanup:scan` table, which the e2e suite cannot run. Pinned by tests/Unit/Command/CleanupScanCommandTest.php::testScanOutput (rows in registration order, then TOTAL); registration order over HTTP is asserted by the scan test in tests/e2e/orphaned-data-cleanup.spec.ts. + #### Scenario: Purge API returns per-category counts - GIVEN a `POST /api/admin/cleanup/purge` request @@ -209,6 +229,8 @@ A scheduled daily job MUST run and automatically purge a safe-to-auto-purge subs - AND call `OrphanedDataCleanupService::purge` with that list and `source='job'` - AND the orchestrator MUST emit one activity event when the total purge count is non-zero +@e2e exclude needs the daily OrphanedDataCleanupJob to run, and a background-job tick cannot be triggered for a specific job over HTTP. Pinned by tests/Unit/BackgroundJob/OrphanedDataCleanupJobTest.php::testCategoriesThePurgeRuns (empty config purges the Tier-A list) and tests/Unit/BackgroundJob/OrphanedDataCleanupJobScheduleTest.php::testRunsDailyAndIsNotTimeSensitive / testPurgeIsARealJobRunWithoutAUser (24h interval, `source='job'`). + #### Scenario: Admin overrides auto-purge category list - GIVEN the admin sets `cleanup_auto_purge_categories` to a JSON-encoded list (e.g. `["expired_locks"]`) @@ -216,15 +238,19 @@ A scheduled daily job MUST run and automatically purge a safe-to-auto-purge subs - THEN the job MUST purge only the categories in the configured list - AND skip unknown / non-string entries silently +@e2e exclude needs the daily background job to run, which cannot be triggered over HTTP. Pinned by tests/Unit/BackgroundJob/OrphanedDataCleanupJobTest.php::testCategoriesThePurgeRuns (the `["rules","",5,"nope","shares"]` case drops unknown and non-string entries). + #### Scenario: Auto-purge job is skipped if no categories enabled - GIVEN `cleanup_auto_purge_categories` is set to an empty JSON array (`"[]"`) - WHEN the daily job is scheduled to run - THEN the job MUST resolve the list to `[]`, log `launchpad.cleanup.job_skipped reason=no_categories_enabled`, and return without invoking the orchestrator +@e2e exclude needs the daily background job to run, which cannot be triggered over HTTP. Pinned by tests/Unit/BackgroundJob/OrphanedDataCleanupJobScheduleTest.php::testAnEmptyConfiguredListPurgesNothing and the `job_skipped reason=no_categories_enabled` case of tests/Unit/BackgroundJob/OrphanedDataCleanupJobTest.php::testCategoriesThePurgeRuns. + ### Requirement: REQ-CLN-008 Safe-to-Auto-Purge List -The implementation MUST define which categories are safe enough to auto-purge without admin inspection. The shipped Tier-A list MUST contain exactly the two zero-impact categories: `expired_locks` and `expired_share_tokens`. Each category exposes its tier through `CleanupCategoryInterface::getSafeToPurgeAutomatically()`. +The implementation MUST define which categories are safe enough to auto-purge without admin inspection. The shipped Tier-A list MUST contain exactly the two zero-impact categories: `expired_locks` and `expired_share_tokens`. Each category exposes its tier through `CleanupCategoryInterface::isSafeToPurgeAutomatically()`. #### Scenario: Default auto-purge list is Tier-A only @@ -232,12 +258,16 @@ The implementation MUST define which categories are safe enough to auto-purge wi - WHEN the daily job resolves its auto-purge list - THEN the system MUST default to `["expired_locks", "expired_share_tokens"]` as returned by `CategoryRegistryService::getAutoSafeCategoryNames()` +@e2e exclude the list is resolved inside the daily background job, which cannot be triggered over HTTP. Pinned by tests/Unit/Service/Cleanup/CategoryRegistryServiceTest.php::testGetAutoSafeCategoryNamesReturnsTierAOnly and the empty-config case of tests/Unit/BackgroundJob/OrphanedDataCleanupJobTest.php::testCategoriesThePurgeRuns. + #### Scenario: Admin opts into more aggressive auto-purge - GIVEN the admin sets `cleanup_auto_purge_categories` to include a Tier-B category - WHEN the daily job runs - THEN it MUST purge that category in addition to the configured Tier-A entries +@e2e exclude needs the daily background job to run, which cannot be triggered over HTTP. Pinned by tests/Unit/BackgroundJob/OrphanedDataCleanupJobTest.php::testCategoriesThePurgeRuns (a configured list including a Tier-B category is purged as given). + ### Requirement: REQ-CLN-009 Audit Logging Every successful real (non-dry-run) purge that affects at least one row MUST emit exactly one Nextcloud Activity event with structured metadata. Dry-run purges MUST NOT emit an Activity event. Both real and dry-run purges write a structured PSR-3 log line for cluster operators. @@ -252,24 +282,32 @@ Every successful real (non-dry-run) purge that affects at least one row MUST emi - subject parameters: `totalRows`, `byCategory`, `durationMs`, `source: 'cli'` - AND the event MUST appear in the Nextcloud Activity log visible to admins +@e2e exclude needs `occ` and a purge that deletes at least one row; no HTTP path can create an orphan (every delete cascades, locks expire only after 15 minutes). Pinned by tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testRealPurgeEmitsOneActivityEvent (source `cli`). + #### Scenario: API purge emits activity event - GIVEN an administrator calls `POST /api/admin/cleanup/purge` and deletes 5 items - WHEN the purge succeeds - THEN one activity event MUST be emitted with `source: 'api'` and the authenticated admin's UID under `affectedUser`/`author` +@e2e exclude an event is published only when the purge deletes at least one row, and no HTTP path can create an orphan to delete (every delete cascades, see dashboard-cascade-events; a lock expires only 15 minutes after its heartbeat). Pinned by tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testRealPurgeEmitsOneActivityEvent and tests/Unit/Controller/AdminCleanupControllerCoverageTest.php::testNonStringAndEmptyCategoryEntriesAreDroppedSilently (the controller passes the acting admin's UID and `source: 'api'`). Gap: neither asserts the setAffectedUser/setAuthor arguments. + #### Scenario: Dry-run purge does NOT emit activity event - GIVEN a purge with `dryRun=true` that would delete 5 items - WHEN the purge completes without touching data - THEN NO activity event MUST be emitted +@e2e exclude the absence of an event only means something when the dry run would delete rows, and no HTTP path can create an orphan. Pinned by tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testDryRunRollsBackAndDoesNotEmitEvent (`publish` never called for a 5-row dry run). + #### Scenario: Background job purge emits activity event - GIVEN the daily background job runs and auto-purges N > 0 items - WHEN the purge completes - THEN exactly one activity event MUST be emitted with `source: 'job'` +@e2e exclude needs the daily background job to run and delete rows; neither can be caused over HTTP. Pinned by tests/Unit/BackgroundJob/OrphanedDataCleanupJobScheduleTest.php::testPurgeIsARealJobRunWithoutAUser (`source='job'`) and tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testRealPurgeEmitsOneActivityEvent. + ### Requirement: REQ-CLN-010 Cache Invalidation Scan results MUST be cached in the distributed cache (`ICacheFactory::createDistributed`) under the key `launchpad.cleanup.scan` for `CACHE_TTL_SECONDS` (300s); the cache MUST be invalidated on any successful (non-dry-run) purge. Partial scans (with a non-empty category-name filter) bypass the cache entirely so they cannot pollute the full-set entry. @@ -286,6 +324,8 @@ Scan results MUST be cached in the distributed cache (`ICacheFactory::createDist - WHEN a new scan is requested at T+CACHE_TTL_SECONDS+1 - THEN the system MUST discard the cache and perform a fresh scan returning `cached: false` +@e2e exclude needs the server clock to move past CACHE_TTL_SECONDS (300s): the suite cannot set the instance clock, and a five-minute sleep in the serial shared suite is not acceptable. Expiry itself is the ICache backend's job. Gap: no PHPUnit test asserts the `ttl: 300` argument OrphanedDataCleanupService::setCachedScanResult passes. + #### Scenario: Real purge invalidates cache - GIVEN a cached scan result @@ -309,14 +349,20 @@ Adding a new cleanup category MUST require only creating one new class implement - THEN the system MUST automatically include the new category in scans, purges, the daily auto-purge default list (if Tier-A), CLI listings, and API responses - AND no changes to `OrphanedDataCleanupService`, `AdminCleanupController`, `CleanupScanCommand`, `CleanupPurgeCommand`, or `OrphanedDataCleanupJob` are required +@e2e exclude a source-structure property (which classes a developer must edit), not runtime behaviour an instance can show. Pinned by tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testScanAggregatesCountsAcrossRegistry (the orchestrator runs any category the registry returns) and tests/Unit/Service/Cleanup/CategoryRegistryServiceTest.php::testGetCategoryNamesReturnsRegisteredOrder. + #### Scenario: Category interface contract -- GIVEN the `CleanupCategoryInterface` with methods `getName()`, `getDisplayName()`, `getSafeToPurgeAutomatically()`, `isAvailable()`, `scan()`, and `purge(bool $dryRun = false)` +- GIVEN the `CleanupCategoryInterface` with methods `getName()`, `getDisplayName()`, `isSafeToPurgeAutomatically()`, `isAvailable()`, `scan()`, and `purge(bool $dryRun = false)` - WHEN a new class implements this interface - THEN the registry MUST discover it via constructor injection and the orchestrator MUST invoke it without modification to calling code +@e2e exclude a code contract between CleanupCategoryInterface, the registry and the orchestrator; an instance only ever runs the four shipped classes. Pinned by tests/Unit/Service/Cleanup/CategoryRegistryServiceTest.php::testGetCategoriesReturnsKeyedMap and the four tests/Unit/Service/Cleanup/*CategoryTest.php files. + #### Scenario: Backwards-compatible category additions - GIVEN an existing installation running cleanup regularly - WHEN a new category is added via a code update - THEN existing CLI commands, API endpoints, and the background job MUST work unchanged with the new category, picking it up automatically on the next request + +@e2e exclude needs a code update that adds a category, which an e2e run against a fixed build cannot perform. Pinned by tests/Unit/Service/OrphanedDataCleanupServiceTest.php::testScanAggregatesCountsAcrossRegistry and tests/Unit/Service/OrphanedDataCleanupServiceCoverageTest.php::testPurgeSkipsUnregisteredAndUnavailableCategories (callers iterate whatever the registry holds). diff --git a/openspec/specs/people-widget/screens.md b/openspec/specs/people-widget/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/people-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/people-widget/spec.md b/openspec/specs/people-widget/spec.md index cd0faa878..814e0eb1f 100644 --- a/openspec/specs/people-widget/spec.md +++ b/openspec/specs/people-widget/spec.md @@ -6,7 +6,7 @@ status: done ## Purpose -The `people-widget` capability registers a dashboard widget that displays a discoverable directory of Nextcloud users with customizable layout (card/grid/list), profile field visibility control, group filtering, and birthday tracking. The widget integrates with Nextcloud's Dashboard Widget API via `OCP\Dashboard\IManager`, stores configuration in the widget placement's JSON config, and provides a paginated API endpoint for user lookup. Results expose each user's profile fields as returned by `OCP\Accounts\IAccountManager`; scope-based visibility filtering is a planned follow-up (see REQ-PPL-004). +The `people-widget` capability registers a dashboard widget that displays a discoverable directory of Nextcloud users with customizable layout (card/grid/list), profile field visibility control, group filtering, and birthday tracking. The widget integrates with Nextcloud's Dashboard Widget API via `OCP\Dashboard\IManager`, stores configuration in the widget placement's JSON config, and provides a paginated API endpoint for user lookup. Results expose each user's profile fields as returned by `OCP\Accounts\IAccountManager`; a field whose Nextcloud scope is private shows to its owner only (REQ-PEX-004). ## Data Model @@ -62,9 +62,6 @@ Widget configuration is stored in the placement's `widgetContent` JSON: ## Requirements - -@e2e exclude all scenarios test PHP /api/people endpoint / IAccountManager — user-directory data not present in test fixture - ### Requirement: Widget registration via dashboard API (REQ-PPL-001) The system MUST register a widget with id `launchpad_people` via `OCP\Dashboard\IManager::registerWidget()` in `appinfo/dashboard.php`. The widget MUST have: @@ -74,6 +71,7 @@ The system MUST register a widget with id `launchpad_people` via `OCP\Dashboard\ - Widget MUST be discoverable via Nextcloud's Dashboard widget discovery mechanism #### Scenario: Widget is registered on app load +@e2e exclude feature never built: nothing in lib/ or appinfo/ calls IManager::registerWidget for `launchpad_people` (`git log --all -S launchpad_people -- lib appinfo src` finds no code; there is no appinfo/dashboard.php). The People widget is LaunchPad's own grid type `people`, registered by nc-vue's dashboardWidgetRegistry. No unit test exists. - **GIVEN** LaunchPad is installed and enabled - **WHEN** Nextcloud boots and calls `IManager::getWidgets()` - **THEN** widget `launchpad_people` MUST appear in the list @@ -83,9 +81,10 @@ The system MUST register a widget with id `launchpad_people` via `OCP\Dashboard\ - **GIVEN** a user wants to add a widget - **WHEN** they open the widget picker - **THEN** "People" (or localized variant) MUST be available -- **AND** clicking "Add" MUST create a placement with `widgetId: "launchpad_people"` +- **AND** clicking "Add" MUST create a placement with `widgetId: "people"` #### Scenario: Widget icon is valid SVG +@e2e exclude feature never built: there is no Nextcloud dashboard widget and so no `icon_url` (the LaunchPad type picker uses the MDI name `AccountMultiple`); the brand-guideline half is a matter of taste no test can judge. No unit test exists. - **GIVEN** the widget's icon_url - **WHEN** the dashboard renders - **THEN** the SVG MUST load without errors @@ -108,6 +107,8 @@ Each widget placement MUST support configuration stored in the placement's `widg The frontend MUST validate `birthdayWindowDays` is between 0 and 30 (inclusive) before saving. +**NOTE (2026-11-22, showFields semantics)**: When `showFields` is stored, the role, organisation, email and phone lines show only for keys set to `true`; a key that is left out counts as off. The avatar and each custom profile field show unless their key is explicitly `false`. With no `showFields` stored, every field shows. The form only offers `displayName` and `group` for `sortBy`; `recent-activity` is a planned follow-up and is treated as unknown until it is built. + #### Scenario: Config saved to placement - **GIVEN** user configures widget layout to "card" with a group filter for "management" - **WHEN** they save @@ -120,10 +121,10 @@ The frontend MUST validate `birthdayWindowDays` is between 0 and 30 (inclusive) - **AND** the save MUST NOT proceed #### Scenario: Unknown sortBy value rejected -- **GIVEN** user sets `sortBy: "unknown-field"` -- **WHEN** they save -- **THEN** the frontend MUST reject with error message -- **AND** fall back to `displayName` +- **GIVEN** a placement stores `sortBy: "unknown-field"` +- **WHEN** the user opens it in the edit form and tries to save +- **THEN** the form MUST show the sort control at `displayName` with a message naming the unknown key +- **AND** Save MUST stay disabled until the user picks a sort key, which then saves as the fallback `displayName` or their choice #### Scenario: showFields subset validated - **GIVEN** user configures `showFields: {"displayName": true, "email": true}` (omitting others) @@ -192,17 +193,18 @@ Response shape: The system MUST NOT return empty or null field values — all returned fields MUST have a non-empty value. The system SHOULD only return profile fields the requesting viewer is allowed to see, per Nextcloud's `IAccountManager` field-level visibility settings. Hidden fields SHOULD be omitted entirely from the response (not included with null value). -**NOTE (v1 limitation)**: The current implementation reads `IAccountManager` properties unconditionally via `$account->getProperty($property)->getValue()` without checking `$prop->getScope()`. All non-empty profile fields are returned to any authenticated viewer regardless of the user's privacy settings. Enforcing NC scope-based visibility is a planned follow-up (see Open Follow-Ups). +**NOTE (2026-09-30, widgets-people-expertise-and-fields)**: `buildAccountFields()` checks `$prop->getScope()`: a private (`v2-private`) field shows only when the viewer is its owner; the local, federated and published scopes reach every signed-in user of the instance (REQ-PEX-004). -**NOTE (caching risk)**: The non-group-filter path uses a 1-hour shared APCu cache keyed only on filter + sort parameters, not on the requesting user. If scope-based visibility is enforced in a future revision, this cache MUST be made per-viewer or disabled to prevent data leakage. +**NOTE (caching)**: The service keeps no server-side cache; the widget's own 60-second cache lives in the viewer's browser, and search results are never cached (REQ-PEX-004). #### Scenario: Viewer cannot see hidden email (future) +@e2e exclude the GIVEN cannot be produced: Nextcloud's AccountManager refuses the v2-private scope for display name and email, so no account can hold a private email. No unit test pins email omission (PeopleWidgetService takes the email from IUser::getEMailAddress without a scope check). - **GIVEN** user "alice" has set her email visibility to "private" (not visible to others) - **AND** user "bob" is viewing the people widget - **WHEN** bob fetches the user list - **THEN** alice's entry SHOULD NOT have an `email` field - **AND** the `email` key SHOULD NOT appear in the response object (not `email: null`) -- **NOTE**: This scenario describes the target state; scope-based filtering is not enforced in v1. +- **NOTE**: Enforced since widgets-people-expertise-and-fields for the private scope (REQ-PEX-004). #### Scenario: Viewer can see visible email (future) - **GIVEN** user "alice" has set her email visibility to "public" or "organization" @@ -237,6 +239,7 @@ Days-to-birthday display logic MUST be computed client-side from the returned `b - **THEN** `birthdate` MUST be `"1990-06-10"` (ISO 8601 normalized) #### Scenario: Birthday filter within_next_days +@e2e exclude feature never built: no `within_next_days` predicate exists in lib/ or src/ (`git log --all -S within_next_days -- lib src` finds none; PeopleWidgetService ignores every non-group filter). No unit test exists; tests/Unit/Service/PeopleWidgetBirthdateTest.php pins only the days-to-birthday count no filter uses. - **GIVEN** placement config requests birthday filter `within_next_days: 7` - **AND** today is 2026-05-15 - **WHEN** system fetches user list @@ -244,6 +247,7 @@ Days-to-birthday display logic MUST be computed client-side from the returned `b - **AND** each included user's `birthdate` MUST be the ISO date string of their birthday #### Scenario: Birthday today is included +@e2e exclude feature never built: the `within_next_days` filter this applies does not exist in lib/ or src/ (see the scenario above). No unit test of the filter exists; PeopleWidgetBirthdateTest.php::testBirthdayTodayIsZeroDays pins only the count. - **GIVEN** today is 2026-06-10 - **AND** user "charlie" has birthdate 1990-06-10 - **WHEN** system applies `within_next_days: 7` filter @@ -453,7 +457,7 @@ The widget MUST provide a search input that filters displayed users by substring ### Requirement: Client-side caching and refresh (REQ-PPL-012) -The widget MUST cache results in memory for 60 seconds per placement. A force-refresh button MUST clear the cache and immediately re-fetch user list from the backend. +The widget MUST cache results in memory for 60 seconds per placement configuration (two placements with the same filters, sort and switches share their pages), and the cache MUST survive the widget being unmounted and mounted again in the same page. A force-refresh button MUST clear the cache and immediately re-fetch user list from the backend. #### Scenario: Results cached for 60 seconds - **GIVEN** user fetches the people list (first load) @@ -475,11 +479,142 @@ The widget MUST cache results in memory for 60 seconds per placement. A force-re - **AND** results MUST update to latest state #### Scenario: Tab/browser focus refreshes cache +@e2e exclude optional behaviour (MAY / SHOULD) that was never built: CnPeopleWidget does not listen for focus or visibilitychange. No unit test exists. - **GIVEN** user switches away from browser tab and back - **WHEN** user returns to the tab - **THEN** cache MAY be invalidated (optional) - **AND** widget SHOULD refetch on re-focus (recommended UX) +### Requirement: Administrators define custom profile fields (REQ-PEX-001) + +An administrator MUST be able to define up to 10 custom profile fields, each with a label, a type (text or tags), a source (filled by the person, or read from an LDAP attribute), whether it is searchable, whether it shows in the people widget, and who may see it (everyone, or members of the person's groups). + +#### Scenario: Office location from LDAP +@e2e exclude needs an LDAP directory server and the user_ldap app, which the CI fixture does not provide; pinned by tests/Unit/Service/ProfileFieldServiceTest.php::testLdapFieldsSyncForLdapAccountsOnly and ::testPieterAddsHisSubjectsAndLdapFieldsStayReadOnly + +- **GIVEN** Noor is an administrator and accounts come from LDAP +- **WHEN** she adds the field "Kantoorlocatie" of type text, source LDAP attribute `physicalDeliveryOfficeName`, shown in the widget +- **THEN** after Pieter next signs in, his people card shows "Kantoorlocatie: Stadhuis, 3e verdieping" +- **AND** Pieter sees the field read-only on his LaunchPad personal settings + +### Requirement: People list their own expertise (REQ-PEX-002) + +A person MUST be able to fill the fields sourced from themselves on their LaunchPad personal settings, including tags for expertise. + +#### Scenario: Pieter adds his subjects + +- **GIVEN** the field "Expertise" of type tags, filled by the person, searchable +- **WHEN** Pieter adds the tags "subsidies" and "Omgevingswet" on his personal settings and saves +- **THEN** his people card shows the two tags + +### Requirement: Search finds people across the directory by profile and expertise (REQ-PEX-003) + +With a query of 2 or more characters, the people widget MUST ask the server, which MUST match display name, email, role, headline, biography and every searchable custom field across the whole directory and return the matches a page at a time. Shorter queries MUST keep the current-page filter of REQ-PPL-011. + +#### Scenario: Sanne finds the subsidies expert + +- **GIVEN** Pieter has the tag "subsidies" and is not on the first page of the people widget +- **WHEN** Sanne types "subsidie" in the widget's search box +- **THEN** Pieter is in the results with the tag highlighted + +#### Scenario: Clicking a tag searches for it + +- **GIVEN** Pieter's card shows the tag "Omgevingswet" +- **WHEN** Sanne clicks the tag +- **THEN** the widget shows everyone tagged "Omgevingswet" + +### Requirement: Search and display respect profile visibility (REQ-PEX-004) + +A standard profile field MUST be matched and shown only when the person's Nextcloud visibility setting lets the viewer see it. A custom field MUST be matched and shown only to the audience its definition allows. Search results MUST NOT be served from a cache shared between viewers. + +#### Scenario: Private biography is not searchable + +- **GIVEN** Karin's biography mentions "subsidies" and its visibility is private +- **WHEN** Sanne searches "subsidies" +- **THEN** Karin is not in the results on the strength of her biography +- **AND** her card does not show the biography + +#### Scenario: Group-only field + +- **GIVEN** the field "Kostenplaats" is visible to members of the person's groups only, and Sanne shares no group with Pieter +- **WHEN** Sanne views Pieter's card or searches his cost centre +- **THEN** the field is not shown and does not match + +### Requirement: Candidate resolution is bounded by the requested page (REQ-PPL-013) + +`PeopleWidgetService::listUsers()` MUST NOT materialize the full Nextcloud +user directory for a request that has no `group` filter and uses the default +`displayName` sort. The number of `IUser` objects instantiated from +`IUserManager` MUST scale with the requested `limit`/`offset` window (capped +at `PeopleWidgetService::MAX_LIMIT`), not with the total number of accounts on +the instance. Only the admin-selected `group` sort without a group filter +reads the whole directory, because ordering by group membership needs it. + +#### Scenario: Unfiltered People widget on a large instance fetches a bounded set +@e2e exclude which IUserManager call runs, and with what bound, is not visible in a browser or an API response; pinned by tests/Unit/Service/PeopleWidgetServiceTest.php::testDisplayNameSortUsesBoundedSearchNotFullScan and tests/Unit/Service/PeopleWidgetVisibilityGoldenTest.php::testDirectoryPageStreamsChunksUntilFullOrExhausted + +- **GIVEN** a Nextcloud instance with 5,000 user accounts +- **AND** a People widget configured with no `group` filter and + `limit=10`, `offset=0` +- **WHEN** `GET /api/people?limit=10&offset=0` is called +- **THEN** `IUserManager::searchDisplayName()` MUST be invoked with a + bounded `$limit`/`$offset`, not an unbounded full-table search +- **AND** the response MUST still contain the correct `users`, `total`, + and `hasMore` fields + +#### Scenario: Pagination still returns correct total and hasMore + +- **GIVEN** the same 5,000-user instance and no `group` filter +- **WHEN** the caller requests successive pages (`offset=0,10,20,...`) +- **THEN** `total` MUST reflect the true count of matching (enabled, per + `excludeDisabled`) users +- **AND** `hasMore` MUST correctly indicate whether further pages exist + +#### Scenario: Group-filtered resolution is unaffected + +- **GIVEN** a People widget configured with a `group` filter +- **WHEN** candidates are resolved +- **THEN** behaviour MUST be unchanged from before this change — + `IGroupManager::get($gid)->getUsers()` per group value, deduplicated by + UID + +### Requirement: A profile field can hold a start date (REQ-PEX-005) + +A custom profile field (REQ-PEX-001) MAY have the type date. An administrator MAY mark one date field as the start +date ("in dienst sinds"). The start date SHALL follow the field's source and visibility like any custom field, and SHALL +be read through the same visibility checks (REQ-PEX-004). Marking another field as the start date SHALL unmark the +previous one. + +#### Scenario: Start date from LDAP +@e2e exclude needs an LDAP directory server and the user_ldap app, which the CI fixture does not provide; pinned by tests/Unit/Service/ProfileFieldServiceAccessGoldenTest.php::testAnLdapStartDateIsReadAsACalendarDate (generalized time and ISO dates read as 2026-10-12, an unreadable value read as none) and ::testOneDateFieldIsTheStartDate + +- **GIVEN** the administrator adds a date field "In dienst sinds", source LDAP attribute `employeeStartDate`, marked as the start date +- **WHEN** Yasmina's LDAP entry holds 12 October 2026 +- **THEN** her start date is 12 October 2026 + +### Requirement: The people widget can list new colleagues (REQ-PPL-014) + +The people widget SHALL offer `selectionMode: 'new'` ("New colleagues", nl "Nieuwe collega's"). It SHALL list the +people whose start date lies between `newSinceDays` days ago (default 30, range 1 to 90) and `newUntilDays` days ahead +(default 14, range 0 to 30), newest start first, with photo, name, role and team, within the widget's other filters +(groups, disabled accounts). A person who has not started yet SHALL be marked with the day they start ("begint +maandag"). Only people whose start date the viewer may see SHALL be listed. When no field is marked as the start date, +the form SHALL not offer the mode and a placement that uses it SHALL say that the administrator has not set a start +date field. + +#### Scenario: Three new colleagues on the intranet + +- **GIVEN** Thomas started on 28 September, Lotte on 1 October and Yasmina starts on 12 October +- **AND** today is 5 October 2026 and the widget uses `selectionMode: 'new'` with the defaults +- **WHEN** Pieter opens Intranet Zuiddrecht +- **THEN** "Nieuwe collega's" lists Yasmina with "begint maandag", then Lotte, then Thomas, each with role and team + +#### Scenario: No start date field + +- **GIVEN** no profile field is marked as the start date +- **WHEN** an author opens the people widget form +- **THEN** the selection offers no "New colleagues" + ## Non-Functional Requirements - **Performance**: `GET /api/people` MUST return within 1 second for orgs with <1000 users. Pagination with limit=50 MUST be efficient (offset-based, max 100 per page). @@ -487,12 +622,10 @@ The widget MUST cache results in memory for 60 seconds per placement. A force-re - **Data integrity**: User list MUST reflect real-time group membership (no stale cache on backend for group-filtered paths). - **Accessibility**: Widget MUST support keyboard navigation (Tab through users, Enter to open profile). All fields MUST have accessible labels. Avatar images MUST have alt text. - **Localization**: All user-facing strings MUST support English and Dutch (nl/en). Birthday display formatting MUST work with any user's locale. -- **Privacy**: Scope-based field filtering is a planned follow-up. The shared backend APCu cache (keyed on filter + sort only) MUST be made per-viewer before scope-based visibility is enforced to prevent data leakage. +- **Privacy**: A private standard field shows and matches for its owner only; custom fields follow their definition's audience (REQ-PEX-004). ## Open Follow-Ups -- **Privacy — scope enforcement**: Implement `IAccountManager` scope-based visibility (`$prop->getScope()` check against viewer) before the shared filter cache is safe to retain. -- **Privacy — per-viewer cache**: The 1-hour shared APCu cache ignores the requesting user. When scope-based visibility is enforced, the cache key MUST include the viewer's uid (or the cache must be disabled). - **Feb-29 birthday guard**: The `within_next_days` filter operator constructs dates with `new \DateTime($currentYear . '-' . $date->format('m-d'))` — this throws on Feb 29 in non-leap years. A guard (substitute Feb 28 in non-leap years) must be added. - **Click-through to `/u/{uid}`**: Not present in the reference implementation; must be added to the frontend card/list components. - **Birthday badge overlay**: "🎂 in N days" badge rendering is not in the reference source; to be added if desired. diff --git a/openspec/specs/permissions/screens.md b/openspec/specs/permissions/screens.md new file mode 100644 index 000000000..16003f1b6 --- /dev/null +++ b/openspec/specs/permissions/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet +- LpDelen https://identity.conduction.nl/screens/board?id=launchpad/LpDelen diff --git a/openspec/specs/permissions/spec.md b/openspec/specs/permissions/spec.md index 02d26919a..74f843b5c 100644 --- a/openspec/specs/permissions/spec.md +++ b/openspec/specs/permissions/spec.md @@ -18,9 +18,6 @@ Permission levels control what users can do with their dashboards. When an admin ## Requirements - -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: View-Only Permission Level (REQ-PERM-001) Dashboards with `permissionLevel: "view_only"` MUST restrict users to viewing only, with no widget or layout editing capabilities. @@ -164,7 +161,7 @@ Admin templates MUST be able to mark specific widget placements as compulsory, a - WHEN the dashboard is rendered in edit mode - THEN compulsory widgets MUST display a visual indicator (e.g., lock icon, "Required" badge) - AND the indicator MUST be visible only in edit mode (not in view mode) -- NOTE: Not currently implemented. `WidgetWrapper.vue` has `canRemove` computed property but no visual badge. +- NOTE: `WidgetWrapper.vue` draws a lock (`data-testid="widget-compulsory-indicator"`, named "Required: this widget cannot be removed") beside the widget menu while `editMode` is on and `isCompulsory` is 1. #### Scenario: Non-compulsory widgets on template-derived dashboards - GIVEN an admin template has 5 widgets: 3 compulsory and 2 non-compulsory diff --git a/openspec/specs/personal-settings/spec.md b/openspec/specs/personal-settings/spec.md new file mode 100644 index 000000000..13a3f3c50 --- /dev/null +++ b/openspec/specs/personal-settings/spec.md @@ -0,0 +1,83 @@ +--- +capability: personal-settings +status: done +--- + +# Personal settings Specification + +## Purpose + +Launchpad's own settings dialog: everything a person sets for themselves, in one place, without a page under +`/settings/user`. + +## Requirements + +### Requirement: One dialog holds every personal setting (REQ-PSET-001) + +"Persoonlijke instellingen" in the Instellingen group of Meer (runtime-shell REQ-SHELL-013) SHALL open launchpad's +settings dialog over the current page. The dialog SHALL list its sections in a side list, in the order of board +LpPersoonlijk: Samenvatting per e-mail, Gebruikscijfers, Verborgen widgets, Mijn profiel, Inloggegevens; sections the +library adds (notifications, walkthrough, integrations) SHALL follow. A section whose feature is off SHALL be left +out: Gebruikscijfers when an administrator turned analytics off, Mijn profiel when no profile field is filled by the +person. Changes SHALL be saved at once ("Wijzigingen worden meteen bewaard"). Launchpad SHALL NOT register a section +in Nextcloud's personal settings. + +#### Scenario: Pieter opens his settings + +- **GIVEN** Pieter on the dashboard Intranet Zuiddrecht +- **WHEN** he opens Meer, unfolds Instellingen and chooses Persoonlijke instellingen +- **THEN** the dialog opens over the dashboard with the sections Samenvatting per e-mail, Gebruikscijfers, Verborgen widgets, Mijn profiel and Inloggegevens, in that order + +#### Scenario: Analytics off for everyone + +- **GIVEN** the administrator turned analytics off +- **WHEN** Pieter opens his settings +- **THEN** the dialog has no Gebruikscijfers section + +### Requirement: A person chooses a summary email (REQ-PSET-002) + +The section Samenvatting per e-mail SHALL explain "A mail with new announcements and what changed on your +dashboards" and offer "How often?": Off, Daily ("At 07:30, only when something changed") or Weekly ("On Monday at +07:30"). The choice SHALL be stored per person and SHALL be Off until the person changes it. + +A background job SHALL send the summary at 07:30 in the person's time zone, daily or on Monday, to the person's email +address. It SHALL list the announcements published for the person since the last summary, and per dashboard the +person can open, what changed since then (the "What changed" notes of dashboard-versioning). A daily summary with +nothing in it SHALL NOT be sent. A person without an email address SHALL get no summary and the section SHALL say so. + +#### Scenario: Pieter asks for a daily summary + +- **GIVEN** Pieter set Samenvatting per e-mail to Daily +- **AND** yesterday an announcement was published for his group and the dashboard Team Vergunningen gained a widget +- **WHEN** it is 07:30 in his time zone +- **THEN** he gets one email naming the announcement and "Team Vergunningen: Widget Teamagenda added" + +#### Scenario: Nothing changed + +- **GIVEN** Pieter set Daily and nothing was published or changed since his last summary +- **WHEN** it is 07:30 +- **THEN** no email is sent + +#### Scenario: The default + +- **GIVEN** Sanne never opened her settings +- **THEN** she gets no summary email + +### Requirement: A person sees every widget they hid, on every dashboard (REQ-PSET-003) + +The section Verborgen widgets SHALL say how many widgets the person hid on shared dashboards ("You have hidden 2 +widgets on shared dashboards") and list each one with its title, its dashboard and "Show again". "Show all again" +SHALL show every hidden widget again. Both SHALL act on the person's own layer (dashboards-and-who-may-see-them REQ-DWMS-001) and SHALL +NOT change the shared dashboard for anyone else. With nothing hidden the section SHALL say so and offer no button. + +#### Scenario: Pieter shows Verjaardagen again + +- **GIVEN** Pieter hid Verjaardagen and Kantinemenu on Intranet Zuiddrecht +- **WHEN** he opens Verborgen widgets and chooses Show again next to Verjaardagen +- **THEN** Verjaardagen is back on his view of Intranet Zuiddrecht, and the section lists only Kantinemenu + +#### Scenario: Show all again + +- **GIVEN** Pieter hid two widgets on two dashboards +- **WHEN** he chooses Show all again +- **THEN** both widgets are back on his views, and the section says nothing is hidden diff --git a/openspec/specs/platform-baseline/screens.md b/openspec/specs/platform-baseline/screens.md new file mode 100644 index 000000000..d7d001126 --- /dev/null +++ b/openspec/specs/platform-baseline/screens.md @@ -0,0 +1,4 @@ +# Screens + +- launchpad/LpWerkplek: the start page in the organisation's theme, language and light or dark mode, reached after the Nextcloud sign-in https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- launchpad/LpMobiel: the start page installed as a phone app https://identity.conduction.nl/screens/board?id=launchpad/LpMobiel diff --git a/openspec/specs/platform-baseline/spec.md b/openspec/specs/platform-baseline/spec.md new file mode 100644 index 000000000..7bf07eb0e --- /dev/null +++ b/openspec/specs/platform-baseline/spec.md @@ -0,0 +1,168 @@ +# platform-baseline Specification + +## Purpose +What LaunchPad takes from the Nextcloud it runs on instead of building itself: sign-in, hosting, the organisation's theme, the language, group membership, installing as a phone app and light or dark mode. Each requirement names what LaunchPad must do so that the platform behaviour reaches every LaunchPad page. + +## Requirements + +### Requirement: LaunchPad has no login of its own (REQ-PLB-001) + +LaunchPad MUST run in the Nextcloud session and MUST NOT offer a login form, password store or token flow of its own. Every LaunchPad page and API route MUST require a signed-in Nextcloud user, except the routes that exist to serve visitors without an account: a public dashboard share (`PageController::publicShare`, `PublicShareController`), a kiosk link (`KioskController::render`) and the health check (`HealthController::index`). Single sign-on therefore comes from whatever Nextcloud is set up with (user_oidc, user_saml or LDAP), without a LaunchPad setting. + +#### Scenario: Signed in once, no second prompt + +- **GIVEN** Pieter signed in to Nextcloud through the organisation's identity provider +- **WHEN** he opens `/apps/launchpad/` +- **THEN** his start page loads without a LaunchPad sign-in step + +#### Scenario: Signed-out visitor goes to the Nextcloud login + +- **GIVEN** a browser without a Nextcloud session +- **WHEN** it opens `/apps/launchpad/` +- **THEN** Nextcloud answers with its own login page (and from there the identity provider) +- **AND** no LaunchPad page or dashboard data is sent before sign-in + +#### Scenario: Only the visitor routes are public + +- **GIVEN** the LaunchPad controllers +- **WHEN** their routes are listed with their auth attributes +- **THEN** only the public share, kiosk and health routes carry `#[PublicPage]` + +### Requirement: LaunchPad runs on the organisation's own servers (REQ-PLB-002) + +LaunchPad MUST install as an ordinary Nextcloud app on the organisation's own instance and MUST keep its dashboards, placements, rules and settings in that instance's database and app config. It MUST NOT depend on a hosted Conduction service. A server-side outbound request MUST go only to an address an administrator configured (weather provider, feeds, health pings) or an author placed on a dashboard (live tile, embed, news feed). + +#### Scenario: Installed from the app store on an own instance + +- **GIVEN** a Nextcloud instance run by the organisation +- **WHEN** an administrator enables LaunchPad +- **THEN** every dashboard is stored in that instance's database +- **AND** LaunchPad works with no account at, or connection to, any outside service + +#### Scenario: No outbound call without a configured address + +- **GIVEN** a fresh install with no weather provider, feed, live tile or embed configured +- **WHEN** users open their dashboards +- **THEN** the LaunchPad server makes no outbound HTTP request + +### Requirement: Every page takes on the organisation's theme (REQ-PLB-003) + +LaunchPad styles MUST take colours, fonts and corner radii from Nextcloud's theme variables (`--color-*`, `--border-radius*`, `--font-face`), so a Nextcloud theme or a thematiq NL Design System theme restyles every LaunchPad page without a LaunchPad setting. A hard-coded colour MAY only appear as a user-chosen value (a tile or widget colour) or as a fallback behind a theme variable. + +#### Scenario: A government theme restyles the start page + +- **GIVEN** thematiq applies the organisation's NL Design System theme +- **WHEN** Pieter opens his start page +- **THEN** the page chrome, buttons and links show the theme's colours and font + +#### Scenario: Per-dashboard looks are separate + +- **GIVEN** the organisation theme and a dashboard with its own look (change `platform-dashboard-theme-and-css`) +- **WHEN** the dashboard renders +- **THEN** the organisation theme still sets every value the dashboard look leaves open + +### Requirement: Every string is translatable and follows the user's language (REQ-PLB-004) + +Every user-facing string in LaunchPad MUST go through the Nextcloud l10n domain `launchpad` (`t('launchpad', ...)` in the frontend, `IL10N` for the app id in PHP). LaunchPad MUST ship Dutch and English translations, and pages MUST show the language chosen in the user's Nextcloud personal settings. + +#### Scenario: Dutch user + +- **GIVEN** Pieter set his Nextcloud language to Nederlands +- **WHEN** he opens LaunchPad +- **THEN** the menus, buttons and empty states are in Dutch + +#### Scenario: No string in another app's domain + +- **GIVEN** the frontend sources +- **WHEN** every `t(` and `n(` call is listed +- **THEN** each one names the domain `launchpad` + +### Requirement: Group dashboards follow the groups set at sign-in (REQ-PLB-005) + +LaunchPad MUST read a user's groups from Nextcloud (`IGroupManager`) at the moment it resolves a dashboard or a visibility rule, and MUST NOT keep its own copy of group membership. Groups an identity provider sends at sign-in (through user_oidc or user_saml group provisioning) therefore decide the group dashboards and group rules from that request on. Routing to a group dashboard follows the resolver in `admin-templates` (REQ-TMPL-013). + +#### Scenario: New group at sign-in + +- **GIVEN** the identity provider adds Pieter to group "KCC" and Nextcloud provisions it at sign-in +- **AND** a group dashboard is shared with "KCC" +- **WHEN** Pieter opens LaunchPad after that sign-in +- **THEN** the "KCC" dashboard is available to him without an administrator action in LaunchPad + +#### Scenario: Group removed + +- **GIVEN** the identity provider no longer sends "KCC" for Pieter +- **WHEN** he signs in again and opens LaunchPad +- **THEN** the "KCC" dashboard and widgets with a "KCC" visibility rule are no longer shown to him + +### Requirement: Pages install on a phone through Nextcloud's web app manifest (REQ-PLB-006) + +LaunchPad pages MUST be installable from the browser's "add to home screen" option through the web app manifest Nextcloud serves, and LaunchPad MUST NOT ship a manifest or service worker of its own. The installed app opens where Nextcloud's default app points; with LaunchPad set as default app, that is the LaunchPad start page. The page layout on a phone follows board LpMobiel. + +#### Scenario: Add to home screen + +- **GIVEN** LaunchPad is the Nextcloud default app +- **WHEN** Pieter chooses "Add to home screen" on a LaunchPad page in his phone's browser +- **THEN** a home screen icon appears +- **AND** opening it shows his LaunchPad start page in a window without the browser bar + +### Requirement: Pages follow light or dark mode (REQ-PLB-007) + +LaunchPad pages MUST use Nextcloud's theme variables for every surface, text and border colour, so they follow the user's Nextcloud theme setting, including "follow the system" light or dark, without a LaunchPad setting. + +#### Scenario: Device in dark mode + +- **GIVEN** Pieter's Nextcloud theme follows the system and his device is in dark mode +- **WHEN** he opens his start page +- **THEN** the page, widget frames and menus show the dark theme +- **AND** text keeps WCAG AA contrast against its background + +### Requirement: Outbound requests use the server's proxy setting (REQ-PLB-008) + +Every server-side request LaunchPad sends to another site, for news feeds, calendar feeds, live tiles, weather, health pings and embed checks, MUST go through Nextcloud's HTTP client (`IClientService`), so the proxy an administrator set in `config.php` (`proxy`, `proxyuserpwd`, `noproxy`) applies without a LaunchPad setting. LaunchPad MUST NOT open its own connections with `curl_*`, `file_get_contents` on a URL, or a client it builds itself. + +#### Scenario: A live tile behind the organisation's proxy + +- **GIVEN** the Nextcloud server has `proxy` set to `http://proxy.gemeente.local:3128` +- **AND** Ella placed a live tile that reads `https://data.gemeente.nl/api/meldingen` +- **WHEN** Pieter opens the dashboard and the tile fetches its value +- **THEN** the request leaves the server through `proxy.gemeente.local:3128` + +#### Scenario: A host on the no-proxy list + +- **GIVEN** `noproxy` lists `intranet.gemeente.local` +- **WHEN** a news widget reads a feed from `https://intranet.gemeente.local/nieuws.rss` +- **THEN** the request goes to the intranet directly, not through the proxy + +#### Scenario: No connection of its own + +- **GIVEN** the LaunchPad `lib/` tree +- **WHEN** it is searched for `curl_`, `file_get_contents(` on a URL and `new Client(` +- **THEN** there are no matches + +### Requirement: A phone offers to put LaunchPad on the home screen (REQ-PLB-009) + +On a screen narrower than 768 px, in a browser tab (not already opened as an installed app), the workspace SHALL show a +banner above the first widget: "Put LaunchPad on your home screen" with "Then your workplace opens with one tap, like +an app", and the buttons "Not now" and "Install" (nl "Zet Launchpad op uw beginscherm", "Niet nu", "Installeren"). +Where the browser offers an install prompt, Install SHALL open it; where it does not (Safari on iOS), Install SHALL +show the steps for the browser's Share, Add to Home Screen. "Not now" SHALL hide the banner on that device for 30 days. +The banner SHALL NOT show once the page runs as an installed app, on a wider screen, in the kiosk view or on a public +page. It SHALL be reachable by keyboard and screen reader like any notice. + +#### Scenario: Pieter installs from the banner + +- **GIVEN** Pieter opens his workplace in Chrome on a phone, not installed +- **WHEN** he chooses Install +- **THEN** the browser's install prompt opens +- **AND** after installing, opening LaunchPad from the home screen shows no banner + +#### Scenario: Not now + +- **GIVEN** the banner shows on Pieter's phone +- **WHEN** he chooses Not now +- **THEN** the banner does not show on that phone for 30 days + +#### Scenario: A desktop screen + +- **GIVEN** Pieter opens his workplace on a 1440 px screen +- **THEN** no install banner shows diff --git a/openspec/specs/prometheus-metrics/screens.md b/openspec/specs/prometheus-metrics/screens.md new file mode 100644 index 000000000..1a9099128 --- /dev/null +++ b/openspec/specs/prometheus-metrics/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpBeheerOnderhoud https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerOnderhoud diff --git a/openspec/specs/prometheus-metrics/spec.md b/openspec/specs/prometheus-metrics/spec.md index 5d6088605..5f82b2d26 100644 --- a/openspec/specs/prometheus-metrics/spec.md +++ b/openspec/specs/prometheus-metrics/spec.md @@ -12,14 +12,14 @@ Expose application metrics in Prometheus text exposition format at `GET /api/met Metrics are collected at request time from database queries and system information. No persistent metrics storage is used -- all values are computed on-demand. -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Metrics Architecture - **MetricsController**: Handles HTTP request, formats output as Prometheus text exposition - **MetricsCollector**: Orchestrates metric collection, delegates to MetricsQueryService - **MetricsQueryService**: Executes database queries for entity counts - **HealthController**: Handles health check requests, performs database connectivity test + ## Requirements + ### Requirement: Metrics Endpoint (REQ-PROM-001) The system MUST expose a Prometheus-compatible metrics endpoint accessible to @@ -78,6 +78,7 @@ The system MUST expose an info metric with version labels. - AND Nextcloud version from `IConfig::getSystemValueString('version', '0.0.0')` #### Scenario: Info metric with missing version +@e2e exclude needs launchpad's installed version unset on the shared instance, which no test may do; the engine's fallback is pinned by OpenRegister tests/Unit/AppHost/Observability/ManifestLoaderStoreTest.php::testABlankOrUnreadableVersionIsUnknown, which shows the default is "unknown", not the "0.0.0" this scenario names - GIVEN the app version is not set in config - WHEN the info metric is collected - THEN the version MUST default to "0.0.0" @@ -118,6 +119,7 @@ The system MUST expose dashboard count metrics grouped by type. ``` #### Scenario: Dashboard counts with no dashboards +@e2e exclude needs an empty launchpad_dashboards table, and a shared instance always holds other specs' dashboards and shipped templates; OpenRegister tests/Unit/AppHost/Observability/Source/TableMetricSourceBehaviourTest.php::testGroupedQueryWithNoRowsYieldsAnEmptyFamily pins what the engine does instead: an empty family with no `personal`/`template` 0 samples - GIVEN no dashboards exist in the database - WHEN the metrics endpoint is called - THEN the response MUST include both types with count 0: @@ -128,6 +130,7 @@ The system MUST expose dashboard count metrics grouped by type. - NOTE: The fallback labels use "personal" and "template" when no data exists, while actual data uses the DB type values ("user", "admin_template"). #### Scenario: Dashboard count query failure +@e2e exclude needs one database query to fail on a live instance; OpenRegister tests/Unit/AppHost/Observability/Source/TableMetricSourceBehaviourTest.php::testAQueryFailureIsLoggedAndYieldsNoSamples pins the warning and that the response survives, and shows the family gets no samples rather than the `personal`/`template` 0 fallback this scenario names - GIVEN the database query for dashboards fails - WHEN the metrics endpoint is called - THEN the system MUST log a warning @@ -153,6 +156,7 @@ The system MUST expose the total number of widget placements. ``` #### Scenario: Widget count query failure +@e2e exclude needs one database query to fail on a live instance; OpenRegister tests/Unit/AppHost/Observability/Source/TableMetricSourceBehaviourTest.php::testAQueryFailureIsLoggedAndYieldsNoSamples pins the warning, and shows the family gets no sample rather than the 0 this scenario names - GIVEN the database query for widget placements fails - WHEN the metrics endpoint is called - THEN the system MUST return 0 for the widget count @@ -163,6 +167,7 @@ The system MUST expose the total number of widget placements. The system MUST expose the total number of tile definitions. #### Scenario: Tile count +@e2e exclude nothing can seed launchpad_tiles: TileApiController::create answers 410 Gone and TileService only reads, so a known tile count cannot be arranged; launcher tiles are widget placements and move launchpad_widgets_total instead. The HELP/TYPE lines are asserted by metric-names-types-and-labels-are-preserved; no test pins the tiles_total value - GIVEN 25 tile definitions exist - WHEN the metrics endpoint is called - THEN the response MUST include: @@ -173,6 +178,7 @@ The system MUST expose the total number of tile definitions. ``` #### Scenario: Tile count query failure +@e2e exclude needs one database query to fail on a live instance; OpenRegister tests/Unit/AppHost/Observability/Source/TableMetricSourceBehaviourTest.php::testAQueryFailureIsLoggedAndYieldsNoSamples pins the warning, and shows the family gets no sample rather than the 0 this scenario names - GIVEN the database query for tiles fails - WHEN the metrics endpoint is called - THEN the system MUST return 0 for the tile count @@ -199,6 +205,7 @@ a lazy factory in `Application::register()`. - AND MUST NOT redirect to the login page #### Scenario: Database failure +@e2e exclude needs the database unreachable under a running instance; no unit test feeds the health engine a failing database probe (tests/Unit/Controller/HealthControllerTest.php::testResultIsReportedWithItsOwnStatusCode only passes an executor result through), and OpenRegister's HealthCheckExecutor::formatCheckResult renders a failed check as `failed: <message>`, not the `error` this scenario names - GIVEN the database is not accessible - WHEN GET /api/health is called - THEN the system MUST report `checks.database: "error"` and a non-ok overall status @@ -212,6 +219,7 @@ are exposed; the engine owns the exposition format and the auth posture so the contract cannot drift per app (ADR-006 / ADR-040). #### Scenario: Declarative metrics drive the output +@e2e exclude a single failing metric source cannot be arranged on a live instance; the per-source isolation is pinned by OpenRegister tests/Unit/AppHost/Observability/Source/TableMetricSourceBehaviourTest.php::testAQueryFailureIsLoggedAndYieldsNoSamples; no test asserts the COUNT aggregation itself (that test file stubs func()->count without expecting it). That the counts are live is shown e2e by dashboard-counts-by-type and widget-placement-count - GIVEN the `observability.metrics` block declares `tableCount` descriptors over the allowlisted `launchpad_*` own-tables - WHEN the metrics endpoint is called @@ -219,6 +227,7 @@ contract cannot drift per app (ADR-006 / ADR-040). through the engine, and a single failed source MUST NOT fail the whole response #### Scenario: Engine degrades safely without OpenRegister +@e2e exclude needs OpenRegister disabled, which the shared instance cannot do; pinned by tests/Unit/Controller/MetricsControllerTest.php::testMissingEngineAnswers503 and tests/Unit/Controller/HealthControllerTest.php::testMissingEngineAnswers503 - GIVEN OpenRegister is disabled or absent - WHEN Nextcloud boots - THEN LaunchPad MUST still boot (the engine wiring is lazy) @@ -230,6 +239,7 @@ contract cannot drift per app (ADR-006 / ADR-040). The metrics endpoint MUST respond quickly to avoid blocking Prometheus scrape intervals. #### Scenario: Metrics response under load +@e2e exclude needs 65,000 seeded rows, which the shared instance cannot hold for one spec; no performance test exists, and no test asserts the COUNT aggregation (OpenRegister's TableMetricSource::countAll issues COUNT(*), but its unit test stubs func()->count without expecting it) - GIVEN a large installation with 10,000 dashboards, 50,000 widget placements, and 5,000 tiles - WHEN the metrics endpoint is called - THEN the response MUST return within 2 seconds @@ -241,6 +251,22 @@ The metrics endpoint MUST respond quickly to avoid blocking Prometheus scrape in - THEN both requests MUST complete successfully - AND no locking or caching issues MUST occur +### Requirement: The admin page shows the app's health (REQ-PROM-011) + +The Operations tab of the LaunchPad admin page MUST show a Health panel that reads the health check endpoint (REQ-PROM-007). The panel MUST show "Checking…" while it waits, then "Healthy" or "Degraded" with the result in words, not only a colour. + +#### Scenario: A healthy app + +- **GIVEN** Noor is a Nextcloud administrator and the health check answers `status: "ok"` +- **WHEN** she opens the Operations tab of the LaunchPad admin page +- **THEN** the Health panel says "Healthy" + +#### Scenario: A degraded app + +- **GIVEN** the health check reports that the database cannot be reached +- **WHEN** Noor opens the Operations tab +- **THEN** the Health panel says "Degraded" + ## Non-Functional Requirements - **Performance**: GET /api/metrics MUST return within 2 seconds for installations with up to 100,000 rows across all tables. COUNT queries MUST be used rather than loading entities. diff --git a/openspec/specs/quicklinks-widget/screens.md b/openspec/specs/quicklinks-widget/screens.md new file mode 100644 index 000000000..1ba14729f --- /dev/null +++ b/openspec/specs/quicklinks-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek diff --git a/openspec/specs/quicklinks-widget/spec.md b/openspec/specs/quicklinks-widget/spec.md index b74769604..f7f00c3fc 100644 --- a/openspec/specs/quicklinks-widget/spec.md +++ b/openspec/specs/quicklinks-widget/spec.md @@ -19,7 +19,6 @@ The `content` object carries the eight fields specified in REQ-QLNK-002. Default ### Requirement: REQ-QLNK-001 Registration and widget id The system MUST register a new dashboard widget with id `launchpad_quicklinks` via `OCP\Dashboard\IManager::registerWidget()`. The widget MUST appear in the widget picker under a translatable name `t('Quicklinks')` and MUST have a default grid size of `gridWidth = 4` and `gridHeight = 2`. -@e2e exclude widget registration tested via widget-in-picker scenario #### Scenario: Widget registered and appears in picker @@ -38,7 +37,6 @@ The system MUST register a new dashboard widget with id `launchpad_quicklinks` v ### Requirement: REQ-QLNK-002 Per-placement configuration shape The `widgetContent` JSON blob for a quicklinks widget MUST contain all of the following fields: -@e2e exclude per-placement configuration shape tests JSON schema — Vitest/Newman scope - `links: Array<{label: string, url: string, icon: string, color?: string, openInNewTab?: boolean}>` — array of link objects (required; empty array is valid). - `iconSize: 'small'|'medium'|'large'|'xlarge'` (default `medium`) — controls icon rendering size. @@ -68,7 +66,6 @@ The form MUST preserve all fields on save; omitted fields MUST be populated with ### Requirement: REQ-QLNK-003 Icon resolution Each link's `icon` field MUST follow the same dual-mode convention as link-button-widget (REQ-LBN-002): -@e2e exclude icon resolution tests IconRenderer dispatch — Vitest component scope - A custom URL (starts with `/` or `http(s)://`) MUST render as `<img>` inside the icon container. - A bare name (e.g., `folder`, `calendar`, `mail`) MUST render via the shared `IconRenderer` (built-in MDI component). @@ -99,7 +96,6 @@ Icon size is controlled by the `iconSize` field (REQ-QLNK-004); label rendering ### Requirement: REQ-QLNK-004 Icon sizes and shapes The `iconSize` field MUST map to pixel dimensions as follows: -@e2e exclude icon sizes and shapes tests CSS dimension values — requires a placed quicklinks widget; seeded state not in CI fixture - `small` → 32 px square - `medium` → 48 px square @@ -136,7 +132,6 @@ When `tileBackgroundStyle = 'transparent'`, the shape only affects the icon's ba ### Requirement: REQ-QLNK-005 Label position control When `showLabels: true`, each link MUST display a label. The `labelPosition` field MUST control where and when the label appears: -@e2e exclude label position control tests CSS flex ordering — requires placed widget - `below` → label appears directly below the icon at all times; each link cell occupies `iconSize + label height` vertical space. - `overlay` → label appears centred over the icon only on hover (`:hover`, keyboard focus); default rendering shows icon only; hovering or focusing the link shows the label centred over the icon. @@ -171,7 +166,6 @@ The label text MUST be the link's `label` field, truncated to a sensible max len ### Requirement: REQ-QLNK-006 Column layout flexibility The `columns` field MUST control the layout grid as follows: -@e2e exclude column layout flexibility tests CSS grid layout — requires placed widget - `'auto'` (default) → CSS Flexbox with `flex-wrap: wrap`. Items flow left-to-right, wrapping to the next row when the widget width is exhausted. Item width is elastic based on `iconSize + label area`. - A number `1..12` → CSS Grid with `grid-template-columns: repeat(N, 1fr)`, where `N` is the specified number. Each item occupies exactly `1/N` of the widget's width. @@ -206,7 +200,6 @@ The renderer MUST ignore invalid values (e.g., `columns: 13` or `columns: 'inval ### Requirement: REQ-QLNK-007 Hover effects The `hoverEffect` field MUST control the CSS animation when a user hovers over a link: -@e2e exclude hover effects tests CSS :hover transitions — requires placed widget and hover simulation - `lift` (default) → translate the icon upward by 2–4 px and add a subtle box-shadow (e.g., `0 4px 8px rgba(0, 0, 0, 0.1)`). Transition duration ≈ 200ms. - `fade` → reduce opacity of non-hovered links to 0.6 while hovered link remains 1.0. Transition duration ≈ 150ms. @@ -249,7 +242,6 @@ Effects MUST apply only to the hovered link, not the entire widget. ### Requirement: REQ-QLNK-008 URL sanitisation on save When the edit form submits, the system MUST validate each link's `url` field. Invalid URLs MUST be rejected with an HTTP 400 response and a user-friendly error message. The validation rules are: -@e2e exclude URL sanitisation runs on save in PHP — Newman scope; frontend sanitiser tested by Vitest - MUST start with `http://`, `https://`, or `/` (relative Nextcloud URLs). - MUST NOT contain `javascript:`, `data:`, `vbscript:`, or other dangerous protocols. @@ -295,7 +287,6 @@ The form MUST display inline validation feedback (red border + error text) on th ### Requirement: REQ-QLNK-009 Click and navigation When a user clicks a link in the rendered widget, the system MUST navigate based on the link's `url` and `openInNewTab` fields: -@e2e exclude click and navigation tests window.open + router.push inside a placed widget — requires seeded quicklinks placement - If `url` starts with `/` (relative, internal Nextcloud URL) and `openInNewTab: false` (or not set and auto-detect resolves to same-tab), navigate in the same tab via `router.push(url)` or `window.location.href = url`. - If `url` starts with `http(s)://` (external) OR `openInNewTab: true`, open in a new tab via `window.open(url, '_blank', 'noopener,noreferrer')`. @@ -333,7 +324,6 @@ Auto-detect for `openInNewTab` when not specified: if the URL is external (`http ### Requirement: REQ-QLNK-010 Accessibility Each link in the rendered widget MUST be an HTML `<a>` element (not a `<button>` or `<div>`). The `<a>` MUST have: -@e2e exclude accessibility tests ARIA role on links inside a placed widget — requires placed widget - `href` attribute set to the link's `url`. - `aria-label` set to a descriptive label. If `showLabels: true` and `labelPosition: 'below'`, use the visible label. Otherwise, use `url` hostname or a fallback like `t('Link to') + ' ' + extractHostname(url)`. @@ -372,7 +362,6 @@ Each link in the rendered widget MUST be an HTML `<a>` element (not a `<button>` ### Requirement: REQ-QLNK-011 Empty state and default sizing When a quicklinks widget has zero links (`links: []`), the renderer MUST display an empty state message. The message MUST be: -@e2e exclude empty state and default sizing tests Vue empty-state component inside placed widget — requires seeded empty placement - Translatable: `t('No quicklinks yet — click the gear icon to add some.')` (or similar in Dutch: `t('Nog geen snelkoppelingen — klik op het tandwielpictogram om er enkele toe te voegen.')`). - Centred horizontally and vertically in the widget's viewport. diff --git a/openspec/specs/resource-uploads/screens.md b/openspec/specs/resource-uploads/screens.md new file mode 100644 index 000000000..40d5e2ad9 --- /dev/null +++ b/openspec/specs/resource-uploads/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpTegelBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpTegelBewerken diff --git a/openspec/specs/resource-uploads/spec.md b/openspec/specs/resource-uploads/spec.md index e694f224b..dd2951a8a 100644 --- a/openspec/specs/resource-uploads/spec.md +++ b/openspec/specs/resource-uploads/spec.md @@ -26,11 +26,9 @@ Each upload produces: ## Requirements -@e2e exclude pure backend — all scenarios are PHP/service/API/data-layer; no UI surface - ### Requirement: Admin-only base64 upload endpoint (REQ-RES-001) -The system MUST expose `POST /api/resources` accepting a raw JSON body of the shape `{base64: 'data:image/<type>;base64,...'}`. The endpoint MUST be admin-only — non-admin requests MUST receive HTTP 403 with `{status: 'error', error: 'forbidden'}`. The endpoint MUST NOT accept multipart form data — only a base64-encoded data URL. +The system MUST expose `POST /api/resources` accepting a raw JSON body of the shape `{base64: 'data:image/<type>;base64,...'}`. The endpoint MUST be admin-only, through Nextcloud's `AuthorizedAdminSetting` attribute: Nextcloud refuses a non-admin with HTTP 403 and a request without a session with HTTP 401, each with Nextcloud's own `{message}` body, before LaunchPad runs. The defensive `assertAdmin()` check behind it answers HTTP 403 with `{status: 'error', error: 'forbidden'}` should the attribute ever be removed. The endpoint MUST NOT accept multipart form data — only a base64-encoded data URL. #### Scenario: Admin uploads a PNG @@ -43,7 +41,7 @@ The system MUST expose `POST /api/resources` accepting a raw JSON body of the sh - GIVEN an authenticated non-admin user - WHEN they POST any body to `/api/resources` -- THEN the system MUST return HTTP 403 with `{status: 'error', error: 'forbidden'}` +- THEN the system MUST return Nextcloud's HTTP 403 with `{"message": "Logged in account must be an admin, a sub admin or gotten special right to access this setting"}` - AND no file MUST be written #### Scenario: Multipart upload rejected @@ -115,6 +113,8 @@ Validated bytes MUST be stored via `IAppData::getFolder('resources')` (auto-crea - THEN the folder MUST be created automatically - AND the upload MUST succeed normally +@e2e exclude needs an app-data root with no `resources/` folder, which a shared instance that has served any upload never has again and HTTP cannot delete (there is no delete route); pinned by tests/Unit/Service/ResourceServiceTest.php::testFolderAutoCreatedWhenMissing + ### Requirement: Standardised response envelope (REQ-RES-005) Every successful response MUST conform to `{status: 'success', url: <string>, name: <string>, size: <int>}` (additional fields are allowed). Every error response MUST conform to `{status: 'error', error: <stable_string>, message: <translated string>}`. The `error` field is a stable enum suitable for client-side branching; `message` is for display. Raw exception messages MUST NEVER be returned to the client. @@ -128,7 +128,7 @@ Every successful response MUST conform to `{status: 'success', url: <string>, na #### Scenario: Stable error enum - GIVEN the documented error codes are `forbidden`, `unsupported_media_type`, `invalid_data_url`, `invalid_image_format`, `file_too_large`, `mime_mismatch`, `corrupt_image`, `invalid_svg`, `storage_failure` -- WHEN any rejection scenario above triggers +- WHEN any rejection scenario above that LaunchPad answers itself triggers (Nextcloud answers the non-admin and no-session refusals in its own shape) - THEN the `error` field MUST equal exactly one of those strings (no synonyms, no extras) ### Requirement: Public resource serving endpoint (REQ-RES-006) @@ -166,6 +166,8 @@ The response MUST include `Cache-Control: public, max-age=31536000` (one year, i - WHEN GETting it - THEN `Content-Type` MUST be `application/octet-stream` +@e2e exclude needs a `.bin` file planted in the resources folder by hand; both upload endpoints only ever write allow-listed extensions, so HTTP cannot create one; pinned by tests/Unit/Controller/ResourceServeControllerTest.php::testUnknownExtensionFallsBackToOctetStream and tests/Unit/Service/ResourceServeServiceTest.php::testContentTypeForFilename + #### Scenario: Missing file returns 404 - WHEN GET `/apps/launchpad/resource/does-not-exist.png` @@ -202,6 +204,8 @@ When the resources folder does not yet exist, the response MUST be `{status: 'su - WHEN GET `/api/resources` - THEN HTTP 200 with `{status: 'success', resources: []}` +@e2e exclude needs an app-data root with no `resources/` folder, which HTTP cannot restore once any upload ran (no delete route); pinned by tests/Unit/Controller/ResourceServeControllerTest.php::testListWithNoFolderReturnsEmptyArray and tests/Unit/Service/ResourceServeServiceTest.php::testListFilesReturnsEmptyArrayWhenFolderMissing + ### Requirement: Stream-via-memory buffer, size-bounded (REQ-RES-008) The implementation MUST stream resource bytes via an in-memory buffer bounded by the upload cap (5 MB per REQ-RES-003). For larger files (which currently CANNOT be uploaded but might exist if installed manually), the implementation MUST refuse to load (return 413 with the standardised error envelope) rather than exhaust memory. @@ -212,6 +216,8 @@ The implementation MUST stream resource bytes via an in-memory buffer bounded by - WHEN GETting it - THEN the implementation MUST read it into a `php://memory` stream, write the StreamResponse, and the client MUST receive the full bytes +@e2e exclude the `php://memory` buffer is internal to ResourceServeController::buildStreamResponse and invisible over HTTP (full-byte delivery itself is asserted by resource-uploads::serve-a-png); pinned by tests/Unit/Controller/ResourceServeControllerTest.php::testServePngReturnsBytesAndHeaders + #### Scenario: Refuse to serve oversize external file - GIVEN a manually-installed 50 MB file `<appdata>/resources/huge.bin` @@ -220,6 +226,8 @@ The implementation MUST stream resource bytes via an in-memory buffer bounded by - AND MUST NOT load the file into memory - NOTE: Normal uploads cannot exceed 5 MB (REQ-RES-003) so this only protects against manual filesystem tampering. +@e2e exclude needs a 50 MB file planted in app data by hand (uploads are capped at 5 MB); pinned by tests/Unit/Controller/ResourceServeControllerTest.php::testOversizeFileRefusedWithoutReadingBytes and ::testFileExactlyAtCapIsServed + ### Requirement: SVG sanitiser is mandatory before persistence (REQ-RES-009) The system MUST pass every uploaded SVG (declared `image/svg` or `image/svg+xml`) through `SvgSanitiser::sanitize(string $bytes): ?string` before any persistence. The sanitiser MUST return the sanitised SVG string on success OR `null` on parse failure / fully-stripped content. When `null` is returned, `ResourceService` MUST reject the upload with HTTP 400 `{status: 'error', error: 'invalid_svg'}` and MUST NOT write any file. The sanitised bytes (NOT the original) MUST be what gets persisted. Size validation (REQ-RES-003) MUST run AFTER sanitisation so the measured size is the persisted size. @@ -358,6 +366,8 @@ The sanitiser MUST parse SVG via `DOMDocument::loadXML($bytes, LIBXML_NONET | LI - THEN no network request MUST be issued for `http://attacker/evil.dtd` - AND parsing MUST proceed without fetching the DTD +@e2e exclude whether the server issued an outbound request cannot be observed from the browser or the test runner, and a timing proxy cannot fail on a network that refuses fast; pinned by tests/Unit/Service/SvgSanitiserTest.php::testExternalDtdDoesNotFetchNetwork + #### Scenario: Billion-laughs entity expansion bounded - GIVEN input declares nested entities expanding exponentially (XML billion-laughs payload) @@ -374,11 +384,13 @@ The sanitiser MUST parse SVG via `DOMDocument::loadXML($bytes, LIBXML_NONET | LI - AND `libxml_clear_errors()` MUST have been called after parse - AND no libxml warning text MUST appear in the HTTP response body +@e2e exclude Nextcloud's own PHP error handler keeps warnings out of the response body whether or not the sanitiser calls libxml_use_internal_errors/libxml_clear_errors, so no e2e can fail on their removal; no unit test pins the two calls either (tests/Unit/Service/SvgSanitiserTest.php::testUnparseableBytesReturnNull pins only the null return) + ### Requirement: Raw multipart upload endpoint (REQ-RES-014) The system MUST expose `POST /api/resources/upload` accepting `multipart/form-data` with a single `file` field carrying the raw image bytes (NOT base64). This is the path used by the dashboard image widget so a large image or GIF never has to be base64-encoded in the browser (which can freeze the tab) nor embedded inline in dashboard content. -The endpoint MUST enforce the SAME security as the base64 endpoint (REQ-RES-001): admin-only, via the `AuthorizedAdminSetting` attribute plus a defensive `assertAdmin()` check. A non-admin or unauthenticated request MUST receive HTTP 403 with `{status: 'error', error: 'forbidden'}` and MUST NOT write a file. +The endpoint MUST enforce the SAME security as the base64 endpoint (REQ-RES-001): admin-only, via the `AuthorizedAdminSetting` attribute plus a defensive `assertAdmin()` check. Nextcloud refuses a non-admin with HTTP 403 and an unauthenticated request with HTTP 401, each with its own `{message}` body, and no file MUST be written. The declared image type MUST be derived from the uploaded filename's extension and validated against the same allow-list, size cap (5 MB), raster MIME cross-check, and SVG sanitisation as the base64 endpoint (REQ-RES-002, REQ-RES-003, REQ-RES-009). On success the response MUST be HTTP 200 with the same `{status: 'success', url, name, size}` envelope and URL form (`/apps/launchpad/resource/<filename>`) as REQ-RES-001. A missing/failed `file` field MUST return HTTP 400 with `{status: 'error', error: 'no_file'}` (a multipart-specific code, distinct from the base64 endpoint's `invalid_data_url`). @@ -396,14 +408,14 @@ Uploaded resources are served by REQ-RES-006, which requires an authenticated us - GIVEN an authenticated non-admin user - WHEN they POST a file to `/api/resources/upload` -- THEN the system MUST return HTTP 403 with `{status: 'error', error: 'forbidden'}` +- THEN the system MUST return Nextcloud's HTTP 403 with `{"message": "Logged in account must be an admin, a sub admin or gotten special right to access this setting"}` - AND no file MUST be written #### Scenario: Unauthenticated request rejected - GIVEN no authenticated user - WHEN a request is POSTed to `/api/resources/upload` -- THEN the system MUST return HTTP 403 with `{status: 'error', error: 'forbidden'}` +- THEN the system MUST return Nextcloud's HTTP 401 with `{"message": "Current user is not logged in"}` - AND no file MUST be written #### Scenario: Missing file field rejected diff --git a/openspec/specs/rest-api-reference/spec.md b/openspec/specs/rest-api-reference/spec.md new file mode 100644 index 000000000..b10885b43 --- /dev/null +++ b/openspec/specs/rest-api-reference/spec.md @@ -0,0 +1,41 @@ +--- +status: done +--- + +# REST API reference + +## Purpose + +LaunchPad ships `openapi.json`, an OpenAPI 3.1 reference of its JSON API, generated from `appinfo/routes.php` and the controllers by `composer openapi:generate` and never edited by hand. Every operation states whether integrators may build on it, and `composer check:strict` fails when the reference and the routes drift apart. The document is served by the API itself (see `api-contract`). + +## Requirements + +### Requirement: LaunchPad ships a generated OpenAPI reference (REQ-RAPI-001) + +LaunchPad MUST ship `openapi.json` (OpenAPI 3.1) at the repository root, generated from `appinfo/routes.php` and the controllers, documenting every route with its method, path, parameters, request body, response shapes and required authentication. + +#### Scenario: Integrator reads the dashboard endpoints + +- **GIVEN** Mark, an integrator, opens the LaunchPad API page in the documentation +- **WHEN** he looks up listing dashboards +- **THEN** he finds `GET /index.php/apps/launchpad/api/dashboards` with its response fields and "Authentication: Nextcloud user, app password accepted" + +### Requirement: Every operation states its stability (REQ-RAPI-002) + +Every operation MUST carry `x-launchpad-stability` of `public` or `internal`. A public operation MUST only change after a deprecation notice in the changelog. + +#### Scenario: Internal route marked + +- **GIVEN** the route LaunchPad's own admin page uses to preview visibility rules +- **WHEN** Mark reads its entry +- **THEN** it is labelled "internal: may change without notice" + +### Requirement: The reference cannot drift from the routes (REQ-RAPI-003) + +`composer check:strict` MUST fail when a route in `appinfo/routes.php` has no operation in `openapi.json`, or when regenerating the file changes it. + +#### Scenario: New route without documentation + +- **GIVEN** a developer adds a route to `appinfo/routes.php` and does not regenerate `openapi.json` +- **WHEN** they run `composer check:strict` +- **THEN** `lint:openapi` fails and names the undocumented route diff --git a/openspec/specs/role-feature-permissions/screens.md b/openspec/specs/role-feature-permissions/screens.md new file mode 100644 index 000000000..8bce5f510 --- /dev/null +++ b/openspec/specs/role-feature-permissions/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpBeheerRollen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerRollen +- LpWidgetKiezen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetKiezen diff --git a/openspec/specs/role-feature-permissions/spec.md b/openspec/specs/role-feature-permissions/spec.md index 87b086511..f1f680ee3 100644 --- a/openspec/specs/role-feature-permissions/spec.md +++ b/openspec/specs/role-feature-permissions/spec.md @@ -53,12 +53,22 @@ One object per (groupId, widgetId) pair (slug `rld-{groupId}-{widgetId}`). ## Requirements -### REQ-RFP-001: Feature presence visibility by role +### Requirement: REQ-RFP-001: Feature presence visibility by role The system MUST render or hide dashboard features based on the authenticated user's effective role-feature-permissions. A widget not in the user's effective `allowedWidgets` set MUST NOT appear anywhere in the UI and MUST NOT be returned by `GET /api/widgets`. +This holds on every dashboard the user opens: their own, one shared with them, and a group or +default dashboard. The viewing user's role decides, not the owner's. A placement of a widget +outside it MUST come back from the dashboard reads (`GET /api/dashboard`, `GET /api/dashboard/{id}`) +with `isVisible` 0, or not at all for a view-only viewer, and the grid MUST NOT render it. The +placement itself is kept, so whoever may use the widget still sees it. + +`allowedWidgets` lists every widget a group may use, LaunchPad's own widget types (`text`, `tile`, +`header` and the rest of `lib/widget-types.json`) included, so a rule that names only Nextcloud +dashboard widgets hides LaunchPad's own widgets from its members too. + #### Scenario: Employee-role user does not see admin-only widgets - GIVEN a RoleFeaturePermission exists for group `"medewerkers"` with @@ -79,6 +89,18 @@ appear anywhere in the UI and MUST NOT be returned by `GET /api/widgets`. - THEN `GET /api/widgets` MUST return a list that includes `"user_status"` - AND the card library MUST display `"user_status"` as available to add +#### Scenario: Widget outside the viewer role is hidden on a shared or group dashboard + +- GIVEN a RoleFeaturePermission for group `"medewerkers"` that does NOT include `"analytics_dashboard"` +- AND user "pieter.van.dijk" belongs only to group `"medewerkers"` +- AND a dashboard owned by someone else, shared with pieter or published to his group, holds an + `"analytics_dashboard"` placement and an `"activity"` placement +- WHEN pieter opens that dashboard +- THEN the `"analytics_dashboard"` placement MUST NOT be rendered, and the dashboard read MUST + return it with `isVisible` 0 or leave it out +- AND the `"activity"` placement MUST be rendered +- AND the owner MUST still get the `"analytics_dashboard"` placement when their own role permits it + #### Scenario: Direct URL request to restricted feature returns 403 - GIVEN a RoleFeaturePermission for group `"medewerkers"` does NOT include `"analytics_dashboard"` @@ -92,7 +114,7 @@ appear anywhere in the UI and MUST NOT be returned by `GET /api/widgets`. --- -### REQ-RFP-002: Role-based default dashboard layout +### Requirement: REQ-RFP-002: Role-based default dashboard layout The system MUST seed a role-appropriate default layout. When a new user opens LaunchPad for the first time and no admin template matches their group, the system MUST seed their dashboard @@ -132,7 +154,7 @@ priority). Existing personal customisations MUST never be overwritten. --- -### REQ-RFP-003: Role-based card library +### Requirement: REQ-RFP-003: Role-based card library The card library (widget picker) MUST only surface widgets permitted for the authenticated user's effective role. Widgets outside the allowed set MUST be absent from the picker UI and @@ -168,7 +190,7 @@ from `GET /api/widgets`. --- -### REQ-RFP-004: Role-and-priority layout ordering +### Requirement: REQ-RFP-004: Role-and-priority layout ordering Widgets on a user's dashboard MUST be ordered according to the `priorityWeights` defined in the user's effective RoleFeaturePermission. Widgets with higher priority weight MUST appear @@ -204,7 +226,7 @@ earlier in the default sort order. --- -### REQ-RFP-005: Role precedence for multi-group users +### Requirement: REQ-RFP-005: Role precedence for multi-group users The system MUST resolve a deterministic effective widget set for multi-group users. When a user belongs to multiple groups that each have a RoleFeaturePermission, the system MUST resolve a @@ -244,7 +266,7 @@ the set; `deniedWidgets` from any matched group always win. --- -### REQ-RFP-006: Role, interest, and journey distinction +### Requirement: REQ-RFP-006: Role, interest, and journey distinction The system MUST distinguish between role-based access (Nextcloud group membership), expressed personal interest (user adds a widget they are permitted to add), and journey stage (the user's @@ -283,7 +305,7 @@ effect within one session refresh. --- -### REQ-RFP-007: Admin CRUD for role-feature-permissions +### Requirement: REQ-RFP-007: Admin CRUD for role-feature-permissions IT admins MUST be able to create, read, update, and delete RoleFeaturePermission objects via admin-only API endpoints. Non-admin users MUST receive HTTP 403 on all mutation attempts. @@ -322,7 +344,7 @@ admin-only API endpoints. Non-admin users MUST receive HTTP 403 on all mutation --- -### REQ-RFP-008: Admin CRUD for role-layout-defaults +### Requirement: REQ-RFP-008: Admin CRUD for role-layout-defaults IT admins MUST be able to create, read, update, and delete RoleLayoutDefault objects. Non-admin users MUST receive HTTP 403 on all mutation attempts. @@ -353,7 +375,7 @@ users MUST receive HTTP 403 on all mutation attempts. --- -### REQ-RFP-009: Unconfigured installations retain full backwards-compatibility +### Requirement: REQ-RFP-009: Unconfigured installations retain full backwards-compatibility When no RoleFeaturePermission objects exist in OpenRegister, `GET /api/widgets` MUST return the full widget list unchanged. No change in behaviour for existing LaunchPad installations that @@ -378,17 +400,25 @@ have not configured role-feature-permissions. --- -### REQ-RFP-010: Initial-state widget allowlist +### Requirement: REQ-RFP-010: Initial-state widget allowlist The backend MUST include the resolved `allowedWidgets` list (or `null` for unconfigured) in the initial-state payload delivered to the frontend, so that the card library can filter without a separate API call. +The `widgets` initial-state key MUST carry the Nextcloud dashboard widgets the user may add, +already narrowed to `allowedWidgets`, so the card library lists them without +`GET /api/widgets`. The page MUST read them without running any widget's `load()`, which would +inject every widget's scripts into a page that renders no Nextcloud dashboard; only with the +legacy widget bridge on is the registry loaded. When the widgets cannot be read without loading +them, `widgets` MUST be empty and the card library MUST fall back to `GET /api/widgets`. + #### Scenario: Initial state includes allowedWidgets for role-configured user - GIVEN user "noor.yilmaz" has group `"managers"` with `allowedWidgets: ["activity", "analytics_dashboard"]` - WHEN the LaunchPad page loads and `GET /api/settings` or the initial-state endpoint is called - THEN the response payload MUST include `"allowedWidgets": ["activity", "analytics_dashboard"]` +- AND the `widgets` initial state MUST hold the `"activity"` and `"analytics_dashboard"` widgets and no other - AND the frontend card library MUST use this list to filter without an additional API call #### Scenario: Initial state includes null for unconfigured installation @@ -400,6 +430,47 @@ without a separate API call. --- +### Requirement: REQ-RFP-011: The shipped default rule lets every user add LaunchPad's own widgets + +The `default` RoleFeaturePermission that a fresh install seeds MUST allow every LaunchPad widget +type listed in `lib/widget-types.json`, plus the Nextcloud dashboard widgets `activity` and +`recommendations`. A user with no group rule of their own MUST be able to add any LaunchPad widget. +On upgrade, a `default` rule that still holds exactly what older versions shipped +(`["activity", "recommendations"]` and no denials) MUST be widened to the same list. A `default` +rule an administrator edited MUST be kept as it is. + +The same holds for the group rules a fresh install seeds (`medewerkers`, `managers`, `ict-beheer`, +`hrm`): each MUST allow every LaunchPad widget type besides its own Nextcloud dashboard widgets, +because a rule lists every widget its group may use and REQ-RFP-001 hides anything outside it on +every dashboard. On upgrade, a shipped group rule that still allows and denies exactly what older +versions seeded MUST be widened the same way, its denials kept. A group rule an administrator +edited MUST be kept as it is. + +#### Scenario: A fresh install lets every user add a LaunchPad widget + +- GIVEN LaunchPad is installed and the seeded `default` rule is untouched +- AND user "sem" belongs to no group that has a rule of its own +- WHEN sem adds a `text` widget to his own dashboard +- THEN the widget MUST be added + +#### Scenario: An upgrade widens the old shipped rule and keeps an edited one + +- GIVEN an instance whose `default` rule allows only `["activity", "recommendations"]` and denies nothing +- WHEN LaunchPad is upgraded +- THEN the `default` rule MUST allow every LaunchPad widget type plus `activity` and `recommendations` +- AND when an administrator had changed the `default` rule, it MUST stay as the administrator left it + +#### Scenario: An upgrade widens the shipped group rules and keeps an edited one + +- GIVEN an instance whose `hrm` rule allows only `["activity", "recommendations", "notes", "calendar", "user_status"]` and denies `["system_monitor"]`, as older versions seeded it +- AND user "fatima" belongs only to group `"hrm"` and opens a group dashboard with a `text` widget +- WHEN LaunchPad is upgraded +- THEN the `hrm` rule MUST allow every LaunchPad widget type besides those five, and still deny `system_monitor` +- AND fatima MUST see the `text` widget +- AND when an administrator had changed the `hrm` rule, it MUST stay as the administrator left it + +--- + ## Non-Functional Requirements - **Security**: All permission checks MUST be enforced server-side in `RoleFeaturePermissionService`. diff --git a/openspec/specs/runtime-or-consumption/screens.md b/openspec/specs/runtime-or-consumption/screens.md new file mode 100644 index 000000000..90b136512 --- /dev/null +++ b/openspec/specs/runtime-or-consumption/screens.md @@ -0,0 +1,3 @@ +# Screens + +- No screen: Installatie op een kale Nextcloud, geen scherm. diff --git a/openspec/specs/runtime-or-consumption/spec.md b/openspec/specs/runtime-or-consumption/spec.md index 8cb85f861..8a64160db 100644 --- a/openspec/specs/runtime-or-consumption/spec.md +++ b/openspec/specs/runtime-or-consumption/spec.md @@ -23,13 +23,16 @@ consume OR data at runtime.** OR is never a hard dependency. ## Requirements -@e2e exclude pure runtime/contract spec — scenarios assert manifest.json/info.xml/composer dependency contents, `useOrFeatureDetect()` composable gating, `?_lang=` query-param construction, tenant-scope headers, @nextcloud/axios usage, and OR-absent/5xx/recovery HTTP behaviour. None is a user-facing UI surface; these are unit-test + Newman concerns (no OR-data widget is shipped in launchpad to drive through the UI). - ### Requirement: No install-time OR dependency (REQ-OR-001) LaunchPad MUST NOT declare an install-time dependency on `openregister` or `openconnector` in `appinfo/info.xml`, `composer.json`, or -`src/manifest.json`. +`src/manifest.json`. The manifest MAY list OpenRegister as an optional +dependency (`{"id": "openregister", "required": false}`), so the shell can +name it to the admin, but an entry for `openregister` or `openconnector` +MUST NOT be required: no bare app-id string and no `required: true`. The same +holds for the manifest served by `GET /api/manifest`, which replaces the +bundled one at boot. #### Scenario: Fresh install without OR boots normally @@ -40,12 +43,12 @@ LaunchPad MUST NOT declare an install-time dependency on `openregister` or - AND no "missing dependency" warning or fatal error MUST appear in the Nextcloud log -#### Scenario: manifest.json dependencies array is empty +#### Scenario: The manifest lists OpenRegister only as optional -- GIVEN the `src/manifest.json` file for LaunchPad -- WHEN it is parsed -- THEN the `dependencies` array MUST be `[]` -- AND it MUST NOT contain `"openregister"` or `"openconnector"` +- GIVEN the `src/manifest.json` file for LaunchPad, and the manifest served by `GET /api/manifest` +- WHEN each is parsed +- THEN its `dependencies` array MUST list OpenRegister as `{"id": "openregister", "required": false}` +- AND no entry MUST be a bare `"openregister"` or `"openconnector"` string, and no entry MUST be required --- @@ -56,6 +59,8 @@ and check `enabled.value` before issuing any OR API request. #### Scenario: Widget skips OR fetch when OR is absent +@e2e exclude never built: `useOrFeatureDetect` does not exist anywhere under `src/` (only in `docs/widgets/or-data.md` and `docs/architecture.md`; `git log --all -S useOrFeatureDetect -- src lib` finds no commit), so nothing skips the fetch and no test pins it: spec ahead of code. An OR-less instance is no longer the obstacle: `tests/e2e/or-absent.spec.ts` disables OpenRegister for its length and cites the empty state (`or-absent-empty-state-shown`), but asserting "no request to OpenRegister" there would only measure the missing feature. + - GIVEN a Nextcloud instance without OR installed - WHEN an OR-data widget mounts - THEN `useOrFeatureDetect().enabled.value` MUST be `false` @@ -108,6 +113,8 @@ Until `useTenantContext()` is available: #### Scenario: Widget passes tenant scope when context is available +@e2e exclude `useTenantContext` IS exported by the installed `@conduction/nextcloud-vue` 2.180.0 (its `src/index.js`), but no LaunchPad source imports it and nc-vue's `CnObjectListWidget` does not consult it, so no widget sends tenant scope. There is also no value to assert: OpenRegister reads no tenant header or query parameter on object reads; it scopes by the user's stored `active_organisation` preference (`openregister/lib/Db/OrganisationMapper.php`). The visibility half (only `acme-corp` objects) is OpenRegister's own server-side ACL, which the requirement itself defers to; LaunchPad has no test for it. + - GIVEN `useTenantContext()` is available in the installed nc-vue version - AND the current user is scoped to tenant `acme-corp` - WHEN an OR-data widget fetches OR objects @@ -170,6 +177,7 @@ hardcoded tokens, API keys, or forge request headers. - `useOrFeatureDetect()` lives at `src/composables/useOrFeatureDetect.js`. See `docs/widgets/or-data.md` for the canonical widget pattern. -- The `dependencies: []` guard in `scripts/check-manifest.js` blocks - accidental re-introduction of OR as a hard dep (runs in +- The `dependencies` guard in `scripts/check-manifest.js` blocks a bare + `"openregister"` or `"openconnector"` string, so OR cannot come back as a + hard dep (runs in `npm run check:manifest`, which is wired into `npm run lint`). diff --git a/openspec/specs/runtime-shell/screens.md b/openspec/specs/runtime-shell/screens.md new file mode 100644 index 000000000..55edfc68b --- /dev/null +++ b/openspec/specs/runtime-shell/screens.md @@ -0,0 +1,5 @@ +# Screens + +- LpEersteKeer https://identity.conduction.nl/screens/board?id=launchpad/LpEersteKeer +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag +- LpBeheerAlgemeen https://identity.conduction.nl/screens/board?id=launchpad/LpBeheerAlgemeen diff --git a/openspec/specs/runtime-shell/spec.md b/openspec/specs/runtime-shell/spec.md index 20d06e81e..80361c9d6 100644 --- a/openspec/specs/runtime-shell/spec.md +++ b/openspec/specs/runtime-shell/spec.md @@ -6,7 +6,7 @@ status: done ## Purpose -The `runtime-shell` capability owns the user-facing workspace page chrome — the mount point, the sidebar toggle, the active-dashboard label strip, the empty-state branch, and the lifecycle hooks that bind it all together. It is the page-level orchestrator that coordinates four sibling capabilities (`dashboard-switcher`, `widget-add-edit-modal`, `widget-context-menu`, `grid-layout`) and gates editing affordances based on user role and active dashboard scope. +The `runtime-shell` capability owns the user-facing workspace page chrome — the mount point, the way to the dashboards through More, the empty-state branch, and the lifecycle hooks that bind it all together. It is the page-level orchestrator that coordinates four sibling capabilities (`dashboard-switcher`, `widget-add-edit-modal`, `widget-context-menu`, `grid-layout`) and gates editing affordances based on user role and active dashboard scope. The shell deliberately holds NO source-of-truth data of its own — every key it consumes flows through the typed initial-state contract via `provide` / `inject`, and every persistence call routes through existing dashboard endpoints. Local state is restricted to UI-only fields (currently just `sidebarOpen` after `runtime-shell-trim` removed the toolbar's `saving` + `showAddDropdown` fields). @@ -14,13 +14,13 @@ The shell deliberately holds NO source-of-truth data of its own — every key it ### Requirement: Single mount point (REQ-SHELL-001) -The system MUST render the workspace Vue app into exactly one DOM element (id `launchpad-app`), located inside a `<div id="app-workspace" class="launchpad-workspace">` provided by `templates/index.php`. Nextcloud's chrome MUST treat `#app-workspace` as the main content slot (`'id-app-content' => '#app-workspace'`). No left navigation slot MUST be allocated by the chrome (`'id-app-navigation' => null`) — the shell renders its own slide-in sidebar instead. +The system MUST render the workspace Vue app into exactly one DOM element (id `workspace-vue`, the id `src/main.js` mounts on), located inside a `<div id="app-workspace" class="launchpad-workspace">` provided by `templates/index.php`. Nextcloud's chrome MUST treat `#app-workspace` as the main content slot (`'id-app-content' => '#app-workspace'`). No left navigation slot MUST be allocated by the chrome (`'id-app-navigation' => null`) — the shell renders its own slide-in sidebar instead. #### Scenario: Mount point present - GIVEN the user has navigated to the workspace page - WHEN the page HTML is rendered -- THEN the rendered HTML MUST contain exactly one `<div id="launchpad-app">` +- THEN the rendered HTML MUST contain exactly one `<div id="workspace-vue">` - AND it MUST be a child of `<div id="app-workspace">` - AND no Nextcloud chrome navigation panel MUST be rendered @@ -30,24 +30,23 @@ The system MUST render the workspace Vue app into exactly one DOM element (id `l - The per-widget right-click context menu (REQ-WDG-015) - GridStack's `staticGrid` mode (false when `canEdit`, true otherwise) -- The action menu's edit entries: "Add custom widget…", "Save dashboard", "Dashboard configuration…" +- More's edit entries: "Edit" and "Add widget" (REQ-SHELL-013), and with them the edit bar and its "Dashboard settings" (dashboards REQ-DASH-038) `canEdit` MUST NOT gate any toolbar (none exists) or any sidebar entries (the sidebar shows the same dashboards regardless; per-row create/delete affordances have their own gating per REQ-SWITCH-005). -@e2e exclude edit affordances gated by canEdit requires a non-admin user session — test fixture is single-user admin; canEdit=false scenario not available headlessly #### Scenario: Non-edit user has no edit affordances visible - **GIVEN** a non-admin user viewing a `group_shared` dashboard (`dashboardSource === 'group'`) - **WHEN** they open the action menu -- **THEN** no "Add custom widget", "Save dashboard", or "Dashboard configuration" entries MUST be visible +- **THEN** no "Edit" or "Add widget" entries MUST be visible - **AND** right-clicking any widget MUST fall through to the browser's native context menu #### Scenario: canEdit user sees full edit menu - **GIVEN** an admin user viewing any dashboard - **WHEN** they open the action menu -- **THEN** "Add custom widget…", "Save dashboard", "Dashboard configuration…", and "Documentation" MUST all be present -- **AND** right-clicking a widget MUST open the widget context menu (REQ-WDG-015) +- **THEN** "Edit", "Add widget" and, under Settings, "Documentation" MUST all be present +- **AND** in edit mode, right-clicking a widget MUST open the widget context menu (REQ-WDG-015, which keeps view mode on the browser's native menu) ### Requirement: REQ-SHELL-003 Toolbar contents @@ -55,7 +54,8 @@ When `canEdit` is true, the toolbar MUST render exactly two affordances: an **Ad #### Scenario: Add-widget dropdown lists all widget types -@e2e exclude registry-driven dropdown contents — covered by Vitest component test +@e2e exclude REQ-SHELL-003 was REMOVED by openspec/changes/archive/2026-05-03-runtime-shell-trim (the toolbar with its Add Widget dropdown and Save Layout button was deleted; layout edits save per placement), but this spec was never synced, so there is no control to drive. The toolbar's absence is pinned by src/views/__tests__/WorkspaceApp.spec.js "does not render an in-page edit toolbar even when canEdit=true". + - GIVEN the widget-type registry contains 5 entries - WHEN the user opens the Add Widget dropdown - THEN it MUST display 5 menu items, one per registered type @@ -63,7 +63,8 @@ When `canEdit` is true, the toolbar MUST render exactly two affordances: an **Ad #### Scenario: Save sends layout to correct endpoint -@e2e exclude PUT request shape/endpoint assertion — covered by Vitest + Newman +@e2e exclude REQ-SHELL-003 was REMOVED by openspec/changes/archive/2026-05-03-runtime-shell-trim (the toolbar with its Add Widget dropdown and Save Layout button was deleted; layout edits save per placement), but this spec was never synced, so there is no control to drive. The toolbar's absence is pinned by src/views/__tests__/WorkspaceApp.spec.js "does not render an in-page edit toolbar even when canEdit=true". + - GIVEN `dashboardSource: 'user'` and `activeDashboardId: 'abc'` - WHEN the user clicks Save - THEN the system MUST send `PUT /api/dashboards/abc` with body `{layout: <current widgets>}` @@ -72,64 +73,95 @@ When `canEdit` is true, the toolbar MUST render exactly two affordances: an **Ad #### Scenario: Save button disabled while in flight +@e2e exclude REQ-SHELL-003 was REMOVED by openspec/changes/archive/2026-05-03-runtime-shell-trim (the toolbar with its Add Widget dropdown and Save Layout button was deleted; layout edits save per placement), but this spec was never synced, so there is no control to drive. The toolbar's absence is pinned by src/views/__tests__/WorkspaceApp.spec.js "does not render an in-page edit toolbar even when canEdit=true". + - GIVEN a Save request is in flight - WHEN the user attempts to click Save again - THEN the button MUST be disabled (HTML `disabled` attribute set) - AND no second request MUST fire -### Requirement: REQ-SHELL-004 Hamburger toggle and active-dashboard label +### Requirement: REQ-SHELL-004 The dashboards are reached through More -The shell MUST render, in the title strip: +The shell MUST NOT render a sidebar-toggle (hamburger) button or a title strip with the active dashboard's name. The drawn boards (`launchpad/LpVandaag`, `launchpad/LpWerkplek`) draw neither: the top row holds the More menu (REQ-SHELL-009), and its Dashboards group is how a person switches. -- A sidebar-toggle button using `NcButton` with `type="tertiary"`, an `aria-label` of `t('launchpad', 'Open menu')`, and a 20-px menu icon. The button's visual treatment (size, hover/focus/active rings) MUST match the Nextcloud account-menu button so the workspace chrome reads as native Nextcloud UI. -- The active dashboard's name as a plain `<h1>` (or `<h2>`) text label — NOT as a `<select>` or any other interactive switcher control. Switching between dashboards happens exclusively via the left sidebar (`dashboard-switcher` capability). +- The Dashboards group lists the user's dashboards, marks the open one (`role="menuitemradio"`, `aria-checked="true"`), and ends in "All dashboards". +- "All dashboards" opens the slide-in switcher sidebar (`dashboard-switcher`). The sidebar closes from its own close button, from the backdrop (REQ-SHELL-006) and on Escape. The shell MUST NOT render a standalone "Active dashboard" select dropdown anywhere in its surface area. -#### Scenario: Toggle button matches account-button styling +**Why.** The hamburger and the strip went with LpVandaag (one More menu for the start page) and the navigation panel with REQ-SHELL-009. The former scenarios "Toggle button matches account-button styling", "Active-dashboard name visible" and "Empty label on empty state" were removed with them: there is no toggle and no label left to assert. + +#### Scenario: No sidebar toggle - **GIVEN** the workspace shell rendered for an authenticated user - **WHEN** the page loads -- **THEN** the sidebar-toggle button MUST be a `NcButton type="tertiary"` element -- **AND** its rendered class list MUST include the same `button-vue--vue-tertiary` (or current equivalent) classes the Nextcloud account button uses -- **AND** clicking it MUST toggle the sidebar's `isOpen` state +- **THEN** no sidebar-toggle button MUST be rendered +- **AND** the More menu MUST be rendered exactly once, and the switcher sidebar MUST be closed + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-004 + +#### Scenario: All dashboards opens the switcher + +- **GIVEN** the workspace shell rendered for an authenticated user +- **WHEN** they open More and choose "All dashboards" +- **THEN** the switcher sidebar MUST open +- **AND** its close button MUST close it again + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-004 #### Scenario: No active-dashboard select control - **GIVEN** the workspace shell rendered with multiple dashboards visible to the user - **WHEN** the page is inspected - **THEN** no `<select>` element with `name="activeDashboard"` (or equivalent) MUST be present -- **AND** the active dashboard's name MUST appear as a heading in the title strip -- **AND** dashboard switching MUST happen only via the left sidebar's row click handlers (REQ-SWITCH-002) +- **AND** the open dashboard MUST be the one marked entry of More's Dashboards group +- **AND** dashboard switching MUST happen only through More and the switcher sidebar's row click handlers (REQ-SWITCH-002) -#### Scenario: Active-dashboard name visible +@e2e openspec/specs/runtime-shell/spec.md#req-shell-004 -- GIVEN active dashboard `D` has `name = "Marketing Overview"` -- WHEN the workspace renders -- THEN the label next to the hamburger MUST display `"Marketing Overview"` +### Requirement: Empty state (REQ-SHELL-005) -#### Scenario: Empty label on empty state +When the resolver returned no active dashboard, the shell MUST render an empty-state UI inside the grid container, directly on the page ground with no card or panel of its own, as board LpEersteKeer draws it. Its heading is "You have no dashboard yet" (nl "U heeft nog geen dashboard"). -- GIVEN no active dashboard is resolved (resolver returned null) -- WHEN the workspace renders -- THEN the label MUST be empty -- AND the empty-state component MUST render in the grid area instead +When `allowUserDashboards` is `true` the empty state MUST show, in this order: -### Requirement: Empty state (REQ-SHELL-005) +- the explanation "A dashboard puts your apps, messages and appointments in one place. Start with a few starter widgets and then adjust it as you like." (nl "Een dashboard zet uw apps, berichten en afspraken op één plek. Begin met een paar startwidgets en pas het daarna aan zoals u wilt."); +- the starter widgets: Apps, Calendar, Mail, Files, Weather and News from the organisation (nl Apps, Agenda, E-mail, Bestanden, Weer, Nieuws van de organisatie); +- the note "These 6 starter widgets go on it. You can move or remove them later." (nl "Deze 6 startwidgets komen erop. U kunt ze later verplaatsen of weghalen."); +- a primary "Create my first dashboard (with starter widgets)" button (nl "Maak mijn eerste dashboard (met startwidgets)") and a secondary "Start empty" button (nl "Leeg beginnen"). + +Both buttons create a personal dashboard named "My workspace" (nl "Mijn werkplek", as board LpEersteKeer titles it) through `POST /api/dashboard`, which takes an optional `widgets` choice. `starters` seeds the starter widgets (`lib/Service/StarterWidgetSeeds.php`), each one usable without configuration: an `app-tiles` grid of the person's apps, a `calendar` agenda on their personal calendar, Nextcloud Mail's `mail` dashboard widget through `nc-widget`, `files`, `weather` at their weather-status location, and the organisation's `announcements`. `none` seeds nothing. With no choice the create keeps the default widget bundle (default-widget-bundle), so the "+" new-dashboard flow does not change. + +When `allowUserDashboards` is `false` no create button and no starter list MUST be shown, and the message MUST direct the user to contact their administrator. + +#### Scenario: A first dashboard with starter widgets +- GIVEN a member without a dashboard, and personal dashboards are allowed +- WHEN they choose "Create my first dashboard (with starter widgets)" +- THEN the new dashboard MUST hold the six starter widgets, in the order listed above + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-005 -When the resolver returned no active dashboard, the shell MUST render an empty-state UI inside the grid container with: a friendly message ("No dashboards available"), an explanation, and — if `allowUserDashboards` is `true` — a primary "Create your first dashboard" button that calls the create-personal flow. When `allowUserDashboards` is `false` no Create button MUST be shown and the message MUST direct the user to contact their administrator. -@e2e exclude empty state requires no dashboards — test fixture always has at least one dashboard; empty state cannot be triggered without destructive setup +#### Scenario: A first dashboard started empty +- GIVEN a member without a dashboard, and personal dashboards are allowed +- WHEN they choose "Start empty" +- THEN the new dashboard MUST hold no widgets + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-005 #### Scenario: Empty state with creation enabled +@e2e exclude Unreachable on a live instance: since #361 (c9e58089) SeedDefaultDashboard provisions a dashboard on the reserved `default` group that every account resolves to, so no account gets the empty state without deleting the shipped default on a shared instance (runtime-shell-canEdit.spec.ts keeps its attempt as fixme for this reason). The branch is pinned by src/views/__tests__/WorkspaceApp.spec.js "empty state with allowUserDashboards renders Create CTA" and WorkspaceApp.behaviour.spec.js "creates a first dashboard from the empty state" and "creates an empty first dashboard from Start empty"; what each button stores is proved against the live endpoint by tests/e2e/first-run-starter-widgets.spec.ts. + - GIVEN no active dashboard is resolved - AND `allowUserDashboards` is `true` - WHEN the workspace renders -- THEN the empty-state MUST render with a "Create your first dashboard" button -- AND clicking it MUST call `POST /api/dashboards` with a default name +- THEN the empty-state MUST render with the starter widgets, a "Create my first dashboard (with starter widgets)" button and a "Start empty" button +- AND the first MUST call `POST /api/dashboard` with the name "My workspace" and `widgets: "starters"`, the second with `widgets: "none"` #### Scenario: Empty state with creation disabled +@e2e exclude Unreachable on a live instance: since #361 (c9e58089) SeedDefaultDashboard provisions a dashboard on the reserved `default` group that every account resolves to, so no account gets the empty state without deleting the shipped default on a shared instance (runtime-shell-canEdit.spec.ts keeps its attempt as fixme for this reason). The branch is pinned by src/views/__tests__/WorkspaceApp.spec.js "empty state without allowUserDashboards hides Create CTA". + - GIVEN no active dashboard is resolved - AND `allowUserDashboards` is `false` - WHEN the workspace renders @@ -139,7 +171,6 @@ When the resolver returned no active dashboard, the shell MUST render an empty-s ### Requirement: Sidebar backdrop (REQ-SHELL-006) When `sidebarOpen` is `true`, the shell MUST render a fixed-position backdrop that intercepts clicks and closes the sidebar. The backdrop MUST start at the same `top` offset as the Nextcloud header (50 px) and span the rest of the viewport. Clicks on the sidebar itself MUST NOT close the sidebar. -@e2e exclude sidebar backdrop close tests a fixed-position overlay click — backdrop behaviour is tested end-to-end via PR #111 wave3 tests #### Scenario: Backdrop closes sidebar on click @@ -156,10 +187,11 @@ When `sidebarOpen` is `true`, the shell MUST render a fixed-position backdrop th ### Requirement: Lifecycle hooks (REQ-SHELL-007) The shell MUST register a global `document.click` listener on mount (delegated to the grid composable's `handleClickOutside`) and remove it on unmount. The GridStack instance MUST be initialised after `nextTick()` (so the grid container ref is non-null) and destroyed on unmount. -@e2e exclude lifecycle hooks (addEventListener + GridStack destroy) are internal Vue onMounted/onUnmounted calls — not observable from Playwright without page-unload automation #### Scenario: Listener and grid registered after mount +@e2e exclude Internal mount/unmount wiring with no browser-observable outcome. The document listener the shell registers today is `keydown` (Escape closes the sidebar), not a `click`/`handleClickOutside` one, which no longer exists in src/; its add/remove is pinned by src/views/__tests__/WorkspaceApp.behaviour.spec.js "stops listening for Escape once unmounted". The grid is created and destroyed by the shared library's grid component inside Views.vue; no LaunchPad unit test pins that. + - GIVEN the shell component is being mounted - WHEN the `onMounted` hook runs - THEN `document.addEventListener('click', handleClickOutside)` MUST have been called @@ -167,7 +199,199 @@ The shell MUST register a global `document.click` listener on mount (delegated t #### Scenario: Listener cleanup on unmount +@e2e exclude Internal mount/unmount wiring with no browser-observable outcome. The document listener the shell registers today is `keydown` (Escape closes the sidebar), not a `click`/`handleClickOutside` one, which no longer exists in src/; its add/remove is pinned by src/views/__tests__/WorkspaceApp.behaviour.spec.js "stops listening for Escape once unmounted". The grid is created and destroyed by the shared library's grid component inside Views.vue; no LaunchPad unit test pins that. + - GIVEN the shell has mounted and registered the click listener - WHEN the shell unmounts (e.g. user navigates away) - THEN `document.removeEventListener('click', handleClickOutside)` MUST be called - AND the GridStack instance MUST be destroyed (no DOM leftover, no memory leak) + +### Requirement: REQ-SHELL-008 The first-open support note is for administrators + +The shared library's first-open support note (`CnSupportDialog`: donate, get support, suggest a feature, review) MUST be mounted for administrators only. `App.vue` passes `:supportDialog="false"` to `CnAppRoot` for every account without the `admin` permission (`utils/permissions.js`), so a member never sees it; for an administrator the library's own once-per-user behaviour applies. + +**Why.** Every new user got the note on top of the start page an administrator had just set for their group (#782, seen for three fresh users on 5 October 2026). The note asks for things only an administrator can act on. + +**What this does not change.** The first-visit tour (REQ-SHELL-010) is the library's walkthrough and is declared in `src/manifest.json`. The library withholds the tour while the support note is open, so the two never stack. + +#### Scenario: A member's first visit shows no support note +- GIVEN Pieter is not an administrator and has never opened LaunchPad +- WHEN he opens LaunchPad +- THEN no "Support LaunchPad" dialog MUST open + +#### Scenario: An administrator's first visit keeps the note +- GIVEN Ruben is an administrator and has never opened LaunchPad +- WHEN he opens LaunchPad +- THEN the note MUST open once, as before + +#### Scenario: On the administration page the admin tour comes first +- GIVEN Noor is an administrator who has never opened LaunchPad +- WHEN she opens the administration page (`/apps/launchpad/admin`) +- THEN the admin tour (REQ-SHELL-011) MUST start and no "Support LaunchPad" dialog MUST open on that page load +- AND the note MUST open on her next page load of another LaunchPad page + +### Requirement: REQ-SHELL-009 No navigation panel; the destinations are in the More menu + +LaunchPad MUST NOT render a left navigation panel on any page. `App.vue` passes `hideMenu` to `CnAppRoot`, so neither `CnAppNav` nor the `#menu` slot renders and `NcAppContent` takes the full width. LaunchPad is a dashboard app whose canvas is the page; hydra ADR-114 Decision 10 exempts it from rendering the app chrome in a left panel. + +Everything the panel offered MUST stay reachable through the More menu: the panel's entries (`manifest.menu` in the sections main, footer and settings, after the same permission filter the panel applied), the personal settings dialog, and for an administrator the link to Nextcloud's admin settings. That covers Documentation, Marketplace and Features & roadmap (the panel's footer) and Reports, Flows, Templates and the settings (its Advanced foldout). + +- On the dashboard view (`/` and `/dashboards/:id`) the workspace's own More menu (`DashboardMoreMenu`) carries them under its expandable Settings item, beside the dashboards and the open dashboard's actions. A member without an active dashboard gets the same menu (`StartPageMenu`) in the empty state. +- Both are the one menu of REQ-SHELL-013 (board LpMeer), with the items under Settings in this order: Personal settings, Admin settings for an administrator, then Marketplace, Templates, Reports, Flows, Integrations, Documentation, Features & roadmap (nl Persoonlijke instellingen, Beheerinstellingen, Marktplaats, Sjablonen, Rapporten, Flows, Koppelingen, Documentatie, Functies en roadmap). An entry the board does not name follows at the end. The in-app admin settings route (`admin-settings`) only redirects to Nextcloud's admin settings, so the menu offers that destination once, as the admin settings link. The manifest's `dashboards` entry is the Dashboards group. +- On every other page (Marketplace, Reports, Flows, Features & roadmap, the admin pages) `App.vue` renders the same More menu at the top end of the content, through `CnAppRoot`'s `#header-actions` slot, and keeps that column free so a page's own header actions are never covered. Its Dashboards group is how a member gets back. +- A kiosk view (`?kiosk=1`, REQ-KIOSK-001) renders neither. + +The menus are keyboard reachable with visible focus and use no colour of their own. An external destination opens in a new tab, as the panel's did. + +The admin option "Start page without navigation panel" is no longer offered: with no panel anywhere there is nothing to switch. Neither the frontend nor the backend reads or writes it any more; a stored `start_page_without_navigation` row stays unread (admin-settings REQ-ASET-001). + +**Why.** Ruben's review of 22 Nov 2026: the left panel makes no sense for LaunchPad, and the board grid should have the full width. The drawn boards (`launchpad/LpVandaag`, `launchpad/LpStore` and the others) draw no side bar and a Meer button in the top row. + +#### Scenario: No route renders the panel +- GIVEN a member opens LaunchPad +- WHEN they visit the dashboard view, the Marketplace, Reports, Flows or an admin page +- THEN no navigation panel MUST be rendered and the content MUST take the full width + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-009 + +#### Scenario: The dashboard view carries its destinations in More +- GIVEN a member with an active dashboard +- WHEN they open More +- THEN the menu MUST offer, under Settings, Documentation, Marketplace, Reports, Flows, Features & roadmap and the personal settings, beside the dashboards + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-009 + +#### Scenario: Another page carries More at its top +- GIVEN a member on the Marketplace page +- WHEN the page renders +- THEN the More menu MUST be at the top end of the content, and its Dashboards group MUST lead back to the dashboard view + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-009 + +#### Scenario: No destination is lost +- GIVEN the app's manifest +- WHEN the menu is built for a member and for an administrator +- THEN every entry the panel would have shown MUST have a destination in the menu, and every router destination MUST be a page the app declares + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-009 + +### Requirement: REQ-SHELL-013 One More menu, the same on every page + +The page header MUST carry one control: More. There MUST be no "Startpagina aanpassen" button, no Menu button, no Edit button and no "Add widget" button in the header; editing starts from More, and the edit bar (dashboards REQ-DASH-038) carries the edit actions. + +More MUST be the same menu on every page (board `launchpad/LpMeer`): on the start page, on any dashboard, in the empty state and on every other page. It is a popover of 600 px with two columns: the left column holds only Dashboards, the right column This dashboard and below it Settings. Below 960 px it is one column in the order Dashboards, This dashboard, Settings. Off the dashboard view there is no This dashboard group and Settings stands alone in the right column: + +- **Dashboards** (left): the person's own dashboards, then the shared and group ones, at most eight, as radio items (`role="menuitemradio"`) with the open one checked and highlighted, and the markers default, shared and group. Then "All dashboards". Off the dashboard view no dashboard is checked, and choosing one opens it on the dashboard view. +- **Settings** (right, at the bottom, below This dashboard's Delete and behind the same top rule): ONE menu item with a cog and a chevron, `aria-haspopup="true"` and `aria-expanded`. It starts folded each time the menu opens and unfolds in place as an indented group with a 2 px rule at its start: Personal settings, Admin settings (administrators only), Marketplace, Templates, Reports, Flows, Integrations, Documentation, Features and roadmap (nl Persoonlijke instellingen, Beheerinstellingen, Marktplaats, Sjablonen, Rapporten, Flows, Koppelingen, Documentatie, Functies en roadmap), unfolding below it in the right column. An entry the board does not name follows at the end. +- **This dashboard** (right, only where a dashboard is open): Edit, Add widget, Sharing, Copy link to this dashboard, Duplicate as new dashboard, Set as default, and Delete last, in the error colour behind a rule. Each item keeps its rule: Edit and Add widget need edit rights, Sharing and Delete need ownership, Duplicate needs personal dashboards to be allowed and the quota not reached. Read receipts, for an editor of a dashboard that asks readers to confirm, sits before Delete. + +More MUST NOT offer Versions (a tab of the dashboard settings, REQ-DASH-039), Schedule or Unpublish (the Publication tab), or a second Settings item under This dashboard; the dashboard settings open from the edit bar. + +The menu is a WAI-ARIA menu: the arrow keys move through every visible item over both columns in the visual order (Dashboards, This dashboard, Settings and its unfolded group), Home and End jump to the first and last, Right unfolds Settings and Left folds it, and Escape closes the menu and returns focus to More. + +**Why.** Ruben's decision of 22 Nov 2026, drawn on boards LpMeer and LpBewerken (design-system #1193, #1194): one menu, identical everywhere, for the English demo film. Ruben's decision of 23 Nov 2026 moved Settings from the left column, under Dashboards, to the bottom of the right column, so the left column lists only dashboards. + +#### Scenario: The header carries only More +- GIVEN a member on the start page +- WHEN the page renders +- THEN the only control at the top MUST be More, with no "Startpagina aanpassen", Menu, Edit or Add widget button + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-013 + +#### Scenario: Settings unfolds in place +- GIVEN a member with More open +- WHEN they choose Settings +- THEN Settings, at the bottom of the right column below Delete, MUST report `aria-expanded="true"` and its destinations MUST show indented below it in that column, while the menu stays open + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-013 + +#### Scenario: This dashboard ends in Delete +- GIVEN the owner of the open dashboard with More open +- WHEN they read This dashboard +- THEN it MUST list Edit, Add widget, Sharing, Copy link to this dashboard, Duplicate as new dashboard, Set as default and Delete, in that order, and no Versions or Settings item + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-013 + +#### Scenario: Escape returns focus to More +- GIVEN a member moving through More with the arrow keys +- WHEN they press Escape +- THEN the menu MUST close and focus MUST be on More + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-013 + +### Requirement: REQ-SHELL-010 First-visit tour + +LaunchPad MUST declare one guided tour in `src/manifest.json` (`walkthrough`), and the shell MUST hand that manifest to the shared library's `CnAppRoot` (`src/App.vue`), which draws the tour with `CnWalkthrough`. The tour SHALL be `launchpad:getting-started`, titled "Getting started", triggered on a user's first visit, with two steps in this order, both pointing at the More menu (`launchpad-more-menu`): + +1. As board LpEersteKeer draws step 1: the title "Here you switch between dashboards" (nl "Hier wisselt u tussen dashboards") and the body "Your own dashboards, what colleagues share with you and the organisation's group dashboards are under More, next to the marketplace and the settings. Pick one to open it." (nl "Uw eigen dashboards, wat collega's met u delen en de groepsdashboards van de organisatie staan onder Meer, naast de marktplaats en de instellingen. Kies er een om hem te openen."). It moves on with Next. +2. "Reports and Flows are under More as well.", which asks the user to open Flows from More, moves on when the Flows route matches and may be skipped. + +The More menu is the target with or without an active dashboard: `DashboardMoreMenu` carries `data-testid="launchpad-more-menu"` and the empty state's `StartPageMenu` carries `data-walkthrough-id="launchpad-more-menu"`. With no navigation panel (REQ-SHELL-009) the tour has no menu items to point at. Completion MUST be stored per user under `walkthrough_completed_version` against the declared tour `version` (2), so raising the version shows the tour again. The version went from 1 to 2 when the tour moved from the side bar to More, so a person who finished the old tour sees the new one once. Drawing, dimming, skipping and reopening the tour belong to the library; this requirement covers only what LaunchPad declares. + +Written on 2026-10-07 after the fact, from the code on `development`; covers parity row `d-tour`. The tour does not visit the admin settings. + +#### Scenario: A first visit starts the tour +- GIVEN Pieter has never completed the LaunchPad tour +- WHEN he opens LaunchPad +- THEN step 1, "Here you switch between dashboards", MUST open on the Workspace page + +#### Scenario: The tour points at More +- GIVEN the tour shows step 1 +- WHEN Pieter reads it +- THEN the step MUST ring the More menu, not the centre of the page, and say the dashboards are under More + +#### Scenario: Opening Flows from More ends the tour +- GIVEN the tour shows the Flows step +- WHEN Pieter opens Flows from More and the Flows route matches +- THEN the tour MUST end + +#### Scenario: A finished tour stays closed +- GIVEN Pieter completed tour version 2 +- WHEN he opens LaunchPad again +- THEN the tour MUST NOT start + +### Requirement: The admin area has its own first-visit tour (REQ-SHELL-011) + +LaunchPad MUST declare a second guided tour, `launchpad:admin-getting-started`, for the LaunchPad admin settings page. It MUST start on an administrator's first visit to that page and walk through six stops, in this order, as board LpBeheerAlgemeen draws it ("Rondleiding door het beheer, stap 1 van 6"): the tabs General ("Algemeen"), Templates ("Sjablonen"), Roles and rights ("Rollen en rechten"), Sharing ("Delen"), Kiosk and Demo data ("Demogegevens"). Each stop MUST name its tab and say in one line what is set there; the first stop MUST say the tour is shown once. Each stop MUST offer Skip and Next. Completion MUST be stored per user like the Workspace tour (REQ-SHELL-010). A person who is not an administrator never sees it. + +#### Scenario: An administrator's first visit to the admin page + +- **GIVEN** Noor is a Nextcloud administrator who never opened the LaunchPad admin page +- **WHEN** she opens it +- **THEN** the admin tour starts on the General tab with "step 1 of 6" + +#### Scenario: The tour visits the six tabs in order + +- **GIVEN** Noor is on the first stop of the admin tour +- **WHEN** she chooses Next five times +- **THEN** the tour has visited General, Templates, Roles and rights, Sharing, Kiosk and Demo data, in that order + +#### Scenario: A finished admin tour stays closed + +- **GIVEN** Noor completed the admin tour +- **WHEN** she opens the admin page again +- **THEN** the admin tour does not start + +### Requirement: The board grid sits on the page ground (REQ-SHELL-012) + +LaunchPad MUST draw its pages on the page ground, not on the white content panel. `App.vue` passes `pageGround` to `CnAppRoot`, which paints the content area with the NL Design System content-surface token (`--nldesign-component-content-surface-background-color`), falling back to Nextcloud's `--color-background-hover`, in light and dark mode alike. Widgets keep their own surfaces (`.grid-stack-item-content` and the widget wrappers). LaunchPad adds no colour of its own for this. + +**Why.** Ruben's review of 22 Nov 2026: the grid sat on a white card. The drawn boards (`launchpad/LpVandaag`, `launchpad/LpWerkplek`) put the grid on the page ground with white widget cards. + +#### Scenario: The grid on the page ground +- GIVEN a member opens a dashboard +- WHEN the page renders +- THEN the content area MUST carry the page ground token, not the main background, and each widget MUST keep its own surface + +@e2e openspec/specs/runtime-shell/spec.md#req-shell-012 + +### Requirement: The page header holds only launchpad's own actions (REQ-SHELL-NOBQ) + +Launchpad's pages SHALL NOT show the Buildiq in-app edit button, also where Buildiq is enabled. The manifest SHALL set +`openbuildEditable: false`. + +#### Scenario: Buildiq is enabled + +- **GIVEN** an instance with Buildiq enabled +- **WHEN** a person opens a launchpad dashboard +- **THEN** the page header shows no Buildiq edit button diff --git a/openspec/specs/scheduled-exports/spec.md b/openspec/specs/scheduled-exports/spec.md new file mode 100644 index 000000000..d04c1e249 --- /dev/null +++ b/openspec/specs/scheduled-exports/spec.md @@ -0,0 +1,231 @@ +# scheduled-exports Specification + +## Purpose +LaunchPad renders dashboards on a schedule (PDF, PNG, CSV, XLSX) and delivers them to recipients by email, Files, webhook or SFTP, with a per-recipient filter context, retries for failed deliveries, an audit trail per run and retention for artefacts and run records. + +## Requirements + + +### Requirement: REQ-SCH-001 Recurrence editor produces deterministic next-run timestamps + +The system MUST compute `nextRunAt` from `recurrence` and `runTimezone` deterministically, honouring DST transitions and leap-day edge cases, and MUST recompute `nextRunAt` after every fire. + +#### Scenario: Weekly recurrence falls on the correct date + +- GIVEN a `weekly` recurrence with `daysOfWeek=[Monday]`, `timeOfDay=09:00`, `runTimezone=Europe/Amsterdam` +- WHEN `nextRunAt` is computed on a Friday at 12:00 local time +- THEN `nextRunAt` SHALL be the upcoming Monday at 09:00 Europe/Amsterdam + +#### Scenario: Monthly recurrence on day 31 clamps to last day + +- GIVEN a `monthly` recurrence with `dayOfMonth=31`, `timeOfDay=08:00` +- WHEN the current month is February +- THEN `nextRunAt` SHALL fall on the last day of February at 08:00 (clamped, not skipped) + +#### Scenario: Cron expression across spring DST transition + +- GIVEN a `cron` recurrence `0 9 * * 1` evaluated across the spring DST transition +- WHEN the Monday-at-09:00 fire would land in the missing hour +- THEN the fire SHALL occur at 09:00 local time (post-transition wall-clock), not 08:00 or 10:00 UTC-offset-equivalent + +### Requirement: REQ-SCH-002 Background runner fires schedules without an active browser session + +The system MUST evaluate `scheduled_export` rows from a Nextcloud background job, render and dispatch independently of any logged-in user, and MUST execute renders under the export's `createdBy` identity for ACL purposes. + +#### Scenario: Background job fires and updates timestamps + +- GIVEN an enabled export with `nextRunAt` in the past +- WHEN the background job runs +- THEN the runner SHALL invoke render, dispatch, and update `lastRunAt`, `lastRunStatus`, and `nextRunAt` + +#### Scenario: Disabled creator blocks the run + +- GIVEN an enabled export whose `createdBy` user has been disabled +- WHEN the background job runs +- THEN the run SHALL be skipped, `lastRunStatus` SHALL be set to `failed`, and an admin notification SHALL be queued + +#### Scenario: Overlap prevention — no concurrent runs + +- GIVEN an export whose previous run is still `running` past its expected runtime +- WHEN the next fire window arrives +- THEN the new fire SHALL be skipped (no overlap) and a `partial` run-row SHALL record the skip reason + +### Requirement: REQ-SCH-003 Multi-format render from a single fire + +The system MUST render the configured `subjectId` once per `render_target` and MUST produce PDF, PNG, CSV, and XLSX outputs that match the on-screen rendering for the same filter context. + +#### Scenario: Three render targets produce three artefacts + +- GIVEN an export with `subjectType=dashboard`, three render targets (`pdf`, `png`, `xlsx`) +- WHEN the runner fires +- THEN three artefacts SHALL be produced with distinct sha256s, all referencing the same `correlationId` + +#### Scenario: CSV of a chart widget contains tabular data + +- GIVEN a `csv` render target on a `subjectType=widget` export where the widget is a chart +- WHEN the runner fires +- THEN the CSV SHALL contain the chart's underlying tabular data (headers + rows), not a rasterised representation + +#### Scenario: XLSX with per-widget sheets + +- GIVEN an `xlsx` render target on a dashboard with five widgets and `sheetPerWidget=true` +- WHEN the runner fires +- THEN the resulting workbook SHALL have five sheets named after each widget plus a cover sheet with the export name and run timestamp + +### Requirement: REQ-SCH-004 Per-recipient filter context + +The system MUST apply each recipient's `filterContext` (if set) before rendering for that recipient, producing recipient-specific artefacts, and MUST share render output across recipients whose filter contexts are identical. + +#### Scenario: Two recipients with identical filter contexts share one render + +- GIVEN an export with two recipients, both with `filterContext={gemeenteCode: "GM0355"}` +- WHEN the runner fires +- THEN a single render SHALL be produced and SHALL be delivered to both recipients + +#### Scenario: Two recipients with distinct filter contexts produce two renders + +- GIVEN an export with two recipients with `filterContext={gemeenteCode: "GM0355"}` and `{gemeenteCode: "GM0344"}` respectively +- WHEN the runner fires +- THEN two renders SHALL be produced, each filtered to its respective gemeente, and the audit row SHALL list both artefacts + +#### Scenario: Invalid filter context fails gracefully + +- GIVEN a recipient with a `filterContext` that the subject's data source cannot satisfy (e.g. unknown field) +- WHEN the runner attempts to render for that recipient +- THEN that recipient's delivery SHALL be marked `failed` with a validation error and OTHER recipients SHALL still be processed + +### Requirement: REQ-SCH-005 Email, Nextcloud Files, webhook, and SFTP delivery channels + +The system MUST deliver render artefacts through the configured channel, using the Nextcloud mailer for `email`, writing into the user's Files area for `nextcloudFiles`, POSTing a signed multipart payload for `webhook`, and uploading via SFTP for `sftp`. + +#### Scenario: Email delivery attaches PDF to recipients + +- GIVEN a recipient with `channel=email`, three addresses, and a PDF render target +- WHEN delivery runs +- THEN one email SHALL be sent with the PDF attached and all three addresses on the To: header, and the delivery row SHALL record the mailer's message-id + +#### Scenario: Nextcloud Files delivery respects overwrite setting + +- GIVEN a recipient with `channel=nextcloudFiles`, `channelConfig.targetPath="/Reports/Weekly"`, and a CSV render target +- WHEN delivery runs +- THEN the CSV SHALL be written to `/Reports/Weekly/{filenamePattern}` in the recipient user's Files area, overwriting any existing file with the same name only if `overwrite=true` is set in `channelConfig` + +#### Scenario: SFTP delivery with host-key verification + +- GIVEN a recipient with `channel=sftp` and a valid `channelConfig` (host, port, username, key-or-password, remote path) +- WHEN delivery runs +- THEN the artefact SHALL be uploaded to the remote path and the delivery row SHALL record the SFTP server's post-upload size confirmation + +### Requirement: REQ-SCH-006 Retry with exponential backoff and dead-letter + +The system MUST retry failed deliveries with exponential backoff up to `retryPolicy.maxAttempts` and MUST move permanently-failed deliveries into a dead-letter state that surfaces in the UI and triggers an admin notification. + +#### Scenario: Webhook retry with exponential backoff + +- GIVEN a webhook recipient whose first delivery returns HTTP 503 +- WHEN the runner schedules the retry +- THEN the retry SHALL be attempted after `initialBackoffSeconds` (with optional jitter) and SHALL double on each subsequent failure up to `maxBackoffSeconds` + +#### Scenario: Dead-letter after max retries exhausted + +- GIVEN a recipient whose retries all fail +- WHEN `maxAttempts` is reached +- THEN the delivery SHALL be marked `failed-permanent`, an admin notification SHALL be sent, and a "Retry" action SHALL be available in the run-detail UI + +#### Scenario: Recovery from transient failure + +- GIVEN a recipient with a temporary failure that succeeds on attempt three +- WHEN the third attempt returns 200 +- THEN `attemptCount` SHALL be 3, `status` SHALL be `success`, and the run-row SHALL roll up to `success` (not `partial`) if all other deliveries also succeeded + +### Requirement: REQ-SCH-007 Retention policy enforced by janitor + +The system MUST delete render artefacts after `retention.keepArtefactsForDays` days and MUST delete run-rows after `retention.keepAuditForDays` days, except where the export is explicitly configured to keep artefacts forever. + +#### Scenario: Artefacts expire; audit metadata retained + +- GIVEN an export with `retention.keepArtefactsForDays=14` and a run-row from 20 days ago +- WHEN the janitor runs +- THEN the artefact files SHALL be deleted from the Files area and the run-row's `renderArtefacts[].storagePath` SHALL be nulled while the audit metadata SHALL be retained + +#### Scenario: Null retention means forever + +- GIVEN an export with `retention.keepArtefactsForDays=null` +- WHEN the janitor runs +- THEN no artefact SHALL be deleted regardless of age + +#### Scenario: Audit rows expire and are purged + +- GIVEN a run-row older than `retention.keepAuditForDays` +- WHEN the janitor runs +- THEN the run-row SHALL be deleted (and any remaining artefact files purged together with it) + +### Requirement: REQ-SCH-008 Audit row per run with hash and delivery outcome + +The system MUST persist a `scheduled_export_run` row for every fire (manual or scheduled) capturing the render artefact hashes, the delivery outcomes per recipient including provider message ids, retry counts, and any error bodies. + +#### Scenario: Successful run with one PDF and two recipients + +- GIVEN a fire that produces one PDF artefact and dispatches to two recipients successfully +- WHEN the run completes +- THEN the run-row SHALL contain one entry in `renderArtefacts` (with non-empty `sha256`) and two entries in `deliveries` each with `status=success` and a non-null `providerMessageId` + +#### Scenario: Partial run with one failed delivery + +- GIVEN a fire where one of two recipients fails permanently +- WHEN the run completes +- THEN the run-row SHALL have `status=partial` and the failed delivery entry SHALL include `attemptCount`, the final `error` body, and `status=failed-permanent` + +### Requirement: REQ-SCH-009 Manual "Run now" and "Preview" actions + +The system MUST allow a user with edit permission on the export to trigger an immediate run (which writes a run-row with `triggeredBy=manual`) and to preview the rendered output for a chosen recipient without dispatching. + +#### Scenario: Manual run with user tracking + +- GIVEN a user with edit permission on export E +- WHEN they invoke "Run now" +- THEN the runner SHALL execute E immediately, the run-row SHALL record `triggeredBy=manual` and `triggeredByUser=<user>`, and the next scheduled fire SHALL not be affected + +#### Scenario: Preview without dispatch + +- GIVEN the same user invokes "Preview" for recipient R +- WHEN the preview runs +- THEN the render SHALL be returned in the response (or streamed for binary formats) and NO delivery SHALL be attempted and NO run-row SHALL be written + +### Requirement: REQ-SCH-010 Header signing and credential vaulting + +The system MUST HMAC-SHA256-sign webhook payloads with a per-recipient secret in the `X-LaunchPad-Signature` header, MUST store SFTP credentials encrypted at rest, and MUST route webhook/SFTP credentials through OpenConnector when `openconnectorSourceId` is set on the recipient. + +#### Scenario: Webhook payload is signed + +- GIVEN a webhook recipient with `channelConfig.signingSecret` set +- WHEN a payload is dispatched +- THEN the request SHALL include `X-LaunchPad-Signature: sha256=<hex>` computed over the body using the secret + +#### Scenario: SFTP credentials are redacted on read + +- GIVEN an SFTP recipient persisted via the API +- WHEN the channel is read back +- THEN the password/keymaterial SHALL be returned as a redacted placeholder (`********`) and the original value SHALL be retrievable only by the dispatcher + +#### Scenario: Credentials routed through OpenConnector + +- GIVEN a recipient with `openconnectorSourceId=S` +- WHEN delivery runs +- THEN the dispatch SHALL be issued through OpenConnector source S (so the credential lives in the OC vault and the dispatch appears in the OC call-log) instead of using launchpad-local credentials + +### Requirement: REQ-SCH-011 Scheduled exports live in the dashboard settings + +The scheduled exports of a dashboard MUST be managed from an "Exports" tab in that dashboard's settings ("Dashboard configuration", board LpDashboardInstellingen), next to the "Publication" tab, and NOT from a separate entry in the "Meer" menu or the dashboard row menu (Ruben, 22 Nov 2026). The tab MUST list only the exports whose subject is this dashboard or one of its widgets, with name, contents, next run and last run, and MUST offer "New scheduled export", Edit, Run now, Preview, View runs and Delete. A new export MUST start with this dashboard as its subject, and the editor MUST offer only this dashboard and its widgets as subjects. + +#### Scenario: The Exports tab lists this dashboard's exports + +- GIVEN a user with two exports of dashboard D and one export of dashboard E +- WHEN they open the settings of D and choose the "Exports" tab +- THEN the tab SHALL list the two exports of D and not the export of E + +#### Scenario: The Meer menu no longer offers scheduled exports + +- GIVEN a user who may edit dashboard D +- WHEN they open the "Meer" menu +- THEN it SHALL NOT offer "Scheduled exports…", and "Settings" SHALL lead to the "Exports" tab diff --git a/openspec/specs/service-health-ping/screens.md b/openspec/specs/service-health-ping/screens.md new file mode 100644 index 000000000..ae2025be1 --- /dev/null +++ b/openspec/specs/service-health-ping/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpTegelBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpTegelBewerken diff --git a/openspec/specs/service-health-ping/spec.md b/openspec/specs/service-health-ping/spec.md index 4cba0935b..45b7c32ca 100644 --- a/openspec/specs/service-health-ping/spec.md +++ b/openspec/specs/service-health-ping/spec.md @@ -1,7 +1,7 @@ # service-health-ping Specification ## Purpose -TBD - created by archiving change service-health-ping. Update Purpose after archive. +An optional online, degraded or offline badge on a tile, so a landing page shows at a glance whether the service behind a link answers. The server pings an allow-listed health URL, classifies and caches the result, and the tile renders the badge from that cache. ## Requirements ### Requirement: REQ-HPING-001 Configure a health ping on a tile @@ -27,6 +27,8 @@ The system MUST let a dashboard author enable a health ping on a tile and store The system MUST perform the health request on the server via `IClientService` and classify the outcome as online, degraded or offline. It MUST NOT perform the request from the browser. +A ping that times out, fails to connect, or answers with a status that does not match `expectedStatus` is a failed ping. A failed ping MUST NOT classify the badge `offline` at once: it MUST keep the last-known badge and mark it stale. Only after the configured number of consecutive failed pings (app config `healthping_offline_after_failures`, default 3, at least 1) MUST the badge be classified `offline`. A successful ping MUST reset the count. + #### Scenario: Online when status matches within latency threshold - GIVEN a ping-enabled tile with `expectedStatus` 200 and a latency threshold - WHEN the server request returns 200 within the threshold @@ -37,10 +39,18 @@ The system MUST perform the health request on the server via `IClientService` an - WHEN the response latency exceeds the configured threshold - THEN the badge state MUST be classified `degraded` -#### Scenario: Offline on failure or unexpected status -- GIVEN a ping-enabled tile -- WHEN the request times out, the connection fails, or the status does not match `expectedStatus` -- THEN the badge state MUST be classified `offline` +#### Scenario: A failed ping marks the badge stale +- GIVEN a ping-enabled tile whose last ping read `online`, and `healthping_offline_after_failures` at its default of 3 +- WHEN the next ping times out, the connection fails, or the status does not match `expectedStatus` +- THEN the badge MUST keep the last-known state `online` and its check time +- AND it MUST be marked `stale = true`, not classified `offline` +- AND without a last-known reading the badge MUST have no state yet (`state = null`, `stale = true`) + +#### Scenario: Offline after consecutive failed pings +- GIVEN a ping-enabled tile and `healthping_offline_after_failures` set to N +- WHEN N consecutive pings fail (timeout, connection failure, or a status that does not match `expectedStatus`) +- THEN the badge state MUST be classified `offline` with `stale = false` +- AND a successful ping in between MUST reset the count, so a later failed ping marks the badge stale again #### Scenario: Allow-list enforced at ping time (fail closed) - GIVEN a tile whose `healthUrl` host was removed from `healthping_allowed_hosts` after configuration @@ -55,7 +65,7 @@ The system MUST cache the badge state in `ICache` with a short TTL and MUST refr #### Scenario: Endpoint serves the cached badge - GIVEN a ping-enabled placement the current user may view - WHEN the tile calls `GET /api/health-ping/{placementId}` -- THEN the response MUST be `{ state, checkedAt, latencyMs, stale }` +- THEN the response MUST be `{ state, checkedAt, latencyMs, stale, downSince }`, where `downSince` is the time of the first failed check of the current run of failures while `state` is `offline`, and null otherwise (icon-only-app-tiles REQ-ICT-003) - AND the response MUST NOT contain the health URL, request headers, or upstream response body #### Scenario: Caller authorization @@ -74,9 +84,10 @@ The system MUST cache the badge state in `ICache` with a short TTL and MUST refr - THEN it MUST refresh only the due, ping-enabled placements and skip any whose host is not allow-listed #### Scenario: Stale fallback on refresh failure -- GIVEN a previously cached badge exists -- WHEN a refresh fails to reach the upstream +- GIVEN a previously cached badge exists and its interval has passed +- WHEN a refresh fails to reach the upstream, fewer times in a row than `healthping_offline_after_failures` - THEN the endpoint MUST return the last-known badge with `stale = true` and the tile MUST NOT crash +- AND the cache MUST keep the last-known badge beyond the ping interval, so the interval decides when the next ping is due, not whether the badge survives ### Requirement: REQ-HPING-004 Render an accessible health badge on the tile diff --git a/openspec/specs/setup-wizard/screens.md b/openspec/specs/setup-wizard/screens.md new file mode 100644 index 000000000..5402d8760 --- /dev/null +++ b/openspec/specs/setup-wizard/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpInstellen https://identity.conduction.nl/screens/board?id=launchpad/LpInstellen diff --git a/openspec/specs/setup-wizard/spec.md b/openspec/specs/setup-wizard/spec.md index 278650eef..ea5e0b467 100644 --- a/openspec/specs/setup-wizard/spec.md +++ b/openspec/specs/setup-wizard/spec.md @@ -6,7 +6,7 @@ status: done ## Purpose -The Setup Wizard is a multi-step first-run configuration flow for freshly installed LaunchPad instances. It guides administrators through selecting a storage backend, setting group priority order, installing optional demo data, assigning admin roles, and configuring footer content. The wizard detects first-run state via an admin-setting flag, supports both interactive and non-interactive (CLI) flows, and ensures all choices are persisted immediately so progress is not lost. +The Setup Wizard is a multi-step first-run configuration flow for freshly installed LaunchPad instances. It guides administrators through setting group priority order, installing optional demo data, assigning admin roles, and configuring footer content. The wizard detects first-run state via an admin-setting flag, supports both interactive and non-interactive (CLI) flows, and ensures all choices are persisted immediately so progress is not lost. ## Data Model @@ -16,17 +16,14 @@ The setup wizard does not define a new persistent table; it tracks state via exi Wizard progress (per-step completion status) is derived heuristically from the state of underlying settings: - Step 1 (Welcome): always "done" (no choice to persist) -- Step 2 (Storage): "done" if `launchpad.content_storage` is set; "pending" otherwise -- Step 3 (Group order): "done" if `launchpad.group_priority_order` is set; "pending" otherwise -- Step 4 (Demo data): "done" if at least one demo package has been installed; "pending" otherwise -- Step 5 (Admin roles): "skipped" if not visited; "done" if a "Dashboard Admin" role assignment exists -- Step 6 (Footer): "skipped" if not visited; "done" if `launchpad.footer_config` is set -- Step 7 (Done): "pending" until wizard completes - -## Requirements +- Step 2 (Group order): "done" if `launchpad.group_priority_order` is set; "pending" otherwise +- Step 3 (Demo data): "done" if at least one demo package has been installed; "pending" otherwise +- Step 4 (Admin roles): "done" if a LaunchPad admin role assignment exists; "skipped" once the wizard is finished without one; "pending" otherwise +- Step 5 (Done): "pending" until wizard completes (REQ-WIZ-012: five steps; the footer is set on its own admin tab) +The storage step that sat at Step 2 was retired on 9 Oct 2026 (decision 131, change `retire-setup-wizard-storage-step`). A `content_storage` row it wrote stays in the table and is never read. -@e2e exclude all scenarios test PHP wizard endpoint + flag persistence — wizard is a first-run flow that auto-completes on existing instances; cannot be reliably reproduced +## Requirements ### Requirement: REQ-WIZ-001 Detect First-Run State via Admin Setting Flag @@ -49,7 +46,7 @@ The system MUST detect whether a LaunchPad instance is being initialized for the #### Scenario: Banner includes descriptive text - GIVEN a fresh LaunchPad instance showing the setup banner - WHEN the admin views the banner -- THEN the banner MUST include text explaining: "Get your intranet started: choose storage, configure groups, install demo data, and set up admin roles." +- THEN the banner MUST include text explaining: "Get your intranet started: configure groups, install demo data, and set up admin roles." - NOTE: Banner style and wording are implementation-specific; requirement mandates presence and visibility only #### Scenario: Banner has explicit "Run setup wizard" call-to-action @@ -62,228 +59,103 @@ The system MUST detect whether a LaunchPad instance is being initialized for the - WHEN the admin returns to `/apps/launchpad/admin/dashboards` - THEN if `launchpad.setup_wizard_complete = false`, the banner MUST reappear -### Requirement: REQ-WIZ-002 Multi-Step Wizard Flow with 7 Steps - -The wizard MUST guide the admin through a linear, skippable sequence of 7 steps, each with Skip / Back / Next buttons. Only the "Finish" button on Step 7 marks the wizard complete. - -> NOTE: Steps 2–6 each embed the canonical admin UI component from the corresponding sibling capability (`groupfolder-storage-backend`, `group-priority-order`, `demo-data-showcases`, `admin-roles`, `footer-customization`). The wizard is a thin orchestrator — it owns step sequencing and the completion flag; each sibling capability owns its own settings persistence. No settings surfaces are duplicated. - -#### Scenario: Wizard starts at Step 1 -- GIVEN the banner's "Run setup wizard" button is clicked -- WHEN the wizard modal opens -- THEN Step 1 (Welcome / Overview) MUST be displayed -- AND the step counter MUST show "1 / 7" - -#### Scenario: Next button advances to next step -- GIVEN the wizard is on Step 1 -- WHEN the admin clicks "Next" -- THEN the wizard advances to Step 2 (Storage backend) -- AND the step counter MUST show "2 / 7" -- AND the Back button MUST become active - -#### Scenario: Back button returns to previous step -- GIVEN the wizard is on Step 3 -- WHEN the admin clicks "Back" -- THEN the wizard returns to Step 2 -- AND no data loss occurs (Step 3 values are preserved if re-visited) +### Requirement: REQ-WIZ-004 Step 2 — Group Priority Order (Embedded Component Reuse) -#### Scenario: Skip button jumps to next step without commitment -- GIVEN the wizard is on Step 5 (Admin roles, optional) -- WHEN the admin clicks "Skip" -- THEN the wizard advances to Step 6 -- AND the wizard completion status for Step 5 is marked "skipped" (not "done") -- NOTE: Skipping a step does not prevent the wizard from eventually marking complete +Step 2 MUST embed the existing `group-priority-order` admin UI component, allowing the admin to configure the priority order of Nextcloud groups for dashboard routing. -#### Scenario: Step 1 has no form; only explanatory text -- GIVEN Step 1 (Welcome) is displayed -- WHEN the admin views the step -- THEN the step MUST show text explaining the wizard's purpose: "Configure your LaunchPad instance with storage, group ordering, demo data, admin roles, and footer settings." -- AND there are no form fields to fill -- AND clicking "Next" advances without persisting any choice - -#### Scenario: Step 7 shows summary and Finish button -- GIVEN the wizard reaches Step 7 (Done) -- WHEN the admin views the step -- THEN the step MUST display a summary: "Your setup is complete. Click Finish to save changes and dismiss the setup banner." -- AND a "Finish" button (not "Next") MUST be present -- AND clicking "Finish" executes the completion action - -#### Scenario: Finish button completes wizard -- GIVEN the admin is on Step 7 with the "Finish" button visible -- WHEN the admin clicks "Finish" -- THEN the system MUST set `launchpad.setup_wizard_complete = true` -- AND the wizard modal MUST close -- AND the admin section MUST reload, banner gone - -#### Scenario: Wizard progress persists across Back navigation -- GIVEN the wizard is on Step 3 with group order selected -- WHEN the admin clicks Back to Step 2, modifies storage backend, then clicks Next to Step 3 -- THEN the group order selection from Step 3 MUST still be present (no data loss) - -### Requirement: REQ-WIZ-003 Step 2 — Storage Backend Choice with GroupFolder Dependency Tooltip - -Step 2 MUST present two radio options: "Database (default)" and "GroupFolder (recommended for org use)". The GroupFolder option MUST be disabled with a tooltip if the `groupfolders` Nextcloud app is not installed. - -#### Scenario: Storage backend selection shows two options +#### Scenario: Step 2 embeds existing group-priority-order admin component - GIVEN Step 2 is displayed - WHEN the admin views the step -- THEN two radio buttons MUST be visible: - - "Database (default)" — with description "Store dashboard content in LaunchPad database table" - - "GroupFolder (recommended for org use)" — with description "Store dashboard content in Nextcloud GroupFolders for collaborative access" -- AND exactly one option MUST be pre-selected (default to "Database") - -#### Scenario: GroupFolder option disabled if app not installed -- GIVEN the `groupfolders` Nextcloud app is NOT installed -- WHEN Step 2 is displayed -- THEN the "GroupFolder" radio option MUST be disabled (grayed out) -- AND a tooltip MUST appear on hover: "GroupFolder app is not installed. Install 'Nextcloud GroupFolders' to use this option." -- NOTE: Disabled state prevents selection; tooltip explains why - -#### Scenario: GroupFolder option enabled if app installed -- GIVEN the `groupfolders` Nextcloud app IS installed -- WHEN Step 2 is displayed -- THEN the "GroupFolder" radio option MUST be enabled -- AND the option is selectable - -#### Scenario: Storage choice persists immediately -- GIVEN Step 2 is displayed with "Database" selected -- WHEN the admin selects "GroupFolder" and clicks Next -- THEN the system MUST immediately write `launchpad.content_storage = "groupfolder"` to admin settings -- AND if the admin navigates away (Back, Browser close, etc.), the choice MUST be persisted (not lost) - -#### Scenario: Default is Database -- GIVEN a fresh instance where no storage backend has been chosen -- WHEN Step 2 is displayed -- THEN "Database (default)" MUST be pre-selected -- NOTE: This reflects the safe, always-available default - -### Requirement: REQ-WIZ-004 Step 3 — Group Priority Order (Embedded Component Reuse) - -Step 3 MUST embed the existing `group-priority-order` admin UI component, allowing the admin to configure the priority order of Nextcloud groups for dashboard routing. - -#### Scenario: Step 3 embeds existing group-priority-order admin component -- GIVEN Step 3 is displayed -- WHEN the admin views the step - THEN the existing `group-priority-order` admin UI MUST be visible and functional within the wizard modal - NOTE: The component is not duplicated; the wizard embeds the canonical admin component #### Scenario: Group order choice persists immediately -- GIVEN the admin reorders groups in Step 3 (e.g., "engineering" moved above "sales") +- GIVEN the admin reorders groups in Step 2 (e.g., "engineering" moved above "sales") - WHEN the admin clicks Next - THEN the system MUST immediately persist the new order to `launchpad.group_priority_order` - AND navigating away does not lose the change -#### Scenario: Step 3 allows drag-and-drop reordering (existing UI behavior) +#### Scenario: Step 2 allows drag-and-drop reordering (existing UI behavior) - GIVEN the group-priority-order component is displayed - WHEN the admin drags a group to a new position - THEN the reorder MUST be reflected in the UI - NOTE: Exact interaction (drag, arrow buttons, etc.) is determined by the embedded component's design -### Requirement: REQ-WIZ-005 Step 4 — Demo Data Installation (Embedded Component Reuse) +### Requirement: REQ-WIZ-005 Step 3 — Demo Data Installation (Embedded Component Reuse) -Step 4 MUST embed the existing `demo-data-showcases` admin UI component, allowing the admin to optionally select and install demo packages. +Step 3 MUST embed the existing `demo-data-showcases` admin UI component, allowing the admin to optionally select and install demo packages. -#### Scenario: Step 4 embeds demo-data-showcases admin component -- GIVEN Step 4 is displayed +#### Scenario: Step 3 embeds demo-data-showcases admin component +- GIVEN Step 3 is displayed - WHEN the admin views the step - THEN the existing `demo-data-showcases` admin UI MUST be visible within the wizard modal - AND the component displays all available demo packages with checkboxes - NOTE: The component is the canonical admin UI; wizard embeds it without duplication #### Scenario: Demo data installation is optional -- GIVEN Step 4 is displayed with zero demo packages selected +- GIVEN Step 3 is displayed with zero demo packages selected - WHEN the admin clicks "Skip" or "Next" - THEN the wizard MUST advance without requiring any demo to be installed -- NOTE: Step 4 is not skippable via a Skip button; all steps are traversed. However, selecting zero demos and clicking Next is equivalent to skipping. +- NOTE: Step 3 is not skippable via a Skip button; all steps are traversed. However, selecting zero demos and clicking Next is equivalent to skipping. #### Scenario: Checked demos are installed on Next -- GIVEN the admin selects checkboxes for "Engineering Demo" and "Sales Demo" on Step 4 +- GIVEN the admin selects checkboxes for "Engineering Demo" and "Sales Demo" on Step 3 - WHEN the admin clicks "Next" - THEN the system MUST trigger the installation of both demo packages -- AND the wizard advances to Step 5 (installation happens asynchronously or blocks until done, implementation choice) +- AND the wizard advances to Step 4 (installation happens asynchronously or blocks until done, implementation choice) - NOTE: The demo-data-showcases component handles the actual installation logic #### Scenario: Demo selection is persisted -- GIVEN the admin selected "Engineering Demo" on Step 4 and advanced to Step 5 -- WHEN the admin navigates Back to Step 4 +- GIVEN the admin selected "Engineering Demo" on Step 3 and advanced to Step 4 +- WHEN the admin navigates Back to Step 3 - THEN the "Engineering Demo" checkbox MUST remain checked - AND no re-installation happens (idempotent) -### Requirement: REQ-WIZ-006 Step 5 — Admin Roles (Optional, Depends on admin-roles Capability) +### Requirement: REQ-WIZ-006 Step 4 — Admin Roles (Optional, Depends on admin-roles Capability) -Step 5 MUST allow the admin to optionally assign the "Dashboard Admin" role to one Nextcloud group. This step is skippable via a Skip button. +Step 4 MUST allow the admin to optionally assign the "Dashboard Admin" role to one Nextcloud group. This step is skippable via a Skip button. -#### Scenario: Step 5 shows group selector for admin role +#### Scenario: Step 4 shows group selector for admin role - GIVEN the `admin-roles` capability is available -- AND Step 5 is displayed +- AND Step 4 is displayed - WHEN the admin views the step - THEN a dropdown or multi-select MUST display all Nextcloud groups - AND a description MUST explain: "Assign 'Dashboard Admin' role to a group to delegate LaunchPad administration to group members." #### Scenario: Admin can select one group for Dashboard Admin role -- GIVEN Step 5 is displayed with groups ["engineering", "sales", "marketing"] +- GIVEN Step 4 is displayed with groups ["engineering", "sales", "marketing"] - WHEN the admin selects "engineering" - AND clicks "Next" - THEN the system MUST call `RoleService::assignRole(groupId="engineering", role="admin", assignedBy=<current-admin>)` - AND the role assignment MUST be created in `oc_launchpad_role_assignments` -#### Scenario: Step 5 is skippable -- GIVEN Step 5 is displayed +#### Scenario: Step 4 is skippable +- GIVEN Step 4 is displayed - WHEN the admin clicks "Skip" - THEN no role assignment is made -- AND the wizard advances to Step 6 -- AND the completion status for Step 5 MUST be marked "skipped" +- AND the wizard advances to Step 5 +- AND the completion status for Step 4 MUST be marked "skipped" #### Scenario: No group selected is equivalent to skip -- GIVEN Step 5 with no group selected +- GIVEN Step 4 with no group selected - WHEN the admin clicks "Next" - THEN no role assignment is made (equivalent to Skip) -- AND the wizard advances to Step 6 +- AND the wizard advances to Step 5 -#### Scenario: Step 5 unavailable if admin-roles capability missing +#### Scenario: Step 4 unavailable if admin-roles capability missing - GIVEN the `admin-roles` capability is NOT implemented or not available -- WHEN the wizard would display Step 5 -- THEN Step 5 MUST be skipped automatically -- AND the step counter jumps from Step 4 to Step 6 +- WHEN the wizard would display Step 4 +- THEN Step 4 MUST be skipped automatically +- AND the step counter jumps from Step 3 to Step 5 - NOTE: Capability dependency is gracefully handled; missing capability does not break wizard +@e2e exclude admin-roles ships inside LaunchPad, so the CI instance cannot be made to lack it; the auto-skip was never built (SetupWizardModal.vue always renders six steps with a Step 4 stub and has no capability check) and no unit test pins it #### Scenario: Only one group can have admin role per wizard run -- GIVEN Step 5 is displayed +- GIVEN Step 4 is displayed - WHEN the admin selects "engineering" and clicks "Next" - THEN only the "engineering" group receives the admin role (not multiple groups) - NOTE: If the admin wishes to assign admin role to multiple groups, they must run the wizard again or use the admin roles management UI directly -### Requirement: REQ-WIZ-007 Step 6 — Footer Configuration (Optional, Depends on footer-customization Capability) - -Step 6 MUST allow the admin to optionally open and configure the footer using the "Structured mode" editor. This step is skippable via a Skip button. - -#### Scenario: Step 6 shows footer editor -- GIVEN the `footer-customization` capability is available -- AND Step 6 is displayed -- WHEN the admin views the step -- THEN the "Structured mode" footer editor MUST be visible and functional -- AND a description MUST explain: "Customize the footer content and appearance for your intranet." - -#### Scenario: Footer edits persist immediately -- GIVEN the admin edits footer content in Step 6 -- WHEN the admin clicks "Next" -- THEN the footer configuration MUST be saved to `launchpad.footer_config` or equivalent setting -- AND navigating away does not lose the changes - -#### Scenario: Step 6 is skippable -- GIVEN Step 6 is displayed -- WHEN the admin clicks "Skip" -- THEN no footer changes are made -- AND the wizard advances to Step 7 -- AND the completion status for Step 6 MUST be marked "skipped" - -#### Scenario: Step 6 unavailable if footer-customization capability missing -- GIVEN the `footer-customization` capability is NOT implemented or not available -- WHEN the wizard would display Step 6 -- THEN Step 6 MUST be skipped automatically -- AND the step counter jumps from Step 5 to Step 7 -- NOTE: Capability dependency is gracefully handled; missing capability does not break wizard - ### Requirement: REQ-WIZ-008 Get Wizard State via API Endpoint The system MUST expose a `GET /api/admin/setup-wizard/state` endpoint that returns the wizard's completion status, current recommended step for re-runs, and per-step status. @@ -303,18 +175,16 @@ The system MUST expose a `GET /api/admin/setup-wizard/state` endpoint that retur "2": "pending", "3": "pending", "4": "pending", - "5": "pending", - "6": "pending", - "7": "pending" + "5": "pending" } } ``` -- NOTE: Step 1 is always "done" (no choice required). Steps 2–7 start "pending". +- NOTE: Step 1 is always "done" (no choice required). Steps 2–5 start "pending". #### Scenario: Endpoint returns recommended step for re-runs -- GIVEN a LaunchPad instance with storage backend set but group order not yet set +- GIVEN a LaunchPad instance where the group order is not yet set - WHEN an NC admin calls `GET /api/admin/setup-wizard/state` -- THEN the response MUST include `currentRecommendedStep: 3` +- THEN the response MUST include `currentRecommendedStep: 2` - NOTE: The heuristic picks the first step with status != "done" #### Scenario: Endpoint returns complete=true when wizard finished @@ -329,11 +199,18 @@ The system MUST expose a `GET /api/admin/setup-wizard/state` endpoint that retur - THEN the system MUST return HTTP 403 (Forbidden) #### Scenario: Endpoint includes skipped step status -- GIVEN the wizard has been run with Step 5 skipped +- GIVEN the wizard has been run with Step 4 skipped - WHEN an NC admin calls `GET /api/admin/setup-wizard/state` -- THEN the response MUST include `"5": "skipped"` in stepStatuses +- THEN the response MUST include `"4": "skipped"` in stepStatuses - NOTE: Skipped status indicates the step was traversed but no action taken; does not block wizard completion +#### Scenario: A stored storage choice from the retired step is ignored +- GIVEN an instance that still holds a `content_storage` row written by the retired storage step +- WHEN an NC admin calls `GET /api/admin/setup-wizard/state` +- THEN `stepStatuses` MUST hold exactly six entries +- AND the stored row MUST NOT change any step status or `currentRecommendedStep` +@e2e exclude no API can write the retired `content_storage` row (its endpoint is gone and AdminSettingKey has no such case), so the GIVEN cannot be seeded in e2e; pinned by tests/Unit/Service/SetupWizardServiceTest.php testAStoredContentStorageValueIsLeftUnread and testWizardHasSixStepsWithoutAStorageStep + ### Requirement: REQ-WIZ-009 Mark Wizard Complete via API Endpoint The system MUST expose a `POST /api/admin/setup-wizard/complete` endpoint that idempotently sets `launchpad.setup_wizard_complete = true` and returns the current wizard state. @@ -367,12 +244,11 @@ The system MUST expose a `POST /api/admin/setup-wizard/complete` endpoint that i The system MUST expose a CLI command `php occ launchpad:setup` that accepts a `--config=/path/setup.yaml` argument to perform wizard setup non-interactively, ideal for Infrastructure-as-Code deployments. -> NOTE: The YAML config schema (fields: `storage_backend`, `group_priority_order`, `demo_packages`, `admin_role_group`, `footer_config`) is formally defined in the `cli-commands` sibling spec. Optional steps (admin roles, footer) may be omitted from the config file entirely; omitting them is equivalent to skipping those steps in the wizard and does not cause an error. +> NOTE: The YAML config schema (fields: `group_priority_order`, `demo_packages`, `admin_role_group`, `footer_config`) is formally defined in the `cli-commands` sibling spec. Optional steps (admin roles, footer) may be omitted from the config file entirely; omitting them is equivalent to skipping those steps in the wizard and does not cause an error. #### Scenario: CLI command accepts YAML config file - GIVEN a YAML file `/tmp/setup.yaml` with content: ```yaml - storage_backend: "groupfolder" group_priority_order: ["engineering", "sales"] demo_packages: ["engineering-demo", "sales-demo"] admin_role_group: "engineering" @@ -382,31 +258,36 @@ The system MUST expose a CLI command `php occ launchpad:setup` that accepts a `- ``` - WHEN an admin runs `php occ launchpad:setup --config=/tmp/setup.yaml` - THEN the system MUST: - - Set `launchpad.content_storage = "groupfolder"` (Step 2) - - Set `launchpad.group_priority_order = ["engineering", "sales"]` (Step 3) - - Install "engineering-demo" and "sales-demo" (Step 4) - - Assign "Dashboard Admin" role to "engineering" (Step 5) - - Set `launchpad.footer_config` with provided config (Step 6) - - Set `launchpad.setup_wizard_complete = true` (Step 7) + - Set `launchpad.group_priority_order = ["engineering", "sales"]` (Step 2) + - Install "engineering-demo" and "sales-demo" (Step 3) + - Assign "Dashboard Admin" role to "engineering" (Step 4) + - Set `launchpad.footer_config` with provided config (Step 5) + - Set `launchpad.setup_wizard_complete = true` (Step 6) #### Scenario: CLI command validates YAML schema -- GIVEN a malformed YAML file (e.g., missing required fields) +- GIVEN a YAML file whose top level is not a map, or whose `group_priority_order` is not a list - WHEN `php occ launchpad:setup --config=/tmp/setup.yaml` is run -- THEN the system MUST output an error: "Invalid setup.yaml: missing field 'storage_backend'" +- THEN the system MUST output an error starting with "Invalid setup.yaml:" - AND the command MUST exit with non-zero status -- AND no settings are applied + +#### Scenario: An old config that still sets storage_backend keeps working +- GIVEN a YAML file written for the seven-step wizard, with `storage_backend: "groupfolder"` +- WHEN `php occ launchpad:setup --config=/tmp/setup.yaml` is run +- THEN the command MUST print that `storage_backend` is no longer used and was ignored +- AND it MUST apply the other steps and exit with status 0 +- AND it MUST NOT write `launchpad.content_storage` #### Scenario: CLI command is verbose by default - GIVEN the command runs successfully - WHEN the output is examined -- THEN it MUST show progress: "Step 1: Welcome... done", "Step 2: Storage backend... done", etc. +- THEN it MUST show progress: "Step 1: Welcome... done", "Step 2: Group order... done", etc. - AND final message: "Setup wizard completed successfully." #### Scenario: CLI command skips optional steps if not in config -- GIVEN a YAML file with only `storage_backend` and `group_priority_order` +- GIVEN a YAML file with only `group_priority_order` - WHEN the command runs -- THEN Steps 5 and 6 MUST be skipped (no error) -- AND Steps 2 and 3 MUST execute with provided values +- THEN Steps 4 and 5 MUST be skipped (no error) +- AND Step 2 MUST execute with the provided value - AND the wizard completes #### Scenario: CLI command is idempotent @@ -424,27 +305,20 @@ The wizard MUST be re-runnable even after `launchpad.setup_wizard_complete = tru - GIVEN a LaunchPad instance with `launchpad.setup_wizard_complete = true` - WHEN an NC admin navigates to `/apps/launchpad/admin` and clicks "Run setup wizard again" (or uses a Re-run button in a separate admin UI section) - THEN the wizard modal MUST open -- AND all step values MUST reflect current settings (storage backend, group order, etc.) +- AND all step values MUST reflect current settings (group order, demo data, etc.) - AND the admin can make changes -#### Scenario: Re-running from Step 2 updates storage backend -- GIVEN the instance has `launchpad.content_storage = "database"` -- AND the admin re-runs the wizard and navigates to Step 2 -- WHEN the admin selects "GroupFolder" and clicks Next -- THEN the system MUST update `launchpad.content_storage = "groupfolder"` -- AND the previous choice "database" is overwritten (not appended or merged) - #### Scenario: Re-running does not re-install demo packages - GIVEN the instance has already installed "engineering-demo" -- AND the admin re-runs the wizard to Step 4 +- AND the admin re-runs the wizard to Step 3 - WHEN the admin unchecks "engineering-demo" and clicks Next - THEN the system MUST NOT re-install the demo (it's already there) - NOTE: Demo installation is one-time; re-running the wizard does not trigger redundant installations. If the admin wishes to un-install, they must use a separate admin UI for demo management. #### Scenario: Re-running preserves skipped steps -- GIVEN the wizard was run previously with Step 5 skipped +- GIVEN the wizard was run previously with Step 4 skipped - AND the admin re-runs the wizard -- WHEN Step 5 is displayed +- WHEN Step 4 is displayed - THEN the step MUST show "Skip" button as before - AND if the admin clicks Skip again, the behavior is consistent with the first run @@ -459,3 +333,67 @@ The wizard MUST be re-runnable even after `launchpad.setup_wizard_complete = tru - THEN the response MUST indicate `complete: true` - AND the admin UI MUST show a "Run setup wizard again" button (not a "Run setup wizard" banner) - NOTE: The UI signals that re-running is available and safe + +### Requirement: REQ-WIZ-012 Multi-Step Wizard Flow with 5 Steps + +The wizard MUST guide the admin through a linear, skippable sequence of 5 steps, as board LpInstellen draws them: +Welcome ("Welkom"), Groups ("Groepen", the group priority order), Examples ("Voorbeelden", the demo dashboards), Roles +("Rollen", the admin roles) and Done ("Klaar"). Each step has Skip / Back / Next buttons. Only the "Finish" button on +Step 5 marks the wizard complete. The wizard MUST NOT ask for storage or for the footer. + +> NOTE: Steps 2 to 4 each embed the canonical admin UI component from the corresponding sibling capability (`group-priority-order`, `demo-data-showcases`, `admin-roles`). The wizard is a thin orchestrator: it owns step sequencing and the completion flag; each sibling capability owns its own settings persistence. No settings surfaces are duplicated. + +#### Scenario: Wizard starts at Step 1 +- GIVEN the banner's "Run setup wizard" button is clicked +- WHEN the wizard modal opens +- THEN Step 1 (Welcome) MUST be displayed +- AND the step counter MUST show "1 / 5" + +#### Scenario: Next button advances to next step +- GIVEN the wizard is on Step 1 +- WHEN the admin clicks "Next" +- THEN the wizard advances to Step 2 (Groups) +- AND the step counter MUST show "2 / 5" +- AND the Back button MUST become active + +#### Scenario: Back button returns to previous step +- GIVEN the wizard is on Step 3 +- WHEN the admin clicks "Back" +- THEN the wizard returns to Step 2 +- AND no data loss occurs (Step 3 values are preserved if re-visited) + +#### Scenario: Skip button jumps to next step without commitment +- GIVEN the wizard is on Step 4 (Roles, optional) +- WHEN the admin clicks "Skip" +- THEN the wizard advances to Step 5 (Done) +- AND the wizard completion status for Step 4 is marked "skipped" (not "done") + +#### Scenario: Step 1 has no form; only explanatory text +- GIVEN Step 1 (Welcome) is displayed +- WHEN the admin views the step +- THEN the step MUST explain that the setup sets groups, example dashboards and roles in five steps, and that existing dashboards stay as they are +- AND there are no form fields to fill +- AND clicking "Next" advances without persisting any choice + +#### Scenario: Step 5 shows summary and Finish button +- GIVEN the wizard reaches Step 5 (Done) +- WHEN the admin views the step +- THEN the step MUST display a summary: "Your setup is complete. Click Finish to save changes and dismiss the setup banner." +- AND a "Finish" button (not "Next") MUST be present + +#### Scenario: Finish button completes wizard +- GIVEN the admin is on Step 5 with the "Finish" button visible +- WHEN the admin clicks "Finish" +- THEN the system MUST set `launchpad.setup_wizard_complete = true` +- AND the wizard modal MUST close +- AND the admin section MUST reload, banner gone + +#### Scenario: No footer step +- GIVEN the admin walks the wizard from Step 1 to Step 5 +- THEN no step shows the footer editor +- AND the wizard state endpoint reports five steps + +#### Scenario: Wizard progress persists across Back navigation +- GIVEN the wizard is on Step 3 after a group order was chosen on Step 2 +- WHEN the admin clicks Back to Step 2, then clicks Next to Step 3 +- THEN the group order chosen on Step 2 MUST still be present (no data loss) diff --git a/openspec/specs/text-display-widget/screens.md b/openspec/specs/text-display-widget/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/text-display-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/text-display-widget/spec.md b/openspec/specs/text-display-widget/spec.md index 65b244ae9..1cd9e75a2 100644 --- a/openspec/specs/text-display-widget/spec.md +++ b/openspec/specs/text-display-widget/spec.md @@ -61,7 +61,6 @@ The renderer MUST run `text` through `DOMPurify.sanitize` before injecting into ### Requirement: Style application with theme-aware fallbacks (REQ-TXT-002) The renderer MUST apply `fontSize`, `color`, `backgroundColor`, and `textAlign` from `content` as inline styles on the wrapper element. When a field is null or empty, the renderer MUST fall back to: `fontSize='14px'`, `color='var(--color-main-text)'`, `backgroundColor='transparent'`, `textAlign='left'`. -@e2e exclude style application with theme-aware fallbacks tests CSS variable resolution — Vitest snapshot scope; requires a placed text widget with custom styles #### Scenario: Custom font size and colour @@ -141,7 +140,6 @@ The component MUST expose a `validate()` method that returns `[t('launchpad', 'T ### Requirement: Layout — fill cell with padded scrollable content (REQ-TXT-005) The widget MUST fill its grid cell (`width: 100%, height: 100%`) with `padding: 16px` and `overflow: auto`. Content MUST be horizontally aligned per `textAlign` and vertically centred when content height is less than cell height (flex centred). -@e2e exclude layout fill cell tests CSS height: 100% / overflow — visual regression scope #### Scenario: Overflow scrolls within the cell @@ -159,7 +157,6 @@ The widget MUST fill its grid cell (`width: 100%, height: 100%`) with `padding: ### Requirement: REQ-TXMD-001 Add contentMode field to text-widget config The text-widget MUST support a `contentMode` field in its `styleConfig.content` object, with permitted values `'html'` or `'markdown'`. The field is optional; when absent, it defaults to `'html'` (backward compatibility with existing widgets). New widgets MUST receive a default determined by the system-wide default mode (see REQ-TXMD-005). -@e2e exclude add contentMode field tests JSON schema change — Vitest/Newman scope The field is optional; when absent, it defaults to `'html'` (backward compatibility with existing widgets). New widgets MUST receive a default determined by the system-wide default mode (see REQ-TXMD-005). #### Scenario: Existing widgets retain html mode @@ -191,7 +188,6 @@ The text-widget MUST support a `contentMode` field in its `styleConfig.content` ### Requirement: REQ-TXMD-002 CommonMark-compliant markdown parsing When `contentMode = 'markdown'`, the renderer MUST parse the widget text using a CommonMark-compliant parser and convert it to HTML. The parser MUST handle headings (H1–H6 via `#...######` syntax), emphasis (`**bold**`, `*italic*`, `***bold-italic***`), code (inline `` `code` `` and code blocks), links, lists (bullet and ordered), block quotes, and tables. -@e2e exclude CommonMark-compliant markdown parsing tests the JS markdown library integration — Vitest unit scope The parser MUST handle headings (H1–H6 via `#...######` syntax), emphasis (`**bold**`, `*italic*`, `***bold-italic***`), code (inline `` `code` `` and code blocks), links, lists (bullet and ordered), block quotes, and tables. #### Scenario: Heading shortcuts render to semantic heading tags @@ -250,14 +246,13 @@ When `contentMode = 'markdown'`, the renderer MUST parse the widget text using a ### Requirement: REQ-TXMD-003 Sanitisation of parsed markdown output All HTML output produced by the markdown parser MUST be passed through the same XSS allow-list sanitiser used by REQ-TXT-001 (HTML mode). Tags and attributes that pose security risk MUST be stripped. Safe tags (heading, emphasis, link, list, blockquote, table) MUST be preserved. Anchors MUST receive `rel="noopener noreferrer"` whenever they carry `target="_blank"`, to mitigate reverse-tabnabbing. -@e2e exclude sanitisation of parsed markdown output tests DOMPurify config — Vitest unit scope Tags and attributes that pose security risk MUST be stripped. Safe tags (heading, emphasis, link, list, blockquote, table) MUST be preserved. Anchors MUST receive `rel="noopener noreferrer"` whenever they carry `target="_blank"`, to mitigate reverse-tabnabbing. #### Scenario: Script tags in markdown are stripped - GIVEN `text = "<script>alert(1)</script> and **bold**"` - WHEN the widget renders with `contentMode = 'markdown'` - THEN the DOM MUST NOT contain a `<script>` element -- AND the visible text MUST be " and **bold**" (script is stripped, markdown bold is parsed) +- AND the visible text MUST be "and bold", with "bold" in a `<strong>` (script is stripped, markdown bold is parsed) #### Scenario: Event handlers are removed from parsed elements @@ -282,7 +277,6 @@ All HTML output produced by the markdown parser MUST be passed through the same ### Requirement: REQ-TXMD-004 Mode toggle in the edit form The text-widget edit sub-form MUST display a `Mode` toggle or radio/select group with two options: `HTML` and `Markdown`. The toggle's state MUST be bound to `contentMode` in the widget's `styleConfig.content` object. Switching modes MUST NOT lose the text content — only the parsing behavior changes. -@e2e exclude mode toggle in edit form tests radio group inside AddWidgetModal for a placed text widget — requires seeded text placement The toggle's state MUST be bound to `contentMode` in the widget's `styleConfig.content` object. Switching modes MUST NOT lose the text content — only the parsing behavior changes. #### Scenario: HTML mode is shown by default for existing widgets @@ -319,7 +313,6 @@ The text-widget edit sub-form MUST display a `Mode` toggle or radio/select group ### Requirement: REQ-TXMD-005 System default for new widget content mode The widget registry's `text.defaultContent.contentMode` MUST seed every new text widget with a known-good mode. The shipped default MUST be `'markdown'` (the primary authoring mode). Invalid mode values written through the form MUST be rejected so that placements only ever persist `'html'` or `'markdown'`. A future admin setting (`launchpad.text_widget_default_mode`, deferred to the `admin-text-widget-settings` change) MAY override the registry default at runtime. -@e2e exclude system default for new widget content mode tests defaultMode config constant — Vitest scope The shipped default MUST be `'markdown'` (the primary authoring mode). Invalid mode values written through the form MUST be rejected so that placements only ever persist `'html'` or `'markdown'`. A future admin setting (`launchpad.text_widget_default_mode`, deferred to the `admin-text-widget-settings` change) MAY override the registry default at runtime. #### Scenario: Default is markdown when nothing else applies @@ -335,6 +328,7 @@ The widget registry's `text.defaultContent.contentMode` MUST seed every new text - AND no widget save MUST persist an invalid mode #### Scenario: Setting affects only new widgets, not existing ones +@e2e exclude the runtime default-mode setting was never built: `launchpad.text_widget_default_mode` is deferred to the unshipped `admin-text-widget-settings` change and appears nowhere in src/, lib/ or appinfo/ (`git log --all -S text_widget_default_mode -- src lib appinfo` is empty), so the default cannot be changed in a running instance. No unit test pins it either. The two observable halves are cited elsewhere: existing html widgets keep html (existing-widgets-retain-html-mode, existing-widget-renders-unchanged) and new widgets get the registry default (new-widget-receives-the-configured-default). - GIVEN existing widgets already have `contentMode = 'html'` - WHEN the system default changes from `'html'` to `'markdown'` @@ -344,7 +338,6 @@ The widget registry's `text.defaultContent.contentMode` MUST seed every new text ### Requirement: REQ-TXMD-006 Backward compatibility — existing HTML-mode widgets unaffected All widgets with `contentMode = 'html'` (the default for existing widgets) MUST continue to render exactly as before per REQ-TXT-001..005. The markdown parser MUST NOT be invoked for these placements. The introduction of markdown mode MUST NOT degrade or change the behavior of HTML mode. -@e2e exclude backward compatibility tests that existing HTML-mode blobs are unaffected — Newman/Vitest scope The markdown parser MUST NOT be invoked for these placements. The introduction of markdown mode MUST NOT degrade or change the behavior of HTML mode. #### Scenario: Existing widget renders unchanged @@ -370,7 +363,6 @@ All widgets with `contentMode = 'html'` (the default for existing widgets) MUST ### Requirement: REQ-TXMD-007 Heading levels H1–H6 with markdown shortcuts The markdown parser MUST recognise and render heading levels via the standard `#`-prefix syntax: `#` for H1, `##` for H2, ..., `######` for H6. Each heading level MUST produce a corresponding semantic HTML tag (`<h1>` through `<h6>`). -@e2e exclude heading levels H1-H6 with markdown shortcuts tests markdown rendering inside a placed text widget — requires seeded markdown placement #### Scenario: Single hash produces h1 @@ -406,7 +398,6 @@ The markdown parser MUST recognise and render heading levels via the standard `# ### Requirement: REQ-TBLE-001 Table Data Model The widget MUST store table content in a `tableData` JSON object within `styleConfig`, with the schema: -@e2e exclude table data model tests JSON schema and migration — Vitest/Newman scope ```jsonc { @@ -447,7 +438,7 @@ All fields MUST be present on save; no partial updates. #### Scenario: Merged cells with span metadata -- GIVEN `rows = [[{text:"Header", "colSpan": 2}, {text:"X"}], [{text:"A"}, {text:"B"}, {text:"C"}]]` +- GIVEN `rows = [[{text:"Header", "colSpan": 2}, {text:""}, {text:"X"}], [{text:"A"}, {text:"B"}, {text:"C"}]]` (the covered cell stays in the row as an empty placeholder, as REQ-TBLE-006 and REQ-TBLE-009 lay it out) - WHEN the editor loads - THEN the first row's first cell MUST show `colSpan: 2`, and subsequent rows MUST account for the wider first cell - NOTE: This scenario documents the data structure; merged-cell layout rules are covered in REQ-TBLE-007. @@ -462,7 +453,6 @@ All fields MUST be present on save; no partial updates. ### Requirement: REQ-TBLE-002 Table Mode Toggle The editor MUST expose a `tableMode` boolean flag (or "Text | Table" mode selector) that switches rendering between markdown/HTML text and structured table data. -@e2e exclude table mode toggle tests radio group inside placed text widget editor — requires seeded table placement #### Scenario: Switch from text to table mode @@ -488,7 +478,6 @@ The editor MUST expose a `tableMode` boolean flag (or "Text | Table" mode select ### Requirement: REQ-TBLE-003 Add Row Operation The editor MUST provide controls to insert a new row above or below the current selection. -@e2e exclude add row operation tests table editor inside placed widget — requires seeded table placement #### Scenario: Add row below current row @@ -522,7 +511,6 @@ The editor MUST provide controls to insert a new row above or below the current ### Requirement: REQ-TBLE-004 Add Column Operation The editor MUST provide controls to insert a new column left or right of the current selection. -@e2e exclude add column operation tests table editor inside placed widget — requires seeded table placement #### Scenario: Add column right of current column @@ -550,7 +538,6 @@ The editor MUST provide controls to insert a new column left or right of the cur ### Requirement: REQ-TBLE-005 Delete Row and Delete Column Operations The editor MUST provide controls to remove rows or columns, with confirmation if the target contains text. -@e2e exclude delete row and column tests table editor — requires seeded table placement #### Scenario: Delete empty row @@ -585,7 +572,6 @@ The editor MUST provide controls to remove rows or columns, with confirmation if ### Requirement: REQ-TBLE-006 Merge and Split Cells The editor MUST allow users to merge multiple selected cells horizontally or vertically, and to split a merged cell back to 1×1. -@e2e exclude merge and split cells tests complex grid-integrity algorithm — Vitest scope; not yet visibly shipped in v1.0.5 #### Scenario: Merge 2 horizontal cells @@ -626,7 +612,6 @@ The editor MUST allow users to merge multiple selected cells horizontally or ver ### Requirement: REQ-TBLE-007 Column Alignment and Header Row Toggle The editor MUST expose per-column alignment controls and a header-row flag toggle. -@e2e exclude column alignment and header row toggle tests CSS class application — Vitest scope #### Scenario: Set column alignment to center @@ -659,7 +644,6 @@ The editor MUST expose per-column alignment controls and a header-row flag toggl ### Requirement: REQ-TBLE-008 Table Validation — Grid Integrity On save, the system MUST validate that the table grid is rectangular and cell spans do not exceed bounds. -@e2e exclude table validation grid integrity tests algorithmic invariant — Vitest scope #### Scenario: Valid rectangular grid without merges @@ -699,7 +683,6 @@ On save, the system MUST validate that the table grid is rectangular and cell sp ### Requirement: REQ-TBLE-009 Render HTML Table with Cell Merging The renderer MUST output an HTML `<table>` with correct `<th>` / `<td>` elements, `rowspan` / `colspan` attributes, and per-column text alignment. -@e2e exclude render HTML table with cell merging tests colspan/rowspan rendering inside placed widget — requires seeded table placement #### Scenario: Render basic 2x2 table @@ -749,7 +732,6 @@ The renderer MUST output an HTML `<table>` with correct `<th>` / `<td>` elements ### Requirement: REQ-TBLE-010 Cell Text Sanitisation Cell text MUST be sanitised using DOMPurify before rendering to prevent XSS attacks. -@e2e exclude cell text sanitisation tests DOMPurify integration — Vitest scope #### Scenario: Safe HTML tags preserved @@ -781,7 +763,6 @@ Cell text MUST be sanitised using DOMPurify before rendering to prevent XSS atta ### Requirement: REQ-TBLE-011 Empty-Table Placeholder When a table is freshly created (empty cells, no user text), the renderer MUST display a subtle placeholder to indicate the table is empty. -@e2e exclude empty-table placeholder tests Vue empty state inside placed widget — requires seeded empty-table placement #### Scenario: Empty 1x1 table shows placeholder diff --git a/openspec/specs/tile-quick-search/screens.md b/openspec/specs/tile-quick-search/screens.md new file mode 100644 index 000000000..dd0a09b0b --- /dev/null +++ b/openspec/specs/tile-quick-search/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpVandaag https://identity.conduction.nl/screens/board?id=launchpad/LpVandaag diff --git a/openspec/specs/tile-quick-search/spec.md b/openspec/specs/tile-quick-search/spec.md index b92fe85ae..149647f2e 100644 --- a/openspec/specs/tile-quick-search/spec.md +++ b/openspec/specs/tile-quick-search/spec.md @@ -251,3 +251,46 @@ cannot see on screen, or cannot find tiles they can. - WHEN its title is resolved - THEN the widget type's display name MUST be used - AND the generic fallback word MUST be used only when nothing else resolves + +### Requirement: Administrators define search shortcuts (REQ-SPX-001) + +An administrator MUST be able to define up to 30 search shortcuts, each with a prefix (`!` and 1 to 10 letters or digits, unique regardless of case), a name, and an https address containing `{query}`. The server MUST refuse an entry that breaks any of these rules. + +#### Scenario: Add the TOPdesk shortcut + +- **GIVEN** Noor is an administrator on the LaunchPad admin page, section "Search shortcuts" +- **WHEN** she adds prefix `!t`, name "TOPdesk" and address `https://topdesk.gemeente.nl/tas/secure/search?q={query}` and saves +- **THEN** the shortcut is listed + +#### Scenario: Plain http is refused + +- **GIVEN** Noor adds a shortcut +- **WHEN** she enters the address `http://intranet.gemeente.nl/zoek?q={query}` +- **THEN** the save fails with "Use an https address that contains {query}" + +### Requirement: A prefix sends the query to its site (REQ-SPX-002) + +In the search widget and the Workspace quick search, a query whose first word is a known prefix MUST show a single result naming the site and the rest of the query, and Enter MUST open the site's address with the URL-encoded rest in a new tab. A query without a known prefix MUST behave as before: tile filtering, then the configured fallback. + +#### Scenario: Search TOPdesk + +- **GIVEN** the shortcut `!t` for "TOPdesk" +- **WHEN** Pieter types `!t printer 3e verdieping` in the quick search +- **THEN** the only result reads "Search TOPdesk for printer 3e verdieping" +- **AND WHEN** he presses Enter, a new tab opens `https://topdesk.gemeente.nl/tas/secure/search?q=printer%203e%20verdieping` + +#### Scenario: Unknown prefix falls through + +- **GIVEN** no shortcut `!x` +- **WHEN** Pieter types `!x rapport` +- **THEN** the box filters tiles for `!x rapport` and applies the normal fallback + +### Requirement: Users can see the shortcuts (REQ-SPX-003) + +Typing `!` alone or `?` in a search box MUST list the available shortcuts with their prefix and name, announced to screen readers. + +#### Scenario: List the shortcuts + +- **GIVEN** shortcuts `!t` "TOPdesk" and `!z` "Zaaksysteem" +- **WHEN** Pieter types `?` in the search widget +- **THEN** he sees "!t TOPdesk" and "!z Zaaksysteem" diff --git a/openspec/specs/tiles/screens.md b/openspec/specs/tiles/screens.md new file mode 100644 index 000000000..ae2025be1 --- /dev/null +++ b/openspec/specs/tiles/screens.md @@ -0,0 +1,4 @@ +# Screens + +- LpWerkplek https://identity.conduction.nl/screens/board?id=launchpad/LpWerkplek +- LpTegelBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpTegelBewerken diff --git a/openspec/specs/tiles/spec.md b/openspec/specs/tiles/spec.md index 89659d79d..a00e2d671 100644 --- a/openspec/specs/tiles/spec.md +++ b/openspec/specs/tiles/spec.md @@ -38,7 +38,6 @@ This means tile placements store a COPY of the tile configuration at creation ti ### Requirement: REQ-TILE-001 Reusable tile entity model \u2014 DEPRECATED The reusable tile entity model (rows in `oc_launchpad_tiles`, accessed via `TileService::createTile / updateTile / deleteTile` and `POST/PUT/DELETE /api/tiles[/{id}]`) MUST be treated as deprecated as of the `unified-add-widget-flow` change. The unified add-widget flow (REQ-WDG-022) introduces `tile` as a registry-driven widget type that stores its data inline on each placement, removing the need for a separate reusable-entity table; existing rows MUST remain readable for backwards compatibility. -@e2e exclude tile entity DEPRECATED — write endpoints return 410; checked by Newman, not UI The unified add-widget flow (REQ-WDG-022) introduces `tile` as a registry-driven widget type that stores its data inline on each placement, removing the need for a separate reusable-entity table; existing rows MUST remain readable for backwards compatibility. The following behaviour MUST hold during the deprecation window: @@ -61,6 +60,7 @@ The following behaviour MUST hold during the deprecation window: - **WHEN** an authenticated user calls `GET /api/tiles` - **THEN** the response MUST be HTTP 200 with the row's fields in the documented shape - **AND** this MUST work as long as the `oc_launchpad_tiles` table exists in the schema +@e2e exclude needs rows in oc_launchpad_tiles, which no API can create any more (POST /api/tiles is 410 Gone, cited by tiles::write-endpoints-return-410-gone) and the CI instance seeds none; pinned by tests/Unit/Controller/TileApiControllerTest.php testIndexStillReturnsExistingRowsForBackwardsCompat; the empty-list read is cited by tiles::list-tiles-when-none-exist #### Scenario: Existing tile placements still render @@ -72,19 +72,20 @@ The following behaviour MUST hold during the deprecation window: ### Requirement: List User Tiles (REQ-TILE-002) Users MUST be able to retrieve all their custom tile definitions, scoped to their user ID. -@e2e exclude list user tiles tests REST endpoint — Newman scope #### Scenario: List tiles for a user - GIVEN user "alice" has 5 custom tiles - WHEN she sends GET /api/tiles - THEN the system MUST return HTTP 200 with an array of all 5 tiles - AND each tile MUST include: id, userId, title, icon, iconType, backgroundColor, textColor, linkType, linkValue, createdAt, updatedAt +@e2e exclude needs rows in oc_launchpad_tiles, which no API can create any more (POST /api/tiles is 410 Gone, cited by tiles::write-endpoints-return-410-gone) and the CI instance seeds none; pinned by tests/Unit/Controller/TileApiControllerTest.php testIndexStillReturnsExistingRowsForBackwardsCompat and tests/Unit/Db/TileMapperTest.php #### Scenario: Tiles are user-scoped - GIVEN user "alice" has 5 tiles and user "bob" has 3 tiles - WHEN "alice" sends GET /api/tiles - THEN the response MUST contain only alice's 5 tiles - AND bob's tiles MUST NOT be included +@e2e exclude needs rows in oc_launchpad_tiles, which no API can create any more (POST /api/tiles is 410 Gone, cited by tiles::write-endpoints-return-410-gone) and the CI instance seeds none; user scoping is pinned by tests/Unit/Db/TileMapperTest.php (findByUserId) #### Scenario: List tiles when none exist - GIVEN user "carol" has no custom tiles @@ -94,7 +95,7 @@ Users MUST be able to retrieve all their custom tile definitions, scoped to thei ### Requirement: Update Custom Tile (REQ-TILE-003) Users MUST be able to update the properties of their custom tiles with ownership verification. -@e2e exclude update tile tests REST PUT — Newman scope +@e2e exclude superseded by REQ-TILE-001: PUT /api/tiles/{id} answers 410 Gone for every caller (cited by tiles::write-endpoints-return-410-gone; pinned by tests/Unit/Controller/TileApiControllerTest.php testUpdateReturns410GoneEnvelope), and no tile row can be created to update since POST /api/tiles is 410 too #### Scenario: Update tile title and colors - GIVEN user "alice" has tile id 3 with title "My Files" @@ -132,7 +133,7 @@ Users MUST be able to update the properties of their custom tiles with ownership ### Requirement: Delete Custom Tile (REQ-TILE-004) Users MUST be able to delete their custom tile definitions with ownership verification. -@e2e exclude delete tile tests REST DELETE — Newman scope +@e2e exclude superseded by REQ-TILE-001: DELETE /api/tiles/{id} answers 410 Gone for every caller (cited by tiles::write-endpoints-return-410-gone; pinned by tests/Unit/Controller/TileApiControllerTest.php testDestroyReturns410GoneEnvelope), and no tile row can be created to delete since POST /api/tiles is 410 too #### Scenario: Delete a tile not placed on any dashboard - GIVEN user "alice" has tile id 3 that is not placed on any dashboard @@ -156,14 +157,14 @@ Users MUST be able to delete their custom tile definitions with ownership verifi ### Requirement: Place Tile on Dashboard (REQ-TILE-005) Users MUST be able to place tile data onto a dashboard, creating a widget placement with inline tile data. -@e2e exclude place tile on dashboard tests REST POST — Newman scope #### Scenario: Place a tile on a dashboard - GIVEN user "alice" has dashboard id 5 - WHEN she sends POST /api/dashboard/5/tile with body: ```json - {"tileTitle": "My Files", "tileIcon": "icon-folder", "tileIconType": "class", "tileBackgroundColor": "#3b82f6", "tileTextColor": "#ffffff", "tileLinkType": "app", "tileLinkValue": "/apps/files", "gridX": 0, "gridY": 0, "gridWidth": 2, "gridHeight": 2} + {"title": "My Files", "icon": "icon-folder", "iconType": "class", "bgColor": "#3b82f6", "textColor": "#ffffff", "linkType": "app", "linkValue": "/apps/files", "gridX": 0, "gridY": 0, "gridWidth": 2, "gridHeight": 2} ``` +- NOTE: the request names are `title`, `icon`, `iconType`, `bgColor`, `textColor`, `linkType` and `linkValue` (RequestDataExtractor::TILE_PARAMS, sent so by the frontend); the placement stores them as `tileTitle`, `tileIcon`, `tileIconType`, `tileBackgroundColor`, `tileTextColor`, `tileLinkType` and `tileLinkValue`. The body used to show the stored names, which the endpoint never read. - THEN the system MUST create a widget placement record with `tileType` set to `"custom"` - AND `widgetId` MUST be set to `'tile-' + uniqid()` (NOT null) - AND the tile data MUST be stored inline on the placement via `TileUpdater::applyTileConfig()` @@ -197,7 +198,6 @@ Users MUST be able to place tile data onto a dashboard, creating a widget placem ### Requirement: Tile Icon Rendering (REQ-TILE-006) The frontend MUST support four icon formats: emoji, CSS class, URL, and SVG path. -@e2e exclude tile icon rendering (emoji/CSS/URL/SVG path) requires a pre-placed tile on the dashboard — needs seeded state not available in CI fixture #### Scenario: Render emoji icon - GIVEN a tile with `iconType: "emoji"` and `icon: "\ud83d\udcc1"` @@ -226,7 +226,6 @@ The frontend MUST support four icon formats: emoji, CSS class, URL, and SVG path ### Requirement: Tile Color Validation (REQ-TILE-007) Tile colors MUST be validated to ensure proper display and accessibility. -@e2e exclude tile color validation tests server-side validator — Newman scope #### Scenario: Valid hex colors accepted - GIVEN a tile creation request with `backgroundColor: "#3b82f6"` and `textColor: "#ffffff"` @@ -238,6 +237,7 @@ Tile colors MUST be validated to ensure proper display and accessibility. - WHEN the tile is created - THEN the system SHOULD return HTTP 400 with a validation error - NOTE: Color format validation is NOT currently implemented +@e2e exclude never built: no colour validation exists, TileUpdater::applyTileConfig() stores `bgColor` and `textColor` as given (lib/Service/TileUpdater.php) and no unit test pins a format check; the default colours are cited under default-colors-when-not-specified #### Scenario: Default colors when not specified - GIVEN a tile creation request without `backgroundColor` or `textColor` @@ -247,7 +247,6 @@ Tile colors MUST be validated to ensure proper display and accessibility. ### Requirement: Tile Link Navigation (REQ-TILE-008) Tiles MUST navigate correctly based on their linkType. -@e2e exclude tile link navigation tests window.location or router.push inside a widget click — requires a placed tile; seeding not available #### Scenario: App link navigation - GIVEN a tile with `linkType: "app"` and `linkValue: "files"` @@ -268,7 +267,6 @@ Tiles MUST navigate correctly based on their linkType. ### Requirement: Tile Styling (REQ-TILE-009) Tiles MUST apply their configured colors as CSS custom properties for consistent rendering. -@e2e exclude tile background/text colour CSS tests require a pre-placed tile — seeded state not available in CI fixture #### Scenario: Tile background and text colors applied - GIVEN a tile with `backgroundColor: "#3b82f6"` and `textColor: "#ffffff"` @@ -292,13 +290,13 @@ Tiles MUST apply their configured colors as CSS custom properties for consistent ### Requirement: Tile Edit Mode (REQ-TILE-010) Tiles MUST support an edit mode that allows configuration changes. -@e2e exclude tile edit-mode button visibility requires a placed tile in edit mode — seeded state not available #### Scenario: Edit button visible in edit mode - GIVEN a tile on a dashboard in edit mode - WHEN the tile is rendered -- THEN an edit button (settings icon) MUST appear at the top-right corner of the tile -- AND the button MUST have `aria-label="Edit tile"` for accessibility +- THEN the tile menu button (the shared widget edit cog) MUST appear at the top-right corner of the tile +- AND the button MUST have `aria-label="Tile menu"` for accessibility +- AND the menu it opens MUST offer "Edit tile" #### Scenario: Edit button hidden in view mode - GIVEN a tile on a dashboard in view mode @@ -307,30 +305,30 @@ Tiles MUST support an edit mode that allows configuration changes. #### Scenario: Edit button click emits event - GIVEN a tile in edit mode -- WHEN the user clicks the edit button +- WHEN the user chooses "Edit tile" in the tile menu - THEN the `TileWidget` component MUST emit an `edit` event - AND `click.prevent` MUST prevent link navigation when clicking the edit button ### Requirement: Tile Management UI (REQ-TILE-011) Users MUST be able to manage their tile definitions through a dedicated UI. -@e2e exclude tile management UI (modal form) requires an existing tile placement — seeded state not available #### Scenario: Tile card display - GIVEN user "alice" has custom tiles - WHEN she views the tile management panel - THEN each tile MUST be displayed as a `TileCard` component with its icon, title, and colors +@e2e exclude never built: no TileCard component or tile management panel exists (`git log --all --diff-filter=A -- '*TileCard.vue'` finds nothing); tiles are managed on the grid through TileEditor, cited by tiles::tile-editor #### Scenario: Tile editor - GIVEN the user wants to create or edit a tile - WHEN the tile editor opens -- THEN `TileEditor.vue` MUST provide fields for title, icon, iconType, colors, linkType, and linkValue -- AND changes MUST be saved via the tile API +- THEN `TileEditor.vue` MUST provide fields for the name, the icon, the background and text colours, the tile type (linkType) and its address (linkValue) +- AND the icon type (iconType) MUST follow from the chosen icon, not from a field of its own +- AND changes MUST be saved via `PUT /api/widgets/{placementId}` (the `/api/tiles` endpoints are gone, REQ-TILE-001) ### Requirement: REQ-TILE-PLACEMENT Inline-content placement model — promoted to canonical Tile placements (rows in `oc_launchpad_widget_placements` with `tileType: 'custom'` historically, or `widgetId: 'tile'` going forward) MUST store their data INLINE on the placement. This MUST be treated as the canonical model for tile data on dashboards going forward. -@e2e exclude inline-content placement model is a data-model spec — no distinct UI surface beyond what REQ-TILE-010/011 cover New tile placements created via the unified add-widget flow (REQ-WDG-010 + REQ-WDG-022) MUST store their data in `placement.content.{title, icon, iconType, backgroundColor, textColor, linkType, linkValue}` — the standard widget-content shape. Legacy placements with the flat `placement.tileTitle / tileIcon / ...` shape MUST continue to work via the renderer's dual-shape support (REQ-WDG-022 scenario "Tile renderer supports legacy and new content shapes"). @@ -343,6 +341,356 @@ A future migration MAY rewrite legacy placements into the new content shape, but - **THEN** the resulting `oc_launchpad_widget_placements` row MUST have its data in `content` (JSON column) - **AND** the legacy flat `tileTitle`/`tileIcon`/etc. columns MUST NOT be populated for new placements +### Requirement: Users can import a browser bookmarks file as tiles (REQ-BMI-001) + +A user with add rights on a dashboard MUST be able to choose a bookmarks file in the HTML format browsers export, see its folders and bookmarks, pick which to import, and have them added as tiles. Each chosen top-level folder MUST become a container titled with the folder name holding its bookmarks as tiles, with nested folders flattened into it. Loose bookmarks MUST become tiles on the dashboard. New items MUST be appended at the bottom of the dashboard. + +#### Scenario: Import one folder + +- **GIVEN** Pieter has full permission on "Mijn werkplek" and a bookmarks file with folders "Werk" (12 bookmarks) and "Privé" (30 bookmarks) +- **WHEN** he chooses "Import bookmarks", selects the file, ticks only "Werk" and confirms +- **THEN** a container "Werk" with 12 tiles appears at the bottom of "Mijn werkplek" +- **AND** nothing from "Privé" is imported + +#### Scenario: View-only dashboard offers no import + +- **GIVEN** Pieter views the group dashboard "Organisatie" with view-only permission +- **WHEN** he opens the dashboard menu +- **THEN** "Import bookmarks" is not in the menu + +### Requirement: The import checks every address (REQ-BMI-002) + +The server MUST import only `http` and `https` addresses that pass the shared URL safety check. Other bookmarks MUST be skipped and listed back to the user with the reason. + +#### Scenario: A script bookmark is skipped + +- **GIVEN** the chosen folder holds a bookmarklet `javascript:alert(1)` and 5 normal bookmarks +- **WHEN** Pieter confirms the import +- **THEN** 5 tiles are created +- **AND** the result says "1 bookmark skipped: only web addresses can become tiles" + +### Requirement: The import respects the widget quota as one operation (REQ-BMI-003) + +The server MUST check the dashboard's widget quota for the whole import before creating anything, and MUST create all items in one transaction. When the quota would be exceeded it MUST return HTTP 409 with the quota body and create nothing. + +#### Scenario: Import too large for the quota + +- **GIVEN** the administrator limits dashboards to 20 widgets and "Mijn werkplek" has 18 +- **WHEN** Pieter imports 3 folders +- **THEN** the response is 409, the dialog says the dashboard has room for 2 more items, and no container or tile is created + +### Requirement: Large files are refused in the browser (REQ-BMI-004) + +The browser MUST refuse bookmark files over 5 MB or with more than 2,000 bookmarks before sending anything, with a message naming the limit. + +#### Scenario: Oversized file + +- **GIVEN** a bookmarks file with 3,500 bookmarks +- **WHEN** Pieter selects it +- **THEN** the dialog says "This file has more than 2,000 bookmarks. Export one folder at a time." and nothing is sent to the server + +### Requirement: Administrators declare the office networks (REQ-TIA-001) + +An administrator MUST be able to list the office networks as IPv4 and IPv6 CIDR ranges on the LaunchPad admin page. The server MUST reject a malformed range with HTTP 400. The page MUST show the administrator's own current address and whether it falls inside the listed ranges. + +#### Scenario: Administrator adds the office range + +- **GIVEN** Noor is a Nextcloud administrator on the LaunchPad admin page +- **WHEN** she adds `10.20.0.0/16` under "Office networks" and saves +- **THEN** the list shows `10.20.0.0/16` +- **AND** the page says whether her current address is inside the office networks + +#### Scenario: Malformed range is refused + +- **GIVEN** Noor edits the office networks +- **WHEN** she enters `10.20.0.0/40` and saves +- **THEN** the save fails with the message "This is not a valid network range" and the stored list is unchanged + +### Requirement: A tile can hold an office-network address (REQ-TIA-002) + +A tile MUST accept an optional second address for use on the office network. The server MUST validate it with the same rules as the tile's main address. + +#### Scenario: Author adds the internal address + +- **GIVEN** Ella may edit the dashboard "Team Vergunningen" with a tile "Zaaksysteem" at `https://zaken.gemeente.nl` +- **WHEN** she sets "Address on the office network" to `http://zaken.intern` and saves +- **THEN** the tile keeps both addresses + +### Requirement: The tile opens the address that fits the network (REQ-TIA-003) + +When a request comes from an address inside the office networks, a tile with an office-network address MUST open that address. Everywhere else, and whenever no office networks are set, it MUST open its main address. The decision MUST be made by the server from the request address, not by probing hosts from the browser. + +#### Scenario: At the office + +- **GIVEN** the office networks include `10.20.0.0/16` and Pieter's request comes from `10.20.4.7` +- **WHEN** he clicks "Zaaksysteem" +- **THEN** his browser opens `http://zaken.intern` + +#### Scenario: At home + +- **GIVEN** Pieter's request comes from `84.1.2.3`, outside the office networks +- **WHEN** he clicks "Zaaksysteem" +- **THEN** his browser opens `https://zaken.gemeente.nl` + +#### Scenario: Editor shows the address in effect + +- **GIVEN** Ella is on the office network and edits "Zaaksysteem" +- **WHEN** she looks below "Address on the office network" +- **THEN** she reads "You are on the office network: this tile opens the internal address" + +### Requirement: The add flow lists the apps this server runs for the user (REQ-DISC-001) + +The add flow MUST show a "Discovered on this server" section with every app in the user's Nextcloud app menu except LaunchPad, including AppAPI external apps that have a page, with each app's name and icon. The server MUST build the list from the user's own app menu, so apps restricted to groups the user is not in MUST NOT appear. + +#### Scenario: Deck is discovered + +- **GIVEN** the server has Deck enabled for everyone and Pieter edits "Mijn werkplek" +- **WHEN** he opens "Add" +- **THEN** "Deck" appears under "Discovered on this server" with the Deck icon + +#### Scenario: Restricted app stays hidden + +- **GIVEN** the app "Forms" is enabled only for group "Communicatie" and Pieter is not a member +- **WHEN** he opens "Add" +- **THEN** "Forms" is not under "Discovered on this server" + +### Requirement: One click turns a discovered app into a tile (REQ-DISC-002) + +Choosing a discovered app MUST place a tile with the app's name, icon and address in one action, through the normal tile creation path. Apps already on the dashboard MUST be marked "On this dashboard". + +#### Scenario: Place Deck + +- **GIVEN** "Deck" is listed under "Discovered on this server" +- **WHEN** Pieter clicks it +- **THEN** a tile "Deck" appears at the bottom of "Mijn werkplek" and opens `/apps/deck/` +- **AND** the next time he opens "Add", "Deck" shows "On this dashboard" + +### Requirement: Discovery never touches the container host (REQ-DISC-003) + +Discovery MUST read only the Nextcloud app menu. It MUST NOT read a Docker socket, container labels or AppAPI deployment data. + +#### Scenario: No socket access + +- **GIVEN** an instance where AppAPI runs the external app "Context Chat" with a page +- **WHEN** Pieter opens "Add" +- **THEN** "Context Chat" is discovered from the app menu +- **AND** LaunchPad makes no call to a Docker or AppAPI daemon endpoint +@e2e exclude needs AppAPI with an external app (Context Chat), which the CI instance lacks, and the absence of a server-side daemon call is not observable from the browser; pinned by tests/Unit/Service/ServiceDiscoveryServiceTest.php (testKeepsAnExternalApp, testListsTheMenuAppsWithoutLaunchPad: discovery reads only INavigationManager) + +### Requirement: A tile can start a program on the user's computer (REQ-TLT-001) + +A tile MUST accept link type `program` with an address whose scheme is on the administrator's allowed-scheme list. The server MUST refuse `javascript`, `data`, `file`, `vbscript`, `about` and `blob` schemes even when an administrator lists them. The allowed list MUST be empty until an administrator fills it. + +#### Scenario: Word tile + +- **GIVEN** Noor allowed the scheme `ms-word` on the LaunchPad admin page +- **WHEN** Ella adds a tile "Word" of type "Program on this computer" with address `ms-word:ofe|u|https://docs.example.nl/sjabloon.docx` and Pieter clicks it +- **THEN** Pieter's browser hands the address to the installed Word program +- **AND** the tile shows "Nothing happened? The program may not be installed on this computer." + +#### Scenario: Script scheme is refused + +- **GIVEN** any administrator setting +- **WHEN** a client saves a tile of type `program` with address `javascript:alert(1)` +- **THEN** the response is 400 and no tile is saved + +### Requirement: A tile can start a remote desktop or a published program (REQ-TLT-002) + +A tile MUST accept link type `remote-desktop` in one of two modes: a web gateway address (https only), or an RDP connection with host, port, an optional published program and an optional gateway. For the RDP mode the server MUST generate a `.rdp` file from the validated fields only, MUST check that the caller may view the tile's dashboard, and MUST NOT write any credential into the file. + +#### Scenario: Published Windows program through a gateway + +- **GIVEN** a tile "Belastingen (oud)" of type "Remote desktop" in RDP mode with host `rds01.gemeente.local`, program `||Belastingen` and gateway `rdgw.gemeente.nl` +- **WHEN** Pieter clicks it +- **THEN** his browser downloads `Belastingen (oud).rdp` containing `full address:s:rds01.gemeente.local`, `remoteapplicationprogram:s:||Belastingen` and `gatewayhostname:s:rdgw.gemeente.nl` +- **AND** the file contains no user name or password + +#### Scenario: Someone without access asks for the file + +- **GIVEN** the tile sits on a dashboard Sanne may not view +- **WHEN** Sanne requests `GET /api/tiles/{placementId}/rdp` +- **THEN** the response is 403 + +#### Scenario: Web gateway + +- **GIVEN** a tile "Werkplek" of type "Remote desktop" in gateway mode with address `https://desktop.gemeente.nl/guacamole/#/client/werkplek` +- **WHEN** Pieter clicks it +- **THEN** the gateway opens, and the gateway signs him in through the organisation's identity provider + +### Requirement: A tile can start single sign-on into a company app (REQ-TLT-003) + +An administrator MUST be able to define identity-provider launch templates, each an https address containing `{appId}`. A tile of link type `sso` MUST name a template and an app identifier, and MUST open the template with the URL-encoded identifier. LaunchPad MUST NOT pass any token or password. + +#### Scenario: Entra ID app + +- **GIVEN** Noor defined the template "Microsoft Entra ID" as `https://launcher.myapps.microsoft.com/api/signin/{appId}?tenantId=contoso` +- **WHEN** Ella adds a tile "Salarisstrook" of type "Single sign-on app" with template "Microsoft Entra ID" and app id `a1b2c3` and Pieter clicks it +- **THEN** his browser opens `https://launcher.myapps.microsoft.com/api/signin/a1b2c3?tenantId=contoso` +- **AND** Entra ID signs him in with the session from his Nextcloud sign-in + +#### Scenario: Author cannot type an identity-provider address + +- **GIVEN** Ella edits a single sign-on tile +- **WHEN** she looks at the fields +- **THEN** she can pick a template and enter an app id, and there is no free address field + +### Requirement: A tile carries its own link target (REQ-TOB-001) + +Every tile placement MUST accept a link target of `same-tab`, `new-tab` or `side-panel` in its content, set in the tile editor by anyone who may edit the tile. The server MUST reject any other value with HTTP 400 and leave the placement unchanged. + +#### Scenario: Author makes a web tile open in the same tab + +- **GIVEN** Ella has full permission on her dashboard "Mijn werkplek" with a tile "Intranet" pointing at `https://intranet.example.nl` +- **WHEN** she opens the tile editor, sets "Opens in" to "Same tab" and saves +- **THEN** clicking "Intranet" on the Workspace page opens the intranet in the current tab + +#### Scenario: Unknown target is refused + +- **GIVEN** a tile placement on a dashboard Ella may edit +- **WHEN** a client sends `PUT /api/widgets/{placementId}` with `content.linkTarget = "popup"` +- **THEN** the response is 400 and the stored target is unchanged + +### Requirement: A dashboard sets the default target for its tiles (REQ-TOB-002) + +A dashboard MUST accept a default link target. A tile without its own target MUST use the dashboard default, and a dashboard without a default MUST keep the current rule: a web address opens in a new tab and an app opens in the same tab. + +#### Scenario: Dashboard default applies to tiles without their own choice + +- **GIVEN** the group dashboard "Team Burgerzaken" has default target "Same tab" and a tile "Zaaksysteem" with no target of its own +- **WHEN** Pieter clicks "Zaaksysteem" on the Workspace page +- **THEN** it opens in the current tab + +#### Scenario: Upgrade keeps today's behaviour + +- **GIVEN** a dashboard created before this change, with no default and tiles with no target +- **WHEN** a user clicks a tile pointing at `https://example.org` +- **THEN** it opens in a new tab, and an app tile opens in the same tab + +### Requirement: A tile can open its app in a panel beside the tiles (REQ-TOB-003) + +A tile with target `side-panel` MUST open its address in a panel on the Workspace page next to the grid, keep the grid usable, show a close button and an "Open in new tab" link, close on Escape and return focus to the tile. Only one panel MUST be open at a time. + +#### Scenario: Files opens beside the tiles + +- **GIVEN** Ella's dashboard has a tile "Bestanden" linking to the Files app with target "Panel beside the tiles" +- **WHEN** she clicks "Bestanden" +- **THEN** the Files app shows in a panel next to her tiles, and the tiles stay visible and clickable +- **AND WHEN** she presses Escape, the panel closes and focus is back on "Bestanden" + +#### Scenario: Opening a second tile replaces the panel + +- **GIVEN** the panel shows "Bestanden" +- **WHEN** Ella clicks a second panel tile "Agenda" +- **THEN** the panel shows the Calendar app and no second panel appears + +### Requirement: The panel only frames allowed pages (REQ-TOB-004) + +The panel MUST frame a Nextcloud address on the same instance, and MUST frame an outside address only when its host is on the embed allow-list (`iframe_allowed_hosts`). Otherwise, or when the page refuses to be framed, the panel MUST show a fallback card with the page title and an "Open in new tab" link, never an empty frame. + +#### Scenario: Outside host not on the allow-list + +- **GIVEN** the allow-list holds only `kaart.example.nl` and a tile points at `https://portal.example.com` with target "Panel beside the tiles" +- **WHEN** Pieter clicks the tile +- **THEN** the panel shows the fallback card "This page could not be loaded." with "Open in new tab" + +#### Scenario: Editor explains why the panel is unavailable + +- **GIVEN** Ella edits a tile pointing at `https://portal.example.com`, whose host is not on the allow-list +- **WHEN** she opens "Opens in" +- **THEN** "Panel beside the tiles" is disabled with the text "This address cannot open in the panel." + +### Requirement: Quick search opens a tile the way a click does (REQ-TOB-005) + +Activating a tile from quick search MUST use the same resolved target as clicking the tile, including the side panel. + +#### Scenario: Search result opens in the panel + +- **GIVEN** a tile "Bestanden" with target "Panel beside the tiles" +- **WHEN** Pieter types "best" in the quick-search box and presses Enter on "Bestanden" +- **THEN** the Files app opens in the panel beside the tiles + +### Requirement: A tile can be an app tile with only its icon (REQ-ICT-001) + +A tile placement with `content.iconOnly: true` SHALL render as an app tile: a square in the tile's colour, as wide as +one grid column, with the tile's icon in white at about 45% of the square and no printed label, card, header or +padding around it. The tile's title SHALL be its accessible name and its tooltip. In edit mode the tile SHALL have its +own drag handle and widget menu and SHALL move and resize like any widget. With `content.pinned: true` it SHALL show a +pin at the top left. The marks SHALL be decorative (`aria-hidden`); what they say SHALL be part of the accessible name +("Zaaksysteem, 14 open", "Raadsinformatie, storing"). + +#### Scenario: Six app tiles under Mijn apps + +- **GIVEN** Pieter's dashboard holds a Tussenkop "Mijn apps" and six icon-only tiles +- **WHEN** he opens the dashboard +- **THEN** each tile is a coloured square with a white icon and no visible name +- **AND** hovering Zaaksysteem shows the tooltip "Zaaksysteem", and a screen reader reads its name + +#### Scenario: Four tiles per row on a phone + +- **GIVEN** the same dashboard at 390 px wide +- **WHEN** it renders +- **THEN** the app tiles stand four to a row + +### Requirement: An app tile shows a live count (REQ-ICT-002) + +An icon-only tile MAY name a count source in `content.countSource`: + +- `{"type": "register", "register": …, "schema": …, "filter": {…}}`: the number of OpenRegister objects the viewer may + read that match the filter, asked with the viewer's own session; the filter value `@me` stands for the viewer; +- `{"type": "nc-widget", "widgetId": …}`: the number of items a Nextcloud dashboard widget (API v2) returns for the + viewer. + +The count SHALL show as a white pill at the top right, "99+" above 99, and SHALL NOT show when it is 0 or the source +does not answer. The tile SHALL refresh the count when the dashboard refreshes, at most once a minute. A count source +whose app is not installed SHALL show no pill and no error. + +#### Scenario: Open cases on the Zaaksysteem tile + +- **GIVEN** a tile Zaaksysteem with `countSource` type register, register `dossiq`, schema `case`, filter `{"assignee": "@me", "isFinalStatus": false}` +- **AND** 14 open cases are assigned to Pieter +- **WHEN** Pieter opens the dashboard +- **THEN** the tile shows the pill "14" + +#### Scenario: The source app is missing + +- **GIVEN** the same tile on an instance without the register `dossiq` +- **WHEN** the dashboard renders +- **THEN** the tile shows no pill and no error + +### Requirement: An app tile shows an outage (REQ-ICT-003) + +When the tile's health ping (service-health-ping) reports the service down, an icon-only tile SHALL show a red dot at +the top right in place of the count, and its accessible name SHALL say the service is down since the time of the +first failed check. When the service answers again, the dot SHALL go and the count SHALL return. + +#### Scenario: Raadsinformatie is down + +- **GIVEN** the tile Raadsinformatie has a health ping and its last checks failed since 09:12 +- **WHEN** Pieter opens the dashboard +- **THEN** the tile shows the red dot and no count +- **AND** its accessible name reads "Raadsinformatie, storing sinds 09:12" + +### Requirement: The tile colour is one of eight theme colours (REQ-ICT-004) + +The tile form (board LpTegelBewerken, "Kleur") SHALL offer the colour as a radio group of eight swatches, one per +theme token: `--sc-primary`, `--sc-primary-deep`, `--sc-accent`, `--sc-accent-deep`, `--sc-work-ink`, +`--sc-work-text`, `--sc-work-muted`, `--sc-work-field`, each previewing the white icon. The tile SHALL store the +token name (`content.colourToken`) and SHALL render through the token, so the colour follows the theme. Each swatch +SHALL have a name for screen readers. A tile that stores a hex colour SHALL keep rendering it. When a theme adds +tokens, the palette MAY grow; a token the theme does not define SHALL fall back to `--sc-primary`. + +#### Scenario: Pieter colours Zaaksysteem + +- **GIVEN** Pieter edits the tile Zaaksysteem +- **WHEN** he chooses the swatch for the primary colour and saves +- **THEN** the tile stores `colourToken: "--sc-primary"` and renders in the theme's primary colour with a white icon + +#### Scenario: The theme changes + +- **GIVEN** a tile with `colourToken: "--sc-accent"` +- **WHEN** the administrator switches the instance theme +- **THEN** the tile takes the new theme's accent colour without being edited + ## Non-Functional Requirements - **Performance**: GET /api/tiles MUST return within 300ms for users with up to 100 tiles. diff --git a/openspec/specs/video-widget/screens.md b/openspec/specs/video-widget/screens.md new file mode 100644 index 000000000..54d3ac3bd --- /dev/null +++ b/openspec/specs/video-widget/screens.md @@ -0,0 +1,3 @@ +# Screens + +- LpIntranet https://identity.conduction.nl/screens/board?id=launchpad/LpIntranet diff --git a/openspec/specs/video-widget/spec.md b/openspec/specs/video-widget/spec.md index 1b2da79e1..d5bae8741 100644 --- a/openspec/specs/video-widget/spec.md +++ b/openspec/specs/video-widget/spec.md @@ -31,9 +31,9 @@ The `content` object carries these fields: ### Requirement: REQ-VID-001 Register Video Widget with Nextcloud Dashboard API The system MUST register a video widget with Nextcloud's Dashboard API so it appears in widget discovery and can be added to dashboards. -@e2e exclude widget registration tested via widget-in-picker scenario #### Scenario: Widget is discovered in the widget list +@e2e exclude never built: the archived change openspec/changes/archive/2026-05-03-video-widget/tasks.md left it unchecked and `git log --all -S VideoWidgetProvider -- lib` is empty; `video` is a LaunchPad placement type registered client-side by nc-vue, not an IManager widget, so GET /api/widgets has no `launchpad_video`; no unit test exists - GIVEN Nextcloud has the Dashboard Widget API enabled - WHEN a user navigates to the dashboard widget picker via LaunchPad - THEN GET /api/widgets MUST include a widget with `id: "launchpad_video"`, `title: "Video"`, and an icon @@ -41,18 +41,21 @@ The system MUST register a video widget with Nextcloud's Dashboard API so it app - AND the widget MUST implement `OCP\Dashboard\IWidget` #### Scenario: Widget metadata is localized +@e2e exclude never built: the archived change openspec/changes/archive/2026-05-03-video-widget/tasks.md left it unchecked and `git log --all -S VideoWidgetProvider -- lib` is empty; there is no IWidget title and the description string exists nowhere in src/, lib/ or l10n/; no unit test exists - GIVEN the video widget is registered - WHEN a user requests the widget list - THEN the widget title MUST be localized to English ("Video") and Dutch ("Video") - AND the description MUST be localized (English: "Embed video from YouTube, Vimeo, PeerTube, or Nextcloud Files") #### Scenario: Widget icon is visually distinct +@e2e exclude never built: there is no IWidget icon and no img/widgets/ directory (img/widgets/video.svg does not exist, and the AND names that file); the type is registered client-side by nc-vue with the MDI icon name `Video` (CnVideoWidget/index.js), which CnAddWidgetModal draws in front of its type select, while the Add widget picker (src/modals/WidgetPickerModal.vue) shows a LaunchPad type as its title and a Plus action only; no unit test exists - GIVEN the video widget is displayed in the widget picker - WHEN rendered alongside other widgets - THEN the icon MUST be a clear video-player symbol (play button or film reel) - AND the icon file MUST be stored at `img/widgets/video.svg` #### Scenario: Widget registration occurs on app boot +@e2e exclude never built: the archived change openspec/changes/archive/2026-05-03-video-widget/tasks.md left it unchecked and `git log --all -S VideoWidgetProvider -- lib` is empty; nothing registers a video widget with OCP\Dashboard\IManager, and app boot has no browser-visible effect; no unit test exists - GIVEN the LaunchPad app is installed and enabled - WHEN Nextcloud boots and initializes app managers - THEN `VideoWidgetProvider::load()` MUST be called by Nextcloud's AppManager @@ -61,7 +64,6 @@ The system MUST register a video widget with Nextcloud's Dashboard API so it app ### Requirement: REQ-VID-002 Store Video Widget Configuration per Placement The widget placement's `widgetContent` JSON MUST store source type, URL/file ID, and display options. -@e2e exclude video widget config stored via REST widget-placement API — Newman scope #### Scenario: Widget stores YouTube URL - GIVEN a user adds the video widget to their dashboard @@ -118,7 +120,6 @@ The widget placement's `widgetContent` JSON MUST store source type, URL/file ID, ### Requirement: REQ-VID-003 Support Multiple Video Source Types The widget MUST handle YouTube, Vimeo, PeerTube, and Nextcloud Files as distinct source types with appropriate rendering logic. -@e2e exclude support multiple video source types tests Vue computed embed-URL logic — Vitest component scope; server-side URL parsing covered by Newman #### Scenario: YouTube URL is normalized to embed form - GIVEN a user submits raw YouTube URLs in various formats: @@ -137,6 +138,7 @@ The widget MUST handle YouTube, Vimeo, PeerTube, and Nextcloud Files as distinct - THEN the video ID `12345` MUST be extracted and returned as `https://player.vimeo.com/video/12345` #### Scenario: PeerTube URL is preserved and validated +@e2e exclude the allow-list check its second AND requires was never built (no `video_widget_allowed_domains` setting in lib/ or src/, `git log --all -S video_widget_allowed_domains -- lib src` is empty), so no PeerTube domain can be shown refused; the extraction itself is built (VideoParsingService::parsePeerTube behind POST /api/widgets/video/parse) and pinned by tests/Unit/Service/VideoParsingServiceTest.php::testAVideoUrlIsParsedToItsCanonicalEmbed (the `peertube watch` and `peertube videos/watch` cases) - GIVEN a PeerTube instance URL like `https://peertube.example.com/w/abc123` - WHEN `VideoParsingService::parsePeerTubeUrl()` processes it - THEN the domain and UUID/path MUST be extracted and validated as a PeerTube-compatible embed form @@ -154,9 +156,9 @@ The widget MUST handle YouTube, Vimeo, PeerTube, and Nextcloud Files as distinct ### Requirement: REQ-VID-004 Enforce Admin-Controlled Domain Allowlist The system MUST prevent embedding videos from arbitrary domains unless explicitly allowed by the administrator. -@e2e exclude enforce admin-controlled domain allow-list tests PHP config + IAppConfig — Newman scope #### Scenario: Allowed domains setting exists +@e2e exclude never built: no `launchpad.video_widget_allowed_domains` setting, default or admin settings field exists in lib/ or src/ (`git log --all -S video_widget_allowed_domains -- lib src` is empty); no unit test exists - GIVEN no `launchpad.video_widget_allowed_domains` setting is configured - WHEN the system boots - THEN the default allowlist MUST be: @@ -166,17 +168,20 @@ The system MUST prevent embedding videos from arbitrary domains unless explicitl - AND the admin MUST be able to override this via LaunchPad admin settings page #### Scenario: Widget save rejects disallowed domain +@e2e exclude never built: the domain allow-list it configures does not exist (no setting, no server-side check; placements are stored verbatim by WidgetApiController::contentToPersist); no unit test exists - GIVEN admin has set `launchpad.video_widget_allowed_domains` to only `["youtube.com", "www.youtube.com", "youtu.be"]` - WHEN a user attempts to save a widget with `sourceType: 'vimeo'` and `videoUrl: 'https://vimeo.com/12345'` - THEN the backend MUST return HTTP 400 with error message (English): "Domain not allowed by administrator" - AND the widget MUST NOT be created/updated #### Scenario: Admin adds a custom PeerTube instance to allowlist +@e2e exclude never built: there is no allow-list setting or admin settings field to add a domain to; no unit test exists - GIVEN admin edits LaunchPad settings to add `"peertube.example.com"` to the allowed list - WHEN a user submits a widget with `sourceType: 'peertube'` and `videoUrl: 'https://peertube.example.com/w/abc123'` - THEN the domain check MUST succeed and the widget MUST be saved #### Scenario: Widget render shows domain-blocked error +@e2e exclude never built: with no allow-list there is no blocked domain, and the string "Video domain is no longer allowed by administrator" exists nowhere in src/, nc-vue or l10n/; no unit test exists - GIVEN an existing widget placement with a video URL from a now-blocked domain - WHEN the dashboard is rendered - THEN the widget MUST display an error message (English): "Video domain is no longer allowed by administrator" @@ -192,7 +197,6 @@ The system MUST prevent embedding videos from arbitrary domains unless explicitl ### Requirement: REQ-VID-005 Parse and Validate Video URLs Server-Side The backend MUST extract video IDs from user-provided URLs and validate format before storage. -@e2e exclude parse and validate video URLs server-side tests PHP VideoUrlParser — Newman scope #### Scenario: URL parsing endpoint is available - GIVEN a user is editing a widget config in the frontend @@ -207,6 +211,7 @@ The backend MUST extract video IDs from user-provided URLs and validate format b - THEN it MUST return HTTP 400 with `{"isValid": false, "error": "Invalid URL format"}` #### Scenario: Domain validation happens at parse time +@e2e exclude never built: the parse endpoint exists (POST /api/widgets/video/parse, cited by url-parsing-endpoint-is-available) but the domain allow-list it would check does not (no `video_widget_allowed_domains` setting in lib/ or src/), so no domain is blocked and "Domain not allowed by administrator" exists nowhere in lib/; no unit test exists - GIVEN a user submits a URL from a blocked domain - WHEN POST /api/widgets/video/parse is called - THEN it MUST return `{"isValid": false, "error": "Domain not allowed by administrator"}` @@ -227,7 +232,6 @@ The backend MUST extract video IDs from user-provided URLs and validate format b ### Requirement: REQ-VID-006 Check File Access Control for Nextcloud Files When `sourceType` is `nc-file`, the system MUST verify the viewing user can read the file before allowing playback. -@e2e exclude check file ACL tests PHP ACL + streaming endpoint — Newman scope #### Scenario: File is readable by viewer - GIVEN a widget with `sourceType: 'nc-file'` and `fileId: 12345` @@ -266,7 +270,6 @@ When `sourceType` is `nc-file`, the system MUST verify the viewing user can read ### Requirement: REQ-VID-007 Use iframe with CSP-Safe Sandbox Attributes Hosted video platforms (YouTube, Vimeo, PeerTube) MUST be embedded via iframe with strict sandbox restrictions. -@e2e exclude iframe with CSP-safe sandbox attributes tests HTML attribute rendering — requires a placed video widget; seeded state not in CI fixture #### Scenario: YouTube iframe uses proper sandbox - GIVEN a widget with `sourceType: 'youtube'` and canonical URL `https://www.youtube.com/embed/ABC123` @@ -302,7 +305,6 @@ Hosted video platforms (YouTube, Vimeo, PeerTube) MUST be embedded via iframe wi ### Requirement: REQ-VID-008 Respect Autoplay, Muting, and Loop Settings The widget MUST apply user-selected playback options while respecting browser autoplay policies. -@e2e exclude autoplay/muting/loop settings test HTML video attribute rendering — requires a placed video widget #### Scenario: Autoplay with muted enforces mute - GIVEN a user sets `autoplay: true` and `muted: false` @@ -339,7 +341,6 @@ The widget MUST apply user-selected playback options while respecting browser au ### Requirement: REQ-VID-009 Enforce Aspect Ratio via CSS The widget MUST apply the configured aspect ratio using modern CSS and fallback techniques. -@e2e exclude aspect ratio CSS tests CSS padding-bottom trick — visual regression scope #### Scenario: Aspect ratio options - GIVEN a user selects `aspectRatio` from a dropdown @@ -354,6 +355,7 @@ The widget MUST apply the configured aspect ratio using modern CSS and fallback - AND the iframe/video MUST stretch to fill: `width: 100%; height: 100%;` #### Scenario: Aspect ratio padding fallback +@e2e exclude needs a browser without CSS aspect-ratio support, which the CI fixture's Chromium is not, and the fallback and its sentinel class were never built (CnVideoWidget.vue renders only `aspect-ratio`); no unit test exists - GIVEN a widget needs to support older browsers - WHEN the container doesn't support `aspect-ratio` CSS - THEN the backend SHOULD render a fallback with `padding-bottom: calc(9 / 16 * 100%)` technique @@ -368,7 +370,6 @@ The widget MUST apply the configured aspect ratio using modern CSS and fallback ### Requirement: REQ-VID-010 Support No-Cookie YouTube Embedding The system MUST support an optional admin setting to enable YouTube no-cookie embedding to reduce tracking. -@e2e exclude no-cookie YouTube embedding tests URL-transform logic in PHP — Newman scope #### Scenario: No-cookie setting default - GIVEN `launchpad.video_widget_use_nocookie_youtube` is not configured @@ -377,18 +378,21 @@ The system MUST support an optional admin setting to enable YouTube no-cookie em - AND YouTube's tracking cookies MUST be enabled by default #### Scenario: Admin enables no-cookie mode +@e2e exclude never built: no `launchpad.video_widget_use_nocookie_youtube` setting exists in lib/ or src/ (`git log --all -S video_widget_use_nocookie -- lib src` is empty; only the CSP allows youtube-nocookie.com); no unit test exists - GIVEN admin sets `launchpad.video_widget_use_nocookie_youtube = true` - WHEN a widget with `sourceType: 'youtube'` is created - THEN the system MUST rewrite the embed URL to: `https://www.youtube-nocookie.com/embed/ABC123` - AND the no-cookie domain MUST be used for all subsequent renders #### Scenario: Existing widgets respect no-cookie toggle +@e2e exclude never built: there is no no-cookie setting to toggle and no render-time rewrite; no unit test exists - GIVEN an existing widget with URL `https://www.youtube.com/embed/ABC123` - WHEN the admin toggles `use_nocookie_youtube` from false to true - THEN on next render, the URL MUST be dynamically rewritten to `youtube-nocookie.com` if applicable - NOTE: Stored URL is `www.youtube.com`; render-time transformation happens via controller logic #### Scenario: No-cookie does not affect Vimeo/PeerTube +@e2e exclude never built: there is no no-cookie setting to toggle; no unit test exists - GIVEN widgets with `sourceType: 'vimeo'` or `sourceType: 'peertube'` - WHEN the no-cookie setting is toggled - THEN only YouTube URLs are affected @@ -397,7 +401,6 @@ The system MUST support an optional admin setting to enable YouTube no-cookie em ### Requirement: REQ-VID-011 Display Appropriate Empty and Error States The widget MUST show user-friendly messages for missing config, access issues, and invalid domains. -@e2e exclude display appropriate empty and error states tests Vue state inside placed widget — requires seeded placement #### Scenario: Empty state - no video configured - GIVEN a widget placement with `sourceType: null` or missing `videoUrl`/`fileId` @@ -414,6 +417,7 @@ The widget MUST show user-friendly messages for missing config, access issues, a - AND the save button MUST be disabled #### Scenario: Domain not allowed error +@e2e exclude never built: with no domain allow-list nothing defines a blocked domain, and neither the parse endpoint nor the "Domain not allowed by administrator" message exists; no unit test exists - GIVEN a user attempts to save a widget with a blocked domain - WHEN the parse endpoint is called - THEN it MUST return `{"isValid": false, "error": "Domain not allowed by administrator"}` diff --git a/openspec/specs/widgets/screens.md b/openspec/specs/widgets/screens.md new file mode 100644 index 000000000..ebc9da4b7 --- /dev/null +++ b/openspec/specs/widgets/screens.md @@ -0,0 +1,6 @@ +# Screens + +- LpWidgetKiezen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetKiezen +- LpManagement https://identity.conduction.nl/screens/board?id=launchpad/LpManagement +- LpWidgetInstellen https://identity.conduction.nl/screens/board?id=launchpad/LpWidgetInstellen +- LpBewerken https://identity.conduction.nl/screens/board?id=launchpad/LpBewerken diff --git a/openspec/specs/widgets/spec.md b/openspec/specs/widgets/spec.md index f5ea6db82..aa13b9b92 100644 --- a/openspec/specs/widgets/spec.md +++ b/openspec/specs/widgets/spec.md @@ -14,8 +14,6 @@ Widgets are the primary content blocks on LaunchPad dashboards. LaunchPad integr ## Data Model -@e2e exclude all 89 scenarios test REST widget-discovery/placement/update/batch API — widget add/edit UI flows are covered by the widget-specific specs (label-widget, text-display-widget, image-widget etc.) - ### Widget Discovery Widgets are discovered at runtime from Nextcloud's `IManager::getWidgets()`. Each widget provides: - **id**: Widget identifier (e.g., `weather_status`, `recommendations`) @@ -43,7 +41,9 @@ Widgets are discovered at runtime from Nextcloud's `IManager::getWidgets()`. Eac - **tileTitle**, **tileIcon**, **tileIconType**, **tileBackgroundColor**, **tileTextColor**, **tileLinkType**, **tileLinkValue**: Tile-specific fields stored directly on the placement (nullable STRING) - **createdAt**: Timestamp string (DATETIME) - **updatedAt**: Timestamp string (DATETIME) + ## Requirements + ### Requirement: Discover Available Widgets (REQ-WDG-001) The system MUST provide an API to list all Nextcloud dashboard widgets available for placement. @@ -136,6 +136,7 @@ Users MUST be able to place a discovered widget onto their dashboard with grid c - WHEN the user sends POST /api/dashboard/5/widgets with `gridX: 10, gridWidth: 4` (exceeds column count) - THEN the system SHOULD return HTTP 400 with a validation error - NOTE: Grid bounds validation is NOT currently implemented in the backend. GridStack on the frontend handles constraint enforcement. +@e2e exclude never built: no bounds check exists, WidgetApiController::addWidget passes the coordinates to PlacementService::addWidget, whose freeSpot() moves a placement that does not fit instead of refusing it (lib/Service/PlacementService.php); placement on a free spot is cited under add-a-widget-to-a-dashboard #### Scenario: Add widget with non-existent widgetId - GIVEN widget "fake_widget" is not registered in Nextcloud @@ -258,11 +259,13 @@ Widget placements MUST maintain a sort order for consistent rendering and tab na - GIVEN dashboard id 5 has placements with sortOrder 1 (weather), 2 (notes), 3 (calendar) - WHEN the user rearranges them so calendar is first - THEN sortOrder MUST be updated to: calendar (1), weather (2), notes (3) +@e2e exclude never built: no write path renumbers a placement's sort_order on a rearrange, the batch save (WidgetPlacementMapper::updatePosition) writes only grid_x, grid_y, grid_width and grid_height, `sortOrder` is not an accepted PUT field (RequestDataExtractor) and the grid orders by position; sort_order is set only when a placement is created or copied (PlacementPayloadHydrator, WidgetPlacementMapper clone) #### Scenario: Sort order used for tab navigation - GIVEN a dashboard with multiple placements ordered by sortOrder - WHEN the user presses Tab in view mode - THEN focus MUST move through widgets in sortOrder sequence +@e2e exclude no write path sets a placement's sortOrder (not a PUT field in lib/Controller/RequestDataExtractor.php, not written by WidgetPlacementMapper::updatePositions), so a dashboard ordered by sortOrder cannot be arranged; never built (see widgets::reorder-widgets, test.fixme), and no unit test pins tab order ### Requirement: Batch Update Placements (REQ-WDG-008) @@ -319,6 +322,15 @@ The frontend MUST use a layered rendering architecture: `DashboardGrid` -> `Widg - AND render `TileWidget` directly instead of `WidgetWrapper` - AND WidgetWrapper applies transparent background and no padding for tile-type widgetIds +#### Scenario: Chart, stat and table widgets pass through to the nextcloud-vue renderers +- GIVEN OpenRegister is installed and an author places a `chart`, `stats-block`, `stat`, `gauge`, `delta` or `table` widget whose content names an OpenRegister data source +- WHEN the widget is rendered +- THEN `chart` MUST render through `ChartHost.vue` onto nextcloud-vue's `CnChartWidget`, and `stats-block` through `StatsBlockHost.vue` onto `CnStatsBlockWidget` (`RENDERER_OVERRIDES` in `src/constants/widgetRegistry.js`) +- AND `stat`, `gauge`, `delta` and `table` MUST use the nextcloud-vue registry renderer unchanged +- AND the figures MUST come from the OpenRegister data source through nextcloud-vue (specs `nextcloud-vue/widget-renderer` and `openregister/aggregation-api`), not from a LaunchPad endpoint +- AND each of these types MUST be listed in `lib/widget-types.json` so it appears in the widget picker +@e2e exclude needs an OpenRegister register, schema and objects seeded as a data source, and the clauses name internal component wiring (ChartHost/StatsBlockHost onto CnChartWidget/CnStatsBlockWidget, RENDERER_OVERRIDES) and a source file; pinned by src/components/Widgets/Renderers/__tests__/chartAndStatsHosts.spec.js and src/constants/__tests__/widgetRegistry.completeness.spec.js + ### Requirement: Widget Picker (REQ-WDG-010) The widget picker MUST be implemented as a single modal that handles both creation and editing flows. The modal MUST present a type selector at the top (unless a type was preselected by the caller) followed by the per-type configuration sub-form for the currently selected type. Submit MUST emit `{type, content}` where `content` carries only the fields relevant to the selected type — fields belonging to other types MUST NOT be included. @@ -328,7 +340,7 @@ The widget picker MUST be implemented as a single modal that handles both creati - GIVEN no widget is being edited and no type was preselected - WHEN the user opens the modal with `show=true, preselectedType=null, editingWidget=null` - THEN the modal MUST render a `<select>` listing every registered widget type -- AND the form area MUST render the sub-form for the first type (alphabetical or registry order) +- AND the form area MUST render the sub-form for the `initialType` the host passed (the type picked in the widget picker), or for the first type (alphabetical or registry order) when none was passed - AND the action button MUST read `t('Add')` #### Scenario: Open in create mode with preselected type @@ -338,6 +350,7 @@ The widget picker MUST be implemented as a single modal that handles both creati - THEN the type `<select>` MUST NOT be visible - AND the form area MUST render the text sub-form - AND the action button MUST read `t('Add')` +@e2e exclude no LaunchPad control opens the modal with a preselected type: the toolbar dropdown is gone and Views.vue openCustomWidgetModal() is only ever called without one (Views.vue:3109); pinned by src/views/__tests__/ViewsEditorsAndRowActions.spec.js ("opens in create mode with the preselected type") #### Scenario: Open in edit mode @@ -363,6 +376,17 @@ The widget picker MUST be implemented as a single modal that handles both creati - THEN the modal MUST emit `submit({type: 'text', content: {text: 'Hello', fontSize: '16px'}})` - AND `content` MUST NOT contain image fields like `url`, `alt`, etc. +#### Scenario: One entry point adds every kind of widget + +- GIVEN a user who may edit the dashboard +- WHEN they open the More menu or a dashboard's row menu +- THEN there MUST be one "Add widget" entry, and no separate "Add custom widget" entry +- AND "Add widget" MUST open the widget picker, which lists the Nextcloud widgets, the apps and, under "Widgets from Launchpad", each Launchpad widget type (Text, Image, News and the rest) +- AND picking a Launchpad type MUST close the picker and open the custom widget form in create mode on that type, with its type select still visible and changeable +- AND a search MUST filter the Launchpad types by name, as it filters the other widgets + +Decided on 22 Nov 2026 (Ruben): two add buttons for one job confused people; the board LpWidgetKiezen draws one "Add widget" window that lists the Launchpad widgets in it. + #### Scenario: Widget picker displays available widgets - GIVEN the user wants to add a widget - WHEN the widget picker opens via `WidgetPicker.vue` @@ -469,6 +493,7 @@ The set of supported widget types MUST come from a single in-frontend registry t - AND the modal type selector MUST list it - AND the grid renderer MUST render placements of the new type - AND no other UI code MUST need to be changed to support the new type +@e2e exclude a developer adding a registry entry is a source change, not a runtime action; pinned by src/constants/__tests__/widgetRegistry.completeness.spec.js and src/constants/__tests__/widgetRegistry.spec.js #### Scenario: Registry is the single source of truth @@ -476,6 +501,7 @@ The set of supported widget types MUST come from a single in-frontend registry t - WHEN any consumer (toolbar, modal, renderer) enumerates widget types - THEN it MUST list those 5 types - AND MUST NOT hard-code any type name elsewhere in the codebase +@e2e exclude a claim about the source (no hard-coded type names) checked by grep, not by a browser; the registry no longer has 5 entries (lib/widget-types.json lists 38); pinned by src/constants/__tests__/widgetRegistry.completeness.spec.js ### Requirement: Right-click context menu in edit mode (REQ-WDG-015) @@ -542,6 +568,7 @@ The popover MUST close when the user clicks anywhere outside its bounding box (i - WHEN the unmount lifecycle runs - THEN the document-level `click` listener MUST be removed - AND no popover state MUST leak into a subsequent mount +@e2e exclude a document-level listener's removal on unmount is not observable from a browser test; pinned by src/composables/__tests__/useGridManager.spec.js ("REQ-WDG-016: detach removes the document click listener (no leaks across mounts)") ### Requirement: Position constraints (REQ-WDG-017) @@ -678,7 +705,7 @@ The widget registry (`src/constants/widgetRegistry.js`) MUST include a `tile` wi - Suppresses click handling while the dashboard is in edit mode (consistent with REQ-WDG-014) - Has `defaultContent: {title:'', icon:'', iconType:'class', backgroundColor:'#3b82f6', textColor:'#ffffff', linkType:'app', linkValue:''}` -The tile widget type MUST be selectable from the unified "Add custom widget" picker (REQ-WDG-010) and surfaced alongside `label`, `text`, `image`, `link`, and `nc-widget`. +The tile widget type MUST be selectable from the custom widget form that "Custom widget" in the widget picker opens (REQ-WDG-010) and surfaced alongside `label`, `text`, `image`, `link`, and `nc-widget`. #### Scenario: Tile widget appears in the picker @@ -703,6 +730,8 @@ The tile widget type MUST be selectable from the unified "Add custom widget" pic ### Requirement: REQ-WDG-023 Widget registry completeness verifiable in CI +@e2e exclude these scenarios are about the Vitest suite failing on a broken registry, not about runtime behaviour; pinned by src/constants/__tests__/widgetRegistry.completeness.spec.js itself (EXPECTED_TYPES set equality, listWidgetTypes surfacing, required-field checks) + The widget registry (`src/constants/widgetRegistry.js`) MUST be covered by an explicit completeness test (`src/constants/__tests__/widgetRegistry.completeness.spec.js`) that asserts a canonical EXPECTED_TYPES set: - `calendar`, `container`, `divider`, `files`, `header`, `image`, `label`, `link`, `links`, `menu`, `nc-widget`, `news`, `people`, `quicklinks`, `text`, `tile`, `video` (current set; updated when widget capabilities are added or removed) @@ -899,6 +928,7 @@ The popover MUST close when the user clicks anywhere outside its bounding box (i - WHEN the unmount lifecycle runs - THEN the document-level `click` listener MUST be removed - AND no popover state MUST leak into a subsequent mount +@e2e exclude a document-level listener's removal on unmount is not observable from a browser test; pinned by src/composables/__tests__/useGridManager.spec.js ("REQ-WDG-016: detach removes the document click listener (no leaks across mounts)") ### Requirement: REQ-WDG-017 Position constraints @@ -945,6 +975,150 @@ The workspace MUST render the dashboard canvas as its only content region. There - **THEN** every available widget MUST be listed there - **AND** selecting one MUST place it on the active dashboard +### Requirement: The widget picker narrows its list as you type (REQ-WDG-028) + +The widget picker MUST show a search box above the list of widgets and apps you may add. Typing MUST narrow both lists to the entries whose title contains the typed text, ignoring case. Clearing the box MUST bring back the full lists. When nothing matches, the picker MUST say so instead of showing empty lists. + +#### Scenario: Typing narrows the list + +- **GIVEN** Pieter opens "Add widget" on his dashboard +- **WHEN** he types "cal" in "Search widgets" +- **THEN** the picker lists only the widgets and apps whose title contains "cal", such as "Calendar" + +#### Scenario: Clearing the search + +- **GIVEN** Pieter typed "cal" in "Search widgets" +- **WHEN** he clears the search box +- **THEN** the picker lists every widget and app again + +#### Scenario: Nothing matches + +- **GIVEN** Pieter opens "Add widget" +- **WHEN** he types "zzz" +- **THEN** the picker says that no widget matches +- **AND** it shows no empty list + +### Requirement: A Nextcloud widget with a reload interval refreshes itself (REQ-WDG-029) + +When a Nextcloud dashboard widget declares a reload interval above zero, LaunchPad MUST fetch its items again at that interval while the widget is on the page. The page MUST NOT reload. The timer MUST stop when the widget leaves the page. A widget without a reload interval MUST load its items once. + +#### Scenario: Items refresh on the widget's interval + +- **GIVEN** a widget on Pieter's dashboard declares a reload interval of 60 seconds +- **WHEN** 60 seconds pass with the dashboard open +- **THEN** the widget shows its items fetched again +- **AND** the page itself does not reload + +#### Scenario: No interval, no refresh + +- **GIVEN** a widget declares a reload interval of 0 +- **WHEN** Pieter keeps the dashboard open +- **THEN** the widget loads its items once and does not fetch them again + +#### Scenario: Leaving the dashboard stops the timer + +- **GIVEN** a widget with a reload interval is on the page +- **WHEN** Pieter switches to another dashboard +- **THEN** the widget's refresh timer stops + +### Requirement: Another app's widget shows that app's items for the viewer (REQ-WDG-030) + +@e2e exclude needs the Mail and Deck apps, which the CI instance (NC 32 + openregister) does not have; no Mail- or Deck-specific test exists — the generic item path is pinned by tests/Unit/Service/WidgetItemLoaderTest.php and the nc-widget list rendering by tests/e2e/widgets-nc-widget.spec.ts + +When a person places a widget that another Nextcloud app registers, such as the Mail app's mailbox widget or Deck's upcoming cards, LaunchPad MUST ask that app for the items it holds for the viewer and list them with their title, subtitle and icon. Each item MUST link to the item in its own app. When the app returns no items, the widget MUST show the app's own empty message. + +#### Scenario: A mailbox preview + +- **GIVEN** the Mail app is enabled and Pieter placed its mailbox widget on "Mijn werkplek" +- **WHEN** he opens the Workspace page +- **THEN** the widget lists his latest messages with sender and subject +- **AND** clicking a message opens it in Mail + +#### Scenario: Open tasks from a planning app + +- **GIVEN** Deck is enabled and Sanne placed its upcoming cards widget on her dashboard +- **WHEN** she opens the Workspace page +- **THEN** the widget lists the cards assigned to her with their due dates +- **AND** clicking a card opens it in Deck + +#### Scenario: Nothing to show + +- **GIVEN** Pieter's mailbox has no messages the Mail widget returns +- **WHEN** he opens the Workspace page +- **THEN** the widget shows the empty message the Mail app supplies + +### Requirement: REQ-WDG-031 A section heading widget + +The `section-heading` widget ("Tussenkop", boards `launchpad/LpIntranet` and `launchpad/LpWerkplek`) MUST head the widgets or app tiles that follow it on the grid. It MUST draw a 20px bold title, one 14px muted line of explanation when it has one, and a 1px rule below, on the page ground without a card. A new one MUST span the grid's full width and be one row tall. Its content is `{title, description}`, and its form requires a title. + +The picker MUST offer it as "Section heading" (nl "Tussenkop") among the widgets from Launchpad, with the icon `format-header-1`, to everyone. The Zuiddrecht demo seed heads its groups with it as the boards draw them (Mijn werkplek, Intranet Zuiddrecht, Team Vergunningen), and the start page Vandaag keeps its six app tiles straight on the grid with no heading. The label widget's group heading stays for existing placements; it has no line of explanation, so it is not the Tussenkop. + +#### Scenario: A section heading heads a group +- GIVEN an editor in edit mode +- WHEN they add a Section heading titled "Samenwerken" with the line "De tegels van het team" +- THEN the grid MUST show a full-width heading "Samenwerken" with that line below it and a rule under both, without a card + +@e2e openspec/specs/widgets/spec.md#req-wdg-031 + +### Requirement: Recent work shows where the reader left off (REQ-WDG-032) + +LaunchPad SHALL offer a `recent-work` widget type ("Verder waar u was", boards LpVandaag and LpStart). It SHALL read +the reader's own activity from the Activity app (`GET /ocs/v2.php/apps/activity/api/v2/activity/self`), so what +colleagues did never shows, and SHALL list one row per thing the reader worked on, newest first, at most +`content.limit` rows (default 6). Each row SHALL be named by the thing (the last part of its name), with below it the +app and when: "vanochtend", "vanmiddag" or "vanavond" for today, the weekday within the last week, and the day and +month before that. A row SHALL link to the thing. + +The widget SHALL leave out what the reader deleted, things named only by an id, and activity without a link. The same +thing saved again under a new id SHALL count once. With `content.apps` it SHALL show only those apps' work. When the +Activity app does not answer, the widget SHALL say "Recent work needs the Activity app."; with no activity it SHALL +say "Nothing you worked on recently." + +#### Scenario: Pieter picks up where he left off + +- **GIVEN** this morning Pieter edited "Besluit Woo-verzoek jeugdzorg.docx" twice and on Friday commented on decision "Collegevoorstel Havenpark" +- **WHEN** he opens the start page with the Verder waar u was widget +- **THEN** the widget shows "Besluit Woo-verzoek jeugdzorg.docx" once with "files · vanochtend", then "Collegevoorstel Havenpark" with its app and "vrijdag" + +#### Scenario: A deleted file is not work to pick up + +- **GIVEN** Pieter deleted "concept.docx" an hour ago +- **WHEN** the widget renders +- **THEN** "concept.docx" is not listed + +#### Scenario: Only the apps the author chose + +- **GIVEN** a recent-work widget with `apps: ["files"]` +- **WHEN** the widget renders +- **THEN** it lists only work in Files + +#### Scenario: Without the Activity app + +- **GIVEN** the Activity app is disabled +- **WHEN** the widget renders +- **THEN** it says "Recent work needs the Activity app." + +### Requirement: The search widget can search the internet (REQ-WDG-033) + +A `search` widget with `content.layout: 'web'` SHALL draw an internet search form (board LpWerkplek, "Zoeken op +internet"): a labelled search field, the name of the search engine, a Search button and the line "Opens the results +in a new tab". The engine SHALL be `content.engine` `{name, url}` when its url holds `{q}`, else DuckDuckGo +(`https://duckduckgo.com/?q={q}`). Submitting SHALL open the engine's url with the URL-encoded words in a new tab, +with `noopener` and `noreferrer`; an empty field SHALL do nothing. Without `layout: 'web'` the widget SHALL stay the +tile search of tile-quick-search. + +#### Scenario: Pieter searches the internet + +- **GIVEN** a search widget with `layout: 'web'` and no engine set +- **WHEN** Pieter types "omgevingswet termijnen" and chooses Search +- **THEN** a new tab opens `https://duckduckgo.com/?q=omgevingswet%20termijnen` + +#### Scenario: An engine without a placeholder is ignored + +- **GIVEN** a search widget with `engine: {name: "Intranet", url: "https://intranet.example.nl/search"}` +- **WHEN** the widget renders +- **THEN** it names DuckDuckGo as the engine + ## Non-Functional Requirements - **Performance**: GET /api/widgets MUST return within 1 second even with 50+ registered widgets. Widget item fetching SHOULD be parallelized across widget types. @@ -1003,18 +1177,21 @@ Widgets that implement none of the optional capability interfaces MUST receive t - WHEN `WidgetFormatter::format($widget, $userId)` is called - THEN the result has `itemApiVersions: []`, `buttons: []`, `reloadInterval: 0`, `iconUrl: null`, `itemIconsRound: false` - AND the result still includes the base `id`, `title`, `order`, `iconClass`, `widgetUrl` from the widget +@e2e exclude a PHP formatter contract over mock IWidget implementations, no browser surface; pinned by tests/Unit/Service/WidgetFormatterTest.php::testPlainWidgetGetsTheBaseShapeWithDefaults #### Scenario: Format a widget that implements both API versions - GIVEN an `IWidget` that implements both `IAPIWidget` and `IAPIWidgetV2` - WHEN `WidgetFormatter::format($widget, $userId)` is called - THEN the result has `itemApiVersions: [1, 2]` (in declaration order, V1 first) +@e2e exclude a PHP formatter contract over mock IWidget implementations, no browser surface; pinned by tests/Unit/Service/WidgetFormatterTest.php::testApiVersionsListV1ThenV2 #### Scenario: Format a button widget includes per-button serialization - GIVEN an `IButtonWidget` whose `getWidgetButtons($userId)` returns two buttons (Add: `link=/add`, Settings: `link=/settings`) - WHEN `WidgetFormatter::format($widget, $userId)` is called - THEN `result.buttons` is `[{type: 'Add', text: '...', link: '/add'}, {type: 'Settings', text: '...', link: '/settings'}]` +@e2e exclude a PHP formatter contract over mock IButtonWidget implementations, no browser surface; pinned by tests/Unit/Service/WidgetFormatterTest.php::testButtonsAreAskedForTheUserAndFlattened ### REQ-WDG-025: Widget item loader strategy @@ -1032,18 +1209,21 @@ The result MUST be keyed by widget ID and MUST contain one entry per non-skipped - GIVEN a registered-widgets map containing only `widget-a` - WHEN `loadItems($widgets, $userId, ['widget-a', 'widget-unknown'], 7)` is called - THEN the result contains exactly one key `'widget-a'` (no entry for `'widget-unknown'`) +@e2e exclude a PHP loader contract over mock widgets, no browser surface; pinned by tests/Unit/Service/WidgetItemLoaderTest.php::testUnknownIdsAreSkippedAndOnlyRequestedWidgetsLoad #### Scenario: V2-capable widget uses V2 API - GIVEN a widget that implements both `IAPIWidget` and `IAPIWidgetV2` - WHEN the loader processes that widget - THEN `getItemsV2()` is called (V1 API is NOT called) +@e2e exclude which PHP interface method the loader calls is not observable over HTTP; pinned by tests/Unit/Service/WidgetItemLoaderTest.php::testV2IsPreferredWhenTheWidgetImplementsBoth #### Scenario: Non-API widget gets empty-default envelope - GIVEN a widget that implements neither `IAPIWidget` nor `IAPIWidgetV2` - WHEN the loader processes that widget - THEN the entry for that widget ID is `{items: [], emptyContentMessage: '', halfEmptyContentMessage: ''}` +@e2e exclude needs a registered widget implementing neither item API, which the CI instance cannot be given; pinned by tests/Unit/Service/WidgetItemLoaderTest.php::testWidgetWithoutItemApiGetsAnEmptyEntry ### REQ-WDG-026: Widget item serialization and empty-content messaging @@ -1054,15 +1234,44 @@ The system MUST serialize widget items via `WidgetItem::jsonSerialize()` (both V - GIVEN a V2 widget returning two items + empty message `'No items'` + half-empty message `'Almost empty'` - WHEN the loader processes that widget - THEN the entry has `items: [<2 serialized items>], emptyContentMessage: 'No items', halfEmptyContentMessage: 'Almost empty'` +@e2e exclude needs a V2 widget with fixed items and messages, which the CI instance cannot be given; pinned by tests/Unit/Service/WidgetItemLoaderTest.php::testV2WidgetReturnsSerializedItemsAndMessages #### Scenario: V1 serializes items and returns empty messages - GIVEN a V1 widget returning three items - WHEN the loader processes that widget - THEN the entry has `items: [<3 serialized items>], emptyContentMessage: '', halfEmptyContentMessage: ''` +@e2e exclude needs a V1 widget with fixed items, which the CI instance cannot be given; pinned by tests/Unit/Service/WidgetItemLoaderTest.php::testV1WidgetReturnsSerializedItemsWithEmptyMessages #### Notes (REQ-WDG-024..026) - `applyButtons` reaches into the widget impl per-user; button visibility is a widget-impl concern, not the formatter's. The REQ documents the call site, not the underlying permission model. - Loader's silent-skip of unknown widget IDs means callers cannot distinguish "widget returned no items" from "widget not registered". Future tightening (e.g. return a `null` sentinel for skipped IDs) is deferred — would be a breaking API change. - The V1/V2 empty-message asymmetry is inherent in the Nextcloud `IAPIWidget` contract; V1 callers will always see `emptyContentMessage: ''`. The frontend already special-cases the empty string. + +### Requirement: A widget below the fold loads when it comes into view (REQ-WDG-044) + +On a dashboard in view mode, a widget's content SHALL mount, and so ask its source, only when its card comes within one +viewport height of the visible area, or once the page has settled (2.5 seconds after the card appeared, at the browser's next +idle moment), or when the page is about to print, whichever comes first. Its card (frame, title, place in the grid) SHALL +show from the start. A widget whose content has mounted SHALL stay mounted. In edit mode, in the headless export render +(`?export=1`) and in a browser without IntersectionObserver every widget's content SHALL mount at once. + +#### Scenario: The case list below the fold waits for the reader + +- **GIVEN** Pieter's start page has the case list widget below the fold +- **WHEN** he opens the start page +- **THEN** the widgets on screen ask their sources and the case list does not yet +- **AND** when he scrolls towards the case list it asks its source and shows the cases + +#### Scenario: Everything has loaded before a download + +- **GIVEN** Pieter opened his start page and did not scroll +- **WHEN** the page has settled, or he chooses Download +- **THEN** every widget has mounted, so the printed dashboard shows every widget's content + +#### Scenario: Edit mode shows every widget at once + +- **GIVEN** Pieter edits his start page +- **WHEN** the dashboard shows in edit mode +- **THEN** every widget's content mounts at once diff --git a/openspec/specs/wiki-widget/spec.md b/openspec/specs/wiki-widget/spec.md new file mode 100644 index 000000000..30357841c --- /dev/null +++ b/openspec/specs/wiki-widget/spec.md @@ -0,0 +1,61 @@ +# wiki-widget Specification + +## Purpose +The organisation's wiki on a dashboard: search, the person's favourite pages and the recent pages. + +## Requirements + +### Requirement: The wiki widget shows favourites, recent pages and search (REQ-WIKI-001) + +The `wiki-pages` widget SHALL read pages through OpenRegister's XWiki integration, never with credentials in the +browser. It SHALL show a search field, the person's favourites and the recent pages, at most `limit` each (default +3). Each page SHALL be a link into the wiki that opens in a new tab, with its space as detail. A page address that is +not http(s) SHALL NOT become a link. Typing SHALL search the wiki once typing pauses; a cleared search SHALL show the +favourites and recent pages again. When OpenRegister answers that no XWiki source is set up, the widget SHALL say the +wiki is not connected and ask the person to contact their administrator. + +#### Scenario: Pieter's wiki + +- **GIVEN** the wiki holds "Werkinstructie kapvergunningen", "Termijnen Omgevingswet" and "Legesverordening 2026" +- **WHEN** Pieter opens a dashboard with the Wiki widget +- **THEN** he sees his favourites and the recent pages as links into the wiki +- **AND** searching "leges" shows "Legesverordening 2026" + +#### Scenario: The wiki is not connected + +- **GIVEN** no `xwiki` source is set up in the connector app +- **WHEN** a person opens a dashboard with the Wiki widget +- **THEN** the widget says "The wiki is not connected yet. Ask your administrator to connect XWiki." + +### Requirement: A person keeps favourite pages (REQ-WIKI-002) + +A star on every page SHALL add it to or remove it from the person's favourites. A new favourite SHALL come first. The +favourites SHALL be kept in the person's launchpad preference `wiki-favourites`, at most 20, so they follow the person +across dashboards and devices. When saving fails, the favourites SHALL stay as they were. + +#### Scenario: Starring a page + +- **WHEN** Pieter stars "Termijnen Omgevingswet" and reloads the page +- **THEN** "Termijnen Omgevingswet" is the first of his favourites + +### Requirement: A team wiki shows one space (REQ-WIKI-003) + +With `space` set, the widget SHALL show only the pages of that space, in favourites, recent pages and search results. +The form SHALL offer the space and the number of pages per list, 1 to 20. + +#### Scenario: Wiki of the team + +- **GIVEN** a Wiki widget with space "Vergunningen" on the department page +- **THEN** only pages of the space "Vergunningen" show + +### Requirement: The picker offers the wiki only where it can work (REQ-WIKI-004) + +The picker SHALL offer the Wiki widget only when OpenRegister is enabled for the viewer, as the initial state's +`integrationApps` says. Outside edit mode a placed Wiki widget SHALL be left out for a viewer without OpenRegister; in +edit mode it SHALL render and explain that OpenRegister is needed. + +#### Scenario: No OpenRegister + +- **GIVEN** an instance where OpenRegister is disabled for the person +- **WHEN** they open the widget picker +- **THEN** "Wiki" is not offered diff --git a/openspec/specs/work-packages-widget/spec.md b/openspec/specs/work-packages-widget/spec.md new file mode 100644 index 000000000..091855d10 --- /dev/null +++ b/openspec/specs/work-packages-widget/spec.md @@ -0,0 +1,53 @@ +# work-packages-widget Specification + +## Purpose +A person's open OpenProject work packages, or one project's, on a dashboard. + +## Requirements + +### Requirement: The widget lists open work packages, due date first (REQ-WP-001) + +The `work-packages` widget SHALL list the open work packages assigned to the viewer, sorted by due date, at most +`limit` (default 4, at most 25). Launchpad's backend SHALL read them through the official OpenProject integration with +the viewer's own token; no credential SHALL reach the browser or launchpad. Each work package SHALL show its subject as +a link into OpenProject that opens in a new tab, its project, its due date (overdue once passed) and its status. + +#### Scenario: Pieter's work packages + +- **GIVEN** Pieter has open work packages "Welstandsadvies verwerken" (In uitvoering, due today) and "Raming + herinrichting Stadshaven" (Wacht op reactie, due Friday) +- **WHEN** he opens a dashboard with "My work packages" +- **THEN** both show, the one due today first, each with its status and due date + +### Requirement: A person without a connected account is asked to connect (REQ-WP-002) + +When the viewer has not connected their OpenProject account, or OpenProject refuses their token, the widget SHALL say so +and link to the integration's personal settings. Without the integration it SHALL say the integration is needed. When +OpenProject fails otherwise it SHALL say the work packages could not be loaded. + +#### Scenario: Not connected + +- **GIVEN** a person who never connected their OpenProject account +- **WHEN** they open a dashboard with "My work packages" +- **THEN** the widget says "Connect your OpenProject account to see your work packages." with a link to connect + +### Requirement: A team page lists one project's work packages (REQ-WP-003) + +With `scope: 'project'` and a project identifier, the widget SHALL list every open work package of that project, with +the assignee next to the project. The form SHALL require the project for that scope and allow 1 to 25 work packages. + +#### Scenario: Work packages of the team + +- **GIVEN** a widget with scope project and project "havenpark" on the department page +- **THEN** the open work packages of Havenpark show for every assignee, each with its assignee + +### Requirement: The picker offers the widget only with the integration (REQ-WP-004) + +The picker SHALL offer "My work packages" only when `integration_openproject` is enabled for the viewer. Outside edit +mode a placed widget SHALL be left out for a viewer without the integration. + +#### Scenario: No integration + +- **GIVEN** an instance without `integration_openproject` +- **WHEN** a person opens the widget picker +- **THEN** "My work packages" is not offered diff --git a/package-lock.json b/package-lock.json index 9e9b48cde..dd180fad4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,163 +9,129 @@ "version": "1.0.0", "license": "EUPL-1.2", "dependencies": { - "@conduction/nextcloud-vue": "^2.57.1", + "@conduction/nextcloud-vue": "^2.230.0", "@mdi/js": "^7.4.47", "@nextcloud/axios": "^2.6.0", - "@nextcloud/dialogs": "^7.4.1", + "@nextcloud/dialogs": "^8.0.0", "@nextcloud/initial-state": "^2.2.0", "@nextcloud/l10n": "^3.4.1", "@nextcloud/router": "^3.1.0", - "@nextcloud/vue": "^9.13.0", - "dexie": "^4.4.6", - "dompurify": "^3.4.15", + "@nextcloud/vue": "^9.13.1", + "dexie": "^4.4.7", + "dompurify": "^3.4.18", "gridstack": "^13.3.0", "marked": "^18.0.14", - "pinia": "^4.0.3", - "vue": "^3.5.42", + "pinia": "^4.1.0", + "vue": "^3.5.44", "vue-loader": "^17.4.2", - "vue-material-design-icons": "^5.2.0", + "vue-material-design-icons": "^5.4.0", "vue-router": "^4.5.0", "vuedraggable": "^4.1.0" }, "devDependencies": { + "@axe-core/playwright": "^4.14.0", "@cyclonedx/cyclonedx-npm": "^6.0.1", - "@nextcloud/babel-config": "^1.2.0", + "@nextcloud/babel-config": "^2.0.0", "@nextcloud/browserslist-config": "^3.1.2", "@nextcloud/eslint-config": "^9.0.1", - "@nextcloud/password-confirmation": "^6.1.0", + "@nextcloud/password-confirmation": "^6.2.1", "@nextcloud/prettier-config": "^1.2.0", "@nextcloud/stylelint-config": "^3.2.2", - "@nextcloud/webpack-vue-config": "^7.0.2", + "@nextcloud/webpack-vue-config": "^7.1.0", "@playwright/test": "^1.63.0", - "@typescript-eslint/parser": "^8.70.0", + "@typescript-eslint/parser": "^8.71.0", "@vitejs/plugin-vue": "^6.0.9", - "@vitest/coverage-v8": "^4.1.11", - "@vitest/ui": "^4.1.11", - "@vue/compiler-sfc": "^3.5.13", - "@vue/server-renderer": "^3.5.42", + "@vitest/coverage-v8": "^5.0.2", + "@vitest/ui": "^5.0.2", + "@vue/compiler-sfc": "^3.5.43", + "@vue/server-renderer": "^3.5.43", "@vue/test-utils": "^2.5.1", "@vue/tsconfig": "^0.9.1", + "axe-core": "~4.14.1", "eslint": "^10.11.0", "eslint-config-prettier": "^10.1.8", - "jsdom": "^30.0.1", + "jsdom": "^31.0.1", "prettier": "^3.9.8", "stylelint": "^17.15.0", "terser-webpack-plugin": "^5.3.11", "typescript": "^5.4.0", - "vitest": "^4.1.11", - "vue-eslint-parser": "^10.3.0" + "vitest": "^5.0.2", + "vue-eslint-parser": "^10.4.2" }, "engines": { "node": "^22.14 || ^24 || >=26", "npm": "^11.0.0" } }, - "node_modules/@asamuzakjp/css-color": { - "version": "6.0.7", - "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-6.0.7.tgz", - "integrity": "sha512-vC/bk1Lz7Tn/EfU9/apOTBk80/8dyGyWMowPoV1tJ52muDGsDqt2HPT2klrFUiY60MQmQv9q8yIht15JnBgDGw==", + "node_modules/@axe-core/playwright": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.14.0.tgz", + "integrity": "sha512-SGUhG5PIHd2eMdpgBF2PyQLOhX+qyDR2PT4cmoS4Qk2ak+jX/rrSvst9l0PGv5WTHolKpUMvVmoHpr4cZgf1RQ==", "dev": true, - "license": "MIT", + "license": "MPL-2.0", "dependencies": { - "@csstools/css-calc": "^3.3.0", - "@csstools/css-color-parser": "^4.1.10", - "@csstools/css-parser-algorithms": "^4.0.0", - "@csstools/css-tokenizer": "^4.0.0", - "lru-cache": "^11.5.2" + "axe-core": "~4.14.0" }, "engines": { - "node": "^22.13.0 || >=24.0.0" - } - }, - "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { - "version": "11.5.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", - "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/@asamuzakjp/dom-selector": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-8.3.2.tgz", - "integrity": "sha512-93Z1N+BQNXysodoicpOIyNh2drHfz/CTf9nnT0FEx72GJcIiwgydD7tGAr78j41LsYn3hlRn+LdGPuBLn1Bl8Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "bidi-js": "^1.0.3", - "css-tree": "^3.2.1", - "is-potential-custom-element-name": "^1.0.1", - "lru-cache": "^11.5.2" + "node": ">=22.12.0" }, - "engines": { - "node": "^22.13.0 || >=24.0.0" - } - }, - "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { - "version": "11.5.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", - "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" + "peerDependencies": { + "playwright-core": ">= 1.0.0" } }, "node_modules/@babel/code-frame": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", - "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", - "devOptional": true, + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.6.tgz", + "integrity": "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw==", + "dev": true, "license": "MIT", + "peer": true, "dependencies": { - "@babel/helper-validator-identifier": "^7.29.7", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" + "@babel/helper-validator-identifier": "^8.0.6", + "js-tokens": "^10.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/compat-data": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", - "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-8.1.2.tgz", + "integrity": "sha512-XvUnYY6D/bJMB88821n7HFmiwFS6feV7vZLxxudRgWnnwAGtOnDa7C+6svNciIN+BAZDY6WEdIeKHaEW9c0LPg==", "dev": true, "license": "MIT", "peer": true, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/core": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", - "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-8.1.2.tgz", + "integrity": "sha512-xqDajHAAOjklW5UtWzFd9vSmlQ16+emgGi0HsyDQFGRQWZ/GjuwCoYGC3PnHxspmOR+HJBzDIOkMxNq/VvC98w==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helpers": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7", - "@jridgewell/remapping": "^2.3.5", + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.1.2", + "@babel/helper-compilation-targets": "^8.0.7", + "@babel/helpers": "^8.1.2", + "@babel/parser": "^8.1.2", + "@babel/template": "^8.1.2", + "@babel/traverse": "^8.1.2", + "@babel/types": "^8.1.2", + "@types/gensync": "^1.0.5", "convert-source-map": "^2.0.0", - "debug": "^4.1.0", + "empathic": "^2.0.1", "gensync": "^1.0.0-beta.2", + "import-meta-resolve": "^4.2.0", "json5": "^2.2.3", - "semver": "^6.3.1" + "obug": "^3.0.0", + "verkit": "^0.5.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "funding": { "type": "opencollective", @@ -173,1581 +139,1510 @@ } }, "node_modules/@babel/generator": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", - "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-8.1.2.tgz", + "integrity": "sha512-tAjURz1NaCZGtdG3hB6gjaIeTVo4XFD4TnbqIEneADVJ1Jpt2NxhPBAjbhius8ulUG5b/P2b56ec1ClJZa2aBQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/parser": "^7.29.8", - "@babel/types": "^7.29.8", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", + "@babel/parser": "^8.1.2", + "@babel/types": "^8.1.2", + "@jridgewell/gen-mapping": "0.4.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.31", + "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping": { + "version": "0.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.4.0-beta.0.tgz", + "integrity": "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, "node_modules/@babel/helper-annotate-as-pure": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz", - "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-8.0.0.tgz", + "integrity": "sha512-NSpMkMsvvZqzThJ0p1B02cbtA2ObEyfBvq950bmNkyxsxvcxwhvvCB036rKhlEnuBBo30bOrk13u3FzlKSoRrw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/types": "^7.29.7" + "@babel/types": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", - "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "version": "8.0.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-8.0.7.tgz", + "integrity": "sha512-ilAZCdOOlOVA7dQbaFNw2f/59p6GW33NxTopc3DvEE3efp3ZXTrGX/yZScaKw8/vd9bq31Ag0EcXiLw32bAgJg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/compat-data": "^7.29.7", - "@babel/helper-validator-option": "^7.29.7", + "@babel/compat-data": "^8.0.5", + "@babel/helper-validator-option": "^8.0.0", "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" + "flru": "1.0.2", + "verkit": "^0.5.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-create-class-features-plugin": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.7.tgz", - "integrity": "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg==", + "version": "8.0.10", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-8.0.10.tgz", + "integrity": "sha512-a97s55BatmvDeeQ9rngs/IPi1aeQ3vVUbXr0DsNGhzF/vB2w49N+FqD+D0/YEGLziU7zALhrKFlk6FGlvbM38w==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-member-expression-to-functions": "^7.29.7", - "@babel/helper-optimise-call-expression": "^7.29.7", - "@babel/helper-replace-supers": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", - "@babel/traverse": "^7.29.7", - "semver": "^6.3.1" + "@babel/helper-annotate-as-pure": "^8.0.0", + "@babel/helper-member-expression-to-functions": "^8.0.5", + "@babel/helper-optimise-call-expression": "^8.0.0", + "@babel/helper-replace-supers": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", + "@babel/traverse": "^8.0.10", + "verkit": "^0.5.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/helper-create-regexp-features-plugin": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.29.7.tgz", - "integrity": "sha512-907Uymvqgg1dwUA+7IGwFAOSYzQOuzPXKNJ1yxzwPffzkYFg2q2eHi1fIOs6sXkG9NbIUMunnUlkYsfRFNvomg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-8.1.2.tgz", + "integrity": "sha512-8CIAQ0MF4fJWgofcwAJcAQlpDDL+OxCJY6w2xf8djG42K0UQEvfSlywzjKFmshcWrJFCBojEqhG23lTPpZjLiw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "regexpu-core": "^6.3.1", - "semver": "^6.3.1" + "@babel/helper-annotate-as-pure": "^8.0.0", + "regexpu-core": "^6.5.4", + "verkit": "^0.5.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/helper-define-polyfill-provider": { - "version": "0.6.8", - "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.8.tgz", - "integrity": "sha512-47UwBLPpQi1NoWzLuHNjRoHlYXMwIJoBf7MFou6viC/sIHWYygpvr0B6IAyh5sBdA2nr2LPIRww8lfaUVQINBA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-1.0.0.tgz", + "integrity": "sha512-9jzVaTeZyXRDKTgUnNzcPQMO8y0ga3o+Z4fKjNet9Fcx7slgKa83qRbz0EwROSd6qO6CoEe/HQszqSPKb5lhkw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-compilation-targets": "^7.28.6", - "@babel/helper-plugin-utils": "^7.28.6", - "debug": "^4.4.3", - "lodash.debounce": "^4.0.8", - "resolve": "^1.22.11" + "@babel/helper-compilation-targets": "^8.0.0", + "@babel/helper-plugin-utils": "^8.0.0", + "lodash.debounce": "^4.0.8" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" }, "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + "@babel/core": "^7.4.0 || ^8.0.0" } }, "node_modules/@babel/helper-globals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", - "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-8.0.6.tgz", + "integrity": "sha512-OdnA/N52LhzFpeUuVz5YGuSWjc7TPHiFmVYZbPlSgExocO2GwbxVpSni9MVs5wwW+wZ4kPuwBEBN9pIPDYz1mA==", "dev": true, "license": "MIT", "peer": true, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-member-expression-to-functions": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.7.tgz", - "integrity": "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-8.1.2.tgz", + "integrity": "sha512-2SP3fg4vqEN1qwXaaULsgmMC3I+NSi/OVZCObdPO3NSYAVfNq4BZ6akTqU+3dLEUTQHoeYaXEUnyEHaEGkAwVg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/helper-skip-transparent-expression-wrappers": "^8.1.0", + "@babel/traverse": "^8.1.2", + "@babel/types": "^8.1.2" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-module-imports": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", - "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-8.0.0.tgz", + "integrity": "sha512-NZ7mSS93o4ndX4KrbD7W8Sf3QT8Qe24PrnFyUcuOPDzK6faqDFKjY9RG7he7+I7FdiQ4llpnosFqzrXa+Vy3Ew==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/traverse": "^8.0.0", + "@babel/types": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", - "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-8.1.2.tgz", + "integrity": "sha512-iSa4SKZHScghjyCDWgrkcb/gt+huMuoZ8ZpY0iQQUG1C41XH9Iy3nQA0vcNDTcALItQ0kZ9cuWzqm76p/kkHJA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-module-imports": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-module-imports": "^8.0.0", + "@babel/helper-validator-identifier": "^8.0.6", + "@babel/traverse": "^8.1.2" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/helper-optimise-call-expression": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.29.7.tgz", - "integrity": "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-8.0.0.tgz", + "integrity": "sha512-3W6satvtPuCUkUx63S2jMoW9EQNYkADgs1HTfufmL7gCmAulHMKupA/12WNz4A0GMMFn/YnWWwqOT9IZrJHQjg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/types": "^7.29.7" + "@babel/types": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", - "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-8.0.1.tgz", + "integrity": "sha512-3PKFgjTyPlhFhorfP+SjKQxLViIL++zWjFOO4hGriYU+Bsm983DxEM1JmDRJVWXV0O9npu+xXRqz7Pbd3mh70g==", "dev": true, "license": "MIT", "peer": true, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" + }, + "peerDependencies": { + "@babel/core": "^8.0.0" } }, "node_modules/@babel/helper-remap-async-to-generator": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.29.7.tgz", - "integrity": "sha512-16AMiW26DbXWBbr3B8wNozKM0ydMLB892vaOaJW/fPJdnT8vJk5sdkQcU/isqUxyCE0cEoa8wZOcbgDuC4b6Og==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-8.0.1.tgz", + "integrity": "sha512-baAKuLEMmu6BCSY3tuiU7qglM1qOZt6F1SrFScA241oNqksxkxfEZEKztlGRmoVns9AQ5UgArH7RsUEjxWnzgQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-wrap-function": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-annotate-as-pure": "^8.0.0", + "@babel/helper-wrap-function": "^8.0.0", + "@babel/traverse": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/helper-replace-supers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.29.7.tgz", - "integrity": "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-8.0.1.tgz", + "integrity": "sha512-B1SZADIcy3tmH8CmWvj4SHi/oAPom4UL3uknTc2QRNsPVLFk/sPnZvQL/8kj7Y5omvjMqie0vklvs6XM4OLW5Q==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-member-expression-to-functions": "^7.29.7", - "@babel/helper-optimise-call-expression": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-member-expression-to-functions": "^8.0.0", + "@babel/helper-optimise-call-expression": "^8.0.0", + "@babel/traverse": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/helper-skip-transparent-expression-wrappers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.7.tgz", - "integrity": "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-8.1.0.tgz", + "integrity": "sha512-nU02D56QABKl7gDT/7hGpMd2TtWYYcoOj4NT3+Xzr76oJrMl+3SUR8gp3CelvrjkvDUvwj+WZCUzuPBCUJSZoA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/traverse": "^8.1.0", + "@babel/types": "^8.1.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-string-parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", - "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.1.2.tgz", + "integrity": "sha512-TRz5Z0MgfIfWqwEIq/pCpUpEXQxUt2Ig2ZbxG3SdmhSbHMAFFYGOix0kI4JLV371/TA+qWnQ4xWHPWjojkyRFA==", "license": "MIT", "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz", + "integrity": "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==", "license": "MIT", "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-validator-option": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", - "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-8.0.0.tgz", + "integrity": "sha512-U4Dybxh4WESWHt5XhBeExi4DrY0/DNK1aHpQbsrQXCUbFHuMweT0TpLEWKvaraV2Y6fS+ZXunsZ8zIuZIgvF2Q==", "dev": true, "license": "MIT", "peer": true, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helper-wrap-function": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.29.7.tgz", - "integrity": "sha512-iES0Skag9ERIF68aXadpO6dbXa03mNWK3sEqJaMnLNs/eC3l0lkImdfoy6Y09/SfkpawdAB4RjQ7PVA7TcVGdw==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-8.0.0.tgz", + "integrity": "sha512-Qpm8+wi5xfDkBfollanwriCcKniFfBmMmaKB01GVM6VGzKXo1fdxosZp04qEr5HM+LKhwr3hG1yRy8+ORsficA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/template": "^8.0.0", + "@babel/traverse": "^8.0.0", + "@babel/types": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/helpers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", - "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-8.1.2.tgz", + "integrity": "sha512-BmtiG8H9OUWSTFOgl9jtPYmfDi6uc21Pf4GUxkgGoZnzMIzpDnhkl5gsGJW6wb1jmKCyU565F8IYe5mwOTctfw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/template": "^8.1.2", + "@babel/types": "^8.1.2" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/parser": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz", - "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.1.2.tgz", + "integrity": "sha512-ZDKU7vaX0VORd2BhaO+3FKr/30TKjbUy3SMZcydiPngnAb+MesgUoh5SJcE5EwEyBj14M5J6fK56GuBqvYmOpw==", "license": "MIT", "dependencies": { - "@babel/types": "^7.29.8" + "@babel/types": "^8.1.2" }, "bin": { "parser": "bin/babel-parser.js" }, "engines": { - "node": ">=6.0.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/plugin-bugfix-firefox-class-in-computed-class-key": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-firefox-class-in-computed-class-key/-/plugin-bugfix-firefox-class-in-computed-class-key-7.29.7.tgz", - "integrity": "sha512-j8SrR0zLZrRsC09DlszEx8FpMiwukKffYXMK0d5LmOglO7vGG6sz/BR/20yHqWH+Lnn31JTt2PE3hIWNgM2J6w==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-firefox-class-in-computed-class-key/-/plugin-bugfix-firefox-class-in-computed-class-key-8.0.1.tgz", + "integrity": "sha512-Ytgjjne4RnG3Oig7ik+NfY4ebRY30BPptVkkyu1f72eINJXRM3/bkU++tIc5aPvyLmo4KH20avq0xJ2o+9aEnw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-bugfix-safari-class-field-initializer-scope": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-class-field-initializer-scope/-/plugin-bugfix-safari-class-field-initializer-scope-7.29.7.tgz", - "integrity": "sha512-r8j8escF+U2FUHo0KOhPUdMzUO+jp9fInva6+ACVAF3Y97Ev+5iNZwiqTghmzNeWwDkOPlYuTcfb1vDaoZKmAQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-class-field-initializer-scope/-/plugin-bugfix-safari-class-field-initializer-scope-8.0.1.tgz", + "integrity": "sha512-X7pAMBhuKluA7UfwZNvKN0XVVu/AGeo84Z75eJl85rcb8J2aBzLK92btahM1X5h0oi0QIrbe0qIMA/0+4Buk7w==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.29.7.tgz", - "integrity": "sha512-GE1TFSiuFeGsCxmYXZl8HwoPrVlwe4rHPFE8weieGKZqnDORK+Ar3vgWMgW+AOxQ6/2TgLSKx9p6W7O4rC6qgQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-8.0.1.tgz", + "integrity": "sha512-DJviKTxYfH0hFwnMiW4dnPyMGzS3Hrr4zUfXl1zwQ0QiGlGlNYklLoPSYEQr8S7nau0/K7NdQjTh0qbYuyFjCA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array/-/plugin-bugfix-safari-rest-destructuring-rhs-array-7.29.7.tgz", - "integrity": "sha512-oBNVCvnO5tND+xSopWvV8WNGfpTfgP4Zr/YXXSj8zfmcPktp5Ku/aZlsIowgSD4fjmgHn6sGmB9APVsU5zOdhA==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-rest-destructuring-rhs-array/-/plugin-bugfix-safari-rest-destructuring-rhs-array-8.0.6.tgz", + "integrity": "sha512-vk9CzgaQGcTTBL8F0YNr7LBEka6pXP/I5KcMj0oicGXUquWSNqxiijHGQkHF+s8m910NbGMpn5mU2sFV7AQjBA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-7.29.7.tgz", - "integrity": "sha512-QQt9qKHZ2sg/kivaLr7lnQr8HVrQDdBNSfCsTjiDxRuX/K5ORyKq+Bu8Xr0cDE3Dfkv0cw28Ve0EKyKMvulkOw==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-8.0.1.tgz", + "integrity": "sha512-x8bi0LFVD2xkULjfNn+hCMg16yAFHAM9fS/ThSFeYBi+0MP9K6qcY2BZb4urUwC7PYtEy5wPe6TKjOEjXrCGFA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", - "@babel/plugin-transform-optional-chaining": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", + "@babel/plugin-transform-optional-chaining": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.13.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-7.29.7.tgz", - "integrity": "sha512-pn6QacGLgvCcwc+syUhKE/qSjV2D1IHDB84RNxWYSt1mW3K/SCtjinZ2p0cETJxAWBjPy3K/1lHwG5BjjPxNlw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/traverse": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/plugin-proposal-private-property-in-object": { - "version": "7.21.0-placeholder-for-preset-env.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", - "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-dynamic-import": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz", - "integrity": "sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-assertions": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.29.7.tgz", - "integrity": "sha512-/An1OCBN93thpBAGyfsK2pcf0jvju1SAtKkL2Ny++B5Sy6sqgzXDQH1cZxWbF96Wuk+bn41MDA9bLd4VVAw6rw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.29.7.tgz", - "integrity": "sha512-zGYcYfq/WmZ4V+kBIXQon9dSSc8ircGZqw9ZaNhhGj9nZkeBu1jHLBDQqYYi5WA9uawvA2sIMbry2nCFhf5Djg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-unicode-sets-regex": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-unicode-sets-regex/-/plugin-syntax-unicode-sets-regex-7.18.6.tgz", - "integrity": "sha512-727YkEAPwSIQTv5im8QHz3upqp92JTWhidIC81Tdx4VJYIte/VndKf1qKrfnnhPLiPghStWfvC/iFaMCQu7Nqg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-8.0.1.tgz", + "integrity": "sha512-P8+RN2n7ts2s1vnE+lXdHYf+dhnmcGSen/kWzBsVluT9Sey5AqmcRXYWlHqgQxaNlKTD5YMa1tf5z4d1v8W88w==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.18.6", - "@babel/helper-plugin-utils": "^7.18.6" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-arrow-functions": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.29.7.tgz", - "integrity": "sha512-N7zArUXWzAMzm+/N0uPBeVB3Fam5lMxtUwMmDK5f/IBBS7a7p1qeUoxd/6CckXoxUdgsntq1Dh8xNW06maZbDQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-8.0.1.tgz", + "integrity": "sha512-o/gr7kRlq3PKLLuYth4udOsrC7geBerti+QtwPeyxMOsEQO1d8kDHqk9r2PtMx2y9i8FG7tzyTerfv1yMLSMsQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-async-generator-functions": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.29.7.tgz", - "integrity": "sha512-d98gXZkgswvkyohMBABkhm3GeXhYj8psWfwQ2C7gtfrKGTykQa/iOIi+JJhwMjPlZ6Vm2XN+DCf3Es1EoG4ZLA==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-8.0.6.tgz", + "integrity": "sha512-4K13qZ2TVi9W/NHMg3y0Fguu63cPjGNZT5TpPctIUDdiuIpxo4jwvySGrPWlD6KD00exvpx6Y6l5foFEpnzDcg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-remap-async-to-generator": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-remap-async-to-generator": "^8.0.1", + "@babel/traverse": "^8.0.6" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-async-to-generator": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.29.7.tgz", - "integrity": "sha512-pcUb2SS+RMo9TWVBwKGI5ShtoG7R+zBsFmCKDa6fe8c+hPr3XJlZgoE5j6i8W7gDjhyvy+85vmYexanvXh3d1w==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-8.0.1.tgz", + "integrity": "sha512-e1jmmEU4p2Lx64sA1+EF8e8/RxPuegzbXcEbmFp5alDyLE+f2ViUpZ77bRWMXzihTwgVVmn/TOpqDbAuS5g1Ew==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-module-imports": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-remap-async-to-generator": "^7.29.7" + "@babel/helper-module-imports": "^8.0.0", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-remap-async-to-generator": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-block-scoped-functions": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.29.7.tgz", - "integrity": "sha512-cUSmjh72N+rN4PrkFlN1dJwNCwjVp5d38/CQrEsFggkD10UiFlBFgdH3tv5dNsLuHY+3S8db2xCHjhZcv5WgvA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-8.0.1.tgz", + "integrity": "sha512-0V97/gcf7LIgPieEiK1YT0eXa18XJFSLOTZjzEZhA9SJIqZhD/IwGUrCitBzXSmnGCP7hchwC6svHtJ/Eidcpg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-block-scoping": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.29.7.tgz", - "integrity": "sha512-ONyr4+AZhKh8yKWInVxU9AXA9EbsyeLcL6V0dJy6M2/62vuvpGm29zzuymbTpdc451GEpDIdAyPLP3r+P61yKQ==", + "version": "8.0.10", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-8.0.10.tgz", + "integrity": "sha512-quUFdseabc7Z/gALDVAKy7iaLrErgiuiHR31oxLEzUs+Wn8nYqLGHnunM7WOU24SNEk0DrCHV+oKwlJ6Bp8OGA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-class-properties": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.29.7.tgz", - "integrity": "sha512-GtcpjFvanPfzNQi3eTitsCqtRRmmqzpy/A+yhTR1HaZo1Ly3EA8ZXxlPyHdR8/IuRMYc3E4wdGBewB2QKQjAaA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-8.0.1.tgz", + "integrity": "sha512-tORnYiVhIHnKj90TgbSZXrO24f9oEpA6MgFxpIDSKKlHv7AzBIRhkMlYevanueLNYaQXqZWarfCgXM4bWTfNiw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-class-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-class-static-block": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.29.7.tgz", - "integrity": "sha512-kibJgmEdX2iMwsHY2tSZNDgj8PwIlCQz7FK9KuGKO8zsuoUwSEhoNnNVp/emKWrbY4HeO6kkXfdMqRKKKXBm2A==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-8.1.2.tgz", + "integrity": "sha512-6YMTik3C/R98+njg1icUI8ZD/NmO9T13iJbVqc7qwYlDYnAz+ef4X56QoXEoUQn2i1EAB1CsB/We/UUFHK8/Jg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-class-features-plugin": "^8.0.10", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.12.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-classes": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.29.7.tgz", - "integrity": "sha512-qV0OGGBVacduzQHE649JyCneOFI/maT+YKsO+K4Yi3xv2wTPNjM/W2o2gdzMwEAZz7fXNTHAe0NcSg30bIN69g==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-8.1.0.tgz", + "integrity": "sha512-Rw8veCkRzrpYksK1zxN2oAN8xZbJA9qVV/R5LzaFbDJEnKcwv0rsYMYb5I36eMuOI6svYutG5GuEbcNOjXbAdA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-globals": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-replace-supers": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-annotate-as-pure": "^8.0.0", + "@babel/helper-compilation-targets": "^8.0.7", + "@babel/helper-globals": "^8.0.6", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-replace-supers": "^8.0.1", + "@babel/traverse": "^8.1.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-computed-properties": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.29.7.tgz", - "integrity": "sha512-RK7/IyU5phpuCdBAuig5VkzG/EnbDaui5SQGdU9BFrHdV+mV4cUjLMQ9lJDjLNtWHsqtiefpGZUXQP2BiTYMsA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-8.0.1.tgz", + "integrity": "sha512-i4l3OGLO8DUDcwdnyraOvILbhqdUf4QgfzhVxSOSzRy49XKXrY7pwaSg9gDSKmhZfNPrEMciBSJSciQh/CjB1A==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/template": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-destructuring": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.29.7.tgz", - "integrity": "sha512-iPX8aD6H9zV5s7ZsqTdNocPN/MGQ5sSMnElKrktxjJRMnB2jN/1p2+R7GkfD6CAYoVFqy5A4XnSIUeGgJzIWpg==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-8.0.5.tgz", + "integrity": "sha512-evjxc5fGvpXG2WMGSalpX8IJZVumLIDgk5r5eRhvXRDqFX/GPWq1BeRfJalPCcwJfrR5A/wvegUhx9W5Nr7/mg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-dotall-regex": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.29.7.tgz", - "integrity": "sha512-3qc18hsD2RdZiyJNDNc7HQpv6xbncwh8FYtxNFFzclSyh/trPD9KkVR9BDECUjDLvb7yJVF15GfYUuC+LMkkiQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-8.0.1.tgz", + "integrity": "sha512-czOUoSaZljJ92yu+bYlXqb/UBN8K9daNCob/B6/7nthSvfGP6YhCnfqD64XWfyb2dN4ypxALNplApoJrsMd4fw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-duplicate-keys": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.29.7.tgz", - "integrity": "sha512-6IvRRriEMqnBwD6chtxdLpMYCHWEzN+oL5cyQtjykya19UgzbmKhxmhZgKC/LHxS2nYr9Q/qYPZ5Lr6jOL9+yQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-8.0.1.tgz", + "integrity": "sha512-kNnVLkxFUEcTtCyB5PFVQ5Xoy88Bk1lU/ZgDu97CW8eNhRH2Wsiy8Sq5l5dFnwtIUYjzsXHU77jUy1W5AtGSIw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-duplicate-named-capturing-groups-regex": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-7.29.7.tgz", - "integrity": "sha512-2wiIyo2BjtgU7HufSeDnL9L2O7zr8jmhFKuSr65VpRkUiRKRNpb0mdlk56+XPPKoIrfHqzbMuglDvZun0RISsA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-8.0.1.tgz", + "integrity": "sha512-Tv43P47o6fuHgBL7HLHQg3WKXohW9CEUGjLtnCDW27yJLK0zKUdTTqREbZbycNHA83hewMjde5tF6ekrHu9bAA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-dynamic-import": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-7.29.7.tgz", - "integrity": "sha512-giOlEm/EFjfjr+te9NsdjkUo2v4f8rS/SXPumRVHAtbNcyNlvtREkU1dZzaIDclNpnaVhlCqRdFKhJBjBikzLg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-8.0.1.tgz", + "integrity": "sha512-AS9GlgKc43tJNRu7yOvLaTko4qmdOb+8M69uNS8i421WLO20eVez7LdG5khKdi8E0LIQpYzzzdGIrdXWnO753g==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-explicit-resource-management": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.29.7.tgz", - "integrity": "sha512-Rstj7coNz8sE+7Ju7ihpHLI564lsK5pUpNNlvptCIC/16E/S5hbl6n3kESPKdNRmqEWlpn5xpS5Q2dvXBsySLw==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-8.0.5.tgz", + "integrity": "sha512-Vr20jk/ZxRGu30o0jYvcKl2Pf0tiyr8H9q2ZGxYD6yjOpv9DdP6//I85q0cSOdADZhsu/ZZoApjGVCfl4xnVJw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/plugin-transform-destructuring": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/plugin-transform-destructuring": "^8.0.5" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-exponentiation-operator": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.29.7.tgz", - "integrity": "sha512-zFpMOTLZBdW5LfObqcSbL6kefg4R4eLdmvS0wbN9M6D5Mym/sKm9toOoWyVOa+xDjvCnuWcHls2YonXwHvH3CQ==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-8.1.2.tgz", + "integrity": "sha512-XD1ffIILGPUV/Rv9BUlobcrsugpfo4LxPAHqfx8SQKoRlDTs5cTisHAA3hhQ7suw3JLr9x28P/BHhxQYpnDG1A==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.1.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-export-namespace-from": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-7.29.7.tgz", - "integrity": "sha512-24B2nOy2TeJSMheqwPD4DDQOV/elLSIlKxjZt4i05H5AgdPdWR3n18HnNrcJ+j76WJd9gbwb9jPjNYUy6RautA==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-8.1.0.tgz", + "integrity": "sha512-4NpXrz/RfrjoCC3NZkRNWvLSe+kG/p3RKzWIOFAEqE7AuNOiOPi+3T0iEIUQBqjG42RnmUY0uMV0XlREIubxLQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-for-of": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.29.7.tgz", - "integrity": "sha512-zeSIHh0+E1Um1WJRXCFlHQYu2ieJNdivLLjlBEp+dIBu3S51n+SZZmIXjxnItw6pz56Cn+KvK68BIBVsxq2JiQ==", + "version": "8.0.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-8.0.7.tgz", + "integrity": "sha512-h+/9Kyy55fWlnLDmMIWwz21nWLFodIZYpvvCq7gW6Fb55via7sTYPymeTNKbh8N9XZjZ025ClVtg0kxIPnEjGA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-function-name": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.29.7.tgz", - "integrity": "sha512-otRWaHXE6fbAGkePvaj/kvs3HsqXfPhlnzwSOlnFgbqCPMd975dW+4wZ00WFBt+/YlBGcJwNrARQTOJOb4ZrIg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-8.0.1.tgz", + "integrity": "sha512-H1L/JfPf3CqmubuaiZaquXKQ8MRs4YWSsgRllkTviM8TafcCNnlvc4/fJZ3rXP8HmFM+/Bg+TlsPehUI9BtDFA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-compilation-targets": "^8.0.0", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-json-strings": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.29.7.tgz", - "integrity": "sha512-RRnE2+eon1rJAq8MnoF1b5kTpY1vU88twHcvcKMrsqP/jxIRqDVs9iJB5fqPuqyeFAW0wJo4MlUIPpQCq/aRsg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-8.0.1.tgz", + "integrity": "sha512-Mowp8X0J6p7ZehLU82B5e65te2uuSeDHyxrEROwEAS2VKXNXssfw5ZMqhY7k9iXTsOv1Xs/49G3lDCj9Vvw8qQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-literals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.29.7.tgz", - "integrity": "sha512-DZ/oLP21ZuWx1vKqnoNv6/tvEK48AQOBRai40CX9dTjGluvT/YZCyY3rryDtyUqCEoyNroy5KKPwX2iQCiRvyw==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-8.0.1.tgz", + "integrity": "sha512-ai7kfPRcfyUV1EszXoF1PvL3IuJoCuH08WSEPoRcJTWfZZ55VL/rcfvbVY16QLA3jjbzzSneQSoCtD3L6OyUjw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-logical-assignment-operators": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.29.7.tgz", - "integrity": "sha512-A0H91hh6W8MFRkp5TqJmMr39jzGD1A1E1Ysiv2O06Sfbhkapm+XyIzxWCEh5kqwOZ1/8QZ0dY3SeQ7XBqfJd5Q==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-8.1.2.tgz", + "integrity": "sha512-6X1QzwwiVFshP6vmumH3hUnoDUvGDyehl7E8wQu5B++aT4qRx6VQSjS7Qsdl51a1cB5OpLuElu4R/wr3TAzGRw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.1.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-member-expression-literals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.29.7.tgz", - "integrity": "sha512-hl1kwFZCCiDyfH25Xmco9jTrkPgnS9pmOzSG7W5I4SaGbLeqKv417hcU2RKmaxoPEgsoJh7ZPOrnPGq99bHoUg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-8.0.1.tgz", + "integrity": "sha512-3Axi9abnyGsm/hh6DsKPZ1Cr9fTtKqS7w0Ig5g12mU269YclpH8pV3xMln2vPLexXgUp6S6L+I06d9/YOLfRKA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-modules-amd": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.29.7.tgz", - "integrity": "sha512-fxtQoH3m5ywUSIfaH0FGCzWu4McsYon5bD3K4XnskC7f+OyQMj7rsOMi4NvvmJ83WwBAg4UCe+ov4VZlqEvyew==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-8.1.2.tgz", + "integrity": "sha512-2STLS26gEdnkdGm3JHPg5utUFiR/Y51R0s/v+eNB+dUFQeyEontLBM0t2JTMSCA75U+vAfHCBmrtnXLjEHzqNg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-module-transforms": "^8.1.2", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-modules-commonjs": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.7.tgz", - "integrity": "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-8.1.2.tgz", + "integrity": "sha512-bYW5KcM2w1DAXUV2a5HnWWVn+KGdz2EqpLocooynARzjdLjNTxLlftPGPP9APhTdmMrdynVEcu3QCUWhW/FIUw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-module-transforms": "^8.1.2", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-modules-systemjs": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.29.8.tgz", - "integrity": "sha512-6iSnEK0zlkLKU4heofK/AdmRD4e2SHVpJMtrwnTCzhnaM98ria4rTrOXBBi45BTTYnJtO8txnPsX4fChYXkmeA==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-8.1.0.tgz", + "integrity": "sha512-dwrEjptAfSXkaQiJN1vApWFCwjLMAZ7XtNVbWqrjSsgQIJ1ixy5Zv3lOjGRHGoNRQ5IkD/OObEW2RhOuf64kSw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7", - "@babel/traverse": "^7.29.8" + "@babel/helper-module-transforms": "^8.1.0", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-validator-identifier": "^8.0.6" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-modules-umd": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.29.7.tgz", - "integrity": "sha512-B4UkaTK3QpgCwJnrxKfMPKdo92CN7OKXAlpAAnM3UPu0Q0lCCk57ylA9AJbRy2v8dDKOPAAWcoR6CMyeoHwRCA==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-8.1.2.tgz", + "integrity": "sha512-+0diEH9S1PlOR78T2n1a1IdLXf0LraVDJhdkrpx/iWIvnfwDZlHlEr+zK99G47w1IJhbvxZ/FhTHORJ5rgCnuA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-module-transforms": "^8.1.2", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.29.7.tgz", - "integrity": "sha512-vuFoLwr4qnv2xbZ16SQd6uPcH5FNrLHhk/Jzo++0XJFcaDsr4gjJVg6j398oMHiC+83k/GiBzviwF5KBJkPUtQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-8.0.1.tgz", + "integrity": "sha512-zCHu+Jr2gTdJE48lN9SV/kXueCW2M79mKtKJc/ttfzzr/jvgdQdCd17RADMqFRQc/25MLxdtjTmlD0HSAMOlIQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-new-target": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.29.7.tgz", - "integrity": "sha512-fEo41GmsOUhOBlw8ioo6zvjX5Xc2Lqkzlyfqbpsk3eB6TReV18uhxZ0esfEokVbY2+PVJAQHNKxER6lGrzNd3A==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-8.0.1.tgz", + "integrity": "sha512-QSQxVg1x4PuOuhWUs4Y9u+x9Y+ER8z6G3tC+bDLBzvoOrNLJrEBQLRnwrTP8e5klihAw6Z+e9X5RjdAKcAGapA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.29.7.tgz", - "integrity": "sha512-idmp1dFaekP9GbcMvG24Kvw2BfhFZjHnNJCkV4WuIY4PskJzwI3f1N5OdgYke38T7rftO6ERulFRn2cFeZwRkg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-8.0.1.tgz", + "integrity": "sha512-AgCJAmQLF7+PtsK79wJqr4xJ2StHCXlz7JL5CVFP4HejJx25Tk6yl1ZrXvi0cKh3VGDVnfVxefxnrpsBirgpyQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-numeric-separator": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.29.7.tgz", - "integrity": "sha512-zR7fv/z14OjgHl4AgRtkDBvBMhIzCxqV/qN/2BCRC7LjFwvuzjYe7gDWxC4Wl/SNsLM6SE1IWvRPYMgSJaUvNw==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-8.0.1.tgz", + "integrity": "sha512-it2DmUyLIA1GQUXlFDEnI+/G89mTgxndnAiZYpW8xYR6LboblfirMqiWJeTna5uypQJg7viTT4D1iEURRtFcfw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-object-rest-spread": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.29.7.tgz", - "integrity": "sha512-Ld98jn4c0smUywL57m7SgsHq3OpThOa6LqZJif3G6jYOovPleoFhVrBJ1WegRApSFB2wu4+RelAj9AC9G08Z4A==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-8.0.1.tgz", + "integrity": "sha512-VmxkDu6bBdbxRzqn6E93hYucug4OVa6svSO19W//vVzNUGAmQzk3QRyHyyEtfcjSLR3NWfRsWwVM9zExLmd+2w==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/plugin-transform-destructuring": "^7.29.7", - "@babel/plugin-transform-parameters": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/helper-compilation-targets": "^8.0.0", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/plugin-transform-destructuring": "^8.0.1", + "@babel/plugin-transform-parameters": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-object-super": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.29.7.tgz", - "integrity": "sha512-Ea/diGcw0twB5IlZPO5sgET6fJsLJqPABqTuFWIR+iMPGPZJkATEIWx0wa+aEQ5UY1CBQyP/gkAiLEqn1vBiQA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-8.0.1.tgz", + "integrity": "sha512-fDkPXRTRKGm25bAq01q82UM4ypPqdVXCwphUUm4t1dL01fGIG0v8KRvT+4BjhMAtRxtPuI34t5Vs7yjRgs3ZgQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-replace-supers": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-replace-supers": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-optional-catch-binding": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.29.7.tgz", - "integrity": "sha512-sLsyndxK2VwX6yNUOakMb7Sh553ZTe/vVM1XJ+9Z5aW1ytsc8xOIwmyk05NNjN60vkc5/KqoTH6hB4V41LJhng==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-8.0.1.tgz", + "integrity": "sha512-b2OQ74uGliyATcasTjxGy2O/86UI/n+EN4juB4EMfEwTi9j9uq70PuP0L8fW77vfRY66gO/YoTo/WbIdQ/Si1g==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-optional-chaining": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.29.7.tgz", - "integrity": "sha512-6GM1dhvK3gNODkXcEcMCOLEDCLSoZ/sBbro2Ax8HURyasQ4NshagQixkRFdh5niI6E4gmA/jYI/4aT7rRos3ZQ==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-8.0.5.tgz", + "integrity": "sha512-w8ouIDKdmUc2oyvBx4S/WtiQM7bMww5LGjB2A4L1+sDWZGw37XxzqOqfgHnPm+2ldINmAqrf2ekzpeJ/sS9poQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-parameters": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.29.7.tgz", - "integrity": "sha512-ZDOBqV/qLYJI0YElr8DcENEyARsFQeESqWXH6gZlghYXuPPjvweuDhP4VyEi4BlUBlLRFZVjxoZDMjxhLW766g==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-8.0.5.tgz", + "integrity": "sha512-oXsstDkzuE+gOqBz2+e1VFqDew0KlGgd9GT4MGptmcIq3uDbxcowHRSaqMCvp3nbiZws4wTm8Phuk9ZJO3NtTg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-private-methods": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.29.7.tgz", - "integrity": "sha512-/6Rz4DK1ETDEM/bWHsPHcaEe7ZaT1EqSXjtSP/L0DijOYuaUhiRiOKcwpZ8P7zR4xXEHc2ITdiCgBm9Tpyv9ug==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-8.0.1.tgz", + "integrity": "sha512-TrFCGcXaVDh6S5IRhmLSRTY9H80VTCMQWnZtzBRg4RWg3KCLmdmsmj4M15kZAPZfoPkWL/SJb4em3Py/vOiX8g==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-class-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-private-property-in-object": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.29.7.tgz", - "integrity": "sha512-+BNo06dnrzdNNqCm1X6YUaVv0DKk8Q+JYcoZfOkLhYWNCXzlwTSRq8zGWayT1csjcpNXV9CQTBRRbmTLZac5cA==", + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-8.0.5.tgz", + "integrity": "sha512-OilYoElZMdD/My3fJTh0jLOPy8Y9Jfpcb9nPXG0Bpy4oRbZeeVX39P1cXKsPwnXTBZg7qEKk8TQ0lzpJvdK3yw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-annotate-as-pure": "^8.0.0", + "@babel/helper-create-class-features-plugin": "^8.0.5", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-property-literals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.29.7.tgz", - "integrity": "sha512-bOMRLQuI0A5ZqHq3OWJ89/rXpJ/NJrbVhXiP4zwPGMs6kpcVsuTUNjwoE30K0Qm3mf48a/TnRYYD6vPNqcg6jA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-8.0.1.tgz", + "integrity": "sha512-Z/qx4cxUtYR1nt7XWRutObPxDks98fEYsjWbVeKEqZH6y3AGknmgzCqmHf2FHWZCl1DfoPeuJY+3hZ+35D+2tg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-regenerator": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.29.8.tgz", - "integrity": "sha512-0UpIXPtdDtMXfnV2OJAVMLpj3H/92vmkA6lpSRakmycJvj3VUy6Xs1dM8tXRugupykr5WB+LpiVl0J8LMVg2mg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-8.1.2.tgz", + "integrity": "sha512-CDkfthA0lFT+qeDesnl3GMFbV+GwgBpLafWJFY2aKBiObST5EdsmVkbf1bxxcmyUb+NDrysiNoZ/qu08FcCSow==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-regexp-modifiers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-7.29.7.tgz", - "integrity": "sha512-mB5Fs0VWrJ42ZCmc8114v60qetdaUVNkj9PmSZRmanCZM3S9hm0CFRLjRmYIsuXav14l2jvZ+4T8iiCGnhj3nQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-8.0.1.tgz", + "integrity": "sha512-02ITRDBesPdTYU0oShAzERwEPzozOUQSXlz3qrt8JGuhalBJQv9z5NjgHJPC9sS3Fsam8gDtfAEpBnqZwUIdjQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-reserved-words": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.29.7.tgz", - "integrity": "sha512-5+YhdpVgmfSmwZyLMftfaiffLRMHjzIRHFHHLdibcSyJm2pasMrKHrO3Ptrt2DRshjvpgjEJJ1zVW14WPq/6QA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-8.0.1.tgz", + "integrity": "sha512-+aykZi7ZP3U84veqfJXm3HhPZGddWFi64g7jr0ni6tb1zel+1ey+SL+IRKPoZXFyFqvYEsoqrmx4PyEJRlHl/Q==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-shorthand-properties": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.29.7.tgz", - "integrity": "sha512-I+WYbGBAiCn7nA6xBrlgPH+MB7HWb4u8pv5S0Pv7OtwNvIFvCCb24YlttKEeUFVurfBCEaOTnuhlqsb7f0Z5Dg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-8.0.1.tgz", + "integrity": "sha512-JddANd9yPVH8dYgVoNkqAH5BftnsDxFpG51Zas7sc6F3poz5QWcejHNGO8a/57IX5ByjGSzEmYk9Z7ZMa5MWaw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-spread": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.29.8.tgz", - "integrity": "sha512-4S9ksMGVWUshvgK0mKfvZky7leuG5/uoFVwMpAomJ8bMoDJiNHRVmc1EglwW/CmGVSqqWpEbXm9FmbRit22qoA==", + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-8.0.8.tgz", + "integrity": "sha512-utcuNZcN76LeCKZQ/JjwkhPgKycS/q2K84Im+CDhDToofxx0vQ4ViXwCbJZ6kPKuqKQVBrUQpdZvgxhxcRPepg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-sticky-regex": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.29.7.tgz", - "integrity": "sha512-BCHzNYJGe9l7EpwwDBN/ztlL2NYFFq8hp9ddjtUEM9f2O7S7kKV/lL6Fwo7IF7NSkYhPK2vO+86nIGltA90MsA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-8.0.1.tgz", + "integrity": "sha512-IsVP6WrZZQdaG2zLmeKwWiI+ua2NB5L1+f77C2/8z2NCDz7uxlIA/lnwocYOJk9PXcOC2sZgRls3LN4XpNduzQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-template-literals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.29.7.tgz", - "integrity": "sha512-NCSEJ4sLFU2gqAub45HYh4fus2yQ36rr6ei6vpU7NdoJqCpxvEG8E6eJpscGyXP3VHD2Ny+fSXr04k1hoUrFqA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-8.0.1.tgz", + "integrity": "sha512-JXvtj5+BJA9Qv3prDzW2z2DkGTJNmG0BObTdUD03STiu1Jr4fNQkQy3hYZgPL46a2RjcuhwBMYf49BOuJ98gnA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-typeof-symbol": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.29.7.tgz", - "integrity": "sha512-223mNGoTkBiTEWFoK+Q6Go3tueMRclO8vxxxxquNCYuNI4jWOofFKJRRDu6SDrB8Sgo1UEGW9T4GAQ8ZyRso1A==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-8.0.1.tgz", + "integrity": "sha512-+wJoxgxP2gtey0UMUOMhzMMji2XHO/Uu6MXUh/r5Yhc2jngKzK/wFxY2WNe4UCaRcMvCb4gcnB8wIgFXJsocXg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-unicode-escapes": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.29.7.tgz", - "integrity": "sha512-jCfXxSjf94lf4E0hKE0AByxF6F3/pVFqRdUUNkDJhsY0m1ZKjnN6ZYyMeHNpzflxb/0q5b7t3p+BE+SLF1WOtA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-8.0.1.tgz", + "integrity": "sha512-TAXJepIJ6vZphytTwcf+LuXi2M2ZWI43VCqNw+1ZZLPP/38Z1A8j4Mahvg8kqDgMOSM/cakk+hedTJCiw3jQuQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-unicode-property-regex": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.29.7.tgz", - "integrity": "sha512-OgZ+zoAJgZLUCunsTRQ5LAjOywDv5zzZ2/hQ5aMw1pGXyY2rtE8/chXYUmu3AlVHKpm10KEdG9aMwbI/K76ZGw==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-8.0.1.tgz", + "integrity": "sha512-zjBN9tSMSuomNDfurL69Gf7+v4D2t5uI1mSZaYJDo88SKpbduhCXqtxH7Tx66iCF6caWYwnBzSM0tnCozmQq5Q==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-unicode-regex": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.29.7.tgz", - "integrity": "sha512-7D/x/23/d/3VqZ0QA+LGbZMlGwZjztBygSWWWsfTPoQ1oQ6Q1P6Mr3d0kk42XabyUVw+fha3LqdRsFqeKqvCyA==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-8.0.1.tgz", + "integrity": "sha512-v0oO83cvT5lwbcIVRShpx4vaHD8AvM9IBowsQuTeP+kGmhh3recJQs33Bl6dlo3/2g9amlznLbFGn4VJbPCJqA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/plugin-transform-unicode-sets-regex": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.29.7.tgz", - "integrity": "sha512-BLOhLht9DOJwIxlmp91wHvkXv1lguuHS3/FwUO8HL1H0u8s4hR1gASVFyilu9iGtcTRYqjTZmlsFFeQletntEg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-8.0.1.tgz", + "integrity": "sha512-MlQeyS0K7gh0XNeLBMS/3Z07HjDOKhA7xm2L18GyxOXyiFHI9E+ZuQ4mFYmcLjluXsE/Wf6dABIqZvKpKw0Z3w==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" + "@babel/helper-create-regexp-features-plugin": "^8.0.1", + "@babel/helper-plugin-utils": "^8.0.1" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/preset-env": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.29.7.tgz", - "integrity": "sha512-GYzX36n1nsciIb0uyH0GHwxwtNwPQIcpxSeiVLDtG/B7jB5xXgchnmL1f/jCX5o+pwnaDBtO60ONSJhEBJfxYA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/compat-data": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-validator-option": "^7.29.7", - "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^7.29.7", - "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^7.29.7", - "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.29.7", - "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": "^7.29.7", - "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.29.7", - "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^7.29.7", - "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2", - "@babel/plugin-syntax-import-assertions": "^7.29.7", - "@babel/plugin-syntax-import-attributes": "^7.29.7", - "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", - "@babel/plugin-transform-arrow-functions": "^7.29.7", - "@babel/plugin-transform-async-generator-functions": "^7.29.7", - "@babel/plugin-transform-async-to-generator": "^7.29.7", - "@babel/plugin-transform-block-scoped-functions": "^7.29.7", - "@babel/plugin-transform-block-scoping": "^7.29.7", - "@babel/plugin-transform-class-properties": "^7.29.7", - "@babel/plugin-transform-class-static-block": "^7.29.7", - "@babel/plugin-transform-classes": "^7.29.7", - "@babel/plugin-transform-computed-properties": "^7.29.7", - "@babel/plugin-transform-destructuring": "^7.29.7", - "@babel/plugin-transform-dotall-regex": "^7.29.7", - "@babel/plugin-transform-duplicate-keys": "^7.29.7", - "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^7.29.7", - "@babel/plugin-transform-dynamic-import": "^7.29.7", - "@babel/plugin-transform-explicit-resource-management": "^7.29.7", - "@babel/plugin-transform-exponentiation-operator": "^7.29.7", - "@babel/plugin-transform-export-namespace-from": "^7.29.7", - "@babel/plugin-transform-for-of": "^7.29.7", - "@babel/plugin-transform-function-name": "^7.29.7", - "@babel/plugin-transform-json-strings": "^7.29.7", - "@babel/plugin-transform-literals": "^7.29.7", - "@babel/plugin-transform-logical-assignment-operators": "^7.29.7", - "@babel/plugin-transform-member-expression-literals": "^7.29.7", - "@babel/plugin-transform-modules-amd": "^7.29.7", - "@babel/plugin-transform-modules-commonjs": "^7.29.7", - "@babel/plugin-transform-modules-systemjs": "^7.29.7", - "@babel/plugin-transform-modules-umd": "^7.29.7", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.29.7", - "@babel/plugin-transform-new-target": "^7.29.7", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.29.7", - "@babel/plugin-transform-numeric-separator": "^7.29.7", - "@babel/plugin-transform-object-rest-spread": "^7.29.7", - "@babel/plugin-transform-object-super": "^7.29.7", - "@babel/plugin-transform-optional-catch-binding": "^7.29.7", - "@babel/plugin-transform-optional-chaining": "^7.29.7", - "@babel/plugin-transform-parameters": "^7.29.7", - "@babel/plugin-transform-private-methods": "^7.29.7", - "@babel/plugin-transform-private-property-in-object": "^7.29.7", - "@babel/plugin-transform-property-literals": "^7.29.7", - "@babel/plugin-transform-regenerator": "^7.29.7", - "@babel/plugin-transform-regexp-modifiers": "^7.29.7", - "@babel/plugin-transform-reserved-words": "^7.29.7", - "@babel/plugin-transform-shorthand-properties": "^7.29.7", - "@babel/plugin-transform-spread": "^7.29.7", - "@babel/plugin-transform-sticky-regex": "^7.29.7", - "@babel/plugin-transform-template-literals": "^7.29.7", - "@babel/plugin-transform-typeof-symbol": "^7.29.7", - "@babel/plugin-transform-unicode-escapes": "^7.29.7", - "@babel/plugin-transform-unicode-property-regex": "^7.29.7", - "@babel/plugin-transform-unicode-regex": "^7.29.7", - "@babel/plugin-transform-unicode-sets-regex": "^7.29.7", - "@babel/preset-modules": "0.1.6-no-external-plugins", - "babel-plugin-polyfill-corejs2": "^0.4.15", - "babel-plugin-polyfill-corejs3": "^0.14.0", - "babel-plugin-polyfill-regenerator": "^0.6.6", + "version": "8.0.7", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-8.0.7.tgz", + "integrity": "sha512-c4/6ls3f+XPhxE3iT0/Wm7Z3abRS5zH5QmXBT6LPzpxgDKyhPsQk0+xNmChY0Rvh4yotKD87K2Api6f5KSaT8w==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/compat-data": "^8.0.5", + "@babel/helper-compilation-targets": "^8.0.7", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/helper-validator-option": "^8.0.0", + "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^8.0.1", + "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^8.0.1", + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^8.0.1", + "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": "^8.0.6", + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^8.0.1", + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^8.0.1", + "@babel/plugin-transform-arrow-functions": "^8.0.1", + "@babel/plugin-transform-async-generator-functions": "^8.0.6", + "@babel/plugin-transform-async-to-generator": "^8.0.1", + "@babel/plugin-transform-block-scoped-functions": "^8.0.1", + "@babel/plugin-transform-block-scoping": "^8.0.7", + "@babel/plugin-transform-class-properties": "^8.0.1", + "@babel/plugin-transform-class-static-block": "^8.0.5", + "@babel/plugin-transform-classes": "^8.0.5", + "@babel/plugin-transform-computed-properties": "^8.0.1", + "@babel/plugin-transform-destructuring": "^8.0.5", + "@babel/plugin-transform-dotall-regex": "^8.0.1", + "@babel/plugin-transform-duplicate-keys": "^8.0.1", + "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^8.0.1", + "@babel/plugin-transform-dynamic-import": "^8.0.1", + "@babel/plugin-transform-explicit-resource-management": "^8.0.5", + "@babel/plugin-transform-exponentiation-operator": "^8.0.1", + "@babel/plugin-transform-export-namespace-from": "^8.0.1", + "@babel/plugin-transform-for-of": "^8.0.7", + "@babel/plugin-transform-function-name": "^8.0.1", + "@babel/plugin-transform-json-strings": "^8.0.1", + "@babel/plugin-transform-literals": "^8.0.1", + "@babel/plugin-transform-logical-assignment-operators": "^8.0.1", + "@babel/plugin-transform-member-expression-literals": "^8.0.1", + "@babel/plugin-transform-modules-amd": "^8.0.1", + "@babel/plugin-transform-modules-commonjs": "^8.0.1", + "@babel/plugin-transform-modules-systemjs": "^8.0.1", + "@babel/plugin-transform-modules-umd": "^8.0.1", + "@babel/plugin-transform-named-capturing-groups-regex": "^8.0.1", + "@babel/plugin-transform-new-target": "^8.0.1", + "@babel/plugin-transform-nullish-coalescing-operator": "^8.0.1", + "@babel/plugin-transform-numeric-separator": "^8.0.1", + "@babel/plugin-transform-object-rest-spread": "^8.0.1", + "@babel/plugin-transform-object-super": "^8.0.1", + "@babel/plugin-transform-optional-catch-binding": "^8.0.1", + "@babel/plugin-transform-optional-chaining": "^8.0.5", + "@babel/plugin-transform-parameters": "^8.0.5", + "@babel/plugin-transform-private-methods": "^8.0.1", + "@babel/plugin-transform-private-property-in-object": "^8.0.5", + "@babel/plugin-transform-property-literals": "^8.0.1", + "@babel/plugin-transform-regenerator": "^8.0.6", + "@babel/plugin-transform-regexp-modifiers": "^8.0.1", + "@babel/plugin-transform-reserved-words": "^8.0.1", + "@babel/plugin-transform-shorthand-properties": "^8.0.1", + "@babel/plugin-transform-spread": "^8.0.5", + "@babel/plugin-transform-sticky-regex": "^8.0.1", + "@babel/plugin-transform-template-literals": "^8.0.1", + "@babel/plugin-transform-typeof-symbol": "^8.0.1", + "@babel/plugin-transform-unicode-escapes": "^8.0.1", + "@babel/plugin-transform-unicode-property-regex": "^8.0.1", + "@babel/plugin-transform-unicode-regex": "^8.0.1", + "@babel/plugin-transform-unicode-sets-regex": "^8.0.1", + "@babel/preset-modules": "^0.2.0", + "babel-plugin-polyfill-corejs3": "^1.0.0", "core-js-compat": "^3.48.0", - "semver": "^6.3.1" + "verkit": "^0.5.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" }, "peerDependencies": { - "@babel/core": "^7.0.0-0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/preset-modules": { - "version": "0.1.6-no-external-plugins", - "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.6-no-external-plugins.tgz", - "integrity": "sha512-HrcgcIESLm9aIR842yhJ5RWan/gebQUJ6E/E5+rf0y9o6oj7w0Br+sWuL6kEQ/o/AdfvR1Je9jG18/gnpwjEyA==", + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.2.0.tgz", + "integrity": "sha512-yz0RBN2fx4fjCeFcTWsWgL7PxSRltvTa0Qg14HkWCU3qS8MO7ZSJlBVbGceynd5C9NsJwwUHNQD3dc6tYO+jqQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/types": "^7.4.4", + "@babel/helper-plugin-utils": "^8.0.1", + "@babel/plugin-transform-dotall-regex": "^8.0.1", + "@babel/plugin-transform-unicode-property-regex": "^8.0.1", + "@babel/types": "^8.0.0", "esutils": "^2.0.2" }, "peerDependencies": { - "@babel/core": "^7.0.0-0 || ^8.0.0-0 <8.0.0" + "@babel/core": "^8.0.0" } }, "node_modules/@babel/runtime": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", - "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.14.tgz", + "integrity": "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw==", "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/template": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", - "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-8.1.2.tgz", + "integrity": "sha512-9B3FA5HZWK7rTJ7nU2F03qAc/t80O/WB5YQ7NKYdvmMwpq7EUyN04APNQWpkqwSqWtOsuwR0jMSRYLFoAd1m9A==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/code-frame": "^8.0.6", + "@babel/parser": "^8.1.2", + "@babel/types": "^8.1.2" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/traverse": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", - "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-8.1.2.tgz", + "integrity": "sha512-J8OoydypQO6HGgRYiiHPMj0iBfz2XpSm5hkmd0+OEHWgQFzYL8TEvYq2y4Gu8vxRCa7g06BilFZ0Imiye5jzzg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.8", - "@babel/helper-globals": "^7.29.7", - "@babel/parser": "^7.29.8", - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.8", - "debug": "^4.3.1" + "@babel/code-frame": "^8.0.6", + "@babel/generator": "^8.1.2", + "@babel/helper-globals": "^8.0.6", + "@babel/parser": "^8.1.2", + "@babel/template": "^8.1.2", + "@babel/types": "^8.1.2", + "obug": "^3.0.0" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@babel/types": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", - "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.1.2.tgz", + "integrity": "sha512-uXt6qt2f5G61jZwNIzK1RKu7l5Xjt1VXtPPOGuVveha9fxbx0QM94U1kM4pFZKTRLjWK+X8vmwjwbIemJjiQTA==", "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7" + "@babel/helper-string-parser": "^8.1.2", + "@babel/helper-validator-identifier": "^8.0.6" }, "engines": { - "node": ">=6.9.0" + "node": "^22.18.0 || >=24.11.0" } }, "node_modules/@bcoe/v8-coverage": { @@ -1760,19 +1655,6 @@ "node": ">=18" } }, - "node_modules/@bramus/specificity": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz", - "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==", - "dev": true, - "license": "MIT", - "dependencies": { - "css-tree": "^3.0.0" - }, - "bin": { - "specificity": "bin/cli.js" - } - }, "node_modules/@buttercup/fetch": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@buttercup/fetch/-/fetch-0.2.1.tgz", @@ -1973,9 +1855,9 @@ } }, "node_modules/@conduction/nextcloud-vue": { - "version": "2.57.1", - "resolved": "https://registry.npmjs.org/@conduction/nextcloud-vue/-/nextcloud-vue-2.57.1.tgz", - "integrity": "sha512-yYN+ZZZqeN8Aj+ncgcMv4P3XWrU69vBDFnYDX4ZIHpGfC9pYpXXuLd+kDKiveap/ingjkD5Ign3miK+dutHhQA==", + "version": "2.230.0", + "resolved": "https://registry.npmjs.org/@conduction/nextcloud-vue/-/nextcloud-vue-2.230.0.tgz", + "integrity": "sha512-ExaZz00oHGAJejnn1dmVnWORh/xJZOxQvDOGZSCKhfleNXbFDKSjIlLe1k+2hesWhstgDiOAD/IZwoKQIYKumw==", "license": "EUPL-1.2", "dependencies": { "@ckpack/vue-color": "^1.6.0", @@ -2018,6 +1900,9 @@ "bin": { "manifest-migrate": "src/cli/manifest-migrate.js" }, + "engines": { + "npm": "^11.0.0" + }, "optionalDependencies": { "@mdi/js": "^7.4.47" }, @@ -2030,16 +1915,16 @@ "@nextcloud/router": "^2.0.0 || ^3.0.0", "@nextcloud/stylelint-config": "^3.2.2", "@nextcloud/vue": "^9.0.0", - "@vueuse/core": "^11.0.0 || ^14.0.0", + "@vueuse/core": "^11.0.0 || ^14.0.0 || ^15.0.0", "axe-core": "^4.10.0", "dexie": "^4.0.8", "dompurify": "^3.0.0", "eslint": "^8.56.0 || ^9.0.0 || ^10.0.0", "eslint-plugin-vue": "^9.21.0 || ^10.0.0", - "gridstack": "^12.0.0 || ^13.0.0", + "gridstack": "^12.0.0 || ^13.0.0 || ^14.0.0", "marked": ">=12 <19", "pinia": "^2.0.0 || ^3.0.0 || ^4.0.0", - "stylelint": "^17.9.1", + "stylelint": "^17.9.1 || ^18", "vue": "^3.5.0", "vue-eslint-parser": "^9.4.0 || ^10.0.0", "vue-material-design-icons": "^5.0.0" @@ -2065,24 +1950,42 @@ } } }, - "node_modules/@csstools/color-helpers": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz", - "integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT-0", + "node_modules/@conduction/nextcloud-vue/node_modules/@nextcloud/dialogs": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@nextcloud/dialogs/-/dialogs-7.6.0.tgz", + "integrity": "sha512-s6PZDNioK+iWbVm/Y2utlpWDCKqlxfh0oUaOkiQWaxZq8j5UQsh1iI1bKAnhCRFlNc/yKmj1EOVBMRQ2EDGkNQ==", + "license": "AGPL-3.0-or-later", + "dependencies": { + "@mdi/js": "^7.4.47", + "@nextcloud/auth": "^2.6.0", + "@nextcloud/axios": "^2.6.0", + "@nextcloud/browser-storage": "^0.5.0", + "@nextcloud/event-bus": "^3.3.3", + "@nextcloud/files": "^4.0.0", + "@nextcloud/initial-state": "^3.0.0", + "@nextcloud/l10n": "^3.4.1", + "@nextcloud/paths": "^3.1.0", + "@nextcloud/router": "^3.2.0", + "@nextcloud/sharing": "^0.4.0", + "@nextcloud/vue": "^9.13.1", + "@types/toastify-js": "^1.12.4", + "@vueuse/core": "^15.0.0", + "p-queue": "^9.3.3", + "toastify-js": "^1.12.0", + "vue": "^3.5.44", + "webdav": "^5.11.0" + }, "engines": { - "node": ">=20.19.0" + "node": "^22.18 || ^24 || >=26" + } + }, + "node_modules/@conduction/nextcloud-vue/node_modules/@nextcloud/dialogs/node_modules/@nextcloud/initial-state": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@nextcloud/initial-state/-/initial-state-3.0.0.tgz", + "integrity": "sha512-cV+HBdkQJGm8FxkBI5rFT/FbMNWNBvpbj6OPrg4Ae4YOOsQ15CL8InPOAw1t4XkOkQK2NEdUGQLVUz/19wXbdQ==", + "license": "GPL-3.0-or-later", + "engines": { + "node": "^20.0.0 || ^22.0.0 || ^24.0.0" } }, "node_modules/@csstools/css-calc": { @@ -2109,34 +2012,6 @@ "@csstools/css-tokenizer": "^4.0.0" } }, - "node_modules/@csstools/css-color-parser": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.1.tgz", - "integrity": "sha512-YpAJZhaHplYQkG8ib+/Fx5Y0eF2lVWi3tIvMJA6i39TLyUNp2439cifzW8VMjhlqrBjHzK5hVGugRRm2zTKI/A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "dependencies": { - "@csstools/color-helpers": "^6.1.1", - "@csstools/css-calc": "^3.3.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-parser-algorithms": "^4.0.0", - "@csstools/css-tokenizer": "^4.0.0" - } - }, "node_modules/@csstools/css-parser-algorithms": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz", @@ -2353,447 +2228,68 @@ "node": ">=14.17.0" } }, - "node_modules/@es-joy/jsdoccomment": { - "version": "0.91.0", - "resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.91.0.tgz", - "integrity": "sha512-vgqlMGNNhZxwDYbUNIHj3Hskb4R28iqdXx90ufHyt/NeuTQkeqjTDslAs9I0/GCAfbxP5BpH5WsL1R1fht5Lxg==", + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { - "@types/estree": "^1.0.9", - "@typescript-eslint/types": "^8.65.0", - "comment-parser": "1.4.7", - "esquery": "^1.7.0", - "jsdoc-type-pratt-parser": "~8.0.0" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" } }, - "node_modules/@es-joy/resolve.exports": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@es-joy/resolve.exports/-/resolve.exports-1.2.0.tgz", - "integrity": "sha512-Q9hjxWI5xBM+qW2enxfe8wDKdFWMfd0Z29k5ZJnuBqD/CasY5Zryj09aCA6owbGATWz+39p5uIdaHXpopOcG8g==", + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", "dev": true, "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", - "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", - "cpu": [ - "ppc64" - ], - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", - "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", - "cpu": [ - "arm" - ], - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", - "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", - "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", - "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", - "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", - "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", - "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", - "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", - "cpu": [ - "arm" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", - "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", - "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", - "cpu": [ - "ia32" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", - "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", - "cpu": [ - "loong64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", - "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", - "cpu": [ - "mips64el" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", - "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", - "cpu": [ - "ppc64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", - "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", - "cpu": [ - "riscv64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", - "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", - "cpu": [ - "s390x" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", - "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", - "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", - "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", - "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", - "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", - "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", - "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" } }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", - "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", - "cpu": [ - "arm64" - ], + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, "license": "MIT", "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" + "peer": true, + "dependencies": { + "tslib": "^2.4.0" } }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", - "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", - "cpu": [ - "ia32" - ], + "node_modules/@es-joy/jsdoccomment": { + "version": "0.91.0", + "resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.91.0.tgz", + "integrity": "sha512-vgqlMGNNhZxwDYbUNIHj3Hskb4R28iqdXx90ufHyt/NeuTQkeqjTDslAs9I0/GCAfbxP5BpH5WsL1R1fht5Lxg==", + "dev": true, "license": "MIT", - "optional": true, - "os": [ - "win32" - ], + "dependencies": { + "@types/estree": "^1.0.9", + "@typescript-eslint/types": "^8.65.0", + "comment-parser": "1.4.7", + "esquery": "^1.7.0", + "jsdoc-type-pratt-parser": "~8.0.0" + }, "engines": { - "node": ">=18" + "node": "^20.19.0 || ^22.13.0 || >=24" } }, - "node_modules/@esbuild/win32-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", - "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", - "cpu": [ - "x64" - ], + "node_modules/@es-joy/resolve.exports": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@es-joy/resolve.exports/-/resolve.exports-1.2.0.tgz", + "integrity": "sha512-Q9hjxWI5xBM+qW2enxfe8wDKdFWMfd0Z29k5ZJnuBqD/CasY5Zryj09aCA6owbGATWz+39p5uIdaHXpopOcG8g==", + "dev": true, "license": "MIT", - "optional": true, - "os": [ - "win32" - ], "engines": { - "node": ">=18" + "node": ">=10" } }, "node_modules/@eslint-community/eslint-utils": { @@ -2860,20 +2356,37 @@ } }, "node_modules/@eslint/config-array": { - "version": "0.23.5", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", - "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", + "version": "0.23.6", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz", + "integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==", "devOptional": true, "license": "Apache-2.0", "dependencies": { "@eslint/object-schema": "^3.0.5", "debug": "^4.3.1", - "minimatch": "^10.2.4" + "minimatch": "^11.0.5" }, "engines": { "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "devOptional": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@eslint/config-helpers": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", @@ -3132,6 +2645,12 @@ "node": ">=18.0.0" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "license": "BlueOak-1.0.0" + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -3768,20 +3287,27 @@ "integrity": "sha512-W6CLUJ2eBMw3Rec70qrsEW0jOm/3twwJv21mrmj2yORiaVmVYGS4sSS5yUwvQc1ZlDLYGPnClVWmUUMagKNsfA==", "license": "MIT" }, - "node_modules/@napi-rs/lzma-linux-x64-gnu": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", - "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", - "cpu": [ - "x64" - ], + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, "license": "MIT", "optional": true, - "os": [ - "linux" - ], + "peer": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, "engines": { - "node": "^22.20 || ^24.12 || >=25" + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" } }, "node_modules/@nextcloud/auth": { @@ -3812,18 +3338,17 @@ } }, "node_modules/@nextcloud/babel-config": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@nextcloud/babel-config/-/babel-config-1.3.0.tgz", - "integrity": "sha512-qk4mBJahzp2mkiizU9RbeABa6JhqSwR43SXptNQhM3kpxAuP2OAQQhomYnxog/XfFcYExZzOkgRBPlcLEoik0w==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@nextcloud/babel-config/-/babel-config-2.0.0.tgz", + "integrity": "sha512-oIsccWxW/VPg+fXaGeTt1MWfUaRV8A1so97wJjhsdtCjohOVlcok9kPQh6VjO5L0RGyTlKlRv230QAEV0OsOzQ==", "dev": true, "license": "AGPL-3.0-or-later", "engines": { - "node": "^20 || ^22 || ^24" + "node": "^22.18 || ^24.11 || >=26" }, "peerDependencies": { - "@babel/core": "^7.27.4", - "@babel/plugin-syntax-dynamic-import": "^7.8.3", - "@babel/preset-env": "^7.27.2" + "@babel/core": "^8.0.1", + "@babel/preset-env": "^8.0.2" } }, "node_modules/@nextcloud/browser-storage": { @@ -3871,9 +3396,9 @@ } }, "node_modules/@nextcloud/dialogs": { - "version": "7.5.0", - "resolved": "https://registry.npmjs.org/@nextcloud/dialogs/-/dialogs-7.5.0.tgz", - "integrity": "sha512-2gmv0V3ObphxRd7ZvXwTsPvn/XSf2vummdXb2LRFpkoSamWbk+41SWv7cnDQPC+Ve9p46WebDuqyG+wbefkhEw==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@nextcloud/dialogs/-/dialogs-8.0.0.tgz", + "integrity": "sha512-8uN59XKOMk7MVCh0Nxdd8hvZmZQxlVIRv8s1GrhC5+Ub0hD6yJ/8XyruF54lrkmGmBqh048/i/ZER93vwfRpDg==", "license": "AGPL-3.0-or-later", "dependencies": { "@mdi/js": "^7.4.47", @@ -3886,16 +3411,16 @@ "@nextcloud/initial-state": "^3.0.0", "@nextcloud/l10n": "^3.4.1", "@nextcloud/paths": "^3.1.0", - "@nextcloud/router": "^3.1.0", + "@nextcloud/router": "^3.2.0", "@nextcloud/sharing": "^0.4.0", - "@nextcloud/vue": "^9.9.0", - "@vueuse/core": "^14.4.0", - "p-queue": "^9.3.3", - "vue": "^3.5.41", - "webdav": "^5.10.0" + "@nextcloud/vue": "^9.13.1", + "@vueuse/core": "^15.0.0", + "p-queue": "^10.0.0", + "vue": "^3.5.44", + "webdav": "^5.11.0" }, "engines": { - "node": "^20 || ^22 || ^24" + "node": "^22.18 || ^24 || >=26" } }, "node_modules/@nextcloud/dialogs/node_modules/@nextcloud/initial-state": { @@ -3907,6 +3432,18 @@ "node": "^20.0.0 || ^22.0.0 || ^24.0.0" } }, + "node_modules/@nextcloud/dialogs/node_modules/p-queue": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-10.0.0.tgz", + "integrity": "sha512-P2wrCri3bhGLPo3kX7qYVXbo/5GvaVATU0DpO24CbeT53Y4z35t8JUWku04ERpXHUYB5rPMi3TkWE3fmJgx5rA==", + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@nextcloud/eslint-config": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/@nextcloud/eslint-config/-/eslint-config-9.0.1.tgz", @@ -3974,9 +3511,9 @@ } }, "node_modules/@nextcloud/files": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@nextcloud/files/-/files-4.1.0.tgz", - "integrity": "sha512-C45fxBxU9v5HQ437I+r4EuqG/A9CYqNnYM34ltdxFNSBMjId7DoRJrk5UDA7QsC4eB/CP1xNxFSpkY+g6RPWXA==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@nextcloud/files/-/files-4.1.1.tgz", + "integrity": "sha512-3fvaBNObXFjVgFm0FvPXr+rtYh2CUGAc0+98dhIP0AC7Q+UCVYIwyB3tsSBGP29HnqGWqGRY7nZaj7gI7NzbvQ==", "license": "AGPL-3.0-or-later", "dependencies": { "@nextcloud/auth": "^2.6.0", @@ -3985,13 +3522,13 @@ "@nextcloud/l10n": "^3.4.1", "@nextcloud/logger": "^3.0.3", "@nextcloud/paths": "^3.1.0", - "@nextcloud/router": "^3.1.0", + "@nextcloud/router": "^3.2.0", "@nextcloud/sharing": "^0.4.0", "axios-retry": "^4.5.0", "is-svg": "^6.1.0", "p-queue": "^9.3.3", "typescript-event-target": "^1.1.2", - "webdav": "^5.10.0" + "webdav": "^5.11.0" }, "engines": { "node": "^24.0.0 || >=26.0.0" @@ -4047,18 +3584,18 @@ } }, "node_modules/@nextcloud/password-confirmation": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/@nextcloud/password-confirmation/-/password-confirmation-6.1.0.tgz", - "integrity": "sha512-N2ChXDbPcUcQCoAjj1yc65zfc61yiKpdM3qm/y3Y/y//NG7XWNNINwBg85lqJ2SISgmVStpsQ1d0blpFCoQXkQ==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@nextcloud/password-confirmation/-/password-confirmation-6.2.1.tgz", + "integrity": "sha512-FRRQ0LAsUT7I9OGyUQOg86QxIyLTVLmBIbPW7lfduj9aDtYZyrrtyHjTlt8caUfdu2Q/tCr88vhbFzhvR9uMhQ==", "license": "MIT", "dependencies": { - "@nextcloud/auth": "^2.5.3", - "@nextcloud/axios": "^2.5.2", + "@nextcloud/auth": "^2.6.0", + "@nextcloud/axios": "^2.6.0", "@nextcloud/l10n": "^3.4.1", "@nextcloud/logger": "^3.0.3", "@nextcloud/router": "^3.1.0", - "@nextcloud/vue": "^9.6.0", - "vue": "^3.5.30" + "@nextcloud/vue": "^9.13.1", + "vue": "^3.5.43" }, "engines": { "node": "^20.0.0 || ^22.0.0 || ^24.0.0" @@ -4154,9 +3691,9 @@ } }, "node_modules/@nextcloud/vue": { - "version": "9.13.0", - "resolved": "https://registry.npmjs.org/@nextcloud/vue/-/vue-9.13.0.tgz", - "integrity": "sha512-XiG34Od/hMlt4VgDmHlcUXhAj2KD/4LeorsVD5sc9Vix0wqa6e3aSHjPWghll/ZD+8JnKkId6zLoexM4VqQngQ==", + "version": "9.14.1", + "resolved": "https://registry.npmjs.org/@nextcloud/vue/-/vue-9.14.1.tgz", + "integrity": "sha512-qLCYNx0fFy2ZI+2e6nmNtzNfHsU/utwCM+u67kqLUi/Uk11RrFxEXb2DxOJwodbF2K/EArtmuk3l9FJqYJ6v/g==", "license": "AGPL-3.0-or-later", "dependencies": { "@ckpack/vue-color": "^1.6.0", @@ -4173,19 +3710,19 @@ "@nextcloud/sharing": "^0.4.0", "@nextcloud/vue-select": "^4.1.0", "@vuepic/vue-datepicker": "^11.0.3", - "@vueuse/components": "^14.4.0", - "@vueuse/core": "^14.4.0", + "@vueuse/components": "^15.0.0", + "@vueuse/core": "^15.0.0", "blurhash": "^2.0.5", "clone": "^2.1.2", "debounce": "^3.0.0", - "dompurify": "^3.4.15", + "dompurify": "^3.4.17", "emoji-mart-vue-fast": "^15.0.5", "escape-html": "^1.0.3", "floating-vue": "^5.2.2", - "focus-trap": "^8.2.2", - "linkifyjs": "^4.3.3", + "focus-trap": "^8.2.3", + "linkifyjs": "^4.4.0", "mdast-util-to-string": "^4.0.0", - "p-queue": "^9.3.3", + "p-queue": "^10.0.0", "rehype-external-links": "^3.0.0", "rehype-highlight": "^7.0.2", "rehype-react": "^8.0.0", @@ -4195,21 +3732,21 @@ "remark-unlink-protocols": "^1.0.0", "splitpanes": "^4.0.4", "striptags": "^3.2.0", - "tabbable": "^6.4.0", + "tabbable": "^6.5.1", "tributejs": "^5.1.3", "ts-md5": "^2.0.1", "unified": "^11.0.5", "unist-builder": "^4.0.0", - "unist-util-visit-parents": "^6.0.2", - "vue": "^3.5.18", - "vue-router": "^5.3.1" + "unist-util-visit-parents": "^6.1.0", + "vue": "^3.5.44", + "vue-router": "^5.4.0" }, "engines": { "node": "^20.11.0 || ^22 || ^24" }, "peerDependencies": { - "@nextcloud/dialogs": "^7.4.0", - "@nextcloud/files": "^4.1.0" + "@nextcloud/dialogs": "^7.4.0 || ^8.0.0", + "@nextcloud/files": "^4.1.1" }, "peerDependenciesMeta": { "@nextcloud/dialogs": { @@ -4241,27 +3778,63 @@ "node": "^20.0.0 || ^22.0.0 || ^24.0.0" } }, + "node_modules/@nextcloud/vue/node_modules/chokidar": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-6.0.0.tgz", + "integrity": "sha512-Ec2Z7wpcKBiMpR7DxteoqS/sq5G5d2A4fpxzPv6+fD7xNNdrTghn7L11YwV5EN1B3i72Erc3XVT5FkWIDx90+A==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.1.1" + }, + "engines": { + "node": ">= 22.22" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@nextcloud/vue/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/@nextcloud/vue/node_modules/p-queue": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-10.0.0.tgz", + "integrity": "sha512-P2wrCri3bhGLPo3kX7qYVXbo/5GvaVATU0DpO24CbeT53Y4z35t8JUWku04ERpXHUYB5rPMi3TkWE3fmJgx5rA==", + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@nextcloud/vue/node_modules/vue-router": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-5.3.1.tgz", - "integrity": "sha512-GDBZzgmILxA/kFnkFbJjQZdZ2QQbngnIMMuoUcjhZIfH1RGMaPjPwX5ASnV38qamuA9uhO0RDjSBHTDNG2uXyQ==", + "version": "5.5.1", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-5.5.1.tgz", + "integrity": "sha512-lUENd/QIhKd2HWACnXID3us0GWBnuOi3BwkTUzce2+4nfM/b3seV5saNURM9+wt48/qUxviotpcm7yFxC0U4qA==", "license": "MIT", "dependencies": { - "@vue-macros/common": "^3.1.3", - "@vue/devtools-api": "^8.1.5", - "ast-walker-scope": "^0.9.0", - "chokidar": "^5.0.0", - "confbox": "^0.2.4", - "local-pkg": "^1.2.1", - "magic-string": "^0.30.21", + "@vue-macros/common": "^3.1.4", + "@vue/devtools-api": "^8.2.1", + "ast-walker-scope": "^0.10.0", + "chokidar": "^6.0.0", + "confbox": "^0.3.2", + "local-pkg": "^2.0.0", + "magic-string": "^1.4.5", "mlly": "^1.8.2", "muggle-string": "^0.4.1", - "nostics": "^1.1.4", + "nostics": "^1.3.0", "pathe": "^2.0.3", - "picomatch": "^4.0.5", + "picomatch": "^4.0.7", "scule": "^1.3.0", "tinyglobby": "^0.2.17", - "unplugin": "^3.3.0", + "unplugin": "^3.7.0", "unplugin-utils": "^0.3.2" }, "funding": { @@ -4290,9 +3863,9 @@ } }, "node_modules/@nextcloud/webpack-vue-config": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/@nextcloud/webpack-vue-config/-/webpack-vue-config-7.0.4.tgz", - "integrity": "sha512-JM4gHZZCLGVtxiILjb0RvQQRjBFbau0hQHQyNrLR+wkY3UaLMXkj9P8dT+w8/d6WIOnwLbQFY2Duox6crbgh5Q==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@nextcloud/webpack-vue-config/-/webpack-vue-config-7.1.0.tgz", + "integrity": "sha512-+bPqIOgbRhKg1ZUQjzK2pqvEE9AjaFZ8+XSWdVlK/xdxk61U6c+L+R4DSQpIzXd8Au0NCgQtJ4UWvCjQnAjlNA==", "dev": true, "hasInstallScript": true, "license": "AGPL-3.0-or-later", @@ -4300,9 +3873,9 @@ "node": "^20.0.0 || ^22.0.0 || ^24.0.0" }, "peerDependencies": { - "@babel/core": "^7.22.9", + "@babel/core": "^7.22.9 || ^8.0.0", "babel-loader": "^10.0.0", - "css-loader": "^7.1.1", + "css-loader": "^7.1.5", "minimizer-webpack-plugin": "^5.6.1", "node-polyfill-webpack-plugin": "4.0.0", "sass": "^1.64.2", @@ -4331,9 +3904,9 @@ } }, "node_modules/@nodable/entities": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.0.0.tgz", - "integrity": "sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.1.0.tgz", + "integrity": "sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==", "funding": [ { "type": "github", @@ -4519,10 +4092,22 @@ "node": ">=20.0" } }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "devOptional": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, "node_modules/@parcel/watcher": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", + "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, @@ -4562,6 +4147,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4583,6 +4169,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4604,6 +4191,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4625,6 +4213,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4646,6 +4235,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4667,6 +4257,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4688,6 +4279,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4709,6 +4301,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4730,6 +4323,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4751,6 +4345,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4772,6 +4367,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -4793,6 +4389,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5052,337 +4649,301 @@ "dev": true, "license": "MIT" }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", - "devOptional": true, - "license": "MIT" - }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz", - "integrity": "sha512-UZ8sUxPTiHWYX9QNdJedb1kDZSpS1t/VPWBWGSgqHNi9w3Cu6IXvu2mzbhiTiPvtrqgTQJ+zqiAq2iPIPilpaQ==", + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "android" - ] + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.1.tgz", - "integrity": "sha512-cQ4nFQABN5cDvDpbvJ7bMStCpnaVxynZrRMfUJYgxcIk9Sh54FIO1vtfkg0B69REjER77ioZ/ov+eAApx/KmLQ==", + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "android" - ] + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.1.tgz", - "integrity": "sha512-FQNqd1lRy/0QhDk3xeRIkSBiCpXCiDnZO3YLVdcDKN1UBiKToNftCzcXYNLshmPDUMlu2TdeS8tGcsU6f3YF1Q==", + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "darwin" - ] + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.1.tgz", - "integrity": "sha512-pvD16V939D3CloK0+qikpGaxiPrDUXTe7Y5cWOMkMSy7m1cawa8EGy/kXYi/G/cKAC4HDAbSnzCIk1WmsoOKXg==", + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.1.tgz", - "integrity": "sha512-pcFGeL2345VwdTnJhA6zLbew+YgWB0qBG2+dMtXjCicf6+rm6kO6cOoh5VnTe0ZMrMRgRyuHmCJxZWrIdzYuOw==", - "cpu": [ - "arm64" ], - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.1.tgz", - "integrity": "sha512-mRJlqSRulVzcKq/LKA6ICSIc3K/l4fzlVn/gePn2nXIHy8seRi5z/eeRE0d/XMBxcMldiXtQTSpRj0tkkC3g8Q==", + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.1.tgz", - "integrity": "sha512-YDUNvVM85TI3g/1OpnqKP1h4NeW/j64DfWMf+G3M809xNk1bJSnpFp4sh83NpmVE5DXnkh8ULor4LTVZKoYLHw==", - "cpu": [ - "arm" ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.1.tgz", - "integrity": "sha512-7Mcn71p9ZuQFAj+h+dhQXy/yeLePRS2yKRnmW1DijA9thKO5qap0GNOIQK4yQ6iP3SU0Mrb/yWo8h8vgRba8lw==", + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.1.tgz", - "integrity": "sha512-4YiLQTX6U4CSl0L9cluep9A9W6UmTfqBDc2/CH6wlu54pl4E7Jn3cOD8oxzvBDEGk/JMKgJ47C8g+radF7mwvg==", - "cpu": [ - "arm64" ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.1.tgz", - "integrity": "sha512-2ra8F7w8OquwZN9z2/fKFnli69wa8PLwaVzRMIPGb13ByMJwC28Fbp8YcVGoUhlYMTt7j5j9bNgpysrN2UM+vw==", + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.1.tgz", - "integrity": "sha512-Sy20ncyhjmBP0Ml+UvQbimjlk6VFgjW5uNP+qqwHB00mTE8Bl2C1TuHTlRwK2YoXeZbee5lP2XevBWVkAQAtSQ==", - "cpu": [ - "loong64" ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.1.tgz", - "integrity": "sha512-noITLp8oNjYliPnGWmLyelIHwULGqbHloQHGw1rtxbWhTuWooRpnZarZQJ1y9EUC4szuCusCc+HEpUtxpIwYvA==", + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", "cpu": [ - "loong64" + "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.1.tgz", - "integrity": "sha512-hlxxXd+F1mWiAcaFR7Sv9ZQT6m6UfI8+Vy/kFJzztq2pDMU/0wZ9sish0iszNZvsQDo8Gc0i5yuFEOz5dDf6fA==", - "cpu": [ - "ppc64" ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.1.tgz", - "integrity": "sha512-EF7OpqQTQ/BvGqLzUi4rEHuagCV9MugAUXSHemwPW5vxZ75RR+jxO/2j95Ph2dalMpFHSVECjRoioHZgA9zOYA==", + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", "cpu": [ "ppc64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.1.tgz", - "integrity": "sha512-wQO3JesW9PRkwlabQ27y7sPfVOOTLRG73I4F2UYHG5PXun3J9U3y+b7ezVKSYbsvSKGQ1k1cq8Qlun4C9kLt3w==", - "cpu": [ - "riscv64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.1.tgz", - "integrity": "sha512-ouAGwhO6wHRXdnOVCOsB0tRFkA7nhNB2Nwax6oECXN0YiN8EYUTBAOudADOB1PI+yDL61TeNx/u7MVCzksNbkQ==", - "cpu": [ - "riscv64" ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.1.tgz", - "integrity": "sha512-q2R38Sn+1J8RxhfJ+T54wSWmyKXWec+9jgDfqO2AtArEqHO5R2aeayp5H5OYLr5UYDVGsVaZPEFUooMhYCdz5A==", + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", "cpu": [ "s390x" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.1.tgz", - "integrity": "sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w==", + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.1.tgz", - "integrity": "sha512-4h6XqthmB4Hspji84wvgk+ElodTsGj+dbZqHJHHtKxj4mYq0ANSEEPX9ys3moJueqsRjwpaJYH7874Itwnj2ow==", + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" - ] - }, - "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.1.tgz", - "integrity": "sha512-dlfCOa87o1VAYegLQ9EKilx2JCeRofiyPGhTCmqnuXZ6bMPiycO1rq1+sKoulAp7pGLIsTIw+1x5R+zgh5LhhA==", - "cpu": [ - "x64" ], - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ] + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.1.tgz", - "integrity": "sha512-cjkLbOlfcm3QGhMM1J5zaZjsw1GggbN6rw9UTSSRrPrR1KkcXnN7Uq9rPw34xImQ9VOY9GN+6u2Zj80B9ptkcw==", + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "openharmony" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.1.tgz", - "integrity": "sha512-Li1KdUnWGE4N3e1F/B4RTB1ms+nG4WBgjByO46pkeBVX/2UBsY53xf5vK9WygVmnH3RwncIST7lkSdLSY6P9lg==", - "cpu": [ - "arm64" ], - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.1.tgz", - "integrity": "sha512-t4ZYOSoLTgwhuFMrmTMLx/+i1DQVK7HYqMc6kY46EApwi8X0nIVphzdNoThU3xt6n+N5urG1/gxBdCaKDLavfg==", + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", "cpu": [ - "ia32" + "wasm32" ], + "dev": true, "license": "MIT", "optional": true, - "os": [ - "win32" - ] + "peer": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } }, - "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.1.tgz", - "integrity": "sha512-RgroPfMmKlD1RzSDxvwgcPiy2HNQKoYV7OmwIXDsk73uKW5t6B/V8KIy27SMv/FNXFo/oSBtWc9J0X7t91ezZg==", + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", "cpu": [ - "x64" + "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "win32" - ] + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.1.tgz", - "integrity": "sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w==", + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "win32" - ] + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "license": "MIT" }, "node_modules/@sindresorhus/base62": { "version": "1.0.0", @@ -5410,18 +4971,11 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@standard-schema/spec": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", - "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "dev": true, - "license": "MIT" - }, "node_modules/@stylistic/eslint-plugin": { "version": "5.10.0", "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin/-/eslint-plugin-5.10.0.tgz", "integrity": "sha512-nPK52ZHvot8Ju/0A4ucSX1dcPV2/1clx0kLcH5wDmrE4naKso7TUC/voUyU1O9OTKTrR6MYip6LP0ogEMQ9jPQ==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", @@ -5510,18 +5064,24 @@ "prosemirror-view": "^1.18.7" } }, - "node_modules/@toast-ui/editor/node_modules/dompurify": { - "version": "2.5.9", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-2.5.9.tgz", - "integrity": "sha512-i6mvVmWN4xo9LrhCOZrDgSs9noW6nOahbrmzjRbPF36YPyj5Ue5lgok0MHDWkG7xzpWFO2OYttXdzM7rJxHvNA==", - "license": "(MPL-2.0 OR Apache-2.0)" - }, "node_modules/@tokenizer/token": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", "license": "MIT" }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@types/body-parser": { "version": "1.19.6", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", @@ -5650,6 +5210,14 @@ "@types/send": "*" } }, + "node_modules/@types/gensync": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/gensync/-/gensync-1.0.5.tgz", + "integrity": "sha512-MbsRCT7mTikHwKZ0X+LVUTLRrZZRLipTuXEO9qOYO+zmjMVk81axyClMROf6uoPD9MRVu46bx8zoR0Ad9q3NAg==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/@types/hast": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", @@ -5676,6 +5244,14 @@ "@types/sizzle": "*" } }, + "node_modules/@types/jsesc": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@types/jsesc/-/jsesc-2.5.1.tgz", + "integrity": "sha512-9VN+6yxLOPLOav+7PwjZbxiID2bVaeq0ED4qSQmdQTdjnXJSaCVKTR58t15oqH1H5t8Ng2ZX1SabJVoN9Q34bw==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -5768,6 +5344,12 @@ "integrity": "sha512-TC0dmN0K8YcWEAEfiPi5gJP14eJe30TTGjkvek3iM/1NdHHsdCA/Td6GvNndMOo/iSnIsZ4HuuhrYPDAmbxzww==", "license": "MIT" }, + "node_modules/@types/toastify-js": { + "version": "1.12.4", + "resolved": "https://registry.npmjs.org/@types/toastify-js/-/toastify-js-1.12.4.tgz", + "integrity": "sha512-zfZHU4tKffPCnZRe7pjv/eFKzTVHozKewFCKaCjZ4gFinKgJRz/t0bkZiMCXJxPhv/ZoeDGNOeRD09R0kQZ/nw==", + "license": "MIT" + }, "node_modules/@types/trusted-types": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", @@ -5838,16 +5420,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.70.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.70.0.tgz", - "integrity": "sha512-zYvrmj9Yxd63UGaXw+kdt6A0F0s0qveJyuatIM77bYC2DE4pgmg7a50u8LR7PRtXd0x+h+Tl3eXabGm06SWd3Q==", - "devOptional": true, + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.73.0.tgz", + "integrity": "sha512-AuL45bVcmssHfZ3Di3cs9Q0l4gBm4ZFVrJOQEE7VpqW+PVgQaEwSwazz4TVIiFabXkk6U51EprYDwqw+HR8ePw==", + "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.70.0", - "@typescript-eslint/types": "8.70.0", - "@typescript-eslint/typescript-estree": "8.70.0", - "@typescript-eslint/visitor-keys": "8.70.0", + "@typescript-eslint/scope-manager": "8.73.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0", "debug": "^4.4.3" }, "engines": { @@ -5863,14 +5445,14 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/project-service": { - "version": "8.70.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.70.0.tgz", - "integrity": "sha512-hFHbTNqhU9G+2eKFXCBVb1tjFT/LceiJ4+HfLO4pTpDI0KHi6iajpcFFkaSQ9gXmCh7n82A0PthaayEdN6mspQ==", - "devOptional": true, + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.73.0.tgz", + "integrity": "sha512-/pEf8Rc4Mjk+qJnY0uO1+Gadeal8uv50xpuic+srG2vIVatA0XxvWMUeMtFvs6OCHqftiQ7/+qH4aehG5stzIA==", + "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.70.0", - "@typescript-eslint/types": "^8.70.0", + "@typescript-eslint/tsconfig-utils": "^8.73.0", + "@typescript-eslint/types": "^8.73.0", "debug": "^4.4.3" }, "engines": { @@ -5885,14 +5467,14 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/scope-manager": { - "version": "8.70.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.70.0.tgz", - "integrity": "sha512-8nP3Kwh5hlgZ4FicGvmznAmJe8UL4sdU8tLukrPaMuQmDuk4Y8xYfzu/aYZW4xT2JCgc7H/TpDI5cGlxcWJSqQ==", - "devOptional": true, + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.73.0.tgz", + "integrity": "sha512-/TjD738Iq2rzj5z0ixVOi+TsvgjAzZPLPaH1yWdDBytR/HTR5gMpyYWZeCe5WTQZLwk3ho8AV7U3muoQCRtXBQ==", + "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.70.0", - "@typescript-eslint/visitor-keys": "8.70.0" + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -5903,10 +5485,10 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.70.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.70.0.tgz", - "integrity": "sha512-adnkeeNq9Sq1sUf4+FRVc0KdgYghzsgFpZSQVZVvY0LCuUuN0FnQgyGzCJeC4fW1cdXseBAjU2EOqUIjbNcZUw==", - "devOptional": true, + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.73.0.tgz", + "integrity": "sha512-lmtCFOfYaJfpqZywGuXi4FpNtE+NQ+YLe3T0K9rtEDcW8ZuGWvfI++pj8r05sYMI8vWT2CYK4rWyedmD6Rp4og==", + "dev": true, "license": "MIT", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -5920,10 +5502,10 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/types": { - "version": "8.70.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.70.0.tgz", - "integrity": "sha512-asTOIYhDg4zdzOScCyaytrsV3cR6B4ecPQlXw/dJIm7J/MZTtCtfVII9JD8Geh4jTCrK/Xe6cg5UevoleMcoJQ==", - "devOptional": true, + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.73.0.tgz", + "integrity": "sha512-O/1ytYzflF16QDKXx4/qOXg1IuZp+n7hr9t+S0nv7N/2Tl8rJiNCshztV1gcSUvHbPtoX3+zmNbtSAyVbzxVfw==", + "dev": true, "license": "MIT", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -5934,18 +5516,18 @@ } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/typescript-estree": { - "version": "8.70.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.70.0.tgz", - "integrity": "sha512-d9NmHMPEKQ7QCLLm1jI3zmoQBwT5KwFYjXBJ9ymZfKCUU+5rmTRykKAFvH5Qn/ZCds3CEAFS9OC9M/jkl0X2bA==", - "devOptional": true, + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.73.0.tgz", + "integrity": "sha512-InjlBkSdWceIwIBWSwS3ENUp+i0O02PGX3Zv2wnihWJC1WDVGvG7mTHuf8b57uAaITj94d6tRPDH+sUEtXdRQQ==", + "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.70.0", - "@typescript-eslint/tsconfig-utils": "8.70.0", - "@typescript-eslint/types": "8.70.0", - "@typescript-eslint/visitor-keys": "8.70.0", + "@typescript-eslint/project-service": "8.73.0", + "@typescript-eslint/tsconfig-utils": "8.73.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0", "debug": "^4.4.3", - "minimatch": "^10.2.2", + "minimatch": "^11.0.1", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" @@ -5958,17 +5540,23 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { + "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev", "typescript": ">=4.8.4 <6.1.0" + }, + "peerDependenciesMeta": { + "@typescript/native": { + "optional": true + } } }, "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/visitor-keys": { - "version": "8.70.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.70.0.tgz", - "integrity": "sha512-BoC8PiO4Hkdo0TVJh9Ntxr5MxPDI7/oFsrygN5ADelFSeXG/qgNuucIGA+L5Z6JpPTE/uRfcTWtscjbUaufepQ==", - "devOptional": true, + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.73.0.tgz", + "integrity": "sha512-k4lsFVpRZICbltkIEEH4hZRkwXkqDF1GHBpClKQOHQY+RkoZAAuyc1ci3I6p+CB6v3U4jaHIUshc4RzzQXZWLg==", + "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.70.0", + "@typescript-eslint/types": "8.73.0", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -5983,7 +5571,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "devOptional": true, + "dev": true, "license": "Apache-2.0", "engines": { "node": "^20.19.0 || ^22.13.0 || >=24" @@ -5992,11 +5580,28 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@typescript-eslint/parser/node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@typescript-eslint/parser/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "devOptional": true, + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -6091,7 +5696,7 @@ "version": "8.68.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.68.0.tgz", "integrity": "sha512-9RnpsGJjrAllCMefGVVsImJM24YurhC0Q1h4UbvivtvOqXmR/vEJge2OoE++z9m6hyg8T1Q8t5SNT6tHSbrxcg==", - "devOptional": true, + "dev": true, "license": "MIT", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -6252,29 +5857,27 @@ } }, "node_modules/@vitest/coverage-v8": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.11.tgz", - "integrity": "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.1.0.tgz", + "integrity": "sha512-OY9aShBQG5KOIw2zCo9fDoCHI9RHliNHJ//nM7m6jGg41Hyke9JOGWmeMlK74xYErsxMoK8mIB3gAeEyFVA7LA==", "dev": true, "license": "MIT", "dependencies": { "@bcoe/v8-coverage": "^1.0.2", - "@vitest/utils": "4.1.11", - "ast-v8-to-istanbul": "^1.0.0", - "istanbul-lib-coverage": "^3.2.2", - "istanbul-lib-report": "^3.0.1", - "istanbul-reports": "^3.2.0", - "magicast": "^0.5.2", - "obug": "^2.1.1", - "std-env": "^4.0.0-rc.1", - "tinyrainbow": "^3.1.0" + "@vitest/istanbul-lib-coverage": "^2.1.0", + "@vitest/istanbul-lib-report": "^2.1.0", + "ast-v8-to-istanbul": "^1.0.7", + "magicast": "^0.5.5", + "obug": "^3.0.0", + "std-env": "^4.3.0", + "tinyrainbow": "^3.2.0" }, "funding": { "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "@vitest/browser": "4.1.11", - "vitest": "4.1.11" + "@vitest/browser": "5.1.0", + "vitest": "5.1.0" }, "peerDependenciesMeta": { "@vitest/browser": { @@ -6282,40 +5885,46 @@ } } }, - "node_modules/@vitest/expect": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", - "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "node_modules/@vitest/istanbul-lib-coverage": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-2.1.0.tgz", + "integrity": "sha512-WOjuS+xcjSIy7ruYBQ+9BUcV7XZQ0FyVcbWbWxW9TRx/kLGx5SQaeFRIFDJxjNplb6YsT7SpKo2zuXXUo91OIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22" + } + }, + "node_modules/@vitest/istanbul-lib-report": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-2.1.0.tgz", + "integrity": "sha512-+ZFta25nWtGCOBG9/IET8w1RO5Oawsd6H8Uf6AJ9EA/StFuKVtKAEJEJ6uRt84OH+T4YkI0ASmIHAhRA+0KVxw==", "dev": true, "license": "MIT", "dependencies": { - "@standard-schema/spec": "^1.1.0", - "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", - "chai": "^6.2.2", - "tinyrainbow": "^3.1.0" + "@vitest/istanbul-lib-coverage": "2.1.0" }, - "funding": { - "url": "https://opencollective.com/vitest" + "engines": { + "node": ">=22" } }, "node_modules/@vitest/mocker": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", - "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.1.11", + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", "estree-walker": "^3.0.3", - "magic-string": "^0.30.21" + "magic-string": "^1.4.3" }, "funding": { "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "msw": "^2.4.9", + "msw": "^2.4.9 || ^3.0.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { @@ -6337,53 +5946,33 @@ "@types/estree": "^1.0.0" } }, - "node_modules/@vitest/pretty-format": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", - "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", - "dev": true, - "license": "MIT", - "dependencies": { - "tinyrainbow": "^3.1.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/runner": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", - "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.1.11", - "pathe": "^2.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" + "@jridgewell/sourcemap-codec": "^1.6.0" } }, - "node_modules/@vitest/snapshot": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", - "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "node_modules/@vitest/pretty-format": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-5.1.0.tgz", + "integrity": "sha512-IRx5mc30CrFzyMNni6SZKQ1r53kv049Mcvvk0WbWcD6PUz/bFjG4zYv0KosQAeonPpGp5WxqYBMqdSOfJfvVWw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.11", - "@vitest/utils": "4.1.11", - "magic-string": "^0.30.21", - "pathe": "^2.0.3" + "tinyrainbow": "^3.2.0" }, "funding": { "url": "https://opencollective.com/vitest" } }, "node_modules/@vitest/spy": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", - "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", "dev": true, "license": "MIT", "funding": { @@ -6391,37 +5980,36 @@ } }, "node_modules/@vitest/ui": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/ui/-/ui-4.1.11.tgz", - "integrity": "sha512-r/rwyKoev21mWdRGSEkZOqkQ2BYy68mwjihg9M90nNRbf4NGrgzZ4cj6JNCEwlOGJkbKeMgsjlykvwKUbRr7gw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/ui/-/ui-5.1.0.tgz", + "integrity": "sha512-00S3x4NRmqIBUiTVWF9/xLaA9EP9KeKv0+1sBO7e2Y4luBISlW+2ttnhlk/zjbTqEvVhJWCCo7MXzu6zNbefqQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.1.11", - "fflate": "^0.8.2", - "flatted": "^3.4.2", + "@vitest/utils": "5.1.0", + "fflate": "^0.8.3", + "flatted": "^3.4.4", "pathe": "^2.0.3", "sirv": "^3.0.2", - "tinyglobby": "^0.2.15", - "tinyrainbow": "^3.1.0" + "tinyrainbow": "^3.2.0" }, "funding": { "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "vitest": "4.1.11" + "vitest": "5.1.0" } }, "node_modules/@vitest/utils": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", - "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-5.1.0.tgz", + "integrity": "sha512-V+qgCwkvVw+s1t1S5TaoBHsLi5Sz/YmohCMoOu0mZ8ZQst2bKhRYARAQucWpVg8D0mv0x5MHcWXY5QdOsoiGBQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.11", + "@vitest/pretty-format": "5.1.0", "convert-source-map": "^2.0.0", - "tinyrainbow": "^3.1.0" + "tinyrainbow": "^3.2.0" }, "funding": { "url": "https://opencollective.com/vitest" @@ -6508,54 +6096,179 @@ } } }, + "node_modules/@vue-macros/common/node_modules/local-pkg": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.2.1.tgz", + "integrity": "sha512-++gUqRDEvcnN6Zhqrr+y/CkVEHhlrR96vZn3nZZPYzMcBUyBtTKzB9NadClFIsIVSsu+3i9tfk/erqy9kAmt7Q==", + "license": "MIT", + "dependencies": { + "mlly": "^1.7.4", + "pkg-types": "^2.3.0", + "quansync": "^0.2.11" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vue-macros/common/node_modules/quansync": { + "version": "0.2.11", + "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", + "integrity": "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/antfu" + }, + { + "type": "individual", + "url": "https://github.com/sponsors/sxzz" + } + ], + "license": "MIT" + }, "node_modules/@vue/compiler-core": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.42.tgz", - "integrity": "sha512-2Ye1ilMtKXxl8qZUrQ5j0CdgenFp/HFQmta6rfRyfEsTG69L6Wk+tWuNoHYHMx9E8tF2Slvdg1FuwDvAXdy1LQ==", + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.45.tgz", + "integrity": "sha512-XGHJrM6ufZARAc/w+tyOswStw9tdKiqCKBScI4gGaNxD+aaGu/HQWgKJ+JItjRLPqenQ7iE7G8AJC7T5ew1p+g==", "license": "MIT", "dependencies": { - "@babel/parser": "^7.29.8", - "@vue/shared": "3.5.42", + "@babel/parser": "^7.29.12", + "@vue/shared": "3.5.45", "entities": "^7.0.1", "estree-walker": "^2.0.2", - "source-map-js": "^1.2.1" + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-core/node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@vue/compiler-core/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@vue/compiler-core/node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@vue/compiler-core/node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.45.tgz", + "integrity": "sha512-LbP2d19GSOYGPmvMBBCVJVlv7TKtjM1Cfeyu3cYia720pknZP+1cLX7H5MVatvruT6MuJhiPuNbQBW/MDn/EwA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.45.tgz", + "integrity": "sha512-MKFjb2UX0M/l/jhfzqMLrI8VM4pfvFKG3pqFZkSZFHRLtNld/O4RtUPZFWSwhro/14qP88UQEkWzHxAZAQ0tsw==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.12", + "@vue/compiler-core": "3.5.45", + "@vue/compiler-dom": "3.5.45", + "@vue/compiler-ssr": "3.5.45", + "@vue/shared": "3.5.45", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.32", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-sfc/node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@vue/compiler-sfc/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" } }, - "node_modules/@vue/compiler-dom": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.42.tgz", - "integrity": "sha512-qbhQZEFmycr+ni/qyuccS4sucNN7VAbDfbkvNxWOX2VfgFm90MNs3/UhRNKoPMEIVn0F8gdlYjLPvqxHwHeQOA==", + "node_modules/@vue/compiler-sfc/node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", "license": "MIT", "dependencies": { - "@vue/compiler-core": "3.5.42", - "@vue/shared": "3.5.42" + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" } }, - "node_modules/@vue/compiler-sfc": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.42.tgz", - "integrity": "sha512-fkCAFB4okcAANGMThboWnScp/gzWjU0ZSkVnjTIiplmMDq2uq0tIB3j+xVu4rhv5rvOgBySCysudmbMd6xRRqw==", + "node_modules/@vue/compiler-sfc/node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", "license": "MIT", "dependencies": { - "@babel/parser": "^7.29.8", - "@vue/compiler-core": "3.5.42", - "@vue/compiler-dom": "3.5.42", - "@vue/compiler-ssr": "3.5.42", - "@vue/shared": "3.5.42", - "estree-walker": "^2.0.2", - "magic-string": "^0.30.21", - "postcss": "^8.5.19", - "source-map-js": "^1.2.1" + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" } }, "node_modules/@vue/compiler-ssr": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.42.tgz", - "integrity": "sha512-xmLk3wLkbizPAiLyomjgFFosf2ys9b5Ghb+oh/k2tnvipNz8OFrQOiTcWCzyK7MpBp9KkyGtfvgfLUivbmuGYA==", + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.45.tgz", + "integrity": "sha512-RF5sbZOfYz5AK00tOJUn2PwFXR2fS1u2HVzI8D9VF9rGAFxuGBqg2bB1kJ3ZHMprqSltXnT9MZE1IsqjSM8oew==", "license": "MIT", "dependencies": { - "@vue/compiler-dom": "3.5.42", - "@vue/shared": "3.5.42" + "@vue/compiler-dom": "3.5.45", + "@vue/shared": "3.5.45" } }, "node_modules/@vue/devtools-api": { @@ -6586,51 +6299,51 @@ "license": "MIT" }, "node_modules/@vue/reactivity": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.42.tgz", - "integrity": "sha512-TzNNfKpb7hDxbQltwAut8VDQA5YP+BuRlxntHUuRjyKwlMvmAPbs3unhCvieijifY6vFfVBwsS7wG/C7uq+bEQ==", + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.45.tgz", + "integrity": "sha512-WqkyubNWpI4OYBOipSrjIssMdJO8K1i9Zts/Wm8Er10/0msOEwCyWWWvZnAI7WW3kQsTong6DJp8Cbb+vd4cPA==", "license": "MIT", "dependencies": { - "@vue/shared": "3.5.42" + "@vue/shared": "3.5.45" } }, "node_modules/@vue/runtime-core": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.42.tgz", - "integrity": "sha512-9uACtuHs7vJGkm5Bp3xu4xRDLFTIYy5DgxpToVjqGIAhAEKwQfsaLvKINhM6nFVp6bZPRFGdDqd1g52MqKsotA==", + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.45.tgz", + "integrity": "sha512-bzIO3+FABjpj85uIKSc+Qnj36/sxDNI3tcH9i6w6xKA1k6e0ejv0G0jMCfeJBvK3yGL5XbJ3DMZj+ClqyCHFYw==", "license": "MIT", "dependencies": { - "@vue/reactivity": "3.5.42", - "@vue/shared": "3.5.42" + "@vue/reactivity": "3.5.45", + "@vue/shared": "3.5.45" } }, "node_modules/@vue/runtime-dom": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.42.tgz", - "integrity": "sha512-rsCmhiWLaRxGltLwhlCWyYkFn7WAbKRh0q17eZ1A6Dq6eqc2ACQ61IIryxz0LrsvCzHSilLA9JHovVwM8CNE2g==", + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.45.tgz", + "integrity": "sha512-ZvRTFMDgfqTDYWvJfoVpQTJx1RN5M6l7Pyd6wfdY2NaXzbPQVh9ezeQYFbNPP6bIcRVn2SqSSR25N/jSW69BFw==", "license": "MIT", "dependencies": { - "@vue/reactivity": "3.5.42", - "@vue/runtime-core": "3.5.42", - "@vue/shared": "3.5.42", + "@vue/reactivity": "3.5.45", + "@vue/runtime-core": "3.5.45", + "@vue/shared": "3.5.45", "csstype": "^3.2.3" } }, "node_modules/@vue/server-renderer": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.42.tgz", - "integrity": "sha512-2++5dUyYS4gvo7xQXSECUDhB7TS0aOl5SeVfC5qSq1Jgfhjvegw1zqhwTIR3imZ+QYPJQw9gfcFvXGAjGZ7ajQ==", + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.45.tgz", + "integrity": "sha512-1fNXUHhhsWf4EVL4XixbGBU5mKdiIXJAB82feHRTyPPo6ZUEYWIJuEeUl3mVV6QDBp50HJOX4obLhxYXlrjrzA==", "license": "MIT", "dependencies": { - "@vue/compiler-ssr": "3.5.42", - "@vue/runtime-dom": "3.5.42", - "@vue/shared": "3.5.42" + "@vue/compiler-ssr": "3.5.45", + "@vue/runtime-dom": "3.5.45", + "@vue/shared": "3.5.45" } }, "node_modules/@vue/shared": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.42.tgz", - "integrity": "sha512-2rPxex1jQf4jvl9MOHl6YaXCPcrNqz/FstMOEh3QWY+/OME9nQTvl9WYeCwhW7AFjaR0SnngZGlp/wkR6rkI6g==", + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.45.tgz", + "integrity": "sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==", "license": "MIT" }, "node_modules/@vue/test-utils": { @@ -6689,13 +6402,16 @@ } }, "node_modules/@vueuse/components": { - "version": "14.4.0", - "resolved": "https://registry.npmjs.org/@vueuse/components/-/components-14.4.0.tgz", - "integrity": "sha512-USgxljmrGUTjtMJcOCbjU7SlRP6K1i5inM6JgMD8bOBn/oL4dK0XYTtNfWyuo0FgUhtCftIKXi+4vJ8ml+tmqw==", + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/@vueuse/components/-/components-15.0.0.tgz", + "integrity": "sha512-gX6FE9oVef+HUKhfUx9OTxJ+XGFjDEMi5p+Y7Pr2gYgxumSnfsfA/J0BgoI0GTK6x/x0Iu8AYbl1KM2w4g/T2g==", "license": "MIT", "dependencies": { - "@vueuse/core": "14.4.0", - "@vueuse/shared": "14.4.0" + "@vueuse/core": "15.0.0", + "@vueuse/shared": "15.0.0" + }, + "engines": { + "node": ">=22" }, "peerDependencies": { "vue": "^3.5.0" @@ -7297,10 +7013,56 @@ "url": "https://github.com/sponsors/sxzz" } }, + "node_modules/ast-kit/node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/ast-kit/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/ast-kit/node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/ast-kit/node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/ast-v8-to-istanbul": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.5.tgz", - "integrity": "sha512-UPAgKJFSEGMWSDr3LX4tqnAb4f7KGT8O40Tyx8wbYmmZ/yn58lNCm8h3svs3eXgiGd5AXxz8NDOvXWvicq+rJA==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.8.tgz", + "integrity": "sha512-lPdpagk13ANXV+HClJEpCZM7kUsl5XcvgqKzZhaj6Ve1ZFICcY2sGhAN1n1vT0tML6EclT7bfVgTxqL57Gkpow==", "dev": true, "license": "MIT", "dependencies": { @@ -7319,30 +7081,49 @@ "@types/estree": "^1.0.0" } }, - "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", - "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", - "dev": true, - "license": "MIT" - }, "node_modules/ast-walker-scope": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/ast-walker-scope/-/ast-walker-scope-0.9.0.tgz", - "integrity": "sha512-IJdzo2vLiElBxKzwS36VsCue/62d6IdWjnPB2v3nuPKeWGynp6FF/CYoLa5i/3jXH/z97ZDdsXz6abpgM6w07A==", + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/ast-walker-scope/-/ast-walker-scope-0.10.0.tgz", + "integrity": "sha512-KzvoxDfXNz2Gm8KYLh47K3qcY3Zza3WKOuh2xoqa7LBu6MDKWAZLovJtU9DuAd/Er+rhQHCRn619lHS5U+qmhw==", "license": "MIT", "dependencies": { - "@babel/parser": "^7.29.2", - "@babel/types": "^7.29.0", - "ast-kit": "^2.2.0" + "@babel/parser": "^8.0.0", + "@babel/types": "^8.0.0", + "ast-kit": "^3.0.0" }, "engines": { - "node": ">=20.19.0" + "node": "^22.18.0 || >=24.11.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/ast-walker-scope/node_modules/ast-kit": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ast-kit/-/ast-kit-3.0.1.tgz", + "integrity": "sha512-fCGiQvmHghhf858e/SVGh2aUo/FsbtB5qB8bifo6ygHK5OMcGna56FUvS0IrYvo+unYwIi1nCklEh/KUaOKVmg==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^8.1.0", + "estree-walker": "^3.0.3", + "pathe": "^2.0.3" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" }, "funding": { "url": "https://github.com/sponsors/sxzz" } }, + "node_modules/ast-walker-scope/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, "node_modules/astral-regex": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", @@ -7376,6 +7157,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/axe-core": { + "version": "4.14.1", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.1.tgz", + "integrity": "sha512-FHfa+lmNjQZfJz1q8wKqIDwC6DExcHt/pkjNQb09a3NPjCKg2rhu5qb2S4r76ASyFNNtuFooJpZe37OgudVGtQ==", + "devOptional": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, "node_modules/axios": { "version": "1.20.0", "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", @@ -7427,49 +7218,22 @@ } } }, - "node_modules/babel-plugin-polyfill-corejs2": { - "version": "0.4.17", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.17.tgz", - "integrity": "sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/compat-data": "^7.28.6", - "@babel/helper-define-polyfill-provider": "^0.6.8", - "semver": "^6.3.1" - }, - "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" - } - }, "node_modules/babel-plugin-polyfill-corejs3": { - "version": "0.14.2", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.14.2.tgz", - "integrity": "sha512-coWpDLJ410R781Npmn/SIBZEsAetR4xVi0SxLMXPaMO4lSf1MwnkGYMtkFxew0Dn8B3/CpbpYxN0JCgg8mn67g==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-1.0.0.tgz", + "integrity": "sha512-yIkslVjbmml2Xjb6XhFW7lISXHsqk6cesxTdDsXoMom4Lnb99DbD3OQbSOoM5Z+ASh8YXYaLAsRQrU2Jeh3Qig==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@babel/helper-define-polyfill-provider": "^0.6.8", + "@babel/helper-define-polyfill-provider": "^1.0.0", "core-js-compat": "^3.48.0" }, - "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" - } - }, - "node_modules/babel-plugin-polyfill-regenerator": { - "version": "0.6.8", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.8.tgz", - "integrity": "sha512-M762rNHfSF1EV3SLtnCJXFoQbbIIz0OyRwnCmV0KPC7qosSfCO0QLTSuJX3ayAebubhE6oYBAYPrBA5ljowaZg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/helper-define-polyfill-provider": "^0.6.8" + "engines": { + "node": "^20.19.0 || >=22.12.0" }, "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + "@babel/core": "^7.4.0 || ^8.0.0" } }, "node_modules/bail": { @@ -7486,7 +7250,6 @@ "version": "4.0.4", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "devOptional": true, "license": "MIT", "engines": { "node": "18 || 20 || >=22" @@ -7540,14 +7303,31 @@ "license": "MIT", "peer": true }, - "node_modules/bidi-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", - "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", "dev": true, "license": "MIT", "dependencies": { - "require-from-string": "^2.0.2" + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, "node_modules/bindings": { @@ -7640,20 +7420,20 @@ "peer": true }, "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "dev": true, "license": "MIT", "peer": true, "dependencies": { "bytes": "^3.1.2", - "content-type": "^2.0.0", + "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", + "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", - "qs": "^6.15.2", + "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, @@ -7703,10 +7483,9 @@ "license": "ISC" }, "node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", - "devOptional": true, + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" @@ -8041,9 +7820,9 @@ "optional": true }, "node_modules/cacache/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.8.tgz", + "integrity": "sha512-BnlDzDYQoplTsZSvPi86CNzmbcb07X8ufR8fk1zivaiEJlXJkiq1MQyDCVmlWcsWbj6aWXqHnrwwevbrm/Saig==", "dev": true, "license": "MIT", "optional": true, @@ -8224,9 +8003,9 @@ } }, "node_modules/chai": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", - "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", "dev": true, "license": "MIT", "engines": { @@ -8302,7 +8081,9 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "dev": true, "license": "MIT", + "peer": true, "dependencies": { "readdirp": "^5.0.0" }, @@ -8493,9 +8274,9 @@ } }, "node_modules/compression": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", - "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.2.tgz", + "integrity": "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==", "dev": true, "license": "MIT", "peer": true, @@ -8503,6 +8284,7 @@ "bytes": "3.1.2", "compressible": "~2.0.18", "debug": "2.6.9", + "destroy": "1.2.0", "negotiator": "~0.6.4", "on-headers": "~1.1.0", "safe-buffer": "5.2.1", @@ -8510,6 +8292,10 @@ }, "engines": { "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/compression/node_modules/debug": { @@ -8543,9 +8329,9 @@ } }, "node_modules/confbox": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", - "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz", + "integrity": "sha512-ZUAKhKlkCOrIGKc8cj7zek9s9z1mveHif/25nUshI2BzCRzF7KH7KHa+Lnh2ubq+e1tIlaFuP763mzW4qVoehg==", "license": "MIT" }, "node_modules/config-chain": { @@ -8644,9 +8430,9 @@ } }, "node_modules/core-js": { - "version": "3.50.0", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.50.0.tgz", - "integrity": "sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==", + "version": "3.51.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.51.0.tgz", + "integrity": "sha512-7bDKx/5jm5MxzsXxc93g6Z2+4ZsuT/MddrfRmTDJNAkWsYWHU8EVNEsBiIEWnMAMCHMmRfUEjkuo3jeNBOIHRw==", "hasInstallScript": true, "license": "MIT", "engines": { @@ -8894,19 +8680,6 @@ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" } }, - "node_modules/cssesc": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", - "devOptional": true, - "license": "MIT", - "bin": { - "cssesc": "bin/cssesc" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -9028,50 +8801,17 @@ } }, "node_modules/data-urls": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", - "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", "dev": true, "license": "MIT", "dependencies": { "whatwg-mimetype": "^5.0.0", - "whatwg-url": "^16.0.0" - }, - "engines": { - "node": "^20.19.0 || ^22.12.0 || >=24.0.0" - } - }, - "node_modules/data-urls/node_modules/@exodus/bytes": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz", - "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^20.19.0 || ^22.12.0 || >=24.0.0" - }, - "peerDependencies": { - "@noble/hashes": "^1.8.0 || ^2.0.0" - }, - "peerDependenciesMeta": { - "@noble/hashes": { - "optional": true - } - } - }, - "node_modules/data-urls/node_modules/whatwg-url": { - "version": "16.0.1", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", - "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@exodus/bytes": "^1.11.0", - "tr46": "^6.0.0", - "webidl-conversions": "^8.0.1" + "whatwg-url": "^17.1.2" }, "engines": { - "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + "node": "^22.14.0 || >=24.0.0" } }, "node_modules/date-fns": { @@ -9293,6 +9033,18 @@ "minimalistic-assert": "^1.0.0" } }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, "node_modules/detect-indent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-7.0.2.tgz", @@ -9310,8 +9062,8 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "devOptional": true, "license": "Apache-2.0", - "optional": true, "engines": { "node": ">=8" } @@ -9343,9 +9095,9 @@ } }, "node_modules/dexie": { - "version": "4.4.6", - "resolved": "https://registry.npmjs.org/dexie/-/dexie-4.4.6.tgz", - "integrity": "sha512-hJP/BO6mjB+tX6hToIO1kmxYLNmun90wYbfcoAoLpKEyDYal/k33dg0TAfoUe2TDsbbLoVIzljJ3BN2UbR5EOg==", + "version": "4.4.7", + "resolved": "https://registry.npmjs.org/dexie/-/dexie-4.4.7.tgz", + "integrity": "sha512-wemFiCl3DTCnfzyqepUTX1ugbYbkTrw3aEZOG7YjAOUoEQB5g5PrEywPzk5JpbX/SxqQ9IvjUpxCDIEjoOWEfA==", "license": "Apache-2.0" }, "node_modules/diffie-hellman": { @@ -9467,9 +9219,9 @@ } }, "node_modules/dompurify": { - "version": "3.4.15", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.15.tgz", - "integrity": "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==", + "version": "3.4.18", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.18.tgz", + "integrity": "sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==", "license": "(MPL-2.0 OR Apache-2.0)", "optionalDependencies": { "@types/trusted-types": "^2.0.7" @@ -9605,6 +9357,17 @@ "devOptional": true, "license": "MIT" }, + "node_modules/empathic": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.1.0.tgz", + "integrity": "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=14" + } + }, "node_modules/encodeurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", @@ -9757,48 +9520,6 @@ "node": ">= 0.4" } }, - "node_modules/esbuild": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", - "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", - "devOptional": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.25.12", - "@esbuild/android-arm": "0.25.12", - "@esbuild/android-arm64": "0.25.12", - "@esbuild/android-x64": "0.25.12", - "@esbuild/darwin-arm64": "0.25.12", - "@esbuild/darwin-x64": "0.25.12", - "@esbuild/freebsd-arm64": "0.25.12", - "@esbuild/freebsd-x64": "0.25.12", - "@esbuild/linux-arm": "0.25.12", - "@esbuild/linux-arm64": "0.25.12", - "@esbuild/linux-ia32": "0.25.12", - "@esbuild/linux-loong64": "0.25.12", - "@esbuild/linux-mips64el": "0.25.12", - "@esbuild/linux-ppc64": "0.25.12", - "@esbuild/linux-riscv64": "0.25.12", - "@esbuild/linux-s390x": "0.25.12", - "@esbuild/linux-x64": "0.25.12", - "@esbuild/netbsd-arm64": "0.25.12", - "@esbuild/netbsd-x64": "0.25.12", - "@esbuild/openbsd-arm64": "0.25.12", - "@esbuild/openbsd-x64": "0.25.12", - "@esbuild/openharmony-arm64": "0.25.12", - "@esbuild/sunos-x64": "0.25.12", - "@esbuild/win32-arm64": "0.25.12", - "@esbuild/win32-ia32": "0.25.12", - "@esbuild/win32-x64": "0.25.12" - } - }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -9829,9 +9550,9 @@ } }, "node_modules/eslint": { - "version": "10.11.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.11.0.tgz", - "integrity": "sha512-P7a6UEEqb9G95MYAtqkmsTbVXIYyzIfl6NGOIJk162PaahFxFyeGcrlXYFSiagECg4sEm8IseJdZBKR3rx6MsQ==", + "version": "10.15.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz", + "integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==", "devOptional": true, "license": "MIT", "workspaces": [ @@ -9840,11 +9561,11 @@ "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", - "@eslint/config-array": "^0.23.5", + "@eslint/config-array": "^0.23.6", "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", "@eslint/plugin-kit": "^0.7.3", - "@humanfs/node": "^0.16.6", + "@humanfs/node": "^0.16.8", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", @@ -9865,7 +9586,7 @@ "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "minimatch": "^10.2.5", + "minimatch": "^11.0.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, @@ -10165,6 +9886,23 @@ "devOptional": true, "license": "MIT" }, + "node_modules/eslint/node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "devOptional": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/espree": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", @@ -10410,9 +10148,9 @@ } }, "node_modules/exsolve": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.1.1.tgz", - "integrity": "sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz", + "integrity": "sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg==", "license": "MIT" }, "node_modules/extend": { @@ -10472,9 +10210,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.6.tgz", - "integrity": "sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "funding": [ { "type": "github", @@ -10488,9 +10226,9 @@ "license": "BSD-3-Clause" }, "node_modules/fast-xml-builder": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.1.tgz", - "integrity": "sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.2.tgz", + "integrity": "sha512-OX91VSlShLPDgRZV7tk/YQ4l8tT75QziF5Ixg8g4PFbCVPjuTWwN+yQfAxLJ0dufJpprdOd6HlM74Jhd39TcBQ==", "funding": [ { "type": "github", @@ -10504,9 +10242,9 @@ } }, "node_modules/fast-xml-parser": { - "version": "5.11.1", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.11.1.tgz", - "integrity": "sha512-TBw6K/fxoQGGjCmZDw9w/ZwP3uDcnTM4YH/g+PFRWr8sbe5idXtxNN6vITh4+1ruCZaho6uBFurElsA7F0zzgw==", + "version": "5.12.1", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.12.1.tgz", + "integrity": "sha512-wR8dO/fx+z8C5exuem1e7BKOWvjsuzvjS/tvA/Xu3Z1zQqJGcXrPzXbcAiaMgp2KjreEROcTkmnnisrcmJ2hYQ==", "funding": [ { "type": "github", @@ -10515,11 +10253,11 @@ ], "license": "MIT", "dependencies": { - "@nodable/entities": "^3.0.0", - "fast-xml-builder": "^1.2.0", - "is-unsafe": "^2.0.0", + "@nodable/entities": "^3.1.0", + "fast-xml-builder": "^1.3.2", + "is-unsafe": "^2.0.3", "path-expression-matcher": "^1.6.2", - "strnum": "^2.4.2", + "strnum": "^2.5.1", "xml-naming": "^0.3.0" }, "bin": { @@ -10695,16 +10433,15 @@ "license": "ISC" }, "node_modules/floating-vue": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/floating-vue/-/floating-vue-5.2.2.tgz", - "integrity": "sha512-afW+h2CFafo+7Y9Lvw/xsqjaQlKLdJV7h1fCHfcYQ1C4SVMlu7OAekqWgu5d4SgvkBVU0pVpLlVsrSTBURFRkg==", + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/floating-vue/-/floating-vue-5.4.0.tgz", + "integrity": "sha512-hb5y5N8sXs9Dy4iZfWBKLzf3FkUkqhbkQREhRulAEvIihMlSGxc/7pXGrIDetoqXm/RRHNVjvN6lql9IhMM+tQ==", "license": "MIT", "dependencies": { - "@floating-ui/dom": "~1.1.1", - "vue-resize": "^2.0.0-alpha.1" + "@floating-ui/dom": "^1.8.0" }, "peerDependencies": { - "@nuxt/kit": "^3.2.0", + "@nuxt/kit": "^3.2.0 || ^4.0.0 || ^5.0.0-0", "vue": "^3.2.0" }, "peerDependenciesMeta": { @@ -10713,28 +10450,30 @@ } } }, - "node_modules/floating-vue/node_modules/@floating-ui/dom": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.1.1.tgz", - "integrity": "sha512-TpIO93+DIujg3g7SykEAGZMDtbJRrmnYRCNYSjJlvIbGhBjRSNTLVbNeDQBrzy9qDgUbiWdc7KA0uZHZ2tJmiw==", + "node_modules/flru": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz", + "integrity": "sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog==", + "dev": true, "license": "MIT", - "dependencies": { - "@floating-ui/core": "^1.1.0" + "peer": true, + "engines": { + "node": ">=6" } }, "node_modules/focus-trap": { - "version": "8.2.2", - "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-8.2.2.tgz", - "integrity": "sha512-qV0g8hRYBqgACcFOH3f9wXc4zPKhr/0z9RI2a6ZijZ72EeBi4g8oBy8zAWuUR1TsMpOzwpUMFvjdasrC41Joug==", + "version": "8.2.5", + "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-8.2.5.tgz", + "integrity": "sha512-VrqfyRXaHZ0EkhXlfyalszmhnSN9yjdYXwlwLSRoJrDJ0/eswY5J5Avj/Hcd/PrOHCMnsMhwx7+7+s1kmv9Asg==", "license": "MIT", "dependencies": { - "tabbable": "^6.5.0" + "tabbable": "^6.5.2" } }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", "funding": [ { "type": "individual", @@ -10862,12 +10601,14 @@ "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, "os": [ "darwin" ], + "peer": true, "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } @@ -11269,9 +11010,9 @@ } }, "node_modules/hast-util-to-jsx-runtime": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", - "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==", + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.7.tgz", + "integrity": "sha512-F7DNV2NMcTxA4GqPVHnXzX+mpoPHAIY9rJAVH3CZ1FdBZOcBUEjUuvMkMpHVs/sicEtznh9tMGj5WUR9S4E2rg==", "license": "MIT", "dependencies": { "@types/estree": "^1.0.0", @@ -11286,7 +11027,7 @@ "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", - "style-to-js": "^1.0.0", + "style-to-object": "^2.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" }, @@ -11296,15 +11037,12 @@ } }, "node_modules/hast-util-to-text": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.2.tgz", - "integrity": "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.3.tgz", + "integrity": "sha512-5yrlWOvGFs6CqHriUpSsNrjzT/Tdo+IOQudbznxOn8K5qblp18MJyzOg8IgDOKQ8MYgQcJA7SusuCjSpDr8mSA==", "license": "MIT", "dependencies": { - "@types/hast": "^3.0.0", - "@types/unist": "^3.0.0", - "hast-util-is-element": "^3.0.0", - "unist-util-find-after": "^5.0.0" + "@types/hast": "^3.0.0" }, "funding": { "type": "opencollective", @@ -11389,22 +11127,22 @@ "license": "MIT" }, "node_modules/html-encoding-sniffer": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", - "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", "dev": true, "license": "MIT", "dependencies": { - "@exodus/bytes": "^1.6.0" + "@exodus/bytes": "^1.15.1" }, "engines": { - "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + "node": "^22.13.0 || >=24.0.0" } }, "node_modules/html-encoding-sniffer/node_modules/@exodus/bytes": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz", - "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", "dev": true, "license": "MIT", "engines": { @@ -11413,10 +11151,25 @@ "peerDependencies": { "@noble/hashes": "^1.8.0 || ^2.0.0" }, - "peerDependenciesMeta": { - "@noble/hashes": { - "optional": true - } + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/html-encoding-sniffer/node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, "node_modules/html-entities": { @@ -11436,13 +11189,6 @@ ], "license": "MIT" }, - "node_modules/html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true, - "license": "MIT" - }, "node_modules/html-tags": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/html-tags/-/html-tags-5.1.0.tgz", @@ -11668,7 +11414,7 @@ "version": "5.1.9", "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.9.tgz", "integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==", - "devOptional": true, + "dev": true, "license": "MIT", "peer": true }, @@ -11746,9 +11492,9 @@ "license": "ISC" }, "node_modules/inline-style-parser": { - "version": "0.2.7", - "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", - "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==", + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.9.tgz", + "integrity": "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg==", "license": "MIT" }, "node_modules/interpret": { @@ -11763,9 +11509,9 @@ } }, "node_modules/ip-address": { - "version": "10.7.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.0.tgz", - "integrity": "sha512-BGFsyJd5mpXp3rK6jIdADLNgpJUK1jnjzvYF8lK+VyDab9JAmqN0YOKDdP17HlgKb2+ehPgDc8EtnRLbGCAMhA==", + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", "dev": true, "license": "MIT", "optional": true, @@ -12165,9 +11911,9 @@ } }, "node_modules/is-unsafe": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.2.tgz", - "integrity": "sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.3.tgz", + "integrity": "sha512-ZBllczCCO267vgdFb6Tq3pv+LhHaCiGMdr+ZsuL+OopruAg7S+3ZDs1vD0RPC0uSrkjzbraxaGjtX1YBxjPeFQ==", "funding": [ { "type": "github", @@ -12219,45 +11965,6 @@ "node": ">=0.10.0" } }, - "node_modules/istanbul-lib-coverage": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", - "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^4.0.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-reports": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", - "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/jackspeak": { "version": "3.4.3", "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", @@ -12334,10 +12041,10 @@ "license": "MIT" }, "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "devOptional": true, + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, "license": "MIT" }, "node_modules/js-yaml": { @@ -12374,50 +12081,47 @@ } }, "node_modules/jsdom": { - "version": "30.0.1", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.0.1.tgz", - "integrity": "sha512-52v7mUVUfNQVYYqE1lcdaymWL0njO7lTLUog6ZvW2U5KsbiLk/GnZlVJ+qx0xfNJZ6Gn+KSpPNE52vurbxZwrA==", + "version": "31.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.1.tgz", + "integrity": "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==", "dev": true, "license": "MIT", "dependencies": { - "@asamuzakjp/css-color": "^6.0.5", - "@asamuzakjp/dom-selector": "^8.3.0", - "@bramus/specificity": "^2.4.2", - "@csstools/css-syntax-patches-for-csstree": "^1.1.7", - "@exodus/bytes": "^1.15.1", - "css-tree": "^3.2.1", - "data-urls": "^7.0.0", + "@exodus/bytes": "^1.16.0", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", + "data-urls": "^8.0.0", "decimal.js": "^10.6.0", - "html-encoding-sniffer": "^6.0.0", + "html-encoding-sniffer": "^7.0.0", "is-potential-custom-element-name": "^1.0.1", - "lru-cache": "^11.5.2", - "parse5": "^8.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", "saxes": "^6.0.0", - "symbol-tree": "^3.2.4", "tough-cookie": "^6.0.2", - "undici": "^8.9.0", - "w3c-xmlserializer": "^5.0.0", + "undici": "^8.12.3", + "w3c-xmlserializer": "^6.0.0", "webidl-conversions": "^8.0.1", "whatwg-mimetype": "^5.0.0", - "whatwg-url": "^17.1.0", + "whatwg-url": "^17.3.0", "xml-name-validator": "^5.0.0" }, "engines": { "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "peerDependencies": { - "canvas": "^3.2.3" + "@napi-rs/canvas": "^1.0.13" }, "peerDependenciesMeta": { - "canvas": { + "@napi-rs/canvas": { "optional": true } } }, "node_modules/jsdom/node_modules/@exodus/bytes": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz", - "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", "dev": true, "license": "MIT", "engines": { @@ -12432,10 +12136,25 @@ } } }, + "node_modules/jsdom/node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/jsdom/node_modules/lru-cache": { - "version": "11.5.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", - "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", "dev": true, "license": "BlueOak-1.0.0", "engines": { @@ -12500,87 +12219,360 @@ "@keyv/serialize": "^1.1.1" } }, - "node_modules/kind-of": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", - "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", - "devOptional": true, - "license": "MIT", + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/known-css-properties": { + "version": "0.37.0", + "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz", + "integrity": "sha512-JCDrsP4Z1Sb9JwG0aJ8Eo2r7k4Ou5MwmThS/6lcIe1ICyb7UBJKGRIUUdqc2ASdE/42lgz6zFUnzAIhtXnBVrQ==", + "devOptional": true, + "license": "MIT", + "peer": true + }, + "node_modules/launch-editor": { + "version": "2.14.2", + "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.2.tgz", + "integrity": "sha512-NHJEb30MGBCkmZXLZwz25t37QR4aY03ZzPYUJXOJaOa92uWwExI9SBQUuIznBYc1xkD7cJNGX7oc3Nl3sq2kQQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "picocolors": "^1.1.1", + "shell-quote": "^1.10.0" + } + }, + "node_modules/layerr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/layerr/-/layerr-3.0.0.tgz", + "integrity": "sha512-tv754Ki2dXpPVApOrjTyRo4/QegVb9eVFq4mjqp4+NM5NaX7syQvN5BBNfV/ZpAHCEHV24XdUVrBAoka4jt3pA==", + "license": "MIT" + }, + "node_modules/leaflet": { + "version": "1.9.4", + "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz", + "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==", + "license": "BSD-2-Clause" + }, + "node_modules/leaflet.markercluster": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/leaflet.markercluster/-/leaflet.markercluster-1.5.3.tgz", + "integrity": "sha512-vPTw/Bndq7eQHjLBVlWpnGeLa3t+3zGiuM7fJwCkiMFq+nmRuG3RI3f7f4N4TDX7T4NpbAXpR2+NTRSEGfCSeA==", + "license": "MIT", + "peerDependencies": { + "leaflet": "^1.3.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/libxmljs2": { + "version": "0.37.0", + "resolved": "https://registry.npmjs.org/libxmljs2/-/libxmljs2-0.37.0.tgz", + "integrity": "sha512-Xb78V8GZouoZFrq8cCwx7+G3WYOcJG0xb3YUbweSyE4z2EIrQCZMr3Ye/dHn4mESs6YxUMeQeUZm5IXg+iLHog==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "dependencies": { + "bindings": "~1.5.0", + "nan": "~2.22.2", + "node-gyp": "^11.2.0", + "prebuild-install": "^7.1.3" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "devOptional": true, + "license": "MPL-2.0", + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, "engines": { - "node": ">=0.10.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/known-css-properties": { - "version": "0.37.0", - "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz", - "integrity": "sha512-JCDrsP4Z1Sb9JwG0aJ8Eo2r7k4Ou5MwmThS/6lcIe1ICyb7UBJKGRIUUdqc2ASdE/42lgz6zFUnzAIhtXnBVrQ==", - "devOptional": true, - "license": "MIT", - "peer": true - }, - "node_modules/launch-editor": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.1.tgz", - "integrity": "sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==", + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], "dev": true, - "license": "MIT", + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], "peer": true, - "dependencies": { - "picocolors": "^1.1.1", - "shell-quote": "^1.8.4" + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/layerr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/layerr/-/layerr-3.0.0.tgz", - "integrity": "sha512-tv754Ki2dXpPVApOrjTyRo4/QegVb9eVFq4mjqp4+NM5NaX7syQvN5BBNfV/ZpAHCEHV24XdUVrBAoka4jt3pA==", - "license": "MIT" - }, - "node_modules/leaflet": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz", - "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==", - "license": "BSD-2-Clause" - }, - "node_modules/leaflet.markercluster": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/leaflet.markercluster/-/leaflet.markercluster-1.5.3.tgz", - "integrity": "sha512-vPTw/Bndq7eQHjLBVlWpnGeLa3t+3zGiuM7fJwCkiMFq+nmRuG3RI3f7f4N4TDX7T4NpbAXpR2+NTRSEGfCSeA==", - "license": "MIT", - "peerDependencies": { - "leaflet": "^1.3.1" + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, "engines": { - "node": ">= 0.8.0" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/libxmljs2": { - "version": "0.37.0", - "resolved": "https://registry.npmjs.org/libxmljs2/-/libxmljs2-0.37.0.tgz", - "integrity": "sha512-Xb78V8GZouoZFrq8cCwx7+G3WYOcJG0xb3YUbweSyE4z2EIrQCZMr3Ye/dHn4mESs6YxUMeQeUZm5IXg+iLHog==", + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], "dev": true, - "hasInstallScript": true, - "license": "MIT", + "license": "MPL-2.0", "optional": true, - "dependencies": { - "bindings": "~1.5.0", - "nan": "~2.22.2", - "node-gyp": "^11.2.0", - "prebuild-install": "^7.1.3" - }, + "os": [ + "win32" + ], + "peer": true, "engines": { - "node": ">=22" + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, "node_modules/lines-and-columns": { @@ -12591,23 +12583,23 @@ "license": "MIT" }, "node_modules/linkifyjs": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.3.tgz", - "integrity": "sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.4.0.tgz", + "integrity": "sha512-InTexvtbai+2c+dEVGcc6O6P2DMVIiwD9a/i4zFroazOIYLOS6FSVmAJ7kFeumnCMx6/gQqNAkbUvgMubV4+MA==", "license": "MIT" }, "node_modules/local-pkg": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.2.1.tgz", - "integrity": "sha512-++gUqRDEvcnN6Zhqrr+y/CkVEHhlrR96vZn3nZZPYzMcBUyBtTKzB9NadClFIsIVSsu+3i9tfk/erqy9kAmt7Q==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-2.0.0.tgz", + "integrity": "sha512-xvTNwM27EpU+fkLSpo33Pq/nm8m5zNf0aU/hF4W4ZM9RHQjVZa5KTmmXIzEzVsdI09NOUqj0djHhTv96sUowSQ==", "license": "MIT", "dependencies": { - "mlly": "^1.7.4", - "pkg-types": "^2.3.0", - "quansync": "^0.2.11" + "mlly": "^1.8.2", + "pkg-types": "^2.3.1", + "quansync": "^1.0.0" }, "engines": { - "node": ">=14" + "node": ">=20.19.0" }, "funding": { "url": "https://github.com/sponsors/antfu" @@ -12675,17 +12667,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "license": "ISC", - "peer": true, - "dependencies": { - "yallist": "^3.0.2" - } - }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -12711,9 +12692,9 @@ } }, "node_modules/magicast": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.4.tgz", - "integrity": "sha512-llBEhWm1SacoRwgHUoQJYtwp4PBLF4faQi5TCpIGyGs9n4y5+juI0tDgyKIfpqxckRHaHzouUEph3THklWh03w==", + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", "dev": true, "license": "MIT", "dependencies": { @@ -12722,33 +12703,54 @@ "source-map-js": "^1.2.1" } }, - "node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "node_modules/magicast/node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/magicast/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/magicast/node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", "dev": true, "license": "MIT", "dependencies": { - "semver": "^7.5.3" + "@babel/types": "^7.29.14" }, - "engines": { - "node": ">=10" + "bin": { + "parser": "bin/babel-parser.js" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "engines": { + "node": ">=6.0.0" } }, - "node_modules/make-dir/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "node_modules/magicast/node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" }, "engines": { - "node": ">=10" + "node": ">=6.9.0" } }, "node_modules/make-fetch-happen": { @@ -12852,15 +12854,15 @@ } }, "node_modules/mdast-util-find-and-replace": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz", - "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.4.tgz", + "integrity": "sha512-z4B5c6jrnJ1ltOQemhWYPBSAo6y42Z8Gt2yEgfgNTMcLSU59B8bfj8Z8AnAlJrBGLnqkdAUZ7jdDEqQw3KuipQ==", "license": "MIT", "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" + "unist-util-visit-parents": "^6.1.0" }, "funding": { "type": "opencollective", @@ -12880,9 +12882,9 @@ } }, "node_modules/mdast-util-from-markdown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz", - "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz", + "integrity": "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A==", "license": "MIT", "dependencies": { "@types/mdast": "^4.0.0", @@ -12922,9 +12924,9 @@ } }, "node_modules/mdast-util-mdx-jsx": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz", - "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.1.tgz", + "integrity": "sha512-oXp1GIa+E9IwIs3a106+tr3Bz2MlTTBvlXjOZMoIat11kk7vjqgmBnksB9WHmWv+gZh7k3IUgpAHlwHB7DH4GQ==", "license": "MIT", "dependencies": { "@types/estree-jsx": "^1.0.0", @@ -12992,9 +12994,9 @@ } }, "node_modules/mdast-util-to-hast": { - "version": "13.2.1", - "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", - "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", + "version": "13.2.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.2.tgz", + "integrity": "sha512-l2pnmOuqs+SGLVpTVXnRLQu5v1AzvDe181404fbXzzqObVxrAnnVxapAP27pUwzLBL/ABIkgUhGlPVU7QSvIFg==", "license": "MIT", "dependencies": { "@types/hast": "^3.0.0", @@ -13013,9 +13015,9 @@ } }, "node_modules/mdast-util-to-markdown": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz", - "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==", + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.2.3.tgz", + "integrity": "sha512-dImdB6VZRMRac1SwAW6o1c0ESk/7pFFAMCMuKM+9v7LpTSthMM5nzXpqKw4Mjo66aXVKhNkyrP4bMB9MurPyWg==", "license": "MIT", "dependencies": { "@types/mdast": "^4.0.0", @@ -13023,8 +13025,10 @@ "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", + "micromark-util-character": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" }, @@ -13140,9 +13144,9 @@ } }, "node_modules/micromark": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", - "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", + "integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==", "funding": [ { "type": "GitHub Sponsors", @@ -13165,6 +13169,7 @@ "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", @@ -13175,9 +13180,9 @@ } }, "node_modules/micromark-core-commonmark": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz", - "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz", + "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==", "funding": [ { "type": "GitHub Sponsors", @@ -13194,18 +13199,19 @@ "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", - "micromark-factory-space": "^2.0.0", + "micromark-factory-space": "^2.1.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" + "micromark-util-types": "^2.0.3" } }, "node_modules/micromark-factory-destination": { @@ -13252,9 +13258,9 @@ } }, "node_modules/micromark-factory-space": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz", - "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz", + "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==", "funding": [ { "type": "GitHub Sponsors", @@ -13436,6 +13442,25 @@ "micromark-util-symbol": "^2.0.0" } }, + "node_modules/micromark-util-edit-map": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz", + "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, "node_modules/micromark-util-encode": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", @@ -13566,9 +13591,9 @@ "license": "MIT" }, "node_modules/micromark-util-types": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", - "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", "funding": [ { "type": "GitHub Sponsors", @@ -13686,7 +13711,7 @@ "version": "10.2.6", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", - "devOptional": true, + "dev": true, "license": "BlueOak-1.0.0", "dependencies": { "brace-expansion": "^5.0.8" @@ -14026,9 +14051,9 @@ "optional": true }, "node_modules/nanoid": { - "version": "3.3.18", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", - "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", "funding": [ { "type": "github", @@ -14162,6 +14187,7 @@ "version": "7.1.1", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "dev": true, "license": "MIT", "optional": true, "peer": true @@ -14405,9 +14431,9 @@ } }, "node_modules/nostics": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/nostics/-/nostics-1.2.0.tgz", - "integrity": "sha512-FGqEfhQjrvo1lL8KFifdTQiNwwQHJxC1jtYE1Rc54qF/jxONUNL+kC9gS1krX8Q65PgrQ5fCqH/I4NhWBvdSqg==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/nostics/-/nostics-1.4.0.tgz", + "integrity": "sha512-WjXHOuNuzY3MPKOoCT2zL1Sa3cS2mOUe4o8F94JvBOH2cGfyNItbQmCb2pNHIxoodd5O+vtmmHq7PoSZVGgCHA==", "license": "MIT" }, "node_modules/nth-check": { @@ -14496,9 +14522,9 @@ } }, "node_modules/obug": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", - "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", "dev": true, "funding": [ "https://github.com/sponsors/sxzz", @@ -14795,19 +14821,51 @@ "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", "devOptional": true, "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - }, + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-json/node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/parse-json/node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "devOptional": true, + "license": "MIT", "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=6.9.0" } }, + "node_modules/parse-json/node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "devOptional": true, + "license": "MIT" + }, "node_modules/parse-statements": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/parse-statements/-/parse-statements-1.0.11.tgz", @@ -14816,22 +14874,35 @@ "license": "MIT" }, "node_modules/parse5": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", - "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz", + "integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==", "dev": true, "license": "MIT", "dependencies": { - "entities": "^8.0.0" + "parse5": "^8.1.1" }, "funding": { "url": "https://github.com/inikulin/parse5?sponsor=1" } }, "node_modules/parse5/node_modules/entities": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz", - "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", "dev": true, "license": "BSD-2-Clause", "engines": { @@ -14955,9 +15026,9 @@ "license": "MIT" }, "node_modules/pbkdf2": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.6.tgz", - "integrity": "sha512-BT6eelPB1EyGHo8pC0o9Bl6k6SYVhKO1jEbd3lcTrtr7XHdjP8BW1YpfCV3G9Kwkxgattk+S5q2/RvuttCsS1g==", + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.7.tgz", + "integrity": "sha512-nS4mvFgVwUrecPTRdpdseM2fwpdfnX0/HibA8DgBRQtihUAzHQYJFU2l+OlEtiXtpqkrMvCPDwyXMUnASDt6Qw==", "dev": true, "license": "MIT", "peer": true, @@ -14998,18 +15069,18 @@ } }, "node_modules/pinia": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/pinia/-/pinia-4.0.3.tgz", - "integrity": "sha512-XMQqpvjgG7LMqVhhFUzKLT4KEbsYbfZZ0CZU9PgdFm1O2VKBmIkykL8+SfNhOaT7sR0wT6BEgKT0YNDYWgmVRA==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/pinia/-/pinia-4.1.0.tgz", + "integrity": "sha512-+5/HMuVjYQfKlCD5xQ7zfXn1xUzYFEa7pd0DQK5SaMfZCaFRTHlaH/c02N1FoGOdlzSiwf5EOPgJx//1QDw6gw==", "license": "MIT", "dependencies": { - "nostics": "^1.1.4" + "nostics": "^1.2.0" }, "funding": { "url": "https://github.com/sponsors/posva" }, "peerDependencies": { - "@vue/devtools-api": "^8.1.5", + "@vue/devtools-api": "^8.2.1", "typescript": ">=5.6.0", "vue": "^3.5.11" }, @@ -15097,22 +15168,16 @@ } }, "node_modules/pkg-types": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.3.tgz", - "integrity": "sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.4.0.tgz", + "integrity": "sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==", "license": "MIT", "dependencies": { "confbox": "^0.3.1", - "exsolve": "^1.1.1", + "exsolve": "^1.1.3", "pathe": "^2.0.3" } }, - "node_modules/pkg-types/node_modules/confbox": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.1.tgz", - "integrity": "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==", - "license": "MIT" - }, "node_modules/pkijs": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.0.tgz", @@ -15173,9 +15238,9 @@ } }, "node_modules/postcss": { - "version": "8.5.28", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", - "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", "funding": [ { "type": "opencollective", @@ -15192,9 +15257,9 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.18", + "nanoid": "^3.3.20", "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" + "source-map-js": "^1.2.2" }, "engines": { "node": "^10 || ^12 || >=14" @@ -15355,13 +15420,12 @@ } }, "node_modules/postcss-selector-parser": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.5.tgz", - "integrity": "sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw==", + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.2.1.tgz", + "integrity": "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ==", "devOptional": true, "license": "MIT", "dependencies": { - "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" }, "engines": { @@ -15596,9 +15660,9 @@ } }, "node_modules/prosemirror-model": { - "version": "1.25.11", - "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.11.tgz", - "integrity": "sha512-QWg9RhnpLlogAmp3p96uEFrE5txQpFynd4vhBAELkwgOCWQs/X0yCzB3/hrHqiPwf91RG5KyWq6553zs9JqIOQ==", + "version": "1.25.13", + "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.13.tgz", + "integrity": "sha512-MlDMWGjYXaYOeCiO17jcybntCOzPnN+97U0809ke2QsgPtxW3n5/sD6ZKyJONUgMw1iP93ohZTjeKjnRJ7L6kQ==", "license": "MIT", "dependencies": { "orderedmap": "^2.0.0" @@ -15625,12 +15689,12 @@ } }, "node_modules/prosemirror-view": { - "version": "1.42.3", - "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.3.tgz", - "integrity": "sha512-oTN7EtH+CpwxU9NrwEYWd0UZ4JUx7l048l5A2Xppm4p/60isZYLnth9QVQmC3VRIvdrIWCxwZSd+Uz791G31/w==", + "version": "1.42.9", + "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.9.tgz", + "integrity": "sha512-bKbfzeKZOu2H2JQU2TaJmYu6EBcor3VnGIR4jR31cbEt1ztUnfUB6bKGV1+fJzOJdrVWR+tRU0208zM3oQx4wA==", "license": "MIT", "dependencies": { - "prosemirror-model": "^1.25.8", + "prosemirror-model": "^1.25.12", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0" } @@ -15643,9 +15707,9 @@ "license": "ISC" }, "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "dev": true, "license": "MIT", "peer": true, @@ -15655,6 +15719,10 @@ }, "engines": { "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/proxy-addr/node_modules/ipaddr.js": { @@ -15766,9 +15834,9 @@ "license": "MIT" }, "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "dev": true, "license": "BSD-3-Clause", "peer": true, @@ -15784,9 +15852,9 @@ } }, "node_modules/quansync": { - "version": "0.2.11", - "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", - "integrity": "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/quansync/-/quansync-1.0.0.tgz", + "integrity": "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==", "funding": [ { "type": "individual", @@ -16003,17 +16071,17 @@ "peer": true }, "node_modules/regenerate": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz", - "integrity": "sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.5.0.tgz", + "integrity": "sha512-1s+CxXjJ71i7LNVy8nYwg47XV4y6lAnOEhsMtSKq3WpmPfhl9LuKlTqKIn/3yUpE8lBz+W+TT88Bxyhnr0U4yw==", "dev": true, "license": "MIT", "peer": true }, "node_modules/regenerate-unicode-properties": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.2.2.tgz", - "integrity": "sha512-m03P+zhBeQd1RGnYxrGyDAPpWX/epKirLrp8e3qevZdVkKtnCrjjWczIbYc8+xd6vcTStVlqfycTx1KR4LOr0g==", + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.3.0.tgz", + "integrity": "sha512-9ns8odR8e9q3otKeHj3DE80jZYKg6zVeZKE+zQmRKXFoVUcuiTGeO6iusDhPRoIQQPVPRvH+SfBhrTud4eczuw==", "dev": true, "license": "MIT", "peer": true, @@ -16025,17 +16093,17 @@ } }, "node_modules/regexpu-core": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-6.4.0.tgz", - "integrity": "sha512-0ghuzq67LI9bLXpOX/ISfve/Mq33a4aFRzoQYhnnok1JOFpmE/A2TBGkNVenOGEeSBCjIiWcc6MVOG5HEQv0sA==", + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-6.5.4.tgz", + "integrity": "sha512-VpdamrZ9bw4YmvMZfTA3Yg8IHU9Guvg21bonvgjC4l3KfBkOqCPJesHakz7cQeE4Vh4zz4r4Gy6igAcnJxZv9g==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "regenerate": "^1.4.2", - "regenerate-unicode-properties": "^10.2.2", + "regenerate": "^1.5.0", + "regenerate-unicode-properties": "^10.3.0", "regjsgen": "^0.8.0", - "regjsparser": "^0.13.0", + "regjsparser": "^0.14.0", "unicode-match-property-ecmascript": "^2.0.0", "unicode-match-property-value-ecmascript": "^2.2.1" }, @@ -16052,9 +16120,9 @@ "peer": true }, "node_modules/regjsparser": { - "version": "0.13.2", - "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.13.2.tgz", - "integrity": "sha512-NgRBy2Nx/bE+9F27nVHnqcN5HjyLmecqsqx2PJHu3/IEtADD4WuxuXIVExD5PoSDFVrl78dOonfcOe5O+5nbzQ==", + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.14.1.tgz", + "integrity": "sha512-IeYboCLG1KBNRksrZQIZ1SV5KVWZiR0ikFokOcA0n63vLvlaFvCsfxN+fd4aXwL0KW3YD+ByRzIgo9ZAHdbldw==", "dev": true, "license": "BSD-2-Clause", "peer": true, @@ -16377,50 +16445,40 @@ "license": "MIT", "peer": true }, - "node_modules/rollup": { - "version": "4.63.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz", - "integrity": "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==", + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { - "@types/estree": "1.0.9" + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" }, "bin": { - "rollup": "dist/bin/rollup" + "rolldown": "bin/cli.mjs" }, "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" + "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@napi-rs/lzma-linux-x64-gnu": "1.5.1", - "@rollup/rollup-android-arm-eabi": "4.63.1", - "@rollup/rollup-android-arm64": "4.63.1", - "@rollup/rollup-darwin-arm64": "4.63.1", - "@rollup/rollup-darwin-x64": "4.63.1", - "@rollup/rollup-freebsd-arm64": "4.63.1", - "@rollup/rollup-freebsd-x64": "4.63.1", - "@rollup/rollup-linux-arm-gnueabihf": "4.63.1", - "@rollup/rollup-linux-arm-musleabihf": "4.63.1", - "@rollup/rollup-linux-arm64-gnu": "4.63.1", - "@rollup/rollup-linux-arm64-musl": "4.63.1", - "@rollup/rollup-linux-loong64-gnu": "4.63.1", - "@rollup/rollup-linux-loong64-musl": "4.63.1", - "@rollup/rollup-linux-ppc64-gnu": "4.63.1", - "@rollup/rollup-linux-ppc64-musl": "4.63.1", - "@rollup/rollup-linux-riscv64-gnu": "4.63.1", - "@rollup/rollup-linux-riscv64-musl": "4.63.1", - "@rollup/rollup-linux-s390x-gnu": "4.63.1", - "@rollup/rollup-linux-x64-gnu": "4.63.1", - "@rollup/rollup-linux-x64-musl": "4.63.1", - "@rollup/rollup-openbsd-x64": "4.63.1", - "@rollup/rollup-openharmony-arm64": "4.63.1", - "@rollup/rollup-win32-arm64-msvc": "4.63.1", - "@rollup/rollup-win32-ia32-msvc": "4.63.1", - "@rollup/rollup-win32-x64-gnu": "4.63.1", - "@rollup/rollup-win32-x64-msvc": "4.63.1", - "fsevents": "~2.3.2" + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, "node_modules/rope-sequence": { @@ -16536,7 +16594,7 @@ "version": "1.103.1", "resolved": "https://registry.npmjs.org/sass/-/sass-1.103.1.tgz", "integrity": "sha512-9icZURbP51S6S0QGoyaeqk9uB06GNWxsFYWfH5RgpFgqK5FA8tJcM3AdVxrZEVJ7dz+L87nG95gBKf4VuaMHGw==", - "devOptional": true, + "dev": true, "license": "MIT", "peer": true, "dependencies": { @@ -16612,37 +16670,31 @@ } }, "node_modules/schema-utils": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz", - "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==", + "version": "4.8.5", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.8.5.tgz", + "integrity": "sha512-K1RRP7aTUAY2lGXNzPwjMK6AMMzbETdpF3pTPMEnH/RrpmPx6K1X47/gSebrV+1I9pRcgpwZwqpYBlyZAsliiw==", "license": "MIT", "dependencies": { - "@types/json-schema": "^7.0.9", - "ajv": "^8.9.0", - "ajv-formats": "^2.1.1", + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", "ajv-keywords": "^5.1.0" }, + "bin": { + "schema-utils": "bin/schema-utils.js" + }, "engines": { "node": ">= 10.13.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/webpack" - } - }, - "node_modules/schema-utils/node_modules/ajv-formats": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", - "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", - "license": "MIT", - "dependencies": { - "ajv": "^8.0.0" }, "peerDependencies": { - "ajv": "^8.0.0" + "webpack": "^5.0.0" }, "peerDependenciesMeta": { - "ajv": { + "webpack": { "optional": true } } @@ -16679,17 +16731,6 @@ "node": ">=18" } }, - "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "peer": true, - "bin": { - "semver": "bin/semver.js" - } - }, "node_modules/send": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", @@ -16972,9 +17013,9 @@ } }, "node_modules/shell-quote": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.10.0.tgz", - "integrity": "sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", "dev": true, "license": "MIT", "peer": true, @@ -17065,13 +17106,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/siginfo": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", - "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", - "dev": true, - "license": "ISC" - }, "node_modules/signal-exit": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", @@ -17307,9 +17341,9 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -17408,13 +17442,6 @@ "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/stackback": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", - "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", - "dev": true, - "license": "MIT" - }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -17427,9 +17454,9 @@ } }, "node_modules/std-env": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", - "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", "dev": true, "license": "MIT" }, @@ -17634,9 +17661,9 @@ "license": "MIT" }, "node_modules/strnum": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.4.2.tgz", - "integrity": "sha512-rDG3Ah4TV0k1hWvLSzkZtMmLN9+eS+h3knq4MP6A42Y3Yh5qGNnOUs1jJkoSr8FG5dsL28c7KgkIBzSEykqtuw==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.5.1.tgz", + "integrity": "sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA==", "funding": [ { "type": "github", @@ -17688,22 +17715,13 @@ "integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==", "license": "MIT" }, - "node_modules/style-to-js": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz", - "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==", - "license": "MIT", - "dependencies": { - "style-to-object": "1.0.14" - } - }, "node_modules/style-to-object": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz", - "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-2.0.2.tgz", + "integrity": "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA==", "license": "MIT", "dependencies": { - "inline-style-parser": "0.2.7" + "inline-style-parser": "0.2.9" } }, "node_modules/stylelint": { @@ -18046,17 +18064,10 @@ "integrity": "sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==", "devOptional": true }, - "node_modules/symbol-tree": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", - "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", - "dev": true, - "license": "MIT" - }, "node_modules/tabbable": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.5.0.tgz", - "integrity": "sha512-wieBHXygIm7OyQOu5hQlkk62/WyCFYGlWg7L6/ZCUZwx0o398Zkn4pVmMyfYhfMG8kGrj/Krt8eIk6UKC6VzwA==", + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.5.2.tgz", + "integrity": "sha512-XgdnB1nGU6KU4VgMnZPaZCx7M1hBrLyEiZYau2G2gq9UT0d7d4FUBlNX7vvPlm/B1vk1PjrzJBx9Lbv4fsqS9g==", "license": "MIT" }, "node_modules/table": { @@ -18339,16 +18350,19 @@ } }, "node_modules/tinybench": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", - "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } }, "node_modules/tinyexec": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz", - "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", "dev": true, "license": "MIT", "engines": { @@ -18372,9 +18386,9 @@ } }, "node_modules/tinyrainbow": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz", - "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", "dev": true, "license": "MIT", "engines": { @@ -18447,6 +18461,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/toastify-js": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/toastify-js/-/toastify-js-1.12.0.tgz", + "integrity": "sha512-HeMHCO9yLPvP9k0apGSdPUWrUbLnxUKNFzgUoZp1PHCLploIX/4DSQ7V8H25ef+h4iO9n0he7ImfcndnN6nDrQ==", + "license": "MIT" + }, "node_modules/toidentifier": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", @@ -18482,16 +18502,16 @@ } }, "node_modules/tr46": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", - "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", "dev": true, "license": "MIT", "dependencies": { "punycode": "^2.3.1" }, "engines": { - "node": ">=20" + "node": "^22.14.0 || >=24.0.0" } }, "node_modules/tree-dump": { @@ -18542,7 +18562,7 @@ "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "devOptional": true, + "dev": true, "license": "MIT", "engines": { "node": ">=18.12" @@ -18817,9 +18837,9 @@ "license": "MIT" }, "node_modules/undici": { - "version": "8.10.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-8.10.0.tgz", - "integrity": "sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==", + "version": "8.13.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.13.0.tgz", + "integrity": "sha512-mxbeyRlRhHUTWE1zf/FwDOXTKMhE1vMQRz/o2oOir/5fIWsB79TeZrByMkj019EdDuxPg03jprCjFLxLkmxTCQ==", "dev": true, "license": "MIT", "engines": { @@ -18953,20 +18973,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/unist-util-find-after": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unist-util-find-after/-/unist-util-find-after-5.0.0.tgz", - "integrity": "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==", - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, "node_modules/unist-util-is": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", @@ -19007,14 +19013,14 @@ } }, "node_modules/unist-util-visit": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", - "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.2.0.tgz", + "integrity": "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ==", "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" + "unist-util-visit-parents": "^6.1.0" }, "funding": { "type": "opencollective", @@ -19022,9 +19028,9 @@ } }, "node_modules/unist-util-visit-parents": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", - "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==", "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", @@ -19047,12 +19053,13 @@ } }, "node_modules/unplugin": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-3.4.0.tgz", - "integrity": "sha512-9skdIFlCsPdFV7wUfZxNsFInlW+7nJmGu2gkTu0OUhF56aXGsHab9x52/QhdJ4lC7ZDPWTxbiC4ANqVlsuaW3w==", + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-3.7.0.tgz", + "integrity": "sha512-GrM2uq3DQo3hvLU2FjeYhooJ8BY9N6j1Fbzgx7Pta3VVJevsD3VP4dPjZkZOS0mLvN8w9zzr9OlP+31bSMyuLw==", "license": "MIT", "dependencies": { "@jridgewell/remapping": "^2.3.5", + "@rolldown/pluginutils": "^1.0.1", "picomatch": "^4.0.7", "webpack-virtual-modules": "^0.6.2" }, @@ -19177,9 +19184,9 @@ } }, "node_modules/url-join": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/url-join/-/url-join-5.0.0.tgz", - "integrity": "sha512-n2huDr9h9yzd6exQVnH/jU5mr+Pfx08LRXXZhkLLetAMESRj+anQsTAh940iMrIetKAmry9coFuZQ2jY8/p3WA==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-5.2.0.tgz", + "integrity": "sha512-/tMVQdp/2eE90fGb6npbd2nLHH8jamzLLeZhLEKTz4Rc38wO5AeEuIhoWroWWfQJS50ZzL4Xod9JER/pJWTTEQ==", "license": "MIT", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" @@ -19258,6 +19265,20 @@ "node": ">= 0.8" } }, + "node_modules/verkit": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/verkit/-/verkit-0.5.0.tgz", + "integrity": "sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, "node_modules/vfile": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", @@ -19273,9 +19294,9 @@ } }, "node_modules/vfile-message": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", - "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.4.tgz", + "integrity": "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg==", "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", @@ -19287,24 +19308,24 @@ } }, "node_modules/vite": { - "version": "6.4.3", - "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", - "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { - "esbuild": "^0.25.0", - "fdir": "^6.4.4", - "picomatch": "^4.0.2", - "postcss": "^8.5.3", - "rollup": "^4.34.9", - "tinyglobby": "^0.2.13" + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" }, "bin": { "vite": "bin/vite.js" }, "engines": { - "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + "node": "^20.19.0 || >=22.12.0" }, "funding": { "url": "https://github.com/vitejs/vite?sponsor=1" @@ -19313,14 +19334,15 @@ "fsevents": "~2.3.3" }, "peerDependencies": { - "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" @@ -19329,13 +19351,16 @@ "@types/node": { "optional": true }, - "jiti": { + "@vitejs/devtools": { "optional": true }, - "less": { + "esbuild": { "optional": true }, - "lightningcss": { + "jiti": { + "optional": true + }, + "less": { "optional": true }, "sass": { @@ -19362,38 +19387,31 @@ } }, "node_modules/vitest": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", - "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.11", - "@vitest/mocker": "4.1.11", - "@vitest/pretty-format": "4.1.11", - "@vitest/runner": "4.1.11", - "@vitest/snapshot": "4.1.11", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", - "es-module-lexer": "^2.0.0", - "expect-type": "^1.3.0", - "magic-string": "^0.30.21", - "obug": "^2.1.1", - "pathe": "^2.0.3", - "picomatch": "^4.0.3", - "std-env": "^4.0.0-rc.1", - "tinybench": "^2.9.0", - "tinyexec": "^1.0.2", - "tinyglobby": "^0.2.15", - "tinyrainbow": "^3.1.0", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", - "why-is-node-running": "^2.3.0" + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" }, "bin": { "vitest": "vitest.mjs" }, "engines": { - "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" }, "funding": { "url": "https://opencollective.com/vitest" @@ -19401,16 +19419,16 @@ "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", - "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.11", - "@vitest/browser-preview": "4.1.11", - "@vitest/browser-webdriverio": "4.1.11", - "@vitest/coverage-istanbul": "4.1.11", - "@vitest/coverage-v8": "4.1.11", - "@vitest/ui": "4.1.11", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", "happy-dom": "*", "jsdom": "*", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { "@edge-runtime/vm": { @@ -19451,6 +19469,16 @@ } } }, + "node_modules/vitest/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, "node_modules/vm-browserify": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", @@ -19460,16 +19488,16 @@ "peer": true }, "node_modules/vue": { - "version": "3.5.42", - "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.42.tgz", - "integrity": "sha512-4RyHQTbQvOPs3MfvUO1Sg0YRrKNnA0mAVtvpd12Tg1fKDN7OHBUl1IqSn8zGJjK9nI3NkNp8cgTpVrSZC5TTcA==", + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.45.tgz", + "integrity": "sha512-3cvsib8m9c0vB24+MDKsgcW4+Da4xaBl9Z/5Tbm2pmSIsRPxcil4cdXjXlVsmJ2g64XJo5h+IRd7rsdGT9pZaw==", "license": "MIT", "dependencies": { - "@vue/compiler-dom": "3.5.42", - "@vue/compiler-sfc": "3.5.42", - "@vue/runtime-dom": "3.5.42", - "@vue/server-renderer": "3.5.42", - "@vue/shared": "3.5.42" + "@vue/compiler-dom": "3.5.45", + "@vue/compiler-sfc": "3.5.45", + "@vue/runtime-dom": "3.5.45", + "@vue/server-renderer": "3.5.45", + "@vue/shared": "3.5.45" }, "peerDependencies": { "typescript": "*" @@ -19535,9 +19563,9 @@ } }, "node_modules/vue-eslint-parser": { - "version": "10.4.1", - "resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.4.1.tgz", - "integrity": "sha512-Gk6gRDj0n/fkRa3C3l0bBheoBckUq/Rs0F/TvMWIS6nzzx67amAViMe9CkNgsP2tXyQONvGiHQESHwFtZ3aYDA==", + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.4.2.tgz", + "integrity": "sha512-WMpzulb50kb6snghzoGzS++62wcOszAk/piYcnvzdStM8Wni/BmogYltpoOFv2eK9hDbXxvwFQgnwZGpAoUfpA==", "devOptional": true, "license": "MIT", "dependencies": { @@ -19594,20 +19622,11 @@ } }, "node_modules/vue-material-design-icons": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/vue-material-design-icons/-/vue-material-design-icons-5.3.1.tgz", - "integrity": "sha512-6UNEyhlTzlCeT8ZeX5WbpUGFTTPSbOoTQeoASTv7X4Ylh0pe8vltj+36VMK56KM0gG8EQVoMK/Qw/6evalg8lA==", + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/vue-material-design-icons/-/vue-material-design-icons-5.4.0.tgz", + "integrity": "sha512-NqKTWn+4cnWDiD2P6xeKqaLg1iGajl0VVUcMbcv5aDRoXFPu70hqN55sBSrGKatkeP5M1aDZ/YCiCgBkr9qh1A==", "license": "MIT" }, - "node_modules/vue-resize": { - "version": "2.0.0-alpha.1", - "resolved": "https://registry.npmjs.org/vue-resize/-/vue-resize-2.0.0-alpha.1.tgz", - "integrity": "sha512-7+iqOueLU7uc9NrMfrzbG8hwMqchfVfSzpVlCMeJQe4pyibqyoifDNbKTZvwxZKDvGkB+PdFeKvnGZMoEb8esg==", - "license": "MIT", - "peerDependencies": { - "vue": "^3.0.0" - } - }, "node_modules/vue-router": { "version": "4.6.4", "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz", @@ -19658,16 +19677,16 @@ "license": "MIT" }, "node_modules/w3c-xmlserializer": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", - "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", "dev": true, "license": "MIT", "dependencies": { "xml-name-validator": "^5.0.0" }, "engines": { - "node": ">=18" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/watchpack": { @@ -19692,16 +19711,17 @@ } }, "node_modules/webdav": { - "version": "5.10.0", - "resolved": "https://registry.npmjs.org/webdav/-/webdav-5.10.0.tgz", - "integrity": "sha512-fVPuRLtcduVGvSO7Tn/6TQCzIvI/g6BO/+xPRctCvi/GytYpjn4czxWbh4HsArsdom9qz9BI63k9/v2HBUui1A==", + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/webdav/-/webdav-5.11.0.tgz", + "integrity": "sha512-DbUS8rHvWse55EiHM0q5q1z3eVRCLWW7Va7mUqA2/JJdQHIew4Op2HTglHkBJDOAVrQeQf0I+REUJkIrYqtL+w==", "license": "MIT", "dependencies": { "@buttercup/fetch": "^0.2.1", + "@nodable/entities": "^3.0.0", "base-64": "^1.0.0", "byte-length": "^1.0.2", "entities": "^6.0.1", - "fast-xml-parser": "^5.7.2", + "fast-xml-parser": "^5.11.1", "hot-patcher": "^2.0.1", "layerr": "^3.0.0", "md5": "^2.3.0", @@ -19716,21 +19736,6 @@ "node": ">=14" } }, - "node_modules/webdav/node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "license": "MIT" - }, - "node_modules/webdav/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, "node_modules/webdav/node_modules/entities": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", @@ -19744,15 +19749,16 @@ } }, "node_modules/webdav/node_modules/minimatch": { - "version": "9.0.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", - "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", - "license": "ISC", + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^2.0.2" + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -19867,17 +19873,17 @@ } }, "node_modules/webpack-dev-middleware": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-8.1.1.tgz", - "integrity": "sha512-JrxAE/HwNmEnTkzkUGHFItHpGalzuEIUDifXhjAkIEHZzHK/ZJFVoTQF5ubZQlgeRireqLdr2lZttrrmOH61IA==", + "version": "8.6.3", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-8.6.3.tgz", + "integrity": "sha512-dDxACv07a+8mOYnQusKjndG7HEIdKJA1bimx4mCfZKu0jDaq5EbaeFaAuNtTdbkKFgg9mtmCpc5ZTjtFxszpNg==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "memfs": "^4.56.10", - "mime-types": "^3.0.2", - "range-parser": "^1.2.1", - "schema-utils": "^4.3.3" + "memfs": "^4.68.2", + "mime-db": "^1.54.0", + "range-parser": "^1.3.0", + "schema-utils": "^4.8.5" }, "engines": { "node": ">= 20.9.0" @@ -19886,6 +19892,9 @@ "type": "opencollective", "url": "https://opencollective.com/webpack" }, + "optionalDependencies": { + "ws": "^8.18.3" + }, "peerDependencies": { "webpack": "^5.101.0" }, @@ -19906,24 +19915,6 @@ "node": ">= 0.6" } }, - "node_modules/webpack-dev-middleware/node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "mime-db": "^1.54.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/webpack-dev-server": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-6.0.0.tgz", @@ -20033,14 +20024,14 @@ } }, "node_modules/whatwg-url": { - "version": "17.1.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.1.0.tgz", - "integrity": "sha512-3GeworPmc2ZfEEHP7lEbUfBX/L75wdEsi0rLNhXcXxnoN5jyq0SL5gCy06SGW2cyTIZdTvWIDQNQoza++vKeaw==", + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", "dev": true, "license": "MIT", "dependencies": { - "@exodus/bytes": "^1.15.1", - "tr46": "^6.0.0", + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", "webidl-conversions": "^8.0.1" }, "engines": { @@ -20048,9 +20039,9 @@ } }, "node_modules/whatwg-url/node_modules/@exodus/bytes": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz", - "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", "dev": true, "license": "MIT", "engines": { @@ -20065,6 +20056,21 @@ } } }, + "node_modules/whatwg-url/node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -20105,20 +20111,16 @@ } }, "node_modules/why-is-node-running": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", - "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", "dev": true, "license": "MIT", - "dependencies": { - "siginfo": "^2.0.0", - "stackback": "0.0.2" - }, "bin": { "why-is-node-running": "cli.js" }, "engines": { - "node": ">=8" + "node": ">=20.11" } }, "node_modules/wildcard": { @@ -20394,14 +20396,6 @@ "node": ">=0.4" } }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true, - "license": "ISC", - "peer": true - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index 84b6ba3ff..706640d8b 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,9 @@ "npm": "^11.0.0" }, "scripts": { - "build": "webpack --config webpack.config.js --progress --mode production", + "build": "webpack --config webpack.config.js --progress --mode production && npm run build:embed-sdk && npm run check:a11y", + "build:embed-sdk": "webpack --config src/embed-sdk/webpack.config.cjs", + "check:a11y": "vitest run src/__tests__/axe-core-check.spec.js", "dev": "NODE_ENV=development webpack --config webpack.config.js --progress", "watch": "NODE_ENV=development webpack --config webpack.config.js --progress --watch", "check:schema-l10n": "node scripts/check-schema-l10n.js", @@ -35,52 +37,54 @@ "prepare": "git config core.hooksPath .githooks || true" }, "dependencies": { - "@conduction/nextcloud-vue": "^2.57.1", + "@conduction/nextcloud-vue": "^2.230.0", "@mdi/js": "^7.4.47", "@nextcloud/axios": "^2.6.0", - "@nextcloud/dialogs": "^7.4.1", + "@nextcloud/dialogs": "^8.0.0", "@nextcloud/initial-state": "^2.2.0", "@nextcloud/l10n": "^3.4.1", "@nextcloud/router": "^3.1.0", - "@nextcloud/vue": "^9.13.0", - "dexie": "^4.4.6", - "dompurify": "^3.4.15", + "@nextcloud/vue": "^9.13.1", + "dexie": "^4.4.7", + "dompurify": "^3.4.18", "gridstack": "^13.3.0", "marked": "^18.0.14", - "pinia": "^4.0.3", - "vue": "^3.5.42", + "pinia": "^4.1.0", + "vue": "^3.5.44", "vue-loader": "^17.4.2", - "vue-material-design-icons": "^5.2.0", + "vue-material-design-icons": "^5.4.0", "vue-router": "^4.5.0", "vuedraggable": "^4.1.0" }, "devDependencies": { + "@axe-core/playwright": "^4.14.0", "@cyclonedx/cyclonedx-npm": "^6.0.1", - "@nextcloud/babel-config": "^1.2.0", + "@nextcloud/babel-config": "^2.0.0", "@nextcloud/browserslist-config": "^3.1.2", "@nextcloud/eslint-config": "^9.0.1", - "@nextcloud/password-confirmation": "^6.1.0", + "@nextcloud/password-confirmation": "^6.2.1", "@nextcloud/prettier-config": "^1.2.0", "@nextcloud/stylelint-config": "^3.2.2", - "@nextcloud/webpack-vue-config": "^7.0.2", + "@nextcloud/webpack-vue-config": "^7.1.0", "@playwright/test": "^1.63.0", - "@typescript-eslint/parser": "^8.70.0", + "@typescript-eslint/parser": "^8.71.0", "@vitejs/plugin-vue": "^6.0.9", - "@vitest/coverage-v8": "^4.1.11", - "@vitest/ui": "^4.1.11", - "@vue/compiler-sfc": "^3.5.13", - "@vue/server-renderer": "^3.5.42", + "@vitest/coverage-v8": "^5.0.2", + "@vitest/ui": "^5.0.2", + "@vue/compiler-sfc": "^3.5.43", + "@vue/server-renderer": "^3.5.43", "@vue/test-utils": "^2.5.1", "@vue/tsconfig": "^0.9.1", + "axe-core": "~4.14.1", "eslint": "^10.11.0", "eslint-config-prettier": "^10.1.8", - "jsdom": "^30.0.1", + "jsdom": "^31.0.1", "prettier": "^3.9.8", "stylelint": "^17.15.0", "terser-webpack-plugin": "^5.3.11", "typescript": "^5.4.0", - "vitest": "^4.1.11", - "vue-eslint-parser": "^10.3.0" + "vitest": "^5.0.2", + "vue-eslint-parser": "^10.4.2" }, "browserslist": [ "extends @nextcloud/browserslist-config" @@ -88,7 +92,11 @@ "overrides": { "pinia": "$pinia", "@vueuse/core": "^14.0.0", - "@vueuse/shared": "^14.0.0" + "@vueuse/shared": "^14.0.0", + "dompurify": "$dompurify", + "webdav": { + "minimatch": "^11.0.1" + } }, "prettier": "@nextcloud/prettier-config" } diff --git a/phpmd.baseline.xml b/phpmd.baseline.xml index be78dd303..691b004e8 100644 --- a/phpmd.baseline.xml +++ b/phpmd.baseline.xml @@ -22,23 +22,9 @@ <violation rule="PHPMD\Rule\CleanCode\BooleanArgumentFlag" file="lib/Service/PeopleWidgetService.php"/> <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/AppInfo/Application.php"/> <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Command/SetupCommand.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/AcknowledgementController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/AdminController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/AdminDemoShowcasesController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/AdminOrgNavigationController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/AdminSettingsController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/AdminWidgetRulesController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/AnalyticsController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/DashboardApiController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/DashboardMetadataController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/DashboardReactionApiController.php"/> <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/DashboardTranslationApiController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/MetadataAdminController.php"/> <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/PageController.php"/> <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/PeopleWidgetController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/RoleFeaturePermissionApiController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/RuleApiController.php"/> - <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/TileApiController.php"/> <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Controller/WidgetApiController.php"/> <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Db/DashboardMapper.php"/> <violation rule="PHPMD\Rule\CleanCode\StaticAccess" file="lib/Migration/MigrationTableBuilder.php"/> @@ -95,11 +81,6 @@ <violation rule="PHPMD\Rule\Design\WeightedMethodCount" file="lib/Service/DashboardVersionService.php"/> <violation rule="PHPMD\Rule\Design\WeightedMethodCount" file="lib/Service/FilesWidgetService.php"/> <violation rule="PHPMD\Rule\Design\WeightedMethodCount" file="lib/Service/RoleFeaturePermissionService.php"/> - <violation rule="PHPMD\Rule\Naming\BooleanGetMethodName" file="lib/Service/Cleanup/CleanupCategoryInterface.php" method="getSafeToPurgeAutomatically"/> - <violation rule="PHPMD\Rule\Naming\BooleanGetMethodName" file="lib/Service/Cleanup/ExpiredLocksCategory.php" method="getSafeToPurgeAutomatically"/> - <violation rule="PHPMD\Rule\Naming\BooleanGetMethodName" file="lib/Service/Cleanup/OrphanedConditionalRulesCategory.php" method="getSafeToPurgeAutomatically"/> - <violation rule="PHPMD\Rule\Naming\BooleanGetMethodName" file="lib/Service/Cleanup/OrphanedSharesCategory.php" method="getSafeToPurgeAutomatically"/> - <violation rule="PHPMD\Rule\Naming\BooleanGetMethodName" file="lib/Service/Cleanup/OrphanedWidgetPlacementsCategory.php" method="getSafeToPurgeAutomatically"/> <violation rule="PHPMD\Rule\Naming\LongVariable" file="lib/Controller/AcknowledgementController.php"/> <violation rule="PHPMD\Rule\Naming\LongVariable" file="lib/Db/WidgetPlacement.php"/> <violation rule="PHPMD\Rule\Naming\LongVariable" file="lib/Service/AcknowledgementService.php"/> diff --git a/phpstan-bootstrap.php b/phpstan-bootstrap.php index b473c89c3..d9fca55dd 100644 --- a/phpstan-bootstrap.php +++ b/phpstan-bootstrap.php @@ -2,6 +2,9 @@ /** * PHPStan bootstrap file - registers OCP autoloader for static analysis. + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 */ $autoloader = require __DIR__ . '/vendor/autoload.php'; diff --git a/phpstan.neon b/phpstan.neon index 21f5cfacb..8835a91a4 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -18,6 +18,10 @@ parameters: # the leaf Health/Metrics controllers' "extends unknown class" resolves, # WITHOUT phpstan analysing/reporting the skeleton file itself (ADR-040). - tests/phpstan/apphost-symbols.php + # OpenRegister ships IMcpToolProvider at runtime only (mcp-tool-surface). + - tests/Stubs/Mcp/IMcpToolProvider.php + # OpenRegister's published object service contract (embedded-analytics store). + - tests/Stubs/OpenRegister/ObjectServiceInterface.php # Prevents false-positive "always true/false" errors caused by defensive runtime # checks on values whose PHPDoc type is narrower than what callers may pass. diff --git a/playwright.config.ts b/playwright.config.ts index f22a45af5..79200b4ea 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -137,7 +137,9 @@ export default defineConfig({ // 60s, not 30s: the value the 80-test measurement run used, under which // every promoted file was green. The old 30s was never exercised against // this fixture by anything but the four-test subset. - timeout: 60_000, + // E2E_TEST_TIMEOUT (ms) raises it for a run against a shared, busy + // instance, where a fresh account's first sign-in alone can take a minute. + timeout: Number(process.env.E2E_TEST_TIMEOUT) || 60_000, expect: { timeout: 10_000, }, diff --git a/publiccode.yml b/publiccode.yml index 51267e045..92660a822 100644 --- a/publiccode.yml +++ b/publiccode.yml @@ -2,49 +2,92 @@ publiccodeYmlVersion: "0.4" name: LaunchPad url: "https://github.com/ConductionNL/launchpad" -softwareVersion: "1.0.5" -releaseDate: "2026-05-26" +landingURL: "https://launchpad.conduction.nl" +logo: img/app-store.svg +softwareVersion: "1.1.0" +releaseDate: "2026-09-06" developmentStatus: beta softwareType: "standalone/other" platforms: - - nextcloud + - web categories: - data-visualization - business-intelligence +dependsOn: + open: + - name: Nextcloud + versionMin: "32" + versionMax: "35" + +intendedAudience: + countries: + - nl + scope: + - government + - local-authorities + description: en: shortDescription: > - Business intelligence dashboard and data visualisation for Nextcloud. + Drag-and-drop dashboards with templates, tiles and smart visibility for Nextcloud. longDescription: > - LaunchPad is a business intelligence and dashboard application for Nextcloud. - It enables organisations to create and manage customisable dashboards with - charts, graphs, and KPI widgets. Data is sourced via GraphQL from Open Register - and other connected data sources. LaunchPad is designed for operational reporting - and monitoring in both government and commercial organisations. + LaunchPad extends the Nextcloud dashboard. Users create personal workspaces + with drag-and-drop widgets, custom shortcut tiles and smart visibility rules, + and admins roll out dashboard templates to entire teams. LaunchPad works with + every existing Nextcloud dashboard widget, supporting both the v1 and v2 + Dashboard APIs. It suits organisations that want consistent, curated + dashboards for their teams while still giving users the freedom to + personalise them. Conduction maintains this component within the Nextcloud + ISV programme. LaunchPad is available in the Nextcloud App Store at + https://apps.nextcloud.com/apps/launchpad. + screenshots: + - img/screenshot-dashboard.png + - img/screenshot-widgets.png + - img/screenshot-admin.png features: - - Customisable dashboards with charts and KPI widgets - - GraphQL data integration - - Operational reporting and monitoring - - Real-time data visualisation + - Drag-and-drop grid layout to position and resize widgets + - Multiple dashboards per user + - Custom shortcut tiles with icons, colours and links + - Admin templates distributed to user groups + - View-only, add-only or full customisation per template + - Conditional widget visibility by group, time of day or date + - Per-widget styling of colours, borders and titles + - Compulsory widgets that users cannot remove + - Dashboard sharing with users, groups or a read-only public link + - Group dashboards next to personal dashboards nl: shortDescription: > - Business intelligence-dashboard en datavisualisatie voor Nextcloud. + Drag-and-drop dashboards met templates, tegels en slimme zichtbaarheid voor Nextcloud. longDescription: > - LaunchPad is een business intelligence- en dashboardtoepassing voor Nextcloud. - Het stelt organisaties in staat aanpasbare dashboards te maken en te beheren - met grafieken, diagrammen en KPI-widgets. Gegevens worden via GraphQL - opgehaald uit Open Register en andere gekoppelde databronnen. LaunchPad is - ontworpen voor operationele rapportage en monitoring in zowel overheids- als - commerciële organisaties. + LaunchPad breidt het Nextcloud-dashboard uit. Gebruikers maken persoonlijke + werkruimtes met drag-and-drop widgets, eigen snelkoppelingstegels en slimme + zichtbaarheidsregels, en beheerders rollen dashboardtemplates uit naar hele + teams. LaunchPad werkt met elke bestaande Nextcloud-dashboardwidget en + ondersteunt zowel de v1- als de v2-Dashboard-API. Het is bedoeld voor + organisaties die consistente, samengestelde dashboards voor hun teams willen, + terwijl gebruikers de vrijheid houden om ze te personaliseren. Conduction + onderhoudt dit component binnen het Nextcloud ISV-programma. LaunchPad is + beschikbaar in de Nextcloud App Store via + https://apps.nextcloud.com/apps/launchpad. + screenshots: + - img/screenshot-dashboard.png + - img/screenshot-widgets.png + - img/screenshot-admin.png features: - - Aanpasbare dashboards met grafieken en KPI-widgets - - GraphQL-data-integratie - - Operationele rapportage en monitoring - - Realtime datavisualisatie + - Drag-and-drop rasterindeling om widgets te plaatsen en te schalen + - Meerdere dashboards per gebruiker + - Eigen snelkoppelingstegels met iconen, kleuren en links + - Beheerdertemplates die naar gebruikersgroepen worden uitgerold + - Alleen bekijken, toevoegen of volledige aanpassing per template + - Conditionele zichtbaarheid van widgets op groep, tijdstip of datum + - Styling per widget voor kleuren, randen en titels + - Verplichte widgets die gebruikers niet kunnen verwijderen + - Dashboards delen met gebruikers, groepen of via een alleen-lezen publieke link + - Groepsdashboards naast persoonlijke dashboards legal: license: EUPL-1.2 @@ -52,7 +95,12 @@ legal: repoOwner: "Conduction B.V." maintenance: - type: community + type: contract + contractors: + - name: Conduction B.V. + until: "2028-12-31" + email: info@conduction.nl + website: https://conduction.nl contacts: - name: Conduction B.V. email: info@conduction.nl @@ -61,5 +109,44 @@ maintenance: localisation: localisationReady: true availableLanguages: - - nl + - be + - bg + - bs + - ca + - cs + - da + - de + - el - en + - es + - et + - fi + - fr + - ga + - hr + - hu + - is + - it + - lb + - lt + - lv + - mk + - mt + - nb + - nl + - pl + - pt + - rm + - ro + - ru + - sk + - sl + - sq + - sr + - sv + - tr + - uk + +# Common Ground layer (nl.vng profile), as a standard supports entry. +supports: + - id: https://commonground.nl/cms/view/54476261/5-lagen-model#interaction diff --git a/sbom.cdx.json b/sbom.cdx.json new file mode 100644 index 000000000..04531c06a --- /dev/null +++ b/sbom.cdx.json @@ -0,0 +1,24821 @@ +{ + "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json", + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "metadata": { + "tools": [ + { + "name": "composer", + "version": "2.8.12" + }, + { + "vendor": "cyclonedx", + "name": "cyclonedx-php-composer", + "version": "v6.2.0", + "externalReferences": [ + { + "type": "distribution", + "url": "https://api.github.com/repos/CycloneDX/cyclonedx-php-composer/zipball/934440a5ef7c3c3cdb58c3c3d389d412630ccbf6", + "comment": "dist reference: 934440a5ef7c3c3cdb58c3c3d389d412630ccbf6" + }, + { + "type": "vcs", + "url": "https://github.com/CycloneDX/cyclonedx-php-composer.git", + "comment": "source reference: 934440a5ef7c3c3cdb58c3c3d389d412630ccbf6" + }, + { + "type": "website", + "url": "https://github.com/CycloneDX/cyclonedx-php-composer/#readme", + "comment": "as detected from Composer manifest 'homepage'" + }, + { + "type": "issue-tracker", + "url": "https://github.com/CycloneDX/cyclonedx-php-composer/issues", + "comment": "as detected from Composer manifest 'support.issues'" + }, + { + "type": "vcs", + "url": "https://github.com/CycloneDX/cyclonedx-php-composer/", + "comment": "as detected from Composer manifest 'support.source'" + } + ] + }, + { + "vendor": "cyclonedx", + "name": "cyclonedx-library", + "version": "v4.0.0", + "externalReferences": [ + { + "type": "distribution", + "url": "https://api.github.com/repos/CycloneDX/cyclonedx-php-library/zipball/c95a371894c4e32bea42bfa024f2ab5092cbb292", + "comment": "dist reference: c95a371894c4e32bea42bfa024f2ab5092cbb292" + }, + { + "type": "vcs", + "url": "https://github.com/CycloneDX/cyclonedx-php-library.git", + "comment": "source reference: c95a371894c4e32bea42bfa024f2ab5092cbb292" + }, + { + "type": "website", + "url": "https://github.com/CycloneDX/cyclonedx-php-library/#readme", + "comment": "as detected from Composer manifest 'homepage'" + }, + { + "type": "documentation", + "url": "https://cyclonedx-php-library.readthedocs.io", + "comment": "as detected from Composer manifest 'support.docs'" + }, + { + "type": "issue-tracker", + "url": "https://github.com/CycloneDX/cyclonedx-php-library/issues", + "comment": "as detected from Composer manifest 'support.issues'" + }, + { + "type": "vcs", + "url": "https://github.com/CycloneDX/cyclonedx-php-library/", + "comment": "as detected from Composer manifest 'support.source'" + } + ] + } + ], + "component": { + "bom-ref": "conductionnl/launchpad-1.0.0.0", + "type": "application", + "name": "launchpad", + "version": "1.0.0", + "group": "conductionnl", + "description": "Enhanced dashboard with grid layout and admin controls for Nextcloud", + "author": "LaunchPad Contributors", + "licenses": [ + { + "license": { + "id": "EUPL-1.2" + } + } + ], + "purl": "pkg:composer/conductionnl/launchpad@1.0.0", + "properties": [ + { + "name": "cdx:composer:package:type", + "value": "project" + } + ] + } + }, + "components": [ + { + "type": "library", + "name": "helper-string-parser", + "group": "@babel", + "version": "8.1.2", + "bom-ref": "launchpad@1.0.0|@babel/helper-string-parser@8.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-string-parser@8.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4d1cf96743207c87d6ab0108abfa42a54a445d0c54b76220d996f11b749d9a149b1cc00515818e8b1d2423824b577ef5fd303ea969d0e315873d68e88e4c9114" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@babel/helper-string-parser" + } + ] + }, + { + "type": "library", + "name": "helper-validator-identifier", + "group": "@babel", + "version": "8.0.6", + "bom-ref": "launchpad@1.0.0|@babel/helper-validator-identifier@8.0.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-validator-identifier@8.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1d8c74626b9c851c514a99e3bdc35f7e73d2f0309ab8a3669ee988b871b78e740055ec1103b91f246c05d776b2129499b3bb3847fa011f87a9a6e5dc01077925" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@babel/helper-validator-identifier" + } + ] + }, + { + "type": "library", + "name": "parser", + "group": "@babel", + "version": "8.1.2", + "bom-ref": "launchpad@1.0.0|@babel/parser@8.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/parser@8.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/parser/-/parser-8.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "643294eef697d1539177606168efb714aaffdf44ca8db532dd23197327623e782701bf8c7ac814a21e5225c139130132063d7833927a7cae7a1ae06abd898ea7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@babel/parser" + } + ] + }, + { + "type": "library", + "name": "runtime", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|@babel/runtime@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/runtime@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "639b6a7af41a500661863f3606960c342d6cb2f2d04d501fc0a766f22cbcab09a1bc2dbf0a9700bbc382f9012d8ccee9324ee49f1f37bb5423f20ce489cc9e97" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@babel/runtime" + } + ] + }, + { + "type": "library", + "name": "types", + "group": "@babel", + "version": "8.1.2", + "bom-ref": "launchpad@1.0.0|@babel/types@8.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/types@8.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/types/-/types-8.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b97b7aaadd9fe46eb58d9c0d2332b544abbb9795e3b75557b4f3ce1ae56f7a16bd7f16f1d1033de14d64338a4564a4d12e358af97f2f9b08f06c87a62638904c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@babel/types" + } + ] + }, + { + "type": "library", + "name": "fetch", + "group": "@buttercup", + "version": "0.2.1", + "bom-ref": "launchpad@1.0.0|@buttercup/fetch@0.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40buttercup/fetch@0.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@buttercup/fetch/-/fetch-0.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b0280408ec7cc22a98f0d375c4ddb606aa8acd76081b602270d2e56a43802387f45a0c8b5546c08a031ff0266106d27176e753701d600f995c8aa8b8e23c09be" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@buttercup/fetch" + } + ] + }, + { + "type": "library", + "name": "memory", + "group": "@cacheable", + "version": "2.2.0", + "bom-ref": "launchpad@1.0.0|@cacheable/memory@2.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40cacheable/memory@2.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0932caa8b22d442122c4401ec03dff8fd0c1dffa3dea0a533c3e1e275bfe0c63a5c594599dc45090662aaa70060ac71877a44d7977c67a2b82a61b0fb6ac887d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@cacheable/memory" + } + ] + }, + { + "type": "library", + "name": "utils", + "group": "@cacheable", + "version": "2.5.0", + "bom-ref": "launchpad@1.0.0|@cacheable/utils@2.5.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40cacheable/utils@2.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6ee8a980e5439243d7351e7ec41a43c3b664da7d44bd4eea04908d51c2fbae143ffe47e93973c0bd0e75d4eb34be92d8275a599efb9d372b6442dda1b2ddf0a8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@cacheable/utils" + } + ] + }, + { + "type": "library", + "name": "vue-color", + "group": "@ckpack", + "version": "1.6.0", + "bom-ref": "launchpad@1.0.0|@ckpack/vue-color@1.6.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40ckpack/vue-color@1.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@ckpack/vue-color/-/vue-color-1.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6fd9054ca8586cd02b7e03f59669da566d1536c59d663a886f21d462bcbb999f84ec979341c95b8ead7edb15a7d12137c33a916255e60158c408f3a0b5e5a631" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@ckpack/vue-color" + } + ] + }, + { + "type": "library", + "name": "autocomplete", + "group": "@codemirror", + "version": "6.20.3", + "bom-ref": "launchpad@1.0.0|@codemirror/autocomplete@6.20.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/autocomplete@6.20.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b65a2c52a6fedc16f10b165dbb8b4a7918213c50be40ceeae17e5884a57678298f1bed6bd85ddfe00692cf9b02ac5a94b57e09876d1515329e725d7a320895f6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/autocomplete" + } + ] + }, + { + "type": "library", + "name": "commands", + "group": "@codemirror", + "version": "6.11.0", + "bom-ref": "launchpad@1.0.0|@codemirror/commands@6.11.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/commands@6.11.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fcae1197904dd0eb5388f5a624276a383bb7f179c332c0f1298e6b82b3e70a4bad3d325fdb055b9288b12df79a945e4ac2c7bfb3c3fc3398c0894462c12c2714" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/commands" + } + ] + }, + { + "type": "library", + "name": "lang-css", + "group": "@codemirror", + "version": "6.3.1", + "bom-ref": "launchpad@1.0.0|@codemirror/lang-css@6.3.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/lang-css@6.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "92be5fc011a21ad9b3ea5d0b48921b9e8f50ae27cd314bac8af1db9c0d47e839aacb81d916d7b75002028b1d55b8aa3494c3ca42bdaba81fb40642a2fd2dc48e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/lang-css" + } + ] + }, + { + "type": "library", + "name": "lang-html", + "group": "@codemirror", + "version": "6.4.12", + "bom-ref": "launchpad@1.0.0|@codemirror/lang-html@6.4.12", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/lang-html@6.4.12", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a70d91796294a9291bbe1efa4404f8358c62a2046ef8f5a4476ba40303bdb8e82b9bcba2a64ce3b4a2ad369c9e010c073aac44792bc05d9eafaf701fc81f72ff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/lang-html" + } + ] + }, + { + "type": "library", + "name": "lang-javascript", + "group": "@codemirror", + "version": "6.2.5", + "bom-ref": "launchpad@1.0.0|@codemirror/lang-javascript@6.2.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/lang-javascript@6.2.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cc3e1ee664bee7486d4bb17e4d88c13ec8881466a77d5aa0e07c94cfa58d16292038f7f60602a5c7e4d079d235c3a9ff22a4415416c15a618574b07feeec4ee0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/lang-javascript" + } + ] + }, + { + "type": "library", + "name": "lang-json", + "group": "@codemirror", + "version": "6.0.2", + "bom-ref": "launchpad@1.0.0|@codemirror/lang-json@6.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/lang-json@6.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c763ad3be02fc041eb130474172c8fb5f0d48a5a06deb9d54d2655d56f14b5e68b2fcfcc6a341df03a6f51bd985730befd3d7c6920efd07f66bbec70d044ada1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/lang-json" + } + ] + }, + { + "type": "library", + "name": "lang-xml", + "group": "@codemirror", + "version": "6.1.0", + "bom-ref": "launchpad@1.0.0|@codemirror/lang-xml@6.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/lang-xml@6.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "df3d1b96189c1cb7f08b65209196113e2a128154e8f4f57918fe5db9c147e85687cb420025183e8b18f98134758274ff8250080bcc6fe30d952f52e865fb3e26" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/lang-xml" + } + ] + }, + { + "type": "library", + "name": "language", + "group": "@codemirror", + "version": "6.12.4", + "bom-ref": "launchpad@1.0.0|@codemirror/language@6.12.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/language@6.12.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d6ae0f693fa8e8f6e0a6426de10f05bf95c9c53cb8154678316113b72883c372743f2afd136bea70a2fe93dc1cbe335322c6aec6f13b39f9968f71513c743be8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/language" + } + ] + }, + { + "type": "library", + "name": "lint", + "group": "@codemirror", + "version": "6.9.7", + "bom-ref": "launchpad@1.0.0|@codemirror/lint@6.9.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/lint@6.9.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "dbcffe8962d8c4ac6cbc66214982fbcda099a8bcf9f851450eaf6d56cbc6bfd92ff116387c501c849e565fd33762bad195322c1028ec5cfa9e3609d298d3f676" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/lint" + } + ] + }, + { + "type": "library", + "name": "search", + "group": "@codemirror", + "version": "6.7.1", + "bom-ref": "launchpad@1.0.0|@codemirror/search@6.7.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/search@6.7.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b8c7b950ee8f6a626d487ad78611cecd25f745e5ad889aef6ba1a73ccc123ab66d884c5be57e5e13186bd8e519415bddc4fb0aa58dd1a369856d069da4f5a61c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/search" + } + ] + }, + { + "type": "library", + "name": "state", + "group": "@codemirror", + "version": "6.7.1", + "bom-ref": "launchpad@1.0.0|@codemirror/state@6.7.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/state@6.7.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f50ccd0e01381180e70077eb4e547697088f72288eca62edc0a2bef321d0cc273b1978403fdc5d11b109172d88581d63f5419497d06c80c993a3f226034d93ec" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/state" + } + ] + }, + { + "type": "library", + "name": "view", + "group": "@codemirror", + "version": "6.43.9", + "bom-ref": "launchpad@1.0.0|@codemirror/view@6.43.9", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40codemirror/view@6.43.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b13b94cd3a4f30579b46183a75ac0286828a827748c1f8e6260295c4179f3c495c53637043a005ae8ba9934485a847ab43264e1917c336748df03c3f94c02c5f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@codemirror/view" + } + ] + }, + { + "type": "library", + "name": "nextcloud-vue", + "group": "@conduction", + "version": "2.229.0", + "bom-ref": "launchpad@1.0.0|@conduction/nextcloud-vue@2.229.0", + "licenses": [ + { + "license": { + "id": "EUPL-1.2" + } + } + ], + "purl": "pkg:npm/%40conduction/nextcloud-vue@2.229.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@conduction/nextcloud-vue/-/nextcloud-vue-2.229.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0ecbf51db9e31ef7272aaf88b90239034d86955dfeb3dd68cbaa1f300fd77630d4e4dc267616ef0c4d3341db9506c18ff41419fc2bef54cf24aaa2c0a1e611b1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@conduction/nextcloud-vue" + } + ], + "components": [ + { + "type": "library", + "name": "dialogs", + "group": "@nextcloud", + "version": "7.6.0", + "bom-ref": "launchpad@1.0.0|@conduction/nextcloud-vue@2.229.0|@nextcloud/dialogs@7.6.0", + "licenses": [ + { + "license": { + "id": "AGPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/dialogs@7.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/dialogs/-/dialogs-7.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b3a3d90cd8a82be8966d59bf636bad96958308aaa5c5f874a1468e9224166b166af23e5442c875888d5b2809e109116535cff22a68f510e5413114361031a435" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@conduction/nextcloud-vue/node_modules/@nextcloud/dialogs" + } + ], + "components": [ + { + "type": "library", + "name": "initial-state", + "group": "@nextcloud", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|@conduction/nextcloud-vue@2.229.0|@nextcloud/dialogs@7.6.0|@nextcloud/initial-state@3.0.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/initial-state@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/initial-state/-/initial-state-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "715f8705d9102469bc171901239ac54ff15b30d58d06fa5b8fa38fae0e007b860e3ac435e422fc2273ce030d6de1790e9102b63447541902d5533ff5f705db75" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@conduction/nextcloud-vue/node_modules/@nextcloud/dialogs/node_modules/@nextcloud/initial-state" + } + ] + } + ] + } + ] + }, + { + "type": "library", + "name": "css-calc", + "group": "@csstools", + "version": "3.3.0", + "bom-ref": "launchpad@1.0.0|@csstools/css-calc@3.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40csstools/css-calc@3.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7398a162c3e4746e890a4536cd3326e3e93aafb457b86c6d59886ee431cc222175147ceb7e61cbe6ca35d40a05a54bffb6eeb5c5f7264f80262a815f30fa2a75" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@csstools/css-calc" + } + ] + }, + { + "type": "library", + "name": "css-parser-algorithms", + "group": "@csstools", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|@csstools/css-parser-algorithms@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40csstools/css-parser-algorithms@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f81f3ba92edf206dcbe61deac09fc815b8e856839efdba4e761f610235dbbf1d28f08984994b065cdd229c53a79360a108582a92418543e4e9339adb86429ee3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@csstools/css-parser-algorithms" + } + ] + }, + { + "type": "library", + "name": "css-syntax-patches-for-csstree", + "group": "@csstools", + "version": "1.1.9", + "bom-ref": "launchpad@1.0.0|@csstools/css-syntax-patches-for-csstree@1.1.9", + "licenses": [ + { + "license": { + "id": "MIT-0" + } + } + ], + "purl": "pkg:npm/%40csstools/css-syntax-patches-for-csstree@1.1.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8861b0e0eb0062c4baa43dbd31d2766d7fe7271eb96b4e19662c3ac7e5705a53f60dd5dfe9ffbe666baffcecc02e97727d58636ddb88205d9c5ccec758121ef4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@csstools/css-syntax-patches-for-csstree" + } + ] + }, + { + "type": "library", + "name": "css-tokenizer", + "group": "@csstools", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|@csstools/css-tokenizer@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40csstools/css-tokenizer@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "43150b1c09bb70dbbbdb0f7b25434204538315a5e96c383e74ff1bfe8585019d8c4d1a69037534d18d8bd47a9a4b827ac81ab1c1afd8de73016b154a6c1fcdb0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@csstools/css-tokenizer" + } + ] + }, + { + "type": "library", + "name": "selector-resolve-nested", + "group": "@csstools", + "version": "4.0.1", + "bom-ref": "launchpad@1.0.0|@csstools/selector-resolve-nested@4.0.1", + "licenses": [ + { + "license": { + "id": "MIT-0" + } + } + ], + "purl": "pkg:npm/%40csstools/selector-resolve-nested@4.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@csstools/selector-resolve-nested/-/selector-resolve-nested-4.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8f7bdd42ed17c0b304e6a3935b19bc7279afb1fe36dd1d982fa0db2a49421d9c240e6ed474a36ee913e5c3844420985294a048098dc1ef4ffb41976270ba9982" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@csstools/selector-resolve-nested" + } + ] + }, + { + "type": "library", + "name": "selector-specificity", + "group": "@csstools", + "version": "6.0.0", + "bom-ref": "launchpad@1.0.0|@csstools/selector-specificity@6.0.0", + "licenses": [ + { + "license": { + "id": "MIT-0" + } + } + ], + "purl": "pkg:npm/%40csstools/selector-specificity@6.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@csstools/selector-specificity/-/selector-specificity-6.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e2c4a097bf0eb4e5c45ffd9dfbef00f37cc735383008931a476e05bec60bed47ff552f07664f4f4f0479d5e9536c6a8cbb01f7b332efbce5c46959ea9f4677cc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@csstools/selector-specificity" + } + ] + }, + { + "type": "library", + "name": "tinycolor", + "group": "@ctrl", + "version": "3.6.1", + "bom-ref": "launchpad@1.0.0|@ctrl/tinycolor@3.6.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40ctrl/tinycolor@3.6.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-3.6.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4884d257a6885ecb95355ddfdced1fda7fdc8321035a84aab5931888099cb181f275c2ab3b3de053107f89777f41fd3cf88657e0aa6035bbd474c0665b3fa470" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@ctrl/tinycolor" + } + ] + }, + { + "type": "library", + "name": "core", + "group": "@emnapi", + "version": "2.0.0-beta.2", + "bom-ref": "launchpad@1.0.0|@emnapi/core@2.0.0-beta.2", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40emnapi/core@2.0.0-beta.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "333095a16b5c8383e6d81de37b998cbd832f8f732604ac3e7d4eef6ec25cf7f893f22a7afde6081e8fc3b26fe6afec2c1c1e92132243bb1074f58cbaafff3ee0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@emnapi/core" + } + ] + }, + { + "type": "library", + "name": "runtime", + "group": "@emnapi", + "version": "2.0.0-beta.2", + "bom-ref": "launchpad@1.0.0|@emnapi/runtime@2.0.0-beta.2", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40emnapi/runtime@2.0.0-beta.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "25cad23f33ef66e359bc9a8f4c5f45c36e4b6ce27c6afcc556569fda0ae61f80a4bb4a063f8eed460a8f65a75c7e3dd8a1930790556709815b40cf08fa2e5013" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@emnapi/runtime" + } + ] + }, + { + "type": "library", + "name": "wasi-threads", + "group": "@emnapi", + "version": "2.2.0", + "bom-ref": "launchpad@1.0.0|@emnapi/wasi-threads@2.2.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40emnapi/wasi-threads@2.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "24fece607dfc43bfa9c9301ed78ada6472d020aec10ca6ddc238be5e2de971dffa424258407dd25f8c2ee84a651ab1895917a9a0dcde75f9b41b707d6787bd47" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@emnapi/wasi-threads" + } + ] + }, + { + "type": "library", + "name": "eslint-utils", + "group": "@eslint-community", + "version": "4.10.1", + "bom-ref": "launchpad@1.0.0|@eslint-community/eslint-utils@4.10.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40eslint-community/eslint-utils@4.10.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "72e69d73154513cb032ba89625bb3c4a7d1abf636b8764121908559415bd01a007a87c235ac6474fc2c9e211463e1ec048157675e15d33b1ff0cf8ee96687cae" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint-community/eslint-utils" + } + ], + "components": [ + { + "type": "library", + "name": "eslint-visitor-keys", + "version": "3.4.3", + "bom-ref": "launchpad@1.0.0|@eslint-community/eslint-utils@4.10.1|eslint-visitor-keys@3.4.3", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/eslint-visitor-keys@3.4.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c2973e2d77a2ca28acc4f944914cd4eacbf24b57eb20edcc8318f57ddcbb3e6f1883382e6b1d8ddc56bf0ff6a0d56a9b3a9add23eb98eb031497cfdad86fa26a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys" + } + ] + } + ] + }, + { + "type": "library", + "name": "regexpp", + "group": "@eslint-community", + "version": "4.12.2", + "bom-ref": "launchpad@1.0.0|@eslint-community/regexpp@4.12.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40eslint-community/regexpp@4.12.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "12b8924e5b79382f7fed25e445208085f4b1c684948019b7dce1fe224c1b769828aac4ac520ef2dee87e208088fd08380415abdd4da2dfd4699b271bc4cab87b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint-community/regexpp" + } + ] + }, + { + "type": "library", + "name": "config-array", + "group": "@eslint", + "version": "0.23.6", + "bom-ref": "launchpad@1.0.0|@eslint/config-array@0.23.6", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40eslint/config-array@0.23.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5ab4c7ee78a823d40f6383591a7b32c2679cb3025d81eab804233beaaa24f558234cedbd66053352f72e24b54f61540ce2e0db68f054d0cdf747d0c8c48f17df" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint/config-array" + } + ], + "components": [ + { + "type": "library", + "name": "minimatch", + "version": "11.0.8", + "bom-ref": "launchpad@1.0.0|@eslint/config-array@0.23.6|minimatch@11.0.8", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0" + } + } + ], + "purl": "pkg:npm/minimatch@11.0.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9c542e6124d5ac6bf2b15069b39221fb405d9d814dfc28f70bcd7aafafa9ef22be147ad52c61383b837d005c3292b94d96f3361d8b7e45a775522ae8ea1f3c22" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint/config-array/node_modules/minimatch" + } + ] + } + ] + }, + { + "type": "library", + "name": "config-helpers", + "group": "@eslint", + "version": "0.7.0", + "bom-ref": "launchpad@1.0.0|@eslint/config-helpers@0.7.0", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40eslint/config-helpers@0.7.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0ce6ddfca294b14f85685bf83cbc5245e9e95df41698f5d73f7a4f67afcad4f0ab32edaf42930332e41efc1a987a82dccfcae8d1b54317547138981f54476153" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint/config-helpers" + } + ] + }, + { + "type": "library", + "name": "core", + "group": "@eslint", + "version": "1.2.1", + "bom-ref": "launchpad@1.0.0|@eslint/core@1.2.1", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40eslint/core@1.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "330704d4ff806780ba0d69698a7fce98e039e2698867ffb166e26241de12c81dbda00263377d145bdc2428da6d5b672da78704b2f8652d8fc2b10d6ea070e5a1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint/core" + } + ] + }, + { + "type": "library", + "name": "object-schema", + "group": "@eslint", + "version": "3.0.5", + "bom-ref": "launchpad@1.0.0|@eslint/object-schema@3.0.5", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40eslint/object-schema@3.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bea4da504831ce6f980d274495a77a3e24685f8b7c5460e30adb74e739f89d4f35d14231fee34457bfe5649e8ac054e12993b33b1cd7cb8f1d6be368ec765a33" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint/object-schema" + } + ] + }, + { + "type": "library", + "name": "plugin-kit", + "group": "@eslint", + "version": "0.7.3", + "bom-ref": "launchpad@1.0.0|@eslint/plugin-kit@0.7.3", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40eslint/plugin-kit@0.7.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2243befca114bf06d5a62511660f8fef317be33e49c5ed14809c559e2f91b681d0e8866279768ed3692669da266a9feafa5e9b73f8dd3c61aa4e386e667bb3d5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@eslint/plugin-kit" + } + ] + }, + { + "type": "library", + "name": "xml", + "group": "@file-type", + "version": "0.4.4", + "bom-ref": "launchpad@1.0.0|@file-type/xml@0.4.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40file-type/xml@0.4.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@file-type/xml/-/xml-0.4.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3610b25e81e5559f13a8ce3bea1cb3c06276e3e0f920f49a6619ab3e3eea5e71156f7aba8eb17303798cf5306992729223d12e41e1932918360d7194c2f041a1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@file-type/xml" + } + ] + }, + { + "type": "library", + "name": "core", + "group": "@floating-ui", + "version": "1.8.0", + "bom-ref": "launchpad@1.0.0|@floating-ui/core@1.8.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40floating-ui/core@1.8.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d02219e62b69b3ff31ec11bc744221b39dc1bc2507d8f0a8a20b5a930453badf80ae6e7cb09a2827402e6612f0d87258211e5c30b34f0524bbdbcb0f868da485" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@floating-ui/core" + } + ] + }, + { + "type": "library", + "name": "dom", + "group": "@floating-ui", + "version": "1.8.0", + "bom-ref": "launchpad@1.0.0|@floating-ui/dom@1.8.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40floating-ui/dom@1.8.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c974abcde1d905365a74b3a57f28429091cd78b2671d19d1227c1d678d0bed989a02dac1c28625b03ad7defe7307552d93b08b7f370e5675555a85c4932ec27a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@floating-ui/dom" + } + ] + }, + { + "type": "library", + "name": "utils", + "group": "@floating-ui", + "version": "0.2.12", + "bom-ref": "launchpad@1.0.0|@floating-ui/utils@0.2.12", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40floating-ui/utils@0.2.12", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1e90a8f2d996ccb55a779b36775f44840cf9ceaaeb43ab3af6a77a9a83cc42f90eb92c034f562045f59256e7387a79eaae0bf7387a6988e18c43ba02d77c88c3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@floating-ui/utils" + } + ] + }, + { + "type": "library", + "name": "core", + "group": "@humanfs", + "version": "0.19.2", + "bom-ref": "launchpad@1.0.0|@humanfs/core@0.19.2", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40humanfs/core@0.19.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5215cd9be08531671b0a15f2c05c249a1aa3b373d10a67126bf85f0602c86fba10e4735bd704b489c5ac1ad48050d81e7c7788f9e06b03c2357f199b1ec19dbc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@humanfs/core" + } + ] + }, + { + "type": "library", + "name": "node", + "group": "@humanfs", + "version": "0.16.8", + "bom-ref": "launchpad@1.0.0|@humanfs/node@0.16.8", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40humanfs/node@0.16.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "804d5e40d67747efa44f3154a5d1a5a66cbc903643fcc2f21ea0f0aa3915408d0931d2350f9d6ccb51fde7c3cd5d890cdab01a73b7b9fc29c8299ac7b4f87705" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@humanfs/node" + } + ] + }, + { + "type": "library", + "name": "types", + "group": "@humanfs", + "version": "0.15.0", + "bom-ref": "launchpad@1.0.0|@humanfs/types@0.15.0", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40humanfs/types@0.15.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "659d70d1aa10930b94b82ed87feeec75e68d7ea42288b71245b7c8d3ca00c6a2eda5742bf402155fb032ec72c3ba22d801a14fbbca0160dabf4088bd5111c9dd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@humanfs/types" + } + ] + }, + { + "type": "library", + "name": "module-importer", + "group": "@humanwhocodes", + "version": "1.0.1", + "bom-ref": "launchpad@1.0.0|@humanwhocodes/module-importer@1.0.1", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40humanwhocodes/module-importer@1.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6f1bde57857cbf961be277054d3deb3d281904ea429237cad32e28555549c08b8354144c0d7acfc9744bf7cf22e5aa7d9bd6e7c8412359f9b95a4066b5f7cb7c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@humanwhocodes/module-importer" + } + ] + }, + { + "type": "library", + "name": "retry", + "group": "@humanwhocodes", + "version": "0.4.3", + "bom-ref": "launchpad@1.0.0|@humanwhocodes/retry@0.4.3", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40humanwhocodes/retry@0.4.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6d5d13828f4ae217cf09e93e68c027f35469a452afdb248341e328499baf4c04b2c0d4e7549080ac2644d855aaa6f21ab4abbb54c44b5a547511acef5610f285" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@humanwhocodes/retry" + } + ] + }, + { + "type": "library", + "name": "nonrecursive-glob-match", + "group": "@isaacs", + "version": "1.1.0", + "bom-ref": "launchpad@1.0.0|@isaacs/nonrecursive-glob-match@1.1.0", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0" + } + } + ], + "purl": "pkg:npm/%40isaacs/nonrecursive-glob-match@1.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "18f9bf0dbbe4e512e68519f15c86bb9d3a4ad31b65e04d308f432c96cb8d889d45211394fb6fbd960502fdd805ec4cb84025a17c4b20c6294c44c09d1cf7c37f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@isaacs/nonrecursive-glob-match" + } + ] + }, + { + "type": "library", + "name": "gen-mapping", + "group": "@jridgewell", + "version": "0.3.13", + "bom-ref": "launchpad@1.0.0|@jridgewell/gen-mapping@0.3.13", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40jridgewell/gen-mapping@0.3.13", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "da492dffb9e227a32010fc45d1b61d43a7ad65a03e7d0bc370b29c921cb5c8840ecdaa0a8c10634a3eb7fda2d58d8137aa146de5dbccfae5327c283a50a0816c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/gen-mapping" + } + ] + }, + { + "type": "library", + "name": "remapping", + "group": "@jridgewell", + "version": "2.3.5", + "bom-ref": "launchpad@1.0.0|@jridgewell/remapping@2.3.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40jridgewell/remapping@2.3.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2c8f6effe95a606e03b354c3292256d983eb22571560ec22d9f502eb1078de5b9e0a383157895f7ce0990ad605887e9334e5feb50297c7ded3e082876e1c8711" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/remapping" + } + ] + }, + { + "type": "library", + "name": "resolve-uri", + "group": "@jridgewell", + "version": "3.1.2", + "bom-ref": "launchpad@1.0.0|@jridgewell/resolve-uri@3.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40jridgewell/resolve-uri@3.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6d12128022233f6d3fb5b5923d63048b9e1054f45913192e0fd9492fe508c542adc15240f305b54eb6f58ccb354455e8d42053359ff98690bd42f98a59da292b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/resolve-uri" + } + ] + }, + { + "type": "library", + "name": "source-map", + "group": "@jridgewell", + "version": "0.3.11", + "bom-ref": "launchpad@1.0.0|@jridgewell/source-map@0.3.11", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40jridgewell/source-map@0.3.11", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "64ca7557c64570f1b97485a740baf7352235322094ed4113752fc0d06f15fd7587bc9bf766c16abad267d58e513e600f5fa177062137f7b3aabde53ff4d0ae20" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/source-map" + } + ] + }, + { + "type": "library", + "name": "sourcemap-codec", + "group": "@jridgewell", + "version": "1.6.0", + "bom-ref": "launchpad@1.0.0|@jridgewell/sourcemap-codec@1.6.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40jridgewell/sourcemap-codec@1.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4fb8dffb9ce0b191f0349e25bd0eff69ecdbca4d27357fb32555a998703b558b04c7b6bbaabe5183921bb4916a920cdee58dacaeeab545463c43cdfb39dee217" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/sourcemap-codec" + } + ] + }, + { + "type": "library", + "name": "trace-mapping", + "group": "@jridgewell", + "version": "0.3.31", + "bom-ref": "launchpad@1.0.0|@jridgewell/trace-mapping@0.3.31", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40jridgewell/trace-mapping@0.3.31", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cf3351f9275048327373c8e869e3fc410a0242bf0db98c76748232b65d507811191c9f6e5ba85e6ecad881bcfc849c1441aa374d608cb667d5f0dbb5b7038b03" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@jridgewell/trace-mapping" + } + ] + }, + { + "type": "library", + "name": "bigmap", + "group": "@keyv", + "version": "1.3.1", + "bom-ref": "launchpad@1.0.0|@keyv/bigmap@1.3.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40keyv/bigmap@1.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "59bcc4f6c76642d2b2f2facd3daf41467c19879505e2cd4a4e648ad0a5152e8dde7dfe4195034d5839c53a8b8da4a7cf2839e6b3dc729c98ec3188cc693fda15" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@keyv/bigmap" + } + ] + }, + { + "type": "library", + "name": "serialize", + "group": "@keyv", + "version": "1.1.1", + "bom-ref": "launchpad@1.0.0|@keyv/serialize@1.1.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40keyv/serialize@1.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7579f715984fbf4512fbb76d26c222d91f9ceea5988917a8121e73527b5609fe284a930d89bf050e14a879dea6dd0c99771e612bb88b164624deb371c2df2f4c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@keyv/serialize" + } + ] + }, + { + "type": "library", + "name": "common", + "group": "@lezer", + "version": "1.5.2", + "bom-ref": "launchpad@1.0.0|@lezer/common@1.5.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40lezer/common@1.5.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b31404e3ad1f3d9c94dec75cf2569fc623f0247073651cbfb9d345ca7190932d5278f60176190197590e6a003db93de9c51f0ad3d6ceae64d4a80f706ff3e349" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@lezer/common" + } + ] + }, + { + "type": "library", + "name": "css", + "group": "@lezer", + "version": "1.3.6", + "bom-ref": "launchpad@1.0.0|@lezer/css@1.3.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40lezer/css@1.3.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@lezer/css/-/css-1.3.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "60913bf16720fb35fc7f5d21887590e00cf8f10aff735dde21dd15b514182c1a711c3983792ad722591b97e7c9196e36ad60bfba851ca3d9a105979558ffc0d6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@lezer/css" + } + ] + }, + { + "type": "library", + "name": "highlight", + "group": "@lezer", + "version": "1.2.3", + "bom-ref": "launchpad@1.0.0|@lezer/highlight@1.2.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40lezer/highlight@1.2.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a97747ed4a93bc67dd54120dae02a10ec553253c5a72d34dc4b93bf94330661535de530768e06525ef55aa9f74ef26b9e98dfe79ddad96acf2b3b8c3913996d2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@lezer/highlight" + } + ] + }, + { + "type": "library", + "name": "html", + "group": "@lezer", + "version": "1.3.13", + "bom-ref": "launchpad@1.0.0|@lezer/html@1.3.13", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40lezer/html@1.3.13", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a08ee7e8d26697bdbd9bba639bd96f2ef9976dda0ca22d9ffb5a7048326497d77af331abedaf41b73f0d7474c6419b56d83036e726debaffd2c836fd0f9b6c7a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@lezer/html" + } + ] + }, + { + "type": "library", + "name": "javascript", + "group": "@lezer", + "version": "1.5.4", + "bom-ref": "launchpad@1.0.0|@lezer/javascript@1.5.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40lezer/javascript@1.5.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bef631dcc856a9e66d18fc034ad3367708258dde6c9a89580f6951d94c857077f16c141e6eac7cca39859b1b49fc4ea737abb50fdb2b3a25569b745be2d99c50" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@lezer/javascript" + } + ] + }, + { + "type": "library", + "name": "json", + "group": "@lezer", + "version": "1.0.3", + "bom-ref": "launchpad@1.0.0|@lezer/json@1.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40lezer/json@1.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "04ff4acdd17d637e4f0e9bf4e2bd157924ca0dea31e6f56bdde7c4ede05bc77af8b37a0d2dfba77217a36618c0ae67a27811fe9d53a9808881269100bfc8a5a9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@lezer/json" + } + ] + }, + { + "type": "library", + "name": "lr", + "group": "@lezer", + "version": "1.4.10", + "bom-ref": "launchpad@1.0.0|@lezer/lr@1.4.10", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40lezer/lr@1.4.10", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ae70a94c805a7cec78991a78df13b10c96c58a9266fdcd1c89afd5e5388696198c6bec2c49da06994377c3906aae4b3fd3d43f0f8b4d02659a4fca7a3518bbec" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@lezer/lr" + } + ] + }, + { + "type": "library", + "name": "xml", + "group": "@lezer", + "version": "1.0.6", + "bom-ref": "launchpad@1.0.0|@lezer/xml@1.0.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40lezer/xml@1.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@lezer/xml/-/xml-1.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "09d0f08ab2f4384692b45b9effae9998549ea69b8be83c23964f2a935e779924308921ff0e5ae2e063729ab3569d498f976526ed07d5d453bd2855325f74f0c3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@lezer/xml" + } + ] + }, + { + "type": "library", + "name": "find-cluster-break", + "group": "@marijn", + "version": "1.0.4", + "bom-ref": "launchpad@1.0.0|@marijn/find-cluster-break@1.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40marijn/find-cluster-break@1.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5b2d15efe4865239c5f7f4e488cd612950cf8fb8ca5ddb8f35ba0c56d1d303c77248c5115aa7e0fc967d1364aaf09812266925ee4ed07bd14b78c4ab4ab69699" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@marijn/find-cluster-break" + } + ] + }, + { + "type": "library", + "name": "js", + "group": "@mdi", + "version": "7.4.47", + "bom-ref": "launchpad@1.0.0|@mdi/js@7.4.47", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40mdi/js@7.4.47", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@mdi/js/-/js-7.4.47.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "28f9cd3ad9b98b6a4c69ba99c69533ee241ffa67eb619c8a099f10373f39733804b7b72e1dc1a8ad67ddcd4316600d120fe6ba1e7e05989f98873cf38e44d9ad" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@mdi/js" + } + ] + }, + { + "type": "library", + "name": "fetch-event-source", + "group": "@microsoft", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|@microsoft/fetch-event-source@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40microsoft/fetch-event-source@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@microsoft/fetch-event-source/-/fetch-event-source-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5ba08b509d9e04cc3745e73bd2aaec116d233a6ff7b70c09bf6d66ae68f6c8e4626959956064b8b124b9c94c2f41cd599432d818f9c29555a651431a80a36c7c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@microsoft/fetch-event-source" + } + ] + }, + { + "type": "library", + "name": "wasm-runtime", + "group": "@napi-rs", + "version": "1.2.6", + "bom-ref": "launchpad@1.0.0|@napi-rs/wasm-runtime@1.2.6", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40napi-rs/wasm-runtime@1.2.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "991c83984c3dfdf0835c219f2f5b1b808c3f1942b43d5c515b863080f37ad45dcb43e7d2ca80456ab255ce01b2845ea447311067415e8c3aa6e162d749ea909b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@napi-rs/wasm-runtime" + } + ] + }, + { + "type": "library", + "name": "auth", + "group": "@nextcloud", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/auth@2.6.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/auth@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/auth/-/auth-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5644fcefef54aa93e2ecedfa6d5104e3f331585f1df7455072e325bca96db19c8b48b9041ab3d7828c2d0fbe58e7893ad3ff1247a9976dea81c1aa62f1d0d46c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/auth" + } + ] + }, + { + "type": "library", + "name": "axios", + "group": "@nextcloud", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/axios@2.6.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/axios@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/axios/-/axios-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7a1708832a2b6bc0c027e4931ba8852387beb9f3d516b200ea8d0580c29e29d7f26b1449f5433b2fe9fb57eadcfeabfcb038960bf85620ac05b4bc365b9c84e1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/axios" + } + ] + }, + { + "type": "library", + "name": "browser-storage", + "group": "@nextcloud", + "version": "0.5.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/browser-storage@0.5.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/browser-storage@0.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/browser-storage/-/browser-storage-0.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bac62be069494252b786065446f925a966fd8af8bbb20b12b85a97aeceece219752d34b87a7ccfae7910ba69ba9d1b10aee7f42134be381b0afa810b11bbd83c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/browser-storage" + } + ] + }, + { + "type": "library", + "name": "capabilities", + "group": "@nextcloud", + "version": "1.2.1", + "bom-ref": "launchpad@1.0.0|@nextcloud/capabilities@1.2.1", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/capabilities@1.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/capabilities/-/capabilities-1.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b27674ffdd74cf3c0de8f0ec225c7652f92daf54b9c740a58435277cf9428fb9ed36f102cee547358e70cdbcb6d8b22473ef598da0cab42c2e0addb27bef69fd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/capabilities" + } + ], + "components": [ + { + "type": "library", + "name": "initial-state", + "group": "@nextcloud", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/capabilities@1.2.1|@nextcloud/initial-state@3.0.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/initial-state@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/initial-state/-/initial-state-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "715f8705d9102469bc171901239ac54ff15b30d58d06fa5b8fa38fae0e007b860e3ac435e422fc2273ce030d6de1790e9102b63447541902d5533ff5f705db75" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/capabilities/node_modules/@nextcloud/initial-state" + } + ] + } + ] + }, + { + "type": "library", + "name": "dialogs", + "group": "@nextcloud", + "version": "8.0.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/dialogs@8.0.0", + "licenses": [ + { + "license": { + "id": "AGPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/dialogs@8.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/dialogs/-/dialogs-8.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f2e379f5728e324ecc54287437175df21bd9999431955211bfcb351ab842e7e51bd210fac89ffc5f2aee179e25ae4986981aa1d38f3f8bf64447ddefc1f4690e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/dialogs" + } + ], + "components": [ + { + "type": "library", + "name": "initial-state", + "group": "@nextcloud", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/dialogs@8.0.0|@nextcloud/initial-state@3.0.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/initial-state@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/initial-state/-/initial-state-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "715f8705d9102469bc171901239ac54ff15b30d58d06fa5b8fa38fae0e007b860e3ac435e422fc2273ce030d6de1790e9102b63447541902d5533ff5f705db75" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/dialogs/node_modules/@nextcloud/initial-state" + } + ] + }, + { + "type": "library", + "name": "p-queue", + "version": "10.0.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/dialogs@8.0.0|p-queue@10.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/p-queue@10.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/p-queue/-/p-queue-10.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3f6c2b0ab8b76e118b3e8de45fba985576e8ff91af6950135340e93b6e026de4f9dd8e33df9b7c2545a4bb4e044695c7518079acf322dd39161377e6260c79ac" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/dialogs/node_modules/p-queue" + } + ] + } + ] + }, + { + "type": "library", + "name": "event-bus", + "group": "@nextcloud", + "version": "3.3.3", + "bom-ref": "launchpad@1.0.0|@nextcloud/event-bus@3.3.3", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/event-bus@3.3.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/event-bus/-/event-bus-3.3.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cc87ef2a6506917a55cd12a85eb70ef6192888a0e6eb97ea371cbf5c86c8c6b421641c8fab78039230699eedd5e46b3c25d6306bbdd1f038f357da07f0762122" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/event-bus" + } + ], + "components": [ + { + "type": "library", + "name": "semver", + "version": "7.8.5", + "bom-ref": "launchpad@1.0.0|@nextcloud/event-bus@3.3.3|semver@7.8.5", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/semver@7.8.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "63bfca0ec6fc2e3a28669c1aa86cae94ee8342592c8029dc7211c693eb19218e1206f52870c044147e54af57c8e1d57e26f974c3a723bee71a222e34a6e462a0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/event-bus/node_modules/semver" + } + ] + } + ] + }, + { + "type": "library", + "name": "files", + "group": "@nextcloud", + "version": "4.1.1", + "bom-ref": "launchpad@1.0.0|@nextcloud/files@4.1.1", + "licenses": [ + { + "license": { + "id": "AGPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/files@4.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/files/-/files-4.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ddfbda04d39b5c58d58059b416f3d7afeaed621d8250601cd3ef7c76120fd000bb43e502558230c81dedb120463f6f479ea196a86458ee765a8fb808ecdcdbbd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/files" + } + ] + }, + { + "type": "library", + "name": "initial-state", + "group": "@nextcloud", + "version": "2.2.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/initial-state@2.2.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/initial-state@2.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/initial-state/-/initial-state-2.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7035bdf0be4a1868294bca7377ed39df4e3fa7cd1ccaef14db14834066be9063d3a5416609bbf6aa73b95abc301936aeca36228c26a5d9b9b0f3655d7521fe3e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/initial-state" + } + ] + }, + { + "type": "library", + "name": "l10n", + "group": "@nextcloud", + "version": "3.4.1", + "bom-ref": "launchpad@1.0.0|@nextcloud/l10n@3.4.1", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/l10n@3.4.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/l10n/-/l10n-3.4.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6931629d370a88ada0117c0b82eb577a4a5967cfefff84220bc0b74022c7e66d28f96b71b010be7ea575e3679b0bfadf0e7cc22e163866db304aef1b15b66872" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/l10n" + } + ] + }, + { + "type": "library", + "name": "logger", + "group": "@nextcloud", + "version": "3.0.3", + "bom-ref": "launchpad@1.0.0|@nextcloud/logger@3.0.3", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/logger@3.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/logger/-/logger-3.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4dc6d544be3f3b97df235457166400143de0c304f5e4001daf5efbd31f9136a56f7c1768195ca1ccec0223203955f7377c0d6225715afab13a6ee2594a8aa573" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/logger" + } + ] + }, + { + "type": "library", + "name": "notify_push", + "group": "@nextcloud", + "version": "1.4.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/notify_push@1.4.0", + "licenses": [ + { + "license": { + "id": "AGPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/notify_push@1.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/notify_push/-/notify_push-1.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d3b503833d712c6f570013fcfa6c10d82b0d599bba94acf3d04ad40361df13565fc572a2c15a68eb4b77d32df8504c4607df8e9359c569853c7f22479dccfd69" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/notify_push" + } + ] + }, + { + "type": "library", + "name": "password-confirmation", + "group": "@nextcloud", + "version": "6.2.1", + "bom-ref": "launchpad@1.0.0|@nextcloud/password-confirmation@6.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40nextcloud/password-confirmation@6.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/password-confirmation/-/password-confirmation-6.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "151450d0b02c513ec8f4e1b25103a0f3a4312322d354b98121b3d6ee57ddba3f5a0ed619cabaedc878d396df1c6947ddbb643fb42afcf2f85b17386f47db8c85" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/password-confirmation" + } + ] + }, + { + "type": "library", + "name": "paths", + "group": "@nextcloud", + "version": "3.1.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/paths@3.1.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/paths@3.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/paths/-/paths-3.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bed15803f92d85a503ceee8a7a34ce2f53b09cecbbff2ca7ab9cdd07f501a5869c0168d45f90dd87838c5b1deb11abe4049f7f40686b16bc8d24b8cd7def0e40" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/paths" + } + ] + }, + { + "type": "library", + "name": "router", + "group": "@nextcloud", + "version": "3.2.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/router@3.2.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/router@3.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/router/-/router-3.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6a7e2027b9a50d91ad62af334f1a784a0fa22e528a1af43d647dc3a7a81afc89433403fb55e3151a986c63bf7c3918e7700a7dfac11fdfbd0be73a6c9eec609e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/router" + } + ] + }, + { + "type": "library", + "name": "sharing", + "group": "@nextcloud", + "version": "0.4.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/sharing@0.4.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/sharing@0.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/sharing/-/sharing-0.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d6150dc9ceee25d0699e298e9c4b2126312d00f023cc361597aaa65aa179671a0df703af6c4c70d108d7df11486c76d7d9d9af6d134b063d11ccbce2a666727a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/sharing" + } + ], + "components": [ + { + "type": "library", + "name": "initial-state", + "group": "@nextcloud", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/sharing@0.4.0|@nextcloud/initial-state@3.0.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/initial-state@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/initial-state/-/initial-state-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "715f8705d9102469bc171901239ac54ff15b30d58d06fa5b8fa38fae0e007b860e3ac435e422fc2273ce030d6de1790e9102b63447541902d5533ff5f705db75" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/sharing/node_modules/@nextcloud/initial-state" + } + ] + } + ] + }, + { + "type": "library", + "name": "stylelint-config", + "group": "@nextcloud", + "version": "3.2.2", + "bom-ref": "launchpad@1.0.0|@nextcloud/stylelint-config@3.2.2", + "licenses": [ + { + "license": { + "id": "AGPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/stylelint-config@3.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/stylelint-config/-/stylelint-config-3.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e6bafbedf18afb3a1af3237ef33478dd76eacae37fc81db0480cb8bca13617e86001e3a1a540320a157ea5fc920db3f6d2de2cdb60c7827ec10e264ab1b344dd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/stylelint-config" + } + ] + }, + { + "type": "library", + "name": "typings", + "group": "@nextcloud", + "version": "1.10.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/typings@1.10.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/typings@1.10.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/typings/-/typings-1.10.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "48c0b8dab0e3387dd2b293d32cc651bfbe999621e98f6249905f2918b3fc97542b553671138ed0cf9a9e2a66e3d952fe751bf67bf3608b1940166cd59f1921aa" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/typings" + } + ] + }, + { + "type": "library", + "name": "vue-select", + "group": "@nextcloud", + "version": "4.1.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/vue-select@4.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40nextcloud/vue-select@4.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/vue-select/-/vue-select-4.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8d022ee17b9402e26beaa2ff20a6bade1dd5bffe0eacff656ad97613a92ab5f7f02c157ea8c494e069bebec39fcaa05b0526388b779e31f772262d783b562a6e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/vue-select" + } + ] + }, + { + "type": "library", + "name": "vue", + "group": "@nextcloud", + "version": "9.14.1", + "bom-ref": "launchpad@1.0.0|@nextcloud/vue@9.14.1", + "licenses": [ + { + "license": { + "id": "AGPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/vue@9.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/vue/-/vue-9.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a8b098371d1f172d9923ed9eea798db7335f1ec53fbadc0233ebbaee4a8b522fd4935d51ac5c445dbd83c4e270a1d6c5d8afc402bb66ba4de5f4526a609eaffe" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/vue" + } + ], + "components": [ + { + "type": "library", + "name": "initial-state", + "group": "@nextcloud", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/vue@9.14.1|@nextcloud/initial-state@3.0.0", + "licenses": [ + { + "license": { + "id": "GPL-3.0-or-later" + } + } + ], + "purl": "pkg:npm/%40nextcloud/initial-state@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nextcloud/initial-state/-/initial-state-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "715f8705d9102469bc171901239ac54ff15b30d58d06fa5b8fa38fae0e007b860e3ac435e422fc2273ce030d6de1790e9102b63447541902d5533ff5f705db75" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/vue/node_modules/@nextcloud/initial-state" + } + ] + }, + { + "type": "library", + "name": "p-queue", + "version": "10.0.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/vue@9.14.1|p-queue@10.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/p-queue@10.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/p-queue/-/p-queue-10.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3f6c2b0ab8b76e118b3e8de45fba985576e8ff91af6950135340e93b6e026de4f9dd8e33df9b7c2545a4bb4e044695c7518079acf322dd39161377e6260c79ac" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/vue/node_modules/p-queue" + } + ] + }, + { + "type": "library", + "name": "vue-router", + "version": "5.5.1", + "bom-ref": "launchpad@1.0.0|@nextcloud/vue@9.14.1|vue-router@5.5.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue-router@5.5.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue-router/-/vue-router-5.5.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "95410d77f40884a7761d60029d7203deeb34196067b8e8b707091353371edbee277ccfdbdec795e6c68d51133dfb0b78f3fa94c6f8a8b69726ef21710b4538a8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/vue/node_modules/vue-router" + } + ] + }, + { + "type": "library", + "name": "chokidar", + "version": "6.0.0", + "bom-ref": "launchpad@1.0.0|@nextcloud/vue@9.14.1|chokidar@6.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/chokidar@6.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/chokidar/-/chokidar-6.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "11cd99ef0a5c28188ca51ec3c6d7a8a92fecab91b97760387e9c733efebe7c3ef134d76b4e0867ecbd7563057910dd41de2ef612b7375d54f91645880f1f74f8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/vue/node_modules/chokidar" + } + ] + }, + { + "type": "library", + "name": "magic-string", + "version": "1.4.5", + "bom-ref": "launchpad@1.0.0|@nextcloud/vue@9.14.1|magic-string@1.4.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/magic-string@1.4.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a0b2c2dbe62f4147c06bebf1a2e7c4ff273589c6fceccf625c846a02847fd84844ffc71bdd217ff868b4736072d41fb9573d9edaf42d52f1e2bb5fbadd99e1fb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nextcloud/vue/node_modules/magic-string" + } + ] + } + ] + }, + { + "type": "library", + "name": "entities", + "group": "@nodable", + "version": "3.1.0", + "bom-ref": "launchpad@1.0.0|@nodable/entities@3.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40nodable/entities@3.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nodable/entities/-/entities-3.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2ec4bf0e31ebfae0cceb8ec6aeefdc03cf89ddadc77e1b6dc0228bcaea3237bc974c50b1281b5280c401beb5bdc8d3dadbfcc345436e18f687e50505a1ae1aad" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nodable/entities" + } + ] + }, + { + "type": "library", + "name": "fs.scandir", + "group": "@nodelib", + "version": "2.1.5", + "bom-ref": "launchpad@1.0.0|@nodelib/fs.scandir@2.1.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40nodelib/fs.scandir@2.1.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "beadb806adf29b91c4426d8d282af7c970f08dceef4ec1138510e7929d832bda75baa2d1f831eeae6fcd393a34286ec760753b7a9a4a663dcccaa62e3017fada" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nodelib/fs.scandir" + } + ] + }, + { + "type": "library", + "name": "fs.stat", + "group": "@nodelib", + "version": "2.0.5", + "bom-ref": "launchpad@1.0.0|@nodelib/fs.stat@2.0.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40nodelib/fs.stat@2.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "46484f3e9db3aea0c0400ff68cd867ced70f025bfae17761229edaef8e78039a2f23b06e93182decc5fbb9dc00bb7ce0d437293d4d2bcf7555d5279aaaf638f8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nodelib/fs.stat" + } + ] + }, + { + "type": "library", + "name": "fs.walk", + "group": "@nodelib", + "version": "1.2.8", + "bom-ref": "launchpad@1.0.0|@nodelib/fs.walk@1.2.8", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40nodelib/fs.walk@1.2.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a0607e53196059c810920c28f067041b07a6a1316ddc520ef5a6da6c199a1b05c8a01299f864f2d293f5f396de1a0ecb96287f3521d25765c0b35967ce7a1c4a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@nodelib/fs.walk" + } + ] + }, + { + "type": "library", + "name": "types", + "group": "@oxc-project", + "version": "0.156.0", + "bom-ref": "launchpad@1.0.0|@oxc-project/types@0.156.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40oxc-project/types@0.156.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d43bb2838f1374935dca1101f179f52f7e9b4fd3efe8652d94a8c7c4ecacf3191a17fad0ab75c913e6c0bab48afc0808cf998616c6fbedc9fd3dbdb4f9609273" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@oxc-project/types" + } + ] + }, + { + "type": "library", + "name": "watcher-android-arm64", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-android-arm64@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-android-arm64@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b6b8292d208a442fe1b858d75ff4a687ed2c59ee3e62d29f92d213a22325e7d821cfbcfeaa41fa90cbcd9d46cbc91b3d375d6df25e2cbd20acd7ee41deb38084" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-android-arm64" + } + ] + }, + { + "type": "library", + "name": "watcher-darwin-arm64", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-darwin-arm64@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-darwin-arm64@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "637415d2097b435cdb7ee7ae9e45881112026c4a234050a0a721bb62a3863452ec7245f2235c6ef66008529298f50058cc1b5290df1d04fc1ddf28803bda2f33" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-darwin-arm64" + } + ] + }, + { + "type": "library", + "name": "watcher-darwin-x64", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-darwin-x64@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-darwin-x64@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3a1bfa3a9ce151f2980fb05e6fc903bc6d236c8c4e442618d4945d667681b678e3909c600fb6552f49f0dac098774c9330a4efcf79e74e7385ddc0e27cafa4bf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-darwin-x64" + } + ] + }, + { + "type": "library", + "name": "watcher-freebsd-x64", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-freebsd-x64@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-freebsd-x64@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e47997bc382cf152beef88c5f72f7fd85137fce9e570a99ce7ab63992ac4b998e94993862fe7ef02ef8728905d3ecf6ec283f6844e939525295d9fc2e6350599" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-freebsd-x64" + } + ] + }, + { + "type": "library", + "name": "watcher-linux-arm-glibc", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-linux-arm-glibc@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-linux-arm-glibc@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3ecfe1ba2dc0faf31b8ddaa5a80a302b664bf3e04ef1d063c5e5978fa9e94c1b378f1e305a66cfa5a2eeab0ad0ad2a8854c0a7a56a36dfc6c9d54dfb1a140e62" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-linux-arm-glibc" + } + ] + }, + { + "type": "library", + "name": "watcher-linux-arm-musl", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-linux-arm-musl@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-linux-arm-musl@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f5ce80507807a06f8863cf0c4481eea73b508909eb6ea1d842390cd9bb40f817ffc109d032e883d167e4d4456fdd394d4f7c78d6e53bd6b9fa138c61ffecef93" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-linux-arm-musl" + } + ] + }, + { + "type": "library", + "name": "watcher-linux-arm64-glibc", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-linux-arm64-glibc@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-linux-arm64-glibc@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c8746a4b6a301177ba1e273dcfa321d440ac09df8e0d5386bd90f2722a91776d7ebfea3e0e75cc3abc39d034a9206dac6fc18f11a3cf99f78201628f25dab8ea" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-linux-arm64-glibc" + } + ] + }, + { + "type": "library", + "name": "watcher-linux-arm64-musl", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-linux-arm64-musl@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-linux-arm64-musl@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5a10767bf57baea7471d666eb0148fbb2e448bc4ba952cfa144e5328a433e61ddad0ef82fa6858eefc54f5bfecb6abcc6fc6de2e73d8f3666b1532cab3e4ab28" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-linux-arm64-musl" + } + ] + }, + { + "type": "library", + "name": "watcher-linux-x64-glibc", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-linux-x64-glibc@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-linux-x64-glibc@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ba5184eb1e8ecfa880c20ef94fc6104a882e0566ac9e221b5fe416a5a60f7029c33a97565f793ee316c460f6552f13aea0923eb2f2493c3dec123f06ee5ad0dc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-linux-x64-glibc" + } + ] + }, + { + "type": "library", + "name": "watcher-linux-x64-musl", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-linux-x64-musl@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-linux-x64-musl@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b640582aded842b8c82566039eda366203bc31192394c4d2368447cec5e29c1a9b2dd78e3372f7db03d926f219c6a68b31f4a54bfe2c5231ffe924d53ff5c32f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-linux-x64-musl" + } + ] + }, + { + "type": "library", + "name": "watcher-win32-arm64", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-win32-arm64@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-win32-arm64@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8086403f6de36878c659ab18fd363ac8becd1c50a57f419aec537e88836f93e28df78ae19bde25619845b1b60535c034e3fa27bc60fd90a9a224b241d876cdc1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-win32-arm64" + } + ] + }, + { + "type": "library", + "name": "watcher-win32-x64", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher-win32-x64@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher-win32-x64@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "700fbfa575766247f1948717390e5f496a80cf33f20fbf3fc79a9b2bf234bd492b9581c0f13233f8c5e301b1a8ba0b8a5522386ce9a44d2275fe9a154ac82df8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher-win32-x64" + } + ] + }, + { + "type": "library", + "name": "watcher", + "group": "@parcel", + "version": "2.6.0", + "bom-ref": "launchpad@1.0.0|@parcel/watcher@2.6.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40parcel/watcher@2.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ec535e365f0d084eda20dc7b59788a42b3d86560bf86fad3b2693ace6c5b23b2d35c4ee155e93f9fc01f560a5edb2f36ce5df0d07bc21cdd1b54a301a09702d3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@parcel/watcher" + } + ] + }, + { + "type": "library", + "name": "binding-android-arm-eabi", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-android-arm-eabi@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-android-arm-eabi@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7be11b7b4593fbdb5b5e634a3c8882f18ad6007630ba0de6ea2e29deb6461ae95f66b8b58ed2381ec953f8e66715ffce207a30585ef50d3947c1704fd92880ec" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-android-arm-eabi" + } + ] + }, + { + "type": "library", + "name": "binding-android-arm64", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-android-arm64@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-android-arm64@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "84ea266eb4c9faccedd9c884cd2ee8080efc94c3c1805e54310582248c8d7e7ac8ec62e5f0762816a0a7a4bda070f39a5ccaabc86094e44c5d40ac830dc0bec8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-android-arm64" + } + ] + }, + { + "type": "library", + "name": "binding-darwin-arm64", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-darwin-arm64@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-darwin-arm64@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5e8300da9c022864d0cd48cf82d47091e747e1699785d20f293ea5ea83b17753d46cda1d188e837017a480dec40bfffec77a5f0585ffa8bd60366640aa2bf0e6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-darwin-arm64" + } + ] + }, + { + "type": "library", + "name": "binding-darwin-x64", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-darwin-x64@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-darwin-x64@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ce8f04b124b0319098fdef9f46719a5f4d981a0bc90f4caf84d8bff61a463c0d8c27d645f1d3c2c3be5419fa48e8ea50fe6c91fdd2189a8811bea8990f44eb5e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-darwin-x64" + } + ] + }, + { + "type": "library", + "name": "binding-freebsd-x64", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-freebsd-x64@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-freebsd-x64@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3bc21200e7c8d678fb02e04f777d05485e3bcfb7fb973964e69a105468228a4bd0b86101158bd6f248be5049d3f9824f9cd1a34339f7d38925b783bd15413b98" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-freebsd-x64" + } + ] + }, + { + "type": "library", + "name": "binding-linux-arm-gnueabihf", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-linux-arm-gnueabihf@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-linux-arm-gnueabihf@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fe56026dae4d3b4caae12d2318c1fc41306d92f431a178e8416cc5e41716a7d32307d8f15510f51900cda1f9158dc3a3df40d6ca12c837fe0e7bad092b368e37" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-linux-arm-gnueabihf" + } + ] + }, + { + "type": "library", + "name": "binding-linux-arm64-gnu", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-linux-arm64-gnu@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-linux-arm64-gnu@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a66fdaa453019d26c56f73ba9c6e691ced62a87859ae31831448d29bea2df49d7b5d73ef1fd2fdd32e61fa381f1c213e41d96cbf2f2a284714e152b18230febc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-linux-arm64-gnu" + } + ] + }, + { + "type": "library", + "name": "binding-linux-arm64-musl", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-linux-arm64-musl@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-linux-arm64-musl@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2b54a6429dc51627219fca2aacd230bc5a19e7072f8c2ee0a01ce968c36f2dff4565cf9007f42f2e69e92598000061e20fdf34b4ff056599d79362bde2bbe5c6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-linux-arm64-musl" + } + ] + }, + { + "type": "library", + "name": "binding-linux-ppc64-gnu", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-linux-ppc64-gnu@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-linux-ppc64-gnu@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "234c700f9ee33ffdc0efee543d98a7db0f18ed71c4984339ceaa5864e710e39325356ead5095338b2995df246beeb2f8bf0c9f11c46c464b02e1aeca734f29e5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-linux-ppc64-gnu" + } + ] + }, + { + "type": "library", + "name": "binding-linux-s390x-gnu", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-linux-s390x-gnu@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-linux-s390x-gnu@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "06bb441d3db848d5e3f47897ab2facfe45e24a2406b7a10a08f525462ac0a088a85712869db5c150491b6404807a2ee2649074fd89e6fb424fd34229c7b0274b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-linux-s390x-gnu" + } + ] + }, + { + "type": "library", + "name": "binding-linux-x64-gnu", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-linux-x64-gnu@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-linux-x64-gnu@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ae6ef9ffd0e41ca794d969c0f30e17f785866202e50c21427e4402fb86e0b952660bf8ef0d1bf607edb02ce621c84d1f56ebfbfff0a4937f4ea0eb9fc82bbbe9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-linux-x64-gnu" + } + ] + }, + { + "type": "library", + "name": "binding-linux-x64-musl", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-linux-x64-musl@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-linux-x64-musl@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8ab87fe3e89814ce06033a65b8312b823cfcf5b8fa343b6aa8c006ffa3b52c6dfc11ddcda7279bcc2a5c54d9055bcba1cbeff7fc1a1c52f9d70d1df709759ef4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-linux-x64-musl" + } + ] + }, + { + "type": "library", + "name": "binding-openharmony-arm64", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-openharmony-arm64@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-openharmony-arm64@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f8a59358da0fb7e09f4aaf780a271e5aedf23c4f90ce4686fa984fcb3f46eb4b6664bc1f424700e007a4b1a7f3bc9030e29be0d6671de5ad53914a95bf4b3824" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-openharmony-arm64" + } + ] + }, + { + "type": "library", + "name": "binding-wasm32-wasi", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-wasm32-wasi@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-wasm32-wasi@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ec41feb243ac979aa95a72b4bf36a68091613afd5cc31429b319bcb48f3cdcaf5fbabe5cdbba7cabcedfcc43ba05b04f69b036ffeb3fcd1eb7fe92dcd77ee23a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-wasm32-wasi" + } + ] + }, + { + "type": "library", + "name": "binding-win32-arm64-msvc", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-win32-arm64-msvc@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-win32-arm64-msvc@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "dd0d5883543bb44bc15a865fe6b16f1bf18a6503e0c1faeefa9e3005a8c37c9141b344870a92fef9d7d38d6f60c8029dd53ed9a4862f75a51ac7b3dafc884555" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-win32-arm64-msvc" + } + ] + }, + { + "type": "library", + "name": "binding-win32-x64-msvc", + "group": "@rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|@rolldown/binding-win32-x64-msvc@1.2.19", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/binding-win32-x64-msvc@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cbfb2a45173a77b8440b33857399f72d27aa72d988a7d98c8d8d4aab8b35e2e2cf77f2d9e33ee2d73ad6e9f32da7698f7ae4080b87ba50b31cc10ccca26a906a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/binding-win32-x64-msvc" + } + ] + }, + { + "type": "library", + "name": "pluginutils", + "group": "@rolldown", + "version": "1.0.1", + "bom-ref": "launchpad@1.0.0|@rolldown/pluginutils@1.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40rolldown/pluginutils@1.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "da3f5b1ade4987c863faf3ed8333ed97bda3d324711c0cae9a8a3a4cd7c08ec2c1d3852da52bcf6cf703701331cfb9fef42601d1cd46c501716118368e29aa1b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@rolldown/pluginutils" + } + ] + }, + { + "type": "library", + "name": "merge-streams", + "group": "@sindresorhus", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|@sindresorhus/merge-streams@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40sindresorhus/merge-streams@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b65a98f71ab9ba4c53519066a0ea7e9bad5cab0403e691c9b45637327f0203ca6ceb28212c7fc7c3c50f76a83838b9855b720595c5e740d9a8fdd87c1f35d821" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@sindresorhus/merge-streams" + } + ] + }, + { + "type": "library", + "name": "eslint-plugin", + "group": "@stylistic", + "version": "5.10.0", + "bom-ref": "launchpad@1.0.0|@stylistic/eslint-plugin@5.10.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40stylistic/eslint-plugin@5.10.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@stylistic/eslint-plugin/-/eslint-plugin-5.10.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9cf2b9d991efa2df09bbfd00e2e7125f575c3d5dbfd5c971d242dc1f9c039ab1389da2aca3b4d40bfbe85325353bd393293ad1e8c622a7a2cfd28804310f633d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@stylistic/eslint-plugin" + } + ] + }, + { + "type": "library", + "name": "svg.draggable.js", + "group": "@svgdotjs", + "version": "3.0.6", + "bom-ref": "launchpad@1.0.0|@svgdotjs/svg.draggable.js@3.0.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40svgdotjs/svg.draggable.js@3.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@svgdotjs/svg.draggable.js/-/svg.draggable.js-3.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ee22459bd94bdc2e341d072acc47deccada5f9d5b60a9a156376fbeca406a9cf065d66ba2e18665f90a4bfb6a541f51706e65b8e920267e0efab5733946c7b80" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@svgdotjs/svg.draggable.js" + } + ] + }, + { + "type": "library", + "name": "svg.filter.js", + "group": "@svgdotjs", + "version": "3.0.9", + "bom-ref": "launchpad@1.0.0|@svgdotjs/svg.filter.js@3.0.9", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40svgdotjs/svg.filter.js@3.0.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@svgdotjs/svg.filter.js/-/svg.filter.js-3.0.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ffaf57311083a1a9b61e00b895d1c868381e41fd5588722c6b42dde2e5a0897b59f84db80d61deffd21bea46cd899ed64487655689140d1d4583492322991f6f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@svgdotjs/svg.filter.js" + } + ] + }, + { + "type": "library", + "name": "svg.js", + "group": "@svgdotjs", + "version": "3.2.8", + "bom-ref": "launchpad@1.0.0|@svgdotjs/svg.js@3.2.8", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40svgdotjs/svg.js@3.2.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@svgdotjs/svg.js/-/svg.js-3.2.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "35475b23fec50dda86a732a6aabd3d210a32f4c51cac00bfddb0bc80b8178ba39f26ecab8b8e74ccc2ef25e905521baade237982974f8e84a84ad365f448a37e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@svgdotjs/svg.js" + } + ] + }, + { + "type": "library", + "name": "svg.resize.js", + "group": "@svgdotjs", + "version": "2.0.5", + "bom-ref": "launchpad@1.0.0|@svgdotjs/svg.resize.js@2.0.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40svgdotjs/svg.resize.js@2.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@svgdotjs/svg.resize.js/-/svg.resize.js-2.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e217915b807542b25e10d7e2ef7dba9543d80427af8fbf0526cf247de0f19f9b2dd0860f2115e84ed39262f4f315681a5965dddd808313a6a8e1f9aff7546d84" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@svgdotjs/svg.resize.js" + } + ] + }, + { + "type": "library", + "name": "svg.select.js", + "group": "@svgdotjs", + "version": "4.0.3", + "bom-ref": "launchpad@1.0.0|@svgdotjs/svg.select.js@4.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40svgdotjs/svg.select.js@4.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@svgdotjs/svg.select.js/-/svg.select.js-4.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "aa4320b28d6c77685729dd45675c1e3bb00dab5dac3664097860e3b38e90c0356cc5245c1e6bd628bd8d0c5ed88a6a707f7b25e5eb0e2e43eab55d9b437bff26" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@svgdotjs/svg.select.js" + } + ] + }, + { + "type": "library", + "name": "editor", + "group": "@toast-ui", + "version": "3.2.2", + "bom-ref": "launchpad@1.0.0|@toast-ui/editor@3.2.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40toast-ui/editor@3.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@toast-ui/editor/-/editor-3.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0125fb2c58cdd9961026bc269146a33ecec346bf45b0cd7e450f3609f4ced18e595e8ac19355594b80b60e9c629f1f64979e55e05f3f036876405e10303b516c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@toast-ui/editor" + } + ] + }, + { + "type": "library", + "name": "token", + "group": "@tokenizer", + "version": "0.3.0", + "bom-ref": "launchpad@1.0.0|@tokenizer/token@0.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40tokenizer/token@0.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3af8c5fb3e752f7a2fd0ec8053476ecec62ebced353c7ef1e2de83271fa0b9a8604e704792125d1bbb2841e4d214b58ddde7e71f289b67867c97612e5b024ddc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@tokenizer/token" + } + ] + }, + { + "type": "library", + "name": "wasm-util", + "group": "@tybys", + "version": "0.10.4", + "bom-ref": "launchpad@1.0.0|@tybys/wasm-util@0.10.4", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40tybys/wasm-util@0.10.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5b77388118a0152d13fcc6b8a88605dc60c07390107476f5c8be739c94f566fd58683f4a8adc7ae7ac018efaf5f6a6e2a2c9994fc9560cce4110cca752a5fae4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@tybys/wasm-util" + } + ] + }, + { + "type": "library", + "name": "debug", + "group": "@types", + "version": "4.1.13", + "bom-ref": "launchpad@1.0.0|@types/debug@4.1.13", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/debug@4.1.13", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2925609909b33303e59ad9633a899aca847cf56e05ca70808b713c3cfb3bbe60d53def38853faf18f2a425f4e19265ecd31d2301a6bd53cb96f1b6dfc92d9f5b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/debug" + } + ] + }, + { + "type": "library", + "name": "escape-html", + "group": "@types", + "version": "1.0.4", + "bom-ref": "launchpad@1.0.0|@types/escape-html@1.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/escape-html@1.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/escape-html/-/escape-html-1.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a99ef64854e05006796bb4e3ea47f64872deb621f94ba7fc1b97eb07648f437132174da4c5dc8115fe13cf86da9c4df10a01a72a058bb7ffdae95b981ca6094e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/escape-html" + } + ] + }, + { + "type": "library", + "name": "esrecurse", + "group": "@types", + "version": "4.3.1", + "bom-ref": "launchpad@1.0.0|@types/esrecurse@4.3.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/esrecurse@4.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c490406c389fa398697df0c1b8797463ccb0b306e2029fd68bb63f1ad0204a5672200069a72babc55b9e38f13c2d440ec5d9608ba66a71eeeea04a6a3537a253" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/esrecurse" + } + ] + }, + { + "type": "library", + "name": "estree-jsx", + "group": "@types", + "version": "1.0.5", + "bom-ref": "launchpad@1.0.0|@types/estree-jsx@1.0.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/estree-jsx@1.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e7609c515345c9f6f503600ba1c430fc377505014d992764b82dc1919ea2aa174c7d0cfb25638546e2459683b38e4fba5a28d4e7a9bda0a5c501773ba374e8c2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/estree-jsx" + } + ] + }, + { + "type": "library", + "name": "estree", + "group": "@types", + "version": "1.0.9", + "bom-ref": "launchpad@1.0.0|@types/estree@1.0.9", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/estree@1.0.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1a174f832d5e978fc898fd395f4e54c38730dbf33ddc10949a712f599352b650b310a304e05924f98a680393a21cd426a12ec269f6fc5dadcfc9af26d50af37a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/estree" + } + ] + }, + { + "type": "library", + "name": "hast", + "group": "@types", + "version": "3.0.5", + "bom-ref": "launchpad@1.0.0|@types/hast@3.0.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/hast@3.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ae9fdecd259a0f59b8e1d3ca2021a18ac908d779d5afba939681700dafc86248617f99f3c0ffb3210708261dd62054813b2fc7d4fcc1e348cf8cc0e4b0de05fa" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/hast" + } + ] + }, + { + "type": "library", + "name": "jquery", + "group": "@types", + "version": "3.5.16", + "bom-ref": "launchpad@1.0.0|@types/jquery@3.5.16", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/jquery@3.5.16", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/jquery/-/jquery-3.5.16.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6ec23bcb866078c926a46f4e33bd74451cc3169fb0e0fd511a222ddf40b5992053f84c4295e7a1e0739bc2002b9c31442e646b3a95e049837d545d618fe7f597" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/jquery" + } + ] + }, + { + "type": "library", + "name": "json-schema", + "group": "@types", + "version": "7.0.15", + "bom-ref": "launchpad@1.0.0|@types/json-schema@7.0.15", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/json-schema@7.0.15", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e7e7cff0ff0c14d0be0326420f1ac1da991914f1b3a90594ce949ebae54bbe6f1531ca2b3586af06aa057312bc6d0cf842c6e7e2850411e9b8c032df732b061c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/json-schema" + } + ] + }, + { + "type": "library", + "name": "mdast", + "group": "@types", + "version": "4.0.4", + "bom-ref": "launchpad@1.0.0|@types/mdast@4.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/mdast@4.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "90668d6cf87593b005ce0a6e77f80c76f226e71b840b291147e26758a427a3d4c05d56ba5885421933ef6067a42032f8bb009941261b53134149bd5a528efda0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/mdast" + } + ] + }, + { + "type": "library", + "name": "ms", + "group": "@types", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|@types/ms@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/ms@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1ac0822190c4fe9de2f7abed12ac7eedd054197adcef37922b7c303c721a453852fbd3a15885d1ab3b3877a93549553c83dd43acd456c56506869e4a5d06f654" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/ms" + } + ] + }, + { + "type": "library", + "name": "node", + "group": "@types", + "version": "26.4.0", + "bom-ref": "launchpad@1.0.0|@types/node@26.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/node@26.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7da8869e822b2c7fd5f1c89b38c10067ca4cc3aa17a92ba4976f6b6b898df0675a07665ec3379a2e3f8836957937e67578a5b363e233688647d84211e9865135" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/node" + } + ] + }, + { + "type": "library", + "name": "semver", + "group": "@types", + "version": "7.8.0", + "bom-ref": "launchpad@1.0.0|@types/semver@7.8.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/semver@7.8.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d66008363b500975de2e427d7a15e4c0e701a6ab4bc6256d2a1a547fcdc375135d40a57489766968762a46bee78fec2fc6e273a00980c1723eb0234cbf50b32d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/semver" + } + ] + }, + { + "type": "library", + "name": "sizzle", + "group": "@types", + "version": "2.3.10", + "bom-ref": "launchpad@1.0.0|@types/sizzle@2.3.10", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/sizzle@2.3.10", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.10.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4c2d1d98dd0af1871610011f88f8b98093f5e1e25edf44d31a392f7a4de233fd4d7471ec74203f4dde86bcd9dd30ea3f8929c8b19e07bae86b60f0c099bc73c3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/sizzle" + } + ] + }, + { + "type": "library", + "name": "toastify-js", + "group": "@types", + "version": "1.12.4", + "bom-ref": "launchpad@1.0.0|@types/toastify-js@1.12.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/toastify-js@1.12.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/toastify-js/-/toastify-js-1.12.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cdf647538b4a7df3c29d945eee98effde14acd3547a3329ec0508a6828d9e201629ca809473fedd1b91988c0972713e1bff66878318d39e443d3d47491067f9f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/toastify-js" + } + ] + }, + { + "type": "library", + "name": "trusted-types", + "group": "@types", + "version": "2.0.7", + "bom-ref": "launchpad@1.0.0|@types/trusted-types@2.0.7", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/trusted-types@2.0.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "49c68f767d5d41cce06e5d101537933a65471542eddfde17260390368c95859eabdaf2e730b25f04f779dd2079d93ff71b7e95235fe0d8c65a5f47300ee5ec7f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/trusted-types" + } + ] + }, + { + "type": "library", + "name": "unist", + "group": "@types", + "version": "3.0.3", + "bom-ref": "launchpad@1.0.0|@types/unist@3.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/unist@3.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "928fe0205251bf5efb5e066c65c0709ea24de71fc689e9fca8d3a7d03e5b414ff303355ff59b7706571488baa157dcb801193419b4f7b675223cd8274d7cdcfd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/unist" + } + ] + }, + { + "type": "library", + "name": "web-bluetooth", + "group": "@types", + "version": "0.0.21", + "bom-ref": "launchpad@1.0.0|@types/web-bluetooth@0.0.21", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/web-bluetooth@0.0.21", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a0840b0865ad705672d895bbee3f64f271f300ea6a3072d07a30c0e3c5d73161fab630901f3e51085cf56f3b2644ec8be8f526f8b2e75222380429f6db58a7c4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@types/web-bluetooth" + } + ] + }, + { + "type": "library", + "name": "parser", + "group": "@typescript-eslint", + "version": "8.73.0", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40typescript-eslint/parser@8.73.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.73.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "02e2f8e5b55c9acb077d9dc38b772cf50d25e20066e19155ac9390104ed5a6a5be3d5810684c12c1acf3e1354888569b5e493a539d44a6b603c2ac3e1d1f1e3f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser" + } + ], + "components": [ + { + "type": "library", + "name": "scope-manager", + "group": "@typescript-eslint", + "version": "8.73.0", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|@typescript-eslint/scope-manager@8.73.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40typescript-eslint/scope-manager@8.73.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.73.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fd38c3ef7f08ab6af38f9cf48b154e8be4ecbe08c0cd93cb3da1f5c96743072b51fc74d1e60329c985997827b95934192f0937868f0057b5379aea10091b5705" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/scope-manager" + } + ] + }, + { + "type": "library", + "name": "types", + "group": "@typescript-eslint", + "version": "8.73.0", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|@typescript-eslint/types@8.73.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40typescript-eslint/types@8.73.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.73.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3bfd72b58cdf945d7a403297c78fea39783522e669fa7ee1afdb7e4b49efecdff64e5f2b262342b21ced57581c494bc76cfb685f7fb398d6ed480c956f3c557f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/types" + } + ] + }, + { + "type": "library", + "name": "typescript-estree", + "group": "@typescript-eslint", + "version": "8.73.0", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|@typescript-eslint/typescript-estree@8.73.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40typescript-eslint/typescript-estree@8.73.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.73.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2278e506449d59c788c080564b04b710d529fa2d0ed363c65f766fdb09e2856242d560d51af1bb9931ee7fc6f9eee01a2138fde1dead44f0c7fac504b5775141" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/typescript-estree" + } + ] + }, + { + "type": "library", + "name": "visitor-keys", + "group": "@typescript-eslint", + "version": "8.73.0", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|@typescript-eslint/visitor-keys@8.73.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40typescript-eslint/visitor-keys@8.73.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.73.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "93896c155a5164809b96d9081041f8859464c1792a0c5d461c1a4294a40e1d063e464a19000bb2735722dc8ea9f8207abf75388da1c852c85ce11cf34176562e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/visitor-keys" + } + ] + }, + { + "type": "library", + "name": "project-service", + "group": "@typescript-eslint", + "version": "8.73.0", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|@typescript-eslint/project-service@8.73.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40typescript-eslint/project-service@8.73.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.73.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fe911ff1173832393ea899d8d2e3b5f8669d79a97cbafe74c69ba273eb2b1b6bc855ab40d17c6f58c51e32d16fb3a3821ea7ed890efffaa1f869e846e6cb7320" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/project-service" + } + ] + }, + { + "type": "library", + "name": "tsconfig-utils", + "group": "@typescript-eslint", + "version": "8.73.0", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|@typescript-eslint/tsconfig-utils@8.73.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40typescript-eslint/tsconfig-utils@8.73.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.73.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "966b4214e7d86897e9a99cb01ae5e2e05a4db44f8d43e60b7b74f42bdaed103716f19b865af7c8fbea63f2bd39b18308f2f593d8260ae2b5b279d983e91a78a2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/@typescript-eslint/tsconfig-utils" + } + ] + }, + { + "type": "library", + "name": "minimatch", + "version": "11.0.9", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|minimatch@11.0.9", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0" + } + } + ], + "purl": "pkg:npm/minimatch@11.0.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2821647f28ea7ab3654acb6396120635720a64603fe8ee15e1196167e0ecafadb548f3f0d26ce5ca913d0fd64ea0f89579f1c80fe8fbfd7b8c325a9f0ff17ad1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/minimatch" + } + ] + }, + { + "type": "library", + "name": "semver", + "version": "7.8.6", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|semver@7.8.6", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/semver@7.8.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f65a52494e0c972de6aedaeec0bb3578b2bafa0cdbcea78117044d8c88c4fbd2ee0e959d61cb6b4254377a3d489608bb8249e9b134673e82cff03a421ea1c827" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/semver" + } + ] + }, + { + "type": "library", + "name": "eslint-visitor-keys", + "version": "5.0.1", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/parser@8.73.0|eslint-visitor-keys@5.0.1", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/eslint-visitor-keys@5.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b43e34787c40df98743c421935e223907a034786238c9a77e1b88cd260efa6505efff981f881c2a870c657ba7117eecc9254ef8a085c08f3d90bbca75b28dd4c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/parser/node_modules/eslint-visitor-keys" + } + ] + } + ] + }, + { + "type": "library", + "name": "types", + "group": "@typescript-eslint", + "version": "8.68.0", + "bom-ref": "launchpad@1.0.0|@typescript-eslint/types@8.68.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40typescript-eslint/types@8.68.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.68.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f519e9b06263ac096508c79f19556c22624cdb862eae10b443587851bbe2bedbcea97991fef10981ed8ea04fbecfd9ba87283c4f543cb7948d4fab4749baf172" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/@typescript-eslint/types" + } + ] + }, + { + "type": "library", + "name": "codemirror-theme-github", + "group": "@uiw", + "version": "4.25.11", + "bom-ref": "launchpad@1.0.0|@uiw/codemirror-theme-github@4.25.11", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40uiw/codemirror-theme-github@4.25.11", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@uiw/codemirror-theme-github/-/codemirror-theme-github-4.25.11.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "decd0b2b7817da6bc623df7acf71b4b441d9aac85b789465cbe40c46c286008d537ebd55e3be5b7da5bd36f9e80dd20db901edf9107eae2eaae7bf96585f1df8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@uiw/codemirror-theme-github" + } + ] + }, + { + "type": "library", + "name": "codemirror-themes", + "group": "@uiw", + "version": "4.25.11", + "bom-ref": "launchpad@1.0.0|@uiw/codemirror-themes@4.25.11", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40uiw/codemirror-themes@4.25.11", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@uiw/codemirror-themes/-/codemirror-themes-4.25.11.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4813423a046c0ad7b018da1c45b9a36c2925b465e515c3c9b2f871437e755729d08e759488f6d4ac570453f85a4371da9d139d0008d65d924f9396cc0719768f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@uiw/codemirror-themes" + } + ] + }, + { + "type": "library", + "name": "structured-clone", + "group": "@ungap", + "version": "1.4.0", + "bom-ref": "launchpad@1.0.0|@ungap/structured-clone@1.4.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/%40ungap/structured-clone@1.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d66119b4c28f334f6f0e642de72ed8be6376f831533fb4e0d0459776273cfc2e95467a5bdf77b88218ac0881375998ec13637c99ff9057566a87b64560b5889d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@ungap/structured-clone" + } + ] + }, + { + "type": "library", + "name": "background", + "group": "@vue-flow", + "version": "1.3.2", + "bom-ref": "launchpad@1.0.0|@vue-flow/background@1.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue-flow/background@1.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue-flow/background/-/background-1.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7893e10dc2e3d70128e396c1a2a4d7c35ba1974c8ad916901a710836abef06c0052a1fdc6a61c977934f98e752d70f8cf6582073d8a051ec31684777882417db" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue-flow/background" + } + ] + }, + { + "type": "library", + "name": "core", + "group": "@vue-flow", + "version": "1.48.2", + "bom-ref": "launchpad@1.0.0|@vue-flow/core@1.48.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue-flow/core@1.48.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue-flow/core/-/core-1.48.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "adac6180a584f86fe6704bd7263185503616f6b008dc63ad887477664369c015ae21a082d44622066286c093a83735458303bb08e804ae72bb8b4f22dbcec014" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue-flow/core" + } + ] + }, + { + "type": "library", + "name": "minimap", + "group": "@vue-flow", + "version": "1.5.4", + "bom-ref": "launchpad@1.0.0|@vue-flow/minimap@1.5.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue-flow/minimap@1.5.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue-flow/minimap/-/minimap-1.5.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9780be5d30179d1c6c46951d37b70054505e9e70b5b15473ab86c34a954af9a83bb5d31ccc09e11581a06cb914c37bf7b18ea0a24c96c0c97c083a27a7c781da" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue-flow/minimap" + } + ] + }, + { + "type": "library", + "name": "node-resizer", + "group": "@vue-flow", + "version": "1.5.1", + "bom-ref": "launchpad@1.0.0|@vue-flow/node-resizer@1.5.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue-flow/node-resizer@1.5.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue-flow/node-resizer/-/node-resizer-1.5.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0cd6205d3177f465cf0328153059a09f96b3805ced6967ea6d6beff03fd7d071a07ae9d1adec49d16f780f25c7d6b9e7746c98009d0a7b1123c9e96c6fe3656e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue-flow/node-resizer" + } + ] + }, + { + "type": "library", + "name": "common", + "group": "@vue-macros", + "version": "3.1.4", + "bom-ref": "launchpad@1.0.0|@vue-macros/common@3.1.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue-macros/common@3.1.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue-macros/common/-/common-3.1.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ff916ffba0e021c33d6a3634e5998a06ff8b317d4cf40d17f885300d155db7aedc8b0f0e57d6ef1b6af7e29dd188469d96c4326e384a3d128d5c30bc069db773" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue-macros/common" + } + ], + "components": [ + { + "type": "library", + "name": "local-pkg", + "version": "1.2.1", + "bom-ref": "launchpad@1.0.0|@vue-macros/common@3.1.4|local-pkg@1.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/local-pkg@1.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fbe814a910c4bdc9cde9986aaebfb2fc2915107865ad1f7abd99f79d964f63331c054c81b532b307d35a74294522c2154acbbede2f6d7e4fdeaeacbd9009aded" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue-macros/common/node_modules/local-pkg" + } + ] + }, + { + "type": "library", + "name": "quansync", + "version": "0.2.11", + "bom-ref": "launchpad@1.0.0|@vue-macros/common@3.1.4|quansync@0.2.11", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/quansync@0.2.11", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0227d3ed011b5bd36b8b8b40c11e4cfeece906ea9f65ffb3c1a10cfd09331238fb341b850f6ac1bb2d0addd13ef3096d6decc357b24c03459f9c23d845261b5c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue-macros/common/node_modules/quansync" + } + ] + } + ] + }, + { + "type": "library", + "name": "compiler-core", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/compiler-core@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/compiler-core@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5c61c9acceae7d901101cff0fadc8eb304adc3db5d2a2a8228149c23880668dc43f9a686bbf1d05a0289f8922d8d12cfa9e9d0ee213b1bc0090bb4f97b0d69fa" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-core" + } + ], + "components": [ + { + "type": "library", + "name": "parser", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|@vue/compiler-core@3.5.45|@babel/parser@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/parser@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "54bdb6d2f5eec8edb3deb34843063b7ed8fd530a6a3adfb7dec1feb015a439e91bb1247683b1043273b1db8665087d31380dc333fdf74a27d51466e7243f2bff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-core/node_modules/@babel/parser" + } + ] + }, + { + "type": "library", + "name": "types", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|@vue/compiler-core@3.5.45|@babel/types@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/types@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "52323f74a9b02704fda4eb33262b6ad86e8439b64f9ec6547dd0abf76cf64e51771192bd27711d7ce294ac2cc797ac05b616f3c21ce5d52a1cfd4230c518aaeb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-core/node_modules/@babel/types" + } + ] + }, + { + "type": "library", + "name": "helper-string-parser", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|@vue/compiler-core@3.5.45|@babel/helper-string-parser@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-string-parser@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "097bca305bccf348a123b568c7d8dbfa44239f28c449034f33ebc1ed4d19cfa4d6b9903e67f14bd103cc1f7d34877dea26d231f9111e0615ea58e3d6e3c4dc01" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-core/node_modules/@babel/helper-string-parser" + } + ] + }, + { + "type": "library", + "name": "helper-validator-identifier", + "group": "@babel", + "version": "7.29.7", + "bom-ref": "launchpad@1.0.0|@vue/compiler-core@3.5.45|@babel/helper-validator-identifier@7.29.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-validator-identifier@7.29.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a9e8711a4463e7987f7dff0431a27e71887268a947231a980e7ebcdb0403ed1369f54ba3390b07a20dae4b4af6bf3af8a56fac5dff7435e79aca370d697ddf16" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-core/node_modules/@babel/helper-validator-identifier" + } + ] + } + ] + }, + { + "type": "library", + "name": "compiler-dom", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/compiler-dom@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/compiler-dom@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2db3f6775f4648e6063e6bcc04109525596fed32ad8ccd427decaeddc6226bbdb4a649d93fed5c2d7ec7e4c55ab6faee4fa32e26188fb8d6d0056fcc0e7fc4c0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-dom" + } + ] + }, + { + "type": "library", + "name": "compiler-sfc", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/compiler-sfc@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/compiler-sfc@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "30a1636f6517d0cfe5fe385fcea30bac8f15338a5fbc5286de9a8566449914744bb4d95dfcee11b543d91564b086ba3fd78a8ff3c5101245b31f1019010d2db3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-sfc" + } + ], + "components": [ + { + "type": "library", + "name": "parser", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|@vue/compiler-sfc@3.5.45|@babel/parser@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/parser@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "54bdb6d2f5eec8edb3deb34843063b7ed8fd530a6a3adfb7dec1feb015a439e91bb1247683b1043273b1db8665087d31380dc333fdf74a27d51466e7243f2bff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-sfc/node_modules/@babel/parser" + } + ] + }, + { + "type": "library", + "name": "types", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|@vue/compiler-sfc@3.5.45|@babel/types@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/types@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "52323f74a9b02704fda4eb33262b6ad86e8439b64f9ec6547dd0abf76cf64e51771192bd27711d7ce294ac2cc797ac05b616f3c21ce5d52a1cfd4230c518aaeb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-sfc/node_modules/@babel/types" + } + ] + }, + { + "type": "library", + "name": "helper-string-parser", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|@vue/compiler-sfc@3.5.45|@babel/helper-string-parser@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-string-parser@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "097bca305bccf348a123b568c7d8dbfa44239f28c449034f33ebc1ed4d19cfa4d6b9903e67f14bd103cc1f7d34877dea26d231f9111e0615ea58e3d6e3c4dc01" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-sfc/node_modules/@babel/helper-string-parser" + } + ] + }, + { + "type": "library", + "name": "helper-validator-identifier", + "group": "@babel", + "version": "7.29.7", + "bom-ref": "launchpad@1.0.0|@vue/compiler-sfc@3.5.45|@babel/helper-validator-identifier@7.29.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-validator-identifier@7.29.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a9e8711a4463e7987f7dff0431a27e71887268a947231a980e7ebcdb0403ed1369f54ba3390b07a20dae4b4af6bf3af8a56fac5dff7435e79aca370d697ddf16" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-sfc/node_modules/@babel/helper-validator-identifier" + } + ] + } + ] + }, + { + "type": "library", + "name": "compiler-ssr", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/compiler-ssr@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/compiler-ssr@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "445e6c6d939f633e402b4d2d389527d8fc055d1d9f4b5bb61d5cc8f03f5517dac6005c6e181aa0d9b075909dd91cca6ba9296d5e74fd31913522caa348cf287b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/compiler-ssr" + } + ] + }, + { + "type": "library", + "name": "devtools-api", + "group": "@vue", + "version": "8.2.1", + "bom-ref": "launchpad@1.0.0|@vue/devtools-api@8.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/devtools-api@8.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-8.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "eaee2f5c19480400b5c0ca65219829c8f9fbba1fece017fa1796cccef2eff84749d1a1ecffee01ed882ff3ae044ad4128d16ec4734e4a3f9141b503521e8d0dc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/devtools-api" + } + ] + }, + { + "type": "library", + "name": "devtools-kit", + "group": "@vue", + "version": "8.2.1", + "bom-ref": "launchpad@1.0.0|@vue/devtools-kit@8.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/devtools-kit@8.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-8.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "148188baadc0591784a5b00763f71119e1c37c8d2a39bf0e090dd88db1005f4e2e6b12036c673dae191b55c1bbae77c73d713746c5392ab58ebbd57fa2477c01" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/devtools-kit" + } + ] + }, + { + "type": "library", + "name": "devtools-shared", + "group": "@vue", + "version": "8.2.1", + "bom-ref": "launchpad@1.0.0|@vue/devtools-shared@8.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/devtools-shared@8.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-8.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "16469cee551d1917a1ea954e8b70183d119ef362d0a919807d3856ed14658a03803f4640fd9d73f572c70ccf5dbf7e295761d173bf432bcb8a3de1b67cb9c0fe" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/devtools-shared" + } + ] + }, + { + "type": "library", + "name": "reactivity", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/reactivity@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/reactivity@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5aa932b9b356a48e0e6013a2a52ae322cb0c7493bc2b58bd66db3f5a6f04af5d3fd26b0e1300b25965af667008ed65b7910b13a2783a0c9a7c09b6febdde1c3c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/reactivity" + } + ] + }, + { + "type": "library", + "name": "runtime-core", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/runtime-core@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/runtime-core@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6f320edfe140063a63f39b8829273e4278f7ebfb310cd237b5c1fd8bac3ac4a03593a7b47a3bf41b48cc09f78906f2b7c862f95db2770cc663f8296ac821c563" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/runtime-core" + } + ] + }, + { + "type": "library", + "name": "runtime-dom", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/runtime-dom@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/runtime-dom@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "66f45314c0e07ea4c3616bc97e8569413271d5137933a97b3f277ac1f758d8d697cdb3d0561f5ecde41815b34f3fa6c8711567d92a92491db937f8d25baf4117" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/runtime-dom" + } + ] + }, + { + "type": "library", + "name": "server-renderer", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/server-renderer@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/server-renderer@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d5f357507861b167f81152f85e2c5b18153998a76221724007cd9f787453c8f3e8e99504616209b8479497799557a403069e741c9397e286cb87161796b8ebcc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/server-renderer" + } + ] + }, + { + "type": "library", + "name": "shared", + "group": "@vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|@vue/shared@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/shared@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b9ef5f80799534f94fee25b7f9cc68057fc29e5c39ddd1e5552c3424a198eb3d6539b83ca47a23f76f0cda7cc6e3fc95b0c67735a459dacdb3eb5b82d7a343c1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vue/shared" + } + ] + }, + { + "type": "library", + "name": "vue-datepicker", + "group": "@vuepic", + "version": "11.0.3", + "bom-ref": "launchpad@1.0.0|@vuepic/vue-datepicker@11.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vuepic/vue-datepicker@11.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vuepic/vue-datepicker/-/vue-datepicker-11.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b1bd9a770ab02b63e2ccb40ea71098a6cd92c21553ebf89cd873083aa1c95ee61aea200965618be585654bb3b8696fac93a672c650d444b3bb90364f2f81c1ff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vuepic/vue-datepicker" + } + ] + }, + { + "type": "library", + "name": "components", + "group": "@vueuse", + "version": "15.0.0", + "bom-ref": "launchpad@1.0.0|@vueuse/components@15.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vueuse/components@15.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vueuse/components/-/components-15.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "817e8513da1579ff8750a85f531f4e4f127e5c61630c4322e69f98ecfaf6818831ba64a77ec7c0fc9d018282341932bac7fc7422ef0061b97528cdb0e20fd3da" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vueuse/components" + } + ] + }, + { + "type": "library", + "name": "core", + "group": "@vueuse", + "version": "14.4.0", + "bom-ref": "launchpad@1.0.0|@vueuse/core@14.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vueuse/core@14.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vueuse/core/-/core-14.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5f8587cf51e50b3081a185deb149227f3cd60407198171bc162e6234f420fdea5dcce07782ef056b08f786fbb0611d6719c5c69efc706187140bfef5fbeb2fb5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vueuse/core" + } + ] + }, + { + "type": "library", + "name": "metadata", + "group": "@vueuse", + "version": "14.4.0", + "bom-ref": "launchpad@1.0.0|@vueuse/metadata@14.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vueuse/metadata@14.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b30c7fdb9e51e89c87645261c7ce398b3e424560d97427ef9193a900259ce7e739587706db89aff20513d5621d150687b7a76aefdaef20b77d4270968b2566f6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vueuse/metadata" + } + ] + }, + { + "type": "library", + "name": "shared", + "group": "@vueuse", + "version": "14.4.0", + "bom-ref": "launchpad@1.0.0|@vueuse/shared@14.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vueuse/shared@14.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "251818f744b3f030ed3ccb1a0df96f3cca7dc5893af4964099bb83bc0aae5155caaf68048eab7318d4d3b612df7241f407306abe7bb7d606f86bc4c62d17bbf6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@vueuse/shared" + } + ] + }, + { + "type": "library", + "name": "ast", + "group": "@webassemblyjs", + "version": "1.14.1", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/ast@1.14.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/ast@1.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9ee0440e041f9b571c469ffc6c242bc757eba21cae7e5e0995b30c6783f5c2978e7c3845e85424c592756ff7be3cbc2be97d4d870e8e2e67b9bacb8159806fb9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/ast" + } + ] + }, + { + "type": "library", + "name": "floating-point-hex-parser", + "group": "@webassemblyjs", + "version": "1.13.2", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/floating-point-hex-parser@1.13.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/floating-point-hex-parser@1.13.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ea85f24cecdb2b1187e2cb5e2db2cd3aeef53a3f82f0b837e27e82a91bea7d2d8eef507163a0727cc0d1841cadce49e3f721943d5275a882a14650303b5028bc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/floating-point-hex-parser" + } + ] + }, + { + "type": "library", + "name": "helper-api-error", + "group": "@webassemblyjs", + "version": "1.13.2", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/helper-api-error@1.13.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/helper-api-error@1.13.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "539e86318c72e194026c365de89bafbcd57f5858a574e8ec6960f74f3cef9b0fe66acddc5f34493cc8cff3726a12c8126f2ae66868c17c3b55eca0d757d53315" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/helper-api-error" + } + ] + }, + { + "type": "library", + "name": "helper-buffer", + "group": "@webassemblyjs", + "version": "1.14.1", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/helper-buffer@1.14.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/helper-buffer@1.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8f21fbc2d70788ab2c0ed14f441fa241dc650dff7a9b4137f726f4939b8956114695e645a0dc3573869e21c5543cf6d751527de30c2730e02a507cb3a043d530" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/helper-buffer" + } + ] + }, + { + "type": "library", + "name": "helper-numbers", + "group": "@webassemblyjs", + "version": "1.13.2", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/helper-numbers@1.13.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/helper-numbers@1.13.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "144f1a0a64b943a79061c577808df93b827bf3dc25400fbb26ba934e926a9f97a603853686fc099af1510b41ce0d2fb761ee968a80e496077ab1c277f8f2e710" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/helper-numbers" + } + ] + }, + { + "type": "library", + "name": "helper-wasm-bytecode", + "group": "@webassemblyjs", + "version": "1.13.2", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/helper-wasm-bytecode@1.13.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/helper-wasm-bytecode@1.13.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "dd06cb2b2f771741002172e1d28804551eab3ae6c0f40a19f9645884d6c5cae07bd23ddd45dc07f60faa5e12c03b4922606960dd3c4357e238ad04ebfd835790" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/helper-wasm-bytecode" + } + ] + }, + { + "type": "library", + "name": "helper-wasm-section", + "group": "@webassemblyjs", + "version": "1.14.1", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/helper-wasm-section@1.14.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/helper-wasm-section@1.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "76ce665c4a9327aa31468aa38560d4f373a0cc0623c2c095f0ba3f37ea11b0d0e6c7f643a6a6a59abb6038c907c31b06d2223fff707058012b6111ed827d1d67" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/helper-wasm-section" + } + ] + }, + { + "type": "library", + "name": "ieee754", + "group": "@webassemblyjs", + "version": "1.13.2", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/ieee754@1.13.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/ieee754@1.13.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e0bb4ece1e7c4bfe655f82132b19c02b6512b8d12fa5d555f409601906fcac90c768b787722c06e33946af48ff48d5a5afbc77bced650c4b2e78fbed70334293" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/ieee754" + } + ] + }, + { + "type": "library", + "name": "leb128", + "group": "@webassemblyjs", + "version": "1.13.2", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/leb128@1.13.2", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/leb128@1.13.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2dd7b5a0da08773573764344016675759e68ac86df7fcd183dd1f1db49ab1f01eb54d3538cdafc137c73f41769706a9141b0046be7e4ac26fe7d115397feac43" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/leb128" + } + ] + }, + { + "type": "library", + "name": "utf8", + "group": "@webassemblyjs", + "version": "1.13.2", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/utf8@1.13.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/utf8@1.13.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "dcd4161a3293012635c55e66ec7af488f7970fdf910e86cb965dd3f5dd803be8379b2f31cb9a5e5728d26a0e08e74991d5b05237f0add76968f91f6d264d0d65" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/utf8" + } + ] + }, + { + "type": "library", + "name": "wasm-edit", + "group": "@webassemblyjs", + "version": "1.14.1", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/wasm-edit@1.14.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/wasm-edit@1.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "44d2542101ff27c880ff5373944e0decab7264d1e2df0edab7b8438ef44d9b9adc5176b4d33d6f473de0959a142df2799a9bd884bc9b9957307231ab0b5a51ad" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/wasm-edit" + } + ] + }, + { + "type": "library", + "name": "wasm-gen", + "group": "@webassemblyjs", + "version": "1.14.1", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/wasm-gen@1.14.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/wasm-gen@1.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "026a264888cff196df19086e9a436f802df7018eeab4c0979cde9b2f6bb626ce2054283c7e9ef7e5a12231205b0d1ed44088fdd27e3028015448477440dd9492" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/wasm-gen" + } + ] + }, + { + "type": "library", + "name": "wasm-opt", + "group": "@webassemblyjs", + "version": "1.14.1", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/wasm-opt@1.14.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/wasm-opt@1.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3d370a2d436f06a9d8d94e84e5b74e41c48cfa854ffcf9ab0d8f4dce8c098e2b25123c0ffc2e1a9f6df4dcc0954b6320f5ddc026920675414841059b3ddb344b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/wasm-opt" + } + ] + }, + { + "type": "library", + "name": "wasm-parser", + "group": "@webassemblyjs", + "version": "1.14.1", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/wasm-parser@1.14.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/wasm-parser@1.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "24b065f8a674479a81ee60a7b9dff2c97d3c8d6170e4cb286a5275a50e047459608fd55d5ca1ae10d1ac8822237a02355bba7dd6b525701fcb079c9124a35371" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/wasm-parser" + } + ] + }, + { + "type": "library", + "name": "wast-printer", + "group": "@webassemblyjs", + "version": "1.14.1", + "bom-ref": "launchpad@1.0.0|@webassemblyjs/wast-printer@1.14.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40webassemblyjs/wast-printer@1.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "90f4925c4e837b55ce47cdb40bdd11228da882f646f9cdca887cea5283bf177e18dac846cdeb1faafee8e7bc6bc68bd9247fcc7ad179523ae827f47fde2b288b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@webassemblyjs/wast-printer" + } + ] + }, + { + "type": "library", + "name": "ieee754", + "group": "@xtuc", + "version": "1.2.0", + "bom-ref": "launchpad@1.0.0|@xtuc/ieee754@1.2.0", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/%40xtuc/ieee754@1.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0d7f272a0a9c1b0b1cd1e252a98b799703f80c7e459479e6b96581472ed7d0d71a191d19b6ec9e11280cc1361512dc66b0d198faa8ade10613fcc2184ce4cf78" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@xtuc/ieee754" + } + ] + }, + { + "type": "library", + "name": "long", + "group": "@xtuc", + "version": "4.2.2", + "bom-ref": "launchpad@1.0.0|@xtuc/long@4.2.2", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/%40xtuc/long@4.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "36e1ea058d4f07f0fcc54eacfed84180e02200fec73980d0df6f8115920b27c8af9149001d09d67e7e9684befd3b08f5aa6527a0dfd83e192d748a2e722a6401" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@xtuc/long" + } + ] + }, + { + "type": "library", + "name": "monotone-cubic-spline", + "group": "@yr", + "version": "1.0.3", + "bom-ref": "launchpad@1.0.0|@yr/monotone-cubic-spline@1.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40yr/monotone-cubic-spline@1.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@yr/monotone-cubic-spline/-/monotone-cubic-spline-1.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1505e43ad6b45c14943c79dd20a38dd98f49790cf965e32a2d865554af7716588d0459bb2cd30866663a16b30407d5cf7036c4d9b7a431b643ea4cc3931c188c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/@yr/monotone-cubic-spline" + } + ] + }, + { + "type": "library", + "name": "acorn-jsx", + "version": "5.3.2", + "bom-ref": "launchpad@1.0.0|acorn-jsx@5.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/acorn-jsx@5.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "aeaf6cf893617f4202863b435f196527b838d68664e52957b69d0b1f0c80e5c7a3c27eef2a62a9e293eb8ba60478fbf63d4eb9b00b1e81b5ed2229e60c50d781" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/acorn-jsx" + } + ] + }, + { + "type": "library", + "name": "acorn", + "version": "8.18.0", + "bom-ref": "launchpad@1.0.0|acorn@8.18.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/acorn@8.18.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "946abef72af5fc6b8059a558207463befc921b9ff855f288bc2f045b14ad3dd70387f29aec51b7b703fabf8779064adabd48a584802c1b8423f37b74d8b5943d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/acorn" + } + ] + }, + { + "type": "library", + "name": "agent-base", + "version": "6.0.2", + "bom-ref": "launchpad@1.0.0|agent-base@6.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/agent-base@6.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "45937035c945efe312ffc6c383bd1a9a0df6772799199c620ee42667128b025423af78c6c8bc7ee0a924e7c50eec3d90760148402a2fb92b991129dee911ba5d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/agent-base" + } + ] + }, + { + "type": "library", + "name": "ajv-formats", + "version": "3.0.1", + "bom-ref": "launchpad@1.0.0|ajv-formats@3.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ajv-formats@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f2252a979d04511fae51c7514371c3a9ae84572a3776870bf20e5627714d7169aeeb621b90652e7bfa44c8b056f1518a2ae7133e0a9e92ce1f214d43038ca8c1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ajv-formats" + } + ] + }, + { + "type": "library", + "name": "ajv-keywords", + "version": "5.1.0", + "bom-ref": "launchpad@1.0.0|ajv-keywords@5.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ajv-keywords@5.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6024bf24d140532af9bc0ba19350d69b5081c511d6f4b6c9da8cd679e9ab22aa5bb2a2a31d5c583f28b9182d2b8d9213e49c49def8ab5534bcc24e22fd9fa4af" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ajv-keywords" + } + ] + }, + { + "type": "library", + "name": "ajv", + "version": "8.20.0", + "bom-ref": "launchpad@1.0.0|ajv@8.20.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ajv@8.20.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4e16e58be3a53a3fa230f60505505f2773a60809da4b2367e0cd6fcfd4fa1a46b926df5b6bf1c8479ea3a32eb9b58ea4c7f142179557341f35f58eff194ac118" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ajv" + } + ] + }, + { + "type": "library", + "name": "ansi-regex", + "version": "6.3.0", + "bom-ref": "launchpad@1.0.0|ansi-regex@6.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ansi-regex@6.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5a90df2fb34eea3eed1fcf080c13557542710e1f67982b5e0155bd76c7a9f38e977701789da0812befed18b5f728981ca603115c21654ccda1286a0af45b1dad" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/ansi-regex" + } + ] + }, + { + "type": "library", + "name": "ansi-styles", + "version": "4.3.0", + "bom-ref": "launchpad@1.0.0|ansi-styles@4.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ansi-styles@4.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cdb07dac22404f5adb8e25436f686a2851cd60bc60b64f0d511c59dc86700f717a36dc5b5d94029e74a2d4b931f880e885d3e5169db6db05402c885e64941212" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ansi-styles" + } + ] + }, + { + "type": "library", + "name": "anynum", + "version": "1.0.1", + "bom-ref": "launchpad@1.0.0|anynum@1.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/anynum@1.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/anynum/-/anynum-1.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "37afff14b113fed5d834cfc5e8005c6b5a07e9f581f8a953b7dd3d2dedbc58c0c193ca1a4f8bd8d7b0c2af083632f9aea942addcd8b837974627f12806070ee8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/anynum" + } + ] + }, + { + "type": "library", + "name": "apexcharts", + "version": "4.7.0", + "bom-ref": "launchpad@1.0.0|apexcharts@4.7.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/apexcharts@4.7.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/apexcharts/-/apexcharts-4.7.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8994abac11af5652fe9edd81d4da6a7c3b8167d8d7eb55fd236f975748656171ed4f08702d31c32865e33570201410cbbaf498081febab69cf5953d1bf60eb18" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/apexcharts" + } + ] + }, + { + "type": "library", + "name": "argparse", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|argparse@2.0.1", + "licenses": [ + { + "license": { + "id": "Python-2.0" + } + } + ], + "purl": "pkg:npm/argparse@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f3ef56a9e6db173a57f4e47e59ae8edbd6ac22881e44ccdc1ad00835da4c1c7c80835d1fd3969215505b704a867ff3d7c35123019faadbf6c4060dc3beeacadd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/argparse" + } + ] + }, + { + "type": "library", + "name": "ast-kit", + "version": "2.2.0", + "bom-ref": "launchpad@1.0.0|ast-kit@2.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ast-kit@2.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ast-kit/-/ast-kit-2.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9b543f45a54e9d3a7d2713d7f85f999fb21c2d833333c919a1f0c899fb0a65df0c6d1fa291d3b34deced4ad5aa7eba88c599d85abcb223d78f9b73468e76601b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ast-kit" + } + ], + "components": [ + { + "type": "library", + "name": "parser", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|ast-kit@2.2.0|@babel/parser@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/parser@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "54bdb6d2f5eec8edb3deb34843063b7ed8fd530a6a3adfb7dec1feb015a439e91bb1247683b1043273b1db8665087d31380dc333fdf74a27d51466e7243f2bff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ast-kit/node_modules/@babel/parser" + } + ] + }, + { + "type": "library", + "name": "types", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|ast-kit@2.2.0|@babel/types@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/types@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "52323f74a9b02704fda4eb33262b6ad86e8439b64f9ec6547dd0abf76cf64e51771192bd27711d7ce294ac2cc797ac05b616f3c21ce5d52a1cfd4230c518aaeb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ast-kit/node_modules/@babel/types" + } + ] + }, + { + "type": "library", + "name": "helper-string-parser", + "group": "@babel", + "version": "7.29.14", + "bom-ref": "launchpad@1.0.0|ast-kit@2.2.0|@babel/helper-string-parser@7.29.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-string-parser@7.29.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "097bca305bccf348a123b568c7d8dbfa44239f28c449034f33ebc1ed4d19cfa4d6b9903e67f14bd103cc1f7d34877dea26d231f9111e0615ea58e3d6e3c4dc01" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ast-kit/node_modules/@babel/helper-string-parser" + } + ] + }, + { + "type": "library", + "name": "helper-validator-identifier", + "group": "@babel", + "version": "7.29.7", + "bom-ref": "launchpad@1.0.0|ast-kit@2.2.0|@babel/helper-validator-identifier@7.29.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-validator-identifier@7.29.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a9e8711a4463e7987f7dff0431a27e71887268a947231a980e7ebcdb0403ed1369f54ba3390b07a20dae4b4af6bf3af8a56fac5dff7435e79aca370d697ddf16" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ast-kit/node_modules/@babel/helper-validator-identifier" + } + ] + } + ] + }, + { + "type": "library", + "name": "ast-walker-scope", + "version": "0.10.0", + "bom-ref": "launchpad@1.0.0|ast-walker-scope@0.10.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ast-walker-scope@0.10.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ast-walker-scope/-/ast-walker-scope-0.10.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2b3be8c437d7373d869bc2982e1e3b2b7a9c6376736b758a3ae876c68a9aecb06ee8c0ca58064ba2f26d53d0ee01dfc4afeae14070919fad7d9474b953eaa687" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ast-walker-scope" + } + ], + "components": [ + { + "type": "library", + "name": "ast-kit", + "version": "3.0.1", + "bom-ref": "launchpad@1.0.0|ast-walker-scope@0.10.0|ast-kit@3.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ast-kit@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ast-kit/-/ast-kit-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7c21a242f98782185ff39f1efd2546876694a3f16c6ed079a81f1b89fa3aca01cae4e31c1a76b9e8552f4b422b62fa3eba7630222d670a494487f29468e2959a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ast-walker-scope/node_modules/ast-kit" + } + ] + }, + { + "type": "library", + "name": "estree-walker", + "version": "3.0.3", + "bom-ref": "launchpad@1.0.0|ast-walker-scope@0.10.0|estree-walker@3.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/estree-walker@3.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ed150a7d781230c933b7a66e5e6a9aa4ebab2c63cf7e08fa97db9167b9511a896f934cb6ca871cdf92dd731282e4f419767d8332a8a8010d8da1672b4ca9a6ea" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ast-walker-scope/node_modules/estree-walker" + } + ] + } + ] + }, + { + "type": "library", + "name": "astral-regex", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|astral-regex@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/astral-regex@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "67bb4cc35cad4d7b798ea31c38ff8e42d794d55b8d2bd634daeb89b4a4354afebd8d740a2a0e5c89b2f0189a30f32cd93fe780735f0498b18f6a5d1ba77eabbd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/astral-regex" + } + ] + }, + { + "type": "library", + "name": "asynckit", + "version": "0.4.0", + "bom-ref": "launchpad@1.0.0|asynckit@0.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/asynckit@0.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "39e8bd387e2d461d18a94dc6c615fbf5d33f9b0560bdb64969235a464f9bb21923d12e5c7c772061a92b7818eb1f06ad5ca6f3f88a087582f1aca8a6d8c8d6d1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/asynckit" + } + ] + }, + { + "type": "library", + "name": "axe-core", + "version": "4.14.1", + "bom-ref": "launchpad@1.0.0|axe-core@4.14.1", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/axe-core@4.14.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1477dafa598d8d065f273d6af302aa203c02e83131707b7fa648cd41bd3d6b734f8c22a0dab86ee6a6f64b8afbe804b214d36db85a2826965edfb3a0b9d546b5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/axe-core" + } + ] + }, + { + "type": "library", + "name": "axios-retry", + "version": "4.5.0", + "bom-ref": "launchpad@1.0.0|axios-retry@4.5.0", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/axios-retry@4.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/axios-retry/-/axios-retry-4.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "691f7da178691031a8d14b80958727da219176cdf4937eba65f6b4e57592711f506900f825888fdffd50b75bbb62579f50e2be727d02730a0bd6879f6af41495" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/axios-retry" + } + ] + }, + { + "type": "library", + "name": "axios", + "version": "1.20.0", + "bom-ref": "launchpad@1.0.0|axios@1.20.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/axios@1.20.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "afc68e87c8fd7062a981002aa73ad41e748873a6b9f58dd77ff72ff2ccb50eb1c29191f340612ea2ad6d01193aa92c8376d4064838296fd90596bbb33efae0c2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/axios" + } + ] + }, + { + "type": "library", + "name": "bail", + "version": "2.0.2", + "bom-ref": "launchpad@1.0.0|bail@2.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/bail@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d313ba99877b241d987acc432a995a7d1a6c88eccfb7d574d9d74f08b6d8d716063ce5f6e0d4f2379d2a9d4c6008f712a183212a902e0538d0a1164202450347" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/bail" + } + ] + }, + { + "type": "library", + "name": "balanced-match", + "version": "4.0.4", + "bom-ref": "launchpad@1.0.0|balanced-match@4.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/balanced-match@4.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "04bae011c453c17da8ea01b118e08dc8cbc64a9df96287ee633c3d87520c4d198aaadb40659554ebb6dd6fd3ebdaf50703cfa3de2dad25f8cee82ebee26c864c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/balanced-match" + } + ] + }, + { + "type": "library", + "name": "base-64", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|base-64@1.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/base-64@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9300cf205086c743591e8837e9d8feb478b03f840ccec67702031589404a234f95e67e14d2e7d30943219d0d3876269123c117fd070f7ea97bce5859ee3e3382" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/base-64" + } + ] + }, + { + "type": "library", + "name": "baseline-browser-mapping", + "version": "2.11.20", + "bom-ref": "launchpad@1.0.0|baseline-browser-mapping@2.11.20", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/baseline-browser-mapping@2.11.20", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.20.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1f4ba5c928a0bfa89c0c9d45ed28ed7420fa3eb853a5d60298fd0269cb56cb5f9e921d0015dd28d569f94fc6fe8674e6741c75f6ef7284beb0bc2ca55cc63bcf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/baseline-browser-mapping" + } + ] + }, + { + "type": "library", + "name": "birpc", + "version": "2.9.0", + "bom-ref": "launchpad@1.0.0|birpc@2.9.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/birpc@2.9.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2ab6b21d2e69062ebd5e2f499afa2aac8818183903ea67127bf8ba60a8b7c3991e9022f3ad7e3e9dac1c5eaae3dad229e742b0fe64ffb37a7e1952b4034b0ac7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/birpc" + } + ] + }, + { + "type": "library", + "name": "blurhash", + "version": "2.0.5", + "bom-ref": "launchpad@1.0.0|blurhash@2.0.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/blurhash@2.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/blurhash/-/blurhash-2.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "711ca059dee418140edd51213e24e0ab859ce3772db0cfa8e3ababae63ce8ae01efb4edfce5481f4e2557698032f48cfa9751543d86dedaabb93139e24744afb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/blurhash" + } + ] + }, + { + "type": "library", + "name": "boolbase", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|boolbase@1.0.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/boolbase@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "25939203b328f6c34607cf948d283374bb68916024cb5cdbced3375912c26d9ef4ff771300d99098e751ef2da0f89d1ed965f2c32d724b8ebcb58f88aeea84c3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/boolbase" + } + ] + }, + { + "type": "library", + "name": "brace-expansion", + "version": "5.0.13", + "bom-ref": "launchpad@1.0.0|brace-expansion@5.0.13", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/brace-expansion@5.0.13", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "561ddd9856dce3065ea31eccf48ff42fd19f15df374aee3ec82724fce17d1a2fcffdd0079f4453ed7e0af51ee030d3210dc9370ef851e905ec9d07638e0c0dbd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/brace-expansion" + } + ] + }, + { + "type": "library", + "name": "braces", + "version": "3.0.3", + "bom-ref": "launchpad@1.0.0|braces@3.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/braces@3.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c906d780efce499543d88b222e5ae8fbb1dfe90d7c109aca484b1da0ccca78f29772dde0bc3f282dc390748cc6ba9af9163f840def203bf9717350737cca71bc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/braces" + } + ] + }, + { + "type": "library", + "name": "browserslist", + "version": "4.28.8", + "bom-ref": "launchpad@1.0.0|browserslist@4.28.8", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/browserslist@4.28.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "576369a1f2db946eb899f3ad4a00e13891126441a88330cc06ffeaf96ea87382d758ffeaef978e5e839a68ebb510e69d07d538070c7f7b4cb36efc0a1fccda94" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/browserslist" + } + ] + }, + { + "type": "library", + "name": "buffer-from", + "version": "1.1.2", + "bom-ref": "launchpad@1.0.0|buffer-from@1.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/buffer-from@1.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "13e5d0091c126da6a20a1b6fea4e83c2073e6f1f81b3abee2891c7979928c7f05a29b8625f3a903b02b870edb6c84946a763829a3c15853dc79b18323c69c97d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/buffer-from" + } + ] + }, + { + "type": "library", + "name": "byte-length", + "version": "1.0.2", + "bom-ref": "launchpad@1.0.0|byte-length@1.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/byte-length@1.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/byte-length/-/byte-length-1.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a2f0698e6b2077fb5e46681c3e1db7778809bf10e85ed03310bf714df314f1873692a0836fb2fd8c01b45c79759f3b8697e87779b0881758bad9417203d57fd9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/byte-length" + } + ] + }, + { + "type": "library", + "name": "cacheable", + "version": "2.5.0", + "bom-ref": "launchpad@1.0.0|cacheable@2.5.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/cacheable@2.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "eb473200ecad89bfcecc1c3524d4a8495fdba0ad40b47af20c88ef54193b5db378ba07e4337f92af2edf1233603cc1a03a3b9a64f029f2bb99d02c5a7f0caaf6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/cacheable" + } + ] + }, + { + "type": "library", + "name": "call-bind-apply-helpers", + "version": "1.0.2", + "bom-ref": "launchpad@1.0.0|call-bind-apply-helpers@1.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/call-bind-apply-helpers@1.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4a9d5a6e52748af0e44b38dc68977112e9cde7f5ef92c149dac30115fabac74af285057fd9bfcac057b6d5c329987b4f3928a3f0af7dff049fa04b9339b9ae31" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/call-bind-apply-helpers" + } + ] + }, + { + "type": "library", + "name": "callsites", + "version": "3.1.0", + "bom-ref": "launchpad@1.0.0|callsites@3.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/callsites@3.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3fc06302c5ef652f95203508d7584709012fef8613ebb6148b924914d588a8bdb7e6c0668d7e3eab1f4cbaf96ce62bf234435cb71e3ac502d0dda4ee13bb2c69" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/callsites" + } + ] + }, + { + "type": "library", + "name": "caniuse-lite", + "version": "1.0.30001810", + "bom-ref": "launchpad@1.0.0|caniuse-lite@1.0.30001810", + "licenses": [ + { + "license": { + "id": "CC-BY-4.0" + } + } + ], + "purl": "pkg:npm/caniuse-lite@1.0.30001810", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4c84d03d491acfe69593918be8d84e77093568468d4d20cfb06156ad3ba1286b634c5ef48cbfce86dd96e1ceab5d47b97eeec87b5f5521a8405c720889658d7a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/caniuse-lite" + } + ] + }, + { + "type": "library", + "name": "ccount", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|ccount@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ccount@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7b2ac5d23885a58fb776b4fadfcddfd6a8646c6b0b4a27cd02303ad4852366398b0968c8b58e8b07d7edf588680e0c1f99c941db386ee752dcefef796fc35102" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ccount" + } + ] + }, + { + "type": "library", + "name": "chalk", + "version": "4.1.2", + "bom-ref": "launchpad@1.0.0|chalk@4.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/chalk@4.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a0a9db845c91217a54b9ecfc881326c846b89db8f820e432ba173fc32f6463bfd654f73020ef5503aebc3eef1190eefed06efa48b44e7b2c3d0a9434eb58b898" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/chalk" + } + ] + }, + { + "type": "library", + "name": "character-entities-html4", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|character-entities-html4@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/character-entities-html4@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d6fedf810463ea19d2c05a6ad44bb4ca7aff083130d2b5e8d81eb5a97acb35d1d998f2a06fb7ea4b56b6270174ac84a8f6aefb8c323c54c107a00a67f2a0e864" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/character-entities-html4" + } + ] + }, + { + "type": "library", + "name": "character-entities-legacy", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|character-entities-legacy@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/character-entities-legacy@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4693e9d1ab13ffab9f466fff009570a558996c633f3248d017125c710447988485ff6d8d06db07a805a62fefe99a43d6a08509756c9e565793975c3274701355" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/character-entities-legacy" + } + ] + }, + { + "type": "library", + "name": "character-entities", + "version": "2.0.2", + "bom-ref": "launchpad@1.0.0|character-entities@2.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/character-entities@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b21c7ba10d00c1e9ff05121d92392fcf9e0f9c4108fc48f05c3488669f3afca29d6da7c78750dffd16060619f885b7b6fae282f459d3e540847723f3dda8bd85" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/character-entities" + } + ] + }, + { + "type": "library", + "name": "character-reference-invalid", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|character-reference-invalid@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/character-reference-invalid@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "881678178c116f239156cbb48cf57b81790eb066231873e6032bfe1e21c6f208b93ed0bd288da3d7ebfcfed9626d1be3a165f4dbbca9986fe7d07b4ee6deee9f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/character-reference-invalid" + } + ] + }, + { + "type": "library", + "name": "charenc", + "version": "0.0.2", + "bom-ref": "launchpad@1.0.0|charenc@0.0.2", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/charenc@0.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cab2d0ff255415793383b10342c3e2784ff9dfed1195a593b3ec01aef5b7e9cca2949d9268359f978623eccb4b4d795e57db8429e7db00650fbf6fe2592a2844" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/charenc" + } + ] + }, + { + "type": "library", + "name": "chokidar", + "version": "5.0.0", + "bom-ref": "launchpad@1.0.0|chokidar@5.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/chokidar@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4d0326737c3ee40c63a4bf22222c1e6c5ef77510c5e1f04889e02a1a7f5118259a115c10e856f67067b7d589ecd11448ce28b982827563bc5b330a354f132997" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/chokidar" + } + ] + }, + { + "type": "library", + "name": "chrome-trace-event", + "version": "1.0.4", + "bom-ref": "launchpad@1.0.0|chrome-trace-event@1.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/chrome-trace-event@1.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "acd8c0a5a2f3bb068e4e30a24fc9520dd18dd403c28aa90284b309c493d62ee9cf02de5fcbcc6053dfe334e72157ce307c8c6b034951401ee8093f23ae7ff0ad" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/chrome-trace-event" + } + ] + }, + { + "type": "library", + "name": "clone", + "version": "2.1.2", + "bom-ref": "launchpad@1.0.0|clone@2.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/clone@2.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "dcf7bf085d4d9fde21ca1218a63b622e1742a04a33d03a90fbdf3c13d826784750665a23c6739bef8c1cb45caec16407ceac9ff57ec2ecc1bc8ee529a81253f3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/clone" + } + ] + }, + { + "type": "library", + "name": "codemirror", + "version": "6.0.2", + "bom-ref": "launchpad@1.0.0|codemirror@6.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/codemirror@6.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "561c9d1e8b4d5b9c355062b4423f7a0704a4fd9a9ba7d59b9f22b65bf79532fe10c85e3520d446a6352114963bfee0cdbae752737ddafcf2abe220ea45dbaf1f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/codemirror" + } + ] + }, + { + "type": "library", + "name": "color-convert", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|color-convert@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/color-convert@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4511023ec8fb8aeff16f9a0a61cb051d2a6914d9ec8ffe763954d129be333f9a275f0545df3566993a0d70e7c60be0910e97cafd4e7ce1f320dfc64709a12529" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/color-convert" + } + ] + }, + { + "type": "library", + "name": "color-name", + "version": "1.1.4", + "bom-ref": "launchpad@1.0.0|color-name@1.1.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/color-name@1.1.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "74ecbedc0b96ddadb035b64722e319a537208c6b8b53fb812ffb9b71917d3976c3a3c7dfe0ef32569e417f479f4bcb84a18a39ab8171edd63d3a04065e002c40" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/color-name" + } + ] + }, + { + "type": "library", + "name": "colord", + "version": "2.10.0", + "bom-ref": "launchpad@1.0.0|colord@2.10.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/colord@2.10.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/colord/-/colord-2.10.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "022749a6da412668d3725029f4190bc098b44fdddfa397a92676da66c96983a415ce91e3022bde179e6613d01c50988632a44780c0d8f2ca0cb10b6e3583077f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/colord" + } + ] + }, + { + "type": "library", + "name": "combined-stream", + "version": "1.0.8", + "bom-ref": "launchpad@1.0.0|combined-stream@1.0.8", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/combined-stream@1.0.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1503783117ee25e1dfedc05b04c2455e12920eafb690002b06599106f72f144e410751d9297b5214048385d973f73398c3187c943767be630e7bffb971da0476" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/combined-stream" + } + ] + }, + { + "type": "library", + "name": "comma-separated-tokens", + "version": "2.0.3", + "bom-ref": "launchpad@1.0.0|comma-separated-tokens@2.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/comma-separated-tokens@2.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "16ee2125dbf37b29427d03e9f5219689da73accb3bb53ae5bba55bf1719a446724f1048d649269e77f16adbeb42dac787cfc11eb8562638ebc3885136d194666" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/comma-separated-tokens" + } + ] + }, + { + "type": "library", + "name": "commander", + "version": "14.0.3", + "bom-ref": "launchpad@1.0.0|commander@14.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/commander@14.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1fecb4268fd3d5167da8f3f8121d6991c41c2d1825ada25a48ba323ad1f1bba01aa648d6542cb64a2b75410e31dc39e0f2a0e54ac6447adee0e4fab4e8cbd383" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/commander" + } + ] + }, + { + "type": "library", + "name": "confbox", + "version": "0.3.2", + "bom-ref": "launchpad@1.0.0|confbox@0.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/confbox@0.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "65400a84a96408eac818a73c723ef37a4f6cf73d66bde1e27ffdb99d4b21236073091cc5eca1fb2876be2e7876b9babe7b5b4895a16e3fbeb79b35b8a95a1e86" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/confbox" + } + ] + }, + { + "type": "library", + "name": "core-js", + "version": "3.51.0", + "bom-ref": "launchpad@1.0.0|core-js@3.51.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/core-js@3.51.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/core-js/-/core-js-3.51.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "edb0cac7fe639b9331cec5f173dde0e99dbee19b2e4ff31d76b7d19930c9340916b1858753c115344b018881169cc00c08732645f5048e4ba8de378d04e20747" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/core-js" + } + ] + }, + { + "type": "library", + "name": "cosmiconfig", + "version": "9.0.2", + "bom-ref": "launchpad@1.0.0|cosmiconfig@9.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/cosmiconfig@9.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "82d4d9c530dabb5c0bed8ef389f73675df231d22bf93a053c7fd97a7f06976501d9e5616155b7baa126a8308bbeb7ef2470450dea2f866275b07823cb40e553a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/cosmiconfig" + } + ] + }, + { + "type": "library", + "name": "crelt", + "version": "1.0.7", + "bom-ref": "launchpad@1.0.0|crelt@1.0.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/crelt@1.0.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "68ae816d67e17f853fc0270b1ca3c997fc5ae95915b2d45a3f2c16b4c286c2e38b73fc194f2418ba8c60bd99cdb01befeca83761305061804282072f890733b8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/crelt" + } + ] + }, + { + "type": "library", + "name": "cross-spawn", + "version": "7.0.6", + "bom-ref": "launchpad@1.0.0|cross-spawn@7.0.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/cross-spawn@7.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b95d903963f69d6ceccb668ca7c69189b862f5d9731791e0879487681f4e893184c834e2249cb1d2ecb9d505ddc966ed00736e6b85c9cd429c6b73b3294777bc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/cross-spawn" + } + ] + }, + { + "type": "library", + "name": "crypt", + "version": "0.0.2", + "bom-ref": "launchpad@1.0.0|crypt@0.0.2", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/crypt@0.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "982c4196c1c5621f42f8756988469c7a6f051019cc5e053d832e3398d0be497019341ff589d829fdaba5149e058028bb18f1156dfca7834f761aa2f6936ae6a3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/crypt" + } + ] + }, + { + "type": "library", + "name": "css-functions-list", + "version": "3.3.3", + "bom-ref": "launchpad@1.0.0|css-functions-list@3.3.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/css-functions-list@3.3.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/css-functions-list/-/css-functions-list-3.3.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f0714404f2a13a924f10fbbbd302497ad8cab5af3a1b0f7e082c829c1decba2daa41f3af472a81cb820a2ca280c1d32959bda51d75a4f566f867a0266944f53e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/css-functions-list" + } + ] + }, + { + "type": "library", + "name": "css-tree", + "version": "3.2.1", + "bom-ref": "launchpad@1.0.0|css-tree@3.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/css-tree@3.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5fbb2343371e521bb5bbb63fca5ad1645536152e8b462155a7aaca2cf836df2df1ddcdc338a030b97183a7e3c01a387a0929c28d8780ba5f29713f1b025fa548" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/css-tree" + } + ] + }, + { + "type": "library", + "name": "csstype", + "version": "3.2.3", + "bom-ref": "launchpad@1.0.0|csstype@3.2.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/csstype@3.2.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cf51c629c632db103c00641fc2b9f43c0cbe3c1ed7fc64a3dd45495bda8aca7e37c566be825e675e6538aaa2cc4735952c50bc2aeb145fc4ffd240a2398a4021" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/csstype" + } + ] + }, + { + "type": "library", + "name": "d3-color", + "version": "3.1.0", + "bom-ref": "launchpad@1.0.0|d3-color@3.1.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/d3-color@3.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ce0fdc85b5f2781b4c4352db0ff592a16d83a42dc8d26a663dd5beca74538ffc760c0598ac863ba9e6481e2768cf0576e26e226afaf5e653702302f14663b184" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-color" + } + ] + }, + { + "type": "library", + "name": "d3-dispatch", + "version": "3.0.1", + "bom-ref": "launchpad@1.0.0|d3-dispatch@3.0.1", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/d3-dispatch@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "af35323d4fd2eebc147e53322dcd444c37818f4351b8728a01cbee928cf086c86bea0e9ce5df338787368108d8d9b6747577862d67353c5d7be0fdad56f2a17e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-dispatch" + } + ] + }, + { + "type": "library", + "name": "d3-drag", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|d3-drag@3.0.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/d3-drag@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a566d424b7444d503c95034979c331a177c7eb1fa63b6510a3cad2999f90ab171bc80de17dea6b160213fff1d6da79470a159e2083304b616afa010046485392" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-drag" + } + ] + }, + { + "type": "library", + "name": "d3-ease", + "version": "3.0.1", + "bom-ref": "launchpad@1.0.0|d3-ease@3.0.1", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/d3-ease@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c11fd72b70f75dc2c8670a5bbd0c10e5f2bef1891db358a9ec0d93c5ed32c6771749dab52fdb24706edb95c79d90e5fe65c83118098b5f516b4466c00f0ce2d3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-ease" + } + ] + }, + { + "type": "library", + "name": "d3-interpolate", + "version": "3.0.1", + "bom-ref": "launchpad@1.0.0|d3-interpolate@3.0.1", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/d3-interpolate@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ddb62cd6b383df7ba8f1aa897ca3f72563c089b830f199b6f8bf6f04a107276460faf89347ba39326bf999972278df854586803965f94890135fa9353d6cfbda" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-interpolate" + } + ] + }, + { + "type": "library", + "name": "d3-selection", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|d3-selection@3.0.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/d3-selection@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7e64d159b34c9ac996abac4957c0f5f54fe0c3f6f0ac77cd5f1ac837e1df6609f3a931e9f633a628c86c4d48d73899d939d658f50dbccb8c9e6cacea0ca97195" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-selection" + } + ] + }, + { + "type": "library", + "name": "d3-timer", + "version": "3.0.1", + "bom-ref": "launchpad@1.0.0|d3-timer@3.0.1", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/d3-timer@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9dd7c9fc9c7131dde7c37d6ec8aa18da76a2bc5fabdbd57e2dcd2cbd9c5ed49bef2119a2f2152caccbdd3b0812d68eae0479a2cfdd60790d3294f3f46a3d5550" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-timer" + } + ] + }, + { + "type": "library", + "name": "d3-transition", + "version": "3.0.1", + "bom-ref": "launchpad@1.0.0|d3-transition@3.0.1", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/d3-transition@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0292af7e3b1247ab60d3ac6b2f8df80b45b274bafb25ec0107757eff7f51307b1a5d3386d339adfce0177a78393392c19b4a239b126ba68990559d5a3ef04be3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-transition" + } + ] + }, + { + "type": "library", + "name": "d3-zoom", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|d3-zoom@3.0.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/d3-zoom@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6fc02657791f41aa9602e69c6cfb8d6cbeaf6a19ce25f94e85ec4bccc30d2e06badbefe7874273bc9d1a3bfe5ae4c560505192ec7bb53fd3f4de8ddf2640c2cb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/d3-zoom" + } + ] + }, + { + "type": "library", + "name": "data-uri-to-buffer", + "version": "4.0.1", + "bom-ref": "launchpad@1.0.0|data-uri-to-buffer@4.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/data-uri-to-buffer@4.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d11f629116faebc1c1ed00f14f5be4a6e501b6a739dd8c80c0cc0679414a4688d8fcd58abdd67ef5462d45f1a686a35b4644d256931b9b28578a9145bf671bfc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/data-uri-to-buffer" + } + ] + }, + { + "type": "library", + "name": "date-fns", + "version": "4.4.0", + "bom-ref": "launchpad@1.0.0|date-fns@4.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/date-fns@4.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fb550c6de87af251f549e807f370865b0a5be8e1c76e94a0af7face44c30e4ce02020b30069a164b40234ce7c4277dc78982b3d61763fca4c5a6bcd71e6abfeb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/date-fns" + } + ] + }, + { + "type": "library", + "name": "debounce", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|debounce@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/debounce@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/debounce/-/debounce-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "eb86f245b174fc08abc1bb87a81dff669306f7f9dc9036ba640d3277a5276903706db7a608ec2fcf6b0be6c8d72c78591c00f28b02e6d0ce6a32196d514c7e4c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/debounce" + } + ] + }, + { + "type": "library", + "name": "debug", + "version": "4.4.3", + "bom-ref": "launchpad@1.0.0|debug@4.4.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/debug@4.4.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "446c305a7c10be455f6af295b76d8518bc3ec5849dcc04709b4aeee83853540dee994e6165cdbc57790ee2cb6062bcab4e52e9baf808f468a28e5b408cd6dca8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/debug" + } + ] + }, + { + "type": "library", + "name": "decode-named-character-reference", + "version": "1.3.0", + "bom-ref": "launchpad@1.0.0|decode-named-character-reference@1.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/decode-named-character-reference@1.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1ada50601dbcdcaacfa7a9d1c39d2add4f7f55f3aeb5939ed74dea94dec13cfe80776ef16273885afe253f3a3c1c200bfa6319a1f27d284cb7d1faba31f68ae9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/decode-named-character-reference" + } + ] + }, + { + "type": "library", + "name": "deep-is", + "version": "0.1.4", + "bom-ref": "launchpad@1.0.0|deep-is@0.1.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/deep-is@0.1.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a083f392c993838fccae289a6063bea245c34fbced9ffc37129b6fffe81221d31d2ac268d2ee027d834524fcbee1228cb82a86c36c319c0f9444c837b7c6bf6d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/deep-is" + } + ] + }, + { + "type": "library", + "name": "delayed-stream", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|delayed-stream@1.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/delayed-stream@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "672483ecd7fdd5a2c1d11c4be0a1ab28705797b11db350c098475ca156b05e72c3ed20e1a4d82db88236680920edaed04b8d63c4f499d7ba7855d1a730793731" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/delayed-stream" + } + ] + }, + { + "type": "library", + "name": "dequal", + "version": "2.0.3", + "bom-ref": "launchpad@1.0.0|dequal@2.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/dequal@2.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d237bea8f28710ca21bdf453084a370ab3c6e9c033018826ccacb1462612483912e9e1897725499bb59a600e4409a003f702c1d93e0411eca603968555c61708" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/dequal" + } + ] + }, + { + "type": "library", + "name": "detect-libc", + "version": "2.1.2", + "bom-ref": "launchpad@1.0.0|detect-libc@2.1.2", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/detect-libc@2.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "06d8f604e38ef37a375b21f9f5ef0c817b3111055c6ab9143a9118aee6c1d2eaf09cdd74c90dfae2bb22072535d67665a966199b4e62fe87fb8a8e26ce2841b5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/detect-libc" + } + ] + }, + { + "type": "library", + "name": "devlop", + "version": "1.1.0", + "bom-ref": "launchpad@1.0.0|devlop@1.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/devlop@1.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "456988aa17057f5951601bcd9abeea4cdbb20adffbfe7b368dba69d7e3da96013fac341c053d1f8a848c52927dde2ae55210b986b838718a9ee94fb42265b4ac" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/devlop" + } + ] + }, + { + "type": "library", + "name": "dexie", + "version": "4.4.7", + "bom-ref": "launchpad@1.0.0|dexie@4.4.7", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/dexie@4.4.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/dexie/-/dexie-4.4.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c1e9858829770d30a77f3caa7a95135f5ba06d86e44ebc3768464e1bb62300e5281100798393eb132c0fce4e49a5b5ff4b1a90f48be3529c420c8123a0e5847c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/dexie" + } + ] + }, + { + "type": "library", + "name": "dom-serializer", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|dom-serializer@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/dom-serializer@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c08900af28aab7f9d5e4440aa90a68dd24e848e57d2740e76c9ab02bb5affd3adcf76cc801867816532ef893c55b50df185b7cd594c21a00c469b7df5de2f226" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/dom-serializer" + } + ], + "components": [ + { + "type": "library", + "name": "entities", + "version": "4.5.0", + "bom-ref": "launchpad@1.0.0|dom-serializer@2.0.0|entities@4.5.0", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/entities@4.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5748631f87463e1f40a39a74328458e8156ab700a3873eaf2392d3f00279e47fb883dff8bdb1f1d48e787d2d17b9c94b8431c0acf40288c8c3c6368bf1f3f187" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/dom-serializer/node_modules/entities" + } + ] + } + ] + }, + { + "type": "library", + "name": "domelementtype", + "version": "2.3.0", + "bom-ref": "launchpad@1.0.0|domelementtype@2.3.0", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/domelementtype@2.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "38b113063eb0d0eb1a801c1d5e73dd37472731f17da2937af5ca3eed9adb7cf1ab7693d5341523d36b298ba07537bc0284b4223e7e02487ff326f5f0e7a8261f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/domelementtype" + } + ] + }, + { + "type": "library", + "name": "domhandler", + "version": "5.0.3", + "bom-ref": "launchpad@1.0.0|domhandler@5.0.3", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/domhandler@5.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "720c25bffd621508859d4f7a5d78113a1f314de7adb272620ec4dced36022c577dfbf58d908a8f4f188cffca5277c548ae15c64dfd4dcb5ab586ab95a83241e7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/domhandler" + } + ] + }, + { + "type": "library", + "name": "dompurify", + "version": "3.4.18", + "bom-ref": "launchpad@1.0.0|dompurify@3.4.18", + "licenses": [ + { + "expression": "(MPL-2.0 OR Apache-2.0)" + } + ], + "purl": "pkg:npm/dompurify@3.4.18", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.18.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a1f7b7c08fee366ebc1c89c005814962a431470d4468a02335dac554aaa3518f9466eaef35dd8bfc7b907b4f7bb3fe118af5a26723fab53edaa13f1ab637e1c2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/dompurify" + } + ] + }, + { + "type": "library", + "name": "domutils", + "version": "3.2.2", + "bom-ref": "launchpad@1.0.0|domutils@3.2.2", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/domutils@3.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ea464ac946a3943baa9472955f5c3b832b258fd30f217cc8162cffac6bb7e6e0b5c0c8be90c850c06865e25b7dba70bd55bf4836763d677fd9037f8584048b6b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/domutils" + } + ] + }, + { + "type": "library", + "name": "dunder-proto", + "version": "1.0.1", + "bom-ref": "launchpad@1.0.0|dunder-proto@1.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/dunder-proto@1.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "28837f9c3241411717c3430b561644f62407986ebca80548060f42aa65188e64088608a3f54e4c16faea9142f915bb72cb366e39e3add3375e45ee1463b72df8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/dunder-proto" + } + ] + }, + { + "type": "library", + "name": "electron-to-chromium", + "version": "1.5.416", + "bom-ref": "launchpad@1.0.0|electron-to-chromium@1.5.416", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/electron-to-chromium@1.5.416", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.416.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2ba6ef0760639cdaee82d22287a7b095b048f435daf7bea321d8889512c7841a0423d6b825a4238c7c85f80d48408e78dda4184782e798ead3fcae5f663d1a3c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/electron-to-chromium" + } + ] + }, + { + "type": "library", + "name": "emoji-mart-vue-fast", + "version": "15.0.5", + "bom-ref": "launchpad@1.0.0|emoji-mart-vue-fast@15.0.5", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/emoji-mart-vue-fast@15.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/emoji-mart-vue-fast/-/emoji-mart-vue-fast-15.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c27c4ba2bf20829aac86838fc08737dcc74e0b70355c57832e053060b3ed34f2fc55e02d5c9015ae716ad423793de098005a0ba3822e7c7419f427c70f82198b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/emoji-mart-vue-fast" + } + ] + }, + { + "type": "library", + "name": "emoji-regex", + "version": "8.0.0", + "bom-ref": "launchpad@1.0.0|emoji-regex@8.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/emoji-regex@8.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3128d8cdc58d380d1ec001e9cf4331a5816fc20eb28f2d4d1b7c6d7a8ab3eb8e150a8fd13e09ebd7f186b7e89cde2253cd0f04bb74dd335e126b09d5526184e8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/emoji-regex" + } + ] + }, + { + "type": "library", + "name": "enhanced-resolve", + "version": "5.24.5", + "bom-ref": "launchpad@1.0.0|enhanced-resolve@5.24.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/enhanced-resolve@5.24.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2f597c4cdbe89a6e94556e41db9dc01b141a81242bfaf1b084c96badf452daa9a1c78e8032931524a4182ef5986f2b13318f15a2270ebf31f3a0731bcb307ee0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/enhanced-resolve" + } + ] + }, + { + "type": "library", + "name": "entities", + "version": "7.0.1", + "bom-ref": "launchpad@1.0.0|entities@7.0.1", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/entities@7.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4d6ae02ce1544131fdf78614ca5d724f8bb26af6399cd0799ae7dff91b566aa3550802b8d3c6f96679db34050458b4c2a6e9bdc3a6ab4fbd22d57750e1478e3c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/entities" + } + ] + }, + { + "type": "library", + "name": "env-paths", + "version": "2.2.1", + "bom-ref": "launchpad@1.0.0|env-paths@2.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/env-paths@2.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fa1d6590b2a164c4d88e8835544a49346ecd64959cb9cd830e4feab2a49345108e5e22e3790d5dd7fb9dad41a1a8cc5480097028d67471fdaea9a9f918bb92d8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/env-paths" + } + ] + }, + { + "type": "library", + "name": "error-ex", + "version": "1.3.4", + "bom-ref": "launchpad@1.0.0|error-ex@1.3.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/error-ex@1.3.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b2a41a9809d1d785600abd40eb5f00dec1abca07292be1c46de9c0fc7884024914c1c648201fed816a871715a03b20e1e270782424629a1efd751e58c1cf4c0d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/error-ex" + } + ] + }, + { + "type": "library", + "name": "es-define-property", + "version": "1.0.1", + "bom-ref": "launchpad@1.0.0|es-define-property@1.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/es-define-property@1.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7b79d17e07d4678acd18bdb7da05205f4e90372c9ecf4e0a76316b17e2d34683979ab3a014a0e0e0109db235bc1274faf5ea9d606991a49c223d560dac2696de" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/es-define-property" + } + ] + }, + { + "type": "library", + "name": "es-errors", + "version": "1.3.0", + "bom-ref": "launchpad@1.0.0|es-errors@1.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/es-errors@1.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "65fe47d8ac6ddb18d3bdb26f3f66562c4202c40ea3fa1026333225ca9cb8c5c060d6f2959f1f3d5b2d066d2fa47f9730095145cdd0858765d20853542d2e9cb3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/es-errors" + } + ] + }, + { + "type": "library", + "name": "es-module-lexer", + "version": "2.3.2", + "bom-ref": "launchpad@1.0.0|es-module-lexer@2.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/es-module-lexer@2.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a681c6a4e4400688c926e72757d29b39abc44d6f250559e98645bbec4479fc1439173ee85d2a0235e93b207def4799d18ddb04cfddba89b1585fc2ad2d099dcb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/es-module-lexer" + } + ] + }, + { + "type": "library", + "name": "es-object-atoms", + "version": "1.1.2", + "bom-ref": "launchpad@1.0.0|es-object-atoms@1.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/es-object-atoms@1.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1d6701a0de8d8a57aab52c9d2b616a1db4bf2e80ddda9aab9d01cbc89cc18f890ea7f932d8c58c37af78c4e7e42bcfd29d4b16d831fb11fc9597274a0ac9b567" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/es-object-atoms" + } + ] + }, + { + "type": "library", + "name": "es-set-tostringtag", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|es-set-tostringtag@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/es-set-tostringtag@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8fabd6cdfac655fc97c607be3b4c79b21e9cbf10288346bfe1175dd8adfacc2315e5e27effeb4e0278113bc70e0cc3566d545d5659866502f6612df247c6c850" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/es-set-tostringtag" + } + ] + }, + { + "type": "library", + "name": "escalade", + "version": "3.2.0", + "bom-ref": "launchpad@1.0.0|escalade@3.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/escalade@3.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5948f6aa5c5a42d3b883a3eae5cdbd193716183c9df22b4bf334e58a98040b3dc97ac02288e2a8b5df0953aa2d0773c00a01bac64254c9585ba0c4be6e37bf8c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/escalade" + } + ] + }, + { + "type": "library", + "name": "escape-html", + "version": "1.0.3", + "bom-ref": "launchpad@1.0.0|escape-html@1.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/escape-html@1.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3624aea59e0e7ae1b0afaf251887b29bf92c219309a1d506392099fc54a74f172b7a46efaab81d53194938ca628da299563009ad6ac6b3fe89cbc38cbb28fda3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/escape-html" + } + ] + }, + { + "type": "library", + "name": "escape-string-regexp", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|escape-string-regexp@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/escape-string-regexp@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4eda5c349dd7033c771aaf2c591cc96956a346cd2e57103660091d6f58e6d9890fcf81ba7a05050320379f9bed10865e7cf93959ae145db2ae4b97ca90959d80" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/escape-string-regexp" + } + ] + }, + { + "type": "library", + "name": "eslint-plugin-vue", + "version": "10.10.0", + "bom-ref": "launchpad@1.0.0|eslint-plugin-vue@10.10.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/eslint-plugin-vue@10.10.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-10.10.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "74bf71f6b047aaa35c0725a22ce1cae8bd1207ded5f36fcd0b4719467f5c5cf8ccee90ae5a5a5040ff5b147e2f8c1bfcd1e8f5669cc092e0fccd61f5a3d6d96c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint-plugin-vue" + } + ], + "components": [ + { + "type": "library", + "name": "semver", + "version": "7.8.5", + "bom-ref": "launchpad@1.0.0|eslint-plugin-vue@10.10.0|semver@7.8.5", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/semver@7.8.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "63bfca0ec6fc2e3a28669c1aa86cae94ee8342592c8029dc7211c693eb19218e1206f52870c044147e54af57c8e1d57e26f974c3a723bee71a222e34a6e462a0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint-plugin-vue/node_modules/semver" + } + ] + } + ] + }, + { + "type": "library", + "name": "eslint-scope", + "version": "9.1.2", + "bom-ref": "launchpad@1.0.0|eslint-scope@9.1.2", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/eslint-scope@9.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c52f741f9d5c2b0d2396dc66be61f2d886a2d4b22aadf6f0e7b6fbf70fc9ecc7ef0df90890567e923eb30b7063b54c21d79d07b1249dc5765cb2ebfbda688315" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint-scope" + } + ] + }, + { + "type": "library", + "name": "eslint-visitor-keys", + "version": "4.2.1", + "bom-ref": "launchpad@1.0.0|eslint-visitor-keys@4.2.1", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/eslint-visitor-keys@4.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "521764e6c7ea71e7bff47feb08e262918cfaee8d1ad93c3684644f386d98d51d9d83b6eb45ed6e1b4c9a3500c7bbe4cefee40f17fe5e09aa6f612987523b7b25" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint-visitor-keys" + } + ] + }, + { + "type": "library", + "name": "eslint", + "version": "10.15.0", + "bom-ref": "launchpad@1.0.0|eslint@10.15.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/eslint@10.15.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fb95a0e29fb37b7b06d5612b62050eff71f521021f141ca6554034168fd74de04e2d2e9440851e929489f2c751927eceef08e1f386f9e70feba2a6af1f669272" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint" + } + ], + "components": [ + { + "type": "library", + "name": "ajv", + "version": "6.15.0", + "bom-ref": "launchpad@1.0.0|eslint@10.15.0|ajv@6.15.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ajv@6.15.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7e0171ec77e8abad32b4ad9cec386717c8c8bf362038cc5fba08cb3923078cb20f81e9ea6bb4bba1a6a001352af7d995e8862f376b51982d309d3617ea23db33" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint/node_modules/ajv" + } + ] + }, + { + "type": "library", + "name": "eslint-visitor-keys", + "version": "5.0.1", + "bom-ref": "launchpad@1.0.0|eslint@10.15.0|eslint-visitor-keys@5.0.1", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/eslint-visitor-keys@5.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b43e34787c40df98743c421935e223907a034786238c9a77e1b88cd260efa6505efff981f881c2a870c657ba7117eecc9254ef8a085c08f3d90bbca75b28dd4c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint/node_modules/eslint-visitor-keys" + } + ] + }, + { + "type": "library", + "name": "espree", + "version": "11.2.0", + "bom-ref": "launchpad@1.0.0|eslint@10.15.0|espree@11.2.0", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/espree@11.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ee9dc3ad5108a295b50756af0062ee0928758ee6dcd351f624773c078aaa19b966839808f72ba60600028d6a3826521cd38b9fba0e3127749023c1e44bf460cf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint/node_modules/espree" + } + ] + }, + { + "type": "library", + "name": "minimatch", + "version": "11.0.8", + "bom-ref": "launchpad@1.0.0|eslint@10.15.0|minimatch@11.0.8", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0" + } + } + ], + "purl": "pkg:npm/minimatch@11.0.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9c542e6124d5ac6bf2b15069b39221fb405d9d814dfc28f70bcd7aafafa9ef22be147ad52c61383b837d005c3292b94d96f3361d8b7e45a775522ae8ea1f3c22" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint/node_modules/minimatch" + } + ] + }, + { + "type": "library", + "name": "json-schema-traverse", + "version": "0.4.1", + "bom-ref": "launchpad@1.0.0|eslint@10.15.0|json-schema-traverse@0.4.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/json-schema-traverse@0.4.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c5b6c21f9742614e53f0b704861ba1ec727cf075ee5b7aac237634cce64529f6441dca5688753f271ce4eb6f41aec69bfe63221d0b62f7030ffbce3944f7b756" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/eslint/node_modules/json-schema-traverse" + } + ] + } + ] + }, + { + "type": "library", + "name": "espree", + "version": "10.4.0", + "bom-ref": "launchpad@1.0.0|espree@10.4.0", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/espree@10.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8fa3c0436b94afbf4f6610633f90b97e197c7b7f459919ce8ec0f99469d6ac553c8b61bbefab412bbfa73fc2ae4144d3c80654c1f42a5c082b547e4c6c7f4261" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/espree" + } + ] + }, + { + "type": "library", + "name": "esquery", + "version": "1.7.0", + "bom-ref": "launchpad@1.0.0|esquery@1.7.0", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/esquery@1.7.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "029e86d16430714fcb1ecbcbc0e3757c0417f59a7403663a63f709065f6bfc96d6f74672838ff36c6eb3cca6b639300b10b6ab60798abb41a1a4ce443beed3d2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/esquery" + } + ] + }, + { + "type": "library", + "name": "esrecurse", + "version": "4.3.0", + "bom-ref": "launchpad@1.0.0|esrecurse@4.3.0", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/esrecurse@4.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2a67ca2f76fa1be457bcff0dd6faf74ead642ffa021609f63585c4b6a3fcfcbde929aa540381bc70555aa05dd2537db7083e17ca947f7df8a81e692d8bafd36a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/esrecurse" + } + ] + }, + { + "type": "library", + "name": "estraverse", + "version": "5.3.0", + "bom-ref": "launchpad@1.0.0|estraverse@5.3.0", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/estraverse@5.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "30c74046e54443388d4de243f0380caa6870475d41450fdc04ffa92ed61d4939dfdcc20ef1f15e8883446d7dfa65d3657d4ffb03d7f7814c38f41de842cbf004" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/estraverse" + } + ] + }, + { + "type": "library", + "name": "estree-util-is-identifier-name", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|estree-util-is-identifier-name@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/estree-util-is-identifier-name@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "845b6a20365321467d0572dbf32e29606ca4ebec1e9088af3554dc9af93c3683a1f957919f9cba7041f36d446b59b7e9d5f22a7558a98a5ce3fa57da69d3599a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/estree-util-is-identifier-name" + } + ] + }, + { + "type": "library", + "name": "estree-walker", + "version": "2.0.2", + "bom-ref": "launchpad@1.0.0|estree-walker@2.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/estree-walker@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "45f924fcca7f0cbec95637b7bb5f05c45ba34254cd476aba41f312301ec0bc2071f753468ff6dade409fcdad1fe9d5436f0ed89517ff9c3ae7ee942b082c90ff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/estree-walker" + } + ] + }, + { + "type": "library", + "name": "esutils", + "version": "2.0.3", + "bom-ref": "launchpad@1.0.0|esutils@2.0.3", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/esutils@2.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "915b1ca97938382a7af126747648042958baffc8a3df4d0a0564c9ab7d8ffdd61e5934b02b8d56c93c5a94dd5e46603967d514fcb5fd0fb1564a657d480631ea" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/esutils" + } + ] + }, + { + "type": "library", + "name": "eventemitter3", + "version": "5.0.4", + "bom-ref": "launchpad@1.0.0|eventemitter3@5.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/eventemitter3@5.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9a5b1347219a3c18cf79d93a06fc3e6aa6ec5c3b680320339b930eec9814fb2551c8c4393bc6c3e0a71c8bb052f397fddef79e81e08f90bf11e062c29678cb17" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/eventemitter3" + } + ] + }, + { + "type": "library", + "name": "events", + "version": "3.3.0", + "bom-ref": "launchpad@1.0.0|events@3.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/events@3.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "990c3ed9f9106c02f343b574318d08a9d9d734e793b4fe2bd2537dcfb0006b009782a79aedb0e28b6d0062b201ac577f1f1d0cd8e733e92d75d4268591471bd1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/events" + } + ] + }, + { + "type": "library", + "name": "exsolve", + "version": "1.2.0", + "bom-ref": "launchpad@1.0.0|exsolve@1.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/exsolve@1.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "875a503d1f57a1e48c767b513428f24f39daba67b85297d7ad42c19e5919d8250cfc6e5e49afa9041c8695d3b9b91f1dc5b3c2f8eb895ec3cf35ff8967cd400e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/exsolve" + } + ] + }, + { + "type": "library", + "name": "extend", + "version": "3.0.2", + "bom-ref": "launchpad@1.0.0|extend@3.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/extend@3.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7e3aae0b9f5c0fb0b25babab3572b4141b9f9197288861bcd304ee3ee8d7e7dd1c0794ed967db4136501e12fd601156a8577df665d8b3604be81074f2088a6fe" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/extend" + } + ] + }, + { + "type": "library", + "name": "fast-deep-equal", + "version": "3.1.3", + "bom-ref": "launchpad@1.0.0|fast-deep-equal@3.1.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fast-deep-equal@3.1.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7f7a90f68432f63d808417bf1fd542f75c0b98a042094fe00ce9ca340606e61b303bb04b2a3d3d1dce4760dcfd70623efb19690c22200da8ad56cd3701347ce1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/fast-deep-equal" + } + ] + }, + { + "type": "library", + "name": "fast-glob", + "version": "3.3.3", + "bom-ref": "launchpad@1.0.0|fast-glob@3.3.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fast-glob@3.3.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ecca6d2fc53472a705773233c0e4c7a22957f71e41acdab27bb67f2ee0bb9023118a8d44312caa44adc1100503eec5d1ab8893e00cd356e65d8604364c2bd82e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/fast-glob" + } + ], + "components": [ + { + "type": "library", + "name": "glob-parent", + "version": "5.1.2", + "bom-ref": "launchpad@1.0.0|fast-glob@3.3.3|glob-parent@5.1.2", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/glob-parent@5.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "00e22049009ea62258c0fdc04671b1fb95674eed870587736c63f8e5e2f0d6faf7cc1def64b7b279dd6c0bd8676dc39cf7f4ab33233944f42b906cf8692f59a3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/fast-glob/node_modules/glob-parent" + } + ] + } + ] + }, + { + "type": "library", + "name": "fast-json-stable-stringify", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|fast-json-stable-stringify@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fast-json-stable-stringify@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "96177fc05f8b93df076684c2b6556b687b5f8795d88a32236a55dc93bb1a52db9a9d20f22ccc671e149710326a1f10fb9ac47c0f4b829aa964c23095f31bf01f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/fast-json-stable-stringify" + } + ] + }, + { + "type": "library", + "name": "fast-levenshtein", + "version": "2.0.6", + "bom-ref": "launchpad@1.0.0|fast-levenshtein@2.0.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fast-levenshtein@2.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0c25eee887e1a9c92ced364a6371f1a77cbaaa9858e522599ab58c0eb29c11148e5d641d32153d220fcf62bcf2c3fba5f63388ca1d0de0cd2d6c2e61a1d83c77" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/fast-levenshtein" + } + ] + }, + { + "type": "library", + "name": "fast-uri", + "version": "3.1.9", + "bom-ref": "launchpad@1.0.0|fast-uri@3.1.9", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/fast-uri@3.1.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "852ff45addd86b4e37a0a5ecd2c231acca4a4084d784c2c8ad500a2978b8828cc60bdbfb6115959d7219ce334f4ced3633d05dc4b096a8ad7245780dce257225" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/fast-uri" + } + ] + }, + { + "type": "library", + "name": "fast-xml-builder", + "version": "1.3.2", + "bom-ref": "launchpad@1.0.0|fast-xml-builder@1.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fast-xml-builder@1.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "397f7555295284b3c3811655eed93f610e25f2d4fbe50ce217923183c8383c56c254f8ee4d6c0dfb241f0312c9d1db9f269a6b74e77a1e533be0985ddfd4dc05" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/fast-xml-builder" + } + ] + }, + { + "type": "library", + "name": "fast-xml-parser", + "version": "5.12.1", + "bom-ref": "launchpad@1.0.0|fast-xml-parser@5.12.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fast-xml-parser@5.12.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.12.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c11f1d3bf7f1fb3f02e5ec6e7a6d5eec128e5af8ecbb3be34bfb6f03f5eedd9d7342a246717acfcd76dc02268c829d8a8eb78444e7139269e78acadc989da161" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/fast-xml-parser" + } + ] + }, + { + "type": "library", + "name": "fastest-levenshtein", + "version": "1.0.16", + "bom-ref": "launchpad@1.0.0|fastest-levenshtein@1.0.16", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fastest-levenshtein@1.0.16", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7919c2b534ed199169402c2126250ebb13d05915d52980e7d1bd8f7877d72fafd98b9dd22c0cc01df5615562b602bc82fd61f4e6419fc611483ef4c5d125d0ce" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/fastest-levenshtein" + } + ] + }, + { + "type": "library", + "name": "fastq", + "version": "1.20.3", + "bom-ref": "launchpad@1.0.0|fastq@1.20.3", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/fastq@1.20.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5cabf99e72ecea72c5ef536088a24b21914b90fc8812e3ac7a52c6eee8d99c6ad17d02bc1e9bd8f96a8a84025401d2e89b054712b552e0b7f11653ead3f15303" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/fastq" + } + ] + }, + { + "type": "library", + "name": "fdir", + "version": "6.5.0", + "bom-ref": "launchpad@1.0.0|fdir@6.5.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fdir@6.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b486d8b596ee70eb340511aa3c992c84951874bf920c7edd54cf208f2f84469dd60148cb105244fb4da46a7c87b708d63a7c2b298062c0098cd29e242c90275e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/fdir" + } + ] + }, + { + "type": "library", + "name": "fetch-blob", + "version": "3.2.0", + "bom-ref": "launchpad@1.0.0|fetch-blob@3.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fetch-blob@3.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ef2010a43d94309ccb8b50eabfba856273db68fc7b65f14ae8f888c50e0f7e418fc8dca5d94831f9afee994a2798aaa384ce039df6ccbdd5faa2d5eaf37b2841" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/fetch-blob" + } + ] + }, + { + "type": "library", + "name": "file-entry-cache", + "version": "11.1.5", + "bom-ref": "launchpad@1.0.0|file-entry-cache@11.1.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/file-entry-cache@11.1.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f8f1531c84c8d3c2481a19cda46348f13f229d4a6065f93718d12a7d3f51db3655da21578370afab34a5fee121b3b4d21ae8d84442c400dc83bd2f058fbf92ed" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/file-entry-cache" + } + ] + }, + { + "type": "library", + "name": "fill-range", + "version": "7.1.1", + "bom-ref": "launchpad@1.0.0|fill-range@7.1.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fill-range@7.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "62c1a97b75872caf19622e2d583836272dde6d1cf6ad7a300f19e57786e4401d3471cff5670f405a70b48bdced0c98ad8afb50bda23d29a2f22ab73e8415b4ca" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/fill-range" + } + ] + }, + { + "type": "library", + "name": "find-up", + "version": "5.0.0", + "bom-ref": "launchpad@1.0.0|find-up@5.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/find-up@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "efcfcf5d3d7094b2c3813cc3b3bb23abd873cf4bd70fece7fbbc32a447b87d74310a6766a9f1ac10f4319a2092408dda8c557dd5b552b2f36dac94625ba9c69e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/find-up" + } + ] + }, + { + "type": "library", + "name": "flat-cache", + "version": "6.1.23", + "bom-ref": "launchpad@1.0.0|flat-cache@6.1.23", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/flat-cache@6.1.23", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7fef8163da5393ef7cdf12b514bce52e998cd22d33fa31e6c7740448691444c5ee8d0673d64e70cf05fa8639d0f20a1a0f407eb189c32b5c99e8c4f265f51aa8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/flat-cache" + } + ] + }, + { + "type": "library", + "name": "flatted", + "version": "3.4.4", + "bom-ref": "launchpad@1.0.0|flatted@3.4.4", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/flatted@3.4.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e7ec9b841640344271687dd7e5ebc015ab54c4b7c41d2afb9fa91827ed50774994aabe1ebbd8087fa1836d61dff112628c7ae38cef06fa56b5e1294bd92792d5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/flatted" + } + ] + }, + { + "type": "library", + "name": "floating-vue", + "version": "5.4.0", + "bom-ref": "launchpad@1.0.0|floating-vue@5.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/floating-vue@5.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/floating-vue/-/floating-vue-5.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "85be72e4df2c5ecf43cb88997d604a2f37f7164524aa16e441112146e94012f22284c9521b173fee95c6ac80deb68a979bf4511cd563bcdea5aa5f4884c33eb5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/floating-vue" + } + ] + }, + { + "type": "library", + "name": "focus-trap", + "version": "8.2.5", + "bom-ref": "launchpad@1.0.0|focus-trap@8.2.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/focus-trap@8.2.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/focus-trap/-/focus-trap-8.2.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "56ba9fc915da1d9d049215e57f26a5b339a19d237dca37585f09702d246826b0c9d3f7acc18e49e40be3fc771dfcface1c2327b0c870c7bfbbfacd649aff40b2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/focus-trap" + } + ] + }, + { + "type": "library", + "name": "follow-redirects", + "version": "1.16.3", + "bom-ref": "launchpad@1.0.0|follow-redirects@1.16.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/follow-redirects@1.16.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b68392a2a37a779d568dfd5a38525872856fd5a343f6b8ff0b08cb534573e34a03b92a560dac8278a7b82692f934bd16745be838e088dc1468ebd1da8636d1d4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/follow-redirects" + } + ] + }, + { + "type": "library", + "name": "form-data", + "version": "4.0.6", + "bom-ref": "launchpad@1.0.0|form-data@4.0.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/form-data@4.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bca6ad021e129557e06eff98b66862463844309b18a6c1b5636acc42d47e49549bcadb120f5606cc321cac026674579cf3cbbff95a069b19e5fbcd202f5b5109" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/form-data" + } + ] + }, + { + "type": "library", + "name": "formdata-polyfill", + "version": "4.0.10", + "bom-ref": "launchpad@1.0.0|formdata-polyfill@4.0.10", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/formdata-polyfill@4.0.10", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6ee7b01f332f60bdbd8dd7904d520b79c49a64a9edfd12568e8642179396eb467aeff1a648b06438533baa1d4f237cc536d25b6992f9790bb5bcb7daccec23e2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/formdata-polyfill" + } + ] + }, + { + "type": "library", + "name": "fsevents", + "version": "2.3.3", + "bom-ref": "launchpad@1.0.0|fsevents@2.3.3", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/fsevents@2.3.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e71a037d7f9f2fb7da0139da82658fa5b16dc21fd1efb5a630caaa1c64bae42defbc1d181eb805f81d58999df8e35b4c8f99fade4d36d765cda09c339617df43" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/fsevents" + } + ] + }, + { + "type": "library", + "name": "function-bind", + "version": "1.1.2", + "bom-ref": "launchpad@1.0.0|function-bind@1.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/function-bind@1.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ed71cdc47eea5fdc46e66230c6486e993a31fcc21135c3a00ebc56b0cb76a40af6dd61e9e8cad194dec50521690a9afea153b417be38894811f369c931f1b648" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/function-bind" + } + ] + }, + { + "type": "library", + "name": "get-east-asian-width", + "version": "1.6.0", + "bom-ref": "launchpad@1.0.0|get-east-asian-width@1.6.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/get-east-asian-width@1.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4116ef0c86f1e9892551ee91c5e4de95e311d32bf77181fa3ec3d91dc9d59fbc6fef33b504737caf45c44eef27e987b743e6a1b526ab7375a0b4d5a67a12017c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/get-east-asian-width" + } + ] + }, + { + "type": "library", + "name": "get-intrinsic", + "version": "1.3.0", + "bom-ref": "launchpad@1.0.0|get-intrinsic@1.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/get-intrinsic@1.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f5f4a349aa2cfdf448548a7ec5226513a95fc21112ecb36d29a08121a987b23af69dad418800493e8d263a38f3f062435116ab9823c6a9a89583999f8dbf7c09" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/get-intrinsic" + } + ] + }, + { + "type": "library", + "name": "get-proto", + "version": "1.0.1", + "bom-ref": "launchpad@1.0.0|get-proto@1.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/get-proto@1.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b1349f063a17069f3d26f20a21e7eac3b53608279bb1cef892263a6b0886a202ada1219b823604fc6ffe97db05dcc5853cd73d21ca0e0b83837ca1dfc459a9d2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/get-proto" + } + ] + }, + { + "type": "library", + "name": "glob-parent", + "version": "6.0.2", + "bom-ref": "launchpad@1.0.0|glob-parent@6.0.2", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/glob-parent@6.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5f1c08f043a1550816a7a8832feddbd2bf3a7f877a017eb3494e791df078c9d084b972d773915c61e3aefa79c67ed4b84c48eeff5d6bb782893d33206df9afe0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/glob-parent" + } + ] + }, + { + "type": "library", + "name": "global-modules", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|global-modules@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/global-modules@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/global-modules/-/global-modules-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3466df989069f71f08c722527753fea2d60af2fa27a0969cb4ea20ad57c5448004635ba48a5f1148a0f3d98a3bc21d688a1979d65febe96e1ea6478a247a8bf0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/global-modules" + } + ] + }, + { + "type": "library", + "name": "global-prefix", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|global-prefix@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/global-prefix@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/global-prefix/-/global-prefix-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6b00a89c9495087546343eb1ded98c68a710bf05cb8637649a89b2d96f86a1aba2f183e06205c965ec218377d60be0e57eaa90b9683c030aa31930f69c03d55a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/global-prefix" + } + ], + "components": [ + { + "type": "library", + "name": "which", + "version": "1.3.1", + "bom-ref": "launchpad@1.0.0|global-prefix@3.0.0|which@1.3.1", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/which@1.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1f125d616ab53132106c9de7c3472ab2c1e84cd536ebb2a5ac3b866755989710d2b54b4a52139a266875d76fd36661f1c547ee26a3d748e9bbb43c9ab3439221" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/global-prefix/node_modules/which" + } + ] + } + ] + }, + { + "type": "library", + "name": "globby", + "version": "16.2.4", + "bom-ref": "launchpad@1.0.0|globby@16.2.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/globby@16.2.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/globby/-/globby-16.2.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "73c07f54d2e6c51726aaa7a7440f6dfbd2323a37fdf95ea54f13da5092ea38238d7509166741136205f4a9bb49a8fb2008dbac4fd319e497a2770f046fdb67da" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/globby" + } + ], + "components": [ + { + "type": "library", + "name": "ignore", + "version": "7.0.6", + "bom-ref": "launchpad@1.0.0|globby@16.2.4|ignore@7.0.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ignore@7.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ignore/-/ignore-7.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "04083a42413c5be4ee40baebc34520afb1de81776e46eba3f3fb62da448e73e8f3d5d9b1f3f58d723afa5c69eae58a435b1170c1a6afa83d3e8c850e29e953b3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/globby/node_modules/ignore" + } + ] + } + ] + }, + { + "type": "library", + "name": "globjoin", + "version": "0.1.4", + "bom-ref": "launchpad@1.0.0|globjoin@0.1.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/globjoin@0.1.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/globjoin/-/globjoin-0.1.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c587e7c3ad82286f272e46417d66e15b00f0d36087b72f3a8df3dc73672bdd97deb8af72b2854f3c45317f6d5b003feb580824e764ae06b2c995e7cdcbc9af16" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/globjoin" + } + ] + }, + { + "type": "library", + "name": "gopd", + "version": "1.2.0", + "bom-ref": "launchpad@1.0.0|gopd@1.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/gopd@1.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "65429187afe4505a0089302d4d83d9277870f70371c7e04804e8a39e51bd3e7ac9b027128ecd70cb20fabc9a5a62d827cc3aca6114aa7f738ee917daf77c6c46" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/gopd" + } + ] + }, + { + "type": "library", + "name": "graceful-fs", + "version": "4.2.11", + "bom-ref": "launchpad@1.0.0|graceful-fs@4.2.11", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/graceful-fs@4.2.11", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "45b279fe398570d342703579a3d7939c12c9fc7b33595d0fef76dcf857f89d2feb263f98692e881b288e2f45680585fe9755ab97793ade1fcaac7fa7849d17bd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/graceful-fs" + } + ] + }, + { + "type": "library", + "name": "gridstack", + "version": "13.3.0", + "bom-ref": "launchpad@1.0.0|gridstack@13.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/gridstack@13.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/gridstack/-/gridstack-13.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d6da85777fe16f70923895851bc68595e086593e86ab1fe19e3453efca1c9e2c69d173e4e406ba531926d2a9fd5471702eb11d3856fe657b50653f9afc8752de" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/gridstack" + } + ] + }, + { + "type": "library", + "name": "has-flag", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|has-flag@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/has-flag@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1329094ff4352a34d672da698080207d23b4b4a56e6548e180caf5ee4a93ba6325e807efdc421295e53ba99533a170c54c01d30c2e0d3a81bf67153712f94c3d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/has-flag" + } + ] + }, + { + "type": "library", + "name": "has-symbols", + "version": "1.1.0", + "bom-ref": "launchpad@1.0.0|has-symbols@1.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/has-symbols@1.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d5c0cd77027625aa2199bdec8383a629a301c2e0b8f2c6278b91d4c360efb02f0b8c64cb2bd87e79bd57e91cae3877b8853d142c25baf22a26863528294aa53d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/has-symbols" + } + ] + }, + { + "type": "library", + "name": "has-tostringtag", + "version": "1.0.2", + "bom-ref": "launchpad@1.0.0|has-tostringtag@1.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/has-tostringtag@1.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "36a00307c5633c52ccd95d15bc751ec30c2cc3465605a21d828fa2787b4ade16ac2f3e2a78246361ca9f07a010ac182044aa69285f0be76fd5a9d56c3b8ec397" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/has-tostringtag" + } + ] + }, + { + "type": "library", + "name": "hash-sum", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|hash-sum@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hash-sum@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hash-sum/-/hash-sum-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "59d6536c00720fea477e5fe0f504ac048230cbc213f84b0f88a0ecd0a357fb348785d0cb14a759bb40501e58ef3bed1023f05ab1b31251af3060d0994ef86c96" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/hash-sum" + } + ] + }, + { + "type": "library", + "name": "hashery", + "version": "1.5.1", + "bom-ref": "launchpad@1.0.0|hashery@1.5.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hashery@1.5.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "899c8a1bdebf2703f3d4de79be3d887b6bd76e1bb8e34cdf51f26f4b012a11b78b96e93b3676a97c6a9aecb1f498eb270f14c5f39331f3f77247a1dfa9c6e66d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/hashery" + } + ] + }, + { + "type": "library", + "name": "hasown", + "version": "2.0.4", + "bom-ref": "launchpad@1.0.0|hasown@2.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hasown@2.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4f651b7db044177db089ea5722c3254d6f7e743602eb0321fedfef600e2db8e30aa96cff9f7bebd4d152c508b23fece4da65eca0c03f8bfeea57a2cabadd6dd4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/hasown" + } + ] + }, + { + "type": "library", + "name": "hast-util-is-element", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|hast-util-is-element@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hast-util-is-element@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "55a97d9a7bf6216a4b6cd3ea73fa547a6f9aec8a63d9a1da702c2035f4e22b4bc92a5d0b17ee016b8fafd683c71697f76cb626adeab4fe5dc6b9df52e4e1f8da" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/hast-util-is-element" + } + ] + }, + { + "type": "library", + "name": "hast-util-to-jsx-runtime", + "version": "2.3.7", + "bom-ref": "launchpad@1.0.0|hast-util-to-jsx-runtime@2.3.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hast-util-to-jsx-runtime@2.3.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "17b0cd57634c713c40e06a8f5479d7cd7fa6a683c700863dac90151f7099d4574164e7015048d4baf3243291d5b3fb22704b739e1f6d3068f959447d4b8136ae" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/hast-util-to-jsx-runtime" + } + ] + }, + { + "type": "library", + "name": "hast-util-to-text", + "version": "4.0.3", + "bom-ref": "launchpad@1.0.0|hast-util-to-text@4.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hast-util-to-text@4.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e72ae558ebc616ce82a87ae25294ac36b8f34ff4dda3e20e42e75bce7c4e9fc2b9a9b969d7c309cb33a0f0880338a43c31881070903b4aeb2e0a34a90ebf2648" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/hast-util-to-text" + } + ] + }, + { + "type": "library", + "name": "hast-util-whitespace", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|hast-util-whitespace@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hast-util-whitespace@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f3c254374ea2a4bc2c9eff9d567f8e2183af02ebc1332fd0a22e8eee6407c5d3d7a63cbe09deb14645b0bb1ec328efb8b1820bb4b05120a82c7694b681073bab" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/hast-util-whitespace" + } + ] + }, + { + "type": "library", + "name": "highlight.js", + "version": "11.11.2", + "bom-ref": "launchpad@1.0.0|highlight.js@11.11.2", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/highlight.js@11.11.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.11.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a1a5cc002014d24cce3170635a935c5febe5c12042200899f411daee0035e4d393b53d8bfe5f0e4990eea92d97a693a16413c9ee19b8a3c7a9da4cae8a9dae11" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/highlight.js" + } + ] + }, + { + "type": "library", + "name": "hookable", + "version": "5.5.3", + "bom-ref": "launchpad@1.0.0|hookable@5.5.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hookable@5.5.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "61cf8141ef12be85c7d7ae3741ecf5cea2d199b039ac22feb129a4e93568b342d655f34807b3c69dc76521defb5b32c648807929a5a04da353b3694d54423a55" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/hookable" + } + ] + }, + { + "type": "library", + "name": "hookified", + "version": "1.15.1", + "bom-ref": "launchpad@1.0.0|hookified@1.15.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hookified@1.15.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "32f1bf725b000ead463ccd8a1a8da7c9f6965729fd9da3e25eba887b88d88d735942ddb7f245b2386aecc9cfc3991010f917bac9ea3ac97ff2a0d086e4a00456" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/hookified" + } + ] + }, + { + "type": "library", + "name": "hot-patcher", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|hot-patcher@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hot-patcher@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hot-patcher/-/hot-patcher-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1028352451b46337a189c41aa207a795cb36aa0e96b1742cc6d9dbaf58baf7abb9b4b523b49750021d2eda0d10e58578e5fdbadd36b51a7509b1cf1621f25fe1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/hot-patcher" + } + ] + }, + { + "type": "library", + "name": "html-tags", + "version": "5.1.0", + "bom-ref": "launchpad@1.0.0|html-tags@5.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/html-tags@5.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/html-tags/-/html-tags-5.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9fa979b9c6bbff2e63a316772d478f87398115427e536616ce131af1751379c49e4a542265d1795c077f437fd6525d15b17814c168bc23b08d230748e5637549" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/html-tags" + } + ] + }, + { + "type": "library", + "name": "htmlparser2", + "version": "8.0.2", + "bom-ref": "launchpad@1.0.0|htmlparser2@8.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/htmlparser2@8.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "19876358a0e46d12e467981eb87b39358d69b89f8f5f03fbf9f1cf473d3a122aec6fdba07fa77c9245dabfa00385c38384514f3085f2c64c52b8c7f70fa34214" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/htmlparser2" + } + ], + "components": [ + { + "type": "library", + "name": "entities", + "version": "4.5.0", + "bom-ref": "launchpad@1.0.0|htmlparser2@8.0.2|entities@4.5.0", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/entities@4.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5748631f87463e1f40a39a74328458e8156ab700a3873eaf2392d3f00279e47fb883dff8bdb1f1d48e787d2d17b9c94b8431c0acf40288c8c3c6368bf1f3f187" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/htmlparser2/node_modules/entities" + } + ] + } + ] + }, + { + "type": "library", + "name": "https-proxy-agent", + "version": "5.0.1", + "bom-ref": "launchpad@1.0.0|https-proxy-agent@5.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/https-proxy-agent@5.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7457008e94d0160a0b3330b657053e0bf09b4bbb912f49569b10c84e6aa6ec2fbb17439d9a3eacf65e9a95973a0042d786b9e080cd827964971c639d5f662dc0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/https-proxy-agent" + } + ] + }, + { + "type": "library", + "name": "ignore", + "version": "5.3.2", + "bom-ref": "launchpad@1.0.0|ignore@5.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ignore@5.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "86c053354a904c3c245ad71d608da2d3a63f9d4044b0d10324a8d676280bbde832f240ee2404bcb91969924710a721172f467fa630f2e4706632344227682afa" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/ignore" + } + ] + }, + { + "type": "library", + "name": "immutable", + "version": "5.1.9", + "bom-ref": "launchpad@1.0.0|immutable@5.1.9", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/immutable@5.1.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/immutable/-/immutable-5.1.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9bc9d57b3debc2b8265b1b4b32dd596170762efece2989ff762b32c409520d8025292945a0f3df20098033f339c6a2f89b80bfc003f0ed2dbf08d6948a2d47c6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/immutable" + } + ] + }, + { + "type": "library", + "name": "import-fresh", + "version": "3.3.1", + "bom-ref": "launchpad@1.0.0|import-fresh@3.3.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/import-fresh@3.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4d1dca7eb4d94d82cf07a8d48dfc7a305f56716ac72fdb2ee5339b2b866462005d58a3ce1684a8408744b93b91f36a66b711f6b29586f61e9eb707ebd692c1a9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/import-fresh" + } + ] + }, + { + "type": "library", + "name": "import-meta-resolve", + "version": "4.2.0", + "bom-ref": "launchpad@1.0.0|import-meta-resolve@4.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/import-meta-resolve@4.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "22abf67f369340ddbcb3f170640a05ab4652b3fee13001c9557fb0f0f665ddc635f4fc64ea31456a5c50a087d6dbcdba8bf7c32d7bfc2221194484f4943b9672" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/import-meta-resolve" + } + ] + }, + { + "type": "library", + "name": "imurmurhash", + "version": "0.1.4", + "bom-ref": "launchpad@1.0.0|imurmurhash@0.1.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/imurmurhash@0.1.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2665cc67ac2ebc398b88712697dca4cea3ba97015ba1fd061b822470668435d0910c398c5679f2eece47b0880709b6aad30d8cc8f843aa48535204b62d4d8f1c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/imurmurhash" + } + ] + }, + { + "type": "library", + "name": "ini", + "version": "1.3.8", + "bom-ref": "launchpad@1.0.0|ini@1.3.8", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/ini@1.3.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "255ff2ba0576bb35b988c4528990320ed41dfa7c6d5278de2edd1a70d770f7c90a2ebbee455c81f34b6c444384ef2bc65606a5859e913570a61079142812b17b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/ini" + } + ] + }, + { + "type": "library", + "name": "inline-style-parser", + "version": "0.2.9", + "bom-ref": "launchpad@1.0.0|inline-style-parser@0.2.9", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/inline-style-parser@0.2.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "22db4df01a8a2f1cd4ae74ea1c8fbf870009408b410148dda07111083bfea0eb97e3c54fe9bcd6f3e42339749fa1ebf3ab762b600c17d6e2c7a7c4ea3bdc887a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/inline-style-parser" + } + ] + }, + { + "type": "library", + "name": "is-absolute-url", + "version": "4.0.1", + "bom-ref": "launchpad@1.0.0|is-absolute-url@4.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-absolute-url@4.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-absolute-url/-/is-absolute-url-4.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ff9d7f4ca13cf0b9a6ec6738ffc6ed725357592fa0e74c1785826af07588040194067a00751bb56977a1dfae2dfceef05c301c4c90cff0f36e34a5940d689ef8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-absolute-url" + } + ] + }, + { + "type": "library", + "name": "is-alphabetical", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|is-alphabetical@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-alphabetical@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "156cb263ad0c79337279246990cd88af2d06f61a6befff640f8d260ff706404ba295c6584b8a24cfc48dd90eab2c227c81b0ade9f37eac2fbab4c192f7d2dac5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-alphabetical" + } + ] + }, + { + "type": "library", + "name": "is-alphanumerical", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|is-alphanumerical@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-alphanumerical@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8666d8857ffd314305e6e87bb4e5f22bf9f466f5a969de5c681035ec6b02eafcae0aa696962446e4ad6a4bd8a799484431a381216effc210274b0bde5bf2ed67" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-alphanumerical" + } + ] + }, + { + "type": "library", + "name": "is-arrayish", + "version": "0.2.1", + "bom-ref": "launchpad@1.0.0|is-arrayish@0.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-arrayish@0.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cf3d3a4bcb74a33a035cc1beb9b7b6eb37824cd5dc2883c96498bc841ac5e227422e6b38086f50b4aeea065d5ba22e4e0f31698ecc1be493e61c26cca63698ce" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-arrayish" + } + ] + }, + { + "type": "library", + "name": "is-buffer", + "version": "1.1.6", + "bom-ref": "launchpad@1.0.0|is-buffer@1.1.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-buffer@1.1.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "35c7402f0a579139b966fbdb93ba303944af56f04a0e028fe7f7b07d71339e64057ece194666a739e2814e34558e46b7405a0de9727ef45dd44aa7c7a93694e7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-buffer" + } + ] + }, + { + "type": "library", + "name": "is-decimal", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|is-decimal@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-decimal@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "00007d862a2642ce435d6711075aeab31194b2d6d1ae814e3cf540a26364ff75c74792721190a13b24d67b6a1ac8a9ec4acaff91c1aa17ecfacae1fa1c7a4dd0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-decimal" + } + ] + }, + { + "type": "library", + "name": "is-extglob", + "version": "2.1.1", + "bom-ref": "launchpad@1.0.0|is-extglob@2.1.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-extglob@2.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "49b29b00d90deb4dd58b88c466fe3d2de549327e321b0b1bcd9c28ac4a32122badb0dde725875b3b7eb37e1189e90103a4e6481640ed9eae494719af9778eca1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-extglob" + } + ] + }, + { + "type": "library", + "name": "is-fullwidth-code-point", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|is-fullwidth-code-point@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-fullwidth-code-point@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cf29a6e7ebbeb02b125b20fda8d69e8d5dc316f84229c94a762cd868952e1c0f3744b8dbee74ae1a775d0871afd2193e298ec130096c59e2b851e83a115e9742" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-fullwidth-code-point" + } + ] + }, + { + "type": "library", + "name": "is-glob", + "version": "4.0.3", + "bom-ref": "launchpad@1.0.0|is-glob@4.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-glob@4.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c5e9526b21c7dfa66013b6568658bba56df884d6cd97c3a3bf92959a4243e2105d0f7b61f137e4f6f61ab0b33e99758e6611648197f184b4a7af046be1e9524a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-glob" + } + ] + }, + { + "type": "library", + "name": "is-hexadecimal", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|is-hexadecimal@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-hexadecimal@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0e0650a76e3573ca0ee9c03549b4c45a25dea31578daf95c271807f81de18b5022aaa2abb9947764617c227ddf8f8fbfcbfeeb1ef94e64b66d809ff8b6d60666" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-hexadecimal" + } + ] + }, + { + "type": "library", + "name": "is-number", + "version": "7.0.0", + "bom-ref": "launchpad@1.0.0|is-number@7.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-number@7.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e350a27e483a7bc4f2952a5db53a5e2d532abd20445734edb47bc4443ef8d7ea6767c00dbf4d34e0c44be3740a3c394af5c1af369e8d6566540656c65d8c719e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-number" + } + ] + }, + { + "type": "library", + "name": "is-path-inside", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|is-path-inside@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-path-inside@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "949255ff97584be45c2fcb907410d6f5cf6e5852cb04d4721619c0297c39b55a8b94a67844c1992aff9843f200dce843f91a5b25ad4b2c53351503c6c885ef38" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-path-inside" + } + ] + }, + { + "type": "library", + "name": "is-plain-obj", + "version": "4.1.0", + "bom-ref": "launchpad@1.0.0|is-plain-obj@4.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-plain-obj@4.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f8f822faf32e50d909c84c62301b792251683322a7af9ce127852ca73e7c58e841179428219905c8d1c86c102d1f0cd502093946d9dd54db0344deb5fe6983aa" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-plain-obj" + } + ] + }, + { + "type": "library", + "name": "is-plain-object", + "version": "5.1.0", + "bom-ref": "launchpad@1.0.0|is-plain-object@5.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-plain-object@5.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6d48bfca39ad298711554b56446af4500eb110587623acd653032b517077b3b6e6602699f1afb466c4d192b6b087f9b39520f56343e1f1ba7f53e4ef06958337" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-plain-object" + } + ] + }, + { + "type": "library", + "name": "is-retry-allowed", + "version": "2.2.0", + "bom-ref": "launchpad@1.0.0|is-retry-allowed@2.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-retry-allowed@2.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-2.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5d59bb2ce78ba535b88d5d7d4121f7f2f92cc31a0bb9df2c439ed8c095533d6762688f48f24784846169065b25c95b20750cb83a983c40e2dbf18460b3266242" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-retry-allowed" + } + ] + }, + { + "type": "library", + "name": "is-svg", + "version": "6.1.0", + "bom-ref": "launchpad@1.0.0|is-svg@6.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-svg@6.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-svg/-/is-svg-6.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8bb60f76f62e48261c68b42b2b0b7c72f2939701dc740e87a7c37d48edd0e63233a3cc7a907dcde3b5b406f3cfecd7715419881f1ed7f432b7e9ccd8616ee51e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-svg" + } + ] + }, + { + "type": "library", + "name": "is-unsafe", + "version": "2.0.3", + "bom-ref": "launchpad@1.0.0|is-unsafe@2.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/is-unsafe@2.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6419657330823b6ebbbe07456fa4eade9bfe2e11da0a218c76bf99b2e2fe3a8a6bb8083b4bedd90ecd6f0f444f0b4b92ae48f36eb6b16868ed5f5601c633de15" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/is-unsafe" + } + ] + }, + { + "type": "library", + "name": "isexe", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|isexe@2.0.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/isexe@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "447c4c2e9f659ca1c61d19e0f5016144231b600715a67ebdb2648672addfdfac638155564e18f8aaa2db4cb96aed2b23f01f9f210d44b8210623694ab3241e23" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/isexe" + } + ] + }, + { + "type": "library", + "name": "jest-worker", + "version": "27.5.1", + "bom-ref": "launchpad@1.0.0|jest-worker@27.5.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/jest-worker@27.5.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "eefba1f3957971d0e87cfcb19f9f27acf8c192d668d2ef71d60f16b6342897e8d90da13e7e137e708bd38f5d469dd067327c9fad4386d6c650c427632a1f832a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/jest-worker" + } + ], + "components": [ + { + "type": "library", + "name": "supports-color", + "version": "8.1.1", + "bom-ref": "launchpad@1.0.0|jest-worker@27.5.1|supports-color@8.1.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/supports-color@8.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3295043763a876d533c6f29097bd9c505ed14391221ec1af4ac546d226bd73945b5862f6088e02ec4a4f4bc513048a659e5cd988db95e7ac3e16e371cb7b72d9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/jest-worker/node_modules/supports-color" + } + ] + } + ] + }, + { + "type": "library", + "name": "js-yaml", + "version": "4.3.2", + "bom-ref": "launchpad@1.0.0|js-yaml@4.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/js-yaml@4.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "48534ebd227e0e07fff409fdd38631f828129483c2908a5aa38aa8e7596979edb94c845e8dd1f7ae1478119306a0dc77fd33f73bec335ae893165e2ca9b96dcc" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/js-yaml" + } + ] + }, + { + "type": "library", + "name": "json-parse-even-better-errors", + "version": "2.3.1", + "bom-ref": "launchpad@1.0.0|json-parse-even-better-errors@2.3.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/json-parse-even-better-errors@2.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c72170ca1ae8fc91287fa1a17b68b3d8d717a23dac96836c5abfd7b044432bfa223c27da36197938d7e9fa341d01945043420958dcc7f7321917b962f75921db" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/json-parse-even-better-errors" + } + ] + }, + { + "type": "library", + "name": "json-schema-traverse", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|json-schema-traverse@1.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/json-schema-traverse@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "34cf3f3fd9f75e35e12199f594b86415a0024ce5114178d6855e0103f4673aff31be0aadaa9017f483b89914314b1d51968e2dab37aa6f4b0e96bb9a3b2dddba" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/json-schema-traverse" + } + ] + }, + { + "type": "library", + "name": "json-stable-stringify-without-jsonify", + "version": "1.0.1", + "bom-ref": "launchpad@1.0.0|json-stable-stringify-without-jsonify@1.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/json-stable-stringify-without-jsonify@1.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "05d6e8cbe97bb40dce196e858f21475a43f92ee0728f54e4df72e3caad1ac72cdd93dfff2528b6bb77cfd504a677528dc2ae9538a606940bbcec28ac562afa3f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/json-stable-stringify-without-jsonify" + } + ] + }, + { + "type": "library", + "name": "keyv", + "version": "5.6.0", + "bom-ref": "launchpad@1.0.0|keyv@5.6.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/keyv@5.6.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0980c3dd23adb07b725de10e458471daa06da432458d14c65d4b66344306cb360e2a3d53137b7271d961a3b900d547f1f4e616673839d901411802d38abcc34b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/keyv" + } + ] + }, + { + "type": "library", + "name": "kind-of", + "version": "6.0.3", + "bom-ref": "launchpad@1.0.0|kind-of@6.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/kind-of@6.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "75c4b5ba5fbdb66783f794fec76f3f7a12e077d98435adcbb2f0d3b739b7bf20443bb44fa6dbc00feb78e165576948d305172ba45785942f160abb94478e7a87" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/kind-of" + } + ] + }, + { + "type": "library", + "name": "known-css-properties", + "version": "0.37.0", + "bom-ref": "launchpad@1.0.0|known-css-properties@0.37.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/known-css-properties@0.37.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2420ebb0fe19d526fd2701b4689f04a36afb9383aee4cc264e14bfea57087b5202c9bed404928644851476a736012744ff8da5833eb31549f300886d5e7055ad" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/known-css-properties" + } + ] + }, + { + "type": "library", + "name": "layerr", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|layerr@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/layerr@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/layerr/-/layerr-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b6fef9e0a8b6757a4f540a4eae34f2468e3f41e8156fd79516ae268eaa78f8d33935a5fbb3242f37904135f57f6690070841d5db85dd515ac102891ae23b77a4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/layerr" + } + ] + }, + { + "type": "library", + "name": "leaflet.markercluster", + "version": "1.5.3", + "bom-ref": "launchpad@1.0.0|leaflet.markercluster@1.5.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/leaflet.markercluster@1.5.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/leaflet.markercluster/-/leaflet.markercluster-1.5.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bcf4f0fc19ddabb7901e32c15655a99c678b6b7b7edf31a2b8cedf2700a488c16afa7991b86dd12377fb7f83784c35fb4f83696c05e9476f8d4d148419f09278" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/leaflet.markercluster" + } + ] + }, + { + "type": "library", + "name": "leaflet", + "version": "1.9.4", + "bom-ref": "launchpad@1.0.0|leaflet@1.9.4", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/leaflet@1.9.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9f14b5ca7cc93a63a51e9fa22f71725aa2bcf46b4d2fc53caef94c3ac41d4d3b2cc59c025e1f0dd8d07718340e2fe611dd79d6c99031c108b15116fe140ef83c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/leaflet" + } + ] + }, + { + "type": "library", + "name": "levn", + "version": "0.4.1", + "bom-ref": "launchpad@1.0.0|levn@0.4.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/levn@0.4.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f9b4f6b87e04e4b184ee1fe7ddebdc4bfb109495c2a48a7aca6f0e589e5e57afbaec3b2a97f2da693eea24102ddabcdfa1aff94011818710e2c7574cb7691029" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/levn" + } + ] + }, + { + "type": "library", + "name": "lightningcss-android-arm64", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-android-arm64@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-android-arm64@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "804a514da94a768b29e016fca96b5cda23a013949e2079694b5ba9f5b16adb003262197551d4ce6d88877bdf3310cf5242f4a8a906752100f424da60dcc979a6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-android-arm64" + } + ] + }, + { + "type": "library", + "name": "lightningcss-darwin-arm64", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-darwin-arm64@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-darwin-arm64@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "49c89acfc79e9cd4ca9fd6f7b7bfb1af48a94e9f58c4a418e27a704379ab46e2f404054704bc99c687e168a04056dce6b5167fcd3ca8d3fb68e01d6e586fc38e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-darwin-arm64" + } + ] + }, + { + "type": "library", + "name": "lightningcss-darwin-x64", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-darwin-x64@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-darwin-x64@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "67950f031ceb8e558d3721b2ea2eb9709cf3be02790f74fac0cbecfa05a963d77ba9184036bc6a029e8b871220661584c35f117c94c6711c63b8b201afe9bc5d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-darwin-x64" + } + ] + }, + { + "type": "library", + "name": "lightningcss-freebsd-x64", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-freebsd-x64@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-freebsd-x64@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "41033f4e2fe141a8c9c0263e4625ae099f6c76d23f5d093b9c32b9bc2f2491dc22c5ecce94382f0f1efe453f908cae857054f8329b2ea019c7228fcedd2b5146" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-freebsd-x64" + } + ] + }, + { + "type": "library", + "name": "lightningcss-linux-arm-gnueabihf", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-linux-arm-gnueabihf@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-linux-arm-gnueabihf@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "37b15505eea24b6e0c94ce91ff84414f11a14217991aceed890f54df652d17be4dccfe50ef158f46a2c108ac65450464deb6358c220f2f3c7b5b33a1b942112d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-linux-arm-gnueabihf" + } + ] + }, + { + "type": "library", + "name": "lightningcss-linux-arm64-gnu", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-linux-arm64-gnu@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-linux-arm64-gnu@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8f6bff8ad9b2e0794dc6573abe829762006a362d0d8362d2860e33ec6b9fa4482cd393fedacb815728bd23a607ab9ba8545c7d1138a7dde08484b5725c64272a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-linux-arm64-gnu" + } + ] + }, + { + "type": "library", + "name": "lightningcss-linux-arm64-musl", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-linux-arm64-musl@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-linux-arm64-musl@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ca23b944e32e6108176c2eb4ca3654e4261215918a5cbd071404d7b7d987267d7ecd6e79a02b4c23d35f7158582cc1432fb815ee804fa27fc498c3068363afb5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-linux-arm64-musl" + } + ] + }, + { + "type": "library", + "name": "lightningcss-linux-x64-gnu", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-linux-x64-gnu@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-linux-x64-gnu@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6abf89bbb2e670dd09a381692f88691726f0346f7fdc0fc1af9296da7da3c8e0e0dcc1195da0d800375e9a8352f810cd7cc80abf29492e3e12e6dc9101cb6e02" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-linux-x64-gnu" + } + ] + }, + { + "type": "library", + "name": "lightningcss-linux-x64-musl", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-linux-x64-musl@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-linux-x64-musl@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4588986e4a24c34b6b7caaaacdf179e658229f010fac3dce2437d3b89cc5b3530aea21670de9dacf57ea2cbb57e084c6dce92d2505ce7936b0d5ac2b0409593f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-linux-x64-musl" + } + ] + }, + { + "type": "library", + "name": "lightningcss-win32-arm64-msvc", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-win32-arm64-msvc@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-win32-arm64-msvc@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d4af8c3df2d2155a69873a5d6df92195693ac01ad339b0734b64fa75bd743cd399811f46a15b005b3c0dcae8546186d3a76de3fb846b9dc7ee8d9e2e0335efc0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-win32-arm64-msvc" + } + ] + }, + { + "type": "library", + "name": "lightningcss-win32-x64-msvc", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss-win32-x64-msvc@1.33.0", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss-win32-x64-msvc@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3a5108083c7f5e5d05a92a786ebcbccc59c2bc6a628371a5e200aabaf6301eea892840b5fa7f4d8039e216fa871a632fd5992a0c9ac3a8a292ca44c35fe7a1b8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss-win32-x64-msvc" + } + ] + }, + { + "type": "library", + "name": "lightningcss", + "version": "1.33.0", + "bom-ref": "launchpad@1.0.0|lightningcss@1.33.0", + "licenses": [ + { + "license": { + "id": "MPL-2.0" + } + } + ], + "purl": "pkg:npm/lightningcss@1.33.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5a4503ae88ee26cd3192019fdae756c5adf21814713edc54901efd8ba68264b46073b3ccf1f65ef53a2c7cf0dcbc4a5065bb850129c762644b04b51b98b38820" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lightningcss" + } + ] + }, + { + "type": "library", + "name": "lines-and-columns", + "version": "1.2.4", + "bom-ref": "launchpad@1.0.0|lines-and-columns@1.2.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/lines-and-columns@1.2.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ef297295eb1943f3d5dbd8e110397751f8e8e995fb802a89af917b3caaea73ddefedfcd2ca6b75069c0453c9c0517b3cab3cefaa16e384ae50660e8cb7f1e406" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lines-and-columns" + } + ] + }, + { + "type": "library", + "name": "linkifyjs", + "version": "4.4.0", + "bom-ref": "launchpad@1.0.0|linkifyjs@4.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/linkifyjs@4.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2274dec6fb5b6a2fb673e74454671ce8ee8fd83315222c03f5afe2e3316ba1acce2182ce4ba152566009ee415eba69c2331ebf810a8d0246d4be032e6d5e3e30" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/linkifyjs" + } + ] + }, + { + "type": "library", + "name": "local-pkg", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|local-pkg@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/local-pkg@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/local-pkg/-/local-pkg-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c6f4cdc0cdbb12953e7e42d2a68df73eafe79bc9b9ccd7f4694fe11785b864cf511d08d565ae4a4e699723313356c748d3d34e52a8f47631e14eff7ab14a3049" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/local-pkg" + } + ] + }, + { + "type": "library", + "name": "locate-path", + "version": "6.0.0", + "bom-ref": "launchpad@1.0.0|locate-path@6.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/locate-path@6.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "88f64ae9e6236f146edee078fd667712c10830914ca80a28a65dd1fb3baad148dc026fcc3ba282c1e0e03df3f77a54f3b6828fdcab67547c539f63470520d553" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/locate-path" + } + ] + }, + { + "type": "library", + "name": "lodash.truncate", + "version": "4.4.2", + "bom-ref": "launchpad@1.0.0|lodash.truncate@4.4.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/lodash.truncate@4.4.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8edb6645eedb46c7b9d8eb1620c0cb697c56a91026b4851c70043781aaef882a898da7d739f34c3b4c8c7cda5d0facdb19a4d4d0fe4dcfb7bb8004fa70a98947" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/lodash.truncate" + } + ] + }, + { + "type": "library", + "name": "lodash", + "version": "4.18.1", + "bom-ref": "launchpad@1.0.0|lodash@4.18.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/lodash@4.18.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "74c22789c4cf544f1dd5ee68b5fc269a3971919a14a6254bc32793754b22fc26a3fe07f3cdb941702139b111d5fc0b23b829b15abb5ed93346498b82782abed1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/lodash" + } + ] + }, + { + "type": "library", + "name": "longest-streak", + "version": "3.1.0", + "bom-ref": "launchpad@1.0.0|longest-streak@3.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/longest-streak@3.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f518bea3425881e8536950410e832a225f065ed6d683bd753b7b2b7ed707859d1daa7113a8b6a820ad31d7b7d4c3dac54a52bfd0d96c29ed00861ca5e695c4da" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/longest-streak" + } + ] + }, + { + "type": "library", + "name": "lowlight", + "version": "3.3.0", + "bom-ref": "launchpad@1.0.0|lowlight@3.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/lowlight@3.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/lowlight/-/lowlight-3.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d09361805a0fbcfe94ea513f51d56c4aaf7db67e838638e9023e4cc46e3d7b077698e055b70598213f0297200186ad7df1a5d7383314e8ec7c0eb1b2fc2a5365" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/lowlight" + } + ] + }, + { + "type": "library", + "name": "magic-string-ast", + "version": "1.0.3", + "bom-ref": "launchpad@1.0.0|magic-string-ast@1.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/magic-string-ast@1.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/magic-string-ast/-/magic-string-ast-1.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0af9241f58bcd7397b9a66fde03b11885786f55d9f47625eb8af320e04bca2265215afbec162c4819e6e7c43b22c76ef49b0f581344abfd35d5faf519efafd24" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/magic-string-ast" + } + ] + }, + { + "type": "library", + "name": "magic-string", + "version": "0.30.21", + "bom-ref": "launchpad@1.0.0|magic-string@0.30.21", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/magic-string@0.30.21", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bddd85e1853211728670b1e8abe4c4c828f1b9e49e1e7171cb28cda7cd328345d5e2f5219c37abfe5bef96a33f6ab0796d740de4adbfde88a7c82472c7c4f609" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/magic-string" + } + ] + }, + { + "type": "library", + "name": "marked", + "version": "18.0.14", + "bom-ref": "launchpad@1.0.0|marked@18.0.14", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/marked@18.0.14", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/marked/-/marked-18.0.14.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9811cae85047b8102586045ef3cc3d1743b501bc305c951c4226d46c2fd071d4db546003eda5b36bec6ddcdea84ff8c2671dff38c792fbcae7ba21d9710f6cec" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/marked" + } + ] + }, + { + "type": "library", + "name": "material-colors", + "version": "1.2.6", + "bom-ref": "launchpad@1.0.0|material-colors@1.2.6", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/material-colors@1.2.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/material-colors/-/material-colors-1.2.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "eaa13807d75e14121af584a939cf4ed1281ce37cd379561b8034f9bde44a4a5076f99b87368555c40d4bfdc90c51ac95f40cbdcbb67f49908b706b5e5bd8bb6e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/material-colors" + } + ] + }, + { + "type": "library", + "name": "math-intrinsics", + "version": "1.1.0", + "bom-ref": "launchpad@1.0.0|math-intrinsics@1.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/math-intrinsics@1.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fc85ed6f0124e474cfc84c32297ea11a4617c4cf676e3eb807e8a55499c2fd1e81d291f91b85776f4a556cbec3063e2d921040a696d05257fa17a5e5f4b1eed6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/math-intrinsics" + } + ] + }, + { + "type": "library", + "name": "mathml-tag-names", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|mathml-tag-names@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mathml-tag-names@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mathml-tag-names/-/mathml-tag-names-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "69ae805363dcc7454ffd75a787c2062f44984a04070d3e9472ba2bda3da65de14094ddda85a36cf0466d1b5622b6270c9122e3dc6b7a54f15f66882dec6e6215" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/mathml-tag-names" + } + ] + }, + { + "type": "library", + "name": "md5", + "version": "2.3.0", + "bom-ref": "launchpad@1.0.0|md5@2.3.0", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/md5@2.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4f51884d898568ab8ef75bf1ca840c1444ecb7e3bbd5550f114df37b918dcc39b439674ff2fd7389368010f52bff790bb18dd27ed833db8d80d527ad4220cbee" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/md5" + } + ] + }, + { + "type": "library", + "name": "mdast-squeeze-paragraphs", + "version": "6.0.0", + "bom-ref": "launchpad@1.0.0|mdast-squeeze-paragraphs@6.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-squeeze-paragraphs@6.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-squeeze-paragraphs/-/mdast-squeeze-paragraphs-6.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e8d0db24f4e0d0cd187be4e56305f5289d4b15ba79d793f68a699127225085cf4d6bd71eb47cd2a07358210717a4034400fd6c9bdc9dfc24d9536b87a91e40fb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-squeeze-paragraphs" + } + ] + }, + { + "type": "library", + "name": "mdast-util-find-and-replace", + "version": "3.0.4", + "bom-ref": "launchpad@1.0.0|mdast-util-find-and-replace@3.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-find-and-replace@3.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "cf807973a8eb9c9d65b4e41e9a15983c1480a3acb8d99f06b76c8481f80d4cc70b494e7d07c6df8fc67c02702526b0462e7aa4740519ee374312a430dcaba2a5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-find-and-replace" + } + ], + "components": [ + { + "type": "library", + "name": "escape-string-regexp", + "version": "5.0.0", + "bom-ref": "launchpad@1.0.0|mdast-util-find-and-replace@3.0.4|escape-string-regexp@5.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/escape-string-regexp@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fef798ef925b30ae23d728efb94c6e56c892fe1affe221ecf454d3e9c8137b1c5d1342f2fe095c7010249681ff0e87e48d16d95376e7a23dfc98e9a1919d251f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp" + } + ] + } + ] + }, + { + "type": "library", + "name": "mdast-util-from-markdown", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|mdast-util-from-markdown@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-from-markdown@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2912e098f68fd87d6e9766e9a0990e4bef6901c0c0023f4dbb59aa2e787c34b7891b9b65be3e364c7f343c8181a513969515cb934943ad636e642172fedb01e0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-from-markdown" + } + ] + }, + { + "type": "library", + "name": "mdast-util-mdx-expression", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|mdast-util-mdx-expression@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-mdx-expression@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "27a7fef61529fa575366a2914a0ed5c3957a32a8c04dcfb713881fdc214d72e64d583f1777223acd0f06a87edff35ebd30ce8fee13014435469e7ee81c1f645d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-mdx-expression" + } + ] + }, + { + "type": "library", + "name": "mdast-util-mdx-jsx", + "version": "3.2.1", + "bom-ref": "launchpad@1.0.0|mdast-util-mdx-jsx@3.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-mdx-jsx@3.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a17a751886be13d23022cddad74ebeb6bdc1cf63254d306f9578ce64ca086add75924eef8ea82606792c07d587996bfe81987b9372148290079701c1ec31f819" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-mdx-jsx" + } + ] + }, + { + "type": "library", + "name": "mdast-util-mdxjs-esm", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|mdast-util-mdxjs-esm@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-mdxjs-esm@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "11c98ea71b19f7a0af94fd3736086d1f512c2edaf49fd4e6e253d425405c715f51c143a77aa4b2720d7d9f91c6cc27fed742e8ccc45239bb55af779ed56a07b6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-mdxjs-esm" + } + ] + }, + { + "type": "library", + "name": "mdast-util-newline-to-break", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|mdast-util-newline-to-break@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-newline-to-break@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-newline-to-break/-/mdast-util-newline-to-break-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "31b81e15c6b484b608131ff6cc6b2ccc2484249d49482762639c50c5170b0c319af043ef94b3eea49e0349a8db30f0270b48def237dbf538940139f1c6b1d4a2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-newline-to-break" + } + ] + }, + { + "type": "library", + "name": "mdast-util-phrasing", + "version": "4.1.0", + "bom-ref": "launchpad@1.0.0|mdast-util-phrasing@4.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-phrasing@4.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4ea202c32bc9269070bc600c6638f82769f45fc416a76d5bf65d28ede5f2549db960d5986c90d52320f56d95c4e96b55e9198a2556264002966b4cd6380073db" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-phrasing" + } + ] + }, + { + "type": "library", + "name": "mdast-util-to-hast", + "version": "13.2.2", + "bom-ref": "launchpad@1.0.0|mdast-util-to-hast@13.2.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-to-hast@13.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "976a6798ebaab3e4862d5a535579d12d0bb9bf5033bc37b5f35e34e1f6d7cf3a8e6d5c6b0279d5c5aa403f6ee9530ccb04bfc00489205211a53d553b412bc816" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-to-hast" + } + ] + }, + { + "type": "library", + "name": "mdast-util-to-markdown", + "version": "2.2.3", + "bom-ref": "launchpad@1.0.0|mdast-util-to-markdown@2.2.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-to-markdown@2.2.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.2.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "74899d07a55944c45a7354b0016ea8d5cd044a4ffba4514030232e28cfbdbfb2e94d2b6130ce67cd7a6a2b0e0c8e8eba69754a84d932acfe1b301f4cbab3f25a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-to-markdown" + } + ] + }, + { + "type": "library", + "name": "mdast-util-to-string", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|mdast-util-to-string@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mdast-util-to-string@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d07e38bc38a69f9d45d18c2fc522529b47820ce25346598dd11d72061e072e3f70895d439f44285c66ef1405a3da1488b554e50a6045d61a8a948c9405514b3e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdast-util-to-string" + } + ] + }, + { + "type": "library", + "name": "mdn-data", + "version": "2.27.1", + "bom-ref": "launchpad@1.0.0|mdn-data@2.27.1", + "licenses": [ + { + "license": { + "id": "CC0-1.0" + } + } + ], + "purl": "pkg:npm/mdn-data@2.27.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f58b9b9edddef00d0e2b0c58497ca12f29865b8b02b9f70b1ba55d88375419590f869a8bc65bcfe6f975f7cde0423265deda9baccef7d668da65a3faf00828b1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/mdn-data" + } + ] + }, + { + "type": "library", + "name": "meow", + "version": "14.1.0", + "bom-ref": "launchpad@1.0.0|meow@14.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/meow@14.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/meow/-/meow-14.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "103628e95966b67ba695c0426e1d602c9ffff63bccfe77571df557205ad956be9f19cc1353209314d4cb08ab98ddf7db2bc2fffb7333aa7779f11a23899a8757" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/meow" + } + ] + }, + { + "type": "library", + "name": "merge-stream", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|merge-stream@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/merge-stream@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "69bbffa8e72e3df9375113df0f39995352ca9aec3c913fb49c81ef2ab2a016bc227e897f76859c740e19aac590f0436b14a91debb31fa68fcba2f6c852c6eddf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/merge-stream" + } + ] + }, + { + "type": "library", + "name": "merge2", + "version": "1.4.1", + "bom-ref": "launchpad@1.0.0|merge2@1.4.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/merge2@1.4.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f2aed51203095b827cb5c7d53f2f20d3d35c43065d6f0144aa17bf5999282338e7ff74c60f0b4e098b571b10373bcb4fce97330820e0bfe3f63f9cb4d1924e3a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/merge2" + } + ] + }, + { + "type": "library", + "name": "micromark-core-commonmark", + "version": "2.0.4", + "bom-ref": "launchpad@1.0.0|micromark-core-commonmark@2.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-core-commonmark@2.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c3111e13cbfc5d5bceaf19f54d98fbe2a62102d4d0b12aae7c7552dee355c93d4cba95f187268793cffdc4334f87d0662fbed03438164e467746c607076af2ef" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-core-commonmark" + } + ] + }, + { + "type": "library", + "name": "micromark-factory-destination", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-factory-destination@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-factory-destination@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5deeab0dd2659266c5444c694ce9918fd37731a5a66c081da52ac142f085aa17b3527e001ea2476da1277db5586227b1552b3ffeda8e758fc3c618dd0a226720" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-factory-destination" + } + ] + }, + { + "type": "library", + "name": "micromark-factory-label", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-factory-label@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-factory-label@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "54531e932404c6a216ef120285c5e7e28936f58137ae7bb2bde5b7c194165aa17836ff56939ae027df4accfbc78e498f5c5f7715721b069e98756dedef5ffb56" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-factory-label" + } + ] + }, + { + "type": "library", + "name": "micromark-factory-space", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|micromark-factory-space@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-factory-space@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7d2f219cb2239e3bdd4088f7f467ae83cc16b11d07ad8678dca4a12b135fc13eedd8b387a3f2db59913311a48e8f0b63742b23a04eacc878689c4cd6d33bf4f9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-factory-space" + } + ] + }, + { + "type": "library", + "name": "micromark-factory-title", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-factory-title@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-factory-title@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e5b67edc28e101df5e0a16131ec8f2e931b1a4e1522a028a24f271af6f778d36dfaf2d8a0e85a48416fa4dc3d5078366cda3e132cd45ae6f40647ece0f80a3cf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-factory-title" + } + ] + }, + { + "type": "library", + "name": "micromark-factory-whitespace", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-factory-whitespace@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-factory-whitespace@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "39bd27b99dcf2adfe7d213911f2be80fdb9986bf996bcb05a0ff8e9cc72758ae659e04b300b81060a32bf512553962ea418bb29faba5a865925ddc1fe85f3495" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-factory-whitespace" + } + ] + }, + { + "type": "library", + "name": "micromark-util-character", + "version": "2.1.1", + "bom-ref": "launchpad@1.0.0|micromark-util-character@2.1.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-character@2.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c2ff2d7544c9ded8521451492ada5828e62218fdbebfde87be4e13bbc2a9080b1332ceb28be9d5986875b32bd20ac6b1cf8e49e896f0fbd0c3ea0f7bf8d57aed" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-character" + } + ] + }, + { + "type": "library", + "name": "micromark-util-chunked", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-chunked@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-chunked@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "41434510e3c42df9afbfee3188d836b1161e4bf3fce294d6d130a03f9cdcf45a577ad1d8d1a6fb4b12b201008d09cd5e2b4e39f6ea0b235cb9a0ee5573575b84" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-chunked" + } + ] + }, + { + "type": "library", + "name": "micromark-util-classify-character", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-classify-character@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-classify-character@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2b4907ccce9a7d6fcc6de59858b8e81d0bf5b2083643d11c707103cd293188ffc469a80dcc29bb4ff58c299deb8cc6ef229bc189983047774a33282d038986d5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-classify-character" + } + ] + }, + { + "type": "library", + "name": "micromark-util-combine-extensions", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-combine-extensions@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-combine-extensions@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3a70271fc5239b2e7d25cc99c3c2526caf5c1a9755638e0d2a048cec4f4487b0e22d2d84f513507f474e35a183cc41bdca3125e6172a788b23e217d190b1ff06" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-combine-extensions" + } + ] + }, + { + "type": "library", + "name": "micromark-util-decode-numeric-character-reference", + "version": "2.0.2", + "bom-ref": "launchpad@1.0.0|micromark-util-decode-numeric-character-reference@2.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-decode-numeric-character-reference@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "71c51b624e82c1576498240ccabeb8757cf8d847c71a43d09418f9a7b6151b3abc23b0ad8d7649aee6c061ecdfed1a7e6e33ec7a244ea9eec6e9fa0577e944bb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-decode-numeric-character-reference" + } + ] + }, + { + "type": "library", + "name": "micromark-util-decode-string", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-decode-string@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-decode-string@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9c357fefb163e9e1f5ca7c2c7184ceb1b2bbad1fff523d1b65707025945f68b109d6218147a9087cd9a536a6aa25feb8f443f417735635d7898b4dde96594d51" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-decode-string" + } + ] + }, + { + "type": "library", + "name": "micromark-util-edit-map", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|micromark-util-edit-map@1.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-edit-map@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3dada58e5b042fab15c056987b2ace2d261b42def726f19b3ce605abef401255e24a77c8e50e38eb9451675b07bfb9438c33a71910c36aa3d7a8296a58afead5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-edit-map" + } + ] + }, + { + "type": "library", + "name": "micromark-util-encode", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-encode@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-encode@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "737715c76cb82aa527c28a5c3bd6ff482768d8eebb2f0249fd4caa19f6e281a85f7a02fd9b2a041680d8660913edfdfa4f46cbaccf6165301a0321fe3c20178f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-encode" + } + ] + }, + { + "type": "library", + "name": "micromark-util-html-tag-name", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-html-tag-name@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-html-tag-name@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d9c3448980e1096288f86b3d4f44e2cac935dfa4a7475de184ef325ba04637284e0b8a98167c05d6729f0f71c50085c0e5ce3946b206d6e6f5d46897798775c4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-html-tag-name" + } + ] + }, + { + "type": "library", + "name": "micromark-util-normalize-identifier", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-normalize-identifier@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-normalize-identifier@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b313ea9a8ef42f201126cd30d947250023d4504aa5b42909e8f84a74c203b89de049ffd0fbf1887b758a9742236ff1b21fd94ea5491100edb0a7419590bbd2f5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-normalize-identifier" + } + ] + }, + { + "type": "library", + "name": "micromark-util-resolve-all", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-resolve-all@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-resolve-all@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "55d432c455854f6fc51898304272586ded638d0a0d4d2e118e09664a34d496950c6bde47b71f4d1de616e2b1832736e3bc2b25f5e2e3310c0678496caa6cdc1e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-resolve-all" + } + ] + }, + { + "type": "library", + "name": "micromark-util-sanitize-uri", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-sanitize-uri@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-sanitize-uri@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f4df48a2667f62e18665999079cd4c6e0c6d960a2e8314e8755c03cf3128b8f2a8dea156bf29851d67270e2dafcd5d5f7fa91ab3db9c5bea37cb324af5807501" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-sanitize-uri" + } + ] + }, + { + "type": "library", + "name": "micromark-util-subtokenize", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|micromark-util-subtokenize@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-subtokenize@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5d02eee79da249cb6f9c47205f0ebe4b1ef919f9403cd103d6ac7b78127ec327416f62826d165ef8dc2f20410c33cdee9a5d7ed96497a4101ca7d2140a009858" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-subtokenize" + } + ] + }, + { + "type": "library", + "name": "micromark-util-symbol", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|micromark-util-symbol@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-symbol@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bece6df00a5ab9df4ddbc9200ab45474479de1427ec1636f89c1cb3f109af4436562e018df5334113cb9cb5bc0df762834f0c54e08446e787a79f684f21e31d1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-symbol" + } + ] + }, + { + "type": "library", + "name": "micromark-util-types", + "version": "2.0.3", + "bom-ref": "launchpad@1.0.0|micromark-util-types@2.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark-util-types@2.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a31076224d37848d20bfe54d9fdb67875b756047bd3033e9b558801207dd7f76101ec9f4a7319380276548225773086a9bca61684b8cef3784bb7410cd506b3e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark-util-types" + } + ] + }, + { + "type": "library", + "name": "micromark", + "version": "4.0.3", + "bom-ref": "launchpad@1.0.0|micromark@4.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromark@4.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a0661f4331d21b974e328bd0709ddfc93999956016a62d17034b09c09b3e8ba393f3ca35f89b70ffccf40a6768c122f11a18452bcf6b43fa17a61ff0374d8f37" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromark" + } + ] + }, + { + "type": "library", + "name": "micromatch", + "version": "4.0.8", + "bom-ref": "launchpad@1.0.0|micromatch@4.0.8", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/micromatch@4.0.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3d7c1f06162ed210423f0f039f413e58361beda7f77522d558a8b71c6bfce08745e13c85a02d32b3115dd06a31c3b9d2bf84ff3f3109431b18b0488508aa3604" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromatch" + } + ], + "components": [ + { + "type": "library", + "name": "picomatch", + "version": "2.3.2", + "bom-ref": "launchpad@1.0.0|micromatch@4.0.8|picomatch@2.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/picomatch@2.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "57bfaf404274e99f9ce6d4b27bc4be9c751f239d71a172178c743df5c42d294910aaa3b590efca08951f657b81e3b87f60194385a8761f785d5065e7f227b4a0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/micromatch/node_modules/picomatch" + } + ] + } + ] + }, + { + "type": "library", + "name": "mime-db", + "version": "1.52.0", + "bom-ref": "launchpad@1.0.0|mime-db@1.52.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mime-db@1.52.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b0f538b95edd625bed589c70c311c3d0fba285536213b4f201b439496c43081f66518bce82ba103b061040e28f27c0886c4fb51135653a82b5502da7537818be" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mime-db" + } + ] + }, + { + "type": "library", + "name": "mime-types", + "version": "2.1.35", + "bom-ref": "launchpad@1.0.0|mime-types@2.1.35", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mime-types@2.1.35", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "64363e6cf9b9cd34c5f98a42ac053d9cad148080983d3d10b53d4d65616fe2cfbe4cd91c815693d20ebee11dae238323423cf2b07075cf1b962f9d21cda7978b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mime-types" + } + ] + }, + { + "type": "library", + "name": "minimizer-webpack-plugin", + "version": "5.8.0", + "bom-ref": "launchpad@1.0.0|minimizer-webpack-plugin@5.8.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/minimizer-webpack-plugin@5.8.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.8.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d9c4fdfa0a097c186d333fa026a7a349fd3d0a58266213e171c45bfdf6f4ced55b8b1b740643bc991b88dba1683cfb94364464ea2103af2580228b9ce56f1e24" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/minimizer-webpack-plugin" + } + ] + }, + { + "type": "library", + "name": "mlly", + "version": "1.8.2", + "bom-ref": "launchpad@1.0.0|mlly@1.8.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mlly@1.8.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "77e39bc4c40599bb75d2cadeb4d0f2b70b7ce55adb92185403f2411a6d4c3da589eb90a5e303a02da075358bc9499d047f4dcc30453fd31a4f317508436f547c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mlly" + } + ], + "components": [ + { + "type": "library", + "name": "pkg-types", + "version": "1.3.1", + "bom-ref": "launchpad@1.0.0|mlly@1.8.2|pkg-types@1.3.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/pkg-types@1.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fc99b933846fb4115590a591bb604b51334ff3f3366be530b805fe69ee3bef4ab5a951ad7e31be5930aea68662c689239878abcbcb88f9d958f0a5d85791d555" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mlly/node_modules/pkg-types" + } + ] + }, + { + "type": "library", + "name": "confbox", + "version": "0.1.8", + "bom-ref": "launchpad@1.0.0|mlly@1.8.2|confbox@0.1.8", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/confbox@0.1.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "44cb66c3488591e478615f9f50e4ae72b88040d6fd83ccc5479d8c582b65f9c09938544d2facde077f79bcfcc58448e39f87ccc57b9d9842e797f285fd6acaeb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/mlly/node_modules/confbox" + } + ] + } + ] + }, + { + "type": "library", + "name": "ms", + "version": "2.1.3", + "bom-ref": "launchpad@1.0.0|ms@2.1.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ms@2.1.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e85973b9b4cb646dc9d9afcd542025784863ceae68c601f268253dc985ef70bb2fa1568726afece715c8ebf5d73fab73ed1f7100eb479d23bfb57b45dd645394" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ms" + } + ] + }, + { + "type": "library", + "name": "muggle-string", + "version": "0.4.1", + "bom-ref": "launchpad@1.0.0|muggle-string@0.4.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/muggle-string@0.4.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "54d4eb01a93f2a13b68bc76aaa7aa700739addc601c171197bd87e0f987fd59a854931051dd33ae6547b46822aab7b410586afb0e5d5f383681d76740243f2a9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/muggle-string" + } + ] + }, + { + "type": "library", + "name": "nanoid", + "version": "3.3.20", + "bom-ref": "launchpad@1.0.0|nanoid@3.3.20", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/nanoid@3.3.20", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b8a760d86dc63422909fd6f260ea716c6aab4f67c63b9291b7927ff1bde9a24f2b4faab119617a871332262118b407fe155c98b83f6145a0ea5f9b8f15827865" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/nanoid" + } + ] + }, + { + "type": "library", + "name": "natural-compare", + "version": "1.4.0", + "bom-ref": "launchpad@1.0.0|natural-compare@1.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/natural-compare@1.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "396343f1e8b756d342f61ed5eb4a9f7f7495a1b1ebf7de824f0831b9b832418129836f7487d2746eec8408d3497b19059b9b0e6a38791b5d7a45803573c64c4b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/natural-compare" + } + ] + }, + { + "type": "library", + "name": "neo-async", + "version": "2.6.2", + "bom-ref": "launchpad@1.0.0|neo-async@2.6.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/neo-async@2.6.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "61ddd4112e665824aa47ea8d4fddd2dd4a18524a8067d94b83c6bb83dae29ac5a66062bc7154e8038fec17746bb21772577b0018c5d5526a4c60ec3e74ba4ebb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/neo-async" + } + ] + }, + { + "type": "library", + "name": "nested-property", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|nested-property@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/nested-property@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/nested-property/-/nested-property-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c857a15cd591b3870cd3e773ed0c42774ea14db59b4a4574212b2a05f927b54e93398e109b743cf1f4512ce75d90687642ae9d66f9ca5406a17e18dc52f2e7c8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/nested-property" + } + ] + }, + { + "type": "library", + "name": "node-addon-api", + "version": "7.1.1", + "bom-ref": "launchpad@1.0.0|node-addon-api@7.1.1", + "scope": "optional", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/node-addon-api@7.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e66ddbb32ae3156135c5fee7cfb61774de2e76756d5caebf61f827e6a9da84be9b0a47f6c8ab789379ee4ca02d4f8af7206f09351da772c20c759b80cc98c741" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/node-addon-api" + } + ] + }, + { + "type": "library", + "name": "node-domexception", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|node-domexception@1.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/node-domexception@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fe3299a0ca70d05f06470978fde2d138f03771f717b4b0293f44332e6513fc7b8f0995b207b218f59acc78ac363bf9c522a3d00773d533d6989b4177d760170d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/node-domexception" + } + ] + }, + { + "type": "library", + "name": "node-fetch", + "version": "3.3.2", + "bom-ref": "launchpad@1.0.0|node-fetch@3.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/node-fetch@3.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "75107bf2cacdfe5ea0a96ba56a1f52af17989f179d7481b7d3e18ea8affd3a52d5c8b8371cf9ebe92a8e59358e5ca4700b6786602919e7d34db9282f4aba6038" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/node-fetch" + } + ] + }, + { + "type": "library", + "name": "node-releases", + "version": "2.0.54", + "bom-ref": "launchpad@1.0.0|node-releases@2.0.54", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/node-releases@2.0.54", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.54.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "607b3b06699cb1d008e4ecee7fc259a3a3d3d26bf6188582f6f31fbd40b7769eb933c867ed4c7c08f2feda8048ee3b8dba3f5dd277614dcce7ab6383069b3d71" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/node-releases" + } + ] + }, + { + "type": "library", + "name": "normalize-path", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|normalize-path@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/normalize-path@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e9e66ce4bb375ad0a2b075a9f52d86532f1daa4a468b80554b3dc66aa884e9ecee6f4e75d844b3b57530501e82e8829b4246363e76ff983e166288c24707302c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/normalize-path" + } + ] + }, + { + "type": "library", + "name": "nostics", + "version": "1.4.0", + "bom-ref": "launchpad@1.0.0|nostics@1.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/nostics@1.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/nostics/-/nostics-1.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5a35c73ae36ecd8dcc3ca3a8093db32f549addc4b698e51ee28f05f7826f04e1f67067f2348b5b42609bda9347231a2875de4efafb66987abb3e84995468021c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/nostics" + } + ] + }, + { + "type": "library", + "name": "nth-check", + "version": "2.1.1", + "bom-ref": "launchpad@1.0.0|nth-check@2.1.1", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/nth-check@2.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "96a8eb8e668ea009d67cc9813cbf97367ca7661dbeb30c625f7594134b38c841c8ea6f80c2b2b65193a2988465dd7ff841cb55a92f008998c5ab2386acc5dbff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/nth-check" + } + ] + }, + { + "type": "library", + "name": "optionator", + "version": "0.9.4", + "bom-ref": "launchpad@1.0.0|optionator@0.9.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/optionator@0.9.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e88a50ee6294c5171934b20e6d1d21cfb971b1aa5248860d649c173c6785d264d5a862852178f50d070ca13db64b744e70bc98febcf43d669667d6b25a669df6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/optionator" + } + ] + }, + { + "type": "library", + "name": "orderedmap", + "version": "2.1.1", + "bom-ref": "launchpad@1.0.0|orderedmap@2.1.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/orderedmap@2.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4ef016c62d270ded63febb4c7167088fde3e15f7ba9fbce1a30df7878d122b19ac9a8cece9dcff7be11a8f299fa0570777bb31367f321ccf3cdfdba2c4c395ea" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/orderedmap" + } + ] + }, + { + "type": "library", + "name": "p-limit", + "version": "3.1.0", + "bom-ref": "launchpad@1.0.0|p-limit@3.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/p-limit@3.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4d839a9ccdf01b0346b193767154d83c0af0e39e319d78f9aa6585d5b12801ce3e714fe897b19587ba1d7af8e9d4534776e1dcdca64c70576ec54e5773ab8945" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/p-limit" + } + ] + }, + { + "type": "library", + "name": "p-locate", + "version": "5.0.0", + "bom-ref": "launchpad@1.0.0|p-locate@5.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/p-locate@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2da363b51594058fbecc1e6713f37071aa0cca548f93e4be647341d53cdd6cc24c9f2e9dca7a401aded7fed97f418ab74c8784ea7c47a696e8d8b1b29ab1b93f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/p-locate" + } + ] + }, + { + "type": "library", + "name": "p-queue", + "version": "9.3.3", + "bom-ref": "launchpad@1.0.0|p-queue@9.3.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/p-queue@9.3.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/p-queue/-/p-queue-9.3.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "35700e76711ee45b1925f4f8a0af38944d58e5c145756951b8ea39b70c3c0f234cc72457c27dfd7c8914b4d2caa6970f0be51853f6d7ba33425060efd35cbb08" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/p-queue" + } + ] + }, + { + "type": "library", + "name": "p-timeout", + "version": "7.0.1", + "bom-ref": "launchpad@1.0.0|p-timeout@7.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/p-timeout@7.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0314ccdb00c63911c61243c2b7ccaac4e4cc8297db107a85e757ffe5f2429b0142dc2ff335c193eb74b2987dadb4e01a888c2cdb3560e3e8b34028eb6a47301e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/p-timeout" + } + ] + }, + { + "type": "library", + "name": "parent-module", + "version": "1.0.1", + "bom-ref": "launchpad@1.0.0|parent-module@1.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/parent-module@1.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "190d84591a5057cfe8f80c3c62ab5f6593df3515996246e2744f64e6ba65fe10b7bed1c705f1a6d887e2eaa595f9ca031a4ad42990311372e8b7991cb11961fa" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/parent-module" + } + ] + }, + { + "type": "library", + "name": "parse-entities", + "version": "4.0.2", + "bom-ref": "launchpad@1.0.0|parse-entities@4.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/parse-entities@4.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "186d804185a82e02fcefb81020a7913c63b5c45f7e786d6e8c86f9b284b980fbcb435cb6a3c14bf74c3641635d7fd237eb5329a7bef6e9cfa58f7534a8ad6e1b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/parse-entities" + } + ], + "components": [ + { + "type": "library", + "name": "unist", + "group": "@types", + "version": "2.0.11", + "bom-ref": "launchpad@1.0.0|parse-entities@4.0.2|@types/unist@2.0.11", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40types/unist@2.0.11", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0a604a88be8d368fceaa098c9fde4593d5a1969da6b6f22ff8a36940a3761784a3beb11eb2e6d34561984a0f819d664e9e509a493535b0ca6c04ece06d8867b0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/parse-entities/node_modules/@types/unist" + } + ] + } + ] + }, + { + "type": "library", + "name": "parse-json", + "version": "5.2.0", + "bom-ref": "launchpad@1.0.0|parse-json@5.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/parse-json@5.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6b208abe6fe98421b13a461148233cda20f072df3f1289d2120092c56c43eef7ba8c7820b059787d955004f44d810a0a8ae57fa1d845ac6cd05d9c1b89f0bc46" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/parse-json" + } + ], + "components": [ + { + "type": "library", + "name": "code-frame", + "group": "@babel", + "version": "7.29.7", + "bom-ref": "launchpad@1.0.0|parse-json@5.2.0|@babel/code-frame@7.29.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/code-frame@7.29.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "02ea7b69439fa5b01483644e38937a230e5ff43301973bb4988926fe66a52d014dfd84203b8f300a3d0ac5adec10726f3d5160eec891faa4489f05dddaa8502b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/parse-json/node_modules/@babel/code-frame" + } + ] + }, + { + "type": "library", + "name": "helper-validator-identifier", + "group": "@babel", + "version": "7.29.7", + "bom-ref": "launchpad@1.0.0|parse-json@5.2.0|@babel/helper-validator-identifier@7.29.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40babel/helper-validator-identifier@7.29.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a9e8711a4463e7987f7dff0431a27e71887268a947231a980e7ebcdb0403ed1369f54ba3390b07a20dae4b4af6bf3af8a56fac5dff7435e79aca370d697ddf16" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/parse-json/node_modules/@babel/helper-validator-identifier" + } + ] + }, + { + "type": "library", + "name": "js-tokens", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|parse-json@5.2.0|js-tokens@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/js-tokens@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "45d2547e5704ddc5332a232a420b02bb4e853eef5474824ed1b7986cf84737893a6a9809b627dca02b53f5b7313a9601b690f690233a49bce0e026aeb16fcf29" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/parse-json/node_modules/js-tokens" + } + ] + } + ] + }, + { + "type": "library", + "name": "path-exists", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|path-exists@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/path-exists@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6a4f50cb943b8d86f65b071ecb9169be0d8aa0073f64884b48b392066466ca03ec1b091556dd1f65ad2aaed333fa6ead2530077d943c167981e0c1b82d6cbbff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/path-exists" + } + ] + }, + { + "type": "library", + "name": "path-expression-matcher", + "version": "1.6.2", + "bom-ref": "launchpad@1.0.0|path-expression-matcher@1.6.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/path-expression-matcher@1.6.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.6.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7a74a56a26add3989ab27ce680dc518fcade15d8f7a6e6364293603f568f21a55f4fa9e7f480ae3e816528793c10ddb61dcc1ec2c84efa63760c66e40843ada9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/path-expression-matcher" + } + ] + }, + { + "type": "library", + "name": "path-key", + "version": "3.1.1", + "bom-ref": "launchpad@1.0.0|path-key@3.1.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/path-key@3.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a2399e374a9dfb2d23b3312da18e3caf43deab97703049089423aee90e5fe3595f92cc17b8ab58ae18284e92e7c887079b6e1486ac7ee53aa6d889d2c0b844e9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/path-key" + } + ] + }, + { + "type": "library", + "name": "path-posix", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|path-posix@1.0.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/path-posix@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/path-posix/-/path-posix-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d602745a9348898710c9d820dc477c2b3bc8a93b03a4dc2af9c8c10acb2f06db935a312a635016fa2f8e7a988432a0c2cf2ae8f41dac2c07b84413da8cc60588" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/path-posix" + } + ] + }, + { + "type": "library", + "name": "pathe", + "version": "2.0.3", + "bom-ref": "launchpad@1.0.0|pathe@2.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/pathe@2.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5948c6700a8fd6041a72841ef8e049b0503b2dde03c97b9422367971cef970b1ef27b76d36c4ee8298712000f0b294be02b68051e3c22ab495b4f2c58ff17cf3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/pathe" + } + ] + }, + { + "type": "library", + "name": "perfect-debounce", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|perfect-debounce@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/perfect-debounce@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2e381d4f2b5515779482d1d9afd59856261233f83c3247133d80e53daddc0ea322ac78ca89264f61de83a0bee92bc00942bfae5a442f0a31cd76232ab2b26cfa" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/perfect-debounce" + } + ] + }, + { + "type": "library", + "name": "picocolors", + "version": "1.1.1", + "bom-ref": "launchpad@1.0.0|picocolors@1.1.1", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/picocolors@1.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c5c787dac9e1b5be4cf658aa0ec984c39ea57b7efa993664117fe311bfd1c4d1727a036e97b78db250973fd1438ff2dcbb45fc284c8c71e3f69eda5a1eb0c454" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/picocolors" + } + ] + }, + { + "type": "library", + "name": "picomatch", + "version": "4.0.7", + "bom-ref": "launchpad@1.0.0|picomatch@4.0.7", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/picomatch@4.0.7", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a9c26ef3c436216a89b030f9dbd24a31dc069bf76f2275b81ef427470887f49b62849bf318eb1c0ed1c4df1d6904a794393cac43c91598b9c9da426eef285c18" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/picomatch" + } + ] + }, + { + "type": "library", + "name": "pinia", + "version": "4.1.0", + "bom-ref": "launchpad@1.0.0|pinia@4.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/pinia@4.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/pinia/-/pinia-4.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fb9fc732e5636107ca9420f9c50ef37d79f5c54cd81446bba5dd0340ae5268c7d909a1514c795a1ff734d8dd45a0639d9734a2c1fe4438f809c7fff5403c3a83" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/pinia" + } + ] + }, + { + "type": "library", + "name": "pkg-types", + "version": "2.4.0", + "bom-ref": "launchpad@1.0.0|pkg-types@2.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/pkg-types@2.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d3b172b3b895c745fa4dcbe230e82880cd4b937dd9caa39eccc9d4efd4be91f7d6ab0a251bfe56f55f0481049e60221f15361582cb116e71fadf439adbeb2804" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/pkg-types" + } + ] + }, + { + "type": "library", + "name": "postcss-html", + "version": "1.8.1", + "bom-ref": "launchpad@1.0.0|postcss-html@1.8.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss-html@1.8.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss-html/-/postcss-html-1.8.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "38b17a3fba9cb5f0166b23a12e97159d31aa55e273bb65b75a92187a57f3dbe255e681b17e4704bf078df54e17a5ea84d0ff7c75c0fdb2cbac1b0945d132b4b9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss-html" + } + ], + "components": [ + { + "type": "library", + "name": "js-tokens", + "version": "9.0.1", + "bom-ref": "launchpad@1.0.0|postcss-html@1.8.1|js-tokens@9.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/js-tokens@9.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9b16bd13d21314eb746da9f78fa2f93298f07a01b3ea505098cd4826459e05919c331b68e74f9e59d8c2ff9db10db4b6bf2d24eef20c2b415edb07cbf4e412a5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss-html/node_modules/js-tokens" + } + ] + } + ] + }, + { + "type": "library", + "name": "postcss-media-query-parser", + "version": "0.2.3", + "bom-ref": "launchpad@1.0.0|postcss-media-query-parser@0.2.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss-media-query-parser@0.2.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss-media-query-parser/-/postcss-media-query-parser-0.2.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "dec3a5c666ca7121cc8e5517419290d3a8ceb3013ba159173f1999768075af9974aba8131534121f13713ab09c70495b5bb771372b627cd128f2a89d5f656c8a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss-media-query-parser" + } + ] + }, + { + "type": "library", + "name": "postcss-resolve-nested-selector", + "version": "0.1.6", + "bom-ref": "launchpad@1.0.0|postcss-resolve-nested-selector@0.1.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss-resolve-nested-selector@0.1.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss-resolve-nested-selector/-/postcss-resolve-nested-selector-0.1.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d2c82522cf569a4cdbafc950c04c88ce50ce382f5b1a67d529c2536b1bf7bcc99ddeea38a380deac2dc49f46e79a071e7aa97d05f0bc851929edc8347e3755ab" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss-resolve-nested-selector" + } + ] + }, + { + "type": "library", + "name": "postcss-safe-parser", + "version": "6.0.0", + "bom-ref": "launchpad@1.0.0|postcss-safe-parser@6.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss-safe-parser@6.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss-safe-parser/-/postcss-safe-parser-6.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "14044737ca701fe5a24b638f0b1248f05b912694d59e7e993458aa00cd9a796d8bc131d65a65a0232282e9c528d0bf1a78a885ff5e0c36f9e996ce91d8f05e31" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss-safe-parser" + } + ] + }, + { + "type": "library", + "name": "postcss-scss", + "version": "4.0.9", + "bom-ref": "launchpad@1.0.0|postcss-scss@4.0.9", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss-scss@4.0.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss-scss/-/postcss-scss-4.0.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "02328e7a2c008ad2ff317c505b60e5893dbc10aba4bef6c45b1dcb06624844df0a7c11996d14f13585b4912aa2d423a24d9e7b9d9f4d5b4e92eaec7ffcdd5cf4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss-scss" + } + ] + }, + { + "type": "library", + "name": "postcss-selector-parser", + "version": "7.2.1", + "bom-ref": "launchpad@1.0.0|postcss-selector-parser@7.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss-selector-parser@7.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1b0c653204d35f02289be79b0bb6a7de4e916890f09254504277e25ec2cf1a272ef05615fe4ffed7ff58636394dbeafddfc1f6b785f44c3c6889ff873f6ae3cd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss-selector-parser" + } + ] + }, + { + "type": "library", + "name": "postcss-value-parser", + "version": "4.2.0", + "bom-ref": "launchpad@1.0.0|postcss-value-parser@4.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss-value-parser@4.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d4d342b3abaeadf9156de5c6e12f09153f6dd7d9b8e480a789ff3358b779a0f499e74427c0c7caf87de3bf8d3c7788f0ffb06db6fe5ac52e48887a0b69534779" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss-value-parser" + } + ] + }, + { + "type": "library", + "name": "postcss", + "version": "8.5.33", + "bom-ref": "launchpad@1.0.0|postcss@8.5.33", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss@8.5.33", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4551c453dfcfa751678ebfcca4026c668003ba408a85f222d793ae9c46221a4b489182e43d5bc2d6c8a85a89460d2ed7072313c7d9bf2066eba3426cd77ce19d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/postcss" + } + ] + }, + { + "type": "library", + "name": "prelude-ls", + "version": "1.2.1", + "bom-ref": "launchpad@1.0.0|prelude-ls@1.2.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prelude-ls@1.2.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "be47033eb459a354192db9f944b18fa60fd698843ae6aa165a170629ffdbe5ea659246ab5f49bdcfca6909ab789a53aa52c5a9c8db9880edd5472ad81d2cd7e6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/prelude-ls" + } + ] + }, + { + "type": "library", + "name": "property-information", + "version": "7.2.0", + "bom-ref": "launchpad@1.0.0|property-information@7.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/property-information@7.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "200b73201eac52259a258ad7f6c9a9dd5e3aa4119b05e2c5446761db9920d77df855c0650fc1f384f78d216407f738469a8da2b487b6e441edf5d40fec6e619a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/property-information" + } + ] + }, + { + "type": "library", + "name": "prosemirror-commands", + "version": "1.7.2", + "bom-ref": "launchpad@1.0.0|prosemirror-commands@1.7.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prosemirror-commands@1.7.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "aba43ab33c6a76ef5777a11c74ab2a5e086ee6741d653a41e10f72774e1645ceff8edefaddefeb4fad0ec21d0bd46618f93e3aa39ac3fbd944377e9d652e37b7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/prosemirror-commands" + } + ] + }, + { + "type": "library", + "name": "prosemirror-history", + "version": "1.5.0", + "bom-ref": "launchpad@1.0.0|prosemirror-history@1.5.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prosemirror-history@1.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ce5cd3887d3578a039e5401fd4c123b6cb097879c6c4ed23e0ae03a71fa09e65fd9fe4873650ea236a0ed4abf588f379075766e5fb258c27ea285f6714be8746" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/prosemirror-history" + } + ] + }, + { + "type": "library", + "name": "prosemirror-inputrules", + "version": "1.5.1", + "bom-ref": "launchpad@1.0.0|prosemirror-inputrules@1.5.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prosemirror-inputrules@1.5.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ef08f8b8c8ca69758043508383137336d47d025b2ec331df7451f5ca01070362871760ce11a5e5d4225f34f00a0a0f6a344878aee9bdef940b6828903f263a17" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/prosemirror-inputrules" + } + ] + }, + { + "type": "library", + "name": "prosemirror-keymap", + "version": "1.2.3", + "bom-ref": "launchpad@1.0.0|prosemirror-keymap@1.2.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prosemirror-keymap@1.2.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e07b9c465a622ddd483d041736a7a8f35046b6463c022e6c98784a5bd8e33ca45cdb0408c64b20ec7975b5323621f4f607f2e05fa6df62f5f1129265eda2982b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/prosemirror-keymap" + } + ] + }, + { + "type": "library", + "name": "prosemirror-model", + "version": "1.25.13", + "bom-ref": "launchpad@1.0.0|prosemirror-model@1.25.13", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prosemirror-model@1.25.13", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.13.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3250cc5868d85da60e78288ed7b8dcc9b9ed08eccf9cdfbded4d3cd3d91ed90b203edc56de7e7fb03e992b224e35480cc3588ff77a216538de2a39d127b2fa91" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/prosemirror-model" + } + ] + }, + { + "type": "library", + "name": "prosemirror-state", + "version": "1.4.4", + "bom-ref": "launchpad@1.0.0|prosemirror-state@1.4.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prosemirror-state@1.4.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ea38981c7d822066c27e7c5d1db5d9d7683248563f7f3fee959137df71ba6cfa8867817e4d7a3d89f891f3a9c01e95a77e836339bde8e444a2ec9f14cf58d71f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/prosemirror-state" + } + ] + }, + { + "type": "library", + "name": "prosemirror-transform", + "version": "1.12.0", + "bom-ref": "launchpad@1.0.0|prosemirror-transform@1.12.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prosemirror-transform@1.12.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1b16e8c8de00308b281cdb73e6e7f6af646ee79d62e6159e08c0fa13621be04a20aa8b9bd0d7e59e26813d543832b184e7267c255f6d50783da9c6534eb70de3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/prosemirror-transform" + } + ] + }, + { + "type": "library", + "name": "prosemirror-view", + "version": "1.42.9", + "bom-ref": "launchpad@1.0.0|prosemirror-view@1.42.9", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/prosemirror-view@1.42.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6ca6dfcde2993aed87d89414d93689998bba101728af75671884788d1df571b12dd73b549df501e9b286575f9f27338976b55647eb51534db4f33337a10c78c0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/prosemirror-view" + } + ] + }, + { + "type": "library", + "name": "proxy-from-env", + "version": "2.1.0", + "bom-ref": "launchpad@1.0.0|proxy-from-env@2.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/proxy-from-env@2.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "709fa81d35b554011af1c26c96099466b73eb2344a8002a5dd9cac7baf8f577f2165efd5e99d784db0ae5dc6a7f45f60865cf842b16bd9cf764cd17cd949181c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/proxy-from-env" + } + ] + }, + { + "type": "library", + "name": "punycode", + "version": "2.3.1", + "bom-ref": "launchpad@1.0.0|punycode@2.3.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/punycode@2.3.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bd8b7b503d54f5683ad77f2c84bb4b3af740bbef03b02fe2945b44547707fb0c9d712a4d136d007d239db9fe8c91115a84be4563b5f5a14ee7295645b5fabc16" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/punycode" + } + ] + }, + { + "type": "library", + "name": "qified", + "version": "0.10.1", + "bom-ref": "launchpad@1.0.0|qified@0.10.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/qified@0.10.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f8ec328208bd2314f578f28669f708f3bb9b4a6c6897ab26c09f910070d0971f7ef5c3f01560e22851423ee5a1afd8a09e51a967dbc340bc3aecde1d71354510" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/qified" + } + ], + "components": [ + { + "type": "library", + "name": "hookified", + "version": "2.2.0", + "bom-ref": "launchpad@1.0.0|qified@0.10.1|hookified@2.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/hookified@2.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a7f2e017344de457a80f70cb4ba6e451aa5ec9ee84e1223ac89b3a29eb4435dd7c4be141b61a98ab66a62545a9b79cf4110c301de9a27636393aa24610a9b9b8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/qified/node_modules/hookified" + } + ] + } + ] + }, + { + "type": "library", + "name": "quansync", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|quansync@1.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/quansync@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/quansync/-/quansync-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e7165a70412e7efdc74933d0b9c86bbd5eaca1a88008c167ab51fcc24562a1cb681f74d185af52cfaea53b14703cafea663ec73e24af7a287dc80ca1f7c82fa8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/quansync" + } + ] + }, + { + "type": "library", + "name": "querystringify", + "version": "2.2.0", + "bom-ref": "launchpad@1.0.0|querystringify@2.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/querystringify@2.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "148aa08f6114bd36bb479d2ed2b1acc937edce3626bff6b784edf8e5b64daea69b36a8ed8220cc826a389a452377e9f3539a05ddd0a52aa1483d42b26d4caaa1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/querystringify" + } + ] + }, + { + "type": "library", + "name": "queue-microtask", + "version": "1.2.3", + "bom-ref": "launchpad@1.0.0|queue-microtask@1.2.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/queue-microtask@1.2.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "36e68d49ae9f94a4f925a498433268934e09cd32f5080e9a1a1bf9adf2d6dcf82a03e3360a1a59427002f21f22e19164052f17e51aa40c11c0eebe217a3dcaf4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/queue-microtask" + } + ] + }, + { + "type": "library", + "name": "readdirp", + "version": "5.1.1", + "bom-ref": "launchpad@1.0.0|readdirp@5.1.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/readdirp@5.1.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2a4a3e6395d0e9f33e09edddab79bd606c6769c619625f5c035c198da17755baf2d8bde2d6a560f3e08080d3ec5d102b3cc50c09a391ee86bd36a9ed738dc928" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/readdirp" + } + ] + }, + { + "type": "library", + "name": "rehype-external-links", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|rehype-external-links@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/rehype-external-links@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/rehype-external-links/-/rehype-external-links-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ca9f9ee4df55dc2e9bc017800b89fbf7a91cf3a33880909d955862313c48ac91b95070cc87e3c900d7fd85ea8e4496edd67ac26c3c0894064a8c034869505bbf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/rehype-external-links" + } + ] + }, + { + "type": "library", + "name": "rehype-highlight", + "version": "7.0.2", + "bom-ref": "launchpad@1.0.0|rehype-highlight@7.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/rehype-highlight@7.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/rehype-highlight/-/rehype-highlight-7.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "935e7ca4aef0742daa2f733935c651399dad47f97bccece3c5777954675c7c8ca88a38d0aa91dddc92ad612043a43677f142365895ae140b64303c66c7992cb4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/rehype-highlight" + } + ] + }, + { + "type": "library", + "name": "rehype-react", + "version": "8.0.0", + "bom-ref": "launchpad@1.0.0|rehype-react@8.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/rehype-react@8.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/rehype-react/-/rehype-react-8.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bf3a3463161b0761c4fb7ebef4759755dc4da0d0ee6f1eb7af92c1ce9c4119558cf2cf6676731d6e6b890405fa4d3cae19d663662c7aa94dc6712b8a0885a2bf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/rehype-react" + } + ] + }, + { + "type": "library", + "name": "remark-breaks", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|remark-breaks@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/remark-breaks@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/remark-breaks/-/remark-breaks-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "22312324e907e05b89bc7655216d100835b1706f7a902abb027fca547d8d7c97baaca654d80b07781dce1233cd4718b8402df85ddc7b236286627e88a53ee0c5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/remark-breaks" + } + ] + }, + { + "type": "library", + "name": "remark-parse", + "version": "11.0.0", + "bom-ref": "launchpad@1.0.0|remark-parse@11.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/remark-parse@11.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "142c6528b3469274b96daff5966a588a3314cd7d9eb315b9c50aa35b1c3678715f4b631275a1d520d166863a3ea8dd5685984d8a6ab475901337da47d080eba4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/remark-parse" + } + ] + }, + { + "type": "library", + "name": "remark-rehype", + "version": "11.1.2", + "bom-ref": "launchpad@1.0.0|remark-rehype@11.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/remark-rehype@11.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0e1ee5e7b89a9da128229cdba743c2f542807424959250fc139469c3b1137db4e5dc5a9c38e82ae6ad8b54386018291a06fee9db82578a43ddbe18661ef28cb3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/remark-rehype" + } + ] + }, + { + "type": "library", + "name": "remark-unlink-protocols", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|remark-unlink-protocols@1.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/remark-unlink-protocols@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/remark-unlink-protocols/-/remark-unlink-protocols-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e63fc5dbc8e1166c5ecb3f27b89618216751e2736929667c03eb55c272bfd29abb463b9edf70883446127244aad8f66f79d84a5306e7d3cab28ae1a83cb06e9e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/remark-unlink-protocols" + } + ] + }, + { + "type": "library", + "name": "require-from-string", + "version": "2.0.2", + "bom-ref": "launchpad@1.0.0|require-from-string@2.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/require-from-string@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5dfd2759ee91b1ece214cbbe029f5b8a251b9a996ae92f7fa7eef0ed85cffc904786b5030d48706bebc0372b9bbaa7d9593bde53ffc36151ac0c6ed128bfef13" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/require-from-string" + } + ] + }, + { + "type": "library", + "name": "requires-port", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|requires-port@1.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/requires-port@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2a280e087728714dd7383271b2ef22fe3f13f6dcd3e1a74789e730391450d19645729eda8705ee454d66fb2b8ef740b9654c867867e87070c8d783372f7c8301" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/requires-port" + } + ] + }, + { + "type": "library", + "name": "resolve-from", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|resolve-from@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/resolve-from@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a5bfcc6265ecb40932b11171f2988d235b4614d408140def904dc6ab812e035745ea01e9ffebe066ab021896a9bf2f0ddd0fb8a3b170beab8f25c9d9ed1632e2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/resolve-from" + } + ] + }, + { + "type": "library", + "name": "reusify", + "version": "1.1.0", + "bom-ref": "launchpad@1.0.0|reusify@1.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/reusify@1.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "83a4147dfd38a19a47b34786e69f37ac52e11de574d2e83f61ff6764ce9f2de52b3e0b814e44d039da40596b29321e794d97d54033da37735025f6d5440c5d23" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/reusify" + } + ] + }, + { + "type": "library", + "name": "rolldown", + "version": "1.2.19", + "bom-ref": "launchpad@1.0.0|rolldown@1.2.19", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/rolldown@1.2.19", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "408895d49f5dd29ccde2379e4c7e2c8cfcb4019e9c032d9c1b41317a8135f94f11be3fa1477818928931d186de50d1a566a890249daeb5c1137b4a0a5f0cecb8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/rolldown" + } + ] + }, + { + "type": "library", + "name": "rope-sequence", + "version": "1.3.4", + "bom-ref": "launchpad@1.0.0|rope-sequence@1.3.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/rope-sequence@1.3.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "513e440ded9cbb613fe8ee22814af93d216cdb79efbee9227161f1e869ce3e51c08a261bccdb824500ae89474725072a29a94b2a5ad82678d8d32486b173505d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/rope-sequence" + } + ] + }, + { + "type": "library", + "name": "run-parallel", + "version": "1.2.0", + "bom-ref": "launchpad@1.0.0|run-parallel@1.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/run-parallel@1.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e65e15c9947ce8b67f943c594d1ea3a8bf00144d92d0814b30fdba01b8ec2d5003c4776107f734194b07fb2dfd51f0a2dddcf3f0e950b8f9a768938ca031d004" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/run-parallel" + } + ] + }, + { + "type": "library", + "name": "sass", + "version": "1.103.1", + "bom-ref": "launchpad@1.0.0|sass@1.103.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/sass@1.103.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/sass/-/sass-1.103.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f627195116cfe754ba4b4406a3269eaa4f6e074e86356c6c15859f1f9460a4582a2b9140f2d25c33701d571ad911527b773f8bf3b9c6f7980129fe15b9a3071b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/sass" + } + ] + }, + { + "type": "library", + "name": "sax", + "version": "1.6.1", + "bom-ref": "launchpad@1.0.0|sax@1.6.1", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0" + } + } + ], + "purl": "pkg:npm/sax@1.6.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e36b415702d69da42f5b9cdce076d9ad3b9671c1020997c18bdd850eec2dab16ac1fe25b3c1dff14e29bd66db6d8ae364785b1bb1cf332c4ecc1fce0b52bbae1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/sax" + } + ] + }, + { + "type": "library", + "name": "schema-utils", + "version": "4.8.5", + "bom-ref": "launchpad@1.0.0|schema-utils@4.8.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/schema-utils@4.8.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.8.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2b54513fb6935006369465cdccfc2330ae8030ccdb113769177a533cc1271ff46ba663f1e8ad57e3bfe049e6eb57ed48f6945c829c19c2aa58065c9902c9628b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/schema-utils" + } + ] + }, + { + "type": "library", + "name": "scule", + "version": "1.3.0", + "bom-ref": "launchpad@1.0.0|scule@1.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/scule@1.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/scule/-/scule-1.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e85b47244bedfa954c201f48058f8870227a6797f58909f2b60c9f28c8432a09b3606f93787ff0c75cb7976eebb2149b2e249a9eb47d7df643ac4b268e5405da" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/scule" + } + ] + }, + { + "type": "library", + "name": "shebang-command", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|shebang-command@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/shebang-command@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "907c6bdb366962d766acdd6a0e3aeb5ff675ad1d641bc0f1fa09292b51b87979af5ecc26704d614d6056614ce5ada630d7fc99a7a62e0d8efb62dbdb3747660c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/shebang-command" + } + ] + }, + { + "type": "library", + "name": "shebang-regex", + "version": "3.0.0", + "bom-ref": "launchpad@1.0.0|shebang-regex@3.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/shebang-regex@3.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "efef9d161b5cc77df9dee05aabc0c347836ec417ad0730bb6503a19934089c711de9b4ab5dd884cb30af1b4ed9e3851874b4a1594c97b7933fca1cfc7a471bd4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/shebang-regex" + } + ] + }, + { + "type": "library", + "name": "signal-exit", + "version": "4.1.0", + "bom-ref": "launchpad@1.0.0|signal-exit@4.1.0", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/signal-exit@4.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6f3c99d5ef3cc3d3b588d25b2a73a5bd84eb58f0e5e3a3b56c6d03dd7227bfef6d90faf1acdf235144e21650e4926296827d4ce827c8035dd2b86a8e6bd2a8af" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/signal-exit" + } + ] + }, + { + "type": "library", + "name": "slash", + "version": "5.1.0", + "bom-ref": "launchpad@1.0.0|slash@5.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/slash@5.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "640ea84774ffa44caeab032000a4f4fe102ff28017724cdb926474524528b10f8c7384711a8264466c07807b9f69e9e5c80804d4cc60a5d72b7fbe72e977270e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/slash" + } + ] + }, + { + "type": "library", + "name": "slice-ansi", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|slice-ansi@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/slice-ansi@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a8c08c7e1634e347151d3e372bd045ca0a986d43c564a1ce83b2bbde6b5358945bf29c8fddfcdfe08c5de52cdd10943a311520fd606738bc60859b4a2aeac435" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/slice-ansi" + } + ] + }, + { + "type": "library", + "name": "sortablejs", + "version": "1.14.0", + "bom-ref": "launchpad@1.0.0|sortablejs@1.14.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/sortablejs@1.14.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/sortablejs/-/sortablejs-1.14.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a415ef402b39ff7ddf74dd7fdfda4f2f4359176d0b7916cb4398ed9e17883cdf494006ae7c68ca75676e667e14ef00ad56ecca8664642340c56076116c1d87d7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/sortablejs" + } + ] + }, + { + "type": "library", + "name": "source-map-js", + "version": "1.2.2", + "bom-ref": "launchpad@1.0.0|source-map-js@1.2.2", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/source-map-js@1.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2868fff18e37c77e5a6550edb7e27898ad61a0b18750b3187d290e0c93508cd0c2de85b53ea3e8c4cc28d292d4b1633f5041b338dfcdc5e1f2c047cd5cd3f757" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/source-map-js" + } + ] + }, + { + "type": "library", + "name": "source-map-support", + "version": "0.5.21", + "bom-ref": "launchpad@1.0.0|source-map-support@0.5.21", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/source-map-support@0.5.21", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b811d4dcbddccec232617297f3c7ddac6a2fc5d482a13183459e92617b524712d95331e0e4fffae87b7aba85251eef4466877e8a75e12a8dea420c17513ff2d7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/source-map-support" + } + ] + }, + { + "type": "library", + "name": "source-map", + "version": "0.6.1", + "bom-ref": "launchpad@1.0.0|source-map@0.6.1", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/source-map@0.6.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "52381aa6e99695b3219018334fb624739617513e3a17488abbc4865ead1b7303f9773fe1d0f963e9e9c9aa3cf565bab697959aa989eb55bc16396332177178ee" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/source-map" + } + ] + }, + { + "type": "library", + "name": "space-separated-tokens", + "version": "2.0.2", + "bom-ref": "launchpad@1.0.0|space-separated-tokens@2.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/space-separated-tokens@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "3c41a5030ac6f325c65d18d6df67c66e0eba24094e0306ce6eea95a09a6ffe6460a160d07e01f5c033efb735b25123405c119293c87be796036db704cb7487d9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/space-separated-tokens" + } + ] + }, + { + "type": "library", + "name": "splitpanes", + "version": "4.1.2", + "bom-ref": "launchpad@1.0.0|splitpanes@4.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/splitpanes@4.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/splitpanes/-/splitpanes-4.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7eb35c8680afef0d2731012e6831a0306314ea3bf736137a6c119055f08d83025d55c61a4668b57706038e9ed289f028505762423051076e782c9362773a35e5" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/splitpanes" + } + ] + }, + { + "type": "library", + "name": "string-width", + "version": "8.2.2", + "bom-ref": "launchpad@1.0.0|string-width@8.2.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/string-width@8.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/string-width/-/string-width-8.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "19a3d487981f76b633a9e54d66f51f4f6def618c57cca62275472732d260ff7af1455eb7105672de4eb17ca9667de243d35efa967515fd4b2bdd77304af173a6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/string-width" + } + ] + }, + { + "type": "library", + "name": "stringify-entities", + "version": "4.0.4", + "bom-ref": "launchpad@1.0.0|stringify-entities@4.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/stringify-entities@4.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2307c1a6d6ad94ef90089528d7d02abeb3cdaa554ca56f5810bd8b21563e469bf6aac8c21b16832cd460786b1058985f22d79bb8986c1922e36816cd490fa27a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/stringify-entities" + } + ] + }, + { + "type": "library", + "name": "strip-ansi", + "version": "7.2.0", + "bom-ref": "launchpad@1.0.0|strip-ansi@7.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/strip-ansi@7.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c833cc363a785b27d80641e78c844b7dc6b58ba28cc860adb1582829eff3d7eeafba481a10d76018166df9998a3dce206afbc46793a01df1ddadace180dc86ef" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/strip-ansi" + } + ] + }, + { + "type": "library", + "name": "striptags", + "version": "3.2.0", + "bom-ref": "launchpad@1.0.0|striptags@3.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/striptags@3.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/striptags/-/striptags-3.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "838e59386cc70cc7b66dd60c748bdd01f0909024c330605acd2c35ca9328c3018879eed9439754d2b049f09aa097e8c0288bf875b784d63b1c66af7089dd5393" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/striptags" + } + ] + }, + { + "type": "library", + "name": "strnum", + "version": "2.5.1", + "bom-ref": "launchpad@1.0.0|strnum@2.5.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/strnum@2.5.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/strnum/-/strnum-2.5.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "50ce274cb5b34220c1b1e571506c4dd30273224d1453cf508bba4a5f3f6a212a3e961be2262913ba2901b0afe8151969bd81ef49dcf44d5a0bc90fac129630c4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/strnum" + } + ] + }, + { + "type": "library", + "name": "strtok3", + "version": "10.3.5", + "bom-ref": "launchpad@1.0.0|strtok3@10.3.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/strtok3@10.3.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "922e216507e1e6b5f44032cb90e0a3fa1f8254d92a9a9fc231ff2ff2466990d54aea3190a28332b6accb65851560865c159eb20c1ef411f0fc3ce7055e2179a0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/strtok3" + } + ] + }, + { + "type": "library", + "name": "style-mod", + "version": "4.1.3", + "bom-ref": "launchpad@1.0.0|style-mod@4.1.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/style-mod@4.1.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8bf9fc56c67276bba08f722ece597cfb1ff4d061f6be762c9357a8983f10891ad201e5ba22d6c2403b5f5c27891ddd22c2235a82a8d092fa6f44410fb56dc8a1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/style-mod" + } + ] + }, + { + "type": "library", + "name": "style-to-object", + "version": "2.0.2", + "bom-ref": "launchpad@1.0.0|style-to-object@2.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/style-to-object@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/style-to-object/-/style-to-object-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4266d73d4ca5a94f341c081338978439d6c0e345bd2adc668cc850cbeb6af9bf05d9aa21dda40bbb2f36861da39b6aac0bd851f5e234f9e42275333274a72a44" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/style-to-object" + } + ] + }, + { + "type": "library", + "name": "stylelint-config-html", + "version": "2.0.0", + "bom-ref": "launchpad@1.0.0|stylelint-config-html@2.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/stylelint-config-html@2.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/stylelint-config-html/-/stylelint-config-html-2.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2e4d4d3c4754c731e43efdde864b63a623a4e0c3daa90dc7f1f92f871756950a5a6429bdcded12a0c6d140baa453110c7cf1351bdff1f7af2ec66ffe7769e3a0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint-config-html" + } + ] + }, + { + "type": "library", + "name": "stylelint-config-recommended-scss", + "version": "17.0.1", + "bom-ref": "launchpad@1.0.0|stylelint-config-recommended-scss@17.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/stylelint-config-recommended-scss@17.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/stylelint-config-recommended-scss/-/stylelint-config-recommended-scss-17.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c790d57a1cc9b9d730174a1ddec1a9824967d8f2cbada9c513bb70c1ba7b76a0c8342c99bf0cc590c73a4cb84d3af6b346254125801340ba2e258d313c607c58" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint-config-recommended-scss" + } + ] + }, + { + "type": "library", + "name": "stylelint-config-recommended-vue", + "version": "1.6.1", + "bom-ref": "launchpad@1.0.0|stylelint-config-recommended-vue@1.6.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/stylelint-config-recommended-vue@1.6.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/stylelint-config-recommended-vue/-/stylelint-config-recommended-vue-1.6.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "94b5bb85320c0624df8de9c6b83ab69321c0e9f05677ff837fb30ee3f0163b18857973fd7256e92a0836ee41dfc00dc7ed434c182eda78fde6365641e4b32611" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint-config-recommended-vue" + } + ], + "components": [ + { + "type": "library", + "name": "semver", + "version": "7.8.5", + "bom-ref": "launchpad@1.0.0|stylelint-config-recommended-vue@1.6.1|semver@7.8.5", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/semver@7.8.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "63bfca0ec6fc2e3a28669c1aa86cae94ee8342592c8029dc7211c693eb19218e1206f52870c044147e54af57c8e1d57e26f974c3a723bee71a222e34a6e462a0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint-config-recommended-vue/node_modules/semver" + } + ] + } + ] + }, + { + "type": "library", + "name": "stylelint-config-recommended", + "version": "18.0.0", + "bom-ref": "launchpad@1.0.0|stylelint-config-recommended@18.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/stylelint-config-recommended@18.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/stylelint-config-recommended/-/stylelint-config-recommended-18.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9b1813d9763a619dc75967b70e2f2e986e9a0665a61d36e54e0bbf7f5d2ba855e7c96c63296c0d7634969209300adc482a7aa3489cef1663d3e7269b54847166" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint-config-recommended" + } + ] + }, + { + "type": "library", + "name": "stylelint-scss", + "version": "7.2.0", + "bom-ref": "launchpad@1.0.0|stylelint-scss@7.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/stylelint-scss@7.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/stylelint-scss/-/stylelint-scss-7.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e84efd05a721bf4233d20a9151981da9d5c2b22ab6e8358158804d1d8b634e6029df026ee9ca7f237ed57d6ec13e7b66876a6e1776d8d3d5d69781d91ab2e1cf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint-scss" + } + ] + }, + { + "type": "library", + "name": "stylelint-use-logical", + "version": "2.1.3", + "bom-ref": "launchpad@1.0.0|stylelint-use-logical@2.1.3", + "licenses": [ + { + "license": { + "id": "CC0-1.0" + } + } + ], + "purl": "pkg:npm/stylelint-use-logical@2.1.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/stylelint-use-logical/-/stylelint-use-logical-2.1.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "85a3e48312ab7be792aabe086499c7c0d4fff7fc080b291e15921acfbad96dee12a214c7930eef05a84c3ab649669767cbf10154701c3c7d8805ea2251c6565b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint-use-logical" + } + ] + }, + { + "type": "library", + "name": "stylelint", + "version": "17.15.0", + "bom-ref": "launchpad@1.0.0|stylelint@17.15.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/stylelint@17.15.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/stylelint/-/stylelint-17.15.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9962247ac610bd08dfe0abdd7aef67b3420bf3f2bfc2d8da1b13eab0f77a0e52d9bda4311b2b09b28731503ac17321d0e5595e024e2e48c6ade3232b5440fb3c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint" + } + ], + "components": [ + { + "type": "library", + "name": "media-query-list-parser", + "group": "@csstools", + "version": "5.0.0", + "bom-ref": "launchpad@1.0.0|stylelint@17.15.0|@csstools/media-query-list-parser@5.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40csstools/media-query-list-parser@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@csstools/media-query-list-parser/-/media-query-list-parser-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4fd95799939f9da9b778c1113ecb338d8e4d2b48d7f119938669a6f7d159f1bef3f3231a15958ac0b58666e4f074eddd7516397f2d771a69846195c1e08f7c12" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint/node_modules/@csstools/media-query-list-parser" + } + ] + }, + { + "type": "library", + "name": "ignore", + "version": "7.0.6", + "bom-ref": "launchpad@1.0.0|stylelint@17.15.0|ignore@7.0.6", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ignore@7.0.6", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ignore/-/ignore-7.0.6.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "04083a42413c5be4ee40baebc34520afb1de81776e46eba3f3fb62da448e73e8f3d5d9b1f3f58d723afa5c69eae58a435b1170c1a6afa83d3e8c850e29e953b3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint/node_modules/ignore" + } + ] + }, + { + "type": "library", + "name": "postcss-safe-parser", + "version": "7.0.1", + "bom-ref": "launchpad@1.0.0|stylelint@17.15.0|postcss-safe-parser@7.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/postcss-safe-parser@7.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/postcss-safe-parser/-/postcss-safe-parser-7.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d008a8342259d833d8cf90014fa6dd748aa5860c21a4767f97ae58018a34042227d31883a6c9d31f3d209e84c6934397656d0946cf9c0f02fcbbfb5e45dcfef0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/stylelint/node_modules/postcss-safe-parser" + } + ] + } + ] + }, + { + "type": "library", + "name": "supports-color", + "version": "7.2.0", + "bom-ref": "launchpad@1.0.0|supports-color@7.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/supports-color@7.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "aa9080bd197db2db8e1ef78ab27ec79dc251befe74d6a21a70acd094effe2f0c5cf7ed2adb02f2bf80dfbedf34fc33e7da9a8e06c25d0e2a205c647df8ebf047" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/supports-color" + } + ] + }, + { + "type": "library", + "name": "supports-hyperlinks", + "version": "4.5.0", + "bom-ref": "launchpad@1.0.0|supports-hyperlinks@4.5.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/supports-hyperlinks@4.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-4.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "656d8ebdf7825eb3536cb6a43d4ce3406f76d8478608eb5e1525687a4e43292b5387cf7cc1fef382db8597340df077d90b10b7121d36c8956b456e758400dffb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/supports-hyperlinks" + } + ], + "components": [ + { + "type": "library", + "name": "has-flag", + "version": "5.0.1", + "bom-ref": "launchpad@1.0.0|supports-hyperlinks@4.5.0|has-flag@5.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/has-flag@5.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/has-flag/-/has-flag-5.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0ac354b79c7d2d4771ea19e4fc4d9264bb03caf7ea00d65252ae3e0f70fc4730c9d8cf870d322417ad226d2d6f1da2b9e6fce0899c356c43c51bdc87ee5df7c0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/supports-hyperlinks/node_modules/has-flag" + } + ] + }, + { + "type": "library", + "name": "supports-color", + "version": "10.2.2", + "bom-ref": "launchpad@1.0.0|supports-hyperlinks@4.5.0|supports-color@10.2.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/supports-color@10.2.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "492fa3c78e461754238045d0c78349655f489aa98ed8d3f3e4536c207aec0e387662c1e76b0a5a9fb48d435a3c36e86b6c7672f4066122809488279a5bf0bcd2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/supports-hyperlinks/node_modules/supports-color" + } + ] + } + ] + }, + { + "type": "library", + "name": "svg-tags", + "version": "1.0.0", + "bom-ref": "launchpad@1.0.0|svg-tags@1.0.0", + "purl": "pkg:npm/svg-tags@1.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/svg-tags/-/svg-tags-1.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a2fb2ccac4136be96e87b03959ebb746d6ba1499450416c89e33a1ef6d8b22dea4969536fc7b5d51bb338eefc6e1d7af72f93c3c6b7b1422efe707edbb74c750" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/svg-tags" + } + ] + }, + { + "type": "library", + "name": "tabbable", + "version": "6.5.2", + "bom-ref": "launchpad@1.0.0|tabbable@6.5.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/tabbable@6.5.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/tabbable/-/tabbable-6.5.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5e07670759c653a294e1580c9d93da642c7b335841acbc8489961abb61b682af544f477b778154065357eefbcf966fc1d6f9353e3af3241c7d2dbbf87eca92f6" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/tabbable" + } + ] + }, + { + "type": "library", + "name": "table", + "version": "6.9.0", + "bom-ref": "launchpad@1.0.0|table@6.9.0", + "licenses": [ + { + "license": { + "id": "BSD-3-Clause" + } + } + ], + "purl": "pkg:npm/table@6.9.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/table/-/table-6.9.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "f6463e0b283260cea3d36b796051db373d85379426606bfdcc08d5a789420e3942c3b6a675c917944b7f6e33215087e3e13846444e200941f9fb21a736e3e8e4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/table" + } + ], + "components": [ + { + "type": "library", + "name": "string-width", + "version": "4.2.3", + "bom-ref": "launchpad@1.0.0|table@6.9.0|string-width@4.2.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/string-width@4.2.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c0ac90450a63274b08a7ad84ad265d1ac8cc256b1aa79a1136284786ee86ec954effd8c807a5327af2feb57b8eaab9e0f23fdcc4a4d6c96530bd24eb8a2673fe" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/table/node_modules/string-width" + } + ] + }, + { + "type": "library", + "name": "strip-ansi", + "version": "6.0.1", + "bom-ref": "launchpad@1.0.0|table@6.9.0|strip-ansi@6.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/strip-ansi@6.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "637f153d21dcaa416b0a916743dbee4979aabaebf9a1738aa46793e9a1abaf7a3719cf409556ba2417d448e0a76f1186645fbfd28a08ecaacfb944b3b54754e4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/table/node_modules/strip-ansi" + } + ] + }, + { + "type": "library", + "name": "ansi-regex", + "version": "5.0.1", + "bom-ref": "launchpad@1.0.0|table@6.9.0|ansi-regex@5.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ansi-regex@5.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "aae2505e54d25062f62c7f52517a3c570b18e2ca1a9e1828e8b3529bce04d4b05c13cb373b4c29762473c91f73fd9649325316bf7eea38e6fda5d26531410a15" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/table/node_modules/ansi-regex" + } + ] + } + ] + }, + { + "type": "library", + "name": "tapable", + "version": "2.3.3", + "bom-ref": "launchpad@1.0.0|tapable@2.3.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/tapable@2.3.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bb173fce9a8583ac7b0bcbce13b961e8b6dd6bc7842fdce6566fcf2de4cf051861d710a0756690f89d42522786a487e6d8776db14a51bfe1ec8626ac04c71ce8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/tapable" + } + ] + }, + { + "type": "library", + "name": "terser", + "version": "5.51.2", + "bom-ref": "launchpad@1.0.0|terser@5.51.2", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/terser@5.51.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6d69e348db1c9ae23e189cdee99ba99c73fc1bf71372c245f9b5c279092793648742c81b3499cbaea887f636765b84933d55c7da60ca2915f78b03e173d0a7fd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/terser" + } + ], + "components": [ + { + "type": "library", + "name": "commander", + "version": "2.20.3", + "bom-ref": "launchpad@1.0.0|terser@5.51.2|commander@2.20.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/commander@2.20.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1a956498cf2f176bd05248f62ef6660f7e49c5e24e2c2c09f5c524ba0ca4da7ba16efdfe989be92d862dfb4f9448cc44fa88fe7b2fe52449e1670ef9c7f38c71" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/terser/node_modules/commander" + } + ] + } + ] + }, + { + "type": "library", + "name": "tinyglobby", + "version": "0.2.17", + "bom-ref": "launchpad@1.0.0|tinyglobby@0.2.17", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/tinyglobby@0.2.17", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c1747f758a5ca8a99f5a911d66388a24ec023459dd0f40cc9eb5bf7188d51adb449017d581c2c51e836b963e3b9a339589cf72c8dbbae5a96c805e0d4324dada" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/tinyglobby" + } + ] + }, + { + "type": "library", + "name": "to-regex-range", + "version": "5.0.1", + "bom-ref": "launchpad@1.0.0|to-regex-range@5.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/to-regex-range@5.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "eb93fb8b3e97e7212bd5cc1c82f4316db230ed493780ecb974876d678ac3bde2ea86b7493fe2e2fc7c7ab722b43446fed860b29de08c2621aaac00c248d93cb1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/to-regex-range" + } + ] + }, + { + "type": "library", + "name": "toastify-js", + "version": "1.12.0", + "bom-ref": "launchpad@1.0.0|toastify-js@1.12.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/toastify-js@1.12.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/toastify-js/-/toastify-js-1.12.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1de30708ef722cfbcff64d1aa4649d3d45ab51b2e7c5428d173814a19a753c708ba65a085ffe03490ed5f07db979ffa1e223bd9f485eec899f72776737a9c3ad" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/toastify-js" + } + ] + }, + { + "type": "library", + "name": "tributejs", + "version": "5.1.3", + "bom-ref": "launchpad@1.0.0|tributejs@5.1.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/tributejs@5.1.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/tributejs/-/tributejs-5.1.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0790978a1695cd7c3ed541e1345c80c144cc0e4d447e82cfe538f55610fdcb26d9d48f0364912ff2d675974449a34b74b64f59851f1e1b9b44b1a0af46282675" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/tributejs" + } + ] + }, + { + "type": "library", + "name": "trim-lines", + "version": "3.0.1", + "bom-ref": "launchpad@1.0.0|trim-lines@3.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/trim-lines@3.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9118fc07e60764273d91061d59f241dbfa1497dac0f7da9ba3061806daf8ba2e26672010d89a6f54177fe94d989680137ea06105348c853a60047b54d0c7f746" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/trim-lines" + } + ] + }, + { + "type": "library", + "name": "trough", + "version": "2.2.0", + "bom-ref": "launchpad@1.0.0|trough@2.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/trough@2.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b663292b4d018d9894c95cafac12bb9277ab3609a0bdc57f28b572ba66bf482f9340dd7aec6acc45c880353cf4f7e937cd6f0bf2deb48d63b51a97e465d8d36b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/trough" + } + ] + }, + { + "type": "library", + "name": "ts-api-utils", + "version": "2.5.0", + "bom-ref": "launchpad@1.0.0|ts-api-utils@2.5.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ts-api-utils@2.5.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "389fe26f184f96aacc33452234727fd02290928285db8dff0049a996ddeaa518245bc546ec87ce4b8d61ed5f138c84ea741c87ceb8dc4bfdac8becb894887c34" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/ts-api-utils" + } + ] + }, + { + "type": "library", + "name": "ts-md5", + "version": "2.0.1", + "bom-ref": "launchpad@1.0.0|ts-md5@2.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ts-md5@2.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ts-md5/-/ts-md5-2.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c85df9142a0438507339c95290c34451b15066ebfcf4a110fb95f3d371eb312194181d7eafe125f89886385c2c3f8a7d445373c25af2758a132ef3ceb880a5f7" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ts-md5" + } + ] + }, + { + "type": "library", + "name": "tslib", + "version": "2.8.1", + "bom-ref": "launchpad@1.0.0|tslib@2.8.1", + "licenses": [ + { + "license": { + "id": "0BSD" + } + } + ], + "purl": "pkg:npm/tslib@2.8.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "a0916ef781d06fe29576e49440bef09e99aa9df98bb0e03f9c087a6fa107d30084a0ad3f98f79753a737c0a0d5f373243ae1cf447b525ca294f7d2016b34bfdb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/tslib" + } + ] + }, + { + "type": "library", + "name": "type-check", + "version": "0.4.0", + "bom-ref": "launchpad@1.0.0|type-check@0.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/type-check@0.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5e5794a1cf6ec065ea8d6c176944d9026ccc705679f39f10036befc7552be7121c8b15c83fef0b9c50e0469954df4bacead7aa765b2415fbbe69ee0aefd3a87b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/type-check" + } + ] + }, + { + "type": "library", + "name": "typescript-event-target", + "version": "1.1.2", + "bom-ref": "launchpad@1.0.0|typescript-event-target@1.1.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/typescript-event-target@1.1.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/typescript-event-target/-/typescript-event-target-1.1.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "4ef92b4d4a6fee008f95c9d2a04c14554070b1d85e2a6f87179bb6b4f00ab9b90818c7e8bdd4a2cc24da65163f36147cf888f2f2265951aa5b55002c36b905af" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/typescript-event-target" + } + ] + }, + { + "type": "library", + "name": "typescript", + "version": "5.9.3", + "bom-ref": "launchpad@1.0.0|typescript@5.9.3", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/typescript@5.9.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8e5d6f6733c38a72ebf5e52ddc9feded5e8580d130f508ef04f772b33f4a7d00c3e357d0ac2d98e2f290762694a454f86d795bd511e12e9a7cc2d9ba3394e04b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/typescript" + } + ] + }, + { + "type": "library", + "name": "ufo", + "version": "1.6.4", + "bom-ref": "launchpad@1.0.0|ufo@1.6.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/ufo@1.6.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "24535b903d52bf07b42af1a2f0639e2dc3f8900590eb4f6dc2f09d707c6ad6848bf2cbefdfd66e4af6a3703f01fb90f478be3eb3522cd83fcee8a377a9c4de44" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/ufo" + } + ] + }, + { + "type": "library", + "name": "undici-types", + "version": "8.3.0", + "bom-ref": "launchpad@1.0.0|undici-types@8.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/undici-types@8.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8f7ef949c57ad1da26f9890f1487d32dc3a23f190dfdbb87cf91a86e32e18b116e00d68db370bd9781a6ad6a9e8e05d627b05b25c158a53114912d467bc6e965" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/undici-types" + } + ] + }, + { + "type": "library", + "name": "unicorn-magic", + "version": "0.4.0", + "bom-ref": "launchpad@1.0.0|unicorn-magic@0.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unicorn-magic@0.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c07e7dd15f55360607f60de51fdc168d3ad4a0ab232c5eac18b8e1478b07d4b5a92e608e1f465fecfba484303c0624bb2877b8a0f3647131ea6248fb48e1943b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/unicorn-magic" + } + ] + }, + { + "type": "library", + "name": "unified", + "version": "11.0.5", + "bom-ref": "launchpad@1.0.0|unified@11.0.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unified@11.0.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c4abc684f5b0de4f3842387c6c8dd97898ea9f269d2be18416d6b349f66ffeb29e4e44e3389868ea616a87648cf7a888719a24c623a983bf066b34d283cf8a1c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unified" + } + ] + }, + { + "type": "library", + "name": "unist-builder", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|unist-builder@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unist-builder@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unist-builder/-/unist-builder-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c264459c7f812e96674caa5ce4beceebb29a73cf6cf4732bb442e99cd684e930286eae434d966ce5869341f019040f5b14f102c76b9500f3b7d5cf8656e83c9a" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unist-builder" + } + ] + }, + { + "type": "library", + "name": "unist-util-is", + "version": "6.0.1", + "bom-ref": "launchpad@1.0.0|unist-util-is@6.0.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unist-util-is@6.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2ec8882dbb41113903cfc23da75750d2ec91516b9a43377f72e11e4b5868452c96e44e571a64f39706353ab373cda906a3023d0ebfc8f0755ac38853b67c72f2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unist-util-is" + } + ] + }, + { + "type": "library", + "name": "unist-util-position", + "version": "5.0.0", + "bom-ref": "launchpad@1.0.0|unist-util-position@5.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unist-util-position@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7ee72c0bb1e35ef901e51de44c23bb9148d176b4b4049b7733f14fc661cc04e9bc2508b606c1c01c5b32dbb13412894ff2ba743735ec27e8cd3f20d6bce2593c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unist-util-position" + } + ] + }, + { + "type": "library", + "name": "unist-util-stringify-position", + "version": "4.0.0", + "bom-ref": "launchpad@1.0.0|unist-util-stringify-position@4.0.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unist-util-stringify-position@4.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "d00495d3a000a0a083912dbec70e515c9cb0aeebaba5b0b82594a6ee7afb30eb75a23033bf2c9a3be53165fd7c8fc14217a926cc264a70080dff2bb6826d9781" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unist-util-stringify-position" + } + ] + }, + { + "type": "library", + "name": "unist-util-visit-parents", + "version": "6.1.0", + "bom-ref": "launchpad@1.0.0|unist-util-visit-parents@6.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unist-util-visit-parents@6.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "bca5f1cfa3b7f2c2838f59adc7f936716be490506e606c7ab86ae5cc191579609117f17cb1d2348f759b933ff9ad535146e55cf14ae045d6c2c4d86661780fdf" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unist-util-visit-parents" + } + ] + }, + { + "type": "library", + "name": "unist-util-visit", + "version": "5.2.0", + "bom-ref": "launchpad@1.0.0|unist-util-visit@5.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unist-util-visit@5.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7e9b18b3f555a19c5f198f7f8f7150a5998df3074b25a5753eddfc01a24d66ef6e2881dc154de16a509d06f784ab51c628ed4e11f258eb9c35cefa055756f7a9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unist-util-visit" + } + ] + }, + { + "type": "library", + "name": "unplugin-utils", + "version": "0.3.2", + "bom-ref": "launchpad@1.0.0|unplugin-utils@0.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unplugin-utils@0.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unplugin-utils/-/unplugin-utils-0.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c554e8461d824e62e4d879c41bb69ce2b9753094d3dd1164a52f01fbefd29c1d245efb9a6af0fe9f79bfbebcf259039d24d4994000a76f3d35a67a696f057904" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unplugin-utils" + } + ] + }, + { + "type": "library", + "name": "unplugin", + "version": "3.7.0", + "bom-ref": "launchpad@1.0.0|unplugin@3.7.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/unplugin@3.7.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/unplugin/-/unplugin-3.7.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1ab336baadc3428de1bcb536163798868a09f0163d37a8f515bce0c7b3ed6b755525ebec0f754fe1d3e366464e4b498bbcdf30f73cebf4e94ffb7d5b48ccae2f" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/unplugin" + } + ] + }, + { + "type": "library", + "name": "update-browserslist-db", + "version": "1.3.2", + "bom-ref": "launchpad@1.0.0|update-browserslist-db@1.3.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/update-browserslist-db@1.3.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "510f8c4b1961466d5bce3854f8372e5df8c53b517336daa12b9fbd62f969f7422d0cb939bd3f77d80d2b16eeb5f677fb4554be63f55e6945b58da443a99f1527" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/update-browserslist-db" + } + ] + }, + { + "type": "library", + "name": "uri-js", + "version": "4.4.1", + "bom-ref": "launchpad@1.0.0|uri-js@4.4.1", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/uri-js@4.4.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "eeb294cb2df7435c9cf7ca50d430262edc17d74f45ed321f5a55b561da3c5a5d628b549e1e279e8741c77cf78bd9f3172bacf4b3c79c2acf5fac2b8b26f9dd06" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/uri-js" + } + ] + }, + { + "type": "library", + "name": "url-join", + "version": "5.2.0", + "bom-ref": "launchpad@1.0.0|url-join@5.2.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/url-join@5.2.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/url-join/-/url-join-5.2.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "fed31541da7fd9e13dd1f19bea7a5b7769cb1c7f236a6ccb2de6612c4293cf845cdfcc0ee40784b888685aba1659f4094b9d19ccbe17a1df49111fe92564d311" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/url-join" + } + ] + }, + { + "type": "library", + "name": "url-parse", + "version": "1.5.10", + "bom-ref": "launchpad@1.0.0|url-parse@1.5.10", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/url-parse@1.5.10", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "5b2a5c7e24617de50ff6fbc5d23eabc3427786b5abc3a899bf7fb6da1ea244c27ff33d538fa5df2cfe03b148b1e4c84c3e75e98870e82b2a19fdb74293004289" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/url-parse" + } + ] + }, + { + "type": "library", + "name": "util-deprecate", + "version": "1.0.2", + "bom-ref": "launchpad@1.0.0|util-deprecate@1.0.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/util-deprecate@1.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "10f0f9ab5b97c85c49a42acb9c27359c79eade039ae83641a1c008888d93692080ed5089d5424331a802cc891736c5187c3d5d68afff2d3110f318886eb1ed73" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/util-deprecate" + } + ] + }, + { + "type": "library", + "name": "vfile-message", + "version": "4.0.4", + "bom-ref": "launchpad@1.0.0|vfile-message@4.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vfile-message@4.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ebac9c46cc0890d9871fd3c792eec00edbf9455c2022b39cbafdc9f12bf3ea1e2a80646b2956bef7f9deb8ac896545f23a96302d3bd2fb0859e11daeac71e042" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vfile-message" + } + ] + }, + { + "type": "library", + "name": "vfile", + "version": "6.0.3", + "bom-ref": "launchpad@1.0.0|vfile@6.0.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vfile@6.0.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2b321b1fff6d5dab76bb7d237feb26330142b27a38c0755d366cc5c8bf93fcbdd41aaaa4e8929f56a3853991296521c00c7d64e3469be8d5085d9ab8db6a2fdd" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vfile" + } + ] + }, + { + "type": "library", + "name": "vite", + "version": "8.3.8", + "bom-ref": "launchpad@1.0.0|vite@8.3.8", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vite@8.3.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2f33a7de1f6b1bfd2f84b757ad5e3227840503d784a2a0a5f98c7e90625deda07dc3a9df3605472926302cf6541ebcf86466beb7e9178d5f62b6f7070cb428b8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/vite" + } + ] + }, + { + "type": "library", + "name": "vue-codemirror6", + "version": "1.6.2", + "bom-ref": "launchpad@1.0.0|vue-codemirror6@1.6.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue-codemirror6@1.6.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue-codemirror6/-/vue-codemirror6-1.6.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "53b5dd14229b2c3b821ab7c7f9b0856d66d23c1021105ac160b04eaed8a607fcaf32d9ac97069b6733b888baaeb40f1405bdfb490e81f82c23d509820ee1b19e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue-codemirror6" + } + ] + }, + { + "type": "library", + "name": "vue-demi", + "version": "0.14.10", + "bom-ref": "launchpad@1.0.0|vue-demi@0.14.10", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue-demi@0.14.10", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "9cc6413b0bb369b50ed272e021c73aaf271911e6c5e9e7947da890c7df964a4f1edbd21b2ef3d4f5f788eada96e244e8de1be8600264321f27f03d1fb884a986" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue-demi" + } + ] + }, + { + "type": "library", + "name": "vue-eslint-parser", + "version": "10.4.2", + "bom-ref": "launchpad@1.0.0|vue-eslint-parser@10.4.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue-eslint-parser@10.4.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.4.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "58ca73ba56f9d246fab27821ce81b34befbadb070eb33024fe9898727bf3752b4cf169e2fc19a881896da68385bf678af610db5f1bf0150827c191a902851fa4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue-eslint-parser" + } + ], + "components": [ + { + "type": "library", + "name": "semver", + "version": "7.8.5", + "bom-ref": "launchpad@1.0.0|vue-eslint-parser@10.4.2|semver@7.8.5", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/semver@7.8.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "63bfca0ec6fc2e3a28669c1aa86cae94ee8342592c8029dc7211c693eb19218e1206f52870c044147e54af57c8e1d57e26f974c3a723bee71a222e34a6e462a0" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue-eslint-parser/node_modules/semver" + } + ] + } + ] + }, + { + "type": "library", + "name": "vue-loader", + "version": "17.4.2", + "bom-ref": "launchpad@1.0.0|vue-loader@17.4.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue-loader@17.4.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue-loader/-/vue-loader-17.4.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "c9328e03847f54de23aa3c38cb91ebca714bf002b4677fc9b7b78e257122b6c9b418c4470c18c27c28ae4e22cfece112bec658a36a404c25a10eac42e59acceb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue-loader" + } + ] + }, + { + "type": "library", + "name": "vue-material-design-icons", + "version": "5.4.0", + "bom-ref": "launchpad@1.0.0|vue-material-design-icons@5.4.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue-material-design-icons@5.4.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue-material-design-icons/-/vue-material-design-icons-5.4.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "36a2935a7fb8727583883d8feb178aa9a2e0d6219a8e5d1555470c6dcbf96834685c53eeef486a379e6c052ac629ab6478fe4cd5a0d9fd80a20a0064afdaa1d4" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue-material-design-icons" + } + ] + }, + { + "type": "library", + "name": "vue-router", + "version": "4.6.4", + "bom-ref": "launchpad@1.0.0|vue-router@4.6.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue-router@4.6.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "1f3f6ae6c6b7dd885dba0970cfa83db244fc3813e28bee1b167f3cc3a27e27831f128e0a451a6688d1bf8471e475b44594b04eab137ccbc81fd856f431352056" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue-router" + } + ], + "components": [ + { + "type": "library", + "name": "devtools-api", + "group": "@vue", + "version": "6.6.4", + "bom-ref": "launchpad@1.0.0|vue-router@4.6.4|@vue/devtools-api@6.6.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/%40vue/devtools-api@6.6.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "b068533ccb97a99d6b54e937d91ca5ced5a47d74d186e4bbbe000abf4ce3aa4f206ec1e427bc5f15ffa36f24b1b7bb5639b109c3229a1cc8a457f5860e2426f2" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue-router/node_modules/@vue/devtools-api" + } + ] + } + ] + }, + { + "type": "library", + "name": "vue3-apexcharts", + "version": "1.8.0", + "bom-ref": "launchpad@1.0.0|vue3-apexcharts@1.8.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue3-apexcharts@1.8.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue3-apexcharts/-/vue3-apexcharts-1.8.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "e6d483e265d305b209f62afee7ca8713aa0db487b444d82a21160c2a972c21ac642adc14c30e0986f3e4a541659a25b83896db7649608e5797ab595f70ce2074" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue3-apexcharts" + } + ] + }, + { + "type": "library", + "name": "vue", + "version": "3.5.45", + "bom-ref": "launchpad@1.0.0|vue@3.5.45", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vue@3.5.45", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vue/-/vue-3.5.45.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ddcbec89bf26f5cd2f076e3e3032ac81c5b8f836b8c5a065f59ff94db9b6a66488b113f172297871d5e35e556c989da0eb85c9a3987e21177baec7464fda596b" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vue" + } + ] + }, + { + "type": "library", + "name": "vuedraggable", + "version": "4.1.0", + "bom-ref": "launchpad@1.0.0|vuedraggable@4.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/vuedraggable@4.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/vuedraggable/-/vuedraggable-4.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "154e47096066b1fdb41a93f77ae754456dd67564ca21b10843187dffc184f34ea1c9d47da99a91471444dd18ea5fb3e4b8bb8c406fc0ee7ddc7e3f6b084721c3" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/vuedraggable" + } + ] + }, + { + "type": "library", + "name": "w3c-keyname", + "version": "2.2.8", + "bom-ref": "launchpad@1.0.0|w3c-keyname@2.2.8", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/w3c-keyname@2.2.8", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "769a2306136c08d37b4fcd939bb936e80e86f4c2f7364843b27c3d9ff7a8c52465541078084b4843f29308b2361707f76ad6925d1858164422dd29671703ef3d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/w3c-keyname" + } + ] + }, + { + "type": "library", + "name": "watchpack", + "version": "2.5.2", + "bom-ref": "launchpad@1.0.0|watchpack@2.5.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/watchpack@2.5.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ea2ff4d0d0633f8c863ecf9c68a4b245fa5317ff13a2bb2ed0c396de633321b86021215d7abf22ef16ea80794b33026b76237c9dd055dd4035fc07f33d2afe8e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/watchpack" + } + ] + }, + { + "type": "library", + "name": "web-streams-polyfill", + "version": "3.3.3", + "bom-ref": "launchpad@1.0.0|web-streams-polyfill@3.3.3", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/web-streams-polyfill@3.3.3", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "7762562c28af999613488a207bd32c805099aede7bd418a47161989230b59219656d3783946a99d83f2f0fc13f9496bc58659b6fb3e59bcfd725857b2091d967" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/web-streams-polyfill" + } + ] + }, + { + "type": "library", + "name": "webdav", + "version": "5.11.0", + "bom-ref": "launchpad@1.0.0|webdav@5.11.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/webdav@5.11.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/webdav/-/webdav-5.11.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "0db512f2b1ef5ac7b9e44887334ab9ab5cf77954422d65bb55aee652a036fc925d40721ec383a9d874e094790124338056b41e41fd08f9111426422b62ab4bfb" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/webdav" + } + ], + "components": [ + { + "type": "library", + "name": "entities", + "version": "6.0.1", + "bom-ref": "launchpad@1.0.0|webdav@5.11.0|entities@6.0.1", + "licenses": [ + { + "license": { + "id": "BSD-2-Clause" + } + } + ], + "purl": "pkg:npm/entities@6.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "68df7b357585e805814da85f54e22b07f352864ce2e47ec5f6bd6cf660f77038f82a8e5fdaa86156860c89b5c5ec694bbde6ff0f68a859acbc97123ded57a7de" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/webdav/node_modules/entities" + } + ] + }, + { + "type": "library", + "name": "minimatch", + "version": "11.0.9", + "bom-ref": "launchpad@1.0.0|webdav@5.11.0|minimatch@11.0.9", + "licenses": [ + { + "license": { + "id": "BlueOak-1.0.0" + } + } + ], + "purl": "pkg:npm/minimatch@11.0.9", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "2821647f28ea7ab3654acb6396120635720a64603fe8ee15e1196167e0ecafadb548f3f0d26ce5ca913d0fd64ea0f89579f1c80fe8fbfd7b8c325a9f0ff17ad1" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/webdav/node_modules/minimatch" + } + ] + } + ] + }, + { + "type": "library", + "name": "webpack-sources", + "version": "3.5.1", + "bom-ref": "launchpad@1.0.0|webpack-sources@3.5.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/webpack-sources@3.5.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.5.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8f2ba218976dbd8e37e33e5b519ae3cfaeefefafde3cdbc5653a7d31dcf6f48947e3e18fb20c868e2bf47ca23e33b05d914e800e3ba551c280777b542b75a513" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/webpack-sources" + } + ] + }, + { + "type": "library", + "name": "webpack-virtual-modules", + "version": "0.6.2", + "bom-ref": "launchpad@1.0.0|webpack-virtual-modules@0.6.2", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/webpack-virtual-modules@0.6.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ebafd5da2e6141a9c2e75bc140a3c7e1a23c34c01c056e7d15506cfab0bb7861eea4cc9f9f7e2aeeb64813e113949f974debea7d485554181250d496d9f94451" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/webpack-virtual-modules" + } + ] + }, + { + "type": "library", + "name": "webpack", + "version": "5.110.1", + "bom-ref": "launchpad@1.0.0|webpack@5.110.1", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/webpack@5.110.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/webpack/-/webpack-5.110.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8089d007e8f15f1827672bcfc2ecd3e4d190984083a9ebbce68c5cae38a7ad81ea3e805ec7484200dd92153255c8f56b2b43eaf44e385453fe7bcf5f01cd74ff" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/webpack" + } + ], + "components": [ + { + "type": "library", + "name": "mime-db", + "version": "1.54.0", + "bom-ref": "launchpad@1.0.0|webpack@5.110.1|mime-db@1.54.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/mime-db@1.54.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "694e4426e20dd960de982700a76bc505fa7f9b810085626750d492c348b1b3bfe45db77a3e0eb8126c0990d745841f1a5add6c1f60935eb2f1a3f880195de83d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/webpack/node_modules/mime-db" + } + ] + } + ] + }, + { + "type": "library", + "name": "which", + "version": "2.0.2", + "bom-ref": "launchpad@1.0.0|which@2.0.2", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/which@2.0.2", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "04b2374e5d535b73ef97bd25df2ab763ae22f9ac29c17aac181616924a8cb676d782b303fb28fbae15b492e103c7325a6171a3116e6881aa4a34c10a34c8e26c" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/which" + } + ] + }, + { + "type": "library", + "name": "word-wrap", + "version": "1.2.5", + "bom-ref": "launchpad@1.0.0|word-wrap@1.2.5", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/word-wrap@1.2.5", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "04ddb607979a30c23d50cb63ac677983978260fa423c3532d052576d8b1a4f9cd8c6314e7244b9dd2403137a56915a16a475d56f706b61c10de13c1ae7907970" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/word-wrap" + } + ] + }, + { + "type": "library", + "name": "write-file-atomic", + "version": "7.0.1", + "bom-ref": "launchpad@1.0.0|write-file-atomic@7.0.1", + "licenses": [ + { + "license": { + "id": "ISC" + } + } + ], + "purl": "pkg:npm/write-file-atomic@7.0.1", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-7.0.1.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "393224f2247cfda091581aafc6bcf1474860c56a676016e56354b984358141f93f545989c3398981014ddd6b2850a1c84afd9e0307be3e96d4cf22f508a4cb5e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/write-file-atomic" + } + ] + }, + { + "type": "library", + "name": "xml-name-validator", + "version": "5.0.0", + "bom-ref": "launchpad@1.0.0|xml-name-validator@5.0.0", + "licenses": [ + { + "license": { + "id": "Apache-2.0" + } + } + ], + "purl": "pkg:npm/xml-name-validator@5.0.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "12f18af042770e16877db465113396012e693bd31921379ab87289c9bf30c9a8d47d051e9e4220d8cbcb0d36784ff4e021c9b71d4d1314181659ba00677d141e" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/xml-name-validator" + } + ] + }, + { + "type": "library", + "name": "xml-naming", + "version": "0.3.0", + "bom-ref": "launchpad@1.0.0|xml-naming@0.3.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/xml-naming@0.3.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "8218a0d93044fc7d7568e56099a840dcc8629af901afa2486249c7fc385d935d275f075b22a049b1b7ccc69bc53c6f1b030efb80ddbd6905af2a9995a0f96f3d" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/xml-naming" + } + ] + }, + { + "type": "library", + "name": "yocto-queue", + "version": "0.1.0", + "bom-ref": "launchpad@1.0.0|yocto-queue@0.1.0", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/yocto-queue@0.1.0", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "ad592cbec9cd09d27fa2119ceb180fc3237c7a1782c6c88b33c9b1b84fedfe6395a897b03ee3b59a22e94c74224604ca08b7b12f831e00555a82db3b1e6359d9" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:development", + "value": "true" + }, + { + "name": "cdx:npm:package:path", + "value": "node_modules/yocto-queue" + } + ] + }, + { + "type": "library", + "name": "zwitch", + "version": "2.0.4", + "bom-ref": "launchpad@1.0.0|zwitch@2.0.4", + "licenses": [ + { + "license": { + "id": "MIT" + } + } + ], + "purl": "pkg:npm/zwitch@2.0.4", + "externalReferences": [ + { + "url": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "type": "distribution", + "hashes": [ + { + "alg": "SHA-512", + "content": "6d7138711fe455984a657fd18cf11f94768a56151597ce67a14defe9bf1aa5f404735c7803ecc1c6367894df0ba8677a599ddd97df29638a3bd7b5459a83e9f8" + } + ], + "comment": "as detected from npm-ls property \"resolved\" and property \"integrity\"" + } + ], + "properties": [ + { + "name": "cdx:npm:package:path", + "value": "node_modules/zwitch" + } + ] + } + ], + "dependencies": [ + { + "ref": "conductionnl/launchpad-1.0.0.0" + } + ] +} diff --git a/scripts/OpenApiControllerReader.php b/scripts/OpenApiControllerReader.php new file mode 100644 index 000000000..d1388763b --- /dev/null +++ b/scripts/OpenApiControllerReader.php @@ -0,0 +1,547 @@ +<?php +/** + * OpenApiControllerReader + * + * Reads a controller source file without loading it: the class summary and, + * per public method, its attributes, parameters, docblock text, `@param` + * descriptions, `@psalm-return` response shapes, `@openapi-stability` tag and + * the HTTP status codes it can answer with. Static parsing keeps the + * generator independent of a Nextcloud runtime (governance-rest-api-reference + * D1). + * + * @category Tooling + * @package OCA\LaunchPad\Scripts + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Scripts; + +use PhpParser\Node; +use PhpParser\Node\Arg; +use PhpParser\Node\Expr\ClassConstFetch; +use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\Variable; +use PhpParser\Node\Identifier; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar\Int_; +use PhpParser\Node\Stmt\Class_; +use PhpParser\Node\Stmt\ClassMethod; +use PhpParser\NodeFinder; +use PhpParser\NodeTraverser; +use PhpParser\NodeVisitor\NameResolver; +use PhpParser\ParserFactory; +use PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode; +use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode; +use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use PHPStan\PhpDocParser\Lexer\Lexer; +use PHPStan\PhpDocParser\Parser\ConstExprParser; +use PHPStan\PhpDocParser\Parser\PhpDocParser; +use PHPStan\PhpDocParser\Parser\TokenIterator; +use PHPStan\PhpDocParser\Parser\TypeParser; +use PHPStan\PhpDocParser\ParserConfig; + +/** + * Reads what the OpenAPI generator needs from a controller's source. + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ +final class OpenApiControllerReader { + + /** + * The fully qualified name of Nextcloud's `Http` class, whose `STATUS_*` constants are status codes. + * + * @var string + */ + private const HTTP_CLASS = 'OCP\AppFramework\Http'; + + /** + * The named arguments that carry a status code. + * + * @var list<string> + */ + private const STATUS_ARGUMENTS = ['statusCode', 'status', 'code']; + + /** + * The calls that refuse with 403: the ADR-023 action check. + * + * @var list<string> + */ + private const FORBIDDING_CALLS = ['actionRefusal', 'requireAction']; + + /** + * The PHPDoc parser. + * + * @var PhpDocParser + */ + private PhpDocParser $docParser; + + /** + * The PHPDoc lexer. + * + * @var Lexer + */ + private Lexer $lexer; + + /** + * Build a reader. + * + * @param OpenApiTypeMapper $types Maps the `@psalm-return` shapes. + * @param array<string, int> $statusCodes The `Http::STATUS_*` names and their codes. + */ + public function __construct( + private readonly OpenApiTypeMapper $types, + private readonly array $statusCodes, + ) { + $config = new ParserConfig(usedAttributes: []); + $constants = new ConstExprParser(config: $config); + $this->lexer = new Lexer(config: $config); + $this->docParser = new PhpDocParser( + config: $config, + typeParser: new TypeParser(config: $config, constExprParser: $constants), + constantExprParser: $constants + ); + }//end __construct() + + /** + * Read one controller file; null when it holds no class. + * + * @param string $file The path of the PHP file. + * + * @return array{class: string, summary: string, methods: array<string, array<string, mixed>>}|null + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public function read(string $file): ?array { + $parser = (new ParserFactory())->createForHostVersion(); + $stmts = $parser->parse((string) file_get_contents($file)); + if ($stmts === null) { + return null; + } + + $traverser = new NodeTraverser(new NameResolver()); + $stmts = $traverser->traverse($stmts); + $class = (new NodeFinder())->findFirstInstanceOf($stmts, Class_::class); + if ($class instanceof Class_ === false || $class->namespacedName === null) { + return null; + } + + $bodies = []; + foreach ($class->getMethods() as $method) { + $bodies[$method->name->toString()] = $this->scanBody(method: $method); + } + + $methods = []; + foreach ($class->getMethods() as $method) { + if ($method->isPublic() === false || $method->isStatic() === true || $method->name->toString() === '__construct') { + continue; + } + + $methods[$method->name->toString()] = $this->readMethod( + method: $method, + codes: $this->reachableCodes(name: $method->name->toString(), bodies: $bodies), + requestParams: $this->reachableRequestParams(name: $method->name->toString(), bodies: $bodies) + ); + } + + return [ + 'class' => $class->namespacedName->toString(), + 'summary' => $this->firstSentence(text: $this->docText(doc: $this->doc(node: $class))), + 'methods' => $methods, + ]; + }//end read() + + /** + * The first sentence of a text, without its closing full stop. + * + * @param string $text The text. + * + * @return string + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public function firstSentence(string $text): string { + $paragraph = trim(explode("\n\n", $text)[0]); + $paragraph = (string) preg_replace('/\s+/', ' ', $paragraph); + if (preg_match('/^(.+?[.!?])(\s|$)/u', $paragraph, $match) === 1) { + $paragraph = $match[1]; + } + + return rtrim($paragraph, '.'); + }//end firstSentence() + + /** + * What the generator needs of one public method. + * + * @param ClassMethod $method The method. + * @param list<int> $codes The status codes it can answer with. + * @param array<string, array<string, mixed>> $requestParams The parameters it reads through `getParam()`. + * + * @return array<string, mixed> + */ + private function readMethod(ClassMethod $method, array $codes, array $requestParams): array { + $doc = $this->doc(node: $method); + $paramDocs = []; + foreach (($doc?->getParamTagValues() ?? []) as $tag) { + $paramDocs[ltrim($tag->parameterName, '$')] = [ + 'type' => (string) $tag->type, + 'description' => $this->collapse(text: $tag->description), + ]; + } + + $params = []; + foreach ($method->params as $param) { + if ($param->var instanceof Variable === false || is_string($param->var->name) === false) { + continue; + } + + $name = $param->var->name; + $params[] = [ + 'name' => $name, + 'native' => $this->nativeType(type: $param->type), + 'optional' => ($param->default !== null || $param->variadic === true), + 'docType' => ($paramDocs[$name]['type'] ?? null), + 'description' => ($paramDocs[$name]['description'] ?? ''), + ]; + } + + $named = array_column($params, 'name'); + foreach ($requestParams as $name => $read) { + if (in_array($name, $named, true) === true) { + continue; + } + + $params[] = [ + 'name' => $name, + 'native' => $read['type'], + 'optional' => true, + 'docType' => null, + 'description' => '', + ]; + } + + return [ + 'attributes' => $this->attributes(method: $method), + 'params' => $params, + 'text' => $this->docText(doc: $doc), + 'responses' => $this->responses(doc: $doc), + 'stability' => $this->tagValue(doc: $doc, name: '@openapi-stability'), + 'codes' => $codes, + ]; + }//end readMethod() + + /** + * The fully qualified names of a method's attributes. + * + * @param ClassMethod $method The method. + * + * @return list<string> + */ + private function attributes(ClassMethod $method): array { + $names = []; + foreach ($method->attrGroups as $group) { + foreach ($group->attrs as $attribute) { + $names[] = $attribute->name->toString(); + } + } + + return $names; + }//end attributes() + + /** + * A native parameter type as written (`?string`, `int|null`), or null when untyped. + * + * @param Node|null $type The type node. + * + * @return string|null + */ + private function nativeType(?Node $type): ?string { + return match (true) { + $type === null => null, + $type instanceof Node\NullableType => '?'.$this->nativeType(type: $type->type), + $type instanceof Node\UnionType => implode('|', array_map(fn (Node $member): string => (string) $this->nativeType(type: $member), $type->types)), + $type instanceof Identifier => $type->toString(), + $type instanceof Name => $type->toString(), + default => null, + }; + }//end nativeType() + + /** + * The response schemas a `@psalm-return` (or `@return`) union of `JSONResponse<status, body, headers>` declares. + * + * @param PhpDocNode|null $doc The docblock. + * + * @return array<int, array<string, mixed>> Status code to body schema; empty when none is declared. + */ + private function responses(?PhpDocNode $doc): array { + $tags = ($doc?->getReturnTagValues(tagName: '@psalm-return') ?? []); + if ($tags === []) { + $tags = ($doc?->getReturnTagValues() ?? []); + } + + $responses = []; + foreach ($tags as $tag) { + if ($tag instanceof ReturnTagValueNode === false) { + continue; + } + + foreach ($this->members(type: $tag->type) as $member) { + if ($member instanceof GenericTypeNode === false || count($member->genericTypes) < 2) { + continue; + } + + $status = $this->types->statusOf(node: $member->genericTypes[0]); + if ($status !== null) { + $responses[$status] = $this->types->schema(node: $member->genericTypes[1]); + } + } + } + + ksort($responses); + return $responses; + }//end responses() + + /** + * The members of a union, or the type itself. + * + * @param TypeNode $type The type. + * + * @return list<TypeNode> + */ + private function members(TypeNode $type): array { + if ($type instanceof UnionTypeNode) { + return array_values($type->types); + } + + return [$type]; + }//end members() + + /** + * The status codes in a method body and the `$this->...()` methods it calls. + * + * @param ClassMethod $method The method. + * + * @return array{codes: list<int>, calls: list<string>, requestParams: array<string, array<string, mixed>>} + */ + private function scanBody(ClassMethod $method): array { + $finder = new NodeFinder(); + $codes = []; + foreach ($finder->findInstanceOf((array) $method->stmts, ClassConstFetch::class) as $fetch) { + if ($fetch->class instanceof Name && $fetch->class->toString() === self::HTTP_CLASS && $fetch->name instanceof Identifier) { + $code = ($this->statusCodes[$fetch->name->toString()] ?? null); + if ($code !== null) { + $codes[] = $code; + } + } + } + + foreach ($finder->findInstanceOf((array) $method->stmts, Arg::class) as $arg) { + if ($arg->name !== null && in_array($arg->name->toString(), self::STATUS_ARGUMENTS, true) === true && $arg->value instanceof Int_) { + $codes[] = $arg->value->value; + } + } + + $calls = []; + foreach ($finder->findInstanceOf((array) $method->stmts, MethodCall::class) as $call) { + if ($call->var instanceof Variable && $call->var->name === 'this' && $call->name instanceof Identifier) { + $calls[] = $call->name->toString(); + } + } + + $requestParams = []; + foreach ($finder->findInstanceOf((array) $method->stmts, MethodCall::class) as $call) { + if ($call->name instanceof Identifier === false) { + continue; + } + + if (in_array($call->name->toString(), self::FORBIDDING_CALLS, true) === true) { + $codes[] = 403; + } + + if ($call->name->toString() === 'getParam') { + $requestParams += $this->requestParam(call: $call); + } + } + + return ['codes' => $codes, 'calls' => array_values(array_unique($calls)), 'requestParams' => $requestParams]; + }//end scanBody() + + /** + * The parameter a `$this->request->getParam('name', default)` call reads. + * + * @param MethodCall $call The call. + * + * @return array<string, array{optional: bool, type: string|null}> Empty when the name is not a literal. + */ + private function requestParam(MethodCall $call): array { + $key = null; + $default = null; + foreach ($call->getArgs() as $position => $arg) { + $name = ($arg->name?->toString() ?? ['key', 'default'][$position] ?? ''); + if ($name === 'key' && $arg->value instanceof Node\Scalar\String_) { + $key = $arg->value->value; + } + + if ($name === 'default') { + $default = $arg->value; + } + } + + if ($key === null) { + return []; + } + + $type = match (true) { + $default instanceof Node\Expr\Array_ => 'array', + $default instanceof Int_ => 'int', + $default instanceof Node\Scalar\Float_ => 'float', + $default instanceof Node\Scalar\String_ => 'string', + $default instanceof Node\Expr\ConstFetch && in_array(strtolower($default->name->toString()), ['true', 'false'], true) => 'bool', + default => null, + }; + + return [$key => ['optional' => true, 'type' => $type]]; + }//end requestParam() + + /** + * The status codes a method reaches, through the methods of its own class it calls. + * + * @param string $name The method. + * @param array<string, array{codes: list<int>, calls: list<string>}> $bodies Every method's scan. + * + * @return list<int> + */ + private function reachableCodes(string $name, array $bodies): array { + $seen = []; + $queue = [$name]; + $codes = []; + while ($queue !== []) { + $current = array_shift($queue); + if (isset($seen[$current]) === true || isset($bodies[$current]) === false) { + continue; + } + + $seen[$current] = true; + $codes = array_merge($codes, $bodies[$current]['codes']); + $queue = array_merge($queue, $bodies[$current]['calls']); + } + + $codes = array_values(array_unique($codes)); + sort($codes); + return $codes; + }//end reachableCodes() + + /** + * The request parameters a method reads through `getParam()`, itself or through the methods of its class it calls. + * + * @param string $name The method. + * @param array<string, array<string, mixed>> $bodies Every method's scan. + * + * @return array<string, array<string, mixed>> + */ + private function reachableRequestParams(string $name, array $bodies): array { + $seen = []; + $queue = [$name]; + $params = []; + while ($queue !== []) { + $current = array_shift($queue); + if (isset($seen[$current]) === true || isset($bodies[$current]) === false) { + continue; + } + + $seen[$current] = true; + $params += $bodies[$current]['requestParams']; + $queue = array_merge($queue, $bodies[$current]['calls']); + } + + return $params; + }//end reachableRequestParams() + + /** + * The parsed docblock of a node, or null. + * + * @param Node $node The class or method. + * + * @return PhpDocNode|null + */ + private function doc(Node $node): ?PhpDocNode { + $comment = $node->getDocComment(); + if ($comment === null) { + return null; + } + + // A union wrapped after its `|` continues on the next line; join it so the type parses whole. + $text = (string) preg_replace('/\|[ \t]*\n[ \t]*\*[ \t]*/', '|', $comment->getText()); + $tokens = new TokenIterator(tokens: $this->lexer->tokenize(s: $text)); + return $this->docParser->parse(tokens: $tokens); + }//end doc() + + /** + * The prose of a docblock before its first tag, paragraphs kept, lines joined. + * + * @param PhpDocNode|null $doc The docblock. + * + * @return string + */ + private function docText(?PhpDocNode $doc): string { + $lines = []; + foreach (($doc?->children ?? []) as $child) { + if ($child instanceof PhpDocTagNode) { + break; + } + + if ($child instanceof PhpDocTextNode) { + $lines[] = $child->text; + } + } + + $paragraphs = preg_split('/\n\s*\n/', trim(implode("\n", $lines))); + $paragraphs = array_map(fn (string $paragraph): string => $this->collapse(text: $paragraph), (array) $paragraphs); + return implode("\n\n", array_filter($paragraphs, static fn (string $paragraph): bool => $paragraph !== '')); + }//end docText() + + /** + * The value of a custom tag such as `@openapi-stability`, or null. + * + * @param PhpDocNode|null $doc The docblock. + * @param string $name The tag, with its `@`. + * + * @return string|null + */ + private function tagValue(?PhpDocNode $doc, string $name): ?string { + foreach (($doc?->getTagsByName(tagName: $name) ?? []) as $tag) { + if ($tag->value instanceof GenericTagValueNode) { + return trim($tag->value->value); + } + } + + return null; + }//end tagValue() + + /** + * A text with its whitespace runs collapsed to single spaces. + * + * @param string $text The text. + * + * @return string + */ + private function collapse(string $text): string { + $text = (string) preg_replace('/\{@(?:see|link)\s+([^}\s]+)\s*\}/', '`$1`', $text); + return trim((string) preg_replace('/\s+/', ' ', $text)); + }//end collapse() +}//end class diff --git a/scripts/OpenApiDocument.php b/scripts/OpenApiDocument.php new file mode 100644 index 000000000..6375fd066 --- /dev/null +++ b/scripts/OpenApiDocument.php @@ -0,0 +1,128 @@ +<?php +/** + * OpenApiDocument + * + * Wires the OpenAPI generator to this repository's files, so the generate + * script and the drift check build the document the same way + * (governance-rest-api-reference D1, D3). + * + * @category Tooling + * @package OCA\LaunchPad\Scripts + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Scripts; + +require_once __DIR__.'/OpenApiRouteCoverage.php'; +require_once __DIR__.'/OpenApiTypeMapper.php'; +require_once __DIR__.'/OpenApiControllerReader.php'; +require_once __DIR__.'/OpenApiGenerator.php'; + +/** + * Builds the document of a checkout. + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ +final class OpenApiDocument { + + /** + * The document of the checkout at `$root`, decoded. + * + * @param string $root The repository root. + * + * @return array<string, mixed> + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function build(string $root): array { + $codes = OpenApiGenerator::statusCodes(httpFile: $root.'/vendor/nextcloud/ocp/OCP/AppFramework/Http.php'); + $aliasTypes = OpenApiGenerator::aliasTypes(file: $root.'/lib/ResponseDefinitions.php'); + $types = new OpenApiTypeMapper(aliases: array_fill_keys(array_keys($aliasTypes), true), statusCodes: $codes); + $generator = new OpenApiGenerator( + reader: new OpenApiControllerReader(types: $types, statusCodes: $codes), + types: $types, + controllerDir: $root.'/lib/Controller', + namespace: 'OCA\LaunchPad\Controller' + ); + $overlayJson = (string) file_get_contents(__DIR__.'/openapi-overlay.json'); + $overlay = (array) self::decoded(value: json_decode($overlayJson, false, 512, JSON_THROW_ON_ERROR)); + $routes = require $root.'/appinfo/routes.php'; + $appVersion = self::appVersion(infoXml: (string) file_get_contents($root.'/appinfo/info.xml')); + if ($appVersion !== null) { + $overlay['info']['version'] = $appVersion; + } + + return $generator->generate( + routes: $routes, + overlay: $overlay, + definitions: OpenApiGenerator::definitions(file: $root.'/lib/ResponseDefinitions.php', types: $types) + ); + }//end build() + + /** + * A decoded JSON value as arrays, with every empty object kept an object so it is written back as `{}`. + * + * @param mixed $value The value `json_decode()` gave with objects. + * + * @return mixed + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function decoded(mixed $value): mixed { + if ($value instanceof \stdClass) { + $properties = get_object_vars($value); + if ($properties === []) { + return $value; + } + + return array_map(static fn (mixed $item): mixed => self::decoded(value: $item), $properties); + } + + if (is_array($value) === true) { + return array_map(static fn (mixed $item): mixed => self::decoded(value: $item), $value); + } + + return $value; + }//end decoded() + + /** + * The `<version>` of an appinfo/info.xml, which the release workflow also writes into openapi.json. + * + * @param string $infoXml The contents of appinfo/info.xml. + * + * @return string|null Null when the file names no version. + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function appVersion(string $infoXml): ?string { + if (preg_match('#<version>\s*([^<\s]+)\s*</version>#', $infoXml, $match) !== 1) { + return null; + } + + return $match[1]; + }//end appVersion() + + /** + * The document of the checkout at `$root`, encoded the way it is committed. + * + * @param string $root The repository root. + * + * @return string + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function encodedFor(string $root): string { + return OpenApiGenerator::encode(document: self::build(root: $root)); + }//end encodedFor() +}//end class diff --git a/scripts/OpenApiDrift.php b/scripts/OpenApiDrift.php new file mode 100644 index 000000000..4afacd8b6 --- /dev/null +++ b/scripts/OpenApiDrift.php @@ -0,0 +1,119 @@ +<?php +/** + * OpenApiDrift + * + * The regeneration half of the `composer lint:openapi` drift check + * (governance-rest-api-reference D3): the committed openapi.json must be + * exactly what `composer openapi:generate` writes, so a changed controller, + * docblock or route that was not regenerated fails `check:strict`. + * + * @category Tooling + * @package OCA\LaunchPad\Scripts + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Scripts; + +/** + * Compares the committed document with a fresh one. + * + * @spec openspec/specs/rest-api-reference/spec.md + */ +final class OpenApiDrift { + + /** + * At most this many differing operations are named; the rest are counted. + * + * @var int + */ + private const NAMED = 10; + + /** + * The problems, one line each; empty when the committed file is current. + * + * @param string $committed The committed openapi.json. + * @param string $generated What the generator writes now. + * + * @return list<string> + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + public static function problems(string $committed, string $generated): array { + if ($committed === $generated) { + return []; + } + + $problems = ['openapi.json is not what `composer openapi:generate` writes; regenerate it and commit the result']; + $changed = self::changedParts( + committed: (array) json_decode($committed, true), + generated: (array) json_decode($generated, true) + ); + foreach (array_slice($changed, 0, self::NAMED) as $part) { + $problems[] = ' changed: '.$part; + } + + if (count($changed) > self::NAMED) { + $problems[] = sprintf(' ... and %d more', (count($changed) - self::NAMED)); + } + + return $problems; + }//end problems() + + /** + * The operations ("VERB /path") and top-level sections that differ. + * + * @param array<string, mixed> $committed The committed document. + * @param array<string, mixed> $generated The fresh document. + * + * @return list<string> + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + public static function changedParts(array $committed, array $generated): array { + $changed = []; + foreach (array_unique(array_merge(array_keys($committed), array_keys($generated))) as $section) { + if ($section !== 'paths' && ($committed[$section] ?? null) !== ($generated[$section] ?? null)) { + $changed[] = (string) $section; + } + } + + $before = self::operations(document: $committed); + $after = self::operations(document: $generated); + foreach (array_unique(array_merge(array_keys($before), array_keys($after))) as $key) { + if (($before[$key] ?? null) !== ($after[$key] ?? null)) { + $changed[] = $key; + } + } + + return $changed; + }//end changedParts() + + /** + * Every operation of a document by "VERB /path". + * + * @param array<string, mixed> $document The document. + * + * @return array<string, mixed> + */ + private static function operations(array $document): array { + $operations = []; + foreach ((array) ($document['paths'] ?? []) as $path => $item) { + foreach ((array) $item as $verb => $operation) { + $operations[strtoupper((string) $verb).' '.$path] = $operation; + } + } + + return $operations; + }//end operations() +}//end class diff --git a/scripts/OpenApiGenerator.php b/scripts/OpenApiGenerator.php new file mode 100644 index 000000000..fedfb73f9 --- /dev/null +++ b/scripts/OpenApiGenerator.php @@ -0,0 +1,752 @@ +<?php +/** + * OpenApiGenerator + * + * Builds `openapi.json` (OpenAPI 3.1) from `appinfo/routes.php` and the + * controllers (governance-rest-api-reference D1): one operation per versioned + * API route, with its parameters, request body, response codes and shapes, + * authentication and `x-launchpad-stability`. The parts no code can say (the + * document's introduction, shared components, wording an integrator needs on + * a handful of operations) come from `scripts/openapi-overlay.json`. + * + * @category Tooling + * @package OCA\LaunchPad\Scripts + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Scripts; + + +/** + * Generates the OpenAPI document of LaunchPad's API. + * + * @spec openspec/specs/rest-api-reference/spec.md + */ +final class OpenApiGenerator { + + /** + * The OpenAPI version written. + * + * @var string + */ + public const OPENAPI_VERSION = '3.1.0'; + + /** + * The verbs that carry a request body; the parameters of the others go in the query. + * + * @var list<string> + */ + private const BODY_VERBS = ['post', 'put', 'patch']; + + /** + * The keys that make an override a whole schema, replacing what it lands on. + * + * @var array<string, true> + */ + private const WHOLE_SCHEMAS = ['$ref' => true, 'allOf' => true, 'anyOf' => true, 'oneOf' => true]; + + /** + * The key an operation carries its access level under until its description is closed. + * + * @var string + */ + private const ACCESS_KEY = 'x-access'; + + /** + * The order verbs are written in under one path. + * + * @var list<string> + */ + private const VERB_ORDER = ['get', 'put', 'post', 'delete', 'patch', 'options', 'head']; + + /** + * The attributes that decide who may call a route. + * + * @var array<string, string> + */ + private const ATTRIBUTES = [ + 'public' => 'OCP\AppFramework\Http\Attribute\PublicPage', + 'user' => 'OCP\AppFramework\Http\Attribute\NoAdminRequired', + 'delegated' => 'OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting', + ]; + + /** + * The sentence each access level adds to an operation's description. + * + * @var array<string, string> + */ + private const ACCESS_SENTENCE = [ + 'public' => 'It needs no login.', + 'user' => 'Needs a signed-in Nextcloud user.', + 'delegated' => 'Needs an administrator, or a user the matching admin setting is delegated to.', + 'admin' => 'Needs an administrator.', + ]; + + /** + * The default description of a success response. + * + * @var array<int, string> + */ + private const SUCCESS_DESCRIPTION = [ + 200 => 'The request succeeded.', + 201 => 'The resource was created.', + 202 => 'The request was accepted.', + 204 => 'The request succeeded; there is no body.', + ]; + + /** + * The reason phrases of the problem responses, by status code. + * + * @var array<int, string> + */ + private const REASONS = [ + 400 => 'Bad Request', + 401 => 'Unauthorized', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 409 => 'Conflict', + 410 => 'Gone', + 413 => 'Content Too Large', + 415 => 'Unsupported Media Type', + 422 => 'Unprocessable Content', + 423 => 'Locked', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + ]; + + /** + * Build a generator. + * + * @param OpenApiControllerReader $reader Reads the controllers. + * @param OpenApiTypeMapper $types Maps parameter types. + * @param string $controllerDir The directory of the controllers. + * @param string $namespace The namespace of the controllers. + */ + public function __construct( + private readonly OpenApiControllerReader $reader, + private readonly OpenApiTypeMapper $types, + private readonly string $controllerDir, + private readonly string $namespace, + ) { + }//end __construct() + + /** + * The `Http::STATUS_*` constants of a copy of Nextcloud's `Http` class, by name. + * + * @param string $httpFile The path of OCP/AppFramework/Http.php. + * + * @return array<string, int> + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function statusCodes(string $httpFile): array { + preg_match_all('/const\s+(STATUS_[A-Z_]+)\s*=\s*(\d+)\s*;/', (string) @file_get_contents($httpFile), $matches, PREG_SET_ORDER); + $codes = []; + foreach ($matches as $match) { + $codes[$match[1]] = (int) $match[2]; + } + + return $codes; + }//end statusCodes() + + /** + * The `@psalm-type` aliases of a definitions file, as component schemas. + * + * @param string $file The file holding the aliases. + * @param OpenApiTypeMapper $types A mapper that already knows the alias names. + * + * @return array<string, array<string, mixed>> + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function definitions(string $file, OpenApiTypeMapper $types): array { + $schemas = []; + foreach (self::aliasTypes(file: $file) as $name => $type) { + $schemas[$name] = $types->schemaOf(type: $type); + } + + return $schemas; + }//end definitions() + + /** + * The `@psalm-type` aliases of a definitions file, name to type string. + * + * @param string $file The file holding the aliases. + * + * @return array<string, string> + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function aliasTypes(string $file): array { + $source = (string) @file_get_contents($file); + $types = []; + // One alias per tag: from `@psalm-type Name =` up to the next tag or the end of the docblock. + preg_match_all('/@psalm-type\s+(\w+)\s*=\s*(.+?)(?=\n\s*\*\s*@|\n\s*\*\/)/s', $source, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { + $types[$match[1]] = trim((string) preg_replace('/\n\s*\*\s?/', ' ', $match[2])); + } + + return $types; + }//end aliasTypes() + + /** + * The document for a route table, with the overlay applied. + * + * @param array<string, mixed> $routes The route table, as appinfo/routes.php returns it. + * @param array<string, mixed> $overlay The hand-written parts. + * @param array<string, array<string, mixed>> $definitions The component schemas from `@psalm-type`. + * + * @return array<string, mixed> + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + public function generate(array $routes, array $overlay, array $definitions=[]): array { + $controllers = []; + $paths = []; + $tags = []; + $overrides = (array) ($overlay['operations'] ?? []); + $usedIds = []; + + foreach (($routes['routes'] ?? []) as $route) { + $key = OpenApiRouteCoverage::routeKey(route: (array) $route); + if ($key === null) { + continue; + } + + [$controller, $method] = explode('#', (string) $route['name'], 2); + $read = ($controllers[$controller] ??= $this->readController(name: $controller)); + $info = ($read['methods'][$method] ?? null); + if ($info === null) { + throw new \RuntimeException(sprintf('route %s names %s, which has no public method', $key, (string) $route['name'])); + } + + $tag = self::kebab(name: $controller); + $tags[$tag] = ($read['summary'] ?? ''); + $verb = strtolower((string) ($route['verb'] ?? 'GET')); + $path = substr('/'.ltrim((string) $route['url'], '/'), strlen(OpenApiRouteCoverage::VERSIONED_PREFIX)); + $operation = $this->operation(verb: $verb, path: $path, tag: $tag, method: $method, info: $info); + $operation['operationId'] = self::uniqueId(id: $operation['operationId'], used: $usedIds); + if (isset($overrides[$key]) === true) { + $operation = self::merge(base: $operation, override: (array) $overrides[$key]); + } + + $paths[$path][$verb] = self::withAccessSentence(operation: $operation); + } + + return $this->document(paths: $paths, tags: $tags, overlay: $overlay, definitions: $definitions); + }//end generate() + + /** + * The document encoded the way it is committed. + * + * @param array<string, mixed> $document The document. + * + * @return string + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function encode(array $document): string { + return json_encode($document, (JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))."\n"; + }//end encode() + + /** + * A camelCase name in kebab-case: `dashboardApi` becomes `dashboard-api`. + * + * @param string $name The name. + * + * @return string + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function kebab(string $name): string { + return strtolower((string) preg_replace('/(?<=[a-z0-9])([A-Z])/', '-$1', $name)); + }//end kebab() + + /** + * An override merged into an operation: objects merge key by key, anything else is replaced. + * + * A `$ref`, and an override that is itself a `$ref` or an `allOf`, `anyOf` + * or `oneOf`, is replaced whole: half of one schema merged into another + * describes neither. + * + * @param array<string, mixed> $base The generated operation. + * @param array<string, mixed> $override The overlay's entry. + * + * @return array<string, mixed> + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public static function merge(array $base, array $override): array { + foreach ($override as $key => $value) { + $mergeable = (is_array($value) === true && array_is_list($value) === false + && isset($base[$key]) === true && is_array($base[$key]) === true && array_is_list($base[$key]) === false + && isset($base[$key]['$ref']) === false && array_intersect_key($value, self::WHOLE_SCHEMAS) === []); + if ($mergeable === true) { + $base[$key] = self::merge(base: $base[$key], override: $value); + continue; + } + + $base[$key] = $value; + } + + return $base; + }//end merge() + + /** + * An operation with the sentence on who may call it closing its description, and its responses in code order. + * + * The sentence follows the route's attributes, so an overlay that rewords + * the description cannot leave a stale statement about access behind. + * + * @param array<string, mixed> $operation The operation, still carrying its access level. + * + * @return array<string, mixed> + */ + private static function withAccessSentence(array $operation): array { + $access = (string) $operation[self::ACCESS_KEY]; + unset($operation[self::ACCESS_KEY]); + $operation['description'] = trim((string) $operation['description'].' '.self::ACCESS_SENTENCE[$access]); + $responses = (array) $operation['responses']; + ksort($responses, SORT_NATURAL); + $operation['responses'] = $responses; + return $operation; + }//end withAccessSentence() + + /** + * An operation id not used before, suffixed with a number when it was. + * + * @param string $id The id. + * @param array<string, true> $used The ids used so far; the returned one is added. + * + * @return string + */ + private static function uniqueId(string $id, array &$used): string { + $unique = $id; + $suffix = 2; + while (isset($used[$unique]) === true) { + $unique = $id.'-'.$suffix; + $suffix++; + } + + $used[$unique] = true; + return $unique; + }//end uniqueId() + + /** + * Read the controller a route name points at. + * + * @param string $name The controller part of the route name (`dashboardApi`). + * + * @return array<string, mixed> + */ + private function readController(string $name): array { + $file = $this->controllerDir.'/'.ucfirst($name).'Controller.php'; + $read = $this->reader->read(file: $file); + if ($read === null) { + throw new \RuntimeException(sprintf('no controller class in %s', $file)); + } + + return $read; + }//end readController() + + /** + * One operation. + * + * @param string $verb The lower-case verb. + * @param string $path The path below the versioned prefix. + * @param string $tag The tag (the controller in kebab-case). + * @param string $method The controller method. + * @param array<string, mixed> $info What the reader found on the method. + * + * @return array<string, mixed> + */ + private function operation(string $verb, string $path, string $tag, string $method, array $info): array { + $access = $this->access(attributes: (array) $info['attributes']); + $text = (string) $info['text']; + $summary = $this->reader->firstSentence(text: $text); + $stability = (string) ($info['stability'] ?? 'internal'); + if (in_array($stability, OpenApiRouteCoverage::STABILITY, true) === false) { + $stability = 'internal'; + } + + if ($summary === '') { + $summary = $method; + } + + $operation = [ + 'operationId' => $tag.'-'.self::kebab(name: $method), + 'x-launchpad-stability' => $stability, + 'summary' => $summary, + 'description' => str_replace("\n\n", ' ', $text), + 'tags' => [$tag], + self::ACCESS_KEY => $access, + ]; + if ($access === 'public') { + $operation['security'] = []; + } + + [$parameters, $body] = $this->parameters(verb: $verb, path: $path, params: (array) $info['params']); + if ($parameters !== []) { + $operation['parameters'] = $parameters; + } + + if ($body !== null) { + $operation['requestBody'] = $body; + } + + $operation['responses'] = $this->responses(access: $access, codes: (array) $info['codes'], shapes: (array) $info['responses']); + return $operation; + }//end operation() + + /** + * Who may call a method: public, user, delegated or admin. + * + * @param list<string> $attributes The method's attributes. + * + * @return string + */ + private function access(array $attributes): string { + foreach (self::ATTRIBUTES as $access => $attribute) { + if (in_array($attribute, $attributes, true) === true) { + return $access; + } + } + + return 'admin'; + }//end access() + + /** + * The parameters (path and query) and the request body of an operation. + * + * @param string $verb The lower-case verb. + * @param string $path The path. + * @param list<array<string, mixed>> $params The method's parameters. + * + * @return array{0: list<array<string, mixed>>, 1: array<string, mixed>|null} + */ + private function parameters(string $verb, string $path, array $params): array { + preg_match_all('/\{(\w+)\}/', $path, $matches); + $inPath = $matches[1]; + $byName = array_column($params, null, 'name'); + $parameters = []; + foreach ($inPath as $name) { + $param = ($byName[$name] ?? ['name' => $name, 'native' => 'string', 'docType' => null, 'description' => '']); + $parameters[] = $this->parameter(param: $param, in: 'path', required: true); + } + + $properties = []; + $required = []; + foreach ($params as $param) { + if (in_array($param['name'], $inPath, true) === true) { + continue; + } + + if (in_array($verb, self::BODY_VERBS, true) === false) { + $parameters[] = $this->parameter(param: $param, in: 'query', required: ($param['optional'] === false)); + continue; + } + + $properties[$param['name']] = (object) $this->describe(schema: $this->paramSchema(param: $param), description: (string) $param['description']); + if ($param['optional'] === false) { + $required[] = $param['name']; + } + } + + if ($properties === []) { + return [$parameters, null]; + } + + $schema = ['type' => 'object', 'properties' => $properties]; + if ($required !== []) { + $schema['required'] = $required; + } + + $body = [ + 'required' => ($required !== []), + 'content' => ['application/json' => ['schema' => $schema]], + ]; + return [$parameters, $body]; + }//end parameters() + + /** + * One path or query parameter. + * + * @param array<string, mixed> $param The method parameter. + * @param string $in `path` or `query`. + * @param bool $required Whether it must be given. + * + * @return array<string, mixed> + */ + private function parameter(array $param, string $in, bool $required): array { + $schema = $this->paramSchema(param: $param); + $type = ($schema['type'] ?? null); + $plain = (is_string($type) === true && in_array($type, ['string', 'integer', 'number', 'boolean'], true) === true); + if ($in === 'path' || $plain === false) { + $schema = $this->scalarOf(schema: $schema); + } + + $parameter = ['name' => (string) $param['name'], 'in' => $in, 'required' => $required]; + if ((string) ($param['description'] ?? '') !== '') { + $parameter['description'] = (string) $param['description']; + } + + if (($schema['type'] ?? null) === 'string' && preg_match('/(^uuid|Uuid)$/', (string) $param['name']) === 1) { + $schema['format'] = 'uuid'; + } + + $parameter['schema'] = (object) $schema; + return $parameter; + }//end parameter() + + /** + * The scalar a path or query value is sent as: the first non-null scalar of the schema, else a string. + * + * @param array<string, mixed> $schema The parameter's schema. + * + * @return array<string, mixed> + */ + private function scalarOf(array $schema): array { + $types = (array) ($schema['type'] ?? []); + foreach ($types as $type) { + if (in_array($type, ['string', 'integer', 'number', 'boolean'], true) === true) { + return ['type' => $type]; + } + } + + return ['type' => 'string']; + }//end scalarOf() + + /** + * The schema of a method parameter: its `@param` type, else its native type. + * + * @param array<string, mixed> $param The parameter. + * + * @return array<string, mixed> + */ + private function paramSchema(array $param): array { + foreach ([($param['docType'] ?? null), ($param['native'] ?? null)] as $type) { + if (is_string($type) === false || $type === '') { + continue; + } + + $schema = $this->types->schemaOf(type: $type); + if ($schema !== []) { + return $schema; + } + } + + return []; + }//end paramSchema() + + /** + * A schema with a description added, when there is one. + * + * @param array<string, mixed> $schema The schema. + * @param string $description The description. + * + * @return array<string, mixed> + */ + private function describe(array $schema, string $description): array { + if ($description !== '') { + $schema['description'] = $description; + } + + return $schema; + }//end describe() + + /** + * The responses of an operation. + * + * Declared `@psalm-return` shapes win. Otherwise the 2xx codes the method + * reaches are its successes (200 when it names none) and every 4xx or 5xx + * code it reaches is a problem response. A route behind a login also + * answers 401, an admin route also 403. + * + * @param string $access The access level. + * @param list<int> $codes The codes the method reaches. + * @param array<int, array<string, mixed>> $shapes The declared response bodies. + * + * @return array<string, mixed> + */ + private function responses(string $access, array $codes, array $shapes): array { + $all = $codes; + if ($shapes !== []) { + // Declared shapes say which successes there are; a 2xx the body + // scan found in a shared helper is another route's. + $all = array_values(array_filter($codes, static fn (int $code): bool => $code >= 300)); + } + + $all = array_merge($all, array_keys($shapes)); + if ($access !== 'public') { + $all[] = 401; + } + + if ($access === 'admin' || $access === 'delegated') { + $all[] = 403; + } + + $success = array_filter($all, static fn (int $code): bool => $code >= 200 && $code < 300); + if ($success === [] && $shapes === []) { + $all[] = 200; + } + + $all = array_values(array_unique(array_filter($all, static fn (int $code): bool => $code >= 200 && $code < 600))); + sort($all); + + $responses = []; + foreach ($all as $code) { + if ($code >= 400) { + $responses[(string) $code] = $this->problem(code: $code, schema: ($shapes[$code] ?? null)); + continue; + } + + if ($code >= 300) { + continue; + } + + $responses[(string) $code] = $this->success(code: $code, schema: ($shapes[$code] ?? [])); + } + + return $responses; + }//end responses() + + /** + * A problem response: the shared one, or the problem document extended with a declared body. + * + * @param int $code The status code. + * @param array<string, mixed>|null $schema The declared body, or null. + * + * @return array<string, mixed> + */ + private function problem(int $code, ?array $schema): array { + if ($schema === null || $schema === []) { + return ['$ref' => '#/components/responses/Problem'.$code]; + } + + return [ + 'description' => (self::REASONS[$code] ?? 'Error').'.', + 'content' => [ + 'application/problem+json' => [ + 'schema' => ['allOf' => [['$ref' => '#/components/schemas/Problem'], $schema]], + ], + ], + ]; + }//end problem() + + /** + * A success response. + * + * @param int $code The status code. + * @param array<string, mixed> $schema The body schema; `{}` when not declared. + * + * @return array<string, mixed> + */ + private function success(int $code, array $schema): array { + $response = [ + 'description' => (self::SUCCESS_DESCRIPTION[$code] ?? 'The request succeeded.'), + 'headers' => ['API-Version' => ['$ref' => '#/components/headers/API-Version']], + ]; + if ($code !== 204) { + $response['content'] = ['application/json' => ['schema' => (object) $schema]]; + } + + return $response; + }//end success() + + /** + * The whole document: the overlay's frame, the tags, the paths and the components. + * + * @param array<string, array<string, mixed>> $paths The operations by path and verb. + * @param array<string, string> $tags The tag descriptions. + * @param array<string, mixed> $overlay The hand-written parts. + * @param array<string, array<string, mixed>> $definitions The `@psalm-type` schemas. + * + * @return array<string, mixed> + */ + private function document(array $paths, array $tags, array $overlay, array $definitions): array { + ksort($paths); + foreach ($paths as $path => $item) { + uksort( + $item, + static fn (string $left, string $right): int => (array_search($left, self::VERB_ORDER, true) <=> array_search($right, self::VERB_ORDER, true)) + ); + $paths[$path] = $item; + } + + ksort($tags); + $tagList = []; + foreach ($tags as $name => $description) { + $tag = ['name' => $name]; + if ($description !== '') { + $tag['description'] = $description.'.'; + } + + $tagList[] = $tag; + } + + $components = (array) ($overlay['components'] ?? []); + $components['schemas'] = array_merge((array) ($components['schemas'] ?? []), $definitions); + $components['responses'] = $this->problemResponses(paths: $paths, existing: (array) ($components['responses'] ?? [])); + + $document = [ + 'openapi' => self::OPENAPI_VERSION, + 'info' => ($overlay['info'] ?? ['title' => 'LaunchPad', 'version' => '1']), + ]; + foreach (['servers', 'security'] as $key) { + if (isset($overlay[$key]) === true) { + $document[$key] = $overlay[$key]; + } + } + + $document['tags'] = $tagList; + $document['paths'] = $paths; + $document['components'] = $components; + return $document; + }//end document() + + /** + * The problem responses the operations refer to: the overlay's, plus a plain one for each other code used. + * + * @param array<string, array<string, mixed>> $paths The operations. + * @param array<string, mixed> $existing The overlay's responses. + * + * @return array<string, mixed> + */ + private function problemResponses(array $paths, array $existing): array { + $responses = $existing; + foreach ($paths as $item) { + foreach ($item as $operation) { + foreach (array_keys((array) ($operation['responses'] ?? [])) as $code) { + $name = 'Problem'.$code; + if ((int) $code < 400 || isset($responses[$name]) === true) { + continue; + } + + $responses[$name] = [ + 'description' => (self::REASONS[(int) $code] ?? 'Error').'.', + 'content' => ['application/problem+json' => ['schema' => ['$ref' => '#/components/schemas/Problem']]], + ]; + } + } + } + + ksort($responses, SORT_NATURAL); + return $responses; + }//end problemResponses() +}//end class diff --git a/scripts/OpenApiRouteCoverage.php b/scripts/OpenApiRouteCoverage.php new file mode 100644 index 000000000..b23deb465 --- /dev/null +++ b/scripts/OpenApiRouteCoverage.php @@ -0,0 +1,161 @@ +<?php +/** + * OpenApiRouteCoverage + * + * The route half of the `composer lint:openapi` drift check + * (governance-rest-api-reference D3): every versioned API route in + * `appinfo/routes.php` has an operation in `openapi.json`, every operation + * carries `x-launchpad-stability` (public or internal), and no operation is + * documented for a route that does not exist. + * + * Path parameters are compared by position, not by name, so `{id}` in a route + * and `{uuid}` in the document are the same segment. The catch-all API + * fallback route is not an operation and is left out. + * + * @category Tooling + * @package OCA\LaunchPad\Scripts + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Scripts; + +use OCA\LaunchPad\Middleware\Support\ApiPathAliases; + +/** + * Compares the route table with the OpenAPI document. + * + * @spec openspec/specs/rest-api-reference/spec.md + */ +final class OpenApiRouteCoverage { + + /** + * The prefix of every versioned API route; the document's server URL ends in it. + * + * @var string + */ + public const VERSIONED_PREFIX = '/api/v1'; + + /** + * The stability levels an operation may carry. + * + * @var list<string> + */ + public const STABILITY = ['public', 'internal']; + + /** + * The problems found, one line each; empty when the document covers the routes. + * + * @param array<string, mixed> $routes The route table, as appinfo/routes.php returns it. + * @param array<string, mixed> $document The decoded openapi.json. + * + * @return list<string> + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + public static function problems(array $routes, array $document): array { + $operations = self::operations(document: $document); + $routed = []; + $problems = []; + + foreach (($routes['routes'] ?? []) as $route) { + $key = self::routeKey(route: (array) $route); + if ($key === null) { + continue; + } + + $routed[$key] = true; + if (array_key_exists($key, $operations) === false) { + $problems[] = sprintf('undocumented route: %s (%s)', $key, (string) ($route['name'] ?? '?')); + } + } + + foreach ($operations as $key => $stability) { + if (in_array($stability, self::STABILITY, true) === false) { + $problems[] = sprintf('no x-launchpad-stability (public or internal): %s', $key); + } + + if (isset($routed[$key]) === false) { + $problems[] = sprintf('documented operation without a route: %s', $key); + } + } + + return $problems; + }//end problems() + + /** + * Every operation of the document by "VERB /path", with its stability. + * + * @param array<string, mixed> $document The decoded openapi.json. + * + * @return array<string, mixed> + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + public static function operations(array $document): array { + $operations = []; + foreach ((array) ($document['paths'] ?? []) as $path => $item) { + foreach ((array) $item as $verb => $operation) { + if (is_array($operation) === false || isset($operation['responses']) === false) { + continue; + } + + $operations[strtoupper((string) $verb).' '.self::normalise(path: (string) $path)] = ($operation['x-launchpad-stability'] ?? null); + } + } + + return $operations; + }//end operations() + + /** + * The "VERB /path" a route is documented under, or null when it is not an API operation. + * + * @param array<string, mixed> $route One route entry. + * + * @return string|null + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + public static function routeKey(array $route): ?string { + $url = '/'.ltrim((string) ($route['url'] ?? ''), '/'); + if (str_starts_with($url, self::VERSIONED_PREFIX.'/') === false) { + return null; + } + + $relative = substr($url, strlen(self::VERSIONED_PREFIX)); + $fallback = ['url' => '/api'.$relative, 'requirements' => ($route['requirements'] ?? [])]; + if (ApiPathAliases::isApiFallback(route: $fallback) === true) { + return null; + } + + return strtoupper((string) ($route['verb'] ?? 'GET')).' '.self::normalise(path: $relative); + }//end routeKey() + + /** + * A path with every parameter written as `{}` and no trailing slash. + * + * @param string $path The path. + * + * @return string + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + public static function normalise(string $path): string { + $trimmed = rtrim($path, '/'); + if ($trimmed === '') { + $trimmed = '/'; + } + + return (string) preg_replace('#\{[^}]+\}#', '{}', $trimmed); + }//end normalise() +}//end class diff --git a/scripts/OpenApiTypeMapper.php b/scripts/OpenApiTypeMapper.php new file mode 100644 index 000000000..2329ec2cb --- /dev/null +++ b/scripts/OpenApiTypeMapper.php @@ -0,0 +1,364 @@ +<?php +/** + * OpenApiTypeMapper + * + * Turns a PHPDoc type (`int`, `?string`, `list<array{id: int}>`, a + * `@psalm-type` alias, ...) into an OpenAPI 3.1 schema, for the generator + * behind `composer openapi:generate` (governance-rest-api-reference D1). + * + * @category Tooling + * @package OCA\LaunchPad\Scripts + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + +declare(strict_types=1); + +namespace OCA\LaunchPad\Scripts; + +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; +use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; +use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use PHPStan\PhpDocParser\Lexer\Lexer; +use PHPStan\PhpDocParser\Parser\ConstExprParser; +use PHPStan\PhpDocParser\Parser\TokenIterator; +use PHPStan\PhpDocParser\Parser\TypeParser; +use PHPStan\PhpDocParser\ParserConfig; + +/** + * Maps PHPDoc types to OpenAPI 3.1 schemas. + * + * A name in `$aliases` becomes a `$ref` to `#/components/schemas/<name>`. + * A class name, `mixed` and anything not understood become `{}` (any value), + * so an unknown type documents less, never something wrong. + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ +final class OpenApiTypeMapper { + + /** + * The scalar PHPDoc names and their JSON Schema type. + * + * @var array<string, string> + */ + private const SCALARS = [ + 'int' => 'integer', + 'integer' => 'integer', + 'positive-int' => 'integer', + 'non-negative-int' => 'integer', + 'float' => 'number', + 'double' => 'number', + 'string' => 'string', + 'non-empty-string' => 'string', + 'numeric-string' => 'string', + 'class-string' => 'string', + 'bool' => 'boolean', + 'boolean' => 'boolean', + 'true' => 'boolean', + 'false' => 'boolean', + 'null' => 'null', + 'void' => 'null', + 'object' => 'object', + 'stdClass' => 'object', + '\stdClass' => 'object', + 'array' => 'array', + 'list' => 'array', + 'non-empty-array' => 'array', + 'non-empty-list' => 'array', + 'iterable' => 'array', + ]; + + /** + * The parser of PHPDoc types. + * + * @var TypeParser + */ + private TypeParser $parser; + + /** + * The PHPDoc lexer. + * + * @var Lexer + */ + private Lexer $lexer; + + /** + * Build a mapper. + * + * @param array<string, true> $aliases The `@psalm-type` names that are component schemas. + * @param array<string, int> $statusCodes The `Http::STATUS_*` constant names and their codes. + */ + public function __construct( + private readonly array $aliases=[], + private readonly array $statusCodes=[], + ) { + $config = new ParserConfig(usedAttributes: []); + $this->lexer = new Lexer(config: $config); + $this->parser = new TypeParser(config: $config, constExprParser: new ConstExprParser(config: $config)); + }//end __construct() + + /** + * Parse a PHPDoc type string, or null when it does not parse. + * + * @param string $type The type as written. + * + * @return TypeNode|null + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public function parse(string $type): ?TypeNode { + try { + $tokens = new TokenIterator(tokens: $this->lexer->tokenize(s: $type)); + return $this->parser->parse(tokens: $tokens); + } catch (\Throwable) { + return null; + } + }//end parse() + + /** + * The schema of a type string; `{}` when it does not parse. + * + * @param string $type The type as written. + * + * @return array<string, mixed> + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public function schemaOf(string $type): array { + $node = $this->parse(type: $type); + if ($node === null) { + return []; + } + + return $this->schema(node: $node); + }//end schemaOf() + + /** + * The schema of a parsed type. + * + * @param TypeNode $node The type. + * + * @return array<string, mixed> + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public function schema(TypeNode $node): array { + return match (true) { + $node instanceof NullableTypeNode => $this->union(members: [$node->type, new IdentifierTypeNode(name: 'null')]), + $node instanceof UnionTypeNode => $this->union(members: $node->types), + $node instanceof ArrayShapeNode => $this->shape(node: $node), + $node instanceof ArrayTypeNode => ['type' => 'array', 'items' => (object) $this->schema(node: $node->type)], + $node instanceof GenericTypeNode => $this->generic(node: $node), + $node instanceof ConstTypeNode => $this->constant(node: $node), + $node instanceof IdentifierTypeNode => $this->identifier(name: $node->name), + default => [], + }; + }//end schema() + + /** + * The HTTP status a type stands for (`Http::STATUS_OK`, `200`), or null. + * + * @param TypeNode $node The first argument of a `JSONResponse<...>`. + * + * @return int|null + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + public function statusOf(TypeNode $node): ?int { + if ($node instanceof ConstTypeNode === false) { + return null; + } + + $expr = $node->constExpr; + if ($expr instanceof ConstExprIntegerNode) { + return (int) $expr->value; + } + + if ($expr instanceof ConstFetchNode) { + return ($this->statusCodes[$expr->name] ?? null); + } + + return null; + }//end statusOf() + + /** + * A union: a nullable type list when every member is a plain type, else `anyOf`. + * + * @param array<TypeNode> $members The members. + * + * @return array<string, mixed> + */ + private function union(array $members): array { + $schemas = array_map(fn (TypeNode $member): array => $this->schema(node: $member), $members); + $types = []; + foreach ($schemas as $schema) { + if ($schema === []) { + return []; + } + + if (array_keys($schema) !== ['type'] || is_string($schema['type']) === false) { + return $this->anyOf(schemas: $schemas); + } + + $types[] = $schema['type']; + } + + $types = array_values(array_unique($types)); + if (count($types) === 1) { + return ['type' => $types[0]]; + } + + return ['type' => $types]; + }//end union() + + /** + * An `anyOf`, with `null` folded into a single `{type: null}` member. + * + * @param list<array<string, mixed>> $schemas The member schemas. + * + * @return array<string, mixed> + */ + private function anyOf(array $schemas): array { + $unique = []; + foreach ($schemas as $schema) { + $unique[json_encode($schema)] = $schema; + } + + return ['anyOf' => array_values($unique)]; + }//end anyOf() + + /** + * An array shape: an object with its keys, or a tuple when no key is named. + * + * @param ArrayShapeNode $node The shape. + * + * @return array<string, mixed> + */ + private function shape(ArrayShapeNode $node): array { + $properties = []; + $required = []; + foreach ($node->items as $item) { + if ($item->keyName === null) { + return ['type' => 'array']; + } + + $key = (string) $item->keyName; + if ($item->keyName instanceof ConstExprStringNode) { + $key = $item->keyName->value; + } + + $properties[$key] = (object) $this->schema(node: $item->valueType); + if ($item->optional === false) { + $required[] = $key; + } + } + + $schema = ['type' => 'object']; + if ($properties !== []) { + $schema['properties'] = $properties; + } + + if ($required !== []) { + $schema['required'] = $required; + } + + $schema['additionalProperties'] = ($node->sealed === false); + return $schema; + }//end shape() + + /** + * A generic: `list<T>` and `array<int, T>` are arrays, `array<string, T>` is a map. + * + * @param GenericTypeNode $node The generic. + * + * @return array<string, mixed> + */ + private function generic(GenericTypeNode $node): array { + $base = ltrim($node->type->name, '\\'); + if (in_array($base, ['array', 'list', 'non-empty-array', 'non-empty-list', 'iterable'], true) === false) { + return $this->identifier(name: $node->type->name); + } + + $args = $node->genericTypes; + $value = end($args); + $items = (object) $this->schema(node: $value); + if (count($args) === 2 && $this->isStringKey(node: $args[0]) === true) { + return ['type' => 'object', 'additionalProperties' => $items]; + } + + return ['type' => 'array', 'items' => $items]; + }//end generic() + + /** + * Whether a key type is `string` (a map) rather than `int` (a list). + * + * @param TypeNode $node The key type. + * + * @return bool + */ + private function isStringKey(TypeNode $node): bool { + return $node instanceof IdentifierTypeNode && in_array($node->name, ['string', 'non-empty-string', 'array-key'], true); + }//end isStringKey() + + /** + * A constant type: a literal becomes a `const`. + * + * @param ConstTypeNode $node The constant. + * + * @return array<string, mixed> + */ + private function constant(ConstTypeNode $node): array { + $expr = $node->constExpr; + return match (true) { + $expr instanceof ConstExprStringNode => ['type' => 'string', 'const' => $expr->value], + $expr instanceof ConstExprIntegerNode => ['type' => 'integer', 'const' => (int) $expr->value], + $expr instanceof ConstExprFloatNode => ['type' => 'number', 'const' => (float) $expr->value], + $expr instanceof ConstExprTrueNode => ['type' => 'boolean', 'const' => true], + $expr instanceof ConstExprFalseNode => ['type' => 'boolean', 'const' => false], + default => [], + }; + }//end constant() + + /** + * A named type: a scalar, a component alias, or `{}`. + * + * @param string $name The name as written. + * + * @return array<string, mixed> + */ + private function identifier(string $name): array { + if (isset($this->aliases[$name]) === true) { + return ['$ref' => '#/components/schemas/'.$name]; + } + + $type = (self::SCALARS[$name] ?? self::SCALARS[strtolower($name)] ?? null); + if ($type === null) { + return []; + } + + if ($name === 'true' || $name === 'false') { + return ['type' => 'boolean']; + } + + return ['type' => $type]; + }//end identifier() +}//end class diff --git a/scripts/coverage-guard.php b/scripts/coverage-guard.php index 1b27e667b..81bc1da56 100755 --- a/scripts/coverage-guard.php +++ b/scripts/coverage-guard.php @@ -67,90 +67,128 @@ const CG_WHOLE_FILE = '<whole file>'; /** - * Sum clover metrics for a named subset of files. - * - * WHY THIS EXISTS. Comparing the project-wide aggregate made the ratchet fire on - * measurement noise. Measured on doriath#240 — a pull request whose entire diff - * was `webpack.config.js`, containing no PHP at all: - * - * Coverage current: 60.50% (8303/13723 statements) - * Coverage merge base: 60.55% (8309/13723 statements) - * FAIL: coverage dropped by 0.05% against the merge base. - * - * The denominator is identical, so both runs compiled the same source, and both - * reported exactly `Tests: 948, Assertions: 3051, Skipped: 1`. Only which six - * statements xdebug recorded as covered moved. The header above argues that a - * measured `--against` floor cancels driver variance, and it does — but it does - * not cancel RUN-TO-RUN variance, and the ratchet has no tolerance. + * One clover report and the label its messages use ("current", "merge-base"). * - * A tolerance band was the obvious alternative and is the wrong one: it blinds - * the gate to small real regressions permanently, at a threshold nobody can - * justify. Scoping to the files the change actually touched keeps full strength - * where it matters and makes the noise unreachable — a diff with no PHP cannot - * fail, by construction, rather than by being forgiven. - * - * Matching is by path SUFFIX. Clover records absolute paths from the machine - * that produced it, and the two reports here are produced from two different - * checkouts, so absolute equality would match nothing and silently measure zero. - * - * @param string $file Clover report to read. - * @param string $label Human label for error messages. - * @param array<int,string> $only Repo-relative paths to include. + * @spec exclude CI tooling shared by every app; it implements no app requirement. + */ +final class CgClover +{ + + + /** + * @param string $file Path of the clover report. + * @param string $label Label for messages about this report. + */ + public function __construct( + public readonly string $file, + public readonly string $label + ) { + }//end __construct() + + +}//end class + +/** + * The head and merge-base reports of a scoped comparison. * - * @return array{0:int,1:int,2:float} statements, covered, percentage + * @spec exclude CI tooling shared by every app; it implements no app requirement. */ -function cgMeasureFiles(string $file, string $label, array $only): array +final class CgSides { - if (file_exists($file) === false) { - fwrite(STDERR, "Error: {$label} clover file not found: {$file}\n"); - exit(CG_INPUT); - } - $xml = @simplexml_load_file($file); - if ($xml === false) { - fwrite(STDERR, "Error: could not parse {$label} report {$file}\n"); - exit(CG_INPUT); - } - $statements = 0; - $covered = 0; - $matched = 0; + /** + * @param CgClover $head The head clover report. + * @param CgClover $base The merge-base clover report. + */ + public function __construct( + public readonly CgClover $head, + public readonly CgClover $base + ) { + }//end __construct() - foreach ($xml->xpath('//file') as $entry) { - $name = (string) $entry['name']; - if ($name === '') { - continue; - } - foreach ($only as $wanted) { - if (str_ends_with($name, $wanted) === false) { - continue; - } +}//end class + +/** + * The options of one run, read once from the command line. + * + * An option given without a value (`--against`) or with an empty one + * (`--against=`) reads as absent. + * + * @spec exclude CI tooling shared by every app; it implements no app requirement. + */ +final class CgRun +{ - $matched++; - $statements += (int) $entry->metrics['statements']; - $covered += (int) $entry->metrics['coveredstatements']; - break; + /** + * The head clover report. + * + * @var CgClover + */ + public readonly CgClover $head; + + /** + * The merge-base clover report, null without `--against`. + * + * @var CgClover|null + */ + public readonly ?CgClover $base; + + /** + * The changed-file list, null without `--changed-files`. + * + * @var string|null + */ + public readonly ?string $changedList; + + /** + * Whether `--deletion-neutral` was given. + * + * @var boolean + */ + public readonly bool $deletionNeutral; + + /** + * Whether `--update-baseline` was given. + * + * @var boolean + */ + public readonly bool $updateBaseline; + + /** + * Path of the committed `.coverage-baseline`. + * + * @var string + */ + public readonly string $baselineFile; + + + /** + * @param array<string,string|bool> $options Parsed `--key=value` options. + * @param string $clover Head clover report path. + */ + public function __construct(array $options, string $clover) + { + $against = cgOptionString($options, 'against'); + $this->head = new CgClover($clover, 'current'); + $base = null; + if ($against !== null) { + $base = new CgClover($against, 'merge-base'); } - } - // Zero matches is NOT zero coverage. It means the changed files are absent - // from this report — typically because they are new on the head side and do - // not exist at the merge base, which is normal and must not read as a drop. - if ($matched === 0) { - return [0, 0, 0.0]; - } + $this->base = $base; + $this->changedList = cgOptionString($options, 'changed-files'); + $this->deletionNeutral = isset($options['deletion-neutral']); + $this->updateBaseline = isset($options['update-baseline']); + $this->baselineFile = (__DIR__ . '/../.coverage-baseline'); + }//end __construct() - $percentage = 0.0; - if ($statements > 0) { - $percentage = round((($covered / $statements) * 100), 2); - } - return [$statements, $covered, $percentage]; -} +}//end class /** - * Attribute every statement in the named files to the METHOD it sits in. + * Method buckets of one clover report, filled file entry by file entry. * * WHY BY METHOD NAME, AND WHY NOT BY LINE NUMBER. * @@ -203,111 +241,359 @@ function cgMeasureFiles(string $file, string $label, array $only): array * same-named pair is still charged against the change. Not seen in any of the * 2 608 entries surveyed; handled so it cannot become a silent hole. * - * @param string $file Clover report to read. - * @param string $label Human label for error messages. - * @param array<int,string> $only Repo-relative paths to include. + * @spec exclude CI tooling shared by every app; it implements no app requirement. + */ +final class CgAttribution +{ + + /** + * Buckets keyed "<path>::<method>". + * + * @var array<string,array{0:int,1:int}> + */ + public array $buckets = []; + + /** + * Repo-relative paths this report matched. + * + * @var array<int,string> + */ + public array $matched = []; + + /** + * Paths that had to fall back to file-level metrics. + * + * @var array<int,string> + */ + public array $fellBack = []; + + + /** + * @param string $label Label for messages about this report. + */ + public function __construct(private readonly string $label) + { + }//end __construct() + + + /** + * Add one matched clover `<file>` entry to the buckets. + * + * @param SimpleXMLElement $entry Clover `<file>` entry. + * @param string $path Repo-relative path the entry matched. + * + * @return void + * + * @spec exclude CI tooling shared by every app; it implements no app requirement. + */ + public function addEntry(SimpleXMLElement $entry, string $path): void + { + $this->matched[] = $path; + + foreach ($this->entryBuckets(entry: $entry, path: $path) as $key => $pair) { + $this->buckets[$key] = cgAddPair(($this->buckets[$key] ?? [0, 0]), $pair); + } + }//end addEntry() + + + /** + * Drop repeated paths, keeping the first occurrence of each. + * + * @spec exclude CI tooling shared by every app; it implements no app requirement. + * + * @return void + */ + public function dedupe(): void + { + $this->matched = array_values(array_unique($this->matched)); + $this->fellBack = array_values(array_unique($this->fellBack)); + }//end dedupe() + + + /** + * The buckets of one entry, reconciled against its declared statement count. + * + * @param SimpleXMLElement $entry Clover `<file>` entry. + * @param string $path Repo-relative path the entry matched. + * + * @return array<string,array{0:int,1:int}> + */ + private function entryBuckets(SimpleXMLElement $entry, string $path): array + { + $local = cgLineBuckets($entry, $path); + $statements = cgSumBuckets($local)[0]; + $declared = (int) $entry->metrics['statements']; + + if ($statements === 0 && $declared > 0) { + return $this->fallBack(entry: $entry, path: $path); + } + + if ($statements !== $declared) { + echo " note: {$this->label} report declares {$declared} statement(s) for {$path} but emits " + . "{$statements} attributable line(s); the attributable ones are what is compared.\n"; + } + + return $local; + }//end entryBuckets() + + + /** + * No usable line data. Measuring 0/0 here would drop the file out of the + * comparison entirely, so fall back to the file metric and say so. + * + * @param SimpleXMLElement $entry Clover `<file>` entry. + * @param string $path Repo-relative path the entry matched. + * + * @return array<string,array{0:int,1:int}> + */ + private function fallBack(SimpleXMLElement $entry, string $path): array + { + $this->fellBack[] = $path; + $declared = (int) $entry->metrics['statements']; + + echo " note: {$this->label} report carries no line data for {$path}; " + . "falling back to its file-level metric ({$entry->metrics['coveredstatements']}/{$declared}).\n"; + + return [($path . '::' . CG_WHOLE_FILE) => [$declared, (int) $entry->metrics['coveredstatements']]]; + }//end fallBack() + + +}//end class + +/** + * Print an input error and stop with CG_INPUT. + * + * @param string $message Error text, newline included. * - * @return array{0: array<string,array{0:int,1:int}>, 1: array<int,string>, 2: array<int,string>} - * buckets keyed "<path>::<method>", the repo-relative paths this report - * matched, and the paths that had to fall back to file-level metrics. + * @return never */ -function cgAttributeMethods(string $file, string $label, array $only): array +function cgFail(string $message): never { - if (file_exists($file) === false) { - fwrite(STDERR, "Error: {$label} clover file not found: {$file}\n"); - exit(CG_INPUT); + fwrite(STDERR, $message); + exit(CG_INPUT); +}//end cgFail() + +/** + * Stop with CG_INPUT when a clover report does not exist. + * + * @param CgClover $report Clover report to read. + * + * @return void + */ +function cgRequireFile(CgClover $report): void +{ + if (file_exists($report->file) === false) { + cgFail("Error: {$report->label} clover file not found: {$report->file}\n"); } +}//end cgRequireFile() - $xml = @simplexml_load_file($file); +/** + * Load a clover report, stopping with CG_INPUT when it is missing or unparseable. + * + * @param CgClover $report Clover report to read. + * + * @return SimpleXMLElement + */ +function cgOpenReport(CgClover $report): SimpleXMLElement +{ + cgRequireFile($report); + + $xml = @simplexml_load_file($report->file); if ($xml === false) { - fwrite(STDERR, "Error: could not parse {$label} report {$file}\n"); - exit(CG_INPUT); + cgFail("Error: could not parse {$report->label} report {$report->file}\n"); } - $buckets = []; - $matched = []; - $fellBack = []; + return $xml; +}//end cgOpenReport() - foreach ($xml->xpath('//file') as $entry) { - $name = (string) $entry['name']; - if ($name === '') { - continue; - } +/** + * The first wanted repo-relative path the clover file name ends with. + * + * Matching is by path SUFFIX. Clover records absolute paths from the machine + * that produced it, and the two reports here are produced from two different + * checkouts, so absolute equality would match nothing and silently measure zero. + * + * @param string $name Clover file name. + * @param array<int,string> $only Repo-relative paths to include. + * + * @return ?string + */ +function cgMatchPath(string $name, array $only): ?string +{ + if ($name === '') { + return null; + } - $path = null; - foreach ($only as $wanted) { - if (str_ends_with($name, $wanted) === true) { - $path = $wanted; - break; - } + foreach ($only as $wanted) { + if (str_ends_with($name, $wanted) === true) { + return $wanted; } + } - if ($path === null) { - continue; - } + return null; +}//end cgMatchPath() - $matched[] = $path; +/** + * Percentage of a [statements, covered] pair, 0.0 when there are no statements. + * + * @param array{0:int,1:int} $pair A [statements, covered] pair. + * + * @return float + */ +function cgPercent(array $pair): float +{ + if ($pair[0] > 0) { + return round((($pair[1] / $pair[0]) * 100), 2); + } - $method = CG_WHOLE_FILE; - $statements = 0; - $covered = 0; - $local = []; + return 0.0; +}//end cgPercent() - foreach ($entry->line as $line) { - $type = (string) $line['type']; +/** + * Sum two [statements, covered] pairs. + * + * @param array{0:int,1:int} $left First [statements, covered] pair. + * @param array{0:int,1:int} $right Second [statements, covered] pair. + * + * @return array{0:int,1:int} + */ +function cgAddPair(array $left, array $right): array +{ + return [($left[0] + $right[0]), ($left[1] + $right[1])]; +}//end cgAddPair() - if ($type === 'method') { - $named = (string) $line['name']; - $method = ($named === '' ? CG_WHOLE_FILE : $named); - continue; - } +/** + * Sum clover metrics for a named subset of files. + * + * WHY THIS EXISTS. Comparing the project-wide aggregate made the ratchet fire on + * measurement noise. Measured on doriath#240 — a pull request whose entire diff + * was `webpack.config.js`, containing no PHP at all: + * + * Coverage current: 60.50% (8303/13723 statements) + * Coverage merge base: 60.55% (8309/13723 statements) + * FAIL: coverage dropped by 0.05% against the merge base. + * + * The denominator is identical, so both runs compiled the same source, and both + * reported exactly `Tests: 948, Assertions: 3051, Skipped: 1`. Only which six + * statements xdebug recorded as covered moved. The header above argues that a + * measured `--against` floor cancels driver variance, and it does — but it does + * not cancel RUN-TO-RUN variance, and the ratchet has no tolerance. + * + * A tolerance band was the obvious alternative and is the wrong one: it blinds + * the gate to small real regressions permanently, at a threshold nobody can + * justify. Scoping to the files the change actually touched keeps full strength + * where it matters and makes the noise unreachable — a diff with no PHP cannot + * fail, by construction, rather than by being forgiven. + * + * Zero matches is NOT zero coverage. It means the changed files are absent from + * this report — typically because they are new on the head side and do not + * exist at the merge base, which is normal and must not read as a drop. It + * measures [0, 0, 0.0]. + * + * @param CgClover $report Clover report to read. + * @param array<int,string> $only Repo-relative paths to include. + * + * @return array{0:int,1:int,2:float} statements, covered, percentage + */ +function cgMeasureFiles(CgClover $report, array $only): array +{ + $pair = [0, 0]; - if ($type !== 'stmt') { - continue; - } + foreach (cgOpenReport($report)->xpath('//file') as $entry) { + if (cgMatchPath((string) $entry['name'], $only) !== null) { + $metrics = [(int) $entry->metrics['statements'], (int) $entry->metrics['coveredstatements']]; + $pair = cgAddPair($pair, $metrics); + } + } - $key = ($path . '::' . $method); - if (isset($local[$key]) === false) { - $local[$key] = [0, 0]; - } + return [$pair[0], $pair[1], cgPercent($pair)]; +}//end cgMeasureFiles() - $local[$key][0]++; - $statements++; +/** + * Attribute every statement in the named files to the METHOD it sits in. + * + * See CgAttribution for why by method name and how degenerate files are handled. + * + * @param CgClover $report Clover report to read. + * @param array<int,string> $only Repo-relative paths to include. + * + * @return CgAttribution + */ +function cgAttributeMethods(CgClover $report, array $only): CgAttribution +{ + $run = new CgAttribution($report->label); - if (((int) $line['count']) > 0) { - $local[$key][1]++; - $covered++; - } + foreach (cgOpenReport($report)->xpath('//file') as $entry) { + $path = cgMatchPath((string) $entry['name'], $only); + if ($path !== null) { + $run->addEntry($entry, $path); } + } - $declared = (int) $entry->metrics['statements']; + $run->dedupe(); - if ($statements === 0 && $declared > 0) { - // No usable line data. Measuring 0/0 here would drop the file out of - // the comparison entirely, so fall back to the file metric and say so. - $fellBack[] = $path; - $local = [ - ($path . '::' . CG_WHOLE_FILE) => [$declared, (int) $entry->metrics['coveredstatements']], - ]; - echo " note: {$label} report carries no line data for {$path}; " - . "falling back to its file-level metric ({$entry->metrics['coveredstatements']}/{$declared}).\n"; - } else if ($statements !== $declared) { - echo " note: {$label} report declares {$declared} statement(s) for {$path} but emits " - . "{$statements} attributable line(s); the attributable ones are what is compared.\n"; + return $run; +}//end cgAttributeMethods() + +/** + * Bucket the `stmt` lines of one clover `<file>` entry by the method that opens them. + * + * @param SimpleXMLElement $entry Clover `<file>` entry. + * @param string $path Repo-relative path the entry matched. + * + * @return array<string,array{0:int,1:int}> + */ +function cgLineBuckets(SimpleXMLElement $entry, string $path): array +{ + $method = CG_WHOLE_FILE; + $local = []; + + foreach ($entry->line as $line) { + $type = (string) $line['type']; + if ($type === 'method') { + $method = cgMethodName($line); + } else if ($type === 'stmt') { + $key = ($path . '::' . $method); + $local[$key] = cgCountLine(($local[$key] ?? [0, 0]), $line); } + } - foreach ($local as $key => $pair) { - if (isset($buckets[$key]) === false) { - $buckets[$key] = [0, 0]; - } + return $local; +}//end cgLineBuckets() - $buckets[$key][0] += $pair[0]; - $buckets[$key][1] += $pair[1]; - } - }//end foreach +/** + * The bucket name a `type="method"` line opens. + * + * @param SimpleXMLElement $line Clover `<line>` element. + * + * @return string + */ +function cgMethodName(SimpleXMLElement $line): string +{ + $named = (string) $line['name']; + if ($named === '') { + return CG_WHOLE_FILE; + } - return [$buckets, array_values(array_unique($matched)), array_values(array_unique($fellBack))]; -}//end cgAttributeMethods() + return $named; +}//end cgMethodName() + +/** + * Count one `stmt` line into a [statements, covered] pair. + * + * @param array{0:int,1:int} $pair A [statements, covered] pair. + * @param SimpleXMLElement $line Clover `<line>` element. + * + * @return array{0:int,1:int} + */ +function cgCountLine(array $pair, SimpleXMLElement $line): array +{ + if (((int) $line['count']) > 0) { + return [($pair[0] + 1), ($pair[1] + 1)]; + } + + return [($pair[0] + 1), $pair[1]]; +}//end cgCountLine() /** * Collapse every bucket belonging to the named files into one per file. @@ -327,8 +613,8 @@ function cgAttributeMethods(string $file, string $label, array $only): array * as the file-scoped mode compares it today, and the deletion penalty applies to * it. Conservative, and visible in the output. * - * @param array<string,array{0:int,1:int}> $buckets - * @param array<int,string> $paths + * @param array<string,array{0:int,1:int}> $buckets Buckets to read. + * @param array<int,string> $paths Files to collapse. * * @return array<string,array{0:int,1:int}> */ @@ -342,28 +628,40 @@ function cgCollapseFiles(array $buckets, array $paths): array $out = []; foreach ($buckets as $key => $pair) { - $split = strrpos($key, '::'); - $path = ($split === false ? $key : substr($key, 0, $split)); + $key = cgCollapsedKey($key, $collapse); + $out[$key] = cgAddPair(($out[$key] ?? [0, 0]), $pair); + } - if (isset($collapse[$path]) === true) { - $key = ($path . '::' . CG_WHOLE_FILE); - } + return $out; +}//end cgCollapseFiles() - if (isset($out[$key]) === false) { - $out[$key] = [0, 0]; - } +/** + * The bucket key after collapsing: the file's CG_WHOLE_FILE key for a collapsed file. + * + * @param string $key Bucket key "<path>::<method>". + * @param array<string,bool> $collapse Paths to collapse, as keys. + * + * @return string + */ +function cgCollapsedKey(string $key, array $collapse): string +{ + $split = strrpos($key, '::'); + $path = $key; + if ($split !== false) { + $path = substr($key, 0, $split); + } - $out[$key][0] += $pair[0]; - $out[$key][1] += $pair[1]; + if (isset($collapse[$path]) === true) { + return ($path . '::' . CG_WHOLE_FILE); } - return $out; -}//end cgCollapseFiles() + return $key; +}//end cgCollapsedKey() /** * Sum a bucket map, optionally restricted to a set of keys. * - * @param array<string,array{0:int,1:int}> $buckets + * @param array<string,array{0:int,1:int}> $buckets Buckets to read. * @param array<string,bool>|null $keep Keys to include, or null for all. * * @return array{0:int,1:int} statements, covered @@ -394,19 +692,8 @@ function cgSumBuckets(array $buckets, ?array $keep = null): array */ function cgReadChangedFiles(string $path): array { - if (file_exists($path) === false) { - fwrite(STDERR, "Error: changed-files list not found: {$path}\n"); - exit(CG_INPUT); - } - - $lines = file($path, (FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); - if ($lines === false) { - fwrite(STDERR, "Error: could not read changed-files list: {$path}\n"); - exit(CG_INPUT); - } - $php = []; - foreach ($lines as $line) { + foreach (cgReadLines($path) as $line) { $line = trim($line); if ($line !== '' && str_ends_with($line, '.php') === true) { $php[] = $line; @@ -414,12 +701,33 @@ function cgReadChangedFiles(string $path): array } return array_values(array_unique($php)); -} +}//end cgReadChangedFiles() + +/** + * The non-empty lines of the changed-file list, stopping with CG_INPUT when it cannot be read. + * + * @param string $path File containing one repo-relative path per line. + * + * @return array<int,string> + */ +function cgReadLines(string $path): array +{ + if (file_exists($path) === false) { + cgFail("Error: changed-files list not found: {$path}\n"); + } + + $lines = file($path, (FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); + if ($lines === false) { + cgFail("Error: could not read changed-files list: {$path}\n"); + } + + return $lines; +}//end cgReadLines() /** * Parse `--key=value` / `--flag` into a map, and everything else in order. * - * @param array<int,string> $argv + * @param array<int,string> $argv Command-line arguments, script name first. * * @return array{0: array<string,string|bool>, 1: array<int,string>} */ @@ -434,19 +742,47 @@ function cgParseArgs(array $argv): array continue; } - $body = substr($arg, 2); - $eq = strpos($body, '='); + [$key, $value] = cgParseOption(substr($arg, 2)); + $options[$key] = $value; + } - if ($eq === false) { - $options[$body] = true; - continue; - } + return [$options, $positional]; +}//end cgParseArgs() - $options[substr($body, 0, $eq)] = substr($body, ($eq + 1)); +/** + * Split one option body (`key=value` or `flag`) into its key and value. + * + * @param string $body Option text after the leading `--`. + * + * @return array{0:string,1:string|bool} + */ +function cgParseOption(string $body): array +{ + $eq = strpos($body, '='); + if ($eq === false) { + return [$body, true]; } - return [$options, $positional]; -} + return [substr($body, 0, $eq), substr($body, ($eq + 1))]; +}//end cgParseOption() + +/** + * An option's value when it is a non-empty string, otherwise null. + * + * @param array<string,string|bool> $options Parsed `--key=value` options. + * @param string $name Option key. + * + * @return ?string + */ +function cgOptionString(array $options, string $name): ?string +{ + $value = ($options[$name] ?? null); + if (is_string($value) === true && $value !== '') { + return $value; + } + + return null; +}//end cgOptionString() /** * Read a clover report and return its statement counts and percentage. @@ -456,51 +792,64 @@ function cgParseArgs(array $argv): array * satisfy the guard — and when the empty report is the merge-base side, it * would set the floor to 0 and pass every possible drop. * + * @param CgClover $report Clover report to read. + * * @return array{0: int, 1: int, 2: float} */ -function cgMeasure(string $file, string $label): array +function cgMeasure(CgClover $report): array { - if (file_exists($file) === false) { - fwrite(STDERR, "Error: {$label} clover file not found: {$file}\n"); - exit(CG_INPUT); - } + cgRequireFile($report); - $xml = @simplexml_load_file($file); + $xml = @simplexml_load_file($report->file); if ($xml === false || isset($xml->project->metrics) === false) { - fwrite(STDERR, "Error: could not parse coverage metrics from {$label} report {$file}\n"); - exit(CG_INPUT); + cgFail("Error: could not parse coverage metrics from {$report->label} report {$report->file}\n"); } - $metrics = $xml->project->metrics; - $statements = (int) $metrics['statements']; - $covered = (int) $metrics['coveredstatements']; + $metrics = $xml->project->metrics; + $pair = [(int) $metrics['statements'], (int) $metrics['coveredstatements']]; + cgRequireStatements($report, $pair[0]); + + return [$pair[0], $pair[1], cgPercent($pair)]; +}//end cgMeasure() +/** + * Stop with CG_INPUT when a whole-project report counts no statements. + * + * @param CgClover $report Clover report to read. + * @param int $statements Statements the report counts. + * + * @return void + */ +function cgRequireStatements(CgClover $report, int $statements): void +{ if ($statements <= 0) { - fwrite( - STDERR, - "Error: {$label} report {$file} counts zero statements. Refusing to turn an empty " + cgFail( + "Error: {$report->label} report {$report->file} counts zero statements. Refusing to turn an empty " . "report into a percentage — this is a measurement failure, not a coverage result.\n" ); - exit(CG_INPUT); } - - return [$statements, $covered, round((($covered / $statements) * 100), 2)]; -} +}//end cgRequireStatements() /** * Compare percentages as integer hundredths. * * Used only against the committed floor, which IS a two-decimal constant, so * two decimals is all the precision that comparison can carry. + * + * @param float $percentage Percentage to convert. + * + * @return int */ function cgHundredths(float $percentage): int { return (int) round(($percentage * 100)); -} +}//end cgHundredths() /** * Is the head ratio strictly below the merge-base ratio? * + * Both sides are [statements, covered, ...] measurements. + * * Compared as exact integer cross-products, NOT as rounded percentages, and * that distinction is load-bearing. Rounding to two decimals hides roughly one * statement: measured on openbuild, dropping 8229/13987 to 8228/13987 leaves @@ -514,11 +863,16 @@ function cgHundredths(float $percentage): int * swallowed. That is the intended direction: the counts are printed on failure, * so a flake is immediately legible as a flake, whereas a swallowed drop is * legible as nothing at all. + * + * @param array{0:int,1:int} $head Head measurement: statements, covered, percentage. + * @param array{0:int,1:int} $base Merge-base measurement: statements, covered, percentage. + * + * @return bool */ -function cgRatioDropped(int $covered, int $statements, int $baseCovered, int $baseStatements): bool +function cgRatioDropped(array $head, array $base): bool { - return (($covered * $baseStatements) < ($baseCovered * $statements)); -} + return (($head[1] * $base[0]) < ($base[1] * $head[0])); +}//end cgRatioDropped() /** * Print a percentage together with the counts it came from. @@ -527,311 +881,601 @@ function cgRatioDropped(int $covered, int $statements, int $baseCovered, int $ba * distinguish "tests were deleted" from "untested code was added", and the * second is the common way a ratchet is tripped by a change that added no * tests at all. + * + * @param string $label Text printed before the figures. + * @param array{0:int,1:int,2:float} $measure statements, covered, percentage + * + * @return void */ -function cgReport(string $label, int $statements, int $covered, float $percentage): void +function cgReport(string $label, array $measure): void { - printf("%-22s %6.2f%% (%d/%d statements)\n", $label, $percentage, $covered, $statements); -} + printf("%-22s %6.2f%% (%d/%d statements)\n", $label, $measure[2], $measure[1], $measure[0]); +}//end cgReport() -// ── main ──────────────────────────────────────────────────────────────────── +/** + * Say how many statements a change added, when it added any. + * + * @param int $added Head statements minus base statements. + * @param string $where Text after "statements", e.g. " to those files". + * + * @return void + */ +function cgPrintAdded(int $added, string $where): void +{ + if ($added > 0) { + echo " This change adds {$added} statements{$where}. Adding code without tests drops coverage.\n"; + } +}//end cgPrintAdded() -[$options, $positional] = cgParseArgs($argv); +/** + * The verdict when none of the changed files is in either report. + * + * @return int + */ +function cgNothingMeasured(): int +{ + echo "OK: none of the changed PHP files appear in either coverage report.\n"; + echo " Nothing was measured, so nothing is claimed about them.\n"; + return CG_OK; +}//end cgNothingMeasured() -if (isset($options['capabilities']) === true) { +/** + * Print the capabilities, one per line. + * + * @return int + */ +function cgPrintCapabilities(): int +{ echo implode("\n", CG_CAPABILITIES), "\n"; - exit(CG_OK); -} - -$cloverFile = ($positional[0] ?? 'coverage/clover.xml'); -$baselineFile = (__DIR__ . '/../.coverage-baseline'); -$against = ($options['against'] ?? null); -$changedList = ($options['changed-files'] ?? null); -$deletionFree = isset($options['deletion-neutral']); - -// A flag that is accepted and ignored is the silent-downgrade shape this script's -// `--capabilities` probe exists to prevent, so refuse rather than fall through to -// a comparison the caller did not ask for. -if ($deletionFree === true && (is_string($changedList) === false || $changedList === '')) { - fwrite(STDERR, "Error: --deletion-neutral requires --changed-files (and therefore --against). It refines the file-scoped comparison; it has no meaning against the whole project.\n"); - exit(CG_INPUT); -} + return CG_OK; +}//end cgPrintCapabilities() + +/** + * Run the guard and return its exit code. + * + * @param array<int,string> $argv Command-line arguments, script name first. + * + * @return int + */ +function cgMain(array $argv): int +{ + [$options, $positional] = cgParseArgs($argv); -// ── scoped mode: compare ONLY the PHP the change touched ──────────────────── -// -// Requires --against. Without a merge-base report there is nothing to compare a -// file subset to, and falling back to the committed whole-project constant here -// would compare a subset against a whole and fail everything. -if (is_string($changedList) === true && $changedList !== '') { - if (is_string($against) === false || $against === '') { - fwrite(STDERR, "Error: --changed-files requires --against; a file subset has no meaning against the committed whole-project baseline.\n"); - exit(CG_INPUT); + if (isset($options['capabilities']) === true) { + return cgPrintCapabilities(); } - $changed = cgReadChangedFiles($changedList); + $run = new CgRun($options, ($positional[0] ?? 'coverage/clover.xml')); + + cgRequireScopeForDeletionNeutral($run); + $changedList = $run->changedList; + if ($changedList !== null) { + return cgScoped($run, $changedList); + } + + return cgWholeProject($run); +}//end cgMain() + +/** + * Stop with CG_INPUT when `--deletion-neutral` comes without `--changed-files`. + * + * A flag that is accepted and ignored is the silent-downgrade shape this script's + * `--capabilities` probe exists to prevent, so refuse rather than fall through to + * a comparison the caller did not ask for. + * + * @param CgRun $run Options of this run. + * + * @return void + */ +function cgRequireScopeForDeletionNeutral(CgRun $run): void +{ + if ($run->deletionNeutral === true && $run->changedList === null) { + cgFail( + 'Error: --deletion-neutral requires --changed-files (and therefore --against). ' + . "It refines the file-scoped comparison; it has no meaning against the whole project.\n" + ); + } +}//end cgRequireScopeForDeletionNeutral() + +/** + * Scoped mode: compare ONLY the PHP the change touched. + * + * Requires --against. Without a merge-base report there is nothing to compare a + * file subset to, and falling back to the committed whole-project constant here + * would compare a subset against a whole and fail everything. + * + * @param CgRun $run Options of this run. + * @param string $changedList File containing one repo-relative path per line. + * + * @return int + */ +function cgScoped(CgRun $run, string $changedList): int +{ + $base = $run->base; + if ($base === null) { + cgFail("Error: --changed-files requires --against; a file subset has no meaning against the committed whole-project baseline.\n"); + } + + $changed = cgReadChangedFiles($changedList); if (empty($changed) === true) { - echo "OK: this change touches no PHP files, so there is no coverage to compare.\n"; - echo " (Whole-project drift between two runs of identical code is measurement noise, not a regression.)\n"; - exit(CG_OK); + return cgNoPhpChanged(); } echo 'Scoped to ' . count($changed) . " changed PHP file(s).\n"; - // ── deletion-neutral mode ─────────────────────────────────────────────── - // - // WHAT THIS FIXES. `cgRatioDropped()` is a single integer cross-product with - // no tolerance, so the file-scoped ratchet demands, exactly: - // - // the code you touched must be at least as well covered as the code you - // did not. - // - // For ADDITIONS that is right, and it earns its keep: openconnector#1265 - // covered 27 of 54 new statements against a 61.86% floor, needed 34, and - // writing the missing seven is what exposed a cascade that deleted nothing - // and reported success. - // - // For DELETIONS it INVERTS. Removing `d` statements of which `c` were covered - // lowers the ratio whenever c/d exceeds the ratio of what remains — i.e. - // whenever the deleted code was better tested than average. And dead code is - // dead because nothing CALLS it, not because nothing TESTED it: gate-57 - // (orphaned-write-capability) exists to find precisely that code, so gate-57 - // and this ratchet are in arithmetic opposition, not tension. Such a pull - // request cannot satisfy the ratchet from inside its own subject at all — - // the only moves are delete less, add filler, or delete additional - // *uncovered* statements until it balances. The gate can be satisfied by - // deleting more code and cannot be satisfied by testing anything. - // - // Measured, both blocked by the file-scoped rule: - // opencatalogi#895 head 112/115 (97.39%) base 148/151 (98.01%) -0.62% - // launchpad#128 head 183/254 (72.05%) base 220/304 (72.37%) -0.32% - // - // THE RULE, AND IT IS ASYMMETRIC ON PURPOSE: - // - // drop BASE-ONLY methods (deletions) from the base side; - // KEEP HEAD-ONLY methods (additions) on the head side. - // - // The symmetric version — "compare over statements present in both reports" — - // is the obvious one and it is broken. It also drops head-only statements, so - // a change adding 40 new statements with 0 of them covered compares an empty - // set to an empty set and PASSES. That is the openconnector#1265 shape, and - // the symmetric rule would have retired the half of this ratchet that works. - // A mutant reintroducing it is in the test suite and must stay there. - // - // Consequences, all four measured in quality-config/tests/test-coverage-guard.py: - // pure deletion (opencatalogi) PASS 112/115 vs 112/115 — exactly neutral - // pure deletion (launchpad) PASS 183/254 vs 183/254 - // regression in survivors FAIL 180/254 vs 183/254 - // new untested code FAIL 183/294 (62.24%) vs 183/254 (72.05%) - // - // KNOWN RESIDUAL, stated rather than discovered: a RENAME reads as a delete - // plus an add. The old name leaves the base side, the new name arrives on the - // head side and must be covered. That is the right incentive — a renamed - // method is new code as far as the test suite is concerned — but it means a - // pure rename of a well-covered method is not free, and an author who did not - // expect it will read the failure as noise. It is documented here and in the - // failure message so it is legible when it happens. - if ($deletionFree === true) { - [$headBuckets, $headFiles, $headFellBack] = cgAttributeMethods($cloverFile, 'current', $changed); - [$baseBuckets, $baseFiles, $baseFellBack] = cgAttributeMethods($against, 'merge-base', $changed); - - // Either side falling back forces BOTH sides to file level for that file — - // see cgCollapseFiles() for why anything else is an invisible pass. - $collapse = array_values(array_unique(array_merge($headFellBack, $baseFellBack))); - if (empty($collapse) === false) { - echo 'Falling back to file-level metrics on both sides for: ' . implode(', ', $collapse) . "\n"; - $headBuckets = cgCollapseFiles($headBuckets, $collapse); - $baseBuckets = cgCollapseFiles($baseBuckets, $collapse); - } + $sides = new CgSides($run->head, $base); + return ($run->deletionNeutral === true ? cgDeletionNeutral($sides, $changed) : cgFileScoped($sides, $changed)); +}//end cgScoped() - echo 'Deletion-neutral: attributed by method name (head ' . count($headFiles) . ' file(s), ' - . 'base ' . count($baseFiles) . ' file(s), ' . count($headBuckets) . ' head method(s), ' - . count($baseBuckets) . " base method(s)).\n"; - - // A changed file the base measured and the head did not is normally a - // DELETED file, and treating it as deleted is the point of this mode. But - // it is also what an accidental coverage exclusion looks like, and the two - // are indistinguishable from here — so it is said out loud rather than - // absorbed silently. - $goneFiles = array_values(array_diff($baseFiles, $headFiles)); - if (empty($goneFiles) === false) { - echo 'Measured at the merge base and absent from the head report: ' - . implode(', ', $goneFiles) . "\n"; - echo " Treated as deleted. If one of those files still exists, it has been dropped from\n"; - echo " coverage measurement and that is the thing to fix, not this guard.\n"; - } +/** + * The verdict when the change touches no PHP. + * + * @return int + */ +function cgNoPhpChanged(): int +{ + echo "OK: this change touches no PHP files, so there is no coverage to compare.\n"; + echo " (Whole-project drift between two runs of identical code is measurement noise, not a regression.)\n"; + return CG_OK; +}//end cgNoPhpChanged() - if (empty($headBuckets) === true && empty($baseBuckets) === true) { - echo "OK: none of the changed PHP files appear in either coverage report.\n"; - echo " Nothing was measured, so nothing is claimed about them.\n"; - exit(CG_OK); - } +/** + * File-scoped mode: the changed files' totals, head against merge base. + * + * @param CgSides $sides Head and merge-base reports. + * @param array<int,string> $changed Changed PHP files, repo-relative. + * + * @return int + */ +function cgFileScoped(CgSides $sides, array $changed): int +{ + $head = cgMeasureFiles($sides->head, $changed); + $base = cgMeasureFiles($sides->base, $changed); - $keep = []; - foreach ($headBuckets as $key => $unused) { - $keep[$key] = true; - } + if ($head[0] === 0 && $base[0] === 0) { + return cgNothingMeasured(); + } - $dropped = []; - foreach ($baseBuckets as $key => $pair) { - if (isset($keep[$key]) === false) { - $dropped[$key] = $pair; - } - } + cgReport('Changed files, head:', $head); + cgReport('Changed files, base:', $base); - [$statements, $covered] = cgSumBuckets($headBuckets); - [$baseStatements, $baseCovered] = cgSumBuckets($baseBuckets, $keep); + if ($base[0] === 0) { + echo "OK: the changed PHP is new at the merge base, so there is no prior figure to drop below.\n"; + return CG_OK; + } - $current = ($statements > 0 ? round((($covered / $statements) * 100), 2) : 0.0); - $base = ($baseStatements > 0 ? round((($baseCovered / $baseStatements) * 100), 2) : 0.0); + return (cgRatioDropped($head, $base) === true ? cgFileScopedDropped($head, $base) : cgFileScopedKept()); +}//end cgFileScoped() - if (empty($dropped) === false) { - [$droppedStatements, $droppedCovered] = cgSumBuckets($dropped); - echo 'Removed from the base side: ' . count($dropped) - . " method(s) absent from head, {$droppedCovered}/{$droppedStatements} statements.\n"; - echo " A method that no longer exists is not a coverage regression; it is deleted code.\n"; - } +/** + * The verdict when the changed files lost coverage. + * + * @param array{0:int,1:int,2:float} $head Head measurement: statements, covered, percentage. + * @param array{0:int,1:int,2:float} $base Merge-base measurement: statements, covered, percentage. + * + * @return int + */ +function cgFileScopedDropped(array $head, array $base): int +{ + $delta = round(($base[2] - $head[2]), 2); + echo "FAIL: coverage of the files this change touches dropped by {$delta}%.\n"; + echo " base {$base[1]}/{$base[0]} -> head {$head[1]}/{$head[0]} statements.\n"; + cgPrintAdded(($head[0] - $base[0]), ' to those files'); - cgReport('Surviving code, head:', $statements, $covered, $current); - cgReport('Surviving code, base:', $baseStatements, $baseCovered, $base); + return CG_DROPPED; +}//end cgFileScopedDropped() - if ($baseStatements === 0) { - echo "OK: none of the changed PHP existed at the merge base, so there is no prior figure to drop below.\n"; - exit(CG_OK); - } +/** + * The verdict when the changed files kept their coverage. + * + * @return int + */ +function cgFileScopedKept(): int +{ + echo "OK: coverage of the changed files did not drop.\n"; + return CG_OK; +}//end cgFileScopedKept() - if (cgRatioDropped($covered, $statements, $baseCovered, $baseStatements) === true) { - $delta = round(($base - $current), 2); - echo($delta > 0 - ? "FAIL: coverage of the code this change KEEPS or ADDS dropped by {$delta}%.\n" - : "FAIL: coverage of the code this change KEEPS or ADDS dropped by less than 0.01% — too " - . "little to show in the percentage, but a real loss in the counts below.\n"); - echo " base {$baseCovered}/{$baseStatements} -> head {$covered}/{$statements} statements, " - . "comparing only methods that exist on BOTH sides plus everything new on this branch.\n"; - - if ($statements > $baseStatements) { - $added = ($statements - $baseStatements); - echo " This change adds {$added} statements to those files. Adding code without tests drops coverage.\n"; - } - - echo " Deleted methods were already excluded, so this is not a deletion penalty. If you\n"; - echo " RENAMED a method, note that a rename reads as a delete plus an add: the new name is\n"; - echo " new code here and has to be covered.\n"; - - exit(CG_DROPPED); - } +/** + * Deletion-neutral mode. + * + * WHAT THIS FIXES. `cgRatioDropped()` is a single integer cross-product with + * no tolerance, so the file-scoped ratchet demands, exactly: + * + * the code you touched must be at least as well covered as the code you + * did not. + * + * For ADDITIONS that is right, and it earns its keep: openconnector#1265 + * covered 27 of 54 new statements against a 61.86% floor, needed 34, and + * writing the missing seven is what exposed a cascade that deleted nothing + * and reported success. + * + * For DELETIONS it INVERTS. Removing `d` statements of which `c` were covered + * lowers the ratio whenever c/d exceeds the ratio of what remains — i.e. + * whenever the deleted code was better tested than average. And dead code is + * dead because nothing CALLS it, not because nothing TESTED it: gate-57 + * (orphaned-write-capability) exists to find precisely that code, so gate-57 + * and this ratchet are in arithmetic opposition, not tension. Such a pull + * request cannot satisfy the ratchet from inside its own subject at all — + * the only moves are delete less, add filler, or delete additional + * *uncovered* statements until it balances. The gate can be satisfied by + * deleting more code and cannot be satisfied by testing anything. + * + * Measured, both blocked by the file-scoped rule: + * opencatalogi#895 head 112/115 (97.39%) base 148/151 (98.01%) -0.62% + * launchpad#128 head 183/254 (72.05%) base 220/304 (72.37%) -0.32% + * + * THE RULE, AND IT IS ASYMMETRIC ON PURPOSE: + * + * drop BASE-ONLY methods (deletions) from the base side; + * KEEP HEAD-ONLY methods (additions) on the head side. + * + * The symmetric version — "compare over statements present in both reports" — + * is the obvious one and it is broken. It also drops head-only statements, so + * a change adding 40 new statements with 0 of them covered compares an empty + * set to an empty set and PASSES. That is the openconnector#1265 shape, and + * the symmetric rule would have retired the half of this ratchet that works. + * A mutant reintroducing it is in the test suite and must stay there. + * + * Consequences, all four measured in quality-config/tests/test-coverage-guard.py: + * pure deletion (opencatalogi) PASS 112/115 vs 112/115 — exactly neutral + * pure deletion (launchpad) PASS 183/254 vs 183/254 + * regression in survivors FAIL 180/254 vs 183/254 + * new untested code FAIL 183/294 (62.24%) vs 183/254 (72.05%) + * + * KNOWN RESIDUAL, stated rather than discovered: a RENAME reads as a delete + * plus an add. The old name leaves the base side, the new name arrives on the + * head side and must be covered. That is the right incentive — a renamed + * method is new code as far as the test suite is concerned — but it means a + * pure rename of a well-covered method is not free, and an author who did not + * expect it will read the failure as noise. It is documented here and in the + * failure message so it is legible when it happens. + * + * @param CgSides $sides Head and merge-base reports. + * @param array<int,string> $changed Changed PHP files, repo-relative. + * + * @return int + */ +function cgDeletionNeutral(CgSides $sides, array $changed): int +{ + $head = cgAttributeMethods($sides->head, $changed); + $base = cgAttributeMethods($sides->base, $changed); - echo "OK: coverage of the surviving and added code did not drop.\n"; - exit(CG_OK); - }//end if + cgCollapseFallbacks($head, $base); + cgPrintAttribution($head, $base); - [$statements, $covered, $current] = cgMeasureFiles($cloverFile, 'current', $changed); - [$baseStatements, $baseCovered, $base] = cgMeasureFiles($against, 'merge-base', $changed); + if (empty($head->buckets) === true && empty($base->buckets) === true) { + return cgNothingMeasured(); + } - if ($statements === 0 && $baseStatements === 0) { - echo "OK: none of the changed PHP files appear in either coverage report.\n"; - echo " Nothing was measured, so nothing is claimed about them.\n"; - exit(CG_OK); + return cgCompareSurvivors($head->buckets, $base->buckets); +}//end cgDeletionNeutral() + +/** + * Either side falling back forces BOTH sides to file level for that file — + * see cgCollapseFiles() for why anything else is an invisible pass. + * + * @param CgAttribution $head Head attribution. + * @param CgAttribution $base Merge-base attribution. + * + * @return void + */ +function cgCollapseFallbacks(CgAttribution $head, CgAttribution $base): void +{ + $collapse = array_values(array_unique(array_merge($head->fellBack, $base->fellBack))); + if (empty($collapse) === true) { + return; } - cgReport('Changed files, head:', $statements, $covered, $current); - cgReport('Changed files, base:', $baseStatements, $baseCovered, $base); + echo 'Falling back to file-level metrics on both sides for: ' . implode(', ', $collapse) . "\n"; + $head->buckets = cgCollapseFiles($head->buckets, $collapse); + $base->buckets = cgCollapseFiles($base->buckets, $collapse); +}//end cgCollapseFallbacks() - if ($baseStatements === 0) { - echo "OK: the changed PHP is new at the merge base, so there is no prior figure to drop below.\n"; - exit(CG_OK); +/** + * Print what was attributed on each side and which files the head no longer measures. + * + * @param CgAttribution $head Head attribution. + * @param CgAttribution $base Merge-base attribution. + * + * @return void + */ +function cgPrintAttribution(CgAttribution $head, CgAttribution $base): void +{ + echo 'Deletion-neutral: attributed by method name (head ' . count($head->matched) . ' file(s), ' + . 'base ' . count($base->matched) . ' file(s), ' . count($head->buckets) . ' head method(s), ' + . count($base->buckets) . " base method(s)).\n"; + + cgPrintGoneFiles(array_values(array_diff($base->matched, $head->matched))); +}//end cgPrintAttribution() + +/** + * A changed file the base measured and the head did not is normally a DELETED + * file, and treating it as deleted is the point of this mode. But it is also + * what an accidental coverage exclusion looks like, and the two are + * indistinguishable from here — so it is said out loud rather than absorbed + * silently. + * + * @param array<int,string> $goneFiles Files the base measured and the head did not. + * + * @return void + */ +function cgPrintGoneFiles(array $goneFiles): void +{ + if (empty($goneFiles) === true) { + return; } - if (cgRatioDropped($covered, $statements, $baseCovered, $baseStatements) === true) { - $delta = round(($base - $current), 2); - echo "FAIL: coverage of the files this change touches dropped by {$delta}%.\n"; - echo " base {$baseCovered}/{$baseStatements} -> head {$covered}/{$statements} statements.\n"; - if ($statements > $baseStatements) { - $added = ($statements - $baseStatements); - echo " This change adds {$added} statements to those files. Adding code without tests drops coverage.\n"; - } + echo 'Measured at the merge base and absent from the head report: ' . implode(', ', $goneFiles) . "\n"; + echo " Treated as deleted. If one of those files still exists, it has been dropped from\n"; + echo " coverage measurement and that is the thing to fix, not this guard.\n"; +}//end cgPrintGoneFiles() + +/** + * Compare every head bucket with the base buckets that still exist on the head side. + * + * @param array<string,array{0:int,1:int}> $headBuckets Head buckets. + * @param array<string,array{0:int,1:int}> $baseBuckets Merge-base buckets. + * + * @return int + */ +function cgCompareSurvivors(array $headBuckets, array $baseBuckets): int +{ + $keep = array_fill_keys(array_keys($headBuckets), true); + cgPrintDropped(array_diff_key($baseBuckets, $keep)); + + $head = cgSumBuckets($headBuckets); + $base = cgSumBuckets($baseBuckets, $keep); + $head[] = cgPercent($head); + $base[] = cgPercent($base); + + cgReport('Surviving code, head:', $head); + cgReport('Surviving code, base:', $base); + + return cgJudgeSurvivors($head, $base); +}//end cgCompareSurvivors() + +/** + * @param array<string,array{0:int,1:int}> $dropped Base buckets absent from head. + * + * @return void + */ +function cgPrintDropped(array $dropped): void +{ + if (empty($dropped) === true) { + return; + } + + [$droppedStatements, $droppedCovered] = cgSumBuckets($dropped); + echo 'Removed from the base side: ' . count($dropped) + . " method(s) absent from head, {$droppedCovered}/{$droppedStatements} statements.\n"; + echo " A method that no longer exists is not a coverage regression; it is deleted code.\n"; +}//end cgPrintDropped() + +/** + * @param array{0:int,1:int,2:float} $head Head measurement: statements, covered, percentage. + * @param array{0:int,1:int,2:float} $base Merge-base measurement: statements, covered, percentage. + * + * @return int + */ +function cgJudgeSurvivors(array $head, array $base): int +{ + if ($base[0] === 0) { + echo "OK: none of the changed PHP existed at the merge base, so there is no prior figure to drop below.\n"; + return CG_OK; + } - exit(CG_DROPPED); + if (cgRatioDropped($head, $base) === true) { + return cgSurvivorsDropped($head, $base); } - echo "OK: coverage of the changed files did not drop.\n"; - exit(CG_OK); -}//end if + echo "OK: coverage of the surviving and added code did not drop.\n"; + return CG_OK; +}//end cgJudgeSurvivors() + +/** + * @param array{0:int,1:int,2:float} $head Head measurement: statements, covered, percentage. + * @param array{0:int,1:int,2:float} $base Merge-base measurement: statements, covered, percentage. + * + * @return int + */ +function cgSurvivorsDropped(array $head, array $base): int +{ + $delta = round(($base[2] - $head[2]), 2); + echo($delta > 0 + ? "FAIL: coverage of the code this change KEEPS or ADDS dropped by {$delta}%.\n" + : "FAIL: coverage of the code this change KEEPS or ADDS dropped by less than 0.01% — too " + . "little to show in the percentage, but a real loss in the counts below.\n"); + echo " base {$base[1]}/{$base[0]} -> head {$head[1]}/{$head[0]} statements, " + . "comparing only methods that exist on BOTH sides plus everything new on this branch.\n"; + cgPrintAdded(($head[0] - $base[0]), ' to those files'); + echo " Deleted methods were already excluded, so this is not a deletion penalty. If you\n"; + echo " RENAMED a method, note that a rename reads as a delete plus an add: the new name is\n"; + echo " new code here and has to be covered.\n"; + + return CG_DROPPED; +}//end cgSurvivorsDropped() + +/** + * Whole-project mode: the merge base as the floor when measured, else the committed floor. + * + * @param CgRun $run Options of this run. + * + * @return int + */ +function cgWholeProject(CgRun $run): int +{ + $head = cgMeasure($run->head); + cgReport('Coverage current:', $head); + + $against = $run->base; + if ($against === null) { + return cgCommittedFloor($run, $head); + } + + $base = cgMeasure($against); + cgReport('Coverage merge base:', $base); + cgPrintCommitted($run->baselineFile); + + return cgAgainstBase($head, $base); +}//end cgWholeProject() + +/** + * The ratchet: a MEASURED floor. + * + * @param array{0:int,1:int,2:float} $head Head measurement: statements, covered, percentage. + * @param array{0:int,1:int,2:float} $base Merge-base measurement: statements, covered, percentage. + * + * @return int + */ +function cgAgainstBase(array $head, array $base): int +{ + if (cgRatioDropped($head, $base) === true) { + return cgAgainstDropped($head, $base); + } + + if (cgRatioDropped($base, $head) === true) { + return cgAgainstImproved($head, $base); + } + + echo "OK: coverage unchanged against the merge base.\n"; + return CG_OK; +}//end cgAgainstBase() -[$statements, $covered, $current] = cgMeasure($cloverFile, 'current'); -cgReport('Coverage current:', $statements, $covered, $current); +/** + * @param array{0:int,1:int,2:float} $head Head measurement: statements, covered, percentage. + * @param array{0:int,1:int,2:float} $base Merge-base measurement: statements, covered, percentage. + * + * @return int + */ +function cgAgainstImproved(array $head, array $base): int +{ + $gain = round(($head[2] - $base[2]), 2); + echo "OK: coverage improved by {$gain}% against the merge base " + . "({$base[1]}/{$base[0]} -> {$head[1]}/{$head[0]}).\n"; -// ── the ratchet: a MEASURED floor ─────────────────────────────────────────── -if (is_string($against) === true && $against !== '') { - [$baseStatements, $baseCovered, $base] = cgMeasure($against, 'merge-base'); - cgReport('Coverage merge base:', $baseStatements, $baseCovered, $base); + return CG_OK; +}//end cgAgainstImproved() +/** + * Show the committed floor, which a measured merge base replaces. + * + * @param string $baselineFile Path of the committed `.coverage-baseline`. + * + * @return void + */ +function cgPrintCommitted(string $baselineFile): void +{ if (file_exists($baselineFile) === true) { $committed = trim(file_get_contents($baselineFile)); echo "Committed .coverage-baseline: {$committed}% — recorded only, NOT enforced on this run.\n"; echo "The merge base is measured, so it is the floor; see the header of this script.\n"; } +}//end cgPrintCommitted() - if (cgRatioDropped($covered, $statements, $baseCovered, $baseStatements) === true) { - $delta = round(($base - $current), 2); - echo($delta > 0 ? "FAIL: coverage dropped by {$delta}% against the merge base.\n" - : "FAIL: coverage dropped against the merge base by less than 0.01% — too little to show in " - . "the percentage, but a real loss in the counts below.\n"); - echo " merge base {$baseCovered}/{$baseStatements} -> head {$covered}/{$statements} statements.\n"; - if ($statements > $baseStatements) { - $added = ($statements - $baseStatements); - echo " This change adds {$added} statements. Adding code without tests drops coverage.\n"; - } +/** + * @param array{0:int,1:int,2:float} $head Head measurement: statements, covered, percentage. + * @param array{0:int,1:int,2:float} $base Merge-base measurement: statements, covered, percentage. + * + * @return int + */ +function cgAgainstDropped(array $head, array $base): int +{ + $delta = round(($base[2] - $head[2]), 2); + echo($delta > 0 ? "FAIL: coverage dropped by {$delta}% against the merge base.\n" + : "FAIL: coverage dropped against the merge base by less than 0.01% — too little to show in " + . "the percentage, but a real loss in the counts below.\n"); + echo " merge base {$base[1]}/{$base[0]} -> head {$head[1]}/{$head[0]} statements.\n"; + cgPrintAdded(($head[0] - $base[0]), ''); + + return CG_DROPPED; +}//end cgAgainstDropped() + +/** + * Fail-safe: the committed floor. + * + * @param CgRun $run Options of this run. + * @param array{0:int,1:int,2:float} $head Head measurement: statements, covered, percentage. + * + * @return int + */ +function cgCommittedFloor(CgRun $run, array $head): int +{ + $baseline = cgReadBaseline($run->baselineFile); - exit(CG_DROPPED); + $order = (cgHundredths($head[2]) <=> cgHundredths($baseline)); + if ($order < 0) { + return cgBelowFloor($head[2], $baseline); } - if (cgRatioDropped($baseCovered, $baseStatements, $covered, $statements) === true) { - $gain = round(($current - $base), 2); - echo "OK: coverage improved by {$gain}% against the merge base " - . "({$baseCovered}/{$baseStatements} -> {$covered}/{$statements}).\n"; - exit(CG_OK); + if ($order > 0) { + echo 'OK: coverage is ' . round(($head[2] - $baseline), 2) . "% above the committed floor.\n"; + cgUpdateBaseline($run, $head[2]); + return CG_OK; } - echo "OK: coverage unchanged against the merge base.\n"; - exit(CG_OK); -} + echo "OK: coverage unchanged.\n"; + return CG_OK; +}//end cgCommittedFloor() -// ── fail-safe: the committed floor ────────────────────────────────────────── -if (file_exists($baselineFile) === false) { - fwrite(STDERR, "Error: baseline file not found: {$baselineFile}\n"); - exit(CG_INPUT); -} +/** + * The verdict when coverage is below the committed floor. + * + * @param float $current Measured head percentage. + * @param float $baseline Committed floor percentage. + * + * @return int + */ +function cgBelowFloor(float $current, float $baseline): int +{ + echo 'FAIL: coverage dropped by ' . round(($baseline - $current), 2) . "% below the committed floor.\n"; + return CG_DROPPED; +}//end cgBelowFloor() -$raw = trim(file_get_contents($baselineFile)); -if (preg_match('/^[0-9]+(\.[0-9]+)?$/', $raw) !== 1) { - fwrite(STDERR, "Error: unparseable coverage baseline value '{$raw}' — refusing to guess.\n"); - exit(CG_INPUT); -} - -$baseline = (float) $raw; -printf("%-22s %6.2f%% (committed fail-safe floor)\n", 'Coverage baseline:', $baseline); - -if (cgHundredths($current) < cgHundredths($baseline)) { - $delta = round(($baseline - $current), 2); - echo "FAIL: coverage dropped by {$delta}% below the committed floor.\n"; - exit(CG_DROPPED); -} - -if (cgHundredths($current) > cgHundredths($baseline)) { - $gain = round(($current - $baseline), 2); - echo "OK: coverage is {$gain}% above the committed floor.\n"; - - // Kept for callers that want the recomputed value written out. Being ABOVE - // the committed floor is explicitly not a failure: the floor is conservative - // by design and drifts low as coverage rises. The live ratchet is the - // merge-base comparison above, which cannot go stale at all. - if (isset($options['update-baseline']) === true) { - file_put_contents($baselineFile, (number_format($current, 2) . "\n")); +/** + * Read and print the committed floor, stopping with CG_INPUT when it is missing or not a number. + * + * @param string $baselineFile Path of the committed `.coverage-baseline`. + * + * @return float + */ +function cgReadBaseline(string $baselineFile): float +{ + if (file_exists($baselineFile) === false) { + cgFail("Error: baseline file not found: {$baselineFile}\n"); + } + + $raw = trim(file_get_contents($baselineFile)); + if (preg_match('/^[0-9]+(\.[0-9]+)?$/', $raw) !== 1) { + cgFail("Error: unparseable coverage baseline value '{$raw}' — refusing to guess.\n"); + } + + $baseline = (float) $raw; + printf("%-22s %6.2f%% (committed fail-safe floor)\n", 'Coverage baseline:', $baseline); + + return $baseline; +}//end cgReadBaseline() + +/** + * Kept for callers that want the recomputed value written out. Being ABOVE + * the committed floor is explicitly not a failure: the floor is conservative + * by design and drifts low as coverage rises. The live ratchet is the + * merge-base comparison, which cannot go stale at all. + * + * @param CgRun $run Options of this run. + * @param float $current Measured head percentage. + * + * @return void + */ +function cgUpdateBaseline(CgRun $run, float $current): void +{ + if ($run->updateBaseline === true) { + file_put_contents($run->baselineFile, (number_format($current, 2) . "\n")); echo "Recomputed floor written: {$current}%\n"; } +}//end cgUpdateBaseline() - exit(CG_OK); -} +// ── main ──────────────────────────────────────────────────────────────────── -echo "OK: coverage unchanged.\n"; -exit(CG_OK); +exit(cgMain($argv)); diff --git a/scripts/coverage-publish.php b/scripts/coverage-publish.php new file mode 100644 index 000000000..844563f5f --- /dev/null +++ b/scripts/coverage-publish.php @@ -0,0 +1,139 @@ +#!/usr/bin/env php +<?php +/** + * Publishes the measured test coverage of this app. + * + * Reads the reports the test suites write and turns them into two things: + * - coverage-summary.json at the repository root, in the Istanbul + * json-summary shape ("total.lines.pct"), with the PHP and JavaScript + * suites listed separately; + * - the block between the coverage markers in README.md. + * + * It measures nothing itself. Run it through `composer coverage:publish`, + * which first runs PHPUnit and Vitest with coverage enabled. + * + * Usage: + * php scripts/coverage-publish.php [--clover=coverage/clover.xml] + * [--vitest=coverage-vitest/coverage-summary.json] [--readme=README.md] + * [--out=coverage-summary.json] + * + * Exit codes: 0 published, 2 missing or unreadable input. + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +$root = dirname(__DIR__); +$opts = getopt('', ['clover::', 'vitest::', 'readme::', 'out::']); +$clover = $root . '/' . ($opts['clover'] ?? 'coverage/clover.xml'); +$vitest = $root . '/' . ($opts['vitest'] ?? 'coverage-vitest/coverage-summary.json'); +$readme = $root . '/' . ($opts['readme'] ?? 'README.md'); +$out = $root . '/' . ($opts['out'] ?? 'coverage-summary.json'); + +/** + * Builds one Istanbul metric entry. + * + * @param int $total Number of measured items. + * @param int $covered Number of those that ran. + * + * @return array{total: int, covered: int, skipped: int, pct: float|int} + */ +function metric(int $total, int $covered): array +{ + $pct = 0; + if ($total > 0) { + $pct = round(($covered / $total) * 100, 2); + } + + return [ + 'total' => $total, + 'covered' => $covered, + 'skipped' => 0, + 'pct' => $pct, + ]; +} + +$suites = []; + +if (is_file($clover) === false) { + fwrite(STDERR, "coverage-publish: $clover not found; run the PHPUnit suite with --coverage-clover first\n"); + exit(2); +} +$xml = simplexml_load_file($clover); +if ($xml === false || isset($xml->project->metrics) === false) { + fwrite(STDERR, "coverage-publish: $clover is not a clover report\n"); + exit(2); +} +$m = $xml->project->metrics; +$suites['phpunit'] = [ + 'statements' => metric((int) $m['statements'], (int) $m['coveredstatements']), + 'functions' => metric((int) $m['methods'], (int) $m['coveredmethods']), +]; +$suites['phpunit']['lines'] = $suites['phpunit']['statements']; + +if (is_file($vitest) === true) { + $js = json_decode((string) file_get_contents($vitest), true); + if (is_array($js) === false || isset($js['total']['statements']) === false) { + fwrite(STDERR, "coverage-publish: $vitest is not a json-summary report\n"); + exit(2); + } + foreach (['lines', 'statements', 'functions'] as $key) { + $suites['vitest'][$key] = metric((int) $js['total'][$key]['total'], (int) $js['total'][$key]['covered']); + } +} + +$total = []; +foreach (['lines', 'statements', 'functions'] as $key) { + $sum = 0; + $hit = 0; + foreach ($suites as $suite) { + $sum += $suite[$key]['total']; + $hit += $suite[$key]['covered']; + } + $total[$key] = metric($sum, $hit); +} + +$commit = trim((string) shell_exec('git -C ' . escapeshellarg($root) . ' rev-parse --short HEAD 2>/dev/null')); +$summary = [ + 'total' => $total, + 'suites' => $suites, + 'measuredAt' => gmdate('Y-m-d'), + 'commit' => $commit, + 'generator' => 'scripts/coverage-publish.php', +]; +file_put_contents($out, json_encode($summary, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"); + +$fmt = static fn (float $pct): string => number_format($pct, 1) . '%'; +$parts = ['PHP ' . $fmt($suites['phpunit']['statements']['pct']) . ' of ' . number_format($suites['phpunit']['statements']['total']) . ' statements']; +if (isset($suites['vitest']) === true) { + $parts[] = 'JavaScript ' . $fmt($suites['vitest']['statements']['pct']) + . ' of ' . number_format($suites['vitest']['statements']['total']) . ' statements'; +} + +$jsNote = 'The JavaScript frontend is not in this figure, because it has no coverage measurement yet. '; +if (isset($suites['vitest']) === true) { + $jsNote = ''; +} +$block = "<!-- coverage:start -->\n" + . 'Measured test coverage: ' . $fmt($total['statements']['pct']) . ' of statements (' . implode(', ', $parts) . '), ' + . 'at commit `' . $commit . '` on ' . $summary['measuredAt'] . '. ' + . $jsNote + . "The figures come from [`coverage-summary.json`](coverage-summary.json); refresh them with `composer coverage:publish`.\n" + . '<!-- coverage:end -->'; + +if (is_file($readme) === true) { + $text = (string) file_get_contents($readme); + $pattern = '/<!-- coverage:start -->.*?<!-- coverage:end -->/s'; + if (preg_match($pattern, $text) === 1) { + $text = preg_replace($pattern, $block, $text); + file_put_contents($readme, $text); + } else { + fwrite( + STDERR, + "coverage-publish: no coverage markers in README.md; add <!-- coverage:start --><!-- coverage:end --> where the line belongs\n" + ); + } +} + +echo 'Coverage ' . $fmt($total['statements']['pct']) . ' (' . implode(', ', $parts) . ")\n"; +exit(0); diff --git a/scripts/generate-openapi.php b/scripts/generate-openapi.php new file mode 100644 index 000000000..a0b107cff --- /dev/null +++ b/scripts/generate-openapi.php @@ -0,0 +1,41 @@ +<?php +/** + * generate-openapi.php + * + * `composer openapi:generate` (governance-rest-api-reference D1): writes + * openapi.json (OpenAPI 3.1) from appinfo/routes.php, the controllers in + * lib/Controller, the `@psalm-type` response shapes in + * lib/ResponseDefinitions.php and the hand-written parts in + * scripts/openapi-overlay.json. With `--stdout` it prints the document + * instead; `composer lint:openapi` compares that with the committed file. + * + * @category Tooling + * @package OCA\LaunchPad\Scripts + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/changes/archive/2026-11-19-governance-rest-api-reference/design.md + */ + +declare(strict_types=1); + +use OCA\LaunchPad\Scripts\OpenApiDocument; + +$root = dirname(__DIR__); +require_once $root.'/vendor/autoload.php'; +require_once __DIR__.'/OpenApiDocument.php'; + +$encoded = OpenApiDocument::encodedFor(root: $root); +if (in_array('--stdout', $argv, true) === true) { + echo $encoded; + exit(0); +} + +file_put_contents($root.'/openapi.json', $encoded); +echo "openapi:generate: wrote openapi.json\n"; diff --git a/scripts/lint-openapi.php b/scripts/lint-openapi.php new file mode 100644 index 000000000..b70d12db8 --- /dev/null +++ b/scripts/lint-openapi.php @@ -0,0 +1,59 @@ +<?php +/** + * lint-openapi.php + * + * `composer lint:openapi` (governance-rest-api-reference D3): fails when a + * versioned API route in appinfo/routes.php has no operation in openapi.json, + * when an operation has no x-launchpad-stability, when an operation is + * documented for a route that does not exist, or when regenerating the + * document (`composer openapi:generate`) would change the committed file. + * Prints one line per problem. + * + * @category Tooling + * @package OCA\LaunchPad\Scripts + * @author Conduction b.v. <info@conduction.nl> + * @copyright 2026 Conduction b.v. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * @version GIT:auto + * @link https://conduction.nl + * + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @spec openspec/specs/rest-api-reference/spec.md + */ + +declare(strict_types=1); + +use OCA\LaunchPad\Scripts\OpenApiDocument; +use OCA\LaunchPad\Scripts\OpenApiDrift; +use OCA\LaunchPad\Scripts\OpenApiRouteCoverage; + +$root = dirname(__DIR__); +require_once $root.'/vendor/autoload.php'; +require_once __DIR__.'/OpenApiDocument.php'; +require_once __DIR__.'/OpenApiDrift.php'; + +$document = json_decode((string) file_get_contents($root.'/openapi.json'), true); +if (is_array($document) === false) { + fwrite(STDERR, "lint:openapi: openapi.json is missing or not valid JSON\n"); + exit(1); +} + +$routes = require $root.'/appinfo/routes.php'; +$problems = OpenApiRouteCoverage::problems(routes: $routes, document: $document); +$problems = array_merge( + $problems, + OpenApiDrift::problems( + committed: (string) file_get_contents($root.'/openapi.json'), + generated: OpenApiDocument::encodedFor(root: $root) + ) +); +if ($problems !== []) { + fwrite(STDERR, implode("\n", $problems)."\n"); + $count = count(array_filter($problems, static fn (string $line): bool => str_starts_with($line, ' ') === false)); + fwrite(STDERR, sprintf("lint:openapi: %d problem(s)\n", $count)); + exit(1); +} + +echo sprintf("lint:openapi: %d operations, every API route documented\n", count(OpenApiRouteCoverage::operations(document: $document))); diff --git a/scripts/openapi-overlay.json b/scripts/openapi-overlay.json new file mode 100644 index 000000000..5b154d6b8 --- /dev/null +++ b/scripts/openapi-overlay.json @@ -0,0 +1,2161 @@ +{ + "info": { + "title": "LaunchPad", + "version": "1.0.0", + "description": "The JSON API of LaunchPad, the dashboard app for Nextcloud: dashboards and their widgets and tiles, kiosk screens, public shares, role-based layouts and permissions, templates and the admin settings behind them.\n\nEvery path is served under `/api/v1/`, the version this document describes. The unversioned `/api/` paths keep working, are deprecated, and name their `/api/v1/` successor in a `Link` header next to a `Deprecation` header. Errors are RFC 9457 problem details (`application/problem+json`), and every response carries an `API-Version` header. Paths that implement an external standard keep the formats of that standard and are not described here.", + "contact": { + "name": "Conduction B.V.", + "email": "info@conduction.nl", + "url": "https://conduction.nl" + }, + "license": { + "name": "EUPL-1.2", + "url": "https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12" + } + }, + "servers": [ + { + "url": "https://{host}/index.php/apps/launchpad/api/v1", + "description": "The LaunchPad API, version 1, on a Nextcloud instance.", + "variables": { + "host": { + "default": "localhost", + "description": "The host name of the Nextcloud instance." + } + } + } + ], + "security": [ + { + "basic_auth": [] + }, + { + "bearer_auth": [] + } + ], + "components": { + "securitySchemes": { + "basic_auth": { + "type": "http", + "scheme": "basic", + "description": "A Nextcloud user name with an app password." + }, + "bearer_auth": { + "type": "http", + "scheme": "bearer", + "description": "A Nextcloud OAuth2 access token." + } + }, + "headers": { + "API-Version": { + "description": "The version of the API that answered, which is the installed app version.", + "schema": { + "type": "string", + "example": "1.0.0" + } + } + }, + "schemas": { + "Problem": { + "type": "object", + "description": "An RFC 9457 problem details document. The members the error already had are kept next to these.", + "properties": { + "type": { + "type": "string", + "description": "A URI reference that identifies the problem type.", + "example": "about:blank" + }, + "title": { + "type": "string", + "description": "A short summary of the problem type.", + "example": "Not Found" + }, + "status": { + "type": "integer", + "description": "The HTTP status code.", + "example": 404 + }, + "detail": { + "type": "string", + "description": "An explanation of this occurrence of the problem." + }, + "instance": { + "type": "string", + "description": "A URI reference that identifies this occurrence." + } + }, + "required": [ + "type", + "title", + "status" + ], + "additionalProperties": true + }, + "CalculatedField": { + "type": "object", + "description": "A calculated field of a widget placement: a formula over the widget's data, other calculated fields and other widgets on the dashboard, stored as its source text and its compiled AST.", + "required": [ + "name", + "compiledExpression" + ], + "properties": { + "id": { + "type": "string", + "description": "The field's id." + }, + "name": { + "type": "string", + "description": "The identifier other fields reference it by; unique on the widget." + }, + "label": { + "type": "string", + "description": "The column or series label." + }, + "expression": { + "type": "string", + "description": "The formula as written, e.g. `(revenue - refunds) / revenue * 100`." + }, + "compiledExpression": { + "type": "object", + "description": "The AST the editor's parser produced: nodes `literal`, `fieldRef` (`source` is `self` or `widget:<id>`), `calculatedRef`, `binary`, `unary`, `if` and `call`. The server checks it rather than re-parsing the text." + }, + "returnType": { + "type": "string", + "enum": [ + "number", + "string", + "boolean", + "date", + "duration", + "null" + ], + "description": "Set by the server's type check on save.", + "readOnly": true + }, + "evaluationMode": { + "type": "string", + "enum": [ + "client", + "server", + "both" + ], + "default": "client", + "description": "`client` evaluates in the browser; `server` and `both` also materialise the value on the widget's OpenRegister source schema." + }, + "serverComputedFieldId": { + "type": [ + "string", + "null" + ], + "readOnly": true, + "description": "The key of the calculated property on the source schema (`launchpad_<placement>__<name>`), null when the field is not materialised." + }, + "formatOptions": { + "type": "object", + "description": "Display formatting (number, date or duration), applied when the value is rendered only." + } + } + }, + "CalculatedFieldError": { + "type": "object", + "description": "Why a placement's calculated fields were refused; nothing is saved.", + "required": [ + "error", + "message" + ], + "properties": { + "error": { + "type": "string", + "enum": [ + "invalidField", + "invalidExpression", + "duplicateField", + "unknownFunction", + "functionNotAllowed", + "arityMismatch", + "functionSignature", + "typeError", + "cycleDetected" + ] + }, + "message": { + "type": "string" + }, + "field": { + "type": "string", + "description": "The field the error is about." + }, + "name": { + "type": "string", + "description": "The function, for function errors." + }, + "cycle": { + "type": "array", + "items": { + "type": "string" + }, + "description": "For `cycleDetected`: the cycle as `<widget>.<field>`, first node repeated at the end." + }, + "widgets": { + "type": "array", + "items": { + "type": "string" + }, + "description": "For `cycleDetected`: the widgets in the cycle." + } + } + }, + "CalculatedFieldWarning": { + "type": "object", + "description": "A save that went through with a change: a server-mode field stored as a client field (`downgraded_evaluation_mode`: it reads another register or schema, OpenRegister cannot evaluate it alike, or the source schema could not be updated), or calculated properties left on the schema of a removed widget (`server_fields_not_removed`).", + "properties": { + "warning": { + "type": "string", + "enum": [ + "downgraded_evaluation_mode", + "server_fields_not_removed" + ] + }, + "field": { + "type": "string" + }, + "reason": { + "type": "string" + } + } + } + }, + "responses": { + "Problem400": { + "description": "Bad request", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem401": { + "description": "Unauthorized", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem404": { + "description": "Not found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem409": { + "description": "Conflict", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem500": { + "description": "Internal server error", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + }, + "Problem502": { + "description": "Bad gateway", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + } + } + }, + "operations": { + "DELETE /admin/catalogue/{}": { + "description": "Remove a catalogue entry.", + "responses": { + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "DELETE /admin/demo-showcases/{}": { + "responses": { + "204": { + "description": "The request succeeded." + } + } + }, + "DELETE /admin/roles/{}": { + "responses": { + "204": { + "description": "The request succeeded." + } + } + }, + "DELETE /announcements/{}": { + "description": "DELETE /api/announcements/{uuid}: delete an announcement. Its author or an administrator." + }, + "DELETE /dashboards/{}/lock": { + "responses": { + "204": { + "description": "The request succeeded." + } + } + }, + "DELETE /dashboards/{}/presence": { + "responses": { + "204": { + "description": "The request succeeded." + } + } + }, + "DELETE /dashboards/{}/reactions/{}": { + "responses": { + "204": { + "description": "The request succeeded." + } + } + }, + "DELETE /exports/{}": { + "description": "Soft-delete a scheduled export. An export is reachable by its owner or an administrator (scheduled-exports)." + }, + "DELETE /kiosk/playlists/{}": { + "responses": { + "204": { + "description": "The request succeeded." + } + } + }, + "DELETE /role-feature-permissions/{}": { + "description": "DELETE /api/role-feature-permissions/{id}.", + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + } + } + }, + "DELETE /role-layout-defaults/{}": { + "description": "DELETE /api/role-layout-defaults/{id}.", + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + } + } + }, + "DELETE /tenant-themes/{}": { + "description": "DELETE /api/tenant-themes/{id} — delete a tenant theme; one that tokens use only with force.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "DELETE /tiles/{}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The id." + } + ] + }, + "DELETE /widgets/files/{}/files/{}": { + "description": "`DELETE /api/widgets/files/{placementId}/files/{fileId}`. Moves the supplied file into the user's trash bin." + }, + "DELETE /widgets/{}": { + "description": "Remove a widget placement. Needs a signed-in Nextcloud user. The calculated properties its server-mode fields own on the OpenRegister source schema are removed with it; when OpenRegister refuses, the placement is still removed and `warnings` says so.", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/LaunchPadStatusOk" + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "example": "ok" + }, + "warnings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CalculatedFieldWarning" + } + } + } + } + ] + } + } + } + } + } + }, + "GET /activity-report": { + "description": "GET a person's activity over a period as counts per activity type and per day (UTC), from the activity events; nothing reports hours. Anybody reads their own. Another person's activity is refused with 403 until an administrator turned activity reporting on with a purpose, is read only by an administrator, carries the purpose, and every such read is written to the audit log.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "GET /activity-report/export": { + "description": "The same report as CSV, with the same numbers: one row per activity type, one per active day, and the total. The same rules as the report decide who may have it.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "GET /admin/activity-reporting": { + "description": "Whether activity reporting on named people is on, and the purpose it serves. Administrators only." + }, + "GET /admin/catalogue": { + "description": "Every catalogue entry, the open requests and the catalogue manager group." + }, + "GET /admin/custom-css": { + "description": "Read the stored CSS for all of LaunchPad (REQ-THM-003)." + }, + "GET /admin/public-start": { + "description": "Answers `{enabled, token, active, reason, candidates}`: whether the public start page is on, the chosen link, whether it is live, why not (`off`, `no-link`, `not-found`, `revoked`, `password`, `expired`), and the public links without a password that are not revoked or expired." + }, + "GET /admin/search-shortcuts": { + "description": "List the search shortcuts every search box honours: `{prefix, name, urlTemplate}` per shortcut." + }, + "GET /admin/storage-report": { + "description": "GET storage use per workspace (a Nextcloud group: the files of its members) and per service (files, trash, versions, each app's app data), now and as a twelve-month series of daily snapshots, the object count per register, and the removable total named apart: trash past its retention and launchpad uploads no row names. Read from the platform's own figures, never by walking files or objects. Administrators only; anybody else gets 403." + }, + "GET /admin/storage-report/export": { + "description": "GET the storage report as CSV: the total, each workspace and service with its twelve months, and the removable total. Administrators only; anybody else gets 403." + }, + "GET /analytics/me": { + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether analytics is on for everyone." + }, + "optedOut": { + "type": "boolean", + "description": "Whether the caller's visits are left out of the counts." + } + } + } + } + } + } + } + }, + "GET /announcements": { + "description": "GET /api/announcements: the announcements the user sees now, their drafts when they author, and the categories they follow." + }, + "GET /announcements/groups": { + "description": "GET /api/announcements/groups: the groups the announcement form offers as the target group, by display name. Announcement editors only." + }, + "GET /announcements/reach": { + "description": "GET /api/announcements/reach: about how many people the target groups reach, for the preview. Announcement editors only.", + "parameters": [ + { + "name": "groups", + "in": "query", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Target group ids." + }, + { + "name": "user", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ] + }, + "GET /announcements/{}/comments": { + "description": "GET /api/announcements/{uuid}/comments: the comments on an announcement that reaches the user, oldest first." + }, + "GET /colleague-activity": { + "description": "GET what other people did recently, as the caller may see it: the caller's own activity stream from the activity app, without the caller's own actions, and without events on a dashboard the caller cannot see now. A left-out entry is absent, not redacted, and is not in any count." + }, + "GET /dashboards/visible": { + "parameters": [ + { + "name": "metadata", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "The metadata." + }, + { + "name": "path", + "in": "query", + "required": false, + "description": "The path.", + "schema": { + "type": "string" + } + }, + { + "name": "cascade", + "in": "query", + "required": false, + "description": "The cascade.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + }, + "500": { + "$ref": "#/components/responses/Problem500" + } + } + }, + "GET /dashboards/{}/filter-events/report": { + "description": "GET /api/dashboards/{uuid}/filter-events/report — the most-used drill-down paths of a dashboard, counted from its filter telemetry. A path is the sequence of filtered dimensions one user drilled through until a reset; it names dimensions only, never filter values. The dashboard's owner and administrators get every user's paths (scope `all`); another user who may view the dashboard gets only their own (scope `own`); anyone else gets 404.", + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "dashboardId": { + "type": "string" + }, + "scope": { + "type": "string", + "enum": [ + "all", + "own" + ] + }, + "events": { + "type": "integer" + }, + "paths": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "count": { + "type": "integer" + } + } + } + } + } + } + } + } + } + } + }, + "GET /dashboards/{}/resolved": { + "description": "GET /api/dashboards/{uuid}/resolved — resolve the dashboard's content for the viewer's locale. Optional `?lang=<code>` query parameter overrides the user's Nextcloud locale; in strict mode an unknown explicit lang returns 404 instead of falling back. REQ-DASH-039. Response shape: - `dashboard`: the dashboard entity payload - `translation`: the matched translation row - `availableLanguages`: sorted list of codes - `currentLanguage`: the matched code - `isFallback`: true when the primary fallback was used." + }, + "GET /embed-settings/telemetry": { + "description": "GET /api/embed-settings/telemetry — whether embed usage telemetry is collected.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + } + } + }, + "GET /embed-tokens": { + "description": "GET /api/embed-tokens — every embed token's metadata, without JWT or hash.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + } + } + }, + "GET /embed-tokens/{}": { + "description": "GET /api/embed-tokens/{id} — one embed token's metadata, without JWT or hash.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "GET /embed-tokens/{}/usage": { + "description": "GET /api/embed-tokens/{id}/usage — seven days of usage in aggregate, no row per visitor (REQ-EMB-008).", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "GET /exports": { + "parameters": [ + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Page size, 1-200." + }, + { + "name": "offset", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Rows to skip." + }, + { + "name": "sort", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "name, nextRunAt or lastRunAt." + }, + { + "name": "order", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "asc or desc." + } + ] + }, + "GET /exports/{}": { + "description": "Read one scheduled export. An export is reachable by its owner or an administrator (scheduled-exports)." + }, + "GET /exports/{}/runs": { + "description": "List the runs of a scheduled export, newest first. An export is reachable by its owner or an administrator (scheduled-exports)." + }, + "GET /exports/{}/runs/{}": { + "description": "Read one run of a scheduled export with every delivery. An export is reachable by its owner or an administrator (scheduled-exports)." + }, + "GET /health-ping/{}": { + "description": "`GET /api/health-ping/{placementId}`. Returns the health badge for one placement. Returns 401 when anonymous, 403 when the caller may not view the underlying dashboard (REQ-HPING-003 \"Caller authorization\" — the ping is NEVER performed in that case), 404 when the placement does not exist or has no ping configured, else 200 with the badge (possibly `stale: true`)." + }, + "GET /livetile/connector/status": { + "description": "`GET /api/livetile/connector/status`. Reports whether the OpenConnector `dashboard-http-datasource` capability is currently available, so the config form can hide or disable `connector` source mode (REQ-LIVETILE-005). Requires only an authenticated caller — carries no placement-specific data." + }, + "GET /livetile/{}": { + "description": "`GET /api/livetile/{placementId}`. Returns the live-tile value for one placement. Returns 401 when anonymous, 403 when the caller may not view the underlying dashboard (REQ-LIVETILE-003 \"Caller authorization\" — the fetch is NEVER performed in that case), 404 when the placement does not exist, else 200 with the value (possibly `stale: true`)." + }, + "GET /manifest": { + "description": "Build and return the v2 app manifest for the authenticated user. Reads the user's dashboard objects from OpenRegister. Each object with a `slug` and `title` property becomes one page entry and one menu entry. Objects the user owns, plus objects explicitly granted to them via OpenRegister's per-object sharing primitive, are included. Route: GET /apps/launchpad/api/manifest." + }, + "GET /office-tiles": { + "description": "Handle `GET /api/office-tiles` (REQ-OFT-001): the office tile pack for the signed-in user, a \"New ...\" tile per file creator the server's office apps register and a tile per enabled office app. Needs a signed-in Nextcloud user with the `office-tiles.list` action." + }, + "GET /openapi.json": { + "responses": { + "200": { + "description": "The OpenAPI document.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + }, + "access-control-allow-origin": { + "description": "Always `*`.", + "schema": { + "type": "string", + "enum": [ + "*" + ] + } + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + } + }, + "GET /people": { + "description": "GET /api/people. REQ-PPL-003: returns `{users, total, hasMore}`, offset-based pagination, capped at {@see PeopleWidgetService::MAX_LIMIT}. Request parameters: - `filters` JSON-encoded array of FilterObject entries (see REQ-PPL-002 / REQ-PPL-006). - `excludeDisabled` 1/0 boolean (default 1). - `showBirthdays` 1/0 boolean (default 1). - `sortBy` One of `displayName` (default), `group`, `recent-activity` (rejected with 400). - `limit` 1..100 (default 50). - `offset` >= 0 (default 0)." + }, + "GET /reports": { + "description": "GET the shipped reports, each with whether it can run on this instance and the registers or schemas it misses." + }, + "GET /reports/{}": { + "description": "GET one report run with the declared parameters as query values. An unavailable report answers with the missing names." + }, + "GET /role-feature-permissions": { + "description": "GET /api/role-feature-permissions." + }, + "GET /role-layout-defaults": { + "description": "GET /api/role-layout-defaults." + }, + "GET /tenant-themes": { + "description": "GET /api/tenant-themes — every tenant theme, with how many embed tokens use it.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + } + } + }, + "GET /tiles/{}/rdp": { + "description": "Returns the `.rdp` connection file of a remote-desktop tile in RDP mode, written from the tile's checked host, port, published program and gateway. The file never contains a user name or password. Returns 403 when the caller may not view the tile's dashboard and 404 when the placement is not a remote-desktop tile in RDP mode.", + "responses": { + "200": { + "description": "The RDP connection file, as an attachment named after the tile." + }, + "403": { + "$ref": "#/components/responses/Problem403" + } + } + }, + "GET /weather/{}": { + "description": "`GET /api/weather/{placementId}`. Returns the weather reading for one placement. Returns 401 when anonymous, 403 when the caller may not view the underlying dashboard (REQ-WEATHER-001 \"Caller authorization\" — the fetch is NEVER performed in that case), 502 when resolution failed with no cached reading available, else 200 with the reading (possibly `stale: true`)." + }, + "GET /widgets/files/{}/contents": { + "description": "`GET /api/widgets/files/{placementId}/contents`. Returns the configured folder's contents as `{items: [...], nextCursor: ?string}`. Empty folder is HTTP 200 with `items: []`. Missing folder is HTTP 404. Read-denied folder is HTTP 403." + }, + "GET /widgets/items": { + "parameters": [ + { + "name": "widgets", + "in": "query", + "required": false, + "description": "Array of widget IDs.", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Maximum items per widget.", + "schema": { + "type": "integer" + } + }, + { + "name": "content", + "in": "query", + "required": false, + "description": "The content.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "201": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "PATCH /exports/{}": { + "description": "Update a scheduled export; a changed recurrence is rescheduled. An export is reachable by its owner or an administrator (scheduled-exports).", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "POST /acknowledgements": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "announcementKey": { + "description": "The announcement key." + } + } + } + } + } + } + }, + "POST /admin/catalogue": { + "description": "Add a catalogue entry.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The app's name." + }, + "description": { + "description": "A short description." + }, + "icon": { + "description": "An icon class or image address." + }, + "iconType": { + "description": "class or url." + }, + "linkType": { + "description": "app (a Nextcloud app id) or url." + }, + "linkValue": { + "description": "The app id or the web address." + }, + "targetGroups": { + "description": "Group ids that see the entry; empty means everyone." + }, + "sortOrder": { + "description": "Position in the catalogue." + } + } + } + } + }, + "required": false + }, + "responses": { + "201": { + "description": "Created." + } + } + }, + "POST /admin/catalogue/requests/{}/approve": { + "description": "Approve a request with the catalogue entry the administrator completed.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The app's name." + }, + "description": { + "description": "A short description." + }, + "icon": { + "description": "An icon class or image address." + }, + "iconType": { + "description": "class or url." + }, + "linkType": { + "description": "app (a Nextcloud app id) or url." + }, + "linkValue": { + "description": "The app id or the web address." + }, + "targetGroups": { + "description": "Group ids that see the entry; empty means everyone." + }, + "sortOrder": { + "description": "Position in the catalogue." + } + } + } + } + }, + "required": false + }, + "responses": { + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + }, + "POST /admin/catalogue/requests/{}/decline": { + "responses": { + "404": { + "$ref": "#/components/responses/Problem404" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + }, + "POST /admin/cleanup/purge": { + "description": "`POST /api/admin/cleanup/purge` — REQ-CLN-005. Body shape: { \"categories\": [\"expired_locks\", ...], // optional, []=all \"dryRun\": true|false // optional, false default }. Returns the per-category breakdown plus total, duration, and dryRun flag. Unknown categories receive HTTP 400 with the list of valid names so the caller can correct the request." + }, + "POST /admin/metadata-fields": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /admin/roles": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /admin/templates": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /admin/templates/shipped/{}/install": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /announcements": { + "description": "POST /api/announcements: write a draft. Administrators and announcement editors only.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "kind": { + "description": "news or notice." + }, + "title": { + "description": "The title." + }, + "body": { + "description": "The text, in Markdown." + }, + "category": { + "description": "The category, or null." + }, + "level": { + "description": "info or warning, for a notice." + }, + "dismissible": { + "description": "Whether a reader may dismiss the notice." + }, + "targetGroups": { + "description": "Group ids; empty means everyone." + }, + "publishAt": { + "description": "When it becomes visible (ISO 8601)." + }, + "expiresAt": { + "description": "When it stops being visible (ISO 8601); required for a notice." + }, + "allowComments": { + "description": "Whether readers may comment." + } + } + } + } + }, + "required": false + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + } + } + }, + "POST /announcements/follows": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "category": { + "description": "The category." + } + } + } + } + } + } + }, + "POST /announcements/{}/comments": { + "description": "POST /api/announcements/{uuid}/comments: comment on an announcement that reaches the user and allows comments.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "message": { + "description": "The comment text." + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + } + } + }, + "POST /announcements/{}/like": { + "description": "POST /api/announcements/{uuid}/like: like an announcement that reaches the user; liking twice changes nothing." + }, + "POST /catalogue/requests": { + "responses": { + "201": { + "description": "Created." + } + } + }, + "POST /dashboard/{}/tile": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "content": { + "type": "object", + "description": "The tile: its title, icon, colours, link type and link value." + } + } + } + } + } + } + }, + "POST /dashboard/{}/tiles/import": { + "description": "Import chosen browser bookmarks onto a dashboard (launcher-bookmark-import REQ-BMI-001..003): each folder becomes a container of link tiles, each loose bookmark a tile, appended at the bottom. Addresses that are not http or https are skipped and listed back. The widget quota is checked for the whole import; nothing is created when it does not fit. Needs a signed-in Nextcloud user who may add to the dashboard.", + "requestBody": { + "required": true + }, + "responses": { + "201": { + "description": "The placements were created; `skipped` lists the bookmarks that were not, with the reason.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "placements": { + "type": "array", + "items": {} + }, + "skipped": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "url": { + "type": "string" + }, + "reason": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + }, + "POST /dashboard/{}/widgets": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "description": "The content." + } + } + } + } + } + } + }, + "POST /dashboards/group/{}": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /dashboards/{}/presence": { + "description": "Announce or renew the caller's editing of a dashboard and answer the colleagues editing it, each with display name and start time (building-edit-a-dashboard-together). Needs edit rights on the dashboard and a signed-in Nextcloud user." + }, + "POST /dashboards/{}/translations": { + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + } + } + }, + "POST /dashboards/{}/versions": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /dashboards/{}/view-event": { + "responses": { + "204": { + "description": "The request succeeded." + } + } + }, + "POST /embed-tokens": { + "description": "POST /api/embed-tokens — issue an embed token; the JWT is in this response only (REQ-EMB-001).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The token name." + }, + "description": { + "description": "The description." + }, + "subject": { + "description": "{type: widget|dashboard, id, filterContext?}." + }, + "scope": { + "description": "{mode, allowedFilters, allowedActions}." + }, + "hostOrigins": { + "description": "The origins that may frame the embed." + }, + "tenantThemeId": { + "description": "The tenant theme." + }, + "tokenExpiresAt": { + "description": "ISO 8601 expiry, empty for none." + }, + "rateLimitPolicy": { + "description": "{requestsPerMinute, burstSize}." + } + } + } + } + }, + "required": false + }, + "responses": { + "201": { + "description": "The request succeeded." + }, + "400": { + "$ref": "#/components/responses/Problem400" + } + } + }, + "POST /embed-tokens/{}/purge-cache": { + "description": "POST /api/embed-tokens/{id}/purge-cache — make every render worker re-read the token now.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "POST /embed-tokens/{}/re-issue": { + "description": "POST /api/embed-tokens/{id}/re-issue — revoke the token and issue a like one; the new JWT is shown once.", + "responses": { + "201": { + "description": "The request succeeded." + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "POST /embed-tokens/{}/revoke": { + "description": "POST /api/embed-tokens/{id}/revoke — revoke a token; render workers refuse it within 60 seconds (REQ-EMB-009).", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "POST /embed-tokens/{}/unrevoke": { + "description": "POST /api/embed-tokens/{id}/unrevoke — accept a revoked token again.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "POST /exports": { + "description": "Create a scheduled export. An export is reachable by its owner or an administrator (scheduled-exports).", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /exports/{}/preview": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The export uuid.", + "schema": { + "type": "string" + } + }, + { + "name": "recipientId", + "in": "query", + "required": false, + "description": "The recipient whose filter context applies.", + "schema": { + "type": "string" + } + }, + { + "name": "format", + "in": "query", + "required": false, + "description": "pdf, png, csv or xlsx; the file itself is returned.", + "schema": { + "type": "string" + } + } + ] + }, + "POST /exports/{}/run": { + "description": "Run a scheduled export now (triggeredBy=manual). An export is reachable by its owner or an administrator (scheduled-exports).", + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /exports/{}/runs/{}/retry": { + "description": "Retry every delivery of a run that failed for good. An export is reachable by its owner or an administrator (scheduled-exports)." + }, + "POST /health-ping/validate": { + "description": "`POST /api/health-ping/validate`. Validates a candidate health-ping config before the author saves the placement (REQ-HPING-001 \"rejected at save time\" — host allow-list, fail-closed). Performs NO ping — only the allow-list check that `resolveForPlacement()` would apply.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "config": { + "description": "The config." + } + } + } + } + } + } + }, + "POST /iframe/framable": { + "description": "`POST /api/iframe/framable`. Server-side check of whether a URL may actually be framed (REQ-IFRAME-003 \"graceful degradation\"). The browser cannot tell an `X-Frame-Options: DENY` / `frame-ancestors 'none'` refusal apart from a normal cross-origin embed, so the widget calls this on mount and shows the fallback card up front when the target refuses framing, instead of a permanently blank frame. Allow-list fail-closed; never leaks the target's response body.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { + "description": "The url." + } + } + } + } + } + } + }, + "POST /iframe/validate-url": { + "description": "`POST /api/iframe/validate-url`. Validates a candidate iframe config before the author saves the placement (REQ-IFRAME-002 \"rejected at save time\" — host allow-list, fail-closed). Requires only an authenticated caller — the allow-list itself is admin-controlled, not per-user.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "config": { + "description": "The config." + } + } + } + } + } + } + }, + "POST /kiosk/playlists": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /livetile/validate-source": { + "description": "`POST /api/livetile/validate-source`. Validates a candidate source config before the author saves the placement (REQ-LIVETILE-002 \"rejected at save time\" — host allow-list, fail-closed). Performs NO fetch — only the allow-list / capability-probe checks that `resolveForPlacement()` would apply.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "config": { + "description": "The config." + } + } + } + } + } + } + }, + "POST /office-tiles/create": { + "description": "Handle `POST /api/office-tiles/create` (REQ-OFT-002): create a file in the signed-in user's own files from an office app's blank template, under a free name (never overwriting). Needs a signed-in Nextcloud user with the `office-tiles.create` action.", + "requestBody": { + "required": true + }, + "responses": { + "201": { + "description": "The file was created." + }, + "400": { + "$ref": "#/components/responses/Problem400" + } + } + }, + "POST /reports/{}/dashboard": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "POST /role-feature-permissions": { + "description": "POST /api/role-feature-permissions. Body: `{name, description?, groupId, allowedWidgets, deniedWidgets?, priorityWeights?}`. Upsert keyed by `groupId`.", + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + } + } + }, + "POST /role-layout-defaults": { + "description": "POST /api/role-layout-defaults.", + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": {} + } + } + } + } + }, + "POST /status-reports": { + "description": "POST a body of work with the rating and summary a person chose, and keep the report in the launchpad register: the figures are computed again and always marked computed, the rating and the summary are marked written when they differ from the computed ones. Needs a signed-in Nextcloud user and OpenRegister (503 without it).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "register": { + "type": "string", + "description": "The register slug of the body of work." + }, + "schema": { + "type": "string", + "description": "The schema slug of its items." + }, + "title": { + "type": "string" + }, + "deadline": { + "type": "string", + "description": "YYYY-MM-DD." + }, + "filters": { + "type": "object" + }, + "statusProperty": { + "type": "string", + "description": "Default status." + }, + "closedValues": { + "type": "array", + "items": { + "type": "string" + } + }, + "dueProperty": { + "type": "string", + "description": "Default deadline." + }, + "health": { + "type": "string", + "enum": [ + "on-track", + "at-risk", + "off-track" + ] + }, + "summary": { + "type": "string" + } + } + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "The request succeeded." + }, + "400": { + "$ref": "#/components/responses/Problem400" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + }, + "POST /status-reports/draft": { + "description": "POST a body of work (the objects of one schema in one register, optionally filtered) and get its status report prefilled, not kept: the figures (total, open, closed, overdue, share closed, days to the deadline), the health rating they give and a summary, each marked computed. The objects are read as the caller.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "register": { + "type": "string", + "description": "The register slug of the body of work." + }, + "schema": { + "type": "string", + "description": "The schema slug of its items." + }, + "title": { + "type": "string" + }, + "deadline": { + "type": "string", + "description": "YYYY-MM-DD." + }, + "filters": { + "type": "object" + }, + "statusProperty": { + "type": "string", + "description": "Default status." + }, + "closedValues": { + "type": "array", + "items": { + "type": "string" + } + }, + "dueProperty": { + "type": "string", + "description": "Default deadline." + } + } + } + } + }, + "required": true + }, + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "409": { + "$ref": "#/components/responses/Problem409" + } + } + }, + "POST /tenant-themes": { + "description": "POST /api/tenant-themes — create a tenant theme; names, values, :root-only CSS and contrast are checked (REQ-EMB-005).", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The theme name." + }, + "cssVariables": { + "description": "Custom properties, {\"--c-primary\": \"#0b5394\", ...}." + }, + "logoUrl": { + "description": "An https logo URL." + }, + "customCss": { + "description": "Extra CSS, :root rules only." + } + } + } + } + }, + "required": false + }, + "responses": { + "201": { + "description": "The request succeeded." + }, + "400": { + "$ref": "#/components/responses/Problem400" + } + } + }, + "POST /tile-click/{}": { + "parameters": [ + { + "name": "placementId", + "in": "path", + "required": true, + "description": "The widget-placement (tile) ID from the URL (numeric — enforced by the route `requirements`).", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "The request succeeded." + } + } + }, + "POST /widgets/files/{}/upload": { + "description": "`POST /api/widgets/files/{placementId}/upload`. Accepts `multipart/form-data` with one or more `files[]` entries and writes them into the placement-configured folder (or a sub-path of it, if `currentPath` is supplied)." + }, + "POST /widgets/{}/rules": { + "responses": { + "201": { + "description": "The request succeeded." + } + } + }, + "PUT /admin/action-matrix": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "matrix": { + "description": "The matrix." + } + } + } + } + } + } + }, + "PUT /admin/activity-reporting": { + "description": "Turn activity reporting on named people on or off. Turning it on needs a purpose, which every report on a named person shows. Administrators only.", + "requestBody": { + "required": true + } + }, + "PUT /admin/catalogue/{}": { + "description": "Change a catalogue entry.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The app's name." + }, + "description": { + "description": "A short description." + }, + "icon": { + "description": "An icon class or image address." + }, + "iconType": { + "description": "class or url." + }, + "linkType": { + "description": "app (a Nextcloud app id) or url." + }, + "linkValue": { + "description": "The app id or the web address." + }, + "targetGroups": { + "description": "Group ids that see the entry; empty means everyone." + }, + "sortOrder": { + "description": "Position in the catalogue." + } + } + } + } + }, + "required": false + }, + "responses": { + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "PUT /admin/custom-css": { + "description": "Clean, scope and store the CSS for all of LaunchPad (REQ-THM-003). Answers with the stored CSS and what the cleaning removed; 400 for a value that is no string or is over 20 KB.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "customCss": { + "type": "string", + "description": "The CSS; an empty string clears it." + } + } + } + } + } + } + }, + "PUT /admin/custom-css/dashboards/{}": { + "description": "Clean, scope and store the CSS for one dashboard (REQ-THM-003), scoped to that dashboard's region. Answers with the stored CSS and what the cleaning removed; 400 for a value that is no string or is over 20 KB, 404 for an unknown dashboard.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "customCss": { + "type": "string", + "description": "The CSS; an empty string clears it." + } + } + } + } + } + } + }, + "PUT /admin/public-start": { + "description": "Body `{enabled, token}`. A link with a password, a revoked or expired link, an unknown token, and switching on without a link answer 400." + }, + "PUT /admin/search-shortcuts": { + "description": "Replace the search shortcuts with the `shortcuts` list from the request body and return the stored list. An invalid list is refused with 400." + }, + "PUT /analytics/me": { + "description": "Store the caller's own opt-out. A request naming another user is refused.", + "responses": { + "200": { + "description": "The request succeeded.", + "headers": { + "API-Version": { + "$ref": "#/components/headers/API-Version" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether analytics is on for everyone." + }, + "optedOut": { + "type": "boolean", + "description": "Whether the caller's visits are left out of the counts." + } + } + } + } + } + } + } + }, + "PUT /announcements/{}": { + "description": "PUT /api/announcements/{uuid}: change an announcement. Its author or an administrator.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "kind": { + "description": "news or notice." + }, + "title": { + "description": "The title." + }, + "body": { + "description": "The text, in Markdown." + }, + "category": { + "description": "The category, or null." + }, + "level": { + "description": "info or warning, for a notice." + }, + "dismissible": { + "description": "Whether a reader may dismiss the notice." + }, + "targetGroups": { + "description": "Group ids; empty means everyone." + }, + "publishAt": { + "description": "When it becomes visible (ISO 8601)." + }, + "expiresAt": { + "description": "When it stops being visible (ISO 8601); required for a notice." + }, + "allowComments": { + "description": "Whether readers may comment." + } + } + } + } + }, + "required": false + } + }, + "PUT /dashboard/{}": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "defaultLinkTarget": { + "type": [ + "string", + "null" + ], + "description": "The default way the dashboard's tiles open; anything not a string is ignored." + }, + "hierarchies": { + "type": "array", + "description": "The hierarchy descriptors the filter bus joins widgets on (REQ-CWF-011), broadest level first; an empty list clears them. A malformed descriptor is refused with 400.", + "maxItems": 8, + "items": { + "type": "object", + "required": [ + "id", + "levels" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]{0,63}$" + }, + "levels": { + "type": "array", + "minItems": 1, + "maxItems": 8, + "items": { + "type": "object", + "required": [ + "dimension" + ], + "properties": { + "dimension": { + "type": "string", + "pattern": "^[A-Za-z][A-Za-z0-9_.]{0,63}$" + }, + "label": { + "type": "string", + "maxLength": 128 + }, + "parentDimension": { + "type": [ + "string", + "null" + ], + "description": "The dimension of the level above; derived when left out." + } + } + } + } + } + } + } + } + } + } + } + } + }, + "PUT /embed-settings/telemetry": { + "description": "PUT /api/embed-settings/telemetry — turn embed usage telemetry on or off; the change is audited.", + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + } + } + }, + "PUT /embed-tokens/{}": { + "description": "PUT /api/embed-tokens/{id} — update name, description or rate limit; subject, scope and origins never change.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The token name." + }, + "description": { + "description": "The description." + }, + "rateLimitPolicy": { + "description": "{requestsPerMinute, burstSize}." + } + } + } + } + }, + "required": false + }, + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "PUT /tenant-themes/{}": { + "description": "PUT /api/tenant-themes/{id} — replace a tenant theme; tokens using it follow at once.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "The theme name." + }, + "cssVariables": { + "description": "Custom properties, {\"--c-primary\": \"#0b5394\", ...}." + }, + "logoUrl": { + "description": "An https logo URL." + }, + "customCss": { + "description": "Extra CSS, :root rules only." + } + } + } + } + }, + "required": false + }, + "responses": { + "400": { + "$ref": "#/components/responses/Problem400" + }, + "404": { + "$ref": "#/components/responses/Problem404" + } + } + }, + "PUT /tiles/{}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The id." + } + ] + }, + "PUT /widgets/{}": { + "description": "Update a widget placement. Needs a signed-in Nextcloud user. A body with `calculatedFields` is checked first (structure, allowed functions, argument counts, types, cycles across the dashboard) and refused with 400 and a `CalculatedFieldError` when a field fails; the stored fields come back with `returnType` set. Server-mode fields are then written to the widget's OpenRegister source schema as read-only calculated properties.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "calculatedFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CalculatedField" + } + } + } + } + } + } + }, + "responses": { + "400": { + "description": "A calculated field was refused.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CalculatedFieldError" + } + } + } + }, + "200": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/LaunchPadPlacement" + }, + { + "type": "object", + "properties": { + "calculatedFields": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CalculatedField" + } + }, + "warnings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CalculatedFieldWarning" + }, + "description": "Present when a calculated field was saved differently from how it was sent." + } + } + } + ] + } + } + } + } + } + } + } +} diff --git a/sigrid.yaml b/sigrid.yaml new file mode 100644 index 000000000..a140cbe11 --- /dev/null +++ b/sigrid.yaml @@ -0,0 +1,91 @@ +# Sigrid analysis scope for Launchpad. +# +# Every key below is documented at +# https://docs.sigrid-says.com/reference/analysis-scope-configuration.html +# Sigrid's default excludes (node_modules, vendor, build output, docs, migrations, +# mocks and stubs) still apply on top of this file. + +# Pin the maintainability model, so a yearly recalibration never changes the +# rating without a deliberate change to this file. +model: "2026" + +# Every top-level directory is a component (lib/, src/, appinfo/, templates/ ...), +# as SIG's guidance (section 2.2) defines top-level components. See openregister +# ADR-014. +component_base_dirs: [""] + +# Test-code patterns can only be set per language, and listing languages switches +# off automatic technology detection. The list therefore names every technology +# in the repo, so nothing that automatic detection would find is dropped. +languages: + - name: php + production: + test: + include: + - ".*/tests/.*[.]php" + - name: javascript + production: + test: + include: + - ".*/tests/.*" + - ".*/__tests__/.*" + - ".*[.](spec|test)[.](js|mjs|cjs|ts|tsx)" + - name: typescript + production: + test: + include: + - ".*/tests/.*" + - ".*/__tests__/.*" + - ".*[.](spec|test)[.](js|mjs|cjs|ts|tsx)" + - name: vue + production: + test: + include: + - ".*/tests/.*[.]vue" + - name: python + production: + test: + include: + - ".*/tests?/.*[.]py" + - ".*/test_[^/]*[.]py" + - ".*/conftest[.]py" + - name: script + production: + test: + include: + - ".*/tests/.*[.]sh" + +# Only generated files and developer tooling are excluded. +exclude: + # Translation catalogues. l10n/<locale>.js is generated from l10n/<locale>.json + # (an OC.L10N.register() call around the same key/value pairs); no logic. + - ".*/l10n/[^/]*[.]js" + # Developer tooling: translation, quality, release and test-runner scripts. + # Not part of the shipped app. + - ".*/scripts/.*" + - ".*/tools/.*" + # OpenSpec change proposals: design notes and spike code for changes that are + # not built yet. The shipped code lives in lib/ and src/. + - ".*/openspec/changes/.*" + # Developer tooling for Claude Code under .claude/: skills, agents and their + # configuration, partly copied from upstream. Not part of the shipped app. + - ".*/[.]claude/.*" + # Root-level tool configuration (ESLint flat config, PHPStan bootstrap, PHP-CS-Fixer). + - ".*/eslint[.]config[.]m?js" + - ".*/phpstan-bootstrap[.]php" + - ".*/[.]php-cs-fixer[.]dist[.]php" + +# Open Source Health. Every @nextcloud package is part of the Nextcloud +# platform's own libraries, which a Nextcloud app cannot avoid. Their AGPL and GPL +# licences are accepted, so only the licence property is excluded for them: +# vulnerabilities, freshness, activity and management are still scored. [:/] +# matches the scoped npm name in either form, because the name the analysis +# compares against is not documented. +# +# The @nextcloud production packages in package-lock.json that this covers: +# auth, axios, browser-storage, capabilities, dialogs, event-bus, files, +# initial-state, l10n, logger, notify_push, password-confirmation, paths, +# router, sharing, typings, vue and vue-select. +dependencychecker: + exclude: + - license: "^@nextcloud[:/].*$" diff --git a/src/App.vue b/src/App.vue index b3e55e9bf..2e31f17b9 100644 --- a/src/App.vue +++ b/src/App.vue @@ -14,18 +14,105 @@ <template> <CnAppRoot + ref="appRoot" :manifest="liveManifest" :registry="registry" :pageTypes="pageTypes" :customComponents="customComponents" :permissions="permissions" - appId="launchpad" /> + :supportDialog="supportNoteForThisAccount" + :userSettingsSections="userSettingsSections" + :translate="translateForApp" + :requiresApps="[]" + :hideMenu="true" + :pageGround="true" + appId="launchpad"> + <!-- + runtime-shell REQ-SHELL-012: `pageGround` puts the board grid on the + page ground instead of the white content panel. + runtime-shell REQ-SHELL-009: LaunchPad renders no navigation panel. + Its destinations are in the More menu: on the dashboard view the + workspace's own More menu, on every other page this one. + --> + <template v-if="showsPageMenu" #header-actions> + <div class="launchpad-page-menu" data-testid="launchpad-page-menu"> + <StartPageMenu /> + </div> + </template> + <!-- + The user settings dialog. Every per-person setting lives here; + LaunchPad adds nothing to Nextcloud's personal settings (Ruben, + 11 Oct 2026). The app's own sections go in #user-settings-sections, + in board LpPersoonlijk's order (personal-settings REQ-PSET-001): + Samenvatting per e-mail, Gebruikscijfers, Verborgen widgets, Mijn profiel; the library keeps + drawing credentials, notifications, the walkthrough replay and + integrations after them, in the order of the userSettingsSections prop. + --> + <template #user-settings-sections> + <DigestSettings /> + <AnalyticsOptOutSettings /> + <HiddenWidgetsSettings /> + <ProfileFieldsSettings /> + </template> + </CnAppRoot> </template> <script> import { CnAppRoot } from '@conduction/nextcloud-vue' +import { translate as ncTranslate } from '@nextcloud/l10n' +import { computed } from 'vue' +import StartPageMenu from './components/Workspace/StartPageMenu.vue' +import AnalyticsOptOutSettings from './views/settings/AnalyticsOptOutSettings.vue' +import DigestSettings from './views/settings/DigestSettings.vue' +import HiddenWidgetsSettings from './views/settings/HiddenWidgetsSettings.vue' +import ProfileFieldsSettings from './views/settings/ProfileFieldsSettings.vue' +import { REQUIRED_OBJECT_PROP } from './constants/propDefinitions.js' import customComponents from './customComponents.js' -import { ICON_CATALOGUE } from './services/iconCatalogue.js' +import { LAZY_ICON_CATALOGUE } from './services/iconCatalogue.js' +import { buildPeopleSource } from './services/widgetDataAdapters.js' +import { isAdminPagePath } from './utils/adminPage.js' +import { bootPath } from './utils/bootPath.js' +import { isKioskMode } from './utils/kioskMode.js' +import { permits } from './utils/permissions.js' + +/** + * The routes that are the dashboard view, whose workspace carries its own + * More menu (REQ-SHELL-009). + */ +export const DASHBOARD_ROUTES = ['Workspace', 'dashboard-detail'] + +/** + * The sections `CnAppNav` renders. An entry in any other section (for + * example `integrations`, which lives in the per-user settings dialog) is + * not a panel destination and is not offered as one. + */ +const PANEL_SECTIONS = ['main', 'footer', 'settings'] + +/** + * The manifest menu entries the navigation panel would render for an + * account: the same permission test as `CnAppNav.passesPermission` + * (an entry without `permission` is for everyone), the panel's sections, + * sorted by `order`. `visibleIf.appInstalled` is honoured against + * `OC.appswebroots`, as the panel does; the app's manifest declares no + * other predicate. + * + * @param {object} manifest The bundled manifest (with fragments merged). + * @param {string[]} permissions The permission strings this account holds. + * @return {object[]} The entries, in panel order. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ +export function panelEntriesFor(manifest, permissions) { + const roots = (typeof window !== 'undefined' && window.OC?.appswebroots) || null + return (manifest?.menu ?? []) + .filter((item) => item && PANEL_SECTIONS.includes(item.section ?? 'main')) + .filter((item) => !item.permission || permits(item.permission, permissions)) + .filter((item) => { + const app = item.visibleIf?.appInstalled + return !app || !roots || Object.hasOwn(roots, app) + }) + .slice() + .sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) +} /** * Root component — mounts `CnAppRoot`, which renders the shared chrome @@ -52,6 +139,11 @@ export default { name: 'App', components: { CnAppRoot, + AnalyticsOptOutSettings, + DigestSettings, + HiddenWidgetsSettings, + ProfileFieldsSettings, + StartPageMenu, }, inject: { @@ -78,7 +170,10 @@ export default { }, }, - /** @spec openspec/specs/runtime-shell/spec.md */ + /** + * @spec openspec/specs/runtime-shell/spec.md + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ provide() { // Re-provide the reactive manifest refs so deeply nested // descendants don't need to prop-drill through WorkspaceApp/Views. @@ -87,7 +182,13 @@ export default { return { runtimeManifest: this.runtimeManifest, manifestLoading: this.manifestLoading, - cnIconCatalogue: ICON_CATALOGUE, + cnIconCatalogue: LAZY_ICON_CATALOGUE, + // runtime-shell REQ-SHELL-009: what `StartPageMenu` reads. A + // computed ref, because provide() runs once and the route changes. + launchpadChrome: computed(() => this.chromeState), + // people-new-colleagues REQ-PPL-014: the people widget form asks + // whether a start date field exists; placements re-provide their own. + cnPeopleSource: buildPeopleSource(), } }, @@ -96,27 +197,18 @@ export default { * Bundled (stub) manifest from the bootstrap. `liveManifest` prefers * the runtime one once it arrives. */ - manifest: { - type: Object, - required: true, - }, + manifest: REQUIRED_OBJECT_PROP, /** * V2 kind-tagged registry (ADR-036). `CnPageRenderer` resolves every * `type: "custom"` page's `component` string against it. */ - registry: { - type: Object, - required: true, - }, + registry: REQUIRED_OBJECT_PROP, /** * Declarative page-type components, from the library's defaults. */ - pageTypes: { - type: Object, - required: true, - }, + pageTypes: REQUIRED_OBJECT_PROP, /** * The permission strings this account holds, built by @@ -163,6 +255,89 @@ export default { }, computed: { + /** + * The sections of the user settings dialog, in board LpPersoonlijk's + * order: the app's own (My profile), then the credentials, and the + * library's notifications, walkthrough replay and integrations. + * + * @return {string[]} Section keys for CnAppRoot. + * @spec openspec/specs/people-widget/spec.md + */ + userSettingsSections() { + return ['app', 'credentials', 'notifications', 'walkthrough', 'integrations'] + }, + + /** + * Whether this page carries the app's More menu at its top: every + * page but the dashboard view, whose workspace has its own More menu, + * and a kiosk view (`?kiosk=1`, REQ-KIOSK-001), which has no chrome. + * It is how a member gets from the Store, Reports, Flows or an admin + * page to anywhere else, now that there is no navigation panel. + * + * @return {boolean} True to render the More menu on this page. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + showsPageMenu() { + if (isKioskMode()) { + return false + } + return !DASHBOARD_ROUTES.includes(this.$route?.name) + }, + + /** + * The entries the panel would have rendered for this account, from + * the app's own manifest: `CnAppNav`'s permission filter, its three + * sections, its order. The runtime manifest's one-entry-per-dashboard + * list is left to the dashboard switcher, which stands beside the + * menu that renders these. + * + * @return {object[]} The visible menu entries, sorted by `order`. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ + chromeMenuEntries() { + return panelEntriesFor(this.manifest, this.permissions) + }, + + /** + * The decision `StartPageMenu` renders from (REQ-SHELL-009). The + * panel is never rendered, so the menus always carry its entries. + * + * @return {{ railSuppressed: boolean, entries: object[], isAdmin: boolean, includePersonalSettings: boolean }} + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ + chromeState() { + return { + railSuppressed: true, + entries: this.chromeMenuEntries, + isAdmin: permits('admin', this.permissions), + includePersonalSettings: + this.manifest?.nav?.includePersonalSettings !== false, + } + }, + + /** + * Whether the shared first-open support note ("Support LaunchPad": + * donate, get support, suggest a feature, review) is mounted for this + * account: administrators only (REQ-SHELL-008). + * + * It used to open for everyone, over the start page an administrator + * had just rolled out to a group (#782). The note asks for things only + * an administrator can act on, so it is theirs. `CnAppRoot` takes + * `false` to opt out; any other value keeps its default, which is the + * library's per-user "once ever" behaviour for the administrator. + * + * Not on a page load that opens the administration page either: that + * page starts its own first-visit tour (REQ-SHELL-011), and the tour + * comes first. The note waits for the next page load elsewhere. + * + * @return {boolean} false for a non-admin account and on the administration page. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-008 + */ + supportNoteForThisAccount() { + return permits('admin', this.permissions) && !isAdminPagePath(bootPath()) + }, + /** * The manifest CnAppRoot should render. * @@ -229,5 +404,75 @@ export default { } }, }, + + /** @spec openspec/specs/people-widget/spec.md */ + mounted() { + window.addEventListener('hashchange', this.openUserSettingsFromHash) + this.openUserSettingsFromHash() + }, + + /** @spec openspec/specs/people-widget/spec.md */ + beforeUnmount() { + window.removeEventListener('hashchange', this.openUserSettingsFromHash) + }, + + methods: { + /** + * Translate a string the manifest carries (menu labels, page titles + * and descriptions, setup and walkthrough copy) in LaunchPad's own + * catalogue. `CnAppRoot` never imports an app's `t()`; without this + * its default is the identity, and every manifest string stayed + * English for a Dutch reader although `l10n/nl.js` has them all. + * + * @param {string} key The text as the manifest writes it. + * @param {object} [vars] Placeholder values. + * @return {string} The translation, or the key when there is none. + * @spec exclude wiring only: hands the library the app's translator. Which strings exist and what they say is specified where the manifest declares them. + */ + translateForApp(key, vars) { + return ncTranslate('launchpad', key, vars) + }, + + /** + * The mounted CnAppRoot, or null before it mounts. + * + * @return {object|null} The CnAppRoot instance. + * @spec openspec/specs/people-widget/spec.md + */ + appRoot() { + return this.$refs.appRoot || null + }, + + /** + * Open the user settings dialog when the location hash is + * `#user-settings`, the deep link that replaces the old forms in + * Nextcloud's personal settings. + * + * @return {void} + * @spec openspec/specs/people-widget/spec.md + */ + openUserSettingsFromHash() { + const root = this.appRoot() + if (root && window.location.hash === '#user-settings') { + root.userSettingsOpen = true + } + }, + }, } </script> + +<style> +/* The More menu on a page other than the dashboard view: at the top end of + the content, which keeps the column beside it free so a page's own header + actions are never covered. */ +.launchpad-page-menu { + position: absolute; + top: calc(2 * var(--default-grid-baseline, 4px)); + inset-inline-end: calc(2 * var(--default-grid-baseline, 4px)); + z-index: 10; +} + +#app-content-vue:has(> .launchpad-page-menu) { + padding-inline-end: calc(var(--default-clickable-area, 34px) + 4 * var(--default-grid-baseline, 4px)); +} +</style> diff --git a/src/__tests__/App.navigationPanel.spec.js b/src/__tests__/App.navigationPanel.spec.js new file mode 100644 index 000000000..117876863 --- /dev/null +++ b/src/__tests__/App.navigationPanel.spec.js @@ -0,0 +1,241 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * LaunchPad without the navigation panel (runtime-shell REQ-SHELL-009). + * + * No route renders the panel. The dashboard view carries the workspace's own + * More menu; every other page carries the app's More menu at its top. The + * stand-in `CnAppRoot` honours `hideMenu` as the library does. + * + * The route-no-loss rule: every entry the panel would have shown has a + * destination in the start-page menu, and every router destination is a + * page the app declares. + */ + +import { mount } from '@vue/test-utils' +import fs from 'node:fs' +import path from 'node:path' +import { createPinia } from 'pinia' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnAppRoot: { + name: 'CnAppRoot', + props: ['hideMenu', 'pageGround'], + template: + '<div><slot v-if="!hideMenu" name="menu"><nav data-testid="cn-nav" /></slot><main /><slot name="header-actions" /></div>', + }, + // The user settings dialog's library sections (src/views/settings/UserSettings.vue). + CnCredentials: { name: 'CnCredentials', template: '<div />' }, + CnNotificationPreferences: { name: 'CnNotificationPreferences', template: '<div />' }, +})) +vi.mock('../customComponents.js', () => ({ default: {} })) +vi.mock('../services/iconCatalogue.js', () => ({ ICON_CATALOGUE: [], LAZY_ICON_CATALOGUE: [], loadIconCatalogue: () => Promise.resolve([]) })) + +import App, { DASHBOARD_ROUTES, panelEntriesFor } from '../App.vue' +import { + isExternal, + resolveMenuItem, + settingsMenuItems, + startPageSections, +} from '../components/Workspace/moreMenuItems.js' +import bundledStub from '../manifest.json' +import { routesFromManifest } from '../utils/manifestRoutes.js' +import { applyManifestFragments } from '../utils/mergeManifestFragments.js' + +/** + * The manifest main.js builds: the bundled stub with every fragment + * merged, read from disk because `require.context` is webpack-only. + * + * @return {object} The merged manifest. + */ +function mergedManifest() { + const dir = path.resolve(__dirname, '../manifest.d') + const fragments = fs + .readdirSync(dir) + .filter((name) => name.endsWith('.json')) + .sort() + .map((name) => JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'))) + return applyManifestFragments(bundledStub, fragments) +} + +function mountApp({ routeName, permissions = ['user'] }) { + return mount(App, { + props: { + manifest: mergedManifest(), + registry: {}, + pageTypes: {}, + permissions, + }, + global: { + plugins: [createPinia()], + mocks: { $route: { name: routeName } }, + }, + }) +} + +describe('App without the navigation panel (REQ-SHELL-009)', () => { + it.each([...DASHBOARD_ROUTES, 'Store', 'Reports', 'Flows', 'admin-settings'])( + 'renders no panel on the %s route', + (routeName) => { + const wrapper = mountApp({ routeName }) + expect(wrapper.find('[data-testid="cn-nav"]').exists()).toBe(false) + expect(wrapper.find('nav').exists()).toBe(false) + }, + ) + + it.each(DASHBOARD_ROUTES)( + 'leaves the More menu to the workspace on the %s route', + (routeName) => { + const wrapper = mountApp({ routeName }) + expect( + wrapper.find('[data-testid="launchpad-page-menu"]').exists(), + ).toBe(false) + }, + ) + + it.each([ + 'Store', + 'Reports', + 'Flows', + 'FeaturesRoadmap', + 'admin-settings', + 'admin-templates-index', + ])('puts the More menu at the top of the %s page', (routeName) => { + const wrapper = mountApp({ routeName }) + const holder = wrapper.find('[data-testid="launchpad-page-menu"]') + expect(holder.exists()).toBe(true) + expect(holder.findComponent({ name: 'StartPageMenu' }).exists()).toBe( + true, + ) + }) + + it('tells the menus the panel is left out, on every route', () => { + const wrapper = mountApp({ routeName: 'Store' }) + expect(wrapper.vm.chromeState.railSuppressed).toBe(true) + expect(App.provide.call({ chromeState: {} })).toHaveProperty( + 'launchpadChrome', + ) + }) +}) + +describe('App on the page ground (REQ-SHELL-012)', () => { + it('asks the root to draw its pages on the page ground', () => { + const wrapper = mountApp({ routeName: 'Workspace' }) + expect( + wrapper.findComponent({ name: 'CnAppRoot' }).props('pageGround'), + ).toBe(true) + }) +}) + +describe('Route no loss: every panel destination stays reachable', () => { + const manifest = mergedManifest() + const routeNames = new Set( + routesFromManifest(manifest, {}) + .map((r) => r.name) + .filter(Boolean), + ) + + /** + * What CnAppNav renders from this manifest for a permission set: every + * entry in a panel section whose permission the account holds. The + * panel's own filter, restated here so this test does not pass by + * agreeing with `panelEntriesFor` on a wrong answer. + * + * @param {string[]} permissions The account's permissions. + * @return {object[]} The entries. + */ + function panelWouldShow(permissions) { + return manifest.menu.filter( + (item) => + ['main', 'footer', 'settings'].includes(item.section ?? 'main') + && (!item.permission || permissions.includes(item.permission)), + ) + } + + it.each([ + ['a member', ['user']], + ['an administrator', ['user', 'admin']], + ])('offers %s every entry the panel would have shown', (_who, permissions) => { + const shown = panelWouldShow(permissions) + expect(shown.length).toBeGreaterThan(0) + const offered = panelEntriesFor(manifest, permissions) + expect(offered.map((e) => e.id).sort()).toEqual( + shown.map((e) => e.id).sort(), + ) + for (const entry of offered) { + const item = resolveMenuItem(entry, () => {}) + expect(item, `${entry.id} has no destination`).not.toBeNull() + if (item.to) { + expect( + routeNames.has(item.to.name), + `${entry.id} -> ${item.to.name}`, + ).toBe(true) + } else { + expect(Boolean(item.href || item.onClick)).toBe(true) + } + } + }) + + it.each([ + ['a member', ['user'], false], + ['an administrator', ['user', 'admin'], true], + ])('puts every entry under More\'s Settings for %s, but the two offered elsewhere', (_who, permissions, isAdmin) => { + const entries = panelEntriesFor(manifest, permissions) + const chrome = { railSuppressed: true, entries, isAdmin, includePersonalSettings: true } + const ids = settingsMenuItems(startPageSections(chrome, () => {})).map((item) => item.id) + // The Dashboards group stands in for the dashboards entry, and the + // admin settings link for the admin settings route. + const elsewhere = ['dashboards', 'admin-settings'] + for (const entry of entries.filter((e) => !elsewhere.includes(e.id))) { + expect(ids, `${entry.id} is not under Settings`).toContain(entry.id) + } + expect(ids.includes('admin-settings-link')).toBe(isAdmin) + expect(ids[0]).toBe('personal-settings') + }) + + it('hides the admin entries from a member, as the panel does', () => { + const ids = panelEntriesFor(manifest, ['user']).map((e) => e.id) + expect(ids).not.toContain('admin-settings') + expect(ids).not.toContain('admin-templates') + expect(ids).toContain('Documentation') + expect(ids).toContain('StoreMenu') + expect(ids).toContain('ReportsMenu') + expect(ids).toContain('FeaturesRoadmapMenu') + }) + + it('names the three footer destinations, with Reports under Advanced', () => { + const entries = panelEntriesFor(manifest, ['user']) + const footer = entries + .filter((e) => e.section === 'footer') + .map((e) => e.label) + expect(footer).toEqual([ + 'Documentation', + 'Marketplace', + 'Features & roadmap', + ]) + expect(entries.find((e) => e.id === 'ReportsMenu').section).toBe('settings') + }) + + it('opens a scheme-prefixed link in a new tab and an app path in the same one', () => { + expect(isExternal('https://launchpad.conduction.nl')).toBe(true) + expect(isExternal('/index.php/settings/admin/launchpad')).toBe(false) + expect( + resolveMenuItem({ id: 'x', label: 'X', href: 'https://a.b' }, null) + .external, + ).toBe(true) + }) + + it('resolves an action entry to a button only when the opener exists', () => { + const entry = { + id: 'me', + label: 'Me', + action: 'user-settings', + route: 'ignored', + } + expect(resolveMenuItem(entry, null)).toBeNull() + const open = () => {} + expect(resolveMenuItem(entry, open)).toMatchObject({ onClick: open }) + }) +}) diff --git a/src/__tests__/App.supportNote.spec.js b/src/__tests__/App.supportNote.spec.js new file mode 100644 index 000000000..848900e9d --- /dev/null +++ b/src/__tests__/App.supportNote.spec.js @@ -0,0 +1,61 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The first-open support note is mounted for administrators only + * (runtime-shell REQ-SHELL-008): `App.vue` hands `CnAppRoot` `false` for + * every other account, which is the library's documented opt-out. + */ + +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnAppRoot: { name: 'CnAppRoot', template: '<div />' }, +})) +vi.mock('../customComponents.js', () => ({ default: {} })) +const boot = vi.hoisted(() => ({ path: '/index.php/apps/launchpad/' })) +vi.mock('../utils/bootPath.js', () => ({ bootPath: () => boot.path, bootHash: () => '' })) +vi.mock('../services/iconCatalogue.js', () => ({ ICON_CATALOGUE: [], LAZY_ICON_CATALOGUE: [], loadIconCatalogue: () => Promise.resolve([]) })) + +import App from '../App.vue' + +describe('App support note', () => { + it('is off for a member', () => { + expect( + App.computed.supportNoteForThisAccount.call({ permissions: ['user'] }), + ).toBe(false) + }) + + it('is off when the permissions are missing', () => { + expect( + App.computed.supportNoteForThisAccount.call({ permissions: undefined }), + ).toBe(false) + }) + + it('stays on for an administrator', () => { + expect( + App.computed.supportNoteForThisAccount.call({ + permissions: ['user', 'admin'], + }), + ).toBe(true) + }) + + it('waits on a page load that opens the administration page, where the admin tour comes first', () => { + boot.path = '/index.php/apps/launchpad/admin/general' + try { + expect( + App.computed.supportNoteForThisAccount.call({ + permissions: ['user', 'admin'], + }), + ).toBe(false) + } finally { + boot.path = '/index.php/apps/launchpad/' + } + }) + + it('is what the root receives', () => { + // The template binding is the wiring; a computed nobody binds is a + // guard with no call site. + expect(App.render?.toString() ?? '').toContain('supportNoteForThisAccount') + }) +}) diff --git a/src/__tests__/App.translate.spec.js b/src/__tests__/App.translate.spec.js new file mode 100644 index 000000000..ec5ef02fb --- /dev/null +++ b/src/__tests__/App.translate.spec.js @@ -0,0 +1,49 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The manifest's strings (menu labels, page titles and descriptions) are + * translated in LaunchPad's own catalogue. `CnAppRoot` defaults its + * `translate` prop to the identity, so without the binding every one of them + * stayed English. + */ + +import { describe, expect, it, vi } from 'vitest' + +const translate = vi.fn((app, text) => `${app}:${text}`) + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (...args) => translate(...args), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + CnAppRoot: { name: 'CnAppRoot', template: '<div />' }, +})) +vi.mock('../customComponents.js', () => ({ default: {} })) +vi.mock('../services/iconCatalogue.js', () => ({ ICON_CATALOGUE: [], LAZY_ICON_CATALOGUE: [], loadIconCatalogue: () => Promise.resolve([]) })) + +import App from '../App.vue' + +describe('App manifest translator', () => { + it('looks a manifest string up in the launchpad catalogue', () => { + expect(App.methods.translateForApp('Documentation')).toBe( + 'launchpad:Documentation', + ) + }) + + it('passes placeholder values on', () => { + const vars = { count: 3 } + App.methods.translateForApp('{count} dashboards', vars) + expect(translate).toHaveBeenLastCalledWith( + 'launchpad', + '{count} dashboards', + vars, + ) + }) + + it('is what the root receives', () => { + // The template binding is the wiring; a method nobody binds is a + // translator with no call site. + expect(App.render?.toString() ?? '').toContain('translateForApp') + }) +}) diff --git a/src/__tests__/App.withoutOpenRegister.spec.js b/src/__tests__/App.withoutOpenRegister.spec.js new file mode 100644 index 000000000..eacbfac38 --- /dev/null +++ b/src/__tests__/App.withoutOpenRegister.spec.js @@ -0,0 +1,37 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * LaunchPad runs without OpenRegister (launchpad-adopt-or-abstractions, + * "Install on OR-less Nextcloud"). `CnAppRoot` blocks the whole shell for + * every app in `requiresApps`, and its default is `['openregister']`, so the + * root must be told that LaunchPad requires no app. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnAppRoot: { + name: 'CnAppRoot', + props: { requiresApps: { type: Array, default: () => ['openregister'] } }, + template: '<div><slot name="menu" /><main /></div>', + }, + CnCredentials: { name: 'CnCredentials', template: '<div />' }, + CnNotificationPreferences: { name: 'CnNotificationPreferences', template: '<div />' }, +})) +vi.mock('../customComponents.js', () => ({ default: {} })) +vi.mock('../services/iconCatalogue.js', () => ({ ICON_CATALOGUE: [], LAZY_ICON_CATALOGUE: [], loadIconCatalogue: () => Promise.resolve([]) })) + +import App from '../App.vue' +import bundledStub from '../manifest.json' + +describe('App without OpenRegister', () => { + it('tells the app root that no app is required, so a missing OpenRegister does not block the shell', () => { + const wrapper = mount(App, { + props: { manifest: bundledStub, registry: {}, pageTypes: {}, permissions: ['user'] }, + global: { mocks: { $route: { name: 'Workspace' } } }, + }) + expect(wrapper.findComponent({ name: 'CnAppRoot' }).props('requiresApps')).toEqual([]) + }) +}) diff --git a/src/__tests__/DashboardSwitcherSidebar.test.js b/src/__tests__/DashboardSwitcherSidebar.test.js deleted file mode 100644 index 1efa843e0..000000000 --- a/src/__tests__/DashboardSwitcherSidebar.test.js +++ /dev/null @@ -1,468 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - */ - -import { mount } from '@vue/test-utils' -import { describe, expect, it, vi } from 'vitest' -import DashboardSwitcherSidebar from '@/components/Workspace/DashboardSwitcherSidebar.vue' - -// Mock the translate function -vi.mock('@nextcloud/l10n', () => ({ - translate: vi.fn((app, key) => key), -})) - -describe('DashboardSwitcherSidebar', () => { - describe('REQ-SWITCH-001: Three-section navigation', () => { - it('renders only visible sections', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [{ id: 'u1', name: 'User Dash', icon: 'Star' }], - }, - mocks: { - t: (app, key) => key, - }, - }) - - // Should have only "My Dashboards" section - expect(wrapper.find('.sidebar-section-heading').text()).toBe( - 'My Dashboards', - ) - expect(wrapper.findAll('.sidebar-section-heading')).toHaveLength(1) - }) - - it('renders all three sections when populated', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupName: 'Engineering', - groupDashboards: [ - { - id: 'g1', - name: 'Group Dash', - icon: 'Home', - source: 'group', - }, - { - id: 'd1', - name: 'Default Dash', - icon: 'Star', - source: 'default', - }, - ], - userDashboards: [{ id: 'u1', name: 'User Dash', icon: 'Heart' }], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const headings = wrapper.findAll('.sidebar-section-heading') - expect(headings).toHaveLength(3) - expect(headings.at(0).text()).toBe('Engineering') - expect(headings.at(1).text()).toBe('Default') - expect(headings.at(2).text()).toBe('My Dashboards') - }) - - it('shows My Dashboards when allowUserDashboards is true even with empty list', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [], - allowUserDashboards: true, - }, - mocks: { - t: (app, key) => key, - }, - }) - - expect(wrapper.find('.sidebar-section-heading').text()).toBe( - 'My Dashboards', - ) - }) - - it('does not render My Dashboards when empty and allowUserDashboards is false', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [], - allowUserDashboards: false, - }, - mocks: { - t: (app, key) => key, - }, - }) - - expect(wrapper.find('.sidebar-section-heading').exists()).toBe(false) - }) - }) - - describe('REQ-SWITCH-002: Click semantics', () => { - it('emits update:open(false) BEFORE switch event', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [ - { - id: 'g1', - name: 'Group Dash', - icon: 'Home', - source: 'group', - }, - ], - userDashboards: [], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const emits = [] - wrapper.vm.$on('update:open', () => emits.push('update:open')) - wrapper.vm.$on('switch', () => emits.push('switch')) - - const dashButton = wrapper.find('.sidebar-item--dashboard') - await dashButton.trigger('click') - - expect(emits).toEqual(['update:open', 'switch']) - }) - - it('emits switch with correct source for primary group items', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [ - { - id: 'g1', - name: 'Group Dash', - icon: 'Home', - source: 'group', - }, - ], - userDashboards: [], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const dashButton = wrapper.find('.sidebar-item--dashboard') - await dashButton.trigger('click') - - const switchEmits = wrapper.emitted('switch') - expect(switchEmits).toHaveLength(1) - expect(switchEmits[0]).toEqual(['g1', 'group']) - }) - - it('emits switch with source "default" for default group items', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [ - { - id: 'd1', - name: 'Default Dash', - icon: 'Star', - source: 'default', - }, - ], - userDashboards: [], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const dashButton = wrapper.find('.sidebar-item--dashboard') - await dashButton.trigger('click') - - const switchEmits = wrapper.emitted('switch') - expect(switchEmits[0]).toEqual(['d1', 'default']) - }) - - it('emits switch with source "user" for personal items', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [{ id: 'u1', name: 'User Dash', icon: 'Heart' }], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const dashButton = wrapper.find('.sidebar-item--dashboard') - await dashButton.trigger('click') - - const switchEmits = wrapper.emitted('switch') - expect(switchEmits[0]).toEqual(['u1', 'user']) - }) - }) - - describe('REQ-SWITCH-003: Active item highlight', () => { - it('applies active class to the active dashboard', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [ - { - id: 'g1', - name: 'Group Dash 1', - icon: 'Home', - source: 'group', - }, - { - id: 'g2', - name: 'Group Dash 2', - icon: 'Star', - source: 'group', - }, - ], - userDashboards: [], - activeDashboardId: 'g2', - }, - mocks: { - t: (app, key) => key, - }, - }) - - const items = wrapper.findAll('.sidebar-item--dashboard') - expect(items.at(0).classes()).not.toContain('active') - expect(items.at(1).classes()).toContain('active') - }) - - it('updates active class reactively when prop changes', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [ - { - id: 'g1', - name: 'Group Dash', - icon: 'Home', - source: 'group', - }, - ], - userDashboards: [{ id: 'u1', name: 'User Dash', icon: 'Heart' }], - activeDashboardId: 'g1', - }, - mocks: { - t: (app, key) => key, - }, - }) - - expect(wrapper.findAll('.sidebar-item.active')).toHaveLength(1) - - await wrapper.setProps({ activeDashboardId: 'u1' }) - - const activeItems = wrapper.findAll('.sidebar-item.active') - expect(activeItems).toHaveLength(1) - expect(activeItems.at(0).text()).toContain('User Dash') - }) - }) - - describe('REQ-SWITCH-004: Personal delete affordance', () => { - it('does not emit switch when delete button is clicked', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [{ id: 'u1', name: 'User Dash', icon: 'Heart' }], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const deleteButton = wrapper.find('.sidebar-item-delete') - await deleteButton.trigger('click') - - expect(wrapper.emitted('switch')).toBeUndefined() - expect(wrapper.emitted('update:open')).toBeUndefined() - }) - - it('emits delete-dashboard when delete button is clicked', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [{ id: 'u1', name: 'User Dash', icon: 'Heart' }], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const deleteButton = wrapper.find('.sidebar-item-delete') - await deleteButton.trigger('click') - - const deleteEmits = wrapper.emitted('deleteDashboard') - expect(deleteEmits).toHaveLength(1) - expect(deleteEmits[0]).toEqual(['u1']) - }) - - it('shows delete button only for personal dashboards, not for group items', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [ - { - id: 'g1', - name: 'Group Dash', - icon: 'Home', - source: 'group', - }, - ], - userDashboards: [{ id: 'u1', name: 'User Dash', icon: 'Heart' }], - }, - mocks: { - t: (app, key) => key, - }, - }) - - expect(wrapper.findAll('.sidebar-item-delete')).toHaveLength(1) - }) - }) - - describe('REQ-SWITCH-005: Create-dashboard affordance', () => { - it('renders + New Dashboard button when allowUserDashboards is true', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [], - allowUserDashboards: true, - }, - mocks: { - t: (app, key) => key, - }, - }) - - expect(wrapper.find('.sidebar-item--action').exists()).toBe(true) - }) - - it('does not render + New Dashboard button when allowUserDashboards is false', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [], - allowUserDashboards: false, - }, - mocks: { - t: (app, key) => key, - }, - }) - - expect(wrapper.find('.sidebar-item--action').exists()).toBe(false) - }) - - it('emits update:open(false) and create-dashboard in order', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [], - userDashboards: [], - allowUserDashboards: true, - }, - mocks: { - t: (app, key) => key, - }, - }) - - const emits = [] - wrapper.vm.$on('update:open', () => emits.push('update:open')) - wrapper.vm.$on('createDashboard', () => emits.push('createDashboard')) - - const createButton = wrapper.find('.sidebar-item--action') - await createButton.trigger('click') - - expect(emits).toEqual(['update:open', 'createDashboard']) - }) - }) - - describe('REQ-SWITCH-006: Slide-in animation', () => { - it('applies open class when isOpen is true', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - isOpen: false, - groupDashboards: [], - userDashboards: [], - }, - mocks: { - t: (app, key) => key, - }, - }) - - expect( - wrapper.find('.dashboard-switcher-sidebar').classes(), - ).not.toContain('open') - - await wrapper.setProps({ isOpen: true }) - - expect(wrapper.find('.dashboard-switcher-sidebar').classes()).toContain( - 'open', - ) - }) - }) - - describe('REQ-SWITCH-007: Icon rendering', () => { - it('renders icons via IconRenderer for all dashboard items', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [ - { id: 'g1', name: 'Home', icon: 'Home', source: 'group' }, - { - id: 'g2', - name: 'Chart', - icon: 'ChartBar', - source: 'group', - }, - ], - userDashboards: [ - { id: 'u1', name: 'Star', icon: 'Star' }, - { id: 'u2', name: 'Default', icon: null }, - ], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const iconRenderers = wrapper.findAllComponents({ name: 'IconRenderer' }) - expect(iconRenderers.length).toBeGreaterThan(0) - }) - }) - - describe('Accessibility', () => { - it('responds to Esc key to close sidebar', async () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - isOpen: true, - groupDashboards: [], - userDashboards: [], - }, - mocks: { - t: (app, key) => key, - }, - }) - - await wrapper.find('.dashboard-switcher-sidebar').trigger('keydown.esc') - - const updateEmits = wrapper.emitted('update:open') - expect(updateEmits).toHaveLength(1) - expect(updateEmits[0]).toEqual([false]) - }) - - it('has aria-labels on dashboard items', () => { - const wrapper = mount(DashboardSwitcherSidebar, { - propsData: { - groupDashboards: [ - { - id: 'g1', - name: 'Engineering Dashboard', - icon: 'Home', - source: 'group', - }, - ], - userDashboards: [], - }, - mocks: { - t: (app, key) => key, - }, - }) - - const button = wrapper.find('.sidebar-item--dashboard') - expect(button.attributes('aria-label')).toBe('Engineering Dashboard') - }) - }) -}) diff --git a/src/__tests__/Views.test.js b/src/__tests__/Views.test.js deleted file mode 100644 index 73a9e3ee9..000000000 --- a/src/__tests__/Views.test.js +++ /dev/null @@ -1,502 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - */ - -import { mount } from '@vue/test-utils' -import { createPinia, setActivePinia } from 'pinia' -import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' - -// --------------------------------------------------------------------------- -// Global mocks -// --------------------------------------------------------------------------- - -// Mock @nextcloud/vue to avoid CSS extension errors in jsdom. -// Enumerate all components used across app source files. -vi.mock('@nextcloud/vue', () => { - const makeStub = ( - name, - template = `<div class="nc-stub-${name.toLowerCase()}" />`, - ) => ({ - name, - template, - props: { - type: { default: 'secondary' }, - disabled: { default: false }, - ariaLabel: { default: '' }, - checked: { default: false }, - description: { default: '' }, - options: { default: () => [] }, - label: { default: '' }, - trackBy: { default: '' }, - clearable: { default: true }, - show: { default: false }, - value: { default: null }, - }, - }) - - return { - NcButton: { - name: 'NcButton', - props: { - type: { type: String, default: 'secondary' }, - disabled: { type: Boolean, default: false }, - ariaLabel: { type: String, default: '' }, - }, - render(h) { - return h( - 'button', - { - class: 'button-vue', - attrs: { disabled: this.disabled || null }, - on: this.$listeners, - }, - [this.$slots.default, this.$slots.icon], - ) - }, - }, - NcEmptyContent: { - name: 'NcEmptyContent', - props: { name: String, description: String }, - render(h) { - return h('div', { class: 'empty-content' }, [ - this.$slots.icon, - this.$slots.default, - this.$slots.action, - ]) - }, - }, - NcDashboardWidget: makeStub('NcDashboardWidget'), - NcLoadingIcon: makeStub('NcLoadingIcon'), - NcModal: makeStub('NcModal'), - NcSelect: makeStub('NcSelect'), - NcTextField: makeStub('NcTextField'), - NcColorPicker: makeStub('NcColorPicker'), - NcCheckboxRadioSwitch: makeStub('NcCheckboxRadioSwitch'), - } -}) - -// Mock @nextcloud/l10n -vi.mock('@nextcloud/l10n', () => ({ - t: vi.fn((_app, key) => key), - translate: vi.fn((_app, key) => key), -})) - -// Mock @nextcloud/dialogs (toasts) -vi.mock('@nextcloud/dialogs', () => ({ - showSuccess: vi.fn(), - showError: vi.fn(), -})) - -// Mock @nextcloud/initial-state (used by stores / utilities) -vi.mock('@nextcloud/initial-state', () => ({ - loadState: vi.fn((_app, _key, fallback) => fallback), -})) - -// Mock @nextcloud/axios (prevent HTTP calls) -vi.mock('@nextcloud/axios', () => ({ - default: { - get: vi.fn(() => Promise.resolve({ data: [] })), - post: vi.fn(() => Promise.resolve({ data: {} })), - put: vi.fn(() => Promise.resolve({ data: {} })), - delete: vi.fn(() => Promise.resolve({ data: {} })), - }, -})) - -// Mock @nextcloud/router -vi.mock('@nextcloud/router', () => ({ - generateUrl: vi.fn((path) => path), -})) - -beforeAll(() => { - // Provide a global `t` in case some child components call it directly - if (typeof globalThis.t !== 'function') { - globalThis.t = (_app, key) => key - } -}) - -// --------------------------------------------------------------------------- -// Stub child components to keep tests lightweight -// --------------------------------------------------------------------------- - -const DashboardGridStub = { - name: 'DashboardGrid', - template: '<div class="stub-dashboard-grid" />', - props: ['placements', 'widgets', 'editMode', 'gridColumns'], - methods: { - placeWidget() { - return { x: 0, y: 0, w: 4, h: 4 } - }, - }, -} - -const DashboardSwitcherSidebarStub = { - name: 'DashboardSwitcherSidebar', - template: '<div class="stub-sidebar" />', - props: [ - 'isOpen', - 'groupName', - 'groupDashboards', - 'userDashboards', - 'activeDashboardId', - 'allowUserDashboards', - ], -} - -const SidebarBackdropStub = { - name: 'SidebarBackdrop', - template: '<div class="stub-backdrop" />', - props: ['isOpen'], -} - -const WidgetPickerStub = { - name: 'WidgetPicker', - template: '<div class="stub-picker" />', - props: ['open', 'widgets', 'placedWidgetIds', 'dashboards', 'activeDashboardId'], -} - -const AddWidgetModalStub = { - name: 'AddWidgetModal', - template: '<div class="stub-add-widget-modal" />', - props: ['show', 'widgets', 'editingWidget'], -} - -const WidgetStyleEditorStub = { - name: 'WidgetStyleEditor', - template: '<div class="stub-style-editor" />', - props: ['placement', 'open'], -} - -const TileEditorStub = { - name: 'TileEditor', - template: '<div class="stub-tile-editor" />', - props: ['open', 'tile'], -} - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -/** - * Mount Views.vue with given inject overrides + optional activeDashboard in store. - * - * @param {object} options Options object - * @param {object} options.injectOverrides Values to inject (isAdmin, dashboardSource, etc.) - * @param {object|null} options.activeDashboard Active dashboard object (or null for empty state) - * @return {object} mounted wrapper - */ -async function mountViews({ - injectOverrides = {}, - activeDashboard = { id: 'dash-1', name: 'Test Dashboard', gridColumns: 12 }, -} = {}) { - const pinia = createPinia() - setActivePinia(pinia) - - // Lazy import so mocks are in place first - const { default: Views } = await import('../views/Views.vue') - - // Build store mocks via pinia store overrides - const { useDashboardStore } = await import('../stores/dashboard.js') - const { useWidgetStore } = await import('../stores/widgets.js') - const { useTileStore } = await import('../stores/tiles.js') - - const dashStore = useDashboardStore() - dashStore.activeDashboard = activeDashboard - dashStore.widgetPlacements = [] - dashStore.dashboards = activeDashboard ? [activeDashboard] : [] - dashStore.loadDashboards = vi.fn() - dashStore.switchDashboard = vi.fn() - dashStore.createDashboard = vi.fn() - dashStore.updatePlacements = vi.fn() - dashStore.addWidgetToDashboard = vi.fn() - dashStore.addTileToDashboard = vi.fn() - dashStore.removeWidgetFromDashboard = vi.fn() - dashStore.updateWidgetPlacement = vi.fn() - - const widgetStore = useWidgetStore() - widgetStore.availableWidgets = [] - widgetStore.loadAvailableWidgets = vi.fn() - - const tileStore = useTileStore() - tileStore.tiles = [] - tileStore.loadTiles = vi.fn() - tileStore.createTile = vi.fn() - tileStore.updateTile = vi.fn() - tileStore.deleteTile = vi.fn() - - const defaultInject = { - isAdmin: false, - dashboardSource: 'user', - allowUserDashboards: true, - primaryGroupName: '', - groupDashboards: [], - userDashboards: [], - } - - const inject = { ...defaultInject, ...injectOverrides } - - const wrapper = mount(Views, { - pinia, - provide: inject, - stubs: { - DashboardGrid: DashboardGridStub, - DashboardSwitcherSidebar: DashboardSwitcherSidebarStub, - SidebarBackdrop: SidebarBackdropStub, - WidgetPicker: WidgetPickerStub, - AddWidgetModal: AddWidgetModalStub, - WidgetStyleEditor: WidgetStyleEditorStub, - TileEditor: TileEditorStub, - // Stub icons to avoid MSVGI resolution issues - Close: { template: '<span />' }, - Cog: { template: '<span />' }, - Plus: { template: '<span />' }, - MenuIcon: { template: '<span />' }, - ViewDashboard: { template: '<span />' }, - ContentSave: { template: '<span />' }, - }, - mocks: { - t: (_app, key) => key, - }, - }) - - return wrapper -} - -// --------------------------------------------------------------------------- -// Tests — REQ-SHELL-002: canEdit gate -// --------------------------------------------------------------------------- - -describe('REQ-SHELL-002: canEdit gate', () => { - it('admin can edit any dashboard regardless of source', async () => { - const wrapper = await mountViews({ - injectOverrides: { isAdmin: true, dashboardSource: 'group' }, - }) - - expect(wrapper.vm.canEdit).toBe(true) - // Toolbar must be in DOM - expect(wrapper.find('.launchpad-toolbar').exists()).toBe(true) - }) - - it('non-admin with own personal dashboard (source=user) can edit', async () => { - const wrapper = await mountViews({ - injectOverrides: { isAdmin: false, dashboardSource: 'user' }, - }) - - expect(wrapper.vm.canEdit).toBe(true) - expect(wrapper.find('.launchpad-toolbar').exists()).toBe(true) - }) - - it('non-admin viewing group-shared dashboard cannot edit (toolbar absent)', async () => { - const wrapper = await mountViews({ - injectOverrides: { isAdmin: false, dashboardSource: 'group' }, - }) - - expect(wrapper.vm.canEdit).toBe(false) - // v-if must remove toolbar from DOM entirely (not just hide) - expect(wrapper.find('.launchpad-toolbar').exists()).toBe(false) - }) -}) - -// --------------------------------------------------------------------------- -// Tests — REQ-SHELL-004: Hamburger toggles sidebar -// --------------------------------------------------------------------------- - -describe('REQ-SHELL-004: Hamburger toggles sidebar', () => { - it('clicking the hamburger sets sidebarOpen=true', async () => { - const wrapper = await mountViews() - - expect(wrapper.vm.sidebarOpen).toBe(false) - - const hamburger = wrapper.find('.launchpad-hamburger') - await hamburger.trigger('click') - - expect(wrapper.vm.sidebarOpen).toBe(true) - }) - - it('clicking the hamburger again closes the sidebar', async () => { - const wrapper = await mountViews() - - const hamburger = wrapper.find('.launchpad-hamburger') - await hamburger.trigger('click') - expect(wrapper.vm.sidebarOpen).toBe(true) - - await hamburger.trigger('click') - expect(wrapper.vm.sidebarOpen).toBe(false) - }) - - it('active-dashboard name is shown in the label', async () => { - const wrapper = await mountViews({ - activeDashboard: { - id: 'dash-1', - name: 'Marketing Overview', - gridColumns: 12, - }, - }) - - expect(wrapper.find('.launchpad-active-dashboard-label').text()).toContain( - 'Marketing Overview', - ) - }) -}) - -// --------------------------------------------------------------------------- -// Tests — REQ-SHELL-005: Empty state -// --------------------------------------------------------------------------- - -describe('REQ-SHELL-005: Empty state', () => { - it('shows Create button when no dashboard + allowUserDashboards=true', async () => { - const wrapper = await mountViews({ - injectOverrides: { - allowUserDashboards: true, - isAdmin: false, - dashboardSource: 'group', - }, - activeDashboard: null, - }) - - // Grid stub must be absent - expect(wrapper.findComponent(DashboardGridStub).exists()).toBe(false) - // Empty state must render - expect(wrapper.find('.launchpad-empty').exists()).toBe(true) - // When allowUserDashboards=true, an NcButton should be present via v-if="#action" slot - // The NcButton stub renders with class="button-vue" — it appears somewhere in the tree. - // Because canEdit=false (isAdmin=false, dashboardSource='group'), toolbar is absent, - // so any NcButton in DOM must be the create action one. - const allNcButtons = wrapper.findAllComponents({ name: 'NcButton' }) - expect(allNcButtons.length).toBeGreaterThan(0) - }) - - it('shows no Create button when no dashboard + allowUserDashboards=false', async () => { - const wrapper = await mountViews({ - injectOverrides: { allowUserDashboards: false }, - activeDashboard: null, - }) - - expect(wrapper.find('.launchpad-empty').exists()).toBe(true) - // v-if="allowUserDashboards" is false — no NcButton should be inside the empty-state area - const ncButtonsInEmpty = wrapper - .find('.launchpad-empty') - .findAllComponents({ name: 'NcButton' }) - expect(ncButtonsInEmpty).toHaveLength(0) - }) - - it('shows DashboardGrid when active dashboard exists', async () => { - const wrapper = await mountViews({ - activeDashboard: { id: 'dash-1', name: 'My Board', gridColumns: 12 }, - }) - - expect(wrapper.findComponent(DashboardGridStub).exists()).toBe(true) - expect(wrapper.find('.launchpad-empty').exists()).toBe(false) - }) -}) - -// --------------------------------------------------------------------------- -// Tests — REQ-SHELL-003: Save Layout endpoint routing -// --------------------------------------------------------------------------- - -describe('REQ-SHELL-003: Save Layout', () => { - it('PUT to /api/dashboard/{id} for user source', async () => { - const { api } = await import('../services/api.js') - api.updateDashboard = vi.fn(() => Promise.resolve({ data: {} })) - - const wrapper = await mountViews({ - injectOverrides: { dashboardSource: 'user', isAdmin: false }, - activeDashboard: { id: 'abc-123', name: 'My Board', gridColumns: 12 }, - }) - - await wrapper.vm.saveLayout() - - expect(api.updateDashboard).toHaveBeenCalledWith( - 'abc-123', - expect.objectContaining({ layout: expect.any(Array) }), - ) - }) - - it('PUT to group endpoint for group source', async () => { - const { api } = await import('../services/api.js') - api.updateGroupDashboard = vi.fn(() => Promise.resolve({ data: {} })) - - const wrapper = await mountViews({ - injectOverrides: { dashboardSource: 'group', isAdmin: true }, - activeDashboard: { - id: 'abc-123', - name: 'Group Board', - gridColumns: 12, - groupId: 'grp-1', - uuid: 'uuid-001', - }, - }) - - await wrapper.vm.saveLayout() - - expect(api.updateGroupDashboard).toHaveBeenCalledWith( - 'grp-1', - 'uuid-001', - expect.objectContaining({ layout: expect.any(Array) }), - ) - }) - - it('saving flag is true while request is in-flight and no double-submit fires', async () => { - const { api } = await import('../services/api.js') - // Use a manually-controlled promise so the in-flight state persists - let resolveSave - api.updateDashboard = vi.fn( - () => - new Promise((resolve) => { - resolveSave = resolve - }), - ) - - const wrapper = await mountViews({ - injectOverrides: { isAdmin: true, dashboardSource: 'user' }, - activeDashboard: { id: 'dash-1', name: 'My Board', gridColumns: 12 }, - }) - - // Enter edit mode - await wrapper.vm.toggleEditMode() - - // First save call - wrapper.vm.saveLayout() // don't await — it's in-flight - expect(wrapper.vm.saving).toBe(true) - - // Second save call while in-flight — should be a no-op due to guard - const callsBefore = api.updateDashboard.mock.calls.length - await wrapper.vm.saveLayout() // this one awaits immediately (saving guard returns) - expect(api.updateDashboard.mock.calls.length).toBe(callsBefore) - - // Resolve the first save; saving should reset to false - resolveSave({ data: {} }) - await wrapper.vm.$nextTick() - expect(wrapper.vm.saving).toBe(false) - }) -}) - -// --------------------------------------------------------------------------- -// Tests — REQ-SHELL-007: Lifecycle hooks -// --------------------------------------------------------------------------- - -describe('REQ-SHELL-007: Lifecycle — document.click listener', () => { - beforeEach(() => { - vi.spyOn(document, 'addEventListener') - vi.spyOn(document, 'removeEventListener') - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('DashboardGrid registers document.click on mount and removes on destroy', async () => { - // DashboardGrid is stubbed — this test verifies the stub replaces the real component. - // The real DashboardGrid registers and removes the listener (already tested in DashboardGrid.vue). - // Here we verify Views.vue itself does NOT double-register listeners. - const wrapper = await mountViews() - - // Views.vue does not register its own document.click listener — DashboardGrid does it. - // So document.addEventListener should NOT be called by Views.vue directly. - // (The spec says Views should delegate to DashboardGrid's handler — which already happens.) - wrapper.destroy() - - // No double cleanup from Views.vue (DashboardGrid stub handles its own) - expect(true).toBe(true) // structural assertion: no crash on destroy - }) -}) diff --git a/src/__tests__/adminEntryLibraryCatalogue.spec.js b/src/__tests__/adminEntryLibraryCatalogue.spec.js new file mode 100644 index 000000000..e51fb4eed --- /dev/null +++ b/src/__tests__/adminEntryLibraryCatalogue.spec.js @@ -0,0 +1,21 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Every webpack entry that renders library components registers the library + * catalogue itself. The administration renders inside the main entry + * (src/main.js), so that call covers its shell chrome too. + */ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { describe, expect, it } from 'vitest' + +describe('the library catalogue', () => { + it.each(['main.js'])('is registered by src/%s', (entry) => { + const source = readFileSync(resolve(__dirname, '..', entry), 'utf8') + expect(source).toMatch( + /import\s*\{[^}]*\bregisterTranslations\b[^}]*\}\s*from\s*'@conduction\/nextcloud-vue'/, + ) + expect(source).toMatch(/^\s*registerTranslations\(\)/m) + }) +}) diff --git a/src/__tests__/axe-core-check.spec.js b/src/__tests__/axe-core-check.spec.js new file mode 100644 index 000000000..cf6a0f715 --- /dev/null +++ b/src/__tests__/axe-core-check.spec.js @@ -0,0 +1,116 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The embed render passes axe-core (embedded-analytics task 12). The embed + * page is rendered in each representative shape (a dashboard with chart, + * table, text, image, link and tile widgets, a single widget, a scope with + * interactions, the loading and the refusal state), axe-core runs over it, + * the findings are written to `docs/accessibility/axe-results.json`, and a + * serious or critical violation fails the run. `npm run build` runs this + * file through `npm run check:a11y`. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-12 + */ + +import { mount } from '@vue/test-utils' +import axe from 'axe-core' +import { mkdirSync, writeFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import { computed, nextTick, ref } from 'vue' +import EmbedView from '../views/EmbedView.vue' +import { classify, runAxe } from '../axe-core-check.js' + +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) + +const context = vi.hoisted(() => ({ current: null })) +vi.mock('../composables/useEmbedContext.js', () => ({ useEmbedContext: () => context.current })) + +const REPORT = resolve(__dirname, '../../docs/accessibility/axe-results.json') + +const READ = { mode: 'read', allowedActions: [], allowedFilters: [] } +const INTERACT = { mode: 'read-with-interactions', allowedActions: ['interact', 'drillDown'], allowedFilters: [] } + +const placement = (id, widgetId, extra = {}) => ({ id, widgetId, gridX: id, gridY: 0, gridWidth: 4, ...extra }) + +const DASHBOARD = [ + placement(1, 'chart', { customTitle: 'Requests per month' }), + placement(2, 'object-list', { customTitle: 'Open cases' }), + placement(3, 'header', { content: { text: 'Figures' } }), + placement(4, 'text', { customTitle: 'About', content: { text: 'Updated every night.' } }), + placement(5, 'image', { customTitle: 'Town hall', content: { url: 'https://www.example.com/hall.png' } }), + placement(6, 'link', { content: { url: 'https://www.example.com/report', label: 'Full report' } }), + placement(7, 'divider'), + placement(8, 'tile-mail', { tileType: 'app', tileTitle: 'Mail', tileLinkValue: '/apps/mail', tileIcon: '/apps/mail/img/mail.svg' }), +] + +const SHAPES = { + 'dashboard, read only': { scope: READ, payload: { dashboard: { name: 'City dashboard' }, placements: DASHBOARD } }, + 'dashboard, with interactions': { scope: INTERACT, payload: { dashboard: { name: 'City dashboard' }, placements: DASHBOARD } }, + 'widget: chart': { scope: READ, payload: { placements: [placement(1, 'chart', { customTitle: 'Requests per month' })] } }, + 'widget: table': { scope: READ, payload: { placements: [placement(2, 'object-list', { customTitle: 'Open cases' })] } }, + 'widget: text': { scope: READ, payload: { placements: [placement(4, 'text', { customTitle: 'About', content: { text: 'Updated every night.' } })] } }, + 'widget: image': { scope: READ, payload: { placements: [placement(5, 'image', { customTitle: 'Town hall', content: { url: 'https://www.example.com/hall.png' } })] } }, + 'widget: untitled image': { scope: READ, payload: { placements: [placement(5, 'image', { content: { url: 'https://www.example.com/hall.png' } })] } }, + 'widget: icon-only tile': { scope: INTERACT, payload: { placements: [placement(8, 'tile-mail', { tileType: 'app', tileLinkValue: '/apps/mail', tileIcon: '/apps/mail/img/mail.svg' })] } }, + loading: { scope: READ, loading: true, payload: null }, + refused: { scope: READ, error: { error: 'token_revoked' }, payload: null }, +} + +/** + * An embed context in the given state. + * + * @param {object} shape The shape: scope, payload, loading, error. + * @return {object} + */ +function embedContext(shape) { + const payload = ref(shape.payload) + return { + loading: ref(shape.loading === true), + error: ref(shape.error || null), + payload, + placements: computed(() => payload.value?.placements || []), + scope: computed(() => shape.scope), + filters: computed(() => ({})), + canRun: () => false, + relay: vi.fn(() => false), + start: () => () => {}, + } +} + +const report = {} +let wrapper = null + +describe('the embed render passes axe-core', () => { + beforeAll(() => { + // The base layout the embed page renders in sets both. + document.documentElement.lang = 'en' + document.title = 'Embed - LaunchPad' + }) + + afterEach(() => { + wrapper?.unmount() + wrapper = null + }) + + afterAll(() => { + mkdirSync(dirname(REPORT), { recursive: true }) + writeFileSync(REPORT, JSON.stringify({ axeVersion: axe.version, shapes: report }, null, '\t') + '\n') + }) + + it.each(Object.keys(SHAPES))('%s', async (name) => { + context.current = embedContext(SHAPES[name]) + wrapper = mount(EmbedView, { attachTo: document.body }) + await nextTick() + + const { failures, warnings } = classify(await runAxe(wrapper.element)) + report[name] = { failures, warnings } + if (warnings.length > 0) { + console.warn(`[axe] ${name}: ${warnings.map((warning) => `${warning.id} (${warning.impact})`).join(', ')}`) + } + + expect(failures, `serious or critical axe violations in "${name}"`).toEqual([]) + }) +}) diff --git a/src/__tests__/flowPageOptions.spec.js b/src/__tests__/flowPageOptions.spec.js new file mode 100644 index 000000000..c7f03acfd --- /dev/null +++ b/src/__tests__/flowPageOptions.spec.js @@ -0,0 +1,24 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The flow page turns on the Canvas / List switch (`config.listMode`) and the + * test run on an example payload (`config.testPayload`) of CnFlowEditorPage. + * Both are opt-in, so losing a key hides the screen without any error. + */ + +import { describe, expect, it } from 'vitest' +import manifest from '../manifest.json' + +const flowPages = manifest.pages.filter((page) => page.type === 'flow') + +describe('flow page options', () => { + it('declares a flow page', () => { + expect(flowPages.length).toBeGreaterThan(0) + }) + + it.each(flowPages.map((page) => [page.id, page]))('%s offers the list view and the payload test', (_id, page) => { + expect(page.config.listMode).toBe(true) + expect(page.config.testPayload).toBe(true) + }) +}) diff --git a/src/__tests__/flowPages.spec.js b/src/__tests__/flowPages.spec.js new file mode 100644 index 000000000..fae21e838 --- /dev/null +++ b/src/__tests__/flowPages.spec.js @@ -0,0 +1,43 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The flow pages use the canonical form: an index over the `flows` source whose + * rows open a page of type `flow`, on the addresses links already point at. + * + * @spec exclude Structural invariant of the shipped manifest; no behavioural spec. + */ +import * as fs from 'fs' +import * as path from 'path' +import { describe, expect, it } from 'vitest' +import { createMemoryHistory, createRouter } from 'vue-router' + +const { pages } = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../manifest.json'), 'utf8')) +const byId = new Map(pages.map((page) => [page.id, page])) +const router = createRouter({ + history: createMemoryHistory(), + routes: pages.map((page) => ({ name: page.id, path: page.route, component: {} })), +}) + +describe('flow pages', () => { + it('names no deprecated flow page type', () => { + expect(pages.filter((page) => ['flows', 'flow-detail'].includes(page.type)).map((page) => page.id)).toEqual([]) + }) + + it('Flows is an index over the flows source, scoped to this app', () => { + const { type, config } = byId.get('Flows') + expect(type).toBe('index') + expect(config.entitySource).toBe('flows') + expect(config.app).toBe('launchpad') + }) + + it('Flows opens its rows on a flow page', () => { + expect(byId.get(byId.get('Flows').config.rowRoute).type).toBe('flow') + }) + + it('keeps the flow addresses on the flow pages', () => { + expect(router.resolve('/flows').name).toBe('Flows') + expect(router.resolve('/flows/new').name).toBe('FlowDetail') + expect(router.resolve('/flows/abc').name).toBe('FlowDetail') + }) +}) diff --git a/src/__tests__/internalActions.test.js b/src/__tests__/internalActions.spec.js similarity index 100% rename from src/__tests__/internalActions.test.js rename to src/__tests__/internalActions.spec.js diff --git a/src/__tests__/l10nNoDuplicateKeys.spec.js b/src/__tests__/l10nNoDuplicateKeys.spec.js new file mode 100644 index 000000000..0854c4354 --- /dev/null +++ b/src/__tests__/l10nNoDuplicateKeys.spec.js @@ -0,0 +1,63 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * A key appears once in the Dutch catalogues. Parallel pull requests each + * appended the same key; git merged both lines without a conflict, and the + * LAST copy won at runtime. In nl.js that made "Set as default" read + * "Instellen als standaard" and "View mode" read "Weergave", while nl.json + * and the rest of the app said otherwise. JSON.parse and a JS object cannot + * see a duplicate, so this reads the raw text. Approach copied from + * nextcloud-vue tests/l10n/catalogueNoDuplicateKeys.spec.js. + */ +import { readFileSync } from 'fs' +import { join } from 'path' +import { describe, expect, it } from 'vitest' + +const DIR = join(__dirname, '../../l10n') + +/** + * The keys that occur more than once in one object of a JSON-shaped text. + * + * @param {string} text The raw object text. + * @return {string[]} The duplicated keys. + */ +function duplicateKeys(text) { + const duplicates = [] + const seenStack = [new Set()] + const re = /"((?:[^"\\]|\\.)*)"\s*:|[{}]/g + let match + while ((match = re.exec(text)) !== null) { + if (match[0] === '{') { + seenStack.push(new Set()) + } else if (match[0] === '}') { + seenStack.pop() + } else { + const seen = seenStack[seenStack.length - 1] + if (seen.has(match[1])) { + duplicates.push(match[1]) + } + seen.add(match[1]) + } + } + return duplicates +} + +describe('Dutch l10n catalogues', () => { + it('nl.json has no key twice', () => { + const text = readFileSync(join(DIR, 'nl.json'), 'utf8') + JSON.parse(text) + expect(duplicateKeys(text)).toEqual([]) + }) + + it('nl.js has no key twice', () => { + const text = readFileSync(join(DIR, 'nl.js'), 'utf8') + // The translations object: from the first "{" to the "}" before the plural rule. + const body = text.slice(text.indexOf('{'), text.lastIndexOf('},')) + expect(duplicateKeys(body)).toEqual([]) + }) + + it('finds a duplicate when there is one', () => { + expect(duplicateKeys('{"a": "1", "b": "2", "a": "3"}')).toEqual(['a']) + }) +}) diff --git a/src/__tests__/manifestNoBuildiqEdit.spec.js b/src/__tests__/manifestNoBuildiqEdit.spec.js new file mode 100644 index 000000000..791b332dd --- /dev/null +++ b/src/__tests__/manifestNoBuildiqEdit.spec.js @@ -0,0 +1,19 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Launchpad's page header holds only its own actions (design-system #1192, + * DEMO-SEED "No buildiq control"): the manifest opts out of the Buildiq + * in-app edit button that CnAppRoot adds where Buildiq is enabled. + * + * @spec openspec/changes/no-buildiq-edit-control/specs/runtime-shell/spec.md + */ + +import { describe, expect, it } from 'vitest' +import manifest from '../manifest.json' + +describe('the launchpad manifest', () => { + it('opts out of the Buildiq edit button', () => { + expect(manifest.openbuildEditable).toBe(false) + }) +}) diff --git a/src/__tests__/personalSettingsLocales.spec.js b/src/__tests__/personalSettingsLocales.spec.js new file mode 100644 index 000000000..f99c20527 --- /dev/null +++ b/src/__tests__/personalSettingsLocales.spec.js @@ -0,0 +1,81 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The personal settings dialog (summary email, hidden widgets) and the + * summary mail read in every shipped language: each locale's .json and .js + * catalogue carries every string, with its placeholders, and the plural line + * has one form per plural of the locale. + * + * @spec openspec/changes/archive/2026-11-25-personal-settings-dialog/specs/personal-settings/spec.md + */ + +import fs from 'fs' +import path from 'path' +import { describe, expect, it } from 'vitest' + +const PLURAL = '_You have hidden %n widget on shared dashboards_::_You have hidden %n widgets on shared dashboards_' +const KEYS = [ + 'Hidden widgets', + 'Your hidden widgets could not be loaded.', + 'You have not hidden any widgets on shared dashboards.', + PLURAL, + 'Show all again', + 'Your change could not be saved.', + 'Summary by email', + 'A mail with new announcements and what changed on your dashboards', + 'How often?', + 'Daily', + 'Weekly', + 'At 07:30, only when something changed', + 'On Monday at 07:30', + 'You have no email address, so no summary can be sent to you. Add one in your Nextcloud account.', + 'Your daily LaunchPad summary', + 'Your weekly LaunchPad summary', + 'Nothing new was published and nothing changed on your dashboards.', + 'New announcements', + 'What changed on your dashboards', + 'Open LaunchPad', + 'You get this mail because you asked for it in your LaunchPad settings.', +] + +const L10N = path.resolve(__dirname, '../../l10n') +const LOCALES = fs.readdirSync(L10N) + .filter((file) => /^[a-z]{2}(_[A-Z]{2})?\.json$/.test(file) && file !== 'en.json') + .map((file) => file.slice(0, -5)) + +/** + * Read a locale's .js catalogue the way Nextcloud registers it. + * + * @param {string} locale The locale. + * @return {{translations: object, nplurals: number}} + */ +function readJs(locale) { + let registered = null + const OC = { L10N: { register: (_app, translations, pluralForm) => { registered = { translations, pluralForm } } } } + new Function('OC', fs.readFileSync(path.join(L10N, `${locale}.js`), 'utf8'))(OC) + return { translations: registered.translations, nplurals: Number(/nplurals=(\d+)/.exec(registered.pluralForm)[1]) } +} + +const placeholders = (text) => [...text.matchAll(/%n|\{\w+\}/g)].map((m) => m[0]).sort() + +describe('Personal settings strings in every shipped locale', () => { + it('covers the shipped locales', () => { + expect(LOCALES.length).toBeGreaterThanOrEqual(36) + }) + + it.each(LOCALES)('%s translates every string in .json and .js', (locale) => { + const json = JSON.parse(fs.readFileSync(path.join(L10N, `${locale}.json`), 'utf8')).translations + const js = readJs(locale) + for (const catalogue of [json, js.translations]) { + for (const key of KEYS.filter((k) => k !== PLURAL)) { + expect(typeof catalogue[key], `${locale}: ${key}`).toBe('string') + expect(catalogue[key]).not.toBe('') + expect(placeholders(catalogue[key])).toEqual(placeholders(key)) + } + expect(Array.isArray(catalogue[PLURAL]), `${locale}: plural`).toBe(true) + expect(catalogue[PLURAL]).toHaveLength(js.nplurals) + catalogue[PLURAL].forEach((form) => expect(form).toContain('%n')) + } + }) +}) diff --git a/src/__tests__/smoke.test.js b/src/__tests__/smoke.test.js deleted file mode 100644 index 483f95775..000000000 --- a/src/__tests__/smoke.test.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - */ - -describe('vitest smoke test', () => { - it('runs and evaluates basic arithmetic', () => { - expect(1 + 1).toBe(2) - }) -}) diff --git a/src/__tests__/widgetBridge.test.js b/src/__tests__/widgetBridge.spec.js similarity index 100% rename from src/__tests__/widgetBridge.test.js rename to src/__tests__/widgetBridge.spec.js diff --git a/src/__tests__/workspaceTour.spec.js b/src/__tests__/workspaceTour.spec.js new file mode 100644 index 000000000..24c217878 --- /dev/null +++ b/src/__tests__/workspaceTour.spec.js @@ -0,0 +1,36 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * runtime-shell REQ-SHELL-010: the first-visit tour opens on the More menu, + * where the dashboards live (board LpEersteKeer). + */ + +import { describe, expect, it } from 'vitest' +import manifest from '../manifest.json' + +describe('the Workspace tour in src/manifest.json', () => { + const tour = manifest.walkthrough.tours.find((candidate) => candidate.id === 'launchpad:getting-started') + + it('rings the More menu at step 1 and says the dashboards are there', () => { + const [first] = tour.steps + expect(first.target).toEqual({ kind: 'element', ref: 'launchpad-more-menu' }) + expect(first.placement).not.toBe('center') + expect(first.title).toBe('Here you switch between dashboards') + expect(first.body).toMatch(/dashboards are under More/) + expect(first.advanceOn).toEqual({ type: 'manual' }) + }) + + it('is version 2, so a person who finished the side-bar tour sees the More tour once', () => { + expect(manifest.walkthrough.version).toBe(2) + expect(manifest.walkthrough.completionConfigKey).toBe('walkthrough_completed_version') + }) + + it('then asks to open Flows from More', () => { + expect(tour.steps.map((step) => step.id)).toEqual(['dashboards', 'more-menu']) + const second = tour.steps[1] + expect(second.target).toEqual({ kind: 'element', ref: 'launchpad-more-menu' }) + expect(second.advanceOn).toEqual({ type: 'route-match', route: 'Flows' }) + expect(second.allowManualNext).toBe(true) + }) +}) diff --git a/src/admin.js b/src/admin.js deleted file mode 100644 index 9ea2374ec..000000000 --- a/src/admin.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - * - * Admin entry point. Loads the typed initial-state contract via - * {@link loadInitialState} and exposes every key down the component tree - * via Vue 2's root `provide` option (REQ-INIT-003, REQ-INIT-004) — Vue 3 - * `app.provide(key, value)` semantics, achieved here through the root - * options bag because LaunchPad runs on Vue 2.7. - * - * Provided values are plain (non-reactive) snapshots (REQ-INIT-005). - */ - -import { translatePlural as n, translate as t } from '@nextcloud/l10n' -import { createPinia } from 'pinia' -import { createApp, h } from 'vue' -import AdminSettings from './components/admin/AdminSettings.vue' -// Install the OCA.Dashboard shim before anything else runs. Rendering this -// admin page calls WidgetService::getAvailableWidgets() server-side, which goes -// through NC's IManager::getWidgets() — and that loads every dashboard widget's -// bundle onto the page as a side effect. Those legacy bundles register at module -// top-level via OCA.Dashboard.register(), which only exists on /apps/dashboard -// (or wherever this bridge runs). Importing the bridge here mirrors the main -// workspace entry (where it loads via the widgets store) so the injected widget -// bundles find a register() to call instead of throwing on undefined OCA.Dashboard. -import { widgetBridge } from './services/widgetBridge.js' -import { loadInitialState } from './utils/loadInitialState.js' - -import './publicPath.js' - -// Reference the imported singleton so its side-effecting construction is not -// tree-shaken / flagged as an unused import. - -void widgetBridge - -// Vue 3 has no global Vue constructor — t/n are installed as an app-level -// mixin on the instance created below. -const pinia = createPinia() - -// Load the typed initial-state snapshot for the admin page (REQ-INIT-002). -// Plain (non-reactive) values; descendants `inject(key, default)` to read. -const initialState = loadInitialState('admin') - -const app = createApp({ - name: 'LaunchpadAdminRoot', - render: () => h(AdminSettings), -}) - -// Global t/n — an app-level mixin replaces Vue 2's global Vue.mixin. -app.mixin({ methods: { t, n } }) -app.use(pinia) - -// Vue 3 moves provide() off the component options onto the app instance, so -// each initial-state key is registered individually rather than as a -// `provide:` object. -for (const [key, value] of Object.entries(initialState)) { - app.provide(key, value) -} - -app.mount('#launchpad-admin-settings') - -export default app diff --git a/src/axe-core-check.js b/src/axe-core-check.js new file mode 100644 index 000000000..ef6d4c5bc --- /dev/null +++ b/src/axe-core-check.js @@ -0,0 +1,57 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The accessibility check of the embed render (embedded-analytics task 12): + * axe-core runs over a rendered element and its findings are sorted by + * impact. Serious and critical violations fail the check, moderate and minor + * ones are reported as warnings. + * + * jsdom has no layout, so axe reports colour contrast as incomplete rather + * than as a violation; contrast is covered by the tenant theme's 4.5:1 check + * (`TenantThemeValidator`). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-12 + */ + +import axe from 'axe-core' + +export const FAILING_IMPACTS = ['serious', 'critical'] + +export const RULE_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa', 'best-practice'] + +/** + * Run axe-core over an element of the current document. + * + * @param {Element} element The rendered element. + * @return {Promise<object>} The axe results. + * @spec openspec/changes/embedded-analytics/tasks.md#task-12 + */ +export function runAxe(element) { + return axe.run(element, { + runOnly: { type: 'tag', values: RULE_TAGS }, + resultTypes: ['violations'], + }) +} + +/** + * Sort axe violations into failures (serious, critical) and warnings + * (moderate, minor), each as `{id, impact, help, nodes}` with the offending + * nodes' selectors. + * + * @param {object} results The axe results. + * @return {{failures: Array<object>, warnings: Array<object>}} + * @spec openspec/changes/embedded-analytics/tasks.md#task-12 + */ +export function classify(results) { + const findings = (results.violations || []).map((violation) => ({ + id: violation.id, + impact: violation.impact || 'minor', + help: violation.help, + nodes: violation.nodes.map((node) => node.target.join(' ')), + })) + return { + failures: findings.filter((finding) => FAILING_IMPACTS.includes(finding.impact)), + warnings: findings.filter((finding) => !FAILING_IMPACTS.includes(finding.impact)), + } +} diff --git a/src/components/AcknowledgementPrompt.vue b/src/components/AcknowledgementPrompt.vue index dfc073add..09fd3b408 100644 --- a/src/components/AcknowledgementPrompt.vue +++ b/src/components/AcknowledgementPrompt.vue @@ -60,6 +60,7 @@ <script> import { NcButton } from '@conduction/nextcloud-vue' import { showError } from '@nextcloud/dialogs' +import { REQUIRED_OBJECT_PROP } from '../constants/propDefinitions.js' import { useDashboardStore } from '../stores/dashboard.js' export default { @@ -70,10 +71,7 @@ export default { }, props: { - placement: { - type: Object, - required: true, - }, + placement: REQUIRED_OBJECT_PROP, }, emits: ['acknowledged'], diff --git a/src/components/Announcements/AnnouncementCard.vue b/src/components/Announcements/AnnouncementCard.vue new file mode 100644 index 000000000..4a1b513a2 --- /dev/null +++ b/src/components/Announcements/AnnouncementCard.vue @@ -0,0 +1,238 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <article class="announcement-card" data-test="announcement-card"> + <header class="announcement-card__header"> + <span v-if="announcement.category" class="announcement-card__category">{{ announcement.category }}</span> + <time v-if="announcement.publishAt" class="announcement-card__date" :datetime="announcement.publishAt"> + {{ formattedDate }} + </time> + </header> + <h4 class="announcement-card__title"> + {{ announcement.title }} + </h4> + <p v-if="announcement.body" class="announcement-card__body"> + {{ announcement.body }} + </p> + <!-- REQ-ANN-007: the read confirmation, "I have read this" until the reader confirmed. --> + <div v-if="announcement.requiresConfirmation" class="announcement-card__confirmation" data-test="announcement-confirmation"> + <p v-if="confirmBeforeText" class="announcement-card__deadline" data-test="announcement-confirm-before"> + {{ confirmBeforeText }} + </p> + <p v-if="confirmed" class="announcement-card__confirmed" data-test="announcement-confirmed"> + <CheckCircle :size="18" /> + {{ t('launchpad', 'You confirmed you have read this') }} + </p> + <NcButton + v-else + variant="primary" + :disabled="preview" + data-test="announcement-confirm-read" + @click="$emit('confirmRead', announcement.uuid)"> + {{ t('launchpad', 'I have read this') }} + </NcButton> + <NcButton + v-if="canReport" + variant="tertiary" + data-test="announcement-receipts" + @click="$emit('openReceipts', announcement.uuid)"> + {{ t('launchpad', 'Read confirmations') }} + </NcButton> + </div> + <footer class="announcement-card__footer"> + <NcButton + variant="tertiary" + :pressed="reactions.liked" + :disabled="preview" + :aria-label="likeLabel" + data-test="announcement-like" + @click="$emit('toggleLike', announcement.uuid)"> + <template #icon> + <ThumbUp v-if="reactions.liked" :size="18" /> + <ThumbUpOutline v-else :size="18" /> + </template> + {{ reactions.likes }} + </NcButton> + <NcButton + variant="tertiary" + :disabled="preview" + :aria-label="commentLabel" + data-test="announcement-comments" + @click="$emit('openComments', announcement.uuid)"> + <template #icon> + <CommentOutline :size="18" /> + </template> + {{ reactions.comments }} + </NcButton> + </footer> + <slot /> + </article> +</template> + +<script> +import { getCanonicalLocale, n, t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' +import CheckCircle from 'vue-material-design-icons/CheckCircle.vue' +import CommentOutline from 'vue-material-design-icons/CommentOutline.vue' +import ThumbUp from 'vue-material-design-icons/ThumbUp.vue' +import ThumbUpOutline from 'vue-material-design-icons/ThumbUpOutline.vue' + +/** + * "Confirm before 30 October" in the reader's language, or '' without a + * deadline (REQ-ANN-007). + * + * @param {string|null} confirmBefore The deadline, ISO 8601. + * @param {string} [locale] BCP 47 locale. + * @return {string} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ +export function confirmBeforeLabel(confirmBefore, locale) { + const date = confirmBefore ? new Date(confirmBefore) : null + if (date === null || Number.isNaN(date.getTime())) { + return '' + } + return t('launchpad', 'Confirm before {date}', { date: date.toLocaleDateString(locale, { day: 'numeric', month: 'long' }) }) +} + +/** + * AnnouncementCard — one news announcement as readers see it in the + * Announcements widget, with its like and comment counts (REQ-ANN-002). The + * editor's preview renders this same component with `preview` set + * (REQ-ANN-004). An announcement that asks for a read confirmation shows + * "I have read this" until the reader confirmed, the date to confirm before, + * and, for its author, Read confirmations (REQ-ANN-007). + * + * @spec openspec/changes/engagement-announcements/specs/announcements/spec.md#requirement-readers-like-and-comment-through-nextcloud-comments-req-ann-002 + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ +export default { + name: 'AnnouncementCard', + + components: { CheckCircle, CommentOutline, NcButton, ThumbUp, ThumbUpOutline }, + + props: { + /** The announcement, as the announcements API returns it. */ + announcement: { + type: Object, + required: true, + }, + + /** `{likes, comments, liked}` for this announcement. */ + reactions: { + type: Object, + default: () => ({ likes: 0, comments: 0, liked: false }), + }, + + /** Rendered in the editor's preview: the buttons are inert. */ + preview: { + type: Boolean, + default: false, + }, + + /** Whether the reader already confirmed they have read it (REQ-ANN-007). */ + confirmed: { + type: Boolean, + default: false, + }, + + /** Whether the reader may open its read confirmations: its author or an administrator. */ + canReport: { + type: Boolean, + default: false, + }, + }, + + emits: ['toggleLike', 'openComments', 'confirmRead', 'openReceipts'], + + computed: { + /** @return {string} The publish date in the reader's locale. */ + formattedDate() { + const date = new Date(this.announcement.publishAt) + return Number.isNaN(date.getTime()) ? '' : date.toLocaleDateString() + }, + + /** + * @return {string} "Confirm before 30 October", or '' without a deadline. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + confirmBeforeText() { + return confirmBeforeLabel(this.announcement.confirmBefore, getCanonicalLocale()) + }, + + /** @return {string} */ + likeLabel() { + return this.reactions.liked + ? t('launchpad', 'Unlike {title}', { title: this.announcement.title }) + : t('launchpad', 'Like {title}', { title: this.announcement.title }) + }, + + /** @return {string} */ + commentLabel() { + return n('launchpad', '{count} comment', '{count} comments', this.reactions.comments, { count: this.reactions.comments }) + }, + }, + + methods: { + t, + }, +} +</script> + +<style scoped> +.announcement-card { + padding: 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); + background: var(--color-main-background); +} + +.announcement-card__header { + display: flex; + justify-content: space-between; + gap: 8px; + font-size: 12px; + color: var(--color-text-maxcontrast); +} + +.announcement-card__category { + font-weight: bold; +} + +.announcement-card__title { + margin: 4px 0; +} + +.announcement-card__body { + white-space: pre-line; +} + +.announcement-card__confirmation { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin: 8px 0; +} + +.announcement-card__deadline { + flex-basis: 100%; + margin: 0; + font-weight: bold; +} + +.announcement-card__confirmed { + display: flex; + align-items: center; + gap: 4px; + margin: 0; + color: var(--color-success-text, var(--color-success)); +} + +.announcement-card__footer { + display: flex; + gap: 4px; +} +</style> diff --git a/src/components/Announcements/NoticeBanner.vue b/src/components/Announcements/NoticeBanner.vue new file mode 100644 index 000000000..5f6023f5c --- /dev/null +++ b/src/components/Announcements/NoticeBanner.vue @@ -0,0 +1,133 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div + class="notice-banner" + :class="`notice-banner--${level}`" + :role="level === 'warning' ? 'alert' : 'status'" + data-test="notice-banner"> + <span class="notice-banner__icon" aria-hidden="true"> + <AlertOutline v-if="level === 'warning'" :size="20" /> + <InformationOutline v-else :size="20" /> + </span> + <div class="notice-banner__text"> + <span class="notice-banner__level hidden-visually">{{ levelLabel }}</span> + <strong class="notice-banner__title">{{ notice.title }}</strong> + <span v-if="notice.body" class="notice-banner__body">{{ notice.body }}</span> + </div> + <NcButton + v-if="notice.dismissible && !preview" + variant="tertiary" + :aria-label="t('launchpad', 'Dismiss notice')" + data-test="notice-dismiss" + @click="$emit('dismiss', notice.uuid)"> + <template #icon> + <Close :size="20" /> + </template> + </NcButton> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' +import AlertOutline from 'vue-material-design-icons/AlertOutline.vue' +import Close from 'vue-material-design-icons/Close.vue' +import InformationOutline from 'vue-material-design-icons/InformationOutline.vue' + +/** + * NoticeBanner — one notice above the dashboard grid (REQ-ANN-005). The + * level shows by icon and by text, not by colour alone; a dismissible notice + * has a close button, a non-dismissible one none. The editor's preview + * renders this same component with `preview` set. + * + * @spec openspec/changes/engagement-announcements/specs/announcements/spec.md#requirement-notices-show-above-every-targeted-dashboard-for-their-period-req-ann-005 + */ +export default { + name: 'NoticeBanner', + + components: { AlertOutline, Close, InformationOutline, NcButton }, + + props: { + /** The notice, as the announcements API returns it. */ + notice: { + type: Object, + required: true, + }, + + /** Rendered in the editor's preview: no dismiss button. */ + preview: { + type: Boolean, + default: false, + }, + }, + + emits: ['dismiss'], + + computed: { + /** @return {string} `warning` or `info`. */ + level() { + return this.notice.level === 'warning' ? 'warning' : 'info' + }, + + /** @return {string} The level as text. */ + levelLabel() { + return this.level === 'warning' ? t('launchpad', 'Warning') : t('launchpad', 'Information') + }, + }, + + methods: { t }, +} +</script> + +<style scoped> +/* LpIntranet: a full-width bar under the page header, title in bold and the + body beside it. */ +.notice-banner { + display: flex; + align-items: center; + gap: 10px 16px; + padding: 12px 28px; + background: var(--color-primary-element-light); + color: var(--color-primary-element-light-text); + font-size: 15px; +} + +.notice-banner--warning { + background: var(--color-primary-element-hover); + color: var(--color-primary-element-text); +} + +.notice-banner__icon { + display: flex; + flex: none; +} + +.notice-banner__text { + display: flex; + flex: 1; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 16px; + min-width: 0; +} + +.notice-banner__title { + font-weight: 600; +} + +.notice-banner__body { + flex: 1 1 260px; +} + +.notice-banner--warning .notice-banner__body { + color: var(--color-primary-element-light); +} + +.notice-banner--warning :deep(.button-vue) { + color: var(--color-primary-element-text); +} +</style> diff --git a/src/components/Announcements/NoticeBannerRegion.vue b/src/components/Announcements/NoticeBannerRegion.vue new file mode 100644 index 000000000..bf16dabd6 --- /dev/null +++ b/src/components/Announcements/NoticeBannerRegion.vue @@ -0,0 +1,125 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div v-if="visible.length > 0" class="notice-region" data-test="notice-region"> + <NoticeBanner + v-for="notice in visible" + :key="notice.uuid" + :notice="notice" + @dismiss="dismiss" /> + </div> +</template> + +<script> +import NoticeBanner from './NoticeBanner.vue' +import { announcementsApi } from '../../services/announcementsApi.js' +import { logger } from '../../utils/logger.js' + +/** How often the region re-checks end times, in milliseconds. */ +export const TICK_MS = 60000 + +/** + * NoticeBannerRegion — the notices that reach the reader, above the + * dashboard grid whichever dashboard is open (REQ-ANN-005, D1). The server + * already limits the list to the reader's notices inside their period; the + * region also drops a notice once its end time passes while the page stays + * open, and remembers dismissed notices in the reader's preferences. A + * non-dismissible notice has no close button and stays until its end time. + * + * @spec openspec/changes/engagement-announcements/specs/announcements/spec.md#requirement-notices-show-above-every-targeted-dashboard-for-their-period-req-ann-005 + */ +export default { + name: 'NoticeBannerRegion', + + components: { NoticeBanner }, + + data() { + return { + notices: [], + dismissed: [], + now: Date.now(), + timer: null, + } + }, + + computed: { + /** @return {Array<object>} The notices to show now. */ + visible() { + return this.notices.filter((notice) => { + const ends = Date.parse(notice.expiresAt ?? '') + if (!Number.isNaN(ends) && ends <= this.now) { + return false + } + return !(notice.dismissible && this.dismissed.includes(notice.uuid)) + }) + }, + }, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-9 */ + created() { + this.load() + this.timer = setInterval(() => { + this.now = Date.now() + }, TICK_MS) + }, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-9 */ + beforeUnmount() { + clearInterval(this.timer) + }, + + methods: { + /** @spec openspec/changes/engagement-announcements/tasks.md#task-9 */ + async load() { + // Both at once: the banner is often the largest paint of the page, + // and asking one after the other put a round trip before it. + const dismissed = announcementsApi.dismissedNotices().catch((error) => { + logger.error('Failed to load dismissed notices:', error) + return null + }) + try { + const data = await announcementsApi.list() + const all = Array.isArray(data.announcements) ? data.announcements : [] + this.notices = all.filter((item) => item.kind === 'notice') + } catch (error) { + logger.error('Failed to load notices:', error) + this.notices = [] + return + } + const ids = await dismissed + if (ids !== null) { + this.dismissed = ids + } + }, + + /** + * @param {string} uuid The notice. + * @spec openspec/changes/engagement-announcements/tasks.md#task-9 + */ + async dismiss(uuid) { + const notice = this.notices.find((item) => item.uuid === uuid) + if (!notice || !notice.dismissible) { + return + } + // Keep only the dismissed notices that are still live, so the preference stays small. + const live = new Set(this.notices.map((item) => item.uuid)) + this.dismissed = [...new Set([...this.dismissed.filter((id) => live.has(id)), uuid])] + try { + await announcementsApi.saveDismissedNotices(this.dismissed) + } catch (error) { + logger.error('Failed to save the dismissed notice:', error) + } + }, + }, +} +</script> + +<style scoped> +.notice-region { + display: flex; + flex-direction: column; +} +</style> diff --git a/src/components/Announcements/__tests__/announcements.spec.js b/src/components/Announcements/__tests__/announcements.spec.js new file mode 100644 index 000000000..cbd1f2c2f --- /dev/null +++ b/src/components/Announcements/__tests__/announcements.spec.js @@ -0,0 +1,652 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest for engagement-announcements: the Announcements widget (list, + * category filter, like and comment counts, comments, follow), the notice + * banner and its region (dismiss, non-dismissible, end time), and the editor + * modal (one dialog with a live preview, reach and "Preview as", one + * primary action that schedules or publishes). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import AnnouncementEditorModal, { confirmBeforeIso, confirmBeforeProblem, endTimeProblem, groupChoices, previewNoteText, toIso, visibleUntilText } from '../../../modals/AnnouncementEditorModal.vue' +import AnnouncementsWidget, { readConfirmationState } from '../../Widgets/Renderers/AnnouncementsWidget.vue' +import AnnouncementsWidgetForm from '../../Widgets/Renderers/AnnouncementsWidgetForm.vue' +import AnnouncementCard, { confirmBeforeLabel } from '../AnnouncementCard.vue' +import NoticeBanner from '../NoticeBanner.vue' +import NoticeBannerRegion, { TICK_MS } from '../NoticeBannerRegion.vue' +import { announcementsApi } from '../../../services/announcementsApi.js' +import { logger } from '../../../utils/logger.js' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), + translate: (_app, text) => text, + n: (_app, one, many, count, vars = {}) => (count === 1 ? one : many).replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), +})) +vi.mock('../../../services/announcementsApi.js', () => ({ + announcementsApi: { + list: vi.fn(), + like: vi.fn(), + unlike: vi.fn(), + comments: vi.fn(), + comment: vi.fn(), + follow: vi.fn(), + unfollow: vi.fn(), + create: vi.fn(), + update: vi.fn(), + publish: vi.fn(), + reach: vi.fn(), + reachFor: vi.fn(), + groups: vi.fn(), + confirmRead: vi.fn(), + readState: vi.fn(), + receipts: vi.fn(), + dismissedNotices: vi.fn(), + saveDismissedNotices: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +function field (name) { + return { + name, + props: ['modelValue', 'label', 'inputLabel', 'options'], + emits: ['update:modelValue'], + template: `<input class="${name}" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">`, +} +} +const stubs = { + NcButton: { + props: ['disabled', 'type'], + emits: ['click'], + template: '<button :type="type || \'button\'" :disabled="disabled" @click="$emit(\'click\')"><slot name="icon" /><slot /></button>', + }, + NcSelect: field('nc-select'), + NcTextField: field('nc-text-field'), + NcTextArea: field('nc-text-area'), + NcCheckboxRadioSwitch: { props: ['modelValue'], emits: ['update:modelValue'], template: '<label><slot /></label>' }, + NcModal: { emits: ['close'], template: '<div class="nc-modal-stub"><slot /></div>' }, + AcknowledgementReportModal: { name: 'AcknowledgementReportModal', props: ['open', 'announcementUuid', 'title'], template: '<div class="report-stub" />' }, +} +const mountWith = (component, props = {}) => mount(component, { props, global: { stubs } }) + +const NEWS = [ + { uuid: 'a', kind: 'news', title: 'Nieuwe werkplekken op de 3e verdieping', category: 'Facilitair', allowComments: true, publishAt: '2026-11-14T08:00:00Z' }, + { uuid: 'b', kind: 'news', title: 'Inloopspreekuur privacy', category: 'Privacy', allowComments: false, publishAt: '2026-11-13T08:00:00Z' }, + { uuid: 'n', kind: 'notice', title: 'Onderhoud zaaksysteem', level: 'warning', dismissible: false, expiresAt: '2099-01-01T00:00:00Z' }, +] + +beforeEach(() => { + vi.clearAllMocks() + announcementsApi.readState.mockResolvedValue({ confirmed: [], receipts: [] }) + announcementsApi.list.mockResolvedValue({ + announcements: NEWS, + reactions: { a: { likes: 0, comments: 0, liked: false } }, + followedCategories: [], + canAuthor: false, + }) +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('AnnouncementsWidget', () => { + it('lists the news, not the notices, and filters by category', async () => { + const wrapper = mountWith(AnnouncementsWidget) + await flushPromises() + + expect(wrapper.findAll('[data-test="announcement-card"]').map((card) => card.find('h4').text())) + .toEqual(['Nieuwe werkplekken op de 3e verdieping', 'Inloopspreekuur privacy']) + wrapper.vm.category = 'Privacy' + await flushPromises() + expect(wrapper.findAll('[data-test="announcement-card"]')).toHaveLength(1) + expect(wrapper.find('[data-test="announcements-new"]').exists()).toBe(false) + }) + + it('likes, then comments, and the counts follow', async () => { + announcementsApi.like.mockResolvedValue({ likes: 1, liked: true }) + announcementsApi.comments.mockResolvedValue([]) + announcementsApi.comment.mockResolvedValue({ id: '9', displayName: 'Pieter', message: 'Komen er ook sta-bureaus?' }) + const wrapper = mountWith(AnnouncementsWidget) + await flushPromises() + + await wrapper.find('[data-test="announcement-like"]').trigger('click') + await flushPromises() + expect(announcementsApi.like).toHaveBeenCalledWith('a') + expect(wrapper.find('[data-test="announcement-like"]').text()).toBe('1') + + await wrapper.find('[data-test="announcement-comments"]').trigger('click') + await flushPromises() + wrapper.vm.draftComment = 'Komen er ook sta-bureaus?' + await wrapper.vm.sendComment('a') + await flushPromises() + expect(announcementsApi.comment).toHaveBeenCalledWith('a', 'Komen er ook sta-bureaus?') + expect(wrapper.find('[data-test="announcement-comment-list"]').text()).toContain('Komen er ook sta-bureaus?') + expect(wrapper.find('[data-test="announcement-comments"]').text()).toBe('1') + }) + + it('a second click on like takes it back', async () => { + announcementsApi.list.mockResolvedValue({ announcements: [NEWS[0]], reactions: { a: { likes: 3, comments: 0, liked: true } } }) + announcementsApi.unlike.mockResolvedValue({ likes: 2, liked: false }) + const wrapper = mountWith(AnnouncementsWidget) + await flushPromises() + + await wrapper.vm.toggleLike('a') + expect(announcementsApi.unlike).toHaveBeenCalledWith('a') + expect(wrapper.vm.reactionsOf('a')).toEqual({ likes: 2, comments: 0, liked: false }) + }) + + it('follows and unfollows the chosen category', async () => { + announcementsApi.follow.mockResolvedValue(['Privacy']) + announcementsApi.unfollow.mockResolvedValue([]) + const wrapper = mountWith(AnnouncementsWidget, { content: { category: 'Privacy' } }) + await flushPromises() + + const button = () => wrapper.find('[data-test="announcements-follow"]') + expect(button().text()).toBe('Follow Privacy') + await button().trigger('click') + await flushPromises() + expect(announcementsApi.follow).toHaveBeenCalledWith('Privacy') + expect(button().text()).toBe('Unfollow Privacy') + await button().trigger('click') + await flushPromises() + expect(announcementsApi.unfollow).toHaveBeenCalledWith('Privacy') + }) + + it('shows the load error and offers authors a new announcement', async () => { + announcementsApi.list.mockRejectedValueOnce(new Error('x')) + const failed = mountWith(AnnouncementsWidget) + await flushPromises() + expect(failed.find('[role="alert"]').text()).toBe('Announcements could not be loaded') + + announcementsApi.list.mockResolvedValue({ announcements: [], canAuthor: true }) + const author = mountWith(AnnouncementsWidget) + await flushPromises() + expect(author.text()).toContain('No announcements') + await author.find('[data-test="announcements-new"]').trigger('click') + expect(author.find('[data-test="announcement-editor"]').exists()).toBe(true) + }) +}) + +describe('AnnouncementsWidgetForm', () => { + it('emits the category and a clamped limit', async () => { + const wrapper = mountWith(AnnouncementsWidgetForm, { editingWidget: { content: { category: 'Privacy', limit: 99 } } }) + expect(wrapper.vm.limit).toBe(50) + wrapper.vm.setLimit('0') + wrapper.vm.set('category', ' Facilitair ') + expect(wrapper.emitted('update:content')).toEqual([[{ category: 'Privacy', limit: 1 }], [{ category: 'Facilitair', limit: 1 }]]) + }) +}) + +describe('NoticeBanner', () => { + it('shows the level by icon and text, and a close button only when dismissible', () => { + const warning = mountWith(NoticeBanner, { notice: { uuid: 'n', title: 'Onderhoud', level: 'warning', dismissible: false } }) + expect(warning.attributes('role')).toBe('alert') + expect(warning.find('.notice-banner__level').text()).toBe('Warning') + expect(warning.find('[data-test="notice-dismiss"]').exists()).toBe(false) + + const info = mountWith(NoticeBanner, { notice: { uuid: 'i', title: 'Let op', level: 'info', dismissible: true } }) + expect(info.find('.notice-banner__level').text()).toBe('Information') + info.find('[data-test="notice-dismiss"]').trigger('click') + expect(info.emitted('dismiss')).toEqual([['i']]) + + const preview = mountWith(NoticeBanner, { notice: { uuid: 'i', title: 'Let op', dismissible: true }, preview: true }) + expect(preview.find('[data-test="notice-dismiss"]').exists()).toBe(false) + }) +}) + +describe('NoticeBannerRegion', () => { + it('shows the notices, hides dismissed dismissible ones, and drops one at its end time', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'Date'] }) + vi.setSystemTime(new Date('2026-11-13T18:00:00Z')) + announcementsApi.list.mockResolvedValue({ + announcements: [ + { uuid: 'w', kind: 'notice', title: 'Onderhoud zaaksysteem', level: 'warning', dismissible: false, expiresAt: '2026-11-14T12:00:00Z' }, + { uuid: 'd', kind: 'notice', title: 'Nieuwe printer', level: 'info', dismissible: true, expiresAt: '2026-11-20T00:00:00Z' }, + { uuid: 'x', kind: 'notice', title: 'Al weggeklikt', level: 'info', dismissible: true, expiresAt: '2026-11-20T00:00:00Z' }, + NEWS[0], + ], + }) + announcementsApi.dismissedNotices.mockResolvedValue(['x', 'w', 'gone']) + const wrapper = mountWith(NoticeBannerRegion) + await flushPromises() + + expect(wrapper.findAll('[data-test="notice-banner"]').map((b) => b.find('.notice-banner__title').text())) + .toEqual(['Onderhoud zaaksysteem', 'Nieuwe printer']) + + await wrapper.vm.dismiss('d') + await wrapper.vm.dismiss('w') + expect(announcementsApi.saveDismissedNotices).toHaveBeenCalledTimes(1) + expect(announcementsApi.saveDismissedNotices).toHaveBeenCalledWith(['x', 'w', 'd']) + expect(wrapper.findAll('[data-test="notice-banner"]')).toHaveLength(1) + + vi.setSystemTime(new Date('2026-11-14T12:01:00Z')) + vi.advanceTimersByTime(TICK_MS) + await flushPromises() + expect(wrapper.find('[data-test="notice-region"]').exists()).toBe(false) + wrapper.unmount() + }) + + it('asks for the notices and the dismissed ones at the same time', async () => { + let release + announcementsApi.list.mockReturnValue(new Promise((resolve) => { release = resolve })) + announcementsApi.dismissedNotices.mockResolvedValue([]) + const wrapper = mountWith(NoticeBannerRegion) + await flushPromises() + + expect(announcementsApi.dismissedNotices).toHaveBeenCalled() + release({ announcements: [] }) + await flushPromises() + wrapper.unmount() + }) + + it('still shows the notices when the dismissed list cannot be read', async () => { + announcementsApi.list.mockResolvedValue({ + announcements: [{ uuid: 'd', kind: 'notice', title: 'Nieuwe printer', level: 'info', dismissible: true }], + }) + announcementsApi.dismissedNotices.mockRejectedValue(new Error('preferences down')) + const wrapper = mountWith(NoticeBannerRegion) + await flushPromises() + + expect(wrapper.vm.dismissed).toEqual([]) + expect(wrapper.findAll('[data-test="notice-banner"]')).toHaveLength(1) + expect(logger.error).toHaveBeenCalledWith('Failed to load dismissed notices:', expect.any(Error)) + wrapper.unmount() + }) + + it('shows no region when the notices cannot be loaded, and keeps the old dismissed list', async () => { + announcementsApi.list.mockRejectedValue(new Error('server down')) + announcementsApi.dismissedNotices.mockResolvedValue(['d']) + const wrapper = mountWith(NoticeBannerRegion) + await flushPromises() + + expect(wrapper.find('[data-test="notice-region"]').exists()).toBe(false) + expect(wrapper.vm.notices).toEqual([]) + expect(wrapper.vm.dismissed).toEqual([]) + expect(logger.error).toHaveBeenCalledWith('Failed to load notices:', expect.any(Error)) + wrapper.unmount() + }) + + it('hides a dismissed notice even when saving the preference fails', async () => { + announcementsApi.list.mockResolvedValue({ + announcements: [{ uuid: 'd', kind: 'notice', title: 'Nieuwe printer', level: 'info', dismissible: true }], + }) + announcementsApi.dismissedNotices.mockResolvedValue([]) + announcementsApi.saveDismissedNotices.mockRejectedValue(new Error('save failed')) + const wrapper = mountWith(NoticeBannerRegion) + await flushPromises() + + await wrapper.vm.dismiss('d') + await flushPromises() + expect(wrapper.find('[data-test="notice-region"]').exists()).toBe(false) + expect(logger.error).toHaveBeenCalledWith('Failed to save the dismissed notice:', expect.any(Error)) + wrapper.unmount() + }) + + it('ignores a dismiss for an unknown notice', async () => { + announcementsApi.list.mockResolvedValue({ announcements: [] }) + announcementsApi.dismissedNotices.mockResolvedValue([]) + const wrapper = mountWith(NoticeBannerRegion) + await flushPromises() + + await wrapper.vm.dismiss('nope') + expect(announcementsApi.saveDismissedNotices).not.toHaveBeenCalled() + wrapper.unmount() + }) +}) + +describe('AnnouncementEditorModal', () => { + beforeEach(() => { + announcementsApi.groups.mockResolvedValue([{ id: 'burgerzaken', displayName: 'Burgerzaken' }]) + announcementsApi.reach.mockResolvedValue(4) + }) + + it('refuses a notice without an end time before any call', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + Object.assign(wrapper.vm.form, { kind: 'notice', title: 'Onderhoud zaaksysteem zaterdag 08:00 tot 12:00' }) + await wrapper.vm.submit() + + expect(wrapper.find('[data-test="editor-error"]').text()).toBe('Choose until when the announcement shows') + expect(announcementsApi.create).not.toHaveBeenCalled() + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md#requirement-authors-publish-targeted-announcements-req-ann-001 + it('requires "Show until" for news too, and explains it', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + const input = wrapper.find('[data-test="editor-expires-at"]') + expect(input.attributes('required')).toBeDefined() + expect(wrapper.text()).toContain('Show until') + expect(wrapper.find('[data-test="editor-show-until-hint"]').text()).toBe('After this time the announcement disappears from every dashboard.') + + wrapper.vm.form.title = 'Inloopspreekuur privacy' + await wrapper.vm.submit() + expect(wrapper.find('[data-test="editor-error"]').text()).toBe('Choose until when the announcement shows') + expect(announcementsApi.create).not.toHaveBeenCalled() + }) + + it('refuses an end time before the publish time', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + Object.assign(wrapper.vm.form, { title: 'Inloopspreekuur privacy', publishAt: '2099-11-02T08:00', expiresAt: '2099-11-01T17:00' }) + await wrapper.vm.submit() + expect(wrapper.find('[data-test="editor-error"]').text()).toBe('The end time must be after the publish time') + expect(announcementsApi.create).not.toHaveBeenCalled() + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + it('shows the form and "This is how it looks" side by side, the kind as two choice cards', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + await flushPromises() + + const columns = wrapper.find('.announcement-editor__columns') + expect(columns.find('[data-test="announcement-editor-form"]').exists()).toBe(true) + expect(columns.find('[data-test="editor-preview-pane"]').text()).toContain('This is how it looks') + expect(wrapper.findAll('[data-test="editor-kind"] input[type="radio"]').map((radio) => radio.element.value)).toEqual(['news', 'notice']) + expect(wrapper.find('[data-test="editor-kind-notice"]').text()).toContain('Maintenance notice') + expect(wrapper.find('[data-test="editor-kind-notice"]').text()).toContain('Shown at the top of every dashboard until the end time.') + expect(wrapper.find('[data-test="editor-kind-news"]').classes()).toContain('announcement-editor__kind--chosen') + + await wrapper.find('[data-test="editor-kind-notice"] input').setValue(true) + expect(wrapper.vm.form.kind).toBe('notice') + expect(wrapper.find('[data-test="notice-banner"]').exists()).toBe(true) + expect(wrapper.find('[data-test="announcement-card"]').exists()).toBe(false) + expect(wrapper.text()).not.toContain('Allow comments and following') + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + it('Write a news item: the preview shows the title at once, without saving', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + await flushPromises() + await wrapper.find('[data-test="editor-title"]').setValue('Nieuwe werkplekken op de 3e verdieping') + await wrapper.find('[data-test="editor-body"]').setValue('Vanaf maandag') + + const card = wrapper.find('[data-test="editor-preview-pane"] [data-test="announcement-card"]') + expect(card.find('h4').text()).toBe('Nieuwe werkplekken op de 3e verdieping') + expect(card.text()).toContain('Vanaf maandag') + expect(wrapper.text()).toContain('Allow comments and following') + expect(announcementsApi.create).not.toHaveBeenCalled() + expect(announcementsApi.update).not.toHaveBeenCalled() + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + it('offers the groups and counts the reach again when the target group changes', async () => { + announcementsApi.reach.mockResolvedValueOnce(120).mockResolvedValueOnce(42) + const wrapper = mountWith(AnnouncementEditorModal) + await flushPromises() + expect(wrapper.vm.groupOptions).toEqual([{ id: 'burgerzaken', displayName: 'Burgerzaken' }]) + expect(wrapper.find('[data-test="editor-reach"]').text()).toBe('Reaches 120 people') + + wrapper.vm.form.targetGroups = ['burgerzaken'] + await flushPromises() + expect(announcementsApi.reach).toHaveBeenLastCalledWith(['burgerzaken']) + expect(wrapper.find('[data-test="editor-reach"]').text()).toBe('Reaches 42 people') + }) + + it('keeps the preview working when the groups or reach cannot be loaded', async () => { + announcementsApi.groups.mockRejectedValueOnce(new Error('x')) + announcementsApi.reach.mockRejectedValueOnce(new Error('y')) + const wrapper = mountWith(AnnouncementEditorModal) + await flushPromises() + expect(wrapper.vm.groups).toEqual([]) + expect(wrapper.find('[data-test="editor-reach"]').text()).toBe('Reaches 0 people') + expect(logger.error).toHaveBeenCalledTimes(2) + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + it('says only the author sees the preview until the publication time', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + expect(wrapper.find('[data-test="editor-preview-note"]').text()).toBe('Only you see this preview until you publish the announcement.') + wrapper.vm.form.publishAt = '2099-11-02T08:00' + await wrapper.vm.$nextTick() + expect(wrapper.find('[data-test="editor-preview-note"]').text()).toMatch(/^Only you see this preview until .*November/) + }) + + it('names the end time in the preview and reads Schedule for a future publish time', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + Object.assign(wrapper.vm.form, { title: 'Inloopspreekuur privacy', publishAt: '2099-11-02T08:00', expiresAt: '2099-11-06T17:00' }) + await wrapper.vm.$nextTick() + const until = wrapper.find('[data-test="editor-visible-until"]').text() + expect(until.startsWith('Visible until ')).toBe(true) + expect(until).toMatch(/6/) + expect(until).toMatch(/November/) + expect(wrapper.find('[data-test="editor-publish"]').text()).toBe('Schedule') + expect(wrapper.find('[data-test="editor-cancel"]').text()).toBe('Cancel') + }) + + it('reads Publish when the publish time is empty or past', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + Object.assign(wrapper.vm.form, { title: 'Inloopspreekuur privacy', expiresAt: '2099-11-06T17:00' }) + await wrapper.vm.$nextTick() + expect(wrapper.find('[data-test="editor-publish"]').text()).toBe('Publish') + wrapper.vm.form.publishAt = '2020-01-01T08:00' + await wrapper.vm.$nextTick() + expect(wrapper.find('[data-test="editor-publish"]').text()).toBe('Publish') + }) + + it('Cancel closes without saving', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + await wrapper.find('[data-test="editor-cancel"]').trigger('click') + expect(wrapper.emitted('close')).toHaveLength(1) + expect(announcementsApi.create).not.toHaveBeenCalled() + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + it('saves and schedules a notice in one step, and checks "Preview as" before', async () => { + announcementsApi.create.mockResolvedValue({ uuid: 'u1' }) + announcementsApi.reachFor.mockResolvedValue({ reach: 42, reachesUser: false }) + announcementsApi.publish.mockResolvedValue({ uuid: 'u1', status: 'published' }) + const wrapper = mountWith(AnnouncementEditorModal) + Object.assign(wrapper.vm.form, { + kind: 'notice', + title: 'Onderhoud zaaksysteem zaterdag 08:00 tot 12:00', + targetGroups: ['Burgerzaken'], + level: 'warning', + dismissible: false, + publishAt: '2099-11-13T08:00', + expiresAt: '2099-11-14T12:00', + }) + await flushPromises() + + wrapper.vm.previewAs = 'sanne' + await wrapper.vm.checkPreviewAs() + await flushPromises() + expect(announcementsApi.reachFor).toHaveBeenCalledWith(['Burgerzaken'], 'sanne') + expect(wrapper.find('[data-test="editor-preview-as-answer"]').text()).toBe('sanne does not see this announcement') + + expect(wrapper.find('[data-test="editor-publish"]').text()).toBe('Schedule') + await wrapper.find('[data-test="editor-publish"]').trigger('click') + await flushPromises() + expect(announcementsApi.create).toHaveBeenCalledWith(expect.objectContaining({ + kind: 'notice', level: 'warning', dismissible: false, allowComments: false, targetGroups: ['Burgerzaken'], category: null, + publishAt: toIso('2099-11-13T08:00'), + })) + expect(announcementsApi.publish).toHaveBeenCalledWith('u1') + expect(wrapper.emitted('published')).toEqual([[{ uuid: 'u1', status: 'published' }]]) + }) + + it('shows the server refusal and updates the same announcement on a second try', async () => { + announcementsApi.create.mockResolvedValue({ uuid: 'u2' }) + announcementsApi.update.mockResolvedValue({ uuid: 'u2' }) + announcementsApi.publish.mockRejectedValueOnce({ response: { data: { message: 'The end time has already passed' } } }) + const wrapper = mountWith(AnnouncementEditorModal) + wrapper.vm.form.title = 'Nieuwe werkplekken op de 3e verdieping' + wrapper.vm.form.expiresAt = '2099-11-06T17:00' + await wrapper.vm.submit() + await flushPromises() + expect(wrapper.find('[data-test="editor-error"]').text()).toBe('The end time has already passed') + expect(wrapper.emitted('published')).toBeUndefined() + + announcementsApi.publish.mockResolvedValueOnce({ uuid: 'u2', status: 'published' }) + await wrapper.vm.submit() + await flushPromises() + expect(announcementsApi.create).toHaveBeenCalledTimes(1) + expect(announcementsApi.update).toHaveBeenCalledWith('u2', expect.objectContaining({ kind: 'news', allowComments: true, level: null })) + expect(wrapper.emitted('published')).toHaveLength(1) + }) + + it('does nothing without a title', async () => { + const wrapper = mountWith(AnnouncementEditorModal) + wrapper.vm.form.expiresAt = '2099-11-06T17:00' + await wrapper.vm.submit() + expect(announcementsApi.create).not.toHaveBeenCalled() + expect(wrapper.find('[data-test="editor-publish"]').attributes('disabled')).toBeDefined() + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + it('keeps chosen groups the list does not hold, and names the preview audience', () => { + expect(groupChoices([{ id: 'a', displayName: 'A' }], ['a', 'gone'])).toEqual([{ id: 'a', displayName: 'A' }, { id: 'gone', displayName: 'gone' }]) + expect(previewNoteText('', 'nl-NL')).toBe('Only you see this preview until you publish the announcement.') + expect(previewNoteText('2026-10-30T09:00', 'nl-NL')).toBe('Only you see this preview until 30 oktober 09:00.') + }) + + it('checks the end time against the publish time or now', () => { + const now = new Date('2026-10-29T12:00') + expect(endTimeProblem('', '', now)).toBe('Choose until when the announcement shows') + expect(endTimeProblem('', '2026-10-29T11:00', now)).toBe('The end time must be after the publish time') + expect(endTimeProblem('', '2026-10-30T17:00', now)).toBe('') + expect(endTimeProblem('2026-10-30T17:00', '2026-10-30T17:00', now)).toBe('The end time must be after the publish time') + expect(visibleUntilText('', 'nl-NL')).toBe('') + expect(visibleUntilText('2026-10-30T17:00', 'nl-NL')).toBe('30 oktober 17:00') + }) + + it('turns a datetime-local value into ISO, and empty into null', () => { + expect(toIso('')).toBeNull() + expect(toIso('nonsense')).toBeNull() + expect(toIso('2026-11-14T12:00')).toBe(new Date('2026-11-14T12:00').toISOString()) + }) +}) + +describe('Read confirmation (REQ-ANN-007)', () => { + const ASKING = { uuid: 'r', kind: 'news', title: 'New procedure', requiresConfirmation: true, confirmBefore: '2026-10-30T22:59:00Z', publishAt: '2026-10-26T08:00:00Z' } + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + it('Confirm before Friday: the card shows "I have read this" and the date, then that the reader confirmed', async () => { + const wrapper = mountWith(AnnouncementCard, { announcement: ASKING, canReport: true }) + expect(wrapper.find('[data-test="announcement-confirm-before"]').text()).toMatch(/^Confirm before .*30/) + await wrapper.find('[data-test="announcement-confirm-read"]').trigger('click') + expect(wrapper.emitted('confirmRead')).toEqual([['r']]) + await wrapper.find('[data-test="announcement-receipts"]').trigger('click') + expect(wrapper.emitted('openReceipts')).toEqual([['r']]) + + await wrapper.setProps({ confirmed: true, canReport: false }) + expect(wrapper.find('[data-test="announcement-confirm-read"]').exists()).toBe(false) + expect(wrapper.find('[data-test="announcement-confirmed"]').text()).toBe('You confirmed you have read this') + expect(wrapper.find('[data-test="announcement-receipts"]').exists()).toBe(false) + + const plain = mountWith(AnnouncementCard, { announcement: NEWS[0] }) + expect(plain.find('[data-test="announcement-confirmation"]').exists()).toBe(false) + expect(confirmBeforeLabel(null)).toBe('') + expect(confirmBeforeLabel('not a date')).toBe('') + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + it('the widget confirms, marks the card, and opens the read confirmations for the author', async () => { + announcementsApi.list.mockResolvedValue({ + announcements: [ASKING], + reactions: {}, + followedCategories: [], + canAuthor: true, + }) + announcementsApi.readState.mockResolvedValue({ confirmed: [], receipts: ['r'] }) + announcementsApi.confirmRead.mockResolvedValue({ uuid: 'r', confirmed: true }) + const wrapper = mountWith(AnnouncementsWidget) + await flushPromises() + + await wrapper.find('[data-test="announcement-confirm-read"]').trigger('click') + await flushPromises() + expect(announcementsApi.confirmRead).toHaveBeenCalledWith('r') + expect(wrapper.find('[data-test="announcement-confirmed"]').exists()).toBe(true) + + await wrapper.find('[data-test="announcement-receipts"]').trigger('click') + const report = wrapper.findComponent({ name: 'AcknowledgementReportModal' }) + expect(report.props()).toEqual({ open: true, announcementUuid: 'r', title: 'New procedure' }) + report.vm.$emit('close') + await flushPromises() + expect(wrapper.findComponent({ name: 'AcknowledgementReportModal' }).props('open')).toBe(false) + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + it('a failed confirmation says so and leaves the button', async () => { + announcementsApi.list.mockResolvedValue({ announcements: [ASKING], reactions: {}, followedCategories: [], canAuthor: false }) + announcementsApi.readState.mockRejectedValue(new Error('offline')) + announcementsApi.confirmRead.mockRejectedValue(new Error('offline')) + const wrapper = mountWith(AnnouncementsWidget) + await flushPromises() + // Without the read state the list still shows, every question unconfirmed. + expect(wrapper.find('[data-test="announcement-confirm-read"]').exists()).toBe(true) + expect(announcementsApi.list).toHaveBeenCalledTimes(1) + + await wrapper.vm.confirmRead('r') + expect(wrapper.vm.error).toBe('Your read confirmation could not be saved') + expect(wrapper.vm.readConfirmations.confirmed).toEqual([]) + expect(readConfirmationState({ confirmed: ['a', 5], receipts: 'x' })).toEqual({ confirmed: ['a'], receipts: [] }) + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + it('the form asks for it with a date, and the preview shows "I have read this" and "Confirm before"', async () => { + announcementsApi.groups.mockResolvedValue([]) + announcementsApi.reach.mockResolvedValue(4) + const wrapper = mountWith(AnnouncementEditorModal) + await flushPromises() + expect(wrapper.text()).toContain('Ask for read confirmation') + expect(wrapper.find('[data-test="editor-confirm-before"]').exists()).toBe(false) + expect(wrapper.vm.payload.requiresConfirmation).toBe(false) + expect(wrapper.vm.payload.confirmBefore).toBeNull() + + Object.assign(wrapper.vm.form, { title: 'New procedure', requiresConfirmation: true }) + await flushPromises() + await wrapper.find('[data-test="editor-confirm-before"]').setValue('2099-10-30') + + const preview = wrapper.find('[data-test="editor-preview-pane"]') + expect(preview.find('[data-test="announcement-confirm-read"]').text()).toBe('I have read this') + expect(preview.find('[data-test="announcement-confirm-read"]').attributes('disabled')).toBeDefined() + expect(preview.find('[data-test="announcement-confirm-before"]').text()).toMatch(/^Confirm before .*30/) + expect(wrapper.vm.payload.requiresConfirmation).toBe(true) + expect(wrapper.vm.payload.confirmBefore).toBe(toIso('2099-10-30T23:59')) + + wrapper.vm.form.kind = 'notice' + expect(wrapper.vm.payload.requiresConfirmation).toBe(false) + expect(wrapper.vm.payload.confirmBefore).toBeNull() + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + it('refuses a confirm-before date that is not after the publish time, before any call', async () => { + announcementsApi.groups.mockResolvedValue([]) + announcementsApi.reach.mockResolvedValue(4) + const wrapper = mountWith(AnnouncementEditorModal) + Object.assign(wrapper.vm.form, { + title: 'New procedure', + publishAt: '2099-11-02T08:00', + expiresAt: '2099-11-30T17:00', + requiresConfirmation: true, + confirmBefore: '2099-11-01', + }) + await wrapper.vm.submit() + + expect(wrapper.find('[data-test="editor-error"]').text()).toBe('The confirm-before date must be after the publish time') + expect(announcementsApi.create).not.toHaveBeenCalled() + + const now = new Date('2099-11-01T12:00:00Z') + expect(confirmBeforeProblem('', null, now)).toBe('') + expect(confirmBeforeProblem('', '2099-11-02T00:00:00Z', now)).toBe('') + expect(confirmBeforeProblem('', '2099-11-01T10:00:00Z', now)).toBe('The confirm-before date must be after the publish time') + expect(confirmBeforeIso('')).toBeNull() + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + it('sends the question and its deadline with the announcement', async () => { + announcementsApi.groups.mockResolvedValue([]) + announcementsApi.reach.mockResolvedValue(4) + announcementsApi.create.mockResolvedValue({ uuid: 'new' }) + announcementsApi.publish.mockResolvedValue({ uuid: 'new', status: 'published' }) + const wrapper = mountWith(AnnouncementEditorModal) + Object.assign(wrapper.vm.form, { title: 'New procedure', expiresAt: '2099-11-30T17:00', requiresConfirmation: true, confirmBefore: '2099-11-20' }) + await wrapper.vm.submit() + + expect(announcementsApi.create).toHaveBeenCalledWith(expect.objectContaining({ requiresConfirmation: true, confirmBefore: toIso('2099-11-20T23:59') })) + expect(wrapper.emitted('published')).toHaveLength(1) + }) +}) diff --git a/src/components/ChoiceCards.vue b/src/components/ChoiceCards.vue new file mode 100644 index 000000000..9a3b4655e --- /dev/null +++ b/src/components/ChoiceCards.vue @@ -0,0 +1,154 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div + class="choice-cards" + role="radiogroup" + :aria-labelledby="labelId"> + <span :id="labelId" class="choice-cards__legend">{{ label }}</span> + <div class="choice-cards__grid" :class="`choice-cards__grid--${columns}`"> + <label + v-for="option in options" + :key="option.value" + class="choice-cards__card" + :class="{ + 'choice-cards__card--chosen': modelValue === option.value, + 'choice-cards__card--disabled': option.disabled, + }" + :data-value="option.value"> + <input + class="choice-cards__input" + type="radio" + :name="name" + :value="option.value" + :checked="modelValue === option.value" + :disabled="option.disabled" + @change="$emit('update:modelValue', option.value)"> + <span class="choice-cards__title">{{ option.label }}</span> + <span v-if="option.hint" class="choice-cards__hint">{{ option.hint }}</span> + </label> + </div> + </div> +</template> + +<script> +import { LIST_PROP, TEXT_PROP } from '../constants/propDefinitions.js' + +let choiceCardsCounter = 0 + +/** + * ChoiceCards — one choice out of a few, drawn as cards with a title and one + * line of explanation (the boards' "keuzekaarten"). Native radio inputs keep + * the keyboard and the accessible names: each card is a radio named by its + * title and line, the group a radiogroup named by its label. + * + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + */ +export default { + name: 'ChoiceCards', + + props: { + /** The group's label. */ + label: TEXT_PROP, + + /** The radio group's name. */ + name: TEXT_PROP, + + /** The chosen value; '' when none is chosen. */ + modelValue: TEXT_PROP, + + /** `{value, label, hint?, disabled?}` per card. */ + options: LIST_PROP, + + /** Cards per row. */ + columns: { type: Number, default: 2 }, + }, + + emits: ['update:modelValue'], + + data() { + choiceCardsCounter += 1 + return { labelId: `choice-cards-${choiceCardsCounter}` } + }, +} +</script> + +<style scoped> +.choice-cards { + display: flex; + flex-direction: column; + gap: 6px; +} + +.choice-cards__legend { + font-weight: 600; + font-size: 14px; +} + +.choice-cards__grid { + display: grid; + gap: 8px; +} + +.choice-cards__grid--2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.choice-cards__grid--3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); +} + +.choice-cards__grid--4 { + grid-template-columns: repeat(4, minmax(0, 1fr)); +} + +@media (max-width: 600px) { + .choice-cards__grid--3, + .choice-cards__grid--4 { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +.choice-cards__card { + position: relative; + display: flex; + flex-direction: column; + gap: 2px; + padding: 10px 12px; + border: 2px solid var(--color-border); + border-radius: var(--border-radius-large); + cursor: pointer; +} + +.choice-cards__card--chosen { + border-color: var(--color-primary-element); +} + +.choice-cards__card--disabled { + cursor: not-allowed; + opacity: 0.5; +} + +.choice-cards__card:focus-within { + outline: 2px solid var(--color-main-text); + outline-offset: 2px; +} + +.choice-cards__input { + position: absolute; + opacity: 0; + pointer-events: none; +} + +.choice-cards__title { + font-weight: 600; +} + +.choice-cards__hint { + font-size: 12px; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/DashboardFooter.vue b/src/components/DashboardFooter.vue index 0901ef8e5..0e58be06f 100644 --- a/src/components/DashboardFooter.vue +++ b/src/components/DashboardFooter.vue @@ -88,10 +88,9 @@ * when `footer.html` or any structured-config field is a language map. * * Localisation (REQ-FTR-007): - * - Three-step fallback: viewer locale → first key → empty string. - * - The dashboard's primary-language fallback (step 2 of D3) is left - * to the parent that knows the dashboard context; this component - * ships locale + first-key for the read path. + * - Fallback: viewer locale (exact, then its language part) → the + * dashboard's primary language (`footer.primaryLanguage`, set by the + * server) → first key → empty string. * * Print stylesheet (REQ-FTR-008): the footer renders unchanged in * `@media print`; no `display: none` is applied. @@ -100,14 +99,14 @@ * admin colour overrides; when null the CSS falls through to the NC * theme variables (`--color-main-background`, `--color-main-text`). */ + +import { NULLABLE_OBJECT_PROP } from '../constants/propDefinitions.js' + export default { name: 'DashboardFooter', props: { - footer: { - type: Object, - default: null, - }, + footer: NULLABLE_OBJECT_PROP, locale: { type: String, @@ -237,10 +236,9 @@ export default { methods: { /** - * Locale fallback (REQ-FTR-007) — viewer locale → first key → - * empty string. The parent layer is responsible for inserting the - * dashboard primary-language fallback before this component sees - * the map. + * Locale fallback (REQ-FTR-007) — viewer locale, then its language + * part → the dashboard's primary language → first key → empty + * string. * * @param {Record<string, string>} map Locale-keyed variants. * @spec openspec/specs/footer-customization/spec.md @@ -249,8 +247,14 @@ export default { if (!map || typeof map !== 'object') { return '' } - if (Object.hasOwn(map, this.locale)) { - return map[this.locale] + const wanted = [ + this.locale, + String(this.locale).split(/[-_]/)[0], + this.footer?.primaryLanguage, + ] + const found = wanted.find((code) => code && Object.hasOwn(map, code)) + if (found) { + return map[found] } const keys = Object.keys(map) if (keys.length === 0) { diff --git a/src/components/HeaderSearchDropdown.vue b/src/components/HeaderSearchDropdown.vue new file mode 100644 index 000000000..8889d88f8 --- /dev/null +++ b/src/components/HeaderSearchDropdown.vue @@ -0,0 +1,620 @@ +<!-- SPDX-License-Identifier: EUPL-1.2 --> +<!-- SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> --> + +<template> + <Teleport to="body"> + <div + v-if="open" + class="lp-header-search" + data-testid="header-search-dropdown" + :style="panelStyle"> + <p class="lp-header-search__query" data-testid="header-search-query"> + {{ t('launchpad', 'You searched for {query}', { query: query.trim() }) }} + </p> + <ul + :id="listboxId" + class="lp-header-search__list" + role="listbox" + :aria-label="t('launchpad', 'Search results')"> + <template v-for="group in groups" :key="group.id"> + <li + class="lp-header-search__group" + role="presentation" + data-testid="header-search-group"> + {{ group.name.toLocaleUpperCase() }} + </li> + <li + v-for="result in group.results" + :id="optionId(result)" + :key="result.key" + role="option" + class="lp-header-search__option" + :class="{ 'lp-header-search__option--active': isActive(result) }" + :aria-selected="isActive(result) ? 'true' : 'false'" + data-testid="header-search-option" + @mousedown.prevent="choose(result)"> + <img + v-if="result.icon" + class="lp-header-search__icon" + :src="result.icon" + alt="" + aria-hidden="true"> + <span class="lp-header-search__text"> + <span class="lp-header-search__title">{{ result.title }}</span> + <span v-if="result.detail" class="lp-header-search__detail">{{ result.detail }}</span> + </span> + </li> + </template> + <li + v-if="!loading && groups.length === 0" + class="lp-header-search__empty" + role="presentation"> + {{ t('launchpad', 'No results') }} + </li> + <li + :id="optionId(showAllOption)" + role="option" + class="lp-header-search__option lp-header-search__show-all" + :class="{ 'lp-header-search__option--active': isActive(showAllOption) }" + :aria-selected="isActive(showAllOption) ? 'true' : 'false'" + data-testid="header-search-show-all" + @mousedown.prevent="choose(showAllOption)"> + {{ t('launchpad', 'Show all results') }} + </li> + </ul> + <p + v-if="shortcut" + class="lp-header-search__tip" + data-testid="header-search-tip"> + {{ t('launchpad', 'Tip: type {prefix} to search {name} directly', shortcut) }} + </p> + </div> + </Teleport> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { performFallback } from '../composables/useTileSearchHost.js' +import { LIST_PROP } from '../constants/propDefinitions.js' +import { + firstShortcut, + isSearchable, + moveSelection, + searchAll, +} from '../services/headerSearch.js' +import { + fieldWords, + removeInlineField, + resolveSearchField, +} from '../utils/headerSearchField.js' + +/** + * Nextcloud's top bar search field, across the core versions LaunchPad runs on. + * + * @type {string} + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export const CORE_SEARCH_FIELD_SELECTOR = '.unified-search-input, #unified-search input, .unified-search__input, input.unified-search-menu__input' + +/** Wait this long after the last keystroke before searching. */ +const DEBOUNCE_MS = 250 + +/** The key of the "Show all results" row. */ +const SHOW_ALL_KEY = 'show-all' + +let instanceCounter = 0 + +/** + * HeaderSearchDropdown: the results list under the top bar's search field + * on LaunchPad pages (header-search-dropdown, REQ-SRCH-013). + * + * The field belongs to Nextcloud core and its words to thematiq + * (`search-placeholder.js`). Where core's top bar has a field this component + * does not render or replace it; where it has only a button (Nextcloud 31+ + * on a desktop), it places a field in the button's place that shows the + * button's words (`utils/headerSearchField.js`). It finds the field, gives it the combobox attributes (WAI-ARIA 1.2: + * `role="combobox"`, `aria-expanded`, `aria-controls`, + * `aria-activedescendant`), listens to its input and keys, and draws a + * listbox under it. It never writes the field's `placeholder` or value. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export default { + name: 'HeaderSearchDropdown', + + props: { + /** + * The admin's search shortcuts `{prefix, name, urlTemplate}` + * (REQ-SPX-002); the first one gives the tip. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + shortcuts: LIST_PROP, + + /** + * The CSS selector of the field to attach to. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + fieldSelector: { + type: String, + default: CORE_SEARCH_FIELD_SELECTOR, + }, + }, + + data() { + instanceCounter += 1 + return { + field: null, + query: '', + groups: [], + loading: false, + open: false, + activeIndex: -1, + panelStyle: {}, + listboxId: `lp-header-search-${instanceCounter}`, + observer: null, + labelObserver: null, + timer: null, + controller: null, + } + }, + + computed: { + /** + * The "Show all results" row, as an option. + * + * @return {{key: string}} The row. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + showAllOption() { + return { key: SHOW_ALL_KEY } + }, + + /** + * Every selectable row in list order: the results, then "Show all". + * + * @return {Array<object>} The options. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + options() { + const results = this.groups.flatMap((group) => group.results) + return [...results, this.showAllOption] + }, + + /** + * The shortcut the tip names, or null. + * + * @return {{prefix: string, name: string}|null} The shortcut. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + shortcut() { + return firstShortcut(this.shortcuts) + }, + }, + + watch: { + /** + * Keep the field's combobox state in step with the list. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + open() { + this.syncFieldAria() + }, + + /** + * Keep `aria-activedescendant` on the selected row. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + activeIndex() { + this.syncFieldAria() + }, + }, + + /** + * Attach to the field, now or once the top bar renders it. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + mounted() { + if (!this.attach()) { + // The top bar can render after LaunchPad's bundle runs. + this.observer = new MutationObserver(() => { + if (this.attach()) { + this.observer.disconnect() + this.observer = null + } + }) + this.observer.observe(document.body, { childList: true, subtree: true }) + } + }, + + /** + * Let go of the field and cancel pending work. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + beforeUnmount() { + this.observer?.disconnect() + clearTimeout(this.timer) + this.controller?.abort() + this.detach() + }, + + methods: { + t, + + /** + * Find the field and bind to it. On Nextcloud 31+ the desktop top bar + * has only a button, so LaunchPad places its own field there + * (`resolveSearchField()`), following the button's words. + * + * @return {boolean} Whether the field was found. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + attach() { + const resolved = resolveSearchField( + document.querySelector(this.fieldSelector), + t('launchpad', 'Search'), + ) + if (!resolved) { + return false + } + const { field, created, label } = resolved + this.field = field + if (created && label) { + // thematiq can write its field words after LaunchPad mounts. + this.labelObserver = new MutationObserver(() => { + const words = fieldWords(label.parentElement, field.placeholder) + field.placeholder = words + field.setAttribute('aria-label', words) + }) + this.labelObserver.observe(label, { childList: true, characterData: true, subtree: true }) + } + field.setAttribute('role', 'combobox') + field.setAttribute('aria-autocomplete', 'list') + field.setAttribute('aria-controls', this.listboxId) + field.setAttribute('autocomplete', 'off') + field.addEventListener('input', this.onInput) + field.addEventListener('keydown', this.onKeydown) + field.addEventListener('blur', this.onBlur) + this.syncFieldAria() + return true + }, + + /** + * Unbind from the field. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + detach() { + const field = this.field + if (!field) { + return + } + field.removeEventListener('input', this.onInput) + field.removeEventListener('keydown', this.onKeydown) + field.removeEventListener('blur', this.onBlur) + field.removeAttribute('aria-activedescendant') + field.setAttribute('aria-expanded', 'false') + this.labelObserver?.disconnect() + this.labelObserver = null + removeInlineField(field) + this.field = null + }, + + /** + * Mirror the list's state on the field. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + syncFieldAria() { + const field = this.field + if (!field) { + return + } + field.setAttribute('aria-expanded', this.open ? 'true' : 'false') + const active = this.open ? this.options[this.activeIndex] : null + if (active) { + field.setAttribute('aria-activedescendant', this.optionId(active)) + } else { + field.removeAttribute('aria-activedescendant') + } + }, + + /** + * The DOM id of a row. + * + * @param {{key: string}} option The row. + * @return {string} The id. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + optionId(option) { + return `${this.listboxId}-${option.key}` + }, + + /** + * Whether a row is the selected one. + * + * @param {{key: string}} option The row. + * @return {boolean} True when selected. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + isActive(option) { + return this.options[this.activeIndex]?.key === option.key + }, + + /** + * The field changed: search after a short pause, or close under two + * characters. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + onInput() { + this.query = this.field?.value ?? '' + clearTimeout(this.timer) + if (!isSearchable(this.query)) { + this.close() + return + } + this.timer = setTimeout(() => this.search(), DEBOUNCE_MS) + }, + + /** + * Ask the providers and open the list with the first result selected. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + async search() { + this.controller?.abort() + const controller = new AbortController() + this.controller = controller + const query = this.query + this.loading = true + this.position() + this.open = true + const groups = await searchAll(query.trim(), { signal: controller.signal }) + if (controller.signal.aborted || query !== this.query) { + return + } + this.groups = groups + this.loading = false + this.activeIndex = 0 + this.syncFieldAria() + }, + + /** + * Place the panel under the field, as wide as the field. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + position() { + const rect = this.field?.getBoundingClientRect?.() + if (!rect) { + return + } + this.panelStyle = { + top: `${rect.bottom}px`, + left: `${rect.left}px`, + width: `${rect.width}px`, + } + }, + + /** + * Arrow keys move the selection, Enter opens it, Escape closes the + * list and keeps the query and the focus. + * + * @param {KeyboardEvent} event The key press on the field. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + onKeydown(event) { + if (!this.open) { + return + } + switch (event.key) { + case 'ArrowDown': + case 'ArrowUp': + event.preventDefault() + this.activeIndex = moveSelection( + this.activeIndex, + event.key === 'ArrowDown' ? 1 : -1, + this.options.length, + ) + break + case 'Enter': { + const option = this.options[this.activeIndex] + if (option) { + event.preventDefault() + event.stopPropagation() + this.choose(option) + } + break + } + case 'Escape': + event.preventDefault() + event.stopPropagation() + this.close() + break + default: + break + } + }, + + /** + * Close when the focus leaves the field (a row click is a mousedown + * with its default prevented, so it keeps the focus). + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + onBlur() { + this.close() + }, + + /** + * Open a result, or hand the query to Nextcloud's own search dialog. + * + * @param {{key: string, url?: string}} option The chosen row. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + choose(option) { + if (option.key === SHOW_ALL_KEY) { + const query = this.query.trim() + this.close() + performFallback({ type: 'unified-search', query }) + return + } + if (option.url) { + this.close() + window.location.assign(option.url) + } + }, + + /** + * Close the list. The field keeps its value and its focus. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + close() { + clearTimeout(this.timer) + this.controller?.abort() + this.controller = null + this.open = false + this.loading = false + this.activeIndex = -1 + }, + }, +} +</script> + +<style scoped> +.lp-header-search { + position: fixed; + z-index: 10000; + min-width: 280px; + max-height: 70vh; + overflow-y: auto; + margin-top: 4px; + padding: 8px 0; + background: var(--color-main-background); + color: var(--color-main-text); + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); + box-shadow: 0 4px 16px var(--color-box-shadow); +} + +.lp-header-search__query, +.lp-header-search__tip { + margin: 0; + padding: 6px 16px; + color: var(--color-text-maxcontrast); +} + +.lp-header-search__list { + margin: 0; + padding: 0; + list-style: none; +} + +.lp-header-search__group { + padding: 8px 16px 4px; + font-size: 0.8em; + font-weight: bold; + letter-spacing: 0.04em; + color: var(--color-text-maxcontrast); +} + +.lp-header-search__option { + display: flex; + gap: 12px; + align-items: center; + padding: 6px 16px; + cursor: pointer; +} + +.lp-header-search__option--active { + background: var(--color-primary-element-light); + outline: 2px solid var(--color-primary-element); + outline-offset: -2px; +} + +.lp-header-search__icon { + width: 24px; + height: 24px; + flex-shrink: 0; +} + +.lp-header-search__text { + display: flex; + flex-direction: column; + min-width: 0; +} + +.lp-header-search__title { + font-weight: bold; +} + +.lp-header-search__detail { + overflow: hidden; + color: var(--color-text-maxcontrast); + text-overflow: ellipsis; + white-space: nowrap; +} + +.lp-header-search__empty { + padding: 6px 16px; + color: var(--color-text-maxcontrast); +} + +.lp-header-search__show-all { + border-top: 1px solid var(--color-border); + margin-top: 4px; +} + +.lp-header-search__tip { + border-top: 1px solid var(--color-border); + font-size: 0.9em; +} +</style> + +<style> +/* LaunchPad's field in Nextcloud 31+'s top bar (utils/headerSearchField.js); unscoped: the top bar is core's DOM. + It takes the look of the core button it stands in for; the host has pointer-events: none in core. */ +.lp-header-search-host .unified-search-input__button { + display: none !important; +} + +.lp-header-search-host input.lp-header-search-field { + pointer-events: auto; + width: 100%; + height: calc(var(--default-clickable-area, 34px) - 8px); + min-height: 0; + margin: 0; + padding: 0 12px; + border: none; + border-radius: var(--border-radius-element, 8px); + background-color: rgba(0, 0, 0, 0.15); + backdrop-filter: var(--filter-background-blur); + box-shadow: inset 0 2px 0 rgba(0, 0, 0, 0.12); + color: var(--color-background-plain-text, #fff); + font: inherit; + text-align: start; +} + +.lp-header-search-host input.lp-header-search-field::placeholder { + color: color-mix(in srgb, var(--color-background-plain-text, #fff) 70%, var(--color-background-plain, #00679e)); + opacity: 1; +} + +.lp-header-search-host input.lp-header-search-field:hover, +.lp-header-search-host input.lp-header-search-field:focus { + background-color: rgba(0, 0, 0, 0.22); +} + +.lp-header-search-host input.lp-header-search-field:focus-visible { + outline: 2px solid var(--color-background-plain-text, #fff); + outline-offset: 2px; +} +</style> diff --git a/src/components/HealthPingBadge.vue b/src/components/HealthPingBadge.vue index 5bc6723b0..3442e5834 100644 --- a/src/components/HealthPingBadge.vue +++ b/src/components/HealthPingBadge.vue @@ -5,7 +5,7 @@ <template> <button - v-if="state" + v-if="state && !hidden" type="button" class="health-ping-badge" :class="badgeClass" @@ -74,15 +74,27 @@ export default { * * @type {number} */ + /** + * Poll and report the reading without drawing the badge: an + * icon-only tile shows its outage as a dot (REQ-ICT-003). + */ + hidden: { + type: Boolean, + default: false, + }, + interval: { type: Number, default: DEFAULT_INTERVAL_SECONDS, }, }, + emits: ['reading'], + data() { return { state: null, + downSince: null, checkedAt: null, latencyMs: null, stale: false, @@ -200,21 +212,42 @@ export default { } try { - const data = await fetchHealthPingBadge(this.placementId) - if (!data || data.error || !data.state) { - this.state = null - return - } - this.state = data.state - this.checkedAt = data.checkedAt ?? null - this.latencyMs = - data.latencyMs === null || data.latencyMs === undefined - ? null - : Number(data.latencyMs) - this.stale = Boolean(data.stale) + this.apply(await fetchHealthPingBadge(this.placementId)) } catch { this.state = null } + this.report() + }, + + /** + * Take a badge answer; one without a state hides the badge. + * + * @param {object|null} data The answer. + * @spec openspec/specs/service-health-ping/spec.md + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-an-outage-req-ict-003 + */ + apply(data) { + if (!data || data.error || !data.state) { + this.state = null + return + } + this.state = data.state + this.downSince = data.downSince ?? null + this.checkedAt = data.checkedAt ?? null + this.latencyMs = + data.latencyMs === null || data.latencyMs === undefined + ? null + : Number(data.latencyMs) + this.stale = Boolean(data.stale) + }, + + /** + * Tell the tile the reading: its state and since when it is offline. + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-an-outage-req-ict-003 + */ + report() { + this.$emit('reading', { state: this.state, downSince: this.state === 'offline' ? this.downSince : null }) }, }, } diff --git a/src/components/LazyMount.vue b/src/components/LazyMount.vue new file mode 100644 index 000000000..72cfe2859 --- /dev/null +++ b/src/components/LazyMount.vue @@ -0,0 +1,198 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<!-- + LazyMount — mounts its slot once the element comes within one viewport + height of the visible area, once the page has settled (SETTLE_DELAY_MS, + then the next idle moment), or when the page is about to print; whichever comes + first (widgets REQ-WDG-044). Until then it holds an empty box that fills + its parent, so the card around it keeps its place. Once mounted the slot + stays mounted. `eager`, and a browser without IntersectionObserver, mount + at once. +--> + +<template> + <div class="launchpad-lazy-mount" :data-mounted="shown ? 'true' : 'false'"> + <slot v-if="shown" /> + </div> +</template> + +<script> +import { FLAG_PROP } from '../constants/propDefinitions.js' + +/** How long a deferred slot leaves the widgets on screen to load first. */ +export const SETTLE_DELAY_MS = 2500 + +/** After that delay, the longest it waits for the browser to be idle. */ +export const IDLE_TIMEOUT_MS = 1000 + +/** How far ahead of the visible area a slot mounts: one viewport height. */ +export const ROOT_MARGIN = '100% 0px' + +/** + * The browser features LazyMount uses, behind one seam so tests can swap them. + * + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ +export const LazyMountSupport = { + /** + * The IntersectionObserver constructor, or null without one. + * + * @return {typeof IntersectionObserver|null} The constructor. + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + observer() { + return typeof window !== 'undefined' && typeof window.IntersectionObserver === 'function' + ? window.IntersectionObserver + : null + }, + + /** + * Run `callback` `delay` ms from now, at the browser's next idle moment + * after that (at most `timeout` ms later). + * + * @param {() => void} callback What to run. + * @param {number} delay The wait before looking for an idle moment, in ms. + * @param {number} timeout The longest wait for that idle moment, in ms. + * @return {() => void} Cancels the wait. + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + whenSettled(callback, delay, timeout) { + let idleHandle = null + const timer = window.setTimeout(() => { + if (typeof window.requestIdleCallback === 'function') { + idleHandle = window.requestIdleCallback(callback, { timeout }) + } else { + callback() + } + }, delay) + return () => { + window.clearTimeout(timer) + if (idleHandle !== null) { + window.cancelIdleCallback?.(idleHandle) + } + } + }, +} + +/** + * Mounts its slot when it is about to be seen. + * + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ +export default { + name: 'LazyMount', + + props: { + eager: FLAG_PROP, + }, + + data() { + return { + shown: this.eager === true || !LazyMountSupport.observer(), + } + }, + + watch: { + /** + * Becoming eager (for example entering edit mode) mounts at once. + * + * @param {boolean} value The new eager flag. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + eager(value) { + if (value === true) { + this.reveal() + } + }, + }, + + /** + * Watch the element, the idle moment and the print, unless already shown. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + mounted() { + if (this.shown) { + return + } + const Observer = LazyMountSupport.observer() + this.observer = new Observer(this.onIntersect, { rootMargin: ROOT_MARGIN }) + this.observer.observe(this.$el) + this.cancelIdle = LazyMountSupport.whenSettled(() => this.reveal(), SETTLE_DELAY_MS, IDLE_TIMEOUT_MS) + this.onBeforePrint = () => this.reveal() + window.addEventListener('beforeprint', this.onBeforePrint) + }, + + /** + * Stop watching. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + beforeUnmount() { + this.stopWatching() + }, + + methods: { + /** + * The observer reports the element within reach. + * + * @param {IntersectionObserverEntry[]} entries The observed entries. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + onIntersect(entries) { + if (entries.some((entry) => entry.isIntersecting)) { + this.reveal() + } + }, + + /** + * Mount the slot for good. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + reveal() { + this.shown = true + this.stopWatching() + }, + + /** + * Drop the observer, the idle callback and the print listener. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + stopWatching() { + this.observer?.disconnect() + this.observer = null + this.cancelIdle?.() + this.cancelIdle = null + if (this.onBeforePrint) { + window.removeEventListener('beforeprint', this.onBeforePrint) + this.onBeforePrint = null + } + }, + }, +} + +</script> + +<style scoped> +.launchpad-lazy-mount { + display: contents; +} + +.launchpad-lazy-mount[data-mounted='false'] { + display: block; + width: 100%; + height: 100%; + min-height: 24px; +} +</style> diff --git a/src/components/OrgNavigationItem.vue b/src/components/OrgNavigationItem.vue index edcf07ae5..8de9fcfc5 100644 --- a/src/components/OrgNavigationItem.vue +++ b/src/components/OrgNavigationItem.vue @@ -87,6 +87,7 @@ <script> import { CnDashboardIcon } from '@conduction/nextcloud-vue' +import { REQUIRED_OBJECT_PROP, TEXT_PROP } from '../constants/propDefinitions.js' import { normaliseIconValue } from '../services/iconCatalogue.js' /** @@ -101,7 +102,8 @@ import { normaliseIconValue } from '../services/iconCatalogue.js' * Active-item detection (REQ-ONAV-009) compares the node's `url` to * the panel-supplied `currentUrl` using prefix-or-equal semantics. * Sections that contain an active descendant auto-expand - * (`expanded = true` on mount when `hasActiveDescendant`). + * (`expanded = true` on mount, and again whenever `hasActiveDescendant` + * turns true, e.g. when the current URL settles after mounting). * * Icons (REQ-ONAV-006) render via the shared `CnDashboardIcon`, which * resolves any value the icon picker emits — a URL (→ `<img>`), an SVG @@ -115,20 +117,14 @@ export default { }, props: { - node: { - type: Object, - required: true, - }, + node: REQUIRED_OBJECT_PROP, level: { type: Number, default: 1, }, - currentUrl: { - type: String, - default: '', - }, + currentUrl: TEXT_PROP, }, emits: ['navigate'], @@ -190,6 +186,23 @@ export default { }, }, + watch: { + /** + * Open the section once a descendant becomes active (REQ-ONAV-009). + * The current URL can settle after the rail mounted (the workspace + * moves from the app root to the active dashboard's address), so the + * check in `mounted` alone left the section closed. + * + * @param {boolean} now Whether a descendant is active now. + * @spec openspec/specs/navigation-editor-org/spec.md + */ + hasActiveDescendant(now) { + if (now) { + this.expanded = true + } + }, + }, + /** @spec openspec/specs/navigation-editor-org/spec.md */ mounted() { // Auto-expand when a descendant is active (REQ-ONAV-009). diff --git a/src/components/OrgNavigationPanel.vue b/src/components/OrgNavigationPanel.vue index 611aa683a..6ff42f5bc 100644 --- a/src/components/OrgNavigationPanel.vue +++ b/src/components/OrgNavigationPanel.vue @@ -63,9 +63,9 @@ import { useOrgNavigationStore } from '../stores/orgNavigation.js' * - the position setting is 'hidden' (REQ-ONAV-004), OR * - the filtered tree is empty (REQ-ONAV-008). * - * On mount the component: - * - subscribes to the store and triggers `fetchTree()` + `fetchPosition()` - * - reads `window.location.pathname` to seed the active-item detection + * The workspace shell loads the tree and position into the store; on mount + * the component reads `window.location.pathname` to seed the active-item + * detection. * * Mobile/desktop affordances are CSS-driven (REQ-ONAV-010): a hamburger * button is visible below 800px and toggles `openDrawer`; the rail is @@ -114,9 +114,6 @@ export default { typeof window !== 'undefined' && window.location ? window.location.pathname : '' - // Fire-and-forget — errors are surfaced via store.error. - this.store.fetchPosition() - this.store.fetchTree() }, methods: { diff --git a/src/components/PublicDashboardGrid.vue b/src/components/PublicDashboardGrid.vue index 59ccf327b..3a9a6140c 100644 --- a/src/components/PublicDashboardGrid.vue +++ b/src/components/PublicDashboardGrid.vue @@ -4,22 +4,29 @@ --> <template> - <div class="public-dashboard-grid"> + <div + class="public-dashboard-grid" + :class="{ 'public-dashboard-grid--embed': embedContext !== null }" + :data-embed-mode="embedContext ? embedMode : undefined"> <div v-if="items.length > 0" class="public-share-view__grid"> <div v-for="item in items" :key="item.id" class="public-share-view__cell" - :style="{ gridColumn: 'span ' + Math.min(item.gridWidth, 12) }"> + :style="cellStyle(item)"> <!-- Tile — icon + label linking to its target. --> <a v-if="item.kind === 'tile'" class="public-share-view__tile" - :href="item.tileLink || '#'" + :href="tileHref(item)" + :target="embedContext ? '_blank' : undefined" + :rel="embedContext ? 'noopener noreferrer' : undefined" + :aria-label="item.title ? undefined : t('launchpad', 'Tile')" :style="{ backgroundColor: item.tileBackgroundColor || undefined, color: item.tileTextColor || undefined, - }"> + }" + @click="drillDown(item, $event)"> <img v-if=" item.tileIcon @@ -50,11 +57,24 @@ class="public-share-view__widget-heading"> {{ item.text || item.title }} </h3> - <p + <WeatherWidget + v-else-if="item.kind === 'weather'" + :content="placementOf(item).content || {}" + :placement="placementOf(item)" + :readingSource="readingSource" /> + <LiveTileWidget + v-else-if="item.kind === 'livetile'" + :content="placementOf(item).content || {}" + :placement="placementOf(item)" + :readingSource="readingSource" /> + <PublicNewsWidget + v-else-if="item.kind === 'announcements'" + :placementId="item.id" + :readWidget="readWidget" /> + <CnTextWidget v-else-if="item.kind === 'text'" - class="public-share-view__widget-text"> - {{ item.text }} - </p> + class="public-share-view__widget-text" + :content="textContent(item)" /> <img v-else-if="item.kind === 'image' && item.url" class="public-share-view__widget-image" @@ -84,28 +104,164 @@ </template> <script> +import { CnTextWidget } from '@conduction/nextcloud-vue' import { translate as t } from '@nextcloud/l10n' +import { defineAsyncComponent } from 'vue' +import { LIST_PROP } from '../constants/propDefinitions.js' + +// The live widgets load only when a shared dashboard has one, so a public +// page without them does not download their code (ADR-124). +const LiveTileWidget = defineAsyncComponent(() => import('./Widgets/Renderers/LiveTileWidget.vue')) +const PublicNewsWidget = defineAsyncComponent(() => import('./PublicNewsWidget.vue')) +const WeatherWidget = defineAsyncComponent(() => import('./Widgets/Renderers/WeatherWidget.vue')) + +const STATIC_WIDGET_KINDS = ['label', 'header', 'text', 'image', 'link', 'divider'] + +/** The live widgets that read their data through the link's or playlist's token (REQ-PSHR-011). */ +const LIVE_WIDGET_KINDS = ['announcements', 'weather', 'livetile'] + +/** + * A placement's content when it is an object, else an empty object. + * + * @param {object} p The placement. + * @return {object} The content. + */ +function placementContent(p) { + return p.content && typeof p.content === 'object' ? p.content : {} +} + +/** + * How a placement renders: a tile, one of the static widget kinds, a live + * widget when the grid can read it through a token, or restricted (only + * visible to signed-in users). + * + * @param {object} p The placement. + * @param {boolean} live Whether the grid has a token-scoped read. + * @return {string} The display kind. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +function placementKind(p, live) { + const widgetId = p.widgetId || '' + if (widgetId.startsWith('tile-') || p.tileType) { + return 'tile' + } + if (live && LIVE_WIDGET_KINDS.includes(widgetId)) { + return widgetId + } + return STATIC_WIDGET_KINDS.includes(widgetId) ? widgetId : 'restricted' +} + +/** + * The first non-empty value, else an empty string. + * + * @param {Array<string|undefined>} values The candidates, in order of preference. + * @return {string} The first non-empty value or ''. + */ +function firstFilled(values) { + return values.find(Boolean) || '' +} + +/** + * The tile look and link of a placement, with empty strings for unset values. + * + * @param {object} p The placement. + * @return {object} Icon, background and text colour, and link. + */ +function tileFields(p) { + return { + tileIcon: p.tileIcon || '', + tileBackgroundColor: p.tileBackgroundColor || '', + tileTextColor: p.tileTextColor || '', + tileLink: p.tileLinkValue || '', + } +} + +/** + * A placement normalised for display. + * + * @param {object} p The placement. + * @param {boolean} live Whether the grid has a token-scoped read. + * @return {object} The display item. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +function displayItem(p, live) { + const content = placementContent(p) + return { + id: p.id, + kind: placementKind(p, live), + gridX: Number.isFinite(Number(p.gridX)) ? Number(p.gridX) : null, + gridY: Number.isFinite(Number(p.gridY)) ? Number(p.gridY) : null, + gridWidth: p.gridWidth || 4, + gridHeight: p.gridHeight || 4, + title: firstFilled([ + p.customTitle, + p.tileTitle, + content.label, + content.title, + ]), + showTitle: p.showTitle !== 0 && p.showTitle !== false, + ...tileFields(p), + text: firstFilled([content.text, content.body]), + url: content.url || '', + } +} /** * PublicDashboardGrid: the read-only, anonymous-safe rendering of a * dashboard's placements. Tiles and static widgets (label, header, text, - * image, link, divider) render; any other widget shows that it is only - * visible to signed-in users. Shared by the public share page and the - * kiosk player. + * image, link, divider) render; a text widget renders through the + * dashboard's own CnTextWidget, so its Markdown shows as on the dashboard, + * sanitised (REQ-PSHR-012). With a token-scoped read (`readWidget`) the + * news, weather and live data widgets render with their data too + * (REQ-PSHR-011). Any other widget shows that it is only visible to + * signed-in users. Shared by the public share page and the kiosk player. * * @spec openspec/specs/dashboard-kiosk-mode/spec.md + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 */ export default { name: 'PublicDashboardGrid', + components: { CnTextWidget, LiveTileWidget, PublicNewsWidget, WeatherWidget }, + props: { - placements: { - type: Array, - default: () => [], + placements: LIST_PROP, + + /** + * embedded-analytics task 13: set when the grid renders inside an embed, + * `{scope: {mode, allowedActions}, filters}`. The tenant theme's `--c-*` + * variables then colour the tiles and widgets, a tile link opens outside + * the embed and only when the scope allows `interact`. Null (the + * default) is the normal public-share rendering, unchanged. + */ + embedContext: { + type: Object, + default: null, + }, + + /** + * The token-scoped read of a live widget: placement id to + * `{widget, data}` (REQ-PSHR-011). Set by the public share page and + * the kiosk player; without it (null, the default) the news, weather + * and live data widgets show that they need a sign-in. + */ + readWidget: { + type: Function, + default: null, }, }, + emits: ['drillDown'], + computed: { + /** + * @return {string} The embed's scope mode, read when unknown. + * @spec openspec/changes/embedded-analytics/tasks.md#task-13 + */ + embedMode() { + return this.embedContext?.scope?.mode === 'read-with-interactions' ? 'read-with-interactions' : 'read' + }, + /** * @return {Array<object>} Visible placements in reading order, normalised for display. * @spec openspec/specs/dashboard-kiosk-mode/spec.md @@ -115,55 +271,149 @@ export default { (p) => p.isVisible !== 0 && p.isVisible !== false, ) list.sort((a, b) => a.gridY - b.gridY || a.gridX - b.gridX) - return list.map((p) => { - const content = - p.content && typeof p.content === 'object' ? p.content : {} - const widgetId = p.widgetId || '' - const isTile = widgetId.startsWith('tile-') || !!p.tileType - let kind = 'restricted' - if (isTile) { - kind = 'tile' - } else if ( - ['label', 'header', 'text', 'image', 'link', 'divider'].includes( - widgetId, - ) - ) { - kind = widgetId - } - return { - id: p.id, - kind, - gridWidth: p.gridWidth || 4, - gridHeight: p.gridHeight || 4, - title: - p.customTitle - || p.tileTitle - || content.label - || content.title - || '', - showTitle: p.showTitle !== 0 && p.showTitle !== false, - tileIcon: p.tileIcon || '', - tileBackgroundColor: p.tileBackgroundColor || '', - tileTextColor: p.tileTextColor || '', - tileLink: p.tileLinkValue || '', - text: content.text || content.body || '', - url: content.url || '', - } - }) + const live = this.readWidget !== null + return list.map((p) => displayItem(p, live)) + }, + + /** + * The weather and live data widgets' reading source: the token-scoped + * read, answering the reading itself. + * + * @return {(function((number|string)): Promise<object>)|null} The reading source. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + readingSource() { + const read = this.readWidget + if (read === null) { + return null + } + return async (placementId) => (await read(placementId))?.data ?? {} }, }, methods: { t, + + /** + * The content a text widget renders with: the placement's own content, + * as the dashboard passes it to CnTextWidget (its Markdown or HTML, + * sanitised there); a legacy `body` stands in for a missing `text`. + * + * @param {object} item The display item. + * @return {object} The text widget's content. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-text-in-markdown-on-public-screens-req-pshr-012 + */ + textContent(item) { + const placement = this.placements.find((p) => p.id === item.id) + const content = placement ? placementContent(placement) : {} + return { ...content, text: item.text } + }, + + /** + * The placement a display item came from. + * + * @param {object} item The display item. + * @return {object} The placement. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + placementOf(item) { + return this.placements.find((p) => p.id === item.id) ?? { id: item.id } + }, + + /** + * Where a cell sits: at its column and row when the placement has + * them, so a narrow column beside a wide card stacks as on the + * dashboard (boards LpPubliek, LpKiosk); else it flows by its width. + * + * @param {object} item The display item. + * @return {object} The cell's grid style. + * @spec openspec/specs/dashboard-public-share/spec.md + */ + cellStyle(item) { + const width = Math.min(item.gridWidth, 12) + if (item.gridX === null || item.gridY === null) { + return { gridColumn: 'span ' + width } + } + return { + gridColumn: (Math.min(item.gridX, 11) + 1) + ' / span ' + width, + gridRow: (item.gridY + 1) + ' / span ' + item.gridHeight, + } + }, + + /** + * Where a tile links to: its target, '#' without one; inside an embed + * nowhere (no href) unless the scope allows `interact`, and '#' when it + * allows only `drillDown`, so the tile stays a focusable control. + * + * @param {object} item The display item. + * @return {string|undefined} + * @spec openspec/changes/embedded-analytics/tasks.md#task-13 + */ + tileHref(item) { + if (this.embedContext !== null && !this.embedAllows('interact')) { + return this.embedAllows('drillDown') ? '#' : undefined + } + return item.tileLink || '#' + }, + + /** + * Inside an embed whose scope allows `drillDown`, emit `drillDown` with + * what the visitor opened; without `interact` the link is not followed. + * + * @param {object} item The display item. + * @param {MouseEvent} event The click. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-006--js-sdk-exposes-render-event-and-resize-apis + */ + drillDown(item, event) { + if (this.embedContext === null || !this.embedAllows('drillDown')) { + return + } + if (!this.embedAllows('interact')) { + event.preventDefault() + } + this.$emit('drillDown', { + placementId: item.id, + title: item.title, + link: item.tileLink || null, + source: 'user-interaction', + }) + }, + + /** + * Whether the embed's scope allows an action. + * + * @param {string} action The action. + * @return {boolean} + * @spec openspec/changes/embedded-analytics/tasks.md#task-13 + */ + embedAllows(action) { + const scope = this.embedContext?.scope ?? {} + return scope.mode === 'read-with-interactions' && (scope.allowedActions ?? []).includes(action) + }, }, } </script> <style scoped> +/* embedded-analytics task 13: inside an embed the tenant theme's variables, + injected on :root by the embed page, colour the grid; without a theme + they fall back to the Nextcloud ones. */ +.public-dashboard-grid--embed .public-share-view__tile { + background: var(--c-primary, var(--color-primary-element)); +} + +.public-dashboard-grid--embed .public-share-view__widget { + border-color: var(--c-border, var(--color-border)); + background: var(--c-surface, var(--color-main-background)); + color: var(--c-text, var(--color-main-text)); +} + .public-share-view__grid { display: grid; - grid-template-columns: repeat(12, 1fr); - gap: 12px; + grid-template-columns: repeat(12, minmax(0, 1fr)); + grid-auto-rows: minmax(0, auto); + gap: 16px; + align-items: start; max-width: 1200px; } @@ -194,17 +444,18 @@ export default { } .public-share-view__widget { - height: 100%; - padding: 16px; + box-sizing: border-box; + padding: 18px 20px; border: 1px solid var(--color-border); - border-radius: var(--border-radius-large); + border-radius: 12px; background: var(--color-main-background); + font-size: 14px; } .public-share-view__widget-title { margin: 0 0 8px; - font-size: 1.05em; - font-weight: 700; + font-size: 18px !important; + font-weight: 700 !important; } .public-share-view__widget-heading { @@ -212,9 +463,11 @@ export default { font-weight: 700; } +/* The card already pads its content; the text widget's own inline padding + would double it. */ .public-share-view__widget-text { margin: 0; - white-space: pre-wrap; + padding: 0 !important; } .public-share-view__widget-image { diff --git a/src/components/PublicNewsWidget.vue b/src/components/PublicNewsWidget.vue new file mode 100644 index 000000000..80063d4da --- /dev/null +++ b/src/components/PublicNewsWidget.vue @@ -0,0 +1,153 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="public-news-widget" data-test="public-news-widget"> + <NcLoadingIcon v-if="loading" :size="24" /> + <p v-else-if="failed" class="public-news-widget__state"> + {{ t('launchpad', 'News is currently unavailable.') }} + </p> + <p v-else-if="items.length === 0" class="public-news-widget__state"> + {{ t('launchpad', 'No news yet.') }} + </p> + <ul v-else class="public-news-widget__list"> + <li + v-for="item in items" + :key="item.uuid" + class="public-news-widget__item" + data-test="public-news-item"> + <header class="public-news-widget__meta"> + <span v-if="item.category">{{ item.category }}</span> + <time v-if="item.publishAt" :datetime="item.publishAt"> + {{ formatDate(item.publishAt) }} + </time> + </header> + <h4 class="public-news-widget__title"> + {{ item.title }} + </h4> + <p v-if="item.body" class="public-news-widget__body"> + {{ item.body }} + </p> + </li> + </ul> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon' + +/** + * PublicNewsWidget: the news (announcements) widget as an anonymous + * visitor sees it on a public link or kiosk screen. It reads the + * published announcements for everyone through the token-scoped read and + * lists them read-only, without likes or comments (REQ-PSHR-011). + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +export default { + name: 'PublicNewsWidget', + + components: { NcLoadingIcon }, + + props: { + /** The placement id the read is for. */ + placementId: { + type: [Number, String], + required: true, + }, + + /** The token-scoped read: placement id to `{widget, data}`. */ + readWidget: { + type: Function, + required: true, + }, + }, + + data() { + return { + loading: true, + failed: false, + items: [], + } + }, + + mounted() { + this.load() + }, + + methods: { + t, + + /** + * Load the news items; a failed read shows that news is unavailable. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + async load() { + this.loading = true + this.failed = false + try { + const result = await this.readWidget(this.placementId) + const list = result?.data?.announcements + this.items = Array.isArray(list) ? list : [] + } catch { + this.items = [] + this.failed = true + } finally { + this.loading = false + } + }, + + /** + * A publish date in the visitor's locale. + * + * @param {string} value The ISO date. + * @return {string} The date, or '' when it does not parse. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + formatDate(value) { + const date = new Date(value) + return Number.isNaN(date.getTime()) ? '' : date.toLocaleDateString() + }, + }, +} +</script> + +<style scoped> +.public-news-widget__list { + margin: 0; + padding: 0; + list-style: none; +} + +.public-news-widget__item + .public-news-widget__item { + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid var(--color-border); +} + +.public-news-widget__meta { + display: flex; + gap: 8px; + color: var(--color-text-maxcontrast); + font-size: 12px; +} + +.public-news-widget__title { + margin: 4px 0 0; + font-weight: 700; +} + +.public-news-widget__body { + margin: 4px 0 0; +} + +.public-news-widget__state { + margin: 0; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/RuntimeShellSearch.vue b/src/components/RuntimeShellSearch.vue index 58b81237e..69254a65b 100644 --- a/src/components/RuntimeShellSearch.vue +++ b/src/components/RuntimeShellSearch.vue @@ -37,7 +37,7 @@ :id="listboxId" class="runtime-shell-search__results" role="listbox" - :aria-label="t('launchpad', 'Matching tiles')"> + :aria-label="listboxLabel"> <li v-for="(result, index) in search.state.results" :id="optionId(index)" @@ -64,7 +64,7 @@ index !== search.state.activeIndex, }" aria-hidden="true" /> - <span>{{ result.label }}</span> + <span>{{ resultLabel(result) }}</span> </li> </ul> @@ -99,6 +99,7 @@ import { isSlashFocusShortcut, useTileSearch, } from '../composables/useTileSearch.js' +import { LIST_PROP, TEXT_PROP } from '../constants/propDefinitions.js' let instanceCounter = 0 @@ -155,10 +156,7 @@ export default { * Re-filtered live whenever this changes (e.g. after a dashboard * switch or a placement add/remove). */ - items: { - type: Array, - default: () => [], - }, + items: LIST_PROP, /** * The `quicksearch_fallback_target` setting value: `'none'`, @@ -175,9 +173,14 @@ export default { * config form (REQ-QSEARCH-005). Empty string keeps the built-in * text, which advertises both focus shortcuts. */ - placeholder: { - type: String, - default: '', + placeholder: TEXT_PROP, + + /** + * The admin's search shortcuts `{prefix, name, urlTemplate}` (REQ-SPX-002). + */ + shortcuts: { + type: Array, + default: () => [], }, }, @@ -197,6 +200,7 @@ export default { this.$emit('fallback', action) }, getFallbackTarget: () => this.fallbackTarget, + getShortcuts: () => this.shortcuts, }), instanceId: `runtime-shell-search-${(instanceCounter += 1)}`, @@ -239,6 +243,22 @@ export default { * @spec openspec/specs/tile-quick-search/spec.md#req-qsearch-003 * @return {string|null} */ + /** + * Whether the results are shortcuts rather than tiles (REQ-SPX-002/003). + * + * @spec openspec/specs/tile-quick-search/spec.md + */ + showsShortcuts() { + return Boolean(this.search.state.results[0]?.kind) + }, + + /** @spec openspec/specs/tile-quick-search/spec.md */ + listboxLabel() { + return this.showsShortcuts + ? this.t('launchpad', 'Search shortcuts') + : this.t('launchpad', 'Matching tiles') + }, + ariaControls() { return this.hasResults ? this.listboxId : null }, @@ -290,6 +310,11 @@ export default { if (count === 0) { return this.noResultsMessage } + if (this.showsShortcuts) { + return this.search.state.results + .map((result) => this.resultLabel(result)) + .join(', ') + } return this.n( 'launchpad', '%n matching tile', @@ -329,6 +354,11 @@ export default { }, watch: { + /** @spec openspec/specs/tile-quick-search/spec.md */ + shortcuts() { + this.search.setItems(this.items) + }, + items: { immediate: true, /** @@ -376,6 +406,28 @@ export default { * @param {number} index the option's index in `results`. * @return {string} */ + /** + * The visible text of a result: a tile's label, a listed shortcut, + * or where a shortcut will search (REQ-SPX-002/003). + * + * @param {object} result A result from the composable. + * @return {string} The text. + * @spec openspec/specs/tile-quick-search/spec.md + */ + resultLabel(result) { + if (result.kind === 'shortcut') { + return result.rest + ? this.t('launchpad', 'Search {name} for {query}', { + name: result.shortcut.name, + query: result.rest, + }) + : this.t('launchpad', 'Type what to search for in {name}', { + name: result.shortcut.name, + }) + } + return result.label + }, + optionId(index) { return `${this.listboxId}-option-${index}` }, @@ -443,7 +495,8 @@ export default { */ emitFilter() { const query = this.search.state.query - if (!query) { + // A shortcut query is not a tile filter: no tile is dimmed. + if (!query || this.showsShortcuts) { this.$emit('filter', null) return } diff --git a/src/components/ScheduledExports/ExportOptionFields.vue b/src/components/ScheduledExports/ExportOptionFields.vue new file mode 100644 index 000000000..e4a9f1109 --- /dev/null +++ b/src/components/ScheduledExports/ExportOptionFields.vue @@ -0,0 +1,163 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="export-option-fields"> + <template v-for="field in fields" :key="field.key"> + <NcCheckboxRadioSwitch + v-if="field.kind === 'switch'" + type="switch" + :modelValue="values[field.key] === true" + :data-testid="`field-${field.key}`" + @update:modelValue="$emit('update', field.key, $event)"> + {{ field.label }} + </NcCheckboxRadioSwitch> + <NcSelect + v-else-if="field.kind === 'select'" + :inputLabel="field.label" + :options="field.options" + :modelValue="selectedOption(field)" + label="label" + :clearable="false" + :data-testid="`field-${field.key}`" + @update:modelValue="$emit('update', field.key, $event?.id)" /> + <NcPasswordField + v-else-if="field.kind === 'secret'" + :label="field.label" + :modelValue="values[field.key] ?? ''" + :helperText="secretHelp(field)" + autocomplete="new-password" + :data-testid="`field-${field.key}`" + @update:modelValue="$emit('update', field.key, $event)" /> + <NcTextArea + v-else-if="field.kind === 'textarea'" + :label="field.label" + :modelValue="values[field.key] ?? ''" + :helperText="field.help ?? ''" + :data-testid="`field-${field.key}`" + @update:modelValue="$emit('update', field.key, $event)" /> + <NcTextField + v-else + :label="field.label" + :type="field.type ?? 'text'" + :modelValue=" + values[field.key] === undefined || values[field.key] === null + ? '' + : String(values[field.key]) + " + :helperText="field.help ?? ''" + :data-testid="`field-${field.key}`" + @update:modelValue=" + $emit('update', field.key, toValue(field, $event)) + " /> + </template> + </div> +</template> + +<script> +import { + NcCheckboxRadioSwitch, + NcPasswordField, + NcSelect, + NcTextArea, + NcTextField, +} from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { LIST_PROP, OBJECT_PROP } from '../../constants/propDefinitions.js' + +/** What a stored secret reads as through the export API. */ +const REDACTED = '********' + +/** + * ExportOptionFields: a column of form fields described by data, for the + * format options of a render target and the channel settings of a + * recipient. Each field is `{key, label, kind, type?, options?, help?}` + * with kind `text`, `switch`, `select`, `secret` or `textarea`; a change + * is emitted as `update(key, value)` so the parent owns the values. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ +export default { + name: 'ExportOptionFields', + + components: { + NcCheckboxRadioSwitch, + NcPasswordField, + NcSelect, + NcTextArea, + NcTextField, + }, + + props: { + /** The fields, in order. */ + fields: LIST_PROP, + + /** The current values by field key. */ + values: OBJECT_PROP, + }, + + emits: ['update'], + + methods: { + t, + + /** + * The option of a select field that holds the current value. + * + * @param {object} field The field. + * @return {object|null} The option, or null. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + selectedOption(field) { + return ( + (field.options ?? []).find( + (option) => option.id === this.values[field.key], + ) ?? null + ) + }, + + /** + * A typed value: a number field gives a number (or null when empty). + * + * @param {object} field The field. + * @param {string} value What was typed. + * @return {string|number|null} The value to store. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + toValue(field, value) { + if (field.type !== 'number') { + return value + } + const number = Number.parseInt(value, 10) + return Number.isNaN(number) ? null : number + }, + + /** + * The helper line of a secret: a stored secret is kept when left as is. + * + * @param {object} field The field. + * @return {string} The helper text. + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-010-header-signing-and-credential-vaulting + */ + secretHelp(field) { + if (this.values[field.key] === REDACTED) { + return t( + 'launchpad', + 'Saved. Leave it as it is to keep it, or type a new one.', + ) + } + return field.help ?? '' + }, + }, +} +</script> + +<style scoped> +.export-option-fields { + display: flex; + flex-direction: column; + gap: 8px; +} +</style> diff --git a/src/components/ScheduledExports/ExportRunHistory.vue b/src/components/ScheduledExports/ExportRunHistory.vue new file mode 100644 index 000000000..1fd398350 --- /dev/null +++ b/src/components/ScheduledExports/ExportRunHistory.vue @@ -0,0 +1,252 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <section + class="export-runs" + data-testid="export-run-history" + aria-labelledby="export-runs-title"> + <div class="export-runs__head"> + <h3 id="export-runs-title"> + {{ + t('launchpad', 'Runs of {name}', { name: exportData.name ?? '' }) + }} + </h3> + <NcButton + variant="tertiary" + data-testid="export-runs-back" + @click="$emit('back')"> + <template #icon> + <ArrowLeft :size="20" /> + </template> + {{ t('launchpad', 'Back to the list') }} + </NcButton> + </div> + + <p + v-if="error" + class="export-runs__error" + role="alert" + data-testid="export-runs-error"> + {{ error }} + </p> + <CnDataTable + v-else + :columns="columns" + :rows="runs" + :loading="loading" + :emptyText="t('launchpad', 'This export has not run yet.')" + rowKey="id" + @rowClick="(row) => $emit('openRun', row)"> + <template #column-startedAt="{ row }"> + <button + type="button" + class="export-runs__open" + data-testid="export-run-open" + @click.stop="$emit('openRun', row)"> + {{ formatDateTime(row.startedAt) }} + </button> + </template> + <template #column-status="{ row }"> + <ExportStatus :status="row.status" /> + </template> + <template #column-triggeredBy="{ row }"> + {{ + row.triggeredBy === 'manual' + ? t('launchpad', 'By hand') + : t('launchpad', 'On schedule') + }} + </template> + <template #column-recipients="{ row }"> + {{ (row.deliveries ?? []).length }} + </template> + <template #column-outcome="{ row }"> + <span data-testid="export-run-outcome">{{ outcome(row) }}</span> + </template> + </CnDataTable> + </section> +</template> + +<script> +import { CnDataTable, NcButton } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import ArrowLeft from 'vue-material-design-icons/ArrowLeft.vue' +import ExportStatus from './ExportStatus.vue' +import { REQUIRED_OBJECT_PROP } from '../../constants/propDefinitions.js' +import { useExportsStore } from '../../stores/scheduledExports.js' +import { formatDateTime, serverMessage } from '../../utils/scheduledExports.js' + +/** + * ExportRunHistory: the past runs of one scheduled export, newest first, + * with when it fired, how it ended, who triggered it, how many recipients + * it had and how their deliveries went. A run opens its detail. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-14 + */ +export default { + name: 'ExportRunHistory', + + components: { + ArrowLeft, + CnDataTable, + ExportStatus, + NcButton, + }, + + props: { + /** The export whose runs are shown. */ + exportData: REQUIRED_OBJECT_PROP, + }, + + emits: ['back', 'openRun'], + + /** @spec openspec/changes/scheduled-exports/tasks.md#task-14 */ + data() { + return { + loading: false, + error: '', + } + }, + + computed: { + /** + * @return {object[]} The run-rows of this export, as the store holds them. + * @spec openspec/changes/scheduled-exports/tasks.md#task-14 + */ + runs() { + return useExportsStore().runsByExport[this.exportData.id] ?? [] + }, + + /** + * @return {object[]} The table columns. + * @spec openspec/changes/scheduled-exports/tasks.md#task-14 + */ + columns() { + return [ + { key: 'startedAt', label: t('launchpad', 'Started') }, + { key: 'status', label: t('launchpad', 'Status') }, + { key: 'triggeredBy', label: t('launchpad', 'Triggered') }, + { key: 'recipients', label: t('launchpad', 'Recipients') }, + { key: 'outcome', label: t('launchpad', 'Deliveries') }, + ] + }, + }, + + watch: { + 'exportData.id': { + immediate: true, + /** + * Load the runs of the export shown. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-14 + */ + handler() { + this.load() + }, + }, + }, + + methods: { + t, + formatDateTime, + + /** + * Read the run history. + * + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/tasks.md#task-14 + */ + async load() { + if (!this.exportData.id) { + return + } + this.loading = true + this.error = '' + try { + await useExportsStore().fetchRuns(this.exportData.id) + } catch (e) { + this.error = await serverMessage( + e, + t('launchpad', 'The runs could not be loaded.'), + ) + } finally { + this.loading = false + } + }, + + /** + * How the deliveries of a run went, counted by outcome. + * + * @param {object} run The run-row. + * @return {string} For example "Delivered: 2, failed: 1". + * @spec openspec/changes/scheduled-exports/tasks.md#task-14 + */ + outcome(run) { + const deliveries = run.deliveries ?? [] + if (run.skipReason && deliveries.length === 0) { + return t('launchpad', 'Skipped: {reason}', { + reason: run.skipReason, + }) + } + const count = (statuses) => + deliveries.filter((d) => statuses.includes(d.status)).length + const parts = [] + const delivered = count(['success']) + const failed = count(['failed-permanent']) + const waiting = count(['pending', 'retrying']) + if (delivered > 0) { + parts.push( + t('launchpad', 'delivered: {count}', { count: delivered }), + ) + } + if (failed > 0) { + parts.push(t('launchpad', 'failed: {count}', { count: failed })) + } + if (waiting > 0) { + parts.push(t('launchpad', 'waiting: {count}', { count: waiting })) + } + return parts.length > 0 + ? parts.join(', ') + : t('launchpad', 'No deliveries') + }, + }, +} +</script> + +<style scoped> +.export-runs { + display: flex; + flex-direction: column; + gap: 12px; +} + +.export-runs__head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.export-runs__head h3 { + margin: 0; + font-size: 1.1em; + font-weight: bold; +} + +.export-runs__open { + background: none; + border: 0; + padding: 0; + margin: 0; + min-height: auto; + color: var(--color-main-text); + text-decoration: underline; + cursor: pointer; +} + +.export-runs__error { + color: var(--color-error-text); +} +</style> diff --git a/src/components/ScheduledExports/ExportStatus.vue b/src/components/ScheduledExports/ExportStatus.vue new file mode 100644 index 000000000..520c617c2 --- /dev/null +++ b/src/components/ScheduledExports/ExportStatus.vue @@ -0,0 +1,108 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <span + class="export-status" + :class="`export-status--${tone}`" + :data-status="status || 'none'" + data-testid="export-status"> + <component :is="icon" :size="18" aria-hidden="true" /> + <span>{{ label }}</span> + </span> +</template> + +<script> +import AlertCircle from 'vue-material-design-icons/AlertCircle.vue' +import CheckCircle from 'vue-material-design-icons/CheckCircle.vue' +import CloseCircle from 'vue-material-design-icons/CloseCircle.vue' +import MinusCircleOutline from 'vue-material-design-icons/MinusCircleOutline.vue' +import ProgressClock from 'vue-material-design-icons/ProgressClock.vue' +import { TEXT_PROP } from '../../constants/propDefinitions.js' +import { statusLabel } from '../../utils/scheduledExports.js' + +/** + * ExportStatus: the status of a run or a delivery as an icon with its + * name beside it, so the meaning never rests on colour alone. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ +export default { + name: 'ExportStatus', + + props: { + /** running, success, partial, failed, pending, retrying, failed-permanent; empty for never run. */ + status: TEXT_PROP, + }, + + computed: { + /** + * @return {string} success, warning, error or neutral. + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + tone() { + if (this.status === 'success') { + return 'success' + } + if (['partial', 'retrying'].includes(this.status)) { + return 'warning' + } + if (['failed', 'failed-permanent'].includes(this.status)) { + return 'error' + } + return 'neutral' + }, + + /** + * @return {object} The icon component of the tone. + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + icon() { + if (['running', 'pending', 'retrying'].includes(this.status)) { + return ProgressClock + } + return ( + { + success: CheckCircle, + warning: AlertCircle, + error: CloseCircle, + }[this.tone] ?? MinusCircleOutline + ) + }, + + /** + * @return {string} The status name. + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + label() { + return statusLabel(this.status) + }, + }, +} +</script> + +<style scoped> +.export-status { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.export-status--success { + color: var(--color-success-text); +} + +.export-status--warning { + color: var(--color-warning-text); +} + +.export-status--error { + color: var(--color-error-text); +} + +.export-status--neutral { + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/TileWidget.vue b/src/components/TileWidget.vue index cfd65f44f..8d02fd233 100644 --- a/src/components/TileWidget.vue +++ b/src/components/TileWidget.vue @@ -7,9 +7,10 @@ <div v-if="tile" class="tile-widget" + :class="{ 'tile-widget--icon-only': iconOnly }" :data-tile-id="tile.id" :style="{ - '--tile-bg-color': tile.backgroundColor || '#0082c9', + '--tile-bg-color': backgroundCss, '--tile-text-color': tile.textColor || '#ffffff', }"> <!-- Shared edit cog in edit mode (Edit / Delete), matching the @@ -19,11 +20,20 @@ `position: relative` at equal specificity, so positioning the component directly loses the cascade tie and the cog drops into flow. Wrapping matches the shared nc-vue CnDashboardPage pattern. --> + <span + v-if="editMode" + class="tile-widget__grip" + aria-hidden="true" + data-testid="tile-drag-grip"> + <DragVertical :size="16" /> + </span> <div v-if="editMode" class="tile-widget__edit"> <CnWidgetEditCog + icon="kebab" :menuLabel="t('launchpad', 'Tile menu')" :editLabel="t('launchpad', 'Edit tile')" :deleteLabel="t('launchpad', 'Delete tile')" + :canDelete="!removeLocked" @edit="$emit('edit')" @remove="$emit('remove')" /> </div> @@ -33,12 +43,16 @@ <HealthPingBadge v-if="healthPingEnabled" :placementId="placementId" - :interval="pingInterval" /> + :interval="pingInterval" + :hidden="iconOnly" + @reading="onPingReading" /> <a :href="tileUrl" class="tile-widget__link" - :target="tile.linkType === 'url' ? '_blank' : '_self'" + :target="anchorTarget" + :title="iconOnly ? tile.title : null" + :aria-label="iconOnly ? accessibleName : null" rel="noopener noreferrer" @click="handleActivate"> <!-- SVG icon --> @@ -72,7 +86,28 @@ :size="64" :style="{ color: tile.textColor || '#ffffff' }" /> </div> + <!-- An icon-only tile marks itself as the app tiles do (LpVandaag): + a pin at the top left, a count or an outage dot at the top right. --> + <template v-if="iconOnly"> + <Pin + v-if="content?.pinned === true" + class="tile-widget__pin" + :size="14" + aria-hidden="true" + data-testid="tile-pin" /> + <span + v-if="pingDown" + class="tile-widget__outage" + aria-hidden="true" + data-testid="tile-outage" /> + <span + v-else-if="badgeText !== ''" + class="tile-widget__badge" + aria-hidden="true" + data-testid="tile-badge">{{ badgeText }}</span> + </template> <div + v-if="!iconOnly" class="tile-widget__title" :style="{ color: tile.textColor || '#ffffff', @@ -81,15 +116,49 @@ {{ tile.title }} </div> </a> + <!-- launcher-tile-launch-types D2: the browser cannot tell whether a + program started, so say what to check after the click. --> + <p + v-if="showProgramHint" + class="tile-widget__hint" + role="status"> + {{ t('launchpad', 'Nothing happened? The program may not be installed on this computer.') }} + </p> + + <!-- integrations-office-tiles REQ-OFT-002: a `create` tile asks for a + name and folder, then creates the file from the office app's own + blank template and opens it. --> + <OfficeFileDialog + v-if="isCreateTile" + :open="createDialogOpen" + :title="tile.title" + :defaultName="tile.title" + :busy="creating" + @update:open="createDialogOpen = $event" + @confirm="createFile" /> </div> </template> <script> import { CnDashboardIcon, CnWidgetEditCog } from '@conduction/nextcloud-vue' +import { getCurrentUser } from '@nextcloud/auth' +import { showError } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' import { generateUrl } from '@nextcloud/router' +import { defineAsyncComponent } from 'vue' +import DragVertical from 'vue-material-design-icons/DragVertical.vue' +import Pin from 'vue-material-design-icons/Pin.vue' import HealthPingBadge from './HealthPingBadge.vue' import { useTileClickTracking } from '../composables/useTileClickTracking.js' +import { FLAG_PROP, REQUIRED_OBJECT_PROP } from '../constants/propDefinitions.js' +import { api } from '../services/api.js' +import { COUNT_TTL_MS, countLabel, resolveTileCount, sourceType } from '../services/tileCount.js' +import { useTilePanelStore } from '../stores/tilePanel.js' +import { isOnOfficeNetwork } from '../utils/loadInitialState.js' import { logger } from '../utils/logger.js' +import { tileBackground } from '../utils/tileColour.js' +import { launchHref, launchTarget, LINK_PROGRAM } from '../utils/tileLaunch.js' +import { isSameOrigin, NEW_TAB, resolveLinkTarget, SIDE_PANEL } from '../utils/tileLinkTarget.js' const { recordTileClick } = useTileClickTracking() @@ -97,21 +166,22 @@ export default { name: 'TileWidget', components: { + Pin, + DragVertical, CnWidgetEditCog, CnDashboardIcon, HealthPingBadge, + // Loaded on first use: only a `create` office tile renders it. + OfficeFileDialog: defineAsyncComponent(() => import('../dialogs/OfficeFileDialog.vue').then((module) => module.default)), }, props: { - tile: { - type: Object, - required: true, - }, + tile: REQUIRED_OBJECT_PROP, - editMode: { - type: Boolean, - default: false, - }, + editMode: FLAG_PROP, + + /** The host refuses removing this tile, so the cog offers no Delete. */ + removeLocked: FLAG_PROP, /** * The widget placement id — forwarded to {@link HealthPingBadge} @@ -124,16 +194,24 @@ export default { default: null, }, + /** + * The placement's content blob; a remote-desktop tile keeps its + * gateway or RDP settings there (launcher-tile-launch-types). + * + * @type {object|null} + */ + content: { + type: Object, + default: null, + }, + /** * Whether this tile has a health ping configured * (REQ-HPING-004 "Ping disabled shows no badge"). * * @type {boolean} */ - healthPingEnabled: { - type: Boolean, - default: false, - }, + healthPingEnabled: FLAG_PROP, /** * The tile's configured ping interval in seconds. @@ -144,15 +222,176 @@ export default { type: Number, default: 60, }, + + /** + * The tile's own link target (`content.linkTarget`): `same-tab`, + * `new-tab` or `side-panel`, or null to follow the dashboard. + * + * @type {string|null} + */ + linkTarget: { + type: String, + default: null, + }, + + /** + * The dashboard's default link target, or null for the link-type rule. + * + * @type {string|null} + */ + defaultLinkTarget: { + type: String, + default: null, + }, }, emits: ['edit', 'remove'], + data() { + return { + showProgramHint: false, + createDialogOpen: false, + creating: false, + // REQ-ICT-002: the live count; null until the source answers. + count: null, + countTimer: null, + // REQ-ICT-003: the health ping's last reading. + pingDown: false, + pingDownSince: null, + } + }, + computed: { - /** @spec openspec/specs/tiles/spec.md */ + /** + * Whether the tile shows only its glyph, with the name as its tooltip + * and accessible name (the app tiles of LpVandaag and LpWerkplek). + * + * @return {boolean} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-a-tile-can-be-an-app-tile-with-only-its-icon-req-ict-001 + */ + iconOnly() { + return this.content?.iconOnly === true + }, + + /** + * The count on an icon-only tile, '' for none; above 99 it reads 99+. + * + * @return {string} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-a-tile-can-be-an-app-tile-with-only-its-icon-req-ict-001 + */ + badgeText() { + return countLabel(this.count) + }, + + /** + * The tile's background: its theme colour token, else its hex colour. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-the-tile-colour-is-one-of-eight-theme-colours-req-ict-004 + */ + backgroundCss() { + return tileBackground(this.tile, this.content) + }, + + /** + * The time the outage began, in the viewer's clock, or ''. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-an-outage-req-ict-003 + */ + downSinceText() { + const date = this.pingDownSince ? new Date(this.pingDownSince) : null + if (!date || Number.isNaN(date.getTime())) { + return '' + } + return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + }, + + /** + * The tile's name with its outage, count and pin, for a reader that + * cannot see the marks. + * + * @return {string} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-a-tile-can-be-an-app-tile-with-only-its-icon-req-ict-001 + */ + accessibleName() { + let name = this.tile.title + if (this.pingDown) { + name = this.downSinceText === '' + ? t('launchpad', '{app}, outage', { app: name }) + : t('launchpad', '{app}, outage since {time}', { app: name, time: this.downSinceText }) + } else if (this.badgeText !== '') { + name = t('launchpad', '{app}, {count} open', { app: name, count: this.badgeText }) + } + return this.content?.pinned === true ? t('launchpad', '{app}, pinned', { app: name }) : name + }, + + /** + * How this tile opens: its own target, the dashboard default, or the + * link-type rule (launcher-tile-open-behaviour D2). + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + resolvedTarget() { + return resolveLinkTarget(this.linkTarget, this.defaultLinkTarget, this.tile.linkType) + }, + + /** + * The anchor's `target`: a launch type's own target first + * (launcher-tile-launch-types D2), else the resolved open-in target. A + * `side-panel` tile keeps `_self` so that, if + * the panel cannot take it, a plain click still navigates somewhere; + * handleActivate() opens the panel instead. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + anchorTarget() { + return launchTarget(this.tile, this.content) ?? (this.resolvedTarget === NEW_TAB ? '_blank' : '_self') + }, + + /** + * Whether the tile creates a file instead of opening a link (REQ-OFT-002). + * + * @return {boolean} True for a `create` tile. + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + isCreateTile() { + return this.tile.linkType === 'create' + }, + + /** + * Whether this tile opens its office-network address: only when the + * server saw the request come from an office network and the tile has one. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ + opensInternalUrl() { + return typeof this.tile.internalUrl === 'string' + && this.tile.internalUrl !== '' + && isOnOfficeNetwork() + }, + + /** + * @spec openspec/specs/tiles/spec.md + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-5 + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ tileUrl() { - const value = this.tile.linkValue - if (this.tile.linkType === 'app') { + const launch = launchHref(this.tile, this.content, this.placementId, generateUrl) + if (launch !== null) { + return launch + } + const value = this.opensInternalUrl ? this.tile.internalUrl : this.tile.linkValue + if (this.isCreateTile) { + return '#' + } + if (this.opensInternalUrl === false && this.tile.linkType === 'app') { return generateUrl('/apps/' + value) } // Internal absolute paths (e.g. /apps/deck, /apps/text) MUST go @@ -192,6 +431,8 @@ export default { this.tile ? Object.keys(this.tile) : 'tile is null', ) + this.startCount() + // Add dynamic style to override nldesign's aggressive CSS. const styleId = `tile-${this.tile.id}-style` if (!document.getElementById(styleId)) { @@ -206,7 +447,60 @@ export default { } }, + beforeUnmount() { + this.stopCount() + }, + methods: { + /** + * Read the live count of an icon-only tile with a count source, and + * again each minute while the tile is shown (REQ-ICT-002). + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ + startCount() { + if (!this.iconOnly || sourceType(this.content?.countSource) === null) { + return + } + this.loadCount() + this.countTimer = setInterval(() => this.loadCount(), COUNT_TTL_MS) + }, + + /** + * Stop reading the count. + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ + stopCount() { + if (this.countTimer !== null) { + clearInterval(this.countTimer) + this.countTimer = null + } + }, + + /** + * Ask the count source for the count; no answer is no count. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ + async loadCount() { + this.count = await resolveTileCount(this.content?.countSource, getCurrentUser()?.uid || '') + }, + + /** + * The health ping's reading: an offline service shows the outage dot + * in place of the count (REQ-ICT-003); a reading that clears it brings + * the count back. + * + * @param {{state: (string|null), downSince: (string|null)}} reading The reading. + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-an-outage-req-ict-003 + */ + onPingReading(reading) { + this.pingDown = reading?.state === 'offline' + this.pingDownSince = this.pingDown ? (reading?.downSince ?? null) : null + }, + /** * REQ-TANLT-002 — fire a fire-and-forget tile-click record call * on activation. Never blocks or interferes with the anchor's own @@ -214,13 +508,67 @@ export default { * whether the tracking call succeeds, fails, or is suppressed). A * single `@click` handler covers both mouse clicks and keyboard * (Enter) activation — native `<a>` elements fire a `click` event - * for both. + * for both. A `create` tile opens its name dialog instead of + * following the link (REQ-OFT-002). * + * @param {MouseEvent} [event] The click. * @return {void} * @spec openspec/specs/dashboard-view-analytics/spec.md + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md */ - handleActivate() { + handleActivate(event) { recordTileClick(this.tile?.id) + if (this.tile?.linkType === LINK_PROGRAM) { + this.showProgramHint = true + } + if (this.isCreateTile) { + event?.preventDefault() + if (!this.editMode) { + this.createDialogOpen = true + } + return + } + + // Launcher-tile-open-behaviour D3: a side-panel tile opens beside + // the grid instead of navigating. In edit mode the tile is being + // arranged, so it never opens anything new. + if (this.resolvedTarget !== SIDE_PANEL || this.editMode || !this.tileUrl) { + return + } + event?.preventDefault?.() + useTilePanelStore().open({ + url: this.tileUrl, + title: this.tile?.title || '', + sameOrigin: isSameOrigin(this.tileUrl), + opener: event?.currentTarget || null, + }) + }, + + /** + * Create the file the dialog asked for and open it in its editor. A + * refusal keeps the dialog open with the server's message. + * + * @param {{name: string, folder: string}} choice The name and folder. + * @return {Promise<void>} + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + async createFile(choice) { + this.creating = true + try { + const response = await api.createOfficeFile({ + creatorId: this.tile.linkValue, + name: choice.name, + folder: choice.folder, + }) + this.createDialogOpen = false + window.location.assign(response.data.url) + } catch (error) { + logger.warn('[TileWidget] The office file could not be created:', error) + showError(error?.response?.data?.message || t('launchpad', 'The file could not be created.')) + } finally { + this.creating = false + } }, }, } @@ -239,6 +587,18 @@ export default { background-color: var(--tile-bg-color) !important; } +.tile-widget__hint { + position: absolute; + inset-inline: 0; + bottom: 0; + margin: 0; + padding: 4px 8px; + font-size: 0.85em; + color: var(--color-main-text); + background-color: var(--color-main-background); + text-align: center; +} + .tile-widget__link { display: flex; flex-direction: column; @@ -323,6 +683,99 @@ export default { color: var(--tile-text-color) !important; } +/* An icon-only tile is a square of colour with a 48px white glyph and no + label, as the boards draw the app tiles. The theme underlines and colours + every link with !important, hence the weight here. */ +.tile-widget.tile-widget--icon-only { + border-radius: 8px; +} + +.tile-widget--icon-only .tile-widget__link { + padding: 0; + gap: 0; + text-decoration: none !important; +} + +/* REQ-ICT-001: the white icon fills about 45% of the square, whatever + the column width; a container query unit keeps glyph and emoji in step. */ +.tile-widget.tile-widget--icon-only { + container-type: size; +} + +.tile-widget--icon-only .tile-widget__icon { + min-width: 0; + width: 45cqmin; + height: 45cqmin; + font-size: 45cqmin; +} + +.tile-widget--icon-only .tile-widget__icon :deep(svg) { + width: 100%; + height: 100%; +} + +.tile-widget--icon-only .tile-widget__icon span.icon { + width: 100%; + height: 100%; + background-size: 100%; +} + +/* The marks of an icon-only tile, as CnAppTile draws them. */ +.tile-widget__pin { + position: absolute; + top: 6px; + inset-inline-start: 6px; + display: flex; + opacity: 0.85; +} + +.tile-widget__badge { + position: absolute; + top: 6px; + inset-inline-end: 6px; + box-sizing: border-box; + min-width: 20px; + height: 20px; + padding: 0 6px; + border-radius: 10px; + background: #fff; + color: #1b1c1d; + font-size: 12px; + font-weight: 700; + line-height: 20px; + text-align: center; +} + +.tile-widget__outage { + position: absolute; + top: 6px; + inset-inline-end: 6px; + box-sizing: border-box; + width: 12px; + height: 12px; + border: 2px solid #fff; + border-radius: 50%; + background: var(--color-error, #d91f11); +} + +/* In edit mode a tile shows a drag grip at its top left, a small white + square as LpBewerken draws it. */ +.tile-widget__grip { + position: absolute; + top: 6px; + inset-inline-start: 6px; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border-radius: 4px; + background: var(--color-main-background); + color: var(--color-main-text); + pointer-events: none; +} + /* Position the shared white cog over the tile's top-right corner. The button's own white styling lives in WidgetEditCog. */ .tile-widget__edit { diff --git a/src/components/WidgetRenderer.vue b/src/components/WidgetRenderer.vue index bdfc98921..5c52cdf7b 100644 --- a/src/components/WidgetRenderer.vue +++ b/src/components/WidgetRenderer.vue @@ -13,17 +13,25 @@ <component :is="registryEntry.renderer" v-if="registryEntry" - :content="normalizedContent" + :content="periodContent" :placement="placement" - v-bind="rendererProps" /> + v-bind="rendererProps" + @data="onWidgetData" + @status="(status) => $emit('status', status)" + @edit="$emit('editRequest')" + @editRequest="$emit('editRequest')" /> + + <CalculatedValues v-if="registryEntry" :placement="placement" /> <!-- Custom Tile Widget (legacy path: widgetId === 'tile-{id}') --> <TileWidget v-else-if="isTileWidget && tileData" :tile="tileData" :placementId="placement.id" + :content="normalizedContent" :healthPingEnabled="normalizedContent.healthPingEnabled === true" - :pingInterval="normalizedContent.pingInterval" /> + :pingInterval="normalizedContent.pingInterval" + :linkTarget="normalizedContent.linkTarget || null" /> <!-- API Widget V1 or V2 - Use NcDashboardWidget --> <template v-else-if="isApiWidget"> @@ -46,16 +54,16 @@ <!-- Legacy Widget - Mount via callback --> <div - v-else-if="!loading" + v-else-if="(widget || isTileWidget) && !loading" ref="legacyWidgetContainer" class="widget-renderer__legacy" /> - <!-- Loading state for unknown widget types --> + <!-- Loading state while a widget initialises --> <div v-else-if="loading" class="widget-renderer__loading"> <NcLoadingIcon :size="32" /> </div> - <!-- Unknown widget type --> + <!-- Unknown widget type: no registry entry, tile or installed widget --> <NcEmptyContent v-else :description="t('launchpad', 'Widget not available')"> <template #icon> <AlertCircleOutline :size="48" /> @@ -71,17 +79,74 @@ import { NcLoadingIcon, } from '@conduction/nextcloud-vue' import { mapActions, storeToRefs } from 'pinia' +import { unref } from 'vue' import AlertCircleOutline from 'vue-material-design-icons/AlertCircleOutline.vue' import TileWidget from './TileWidget.vue' +import CalculatedValues from './Widgets/CalculatedFields/CalculatedValues.vue' +import { + FLAG_PROP, + NULLABLE_OBJECT_PROP, + REQUIRED_OBJECT_PROP, +} from '../constants/propDefinitions.js' import { getWidgetTypeEntry } from '../constants/widgetRegistry.js' import { widgetBridge } from '../services/widgetBridge.js' import { buildRendererExtraProps, buildWidgetDataProvide, } from '../services/widgetDataAdapters.js' +import { useCalculatedFieldsStore } from '../stores/calculatedFields.js' import { useTileStore } from '../stores/tiles.js' import { useWidgetStore } from '../stores/widgets.js' +import { contentWithPeriod } from '../utils/dashboardPeriod.js' import { logger } from '../utils/logger.js' +import { placementContent } from '../utils/placementContent.js' + +/** How many times a legacy widget mount is retried before giving up. */ +const LEGACY_MOUNT_ATTEMPTS = 20 + +/* + * Shared widgets that read edit mode from `isAdmin` + `canEdit`: they suppress + * their clicks then, and the menu's empty-state gear asks for the editor. + */ +const EDIT_FLAG_WIDGETS = ['menu', 'link', 'links', 'quicklinks', 'tile', 'video'] + +/** + * The first truthy value among an item's fields, or ''. + * + * @param {object} item The API item. + * @param {Array<string>} keys The field names, in order of preference. + * @return {string} the value. + */ +function firstOf(item, keys) { + for (const key of keys) { + if (item[key]) { + return item[key] + } + } + return '' +} + +/** + * Map an API item onto the NcDashboardWidgetItem props, keeping every + * original field. The key is a compound of stable per-row data (sinceId + + * id + link/targetUrl/title); the index is only a last-resort fallback. + * + * @param {object} item The API item. + * @param {number} index Its position in the list. + * @return {object} the dashboard item. + */ +function toDashboardItem(item, index) { + return { + ...item, + id: `${firstOf(item, ['sinceId'])}-${firstOf(item, ['id'])}-${firstOf(item, ['link', 'targetUrl', 'title']) || index}`, + targetUrl: firstOf(item, ['link', 'targetUrl']), + avatarUrl: firstOf(item, ['iconUrl', 'avatarUrl']), + avatarUsername: firstOf(item, ['avatarUsername']), + overlayIconUrl: firstOf(item, ['overlayIconUrl']), + mainText: firstOf(item, ['title', 'mainText']), + subText: firstOf(item, ['subtitle', 'subText']), + } +} export default { name: 'WidgetRenderer', @@ -91,6 +156,7 @@ export default { NcEmptyContent, NcLoadingIcon, AlertCircleOutline, + CalculatedValues, TileWidget, }, @@ -103,21 +169,26 @@ export default { * @return {object} the injected data-source adapters. */ provide() { - return buildWidgetDataProvide(() => this.placement?.id) + return buildWidgetDataProvide(() => this.placement?.id, () => this.placement?.content) + }, + + inject: { + /** The period the dashboard's dated widgets follow (REQ-DPD-002), a ref, or null. */ + dashboardPeriod: { from: 'dashboardPeriod', default: null }, }, props: { - widget: { - type: Object, - default: null, - }, + widget: NULLABLE_OBJECT_PROP, - placement: { - type: Object, - required: true, - }, + placement: REQUIRED_OBJECT_PROP, + + editMode: FLAG_PROP, }, + // `status`: a renderer's card-head state (the iframe widget's source line + // and outage tag, REQ-IFRAME-005), passed up to WidgetWrapper. + emits: ['editRequest', 'status'], + data() { return { loading: false, // Start false, will be set to true for API widgets only @@ -139,9 +210,28 @@ export default { * @return {object} the content object (empty when unset). * * @spec openspec/specs/widgets/spec.md + * @spec openspec/specs/files-widget/spec.md */ normalizedContent() { - return this.placement?.content || {} + return placementContent(this.placement) + }, + + /** + * The content a registry renderer gets: with the dashboard's period on + * every register source that names a period field, so the stat card, + * stats block, chart and table count only the chosen period. A widget + * without a period field gets its content as stored. + * + * @return {object} the content. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + periodContent() { + const period = unref(this.dashboardPeriod) + if (!period) { + return this.normalizedContent + } + return contentWithPeriod(this.normalizedContent, period, new Date()) }, /** @@ -177,7 +267,7 @@ export default { * @return {boolean} true when the widget should render edge-to-edge. */ isFullBleed() { - return ['header', 'image', 'divider'].includes(this.placement?.widgetId) + return ['header', 'image', 'divider', 'section-heading'].includes(this.placement?.widgetId) }, /** @@ -188,7 +278,11 @@ export default { * @return {object} extra props for `<component :is>` (empty for most types). */ rendererProps() { - return buildRendererExtraProps(this.placement?.widgetId) + const props = buildRendererExtraProps(this.placement?.widgetId) + if (EDIT_FLAG_WIDGETS.includes(this.placement?.widgetId)) { + return { ...props, isAdmin: this.editMode, canEdit: this.editMode } + } + return props }, /** @spec openspec/specs/widgets/spec.md */ @@ -228,6 +322,7 @@ export default { textColor: this.placement.tileTextColor, linkType: this.placement.tileLinkType, linkValue: this.placement.tileLinkValue, + internalUrl: (this.placement.content && this.placement.content.internalUrl) || '', } } // Referenced tile: resolve the Tile entity from the store by id. @@ -275,16 +370,7 @@ export default { // reorder of the upstream items moves DOM nodes instead of tearing // them down. `index` is only a last-resort fallback when a row // carries no stable identifying field at all. - return items.map((item, index) => ({ - ...item, - id: `${item.sinceId || ''}-${item.id || ''}-${item.link || item.targetUrl || item.title || index}`, - targetUrl: item.link || item.targetUrl || '', - avatarUrl: item.iconUrl || item.avatarUrl || '', - avatarUsername: item.avatarUsername || '', - overlayIconUrl: item.overlayIconUrl || '', - mainText: item.title || item.mainText || '', - subText: item.subtitle || item.subText || '', - })) + return items.map(toDashboardItem) }, /** @spec openspec/specs/widgets/spec.md */ @@ -361,6 +447,20 @@ export default { methods: { ...mapActions(useWidgetStore, ['loadWidgetItems', 'refreshWidgetItems']), + /** + * Hand what a self-fetching widget shows to the calculated fields of + * its placement, so they evaluate over it (REQ-CALC-003). + * + * @param {object} data The widget's `data` summary. + * @return {void} + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-19 + */ + onWidgetData(data) { + if (this.placement?.id !== undefined && this.placement?.id !== null) { + useCalculatedFieldsStore().setWidgetData(String(this.placement.id), data) + } + }, + /** @spec openspec/specs/widgets/spec.md */ setupStoreSubscription() { // Subscribe to store changes. @@ -397,23 +497,10 @@ export default { /** @spec openspec/specs/widgets/spec.md */ async initWidget() { - logger.debug('[WidgetRenderer] initWidget called:', { - widgetId: this.widget?.id, - isTileWidget: this.isTileWidget, - isApiWidget: this.isApiWidget, - isApiWidgetV1: this.isApiWidgetV1, - isApiWidgetV2: this.isApiWidgetV2, - itemApiVersions: this.widget?.itemApiVersions, - fullWidget: this.widget, - }) + this.logInitWidget() - if (!this.widget && !this.isTileWidget) { - this.loading = false - return - } - - // Tiles don't need initialization. - if (this.isTileWidget) { + if (!this.widget || this.isTileWidget) { + // Nothing to load, and tiles don't need initialization. this.loading = false return } @@ -424,46 +511,65 @@ export default { this.widget, ) - // Only show loading for API widgets - // Legacy widgets render themselves, so we don't need a loading state - const isLegacy = !this.isApiWidget - if (!isLegacy) { - this.loading = true + if (this.isApiWidget) { + await this.initApiWidget() + } else { + await this.initLegacyWidget() } + }, + /** Log the widget kind flags `initWidget` decides on. */ + logInitWidget() { + logger.debug('[WidgetRenderer] initWidget called:', { + widgetId: this.widget?.id, + isTileWidget: this.isTileWidget, + isApiWidget: this.isApiWidget, + isApiWidgetV1: this.isApiWidgetV1, + isApiWidgetV2: this.isApiWidgetV2, + itemApiVersions: this.widget?.itemApiVersions, + fullWidget: this.widget, + }) + }, + + /** + * Load an API widget's items (v1 and v2) behind a loading state and + * arm its auto-refresh when it has a reload interval. + */ + async initApiWidget() { + // Only API widgets show loading; legacy widgets render themselves. + this.loading = true try { - if (this.isApiWidget) { - logger.debug('[WidgetRenderer] Detected as API widget') - // Load widget items from API (supports both v1 and v2). - await this.loadWidgetItems([this.widget.id]) - // Explicitly sync local data from store after loading. - this.updateLocalWidgetItems() - - // Set up auto-refresh if widget supports it. - if ( - this.widget.reloadInterval - && this.widget.reloadInterval > 0 - ) { - this.setupAutoRefresh(this.widget.reloadInterval) - } - } else { - logger.debug( - '[WidgetRenderer] Legacy widget detected:', - this.widget.id, - ) - // Legacy widget - mount via callback. - // Wait for DOM to be ready - await this.$nextTick() - // Give it a bit more time for the ref to be available - await new Promise((resolve) => setTimeout(resolve, 50)) - this.mountLegacyWidget() + logger.debug('[WidgetRenderer] Detected as API widget') + await this.loadWidgetItems([this.widget.id]) + // Explicitly sync local data from store after loading. + this.updateLocalWidgetItems() + + if ( + this.widget.reloadInterval + && this.widget.reloadInterval > 0 + ) { + this.setupAutoRefresh(this.widget.reloadInterval) } } catch (error) { logger.error('Failed to initialize widget:', error) } finally { - if (!isLegacy) { - this.loading = false - } + this.loading = false + } + }, + + /** Mount a legacy widget via its callback once the DOM is ready. */ + async initLegacyWidget() { + try { + logger.debug( + '[WidgetRenderer] Legacy widget detected:', + this.widget.id, + ) + // Wait for DOM to be ready, then a bit more for the ref. + await this.$nextTick() + await new Promise((resolve) => setTimeout(resolve, 50)) + this.mountLegacyWidget() + } catch (error) { + logger.error('Failed to initialize widget:', error) } }, @@ -483,53 +589,75 @@ export default { // Widget scripts are loaded with defer, so we need to wait for them // to register their callbacks. Try multiple times with increasing delays. - const tryMount = (attempt = 0, maxAttempts = 20) => { - logger.debug( - `[WidgetRenderer] Mount attempt ${attempt + 1}/${maxAttempts} for:`, - this.widget.id, - ) + this.$nextTick(() => { + this.tryMountLegacyWidget() + }) + }, - // Check if callback is registered - if (widgetBridge.hasWidgetCallback(this.widget.id)) { - logger.debug( - '[WidgetRenderer] Callback found! Mounting:', - this.widget.id, - ) - // Pass widget data to the bridge so callbacks can access it - widgetBridge.mountWidget( - this.widget.id, - this.$refs.legacyWidgetContainer, - this.widget, - ) - logger.debug( - '[WidgetRenderer] After mountWidget, container innerHTML length:', - this.$refs.legacyWidgetContainer?.innerHTML.length, - ) - } else if (attempt < maxAttempts) { - // Try again after a short delay - const delay = Math.min(100 * (attempt + 1), 1000) // Exponential backoff up to 1s - logger.debug( - `[WidgetRenderer] Callback not found yet, retrying in ${delay}ms...`, - ) - setTimeout(() => tryMount(attempt + 1, maxAttempts), delay) - } else { - logger.error( - '[WidgetRenderer] Failed to mount widget after', - maxAttempts, - 'attempts:', - this.widget.id, - ) - logger.debug( - '[WidgetRenderer] Available callbacks:', - widgetBridge.getRegisteredWidgetIds(), - ) - } + /** + * Mount the legacy widget when its callback is registered, else retry + * with a growing delay until the attempts run out. + * + * @param {number} [attempt] Zero-based attempt number. + */ + tryMountLegacyWidget(attempt = 0) { + logger.debug( + `[WidgetRenderer] Mount attempt ${attempt + 1}/${LEGACY_MOUNT_ATTEMPTS} for:`, + this.widget.id, + ) + + if (widgetBridge.hasWidgetCallback(this.widget.id)) { + this.mountViaBridge() + } else if (attempt < LEGACY_MOUNT_ATTEMPTS) { + this.retryLegacyMount(attempt) + } else { + this.reportLegacyMountFailure() } + }, - // Start trying immediately - this.$nextTick(() => { - tryMount() - }) + /** Hand the container and widget data to the registered callback. */ + mountViaBridge() { + logger.debug( + '[WidgetRenderer] Callback found! Mounting:', + this.widget.id, + ) + // Pass widget data to the bridge so callbacks can access it + widgetBridge.mountWidget( + this.widget.id, + this.$refs.legacyWidgetContainer, + this.widget, + ) + logger.debug( + '[WidgetRenderer] After mountWidget, container innerHTML length:', + this.$refs.legacyWidgetContainer?.innerHTML.length, + ) + }, + + /** + * Schedule the next mount attempt. + * + * @param {number} attempt Zero-based number of the attempt that failed. + */ + retryLegacyMount(attempt) { + const delay = Math.min(100 * (attempt + 1), 1000) // Exponential backoff up to 1s + logger.debug( + `[WidgetRenderer] Callback not found yet, retrying in ${delay}ms...`, + ) + setTimeout(() => this.tryMountLegacyWidget(attempt + 1), delay) + }, + + /** Log that the legacy widget never registered its callback. */ + reportLegacyMountFailure() { + logger.error( + '[WidgetRenderer] Failed to mount widget after', + LEGACY_MOUNT_ATTEMPTS, + 'attempts:', + this.widget.id, + ) + logger.debug( + '[WidgetRenderer] Available callbacks:', + widgetBridge.getRegisteredWidgetIds(), + ) }, /** @@ -561,7 +689,8 @@ export default { padding: 16px; } -/* Full-bleed widgets (header banner, image, divider) paint edge-to-edge. */ +/* Full-bleed widgets (header banner, image, divider) paint edge-to-edge; a + section heading starts on the grid's line, as the boards draw it. */ .widget-renderer--flush { padding: 0; } diff --git a/src/components/WidgetWrapper.vue b/src/components/WidgetWrapper.vue index a7eadd1bc..85f6f713a 100644 --- a/src/components/WidgetWrapper.vue +++ b/src/components/WidgetWrapper.vue @@ -31,11 +31,31 @@ :iconClass="widget && widget.iconClass ? widget.iconClass : null" :styleConfig="styleConfig" :buttons="widgetButtons" + :headerLink="headerLink" + :headerActions="headerActions" + :subtitle="headStatus.subtitle" :borderless="isChromelessFrame" :flush="isChromelessFrame || rendersOwnHeader" :showRefresh="false" - :showRequestFeature="false"> - <WidgetRenderer :widget="widget" :placement="placement" /> + :showRequestFeature="false" + :showActions="showActionsMenu"> + <!-- REQ-IFRAME-005: the "Outage" tag in the card head, by icon-free + text so it never relies on colour alone. --> + <template v-if="headStatus.outage" #title-meta> + <span class="launchpad-widget__outage-tag" data-testid="widget-outage-tag"> + {{ t('launchpad', 'Outage') }} + </span> + </template> + <!-- REQ-WDG-044: the content below the fold mounts when it comes + into view (or once the page has settled); the card shows at once. --> + <LazyMount :eager="mountsAtOnce"> + <WidgetRenderer + :widget="widget" + :placement="placement" + :editMode="editMode" + @status="onRendererStatus" + @editRequest="$emit('edit', placement)" /> + </LazyMount> </CnWidgetWrapper> <!-- REQ-ACK-002: forced-delivery read-gate. Overlays the widget with a @@ -50,7 +70,7 @@ <!-- One shared edit cog for every widget type (data, NC, chrome-less), shown in edit mode. Sits top-right over the wrapper's header area. The absolute positioning lives on this wrapper DIV, not on - CnWidgetEditCog itself: the cog's root is an NcActions `.action-item` + the menu itself: the cog's root is an NcActions `.action-item` which sets `position: relative` at equal specificity, so positioning the component directly loses the cascade tie and the cog drops into flow (pushing content). Wrapping matches the shared nc-vue @@ -58,9 +78,14 @@ <!-- dashboards-personal-hide-ui REQ-PERSUI-001: in view mode a widget on a shared dashboard can be hidden for this person only. Not offered for a compulsory widget (the server refuses it anyway). --> - <div v-if="showHideForMe" class="launchpad-widget__cog"> - <NcActions :aria-label="t('launchpad', 'Widget options')"> + <!-- embedded-analytics task 40: an administrator can create an embed + token for this one widget, in Beheer ▸ Embeds with it pre-selected. --> + <div v-if="showHideForMe || showEmbed" class="launchpad-widget__cog"> + <NcActions + :aria-label="t('launchpad', 'Widget options')" + :forceMenu="true"> <NcActionButton + v-if="showHideForMe" :closeAfterClick="true" data-testid="widget-hide-for-me" @click="$emit('hideForMe', placement)"> @@ -69,14 +94,44 @@ </template> {{ t('launchpad', 'Hide for me') }} </NcActionButton> + <NcActionLink + v-if="showEmbed" + :href="embedHref" + data-testid="widget-create-embed-token"> + <template #icon> + <CodeTags :size="20" /> + </template> + {{ t('launchpad', 'Create embed token') }} + </NcActionLink> </NcActions> </div> + <!-- LpBewerken: in edit mode every widget shows a drag grip at its top + left and the three-dot menu at its top right. --> + <span + v-if="editMode" + class="launchpad-widget__grip" + aria-hidden="true" + data-testid="widget-drag-grip"> + <DragVertical :size="16" /> + </span> + <!-- REQ-PERM-004: in edit mode a compulsory widget carries a lock, beside + its menu, so the author sees why it has no Delete. Never in view mode. --> + <span + v-if="showCompulsoryIndicator" + class="launchpad-widget__compulsory" + role="img" + :aria-label="t('launchpad', 'Required: this widget cannot be removed')" + :title="t('launchpad', 'Required: this widget cannot be removed')" + data-testid="widget-compulsory-indicator"> + <LockOutline :size="16" /> + </span> <div v-if="editMode" class="launchpad-widget__cog"> - <CnWidgetEditCog + <!-- REQ-CVUI-007: the menu also holds "Who sees this widget?". --> + <WidgetEditMenu :menuLabel="t('launchpad', 'Widget menu')" - :editLabel="t('launchpad', 'Edit widget')" - :deleteLabel="t('launchpad', 'Delete widget')" + :removeLocked="!canRemove" @edit="$emit('edit', placement)" + @whoSees="$emit('whoSees', placement)" @remove="$emit('remove', placement.id)" /> </div> </div> @@ -84,39 +139,81 @@ <script> import { - CnWidgetEditCog, CnWidgetWrapper, NcActionButton, NcActions, } from '@conduction/nextcloud-vue' +import { NcActionLink } from '@nextcloud/vue' +import CodeTags from 'vue-material-design-icons/CodeTags.vue' +import DragVertical from 'vue-material-design-icons/DragVertical.vue' import EyeOff from 'vue-material-design-icons/EyeOff.vue' +import LockOutline from 'vue-material-design-icons/LockOutline.vue' import AcknowledgementPrompt from './AcknowledgementPrompt.vue' +import LazyMount from './LazyMount.vue' import WidgetRenderer from './WidgetRenderer.vue' +import WidgetEditMenu from './Widgets/WidgetEditMenu.vue' +import { + FLAG_PROP, + LIST_PROP, + NULLABLE_OBJECT_PROP, + REQUIRED_OBJECT_PROP, + TEXT_PROP, +} from '../constants/propDefinitions.js' import { resolveWidgetTitle } from '../utils/widgetTitle.js' +/** + * Whether two links lead to the same page, ignoring the host, `/index.php` + * and a trailing slash. + * + * @param {string} a A link. + * @param {string} b Another link. + * @return {boolean} + */ +export function sameDestination(a, b) { + const path = (link) => + String(link ?? '') + .replace(/^[a-z]+:\/\/[^/]+/i, '') + .replace(/^\/index\.php/, '') + .replace(/\/+$/, '') + return a !== undefined && a !== null && path(a) === path(b) +} + +/** + * Whether this page is the headless export render (`?export=1`). + * + * @param {Location} [location] Injected for tests. + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ +export function isExportRender(location = typeof window !== 'undefined' ? window.location : null) { + if (!location || typeof location.search !== 'string') { + return false + } + return new URLSearchParams(location.search).get('export') === '1' +} + export default { name: 'WidgetWrapper', components: { CnWidgetWrapper, - CnWidgetEditCog, + CodeTags, + DragVertical, EyeOff, + LockOutline, NcActionButton, + NcActionLink, NcActions, WidgetRenderer, + WidgetEditMenu, AcknowledgementPrompt, + LazyMount, }, props: { - placement: { - type: Object, - required: true, - }, + placement: REQUIRED_OBJECT_PROP, - widget: { - type: Object, - default: null, - }, + widget: NULLABLE_OBJECT_PROP, /** * The Nextcloud Dashboard widget catalog. @@ -127,35 +224,51 @@ export default { * pre-resolved entry. Passed as a prop rather than read from the store * so this stays a presentational component that mounts without pinia. */ - availableWidgets: { - type: Array, - default: () => [], - }, + availableWidgets: LIST_PROP, - editMode: { - type: Boolean, - default: false, - }, + editMode: FLAG_PROP, // REQ-ACK-002: whether this placement is an outstanding mandatory-read // item for the current user. Resolved by the parent from the pending // set; defaults false so widgets without a requirement are unchanged. - outstandingAcknowledgement: { - type: Boolean, - default: false, - }, + outstandingAcknowledgement: FLAG_PROP, // dashboards-personal-hide-ui: the host allows "Hide for me" here // (a shared dashboard the viewer does not own). - canHideForMe: { - type: Boolean, - default: false, - }, + canHideForMe: FLAG_PROP, + + // REQ-PERM: the host refuses removal (a compulsory widget on a dashboard + // held with less than full permission), so the cog offers no Delete. + removeLocked: FLAG_PROP, + + // embedded-analytics task 40: the Beheer ▸ Embeds link that creates an + // embed token for this widget; '' when the viewer may not create one. + embedHref: TEXT_PROP, }, - emits: ['remove', 'style', 'edit', 'acknowledged', 'hideForMe'], + emits: ['remove', 'style', 'edit', 'whoSees', 'acknowledged', 'hideForMe'], + + data() { + return { + // What the renderer reports for the card head (REQ-IFRAME-005): + // the source line under the title and the outage tag. + headStatus: { subtitle: '', outage: false }, + } + }, computed: { + /** + * Whether the content mounts at once instead of when it comes into + * view: in edit mode, and in the headless export render (`?export=1`), + * which prints the whole dashboard. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + mountsAtOnce() { + return this.editMode || isExportRender() + }, + /** * Whether "Hide for me" is offered: view mode, allowed by the host, * and not a compulsory widget. @@ -171,6 +284,17 @@ export default { ) }, + /** + * Whether "Create embed token" is offered: view mode, with a link + * from the host (only an administrator gets one). + * + * @return {boolean} + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + */ + showEmbed() { + return this.embedHref !== '' && !this.editMode + }, + /** * Whether this placement renders a reusable tile, identified by the * `tile-` widgetId prefix. @@ -206,7 +330,7 @@ export default { /** * Widget types that own their entire visual surface — labels, dividers, - * header banners, and the registry-driven `tile`. They keep a borderless + * header banners, the registry-driven `tile` and the `app-tile`. They keep a borderless * / flush wrapper (no frame, no wrapper header) so the renderer paints * edge to edge; the edit cog still overlays on top. (nc-widget is NOT * here: CnNcWidgetWidget renders just a header + content, so it needs the @@ -215,7 +339,7 @@ export default { * @spec openspec/specs/widgets/spec.md */ isChromelessType() { - return ['label', 'divider', 'header', 'tile'].includes( + return ['label', 'section-heading', 'divider', 'header', 'tile', 'app-tile'].includes( this.placement?.widgetId, ) }, @@ -229,7 +353,46 @@ export default { * @return {boolean} true when the renderer owns the header. */ rendersOwnHeader() { - return this.placement?.widgetId === 'nc-widget' + return ( + this.placement?.widgetId === 'nc-widget' + && this.placement?.content?.showHeader !== false + ) + }, + + /** + * Whether the card's overflow menu shows. On by default outside edit + * mode; a placement whose content says `showActions: false` hides it. + * In edit mode the widget's own three-dot menu takes its place + * (LpBewerken). + * + * @spec openspec/specs/widgets/spec.md + * @return {boolean} false only for an opted-out placement in view mode. + */ + showActionsMenu() { + return !this.editMode && this.placement?.content?.showActions !== false + }, + + /** + * Buttons in the card's title row. The compact Files list draws its + * Upload there (LpWerkplek "Bestanden") and asks the widget to open + * its file picker. + * + * @return {Array<object>} + * @spec openspec/specs/widgets/spec.md + */ + headerActions() { + const content = this.placement?.content || {} + if (this.editMode || this.placement?.widgetId !== 'files' || content.layout !== 'compact' || content.allowUpload !== true) { + return [] + } + const placementId = this.placement.id + return [{ + key: 'upload', + label: this.t('launchpad', 'Upload'), + icon: 'Upload', + variant: 'secondary', + run: () => window.dispatchEvent(new CustomEvent('cn-files-widget:upload', { detail: { placementId } })), + }] }, /** @spec openspec/specs/widgets/spec.md */ @@ -295,13 +458,52 @@ export default { /** @spec openspec/specs/widgets/spec.md */ widgetButtons() { - return this.widget?.buttons || [] + const buttons = this.widget?.buttons || [] + const headerHref = this.headerLink?.href + if (!headerHref) { + return buttons + } + return buttons.filter( + (button) => !sameDestination(button?.link, headerHref), + ) }, - /** @spec openspec/specs/widgets/spec.md */ + /** + * The text link in the card's header (`content.headerLink`, + * `{ label, href }`), as LpVandaag's "Open agenda". Null without a + * label and a link. + * + * @return {{label: string, href: string}|null} + * @spec openspec/changes/lpvandaag-start-page/specs/lpvandaag-start-page/spec.md#requirement-the-start-page-fits-the-screen + */ + headerLink() { + const link = this.placement?.content?.headerLink + if ( + !link + || typeof link.label !== 'string' + || link.label === '' + || typeof link.href !== 'string' + || link.href === '' + ) { + return null + } + return { label: link.label, href: link.href } + }, + + /** @spec openspec/specs/permissions/spec.md */ canRemove() { - // Can't remove compulsory widgets unless full permission - return !this.placement.isCompulsory + return !this.removeLocked + }, + + /** + * Whether the compulsory lock shows: in edit mode only, on a placement + * flagged compulsory (REQ-PERM-004). + * + * @return {boolean} + * @spec openspec/specs/permissions/spec.md + */ + showCompulsoryIndicator() { + return Boolean(this.editMode) && Number(this.placement?.isCompulsory) === 1 }, /** @@ -319,10 +521,40 @@ export default { return this.placement.styleConfig || {} }, }, + + methods: { + /** + * Keep the card-head state a renderer reports (REQ-IFRAME-005): the + * source line under the title and whether the "Outage" tag shows. + * + * @param {{subtitle?: string, outage?: boolean}|null} status The renderer's head status. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + onRendererStatus(status) { + this.headStatus = { + subtitle: typeof status?.subtitle === 'string' ? status.subtitle : '', + outage: status?.outage === true, + } + }, + }, } </script> <style scoped> +.launchpad-widget__outage-tag { + display: inline-flex; + align-items: center; + padding: 0 8px; + border-radius: var(--border-radius-pill, 12px); + border: 1px solid var(--color-error); + color: var(--color-error-text, var(--color-error)); + font-size: 0.75rem; + font-weight: 600; + line-height: 20px; + white-space: nowrap; +} + .launchpad-widget { position: relative; height: 100%; @@ -332,6 +564,51 @@ export default { height: 100%; } +/* The drag grip sits at the top left of a widget in edit mode; the card's + title moves right to make room for it (LpBewerken). On a tile both the + grip and the menu are small white squares. */ +.launchpad-widget__grip { + position: absolute; + top: 18px; + inset-inline-start: 14px; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border-radius: 4px; + color: var(--color-text-maxcontrast); + pointer-events: none; +} + +.launchpad-widget--editing :deep(.cn-widget-wrapper__header) { + padding-inline-start: 42px; +} + +.launchpad-widget--editing:has(.tile-widget, .cn-app-tile-widget) .launchpad-widget__grip { + top: 6px; + inset-inline-start: 6px; + background: var(--color-main-background); + color: var(--color-main-text); +} + +/* REQ-PERM-004: the compulsory lock sits left of the menu in edit mode. */ +.launchpad-widget__compulsory { + position: absolute; + top: 14px; + right: 52px; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border-radius: 50%; + background: var(--color-main-background); + color: var(--color-text-maxcontrast); +} + /* The shared cog overlays the wrapper's top-right (the header's action area when a header is shown, otherwise over the content). */ .launchpad-widget__cog { diff --git a/src/components/Widgets/CalculatedFields/CalculatedValues.vue b/src/components/Widgets/CalculatedFields/CalculatedValues.vue new file mode 100644 index 000000000..fbd91b5a1 --- /dev/null +++ b/src/components/Widgets/CalculatedFields/CalculatedValues.vue @@ -0,0 +1,115 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <dl v-if="rows.length > 0" class="calculated-values" data-testid="calculated-values"> + <div + v-for="row in rows" + :key="row.name" + class="calculated-values__row" + :data-field="row.name"> + <dt class="calculated-values__label"> + {{ row.label }} + </dt> + <dd class="calculated-values__value"> + <span + v-if="row.error" + class="calculated-values__error" + role="img" + tabindex="0" + :title="row.error" + :aria-label="row.error" + data-testid="calculated-value-error"> + <AlertCircle :size="18" aria-hidden="true" /> + </span> + <span v-else data-testid="calculated-value">{{ row.text }}</span> + </dd> + </div> + </dl> +</template> + +<script> +import { getLanguage } from '@nextcloud/l10n' +import { mapState } from 'pinia' +import AlertCircle from 'vue-material-design-icons/AlertCircle.vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { useCalculatedFieldsStore } from '../../../stores/calculatedFields.js' +import { compiledFieldsOf } from '../../../utils/calculatedFields/dashboardValues.js' +import { calculatedFieldErrorText } from '../../../utils/calculatedFields/errorText.js' +import { formatCalculatedValue } from '../../../utils/calculatedFields/formatOptions.js' + +/** + * The calculated fields of a placed widget, shown beside its own data + * (widget-calculated-fields REQ-CALC-008, REQ-CALC-010): each field's label + * and its value formatted for display only, or an error icon whose hover + * text names what went wrong, the formula and the values it read. The value + * in the store stays native for export and drill-down. + */ +export default { + name: 'CalculatedValues', + + components: { AlertCircle }, + + props: { + /** The placement record, carrying `id` and `calculatedFields`. */ + placement: OBJECT_PROP, + }, + + computed: { + ...mapState(useCalculatedFieldsStore, ['valuesOf', 'errorsOf']), + + /** + * One row per calculated field: its label and display text, or its error text. + * + * @return {Array<{name: string, label: string, text: string, error: string|null}>} + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-19 + */ + rows() { + const id = String(this.placement?.id ?? '') + const values = this.valuesOf(id) + const errors = this.errorsOf(id) + const locale = getLanguage() + return compiledFieldsOf(this.placement).map((field) => ({ + name: field.name, + label: field.label || field.name, + text: formatCalculatedValue(values[field.name] ?? null, field, locale), + error: errors[field.name] ? calculatedFieldErrorText(errors[field.name]) : null, + })) + }, + }, +} +</script> + +<style scoped> +.calculated-values { + display: flex; + flex-wrap: wrap; + gap: 4px 16px; + margin: 8px 0 0; + padding: 0 12px 8px; +} + +.calculated-values__row { + display: flex; + gap: 6px; + align-items: baseline; +} + +.calculated-values__label { + color: var(--color-text-maxcontrast); +} + +.calculated-values__value { + margin: 0; + font-weight: bold; + font-variant-numeric: tabular-nums; +} + +.calculated-values__error { + display: inline-flex; + color: var(--color-error-text); + cursor: help; +} +</style> diff --git a/src/components/Widgets/CalculatedFields/__tests__/CalculatedValues.spec.js b/src/components/Widgets/CalculatedFields/__tests__/CalculatedValues.spec.js new file mode 100644 index 000000000..bee683a88 --- /dev/null +++ b/src/components/Widgets/CalculatedFields/__tests__/CalculatedValues.spec.js @@ -0,0 +1,81 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * A placed widget shows its calculated fields beside its own data: the + * value formatted for display only, or an error icon whose hover text names + * what went wrong, the formula and the values it read (REQ-CALC-008, + * REQ-CALC-010). + * + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-19 + */ + +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { nextTick } from 'vue' +import CalculatedValues from '../CalculatedValues.vue' +import { useCalculatedFieldsStore } from '../../../../stores/calculatedFields.js' +import { parse } from '../../../../utils/calculatedFields/parser.js' + +vi.mock('@nextcloud/l10n', () => ({ + getLanguage: () => 'nl-NL', + translate: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => (key in vars ? vars[key] : `{${key}}`)), +})) + +/** + * A placement with calculated fields compiled from their expressions. + * + * @param {string} id The placement id. + * @param {Array<object>} fields The fields: `{name, expression, label?, returnType?, formatOptions?}`. + * @return {object} + */ +function placement(id, fields) { + const names = fields.map((field) => field.name) + return { + id, + calculatedFields: fields.map((field) => ({ ...field, compiledExpression: parse(field.expression, { calculatedNames: names }) })), + } +} + +beforeEach(() => { + setActivePinia(createPinia()) +}) + +describe('CalculatedValues', () => { + it('shows each field with its value formatted at display time, and keeps the native value', async () => { + const place = placement('7', [{ name: 'share', label: 'Share closed', expression: 'closed / total', returnType: 'number', formatOptions: { style: 'percent', maximumFractionDigits: 0 } }]) + const store = useCalculatedFieldsStore() + store.setWidgets([place]) + store.setWidgetData('7', { closed: 3, total: 4 }) + const wrapper = mount(CalculatedValues, { props: { placement: place } }) + await nextTick() + + expect(wrapper.find('dt').text()).toBe('Share closed') + expect(wrapper.find('[data-testid="calculated-value"]').text()).toBe('75%') + expect(store.valuesOf('7').share).toBe(0.75) + }) + + it('shows an error icon naming the formula and the values read, and the other fields still render', async () => { + const place = placement('8', [ + { name: 'ratio', expression: 'a / b' }, + { name: 'sum', expression: 'a + b' }, + ]) + const store = useCalculatedFieldsStore() + store.setWidgets([place]) + store.setWidgetData('8', { a: 4, b: 0 }) + const wrapper = mount(CalculatedValues, { props: { placement: place } }) + await nextTick() + + const error = wrapper.find('[data-field="ratio"] [data-testid="calculated-value-error"]') + expect(error.exists()).toBe(true) + expect(error.attributes('title')).toContain('Formula: a / b') + expect(error.attributes('title')).toContain('b = 0') + expect(wrapper.find('[data-field="sum"] [data-testid="calculated-value"]').text()).toBe('4') + }) + + it('renders nothing for a widget without calculated fields', () => { + const wrapper = mount(CalculatedValues, { props: { placement: { id: '9' } } }) + expect(wrapper.find('[data-testid="calculated-values"]').exists()).toBe(false) + }) +}) diff --git a/src/components/Widgets/ConditionalVisibilityEditor.vue b/src/components/Widgets/ConditionalVisibilityEditor.vue index c237076ab..0bfc05fa2 100644 --- a/src/components/Widgets/ConditionalVisibilityEditor.vue +++ b/src/components/Widgets/ConditionalVisibilityEditor.vue @@ -20,20 +20,36 @@ <div class="conditional-visibility-editor" data-test="conditional-visibility-editor"> - <p class="conditional-visibility-editor__hint"> - {{ - t( - 'launchpad', - 'Show or hide this widget based on group membership, time of day, date range, or a user attribute.', - ) - }} - </p> - <div v-if="loading" class="conditional-visibility-editor__loading"> <NcLoadingIcon :size="32" /> </div> <template v-else> + <!-- REQ-CVUI-006: all or one rule must match, as two choice cards + with radio-group semantics (arrow keys move the choice). --> + <div + class="conditional-visibility-editor__modes" + role="radiogroup" + :aria-label="t('launchpad', 'Who sees this widget?')" + data-test="rule-match"> + <button + v-for="mode in matchModes" + :key="mode.id" + type="button" + role="radio" + class="conditional-visibility-editor__mode" + :class="{ 'conditional-visibility-editor__mode--active': matchMode === mode.id }" + :aria-checked="matchMode === mode.id ? 'true' : 'false'" + :tabindex="matchMode === mode.id ? 0 : -1" + :disabled="savingMatch" + :data-test="'rule-match-' + mode.id" + @click="setMatchMode(mode.id)" + @keydown="onModeKeydown"> + <span class="conditional-visibility-editor__mode-dot" aria-hidden="true" /> + {{ mode.label }} + </button> + </div> + <p v-if="isEmpty" class="conditional-visibility-editor__empty" @@ -47,43 +63,67 @@ </p> <section - v-if="includeRules.length > 0" - class="conditional-visibility-editor__section" - data-test="include-section"> - <h3>{{ t('launchpad', 'Show when ANY of these match') }}</h3> - <div class="conditional-visibility-editor__rows"> - <VisibilityRuleRow - v-for="row in includeRules" - :key="rowKey(row)" - :rule="row" - :availableGroups="availableGroups" - :busy="isRowBusy(row)" - :isNew="row.id === null" - data-test="visibility-rule-row-include" - @update:rule="onRowUpdate(row, $event)" - @save="onRowSave(row, $event)" - @remove="onRowRemove(row)" /> - </div> - </section> - - <section - v-if="excludeRules.length > 0" + v-for="section in sections" + :key="section.id" class="conditional-visibility-editor__section" - data-test="exclude-section"> - <h3>{{ t('launchpad', 'Hide when ANY of these match') }}</h3> - <div class="conditional-visibility-editor__rows"> - <VisibilityRuleRow - v-for="row in excludeRules" + :data-test="section.id + '-section'"> + <h3>{{ section.heading }}</h3> + <ul class="conditional-visibility-editor__rows"> + <li + v-for="row in section.rules" :key="rowKey(row)" - :rule="row" - :availableGroups="availableGroups" - :busy="isRowBusy(row)" - :isNew="row.id === null" - data-test="visibility-rule-row-exclude" - @update:rule="onRowUpdate(row, $event)" - @save="onRowSave(row, $event)" - @remove="onRowRemove(row)" /> - </div> + class="conditional-visibility-editor__card" + :data-test="'visibility-rule-row-' + section.id"> + <div class="conditional-visibility-editor__card-head" data-test="visibility-rule-card"> + <span + :id="'rule-kind-' + rowKey(row)" + class="conditional-visibility-editor__kind" + data-test="rule-card-kind"> + {{ kindLabel(row) }} + </span> + <span + v-if="row.ruleType === 'group'" + class="conditional-visibility-editor__chips" + data-test="rule-card-value"> + <span + v-for="name in groupNamesOf(row)" + :key="name" + class="conditional-visibility-editor__chip">{{ name }}</span> + </span> + <span + v-else + class="conditional-visibility-editor__value" + data-test="rule-card-value">{{ valueOf(row) }}</span> + <span class="conditional-visibility-editor__card-actions"> + <NcButton + variant="tertiary" + :aria-describedby="'rule-kind-' + rowKey(row)" + :aria-expanded="isEditing(row) ? 'true' : 'false'" + data-test="rule-card-edit" + @click="toggleEdit(row)"> + {{ t('launchpad', 'Edit') }} + </NcButton> + <NcButton + variant="tertiary" + :aria-describedby="'rule-kind-' + rowKey(row)" + :disabled="isRowBusy(row)" + data-test="rule-card-delete" + @click="onRowRemove(row)"> + {{ t('launchpad', 'Delete') }} + </NcButton> + </span> + </div> + <VisibilityRuleRow + v-if="isEditing(row)" + :rule="row" + :availableGroups="availableGroups" + :busy="isRowBusy(row)" + :isNew="row.id === null" + @update:rule="onRowUpdate(row, $event)" + @save="onRowSave(row, $event)" + @remove="onRowRemove(row)" /> + </li> + </ul> </section> <NcButton variant="secondary" data-test="add-rule" @click="addRule"> @@ -93,30 +133,31 @@ {{ t('launchpad', 'Add rule') }} </NcButton> - <!-- REQ-CVUI-004: preview as audience/date. --> + <!-- REQ-CVUI-006: View as a person at a moment, with the sentence. --> <section class="conditional-visibility-editor__preview" data-test="visibility-preview"> - <h3>{{ t('launchpad', 'Preview as audience / date') }}</h3> + <h3>{{ t('launchpad', 'View as') }}</h3> <div class="conditional-visibility-editor__preview-fields"> <div class="conditional-visibility-editor__preview-field"> - <NcSelectTags - v-model="previewGroups" - :options="availableGroups" - :multiple="true" - :aria-label-combobox=" - t('launchpad', 'Preview as groups') - " - :placeholder=" - t('launchpad', 'Select groups to preview as') - " - data-test="preview-groups" /> + <NcSelect + v-model="previewPerson" + :options="personOptions" + :filterable="false" + :loading="personLoading" + :inputLabel="t('launchpad', 'Person')" + :placeholder="t('launchpad', 'Search people')" + label="displayName" + trackBy="id" + :clearable="false" + data-test="preview-person" + @search="onPersonSearch" /> </div> <div class="conditional-visibility-editor__preview-field"> <NcTextField v-model="previewDatetime" type="datetime-local" - :label="t('launchpad', 'Preview at date/time')" + :label="t('launchpad', 'Moment')" data-test="preview-datetime" /> </div> <NcButton @@ -149,6 +190,7 @@ <div v-else-if="preview.state.result" class="conditional-visibility-editor__preview-result" + role="status" data-test="preview-result"> <p class="conditional-visibility-editor__preview-verdict"> <Eye v-if="preview.state.result.visible" :size="20" /> @@ -161,27 +203,24 @@ }} </strong> </p> + <p + class="conditional-visibility-editor__preview-sentence" + data-test="visibility-sentence"> + {{ sentence }} + </p> <p v-for="rule in matchedIncludeRules" - :key="'inc-' + rule.id" + :key="'inc-' + rowKey(rule)" class="conditional-visibility-editor__preview-reason" data-test="preview-matched-include"> - {{ - t('launchpad', 'Matched include rule: {summary}', { - summary: describeRule(rule), - }) - }} + {{ t('launchpad', 'Matched include rule: {summary}', { summary: valueOf(rule) }) }} </p> <p v-for="rule in matchedExcludeRules" - :key="'exc-' + rule.id" + :key="'exc-' + rowKey(rule)" class="conditional-visibility-editor__preview-reason" data-test="preview-matched-exclude"> - {{ - t('launchpad', 'Matched exclude rule: {summary}', { - summary: describeRule(rule), - }) - }} + {{ t('launchpad', 'Matched exclude rule: {summary}', { summary: valueOf(rule) }) }} </p> </div> </section> @@ -193,24 +232,107 @@ import { NcButton, NcLoadingIcon, - NcSelectTags, + NcSelect, NcTextField, } from '@conduction/nextcloud-vue' -import { t } from '@nextcloud/l10n' +import { getCurrentUser } from '@nextcloud/auth' +import { getLanguage, t } from '@nextcloud/l10n' import Eye from 'vue-material-design-icons/Eye.vue' import EyeOff from 'vue-material-design-icons/EyeOff.vue' import Plus from 'vue-material-design-icons/Plus.vue' import VisibilityRuleRow from './VisibilityRuleRow.vue' -import { useVisibilityPreview } from '../../composables/useVisibilityPreview.js' +import { previewRuleId, useVisibilityPreview } from '../../composables/useVisibilityPreview.js' +import { LIST_PROP } from '../../constants/propDefinitions.js' import { api } from '../../services/api.js' +import { toGroupOptions } from '../../utils/groupOptions.js' import { logger } from '../../utils/logger.js' +import { + formatMoment, + ruleGroupNames, + ruleKindLabel, + ruleValue, + visibilitySentence, +} from '../../utils/visibilitySentence.js' + +/** How the include rules combine: one is enough, or all must match. */ +const MATCH_MODES = ['all', 'any'] + +/** + * The signed-in user as a person option, or null. + * + * @return {{id: string, displayName: string}|null} the option. + */ +function currentPerson() { + const user = getCurrentUser() + return user ? { id: user.uid, displayName: user.displayName || user.uid } : null +} + +/** + * A moment as the value of a `datetime-local` field, in local time. + * + * @param {Date} date The moment. + * @return {string} `YYYY-MM-DDTHH:mm`. + */ +function localDatetime(date) { + const pad = (n) => String(n).padStart(2, '0') + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}` +} + +/** + * A response body's `data` envelope when present, else the body itself. + * + * @param {object|null} data The response body. + * @return {object|null} the rule. + */ +function unwrapData(data) { + return data && data.data ? data.data : data +} + +/** + * The rule list of a rules response: `{rules}`, `{data: {rules}}` or a bare + * array; anything else reads as no rules. + * + * @param {object|Array|null} data The response body. + * @return {Array<object>} the rules. + */ +function rulesFromResponse(data) { + const payload = rulesPayload(data) + if (Array.isArray(payload.rules)) { + return payload.rules + } + return Array.isArray(data) ? data : [] +} + +/** + * The object of a rules response that carries the `rules` key. + * + * @param {object|Array|null} data The response body. + * @return {object} the payload, `{}` when there is none. + */ +function rulesPayload(data) { + return data && data.rules ? data : data && data.data ? data.data : {} +} + +/** + * Rules as editor rows: persisted, so without a local draft key. + * + * @param {Array<object>} list The rules. + * @return {Array<object>} the rows. + */ +function editableRules(list) { + return list.map((r) => ({ + ...r, + id: r.id, + _localKey: undefined, + })) +} export default { name: 'ConditionalVisibilityEditor', components: { NcButton, - NcSelectTags, + NcSelect, NcTextField, NcLoadingIcon, Plus, @@ -226,14 +348,17 @@ export default { default: null, }, - /** Group-id options for the group-rule / preview-audience pickers. */ - availableGroups: { - type: Array, - default: () => [], + /** Group-id options for the group-rule picker and the group chips. */ + availableGroups: LIST_PROP, + + /** How the include rules combine: `any` (one is enough) or `all`. */ + ruleMatch: { + type: String, + default: 'any', }, }, - emits: ['ruleAdded', 'ruleUpdated', 'ruleRemoved'], + emits: ['ruleAdded', 'ruleUpdated', 'ruleRemoved', 'ruleMatchChanged'], /** @spec openspec/specs/conditional-visibility-editor/spec.md */ setup() { @@ -246,12 +371,103 @@ export default { loading: false, busyKeys: {}, nextLocalId: -1, - previewGroups: [], - previewDatetime: '', + matchMode: this.ruleMatch === 'all' ? 'all' : 'any', + savingMatch: false, + editingKeys: {}, + previewPerson: currentPerson(), + personOptions: currentPerson() ? [currentPerson()] : [], + personLoading: false, + personSearchSeq: 0, + previewDatetime: localDatetime(new Date()), + previewSubject: null, } }, computed: { + /** + * The two choice cards: all rules or one rule must match. + * + * @return {Array<{id: string, label: string}>} the modes. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + matchModes() { + return [ + { id: 'all', label: t('launchpad', 'If all rules match') }, + { id: 'any', label: t('launchpad', 'If one rule matches') }, + ] + }, + + /** + * The include and exclude sections that have rules, with headings + * that follow the match mode (REQ-CVUI-003). + * + * @return {Array<{id: string, heading: string, rules: Array<object>}>} the sections. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + sections() { + return [ + { + id: 'include', + heading: this.matchMode === 'all' + ? t('launchpad', 'Show when ALL of these match') + : t('launchpad', 'Show when ANY of these match'), + rules: this.includeRules, + }, + { id: 'exclude', heading: t('launchpad', 'Hide when ANY of these match'), rules: this.excludeRules }, + ].filter((section) => section.rules.length > 0) + }, + + /** + * Display name per group id, for the chips and the sentence. + * + * @return {{[key: string]: string}} the names. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + groupNames() { + return Object.fromEntries(toGroupOptions(this.availableGroups).map((group) => [group.id, group.displayName])) + }, + + /** + * The include rules the last preview matched (REQ-CVUI-004). + * + * @return {Array<object>} the rules. + * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-004-preview-as-audience-and-date + */ + matchedIncludeRules() { + const ids = this.preview.state.result?.matchedIncludeRuleIds || [] + return this.includeRules.filter((r) => ids.includes(previewRuleId(r))) + }, + + /** + * The exclude rules the last preview matched (REQ-CVUI-004). + * + * @return {Array<object>} the rules. + * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-004-preview-as-audience-and-date + */ + matchedExcludeRules() { + const ids = this.preview.state.result?.matchedExcludeRuleIds || [] + return this.excludeRules.filter((r) => ids.includes(previewRuleId(r))) + }, + + /** + * The View as sentence for the last preview: whether the person + * sees the widget at the moment, and why. + * + * @return {string} the sentence, empty before a preview. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + sentence() { + if (!this.preview.state.result || !this.previewSubject) { + return '' + } + return visibilitySentence({ + ...this.previewSubject, + rules: this.rules.map((rule) => ({ ...rule, id: previewRuleId(rule) })), + result: this.preview.state.result, + groupNames: this.groupNames, + }) + }, + /** @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-003-legible-include-exclude-semantics */ includeRules() { return this.rules.filter((r) => r.isInclude !== false) @@ -265,27 +481,19 @@ export default { isEmpty() { return this.rules.length === 0 }, - - /** @spec openspec/specs/conditional-visibility-editor/spec.md */ - matchedIncludeRules() { - const ids = - (this.preview.state.result - && this.preview.state.result.matchedIncludeRuleIds) - || [] - return this.rules.filter((r) => ids.includes(r.id)) - }, - - /** @spec openspec/specs/conditional-visibility-editor/spec.md */ - matchedExcludeRules() { - const ids = - (this.preview.state.result - && this.preview.state.result.matchedExcludeRuleIds) - || [] - return this.rules.filter((r) => ids.includes(r.id)) - }, }, watch: { + /** + * Follow the placement's mode when it changes outside the dialog. + * + * @param {string} mode the stored mode. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + ruleMatch(mode) { + this.matchMode = mode === 'all' ? 'all' : 'any' + }, + placementId: { immediate: true, /** @spec openspec/specs/conditional-visibility-editor/spec.md */ @@ -327,22 +535,16 @@ export default { this.rules = [] return } + await this.loadRules() + }, + + /** Fetch the placement's rules, clearing them when the fetch fails. */ + async loadRules() { this.loading = true this.preview.reset() try { const { data } = await api.getWidgetRules(this.placementId) - const payload = - data && data.rules ? data : data && data.data ? data.data : {} - const list = Array.isArray(payload.rules) - ? payload.rules - : Array.isArray(data) - ? data - : [] - this.rules = list.map((r) => ({ - ...r, - id: r.id, - _localKey: undefined, - })) + this.rules = editableRules(rulesFromResponse(data)) } catch (error) { logger.error('Failed to load visibility rules:', error) this.rules = [] @@ -403,26 +605,9 @@ export default { this.setRowBusy(row, true) try { if (row.id !== null && row.id !== undefined) { - const { data } = await api.updateRule(row.id, payload) - const updated = data && data.data ? data.data : data - const index = this.rules.indexOf(row) - if (index !== -1) { - this.rules[index] = { ...row, ...updated } - } - this.$emit('ruleUpdated') + await this.updateSavedRule(row, payload) } else { - const { data } = await api.addWidgetRule( - this.placementId, - payload, - ) - const created = data && data.data ? data.data : data - const index = this.rules.indexOf(row) - if (index !== -1 && created && created.id) { - this.rules[index] = { ...created, _localKey: undefined } - } else { - await this.load() - } - this.$emit('ruleAdded') + await this.createDraftRule(row, payload) } } catch (error) { logger.error('Failed to save visibility rule:', error) @@ -431,6 +616,48 @@ export default { } }, + /** + * Write a persisted rule, merge the server's copy into its row and + * close the card's editor. + * + * @param {object} row The persisted rule row. + * @param {object} payload Rule fields to write. + * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-001-rule-builder-in-placement-settings + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + async updateSavedRule(row, payload) { + const { data } = await api.updateRule(row.id, payload) + const updated = unwrapData(data) + const index = this.rules.indexOf(row) + if (index !== -1) { + this.rules[index] = { ...row, ...updated } + } + this.editingKeys = { ...this.editingKeys, [this.rowKey(row)]: false } + this.$emit('ruleUpdated') + }, + + /** + * Create a draft rule and swap the draft row for the created rule; + * reload the list when the response carries no id. + * + * @param {object} row The draft rule row. + * @param {object} payload Rule fields to write. + */ + async createDraftRule(row, payload) { + const { data } = await api.addWidgetRule( + this.placementId, + payload, + ) + const created = unwrapData(data) + const index = this.rules.indexOf(row) + if (index !== -1 && created && created.id) { + this.rules[index] = { ...created, _localKey: undefined } + } else { + await this.load() + } + this.$emit('ruleAdded') + }, + /** * Remove a rule row. A never-persisted draft is discarded locally * with no API call; a saved rule is deleted server-side. @@ -459,41 +686,159 @@ export default { } }, - /** @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-004-preview-as-audience-and-date */ - async runPreview() { + /** + * Choose whether all rules or one rule must match, and save it on + * the placement; on a failed save the previous choice comes back. + * + * @param {string} mode `all` or `any`. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + async setMatchMode(mode) { + if (mode === this.matchMode || !MATCH_MODES.includes(mode)) { + return + } + const previous = this.matchMode + this.matchMode = mode + if (this.placementId === null || this.placementId === undefined) { + return + } + this.savingMatch = true try { - await this.preview.runPreview(this.rules, { - groups: this.previewGroups, - datetime: this.previewDatetime - ? new Date(this.previewDatetime).toISOString() - : null, - }) - } catch { - // Surfaced via preview.state.error in the template. + await api.updateWidgetPlacement(this.placementId, { ruleMatch: mode }) + this.$emit('ruleMatchChanged', mode) + } catch (error) { + logger.error('Failed to save how the visibility rules combine:', error) + this.matchMode = previous + } finally { + this.savingMatch = false } }, /** - * Short human-readable summary of a rule's config, used to indicate - * which rule matched in the preview result. + * Arrow keys on a choice card choose the other card and move the + * focus there, as in a radio group. * - * @param {object} rule the rule entity - * @spec openspec/specs/conditional-visibility-editor/spec.md - * @return {string} + * @param {KeyboardEvent} event the key press. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + async onModeKeydown(event) { + if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) { + return + } + event.preventDefault() + const other = this.matchMode === 'all' ? 'any' : 'all' + await this.setMatchMode(other) + await this.$nextTick() + this.$el.querySelector(`[data-test="rule-match-${this.matchMode}"]`)?.focus() + }, + + /** + * Whether a rule's card shows its editor: a draft always, a saved + * rule after Edit. + * + * @param {object} row The rule row. + * @return {boolean} true when the editor shows. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + isEditing(row) { + return row.id === null || row.id === undefined || !!this.editingKeys[this.rowKey(row)] + }, + + /** + * Open or close a saved rule's editor. + * + * @param {object} row The rule row. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + toggleEdit(row) { + const key = this.rowKey(row) + this.editingKeys = { ...this.editingKeys, [key]: !this.editingKeys[key] } + }, + + /** + * The kind of a rule, as its card names it. + * + * @param {object} row The rule row. + * @return {string} Groups, Times, Period or Profile field. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + kindLabel(row) { + return ruleKindLabel(row) + }, + + /** + * The groups a group rule names, as chips. + * + * @param {object} row The rule row. + * @return {string[]} the group names. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + groupNamesOf(row) { + return ruleGroupNames(row, this.groupNames) + }, + + /** + * The value of a time, period or profile field rule. + * + * @param {object} row The rule row. + * @return {string} the value. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 */ - describeRule(rule) { - const cfg = rule.ruleConfig || {} - switch (rule.ruleType) { - case 'group': - return (cfg.groups || []).join(', ') - case 'time': - return `${cfg.startTime || ''}–${cfg.endTime || ''}` - case 'date': - return `${cfg.startDate || '…'} → ${cfg.endDate || '…'}` - case 'attribute': - return `${cfg.attribute || ''} ${cfg.operator || ''} ${cfg.value || ''}` - default: - return '' + valueOf(row) { + return ruleValue(row) + }, + + /** + * Search people to view as; an empty search offers yourself again. + * The server ignores one-letter searches. + * + * @param {string} query The typed text. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + async onPersonSearch(query) { + const trimmed = (query || '').trim() + if (trimmed.length < 2) { + return + } + const seq = ++this.personSearchSeq + this.personLoading = true + try { + const { data } = await api.searchSharees(trimmed) + if (seq === this.personSearchSeq) { + const self = currentPerson() + this.personOptions = [...(self ? [self] : []), ...(data?.users || []).map((u) => ({ id: u.id, displayName: u.displayName || u.id }))] + } + } catch (error) { + logger.error('Person search failed:', error) + } finally { + this.personLoading = false + } + }, + + /** + * Preview the in-editor rules as the chosen person at the chosen + * moment, in the chosen match mode, and keep who and when for the + * sentence. + * + * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-004-preview-as-audience-and-date + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + async runPreview() { + const person = this.previewPerson + const moment = this.previewDatetime ? new Date(this.previewDatetime) : new Date() + try { + await this.preview.runPreview(this.rules, { + userId: person?.id || null, + datetime: moment.toISOString(), + match: this.matchMode, + placementId: this.placementId, + }) + this.previewSubject = { + name: person?.displayName || person?.id || '', + moment: formatMoment(moment, getLanguage()), + } + } catch { + // Surfaced via preview.state.error in the template. } }, }, @@ -507,10 +852,6 @@ export default { gap: 16px; } -.conditional-visibility-editor__hint { - color: var(--color-text-maxcontrast); - margin: 0; -} .conditional-visibility-editor__loading { display: flex; @@ -530,6 +871,102 @@ export default { display: flex; flex-direction: column; gap: 8px; + margin: 0; + padding: 0; + list-style: none; +} + +.conditional-visibility-editor__modes { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 8px; +} + +.conditional-visibility-editor__mode { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 16px; + border: 2px solid var(--color-border); + border-radius: var(--border-radius-large, 10px); + background: var(--color-main-background); + color: var(--color-main-text); + font: inherit; + text-align: start; + cursor: pointer; +} + +.conditional-visibility-editor__mode--active { + border-color: var(--color-primary-element); + font-weight: bold; +} + +.conditional-visibility-editor__mode:focus-visible { + outline: 2px solid var(--color-primary-element); + outline-offset: 2px; +} + +.conditional-visibility-editor__mode-dot { + flex: none; + width: 14px; + height: 14px; + border: 2px solid var(--color-border-maxcontrast); + border-radius: 50%; +} + +.conditional-visibility-editor__mode--active .conditional-visibility-editor__mode-dot { + border: 4px solid var(--color-primary-element); +} + +.conditional-visibility-editor__card { + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large, 10px); + padding: 8px 12px; +} + +.conditional-visibility-editor__card-head { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.conditional-visibility-editor__kind { + font-weight: bold; + min-width: 96px; +} + +.conditional-visibility-editor__chips { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.conditional-visibility-editor__chip { + padding: 2px 10px; + border-radius: var(--border-radius-pill, 16px); + background: var(--color-primary-element-light); + color: var(--color-primary-element-light-text); +} + +.conditional-visibility-editor__value { + color: var(--color-text-maxcontrast); +} + +.conditional-visibility-editor__card-actions { + display: flex; + gap: 4px; + margin-inline-start: auto; +} + +.conditional-visibility-editor__preview-sentence { + margin: 0; +} + +.conditional-visibility-editor__preview-reason { + margin: 4px 0 0; + color: var(--color-text-maxcontrast); + font-size: 13px; } .conditional-visibility-editor__preview { @@ -571,9 +1008,4 @@ export default { margin: 0 0 4px; } -.conditional-visibility-editor__preview-reason { - margin: 0; - color: var(--color-text-maxcontrast); - font-size: 13px; -} </style> diff --git a/src/components/Widgets/Renderers/ActivityReportWidget.vue b/src/components/Widgets/Renderers/ActivityReportWidget.vue new file mode 100644 index 000000000..a77669990 --- /dev/null +++ b/src/components/Widgets/Renderers/ActivityReportWidget.vue @@ -0,0 +1,406 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="activity-report" data-testid="activity-report-widget"> + <form class="activity-report__controls" @submit.prevent="load"> + <NcTextField + v-model="user" + :label="t('launchpad', 'Person (empty for yourself)')" + data-testid="activity-report-user" /> + <NcTextField + v-model="from" + type="date" + :label="t('launchpad', 'From')" + data-testid="activity-report-from" /> + <NcTextField + v-model="to" + type="date" + :label="t('launchpad', 'To')" + data-testid="activity-report-to" /> + <NcButton type="submit" variant="primary" :disabled="loading"> + {{ t('launchpad', 'Show activity') }} + </NcButton> + </form> + + <p + v-if="loading" + class="activity-report__state" + data-testid="activity-report-loading"> + {{ t('launchpad', 'Loading the activity report…') }} + </p> + + <p + v-else-if="loadFailed" + class="activity-report__state" + role="alert" + data-testid="activity-report-error"> + {{ t('launchpad', 'The activity report could not be loaded. Try again.') }} + </p> + + <p + v-else-if="refusal" + class="activity-report__notice" + role="alert" + data-testid="activity-report-refused"> + {{ refusal }} + </p> + + <template v-else-if="report"> + <p + v-if="report.purpose" + class="activity-report__purpose" + data-testid="activity-report-purpose"> + <strong>{{ t('launchpad', 'Purpose of this report') }}:</strong> + {{ report.purpose }} + </p> + + <p class="activity-report__summary" data-testid="activity-report-summary"> + {{ summary }} + </p> + + <p + v-if="!report.available" + class="activity-report__state" + data-testid="activity-report-unavailable"> + {{ t('launchpad', 'Activity reporting needs the Activity app.') }} + </p> + + <template v-else> + <table + v-if="countRows.length > 0" + class="activity-report__counts" + data-testid="activity-report-counts"> + <caption class="hidden-visually"> + {{ t('launchpad', 'Actions per activity type') }} + </caption> + <thead> + <tr> + <th scope="col"> + {{ t('launchpad', 'Activity type') }} + </th> + <th scope="col"> + {{ t('launchpad', 'Actions') }} + </th> + </tr> + </thead> + <tbody> + <tr v-for="row in countRows" :key="row.type"> + <td>{{ row.label }}</td> + <td>{{ row.count }}</td> + </tr> + </tbody> + <tfoot> + <tr> + <th scope="row"> + {{ t('launchpad', 'Total') }} + </th> + <td data-testid="activity-report-total"> + {{ report.total }} + </td> + </tr> + </tfoot> + </table> + + <ol + class="activity-report__calendar" + :aria-label="t('launchpad', 'Actions per day')" + data-testid="activity-report-calendar"> + <li + v-for="day in calendar" + :key="day.date" + class="activity-report__day" + :class="`activity-report__day--level-${day.level}`" + :title="day.label" + :aria-label="day.label" + :data-testid="`activity-report-day-${day.date}`" /> + </ol> + + <a + class="activity-report__export" + :href="csvUrl" + download + data-testid="activity-report-export"> + {{ t('launchpad', 'Download as CSV') }} + </a> + </template> + </template> + </div> +</template> + +<script> +import { translatePlural as n, translate as t } from '@nextcloud/l10n' +import { NcButton, NcTextField } from '@nextcloud/vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { activityReportCsvUrl, loadActivityReport } from '../../../services/activityReport.js' +import { logger } from '../../../utils/logger.js' + +const DEFAULT_DAYS = 30 +const MAX_DAYS = 366 +const DAY_MS = 86400000 + +/** + * A date as YYYY-MM-DD in UTC, the zone the server buckets in. + * + * @param {Date} date the date + * @return {string} the day + */ +function isoDay(date) { + return date.toISOString().slice(0, 10) +} + +/** + * Every day from `from` to `to`, both included, at most MAX_DAYS. + * + * @param {string} from first day + * @param {string} to last day + * @return {Array<string>} the days + */ +function daysBetween(from, to) { + const start = Date.parse(from + 'T00:00:00Z') + const end = Date.parse(to + 'T00:00:00Z') + if (Number.isNaN(start) || Number.isNaN(end) || end < start) { + return [] + } + const out = [] + for (let time = start; time <= end && out.length < MAX_DAYS; time += DAY_MS) { + out.push(isoDay(new Date(time))) + } + return out +} + +/** + * ActivityReportWidget: a person's activity over a period, as counts per + * activity type and a calendar of intensity per day (REQ-DWMS-006), with the + * purpose the administrator recorded whenever the report is about a named + * person (REQ-DWMS-005). Everything shown comes from the server, which also + * decides who may read whom and writes the audit entry; the CSV link asks the + * same endpoint for the same period, so its totals are the screen's. + */ +export default { + name: 'ActivityReportWidget', + components: { + NcButton, + NcTextField, + }, + + props: { + /** Persisted widget content: `{ days }`, the default period length. */ + content: OBJECT_PROP, + }, + + data() { + const days = Number(this.content?.days) + const length = Number.isInteger(days) && days >= 1 ? Math.min(days, MAX_DAYS) : DEFAULT_DAYS + const today = new Date() + return { + user: '', + from: isoDay(new Date(today.getTime() - (length - 1) * DAY_MS)), + to: isoDay(today), + loading: true, + loadFailed: false, + refusal: '', + report: null, + } + }, + + computed: { + /** + * Who, which period and how many actions, from the server's answer. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 + */ + summary() { + const report = this.report + if (report.self) { + return n( + 'launchpad', + 'Your activity from {from} to {to}: {count} action', + 'Your activity from {from} to {to}: {count} actions', + report.total, + { from: report.from, to: report.to, count: report.total }, + ) + } + return n( + 'launchpad', + 'Activity of {person} from {from} to {to}: {count} action', + 'Activity of {person} from {from} to {to}: {count} actions', + report.total, + { person: report.subject, from: report.from, to: report.to, count: report.total }, + ) + }, + + /** + * @return {Array<{type: string, label: string, count: number}>} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 + */ + countRows() { + return Object.entries(this.report?.counts ?? {}).map(([type, count]) => ({ + type, + label: type.replace(/_/g, ' '), + count: Number(count) || 0, + })) + }, + + /** + * One cell per day of the period, a day without activity at level 0. + * + * @return {Array<{date: string, count: number, level: number, label: string}>} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 + */ + calendar() { + const days = this.report?.days ?? {} + const busiest = Math.max(0, ...Object.values(days).map((value) => Number(value) || 0)) + return daysBetween(this.report.from, this.report.to).map((date) => { + const count = Number(days[date]) || 0 + const level = count === 0 || busiest === 0 ? 0 : Math.max(1, Math.ceil((count / busiest) * 4)) + return { + date, + count, + level, + label: n('launchpad', '{date}: {count} action', '{date}: {count} actions', count, { date, count }), + } + }) + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.6 */ + csvUrl() { + // The report as shown, not the fields as edited since. + return activityReportCsvUrl({ user: this.report.self ? '' : this.report.subject, from: this.report.from, to: this.report.to }) + }, + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 */ + async created() { + await this.load() + }, + + methods: { + t, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 */ + async load() { + this.loading = true + this.loadFailed = false + this.refusal = '' + try { + const result = await loadActivityReport({ user: this.user, from: this.from, to: this.to }) + if (result.refused) { + this.report = null + this.refusal = this.refusalText(result) + } else { + this.report = result + } + } catch (error) { + logger.error('Failed to load the activity report:', error) + this.report = null + this.loadFailed = true + } finally { + this.loading = false + } + }, + + /** + * Why the server refused, in the reader's language. + * + * @param {{status: number, enabled: boolean}} refusal the refusal + * @return {string} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 + */ + refusalText(refusal) { + if (refusal.status === 400) { + return t('launchpad', 'Choose a first and a last day, the last after the first, at most {max} days apart.', { max: MAX_DAYS }) + } + if (!refusal.enabled) { + return t('launchpad', 'Activity reporting on named people is off. An administrator can turn it on in the LaunchPad admin settings, recording the purpose it serves. You can always see your own activity.') + } + return t('launchpad', 'Only an administrator can read another person\'s activity. You can always see your own.') + }, + }, +} +</script> + +<style scoped> +.activity-report { + display: flex; + flex-direction: column; + gap: 8px; + height: 100%; + overflow-y: auto; + padding: 4px 12px 12px; +} + +.activity-report__controls { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 8px; +} + +.activity-report__state, +.activity-report__summary { + color: var(--color-text-maxcontrast); + margin: 0; +} + +.activity-report__notice, +.activity-report__purpose { + margin: 0; + padding: 8px 12px; + border-radius: var(--border-radius-large); + background-color: var(--color-primary-element-light); + color: var(--color-primary-element-light-text); +} + +.activity-report__counts { + border-collapse: collapse; + width: 100%; +} + +.activity-report__counts th, +.activity-report__counts td { + padding: 4px 8px; + text-align: start; + border-bottom: 1px solid var(--color-border); +} + +.activity-report__calendar { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(14px, 1fr)); + gap: 3px; + list-style: none; + margin: 0; + padding: 0; +} + +.activity-report__day { + aspect-ratio: 1; + border-radius: 2px; + border: 1px solid var(--color-border-dark); + background-color: var(--color-background-dark); +} + +.activity-report__day--level-1 { + background-color: var(--color-primary-element-light); +} + +.activity-report__day--level-2 { + background-color: var(--color-primary-element-light-hover); +} + +.activity-report__day--level-3 { + background-color: var(--color-primary-element-hover); +} + +.activity-report__day--level-4 { + background-color: var(--color-primary-element); +} + +.activity-report__export { + color: var(--color-primary-element); + text-decoration: underline; +} +</style> diff --git a/src/components/Widgets/Renderers/ActivityReportWidgetForm.vue b/src/components/Widgets/Renderers/ActivityReportWidgetForm.vue new file mode 100644 index 000000000..1bb2093e0 --- /dev/null +++ b/src/components/Widgets/Renderers/ActivityReportWidgetForm.vue @@ -0,0 +1,99 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="activity-report-form"> + <p class="activity-report-form__hint"> + {{ + t( + 'launchpad', + 'Shows activity per type and per day. Anybody can see their own; another person\'s activity needs activity reporting turned on by an administrator, shows its purpose and is logged.', + ) + }} + </p> + + <NcSelect + :modelValue="days" + :options="dayOptions" + :inputLabel="t('launchpad', 'Days shown at first')" + :clearable="false" + @update:modelValue="updateDays" /> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcSelect } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' + +const DEFAULT_DAYS = 30 +const DAY_OPTIONS = [7, 30, 90, 365] + +/** + * ActivityReportWidgetForm: the period the activity report opens on + * (dashboards-and-who-may-see-them REQ-DWMS-006). Who is reported on is + * chosen in the widget itself, never stored on the placement. + */ +export default { + name: 'ActivityReportWidgetForm', + + components: { NcSelect }, + + props: { + /** The placement being edited, when there is one. */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** The content to start from: `{ days }`. */ + value: objectProp({ days: DEFAULT_DAYS }), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + dayOptions: DAY_OPTIONS, + days: DAY_OPTIONS.includes(Number(initial.days)) ? Number(initial.days) : DEFAULT_DAYS, + } + }, + + methods: { + t, + + /** + * @param {number} days the chosen period length + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 + */ + updateDays(days) { + this.days = DAY_OPTIONS.includes(Number(days)) ? Number(days) : DEFAULT_DAYS + this.$emit('update:content', { days: this.days }) + }, + + /** + * @return {Array<string>} nothing to refuse: every option is valid + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 + */ + validate() { + return [] + }, + }, +} +</script> + +<style scoped> +.activity-report-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.activity-report-form__hint { + color: var(--color-text-maxcontrast); + margin: 0; +} +</style> diff --git a/src/components/Widgets/Renderers/AiAssistantWidget.vue b/src/components/Widgets/Renderers/AiAssistantWidget.vue index 990aeb507..f1be4f66a 100644 --- a/src/components/Widgets/Renderers/AiAssistantWidget.vue +++ b/src/components/Widgets/Renderers/AiAssistantWidget.vue @@ -23,15 +23,15 @@ class="ai-assistant__messages" aria-live="polite"> <li - v-for="(message, index) in chat.messages" + v-for="(message, index) in chat.state.messages" :key="index" :class="`ai-assistant__message ai-assistant__message--${message.role}`"> {{ message.content }} </li> <li - v-if="chat.isStreaming" + v-if="chat.state.isStreaming" class="ai-assistant__message ai-assistant__message--assistant"> - {{ chat.currentText || t('launchpad', 'Thinking…') }} + {{ chat.state.currentText || t('launchpad', 'Thinking…') }} </li> </ol> <p @@ -41,11 +41,11 @@ {{ lastAnswer }} </p> <p - v-if="chat.error" + v-if="chat.state.error" class="ai-assistant__error" role="alert" data-testid="ai-assistant-error"> - {{ chat.error.message }} + {{ chat.state.error.message }} </p> <form v-if="!summaryMode" @@ -58,14 +58,14 @@ :id="inputId" v-model="question" type="text" - :disabled="available !== true || chat.isStreaming" + :disabled="available !== true || chat.state.isStreaming" :placeholder="t('launchpad', 'Ask about this dashboard')" data-testid="ai-assistant-input" /> <button type="submit" :disabled=" available !== true - || chat.isStreaming + || chat.state.isStreaming || question.trim() === '' " data-testid="ai-assistant-send"> @@ -75,7 +75,7 @@ <button v-else type="button" - :disabled="available !== true || chat.isStreaming" + :disabled="available !== true || chat.state.isStreaming" data-testid="ai-assistant-summarise" @click="summarise"> {{ t('launchpad', 'Summarise this dashboard') }} @@ -88,6 +88,10 @@ import { chatHealthUrl, useAiChatStream } from '@conduction/nextcloud-vue' import axios from '@nextcloud/axios' import { translate as t } from '@nextcloud/l10n' +import { + NULLABLE_OBJECT_PROP, + OBJECT_PROP, +} from '../../../constants/propDefinitions.js' import { useDashboardStore } from '../../../stores/dashboard.js' /** The fleet's chat engine. */ @@ -124,16 +128,10 @@ export default { props: { /** Persisted content: `{agentUuid?}`. */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** The placement (`gridWidth`, `gridHeight`). */ - placement: { - type: Object, - default: null, - }, + placement: NULLABLE_OBJECT_PROP, }, /** @spec openspec/specs/launchpad-ai-dashboard-assistant/spec.md */ @@ -177,9 +175,9 @@ export default { * @spec openspec/specs/launchpad-ai-dashboard-assistant/spec.md */ lastAnswer() { - const answers = this.chat.messages.filter((m) => m.role === 'assistant') - return this.chat.isStreaming - ? this.chat.currentText + const answers = this.chat.state.messages.filter((m) => m.role === 'assistant') + return this.chat.state.isStreaming + ? this.chat.state.currentText : (answers[answers.length - 1]?.content ?? '') }, }, @@ -214,7 +212,7 @@ export default { agentUuid: this.content?.agentUuid || '', }) } catch { - // chat.error carries the message the widget shows. + // chat.state.error carries the message the widget shows. } }, @@ -234,7 +232,7 @@ export default { { agentUuid: this.content?.agentUuid || '' }, ) } catch { - // chat.error carries the message the widget shows. + // chat.state.error carries the message the widget shows. } }, }, diff --git a/src/components/Widgets/Renderers/AiAssistantWidgetForm.vue b/src/components/Widgets/Renderers/AiAssistantWidgetForm.vue index 28fe18879..711ba08b2 100644 --- a/src/components/Widgets/Renderers/AiAssistantWidgetForm.vue +++ b/src/components/Widgets/Renderers/AiAssistantWidgetForm.vue @@ -26,6 +26,10 @@ <script> import { translate as t } from '@nextcloud/l10n' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' /** * AiAssistantWidgetForm: the assistant widget's settings, the Hermiq agent @@ -37,15 +41,9 @@ export default { name: 'AiAssistantWidgetForm', props: { - editingWidget: { - type: Object, - default: null, - }, + editingWidget: NULLABLE_OBJECT_PROP, - value: { - type: Object, - default: () => ({ agentUuid: '' }), - }, + value: objectProp({ agentUuid: '' }), }, emits: ['update:content'], diff --git a/src/components/Widgets/Renderers/AnnouncementsWidget.vue b/src/components/Widgets/Renderers/AnnouncementsWidget.vue new file mode 100644 index 000000000..8745e28a0 --- /dev/null +++ b/src/components/Widgets/Renderers/AnnouncementsWidget.vue @@ -0,0 +1,369 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <section class="announcements-widget" data-test="announcements-widget"> + <div class="announcements-widget__toolbar"> + <NcSelect + v-model="category" + :options="categoryOptions" + :inputLabel="t('launchpad', 'Category')" + :reduce="(option) => option.value" + label="label" + :clearable="false" + data-test="announcements-category" /> + <NcButton + v-if="category" + variant="secondary" + data-test="announcements-follow" + @click="toggleFollow(category)"> + {{ isFollowed(category) ? t('launchpad', 'Unfollow {category}', { category }) : t('launchpad', 'Follow {category}', { category }) }} + </NcButton> + <NcButton + v-if="canAuthor" + variant="primary" + data-test="announcements-new" + @click="editorOpen = true"> + {{ t('launchpad', 'New announcement') }} + </NcButton> + </div> + + <p v-if="error" class="announcements-widget__empty" role="alert"> + {{ error }} + </p> + <p v-else-if="!loading && shown.length === 0" class="announcements-widget__empty"> + {{ t('launchpad', 'No announcements') }} + </p> + + <ul class="announcements-widget__list"> + <li v-for="item in shown" :key="item.uuid"> + <AnnouncementCard + :announcement="item" + :reactions="reactionsOf(item.uuid)" + :confirmed="readConfirmations.confirmed.includes(item.uuid)" + :canReport="readConfirmations.receipts.includes(item.uuid)" + @toggleLike="toggleLike" + @openComments="openComments" + @confirmRead="confirmRead" + @openReceipts="openReceipts"> + <div v-if="openUuid === item.uuid" class="announcements-widget__comments" data-test="announcement-comment-list"> + <ul> + <li v-for="comment in comments" :key="comment.id"> + <strong>{{ comment.displayName }}</strong> {{ comment.message }} + </li> + </ul> + <form v-if="item.allowComments" class="announcements-widget__comment-form" @submit.prevent="sendComment(item.uuid)"> + <NcTextField + v-model="draftComment" + :label="t('launchpad', 'Write a comment')" + :maxlength="1000" + data-test="announcement-comment-input" /> + <NcButton type="submit" variant="primary" :disabled="draftComment.trim() === ''"> + {{ t('launchpad', 'Send') }} + </NcButton> + </form> + <p v-else class="announcements-widget__empty"> + {{ t('launchpad', 'Comments are closed') }} + </p> + </div> + </AnnouncementCard> + </li> + </ul> + + <AcknowledgementReportModal + :open="receiptsItem !== null" + :announcementUuid="receiptsItem ? receiptsItem.uuid : ''" + :title="receiptsItem ? receiptsItem.title : ''" + @close="receiptsItem = null" /> + + <AnnouncementEditorModal + v-if="editorOpen" + @close="editorOpen = false" + @published="onPublished" /> + </section> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcButton, NcSelect, NcTextField } from '@nextcloud/vue' +import AcknowledgementReportModal from '../../../modals/AcknowledgementReportModal.vue' +import AnnouncementEditorModal from '../../../modals/AnnouncementEditorModal.vue' +import AnnouncementCard from '../../Announcements/AnnouncementCard.vue' +import { announcementsApi } from '../../../services/announcementsApi.js' +import { logger } from '../../../utils/logger.js' + +/** + * The read confirmation state of the list: the uuids the reader confirmed + * and the ones whose read confirmations the reader may open (REQ-ANN-007). + * + * @param {object|undefined} state `{confirmed, receipts}` from the server. + * @return {{confirmed: Array<string>, receipts: Array<string>}} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ +export function readConfirmationState(state) { + const list = (value) => (Array.isArray(value) ? value.filter((uuid) => typeof uuid === 'string') : []) + return { confirmed: list(state?.confirmed), receipts: list(state?.receipts) } +} + +/** + * AnnouncementsWidget — the news announcements that reach the reader, + * newest first, with a category filter, like and comment counts, comments, + * and follow per category (REQ-ANN-001..003). Notices are not listed here; + * they show as banners above the grid (REQ-ANN-005). Authors get a "New + * announcement" button that opens the editor with its preview step. A + * reader confirms "I have read this"; the author opens who confirmed + * (REQ-ANN-007). + * + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + * + * @spec openspec/changes/engagement-announcements/specs/announcements/spec.md#requirement-readers-like-and-comment-through-nextcloud-comments-req-ann-002 + */ +export default { + name: 'AnnouncementsWidget', + + components: { AcknowledgementReportModal, AnnouncementCard, AnnouncementEditorModal, NcButton, NcSelect, NcTextField }, + + props: { + /** Placement content: `category` (initial filter) and `limit`. */ + content: { + type: Object, + default: () => ({}), + }, + }, + + data() { + return { + loading: true, + error: '', + announcements: [], + reactions: {}, + followed: [], + canAuthor: false, + category: this.content?.category ?? '', + openUuid: '', + comments: [], + draftComment: '', + editorOpen: false, + readConfirmations: { confirmed: [], receipts: [] }, + receiptsItem: null, + } + }, + + computed: { + /** @return {Array<object>} News items, newest first, filtered and limited. */ + shown() { + const limit = Number(this.content?.limit) > 0 ? Number(this.content.limit) : 10 + return this.announcements + .filter((item) => item.kind !== 'notice') + .filter((item) => this.category === '' || item.category === this.category) + .slice(0, limit) + }, + + /** @return {Array<string>} The categories of the announcements and the followed ones. */ + categories() { + const all = new Set(this.followed) + this.announcements.forEach((item) => item.category && all.add(item.category)) + return [...all].sort() + }, + + /** @return {Array<object>} */ + categoryOptions() { + return [ + { value: '', label: t('launchpad', 'All categories') }, + ...this.categories.map((name) => ({ value: name, label: name })), + ] + }, + }, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-7 */ + created() { + this.load() + }, + + methods: { + t, + + /** + * @spec openspec/changes/engagement-announcements/tasks.md#task-7 + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + async load() { + this.loading = true + try { + // The read state is asked beside the list, never after it (REQ-ANN-007). + const [data, readState] = await Promise.all([ + announcementsApi.list(), + announcementsApi.readState().catch((error) => { + logger.error('Failed to load the read confirmations:', error) + return null + }), + ]) + this.announcements = Array.isArray(data.announcements) ? data.announcements : [] + this.reactions = data.reactions ?? {} + this.followed = Array.isArray(data.followedCategories) ? data.followedCategories : [] + this.canAuthor = data.canAuthor === true + this.readConfirmations = readConfirmationState(readState) + this.error = '' + } catch (error) { + logger.error('Failed to load announcements:', error) + this.error = t('launchpad', 'Announcements could not be loaded') + } finally { + this.loading = false + } + }, + + /** + * @param {string} uuid The announcement. + * @return {object} `{likes, comments, liked}`. + */ + reactionsOf(uuid) { + return { likes: 0, comments: 0, liked: false, ...(this.reactions[uuid] ?? {}) } + }, + + /** + * @param {string} uuid The announcement. + * @spec openspec/changes/engagement-announcements/tasks.md#task-7 + */ + async toggleLike(uuid) { + const current = this.reactionsOf(uuid) + try { + const state = current.liked ? await announcementsApi.unlike(uuid) : await announcementsApi.like(uuid) + this.reactions = { ...this.reactions, [uuid]: { ...current, ...state } } + } catch (error) { + logger.error('Failed to change the like:', error) + } + }, + + /** + * @param {string} uuid The announcement. + * @spec openspec/changes/engagement-announcements/tasks.md#task-7 + */ + async openComments(uuid) { + if (this.openUuid === uuid) { + this.openUuid = '' + return + } + this.openUuid = uuid + this.draftComment = '' + try { + this.comments = await announcementsApi.comments(uuid) + } catch (error) { + logger.error('Failed to load comments:', error) + this.comments = [] + } + }, + + /** + * @param {string} uuid The announcement. + * @spec openspec/changes/engagement-announcements/tasks.md#task-7 + */ + async sendComment(uuid) { + const message = this.draftComment.trim() + if (message === '') { + return + } + try { + const comment = await announcementsApi.comment(uuid, message) + this.comments = [...this.comments, comment] + const current = this.reactionsOf(uuid) + this.reactions = { ...this.reactions, [uuid]: { ...current, comments: current.comments + 1 } } + this.draftComment = '' + } catch (error) { + logger.error('Failed to send the comment:', error) + } + }, + + /** + * @param {string} category The category. + * @return {boolean} + */ + isFollowed(category) { + return this.followed.includes(category) + }, + + /** + * @param {string} category The category. + * @spec openspec/changes/engagement-announcements/tasks.md#task-10 + */ + async toggleFollow(category) { + try { + this.followed = this.isFollowed(category) + ? await announcementsApi.unfollow(category) + : await announcementsApi.follow(category) + } catch (error) { + logger.error('Failed to change the follow:', error) + } + }, + + /** + * "I have read this": confirm, then the card says so. + * + * @param {string} uuid The announcement. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + async confirmRead(uuid) { + try { + await announcementsApi.confirmRead(uuid) + if (!this.readConfirmations.confirmed.includes(uuid)) { + this.readConfirmations = { ...this.readConfirmations, confirmed: [...this.readConfirmations.confirmed, uuid] } + } + } catch (error) { + logger.error('Failed to confirm the announcement:', error) + this.error = t('launchpad', 'Your read confirmation could not be saved') + } + }, + + /** + * Open the read confirmations of one announcement. + * + * @param {string} uuid The announcement. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + openReceipts(uuid) { + this.receiptsItem = this.announcements.find((item) => item.uuid === uuid) ?? null + }, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-8 */ + onPublished() { + this.editorOpen = false + this.load() + }, + }, +} +</script> + +<style scoped> +.announcements-widget { + display: flex; + flex-direction: column; + gap: 8px; + height: 100%; + overflow: auto; +} + +.announcements-widget__toolbar { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 8px; +} + +.announcements-widget__list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.announcements-widget__empty { + color: var(--color-text-maxcontrast); +} + +.announcements-widget__comment-form { + display: flex; + align-items: flex-end; + gap: 8px; +} +</style> diff --git a/src/components/Widgets/Renderers/AnnouncementsWidgetForm.vue b/src/components/Widgets/Renderers/AnnouncementsWidgetForm.vue new file mode 100644 index 000000000..399477abf --- /dev/null +++ b/src/components/Widgets/Renderers/AnnouncementsWidgetForm.vue @@ -0,0 +1,94 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="announcements-widget-form"> + <NcTextField + :modelValue="category" + :label="t('launchpad', 'Show one category (empty for all)')" + @update:modelValue="set('category', $event)" /> + <NcTextField + :modelValue="String(limit)" + type="number" + :label="t('launchpad', 'Number of announcements (1–50)')" + @update:modelValue="setLimit($event)" /> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcTextField } from '@nextcloud/vue' +import { NULLABLE_OBJECT_PROP, objectProp } from '../../../constants/propDefinitions.js' + +export const DEFAULT_CONTENT = Object.freeze({ category: '', limit: 10 }) + +/** + * AnnouncementsWidgetForm — the initial category filter and the number of + * announcements of an Announcements widget (engagement-announcements task 7). + * Emits `update:content` on every change. + * + * @spec openspec/changes/engagement-announcements/tasks.md#task-7 + */ +export default { + name: 'AnnouncementsWidgetForm', + + components: { NcTextField }, + + props: { + /** The placement being edited, or `null` in create mode. */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** Initial content values (registry defaults when not editing). */ + value: objectProp(DEFAULT_CONTENT), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + category: typeof initial.category === 'string' ? initial.category : '', + limit: Number(initial.limit) > 0 ? Math.min(50, Number(initial.limit)) : DEFAULT_CONTENT.limit, + } + }, + + methods: { + t, + + /** + * @param {string} field The field. + * @param {string} value The value. + * @spec openspec/changes/engagement-announcements/tasks.md#task-7 + */ + set(field, value) { + this[field] = String(value ?? '').trim() + this.emitUpdate() + }, + + /** + * @param {string} value The typed number. + * @spec openspec/changes/engagement-announcements/tasks.md#task-7 + */ + setLimit(value) { + const parsed = parseInt(value, 10) + this.limit = Number.isNaN(parsed) ? DEFAULT_CONTENT.limit : Math.min(50, Math.max(1, parsed)) + this.emitUpdate() + }, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-7 */ + emitUpdate() { + this.$emit('update:content', { category: this.category, limit: this.limit }) + }, + }, +} +</script> + +<style scoped> +.announcements-widget-form { + display: flex; + flex-direction: column; + gap: 12px; +} +</style> diff --git a/src/components/Widgets/Renderers/AssignedCasesWidget.vue b/src/components/Widgets/Renderers/AssignedCasesWidget.vue new file mode 100644 index 000000000..cfedc8da4 --- /dev/null +++ b/src/components/Widgets/Renderers/AssignedCasesWidget.vue @@ -0,0 +1,163 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="assigned-cases-widget" data-testid="assigned-cases-widget"> + <p v-if="!caseApp" class="assigned-cases-widget__state" data-testid="assigned-cases-no-app"> + {{ t('launchpad', 'My cases needs dossiq. Ask your administrator to enable it.') }} + </p> + <template v-else> + <CnStatusList + :items="items" + :counts="state === 'ok' ? counts : []" + :loading="state === 'loading'" + :error="state === 'error' ? t('launchpad', 'The cases could not be loaded. Try again later.') : ''" + :emptyLabel="t('launchpad', 'No open cases are assigned to you')" /> + <a + v-if="state === 'ok' && total > items.length" + :href="allCasesUrl" + class="assigned-cases-widget__all" + data-testid="assigned-cases-all"> + {{ n('launchpad', 'All %n open case', 'All %n open cases', total) }} + </a> + </template> + </div> +</template> + +<script> +import { CnStatusList } from '@conduction/nextcloud-vue' +import { getCurrentUser } from '@nextcloud/auth' +import { translatePlural as n, translate as t } from '@nextcloud/l10n' +import { generateUrl } from '@nextcloud/router' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { loadAssignedCases } from '../../../services/assignedCases.js' + +/** + * AssignedCasesWidget: the `assigned-cases` widget (board LpWerkplek "Mijn + * zaken"). The open cases assigned to the viewer, deadline first, each with + * its deadline and status, under the counts per status. The cases come from + * OpenRegister with the viewer's session; each opens in the case app. + * + * The case app is the one the initial state's `integrationApps.dossiq` names, + * the id dossiq is installed under, so a renamed install keeps working. + * + * `content`: `{ register, schema, limit }`, by default dossiq's `dossiq` + * register and `case` schema and 4 cases. + * + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md + */ +export default { + name: 'AssignedCasesWidget', + + components: { CnStatusList }, + + inject: { + /** Which apps behind the integration widgets are enabled for the viewer. */ + integrationApps: { from: 'integrationApps', default: () => ({}) }, + }, + + props: { + /** Persisted widget content: `{ register, schema, limit }`, see the component description. */ + content: OBJECT_PROP, + // The placement row is bound on every renderer; declared so it stays out of $attrs. + // eslint-disable-next-line vue/no-unused-properties + placement: OBJECT_PROP, + }, + + data() { + return { + state: 'loading', + cases: [], + counts: [], + total: 0, + } + }, + + computed: { + /** + * @return {string} The id the case app is installed under, '' without it. + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-is-offered-only-with-dossiq-req-cases-004 + */ + caseApp() { + const app = this.integrationApps?.dossiq + return typeof app === 'string' ? app : '' + }, + + /** + * @return {number} How many cases show. + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-lists-the-viewers-open-cases-deadline-first-req-cases-001 + */ + limit() { + const limit = Number(this.content?.limit) + return Number.isInteger(limit) && limit > 0 ? Math.min(limit, 20) : 4 + }, + + /** + * The first cases as list items: title as a link into the case app, + * the case number as detail, the deadline and the status. + * + * @return {Array<object>} + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-lists-the-viewers-open-cases-deadline-first-req-cases-001 + */ + items() { + return this.cases.slice(0, this.limit).map((record) => ({ + id: record.id, + title: record.title, + href: generateUrl('/apps/{app}/cases/{id}', { app: this.caseApp, id: record.id }), + meta: record.identifier, + due: record.deadline, + status: record.status.label ? { label: record.status.label, variant: record.status.variant } : null, + })) + }, + + /** + * @return {string} The case app's list of cases. + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-lists-the-viewers-open-cases-deadline-first-req-cases-001 + */ + allCasesUrl() { + return generateUrl('/apps/{app}/cases', { app: this.caseApp }) + }, + }, + + /** @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-lists-the-viewers-open-cases-deadline-first-req-cases-001 */ + async created() { + if (!this.caseApp) { + return + } + const result = await loadAssignedCases({ + register: String(this.content?.register || 'dossiq'), + schema: String(this.content?.schema || 'case'), + userId: getCurrentUser()?.uid || '', + }) + this.cases = result.cases + this.counts = result.counts + this.total = result.total + this.state = result.state + }, + + methods: { t, n }, +} +</script> + +<style scoped> +.assigned-cases-widget { + display: flex; + flex-direction: column; + gap: 8px; + height: 100%; + min-height: 0; + overflow-y: auto; +} + +.assigned-cases-widget__state { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.assigned-cases-widget__all { + color: var(--color-primary-element); + text-decoration: underline; +} +</style> diff --git a/src/components/Widgets/Renderers/AssignedCasesWidgetForm.vue b/src/components/Widgets/Renderers/AssignedCasesWidgetForm.vue new file mode 100644 index 000000000..a11306ecf --- /dev/null +++ b/src/components/Widgets/Renderers/AssignedCasesWidgetForm.vue @@ -0,0 +1,122 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="assigned-cases-widget-form"> + <p class="assigned-cases-widget-form__hint"> + {{ t('launchpad', 'Shows the open cases assigned to the person viewing, from the register below. Each person sees what OpenRegister lets them see.') }} + </p> + <NcTextField + :modelValue="register" + :label="t('launchpad', 'Register')" + data-testid="assigned-cases-form-register" + @update:modelValue="update({ register: String($event) })" /> + <NcTextField + :modelValue="schema" + :label="t('launchpad', 'Schema')" + data-testid="assigned-cases-form-schema" + @update:modelValue="update({ schema: String($event) })" /> + <NcTextField + :modelValue="String(limit)" + type="number" + min="1" + max="20" + :label="t('launchpad', 'Number of cases')" + data-testid="assigned-cases-form-limit" + @update:modelValue="update({ limit: Number($event) })" /> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcTextField } from '@nextcloud/vue' +import { NULLABLE_OBJECT_PROP, objectProp } from '../../../constants/propDefinitions.js' + +/** + * AssignedCasesWidgetForm: the register and schema the `assigned-cases` + * widget reads (dossiq's `dossiq` and `case` by default) and how many cases + * it lists. + * + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-names-its-data-source-req-cases-003 + */ +export default { + name: 'AssignedCasesWidgetForm', + + components: { NcTextField }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** + * Initial content values, used when not editing. + * + * @type {object} + */ + value: objectProp({ register: 'dossiq', schema: 'case', limit: 4 }), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + register: String(initial.register || 'dossiq'), + schema: String(initial.schema || 'case'), + limit: Number.isInteger(initial.limit) && initial.limit > 0 ? initial.limit : 4, + } + }, + + methods: { + t, + + /** + * Keep a change and tell the modal the whole content. + * + * @param {object} change The changed keys. + * @return {void} + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-names-its-data-source-req-cases-003 + */ + update(change) { + Object.assign(this, change) + this.$emit('update:content', { register: this.register.trim(), schema: this.schema.trim(), limit: this.limit }) + }, + + /** + * Validate: a register and a schema, and 1 to 20 cases. + * + * @return {string[]} The validation errors. + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-names-its-data-source-req-cases-003 + */ + validate() { + const errors = [] + if (this.register.trim() === '' || this.schema.trim() === '') { + errors.push(t('launchpad', 'Name the register and the schema')) + } + if (!Number.isInteger(this.limit) || this.limit < 1 || this.limit > 20) { + errors.push(t('launchpad', 'Show 1 to 20 cases')) + } + return errors + }, + }, +} +</script> + +<style scoped> +.assigned-cases-widget-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.assigned-cases-widget-form__hint { + margin: 0; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/AttentionWidget.vue b/src/components/Widgets/Renderers/AttentionWidget.vue new file mode 100644 index 000000000..b2035c31f --- /dev/null +++ b/src/components/Widgets/Renderers/AttentionWidget.vue @@ -0,0 +1,517 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div + class="attention-widget" + :class="{ 'attention-widget--columns': isColumns }" + :style="isColumns ? { '--attention-columns': columns } : undefined" + data-testid="attention-widget"> + <div v-if="heading" class="attention-widget__head"> + <h2 class="attention-widget__heading"> + {{ heading }} + </h2> + <span + v-if="state === 'items'" + class="attention-widget__summary" + data-testid="attention-summary"> + {{ + n( + 'launchpad', + '%n thing from all your apps that needs attention today', + '%n things from all your apps that need attention today', + visibleItems.length, + ) + }} + </span> + </div> + <div + v-if="state === 'loading'" + class="attention-widget__state" + data-testid="attention-loading"> + {{ t('launchpad', 'Checking your apps…') }} + </div> + + <div + v-else-if="state === 'error'" + class="attention-widget__state attention-widget__state--failed" + role="alert" + data-testid="attention-error"> + {{ + t( + 'launchpad', + 'This list could not be loaded. Reload the page to try again.', + ) + }} + </div> + + <template v-else> + <!-- The columns layout shows at most a handful of items side by side and + draws no filter field (LpVandaag "Vandaag eerst"). --> + <WidgetRowFilter v-if="items.length > 0 && !isColumns" v-model="rowFilter" /> + <ul + v-if="visibleItems.length > 0" + class="attention-widget__list" + data-testid="attention-list"> + <li + v-for="item in visibleItems" + :key="item.key" + class="attention-widget__item" + :class="`attention-widget__item--${item.severity}`" + :data-testid="`attention-item-${item.appId}-${item.id}`"> + <span class="attention-widget__text"> + <strong class="attention-widget__title"> + <span class="attention-widget__sr">{{ + severityLabel(item.severity) + }}</span> + {{ item.title }} + </strong> + <span class="attention-widget__reason">{{ + item.reason + }}</span> + </span> + <span class="attention-widget__app">{{ item.appName }}</span> + <a class="attention-widget__action" :href="item.href"> + {{ item.actionLabel }} + </a> + </li> + </ul> + + <p + v-if="hiddenCount > 0" + class="attention-widget__more" + data-testid="attention-more"> + {{ t('launchpad', 'And {count} more.', { count: hiddenCount }) }} + </p> + + <!-- Only when EVERY source was checked. With a failure in the mix + this sentence would be a claim nobody verified (REQ-ATT-005). --> + <p + v-if="state === 'clear'" + class="attention-widget__state" + data-testid="attention-clear"> + {{ t('launchpad', 'Nothing needs your attention right now.') }} + </p> + + <p + v-if="state === 'none'" + class="attention-widget__state" + data-testid="attention-none"> + {{ + t('launchpad', 'None of your apps reports attention items yet.') + }} + </p> + + <p + v-if="failedApps.length > 0" + class="attention-widget__failed" + role="status" + data-testid="attention-failed"> + {{ + t('launchpad', 'Could not check: {apps}', { + apps: failedApps.join(', '), + }) + }} + </p> + </template> + </div> +</template> + +<script> +import { translatePlural as n, translate as t } from '@nextcloud/l10n' +import WidgetRowFilter from '../WidgetRowFilter.vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { expandToRecords, loadAttentionFeed } from '../../../services/attentionFeed.js' +import { logger } from '../../../utils/logger.js' +import { filterRows } from '../../../utils/rowFilter.js' + +const DEFAULT_LIMIT = 5 +const MAX_LIMIT = 10 + +/** + * AttentionWidget — "First today": what needs the employee's attention, from + * all their apps, in one ranked list with a link into each app + * (openspec/specs/attention-feed). + * + * The widget has five states and keeps three of them apart on purpose: + * `clear` (every source checked, nothing to do), `none` (no app declares + * anything) and a failure. A source that could not be checked is named under + * the list and takes the "nothing needs your attention" sentence away. + */ +export default { + name: 'AttentionWidget', + + components: { + WidgetRowFilter, + }, + + props: { + /** Persisted widget content: `{ limit, layout, columns, itemCards }`; `itemCards` draws one card per record. */ + content: OBJECT_PROP, + }, + + data() { + return { + loading: true, + loadFailed: false, + items: [], + failedApps: [], + sourceCount: 0, + // REQ-DWMS-008: the row filter is view state only. Never saved, + // never shared, gone after a reload. + rowFilter: '', + } + }, + + computed: { + /** + * How many lines to show, 1 to 10. + * + * @return {number} The limit. + * @spec openspec/specs/attention-feed/spec.md#req-att-004 + */ + limit() { + const limit = Number(this.content?.limit) + if (!Number.isInteger(limit) || limit < 1) { + return DEFAULT_LIMIT + } + return Math.min(limit, MAX_LIMIT) + }, + + /** + * The items the person's row filter keeps (REQ-DWMS-008); the loaded + * items and the widget's settings are never touched. + * + * @return {Array<object>} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-008-search-inside-a-widgets-results + */ + filteredItems() { + return filterRows(this.items, this.rowFilter, ['title', 'reason', 'appName']) + }, + + /** @spec openspec/specs/attention-feed/spec.md#req-att-004 */ + /** + * Whether the items stand side by side, one row of `columns` + * (`content.layout: "columns"`), as LpVandaag's "Vandaag eerst". + * + * @return {boolean} + * @spec openspec/changes/lpvandaag-start-page/specs/lpvandaag-start-page/spec.md#requirement-vandaag-eerst-is-one-row + */ + isColumns() { + return this.content?.layout === 'columns' + }, + + /** + * How many items stand side by side in the columns layout: 1 to 4, + * 3 by default. + * + * @return {number} + * @spec openspec/changes/lpvandaag-start-page/specs/lpvandaag-start-page/spec.md#requirement-vandaag-eerst-is-one-row + */ + columns() { + const columns = Number(this.content?.columns) + return Number.isInteger(columns) && columns >= 1 && columns <= 4 + ? columns + : 3 + }, + + /** + * The widget's own heading (`content.title`), drawn with the count + * of items beside it; '' without one, when the card's header names + * the widget. + * + * @return {string} + * @spec openspec/changes/lpvandaag-start-page/specs/lpvandaag-start-page/spec.md#requirement-vandaag-eerst-is-one-row + */ + heading() { + const title = this.content?.title + return typeof title === 'string' ? title : '' + }, + + visibleItems() { + return this.filteredItems.slice(0, this.limit) + }, + + /** @spec openspec/specs/attention-feed/spec.md#req-att-004 */ + hiddenCount() { + return Math.max(0, this.filteredItems.length - this.limit) + }, + + /** + * Which of the five states the widget is in. + * + * @return {string} `loading`, `error`, `items`, `clear`, `none` or `failed`. + * @spec openspec/specs/attention-feed/spec.md#req-att-005 + */ + state() { + if (this.loading) { + return 'loading' + } + if (this.loadFailed) { + return 'error' + } + if (this.items.length > 0) { + return 'items' + } + if (this.failedApps.length > 0) { + return 'failed' + } + return this.sourceCount === 0 ? 'none' : 'clear' + }, + }, + + /** @spec openspec/specs/attention-feed/spec.md#req-att-005 */ + async created() { + await this.load() + }, + + methods: { + t, + n, + + /** + * Load and count. A failure of the sources endpoint is the widget's + * own failure; a failure of one count is that source's. + * + * @spec openspec/specs/attention-feed/spec.md#req-att-005 + * @spec openspec/changes/archive/2026-11-24-start-page-board-sync/specs/attention-feed/spec.md#requirement-vandaag-eerst-can-draw-one-card-per-record-req-att-007 + */ + async load() { + this.loading = true + this.loadFailed = false + try { + const perRecord = this.content?.itemCards === true + const feed = await loadAttentionFeed({ perSource: perRecord ? this.limit : 1 }) + this.items = perRecord + ? expandToRecords(feed.items, (schema) => t('launchpad', 'Open {item}', { item: schema || t('launchpad', 'item') })) + : feed.items + this.failedApps = feed.failedApps + this.sourceCount = feed.sourceCount + } catch (error) { + logger.error('Failed to load the attention feed:', error) + this.loadFailed = true + } finally { + this.loading = false + } + }, + + /** + * Severity in words, for assistive technology: the coloured edge + * alone would say it by colour only. + * + * @param {string} severity `error`, `warning` or `info`. + * @return {string} The spoken prefix. + * @spec openspec/specs/attention-feed/spec.md#req-att-006 + */ + severityLabel(severity) { + if (severity === 'error') { + return t('launchpad', 'Urgent:') + } + if (severity === 'warning') { + return t('launchpad', 'Soon:') + } + return t('launchpad', 'For your information:') + }, + }, +} +</script> + +<style scoped> +.attention-widget { + display: flex; + flex-direction: column; + gap: 4px; + height: 100%; + overflow-y: auto; + padding: 4px 12px 12px; +} + +.attention-widget__list { + list-style: none; + margin: 0; + padding: 0; +} + +.attention-widget__head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 4px 12px; + margin-bottom: 6px; +} + +.attention-widget__heading { + margin: 0; + font-size: 16px; + font-weight: 700; + line-height: 1.3; +} + +.attention-widget__summary { + font-size: 13px; + color: var(--color-text-maxcontrast); +} + +/* `layout: "columns"`: the items in one row, each with its title, reason + and app on the left and its action on the right (LpVandaag). */ +.attention-widget--columns { + padding: 0; +} + +.attention-widget--columns .attention-widget__list { + display: grid; + grid-template-columns: repeat(var(--attention-columns, 3), minmax(0, 1fr)); + gap: 12px; +} + +.attention-widget--columns .attention-widget__item { + display: grid; + grid-template-areas: 'text action' 'app action'; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 2px 12px; + padding: 0 0 0 12px; + border-bottom: 0; +} + +.attention-widget--columns .attention-widget__text { + grid-area: text; + min-width: 0; +} + +.attention-widget--columns .attention-widget__title, +.attention-widget--columns .attention-widget__reason { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.attention-widget--columns .attention-widget__reason { + font-size: 13px; +} + +.attention-widget--columns .attention-widget__app { + grid-area: app; + justify-self: start; + margin-top: 2px; + padding: 1px 8px; + font-size: 12px; + font-weight: 600; +} + +.attention-widget--columns .attention-widget__action { + grid-area: action; + min-height: 34px; + font-size: 13px; +} + +@media (max-width: 960px) { + .attention-widget--columns .attention-widget__list { + grid-template-columns: minmax(0, 1fr); + } +} + +.attention-widget__item { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 16px; + padding: 12px 0 12px 12px; + border-inline-start: 4px solid var(--color-border-dark); + border-bottom: 1px solid var(--color-border); +} + +.attention-widget__item:last-child { + border-bottom: 0; +} + +.attention-widget__item--error { + border-inline-start-color: var(--color-error); +} + +.attention-widget__item--warning { + border-inline-start-color: var(--color-warning); +} + +.attention-widget__text { + display: flex; + flex: 1 1 240px; + flex-direction: column; + gap: 2px; +} + +.attention-widget__reason, +.attention-widget__more, +.attention-widget__failed, +.attention-widget__state { + color: var(--color-text-maxcontrast); +} + +.attention-widget__app { + padding: 2px 10px; + border-radius: var(--border-radius-pill); + background: var(--color-background-dark); + color: var(--color-main-text); + font-size: 13px; +} + +.attention-widget__action { + display: inline-flex; + align-items: center; + min-height: var(--default-clickable-area, 34px); + padding: 0 14px; + border-radius: var(--border-radius-element, var(--border-radius)); + background: var(--color-primary-element); + color: var(--color-primary-element-text); + font-weight: 600; + text-decoration: none; +} + +.attention-widget__action:hover, +.attention-widget__action:focus-visible { + background: var(--color-primary-element-hover); +} + +/* + * The action is a link drawn as a button. A theme that colours every link + * with `!important` (thematiq's nldesign sheets: `a:not(#header a)...`, + * which carries an id in its specificity) painted its text the link blue on + * the blue button, so the button read as an empty bar (:8080, 7 October), + * and underlined it. + * The two `:not(#…)` raise this rule above that one, so the button keeps + * the text colour that belongs to its own background in every theme. + */ +.attention-widget__action.attention-widget__action:not(#attention-a):not( + #attention-b + ) { + color: var(--color-primary-element-text) !important; + text-decoration: none !important; +} + +.attention-widget__action:focus-visible { + outline: 2px solid var(--color-main-text); + outline-offset: 2px; +} + +.attention-widget__more, +.attention-widget__failed, +.attention-widget__state { + margin: 8px 0 0; +} + +.attention-widget__state--failed { + color: var(--color-main-text); +} + +.attention-widget__sr { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} +</style> diff --git a/src/components/Widgets/Renderers/AttentionWidgetForm.vue b/src/components/Widgets/Renderers/AttentionWidgetForm.vue new file mode 100644 index 000000000..3f3416d2d --- /dev/null +++ b/src/components/Widgets/Renderers/AttentionWidgetForm.vue @@ -0,0 +1,114 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="attention-widget-form"> + <p class="attention-widget-form__hint"> + {{ + t( + 'launchpad', + 'Shows what needs attention today, from every app that reports it. Each line links into the app.', + ) + }} + </p> + + <NcSelect + :modelValue="limit" + :options="limitOptions" + :inputLabel="t('launchpad', 'Lines to show')" + :clearable="false" + @update:modelValue="updateLimit" /> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcSelect } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' + +const DEFAULT_LIMIT = 5 +const LIMIT_OPTIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +/** + * AttentionWidgetForm — the one setting of the "First today" widget: how many + * lines it shows (REQ-ATT-004). What it shows is decided by the apps. + */ +export default { + name: 'AttentionWidgetForm', + + components: { NcSelect }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** + * Initial content values, used when not editing. + * + * @type {object} + */ + value: objectProp({ limit: DEFAULT_LIMIT }), + }, + + emits: ['update:content'], + + data() { + const initial = Number( + (this.editingWidget?.content || this.value || {}).limit, + ) + return { + limitOptions: LIMIT_OPTIONS, + limit: LIMIT_OPTIONS.includes(initial) ? initial : DEFAULT_LIMIT, + } + }, + + methods: { + t, + + /** + * Keep the new limit and tell the modal. + * + * @param {number} limit Lines to show. + * @spec openspec/specs/attention-feed/spec.md#req-att-004 + */ + updateLimit(limit) { + this.limit = LIMIT_OPTIONS.includes(Number(limit)) + ? Number(limit) + : DEFAULT_LIMIT + this.$emit('update:content', { limit: this.limit }) + }, + + /** + * Validate the form. The one setting always has a valid value. + * + * @return {string[]} The validation errors (always empty). + * @spec openspec/specs/attention-feed/spec.md#req-att-006 + */ + validate() { + return [] + }, + }, +} +</script> + +<style scoped> +.attention-widget-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.attention-widget-form__hint { + color: var(--color-text-maxcontrast); + margin: 0; +} +</style> diff --git a/src/components/Widgets/Renderers/CalendarWidget.vue b/src/components/Widgets/Renderers/CalendarWidget.vue index bb2f5778f..f255d61b8 100644 --- a/src/components/Widgets/Renderers/CalendarWidget.vue +++ b/src/components/Widgets/Renderers/CalendarWidget.vue @@ -157,6 +157,7 @@ <script> import axios from '@nextcloud/axios' import { generateUrl } from '@nextcloud/router' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' const VIEW_MODES = ['month', 'week', 'agenda'] @@ -179,10 +180,7 @@ export default { * Persisted placement content. Must contain at least one of * `internalCalendars` or `externalIcsUrls` for events to load. */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** * Placement id used for the events endpoint (when present). When diff --git a/src/components/Widgets/Renderers/CalendarWidgetForm.vue b/src/components/Widgets/Renderers/CalendarWidgetForm.vue new file mode 100644 index 000000000..246e214ee --- /dev/null +++ b/src/components/Widgets/Renderers/CalendarWidgetForm.vue @@ -0,0 +1,423 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="calendar-widget-form"> + <fieldset class="calendar-widget-form__group"> + <legend class="calendar-widget-form__legend"> + {{ t('launchpad', 'Calendars') }} + </legend> + <p v-if="loading" class="calendar-widget-form__hint"> + {{ t('launchpad', 'Loading…') }} + </p> + <NcCheckboxRadioSwitch + v-for="calendar in availableCalendars" + :key="calendar.key" + :modelValue="internalCalendars.includes(calendar.key)" + :data-testid="'calendar-' + calendar.key" + @update:modelValue="toggleCalendar(calendar.key, $event)"> + <span + class="calendar-widget-form__swatch" + :style="{ background: calendar.color || 'var(--color-primary-element)' }" + aria-hidden="true" /> + {{ calendar.name || calendar.key }} + </NcCheckboxRadioSwitch> + <!-- A stored calendar that is no longer offered stays listed, so + saving never drops it without the editor seeing it. --> + <NcCheckboxRadioSwitch + v-for="key in unlistedCalendars" + :key="key" + :modelValue="true" + @update:modelValue="toggleCalendar(key, $event)"> + {{ key }} + </NcCheckboxRadioSwitch> + </fieldset> + + <fieldset class="calendar-widget-form__group"> + <legend class="calendar-widget-form__legend"> + {{ t('launchpad', 'External calendar (ICS address)') }} + </legend> + <ul v-if="externalIcsUrls.length > 0" class="calendar-widget-form__urls"> + <li v-for="(address, index) in externalIcsUrls" :key="address" class="calendar-widget-form__url"> + <span class="calendar-widget-form__url-text">{{ address }}</span> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove')" + @click="removeIcs(index)"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </li> + </ul> + <div class="calendar-widget-form__add"> + <NcTextField + :modelValue="newIcs" + :label="t('launchpad', 'External calendar (ICS address)')" + placeholder="https://example.com/calendar.ics" + :error="icsError !== ''" + :helperText="icsError" + @update:modelValue="onIcsInput" + @keydown.enter.prevent="addIcs" /> + <NcButton :disabled="newIcs.trim() === ''" @click="addIcs"> + {{ t('launchpad', 'Add') }} + </NcButton> + </div> + </fieldset> + + <fieldset class="calendar-widget-form__group calendar-widget-form__periods"> + <legend class="calendar-widget-form__legend"> + {{ t('launchpad', 'Period') }} + </legend> + <label + v-for="option in periodOptions" + :key="option.value" + class="calendar-widget-form__period" + :class="{ 'calendar-widget-form__period--selected': period === option.value }"> + <input + type="radio" + name="calendar-period" + :value="option.value" + :checked="period === option.value" + :data-testid="'calendar-period-' + option.value" + @change="onPeriodChange(option.value)"> + {{ option.label }} + </label> + </fieldset> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcButton, NcCheckboxRadioSwitch, NcTextField } from '@nextcloud/vue' +import { NULLABLE_OBJECT_PROP, objectProp } from '../../../constants/propDefinitions.js' +import { contentForPeriod, isIcsAddress, periodOf } from '../../../utils/calendarPeriod.js' + +const DEFAULT_CONTENT = Object.freeze({ + internalCalendars: [], + externalIcsUrls: [], + viewMode: 'agenda', + daysAhead: 7, + colorByCalendar: true, +}) + +/** + * CalendarWidgetForm — the content part of a Calendar widget as board + * LpWidgetInstellen draws it (REQ-CAL-020): the reader's calendars to choose + * from, external calendars by ICS address, and the period 7 days or Month. + * Stores the content the Calendar renderer already reads (`internalCalendars`, + * `externalIcsUrls`, `viewMode`, `daysAhead`, `colorByCalendar`). + * + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ +export default { + name: 'CalendarWidgetForm', + + components: { NcButton, NcCheckboxRadioSwitch, NcTextField }, + + props: { + /** The placement being edited, or `null` in create mode. */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** Initial content values, used when not editing. */ + value: objectProp(DEFAULT_CONTENT), + + /** + * `async () => [{key, name, color}]`: the reader's calendars, passed + * by the modal. + */ + calendarsFetcher: { + type: Function, + default: null, + }, + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + internalCalendars: Array.isArray(initial.internalCalendars) ? [...initial.internalCalendars] : [], + externalIcsUrls: Array.isArray(initial.externalIcsUrls) ? [...initial.externalIcsUrls] : [], + period: periodOf(initial), + colorByCalendar: initial.colorByCalendar !== false, + availableCalendars: [], + loading: false, + newIcs: '', + icsError: '', + } + }, + + computed: { + /** + * The two periods. + * + * @return {Array<{value: string, label: string}>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + periodOptions() { + return [ + { value: 'week', label: t('launchpad', '7 days') }, + { value: 'month', label: t('launchpad', 'Month') }, + ] + }, + + /** + * Stored calendars the fetcher no longer offers. + * + * @return {string[]} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + unlistedCalendars() { + const offered = new Set(this.availableCalendars.map((calendar) => calendar.key)) + return this.loading ? [] : this.internalCalendars.filter((key) => !offered.has(key)) + }, + + /** + * The added ICS addresses plus a valid one still in the field, so an + * address typed but not added is not lost on save. + * + * @return {string[]} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + icsWithPending() { + const pending = this.newIcs.trim() + if (pending !== '' && isIcsAddress(pending) && !this.externalIcsUrls.includes(pending)) { + return [...this.externalIcsUrls, pending] + } + return [...this.externalIcsUrls] + }, + + /** + * The stored content. + * + * @return {object} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + assembledContent() { + return { + internalCalendars: [...this.internalCalendars], + externalIcsUrls: this.icsWithPending, + ...contentForPeriod(this.period), + colorByCalendar: this.colorByCalendar, + } + }, + }, + + mounted() { + this.fetchCalendars() + }, + + methods: { + t, + + /** + * Emit the content. + * + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + emitUpdate() { + this.$emit('update:content', this.assembledContent) + }, + + /** + * Load the reader's calendars. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + async fetchCalendars() { + if (typeof this.calendarsFetcher !== 'function') { + return + } + this.loading = true + try { + const list = await this.calendarsFetcher() + this.availableCalendars = Array.isArray(list) ? list.filter((calendar) => calendar && calendar.key) : [] + } catch { + this.availableCalendars = [] + } finally { + this.loading = false + } + }, + + /** + * Choose or drop one of the reader's calendars. + * + * @param {string} key The calendar key. + * @param {boolean} on Whether it is chosen. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + toggleCalendar(key, on) { + const without = this.internalCalendars.filter((item) => item !== key) + this.internalCalendars = on ? [...without, key] : without + this.emitUpdate() + }, + + /** + * Typing in the ICS field clears its error. + * + * @param {string} val The typed address. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + onIcsInput(val) { + this.newIcs = typeof val === 'string' ? val : '' + this.icsError = '' + this.emitUpdate() + }, + + /** + * Add the typed ICS address; it must be https. + * + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + addIcs() { + const address = this.newIcs.trim() + if (address === '') { + return + } + if (!isIcsAddress(address)) { + this.icsError = t('launchpad', 'An ICS address starts with https://') + return + } + if (!this.externalIcsUrls.includes(address)) { + this.externalIcsUrls = [...this.externalIcsUrls, address] + } + this.newIcs = '' + this.emitUpdate() + }, + + /** + * Remove an added ICS address. + * + * @param {number} index Its position. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + removeIcs(index) { + this.externalIcsUrls = this.externalIcsUrls.filter((_, at) => at !== index) + this.emitUpdate() + }, + + /** + * Choose 7 days or Month. + * + * @param {string} val `week` or `month`. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + onPeriodChange(val) { + this.period = val === 'month' ? 'month' : 'week' + this.emitUpdate() + }, + + /** + * The form's errors: at least one calendar, and every address https. + * An address still in the field counts. Pure: the modal calls it from a + * computed on every input. + * + * @return {string[]} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ + validate() { + const errors = [] + const pending = this.newIcs.trim() + if (pending !== '' && !isIcsAddress(pending)) { + errors.push(t('launchpad', 'An ICS address starts with https://')) + } + if (this.internalCalendars.length === 0 && this.icsWithPending.length === 0) { + errors.push(t('launchpad', 'Choose at least one calendar or add an ICS address')) + } + return errors + }, + }, +} +</script> + +<style scoped> +.calendar-widget-form { + display: flex; + flex-direction: column; + gap: 16px; +} + +.calendar-widget-form__group { + display: flex; + flex-direction: column; + gap: 4px; + border: 0; + margin: 0; + padding: 0; +} + +.calendar-widget-form__legend { + margin-bottom: 4px; + font-weight: 600; +} + +.calendar-widget-form__hint { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.calendar-widget-form__swatch { + display: inline-block; + width: 10px; + height: 10px; + margin-inline-end: 6px; + border-radius: 50%; +} + +.calendar-widget-form__urls { + margin: 0; + padding: 0; + list-style: none; +} + +.calendar-widget-form__url { + display: flex; + gap: 8px; + align-items: center; +} + +.calendar-widget-form__url-text { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.calendar-widget-form__add { + display: flex; + gap: 8px; + align-items: flex-start; +} + +.calendar-widget-form__add > :first-child { + flex: 1; +} + +.calendar-widget-form__periods { + flex-direction: row; + flex-wrap: wrap; + gap: 8px; +} + +.calendar-widget-form__periods .calendar-widget-form__legend { + width: 100%; +} + +.calendar-widget-form__period { + display: inline-flex; + gap: 6px; + align-items: center; + padding: 4px 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-pill); + cursor: pointer; +} + +.calendar-widget-form__period--selected { + border-color: var(--color-primary-element); + background: var(--color-primary-element-light); +} +</style> diff --git a/src/components/Widgets/Renderers/ChartHost.vue b/src/components/Widgets/Renderers/ChartHost.vue index 90f1667f9..78a6ba3b2 100644 --- a/src/components/Widgets/Renderers/ChartHost.vue +++ b/src/components/Widgets/Renderers/ChartHost.vue @@ -8,11 +8,24 @@ :type="chartType" :data-source="dataSource" :widgetId="widgetId" - v-bind="passthroughProps" /> + :selectable="publishing" + v-bind="passthroughProps" + @select="onSelect" + @data="onData" /> </template> <script> import { CnChartWidget } from '@conduction/nextcloud-vue' +import { showInfo, showWarning } from '@nextcloud/dialogs' +import { translate as t } from '@nextcloud/l10n' +import { unref } from 'vue' +import { levelLabels as hierarchyLevelLabels } from '../../../composables/useDashboardFilterSession.js' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { clickedRow, missingAncestors } from '../../../utils/clickedRow.js' +import { periodFieldOf, withPeriod } from '../../../utils/dashboardPeriod.js' +import { logger } from '../../../utils/logger.js' +import { busDeclarationsOf, consumedFilter, filterBusOf, publishedClauses, refetchClock, withBusFilter } from '../../../utils/widgetBusConsumption.js' +import { validateBusDeclarations } from '../../../utils/widgetBusDeclarations.js' // Chart config keys that a content-based placement may carry through to // CnChartWidget verbatim (apexcharts passthrough). `dataSource` resolves the @@ -31,43 +44,201 @@ const CHART_PROP_KEYS = [ 'stacked', 'horizontal', 'colorScheme', + 'legendValues', + 'legendPosition', + 'colorMap', ] +/** + * Whether manual series mix bars and lines (board LpManagement "Grafiek": + * bars for applications, a line for decisions). ApexCharts draws a mixed + * chart as type `line` with a `type` per series. + * + * @param {object} content The placement content. + * @return {boolean} + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-graph-draws-bars-and-lines-req-chartp-002 + */ +export function isMixedSeries(content) { + const series = content?.source === 'manual' && Array.isArray(content.series) ? content.series : [] + const types = new Set(series.map((entry) => entry?.type).filter(Boolean)) + return types.has('line') && types.has('column') +} + +/** + * Chart options with the donut's total written in its centre. + * + * @param {object|undefined} options The placement's own options. + * @param {string} label The total's label. + * @return {object} + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-pie-chart-is-a-donut-with-its-total-in-the-centre-req-chartp-001 + */ +export function withDonutTotal(options, label) { + const own = options && typeof options === 'object' ? options : {} + const pie = own.plotOptions?.pie || {} + const donut = pie.donut || {} + return { + ...own, + plotOptions: { + ...own.plotOptions, + pie: { + ...pie, + donut: { + ...donut, + labels: { show: true, ...donut.labels, total: { show: true, label, ...donut.labels?.total } }, + }, + }, + }, + } +} + /** * ChartHost — thin LaunchPad wrapper adapting the registry's `content` shape * ({ chartKind, dataSource, ...apexcharts overrides }) onto CnChartWidget's * prop interface (apexcharts `type` + a self-fetching `dataSource`). Mirrors * CnDashboardPage's `getChartProps`/`getWidgetDataSource` mapping so a chart * placement renders identically in LaunchPad's generic WidgetRenderer. + * + * On a dashboard with a filter bus, a chart that declares `consumes` has the + * bus's clauses for those dimensions added to its `dataSource.filter`, and + * CnChartWidget refetches when that filter changes (drill-down-cross-widget- + * filter REQ-CWF-002). A declaration that does not fit the dashboard's + * hierarchies keeps the chart off the bus, with a warning (REQ-CWF-008). + * A chart that shows its new data more than 200 ms after a filter change + * logs a warning with the time (Task 35). + * + * A chart that declares `publishes` lets the reader pick a bar or slice: + * CnChartWidget's `select` names the grouped field and the raw key, and the + * host publishes a `widgetClick` clause for each dimension published from + * that field (REQ-CWF-001). A replaced filter from another widget is named + * in a toast (REQ-CWF-005). A pick on a hierarchy level whose ancestors the + * click does not name reads them from one record of that category first, so + * the bus can infer the levels above it (REQ-CWF-004). */ export default { name: 'ChartHost', components: { CnChartWidget }, + inject: { + /** The open dashboard's filter bus (a ref to it), or null. */ + filterBus: { from: 'dashboardFilterBus', default: null }, + /** The period the dashboard's dated widgets follow (REQ-DPD-002), a ref, or null. */ + dashboardPeriod: { from: 'dashboardPeriod', default: null }, + }, + props: { /** The placement's content blob — `{ chartKind, dataSource, props? }`. */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** The placement record (used for a stable widget id). */ - placement: { - type: Object, - default: () => ({}), - }, + placement: OBJECT_PROP, }, + emits: ['data'], + computed: { - /** apexcharts chart type, from `chartKind` (content or nested props). */ + /** + * apexcharts chart type, from `chartKind` (content or nested props); + * `line` for entered bars and lines together. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-graph-draws-bars-and-lines-req-chartp-002 + */ chartType() { + if (isMixedSeries(this.content)) { + return 'line' + } return this.content.chartKind || this.content.props?.chartKind || 'area' }, - /** The OpenRegister dataSource block CnChartWidget self-resolves. */ + /** + * The OpenRegister dataSource block CnChartWidget self-resolves, with the bus's filter when the chart consumes it, + * and the dashboard's period when its source names a period field. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-9 + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ dataSource() { - return this.content.dataSource || this.content.props?.dataSource || null + if (this.content.source === 'manual') { + return null + } + const own = withBusFilter(this.content.dataSource || this.content.props?.dataSource || null, this.busFilter) + const period = unref(this.dashboardPeriod) + return period ? withPeriod(own, periodFieldOf(this.content), period, new Date()) : own + }, + + /** + * The filter the bus's clauses add to the chart's data source; empty off the bus. + * + * @return {{[field: string]: unknown}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-10 + */ + busFilter() { + if (this.bus === null || !this.busCheck.participates) { + return {} + } + return consumedFilter(this.bus.clauses.value, this.busDeclarations.consumes) + }, + + /** + * The bus filter as text, so a change of another dimension's clause is no change. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-35 + */ + busFilterKey() { + return JSON.stringify(this.busFilter) + }, + + /** + * The filter bus itself, unwrapped from the injected ref. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-9 + */ + bus() { + return filterBusOf(this.filterBus) + }, + + /** + * What the chart declares it publishes and consumes. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-9 + */ + busDeclarations() { + return busDeclarationsOf(this.content) + }, + + /** + * Whether the declarations fit the dashboard, and why not. + * + * @return {{participates: boolean, findings: Array<object>}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-9 + */ + busCheck() { + const { publishes, consumes } = this.busDeclarations + if (this.bus === null || (publishes.length === 0 && consumes.length === 0)) { + return { participates: false, findings: [] } + } + return validateBusDeclarations({ widget: { publishes, consumes }, hierarchies: this.bus.hierarchies }) + }, + + /** + * Whether a click on the chart publishes to the bus. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-7 + */ + publishing() { + return this.busCheck.participates && this.busDeclarations.publishes.length > 0 + }, + + /** + * A display label per hierarchy level of the dashboard. + * + * @return {{[dimension: string]: string}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-7 + */ + levelLabels() { + return this.bus ? hierarchyLevelLabels(this.bus.hierarchies || []) : {} }, /** Stable widget id for the chart's date-range wiring. */ @@ -75,7 +246,12 @@ export default { return String(this.placement?.id ?? this.placement?.widgetId ?? 'chart') }, - /** Optional apexcharts overrides forwarded verbatim when present. */ + /** + * Optional apexcharts overrides forwarded verbatim when present, and + * the donut's total in its centre when `showTotal` is set. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-pie-chart-is-a-donut-with-its-total-in-the-centre-req-chartp-001 + */ passthroughProps() { const src = { ...(this.content.props || {}), ...this.content } const out = {} @@ -84,8 +260,101 @@ export default { out[key] = src[key] } } + if (src.showTotal === true && this.chartType === 'donut') { + out.options = withDonutTotal(out.options, t('launchpad', 'Total')) + } return out }, }, + + watch: { + /** + * Start timing the refetch a changed bus filter causes. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-35 + */ + busFilterKey() { + this.refetchClock.start(this.busFilter) + }, + + busCheck: { + immediate: true, + /** + * Log why a chart stays off the bus (REQ-CWF-008). + * + * @param {{findings: Array<object>}} check The check. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-9 + */ + handler(check) { + for (const finding of check.findings) { + logger.warn(`[launchpad] widget ${this.widgetId} is not on the filter bus: ${finding.code} (${finding.dimension})`) + } + }, + }, + }, + + created() { + this.refetchClock = refetchClock({ widgetId: () => this.widgetId, warn: (message) => logger.warn(message) }) + }, + + methods: { + /** + * Pass the chart's data on, settling a refetch timed since a filter change. + * + * @param {object} data What the chart shows. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-35 + */ + onData(data) { + this.refetchClock.settle() + this.$emit('data', data) + }, + + /** + * Publish the reader's pick to the bus, and say so when it replaced + * another widget's filter or was refused. + * + * @param {{field: string, value: unknown, label: string}} selection CnChartWidget's `select` payload. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-7 + */ + onSelect(selection) { + if (!this.publishing) { + return + } + const clauses = publishedClauses(this.busDeclarations.publishes, selection, this.widgetId) + const row = { [selection.field]: selection.value } + if (missingAncestors(this.bus.hierarchies || [], clauses, row).length === 0) { + this.publishPick(clauses, row) + return + } + clickedRow({ selection, clauses, hierarchies: this.bus.hierarchies || [], dataSource: this.dataSource }) + .then((completed) => this.publishPick(clauses, completed)) + }, + + /** + * Publish the clauses of a pick with the clicked row, and say so when + * one replaced another widget's filter or was refused. + * + * @param {Array<object>} clauses The clauses the pick publishes. + * @param {object} row The clicked row, ancestor levels included where known. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ + publishPick(clauses, row) { + const labels = this.levelLabels + for (const clause of clauses) { + const answer = this.bus.publish(clause, { row }) + const name = labels[clause.dimension] || clause.dimension + if (answer.reason === 'forbidden') { + showWarning(t('launchpad', 'You have no access to this scope: {name}', { name })) + } else if (answer.audit && answer.audit.silent === false) { + showInfo(t('launchpad', '{name} filter changed: {from} → {to}', { name, from: String(answer.audit.from), to: String(answer.audit.to) })) + } + } + }, + }, } </script> diff --git a/src/components/Widgets/Renderers/ChartSourceForm.vue b/src/components/Widgets/Renderers/ChartSourceForm.vue new file mode 100644 index 000000000..98f377b1c --- /dev/null +++ b/src/components/Widgets/Renderers/ChartSourceForm.vue @@ -0,0 +1,480 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="chart-source-form"> + <fieldset class="chart-source-form__source"> + <legend>{{ t('launchpad', 'Data source') }}</legend> + <NcCheckboxRadioSwitch + :modelValue="source" + value="register" + :name="`${domId}-source`" + type="radio" + data-testid="chart-source-register" + @update:modelValue="setSource('register')"> + {{ t('launchpad', 'A register query') }} + </NcCheckboxRadioSwitch> + <NcCheckboxRadioSwitch + :modelValue="source" + value="manual" + :name="`${domId}-source`" + type="radio" + data-testid="chart-source-manual" + @update:modelValue="setSource('manual')"> + {{ t('launchpad', 'Values you enter') }} + </NcCheckboxRadioSwitch> + </fieldset> + + <CnChartWidgetForm + v-if="source === 'register'" + ref="registerForm" + :value="registerValue" + @update:content="onRegisterContent" /> + + <PeriodFieldSelect + v-if="source === 'register'" + :register="registerSource.register" + :schema="registerSource.schema" + :modelValue="periodField" + @update:modelValue="setPeriodField" /> + + <template v-else-if="kind === 'pie'"> + <div + v-for="(row, index) in slices" + :key="`slice-${index}`" + class="chart-source-form__row" + data-testid="chart-source-slice"> + <NcTextField + :modelValue="row.label" + :label="t('launchpad', 'Label')" + @update:modelValue="setSlice(index, { label: String($event) })" /> + <NcTextField + :modelValue="String(row.value)" + type="number" + :label="t('launchpad', 'Value')" + @update:modelValue="setSlice(index, { value: Number($event) })" /> + <NcTextField + :modelValue="row.colour" + :label="t('launchpad', 'Colour (optional)')" + placeholder="#3669a5" + @update:modelValue="setSlice(index, { colour: String($event) })" /> + <NcButton variant="tertiary" :aria-label="t('launchpad', 'Remove this value')" @click="removeSlice(index)"> + <template #icon> + <Delete :size="18" /> + </template> + </NcButton> + </div> + <NcButton data-testid="chart-source-add-slice" @click="addSlice"> + {{ t('launchpad', 'Add a value') }} + </NcButton> + </template> + + <template v-else> + <NcTextField + :modelValue="categoriesText" + :label="t('launchpad', 'Labels on the horizontal axis, separated by commas')" + placeholder="apr, mei, jun" + data-testid="chart-source-categories" + @update:modelValue="setCategories(String($event))" /> + <div + v-for="(row, index) in lines" + :key="`series-${index}`" + class="chart-source-form__row" + data-testid="chart-source-series"> + <NcTextField + :modelValue="row.name" + :label="t('launchpad', 'Series name')" + @update:modelValue="setLine(index, { name: String($event) })" /> + <NcSelect + :modelValue="row.type" + :options="['column', 'line']" + :inputLabel="t('launchpad', 'Drawn as')" + :clearable="false" + @update:modelValue="setLine(index, { type: $event })"> + <template #option="{ label }"> + {{ seriesTypeLabel(label) }} + </template> + <template #selected-option="{ label }"> + {{ seriesTypeLabel(label) }} + </template> + </NcSelect> + <NcTextField + :modelValue="row.valuesText" + :label="t('launchpad', 'Values, separated by commas')" + placeholder="112, 98, 130" + @update:modelValue="setLine(index, { valuesText: String($event) })" /> + <NcButton variant="tertiary" :aria-label="t('launchpad', 'Remove this series')" @click="removeLine(index)"> + <template #icon> + <Delete :size="18" /> + </template> + </NcButton> + </div> + <NcButton data-testid="chart-source-add-series" @click="addLine"> + {{ t('launchpad', 'Add a series') }} + </NcButton> + </template> + </div> +</template> + +<script> +import { CnChartWidgetForm } from '@conduction/nextcloud-vue' +import { translate as t } from '@nextcloud/l10n' +import { NcButton, NcCheckboxRadioSwitch, NcSelect, NcTextField } from '@nextcloud/vue' +import Delete from 'vue-material-design-icons/Delete.vue' +import PeriodFieldSelect from './PeriodFieldSelect.vue' +import { NULLABLE_OBJECT_PROP, OBJECT_PROP } from '../../../constants/propDefinitions.js' + +let domIdCounter = 0 + +/** + * The numbers in a comma-separated text; a part that is no number is 0. + * + * @param {string} text The text. + * @return {number[]} + */ +function numbersOf(text) { + return String(text || '').split(',').map((part) => part.trim()).filter((part) => part !== '').map((part) => Number(part.replace(',', '.')) || 0) +} + +/** + * Whether content is a pie chart or a graph, by its chart kind. + * + * @param {object} content The content. + * @return {string} `pie` or `graph`. + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ +export function kindOf(content) { + return ['donut', 'pie'].includes(content?.chartKind) ? 'pie' : 'graph' +} + +/** + * The entered slices of a pie chart's content, for the form. + * + * @param {object} content The content. + * @return {Array<{label: string, value: number, colour: string}>} + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ +function slicesOf(content) { + const labels = Array.isArray(content.labels) ? content.labels : [] + const values = Array.isArray(content.series) ? content.series : [] + const colours = content.colorMap && typeof content.colorMap === 'object' ? content.colorMap : {} + return labels.map((label, index) => ({ label: String(label), value: Number(values[index]) || 0, colour: String(colours[label] || '') })) +} + +/** + * The entered series of a graph's content, for the form. + * + * @param {object} content The content. + * @return {Array<{name: string, type: string, valuesText: string}>} + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ +function linesOf(content) { + return (Array.isArray(content.series) ? content.series : []).map((line) => ({ + name: String(line?.name || ''), + type: line?.type === 'line' ? 'line' : 'column', + valuesText: Array.isArray(line?.data) ? line.data.join(', ') : '', + })) +} + +/** + * ChartSourceForm: the data source of a pie chart or a graph (boards + * LpManagement "Cirkeldiagram" and "Grafiek"). The source is a register + * query, edited by the shared chart form, or values the author enters: label, + * value and colour per slice for a pie chart; axis labels and named series, + * each drawn as bars or a line, for a graph. Whether it edits a pie chart or a + * graph follows the content's chart kind, so both widget types use this form. + * + * Emits the whole content: the preset keys of the widget kept, `source`, and + * either `chartKind` with `dataSource`, or the manual `labels`/`series`/ + * `colorMap` (pie) or `categories`/`series` (graph). + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md + */ +export default { + name: 'ChartSourceForm', + + components: { CnChartWidgetForm, Delete, NcButton, NcCheckboxRadioSwitch, NcSelect, NcTextField, PeriodFieldSelect }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** + * The preset content, used when not editing. + * + * @type {object} + */ + value: OBJECT_PROP, + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + const kind = kindOf(initial) + return { + domId: `chart-source-${++domIdCounter}`, + kind, + initial, + source: initial.source === 'manual' ? 'manual' : 'register', + registerContent: { chartKind: initial.chartKind, dataSource: initial.dataSource }, + slices: kind === 'pie' ? slicesOf(initial) : [], + categoriesText: Array.isArray(initial.categories) ? initial.categories.join(', ') : '', + lines: kind === 'graph' ? linesOf(initial) : [], + periodField: typeof initial.dataSource?.periodField === 'string' ? initial.dataSource.periodField : '', + } + }, + + computed: { + /** + * @return {object} What the shared chart form starts from. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + registerValue() { + return { chartKind: this.initial.chartKind, dataSource: this.initial.dataSource } + }, + + /** + * The register and schema the register query reads, for the period's date field. + * + * @return {{register: string, schema: string}} + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + registerSource() { + const dataSource = this.registerContent?.dataSource || {} + return { register: String(dataSource.register || ''), schema: String(dataSource.schema || '') } + }, + + /** + * The content the widget saves. + * + * @return {object} + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + assembledContent() { + const { labels, series, colorMap, categories, dataSource, ...preset } = this.initial + if (this.source === 'register') { + return { ...preset, source: 'register', ...this.registerContent, dataSource: this.datedSource(this.registerContent.dataSource) } + } + if (this.kind === 'pie') { + const shown = this.slices.filter((row) => row.label.trim() !== '') + return { + ...preset, + source: 'manual', + labels: shown.map((row) => row.label.trim()), + series: shown.map((row) => row.value), + colorMap: Object.fromEntries(shown.filter((row) => row.colour.trim() !== '').map((row) => [row.label.trim(), row.colour.trim()])), + } + } + return { + ...preset, + source: 'manual', + categories: this.categoriesText.split(',').map((part) => part.trim()).filter((part) => part !== ''), + series: this.lines.map((row) => ({ name: row.name.trim(), type: row.type, data: numbersOf(row.valuesText) })), + } + }, + }, + + methods: { + t, + + /** + * @param {string} type `column` or `line`. + * @return {string} How the series is drawn, in words. + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + seriesTypeLabel(type) { + return type === 'line' ? t('launchpad', 'Line') : t('launchpad', 'Bars') + }, + + /** + * Tell the modal the whole content. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + emitContent() { + this.$emit('update:content', this.assembledContent) + }, + + /** + * @param {string} source `register` or `manual`. + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + setSource(source) { + this.source = source + if (source === 'manual' && this.kind === 'pie' && this.slices.length === 0) { + this.addSlice() + return + } + if (source === 'manual' && this.kind === 'graph' && this.lines.length === 0) { + this.addLine() + return + } + this.emitContent() + }, + + /** + * The register query's data source with the period's date field, or without one when none is chosen. + * + * @param {object|null} dataSource The data source. + * @return {object|null} + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + datedSource(dataSource) { + if (!dataSource || typeof dataSource !== 'object') { + return dataSource + } + const { periodField, ...rest } = dataSource + return this.periodField === '' ? rest : { ...rest, periodField: this.periodField } + }, + + /** + * @param {string} field The date field for the period, '' for none. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + setPeriodField(field) { + this.periodField = typeof field === 'string' ? field : '' + this.emitContent() + }, + + /** + * @param {object} content What the shared chart form emits. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + onRegisterContent(content) { + this.registerContent = { chartKind: content.chartKind, dataSource: content.dataSource } + this.emitContent() + }, + + /** + * Add an empty slice. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + addSlice() { + this.slices.push({ label: '', value: 0, colour: '' }) + this.emitContent() + }, + + /** + * @param {number} index The slice. + * @param {object} change The changed keys. + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + setSlice(index, change) { + Object.assign(this.slices[index], change) + this.emitContent() + }, + + /** + * @param {number} index The slice. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + removeSlice(index) { + this.slices.splice(index, 1) + this.emitContent() + }, + + /** + * @param {string} text The comma-separated axis labels. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + setCategories(text) { + this.categoriesText = text + this.emitContent() + }, + + /** + * Add an empty series, as bars. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + addLine() { + this.lines.push({ name: '', type: 'column', valuesText: '' }) + this.emitContent() + }, + + /** + * @param {number} index The series. + * @param {object} change The changed keys. + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + setLine(index, change) { + Object.assign(this.lines[index], change) + this.emitContent() + }, + + /** + * @param {number} index The series. + * + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + removeLine(index) { + this.lines.splice(index, 1) + this.emitContent() + }, + + /** + * Validate: the register query through the shared form; entered values + * need at least one labelled slice, or axis labels and a named series. + * + * @return {string[]} The validation errors. + * @spec openspec/changes/chart-presets/specs/chart-presets/spec.md#requirement-a-chart-reads-a-register-query-or-entered-values-req-chartp-003 + */ + validate() { + if (this.source === 'register') { + const form = this.$refs.registerForm + return typeof form?.validate === 'function' ? form.validate() : [] + } + const content = this.assembledContent + if (this.kind === 'pie') { + return content.labels.length > 0 ? [] : [t('launchpad', 'Enter at least one value with a label')] + } + const named = content.series.filter((line) => line.name !== '' && line.data.length > 0) + return content.categories.length > 0 && named.length > 0 + ? [] + : [t('launchpad', 'Enter the axis labels and at least one named series with values')] + }, + }, +} +</script> + +<style scoped> +.chart-source-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.chart-source-form__source { + margin: 0; + padding: 0; + border: 0; +} + +.chart-source-form__row { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 8px; +} + +.chart-source-form__row > * { + flex: 1 1 140px; +} + +.chart-source-form__row > .button-vue { + flex: 0 0 auto; +} +</style> diff --git a/src/components/Widgets/Renderers/ClockWidget.vue b/src/components/Widgets/Renderers/ClockWidget.vue index 65c298457..94c3f1c29 100644 --- a/src/components/Widgets/Renderers/ClockWidget.vue +++ b/src/components/Widgets/Renderers/ClockWidget.vue @@ -49,12 +49,13 @@ <script> import { getCanonicalLocale, translate as t } from '@nextcloud/l10n' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' /** * Persisted-content field defaults (REQ-CLOCK-002). `timezone: ''` means - * "follow the browser/device timezone" — the widget never fetches the - * server-held Nextcloud user timezone, keeping the clock fully - * client-side (REQ-CLOCK-001: no backend endpoint, no data fetch). + * "the viewer's Nextcloud timezone", which the page hands over in its + * initial state; where there is none (a public page) the device zone is used. + * The clock itself never fetches anything (REQ-CLOCK-001). */ const DEFAULT_CONTENT = Object.freeze({ style: 'digital', @@ -78,16 +79,18 @@ const DEFAULT_CONTENT = Object.freeze({ export default { name: 'ClockWidget', + inject: { + /** The viewer's Nextcloud timezone, from the initial state, or ''. */ + userTimezone: { from: 'userTimezone', default: '' }, + }, + props: { /** * Persisted widget content blob. * * @type {{style?: string, hourFormat?: string, timezone?: string, showDate?: boolean}} */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, }, data() { @@ -145,15 +148,20 @@ export default { }, /** - * Resolved IANA timezone, or '' to use the browser/device timezone. + * Resolved IANA timezone: the configured one, else the viewer's + * Nextcloud timezone, else '' for the browser/device timezone. * * @return {string} the IANA timezone name, or the empty string. * @spec openspec/specs/clock-weather-widgets/spec.md */ timezone() { - return typeof this.content?.timezone === 'string' + const configured = typeof this.content?.timezone === 'string' ? this.content.timezone : DEFAULT_CONTENT.timezone + if (configured !== '') { + return configured + } + return typeof this.userTimezone === 'string' ? this.userTimezone : '' }, /** diff --git a/src/components/Widgets/Renderers/ClockWidgetForm.vue b/src/components/Widgets/Renderers/ClockWidgetForm.vue index a98b69c41..bbe8c40b5 100644 --- a/src/components/Widgets/Renderers/ClockWidgetForm.vue +++ b/src/components/Widgets/Renderers/ClockWidgetForm.vue @@ -58,6 +58,10 @@ <script> import { translate as t } from '@nextcloud/l10n' import { NcCheckboxRadioSwitch, NcSelect } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' const DEFAULT_CONTENT = Object.freeze({ style: 'digital', @@ -129,20 +133,14 @@ export default { * * @type {{content: object}|null} */ - editingWidget: { - type: Object, - default: null, - }, + editingWidget: NULLABLE_OBJECT_PROP, /** * Initial content values — used when not editing. * * @type {object} */ - value: { - type: Object, - default: () => ({ ...DEFAULT_CONTENT }), - }, + value: objectProp(DEFAULT_CONTENT), }, emits: ['update:content'], diff --git a/src/components/Widgets/Renderers/ColleagueActivityWidget.vue b/src/components/Widgets/Renderers/ColleagueActivityWidget.vue new file mode 100644 index 000000000..8d58f81e3 --- /dev/null +++ b/src/components/Widgets/Renderers/ColleagueActivityWidget.vue @@ -0,0 +1,268 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="colleague-activity" data-testid="colleague-activity-widget"> + <p + v-if="loading" + class="colleague-activity__state" + data-testid="colleague-activity-loading"> + {{ t('launchpad', 'Loading recent activity…') }} + </p> + + <p + v-else-if="loadFailed" + class="colleague-activity__state" + role="alert" + data-testid="colleague-activity-error"> + {{ t('launchpad', 'Recent activity could not be loaded. Reload the page to try again.') }} + </p> + + <p + v-else-if="!available" + class="colleague-activity__state" + data-testid="colleague-activity-unavailable"> + {{ t('launchpad', 'Recent activity needs the Activity app.') }} + </p> + + <template v-else> + <p class="colleague-activity__summary" data-testid="colleague-activity-total"> + {{ summary }} + </p> + <WidgetRowFilter v-if="entries.length > 0" v-model="rowFilter" /> + <ul + v-if="filteredEntries.length > 0" + class="colleague-activity__list" + data-testid="colleague-activity-list"> + <li + v-for="entry in filteredEntries" + :key="entry.id" + class="colleague-activity__item" + :data-testid="`colleague-activity-entry-${entry.id}`"> + <span class="colleague-activity__actor">{{ entry.actorDisplayName }}</span> + <a + v-if="entry.link" + class="colleague-activity__what" + :href="entry.link"> + {{ describe(entry) }} + </a> + <span v-else class="colleague-activity__what">{{ describe(entry) }}</span> + <time + class="colleague-activity__when" + :datetime="isoTime(entry.timestamp)"> + {{ shortTime(entry.timestamp) }} + </time> + </li> + </ul> + <p + v-else-if="entries.length === 0" + class="colleague-activity__state" + data-testid="colleague-activity-empty"> + {{ t('launchpad', 'No recent activity by colleagues that you can see.') }} + </p> + </template> + </div> +</template> + +<script> +import { translatePlural as n, translate as t } from '@nextcloud/l10n' +import WidgetRowFilter from '../WidgetRowFilter.vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { loadColleagueActivity } from '../../../services/colleagueActivity.js' +import { logger } from '../../../utils/logger.js' +import { filterRows } from '../../../utils/rowFilter.js' + +const DEFAULT_LIMIT = 10 +const MAX_LIMIT = 50 +const DEFAULT_DAYS = 7 +const MAX_DAYS = 90 + +/** + * Bound a configured number to 1..max, falling back when it is not one. + * + * @param {number|string|undefined} value the configured value + * @param {number} fallback the default + * @param {number} max the upper bound + * @return {number} the bounded number + */ +function bounded(value, fallback, max) { + const number = Number(value) + if (!Number.isInteger(number) || number < 1) { + return fallback + } + return Math.min(number, max) +} + +/** + * ColleagueActivityWidget — what colleagues did recently, as the reader may + * see it (REQ-DWMS-007). The server leaves out what the reader may not see + * and counts only what it lists; the widget shows its totals unchanged and + * never adds anything back. + */ +export default { + name: 'ColleagueActivityWidget', + components: { + WidgetRowFilter, + }, + + props: { + /** Persisted widget content: `{ limit, days }`. */ + content: OBJECT_PROP, + }, + + data() { + return { + loading: true, + loadFailed: false, + available: true, + entries: [], + total: 0, + actors: 0, + days: DEFAULT_DAYS, + // REQ-DWMS-008: view state only, never saved. + rowFilter: '', + } + }, + + computed: { + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 */ + limit() { + return bounded(this.content?.limit, DEFAULT_LIMIT, MAX_LIMIT) + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 */ + periodDays() { + return bounded(this.content?.days, DEFAULT_DAYS, MAX_DAYS) + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-6.1 */ + filteredEntries() { + return filterRows(this.entries, this.rowFilter, ['actorDisplayName', 'title', 'type']) + }, + + /** + * The totals line, from the server's figures: only entries the reader may see are in them. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.2 + */ + summary() { + return n( + 'launchpad', + '{count} action by colleagues in the last {days} days', + '{count} actions by colleagues in the last {days} days', + this.total, + { count: this.total, days: this.days }, + ) + }, + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 */ + async created() { + await this.load() + }, + + methods: { + t, + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 */ + async load() { + this.loading = true + this.loadFailed = false + try { + const result = await loadColleagueActivity({ limit: this.limit, days: this.periodDays }) + this.available = result.available + this.entries = result.entries + this.total = result.total + this.actors = result.actors + this.days = result.days + } catch (error) { + logger.error('Failed to load colleague activity:', error) + this.loadFailed = true + } finally { + this.loading = false + } + }, + + /** + * What the entry is about: the dashboard's title when it names one, else its kind. + * + * @param {object} entry the entry + * @return {string} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 + */ + describe(entry) { + const kind = String(entry.type || '').replace(/_/g, ' ') + return entry.title ? `${entry.title} (${kind})` : kind + }, + + /** + * @param {number} timestamp Unix seconds + * @return {string} the ISO time + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 + */ + isoTime(timestamp) { + return new Date(Number(timestamp) * 1000).toISOString() + }, + + /** + * @param {number} timestamp Unix seconds + * @return {string} the local date and time + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 + */ + shortTime(timestamp) { + return new Date(Number(timestamp) * 1000).toLocaleString(undefined, { + dateStyle: 'short', + timeStyle: 'short', + }) + }, + }, +} +</script> + +<style scoped> +.colleague-activity { + display: flex; + flex-direction: column; + gap: 4px; + height: 100%; + overflow-y: auto; + padding: 4px 12px 12px; +} + +.colleague-activity__state, +.colleague-activity__summary { + color: var(--color-text-maxcontrast); + margin: 0; +} + +.colleague-activity__list { + list-style: none; + margin: 0; + padding: 0; +} + +.colleague-activity__item { + display: flex; + flex-wrap: wrap; + gap: 4px 8px; + align-items: baseline; + padding: 6px 0; + border-bottom: 1px solid var(--color-border); +} + +.colleague-activity__actor { + font-weight: bold; + color: var(--color-main-text); +} + +.colleague-activity__what { + flex: 1 1 auto; + color: var(--color-main-text); +} + +.colleague-activity__when { + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/ColleagueActivityWidgetForm.vue b/src/components/Widgets/Renderers/ColleagueActivityWidgetForm.vue new file mode 100644 index 000000000..7302431bb --- /dev/null +++ b/src/components/Widgets/Renderers/ColleagueActivityWidgetForm.vue @@ -0,0 +1,138 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="colleague-activity-form"> + <p class="colleague-activity-form__hint"> + {{ + t( + 'launchpad', + 'Shows what colleagues did recently. Only what you are allowed to see is listed or counted.', + ) + }} + </p> + + <NcSelect + :modelValue="limit" + :options="limitOptions" + :inputLabel="t('launchpad', 'Lines to show')" + :clearable="false" + @update:modelValue="updateLimit" /> + + <NcSelect + :modelValue="days" + :options="dayOptions" + :inputLabel="t('launchpad', 'Days back')" + :clearable="false" + @update:modelValue="updateDays" /> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcSelect } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' + +const DEFAULT_LIMIT = 10 +const DEFAULT_DAYS = 7 +const LIMIT_OPTIONS = [5, 10, 20, 50] +const DAY_OPTIONS = [1, 7, 14, 30, 90] + +/** + * ColleagueActivityWidgetForm — the two settings of the colleague activity + * widget: how many lines it lists and how many days back it looks + * (REQ-DWMS-007). What may be seen is decided by the server. + */ +export default { + name: 'ColleagueActivityWidgetForm', + + components: { NcSelect }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** + * Initial content values, used when not editing. + * + * @type {object} + */ + value: objectProp({ limit: DEFAULT_LIMIT, days: DEFAULT_DAYS }), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + limitOptions: LIMIT_OPTIONS, + dayOptions: DAY_OPTIONS, + limit: LIMIT_OPTIONS.includes(Number(initial.limit)) ? Number(initial.limit) : DEFAULT_LIMIT, + days: DAY_OPTIONS.includes(Number(initial.days)) ? Number(initial.days) : DEFAULT_DAYS, + } + }, + + methods: { + t, + + /** + * Keep the new limit and tell the modal. + * + * @param {number} limit Lines to show. + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 + */ + updateLimit(limit) { + this.limit = LIMIT_OPTIONS.includes(Number(limit)) ? Number(limit) : DEFAULT_LIMIT + this.emitContent() + }, + + /** + * Keep the new period and tell the modal. + * + * @param {number} days Days back. + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 + */ + updateDays(days) { + this.days = DAY_OPTIONS.includes(Number(days)) ? Number(days) : DEFAULT_DAYS + this.emitContent() + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 */ + emitContent() { + this.$emit('update:content', { limit: this.limit, days: this.days }) + }, + + /** + * Validate the form. Both settings always have a valid value. + * + * @return {string[]} The validation errors (always empty). + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 + */ + validate() { + return [] + }, + }, +} +</script> + +<style scoped> +.colleague-activity-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.colleague-activity-form__hint { + color: var(--color-text-maxcontrast); + margin: 0; +} +</style> diff --git a/src/components/Widgets/Renderers/CommunitiesWidget.vue b/src/components/Widgets/Renderers/CommunitiesWidget.vue new file mode 100644 index 000000000..6ff0a3853 --- /dev/null +++ b/src/components/Widgets/Renderers/CommunitiesWidget.vue @@ -0,0 +1,348 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="communities-widget" data-testid="communities-widget"> + <h3 v-if="title" class="communities-widget__title"> + {{ title }} + </h3> + + <p + v-if="state === 'no-talk'" + class="communities-widget__state" + data-testid="communities-no-talk"> + {{ + t( + 'launchpad', + 'Communities need Nextcloud Talk. Ask your administrator to enable it.', + ) + }} + </p> + + <p + v-else-if="state === 'loading'" + class="communities-widget__state" + data-testid="communities-loading"> + {{ t('launchpad', 'Loading communities…') }} + </p> + + <p + v-else-if="state === 'error'" + class="communities-widget__state communities-widget__state--failed" + role="alert" + data-testid="communities-error"> + {{ + t( + 'launchpad', + 'The communities could not be loaded. Reload the page to try again.', + ) + }} + </p> + + <p + v-else-if="state === 'empty'" + class="communities-widget__state" + data-testid="communities-empty"> + {{ + onlyPinned + ? t('launchpad', 'Your organisation has not pinned a community you can see yet.') + : t('launchpad', 'There are no open communities to join yet.') + }} + </p> + + <ul v-else class="communities-widget__list" data-testid="communities-list"> + <li + v-for="community in visibleCommunities" + :key="community.token" + class="communities-widget__item" + :data-testid="`community-${community.token}`"> + <span class="communities-widget__text"> + <strong class="communities-widget__name">{{ community.name }}</strong> + <span + v-if="community.pinned" + class="communities-widget__pinned" + data-testid="community-pinned"> + {{ t('launchpad', 'Pinned by your organisation') }} + </span> + <span v-if="community.description" class="communities-widget__description"> + {{ community.description }} + </span> + <span + v-if="community.members !== null" + class="communities-widget__members"> + {{ + n( + 'launchpad', + '%n member', + '%n members', + community.members, + ) + }} + </span> + </span> + + <a + v-if="community.joined" + class="communities-widget__action button-vue" + :href="openUrl(community.token)" + data-testid="community-open"> + {{ t('launchpad', 'Open') }} + </a> + <NcButton + v-else + variant="primary" + :disabled="joining === community.token" + :aria-label="t('launchpad', 'Join {name}', { name: community.name })" + data-testid="community-join" + @click="join(community)"> + {{ t('launchpad', 'Join') }} + </NcButton> + </li> + </ul> + + <p + v-if="joinError" + class="communities-widget__state communities-widget__state--failed" + role="alert" + data-testid="communities-join-error"> + {{ joinError }} + </p> + </div> +</template> + +<script> +import { translatePlural as n, translate as t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { + communityUrl, + joinCommunity, + loadCommunities, +} from '../../../services/talkCommunities.js' +import { logger } from '../../../utils/logger.js' + +/** + * CommunitiesWidget: the open Talk conversations the viewer may join, with + * the organisation's pinned ones first (openspec/changes/engagement-communities). + * + * Talk is called from the browser as the viewer, so Talk decides what each + * person sees and may join. Without Talk the widget says so and calls nothing. + */ +export default { + name: 'CommunitiesWidget', + + components: { NcButton }, + + inject: { + /** Whether Talk is enabled for the viewer, from the initial state (REQ-COMM-004). */ + talkEnabled: { from: 'talkEnabled', default: false }, + /** The tokens the organisation pinned, in the order pinned (REQ-COMM-003). */ + pinnedCommunities: { from: 'pinnedCommunities', default: () => [] }, + }, + + props: { + /** Persisted widget content: `{ title, onlyPinned }`. */ + content: OBJECT_PROP, + + /** + * The placement row this widget renders as. Declared so the binding + * `WidgetRenderer` passes every renderer does not fall through as an + * attribute; the widget reads nothing from it. + */ + // eslint-disable-next-line vue/no-unused-properties + placement: OBJECT_PROP, + }, + + data() { + return { + loading: true, + loadFailed: false, + communities: [], + joining: '', + joinError: '', + } + }, + + computed: { + /** @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 */ + title() { + return String(this.content?.title || '').trim() + }, + + /** @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 */ + onlyPinned() { + return this.content?.onlyPinned === true + }, + + /** + * The communities shown: every one, or only the pinned ones. + * + * @return {Array<object>} The communities. + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 + */ + visibleCommunities() { + return this.onlyPinned + ? this.communities.filter((community) => community.pinned) + : this.communities + }, + + /** + * Which state the widget is in. + * + * @return {string} `no-talk`, `loading`, `error`, `empty` or `list`. + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-without-talk-the-widget-explains-itself-req-comm-004 + */ + state() { + if (this.talkEnabled !== true) { + return 'no-talk' + } + if (this.loading) { + return 'loading' + } + if (this.loadFailed) { + return 'error' + } + return this.visibleCommunities.length === 0 ? 'empty' : 'list' + }, + }, + + /** @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-without-talk-the-widget-explains-itself-req-comm-004 */ + async created() { + if (this.talkEnabled !== true) { + this.loading = false + return + } + await this.load() + }, + + methods: { + t, + n, + + /** + * Load the communities from Talk. + * + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-the-communities-widget-lists-open-talk-conversations-the-viewer-may-join-req-comm-001 + */ + async load() { + this.loading = true + this.loadFailed = false + try { + this.communities = await loadCommunities(this.pinnedCommunities) + } catch (error) { + logger.error('Communities could not be loaded from Talk', { error }) + this.loadFailed = true + } finally { + this.loading = false + } + }, + + /** + * Join a community; on success its button becomes "Open". + * + * @param {object} community The community. + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-one-click-joins-a-community-req-comm-002 + */ + async join(community) { + this.joining = community.token + this.joinError = '' + try { + await joinCommunity(community.token) + this.communities = this.communities.map((entry) => + entry.token === community.token ? { ...entry, joined: true } : entry, + ) + } catch (error) { + logger.error('Joining a Talk community failed', { error }) + this.joinError = t('launchpad', 'You could not join {name}. Try again later.', { + name: community.name, + }) + } finally { + this.joining = '' + } + }, + + /** + * The Talk page of a community. + * + * @param {string} token The conversation token. + * @return {string} The URL. + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-one-click-joins-a-community-req-comm-002 + */ + openUrl(token) { + return communityUrl(token) + }, + }, +} +</script> + +<style scoped> +.communities-widget { + display: flex; + flex-direction: column; + gap: 8px; + height: 100%; + overflow: auto; +} + +.communities-widget__title { + margin: 0; + font-size: 1.1em; +} + +.communities-widget__state { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.communities-widget__state--failed { + color: var(--color-error-text, var(--color-error)); +} + +.communities-widget__list { + display: flex; + flex-direction: column; + gap: 8px; + margin: 0; + padding: 0; + list-style: none; +} + +.communities-widget__item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 8px; + border-radius: var(--border-radius-large, var(--border-radius)); + background: var(--color-background-hover); +} + +.communities-widget__text { + display: flex; + flex-direction: column; + min-width: 0; +} + +.communities-widget__pinned { + font-size: 0.85em; + font-weight: bold; + color: var(--color-main-text); +} + +.communities-widget__description, +.communities-widget__members { + font-size: 0.9em; + color: var(--color-text-maxcontrast); +} + +.communities-widget__action { + flex-shrink: 0; + padding: 6px 14px; + border-radius: var(--border-radius-element, var(--border-radius-large)); + border: 1px solid var(--color-border-dark); + color: var(--color-main-text); + text-decoration: none; +} +</style> diff --git a/src/components/Widgets/Renderers/CommunitiesWidgetForm.vue b/src/components/Widgets/Renderers/CommunitiesWidgetForm.vue new file mode 100644 index 000000000..642146ed4 --- /dev/null +++ b/src/components/Widgets/Renderers/CommunitiesWidgetForm.vue @@ -0,0 +1,117 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="communities-widget-form"> + <p class="communities-widget-form__hint"> + {{ + t( + 'launchpad', + 'Lists the open Talk conversations each person may join. Talk decides who sees which conversation.', + ) + }} + </p> + + <NcTextField + :modelValue="title" + :label="t('launchpad', 'Title')" + @update:modelValue="update({ title: $event })" /> + + <NcCheckboxRadioSwitch + type="switch" + :modelValue="onlyPinned" + data-testid="communities-only-pinned" + @update:modelValue="update({ onlyPinned: $event === true })"> + {{ t('launchpad', 'Show only pinned') }} + </NcCheckboxRadioSwitch> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcCheckboxRadioSwitch, NcTextField } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' + +/** + * CommunitiesWidgetForm: the title of the Communities widget and whether it + * shows only the organisation's pinned communities + * (openspec/changes/engagement-communities, REQ-COMM-003). + */ +export default { + name: 'CommunitiesWidgetForm', + + components: { NcCheckboxRadioSwitch, NcTextField }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** + * Initial content values, used when not editing. + * + * @type {object} + */ + value: objectProp({ title: '', onlyPinned: false }), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + title: String(initial.title || ''), + onlyPinned: initial.onlyPinned === true, + } + }, + + methods: { + t, + + /** + * Keep a change and tell the modal the whole content. + * + * @param {object} change The changed keys. + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 + */ + update(change) { + Object.assign(this, change) + this.$emit('update:content', { + title: this.title, + onlyPinned: this.onlyPinned, + }) + }, + + /** + * Validate the form. Both settings are optional. + * + * @return {string[]} The validation errors (always empty). + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 + */ + validate() { + return [] + }, + }, +} +</script> + +<style scoped> +.communities-widget-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.communities-widget-form__hint { + color: var(--color-text-maxcontrast); + margin: 0; +} +</style> diff --git a/src/components/Widgets/Renderers/ConnectionsWidget.vue b/src/components/Widgets/Renderers/ConnectionsWidget.vue new file mode 100644 index 000000000..cd2720e05 --- /dev/null +++ b/src/components/Widgets/Renderers/ConnectionsWidget.vue @@ -0,0 +1,187 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="connections-widget" data-testid="connections-widget"> + <p v-if="!hasIntegriq" class="connections-widget__state" data-testid="connections-no-app"> + {{ t('launchpad', 'Connection states need the Integrations app') }} + </p> + <p v-else-if="used.length === 0" class="connections-widget__state" data-testid="connections-none"> + {{ t('launchpad', 'No widget on this dashboard uses an outside connection') }} + </p> + <p v-else-if="state === 'loading'" class="connections-widget__state" data-testid="connections-loading"> + {{ t('launchpad', 'Loading connection states …') }} + </p> + <p v-else-if="state === 'error'" class="connections-widget__state" data-testid="connections-error"> + {{ t('launchpad', 'The connection states could not be loaded. Try again later.') }} + </p> + <ul v-else class="connections-widget__list"> + <li + v-for="line in lines" + :key="line.key" + class="connections-widget__item" + :data-testid="'connection-' + line.key"> + <div class="connections-widget__head"> + <span class="connections-widget__title">{{ line.title }}</span> + <span + class="connections-widget__status" + :class="{ 'connections-widget__status--error': line.isError }" + data-testid="connection-status">{{ line.statusLabel }}</span> + </div> + <div class="connections-widget__meta" data-testid="connection-success"> + {{ t('launchpad', 'Last success: {time}', { time: timeText(line.lastSuccessAt) }) }} + </div> + <div v-if="line.lastErrorAt" class="connections-widget__meta" data-testid="connection-error"> + {{ t('launchpad', 'Last error: {time}', { time: timeText(line.lastErrorAt) }) }}<template v-if="line.message"> + · {{ line.message }} + </template> + </div> + </li> + </ul> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { connectionsUsedBy, fetchConnectionRows, joinConnectionStates } from '../../../services/dashboardConnections.js' + +/** + * ConnectionsWidget: the `connections` widget, "Koppelingen van dit + * dashboard" (board LpManagement). Lists, once each, the declared connections + * the placements on its own dashboard use, with the status the Integrations + * page names, the last success and the last error with its message, as + * integriq holds them. The rows are read through OpenRegister with the + * viewer's own session; the widget never calls a connection itself. + * + * The dashboard's placements come from the `dashboardPlacements` the + * dashboard view provides. Without integriq the widget says so. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +export default { + name: 'ConnectionsWidget', + + inject: { + /** Which apps behind the integration widgets are enabled for the viewer. */ + integrationApps: { from: 'integrationApps', default: () => ({}) }, + /** The open dashboard's placements, a ref provided by the dashboard view. */ + dashboardPlacements: { from: 'dashboardPlacements', default: null }, + }, + + props: { + // The widget has no settings; declared so it stays out of $attrs. + // eslint-disable-next-line vue/no-unused-properties + content: OBJECT_PROP, + // eslint-disable-next-line vue/no-unused-properties + placement: OBJECT_PROP, + }, + + data() { + return { state: 'loading', rows: [] } + }, + + computed: { + /** + * @return {boolean} Whether integriq is enabled for the viewer. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ + hasIntegriq() { + const app = this.integrationApps?.integriq + return app === true || (typeof app === 'string' && app !== '') + }, + + /** + * @return {Array<object>} The declared connections this dashboard's placements use. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ + used() { + const placements = this.dashboardPlacements?.value ?? this.dashboardPlacements + return connectionsUsedBy(Array.isArray(placements) ? placements : []) + }, + + /** + * @return {Array<object>} The connections in use with their states. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ + lines() { + return joinConnectionStates(this.used, this.rows) + }, + }, + + /** @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections */ + async created() { + if (!this.hasIntegriq) { + return + } + const result = await fetchConnectionRows() + this.rows = result.rows + this.state = result.state + }, + + methods: { + t, + + /** + * A time in the reader's locale, or "Not yet". + * + * @param {string|null} at The ISO time. + * @return {string} The time text. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ + timeText(at) { + const date = at ? new Date(at) : null + if (!date || Number.isNaN(date.getTime())) { + return t('launchpad', 'Not yet') + } + return date.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + }, + }, +} +</script> + +<style scoped> +.connections-widget { + display: flex; + flex-direction: column; + gap: 8px; + height: 100%; + min-height: 0; + overflow-y: auto; +} + +.connections-widget__state { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.connections-widget__list { + display: flex; + flex-direction: column; + gap: 10px; + margin: 0; + padding: 0; + list-style: none; +} + +.connections-widget__head { + display: flex; + justify-content: space-between; + gap: 8px; +} + +.connections-widget__title { + font-weight: 600; +} + +.connections-widget__status--error { + color: var(--color-error-text); +} + +.connections-widget__meta { + font-size: 13px; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/ConnectionsWidgetForm.vue b/src/components/Widgets/Renderers/ConnectionsWidgetForm.vue new file mode 100644 index 000000000..ae0af6a34 --- /dev/null +++ b/src/components/Widgets/Renderers/ConnectionsWidgetForm.vue @@ -0,0 +1,64 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="connections-widget-form"> + <p class="connections-widget-form__hint"> + {{ t('launchpad', 'Lists the outside connections the widgets on this dashboard use, with the state the Integrations app holds for each. Each person sees what OpenRegister lets them see.') }} + </p> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NULLABLE_OBJECT_PROP, objectProp } from '../../../constants/propDefinitions.js' + +/** + * ConnectionsWidgetForm: the `connections` widget has no settings; the + * form says what it shows. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +export default { + name: 'ConnectionsWidgetForm', + + props: { + /** The placement being edited, or `null` in create mode. */ + // eslint-disable-next-line vue/no-unused-properties + editingWidget: NULLABLE_OBJECT_PROP, + /** Initial content values, used when not editing. */ + // eslint-disable-next-line vue/no-unused-properties + value: objectProp({}), + }, + + emits: ['update:content'], + + /** @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections */ + mounted() { + this.$emit('update:content', {}) + }, + + methods: { + t, + + /** + * Nothing to validate. + * + * @return {string[]} No errors. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ + validate() { + return [] + }, + }, +} +</script> + +<style scoped> +.connections-widget-form__hint { + margin: 0; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/ContainerChild.vue b/src/components/Widgets/Renderers/ContainerChild.vue index 63bce59a0..55293c373 100644 --- a/src/components/Widgets/Renderers/ContainerChild.vue +++ b/src/components/Widgets/Renderers/ContainerChild.vue @@ -4,9 +4,28 @@ --> <template> + <!-- REQ-TILE-041: in edit mode a tile in a group opens the tile form. --> + <div v-if="childRenderer && showsTileEdit" class="container-child container-child--tile"> + <component + :is="childRenderer" + :content="childContent" + :placement="placement" + :editMode="editMode" + v-bind="extraProps" /> + <!-- The same tile menu as a tile on the dashboard (REQ-TILE-010). --> + <div class="container-child__edit" data-testid="container-child-tile-menu"> + <CnWidgetEditCog + icon="kebab" + :menuLabel="tileMenuLabel" + :editLabel="editTileLabel" + :deleteLabel="deleteTileLabel" + @edit="$emit('editTile')" + @remove="$emit('removeTile')" /> + </div> + </div> <component :is="childRenderer" - v-if="childRenderer" + v-else-if="childRenderer" :content="childContent" :placement="placement" :editMode="editMode" @@ -17,11 +36,17 @@ </template> <script> +import { CnWidgetEditCog } from '@conduction/nextcloud-vue' +import { + FLAG_PROP, + REQUIRED_OBJECT_PROP, +} from '../../../constants/propDefinitions.js' import { getWidgetTypeEntry } from '../../../constants/widgetRegistry.js' import { buildRendererExtraProps, buildWidgetDataProvide, } from '../../../services/widgetDataAdapters.js' +import { isGroupTileChild } from '../../../utils/groupTiles.js' /** * ContainerChild — registry-driven dispatcher for a single child placement @@ -46,6 +71,10 @@ import { export default { name: 'ContainerChild', + components: { + CnWidgetEditCog, + }, + /** * Bridge the nc-vue data widgets' injected sources to launchpad's * endpoints, scoped to this child's placement. Without this a nested @@ -57,21 +86,20 @@ export default { * @return {object} the injected data-source adapters. */ provide() { - return buildWidgetDataProvide(() => this.placement?.id) + return buildWidgetDataProvide(() => this.placement?.id, () => this.placement?.content) }, props: { - placement: { - type: Object, - required: true, - }, + placement: REQUIRED_OBJECT_PROP, - editMode: { - type: Boolean, - default: false, - }, + editMode: FLAG_PROP, + + /** Whether the dashboard can open the tile form for this child. */ + canEditTile: FLAG_PROP, }, + emits: ['editTile', 'removeTile'], + computed: { /** * Per-type extra props for nc-vue renderers that take a prop (files @@ -103,6 +131,32 @@ export default { return this.placement?.content || {} }, + /** + * Whether this child shows the edit cog of a tile: in edit mode, for a + * tile the tile form can edit, when the dashboard offers the form. + * + * @return {boolean} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + showsTileEdit() { + return this.editMode && this.canEditTile && isGroupTileChild(this.placement) + }, + + /** @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 */ + tileMenuLabel() { + return t('launchpad', 'Tile menu') + }, + + /** @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 */ + editTileLabel() { + return t('launchpad', 'Edit tile') + }, + + /** @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 */ + deleteTileLabel() { + return t('launchpad', 'Delete tile') + }, + /** @spec openspec/specs/container-widget/spec.md */ unknownLabel() { const type = this.placement?.type || '' @@ -118,6 +172,18 @@ export default { height: 100%; } +.container-child--tile { + position: relative; +} + +.container-child__edit { + position: absolute; + top: 2px; + inset-inline-end: 2px; + z-index: 1; + pointer-events: auto; +} + .container-child--unknown { display: flex; align-items: center; diff --git a/src/components/Widgets/Renderers/ContainerWidget.vue b/src/components/Widgets/Renderers/ContainerWidget.vue index 1296f97d2..30133b11d 100644 --- a/src/components/Widgets/Renderers/ContainerWidget.vue +++ b/src/components/Widgets/Renderers/ContainerWidget.vue @@ -5,21 +5,44 @@ <template> <div class="container-widget" :style="wrapperStyle"> - <h4 v-if="hasTitle" class="container-widget__title"> - {{ titleText }} - </h4> + <div v-if="hasTitle || canForgetUsage" class="container-widget__header"> + <h4 v-if="hasTitle" class="container-widget__title"> + {{ titleText }} + </h4> + <NcButton + v-if="canForgetUsage" + class="container-widget__forget" + variant="tertiary" + data-testid="container-forget-usage" + @click="forgetUsage"> + {{ t('launchpad', 'Forget my usage') }} + </NcButton> + </div> + + <p v-if="sortDescription" :id="descriptionId" class="hidden-visually"> + {{ sortDescription }} + </p> - <div ref="innerGrid" class="grid-stack launchpad-container-grid"> + <div + ref="innerGrid" + class="grid-stack launchpad-container-grid" + :aria-describedby="sortDescription ? descriptionId : null"> <div - v-for="(child, index) in children" + v-for="(child, index) in displayedChildren" :key="childKey(child, index)" class="grid-stack-item container-widget__child" :gs-x="child.gridX || 0" :gs-y="child.gridY || 0" :gs-w="child.gridWidth || 2" - :gs-h="child.gridHeight || 2"> + :gs-h="child.gridHeight || 2" + :data-launchpad-child="index"> <div class="grid-stack-item-content"> - <ContainerChild :placement="child" :editMode="editMode" /> + <ContainerChild + :placement="child" + :editMode="editMode" + :canEditTile="canEditTiles" + @editTile="editTile(index)" + @removeTile="editTile(index, true)" /> </div> </div> </div> @@ -27,11 +50,29 @@ </template> <script> +import { getLanguage, translate as t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' import ContainerChild from './ContainerChild.vue' import { getNestedGridOptions, + NESTED_COLUMNS, useNestedGridManager, } from '../../../composables/useNestedGridManager.js' +import { useTileClickTracking } from '../../../composables/useTileClickTracking.js' +import { FLAG_PROP, OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { + childUseKey, + forgetTileUse, + normaliseSortMode, + readTileUse, + reflowChildren, + sortChildren, + USAGE_MODES, +} from '../../../utils/tileSort.js' + +const { recordTileUse } = useTileClickTracking() + +let descriptionCounter = 0 const PADDING_TOKENS = Object.freeze({ none: '0', @@ -62,33 +103,114 @@ export default { components: { ContainerChild, + NcButton, + }, + + /** + * The dashboard's opener of the tile form for a tile in a group + * (REQ-TILE-041); absent where no dashboard hosts the container. + */ + inject: { + openGroupTileEditor: { default: null }, }, props: { - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, - editMode: { - type: Boolean, - default: false, - }, + /** The container's own placement; its id keys children that have none. */ + placement: OBJECT_PROP, + + editMode: FLAG_PROP, }, emits: ['update:content'], data() { + descriptionCounter += 1 return { gridInstance: null, + // The viewer's usage as it was when the page loaded: the order + // changes on the next load, not while tiles are being clicked. + tileUse: readTileUse(), + descriptionId: `container-sort-${descriptionCounter}`, } }, computed: { - /** @spec openspec/specs/container-widget/spec.md */ + /** + * The stored children. A child without an id or uuid of its own (a + * bookmark import writes them that way) gets `<container id>-<index>` + * as its uuid, so its use can be counted and it keeps one key. + * + * @return {Array<object>} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ children() { const list = this.content?.placements - return Array.isArray(list) ? list : [] + if (!Array.isArray(list)) { + return [] + } + const owner = this.placement?.id + if (owner === undefined || owner === null) { + return list + } + return list.map((child, index) => (childUseKey(child) === '' + ? { ...child, uuid: `${owner}-${index}` } + : child)) + }, + + /** @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md */ + sortMode() { + return normaliseSortMode(this.content?.sortBy) + }, + + /** + * The children as shown: the stored layout in edit mode or when sorted + * by hand, otherwise sorted and reflowed row by row (REQ-TSO-001). + * Nothing here is written back. + * + * @return {Array<object>} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + displayedChildren() { + if (this.editMode || this.sortMode === 'manual') { + return this.children + } + const ordered = sortChildren(this.children, this.sortMode, { use: this.tileUse, locale: getLanguage() }) + return reflowChildren(ordered, NESTED_COLUMNS) + }, + + /** + * Whether the tiles in this group open the tile form: in edit mode, on a + * dashboard that offers it, for a container that is a placement of its own. + * + * @return {boolean} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + canEditTiles() { + const id = this.placement?.id + return this.editMode + && typeof this.openGroupTileEditor === 'function' + && id !== undefined + && id !== null + }, + + /** @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md */ + canForgetUsage() { + return !this.editMode && USAGE_MODES.includes(this.sortMode) + }, + + /** @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md */ + sortDescription() { + if (this.editMode) { + return '' + } + return { + alphabetical: t('launchpad', 'Sorted alphabetically'), + 'most-used': t('launchpad', 'Sorted by most used'), + 'last-used': t('launchpad', 'Sorted by last used'), + random: t('launchpad', 'Sorted at random'), + }[this.sortMode] ?? '' }, /** @spec openspec/specs/container-widget/spec.md */ @@ -137,15 +259,112 @@ export default { }, }, + /** @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md */ mounted() { + // A click anywhere in a child counts a use of that child; the child's + // own link or button stays the control (no click handler on the cell). + this.$refs.innerGrid?.addEventListener('click', this.onChildClick, true) this.initInnerGrid() }, + /** @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md */ beforeUnmount() { + this.$refs.innerGrid?.removeEventListener('click', this.onChildClick, true) this.destroyInnerGrid() }, methods: { + t, + + /** + * Open the tile form for the child at `index`. In edit mode the children + * are shown in their stored order, so the index is the stored position. + * + * @param {number} index The child's position in `content.placements`. + * @param {boolean} [remove] Remove the tile instead of opening the form. + * @return {void} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + editTile(index, remove = false) { + if (!this.canEditTiles || this.displayedChildren !== this.children) { + return + } + this.openGroupTileEditor({ containerId: this.placement.id, index, remove }) + }, + + /** + * Count a use of the child a click landed in. + * + * @param {MouseEvent} event The click, in its capture phase. + * @return {void} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + onChildClick(event) { + const grid = this.$refs.innerGrid + let cell = event.target?.closest?.('[data-launchpad-child]') ?? null + // A group inside this group has cells of its own: take this grid's. + while (cell && cell.parentElement !== grid) { + cell = cell.parentElement?.closest('[data-launchpad-child]') ?? null + } + const child = cell ? this.displayedChildren[Number(cell.dataset.launchpadChild)] : undefined + if (child) { + this.countUse(child) + } + }, + + /** + * Count a use of a child in this browser; only in view mode. + * + * @param {object} child The child placement. + * @return {void} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + countUse(child) { + if (this.editMode) { + return + } + recordTileUse(childUseKey(child)) + }, + + /** + * Forget this browser's usage of this container's tiles (REQ-TSO-003). + * + * @return {void} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + async forgetUsage() { + forgetTileUse(this.children.map(childUseKey).filter((key) => key !== '')) + this.tileUse = readTileUse() + await this.$nextTick() + this.moveGridItemsToAttributes() + }, + + /** + * Move every inner grid item to the position its `gs-*` attributes now + * name. GridStack keeps its own copy of each item's position, so a + * re-sorted view only shows its new order once the grid is told. + * + * @return {void} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + moveGridItemsToAttributes() { + const grid = this.gridInstance + if (!grid || typeof grid.update !== 'function' || !this.$refs.innerGrid) { + return + } + const items = this.$refs.innerGrid.querySelectorAll(':scope > .grid-stack-item') + grid.batchUpdate?.() + for (const el of items) { + grid.update(el, { + x: Number(el.getAttribute('gs-x') ?? 0), + y: Number(el.getAttribute('gs-y') ?? 0), + w: Number(el.getAttribute('gs-w') ?? 2), + h: Number(el.getAttribute('gs-h') ?? 2), + }) + } + grid.batchUpdate?.(false) + }, + /** * Stable key for v-for over child placements. Falls back to the * loop index when a child has neither id nor uuid, which keeps @@ -222,6 +441,11 @@ export default { * @spec openspec/specs/container-widget/spec.md */ onGridChange(_event, nodes) { + // A sorted view reflows the tiles; that order must never be + // written back (REQ-TSO-001). The stored layout persists as before. + if (this.displayedChildren !== this.children) { + return + } if (!Array.isArray(nodes) || nodes.length === 0) { return } @@ -296,6 +520,14 @@ export default { overflow: hidden; } +.container-widget__header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + pointer-events: auto; +} + .container-widget__title { margin: 0; font-size: 14px; diff --git a/src/components/Widgets/Renderers/ContainerWidgetForm.vue b/src/components/Widgets/Renderers/ContainerWidgetForm.vue new file mode 100644 index 000000000..89b100929 --- /dev/null +++ b/src/components/Widgets/Renderers/ContainerWidgetForm.vue @@ -0,0 +1,134 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="container-widget-form"> + <CnContainerWidgetForm + :editingWidget="editingWidget" + :value="value" + @update:content="onCommunalContent" /> + + <NcSelect + :modelValue="sortBy" + :options="sortOptions" + :inputLabel="t('launchpad', 'Sort tiles')" + :reduce="(option) => option.value" + label="label" + :clearable="false" + data-testid="container-sort-by" + @update:modelValue="onSortBy" /> + </div> +</template> + +<script> +import { CnContainerWidgetForm } from '@conduction/nextcloud-vue' +import { translate as t } from '@nextcloud/l10n' +import { NcSelect } from '@nextcloud/vue' +import { NULLABLE_OBJECT_PROP, objectProp } from '../../../constants/propDefinitions.js' +import { normaliseSortMode } from '../../../utils/tileSort.js' + +/** + * ContainerWidgetForm: the communal container fields (background, padding, + * title) plus "Sort tiles" (REQ-CONT-007 as LaunchPad extends it). The + * communal form stays unchanged for the other apps; this form adds `sortBy` + * to the content it emits. + * + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ +export default { + name: 'ContainerWidgetForm', + + components: { + CnContainerWidgetForm, + NcSelect, + }, + + props: { + editingWidget: NULLABLE_OBJECT_PROP, + + value: objectProp({ placements: [], backgroundColor: 'transparent', padding: 'medium', title: '', sortBy: 'manual' }), + }, + + emits: ['update:content'], + + /** @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md */ + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + content: { ...initial }, + sortBy: normaliseSortMode(initial.sortBy), + } + }, + + computed: { + /** @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md */ + sortOptions() { + return [ + { value: 'manual', label: t('launchpad', 'By hand') }, + { value: 'alphabetical', label: t('launchpad', 'Alphabetically') }, + { value: 'most-used', label: t('launchpad', 'Most used') }, + { value: 'last-used', label: t('launchpad', 'Last used') }, + { value: 'random', label: t('launchpad', 'At random') }, + ] + }, + }, + + methods: { + t, + + /** + * Keep what the communal fields emit and pass it on with the sort. + * + * @param {object} content The communal form's content. + * @return {void} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + onCommunalContent(content) { + this.content = { ...this.content, ...content } + this.emit() + }, + + /** + * Store the chosen sort. + * + * @param {string} value The chosen mode. + * @return {void} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + onSortBy(value) { + this.sortBy = normaliseSortMode(value) + this.emit() + }, + + /** + * Tell the host the whole content. + * + * @return {void} + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + emit() { + this.$emit('update:content', { ...this.content, sortBy: this.sortBy }) + }, + + /** + * Nothing is required. + * + * @return {Array<string>} No errors. + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md + */ + validate() { + return [] + }, + }, +} +</script> + +<style scoped> +.container-widget-form { + display: flex; + flex-direction: column; + gap: 12px; +} +</style> diff --git a/src/components/Widgets/Renderers/FilesWidget.vue b/src/components/Widgets/Renderers/FilesWidget.vue index c63a8fc03..d2d571bd0 100644 --- a/src/components/Widgets/Renderers/FilesWidget.vue +++ b/src/components/Widgets/Renderers/FilesWidget.vue @@ -204,21 +204,66 @@ * changes so re-configuring the widget root never leaves the user on * a stale path. */ + +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' + +/** + * Load the HTTP client and build one files-widget endpoint URL. + * + * @param {string} path The route template. + * @param {object} params The route parameters. + * @return {Promise<{axios: object, url: string}>} the client and the URL. + */ +async function filesEndpoint(path, params) { + const [{ default: axios }, { generateUrl }] = await Promise.all([ + import('@nextcloud/axios'), + import('@nextcloud/router'), + ]) + + return { axios, url: generateUrl(path, params) } +} + +/** + * A multipart form carrying every chosen file as `files[]`. + * + * @param {FileList} fileList The chosen files. + * @return {FormData} the upload form. + */ +function uploadFormData(fileList) { + const formData = new FormData() + for (let i = 0; i < fileList.length; i++) { + formData.append('files[]', fileList[i]) + } + return formData +} + +/** + * The error state a failed contents request maps to. + * + * @param {object} err The request error. + * @return {string} `folder_not_found`, `no_access` or `unknown_error`. + */ +function contentsErrorCode(err) { + const status = err?.response?.status + const code = err?.response?.data?.error + if (status === 404 || code === 'folder_not_found') { + return 'folder_not_found' + } + if (status === 403 || code === 'no_access') { + return 'no_access' + } + return 'unknown_error' +} + export default { name: 'FilesWidget', props: { /** Persisted content blob: see FilesForm for shape. */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** Placement entity (provides `id` for endpoint scoping). */ - placement: { - type: Object, - default: () => ({}), - }, + placement: OBJECT_PROP, /* * `isAdmin` / `canEdit` used to be declared here and were removed: no @@ -341,47 +386,73 @@ export default { this.errorCode = null try { - const [{ default: axios }, { generateUrl }] = await Promise.all([ - import('@nextcloud/axios'), - import('@nextcloud/router'), - ]) - - const url = generateUrl( - '/apps/launchpad/api/widgets/files/{placementId}/contents', - { placementId: this.placementId }, - ) - const params = { - currentPath: this.currentSubPath, - limit: 50, - } - if (append && this.nextCursor) { - params.cursor = this.nextCursor - } - - const response = await axios.get(url, { params }) - const data = response?.data || {} - const nextItems = Array.isArray(data.items) ? data.items : [] - this.items = append ? this.items.concat(nextItems) : nextItems - this.nextCursor = data.nextCursor || null + const data = await this.requestContents(append) + this.applyContents(data, append) } catch (err) { - const status = err?.response?.status - const code = err?.response?.data?.error - if (status === 404 || code === 'folder_not_found') { - this.errorCode = 'folder_not_found' - } else if (status === 403 || code === 'no_access') { - this.errorCode = 'no_access' - } else { - this.errorCode = 'unknown_error' - } - if (!append) { - this.items = [] - this.nextCursor = null - } + this.applyContentsError(err, append) } finally { this.loading = false } }, + /** + * Request one page of the current folder's contents. + * + * @param {boolean} append True to ask for the next cursor page. + * @return {Promise<object>} the response body, `{}` when absent. + */ + async requestContents(append) { + const { axios, url } = await filesEndpoint( + '/apps/launchpad/api/widgets/files/{placementId}/contents', + { placementId: this.placementId }, + ) + const response = await axios.get(url, { params: this.contentsParams(append) }) + return response?.data || {} + }, + + /** + * The query parameters of a contents request. + * + * @param {boolean} append True to add the next-page cursor. + * @return {object} the request parameters. + */ + contentsParams(append) { + const params = { + currentPath: this.currentSubPath, + limit: 50, + } + if (append && this.nextCursor) { + params.cursor = this.nextCursor + } + return params + }, + + /** + * Store a fetched page: appended to or replacing the list. + * + * @param {object} data The response body. + * @param {boolean} append True to append to the existing list. + */ + applyContents(data, append) { + const nextItems = Array.isArray(data.items) ? data.items : [] + this.items = append ? this.items.concat(nextItems) : nextItems + this.nextCursor = data.nextCursor || null + }, + + /** + * Record a failed fetch; a failed first page also clears the list. + * + * @param {object} err The request error. + * @param {boolean} append True when the failed request was a next page. + */ + applyContentsError(err, append) { + this.errorCode = contentsErrorCode(err) + if (!append) { + this.items = [] + this.nextCursor = null + } + }, + /** @spec openspec/specs/files-widget/spec.md */ loadMore() { if (this.nextCursor) { @@ -506,19 +577,7 @@ export default { return } try { - const [{ default: axios }, { generateUrl }] = await Promise.all([ - import('@nextcloud/axios'), - import('@nextcloud/router'), - ]) - - const url = generateUrl( - '/apps/launchpad/api/widgets/files/{placementId}/files/{fileId}', - { placementId: this.placementId, fileId: target.fileId }, - ) - await axios.delete(url) - this.items = this.items.filter( - (item) => item.fileId !== target.fileId, - ) + await this.deleteFile(target) } catch { // Swallow — refresh the listing so the UI stays // truthful even if the optimistic remove failed. @@ -528,6 +587,22 @@ export default { } }, + /** + * Delete one file and drop it from the list. + * + * @param {object} target The directory entry to delete. + */ + async deleteFile(target) { + const { axios, url } = await filesEndpoint( + '/apps/launchpad/api/widgets/files/{placementId}/files/{fileId}', + { placementId: this.placementId, fileId: target.fileId }, + ) + await axios.delete(url) + this.items = this.items.filter( + (item) => item.fileId !== target.fileId, + ) + }, + /** @spec openspec/specs/files-widget/spec.md */ triggerUpload() { if (this.$refs.fileInput) { @@ -547,32 +622,38 @@ export default { return } - const formData = new FormData() - for (let i = 0; i < fileList.length; i++) { - formData.append('files[]', fileList[i]) - } + const formData = uploadFormData(fileList) try { - const [{ default: axios }, { generateUrl }] = await Promise.all([ - import('@nextcloud/axios'), - import('@nextcloud/router'), - ]) - - const url = generateUrl( - '/apps/launchpad/api/widgets/files/{placementId}/upload', - { placementId: this.placementId }, - ) - await axios.post(url, formData, { - params: { currentPath: this.currentSubPath }, - }) + await this.postUpload(formData) this.fetchContents() } catch { // Surface failure by re-fetching; the user can retry. this.fetchContents() } finally { - if (this.$refs.fileInput) { - this.$refs.fileInput.value = '' - } + this.resetFileInput() + } + }, + + /** + * Upload a form of files into the current folder. + * + * @param {FormData} formData The files to upload. + */ + async postUpload(formData) { + const { axios, url } = await filesEndpoint( + '/apps/launchpad/api/widgets/files/{placementId}/upload', + { placementId: this.placementId }, + ) + await axios.post(url, formData, { + params: { currentPath: this.currentSubPath }, + }) + }, + + /** Clear the hidden file input so the same file can be chosen again. */ + resetFileInput() { + if (this.$refs.fileInput) { + this.$refs.fileInput.value = '' } }, diff --git a/src/components/Widgets/Renderers/IframeWidget.vue b/src/components/Widgets/Renderers/IframeWidget.vue index 69e00c673..d19c1f4c2 100644 --- a/src/components/Widgets/Renderers/IframeWidget.vue +++ b/src/components/Widgets/Renderers/IframeWidget.vue @@ -11,30 +11,57 @@ </div> <!-- Fallback card — never a silent blank frame (REQ-IFRAME-004). - Conveyed by icon AND text, never colour alone. --> + Conveyed by icon AND text, never colour alone. When the target + itself failed it is the outage state (REQ-IFRAME-005): what could + not be loaded, the cause and its time, Reload and Open in a new + tab. The "Outage" tag and the source line sit in the card head + (emitted as `status`). --> <div v-else-if="state === 'failed'" class="iframe-widget__fallback" - role="status"> + :class="{ 'iframe-widget__fallback--outage': isOutage }" + role="status" + :data-testid="isOutage ? 'iframe-widget-outage' : 'iframe-widget-fallback'"> <AlertCircleOutline :size="32" /> <span class="iframe-widget__fallback-title">{{ displayTitle }}</span> - <span class="iframe-widget__fallback-text">{{ fallbackMessage }}</span> - <a - v-if="hasUrl" - :href="url" - target="_blank" - rel="noopener noreferrer" - class="iframe-widget__fallback-link" - :aria-label=" - t('launchpad', 'Open {title} in a new tab', { - title: displayTitle, - }) - "> - <OpenInNew :size="16" /> - {{ t('launchpad', 'Open in new tab') }} - </a> + <span class="iframe-widget__fallback-text">{{ isOutage ? outageMessage : fallbackMessage }}</span> + <span + v-if="isOutage && outageCause" + class="iframe-widget__fallback-cause" + data-testid="iframe-widget-outage-cause">{{ outageCause }}</span> + <div v-if="hasUrl" class="iframe-widget__fallback-actions"> + <NcButton + v-if="isOutage" + variant="secondary" + data-testid="iframe-widget-reload" + @click="restart"> + <template #icon> + <Reload :size="16" /> + </template> + {{ t('launchpad', 'Reload') }} + </NcButton> + <a + :href="url" + target="_blank" + rel="noopener noreferrer" + class="iframe-widget__fallback-link" + :aria-label=" + t('launchpad', 'Open {title} in a new tab', { + title: displayTitle, + }) + "> + <OpenInNew :size="16" /> + {{ t('launchpad', 'Open in a new tab') }} + </a> + </div> </div> + <!-- REQ-DPD-003: a downloaded dashboard cannot carry another site's + page; the PDF names it instead (shown only in print). --> + <p class="iframe-widget__print-note" data-testid="iframe-widget-print-note"> + {{ printNote }} + </p> + <iframe v-if="hasUrl && state !== 'failed' && framableConfirmed" ref="frame" @@ -51,10 +78,21 @@ <script> import { translate as t } from '@nextcloud/l10n' -import { NcLoadingIcon } from '@nextcloud/vue' +import { NcButton, NcLoadingIcon } from '@nextcloud/vue' import AlertCircleOutline from 'vue-material-design-icons/AlertCircleOutline.vue' import OpenInNew from 'vue-material-design-icons/OpenInNew.vue' +import Reload from 'vue-material-design-icons/Reload.vue' +import { + NULLABLE_OBJECT_PROP, + OBJECT_PROP, +} from '../../../constants/propDefinitions.js' import { checkIframeFramable } from '../../../services/iframeClient.js' +import { + embedSourceLine, + isReport, + OUTAGE_REASONS, + outageCauseLine, +} from '../../../utils/embedOutage.js' /** * How long to wait for the iframe's `load` event before treating the embed @@ -80,6 +118,20 @@ const ASPECT_RATIO_MAP = { const DEFAULT_HEIGHT = 400 +/** + * The framable check's reason → the widget's failure reason. A host taken + * off the allow-list is policy, not an outage; a check that could not run + * is an outage with an unknown cause. + * + * @type {Record<string, string>} + */ +const CHECK_REASON_MAP = { + host_not_allowed: 'not_permitted', + x_frame_options: 'blocked', + frame_ancestors: 'blocked', + unreachable: 'unreachable', +} + /** * IframeWidget — the `iframe` dashboard widget type (REQ-IFRAME-001..004). * @@ -99,9 +151,11 @@ export default { name: 'IframeWidget', components: { + NcButton, NcLoadingIcon, AlertCircleOutline, OpenInNew, + Reload, }, props: { @@ -111,10 +165,7 @@ export default { * * @type {object} */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** * The widget placement (unused directly — the iframe embeds @@ -123,10 +174,7 @@ export default { * @type {{id?: number|string}|null} */ // eslint-disable-next-line vue/no-unused-properties -- absorbs WidgetRenderer's uniform binding; see above - placement: { - type: Object, - default: null, - }, + placement: NULLABLE_OBJECT_PROP, /** * Milliseconds to wait for the `load` event before treating the @@ -142,10 +190,15 @@ export default { }, }, + emits: ['status'], + data() { return { state: 'loading', failureReason: '', + // When the widget saw the failure (REQ-IFRAME-005 "the cause and + // its time"); null while nothing failed. + failedAt: null, loadTimer: null, // The iframe is NOT rendered until the server-side framable check // (REQ-IFRAME-003) confirms the target permits framing. Rendering @@ -170,6 +223,18 @@ export default { return this.url !== '' }, + /** + * The line a downloaded dashboard prints instead of the embedded page. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-reader-can-download-the-dashboard-req-dpd-003 + */ + printNote() { + return t('launchpad', '{title}: embedded pages are not included in the download', { + title: this.displayTitle, + }) + }, + /** @spec openspec/specs/iframe-embed-widget/spec.md */ displayTitle() { const title = @@ -221,14 +286,62 @@ export default { if (!this.hasUrl) { return t('launchpad', 'This embed has not been configured yet.') } - if (this.failureReason === 'blocked') { - return t( - 'launchpad', - 'This site does not allow itself to be embedded. Its owner blocks framing, which cannot be overridden here.', - ) + if (this.failureReason === 'not_permitted') { + return t('launchpad', 'This embed is no longer permitted by your administrator.') } return t('launchpad', 'This page could not be loaded.') }, + + /** + * Whether the failure is an outage of the target itself, as opposed + * to an unconfigured embed or one the administrator no longer permits. + * + * @return {boolean} True when the outage state shows. + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + isOutage() { + return this.state === 'failed' && OUTAGE_REASONS.includes(this.failureReason) + }, + + /** + * @return {string} "The report could not be loaded" or the page variant. + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + outageMessage() { + return isReport(this.content) + ? t('launchpad', 'The report could not be loaded') + : t('launchpad', 'The page could not be loaded') + }, + + /** + * @return {string} The cause and its time, or '' when no cause is known. + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + outageCause() { + return outageCauseLine( + { + content: this.content, + reason: this.failureReason, + failedAt: this.failedAt, + now: new Date(), + }, + t, + ) + }, + + /** + * What the card head shows for this embed: the source line under the + * title and whether the "Outage" tag is up. + * + * @return {{subtitle: string, outage: boolean}} The head status. + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + headStatus() { + return { + subtitle: embedSourceLine(this.content, t), + outage: this.isOutage, + } + }, }, watch: { @@ -244,6 +357,26 @@ export default { url() { this.restart() }, + + /** + * Tell the card head (WidgetWrapper) the source line and the outage + * tag whenever either changes. + * + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + headStatus: { + /** + * @param {{subtitle: string, outage: boolean}} status The head status. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + handler(status) { + this.$emit('status', status) + }, + + immediate: true, + deep: true, + }, }, mounted() { @@ -266,6 +399,7 @@ export default { restart() { this.clearTimer() this.framableConfirmed = false + this.failedAt = null if (!this.hasUrl) { this.state = 'failed' this.failureReason = 'unconfigured' @@ -287,8 +421,7 @@ export default { } if (result && result.framable === false) { this.clearTimer() - this.state = 'failed' - this.failureReason = 'blocked' + this.fail(CHECK_REASON_MAP[result.reason] ?? 'unknown') return } // Server confirms framing is permitted — ONLY NOW render the @@ -301,8 +434,7 @@ export default { this.clearTimer() this.loadTimer = setTimeout(() => { if (this.state === 'loading') { - this.state = 'failed' - this.failureReason = 'timeout' + this.fail('timeout') } }, this.loadTimeoutMs) }) @@ -343,8 +475,7 @@ export default { } if (blank) { - this.state = 'failed' - this.failureReason = 'blocked' + this.fail('blocked') return } @@ -360,8 +491,20 @@ export default { */ onError() { this.clearTimer() + this.fail('error') + }, + + /** + * Enter the failed state with a reason and the time it was seen. + * + * @param {string} reason The failure reason. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + fail(reason) { this.state = 'failed' - this.failureReason = 'error' + this.failureReason = reason + this.failedAt = new Date() }, /** @@ -383,6 +526,25 @@ export default { </script> <style scoped> +.iframe-widget__print-note { + display: none; + margin: 0; + padding: 12px; + color: var(--color-main-text); +} + +@media print { + .iframe-widget__print-note { + display: block; + } + + .iframe-widget__frame, + .iframe-widget__state, + .iframe-widget__fallback { + display: none !important; + } +} + .iframe-widget { width: 100%; position: relative; @@ -432,11 +594,24 @@ export default { font-size: 0.85rem; } +.iframe-widget__fallback-cause { + font-size: 0.85rem; + color: var(--color-main-text); +} + +.iframe-widget__fallback-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 12px; + margin-top: 6px; +} + .iframe-widget__fallback-link { display: inline-flex; align-items: center; gap: 4px; - margin-top: 6px; color: var(--color-primary-element, var(--color-main-text)); text-decoration: underline; } diff --git a/src/components/Widgets/Renderers/IframeWidgetForm.vue b/src/components/Widgets/Renderers/IframeWidgetForm.vue index 1c305b217..2a682b9e8 100644 --- a/src/components/Widgets/Renderers/IframeWidgetForm.vue +++ b/src/components/Widgets/Renderers/IframeWidgetForm.vue @@ -90,7 +90,12 @@ <script> import { translate as t } from '@nextcloud/l10n' import { NcCheckboxRadioSwitch, NcSelect, NcTextField } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' import { validateIframeUrl } from '../../../services/iframeClient.js' +import { allowListMessage, urlFieldErrors } from '../../../utils/urlAllowList.js' const DEFAULT_HEIGHT = 400 @@ -129,6 +134,9 @@ function sandboxTokenOptions() { * blur so authors get fast feedback, surfaced through the synchronous * `validate()` the modal's submit gate calls. */ +/** Validation codes that mean the URL itself was not confirmed allow-listed. */ +const URL_CHECK_FAILURES = ['url_required', 'invalid_url', 'host_not_allowed', 'validation_unavailable'] + export default { name: 'IframeWidgetForm', @@ -144,20 +152,14 @@ export default { * * @type {{content: object}|null} */ - editingWidget: { - type: Object, - default: null, - }, + editingWidget: NULLABLE_OBJECT_PROP, /** * Initial content values — used when not editing. * * @type {object} */ - value: { - type: Object, - default: () => ({ ...DEFAULT_CONTENT }), - }, + value: objectProp(DEFAULT_CONTENT), }, emits: ['update:content'], @@ -325,26 +327,35 @@ export default { return } const result = await validateIframeUrl(this.assembledContent) + // The check runs on leaving the URL field, often before a title is + // typed: only errors about the URL itself decide the host's status. this.allowListChecked = result.valid === true - if ( - result.valid === false - && result.errors.includes('host_not_allowed') - ) { - this.urlAllowListError = t( - 'launchpad', - 'This host is not on the allow-list.', - ) - } else if ( - result.valid === false - && result.errors.includes('invalid_url') - ) { - this.urlAllowListError = t('launchpad', 'Enter a valid http(s) URL.') - } else { - this.urlAllowListError = '' - } + || (Array.isArray(result.errors) + && !result.errors.some((code) => URL_CHECK_FAILURES.includes(code))) + this.urlAllowListError = this.hostRefusal(result) || allowListMessage(result) this.emitUpdate() }, + /** + * The refusal naming the host when the server says it is not on the + * allow-list (REQ-IFRAME-002), or `''`. + * + * @param {{valid: boolean, errors?: string[]}} result The server's validation answer. + * @return {string} + * @spec openspec/specs/iframe-embed-widget/spec.md + */ + hostRefusal(result) { + if (!Array.isArray(result.errors) || !result.errors.includes('host_not_allowed')) { + return '' + } + try { + const host = new URL(this.url.trim()).hostname + return t('launchpad', 'The host {host} is not on the allow-list.', { host }) + } catch { + return '' + } + }, + /** * Validate the form. Requires a syntactically valid URL and a * non-empty title (REQ-IFRAME-004 "Accessible frame title"). Any @@ -355,16 +366,7 @@ export default { * @spec openspec/specs/iframe-embed-widget/spec.md */ validate() { - const errors = [] - - if (typeof this.url !== 'string' || this.url.trim() === '') { - errors.push(t('launchpad', 'URL is required')) - } else if (!/^https?:\/\/.+/i.test(this.url.trim())) { - errors.push(t('launchpad', 'Enter a valid http(s) URL.')) - } - if (this.urlAllowListError) { - errors.push(this.urlAllowListError) - } + const errors = urlFieldErrors(this.url, this.urlAllowListError) if (typeof this.title !== 'string' || this.title.trim() === '') { errors.push(t('launchpad', 'Title is required')) diff --git a/src/components/Widgets/Renderers/ImageWidgetForm.vue b/src/components/Widgets/Renderers/ImageWidgetForm.vue new file mode 100644 index 000000000..cd6c6ea77 --- /dev/null +++ b/src/components/Widgets/Renderers/ImageWidgetForm.vue @@ -0,0 +1,579 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="image-widget-form"> + <fieldset class="image-widget-form__choices"> + <legend class="image-widget-form__legend"> + {{ t('launchpad', 'Where does the image come from?') }} + </legend> + <label + v-for="card in sourceCards" + :key="card.value" + class="image-widget-form__choice" + :class="{ 'image-widget-form__choice--selected': source === card.value }"> + <input + type="radio" + name="image-source" + class="image-widget-form__choice-input" + :value="card.value" + :checked="source === card.value" + :data-testid="'image-source-' + card.value" + @change="onSourceChange(card.value)"> + <span class="image-widget-form__choice-title">{{ card.title }}</span> + <span class="image-widget-form__choice-text">{{ card.text }}</span> + </label> + </fieldset> + + <template v-if="source === 'upload'"> + <div v-if="chosen" class="image-widget-form__chosen" data-testid="image-chosen"> + <img + v-if="previewSrc" + class="image-widget-form__thumb" + :src="previewSrc" + alt=""> + <div class="image-widget-form__chosen-text"> + <span class="image-widget-form__chosen-name">{{ chosen.name }}</span> + <span class="image-widget-form__chosen-meta">{{ chosenMeta }}</span> + </div> + <NcButton variant="tertiary" :disabled="uploading" @click="chooseAnother"> + {{ t('launchpad', 'Choose another') }} + </NcButton> + </div> + <div v-else class="image-widget-form__upload-row"> + <NcButton :disabled="uploading" @click="pickFromFiles"> + {{ t('launchpad', 'Pick from Files') }} + </NcButton> + <label class="image-widget-form__upload-label"> + <input + type="file" + accept="image/*" + class="image-widget-form__file-input" + data-testid="image-file-input" + :disabled="uploading" + @change="onFileInput"> + <span class="image-widget-form__upload-button">{{ t('launchpad', 'Upload') }}</span> + </label> + </div> + </template> + + <NcTextField + v-else + :modelValue="url" + :label="t('launchpad', 'Image URL')" + placeholder="https://" + @update:modelValue="updateField('url', $event)" /> + + <p v-if="fileError" class="image-widget-form__error" role="alert"> + {{ fileError }} + </p> + + <NcTextField + :modelValue="alt" + :label="t('launchpad', 'Text for who does not see the image')" + :required="true" + :error="altMissing" + :helperText="altMissing ? t('launchpad', 'Alternative text is required') : ''" + @update:modelValue="updateField('alt', $event)" /> + + <NcTextField + :modelValue="link" + :label="t('launchpad', 'Link (optional)')" + placeholder="https://" + @update:modelValue="updateField('link', $event)" /> + </div> +</template> + +<script> +import axios from '@nextcloud/axios' +import { FilePickerClosed, getFilePickerBuilder } from '@nextcloud/dialogs' +import { translate as t } from '@nextcloud/l10n' +import { NcButton, NcTextField } from '@nextcloud/vue' +import { NULLABLE_OBJECT_PROP, objectProp } from '../../../constants/propDefinitions.js' +import { describeImageFile, isUploadableImage, MAX_IMAGE_BYTES } from '../../../utils/imageFile.js' + +const ALLOWED_FITS = Object.freeze(['cover', 'contain', 'fill', 'none']) + +const DEFAULT_CONTENT = Object.freeze({ url: '', alt: '', link: '', fit: 'cover' }) + +/** + * A stored image is an upload when it lives on this server (a relative or + * data URL), else a web address. + * + * @param {string} url The stored URL. + * @return {string} `upload` or `url`. + */ +function sourceOf(url) { + return typeof url === 'string' && /^https?:\/\//i.test(url) ? 'url' : 'upload' +} + +/** + * ImageWidgetForm — the content part of an Image widget as board + * LpWidgetInstellen draws it (REQ-IMG-020): Upload file (from Files or the + * computer, up to 5 MB) or Web address, the chosen file with its name, size + * and dimensions, the required text for who does not see the image, and an + * optional link. Stores `{url, alt, link, fit}` as before, so the renderer is + * unchanged. A picked file is uploaded only when the modal calls `commit()`. + * + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ +export default { + name: 'ImageWidgetForm', + + components: { NcButton, NcTextField }, + + props: { + /** The placement being edited, or `null` in create mode. */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** Initial content values, used when not editing. */ + value: objectProp(DEFAULT_CONTENT), + + /** + * Upload transport `async (file) => ({ url })`, passed by the modal. + * Without one a picked file is embedded as a data URL. + */ + fileUploadFn: { + type: Function, + default: null, + }, + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + const url = typeof initial.url === 'string' ? initial.url : '' + return { + url, + alt: typeof initial.alt === 'string' ? initial.alt : '', + link: typeof initial.link === 'string' ? initial.link : '', + fit: ALLOWED_FITS.includes(initial.fit) ? initial.fit : DEFAULT_CONTENT.fit, + source: sourceOf(url), + // The chosen file: {name, size, width, height}; a stored upload + // shows its file name only. + chosen: url !== '' && sourceOf(url) === 'upload' ? { name: url.split('/').pop().split('?')[0] || url, size: null, width: null, height: null } : null, + pendingFile: null, + pendingPreviewUrl: '', + fileError: '', + uploading: false, + altTouched: false, + } + }, + + computed: { + /** + * The two choice cards. + * + * @return {Array<{value: string, title: string, text: string}>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + sourceCards() { + return [ + { + value: 'upload', + title: t('launchpad', 'Upload file'), + text: t('launchpad', 'From Files or your computer, up to 5 MB'), + }, + { + value: 'url', + title: t('launchpad', 'Web address'), + text: t('launchpad', 'An image on another site'), + }, + ] + }, + + /** + * The thumbnail: the picked file, else the stored upload. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + previewSrc() { + return this.pendingPreviewUrl || this.url + }, + + /** + * Size and dimensions of the chosen file. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + chosenMeta() { + return describeImageFile(this.chosen) + }, + + /** + * Whether the required alternative text was emptied by the editor. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + altMissing() { + return this.altTouched && this.alt.trim() === '' + }, + + /** + * The stored content. + * + * @return {{url: string, alt: string, link: string, fit: string}} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + assembledContent() { + return { url: this.url, alt: this.alt, link: this.link, fit: this.fit } + }, + }, + + beforeUnmount() { + this.revokePreview() + }, + + methods: { + t, + + /** + * Set one field and emit the content. + * + * @param {string} field url, alt or link. + * @param {string} val The value. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + updateField(field, val) { + if (field === 'alt') { + this.altTouched = true + } + this[field] = typeof val === 'string' ? val : '' + this.$emit('update:content', this.assembledContent) + }, + + /** + * Switch between upload and web address. Switching drops what the + * other source held, so a stale upload never saves under a web address. + * + * @param {string} val `upload` or `url`. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + onSourceChange(val) { + if (val === this.source) { + return + } + this.source = val === 'url' ? 'url' : 'upload' + this.chooseAnother() + this.updateField('url', '') + }, + + /** + * A file from the computer. + * + * @param {Event} event The input's change event. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + async onFileInput(event) { + const file = event?.target?.files?.[0] + if (event?.target) { + event.target.value = '' + } + if (file) { + await this.holdFile(file) + } + }, + + /** + * A file from Files: read with the editor's session, then held like a + * file from the computer, so readers never need access to it. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + async pickFromFiles() { + const picker = getFilePickerBuilder(t('launchpad', 'Pick from Files')) + .setMultiSelect(false) + .setMimeTypeFilter(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml']) + .addButton({ label: t('launchpad', 'Choose'), type: 'primary', callback: () => {} }) + .build() + let node + try { + const nodes = await picker.pickNodes() + node = Array.isArray(nodes) ? nodes[0] : nodes + } catch (e) { + if (!(e instanceof FilePickerClosed)) { + this.fileError = t('launchpad', 'The file could not be read') + } + return + } + if (!node?.source) { + return + } + try { + const response = await axios.get(node.source, { responseType: 'blob' }) + const file = new File([response.data], node.basename || 'image', { type: node.mime || response.data?.type || '' }) + await this.holdFile(file) + } catch { + this.fileError = t('launchpad', 'The file could not be read') + } + }, + + /** + * Hold a picked file for upload on save, after the type and size check. + * + * @param {File} file The file. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + async holdFile(file) { + const problem = isUploadableImage(file) + if (problem === 'type') { + this.fileError = t('launchpad', 'Choose an image file') + return + } + if (problem === 'size') { + this.fileError = t('launchpad', 'The file is larger than 5 MB') + return + } + this.fileError = '' + this.revokePreview() + this.pendingFile = file + this.pendingPreviewUrl = typeof URL.createObjectURL === 'function' ? URL.createObjectURL(file) : '' + this.chosen = { name: file.name, size: file.size, width: null, height: null } + this.measure(this.pendingPreviewUrl) + }, + + /** + * Read the dimensions of the held image. + * + * @param {string} src The object URL. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + measure(src) { + if (!src || typeof Image === 'undefined') { + return + } + const image = new Image() + image.onload = () => { + if (this.chosen && this.pendingPreviewUrl === src) { + this.chosen = { ...this.chosen, width: image.naturalWidth, height: image.naturalHeight } + } + } + image.src = src + }, + + /** + * Drop the chosen file so another can be picked. + * + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + chooseAnother() { + this.revokePreview() + this.pendingFile = null + this.chosen = null + this.fileError = '' + if (this.source === 'upload' && this.url !== '') { + this.updateField('url', '') + } + }, + + /** + * Free the object URL of the held file. + * + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + revokePreview() { + if (this.pendingPreviewUrl && typeof URL.revokeObjectURL === 'function') { + URL.revokeObjectURL(this.pendingPreviewUrl) + } + this.pendingPreviewUrl = '' + }, + + /** + * Upload the held file and store its URL; called by the modal on submit. + * + * @return {Promise<void>} + * @throws {Error} when the upload fails, so the modal keeps the dialog open. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + async commit() { + if (this.pendingFile === null) { + return + } + this.uploading = true + try { + let url + if (typeof this.fileUploadFn === 'function') { + const result = await this.fileUploadFn(this.pendingFile) + url = typeof result === 'string' ? result : result?.url + } else { + url = await readAsDataUrl(this.pendingFile) + } + if (typeof url !== 'string' || url === '') { + throw new Error(t('launchpad', 'The image could not be uploaded')) + } + this.pendingFile = null + this.updateField('url', url) + } catch (err) { + this.fileError = t('launchpad', 'The image could not be uploaded') + throw err + } finally { + this.uploading = false + } + }, + + /** + * The form's errors; the alternative text is named when missing. Pure: + * the modal calls it from a computed on every input. + * + * @return {string[]} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/image-widget/spec.md#requirement-the-image-content-form-req-img-020 + */ + validate() { + const errors = [] + if (this.url.trim() === '' && this.pendingFile === null) { + errors.push(t('launchpad', 'Choose an image or enter its web address')) + } + if (this.alt.trim() === '') { + errors.push(t('launchpad', 'Alternative text is required')) + } + return errors + }, + }, +} + +/** + * Read a file as a data URL, for hosts that pass no upload transport. + * + * @param {File} file The file. + * @return {Promise<string>} the data URL. + */ +function readAsDataUrl(file) { + if (file.size > MAX_IMAGE_BYTES) { + return Promise.reject(new Error('too large')) + } + return new Promise((resolve, reject) => { + const reader = new FileReader() + reader.onload = () => resolve(String(reader.result)) + reader.onerror = () => reject(reader.error) + reader.readAsDataURL(file) + }) +} +</script> + +<style scoped> +.image-widget-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.image-widget-form__choices { + display: flex; + flex-wrap: wrap; + gap: 8px; + border: 0; + margin: 0; + padding: 0; +} + +.image-widget-form__legend { + width: 100%; + margin-bottom: 4px; + font-weight: 600; +} + +.image-widget-form__choice { + position: relative; + display: flex; + flex: 1 1 200px; + flex-direction: column; + gap: 2px; + padding: 10px 12px 10px 36px; + border: 2px solid var(--color-border); + border-radius: var(--border-radius-large); + cursor: pointer; +} + +.image-widget-form__choice--selected { + border-color: var(--color-primary-element); + background: var(--color-primary-element-light); +} + +.image-widget-form__choice-input { + position: absolute; + top: 12px; + left: 12px; + margin: 0; +} + +.image-widget-form__choice-title { + font-weight: 600; +} + +.image-widget-form__choice-text, +.image-widget-form__chosen-meta { + font-size: 13px; + color: var(--color-text-maxcontrast); +} + +.image-widget-form__upload-row, +.image-widget-form__chosen { + display: flex; + gap: 12px; + align-items: center; +} + +.image-widget-form__chosen { + padding: 8px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); +} + +.image-widget-form__chosen-text { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; +} + +.image-widget-form__chosen-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.image-widget-form__thumb { + width: 48px; + height: 48px; + object-fit: cover; + border-radius: var(--border-radius); +} + +.image-widget-form__file-input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; +} + +.image-widget-form__upload-label { + position: relative; + cursor: pointer; +} + +.image-widget-form__upload-button { + display: inline-block; + padding: 8px 16px; + border: 1px solid var(--color-border-dark); + border-radius: var(--border-radius-element, var(--border-radius-pill)); +} + +.image-widget-form__upload-label:focus-within .image-widget-form__upload-button { + outline: 2px solid var(--color-primary-element); + outline-offset: 2px; +} + +.image-widget-form__error { + margin: 0; + color: var(--color-error-text, var(--color-error)); +} +</style> diff --git a/src/components/Widgets/Renderers/LinkButtonHost.vue b/src/components/Widgets/Renderers/LinkButtonHost.vue index 96ceed0e0..0a12899bd 100644 --- a/src/components/Widgets/Renderers/LinkButtonHost.vue +++ b/src/components/Widgets/Renderers/LinkButtonHost.vue @@ -13,6 +13,8 @@ <CnLinkButtonWidget :content="content" :placement="placement" + :isAdmin="isAdmin" + :canEdit="canEdit" @internalAction="onInternalAction" @createFile="onCreateFile" /> @@ -89,6 +91,7 @@ import { CnLinkButtonWidget } from '@conduction/nextcloud-vue' import { translate as t } from '@nextcloud/l10n' import { useInternalActions } from '../../../composables/useInternalActions.js' +import { FLAG_PROP, OBJECT_PROP } from '../../../constants/propDefinitions.js' // `@nextcloud/axios` / `@nextcloud/router` / `@nextcloud/dialogs` are loaded // lazily inside `onCreateConfirm()` so the registry import graph doesn't drag @@ -110,16 +113,16 @@ export default { props: { /** The placement content blob (`{label, url, actionType, …}`). */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** The placement (carries `id`). */ - placement: { - type: Object, - default: () => ({}), - }, + placement: OBJECT_PROP, + + /** Set with `canEdit` in edit mode, where the widget suppresses clicks. */ + isAdmin: FLAG_PROP, + + /** Set with `isAdmin` in edit mode, where the widget suppresses clicks. */ + canEdit: FLAG_PROP, }, data() { diff --git a/src/components/Widgets/Renderers/LiveTileWidget.vue b/src/components/Widgets/Renderers/LiveTileWidget.vue index 5f55fb31f..2d4c2b7d2 100644 --- a/src/components/Widgets/Renderers/LiveTileWidget.vue +++ b/src/components/Widgets/Renderers/LiveTileWidget.vue @@ -7,6 +7,7 @@ <component :is="clickThroughTag" class="live-tile-widget" + :class="styleClasses" v-bind="clickThroughAttrs" @click="onActivate"> <div v-if="loading" class="live-tile-widget__state"> @@ -22,10 +23,10 @@ </div> <div - v-else-if="errorMessage" + v-else-if="shownError" class="live-tile-widget__state live-tile-widget__state--error"> <AlertCircleOutline :size="32" /> - <span>{{ errorMessage }}</span> + <span>{{ shownError }}</span> <button type="button" class="live-tile-widget__retry" @click.stop="load"> {{ t('launchpad', 'Retry') }} </button> @@ -39,11 +40,61 @@ {{ t('launchpad', 'Showing last known value') }} </span> - <div v-if="label" class="live-tile-widget__label"> + <div v-if="label && showTitle" class="live-tile-widget__label"> {{ label }} </div> - <div class="live-tile-widget__value" :aria-label="valueAriaLabel"> + <!-- REQ-LTC-001: a list, table or key-value tile shows the mapped + rows the server sent; a link shows only when it is https + (REQ-LTC-003). --> + <ul v-if="display === 'list'" class="live-tile-widget__list"> + <li v-for="(item, index) in items" :key="index" class="live-tile-widget__list-item"> + <a + v-if="linkOf(item)" + :href="linkOf(item)" + target="_blank" + rel="noopener noreferrer" + class="live-tile-widget__list-title">{{ titleOf(item) }}</a> + <span v-else class="live-tile-widget__list-title">{{ titleOf(item) }}</span> + <span + v-for="field in detailsOf(item)" + :key="field.label" + class="live-tile-widget__list-detail">{{ field.label ? field.label + ': ' : '' }}{{ textOf(field) }}</span> + </li> + </ul> + + <table v-else-if="display === 'table'" class="live-tile-widget__table"> + <thead> + <tr> + <th v-for="column in columns" :key="column" scope="col"> + {{ column }} + </th> + </tr> + </thead> + <tbody> + <tr v-for="(item, index) in items" :key="index"> + <td v-for="field in item" :key="field.label"> + <a + v-if="field.role === 'link' && isHttps(field.value)" + :href="field.value" + target="_blank" + rel="noopener noreferrer">{{ field.value }}</a> + <template v-else> + {{ textOf(field) }} + </template> + </td> + </tr> + </tbody> + </table> + + <dl v-else-if="display === 'keyvalue'" class="live-tile-widget__pairs"> + <template v-for="pair in pairs" :key="pair.label"> + <dt>{{ pair.label }}</dt> + <dd>{{ textOf(pair) }}</dd> + </template> + </dl> + + <div v-else class="live-tile-widget__value" :aria-label="valueAriaLabel"> {{ displayValue }} </div> @@ -71,7 +122,13 @@ import AlertCircleOutline from 'vue-material-design-icons/AlertCircleOutline.vue import AlertOutline from 'vue-material-design-icons/AlertOutline.vue' import CheckCircleOutline from 'vue-material-design-icons/CheckCircleOutline.vue' import CloudOffOutline from 'vue-material-design-icons/CloudOffOutline.vue' +import { + NULLABLE_OBJECT_PROP, + OBJECT_PROP, +} from '../../../constants/propDefinitions.js' import { fetchLiveTileValue } from '../../../services/liveTileClient.js' +import { knownColour } from '../../../utils/liveTilePreview.js' +import { loadPlacementReading } from '../../../utils/placementReading.js' /** * Maps a badge `state` to an icon component. Falls back to @@ -116,10 +173,7 @@ export default { * * @type {object} */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** * The widget placement — only `placement.id` is used, to call the @@ -127,8 +181,18 @@ export default { * * @type {{id?: number|string}|null} */ - placement: { - type: Object, + placement: NULLABLE_OBJECT_PROP, + + /** + * Where the reading comes from instead of LaunchPad's per-placement + * endpoint: a function of the placement id that resolves the reading. + * A public link or kiosk screen passes its token-scoped read here + * (REQ-PSHR-011); null (the default) is the signed-in dashboard. + * + * @type {(function((number|string)): Promise<object>)|null} + */ + readingSource: { + type: Function, default: null, }, }, @@ -147,6 +211,30 @@ export default { return typeof this.content?.label === 'string' ? this.content.label : '' }, + /** + * Whether the title shows; only an explicit `false` hides it. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + showTitle() { + return this.content?.showTitle !== false + }, + + /** + * The colour and border the form chose. + * + * @return {object} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + styleClasses() { + const colour = knownColour(this.content?.colour) + return { + ['live-tile-colour--' + colour]: colour !== '', + 'live-tile-widget--bordered': this.content?.border === true, + } + }, + /** * "Data source unavailable" is distinguished from a generic error: * a `connector`-mode tile with no cached value, marked stale, is @@ -156,14 +244,84 @@ export default { * @spec openspec/specs/live-data-tile-widget/spec.md */ unavailable() { + return this.content?.sourceMode === 'connector' && this.noValue + }, + + /** + * Whether the server answered without any value: the source failed + * and there was no last-known value to serve (`value: null`, + * `stale: true`, nothing mapped). + * + * @return {boolean} + * @spec openspec/specs/live-data-tile-widget/spec.md + */ + noValue() { return ( - this.content?.sourceMode === 'connector' - && this.reading !== null + this.reading !== null && this.reading.value === null && this.reading.stale === true + && this.items.length === 0 + && this.pairs.length === 0 ) }, + /** + * The error the tile shows: a failed request, or a reading without + * any value, which is an error rather than a "last known value". + * + * @return {string} The message, or '' when there is no error. + * @spec openspec/specs/live-data-tile-widget/spec.md + */ + shownError() { + if (this.errorMessage) { + return this.errorMessage + } + return this.noValue + ? t('launchpad', 'The value is currently unavailable.') + : '' + }, + + /** + * How the tile shows its data: `value` (a single value), `list`, `table` or `keyvalue`. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + display() { + const display = this.reading?.display + return ['list', 'table', 'keyvalue'].includes(display) ? display : 'value' + }, + + /** + * The mapped rows of a list or table: each an array of `{label, role, value}`. + * + * @return {Array<Array<object>>} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + items() { + return Array.isArray(this.reading?.items) ? this.reading.items.filter(Array.isArray) : [] + }, + + /** + * The mapped pairs of a key-value tile. + * + * @return {Array<object>} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + pairs() { + return Array.isArray(this.reading?.pairs) ? this.reading.pairs : [] + }, + + /** + * The table's column headers, from the mapping labels of the first row. + * + * @return {string[]} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + columns() { + return (this.items[0] || []).map((field) => field.label) + }, + /** @spec openspec/specs/live-data-tile-widget/spec.md */ displayValue() { if (!this.reading) { @@ -218,12 +376,13 @@ export default { /** @spec openspec/specs/live-data-tile-widget/spec.md */ clickThroughTag() { - return this.hasLink ? 'a' : 'div' + // A list or table holds links of its own, and a link may not hold a link. + return this.hasLink && this.display === 'value' ? 'a' : 'div' }, /** @spec openspec/specs/live-data-tile-widget/spec.md */ clickThroughAttrs() { - if (!this.hasLink) { + if (this.clickThroughTag !== 'a') { return {} } const newTab = this.content?.linkTarget === 'new-tab' @@ -242,6 +401,80 @@ export default { methods: { t, + /** + * Whether a value is an https address, the only kind shown as a link. + * + * @param {string|number|boolean|null} value - a mapped value. + * @return {boolean} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-only-safe-links-are-clickable-req-ltc-003 + */ + isHttps(value) { + if (typeof value !== 'string') { + return false + } + try { + return new URL(value).protocol === 'https:' + } catch { + return false + } + }, + + /** + * The link of a list row, or '' when it has no https link. + * + * @param {Array<object>} item - the row's mapped fields. + * @return {string} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-only-safe-links-are-clickable-req-ltc-003 + */ + linkOf(item) { + const link = item.find((field) => field.role === 'link') + return link && this.isHttps(link.value) ? link.value : '' + }, + + /** + * The title of a list row: its title field, else its first value. + * + * @param {Array<object>} item - the row's mapped fields. + * @return {string} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + titleOf(item) { + const title = item.find((field) => field.role === 'title') || item.find((field) => field.role !== 'link') + return title ? this.textOf(title) : '' + }, + + /** + * The fields of a list row shown under its title: dates and other fields with a value. + * + * @param {Array<object>} item - the row's mapped fields. + * @return {Array<object>} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + detailsOf(item) { + const title = item.find((field) => field.role === 'title') || item.find((field) => field.role !== 'link') + return item.filter((field) => field !== title && field.role !== 'link' && this.textOf(field) !== '') + }, + + /** + * A mapped value as text; a date shown in the reader's locale. + * + * @param {{role: string, value: (string|number|boolean|null)}} field - a mapped field. + * @return {string} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + textOf(field) { + if (field.value === null || field.value === undefined) { + return '' + } + if (field.role === 'date' && typeof field.value === 'string') { + const date = new Date(field.value) + if (!Number.isNaN(date.getTime())) { + return date.toLocaleDateString() + } + } + return String(field.value) + }, + /** * No-op click handler placeholder — click-through is handled by the * native anchor (`clickThroughTag`/`clickThroughAttrs`) when a link @@ -262,100 +495,64 @@ export default { * * @return {Promise<void>} * @spec openspec/specs/live-data-tile-widget/spec.md + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 */ async load() { - const placementId = this.placement?.id - if (placementId === undefined || placementId === null) { - this.loading = false - this.errorMessage = t( + await loadPlacementReading(this, { + placementId: this.placement?.id, + fetch: this.readingSource ?? fetchLiveTileValue, + unsaved: t( 'launchpad', 'This tile is not available until it is saved.', - ) - return - } - - this.loading = true - this.errorMessage = '' - try { - const data = await fetchLiveTileValue(placementId) - if (data && data.error) { - this.reading = null - this.errorMessage = t( - 'launchpad', - 'The value is currently unavailable.', - ) - return - } - this.reading = data - } catch { - this.reading = null - this.errorMessage = t('launchpad', 'Failed to load the value.') - } finally { - this.loading = false - } + ), + unavailable: t('launchpad', 'The value is currently unavailable.'), + failed: t('launchpad', 'Failed to load the value.'), + }) }, }, } </script> +<style scoped src="./readingTile.css"></style> + <style scoped> .live-tile-widget { - width: 100%; - height: 100%; - display: flex; - align-items: center; - justify-content: center; text-decoration: none; color: inherit; } -.live-tile-widget__state { - display: flex; - flex-direction: column; - align-items: center; - gap: 8px; +.live-tile-widget__label { + font-weight: 600; color: var(--color-text-maxcontrast, var(--color-main-text)); - text-align: center; } -.live-tile-widget__retry { - border: 1px solid var(--color-border); - border-radius: var(--border-radius); - background: transparent; - padding: 4px 12px; - cursor: pointer; - color: var(--color-main-text); +.live-tile-widget__value { + font-size: 1.8rem; + font-weight: 600; + color: var(--live-tile-accent, var(--color-main-text)); } -.live-tile-widget__reading { - position: relative; - width: 100%; - display: flex; - flex-direction: column; - align-items: center; - gap: 4px; +.live-tile-widget--bordered { + display: block; + padding: 8px; + border: 1px solid var(--color-border-dark); + border-radius: var(--border-radius-large); } -.live-tile-widget__stale-badge { - position: absolute; - top: -8px; - right: -8px; - font-size: 0.7rem; - padding: 2px 6px; - border-radius: var(--border-radius-pill, 8px); - background: var(--color-warning, #ffcc00); - color: var(--color-main-text); +.live-tile-colour--primary { + --live-tile-accent: var(--color-primary-element); } -.live-tile-widget__label { - font-weight: 600; - color: var(--color-text-maxcontrast, var(--color-main-text)); +.live-tile-colour--success { + --live-tile-accent: var(--color-success-text, var(--color-success)); } -.live-tile-widget__value { - font-size: 1.8rem; - font-weight: 600; - color: var(--color-main-text); +.live-tile-colour--warning { + --live-tile-accent: var(--color-warning-text, var(--color-warning)); +} + +.live-tile-colour--error { + --live-tile-accent: var(--color-error-text, var(--color-error)); } .live-tile-widget__badge { @@ -368,6 +565,65 @@ export default { border: 1px solid var(--color-border); } +.live-tile-widget__list { + margin: 0; + padding: 0; + list-style: none; + display: flex; + flex-direction: column; + gap: 6px; + text-align: start; +} + +.live-tile-widget__list-item { + display: flex; + flex-direction: column; +} + +.live-tile-widget__list-title { + font-weight: 600; + color: var(--color-main-text); +} + +a.live-tile-widget__list-title { + text-decoration: underline; +} + +.live-tile-widget__list-detail { + font-size: 0.85rem; + color: var(--color-text-maxcontrast); +} + +.live-tile-widget__table { + width: 100%; + border-collapse: collapse; + font-size: 0.9rem; + text-align: start; +} + +.live-tile-widget__table th, +.live-tile-widget__table td { + padding: 4px 6px; + border-bottom: 1px solid var(--color-border); + text-align: start; +} + +.live-tile-widget__pairs { + display: grid; + grid-template-columns: auto 1fr; + gap: 4px 12px; + margin: 0; + text-align: start; +} + +.live-tile-widget__pairs dt { + font-weight: 600; +} + +.live-tile-widget__pairs dd { + margin: 0; +} + .live-tile-widget__badge--ok { border-color: var(--color-success, #46ba61); } diff --git a/src/components/Widgets/Renderers/LiveTileWidgetForm.vue b/src/components/Widgets/Renderers/LiveTileWidgetForm.vue index ac4ef917c..36e6a0a9e 100644 --- a/src/components/Widgets/Renderers/LiveTileWidgetForm.vue +++ b/src/components/Widgets/Renderers/LiveTileWidgetForm.vue @@ -5,55 +5,72 @@ <template> <div class="live-tile-widget-form"> - <p class="live-tile-widget-form__hint"> - {{ - t( - 'launchpad', - 'Bind this tile to a live value from a data source: a count, a status, a KPI number.', - ) - }} - </p> + <!-- REQ-LIVETILE-020 (board LpWidgetInstellen): where the value comes + from as two choice cards. --> + <fieldset class="live-tile-widget-form__choices"> + <legend class="live-tile-widget-form__legend"> + {{ t('launchpad', 'Where does the value come from?') }} + </legend> + <label + v-for="card in sourceCards" + :key="card.value" + class="live-tile-widget-form__choice" + :class="{ + 'live-tile-widget-form__choice--selected': sourceMode === card.value, + 'live-tile-widget-form__choice--disabled': card.disabled, + }"> + <input + type="radio" + name="live-tile-source" + class="live-tile-widget-form__choice-input" + :value="card.value" + :checked="sourceMode === card.value" + :disabled="card.disabled" + :data-testid="'live-tile-source-' + card.value" + @change="onSourceModeChange(card.value)"> + <span class="live-tile-widget-form__choice-title">{{ card.title }}</span> + <span class="live-tile-widget-form__choice-text">{{ card.text }}</span> + </label> + </fieldset> <!-- @nextcloud/vue@9 renamed the two-way prop of every form control from `value`/`checked` to `modelValue`, and the paired event from `update:value`/`update:checked` to `update:modelValue`. The old - names fail silently — `:value` falls through as a plain attribute - and the old event is simply never emitted, so the field renders - but never writes back. The listener must stay camelCase: + names fail silently. The listener must stay camelCase: `useModel()` decides controlled-vs-local by looking for a literal - `onUpdate:modelValue` in the vnode props, and a kebab-case - `@update:model-value` does not match. --> - <NcTextField - :modelValue="label" - :label="t('launchpad', 'Label')" - :placeholder="t('launchpad', 'e.g. Open tickets')" - @update:modelValue="updateField('label', $event)" /> - - <NcSelect - :modelValue="sourceMode" - :options="sourceModeOptions" - :inputLabel="t('launchpad', 'Source')" - :reduce="(option) => option.value" - label="label" - @update:modelValue="onSourceModeChange" /> - + `onUpdate:modelValue` in the vnode props. --> <template v-if="sourceMode === 'connector'"> - <p v-if="!connectorAvailable" class="live-tile-widget-form__warning"> - {{ - t( - 'launchpad', - 'OpenConnector is not installed — direct-URL mode only.', - ) - }} - </p> + <NcSelect + v-if="connections.length > 0" + :modelValue="sourceId" + :options="connections" + :inputLabel="t('launchpad', 'Connection')" + :reduce="(option) => option.value" + label="label" + @update:modelValue="updateField('sourceId', $event || '')" /> <NcTextField + v-else :modelValue="sourceId" - :label="t('launchpad', 'OpenConnector source id')" + :label="t('launchpad', 'Integriq source id')" :disabled="!connectorAvailable" @update:modelValue="updateField('sourceId', $event)" /> + <p + v-if="selectedConnection" + class="live-tile-widget-form__hint-small" + data-testid="live-tile-last-success"> + {{ t('launchpad', 'Last success: {time}', { time: lastSuccessText }) }} + </p> </template> <template v-else> + <p v-if="!connectorAvailable" class="live-tile-widget-form__warning"> + {{ + t( + 'launchpad', + 'Integriq is not installed — direct-URL mode only.', + ) + }} + </p> <NcTextField :modelValue="url" :label="t('launchpad', 'URL')" @@ -67,63 +84,201 @@ <NcTextField :modelValue="valueExpr" - :label="t('launchpad', 'Value expression')" + :label="t('launchpad', 'Path in the response')" placeholder="$.data.count" @update:modelValue="updateField('valueExpr', $event)" /> - <NcTextField - :modelValue="String(refresh)" - type="number" - :label="t('launchpad', 'Refresh interval (seconds)')" - @update:modelValue="onRefreshChange" /> - <p class="live-tile-widget-form__hint-small"> - {{ - t('launchpad', 'Minimum {min} seconds.', { - min: MIN_REFRESH_SECONDS, - }) - }} - </p> + <!-- REQ-LTC-001: a single value, or several mapped fields as a list, + a table or key-value pairs. --> + <fieldset class="live-tile-widget-form__views"> + <legend class="live-tile-widget-form__legend"> + {{ t('launchpad', 'View') }} + </legend> + <label + v-for="option in displayOptions" + :key="option.value" + class="live-tile-widget-form__view" + :class="{ 'live-tile-widget-form__view--selected': display === option.value }"> + <input + type="radio" + name="live-tile-view" + :value="option.value" + :checked="display === option.value" + :data-testid="'live-tile-view-' + option.value" + @change="onDisplayChange(option.value)"> + {{ option.label }} + </label> + </fieldset> + + <template v-if="display !== 'value'"> + <NcSelect + :modelValue="null" + :options="presetOptions" + :inputLabel="t('launchpad', 'Preset')" + :placeholder="t('launchpad', 'Fill the mapping from a preset')" + label="label" + @update:modelValue="applyPreset" /> - <div class="live-tile-widget-form__row"> <NcTextField - :modelValue="formatPrefix" - :label="t('launchpad', 'Prefix')" - @update:modelValue="updateFormat('prefix', $event)" /> + v-if="display !== 'keyvalue'" + :modelValue="String(limit)" + type="number" + :label="t('launchpad', 'Number of rows (1 to 50)')" + @update:modelValue="onLimitChange" /> + + <fieldset class="live-tile-widget-form__mapping"> + <legend>{{ t('launchpad', 'Fields') }}</legend> + <div + v-for="(field, index) in mapping" + :key="index" + class="live-tile-widget-form__mapping-row"> + <NcTextField + :modelValue="field.label" + :label="t('launchpad', 'Field label')" + @update:modelValue="updateMapping(index, 'label', $event)" /> + <NcTextField + :modelValue="field.path" + :label="t('launchpad', 'Field path')" + placeholder="name" + @update:modelValue="updateMapping(index, 'path', $event)" /> + <NcSelect + :modelValue="field.role" + :options="roleOptions" + :inputLabel="t('launchpad', 'Field role')" + :reduce="(option) => option.value" + label="label" + @update:modelValue="updateMapping(index, 'role', $event || 'field')" /> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove field')" + @click="removeMapping(index)"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </div> + <NcButton + :disabled="mapping.length >= MAX_FIELDS" + @click="addMapping"> + {{ t('launchpad', 'Add field') }} + </NcButton> + </fieldset> + </template> + + <div class="live-tile-widget-form__row"> <NcTextField - :modelValue="formatSuffix" - :label="t('launchpad', 'Suffix')" - @update:modelValue="updateFormat('suffix', $event)" /> + :modelValue="unit" + :label="t('launchpad', 'Unit (optional)')" + @update:modelValue="onUnitChange" /> + <NcSelect + :modelValue="Number(refresh)" + :options="refreshOptions" + :inputLabel="t('launchpad', 'Refresh')" + :reduce="(option) => option.value" + :clearable="false" + label="label" + @update:modelValue="onRefreshChange" /> </div> - <NcCheckboxRadioSwitch - :modelValue="formatThousands" - type="switch" - @update:modelValue="updateFormat('thousands', $event)"> - {{ t('launchpad', 'Thousands separator') }} - </NcCheckboxRadioSwitch> - <NcTextField - :modelValue="linkUrl" - :label="t('launchpad', 'Click-through link (optional)')" - @update:modelValue="updateField('linkUrl', $event)" /> - <NcSelect - :modelValue="linkTarget" - :options="linkTargetOptions" - :inputLabel="t('launchpad', 'Link target')" - :reduce="(option) => option.value" - label="label" - @update:modelValue=" - (val) => updateField('linkTarget', val || 'same-tab') - " /> + <fieldset class="live-tile-widget-form__formatting"> + <legend class="live-tile-widget-form__legend"> + {{ t('launchpad', 'Formatting') }} + </legend> + <NcTextField + :modelValue="label" + :label="t('launchpad', 'Title')" + :placeholder="t('launchpad', 'e.g. Open tickets')" + @update:modelValue="updateField('label', $event)" /> + <NcCheckboxRadioSwitch + :modelValue="showTitle" + type="switch" + data-testid="live-tile-show-title" + @update:modelValue="updateField('showTitle', $event)"> + {{ t('launchpad', 'Show title') }} + </NcCheckboxRadioSwitch> + <NcSelect + :modelValue="colour" + :options="colourOptions" + :inputLabel="t('launchpad', 'Color')" + :reduce="(option) => option.value" + :clearable="false" + label="label" + @update:modelValue="updateField('colour', $event || '')" /> + <NcCheckboxRadioSwitch + :modelValue="border" + type="switch" + data-testid="live-tile-border" + @update:modelValue="updateField('border', $event)"> + {{ t('launchpad', 'Border') }} + </NcCheckboxRadioSwitch> + <div class="live-tile-widget-form__row"> + <NcTextField + :modelValue="formatPrefix" + :label="t('launchpad', 'Prefix')" + @update:modelValue="updateFormat('prefix', $event)" /> + </div> + <NcCheckboxRadioSwitch + :modelValue="formatThousands" + type="switch" + data-testid="live-tile-thousands" + @update:modelValue="updateFormat('thousands', $event)"> + {{ t('launchpad', 'Thousands separator') }} + </NcCheckboxRadioSwitch> + + <NcTextField + :modelValue="linkUrl" + :label="t('launchpad', 'Click-through link (optional)')" + @update:modelValue="updateField('linkUrl', $event)" /> + <NcSelect + :modelValue="linkTarget" + :options="linkTargetOptions" + :inputLabel="t('launchpad', 'Link target')" + :reduce="(option) => option.value" + label="label" + @update:modelValue=" + (val) => updateField('linkTarget', val || 'same-tab') + " /> + </fieldset> + + <!-- The preview follows the fields (REQ-LIVETILE-020). --> + <section + class="live-tile-widget-form__preview" + :class="previewClasses" + :aria-label="t('launchpad', 'Preview')" + data-testid="live-tile-preview"> + <div v-if="showTitle && label" class="live-tile-widget-form__preview-title"> + {{ label }} + </div> + <div class="live-tile-widget-form__preview-value"> + {{ previewValue }} + </div> + <div class="live-tile-widget-form__hint-small"> + {{ refreshText }} + </div> + </section> </div> </template> <script> import { translate as t } from '@nextcloud/l10n' -import { NcCheckboxRadioSwitch, NcSelect, NcTextField } from '@nextcloud/vue' +import { NcButton, NcCheckboxRadioSwitch, NcSelect, NcTextField } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' import { fetchConnectorAvailability, + fetchLiveTileValue, validateLiveTileSource, } from '../../../services/liveTileClient.js' +import { fetchLiveTileConnections } from '../../../services/liveTileConnections.js' +import { + knownColour, + previewValue, + refreshLabel, + refreshOptions, + suffixToUnit, + unitToSuffix, +} from '../../../utils/liveTilePreview.js' +import { allowListMessage, urlFieldErrors } from '../../../utils/urlAllowList.js' const MIN_REFRESH_SECONDS = 30 const DEFAULT_REFRESH_SECONDS = 300 @@ -141,6 +296,68 @@ const DEFAULT_CONTENT = Object.freeze({ linkTarget: 'same-tab', }) +const MAX_FIELDS = 6 +const DEFAULT_LIMIT = 10 + +/** + * The "Latest documents" presets (REQ-LTC-004): where each system keeps its + * documents and which fields give the title, link, last modified and editor. + * + * @type {Record<string, {valueExpr: string, paths: string[]}>} + */ +const DOCUMENT_PRESETS = Object.freeze({ + sharepoint: { valueExpr: '$.value', paths: ['name', 'webUrl', 'lastModifiedDateTime', 'lastModifiedBy.user.displayName'] }, + confluence: { valueExpr: '$.results', paths: ['title', '_links.webui', 'version.when', 'version.by.displayName'] }, +}) + +/** + * The stored mapping as editable rows. + * + * @param {Array<object>|undefined} stored The stored mapping. + * @return {Array<{label: string, path: string, role: string}>} the rows. + */ +function mappingRows(stored) { + if (!Array.isArray(stored)) { + return [] + } + return stored.slice(0, MAX_FIELDS).map((field) => ({ + label: typeof field?.label === 'string' ? field.label : '', + path: typeof field?.path === 'string' ? field.path : '', + role: ['title', 'link', 'date', 'field'].includes(field?.role) ? field.role : 'field', + })) +} + +const SOURCE_FIELDS = Object.freeze(['label', 'sourceMode', 'url', 'sourceId', 'valueExpr', 'refresh']) +const LINK_FIELDS = Object.freeze(['linkUrl', 'linkTarget']) + +/** + * The stored value of each named field, or its default when unset or null. + * + * @param {object} initial The stored content. + * @param {Array<string>} fields The field names. + * @return {object} the fields to edit. + */ +function storedOrDefault(initial, fields) { + return Object.fromEntries( + fields.map((field) => [field, initial[field] ?? DEFAULT_CONTENT[field]]), + ) +} + +/** + * The number-format fields of the form, read over the default format. + * + * @param {object|null|undefined} stored The stored format. + * @return {object} formatPrefix, formatSuffix and formatThousands. + */ +function formatFields(stored) { + const format = { ...DEFAULT_CONTENT.format, ...(stored || {}) } + return { + formatPrefix: format.prefix, + formatSuffix: format.suffix, + formatThousands: !!format.thousands, + } +} + /** * LiveTileWidgetForm — `CnAddWidgetModal` sub-form for creating or editing a * `livetile` placement (REQ-LIVETILE-002/004/005). @@ -157,6 +374,7 @@ export default { name: 'LiveTileWidgetForm', components: { + NcButton, NcTextField, NcSelect, NcCheckboxRadioSwitch, @@ -168,41 +386,34 @@ export default { * * @type {{content: object}|null} */ - editingWidget: { - type: Object, - default: null, - }, + editingWidget: NULLABLE_OBJECT_PROP, /** * Initial content values — used when not editing. * * @type {object} */ - value: { - type: Object, - default: () => ({ ...DEFAULT_CONTENT }), - }, + value: objectProp(DEFAULT_CONTENT), }, emits: ['update:content'], data() { const initial = this.editingWidget?.content || this.value || {} - const format = { ...DEFAULT_CONTENT.format, ...(initial.format || {}) } - const badge = { ...DEFAULT_CONTENT.badge, ...(initial.badge || {}) } return { - label: initial.label ?? DEFAULT_CONTENT.label, - sourceMode: initial.sourceMode ?? DEFAULT_CONTENT.sourceMode, - url: initial.url ?? DEFAULT_CONTENT.url, - sourceId: initial.sourceId ?? DEFAULT_CONTENT.sourceId, - valueExpr: initial.valueExpr ?? DEFAULT_CONTENT.valueExpr, - refresh: initial.refresh ?? DEFAULT_CONTENT.refresh, - formatPrefix: format.prefix, - formatSuffix: format.suffix, - formatThousands: !!format.thousands, - badge, - linkUrl: initial.linkUrl ?? DEFAULT_CONTENT.linkUrl, - linkTarget: initial.linkTarget ?? DEFAULT_CONTENT.linkTarget, + ...storedOrDefault(initial, SOURCE_FIELDS), + ...formatFields(initial.format), + badge: { ...DEFAULT_CONTENT.badge, ...(initial.badge || {}) }, + ...storedOrDefault(initial, LINK_FIELDS), + showTitle: initial.showTitle !== false, + colour: knownColour(initial.colour), + border: initial.border === true, + connections: [], + reading: null, + display: ['list', 'table', 'keyvalue'].includes(initial.display) ? initial.display : 'value', + limit: Number.isInteger(Number(initial.limit)) && Number(initial.limit) > 0 ? Number(initial.limit) : DEFAULT_LIMIT, + mapping: mappingRows(initial.mapping), + MAX_FIELDS, connectorAvailable: false, urlAllowListError: '', MIN_REFRESH_SECONDS, @@ -210,6 +421,128 @@ export default { }, computed: { + /** + * The two choice cards for where the value comes from. Connection is + * disabled without integriq. + * + * @return {Array<{value: string, title: string, text: string, disabled: boolean}>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + sourceCards() { + return [ + { + value: 'connector', + title: t('launchpad', 'Connection'), + text: t('launchpad', 'A system the administrator has connected'), + disabled: !this.connectorAvailable, + }, + { + value: 'url', + title: t('launchpad', 'Web address'), + text: t('launchpad', 'An address that returns JSON'), + disabled: false, + }, + ] + }, + + /** + * The chosen connection, when it is one of the listed ones. + * + * @return {{value: string, label: string, lastSuccessAt: (string|null)}|null} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + selectedConnection() { + return this.connections.find((option) => option.value === this.sourceId) || null + }, + + /** + * When the chosen connection last succeeded, in the reader's locale. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + lastSuccessText() { + const at = this.selectedConnection?.lastSuccessAt + const date = at ? new Date(at) : null + if (!date || Number.isNaN(date.getTime())) { + return t('launchpad', 'Not yet') + } + return date.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + }, + + /** + * The unit field: the stored suffix without its leading space. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + unit() { + return suffixToUnit(this.formatSuffix) + }, + + /** + * The refresh choices, keeping a stored interval that is not one of them. + * + * @return {Array<{value: number, label: string}>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + refreshOptions() { + return refreshOptions(this.clampRefresh(this.refresh)) + }, + + /** + * The theme colours a tile can take. + * + * @return {Array<{value: string, label: string}>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + colourOptions() { + return [ + { value: '', label: t('launchpad', 'Default') }, + { value: 'primary', label: t('launchpad', 'Primary') }, + { value: 'success', label: t('launchpad', 'Success') }, + { value: 'warning', label: t('launchpad', 'Warning') }, + { value: 'error', label: t('launchpad', 'Error') }, + ] + }, + + /** + * The preview's colour and border classes, as the tile renders them. + * + * @return {object} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + previewClasses() { + return { + ['live-tile-colour--' + this.colour]: this.colour !== '', + 'live-tile-widget-form__preview--bordered': this.border, + } + }, + + /** + * The value in the preview: the tile's last reading when it has one. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + previewValue() { + return previewValue(this.reading, { + prefix: this.formatPrefix, + suffix: this.formatSuffix, + thousands: this.formatThousands, + }) + }, + + /** + * "Refreshes every 5 minutes" under the preview. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + refreshText() { + return refreshLabel(this.clampRefresh(this.refresh), true) + }, + /** @spec openspec/specs/live-data-tile-widget/spec.md */ sourceModeOptions() { const options = [{ value: 'url', label: t('launchpad', 'Direct URL') }] @@ -218,12 +551,55 @@ export default { if (this.connectorAvailable) { options.push({ value: 'connector', - label: t('launchpad', 'OpenConnector source'), + label: t('launchpad', 'Integriq source'), }) } return options }, + /** + * The displays a tile can have. + * + * @return {Array<{value: string, label: string}>} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + displayOptions() { + return [ + { value: 'value', label: t('launchpad', 'Single value') }, + { value: 'list', label: t('launchpad', 'List') }, + { value: 'table', label: t('launchpad', 'Table') }, + { value: 'keyvalue', label: t('launchpad', 'Key-value pairs') }, + ] + }, + + /** + * What a mapped field is for. + * + * @return {Array<{value: string, label: string}>} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + roleOptions() { + return [ + { value: 'title', label: t('launchpad', 'Title') }, + { value: 'link', label: t('launchpad', 'Link') }, + { value: 'date', label: t('launchpad', 'Date') }, + { value: 'field', label: t('launchpad', 'Other field') }, + ] + }, + + /** + * The mapping presets. + * + * @return {Array<{value: string, label: string}>} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-preset-shows-another-intranets-latest-documents-req-ltc-004 + */ + presetOptions() { + return [ + { value: 'sharepoint', label: t('launchpad', 'Latest documents (SharePoint)') }, + { value: 'confluence', label: t('launchpad', 'Latest documents (Confluence)') }, + ] + }, + /** @spec openspec/specs/live-data-tile-widget/spec.md */ linkTargetOptions() { return [ @@ -250,12 +626,63 @@ export default { badge: this.badge, linkUrl: this.linkUrl, linkTarget: this.linkTarget, + ...this.styleContent, + ...this.displayContent, } }, + + /** + * Title visibility, colour and border; only what differs from the + * default, so a tile saved before these existed is stored as it was. + * + * @return {object} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + styleContent() { + const content = {} + if (this.showTitle === false) { + content.showTitle = false + } + if (this.colour !== '') { + content.colour = this.colour + } + if (this.border === true) { + content.border = true + } + return content + }, + + /** + * The display, limit and mapping of the content; nothing for a single-value tile, + * so a tile saved before lists existed is stored as it was. + * + * @return {object} + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + displayContent() { + if (this.display === 'value') { + return {} + } + const content = { + display: this.display, + mapping: this.mapping.map((field) => ({ ...field })), + } + if (this.display !== 'keyvalue') { + content.limit = Number(this.limit) + } + return content + }, }, + /** + * Probe integriq, list the connections and load the preview's value. + * + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ created() { this.refreshConnectorAvailability() + this.loadConnections() + this.loadReading() }, methods: { @@ -299,6 +726,51 @@ export default { } }, + /** + * Load the connections the editor can choose from. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + async loadConnections() { + try { + const list = await fetchLiveTileConnections() + this.connections = Array.isArray(list) ? list : [] + } catch { + this.connections = [] + } + }, + + /** + * Load the tile's current value for the preview when an existing tile + * is edited; a new tile previews a dash. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + async loadReading() { + const id = this.editingWidget?.id + if (id === undefined || id === null || id === '') { + return + } + try { + this.reading = await fetchLiveTileValue(id) + } catch { + this.reading = null + } + }, + + /** + * Set the unit; stored as the number format's suffix. + * + * @param {string} val The unit as typed. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ + onUnitChange(val) { + this.formatSuffix = unitToSuffix(val) + this.emitUpdate() + }, + /** * Switch where the tile reads its value from. * @@ -364,6 +836,94 @@ export default { this.emitUpdate() }, + /** + * Choose how the tile shows its data. A list, table or key-value tile + * starts with one title field. + * + * @param {string} val The display; falsy is a single value. + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + onDisplayChange(val) { + this.display = val || 'value' + if (this.display !== 'value' && this.mapping.length === 0) { + this.mapping = [{ label: '', path: '', role: 'title' }] + } + this.emitUpdate() + }, + + /** + * Set how many rows a list or table shows. + * + * @param {string|number} val The limit. + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + onLimitChange(val) { + this.limit = val + this.emitUpdate() + }, + + /** + * Change one key of one mapped field. + * + * @param {number} index The row. + * @param {string} key label, path or role. + * @param {string} val The new value. + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + updateMapping(index, key, val) { + this.mapping = this.mapping.map((field, at) => (at === index ? { ...field, [key]: val } : field)) + this.emitUpdate() + }, + + /** + * Add a mapped field, up to six. + * + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + addMapping() { + if (this.mapping.length >= MAX_FIELDS) { + return + } + this.mapping = [...this.mapping, { label: '', path: '', role: 'field' }] + this.emitUpdate() + }, + + /** + * Remove a mapped field. + * + * @param {number} index The row. + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + removeMapping(index) { + this.mapping = this.mapping.filter((_, at) => at !== index) + this.emitUpdate() + }, + + /** + * Fill a list of the latest documents from a preset, for the author to confirm. + * The source stays the author's choice. + * + * @param {{value: string}|string|null} option The chosen preset. + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-preset-shows-another-intranets-latest-documents-req-ltc-004 + */ + applyPreset(option) { + const preset = DOCUMENT_PRESETS[option?.value ?? option] + if (!preset) { + return + } + const [title, link, modified, editor] = preset.paths + this.display = 'list' + this.limit = DEFAULT_LIMIT + this.valueExpr = preset.valueExpr + this.mapping = [ + { label: t('launchpad', 'Document'), path: title, role: 'title' }, + { label: t('launchpad', 'Open'), path: link, role: 'link' }, + { label: t('launchpad', 'Last modified'), path: modified, role: 'date' }, + { label: t('launchpad', 'Modified by'), path: editor, role: 'field' }, + ] + this.emitUpdate() + }, + /** @spec openspec/specs/live-data-tile-widget/spec.md */ emitUpdate() { this.$emit('update:content', this.assembledContent) @@ -385,22 +945,7 @@ export default { return } const result = await validateLiveTileSource(this.assembledContent) - if ( - result.valid === false - && result.errors.includes('host_not_allowed') - ) { - this.urlAllowListError = t( - 'launchpad', - 'This host is not on the allow-list.', - ) - } else if ( - result.valid === false - && result.errors.includes('invalid_url') - ) { - this.urlAllowListError = t('launchpad', 'Enter a valid http(s) URL.') - } else { - this.urlAllowListError = '' - } + this.urlAllowListError = allowListMessage(result) }, /** @@ -413,33 +958,73 @@ export default { * @spec openspec/specs/live-data-tile-widget/spec.md */ validate() { + const errors = this.sourceErrors() + + if (typeof this.valueExpr !== 'string' || this.valueExpr.trim() === '') { + errors.push(t('launchpad', 'Value expression is required')) + } + + return errors.concat(this.displayErrors()) + }, + + /** + * The errors of a list, table or key-value display: at least one field, + * every field with a path, and a limit from 1 to 50. + * + * @return {string[]} the display errors. + * @spec openspec/changes/archive/2026-11-19-integrations-live-tile-lists/specs/live-data-tile-widget/spec.md#requirement-a-live-tile-can-show-a-list-a-table-or-key-value-pairs-req-ltc-001 + */ + displayErrors() { + if (!['list', 'table', 'keyvalue'].includes(this.display)) { + return [] + } const errors = [] + const mapping = Array.isArray(this.mapping) ? this.mapping : [] + if (mapping.length === 0) { + errors.push(t('launchpad', 'Add at least one field')) + } else if (mapping.some((field) => typeof field.path !== 'string' || field.path.trim() === '')) { + errors.push(t('launchpad', 'Every field needs a path')) + } + const limit = Number(this.limit) + if (this.display !== 'keyvalue' && (!Number.isInteger(limit) || limit < 1 || limit > 50)) { + errors.push(t('launchpad', 'The number of rows is from 1 to 50')) + } + return errors + }, + /** + * The errors of the chosen source: the URL checks in `url` mode, the + * connector checks in `connector` mode. + * + * @return {string[]} the source errors. + */ + sourceErrors() { if (this.sourceMode === 'url') { - if (typeof this.url !== 'string' || this.url.trim() === '') { - errors.push(t('launchpad', 'URL is required')) - } else if (!/^https?:\/\/.+/i.test(this.url.trim())) { - errors.push(t('launchpad', 'Enter a valid http(s) URL.')) - } - if (this.urlAllowListError) { - errors.push(this.urlAllowListError) - } - } else if (this.sourceMode === 'connector') { - if (!this.connectorAvailable) { - errors.push(t('launchpad', 'OpenConnector is not available.')) - } - if ( - typeof this.sourceId !== 'string' - || this.sourceId.trim() === '' - ) { - errors.push(t('launchpad', 'Source id is required')) - } + return [...urlFieldErrors(this.url, this.urlAllowListError)] } - - if (typeof this.valueExpr !== 'string' || this.valueExpr.trim() === '') { - errors.push(t('launchpad', 'Value expression is required')) + if (this.sourceMode === 'connector') { + return this.connectorErrors() } + return [] + }, + /** + * The errors of `connector` mode: OpenConnector must be available and + * a source id chosen. + * + * @return {string[]} the connector errors. + */ + connectorErrors() { + const errors = [] + if (!this.connectorAvailable) { + errors.push(t('launchpad', 'Integriq is not available.')) + } + if ( + typeof this.sourceId !== 'string' + || this.sourceId.trim() === '' + ) { + errors.push(t('launchpad', 'Source id is required')) + } return errors }, }, @@ -471,6 +1056,22 @@ export default { color: var(--color-warning-text, var(--color-text-maxcontrast)); } +.live-tile-widget-form__mapping { + display: flex; + flex-direction: column; + gap: 8px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius); + padding: 8px; +} + +.live-tile-widget-form__mapping-row { + display: grid; + grid-template-columns: 1fr 1fr 1fr auto; + gap: 8px; + align-items: end; +} + .live-tile-widget-form__row { display: flex; gap: 12px; @@ -479,4 +1080,121 @@ export default { .live-tile-widget-form__row > * { flex: 1; } + +.live-tile-widget-form__choices, +.live-tile-widget-form__views, +.live-tile-widget-form__formatting { + display: flex; + flex-wrap: wrap; + gap: 8px; + border: 0; + margin: 0; + padding: 0; +} + +.live-tile-widget-form__formatting { + flex-direction: column; + flex-wrap: nowrap; + gap: 12px; + border-top: 1px solid var(--color-border); + padding-top: 12px; +} + +.live-tile-widget-form__legend { + width: 100%; + margin-bottom: 4px; + font-weight: 600; +} + +.live-tile-widget-form__choice { + position: relative; + display: flex; + flex: 1 1 200px; + flex-direction: column; + gap: 2px; + padding: 10px 12px 10px 36px; + border: 2px solid var(--color-border); + border-radius: var(--border-radius-large); + cursor: pointer; +} + +.live-tile-widget-form__choice--selected { + border-color: var(--color-primary-element); + background: var(--color-primary-element-light); +} + +.live-tile-widget-form__choice--disabled { + cursor: not-allowed; + opacity: 0.6; +} + +.live-tile-widget-form__choice-input { + position: absolute; + top: 12px; + left: 12px; + margin: 0; +} + +.live-tile-widget-form__choice-title { + font-weight: 600; +} + +.live-tile-widget-form__choice-text { + font-size: 13px; + color: var(--color-text-maxcontrast); +} + +.live-tile-widget-form__view { + display: inline-flex; + gap: 6px; + align-items: center; + padding: 4px 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-pill); + cursor: pointer; +} + +.live-tile-widget-form__view--selected { + border-color: var(--color-primary-element); + background: var(--color-primary-element-light); +} + +.live-tile-widget-form__preview { + display: flex; + flex-direction: column; + gap: 4px; + padding: 12px; + border-radius: var(--border-radius-large); + background: var(--color-background-hover); +} + +.live-tile-widget-form__preview--bordered { + border: 1px solid var(--color-border-dark); +} + +.live-tile-widget-form__preview-title { + font-weight: 600; +} + +.live-tile-widget-form__preview-value { + font-size: 28px; + font-weight: 700; + color: var(--live-tile-accent, var(--color-main-text)); +} + +.live-tile-colour--primary { + --live-tile-accent: var(--color-primary-element); +} + +.live-tile-colour--success { + --live-tile-accent: var(--color-success-text, var(--color-success)); +} + +.live-tile-colour--warning { + --live-tile-accent: var(--color-warning-text, var(--color-warning)); +} + +.live-tile-colour--error { + --live-tile-accent: var(--color-error-text, var(--color-error)); +} </style> diff --git a/src/components/Widgets/Renderers/NewsWidget.vue b/src/components/Widgets/Renderers/NewsWidget.vue index e19516b2e..c3169a216 100644 --- a/src/components/Widgets/Renderers/NewsWidget.vue +++ b/src/components/Widgets/Renderers/NewsWidget.vue @@ -25,6 +25,7 @@ <div v-else-if="items.length === 0" class="news-widget__state news-widget__state--empty"> + <RssIcon class="news-widget__state-icon" :size="32" /> {{ t( 'launchpad', @@ -33,85 +34,110 @@ }} </div> - <ul v-else class="news-widget__list"> - <li v-for="item in items" :key="item.guid" class="news-widget__item"> - <a - v-if="item.link" - :href="item.link" - target="_blank" - rel="noopener noreferrer" - class="news-widget__item-link" - @click="onItemClick($event, item)"> - <img - v-if="showThumbnails && item.thumbnailUrl" - class="news-widget__thumb" - :src="item.thumbnailUrl" - alt="" /> - <div class="news-widget__body"> - <h4 class="news-widget__title">{{ item.title }}</h4> - <!-- Feed summaries carry inline markup REQ-NEWS-005 - deliberately preserves. This is third-party RSS, - so it is sanitised twice: server-side on fetch - by NewsWidgetService::sanitiseSummaryHtml(), and - again through DOMPurify in formattedSummary() - after truncation. --> - <!-- eslint-disable vue/no-v-html --> - <p - v-if="showSummary && item.summary" - class="news-widget__summary" - v-html="formattedSummary(item)" /> - <!-- eslint-enable vue/no-v-html --> - <div class="news-widget__meta"> - <span class="news-widget__source">{{ - item.sourceTitle - }}</span> - <span class="news-widget__date">{{ - formatDate(item.pubDate) - }}</span> + <template v-else> + <WidgetRowFilter v-model="rowFilter" /> + <div + v-if="layout === 'carousel' && shownItems.length > 1" + class="news-widget__carousel-nav"> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Previous item')" + :disabled="carouselIndex === 0" + @click="showSlide(carouselIndex - 1)"> + <template #icon> + <ChevronLeft :size="20" /> + </template> + </NcButton> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Next item')" + :disabled="carouselIndex >= shownItems.length - 1" + @click="showSlide(carouselIndex + 1)"> + <template #icon> + <ChevronRight :size="20" /> + </template> + </NcButton> + </div> + <ul ref="list" class="news-widget__list"> + <li v-for="item in shownItems" :key="item.guid" class="news-widget__item"> + <a + v-if="safeLink(item)" + :href="safeLink(item)" + target="_blank" + rel="noopener noreferrer" + class="news-widget__item-link" + @click="onItemClick($event, item)"> + <img + v-if="showThumbnails && item.thumbnailUrl" + class="news-widget__thumb" + :src="item.thumbnailUrl" + alt="" /> + <div class="news-widget__body"> + <h4 class="news-widget__title">{{ item.title }}</h4> + <!-- Feed summaries carry inline markup REQ-NEWS-005 + deliberately preserves. This is third-party RSS, + so it is sanitised twice: server-side on fetch + by NewsWidgetService::sanitiseSummaryHtml(), and + again through DOMPurify in formattedSummary() + after truncation. --> + <!-- eslint-disable vue/no-v-html --> + <p + v-if="showSummary && item.summary" + class="news-widget__summary" + v-html="formattedSummary(item)" /> + <!-- eslint-enable vue/no-v-html --> + <div class="news-widget__meta"> + <span class="news-widget__source">{{ + item.sourceTitle + }}</span> + <span class="news-widget__date">{{ + formatDate(item.pubDate) + }}</span> + </div> </div> - </div> - </a> - <div - v-else - class="news-widget__item-link news-widget__item-link--inert"> - <!-- Decorative: the headline beside it carries the meaning, - and this card is inert, so there is no link for the - image to name. aria-hidden states that explicitly - rather than leaving alt="" to imply it. --> - <img - v-if="showThumbnails && item.thumbnailUrl" - class="news-widget__thumb" - :src="item.thumbnailUrl" - alt="" - aria-hidden="true" /> - <div class="news-widget__body"> - <h4 class="news-widget__title"> - {{ item.title }} - </h4> - <!-- Feed summaries carry inline markup REQ-NEWS-005 - deliberately preserves. This is third-party RSS, - so it is sanitised twice: server-side on fetch - by NewsWidgetService::sanitiseSummaryHtml(), and - again through DOMPurify in formattedSummary() - after truncation. --> - <!-- eslint-disable vue/no-v-html --> - <p - v-if="showSummary && item.summary" - class="news-widget__summary" - v-html="formattedSummary(item)" /> - <!-- eslint-enable vue/no-v-html --> - <div class="news-widget__meta"> - <span class="news-widget__source">{{ - item.sourceTitle - }}</span> - <span class="news-widget__date">{{ - formatDate(item.pubDate) - }}</span> + </a> + <div + v-else + class="news-widget__item-link news-widget__item-link--inert"> + <!-- Decorative: the headline beside it carries the meaning, + and this card is inert, so there is no link for the + image to name. aria-hidden states that explicitly + rather than leaving alt="" to imply it. --> + <img + v-if="showThumbnails && item.thumbnailUrl" + class="news-widget__thumb" + :src="item.thumbnailUrl" + alt="" + aria-hidden="true" /> + <div class="news-widget__body"> + <h4 class="news-widget__title"> + {{ item.title }} + </h4> + <!-- Feed summaries carry inline markup REQ-NEWS-005 + deliberately preserves. This is third-party RSS, + so it is sanitised twice: server-side on fetch + by NewsWidgetService::sanitiseSummaryHtml(), and + again through DOMPurify in formattedSummary() + after truncation. --> + <!-- eslint-disable vue/no-v-html --> + <p + v-if="showSummary && item.summary" + class="news-widget__summary" + v-html="formattedSummary(item)" /> + <!-- eslint-enable vue/no-v-html --> + <div class="news-widget__meta"> + <span class="news-widget__source">{{ + item.sourceTitle + }}</span> + <span class="news-widget__date">{{ + formatDate(item.pubDate) + }}</span> + </div> </div> </div> - </div> - </li> - </ul> + </li> + </ul> + </template> </div> </template> @@ -119,6 +145,16 @@ import axios from '@nextcloud/axios' import { generateUrl } from '@nextcloud/router' import DOMPurify from 'dompurify' +import NcButton from '@nextcloud/vue/components/NcButton' +import ChevronLeft from 'vue-material-design-icons/ChevronLeft.vue' +import ChevronRight from 'vue-material-design-icons/ChevronRight.vue' +import RssIcon from 'vue-material-design-icons/Rss.vue' +import WidgetRowFilter from '../WidgetRowFilter.vue' +import { + NULLABLE_OBJECT_PROP, + OBJECT_PROP, +} from '../../../constants/propDefinitions.js' +import { filterRows } from '../../../utils/rowFilter.js' const ALLOWED_LAYOUTS = ['list', 'grid', 'carousel'] const DEFAULT_LAYOUT = 'list' @@ -196,6 +232,8 @@ function truncateSummaryHtml(html, maxChars) { return DOMPurify.sanitize(body.innerHTML, { ALLOWED_TAGS: ALLOWED_SUMMARY_TAGS, ALLOWED_ATTR: ALLOWED_SUMMARY_ATTR, + ALLOW_DATA_ATTR: false, + ALLOW_ARIA_ATTR: false, }) } @@ -223,18 +261,20 @@ function truncateSummaryHtml(html, maxChars) { export default { name: 'NewsWidget', + components: { + ChevronLeft, + ChevronRight, + NcButton, + RssIcon, + WidgetRowFilter, + }, + props: { /** Persisted widget content blob (placement.styleConfig.content). */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** Placement entity carrying the id we hit the API with. */ - placement: { - type: Object, - default: null, - }, + placement: NULLABLE_OBJECT_PROP, }, data() { @@ -244,10 +284,26 @@ export default { failedUrls: [], loading: false, hasError: false, + // REQ-DWMS-008: the row filter is view state only. Never saved, + // never shared, gone after a reload. + rowFilter: '', + // The item the carousel layout shows. + carouselIndex: 0, } }, computed: { + /** + * The items the person's row filter keeps; the fetched items themselves + * and the widget's settings are never touched. + * + * @return {Array<object>} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-008-search-inside-a-widgets-results + */ + shownItems() { + return filterRows(this.items, this.rowFilter, ['title', 'summary', 'sourceTitle']) + }, + /** @spec openspec/specs/news-widget/spec.md */ feedUrls() { const value = this.content && this.content.feedUrls @@ -314,6 +370,15 @@ export default { /** @spec openspec/specs/news-widget/spec.md */ failedBadgeLabel() { + const allFailed = this.items.length === 0 + && this.feedUrls.length > 0 + && this.failedCount >= this.feedUrls.length + if (allFailed && this.failedCount > 1) { + return t('launchpad', 'All {count} feeds failed').replace( + '{count}', + String(this.failedCount), + ) + } if (this.failedCount === 1) { return t('launchpad', '1 feed failed') } @@ -354,6 +419,36 @@ export default { }, methods: { + /** + * The item's link when it is an http(s) URL; null otherwise, so a + * `javascript:`, `data:` or other scheme renders as an inert card. + * + * @param {object} item News item. + * @return {string|null} The link to bind, or null. + * @spec openspec/specs/news-widget/spec.md + */ + safeLink(item) { + const link = item && typeof item.link === 'string' ? item.link.trim() : '' + return /^https?:\/\//i.test(link) ? link : null + }, + + /** + * Scroll the carousel to one item. + * + * @param {number} index The item to show. + * @return {void} + * @spec openspec/specs/news-widget/spec.md + */ + showSlide(index) { + const last = this.shownItems.length - 1 + this.carouselIndex = Math.max(0, Math.min(last, index)) + const list = this.$refs.list + const slide = list && list.children[this.carouselIndex] + if (slide) { + list.scrollTo({ left: slide.offsetLeft - list.offsetLeft, behavior: 'smooth' }) + } + }, + /** @spec openspec/specs/news-widget/spec.md */ async loadItems() { if (this.placementId === null) { @@ -375,6 +470,7 @@ export default { }) const data = response && response.data ? response.data : {} this.items = Array.isArray(data.items) ? data.items : [] + this.carouselIndex = 0 this.failedCount = typeof data.feedsFailed === 'number' ? data.feedsFailed : 0 this.failedUrls = Array.isArray(data.failedUrls) @@ -399,13 +495,14 @@ export default { * @spec openspec/specs/news-widget/spec.md */ onItemClick(event, item) { - if (!item || !item.link) { + const link = this.safeLink(item) + if (link === null) { return } // Keep the native anchor behaviour; the `window.open` below is // only needed when consumers preventDefault() the anchor. if (event && event.defaultPrevented) { - window.open(item.link, '_blank', 'noopener,noreferrer') + window.open(link, '_blank', 'noopener,noreferrer') } }, @@ -455,20 +552,20 @@ export default { } const diffMinutes = Math.floor(diffSeconds / 60) if (diffMinutes < 60) { - return t('launchpad', '{n} minutes ago').replace( - '{n}', - String(diffMinutes), - ) + return diffMinutes === 1 + ? t('launchpad', '1 minute ago') + : t('launchpad', '{n} minutes ago').replace('{n}', String(diffMinutes)) } const diffHours = Math.floor(diffMinutes / 60) if (diffHours < 24) { - return t('launchpad', '{n} hours ago').replace( - '{n}', - String(diffHours), - ) + return diffHours === 1 + ? t('launchpad', '1 hour ago') + : t('launchpad', '{n} hours ago').replace('{n}', String(diffHours)) } const diffDays = Math.floor(diffHours / 24) - return t('launchpad', '{n} days ago').replace('{n}', String(diffDays)) + return diffDays === 1 + ? t('launchpad', '1 day ago') + : t('launchpad', '{n} days ago').replace('{n}', String(diffDays)) }, }, } @@ -499,6 +596,8 @@ export default { .news-widget__state { flex: 1; display: flex; + flex-direction: column; + gap: 8px; align-items: center; justify-content: center; padding: 16px; @@ -531,12 +630,25 @@ export default { display: flex; flex-direction: row; gap: 12px; - overflow-x: auto; - overflow-y: hidden; + overflow: hidden; + scroll-snap-type: x mandatory; } .news-widget--carousel .news-widget__item { - flex: 0 0 220px; + flex: 0 0 100%; + scroll-snap-align: start; +} + +.news-widget__carousel-nav { + display: flex; + justify-content: flex-end; + gap: 4px; +} + +.news-widget--grid .news-widget__item-link { + border: 1px solid var(--color-border); + box-shadow: 0 1px 3px var(--color-box-shadow); + background-color: var(--color-main-background); } .news-widget__item-link { diff --git a/src/components/Widgets/Renderers/NewsWidgetForm.vue b/src/components/Widgets/Renderers/NewsWidgetForm.vue index 5282c876d..35512ee76 100644 --- a/src/components/Widgets/Renderers/NewsWidgetForm.vue +++ b/src/components/Widgets/Renderers/NewsWidgetForm.vue @@ -99,6 +99,10 @@ <script> import { translate as t } from '@nextcloud/l10n' import { NcCheckboxRadioSwitch, NcSelect, NcTextField } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' const ALLOWED_LAYOUTS = Object.freeze(['list', 'grid', 'carousel']) @@ -113,6 +117,99 @@ const DEFAULT_CONTENT = Object.freeze({ metadataFilter: null, }) +/** + * A number from stored content, or the fallback when it is not one. + * + * @param {unknown} value The stored value. + * @param {number} fallback The default. + * @return {number} the number to edit. + */ +function numberOr(value, fallback) { + return typeof value === 'number' ? value : fallback +} + +/** + * A toggle from stored content: unset reads as the fallback, anything but + * `true` as off. + * + * @param {unknown} value The stored value. + * @param {boolean} fallback The default. + * @return {boolean} the toggle to edit. + */ +function toggleOr(value, fallback) { + if (value === undefined) { + return fallback + } + return value === true +} + +/** + * The feed, layout and display fields of the form, read from stored content. + * + * @param {object} initial The stored content. + * @return {object} the display part of the form state. + */ +function displayFields(initial) { + return { + feedUrls: Array.isArray(initial.feedUrls) ? [...initial.feedUrls] : [], + layout: ALLOWED_LAYOUTS.includes(initial.layout) + ? initial.layout + : DEFAULT_CONTENT.layout, + + itemLimit: numberOr(initial.itemLimit, DEFAULT_CONTENT.itemLimit), + showThumbnails: toggleOr(initial.showThumbnails, DEFAULT_CONTENT.showThumbnails), + showSummary: toggleOr(initial.showSummary, DEFAULT_CONTENT.showSummary), + summaryMaxChars: numberOr(initial.summaryMaxChars, DEFAULT_CONTENT.summaryMaxChars), + dateFormat: initial.dateFormat === 'absolute' ? 'absolute' : 'relative', + } +} + +/** + * The validation error of one feed URL row, or null when it is valid. + * + * @param {unknown} url The feed URL row. + * @return {string|null} the error. + */ +function feedUrlError(url) { + if (typeof url !== 'string' || url.trim() === '') { + return t('launchpad', 'Empty feed URL — remove it or fill it in') + } + if (!/^https?:\/\//i.test(url.trim())) { + return t( + 'launchpad', + 'Feed URL must start with http:// or https://', + ) + } + return null +} + +/** + * A string from a stored metadata filter, or '' when it is not one. + * + * @param {unknown} value The stored value. + * @return {string} the string to edit. + */ +function stringOrEmpty(value) { + return typeof value === 'string' ? value : '' +} + +/** + * The metadata-filter fields of the form, read from a stored filter. + * + * @param {unknown} filter The stored `{fieldKey, value}` filter, or null. + * @return {{enabled: boolean, fieldKey: string, value: string}} the filter fields. + */ +function metadataFilterFields(filter) { + if (filter === null || typeof filter !== 'object') { + return { enabled: false, fieldKey: '', value: '' } + } + return { + enabled: true, + fieldKey: stringOrEmpty(filter.fieldKey), + value: stringOrEmpty(filter.value), + } +} + /** * NewsWidgetForm — sub-form for creating or editing a `news` placement. * @@ -140,16 +237,10 @@ export default { props: { /** The placement being edited, or `null` in create mode. */ - editingWidget: { - type: Object, - default: null, - }, + editingWidget: NULLABLE_OBJECT_PROP, /** Initial content values (registry defaults when not editing). */ - value: { - type: Object, - default: () => ({ ...DEFAULT_CONTENT }), - }, + value: objectProp(DEFAULT_CONTENT), }, emits: [ @@ -163,43 +254,12 @@ export default { data() { const initial = this.editingWidget?.content || this.value || {} - const filter = initial.metadataFilter - const hasFilter = filter !== null && typeof filter === 'object' + const filter = metadataFilterFields(initial.metadataFilter) return { - feedUrls: Array.isArray(initial.feedUrls) ? [...initial.feedUrls] : [], - layout: ALLOWED_LAYOUTS.includes(initial.layout) - ? initial.layout - : DEFAULT_CONTENT.layout, - - itemLimit: - typeof initial.itemLimit === 'number' - ? initial.itemLimit - : DEFAULT_CONTENT.itemLimit, - - showThumbnails: - initial.showThumbnails === undefined - ? DEFAULT_CONTENT.showThumbnails - : initial.showThumbnails === true, - - showSummary: - initial.showSummary === undefined - ? DEFAULT_CONTENT.showSummary - : initial.showSummary === true, - - summaryMaxChars: - typeof initial.summaryMaxChars === 'number' - ? initial.summaryMaxChars - : DEFAULT_CONTENT.summaryMaxChars, - - dateFormat: initial.dateFormat === 'absolute' ? 'absolute' : 'relative', - metadataFilterEnabled: hasFilter, - metadataFieldKey: - hasFilter && typeof filter.fieldKey === 'string' - ? filter.fieldKey - : '', - - metadataValue: - hasFilter && typeof filter.value === 'string' ? filter.value : '', + ...displayFields(initial), + metadataFilterEnabled: filter.enabled, + metadataFieldKey: filter.fieldKey, + metadataValue: filter.value, } }, @@ -376,32 +436,14 @@ export default { * @spec openspec/specs/news-widget/spec.md */ validate() { - const errors = [] - for (const url of this.feedUrls) { - if (typeof url !== 'string' || url.trim() === '') { - errors.push( - t('launchpad', 'Empty feed URL — remove it or fill it in'), - ) - continue - } - if (!/^https?:\/\//i.test(url.trim())) { - errors.push( - t( - 'launchpad', - 'Feed URL must start with http:// or https://', - ), - ) - } - } - if (this.metadataFilterEnabled) { - if (this.metadataFieldKey.trim() === '') { - errors.push( - t( - 'launchpad', - 'Metadata field key is required when filter is enabled', - ), - ) - } + const errors = this.feedUrls.map(feedUrlError).filter(Boolean) + if (this.metadataFilterEnabled && this.metadataFieldKey.trim() === '') { + errors.push( + t( + 'launchpad', + 'Metadata field key is required when filter is enabled', + ), + ) } return errors }, diff --git a/src/components/Widgets/Renderers/PeopleWidget.vue b/src/components/Widgets/Renderers/PeopleWidget.vue deleted file mode 100644 index c775028d8..000000000 --- a/src/components/Widgets/Renderers/PeopleWidget.vue +++ /dev/null @@ -1,578 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2026 LaunchPad Contributors - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <div class="people-widget" :class="layoutClass"> - <header class="people-widget__header"> - <input - v-model="search" - type="search" - class="people-widget__search" - :aria-label="t('launchpad', 'Search people')" - :placeholder="t('launchpad', 'Search by name or email…')" /> - <button - type="button" - class="people-widget__refresh" - :title="t('launchpad', 'Refresh')" - :aria-label="t('launchpad', 'Refresh')" - @click="forceRefresh"> - ↻ - </button> - </header> - - <div v-if="loading && users.length === 0" class="people-widget__state"> - {{ t('launchpad', 'Loading…') }} - </div> - - <div - v-else-if="error" - class="people-widget__state people-widget__state--error"> - <p>{{ t('launchpad', 'Failed to load users') }}</p> - <button type="button" class="people-widget__retry" @click="forceRefresh"> - {{ t('launchpad', 'Retry') }} - </button> - </div> - - <div v-else-if="filteredUsers.length === 0" class="people-widget__state"> - {{ - search - ? t('launchpad', 'No users match your search') - : t('launchpad', 'No matching users.') - }} - </div> - - <div v-else class="people-widget__items" :style="gridStyle" role="list"> - <a - v-for="user in filteredUsers" - :key="user.uid" - :href="profileUrl(user.uid)" - class="people-widget__item" - role="listitem"> - <img - :src="user.avatarUrl" - :width="avatarSize" - :height="avatarSize" - :alt=" - t('launchpad', 'Avatar of {name}', { - name: user.displayName, - }) - " - class="people-widget__avatar" /> - - <div class="people-widget__meta"> - <strong class="people-widget__name">{{ - user.displayName - }}</strong> - <span - v-if="layout !== 'grid' && user.role" - class="people-widget__role"> - {{ user.role }} - </span> - <span - v-if=" - layout !== 'grid' - && (user.organisation || user.department) - " - class="people-widget__org"> - {{ user.organisation || user.department }} - </span> - <span - v-if="layout !== 'grid' && user.email" - class="people-widget__email"> - {{ user.email }} - </span> - <span - v-if="showBirthdayBadge(user)" - class="people-widget__birthday"> - {{ formatBirthdayBadge(user) }} - </span> - </div> - </a> - </div> - - <footer v-if="hasMore && !error" class="people-widget__footer"> - <button - type="button" - class="people-widget__load-more" - :disabled="loading" - @click="loadMore"> - {{ - loading - ? t('launchpad', 'Loading…') - : t('launchpad', 'Load more') - }} - </button> - </footer> - </div> -</template> - -<script> -const CACHE_TTL_MS = 60 * 1000 - -const DEFAULT_CONTENT = Object.freeze({ - layout: 'grid', - filters: [], - excludeDisabled: true, - showBirthdays: true, - birthdayWindowDays: 7, - sortBy: 'displayName', - columns: 3, -}) - -/** - * PeopleWidget — renders a paginated, group-filterable user directory - * (capability `people-widget`, REQ-PPL-001..012). - * - * Three layout modes (`card`, `grid`, `list`) backed by the same item - * markup; CSS modifiers tune avatar size and column count. Search is a - * client-side substring filter on the current page (REQ-PPL-011). - * - * Pagination is offset-based and matches the backend service contract - * (REQ-PPL-003): each "Load more" tap appends one page of size - * `PAGE_SIZE` starting at the current `users.length`. - * - * Caching: results are kept in an in-memory map keyed on the JSON-encoded - * filter shape for {@link CACHE_TTL_MS}; the toolbar refresh button - * clears the cache and refetches (REQ-PPL-012). - * - * Click-through (REQ-PPL-010): each item is rendered as an `<a>` linking - * to `/u/{uid}` so the browser does the navigation natively (same tab, - * keyboard accessible by default). - */ -export default { - name: 'PeopleWidget', - - props: { - /** - * Persisted widget content (see `DEFAULT_CONTENT` for shape). - */ - content: { - type: Object, - default: () => ({ ...DEFAULT_CONTENT }), - }, - }, - - data() { - return { - users: [], - total: 0, - hasMore: false, - loading: false, - error: null, - search: '', - cacheKey: '', - cacheStoredAt: 0, - } - }, - - computed: { - /** @spec openspec/specs/people-widget/spec.md */ - layout() { - const value = this.content?.layout - return ['card', 'grid', 'list'].includes(value) - ? value - : DEFAULT_CONTENT.layout - }, - - /** @spec openspec/specs/people-widget/spec.md */ - layoutClass() { - return `people-widget--${this.layout}` - }, - - /** @spec openspec/specs/people-widget/spec.md */ - columns() { - const raw = this.content?.columns - if (typeof raw === 'number' && [2, 3, 4].includes(raw)) { - return raw - } - return this.layout === 'grid' ? 4 : 3 - }, - - /** @spec openspec/specs/people-widget/spec.md */ - gridStyle() { - if (this.layout === 'list') { - return {} - } - return { - 'grid-template-columns': `repeat(${this.columns}, minmax(0, 1fr))`, - } - }, - - /** @spec openspec/specs/people-widget/spec.md */ - avatarSize() { - switch (this.layout) { - case 'card': - return 80 - case 'list': - return 44 - case 'grid': - default: - return 64 - } - }, - - /** @spec openspec/specs/people-widget/spec.md */ - showBirthdays() { - return this.content?.showBirthdays !== false - }, - - /** @spec openspec/specs/people-widget/spec.md */ - birthdayWindowDays() { - const value = this.content?.birthdayWindowDays - if (typeof value === 'number' && value >= 0 && value <= 30) { - return value - } - return DEFAULT_CONTENT.birthdayWindowDays - }, - - /** @spec openspec/specs/people-widget/spec.md */ - filteredUsers() { - if (!this.search) { - return this.users - } - const needle = this.search.toLowerCase() - return this.users.filter((user) => { - const name = (user.displayName || '').toLowerCase() - const email = (user.email || '').toLowerCase() - return name.includes(needle) || email.includes(needle) - }) - }, - - /** @spec openspec/specs/people-widget/spec.md */ - queryParams() { - const filters = Array.isArray(this.content?.filters) - ? this.content.filters - : [] - return { - filters: JSON.stringify(filters), - excludeDisabled: this.content?.excludeDisabled === false ? 0 : 1, - showBirthdays: this.content?.showBirthdays === false ? 0 : 1, - sortBy: this.content?.sortBy || DEFAULT_CONTENT.sortBy, - } - }, - }, - - watch: { - queryParams: { - /** @spec openspec/specs/people-widget/spec.md */ - handler() { - this.cacheKey = '' - this.cacheStoredAt = 0 - this.users = [] - this.total = 0 - this.hasMore = false - this.fetchPage(0) - }, - - deep: true, - }, - }, - - mounted() { - this.fetchPage(0) - }, - - methods: { - /** - * Nextcloud profile URL for a user. - * - * @param {string} uid The user id. - * @return {string} Path to that user's profile page. - * @spec openspec/specs/people-widget/spec.md - */ - profileUrl(uid) { - return `/u/${encodeURIComponent(uid)}` - }, - - /** - * Whether a user's card should carry a birthday badge — requires the - * widget setting, a known birthdate, and an upcoming date. - * - * @param {object} user The user record. - * @return {boolean} True when the badge should render. - * @spec openspec/specs/people-widget/spec.md - */ - showBirthdayBadge(user) { - if (!this.showBirthdays || !user.birthdate) { - return false - } - const days = this.daysToBirthday(user.birthdate) - if (days === null) { - return false - } - return days >= 0 && days <= this.birthdayWindowDays - }, - - /** - * Badge text for an upcoming birthday. - * - * @param {object} user The user record. - * @return {string} Localised "today" or "in {n} days" label. - * @spec openspec/specs/people-widget/spec.md - */ - formatBirthdayBadge(user) { - const days = this.daysToBirthday(user.birthdate) - if (days === 0) { - return t('launchpad', '🎂 today') - } - return t('launchpad', '🎂 in {n} days', { n: days }) - }, - - /** - * Days until a user's next birthday, ignoring the birth year. - * - * @param {string} iso Birthdate as `YYYY-MM-DD`. - * @return {number|null} Whole days until the next occurrence, or - * null when the input is missing or unparseable. - * @spec openspec/specs/people-widget/spec.md - */ - daysToBirthday(iso) { - if (typeof iso !== 'string' || !iso) { - return null - } - const parts = iso.split('-') - if (parts.length !== 3) { - return null - } - const [, monthStr, dayStr] = parts - const month = Number(monthStr) - const day = Number(dayStr) - if (!Number.isFinite(month) || !Number.isFinite(day)) { - return null - } - const today = new Date() - today.setHours(0, 0, 0, 0) - let candidate = new Date(today.getFullYear(), month - 1, day) - if (candidate < today) { - candidate = new Date(today.getFullYear() + 1, month - 1, day) - } - const diffMs = candidate.getTime() - today.getTime() - return Math.round(diffMs / (24 * 60 * 60 * 1000)) - }, - - /** @spec openspec/specs/people-widget/spec.md */ - async loadMore() { - if (this.loading || !this.hasMore) { - return - } - await this.fetchPage(this.users.length) - }, - - /** @spec openspec/specs/people-widget/spec.md */ - forceRefresh() { - this.cacheKey = '' - this.cacheStoredAt = 0 - this.users = [] - this.total = 0 - this.hasMore = false - this.fetchPage(0) - }, - - /** - * Fetch one page of users, serving from the in-memory cache when a - * matching entry is younger than `CACHE_TTL_MS` (REQ-PPL-003). - * - * @param {number} offset Zero-based index of the first user to - * fetch; pages are `PAGE_SIZE` long. - * @spec openspec/specs/people-widget/spec.md - */ - async fetchPage(offset) { - const cacheKey = JSON.stringify({ params: this.queryParams, offset }) - const fresh = - this.cacheKey === cacheKey - && Date.now() - this.cacheStoredAt < CACHE_TTL_MS - if (fresh && this.users.length > 0) { - return - } - - this.loading = true - this.error = null - try { - const params = new URLSearchParams() - Object.entries(this.queryParams).forEach(([key, value]) => { - params.append(key, String(value)) - }) - params.append('limit', '50') - params.append('offset', String(offset)) - - // Lazy import @nextcloud/* helpers — keeps the renderer - // out of the vitest css-no-op transform path for the - // majority of tests that don't exercise the network call. - const [{ default: axios }, { generateUrl }] = await Promise.all([ - import('@nextcloud/axios'), - import('@nextcloud/router'), - ]) - - const url = `${generateUrl('/apps/launchpad/api/people')}?${params.toString()}` - const response = await axios.get(url) - const data = response?.data || {} - - const incoming = Array.isArray(data.users) ? data.users : [] - if (offset === 0) { - this.users = incoming - } else { - this.users = this.users.concat(incoming) - } - this.total = - typeof data.total === 'number' ? data.total : this.users.length - this.hasMore = data.hasMore === true - - this.cacheKey = cacheKey - this.cacheStoredAt = Date.now() - } catch (err) { - this.error = err - } finally { - this.loading = false - } - }, - }, -} -</script> - -<style scoped> -.people-widget { - display: flex; - flex-direction: column; - height: 100%; - gap: 8px; - padding: 8px; - overflow: hidden; -} - -.people-widget__header { - display: flex; - gap: 6px; - align-items: center; - flex: 0 0 auto; -} - -.people-widget__search { - flex: 1 1 auto; - padding: 4px 8px; - border: 1px solid var(--color-border); - border-radius: var(--border-radius); - background: var(--color-main-background); - color: var(--color-main-text); -} - -.people-widget__refresh { - border: 1px solid var(--color-border); - background: var(--color-background-hover); - border-radius: var(--border-radius); - padding: 2px 8px; - cursor: pointer; - font-size: 14px; -} - -.people-widget__items { - flex: 1 1 auto; - overflow-y: auto; - display: grid; - gap: 8px; -} - -.people-widget--list .people-widget__items { - display: flex; - flex-direction: column; -} - -.people-widget__item { - display: flex; - gap: 8px; - align-items: center; - padding: 6px; - border-radius: var(--border-radius); - color: var(--color-main-text); - text-decoration: none; - border: 1px solid transparent; -} - -.people-widget--card .people-widget__item { - flex-direction: column; - text-align: center; - border: 1px solid var(--color-border); - background: var(--color-main-background); - min-height: 200px; -} - -.people-widget--grid .people-widget__item { - flex-direction: column; - text-align: center; -} - -.people-widget__item:hover { - background: var(--color-background-hover); - border-color: var(--color-border); -} - -.people-widget__avatar { - border-radius: 50%; - object-fit: cover; - background: var(--color-background-darker); -} - -.people-widget__meta { - display: flex; - flex-direction: column; - gap: 2px; - min-width: 0; -} - -.people-widget__name { - font-weight: 600; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - max-width: 100%; -} - -.people-widget__role, -.people-widget__org, -.people-widget__email { - font-size: 12px; - color: var(--color-text-maxcontrast); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.people-widget__birthday { - font-size: 12px; - color: var(--color-warning, #c4a000); -} - -.people-widget__state { - flex: 1 1 auto; - display: flex; - align-items: center; - justify-content: center; - color: var(--color-text-maxcontrast); - font-size: 13px; - padding: 16px; - text-align: center; -} - -.people-widget__state--error { - flex-direction: column; - gap: 8px; -} - -.people-widget__retry, -.people-widget__load-more { - padding: 4px 12px; - border: 1px solid var(--color-border); - border-radius: var(--border-radius); - background: var(--color-background-hover); - cursor: pointer; - font-size: 13px; -} - -.people-widget__footer { - flex: 0 0 auto; - display: flex; - justify-content: center; - padding-top: 4px; -} -</style> diff --git a/src/components/Widgets/Renderers/PeriodFieldSelect.vue b/src/components/Widgets/Renderers/PeriodFieldSelect.vue new file mode 100644 index 000000000..42bf9c69a --- /dev/null +++ b/src/components/Widgets/Renderers/PeriodFieldSelect.vue @@ -0,0 +1,97 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcSelect + class="period-field-select" + :modelValue="modelValue || null" + :options="options" + :inputLabel="t('launchpad', 'Date field for the period')" + :placeholder="t('launchpad', 'None: the widget does not follow the period')" + :clearable="true" + :loading="loading" + @update:modelValue="$emit('update:modelValue', $event || '')" /> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcSelect } from '@nextcloud/vue' +import { TEXT_PROP } from '../../../constants/propDefinitions.js' +import { fetchDateFields } from '../../../utils/periodDateFields.js' + +/** + * PeriodFieldSelect: the optional "Date field for the period" of a widget + * with a register source. The options are the source's date fields; the + * chosen one is stored as the source's `periodField`, so the widget's figures + * follow the dashboard's period (dashboard-period-and-download REQ-DPD-002). + * Empty means the widget ignores the period. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ +export default { + name: 'PeriodFieldSelect', + + components: { NcSelect }, + + props: { + /** The source's register. */ + register: TEXT_PROP, + + /** The source's schema. */ + schema: TEXT_PROP, + + /** The chosen date field, '' for none. */ + modelValue: TEXT_PROP, + }, + + emits: ['update:modelValue'], + + data() { + return { fields: [], loading: false } + }, + + computed: { + /** + * The date fields, with the chosen one kept when the sample no longer shows it. + * + * @return {string[]} + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + options() { + if (this.modelValue && !this.fields.includes(this.modelValue)) { + return [this.modelValue, ...this.fields] + } + return this.fields + }, + }, + + watch: { + register: 'loadFields', + schema: 'loadFields', + }, + + mounted() { + this.loadFields() + }, + + methods: { + t, + + /** + * Read the source's date fields. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + async loadFields() { + this.loading = true + try { + this.fields = await fetchDateFields(this.register, this.schema) + } finally { + this.loading = false + } + }, + }, +} +</script> diff --git a/src/components/Widgets/Renderers/RecentWorkWidget.vue b/src/components/Widgets/Renderers/RecentWorkWidget.vue new file mode 100644 index 000000000..294796a83 --- /dev/null +++ b/src/components/Widgets/Renderers/RecentWorkWidget.vue @@ -0,0 +1,278 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="recent-work" data-testid="recent-work-widget"> + <p v-if="loading" class="recent-work__state" data-testid="recent-work-loading"> + {{ t('launchpad', 'Loading your recent work…') }} + </p> + <p v-else-if="unavailable" class="recent-work__state" data-testid="recent-work-unavailable"> + {{ t('launchpad', 'Recent work needs the Activity app.') }} + </p> + <p v-else-if="rows.length === 0" class="recent-work__state" data-testid="recent-work-empty"> + {{ t('launchpad', 'Nothing you worked on recently.') }} + </p> + <ul v-else class="recent-work__list" data-testid="recent-work-list"> + <li v-for="row in rows" :key="row.key"> + <a :href="row.link" class="recent-work__row" data-testid="recent-work-row"> + <span class="recent-work__text"> + <span class="recent-work__title">{{ row.title }}</span> + <span class="recent-work__meta">{{ row.meta }}</span> + </span> + <ChevronRight class="recent-work__chevron" :size="20" aria-hidden="true" /> + </a> + </li> + </ul> + </div> +</template> + +<script> +import { getCanonicalLocale, t } from '@nextcloud/l10n' +import ChevronRight from 'vue-material-design-icons/ChevronRight.vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' + +/** Milliseconds in a day. */ +const DAY_MS = 86400000 + +/** A name that is only an id (a record's uuid) says nothing to the reader. */ +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + +/** App ids the Activity app reports under another name than the reader knows. */ +const APP_LABELS = { dav: 'calendar', spreed: 'talk' } + +/** + * When something was done, as the boards word it in recent work: this + * morning, afternoon or evening for today, the weekday within the last week, + * the day and month before that. + * + * @param {string} value ISO date. + * @param {Date} now The current moment. + * @param {string} locale BCP 47 locale. + * @return {string} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ +export function recentWhen(value, now, locale) { + const when = new Date(value ?? '') + if (Number.isNaN(when.getTime())) { + return '' + } + const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()) + if (when >= startOfToday) { + if (when.getHours() < 12) { + return t('launchpad', 'this morning') + } + return when.getHours() < 18 ? t('launchpad', 'this afternoon') : t('launchpad', 'this evening') + } + if (startOfToday - when < 6 * DAY_MS) { + return when.toLocaleDateString(locale, { weekday: 'long' }) + } + return when.toLocaleDateString(locale, { day: 'numeric', month: 'short' }) +} + +/** + * Whether an activity is the reader removing something. + * + * @param {object} activity An Activity API entry. + * @return {boolean} True for a delete. + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ +function isDeletion(activity) { + return /deleted|_delete/.test(String(activity.type ?? '')) || /deleted/.test(String(activity.subject ?? '')) +} + +/** + * The two keys one thing is known by: its object, and its name within its + * app (the same file saved again gets a new id). + * + * @param {object} activity An Activity API entry. + * @param {string} name The thing's name. + * @return {Array<string>} The object key and the name key. + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ +function thingKeys(activity, name) { + return [`${activity.object_type ?? ''}:${activity.object_id ?? name}`, `${activity.app ?? ''}:${name}`] +} + +/** + * Whether an activity names a thing a row can show: a name that is not + * only an id, a link, and an app the author chose. + * + * @param {object} activity An Activity API entry. + * @param {string} name The thing's name. + * @param {Array<string>} apps Only these apps' activity, all when empty. + * @return {boolean} True when it can be a row. + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ +function isShowable(activity, name, apps) { + if (name === '' || UUID.test(name) || !activity.link) { + return false + } + return apps.length === 0 || apps.includes(activity.app) +} + +/** + * The rows recent work shows for the reader's own activity: one row per + * thing (its newest activity), named by the thing and not by the action, + * with the app and when below it. Something the reader removed is not work + * to pick up again, and neither is its older activity: the feed is newest + * first, so the delete marks the thing as seen before that comes. + * + * @param {Array<object>} activities The Activity API's own-activity entries, newest first. + * @param {number} limit The most rows to show. + * @param {Date} now The current moment. + * @param {string} locale BCP 47 locale. + * @param {Array<string>} [apps] Only these apps' activity, all when empty. + * @return {Array<{key: string, title: string, meta: string, link: string}>} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ +export function recentWorkRows(activities, limit, now, locale, apps = []) { + const rows = [] + const seen = new Set() + for (const activity of Array.isArray(activities) ? activities : []) { + const name = String(activity?.object_name ?? '').split('/').filter(Boolean).pop() || '' + const keys = thingKeys(activity, name) + if (isDeletion(activity)) { + if (name !== '') { + keys.forEach((k) => seen.add(k)) + } + continue + } + if (!isShowable(activity, name, apps) || keys.some((k) => seen.has(k))) { + continue + } + keys.forEach((k) => seen.add(k)) + const app = APP_LABELS[activity.app] ?? activity.app ?? '' + rows.push({ + key: keys[0], + title: name, + meta: [app, recentWhen(activity.datetime, now, locale)].filter(Boolean).join(' · '), + link: activity.link, + }) + if (rows.length >= limit) { + break + } + } + return rows +} + +/** + * RecentWorkWidget: "Verder waar u was" on LpVandaag. The reader's own + * recent work from the Activity app (its `self` filter), so what colleagues + * or other apps did does not show here. + * + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ +export default { + name: 'RecentWorkWidget', + + components: { ChevronRight }, + + props: { + /** `{limit, apps}`: how many rows to show (default 6), and only these apps' work. */ + content: OBJECT_PROP, + }, + + data() { + return { + loading: true, + unavailable: false, + activities: [], + } + }, + + computed: { + /** + * @return {Array<object>} The rows to show. + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ + rows() { + const limit = Number(this.content?.limit) > 0 ? Number(this.content.limit) : 6 + const apps = Array.isArray(this.content?.apps) ? this.content.apps : [] + return recentWorkRows(this.activities, limit, new Date(), getCanonicalLocale(), apps) + }, + }, + + /** + * Ask the Activity app for the reader's own recent activity. + * + * @return {Promise<void>} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ + async mounted() { + const [{ default: axios }, { generateOcsUrl }] = await Promise.all([ + import('@nextcloud/axios'), + import('@nextcloud/router'), + ]) + try { + const { data } = await axios.get(generateOcsUrl('/apps/activity/api/v2/activity/self'), { + params: { format: 'json', limit: 200 }, + }) + this.activities = Array.isArray(data?.ocs?.data) ? data.ocs.data : [] + } catch (error) { + // 304 means no activity yet; anything else means the app cannot answer. + this.unavailable = error?.response?.status !== 304 + } finally { + this.loading = false + } + }, + + methods: { t }, +} +</script> + +<style scoped> +.recent-work__list { + margin: 0; + padding: 0; + list-style: none; +} + +/* The theme colours and underlines every link with id weight; a row reads + as a list row in the main text colour. */ +.recent-work__row:not(#recent-work-a):not(#recent-work-b) { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 0; + border-top: 1px solid var(--color-border); + color: var(--color-main-text) !important; + text-decoration: none !important; +} + +.recent-work__text { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; +} + +.recent-work__title { + overflow: hidden; + font-size: 15px; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +.recent-work__meta { + color: var(--color-text-maxcontrast); + font-size: 13px; +} + +.recent-work__chevron { + flex: none; + color: var(--color-primary-element); +} + +.recent-work__state { + margin: 0; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/RecentWorkWidgetForm.vue b/src/components/Widgets/Renderers/RecentWorkWidgetForm.vue new file mode 100644 index 000000000..4f7f7b97f --- /dev/null +++ b/src/components/Widgets/Renderers/RecentWorkWidgetForm.vue @@ -0,0 +1,78 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <fieldset class="recent-work-widget-form"> + <NcTextField + :modelValue="String(limit)" + type="number" + :label="t('launchpad', 'How many items')" + data-testid="recent-work-form-limit" + @update:modelValue="update($event)" /> + </fieldset> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcTextField } from '@nextcloud/vue' +import { objectProp } from '../../../constants/propDefinitions.js' + +/** + * RecentWorkWidgetForm: how many items of the reader's own recent work the + * `recent-work` widget lists. + * + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ +export default { + name: 'RecentWorkWidgetForm', + + components: { NcTextField }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: { + type: Object, + default: null, + }, + + /** + * Initial content values, used when not editing. + * + * @type {object} + */ + value: objectProp({ limit: 6 }), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { limit: Number(initial.limit) > 0 ? Number(initial.limit) : 6 } + }, + + methods: { + t, + + /** + * Keep the new number, between 1 and 20, and tell the modal. + * + * @param {string|number} value The typed number. + * @return {void} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-recent-work-shows-where-the-reader-left-off-req-wdg-032 + */ + update(value) { + const number = Math.round(Number(value)) + this.limit = Number.isFinite(number) ? Math.min(Math.max(number, 1), 20) : 6 + this.$emit('update:content', { limit: this.limit }) + }, + }, +} +</script> diff --git a/src/components/Widgets/Renderers/SearchWidget.vue b/src/components/Widgets/Renderers/SearchWidget.vue index b48e54256..601fbe982 100644 --- a/src/components/Widgets/Renderers/SearchWidget.vue +++ b/src/components/Widgets/Renderers/SearchWidget.vue @@ -5,10 +5,35 @@ <template> <div class="search-widget"> + <!-- An internet search as LpWerkplek draws it: a field, the engine, + a Search button, and a line that the results open in a new tab. --> + <form + v-if="webLayout" + class="search-widget__web" + role="search" + data-testid="search-widget-web" + @submit.prevent="searchWeb"> + <span class="search-widget__row"> + <label :for="inputId" class="hidden-visually">{{ t('launchpad', 'Internet search') }}</label> + <input + :id="inputId" + v-model="webQuery" + type="search" + class="search-widget__input" + :placeholder="content.placeholder || t('launchpad', 'Search the internet')"> + <span class="search-widget__engine" data-testid="search-widget-engine">{{ engine.name }}</span> + <button type="submit" class="search-widget__submit"> + {{ t('launchpad', 'Search') }} + </button> + </span> + <span class="search-widget__note">{{ t('launchpad', 'Opens the results in a new tab') }}</span> + </form> <RuntimeShellSearch + v-else :items="searchableTiles" :placeholder="content.placeholder || ''" :fallbackTarget="effectiveFallbackTarget" + :shortcuts="injectedSearchShortcuts" @open="onSearchOpen" @filter="onSearchFilter" @fallback="onSearchFallback" @@ -25,6 +50,7 @@ import { focusGrid, performFallback, } from '../../../composables/useTileSearchHost.js' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' import { useDashboardStore } from '../../../stores/dashboard.js' import { useTileSearchStore } from '../../../stores/tileSearch.js' import { useWidgetStore } from '../../../stores/widgets.js' @@ -64,6 +90,15 @@ export default { from: 'quicksearchFallbackTarget', default: 'none', }, + + /** + * The admin's search shortcuts (REQ-SPX-002). An empty list keeps + * the box as it was. + */ + injectedSearchShortcuts: { + from: 'searchShortcuts', + default: () => [], + }, }, props: { @@ -72,10 +107,7 @@ export default { * * @type {{placeholder?: string, fallbackTarget?: string}} */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** * The placement row this widget renders as. Deliberately declared and @@ -86,13 +118,45 @@ export default { * Declaring it absorbs the binding instead. */ // eslint-disable-next-line vue/no-unused-properties - placement: { - type: Object, - default: () => ({}), - }, + placement: OBJECT_PROP, + }, + + data() { + return { + webQuery: '', + inputId: `search-widget-${Math.random().toString(36).slice(2, 10)}`, + } }, computed: { + /** + * Whether the widget is an internet search form (`content.layout: + * 'web'`) rather than the tile search. + * + * @return {boolean} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-the-search-widget-can-search-the-internet-req-wdg-033 + */ + webLayout() { + return this.content?.layout === 'web' + }, + + /** + * The search engine: `content.engine` `{name, url}` with `{q}` in the + * url, else DuckDuckGo. + * + * @return {{name: string, url: string}} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-the-search-widget-can-search-the-internet-req-wdg-033 + */ + engine() { + const engine = this.content?.engine + if (engine && typeof engine.url === 'string' && engine.url.includes('{q}')) { + return { name: String(engine.name || ''), url: engine.url } + } + return { name: 'DuckDuckGo', url: 'https://duckduckgo.com/?q={q}' } + }, + ...mapState(useDashboardStore, ['widgetPlacements']), ...mapState(useWidgetStore, ['availableWidgets']), @@ -141,6 +205,21 @@ export default { }, methods: { + /** + * Open the engine's results for the typed words in a new tab. + * + * @return {void} + * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-the-search-widget-can-search-the-internet-req-wdg-033 + */ + searchWeb() { + const query = this.webQuery.trim() + if (query === '') { + return + } + window.open(this.engine.url.replace('{q}', encodeURIComponent(query)), '_blank', 'noopener,noreferrer') + }, + /** * REQ-QSEARCH-003 "Enter opens the selected tile". * @@ -194,6 +273,57 @@ export default { </script> <style scoped> +.search-widget__web { + display: flex; + flex-direction: column; + gap: 8px; +} + +.search-widget__row { + display: flex; + gap: 8px; +} + +.search-widget__input { + flex: 1; + box-sizing: border-box; + min-width: 0; + height: 40px; + margin: 0; + padding: 0 12px; + border: 1px solid var(--color-border-maxcontrast); + border-radius: 8px; + font-size: 14px; +} + +.search-widget__engine { + display: inline-flex; + align-items: center; + box-sizing: border-box; + height: 40px; + padding: 0 12px; + border: 1px solid var(--color-border-maxcontrast); + border-radius: 8px; + font-size: 14px; +} + +.search-widget__submit { + height: 40px; + margin: 0; + padding: 0 16px; + border: 0; + border-radius: 8px; + background: var(--color-primary-element); + color: var(--color-primary-element-text); + font-size: 14px; + font-weight: 600; +} + +.search-widget__note { + color: var(--color-text-maxcontrast); + font-size: 13px; +} + .search-widget { width: 100%; /* The results listbox is absolutely positioned inside RuntimeShellSearch diff --git a/src/components/Widgets/Renderers/SearchWidgetForm.vue b/src/components/Widgets/Renderers/SearchWidgetForm.vue index 42071d256..83a2a172e 100644 --- a/src/components/Widgets/Renderers/SearchWidgetForm.vue +++ b/src/components/Widgets/Renderers/SearchWidgetForm.vue @@ -56,6 +56,10 @@ import { FALLBACK_TARGET_UNIFIED_SEARCH, isValidFallbackTemplate, } from '../../../composables/useTileSearch.js' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' /** * The "inherit the admin setting" marker (REQ-QSEARCH-005). @@ -122,20 +126,14 @@ export default { * * @type {{content: object}|null} */ - editingWidget: { - type: Object, - default: null, - }, + editingWidget: NULLABLE_OBJECT_PROP, /** * Initial content values — used when not editing. * * @type {object} */ - value: { - type: Object, - default: () => ({ ...DEFAULT_CONTENT }), - }, + value: objectProp(DEFAULT_CONTENT), }, emits: ['update:content'], diff --git a/src/components/Widgets/Renderers/SectionHeadingWidget.vue b/src/components/Widgets/Renderers/SectionHeadingWidget.vue new file mode 100644 index 000000000..a532470e6 --- /dev/null +++ b/src/components/Widgets/Renderers/SectionHeadingWidget.vue @@ -0,0 +1,100 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="lp-section-heading" data-testid="section-heading-widget"> + <h2 class="lp-section-heading__title"> + {{ title }} + </h2> + <p v-if="description" class="lp-section-heading__description"> + {{ description }} + </p> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' + +/** + * SectionHeadingWidget: the `section-heading` widget ("Tussenkop", boards + * LpIntranet and LpWerkplek). A heading over the widgets or app tiles that + * follow it on the grid: a 20px bold title, one muted line of explanation + * and a rule below, on the page ground without a card. It spans the grid's + * full width. + * + * @spec openspec/specs/widgets/spec.md#requirement-req-wdg-031-a-section-heading-widget + */ +export default { + name: 'SectionHeadingWidget', + + props: { + /** + * Persisted content: `{title, description}`. + * + * @type {{title?: string, description?: string}} + */ + content: OBJECT_PROP, + }, + + computed: { + /** + * The heading, or a placeholder while it has none. + * + * @return {string} + * @spec openspec/specs/widgets/spec.md#requirement-req-wdg-031-a-section-heading-widget + */ + title() { + const value = typeof this.content?.title === 'string' ? this.content.title.trim() : '' + return value || t('launchpad', 'Section heading') + }, + + /** + * The line of explanation, or empty. + * + * @return {string} + * @spec openspec/specs/widgets/spec.md#requirement-req-wdg-031-a-section-heading-widget + */ + description() { + return typeof this.content?.description === 'string' ? this.content.description.trim() : '' + }, + }, +} +</script> + +<style scoped> +/* Board LpWerkplek: the title over its one line, on the grid's line, the + rule under both; the one-row cell holds them without clipping the line. */ +.lp-section-heading { + display: flex; + flex-direction: column; + justify-content: flex-end; + gap: 0; + box-sizing: border-box; + width: 100%; + height: 100%; + padding: 0 0 4px; + border-bottom: 1px solid var(--color-border); +} + +.lp-section-heading__title { + margin: 0; + color: var(--color-main-text); + font-size: 20px; + font-weight: 700; + line-height: 1.25; +} + +.lp-section-heading__description { + overflow: hidden; + margin: 0; + color: var(--color-text-maxcontrast); + font-size: 14px; + line-height: 1.3; + flex: none; + text-overflow: ellipsis; + white-space: nowrap; +} +</style> diff --git a/src/components/Widgets/Renderers/SectionHeadingWidgetForm.vue b/src/components/Widgets/Renderers/SectionHeadingWidgetForm.vue new file mode 100644 index 000000000..34a36f9d7 --- /dev/null +++ b/src/components/Widgets/Renderers/SectionHeadingWidgetForm.vue @@ -0,0 +1,105 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <fieldset class="section-heading-widget-form"> + <NcTextField + :modelValue="title" + :label="t('launchpad', 'Heading')" + :required="true" + data-testid="section-heading-form-title" + @update:modelValue="update({ title: String($event) })" /> + <NcTextField + :modelValue="description" + :label="t('launchpad', 'Explanation')" + :helperText="t('launchpad', 'One line under the heading. Leave empty for none.')" + data-testid="section-heading-form-description" + @update:modelValue="update({ description: String($event) })" /> + </fieldset> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcTextField } from '@nextcloud/vue' +import { objectProp } from '../../../constants/propDefinitions.js' + +/** + * SectionHeadingWidgetForm: the heading and the one line of explanation of + * a `section-heading` widget. + * + * @spec openspec/specs/widgets/spec.md#requirement-req-wdg-031-a-section-heading-widget + */ +export default { + name: 'SectionHeadingWidgetForm', + + components: { NcTextField }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: { + type: Object, + default: null, + }, + + /** + * Initial content values, used when not editing. + * + * @type {object} + */ + value: objectProp({ title: '', description: '' }), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + title: String(initial.title || ''), + description: String(initial.description || ''), + } + }, + + methods: { + t, + + /** + * Keep a change and tell the modal the whole content. + * + * @param {object} change The changed keys. + * @return {void} + * @spec openspec/specs/widgets/spec.md#requirement-req-wdg-031-a-section-heading-widget + */ + update(change) { + Object.assign(this, change) + this.$emit('update:content', { title: this.title.trim(), description: this.description.trim() }) + }, + + /** + * Validate the form: a heading needs a title. + * + * @return {string[]} The validation errors. + * @spec openspec/specs/widgets/spec.md#requirement-req-wdg-031-a-section-heading-widget + */ + validate() { + return this.title.trim() === '' ? [t('launchpad', 'Give the heading a title')] : [] + }, + }, +} +</script> + +<style scoped> +.section-heading-widget-form { + margin: 0; + padding: 0; + border: 0; + display: flex; + flex-direction: column; + gap: 12px; +} +</style> diff --git a/src/components/Widgets/Renderers/StatsBlockHost.vue b/src/components/Widgets/Renderers/StatsBlockHost.vue index 639906024..9349fe308 100644 --- a/src/components/Widgets/Renderers/StatsBlockHost.vue +++ b/src/components/Widgets/Renderers/StatsBlockHost.vue @@ -12,11 +12,16 @@ :showZeroCount="props.showZeroCount" :horizontal="props.horizontal" :route="props.route" - :iconClass="props.iconClass" /> + :iconClass="props.iconClass" + @data="onData" /> </template> <script> import { CnStatsBlockWidget } from '@conduction/nextcloud-vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { logger } from '../../../utils/logger.js' +import { busDeclarationsOf, consumedFilter, filterBusOf, refetchClock, withBusFilter } from '../../../utils/widgetBusConsumption.js' +import { validateBusDeclarations } from '../../../utils/widgetBusDeclarations.js' /** * StatsBlockHost — thin LaunchPad wrapper adapting the registry's `content` @@ -24,36 +29,105 @@ import { CnStatsBlockWidget } from '@conduction/nextcloud-vue' * onto CnStatsBlockWidget's separate-prop interface. CnStatsBlockWidget * self-fetches its count from `dataSource`; this host only maps content → * props, mirroring CnDashboardPage's `getStatsBlockProps`. + * + * On a dashboard with a filter bus, a stats block that declares `consumes` + * counts with the bus's clauses for those dimensions in its + * `dataSource.filter`, the way a consuming chart does (drill-down-cross- + * widget-filter REQ-CWF-002); a consumed dimension outside the dashboard's + * hierarchies keeps it off the bus, with a warning (REQ-CWF-008). */ export default { name: 'StatsBlockHost', components: { CnStatsBlockWidget }, + inject: { + /** The open dashboard's filter bus (a ref to it), or null. */ + filterBus: { from: 'dashboardFilterBus', default: null }, + }, + props: { /** The placement's content blob — `{ title, dataSource, props }`. */ - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, - /** The placement record (unused; accepted for the renderer interface). */ - // eslint-disable-next-line vue/no-unused-properties -- absorbs WidgetRenderer's uniform binding - placement: { - type: Object, - default: () => ({}), - }, + /** The placement record (its id names the widget in a warning). */ + placement: OBJECT_PROP, }, + emits: ['data'], + computed: { /** The card title. */ title() { return this.content.title || '' }, - /** The OpenRegister dataSource block CnStatsBlockWidget self-resolves. */ + /** + * The OpenRegister dataSource block CnStatsBlockWidget self-resolves, with the bus's filter when the block consumes it. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-10 + */ dataSource() { - return this.content.dataSource || null + return withBusFilter(this.content.dataSource || null, this.busFilter) + }, + + /** + * The filter bus itself, unwrapped from the injected ref. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-10 + */ + bus() { + return filterBusOf(this.filterBus) + }, + + /** + * The dimensions the block consumes. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-10 + */ + consumes() { + return busDeclarationsOf(this.content).consumes + }, + + /** + * Whether the block's `consumes` fits the dashboard, and why not. + * + * @return {{participates: boolean, findings: Array<object>}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-10 + */ + busCheck() { + if (this.bus === null || this.consumes.length === 0) { + return { participates: false, findings: [] } + } + return validateBusDeclarations({ widget: { consumes: this.consumes }, hierarchies: this.bus.hierarchies }) + }, + + /** + * The filter the bus's clauses add to the block's data source; empty off the bus. + * + * @return {{[field: string]: unknown}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-10 + */ + busFilter() { + if (!this.busCheck.participates) { + return {} + } + return consumedFilter(this.bus.clauses.value, this.consumes) + }, + + /** + * The bus filter as text, so a change of another dimension's clause is no change. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-35 + */ + busFilterKey() { + return JSON.stringify(this.busFilter) + }, + + /** The widget's name in a warning. */ + widgetId() { + return String(this.placement?.id ?? this.placement?.widgetId ?? 'stats-block') }, /** Presentation props (count label, variant, icon, …). */ @@ -61,5 +135,51 @@ export default { return this.content.props || {} }, }, + + watch: { + /** + * Start timing the refetch a changed bus filter causes. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-35 + */ + busFilterKey() { + this.refetchClock.start(this.busFilter) + }, + + busCheck: { + immediate: true, + /** + * Log why a stats block stays off the bus (REQ-CWF-008). + * + * @param {{findings: Array<object>}} check The check. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-10 + */ + handler(check) { + for (const finding of check.findings) { + logger.warn(`[launchpad] widget ${this.widgetId} is not on the filter bus: ${finding.code} (${finding.dimension})`) + } + }, + }, + }, + + created() { + this.refetchClock = refetchClock({ widgetId: () => this.widgetId, warn: (message) => logger.warn(message) }) + }, + + methods: { + /** + * Pass the block's data on, settling a refetch timed since a filter change. + * + * @param {object} data What the block shows. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-35 + */ + onData(data) { + this.refetchClock.settle() + this.$emit('data', data) + }, + }, } </script> diff --git a/src/components/Widgets/Renderers/StatusReportWidget.vue b/src/components/Widgets/Renderers/StatusReportWidget.vue new file mode 100644 index 000000000..09dd9ef6a --- /dev/null +++ b/src/components/Widgets/Renderers/StatusReportWidget.vue @@ -0,0 +1,356 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="status-report" data-testid="status-report-widget"> + <p + v-if="!configured" + class="status-report__state" + data-testid="status-report-unconfigured"> + {{ t('launchpad', 'Choose the register and schema of the body of work in this widget\'s settings.') }} + </p> + + <template v-else> + <p class="status-report__subject" data-testid="status-report-subject"> + {{ subjectLine }} + </p> + + <NcButton + v-if="!kept" + :disabled="busy" + data-testid="status-report-prepare" + @click="prepare"> + {{ draft ? t('launchpad', 'Prepare again') : t('launchpad', 'Prepare report') }} + </NcButton> + + <p + v-if="refusal" + class="status-report__notice" + role="alert" + data-testid="status-report-refused"> + {{ refusal }} + </p> + + <form + v-if="draft && !kept" + class="status-report__draft" + data-testid="status-report-draft" + @submit.prevent="keep"> + <dl class="status-report__figures" data-testid="status-report-figures"> + <template v-for="figure in figures" :key="figure.key"> + <dt>{{ figure.label }}</dt> + <dd :data-testid="`status-report-figure-${figure.key}`"> + {{ figure.value }} + </dd> + </template> + </dl> + <p class="status-report__hint"> + {{ t('launchpad', 'The figures are computed from the body of work and cannot be changed. The rating and the summary are a proposal: change them if they do not fit.') }} + </p> + + <NcSelect + v-model="health" + :options="healthOptions" + :reduce="(option) => option.id" + label="label" + :inputLabel="t('launchpad', 'Health rating')" + :clearable="false" + data-testid="status-report-health" /> + + <NcTextArea + v-model="summary" + :label="t('launchpad', 'Summary')" + :maxlength="maxSummary" + resize="vertical" + data-testid="status-report-summary" /> + + <NcButton + type="submit" + variant="primary" + :disabled="busy || summary.trim() === ''" + data-testid="status-report-keep"> + {{ t('launchpad', 'Keep report') }} + </NcButton> + </form> + + <div v-if="kept" class="status-report__kept" data-testid="status-report-kept"> + <p> + <strong>{{ healthLabel(kept.health) }}</strong> + — {{ t('launchpad', 'Kept report of {date}', { date: kept.date }) }} + </p> + <p class="status-report__kept-summary"> + {{ kept.summary }} + </p> + <ul class="status-report__provenance" data-testid="status-report-provenance"> + <li data-testid="status-report-provenance-health"> + {{ t('launchpad', 'Health rating') }}: {{ originLabel(kept.provenance?.health) }} + </li> + <li data-testid="status-report-provenance-summary"> + {{ t('launchpad', 'Summary') }}: {{ originLabel(kept.provenance?.summary) }} + </li> + <li>{{ t('launchpad', 'Figures') }}: {{ originLabel('computed') }}</li> + </ul> + <NcButton data-testid="status-report-new" @click="reset"> + {{ t('launchpad', 'New report') }} + </NcButton> + </div> + </template> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcButton, NcSelect, NcTextArea } from '@nextcloud/vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { draftStatusReport, keepStatusReport, subjectOf } from '../../../services/statusReport.js' +import { logger } from '../../../utils/logger.js' + +/** The summary length the server accepts. */ +const MAX_SUMMARY = 5000 + +/** + * StatusReportWidget: a dated status report on one body of work + * (REQ-DWMS-004). The product prefills the figures, the health rating and a + * summary; the person may change the rating and rewrite the summary, then + * keeps the report. The server computes the figures again on keeping and + * records, per value, whether it was computed or written by a person; the + * widget shows that record back. + */ +export default { + name: 'StatusReportWidget', + components: { + NcButton, + NcSelect, + NcTextArea, + }, + + props: { + /** Persisted widget content: the body of work (register, schema, title, deadline, …). */ + content: OBJECT_PROP, + }, + + data() { + return { + busy: false, + refusal: '', + draft: null, + health: null, + summary: '', + kept: null, + maxSummary: MAX_SUMMARY, + } + }, + + computed: { + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 */ + subject() { + return subjectOf(this.content) + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 */ + configured() { + return Boolean(this.subject.register && this.subject.schema) + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 */ + subjectLine() { + const name = this.subject.title || `${this.subject.register}/${this.subject.schema}` + return this.subject.deadline + ? t('launchpad', 'Status of {name}, deadline {deadline}', { name, deadline: this.subject.deadline }) + : t('launchpad', 'Status of {name}', { name }) + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 */ + healthOptions() { + return ['on-track', 'at-risk', 'off-track'].map((id) => ({ id, label: this.healthLabel(id) })) + }, + + /** + * The prefilled figures, in a fixed order, as label and value. + * + * @return {Array<{key: string, label: string, value: (string|number)}>} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ + figures() { + const figures = this.draft?.figures ?? {} + const rows = [ + ['total', t('launchpad', 'Items')], + ['open', t('launchpad', 'Open')], + ['closed', t('launchpad', 'Closed')], + ['overdue', t('launchpad', 'Overdue')], + ['percentClosed', t('launchpad', 'Share closed')], + ['daysToDeadline', t('launchpad', 'Days to the deadline')], + ] + return rows + .filter(([key]) => figures[key] !== undefined && figures[key] !== null) + .map(([key, label]) => ({ key, label, value: key === 'percentClosed' ? `${figures[key]}%` : figures[key] })) + }, + }, + + methods: { + t, + + /** + * @param {string} health the rating + * @return {string} the rating in words + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ + healthLabel(health) { + return { + 'on-track': t('launchpad', 'On track'), + 'at-risk': t('launchpad', 'At risk'), + 'off-track': t('launchpad', 'Off track'), + }[health] ?? String(health ?? '') + }, + + /** + * @param {string} origin `computed` or `written` + * @return {string} who the value came from + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ + originLabel(origin) { + return origin === 'written' ? t('launchpad', 'written by a person') : t('launchpad', 'computed by LaunchPad') + }, + + /** + * Why the server refused, in the reader's language. + * + * @param {number} status the HTTP status + * @return {string} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ + refusalText(status) { + if (status === 503) { + return t('launchpad', 'Status reports need OpenRegister, which is not available.') + } + if (status === 400) { + return t('launchpad', 'The report could not be made: check the register, the schema and the deadline in this widget\'s settings.') + } + if (status === 403 || status === 404) { + return t('launchpad', 'The items of this body of work cannot be read with your account.') + } + return t('launchpad', 'The report could not be made. Try again.') + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.2 */ + async prepare() { + await this.run(async () => { + const answer = await draftStatusReport(this.subject) + if (answer.refused) { + this.refusal = this.refusalText(answer.status) + return + } + this.draft = answer.report + this.health = answer.report?.health ?? 'on-track' + this.summary = String(answer.report?.summary ?? '') + }) + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 */ + async keep() { + if (this.summary.trim() === '') { + return + } + await this.run(async () => { + const answer = await keepStatusReport(this.subject, this.health, this.summary) + if (answer.refused) { + this.refusal = this.refusalText(answer.status) + return + } + this.kept = answer.report + }) + }, + + /** + * Run one request with the busy flag and the refusal cleared. + * + * @param {function(): Promise<void>} step the request + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ + async run(step) { + this.busy = true + this.refusal = '' + try { + await step() + } catch (error) { + logger.error('Status report request failed:', error) + this.refusal = this.refusalText(0) + } finally { + this.busy = false + } + }, + + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 */ + reset() { + this.draft = null + this.kept = null + this.summary = '' + this.health = null + this.refusal = '' + }, + }, +} +</script> + +<style scoped> +.status-report { + display: flex; + flex-direction: column; + gap: 8px; + height: 100%; + overflow-y: auto; + padding: 4px 12px 12px; +} + +.status-report__state, +.status-report__hint, +.status-report__subject { + color: var(--color-text-maxcontrast); + margin: 0; +} + +.status-report__notice { + margin: 0; + padding: 8px 12px; + border-radius: var(--border-radius-large); + background-color: var(--color-error); + color: var(--color-error-text); +} + +.status-report__draft, +.status-report__kept { + display: flex; + flex-direction: column; + gap: 8px; +} + +.status-report__figures { + display: grid; + grid-template-columns: max-content 1fr; + gap: 2px 12px; + margin: 0; +} + +.status-report__figures dt { + color: var(--color-text-maxcontrast); +} + +.status-report__figures dd { + margin: 0; + font-weight: bold; + color: var(--color-main-text); +} + +.status-report__kept-summary { + white-space: pre-wrap; + margin: 0; +} + +.status-report__provenance { + margin: 0; + padding-inline-start: 20px; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/StatusReportWidgetForm.vue b/src/components/Widgets/Renderers/StatusReportWidgetForm.vue new file mode 100644 index 000000000..2347a94c6 --- /dev/null +++ b/src/components/Widgets/Renderers/StatusReportWidgetForm.vue @@ -0,0 +1,128 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="status-report-form"> + <p class="status-report-form__hint"> + {{ + t( + 'launchpad', + 'Reports on the items of one schema in one register: how many are open, closed and overdue, and a health rating. You can change the rating and the summary before keeping a report.', + ) + }} + </p> + + <NcTextField + v-for="field in fields" + :key="field.key" + :modelValue="values[field.key]" + :label="field.label" + :type="field.type" + :helperText="field.helper" + :data-testid="`status-report-form-${field.key}`" + @update:modelValue="set(field.key, $event)" /> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcTextField } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' + +const KEYS = ['title', 'register', 'schema', 'deadline', 'statusProperty', 'closedValues', 'dueProperty'] + +/** + * StatusReportWidgetForm: the body of work a status report is about + * (dashboards-and-who-may-see-them REQ-DWMS-004). Register and schema are + * required; the rest narrows how items count as closed or overdue. + */ +export default { + name: 'StatusReportWidgetForm', + + components: { NcTextField }, + + props: { + /** The placement being edited, when there is one. */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** The content to start from. */ + value: objectProp({}), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + const values = {} + for (const key of KEYS) { + const raw = initial[key] + values[key] = Array.isArray(raw) ? raw.join(', ') : String(raw ?? '') + } + return { values } + }, + + computed: { + /** @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 */ + fields() { + return [ + { key: 'title', label: t('launchpad', 'Name of the body of work'), type: 'text' }, + { key: 'register', label: t('launchpad', 'Register'), type: 'text' }, + { key: 'schema', label: t('launchpad', 'Schema'), type: 'text' }, + { key: 'deadline', label: t('launchpad', 'Deadline'), type: 'date' }, + { key: 'statusProperty', label: t('launchpad', 'Status property'), type: 'text', helper: t('launchpad', 'The property that says whether an item is done.') }, + { key: 'closedValues', label: t('launchpad', 'Values that mean closed'), type: 'text', helper: t('launchpad', 'Separate several values with commas.') }, + { key: 'dueProperty', label: t('launchpad', 'Due date property'), type: 'text', helper: t('launchpad', 'An open item past this date counts as overdue.') }, + ] + }, + }, + + methods: { + t, + + /** + * @param {string} key the field + * @param {string} value the typed value + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ + set(key, value) { + this.values = { ...this.values, [key]: String(value ?? '') } + const content = {} + for (const name of KEYS) { + content[name] = this.values[name].trim() + } + content.closedValues = content.closedValues.split(',').map((part) => part.trim()).filter((part) => part !== '') + this.$emit('update:content', content) + }, + + /** + * @return {Array<string>} what keeps the widget from being saved + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ + validate() { + const errors = [] + if (this.values.register.trim() === '' || this.values.schema.trim() === '') { + errors.push(t('launchpad', 'A status report needs the register and the schema of the body of work.')) + } + return errors + }, + }, +} +</script> + +<style scoped> +.status-report-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.status-report-form__hint { + color: var(--color-text-maxcontrast); + margin: 0; +} +</style> diff --git a/src/components/Widgets/Renderers/TileHost.vue b/src/components/Widgets/Renderers/TileHost.vue new file mode 100644 index 000000000..432ba3598 --- /dev/null +++ b/src/components/Widgets/Renderers/TileHost.vue @@ -0,0 +1,88 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div v-if="isCreateTile" class="tile-host"> + <TileWidget :tile="createTile" :editMode="editMode" /> + </div> + <CnDashTileWidget + v-else + :content="content" + :placement="placement" + v-bind="$attrs" /> +</template> + +<script> +import { CnDashTileWidget } from '@conduction/nextcloud-vue' +import TileWidget from '../../TileWidget.vue' +import { FLAG_PROP, OBJECT_PROP } from '../../../constants/propDefinitions.js' + +/** + * TileHost — the `tile` widget type inside LaunchPad. A tile whose link type + * is `create` (an office "New ..." tile, REQ-OFT-002) renders through + * LaunchPad's TileWidget, which asks for a name and creates the file; every + * other tile renders through the shared CnDashTileWidget exactly as before. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ +export default { + name: 'TileHost', + + components: { + CnDashTileWidget, + TileWidget, + }, + + inheritAttrs: false, + + props: { + content: OBJECT_PROP, + + placement: OBJECT_PROP, + + editMode: FLAG_PROP, + }, + + computed: { + /** + * Whether this tile creates a file. + * + * @return {boolean} True for a `create` tile. + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + isCreateTile() { + return (this.content?.linkType ?? this.placement?.tileLinkType) === 'create' + }, + + /** + * The tile in the shape TileWidget reads, from the child's content. + * + * @return {object} The tile. + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + createTile() { + const c = this.content || {} + return { + id: this.placement?.id ?? ('create-' + (c.linkValue || '')), + title: c.title || '', + icon: c.icon || 'icon-filetype-file', + iconType: c.iconType || 'class', + backgroundColor: c.backgroundColor || '', + textColor: c.textColor || '', + linkType: 'create', + linkValue: c.linkValue || '', + } + }, + }, +} +</script> + +<style scoped> +.tile-host { + position: relative; + height: 100%; + width: 100%; +} +</style> diff --git a/src/components/Widgets/Renderers/VideoHost.vue b/src/components/Widgets/Renderers/VideoHost.vue new file mode 100644 index 000000000..d551ef0dd --- /dev/null +++ b/src/components/Widgets/Renderers/VideoHost.vue @@ -0,0 +1,151 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div v-if="resolving" class="video-host__loading"> + <NcLoadingIcon :size="32" /> + </div> + <CnVideoWidget + v-else + :content="resolvedContent" + :canEdit="canEdit" + @edit="$emit('edit')" /> +</template> + +<script> +import { CnVideoWidget, NcLoadingIcon } from '@conduction/nextcloud-vue' +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' + +/** + * VideoHost — LaunchPad wrapper around CnVideoWidget. A Nextcloud Files + * source (`sourceType: 'nc-file'`) is resolved at render time through the + * ACL-checked `GET /api/widgets/video/{placementId}/file`, for the viewer: + * a readable video gets its streaming URL, a deleted file and a non-video + * get their message, and anything else leaves the URL empty so the widget + * says "Video not accessible". Hosted players pass straight through. + * + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-006-check-file-access-control-for-nextcloud-files + */ +export default { + name: 'VideoHost', + + components: { CnVideoWidget, NcLoadingIcon }, + + props: { + /** The placement's content blob. */ + content: OBJECT_PROP, + + /** The placement record; its id addresses the file endpoint. */ + placement: OBJECT_PROP, + + /** Edit mode: the empty widget then offers "Configure now". */ + canEdit: { + type: Boolean, + default: false, + }, + }, + + emits: ['edit'], + + data() { + return { + resolving: false, + resolved: null, + } + }, + + computed: { + /** + * Whether this placement plays a Nextcloud file. + * + * @return {boolean} + */ + isFileSource() { + return this.content.sourceType === 'nc-file' + && this.content.fileId !== null + && this.content.fileId !== undefined + && this.content.fileId !== '' + }, + + /** + * The content handed to CnVideoWidget: the stored content, plus the + * streaming URL or the message for a file source. + * + * @return {object} + */ + resolvedContent() { + if (!this.isFileSource) { + return this.content + } + return { ...this.content, fileStreamingUrl: '', ...(this.resolved || {}) } + }, + }, + + watch: { + 'content.fileId': function() { + this.resolve() + }, + }, + + mounted() { + this.resolve() + }, + + methods: { + /** + * Ask the file endpoint what this viewer may play. + * + * @return {Promise<void>} + */ + async resolve() { + this.resolved = null + if (!this.isFileSource || !this.placement?.id) { + return + } + this.resolving = true + try { + const url = generateUrl('/apps/launchpad/api/widgets/video/{placementId}/file', { + placementId: this.placement.id, + }) + const response = await axios.get(url) + this.resolved = { fileStreamingUrl: String(response?.data?.streamingUrl || '') } + } catch (error) { + this.resolved = this.refusalOf(error?.response?.data?.error) + } finally { + this.resolving = false + } + }, + + /** + * The content patch for a refused file: its message, or an empty URL + * (CnVideoWidget's "Video not accessible"). + * + * @param {string|undefined} code The endpoint's error code. + * @return {object} + */ + refusalOf(code) { + if (code === 'not_found') { + return { error: t('launchpad', 'Video file not found') } + } + if (code === 'not_video') { + return { error: t('launchpad', 'File is not a video') } + } + return { fileStreamingUrl: '' } + }, + }, +} +</script> + +<style scoped> +.video-host__loading { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; +} +</style> diff --git a/src/components/Widgets/Renderers/VideoWidgetForm.vue b/src/components/Widgets/Renderers/VideoWidgetForm.vue new file mode 100644 index 000000000..967a55db5 --- /dev/null +++ b/src/components/Widgets/Renderers/VideoWidgetForm.vue @@ -0,0 +1,151 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <CnVideoWidgetForm + ref="form" + :editingWidget="editingWidget" + :value="value" + :urlError="urlError" + @update:content="onContent" /> +</template> + +<script> +import { CnVideoWidgetForm } from '@conduction/nextcloud-vue' +import axios from '@nextcloud/axios' +import { t } from '@nextcloud/l10n' +import { generateUrl } from '@nextcloud/router' + +/** How long the URL must stay unchanged before it is sent to the parse endpoint. */ +const PARSE_DELAY_MS = 300 + +/** + * The localised text of a parse endpoint error (VideoParsingService). + * + * @param {string} error The endpoint's error. + * @return {string} + */ +function parseErrorLabel(error) { + if (error === 'Invalid URL format') { + return t('launchpad', 'Invalid URL format') + } + if (error === 'Unsupported video source') { + return t('launchpad', 'Unsupported video source') + } + return error +} + +/** + * The video widget form with the server's verdict on the URL: each URL the + * user types is sent to `POST /api/widgets/video/parse`, and its error is + * shown under the field and blocks saving (REQ-VID-005). A Nextcloud file + * source is not parsed. + * + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-005-parse-and-validate-video-urls-server-side + */ +export default { + name: 'VideoWidgetForm', + + components: { CnVideoWidgetForm }, + + props: { + /** The placement being edited, or `null` in create mode. */ + editingWidget: { + type: Object, + default: null, + }, + + /** Initial content values. */ + value: { + type: Object, + default: () => ({}), + }, + }, + + emits: ['update:content'], + + data() { + return { + urlError: '', + lastContent: null, + } + }, + + computed: { + /** + * The content the dialog stores, read from the shared form. + * + * @return {object|undefined} + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-005-parse-and-validate-video-urls-server-side + */ + assembledContent() { + // Read again on each change: `$refs` alone is not reactive. + void this.lastContent + return this.$refs.form?.assembledContent + }, + }, + + beforeUnmount() { + clearTimeout(this.parseTimer) + }, + + methods: { + /** + * The shared form's errors plus the parse endpoint's. + * + * @return {string[]} + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-005-parse-and-validate-video-urls-server-side + */ + validate() { + return this.$refs.form ? this.$refs.form.validate() : [] + }, + + /** + * Pass a change up, and parse a changed URL once typing pauses. + * + * @param {object} content The assembled content. + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-005-parse-and-validate-video-urls-server-side + * @return {void} + */ + onContent(content) { + const urlChanged = content?.videoUrl !== this.lastContent?.videoUrl + this.lastContent = content + if (urlChanged) { + this.urlError = '' + clearTimeout(this.parseTimer) + const url = String(content?.videoUrl || '').trim() + if (url !== '' && content?.sourceType !== 'nc-file') { + this.parseTimer = setTimeout(() => this.parse(url), PARSE_DELAY_MS) + } + } + this.$emit('update:content', content) + }, + + /** + * Ask the parse endpoint about a URL. Only the answer for the URL still + * in the field counts; a failed request leaves the form's own check. + * + * @param {string} url The URL. + * @return {Promise<void>} + * @spec openspec/specs/video-widget/spec.md#requirement-req-vid-005-parse-and-validate-video-urls-server-side + */ + async parse(url) { + let error = '' + try { + await axios.post(generateUrl('/apps/launchpad/api/widgets/video/parse'), { videoUrl: url }) + } catch (failure) { + const data = failure?.response?.data + error = data && data.isValid === false && typeof data.error === 'string' ? parseErrorLabel(data.error) : '' + } + if (String(this.lastContent?.videoUrl || '').trim() !== url) { + return + } + this.urlError = error + // The dialog re-runs validate() on every content update. + this.$emit('update:content', this.lastContent) + }, + }, +} +</script> diff --git a/src/components/Widgets/Renderers/WeatherWidget.vue b/src/components/Widgets/Renderers/WeatherWidget.vue index 74df2b062..59217e43b 100644 --- a/src/components/Widgets/Renderers/WeatherWidget.vue +++ b/src/components/Widgets/Renderers/WeatherWidget.vue @@ -69,7 +69,12 @@ import WeatherRainy from 'vue-material-design-icons/WeatherRainy.vue' import WeatherSnowy from 'vue-material-design-icons/WeatherSnowy.vue' import WeatherSunny from 'vue-material-design-icons/WeatherSunny.vue' import WeatherWindy from 'vue-material-design-icons/WeatherWindy.vue' +import { + NULLABLE_OBJECT_PROP, + OBJECT_PROP, +} from '../../../constants/propDefinitions.js' import { fetchWeatherReading } from '../../../services/weatherClient.js' +import { loadPlacementReading } from '../../../utils/placementReading.js' /** * Maps a normalised `condition` code (returned by `WeatherService`) to an @@ -127,10 +132,7 @@ export default { * @type {{location?: string, unitsOverride?: string}} */ // eslint-disable-next-line vue/no-unused-properties -- resolved server-side; see above - content: { - type: Object, - default: () => ({}), - }, + content: OBJECT_PROP, /** * The widget placement — only `placement.id` is used, to call the @@ -138,8 +140,18 @@ export default { * * @type {{id?: number|string}|null} */ - placement: { - type: Object, + placement: NULLABLE_OBJECT_PROP, + + /** + * Where the reading comes from instead of LaunchPad's per-placement + * endpoint: a function of the placement id that resolves the reading. + * A public link or kiosk screen passes its token-scoped read here + * (REQ-PSHR-011); null (the default) is the signed-in dashboard. + * + * @type {(function((number|string)): Promise<object>)|null} + */ + readingSource: { + type: Function, default: null, }, }, @@ -234,90 +246,28 @@ export default { * reachable from here. * * @spec openspec/specs/clock-weather-widgets/spec.md#req-weather-001 + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 * @return {Promise<void>} */ async load() { - const placementId = this.placement?.id - if (placementId === undefined || placementId === null) { - this.loading = false - this.errorMessage = t( + await loadPlacementReading(this, { + placementId: this.placement?.id, + fetch: this.readingSource ?? fetchWeatherReading, + unsaved: t( 'launchpad', 'Weather is not available until this tile is saved.', - ) - return - } - - this.loading = true - this.errorMessage = '' - try { - const data = await fetchWeatherReading(placementId) - if (data && data.error) { - this.reading = null - this.errorMessage = t( - 'launchpad', - 'Weather is currently unavailable.', - ) - return - } - this.reading = data - } catch { - this.reading = null - this.errorMessage = t('launchpad', 'Failed to load weather.') - } finally { - this.loading = false - } + ), + unavailable: t('launchpad', 'Weather is currently unavailable.'), + failed: t('launchpad', 'Failed to load weather.'), + }) }, }, } </script> -<style scoped> -.weather-widget { - width: 100%; - height: 100%; - display: flex; - align-items: center; - justify-content: center; -} - -.weather-widget__state { - display: flex; - flex-direction: column; - align-items: center; - gap: 8px; - color: var(--color-text-maxcontrast, var(--color-main-text)); - text-align: center; -} - -.weather-widget__retry { - border: 1px solid var(--color-border); - border-radius: var(--border-radius); - background: transparent; - padding: 4px 12px; - cursor: pointer; - color: var(--color-main-text); -} - -.weather-widget__reading { - position: relative; - width: 100%; - display: flex; - flex-direction: column; - align-items: center; - gap: 4px; -} - -.weather-widget__badge { - position: absolute; - top: -8px; - right: -8px; - font-size: 0.7rem; - padding: 2px 6px; - border-radius: var(--border-radius-pill, 8px); - background: var(--color-warning, #ffcc00); - color: var(--color-main-text); -} +<style scoped src="./readingTile.css"></style> +<style scoped> .weather-widget__location { font-weight: 600; color: var(--color-main-text); diff --git a/src/components/Widgets/Renderers/WeatherWidgetForm.vue b/src/components/Widgets/Renderers/WeatherWidgetForm.vue index 006cbcc36..76cbdd658 100644 --- a/src/components/Widgets/Renderers/WeatherWidgetForm.vue +++ b/src/components/Widgets/Renderers/WeatherWidgetForm.vue @@ -37,6 +37,10 @@ <script> import { translate as t } from '@nextcloud/l10n' import { NcSelect, NcTextField } from '@nextcloud/vue' +import { + NULLABLE_OBJECT_PROP, + objectProp, +} from '../../../constants/propDefinitions.js' const DEFAULT_CONTENT = Object.freeze({ location: '', @@ -66,20 +70,14 @@ export default { * * @type {{content: object}|null} */ - editingWidget: { - type: Object, - default: null, - }, + editingWidget: NULLABLE_OBJECT_PROP, /** * Initial content values — used when not editing. * * @type {object} */ - value: { - type: Object, - default: () => ({ ...DEFAULT_CONTENT }), - }, + value: objectProp(DEFAULT_CONTENT), }, emits: ['update:content'], diff --git a/src/components/Widgets/Renderers/WikiPagesWidget.vue b/src/components/Widgets/Renderers/WikiPagesWidget.vue new file mode 100644 index 000000000..1a337b7a3 --- /dev/null +++ b/src/components/Widgets/Renderers/WikiPagesWidget.vue @@ -0,0 +1,314 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="wiki-pages-widget" data-testid="wiki-pages-widget"> + <p + v-if="state === 'not-connected' || state === 'unavailable'" + class="wiki-pages-widget__state" + data-testid="wiki-pages-not-connected"> + {{ state === 'not-connected' + ? t('launchpad', 'The wiki is not connected yet. Ask your administrator to connect XWiki.') + : t('launchpad', 'The wiki needs OpenRegister. Ask your administrator to enable it.') }} + </p> + + <template v-else> + <NcTextField + :modelValue="query" + :label="t('launchpad', 'Search the wiki')" + type="search" + :showTrailingButton="query !== ''" + trailingButtonIcon="close" + data-testid="wiki-pages-search" + @update:modelValue="onQuery" + @trailingButtonClick="onQuery('')" /> + + <section + v-for="section in sections" + :key="section.key" + class="wiki-pages-widget__section" + :data-testid="`wiki-pages-${section.key}`"> + <h3 class="wiki-pages-widget__heading"> + {{ section.title }} + </h3> + <CnStatusList + :items="items(section.pages)" + :loading="section.loading" + :emptyLabel="section.emptyLabel"> + <template #actions="{ item }"> + <NcButton + variant="tertiary" + :aria-label="favouriteLabel(item)" + :pressed="isFavourite(item.id)" + @click="toggleFavourite(item.id)"> + <template #icon> + <Star v-if="isFavourite(item.id)" :size="18" /> + <StarOutline v-else :size="18" /> + </template> + </NcButton> + </template> + </CnStatusList> + </section> + </template> + </div> +</template> + +<script> +import { CnStatusList } from '@conduction/nextcloud-vue' +import { translate as t } from '@nextcloud/l10n' +import { NcButton, NcTextField } from '@nextcloud/vue' +import Star from 'vue-material-design-icons/Star.vue' +import StarOutline from 'vue-material-design-icons/StarOutline.vue' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { readWikiFavourites, saveWikiFavourites, searchWikiPages } from '../../../services/wikiPages.js' +import { logger } from '../../../utils/logger.js' + +/** How long the search waits after the last key before it asks the wiki. */ +const SEARCH_DELAY_MS = 300 + +/** + * WikiPagesWidget: the `wiki-pages` widget (board LpWerkplek "Wiki"). A + * search field over the wiki, the person's favourite pages and the most + * recent pages, each a link into the wiki. The pages come from + * OpenRegister's XWiki integration, so the wiki's address and credentials + * stay on the server; the favourites are the person's own. + * + * `content`: `{ space, limit }`. `space` keeps only the pages of one + * wiki space ("Vergunningen"); `limit` is how many favourites and recent + * pages show (default 3). + * + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md + */ +export default { + name: 'WikiPagesWidget', + + components: { CnStatusList, NcButton, NcTextField, Star, StarOutline }, + + props: { + /** Persisted widget content: `{ space, limit }`. */ + content: OBJECT_PROP, + + /** The placement row; declared so it does not fall through as an attribute. */ + // eslint-disable-next-line vue/no-unused-properties + placement: OBJECT_PROP, + }, + + data() { + return { + state: 'loading', + recent: [], + favourites: [], + query: '', + results: [], + searching: false, + searchTimer: null, + } + }, + + computed: { + /** + * The lists the widget shows: the search results while a search runs, + * else the favourites and the recent pages. + * + * @return {Array<{key: string, title: string, pages: Array<object>, loading: boolean, emptyLabel: string}>} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-wiki-widget-shows-favourites-recent-pages-and-search-req-wiki-001 + */ + sections() { + if (this.query.trim() !== '') { + return [{ key: 'results', title: t('launchpad', 'Search results'), pages: this.results, loading: this.searching, emptyLabel: t('launchpad', 'No page matches your search') }] + } + return [ + { key: 'favourites', title: t('launchpad', 'Favourites'), pages: this.shownFavourites, loading: false, emptyLabel: t('launchpad', 'Star a page to keep it here') }, + { key: 'recent', title: t('launchpad', 'Recent'), pages: this.recent, loading: this.state === 'loading', emptyLabel: t('launchpad', 'No pages yet') }, + ] + }, + + /** + * @return {number} How many favourites and recent pages show. + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-team-wiki-shows-one-space-req-wiki-003 + */ + limit() { + const limit = Number(this.content?.limit) + return Number.isInteger(limit) && limit > 0 ? Math.min(limit, 20) : 3 + }, + + /** + * @return {string} The one space to show, '' for every space. + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-team-wiki-shows-one-space-req-wiki-003 + */ + space() { + return String(this.content?.space || '').trim() + }, + + /** + * @return {Array<object>} The favourites in this widget's space, at most `limit`. + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-person-keeps-favourite-pages-req-wiki-002 + */ + shownFavourites() { + return this.inSpace(this.favourites).slice(0, this.limit) + }, + }, + + /** @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-wiki-widget-shows-favourites-recent-pages-and-search-req-wiki-001 */ + async created() { + const [recent, favourites] = await Promise.all([ + searchWikiPages('', this.space ? 50 : this.limit), + readWikiFavourites(), + ]) + this.favourites = favourites + this.recent = this.inSpace(recent.pages).slice(0, this.limit) + this.state = recent.state + }, + + beforeUnmount() { + clearTimeout(this.searchTimer) + }, + + methods: { + t, + + /** + * The pages of this widget's space; every page without one. + * + * @param {Array<object>} pages The pages. + * @return {Array<object>} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-team-wiki-shows-one-space-req-wiki-003 + */ + inSpace(pages) { + return this.space === '' ? pages : pages.filter((page) => page.space === this.space) + }, + + /** + * Pages as list items: a link into the wiki, opening in a new tab, with the space as detail. + * + * @param {Array<object>} pages The pages. + * @return {Array<object>} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-wiki-widget-shows-favourites-recent-pages-and-search-req-wiki-001 + */ + items(pages) { + return pages.map((page) => ({ + id: page.reference, + title: page.title, + href: page.url, + external: true, + meta: page.space, + })) + }, + + /** + * Search the wiki once typing pauses. + * + * @param {string} value The search text. + * @return {void} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-wiki-widget-shows-favourites-recent-pages-and-search-req-wiki-001 + */ + onQuery(value) { + this.query = String(value ?? '') + clearTimeout(this.searchTimer) + if (this.query.trim() === '') { + this.results = [] + this.searching = false + return + } + this.searching = true + this.searchTimer = setTimeout(() => this.search(this.query.trim()), SEARCH_DELAY_MS) + }, + + /** + * Ask the wiki for pages matching a query; a later query wins. + * + * @param {string} query The search text. + * @return {Promise<void>} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-wiki-widget-shows-favourites-recent-pages-and-search-req-wiki-001 + */ + async search(query) { + const found = await searchWikiPages(query, 10) + if (this.query.trim() !== query) { + return + } + this.results = this.inSpace(found.pages) + this.searching = false + }, + + /** + * @param {string} reference The page reference. + * @return {boolean} Whether the page is a favourite. + */ + isFavourite(reference) { + return this.favourites.some((page) => page.reference === reference) + }, + + /** + * The star button's name for a page. + * + * @param {{id: string, title: string}} item The list item. + * @return {string} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-person-keeps-favourite-pages-req-wiki-002 + */ + favouriteLabel(item) { + return this.isFavourite(item.id) + ? t('launchpad', 'Remove {title} from favourites', { title: item.title }) + : t('launchpad', 'Add {title} to favourites', { title: item.title }) + }, + + /** + * Star or unstar a page; a new favourite comes first. + * + * @param {string} reference The page reference. + * @return {Promise<void>} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-person-keeps-favourite-pages-req-wiki-002 + */ + async toggleFavourite(reference) { + const before = this.favourites + if (this.isFavourite(reference)) { + this.favourites = before.filter((page) => page.reference !== reference) + } else { + const page = [...this.results, ...this.recent].find((entry) => entry.reference === reference) + if (!page) { + return + } + this.favourites = [page, ...before] + } + try { + this.favourites = await saveWikiFavourites(this.favourites) + } catch (error) { + logger.error('The wiki favourites could not be saved', { error }) + this.favourites = before + } + }, + }, +} +</script> + +<style scoped> +.wiki-pages-widget { + display: flex; + flex-direction: column; + gap: 12px; + height: 100%; + min-height: 0; + overflow-y: auto; +} + +.wiki-pages-widget__section { + display: flex; + flex-direction: column; + gap: 4px; +} + +.wiki-pages-widget__heading { + margin: 0; + color: var(--color-text-maxcontrast); + font-size: var(--font-size-small, 13px); + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.wiki-pages-widget__state { + margin: 0; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/WikiPagesWidgetForm.vue b/src/components/Widgets/Renderers/WikiPagesWidgetForm.vue new file mode 100644 index 000000000..2b6839035 --- /dev/null +++ b/src/components/Widgets/Renderers/WikiPagesWidgetForm.vue @@ -0,0 +1,112 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="wiki-pages-widget-form"> + <NcTextField + :modelValue="String(limit)" + type="number" + min="1" + max="20" + :label="t('launchpad', 'Pages per list')" + data-testid="wiki-pages-form-limit" + @update:modelValue="update({ limit: Number($event) })" /> + <NcTextField + :modelValue="space" + :label="t('launchpad', 'Wiki space')" + :helperText="t('launchpad', 'Leave empty to show every space.')" + data-testid="wiki-pages-form-space" + @update:modelValue="update({ space: String($event) })" /> + + <p class="wiki-pages-widget-form__hint"> + {{ t('launchpad', 'Shows search, favourites and recent pages from XWiki, through the connection your administrator set up.') }} + </p> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcTextField } from '@nextcloud/vue' +import { NULLABLE_OBJECT_PROP, objectProp } from '../../../constants/propDefinitions.js' + +/** + * WikiPagesWidgetForm: which wiki space the `wiki-pages` widget shows and + * how many favourites and recent pages it lists. + * + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-team-wiki-shows-one-space-req-wiki-003 + */ +export default { + name: 'WikiPagesWidgetForm', + + components: { NcTextField }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** + * Initial content values, used when not editing. + * + * @type {object} + */ + value: objectProp({ space: '', limit: 3 }), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + space: String(initial.space || ''), + limit: Number.isInteger(initial.limit) && initial.limit > 0 ? initial.limit : 3, + } + }, + + methods: { + t, + + /** + * Keep a change and tell the modal the whole content. + * + * @param {object} change The changed keys. + * @return {void} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-team-wiki-shows-one-space-req-wiki-003 + */ + update(change) { + Object.assign(this, change) + this.$emit('update:content', { space: this.space.trim(), limit: this.limit }) + }, + + /** + * Validate the form: the list length is 1 to 20. + * + * @return {string[]} The validation errors. + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-team-wiki-shows-one-space-req-wiki-003 + */ + validate() { + return Number.isInteger(this.limit) && this.limit >= 1 && this.limit <= 20 + ? [] + : [t('launchpad', 'Show 1 to 20 pages per list')] + }, + }, +} +</script> + +<style scoped> +.wiki-pages-widget-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.wiki-pages-widget-form__hint { + margin: 0; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/WorkPackagesWidget.vue b/src/components/Widgets/Renderers/WorkPackagesWidget.vue new file mode 100644 index 000000000..3e101d4f3 --- /dev/null +++ b/src/components/Widgets/Renderers/WorkPackagesWidget.vue @@ -0,0 +1,129 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="work-packages-widget" data-testid="work-packages-widget"> + <p v-if="state === 'not-installed'" class="work-packages-widget__state" data-testid="work-packages-not-installed"> + {{ t('launchpad', 'Work packages need the OpenProject integration. Ask your administrator to enable it.') }} + </p> + <p v-else-if="state === 'not-connected'" class="work-packages-widget__state" data-testid="work-packages-not-connected"> + {{ t('launchpad', 'Connect your OpenProject account to see your work packages.') }} + <a :href="connectUrl" class="work-packages-widget__connect">{{ t('launchpad', 'Connect OpenProject') }}</a> + </p> + <CnStatusList + v-else + :items="items" + :loading="state === 'loading'" + :error="state === 'error' ? t('launchpad', 'The work packages could not be loaded. Try again later.') : ''" + :emptyLabel="scope === 'project' ? t('launchpad', 'This project has no open work packages') : t('launchpad', 'You have no open work packages')" /> + </div> +</template> + +<script> +import { CnStatusList } from '@conduction/nextcloud-vue' +import { translate as t } from '@nextcloud/l10n' +import { OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { loadWorkPackages } from '../../../services/workPackages.js' + +/** + * WorkPackagesWidget: the `work-packages` widget (board LpWerkplek "Mijn + * werkpakketten", LpAfdeling "Werkpakketten van het team"). The open + * OpenProject work packages, due date first, each a link into OpenProject + * with its status, project and due date. They are read through the official + * OpenProject integration with the person's own token. + * + * `content`: `{ scope, project, limit }`. `scope` `mine` (default) lists the + * person's own; `project` lists every open one of `project`. `limit` defaults to 4. + * + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md + */ +export default { + name: 'WorkPackagesWidget', + + components: { CnStatusList }, + + props: { + /** + * The placement row, which the widget does not read; declared so the + * binding every renderer gets does not fall through as an attribute. + */ + // eslint-disable-next-line vue/no-unused-properties + placement: OBJECT_PROP, + + /** Persisted widget content: `{ scope, project, limit }`. */ + content: OBJECT_PROP, + }, + + data() { + return { state: 'loading', workPackages: [], connectUrl: '' } + }, + + computed: { + /** + * @return {string} `mine` or `project`. + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-a-team-page-lists-one-projects-work-packages-req-wp-003 + */ + scope() { + return this.content?.scope === 'project' ? 'project' : 'mine' + }, + + /** + * The work packages as list items: subject as a link, project (and the + * assignee on a project list) as detail, the due date and the status. + * + * @return {Array<object>} + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-the-widget-lists-open-work-packages-due-date-first-req-wp-001 + */ + items() { + return this.workPackages.map((workPackage) => ({ + id: String(workPackage.id), + title: workPackage.subject || `#${workPackage.id}`, + href: workPackage.url, + external: true, + meta: this.scope === 'project' && workPackage.assignee + ? `${workPackage.project} · ${workPackage.assignee}` + : workPackage.project, + due: workPackage.dueDate, + status: workPackage.status ? { label: workPackage.status, variant: 'info' } : null, + })) + }, + }, + + /** @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-the-widget-lists-open-work-packages-due-date-first-req-wp-001 */ + async created() { + const limit = Number(this.content?.limit) + const result = await loadWorkPackages({ + scope: this.scope, + project: String(this.content?.project || ''), + limit: Number.isInteger(limit) && limit > 0 ? limit : 4, + }) + this.workPackages = result.workPackages + this.connectUrl = result.connectUrl + this.state = result.state + }, + + methods: { t }, +} +</script> + +<style scoped> +.work-packages-widget { + height: 100%; + min-height: 0; + overflow-y: auto; +} + +.work-packages-widget__state { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.work-packages-widget__connect { + display: block; + margin-top: 8px; + color: var(--color-primary-element); + text-decoration: underline; +} +</style> diff --git a/src/components/Widgets/Renderers/WorkPackagesWidgetForm.vue b/src/components/Widgets/Renderers/WorkPackagesWidgetForm.vue new file mode 100644 index 000000000..05220be6d --- /dev/null +++ b/src/components/Widgets/Renderers/WorkPackagesWidgetForm.vue @@ -0,0 +1,148 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="work-packages-widget-form"> + <p class="work-packages-widget-form__hint"> + {{ t('launchpad', 'Shows open OpenProject work packages, due date first. Each person sees what OpenProject lets them see.') }} + </p> + + <fieldset class="work-packages-widget-form__scope"> + <legend>{{ t('launchpad', 'Which work packages') }}</legend> + <NcCheckboxRadioSwitch + :modelValue="scope" + value="mine" + name="work-packages-scope" + type="radio" + data-testid="work-packages-form-scope-mine" + @update:modelValue="update({ scope: 'mine' })"> + {{ t('launchpad', 'Assigned to the person viewing') }} + </NcCheckboxRadioSwitch> + <NcCheckboxRadioSwitch + :modelValue="scope" + value="project" + name="work-packages-scope" + type="radio" + data-testid="work-packages-form-scope-project" + @update:modelValue="update({ scope: 'project' })"> + {{ t('launchpad', 'Everyone in one project') }} + </NcCheckboxRadioSwitch> + </fieldset> + + <NcTextField + v-if="scope === 'project'" + :modelValue="project" + :label="t('launchpad', 'Project identifier')" + :helperText="t('launchpad', 'The identifier in the project address, such as havenpark.')" + data-testid="work-packages-form-project" + @update:modelValue="update({ project: String($event) })" /> + + <NcTextField + :modelValue="String(limit)" + type="number" + min="1" + max="25" + :label="t('launchpad', 'Number of work packages')" + data-testid="work-packages-form-limit" + @update:modelValue="update({ limit: Number($event) })" /> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcCheckboxRadioSwitch, NcTextField } from '@nextcloud/vue' +import { NULLABLE_OBJECT_PROP, objectProp } from '../../../constants/propDefinitions.js' + +/** + * WorkPackagesWidgetForm: whether the `work-packages` widget lists the + * viewer's own work packages or one project's, and how many. + * + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-a-team-page-lists-one-projects-work-packages-req-wp-003 + */ +export default { + name: 'WorkPackagesWidgetForm', + + components: { NcCheckboxRadioSwitch, NcTextField }, + + props: { + /** + * The placement being edited, or `null` in create mode. + * + * @type {{content: object}|null} + */ + editingWidget: NULLABLE_OBJECT_PROP, + + /** + * Initial content values, used when not editing. + * + * @type {object} + */ + value: objectProp({ scope: 'mine', project: '', limit: 4 }), + }, + + emits: ['update:content'], + + data() { + const initial = this.editingWidget?.content || this.value || {} + return { + scope: initial.scope === 'project' ? 'project' : 'mine', + project: String(initial.project || ''), + limit: Number.isInteger(initial.limit) && initial.limit > 0 ? initial.limit : 4, + } + }, + + methods: { + t, + + /** + * Keep a change and tell the modal the whole content. + * + * @param {object} change The changed keys. + * @return {void} + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-a-team-page-lists-one-projects-work-packages-req-wp-003 + */ + update(change) { + Object.assign(this, change) + this.$emit('update:content', { scope: this.scope, project: this.project.trim(), limit: this.limit }) + }, + + /** + * Validate: a project list names its project, and the number is 1 to 25. + * + * @return {string[]} The validation errors. + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-a-team-page-lists-one-projects-work-packages-req-wp-003 + */ + validate() { + const errors = [] + if (this.scope === 'project' && this.project.trim() === '') { + errors.push(t('launchpad', 'Name the project')) + } + if (!Number.isInteger(this.limit) || this.limit < 1 || this.limit > 25) { + errors.push(t('launchpad', 'Show 1 to 25 work packages')) + } + return errors + }, + }, +} +</script> + +<style scoped> +.work-packages-widget-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.work-packages-widget-form__scope { + margin: 0; + padding: 0; + border: 0; +} + +.work-packages-widget-form__hint { + margin: 0; + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Widgets/Renderers/__tests__/ActivityReportWidget.spec.js b/src/components/Widgets/Renderers/__tests__/ActivityReportWidget.spec.js new file mode 100644 index 000000000..160df57a4 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ActivityReportWidget.spec.js @@ -0,0 +1,156 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ActivityReportWidget: the purpose on a report about a named person, the + * refusal said in words, counts and a calendar from the server's figures + * (openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them REQ-DWMS-005/006). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const interpolate = (text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`) +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => interpolate(text, vars), + translatePlural: (_app, one, many, count, vars = {}) => interpolate(count === 1 ? one : many, vars), +})) +vi.mock('@nextcloud/vue', () => ({ + NcTextField: { name: 'NcTextField', props: ['modelValue', 'label', 'type'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)">' }, + NcButton: { name: 'NcButton', template: '<button type="submit"><slot /></button>' }, +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const loadActivityReport = vi.fn() +vi.mock('../../../../services/activityReport.js', () => ({ + loadActivityReport: (...args) => loadActivityReport(...args), + activityReportCsvUrl: ({ user, from, to }) => `/csv?user=${user}&from=${from}&to=${to}`, +})) + +import ActivityReportWidget from '../ActivityReportWidget.vue' + + +function report(overrides = {}) { + return { + refused: false, + subject: 'alice', + self: false, + from: '2026-09-01', + to: '2026-09-05', + purpose: 'workload balancing', + available: true, + counts: { dashboard_updated: 3, file_changed: 1 }, + days: { '2026-09-02': 1, '2026-09-04': 3 }, + total: 4, + ...overrides, + } +} + +async function mountWith(result, content = {}) { + loadActivityReport.mockResolvedValue(result) + const wrapper = mount(ActivityReportWidget, { props: { content } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + loadActivityReport.mockReset() +}) + +describe('ActivityReportWidget', () => { + it('shows the purpose on a report about a named person', async () => { + const wrapper = await mountWith(report()) + + expect(wrapper.find('[data-testid="activity-report-purpose"]').text()).toContain('workload balancing') + expect(wrapper.find('[data-testid="activity-report-summary"]').text()).toBe('Activity of alice from 2026-09-01 to 2026-09-05: 4 actions') + }) + + it('shows no purpose block on your own report when none was recorded', async () => { + const wrapper = await mountWith(report({ self: true, purpose: null })) + + expect(wrapper.find('[data-testid="activity-report-purpose"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="activity-report-summary"]').text()).toBe('Your activity from 2026-09-01 to 2026-09-05: 4 actions') + }) + + it('lists the counts per type and the server total', async () => { + const wrapper = await mountWith(report()) + + const rows = wrapper.findAll('[data-testid="activity-report-counts"] tbody tr') + expect(rows.map((row) => row.text())).toEqual(['dashboard updated3', 'file changed1']) + expect(wrapper.find('[data-testid="activity-report-total"]').text()).toBe('4') + }) + + it('draws one cell per day, an empty day at level 0 and the busiest at level 4', async () => { + const wrapper = await mountWith(report()) + + const cells = wrapper.findAll('[data-testid="activity-report-calendar"] li') + expect(cells).toHaveLength(5) + expect(wrapper.find('[data-testid="activity-report-day-2026-09-01"]').classes()).toContain('activity-report__day--level-0') + expect(wrapper.find('[data-testid="activity-report-day-2026-09-02"]').classes()).toContain('activity-report__day--level-2') + expect(wrapper.find('[data-testid="activity-report-day-2026-09-04"]').classes()).toContain('activity-report__day--level-4') + expect(wrapper.find('[data-testid="activity-report-day-2026-09-04"]').attributes('aria-label')).toBe('2026-09-04: 3 actions') + }) + + it('links the CSV of the report as shown', async () => { + const wrapper = await mountWith(report()) + + expect(wrapper.find('[data-testid="activity-report-export"]').attributes('href')).toBe('/csv?user=alice&from=2026-09-01&to=2026-09-05') + }) + + it('says the capability is off and how to turn it on when the server refuses for that', async () => { + const wrapper = await mountWith({ refused: true, status: 403, message: 'off', enabled: false }) + + const text = wrapper.find('[data-testid="activity-report-refused"]').text() + expect(text).toContain('Activity reporting on named people is off.') + expect(text).toContain('An administrator can turn it on in the LaunchPad admin settings') + expect(wrapper.find('[data-testid="activity-report-counts"]').exists()).toBe(false) + }) + + it('says only an administrator may read another person when it is on', async () => { + const wrapper = await mountWith({ refused: true, status: 403, message: 'no', enabled: true }) + + expect(wrapper.find('[data-testid="activity-report-refused"]').text()).toBe('Only an administrator can read another person\'s activity. You can always see your own.') + }) + + it('says what is wrong with a refused period', async () => { + const wrapper = await mountWith({ refused: true, status: 400, message: 'bad', enabled: true }) + + expect(wrapper.find('[data-testid="activity-report-refused"]').text()).toContain('at most 366 days apart') + }) + + it('says the Activity app is needed when the server cannot read events', async () => { + const wrapper = await mountWith(report({ available: false, counts: {}, days: {}, total: 0 })) + + expect(wrapper.find('[data-testid="activity-report-unavailable"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="activity-report-calendar"]').exists()).toBe(false) + }) + + it('asks for yourself over the configured number of days, ending today', async () => { + await mountWith(report(), { days: 7 }) + + const request = loadActivityReport.mock.calls[0][0] + expect(request.user).toBe('') + const span = (Date.parse(request.to) - Date.parse(request.from)) / 86400000 + expect(span).toBe(6) + }) + + it('asks again for the person typed in', async () => { + const wrapper = await mountWith(report()) + loadActivityReport.mockResolvedValue(report({ subject: 'bob' })) + + await wrapper.find('[data-testid="activity-report-user"]').setValue('bob') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(loadActivityReport).toHaveBeenLastCalledWith(expect.objectContaining({ user: 'bob' })) + expect(wrapper.find('[data-testid="activity-report-summary"]').text()).toContain('Activity of bob') + }) + + it('says so when the report cannot be loaded', async () => { + loadActivityReport.mockRejectedValue(new Error('down')) + const wrapper = mount(ActivityReportWidget, { props: { content: {} } }) + await flushPromises() + + expect(wrapper.find('[data-testid="activity-report-error"]').exists()).toBe(true) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ActivityReportWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/ActivityReportWidgetForm.spec.js new file mode 100644 index 000000000..35e8275fc --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ActivityReportWidgetForm.spec.js @@ -0,0 +1,50 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ActivityReportWidgetForm: the period the report opens on (REQ-DWMS-006), + * in the protocol the add-widget modal speaks. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) +vi.mock('@nextcloud/vue', () => ({ + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel', 'clearable'], + emits: ['update:modelValue'], + template: + '<div class="select-stub" :data-label="inputLabel" :data-value="modelValue" />', + }, +})) + +import ActivityReportWidgetForm from '../ActivityReportWidgetForm.vue' + +describe('ActivityReportWidgetForm', () => { + it('starts at thirty days, with a labelled select', () => { + const selects = mount(ActivityReportWidgetForm).findAll('.select-stub') + + expect(selects.map((s) => s.attributes('data-label'))).toEqual(['Days shown at first']) + expect(selects.map((s) => s.attributes('data-value'))).toEqual(['30']) + }) + + it('opens on the widget being edited, and replaces a value it does not offer', () => { + expect(mount(ActivityReportWidgetForm, { props: { editingWidget: { content: { days: 90 } } } }) + .find('.select-stub').attributes('data-value')).toBe('90') + expect(mount(ActivityReportWidgetForm, { props: { editingWidget: { content: { days: 12 } } } }) + .find('.select-stub').attributes('data-value')).toBe('30') + }) + + it('emits the chosen period, falling back for one it does not offer', async () => { + const wrapper = mount(ActivityReportWidgetForm) + const select = wrapper.findComponent({ name: 'NcSelect' }) + + await select.vm.$emit('update:modelValue', 365) + await select.vm.$emit('update:modelValue', 999) + + expect(wrapper.emitted('update:content')).toEqual([[{ days: 365 }], [{ days: 30 }]]) + expect(wrapper.vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/AiAssistantWidget.guards.spec.js b/src/components/Widgets/Renderers/__tests__/AiAssistantWidget.guards.spec.js new file mode 100644 index 000000000..9ee523dc3 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/AiAssistantWidget.guards.spec.js @@ -0,0 +1,155 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * AiAssistantWidget guards (launchpad-ai-dashboard-assistant): outside the + * workspace page the chat context carries no dashboard uuid; a blank + * question or an unavailable Hermiq never reaches the chat; a failing send + * leaves the error on screen instead of throwing. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { reactive } from 'vue' +import AiAssistantWidget from '../AiAssistantWidget.vue' + +const state = vi.hoisted(() => ({ storeThrows: false, sendError: null })) +const created = [] +vi.mock('@conduction/nextcloud-vue', () => ({ + chatHealthUrl: (appId) => `/index.php/apps/${appId}/api/chat/health`, + useAiChatStream: (instance, options) => { + // The composable's real shape: reactive `state` beside the methods. + const chat = { + state: reactive({ + messages: [], + isStreaming: false, + currentText: '', + error: null, + }), + options, + } + chat.send = vi.fn(async () => { + if (state.sendError) { + chat.state.error = state.sendError + throw state.sendError + } + }) + created.push(chat) + return chat + }, +})) +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) +vi.mock('../../../../stores/dashboard.js', () => ({ + useDashboardStore: () => { + if (state.storeThrows) { + throw new Error('no active pinia') + } + return { activeDashboard: { uuid: 'team' } } + }, +})) + +const big = { id: 1, gridWidth: 4, gridHeight: 4 } +const small = { id: 2, gridWidth: 2, gridHeight: 2 } + +beforeEach(() => { + vi.clearAllMocks() + created.length = 0 + state.storeThrows = false + state.sendError = null +}) + +describe('AiAssistantWidget guards', () => { + it('sends a null dashboard uuid when the dashboard store is unavailable', async () => { + state.storeThrows = true + axios.get.mockResolvedValue({ status: 200, data: {} }) + mount(AiAssistantWidget, { props: { content: {}, placement: big } }) + await flushPromises() + expect(created[0].options.context.objectUuid).toBeNull() + expect(created[0].options.context.appId).toBe('launchpad') + }) + + it('does not send a whitespace-only question', async () => { + axios.get.mockResolvedValue({ status: 200, data: {} }) + const wrapper = mount(AiAssistantWidget, { + props: { content: {}, placement: big }, + }) + await flushPromises() + const input = wrapper.find('[data-testid="ai-assistant-input"]') + await input.setValue(' ') + expect( + wrapper.find('[data-testid="ai-assistant-send"]').attributes('disabled'), + ).toBeDefined() + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(created[0].send).not.toHaveBeenCalled() + expect(input.element.value).toBe(' ') + }) + + it('does not send a question while the health probe is still pending', async () => { + axios.get.mockReturnValue(new Promise(() => {})) + const wrapper = mount(AiAssistantWidget, { + props: { content: {}, placement: big }, + }) + await flushPromises() + const input = wrapper.find('[data-testid="ai-assistant-input"]') + expect(input.attributes('disabled')).toBeDefined() + // v-model still writes through the disabled input's value. + await input.setValue('Anything overdue?') + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(created[0].send).not.toHaveBeenCalled() + }) + + it('does not summarise before Hermiq has answered the health probe', async () => { + axios.get.mockReturnValue(new Promise(() => {})) + const wrapper = mount(AiAssistantWidget, { + props: { content: {}, placement: small }, + }) + await flushPromises() + const button = wrapper.find('[data-testid="ai-assistant-summarise"]') + expect(button.attributes('disabled')).toBeDefined() + await wrapper.vm.summarise() + expect(created[0].send).not.toHaveBeenCalled() + }) + + it('shows the chat error when sending a question fails', async () => { + state.sendError = new Error('Hermiq timed out') + axios.get.mockResolvedValue({ status: 200, data: {} }) + const wrapper = mount(AiAssistantWidget, { + props: { content: { agentUuid: 'a-9' }, placement: big }, + }) + await flushPromises() + await wrapper + .find('[data-testid="ai-assistant-input"]') + .setValue(' Status? ') + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(created[0].send).toHaveBeenCalledWith('Status?', { agentUuid: 'a-9' }) + expect(wrapper.find('[data-testid="ai-assistant-error"]').text()).toBe( + 'Hermiq timed out', + ) + expect( + wrapper.find('[data-testid="ai-assistant-input"]').element.value, + ).toBe('') + }) + + it('shows the chat error when the summary request fails', async () => { + state.sendError = new Error('No agent') + axios.get.mockResolvedValue({ status: 200, data: {} }) + const wrapper = mount(AiAssistantWidget, { + props: { content: {}, placement: small }, + }) + await flushPromises() + await wrapper.find('[data-testid="ai-assistant-summarise"]').trigger('click') + await flushPromises() + expect(created[0].send).toHaveBeenCalledWith( + 'Summarise this dashboard for me.', + { agentUuid: '' }, + ) + expect(wrapper.find('[data-testid="ai-assistant-error"]').text()).toBe( + 'No agent', + ) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/AiAssistantWidget.spec.js b/src/components/Widgets/Renderers/__tests__/AiAssistantWidget.spec.js index e2e20d0d8..77cad0283 100644 --- a/src/components/Widgets/Renderers/__tests__/AiAssistantWidget.spec.js +++ b/src/components/Widgets/Renderers/__tests__/AiAssistantWidget.spec.js @@ -18,15 +18,18 @@ const created = [] vi.mock('@conduction/nextcloud-vue', () => ({ chatHealthUrl: (appId) => `/index.php/apps/${appId}/api/chat/health`, useAiChatStream: (instance, options) => { - const chat = reactive({ - messages: [], - isStreaming: false, - currentText: '', - error: null, + // The composable's real shape: reactive `state` beside the methods. + const chat = { + state: reactive({ + messages: [], + isStreaming: false, + currentText: '', + error: null, + }), options, - }) + } chat.send = vi.fn(async (content) => { - chat.messages.push( + chat.state.messages.push( { role: 'user', content }, { role: 'assistant', content: 'Two cases are overdue.' }, ) diff --git a/src/components/Widgets/Renderers/__tests__/AiAssistantWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/AiAssistantWidgetForm.spec.js new file mode 100644 index 000000000..caa8223da --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/AiAssistantWidgetForm.spec.js @@ -0,0 +1,85 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `AiAssistantWidgetForm.vue`: the optional Hermiq + * agent field seeds from the widget being edited (falling back to the + * `value` prop), emits a trimmed `{agentUuid}` on input, and validate() + * never reports errors because nothing is required. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import AiAssistantWidgetForm from '../AiAssistantWidgetForm.vue' + +describe('AiAssistantWidgetForm — initial state', () => { + it('prefers the edited widget content over the value prop', () => { + const wrapper = mount(AiAssistantWidgetForm, { + props: { + editingWidget: { content: { agentUuid: 'agent-from-widget' } }, + value: { agentUuid: 'agent-from-value' }, + }, + }) + expect(wrapper.vm.agentUuid).toBe('agent-from-widget') + expect(wrapper.find('[data-testid="ai-assistant-agent"]').element.value).toBe('agent-from-widget') + }) + + it('falls back to the value prop when no widget is being edited', () => { + const wrapper = mount(AiAssistantWidgetForm, { + props: { value: { agentUuid: 'agent-from-value' } }, + }) + expect(wrapper.vm.agentUuid).toBe('agent-from-value') + }) + + it('falls back to the value prop when the edited widget has no content', () => { + const wrapper = mount(AiAssistantWidgetForm, { + props: { editingWidget: { id: 4 }, value: { agentUuid: 'v' } }, + }) + expect(wrapper.vm.agentUuid).toBe('v') + }) + + it('starts empty when the content carries no agentUuid', () => { + const wrapper = mount(AiAssistantWidgetForm, { + props: { editingWidget: { content: { other: 1 } } }, + }) + expect(wrapper.vm.agentUuid).toBe('') + }) + + it('starts empty with the default value prop', () => { + const wrapper = mount(AiAssistantWidgetForm) + expect(wrapper.vm.agentUuid).toBe('') + }) +}) + +describe('AiAssistantWidgetForm — emitted content', () => { + it('emits the trimmed agent uuid when the field is typed in', async () => { + const wrapper = mount(AiAssistantWidgetForm) + await wrapper.find('[data-testid="ai-assistant-agent"]').setValue(' abc-123 ') + const emitted = wrapper.emitted('update:content') + expect(emitted).toBeTruthy() + expect(emitted[emitted.length - 1][0]).toEqual({ agentUuid: 'abc-123' }) + }) + + it('emits an empty uuid when the field is cleared to whitespace', async () => { + const wrapper = mount(AiAssistantWidgetForm, { + props: { value: { agentUuid: 'abc' } }, + }) + await wrapper.find('[data-testid="ai-assistant-agent"]').setValue(' ') + const emitted = wrapper.emitted('update:content') + expect(emitted[emitted.length - 1][0]).toEqual({ agentUuid: '' }) + }) + + it('does not emit before any input', () => { + const wrapper = mount(AiAssistantWidgetForm) + expect(wrapper.emitted('update:content')).toBeUndefined() + }) +}) + +describe('AiAssistantWidgetForm — validate()', () => { + it('reports no errors, whether or not an agent is set', () => { + expect(mount(AiAssistantWidgetForm).vm.validate()).toEqual([]) + expect(mount(AiAssistantWidgetForm, { + props: { value: { agentUuid: 'x' } }, + }).vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/AssignedCasesWidget.spec.js b/src/components/Widgets/Renderers/__tests__/AssignedCasesWidget.spec.js new file mode 100644 index 000000000..c566263b6 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/AssignedCasesWidget.spec.js @@ -0,0 +1,110 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * AssignedCasesWidget and its form (assigned-cases-widget REQ-CASES-001..004). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, + t: (_app, text) => text, + translatePlural: (_app, one, many, count) => (count === 1 ? one : many).replace('%n', String(count)), +})) +vi.mock('@nextcloud/auth', async (importOriginal) => ({ ...(await importOriginal()), getCurrentUser: () => ({ uid: 'pieter' }) })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path, params = {}) => `/index.php${path.replace(/\{(\w+)\}/g, (_m, key) => params[key])}`, +})) + +const loadAssignedCases = vi.fn() +vi.mock('../../../../services/assignedCases.js', () => ({ loadAssignedCases: (...args) => loadAssignedCases(...args) })) + +import AssignedCasesWidget from '../AssignedCasesWidget.vue' +import AssignedCasesWidgetForm from '../AssignedCasesWidgetForm.vue' + +const CnStatusList = { name: 'CnStatusList', props: ['items', 'counts', 'loading', 'error', 'emptyLabel'], template: '<div class="list" />' } + +const CASES = Array.from({ length: 6 }, (_, i) => ({ + id: `c${i}`, + title: `Zaak ${i}`, + identifier: `Z-2026-04${i}`, + deadline: '2026-10-05', + status: { key: 's1', label: 'In behandeling', variant: 'purple' }, +})) + +/** + * Mount the widget. + * + * @param {object} content The widget content. + * @param {object} integrationApps The apps enabled for the viewer. + * @return {Promise<object>} The wrapper. + */ +async function mountWidget(content = {}, integrationApps = { dossiq: 'dossiq' }) { + const wrapper = mount(AssignedCasesWidget, { + props: { content, placement: {} }, + global: { stubs: { CnStatusList }, provide: { integrationApps } }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + loadAssignedCases.mockReset().mockResolvedValue({ + state: 'ok', + cases: CASES, + counts: [{ key: 's1', label: 'In behandeling', variant: 'purple', count: 6 }], + total: 6, + }) +}) + +describe('AssignedCasesWidget', () => { + it('reads the viewer\'s cases from the dossiq register and lists the first four with deadline and status', async () => { + const wrapper = await mountWidget() + expect(loadAssignedCases).toHaveBeenCalledWith({ register: 'dossiq', schema: 'case', userId: 'pieter' }) + const list = wrapper.getComponent(CnStatusList) + expect(list.props('items')).toHaveLength(4) + expect(list.props('items')[0]).toEqual({ + id: 'c0', + title: 'Zaak 0', + href: '/index.php/apps/dossiq/cases/c0', + meta: 'Z-2026-040', + due: '2026-10-05', + status: { label: 'In behandeling', variant: 'purple' }, + }) + expect(list.props('counts')).toEqual([{ key: 's1', label: 'In behandeling', variant: 'purple', count: 6 }]) + expect(wrapper.get('[data-testid="assigned-cases-all"]').text()).toBe('All 6 open cases') + expect(wrapper.get('[data-testid="assigned-cases-all"]').attributes('href')).toBe('/index.php/apps/dossiq/cases') + }) + + it('links into the case app under the id it is installed as', async () => { + const wrapper = await mountWidget({ limit: 1 }, { dossiq: 'procest' }) + expect(wrapper.getComponent(CnStatusList).props('items')[0].href).toBe('/index.php/apps/procest/cases/c0') + }) + + it('reads nothing without dossiq', async () => { + const wrapper = await mountWidget({}, { dossiq: false }) + expect(loadAssignedCases).not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="assigned-cases-no-app"]').exists()).toBe(true) + }) + + it('shows the error without counts when reading fails', async () => { + loadAssignedCases.mockResolvedValue({ state: 'error', cases: [], counts: [], total: 0 }) + const list = (await mountWidget()).getComponent(CnStatusList) + expect(list.props('error')).toBe('The cases could not be loaded. Try again later.') + expect(list.props('counts')).toEqual([]) + }) +}) + +describe('AssignedCasesWidgetForm', () => { + it('defaults to dossiq\'s register and needs a register, a schema and 1 to 20 cases', () => { + const wrapper = mount(AssignedCasesWidgetForm, { global: { stubs: { NcTextField: true } } }) + expect(wrapper.vm.validate()).toEqual([]) + wrapper.vm.update({ register: ' ', limit: 0 }) + expect(wrapper.vm.validate()).toEqual(['Name the register and the schema', 'Show 1 to 20 cases']) + expect(wrapper.emitted('update:content').at(-1)[0]).toEqual({ register: '', schema: 'case', limit: 0 }) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/AttentionWidget.spec.js b/src/components/Widgets/Renderers/__tests__/AttentionWidget.spec.js new file mode 100644 index 000000000..001ce89a5 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/AttentionWidget.spec.js @@ -0,0 +1,335 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * AttentionWidget: what the employee is told in each state + * (openspec/specs/attention-feed REQ-ATT-004, REQ-ATT-005). The feed's rules + * are attentionFeed.spec.js; here the feed is given and the screen is read. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), + translatePlural: (_app, one, many, count) => + (count === 1 ? one : many).replace('%n', String(count)), +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const loadAttentionFeed = vi.fn() +const expandToRecords = vi.fn((items) => items.map((i) => ({ ...i, key: i.key + '/r', title: 'Record of ' + i.title }))) +vi.mock('../../../../services/attentionFeed.js', () => ({ + loadAttentionFeed: (...args) => loadAttentionFeed(...args), + expandToRecords: (...args) => expandToRecords(...args), +})) + +import AttentionWidget from '../AttentionWidget.vue' + +function item(appId, appName, severity, count, overrides = {}) { + return { + key: `${appId}/x`, + id: 'x', + appId, + appName, + title: `${appName} title`, + severity, + count, + attention: true, + failed: false, + reason: `${count} things need you.`, + actionLabel: `Open ${appName}`, + href: `/index.php/apps/${appId}/list?assignee=@me`, + ...overrides, + } +} + +const CLEAR = 'Nothing needs your attention right now.' + +async function mountWith(feed, content = {}) { + loadAttentionFeed.mockResolvedValue(feed) + const wrapper = mount(AttentionWidget, { props: { content } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + loadAttentionFeed.mockReset() +}) + +describe('AttentionWidget', () => { + it('shows one line per item that needs attention', async () => { + const wrapper = await mountWith({ + items: [ + item('pipelinq', 'Pipelinq', 'error', 5), + item('dossiq', 'Dossiq', 'error', 3), + item('decidiq', 'Decidiq', 'warning', 2), + ], + failedApps: [], + sourceCount: 3, + }) + + const lines = wrapper.findAll('.attention-widget__item') + expect( + lines.map((line) => line.find('.attention-widget__app').text()), + ).toEqual(['Pipelinq', 'Dossiq', 'Decidiq']) + const dossiq = wrapper.find('[data-testid="attention-item-dossiq-x"]') + expect(dossiq.text()).toContain('Dossiq title') + expect(dossiq.text()).toContain('3 things need you.') + expect(dossiq.find('a').text()).toBe('Open Dossiq') + expect(dossiq.find('a').attributes('href')).toBe( + '/index.php/apps/dossiq/list?assignee=@me', + ) + expect(dossiq.classes()).toContain('attention-widget__item--error') + expect( + wrapper.find('[data-testid="attention-item-decidiq-x"]').classes(), + ).toContain('attention-widget__item--warning') + expect(wrapper.text()).not.toContain(CLEAR) + expect(wrapper.find('[data-testid="attention-failed"]').exists()).toBe(false) + }) + + it('says the severity in words, not by colour alone', async () => { + const wrapper = await mountWith({ + items: [ + item('a', 'A', 'error', 1), + item('b', 'B', 'warning', 1), + item('c', 'C', 'info', 1), + ], + failedApps: [], + sourceCount: 3, + }) + + expect( + wrapper.findAll('.attention-widget__sr').map((el) => el.text()), + ).toEqual(['Urgent:', 'Soon:', 'For your information:']) + }) + + it('leaves out a source that does not need attention', async () => { + // The feed only hands over what needs attention; the widget shows + // exactly that and does not invent a line for the rest. + const wrapper = await mountWith({ + items: [item('dossiq', 'Dossiq', 'error', 3)], + failedApps: [], + sourceCount: 2, + }) + + expect(wrapper.findAll('.attention-widget__item')).toHaveLength(1) + expect(wrapper.text()).not.toContain('Learniq') + }) + + it('says nothing needs attention only when every source was checked', async () => { + const wrapper = await mountWith({ + items: [], + failedApps: [], + sourceCount: 2, + }) + + expect(wrapper.find('[data-testid="attention-clear"]').text()).toBe(CLEAR) + expect(wrapper.find('[data-testid="attention-none"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="attention-failed"]').exists()).toBe(false) + }) + + it('a failed source is named and never reads as nothing to do', async () => { + const wrapper = await mountWith({ + items: [], + failedApps: ['Dossiq'], + sourceCount: 2, + }) + + expect(wrapper.find('[data-testid="attention-failed"]').text()).toBe( + 'Could not check: Dossiq', + ) + expect(wrapper.find('[data-testid="attention-clear"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="attention-none"]').exists()).toBe(false) + expect(wrapper.text()).not.toContain(CLEAR) + }) + + it('a failed source does not hide the others', async () => { + const wrapper = await mountWith({ + items: [item('pipelinq', 'Pipelinq', 'error', 5)], + failedApps: ['Dossiq', 'Learniq'], + sourceCount: 3, + }) + + expect( + wrapper.find('[data-testid="attention-item-pipelinq-x"]').exists(), + ).toBe(true) + expect(wrapper.find('[data-testid="attention-failed"]').text()).toBe( + 'Could not check: Dossiq, Learniq', + ) + expect(wrapper.text()).not.toContain(CLEAR) + }) + + it('says so when no app declares anything', async () => { + const wrapper = await mountWith({ + items: [], + failedApps: [], + sourceCount: 0, + }) + + expect(wrapper.find('[data-testid="attention-none"]').text()).toBe( + 'None of your apps reports attention items yet.', + ) + expect(wrapper.find('[data-testid="attention-clear"]').exists()).toBe(false) + }) + + it('says the list could not be loaded when the sources endpoint fails', async () => { + loadAttentionFeed.mockRejectedValue(new Error('500')) + const wrapper = mount(AttentionWidget) + await flushPromises() + + expect(wrapper.find('[data-testid="attention-error"]').text()).toBe( + 'This list could not be loaded. Reload the page to try again.', + ) + expect(wrapper.text()).not.toContain(CLEAR) + expect(wrapper.find('[data-testid="attention-none"]').exists()).toBe(false) + }) + + it('shows a loading line until the feed answers', async () => { + let resolve + loadAttentionFeed.mockReturnValue( + new Promise((r) => { + resolve = r + }), + ) + const wrapper = mount(AttentionWidget) + await wrapper.vm.$nextTick() + + expect(wrapper.find('[data-testid="attention-loading"]').exists()).toBe(true) + expect(wrapper.text()).not.toContain(CLEAR) + + resolve({ items: [], failedApps: [], sourceCount: 1 }) + await flushPromises() + expect(wrapper.find('[data-testid="attention-loading"]').exists()).toBe( + false, + ) + expect(wrapper.find('[data-testid="attention-clear"]').exists()).toBe(true) + }) + + it('shows at most the configured number of lines and counts the rest', async () => { + const items = Array.from({ length: 7 }, (_v, i) => + item(`app${i}`, `App ${i}`, 'info', 1), + ) + + const five = await mountWith({ items, failedApps: [], sourceCount: 7 }) + expect(five.findAll('.attention-widget__item')).toHaveLength(5) + expect(five.find('[data-testid="attention-more"]').text()).toBe( + 'And 2 more.', + ) + + const two = await mountWith( + { items, failedApps: [], sourceCount: 7 }, + { limit: 2 }, + ) + expect(two.findAll('.attention-widget__item')).toHaveLength(2) + expect(two.find('[data-testid="attention-more"]').text()).toBe('And 5 more.') + + const capped = await mountWith( + { items, failedApps: [], sourceCount: 7 }, + { limit: 500 }, + ) + expect(capped.findAll('.attention-widget__item')).toHaveLength(7) + expect(capped.find('[data-testid="attention-more"]').exists()).toBe(false) + + const nonsense = await mountWith( + { items, failedApps: [], sourceCount: 7 }, + { limit: 'many' }, + ) + expect(nonsense.findAll('.attention-widget__item')).toHaveLength(5) + }) +}) + +describe('AttentionWidget columns layout (LpVandaag "Vandaag eerst")', () => { + const feed = { + items: [ + item('dossiq', 'dossiq', 'error', 1), + item('pipelinq', 'pipelinq', 'warning', 1), + item('decidiq', 'decidiq', 'warning', 1), + item('learniq', 'learniq', 'info', 1), + ], + failedApps: [], + sourceCount: 4, + } + + it('draws its own heading with how many things it shows, in one row of three', async () => { + const wrapper = await mountWith(feed, { + title: 'Vandaag eerst', + layout: 'columns', + limit: 3, + }) + expect(wrapper.find('.attention-widget').classes()).toContain( + 'attention-widget--columns', + ) + expect(wrapper.find('.attention-widget').attributes('style')).toContain( + '--attention-columns: 3', + ) + expect(wrapper.find('.attention-widget__heading').text()).toBe( + 'Vandaag eerst', + ) + expect(wrapper.find('[data-testid="attention-summary"]').text()).toBe( + '3 things from all your apps that need attention today', + ) + expect(wrapper.findAll('.attention-widget__item')).toHaveLength(3) + }) + + it('draws no filter field in the columns layout, as the board does', async () => { + const wrapper = await mountWith(feed, { layout: 'columns', limit: 3 }) + expect(wrapper.findComponent({ name: 'WidgetRowFilter' }).exists()).toBe(false) + }) + + it('takes 1 to 4 columns and falls back to 3', async () => { + const two = await mountWith(feed, { layout: 'columns', columns: 2 }) + expect(two.find('.attention-widget').attributes('style')).toContain( + '--attention-columns: 2', + ) + const wrong = await mountWith(feed, { layout: 'columns', columns: 9 }) + expect(wrong.find('.attention-widget').attributes('style')).toContain( + '--attention-columns: 3', + ) + }) + + it('draws no heading without a title, and no count without items', async () => { + const plain = await mountWith(feed) + expect(plain.find('.attention-widget__head').exists()).toBe(false) + expect(plain.find('.attention-widget').classes()).not.toContain( + 'attention-widget--columns', + ) + const empty = await mountWith( + { items: [], failedApps: [], sourceCount: 2 }, + { title: 'Vandaag eerst', layout: 'columns' }, + ) + expect(empty.find('.attention-widget__heading').text()).toBe('Vandaag eerst') + expect(empty.find('[data-testid="attention-summary"]').exists()).toBe(false) + }) +}) + +describe('AttentionWidget one card per record (LpVandaag)', () => { + it('asks for records and draws a card per record with itemCards', async () => { + const wrapper = await mountWith({ items: [item('dossiq', 'dossiq', 'error', 2)], failedApps: [], sourceCount: 1 }, { layout: 'columns', limit: 3, itemCards: true }) + expect(loadAttentionFeed).toHaveBeenCalledWith({ perSource: 3 }) + expect(wrapper.find('.attention-widget__title').text()).toContain('Record of dossiq title') + }) + + it('counts only, one card per source, without itemCards', async () => { + const wrapper = await mountWith({ items: [item('dossiq', 'dossiq', 'error', 2)], failedApps: [], sourceCount: 1 }, { limit: 3 }) + expect(loadAttentionFeed).toHaveBeenCalledWith({ perSource: 1 }) + expect(wrapper.findAll('.attention-widget__item')).toHaveLength(1) + expect(wrapper.find('.attention-widget__title').text()).toContain('dossiq title') + }) + + // @spec openspec/changes/archive/2026-11-24-start-page-board-sync/specs/attention-feed/spec.md#requirement-vandaag-eerst-can-draw-one-card-per-record-req-att-007 + it('stops at the limit in total across sources, in ranking order', async () => { + expandToRecords.mockImplementationOnce((items) => items.flatMap((i) => [ + { ...i, key: i.key + '/1', title: i.appName + ' record 1' }, + { ...i, key: i.key + '/2', title: i.appName + ' record 2' }, + ])) + const wrapper = await mountWith({ + items: [item('dossiq', 'dossiq', 'error', 2), item('decidiq', 'decidiq', 'warning', 2)], + failedApps: [], + sourceCount: 2, + }, { layout: 'columns', limit: 3, itemCards: true }) + const titles = wrapper.findAll('.attention-widget__title').map((n) => n.text()) + expect(titles).toEqual(['Urgent: dossiq record 1', 'Urgent: dossiq record 2', 'Soon: decidiq record 1']) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/AttentionWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/AttentionWidgetForm.spec.js new file mode 100644 index 000000000..9fb01091e --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/AttentionWidgetForm.spec.js @@ -0,0 +1,62 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * AttentionWidgetForm: the one setting, lines to show (REQ-ATT-004), in the + * protocol the add-widget modal speaks (`editingWidget`, `value`, + * `update:content`, `validate()`). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) +vi.mock('@nextcloud/vue', () => ({ + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel', 'clearable'], + emits: ['update:modelValue'], + template: + '<div class="select-stub" :data-label="inputLabel" :data-value="modelValue" />', + }, +})) + +import AttentionWidgetForm from '../AttentionWidgetForm.vue' + +describe('AttentionWidgetForm', () => { + it('starts at five lines, with a labelled select', () => { + const wrapper = mount(AttentionWidgetForm) + + const select = wrapper.find('.select-stub') + expect(select.attributes('data-value')).toBe('5') + expect(select.attributes('data-label')).toBe('Lines to show') + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('opens on the limit of the widget being edited', () => { + const wrapper = mount(AttentionWidgetForm, { + props: { editingWidget: { content: { limit: 8 } } }, + }) + + expect(wrapper.find('.select-stub').attributes('data-value')).toBe('8') + }) + + it('falls back to five for a limit outside 1 to 10', () => { + const wrapper = mount(AttentionWidgetForm, { + props: { editingWidget: { content: { limit: 40 } } }, + }) + + expect(wrapper.find('.select-stub').attributes('data-value')).toBe('5') + }) + + it('emits the content when the limit changes', async () => { + const wrapper = mount(AttentionWidgetForm) + + await wrapper + .findComponent({ name: 'NcSelect' }) + .vm.$emit('update:modelValue', 3) + + expect(wrapper.emitted('update:content')).toEqual([[{ limit: 3 }]]) + expect(wrapper.find('.select-stub').attributes('data-value')).toBe('3') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/CalendarWidget.spec.js b/src/components/Widgets/Renderers/__tests__/CalendarWidget.spec.js new file mode 100644 index 000000000..da66ec148 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/CalendarWidget.spec.js @@ -0,0 +1,252 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `CalendarWidget.vue`: the initial view mode, the + * date window each mode requests, the loading / error / empty states, how + * events land in the agenda, month and week views, the failure summary and + * the per-calendar colour accent. + * + * "Today" is fixed to Wednesday 11 March 2026 so the month and week grids + * are known. Event times are local (no zone suffix), so the day buckets do + * not depend on the machine's timezone. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import CalendarWidget from '../CalendarWidget.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + '/index.php' + path.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) + +const TODAY = new Date(2026, 2, 11, 10, 0, 0) +const SOURCES = { internalCalendars: ['personal'], externalIcsUrls: [] } + +const EVENTS = [ + { title: 'Standup', start: '2026-03-11T09:30:00', calendarName: 'Work', color: '#ff0000' }, + { title: 'Holiday', start: '2026-03-11T00:00:00', allDay: true }, + { title: 'Review', start: '2026-03-12T14:05:00', color: '' }, +] + +function mountWidget(content = {}, placementId = 7) { + return mount(CalendarWidget, { + props: { content: { ...SOURCES, ...content }, placementId }, + }) +} + +/** + * The `from`/`to` query of the n-th request. + * + * @param {number} n zero-based call index. + * @return {{from: string, to: string}} the window. + */ +function windowOf(n = 0) { + return axios.get.mock.calls[n][1].params +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(TODAY) + globalThis.t = (_app, key) => key + axios.get.mockReset() + axios.get.mockResolvedValue({ data: { events: EVENTS, failures: [] } }) +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('CalendarWidget: loading', () => { + it('fetches the agenda window of the placement on mount', async () => { + const wrapper = mountWidget({ daysAhead: 3 }) + await wrapper.vm.$nextTick() + expect(wrapper.find('.calendar-widget__loading').exists()).toBe(true) + await flushPromises() + + expect(axios.get).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/widgets/calendar/7/events', + { + params: { + from: new Date(2026, 2, 11, 0, 0, 0, 0).toISOString(), + to: new Date(2026, 2, 14, 23, 59, 59, 999).toISOString(), + }, + }, + ) + expect(wrapper.find('.calendar-widget__loading').exists()).toBe(false) + }) + + it.each([[undefined], [0], [-2], ['abc']])('falls back to 14 days ahead for %s', async (daysAhead) => { + mountWidget({ daysAhead }) + await flushPromises() + expect(windowOf().to).toBe(new Date(2026, 2, 25, 23, 59, 59, 999).toISOString()) + }) + + it('requests nothing without a placement or without sources', async () => { + const noPlacement = mountWidget({}, null) + const noSources = mount(CalendarWidget, { + props: { content: { internalCalendars: [], externalIcsUrls: 'x' }, placementId: 7 }, + }) + await flushPromises() + + expect(axios.get).not.toHaveBeenCalled() + expect(noSources.find('.calendar-widget__empty').text()).toBe('No calendars configured') + expect(noPlacement.vm.events).toEqual([]) + }) + + it('counts an external ICS feed as a source', async () => { + mount(CalendarWidget, { + props: { content: { externalIcsUrls: ['https://ics.test/a.ics'] }, placementId: 1 }, + }) + await flushPromises() + expect(axios.get).toHaveBeenCalledTimes(1) + }) + + it('shows an error with a retry that fetches again', async () => { + axios.get.mockRejectedValueOnce(new Error('500')) + const wrapper = mountWidget() + await flushPromises() + + expect(wrapper.find('.calendar-widget__error').text()).toContain('Failed to load events') + expect(wrapper.vm.events).toEqual([]) + + await wrapper.find('.calendar-widget__retry').trigger('click') + await flushPromises() + + expect(axios.get).toHaveBeenCalledTimes(2) + expect(wrapper.find('.calendar-widget__error').exists()).toBe(false) + expect(wrapper.findAll('.calendar-widget__agenda-row')).toHaveLength(3) + }) + + it('treats a malformed payload as no events and no failures', async () => { + axios.get.mockResolvedValue({ data: { events: 'nope', failures: {} } }) + const wrapper = mountWidget({ daysAhead: 5 }) + await flushPromises() + + expect(wrapper.find('.calendar-widget__empty').text()).toBe('No events in the next 5 days') + expect(wrapper.find('.calendar-widget__failures').exists()).toBe(false) + }) + + it('summarises unavailable sources', async () => { + axios.get.mockResolvedValue({ data: { events: [], failures: [{ id: 'a' }, { id: 'b' }] } }) + const wrapper = mountWidget() + await flushPromises() + expect(wrapper.find('.calendar-widget__failures').text()).toBe('2 calendar source(s) unavailable') + }) + + it('refetches when the content changes', async () => { + const wrapper = mountWidget() + await flushPromises() + await wrapper.setProps({ content: { ...SOURCES, daysAhead: 1 } }) + await flushPromises() + + expect(axios.get).toHaveBeenCalledTimes(2) + expect(windowOf(1).to).toBe(new Date(2026, 2, 12, 23, 59, 59, 999).toISOString()) + }) +}) + +describe('CalendarWidget: modes', () => { + it('starts in the configured mode, else agenda', () => { + expect(mountWidget({ viewMode: 'week' }).vm.activeMode).toBe('week') + expect(mountWidget({ viewMode: 'year' }).vm.activeMode).toBe('agenda') + }) + + it('labels the mode buttons and marks the active one', () => { + const buttons = mountWidget({ viewMode: 'month' }).findAll('.calendar-widget__mode-btn') + expect(buttons.map((b) => b.text())).toEqual(['Month', 'Week', 'Agenda']) + expect(buttons.map((b) => b.classes().includes('is-active'))).toEqual([true, false, false]) + }) + + it('switching mode refetches with that mode\'s window; unknown modes are ignored', async () => { + const wrapper = mountWidget() + await flushPromises() + + await wrapper.findAll('.calendar-widget__mode-btn')[0].trigger('click') + await flushPromises() + expect(windowOf(1)).toEqual({ + from: new Date(2026, 2, 1).toISOString(), + to: new Date(2026, 2, 31).toISOString(), + }) + + await wrapper.findAll('.calendar-widget__mode-btn')[1].trigger('click') + await flushPromises() + expect(windowOf(2)).toEqual({ + from: new Date(2026, 2, 8, 0, 0, 0, 0).toISOString(), + to: new Date(2026, 2, 14, 23, 59, 59, 999).toISOString(), + }) + + wrapper.vm.setMode('year') + await flushPromises() + expect(wrapper.vm.activeMode).toBe('week') + expect(axios.get).toHaveBeenCalledTimes(3) + }) +}) + +describe('CalendarWidget: views', () => { + it('groups the agenda by day with times, all-day and calendar names', async () => { + const wrapper = mountWidget() + await flushPromises() + + expect(wrapper.findAll('.calendar-widget__agenda-header').map((h) => h.text())).toEqual([ + expect.stringMatching(/^Wed 11 /), + expect.stringMatching(/^Thu 12 /), + ]) + const rows = wrapper.findAll('.calendar-widget__agenda-row') + expect(rows.map((r) => r.find('.calendar-widget__agenda-time').text())).toEqual(['09:30', 'All day', '14:05']) + expect(rows[0].find('.calendar-widget__agenda-cal').text()).toBe('Work') + expect(rows[2].find('.calendar-widget__agenda-cal').exists()).toBe(false) + }) + + it('accents events by calendar colour unless turned off', async () => { + const wrapper = mountWidget() + await flushPromises() + expect(wrapper.vm.eventStyle(EVENTS[0])).toEqual({ 'border-left': '3px solid #ff0000' }) + expect(wrapper.vm.eventStyle(EVENTS[2])).toEqual({}) + expect(wrapper.vm.eventStyle({ color: 5 })).toEqual({}) + + const plain = mountWidget({ colorByCalendar: false }) + expect(plain.vm.eventStyle(EVENTS[0])).toEqual({}) + }) + + it('draws the month from the Sunday before the 1st, with today and overflow', async () => { + const many = Array.from({ length: 5 }, (_v, i) => ({ title: `E${i}`, start: '2026-03-20T08:00:00' })) + axios.get.mockResolvedValue({ data: { events: [...EVENTS, ...many], failures: [] } }) + const wrapper = mountWidget({ viewMode: 'month' }) + await flushPromises() + + expect(wrapper.findAll('.calendar-widget__month-header').map((h) => h.text())) + .toEqual(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']) + const grid = wrapper.vm.monthGrid + expect(grid).toHaveLength(35) + expect(grid[0]).toMatchObject({ iso: '2026-03-01', isOtherMonth: false }) + expect(grid[31]).toMatchObject({ iso: '2026-04-01', isOtherMonth: true }) + expect(grid.filter((c) => c.isToday).map((c) => c.iso)).toEqual(['2026-03-11']) + expect(grid[10].events.map((e) => e.title)).toEqual(['Standup', 'Holiday']) + + const busy = wrapper.findAll('.calendar-widget__month-cell')[19] + expect(busy.findAll('.calendar-widget__month-event')).toHaveLength(3) + expect(busy.find('.calendar-widget__month-overflow').text()).toBe('+2') + }) + + it('shows the week from Sunday to Saturday with the events per day', async () => { + const wrapper = mountWidget({ viewMode: 'week' }) + await flushPromises() + + const cols = wrapper.findAll('.calendar-widget__week-col') + expect(cols.map((c) => c.find('.calendar-widget__week-num').text())).toEqual(['8', '9', '10', '11', '12', '13', '14']) + expect(cols.map((c) => c.classes().includes('is-today'))).toEqual([false, false, false, true, false, false, false]) + expect(cols[3].findAll('.calendar-widget__week-title').map((e) => e.text())).toEqual(['Standup', 'Holiday']) + expect(cols[0].find('.calendar-widget__week-empty').text()).toBe('—') + }) + + it('files an event with a missing or invalid start under today', async () => { + axios.get.mockResolvedValue({ data: { events: [{ title: 'A' }, { title: 'B', start: 'garbage' }], failures: [] } }) + const wrapper = mountWidget() + await flushPromises() + expect(Object.keys(wrapper.vm.eventsByDay)).toEqual(['2026-03-11']) + expect(wrapper.vm.eventsByDay['2026-03-11']).toHaveLength(2) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/CalendarWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/CalendarWidgetForm.spec.js new file mode 100644 index 000000000..5ca381485 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/CalendarWidgetForm.spec.js @@ -0,0 +1,114 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The Calendar content form (REQ-CAL-020): the reader's calendars, external + * calendars by ICS address, and the period 7 days or Month. + */ + +import { NcCheckboxRadioSwitch, NcTextField } from '@nextcloud/vue' +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import CalendarWidgetForm from '../CalendarWidgetForm.vue' + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +function lastEmitted(wrapper) { + return (wrapper.emitted('update:content') || []).at(-1)?.[0] +} + +function icsField(wrapper) { + return wrapper.findAllComponents(NcTextField).find((field) => field.props('label') === 'External calendar (ICS address)') +} + +const CALENDARS = [ + { key: 'personal', name: 'Personal', color: '#0082c9' }, + { key: 'team', name: 'Team', color: '#e9322d' }, +] + +async function mountForm(props = {}) { + const wrapper = mount(CalendarWidgetForm, { props: { calendarsFetcher: vi.fn().mockResolvedValue(CALENDARS), ...props } }) + await flushPromises() + return wrapper +} + +describe('CalendarWidgetForm calendars', () => { + it('lists the reader\'s calendars and stores the chosen ones', async () => { + const wrapper = await mountForm() + const toggles = wrapper.findAllComponents(NcCheckboxRadioSwitch) + expect(toggles.map((toggle) => toggle.text())).toEqual(['Personal', 'Team']) + toggles[1].vm.$emit('update:modelValue', true) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).internalCalendars).toEqual(['team']) + toggles[1].vm.$emit('update:modelValue', false) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).internalCalendars).toEqual([]) + }) + + it('keeps a stored calendar that is no longer offered visible', async () => { + const wrapper = await mountForm({ value: { internalCalendars: ['gone'] } }) + expect(wrapper.findAllComponents(NcCheckboxRadioSwitch).map((toggle) => toggle.text())).toContain('gone') + }) + + it('works without a fetcher', async () => { + const wrapper = mount(CalendarWidgetForm) + await flushPromises() + expect(wrapper.findAllComponents(NcCheckboxRadioSwitch)).toHaveLength(0) + }) +}) + +describe('CalendarWidgetForm add an external calendar (scenario)', () => { + it('adds an ICS address with 7 days', async () => { + const wrapper = await mountForm({ value: { internalCalendars: ['personal'], viewMode: 'month' } }) + icsField(wrapper).vm.$emit('update:modelValue', 'https://example.com/holidays.ics') + await wrapper.vm.$nextTick() + wrapper.vm.addIcs() + await wrapper.find('[data-testid="calendar-period-week"]').trigger('change') + expect(lastEmitted(wrapper)).toEqual({ + internalCalendars: ['personal'], + externalIcsUrls: ['https://example.com/holidays.ics'], + viewMode: 'agenda', + daysAhead: 7, + colorByCalendar: true, + }) + expect(wrapper.text()).toContain('https://example.com/holidays.ics') + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('refuses an address that is not https and removes an added one', async () => { + const wrapper = await mountForm({ value: { externalIcsUrls: ['https://a.test/a.ics'] } }) + icsField(wrapper).vm.$emit('update:modelValue', 'http://a.test/b.ics') + await wrapper.vm.$nextTick() + expect(wrapper.vm.validate()).toEqual(['An ICS address starts with https://']) + wrapper.vm.addIcs() + await wrapper.vm.$nextTick() + expect(icsField(wrapper).props('helperText')).toBe('An ICS address starts with https://') + wrapper.vm.removeIcs(0) + expect(lastEmitted(wrapper).externalIcsUrls).toEqual([]) + }) + + it('keeps a valid address typed but not added', async () => { + const wrapper = await mountForm() + icsField(wrapper).vm.$emit('update:modelValue', 'https://a.test/c.ics') + await wrapper.vm.$nextTick() + expect(wrapper.vm.validate()).toEqual([]) + expect(wrapper.vm.assembledContent.externalIcsUrls).toEqual(['https://a.test/c.ics']) + }) + + it('asks for a calendar when none is chosen', async () => { + const wrapper = await mountForm() + expect(wrapper.vm.validate()).toEqual(['Choose at least one calendar or add an ICS address']) + }) +}) + +describe('CalendarWidgetForm period', () => { + it('Month stores the month view', async () => { + const wrapper = await mountForm({ value: { internalCalendars: ['team'] } }) + expect(wrapper.find('[data-testid="calendar-period-week"]').element.checked).toBe(true) + await wrapper.find('[data-testid="calendar-period-month"]').trigger('change') + expect(lastEmitted(wrapper)).toMatchObject({ viewMode: 'month', daysAhead: 31 }) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ChartPresets.spec.js b/src/components/Widgets/Renderers/__tests__/ChartPresets.spec.js new file mode 100644 index 000000000..47c626b73 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ChartPresets.spec.js @@ -0,0 +1,124 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The pie chart and graph presets (chart-presets REQ-CHARTP-001..003): the + * donut's total in its centre, bars and a line in one graph, and a source + * that is a register query or entered values. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ ...(await importOriginal()), translate: (_app, text) => text })) + +import { loadLazyComponent } from '@conduction/nextcloud-vue' +import ChartHost, { isMixedSeries, withDonutTotal } from '../ChartHost.vue' +import ChartSourceForm, { kindOf } from '../ChartSourceForm.vue' +import { getDefaultContent, getWidgetTypeEntry } from '../../../../constants/widgetRegistry.js' + +const CnChartWidget = { name: 'CnChartWidget', props: ['type', 'dataSource', 'options', 'series', 'labels', 'categories', 'legendValues', 'legendPosition', 'colorMap', 'widgetId', 'selectable'], template: '<div />' } +const CnChartWidgetForm = { + name: 'CnChartWidgetForm', + props: ['value'], + emits: ['update:content'], + methods: { validate: () => ['Choose a register'] }, + template: '<div class="register-form" />', +} +const stubs = { CnChartWidget, CnChartWidgetForm, NcCheckboxRadioSwitch: true, NcSelect: true, NcTextField: true, NcButton: true, Delete: true } + +/** + * Mount the host. + * + * @param {object} content The content. + * @return {object} The chart stub. + */ +function chartOf(content) { + return mount(ChartHost, { props: { content, placement: { id: 1 } }, global: { stubs } }).getComponent(CnChartWidget) +} + +describe('chart presets', () => { + it('registers a pie chart and a graph on the chart host with the one source form', async () => { + expect(await loadLazyComponent(getWidgetTypeEntry('pie-chart').renderer)).toBe(ChartHost) + expect(await loadLazyComponent(getWidgetTypeEntry('graph').renderer)).toBe(ChartHost) + expect(await loadLazyComponent(getWidgetTypeEntry('pie-chart').form)).toBe(ChartSourceForm) + expect(await loadLazyComponent(getWidgetTypeEntry('graph').form)).toBe(ChartSourceForm) + expect(kindOf({ chartKind: 'donut' })).toBe('pie') + expect(kindOf({ chartKind: 'bar' })).toBe('graph') + expect(getDefaultContent('pie-chart')).toMatchObject({ chartKind: 'donut', showTotal: true, legendValues: true }) + expect(getDefaultContent('graph')).toMatchObject({ chartKind: 'bar', dataSource: { bucket: { interval: 'month' } } }) + }) + + it('writes the donut total in the centre and keeps the legend settings', () => { + const chart = chartOf({ ...getDefaultContent('pie-chart'), source: 'manual', labels: ['In behandeling', 'Wacht op advies'], series: [138, 46] }) + expect(chart.props('type')).toBe('donut') + expect(chart.props('dataSource')).toBeNull() + expect(chart.props('labels')).toEqual(['In behandeling', 'Wacht op advies']) + expect(chart.props('options').plotOptions.pie.donut.labels.total).toEqual({ show: true, label: 'Total' }) + expect(chart.props('legendValues')).toBe(true) + expect(chart.props('legendPosition')).toBe('right') + }) + + it('draws bars and a line in one chart from entered series', () => { + const content = { chartKind: 'bar', source: 'manual', categories: ['apr', 'mei'], series: [{ name: 'Aanvragen', type: 'column', data: [112, 98] }, { name: 'Besluiten', type: 'line', data: [95, 104] }] } + expect(isMixedSeries(content)).toBe(true) + expect(chartOf(content).props('type')).toBe('line') + expect(isMixedSeries({ ...content, source: 'register' })).toBe(false) + }) + + it('keeps the author\'s own donut options', () => { + expect(withDonutTotal({ plotOptions: { pie: { donut: { size: '60%', labels: { total: { label: 'Totaal' } } } } } }, 'Total').plotOptions.pie.donut) + .toEqual({ size: '60%', labels: { show: true, total: { show: true, label: 'Totaal' } } }) + }) +}) + +describe('ChartSourceForm', () => { + it('emits the register query with the preset keys', () => { + const wrapper = mount(ChartSourceForm, { props: { value: getDefaultContent('pie-chart') }, global: { stubs } }) + wrapper.getComponent(CnChartWidgetForm).vm.$emit('update:content', { chartKind: 'donut', dataSource: { register: 'dossiq', schema: 'case', groupBy: { field: 'status' } } }) + expect(wrapper.emitted('update:content').at(-1)[0]).toMatchObject({ + source: 'register', + chartKind: 'donut', + showTotal: true, + dataSource: { register: 'dossiq', schema: 'case', groupBy: { field: 'status' } }, + }) + expect(wrapper.vm.validate()).toEqual(['Choose a register']) + }) + + it('builds a pie chart from entered slices with their colours', async () => { + const wrapper = mount(ChartSourceForm, { props: { value: getDefaultContent('pie-chart') }, global: { stubs } }) + wrapper.vm.setSource('manual') + expect(wrapper.vm.validate()).toEqual(['Enter at least one value with a label']) + wrapper.vm.setSlice(0, { label: 'In behandeling', value: 138, colour: '#3669a5' }) + wrapper.vm.addSlice() + wrapper.vm.setSlice(1, { label: 'Wacht op aanvrager', value: 74 }) + const content = wrapper.emitted('update:content').at(-1)[0] + expect(content).toMatchObject({ source: 'manual', labels: ['In behandeling', 'Wacht op aanvrager'], series: [138, 74], colorMap: { 'In behandeling': '#3669a5' } }) + expect(content.dataSource).toBeUndefined() + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('builds a graph from axis labels and named series', () => { + const wrapper = mount(ChartSourceForm, { props: { value: getDefaultContent('graph') }, global: { stubs } }) + wrapper.vm.setSource('manual') + expect(wrapper.vm.validate()).toHaveLength(1) + wrapper.vm.setCategories('apr, mei, jun') + wrapper.vm.setLine(0, { name: 'Aanvragen', valuesText: '112, 98, 130' }) + wrapper.vm.addLine() + wrapper.vm.setLine(1, { name: 'Besluiten', type: 'line', valuesText: '95, x, 118' }) + expect(wrapper.emitted('update:content').at(-1)[0]).toMatchObject({ + source: 'manual', + categories: ['apr', 'mei', 'jun'], + series: [{ name: 'Aanvragen', type: 'column', data: [112, 98, 130] }, { name: 'Besluiten', type: 'line', data: [95, 0, 118] }], + }) + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('reopens entered values from the placement', () => { + const wrapper = mount(ChartSourceForm, { + props: { editingWidget: { content: { chartKind: 'donut', source: 'manual', labels: ['A'], series: [3], colorMap: { A: 'red' } } } }, + global: { stubs }, + }) + expect(wrapper.vm.slices).toEqual([{ label: 'A', value: 3, colour: 'red' }]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ClockWidget.timezone.spec.js b/src/components/Widgets/Renderers/__tests__/ClockWidget.timezone.spec.js new file mode 100644 index 000000000..043078e1c --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ClockWidget.timezone.spec.js @@ -0,0 +1,100 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `ClockWidget.vue` (REQ-CLOCK-003): an unknown IANA + * timezone falls back to the device zone for both the time and the date + * line instead of throwing and blanking the tile. + */ + +import { setLanguage, setLocale } from '@nextcloud/l10n' +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import ClockWidget from '../ClockWidget.vue' + +const INSTANT = new Date('2024-06-15T13:05:09Z') + +beforeEach(() => { + globalThis.t = (_app, key, vars) => { + if (vars && typeof key === 'string') { + return key.replace(/\{(\w+)\}/g, (_, name) => + Object.hasOwn(vars, name) ? vars[name] : `{${name}}`, + ) + } + return key + } + vi.useFakeTimers() + vi.setSystemTime(INSTANT) + setLocale('en_US') +}) + +afterEach(() => { + vi.useRealTimers() + setLocale('en_US') + setLanguage('en') +}) + +describe('ClockWidget — REQ-CLOCK-003 unknown timezone falls back to the device zone', () => { + it('renders device-zone time and date for an invalid IANA zone', () => { + const wrapper = mount(ClockWidget, { + propsData: { + content: { + style: 'digital', + timezone: 'Not/A_Zone', + hourFormat: '24h', + showDate: true, + }, + }, + }) + const expectedTime = new Intl.DateTimeFormat('en-US', { + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + hour12: false, + }).format(INSTANT) + const expectedDate = new Intl.DateTimeFormat('en-US', { + weekday: 'long', + year: 'numeric', + month: 'long', + day: 'numeric', + }).format(INSTANT) + expect(wrapper.find('.clock-widget__time').text()).toBe(expectedTime) + expect(wrapper.find('.clock-widget__date').text()).toBe(expectedDate) + expect( + wrapper.find('.clock-widget__digital').attributes('aria-label'), + ).toBe(`${expectedDate}, ${expectedTime}`) + }) + + it('keeps the analog face labelled with the device-zone time for an invalid zone', () => { + const wrapper = mount(ClockWidget, { + propsData: { content: { style: 'analog', timezone: 'Mars/Olympus' } }, + }) + const expectedTime = new Intl.DateTimeFormat('en-US', { + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }).format(INSTANT) + expect( + wrapper.find('.clock-widget__analog').attributes('aria-label'), + ).toBe(expectedTime) + }) +}) + +describe('ClockWidget — REQ-CLOCK-002 an unset timezone is the viewer\'s Nextcloud timezone', () => { + it('shows the injected user timezone when the clock names none', () => { + const wrapper = mount(ClockWidget, { + propsData: { content: { style: 'digital', hourFormat: '24h', showDate: false } }, + global: { provide: { userTimezone: 'Asia/Tokyo' } }, + }) + // 13:05:09 UTC is 22:05:09 in Tokyo. + expect(wrapper.find('.clock-widget__time').text()).toBe('22:05:09') + }) + + it('keeps a configured timezone over the user\'s', () => { + const wrapper = mount(ClockWidget, { + propsData: { content: { style: 'digital', hourFormat: '24h', timezone: 'Europe/London', showDate: false } }, + global: { provide: { userTimezone: 'Asia/Tokyo' } }, + }) + expect(wrapper.find('.clock-widget__time').text()).toBe('14:05:09') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ClockWidgetForm.controls.spec.js b/src/components/Widgets/Renderers/__tests__/ClockWidgetForm.controls.spec.js new file mode 100644 index 000000000..bb79fd4ed --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ClockWidgetForm.controls.spec.js @@ -0,0 +1,130 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the rendered controls of `ClockWidgetForm.vue`: each + * NcSelect / switch writes its field back through `update:modelValue` and + * the form emits the assembled content; digital-only controls disappear for + * an analog clock; the timezone picker falls back to a curated list when + * `Intl.supportedValuesOf` is missing or throws. + */ + +import { NcCheckboxRadioSwitch, NcSelect } from '@nextcloud/vue' +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import ClockWidgetForm from '../ClockWidgetForm.vue' + +function lastEmitted(wrapper) { + return wrapper.emitted('update:content')?.at(-1)?.[0] +} + +function selectByLabel(wrapper, label) { + return wrapper + .findAllComponents(NcSelect) + .find((select) => select.props('inputLabel') === label) +} + +const DIGITAL = { + style: 'digital', + hourFormat: 'auto', + timezone: 'Europe/Amsterdam', + showDate: true, +} + +beforeEach(() => { + globalThis.t = (_app, key) => key +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('ClockWidgetForm rendered controls', () => { + it('renders style, hour format, timezone and the show-date switch for a digital clock', () => { + const wrapper = mount(ClockWidgetForm, { props: { value: { ...DIGITAL } } }) + const labels = wrapper + .findAllComponents(NcSelect) + .map((select) => select.props('inputLabel')) + expect(labels).toEqual(['Style', 'Hour format', 'Timezone']) + expect(wrapper.findComponent(NcCheckboxRadioSwitch).text()).toContain('Show date') + }) + + it('hides the hour format and show-date controls for an analog clock', () => { + const wrapper = mount(ClockWidgetForm, { + props: { value: { style: 'analog', timezone: '' } }, + }) + const labels = wrapper + .findAllComponents(NcSelect) + .map((select) => select.props('inputLabel')) + expect(labels).toEqual(['Style', 'Timezone']) + expect(wrapper.findComponent(NcCheckboxRadioSwitch).exists()).toBe(false) + }) + + it('switching the style select to analog emits the analog shape and removes the digital controls', async () => { + const wrapper = mount(ClockWidgetForm, { props: { value: { ...DIGITAL } } }) + selectByLabel(wrapper, 'Style').vm.$emit('update:modelValue', 'analog') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper)).toEqual({ + style: 'analog', + timezone: 'Europe/Amsterdam', + }) + expect(selectByLabel(wrapper, 'Hour format')).toBeUndefined() + }) + + it('writes the hour format chosen in its select', async () => { + const wrapper = mount(ClockWidgetForm, { props: { value: { ...DIGITAL } } }) + selectByLabel(wrapper, 'Hour format').vm.$emit('update:modelValue', '12h') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper)).toEqual({ ...DIGITAL, hourFormat: '12h' }) + }) + + it('writes the show-date switch', async () => { + const wrapper = mount(ClockWidgetForm, { props: { value: { ...DIGITAL } } }) + wrapper.findComponent(NcCheckboxRadioSwitch).vm.$emit('update:modelValue', false) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper)).toEqual({ ...DIGITAL, showDate: false }) + }) + + it('writes a chosen timezone and stores a cleared one as an empty string', async () => { + const wrapper = mount(ClockWidgetForm, { props: { value: { ...DIGITAL } } }) + const tz = selectByLabel(wrapper, 'Timezone') + tz.vm.$emit('update:modelValue', 'Asia/Tokyo') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).timezone).toBe('Asia/Tokyo') + tz.vm.$emit('update:modelValue', null) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).timezone).toBe('') + }) +}) + +describe('ClockWidgetForm timezone fallback', () => { + const CURATED_FIRST = ['UTC', 'Europe/Amsterdam', 'Europe/London'] + + it('uses the curated list when Intl.supportedValuesOf throws', () => { + vi.spyOn(Intl, 'supportedValuesOf').mockImplementation(() => { + throw new RangeError('unsupported') + }) + const wrapper = mount(ClockWidgetForm, { props: { value: {} } }) + const zones = wrapper.vm.timezoneOptions.map((o) => o.value) + expect(zones).toHaveLength(18) + expect(zones.slice(0, 3)).toEqual(CURATED_FIRST) + expect(zones.at(-1)).toBe('Pacific/Auckland') + expect(selectByLabel(wrapper, 'Timezone').props('options')).toEqual( + wrapper.vm.timezoneOptions, + ) + }) + + it('uses the curated list when Intl.supportedValuesOf does not exist', () => { + const original = Intl.supportedValuesOf + Intl.supportedValuesOf = undefined + try { + const wrapper = mount(ClockWidgetForm, { props: { value: {} } }) + const zones = wrapper.vm.timezoneOptions.map((o) => o.value) + expect(zones).toHaveLength(18) + expect(zones.slice(0, 3)).toEqual(CURATED_FIRST) + expect(wrapper.vm.timezoneOptions[0]).toEqual({ value: 'UTC', label: 'UTC' }) + } finally { + Intl.supportedValuesOf = original + } + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ColleagueActivityWidget.spec.js b/src/components/Widgets/Renderers/__tests__/ColleagueActivityWidget.spec.js new file mode 100644 index 000000000..4e1446670 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ColleagueActivityWidget.spec.js @@ -0,0 +1,109 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ColleagueActivityWidget: the server's filtered list and totals, shown as + * they come (openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them REQ-DWMS-007). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const interpolate = (text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`) +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => interpolate(text, vars), + translatePlural: (_app, one, many, count, vars = {}) => interpolate(count === 1 ? one : many, vars), +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const loadColleagueActivity = vi.fn() +vi.mock('../../../../services/colleagueActivity.js', () => ({ + loadColleagueActivity: (...args) => loadColleagueActivity(...args), +})) + +import ColleagueActivityWidget from '../ColleagueActivityWidget.vue' + +function entry(id, actorDisplayName, type, title = '') { + return { id, actor: actorDisplayName.toLowerCase(), actorDisplayName, app: 'launchpad', type, subject: type, title, link: `/x/${id}`, timestamp: 1_800_000_000 } +} + +async function mountWith(result, content = {}) { + loadColleagueActivity.mockResolvedValue(result) + const wrapper = mount(ColleagueActivityWidget, { props: { content } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + loadColleagueActivity.mockReset() +}) + +describe('ColleagueActivityWidget', () => { + it('lists the entries and shows the server total, not a count of its own', async () => { + const wrapper = await mountWith({ + available: true, + days: 7, + entries: [entry(1, 'Bob', 'dashboard_updated', 'Team'), entry(2, 'Carol', 'file_changed')], + total: 5, + counts: {}, + actors: 2, + }) + + expect(wrapper.findAll('li')).toHaveLength(2) + expect(wrapper.find('[data-testid="colleague-activity-entry-1"]').text()).toContain('Team (dashboard updated)') + expect(wrapper.find('[data-testid="colleague-activity-total"]').text()).toBe('5 actions by colleagues in the last 7 days') + }) + + it('asks for the configured, bounded limit and period', async () => { + await mountWith({ available: true, days: 90, entries: [], total: 0, counts: {}, actors: 0 }, { limit: 500, days: 400 }) + + expect(loadColleagueActivity).toHaveBeenCalledWith({ limit: 50, days: 90 }) + }) + + it('falls back to the defaults for settings that are not numbers', async () => { + await mountWith({ available: true, days: 7, entries: [], total: 0, counts: {}, actors: 0 }, { limit: 'x', days: -1 }) + + expect(loadColleagueActivity).toHaveBeenCalledWith({ limit: 10, days: 7 }) + }) + + it('says so when nothing is visible', async () => { + const wrapper = await mountWith({ available: true, days: 7, entries: [], total: 0, counts: {}, actors: 0 }) + + expect(wrapper.find('[data-testid="colleague-activity-empty"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="colleague-activity-total"]').text()).toBe('0 actions by colleagues in the last 7 days') + }) + + it('says the Activity app is needed when the server cannot read it', async () => { + const wrapper = await mountWith({ available: false, days: 7, entries: [], total: 0, counts: {}, actors: 0 }) + + expect(wrapper.find('[data-testid="colleague-activity-unavailable"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="colleague-activity-list"]').exists()).toBe(false) + }) + + it('shows an error when the load fails', async () => { + loadColleagueActivity.mockRejectedValue(new Error('500')) + const wrapper = mount(ColleagueActivityWidget, { props: { content: {} } }) + await flushPromises() + + expect(wrapper.find('[data-testid="colleague-activity-error"]').exists()).toBe(true) + }) + + it('filters the rows in view state and leaves the content alone', async () => { + const content = { limit: 10, days: 7 } + const wrapper = await mountWith({ + available: true, + days: 7, + entries: [entry(1, 'Bob', 'dashboard_updated', 'Team'), entry(2, 'Carol', 'file_changed')], + total: 2, + counts: {}, + actors: 2, + }, content) + + await wrapper.find('input').setValue('carol') + + expect(wrapper.findAll('li')).toHaveLength(1) + expect(wrapper.find('[data-testid="colleague-activity-entry-2"]').exists()).toBe(true) + expect(content).toEqual({ limit: 10, days: 7 }) + expect(wrapper.find('[data-testid="colleague-activity-total"]').text()).toBe('2 actions by colleagues in the last 7 days') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ColleagueActivityWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/ColleagueActivityWidgetForm.spec.js new file mode 100644 index 000000000..bb4b86f7b --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ColleagueActivityWidgetForm.spec.js @@ -0,0 +1,51 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ColleagueActivityWidgetForm: lines to show and days back (REQ-DWMS-007), + * in the protocol the add-widget modal speaks. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) +vi.mock('@nextcloud/vue', () => ({ + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel', 'clearable'], + emits: ['update:modelValue'], + template: + '<div class="select-stub" :data-label="inputLabel" :data-value="modelValue" />', + }, +})) + +import ColleagueActivityWidgetForm from '../ColleagueActivityWidgetForm.vue' + +describe('ColleagueActivityWidgetForm', () => { + it('starts at ten lines over seven days, with labelled selects', () => { + const selects = mount(ColleagueActivityWidgetForm).findAll('.select-stub') + + expect(selects.map((s) => s.attributes('data-label'))).toEqual(['Lines to show', 'Days back']) + expect(selects.map((s) => s.attributes('data-value'))).toEqual(['10', '7']) + }) + + it('opens on the settings of the widget being edited, and replaces values it does not offer', () => { + const wrapper = mount(ColleagueActivityWidgetForm, { + props: { editingWidget: { content: { limit: 20, days: 3 } } }, + }) + + expect(wrapper.findAll('.select-stub').map((s) => s.attributes('data-value'))).toEqual(['20', '7']) + }) + + it('emits both settings whenever one changes', async () => { + const wrapper = mount(ColleagueActivityWidgetForm) + const selects = wrapper.findAllComponents({ name: 'NcSelect' }) + + await selects[1].vm.$emit('update:modelValue', 30) + await selects[0].vm.$emit('update:modelValue', 999) + + expect(wrapper.emitted('update:content')).toEqual([[{ limit: 10, days: 30 }], [{ limit: 10, days: 30 }]]) + expect(wrapper.vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/CommunitiesWidget.spec.js b/src/components/Widgets/Renderers/__tests__/CommunitiesWidget.spec.js new file mode 100644 index 000000000..2c5713b75 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/CommunitiesWidget.spec.js @@ -0,0 +1,159 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * CommunitiesWidget: what the viewer sees and does in each state + * (openspec/changes/engagement-communities REQ-COMM-001..004). What Talk + * answers is talkCommunities.spec.js; here the list is given. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => { + const actual = await importOriginal() + const fill = (text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`) + return { + ...actual, + translate: (_app, text, vars) => fill(text, vars), + translatePlural: (_app, one, many, count, vars) => fill(count === 1 ? one : many, vars).replace('%n', String(count)), + } +}) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const loadCommunities = vi.fn() +const joinCommunity = vi.fn() +vi.mock('../../../../services/talkCommunities.js', () => ({ + loadCommunities: (...args) => loadCommunities(...args), + joinCommunity: (...args) => joinCommunity(...args), + communityUrl: (token) => `/index.php/call/${token}`, +})) + +import CommunitiesWidget from '../CommunitiesWidget.vue' + +const NcButton = { + name: 'NcButton', + props: ['disabled', 'variant', 'ariaLabel'], + emits: ['click'], + template: '<button :disabled="disabled" :aria-label="ariaLabel" @click="$emit(\'click\')"><slot /></button>', +} + +const DUURZAAMHEID = { + token: 'duurzaam42', + name: 'Duurzaamheid', + description: 'Ideeën voor een groenere organisatie', + members: 14, + joined: false, + pinned: false, +} +const VRAAG_ICT = { + token: 'vraagict', + name: 'Vraag het de ICT', + description: '', + members: 1, + joined: true, + pinned: true, +} + +/** + * Mount the widget with the given Talk state. + * + * @param {object} opts Options. + * @param {boolean} [opts.talkEnabled] Whether Talk is enabled. + * @param {Array<string>} [opts.pinned] Pinned tokens. + * @param {object} [opts.content] Widget content. + * @return {Promise<object>} The wrapper. + */ +async function mountWidget({ talkEnabled = true, pinned = ['vraagict'], content = {} } = {}) { + const wrapper = mount(CommunitiesWidget, { + props: { content }, + global: { + provide: { talkEnabled, pinnedCommunities: pinned }, + stubs: { NcButton }, + }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + loadCommunities.mockReset() + joinCommunity.mockReset() + loadCommunities.mockResolvedValue([VRAAG_ICT, DUURZAAMHEID]) +}) + +describe('CommunitiesWidget', () => { + it('lists each community with its description and member count, and a Join button', async () => { + const wrapper = await mountWidget() + + expect(loadCommunities).toHaveBeenCalledWith(['vraagict']) + const row = wrapper.find('[data-testid="community-duurzaam42"]') + expect(row.text()).toContain('Duurzaamheid') + expect(row.text()).toContain('Ideeën voor een groenere organisatie') + expect(row.text()).toContain('14 members') + expect(row.find('[data-testid="community-join"]').text()).toBe('Join') + }) + + it('shows the pinned community first with its mark, and Open for one already joined', async () => { + const wrapper = await mountWidget() + + const rows = wrapper.findAll('li') + expect(rows[0].attributes('data-testid')).toBe('community-vraagict') + expect(rows[0].find('[data-testid="community-pinned"]').text()).toBe('Pinned by your organisation') + expect(rows[0].text()).toContain('1 member') + expect(rows[0].find('[data-testid="community-open"]').attributes('href')).toBe('/index.php/call/vraagict') + expect(rows[1].find('[data-testid="community-pinned"]').exists()).toBe(false) + }) + + it('joins in one click, and the button becomes Open', async () => { + joinCommunity.mockResolvedValue(undefined) + const wrapper = await mountWidget() + + await wrapper.find('[data-testid="community-duurzaam42"] [data-testid="community-join"]').trigger('click') + await flushPromises() + + expect(joinCommunity).toHaveBeenCalledWith('duurzaam42') + const row = wrapper.find('[data-testid="community-duurzaam42"]') + expect(row.find('[data-testid="community-join"]').exists()).toBe(false) + expect(row.find('[data-testid="community-open"]').attributes('href')).toBe('/index.php/call/duurzaam42') + }) + + it('says so when a join fails, and keeps the Join button', async () => { + joinCommunity.mockRejectedValue(new Error('403')) + const wrapper = await mountWidget() + + await wrapper.find('[data-testid="community-duurzaam42"] [data-testid="community-join"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="communities-join-error"]').text()).toBe( + 'You could not join Duurzaamheid. Try again later.', + ) + expect(wrapper.find('[data-testid="community-duurzaam42"] [data-testid="community-join"]').exists()).toBe(true) + }) + + it('shows only the pinned ones when the form asks, and a title', async () => { + const wrapper = await mountWidget({ content: { onlyPinned: true, title: 'Communities' } }) + + expect(wrapper.findAll('li').map((li) => li.attributes('data-testid'))).toEqual(['community-vraagict']) + expect(wrapper.find('h3').text()).toBe('Communities') + }) + + it('without Talk explains itself and calls nothing', async () => { + const wrapper = await mountWidget({ talkEnabled: false }) + + expect(loadCommunities).not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="communities-no-talk"]').text()).toBe( + 'Communities need Nextcloud Talk. Ask your administrator to enable it.', + ) + }) + + it('tells a failure apart from an empty list', async () => { + loadCommunities.mockRejectedValueOnce(new Error('500')) + const failed = await mountWidget() + expect(failed.find('[data-testid="communities-error"]').exists()).toBe(true) + + loadCommunities.mockResolvedValueOnce([]) + const empty = await mountWidget() + expect(empty.find('[data-testid="communities-empty"]').text()).toBe('There are no open communities to join yet.') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/CommunitiesWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/CommunitiesWidgetForm.spec.js new file mode 100644 index 000000000..40efedf41 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/CommunitiesWidgetForm.spec.js @@ -0,0 +1,51 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * CommunitiesWidgetForm: the title and "Show only pinned" + * (openspec/changes/engagement-communities REQ-COMM-003). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import CommunitiesWidgetForm from '../CommunitiesWidgetForm.vue' + +const stubs = { + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: '<input :value="modelValue" />', + }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'type'], + emits: ['update:modelValue'], + template: '<label><slot /></label>', + }, +} + +describe('CommunitiesWidgetForm', () => { + it('starts from the placement being edited', () => { + const wrapper = mount(CommunitiesWidgetForm, { + props: { editingWidget: { content: { title: 'Praat mee', onlyPinned: true } } }, + global: { stubs }, + }) + + expect(wrapper.findComponent({ name: 'NcTextField' }).props('modelValue')).toBe('Praat mee') + expect(wrapper.findComponent({ name: 'NcCheckboxRadioSwitch' }).props('modelValue')).toBe(true) + }) + + it('emits the whole content on each change', async () => { + const wrapper = mount(CommunitiesWidgetForm, { global: { stubs } }) + + wrapper.findComponent({ name: 'NcTextField' }).vm.$emit('update:modelValue', 'Communities') + wrapper.findComponent({ name: 'NcCheckboxRadioSwitch' }).vm.$emit('update:modelValue', true) + + expect(wrapper.emitted('update:content')).toEqual([ + [{ title: 'Communities', onlyPinned: false }], + [{ title: 'Communities', onlyPinned: true }], + ]) + expect(wrapper.vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ConnectionsWidget.spec.js b/src/components/Widgets/Renderers/__tests__/ConnectionsWidget.spec.js new file mode 100644 index 000000000..7be872486 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ConnectionsWidget.spec.js @@ -0,0 +1,107 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ConnectionsWidget and its form (dashboard-connections-widget REQ-LP-CONN-005). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { ref } from 'vue' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key]), + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key]), +})) + +const fetchConnectionRows = vi.fn() +vi.mock('../../../../services/dashboardConnections.js', async (importOriginal) => ({ + ...(await importOriginal()), + fetchConnectionRows: (...args) => fetchConnectionRows(...args), +})) + +import ConnectionsWidget from '../ConnectionsWidget.vue' +import ConnectionsWidgetForm from '../ConnectionsWidgetForm.vue' +import { getWidgetTypeEntry, offeredForViewer } from '../../../../constants/widgetRegistry.js' + +const MANAGEMENT = [ + { id: 1, widgetId: 'livetile', content: {} }, + { id: 2, widgetId: 'news', content: {} }, + { id: 3, widgetId: 'connections', content: {} }, +] + +/** + * Mount the widget. + * + * @param {object} integrationApps The apps enabled for the viewer. + * @param {Array<object>} placements The dashboard's placements. + * @return {Promise<object>} The wrapper. + */ +async function mountWidget(integrationApps = { integriq: true }, placements = MANAGEMENT) { + const wrapper = mount(ConnectionsWidget, { + props: { content: {}, placement: {} }, + global: { provide: { integrationApps, dashboardPlacements: ref(placements) } }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + fetchConnectionRows.mockReset().mockResolvedValue({ + state: 'ok', + rows: [ + { key: 'live-tiles', title: 'Live tiles', status: 'configured', lastSuccessAt: '2026-11-25T10:44:00Z' }, + { key: 'news-feeds', title: 'News feeds', status: 'error', lastErrorAt: '2026-11-25T09:30:00Z', statusMessage: 'feeds.example.nl answered 503' }, + { key: 'weather', title: 'Weather provider', status: 'configured' }, + ], + }) +}) + +describe('ConnectionsWidget', () => { + it('lists the connections the management dashboard uses with their states, not the weather provider', async () => { + const wrapper = await mountWidget() + expect(fetchConnectionRows).toHaveBeenCalledTimes(1) + const live = wrapper.get('[data-testid="connection-live-tiles"]') + expect(live.text()).toContain('Live tiles') + expect(live.get('[data-testid="connection-status"]').text()).toBe('Configured') + expect(live.find('[data-testid="connection-error"]').exists()).toBe(false) + const news = wrapper.get('[data-testid="connection-news-feeds"]') + expect(news.get('[data-testid="connection-status"]').text()).toBe('Error') + expect(news.get('[data-testid="connection-error"]').text()).toContain('feeds.example.nl answered 503') + expect(wrapper.find('[data-testid="connection-weather"]').exists()).toBe(false) + }) + + it('says it needs the Integrations app without integriq, and reads nothing', async () => { + const wrapper = await mountWidget({}) + expect(wrapper.get('[data-testid="connections-no-app"]').text()).toBe('Connection states need the Integrations app') + expect(fetchConnectionRows).not.toHaveBeenCalled() + }) + + it('says so when no widget uses a connection', async () => { + const wrapper = await mountWidget({ integriq: true }, [{ widgetId: 'text' }]) + expect(wrapper.find('[data-testid="connections-none"]').exists()).toBe(true) + }) + + it('says so when the states cannot be read', async () => { + fetchConnectionRows.mockResolvedValue({ state: 'error', rows: [] }) + const wrapper = await mountWidget() + expect(wrapper.find('[data-testid="connections-error"]').exists()).toBe(true) + }) +}) + +describe('the connections type', () => { + it('is offered only with integriq', () => { + const entry = getWidgetTypeEntry('connections') + expect(entry.requiresApp).toBe('integriq') + expect(offeredForViewer(entry, { integriq: true })).toBe(true) + expect(offeredForViewer(entry, {})).toBe(false) + }) + + it('has a form without settings', async () => { + const wrapper = mount(ConnectionsWidgetForm, { props: { editingWidget: null } }) + await flushPromises() + expect(wrapper.emitted('update:content')[0]).toEqual([{}]) + expect(wrapper.vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ContainerChild.spec.js b/src/components/Widgets/Renderers/__tests__/ContainerChild.spec.js new file mode 100644 index 000000000..55ab3ffbb --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ContainerChild.spec.js @@ -0,0 +1,110 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `ContainerChild.vue` (REQ-CONT-003): a known + * registry type mounts its renderer with the placement's content, an + * unknown or missing type renders the "Unknown widget type" placeholder, + * the data-source adapters it provides are scoped to its own placement id, + * and Files receives its `apiBase` extra prop. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const axiosGet = vi.fn() +vi.mock('@nextcloud/axios', () => ({ default: { get: (...a) => axiosGet(...a) } })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (p, params = {}) => `/index.php${p.replace(/\{(\w+)\}/g, (_m, k) => params[k])}`, +})) + +const { default: ContainerChild } = await import('../ContainerChild.vue') + +beforeEach(() => { + globalThis.t = (_app, key, vars = {}) => key.replace(/\{(\w+)\}/g, (_m, k) => vars[k]) + axiosGet.mockReset() +}) + +describe('ContainerChild — registry dispatch', () => { + it('mounts the registered renderer for a known type with the placement content', () => { + const wrapper = mount(ContainerChild, { + props: { placement: { id: 3, type: 'label', content: { text: 'Hello child' } } }, + }) + expect(wrapper.vm.childRenderer).not.toBeNull() + expect(wrapper.vm.childContent).toEqual({ text: 'Hello child' }) + expect(wrapper.find('.container-child--unknown').exists()).toBe(false) + expect(wrapper.find('.cn-label-widget').exists()).toBe(true) + }) + + it('passes an empty content object when the placement has none', () => { + const wrapper = mount(ContainerChild, { + props: { placement: { id: 3, type: 'label' } }, + }) + expect(wrapper.vm.childContent).toEqual({}) + }) + + it('renders the unknown-type placeholder naming an unregistered type', () => { + const wrapper = mount(ContainerChild, { + props: { placement: { id: 3, type: 'no-such-widget-type' } }, + }) + expect(wrapper.vm.childRenderer).toBeNull() + expect(wrapper.find('.container-child__missing').text()).toBe('Unknown widget type: no-such-widget-type') + }) + + it('treats a missing type as unknown without a registry lookup', () => { + const wrapper = mount(ContainerChild, { props: { placement: { id: 3 } } }) + expect(wrapper.vm.registryEntry).toBeNull() + expect(wrapper.vm.unknownLabel).toBe('Unknown widget type: ') + expect(wrapper.find('.container-child__missing').exists()).toBe(true) + }) + + it('treats an empty or non-string type as unknown', () => { + expect(mount(ContainerChild, { props: { placement: { type: '' } } }).vm.registryEntry).toBeNull() + expect(mount(ContainerChild, { props: { placement: { type: 42 } } }).vm.registryEntry).toBeNull() + }) +}) + +describe('ContainerChild — extra renderer props', () => { + it('gives the files renderer its apiBase', () => { + const wrapper = mount(ContainerChild, { + props: { placement: { id: 9, type: 'unknown-x' } }, + }) + expect(wrapper.vm.extraProps).toEqual({}) + const files = mount(ContainerChild, { + props: { placement: { id: 9, type: 'files' } }, + shallow: true, + }) + expect(files.vm.extraProps).toEqual({ apiBase: '/apps/launchpad' }) + }) +}) + +describe('ContainerChild — provided data sources', () => { + it('scopes the calendar source to its own placement id', async () => { + axiosGet.mockResolvedValue({ data: { events: [{ id: 'e1' }], failures: 'bad' } }) + const wrapper = mount(ContainerChild, { + props: { placement: { id: 77, type: 'label', content: {} } }, + }) + const provides = wrapper.vm.$.provides + expect(Object.keys(provides)).toEqual(expect.arrayContaining([ + 'cnPeopleSource', 'cnCalendarSource', 'cnSpendAnalyticsSource', + ])) + const result = await provides.cnCalendarSource.fetchEvents({ from: 'a', to: 'b' }) + expect(axiosGet).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/widgets/calendar/77/events', + { params: { from: 'a', to: 'b' } }, + ) + expect(result).toEqual({ events: [{ id: 'e1' }], failures: [] }) + }) + + it('reads the placement id at call time, so a changed placement is followed', async () => { + axiosGet.mockResolvedValue({ data: {} }) + const wrapper = mount(ContainerChild, { + props: { placement: { id: 1, type: 'label', content: {} } }, + }) + const source = wrapper.vm.$.provides.cnCalendarSource + await wrapper.setProps({ placement: { id: 2, type: 'label', content: {} } }) + await source.fetchEvents({}) + expect(axiosGet.mock.calls[0][0]).toBe('/index.php/apps/launchpad/api/widgets/calendar/2/events') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ContainerWidget.grid.spec.js b/src/components/Widgets/Renderers/__tests__/ContainerWidget.grid.spec.js new file mode 100644 index 000000000..8f827e130 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ContainerWidget.grid.spec.js @@ -0,0 +1,114 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the inner GridStack lifecycle of `ContainerWidget.vue` + * (REQ-CONT-002 / REQ-CONT-005): the nested grid is initialised with the + * nested-grid options on the inner host element, its `change` event is wired + * to the persistence bridge, it is torn down on unmount (tolerating a throwing + * destroy), and child keys prefer id, then uuid, then the loop index. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { toRaw } from 'vue' +import { getNestedGridOptions } from '../../../../composables/useNestedGridManager.js' + +const gridstack = vi.hoisted(() => ({ GridStack: { init: vi.fn() } })) +vi.mock('gridstack', () => gridstack) + +// Imported after the mock so the component's dynamic import sees it. +const { default: ContainerWidget } = await import('../ContainerWidget.vue') + +function fakeGrid(overrides = {}) { + return { on: vi.fn(), destroy: vi.fn(), ...overrides } +} + +function mountContainer(content = { placements: [] }) { + return mount(ContainerWidget, { + props: { content }, + global: { stubs: { ContainerChild: true } }, + }) +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + gridstack.GridStack.init.mockReset() +}) + +describe('ContainerWidget inner grid', () => { + it('initialises GridStack with the nested options on the inner host and listens for change', async () => { + const grid = fakeGrid() + gridstack.GridStack.init.mockReturnValue(grid) + const wrapper = mountContainer() + await flushPromises() + + expect(gridstack.GridStack.init).toHaveBeenCalledTimes(1) + const [opts, el] = gridstack.GridStack.init.mock.calls[0] + expect(opts).toEqual(getNestedGridOptions()) + expect(el).toBe(wrapper.find('.launchpad-container-grid').element) + expect(toRaw(wrapper.vm.gridInstance)).toBe(grid) + expect(grid.on).toHaveBeenCalledWith('change', wrapper.vm.onGridChange) + }) + + it('persists through the change handler it registered', async () => { + const grid = fakeGrid() + gridstack.GridStack.init.mockReturnValue(grid) + const placements = [{ id: 7, type: 'label', gridX: 0, gridY: 0, gridWidth: 2, gridHeight: 2 }] + const wrapper = mountContainer({ title: 'Box', placements }) + await flushPromises() + + const handler = grid.on.mock.calls[0][1] + handler({}, [{ el: { dataset: { launchpadIndex: '0' } }, x: 1, y: 2, w: 3, h: 4 }]) + + expect(wrapper.emitted('update:content')).toEqual([[{ + title: 'Box', + placements: [{ ...placements[0], gridX: 1, gridY: 2, gridWidth: 3, gridHeight: 4 }], + }]]) + }) + + it('skips the change wiring when the grid instance has no on()', async () => { + gridstack.GridStack.init.mockReturnValue({}) + const wrapper = mountContainer() + await flushPromises() + expect(wrapper.vm.gridInstance).toEqual({}) + wrapper.unmount() + expect(wrapper.vm.gridInstance).toBeNull() + }) + + it('destroys the grid without removing DOM on unmount', async () => { + const grid = fakeGrid() + gridstack.GridStack.init.mockReturnValue(grid) + const wrapper = mountContainer() + await flushPromises() + + const vm = wrapper.vm + wrapper.unmount() + expect(grid.destroy).toHaveBeenCalledWith(false) + expect(vm.gridInstance).toBeNull() + expect(vm._nestedManager).toBeNull() + }) + + it('swallows a throwing destroy and still clears the instance', async () => { + const grid = fakeGrid({ destroy: vi.fn(() => { throw new Error('gone') }) }) + gridstack.GridStack.init.mockReturnValue(grid) + const wrapper = mountContainer() + await flushPromises() + + const vm = wrapper.vm + expect(() => wrapper.unmount()).not.toThrow() + expect(grid.destroy).toHaveBeenCalledTimes(1) + expect(vm.gridInstance).toBeNull() + }) +}) + +describe('ContainerWidget child keys', () => { + it('prefers id, then a non-empty uuid, then the index', () => { + const wrapper = mountContainer() + const key = wrapper.vm.childKey + expect(key({ id: 0, uuid: 'u' }, 3)).toBe('id-0') + expect(key({ id: null, uuid: 'abc' }, 3)).toBe('uuid-abc') + expect(key({ uuid: '' }, 3)).toBe('idx-3') + expect(key(null, 5)).toBe('idx-5') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ContainerWidget.gridless.spec.js b/src/components/Widgets/Renderers/__tests__/ContainerWidget.gridless.spec.js new file mode 100644 index 000000000..2a24e193d --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ContainerWidget.gridless.spec.js @@ -0,0 +1,83 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `ContainerWidget.vue` (REQ-CONT-002 / REQ-CONT-005) + * when the GridStack runtime is unusable: a module that fails to load, an + * export without `init()`, or an init that arrives after the inner host has + * been torn down all leave the container rendering its children without an + * inner grid and without emitting anything. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const gridstack = vi.hoisted(() => ({ mode: 'ok', init: null })) +vi.mock('gridstack', () => ({ + get GridStack() { + if (gridstack.mode === 'throw') { + throw new Error('gridstack failed to load') + } + if (gridstack.mode === 'no-init') { + return {} + } + return { init: gridstack.init } + }, + default: undefined, +})) + +// Imported after the mock so the component's dynamic import sees it. +const { default: ContainerWidget } = await import('../ContainerWidget.vue') + +const placements = [ + { id: 1, type: 'label', gridX: 0, gridY: 0, gridWidth: 2, gridHeight: 2 }, + { uuid: 'u-2', type: 'label', gridX: 2, gridY: 0, gridWidth: 2, gridHeight: 2 }, +] + +function mountContainer() { + return mount(ContainerWidget, { + props: { content: { placements } }, + global: { stubs: { ContainerChild: true } }, + }) +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + gridstack.mode = 'ok' + gridstack.init = vi.fn(() => ({ on: vi.fn(), destroy: vi.fn() })) +}) + +describe('ContainerWidget without a usable GridStack', () => { + it('still renders every child when the GridStack module fails to load', async () => { + gridstack.mode = 'throw' + const wrapper = mountContainer() + await flushPromises() + expect(wrapper.findAll('.container-widget__child')).toHaveLength(2) + expect(wrapper.vm.gridInstance).toBeNull() + expect(gridstack.init).not.toHaveBeenCalled() + expect(wrapper.emitted('update:content')).toBeUndefined() + }) + + it('skips grid initialisation when the export has no init()', async () => { + gridstack.mode = 'no-init' + const wrapper = mountContainer() + await flushPromises() + expect(wrapper.findAll('.container-widget__child')).toHaveLength(2) + expect(wrapper.vm.gridInstance).toBeNull() + expect(gridstack.init).not.toHaveBeenCalled() + // A repeated initialisation resolves quietly instead of rejecting. + await expect(wrapper.vm.initInnerGrid()).resolves.toBeUndefined() + expect(wrapper.vm.gridInstance).toBeNull() + }) + + it('does not initialise a grid once the inner host has been unmounted', async () => { + const wrapper = mountContainer() + await flushPromises() + expect(gridstack.init).toHaveBeenCalledTimes(1) + const vm = wrapper.vm + wrapper.unmount() + await vm.initInnerGrid() + expect(gridstack.init).toHaveBeenCalledTimes(1) + expect(vm.gridInstance).toBeNull() + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ContainerWidget.groupTiles.spec.js b/src/components/Widgets/Renderers/__tests__/ContainerWidget.groupTiles.spec.js new file mode 100644 index 000000000..f08f4c648 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ContainerWidget.groupTiles.spec.js @@ -0,0 +1,139 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * A tile inside a group opens the tile form from its own tile menu in edit + * mode (tile-form-board-sync REQ-TILE-041): ContainerChild shows the menu, + * ContainerWidget hands the edit or delete to the dashboard's opener. + * + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ContainerChild from '../ContainerChild.vue' +import ContainerWidget from '../ContainerWidget.vue' +import { readTileUse } from '../../../../utils/tileSort.js' + +const CnWidgetEditCog = { + name: 'CnWidgetEditCog', + props: ['menuLabel', 'editLabel', 'deleteLabel'], + emits: ['edit', 'remove'], + template: '<div class="cog" :data-menu="menuLabel"><button class="edit" @click="$emit(\'edit\')">{{ editLabel }}</button><button class="remove" @click="$emit(\'remove\')">{{ deleteLabel }}</button></div>', +} + +const tile = { type: 'tile', content: { title: 'Case system', linkType: 'url', linkValue: 'https://cases.example.org' } } +const bookmark = { type: 'link', content: { label: 'Intranet', url: 'https://intranet.example.org', actionType: 'external' } } +const label = { type: 'label', content: { text: 'Hello' } } + +beforeEach(() => { + globalThis.t = (_app, key) => key +}) + +/** + * Mount a child. + * + * @param {object} placement The child. + * @param {object} [props] More props. + * @return {object} The wrapper. + */ +function mountChild(placement, props = {}) { + return mount(ContainerChild, { + props: { placement, editMode: true, canEditTile: true, ...props }, + global: { stubs: { CnWidgetEditCog } }, + }) +} + +describe('ContainerChild — the tile menu of a tile in a group', () => { + it('shows the tile menu on a tile and on an address link in edit mode', () => { + for (const child of [tile, bookmark]) { + const wrapper = mountChild(child) + const menu = wrapper.find('[data-testid="container-child-tile-menu"]') + expect(menu.exists()).toBe(true) + expect(menu.find('.cog').attributes('data-menu')).toBe('Tile menu') + expect(menu.find('.edit').text()).toBe('Edit tile') + expect(menu.find('.remove').text()).toBe('Delete tile') + } + }) + + it('shows no tile menu in view mode, without an opener, or on another widget', () => { + expect(mountChild(tile, { editMode: false }).find('[data-testid="container-child-tile-menu"]').exists()).toBe(false) + expect(mountChild(tile, { canEditTile: false }).find('[data-testid="container-child-tile-menu"]').exists()).toBe(false) + expect(mountChild(label).find('[data-testid="container-child-tile-menu"]').exists()).toBe(false) + expect(mountChild({ type: 'tile', content: { linkType: 'create', linkValue: 'docx' } }).find('[data-testid="container-child-tile-menu"]').exists()).toBe(false) + }) + + it('emits editTile and removeTile from the menu', async () => { + const wrapper = mountChild(tile) + await wrapper.find('.edit').trigger('click') + await wrapper.find('.remove').trigger('click') + expect(wrapper.emitted('editTile')).toHaveLength(1) + expect(wrapper.emitted('removeTile')).toHaveLength(1) + }) +}) + +/** + * Mount a group. + * + * @param {object} props The props. + * @param {Function|null} opener The dashboard's opener. + * @return {object} The wrapper. + */ +function mountGroup(props, opener) { + return mount(ContainerWidget, { + props, + global: { + stubs: { CnWidgetEditCog }, + provide: opener ? { openGroupTileEditor: opener } : {}, + }, + }) +} + +describe('ContainerWidget — hands a group tile to the dashboard', () => { + const content = { title: 'Work apps', sortBy: 'alphabetical', placements: [label, bookmark, tile] } + + it('opens the form for the child at its stored position', async () => { + const opener = vi.fn() + const wrapper = mountGroup({ content, placement: { id: 41 }, editMode: true }, opener) + const edits = wrapper.findAll('.edit') + expect(edits).toHaveLength(2) + await edits[1].trigger('click') + expect(opener).toHaveBeenCalledWith({ containerId: 41, index: 2, remove: false }) + await wrapper.findAll('.remove')[0].trigger('click') + expect(opener).toHaveBeenLastCalledWith({ containerId: 41, index: 1, remove: true }) + }) + + it('offers no tile menu without an opener, a placement id, or in view mode', () => { + expect(mountGroup({ content, placement: { id: 41 }, editMode: true }, null).vm.canEditTiles).toBe(false) + expect(mountGroup({ content, placement: {}, editMode: true }, vi.fn()).vm.canEditTiles).toBe(false) + expect(mountGroup({ content, placement: { id: 41 }, editMode: false }, vi.fn()).vm.canEditTiles).toBe(false) + }) + + it('opens nothing while the shown order is not the stored one', () => { + const opener = vi.fn() + const wrapper = mountGroup({ content, placement: { id: 41 }, editMode: false }, opener) + wrapper.vm.editTile(2) + expect(opener).not.toHaveBeenCalled() + }) +}) + +describe('ContainerWidget — a click counts a use of the cell it landed in', () => { + it('counts the child of this grid, also when the click lands in a group inside it', async () => { + localStorage.clear() + const inner = { id: 'inner', type: 'container', content: { placements: [{ ...tile, id: 'deep' }] } } + const wrapper = mountGroup({ + content: { placements: [{ ...label, id: 'first' }, inner] }, + placement: { id: 41 }, + editMode: false, + }, vi.fn()) + const cells = wrapper.findAll('.launchpad-container-grid > [data-launchpad-child]') + expect(cells).toHaveLength(2) + await cells[0].trigger('click') + expect(readTileUse().first.count).toBe(1) + const deep = cells[1].findAll('[data-launchpad-child]') + const target = deep.length > 0 ? deep[0] : cells[1] + await target.trigger('click') + expect(readTileUse().inner.count).toBe(1) + wrapper.unmount() + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ContainerWidget.persist.spec.js b/src/components/Widgets/Renderers/__tests__/ContainerWidget.persist.spec.js new file mode 100644 index 000000000..84bb65e30 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ContainerWidget.persist.spec.js @@ -0,0 +1,68 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for how `ContainerWidget.vue` keeps its children's + * positions in sync (REQ-CONT-005): a GridStack `change` maps moved nodes + * back onto `content.placements[]` by their index and emits the whole + * content with the new placements. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it } from 'vitest' +import ContainerWidget from '../ContainerWidget.vue' + +const PLACEMENTS = [ + { id: 1, type: 'label', content: { text: 'A' }, gridX: 0, gridY: 0, gridWidth: 2, gridHeight: 2 }, + { id: 2, type: 'label', content: { text: 'B' }, gridX: 2, gridY: 0, gridWidth: 2, gridHeight: 2 }, +] + +function mountContainer(content = { title: 'Box', placements: PLACEMENTS }) { + return mount(ContainerWidget, { + props: { content }, + global: { stubs: { ContainerChild: true } }, + }) +} + +const node = (index, x, y, w, h) => ({ el: { dataset: { launchpadIndex: String(index) } }, x, y, w, h }) + +beforeEach(() => { + globalThis.t = (_app, key) => key +}) + +describe('ContainerWidget persistence', () => { + it('writes a moved node\'s position onto its placement and keeps the rest', () => { + const wrapper = mountContainer() + + wrapper.vm.onGridChange({}, [node(1, 4, 3, 1, 5)]) + + expect(wrapper.emitted('update:content')).toEqual([[{ + title: 'Box', + placements: [ + PLACEMENTS[0], + { ...PLACEMENTS[1], gridX: 4, gridY: 3, gridWidth: 1, gridHeight: 5 }, + ], + }]]) + }) + + it('ignores nodes without an element or with an unknown index', () => { + const wrapper = mountContainer() + + wrapper.vm.onGridChange({}, [{ x: 9, y: 9, w: 9, h: 9 }, node(7, 1, 1, 1, 1), { el: {}, x: 0 }]) + + expect(wrapper.emitted('update:content')[0][0].placements).toEqual(PLACEMENTS) + }) + + it('emits nothing for an empty or missing node list', () => { + const wrapper = mountContainer() + wrapper.vm.onGridChange({}, []) + wrapper.vm.onGridChange({}, undefined) + expect(wrapper.emitted('update:content')).toBeUndefined() + }) + + it('persists a non-array as no placements', () => { + const wrapper = mountContainer({ placements: PLACEMENTS }) + wrapper.vm.handlePersist(null) + expect(wrapper.emitted('update:content')).toEqual([[{ placements: [] }]]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ContainerWidget.sort.spec.js b/src/components/Widgets/Renderers/__tests__/ContainerWidget.sort.spec.js new file mode 100644 index 000000000..83762081b --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ContainerWidget.sort.spec.js @@ -0,0 +1,166 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the sorted view of `ContainerWidget.vue` + * (launcher-tile-sorting REQ-TSO-001..003): view mode reflows the tiles in + * the chosen order without writing it back, edit mode shows the stored + * layout, clicks are counted in this browser only, "Forget my usage" + * clears them, and the order is announced. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ContainerWidget from '../ContainerWidget.vue' +import { readTileUse, TILE_USE_KEY } from '../../../../utils/tileSort.js' + +const axiosPost = vi.fn(() => Promise.resolve({})) +vi.mock('@nextcloud/axios', () => ({ + default: { post: (...args) => axiosPost(...args), get: () => Promise.resolve({ data: { enabled: true } }) }, +})) + +const tile = (id, title, x) => ({ id, type: 'label', content: { title, text: title }, gridX: x, gridY: 0, gridWidth: 1, gridHeight: 1 }) + +// "Zaaksysteem", "Agenda" and "Mail", placed in that order. +const applicaties = () => [tile(1, 'Zaaksysteem', 0), tile(2, 'Agenda', 1), tile(3, 'Mail', 2)] + +/** + * Mount a container. + * + * @param {object} content The container content. + * @param {boolean} editMode Edit mode. + * @return {object} The wrapper. + */ +function mountContainer(content, editMode = false) { + return mount(ContainerWidget, { props: { content, editMode } }) +} + +/** + * The shown children as [id, gridX]. + * + * @param {object} wrapper The wrapper. + * @return {Array<Array<number>>} + */ +function shown(wrapper) { + return wrapper.vm.displayedChildren.map((c) => [c.id, c.gridX]) +} + +beforeEach(() => { + localStorage.clear() + axiosPost.mockClear() + globalThis.t = (_app, key) => key +}) + +describe('ContainerWidget sorting — REQ-TSO-001', () => { + it('shows Agenda, Mail, Zaaksysteem left to right when sorted alphabetically', () => { + const wrapper = mountContainer({ placements: applicaties(), sortBy: 'alphabetical' }) + expect(shown(wrapper)).toEqual([[2, 0], [3, 1], [1, 2]]) + const items = wrapper.findAll('.container-widget__child') + expect(items.map((item) => item.attributes('gs-x'))).toEqual(['0', '1', '2']) + }) + + it('shows the stored order by hand, and in edit mode whatever the sort', () => { + expect(shown(mountContainer({ placements: applicaties(), sortBy: 'manual' }))).toEqual([[1, 0], [2, 1], [3, 2]]) + expect(shown(mountContainer({ placements: applicaties() }))).toEqual([[1, 0], [2, 1], [3, 2]]) + expect(shown(mountContainer({ placements: applicaties(), sortBy: 'alphabetical' }, true))).toEqual([[1, 0], [2, 1], [3, 2]]) + }) + + it('never writes the sorted order back', () => { + const wrapper = mountContainer({ placements: applicaties(), sortBy: 'alphabetical' }) + const el = { dataset: { launchpadIndex: '0' } } + wrapper.vm.onGridChange(null, [{ el, x: 3, y: 1, w: 1, h: 1 }]) + expect(wrapper.emitted('update:content')).toBeUndefined() + }) +}) + +describe('ContainerWidget most used — REQ-TSO-002', () => { + it('moves a tile opened three times to the front on the next load, and sends no counts', async () => { + const first = mountContainer({ placements: applicaties(), sortBy: 'most-used' }) + expect(shown(first)).toEqual([[2, 0], [3, 1], [1, 2]]) + + const zaaksysteem = first.findAll('.container-widget__child')[2] + await zaaksysteem.trigger('click') + await zaaksysteem.trigger('click') + await zaaksysteem.trigger('click') + expect(readTileUse()['1'].count).toBe(3) + // No jumping while clicking: the order changes on the next load. + expect(shown(first)).toEqual([[2, 0], [3, 1], [1, 2]]) + expect(axiosPost).not.toHaveBeenCalled() + + const reloaded = mountContainer({ placements: applicaties(), sortBy: 'most-used' }) + expect(shown(reloaded)[0]).toEqual([1, 0]) + }) + + it('counts children a bookmark import wrote without an id, keyed by the container', async () => { + const imported = () => applicaties().map((child) => ({ ...child, id: undefined })) + const props = { content: { placements: imported(), sortBy: 'most-used' }, placement: { id: 42 } } + const first = mount(ContainerWidget, { props }) + + const zaaksysteem = first.findAll('.container-widget__child')[2] + await zaaksysteem.trigger('click') + await zaaksysteem.trigger('click') + await zaaksysteem.trigger('click') + expect(readTileUse()['42-0'].count).toBe(3) + + const reloaded = mount(ContainerWidget, { props }) + expect(reloaded.vm.displayedChildren.map((c) => c.content.title)[0]).toBe('Zaaksysteem') + }) + + it('counts nothing in edit mode', async () => { + const wrapper = mountContainer({ placements: applicaties(), sortBy: 'most-used' }, true) + await wrapper.findAll('.container-widget__child')[0].trigger('click') + expect(localStorage.getItem(TILE_USE_KEY)).toBeNull() + }) + + it('shows the stored order without an error when storage is blocked', () => { + const spy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new Error('SecurityError') + }) + expect(shown(mountContainer({ placements: applicaties(), sortBy: 'most-used' }))).toEqual([[2, 0], [3, 1], [1, 2]]) + spy.mockRestore() + }) +}) + +describe('ContainerWidget forget my usage — REQ-TSO-003', () => { + it('offers it for most and last used only, and clears this container\'s counts', async () => { + localStorage.setItem(TILE_USE_KEY, JSON.stringify({ 1: { count: 5, lastUsedAt: 9 }, 99: { count: 1, lastUsedAt: 1 } })) + const wrapper = mountContainer({ placements: applicaties(), sortBy: 'most-used' }) + expect(shown(wrapper)[0]).toEqual([1, 0]) + + await wrapper.find('[data-testid="container-forget-usage"]').trigger('click') + + expect(readTileUse()).toEqual({ 99: { count: 1, lastUsedAt: 1 } }) + expect(shown(wrapper)).toEqual([[2, 0], [3, 1], [1, 2]]) + + expect(mountContainer({ placements: applicaties(), sortBy: 'alphabetical' }).find('[data-testid="container-forget-usage"]').exists()).toBe(false) + expect(mountContainer({ placements: applicaties(), sortBy: 'last-used' }, true).find('[data-testid="container-forget-usage"]').exists()).toBe(false) + }) +}) + +describe('ContainerWidget forget my usage on a live grid — REQ-TSO-003', () => { + it('moves the grid items to the alphabetical places at once', async () => { + localStorage.setItem(TILE_USE_KEY, JSON.stringify({ 1: { count: 5, lastUsedAt: 9 } })) + const wrapper = mountContainer({ placements: applicaties(), sortBy: 'most-used' }) + const update = vi.fn() + wrapper.vm.gridInstance = { update, batchUpdate: vi.fn() } + + await wrapper.find('[data-testid="container-forget-usage"]').trigger('click') + await wrapper.vm.$nextTick() + + const items = wrapper.findAll('.container-widget__child').map((item) => item.element) + expect(shown(wrapper)).toEqual([[2, 0], [3, 1], [1, 2]]) + expect(update.mock.calls.map(([el, opts]) => [items.indexOf(el), opts.x, opts.y])).toEqual([[0, 0, 0], [1, 1, 0], [2, 2, 0]]) + }) +}) + +describe('ContainerWidget accessible order', () => { + it('describes the grid with the sort, and says nothing by hand', () => { + const wrapper = mountContainer({ placements: applicaties(), sortBy: 'most-used' }) + const grid = wrapper.find('.launchpad-container-grid') + const description = wrapper.find(`#${grid.attributes('aria-describedby')}`) + expect(description.text()).toBe('Sorted by most used') + + const manual = mountContainer({ placements: applicaties() }) + expect(manual.find('.launchpad-container-grid').attributes('aria-describedby')).toBeUndefined() + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/ContainerWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/ContainerWidgetForm.spec.js new file mode 100644 index 000000000..bd542e579 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ContainerWidgetForm.spec.js @@ -0,0 +1,62 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `ContainerWidgetForm.vue` (launcher-tile-sorting, + * REQ-CONT-007): the three communal fields plus exactly one "Sort tiles" + * select, seeded from the widget being edited, and every emit carrying the + * communal fields together with `sortBy`. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import ContainerWidgetForm from '../ContainerWidgetForm.vue' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnContainerWidgetForm: { + name: 'CnContainerWidgetForm', + props: ['editingWidget', 'value'], + emits: ['update:content'], + template: '<div class="communal-form" />', + }, +})) + +vi.mock('@nextcloud/vue', () => ({ + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel'], + emits: ['update:modelValue'], + template: '<div class="nc-select" :data-label="inputLabel" />', + }, +})) + +describe('ContainerWidgetForm', () => { + it('renders the communal form plus one "Sort tiles" select, by hand by default', () => { + const wrapper = mount(ContainerWidgetForm) + expect(wrapper.findAll('.communal-form')).toHaveLength(1) + const selects = wrapper.findAllComponents({ name: 'NcSelect' }) + expect(selects).toHaveLength(1) + expect(selects[0].props('inputLabel')).toBe('Sort tiles') + expect(selects[0].props('modelValue')).toBe('manual') + expect(selects[0].props('options').map((o) => o.value)).toEqual(['manual', 'alphabetical', 'most-used', 'last-used', 'random']) + }) + + it('seeds the sort from the widget being edited, and an unknown one as by hand', () => { + const edited = mount(ContainerWidgetForm, { props: { editingWidget: { content: { title: 'Apps', sortBy: 'most-used' } } } }) + expect(edited.vm.sortBy).toBe('most-used') + const unknown = mount(ContainerWidgetForm, { props: { value: { sortBy: 'colour' } } }) + expect(unknown.vm.sortBy).toBe('manual') + }) + + it('emits the communal fields together with the sort', async () => { + const placements = [{ id: 1 }] + const wrapper = mount(ContainerWidgetForm, { props: { editingWidget: { content: { placements, title: 'Apps', sortBy: 'random' } } } }) + + wrapper.findComponent({ name: 'CnContainerWidgetForm' }).vm.$emit('update:content', { placements, backgroundColor: '#fff', padding: 'small', title: 'Applicaties' }) + expect(wrapper.emitted('update:content').at(-1)[0]).toEqual({ placements, backgroundColor: '#fff', padding: 'small', title: 'Applicaties', sortBy: 'random' }) + + wrapper.findComponent({ name: 'NcSelect' }).vm.$emit('update:modelValue', 'alphabetical') + expect(wrapper.emitted('update:content').at(-1)[0]).toEqual({ placements, backgroundColor: '#fff', padding: 'small', title: 'Applicaties', sortBy: 'alphabetical' }) + expect(wrapper.vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/FilesWidget.interactions.spec.js b/src/components/Widgets/Renderers/__tests__/FilesWidget.interactions.spec.js new file mode 100644 index 000000000..14642e65f --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/FilesWidget.interactions.spec.js @@ -0,0 +1,514 @@ +/** + * SPDX-FileCopyrightText: 2026 LaunchPad Contributors + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `FilesWidget.vue` covering the paths the base + * spec leaves out: the unknown-error state + retry, cursor pagination + * (REQ-FLS-003), breadcrumb segment navigation and path joining + * (REQ-FLS-005), the delete modal's cancel / Escape / failure paths + * (REQ-FLS-008), the upload flow (REQ-FLS-007) and size formatting. + */ + +import axios from '@nextcloud/axios' +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import FilesWidget from '../FilesWidget.vue' + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +vi.mock('@nextcloud/axios', () => ({ + default: { + get: vi.fn(), + post: vi.fn(), + delete: vi.fn(), + }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + Object.entries(params).reduce( + (acc, [key, value]) => acc.replace(`{${key}}`, value), + path, + ), +})) + +const FILE = { + fileId: 1, + name: 'budget.pdf', + size: 12345, + modifiedAt: '2026-01-01T12:00:00Z', + isFolder: false, + canEdit: true, + canDelete: true, +} +const FOLDER = { + fileId: 2, + name: 'images', + size: 0, + modifiedAt: '2026-01-02T12:00:00Z', + isFolder: true, + canEdit: true, + canDelete: false, +} + +const CONTENTS_URL = '/apps/launchpad/api/widgets/files/7/contents' + +// Interpolating stand-in for Nextcloud's `t()`, used both by script code +// (global) and by the template (instance mock). +function tInterpolate(_app, key, vars) { + if (!vars) { + return key + } + return Object.entries(vars).reduce( + (acc, [varName, value]) => acc.replace(`{${varName}}`, value), + key, + ) +} + +function mountWidget(content = {}, placement = { id: 7 }) { + return mount(FilesWidget, { + props: { placement, content: { folderPath: '/x', ...content } }, + global: { mocks: { t: tInterpolate } }, + attachTo: document.body, + }) +} + +beforeEach(() => { + globalThis.t = tInterpolate + vi.clearAllMocks() +}) + +afterEach(() => { + document.body.innerHTML = '' + vi.restoreAllMocks() +}) + +describe('FilesWidget — fetching', () => { + it('does not request anything without a placement id', async () => { + const wrapper = mountWidget({}, {}) + await flushPromises() + + expect(axios.get).not.toHaveBeenCalled() + expect(wrapper.find('.files-widget__state--empty').exists()).toBe(true) + }) + + it('sends currentPath and limit on the first request', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE] } }) + mountWidget() + await flushPromises() + + expect(axios.get).toHaveBeenCalledWith(CONTENTS_URL, { + params: { currentPath: '/', limit: 50 }, + }) + }) + + it('treats a missing body / non-array items as an empty folder', async () => { + axios.get.mockResolvedValue({ data: { items: 'nope' } }) + const wrapper = mountWidget() + await flushPromises() + expect(wrapper.text()).toContain('This folder is empty.') + + axios.get.mockResolvedValue(undefined) + await wrapper.find('.files-widget__crumb--root').trigger('click') + await flushPromises() + expect(wrapper.text()).toContain('This folder is empty.') + expect(wrapper.find('.files-widget__pagination').exists()).toBe(false) + }) + + it('shows the generic error with a Retry button that refetches', async () => { + axios.get.mockRejectedValueOnce({ response: { status: 500 } }) + const wrapper = mountWidget({ allowUpload: true }) + await flushPromises() + + const errorState = wrapper.find('.files-widget__state--error') + expect(errorState.exists()).toBe(true) + expect(errorState.text()).toContain('Failed to load folder contents.') + // Upload is hidden while in an error state. + expect(wrapper.find('.files-widget__upload').exists()).toBe(false) + + axios.get.mockResolvedValueOnce({ data: { items: [FILE] } }) + await wrapper.find('.files-widget__retry').trigger('click') + await flushPromises() + + expect(axios.get).toHaveBeenCalledTimes(2) + expect(wrapper.find('.files-widget__state--error').exists()).toBe(false) + expect(wrapper.text()).toContain('budget.pdf') + }) + + it('maps an error body code without status to the matching state', async () => { + axios.get.mockRejectedValueOnce({ response: { data: { error: 'no_access' } } }) + const wrapper = mountWidget() + await flushPromises() + expect(wrapper.find('.files-widget__state--no-access').exists()).toBe(true) + + axios.get.mockRejectedValueOnce(new Error('network')) + await wrapper.find('.files-widget__crumb--root').trigger('click') + await flushPromises() + expect(wrapper.find('.files-widget__state--error').exists()).toBe(true) + }) + + it('shows the loading state while a request is pending', async () => { + let resolve + axios.get.mockReturnValue(new Promise((r) => { resolve = r })) + const wrapper = mountWidget() + await flushPromises() + + expect(wrapper.text()).toContain('Loading folder…') + resolve({ data: { items: [FILE] } }) + await flushPromises() + expect(wrapper.text()).not.toContain('Loading folder…') + expect(wrapper.text()).toContain('budget.pdf') + }) + + it('refetches from root when the placement prop changes', async () => { + axios.get.mockResolvedValue({ data: { items: [FOLDER] } }) + const wrapper = mountWidget() + await flushPromises() + await wrapper.find('.files-widget__row-name').trigger('click') + await flushPromises() + expect(axios.get).toHaveBeenLastCalledWith(CONTENTS_URL, { + params: { currentPath: '/images', limit: 50 }, + }) + + await wrapper.setProps({ placement: { id: 9 } }) + await flushPromises() + expect(axios.get).toHaveBeenLastCalledWith( + '/apps/launchpad/api/widgets/files/9/contents', + { params: { currentPath: '/', limit: 50 } }, + ) + expect(wrapper.findAll('.files-widget__crumb')).toHaveLength(1) + }) +}) + +describe('FilesWidget — pagination', () => { + it('Load more appends the next page using the cursor', async () => { + axios.get.mockResolvedValueOnce({ data: { items: [FILE], nextCursor: 'c1' } }) + const wrapper = mountWidget() + await flushPromises() + + expect(wrapper.find('.files-widget__more').exists()).toBe(true) + + axios.get.mockResolvedValueOnce({ data: { items: [FOLDER], nextCursor: null } }) + await wrapper.find('.files-widget__more').trigger('click') + await flushPromises() + + expect(axios.get).toHaveBeenLastCalledWith(CONTENTS_URL, { + params: { currentPath: '/', limit: 50, cursor: 'c1' }, + }) + const labels = wrapper.findAll('.files-widget__row-label').map((w) => w.text()) + expect(labels).toEqual(['budget.pdf', 'images']) + expect(wrapper.find('.files-widget__pagination').exists()).toBe(false) + }) + + it('a failed next page keeps the already loaded items and cursor', async () => { + axios.get.mockResolvedValueOnce({ data: { items: [FILE], nextCursor: 'c1' } }) + const wrapper = mountWidget() + await flushPromises() + + axios.get.mockRejectedValueOnce({ response: { status: 500 } }) + await wrapper.find('.files-widget__more').trigger('click') + await flushPromises() + + expect(wrapper.vm.items).toEqual([FILE]) + expect(wrapper.vm.nextCursor).toBe('c1') + expect(wrapper.find('.files-widget__state--error').exists()).toBe(true) + }) + + it('loadMore is a no-op without a cursor', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE] } }) + const wrapper = mountWidget() + await flushPromises() + + wrapper.vm.loadMore() + await flushPromises() + expect(axios.get).toHaveBeenCalledTimes(1) + }) +}) + +describe('FilesWidget — navigation', () => { + it('clicking a middle breadcrumb navigates to that segment', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE] } }) + const wrapper = mountWidget() + await flushPromises() + + wrapper.vm.navigateTo('/a/b/c') + await flushPromises() + + const crumbs = wrapper.findAll('.files-widget__crumb') + expect(crumbs.map((c) => c.text())).toEqual(['Root', 'a', 'b', 'c']) + expect(crumbs.at(0).attributes('aria-current')).toBeUndefined() + expect(crumbs.at(3).attributes('aria-current')).toBe('page') + expect(crumbs.at(2).attributes('aria-current')).toBeUndefined() + + await crumbs.at(2).trigger('click') + await flushPromises() + + expect(axios.get).toHaveBeenLastCalledWith(CONTENTS_URL, { + params: { currentPath: '/a/b', limit: 50 }, + }) + expect(wrapper.findAll('.files-widget__crumb').map((c) => c.text())) + .toEqual(['Root', 'a', 'b']) + }) + + it('root crumb is aria-current at root', async () => { + axios.get.mockResolvedValue({ data: { items: [] } }) + const wrapper = mountWidget() + await flushPromises() + expect(wrapper.find('.files-widget__crumb--root').attributes('aria-current')) + .toBe('page') + }) + + it('navigateTo with a falsy path resets to root', async () => { + axios.get.mockResolvedValue({ data: { items: [] } }) + const wrapper = mountWidget() + await flushPromises() + wrapper.vm.navigateTo('') + await flushPromises() + expect(axios.get).toHaveBeenLastCalledWith(CONTENTS_URL, { + params: { currentPath: '/', limit: 50 }, + }) + }) + + it('descending from a sub-folder joins the path with a single slash', async () => { + axios.get.mockResolvedValue({ data: { items: [FOLDER] } }) + const wrapper = mountWidget() + await flushPromises() + + wrapper.vm.navigateTo('/a/') + await flushPromises() + await wrapper.find('.files-widget__row-name').trigger('click') + await flushPromises() + + expect(axios.get).toHaveBeenLastCalledWith(CONTENTS_URL, { + params: { currentPath: '/a/images', limit: 50 }, + }) + }) + + it('joinPath tolerates stray slashes and empty values', async () => { + axios.get.mockResolvedValue({ data: { items: [] } }) + const wrapper = mountWidget() + await flushPromises() + + expect(wrapper.vm.joinPath('/', '/x')).toBe('/x') + expect(wrapper.vm.joinPath('', 'x')).toBe('/x') + expect(wrapper.vm.joinPath('/a//', '//b')).toBe('/a/b') + expect(wrapper.vm.joinPath('/a', undefined)).toBe('/a/') + }) + + it('a file without a fileId does not open a window', async () => { + axios.get.mockResolvedValue({ data: { items: [{ ...FILE, fileId: 0 }] } }) + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null) + const wrapper = mountWidget() + await flushPromises() + + await wrapper.find('.files-widget__row-name').trigger('click') + expect(openSpy).not.toHaveBeenCalled() + }) + + it('the deep link url-encodes the file id', async () => { + axios.get.mockResolvedValue({ data: { items: [{ ...FILE, fileId: 'a b' }] } }) + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null) + const wrapper = mountWidget() + await flushPromises() + + await wrapper.find('.files-widget__row-name').trigger('click') + expect(openSpy).toHaveBeenCalledWith( + '/apps/files/?fileid=a%20b', + '_blank', + 'noopener,noreferrer', + ) + }) +}) + +describe('FilesWidget — delete', () => { + async function openConfirm() { + axios.get.mockResolvedValue({ data: { items: [FILE, FOLDER] } }) + const wrapper = mountWidget({ allowDelete: true }) + await flushPromises() + const button = wrapper.find('.files-widget__row-delete') + expect(button.attributes('aria-label')).toBe('Delete budget.pdf') + await button.trigger('click') + await wrapper.vm.$nextTick() + return wrapper + } + + it('opening the confirm dialog names the file and focuses the dialog', async () => { + const wrapper = await openConfirm() + const dialog = wrapper.find('.files-widget__modal-backdrop') + expect(dialog.exists()).toBe(true) + expect(dialog.text()).toContain('Are you sure you want to delete budget.pdf?') + expect(document.activeElement).toBe(dialog.element) + }) + + it('Cancel closes the dialog without deleting', async () => { + const wrapper = await openConfirm() + const cancel = wrapper.findAll('.files-widget__modal-actions button').at(0) + expect(cancel.text()).toBe('Cancel') + await cancel.trigger('click') + + expect(wrapper.find('.files-widget__modal-backdrop').exists()).toBe(false) + expect(axios.delete).not.toHaveBeenCalled() + }) + + it('Escape closes the dialog', async () => { + const wrapper = await openConfirm() + await wrapper.find('.files-widget__modal-backdrop').trigger('keydown.esc') + expect(wrapper.find('.files-widget__modal-backdrop').exists()).toBe(false) + expect(axios.delete).not.toHaveBeenCalled() + }) + + it('clicking the backdrop itself closes the dialog, clicking inside does not', async () => { + const wrapper = await openConfirm() + await wrapper.find('.files-widget__modal').trigger('click') + expect(wrapper.find('.files-widget__modal-backdrop').exists()).toBe(true) + + await wrapper.find('.files-widget__modal-backdrop').trigger('click') + expect(wrapper.find('.files-widget__modal-backdrop').exists()).toBe(false) + }) + + it('a failed delete refetches the listing and closes the dialog', async () => { + const wrapper = await openConfirm() + axios.delete.mockRejectedValueOnce(new Error('boom')) + + await wrapper.find('.files-widget__modal-confirm').trigger('click') + await flushPromises() + + expect(axios.delete).toHaveBeenCalledWith( + '/apps/launchpad/api/widgets/files/7/files/1', + ) + expect(axios.get).toHaveBeenCalledTimes(2) + expect(wrapper.find('.files-widget__modal-backdrop').exists()).toBe(false) + expect(wrapper.text()).toContain('budget.pdf') + }) + + it('performDelete without a target does nothing', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE] } }) + const wrapper = mountWidget({ allowDelete: true }) + await flushPromises() + + await wrapper.vm.performDelete() + expect(axios.delete).not.toHaveBeenCalled() + }) +}) + +describe('FilesWidget — upload', () => { + function fakeFiles(...names) { + return names.map((name) => new File(['x'], name, { type: 'text/plain' })) + } + + it('the Upload button clicks the hidden file input', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE] } }) + const wrapper = mountWidget({ allowUpload: true }) + await flushPromises() + + const input = wrapper.find('input[type="file"]') + const clickSpy = vi.spyOn(input.element, 'click') + await wrapper.find('.files-widget__upload').trigger('click') + expect(clickSpy).toHaveBeenCalledTimes(1) + }) + + it('upload is hidden when no item is editable', async () => { + axios.get.mockResolvedValue({ data: { items: [{ ...FILE, canEdit: false }] } }) + const wrapper = mountWidget({ allowUpload: true }) + await flushPromises() + expect(wrapper.find('.files-widget__upload').exists()).toBe(false) + }) + + it('choosing files POSTs them as files[] to the current folder and refetches', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE] } }) + axios.post.mockResolvedValue({ data: {} }) + const wrapper = mountWidget({ allowUpload: true }) + await flushPromises() + wrapper.vm.navigateTo('/docs') + await flushPromises() + axios.get.mockClear() + + const files = fakeFiles('a.txt', 'b.txt') + const input = wrapper.find('input[type="file"]') + await wrapper.vm.onFileInputChange({ target: { files } }) + await flushPromises() + + expect(axios.post).toHaveBeenCalledTimes(1) + const [url, formData, config] = axios.post.mock.calls[0] + expect(url).toBe('/apps/launchpad/api/widgets/files/7/upload') + expect(formData).toBeInstanceOf(FormData) + expect(formData.getAll('files[]').map((f) => f.name)).toEqual(['a.txt', 'b.txt']) + expect(config).toEqual({ params: { currentPath: '/docs' } }) + expect(axios.get).toHaveBeenCalledWith(CONTENTS_URL, { + params: { currentPath: '/docs', limit: 50 }, + }) + expect(input.element.value).toBe('') + }) + + it('a failed upload still refetches the listing', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE] } }) + axios.post.mockRejectedValue(new Error('too big')) + const wrapper = mountWidget({ allowUpload: true }) + await flushPromises() + axios.get.mockClear() + + await wrapper.vm.onFileInputChange({ target: { files: fakeFiles('a.txt') } }) + await flushPromises() + + expect(axios.post).toHaveBeenCalledTimes(1) + expect(axios.get).toHaveBeenCalledTimes(1) + }) + + it('an empty selection uploads nothing', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE] } }) + const wrapper = mountWidget({ allowUpload: true }) + await flushPromises() + + await wrapper.find('input[type="file"]').trigger('change') + await wrapper.vm.onFileInputChange({ target: { files: [] } }) + await wrapper.vm.onFileInputChange(undefined) + await flushPromises() + + expect(axios.post).not.toHaveBeenCalled() + }) +}) + +describe('FilesWidget — search box', () => { + it('typing in the search box filters rows and shows the no-match copy', async () => { + axios.get.mockResolvedValue({ data: { items: [FILE, FOLDER] } }) + const wrapper = mountWidget() + await flushPromises() + + const search = wrapper.find('input[type="search"]') + await search.setValue('IMA') + expect(wrapper.findAll('.files-widget__row-label').map((w) => w.text())) + .toEqual(['images']) + + await search.setValue('zzz') + expect(wrapper.find('.files-widget__list').exists()).toBe(false) + expect(wrapper.text()).toContain("No files matching 'zzz'") + expect(axios.get).toHaveBeenCalledTimes(1) + }) +}) + +describe('FilesWidget — size column', () => { + it('formats sizes per unit and leaves folders blank', async () => { + axios.get.mockResolvedValue({ + data: { + items: [ + { ...FILE, fileId: 11, name: 'zero', size: 0 }, + { ...FILE, fileId: 12, name: 'bytes', size: 512 }, + { ...FILE, fileId: 13, name: 'kb', size: 1536 }, + { ...FILE, fileId: 14, name: 'mb', size: 5 * 1024 * 1024 }, + { ...FILE, fileId: 15, name: 'huge', size: 3 * 1024 ** 5 }, + { ...FILE, fileId: 16, name: 'none', size: undefined }, + FOLDER, + ], + }, + }) + const wrapper = mountWidget() + await flushPromises() + + const sizes = wrapper.findAll('.files-widget__row-size').map((w) => w.text()) + expect(sizes).toEqual(['0 B', '512 B', '1.5 KB', '5.0 MB', '3072.0 TB', '0 B', '']) + expect(wrapper.find('.files-widget__row--folder .files-widget__row-label').text()) + .toBe('images') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/IframeWidget.lifecycle.spec.js b/src/components/Widgets/Renderers/__tests__/IframeWidget.lifecycle.spec.js new file mode 100644 index 000000000..52b4b3380 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/IframeWidget.lifecycle.spec.js @@ -0,0 +1,155 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `IframeWidget.vue` (REQ-IFRAME-003/004) lifecycle: + * aspect-ratio sizing, restarting the framable check when the URL changes + * (a superseded verdict is ignored), clearing the load timer on unmount, and + * ignoring a late `load` event once the embed has settled. + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import IframeWidget from '../IframeWidget.vue' +import { checkIframeFramable } from '../../../../services/iframeClient.js' + +vi.mock('../../../../services/iframeClient.js', () => ({ + checkIframeFramable: vi.fn(() => + Promise.resolve({ framable: true, reason: 'ok' }), + ), +})) + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +function deferred() { + let resolve + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + +beforeEach(() => { + checkIframeFramable.mockReset() + checkIframeFramable.mockResolvedValue({ framable: true, reason: 'ok' }) + globalThis.t = (_app, key, vars) => { + if (vars && typeof key === 'string') { + return key.replace(/\{(\w+)\}/g, (_, name) => + Object.hasOwn(vars, name) ? vars[name] : `{${name}}`, + ) + } + return key + } +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('IframeWidget — sizing', () => { + it('sizes the wrapper by aspect ratio with an automatic height', () => { + const wrapper = mount(IframeWidget, { + propsData: { + content: { url: 'https://a.example.com/', aspect: '16:9', height: 250 }, + }, + }) + expect(wrapper.attributes('style')).toContain('aspect-ratio: 16 / 9') + expect(wrapper.element.style.height).toBe('auto') + }) + + it('uses the configured fixed height when no aspect ratio is set', () => { + const wrapper = mount(IframeWidget, { + propsData: { content: { url: 'https://a.example.com/', height: 250 } }, + }) + expect(wrapper.element.style.height).toBe('250px') + }) +}) + +describe('IframeWidget — REQ-IFRAME-003 re-check on URL change', () => { + it('re-checks the new URL and ignores the superseded verdict for the old one', async () => { + const first = deferred() + checkIframeFramable.mockReturnValueOnce(first.promise) + const wrapper = mount(IframeWidget, { + propsData: { content: { url: 'https://old.example.com/', title: 'Old' } }, + }) + expect(checkIframeFramable).toHaveBeenCalledWith('https://old.example.com/') + + await wrapper.setProps({ + content: { url: 'https://new.example.com/', title: 'New' }, + }) + expect(checkIframeFramable).toHaveBeenLastCalledWith( + 'https://new.example.com/', + ) + expect(checkIframeFramable).toHaveBeenCalledTimes(2) + await flushPromises() + expect(wrapper.find('iframe').attributes('src')).toBe( + 'https://new.example.com/', + ) + + // The old target's late "refuses framing" verdict must not flip the + // new, framable embed into the fallback card. + first.resolve({ framable: false, reason: 'x-frame-options' }) + await flushPromises() + expect(wrapper.find('.iframe-widget__fallback').exists()).toBe(false) + expect(wrapper.find('iframe').exists()).toBe(true) + }) + + it('switches to the not-configured fallback when the URL is cleared', async () => { + const wrapper = mount(IframeWidget, { + propsData: { content: { url: 'https://a.example.com/' } }, + }) + await flushPromises() + expect(wrapper.find('iframe').exists()).toBe(true) + await wrapper.setProps({ content: { url: ' ' } }) + expect(wrapper.find('iframe').exists()).toBe(false) + expect(wrapper.find('.iframe-widget__fallback').text()).toContain( + 'This embed has not been configured yet.', + ) + expect(checkIframeFramable).toHaveBeenCalledTimes(1) + }) +}) + +describe('IframeWidget — REQ-IFRAME-004 timer and late load events', () => { + it('clears the pending load-timeout timer on unmount', async () => { + const wrapper = mount(IframeWidget, { + propsData: { + content: { url: 'https://a.example.com/' }, + loadTimeoutMs: 60000, + }, + }) + await flushPromises() + const timer = wrapper.vm.loadTimer + expect(timer).not.toBeNull() + const clearSpy = vi.spyOn(globalThis, 'clearTimeout') + wrapper.unmount() + expect(clearSpy).toHaveBeenCalledWith(timer) + }) + + it('ignores a blank-document load event once the embed is already ready', async () => { + const wrapper = mount(IframeWidget, { + propsData: { content: { url: 'https://a.example.com/', title: 'A' } }, + }) + await flushPromises() + const frame = wrapper.find('iframe') + Object.defineProperty(frame.element, 'contentDocument', { + configurable: true, + get: () => null, + }) + await frame.trigger('load') + expect(frame.element.style.display).toBe('block') + + // The embedded page navigates to an empty same-origin document later; + // that must not turn a working embed into the "blocked" fallback. + Object.defineProperty(frame.element, 'contentDocument', { + configurable: true, + get: () => ({ body: { children: [], textContent: '' } }), + }) + await frame.trigger('load') + await flushPromises() + expect(wrapper.find('.iframe-widget__fallback').exists()).toBe(false) + expect(wrapper.find('iframe').element.style.display).toBe('block') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/IframeWidget.spec.js b/src/components/Widgets/Renderers/__tests__/IframeWidget.spec.js index e650881ec..223101f1b 100644 --- a/src/components/Widgets/Renderers/__tests__/IframeWidget.spec.js +++ b/src/components/Widgets/Renderers/__tests__/IframeWidget.spec.js @@ -166,6 +166,21 @@ describe('IframeWidget — REQ-IFRAME-003 graceful degradation', () => { expect(checkIframeFramable).toHaveBeenCalledWith('https://github.com/') }) + it('says the embed is no longer permitted when its host was taken off the allow-list (REQ-IFRAME-002)', async () => { + checkIframeFramable.mockResolvedValue({ framable: false, reason: 'host_not_allowed' }) + const wrapper = mount(IframeWidget, { + propsData: { + content: { url: 'https://status.example.com/board', title: 'Status' }, + loadTimeoutMs: TEST_TIMEOUT_MS, + }, + }) + await flushPromises() + const fallback = wrapper.find('.iframe-widget__fallback') + expect(fallback.text()).toContain('This embed is no longer permitted by your administrator') + expect(fallback.text()).not.toContain('does not allow itself to be embedded') + expect(wrapper.find('iframe').exists()).toBe(false) + }) + it('does NOT render the iframe while the framable check is still pending (prevents the blocked-frame load event from masking the fallback)', async () => { // Regression: a live XFO-deny target fires a browser "refused to // connect" load event with a null contentDocument that onLoad cannot @@ -297,3 +312,101 @@ describe('IframeWidget — REQ-IFRAME-003 graceful degradation', () => { expect(wrapper.find('.iframe-widget__fallback').exists()).toBe(true) }) }) + +describe('IframeWidget outage state (REQ-IFRAME-005)', () => { + it('shows the outage with the cause, its time, Reload and Open in a new tab', async () => { + checkIframeFramable.mockResolvedValue({ framable: false, reason: 'x_frame_options' }) + const wrapper = mount(IframeWidget, { + propsData: { + content: { url: 'https://app.powerbi.com/r', title: 'Sales', kind: 'report' }, + loadTimeoutMs: TEST_TIMEOUT_MS, + }, + }) + await flushPromises() + const outage = wrapper.find('[data-testid="iframe-widget-outage"]') + expect(outage.exists()).toBe(true) + expect(outage.text()).toContain('The report could not be loaded') + expect(wrapper.find('[data-testid="iframe-widget-outage-cause"]').text()) + .toMatch(/^Gave an error today at \d\d:\d\d: the site refuses to be embedded$/) + expect(wrapper.find('[data-testid="iframe-widget-reload"]').exists()).toBe(true) + expect(wrapper.find('.iframe-widget__fallback-link').text()).toContain('Open in a new tab') + const statuses = wrapper.emitted('status') + expect(statuses.at(-1)[0]).toEqual({ subtitle: 'Embedded report · app.powerbi.com', outage: true }) + }) + + it('prefers the connection cause and time and names the signed-in account', async () => { + checkIframeFramable.mockResolvedValue({ framable: false, reason: 'unreachable' }) + const errorAt = new Date() + errorAt.setHours(9, 30, 0, 0) + const wrapper = mount(IframeWidget, { + propsData: { + content: { + url: 'https://app.powerbi.com/r', + kind: 'report', + connection: { account: 'Pieter Jansen', error: 'token expired', errorAt: errorAt.toISOString() }, + }, + loadTimeoutMs: TEST_TIMEOUT_MS, + }, + }) + await flushPromises() + expect(wrapper.find('[data-testid="iframe-widget-outage-cause"]').text()).toBe('Gave an error today at 09:30: token expired') + expect(wrapper.emitted('status').at(-1)[0].subtitle).toBe('Embedded report · app.powerbi.com · Signed in as Pieter Jansen') + }) + + it('shows the outage without a cause line when the cause is unknown', async () => { + checkIframeFramable.mockResolvedValue({ framable: false, reason: 'check_unavailable' }) + const wrapper = mount(IframeWidget, { + propsData: { content: { url: 'https://example.com/' }, loadTimeoutMs: TEST_TIMEOUT_MS }, + }) + await flushPromises() + expect(wrapper.find('[data-testid="iframe-widget-outage"]').text()).toContain('The page could not be loaded') + expect(wrapper.find('[data-testid="iframe-widget-outage-cause"]').exists()).toBe(false) + expect(wrapper.emitted('status').at(-1)[0].outage).toBe(true) + }) + + it('reloads: Reload runs the check again and shows the frame once it passes', async () => { + checkIframeFramable.mockResolvedValueOnce({ framable: false, reason: 'unreachable' }) + const wrapper = mount(IframeWidget, { + propsData: { content: { url: 'https://example.com/' }, loadTimeoutMs: 5000 }, + }) + await flushPromises() + await wrapper.find('[data-testid="iframe-widget-reload"]').trigger('click') + await flushPromises() + expect(checkIframeFramable).toHaveBeenCalledTimes(2) + expect(wrapper.find('iframe').exists()).toBe(true) + expect(wrapper.emitted('status').at(-1)[0].outage).toBe(false) + }) + + it('is no outage when the host is not permitted or nothing is configured', async () => { + checkIframeFramable.mockResolvedValue({ framable: false, reason: 'host_not_allowed' }) + const refused = mount(IframeWidget, { + propsData: { content: { url: 'https://example.com/' }, loadTimeoutMs: TEST_TIMEOUT_MS }, + }) + await flushPromises() + expect(refused.find('[data-testid="iframe-widget-fallback"]').exists()).toBe(true) + expect(refused.find('[data-testid="iframe-widget-reload"]').exists()).toBe(false) + expect(refused.emitted('status').at(-1)[0].outage).toBe(false) + + const empty = mount(IframeWidget, { propsData: { content: {} } }) + await flushPromises() + expect(empty.emitted('status').at(-1)[0]).toEqual({ subtitle: '', outage: false }) + }) +}) + +// @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-reader-can-download-the-dashboard-req-dpd-003 +describe('IframeWidget — REQ-DPD-003 in a downloaded dashboard', () => { + it('names the embedded page with a line that it is not included', async () => { + const wrapper = mount(IframeWidget, { + propsData: { content: { url: 'https://bi.example.com/report', title: 'Rapport Sociaal domein' } }, + }) + await flushPromises() + const note = wrapper.find('[data-testid="iframe-widget-print-note"]') + expect(note.exists()).toBe(true) + expect(note.text()).toBe('Rapport Sociaal domein: embedded pages are not included in the download') + }) + + it('names an untitled embed as an embedded page', () => { + const wrapper = mount(IframeWidget, { propsData: { content: { url: 'https://bi.example.com/report' } } }) + expect(wrapper.find('[data-testid="iframe-widget-print-note"]').text()).toBe('Embedded page: embedded pages are not included in the download') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/IframeWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/IframeWidgetForm.spec.js index 53739c525..288180074 100644 --- a/src/components/Widgets/Renderers/__tests__/IframeWidgetForm.spec.js +++ b/src/components/Widgets/Renderers/__tests__/IframeWidgetForm.spec.js @@ -154,7 +154,7 @@ describe('IframeWidgetForm — REQ-IFRAME-002 URL + title validation', () => { }) await wrapper.vm.checkUrlAllowed() expect(wrapper.vm.validate()).toContain( - 'This host is not on the allow-list.', + 'The host blocked.example.com is not on the allow-list.', ) }) @@ -179,6 +179,36 @@ describe('IframeWidgetForm — REQ-IFRAME-002 URL + title validation', () => { expect(wrapper.vm.urlAllowListError).toBe('') }) + it('marks the host allow-listed when only the still-empty title is missing', async () => { + // The URL field is left before the title is typed, so the check sees + // an empty title; that says nothing about the host. + validateIframeUrl.mockResolvedValue({ valid: false, errors: ['title_required'] }) + const wrapper = mount(IframeWidgetForm, { + propsData: { + value: { url: 'https://status.example.com/board', title: '' }, + }, + }) + await wrapper.vm.checkUrlAllowed() + expect(wrapper.vm.allowListChecked).toBe(true) + expect(wrapper.vm.urlAllowListError).toBe('') + }) + + it.each([ + ['host_not_allowed'], + ['invalid_url'], + ['url_required'], + ['validation_unavailable'], + ])('does not mark the host allow-listed on %s', async (code) => { + validateIframeUrl.mockResolvedValue({ valid: false, errors: [code, 'title_required'] }) + const wrapper = mount(IframeWidgetForm, { + propsData: { + value: { url: 'https://status.example.com/board', title: '' }, + }, + }) + await wrapper.vm.checkUrlAllowed() + expect(wrapper.vm.allowListChecked).toBe(false) + }) + it('resets allowListChecked when the URL is edited again', async () => { validateIframeUrl.mockResolvedValue({ valid: true, errors: [] }) const wrapper = mount(IframeWidgetForm, { diff --git a/src/components/Widgets/Renderers/__tests__/ImageWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/ImageWidgetForm.spec.js new file mode 100644 index 000000000..7575cf83b --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/ImageWidgetForm.spec.js @@ -0,0 +1,132 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The Image content form (REQ-IMG-020): upload or web address, the chosen + * file with size and dimensions, the required alternative text and the link. + */ + +import { NcTextField } from '@nextcloud/vue' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ImageWidgetForm from '../ImageWidgetForm.vue' + +vi.mock('@nextcloud/dialogs', () => ({ + FilePickerClosed: class FilePickerClosed extends Error {}, + getFilePickerBuilder: vi.fn(), +})) + +function textField(wrapper, label) { + return wrapper.findAllComponents(NcTextField).find((field) => field.props('label') === label) +} + +function lastEmitted(wrapper) { + return (wrapper.emitted('update:content') || []).at(-1)?.[0] +} + +function imageFile(size = 2048, type = 'image/png', name = 'team.png') { + const file = new File(['x'], name, { type }) + Object.defineProperty(file, 'size', { value: size }) + return file +} + +beforeEach(() => { + globalThis.URL.createObjectURL = vi.fn(() => 'blob:preview') + globalThis.URL.revokeObjectURL = vi.fn() +}) + +describe('ImageWidgetForm source', () => { + it('starts on Upload file for a new image and on Web address for a stored https image', () => { + expect(mount(ImageWidgetForm).find('[data-testid="image-source-upload"]').element.checked).toBe(true) + const stored = mount(ImageWidgetForm, { props: { editingWidget: { content: { url: 'https://cdn.test/a.png', alt: 'A' } } } }) + expect(stored.find('[data-testid="image-source-url"]').element.checked).toBe(true) + expect(textField(stored, 'Image URL').props('modelValue')).toBe('https://cdn.test/a.png') + }) + + it('writes the web address and clears it when switching to upload', async () => { + const wrapper = mount(ImageWidgetForm) + await wrapper.find('[data-testid="image-source-url"]').trigger('change') + textField(wrapper, 'Image URL').vm.$emit('update:modelValue', 'https://cdn.test/b.png') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).url).toBe('https://cdn.test/b.png') + await wrapper.find('[data-testid="image-source-upload"]').trigger('change') + expect(lastEmitted(wrapper).url).toBe('') + }) +}) + +describe('ImageWidgetForm chosen file', () => { + it('shows the chosen file with its name and size and uploads it on commit', async () => { + const fileUploadFn = vi.fn().mockResolvedValue({ url: '/apps/launchpad/img/7' }) + const wrapper = mount(ImageWidgetForm, { props: { fileUploadFn } }) + await wrapper.vm.holdFile(imageFile(1.5 * 1024 * 1024)) + await wrapper.vm.$nextTick() + const chosen = wrapper.find('[data-testid="image-chosen"]') + expect(chosen.text()).toContain('team.png') + expect(chosen.text()).toContain('1.5 MB') + expect(fileUploadFn).not.toHaveBeenCalled() + await wrapper.vm.commit() + expect(fileUploadFn).toHaveBeenCalledTimes(1) + expect(lastEmitted(wrapper).url).toBe('/apps/launchpad/img/7') + }) + + it('refuses a file over 5 MB and a file that is not an image', async () => { + const wrapper = mount(ImageWidgetForm) + await wrapper.vm.holdFile(imageFile(6 * 1024 * 1024)) + await wrapper.vm.$nextTick() + expect(wrapper.find('[role="alert"]').text()).toBe('The file is larger than 5 MB') + await wrapper.vm.holdFile(imageFile(10, 'application/pdf', 'a.pdf')) + await wrapper.vm.$nextTick() + expect(wrapper.find('[role="alert"]').text()).toBe('Choose an image file') + expect(wrapper.find('[data-testid="image-chosen"]').exists()).toBe(false) + }) + + it('Choose another drops the chosen file', async () => { + const wrapper = mount(ImageWidgetForm) + await wrapper.vm.holdFile(imageFile()) + await wrapper.vm.$nextTick() + wrapper.vm.chooseAnother() + await wrapper.vm.$nextTick() + expect(wrapper.find('[data-testid="image-chosen"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="image-file-input"]').exists()).toBe(true) + }) + + it('keeps the dialog open when the upload fails', async () => { + const wrapper = mount(ImageWidgetForm, { props: { fileUploadFn: vi.fn().mockRejectedValue(new Error('500')) } }) + await wrapper.vm.holdFile(imageFile()) + await expect(wrapper.vm.commit()).rejects.toThrow('500') + await wrapper.vm.$nextTick() + expect(wrapper.find('[role="alert"]').text()).toBe('The image could not be uploaded') + }) +}) + +describe('ImageWidgetForm alternative text is required (scenario)', () => { + it('refuses an image without alternative text and names the field', async () => { + const wrapper = mount(ImageWidgetForm, { props: { value: { url: 'https://cdn.test/a.png', alt: '' } } }) + expect(wrapper.vm.validate()).toEqual(['Alternative text is required']) + textField(wrapper, 'Text for who does not see the image').vm.$emit('update:modelValue', 'The team at the town hall') + await wrapper.vm.$nextTick() + expect(wrapper.vm.validate()).toEqual([]) + expect(lastEmitted(wrapper)).toEqual({ url: 'https://cdn.test/a.png', alt: 'The team at the town hall', link: '', fit: 'cover' }) + }) + + it('marks the field once the editor empties it, not before', async () => { + const wrapper = mount(ImageWidgetForm) + const alt = () => textField(wrapper, 'Text for who does not see the image') + expect(alt().props('error')).toBe(false) + alt().vm.$emit('update:modelValue', '') + await wrapper.vm.$nextTick() + expect(alt().props('error')).toBe(true) + }) + + it('asks for an image when there is none', () => { + const wrapper = mount(ImageWidgetForm, { props: { value: { alt: 'x' } } }) + expect(wrapper.vm.validate()).toEqual(['Choose an image or enter its web address']) + }) + + it('writes the optional link', async () => { + const wrapper = mount(ImageWidgetForm) + textField(wrapper, 'Link (optional)').vm.$emit('update:modelValue', 'https://intranet.test/team') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).link).toBe('https://intranet.test/team') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/LinkButtonHost.actions.spec.js b/src/components/Widgets/Renderers/__tests__/LinkButtonHost.actions.spec.js new file mode 100644 index 000000000..faf70a664 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/LinkButtonHost.actions.spec.js @@ -0,0 +1,223 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest tests for the action paths of `LinkButtonHost.vue` not covered by + * the overwrite flow spec: `internalAction` dispatches through the + * useInternalActions registry, the createFile modal closes on Cancel, + * backdrop click and Escape (but not while a create is in flight), Enter in + * the name field submits, an empty name never posts, and a non-success + * answer or a non-409 error reports "Failed to create document". + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + __resetInternalActionsForTest, + useInternalActions, +} from '../../../../composables/useInternalActions.js' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnLinkButtonWidget: { name: 'CnLinkButtonWidget', render: () => null }, +})) + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, key) => key, +})) + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `http://localhost${path}`, +})) + +const postMock = vi.fn() +vi.mock('@nextcloud/axios', () => ({ + default: { post: (...args) => postMock(...args) }, +})) + +const showErrorMock = vi.fn() +vi.mock('@nextcloud/dialogs', () => ({ + showError: (...args) => showErrorMock(...args), +})) + +const { default: LinkButtonHost } = await import('../LinkButtonHost.vue') + +/** + * Let the dynamic imports and the axios promise inside onCreateConfirm settle. + */ +async function flush() { + for (let i = 0; i < 10; i++) { + await Promise.resolve() + } + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +/** + * Mount the host with the createFile modal open for `ext`. + * + * @param {string} ext the extension token. + * @return {object} the wrapper. + */ +async function mountOpen(ext = 'docx') { + const wrapper = mount(LinkButtonHost, { + props: { content: {}, placement: { id: 1 } }, + }) + wrapper.findComponent({ name: 'CnLinkButtonWidget' }).vm.$emit('createFile', ext) + await wrapper.vm.$nextTick() + return wrapper +} + +let openSpy + +beforeEach(() => { + postMock.mockReset() + showErrorMock.mockReset() + __resetInternalActionsForTest() + openSpy = vi.spyOn(window, 'open').mockImplementation(() => null) +}) + +afterEach(() => { + openSpy.mockRestore() +}) + +describe('LinkButtonHost — edit mode', () => { + it('hands the edit-mode flags to the widget, which suppresses clicks on them', () => { + const editing = mount(LinkButtonHost, { + props: { content: {}, placement: { id: 1 }, isAdmin: true, canEdit: true }, + }) + expect(editing.findComponent({ name: 'CnLinkButtonWidget' }).vm.$attrs) + .toMatchObject({ isAdmin: true, canEdit: true }) + + const viewing = mount(LinkButtonHost, { + props: { content: {}, placement: { id: 1 } }, + }) + expect(viewing.findComponent({ name: 'CnLinkButtonWidget' }).vm.$attrs) + .toMatchObject({ isAdmin: false, canEdit: false }) + }) +}) + +describe('LinkButtonHost — internal actions', () => { + it('invokes the registered internal action named by the widget', () => { + const action = vi.fn() + useInternalActions().register('open-settings', action) + const wrapper = mount(LinkButtonHost, { props: { content: {}, placement: {} } }) + wrapper.findComponent({ name: 'CnLinkButtonWidget' }).vm.$emit('internalAction', 'open-settings') + expect(action).toHaveBeenCalledTimes(1) + }) + + it('does not invoke other registered actions', () => { + const other = vi.fn() + useInternalActions().register('other', other) + const wrapper = mount(LinkButtonHost, { props: { content: {}, placement: {} } }) + wrapper.findComponent({ name: 'CnLinkButtonWidget' }).vm.$emit('internalAction', 'missing') + expect(other).not.toHaveBeenCalled() + }) +}) + +describe('LinkButtonHost — createFile modal opening', () => { + it('normalises the extension token (leading dot, case, whitespace)', async () => { + const wrapper = await mountOpen(' .DOCX ') + expect(wrapper.vm.pendingExtension).toBe('docx') + expect(wrapper.find('.link-button-host__modal-extension').text()).toBe('.docx') + }) + + it('builds the filename without a dot when there is no extension', async () => { + const wrapper = await mountOpen(null) + wrapper.vm.filenameDraft = ' notes ' + expect(wrapper.vm.pendingFilename).toBe('notes') + }) +}) + +describe('LinkButtonHost — closing the modal', () => { + it('closes on Cancel', async () => { + const wrapper = await mountOpen() + await wrapper.find('.link-button-host__modal-cancel').trigger('click') + expect(wrapper.find('[role="dialog"]').exists()).toBe(false) + }) + + it('closes on a backdrop click', async () => { + const wrapper = await mountOpen() + await wrapper.find('.link-button-host__modal-backdrop').trigger('click') + expect(wrapper.vm.modalOpen).toBe(false) + }) + + it('stays open on a click inside the dialog body', async () => { + const wrapper = await mountOpen() + await wrapper.find('.link-button-host__modal').trigger('click') + expect(wrapper.vm.modalOpen).toBe(true) + }) + + it('closes on Escape', async () => { + const wrapper = await mountOpen() + await wrapper.find('.link-button-host__modal-backdrop').trigger('keydown', { key: 'Escape' }) + expect(wrapper.vm.modalOpen).toBe(false) + }) + + it('cannot be closed while a create is in flight', async () => { + const wrapper = await mountOpen() + wrapper.vm.isExecuting = true + wrapper.vm.closeModal() + expect(wrapper.vm.modalOpen).toBe(true) + expect(wrapper.vm.createButtonLabel).toBe('Creating…') + }) +}) + +describe('LinkButtonHost — submitting', () => { + it('submits on Enter in the filename field', async () => { + postMock.mockResolvedValue({ data: { status: 'success', url: '/f/1' } }) + const wrapper = await mountOpen('md') + await wrapper.find('.link-button-host__modal-input').setValue('readme') + await wrapper.find('.link-button-host__modal-input').trigger('keyup', { key: 'Enter' }) + await flush() + expect(postMock).toHaveBeenCalledWith( + 'http://localhost/apps/launchpad/api/files/create', + { filename: 'readme.md', dir: '/', content: '', overwrite: false }, + ) + expect(openSpy).toHaveBeenCalledWith('/f/1', '_blank') + expect(wrapper.vm.modalOpen).toBe(false) + expect(wrapper.vm.isExecuting).toBe(false) + }) + + it('does not post a blank filename', async () => { + const wrapper = await mountOpen() + await wrapper.find('.link-button-host__modal-input').setValue(' ') + expect(wrapper.vm.canCreate).toBe(false) + await wrapper.vm.onCreateConfirm() + expect(postMock).not.toHaveBeenCalled() + }) + + it('does not post a second time while a create is in flight', async () => { + const wrapper = await mountOpen() + wrapper.vm.isExecuting = true + await wrapper.vm.onCreateConfirm() + expect(postMock).not.toHaveBeenCalled() + }) + + it('reports a failure when the answer is not a success with a url', async () => { + postMock.mockResolvedValue({ data: { status: 'success' } }) + const wrapper = await mountOpen() + await wrapper.vm.onCreateConfirm() + await flush() + expect(showErrorMock).toHaveBeenCalledWith('Failed to create document') + expect(openSpy).not.toHaveBeenCalled() + expect(wrapper.vm.modalOpen).toBe(true) + expect(wrapper.vm.isExecuting).toBe(false) + }) + + it('reports a failure on an error that is not a file_exists conflict', async () => { + postMock.mockRejectedValue({ response: { status: 409, data: { error: 'other' } } }) + const wrapper = await mountOpen() + await wrapper.vm.onCreateConfirm() + await flush() + expect(showErrorMock).toHaveBeenCalledWith('Failed to create document') + expect(wrapper.vm.existingFileWarning).toBe('') + expect(wrapper.vm.isExecuting).toBe(false) + }) + + it('reports a failure on a network error without a response', async () => { + postMock.mockRejectedValue(new Error('offline')) + const wrapper = await mountOpen() + await wrapper.vm.onCreateConfirm() + await flush() + expect(showErrorMock).toHaveBeenCalledWith('Failed to create document') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/LiveTileWidget.lists.spec.js b/src/components/Widgets/Renderers/__tests__/LiveTileWidget.lists.spec.js new file mode 100644 index 000000000..22ea6b95f --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/LiveTileWidget.lists.spec.js @@ -0,0 +1,86 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the list, table and key-value displays of + * `LiveTileWidget.vue` (REQ-LTC-001, REQ-LTC-003). + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import LiveTileWidget from '../LiveTileWidget.vue' +import { fetchLiveTileValue } from '../../../../services/liveTileClient.js' + +vi.mock('../../../../services/liveTileClient.js', () => ({ + fetchLiveTileValue: vi.fn(), +})) + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + fetchLiveTileValue.mockReset() +}) + +function row(title, link, date) { + return [ + { label: 'Incident', role: 'title', value: title }, + { label: 'Open', role: 'link', value: link }, + { label: 'Reported', role: 'date', value: date }, + ] +} + +async function render(reading, content = {}) { + fetchLiveTileValue.mockResolvedValue({ value: null, formatted: null, badge: null, fetchedAt: '2026-11-14T08:00:00Z', stale: false, ...reading }) + const wrapper = mount(LiveTileWidget, { propsData: { content, placement: { id: 7 } } }) + await flushPromises() + return wrapper +} + +describe('LiveTileWidget — lists, tables and pairs', () => { + it('a list shows each title as the link text, opening in a new tab', async () => { + const wrapper = await render({ display: 'list', items: [row('Printer kapot', 'https://topdesk.example/i/1', null), row('VPN traag', 'https://topdesk.example/i/2', null)] }) + const links = wrapper.findAll('ul.live-tile-widget__list li a') + expect(links).toHaveLength(2) + expect(links[0].text()).toBe('Printer kapot') + expect(links[0].attributes('href')).toBe('https://topdesk.example/i/1') + expect(links[0].attributes('target')).toBe('_blank') + expect(links[0].attributes('rel')).toBe('noopener noreferrer') + expect(wrapper.find('.live-tile-widget__value').exists()).toBe(false) + }) + + it('a link that is not https shows the title as plain text', async () => { + const wrapper = await render({ display: 'list', items: [row('Script', 'javascript:alert(1)', null), row('Plain', 'http://example.org', null)] }) + expect(wrapper.findAll('ul.live-tile-widget__list a')).toHaveLength(0) + expect(wrapper.findAll('.live-tile-widget__list-title').map((node) => node.text())).toEqual(['Script', 'Plain']) + }) + + it('a table has column headers from the mapping labels', async () => { + const wrapper = await render({ display: 'table', items: [row('A', 'https://x.example/a', null)] }) + const headers = wrapper.findAll('th') + expect(headers.map((node) => node.text())).toEqual(['Incident', 'Open', 'Reported']) + expect(headers.every((node) => node.attributes('scope') === 'col')).toBe(true) + expect(wrapper.find('td a').attributes('href')).toBe('https://x.example/a') + }) + + it('key-value pairs render as a description list', async () => { + const wrapper = await render({ display: 'keyvalue', pairs: [{ label: 'Open', role: 'field', value: 4 }, { label: 'Team', role: 'field', value: 'Servicedesk' }] }) + expect(wrapper.findAll('dt').map((node) => node.text())).toEqual(['Open', 'Team']) + expect(wrapper.findAll('dd').map((node) => node.text())).toEqual(['4', 'Servicedesk']) + }) + + it('a list tile with a click-through link does not nest links', async () => { + const wrapper = await render({ display: 'list', items: [row('A', 'https://x.example/a', null)] }, { linkUrl: 'https://intranet.example' }) + expect(wrapper.element.tagName).toBe('DIV') + expect(wrapper.findAll('a')).toHaveLength(1) + }) + + it('a single-value tile still renders its value', async () => { + const wrapper = await render({ value: 12, formatted: '12' }) + expect(wrapper.find('.live-tile-widget__value').text()).toBe('12') + expect(wrapper.find('ul').exists()).toBe(false) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/LiveTileWidget.spec.js b/src/components/Widgets/Renderers/__tests__/LiveTileWidget.spec.js index 462562d17..3e996e025 100644 --- a/src/components/Widgets/Renderers/__tests__/LiveTileWidget.spec.js +++ b/src/components/Widgets/Renderers/__tests__/LiveTileWidget.spec.js @@ -185,6 +185,8 @@ describe('LiveTileWidget — REQ-LIVETILE-005 connector-absent leaf consumption' expect(wrapper.find('.live-tile-widget__state--unavailable').exists()).toBe( false, ) + expect(wrapper.find('.live-tile-widget__state--error').exists()).toBe(true) + expect(wrapper.text()).not.toContain('Showing last known value') }) }) @@ -249,3 +251,26 @@ describe('LiveTileWidget — REQ-LIVETILE-004 click-through', () => { expect(wrapper.element.tagName).toBe('DIV') }) }) + +describe('LiveTileWidget — REQ-PSHR-011 a public screen passes its own reading source', () => { + it('reads through readingSource instead of the signed-in endpoint', async () => { + const readingSource = vi.fn().mockResolvedValue({ value: 7, formatted: '7', badge: null, stale: false }) + const wrapper = mount(LiveTileWidget, { + propsData: { content: {}, placement: { id: 3 }, readingSource }, + }) + await flushPromises() + expect(readingSource).toHaveBeenCalledWith(3) + expect(fetchLiveTileValue).not.toHaveBeenCalled() + expect(wrapper.vm.reading.value).toBe(7) + }) + + it('shows the failed state when the token-scoped read is refused', async () => { + const readingSource = vi.fn().mockRejectedValue(new Error('404')) + const wrapper = mount(LiveTileWidget, { + propsData: { content: {}, placement: { id: 3 }, readingSource }, + }) + await flushPromises() + expect(wrapper.vm.reading).toBeNull() + expect(wrapper.find('.live-tile-widget__state--error').exists()).toBe(true) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.boardSync.spec.js b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.boardSync.spec.js new file mode 100644 index 000000000..7717e1fbe --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.boardSync.spec.js @@ -0,0 +1,191 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The Live data form as board LpWidgetInstellen draws it (REQ-LIVETILE-020): + * choice cards, the chosen connection with its last success, the view, unit + * and refresh, the formatting fields and a preview that follows them. + */ + +import { NcCheckboxRadioSwitch, NcSelect, NcTextField } from '@nextcloud/vue' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import LiveTileWidget from '../LiveTileWidget.vue' +import LiveTileWidgetForm from '../LiveTileWidgetForm.vue' +import { + fetchConnectorAvailability, + fetchLiveTileValue, + validateLiveTileSource, +} from '../../../../services/liveTileClient.js' +import { fetchLiveTileConnections } from '../../../../services/liveTileConnections.js' + +vi.mock('../../../../services/liveTileClient.js', () => ({ + fetchConnectorAvailability: vi.fn(), + fetchLiveTileValue: vi.fn(), + validateLiveTileSource: vi.fn(), +})) +vi.mock('../../../../services/liveTileConnections.js', () => ({ + fetchLiveTileConnections: vi.fn(), +})) + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +function lastEmitted(wrapper) { + return (wrapper.emitted('update:content') || []).at(-1)?.[0] +} + +function textField(wrapper, label) { + return wrapper.findAllComponents(NcTextField).find((field) => field.props('label') === label) +} + +function select(wrapper, label) { + return wrapper.findAllComponents(NcSelect).find((s) => s.props('inputLabel') === label) +} + +function toggle(wrapper, text) { + return wrapper.findAllComponents(NcCheckboxRadioSwitch).find((s) => s.text().includes(text)) +} + +const KCC = { value: 'kcc-queue', label: 'Contact centre queue', lastSuccessAt: '2026-11-25T10:38:00Z' } + +beforeEach(() => { + fetchConnectorAvailability.mockReset() + fetchConnectorAvailability.mockResolvedValue(true) + fetchLiveTileValue.mockReset() + fetchLiveTileValue.mockResolvedValue({ value: 12 }) + validateLiveTileSource.mockReset() + validateLiveTileSource.mockResolvedValue({ valid: true, errors: [] }) + fetchLiveTileConnections.mockReset() + fetchLiveTileConnections.mockResolvedValue([KCC]) +}) + +describe('LiveTileWidgetForm source cards', () => { + it('offers Connection and Web address, and choosing a card switches the source', async () => { + const wrapper = mount(LiveTileWidgetForm, { props: { value: { url: 'https://a.test/x', valueExpr: '$.n' } } }) + await flushPromises() + expect(wrapper.find('[data-testid="live-tile-source-url"]').element.checked).toBe(true) + await wrapper.find('[data-testid="live-tile-source-connector"]').trigger('change') + expect(lastEmitted(wrapper).sourceMode).toBe('connector') + expect(textField(wrapper, 'URL')).toBeUndefined() + expect(select(wrapper, 'Connection')).toBeDefined() + }) + + it('disables the Connection card without integriq', async () => { + fetchConnectorAvailability.mockResolvedValue(false) + const wrapper = mount(LiveTileWidgetForm, { props: { value: { url: 'https://a.test/x', valueExpr: '$.n' } } }) + await flushPromises() + expect(wrapper.find('[data-testid="live-tile-source-connector"]').element.disabled).toBe(true) + }) + + it('falls back to the source id field when no connection is listed', async () => { + fetchLiveTileConnections.mockResolvedValue([]) + const wrapper = mount(LiveTileWidgetForm, { props: { value: { sourceMode: 'connector', valueExpr: '$.n' } } }) + await flushPromises() + expect(select(wrapper, 'Connection')).toBeUndefined() + expect(textField(wrapper, 'Integriq source id')).toBeDefined() + }) +}) + +describe('LiveTileWidgetForm KCC waiting time (scenario)', () => { + it('shows the connection\'s last success and a preview with the unit and the refresh', async () => { + const wrapper = mount(LiveTileWidgetForm, { + props: { editingWidget: { id: 9, content: { sourceMode: 'connector', valueExpr: '', label: 'KCC waiting time' } } }, + }) + await flushPromises() + select(wrapper, 'Connection').vm.$emit('update:modelValue', 'kcc-queue') + textField(wrapper, 'Path in the response').vm.$emit('update:modelValue', 'wait.minutes') + textField(wrapper, 'Unit (optional)').vm.$emit('update:modelValue', 'minutes') + await wrapper.vm.$nextTick() + + expect(wrapper.find('[data-testid="live-tile-last-success"]').text()).toContain('Last success:') + expect(wrapper.find('[data-testid="live-tile-last-success"]').text()).not.toContain('Not yet') + expect(fetchLiveTileValue).toHaveBeenCalledWith(9) + const preview = wrapper.find('[data-testid="live-tile-preview"]') + expect(preview.text()).toContain('KCC waiting time') + expect(preview.text()).toContain('12 minutes') + expect(preview.text()).toContain('Refreshes every 5 minutes') + expect(lastEmitted(wrapper)).toMatchObject({ + sourceMode: 'connector', + sourceId: 'kcc-queue', + valueExpr: 'wait.minutes', + format: { suffix: ' minutes' }, + refresh: 300, + }) + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('says Not yet for a connection that never succeeded', async () => { + fetchLiveTileConnections.mockResolvedValue([{ ...KCC, lastSuccessAt: null }]) + const wrapper = mount(LiveTileWidgetForm, { props: { value: { sourceMode: 'connector', sourceId: 'kcc-queue', valueExpr: '$.n' } } }) + await flushPromises() + expect(wrapper.find('[data-testid="live-tile-last-success"]').text()).toContain('Not yet') + }) +}) + +describe('LiveTileWidgetForm view, refresh and formatting', () => { + it('chooses the view with the view radios', async () => { + const wrapper = mount(LiveTileWidgetForm, { props: { value: { url: 'https://a.test/x', valueExpr: '$.n' } } }) + await flushPromises() + await wrapper.find('[data-testid="live-tile-view-table"]').trigger('change') + expect(lastEmitted(wrapper).display).toBe('table') + }) + + it('sets the refresh from its choices and the preview follows', async () => { + const wrapper = mount(LiveTileWidgetForm, { props: { value: { url: 'https://a.test/x', valueExpr: '$.n' } } }) + await flushPromises() + select(wrapper, 'Refresh').vm.$emit('update:modelValue', 900) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).refresh).toBe(900) + expect(wrapper.find('[data-testid="live-tile-preview"]').text()).toContain('Refreshes every 15 minutes') + }) + + it('stores show title, colour and border only when they differ from the default', async () => { + const wrapper = mount(LiveTileWidgetForm, { props: { value: { url: 'https://a.test/x', valueExpr: '$.n', label: 'Open' } } }) + await flushPromises() + expect(wrapper.vm.assembledContent).not.toHaveProperty('showTitle') + expect(wrapper.vm.assembledContent).not.toHaveProperty('colour') + expect(wrapper.vm.assembledContent).not.toHaveProperty('border') + + toggle(wrapper, 'Show title').vm.$emit('update:modelValue', false) + select(wrapper, 'Color').vm.$emit('update:modelValue', 'warning') + toggle(wrapper, 'Border').vm.$emit('update:modelValue', true) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper)).toMatchObject({ showTitle: false, colour: 'warning', border: true }) + const preview = wrapper.find('[data-testid="live-tile-preview"]') + expect(preview.text()).not.toContain('Open') + expect(preview.classes()).toContain('live-tile-colour--warning') + expect(preview.classes()).toContain('live-tile-widget-form__preview--bordered') + }) + + it('drops an unknown stored colour', async () => { + const wrapper = mount(LiveTileWidgetForm, { props: { value: { url: 'https://a.test/x', valueExpr: '$.n', colour: '#123456' } } }) + await flushPromises() + expect(wrapper.vm.colour).toBe('') + }) +}) + +describe('LiveTileWidget renders the formatting', () => { + it('hides the title, and takes the colour and border', async () => { + fetchLiveTileValue.mockResolvedValue({ value: 3, formatted: '3', badge: null, stale: false }) + const wrapper = mount(LiveTileWidget, { + props: { content: { label: 'Open', showTitle: false, colour: 'success', border: true }, placement: { id: 1 } }, + }) + await flushPromises() + expect(wrapper.find('.live-tile-widget__label').exists()).toBe(false) + expect(wrapper.classes()).toContain('live-tile-colour--success') + expect(wrapper.classes()).toContain('live-tile-widget--bordered') + }) + + it('shows the title by default and ignores an unknown colour', async () => { + fetchLiveTileValue.mockResolvedValue({ value: 3, formatted: '3', badge: null, stale: false }) + const wrapper = mount(LiveTileWidget, { + props: { content: { label: 'Open', colour: 'hotpink' }, placement: { id: 1 } }, + }) + await flushPromises() + expect(wrapper.find('.live-tile-widget__label').text()).toBe('Open') + expect(wrapper.classes().some((c) => c.startsWith('live-tile-colour--'))).toBe(false) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.controls.spec.js b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.controls.spec.js new file mode 100644 index 000000000..17503c9cd --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.controls.spec.js @@ -0,0 +1,135 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the rendered controls of `LiveTileWidgetForm.vue`: + * every text field, select and switch writes back through + * `update:modelValue` and the form emits the assembled content. Also covers + * the connector-mode source-id field and validation for an unknown source + * mode. `liveTileClient.js` (the HTTP layer) is mocked. + */ + +import { NcCheckboxRadioSwitch, NcSelect, NcTextField } from '@nextcloud/vue' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import LiveTileWidgetForm from '../LiveTileWidgetForm.vue' +import { + fetchConnectorAvailability, + validateLiveTileSource, +} from '../../../../services/liveTileClient.js' + +vi.mock('../../../../services/liveTileClient.js', () => ({ + fetchConnectorAvailability: vi.fn(), + validateLiveTileSource: vi.fn(), +})) + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +function lastEmitted(wrapper) { + return (wrapper.emitted('update:content') || []).at(-1)?.[0] +} + +function textField(wrapper, label) { + return wrapper + .findAllComponents(NcTextField) + .find((field) => field.props('label') === label) +} + +function select(wrapper, label) { + return wrapper + .findAllComponents(NcSelect) + .find((s) => s.props('inputLabel') === label) +} + +async function mountForm(value = { url: 'https://a.test/x', valueExpr: '$.n' }) { + const wrapper = mount(LiveTileWidgetForm, { props: { value } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + fetchConnectorAvailability.mockReset() + fetchConnectorAvailability.mockResolvedValue(true) + validateLiveTileSource.mockReset() + validateLiveTileSource.mockResolvedValue({ valid: true, errors: [] }) +}) + +describe('LiveTileWidgetForm rendered controls', () => { + it('writes the label typed into the Title field', async () => { + const wrapper = await mountForm() + textField(wrapper, 'Title').vm.$emit('update:modelValue', 'Open tickets') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).label).toBe('Open tickets') + expect(textField(wrapper, 'Title').props('modelValue')).toBe('Open tickets') + }) + + it('writes the value expression field', async () => { + const wrapper = await mountForm() + textField(wrapper, 'Path in the response').vm.$emit('update:modelValue', '$.data.total') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).valueExpr).toBe('$.data.total') + }) + + it('writes prefix, unit and the thousands switch into format', async () => { + const wrapper = await mountForm() + textField(wrapper, 'Prefix').vm.$emit('update:modelValue', '€ ') + textField(wrapper, 'Unit (optional)').vm.$emit('update:modelValue', 'items') + wrapper.findAllComponents(NcCheckboxRadioSwitch) + .find((s) => s.text().includes('Thousands separator')) + .vm.$emit('update:modelValue', true) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).format).toEqual({ + prefix: '€ ', + suffix: ' items', + thousands: true, + }) + expect(wrapper.emitted('update:content')).toHaveLength(3) + }) + + it('writes the click-through link URL', async () => { + const wrapper = await mountForm() + textField(wrapper, 'Click-through link (optional)').vm.$emit( + 'update:modelValue', + 'https://tickets.test/', + ) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).linkUrl).toBe('https://tickets.test/') + }) + + it('writes the link target and falls back to same-tab when cleared', async () => { + const wrapper = await mountForm() + const target = select(wrapper, 'Link target') + target.vm.$emit('update:modelValue', 'new-tab') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).linkTarget).toBe('new-tab') + target.vm.$emit('update:modelValue', null) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).linkTarget).toBe('same-tab') + }) + + it('writes the connector source id from its field in connector mode', async () => { + const wrapper = await mountForm({ sourceMode: 'connector', valueExpr: '$.n' }) + expect(textField(wrapper, 'URL')).toBeUndefined() + const sourceField = textField(wrapper, 'Integriq source id') + expect(sourceField.props('disabled')).toBe(false) + sourceField.vm.$emit('update:modelValue', 'src-42') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper)).toMatchObject({ + sourceMode: 'connector', + sourceId: 'src-42', + }) + expect(wrapper.vm.validate()).toEqual([]) + }) +}) + +describe('LiveTileWidgetForm validation of an unknown source mode', () => { + it('reports no source errors when the stored mode is neither url nor connector', async () => { + const wrapper = await mountForm({ sourceMode: 'legacy', valueExpr: '$.n' }) + expect(wrapper.vm.sourceErrors()).toEqual([]) + expect(wrapper.vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.display.spec.js b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.display.spec.js new file mode 100644 index 000000000..e6aa5c5f4 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.display.spec.js @@ -0,0 +1,128 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the display, mapping and preset of + * `LiveTileWidgetForm.vue` (REQ-LTC-001, REQ-LTC-004). `liveTileClient.js` is mocked. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import LiveTileWidgetForm from '../LiveTileWidgetForm.vue' +import { + fetchConnectorAvailability, + validateLiveTileSource, +} from '../../../../services/liveTileClient.js' + +vi.mock('../../../../services/liveTileClient.js', () => ({ + fetchConnectorAvailability: vi.fn(), + validateLiveTileSource: vi.fn(), +})) + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +function lastEmitted(wrapper) { + return (wrapper.emitted('update:content') || []).at(-1)?.[0] +} + +async function mountForm(value = { url: 'https://a.test/x', valueExpr: '$.n' }) { + const wrapper = mount(LiveTileWidgetForm, { props: { value } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + fetchConnectorAvailability.mockReset() + fetchConnectorAvailability.mockResolvedValue(true) + validateLiveTileSource.mockReset() + validateLiveTileSource.mockResolvedValue({ valid: true, errors: [] }) +}) + +describe('LiveTileWidgetForm display and mapping', () => { + it('a single-value tile is stored without display keys', async () => { + const wrapper = await mountForm() + wrapper.vm.updateField('label', 'Open') + const content = lastEmitted(wrapper) + expect(content).not.toHaveProperty('display') + expect(content).not.toHaveProperty('mapping') + expect(content).not.toHaveProperty('limit') + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('choosing List starts one title field and stores display, mapping and limit', async () => { + const wrapper = await mountForm() + wrapper.vm.onDisplayChange('list') + expect(lastEmitted(wrapper)).toMatchObject({ display: 'list', limit: 10, mapping: [{ label: '', path: '', role: 'title' }] }) + expect(wrapper.vm.validate()).toEqual(['Every field needs a path']) + + wrapper.vm.updateMapping(0, 'path', 'briefDescription') + wrapper.vm.addMapping() + wrapper.vm.updateMapping(1, 'path', 'url') + wrapper.vm.updateMapping(1, 'role', 'link') + wrapper.vm.onLimitChange('5') + expect(lastEmitted(wrapper)).toMatchObject({ + display: 'list', + limit: 5, + mapping: [ + { label: '', path: 'briefDescription', role: 'title' }, + { label: '', path: 'url', role: 'link' }, + ], + }) + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('allows six fields at most, and checks the limit', async () => { + const wrapper = await mountForm() + wrapper.vm.onDisplayChange('table') + for (let i = 0; i < 8; i++) { + wrapper.vm.addMapping() + } + expect(wrapper.vm.mapping).toHaveLength(6) + wrapper.vm.mapping.forEach((_, index) => wrapper.vm.updateMapping(index, 'path', 'f' + index)) + wrapper.vm.onLimitChange('51') + expect(wrapper.vm.validate()).toEqual(['The number of rows is from 1 to 50']) + wrapper.vm.removeMapping(0) + expect(lastEmitted(wrapper).mapping).toHaveLength(5) + }) + + it('a key-value tile stores no limit', async () => { + const wrapper = await mountForm() + wrapper.vm.onDisplayChange('keyvalue') + expect(lastEmitted(wrapper)).not.toHaveProperty('limit') + }) + + it('the SharePoint preset fills a latest-documents list for the author to confirm', async () => { + const wrapper = await mountForm({ sourceMode: 'connector', sourceId: 'intranet-docs', valueExpr: '' }) + wrapper.vm.onDisplayChange('list') + wrapper.vm.applyPreset({ value: 'sharepoint' }) + expect(lastEmitted(wrapper)).toMatchObject({ + sourceId: 'intranet-docs', + valueExpr: '$.value', + display: 'list', + limit: 10, + mapping: [ + { label: 'Document', path: 'name', role: 'title' }, + { label: 'Open', path: 'webUrl', role: 'link' }, + { label: 'Last modified', path: 'lastModifiedDateTime', role: 'date' }, + { label: 'Modified by', path: 'lastModifiedBy.user.displayName', role: 'field' }, + ], + }) + }) + + it('the Confluence preset reads the results array', async () => { + const wrapper = await mountForm() + wrapper.vm.applyPreset('confluence') + expect(lastEmitted(wrapper)).toMatchObject({ valueExpr: '$.results', mapping: [{ path: 'title' }, { path: '_links.webui' }, { path: 'version.when' }, { path: 'version.by.displayName' }] }) + }) + + it('reopens a saved list tile with its mapping', async () => { + const wrapper = await mountForm({ url: 'https://a.test/x', valueExpr: '$.items', display: 'table', limit: 3, mapping: [{ label: 'Naam', path: 'name', role: 'title' }] }) + expect(wrapper.vm.display).toBe('table') + expect(wrapper.vm.limit).toBe(3) + expect(wrapper.vm.mapping).toEqual([{ label: 'Naam', path: 'name', role: 'title' }]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.fields.spec.js b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.fields.spec.js new file mode 100644 index 000000000..f3a3fa93d --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.fields.spec.js @@ -0,0 +1,139 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the field handlers of `LiveTileWidgetForm.vue`: + * switching the source mode, editing the URL (which clears a stale + * allow-list error), the refresh interval, and the number-format options — + * each emits the assembled content. The blur-time allow-list check is skipped + * for connector mode and for an empty URL. `liveTileClient.js` is mocked. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import LiveTileWidgetForm from '../LiveTileWidgetForm.vue' +import { + fetchConnectorAvailability, + validateLiveTileSource, +} from '../../../../services/liveTileClient.js' + +vi.mock('../../../../services/liveTileClient.js', () => ({ + fetchConnectorAvailability: vi.fn(), + validateLiveTileSource: vi.fn(), +})) + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +function lastEmitted(wrapper) { + const events = wrapper.emitted('update:content') || [] + return events.at(-1)?.[0] +} + +async function mountForm(value = { url: 'https://a.test/x', valueExpr: '$.n' }) { + const wrapper = mount(LiveTileWidgetForm, { props: { value } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + fetchConnectorAvailability.mockReset() + fetchConnectorAvailability.mockResolvedValue(true) + validateLiveTileSource.mockReset() + validateLiveTileSource.mockResolvedValue({ valid: true, errors: [] }) +}) + +describe('LiveTileWidgetForm field handlers', () => { + it('switches the source mode and falls back to url for an empty choice', async () => { + const wrapper = await mountForm() + wrapper.vm.onSourceModeChange('connector') + expect(lastEmitted(wrapper).sourceMode).toBe('connector') + wrapper.vm.onSourceModeChange(null) + expect(wrapper.vm.sourceMode).toBe('url') + expect(lastEmitted(wrapper).sourceMode).toBe('url') + }) + + it('clears a stale allow-list error when the URL changes', async () => { + const wrapper = await mountForm() + wrapper.vm.urlAllowListError = 'Host not allowed' + wrapper.vm.onUrlChange('https://b.test/y') + expect(wrapper.vm.urlAllowListError).toBe('') + expect(lastEmitted(wrapper).url).toBe('https://b.test/y') + }) + + it('emits the refresh interval clamped to the minimum', async () => { + const wrapper = await mountForm() + wrapper.vm.onRefreshChange('10') + expect(wrapper.vm.refresh).toBe('10') + expect(lastEmitted(wrapper).refresh).toBe(30) + wrapper.vm.onRefreshChange('120') + expect(lastEmitted(wrapper).refresh).toBe(120) + }) + + it('writes prefix, suffix and thousands into the format, ignoring unknown options', async () => { + const wrapper = await mountForm() + wrapper.vm.updateFormat('prefix', '€ ') + wrapper.vm.updateFormat('suffix', ' open') + wrapper.vm.updateFormat('thousands', true) + expect(lastEmitted(wrapper).format).toEqual({ + prefix: '€ ', + suffix: ' open', + thousands: true, + }) + const before = wrapper.emitted('update:content').length + wrapper.vm.updateFormat('decimals', 2) + expect(wrapper.emitted('update:content')).toHaveLength(before + 1) + expect(lastEmitted(wrapper).format).toEqual({ + prefix: '€ ', + suffix: ' open', + thousands: true, + }) + }) + + it('reads a stored format over the defaults and coerces thousands to a boolean', async () => { + const wrapper = await mountForm({ format: { suffix: '%', thousands: 1 } }) + expect(wrapper.vm.formatPrefix).toBe('') + expect(wrapper.vm.formatSuffix).toBe('%') + expect(wrapper.vm.formatThousands).toBe(true) + }) + + it('keeps connector mode when the probe reports OpenConnector present', async () => { + const wrapper = await mountForm({ sourceMode: 'connector', sourceId: 'src-1' }) + expect(wrapper.vm.connectorAvailable).toBe(true) + expect(wrapper.vm.sourceMode).toBe('connector') + expect(wrapper.emitted('update:content')).toBeUndefined() + }) +}) + +describe('LiveTileWidgetForm blur-time allow-list check', () => { + it('skips the check and clears the error in connector mode', async () => { + const wrapper = await mountForm({ sourceMode: 'connector', sourceId: 's' }) + wrapper.vm.urlAllowListError = 'old' + await wrapper.vm.checkUrlAllowed() + expect(validateLiveTileSource).not.toHaveBeenCalled() + expect(wrapper.vm.urlAllowListError).toBe('') + }) + + it('skips the check and clears the error for a blank URL', async () => { + const wrapper = await mountForm({ url: ' ' }) + wrapper.vm.urlAllowListError = 'old' + await wrapper.vm.checkUrlAllowed() + expect(validateLiveTileSource).not.toHaveBeenCalled() + expect(wrapper.vm.urlAllowListError).toBe('') + }) + + it('checks the assembled content for a URL in url mode', async () => { + const wrapper = await mountForm() + await wrapper.vm.checkUrlAllowed() + expect(validateLiveTileSource).toHaveBeenCalledTimes(1) + expect(validateLiveTileSource.mock.calls[0][0]).toMatchObject({ + sourceMode: 'url', + url: 'https://a.test/x', + valueExpr: '$.n', + }) + expect(wrapper.vm.urlAllowListError).toBe('') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.spec.js index 67e3c60f3..87d49631b 100644 --- a/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.spec.js +++ b/src/components/Widgets/Renderers/__tests__/LiveTileWidgetForm.spec.js @@ -286,7 +286,7 @@ describe('LiveTileWidgetForm — REQ-LIVETILE-005 connector-mode gating', () => // Component self-heals to url mode; force back to connector to // exercise the defensive validate() branch directly. wrapper.vm.sourceMode = 'connector' - expect(wrapper.vm.validate()).toContain('OpenConnector is not available.') + expect(wrapper.vm.validate()).toContain('Integriq is not available.') }) it('requires a source id in connector mode', async () => { diff --git a/src/components/Widgets/Renderers/__tests__/NewsWidget.click.spec.js b/src/components/Widgets/Renderers/__tests__/NewsWidget.click.spec.js new file mode 100644 index 000000000..538afe72a --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/NewsWidget.click.spec.js @@ -0,0 +1,77 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `NewsWidget.vue` (REQ-NEWS-011): a click on a + * rendered item link keeps the native anchor behaviour, and falls back to + * `window.open(..., 'noopener,noreferrer')` only when something inside the + * anchor has prevented the default navigation. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import NewsWidget from '../NewsWidget.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + '/index.php' + path.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) + +const ITEMS = [ + { guid: 'a', title: 'First', link: 'https://news.test/a', summary: '', pubDate: '' }, + { guid: 'b', title: 'Second', link: 'https://news.test/b', summary: '', pubDate: '' }, +] + +let open + +beforeEach(() => { + globalThis.t = (_app, key) => key + axios.get.mockReset() + axios.get.mockResolvedValue({ data: { items: ITEMS, feedsFailed: 0, failedUrls: [] } }) + open = vi.spyOn(window, 'open').mockImplementation(() => null) +}) + +afterEach(() => { + open.mockRestore() +}) + +async function mountWidget() { + const wrapper = mount(NewsWidget, { + props: { content: {}, placement: { id: 4 } }, + attachTo: document.body, + }) + await flushPromises() + return wrapper +} + +describe('NewsWidget item link clicks', () => { + it('leaves an ordinary click to the native anchor (no window.open)', async () => { + const wrapper = await mountWidget() + const anchors = wrapper.findAll('a.news-widget__item-link') + expect(anchors).toHaveLength(2) + const event = new MouseEvent('click', { bubbles: true, cancelable: true }) + // Stop jsdom from attempting a real navigation after the handler ran. + document.addEventListener('click', (e) => e.preventDefault(), { once: true }) + anchors[0].element.dispatchEvent(event) + expect(open).not.toHaveBeenCalled() + wrapper.unmount() + }) + + it('opens the clicked item in a new tab when the anchor default was prevented', async () => { + const wrapper = await mountWidget() + const title = wrapper.findAll('.news-widget__title')[1] + // A listener inside the anchor prevents the default before the + // anchor's own handler runs as the event bubbles. + title.element.addEventListener('click', (e) => e.preventDefault()) + await title.trigger('click') + expect(open).toHaveBeenCalledTimes(1) + expect(open).toHaveBeenCalledWith( + 'https://news.test/b', + '_blank', + 'noopener,noreferrer', + ) + wrapper.unmount() + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/NewsWidget.items.spec.js b/src/components/Widgets/Renderers/__tests__/NewsWidget.items.spec.js new file mode 100644 index 000000000..c56fa5cff --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/NewsWidget.items.spec.js @@ -0,0 +1,193 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `NewsWidget.vue` beyond summary truncation: the + * items request, the failed-feeds badge, the loading / error / empty + * states, the content options with their defaults, item clicks and the + * relative / absolute dates. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import NewsWidget from '../NewsWidget.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + '/index.php' + path.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) + +const NOW = Date.UTC(2026, 2, 11, 12, 0, 0) + +const ITEMS = [ + { guid: 'a', title: 'Linked', link: 'https://news.test/a', summary: '<p>Body</p>', thumbnailUrl: 'https://news.test/a.png', pubDate: '2026-03-11T11:58:00Z' }, + { guid: 'b', title: 'Plain', summary: '', pubDate: '' }, +] + +function mountWidget(content = {}, placement = { id: 4 }) { + return mount(NewsWidget, { props: { content, placement } }) +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(NOW) + globalThis.t = (_app, key) => key + axios.get.mockReset() + axios.get.mockResolvedValue({ data: { items: ITEMS, feedsFailed: 0, failedUrls: [] } }) +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('NewsWidget items', () => { + it('requests the placement items with the item limit and renders them', async () => { + const wrapper = mountWidget({ itemLimit: 5 }) + await flushPromises() + + expect(axios.get).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/widgets/news/4/items', + { params: { limit: 5 } }, + ) + const rows = wrapper.findAll('.news-widget__item') + expect(rows.map((r) => r.find('.news-widget__title').text())).toEqual(['Linked', 'Plain']) + expect(rows[0].find('a.news-widget__item-link').attributes('href')).toBe('https://news.test/a') + expect(rows[0].find('.news-widget__thumb').exists()).toBe(true) + expect(rows[0].find('.news-widget__summary').exists()).toBe(true) + expect(rows[1].find('.news-widget__item-link--inert').exists()).toBe(true) + }) + + it.each([[0], [51], ['5'], [undefined]])('uses the default limit of 10 for %s', async (itemLimit) => { + mountWidget({ itemLimit }) + await flushPromises() + expect(axios.get.mock.calls[0][1]).toEqual({ params: { limit: 10 } }) + }) + + it('filters the rendered items in view state, without another request (REQ-DWMS-008)', async () => { + const content = { itemLimit: 5 } + const wrapper = mountWidget(content) + await flushPromises() + + await wrapper.find('[data-testid="widget-row-filter"]').setValue('plain') + const rows = wrapper.findAll('.news-widget__item') + expect(rows.map((r) => r.find('.news-widget__title').text())).toEqual(['Plain']) + expect(axios.get).toHaveBeenCalledTimes(1) + expect(content).toEqual({ itemLimit: 5 }) + + await wrapper.find('[data-testid="widget-row-filter"]').setValue('') + expect(wrapper.findAll('.news-widget__item')).toHaveLength(2) + }) + + it('does not load without a placement id', async () => { + const wrapper = mountWidget({}, {}) + await flushPromises() + await wrapper.vm.loadItems() + expect(axios.get).not.toHaveBeenCalled() + }) + + it('hides thumbnails and summaries only when explicitly off', async () => { + const wrapper = mountWidget({ showThumbnails: false, showSummary: 'yes' }) + await flushPromises() + expect(wrapper.find('.news-widget__thumb').exists()).toBe(false) + expect(wrapper.find('.news-widget__summary').exists()).toBe(false) + }) + + it('applies an allowed layout and falls back to list', () => { + expect(mountWidget({ layout: 'grid' }).classes()).toContain('news-widget--grid') + expect(mountWidget({ layout: 'masonry' }).classes()).toContain('news-widget--list') + }) + + it('badges one failed feed in the singular with the URL as tooltip', async () => { + axios.get.mockResolvedValue({ data: { items: ITEMS, feedsFailed: 1, failedUrls: ['https://bad.test/rss'] } }) + const wrapper = mountWidget() + await flushPromises() + + const badge = wrapper.find('.news-widget__badge') + expect(badge.text()).toBe('1 feed failed') + expect(badge.attributes('title')).toBe('Failed: https://bad.test/rss') + }) + + it('badges several failed feeds with their count and no tooltip without URLs', async () => { + axios.get.mockResolvedValue({ data: { items: [], feedsFailed: 3, failedUrls: 'x' } }) + const wrapper = mountWidget() + await flushPromises() + + expect(wrapper.find('.news-widget__badge').text()).toBe('3 feeds failed') + expect(wrapper.vm.failedTooltip).toBe('') + expect(wrapper.find('.news-widget__state--empty').exists()).toBe(true) + }) + + it('shows the error state when loading fails', async () => { + axios.get.mockRejectedValue(new Error('502')) + const wrapper = mountWidget() + await flushPromises() + + expect(wrapper.find('.news-widget__state--error').exists()).toBe(true) + expect(wrapper.vm.items).toEqual([]) + expect(wrapper.find('.news-widget__state--loading').exists()).toBe(false) + }) + + it('treats a response without data as no items and no failures', async () => { + axios.get.mockResolvedValue(undefined) + const wrapper = mountWidget() + await flushPromises() + expect(wrapper.vm.items).toEqual([]) + expect(wrapper.vm.failedCount).toBe(0) + }) + + it('reloads when the placement changes', async () => { + const wrapper = mountWidget() + await flushPromises() + await wrapper.setProps({ placement: { id: 9 } }) + await flushPromises() + expect(axios.get.mock.calls.map((c) => c[0])).toEqual([ + '/index.php/apps/launchpad/api/widgets/news/4/items', + '/index.php/apps/launchpad/api/widgets/news/9/items', + ]) + }) +}) + +describe('NewsWidget clicks and dates', () => { + it('opens the link in a new tab only when the anchor was prevented', () => { + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + const wrapper = mountWidget() + + wrapper.vm.onItemClick({ defaultPrevented: false }, ITEMS[0]) + wrapper.vm.onItemClick({ defaultPrevented: true }, ITEMS[1]) + wrapper.vm.onItemClick({ defaultPrevented: true }, null) + expect(open).not.toHaveBeenCalled() + + wrapper.vm.onItemClick({ defaultPrevented: true }, ITEMS[0]) + expect(open).toHaveBeenCalledWith('https://news.test/a', '_blank', 'noopener,noreferrer') + open.mockRestore() + }) + + it.each([ + ['2026-03-11T11:59:30Z', 'just now'], + ['2026-03-11T12:00:30Z', 'just now'], + ['2026-03-11T11:15:00Z', '45 minutes ago'], + ['2026-03-11T07:00:00Z', '5 hours ago'], + ['2026-03-08T12:00:00Z', '3 days ago'], + ['2026-03-11T11:59:00Z', '1 minute ago'], + ['2026-03-11T11:00:00Z', '1 hour ago'], + ['2026-03-10T12:00:00Z', '1 day ago'], + ['', ''], + ['not a date', ''], + [undefined, ''], + ])('formats %s relatively as "%s"', (pubDate, expected) => { + expect(mountWidget().vm.formatDate(pubDate)).toBe(expected) + }) + + it('formats absolute dates as UTC "YYYY-MM-DD HH:MM"', () => { + const wrapper = mountWidget({ dateFormat: 'absolute' }) + expect(wrapper.vm.formatDate('2026-03-08T09:05:00Z')).toBe('2026-03-08 09:05') + }) + + it('renders the item date relative to now', async () => { + const wrapper = mountWidget() + await flushPromises() + expect(wrapper.find('.news-widget__date').text()).toBe('2 minutes ago') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/NewsWidget.safety.spec.js b/src/components/Widgets/Renderers/__tests__/NewsWidget.safety.spec.js new file mode 100644 index 000000000..84d42b57c --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/NewsWidget.safety.spec.js @@ -0,0 +1,108 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `NewsWidget.vue`: attribute stripping in summaries, + * unsafe item links, the all-feeds-failed badge, the empty-state icon and + * the carousel's previous/next navigation (REQ-NEWS-005, -008, -009, -010, + * -011). + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import NewsWidget from '../NewsWidget.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (p) => `/index.php${p}` })) + +/** + * Mount the widget on a placement whose endpoint answers this payload. + * + * @param {object} payload The items response. + * @param {object} content The placement content. + * @return {Promise<object>} The mounted wrapper, after the load. + */ +async function render(payload, content = {}) { + axios.get.mockResolvedValue({ data: { feedsFailed: 0, failedUrls: [], ...payload } }) + const wrapper = mount(NewsWidget, { props: { content, placement: { id: 3 } } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + axios.get.mockReset() +}) + +describe('NewsWidget safety and layout', () => { + it('strips data- and aria- attributes from summary markup', async () => { + const wrapper = await render({ items: [] }) + const out = wrapper.vm.formattedSummary({ + summary: '<p><strong data-track="1" aria-label="x">bold</strong></p>', + }) + expect(out).toBe('<p><strong>bold</strong></p>') + }) + + it.each([ + ["javascript:alert('xss')"], + ['data:text/html,<script>alert(1)</script>'], + [' JavaScript:alert(1)'], + ])('renders an item linking to %s as an inert card', async (link) => { + const wrapper = await render({ items: [{ guid: 'x', title: 'Bad', link }] }) + expect(wrapper.find('a').exists()).toBe(false) + expect(wrapper.find('.news-widget__item-link--inert').exists()).toBe(true) + }) + + it('never opens an unsafe link from the click fallback', async () => { + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + const wrapper = await render({ items: [] }) + wrapper.vm.onItemClick({ defaultPrevented: true }, { link: 'javascript:alert(1)' }) + expect(open).not.toHaveBeenCalled() + open.mockRestore() + }) + + it('badges "All N feeds failed" when every configured feed failed', async () => { + const urls = ['https://a.test/rss', 'https://b.test/rss', 'https://c.test/rss'] + const wrapper = await render({ items: [], feedsFailed: 3, failedUrls: urls }, { feedUrls: urls }) + expect(wrapper.find('.news-widget__badge').text()).toBe('All 3 feeds failed') + }) + + it('keeps the plain count when some feeds still answered', async () => { + const urls = ['https://a.test/rss', 'https://b.test/rss', 'https://c.test/rss'] + const wrapper = await render( + { items: [{ guid: 'ok', title: 'Ok', link: 'https://a.test/1' }], feedsFailed: 2, failedUrls: urls.slice(1) }, + { feedUrls: urls }, + ) + expect(wrapper.find('.news-widget__badge').text()).toBe('2 feeds failed') + }) + + it('shows an RSS icon in the empty state', async () => { + const wrapper = await render({ items: [] }) + expect(wrapper.find('.news-widget__state--empty .rss-icon svg').exists()).toBe(true) + }) + + it('gives the carousel previous and next buttons that move the shown item', async () => { + const items = [1, 2, 3].map((n) => ({ guid: `s${n}`, title: `Slide ${n}`, link: `https://a.test/${n}` })) + const wrapper = await render({ items }, { layout: 'carousel' }) + const list = wrapper.find('.news-widget__list').element + list.scrollTo = vi.fn() + + const [previous, next] = wrapper.findAll('.news-widget__carousel-nav button') + expect(previous.attributes('aria-label')).toBe('Previous item') + expect(next.attributes('aria-label')).toBe('Next item') + expect(previous.attributes('disabled')).toBeDefined() + + await next.trigger('click') + expect(wrapper.vm.carouselIndex).toBe(1) + expect(list.scrollTo).toHaveBeenCalled() + await previous.trigger('click') + expect(wrapper.vm.carouselIndex).toBe(0) + }) + + it('draws no carousel buttons in the list layout', async () => { + const items = [1, 2].map((n) => ({ guid: `l${n}`, title: `Row ${n}` })) + const wrapper = await render({ items }) + expect(wrapper.find('.news-widget__carousel-nav').exists()).toBe(false) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/NewsWidgetForm.controls.spec.js b/src/components/Widgets/Renderers/__tests__/NewsWidgetForm.controls.spec.js new file mode 100644 index 000000000..ff03d0f93 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/NewsWidgetForm.controls.spec.js @@ -0,0 +1,130 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the rendered controls of `NewsWidgetForm.vue`: the + * layout and date-format selects, the numeric item-limit and summary-length + * fields, the thumbnail/summary/metadata switches and the metadata fields + * each write back through `update:modelValue` and emit the assembled + * content. Also pins that a well-formed feed URL passes validation. + */ + +import { NcCheckboxRadioSwitch, NcSelect, NcTextField } from '@nextcloud/vue' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it } from 'vitest' + +let NewsWidgetForm + +beforeEach(async () => { + globalThis.t = (_app, key) => key + NewsWidgetForm = (await import('../NewsWidgetForm.vue')).default +}) + +function lastEmitted(wrapper) { + return wrapper.emitted('update:content')?.at(-1)?.[0] +} + +function select(wrapper, label) { + return wrapper + .findAllComponents(NcSelect) + .find((s) => s.props('inputLabel') === label) +} + +function textField(wrapper, label) { + return wrapper + .findAllComponents(NcTextField) + .find((field) => field.props('label') === label) +} + +function toggle(wrapper, text) { + return wrapper + .findAllComponents(NcCheckboxRadioSwitch) + .find((s) => s.text().includes(text)) +} + +describe('NewsWidgetForm rendered controls', () => { + it('writes the layout chosen in its select', async () => { + const wrapper = mount(NewsWidgetForm) + select(wrapper, 'Layout').vm.$emit('update:modelValue', 'grid') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).layout).toBe('grid') + expect(select(wrapper, 'Layout').props('modelValue')).toBe('grid') + }) + + it('writes the date format chosen in its select', async () => { + const wrapper = mount(NewsWidgetForm) + select(wrapper, 'Date format').vm.$emit('update:modelValue', 'absolute') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).dateFormat).toBe('absolute') + }) + + it('parses and clamps the item limit typed into its field', async () => { + const wrapper = mount(NewsWidgetForm) + const field = textField(wrapper, 'Item limit (1–50)') + field.vm.$emit('update:modelValue', '25') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).itemLimit).toBe(25) + field.vm.$emit('update:modelValue', '500') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).itemLimit).toBe(50) + expect(textField(wrapper, 'Item limit (1–50)').props('modelValue')).toBe('50') + }) + + it('parses and clamps the summary length typed into its field', async () => { + const wrapper = mount(NewsWidgetForm) + textField(wrapper, 'Summary max characters').vm.$emit('update:modelValue', '-10') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).summaryMaxChars).toBe(0) + }) + + it('writes the thumbnail and summary switches', async () => { + const wrapper = mount(NewsWidgetForm) + toggle(wrapper, 'Show thumbnails').vm.$emit('update:modelValue', false) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper)).toMatchObject({ + showThumbnails: false, + showSummary: true, + }) + toggle(wrapper, 'Show summary').vm.$emit('update:modelValue', false) + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper)).toMatchObject({ + showThumbnails: false, + showSummary: false, + }) + }) + + it('reveals the metadata fields from the switch and writes both of them', async () => { + const wrapper = mount(NewsWidgetForm) + expect(textField(wrapper, 'Metadata field key')).toBeUndefined() + + toggle(wrapper, 'Filter by dashboard metadata').vm.$emit('update:modelValue', true) + await wrapper.vm.$nextTick() + textField(wrapper, 'Metadata field key').vm.$emit('update:modelValue', 'department') + textField(wrapper, 'Metadata value to match').vm.$emit('update:modelValue', 'sales') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).metadataFilter).toEqual({ + fieldKey: 'department', + value: 'sales', + }) + }) +}) + +describe('NewsWidgetForm feed URL validation', () => { + it('accepts http and https feed URLs', () => { + const wrapper = mount(NewsWidgetForm, { + props: { + value: { feedUrls: ['https://a.test/rss', ' HTTP://b.test/atom '] }, + }, + }) + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('reports only the bad row among valid ones', () => { + const wrapper = mount(NewsWidgetForm, { + props: { value: { feedUrls: ['https://a.test/rss', 'ftp://c.test/rss'] } }, + }) + expect(wrapper.vm.validate()).toEqual([ + 'Feed URL must start with http:// or https://', + ]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/NewsWidgetForm.interaction.spec.js b/src/components/Widgets/Renderers/__tests__/NewsWidgetForm.interaction.spec.js new file mode 100644 index 000000000..2b8f1a55f --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/NewsWidgetForm.interaction.spec.js @@ -0,0 +1,119 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for how `NewsWidgetForm.vue` reacts to input: the feed + * add/remove buttons and feed URL fields, numeric fields that ignore + * non-numbers and clamp the rest, and the metadata filter fields. Every + * accepted change emits the assembled content. + */ + +import { NcTextField } from '@nextcloud/vue' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it } from 'vitest' + +let NewsWidgetForm + +beforeEach(async () => { + globalThis.t = (_app, key) => key + NewsWidgetForm = (await import('../NewsWidgetForm.vue')).default +}) + +function lastEmitted(wrapper) { + return wrapper.emitted('update:content')?.at(-1)?.[0] +} + +describe('NewsWidgetForm input handling', () => { + it('adds a feed row with the add button and removes the right one with its remove button', async () => { + const wrapper = mount(NewsWidgetForm, { + props: { value: { feedUrls: ['https://a.test/rss', 'https://b.test/rss'] } }, + }) + await wrapper.find('.news-widget-form__feed-add').trigger('click') + expect(lastEmitted(wrapper).feedUrls).toEqual([ + 'https://a.test/rss', + 'https://b.test/rss', + '', + ]) + expect(wrapper.findAll('.news-widget-form__feed-row')).toHaveLength(3) + + await wrapper.findAll('.news-widget-form__feed-remove')[0].trigger('click') + expect(lastEmitted(wrapper).feedUrls).toEqual(['https://b.test/rss', '']) + expect(wrapper.findAll('.news-widget-form__feed-row')).toHaveLength(2) + }) + + it('writes a typed feed URL to its own row', async () => { + const wrapper = mount(NewsWidgetForm, { + props: { value: { feedUrls: ['https://a.test/rss', ''] } }, + }) + const secondFeedField = wrapper + .findAll('.news-widget-form__feed-row')[1] + .findComponent(NcTextField) + secondFeedField.vm.$emit('update:modelValue', 'https://c.test/atom') + await wrapper.vm.$nextTick() + expect(lastEmitted(wrapper).feedUrls).toEqual([ + 'https://a.test/rss', + 'https://c.test/atom', + ]) + }) + + it('ignores a non-numeric value without emitting', () => { + const wrapper = mount(NewsWidgetForm) + const before = wrapper.vm.itemLimit + wrapper.vm.updateNumericField('itemLimit', 'abc', 1, 50) + expect(wrapper.vm.itemLimit).toBe(before) + expect(wrapper.emitted('update:content')).toBeUndefined() + }) + + it('parses and clamps the summary length to 0..5000', () => { + const wrapper = mount(NewsWidgetForm) + wrapper.vm.updateNumericField('summaryMaxChars', '120.9', 0, 5000) + expect(lastEmitted(wrapper).summaryMaxChars).toBe(120) + wrapper.vm.updateNumericField('summaryMaxChars', '-4', 0, 5000) + expect(lastEmitted(wrapper).summaryMaxChars).toBe(0) + wrapper.vm.updateNumericField('summaryMaxChars', '9000', 0, 5000) + expect(lastEmitted(wrapper).summaryMaxChars).toBe(5000) + }) + + it('sets plain fields and emits them', () => { + const wrapper = mount(NewsWidgetForm) + wrapper.vm.updateField('showThumbnails', false) + expect(lastEmitted(wrapper).showThumbnails).toBe(false) + wrapper.vm.updateField('dateFormat', 'absolute') + expect(lastEmitted(wrapper).dateFormat).toBe('absolute') + }) + + it('writes the metadata value, ignores an unknown metadata field, and shows the fields only when enabled', async () => { + const wrapper = mount(NewsWidgetForm) + expect(wrapper.find('.news-widget-form__metadata').exists()).toBe(false) + + wrapper.vm.toggleMetadataFilter(true) + wrapper.vm.updateMetadataField('fieldKey', 'department') + wrapper.vm.updateMetadataField('value', 'marketing') + await wrapper.vm.$nextTick() + expect(wrapper.find('.news-widget-form__metadata').exists()).toBe(true) + expect(lastEmitted(wrapper).metadataFilter).toEqual({ + fieldKey: 'department', + value: 'marketing', + }) + + const count = wrapper.emitted('update:content').length + wrapper.vm.updateMetadataField('operator', 'eq') + expect(wrapper.emitted('update:content')).toHaveLength(count + 1) + expect(lastEmitted(wrapper).metadataFilter).toEqual({ + fieldKey: 'department', + value: 'marketing', + }) + }) + + it('passes validation once an enabled filter has a field key', () => { + const wrapper = mount(NewsWidgetForm) + wrapper.vm.toggleMetadataFilter(true) + expect(wrapper.vm.validate()).toEqual([ + 'Metadata field key is required when filter is enabled', + ]) + wrapper.vm.updateMetadataField('fieldKey', ' ') + expect(wrapper.vm.validate()).toHaveLength(1) + wrapper.vm.updateMetadataField('fieldKey', 'department') + expect(wrapper.vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/PeriodField.spec.js b/src/components/Widgets/Renderers/__tests__/PeriodField.spec.js new file mode 100644 index 000000000..8762d73ee --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/PeriodField.spec.js @@ -0,0 +1,108 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The optional "Date field for the period" of a widget with a register + * source (dashboard-period-and-download REQ-DPD-002): the date fields read + * from a sample of the source's records, the select, and the chart form that + * stores the choice as the source's periodField. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ ...(await importOriginal()), translate: (_app, text) => text })) +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ ...(await importOriginal()), generateUrl: (path, params) => `/index.php${path.replace('{register}', params.register).replace('{schema}', params.schema)}` })) + +import axios from '@nextcloud/axios' +import ChartSourceForm from '../ChartSourceForm.vue' +import PeriodFieldSelect from '../PeriodFieldSelect.vue' +import { getDefaultContent } from '../../../../constants/widgetRegistry.js' +import { dateFieldsOf, fetchDateFields } from '../../../../utils/periodDateFields.js' + +const records = [ + { '@self': { created: '2026-01-01' }, title: 'Bouwvergunning', startDate: '2026-10-02', closedAt: null, decidedOn: '2026-11-01T09:30:00+01:00', count: 3 }, + { title: 'Kapvergunning', startDate: '2026-11-15', closedAt: '2026-11-20T12:00:00Z', decidedOn: 'later', count: 1 }, +] + +const NcSelect = { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel', 'placeholder', 'clearable', 'loading'], + emits: ['update:modelValue'], + template: '<div class="nc-select" />', +} +const CnChartWidgetForm = { name: 'CnChartWidgetForm', props: ['value'], emits: ['update:content'], template: '<div />' } + +beforeEach(() => { + axios.get.mockReset() +}) + +describe('dateFieldsOf', () => { + it('keeps the fields whose every value is an ISO date, metadata and empty values left out', () => { + expect(dateFieldsOf(records)).toEqual(['closedAt', 'startDate']) + }) + + it('reads nothing from no records', () => { + expect(dateFieldsOf([])).toEqual([]) + expect(dateFieldsOf(null)).toEqual([]) + expect(dateFieldsOf([null, 'x'])).toEqual([]) + }) +}) + +describe('fetchDateFields', () => { + it('samples the source\'s records once per register and schema', async () => { + axios.get.mockResolvedValue({ data: { results: records } }) + expect(await fetchDateFields('zaken', 'zaak')).toEqual(['closedAt', 'startDate']) + expect(await fetchDateFields('zaken', 'zaak')).toEqual(['closedAt', 'startDate']) + expect(axios.get).toHaveBeenCalledTimes(1) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/openregister/api/objects/zaken/zaak', { params: { _limit: 5 } }) + }) + + it('answers no fields without a register or schema, and when the records cannot be read', async () => { + expect(await fetchDateFields('', 'zaak')).toEqual([]) + axios.get.mockRejectedValue(new Error('403')) + expect(await fetchDateFields('geheim', 'zaak')).toEqual([]) + expect(axios.get).toHaveBeenCalledTimes(1) + }) +}) + +describe('PeriodFieldSelect', () => { + it('offers the date fields, keeps a stored choice and emits an empty choice as none', async () => { + axios.get.mockResolvedValue({ data: { results: records } }) + const wrapper = mount(PeriodFieldSelect, { props: { register: 'meldingen', schema: 'melding', modelValue: 'reportedOn' }, global: { stubs: { NcSelect } } }) + await flushPromises() + const select = wrapper.getComponent(NcSelect) + expect(select.props('options')).toEqual(['reportedOn', 'closedAt', 'startDate']) + expect(select.props('inputLabel')).toBe('Date field for the period') + + select.vm.$emit('update:modelValue', 'startDate') + select.vm.$emit('update:modelValue', null) + expect(wrapper.emitted('update:modelValue')).toEqual([['startDate'], ['']]) + }) +}) + +describe('ChartSourceForm period field', () => { + it('stores the chosen date field on the register query and drops it again', async () => { + const wrapper = mount(ChartSourceForm, { props: { value: getDefaultContent('graph') }, global: { stubs: { CnChartWidgetForm, PeriodFieldSelect: true, NcCheckboxRadioSwitch: true, NcSelect: true, NcTextField: true, NcButton: true, Delete: true } } }) + wrapper.getComponent(CnChartWidgetForm).vm.$emit('update:content', { chartKind: 'bar', dataSource: { register: 'zaken', schema: 'zaak' } }) + await wrapper.vm.$nextTick() + const select = wrapper.findComponent({ name: 'PeriodFieldSelect' }) + expect(select.props('register')).toBe('zaken') + expect(select.props('schema')).toBe('zaak') + + select.vm.$emit('update:modelValue', 'startDate') + expect(wrapper.emitted('update:content').at(-1)[0].dataSource).toEqual({ register: 'zaken', schema: 'zaak', periodField: 'startDate' }) + + select.vm.$emit('update:modelValue', '') + expect(wrapper.emitted('update:content').at(-1)[0].dataSource).toEqual({ register: 'zaken', schema: 'zaak' }) + }) + + it('reopens with the stored date field', () => { + const content = { ...getDefaultContent('graph'), dataSource: { register: 'zaken', schema: 'zaak', periodField: 'startDate' } } + const wrapper = mount(ChartSourceForm, { props: { editingWidget: { content } }, global: { stubs: { CnChartWidgetForm, PeriodFieldSelect: true, NcCheckboxRadioSwitch: true, NcSelect: true, NcTextField: true, NcButton: true, Delete: true } } }) + expect(wrapper.findComponent({ name: 'PeriodFieldSelect' }).props('modelValue')).toBe('startDate') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/RecentWorkWidget.spec.js b/src/components/Widgets/Renderers/__tests__/RecentWorkWidget.spec.js new file mode 100644 index 000000000..c3a0444de --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/RecentWorkWidget.spec.js @@ -0,0 +1,178 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * RecentWorkWidget: "Verder waar u was" (LpVandaag) lists the reader's own + * recent work, one row per thing, named by the thing, with app and when. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import RecentWorkWidget, { recentWhen, recentWorkRows } from '../RecentWorkWidget.vue' + +vi.mock('@nextcloud/l10n', () => ({ + getCanonicalLocale: () => 'en-GB', + t: (_app, text) => text, +})) +vi.mock('@nextcloud/router', () => ({ generateOcsUrl: (path) => '/ocs/v2.php' + path })) +const get = vi.fn() +vi.mock('@nextcloud/axios', () => ({ default: { get: (...args) => get(...args) } })) + +const NOW = new Date(2026, 9, 5, 15, 0) + +describe('recentWorkRows', () => { + it('names a row by the thing, keeps its newest activity and says app and when', () => { + const rows = recentWorkRows([ + { app: 'files', object_type: 'files', object_id: 7, object_name: '/Vergunningen/Advies welstand.pdf', link: '/f/7', datetime: new Date(2026, 9, 5, 9, 0).toISOString() }, + { app: 'files', object_type: 'files', object_id: 7, object_name: '/Vergunningen/Advies welstand.pdf', link: '/f/7', datetime: new Date(2026, 9, 4, 9, 0).toISOString() }, + { app: 'dav', object_type: 'calendar', object_id: 3, object_name: 'Spreekuur', link: '/c/3', datetime: new Date(2026, 9, 2, 9, 0).toISOString() }, + { app: 'files', object_type: 'files', object_id: 8, object_name: '', link: '/f/8', datetime: NOW.toISOString() }, + ], 6, NOW, 'en-GB') + + expect(rows.map((row) => row.title)).toEqual(['Advies welstand.pdf', 'Spreekuur']) + expect(rows[0].meta).toBe('files · this morning') + expect(rows[1].meta).toBe('calendar · Friday') + }) + + it('leaves out a record named only by its uuid, and other apps when apps are given', () => { + const rows = recentWorkRows([ + { app: 'openregister', object_type: 'object', object_id: 1, object_name: '83fc3a62-a06c-4da6-8112-70214b3cf607', link: '/o/1', datetime: NOW.toISOString() }, + { app: 'openregister', object_type: 'object', object_id: 2, object_name: 'Klacht behandeling', link: '/o/2', datetime: NOW.toISOString() }, + { app: 'files', object_type: 'files', object_id: 3, object_name: '/a.pdf', link: '/f/3', datetime: NOW.toISOString() }, + ], 6, NOW, 'en-GB', ['files']) + expect(rows.map((row) => row.title)).toEqual(['a.pdf']) + expect(recentWorkRows([{ app: 'openregister', object_type: 'object', object_id: 1, object_name: '83fc3a62-a06c-4da6-8112-70214b3cf607', link: '/o/1', datetime: NOW.toISOString() }], 6, NOW, 'en-GB')).toEqual([]) + }) + + it('leaves out what the reader deleted', () => { + const rows = recentWorkRows([ + { app: 'files', type: 'file_deleted', subject: 'You deleted a.pdf', object_type: 'files', object_id: 1, object_name: '/a.pdf', link: '/f/1', datetime: NOW.toISOString() }, + { app: 'files', type: 'file_changed', object_type: 'files', object_id: 2, object_name: '/b.pdf', link: '/f/2', datetime: NOW.toISOString() }, + ], 6, NOW, 'en-GB') + expect(rows.map((row) => row.title)).toEqual(['b.pdf']) + }) + + it('leaves out the older activity of a file the reader deleted later (REQ-WDG-032)', () => { + const rows = recentWorkRows([ + { app: 'files', type: 'file_deleted', subject: 'You deleted concept.docx', object_type: 'files', object_id: 7, object_name: '/concept.docx', link: '/f/7', datetime: NOW.toISOString() }, + { app: 'files', type: 'file_changed', object_type: 'files', object_id: 7, object_name: '/concept.docx', link: '/f/7', datetime: NOW.toISOString() }, + { app: 'files', type: 'file_created', object_type: 'files', object_id: 7, object_name: '/concept.docx', link: '/f/7', datetime: NOW.toISOString() }, + { app: 'files', type: 'file_changed', object_type: 'files', object_id: 8, object_name: '/plan.pdf', link: '/f/8', datetime: NOW.toISOString() }, + ], 6, NOW, 'en-GB') + expect(rows.map((row) => row.title)).toEqual(['plan.pdf']) + }) + + it('shows a file saved again under a new id once', () => { + const rows = recentWorkRows([ + { app: 'files', object_type: 'files', object_id: 1, object_name: '/a/plan.pdf', link: '/f/1', datetime: NOW.toISOString() }, + { app: 'files', object_type: 'files', object_id: 2, object_name: '/a/plan.pdf', link: '/f/2', datetime: NOW.toISOString() }, + ], 6, NOW, 'en-GB') + expect(rows).toHaveLength(1) + }) + + it('stops at the limit', () => { + const many = Array.from({ length: 9 }, (_, i) => ({ app: 'deck', object_type: 'card', object_id: i, object_name: 'Card ' + i, link: '/d/' + i, datetime: NOW.toISOString() })) + expect(recentWorkRows(many, 3, NOW, 'en-GB')).toHaveLength(3) + }) + + it('words today by the part of the day and older days by date', () => { + expect(recentWhen(new Date(2026, 9, 5, 16, 0).toISOString(), NOW, 'en-GB')).toBe('this afternoon') + expect(recentWhen(new Date(2026, 8, 20, 16, 0).toISOString(), NOW, 'en-GB')).toMatch(/^20 Sep/) + }) + + it('leaves out activity without a link', () => { + const rows = recentWorkRows([ + { app: 'files', object_type: 'files', object_id: 1, object_name: '/a.pdf', link: '', datetime: NOW.toISOString() }, + { app: 'files', object_type: 'files', object_id: 2, object_name: '/b.pdf', datetime: NOW.toISOString() }, + { app: 'files', object_type: 'files', object_id: 3, object_name: '/c.pdf', link: '/f/3', datetime: NOW.toISOString() }, + ], 6, NOW, 'en-GB') + expect(rows.map((row) => row.title)).toEqual(['c.pdf']) + expect(rows[0].link).toBe('/f/3') + }) + + it('reads nothing from a missing list', () => { + expect(recentWorkRows(null, 6, NOW, 'en-GB')).toEqual([]) + }) +}) + +describe('recentWhen', () => { + it.each([ + [new Date(2026, 9, 5, 0, 0), 'this morning'], + [new Date(2026, 9, 5, 11, 59), 'this morning'], + [new Date(2026, 9, 5, 12, 0), 'this afternoon'], + [new Date(2026, 9, 5, 17, 59), 'this afternoon'], + [new Date(2026, 9, 5, 18, 0), 'this evening'], + ])('words %s today as %s', (when, words) => { + const late = new Date(2026, 9, 5, 23, 0) + expect(recentWhen(when.toISOString(), late, 'en-GB')).toBe(words) + }) + + it('names the weekday within the last week', () => { + expect(recentWhen(new Date(2026, 9, 4, 10, 0).toISOString(), NOW, 'en-GB')).toBe('Sunday') + expect(recentWhen(new Date(2026, 8, 30, 10, 0).toISOString(), NOW, 'en-GB')).toBe('Wednesday') + }) + + it('writes the day and month before that', () => { + expect(recentWhen(new Date(2026, 8, 28, 10, 0).toISOString(), NOW, 'en-GB')).toMatch(/^28 Sep/) + }) + + it('says nothing for a date it cannot read', () => { + expect(recentWhen('not a date', NOW, 'en-GB')).toBe('') + expect(recentWhen(undefined, NOW, 'en-GB')).toBe('') + }) +}) + +describe('RecentWorkWidget', () => { + it('asks the Activity app for the reader\'s own activity and lists it', async () => { + get.mockResolvedValue({ data: { ocs: { data: [{ app: 'files', object_type: 'files', object_id: 1, object_name: '/a.pdf', link: '/f/1', datetime: new Date().toISOString() }] } } }) + const wrapper = mount(RecentWorkWidget, { props: { content: {} } }) + await flushPromises() + await flushPromises() + + expect(get.mock.calls[0][0]).toBe('/ocs/v2.php/apps/activity/api/v2/activity/self') + expect(wrapper.findAll('[data-testid="recent-work-row"]')).toHaveLength(1) + }) + + it('says it needs the Activity app when that cannot answer', async () => { + get.mockRejectedValue({ response: { status: 404 } }) + const wrapper = mount(RecentWorkWidget, { props: { content: {} } }) + await flushPromises() + await flushPromises() + + expect(wrapper.find('[data-testid="recent-work-unavailable"]').exists()).toBe(true) + }) + + it('says there is nothing when the reader has no activity', async () => { + get.mockResolvedValue({ data: { ocs: { data: [] } } }) + const wrapper = mount(RecentWorkWidget, { props: { content: {} } }) + await flushPromises() + await flushPromises() + + expect(wrapper.find('[data-testid="recent-work-empty"]').text()).toBe('Nothing you worked on recently.') + expect(wrapper.find('[data-testid="recent-work-unavailable"]').exists()).toBe(false) + }) + + it('treats 304 as no activity yet, not as a missing app', async () => { + get.mockRejectedValue({ response: { status: 304 } }) + const wrapper = mount(RecentWorkWidget, { props: { content: {} } }) + await flushPromises() + await flushPromises() + + expect(wrapper.find('[data-testid="recent-work-empty"]').exists()).toBe(true) + }) + + it('applies the limit and the apps of its content', async () => { + get.mockResolvedValue({ data: { ocs: { data: [ + { app: 'files', object_type: 'files', object_id: 1, object_name: '/a.pdf', link: '/f/1', datetime: new Date().toISOString() }, + { app: 'deck', object_type: 'card', object_id: 2, object_name: 'Card', link: '/d/2', datetime: new Date().toISOString() }, + { app: 'files', object_type: 'files', object_id: 3, object_name: '/b.pdf', link: '/f/3', datetime: new Date().toISOString() }, + ] } } }) + const wrapper = mount(RecentWorkWidget, { props: { content: { limit: 1, apps: ['files'] } } }) + await flushPromises() + await flushPromises() + + const rows = wrapper.findAll('[data-testid="recent-work-row"]') + expect(rows).toHaveLength(1) + expect(rows[0].text()).toContain('a.pdf') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/RecentWorkWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/RecentWorkWidgetForm.spec.js new file mode 100644 index 000000000..ad8ac2355 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/RecentWorkWidgetForm.spec.js @@ -0,0 +1,83 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `RecentWorkWidgetForm.vue`: the number of items the + * recent-work widget lists, its default, its 1 to 20 clamp and what the form + * emits to the add/edit modal. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import RecentWorkWidgetForm from '../RecentWorkWidgetForm.vue' + +/** + * @param {object} [props] props for the form. + * @return {import('@vue/test-utils').VueWrapper} the mounted form. + */ +function mountForm(props = {}) { + return mount(RecentWorkWidgetForm, { + propsData: props, + global: { stubs: { NcTextField: true } }, + }) +} + +describe('RecentWorkWidgetForm: initial number of items', () => { + it('starts at 6 in create mode', () => { + expect(mountForm().vm.limit).toBe(6) + }) + + it('takes the limit of the placement being edited over the initial value', () => { + const wrapper = mountForm({ editingWidget: { content: { limit: 9 } }, value: { limit: 3 } }) + expect(wrapper.vm.limit).toBe(9) + }) + + it('takes the initial value when nothing is being edited', () => { + expect(mountForm({ value: { limit: '4' } }).vm.limit).toBe(4) + }) + + it('falls back to 6 for a stored limit that is not a positive number', () => { + expect(mountForm({ value: { limit: 0 } }).vm.limit).toBe(6) + expect(mountForm({ value: { limit: 'many' } }).vm.limit).toBe(6) + }) + + it('shows the limit in the number field', () => { + const field = mountForm({ value: { limit: 7 } }).find('[data-testid="recent-work-form-limit"]') + expect(field.attributes('modelvalue')).toBe('7') + }) +}) + +describe('RecentWorkWidgetForm: typing a number', () => { + it('emits the typed number as the content limit', () => { + const wrapper = mountForm() + wrapper.vm.update('12') + expect(wrapper.vm.limit).toBe(12) + expect(wrapper.emitted('update:content')).toEqual([[{ limit: 12 }]]) + }) + + it('rounds a fraction to the nearest whole number', () => { + const wrapper = mountForm() + wrapper.vm.update('3.6') + expect(wrapper.emitted('update:content').at(-1)).toEqual([{ limit: 4 }]) + }) + + it('clamps to at least 1 and at most 20', () => { + const wrapper = mountForm() + wrapper.vm.update('-5') + expect(wrapper.emitted('update:content').at(-1)).toEqual([{ limit: 1 }]) + wrapper.vm.update(250) + expect(wrapper.emitted('update:content').at(-1)).toEqual([{ limit: 20 }]) + }) + + it('goes back to 6 when the field holds no number', () => { + const wrapper = mountForm({ value: { limit: 10 } }) + wrapper.vm.update('abc') + expect(wrapper.emitted('update:content').at(-1)).toEqual([{ limit: 6 }]) + }) + + it('updates through the number field event', async () => { + const wrapper = mountForm() + await wrapper.findComponent({ name: 'NcTextField' }).vm.$emit('update:modelValue', '8') + expect(wrapper.emitted('update:content').at(-1)).toEqual([{ limit: 8 }]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/SearchWidget.spec.js b/src/components/Widgets/Renderers/__tests__/SearchWidget.spec.js index 9ea4c74c3..50be3044c 100644 --- a/src/components/Widgets/Renderers/__tests__/SearchWidget.spec.js +++ b/src/components/Widgets/Renderers/__tests__/SearchWidget.spec.js @@ -164,3 +164,64 @@ describe('SearchWidget — dimming is store state (REQ-QSEARCH-002)', () => { ).toBe(false) }) }) + +describe('SearchWidget — internet search form (LpWerkplek)', () => { + it('draws a field, the engine and Search, and opens the engine results in a new tab', async () => { + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + const wrapper = mountWidget({ content: { layout: 'web' } }) + expect(wrapper.find('[data-testid="search-widget-web"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="search-widget-engine"]').text()).toBe('DuckDuckGo') + expect(wrapper.findComponent(RuntimeShellSearch).exists()).toBe(false) + + await wrapper.find('input[type="search"]').setValue('omgevingswet') + await wrapper.find('form').trigger('submit') + expect(open).toHaveBeenCalledWith('https://duckduckgo.com/?q=omgevingswet', '_blank', 'noopener,noreferrer') + open.mockRestore() + }) + + it('uses the configured engine, with the words encoded into its {q} slot', async () => { + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + const wrapper = mountWidget({ + content: { layout: 'web', engine: { name: 'Startpage', url: 'https://www.startpage.com/do/search?query={q}' } }, + }) + expect(wrapper.find('[data-testid="search-widget-engine"]').text()).toBe('Startpage') + + await wrapper.find('input[type="search"]').setValue(' bouw & wonen ') + await wrapper.find('form').trigger('submit') + expect(open).toHaveBeenCalledWith('https://www.startpage.com/do/search?query=bouw%20%26%20wonen', '_blank', 'noopener,noreferrer') + open.mockRestore() + }) + + it('falls back to DuckDuckGo for an engine url without a {q} slot', () => { + const wrapper = mountWidget({ content: { layout: 'web', engine: { name: 'Broken', url: 'https://example.org/search' } } }) + expect(wrapper.vm.engine).toEqual({ name: 'DuckDuckGo', url: 'https://duckduckgo.com/?q={q}' }) + }) + + it('opens nothing for blank words', async () => { + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + const wrapper = mountWidget({ content: { layout: 'web' } }) + await wrapper.find('input[type="search"]').setValue(' ') + await wrapper.find('form').trigger('submit') + expect(open).not.toHaveBeenCalled() + open.mockRestore() + }) + + // @spec openspec/changes/archive/2026-11-24-recent-work-and-web-search-widgets/specs/widgets/spec.md#requirement-the-search-widget-can-search-the-internet-req-wdg-033 + it('encodes the space between words (Pieter searches the internet)', async () => { + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + const wrapper = mountWidget({ content: { layout: 'web' } }) + await wrapper.find('input[type="search"]').setValue('omgevingswet termijnen') + await wrapper.find('form').trigger('submit') + expect(open).toHaveBeenCalledWith('https://duckduckgo.com/?q=omgevingswet%20termijnen', '_blank', 'noopener,noreferrer') + open.mockRestore() + }) + + it('names DuckDuckGo on screen for an engine url without a {q} slot', () => { + const wrapper = mountWidget({ content: { layout: 'web', engine: { name: 'Intranet', url: 'https://intranet.example.nl/search' } } }) + expect(wrapper.find('[data-testid="search-widget-engine"]').text()).toBe('DuckDuckGo') + }) + + it('keeps the tile search without the web layout', () => { + expect(mountWidget().find('[data-testid="search-widget-web"]').exists()).toBe(false) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/SectionHeadingWidget.spec.js b/src/components/Widgets/Renderers/__tests__/SectionHeadingWidget.spec.js new file mode 100644 index 000000000..44ba6a6c5 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/SectionHeadingWidget.spec.js @@ -0,0 +1,69 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The section heading widget ("Tussenkop", REQ-WDG-031): its renderer, its + * form, its registration and its full-width size. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, text) => text, + translate: (_app, text) => text, +})) +vi.mock('@nextcloud/vue', () => ({ + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label', 'helperText', 'required'], + emits: ['update:modelValue'], + template: '<input :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)">', + }, +})) + +import SectionHeadingWidget from '../SectionHeadingWidget.vue' +import SectionHeadingWidgetForm from '../SectionHeadingWidgetForm.vue' +import { defaultSizeFor, ONE_ROW_TYPES } from '../../../../composables/useGridManager.js' + +describe('SectionHeadingWidget', () => { + it('draws the title as a heading and the explanation below it', () => { + const wrapper = mount(SectionHeadingWidget, { + props: { content: { title: 'Samenwerken', description: 'De tegels van het team' } }, + }) + expect(wrapper.find('h2').text()).toBe('Samenwerken') + expect(wrapper.find('p').text()).toBe('De tegels van het team') + }) + + it('leaves the explanation out when there is none, and shows a placeholder without a title', () => { + const wrapper = mount(SectionHeadingWidget, { props: { content: { title: ' ' } } }) + expect(wrapper.find('h2').text()).toBe('Section heading') + expect(wrapper.find('p').exists()).toBe(false) + }) +}) + +describe('SectionHeadingWidgetForm', () => { + it('emits the trimmed title and explanation', async () => { + const wrapper = mount(SectionHeadingWidgetForm, { props: { editingWidget: null } }) + await wrapper.find('[data-testid="section-heading-form-title"]').setValue(' Wegwijs ') + await wrapper.find('[data-testid="section-heading-form-description"]').setValue('Snel naar de vaste plekken') + expect(wrapper.emitted('update:content').at(-1)[0]).toEqual({ title: 'Wegwijs', description: 'Snel naar de vaste plekken' }) + }) + + it('starts from the placement being edited, and needs a title', () => { + const editing = mount(SectionHeadingWidgetForm, { + props: { editingWidget: { content: { title: 'Collega\'s', description: 'Wie nieuw is' } } }, + }) + expect(editing.vm.validate()).toEqual([]) + expect(mount(SectionHeadingWidgetForm, { props: { editingWidget: null } }).vm.validate()).toEqual(['Give the heading a title']) + }) +}) + +describe('section-heading placement', () => { + it('spans the grid\'s full width, one row tall', () => { + expect(defaultSizeFor('section-heading', 12)).toEqual({ w: 12, h: 1 }) + expect(defaultSizeFor('section-heading', 8)).toEqual({ w: 8, h: 1 }) + expect(ONE_ROW_TYPES).toContain('section-heading') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/StatusReportWidget.spec.js b/src/components/Widgets/Renderers/__tests__/StatusReportWidget.spec.js new file mode 100644 index 000000000..5195dd6f4 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/StatusReportWidget.spec.js @@ -0,0 +1,160 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * StatusReportWidget: prefilled by the product, edited by a person, kept + * with the record of which is which (dashboards-and-who-may-see-them REQ-DWMS-004). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const interpolate = (text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`) +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => interpolate(text, vars), +})) +vi.mock('@nextcloud/vue', () => ({ + NcButton: { name: 'NcButton', props: ['disabled', 'type', 'variant'], emits: ['click'], template: '<button :type="type || \'button\'" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, + NcSelect: { name: 'NcSelect', props: ['modelValue', 'options', 'inputLabel', 'clearable', 'reduce', 'label'], emits: ['update:modelValue'], template: '<div class="select-stub" :data-value="modelValue" />' }, + NcTextArea: { name: 'NcTextArea', props: ['modelValue', 'label', 'maxlength', 'resize'], emits: ['update:modelValue'], template: '<textarea :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' }, +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const draftStatusReport = vi.fn() +const keepStatusReport = vi.fn() +vi.mock('../../../../services/statusReport.js', async () => { + const actual = await vi.importActual('../../../../services/statusReport.js') + return { + subjectOf: actual.subjectOf, + draftStatusReport: (...args) => draftStatusReport(...args), + keepStatusReport: (...args) => keepStatusReport(...args), + } +}) + +import StatusReportWidget from '../StatusReportWidget.vue' + +const CONTENT = { register: 'dossiq', schema: 'case', title: 'Programme X', deadline: '2026-12-31', closedValues: ['done'] } +const SUBJECT = { register: 'dossiq', schema: 'case', title: 'Programme X', deadline: '2026-12-31', closedValues: ['done'] } + +function draft() { + return { + date: '2026-11-16', + subject: SUBJECT, + health: 'at-risk', + summary: '4 of 10 items are closed; 2 are overdue.', + figures: { total: 10, open: 6, closed: 4, overdue: 2, percentClosed: 40, daysToDeadline: 45 }, + provenance: { date: 'computed', health: 'computed', summary: 'computed', figures: {} }, + } +} + +beforeEach(() => { + draftStatusReport.mockReset() + keepStatusReport.mockReset() +}) + +async function prepared() { + draftStatusReport.mockResolvedValue({ refused: false, report: draft() }) + const wrapper = mount(StatusReportWidget, { props: { content: CONTENT } }) + await wrapper.find('[data-testid="status-report-prepare"]').trigger('click') + await flushPromises() + return wrapper +} + +describe('StatusReportWidget', () => { + it('asks for its settings when no register and schema are set', () => { + const wrapper = mount(StatusReportWidget, { props: { content: { title: 'x' } } }) + + expect(wrapper.find('[data-testid="status-report-unconfigured"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="status-report-prepare"]').exists()).toBe(false) + }) + + it('names the body of work and its deadline', () => { + const wrapper = mount(StatusReportWidget, { props: { content: CONTENT } }) + + expect(wrapper.find('[data-testid="status-report-subject"]').text()).toBe('Status of Programme X, deadline 2026-12-31') + }) + + it('prefills the figures, the rating and the summary from the draft', async () => { + const wrapper = await prepared() + + expect(draftStatusReport).toHaveBeenCalledWith(SUBJECT) + expect(wrapper.find('[data-testid="status-report-figure-total"]').text()).toBe('10') + expect(wrapper.find('[data-testid="status-report-figure-percentClosed"]').text()).toBe('40%') + expect(wrapper.find('[data-testid="status-report-figure-daysToDeadline"]').text()).toBe('45') + expect(wrapper.find('.select-stub').attributes('data-value')).toBe('at-risk') + expect(wrapper.find('textarea').element.value).toBe('4 of 10 items are closed; 2 are overdue.') + }) + + it('keeps the report with the summary the person wrote and shows it as written', async () => { + const wrapper = await prepared() + keepStatusReport.mockResolvedValue({ + refused: false, + report: { ...draft(), summary: 'Behind, recovering.', provenance: { date: 'computed', health: 'computed', summary: 'written', figures: {} } }, + }) + + await wrapper.find('textarea').setValue('Behind, recovering.') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(keepStatusReport).toHaveBeenCalledWith(SUBJECT, 'at-risk', 'Behind, recovering.') + expect(wrapper.find('[data-testid="status-report-kept"]').text()).toContain('Behind, recovering.') + expect(wrapper.find('[data-testid="status-report-provenance-summary"]').text()).toBe('Summary: written by a person') + expect(wrapper.find('[data-testid="status-report-provenance-health"]').text()).toBe('Health rating: computed by LaunchPad') + }) + + it('sends the rating the person picked', async () => { + const wrapper = await prepared() + keepStatusReport.mockResolvedValue({ refused: false, report: { ...draft(), health: 'off-track' } }) + + await wrapper.findComponent({ name: 'NcSelect' }).vm.$emit('update:modelValue', 'off-track') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(keepStatusReport).toHaveBeenCalledWith(SUBJECT, 'off-track', '4 of 10 items are closed; 2 are overdue.') + expect(wrapper.find('[data-testid="status-report-kept"]').text()).toContain('Off track') + }) + + it('does not keep an empty summary', async () => { + const wrapper = await prepared() + + await wrapper.find('textarea').setValue(' ') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(keepStatusReport).not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="status-report-keep"]').attributes('disabled')).toBeDefined() + }) + + it('says OpenRegister is needed when keeping is refused with 503', async () => { + const wrapper = await prepared() + keepStatusReport.mockResolvedValue({ refused: true, status: 503 }) + + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.find('[data-testid="status-report-refused"]').text()).toBe('Status reports need OpenRegister, which is not available.') + expect(wrapper.find('[data-testid="status-report-kept"]').exists()).toBe(false) + }) + + it('says the settings are wrong when the draft is refused with 400', async () => { + draftStatusReport.mockResolvedValue({ refused: true, status: 400 }) + const wrapper = mount(StatusReportWidget, { props: { content: CONTENT } }) + await wrapper.find('[data-testid="status-report-prepare"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="status-report-refused"]').text()).toContain('check the register, the schema and the deadline') + expect(wrapper.find('[data-testid="status-report-draft"]').exists()).toBe(false) + }) + + it('starts over after a report was kept', async () => { + const wrapper = await prepared() + keepStatusReport.mockResolvedValue({ refused: false, report: draft() }) + await wrapper.find('form').trigger('submit') + await flushPromises() + + await wrapper.find('[data-testid="status-report-new"]').trigger('click') + + expect(wrapper.find('[data-testid="status-report-kept"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="status-report-prepare"]').text()).toBe('Prepare report') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/StatusReportWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/StatusReportWidgetForm.spec.js new file mode 100644 index 000000000..80b9b43fc --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/StatusReportWidgetForm.spec.js @@ -0,0 +1,60 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * StatusReportWidgetForm: the body of work a status report is about + * (REQ-DWMS-004), in the protocol the add-widget modal speaks. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) +vi.mock('@nextcloud/vue', () => ({ + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label', 'type', 'helperText'], + emits: ['update:modelValue'], + template: '<input class="field-stub" :data-label="label" :value="modelValue">', + }, +})) + +import StatusReportWidgetForm from '../StatusReportWidgetForm.vue' + +describe('StatusReportWidgetForm', () => { + it('opens on the widget being edited, closed values joined with commas', () => { + const wrapper = mount(StatusReportWidgetForm, { + props: { editingWidget: { content: { register: 'dossiq', schema: 'case', closedValues: ['done', 'closed'] } } }, + }) + + expect(wrapper.find('[data-testid="status-report-form-register"]').element.value).toBe('dossiq') + expect(wrapper.find('[data-testid="status-report-form-closedValues"]').element.value).toBe('done, closed') + expect(wrapper.vm.validate()).toEqual([]) + }) + + it('refuses to save without a register and a schema', () => { + const wrapper = mount(StatusReportWidgetForm) + + expect(wrapper.vm.validate()).toEqual(['A status report needs the register and the schema of the body of work.']) + }) + + it('emits the whole body of work on every change, closed values as a list', async () => { + const wrapper = mount(StatusReportWidgetForm, { props: { editingWidget: { content: { register: 'dossiq' } } } }) + const fields = wrapper.findAllComponents({ name: 'NcTextField' }) + const byLabel = (label) => fields.find((field) => field.props('label') === label) + + await byLabel('Schema').vm.$emit('update:modelValue', ' case ') + await byLabel('Values that mean closed').vm.$emit('update:modelValue', 'done, ,closed') + + expect(wrapper.emitted('update:content').at(-1)[0]).toEqual({ + title: '', + register: 'dossiq', + schema: 'case', + deadline: '', + statusProperty: '', + closedValues: ['done', 'closed'], + dueProperty: '', + }) + expect(wrapper.vm.validate()).toEqual([]) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/TileHost.spec.js b/src/components/Widgets/Renderers/__tests__/TileHost.spec.js new file mode 100644 index 000000000..5834debb6 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/TileHost.spec.js @@ -0,0 +1,52 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * integrations-office-tiles: inside a container a `create` tile renders + * through LaunchPad's TileWidget; every other tile keeps the shared + * CnDashTileWidget with the same content, placement and attributes. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnDashTileWidget: { name: 'CnDashTileWidget', props: ['content', 'placement', 'canEdit'], template: '<div class="cn-tile" />' }, +})) +vi.mock('../../../TileWidget.vue', () => ({ + default: { name: 'TileWidget', props: ['tile', 'editMode'], template: '<div class="lp-tile" />' }, +})) + +const { default: TileHost } = await import('../TileHost.vue') + +describe('TileHost', () => { + it('renders a create tile through TileWidget with the child content', () => { + const content = { title: 'New document', linkType: 'create', linkValue: 'richdocuments:.docx', icon: 'icon-filetype-file', iconType: 'class' } + const wrapper = mount(TileHost, { props: { content, placement: { id: 3 }, editMode: true } }) + + const tile = wrapper.findComponent({ name: 'TileWidget' }) + expect(wrapper.findComponent({ name: 'CnDashTileWidget' }).exists()).toBe(false) + expect(tile.props('editMode')).toBe(true) + expect(tile.props('tile')).toMatchObject({ id: 3, title: 'New document', linkType: 'create', linkValue: 'richdocuments:.docx', icon: 'icon-filetype-file', iconType: 'class' }) + }) + + it('names a create tile without a placement id after its creator', () => { + const wrapper = mount(TileHost, { props: { content: { linkType: 'create', linkValue: 'onlyoffice:.xlsx' } } }) + + expect(wrapper.findComponent({ name: 'TileWidget' }).props('tile').id).toBe('create-onlyoffice:.xlsx') + }) + + it('hands every other tile to CnDashTileWidget unchanged', () => { + const content = { title: 'Files', linkType: 'app', linkValue: '/apps/files/' } + const placement = { id: 4 } + const wrapper = mount(TileHost, { props: { content, placement }, attrs: { canEdit: true } }) + + const shared = wrapper.findComponent({ name: 'CnDashTileWidget' }) + expect(wrapper.findComponent({ name: 'TileWidget' }).exists()).toBe(false) + expect(shared.props('content')).toEqual(content) + expect(shared.props('placement')).toEqual(placement) + expect(shared.props('canEdit')).toBe(true) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/VideoHost.spec.js b/src/components/Widgets/Renderers/__tests__/VideoHost.spec.js new file mode 100644 index 000000000..dfab6ef50 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/VideoHost.spec.js @@ -0,0 +1,97 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `VideoHost.vue` (REQ-VID-006): a Nextcloud-file + * video is resolved through the placement's file endpoint before + * CnVideoWidget renders it; hosted players pass straight through. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import VideoHost from '../VideoHost.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + '/index.php' + path.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + CnVideoWidget: { name: 'CnVideoWidget', props: ['content', 'canEdit'], emits: ['edit'], template: '<div class="cn-video" />' }, + NcLoadingIcon: { name: 'NcLoadingIcon', template: '<span class="loading" />' }, +})) + +const FILE = { sourceType: 'nc-file', fileId: 42, autoplay: false } + +beforeEach(() => { + globalThis.t = (_app, key) => key + axios.get.mockReset() +}) + +/** + * Mount the host and let the file request settle. + * + * @param {object} content The placement content. + * @return {Promise<object>} the CnVideoWidget content prop. + */ +async function renderedContent(content) { + const wrapper = mount(VideoHost, { props: { content, placement: { id: 7 } } }) + await flushPromises() + return wrapper.findComponent({ name: 'CnVideoWidget' }).props('content') +} + +/** + * An axios rejection carrying the endpoint's error code. + * + * @param {number} status The HTTP status. + * @param {string} error The error code. + * @return {Error} + */ +function refusal(status, error) { + return Object.assign(new Error('refused'), { response: { status, data: { error } } }) +} + +describe('VideoHost', () => { + it('asks the placement\'s file endpoint and plays the streaming URL it answers', async () => { + axios.get.mockResolvedValue({ data: { streamingUrl: '/remote.php/dav/files/bob/a.webm' } }) + + const content = await renderedContent(FILE) + + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/widgets/video/7/file') + expect(content).toEqual({ ...FILE, fileStreamingUrl: '/remote.php/dav/files/bob/a.webm' }) + }) + + it('shows "Video file not found" for a deleted file and "File is not a video" for a non-video', async () => { + axios.get.mockRejectedValueOnce(refusal(404, 'not_found')) + expect(await renderedContent(FILE)).toMatchObject({ error: 'Video file not found', fileStreamingUrl: '' }) + + axios.get.mockRejectedValueOnce(refusal(422, 'not_video')) + expect(await renderedContent(FILE)).toMatchObject({ error: 'File is not a video', fileStreamingUrl: '' }) + }) + + it('leaves the URL empty for an unreadable file, so the widget says "Video not accessible"', async () => { + axios.get.mockRejectedValue(refusal(403, 'not_accessible')) + + const content = await renderedContent(FILE) + + expect(content.fileStreamingUrl).toBe('') + expect(content.error).toBeUndefined() + }) + + it('passes a hosted player through without asking the file endpoint', async () => { + const youtube = { sourceType: 'youtube', videoUrl: 'https://www.youtube.com/embed/ABC' } + + expect(await renderedContent(youtube)).toEqual(youtube) + expect(axios.get).not.toHaveBeenCalled() + }) + + it('passes edit mode to the widget and relays its "Configure now" as edit', async () => { + const wrapper = mount(VideoHost, { props: { content: { sourceType: null }, placement: { id: 7 }, canEdit: true } }) + await flushPromises() + const widget = wrapper.findComponent({ name: 'CnVideoWidget' }) + expect(widget.props('canEdit')).toBe(true) + widget.vm.$emit('edit') + expect(wrapper.emitted('edit')).toHaveLength(1) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/VideoWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/VideoWidgetForm.spec.js new file mode 100644 index 000000000..7db4389f5 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/VideoWidgetForm.spec.js @@ -0,0 +1,94 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The video form asks the parse endpoint about each URL and shows its error + * under the field, which blocks saving (REQ-VID-005 "Invalid URL error"). + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import VideoWidgetForm from '../VideoWidgetForm.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { post: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('@conduction/nextcloud-vue', () => ({ + CnVideoWidgetForm: { + name: 'CnVideoWidgetForm', + props: ['editingWidget', 'value', 'urlError'], + emits: ['update:content'], + template: '<div class="cn-video-form" />', + computed: { assembledContent: () => ({ videoUrl: 'x' }) }, + methods: { + validate() { + return this.urlError ? [this.urlError] : [] + }, + }, + }, +})) + +/** + * Mount the form and type a URL into the shared form. + * + * @param {object} content The content the shared form emits. + * @return {Promise<object>} The wrapper. + */ +async function typed(content) { + const wrapper = mount(VideoWidgetForm) + wrapper.findComponent({ name: 'CnVideoWidgetForm' }).vm.$emit('update:content', content) + vi.advanceTimersByTime(300) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.useFakeTimers() + axios.post.mockReset() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('VideoWidgetForm', () => { + it('shows the endpoint\'s error for an invalid URL, and validate returns it', async () => { + axios.post.mockRejectedValue({ response: { status: 400, data: { isValid: false, error: 'Invalid URL format' } } }) + const wrapper = await typed({ sourceType: null, videoUrl: 'not a valid URL' }) + + expect(axios.post).toHaveBeenCalledWith('/index.php/apps/launchpad/api/widgets/video/parse', { videoUrl: 'not a valid URL' }) + expect(wrapper.findComponent({ name: 'CnVideoWidgetForm' }).props('urlError')).toBe('Invalid URL format') + expect(wrapper.vm.validate()).toEqual(['Invalid URL format']) + expect(wrapper.emitted('update:content')).toHaveLength(2) + }) + + it('clears the error for a URL the endpoint accepts', async () => { + axios.post.mockResolvedValue({ data: { isValid: true, canonicalUrl: 'https://www.youtube.com/embed/ABC123' } }) + const wrapper = await typed({ sourceType: 'youtube', videoUrl: 'https://www.youtube.com/embed/ABC123' }) + expect(wrapper.findComponent({ name: 'CnVideoWidgetForm' }).props('urlError')).toBe('') + }) + + it('does not parse a Nextcloud file source or an empty URL', async () => { + await typed({ sourceType: 'nc-file', videoUrl: '42', fileId: 42 }) + await typed({ sourceType: null, videoUrl: '' }) + expect(axios.post).not.toHaveBeenCalled() + }) + + it('ignores the answer for a URL that is no longer in the field', async () => { + let answer + axios.post.mockImplementation(() => new Promise((resolve, reject) => { + answer = reject + })) + const wrapper = await typed({ sourceType: null, videoUrl: 'old' }) + wrapper.findComponent({ name: 'CnVideoWidgetForm' }).vm.$emit('update:content', { sourceType: 'youtube', videoUrl: 'https://youtu.be/ABC123' }) + answer({ response: { data: { isValid: false, error: 'Invalid URL format' } } }) + await flushPromises() + expect(wrapper.findComponent({ name: 'CnVideoWidgetForm' }).props('urlError')).toBe('') + }) + + it('hands the shared form\'s content to the dialog', () => { + const wrapper = mount(VideoWidgetForm) + expect(wrapper.vm.assembledContent).toEqual({ videoUrl: 'x' }) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/WeatherWidget.spec.js b/src/components/Widgets/Renderers/__tests__/WeatherWidget.spec.js index 2c3ed26e4..3226d95be 100644 --- a/src/components/Widgets/Renderers/__tests__/WeatherWidget.spec.js +++ b/src/components/Widgets/Renderers/__tests__/WeatherWidget.spec.js @@ -175,3 +175,33 @@ describe('WeatherWidget — REQ-WEATHER-002 stale + error degradation', () => { expect(wrapper.find('.weather-widget__state--error').exists()).toBe(false) }) }) + +describe('WeatherWidget — REQ-PSHR-011 a public screen passes its own reading source', () => { + it('reads through readingSource instead of the signed-in endpoint', async () => { + const readingSource = vi.fn().mockResolvedValue({ + location: 'Zuiddrecht', + tempValue: 12, + units: 'metric', + condition: 'rain', + conditionText: 'Light rain', + stale: false, + }) + const wrapper = mount(WeatherWidget, { + propsData: { content: {}, placement: { id: 2 }, readingSource }, + }) + await flushPromises() + expect(readingSource).toHaveBeenCalledWith(2) + expect(fetchWeatherReading).not.toHaveBeenCalled() + expect(wrapper.vm.reading.tempValue).toBe(12) + }) + + it('shows the error state when the token-scoped read is refused', async () => { + const readingSource = vi.fn().mockRejectedValue(new Error('404')) + const wrapper = mount(WeatherWidget, { + propsData: { content: {}, placement: { id: 2 }, readingSource }, + }) + await flushPromises() + expect(wrapper.vm.reading).toBeNull() + expect(wrapper.find('.weather-widget__state--error').exists()).toBe(true) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/WikiPagesWidget.spec.js b/src/components/Widgets/Renderers/__tests__/WikiPagesWidget.spec.js new file mode 100644 index 000000000..5cfc16411 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/WikiPagesWidget.spec.js @@ -0,0 +1,151 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * WikiPagesWidget: favourites, recent pages and search over the wiki, and + * what it says when the wiki is not connected (wiki-widget REQ-WIKI-001..003). + * What OpenRegister answers is wikiPages.spec.js; here the service is given. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => { + const actual = await importOriginal() + const fill = (text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`) + return { ...actual, translate: (_app, text, vars) => fill(text, vars) } +}) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const searchWikiPages = vi.fn() +const readWikiFavourites = vi.fn() +const saveWikiFavourites = vi.fn() +vi.mock('../../../../services/wikiPages.js', () => ({ + searchWikiPages: (...args) => searchWikiPages(...args), + readWikiFavourites: (...args) => readWikiFavourites(...args), + saveWikiFavourites: (...args) => saveWikiFavourites(...args), +})) + +import WikiPagesWidget from '../WikiPagesWidget.vue' + +const CnStatusList = { + name: 'CnStatusList', + props: ['items', 'loading', 'emptyLabel'], + template: `<ul class="list"><li v-if="items.length === 0" class="empty">{{ emptyLabel }}</li> + <li v-for="item in items" :key="item.id" class="row" :data-href="item.href" :data-meta="item.meta" :data-external="String(item.external)"> + <span class="title">{{ item.title }}</span><slot name="actions" :item="item" /></li></ul>`, +} +const NcButton = { + name: 'NcButton', + props: ['ariaLabel', 'pressed', 'variant'], + emits: ['click'], + template: '<button class="star" :aria-label="ariaLabel" :aria-pressed="String(pressed)" @click="$emit(\'click\')"><slot name="icon" /></button>', +} +const NcTextField = { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue', 'trailingButtonClick'], + template: '<input class="search" :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)">', +} + +const TERMIJNEN = { reference: 'Kennisbank.Termijnen', title: 'Termijnen Omgevingswet', space: 'Kennisbank Zuiddrecht', url: 'https://wiki.example/termijnen' } +const KAP = { reference: 'Vergunningen.Kap', title: 'Werkinstructie kapvergunningen', space: 'Vergunningen', url: 'https://wiki.example/kap' } +const LEGES = { reference: 'Vergunningen.Leges', title: 'Legesverordening 2026', space: 'Vergunningen', url: 'https://wiki.example/leges' } + +/** + * Mount the widget. + * + * @param {object} content The widget content. + * @return {Promise<object>} The wrapper. + */ +async function mountWidget(content = {}) { + const wrapper = mount(WikiPagesWidget, { + props: { content, placement: {} }, + global: { stubs: { CnStatusList, NcButton, NcTextField, Star: true, StarOutline: true } }, + }) + await flushPromises() + return wrapper +} + +const titles = (section) => section.findAll('.row .title').map((node) => node.text()) + +beforeEach(() => { + vi.useFakeTimers() + searchWikiPages.mockReset().mockResolvedValue({ state: 'ok', pages: [TERMIJNEN, KAP, LEGES] }) + readWikiFavourites.mockReset().mockResolvedValue([KAP]) + saveWikiFavourites.mockReset().mockImplementation(async (pages) => pages) +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('WikiPagesWidget', () => { + it('shows the favourites and the recent pages as links into the wiki, opening in a new tab', async () => { + const wrapper = await mountWidget() + expect(searchWikiPages).toHaveBeenCalledWith('', 3) + expect(titles(wrapper.get('[data-testid="wiki-pages-favourites"]'))).toEqual(['Werkinstructie kapvergunningen']) + const recent = wrapper.get('[data-testid="wiki-pages-recent"]') + expect(titles(recent)).toEqual(['Termijnen Omgevingswet', 'Werkinstructie kapvergunningen', 'Legesverordening 2026']) + const row = recent.find('.row') + expect(row.attributes('data-href')).toBe('https://wiki.example/termijnen') + expect(row.attributes('data-external')).toBe('true') + expect(row.attributes('data-meta')).toBe('Kennisbank Zuiddrecht') + }) + + it('keeps to one space and to the list length', async () => { + const wrapper = await mountWidget({ space: 'Vergunningen', limit: 1 }) + expect(searchWikiPages).toHaveBeenCalledWith('', 50) + expect(titles(wrapper.get('[data-testid="wiki-pages-recent"]'))).toEqual(['Werkinstructie kapvergunningen']) + }) + + it('searches once typing pauses, and a cleared search shows the lists again', async () => { + const wrapper = await mountWidget() + searchWikiPages.mockResolvedValueOnce({ state: 'ok', pages: [LEGES] }) + await wrapper.get('input.search').setValue('leges') + expect(searchWikiPages).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(300) + await flushPromises() + expect(searchWikiPages).toHaveBeenLastCalledWith('leges', 10) + expect(titles(wrapper.get('[data-testid="wiki-pages-results"]'))).toEqual(['Legesverordening 2026']) + await wrapper.get('input.search').setValue('') + expect(wrapper.find('[data-testid="wiki-pages-results"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="wiki-pages-recent"]').exists()).toBe(true) + }) + + it('stars a recent page as the newest favourite and unstars a favourite', async () => { + const wrapper = await mountWidget() + const recentStars = wrapper.get('[data-testid="wiki-pages-recent"]').findAll('button.star') + expect(recentStars[0].attributes('aria-label')).toBe('Add Termijnen Omgevingswet to favourites') + expect(recentStars[1].attributes('aria-pressed')).toBe('true') + await recentStars[0].trigger('click') + await flushPromises() + expect(saveWikiFavourites).toHaveBeenLastCalledWith([TERMIJNEN, KAP]) + expect(titles(wrapper.get('[data-testid="wiki-pages-favourites"]'))).toEqual(['Termijnen Omgevingswet', 'Werkinstructie kapvergunningen']) + + await wrapper.get('[data-testid="wiki-pages-favourites"]').findAll('button.star')[1].trigger('click') + await flushPromises() + expect(saveWikiFavourites).toHaveBeenLastCalledWith([TERMIJNEN]) + }) + + it('puts the favourites back when saving fails', async () => { + saveWikiFavourites.mockRejectedValueOnce(new Error('500')) + const wrapper = await mountWidget() + await wrapper.get('[data-testid="wiki-pages-favourites"]').find('button.star').trigger('click') + await flushPromises() + expect(titles(wrapper.get('[data-testid="wiki-pages-favourites"]'))).toEqual(['Werkinstructie kapvergunningen']) + }) + + it('says the wiki is not connected when OpenRegister has no XWiki source', async () => { + searchWikiPages.mockResolvedValue({ state: 'not-connected', pages: [] }) + const wrapper = await mountWidget() + expect(wrapper.get('[data-testid="wiki-pages-not-connected"]').text()).toBe('The wiki is not connected yet. Ask your administrator to connect XWiki.') + expect(wrapper.find('input.search').exists()).toBe(false) + }) + + it('says OpenRegister is needed when it is not there', async () => { + searchWikiPages.mockResolvedValue({ state: 'unavailable', pages: [] }) + const wrapper = await mountWidget() + expect(wrapper.get('[data-testid="wiki-pages-not-connected"]').text()).toContain('needs OpenRegister') + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/WikiPagesWidgetForm.spec.js b/src/components/Widgets/Renderers/__tests__/WikiPagesWidgetForm.spec.js new file mode 100644 index 000000000..95233f850 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/WikiPagesWidgetForm.spec.js @@ -0,0 +1,45 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * WikiPagesWidgetForm: the space and the list length (wiki-widget REQ-WIKI-003). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ ...(await importOriginal()), translate: (_app, text) => text, t: (_app, text) => text })) + +import WikiPagesWidgetForm from '../WikiPagesWidgetForm.vue' + +const NcTextField = { name: 'NcTextField', props: ['modelValue', 'label'], emits: ['update:modelValue'], template: '<input :value="modelValue">' } + +/** + * Mount the form. + * + * @param {object} props The props. + * @return {object} The wrapper. + */ +function mountForm(props = {}) { + return mount(WikiPagesWidgetForm, { props, global: { stubs: { NcTextField } } }) +} + +describe('WikiPagesWidgetForm', () => { + it('starts from the placement content and emits the trimmed space with the limit', async () => { + const wrapper = mountForm({ editingWidget: { content: { space: 'Vergunningen', limit: 5 } } }) + const fields = wrapper.findAllComponents(NcTextField) + expect(fields[0].props('modelValue')).toBe('5') + expect(fields[1].props('modelValue')).toBe('Vergunningen') + fields[1].vm.$emit('update:modelValue', ' Kennisbank ') + expect(wrapper.emitted('update:content').at(-1)[0]).toEqual({ space: 'Kennisbank', limit: 5 }) + }) + + it('accepts 1 to 20 pages per list', () => { + const wrapper = mountForm() + expect(wrapper.vm.validate()).toEqual([]) + wrapper.vm.update({ limit: 0 }) + expect(wrapper.vm.validate()).toEqual(['Show 1 to 20 pages per list']) + wrapper.vm.update({ limit: 21 }) + expect(wrapper.vm.validate()).toHaveLength(1) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/WorkPackagesWidget.spec.js b/src/components/Widgets/Renderers/__tests__/WorkPackagesWidget.spec.js new file mode 100644 index 000000000..851e28051 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/WorkPackagesWidget.spec.js @@ -0,0 +1,90 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * WorkPackagesWidget and its form: the open work packages with status and due + * date, and what the widget says without the integration or a connected + * account (work-packages-widget REQ-WP-001..003). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ ...(await importOriginal()), translate: (_app, text) => text })) + +const loadWorkPackages = vi.fn() +vi.mock('../../../../services/workPackages.js', () => ({ loadWorkPackages: (...args) => loadWorkPackages(...args) })) + +import WorkPackagesWidget from '../WorkPackagesWidget.vue' +import WorkPackagesWidgetForm from '../WorkPackagesWidgetForm.vue' + +const CnStatusList = { name: 'CnStatusList', props: ['items', 'loading', 'error', 'emptyLabel'], template: '<div class="list" />' } + +const WELSTAND = { id: 12, subject: 'Welstandsadvies verwerken', status: 'In uitvoering', project: 'Havenpark', assignee: 'Pieter Jansen', dueDate: '2026-10-05', url: 'https://op/work_packages/12' } + +/** + * Mount the widget. + * + * @param {object} content The widget content. + * @return {Promise<object>} The wrapper. + */ +async function mountWidget(content = {}) { + const wrapper = mount(WorkPackagesWidget, { props: { content, placement: {} }, global: { stubs: { CnStatusList } } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + loadWorkPackages.mockReset().mockResolvedValue({ state: 'ok', workPackages: [WELSTAND], connectUrl: '' }) +}) + +describe('WorkPackagesWidget', () => { + it('lists the person\'s own work packages as links with project, due date and status', async () => { + const wrapper = await mountWidget() + expect(loadWorkPackages).toHaveBeenCalledWith({ scope: 'mine', project: '', limit: 4 }) + const list = wrapper.getComponent(CnStatusList) + expect(list.props('items')).toEqual([{ + id: '12', + title: 'Welstandsadvies verwerken', + href: 'https://op/work_packages/12', + external: true, + meta: 'Havenpark', + due: '2026-10-05', + status: { label: 'In uitvoering', variant: 'info' }, + }]) + expect(list.props('emptyLabel')).toBe('You have no open work packages') + }) + + it('names the assignee on a project list', async () => { + const wrapper = await mountWidget({ scope: 'project', project: 'havenpark', limit: 6 }) + expect(loadWorkPackages).toHaveBeenCalledWith({ scope: 'project', project: 'havenpark', limit: 6 }) + expect(wrapper.getComponent(CnStatusList).props('items')[0].meta).toBe('Havenpark · Pieter Jansen') + }) + + it('asks the person to connect OpenProject when their account is not connected', async () => { + loadWorkPackages.mockResolvedValue({ state: 'not-connected', workPackages: [], connectUrl: '/index.php/settings/user/openproject' }) + const wrapper = await mountWidget() + const notice = wrapper.get('[data-testid="work-packages-not-connected"]') + expect(notice.text()).toContain('Connect your OpenProject account') + expect(notice.get('a').attributes('href')).toBe('/index.php/settings/user/openproject') + }) + + it('says the integration is needed without it, and shows an error when reading fails', async () => { + loadWorkPackages.mockResolvedValue({ state: 'not-installed', workPackages: [], connectUrl: '' }) + expect((await mountWidget()).find('[data-testid="work-packages-not-installed"]').exists()).toBe(true) + loadWorkPackages.mockResolvedValue({ state: 'error', workPackages: [], connectUrl: '' }) + expect((await mountWidget()).getComponent(CnStatusList).props('error')).toBe('The work packages could not be loaded. Try again later.') + }) +}) + +describe('WorkPackagesWidgetForm', () => { + it('needs a project for a project list and 1 to 25 work packages', () => { + const wrapper = mount(WorkPackagesWidgetForm, { global: { stubs: { NcCheckboxRadioSwitch: true, NcTextField: true } } }) + expect(wrapper.vm.validate()).toEqual([]) + wrapper.vm.update({ scope: 'project' }) + expect(wrapper.vm.validate()).toEqual(['Name the project']) + wrapper.vm.update({ project: ' havenpark ', limit: 30 }) + expect(wrapper.vm.validate()).toEqual(['Show 1 to 25 work packages']) + expect(wrapper.emitted('update:content').at(-1)[0]).toEqual({ scope: 'project', project: 'havenpark', limit: 30 }) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/chartAndStatsHosts.spec.js b/src/components/Widgets/Renderers/__tests__/chartAndStatsHosts.spec.js new file mode 100644 index 000000000..617a5200e --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/chartAndStatsHosts.spec.js @@ -0,0 +1,344 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the thin `ChartHost.vue` and `StatsBlockHost.vue` + * adapters: which props they hand the library widget, where each comes from + * (top-level content or `content.props`) and their defaults. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import { computed, nextTick, ref } from 'vue' +import ChartHost from '../ChartHost.vue' +import StatsBlockHost from '../StatsBlockHost.vue' +import { useFilterBus } from '../../../../composables/useFilterBus.js' +import { logger } from '../../../../utils/logger.js' + +const dialogs = vi.hoisted(() => ({ showInfo: vi.fn(), showWarning: vi.fn() })) +vi.mock('@nextcloud/dialogs', () => dialogs) + +const clickedRowMock = vi.hoisted(() => vi.fn()) +vi.mock('../../../../utils/clickedRow.js', async (importOriginal) => ({ ...(await importOriginal()), clickedRow: clickedRowMock })) + +const ChartStub = { + name: 'CnChartWidget', + inheritAttrs: false, + props: ['type', 'dataSource', 'widgetId', 'selectable'], + emits: ['select', 'data'], + template: '<div class="chart-stub" />', +} + +const StatsStub = { + name: 'CnStatsBlockWidget', + props: ['title', 'dataSource', 'countLabel', 'variant', 'showZeroCount', 'horizontal', 'route', 'iconClass'], + emits: ['data'], + template: '<div class="stats-stub" />', +} + +function mountChart(content, placement = {}) { + return mount(ChartHost, { + props: { content, placement }, + global: { stubs: { CnChartWidget: ChartStub } }, + }).findComponent(ChartStub) +} + +function mountStats(content) { + return mount(StatsBlockHost, { + props: { content, placement: {} }, + global: { stubs: { CnStatsBlockWidget: StatsStub } }, + }).findComponent(StatsStub) +} + +// @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 +describe('ChartHost and the dashboard period (REQ-DPD-002)', () => { + function mountWithPeriod(content, period) { + return mount(ChartHost, { + props: { content, placement: { id: 1 } }, + global: { stubs: { CnChartWidget: ChartStub }, provide: { dashboardPeriod: ref(period) } }, + }) + } + + it('adds the period on its period field to the chart query, and follows a new choice', async () => { + const wrapper = mountWithPeriod({ dataSource: { register: 'zaken', schema: 'zaak', periodField: 'startDate' } }, 'quarter') + const filter = wrapper.findComponent(ChartStub).props('dataSource').filter + expect(Object.keys(filter)).toEqual(['startDate[gte]', 'startDate[lte]']) + expect(filter['startDate[gte]']).toMatch(/^\d{4}-(01|04|07|10)-01$/) + }) + + it('ignores the period without a period field', () => { + const source = { register: 'zaken', schema: 'zaak' } + const wrapper = mountWithPeriod({ dataSource: source }, 'year') + expect(wrapper.findComponent(ChartStub).props('dataSource')).toEqual(source) + }) +}) + +describe('ChartHost', () => { + it('defaults to an area chart without data source, named after the placement id', () => { + const chart = mountChart({}, { id: 12 }) + expect(chart.props()).toEqual({ type: 'area', dataSource: null, widgetId: '12', selectable: false }) + expect(chart.vm.$attrs).toEqual({}) + }) + + it('reads kind and source from content first, then from content.props', () => { + const source = { url: '/a' } + expect(mountChart({ chartKind: 'bar', dataSource: source, props: { chartKind: 'pie' } }).props()) + .toMatchObject({ type: 'bar', dataSource: source }) + expect(mountChart({ props: { chartKind: 'pie', dataSource: source } }).props()) + .toMatchObject({ type: 'pie', dataSource: source }) + }) + + it('falls back from the placement id to its widget id, then to "chart"', () => { + expect(mountChart({}, { widgetId: 'w-3' }).props('widgetId')).toBe('w-3') + expect(mountChart({}, {}).props('widgetId')).toBe('chart') + }) + + it('passes only the known chart keys through, top-level content winning', () => { + const chart = mountChart({ + height: 300, + stacked: true, + unknown: 'dropped', + props: { height: 100, colors: ['#111'], other: 'dropped' }, + }) + expect(chart.vm.$attrs).toEqual({ height: 300, stacked: true, colors: ['#111'] }) + }) +}) + +describe('StatsBlockHost', () => { + it('hands title, source and the display props to the stats widget', () => { + const source = { url: '/count' } + const stats = mountStats({ + title: 'Open cases', + dataSource: source, + props: { countLabel: 'cases', variant: 'primary', showZeroCount: true, horizontal: false, route: '/cases', iconClass: 'icon-x' }, + }) + expect(stats.props()).toEqual({ + title: 'Open cases', + dataSource: source, + countLabel: 'cases', + variant: 'primary', + showZeroCount: true, + horizontal: false, + route: '/cases', + iconClass: 'icon-x', + }) + }) + + it('defaults to an empty title, no source and no display props', () => { + expect(mountStats({}).props()).toEqual({ + title: '', + dataSource: null, + countLabel: undefined, + variant: undefined, + showZeroCount: undefined, + horizontal: undefined, + route: undefined, + iconClass: undefined, + }) + }) +}) + +describe('ChartHost on the filter bus (REQ-CWF-002, REQ-CWF-008)', () => { + const HIERARCHY = { id: 'nl', levels: [{ dimension: 'gemeenteCode' }, { dimension: 'wijkCode', parentDimension: 'gemeenteCode' }] } + + /** + * Mount a chart under a bus. + * + * @param {object} content The placement content. + * @param {object} bus The bus. + * @return {import('@vue/test-utils').VueWrapper} + */ + function mountOnBus(content, bus) { + return mount(ChartHost, { + props: { content, placement: { id: 3 } }, + global: { stubs: { CnChartWidget: ChartStub }, provide: { dashboardFilterBus: computed(() => bus) } }, + }) + } + + it('a consuming chart filters its data source on the bus, and follows it', async () => { + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + const content = { dataSource: { schema: 'zaak', filter: { type: 'bezwaar' } }, consumes: [{ dimension: 'gemeenteCode', field: 'gemeente' }] } + const wrapper = mountOnBus(content, bus) + expect(wrapper.findComponent(ChartStub).props('dataSource')).toEqual(content.dataSource) + + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick' }) + await nextTick() + + expect(wrapper.findComponent(ChartStub).props('dataSource')).toEqual({ schema: 'zaak', filter: { type: 'bezwaar', gemeente: 'GM0355' } }) + }) + + it('a chart consuming a dimension outside the dashboard hierarchies stays unfiltered, with a warning', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + bus.publish({ dimension: 'status', operator: 'eq', value: 'open' }) + const content = { dataSource: { schema: 'zaak' }, consumes: ['status'] } + + const wrapper = mountOnBus(content, bus) + + expect(wrapper.findComponent(ChartStub).props('dataSource')).toEqual({ schema: 'zaak' }) + expect(warn).toHaveBeenCalledWith('[launchpad] widget 3 is not on the filter bus: consumes-unknown-dimension (status)') + warn.mockRestore() + }) + + it('a chart without declarations ignores the bus', () => { + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355' }) + const content = { dataSource: { schema: 'zaak' } } + + expect(mountOnBus(content, bus).findComponent(ChartStub).props('dataSource')).toEqual({ schema: 'zaak' }) + }) +}) + +describe('StatsBlockHost on the filter bus (REQ-CWF-002, REQ-CWF-008)', () => { + const HIERARCHY = { id: 'nl', levels: [{ dimension: 'gemeenteCode' }, { dimension: 'wijkCode', parentDimension: 'gemeenteCode' }] } + + /** + * Mount a stats block under a bus. + * + * @param {object} content The placement content. + * @param {object} bus The bus. + * @return {import('@vue/test-utils').VueWrapper} + */ + function mountOnBus(content, bus) { + return mount(StatsBlockHost, { + props: { content, placement: { id: 8 } }, + global: { stubs: { CnStatsBlockWidget: StatsStub }, provide: { dashboardFilterBus: computed(() => bus) } }, + }) + } + + it('a consuming stats block counts on the bus filter, follows it, and ignores other dimensions', async () => { + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + const content = { dataSource: { register: 'r', schema: 'zaak', filter: { type: 'bezwaar' } }, consumes: [{ dimension: 'gemeenteCode', field: 'gemeente' }] } + const wrapper = mountOnBus(content, bus) + expect(wrapper.findComponent(StatsStub).props('dataSource')).toEqual(content.dataSource) + + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick' }) + await nextTick() + expect(wrapper.findComponent(StatsStub).props('dataSource')).toEqual({ register: 'r', schema: 'zaak', filter: { type: 'bezwaar', gemeente: 'GM0355' } }) + + bus.publish({ dimension: 'wijkCode', operator: 'eq', value: 'WK035501', source: 'widgetClick' }, { row: { gemeenteCode: 'GM0355' } }) + await nextTick() + expect(wrapper.findComponent(StatsStub).props('dataSource').filter).toEqual({ type: 'bezwaar', gemeente: 'GM0355' }) + }) + + it('a stats block consuming a dimension outside the hierarchies stays unfiltered, with a warning', () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + bus.publish({ dimension: 'status', operator: 'eq', value: 'open' }) + + const wrapper = mountOnBus({ dataSource: { schema: 'zaak' }, consumes: ['status'] }, bus) + + expect(wrapper.findComponent(StatsStub).props('dataSource')).toEqual({ schema: 'zaak' }) + expect(warn).toHaveBeenCalledWith('[launchpad] widget 8 is not on the filter bus: consumes-unknown-dimension (status)') + warn.mockRestore() + }) + + it('a stats block without consumes ignores the bus', () => { + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355' }) + const source = { schema: 'zaak' } + + expect(mountOnBus({ dataSource: source }, bus).findComponent(StatsStub).props('dataSource')).toEqual(source) + }) +}) + +describe('ChartHost publishing a pick (REQ-CWF-001, REQ-CWF-005)', () => { + const HIERARCHY = { id: 'nl', levels: [{ dimension: 'gemeenteCode', label: 'Gemeente' }, { dimension: 'wijkCode', parentDimension: 'gemeenteCode' }] } + const CONTENT = { dataSource: { schema: 'zaak', groupBy: 'gemeente' }, publishes: [{ dimension: 'gemeenteCode', fromField: 'gemeente' }] } + + /** + * Mount a chart under a bus. + * + * @param {object} content The placement content. + * @param {object|null} bus The bus. + * @param {number} id The placement id. + * @return {import('@vue/test-utils').VueWrapper} + */ + function mountOnBus(content, bus, id = 4) { + return mount(ChartHost, { + props: { content, placement: { id } }, + global: { stubs: { CnChartWidget: ChartStub }, provide: { dashboardFilterBus: computed(() => bus) } }, + }) + } + + it('a publishing chart is selectable, and a pick publishes a widget click', () => { + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + const chart = mountOnBus(CONTENT, bus).findComponent(ChartStub) + expect(chart.props('selectable')).toBe(true) + + chart.vm.$emit('select', { field: 'gemeente', value: 'GM0355', label: 'Zeist', index: 0 }) + + expect(bus.clauses.value).toEqual([ + { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: '4', pinned: false }, + ]) + }) + + it('a pick on another field publishes nothing', () => { + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + mountOnBus(CONTENT, bus).findComponent(ChartStub).vm.$emit('select', { field: 'status', value: 'open' }) + expect(bus.clauses.value).toEqual([]) + }) + + it('a chart without publishes, or without a bus, is not selectable', () => { + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + expect(mountOnBus({ dataSource: { schema: 'zaak' } }, bus).findComponent(ChartStub).props('selectable')).toBe(false) + expect(mountOnBus(CONTENT, null).findComponent(ChartStub).props('selectable')).toBe(false) + }) + + it('a pick that replaces another widget\'s filter says so, with the level label', () => { + dialogs.showInfo.mockClear() + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + mountOnBus(CONTENT, bus, 5).findComponent(ChartStub).vm.$emit('select', { field: 'gemeente', value: 'GM0355' }) + mountOnBus(CONTENT, bus, 6).findComponent(ChartStub).vm.$emit('select', { field: 'gemeente', value: 'GM0321' }) + + expect(dialogs.showInfo).toHaveBeenCalledTimes(1) + expect(dialogs.showInfo).toHaveBeenCalledWith('Gemeente filter changed: GM0355 → GM0321') + expect(bus.clauses.value.map((clause) => clause.value)).toEqual(['GM0321']) + }) + + it('a pick the reader may not filter on is refused with a warning, and the bus is left as it was', () => { + dialogs.showWarning.mockClear() + const bus = useFilterBus({ hierarchies: [HIERARCHY], canAccess: () => false }) + mountOnBus(CONTENT, bus).findComponent(ChartStub).vm.$emit('select', { field: 'gemeente', value: 'GM0355' }) + + expect(bus.clauses.value).toEqual([]) + expect(dialogs.showWarning).toHaveBeenCalledWith('You have no access to this scope: Gemeente') + }) +}) + +describe('ChartHost drilling down a hierarchy (REQ-CWF-004)', () => { + const NL = { id: 'nl', levels: [{ dimension: 'provincieCode', label: 'Provincie' }, { dimension: 'gemeenteCode', label: 'Gemeente' }, { dimension: 'wijkCode', label: 'Wijk' }] } + const WIJKEN = { dataSource: { register: 'cwf', schema: 'melding', groupBy: 'wijkCode' }, publishes: [{ dimension: 'wijkCode', fromField: 'wijkCode' }] } + + it('a pick on a wijk reads its gemeente and provincie from a record, and the bus infers them', async () => { + clickedRowMock.mockResolvedValue({ wijkCode: 'WK035501', gemeenteCode: 'GM0355', provincieCode: 'PV26' }) + const bus = useFilterBus({ hierarchies: [NL] }) + const host = mount(ChartHost, { + props: { content: WIJKEN, placement: { id: 9 } }, + global: { stubs: { CnChartWidget: ChartStub }, provide: { dashboardFilterBus: computed(() => bus) } }, + }) + + host.findComponent(ChartStub).vm.$emit('select', { field: 'wijkCode', value: 'WK035501' }) + await flushPromises() + + expect(clickedRowMock).toHaveBeenCalledWith(expect.objectContaining({ + selection: { field: 'wijkCode', value: 'WK035501' }, + hierarchies: [NL], + dataSource: WIJKEN.dataSource, + })) + expect(bus.breadcrumb('nl').map((step) => step.value)).toEqual(['PV26', 'GM0355', 'WK035501']) + }) +}) + +describe('hosts forward what the library widget shows (widget-calculated-fields task 19)', () => { + it('ChartHost and StatsBlockHost re-emit the library widget\'s data', () => { + const chart = mount(ChartHost, { props: { content: {}, placement: { id: 1 } }, global: { stubs: { CnChartWidget: ChartStub } } }) + chart.findComponent(ChartStub).vm.$emit('data', { total: 5 }) + expect(chart.emitted('data')).toEqual([[{ total: 5 }]]) + + const stats = mount(StatsBlockHost, { props: { content: {}, placement: {} }, global: { stubs: { CnStatsBlockWidget: StatsStub } } }) + stats.findComponent(StatsStub).vm.$emit('data', { count: 3 }) + expect(stats.emitted('data')).toEqual([[{ count: 3 }]]) + }) +}) + diff --git a/src/components/Widgets/Renderers/__tests__/chartHostResponsiveness.spec.js b/src/components/Widgets/Renderers/__tests__/chartHostResponsiveness.spec.js new file mode 100644 index 000000000..719cc02b1 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/chartHostResponsiveness.spec.js @@ -0,0 +1,145 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * 300 ms responsiveness (drill-down-cross-widget-filter task 30; + * REQ-CWF-002): after a publish every consuming chart gets its filtered data + * source on the next tick, so the only wait is its own fetch. Two charts + * whose fetch takes 100 ms and 250 ms both show the filtered data within + * 300 ms of the publish; a chart that consumes nothing never refetches. + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { computed, defineComponent, h, nextTick } from 'vue' +import ChartHost from '../ChartHost.vue' +import StatsBlockHost from '../StatsBlockHost.vue' +import { useFilterBus } from '../../../../composables/useFilterBus.js' +import { logger } from '../../../../utils/logger.js' + +const HIERARCHY = { id: 'nl', levels: [{ dimension: 'gemeenteCode' }] } + +/** + * A chart stub that "fetches" for `delay` ms whenever its data source changes + * and then renders the filter it fetched with. + * + * @param {Array<object>} log Where each finished fetch is logged. + * @return {object} + */ +function fetchingChart(log) { + return defineComponent({ + name: 'CnChartWidget', + props: ['dataSource', 'widgetId', 'type'], + emits: ['data'], + data: () => ({ shown: null }), + watch: { + dataSource: { + immediate: true, + handler(source) { + const delay = source?.delay ?? 0 + setTimeout(() => { + this.shown = source?.filter?.gemeente ?? null + log.push({ widget: this.widgetId, gemeente: this.shown, at: Date.now() }) + this.$emit('data', { total: 1 }) + }, delay) + }, + }, + }, + render() { + return h('div', { class: 'chart', 'data-widget': this.widgetId }, String(this.shown)) + }, + }) +} + +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(0) +}) +afterEach(() => vi.useRealTimers()) + +describe('consuming charts re-render within 300 ms of a publish', () => { + it('fetches of 100 ms and 250 ms both land inside the bound; a non-consumer does not refetch', async () => { + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + const log = [] + const stub = fetchingChart(log) + const consumes = [{ dimension: 'gemeenteCode', field: 'gemeente' }] + const charts = [ + { id: 'fast', content: { dataSource: { schema: 'zaak', delay: 100 }, consumes } }, + { id: 'slow', content: { dataSource: { schema: 'zaak', delay: 250 }, consumes } }, + { id: 'other', content: { dataSource: { schema: 'zaak', delay: 10 } } }, + ].map(({ id, content }) => mount(ChartHost, { + props: { content, placement: { id } }, + global: { stubs: { CnChartWidget: stub }, provide: { dashboardFilterBus: computed(() => bus) } }, + })) + await vi.advanceTimersByTimeAsync(300) + log.length = 0 + const publishedAt = Date.now() + + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick' }) + await nextTick() + await vi.advanceTimersByTimeAsync(300) + + expect(log.map(({ widget, gemeente }) => [widget, gemeente])).toEqual([['fast', 'GM0355'], ['slow', 'GM0355']]) + for (const entry of log) { + expect(entry.at - publishedAt).toBeLessThanOrEqual(300) + } + expect(charts.map((chart) => chart.find('.chart').text())).toEqual(['GM0355', 'GM0355', 'null']) + }) +}) + +describe('a slow refetch after a filter change is logged (Task 35)', () => { + it('warns for a consumer whose data lands over 200 ms after the change, not for a fast one or a non-consumer', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + const stub = fetchingChart([]) + const consumes = [{ dimension: 'gemeenteCode', field: 'gemeente' }] + const mountChart = (id, content) => mount(ChartHost, { + props: { content, placement: { id } }, + global: { stubs: { CnChartWidget: stub }, provide: { dashboardFilterBus: computed(() => bus) } }, + }) + mountChart('fast', { dataSource: { schema: 'zaak', delay: 150 }, consumes }) + mountChart('slow', { dataSource: { schema: 'zaak', delay: 260 }, consumes }) + mountChart('other', { dataSource: { schema: 'zaak', delay: 400 } }) + await vi.advanceTimersByTimeAsync(500) + expect(warn).not.toHaveBeenCalled() + + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick' }) + await nextTick() + await vi.advanceTimersByTimeAsync(500) + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn).toHaveBeenCalledWith('[launchpad] widget slow took 260 ms to show its data after a filter change (over 200 ms): {"gemeente":"GM0355"}') + warn.mockRestore() + }) + + it('a consuming stats block is timed the same way', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) + const bus = useFilterBus({ hierarchies: [HIERARCHY] }) + const slowStats = defineComponent({ + name: 'CnStatsBlockWidget', + props: ['dataSource'], + emits: ['data'], + watch: { + dataSource: { + immediate: true, + handler() { + setTimeout(() => this.$emit('data', { count: 1 }), 300) + }, + }, + }, + render: () => h('div'), + }) + mount(StatsBlockHost, { + props: { content: { dataSource: { schema: 'zaak' }, consumes: [{ dimension: 'gemeenteCode', field: 'gemeente' }] }, placement: { id: 9 } }, + global: { stubs: { CnStatsBlockWidget: slowStats }, provide: { dashboardFilterBus: computed(() => bus) } }, + }) + await vi.advanceTimersByTimeAsync(400) + + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick' }) + await nextTick() + await vi.advanceTimersByTimeAsync(400) + + expect(warn).toHaveBeenCalledWith('[launchpad] widget 9 took 300 ms to show its data after a filter change (over 200 ms): {"gemeente":"GM0355"}') + warn.mockRestore() + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/fixtures/placementReading.golden.json b/src/components/Widgets/Renderers/__tests__/fixtures/placementReading.golden.json new file mode 100644 index 000000000..cbb974437 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/fixtures/placementReading.golden.json @@ -0,0 +1,1018 @@ +{ + "weather | load | null | reading": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | null | error answer": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | null | empty error": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | null | null": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | null | undefined": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | null | rejects": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | no id | reading": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | no id | error answer": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | no id | empty error": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | no id | null": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | no id | undefined": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | no id | rejects": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | id null | reading": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | id null | error answer": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | id null | empty error": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | id null | null": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | id null | undefined": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | id null | rejects": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:Weather is not available until this tile is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "weather | load | id zero | reading": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": { + "value": 21, + "stale": false + } + }, + "calls": 1 + }, + "weather | load | id zero | error answer": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "t:Weather is currently unavailable.", + "reading": null + }, + "calls": 1 + }, + "weather | load | id zero | empty error": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": { + "error": "" + } + }, + "calls": 1 + }, + "weather | load | id zero | null": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": null + }, + "calls": 1 + }, + "weather | load | id zero | undefined": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": "(undefined)" + }, + "calls": 1 + }, + "weather | load | id zero | rejects": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "t:Failed to load weather.", + "reading": null + }, + "calls": 1 + }, + "weather | load | id 7 | reading": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": { + "value": 21, + "stale": false + } + }, + "calls": 1 + }, + "weather | load | id 7 | error answer": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "t:Weather is currently unavailable.", + "reading": null + }, + "calls": 1 + }, + "weather | load | id 7 | empty error": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": { + "error": "" + } + }, + "calls": 1 + }, + "weather | load | id 7 | null": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": null + }, + "calls": 1 + }, + "weather | load | id 7 | undefined": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": "(undefined)" + }, + "calls": 1 + }, + "weather | load | id 7 | rejects": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "t:Failed to load weather.", + "reading": null + }, + "calls": 1 + }, + "weather | styles": { + ".weather-widget": { + "scoped": true, + "props": { + "width": "100%", + "height": "100%", + "display": "flex", + "align-items": "center", + "justify-content": "center" + } + }, + ".weather-widget__badge": { + "scoped": true, + "props": { + "position": "absolute", + "top": "-8px", + "right": "-8px", + "font-size": "0.7rem", + "padding": "2px 6px", + "border-radius": "var(--border-radius-pill, 8px)", + "background": "var(--color-warning, #ffcc00)", + "color": "var(--color-main-text)" + } + }, + ".weather-widget__body": { + "scoped": true, + "props": { + "display": "flex", + "align-items": "center", + "gap": "12px" + } + }, + ".weather-widget__condition-text": { + "scoped": true, + "props": { + "color": "var(--color-text-maxcontrast, var(--color-main-text))" + } + }, + ".weather-widget__details": { + "scoped": true, + "props": { + "display": "flex", + "flex-direction": "column" + } + }, + ".weather-widget__location": { + "scoped": true, + "props": { + "font-weight": "600", + "color": "var(--color-main-text)" + } + }, + ".weather-widget__reading": { + "scoped": true, + "props": { + "position": "relative", + "width": "100%", + "display": "flex", + "flex-direction": "column", + "align-items": "center", + "gap": "4px" + } + }, + ".weather-widget__retry": { + "scoped": true, + "props": { + "border": "1px solid var(--color-border)", + "border-radius": "var(--border-radius)", + "background": "transparent", + "padding": "4px 12px", + "cursor": "pointer", + "color": "var(--color-main-text)" + } + }, + ".weather-widget__state": { + "scoped": true, + "props": { + "display": "flex", + "flex-direction": "column", + "align-items": "center", + "gap": "8px", + "color": "var(--color-text-maxcontrast, var(--color-main-text))", + "text-align": "center" + } + }, + ".weather-widget__temp": { + "scoped": true, + "props": { + "font-size": "1.8rem", + "font-weight": "600", + "color": "var(--color-main-text)" + } + } + }, + "live tile | load | null | reading": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | null | error answer": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | null | empty error": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | null | null": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | null | undefined": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | null | rejects": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | no id | reading": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | no id | error answer": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | no id | empty error": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | no id | null": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | no id | undefined": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | no id | rejects": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | id null | reading": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | id null | error answer": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | id null | empty error": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | id null | null": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | id null | undefined": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | id null | rejects": { + "during": null, + "after": { + "loading": false, + "errorMessage": "t:This tile is not available until it is saved.", + "reading": { + "old": true + } + }, + "calls": 0 + }, + "live tile | load | id zero | reading": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": { + "value": 21, + "stale": false + } + }, + "calls": 1 + }, + "live tile | load | id zero | error answer": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "t:The value is currently unavailable.", + "reading": null + }, + "calls": 1 + }, + "live tile | load | id zero | empty error": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": { + "error": "" + } + }, + "calls": 1 + }, + "live tile | load | id zero | null": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": null + }, + "calls": 1 + }, + "live tile | load | id zero | undefined": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": "(undefined)" + }, + "calls": 1 + }, + "live tile | load | id zero | rejects": { + "during": { + "id": 0, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "t:Failed to load the value.", + "reading": null + }, + "calls": 1 + }, + "live tile | load | id 7 | reading": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": { + "value": 21, + "stale": false + } + }, + "calls": 1 + }, + "live tile | load | id 7 | error answer": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "t:The value is currently unavailable.", + "reading": null + }, + "calls": 1 + }, + "live tile | load | id 7 | empty error": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": { + "error": "" + } + }, + "calls": 1 + }, + "live tile | load | id 7 | null": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": null + }, + "calls": 1 + }, + "live tile | load | id 7 | undefined": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "", + "reading": "(undefined)" + }, + "calls": 1 + }, + "live tile | load | id 7 | rejects": { + "during": { + "id": 7, + "loading": true, + "errorMessage": "" + }, + "after": { + "loading": false, + "errorMessage": "t:Failed to load the value.", + "reading": null + }, + "calls": 1 + }, + "live tile | styles": { + ".live-tile-widget": { + "scoped": true, + "props": { + "width": "100%", + "height": "100%", + "display": "flex", + "align-items": "center", + "justify-content": "center", + "text-decoration": "none", + "color": "inherit" + } + }, + ".live-tile-widget--bordered": { + "scoped": true, + "props": { + "display": "block", + "padding": "8px", + "border": "1px solid var(--color-border-dark)", + "border-radius": "var(--border-radius-large)" + } + }, + ".live-tile-widget__badge": { + "scoped": true, + "props": { + "display": "inline-flex", + "align-items": "center", + "gap": "4px", + "font-size": "0.8rem", + "padding": "2px 8px", + "border-radius": "var(--border-radius-pill, 8px)", + "border": "1px solid var(--color-border)" + } + }, + ".live-tile-widget__badge--alert": { + "scoped": true, + "props": { + "border-color": "var(--color-error, #e9322d)" + } + }, + ".live-tile-widget__badge--ok": { + "scoped": true, + "props": { + "border-color": "var(--color-success, #46ba61)" + } + }, + ".live-tile-widget__badge--warn": { + "scoped": true, + "props": { + "border-color": "var(--color-warning, #ffcc00)" + } + }, + ".live-tile-widget__label": { + "scoped": true, + "props": { + "font-weight": "600", + "color": "var(--color-text-maxcontrast, var(--color-main-text))" + } + }, + ".live-tile-widget__list": { + "scoped": true, + "props": { + "margin": "0", + "padding": "0", + "list-style": "none", + "display": "flex", + "flex-direction": "column", + "gap": "6px", + "text-align": "start" + } + }, + ".live-tile-widget__list-detail": { + "scoped": true, + "props": { + "font-size": "0.85rem", + "color": "var(--color-text-maxcontrast)" + } + }, + ".live-tile-widget__list-item": { + "scoped": true, + "props": { + "display": "flex", + "flex-direction": "column" + } + }, + ".live-tile-widget__list-title": { + "scoped": true, + "props": { + "font-weight": "600", + "color": "var(--color-main-text)" + } + }, + ".live-tile-widget__pairs dd": { + "scoped": true, + "props": { + "margin": "0" + } + }, + ".live-tile-widget__pairs dt": { + "scoped": true, + "props": { + "font-weight": "600" + } + }, + ".live-tile-widget__pairs": { + "scoped": true, + "props": { + "display": "grid", + "grid-template-columns": "auto 1fr", + "gap": "4px 12px", + "margin": "0", + "text-align": "start" + } + }, + ".live-tile-widget__reading": { + "scoped": true, + "props": { + "position": "relative", + "width": "100%", + "display": "flex", + "flex-direction": "column", + "align-items": "center", + "gap": "4px" + } + }, + ".live-tile-widget__retry": { + "scoped": true, + "props": { + "border": "1px solid var(--color-border)", + "border-radius": "var(--border-radius)", + "background": "transparent", + "padding": "4px 12px", + "cursor": "pointer", + "color": "var(--color-main-text)" + } + }, + ".live-tile-widget__stale-badge": { + "scoped": true, + "props": { + "position": "absolute", + "top": "-8px", + "right": "-8px", + "font-size": "0.7rem", + "padding": "2px 6px", + "border-radius": "var(--border-radius-pill, 8px)", + "background": "var(--color-warning, #ffcc00)", + "color": "var(--color-main-text)" + } + }, + ".live-tile-widget__state": { + "scoped": true, + "props": { + "display": "flex", + "flex-direction": "column", + "align-items": "center", + "gap": "8px", + "color": "var(--color-text-maxcontrast, var(--color-main-text))", + "text-align": "center" + } + }, + ".live-tile-widget__table td": { + "scoped": true, + "props": { + "padding": "4px 6px", + "border-bottom": "1px solid var(--color-border)", + "text-align": "start" + } + }, + ".live-tile-widget__table th": { + "scoped": true, + "props": { + "padding": "4px 6px", + "border-bottom": "1px solid var(--color-border)", + "text-align": "start" + } + }, + ".live-tile-widget__table": { + "scoped": true, + "props": { + "width": "100%", + "border-collapse": "collapse", + "font-size": "0.9rem", + "text-align": "start" + } + }, + ".live-tile-widget__value": { + "scoped": true, + "props": { + "font-size": "1.8rem", + "font-weight": "600", + "color": "var(--live-tile-accent, var(--color-main-text))" + } + } + } +} diff --git a/src/components/Widgets/Renderers/__tests__/fixtures/urlAllowList.golden.json b/src/components/Widgets/Renderers/__tests__/fixtures/urlAllowList.golden.json new file mode 100644 index 000000000..115763387 --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/fixtures/urlAllowList.golden.json @@ -0,0 +1,1392 @@ +{ + "iframe | check | empty | allowed": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | empty | host not allowed": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | empty | invalid url": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | empty | both errors": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | empty | other error": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | empty | valid missing": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | validate | empty | no allow-list error": [ + "t:URL is required" + ], + "iframe | validate | empty | Not allowed": [ + "t:URL is required", + "Not allowed" + ], + "iframe | check | blank | allowed": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | blank | host not allowed": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | blank | invalid url": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | blank | both errors": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | blank | other error": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | check | blank | valid missing": { + "error": "", + "checked": false, + "calls": 0, + "emitted": 0 + }, + "iframe | validate | blank | no allow-list error": [ + "t:URL is required" + ], + "iframe | validate | blank | Not allowed": [ + "t:URL is required", + "Not allowed" + ], + "iframe | check | https | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | https | host not allowed": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | https | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | https | both errors": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | https | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | https | valid missing": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | https | no allow-list error": [], + "iframe | validate | https | Not allowed": [ + "Not allowed" + ], + "iframe | check | http upper case | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | http upper case | host not allowed": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | http upper case | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | http upper case | both errors": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | http upper case | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | http upper case | valid missing": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | http upper case | no allow-list error": [], + "iframe | validate | http upper case | Not allowed": [ + "Not allowed" + ], + "iframe | check | padded | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | padded | host not allowed": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | padded | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | padded | both errors": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | padded | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | padded | valid missing": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | padded | no allow-list error": [], + "iframe | validate | padded | Not allowed": [ + "Not allowed" + ], + "iframe | check | scheme only | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | scheme only | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | scheme only | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | scheme only | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | scheme only | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | scheme only | valid missing": { + "error": "", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | scheme only | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "iframe | validate | scheme only | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "iframe | check | no scheme | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | no scheme | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | no scheme | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | no scheme | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | no scheme | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | no scheme | valid missing": { + "error": "", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | no scheme | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "iframe | validate | no scheme | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "iframe | check | javascript | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | javascript | host not allowed": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | javascript | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | javascript | both errors": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | javascript | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | javascript | valid missing": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | javascript | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "iframe | validate | javascript | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "iframe | check | data | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | data | host not allowed": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | data | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | data | both errors": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | data | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | data | valid missing": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | data | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "iframe | validate | data | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "iframe | check | ftp | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | ftp | host not allowed": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | ftp | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | ftp | both errors": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | ftp | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | ftp | valid missing": { + "error": "t:The host {host} is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | ftp | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "iframe | validate | ftp | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "iframe | check | protocol relative | allowed": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | protocol relative | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | protocol relative | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | protocol relative | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | check | protocol relative | other error": { + "error": "", + "checked": true, + "calls": 1, + "emitted": 1 + }, + "iframe | check | protocol relative | valid missing": { + "error": "", + "checked": false, + "calls": 1, + "emitted": 1 + }, + "iframe | validate | protocol relative | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "iframe | validate | protocol relative | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "live tile url | check | empty | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | empty | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | empty | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | empty | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | empty | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | empty | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | validate | empty | no allow-list error": [ + "t:URL is required" + ], + "live tile url | validate | empty | Not allowed": [ + "t:URL is required", + "Not allowed" + ], + "live tile url | check | blank | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | blank | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | blank | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | blank | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | blank | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | check | blank | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile url | validate | blank | no allow-list error": [ + "t:URL is required" + ], + "live tile url | validate | blank | Not allowed": [ + "t:URL is required", + "Not allowed" + ], + "live tile url | check | https | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | https | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | https | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | https | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | https | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | https | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | https | no allow-list error": [], + "live tile url | validate | https | Not allowed": [ + "Not allowed" + ], + "live tile url | check | http upper case | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | http upper case | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | http upper case | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | http upper case | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | http upper case | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | http upper case | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | http upper case | no allow-list error": [], + "live tile url | validate | http upper case | Not allowed": [ + "Not allowed" + ], + "live tile url | check | padded | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | padded | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | padded | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | padded | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | padded | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | padded | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | padded | no allow-list error": [], + "live tile url | validate | padded | Not allowed": [ + "Not allowed" + ], + "live tile url | check | scheme only | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | scheme only | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | scheme only | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | scheme only | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | scheme only | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | scheme only | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | scheme only | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "live tile url | validate | scheme only | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "live tile url | check | no scheme | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | no scheme | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | no scheme | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | no scheme | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | no scheme | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | no scheme | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | no scheme | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "live tile url | validate | no scheme | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "live tile url | check | javascript | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | javascript | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | javascript | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | javascript | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | javascript | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | javascript | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | javascript | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "live tile url | validate | javascript | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "live tile url | check | data | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | data | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | data | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | data | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | data | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | data | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | data | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "live tile url | validate | data | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "live tile url | check | ftp | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | ftp | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | ftp | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | ftp | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | ftp | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | ftp | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | ftp | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "live tile url | validate | ftp | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "live tile url | check | protocol relative | allowed": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | protocol relative | host not allowed": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | protocol relative | invalid url": { + "error": "t:Enter a valid http(s) URL.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | protocol relative | both errors": { + "error": "t:This host is not on the allow-list.", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | protocol relative | other error": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | check | protocol relative | valid missing": { + "error": "", + "checked": "(none)", + "calls": 1, + "emitted": 0 + }, + "live tile url | validate | protocol relative | no allow-list error": [ + "t:Enter a valid http(s) URL." + ], + "live tile url | validate | protocol relative | Not allowed": [ + "t:Enter a valid http(s) URL.", + "Not allowed" + ], + "live tile connector | check | empty | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | empty | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | empty | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | empty | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | empty | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | empty | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | empty | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | empty | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | blank | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | blank | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | blank | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | blank | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | blank | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | blank | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | blank | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | blank | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | https | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | https | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | https | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | https | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | https | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | https | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | https | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | https | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | http upper case | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | http upper case | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | http upper case | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | http upper case | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | http upper case | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | http upper case | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | http upper case | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | http upper case | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | padded | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | padded | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | padded | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | padded | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | padded | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | padded | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | padded | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | padded | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | scheme only | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | scheme only | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | scheme only | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | scheme only | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | scheme only | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | scheme only | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | scheme only | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | scheme only | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | no scheme | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | no scheme | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | no scheme | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | no scheme | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | no scheme | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | no scheme | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | no scheme | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | no scheme | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | javascript | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | javascript | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | javascript | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | javascript | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | javascript | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | javascript | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | javascript | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | javascript | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | data | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | data | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | data | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | data | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | data | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | data | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | data | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | data | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | ftp | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | ftp | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | ftp | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | ftp | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | ftp | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | ftp | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | ftp | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | ftp | Not allowed": [ + "t:Value expression is required" + ], + "live tile connector | check | protocol relative | allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | protocol relative | host not allowed": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | protocol relative | invalid url": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | protocol relative | both errors": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | protocol relative | other error": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | check | protocol relative | valid missing": { + "error": "", + "checked": "(none)", + "calls": 0, + "emitted": 0 + }, + "live tile connector | validate | protocol relative | no allow-list error": [ + "t:Value expression is required" + ], + "live tile connector | validate | protocol relative | Not allowed": [ + "t:Value expression is required" + ] +} diff --git a/src/components/Widgets/Renderers/__tests__/placementReading.golden.spec.js b/src/components/Widgets/Renderers/__tests__/placementReading.golden.spec.js new file mode 100644 index 000000000..31b90077c --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/placementReading.golden.spec.js @@ -0,0 +1,172 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for WeatherWidget and LiveTileWidget: what `load()` leaves in + * the component (and shows while the request runs) for each placement and + * answer, and the final style each class gets from the component's style + * blocks, compared with fixtures/placementReading.golden.json case by case. + * Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import LiveTileWidget from '../LiveTileWidget.vue' +import WeatherWidget from '../WeatherWidget.vue' +import { fetchLiveTileValue } from '../../../../services/liveTileClient.js' +import { fetchWeatherReading } from '../../../../services/weatherClient.js' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => `t:${text}`, + t: (_app, text) => `t:${text}`, +})) +vi.mock('../../../../services/weatherClient.js', () => ({ + fetchWeatherReading: vi.fn(), +})) +vi.mock('../../../../services/liveTileClient.js', () => ({ + fetchLiveTileValue: vi.fn(), +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/placementReading.golden.json') +const RENDERERS = path.resolve(__dirname, '..') + +const WIDGETS = { + weather: { + component: WeatherWidget, + file: 'WeatherWidget.vue', + client: fetchWeatherReading, + }, + 'live tile': { + component: LiveTileWidget, + file: 'LiveTileWidget.vue', + client: fetchLiveTileValue, + }, +} + +const PLACEMENTS = { + null: null, + 'no id': {}, + 'id null': { id: null }, + 'id zero': { id: 0 }, + 'id 7': { id: 7 }, +} + +const ANSWERS = { + reading: { value: { value: 21, stale: false } }, + 'error answer': { value: { error: 'upstream' } }, + 'empty error': { value: { error: '' } }, + null: { value: null }, + undefined: { value: undefined }, + rejects: { error: new Error('offline') }, +} + +/** + * Run `load()` on a stand-in for the component and record what it did. + * + * @param {object} widget The widget under test. + * @param {{placement: object|null, answer: object}} given The placement and the client answer. + * @return {Promise<object>} The outcome. + */ +async function runLoad(widget, given) { + const host = { + placement: given.placement, + loading: true, + errorMessage: 'stale message', + reading: { old: true }, + } + let during = null + widget.client.mockReset() + widget.client.mockImplementation(async (id) => { + during = { id, loading: host.loading, errorMessage: host.errorMessage } + if (given.answer.error) { + throw given.answer.error + } + return given.answer.value + }) + await widget.component.methods.load.call(host) + return JSON.parse( + JSON.stringify({ + during, + after: { + loading: host.loading, + errorMessage: host.errorMessage, + reading: host.reading === undefined ? '(undefined)' : host.reading, + }, + calls: widget.client.mock.calls.length, + }), + ) +} + +/** + * The final declarations per class selector from a component's style blocks, + * applying the blocks and rules in order (a `src` block read from its file). + * Only selectors of the component's own block are kept. + * + * @param {string} file The component file name. + * @param {string} block The component's class block, e.g. `weather-widget`. + * @return {object} Declarations by selector, each with its scoped flag. + */ +function finalStyles(file, block) { + const source = fs.readFileSync(path.join(RENDERERS, file), 'utf8') + const out = {} + const own = new RegExp(`^\\.${block}(?:$|__|--|[\\s:.[>])`) + for (const match of source.matchAll(/<style([^>]*)>([\s\S]*?)<\/style>/g)) { + const src = /src="([^"]+)"/.exec(match[1]) + const css = ( + src ? fs.readFileSync(path.join(RENDERERS, src[1]), 'utf8') : match[2] + ).replace(/\/\*[\s\S]*?\*\//g, '') + const scoped = /\bscoped\b/.test(match[1]) + for (const rule of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { + for (const selector of rule[1] + .split(',') + .map((s) => s.trim().replace(/\s+/g, ' '))) { + if (!own.test(selector)) { + continue + } + const entry = (out[selector] ??= { scoped, props: {} }) + entry.scoped = entry.scoped && scoped + for (const declaration of rule[2].split(';')) { + const [prop, ...value] = declaration.split(':') + if (prop.trim()) { + entry.props[prop.trim()] = value + .join(':') + .trim() + .replace(/\s+/g, ' ') + } + } + } + } + } + return Object.fromEntries(Object.entries(out).sort()) +} + +describe('placement reading widgets (golden)', () => { + it('matches the recorded outcomes case by case', async () => { + const actual = {} + for (const [name, widget] of Object.entries(WIDGETS)) { + for (const [placementName, placement] of Object.entries(PLACEMENTS)) { + for (const [answerName, answer] of Object.entries(ANSWERS)) { + actual[`${name} | load | ${placementName} | ${answerName}`] = + await runLoad(widget, { + placement, + answer, + }) + } + } + actual[`${name} | styles`] = finalStyles( + widget.file, + name === 'weather' ? 'weather-widget' : 'live-tile-widget', + ) + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const [name, value] of Object.entries(expected)) { + expect(actual[name], name).toEqual(value) + } + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/rendererState.golden.spec.js b/src/components/Widgets/Renderers/__tests__/rendererState.golden.spec.js new file mode 100644 index 000000000..a08de972b --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/rendererState.golden.spec.js @@ -0,0 +1,329 @@ +/** + * SPDX-FileCopyrightText: 2026 LaunchPad Contributors + * SPDX-License-Identifier: EUPL-1.2 + * + * Characterisation tests pinning the initial form state of + * `NewsWidgetForm.vue` and `LiveTileWidgetForm.vue`, and the error and + * paging state `FilesWidget.vue` keeps after a contents fetch, so those + * functions can be split into named steps without changing behaviour. + */ + +import axios from '@nextcloud/axios' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import FilesWidget from '../FilesWidget.vue' +import LiveTileWidgetForm from '../LiveTileWidgetForm.vue' +import NewsWidgetForm from '../NewsWidgetForm.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path, params = {}) => + Object.entries(params).reduce( + (acc, [key, value]) => acc.replace(`{${key}}`, value), + path, + ), +})) +vi.mock('../../../../services/liveTileClient.js', () => ({ + fetchConnectorAvailability: vi.fn(() => Promise.resolve(false)), + validateLiveTileSource: vi.fn(() => Promise.resolve({ valid: true, errors: [] })), +})) + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + vi.clearAllMocks() +}) + +const NEWS_KEYS = [ + 'feedUrls', 'layout', 'itemLimit', 'showThumbnails', 'showSummary', + 'summaryMaxChars', 'dateFormat', 'metadataFilterEnabled', + 'metadataFieldKey', 'metadataValue', +] + +function newsState(props) { + const vm = mount(NewsWidgetForm, { props }).vm + return Object.fromEntries(NEWS_KEYS.map((key) => [key, vm.$data[key]])) +} + +describe('NewsWidgetForm initial state', () => { + it('falls back to defaults for malformed values', () => { + expect(newsState({ + value: { + feedUrls: 'x', + layout: 'masonry', + itemLimit: '5', + showThumbnails: 'yes', + showSummary: undefined, + summaryMaxChars: null, + dateFormat: 'ABSOLUTE', + metadataFilter: { fieldKey: 3, value: null }, + }, + })).toEqual({ + feedUrls: [], + layout: 'list', + itemLimit: 10, + showThumbnails: false, + showSummary: true, + summaryMaxChars: 200, + dateFormat: 'relative', + metadataFilterEnabled: true, + metadataFieldKey: '', + metadataValue: '', + }) + }) + + it('reads the value prop when not editing and copies feed URLs', () => { + const feedUrls = ['https://a.example/rss'] + const state = newsState({ + value: { feedUrls, layout: 'grid', itemLimit: 0, showSummary: false, metadataFilter: null }, + }) + expect(state).toMatchObject({ + feedUrls, + layout: 'grid', + itemLimit: 0, + showThumbnails: true, + showSummary: false, + metadataFilterEnabled: false, + metadataFieldKey: '', + metadataValue: '', + }) + }) + + it('prefers the editing widget content over the value prop', () => { + const state = newsState({ + editingWidget: { content: { layout: 'carousel', metadataFilter: { fieldKey: 'k', value: 'v' } } }, + value: { layout: 'grid' }, + }) + expect(state).toMatchObject({ + layout: 'carousel', + metadataFilterEnabled: true, + metadataFieldKey: 'k', + metadataValue: 'v', + }) + }) + + it('treats a string metadata filter as no filter', () => { + expect(newsState({ value: { metadataFilter: 'x' } })).toMatchObject({ + metadataFilterEnabled: false, + metadataFieldKey: '', + }) + }) +}) + +const LIVE_KEYS = [ + 'label', 'sourceMode', 'url', 'sourceId', 'valueExpr', 'refresh', + 'formatPrefix', 'formatSuffix', 'formatThousands', 'badge', 'linkUrl', + 'linkTarget', 'connectorAvailable', 'urlAllowListError', 'MIN_REFRESH_SECONDS', +] + +function liveState(props) { + const vm = mount(LiveTileWidgetForm, { props }).vm + return Object.fromEntries(LIVE_KEYS.map((key) => [key, vm.$data[key]])) +} + +describe('LiveTileWidgetForm initial state', () => { + it('keeps falsy-but-set values and defaults null ones', () => { + const state = liveState({ + value: { + label: '', + sourceMode: null, + url: 'https://x.example', + sourceId: 0, + valueExpr: undefined, + refresh: 0, + format: { prefix: '€', thousands: 1 }, + badge: { enabled: true }, + linkUrl: null, + linkTarget: 'new-tab', + }, + }) + const defaults = liveState({ value: {} }) + expect(state).toEqual({ + ...defaults, + label: '', + url: 'https://x.example', + sourceId: 0, + refresh: 0, + formatPrefix: '€', + formatThousands: true, + badge: { ...defaults.badge, enabled: true }, + linkTarget: 'new-tab', + }) + expect(defaults.connectorAvailable).toBe(false) + expect(defaults.urlAllowListError).toBe('') + expect(defaults.MIN_REFRESH_SECONDS).toBe(30) + expect(defaults.formatThousands).toBe(false) + }) + + it('prefers the editing widget content and survives null format and badge', () => { + const state = liveState({ + editingWidget: { content: { label: 'Edit', format: null, badge: null } }, + value: { label: 'Value' }, + }) + const defaults = liveState({ value: {} }) + expect(state).toEqual({ ...defaults, label: 'Edit' }) + }) +}) + +function mountFiles() { + return mount(FilesWidget, { + propsData: { placement: { id: 7 }, content: { folderPath: '/x' } }, + }) +} + +describe('FilesWidget contents fetch state', () => { + it.each([ + [{ response: { status: 500, data: { error: 'folder_not_found' } } }, 'folder_not_found'], + [{ response: { status: 500, data: { error: 'no_access' } } }, 'no_access'], + [{ response: { status: 404, data: { error: 'no_access' } } }, 'folder_not_found'], + [{ response: { status: 500 } }, 'unknown_error'], + [new Error('network'), 'unknown_error'], + ])('maps a failure to its error code', async (err, code) => { + axios.get.mockRejectedValue(err) + const wrapper = mountFiles() + await flushPromises() + expect(wrapper.vm.errorCode).toBe(code) + expect(wrapper.vm.items).toEqual([]) + expect(wrapper.vm.nextCursor).toBe(null) + expect(wrapper.vm.loading).toBe(false) + }) + + it('appends the next page with the cursor and keeps items when a later page fails', async () => { + axios.get.mockResolvedValueOnce({ data: { items: [{ fileId: 1, name: 'a' }], nextCursor: 'c1' } }) + const wrapper = mountFiles() + await flushPromises() + expect(axios.get).toHaveBeenLastCalledWith( + '/apps/launchpad/api/widgets/files/7/contents', + { params: { currentPath: '/', limit: 50 } }, + ) + + axios.get.mockResolvedValueOnce({ data: { items: 'bad', nextCursor: '' } }) + await wrapper.vm.fetchContents(true) + expect(axios.get).toHaveBeenLastCalledWith( + '/apps/launchpad/api/widgets/files/7/contents', + { params: { currentPath: '/', limit: 50, cursor: 'c1' } }, + ) + expect(wrapper.vm.items).toEqual([{ fileId: 1, name: 'a' }]) + expect(wrapper.vm.nextCursor).toBe(null) + + wrapper.vm.nextCursor = 'c2' + axios.get.mockRejectedValueOnce({ response: { status: 403 } }) + await wrapper.vm.fetchContents(true) + expect(wrapper.vm.errorCode).toBe('no_access') + expect(wrapper.vm.items).toEqual([{ fileId: 1, name: 'a' }]) + expect(wrapper.vm.nextCursor).toBe('c2') + }) + + it('sends no cursor on a replace fetch and treats a missing body as empty', async () => { + axios.get.mockResolvedValueOnce({}) + const wrapper = mountFiles() + await flushPromises() + expect(wrapper.vm.items).toEqual([]) + expect(wrapper.vm.nextCursor).toBe(null) + expect(wrapper.vm.errorCode).toBe(null) + }) + + it('does not fetch for an unsaved placement', async () => { + mount(FilesWidget, { propsData: { placement: { id: 0 }, content: {} } }) + await flushPromises() + expect(axios.get).not.toHaveBeenCalled() + }) +}) + +describe('FilesWidget upload and delete', () => { + it('uploads every chosen file into the current folder, then refetches and clears the input', async () => { + axios.get.mockResolvedValue({ data: { items: [], nextCursor: null } }) + axios.post.mockResolvedValue({}) + const wrapper = mountFiles() + await flushPromises() + const input = { value: 'C:\\fake' } + Object.defineProperty(wrapper.vm.$refs, 'fileInput', { value: input, configurable: true }) + const files = [new File(['a'], 'a.txt'), new File(['b'], 'b.txt')] + + await wrapper.vm.onFileInputChange({ target: { files } }) + await flushPromises() + + const [url, formData, options] = axios.post.mock.calls[0] + expect(url).toBe('/apps/launchpad/api/widgets/files/7/upload') + expect(formData.getAll('files[]').map((f) => f.name)).toEqual(['a.txt', 'b.txt']) + expect(options).toEqual({ params: { currentPath: '/' } }) + expect(axios.get).toHaveBeenCalledTimes(2) + expect(input.value).toBe('') + }) + + it('refetches after a failed upload and ignores an empty selection', async () => { + axios.get.mockResolvedValue({ data: { items: [], nextCursor: null } }) + axios.post.mockRejectedValue(new Error('boom')) + const wrapper = mountFiles() + await flushPromises() + + await wrapper.vm.onFileInputChange({ target: { files: [] } }) + expect(axios.post).not.toHaveBeenCalled() + + await wrapper.vm.onFileInputChange({ target: { files: [new File(['a'], 'a.txt')] } }) + await flushPromises() + expect(axios.post).toHaveBeenCalledTimes(1) + expect(axios.get).toHaveBeenCalledTimes(2) + }) + + it('drops a deleted file, and refetches when the delete fails', async () => { + axios.get.mockResolvedValue({ data: { items: [{ fileId: 1, name: 'a' }, { fileId: 2, name: 'b' }], nextCursor: null } }) + axios.delete.mockResolvedValueOnce({}) + const wrapper = mountFiles() + await flushPromises() + + wrapper.vm.confirmTarget = { fileId: 1 } + await wrapper.vm.performDelete() + expect(axios.delete).toHaveBeenLastCalledWith('/apps/launchpad/api/widgets/files/7/files/1') + expect(wrapper.vm.items).toEqual([{ fileId: 2, name: 'b' }]) + expect(wrapper.vm.confirmTarget).toBe(null) + + axios.delete.mockRejectedValueOnce(new Error('boom')) + wrapper.vm.confirmTarget = { fileId: 2 } + await wrapper.vm.performDelete() + await flushPromises() + expect(axios.get).toHaveBeenCalledTimes(2) + expect(wrapper.vm.confirmTarget).toBe(null) + + await wrapper.vm.performDelete() + expect(axios.delete).toHaveBeenCalledTimes(2) + }) +}) + +describe('form validation order', () => { + it('lists news errors per row in order, then the filter error', () => { + const vm = mount(NewsWidgetForm, { + props: { value: { feedUrls: ['ftp://x', '', 'https://ok', 5], metadataFilter: { fieldKey: ' ' } } }, + }).vm + expect(vm.validate()).toEqual([ + 'Feed URL must start with http:// or https://', + 'Empty feed URL — remove it or fill it in', + 'Empty feed URL — remove it or fill it in', + 'Metadata field key is required when filter is enabled', + ]) + }) + + it('lists live-tile connector errors before the expression error and skips source checks in another mode', () => { + const vm = mount(LiveTileWidgetForm, { props: { value: { sourceMode: 'connector', sourceId: 3 } } }).vm + vm.sourceMode = 'connector' + vm.connectorAvailable = false + expect(vm.validate()).toEqual([ + 'Integriq is not available.', + 'Source id is required', + 'Value expression is required', + ]) + vm.sourceMode = 'other' + expect(vm.validate()).toEqual(['Value expression is required']) + vm.sourceMode = 'url' + vm.url = '' + vm.valueExpr = '$.x' + expect(vm.validate().length).toBeGreaterThan(0) + }) +}) diff --git a/src/components/Widgets/Renderers/__tests__/urlAllowList.golden.spec.js b/src/components/Widgets/Renderers/__tests__/urlAllowList.golden.spec.js new file mode 100644 index 000000000..abd86565c --- /dev/null +++ b/src/components/Widgets/Renderers/__tests__/urlAllowList.golden.spec.js @@ -0,0 +1,150 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for the URL checks of IframeWidgetForm and LiveTileWidgetForm: + * `checkUrlAllowed()` against every allow-list answer, and `validate()` over + * URLs (allowed, malformed, other schemes) with and without an allow-list + * error, compared with fixtures/urlAllowList.golden.json case by case. + * Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import IframeWidgetForm from '../IframeWidgetForm.vue' +import LiveTileWidgetForm from '../LiveTileWidgetForm.vue' +import { validateIframeUrl } from '../../../../services/iframeClient.js' +import { validateLiveTileSource } from '../../../../services/liveTileClient.js' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => `t:${text}`, + t: (_app, text) => `t:${text}`, +})) +vi.mock('../../../../services/iframeClient.js', () => ({ + validateIframeUrl: vi.fn(), +})) +vi.mock('../../../../services/liveTileClient.js', () => ({ + validateLiveTileSource: vi.fn(), + fetchConnectorAvailability: vi.fn(), + checkConnectorAvailable: vi.fn(), +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/urlAllowList.golden.json') + +const URLS = { + empty: '', + blank: ' ', + https: 'https://ok.example/page', + 'http upper case': 'HTTP://OK.EXAMPLE', + padded: ' https://ok.example ', + 'scheme only': 'https://', + 'no scheme': 'ok.example', + javascript: 'javascript:alert(1)', + data: 'data:text/html,<b>x</b>', + ftp: 'ftp://files.example', + 'protocol relative': '//ok.example', +} + +const ANSWERS = { + allowed: { valid: true, errors: [] }, + 'host not allowed': { valid: false, errors: ['host_not_allowed'] }, + 'invalid url': { valid: false, errors: ['invalid_url'] }, + 'both errors': { valid: false, errors: ['invalid_url', 'host_not_allowed'] }, + 'other error': { valid: false, errors: ['too_long'] }, + 'valid missing': { errors: ['host_not_allowed'] }, +} + +const FORMS = { + iframe: { + component: IframeWidgetForm, + client: validateIframeUrl, + host: (url) => ({ url, title: 'Frame', allowListChecked: 'unset' }), + }, + 'live tile url': { + component: LiveTileWidgetForm, + client: validateLiveTileSource, + host: (url) => ({ + url, + sourceMode: 'url', + valueExpr: 'value', + sourceId: '', + }), + }, + 'live tile connector': { + component: LiveTileWidgetForm, + client: validateLiveTileSource, + host: (url) => ({ + url, + sourceMode: 'connector', + valueExpr: '', + sourceId: 's1', + connectorAvailable: true, + }), + }, +} + +/** + * A stand-in for the form with its methods bound to it. + * + * @param {object} form The form under test. + * @param {object} fields The form's data. + * @return {object} The stand-in. + */ +function standIn(form, fields) { + const host = { urlAllowListError: 'earlier error', ...fields } + host.$emit = vi.fn() + host.assembledContent = { url: fields.url } + for (const [name, fn] of Object.entries(form.component.methods)) { + host[name] = fn.bind(host) + } + return host +} + +describe('URL allow-list checks (golden)', () => { + it('matches the recorded outcomes case by case', async () => { + const actual = {} + for (const [formName, form] of Object.entries(FORMS)) { + for (const [urlName, url] of Object.entries(URLS)) { + for (const [answerName, answer] of Object.entries(ANSWERS)) { + form.client.mockReset() + form.client.mockResolvedValue(answer) + const host = standIn(form, form.host(url)) + let outcome + try { + await host.checkUrlAllowed() + outcome = { + error: host.urlAllowListError, + checked: host.allowListChecked ?? '(none)', + } + } catch (error) { + outcome = { threw: error.constructor.name } + } + actual[`${formName} | check | ${urlName} | ${answerName}`] = { + ...outcome, + calls: form.client.mock.calls.length, + emitted: host.$emit.mock.calls.length, + } + } + for (const allowListError of ['', 'Not allowed']) { + const host = standIn(form, { + ...form.host(url), + urlAllowListError: allowListError, + }) + actual[ + `${formName} | validate | ${urlName} | ${allowListError || 'no allow-list error'}` + ] = host.validate() + } + } + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const [name, value] of Object.entries(expected)) { + expect(actual[name], name).toEqual(value) + } + }) +}) diff --git a/src/components/Widgets/Renderers/readingTile.css b/src/components/Widgets/Renderers/readingTile.css new file mode 100644 index 000000000..f3eacf83c --- /dev/null +++ b/src/components/Widgets/Renderers/readingTile.css @@ -0,0 +1,60 @@ +/* + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Styles shared by the widgets that show one server-side reading + * (WeatherWidget, LiveTileWidget): the centred root, the loading and error + * states with their retry button, the reading column and the badge that + * marks a stale reading. Each widget adds its own rules after this sheet. + */ + +.weather-widget, +.live-tile-widget { + width: 100%; + height: 100%; + display: flex; + align-items: center; + justify-content: center; +} + +.weather-widget__state, +.live-tile-widget__state { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + color: var(--color-text-maxcontrast, var(--color-main-text)); + text-align: center; +} + +.weather-widget__retry, +.live-tile-widget__retry { + border: 1px solid var(--color-border); + border-radius: var(--border-radius); + background: transparent; + padding: 4px 12px; + cursor: pointer; + color: var(--color-main-text); +} + +.weather-widget__reading, +.live-tile-widget__reading { + position: relative; + width: 100%; + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; +} + +.weather-widget__badge, +.live-tile-widget__stale-badge { + position: absolute; + top: -8px; + right: -8px; + font-size: 0.7rem; + padding: 2px 6px; + border-radius: var(--border-radius-pill, 8px); + background: var(--color-warning, #ffcc00); + color: var(--color-main-text); +} diff --git a/src/components/Widgets/VisibilityRuleRow.vue b/src/components/Widgets/VisibilityRuleRow.vue index b93ad9dd8..1c628a8cc 100644 --- a/src/components/Widgets/VisibilityRuleRow.vue +++ b/src/components/Widgets/VisibilityRuleRow.vue @@ -40,7 +40,8 @@ class="visibility-rule-row__field"> <NcSelectTags v-model="local.ruleConfig.groups" - :options="availableGroups" + :options="groupOptions" + :fetchTags="false" :multiple="true" :aria-label-combobox="t('launchpad', 'Groups')" :placeholder="t('launchpad', 'Select groups')" @@ -233,10 +234,67 @@ import { } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' import Delete from 'vue-material-design-icons/Delete.vue' +import { + FLAG_PROP, + LIST_PROP, + REQUIRED_OBJECT_PROP, +} from '../../constants/propDefinitions.js' +import { toGroupOptions } from '../../utils/groupOptions.js' const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/ +/** + * The canonical `time` ruleConfig: the window, plus the days when any. + * + * @param {object} ruleConfig The draft config. + * @return {object} the canonical config. + */ +function timeRuleConfig(ruleConfig) { + const config = { + startTime: ruleConfig.startTime, + endTime: ruleConfig.endTime, + } + if ( + Array.isArray(ruleConfig.days) + && ruleConfig.days.length > 0 + ) { + config.days = [...ruleConfig.days] + } + return config +} + +/** + * The canonical `date` ruleConfig, without empty optional keys. + * + * @param {object} ruleConfig The draft config. + * @return {object} the canonical config. + */ +function dateRuleConfig(ruleConfig) { + const config = {} + if (ruleConfig.startDate) { + config.startDate = ruleConfig.startDate + } + if (ruleConfig.endDate) { + config.endDate = ruleConfig.endDate + } + return config +} + +/** + * The builder of the canonical ruleConfig per rule type. + */ +const RULE_CONFIG_BUILDERS = Object.freeze({ + group: (ruleConfig) => ({ groups: [...(ruleConfig.groups || [])] }), + time: timeRuleConfig, + date: dateRuleConfig, + attribute: (ruleConfig) => ({ + attribute: ruleConfig.attribute, + operator: ruleConfig.operator || 'equals', + value: ruleConfig.value, + }), +}) + /** * Build a pristine, type-correct `ruleConfig` for a given ruleType. Used * both to seed a fresh row and to reset operands when the author switches @@ -274,28 +332,16 @@ export default { props: { /** The rule this row edits: `{id?, ruleType, ruleConfig, isInclude}`. */ - rule: { - type: Object, - required: true, - }, + rule: REQUIRED_OBJECT_PROP, /** Group-id options for the group-rule multi-select. */ - availableGroups: { - type: Array, - default: () => [], - }, + availableGroups: LIST_PROP, /** Disables Save/Remove while a request for this row is in flight. */ - busy: { - type: Boolean, - default: false, - }, + busy: FLAG_PROP, /** True for a not-yet-persisted draft row (no `id` yet). */ - isNew: { - type: Boolean, - default: false, - }, + isNew: FLAG_PROP, }, emits: ['update:rule', 'save', 'remove'], @@ -311,6 +357,15 @@ export default { }, computed: { + /** + * The group picker's options: the offered groups plus any already chosen. + * + * @spec openspec/specs/conditional-visibility-editor/spec.md + */ + groupOptions() { + return toGroupOptions(this.availableGroups, this.local.ruleConfig?.groups) + }, + /** @spec openspec/specs/conditional-visibility-editor/spec.md */ rowKey() { return this.rule.id ?? this.rule._localKey ?? 'draft' @@ -467,18 +522,20 @@ export default { /** @spec openspec/specs/conditional-visibility-editor/spec.md */ hasAtLeastOneValidDate() { const { startDate, endDate } = this.local.ruleConfig - const hasStart = !!startDate - const hasEnd = !!endDate - if (!hasStart && !hasEnd) { + if (!startDate && !endDate) { return false } - if (hasStart && !this.isValidDate(startDate)) { - return false - } - if (hasEnd && !this.isValidDate(endDate)) { - return false - } - return true + return this.isBlankOrValidDate(startDate) && this.isBlankOrValidDate(endDate) + }, + + /** + * Whether an optional date bound is unset or a valid YYYY-MM-DD. + * + * @param {unknown} value The date bound. + * @return {boolean} true when it does not block saving. + */ + isBlankOrValidDate(value) { + return !value || this.isValidDate(value) }, /** @@ -575,41 +632,11 @@ export default { * @return {object} the canonical ruleConfig blob. */ buildRuleConfig() { - switch (this.local.ruleType) { - case 'group': - return { groups: [...(this.local.ruleConfig.groups || [])] } - case 'time': { - const config = { - startTime: this.local.ruleConfig.startTime, - endTime: this.local.ruleConfig.endTime, - } - if ( - Array.isArray(this.local.ruleConfig.days) - && this.local.ruleConfig.days.length > 0 - ) { - config.days = [...this.local.ruleConfig.days] - } - return config - } - case 'date': { - const config = {} - if (this.local.ruleConfig.startDate) { - config.startDate = this.local.ruleConfig.startDate - } - if (this.local.ruleConfig.endDate) { - config.endDate = this.local.ruleConfig.endDate - } - return config - } - case 'attribute': - return { - attribute: this.local.ruleConfig.attribute, - operator: this.local.ruleConfig.operator || 'equals', - value: this.local.ruleConfig.value, - } - default: - return {} + const ruleType = this.local.ruleType + if (!Object.hasOwn(RULE_CONFIG_BUILDERS, ruleType)) { + return {} } + return RULE_CONFIG_BUILDERS[ruleType](this.local.ruleConfig) }, /** diff --git a/src/components/Widgets/WidgetContextMenu.vue b/src/components/Widgets/WidgetContextMenu.vue index 045a56e8d..01116073a 100644 --- a/src/components/Widgets/WidgetContextMenu.vue +++ b/src/components/Widgets/WidgetContextMenu.vue @@ -32,7 +32,7 @@ role="menuitem" data-testid="ctx-visibility-rules" @click="onVisibilityRules"> - {{ t('launchpad', 'Visibility rules…') }} + {{ t('launchpad', 'Who sees this widget?') }} </button> <button type="button" @@ -43,6 +43,7 @@ {{ t('launchpad', 'Read confirmation…') }} </button> <button + v-if="!removeLocked" type="button" class="widget-context-menu__item widget-context-menu__item--danger" role="menuitem" @@ -79,6 +80,7 @@ import { t } from '@nextcloud/l10n' * Props: * - `top` (number): clamped pixel offset from the viewport top * - `left` (number): clamped pixel offset from the viewport left + * - `removeLocked` (boolean): leave Remove out (default false) * * Emits: * - `edit`: user clicked Edit — parent should open `AddWidgetModal` with @@ -103,6 +105,12 @@ export default { type: Number, required: true, }, + + /** Leaves Remove out, for a widget the user may not remove. */ + removeLocked: { + type: Boolean, + default: false, + }, }, emits: [ @@ -114,28 +122,84 @@ export default { 'close', ], + data() { + return { + /** The position after fitting the rendered box into the viewport. */ + fitted: null, + } + }, + computed: { /** * Absolute positioning + the fixed look (z-index, min-width) lives * here so the parent only has to pass coordinates. Position is * `fixed` (not `absolute`) so viewport-relative clientX/clientY * values from the right-click event map cleanly without having to - * account for scroll offsets. + * account for scroll offsets. The parent clamps with an estimated + * size; once rendered, the popover pulls itself back inside the + * viewport with its real size (REQ-WDG-017). * * @return {object} * @spec openspec/specs/widgets/spec.md */ positionStyle() { + const at = this.fitted ?? { top: this.top, left: this.left } return { - top: `${this.top}px`, - left: `${this.left}px`, + top: `${at.top}px`, + left: `${at.left}px`, } }, }, + watch: { + /** + * Re-fit when the parent moves the popover. + * + * @spec openspec/specs/widgets/spec.md + */ + top() { + this.fitToViewport() + }, + + /** + * Re-fit when the parent moves the popover. + * + * @spec openspec/specs/widgets/spec.md + */ + left() { + this.fitToViewport() + }, + }, + + mounted() { + this.fitToViewport() + }, + methods: { t, + /** + * Measure the rendered popover and move it up or left so it ends + * inside the viewport (REQ-WDG-017). The item count changes over time + * (and Remove can be absent), so the real box is used, not a constant. + * + * @return {Promise<void>} + * @spec openspec/specs/widgets/spec.md + */ + async fitToViewport() { + this.fitted = null + await this.$nextTick() + const box = this.$el?.getBoundingClientRect?.() + if (!box || typeof window === 'undefined') { + return + } + const top = Math.max(0, Math.min(this.top, window.innerHeight - box.height)) + const left = Math.max(0, Math.min(this.left, window.innerWidth - box.width)) + if (top !== this.top || left !== this.left) { + this.fitted = { top, left } + } + }, + /** @spec openspec/specs/widgets/spec.md */ onEdit() { this.$emit('edit') @@ -148,7 +212,12 @@ export default { this.$emit('close') }, - /** @spec openspec/specs/conditional-visibility/spec.md */ + /** + * "Who sees this widget?": open the rules dialog for this widget. + * + * @spec openspec/specs/conditional-visibility/spec.md + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-dialog-is-in-the-widgets-menu-req-cvui-007 + */ onVisibilityRules() { this.$emit('visibilityRules') this.$emit('close') diff --git a/src/components/Widgets/WidgetEditMenu.vue b/src/components/Widgets/WidgetEditMenu.vue new file mode 100644 index 000000000..8ecc38508 --- /dev/null +++ b/src/components/Widgets/WidgetEditMenu.vue @@ -0,0 +1,116 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<!-- + WidgetEditMenu — the three-dot menu a widget shows in edit mode (board + LpBewerken): Edit widget, "Who sees this widget?" and Delete widget. + The same look and test ids as nc-vue's CnWidgetEditCog, which offers no + room for a third item; "Who sees this widget?" is here so the rules + dialog is reachable by keyboard and not only by right-click + (conditional-visibility-editor REQ-CVUI-007). +--> + +<template> + <NcActions + :aria-label="menuLabel" + :forceMenu="true" + placement="bottom-end" + variant="tertiary" + class="widget-edit-menu" + data-testid="cn-widget-edit-cog" + @click.stop> + <template #icon> + <DotsVertical :size="20" /> + </template> + <NcActionButton + :closeAfterClick="true" + data-testid="cn-widget-edit-cog-edit" + @click="$emit('edit')"> + <template #icon> + <Pencil :size="20" /> + </template> + {{ t('launchpad', 'Edit widget') }} + </NcActionButton> + <NcActionButton + :closeAfterClick="true" + data-testid="widget-who-sees" + @click="$emit('whoSees')"> + <template #icon> + <AccountEye :size="20" /> + </template> + {{ t('launchpad', 'Who sees this widget?') }} + </NcActionButton> + <NcActionButton + v-if="!removeLocked" + :closeAfterClick="true" + data-testid="cn-widget-edit-cog-delete" + @click="$emit('remove')"> + <template #icon> + <Delete :size="20" /> + </template> + {{ t('launchpad', 'Delete widget') }} + </NcActionButton> + </NcActions> +</template> + +<script> +import { NcActionButton, NcActions } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import AccountEye from 'vue-material-design-icons/AccountEye.vue' +import Delete from 'vue-material-design-icons/Delete.vue' +import DotsVertical from 'vue-material-design-icons/DotsVertical.vue' +import Pencil from 'vue-material-design-icons/Pencil.vue' + +export default { + name: 'WidgetEditMenu', + + components: { + AccountEye, + Delete, + DotsVertical, + NcActionButton, + NcActions, + Pencil, + }, + + props: { + /** Accessible name of the menu. */ + menuLabel: { + type: String, + default: 'Widget menu', + }, + + /** Leaves Delete out, for a widget the user may not remove. */ + removeLocked: { + type: Boolean, + default: false, + }, + }, + + emits: ['edit', 'whoSees', 'remove'], + + methods: { + t, + }, +} +</script> + +<style scoped> +/* The white rounded button of the widget chrome, as CnWidgetEditCog draws it, + so the menu reads on any widget background. */ +.widget-edit-menu :deep(.action-item__menutoggle), +.widget-edit-menu :deep(.button-vue) { + background-color: var(--color-main-background) !important; + border: 1px solid var(--color-border) !important; + border-radius: var(--border-radius, 8px) !important; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08); + color: var(--color-main-text) !important; +} + +.widget-edit-menu :deep(.action-item__menutoggle:hover), +.widget-edit-menu :deep(.button-vue:hover) { + background-color: var(--color-background-hover) !important; +} +</style> diff --git a/src/components/Widgets/WidgetRowFilter.vue b/src/components/Widgets/WidgetRowFilter.vue new file mode 100644 index 000000000..2a25b8cc2 --- /dev/null +++ b/src/components/Widgets/WidgetRowFilter.vue @@ -0,0 +1,60 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <input + :value="modelValue" + type="search" + class="widget-row-filter" + :aria-label="t('launchpad', 'Filter these results')" + :placeholder="t('launchpad', 'Filter these results')" + data-testid="widget-row-filter" + @input="$emit('update:modelValue', $event.target.value)" + @keydown.esc="$emit('update:modelValue', '')"> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { TEXT_PROP } from '../../constants/propDefinitions.js' + +/** + * WidgetRowFilter — the filter field over one widget's rendered rows + * (REQ-DWMS-008). + * + * It holds nothing: the widget keeps the term in its own component state, + * so the term is never persisted, never shared and gone after a reload, and + * it never writes to the placement or its saved search. + * + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/specs/dashboards-and-who-may-see-them/spec.md#requirement-req-dwms-008-search-inside-a-widgets-results + */ +export default { + name: 'WidgetRowFilter', + + props: { + /** + * The filter term, owned by the widget's view state. + */ + modelValue: TEXT_PROP, + }, + + emits: ['update:modelValue'], + + methods: { + t, + }, +} +</script> + +<style scoped> +.widget-row-filter { + width: 100%; + margin: 0 0 8px; + padding: 4px 8px; + border: 1px solid var(--color-border-maxcontrast); + border-radius: var(--border-radius); + background: var(--color-main-background); + color: var(--color-main-text); +} +</style> diff --git a/src/components/Widgets/__tests__/ConditionalVisibilityEditor.edges.spec.js b/src/components/Widgets/__tests__/ConditionalVisibilityEditor.edges.spec.js new file mode 100644 index 000000000..1467ffe0f --- /dev/null +++ b/src/components/Widgets/__tests__/ConditionalVisibilityEditor.edges.spec.js @@ -0,0 +1,251 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the edge paths of `ConditionalVisibilityEditor.vue` + * that the main spec does not reach: no placement means no load, a failed + * load or delete leaves a consistent list, a create answer without an id + * reloads, the preview sends the date/time as ISO and names matched exclude + * rules, a failed preview shows its error, and describeRule() summarises + * every rule type. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ConditionalVisibilityEditor from '../ConditionalVisibilityEditor.vue' +import { api } from '../../../services/api.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (p) => `/index.php${p}` })) + +vi.mock('../../../services/api.js', () => ({ + api: { + getWidgetRules: vi.fn(), + addWidgetRule: vi.fn(), + updateRule: vi.fn(), + deleteRule: vi.fn(), + previewVisibility: vi.fn(), + }, +})) + +// VisibilityRuleRow is OUR OWN component with its own dedicated spec +// (VisibilityRuleRow.spec.js covers its operand/validation behaviour in +// depth); here it is stubbed to a thin, controllable shell so this file +// stays focused on ConditionalVisibilityEditor's own responsibilities: +// list loading, include/exclude grouping, CRUD wiring, and preview. +const RuleRowStub = { + props: ['rule', 'availableGroups', 'busy', 'isNew'], + template: `<div class="rule-row-stub" :data-rule-id="rule.id" :data-is-new="isNew"> + <button class="save-btn" @click="$emit('save', { ruleType: rule.ruleType, ruleConfig: rule.ruleConfig, isInclude: rule.isInclude })">save</button> + <button class="remove-btn" @click="$emit('remove')">remove</button> + <button class="toggle-btn" @click="$emit('update:rule', { ruleType: rule.ruleType, ruleConfig: rule.ruleConfig, isInclude: !rule.isInclude })">toggle</button> + </div>`, +} + +const stubs = { + VisibilityRuleRow: RuleRowStub, + NcButton: { + emits: ['click'], + template: + '<button :data-test="$attrs[\'data-test\']" :disabled="$attrs.disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcSelectTags: { template: '<div class="nc-selecttags-stub" />' }, + NcTextField: { + props: ['value'], + template: + '<input :data-test="$attrs[\'data-test\']" @input="$emit(\'update:value\', $event.target.value)" />', + }, + NcLoadingIcon: { template: '<span class="loading" />' }, + Plus: { template: '<span />' }, + Eye: { template: '<span class="icon-eye" />' }, + EyeOff: { template: '<span class="icon-eye-off" />' }, +} + +function mountEditor(props = {}) { + return mount(ConditionalVisibilityEditor, { + propsData: { placementId: 10, ...props }, + stubs, + }) +} + +beforeEach(() => { + globalThis.t = (_app, key, params) => { + if (!params) { + return key + } + return key.replace(/\{(\w+)\}/g, (_, name) => params[name]) + } + vi.clearAllMocks() +}) + +async function settle(wrapper) { + await new Promise((resolve) => setTimeout(resolve, 0)) + await wrapper.vm.$nextTick() +} + +const groupRule = { + id: 1, + ruleType: 'group', + ruleConfig: { groups: ['marketing'] }, + isInclude: true, +} +const timeRule = { + id: 2, + ruleType: 'time', + ruleConfig: { startTime: '09:00', endTime: '17:00' }, + isInclude: false, +} + +describe('ConditionalVisibilityEditor — loading', () => { + it('does not call the API and shows no rules without a placement id', async () => { + const wrapper = mountEditor({ placementId: null }) + await settle(wrapper) + expect(api.getWidgetRules).not.toHaveBeenCalled() + expect(wrapper.vm.rules).toEqual([]) + }) + + it('falls back to an empty list when loading fails', async () => { + api.getWidgetRules.mockRejectedValue(new Error('boom')) + const wrapper = mountEditor() + await settle(wrapper) + expect(api.getWidgetRules).toHaveBeenCalledWith(10) + expect(wrapper.vm.rules).toEqual([]) + expect(wrapper.vm.loading).toBe(false) + }) + + it('reloads when the placement id changes', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [] } }) + const wrapper = mountEditor() + await settle(wrapper) + await wrapper.setProps({ placementId: 11 }) + await settle(wrapper) + expect(api.getWidgetRules).toHaveBeenLastCalledWith(11) + }) +}) + +describe('ConditionalVisibilityEditor — row edits', () => { + it('ignores an update for a row that is no longer in the list', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [groupRule] } }) + const wrapper = mountEditor() + await settle(wrapper) + const before = wrapper.vm.rules.slice() + wrapper.vm.onRowUpdate({ id: 99 }, { isInclude: false }) + expect(wrapper.vm.rules).toEqual(before) + }) + + it('restores the removed row and emits nothing when the delete fails', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [groupRule, timeRule] } }) + api.deleteRule.mockRejectedValue(new Error('denied')) + const wrapper = mountEditor() + await settle(wrapper) + const row = wrapper.vm.rules[0] + await wrapper.vm.onRowRemove(row) + expect(api.deleteRule).toHaveBeenCalledWith(1) + expect(wrapper.vm.rules.map((r) => r.id)).toEqual([1, 2]) + expect(wrapper.emitted('ruleRemoved')).toBeUndefined() + expect(wrapper.vm.isRowBusy(row)).toBe(false) + }) + + it('reloads the list when a create answer carries no id', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [] } }) + api.addWidgetRule.mockResolvedValue({ data: {} }) + const wrapper = mountEditor() + await settle(wrapper) + wrapper.vm.addRule() + const draft = wrapper.vm.rules[0] + await wrapper.vm.onRowSave(draft, { ruleType: 'group', ruleConfig: { groups: ['a'] }, isInclude: true }) + expect(api.addWidgetRule).toHaveBeenCalledWith(10, { ruleType: 'group', ruleConfig: { groups: ['a'] }, isInclude: true }) + expect(api.getWidgetRules).toHaveBeenCalledTimes(2) + expect(wrapper.emitted('ruleAdded')).toHaveLength(1) + }) + + it('emits nothing and clears the busy flag when a save fails', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [groupRule] } }) + api.updateRule.mockRejectedValue(new Error('bad')) + const wrapper = mountEditor() + await settle(wrapper) + const row = wrapper.vm.rules[0] + await wrapper.vm.onRowSave(row, { ruleType: 'group', ruleConfig: {}, isInclude: true }) + expect(wrapper.emitted('ruleUpdated')).toBeUndefined() + expect(wrapper.vm.isRowBusy(row)).toBe(false) + }) + + it('gives every new draft its own local key', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [] } }) + const wrapper = mountEditor() + await settle(wrapper) + wrapper.vm.addRule() + wrapper.vm.addRule() + const keys = wrapper.vm.rules.map((r) => wrapper.vm.rowKey(r)) + expect(keys).toEqual(['local--1', 'local--2']) + }) +}) + +describe('ConditionalVisibilityEditor — preview', () => { + it('sends the chosen date/time as an ISO string', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [groupRule] } }) + api.previewVisibility.mockResolvedValue({ + data: { visible: true, matchedIncludeRuleIds: [], matchedExcludeRuleIds: [] }, + }) + const wrapper = mountEditor() + await settle(wrapper) + wrapper.vm.previewDatetime = '2026-03-01T10:30' + await wrapper.vm.runPreview() + const body = api.previewVisibility.mock.calls[0][0] + expect(body.context.datetime).toBe(new Date('2026-03-01T10:30').toISOString()) + }) + + it('names the matched exclude rule when the widget is hidden', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [groupRule, timeRule] } }) + api.previewVisibility.mockResolvedValue({ + data: { visible: false, matchedIncludeRuleIds: [], matchedExcludeRuleIds: [2] }, + }) + const wrapper = mountEditor() + await settle(wrapper) + await wrapper.find('[data-test="run-preview"]').trigger('click') + await settle(wrapper) + expect(wrapper.find('[data-test="preview-verdict-text"]').text()).toBe('Hidden') + const reasons = wrapper.findAll('[data-test="preview-matched-exclude"]') + expect(reasons).toHaveLength(1) + expect(reasons[0].text()).toBe('Matched exclude rule: 09:00–17:00') + expect(wrapper.find('[data-test="preview-matched-include"]').exists()).toBe(false) + }) + + it('names a matched exclude rule that was never saved', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [groupRule] } }) + // Echo what the endpoint does: each rule's id, or its index when it has none. + api.previewVisibility.mockImplementation(async (body) => ({ + data: { + visible: false, + matchedIncludeRuleIds: body.rules.filter((r) => r.isInclude).map((r, i) => r.id ?? i), + matchedExcludeRuleIds: body.rules + .map((r, i) => ({ r, i })) + .filter(({ r }) => !r.isInclude) + .map(({ r, i }) => r.id ?? i), + }, + })) + const wrapper = mountEditor() + await settle(wrapper) + wrapper.vm.addRule() + wrapper.vm.rules[1] = { ...wrapper.vm.rules[1], ...timeRule, id: null } + await wrapper.find('[data-test="run-preview"]').trigger('click') + await settle(wrapper) + const reasons = wrapper.findAll('[data-test="preview-matched-exclude"]') + expect(reasons).toHaveLength(1) + expect(reasons[0].text()).toBe('Matched exclude rule: 09:00–17:00') + expect(wrapper.findAll('[data-test="preview-matched-include"]')).toHaveLength(1) + }) + + it('shows the preview error when the preview request fails', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [groupRule] } }) + api.previewVisibility.mockRejectedValue(new Error('500')) + const wrapper = mountEditor() + await settle(wrapper) + await wrapper.vm.runPreview() + await settle(wrapper) + expect(wrapper.find('[data-test="preview-error"]').exists()).toBe(true) + expect(wrapper.find('[data-test="preview-result"]').exists()).toBe(false) + }) +}) diff --git a/src/components/Widgets/__tests__/ConditionalVisibilityEditor.interactions.spec.js b/src/components/Widgets/__tests__/ConditionalVisibilityEditor.interactions.spec.js new file mode 100644 index 000000000..4feb3743e --- /dev/null +++ b/src/components/Widgets/__tests__/ConditionalVisibilityEditor.interactions.spec.js @@ -0,0 +1,170 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `ConditionalVisibilityEditor.vue` driven through its + * rendered controls: an exclude ("Hide when…") row's live update and save, + * the Add rule button, and a rules response that is a bare array. The View + * as pickers are covered in ConditionalVisibilityEditor.viewAs.spec.js. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ConditionalVisibilityEditor from '../ConditionalVisibilityEditor.vue' +import { api } from '../../../services/api.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (p) => `/index.php${p}` })) + +vi.mock('../../../services/api.js', () => ({ + api: { + getWidgetRules: vi.fn(), + addWidgetRule: vi.fn(), + updateRule: vi.fn(), + deleteRule: vi.fn(), + previewVisibility: vi.fn(), + }, +})) + +// VisibilityRuleRow has its own specs; here it is a thin shell that emits +// the row events so this file stays on the editor's own wiring. +const RuleRowStub = { + props: ['rule', 'availableGroups', 'busy', 'isNew'], + emits: ['update:rule', 'save', 'remove'], + template: `<div class="rule-row-stub" :data-rule-id="rule.id" :data-is-new="String(isNew)"> + <button class="save-btn" @click="$emit('save', { ruleType: rule.ruleType, ruleConfig: { groups: ['sales'] }, isInclude: rule.isInclude })">save</button> + <button class="toggle-btn" @click="$emit('update:rule', { ruleType: rule.ruleType, ruleConfig: rule.ruleConfig, isInclude: !rule.isInclude })">toggle</button> + </div>`, +} + +const stubs = { + VisibilityRuleRow: RuleRowStub, + NcButton: { + props: ['disabled'], + emits: ['click'], + template: + '<button :disabled="disabled" @click="$emit(\'click\')"><slot name="icon" /><slot /></button>', + }, + NcSelectTags: { + props: ['modelValue', 'options'], + emits: ['update:modelValue'], + template: + '<div class="nc-selecttags-stub"><button class="pick-all" @click="$emit(\'update:modelValue\', options.map((o) => o.id))">all</button></div>', + }, + NcTextField: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: + '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcLoadingIcon: { template: '<span class="loading" />' }, + Plus: { template: '<span class="icon-plus" />' }, + Eye: { template: '<span class="icon-eye" />' }, + EyeOff: { template: '<span class="icon-eye-off" />' }, +} + +function mountEditor(props = {}) { + return mount(ConditionalVisibilityEditor, { + props: { placementId: 10, availableGroups: ['admin', 'sales'], ...props }, + global: { stubs }, + }) +} + +async function settle(wrapper) { + await new Promise((resolve) => setTimeout(resolve, 0)) + await wrapper.vm.$nextTick() +} + +const excludeRule = { + id: 7, + ruleType: 'group', + ruleConfig: { groups: ['admin'] }, + isInclude: false, +} + +/** Open the editor of every saved rule's card (cards start closed). */ +async function openEditors(wrapper) { + for (const button of wrapper.findAll('[data-test="rule-card-edit"]')) { + await button.trigger('click') + } +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + vi.clearAllMocks() +}) + +describe('ConditionalVisibilityEditor — exclude rows', () => { + it('moves an exclude row to the include section on a live update', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [excludeRule] } }) + const wrapper = mountEditor() + await settle(wrapper) + await openEditors(wrapper) + + const section = wrapper.find('[data-test="exclude-section"]') + expect(section.findAll('.rule-row-stub')).toHaveLength(1) + expect(wrapper.find('[data-test="include-section"]').exists()).toBe(false) + + await section.find('.toggle-btn').trigger('click') + + expect(wrapper.find('[data-test="exclude-section"]').exists()).toBe(false) + const include = wrapper.find('[data-test="include-section"]') + expect(include.find('.rule-row-stub').attributes('data-rule-id')).toBe('7') + expect(wrapper.vm.rules[0]).toMatchObject({ id: 7, isInclude: true }) + expect(api.updateRule).not.toHaveBeenCalled() + }) + + it('saving an exclude row PUTs it and merges the server copy', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [excludeRule] } }) + api.updateRule.mockResolvedValue({ + data: { data: { id: 7, ruleType: 'group', ruleConfig: { groups: ['sales'] }, isInclude: false } }, + }) + const wrapper = mountEditor() + await settle(wrapper) + await openEditors(wrapper) + + await wrapper.find('[data-test="exclude-section"] .save-btn').trigger('click') + await settle(wrapper) + + expect(api.updateRule).toHaveBeenCalledWith(7, { + ruleType: 'group', + ruleConfig: { groups: ['sales'] }, + isInclude: false, + }) + expect(wrapper.vm.rules[0].ruleConfig).toEqual({ groups: ['sales'] }) + expect(wrapper.emitted('ruleUpdated')).toHaveLength(1) + }) +}) + +describe('ConditionalVisibilityEditor — loading shapes', () => { + it('accepts a bare array as the rules response', async () => { + api.getWidgetRules.mockResolvedValue({ data: [excludeRule] }) + const wrapper = mountEditor() + await settle(wrapper) + + expect(api.getWidgetRules).toHaveBeenCalledWith(10) + expect(wrapper.vm.rules).toEqual([{ ...excludeRule, _localKey: undefined }]) + expect(wrapper.find('[data-test="visibility-empty-state"]').exists()).toBe(false) + }) +}) + +describe('ConditionalVisibilityEditor — add rule button', () => { + it('renders its icon and appends a new include draft row', async () => { + api.getWidgetRules.mockResolvedValue({ data: { rules: [] } }) + const wrapper = mountEditor() + await settle(wrapper) + + const addBtn = wrapper.findAll('button').find((b) => b.text() === 'Add rule') + expect(addBtn.find('.icon-plus').exists()).toBe(true) + expect(wrapper.find('[data-test="visibility-empty-state"]').exists()).toBe(true) + + await addBtn.trigger('click') + + const row = wrapper.find('[data-test="include-section"] .rule-row-stub') + expect(row.attributes('data-is-new')).toBe('true') + expect(wrapper.find('[data-test="visibility-empty-state"]').exists()).toBe(false) + }) +}) + diff --git a/src/components/Widgets/__tests__/ConditionalVisibilityEditor.spec.js b/src/components/Widgets/__tests__/ConditionalVisibilityEditor.spec.js index 223152b5d..7233de496 100644 --- a/src/components/Widgets/__tests__/ConditionalVisibilityEditor.spec.js +++ b/src/components/Widgets/__tests__/ConditionalVisibilityEditor.spec.js @@ -75,6 +75,13 @@ function mountEditor(props = {}) { }) } +/** Open the editor of every saved rule's card (cards start closed). */ +async function openEditors(wrapper) { + for (const button of wrapper.findAll('[data-test="rule-card-edit"]')) { + await button.trigger('click') + } +} + beforeEach(() => { globalThis.t = (_app, key, params) => { if (!params) { @@ -155,6 +162,7 @@ describe('ConditionalVisibilityEditor', () => { wrapper.findAll('[data-test="visibility-rule-row-include"]'), ).toHaveLength(1) + await openEditors(wrapper) await wrapper.find('.toggle-btn').trigger('click') expect( @@ -220,6 +228,8 @@ describe('ConditionalVisibilityEditor', () => { await new Promise((resolve) => setTimeout(resolve, 0)) await wrapper.vm.$nextTick() + expect(wrapper.find('.save-btn').exists()).toBe(false) + await openEditors(wrapper) await wrapper.find('.save-btn').trigger('click') await wrapper.vm.$nextTick() @@ -245,7 +255,7 @@ describe('ConditionalVisibilityEditor', () => { await new Promise((resolve) => setTimeout(resolve, 0)) await wrapper.vm.$nextTick() - await wrapper.find('.remove-btn').trigger('click') + await wrapper.find('[data-test="rule-card-delete"]').trigger('click') await wrapper.vm.$nextTick() expect(api.deleteRule).toHaveBeenCalledWith(5) @@ -292,7 +302,6 @@ describe('ConditionalVisibilityEditor', () => { await new Promise((resolve) => setTimeout(resolve, 0)) await wrapper.vm.$nextTick() - wrapper.vm.previewGroups = ['marketing'] await wrapper.find('[data-test="run-preview"]').trigger('click') await new Promise((resolve) => setTimeout(resolve, 0)) await wrapper.vm.$nextTick() @@ -307,7 +316,8 @@ describe('ConditionalVisibilityEditor', () => { isInclude: true, }, ]) - expect(body.context.groups).toEqual(['marketing']) + expect(body.match).toBe('any') + expect(body.placementId).toBe(10) expect(wrapper.find('[data-test="preview-verdict-text"]').text()).toBe( 'Visible', diff --git a/src/components/Widgets/__tests__/ConditionalVisibilityEditor.viewAs.spec.js b/src/components/Widgets/__tests__/ConditionalVisibilityEditor.viewAs.spec.js new file mode 100644 index 000000000..ccf70bf8d --- /dev/null +++ b/src/components/Widgets/__tests__/ConditionalVisibilityEditor.viewAs.spec.js @@ -0,0 +1,211 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * "Who sees this widget?" as board LpZichtbaarheid draws it + * (conditional-visibility-editor REQ-CVUI-006): the two choice cards save + * how the rules combine, each rule is a card with Edit and Delete, and View + * as previews the rules for a person at a moment and says so in a sentence. + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ConditionalVisibilityEditor from '../ConditionalVisibilityEditor.vue' +import { api } from '../../../services/api.js' + +vi.mock('@nextcloud/auth', () => ({ + getCurrentUser: () => ({ uid: 'admin', displayName: 'Ada Admin' }), +})) + +vi.mock('../../../services/api.js', () => ({ + api: { + getWidgetRules: vi.fn(), + addWidgetRule: vi.fn(), + updateRule: vi.fn(), + deleteRule: vi.fn(), + previewVisibility: vi.fn(), + searchSharees: vi.fn(), + updateWidgetPlacement: vi.fn(), + }, +})) + +const RULES = [ + { id: 1, ruleType: 'group', ruleConfig: { groups: ['kcc'] }, isInclude: true }, + { + id: 2, + ruleType: 'time', + ruleConfig: { startTime: '08:00', endTime: '17:00', days: ['mon', 'tue', 'wed', 'thu', 'fri'] }, + isInclude: true, + }, +] + +const stubs = { + VisibilityRuleRow: { props: ['rule'], template: '<div class="rule-row-stub" :data-rule-id="rule.id" />' }, + NcButton: { + props: ['disabled'], + emits: ['click'], + template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot name="icon" /><slot /></button>', + }, + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options'], + emits: ['update:modelValue', 'search'], + template: '<div class="nc-select-stub" />', + }, + NcTextField: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcLoadingIcon: { template: '<span />' }, + Plus: { template: '<span />' }, + Eye: { template: '<span />' }, + EyeOff: { template: '<span />' }, +} + +/** + * The editor for placement 10 with the board's two rules, settled. + * + * @param {object} props Extra props. + * @return {Promise<object>} the wrapper. + */ +async function mountEditor(props = {}) { + api.getWidgetRules.mockResolvedValue({ data: { rules: RULES } }) + const wrapper = mount(ConditionalVisibilityEditor, { + props: { placementId: 10, availableGroups: [{ id: 'kcc', displayName: 'KCC' }], ...props }, + global: { stubs }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('choice cards: all rules or one rule must match', () => { + it('shows both cards as a radio group with the stored mode checked', async () => { + const wrapper = await mountEditor({ ruleMatch: 'all' }) + expect(wrapper.find('[data-test="rule-match"]').attributes('role')).toBe('radiogroup') + const all = wrapper.find('[data-test="rule-match-all"]') + const any = wrapper.find('[data-test="rule-match-any"]') + expect(all.text()).toBe('If all rules match') + expect(any.text()).toBe('If one rule matches') + expect(all.attributes('aria-checked')).toBe('true') + expect(all.attributes('tabindex')).toBe('0') + expect(any.attributes('aria-checked')).toBe('false') + expect(any.attributes('tabindex')).toBe('-1') + expect(wrapper.find('[data-test="include-section"] h3').text()).toBe('Show when ALL of these match') + }) + + it('saves the chosen mode on the placement and tells the dialog', async () => { + api.updateWidgetPlacement.mockResolvedValue({ data: {} }) + const wrapper = await mountEditor() + + await wrapper.find('[data-test="rule-match-all"]').trigger('click') + await flushPromises() + + expect(api.updateWidgetPlacement).toHaveBeenCalledWith(10, { ruleMatch: 'all' }) + expect(wrapper.emitted('ruleMatchChanged')).toEqual([['all']]) + expect(wrapper.find('[data-test="rule-match-all"]').attributes('aria-checked')).toBe('true') + }) + + it('takes the choice back when saving fails, and saves nothing for the chosen card', async () => { + api.updateWidgetPlacement.mockRejectedValue(new Error('403')) + const wrapper = await mountEditor() + + await wrapper.find('[data-test="rule-match-any"]').trigger('click') + expect(api.updateWidgetPlacement).not.toHaveBeenCalled() + + await wrapper.find('[data-test="rule-match-all"]').trigger('click') + await flushPromises() + + expect(wrapper.emitted('ruleMatchChanged')).toBeUndefined() + expect(wrapper.find('[data-test="rule-match-any"]').attributes('aria-checked')).toBe('true') + }) + + it('moves the choice with the arrow keys', async () => { + api.updateWidgetPlacement.mockResolvedValue({ data: {} }) + const wrapper = await mountEditor() + + await wrapper.find('[data-test="rule-match-any"]').trigger('keydown', { key: 'ArrowLeft' }) + await flushPromises() + + expect(api.updateWidgetPlacement).toHaveBeenCalledWith(10, { ruleMatch: 'all' }) + await wrapper.find('[data-test="rule-match-all"]').trigger('keydown', { key: 'Enter' }) + expect(api.updateWidgetPlacement).toHaveBeenCalledTimes(1) + }) +}) + +describe('rule cards', () => { + it('shows each rule with its kind, its value, Edit and Delete', async () => { + const wrapper = await mountEditor() + const cards = wrapper.findAll('[data-test="visibility-rule-card"]') + + expect(cards).toHaveLength(2) + expect(cards[0].find('[data-test="rule-card-kind"]').text()).toBe('Groups') + expect(cards[0].find('[data-test="rule-card-value"]').text()).toBe('KCC') + expect(cards[1].find('[data-test="rule-card-kind"]').text()).toBe('Times') + expect(cards[1].find('[data-test="rule-card-value"]').text()).toBe('Mon–Fri 08:00–17:00') + expect(cards[1].find('[data-test="rule-card-edit"]').text()).toBe('Edit') + expect(cards[1].find('[data-test="rule-card-delete"]').text()).toBe('Delete') + }) + + it('opens and closes a saved rule\'s editor with Edit', async () => { + const wrapper = await mountEditor() + expect(wrapper.find('.rule-row-stub').exists()).toBe(false) + + await wrapper.findAll('[data-test="rule-card-edit"]')[1].trigger('click') + expect(wrapper.find('.rule-row-stub').attributes('data-rule-id')).toBe('2') + + await wrapper.findAll('[data-test="rule-card-edit"]')[1].trigger('click') + expect(wrapper.find('.rule-row-stub').exists()).toBe(false) + }) +}) + +describe('View as', () => { + it('previews as the chosen person at the chosen moment and says why they see the widget', async () => { + api.searchSharees.mockResolvedValue({ data: { users: [{ id: 'sanne', displayName: 'Sanne de Vries' }], groups: [] } }) + api.previewVisibility.mockResolvedValue({ data: { visible: true, matchedIncludeRuleIds: [1, 2], matchedExcludeRuleIds: [] } }) + api.updateWidgetPlacement.mockResolvedValue({ data: {} }) + const wrapper = await mountEditor() + await wrapper.find('[data-test="rule-match-all"]').trigger('click') + + const person = wrapper.findComponent({ name: 'NcSelect' }) + expect(person.props('modelValue')).toEqual({ id: 'admin', displayName: 'Ada Admin' }) + person.vm.$emit('search', 'san') + await flushPromises() + expect(api.searchSharees).toHaveBeenCalledWith('san') + expect(person.props('options').map((o) => o.id)).toEqual(['admin', 'sanne']) + person.vm.$emit('update:modelValue', person.props('options')[1]) + await wrapper.find('[data-test="visibility-preview"] input').setValue('2026-10-13T10:00') + + await wrapper.find('[data-test="run-preview"]').trigger('click') + await flushPromises() + + const body = api.previewVisibility.mock.calls[0][0] + expect(body.context).toEqual({ groups: [], datetime: new Date('2026-10-13T10:00').toISOString(), userId: 'sanne' }) + expect(body.match).toBe('all') + expect(body.placementId).toBe(10) + const sentence = wrapper.find('[data-test="visibility-sentence"]').text() + expect(sentence).toMatch(/^Sanne de Vries sees this widget, because Sanne de Vries is in KCC and .+ 10:00 is within the times\.$/) + }) + + it('says why a person does not see the widget', async () => { + api.previewVisibility.mockResolvedValue({ data: { visible: false, matchedIncludeRuleIds: [1], matchedExcludeRuleIds: [] } }) + api.updateWidgetPlacement.mockResolvedValue({ data: {} }) + const wrapper = await mountEditor({ ruleMatch: 'all' }) + await wrapper.find('[data-test="visibility-preview"] input').setValue('2026-10-17T10:00') + + await wrapper.find('[data-test="run-preview"]').trigger('click') + await flushPromises() + + expect(api.previewVisibility.mock.calls[0][0].context.userId).toBe('admin') + expect(wrapper.find('[data-test="preview-verdict-text"]').text()).toBe('Hidden') + expect(wrapper.find('[data-test="visibility-sentence"]').text()).toMatch( + /^Ada Admin does not see this widget, because .+ 10:00 is outside the times\.$/, + ) + }) +}) diff --git a/src/components/Widgets/__tests__/VisibilityRuleRow.groups.spec.js b/src/components/Widgets/__tests__/VisibilityRuleRow.groups.spec.js new file mode 100644 index 000000000..d109893d4 --- /dev/null +++ b/src/components/Widgets/__tests__/VisibilityRuleRow.groups.spec.js @@ -0,0 +1,76 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The group pickers offer Nextcloud groups, not system tags: `NcSelectTags` + * fetches system tags unless `fetchTags` is off, and labels its options by + * `displayName`, so the offered groups reach it as `{id, displayName}` with + * fetching off (launchpad#97). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ConditionalVisibilityEditor from '../ConditionalVisibilityEditor.vue' +import VisibilityRuleRow from '../VisibilityRuleRow.vue' + +vi.mock('../../../services/api.js', () => ({ + api: { getWidgetRules: vi.fn(async () => ({ data: { rules: [] } })) }, +})) + +const SelectTags = { + name: 'NcSelectTags', + props: ['modelValue', 'options', 'fetchTags'], + template: '<div class="nc-selecttags-stub" />', +} + +const stubs = { + NcButton: { template: '<button><slot /></button>' }, + NcSelect: { template: '<div />' }, + NcSelectTags: SelectTags, + NcTextField: { template: '<input />' }, + NcCheckboxRadioSwitch: { template: '<label><slot /></label>' }, + NcLoadingIcon: { template: '<span />' }, + VisibilityRuleRow: { template: '<div />' }, + Delete: { template: '<span />' }, + Plus: { template: '<span />' }, + Eye: { template: '<span />' }, + EyeOff: { template: '<span />' }, +} + +beforeEach(() => { + globalThis.t = (_app, key) => key +}) + +describe('group pickers', () => { + it('the rule row offers the groups, with tag fetching off, and keeps a chosen group', () => { + const wrapper = mount(VisibilityRuleRow, { + props: { + rule: { ruleType: 'group', ruleConfig: { groups: ['gone'] }, isInclude: true }, + availableGroups: [{ id: 'mkt', displayName: 'Marketing' }, 'sales'], + }, + global: { stubs }, + }) + const picker = wrapper.findComponent(SelectTags) + expect(picker.props('fetchTags')).toBe(false) + expect(picker.props('options')).toEqual([ + { id: 'mkt', displayName: 'Marketing' }, + { id: 'sales', displayName: 'sales' }, + { id: 'gone', displayName: 'gone' }, + ]) + }) + + it('a group rule\'s card shows its groups as chips, by display name', async () => { + const { api } = await import('../../../services/api.js') + api.getWidgetRules.mockResolvedValueOnce({ + data: { rules: [{ id: 1, ruleType: 'group', ruleConfig: { groups: ['kcc', 'gone'] }, isInclude: true }] }, + }) + const wrapper = mount(ConditionalVisibilityEditor, { + props: { placementId: 10, availableGroups: [{ id: 'kcc', displayName: 'KCC' }] }, + global: { stubs }, + }) + await flushPromises() + const chips = wrapper.findAll('[data-test="rule-card-value"] .conditional-visibility-editor__chip') + expect(chips.map((chip) => chip.text())).toEqual(['KCC', 'gone']) + expect(wrapper.find('[data-test="rule-card-kind"]').text()).toBe('Groups') + }) +}) diff --git a/src/components/Widgets/__tests__/VisibilityRuleRow.interactions.spec.js b/src/components/Widgets/__tests__/VisibilityRuleRow.interactions.spec.js new file mode 100644 index 000000000..2000bc62f --- /dev/null +++ b/src/components/Widgets/__tests__/VisibilityRuleRow.interactions.spec.js @@ -0,0 +1,247 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `VisibilityRuleRow.vue` driven through its rendered + * controls (conditional-visibility-editor spec, REQ-CVUI-002): the rule-type + * and operator selects, the groups picker, the time/date/attribute fields, + * the day toggles and the include/exclude radios. Also covers the paths the + * main spec does not reach — an end date, un-toggling a day, clearing the + * operator, inline validation messages and an unknown rule type. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it } from 'vitest' +import VisibilityRuleRow from '../VisibilityRuleRow.vue' + +const stubs = { + NcButton: { + props: ['disabled'], + emits: ['click'], + template: + '<button :disabled="disabled" @click="$emit(\'click\')"><slot name="icon" /><slot /></button>', + }, + NcSelect: { + props: ['modelValue', 'options'], + emits: ['update:modelValue'], + template: `<div class="nc-select-stub" :data-selected="modelValue && modelValue.id"> + <button v-for="o in options" :key="o.id" class="opt" :data-id="o.id" @click="$emit('update:modelValue', o)">{{ o.label }}</button> + <button class="clear" @click="$emit('update:modelValue', null)">clear</button> + </div>`, + }, + NcSelectTags: { + props: ['modelValue', 'options'], + emits: ['update:modelValue'], + template: + '<div class="nc-selecttags-stub"><button v-for="o in options" :key="o.id" class="tag" @click="$emit(\'update:modelValue\', [o.id])">{{ o.displayName }}</button></div>', + }, + NcTextField: { + props: ['modelValue', 'label', 'error', 'helperText'], + emits: ['update:modelValue'], + template: `<div class="nc-textfield-stub" :data-error="String(!!error)"> + <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" /> + <span class="helper">{{ helperText }}</span> + </div>`, + }, + NcCheckboxRadioSwitch: { + props: ['modelValue', 'type', 'name'], + emits: ['update:modelValue'], + template: + '<label><input type="checkbox" :name="name" :checked="modelValue" @change="$emit(\'update:modelValue\', $event.target.checked)" /><slot /></label>', + }, + Delete: { template: '<span class="icon-delete" />' }, +} + +function mountRow(rule, props = {}) { + return mount(VisibilityRuleRow, { + props: { rule, availableGroups: ['marketing', 'sales'], ...props }, + global: { stubs }, + }) +} + +function lastUpdate(wrapper) { + return wrapper.emitted('update:rule').slice(-1)[0][0] +} + +beforeEach(() => { + globalThis.t = (_app, key) => key +}) + +describe('VisibilityRuleRow — rule type select', () => { + it('switches to the date type from the select and emits the new empty shape', async () => { + const wrapper = mountRow({ ruleType: 'group', ruleConfig: { groups: ['sales'] }, isInclude: true }) + await wrapper.find('[data-test="rule-type-select"] .opt[data-id="date"]').trigger('click') + + expect(wrapper.find('[data-test="rule-type-select"]').attributes('data-selected')).toBe('date') + expect(lastUpdate(wrapper)).toEqual({ ruleType: 'date', ruleConfig: {}, isInclude: true }) + expect(wrapper.find('[data-test="rule-start-date"]').exists()).toBe(true) + expect(wrapper.find('[data-test="rule-groups"]').exists()).toBe(false) + }) + + it('ignores re-selecting the current type and a cleared selection', async () => { + const wrapper = mountRow({ ruleType: 'group', ruleConfig: { groups: ['sales'] }, isInclude: true }) + await wrapper.find('[data-test="rule-type-select"] .opt[data-id="group"]').trigger('click') + await wrapper.find('[data-test="rule-type-select"] .clear').trigger('click') + + expect(wrapper.emitted('update:rule')).toBeUndefined() + expect(wrapper.vm.local.ruleConfig).toEqual({ groups: ['sales'] }) + }) +}) + +describe('VisibilityRuleRow — group fields', () => { + it('picking a group updates the config, emits it live and enables Save', async () => { + const wrapper = mountRow({ ruleType: 'group', ruleConfig: { groups: [] }, isInclude: true }, { isNew: true }) + const saveBtn = wrapper.find('[data-test="rule-save"]') + expect(saveBtn.attributes('disabled')).toBeDefined() + expect(saveBtn.text()).toBe('Add rule') + + await wrapper.find('[data-test="rule-groups"] .tag').trigger('click') + + expect(lastUpdate(wrapper).ruleConfig).toEqual({ groups: ['marketing'] }) + expect(saveBtn.attributes('disabled')).toBeUndefined() + await saveBtn.trigger('click') + expect(wrapper.emitted('save')[0][0]).toEqual({ + ruleType: 'group', + ruleConfig: { groups: ['marketing'] }, + isInclude: true, + }) + }) + + it('labels the actions Save / Remove for a persisted rule and disables them while busy', () => { + const wrapper = mountRow({ id: 4, ruleType: 'group', ruleConfig: { groups: ['sales'] }, isInclude: true }, { busy: true }) + expect(wrapper.find('[data-test="rule-save"]').text()).toBe('Save') + expect(wrapper.find('[data-test="rule-remove"]').text()).toBe('Remove') + expect(wrapper.find('[data-test="rule-save"]').attributes('disabled')).toBeDefined() + expect(wrapper.find('[data-test="rule-remove"]').attributes('disabled')).toBeDefined() + expect(wrapper.find('[data-test="rule-mode-include"] input').attributes('name')).toBe('rule-mode-4') + }) +}) + +describe('VisibilityRuleRow — time fields', () => { + it('typing start/end times emits them and flags a malformed time inline', async () => { + const wrapper = mountRow({ ruleType: 'time', ruleConfig: {}, isInclude: true }) + await wrapper.find('[data-test="rule-start-time"] input').setValue('9am') + await wrapper.find('[data-test="rule-end-time"] input').setValue('17:00') + + expect(wrapper.find('[data-test="rule-start-time"]').attributes('data-error')).toBe('true') + expect(wrapper.find('[data-test="rule-start-time"] .helper').text()).toBe('Use HH:MM, e.g. 09:00') + expect(wrapper.find('[data-test="rule-end-time"]').attributes('data-error')).toBe('false') + expect(wrapper.find('[data-test="rule-save"]').attributes('disabled')).toBeDefined() + + await wrapper.find('[data-test="rule-start-time"] input').setValue('09:00') + expect(lastUpdate(wrapper).ruleConfig).toEqual({ startTime: '09:00', endTime: '17:00' }) + expect(wrapper.find('[data-test="rule-save"]').attributes('disabled')).toBeUndefined() + }) + + it('toggling a day on and off again drops it from the emitted days', async () => { + const wrapper = mountRow({ + ruleType: 'time', + ruleConfig: { startTime: '09:00', endTime: '17:00' }, + isInclude: true, + }) + const toggles = wrapper.findAll('[data-test="rule-day-toggle"] input') + expect(toggles).toHaveLength(7) + + await toggles[0].setValue(true) + await toggles[2].setValue(true) + expect(lastUpdate(wrapper).ruleConfig.days).toEqual(['mon', 'wed']) + expect(toggles[0].element.checked).toBe(true) + + await toggles[0].setValue(false) + expect(lastUpdate(wrapper).ruleConfig.days).toEqual(['wed']) + + await toggles[2].setValue(false) + expect('days' in lastUpdate(wrapper).ruleConfig).toBe(false) + }) +}) + +describe('VisibilityRuleRow — date fields', () => { + it('emits both bounds when start and end dates are entered', async () => { + const wrapper = mountRow({ ruleType: 'date', ruleConfig: {}, isInclude: true }) + await wrapper.find('[data-test="rule-start-date"] input').setValue('2026-12-01') + await wrapper.find('[data-test="rule-end-date"] input').setValue('2026-12-31') + + expect(lastUpdate(wrapper).ruleConfig).toEqual({ startDate: '2026-12-01', endDate: '2026-12-31' }) + await wrapper.find('[data-test="rule-save"]').trigger('click') + expect(wrapper.emitted('save')[0][0].ruleConfig).toEqual({ + startDate: '2026-12-01', + endDate: '2026-12-31', + }) + }) + + it('emits an end-only range and blocks Save on a malformed end date', async () => { + const wrapper = mountRow({ ruleType: 'date', ruleConfig: {}, isInclude: true }) + await wrapper.find('[data-test="rule-end-date"] input').setValue('2026-12-31') + expect(lastUpdate(wrapper).ruleConfig).toEqual({ endDate: '2026-12-31' }) + expect(wrapper.vm.isValid).toBe(true) + + await wrapper.find('[data-test="rule-end-date"] input').setValue('31/12/2026') + expect(wrapper.find('[data-test="rule-end-date"] .helper').text()).toBe('Use YYYY-MM-DD') + expect(wrapper.vm.isValid).toBe(false) + await wrapper.find('[data-test="rule-save"]').trigger('click') + expect(wrapper.emitted('save')).toBeUndefined() + }) + + it('is invalid with neither bound set', () => { + const wrapper = mountRow({ ruleType: 'date', ruleConfig: {}, isInclude: true }) + expect(wrapper.vm.isValid).toBe(false) + }) +}) + +describe('VisibilityRuleRow — attribute fields', () => { + it('typing attribute and value and choosing an operator emits the full config', async () => { + const wrapper = mountRow({ ruleType: 'attribute', ruleConfig: {}, isInclude: true }) + await wrapper.find('[data-test="rule-attribute"] input').setValue('language') + await wrapper.find('[data-test="rule-value"] input').setValue('nl') + await wrapper.find('[data-test="rule-operator"] .opt[data-id="starts_with"]').trigger('click') + + expect(wrapper.find('[data-test="rule-operator"]').attributes('data-selected')).toBe('starts_with') + expect(lastUpdate(wrapper).ruleConfig).toEqual({ + attribute: 'language', + operator: 'starts_with', + value: 'nl', + }) + }) + + it('falls back to equals when the operator selection is cleared', async () => { + const wrapper = mountRow({ + ruleType: 'attribute', + ruleConfig: { attribute: 'dept', operator: 'contains', value: 'IT' }, + isInclude: true, + }) + expect(wrapper.find('[data-test="rule-operator"]').attributes('data-selected')).toBe('contains') + + await wrapper.find('[data-test="rule-operator"] .clear').trigger('click') + + expect(wrapper.vm.local.ruleConfig.operator).toBe('equals') + expect(lastUpdate(wrapper).ruleConfig).toEqual({ attribute: 'dept', operator: 'equals', value: 'IT' }) + }) +}) + +describe('VisibilityRuleRow — include/exclude radios', () => { + it('emits isInclude false then true from the exclude and include radios', async () => { + const wrapper = mountRow({ ruleType: 'group', ruleConfig: { groups: ['sales'] }, isInclude: true }) + await wrapper.find('[data-test="rule-mode-exclude"] input').setValue(true) + expect(lastUpdate(wrapper).isInclude).toBe(false) + expect(wrapper.find('[data-test="rule-mode-exclude"] input').element.checked).toBe(true) + + await wrapper.find('[data-test="rule-mode-include"] input').setValue(true) + expect(lastUpdate(wrapper).isInclude).toBe(true) + expect(wrapper.emitted('update:rule')).toHaveLength(2) + }) +}) + +describe('VisibilityRuleRow — unknown rule type', () => { + it('keeps the given config, is never valid and emits an empty ruleConfig', async () => { + const wrapper = mountRow({ ruleType: 'weather', ruleConfig: { sunny: true }, isInclude: false }) + + expect(wrapper.vm.local.ruleConfig).toEqual({ sunny: true }) + expect(wrapper.vm.isValid).toBe(false) + expect(wrapper.find('[data-test="rule-type-select"]').attributes('data-selected')).toBe('group') + + await wrapper.find('[data-test="rule-mode-include"] input').setValue(true) + expect(lastUpdate(wrapper)).toEqual({ ruleType: 'weather', ruleConfig: {}, isInclude: true }) + await wrapper.find('[data-test="rule-save"]').trigger('click') + expect(wrapper.emitted('save')).toBeUndefined() + }) +}) diff --git a/src/components/Widgets/__tests__/WidgetContextMenu.spec.js b/src/components/Widgets/__tests__/WidgetContextMenu.spec.js index 4a92b2ca9..8f8b6c4cc 100644 --- a/src/components/Widgets/__tests__/WidgetContextMenu.spec.js +++ b/src/components/Widgets/__tests__/WidgetContextMenu.spec.js @@ -34,7 +34,25 @@ function mountMenu(props = {}) { } describe('WidgetContextMenu', () => { - it('REQ-WDG-015: renders six items — Edit, Move, Visibility rules…, Read confirmation…, Remove, Cancel', () => { + it('REQ-WDG-017: moves itself up and left when its rendered box would pass the viewport edge', async () => { + const height = window.innerHeight + const width = window.innerWidth + const wrapper = mountMenu({ top: height - 20, left: width - 10 }) + wrapper.element.getBoundingClientRect = () => ({ width: 170, height: 277 }) + await wrapper.vm.fitToViewport() + expect(wrapper.element.style.top).toBe(`${height - 277}px`) + expect(wrapper.element.style.left).toBe(`${width - 170}px`) + }) + + it('REQ-WDG-017: stays at the given position when it fits', async () => { + const wrapper = mountMenu({ top: 100, left: 200 }) + wrapper.element.getBoundingClientRect = () => ({ width: 170, height: 277 }) + await wrapper.vm.fitToViewport() + expect(wrapper.element.style.top).toBe('100px') + expect(wrapper.element.style.left).toBe('200px') + }) + + it('REQ-WDG-015: renders six items — Edit, Move, Who sees this widget?, Read confirmation…, Remove, Cancel', () => { const wrapper = mountMenu() const buttons = wrapper.findAll('.widget-context-menu__item') expect(buttons.length).toBe(6) @@ -42,13 +60,19 @@ describe('WidgetContextMenu', () => { expect(labels).toEqual([ 'Edit', 'Move', - 'Visibility rules…', + 'Who sees this widget?', 'Read confirmation…', 'Remove', 'Cancel', ]) }) + it('REQ-PERM-002: offers no Remove when the widget may not be removed', () => { + const wrapper = mountMenu({ removeLocked: true }) + expect(wrapper.find('[data-testid="ctx-remove"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="ctx-edit"]').exists()).toBe(true) + }) + it('REQ-ACK-007: Read confirmation emits readConfirmation then close', async () => { const wrapper = mountMenu() await wrapper.find('[data-testid="ctx-read-confirmation"]').trigger('click') @@ -90,7 +114,7 @@ describe('WidgetContextMenu', () => { expect(wrapper.emitted('close')).toHaveLength(1) }) - it('conditional-visibility: clicking Visibility rules… emits visibility-rules then close', async () => { + it('conditional-visibility: clicking Who sees this widget? emits visibility-rules then close', async () => { const wrapper = mountMenu() const btn = wrapper.find('[data-testid="ctx-visibility-rules"]') await btn.trigger('click') diff --git a/src/components/Widgets/__tests__/WidgetEditMenu.spec.js b/src/components/Widgets/__tests__/WidgetEditMenu.spec.js new file mode 100644 index 000000000..15ec37ab9 --- /dev/null +++ b/src/components/Widgets/__tests__/WidgetEditMenu.spec.js @@ -0,0 +1,59 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The widget's three-dot menu in edit mode holds "Who sees this widget?", + * so the rules dialog is reachable by keyboard and not only by right-click + * (conditional-visibility-editor REQ-CVUI-007, scenario "From the menu"). + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-dialog-is-in-the-widgets-menu-req-cvui-007 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import WidgetEditMenu from '../WidgetEditMenu.vue' + +vi.mock('@conduction/nextcloud-vue', () => ({ + NcActions: { name: 'NcActions', props: ['ariaLabel'], template: '<div class="actions" role="menu"><slot name="icon" /><slot /></div>' }, + NcActionButton: { + name: 'NcActionButton', + emits: ['click'], + template: '<button role="menuitem" @click="$emit(\'click\')"><slot /></button>', + }, +})) + +/** + * The menu, with Delete offered unless told otherwise. + * + * @param {object} props Prop overrides. + * @return {object} the wrapper. + */ +function mountMenu(props = {}) { + return mount(WidgetEditMenu, { + props: { menuLabel: 'Widget menu', ...props }, + global: { stubs: { DotsVertical: true, Pencil: true, Delete: true, AccountEye: true } }, + }) +} + +describe('WidgetEditMenu', () => { + it('offers Edit widget, Who sees this widget? and Delete widget, in that order', () => { + const items = mountMenu().findAll('[role="menuitem"]').map((item) => item.text()) + expect(items).toEqual(['Edit widget', 'Who sees this widget?', 'Delete widget']) + }) + + it('choosing Who sees this widget? asks for the dialog', async () => { + const wrapper = mountMenu() + await wrapper.find('[data-testid="widget-who-sees"]').trigger('click') + expect(wrapper.emitted('whoSees')).toHaveLength(1) + expect(wrapper.emitted('edit')).toBeUndefined() + }) + + it('passes Edit and Delete on, and leaves Delete out when removal is locked', async () => { + const wrapper = mountMenu() + await wrapper.find('[data-testid="cn-widget-edit-cog-edit"]').trigger('click') + await wrapper.find('[data-testid="cn-widget-edit-cog-delete"]').trigger('click') + expect(wrapper.emitted('edit')).toHaveLength(1) + expect(wrapper.emitted('remove')).toHaveLength(1) + expect(mountMenu({ removeLocked: true }).find('[data-testid="cn-widget-edit-cog-delete"]').exists()).toBe(false) + }) +}) diff --git a/src/components/Widgets/__tests__/WidgetRowFilter.spec.js b/src/components/Widgets/__tests__/WidgetRowFilter.spec.js new file mode 100644 index 000000000..abf858bfd --- /dev/null +++ b/src/components/Widgets/__tests__/WidgetRowFilter.spec.js @@ -0,0 +1,111 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * In-widget search (REQ-DWMS-008): the filter narrows the rendered rows, lives + * in view state only, is gone after a reload, and never touches the widget's + * stored definition. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), + translatePlural: (_app, one, many, count) => + (count === 1 ? one : many).replace('%n', String(count)), +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const loadAttentionFeed = vi.fn() +vi.mock('../../../services/attentionFeed.js', () => ({ + loadAttentionFeed: (...args) => loadAttentionFeed(...args), +})) + +import AttentionWidget from '../Renderers/AttentionWidget.vue' +import WidgetRowFilter from '../WidgetRowFilter.vue' + +function item(appId, title) { + return { + key: `${appId}/x`, + id: 'x', + appId, + appName: appId, + title, + severity: 'warning', + count: 1, + reason: '1 thing needs you.', + actionLabel: 'Open', + href: `/apps/${appId}`, + } +} + +const FEED = { + items: [item('dossiq', 'Open zaken'), item('pipelinq', 'Leads'), item('decidiq', 'Open besluiten')], + failedApps: [], + sourceCount: 3, +} + +async function mountWidget(content) { + loadAttentionFeed.mockResolvedValue(structuredClone(FEED)) + const wrapper = mount(AttentionWidget, { props: { content } }) + await flushPromises() + return wrapper +} + +function titles(wrapper) { + // The title starts with a screen-reader severity label; read past it. + return wrapper.findAll('.attention-widget__title').map((t) => t.text().replace(t.find('.attention-widget__sr').text(), '').trim()) +} + +beforeEach(() => { + loadAttentionFeed.mockReset() +}) + +describe('WidgetRowFilter', () => { + it('emits what is typed, and Escape empties it', async () => { + const wrapper = mount(WidgetRowFilter, { props: { modelValue: '' } }) + const input = wrapper.find('input') + expect(input.attributes('aria-label')).toBe('Filter these results') + + await input.setValue('zaak') + await input.trigger('keydown', { key: 'Escape' }) + + expect(wrapper.emitted('update:modelValue')).toEqual([['zaak'], ['']]) + }) +}) + +describe('in-widget search on a widget that renders rows', () => { + it('filters the rows before a reload and shows them all after it, leaving the definition alone', async () => { + const content = Object.freeze({ limit: 5 }) + const before = JSON.stringify(content) + + const first = await mountWidget(content) + expect(titles(first)).toEqual(['Open zaken', 'Leads', 'Open besluiten']) + + await first.find('[data-testid="widget-row-filter"]').setValue('open') + expect(titles(first)).toEqual(['Open zaken', 'Open besluiten']) + expect(first.emitted()).not.toHaveProperty('update:content') + first.unmount() + + // A reload is a fresh mount: the term was never stored anywhere. + const reloaded = await mountWidget(content) + expect(reloaded.find('[data-testid="widget-row-filter"]').element.value).toBe('') + expect(titles(reloaded)).toEqual(['Open zaken', 'Leads', 'Open besluiten']) + expect(JSON.stringify(content)).toBe(before) + expect(loadAttentionFeed).toHaveBeenCalledTimes(2) + for (const call of loadAttentionFeed.mock.calls) { + expect(call).toEqual([{ perSource: 1 }]) + } + }) + + it('counts the hidden remainder over the filtered rows', async () => { + const wrapper = await mountWidget({ limit: 1 }) + expect(wrapper.find('[data-testid="attention-more"]').text()).toBe('And 2 more.') + + await wrapper.find('[data-testid="widget-row-filter"]').setValue('open') + expect(titles(wrapper)).toEqual(['Open zaken']) + expect(wrapper.find('[data-testid="attention-more"]').text()).toBe('And 1 more.') + }) +}) diff --git a/src/components/Widgets/__tests__/ruleSave.golden.spec.js b/src/components/Widgets/__tests__/ruleSave.golden.spec.js new file mode 100644 index 000000000..4f6efcb58 --- /dev/null +++ b/src/components/Widgets/__tests__/ruleSave.golden.spec.js @@ -0,0 +1,206 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Characterisation tests pinning `ConditionalVisibilityEditor.onRowSave` + * (update, create, reload fallback, error path, busy flag) and + * `VisibilityRuleRow.buildRuleConfig` for every rule type, so both can be + * split into named steps without changing behaviour. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ConditionalVisibilityEditor from '../ConditionalVisibilityEditor.vue' +import VisibilityRuleRow from '../VisibilityRuleRow.vue' +import { api } from '../../../services/api.js' +import { logger } from '../../../utils/logger.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (p) => `/index.php${p}`, +})) +vi.mock('../../../services/api.js', () => ({ + api: { + getWidgetRules: vi.fn(), + addWidgetRule: vi.fn(), + updateRule: vi.fn(), + deleteRule: vi.fn(), + previewVisibility: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ + logger: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() }, +})) + +async function flush() { + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +async function mountEditor() { + api.getWidgetRules.mockResolvedValue({ data: { rules: [] } }) + const wrapper = mount(ConditionalVisibilityEditor, { + propsData: { placementId: 10 }, + shallow: true, + }) + await flush() + return wrapper +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + vi.clearAllMocks() +}) + +describe('ConditionalVisibilityEditor.onRowSave', () => { + it('merges an unwrapped update into the row and emits ruleUpdated', async () => { + const wrapper = await mountEditor() + const row = { id: 5, ruleType: 'group', ruleConfig: {}, isInclude: true } + wrapper.vm.rules.push(row) + api.updateRule.mockResolvedValue({ data: { data: { isInclude: false } } }) + + await wrapper.vm.onRowSave(wrapper.vm.rules[0], { isInclude: false }) + + expect(api.updateRule).toHaveBeenCalledWith(5, { isInclude: false }) + expect(wrapper.vm.rules[0]).toMatchObject({ id: 5, ruleType: 'group', isInclude: false }) + expect(wrapper.emitted('ruleUpdated')).toHaveLength(1) + expect(wrapper.emitted('ruleAdded')).toBeFalsy() + }) + + it('emits ruleUpdated even when the row left the list', async () => { + const wrapper = await mountEditor() + api.updateRule.mockResolvedValue({ data: null }) + await wrapper.vm.onRowSave({ id: 0 }, {}) + expect(api.updateRule).toHaveBeenCalledWith(0, {}) + expect(wrapper.vm.rules).toEqual([]) + expect(wrapper.emitted('ruleUpdated')).toHaveLength(1) + }) + + it('replaces a draft with the created rule and clears its local key', async () => { + const wrapper = await mountEditor() + wrapper.vm.rules.push({ id: null, _localKey: 'k1', ruleType: 'group' }) + api.addWidgetRule.mockResolvedValue({ data: { data: { id: 77, ruleType: 'group' } } }) + + await wrapper.vm.onRowSave(wrapper.vm.rules[0], { ruleType: 'group' }) + + expect(api.addWidgetRule).toHaveBeenCalledWith(10, { ruleType: 'group' }) + expect(wrapper.vm.rules[0]).toEqual({ id: 77, ruleType: 'group', _localKey: undefined }) + expect(wrapper.emitted('ruleAdded')).toHaveLength(1) + }) + + it('reloads when the created rule has no id', async () => { + const wrapper = await mountEditor() + wrapper.vm.rules.push({ _localKey: 'k1' }) + api.addWidgetRule.mockResolvedValue({ data: { ruleType: 'group' } }) + api.getWidgetRules.mockClear() + + await wrapper.vm.onRowSave(wrapper.vm.rules[0], {}) + + expect(api.getWidgetRules).toHaveBeenCalledTimes(1) + expect(wrapper.emitted('ruleAdded')).toHaveLength(1) + }) + + it('logs a failed save, emits nothing and clears the busy flag', async () => { + const wrapper = await mountEditor() + const error = new Error('nope') + api.addWidgetRule.mockRejectedValue(error) + const row = { id: undefined, _localKey: 'k2' } + const busy = vi.spyOn(wrapper.vm, 'setRowBusy') + + await wrapper.vm.onRowSave(row, {}) + + expect(logger.error).toHaveBeenCalledWith('Failed to save visibility rule:', error) + expect(wrapper.emitted('ruleAdded')).toBeFalsy() + expect(busy.mock.calls).toEqual([[row, true], [row, false]]) + }) +}) + +function ruleConfigFor(ruleType, ruleConfig) { + const wrapper = mount(VisibilityRuleRow, { + propsData: { rule: { ruleType: 'group', ruleConfig: { groups: [] }, isInclude: true }, availableGroups: [] }, + shallow: true, + }) + wrapper.vm.local.ruleType = ruleType + wrapper.vm.local.ruleConfig = ruleConfig + return wrapper.vm.buildRuleConfig() +} + +describe('VisibilityRuleRow.buildRuleConfig', () => { + it.each([ + ['group', { groups: ['a'], extra: 1 }, { groups: ['a'] }], + ['group', {}, { groups: [] }], + ['time', { startTime: '08:00', endTime: '09:00', days: [] }, { startTime: '08:00', endTime: '09:00' }], + ['time', { startTime: '08:00', days: 'mon' }, { startTime: '08:00', endTime: undefined }], + ['time', { days: ['mon'] }, { startTime: undefined, endTime: undefined, days: ['mon'] }], + ['date', {}, {}], + ['date', { startDate: '', endDate: '2026-01-02' }, { endDate: '2026-01-02' }], + ['date', { startDate: '2026-01-01', endDate: '2026-01-02' }, { startDate: '2026-01-01', endDate: '2026-01-02' }], + ['attribute', { attribute: 'dept', value: 'x' }, { attribute: 'dept', operator: 'equals', value: 'x' }], + ['attribute', { attribute: 'dept', operator: 'contains', value: 'x' }, { attribute: 'dept', operator: 'contains', value: 'x' }], + ['unknown', { groups: ['a'] }, {}], + ['constructor', {}, {}], + ])('builds the %s config', (ruleType, ruleConfig, expected) => { + expect(ruleConfigFor(ruleType, ruleConfig)).toEqual(expected) + }) + + it('copies the groups and days arrays', () => { + const groups = ['a'] + const days = ['mon'] + expect(ruleConfigFor('group', { groups }).groups).not.toBe(groups) + expect(ruleConfigFor('time', { days }).days).not.toBe(days) + }) +}) + +describe('ConditionalVisibilityEditor.load response shapes', () => { + it.each([ + [{ rules: [{ id: 1, x: 1 }] }, [{ id: 1, x: 1, _localKey: undefined }]], + [{ data: { rules: [{ id: 2 }] } }, [{ id: 2, _localKey: undefined }]], + [{ data: { other: 1 } }, []], + [[{ id: 3 }], [{ id: 3, _localKey: undefined }]], + [null, []], + [{ rules: 'x' }, []], + ])('reads %j', async (data, expected) => { + api.getWidgetRules.mockResolvedValue({ data }) + const wrapper = mount(ConditionalVisibilityEditor, { propsData: { placementId: 10 }, shallow: true }) + await flush() + expect(wrapper.vm.rules).toEqual(expected) + expect(wrapper.vm.loading).toBe(false) + }) + + it('logs a failed load and empties the list; skips the call without a placement', async () => { + const error = new Error('x') + api.getWidgetRules.mockRejectedValue(error) + const wrapper = mount(ConditionalVisibilityEditor, { propsData: { placementId: 10 }, shallow: true }) + await flush() + expect(logger.error).toHaveBeenCalledWith('Failed to load visibility rules:', error) + expect(wrapper.vm.rules).toEqual([]) + api.getWidgetRules.mockClear() + await wrapper.setProps({ placementId: null }) + wrapper.vm.rules = [{ id: 1 }] + await wrapper.vm.load() + expect(api.getWidgetRules).not.toHaveBeenCalled() + expect(wrapper.vm.rules).toEqual([]) + }) +}) + +describe('VisibilityRuleRow.hasAtLeastOneValidDate', () => { + it.each([ + [{}, false], + [{ startDate: '', endDate: '' }, false], + [{ startDate: '2026-01-01' }, true], + [{ endDate: '2026-01-01' }, true], + [{ startDate: '2026-1-1' }, false], + [{ startDate: '2026-01-01', endDate: 'x' }, false], + [{ startDate: 'x', endDate: '2026-01-01' }, false], + [{ startDate: 5 }, false], + ])('judges %j', (ruleConfig, expected) => { + const wrapper = mount(VisibilityRuleRow, { + propsData: { rule: { ruleType: 'date', ruleConfig: {}, isInclude: true }, availableGroups: [] }, + shallow: true, + }) + wrapper.vm.local.ruleConfig = ruleConfig + expect(wrapper.vm.hasAtLeastOneValidDate()).toBe(expected) + }) +}) diff --git a/src/components/Workspace/ActiveFiltersPanel.vue b/src/components/Workspace/ActiveFiltersPanel.vue new file mode 100644 index 000000000..139730be3 --- /dev/null +++ b/src/components/Workspace/ActiveFiltersPanel.vue @@ -0,0 +1,203 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <section + v-if="clauses.length > 0" + class="active-filters" + :aria-label="t('launchpad', 'Active filters')" + data-testid="active-filters"> + <span class="active-filters__heading">{{ t('launchpad', 'Active filters') }}</span> + <ul class="active-filters__list"> + <li + v-for="clause in clauses" + :key="clause.dimension" + class="active-filters__chip" + :class="{ 'active-filters__chip--pinned': clause.pinned }" + :data-dimension="clause.dimension"> + <Lock + v-if="clause.pinned" + :size="16" + class="active-filters__lock" + :title="t('launchpad', 'Pinned filter')" + data-testid="active-filter-lock" /> + <span class="active-filters__label">{{ labelOf(clause) }}:</span> + <span class="active-filters__value">{{ valueOf(clause) }}</span> + <span + v-if="sourceName(clause)" + class="active-filters__source" + data-testid="active-filter-source">({{ sourceName(clause) }})</span> + <button + v-if="!clause.pinned" + type="button" + class="active-filters__remove" + :aria-label="t('launchpad', 'Remove filter: {label}', { label: labelOf(clause) })" + data-testid="active-filter-remove" + @click="$emit('remove', clause.dimension)"> + <Close :size="16" /> + </button> + </li> + </ul> + <NcButton + v-if="hasRemovable" + variant="tertiary" + data-testid="reset-filters" + @click="$emit('reset')"> + <template #icon> + <FilterRemove :size="20" /> + </template> + {{ t('launchpad', 'Reset filters') }} + </NcButton> + </section> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' +import Close from 'vue-material-design-icons/Close.vue' +import FilterRemove from 'vue-material-design-icons/FilterRemove.vue' +import Lock from 'vue-material-design-icons/Lock.vue' +import { LIST_PROP, OBJECT_PROP } from '../../constants/propDefinitions.js' + +/** + * ActiveFiltersPanel: the clauses of the dashboard's filter bus as chips + * (drill-down-cross-widget-filter REQ-CWF-007), with "Reset filters" + * (REQ-CWF-006). A clause a widget click made names that widget; a pinned + * clause shows a lock and cannot be removed. The panel is absent while the + * bus is empty, and "Reset filters" only shows when there is something it + * would clear, so pressing it is never a no-op. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-007-filter-stack-ui-shows-every-active-clause-with-its-source + */ +export default { + name: 'ActiveFiltersPanel', + + components: { NcButton, Close, FilterRemove, Lock }, + + props: { + /** The bus's clauses (`dimension`, `operator`, `value`, `source`, `sourceWidgetId`, `pinned`). */ + clauses: LIST_PROP, + /** A display label per dimension; the dimension itself when absent. */ + labels: OBJECT_PROP, + /** A display name per widget id, for clauses a widget click made. */ + widgetNames: OBJECT_PROP, + }, + + emits: ['remove', 'reset'], + + computed: { + /** + * Whether any clause is not pinned, so a reset would clear something. + * + * @return {boolean} + */ + hasRemovable() { + return this.clauses.some((clause) => !clause.pinned) + }, + }, + + methods: { + t, + + /** + * The clause's dimension label. + * + * @param {object} clause The clause. + * @return {string} + */ + labelOf(clause) { + return this.labels[clause.dimension] || clause.dimension + }, + + /** + * The clause's value as text: a list joined, a range with a dash. + * + * @param {object} clause The clause. + * @return {string} + */ + valueOf(clause) { + if (Array.isArray(clause.value)) { + return clause.value.join(clause.operator === 'between' ? ' – ' : ', ') + } + return clause.value === undefined || clause.value === null ? '' : String(clause.value) + }, + + /** + * The widget a widget-click clause came from, or '' for any other source. + * + * @param {object} clause The clause. + * @return {string} + */ + sourceName(clause) { + if (clause.source !== 'widgetClick' || !clause.sourceWidgetId) { + return '' + } + return this.widgetNames[clause.sourceWidgetId] || '' + }, + }, +} +</script> + +<style scoped> +.active-filters { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin: 0 0 8px; +} + +.active-filters__heading { + font-weight: bold; + color: var(--color-main-text); +} + +.active-filters__list { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} + +.active-filters__chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 4px 2px 10px; + border-radius: var(--border-radius-pill); + background-color: var(--color-primary-element-light); + color: var(--color-primary-element-light-text); +} + +.active-filters__chip--pinned { + padding-inline-end: 10px; +} + +.active-filters__source { + color: var(--color-text-maxcontrast); +} + +.active-filters__remove { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 24px; + min-height: 24px; + margin: 0; + padding: 0; + border: none; + border-radius: 50%; + background: transparent; + color: inherit; + cursor: pointer; +} + +.active-filters__remove:hover, +.active-filters__remove:focus-visible { + background-color: var(--color-background-hover); +} +</style> diff --git a/src/components/Workspace/CoEditorsBanner.vue b/src/components/Workspace/CoEditorsBanner.vue new file mode 100644 index 000000000..73ced08bf --- /dev/null +++ b/src/components/Workspace/CoEditorsBanner.vue @@ -0,0 +1,143 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div + v-if="editors.length > 0" + class="launchpad-co-editors" + role="status" + data-testid="co-editors-banner"> + <NcNoteCard type="info"> + <p>{{ message }}</p> + <div class="launchpad-co-editors__who"> + <span class="launchpad-co-editors__label">{{ t('launchpad', 'Who else is editing?') }}</span> + <ul class="launchpad-co-editors__list"> + <li + v-for="(editor, index) in editors" + :key="index" + class="launchpad-co-editors__initials" + :title="editor.displayName" + :aria-label="editor.displayName" + data-testid="co-editor"> + {{ initialsOf(editor.displayName) }} + </li> + </ul> + </div> + </NcNoteCard> + </div> +</template> + +<script> +import { NcNoteCard } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { LIST_PROP } from '../../constants/propDefinitions.js' + +/** + * The initials of a display name: the first letter of its first and last + * word, upper-cased; one letter for a one-word name. + * + * @param {string} name The display name. + * @return {string} + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ +export function initialsOf(name) { + const words = String(name ?? '').trim().split(/\s+/).filter(Boolean) + if (words.length === 0) { + return '?' + } + const first = words[0].charAt(0) + const last = words.length > 1 ? words[words.length - 1].charAt(0) : '' + return (first + last).toUpperCase() +} + +/** + * The clock time of an ISO date-time in the browser's own zone, as HH:MM. + * + * @param {string} since The ISO date-time. + * @return {string} The time, or the input when it cannot be read. + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ +export function clockTime(since) { + const date = new Date(since) + if (Number.isNaN(date.getTime())) { + return String(since ?? '') + } + return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) +} + +/** + * CoEditorsBanner: in edit mode, who else edits this dashboard and since + * when, with their initials (building-edit-a-dashboard-together, LpBewerken). + * + * @spec openspec/specs/dashboard-co-editing/spec.md + */ +export default { + name: 'CoEditorsBanner', + + components: { + NcNoteCard, + }, + + props: { + /** The colleagues editing, `{displayName, since}`, longest first. */ + editors: LIST_PROP, + }, + + computed: { + /** + * @return {string} The line about the colleague editing longest. + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ + message() { + const first = this.editors[0] ?? {} + return t( + 'launchpad', + '{name} is also editing this dashboard, since {time}. Your changes are not overwritten.', + { name: first.displayName ?? '', time: clockTime(first.since) }, + ) + }, + }, + + methods: { + t, + initialsOf, + }, +} +</script> + +<style scoped> +.launchpad-co-editors { + margin: 0 8px 8px; +} + +.launchpad-co-editors__who { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.launchpad-co-editors__list { + display: flex; + gap: 4px; + margin: 0; + padding: 0; + list-style: none; +} + +.launchpad-co-editors__initials { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 28px; + height: 28px; + padding: 0 4px; + border-radius: var(--border-radius-pill); + background-color: var(--color-primary-element); + color: var(--color-primary-element-text); + font-size: var(--font-size-small, 12px); + font-weight: bold; +} +</style> diff --git a/src/components/Workspace/DashboardBreadcrumb.vue b/src/components/Workspace/DashboardBreadcrumb.vue index 9b765f15c..04bffaf3c 100644 --- a/src/components/Workspace/DashboardBreadcrumb.vue +++ b/src/components/Workspace/DashboardBreadcrumb.vue @@ -41,6 +41,7 @@ <script> import { t } from '@nextcloud/l10n' +import { NULLABLE_OBJECT_PROP } from '../../constants/propDefinitions.js' import { api } from '../../services/api.js' import { logger } from '../../utils/logger.js' @@ -56,10 +57,7 @@ export default { props: { /** The active dashboard (`id`, `uuid`, `parentUuid`). */ - dashboard: { - type: Object, - default: null, - }, + dashboard: NULLABLE_OBJECT_PROP, }, emits: ['navigate'], diff --git a/src/components/Workspace/DashboardDiscussion.vue b/src/components/Workspace/DashboardDiscussion.vue new file mode 100644 index 000000000..30c0d9690 --- /dev/null +++ b/src/components/Workspace/DashboardDiscussion.vue @@ -0,0 +1,155 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <section + v-if="shown" + class="dashboard-discussion" + :aria-label="t('launchpad', 'Discussion')" + data-testid="dashboard-discussion"> + <h3 class="dashboard-discussion__title"> + {{ t('launchpad', 'Discussion') }} + </h3> + <CnIntegrationTab + integrationId="talk" + register="launchpad" + schema="dashboard" + :objectId="dashboard.uuid" + :emptyLabel="t('launchpad', 'No conversation linked to this dashboard yet')" /> + </section> +</template> + +<script> +import { CnIntegrationTab } from '@conduction/nextcloud-vue' +import { translate as t } from '@nextcloud/l10n' +import { NULLABLE_OBJECT_PROP } from '../../constants/propDefinitions.js' +import { api } from '../../services/api.js' +import { conversationEnabled, discussionAvailable, isCollaborative } from '../../utils/dashboardDiscussion.js' + +/** + * The Talk discussion of a shared or group dashboard + * (openregister-leaf-integrations, REQ-LEAF-002, -003, -004). + * + * Access chain: the leaf reads `/apps/openregister/api/objects/launchpad/ + * dashboard/{uuid}/integrations/talk`, which resolves the dashboard's + * discussion object under OpenRegister's read rule. LaunchPad writes that + * object (`DashboardDiscussionMirror`) with the dashboard's audience as + * `PermissionService::canViewDashboard()` derives it (owner, user and group + * shares, the group of a group dashboard), and rewrites it on every share + * change, so a revoked user is refused by OpenRegister and not only hidden + * here. Nothing renders, and nothing is requested, on an unshared personal + * dashboard or without OpenRegister and Talk. + */ +export default { + name: 'DashboardDiscussion', + + components: { CnIntegrationTab }, + + props: { + /** The open dashboard. */ + dashboard: NULLABLE_OBJECT_PROP, + + /** The dashboards shared with this user. */ + sharedWithMe: { + type: Array, + default: () => [], + }, + + /** This user's id, to tell whether they own the dashboard. */ + currentUserId: { + type: String, + default: '', + }, + }, + + data() { + return { + ownShares: [], + } + }, + + computed: { + /** + * Whether the discussion shows: a collaborative dashboard with OpenRegister and Talk installed. + * + * @return {boolean} + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-5 + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ + shown() { + return discussionAvailable() + && conversationEnabled(this.dashboard) + && isCollaborative({ dashboard: this.dashboard, sharedWithMe: this.sharedWithMe, ownShares: this.ownShares }) + }, + + /** + * Whether this user owns a personal dashboard, whose shares only they may list. + * + * @return {boolean} + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-4 + */ + ownsPersonal() { + const dashboard = this.dashboard + return Boolean(dashboard?.id) && dashboard.type === 'user' && this.currentUserId !== '' && dashboard.userId === this.currentUserId + }, + }, + + watch: { + 'dashboard.id': { + immediate: true, + /** + * Read the owner's shares of the open dashboard. + * + * @return {void} + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-4 + */ + handler() { + this.loadOwnShares() + }, + }, + }, + + methods: { + t, + + /** + * Read the shares of a dashboard this user owns; any failure reads as none. + * + * @return {Promise<void>} + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-4 + */ + async loadOwnShares() { + this.ownShares = [] + if (!this.ownsPersonal || !discussionAvailable()) { + return + } + const id = this.dashboard.id + try { + const response = await api.listShares(id) + if (this.dashboard?.id === id) { + this.ownShares = Array.isArray(response?.data) ? response.data : [] + } + } catch { + this.ownShares = [] + } + }, + }, +} +</script> + +<style scoped> +.dashboard-discussion { + margin: 8px 0; + padding: 8px 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); + background: var(--color-main-background); +} + +.dashboard-discussion__title { + margin: 0 0 4px; + font-size: 1em; +} +</style> diff --git a/src/components/Workspace/DashboardEditBar.vue b/src/components/Workspace/DashboardEditBar.vue new file mode 100644 index 000000000..bb01139e2 --- /dev/null +++ b/src/components/Workspace/DashboardEditBar.vue @@ -0,0 +1,260 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 + - + - DashboardEditBar: the bar over a dashboard in edit mode (board + - LpBewerken). It names the dashboard being edited and holds the edit + - actions: Columns 6, 8 or 12, Add widget, Dashboard settings and Done. + - Its last element is where the page's More menu docks while the bar is + - shown (`dock`), so the floating menu never covers Done. +--> +<template> + <div + class="launchpad-edit-bar" + role="toolbar" + :aria-label="t('launchpad', 'Edit dashboard')" + data-testid="launchpad-edit-bar"> + <Pencil :size="20" class="launchpad-edit-bar__icon" /> + <strong class="launchpad-edit-bar__title"> + {{ t('launchpad', 'You are editing {name}', { name: dashboardName }) }} + </strong> + <span class="launchpad-edit-bar__note"> + {{ t('launchpad', 'Changes are saved immediately') }} + </span> + <span class="launchpad-edit-bar__spacer" /> + <span :id="columnsLabelId" class="launchpad-edit-bar__label"> + {{ t('launchpad', 'Columns') }} + </span> + <div + class="launchpad-edit-bar__columns" + role="group" + :aria-labelledby="columnsLabelId" + data-testid="launchpad-edit-bar-columns"> + <button + v-for="option in columnOptions" + :key="option" + type="button" + class="launchpad-edit-bar__column" + :class="{ 'launchpad-edit-bar__column--on': option === columns }" + :aria-pressed="option === columns ? 'true' : 'false'" + :data-testid="`launchpad-edit-bar-columns-${option}`" + @click="$emit('setColumns', option)"> + {{ option }} + </button> + </div> + <button + type="button" + class="launchpad-edit-bar__button" + data-testid="launchpad-edit-bar-add-widget" + @click="$emit('addWidget')"> + <Plus :size="16" /> + {{ t('launchpad', 'Add widget') }} + </button> + <!-- add-tiles-dialog REQ-TILE-043 --> + <button + type="button" + class="launchpad-edit-bar__button" + aria-haspopup="dialog" + data-testid="launchpad-edit-bar-add-tiles" + @click="$emit('addTiles')"> + <ViewGridPlusOutline :size="16" /> + {{ t('launchpad', 'Add tiles') }} + </button> + <button + v-if="canConfigure" + type="button" + class="launchpad-edit-bar__button" + aria-haspopup="dialog" + data-testid="launchpad-edit-bar-settings" + @click="$emit('openSettings')"> + <Cog :size="16" /> + {{ t('launchpad', 'Dashboard settings') }} + </button> + <button + type="button" + class="launchpad-edit-bar__button launchpad-edit-bar__button--done" + data-testid="launchpad-edit-bar-done" + @click="$emit('done')"> + <Check :size="16" /> + {{ t('launchpad', 'Done') }} + </button> + <div ref="dock" class="launchpad-edit-bar__dock" /> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import Check from 'vue-material-design-icons/Check.vue' +import Cog from 'vue-material-design-icons/Cog.vue' +import Pencil from 'vue-material-design-icons/Pencil.vue' +import Plus from 'vue-material-design-icons/Plus.vue' +import ViewGridPlusOutline from 'vue-material-design-icons/ViewGridPlusOutline.vue' + +/** The column counts the grid offers. */ +export const GRID_COLUMN_OPTIONS = [6, 8, 12] + +let barCounter = 0 + +export default { + name: 'DashboardEditBar', + + components: { + Check, + Cog, + Pencil, + Plus, + ViewGridPlusOutline, + }, + + props: { + /** The name of the dashboard being edited. */ + dashboardName: { + type: String, + default: '', + }, + + /** The dashboard's current number of grid columns. */ + columns: { + type: Number, + default: 12, + }, + + /** + * Whether this person may open the dashboard settings (the owner or + * an administrator). + */ + canConfigure: { + type: Boolean, + default: false, + }, + }, + + emits: ['setColumns', 'addWidget', 'addTiles', 'openSettings', 'done', 'dock'], + + data() { + return { + columnsLabelId: `launchpad-edit-bar-columns-${++barCounter}`, + columnOptions: GRID_COLUMN_OPTIONS, + } + }, + + mounted() { + this.$emit('dock', this.$refs.dock) + }, + + beforeUnmount() { + this.$emit('dock', null) + }, + + methods: { + t, + }, +} +</script> + +<style scoped> +/* The bar runs from window edge to window edge right under the top bar, in + the deep brand colour (LpBewerken; an NL Design theme names it its primary + hover colour); it sits inside the dashboard's 20px + inset and 8px top padding, hence the negative margins. */ +.launchpad-edit-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px 16px; + margin: -8px -20px 16px; + padding: 12px 28px; + background: var(--sc-primary-deep, var(--nldesign-color-primary-hover, var(--color-primary-element))); + color: var(--color-primary-element-text); +} + +.launchpad-edit-bar__icon { + flex: none; +} + +.launchpad-edit-bar__title { + font-size: 16px; + font-weight: 600; +} + +.launchpad-edit-bar__note { + font-size: 14px; + opacity: 0.9; +} + +.launchpad-edit-bar__spacer { + flex: 1; +} + +.launchpad-edit-bar__label { + font-size: 14px; + font-weight: 600; +} + +.launchpad-edit-bar__columns { + display: flex; + gap: 2px; + padding: 3px; + border-radius: var(--border-radius-element, 8px); + background: color-mix(in srgb, var(--color-primary-element-text) 16%, transparent); +} + +.launchpad-edit-bar__column, +.launchpad-edit-bar__button { + display: inline-flex; + align-items: center; + gap: 8px; + margin: 0; + border-radius: var(--border-radius-element, 8px); + font: inherit; + font-size: 14px; + font-weight: 600; + cursor: pointer; +} + +.launchpad-edit-bar__column { + min-width: 38px; + height: 32px; + justify-content: center; + padding: 0 10px; + border: 0; + background: transparent; + color: var(--color-primary-element-text); +} + +.launchpad-edit-bar__column--on { + background: var(--color-primary-element-text); + color: var(--color-primary-element); +} + +.launchpad-edit-bar__button { + height: 38px; + padding: 0 14px; + border: 1px solid var(--color-primary-element-text); + background: transparent; + color: var(--color-primary-element-text); +} + +.launchpad-edit-bar__button--done { + padding: 0 16px; + border-color: transparent; + background: var(--color-primary-element-text); + color: var(--color-primary-element); +} + +.launchpad-edit-bar__dock:empty { + display: none; +} + +.launchpad-edit-bar__column:focus-visible, +.launchpad-edit-bar__button:focus-visible { + outline: 2px solid var(--color-primary-element-text); + outline-offset: 2px; +} + +@media (max-width: 640px) { + .launchpad-edit-bar { + padding: 12px 16px; + } +} +</style> diff --git a/src/components/Workspace/DashboardLanguageHeading.vue b/src/components/Workspace/DashboardLanguageHeading.vue index 112d01b05..9c72a5284 100644 --- a/src/components/Workspace/DashboardLanguageHeading.vue +++ b/src/components/Workspace/DashboardLanguageHeading.vue @@ -27,6 +27,7 @@ <script> import { t } from '@nextcloud/l10n' +import { NULLABLE_OBJECT_PROP } from '../../constants/propDefinitions.js' import { api } from '../../services/api.js' import { logger } from '../../utils/logger.js' @@ -44,10 +45,7 @@ export default { props: { /** The active dashboard (`uuid`, `name`, `hasVariants`). */ - dashboard: { - type: Object, - default: null, - }, + dashboard: NULLABLE_OBJECT_PROP, }, /** @spec openspec/specs/dashboard-language-content/spec.md */ diff --git a/src/components/Workspace/DashboardMoreMenu.vue b/src/components/Workspace/DashboardMoreMenu.vue new file mode 100644 index 000000000..f5f7ae26f --- /dev/null +++ b/src/components/Workspace/DashboardMoreMenu.vue @@ -0,0 +1,199 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 + - + - DashboardMoreMenu: the dashboard view's More menu (board LpMeer), the + - only control in the page header. The same menu as on every other page + - (StartPageMenu), plus the This dashboard group for the open dashboard. + - Each action keeps the permission rule it had. +--> +<template> + <LaunchpadMoreMenu + :dashboards="dashboards" + :settings="settings" + :actions="actions" + class="launchpad-more-menu" + data-testid="launchpad-more-menu" /> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { markRaw } from 'vue' +import CheckDecagramOutline from 'vue-material-design-icons/CheckDecagramOutline.vue' +import { isOwnedDashboard } from './DashboardRowActions.vue' +import LaunchpadMoreMenu from './LaunchpadMoreMenu.vue' +import { + dashboardActionItems, + dashboardItems, + readChrome, + settingsMenuItems, + startPageSections, +} from './moreMenuItems.js' + +export default { + name: 'DashboardMoreMenu', + + components: { + LaunchpadMoreMenu, + }, + + inject: { + /** What `App.vue` decided about the navigation panel (see StartPageMenu). */ + launchpadChrome: { + from: 'launchpadChrome', + default: null, + }, + + /** The shared library's opener for the personal settings dialog. */ + cnOpenUserSettings: { + from: 'cnOpenUserSettings', + default: null, + }, + }, + + props: { + /** The active dashboard, or null. */ + dashboard: { + type: Object, + default: null, + }, + + /** The active dashboard's section: 'user', 'group', 'default' or 'shared'. */ + source: { + type: String, + default: 'user', + }, + + /** The person's own dashboards. */ + userDashboards: { + type: Array, + default: () => [], + }, + + /** The group, default and shared dashboards. */ + groupDashboards: { + type: Array, + default: () => [], + }, + + /** Which dashboards came through a share, to mark them. */ + sharedDashboards: { + type: Array, + default: () => [], + }, + + /** The uuid of the person's default dashboard. */ + defaultUuid: { + type: String, + default: '', + }, + + /** Whether the person may edit the active dashboard. */ + canEdit: { + type: Boolean, + default: false, + }, + + /** Whether the person may share the active dashboard. */ + canShare: { + type: Boolean, + default: false, + }, + + /** Whether the person may make a personal copy of it. */ + canDuplicate: { + type: Boolean, + default: false, + }, + + /** Whether the read receipts of the active dashboard are offered. */ + canViewReadReceipts: { + type: Boolean, + default: false, + }, + + /** Whether the dashboard is being edited. */ + isEditMode: { + type: Boolean, + default: false, + }, + }, + + emits: [ + 'switch', + 'openAll', + 'toggleEdit', + 'addWidget', + 'share', + 'copyLink', + 'duplicate', + 'setDefault', + 'readReceipts', + 'delete', + ], + + computed: { + /** + * The Dashboards group, the open one checked. + * + * @return {object[]} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + dashboards() { + return dashboardItems({ + userDashboards: this.userDashboards, + groupDashboards: this.groupDashboards, + sharedDashboards: this.sharedDashboards, + activeId: this.dashboard?.id ?? null, + defaultUuid: this.defaultUuid, + onSwitch: (id, source) => this.$emit('switch', id, source), + onOpenAll: () => this.$emit('openAll'), + }) + }, + + /** + * The items under Settings, while the navigation panel is left out. + * + * @return {object[]} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + settings() { + const chrome = readChrome(this.launchpadChrome) + if (!chrome.railSuppressed) { + return [] + } + return settingsMenuItems(startPageSections(chrome, this.cnOpenUserSettings)) + }, + + /** + * The This dashboard group. Read receipts, when the dashboard asks + * for them, sit before Delete, which stays last. + * + * @return {object[]} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + actions() { + const items = dashboardActionItems({ + dashboard: this.dashboard, + isOwner: isOwnedDashboard(this.dashboard, this.source), + isDefault: Boolean(this.dashboard?.uuid) && this.dashboard.uuid === this.defaultUuid, + isEditMode: this.isEditMode, + canEdit: this.canEdit, + canShare: this.canShare, + canDuplicate: this.canDuplicate, + emit: (event) => this.$emit(event), + }) + if (this.dashboard && this.canViewReadReceipts) { + const at = items.findIndex((item) => item.destructive === true) + items.splice(at === -1 ? items.length : at, 0, { + id: 'read-receipts', + label: t('launchpad', 'Read receipts'), + icon: markRaw(CheckDecagramOutline), + onClick: () => this.$emit('readReceipts'), + }) + } + return items + }, + }, +} +</script> diff --git a/src/components/Workspace/DashboardPageHeader.vue b/src/components/Workspace/DashboardPageHeader.vue new file mode 100644 index 000000000..379342bfb --- /dev/null +++ b/src/components/Workspace/DashboardPageHeader.vue @@ -0,0 +1,329 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <header class="launchpad-page-header" data-testid="dashboard-page-header"> + <div class="launchpad-page-header__row"> + <h1 class="launchpad-page-header__title"> + {{ dashboard.name }} + </h1> + <div class="launchpad-page-header__actions"> + <!-- REQ-DPD-002: the period the dated widgets follow, shown only + when one of them names a period field. --> + <CnSegmentedControl + v-if="showsPeriod" + :modelValue="period" + :options="periodOptions" + :ariaLabel="t('launchpad', 'Period')" + size="compact" + data-testid="dashboard-period" + @update:modelValue="$emit('update:period', $event)" /> + <!-- REQ-DPD-003: everyone who can open the dashboard may download + it, view-only included; the header is not drawn in the kiosk + and public views, so neither offers it. --> + <NcButton + class="launchpad-print-hide" + variant="secondary" + data-testid="dashboard-download" + @click="download"> + <template #icon> + <Download :size="20" /> + </template> + {{ t('launchpad', 'Download') }} + </NcButton> + <!-- The top-right controls teleport in here (headerActionsDock.js). --> + <div :class="dockClass" /> + </div> + </div> + <p v-if="kindLabel || metaLine" class="launchpad-page-header__meta"> + <span v-if="kindLabel" class="launchpad-page-header__kind" data-testid="dashboard-page-header-kind"> + <component :is="kindIcon" :size="18" /> + {{ kindLabel }} + </span> + <span v-if="metaLine">{{ metaLine }}</span> + </p> + </header> +</template> + +<script> +import { CnSegmentedControl } from '@conduction/nextcloud-vue' +import { getCanonicalLocale, t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' +import AccountGroupOutline from 'vue-material-design-icons/AccountGroupOutline.vue' +import AccountOutline from 'vue-material-design-icons/AccountOutline.vue' +import Download from 'vue-material-design-icons/Download.vue' +import ShareVariant from 'vue-material-design-icons/ShareVariant.vue' +import { PAGE_HEADER_DOCK_CLASS } from '../../utils/headerActionsDock.js' +import { printDashboard } from '../../utils/printDashboard.js' + +/** Milliseconds in a day. */ +const DAY_MS = 86400000 + +/** + * When the dashboard was last changed, as the boards word it: the time for + * today, the weekday within the last week, the date before that. + * + * @param {string|null} updatedAt ISO date of the last change. + * @param {Date} now The current moment. + * @param {string} locale BCP 47 locale. + * @return {string} The moment, or '' without a usable date. + */ +export function lastChangedText(updatedAt, now, locale) { + const changed = new Date(updatedAt ?? '') + if (Number.isNaN(changed.getTime())) { + return '' + } + const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime() + if (changed.getTime() >= startOfToday) { + return t('launchpad', 'Last changed today {time}', { + time: changed.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' }), + }) + } + if (changed.getTime() >= startOfToday - 6 * DAY_MS) { + return t('launchpad', 'Last changed {when}', { + when: changed.toLocaleDateString(locale, { weekday: 'long' }), + }) + } + return t('launchpad', 'Last changed {when}', { + when: changed.toLocaleDateString(locale, { day: 'numeric', month: 'long' }), + }) +} + +/** + * What the reader may do on the dashboard, for the meta line: "view only" + * or "you may add widgets"; nothing extra with full rights. + * + * @param {string} permissionLevel The reader's level: `full`, `add_only` or `view_only`. + * @return {string} The words, or '' with full rights. + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-the-header-says-what-dashboard-this-is-and-what-the-reader-may-do-req-dpd-001 + */ +export function rightsText(permissionLevel) { + if (permissionLevel === 'view_only') { + return t('launchpad', 'view only') + } + if (permissionLevel === 'add_only') { + return t('launchpad', 'you may add widgets') + } + return '' +} + +/** + * DashboardPageHeader: the page title row of a dashboard without a greeting + * on the page ground (LpWerkplek, LpIntranet, LpAfdeling, LpManagement): the + * dashboard name, Download (REQ-DPD-003) beside the docked "Meer" menu, and a line + * saying what kind of dashboard it is and when it last changed. + * + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-009-no-navigation-panel-the-destinations-are-in-the-more-menu + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-the-header-says-what-dashboard-this-is-and-what-the-reader-may-do-req-dpd-001 + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-reader-can-download-the-dashboard-req-dpd-003 + */ +export default { + name: 'DashboardPageHeader', + + components: { CnSegmentedControl, Download, NcButton }, + + props: { + /** The active dashboard (`name`, `description`, `updatedAt`). */ + dashboard: { + type: Object, + required: true, + }, + + /** Where the dashboard comes from: `user`, `group`, `default` or `shared`. */ + source: { + type: String, + default: 'user', + }, + + /** Whether this dashboard opens first for the reader. */ + isDefault: { + type: Boolean, + default: false, + }, + + /** The reader's rights on it: `full`, `add_only` or `view_only`. */ + permissionLevel: { + type: String, + default: 'full', + }, + + /** Whether a widget on the dashboard names a period field (REQ-DPD-002). */ + showsPeriod: { + type: Boolean, + default: false, + }, + + /** The chosen period: `month`, `quarter` or `year`. */ + period: { + type: String, + default: 'month', + }, + }, + + emits: ['update:period'], + + /** @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-009-no-navigation-panel-the-destinations-are-in-the-more-menu */ + data() { + return { dockClass: PAGE_HEADER_DOCK_CLASS } + }, + + computed: { + /** + * The period choices, This month first. + * + * @return {Array<{value: string, label: string}>} + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + periodOptions() { + return [ + { value: 'month', label: t('launchpad', 'This month') }, + { value: 'quarter', label: t('launchpad', 'Quarter') }, + { value: 'year', label: t('launchpad', 'Year') }, + ] + }, + + /** + * @return {string} The kind of dashboard for the chip: personal, the + * group it belongs to, or shared; '' for the organisation-wide one. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-009-no-navigation-panel-the-destinations-are-in-the-more-menu + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-the-header-says-what-dashboard-this-is-and-what-the-reader-may-do-req-dpd-001 + */ + kindLabel() { + if (this.source === 'user') { + return this.isDefault + ? t('launchpad', 'Personal dashboard · opens first') + : t('launchpad', 'Personal dashboard') + } + if (this.source === 'shared') { + return t('launchpad', 'Shared with you') + } + if (this.source === 'group' && this.groupName !== '') { + return t('launchpad', 'Group dashboard of {group}', { group: this.groupName }) + } + return '' + }, + + /** + * The group a group dashboard belongs to: its display name when the + * row carries one, else its group id; '' for the organisation-wide + * `default` sentinel. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-the-header-says-what-dashboard-this-is-and-what-the-reader-may-do-req-dpd-001 + */ + groupName() { + const id = String(this.dashboard.groupId ?? '').trim() + if (id === '' || id === 'default') { + return '' + } + const display = String(this.dashboard.groupDisplayName ?? '').trim() + return display !== '' ? display : id + }, + + /** + * @return {object} The chip icon. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-009-no-navigation-panel-the-destinations-are-in-the-more-menu + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-the-header-says-what-dashboard-this-is-and-what-the-reader-may-do-req-dpd-001 + */ + kindIcon() { + if (this.source === 'shared') { + return ShareVariant + } + return this.source === 'group' ? AccountGroupOutline : AccountOutline + }, + + /** + * The description, what the reader may do and the last change, + * joined as one line. + * + * @return {string} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-009-no-navigation-panel-the-destinations-are-in-the-more-menu + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-the-header-says-what-dashboard-this-is-and-what-the-reader-may-do-req-dpd-001 + */ + metaLine() { + const parts = [ + (this.dashboard.description ?? '').trim(), + rightsText(this.permissionLevel), + lastChangedText(this.dashboard.updatedAt, new Date(), getCanonicalLocale()), + ].filter((part) => part !== '') + return parts.join(' · ') + }, + }, + + methods: { + t, + + /** + * Download the dashboard as a PDF: the reader's browser prints the + * page as it is now, with the period and filters applied. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-reader-can-download-the-dashboard-req-dpd-003 + */ + download() { + printDashboard(this.dashboard.name) + }, + }, +} +</script> + +<style scoped> +/* The title starts on the grid's 28px line (the container's 20px inset plus + 8px here) and the meta line sits 14px under it (LpWerkplek). */ +.launchpad-page-header { + display: flex; + flex-direction: column; + gap: 14px; + padding: 16px 8px 8px; +} + +.launchpad-page-header__row { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: flex-start; + gap: 12px 24px; +} + +.launchpad-page-header__title { + flex: 1 1 320px; + min-width: 0; + margin: 0; + font-size: 28px; + font-weight: 700; + line-height: 1.2; + color: var(--color-main-text); +} + +.launchpad-page-header__actions { + flex: none; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} + +.launchpad-page-header__meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; + margin: 0; + font-size: 15px; + color: var(--color-text-maxcontrast); +} + +.launchpad-page-header__kind { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 12px 3px 8px; + border-radius: var(--border-radius-pill, 14px); + background: var(--color-primary-element-light); + color: var(--color-primary-element-light-text); + font-size: 14px; + font-weight: 600; +} +</style> diff --git a/src/components/Workspace/DashboardReactions.vue b/src/components/Workspace/DashboardReactions.vue index e6eb8caea..f67c31291 100644 --- a/src/components/Workspace/DashboardReactions.vue +++ b/src/components/Workspace/DashboardReactions.vue @@ -4,12 +4,15 @@ --> <template> - <div + <section v-if="summary && summary.enabled" class="dashboard-reactions" - role="group" :aria-label="t('launchpad', 'Reactions')" data-testid="dashboard-reactions"> + <p class="dashboard-reactions__question" data-testid="dashboard-reactions-question"> + {{ t('launchpad', 'What do you think of this dashboard?') }} + </p> + <div class="dashboard-reactions__chips" role="group" :aria-label="t('launchpad', 'Reactions')"> <button v-for="emoji in shown" :key="emoji" @@ -41,33 +44,90 @@ @click="toggle(emoji)"> <span aria-hidden="true">{{ emoji }}</span> </button> - </div> + </div> + <p + v-if="lastChangeLine" + class="dashboard-reactions__last-change" + data-testid="dashboard-reactions-last-change"> + {{ lastChangeLine }} + </p> + </section> </template> <script> -import { t } from '@nextcloud/l10n' +import { getCanonicalLocale, t } from '@nextcloud/l10n' import { mapActions, mapState } from 'pinia' +import { TEXT_PROP } from '../../constants/propDefinitions.js' import { api } from '../../services/api.js' import { useDashboardStore } from '../../stores/dashboard.js' +/** Milliseconds in a day. */ +const DAY_MS = 86400000 + +/** + * The moment of a change as the boards word it: "today 08:30" for today, + * the weekday within the last week, the date before that. + * + * @param {Date} changed The moment of the change. + * @param {Date} now The current moment. + * @param {string} locale BCP 47 locale. + * @return {string} The moment. + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard + */ +function whenText(changed, now, locale) { + const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime() + if (changed.getTime() >= startOfToday) { + return t('launchpad', 'today {time}', { + time: changed.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' }), + }) + } + if (changed.getTime() >= startOfToday - 6 * DAY_MS) { + return changed.toLocaleDateString(locale, { weekday: 'long' }) + } + return changed.toLocaleDateString(locale, { day: 'numeric', month: 'long' }) +} + +/** + * The last-change line of the reactions bar: "Last updated by <name>, + * <when>", or "Last updated <when>" without a name. + * + * @param {{name?: string, at?: string|null}|null|undefined} lastChange The summary's last change. + * @param {Date} now The current moment. + * @param {string} locale BCP 47 locale. + * @return {string} The line, or '' without a usable time. + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard + */ +export function lastChangeText(lastChange, now, locale) { + const changed = new Date(lastChange?.at ?? '') + if (Number.isNaN(changed.getTime())) { + return '' + } + const when = whenText(changed, now, locale) + const name = typeof lastChange.name === 'string' ? lastChange.name.trim() : '' + if (name === '') { + return t('launchpad', 'Last updated {when}', { when }, undefined, { escape: false }) + } + return t('launchpad', 'Last updated by {name}, {when}', { name, when }, undefined, { escape: false }) +} + /** - * DashboardReactions: the reactions bar under the dashboard title. Each + * DashboardReactions: the reactions bar at the foot of the dashboard, a + * card over the full width that asks what the viewer thinks of it. Each * emoji with a count, the viewer's own marked (aria-pressed); a click * toggles the viewer's reaction; the allowed emoji nobody used yet are * offered too. Hovering or focusing a count names who reacted. Absent when * reactions are off globally or for the dashboard (the summary says - * `enabled: false`). + * `enabled: false`). After the reactions it names who last changed the + * dashboard, and when. * * @spec openspec/specs/dashboard-reactions/spec.md + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard */ export default { name: 'DashboardReactions', props: { - dashboardUuid: { - type: String, - default: '', - }, + dashboardUuid: TEXT_PROP, }, /** @spec openspec/specs/dashboard-reactions/spec.md */ @@ -106,6 +166,16 @@ export default { : [] return allowed.filter((e) => !this.shown.includes(e)) }, + + /** + * "Last updated by <name>, <when>" from the summary's last change. + * + * @return {string} The line, or '' when the change is unknown. + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard + */ + lastChangeLine() { + return lastChangeText(this.summary?.lastChange, new Date(), getCanonicalLocale()) + }, }, watch: { @@ -212,10 +282,35 @@ export default { <style scoped> .dashboard-reactions { + display: flex; + flex-wrap: wrap; + gap: 8px 16px; + align-items: center; + margin: 8px; + padding: 12px 16px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); + background: var(--color-main-background); +} + +.dashboard-reactions__question, +.dashboard-reactions__last-change { + margin: 0; +} + +.dashboard-reactions__question { + font-weight: bold; +} + +.dashboard-reactions__chips { display: flex; flex-wrap: wrap; gap: 6px; - margin: 0 8px 8px; +} + +.dashboard-reactions__last-change { + margin-inline-start: auto; + color: var(--color-text-maxcontrast); } .dashboard-reactions__chip { diff --git a/src/components/Workspace/DashboardRowActions.vue b/src/components/Workspace/DashboardRowActions.vue index f9c8609a7..c4a47ab9d 100644 --- a/src/components/Workspace/DashboardRowActions.vue +++ b/src/components/Workspace/DashboardRowActions.vue @@ -7,7 +7,7 @@ DashboardRowActions — wave3.6 per-row cog menu Lives at the right edge of every dashboard `<li>` in the sidebar. - The 4 actions (Edit / Configure / Add custom widget / Delete) act on + The 4 actions (Edit / Configure / Add widget / Delete) act on the row's own dashboard, not on whichever dashboard happens to be "active" — so the user can edit, configure, or delete any dashboard they have access to without having to switch first. @@ -19,11 +19,11 @@ event so the host can decide whether to switch + enter edit mode or no-op). - Dashboard configuration → only when the row's `dashboard.isOwner !== false`. - - Add custom widget → only when `canEdit` is true. + - Add widget → only when `canEdit` is true. - Delete dashboard → only when the row's `dashboard.isOwner !== false`. Emits raw events; the host (`DashboardSwitcherSidebar.vue`) maps - them to its `toggle-edit` / `open-config` / `add-custom-widget` / + them to its `toggle-edit` / `open-config` / `add-widget` / `delete-dashboard` outputs with the per-row dashboard payload. `@click.stop` is set on the cog trigger so opening the menu never @@ -71,11 +71,21 @@ v-if="canEdit" :closeAfterClick="true" data-testid="cog-add-widget" - @click="$emit('addCustomWidget')"> + @click="$emit('addWidget')"> <template #icon> <ShapePolygonPlus :size="20" /> </template> - {{ t('launchpad', 'Add custom widget…') }} + {{ t('launchpad', 'Add widget') }} + </NcActionButton> + <NcActionButton + v-if="canEdit" + :closeAfterClick="true" + data-testid="cog-import-bookmarks" + @click="$emit('importBookmarks')"> + <template #icon> + <BookmarkPlusOutline :size="20" /> + </template> + {{ t('launchpad', 'Import bookmarks') }} </NcActionButton> <NcActionButton :closeAfterClick="true" @@ -91,47 +101,6 @@ : t('launchpad', 'Set as default') }} </NcActionButton> - <template v-if="canManagePublication"> - <NcActionButton - v-if="dashboard.publicationStatus !== 'published'" - :closeAfterClick="true" - data-testid="cog-publish" - @click="$emit('publish')"> - <template #icon> - <Publish :size="20" /> - </template> - {{ t('launchpad', 'Publish') }} - </NcActionButton> - <NcActionButton - v-else - :closeAfterClick="true" - data-testid="cog-unpublish" - @click="$emit('unpublish')"> - <template #icon> - <PublishOff :size="20" /> - </template> - {{ t('launchpad', 'Unpublish') }} - </NcActionButton> - <NcActionButton - :closeAfterClick="true" - data-testid="cog-schedule" - @click="$emit('schedule')"> - <template #icon> - <CalendarClock :size="20" /> - </template> - {{ t('launchpad', 'Schedule…') }} - </NcActionButton> - </template> - <NcActionButton - v-if="canViewHistory" - :closeAfterClick="true" - data-testid="cog-version-history" - @click="$emit('versionHistory')"> - <template #icon> - <History :size="20" /> - </template> - {{ t('launchpad', 'Version history…') }} - </NcActionButton> <NcActionButton v-if="canShare" :closeAfterClick="true" @@ -142,6 +111,16 @@ </template> {{ t('launchpad', 'Share') }} </NcActionButton> + <NcActionButton + v-if="canEmbed && dashboard.uuid" + :closeAfterClick="true" + data-testid="cog-embed" + @click="openEmbed"> + <template #icon> + <CodeTags :size="20" /> + </template> + {{ t('launchpad', 'Create embed token') }} + </NcActionButton> <NcActionButton v-if="isOwner" :closeAfterClick="true" @@ -158,19 +137,58 @@ <script> import { t } from '@nextcloud/l10n' import { NcActionButton, NcActions } from '@nextcloud/vue' -import CalendarClock from 'vue-material-design-icons/CalendarClock.vue' +import BookmarkPlusOutline from 'vue-material-design-icons/BookmarkPlusOutline.vue' +import CodeTags from 'vue-material-design-icons/CodeTags.vue' import Cog from 'vue-material-design-icons/Cog.vue' import ContentSave from 'vue-material-design-icons/ContentSave.vue' -import History from 'vue-material-design-icons/History.vue' import Pencil from 'vue-material-design-icons/Pencil.vue' -import Publish from 'vue-material-design-icons/Publish.vue' -import PublishOff from 'vue-material-design-icons/PublishOff.vue' import ShapePolygonPlus from 'vue-material-design-icons/ShapePolygonPlus.vue' import ShareVariant from 'vue-material-design-icons/ShareVariant.vue' import Star from 'vue-material-design-icons/Star.vue' import StarCheck from 'vue-material-design-icons/StarCheck.vue' import TrashCanOutline from 'vue-material-design-icons/TrashCanOutline.vue' import Tune from 'vue-material-design-icons/Tune.vue' +import { + FLAG_PROP, + REQUIRED_OBJECT_PROP, + TEXT_PROP, +} from '../../constants/propDefinitions.js' +import { adminPageUrl } from '../../utils/adminPage.js' +import { embedAdminSearch } from '../../utils/embedToken.js' + +/** + * The address of Beheer ▸ Embeds with a dashboard pre-selected, or one + * widget placement of it when `placement` is given. + * + * @param {object|null} dashboard The dashboard. + * @param {object|null} placement A widget placement on the dashboard. + * @return {string} + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ +export function embedAdminHref(dashboard, placement = null) { + const search = placement + ? embedAdminSearch('widget', placement.id ?? '', dashboard?.id ?? null) + : embedAdminSearch('dashboard', dashboard?.uuid ?? '', dashboard?.id ?? null) + return `${adminPageUrl('embeds')}?${search}` +} + +/** + * Whether the caller owns a dashboard: a row under "My dashboards" (the + * `user` source) always, any other row only when the dashboard says + * `isOwner: true`. Owner-gated actions (configure, delete) use it. + * + * @param {object|null} dashboard The dashboard. + * @param {string} source The dashboard's section. + * @return {boolean} + * @spec openspec/specs/dashboard-switcher/spec.md + */ +export function isOwnedDashboard(dashboard, source) { + if (source === 'user') { + return true + } + return dashboard?.isOwner === true +} export default { name: 'DashboardRowActions', @@ -178,26 +196,21 @@ export default { components: { NcActions, NcActionButton, + CodeTags, Cog, Pencil, ContentSave, Tune, ShapePolygonPlus, + BookmarkPlusOutline, TrashCanOutline, Star, StarCheck, ShareVariant, - CalendarClock, - Publish, - PublishOff, - History, }, props: { - dashboard: { - type: Object, - required: true, - }, + dashboard: REQUIRED_OBJECT_PROP, source: { type: String, @@ -205,10 +218,7 @@ export default { validator: (v) => ['group', 'default', 'user', 'shared'].includes(v), }, - canEdit: { - type: Boolean, - default: false, - }, + canEdit: FLAG_PROP, /* * Wave3.7 — UUID of the user's pinned default dashboard, or @@ -218,10 +228,7 @@ export default { * either a star (this row is NOT default) or a filled star * (this row IS the default). */ - defaultUuid: { - type: String, - default: '', - }, + defaultUuid: TEXT_PROP, /* * Wave3.9 — when this row matches the currently active @@ -231,10 +238,7 @@ export default { * (lives on Views.vue's `isEditMode` data field) and the * active id (`activeDashboard.id`) and forwards both down. */ - isEditMode: { - type: Boolean, - default: false, - }, + isEditMode: FLAG_PROP, activeDashboardId: { type: [String, Number], @@ -247,31 +251,14 @@ export default { * sidebar rows don't expose sharing; the top-right active-dashboard * cog passes the host's `canShareActiveDashboard` gate. */ - canShare: { - type: Boolean, - default: false, - }, + canShare: FLAG_PROP, /* - * sharing-dashboard-schedule-screen REQ-SCHEDUI-001: the host allows - * Publish / Unpublish / Schedule… (owner or administrator). Off by - * default, so sidebar rows do not show them. + * embedded-analytics task 40: the viewer is an administrator, so the + * menu offers "Create embed token", a link to Beheer ▸ Embeds with + * this dashboard pre-selected. Off by default. */ - canManagePublication: { - type: Boolean, - default: false, - }, - - /* - * When true the menu renders "Version history…" (REQ-VERSUI-001). - * The host decides: owner or administrator, and versioning - * supported for this dashboard. Off by default, so sidebar rows - * do not show it. - */ - canViewHistory: { - type: Boolean, - default: false, - }, + canEmbed: FLAG_PROP, /* * NcActions toggle button style. Defaults to the subtle @@ -297,18 +284,26 @@ export default { emits: [ 'toggleEdit', 'openConfig', - 'addCustomWidget', + 'addWidget', + // launcher-bookmark-import REQ-BMI-001: only where the user may add. + 'importBookmarks', 'delete', 'setDefault', 'share', - 'publish', - 'unpublish', - 'schedule', - 'versionHistory', 'menuOpen', ], computed: { + /** + * Beheer ▸ Embeds with this dashboard pre-selected for a new token. + * + * @return {string} + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + */ + embedHref() { + return embedAdminHref(this.dashboard) + }, + /* * Owner-gated actions (Configure, Delete) require the user to * own this dashboard. The visibility API doesn't always set @@ -321,10 +316,7 @@ export default { * @spec openspec/specs/dashboard-switcher/spec.md */ isOwner() { - if (this.source === 'user') { - return true - } - return this.dashboard?.isOwner === true + return isOwnedDashboard(this.dashboard, this.source) }, /* @@ -360,6 +352,15 @@ export default { methods: { t, + + /** + * Open Beheer ▸ Embeds with this dashboard pre-selected. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + */ + openEmbed() { + window.location.assign(this.embedHref) + }, }, } </script> diff --git a/src/components/Workspace/DashboardSwitcherSidebar.vue b/src/components/Workspace/DashboardSwitcherSidebar.vue index 03a38c546..c3a29bee7 100644 --- a/src/components/Workspace/DashboardSwitcherSidebar.vue +++ b/src/components/Workspace/DashboardSwitcherSidebar.vue @@ -22,9 +22,9 @@ The `source` discriminator on each emit is load-bearing — the parent uses it to pick the correct API endpoint (group vs default vs user). - Personal rows expose a hover-revealed delete button (CSS `display: none → - inline-flex`) emitting `delete-dashboard(id)` with `@click.stop` so it - never triggers a switch (REQ-SWITCH-004). + Each row's options menu (DashboardRowActions) carries Delete for a + dashboard the user owns; choosing it emits `deleteDashboard(id, source)` + and never triggers a switch (REQ-SWITCH-004). A dedicated "Add Dashboard" card button (NcButton secondary) renders below the personal dashboards list — still inside the scroll container, @@ -86,395 +86,139 @@ <div class="dashboard-switcher-sidebar__body"> <!-- dashboard-language-and-details-tabs REQ-MDUI-003 --> <DetailFilter :fields="filterFields" @change="$emit('filter', $event)" /> - <!-- 1. Primary group dashboards --> - <section - v-if="primaryGroupDashboards.length > 0" - class="dashboard-switcher-sidebar__section" - data-section="group"> - <h3 class="dashboard-switcher-sidebar__heading"> - {{ primaryGroupHeading }} - </h3> - <ul class="dashboard-switcher-sidebar__list"> - <li - v-for="{ dashboard, depth, hasChildren } in treeRows( - primaryGroupDashboards, - )" - :key="`group-${dashboard.id}`" - class="dashboard-switcher-sidebar__item" - :class="{ active: isActive(dashboard.id) }" - :data-depth="depth" - :style="depthStyle(depth)" - data-source="group" - tabindex="0" - role="button" - :aria-label="dashboard.name" - @click="onSwitch(dashboard.id, 'group')" - @keydown.enter="onSwitch(dashboard.id, 'group')" - @keydown.space.prevent="onSwitch(dashboard.id, 'group')"> - <button - v-if="hasChildren" - type="button" - class="dashboard-switcher-sidebar__expander" - :data-testid="`tree-expand-${dashboard.uuid}`" - :aria-expanded="isExpanded(dashboard) ? 'true' : 'false'" - :aria-label=" - isExpanded(dashboard) - ? t('launchpad', 'Collapse {name}', { - name: dashboard.name, - }) - : t('launchpad', 'Expand {name}', { - name: dashboard.name, - }) - " - @click.stop="toggleExpanded(dashboard)" - @keydown.enter.stop - @keydown.space.stop> - <ChevronDown v-if="isExpanded(dashboard)" :size="16" /> - <ChevronRight v-else :size="16" /> - </button> - <span class="dashboard-switcher-sidebar__icon"> - <CnDashboardIcon :name="dashboard.icon" :size="20" /> - </span> - <span - v-if="isDefaultDashboard(dashboard)" - class="dashboard-switcher-sidebar__default-marker" - :title=" - t( - 'launchpad', - 'Default dashboard — opens automatically when you visit LaunchPad', - ) - " - :aria-label="t('launchpad', 'Default dashboard')"> - <Star :size="16" /> - </span> - <span class="dashboard-switcher-sidebar__label">{{ - dashboard.name - }}</span> - <DashboardRowActions - :dashboard="dashboard" - source="group" - :canEdit="canEdit" - :defaultUuid="defaultUuid" - :isEditMode="isEditMode" - :activeDashboardId="activeDashboardId" - @toggleEdit="onRowToggleEdit(dashboard, 'group')" - @openConfig="onRowOpenConfig(dashboard, 'group')" - @addCustomWidget=" - onRowAddCustomWidget(dashboard, 'group') - " - @delete="onRowDelete(dashboard, 'group')" - @setDefault="onRowSetDefault(dashboard, 'group')" /> - </li> - </ul> - </section> - - <!-- Divider 1 ↔ 2 --> - <hr - v-if=" - primaryGroupDashboards.length > 0 - && defaultGroupDashboards.length > 0 - " - class="dashboard-switcher-sidebar__divider" /> - - <!-- 2. Default group dashboards --> - <section - v-if="defaultGroupDashboards.length > 0" - class="dashboard-switcher-sidebar__section" - data-section="default"> - <h3 class="dashboard-switcher-sidebar__heading"> - {{ t('launchpad', 'Default') }} - </h3> - <ul class="dashboard-switcher-sidebar__list"> - <li - v-for="{ dashboard, depth, hasChildren } in treeRows( - defaultGroupDashboards, - )" - :key="`default-${dashboard.id}`" - class="dashboard-switcher-sidebar__item" - :class="{ active: isActive(dashboard.id) }" - :data-depth="depth" - :style="depthStyle(depth)" - data-source="default" - tabindex="0" - role="button" - :aria-label="dashboard.name" - @click="onSwitch(dashboard.id, 'default')" - @keydown.enter="onSwitch(dashboard.id, 'default')" - @keydown.space.prevent="onSwitch(dashboard.id, 'default')"> - <button - v-if="hasChildren" - type="button" - class="dashboard-switcher-sidebar__expander" - :data-testid="`tree-expand-${dashboard.uuid}`" - :aria-expanded="isExpanded(dashboard) ? 'true' : 'false'" - :aria-label=" - isExpanded(dashboard) - ? t('launchpad', 'Collapse {name}', { - name: dashboard.name, - }) - : t('launchpad', 'Expand {name}', { - name: dashboard.name, - }) - " - @click.stop="toggleExpanded(dashboard)" - @keydown.enter.stop - @keydown.space.stop> - <ChevronDown v-if="isExpanded(dashboard)" :size="16" /> - <ChevronRight v-else :size="16" /> - </button> - <span class="dashboard-switcher-sidebar__icon"> - <CnDashboardIcon :name="dashboard.icon" :size="20" /> - </span> - <span - v-if="isDefaultDashboard(dashboard)" - class="dashboard-switcher-sidebar__default-marker" - :title=" - t( - 'launchpad', - 'Default dashboard — opens automatically when you visit LaunchPad', - ) - " - :aria-label="t('launchpad', 'Default dashboard')"> - <Star :size="16" /> - </span> - <span class="dashboard-switcher-sidebar__label">{{ - dashboard.name - }}</span> - <DashboardRowActions - :dashboard="dashboard" - source="default" - :canEdit="canEdit" - :defaultUuid="defaultUuid" - :isEditMode="isEditMode" - :activeDashboardId="activeDashboardId" - @toggleEdit="onRowToggleEdit(dashboard, 'default')" - @openConfig="onRowOpenConfig(dashboard, 'default')" - @addCustomWidget=" - onRowAddCustomWidget(dashboard, 'default') - " - @delete="onRowDelete(dashboard, 'default')" - @setDefault="onRowSetDefault(dashboard, 'default')" /> - </li> - </ul> - </section> - - <!-- Divider before personal section (only when prev section non-empty) --> - <hr - v-if=" - (primaryGroupDashboards.length > 0 - || defaultGroupDashboards.length > 0) - && showPersonalSection - " - class="dashboard-switcher-sidebar__divider" /> - - <!-- 3. Personal dashboards --> - <section - v-if="showPersonalSection" - class="dashboard-switcher-sidebar__section" - data-section="user"> - <h3 class="dashboard-switcher-sidebar__heading"> - {{ t('launchpad', 'My Dashboards') }} - </h3> - <ul class="dashboard-switcher-sidebar__list"> - <li - v-for="{ dashboard, depth, hasChildren } in treeRows( - userDashboards, - )" - :key="`user-${dashboard.id}`" - class="dashboard-switcher-sidebar__item dashboard-switcher-sidebar__item--personal" - :class="{ active: isActive(dashboard.id) }" - :data-depth="depth" - :style="depthStyle(depth)" - data-source="user" - tabindex="0" - role="button" - :aria-label="dashboard.name" - @click="onSwitch(dashboard.id, 'user')" - @keydown.enter="onSwitch(dashboard.id, 'user')" - @keydown.space.prevent="onSwitch(dashboard.id, 'user')"> - <button - v-if="hasChildren" - type="button" - class="dashboard-switcher-sidebar__expander" - :data-testid="`tree-expand-${dashboard.uuid}`" - :aria-expanded="isExpanded(dashboard) ? 'true' : 'false'" - :aria-label=" - isExpanded(dashboard) - ? t('launchpad', 'Collapse {name}', { - name: dashboard.name, - }) - : t('launchpad', 'Expand {name}', { - name: dashboard.name, - }) - " - @click.stop="toggleExpanded(dashboard)" - @keydown.enter.stop - @keydown.space.stop> - <ChevronDown v-if="isExpanded(dashboard)" :size="16" /> - <ChevronRight v-else :size="16" /> - </button> - <span class="dashboard-switcher-sidebar__icon"> - <CnDashboardIcon :name="dashboard.icon" :size="20" /> - </span> - <span - v-if="isDefaultDashboard(dashboard)" - class="dashboard-switcher-sidebar__default-marker" - :title=" - t( - 'launchpad', - 'Default dashboard — opens automatically when you visit LaunchPad', - ) - " - :aria-label="t('launchpad', 'Default dashboard')"> - <Star :size="16" /> - </span> - <span class="dashboard-switcher-sidebar__label">{{ - dashboard.name - }}</span> - <DashboardRowActions - :dashboard="dashboard" - source="user" - :canEdit="canEdit" - :defaultUuid="defaultUuid" - :isEditMode="isEditMode" - :activeDashboardId="activeDashboardId" - @toggleEdit="onRowToggleEdit(dashboard, 'user')" - @openConfig="onRowOpenConfig(dashboard, 'user')" - @addCustomWidget=" - onRowAddCustomWidget(dashboard, 'user') - " - @delete="onRowDelete(dashboard, 'user')" - @setDefault="onRowSetDefault(dashboard, 'user')" /> - </li> - </ul> - - <!-- - REQ-SWITCH-008: dedicated "Add Dashboard" card button. Lives - BELOW the personal list (not inside the <ul>), still inside - the scroll container, gated on `allowUserDashboards`. Same - emit contract as the removed inline row. - --> - <div - v-if="allowUserDashboards" - class="dashboard-switcher-sidebar__add-dashboard-card"> - <NcButton - variant="secondary" - wide - data-action="create" - data-testid="add-dashboard-button" - :disabled="dashboardQuotaReached" - :title="dashboardQuotaReached ? dashboardQuotaTooltip : null" - :aria-label=" - dashboardQuotaReached - ? dashboardQuotaTooltip - : t('launchpad', 'Add dashboard') - " - @click="onCreate"> - <template #icon> - <Plus :size="20" /> - </template> - {{ t('launchpad', 'Add dashboard') }} - </NcButton> - <p - v-if="dashboardQuotaReached" - class="dashboard-switcher-sidebar__quota-hint" - data-testid="dashboard-quota-hint"> - {{ dashboardQuotaTooltip }} - </p> - </div> - </section> - - <!-- Divider before the shared section --> - <hr - v-if=" - sharedDashboards.length > 0 - && (primaryGroupDashboards.length > 0 - || defaultGroupDashboards.length > 0 - || showPersonalSection) - " - class="dashboard-switcher-sidebar__divider" /> - - <!-- 4. Dashboards shared with the user (REQ-SHARE-002) --> - <section - v-if="sharedDashboards.length > 0" - class="dashboard-switcher-sidebar__section" - data-section="shared"> - <h3 class="dashboard-switcher-sidebar__heading"> - {{ t('launchpad', 'Shared with you') }} - </h3> - <ul class="dashboard-switcher-sidebar__list"> - <li - v-for="{ dashboard, depth, hasChildren } in treeRows( - sharedDashboards, - )" - :key="`shared-${dashboard.id}`" - class="dashboard-switcher-sidebar__item" - :class="{ active: isActive(dashboard.id) }" - :data-depth="depth" - :style="depthStyle(depth)" - data-source="shared" - tabindex="0" - role="button" - :aria-label="dashboard.name" - @click="onSwitch(dashboard.id, 'shared')" - @keydown.enter="onSwitch(dashboard.id, 'shared')" - @keydown.space.prevent="onSwitch(dashboard.id, 'shared')"> - <button - v-if="hasChildren" - type="button" - class="dashboard-switcher-sidebar__expander" - :data-testid="`tree-expand-${dashboard.uuid}`" - :aria-expanded="isExpanded(dashboard) ? 'true' : 'false'" + <!-- + Sections in order: 1. primary group dashboards, 2. default group + dashboards, 3. personal dashboards, 4. dashboards shared with + the user (REQ-SHARE-002). Only visible sections render, with a + divider before every section that follows another. + --> + <template + v-for="(section, index) in visibleSections" + :key="section.source"> + <hr v-if="index > 0" class="dashboard-switcher-sidebar__divider" /> + + <section + class="dashboard-switcher-sidebar__section" + :data-section="section.source"> + <h3 class="dashboard-switcher-sidebar__heading"> + {{ section.heading }} + </h3> + <ul class="dashboard-switcher-sidebar__list"> + <li + v-for="{ dashboard, depth, hasChildren } in treeRows( + section.dashboards, + )" + :key="`${section.source}-${dashboard.id}`" + class="dashboard-switcher-sidebar__item" + :class="{ + 'dashboard-switcher-sidebar__item--personal': + section.source === 'user', + active: isActive(dashboard.id), + }" + :data-depth="depth" + :style="depthStyle(depth)" + :data-source="section.source" + tabindex="0" + role="button" + :aria-label="dashboard.name" + @click="onSwitch(dashboard.id, section.source)" + @keydown.enter="onSwitch(dashboard.id, section.source)" + @keydown.space.prevent="onSwitch(dashboard.id, section.source)"> + <button + v-if="hasChildren" + type="button" + class="dashboard-switcher-sidebar__expander" + :data-testid="`tree-expand-${dashboard.uuid}`" + :aria-expanded="isExpanded(dashboard) ? 'true' : 'false'" + :aria-label=" + isExpanded(dashboard) + ? t('launchpad', 'Collapse {name}', { + name: dashboard.name, + }) + : t('launchpad', 'Expand {name}', { + name: dashboard.name, + }) + " + @click.stop="toggleExpanded(dashboard)" + @keydown.enter.stop + @keydown.space.stop> + <ChevronDown v-if="isExpanded(dashboard)" :size="16" /> + <ChevronRight v-else :size="16" /> + </button> + <span class="dashboard-switcher-sidebar__icon"> + <CnDashboardIcon :name="dashboard.icon" :size="20" /> + </span> + <span + v-if="isDefaultDashboard(dashboard)" + class="dashboard-switcher-sidebar__default-marker" + :title=" + t( + 'launchpad', + 'Default dashboard — opens automatically when you visit LaunchPad', + ) + " + :aria-label="t('launchpad', 'Default dashboard')"> + <Star :size="16" /> + </span> + <span class="dashboard-switcher-sidebar__label">{{ + dashboard.name + }}</span> + <DashboardRowActions + :dashboard="dashboard" + :source="section.source" + :canEdit="canEdit" + :defaultUuid="defaultUuid" + :isEditMode="isEditMode" + :activeDashboardId="activeDashboardId" + @toggleEdit="onRowToggleEdit(dashboard, section.source)" + @openConfig="onRowOpenConfig(dashboard, section.source)" + @addWidget=" + onRowAddWidget(dashboard, section.source) + " + @importBookmarks=" + onRowImportBookmarks(dashboard, section.source) + " + @delete="onRowDelete(dashboard, section.source)" + @setDefault="onRowSetDefault(dashboard, section.source)" /> + </li> + </ul> + + <!-- + REQ-SWITCH-008: dedicated "Add Dashboard" card button. Lives + BELOW the personal list (not inside the <ul>), still inside + the scroll container, gated on `allowUserDashboards`. Same + emit contract as the removed inline row. + --> + <div + v-if="section.source === 'user' && allowUserDashboards" + class="dashboard-switcher-sidebar__add-dashboard-card"> + <NcButton + variant="secondary" + wide + data-action="create" + data-testid="add-dashboard-button" + :disabled="dashboardQuotaReached" + :title="dashboardQuotaReached ? dashboardQuotaTooltip : null" :aria-label=" - isExpanded(dashboard) - ? t('launchpad', 'Collapse {name}', { - name: dashboard.name, - }) - : t('launchpad', 'Expand {name}', { - name: dashboard.name, - }) - " - @click.stop="toggleExpanded(dashboard)" - @keydown.enter.stop - @keydown.space.stop> - <ChevronDown v-if="isExpanded(dashboard)" :size="16" /> - <ChevronRight v-else :size="16" /> - </button> - <span class="dashboard-switcher-sidebar__icon"> - <CnDashboardIcon :name="dashboard.icon" :size="20" /> - </span> - <span - v-if="isDefaultDashboard(dashboard)" - class="dashboard-switcher-sidebar__default-marker" - :title=" - t( - 'launchpad', - 'Default dashboard — opens automatically when you visit LaunchPad', - ) + dashboardQuotaReached + ? dashboardQuotaTooltip + : t('launchpad', 'Add dashboard') " - :aria-label="t('launchpad', 'Default dashboard')"> - <Star :size="16" /> - </span> - <span class="dashboard-switcher-sidebar__label">{{ - dashboard.name - }}</span> - <DashboardRowActions - :dashboard="dashboard" - source="shared" - :canEdit="canEdit" - :defaultUuid="defaultUuid" - :isEditMode="isEditMode" - :activeDashboardId="activeDashboardId" - @toggleEdit="onRowToggleEdit(dashboard, 'shared')" - @openConfig="onRowOpenConfig(dashboard, 'shared')" - @addCustomWidget=" - onRowAddCustomWidget(dashboard, 'shared') - " - @delete="onRowDelete(dashboard, 'shared')" - @setDefault="onRowSetDefault(dashboard, 'shared')" /> - </li> - </ul> - </section> + @click="onCreate"> + <template #icon> + <Plus :size="20" /> + </template> + {{ t('launchpad', 'Add dashboard') }} + </NcButton> + <p + v-if="dashboardQuotaReached" + class="dashboard-switcher-sidebar__quota-hint" + data-testid="dashboard-quota-hint"> + {{ dashboardQuotaTooltip }} + </p> + </div> + </section> + </template> </div> <!-- @@ -497,6 +241,119 @@ import Star from 'vue-material-design-icons/Star.vue' import DashboardRowActions from './DashboardRowActions.vue' import DetailFilter from './DetailFilter.vue' import SidebarFooter from './SidebarFooter.vue' +import { + FLAG_PROP, + LIST_PROP, + REQUIRED_FLAG_PROP, + TEXT_PROP, +} from '../../constants/propDefinitions.js' + +/** + * The dashboards of a list that carry a uuid, keyed by it. + * + * @param {Array<object>} list Dashboards of one section. + * @return {Map<string, object>} the dashboards by uuid. + */ +function indexByUuid(list) { + const byUuid = new Map() + for (const dashboard of list) { + if (dashboard?.uuid) { + byUuid.set(dashboard.uuid, dashboard) + } + } + return byUuid +} + +/** + * Split a section into roots and children-per-parent. A parent outside + * the section, or a dashboard naming itself, counts as no parent. + * + * @param {Array<object>} list Dashboards of one section. + * @param {Map<string, object>} byUuid The section's dashboards by uuid. + * @return {{roots: Array<object>, children: Map<string, Array<object>>}} the forest. + */ +function splitForest(list, byUuid) { + const children = new Map() + const roots = [] + for (const dashboard of list) { + const parent = dashboard?.parentUuid + if (parent && parent !== dashboard.uuid && byUuid.has(parent)) { + appendChild(children, { parent, dashboard }) + } else { + roots.push(dashboard) + } + } + return { roots, children } +} + +/** + * Add a dashboard to its parent's children. + * + * @param {Map<string, Array<object>>} children Children per parent uuid. + * @param {{parent: string, dashboard: object}} link The parent uuid and the child. + */ +function appendChild(children, link) { + if (!children.has(link.parent)) { + children.set(link.parent, []) + } + children.get(link.parent).push(link.dashboard) +} + +/** + * Flatten a forest depth-first into rows, descending into a parent only + * when it is open; each dashboard renders once. + * + * @param {{roots: Array<object>, children: Map<string, Array<object>>}} forest The forest. + * @param {function(string): boolean} isOpen Whether a parent uuid is expanded. + * @return {Array<{dashboard: object, depth: number, hasChildren: boolean}>} Rows to render. + */ +function flattenTree(forest, isOpen) { + const rows = [] + const seen = new Set() + const walk = (dashboard, depth) => { + if (!markSeen(seen, dashboard)) { + return + } + const kids = childrenOf(forest, dashboard.uuid) + rows.push({ dashboard, depth, hasChildren: kids.length > 0 }) + if (kids.length > 0 && isOpen(dashboard.uuid)) { + for (const kid of kids) { + walk(kid, depth + 1) + } + } + } + for (const root of forest.roots) { + walk(root, 0) + } + return rows +} + +/** + * Record a dashboard as rendered, keyed by uuid (or id without one). + * + * @param {Set<string|number>} seen The keys rendered so far. + * @param {object} dashboard The dashboard. + * @return {boolean} false when it was already rendered. + */ +function markSeen(seen, dashboard) { + const key = dashboard.uuid ?? dashboard.id + if (seen.has(key)) { + return false + } + seen.add(key) + return true +} + +/** + * The children of a parent uuid, [] when it has none. + * + * @param {{children: Map<string, Array<object>>}} forest The forest. + * @param {string} uuid The parent uuid. + * @return {Array<object>} the children. + */ +function childrenOf(forest, uuid) { + return forest.children.get(uuid) ?? [] +} export default { name: 'DashboardSwitcherSidebar', @@ -516,10 +373,7 @@ export default { props: { /** Detail field definitions for "Filter by detail". */ - filterFields: { - type: Array, - default: () => [], - }, + filterFields: LIST_PROP, /** * Controlled by the parent. Vue 3 removed the component-level @@ -527,10 +381,7 @@ export default { * `v-model` onto `isOpen` / `update:open`, so the host binds the * prop and the `update:open` listener explicitly (see Views.vue). */ - isOpen: { - type: Boolean, - required: true, - }, + isOpen: REQUIRED_FLAG_PROP, /** * Display name of the user's primary group; falls back to the @@ -590,14 +441,11 @@ export default { * Dashboard" card button below the personal list (REQ-SWITCH-008); * when false the card MUST NOT be in the DOM. */ - allowUserDashboards: { - type: Boolean, - default: false, - }, + allowUserDashboards: FLAG_PROP, /* * `canEdit` flows down to each per-row cog (wave3.6) so the - * Edit / Add-custom-widget entries can hide for view-only + * Edit / Add widget entries can hide for view-only * users. Configure / Delete remain owner-gated per row via * `dashboard.isOwner`. The wave3.3 `isEditMode` / * `isActiveOwner` props were removed when the cog moved out @@ -605,10 +453,7 @@ export default { * `dashboard.isOwner`, and Edit/Save toggle is implicit * (the host enters edit mode after switching). */ - canEdit: { - type: Boolean, - default: false, - }, + canEdit: FLAG_PROP, /* * Wave3.7 — UUID of the user's pinned default dashboard, or @@ -616,39 +461,27 @@ export default { * DashboardRowActions so the cog menu can show "Set as default" * vs "Default dashboard" with the right icon. */ - defaultUuid: { - type: String, - default: '', - }, + defaultUuid: TEXT_PROP, /* * Wave3.9 — host's edit-mode boolean. Forwarded down so the * cog button on the active row flips to "Save dashboard" + * ContentSave icon while editing. */ - isEditMode: { - type: Boolean, - default: false, - }, + isEditMode: FLAG_PROP, /** * dashboard-quota-limits REQ-QUOTA-006: when true the user is at * their per-user dashboard limit, so the "Add dashboard" affordance * is disabled. Default false ⇒ unlimited instances are unaffected. */ - dashboardQuotaReached: { - type: Boolean, - default: false, - }, + dashboardQuotaReached: FLAG_PROP, /** * dashboard-quota-limits REQ-QUOTA-006: localised tooltip explaining * the limit, shown on the disabled "Add dashboard" affordance. */ - dashboardQuotaTooltip: { - type: String, - default: '', - }, + dashboardQuotaTooltip: TEXT_PROP, }, emits: [ @@ -664,7 +497,9 @@ export default { // switch-then-apply orchestration. 'toggleEdit', 'openConfig', - 'addCustomWidget', + 'addWidget', + // launcher-bookmark-import REQ-BMI-001 — `(dashboard, source)`. + 'importBookmarks', // wave3.7 — `(dashboard, source)`. The host pins this row as // the user's default via `POST /api/dashboards/default`. 'setDefault', @@ -705,6 +540,24 @@ export default { return this.groupDashboards.filter((d) => d.source === 'shared') }, + /** + * The sections that render, in order, each with its `source` + * discriminator (load-bearing for the emits), heading and rows. + * Empty sections are left out entirely (no orphan headings); the + * personal section shows when it has rows or creation is allowed. + * + * @return {Array<{source: string, heading: string, dashboards: Array<object>}>} the visible sections. + * @spec openspec/specs/dashboard-switcher/spec.md + */ + visibleSections() { + return [ + { source: 'group', heading: this.primaryGroupHeading, dashboards: this.primaryGroupDashboards, visible: this.primaryGroupDashboards.length > 0 }, + { source: 'default', heading: t('launchpad', 'Default'), dashboards: this.defaultGroupDashboards, visible: this.defaultGroupDashboards.length > 0 }, + { source: 'user', heading: t('launchpad', 'My Dashboards'), dashboards: this.userDashboards, visible: this.showPersonalSection }, + { source: 'shared', heading: t('launchpad', 'Shared with you'), dashboards: this.sharedDashboards, visible: this.sharedDashboards.length > 0 }, + ].filter((section) => section.visible) + }, + /** @spec openspec/specs/dashboard-switcher/spec.md */ primaryGroupHeading() { return this.groupName || t('launchpad', 'Dashboards') @@ -789,49 +642,13 @@ export default { * @spec openspec/specs/dashboards/spec.md */ treeRows(list) { - const byUuid = new Map() - for (const dashboard of list) { - if (dashboard?.uuid) { - byUuid.set(dashboard.uuid, dashboard) - } - } - const children = new Map() - const roots = [] - for (const dashboard of list) { - const parent = dashboard?.parentUuid - if (parent && parent !== dashboard.uuid && byUuid.has(parent)) { - if (!children.has(parent)) { - children.set(parent, []) - } - children.get(parent).push(dashboard) - } else { - roots.push(dashboard) - } - } + const byUuid = indexByUuid(list) + const forest = splitForest(list, byUuid) const openChain = this.activeChain(byUuid) - const rows = [] - const seen = new Set() - const walk = (dashboard, depth) => { - if (seen.has(dashboard.uuid ?? dashboard.id)) { - return - } - seen.add(dashboard.uuid ?? dashboard.id) - const kids = children.get(dashboard.uuid) ?? [] - rows.push({ dashboard, depth, hasChildren: kids.length > 0 }) - if ( - kids.length > 0 - && (this.expanded[dashboard.uuid] === true - || openChain.has(dashboard.uuid)) - ) { - for (const kid of kids) { - walk(kid, depth + 1) - } - } - } - for (const root of roots) { - walk(root, 0) - } - return rows + return flattenTree( + forest, + (uuid) => this.expanded[uuid] === true || openChain.has(uuid), + ) }, /** @@ -971,8 +788,19 @@ export default { * @param {'group'|'default'|'user'|'shared'} source Row section discriminator. * @spec openspec/specs/dashboard-switcher/spec.md */ - onRowAddCustomWidget(dashboard, source) { - this.$emit('addCustomWidget', dashboard, source) + onRowAddWidget(dashboard, source) { + this.$emit('addWidget', dashboard, source) + }, + + /** + * Re-emit the row's "Import bookmarks" action upward. + * + * @param {object} dashboard Row payload. + * @param {'group'|'default'|'user'} source Row section discriminator. + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md + */ + onRowImportBookmarks(dashboard, source) { + this.$emit('importBookmarks', dashboard, source) }, /** @@ -1020,8 +848,18 @@ export default { this.$emit('update:open', false) }, - /** @spec openspec/specs/dashboard-switcher/spec.md */ - onEscClose() { + /** + * Escape closes the sidebar, unless it was meant for an open menu + * inside it (a row's action menu keeps focus on its toggle, which + * reports `aria-expanded="true"`): that Escape closes the menu only. + * + * @param {KeyboardEvent} event the keydown. + * @spec openspec/specs/dashboard-switcher/spec.md + */ + onEscClose(event) { + if (event?.target?.closest?.('[aria-expanded="true"], [role="menu"]')) { + return + } if (this.isOpen) { this.$emit('update:open', false) } @@ -1167,31 +1005,6 @@ export default { font-size: 14px; } -.dashboard-switcher-sidebar__delete { - display: none; - background: transparent; - border: 0; - padding: 2px; - border-radius: 3px; - cursor: pointer; - color: var(--color-text-maxcontrast, #757575); - align-items: center; - justify-content: center; -} - -.dashboard-switcher-sidebar__delete:hover, -.dashboard-switcher-sidebar__delete:focus { - background: var(--color-background-darker, #ececec); - color: var(--color-error, #c0392b); -} - -.dashboard-switcher-sidebar__item--personal:hover - .dashboard-switcher-sidebar__delete, -.dashboard-switcher-sidebar__item--personal:focus-within - .dashboard-switcher-sidebar__delete { - display: inline-flex; -} - .dashboard-switcher-sidebar__add-dashboard-card { display: flex; padding: 8px 16px 4px 16px; diff --git a/src/components/Workspace/DetailFilter.vue b/src/components/Workspace/DetailFilter.vue index a695f93ce..cf8419aea 100644 --- a/src/components/Workspace/DetailFilter.vue +++ b/src/components/Workspace/DetailFilter.vue @@ -28,6 +28,7 @@ <script> import { NcSelect } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' +import { LIST_PROP } from '../../constants/propDefinitions.js' /** * DetailFilter: "Filter by detail" in the dashboard switcher. Offered only @@ -45,10 +46,7 @@ export default { props: { /** Detail field definitions (`key`, `label`, `type`, `options`). */ - fields: { - type: Array, - default: () => [], - }, + fields: LIST_PROP, }, emits: ['change'], diff --git a/src/components/Workspace/EditLockBanner.vue b/src/components/Workspace/EditLockBanner.vue index cc14eb7f1..b7185c835 100644 --- a/src/components/Workspace/EditLockBanner.vue +++ b/src/components/Workspace/EditLockBanner.vue @@ -28,6 +28,11 @@ <script> import { NcButton, NcNoteCard } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' +import { + FLAG_PROP, + REQUIRED_TEXT_PROP, + TEXT_PROP, +} from '../../constants/propDefinitions.js' /** * EditLockBanner: what the workspace page says when it cannot let the @@ -46,15 +51,9 @@ export default { props: { /** Lock status from `useDashboardLock`. */ - status: { - type: String, - required: true, - }, + status: REQUIRED_TEXT_PROP, - holderName: { - type: String, - default: '', - }, + holderName: TEXT_PROP, /** Seconds until the colleague's lock ends if they stop refreshing it. */ expiresIn: { @@ -62,10 +61,7 @@ export default { default: null, }, - isAdmin: { - type: Boolean, - default: false, - }, + isAdmin: FLAG_PROP, }, emits: ['takeOver'], diff --git a/src/components/Workspace/FilterBreadcrumb.vue b/src/components/Workspace/FilterBreadcrumb.vue new file mode 100644 index 000000000..344c94108 --- /dev/null +++ b/src/components/Workspace/FilterBreadcrumb.vue @@ -0,0 +1,159 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div v-if="trails.length > 0" class="filter-breadcrumb" data-testid="filter-breadcrumbs"> + <nav + v-for="trail in trails" + :key="trail.id" + class="filter-breadcrumb__trail" + :aria-label="t('launchpad', 'Drill-down path')" + :data-hierarchy="trail.id" + data-testid="filter-breadcrumb"> + <ol class="filter-breadcrumb__list"> + <li + v-for="(step, index) in trail.steps" + :key="step.dimension" + class="filter-breadcrumb__item" + :data-dimension="step.dimension"> + <span + v-if="index === trail.steps.length - 1" + class="filter-breadcrumb__current" + aria-current="location" + data-testid="filter-breadcrumb-step">{{ crumbText(step) }}</span> + <button + v-else + type="button" + class="filter-breadcrumb__link" + :aria-label="t('launchpad', 'Back to {step}', { step: crumbText(step) })" + data-testid="filter-breadcrumb-step" + @click="$emit('pop', step.dimension)"> + {{ crumbText(step) }} + </button> + <span + v-if="index < trail.steps.length - 1" + class="filter-breadcrumb__separator" + aria-hidden="true">></span> + </li> + </ol> + </nav> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { breadcrumbPath } from '../../composables/useFilterBus.js' +import { LIST_PROP, OBJECT_PROP } from '../../constants/propDefinitions.js' + +/** + * FilterBreadcrumb: the drill-down path of each of the dashboard's + * hierarchies (drill-down-cross-widget-filter REQ-CWF-004), such as + * "Province PV26 > Municipality GM0355 > District WK035501". Each level above + * the deepest is a button that goes back up to that level (`pop` with its + * dimension); the deepest level is the current one. A hierarchy with no + * active level shows no path, and without any the component renders nothing. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ +export default { + name: 'FilterBreadcrumb', + + props: { + /** The dashboard's hierarchy descriptors. */ + hierarchies: LIST_PROP, + /** The bus's clauses. */ + clauses: LIST_PROP, + /** A display label per dimension; the stored level label when absent. */ + labels: OBJECT_PROP, + }, + + emits: ['pop'], + + computed: { + /** + * The path of each hierarchy that has an active level. + * + * @return {Array<{id: string, steps: Array<object>}>} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ + trails() { + return this.hierarchies + .filter((hierarchy) => hierarchy && typeof hierarchy.id === 'string') + .map((hierarchy) => ({ id: hierarchy.id, steps: breadcrumbPath(this.hierarchies, this.clauses, hierarchy.id) })) + .filter((trail) => trail.steps.length > 0) + }, + }, + + methods: { + t, + + /** + * A step as the reader sees it: the level's label and its value. + * + * @param {{dimension: string, label: string, value: unknown}} step The step. + * @return {string} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ + crumbText(step) { + const label = this.labels[step.dimension] || step.label || step.dimension + const value = Array.isArray(step.value) ? step.value.join(', ') : String(step.value ?? '') + return `${label} ${value}` + }, + }, +} +</script> + +<style scoped> +.filter-breadcrumb { + display: flex; + flex-direction: column; + gap: 4px; + margin: 0 0 8px; +} + +.filter-breadcrumb__list { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + margin: 0; + padding: 0; + list-style: none; +} + +.filter-breadcrumb__item { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.filter-breadcrumb__link { + min-height: 24px; + margin: 0; + padding: 0 4px; + border: none; + border-radius: var(--border-radius-small); + background: transparent; + color: var(--color-main-text); + font: inherit; + text-decoration: underline; + cursor: pointer; +} + +.filter-breadcrumb__link:hover, +.filter-breadcrumb__link:focus-visible { + background-color: var(--color-background-hover); +} + +.filter-breadcrumb__current { + padding: 0 4px; + font-weight: bold; + color: var(--color-main-text); +} + +.filter-breadcrumb__separator { + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/Workspace/HiddenWidgetsControl.vue b/src/components/Workspace/HiddenWidgetsControl.vue index 1c2e15106..afaf31c90 100644 --- a/src/components/Workspace/HiddenWidgetsControl.vue +++ b/src/components/Workspace/HiddenWidgetsControl.vue @@ -46,17 +46,25 @@ </NcButton> </div> </NcPopover> - <ResetPersonalViewDialog - :open="resetOpen" - @update:open="resetOpen = $event" - @confirm="confirmReset" /> + <CnConfirmDialog + v-if="resetOpen" + :dialogTitle="t('launchpad', 'Reset your view?')" + :message=" + t( + 'launchpad', + 'Every widget you hid comes back, and the dashboard looks the way its owner set it up.', + ) + " + :confirmLabel="t('launchpad', 'Reset my view')" + @confirm="confirmReset" + @close="resetOpen = false" /> </div> </template> <script> -import { NcButton, NcPopover } from '@conduction/nextcloud-vue' +import { CnConfirmDialog, NcButton, NcPopover } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' -import ResetPersonalViewDialog from '../../dialogs/ResetPersonalViewDialog.vue' +import { LIST_PROP } from '../../constants/propDefinitions.js' import { resolveWidgetTitle } from '../../utils/widgetTitle.js' /** @@ -72,21 +80,15 @@ export default { components: { NcButton, NcPopover, - ResetPersonalViewDialog, + CnConfirmDialog, }, props: { /** Hidden placements (WidgetPlacement::jsonSerialize rows). */ - hiddenPlacements: { - type: Array, - default: () => [], - }, + hiddenPlacements: LIST_PROP, /** Widget catalog, for naming Nextcloud dashboard widgets. */ - availableWidgets: { - type: Array, - default: () => [], - }, + availableWidgets: LIST_PROP, }, emits: ['showAgain', 'reset'], diff --git a/src/components/Workspace/InstallBanner.vue b/src/components/Workspace/InstallBanner.vue new file mode 100644 index 000000000..0b1517d5c --- /dev/null +++ b/src/components/Workspace/InstallBanner.vue @@ -0,0 +1,223 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div + v-if="shown" + class="launchpad-install-banner" + role="region" + :aria-label="t('launchpad', 'Put LaunchPad on your home screen')" + data-testid="install-banner"> + <NcNoteCard type="info"> + <p class="launchpad-install-banner__title"> + <strong>{{ t('launchpad', 'Put LaunchPad on your home screen') }}</strong> + </p> + <p>{{ t('launchpad', 'Then your workplace opens with one tap, like an app') }}</p> + <p + v-if="showSteps" + class="launchpad-install-banner__steps" + role="status" + data-testid="install-banner-steps"> + {{ t('launchpad', 'In your browser, choose Share and then Add to Home Screen.') }} + </p> + <div class="launchpad-install-banner__actions"> + <NcButton + variant="tertiary" + data-testid="install-banner-not-now" + @click="notNow"> + {{ t('launchpad', 'Not now') }} + </NcButton> + <NcButton + variant="primary" + data-testid="install-banner-install" + @click="install"> + {{ t('launchpad', 'Install') }} + </NcButton> + </div> + </NcNoteCard> + </div> +</template> + +<script> +import { NcButton, NcNoteCard } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { FLAG_PROP } from '../../constants/propDefinitions.js' +import { + clearPrompt, + installPrompt, + isStandalone, + readNotNowAt, + shouldShowInstallBanner, + writeNotNowAt, +} from '../../utils/installPrompt.js' + +/** + * The browser storage, or null where reading it throws. + * + * @return {Storage|null} + */ +function browserStorage() { + try { + return window.localStorage + } catch { + return null + } +} + +/** + * InstallBanner: on a phone, offers to put LaunchPad on the home screen + * (board LpMobiel). Install opens the browser's prompt, or shows the steps + * where the browser has none; Not now hides it on this device for 30 days. + * + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ +export default { + name: 'InstallBanner', + + components: { + NcButton, + NcNoteCard, + }, + + props: { + /** Whether this is the kiosk view: no banner there. */ + kiosk: FLAG_PROP, + /** Whether this is a public page: no banner there. */ + isPublic: FLAG_PROP, + }, + + data() { + return { + width: window.innerWidth, + standalone: isStandalone(window), + notNowAt: readNotNowAt(browserStorage()), + showSteps: false, + } + }, + + computed: { + /** + * Whether the banner shows now. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + shown() { + return shouldShowInstallBanner({ + width: this.width, + standalone: this.standalone, + kiosk: this.kiosk, + isPublic: this.isPublic, + notNowAt: this.notNowAt, + now: Date.now(), + }) + }, + }, + + /** + * Follow the width and a finished install. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + mounted() { + window.addEventListener('resize', this.onResize) + window.addEventListener('appinstalled', this.onInstalled) + }, + + /** + * Stop following them. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + beforeUnmount() { + window.removeEventListener('resize', this.onResize) + window.removeEventListener('appinstalled', this.onInstalled) + }, + + methods: { + t, + + /** + * Follow the viewport width. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + onResize() { + this.width = window.innerWidth + }, + + /** + * The page was installed: the banner goes. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + onInstalled() { + this.standalone = true + }, + + /** + * Open the browser's install prompt, or show the steps where the + * browser offers none. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + async install() { + const prompt = installPrompt() + if (!prompt || typeof prompt.prompt !== 'function') { + this.showSteps = true + return + } + clearPrompt() + try { + await prompt.prompt() + const choice = prompt.userChoice ? await prompt.userChoice : null + if (choice && choice.outcome === 'accepted') { + this.standalone = true + } + } catch { + this.showSteps = true + } + }, + + /** + * Hide the banner on this device for 30 days. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + notNow() { + const now = Date.now() + writeNotNowAt(browserStorage(), now) + this.notNowAt = now + }, + }, +} +</script> + +<style scoped> +.launchpad-install-banner { + margin: 0 0 12px; +} + +.launchpad-install-banner__title { + margin: 0 0 4px; +} + +.launchpad-install-banner__steps { + margin-top: 8px; +} + +.launchpad-install-banner__actions { + display: flex; + gap: 8px; + justify-content: flex-end; + margin-top: 8px; +} +</style> diff --git a/src/components/Workspace/LaunchpadMoreMenu.vue b/src/components/Workspace/LaunchpadMoreMenu.vue new file mode 100644 index 000000000..67ae5bccd --- /dev/null +++ b/src/components/Workspace/LaunchpadMoreMenu.vue @@ -0,0 +1,564 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 + - + - LaunchpadMoreMenu: the one More menu of launchpad, the same on every page + - (board LpMeer). A 600 px popover with two columns: Dashboards on the + - left, This dashboard and below it the expandable Settings item on the + - right; one column under 960 px, in that same order. + - + - Settings is one menu item (cog, chevron, aria-haspopup, aria-expanded) + - below a rule. It unfolds in place as an indented group with a rule at its + - start, and starts folded every time the menu opens. + - + - Keyboard: the arrow keys move through every visible item over both + - columns, Home and End jump to the first and last, Right unfolds Settings + - and Left folds it again, Escape closes the menu and returns focus to More. +--> +<template> + <NcPopover + v-model:shown="open" + class="lp-more-menu" + placement="bottom-end" + popupRole="menu" + :setReturnFocus="returnFocus" + data-testid="launchpad-more-menu-popover" + @afterShow="focusItem(0)"> + <template #trigger="{ attrs }"> + <NcButton + ref="trigger" + v-bind="attrs" + variant="secondary" + class="lp-more-menu__trigger" + data-testid="launchpad-more-menu-trigger"> + <template #icon> + <DotsHorizontal :size="20" /> + </template> + {{ triggerLabel }} + </NcButton> + </template> + <div + ref="panel" + class="lp-more-menu__panel" + :class="{ 'lp-more-menu__panel--single': !twoColumns }" + role="menu" + :aria-label="triggerLabel" + data-testid="launchpad-more-menu-panel" + @keydown="onKeydown"> + <div v-if="dashboards.length > 0" class="lp-more-menu__column"> + <div + class="lp-more-menu__group" + role="group" + :aria-labelledby="`${domId}-dashboards`" + data-testid="launchpad-more-menu-group-dashboards"> + <span :id="`${domId}-dashboards`" class="lp-more-menu__title"> + {{ t('launchpad', 'Dashboards') }} + </span> + <LaunchpadMoreMenuItem + v-for="item in dashboards" + :key="item.id" + :item="item" + @click="choose($event, item)" /> + </div> + </div> + <div v-if="hasEndColumn" class="lp-more-menu__column"> + <div + v-if="hasActions" + class="lp-more-menu__group" + role="group" + :aria-labelledby="`${domId}-actions`" + data-testid="launchpad-more-menu-group-this-dashboard"> + <span :id="`${domId}-actions`" class="lp-more-menu__title"> + {{ t('launchpad', 'This dashboard') }} + </span> + <LaunchpadMoreMenuItem + v-for="item in actions" + :key="item.id" + :item="item" + @click="choose($event, item)" /> + </div> + <template v-if="settings.length > 0"> + <button + type="button" + class="lp-more-menu__item lp-more-menu__settings" + :class="{ 'lp-more-menu__settings--open': settingsOpen }" + role="menuitem" + aria-haspopup="true" + :aria-expanded="settingsOpen ? 'true' : 'false'" + :aria-controls="`${domId}-settings`" + tabindex="-1" + data-testid="launchpad-more-menu-settings" + @click="settingsOpen = !settingsOpen"> + <span class="lp-more-menu__icon" aria-hidden="true"> + <Cog :size="18" /> + </span> + <span class="lp-more-menu__label">{{ t('launchpad', 'Settings') }}</span> + <span class="lp-more-menu__chevron" aria-hidden="true"> + <ChevronDown v-if="settingsOpen" :size="18" /> + <ChevronRight v-else :size="18" /> + </span> + </button> + <div + v-show="settingsOpen" + :id="`${domId}-settings`" + class="lp-more-menu__subgroup" + role="group" + :aria-label="t('launchpad', 'Settings')" + data-testid="launchpad-more-menu-group-settings"> + <LaunchpadMoreMenuItem + v-for="item in settings" + :key="item.id" + :item="item" + class="lp-more-menu__subitem" + @click="choose($event, item)" /> + </div> + </template> + </div> + </div> + </NcPopover> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcButton, NcPopover } from '@nextcloud/vue' +import ChevronDown from 'vue-material-design-icons/ChevronDown.vue' +import ChevronRight from 'vue-material-design-icons/ChevronRight.vue' +import Cog from 'vue-material-design-icons/Cog.vue' +import DotsHorizontal from 'vue-material-design-icons/DotsHorizontal.vue' +import LaunchpadMoreMenuItem from './LaunchpadMoreMenuItem.vue' + +let menuCounter = 0 + +export default { + name: 'LaunchpadMoreMenu', + + components: { + ChevronDown, + ChevronRight, + Cog, + DotsHorizontal, + LaunchpadMoreMenuItem, + NcButton, + NcPopover, + }, + + props: { + /** + * The Dashboards group: `{ id, label, icon?, meta?, checked?, href?, + * to?, onClick? }`. `checked` (true or false) makes a radio item. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + dashboards: { + type: Array, + default: () => [], + }, + + /** The items under Settings: `{ id, label, icon?, href?, target?, to?, onClick? }`. */ + settings: { + type: Array, + default: () => [], + }, + + /** + * The This dashboard group: `{ id, label, icon?, destructive?, + * onClick? }`. A destructive item goes last, in the error colour. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + actions: { + type: Array, + default: () => [], + }, + }, + + emits: ['open', 'select'], + + data() { + return { + open: false, + settingsOpen: false, + domId: `lp-more-menu-${++menuCounter}`, + } + }, + + computed: { + /** + * The button's text and the menu's name. + * + * @return {string} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + triggerLabel() { + return t('launchpad', 'More') + }, + + /** + * Whether the This dashboard column is drawn. + * + * @return {boolean} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + hasActions() { + return this.actions.length > 0 + }, + + /** + * Whether the right column is drawn: This dashboard, Settings or both. + * + * @return {boolean} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + hasEndColumn() { + return this.hasActions || this.settings.length > 0 + }, + + /** + * Whether the menu has two columns: Dashboards beside the right column. + * + * @return {boolean} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + twoColumns() { + return this.dashboards.length > 0 && this.hasEndColumn + }, + }, + + watch: { + /** + * Opening folds Settings again and tells the host. + * + * @param {boolean} isOpen Whether the menu is open. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + open(isOpen) { + if (isOpen) { + this.settingsOpen = false + this.$emit('open') + } + }, + }, + + methods: { + t, + + /** + * Choose an item: run it, report it and close the menu. + * + * @param {MouseEvent} event The click. + * @param {object} item The item. + * @return {void} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + choose(event, item) { + if (typeof item.onClick === 'function') { + item.onClick(item) + } + this.$emit('select', item) + this.open = false + }, + + /** + * The visible items in reading order, as elements. + * + * @return {HTMLElement[]} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + itemElements() { + const panel = this.$refs.panel + if (!panel) { + return [] + } + return [...panel.querySelectorAll('.lp-more-menu__item')] + .filter((el) => !el.closest('.lp-more-menu__subgroup') || this.settingsOpen) + }, + + /** + * Move focus to the item at an index, wrapping around. + * + * @param {number} index The index. + * @return {void} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + focusItem(index) { + const items = this.itemElements() + if (items.length === 0) { + return + } + const at = ((index % items.length) + items.length) % items.length + items[at].focus() + }, + + /** + * Unfold or fold Settings from the keyboard, keeping focus on a + * visible item. + * + * @param {boolean} unfold Whether to unfold. + * @param {EventTarget} from The focused element. + * @return {Promise<boolean>} Whether the key was used. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + async toggleSettingsFromKey(unfold, from) { + const toggle = this.$refs.panel?.querySelector('.lp-more-menu__settings') + if (!toggle) { + return false + } + if (unfold && from === toggle) { + this.settingsOpen = true + await this.$nextTick() + this.$refs.panel.querySelector('.lp-more-menu__subitem')?.focus() + return true + } + const inGroup = from instanceof Element && from.closest('.lp-more-menu__subgroup') + if (!unfold && (from === toggle || inGroup)) { + this.settingsOpen = false + toggle.focus() + return true + } + return false + }, + + /** + * The menu's keys. + * + * @param {KeyboardEvent} event The key. + * @return {Promise<void>} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + async onKeydown(event) { + if (event.key === 'Escape') { + event.preventDefault() + event.stopPropagation() + this.open = false + this.$refs.trigger?.$el?.focus?.() + return + } + if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') { + event.preventDefault() + await this.toggleSettingsFromKey(event.key === 'ArrowRight', document.activeElement) + return + } + const items = this.itemElements() + const current = items.indexOf(document.activeElement) + const moves = { + ArrowDown: current + 1, + ArrowUp: current < 0 ? items.length - 1 : current - 1, + Home: 0, + End: items.length - 1, + } + if (!(event.key in moves)) { + return + } + event.preventDefault() + this.focusItem(moves[event.key]) + }, + + /** + * Where focus goes when the menu closes: back to More. + * + * @return {HTMLElement|false} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + returnFocus() { + return this.$refs.trigger?.$el ?? false + }, + }, +} +</script> + +<style> +/* Not scoped: LaunchpadMoreMenuItem draws the items with these classes. */ + +/* The More button is 40px high, and open it is tinted with a brand border + (LpWerkplek, LpVandaag). */ +.lp-more-menu__trigger { + --default-clickable-area: 40px; + min-height: 40px; +} + +.lp-more-menu__trigger[aria-expanded='true']:not(#lp-more-menu-a) { + border-color: var(--color-primary-element) !important; + background-color: var(--color-primary-element-light) !important; + color: var(--color-primary-element-light-text) !important; +} + +.lp-more-menu__panel { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 4px 12px; + box-sizing: border-box; + width: min(600px, calc(100vw - 32px)); + max-height: calc(100vh - 120px); + overflow: auto; + padding: 10px 10px 12px; +} + +.lp-more-menu__panel--single { + grid-template-columns: minmax(0, 1fr); + width: min(320px, calc(100vw - 32px)); +} + +.lp-more-menu__column, +.lp-more-menu__group, +.lp-more-menu__subgroup { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; +} + +.lp-more-menu__title { + padding: 10px 10px 4px; + font-size: 12px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--color-text-maxcontrast); +} + +.lp-more-menu__item { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + min-height: 32px; + margin: 0; + padding: 0 10px; + border: none; + border-radius: var(--border-radius-element, 6px); + background: transparent; + color: var(--color-main-text); + font: inherit; + font-size: 14px; + text-align: start; + text-decoration: none; + cursor: pointer; +} + +/* A theme that underlines, colours and bolds every link and button with + `!important` and an id in its selector made the link items look different + from the button items. The two `:not(#…)` raise this rule above it. */ +/* The same theme also gives every button a tinted background, a height and + padding of its own and no border, so each row read as a selected button + and the rules above Delete and Settings were gone (LpMeer). */ +.lp-more-menu__item:not(#lp-more-menu-a):not(#lp-more-menu-b) { + min-height: 34px !important; + padding: 0 10px !important; + border-top: none !important; + background: transparent !important; + color: var(--color-main-text) !important; + font-weight: 400 !important; + text-decoration: none !important; +} + +.lp-more-menu__item:not(#lp-more-menu-a):not(#lp-more-menu-b):hover, +.lp-more-menu__item:not(#lp-more-menu-a):not(#lp-more-menu-b):focus-visible { + background: var(--color-background-hover) !important; +} + +.lp-more-menu__item--checked:not(#lp-more-menu-a):not(#lp-more-menu-b) { + background: var(--color-primary-element-light) !important; + color: var(--color-primary-element-light-text) !important; + font-weight: 600 !important; +} + +.lp-more-menu__item--destructive:not(#lp-more-menu-a):not(#lp-more-menu-b) { + border-top: 1px solid var(--color-border) !important; + color: var(--color-error-text, var(--color-error)) !important; +} + +.lp-more-menu__settings:not(#lp-more-menu-a):not(#lp-more-menu-b) { + min-height: 38px !important; + padding-top: 6px !important; + border-top: 1px solid var(--color-border) !important; +} + +.lp-more-menu__column > .lp-more-menu__settings:first-child:not(#lp-more-menu-a):not(#lp-more-menu-b) { + padding-top: 0 !important; + border-top: none !important; +} + +.lp-more-menu__settings--open:not(#lp-more-menu-a):not(#lp-more-menu-b) { + font-weight: 600 !important; +} + +.lp-more-menu__item:hover, +.lp-more-menu__item:focus-visible { + background: var(--color-background-hover); +} + +.lp-more-menu__item:focus-visible { + outline: 2px solid var(--color-primary-element); + outline-offset: -2px; +} + +.lp-more-menu__item--checked { + background: var(--color-primary-element-light); +} + +.lp-more-menu__settings { + min-height: 38px; + margin-top: 6px; + padding-top: 6px; + border-top: 1px solid var(--color-border); + border-radius: 0; +} + +/* Settings alone at the top of a column needs no rule above it. */ +.lp-more-menu__column > .lp-more-menu__settings:first-child { + margin-top: 0; + padding-top: 0; + border-top: none; +} + +.lp-more-menu__subgroup { + margin: 0 0 4px 18px; + padding-inline-start: 8px; + border-inline-start: 2px solid var(--color-border); +} + +.lp-more-menu__item--destructive { + margin-top: 4px; + border-top: 1px solid var(--color-border); + border-radius: 0 0 var(--border-radius-element, 6px) var(--border-radius-element, 6px); +} + +.lp-more-menu__icon, +.lp-more-menu__chevron { + display: inline-flex; + flex: none; + width: 18px; + justify-content: center; +} + +.lp-more-menu__chevron { + color: var(--color-text-maxcontrast); +} + +.lp-more-menu__label { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.lp-more-menu__meta { + flex: none; + font-size: 12px; + font-weight: 400; + color: var(--color-text-maxcontrast); +} + +@media (max-width: 960px) { + .lp-more-menu__panel { + grid-template-columns: minmax(0, 1fr); + width: min(320px, calc(100vw - 32px)); + } + + /* Stacked, Settings follows the Dashboards group and keeps its rule. */ + .lp-more-menu__column + .lp-more-menu__column > .lp-more-menu__settings:first-child { + margin-top: 6px; + padding-top: 6px; + border-top: 1px solid var(--color-border); + } +} +</style> diff --git a/src/components/Workspace/LaunchpadMoreMenuItem.vue b/src/components/Workspace/LaunchpadMoreMenuItem.vue new file mode 100644 index 000000000..a4e15a3c8 --- /dev/null +++ b/src/components/Workspace/LaunchpadMoreMenuItem.vue @@ -0,0 +1,73 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 + - + - LaunchpadMoreMenuItem: one item of the More menu (LaunchpadMoreMenu), as a + - link (`href`), a router link (`to`) or a button. An item with `checked` + - is a radio item; a destructive one is drawn in the error colour. +--> +<template> + <component + :is="tag" + v-bind="attributes" + class="lp-more-menu__item" + :class="{ + 'lp-more-menu__item--checked': item.checked === true, + 'lp-more-menu__item--destructive': item.destructive === true, + }" + :role="item.checked === undefined ? 'menuitem' : 'menuitemradio'" + :aria-checked="item.checked === undefined ? undefined : String(item.checked === true)" + tabindex="-1" + :data-testid="`launchpad-more-menu-item-${item.id}`"> + <span class="lp-more-menu__icon" aria-hidden="true"> + <component :is="item.icon" v-if="item.icon" :size="18" /> + </span> + <span class="lp-more-menu__label">{{ item.label }}</span> + <span v-if="item.meta" class="lp-more-menu__meta">{{ item.meta }}</span> + </component> +</template> + +<script> +import { REQUIRED_OBJECT_PROP } from '../../constants/propDefinitions.js' + +export default { + name: 'LaunchpadMoreMenuItem', + + props: { + /** + * The item: `{ id, label, icon?, meta?, checked?, destructive?, href?, + * target?, to? }`. + */ + item: REQUIRED_OBJECT_PROP, + }, + + computed: { + /** + * The element the item renders as. + * + * @return {string} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + tag() { + if (this.item.href) { + return 'a' + } + return this.item.to ? 'router-link' : 'button' + }, + + /** + * The attributes of the item's element. + * + * @return {object} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + attributes() { + if (this.tag === 'a') { + const target = this.item.target || undefined + return { href: this.item.href, target, rel: target === '_blank' ? 'noopener noreferrer' : undefined } + } + return this.tag === 'router-link' ? { to: this.item.to } : { type: 'button' } + }, + }, +} +</script> diff --git a/src/components/Workspace/PhoneHiddenNotice.vue b/src/components/Workspace/PhoneHiddenNotice.vue new file mode 100644 index 000000000..993d01c7b --- /dev/null +++ b/src/components/Workspace/PhoneHiddenNotice.vue @@ -0,0 +1,99 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div + v-if="sentence" + class="launchpad-phone-hidden" + role="status" + data-testid="phone-hidden-notice"> + <NcNoteCard type="info"> + <p class="launchpad-phone-hidden__text"> + <span data-testid="phone-hidden-sentence">{{ sentence }}</span> + <NcButton + variant="tertiary" + class="launchpad-phone-hidden__which" + :aria-expanded="explained ? 'true' : 'false'" + data-testid="phone-hidden-which" + @click="explained = !explained"> + {{ t('launchpad', 'Which?') }} + </NcButton> + </p> + <p + v-if="explained" + class="launchpad-phone-hidden__why" + data-testid="phone-hidden-why"> + {{ t('launchpad', 'Some widgets need a larger screen, so a phone hides them. On a tablet or computer you see them as usual.') }} + </p> + </NcNoteCard> + </div> +</template> + +<script> +import { NcButton, NcNoteCard } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { phoneHiddenSentence } from '../../utils/phoneHiddenWidgets.js' + +/** + * PhoneHiddenNotice: on a phone, says how many widgets are hidden and names + * them (three, then "and N more"), with "Which?" explaining why. It offers + * no desktop layout (board LpMobiel). + * + * @spec openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/specs/launchpad-mobile-remote-access/spec.md#requirement-the-phone-notice-names-the-hidden-widgets-req-mra-007 + */ +export default { + name: 'PhoneHiddenNotice', + + components: { + NcButton, + NcNoteCard, + }, + + props: { + /** The titles of the widgets the phone hides. */ + titles: { + type: Array, + default: () => [], + }, + }, + + data() { + return { + explained: false, + } + }, + + computed: { + /** + * The notice sentence, empty when nothing is hidden. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/specs/launchpad-mobile-remote-access/spec.md#requirement-the-phone-notice-names-the-hidden-widgets-req-mra-007 + */ + sentence() { + return phoneHiddenSentence(this.titles) + }, + }, + + methods: { + t, + }, +} +</script> + +<style scoped> +.launchpad-phone-hidden { + margin: 0 0 12px; +} + +.launchpad-phone-hidden__text, +.launchpad-phone-hidden__why { + margin: 0; +} + +.launchpad-phone-hidden__why { + margin-top: 4px; +} +</style> diff --git a/src/components/Workspace/StartPageMenu.vue b/src/components/Workspace/StartPageMenu.vue new file mode 100644 index 000000000..b49ae2b4d --- /dev/null +++ b/src/components/Workspace/StartPageMenu.vue @@ -0,0 +1,174 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 + - + - StartPageMenu: the More menu on every page but the dashboard view, and in + - the workspace's empty state (runtime-shell REQ-SHELL-009, REQ-SHELL-013). + - It is the same menu as the dashboard view's (board LpMeer): the + - dashboards, then Settings unfolding in place. There is no open dashboard + - here, so there is no This dashboard group. Choosing a dashboard opens it. +--> + +<template> + <LaunchpadMoreMenu + v-if="chrome.railSuppressed" + :dashboards="dashboards" + :settings="settings" + class="launchpad-start-page-menu" + data-walkthrough-id="launchpad-more-menu" + data-testid="launchpad-more-menu" + @open="onOpen" /> +</template> + +<script> +import { mapState } from 'pinia' +import LaunchpadMoreMenu from './LaunchpadMoreMenu.vue' +import { api } from '../../services/api.js' +import { useDashboardStore } from '../../stores/dashboard.js' +import { logger } from '../../utils/logger.js' +import { + dashboardItems, + readChrome, + settingsMenuItems, + startPageSections, +} from './moreMenuItems.js' + +export default { + name: 'StartPageMenu', + + components: { + LaunchpadMoreMenu, + }, + + inject: { + /** + * What `App.vue` decided about the panel: whether it is left out on + * this route, the entries it would have shown, and who is looking. + * + * @type {{ value: { railSuppressed: boolean, entries: object[], isAdmin: boolean, includePersonalSettings: boolean } }} + */ + launchpadChrome: { + from: 'launchpadChrome', + default: null, + }, + + /** + * The shared library's opener for the per-user settings dialog, + * provided by `CnAppRoot`. Absent outside the shell (tests). + * + * @type {(() => void)|null} + */ + cnOpenUserSettings: { + from: 'cnOpenUserSettings', + default: null, + }, + }, + + data() { + return { + /** The uuid of the person's default dashboard, read on first open. */ + defaultUuid: '', + defaultRead: false, + } + }, + + computed: { + ...mapState(useDashboardStore, [ + 'userDashboards', + 'groupSharedDashboards', + 'defaultGroupDashboards', + 'sharedWithMeDashboards', + 'activeDashboardId', + 'loadedOnce', + ]), + + /** + * The chrome decision, unwrapped. Defaults keep the panel. + * + * @return {{ railSuppressed: boolean, entries: object[], isAdmin: boolean, includePersonalSettings: boolean }} + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ + chrome() { + return readChrome(this.launchpadChrome) + }, + + /** + * The Dashboards group, as on the dashboard view. + * + * @return {object[]} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + dashboards() { + return dashboardItems({ + userDashboards: this.userDashboards, + groupDashboards: [ + ...this.groupSharedDashboards, + ...this.defaultGroupDashboards, + ...this.sharedWithMeDashboards, + ], + sharedDashboards: this.sharedWithMeDashboards, + activeId: null, + defaultUuid: this.defaultUuid, + onSwitch: (id) => this.openDashboard(id), + onOpenAll: () => this.openWorkspace(), + }) + }, + + /** + * The items under Settings. + * + * @return {object[]} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + settings() { + return settingsMenuItems(startPageSections(this.chrome, this.cnOpenUserSettings)) + }, + }, + + methods: { + /** + * Read the dashboards and the default one the first time the menu + * opens, when the page has not read them yet. + * + * @return {Promise<void>} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + async onOpen() { + if (!this.loadedOnce) { + await useDashboardStore().loadDashboards() + } + if (this.defaultRead) { + return + } + this.defaultRead = true + try { + const res = await api.getDefaultDashboardPreference() + this.defaultUuid = res?.data?.uuid ?? '' + } catch (error) { + logger.warn('[StartPageMenu] could not read the default dashboard:', error) + } + }, + + /** + * Open a dashboard on the dashboard view. + * + * @param {string|number} id The dashboard's id. + * @return {void} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + openDashboard(id) { + this.$router?.push({ name: 'dashboard-detail', params: { id: String(id) } }) + }, + + /** + * Go to the dashboard view, where every dashboard is listed. + * + * @return {void} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ + openWorkspace() { + this.$router?.push({ name: 'Workspace' }) + }, + }, +} +</script> diff --git a/src/components/Workspace/TileSidePanel.vue b/src/components/Workspace/TileSidePanel.vue new file mode 100644 index 000000000..9676e022a --- /dev/null +++ b/src/components/Workspace/TileSidePanel.vue @@ -0,0 +1,225 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 + - + - The panel beside the tiles that a `side-panel` tile opens in + - (launcher-tile-open-behaviour D3, D4). One panel at a time; opening + - another tile replaces it. Escape or the close button closes it and + - returns focus to the tile. An outside address is framed only when the + - server's framing check passes (embed allow-list, X-Frame-Options); + - otherwise the panel shows a card with "Open in new tab". + - + - @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md +--> + +<template> + <aside + v-if="panel.isOpen" + ref="root" + class="tile-side-panel" + :aria-label="panel.title" + data-test="tile-side-panel" + tabindex="-1" + @keydown.esc.stop="panel.close()"> + <header class="tile-side-panel__header"> + <h2 class="tile-side-panel__title"> + {{ panel.title }} + </h2> + <a + class="tile-side-panel__external" + :href="panel.url" + target="_blank" + rel="noopener noreferrer"> + {{ t('launchpad', 'Open in new tab') }} + </a> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Close')" + data-test="tile-side-panel-close" + @click="panel.close()"> + <template #icon> + <CloseIcon :size="20" /> + </template> + </NcButton> + </header> + + <div + v-if="state === 'refused'" + class="tile-side-panel__fallback" + data-test="tile-side-panel-fallback"> + <p>{{ t('launchpad', 'This page could not be loaded.') }}</p> + <a + :href="panel.url" + target="_blank" + rel="noopener noreferrer"> + {{ t('launchpad', 'Open in new tab') }} + </a> + </div> + <p v-else-if="state === 'checking'" class="tile-side-panel__checking"> + {{ t('launchpad', 'Loading…') }} + </p> + <iframe + v-else + :key="panel.url" + class="tile-side-panel__frame" + :src="panel.url" + :title="panel.title" + data-test="tile-side-panel-frame" + referrerpolicy="strict-origin-when-cross-origin" /> + </aside> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' +import CloseIcon from 'vue-material-design-icons/Close.vue' +import { checkIframeFramable } from '../../services/iframeClient.js' +import { useTilePanelStore } from '../../stores/tilePanel.js' + +export default { + name: 'TileSidePanel', + + components: { + NcButton, + CloseIcon, + }, + + /** + * Bind the one tile panel store the tiles write to. + * + * @return {{panel: object}} The store, as `panel`. + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md#requirement-a-tile-can-open-its-app-in-a-panel-beside-the-tiles-req-tob-003 + */ + setup() { + return { panel: useTilePanelStore() } + }, + + data() { + return { + /** `checking`, `ready` or `refused`. */ + state: 'ready', + } + }, + + watch: { + /** + * Each newly opened address is checked before it is framed, unless it + * is on this Nextcloud. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + 'panel.url': { + immediate: true, + /** + * Check the address the panel now shows. + * + * @param {string|null} url The address, or null when closed. + * @return {void} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md#requirement-the-panel-only-frames-allowed-pages-req-tob-004 + */ + handler(url) { + this.check(url) + }, + }, + }, + + methods: { + t, + + /** + * Decide whether the address may be framed, then move focus into the panel. + * + * @param {string|null} url The address, or null when closed. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + async check(url) { + if (!url) { + return + } + if (this.panel.sameOrigin) { + this.state = 'ready' + } else { + this.state = 'checking' + const result = await checkIframeFramable(url) + // A newer tile replaced this one while the check ran. + if (this.panel.url !== url) { + return + } + this.state = result && result.framable === true ? 'ready' : 'refused' + } + await this.$nextTick() + this.$refs.root?.focus?.() + }, + }, +} +</script> + +<style scoped> +.tile-side-panel { + display: flex; + flex-direction: column; + width: min(50%, 720px); + min-width: 320px; + border-inline-start: 1px solid var(--color-border); + background: var(--color-main-background); +} + +.tile-side-panel:focus { + outline: none; +} + +.tile-side-panel:focus-visible { + outline: 2px solid var(--color-primary-element); + outline-offset: -2px; +} + +.tile-side-panel__header { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 8px 4px 16px; + border-bottom: 1px solid var(--color-border); +} + +.tile-side-panel__title { + flex: 1; + margin: 0; + font-size: var(--default-font-size); + font-weight: bold; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.tile-side-panel__external, +.tile-side-panel__fallback a { + color: var(--color-primary-element); + text-decoration: underline; +} + +.tile-side-panel__frame { + flex: 1; + width: 100%; + border: 0; +} + +.tile-side-panel__fallback, +.tile-side-panel__checking { + padding: 24px 16px; + color: var(--color-text-maxcontrast); +} + +/* Below 768px the panel covers the grid instead of sharing the row. */ +@media (max-width: 767px) { + .tile-side-panel { + position: fixed; + inset: 0; + z-index: 1000; + width: 100%; + min-width: 0; + border-inline-start: 0; + } +} +</style> diff --git a/src/components/Workspace/__tests__/ActiveFiltersPanel.spec.js b/src/components/Workspace/__tests__/ActiveFiltersPanel.spec.js new file mode 100644 index 000000000..e30f80234 --- /dev/null +++ b/src/components/Workspace/__tests__/ActiveFiltersPanel.spec.js @@ -0,0 +1,94 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ActiveFiltersPanel: one chip per clause, the source widget named for a + * widget click, a lock and no remove button for a pinned clause, absent while + * empty, and "Reset filters" only when there is something to clear + * (drill-down-cross-widget-filter tasks 5 and 6; REQ-CWF-006, REQ-CWF-007). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import ActiveFiltersPanel from '../ActiveFiltersPanel.vue' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/{(\w+)}/g, (_match, key) => vars[key] ?? `{${key}}`), +})) + +vi.mock('@nextcloud/vue', () => ({ + NcButton: { name: 'NcButton', emits: ['click'], template: '<button data-testid="reset-filters" @click="$emit(\'click\')"><slot /></button>' }, +})) + +const CLICK = { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: 'w-gemeenten', pinned: false } +const BOOKMARK = { dimension: 'status', operator: 'in', value: ['open', 'paused'], source: 'urlBootstrap', sourceWidgetId: null, pinned: false } +const PINNED = { dimension: 'period.month', operator: 'between', value: ['2026-01', '2026-03'], source: 'userExplicit', sourceWidgetId: null, pinned: true } + +/** + * Mount the panel over clauses. + * + * @param {Array<object>} clauses The clauses. + * @return {import('@vue/test-utils').VueWrapper} + */ +function panel(clauses) { + return mount(ActiveFiltersPanel, { + props: { + clauses, + labels: { gemeenteCode: 'Gemeente', 'period.month': 'Period' }, + widgetNames: { 'w-gemeenten': 'Inwoners per gemeente' }, + }, + }) +} + +describe('ActiveFiltersPanel', () => { + it('REQ-CWF-007: renders nothing while the bus is empty', () => { + expect(panel([]).find('[data-testid="active-filters"]').exists()).toBe(false) + }) + + it('REQ-CWF-007: shows each clause with its label, value and source', () => { + const wrapper = panel([CLICK, BOOKMARK, PINNED]) + const chips = wrapper.findAll('.active-filters__chip') + + expect(chips).toHaveLength(3) + expect(chips[0].text()).toContain('Gemeente:') + expect(chips[0].text()).toContain('GM0355') + expect(chips[0].find('[data-testid="active-filter-source"]').text()).toBe('(Inwoners per gemeente)') + // A restored clause names no source; its dimension stands in for a missing label. + expect(chips[1].text()).toContain('status:') + expect(chips[1].text()).toContain('open, paused') + expect(chips[1].find('[data-testid="active-filter-source"]').exists()).toBe(false) + expect(chips[2].text()).toContain('2026-01 – 2026-03') + }) + + it('REQ-CWF-007: a pinned clause has a lock and no remove button', () => { + const chips = panel([CLICK, PINNED]).findAll('.active-filters__chip') + + expect(chips[1].find('[data-testid="active-filter-lock"]').exists()).toBe(true) + expect(chips[1].find('[data-testid="active-filter-remove"]').exists()).toBe(false) + expect(chips[0].find('[data-testid="active-filter-lock"]').exists()).toBe(false) + expect(chips[0].find('[data-testid="active-filter-remove"]').attributes('aria-label')).toBe('Remove filter: Gemeente') + }) + + it('REQ-CWF-007: remove names the clause dimension', async () => { + const wrapper = panel([CLICK, BOOKMARK]) + + await wrapper.findAll('[data-testid="active-filter-remove"]')[1].trigger('click') + + expect(wrapper.emitted('remove')).toEqual([['status']]) + }) + + it('REQ-CWF-006: Reset filters asks for a reset', async () => { + const wrapper = panel([CLICK, PINNED]) + + await wrapper.find('[data-testid="reset-filters"]').trigger('click') + + expect(wrapper.emitted('reset')).toHaveLength(1) + }) + + it('REQ-CWF-006: no Reset filters when only pinned clauses are left', () => { + const wrapper = panel([PINNED]) + + expect(wrapper.find('[data-testid="active-filters"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="reset-filters"]').exists()).toBe(false) + }) +}) diff --git a/src/components/Workspace/__tests__/CoEditorsBanner.spec.js b/src/components/Workspace/__tests__/CoEditorsBanner.spec.js new file mode 100644 index 000000000..28dadaea9 --- /dev/null +++ b/src/components/Workspace/__tests__/CoEditorsBanner.spec.js @@ -0,0 +1,65 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * CoEditorsBanner: in edit mode, who else edits the dashboard and since when, + * with their initials (building-edit-a-dashboard-together, task 1.1). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import CoEditorsBanner, { clockTime, initialsOf } from '../CoEditorsBanner.vue' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) + +vi.mock('@conduction/nextcloud-vue', () => ({ + NcNoteCard: { + name: 'NcNoteCard', + props: ['type'], + template: '<div class="note" :data-type="type"><slot /></div>', + }, +})) + +describe('CoEditorsBanner', () => { + it('says nothing while nobody else edits', () => { + const wrapper = mount(CoEditorsBanner, { props: { editors: [] } }) + expect(wrapper.find('[data-testid="co-editors-banner"]').exists()).toBe(false) + }) + + it('names the colleague editing longest and since when, and lists every colleague by initials', () => { + const since = '2026-11-14T10:42:00+01:00' + const wrapper = mount(CoEditorsBanner, { + props: { + editors: [ + { displayName: 'Marieke Jansen', since }, + { displayName: 'sanne', since: '2026-11-14T10:50:00+01:00' }, + ], + }, + }) + expect(wrapper.find('p').text()).toBe( + `Marieke Jansen is also editing this dashboard, since ${clockTime(since)}. Your changes are not overwritten.`, + ) + expect(wrapper.text()).toContain('Who else is editing?') + const chips = wrapper.findAll('[data-testid="co-editor"]') + expect(chips.map((chip) => chip.text())).toEqual(['MJ', 'S']) + expect(chips[0].attributes('aria-label')).toBe('Marieke Jansen') + }) +}) + +describe('initialsOf and clockTime', () => { + it('takes the first letters of the first and last word', () => { + expect(initialsOf('Marieke van der Jansen')).toBe('MJ') + expect(initialsOf(' pieter ')).toBe('P') + expect(initialsOf('')).toBe('?') + expect(initialsOf(null)).toBe('?') + }) + + it('reads an ISO time as a clock time, and keeps what it cannot read', () => { + const time = clockTime('2026-11-14T10:42:00+01:00') + expect(time).toMatch(/\d{1,2}.\d{2}/) + expect(clockTime('not a date')).toBe('not a date') + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardDiscussion.spec.js b/src/components/Workspace/__tests__/DashboardDiscussion.spec.js new file mode 100644 index 000000000..91956c48b --- /dev/null +++ b/src/components/Workspace/__tests__/DashboardDiscussion.spec.js @@ -0,0 +1,84 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The discussion of a dashboard renders on shared and group dashboards only, + * and not at all without OpenRegister and Talk (openregister-leaf-integrations + * tasks 4 to 6). + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-4 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import DashboardDiscussion from '../DashboardDiscussion.vue' + +const listShares = vi.hoisted(() => vi.fn()) +vi.mock('../../../services/api.js', () => ({ api: { listShares } })) + +const TabStub = { + name: 'CnIntegrationTab', + props: ['integrationId', 'register', 'schema', 'objectId'], + template: '<div class="tab-stub" />', +} + +/** + * Mount the discussion. + * + * @param {object} props The props. + * @return {import('@vue/test-utils').VueWrapper} + */ +function mountDiscussion(props) { + return mount(DashboardDiscussion, { props, global: { stubs: { CnIntegrationTab: TabStub } } }) +} + +beforeEach(() => { + window.OC = { ...(window.OC || {}), appswebroots: { openregister: '/apps/openregister', spreed: '/apps/spreed' } } + listShares.mockReset() +}) + +afterEach(() => { + delete window.OC.appswebroots +}) + +describe('DashboardDiscussion', () => { + it('mounts the talk leaf on a group dashboard, keyed by the dashboard uuid', () => { + const tab = mountDiscussion({ dashboard: { id: 1, uuid: 'g-1', type: 'group_shared' } }).findComponent(TabStub) + expect(tab.props()).toEqual({ integrationId: 'talk', register: 'launchpad', schema: 'dashboard', objectId: 'g-1' }) + }) + + it('mounts on my dashboard once its shares are read, and asks nothing for someone else\'s', async () => { + listShares.mockResolvedValue({ data: [{ shareType: 'user', shareWith: 'bob' }] }) + const mine = mountDiscussion({ dashboard: { id: 7, uuid: 'u-7', type: 'user', userId: 'alice' }, currentUserId: 'alice' }) + expect(mine.find('[data-testid="dashboard-discussion"]').exists()).toBe(false) + await flushPromises() + expect(mine.find('[data-testid="dashboard-discussion"]').exists()).toBe(true) + expect(listShares).toHaveBeenCalledWith(7) + + listShares.mockClear() + mountDiscussion({ dashboard: { id: 8, uuid: 'u-8', type: 'user', userId: 'carol' }, currentUserId: 'alice', sharedWithMe: [{ id: 8 }] }) + expect(listShares).not.toHaveBeenCalled() + }) + + /** @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 */ + it('renders nothing on a shared dashboard whose conversation is switched off', () => { + const wrapper = mountDiscussion({ dashboard: { id: 1, uuid: 'g-1', type: 'group_shared', conversationEnabled: 0 } }) + expect(wrapper.find('[data-testid="dashboard-discussion"]').exists()).toBe(false) + }) + + it('renders nothing on my unshared dashboard', async () => { + listShares.mockResolvedValue({ data: [] }) + const wrapper = mountDiscussion({ dashboard: { id: 7, uuid: 'u-7', type: 'user', userId: 'alice' }, currentUserId: 'alice' }) + await flushPromises() + expect(wrapper.find('[data-testid="dashboard-discussion"]').exists()).toBe(false) + }) + + it('renders and requests nothing without Talk', async () => { + window.OC.appswebroots = { openregister: '/apps/openregister' } + const wrapper = mountDiscussion({ dashboard: { id: 7, uuid: 'u-7', type: 'user', userId: 'alice' }, currentUserId: 'alice' }) + await flushPromises() + expect(listShares).not.toHaveBeenCalled() + expect(mountDiscussion({ dashboard: { id: 1, uuid: 'g-1', type: 'group_shared' } }).find('[data-testid="dashboard-discussion"]').exists()).toBe(false) + expect(wrapper.html()).toBe('<!--v-if-->') + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardEditBar.spec.js b/src/components/Workspace/__tests__/DashboardEditBar.spec.js new file mode 100644 index 000000000..5a2d275b3 --- /dev/null +++ b/src/components/Workspace/__tests__/DashboardEditBar.spec.js @@ -0,0 +1,89 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The edit bar of board LpBewerken: Columns 6, 8 or 12, Add widget, + * Dashboard settings and Done, and the dock for the More menu. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) + +import DashboardEditBar from '../DashboardEditBar.vue' + +/** + * Mount the bar. + * + * @param {object} props Props. + * @return {object} The wrapper. + */ +function mountBar(props = {}) { + return mount(DashboardEditBar, { + props: { dashboardName: 'Mijn werkplek', columns: 12, canConfigure: true, ...props }, + }) +} + +describe('DashboardEditBar', () => { + it('is a toolbar naming the dashboard being edited', () => { + const wrapper = mountBar() + const bar = wrapper.find('[data-testid="launchpad-edit-bar"]') + expect(bar.attributes('role')).toBe('toolbar') + expect(bar.attributes('aria-label')).toBe('Edit dashboard') + expect(bar.text()).toContain('You are editing Mijn werkplek') + }) + + it('holds Columns, Add widget, Add tiles, Dashboard settings and Done, in that order', () => { + const labels = mountBar().findAll('button').map((b) => b.text()) + expect(labels).toEqual(['6', '8', '12', 'Add widget', 'Add tiles', 'Dashboard settings', 'Done']) + }) + + it('emits addTiles from Add tiles (add-tiles-dialog REQ-TILE-043)', async () => { + const wrapper = mountBar() + await wrapper.find('[data-testid="launchpad-edit-bar-add-tiles"]').trigger('click') + expect(wrapper.emitted('addTiles')).toHaveLength(1) + }) + + it('marks the current column count pressed and emits a chosen one', async () => { + const wrapper = mountBar({ columns: 8 }) + const pressed = wrapper.findAll('[aria-pressed="true"]') + expect(pressed).toHaveLength(1) + expect(pressed[0].text()).toBe('8') + const group = wrapper.find('[data-testid="launchpad-edit-bar-columns"]') + expect(group.attributes('role')).toBe('group') + expect(wrapper.find(`#${group.attributes('aria-labelledby')}`).text()).toBe('Columns') + + await wrapper.find('[data-testid="launchpad-edit-bar-columns-6"]').trigger('click') + expect(wrapper.emitted('setColumns')).toEqual([[6]]) + }) + + it('opens the settings as a dialog, and only for who may configure', async () => { + const wrapper = mountBar() + const settings = wrapper.find('[data-testid="launchpad-edit-bar-settings"]') + expect(settings.attributes('aria-haspopup')).toBe('dialog') + await settings.trigger('click') + expect(wrapper.emitted('openSettings')).toHaveLength(1) + + expect(mountBar({ canConfigure: false }).find('[data-testid="launchpad-edit-bar-settings"]').exists()).toBe(false) + }) + + it('emits Add widget and Done', async () => { + const wrapper = mountBar() + await wrapper.find('[data-testid="launchpad-edit-bar-add-widget"]').trigger('click') + await wrapper.find('[data-testid="launchpad-edit-bar-done"]').trigger('click') + expect(wrapper.emitted('addWidget')).toHaveLength(1) + expect(wrapper.emitted('done')).toHaveLength(1) + }) + + it('hands its dock to the page while shown, and takes it back when gone', () => { + const onDock = vi.fn() + const wrapper = mountBar({ onDock }) + expect(onDock).toHaveBeenLastCalledWith(wrapper.find('.launchpad-edit-bar__dock').element) + wrapper.unmount() + expect(onDock).toHaveBeenLastCalledWith(null) + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardMoreMenu.spec.js b/src/components/Workspace/__tests__/DashboardMoreMenu.spec.js new file mode 100644 index 000000000..f89aeb8ef --- /dev/null +++ b/src/components/Workspace/__tests__/DashboardMoreMenu.spec.js @@ -0,0 +1,182 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The dashboard view's More menu (board LpMeer): the dashboards, Settings + * and This dashboard with each action's permission rule, handed to the one + * LaunchpadMoreMenu. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, text) => text, +})) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (tpl, vars) => tpl.replace('{appId}', vars?.appId), +})) +vi.mock('../LaunchpadMoreMenu.vue', () => ({ + default: { + name: 'LaunchpadMoreMenu', + props: ['dashboards', 'settings', 'actions'], + template: '<div class="menu-stub" />', + }, +})) + +import DashboardMoreMenu from '../DashboardMoreMenu.vue' +import { orderDestinations } from '../moreMenuItems.js' + +const ENTRIES = [ + { id: 'dashboards', label: 'Dashboards', route: 'Workspace' }, + { id: 'admin-templates', label: 'Templates', route: 'admin-templates-index', section: 'settings' }, + { id: 'admin-settings', label: 'Admin settings', route: 'admin-settings', section: 'settings' }, + { id: 'FlowsMenu', label: 'Flows', route: 'Flows', section: 'settings' }, + { id: 'Documentation', label: 'Documentation', href: 'https://launchpad.conduction.nl', section: 'footer' }, + { id: 'StoreMenu', label: 'Marketplace', route: 'Store', section: 'footer' }, + { id: 'ReportsMenu', label: 'Reports', route: 'Reports', section: 'settings' }, + { id: 'FeaturesRoadmapMenu', label: 'Features & roadmap', route: 'FeaturesRoadmap', section: 'footer' }, + { id: 'IntegrationsMenu', label: 'Integrations', route: 'Integrations', section: 'settings' }, +] + +const TODAY = { id: 1, uuid: 'u-1', name: 'Vandaag', isOwner: true } +const TEAM = { id: 2, uuid: 'u-2', name: 'Team Vergunningen' } +const INTRANET = { id: 3, uuid: 'u-3', name: 'Intranet Zuiddrecht' } + +/** + * Mount the menu. + * + * @param {object} props Props. + * @param {object} chrome The chrome decision. + * @return {object} The wrapper and what the menu was handed. + */ +function mountMenu(props = {}, chrome = { railSuppressed: true, entries: ENTRIES, isAdmin: true }) { + const openUserSettings = vi.fn() + const wrapper = mount(DashboardMoreMenu, { + props: { + dashboard: TODAY, + source: 'user', + userDashboards: [TODAY], + groupDashboards: [TEAM, INTRANET], + sharedDashboards: [TEAM], + defaultUuid: 'u-1', + canEdit: true, + canShare: true, + canDuplicate: true, + ...props, + }, + global: { provide: { launchpadChrome: chrome, cnOpenUserSettings: openUserSettings } }, + }) + const menu = wrapper.findComponent({ name: 'LaunchpadMoreMenu' }) + const ids = (key) => menu.props(key).map((item) => item.id) + return { wrapper, menu, ids, openUserSettings } +} + +describe('DashboardMoreMenu', () => { + it('hands the one menu the board\'s three groups', () => { + const { ids } = mountMenu() + expect(ids('dashboards')).toEqual(['dashboard-1', 'dashboard-2', 'dashboard-3', 'all-dashboards']) + expect(ids('settings')).toEqual([ + 'personal-settings', + 'admin-settings-link', + 'StoreMenu', + 'admin-templates', + 'ReportsMenu', + 'FlowsMenu', + 'IntegrationsMenu', + 'Documentation', + 'FeaturesRoadmapMenu', + ]) + expect(ids('actions')).toEqual(['edit', 'add-widget', 'share', 'copy-link', 'duplicate', 'set-default', 'delete']) + }) + + it('marks the open, the default, the shared and the group dashboards', () => { + const { menu } = mountMenu() + const [today, team, intranet] = menu.props('dashboards') + expect(today).toMatchObject({ checked: true, meta: 'default' }) + expect(team).toMatchObject({ checked: false, meta: 'shared' }) + expect(intranet).toMatchObject({ checked: false, meta: 'group' }) + }) + + it('switches dashboards and opens the full switcher', () => { + const { wrapper, menu } = mountMenu() + menu.props('dashboards')[1].onClick() + menu.props('dashboards').at(-1).onClick() + expect(wrapper.emitted('switch')).toEqual([[2, 'shared']]) + expect(wrapper.emitted('openAll')).toHaveLength(1) + }) + + it('emits each action by its event', () => { + const { wrapper, menu } = mountMenu() + for (const item of menu.props('actions')) { + item.onClick() + } + for (const event of ['toggleEdit', 'addWidget', 'share', 'copyLink', 'duplicate', 'setDefault', 'delete']) { + expect(wrapper.emitted(event), event).toHaveLength(1) + } + }) + + it('keeps each action\'s permission rule on someone else\'s dashboard', () => { + const { ids } = mountMenu({ + dashboard: { ...TEAM, isOwner: false }, + source: 'group', + canEdit: false, + canShare: false, + canDuplicate: false, + }) + expect(ids('actions')).toEqual(['copy-link', 'set-default']) + }) + + it('never offers Versions, Settings, Schedule, Unpublish or Create embed token', () => { + const { ids } = mountMenu() + for (const gone of ['versions', 'config', 'schedule', 'unpublish', 'publish', 'embed']) { + expect(ids('actions')).not.toContain(gone) + } + }) + + it('offers the read receipts before Delete when the dashboard asks for them', () => { + const { wrapper, menu, ids } = mountMenu({ canViewReadReceipts: true }) + expect(ids('actions').slice(-2)).toEqual(['read-receipts', 'delete']) + menu.props('actions').find((item) => item.id === 'read-receipts').onClick() + expect(wrapper.emitted('readReceipts')).toHaveLength(1) + expect(mountMenu({ canViewReadReceipts: true, source: 'group', dashboard: TEAM }).ids('actions').at(-1)).toBe('read-receipts') + }) + + it('names Save dashboard while editing', () => { + const { menu } = mountMenu({ isEditMode: true }) + expect(menu.props('actions')[0].label).toBe('Save dashboard') + }) + + it('leaves the admin settings out for a member, and opens the personal settings dialog', () => { + const { menu, ids, openUserSettings } = mountMenu({}, { railSuppressed: true, entries: ENTRIES, isAdmin: false }) + expect(ids('settings')).not.toContain('admin-settings-link') + menu.props('settings').find((item) => item.id === 'personal-settings').onClick() + expect(openUserSettings).toHaveBeenCalled() + }) + + it('leaves Settings to the navigation panel while it shows', () => { + const { ids } = mountMenu({}, { railSuppressed: false, entries: ENTRIES, isAdmin: true }) + expect(ids('settings')).toEqual([]) + }) + + it('offers only the dashboards without an open dashboard', () => { + const { ids } = mountMenu({ dashboard: null }) + expect(ids('actions')).toEqual([]) + expect(ids('dashboards')).toContain('all-dashboards') + }) +}) + +describe('orderDestinations', () => { + it('puts the app\'s destinations in the board\'s order, unknown ones after in their own order', () => { + const items = ['zeta', 'Documentation', 'alpha', 'StoreMenu', 'FlowsMenu'].map((id) => ({ id })) + expect(orderDestinations(items).map((item) => item.id)).toEqual([ + 'StoreMenu', + 'FlowsMenu', + 'Documentation', + 'zeta', + 'alpha', + ]) + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardPageHeader.spec.js b/src/components/Workspace/__tests__/DashboardPageHeader.spec.js new file mode 100644 index 000000000..4eeb0f320 --- /dev/null +++ b/src/components/Workspace/__tests__/DashboardPageHeader.spec.js @@ -0,0 +1,148 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * A dashboard without a greeting row opens with its name and the slot the + * "Meer" menu docks into (LpWerkplek, LpIntranet, LpAfdeling). + * + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-009-no-navigation-panel-the-destinations-are-in-the-more-menu + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import CnSegmentedControl from '@conduction/nextcloud-vue/src/components/CnSegmentedControl/CnSegmentedControl.vue' +import DashboardPageHeader, { lastChangedText, rightsText } from '../DashboardPageHeader.vue' +import { PAGE_HEADER_DOCK_CLASS } from '../../../utils/headerActionsDock.js' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + getCanonicalLocale: () => 'nl', + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? ''), +})) + +const NOW = new Date(2026, 9, 5, 10, 47) + +function mountHeader(props) { + return mount(DashboardPageHeader, { + props: { dashboard: { name: 'Mijn werkplek', description: '', updatedAt: null }, ...props }, + }) +} + +describe('DashboardPageHeader', () => { + it('shows the dashboard name as the page title and a dock slot for the menu', () => { + const wrapper = mountHeader({}) + expect(wrapper.find('h1').text()).toBe('Mijn werkplek') + expect(wrapper.find('.' + PAGE_HEADER_DOCK_CLASS).exists()).toBe(true) + }) + + it('offers Download as its only action of its own: Edit and Add widget are in the More menu (LpWerkplek)', () => { + for (const props of [{}, { source: 'group' }, { isDefault: true }, { permissionLevel: 'view_only' }]) { + const buttons = mountHeader(props).findAll('button') + expect(buttons).toHaveLength(1) + expect(buttons[0].attributes('data-testid')).toBe('dashboard-download') + } + }) + + it('names a personal dashboard, the one that opens first, and a shared one; a group dashboard has no chip', () => { + expect(mountHeader({ source: 'user' }).find('[data-testid="dashboard-page-header-kind"]').text()).toBe('Personal dashboard') + expect(mountHeader({ source: 'user', isDefault: true }).find('[data-testid="dashboard-page-header-kind"]').text()).toBe('Personal dashboard · opens first') + expect(mountHeader({ source: 'shared' }).find('[data-testid="dashboard-page-header-kind"]').text()).toBe('Shared with you') + expect(mountHeader({ source: 'group' }).find('[data-testid="dashboard-page-header-kind"]').exists()).toBe(false) + }) + + // @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-the-header-says-what-dashboard-this-is-and-what-the-reader-may-do-req-dpd-001 + it('names the group of a group dashboard, its display name first, and nothing for the organisation-wide one', () => { + const kind = (props) => mountHeader(props).find('[data-testid="dashboard-page-header-kind"]') + const dashboard = { name: 'Managementinformatie', description: '', updatedAt: null } + expect(kind({ source: 'group', dashboard: { ...dashboard, groupId: 'Bedrijfsvoering' } }).text()).toBe('Group dashboard of Bedrijfsvoering') + expect(kind({ source: 'group', dashboard: { ...dashboard, groupId: 'bv', groupDisplayName: 'Bedrijfsvoering' } }).text()).toBe('Group dashboard of Bedrijfsvoering') + expect(kind({ source: 'group', dashboard: { ...dashboard, groupId: 'default' } }).exists()).toBe(false) + expect(kind({ source: 'default', dashboard: { ...dashboard, groupId: 'default' } }).exists()).toBe(false) + }) + + it('joins the description and the last change into the meta line', () => { + const wrapper = mountHeader({ + source: 'group', + dashboard: { name: 'Intranet Zuiddrecht', description: 'Groepsdashboard van Communicatie', updatedAt: new Date().toISOString() }, + }) + expect(wrapper.find('.launchpad-page-header__meta').text()).toMatch(/^Groepsdashboard van Communicatie · Last changed today \d\d:\d\d$/) + }) +}) + +// @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-the-header-says-what-dashboard-this-is-and-what-the-reader-may-do-req-dpd-001 +describe('the reader\'s rights in the meta line', () => { + it('says view only, you may add widgets, and nothing with full rights', () => { + expect(rightsText('view_only')).toBe('view only') + expect(rightsText('add_only')).toBe('you may add widgets') + expect(rightsText('full')).toBe('') + expect(rightsText(undefined)).toBe('') + }) + + it('reads "Groepsdashboard van Bedrijfsvoering · view only · Last changed today 10:45" for a view-only reader', () => { + const changed = new Date() + changed.setHours(10, 45, 0, 0) + const wrapper = mountHeader({ + source: 'group', + permissionLevel: 'view_only', + dashboard: { name: 'Managementinformatie', description: 'Groepsdashboard van Bedrijfsvoering', updatedAt: changed.toISOString() }, + }) + expect(wrapper.find('.launchpad-page-header__meta').text()).toBe('Groepsdashboard van Bedrijfsvoering · view only · Last changed today 10:45') + }) + + it('names adding widgets for an add-only reader', () => { + const wrapper = mountHeader({ source: 'shared', permissionLevel: 'add_only', dashboard: { name: 'Team', description: '', updatedAt: null } }) + expect(wrapper.find('.launchpad-page-header__meta').text()).toContain('you may add widgets') + }) + + it('adds nothing for the owner with full rights', () => { + const wrapper = mountHeader({ source: 'user', dashboard: { name: 'Mijn werkplek', description: '', updatedAt: null } }) + expect(wrapper.find('.launchpad-page-header__meta').text()).toBe('Personal dashboard') + }) +}) + +// @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 +describe('the period choice (REQ-DPD-002)', () => { + it('is absent on a dashboard without dated sources', () => { + expect(mountHeader({}).find('[data-testid="dashboard-period"]').exists()).toBe(false) + }) + + it('offers This month, Quarter and Year and asks the page for the chosen one', async () => { + const wrapper = mount(DashboardPageHeader, { + props: { dashboard: { name: 'Managementinformatie', description: '', updatedAt: null }, showsPeriod: true, period: 'month' }, + global: { components: { CnSegmentedControl } }, + }) + const control = wrapper.find('[data-testid="dashboard-period"]') + expect(control.exists()).toBe(true) + const options = control.findAll('button') + expect(options.map((button) => button.text())).toEqual(['This month', 'Quarter', 'Year']) + expect(options[0].attributes('aria-checked')).toBe('true') + await options[1].trigger('click') + expect(wrapper.emitted('update:period')).toEqual([['quarter']]) + }) +}) + +describe('lastChangedText', () => { + it('says the time today, the weekday within a week and the date before that', () => { + expect(lastChangedText(new Date(2026, 9, 5, 9, 10).toISOString(), NOW, 'nl')).toBe('Last changed today 09:10') + expect(lastChangedText(new Date(2026, 9, 2, 16, 0).toISOString(), NOW, 'nl')).toBe('Last changed vrijdag') + expect(lastChangedText(new Date(2026, 8, 28, 12, 0).toISOString(), NOW, 'nl')).toBe('Last changed 28 september') + }) + + it('says nothing without a usable date', () => { + expect(lastChangedText(null, NOW, 'nl')).toBe('') + expect(lastChangedText('not a date', NOW, 'nl')).toBe('') + }) +}) + +// @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-reader-can-download-the-dashboard-req-dpd-003 +describe('Download (REQ-DPD-003)', () => { + it('prints the dashboard in the reader\'s browser, also with view-only rights', async () => { + const print = vi.spyOn(window, 'print').mockImplementation(() => {}) + const wrapper = mountHeader({ permissionLevel: 'view_only', dashboard: { name: 'Managementinformatie', description: '', updatedAt: null } }) + const button = wrapper.find('[data-testid="dashboard-download"]') + expect(button.text()).toBe('Download') + await button.trigger('click') + expect(print).toHaveBeenCalledTimes(1) + print.mockRestore() + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardReactions.spec.js b/src/components/Workspace/__tests__/DashboardReactions.spec.js index d7c4b5bdd..4ab851785 100644 --- a/src/components/Workspace/__tests__/DashboardReactions.spec.js +++ b/src/components/Workspace/__tests__/DashboardReactions.spec.js @@ -11,7 +11,7 @@ import axios from '@nextcloud/axios' import { flushPromises, mount } from '@vue/test-utils' import { createPinia, setActivePinia } from 'pinia' import { beforeEach, describe, expect, it, vi } from 'vitest' -import DashboardReactions from '../DashboardReactions.vue' +import DashboardReactions, { lastChangeText } from '../DashboardReactions.vue' vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, @@ -24,6 +24,7 @@ vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text, translatePlural: (_app, one) => one, n: (_app, one) => one, + getCanonicalLocale: () => 'nl-NL', })) const allowed = ['👍', '❤️', '🎉', '😂', '🤔', '😢'] @@ -114,3 +115,59 @@ describe('DashboardReactions', () => { ).toBe('Sanne, Pieter') }) }) + +describe('DashboardReactions at the foot (reactions-bar-at-the-foot)', () => { + /** + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard + */ + it('asks the question before the reactions and names the last change after them', async () => { + const at = new Date() + at.setHours(8, 30, 0, 0) + axios.get.mockResolvedValueOnce({ + data: { counts: { '👍': 2 }, mine: [], enabled: true, allowed, lastChange: { name: 'Communicatie', at: at.toISOString() } }, + }) + const wrapper = mount(DashboardReactions, { props: { dashboardUuid: 'team' } }) + await flushPromises() + + const bar = wrapper.find('[data-testid="dashboard-reactions"]') + const parts = bar.element.children + expect(parts[0].textContent.trim()).toBe('What do you think of this dashboard?') + expect(parts[1].querySelector('[data-testid="reaction-👍"]')).toBeTruthy() + expect(parts[2].getAttribute('data-testid')).toBe('dashboard-reactions-last-change') + expect(parts[2].textContent.trim()).toMatch(/^Last updated by Communicatie, today 08[:.]30$/) + }) + + it('leaves the last-change line out when the change is unknown', async () => { + axios.get.mockResolvedValueOnce({ data: { counts: {}, mine: [], enabled: true, allowed, lastChange: null } }) + const wrapper = mount(DashboardReactions, { props: { dashboardUuid: 'team' } }) + await flushPromises() + + expect(wrapper.find('[data-testid="dashboard-reactions-question"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="dashboard-reactions-last-change"]').exists()).toBe(false) + }) +}) + +describe('lastChangeText', () => { + const now = new Date(2026, 10, 24, 12, 0, 0) + + it('names who changed it today and at what time', () => { + expect(lastChangeText({ name: 'Communicatie', at: new Date(2026, 10, 24, 8, 30).toISOString() }, now, 'nl-NL')) + .toMatch(/^Last updated by Communicatie, today 08[:.]30$/) + }) + + it('gives the weekday within the last week, the date before that', () => { + const weekday = new Date(2026, 10, 22, 9, 0).toLocaleDateString('nl-NL', { weekday: 'long' }) + expect(lastChangeText({ name: 'Pieter', at: new Date(2026, 10, 22, 9, 0).toISOString() }, now, 'nl-NL')) + .toBe(`Last updated by Pieter, ${weekday}`) + const date = new Date(2026, 9, 1, 9, 0).toLocaleDateString('nl-NL', { day: 'numeric', month: 'long' }) + expect(lastChangeText({ name: 'Pieter', at: new Date(2026, 9, 1, 9, 0).toISOString() }, now, 'nl-NL')) + .toBe(`Last updated by Pieter, ${date}`) + }) + + it('leaves the name out when it is unknown, and the line without a usable time', () => { + expect(lastChangeText({ name: ' ', at: new Date(2026, 10, 24, 8, 30).toISOString() }, now, 'nl-NL')) + .toMatch(/^Last updated today 08[:.]30$/) + expect(lastChangeText({ name: 'Pieter', at: null }, now, 'nl-NL')).toBe('') + expect(lastChangeText(null, now, 'nl-NL')).toBe('') + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardRowActions.embed.spec.js b/src/components/Workspace/__tests__/DashboardRowActions.embed.spec.js new file mode 100644 index 000000000..98f35f2d7 --- /dev/null +++ b/src/components/Workspace/__tests__/DashboardRowActions.embed.spec.js @@ -0,0 +1,55 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * An administrator's dashboard menu offers "Create embed token", which opens + * Beheer ▸ Embeds with the dashboard pre-selected (embedded-analytics task 40). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + */ + +import { mount } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import DashboardRowActions from '../DashboardRowActions.vue' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/vue', () => ({ + NcActions: { name: 'NcActions', template: '<div class="actions"><slot /></div>' }, + NcActionButton: { name: 'NcActionButton', emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>' }, +})) + +const dashboard = { id: 7, uuid: 'dash-uuid', name: 'Mijn week', isOwner: true } +const mountMenu = (props) => mount(DashboardRowActions, { props: { dashboard, source: 'user', ...props }, global: { stubs: { CodeTags: true } } }) + +describe('DashboardRowActions embed entry', () => { + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('is hidden unless the host says the viewer may embed', () => { + expect(mountMenu({}).find('[data-testid="cog-embed"]').exists()).toBe(false) + expect(mountMenu({ canEmbed: true, dashboard: { ...dashboard, uuid: '' } }).find('[data-testid="cog-embed"]').exists()).toBe(false) + }) + + it('opens Beheer ▸ Embeds with the dashboard pre-selected', async () => { + const assign = vi.fn() + vi.stubGlobal('location', { assign }) + const wrapper = mountMenu({ canEmbed: true }) + + expect(wrapper.find('[data-testid="cog-embed"]').text()).toBe('Create embed token') + await wrapper.find('[data-testid="cog-embed"]').trigger('click') + + expect(assign).toHaveBeenCalledWith('/index.php/apps/launchpad/admin/embeds?tab=embeds&embedType=dashboard&embedId=dash-uuid&embedDashboard=7') + }) +}) + +describe('embedAdminHref', () => { + it('pre-selects one widget of the dashboard when given a placement', async () => { + const { embedAdminHref } = await import('../DashboardRowActions.vue') + expect(embedAdminHref(dashboard, { id: 12 })) + .toBe('/index.php/apps/launchpad/admin/embeds?tab=embeds&embedType=widget&embedId=12&embedDashboard=7') + expect(embedAdminHref(dashboard)) + .toBe('/index.php/apps/launchpad/admin/embeds?tab=embeds&embedType=dashboard&embedId=dash-uuid&embedDashboard=7') + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardRowActions.history.spec.js b/src/components/Workspace/__tests__/DashboardRowActions.history.spec.js index e8dc11641..3e60e6005 100644 --- a/src/components/Workspace/__tests__/DashboardRowActions.history.spec.js +++ b/src/components/Workspace/__tests__/DashboardRowActions.history.spec.js @@ -2,9 +2,11 @@ * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> * SPDX-License-Identifier: EUPL-1.2 * - * The dashboard menu offers "Version history" only when the host says the - * viewer may see it (owner or administrator, and versioning supported), - * and asks the host to find out when the menu opens (REQ-VERSUI-001). + * The dashboard menu has no "Version history" entry: the versions are the + * tab Versions of the dashboard settings (REQ-VERSUI-001, board LpVersies). + * The menu still tells the host when it opens. + * + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-the-owner-sees-the-version-history-req-versui-001 */ import { mount } from '@vue/test-utils' @@ -42,25 +44,18 @@ function mountMenu(props) { StarCheck: true, ShareVariant: true, TrashCanOutline: true, - History: true, }, }, }) } describe('DashboardRowActions version history', () => { - it('shows the entry and emits versionHistory when allowed', async () => { - const wrapper = mountMenu({ canViewHistory: true }) - const entry = wrapper.find('[data-testid="cog-version-history"]') - expect(entry.exists()).toBe(true) - await entry.trigger('click') - expect(wrapper.emitted('versionHistory')).toHaveLength(1) - }) - - it('hides the entry by default', () => { - expect( - mountMenu({}).find('[data-testid="cog-version-history"]').exists(), - ).toBe(false) + it('offers no Version history entry, whatever the host passes', () => { + for (const props of [{}, { canViewHistory: true }]) { + const wrapper = mountMenu(props) + expect(wrapper.find('[data-testid="cog-version-history"]').exists()).toBe(false) + expect(wrapper.text()).not.toContain('Version history') + } }) it('tells the host when the menu opens', async () => { diff --git a/src/components/Workspace/__tests__/DashboardRowActions.menu.spec.js b/src/components/Workspace/__tests__/DashboardRowActions.menu.spec.js new file mode 100644 index 000000000..239950326 --- /dev/null +++ b/src/components/Workspace/__tests__/DashboardRowActions.menu.spec.js @@ -0,0 +1,111 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The dashboard row's cog menu: which entries show for an owner, an editor + * and a viewer, the edit/save and default/set-default labels, and the event + * each entry asks the host for. Publication and scheduled exports are in the + * dashboard settings, not here (REQ-SCHEDUI-001, REQ-SCH-011). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import DashboardRowActions from '../DashboardRowActions.vue' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) + +vi.mock('@nextcloud/vue', () => ({ + NcActions: { + name: 'NcActions', + emits: ['open'], + template: '<div class="actions"><slot name="icon" /><slot /></div>', + }, + NcActionButton: { + name: 'NcActionButton', + emits: ['click'], + template: '<button @click="$emit(\'click\')"><slot name="icon" /><slot /></button>', + }, +})) + +const icons = ['Cog', 'ContentSave', 'Pencil', 'Tune', 'ShapePolygonPlus', 'BookmarkPlusOutline', 'TrashCanOutline', 'Star', 'StarCheck', 'ShareVariant', 'CalendarClock', 'Publish', 'PublishOff'] +const stubs = Object.fromEntries(icons.map((name) => [name, { template: `<i class="icon-${name}" />` }])) + +/** + * Mount the menu. + * + * @param {object} props Props on top of a group dashboard. + * @return {object} The wrapper. + */ +function menu(props = {}) { + return mount(DashboardRowActions, { + props: { dashboard: { id: 7, uuid: 'u7', publicationStatus: 'draft' }, source: 'group', ...props }, + global: { stubs }, + }) +} + +const entries = (wrapper) => wrapper.findAll('button').map((b) => b.attributes('data-testid')) + +describe('DashboardRowActions menu', () => { + it('offers a viewer of a group dashboard only "Set as default"', () => { + expect(entries(menu())).toEqual(['cog-set-default']) + }) + + it('offers the owner of a personal dashboard every entry the host allows', () => { + const wrapper = menu({ source: 'user', canEdit: true, canShare: true }) + + expect(entries(wrapper)).toEqual([ + 'cog-edit-dashboard', 'cog-dashboard-config', 'cog-add-widget', 'cog-import-bookmarks', 'cog-set-default', + 'cog-share', 'cog-delete', + ]) + }) + + it('offers "Import bookmarks" only where the user may add, and asks the host for it', async () => { + expect(entries(menu())).not.toContain('cog-import-bookmarks') + expect(entries(menu({ canEdit: false, source: 'user' }))).not.toContain('cog-import-bookmarks') + + const wrapper = menu({ canEdit: true }) + const entry = wrapper.find('[data-testid="cog-import-bookmarks"]') + expect(entry.text()).toBe('Import bookmarks') + await entry.trigger('click') + expect(wrapper.emitted('importBookmarks')).toHaveLength(1) + }) + + it('treats a group dashboard as owned only when it says so', () => { + expect(entries(menu({ dashboard: { id: 1, isOwner: true } }))).toContain('cog-delete') + expect(entries(menu({ dashboard: { id: 1, isOwner: 'yes' } }))).not.toContain('cog-delete') + }) + + it('shows "Save dashboard" only on the active row in edit mode', () => { + const active = menu({ canEdit: true, isEditMode: true, activeDashboardId: 7 }) + expect(active.find('[data-testid="cog-edit-dashboard"]').text()).toBe('Save dashboard') + expect(active.find('[data-testid="cog-edit-dashboard"] .icon-ContentSave').exists()).toBe(true) + + const other = menu({ canEdit: true, isEditMode: true, activeDashboardId: 8 }) + expect(other.find('[data-testid="cog-edit-dashboard"]').text()).toBe('Edit dashboard') + expect(menu({ canEdit: true, isEditMode: true }).find('[data-testid="cog-edit-dashboard"]').text()).toBe('Edit dashboard') + }) + + it('marks the default dashboard', () => { + expect(menu({ defaultUuid: 'u7' }).find('[data-testid="cog-set-default"]').text()).toBe('Default dashboard') + expect(menu({ defaultUuid: 'other' }).find('[data-testid="cog-set-default"]').text()).toBe('Set as default') + expect(menu({ dashboard: { id: 1 }, defaultUuid: '' }).find('[data-testid="cog-set-default"] .icon-Star').exists()).toBe(true) + }) + + it('REQ-SCHEDUI-001: offers no publication or scheduled export entries, whatever the host passes', () => { + for (const publicationStatus of ['draft', 'published']) { + const wrapper = menu({ canManagePublication: true, canScheduleExports: true, dashboard: { id: 7, publicationStatus } }) + expect(entries(wrapper)).toEqual(['cog-set-default']) + } + }) + + it('asks the host for the action of each entry', async () => { + const wrapper = menu({ source: 'user', canEdit: true, canShare: true }) + for (const button of wrapper.findAll('button')) { + await button.trigger('click') + } + + expect(Object.keys(wrapper.emitted())).toEqual(expect.arrayContaining([ + 'toggleEdit', 'openConfig', 'addWidget', 'setDefault', 'share', 'delete', + ])) + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardRowActions.publication.spec.js b/src/components/Workspace/__tests__/DashboardRowActions.publication.spec.js deleted file mode 100644 index 149520f2e..000000000 --- a/src/components/Workspace/__tests__/DashboardRowActions.publication.spec.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - * - * A manager finds Publish or Unpublish, and Schedule…, in the dashboard - * menu (sharing-dashboard-schedule-screen REQ-SCHEDUI-001). - */ - -import { mount } from '@vue/test-utils' -import { describe, expect, it, vi } from 'vitest' -import DashboardRowActions from '../DashboardRowActions.vue' - -vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) -vi.mock('@nextcloud/vue', () => ({ - NcActions: { name: 'NcActions', template: '<div><slot /></div>' }, - NcActionButton: { - name: 'NcActionButton', - emits: ['click'], - template: '<button @click="$emit(\'click\')"><slot /></button>', - }, -})) - -const stubs = { - Cog: true, - ContentSave: true, - Pencil: true, - Tune: true, - ShapePolygonPlus: true, - Star: true, - StarCheck: true, - ShareVariant: true, - TrashCanOutline: true, - CalendarClock: true, - Publish: true, - PublishOff: true, -} -function mountMenu(dashboard, canManagePublication) { - return mount(DashboardRowActions, { - props: { dashboard, source: 'user', canManagePublication }, - global: { stubs }, - }) -} - -describe('DashboardRowActions publication', () => { - it('offers Publish and Schedule on a draft, and emits them', async () => { - const wrapper = mountMenu( - { id: 1, uuid: 'd', isOwner: true, publicationStatus: 'draft' }, - true, - ) - await wrapper.find('[data-testid="cog-publish"]').trigger('click') - await wrapper.find('[data-testid="cog-schedule"]').trigger('click') - expect(wrapper.emitted('publish')).toHaveLength(1) - expect(wrapper.emitted('schedule')).toHaveLength(1) - expect(wrapper.find('[data-testid="cog-unpublish"]').exists()).toBe(false) - }) - - it('offers Unpublish on a published dashboard', () => { - const wrapper = mountMenu( - { id: 1, uuid: 'd', isOwner: true, publicationStatus: 'published' }, - true, - ) - expect(wrapper.find('[data-testid="cog-unpublish"]').exists()).toBe(true) - expect(wrapper.find('[data-testid="cog-publish"]').exists()).toBe(false) - }) - - it('offers nothing when the host does not allow it', () => { - const wrapper = mountMenu( - { id: 1, uuid: 'd', isOwner: false, publicationStatus: 'draft' }, - false, - ) - expect(wrapper.find('[data-testid="cog-schedule"]').exists()).toBe(false) - }) -}) diff --git a/src/components/Workspace/__tests__/DashboardSwitcherSidebar.golden.spec.js b/src/components/Workspace/__tests__/DashboardSwitcherSidebar.golden.spec.js new file mode 100644 index 000000000..a04d66b1c --- /dev/null +++ b/src/components/Workspace/__tests__/DashboardSwitcherSidebar.golden.spec.js @@ -0,0 +1,106 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Characterisation tests pinning the rendered sidebar body (comment nodes + * left out) for several section combinations, and the events every row + * action emits per section, so the four section blocks can be rendered + * from one template without changing markup or behaviour. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it } from 'vitest' +import DashboardSwitcherSidebar from '../DashboardSwitcherSidebar.vue' + +beforeEach(() => { + globalThis.t = (_app, key) => key +}) + +const rowActionsStub = { + name: 'DashboardRowActions', + props: ['dashboard', 'source', 'canEdit', 'defaultUuid', 'isEditMode', 'activeDashboardId'], + emits: ['toggleEdit', 'openConfig', 'addWidget', 'delete', 'setDefault'], + template: '<span class="row-actions-stub" :data-source="source" :data-can-edit="String(canEdit)" :data-default-uuid="defaultUuid" :data-edit-mode="String(isEditMode)" :data-active="activeDashboardId" />', +} + +function mountSidebar(props = {}) { + return mount(DashboardSwitcherSidebar, { + propsData: { + isOpen: true, + groupName: 'Team', + groupDashboards: [], + userDashboards: [], + activeDashboardId: null, + allowUserDashboards: false, + ...props, + }, + global: { + stubs: { + CnDashboardIcon: { props: ['name', 'size'], template: '<i class="icon" :data-name="name" />' }, + NcButton: { template: '<button class="nc-button"><slot name="icon" /><slot /></button>' }, + SidebarFooter: { template: '<footer />' }, + DetailFilter: { template: '<div class="filter" />' }, + DashboardRowActions: rowActionsStub, + }, + }, + }) +} + +const rows = { + group: { id: 1, uuid: 'ug', name: 'Team Board', icon: 'Star', source: 'group' }, + groupChild: { id: 2, uuid: 'ugc', name: 'Team Child', icon: null, source: 'group', parentUuid: 'ug' }, + default: { id: 3, uuid: 'ud', name: 'Org Default', icon: 'Home', source: 'default' }, + user: { id: 4, uuid: 'uu', name: 'My Notes', icon: null, source: 'user' }, + shared: { id: 5, uuid: 'us', name: 'Shared One', icon: 'Share', source: 'shared' }, +} + +function bodyHtml(wrapper) { + return wrapper.find('.dashboard-switcher-sidebar__body').html() + .replace(/<!--[\s\S]*?-->/g, '') + .split('\n') + .filter((line) => line.trim() !== '') + .join('\n') +} + +describe('DashboardSwitcherSidebar body markup', () => { + it.each([ + ['all four sections', { + groupDashboards: [rows.group, rows.groupChild, rows.default, rows.shared], + userDashboards: [rows.user], + allowUserDashboards: true, + activeDashboardId: 4, + defaultUuid: 'ud', + canEdit: true, + }], + ['default and shared only', { groupDashboards: [rows.default, rows.shared] }], + ['personal card only', { allowUserDashboards: true, dashboardQuotaReached: true }], + ['group and user without card', { groupDashboards: [rows.group], userDashboards: [rows.user] }], + ['nothing', {}], + ])('renders %s', async (name, props) => { + const html = bodyHtml(mountSidebar(props)) + await expect(html).toMatchFileSnapshot(`./__snapshots__/DashboardSwitcherSidebar.golden.${name.replace(/ /g, '-')}.html`) + }) +}) + +describe('DashboardSwitcherSidebar row wiring per section', () => { + it.each(['group', 'default', 'user', 'shared'])('wires the %s rows', async (source) => { + const wrapper = mountSidebar({ + groupDashboards: [rows.group, rows.default, rows.shared], + userDashboards: [rows.user], + canEdit: true, + }) + const li = wrapper.find(`li[data-source="${source}"]`) + await li.trigger('click') + await li.trigger('keydown', { key: 'Enter' }) + await li.trigger('keydown', { key: ' ' }) + const actions = wrapper.findAllComponents(rowActionsStub).find((c) => c.props('source') === source) + for (const event of ['toggleEdit', 'openConfig', 'addWidget', 'delete', 'setDefault']) { + actions.vm.$emit(event) + } + await wrapper.vm.$nextTick() + const emitted = Object.fromEntries( + Object.entries(wrapper.emitted()).filter(([key]) => !['keydown', 'click'].includes(key)), + ) + await expect(JSON.stringify(emitted, null, 1)).toMatchFileSnapshot(`./__snapshots__/DashboardSwitcherSidebar.golden.emits-${source}.json`) + }) +}) diff --git a/src/components/Workspace/__tests__/DashboardSwitcherSidebar.spec.js b/src/components/Workspace/__tests__/DashboardSwitcherSidebar.spec.js index c2a5be535..cf8502d9d 100644 --- a/src/components/Workspace/__tests__/DashboardSwitcherSidebar.spec.js +++ b/src/components/Workspace/__tests__/DashboardSwitcherSidebar.spec.js @@ -428,6 +428,23 @@ describe('DashboardSwitcherSidebar', () => { }) }) + describe('Escape', () => { + it('closes the sidebar', async () => { + const wrapper = mountSidebar({ userDashboards: [userRow] }) + await wrapper.find('aside').trigger('keydown', { key: 'Escape' }) + expect(wrapper.emitted('update:open')).toEqual([[false]]) + }) + + it('leaves the sidebar open when it closes a menu that holds focus', async () => { + const wrapper = mountSidebar({ userDashboards: [userRow] }) + const toggle = document.createElement('button') + toggle.setAttribute('aria-expanded', 'true') + wrapper.find('aside').element.appendChild(toggle) + toggle.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) + expect(wrapper.emitted('update:open')).toBeUndefined() + }) + }) + describe('REQ-SWITCH-007 icon rendering via shared renderer', () => { it('renders one IconRenderer per dashboard row', () => { const wrapper = mountSidebar({ diff --git a/src/components/Workspace/__tests__/DetailFilter.spec.js b/src/components/Workspace/__tests__/DetailFilter.spec.js new file mode 100644 index 000000000..095c88e5a --- /dev/null +++ b/src/components/Workspace/__tests__/DetailFilter.spec.js @@ -0,0 +1,63 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * "Filter by detail": offered only for select fields with options, and emits + * the filter to apply, or null once the field or value is cleared. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import DetailFilter from '../DetailFilter.vue' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) + +vi.mock('@conduction/nextcloud-vue', () => ({ + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel'], + emits: ['update:modelValue'], + template: '<div class="select">{{ inputLabel }}</div>', + }, +})) + +const fields = [ + { key: 'team', label: 'Team', type: 'select', options: ['Red', 'Blue'] }, + { key: 'tags', label: 'Tags', type: 'multi-select', options: ['a'] }, + { key: 'empty', label: 'Empty', type: 'select', options: [] }, + { key: 'note', label: 'Note', type: 'text', options: ['x'] }, + { key: 'broken', label: 'Broken', type: 'select' }, +] + +describe('DetailFilter', () => { + it('offers only select fields that have options', () => { + const wrapper = mount(DetailFilter, { props: { fields } }) + + expect(wrapper.findComponent({ name: 'NcSelect' }).props('options').map((f) => f.key)).toEqual(['team', 'tags']) + expect(wrapper.findAllComponents({ name: 'NcSelect' })).toHaveLength(1) + }) + + it('renders nothing without a filterable field', () => { + const wrapper = mount(DetailFilter, { props: { fields: [fields[2], fields[3]] } }) + + expect(wrapper.find('[data-testid="detail-filter"]').exists()).toBe(false) + }) + + it('emits the filter once a field and a value are chosen, and null when either is cleared', async () => { + const wrapper = mount(DetailFilter, { props: { fields } }) + + await wrapper.findComponent({ name: 'NcSelect' }).vm.$emit('update:modelValue', fields[0]) + const valueSelect = wrapper.findAllComponents({ name: 'NcSelect' })[1] + expect(valueSelect.props('inputLabel')).toBe('Team') + expect(valueSelect.props('options')).toEqual(['Red', 'Blue']) + + await valueSelect.vm.$emit('update:modelValue', 'Blue') + await wrapper.findComponent({ name: 'NcSelect' }).vm.$emit('update:modelValue', fields[1]) + expect(wrapper.vm.value).toBeNull() + + await wrapper.findAllComponents({ name: 'NcSelect' })[1].vm.$emit('update:modelValue', 'a') + await wrapper.findAllComponents({ name: 'NcSelect' })[1].vm.$emit('update:modelValue', null) + + expect(wrapper.emitted('change')).toEqual([[null], [{ team: 'Blue' }], [null], [{ tags: 'a' }], [null]]) + }) +}) diff --git a/src/components/Workspace/__tests__/FilterBreadcrumb.spec.js b/src/components/Workspace/__tests__/FilterBreadcrumb.spec.js new file mode 100644 index 000000000..b933eb560 --- /dev/null +++ b/src/components/Workspace/__tests__/FilterBreadcrumb.spec.js @@ -0,0 +1,79 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * FilterBreadcrumb: the drill-down path of each hierarchy, broadest level + * first, the levels above the deepest as buttons that go back up, nothing + * while no level is active (drill-down-cross-widget-filter task 23; REQ-CWF-004). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import FilterBreadcrumb from '../FilterBreadcrumb.vue' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/{(\w+)}/g, (_match, key) => vars[key] ?? `{${key}}`), +})) + +const NL = { + id: 'nl-administrative', + levels: [ + { dimension: 'provincieCode', label: 'Province' }, + { dimension: 'gemeenteCode', label: 'Municipality' }, + { dimension: 'wijkCode', label: 'District' }, + { dimension: 'buurtCode', label: 'Neighbourhood' }, + ], +} +const LABELS = { provincieCode: 'Provincie', gemeenteCode: 'Gemeente', wijkCode: 'Wijk' } + +/** + * A clause. + * + * @param {string} dimension The dimension. + * @param {string} value The value. + * @param {string} source The source. + * @return {object} + */ +function clause(dimension, value, source = 'parentScope') { + return { dimension, operator: 'eq', value, source, sourceWidgetId: null, pinned: false } +} + +const DRILLED = [clause('wijkCode', 'WK035501', 'widgetClick'), clause('status', 'open', 'widgetClick'), clause('gemeenteCode', 'GM0355'), clause('provincieCode', 'PV26')] + +/** + * Mount the breadcrumb. + * + * @param {Array<object>} clauses The clauses. + * @param {object} [labels] The level labels. + * @return {import('@vue/test-utils').VueWrapper} + */ +function mountCrumbs(clauses, labels = LABELS) { + return mount(FilterBreadcrumb, { props: { hierarchies: [NL], clauses, labels } }) +} + +describe('FilterBreadcrumb', () => { + it('shows the path broadest first in the reader\'s labels, the deepest level as the current one', () => { + const w = mountCrumbs(DRILLED) + const steps = w.findAll('[data-testid="filter-breadcrumb-step"]') + expect(steps.map((step) => step.text())).toEqual(['Provincie PV26', 'Gemeente GM0355', 'Wijk WK035501']) + expect(steps[2].element.tagName).toBe('SPAN') + expect(steps[2].attributes('aria-current')).toBe('location') + expect(steps[0].element.tagName).toBe('BUTTON') + expect(steps[0].attributes('aria-label')).toBe('Back to Provincie PV26') + expect(w.find('nav').attributes('aria-label')).toBe('Drill-down path') + expect(w.findAll('.filter-breadcrumb__separator')).toHaveLength(2) + }) + + it('goes back up to a level when its step is chosen', async () => { + const w = mountCrumbs(DRILLED) + await w.findAll('button[data-testid="filter-breadcrumb-step"]')[0].trigger('click') + await w.findAll('button[data-testid="filter-breadcrumb-step"]')[1].trigger('click') + expect(w.emitted('pop')).toEqual([['provincieCode'], ['gemeenteCode']]) + }) + + it('falls back to the stored level label, and renders nothing without an active level', () => { + expect(mountCrumbs([clause('provincieCode', 'PV26', 'widgetClick')], {}).text()).toBe('Province PV26') + expect(mountCrumbs([clause('status', 'open')]).find('[data-testid="filter-breadcrumbs"]').exists()).toBe(false) + expect(mountCrumbs([]).html()).not.toContain('filter-breadcrumb') + }) +}) diff --git a/src/components/Workspace/__tests__/HiddenWidgetsControl.spec.js b/src/components/Workspace/__tests__/HiddenWidgetsControl.spec.js index 61067e7d7..309914709 100644 --- a/src/components/Workspace/__tests__/HiddenWidgetsControl.spec.js +++ b/src/components/Workspace/__tests__/HiddenWidgetsControl.spec.js @@ -28,11 +28,12 @@ vi.mock('@conduction/nextcloud-vue', () => ({ emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>', }, - NcDialog: { - name: 'NcDialog', - props: ['open'], + CnConfirmDialog: { + name: 'CnConfirmDialog', + props: ['dialogTitle', 'message', 'confirmLabel'], + emits: ['confirm', 'close'], template: - '<div v-if="open" class="dialog"><slot /><slot name="actions" /></div>', + '<div class="dialog">{{ message }}<button data-testid="cn-confirm-dialog-confirm" @click="$emit(\'confirm\')">{{ confirmLabel }}</button></div>', }, })) @@ -66,9 +67,14 @@ describe('HiddenWidgetsControl', () => { .findAll('[data-testid="hidden-show-again"]')[0] .trigger('click') expect(wrapper.emitted('showAgain')[0][0]).toBe(2) + expect( + wrapper.find('[data-testid="cn-confirm-dialog-confirm"]').exists(), + ).toBe(false) await wrapper.find('[data-testid="hidden-reset"]').trigger('click') expect(wrapper.emitted('reset')).toBeUndefined() - await wrapper.find('[data-testid="hidden-reset-confirm"]').trigger('click') + await wrapper + .find('[data-testid="cn-confirm-dialog-confirm"]') + .trigger('click') expect(wrapper.emitted('reset')).toHaveLength(1) }) }) diff --git a/src/components/Workspace/__tests__/InstallBanner.spec.js b/src/components/Workspace/__tests__/InstallBanner.spec.js new file mode 100644 index 000000000..5a8101d47 --- /dev/null +++ b/src/components/Workspace/__tests__/InstallBanner.spec.js @@ -0,0 +1,130 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * InstallBanner: the phone offer to put LaunchPad on the home screen + * (platform-baseline REQ-PLB-009, board LpMobiel). + * + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text) => text, + translate: (_app, text) => text, + translatePlural: (_app, one, many, count) => (count === 1 ? one : many), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcNoteCard: { name: 'NcNoteCard', template: '<div><slot /></div>' }, + NcButton: { name: 'NcButton', emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>' }, +})) + +import InstallBanner from '../InstallBanner.vue' +import { capturePrompt, clearPrompt, NOT_NOW_KEY, NOT_NOW_MS } from '../../../utils/installPrompt.js' + +function setWidth(width) { + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width }) +} + +function setStandalone(matches) { + window.matchMedia = vi.fn(() => ({ matches })) +} + +beforeEach(() => { + window.localStorage.clear() + setWidth(390) + setStandalone(false) + clearPrompt() +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('InstallBanner', () => { + it('shows on a phone with the board text and both buttons', () => { + const wrapper = mount(InstallBanner) + const banner = wrapper.find('[data-testid="install-banner"]') + expect(banner.exists()).toBe(true) + expect(banner.attributes('role')).toBe('region') + expect(banner.text()).toContain('Put LaunchPad on your home screen') + expect(banner.text()).toContain('Then your workplace opens with one tap, like an app') + expect(wrapper.find('[data-testid="install-banner-not-now"]').text()).toBe('Not now') + expect(wrapper.find('[data-testid="install-banner-install"]').text()).toBe('Install') + }) + + it('does not show on a 1440 px screen', () => { + setWidth(1440) + expect(mount(InstallBanner).find('[data-testid="install-banner"]').exists()).toBe(false) + }) + + it('hides when the window grows past phone width', async () => { + const wrapper = mount(InstallBanner) + setWidth(1024) + window.dispatchEvent(new Event('resize')) + await wrapper.vm.$nextTick() + expect(wrapper.find('[data-testid="install-banner"]').exists()).toBe(false) + }) + + it('does not show when opened as an installed app', () => { + setStandalone(true) + expect(mount(InstallBanner).find('[data-testid="install-banner"]').exists()).toBe(false) + }) + + it('does not show in kiosk or on a public page', () => { + expect(mount(InstallBanner, { props: { kiosk: true } }).find('[data-testid="install-banner"]').exists()).toBe(false) + expect(mount(InstallBanner, { props: { isPublic: true } }).find('[data-testid="install-banner"]').exists()).toBe(false) + }) + + it('Install opens the browser prompt and hides once accepted', async () => { + const prompt = { preventDefault: vi.fn(), prompt: vi.fn(() => Promise.resolve()), userChoice: Promise.resolve({ outcome: 'accepted' }) } + capturePrompt(prompt) + const wrapper = mount(InstallBanner) + await wrapper.find('[data-testid="install-banner-install"]').trigger('click') + await flushPromises() + expect(prompt.prompt).toHaveBeenCalledTimes(1) + expect(wrapper.find('[data-testid="install-banner"]').exists()).toBe(false) + }) + + it('Install keeps the banner when the prompt is dismissed', async () => { + capturePrompt({ preventDefault: vi.fn(), prompt: vi.fn(() => Promise.resolve()), userChoice: Promise.resolve({ outcome: 'dismissed' }) }) + const wrapper = mount(InstallBanner) + await wrapper.find('[data-testid="install-banner-install"]').trigger('click') + await flushPromises() + expect(wrapper.find('[data-testid="install-banner"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="install-banner-steps"]').exists()).toBe(false) + }) + + it('Install without a browser prompt shows the steps', async () => { + const wrapper = mount(InstallBanner) + await wrapper.find('[data-testid="install-banner-install"]').trigger('click') + const steps = wrapper.find('[data-testid="install-banner-steps"]') + expect(steps.exists()).toBe(true) + expect(steps.text()).toContain('Share') + expect(steps.text()).toContain('Add to Home Screen') + }) + + it('Not now hides it and stores the moment for 30 days', async () => { + const wrapper = mount(InstallBanner) + await wrapper.find('[data-testid="install-banner-not-now"]').trigger('click') + expect(wrapper.find('[data-testid="install-banner"]').exists()).toBe(false) + expect(Number(window.localStorage.getItem(NOT_NOW_KEY))).toBeGreaterThan(0) + expect(mount(InstallBanner).find('[data-testid="install-banner"]').exists()).toBe(false) + }) + + it('shows again 30 days after Not now', () => { + window.localStorage.setItem(NOT_NOW_KEY, String(Date.now() - NOT_NOW_MS - 1000)) + expect(mount(InstallBanner).find('[data-testid="install-banner"]').exists()).toBe(true) + }) + + it('a blocked storage only means the banner shows', async () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('SecurityError') }) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('SecurityError') }) + const wrapper = mount(InstallBanner) + expect(wrapper.find('[data-testid="install-banner"]').exists()).toBe(true) + await wrapper.find('[data-testid="install-banner-not-now"]').trigger('click') + expect(wrapper.find('[data-testid="install-banner"]').exists()).toBe(false) + }) +}) diff --git a/src/components/Workspace/__tests__/LaunchpadMoreMenu.spec.js b/src/components/Workspace/__tests__/LaunchpadMoreMenu.spec.js new file mode 100644 index 000000000..a021bc0d4 --- /dev/null +++ b/src/components/Workspace/__tests__/LaunchpadMoreMenu.spec.js @@ -0,0 +1,227 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The one More menu of board LpMeer: its groups, the expandable Settings + * item at the bottom of the right column and the keyboard. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('@nextcloud/vue', () => ({ + NcPopover: { + name: 'NcPopover', + props: ['shown', 'setReturnFocus'], + emits: ['update:shown', 'afterShow'], + template: '<div><slot name="trigger" :attrs="{}" /><div v-if="shown" class="popup"><slot /></div></div>', + }, + NcButton: { + name: 'NcButton', + template: '<button type="button" v-bind="$attrs"><slot name="icon" /><slot /></button>', + }, +})) + +import LaunchpadMoreMenu from '../LaunchpadMoreMenu.vue' + +const DASHBOARDS = [ + { id: 'dashboard-1', label: 'Vandaag', meta: 'default', checked: true }, + { id: 'dashboard-2', label: 'Team Vergunningen', meta: 'shared', checked: false }, + { id: 'all-dashboards', label: 'All dashboards' }, +] +const SETTINGS = [ + { id: 'personal-settings', label: 'Personal settings' }, + { id: 'StoreMenu', label: 'Marketplace', href: '/store' }, +] +const ACTIONS = [ + { id: 'edit', label: 'Edit' }, + { id: 'delete', label: 'Delete', destructive: true }, +] + +/** + * Mount the menu, open. + * + * @param {object} props Props. + * @return {Promise<object>} The wrapper. + */ +async function openMenu(props = {}) { + const wrapper = mount(LaunchpadMoreMenu, { + attachTo: document.body, + props: { dashboards: DASHBOARDS, settings: SETTINGS, actions: ACTIONS, ...props }, + }) + wrapper.vm.open = true + await flushPromises() + return wrapper +} + +const ids = (wrapper) => wrapper.findAll('.lp-more-menu__item').map((el) => el.attributes('data-testid')) +const panel = (wrapper) => wrapper.find('[data-testid="launchpad-more-menu-panel"]') + +describe('LaunchpadMoreMenu', () => { + it('is a menu named More with Dashboards left, This dashboard and then Settings right', async () => { + const wrapper = await openMenu() + expect(panel(wrapper).attributes('role')).toBe('menu') + expect(panel(wrapper).attributes('aria-label')).toBe('More') + const columns = wrapper.findAll('.lp-more-menu__column') + expect(columns).toHaveLength(2) + expect(columns[0].text()).toContain('Dashboards') + expect(columns[0].find('[data-testid="launchpad-more-menu-settings"]').exists()).toBe(false) + expect(columns[1].text()).toContain('This dashboard') + const right = [...columns[1].element.children] + expect(right.map((el) => el.getAttribute('data-testid'))).toEqual([ + 'launchpad-more-menu-group-this-dashboard', + 'launchpad-more-menu-settings', + 'launchpad-more-menu-group-settings', + ]) + wrapper.unmount() + }) + + it('puts Settings alone in the right column off the dashboard view', async () => { + const wrapper = await openMenu({ actions: [] }) + const columns = wrapper.findAll('.lp-more-menu__column') + expect(columns).toHaveLength(2) + expect(panel(wrapper).classes()).not.toContain('lp-more-menu__panel--single') + expect(columns[0].text()).toContain('Dashboards') + expect(columns[1].find('[data-testid="launchpad-more-menu-group-this-dashboard"]').exists()).toBe(false) + expect(columns[1].element.firstElementChild.getAttribute('data-testid')).toBe('launchpad-more-menu-settings') + wrapper.unmount() + }) + + it('marks the open dashboard as the checked radio item, with its marker', async () => { + const wrapper = await openMenu() + const today = wrapper.find('[data-testid="launchpad-more-menu-item-dashboard-1"]') + expect(today.attributes('role')).toBe('menuitemradio') + expect(today.attributes('aria-checked')).toBe('true') + expect(today.text()).toContain('default') + expect(wrapper.find('[data-testid="launchpad-more-menu-item-dashboard-2"]').attributes('aria-checked')).toBe('false') + const all = wrapper.find('[data-testid="launchpad-more-menu-item-all-dashboards"]') + expect(all.attributes('role')).toBe('menuitem') + expect(all.attributes('aria-checked')).toBeUndefined() + wrapper.unmount() + }) + + it('folds Settings into one item that unfolds in place', async () => { + const wrapper = await openMenu() + const toggle = wrapper.find('[data-testid="launchpad-more-menu-settings"]') + expect(toggle.attributes('role')).toBe('menuitem') + expect(toggle.attributes('aria-haspopup')).toBe('true') + expect(toggle.attributes('aria-expanded')).toBe('false') + const group = wrapper.find('[data-testid="launchpad-more-menu-group-settings"]') + expect(group.isVisible()).toBe(false) + + await toggle.trigger('click') + expect(toggle.attributes('aria-expanded')).toBe('true') + expect(group.isVisible()).toBe(true) + expect(group.attributes('role')).toBe('group') + expect(toggle.attributes('aria-controls')).toBe(group.attributes('id')) + expect(group.findAll('[role="menuitem"]').map((el) => el.text())).toEqual(['Personal settings', 'Marketplace']) + expect(wrapper.vm.open).toBe(true) + wrapper.unmount() + }) + + it('starts folded again every time it opens', async () => { + const wrapper = await openMenu() + await wrapper.find('[data-testid="launchpad-more-menu-settings"]').trigger('click') + wrapper.vm.open = false + await flushPromises() + wrapper.vm.open = true + await flushPromises() + expect(wrapper.find('[data-testid="launchpad-more-menu-settings"]').attributes('aria-expanded')).toBe('false') + expect(wrapper.emitted('open')).toHaveLength(2) + wrapper.unmount() + }) + + it('puts Delete last in the This dashboard group', async () => { + const wrapper = await openMenu() + const items = wrapper.find('[data-testid="launchpad-more-menu-group-this-dashboard"]').findAll('.lp-more-menu__item') + expect(items.at(-1).text()).toBe('Delete') + expect(items.at(-1).classes()).toContain('lp-more-menu__item--destructive') + wrapper.unmount() + }) + + it('draws one column without a dashboard to act on, and no Settings item without settings', async () => { + const wrapper = await openMenu({ actions: [], settings: [] }) + expect(wrapper.findAll('.lp-more-menu__column')).toHaveLength(1) + expect(panel(wrapper).classes()).toContain('lp-more-menu__panel--single') + expect(wrapper.find('[data-testid="launchpad-more-menu-settings"]').exists()).toBe(false) + wrapper.unmount() + }) + + it('runs a chosen item and closes', async () => { + const onClick = vi.fn() + const wrapper = await openMenu({ actions: [{ id: 'edit', label: 'Edit', onClick }] }) + await wrapper.find('[data-testid="launchpad-more-menu-item-edit"]').trigger('click') + expect(onClick).toHaveBeenCalledTimes(1) + expect(wrapper.emitted('select')[0][0].id).toBe('edit') + expect(wrapper.vm.open).toBe(false) + wrapper.unmount() + }) + + it('renders a link item as a link', async () => { + const wrapper = await openMenu() + const store = wrapper.find('[data-testid="launchpad-more-menu-item-StoreMenu"]') + expect(store.element.tagName).toBe('A') + expect(store.attributes('href')).toBe('/store') + wrapper.unmount() + }) + + it('moves with the arrow keys over every visible item, across both columns', async () => { + const wrapper = await openMenu() + wrapper.vm.focusItem(0) + const active = () => document.activeElement.getAttribute('data-testid') + expect(active()).toBe('launchpad-more-menu-item-dashboard-1') + await panel(wrapper).trigger('keydown', { key: 'ArrowUp' }) + expect(active()).toBe('launchpad-more-menu-settings') + await panel(wrapper).trigger('keydown', { key: 'ArrowUp' }) + expect(active()).toBe('launchpad-more-menu-item-delete') + await panel(wrapper).trigger('keydown', { key: 'Home' }) + expect(active()).toBe('launchpad-more-menu-item-dashboard-1') + await panel(wrapper).trigger('keydown', { key: 'End' }) + expect(active()).toBe('launchpad-more-menu-settings') + // The folded Settings items are skipped. + expect(ids(wrapper)).toContain('launchpad-more-menu-item-personal-settings') + expect(wrapper.vm.itemElements().map((el) => el.getAttribute('data-testid'))).toEqual([ + 'launchpad-more-menu-item-dashboard-1', + 'launchpad-more-menu-item-dashboard-2', + 'launchpad-more-menu-item-all-dashboards', + 'launchpad-more-menu-item-edit', + 'launchpad-more-menu-item-delete', + 'launchpad-more-menu-settings', + ]) + wrapper.unmount() + }) + + it('unfolds Settings with Right and folds it with Left, keeping focus', async () => { + const wrapper = await openMenu() + const toggle = wrapper.find('[data-testid="launchpad-more-menu-settings"]') + toggle.element.focus() + await panel(wrapper).trigger('keydown', { key: 'ArrowRight' }) + await flushPromises() + expect(toggle.attributes('aria-expanded')).toBe('true') + expect(document.activeElement.getAttribute('data-testid')).toBe('launchpad-more-menu-item-personal-settings') + await panel(wrapper).trigger('keydown', { key: 'ArrowDown' }) + expect(document.activeElement.getAttribute('data-testid')).toBe('launchpad-more-menu-item-StoreMenu') + await panel(wrapper).trigger('keydown', { key: 'End' }) + expect(document.activeElement.getAttribute('data-testid')).toBe('launchpad-more-menu-item-StoreMenu') + await panel(wrapper).trigger('keydown', { key: 'ArrowDown' }) + expect(document.activeElement.getAttribute('data-testid')).toBe('launchpad-more-menu-item-dashboard-1') + await panel(wrapper).trigger('keydown', { key: 'ArrowUp' }) + expect(document.activeElement.getAttribute('data-testid')).toBe('launchpad-more-menu-item-StoreMenu') + + await panel(wrapper).trigger('keydown', { key: 'ArrowLeft' }) + expect(toggle.attributes('aria-expanded')).toBe('false') + expect(document.activeElement).toBe(toggle.element) + wrapper.unmount() + }) + + it('closes on Escape and returns focus to More', async () => { + const wrapper = await openMenu() + wrapper.vm.focusItem(0) + await panel(wrapper).trigger('keydown', { key: 'Escape' }) + expect(wrapper.vm.open).toBe(false) + expect(document.activeElement.getAttribute('data-testid')).toBe('launchpad-more-menu-trigger') + expect(wrapper.vm.returnFocus()).toBe(wrapper.find('[data-testid="launchpad-more-menu-trigger"]').element) + wrapper.unmount() + }) +}) diff --git a/src/components/Workspace/__tests__/PhoneHiddenNotice.spec.js b/src/components/Workspace/__tests__/PhoneHiddenNotice.spec.js new file mode 100644 index 000000000..daf2f5961 --- /dev/null +++ b/src/components/Workspace/__tests__/PhoneHiddenNotice.spec.js @@ -0,0 +1,51 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * PhoneHiddenNotice: on a phone, the notice names the hidden widgets and + * "Which?" explains why (launchpad-mobile-remote-access REQ-MRA-007). + * + * @spec openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/specs/launchpad-mobile-remote-access/spec.md#requirement-the-phone-notice-names-the-hidden-widgets-req-mra-007 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => String(vars[k])), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcNoteCard: { name: 'NcNoteCard', template: '<div><slot /></div>' }, + NcButton: { name: 'NcButton', emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>' }, +})) + +import PhoneHiddenNotice from '../PhoneHiddenNotice.vue' + +describe('PhoneHiddenNotice', () => { + it('shows nothing when no widget is hidden', () => { + const wrapper = mount(PhoneHiddenNotice, { props: { titles: [] } }) + expect(wrapper.find('[data-testid="phone-hidden-notice"]').exists()).toBe(false) + }) + + it('names the hidden widgets with a Which? link and no desktop layout link', () => { + const wrapper = mount(PhoneHiddenNotice, { props: { titles: ['Snel beginnen (Word)', 'Assistent'] } }) + expect(wrapper.find('[data-testid="phone-hidden-sentence"]').text()) + .toBe('2 widgets do not work on a phone and are hidden: Snel beginnen (Word) and Assistent.') + expect(wrapper.find('[data-testid="phone-hidden-which"]').text()).toBe('Which?') + expect(wrapper.text()).not.toMatch(/desktop/i) + }) + + it('explains on Which? and hides the explanation again', async () => { + const wrapper = mount(PhoneHiddenNotice, { props: { titles: ['Assistent'] } }) + expect(wrapper.find('[data-testid="phone-hidden-why"]').exists()).toBe(false) + await wrapper.find('[data-testid="phone-hidden-which"]').trigger('click') + expect(wrapper.find('[data-testid="phone-hidden-why"]').text()).toContain('larger screen') + await wrapper.find('[data-testid="phone-hidden-which"]').trigger('click') + expect(wrapper.find('[data-testid="phone-hidden-why"]').exists()).toBe(false) + }) + + it('names three of five and counts the rest', () => { + const wrapper = mount(PhoneHiddenNotice, { props: { titles: ['A', 'B', 'C', 'D', 'E'] } }) + expect(wrapper.text()).toContain('A, B, C and 2 more') + }) +}) diff --git a/src/components/Workspace/__tests__/StartPageGreeting.spec.js b/src/components/Workspace/__tests__/StartPageGreeting.spec.js new file mode 100644 index 000000000..2841caf40 --- /dev/null +++ b/src/components/Workspace/__tests__/StartPageGreeting.spec.js @@ -0,0 +1,85 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The start page header greets the reader (board LpVandaag, LpStart): the + * header placement of the start page template renders the day-part greeting, + * the first name, the date and the ISO week number. + * + * @spec openspec/changes/archive/2026-11-24-start-page-board-sync/specs/lpvandaag-start-page/spec.md#requirement-the-start-page-greets-the-reader + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), + translatePlural: (_app, one, many, count) => + (count === 1 ? one : many).replace('%n', String(count)), + getCanonicalLocale: () => 'en-GB', + getLanguage: () => 'en', + getLocale: () => 'en_GB', +})) +vi.mock('@nextcloud/auth', () => ({ + getCurrentUser: () => ({ uid: 'pieter', displayName: 'Pieter Jansen', isAdmin: false }), +})) + +import CnHeaderWidget from '@conduction/nextcloud-vue/src/components/CnHeaderWidget/CnHeaderWidget.vue' + +/** + * Mount the header at a given local time with the start page's content. + * + * @param {string} at Local date and time, as 2026-10-05T13:10:00. + * @param {object} content Extra header content. + * @return {object} The wrapper. + */ +function headerAt(at, content = {}) { + vi.setSystemTime(new Date(at)) + return mount(CnHeaderWidget, { + props: { content: { title: 'Vandaag', greeting: true, showDate: true, greetingLine: true, ...content } }, + }) +} + +beforeEach(() => { + vi.useFakeTimers() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('Start page greeting', () => { + it.each([ + ['2026-10-05T11:59:00', 'Good morning, Pieter'], + ['2026-10-05T12:00:00', 'Good afternoon, Pieter'], + ['2026-10-05T17:59:00', 'Good afternoon, Pieter'], + ['2026-10-05T18:00:00', 'Good evening, Pieter'], + ])('greets for the part of the day at %s', (at, greeting) => { + const line = headerAt(at).find('.cn-header-widget__line').text() + expect(line.startsWith(greeting + ' · ')).toBe(true) + }) + + it('uses the first name only and writes out the date', () => { + const line = headerAt('2026-10-05T13:10:00').find('.cn-header-widget__line').text() + expect(line).not.toContain('Jansen') + expect(line).toContain('Monday') + expect(line).toContain('5 October 2026') + }) + + it('adds the ISO week number with showWeek', () => { + const line = headerAt('2026-10-05T13:10:00', { showWeek: true }).find('.cn-header-widget__line').text() + expect(line.endsWith(' · week 41')).toBe(true) + }) + + it('shows no week number without showWeek', () => { + const line = headerAt('2026-10-05T13:10:00').find('.cn-header-widget__line').text() + expect(line).not.toContain('week') + }) + + it('is text a screen reader reads, not an image', () => { + const wrapper = headerAt('2026-10-05T13:10:00') + expect(wrapper.find('.cn-header-widget__line').element.tagName).not.toBe('IMG') + expect(wrapper.find('.cn-header-widget__title').text()).toBe('Vandaag') + }) +}) diff --git a/src/components/Workspace/__tests__/StartPageMenu.spec.js b/src/components/Workspace/__tests__/StartPageMenu.spec.js new file mode 100644 index 000000000..8e0033944 --- /dev/null +++ b/src/components/Workspace/__tests__/StartPageMenu.spec.js @@ -0,0 +1,129 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The More menu off the dashboard view (runtime-shell REQ-SHELL-009, + * REQ-SHELL-013): the same menu as on the dashboard view, with the + * dashboards and Settings and no This dashboard group. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, text) => text, + translate: (_app, text) => text, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (tpl, vars) => tpl.replace('{appId}', vars?.appId), +})) +vi.mock('../LaunchpadMoreMenu.vue', () => ({ + default: { + name: 'LaunchpadMoreMenu', + props: ['dashboards', 'settings', 'actions'], + emits: ['open'], + template: '<div class="menu-stub" />', + }, +})) +vi.mock('../../../services/api.js', () => ({ + api: { getDefaultDashboardPreference: vi.fn() }, +})) + +import StartPageMenu from '../StartPageMenu.vue' +import { api } from '../../../services/api.js' +import { useDashboardStore } from '../../../stores/dashboard.js' + +const ENTRIES = [ + { id: 'dashboards', label: 'Dashboards', route: 'Workspace' }, + { id: 'Documentation', label: 'Documentation', href: 'https://launchpad.conduction.nl', section: 'footer' }, + { id: 'StoreMenu', label: 'Marketplace', route: 'Store', section: 'footer' }, + { id: 'FlowsMenu', label: 'Flows', route: 'Flows', section: 'settings' }, +] + +/** + * Mount the menu. + * + * @param {object|null} chrome The chrome decision. + * @return {object} The wrapper, the menu stub and the router. + */ +function mountMenu(chrome = { railSuppressed: true, entries: ENTRIES, isAdmin: false }) { + const router = { push: vi.fn() } + const wrapper = mount(StartPageMenu, { + global: { + provide: { launchpadChrome: chrome, cnOpenUserSettings: vi.fn() }, + mocks: { $router: router }, + }, + }) + return { wrapper, menu: wrapper.findComponent({ name: 'LaunchpadMoreMenu' }), router } +} + +describe('StartPageMenu', () => { + let store + + beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + store = useDashboardStore() + store.loadedOnce = true + store.dashboards = [ + { id: 1, uuid: 'u-1', name: 'Vandaag', source: 'user' }, + { id: 2, uuid: 'u-2', name: 'Team Vergunningen', source: 'group' }, + ] + api.getDefaultDashboardPreference.mockResolvedValue({ data: { uuid: 'u-1' } }) + }) + + it('renders nothing while the panel is rendered, or when nothing was provided', () => { + expect(mountMenu({ railSuppressed: false, entries: ENTRIES }).menu.exists()).toBe(false) + expect(mountMenu(null).menu.exists()).toBe(false) + }) + + it('offers the dashboards and Settings, and no This dashboard group', () => { + const { menu } = mountMenu() + expect(menu.props('dashboards').map((i) => i.id)).toEqual(['dashboard-1', 'dashboard-2', 'all-dashboards']) + expect(menu.props('dashboards').some((i) => i.checked === true)).toBe(false) + expect(menu.props('settings').map((i) => i.id)).toEqual(['personal-settings', 'StoreMenu', 'FlowsMenu', 'Documentation']) + expect(menu.props('actions')).toBeUndefined() + }) + + it('carries the tour target of the More menu', () => { + const { wrapper } = mountMenu() + expect(wrapper.attributes('data-walkthrough-id')).toBe('launchpad-more-menu') + }) + + it('opens a chosen dashboard on the dashboard view, and All dashboards goes there', () => { + const { menu, router } = mountMenu() + menu.props('dashboards')[1].onClick() + expect(router.push).toHaveBeenCalledWith({ name: 'dashboard-detail', params: { id: '2' } }) + menu.props('dashboards').at(-1).onClick() + expect(router.push).toHaveBeenLastCalledWith({ name: 'Workspace' }) + }) + + it('reads the default dashboard once, on first open, and marks it', async () => { + const { menu } = mountMenu() + menu.vm.$emit('open') + await flushPromises() + menu.vm.$emit('open') + await flushPromises() + expect(api.getDefaultDashboardPreference).toHaveBeenCalledTimes(1) + expect(menu.props('dashboards')[0].meta).toBe('default') + }) + + it('reads the dashboards on open when the page has not', async () => { + store.loadedOnce = false + const load = vi.spyOn(store, 'loadDashboards').mockResolvedValue() + const { menu } = mountMenu() + menu.vm.$emit('open') + await flushPromises() + expect(load).toHaveBeenCalledTimes(1) + }) + + it('keeps the menu working when the default cannot be read', async () => { + api.getDefaultDashboardPreference.mockRejectedValue(new Error('500')) + const { menu } = mountMenu() + menu.vm.$emit('open') + await flushPromises() + expect(menu.props('dashboards')[0].meta).toBeUndefined() + }) +}) diff --git a/src/components/Workspace/__tests__/TileSidePanel.spec.js b/src/components/Workspace/__tests__/TileSidePanel.spec.js new file mode 100644 index 000000000..bfdb193d2 --- /dev/null +++ b/src/components/Workspace/__tests__/TileSidePanel.spec.js @@ -0,0 +1,96 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The panel beside the tiles: open, replace, close, focus return and the + * refused-framing fallback (launcher-tile-open-behaviour D3, D4). + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const checkIframeFramable = vi.fn() + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? ''), +})) +vi.mock('@nextcloud/vue', () => ({ + NcButton: { name: 'NcButton', emits: ['click'], template: '<button v-bind="$attrs" @click="$emit(\'click\')"><slot name="icon" /><slot /></button>' }, +})) +vi.mock('vue-material-design-icons/Close.vue', () => ({ default: { name: 'CloseIcon', template: '<i />' } })) +vi.mock('../../../services/iframeClient.js', () => ({ checkIframeFramable })) + +const { default: TileSidePanel } = await import('../TileSidePanel.vue') +const { useTilePanelStore } = await import('../../../stores/tilePanel.js') + +describe('TileSidePanel', () => { + beforeEach(() => { + setActivePinia(createPinia()) + checkIframeFramable.mockReset() + }) + + it('renders nothing while closed', () => { + expect(mount(TileSidePanel).find('[data-test="tile-side-panel"]').exists()).toBe(false) + }) + + it('frames an address on this Nextcloud without asking, with the tile title and a new-tab link', async () => { + const wrapper = mount(TileSidePanel, { attachTo: document.body }) + useTilePanelStore().open({ url: '/nc/apps/files', title: 'Files', sameOrigin: true }) + await flushPromises() + + const frame = wrapper.find('[data-test="tile-side-panel-frame"]') + expect(frame.attributes('src')).toBe('/nc/apps/files') + expect(frame.attributes('title')).toBe('Files') + expect(wrapper.find('.tile-side-panel__external').attributes()).toMatchObject({ href: '/nc/apps/files', target: '_blank' }) + expect(checkIframeFramable).not.toHaveBeenCalled() + expect(document.activeElement).toBe(wrapper.find('[data-test="tile-side-panel"]').element) + wrapper.unmount() + }) + + it('asks the server before framing an outside address, and shows the fallback when refused', async () => { + checkIframeFramable.mockResolvedValueOnce({ framable: false, reason: 'host_not_allowed' }) + const wrapper = mount(TileSidePanel) + useTilePanelStore().open({ url: 'https://blocked.example', title: 'Blocked' }) + await flushPromises() + + expect(checkIframeFramable).toHaveBeenCalledWith('https://blocked.example') + expect(wrapper.find('[data-test="tile-side-panel-frame"]').exists()).toBe(false) + const fallback = wrapper.find('[data-test="tile-side-panel-fallback"]') + expect(fallback.text()).toContain('Open in new tab') + expect(fallback.find('a').attributes('href')).toBe('https://blocked.example') + }) + + it('frames an outside address the server allows, and a newer tile replaces it', async () => { + checkIframeFramable.mockResolvedValue({ framable: true }) + const wrapper = mount(TileSidePanel) + const panel = useTilePanelStore() + panel.open({ url: 'https://ok.example', title: 'Ok' }) + await flushPromises() + expect(wrapper.find('[data-test="tile-side-panel-frame"]').attributes('src')).toBe('https://ok.example') + + panel.open({ url: '/nc/apps/deck', title: 'Deck', sameOrigin: true }) + await flushPromises() + expect(wrapper.findAll('iframe')).toHaveLength(1) + expect(wrapper.find('iframe').attributes('src')).toBe('/nc/apps/deck') + }) + + it('closes on the close button and on Escape, returning focus to the tile', async () => { + const opener = { focus: vi.fn() } + const wrapper = mount(TileSidePanel) + const panel = useTilePanelStore() + + panel.open({ url: '/nc/apps/files', title: 'Files', sameOrigin: true, opener }) + await flushPromises() + await wrapper.find('[data-test="tile-side-panel-close"]').trigger('click') + expect(panel.isOpen).toBe(false) + + panel.open({ url: '/nc/apps/files', title: 'Files', sameOrigin: true, opener }) + await flushPromises() + await wrapper.find('[data-test="tile-side-panel"]').trigger('keydown', { key: 'Escape' }) + expect(panel.isOpen).toBe(false) + expect(opener.focus).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.all-four-sections.html b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.all-four-sections.html new file mode 100644 index 000000000..b515ea308 --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.all-four-sections.html @@ -0,0 +1,42 @@ +<div data-v-2d41f6f3="" class="dashboard-switcher-sidebar__body"> + <div data-v-2d41f6f3="" class="filter" fields=""></div> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="group"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">Team</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"> + <li data-v-2d41f6f3="" class="dashboard-switcher-sidebar__item" data-depth="0" data-source="group" tabindex="0" role="button" aria-label="Team Board"><button data-v-2d41f6f3="" type="button" class="dashboard-switcher-sidebar__expander" data-testid="tree-expand-ug" aria-expanded="false" aria-label="Expand Team Board"><span data-v-2d41f6f3="" aria-hidden="true" class="material-design-icon chevron-right-icon" role="img"><svg fill="currentColor" class="material-design-icon__svg" width="16" height="16" viewBox="0 0 24 24"><path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z"></path></svg></span></button><span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__icon"><i data-v-2d41f6f3="" class="icon" data-name="Star"></i></span> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__label">Team Board</span><span data-v-2d41f6f3="" class="row-actions-stub" data-source="group" data-can-edit="true" data-default-uuid="ud" data-edit-mode="false" data-active="4"></span> + </li> + </ul> + </section> + <hr data-v-2d41f6f3="" class="dashboard-switcher-sidebar__divider"> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="default"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">Default</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"> + <li data-v-2d41f6f3="" class="dashboard-switcher-sidebar__item" data-depth="0" data-source="default" tabindex="0" role="button" aria-label="Org Default"> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__icon"><i data-v-2d41f6f3="" class="icon" data-name="Home"></i></span><span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__default-marker" title="Default dashboard — opens automatically when you visit LaunchPad" aria-label="Default dashboard"><span data-v-2d41f6f3="" aria-hidden="true" class="material-design-icon star-icon" role="img"><svg fill="currentColor" class="material-design-icon__svg" width="16" height="16" viewBox="0 0 24 24"><path d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path></svg></span></span><span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__label">Org Default</span><span data-v-2d41f6f3="" class="row-actions-stub" data-source="default" data-can-edit="true" data-default-uuid="ud" data-edit-mode="false" data-active="4"></span> + </li> + </ul> + </section> + <hr data-v-2d41f6f3="" class="dashboard-switcher-sidebar__divider"> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="user"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">My Dashboards</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"> + <li data-v-2d41f6f3="" class="dashboard-switcher-sidebar__item dashboard-switcher-sidebar__item--personal active" data-depth="0" data-source="user" tabindex="0" role="button" aria-label="My Notes"> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__icon"><i data-v-2d41f6f3="" class="icon"></i></span> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__label">My Notes</span><span data-v-2d41f6f3="" class="row-actions-stub" data-source="user" data-can-edit="true" data-default-uuid="ud" data-edit-mode="false" data-active="4"></span> + </li> + </ul> + <div data-v-2d41f6f3="" class="dashboard-switcher-sidebar__add-dashboard-card"><button data-v-2d41f6f3="" class="nc-button" variant="secondary" wide="" data-action="create" data-testid="add-dashboard-button" aria-label="Add dashboard"><span data-v-2d41f6f3="" aria-hidden="true" class="material-design-icon plus-icon" role="img"><svg fill="currentColor" class="material-design-icon__svg" width="20" height="20" viewBox="0 0 24 24"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z"></path></svg></span> Add dashboard</button> + </div> + </section> + <hr data-v-2d41f6f3="" class="dashboard-switcher-sidebar__divider"> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="shared"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">Shared with you</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"> + <li data-v-2d41f6f3="" class="dashboard-switcher-sidebar__item" data-depth="0" data-source="shared" tabindex="0" role="button" aria-label="Shared One"> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__icon"><i data-v-2d41f6f3="" class="icon" data-name="Share"></i></span> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__label">Shared One</span><span data-v-2d41f6f3="" class="row-actions-stub" data-source="shared" data-can-edit="true" data-default-uuid="ud" data-edit-mode="false" data-active="4"></span> + </li> + </ul> + </section> +</div> \ No newline at end of file diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.default-and-shared-only.html b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.default-and-shared-only.html new file mode 100644 index 000000000..37a749b3f --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.default-and-shared-only.html @@ -0,0 +1,21 @@ +<div data-v-2d41f6f3="" class="dashboard-switcher-sidebar__body"> + <div data-v-2d41f6f3="" class="filter" fields=""></div> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="default"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">Default</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"> + <li data-v-2d41f6f3="" class="dashboard-switcher-sidebar__item" data-depth="0" data-source="default" tabindex="0" role="button" aria-label="Org Default"> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__icon"><i data-v-2d41f6f3="" class="icon" data-name="Home"></i></span><span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__default-marker" title="Default dashboard — opens automatically when you visit LaunchPad" aria-label="Default dashboard"><span data-v-2d41f6f3="" aria-hidden="true" class="material-design-icon star-icon" role="img"><svg fill="currentColor" class="material-design-icon__svg" width="16" height="16" viewBox="0 0 24 24"><path d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path></svg></span></span><span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__label">Org Default</span><span data-v-2d41f6f3="" class="row-actions-stub" data-source="default" data-can-edit="false" data-default-uuid="" data-edit-mode="false"></span> + </li> + </ul> + </section> + <hr data-v-2d41f6f3="" class="dashboard-switcher-sidebar__divider"> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="shared"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">Shared with you</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"> + <li data-v-2d41f6f3="" class="dashboard-switcher-sidebar__item" data-depth="0" data-source="shared" tabindex="0" role="button" aria-label="Shared One"> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__icon"><i data-v-2d41f6f3="" class="icon" data-name="Share"></i></span> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__label">Shared One</span><span data-v-2d41f6f3="" class="row-actions-stub" data-source="shared" data-can-edit="false" data-default-uuid="" data-edit-mode="false"></span> + </li> + </ul> + </section> +</div> \ No newline at end of file diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-default.json b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-default.json new file mode 100644 index 000000000..70197590c --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-default.json @@ -0,0 +1,81 @@ +{ + "update:open": [ + [ + false + ], + [ + false + ], + [ + false + ] + ], + "switch": [ + [ + 3, + "default" + ], + [ + 3, + "default" + ], + [ + 3, + "default" + ] + ], + "toggleEdit": [ + [ + { + "id": 3, + "uuid": "ud", + "name": "Org Default", + "icon": "Home", + "source": "default" + }, + "default" + ] + ], + "openConfig": [ + [ + { + "id": 3, + "uuid": "ud", + "name": "Org Default", + "icon": "Home", + "source": "default" + }, + "default" + ] + ], + "addWidget": [ + [ + { + "id": 3, + "uuid": "ud", + "name": "Org Default", + "icon": "Home", + "source": "default" + }, + "default" + ] + ], + "deleteDashboard": [ + [ + 3, + "default" + ] + ], + "setDefault": [ + [ + { + "id": 3, + "uuid": "ud", + "name": "Org Default", + "icon": "Home", + "source": "default" + }, + "default" + ] + ] +} \ No newline at end of file diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-group.json b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-group.json new file mode 100644 index 000000000..79f08db1a --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-group.json @@ -0,0 +1,81 @@ +{ + "update:open": [ + [ + false + ], + [ + false + ], + [ + false + ] + ], + "switch": [ + [ + 1, + "group" + ], + [ + 1, + "group" + ], + [ + 1, + "group" + ] + ], + "toggleEdit": [ + [ + { + "id": 1, + "uuid": "ug", + "name": "Team Board", + "icon": "Star", + "source": "group" + }, + "group" + ] + ], + "openConfig": [ + [ + { + "id": 1, + "uuid": "ug", + "name": "Team Board", + "icon": "Star", + "source": "group" + }, + "group" + ] + ], + "addWidget": [ + [ + { + "id": 1, + "uuid": "ug", + "name": "Team Board", + "icon": "Star", + "source": "group" + }, + "group" + ] + ], + "deleteDashboard": [ + [ + 1, + "group" + ] + ], + "setDefault": [ + [ + { + "id": 1, + "uuid": "ug", + "name": "Team Board", + "icon": "Star", + "source": "group" + }, + "group" + ] + ] +} \ No newline at end of file diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-shared.json b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-shared.json new file mode 100644 index 000000000..4e5f16bc5 --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-shared.json @@ -0,0 +1,81 @@ +{ + "update:open": [ + [ + false + ], + [ + false + ], + [ + false + ] + ], + "switch": [ + [ + 5, + "shared" + ], + [ + 5, + "shared" + ], + [ + 5, + "shared" + ] + ], + "toggleEdit": [ + [ + { + "id": 5, + "uuid": "us", + "name": "Shared One", + "icon": "Share", + "source": "shared" + }, + "shared" + ] + ], + "openConfig": [ + [ + { + "id": 5, + "uuid": "us", + "name": "Shared One", + "icon": "Share", + "source": "shared" + }, + "shared" + ] + ], + "addWidget": [ + [ + { + "id": 5, + "uuid": "us", + "name": "Shared One", + "icon": "Share", + "source": "shared" + }, + "shared" + ] + ], + "deleteDashboard": [ + [ + 5, + "shared" + ] + ], + "setDefault": [ + [ + { + "id": 5, + "uuid": "us", + "name": "Shared One", + "icon": "Share", + "source": "shared" + }, + "shared" + ] + ] +} \ No newline at end of file diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-user.json b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-user.json new file mode 100644 index 000000000..c44edad98 --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.emits-user.json @@ -0,0 +1,81 @@ +{ + "update:open": [ + [ + false + ], + [ + false + ], + [ + false + ] + ], + "switch": [ + [ + 4, + "user" + ], + [ + 4, + "user" + ], + [ + 4, + "user" + ] + ], + "toggleEdit": [ + [ + { + "id": 4, + "uuid": "uu", + "name": "My Notes", + "icon": null, + "source": "user" + }, + "user" + ] + ], + "openConfig": [ + [ + { + "id": 4, + "uuid": "uu", + "name": "My Notes", + "icon": null, + "source": "user" + }, + "user" + ] + ], + "addWidget": [ + [ + { + "id": 4, + "uuid": "uu", + "name": "My Notes", + "icon": null, + "source": "user" + }, + "user" + ] + ], + "deleteDashboard": [ + [ + 4, + "user" + ] + ], + "setDefault": [ + [ + { + "id": 4, + "uuid": "uu", + "name": "My Notes", + "icon": null, + "source": "user" + }, + "user" + ] + ] +} \ No newline at end of file diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.group-and-user-without-card.html b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.group-and-user-without-card.html new file mode 100644 index 000000000..5209b586f --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.group-and-user-without-card.html @@ -0,0 +1,21 @@ +<div data-v-2d41f6f3="" class="dashboard-switcher-sidebar__body"> + <div data-v-2d41f6f3="" class="filter" fields=""></div> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="group"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">Team</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"> + <li data-v-2d41f6f3="" class="dashboard-switcher-sidebar__item" data-depth="0" data-source="group" tabindex="0" role="button" aria-label="Team Board"> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__icon"><i data-v-2d41f6f3="" class="icon" data-name="Star"></i></span><span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__default-marker" title="Default dashboard — opens automatically when you visit LaunchPad" aria-label="Default dashboard"><span data-v-2d41f6f3="" aria-hidden="true" class="material-design-icon star-icon" role="img"><svg fill="currentColor" class="material-design-icon__svg" width="16" height="16" viewBox="0 0 24 24"><path d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path></svg></span></span><span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__label">Team Board</span><span data-v-2d41f6f3="" class="row-actions-stub" data-source="group" data-can-edit="false" data-default-uuid="" data-edit-mode="false"></span> + </li> + </ul> + </section> + <hr data-v-2d41f6f3="" class="dashboard-switcher-sidebar__divider"> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="user"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">My Dashboards</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"> + <li data-v-2d41f6f3="" class="dashboard-switcher-sidebar__item dashboard-switcher-sidebar__item--personal" data-depth="0" data-source="user" tabindex="0" role="button" aria-label="My Notes"> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__icon"><i data-v-2d41f6f3="" class="icon"></i></span> + <span data-v-2d41f6f3="" class="dashboard-switcher-sidebar__label">My Notes</span><span data-v-2d41f6f3="" class="row-actions-stub" data-source="user" data-can-edit="false" data-default-uuid="" data-edit-mode="false"></span> + </li> + </ul> + </section> +</div> \ No newline at end of file diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.nothing.html b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.nothing.html new file mode 100644 index 000000000..86586ed7b --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.nothing.html @@ -0,0 +1,3 @@ +<div data-v-2d41f6f3="" class="dashboard-switcher-sidebar__body"> + <div data-v-2d41f6f3="" class="filter" fields=""></div> +</div> \ No newline at end of file diff --git a/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.personal-card-only.html b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.personal-card-only.html new file mode 100644 index 000000000..c9a1096e1 --- /dev/null +++ b/src/components/Workspace/__tests__/__snapshots__/DashboardSwitcherSidebar.golden.personal-card-only.html @@ -0,0 +1,10 @@ +<div data-v-2d41f6f3="" class="dashboard-switcher-sidebar__body"> + <div data-v-2d41f6f3="" class="filter" fields=""></div> + <section data-v-2d41f6f3="" class="dashboard-switcher-sidebar__section" data-section="user"> + <h3 data-v-2d41f6f3="" class="dashboard-switcher-sidebar__heading">My Dashboards</h3> + <ul data-v-2d41f6f3="" class="dashboard-switcher-sidebar__list"></ul> + <div data-v-2d41f6f3="" class="dashboard-switcher-sidebar__add-dashboard-card"><button data-v-2d41f6f3="" class="nc-button" variant="secondary" wide="" data-action="create" data-testid="add-dashboard-button" disabled="" title="" aria-label=""><span data-v-2d41f6f3="" aria-hidden="true" class="material-design-icon plus-icon" role="img"><svg fill="currentColor" class="material-design-icon__svg" width="20" height="20" viewBox="0 0 24 24"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z"></path></svg></span> Add dashboard</button> + <p data-v-2d41f6f3="" class="dashboard-switcher-sidebar__quota-hint" data-testid="dashboard-quota-hint"></p> + </div> + </section> +</div> \ No newline at end of file diff --git a/src/components/Workspace/__tests__/moreMenuItems.spec.js b/src/components/Workspace/__tests__/moreMenuItems.spec.js new file mode 100644 index 000000000..2004cc024 --- /dev/null +++ b/src/components/Workspace/__tests__/moreMenuItems.spec.js @@ -0,0 +1,173 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The items of the one More menu (board LpMeer): the Dashboards group, the + * order under Settings and the This dashboard group with its permission + * rules. + */ + +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (tpl, vars) => tpl.replace('{appId}', vars?.appId), +})) + +import { + DASHBOARD_LIMIT, + dashboardActionItems, + dashboardItems, + settingsMenuItems, + startPageSections, +} from '../moreMenuItems.js' + +const ENTRIES = [ + { id: 'dashboards', label: 'Dashboards', route: 'Workspace' }, + { id: 'admin-templates', label: 'Templates', route: 'admin-templates-index', section: 'settings' }, + { id: 'admin-settings', label: 'Admin settings', route: 'admin-settings', section: 'settings' }, + { id: 'FlowsMenu', label: 'Flows', route: 'Flows', section: 'settings' }, + { id: 'Documentation', label: 'Documentation', href: 'https://launchpad.conduction.nl', section: 'footer' }, + { id: 'StoreMenu', label: 'Marketplace', route: 'Store', section: 'footer' }, + { id: 'ReportsMenu', label: 'Reports', route: 'Reports', section: 'settings' }, + { id: 'FeaturesRoadmapMenu', label: 'Features & roadmap', route: 'FeaturesRoadmap', section: 'footer' }, + { id: 'IntegrationsMenu', label: 'Integrations', route: 'Integrations', section: 'settings' }, +] + +/** + * The labels under Settings for a viewer. + * + * @param {boolean} isAdmin Whether the viewer is an administrator. + * @return {string[]} + */ +function settingsLabels(isAdmin) { + const chrome = { railSuppressed: true, entries: ENTRIES, isAdmin, includePersonalSettings: true } + return settingsMenuItems(startPageSections(chrome, () => {})).map((item) => item.label) +} + +describe('dashboardItems', () => { + const onSwitch = vi.fn() + const onOpenAll = vi.fn() + const items = dashboardItems({ + userDashboards: [{ id: 1, uuid: 'u-1', name: 'Vandaag' }, { id: 4, name: 'Mijn werkplek' }], + groupDashboards: [{ id: 2, name: 'Team Vergunningen' }, { id: 3, name: 'Intranet Zuiddrecht' }, { id: 1, name: 'Vandaag' }], + sharedDashboards: [{ id: 2 }], + activeId: 4, + defaultUuid: 'u-1', + onSwitch, + onOpenAll, + }) + + it('lists own, then shared and group dashboards once, ending in All dashboards', () => { + expect(items.map((i) => i.label)).toEqual(['Vandaag', 'Mijn werkplek', 'Team Vergunningen', 'Intranet Zuiddrecht', 'All dashboards']) + }) + + it('marks default, shared and group, and checks the open one', () => { + expect(items.map((i) => i.meta)).toEqual(['default', undefined, 'shared', 'group', undefined]) + expect(items.map((i) => i.checked)).toEqual([false, true, false, false, undefined]) + }) + + it('switches with the dashboard\'s source, and All dashboards opens the full list', () => { + items[2].onClick() + expect(onSwitch).toHaveBeenCalledWith(2, 'shared') + items.at(-1).onClick() + expect(onOpenAll).toHaveBeenCalled() + }) + + it('lists at most the limit before All dashboards', () => { + const many = Array.from({ length: DASHBOARD_LIMIT + 3 }, (_, i) => ({ id: i + 1, name: `D${i}` })) + const list = dashboardItems({ userDashboards: many, onSwitch, onOpenAll }) + expect(list).toHaveLength(DASHBOARD_LIMIT + 1) + }) +}) + +describe('settingsMenuItems', () => { + it('lists, for an administrator, the board\'s nine destinations in its order', () => { + expect(settingsLabels(true)).toEqual([ + 'Personal settings', + 'Admin settings', + 'Marketplace', + 'Templates', + 'Reports', + 'Flows', + 'Integrations', + 'Documentation', + 'Features & roadmap', + ]) + }) + + it('leaves Admin settings out for anyone else', () => { + expect(settingsLabels(false)).not.toContain('Admin settings') + }) + + it('opens an external destination in a new tab', () => { + const chrome = { railSuppressed: true, entries: ENTRIES, isAdmin: false } + const docs = settingsMenuItems(startPageSections(chrome, null)).find((i) => i.id === 'Documentation') + expect(docs.target).toBe('_blank') + expect(docs.icon).toBeTruthy() + }) +}) + +describe('dashboardActionItems', () => { + const dashboard = { id: 1, uuid: 'u-1', name: 'Vandaag' } + const all = { dashboard, isOwner: true, canEdit: true, canShare: true, canDuplicate: true, emit: vi.fn() } + const ids = (options) => dashboardActionItems(options).map((i) => i.id) + + it('offers the board\'s seven actions to the owner, Delete last and destructive', () => { + const items = dashboardActionItems(all) + expect(items.map((i) => i.label)).toEqual([ + 'Edit', + 'Add widget', + 'Sharing', + 'Copy link to this dashboard', + 'Duplicate as new dashboard', + 'Set as default', + 'Delete', + ]) + expect(items.at(-1).destructive).toBe(true) + expect(items.slice(0, -1).some((i) => i.destructive)).toBe(false) + }) + + it('offers a viewer who may not edit, share or copy only the link and the default', () => { + expect(ids({ dashboard, emit: vi.fn() })).toEqual(['copy-link', 'set-default']) + }) + + it('keeps Edit and Add widget behind canEdit, Share behind canShare, Delete behind ownership', () => { + expect(ids({ ...all, canEdit: false })).not.toContain('edit') + expect(ids({ ...all, canEdit: false })).not.toContain('add-widget') + expect(ids({ ...all, canShare: false })).not.toContain('share') + expect(ids({ ...all, canDuplicate: false })).not.toContain('duplicate') + expect(ids({ ...all, isOwner: false })).not.toContain('delete') + }) + + it('offers nothing without a dashboard, and never Versions or Settings', () => { + expect(dashboardActionItems({ ...all, dashboard: null })).toEqual([]) + expect(ids(all)).not.toContain('versions') + expect(ids(all)).not.toContain('config') + }) + + it('names Save dashboard while editing and Set as default also for the default (LpMeer)', () => { + const items = dashboardActionItems({ ...all, isEditMode: true, isDefault: true }) + expect(items.find((i) => i.id === 'edit').label).toBe('Save dashboard') + expect(items.find((i) => i.id === 'set-default').label).toBe('Set as default') + }) + + it('reports each chosen action by its event', () => { + const emit = vi.fn() + for (const item of dashboardActionItems({ ...all, emit })) { + item.onClick() + } + expect(emit.mock.calls.map(([event]) => event)).toEqual([ + 'toggleEdit', 'addWidget', 'share', 'copyLink', 'duplicate', 'setDefault', 'delete', + ]) + }) +}) + +describe('dashboardIcon', () => { + it('draws the dashboard\'s own icon by name, else the house or the generic dashboard', async () => { + const { dashboardIcon } = await import('../moreMenuItems.js') + expect(dashboardIcon({ icon: 'Bullhorn' }, false).name).toBe('DashboardMenuIcon') + expect(dashboardIcon({ icon: '' }, true).name).toMatch(/Home/) + expect(dashboardIcon({}, false).name).toMatch(/ViewDashboard/) + }) +}) diff --git a/src/components/Workspace/config/DetailsTab.vue b/src/components/Workspace/config/DetailsTab.vue index 077f4d54e..f95e7fb78 100644 --- a/src/components/Workspace/config/DetailsTab.vue +++ b/src/components/Workspace/config/DetailsTab.vue @@ -76,8 +76,102 @@ import { NcTextField, } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' +import { REQUIRED_TEXT_PROP } from '../../../constants/propDefinitions.js' import { api } from '../../../services/api.js' +/** + * Whether a stored value is absent. + * + * @param {unknown} value The stored value. + * @return {boolean} true for undefined, null or ''. + */ +function isUnset(value) { + return value === undefined || value === null || value === '' +} + +/** + * A stored multi-select value (a JSON-encoded list, or a list) as a list. + * + * @param {unknown} value The stored value. + * @return {Array} the selected options, [] when unreadable. + */ +function storedList(value) { + try { + const list = typeof value === 'string' ? JSON.parse(value) : value + return Array.isArray(list) ? list : [] + } catch { + return [] + } +} + +/** + * A stored boolean value: true, '1' or 1 read as on. + * + * @param {unknown} value The stored value. + * @return {boolean} the toggle. + */ +function storedBoolean(value) { + return value === true || value === '1' || value === 1 +} + +/** Stored-value readers per field type; other types read as a string. */ +const FROM_STORED = Object.freeze({ + 'multi-select': storedList, + boolean: storedBoolean, +}) + +/** Payload writers per field type, in the shape the service validates. */ +const TO_PAYLOAD = Object.freeze({ + number: (value) => (value === null || value === '' ? '' : Number(value)), + 'multi-select': (value) => (Array.isArray(value) ? value : []), + boolean: (value) => value === true, +}) + +/** + * A control value in the shape the service accepts for its field. + * + * @param {object} field Field definition. + * @param {unknown} value The control value. + * @return {unknown} the payload value. + */ +function toPayload(field, value) { + if (Object.hasOwn(TO_PAYLOAD, field.type)) { + return TO_PAYLOAD[field.type](value) + } + return value ?? '' +} + +/** + * The field definitions of a definitions response, [] when malformed. + * + * @param {object} defs The definitions response. + * @return {Array<object>} the fields. + */ +function fieldList(defs) { + return Array.isArray(defs?.data?.fields) ? defs.data.fields : [] +} + +/** + * The stored values of a metadata response, {} when malformed. + * + * @param {object} stored The metadata response. + * @return {object} the stored values keyed by field key. + */ +function storedValues(stored) { + return stored?.data && typeof stored.data === 'object' ? stored.data : {} +} + +/** + * The message to show for a failed save: the server's, or the fallback. + * + * @param {object} e The request error. + * @return {string} the message. + */ +function saveErrorMessage(e) { + return e?.response?.data?.message + || t('launchpad', 'The details could not be saved.') +} + /** * DetailsTab: one control per detail field for this dashboard, saved with * the dashboard metadata endpoint. Field definitions come from the @@ -99,10 +193,7 @@ export default { }, props: { - dashboardUuid: { - type: String, - required: true, - }, + dashboardUuid: REQUIRED_TEXT_PROP, }, /** @spec openspec/specs/dashboard-metadata-fields/spec.md */ @@ -137,22 +228,9 @@ export default { this.loading = true this.error = '' try { - const [defs, stored] = await Promise.all([ - api.getMetadataFieldDefinitions(), - api.getDashboardMetadata(this.dashboardUuid), - ]) - this.fields = Array.isArray(defs?.data?.fields) - ? defs.data.fields - : [] - const raw = - stored?.data && typeof stored.data === 'object' - ? stored.data - : {} - const values = {} - for (const field of this.fields) { - values[field.key] = this.fromStored(field, raw[field.key]) - } - this.values = values + const [defs, stored] = await this.fetchDetails() + this.fields = fieldList(defs) + this.values = this.valuesFrom(storedValues(stored)) } catch { this.error = t('launchpad', 'The details could not be loaded.') } finally { @@ -160,6 +238,32 @@ export default { } }, + /** + * Fetch the field definitions and this dashboard's stored values. + * + * @return {Promise<Array<object>>} the definitions and values responses. + */ + fetchDetails() { + return Promise.all([ + api.getMetadataFieldDefinitions(), + api.getDashboardMetadata(this.dashboardUuid), + ]) + }, + + /** + * One control value per field, read from the stored values. + * + * @param {object} raw The stored values keyed by field key. + * @return {object} the control values. + */ + valuesFrom(raw) { + const values = {} + for (const field of this.fields) { + values[field.key] = this.fromStored(field, raw[field.key]) + } + return values + }, + /** * Turn a stored value into the control's value. * @@ -169,22 +273,13 @@ export default { * @spec openspec/specs/dashboard-metadata-fields/spec.md */ fromStored(field, value) { - if (value === undefined || value === null || value === '') { + if (isUnset(value)) { return field.type === 'multi-select' ? [] : null } - if (field.type === 'multi-select') { - try { - const list = - typeof value === 'string' ? JSON.parse(value) : value - return Array.isArray(list) ? list : [] - } catch { - return [] - } - } - if (field.type === 'boolean') { - return value === true || value === '1' || value === 1 - } - return String(value) + const convert = Object.hasOwn(FROM_STORED, field.type) + ? FROM_STORED[field.type] + : String + return convert(value) }, /** @@ -207,25 +302,13 @@ export default { this.error = '' const payload = {} for (const field of this.fields) { - const value = this.values[field.key] - if (field.type === 'number') { - payload[field.key] = - value === null || value === '' ? '' : Number(value) - } else if (field.type === 'multi-select') { - payload[field.key] = Array.isArray(value) ? value : [] - } else if (field.type === 'boolean') { - payload[field.key] = value === true - } else { - payload[field.key] = value ?? '' - } + payload[field.key] = toPayload(field, this.values[field.key]) } try { await api.updateDashboardMetadata(this.dashboardUuid, payload) this.saved = true } catch (e) { - this.error = - e?.response?.data?.message - || t('launchpad', 'The details could not be saved.') + this.error = saveErrorMessage(e) } }, }, diff --git a/src/components/Workspace/config/ExportsTab.vue b/src/components/Workspace/config/ExportsTab.vue new file mode 100644 index 000000000..f09fdb406 --- /dev/null +++ b/src/components/Workspace/config/ExportsTab.vue @@ -0,0 +1,473 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="scheduled-exports-tab"> + <div class="scheduled-exports" data-testid="scheduled-exports"> + <ExportRunHistory + v-if="historyFor" + :exportData="historyFor" + @back="historyFor = null" + @openRun="(run) => (detailRun = run)" /> + + <template v-else> + <div class="scheduled-exports__head"> + <p class="scheduled-exports__hint"> + {{ t('launchpad', 'Send this dashboard on a schedule as PDF, PNG, CSV or Excel, by email, to Files, to a webhook or over SFTP.') }} + </p> + <NcButton + variant="primary" + data-testid="scheduled-exports-new" + @click="openEditor(null)"> + <template #icon> + <Plus :size="20" /> + </template> + {{ t('launchpad', 'New scheduled export') }} + </NcButton> + </div> + + <p + v-if="error" + class="scheduled-exports__error" + role="alert" + data-testid="scheduled-exports-error"> + {{ error }} + </p> + <CnDataTable + :columns="columns" + :rows="rows" + :loading="store.loading" + :emptyText=" + t( + 'launchpad', + 'No scheduled exports yet. Make one to send this dashboard on a schedule.', + ) + " + rowKey="id"> + <template #column-name="{ row }"> + <span data-testid="scheduled-export-name">{{ + row.name + }}</span> + </template> + <template #column-subject="{ row }"> + {{ subjectName(row) }} + </template> + <template #column-nextRunAt="{ row }"> + <span data-testid="scheduled-export-next">{{ + nextRun(row) + }}</span> + </template> + <template #column-lastRunStatus="{ row }"> + <ExportStatus + :status=" + store.running[row.id] ? 'running' : row.lastRunStatus + " /> + </template> + <template #row-actions="{ row }"> + <NcActions + :aria-label=" + t('launchpad', 'Actions for {name}', { + name: row.name, + }) + " + :forceMenu="true"> + <NcActionButton + :closeAfterClick="true" + data-testid="scheduled-export-edit" + @click="openEditor(row)"> + <template #icon> + <Pencil :size="20" /> + </template> + {{ t('launchpad', 'Edit') }} + </NcActionButton> + <NcActionButton + :closeAfterClick="true" + :disabled="Boolean(store.running[row.id])" + data-testid="scheduled-export-run" + @click="runNow(row)"> + <template #icon> + <Play :size="20" /> + </template> + {{ t('launchpad', 'Run now') }} + </NcActionButton> + <NcActionButton + :closeAfterClick="true" + data-testid="scheduled-export-preview" + @click="previewFor = row"> + <template #icon> + <Eye :size="20" /> + </template> + {{ t('launchpad', 'Preview') }} + </NcActionButton> + <NcActionButton + :closeAfterClick="true" + data-testid="scheduled-export-runs" + @click="historyFor = row"> + <template #icon> + <History :size="20" /> + </template> + {{ t('launchpad', 'View runs') }} + </NcActionButton> + <NcActionButton + :closeAfterClick="true" + data-testid="scheduled-export-delete" + @click="deleteTarget = row"> + <template #icon> + <Delete :size="20" /> + </template> + {{ t('launchpad', 'Delete') }} + </NcActionButton> + </NcActions> + </template> + </CnDataTable> + </template> + </div> + + <ScheduledExportModal + v-if="editorOpen" + :open="true" + :exportData="editing" + :subjects="subjects" + :defaultSubject="defaultSubject" + @saved="onSaved" + @close="closeEditor" /> + <RunDetailModal + v-if="detailRun" + :open="true" + :exportData="historyFor" + :run="detailRun" + @close="detailRun = null" /> + <PreviewModal + v-if="previewFor" + :open="true" + :exportData="previewFor" + @close="previewFor = null" /> + <CnConfirmDialog + v-if="deleteTarget" + :dialogTitle="t('launchpad', 'Delete this scheduled export?')" + :message=" + t( + 'launchpad', + '{name} no longer runs. Its past runs stay in the audit log.', + { name: deleteTarget.name }, + ) + " + :confirmLabel="t('launchpad', 'Delete')" + @confirm="confirmDelete" + @close="deleteTarget = null" /> + </div> +</template> + +<script> +import { + CnConfirmDialog, + CnDataTable, + NcActionButton, + NcActions, + NcButton, +} from '@conduction/nextcloud-vue' +import { showError, showInfo, showSuccess, showWarning } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' +import Delete from 'vue-material-design-icons/Delete.vue' +import Eye from 'vue-material-design-icons/Eye.vue' +import History from 'vue-material-design-icons/History.vue' +import Pencil from 'vue-material-design-icons/Pencil.vue' +import Play from 'vue-material-design-icons/Play.vue' +import Plus from 'vue-material-design-icons/Plus.vue' +import PreviewModal from '../../../modals/PreviewModal.vue' +import RunDetailModal from '../../../modals/RunDetailModal.vue' +import ScheduledExportModal from '../../../modals/ScheduledExportModal.vue' +import ExportRunHistory from '../../ScheduledExports/ExportRunHistory.vue' +import ExportStatus from '../../ScheduledExports/ExportStatus.vue' +import { + LIST_PROP, + NULLABLE_OBJECT_PROP, +} from '../../../constants/propDefinitions.js' +import { useExportsStore } from '../../../stores/scheduledExports.js' +import { formatDateTime, serverMessage } from '../../../utils/scheduledExports.js' + +/** + * ExportsTab: the Exports tab of the dashboard settings, listing the + * scheduled exports of this dashboard and its widgets. Each row shows the export's name, what it + * exports, its next run and how its last run went, with Edit, Run now, + * Preview, View runs and Delete. View runs swaps the list for the run + * history; a run opens its detail. + * + * @spec openspec/specs/scheduled-exports/spec.md#requirement-req-sch-011-scheduled-exports-live-in-the-dashboard-settings + */ +export default { + name: 'ExportsTab', + + components: { + CnConfirmDialog, + CnDataTable, + Delete, + ExportRunHistory, + ExportStatus, + Eye, + History, + NcActionButton, + NcActions, + NcButton, + Pencil, + Play, + Plus, + PreviewModal, + RunDetailModal, + ScheduledExportModal, + }, + + props: { + /** This dashboard and its widgets: `{type: 'dashboard'|'widget', id, label}`. */ + subjects: LIST_PROP, + + /** The subject a new export starts with: `{type, id}`. */ + defaultSubject: NULLABLE_OBJECT_PROP, + }, + + /** @spec openspec/changes/scheduled-exports/tasks.md#task-13 */ + data() { + return { + editorOpen: false, + editing: null, + historyFor: null, + detailRun: null, + previewFor: null, + deleteTarget: null, + error: '', + } + }, + + computed: { + /** + * @return {object} The scheduled-exports store. + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + store() { + return useExportsStore() + }, + + /** + * The exports whose subject is this dashboard or one of its widgets. + * + * @return {object[]} The rows. + * @spec openspec/specs/scheduled-exports/spec.md#requirement-req-sch-011-scheduled-exports-live-in-the-dashboard-settings + */ + rows() { + return (this.store.exports || []).filter((row) => this.subjects.some( + (s) => s.type === row.subjectType && String(s.id) === String(row.subjectId), + )) + }, + + /** + * @return {object[]} The table columns. + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + columns() { + return [ + { key: 'name', label: t('launchpad', 'Name') }, + { key: 'subject', label: t('launchpad', 'Contents') }, + { key: 'nextRunAt', label: t('launchpad', 'Next run') }, + { key: 'lastRunStatus', label: t('launchpad', 'Last run') }, + ] + }, + }, + + /** + * Read the list when the tab opens. + * + * @spec openspec/specs/scheduled-exports/spec.md#requirement-req-sch-011-scheduled-exports-live-in-the-dashboard-settings + */ + mounted() { + this.load() + }, + + methods: { + t, + + /** + * Read the exports. + * + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + async load() { + this.error = '' + try { + await this.store.fetchExports() + } catch (e) { + this.error = await serverMessage( + e, + t('launchpad', 'The scheduled exports could not be loaded.'), + ) + } + }, + + /** + * What an export exports, by name when the dashboard or widget is known. + * + * @param {object} row The export. + * @return {string} The subject. + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + subjectName(row) { + const known = this.subjects.find( + (s) => + s.type === row.subjectType + && String(s.id) === String(row.subjectId), + ) + const name = known?.label ?? row.subjectId ?? '' + return row.subjectType === 'widget' + ? t('launchpad', 'Widget: {name}', { name }) + : t('launchpad', 'Dashboard: {name}', { name }) + }, + + /** + * The next run, or why there is none. + * + * @param {object} row The export. + * @return {string} The date and time, or "Off". + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + nextRun(row) { + if (row.enabled === false) { + return t('launchpad', 'Off') + } + return formatDateTime(row.nextRunAt) || t('launchpad', 'Not planned') + }, + + /** + * Open the editor for an export, or for a new one. + * + * @param {object|null} row The export, or null. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + openEditor(row) { + this.editing = row + this.editorOpen = true + }, + + /** + * Close the editor. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + closeEditor() { + this.editorOpen = false + this.editing = null + }, + + /** + * The editor saved: the store already holds the export. + * + * @param {object} saved The saved export. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + onSaved(saved) { + showSuccess( + t('launchpad', '{name} is saved.', { name: saved?.name ?? '' }), + ) + }, + + /** + * "Run now": fire the export and report how the run ended. + * + * @param {object} row The export. + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-009-manual-run-now-and-preview-actions + */ + async runNow(row) { + showInfo(t('launchpad', '{name} is running…', { name: row.name })) + try { + const run = await this.store.runExportNow(row.id) + if (run.status === 'success') { + showSuccess( + t('launchpad', '{name} ran and was delivered.', { + name: row.name, + }), + ) + } else if (run.status === 'failed') { + showError( + t('launchpad', '{name} failed. Open its runs to see why.', { + name: row.name, + }), + ) + } else if (run.status === 'running') { + showInfo( + t( + 'launchpad', + '{name} is still running. Its runs show when it is done.', + { name: row.name }, + ), + ) + } else { + showWarning( + t( + 'launchpad', + '{name} ran, but not every delivery succeeded.', + { name: row.name }, + ), + ) + } + await this.store.fetchExports() + } catch (e) { + showError( + await serverMessage( + e, + t('launchpad', '{name} could not be run.', { + name: row.name, + }), + ), + ) + } + }, + + /** + * Delete the export the confirmation was for. + * + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + async confirmDelete() { + const target = this.deleteTarget + this.deleteTarget = null + if (!target) { + return + } + try { + await this.store.deleteExport(target.id) + } catch (e) { + this.error = await serverMessage( + e, + t('launchpad', 'The scheduled export could not be deleted.'), + ) + } + }, + }, +} +</script> + +<style scoped> +.scheduled-exports { + display: flex; + flex-direction: column; + gap: 16px; +} + +.scheduled-exports__head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.scheduled-exports__hint { + color: var(--color-text-maxcontrast); +} + +.scheduled-exports__error { + color: var(--color-error-text); +} +</style> diff --git a/src/components/Workspace/config/LanguagesTab.vue b/src/components/Workspace/config/LanguagesTab.vue index 18ea6ffed..397103261 100644 --- a/src/components/Workspace/config/LanguagesTab.vue +++ b/src/components/Workspace/config/LanguagesTab.vue @@ -98,6 +98,7 @@ <script> import { NcButton, NcSelect, NcTextField } from '@conduction/nextcloud-vue' import { getLanguage, t } from '@nextcloud/l10n' +import { REQUIRED_TEXT_PROP } from '../../../constants/propDefinitions.js' import { api } from '../../../services/api.js' /** The languages LaunchPad ships, offered for new versions. */ @@ -160,10 +161,7 @@ export default { }, props: { - dashboardUuid: { - type: String, - required: true, - }, + dashboardUuid: REQUIRED_TEXT_PROP, }, /** @spec openspec/specs/dashboard-language-content/spec.md */ diff --git a/src/components/Workspace/config/PublicationTab.vue b/src/components/Workspace/config/PublicationTab.vue new file mode 100644 index 000000000..7fd199173 --- /dev/null +++ b/src/components/Workspace/config/PublicationTab.vue @@ -0,0 +1,261 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="publication-tab" data-testid="publication-tab"> + <p class="publication-tab__hint"> + {{ t('launchpad', 'Colleagues see this dashboard only while it is published.') }} + </p> + + <div class="publication-tab__status"> + <span class="publication-tab__label">{{ t('launchpad', 'Status') }}</span> + <span + class="publication-tab__badge" + :class="`publication-tab__badge--${status}`" + data-testid="publication-status"> + {{ statusLabel }} + </span> + <NcButton + v-if="status === 'published'" + variant="secondary" + :disabled="busy" + data-testid="publication-unpublish" + @click="unpublish"> + {{ t('launchpad', 'Unpublish') }} + </NcButton> + <NcButton + v-else + variant="secondary" + :disabled="busy" + data-testid="publication-publish" + @click="publish"> + {{ t('launchpad', 'Publish') }} + </NcButton> + </div> + + <h3 class="publication-tab__heading"> + {{ t('launchpad', 'Publication schedule') }} + </h3> + <label class="publication-tab__field"> + {{ t('launchpad', 'Goes live on') }} + <input + v-model="goLive" + type="datetime-local" + data-testid="schedule-go-live"> + </label> + <label class="publication-tab__field"> + {{ t('launchpad', 'Comes down on (optional)') }} + <input + v-model="takeDown" + type="datetime-local" + data-testid="schedule-take-down"> + </label> + <p + v-if="error" + class="publication-tab__error" + role="alert" + data-testid="schedule-error"> + {{ error }} + </p> + <div> + <NcButton + variant="secondary" + :disabled="busy || !(goLive || takeDown)" + data-testid="schedule-save" + @click="schedule"> + {{ t('launchpad', 'Schedule') }} + </NcButton> + </div> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' +import { NULLABLE_OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { useDashboardStore } from '../../../stores/dashboard.js' + +/** + * Turn a `datetime-local` value into ISO-8601 with the viewer's offset. + * + * @param {string} local Value like `2026-10-01T09:00`. + * @return {string|null} ISO string, or null when empty or unreadable. + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + */ +export function toIso(local) { + if (!local) { + return null + } + const date = new Date(local) + return Number.isNaN(date.getTime()) ? null : date.toISOString() +} + +/** + * The person-facing reason a schedule was refused. + * + * @param {string} message The server's message. + * @return {string} The explanation. + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + */ +export function scheduleRefusal(message) { + if (message === 'unpublishAt must be after publishAt') { + return t('launchpad', 'The dashboard has to go live before it comes down.') + } + if (message === 'publishAt must be a future timestamp') { + return t('launchpad', 'Choose a time in the future.') + } + return t('launchpad', 'The dashboard could not be scheduled.') +} + +/** + * PublicationTab: the Publication tab of the dashboard settings. Shows + * whether the dashboard is published, publishes or unpublishes it, and + * sets when it goes live and comes down. The server checks owner or + * administrator again. + * + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + */ +export default { + name: 'PublicationTab', + + components: { NcButton }, + + props: { + dashboard: NULLABLE_OBJECT_PROP, + }, + + /** @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 */ + data() { + return { goLive: '', takeDown: '', error: '', busy: false } + }, + + computed: { + /** + * @return {string} `published`, `scheduled` or `draft`. + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + */ + status() { + const status = this.dashboard?.publicationStatus || 'published' + return ['published', 'scheduled'].includes(status) ? status : 'draft' + }, + + /** + * @return {string} The status as the person reads it. + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + */ + statusLabel() { + if (this.status === 'published') { + return t('launchpad', 'Published') + } + return this.status === 'scheduled' + ? t('launchpad', 'Scheduled') + : t('launchpad', 'Draft') + }, + }, + + methods: { + t, + + /** + * @return {Promise<void>} + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + */ + async publish() { + this.busy = true + try { + await useDashboardStore().publishDashboard(this.dashboard.uuid) + } finally { + this.busy = false + } + }, + + /** + * @return {Promise<void>} + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + */ + async unpublish() { + this.busy = true + try { + await useDashboardStore().unpublishDashboard(this.dashboard.uuid) + } finally { + this.busy = false + } + }, + + /** + * Save the go-live and take-down times; a refusal stays in the tab. + * + * @return {Promise<void>} + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + */ + async schedule() { + this.error = '' + this.busy = true + try { + await useDashboardStore().scheduleDashboard( + this.dashboard.uuid, + toIso(this.goLive), + toIso(this.takeDown), + ) + this.goLive = '' + this.takeDown = '' + } catch (error) { + this.error = scheduleRefusal(error?.response?.data?.message ?? '') + } finally { + this.busy = false + } + }, + }, +} +</script> + +<style scoped> +.publication-tab { + display: flex; + flex-direction: column; + gap: 12px; +} + +.publication-tab__hint { + color: var(--color-text-maxcontrast); +} + +.publication-tab__status { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; +} + +.publication-tab__label { + font-weight: bold; +} + +.publication-tab__badge { + padding: 2px 10px; + border-radius: var(--border-radius-pill); + background: var(--color-background-dark); +} + +.publication-tab__badge--published { + background: var(--color-success); + color: var(--color-primary-element-text); +} + +.publication-tab__heading { + margin: 8px 0 0; + font-size: 1em; +} + +.publication-tab__field { + display: flex; + flex-direction: column; + gap: 4px; +} + +.publication-tab__error { + color: var(--color-error-text); +} +</style> diff --git a/src/components/Workspace/config/SharingConversation.vue b/src/components/Workspace/config/SharingConversation.vue new file mode 100644 index 000000000..724cb3b5e --- /dev/null +++ b/src/components/Workspace/config/SharingConversation.vue @@ -0,0 +1,134 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="sharing-conversation" data-test="sharing-conversation"> + <h3 class="sharing-conversation__title"> + {{ t('launchpad', 'Conversation beside this dashboard') }} + </h3> + <NcCheckboxRadioSwitch + v-if="shared" + type="switch" + :modelValue="enabled" + :loading="saving" + :disabled="saving" + data-test="sharing-conversation-switch" + @update:modelValue="toggle"> + {{ t('launchpad', 'Show the conversation beside the dashboard') }} + </NcCheckboxRadioSwitch> + <p v-else class="sharing-conversation__hint" data-test="sharing-conversation-unshared"> + {{ t('launchpad', 'This dashboard is yours alone. Share it with people or a group and the conversation appears here too.') }} + </p> + <p v-if="error !== ''" class="sharing-conversation__error" role="alert"> + {{ error }} + </p> + </div> +</template> + +<script> +import { NcCheckboxRadioSwitch } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { FLAG_PROP, NULLABLE_OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { api } from '../../../services/api.js' +import { conversationEnabled } from '../../../utils/dashboardDiscussion.js' +import { logger } from '../../../utils/logger.js' + +/** + * SharingConversation — the "Conversation beside this dashboard" part of a + * dashboard's Sharing tab (REQ-LEAF-006). On a shared dashboard a switch + * shows or hides the Talk conversation beside it and is stored at once; an + * unshared dashboard says the conversation appears once it is shared. + * + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ +export default { + name: 'SharingConversation', + + components: { NcCheckboxRadioSwitch }, + + props: { + /** The dashboard: {id, conversationEnabled}. */ + dashboard: NULLABLE_OBJECT_PROP, + + /** Whether the dashboard is shared with people or a group. */ + shared: FLAG_PROP, + }, + + emits: ['update:conversationEnabled'], + + data() { + return { + enabled: conversationEnabled(this.dashboard), + saving: false, + error: '', + } + }, + + watch: { + /** + * Follow a switch stored elsewhere. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ + 'dashboard.conversationEnabled': function() { + this.enabled = conversationEnabled(this.dashboard) + }, + }, + + methods: { + t, + + /** + * Store the switch; on a failure it returns to where it was. + * + * @param {boolean} value Whether the conversation shows. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ + async toggle(value) { + const before = this.enabled + this.enabled = value + this.saving = true + this.error = '' + try { + await api.updateDashboard(this.dashboard.id, { conversationEnabled: value }) + this.$emit('update:conversationEnabled', value ? 1 : 0) + } catch (error) { + this.enabled = before + this.error = t('launchpad', 'The conversation setting could not be saved.') + logger.error('Failed to save the conversation switch:', error) + } finally { + this.saving = false + } + }, + }, +} +</script> + +<style scoped> +.sharing-conversation { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 16px; +} + +.sharing-conversation__title { + margin: 0; + font-size: 1em; + font-weight: bold; +} + +.sharing-conversation__hint { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.sharing-conversation__error { + margin: 0; + color: var(--color-error-text); +} +</style> diff --git a/src/components/Workspace/config/SharingEmbedTokens.vue b/src/components/Workspace/config/SharingEmbedTokens.vue new file mode 100644 index 000000000..4c69c7e5f --- /dev/null +++ b/src/components/Workspace/config/SharingEmbedTokens.vue @@ -0,0 +1,458 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="sharing-embed" data-test="sharing-embed"> + <h3 class="sharing-embed__title"> + {{ t('launchpad', 'Embed on your website') }} + </h3> + <p class="sharing-embed__hint"> + {{ t('launchpad', 'Show this dashboard, or one of its widgets, on another website with an embed token.') }} + </p> + + <NcNoteCard v-if="issued" type="warning" data-test="sharing-embed-issued"> + <p> + {{ t('launchpad', 'Token {name} has been created. Copy it now: it is not shown again.', { name: issued.name }) }} + </p> + <code class="sharing-embed__jwt" data-test="sharing-embed-jwt">{{ issued.jwt }}</code> + <div class="sharing-embed__row"> + <NcButton data-test="sharing-embed-copy" @click="copy(issued.jwt, 'jwt')"> + {{ copied === 'jwt' ? t('launchpad', 'Copied') : t('launchpad', 'Copy') }} + </NcButton> + <NcButton variant="tertiary" data-test="sharing-embed-issued-done" @click="issued = null"> + {{ t('launchpad', 'Done') }} + </NcButton> + </div> + </NcNoteCard> + + <!-- Withdraw asks for the reason, as the admin Embeds tab does. --> + <RevokeEmbedTokenDialog + v-if="revoking !== null" + open + :name="revoking.name" + @confirm="revoke" + @update:open="closeRevoke" /> + + <NcNoteCard v-if="error !== ''" type="error" data-test="sharing-embed-error"> + {{ error }} + </NcNoteCard> + + <EmbedTokenForm + v-if="creating" + :dashboards="[dashboardOption]" + :themes="[]" + :defaults="formDefaults" + :saving="saving" + @submit="create" + @cancel="creating = false" /> + + <template v-else> + <NcLoadingIcon v-if="loading" /> + <p v-else-if="tokens.length === 0" class="sharing-embed__hint" data-test="sharing-embed-empty"> + {{ t('launchpad', 'No embed tokens for this dashboard yet.') }} + </p> + <table v-else class="sharing-embed__table" data-test="sharing-embed-table"> + <thead> + <tr> + <th scope="col">{{ t('launchpad', 'Name') }}</th> + <th scope="col">{{ t('launchpad', 'Shows') }}</th> + <th scope="col">{{ t('launchpad', 'Allowed website') }}</th> + <th scope="col">{{ t('launchpad', 'State') }}</th> + <th scope="col"><span class="hidden-visually">{{ t('launchpad', 'Actions') }}</span></th> + </tr> + </thead> + <tbody> + <tr + v-for="token in tokens" + :key="token.id" + :class="{ 'sharing-embed__selected': token.id === selectedId }" + :data-test="'sharing-embed-row-' + token.id" + @click="selectedId = token.id"> + <td>{{ token.name }}</td> + <td>{{ subjectLabel(token) }}</td> + <td>{{ (token.hostOrigins || []).join(', ') }}</td> + <td :data-test="'sharing-embed-state-' + token.id"> + {{ stateLabel(token) }} + </td> + <td> + <NcButton + v-if="!token.revokedAt" + variant="tertiary" + :aria-label="t('launchpad', 'Withdraw {name}', { name: token.name })" + :data-test="'sharing-embed-withdraw-' + token.id" + @click.stop="revoking = token"> + {{ t('launchpad', 'Withdraw') }} + </NcButton> + </td> + </tr> + </tbody> + </table> + + <div v-if="selected" class="sharing-embed__code" data-test="sharing-embed-code"> + <label class="sharing-embed__label" for="sharing-embed-code"> + {{ t('launchpad', 'Code for the website') }} + </label> + <textarea + id="sharing-embed-code" + readonly + rows="3" + :value="code" + @focus="$event.target.select()" /> + <div class="sharing-embed__row"> + <NcButton variant="tertiary" data-test="sharing-embed-copy-code" @click="copy(code, 'code')"> + {{ copied === 'code' ? t('launchpad', 'Copied') : t('launchpad', 'Copy code') }} + </NcButton> + </div> + </div> + + <div class="sharing-embed__row"> + <NcButton variant="secondary" data-test="sharing-embed-new" @click="creating = true"> + {{ t('launchpad', 'Create new embed token') }} + </NcButton> + </div> + </template> + + </div> +</template> + +<script> +import { NcButton, NcLoadingIcon, NcNoteCard } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { generateUrl } from '@nextcloud/router' +import RevokeEmbedTokenDialog from '../../../dialogs/RevokeEmbedTokenDialog.vue' +import EmbedTokenForm from '../../admin/embed/EmbedTokenForm.vue' +import { NULLABLE_OBJECT_PROP } from '../../../constants/propDefinitions.js' +import { api } from '../../../services/api.js' +import { embedApi } from '../../../services/embedApi.js' +import { embedCode, tokensForDashboard, tokenStatus } from '../../../utils/embedToken.js' +import { logger } from '../../../utils/logger.js' + +/** + * SharingEmbedTokens — the "Embed on your website" part of a dashboard's + * Sharing tab (REQ-EMB-011): the dashboard's embed tokens with what they + * show, the allowed website, their state and Withdraw; the code for the + * website of the selected token; and a new token, shown once. Withdrawing + * uses the token revocation, which every render worker honours within 60 + * seconds (REQ-EMB-009). + * + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ +export default { + name: 'SharingEmbedTokens', + + components: { + EmbedTokenForm, + NcButton, + NcLoadingIcon, + NcNoteCard, + RevokeEmbedTokenDialog, + }, + + props: { + /** The dashboard: {id, uuid, name}. */ + dashboard: NULLABLE_OBJECT_PROP, + }, + + data() { + return { + allTokens: [], + placements: [], + loading: true, + saving: false, + creating: false, + selectedId: null, + issued: null, + copied: '', + revoking: null, + error: '', + } + }, + + computed: { + /** + * The tokens of this dashboard and its widgets. + * + * @return {Array<object>} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + tokens() { + return tokensForDashboard(this.allTokens, this.dashboard?.uuid, this.placements.map((placement) => placement.id)) + }, + + /** + * The token whose code is shown. + * + * @return {object|null} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + selected() { + return this.tokens.find((token) => token.id === this.selectedId) ?? null + }, + + /** + * The code for the website of the selected token, with the JWT while it is at hand. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + code() { + const jwt = this.issued?.id === this.selected?.id ? this.issued?.jwt : '' + return embedCode(this.selected, this.appUrl(), jwt) + }, + + /** + * This dashboard as the one choice of the token form. + * + * @return {object} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + dashboardOption() { + return { id: this.dashboard?.id, uuid: this.dashboard?.uuid, name: this.dashboard?.name } + }, + + /** + * A new token starts on this dashboard. + * + * @return {object} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + formDefaults() { + return { subjectType: 'dashboard', subjectId: this.dashboard?.uuid ?? '', dashboardId: this.dashboard?.id ?? null } + }, + }, + + watch: { + 'dashboard.id': { + immediate: true, + /** + * Load the tokens of the dashboard that opened. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + handler() { + this.load() + }, + }, + }, + + methods: { + t, + + /** + * Load every token and the dashboard's widget placements. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + async load() { + if (!this.dashboard?.id) { + this.loading = false + return + } + this.loading = true + this.error = '' + const [tokens, detail] = await Promise.allSettled([ + embedApi.listTokens(), + api.getDashboardById(this.dashboard.id), + ]) + if (tokens.status === 'fulfilled') { + this.allTokens = tokens.value + } else { + this.allTokens = [] + this.error = t('launchpad', 'Embed tokens could not be loaded.') + logger.error('Failed to load embed tokens:', tokens.reason) + } + const placements = detail.status === 'fulfilled' ? detail.value?.data?.placements : null + this.placements = Array.isArray(placements) ? placements : [] + this.loading = false + }, + + /** + * Issue a token from the form; its JWT and code are shown once. + * + * @param {object} payload The form's payload. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + async create(payload) { + this.saving = true + this.error = '' + try { + const result = await embedApi.createToken(payload) + this.issued = result + this.copied = '' + this.allTokens = await embedApi.listTokens() + this.selectedId = result?.id ?? null + this.creating = false + } catch (error) { + this.error = error?.response?.data?.message || t('launchpad', 'The embed token could not be saved.') + logger.error('Failed to create embed token:', error) + } finally { + this.saving = false + } + }, + + /** + * Withdraw the token in the dialog. + * + * @param {{reason: string, notes: string}} choice The reason and notes. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + async revoke({ reason, notes }) { + const token = this.revoking + this.revoking = null + this.error = '' + try { + const updated = await embedApi.revokeToken(token.id, reason, notes) + this.allTokens = this.allTokens.map((item) => (item.id === updated.id ? updated : item)) + } catch (error) { + this.error = error?.response?.data?.message || t('launchpad', 'The embed token could not be revoked.') + logger.error('Failed to revoke embed token:', error) + } + }, + + /** + * Close the Withdraw dialog without withdrawing. + * + * @param {boolean} open Whether the dialog stays open. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + closeRevoke(open) { + if (!open) { + this.revoking = null + } + }, + + /** + * Copy a text to the clipboard. + * + * @param {string} text The text. + * @param {string} what Which copy button was used. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + async copy(text, what) { + try { + await navigator.clipboard.writeText(text) + this.copied = what + } catch (error) { + logger.error('Failed to copy:', error) + } + }, + + /** + * The absolute address of the app. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + appUrl() { + const origin = typeof window === 'undefined' ? '' : window.location.origin + return origin + generateUrl('/apps/launchpad') + }, + + /** + * What a token shows: the whole dashboard or one widget. + * + * @param {object} token The token. + * @return {string} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + subjectLabel(token) { + if (token?.subject?.type !== 'widget') { + return t('launchpad', 'The whole dashboard') + } + const placement = this.placements.find((item) => String(item.id) === String(token.subject.id)) + const name = placement?.customTitle || placement?.tileTitle || placement?.widgetId || token.subject.id + return t('launchpad', 'Widget {name}', { name }) + }, + + /** + * A token's state: Active, Revoked with the date and reason, or Expired. + * + * @param {object} token The token. + * @return {string} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + stateLabel(token) { + const status = tokenStatus(token) + if (status === 'revoked') { + return t('launchpad', 'Revoked on {date} ({reason})', { + date: String(token.revokedAt).slice(0, 10), + reason: token.revocationReason || '', + }) + } + if (status === 'expired') { + return t('launchpad', 'Expired') + } + return t('launchpad', 'Active') + }, + }, +} +</script> + +<style scoped> +.sharing-embed { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 16px; +} + +.sharing-embed__title { + margin: 0; + font-size: 1em; + font-weight: bold; +} + +.sharing-embed__hint { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.sharing-embed__row { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +.sharing-embed__jwt { + display: block; + overflow-wrap: anywhere; + font-family: monospace; +} + +.sharing-embed__table { + width: 100%; + border-collapse: collapse; +} + +.sharing-embed__table th, +.sharing-embed__table td { + padding: 4px 8px; + text-align: start; + border-bottom: 1px solid var(--color-border); +} + +.sharing-embed__table tbody tr { + cursor: pointer; +} + +.sharing-embed__selected { + background: var(--color-primary-element-light); +} + +.sharing-embed__code textarea { + width: 100%; + font-family: monospace; +} + +.sharing-embed__label { + font-weight: bold; +} +</style> diff --git a/src/components/Workspace/config/VersionsTab.vue b/src/components/Workspace/config/VersionsTab.vue new file mode 100644 index 000000000..c88dd1b1b --- /dev/null +++ b/src/components/Workspace/config/VersionsTab.vue @@ -0,0 +1,523 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="launchpad-versions" data-testid="version-history"> + <div v-if="loading" class="launchpad-versions__loading"> + <NcLoadingIcon :size="32" /> + </div> + + <p + v-else-if="error" + class="launchpad-versions__error" + role="alert" + data-testid="version-error"> + {{ error }} + </p> + + <p v-else-if="!modeSupported" data-testid="version-unsupported"> + {{ + t( + 'launchpad', + 'This dashboard is stored in a way that does not keep versions.', + ) + }} + </p> + + <template v-else> + <p class="launchpad-versions__intro"> + {{ t('launchpad', 'Every saved version of this dashboard. Pick an older version to restore it; the current version stays in the list.') }} + </p> + + <p v-if="sortedVersions.length === 0"> + {{ t('launchpad', 'No versions saved yet.') }} + </p> + <table v-else class="launchpad-versions__table"> + <thead> + <tr> + <th v-for="heading in headings" :key="heading" scope="col"> + {{ heading }} + </th> + <th scope="col"> + <span class="hidden-visually">{{ t('launchpad', 'Status') }}</span> + </th> + </tr> + </thead> + <tbody> + <tr + v-for="version in sortedVersions" + :key="version.versionNumber" + class="launchpad-versions__row" + :class="{ 'launchpad-versions__row--selected': selected && selected.versionNumber === version.versionNumber }" + :aria-selected="selected && selected.versionNumber === version.versionNumber ? 'true' : 'false'" + tabindex="0" + data-testid="version-row" + @click="select(version)" + @keydown.enter="select(version)"> + <td>{{ whenText(version.createdAt) }}</td> + <td>{{ version.createdByName || version.createdBy }}</td> + <td>{{ noteLabel(version.note) }}</td> + <td class="launchpad-versions__status"> + <span + v-if="version.versionNumber === currentNumber" + class="launchpad-versions__current" + data-testid="version-current"> + {{ t('launchpad', 'Current version') }} + </span> + </td> + </tr> + </tbody> + </table> + + <!-- The chosen older version and what restoring it does (LpVersies). --> + <div + v-if="selected && selected.versionNumber !== currentNumber" + class="launchpad-versions__preview" + data-testid="version-preview"> + <span class="launchpad-versions__thumb" aria-hidden="true"> + <span /><span /><span /><span /> + </span> + <span class="launchpad-versions__preview-text"> + <strong>{{ t('launchpad', 'Version of {date}', { date: whenText(selected.createdAt) }) }}</strong> + <span> + {{ selected.note ? noteLabel(selected.note) + '. ' : '' }}{{ t('launchpad', 'Restoring it drops the changes made after it. The current version stays in this list.') }} + </span> + </span> + </div> + + <div class="launchpad-versions__save"> + <NcTextField + v-model="note" + :label=" + t('launchpad', 'Note for this version (optional)') + " /> + <NcButton + variant="tertiary" + :disabled="saving" + data-testid="version-save" + @click="saveVersion"> + {{ t('launchpad', 'Save this version now') }} + </NcButton> + </div> + + <div class="launchpad-versions__actions"> + <NcButton + variant="secondary" + data-testid="version-close" + @click="$emit('close')"> + {{ t('launchpad', 'Close') }} + </NcButton> + <NcButton + variant="primary" + :disabled="!selected || selected.versionNumber === currentNumber" + data-testid="version-restore" + @click="askRestore(selected)"> + <template #icon> + <Restore :size="20" /> + </template> + {{ t('launchpad', 'Restore this version') }} + </NcButton> + </div> + </template> + + <CnConfirmDialog + v-if="restoreTarget !== null" + :dialogTitle="t('launchpad', 'Restore this version?')" + :message=" + t( + 'launchpad', + 'The dashboard goes back to how it was on {date}. How it looks now is saved as a version first, so you can undo this.', + { date: formatDate(restoreTarget.createdAt) }, + ) + " + :confirmLabel="t('launchpad', 'Restore')" + @confirm="confirmRestore" + @close="restoreTarget = null" /> + </div> +</template> + +<script> +import { + CnConfirmDialog, + NcButton, + NcLoadingIcon, + NcTextField, +} from '@conduction/nextcloud-vue' +import { getCanonicalLocale, t } from '@nextcloud/l10n' +import Restore from 'vue-material-design-icons/Restore.vue' +import { TEXT_PROP } from '../../../constants/propDefinitions.js' +import { api } from '../../../services/api.js' +import { parseServerStamp } from '../../../utils/serverStamp.js' + +/** + * VersionsTab: the Versions tab of the dashboard settings (board LpVersies): + * the saved versions of one dashboard, newest first, with "Save this version + * now" and a confirmed restore. After a restore the list is read again, so + * the `pre-restore` version that makes the restore reversible shows at the + * top, and `restored` tells the page to reload. + * + * @spec openspec/specs/dashboard-versioning/spec.md + */ +export default { + name: 'VersionsTab', + + components: { + CnConfirmDialog, + NcButton, + NcLoadingIcon, + NcTextField, + Restore, + }, + + props: { + dashboardUuid: TEXT_PROP, + }, + + emits: ['restored', 'close'], + + /** @spec openspec/specs/dashboard-versioning/spec.md */ + data() { + return { + versions: [], + modeSupported: true, + loading: false, + saving: false, + error: '', + note: '', + restoreTarget: null, + selectedNumber: null, + } + }, + + computed: { + /** + * The table's column headings, before the actions column. + * + * @return {string[]} + * @spec openspec/specs/dashboard-versioning/spec.md + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-the-owner-sees-the-version-history-req-versui-001 + */ + headings() { + return [ + t('launchpad', 'When'), + t('launchpad', 'By'), + t('launchpad', 'What changed'), + ] + }, + + /** + * @return {number|null} The newest version's number: the current one. + * @spec openspec/specs/dashboard-versioning/spec.md + * @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-the-owner-sees-the-version-history-req-versui-001 + */ + currentNumber() { + return this.sortedVersions.length > 0 ? this.sortedVersions[0].versionNumber : null + }, + + /** + * @return {object|null} The version picked in the list. + * @spec openspec/specs/dashboard-versioning/spec.md + */ + selected() { + return this.sortedVersions.find((version) => version.versionNumber === this.selectedNumber) ?? null + }, + + /** + * @return {Array<object>} Versions, newest first. + * @spec openspec/specs/dashboard-versioning/spec.md + */ + sortedVersions() { + return [...this.versions].sort( + (a, b) => b.versionNumber - a.versionNumber, + ) + }, + }, + + watch: { + dashboardUuid: { + immediate: true, + /** + * Read the list when the tab opens and for another dashboard. + * + * @param {string} uuid The dashboard's uuid. + * @spec openspec/specs/dashboard-versioning/spec.md + */ + handler(uuid) { + if (uuid) { + this.load() + } + }, + }, + }, + + methods: { + t, + + /** + * Read the version list. + * + * @return {Promise<void>} + * @spec openspec/specs/dashboard-versioning/spec.md + */ + async load() { + this.loading = true + this.error = '' + try { + const { data } = await api.listVersions(this.dashboardUuid) + this.versions = Array.isArray(data?.versions) ? data.versions : [] + this.modeSupported = data?.modeSupported !== false + } catch { + this.error = t( + 'launchpad', + 'The version history could not be loaded.', + ) + } finally { + this.loading = false + } + }, + + /** + * Save the dashboard as it is now, with the typed note. + * + * @return {Promise<void>} + * @spec openspec/specs/dashboard-versioning/spec.md + */ + async saveVersion() { + this.saving = true + this.error = '' + try { + const note = this.note.trim() === '' ? null : this.note.trim() + const { data } = await api.createVersion(this.dashboardUuid, note) + if (data?.version) { + this.versions = [data.version, ...this.versions] + } + this.note = '' + } catch { + this.error = t('launchpad', 'The version could not be saved.') + } finally { + this.saving = false + } + }, + + /** + * Open the confirmation for one version. + * + * @param {object} version The version row. + * @spec openspec/specs/dashboard-versioning/spec.md + */ + /** + * Pick a version in the list. + * + * @param {object} version The version. + * @spec openspec/specs/dashboard-versioning/spec.md + */ + select(version) { + this.selectedNumber = version.versionNumber + }, + + /** + * When a version was saved, as the board words it: "today 10:12", + * else "Friday 2 October, 16:40". + * + * @param {string} value The stamp. + * @return {string} + * @spec openspec/specs/dashboard-versioning/spec.md + */ + whenText(value) { + const parsed = value ? parseServerStamp(value) : null + if (parsed === null) { + return value ? String(value) : '' + } + const locale = getCanonicalLocale() + const time = parsed.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' }) + const now = new Date() + if (parsed.toDateString() === now.toDateString()) { + return t('launchpad', 'today {time}', { time }) + } + const day = parsed.toLocaleDateString(locale, { weekday: 'long', day: 'numeric', month: 'long' }) + return `${day}, ${time}` + }, + + askRestore(version) { + this.restoreTarget = version + }, + + /** + * Restore the chosen version, read the list again and tell the page. + * + * @return {Promise<void>} + * @spec openspec/specs/dashboard-versioning/spec.md + */ + async confirmRestore() { + const target = this.restoreTarget + this.restoreTarget = null + if (!target) { + return + } + try { + await api.restoreVersion(this.dashboardUuid, target.versionNumber) + } catch { + this.error = t('launchpad', 'The version could not be restored.') + return + } + this.$emit('restored', target) + await this.load() + }, + + /** + * Show a stored `Y-m-d H:i:s` timestamp in the viewer's locale. + * + * @param {string} value Timestamp from the server. + * @return {string} Formatted date and time, or the raw value. + * @spec openspec/specs/dashboard-versioning/spec.md + */ + formatDate(value) { + if (!value) { + return '' + } + const parsed = parseServerStamp(value) + if (parsed === null) { + return String(value) + } + return parsed.toLocaleString(undefined, { + dateStyle: 'medium', + timeStyle: 'short', + }) + }, + + /** + * The note column; the automatic safety copy gets a readable label. + * + * @param {string|null} note Stored note. + * @return {string} Text for the note column. + * @spec openspec/specs/dashboard-versioning/spec.md + */ + noteLabel(note) { + if (note === 'pre-restore') { + return t('launchpad', 'Saved automatically before a restore') + } + return note ?? '' + }, + }, +} +</script> + +<style scoped> +.launchpad-versions { + display: flex; + flex-direction: column; + gap: 16px; +} + +.launchpad-versions__save { + display: flex; + gap: 8px; + align-items: flex-end; +} + +.launchpad-versions__table { + width: 100%; + border-collapse: collapse; +} + +/* The table, the chosen row and the preview as LpVersies draws them. */ +.launchpad-versions__intro { + margin: 0; + color: var(--color-text-maxcontrast); + font-size: 14px; +} + +.launchpad-versions__table th { + padding: 10px 12px; + border-bottom: 1px solid var(--color-border); + color: var(--color-text-maxcontrast); + font-size: 13px; + font-weight: 600; + text-align: start; + white-space: nowrap; +} + +.launchpad-versions__table td { + padding: 12px; + border-bottom: 1px solid var(--color-border); + font-size: 14px; + text-align: start; + vertical-align: middle; +} + +.launchpad-versions__row { + cursor: pointer; +} + +.launchpad-versions__row:hover, +.launchpad-versions__row:focus-visible { + background: var(--color-background-hover); +} + +.launchpad-versions__row--selected, +.launchpad-versions__row--selected:hover { + background: var(--color-primary-element-light); +} + +.launchpad-versions__status { + text-align: end; +} + +.launchpad-versions__current { + display: inline-flex; + align-items: center; + padding: 3px 10px; + border-radius: 12px; + background: var(--color-primary-element-light); + color: var(--color-primary-element-light-text); + font-size: 13px; + font-weight: 600; + white-space: nowrap; +} + +.launchpad-versions__preview { + display: flex; + gap: 16px; + align-items: center; + padding: 16px; + border: 1px solid var(--color-border); + border-radius: 12px; + background: var(--color-background-hover); +} + +.launchpad-versions__thumb { + display: grid; + flex: none; + grid-template-columns: 1fr 1fr; + gap: 6px; + width: 120px; + padding: 8px; + border-radius: 8px; + background: var(--color-main-background); +} + +.launchpad-versions__thumb > span { + height: 22px; + border-radius: 4px; + background: var(--color-border); +} + +.launchpad-versions__preview-text { + display: flex; + flex-direction: column; + gap: 4px; + font-size: 14px; +} + +.launchpad-versions__actions { + display: flex; + gap: 8px; + justify-content: flex-end; +} + +.launchpad-versions__error { + color: var(--color-error-text); +} +</style> diff --git a/src/components/Workspace/config/__tests__/DetailsTab.golden.spec.js b/src/components/Workspace/config/__tests__/DetailsTab.golden.spec.js new file mode 100644 index 000000000..4b5bee985 --- /dev/null +++ b/src/components/Workspace/config/__tests__/DetailsTab.golden.spec.js @@ -0,0 +1,136 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Characterisation tests pinning DetailsTab's stored-value conversion, + * save payload per field type, load fallbacks and error messages, so the + * methods can be split into named steps without changing behaviour. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import DetailsTab from '../DetailsTab.vue' +import { api } from '../../../../services/api.js' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('../../../../services/api.js', () => ({ + api: { + getMetadataFieldDefinitions: vi.fn(), + getDashboardMetadata: vi.fn(), + updateDashboardMetadata: vi.fn(), + }, +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcButton: { name: 'NcButton', template: '<button><slot /></button>' }, + NcCheckboxRadioSwitch: { name: 'NcCheckboxRadioSwitch', template: '<input>' }, + NcSelect: { name: 'NcSelect', template: '<select />' }, + NcTextField: { name: 'NcTextField', template: '<input>' }, +})) + +const FIELDS = [ + { key: 'n', type: 'number' }, + { key: 'm', type: 'multi-select' }, + { key: 'b', type: 'boolean' }, + { key: 's', type: 'select' }, + { key: 'x' }, +] + +async function mountTab(fields = FIELDS, stored = {}) { + api.getMetadataFieldDefinitions.mockResolvedValue({ data: { fields } }) + api.getDashboardMetadata.mockResolvedValue({ data: stored }) + const wrapper = mount(DetailsTab, { props: { dashboardUuid: 'u1' }, shallow: true }) + await flushPromises() + return wrapper +} + +beforeEach(() => vi.clearAllMocks()) + +describe('DetailsTab.fromStored', () => { + it.each([ + [{ type: 'multi-select' }, undefined, []], + [{ type: 'multi-select' }, null, []], + [{ type: 'multi-select' }, '', []], + [{ type: 'number' }, '', null], + [{ type: 'boolean' }, null, null], + [{ type: 'multi-select' }, '["a","b"]', ['a', 'b']], + [{ type: 'multi-select' }, '{"a":1}', []], + [{ type: 'multi-select' }, 'not json', []], + [{ type: 'multi-select' }, ['c'], ['c']], + [{ type: 'multi-select' }, 5, []], + [{ type: 'boolean' }, true, true], + [{ type: 'boolean' }, '1', true], + [{ type: 'boolean' }, 1, true], + [{ type: 'boolean' }, '0', false], + [{ type: 'boolean' }, 'true', false], + [{ type: 'number' }, 12, '12'], + [{}, false, 'false'], + [{ type: 'constructor' }, 'v', 'v'], + ])('converts %j %j', async (field, value, expected) => { + const wrapper = await mountTab([], {}) + expect(wrapper.vm.fromStored(field, value)).toEqual(expected) + }) +}) + +describe('DetailsTab.load', () => { + it('fills one value per field from the stored values', async () => { + const wrapper = await mountTab(FIELDS, { n: '3', m: '["a"]', b: '1', s: 'HR' }) + expect(api.getDashboardMetadata).toHaveBeenCalledWith('u1') + expect(wrapper.vm.values).toEqual({ n: '3', m: ['a'], b: true, s: 'HR', x: null }) + expect(wrapper.vm.loading).toBe(false) + expect(wrapper.vm.error).toBe('') + }) + + it('treats malformed definitions and stored values as empty', async () => { + api.getMetadataFieldDefinitions.mockResolvedValue({ data: { fields: 'x' } }) + api.getDashboardMetadata.mockResolvedValue({ data: 'x' }) + const wrapper = mount(DetailsTab, { props: { dashboardUuid: 'u1' }, shallow: true }) + await flushPromises() + expect(wrapper.vm.fields).toEqual([]) + expect(wrapper.vm.values).toEqual({}) + + api.getMetadataFieldDefinitions.mockResolvedValue({ data: { fields: [{ key: 'k', type: 'boolean' }] } }) + api.getDashboardMetadata.mockResolvedValue(null) + await wrapper.vm.load() + expect(wrapper.vm.values).toEqual({ k: null }) + }) + + it('shows the load error and clears loading', async () => { + api.getMetadataFieldDefinitions.mockRejectedValue(new Error('x')) + api.getDashboardMetadata.mockResolvedValue({ data: {} }) + const wrapper = mount(DetailsTab, { props: { dashboardUuid: 'u1' }, shallow: true }) + await flushPromises() + expect(wrapper.vm.error).toBe('The details could not be loaded.') + expect(wrapper.vm.loading).toBe(false) + }) +}) + +describe('DetailsTab.save', () => { + it('sends each value in its field type shape', async () => { + const wrapper = await mountTab() + api.updateDashboardMetadata.mockResolvedValue({}) + wrapper.vm.values = { n: '4.5', m: 'x', b: 'yes', s: undefined, x: 'free' } + await wrapper.vm.save() + expect(api.updateDashboardMetadata).toHaveBeenCalledWith('u1', { n: 4.5, m: [], b: false, s: '', x: 'free' }) + expect(wrapper.vm.saved).toBe(true) + + wrapper.vm.values = { n: null, m: ['a'], b: true, s: null, x: 0 } + await wrapper.vm.save() + expect(api.updateDashboardMetadata).toHaveBeenLastCalledWith('u1', { n: '', m: ['a'], b: true, s: '', x: 0 }) + + wrapper.vm.values = { n: '', m: null, b: 1, s: 'HR', x: undefined } + await wrapper.vm.save() + expect(api.updateDashboardMetadata).toHaveBeenLastCalledWith('u1', { n: '', m: [], b: false, s: 'HR', x: '' }) + }) + + it('shows the server message, or the fallback, when saving fails', async () => { + const wrapper = await mountTab() + api.updateDashboardMetadata.mockRejectedValueOnce({ response: { data: { message: 'Bad budget' } } }) + await wrapper.vm.save() + expect(wrapper.vm.error).toBe('Bad budget') + expect(wrapper.vm.saved).toBe(false) + + api.updateDashboardMetadata.mockRejectedValueOnce(new Error('x')) + await wrapper.vm.save() + expect(wrapper.vm.error).toBe('The details could not be saved.') + }) +}) diff --git a/src/components/Workspace/config/__tests__/ExportsTab.spec.js b/src/components/Workspace/config/__tests__/ExportsTab.spec.js new file mode 100644 index 000000000..0f82038f4 --- /dev/null +++ b/src/components/Workspace/config/__tests__/ExportsTab.spec.js @@ -0,0 +1,315 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ExportsTab (scheduled-exports tasks 13-14, REQ-SCH-011): the list is read + * from GET /api/exports and shows name, subject, next run and last-run + * status; Run now, Delete, Edit and View runs reach the API; the run + * history lists GET /api/exports/{id}/runs with a delivery summary and a + * run opens its detail. Only HTTP, toasts, the router and l10n are mocked. + */ + +import axios from '@nextcloud/axios' +import { showSuccess, showWarning } from '@nextcloud/dialogs' +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ExportsTab from '../ExportsTab.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, + generateRemoteUrl: (service) => `/remote.php/${service}`, +})) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showInfo: vi.fn(), + showSuccess: vi.fn(), + showWarning: vi.fn(), +})) +vi.mock( + '@conduction/nextcloud-vue', + () => import('../../../../modals/__tests__/helpers/scheduledExportStubs.js'), +) + +const BASE = '/index.php/apps/launchpad/api/exports' + +const exports = [ + { + id: 'e1', + name: 'Weekly bezwaren', + subjectType: 'dashboard', + subjectId: 'd-1', + enabled: true, + nextRunAt: '2026-11-16T09:00:00+01:00', + lastRunStatus: 'success', + recurrence: { type: 'weekly', daysOfWeek: ['MO'], timeOfDay: '09:00' }, + renderTargets: [{ format: 'pdf' }], + recipients: [ + { + id: 'r1', + channel: 'email', + channelConfig: { addresses: ['a@gemeente.nl'] }, + }, + ], + }, + { + id: 'e2', + name: 'Service desk snapshot', + subjectType: 'widget', + subjectId: '7', + enabled: false, + nextRunAt: null, + lastRunStatus: 'partial', + recurrence: { type: 'daily', timeOfDay: '08:00' }, + renderTargets: [{ format: 'png' }], + recipients: [ + { + channel: 'webhook', + channelConfig: { url: 'https://hooks.example.org' }, + }, + ], + }, +] + +const runs = [ + { + id: 'run-2', + exportId: 'e1', + startedAt: '2026-11-09T09:00:00+01:00', + status: 'partial', + triggeredBy: 'schedule', + deliveries: [ + { + recipientId: 'r1', + channel: 'email', + status: 'success', + attemptCount: 1, + }, + { + recipientId: 'r2', + channel: 'webhook', + status: 'failed-permanent', + attemptCount: 5, + error: 'HTTP 503', + }, + { + recipientId: 'r3', + channel: 'sftp', + status: 'retrying', + attemptCount: 2, + }, + ], + renderArtefacts: [], + }, + { + id: 'run-1', + exportId: 'e1', + startedAt: '2026-11-02T09:00:00+01:00', + status: 'partial', + triggeredBy: 'schedule', + skipReason: 'The previous run was still running', + deliveries: [], + renderArtefacts: [], + }, +] + +/** An export of another dashboard, which this dashboard's tab leaves out. */ +const otherDashboardExport = { + ...exports[0], + id: 'e3', + name: 'Other dashboard export', + subjectId: 'd-2', +} + +/** + * Mount the list with GET /api/exports answering the two exports. + * + * @return {Promise<object>} The wrapper, after the list loaded. + */ +async function mountList() { + axios.get.mockImplementation(async (url) => { + if (url === BASE) { + return { data: { results: [...exports, otherDashboardExport].map((e) => ({ ...e })), total: 3 } } + } + if (url === `${BASE}/e1/runs`) { + return { data: { results: runs, total: 2 } } + } + if (url === `${BASE}/e1/runs/run-2`) { + return { data: runs[0] } + } + throw new Error(`unexpected GET ${url}`) + }) + const wrapper = mount(ExportsTab, { + props: { + subjects: [ + { type: 'dashboard', id: 'd-1', label: 'Bezwaren' }, + { type: 'widget', id: '7', label: 'KPI' }, + ], + defaultSubject: { type: 'dashboard', id: 'd-1' }, + }, + }) + await flushPromises() + return wrapper +} + +describe('ExportsTab', () => { + beforeEach(() => { + vi.clearAllMocks() + setActivePinia(createPinia()) + }) + + it('lists the exports from the API with subject, next run and last-run status', async () => { + const wrapper = await mountList() + + expect(axios.get).toHaveBeenCalledWith(BASE, { params: { limit: 200 } }) + const rows = wrapper.findAll('tr.row') + expect(rows).toHaveLength(2) + expect(rows[0].find('[data-testid="scheduled-export-name"]').text()).toBe( + 'Weekly bezwaren', + ) + expect(rows[0].text()).toContain('Dashboard: Bezwaren') + expect( + rows[0].find('[data-testid="scheduled-export-next"]').text(), + ).not.toBe('Off') + expect( + rows[0].find('[data-testid="export-status"]').attributes('data-status'), + ).toBe('success') + expect(rows[0].find('[data-testid="export-status"]').text()).toBe( + 'Succeeded', + ) + expect(rows[1].text()).toContain('Widget: KPI') + expect(rows[1].find('[data-testid="scheduled-export-next"]').text()).toBe( + 'Off', + ) + expect(rows[1].find('[data-testid="export-status"]').text()).toBe( + 'Partly failed', + ) + }) + + it('REQ-SCH-011: lists only the exports of this dashboard and its widgets', async () => { + const wrapper = await mountList() + + expect(wrapper.text()).not.toContain('Other dashboard export') + expect(wrapper.findAll('tr.row')).toHaveLength(2) + }) + + it('"Run now" POSTs the run, reports how it went and reads the list again', async () => { + const wrapper = await mountList() + axios.post.mockResolvedValue({ data: { id: 'run-9', status: 'success' } }) + + await wrapper + .findAll('[data-testid="scheduled-export-run"]')[0] + .trigger('click') + await flushPromises() + + expect(axios.post).toHaveBeenCalledWith(`${BASE}/e1/run`) + expect(showSuccess).toHaveBeenCalledWith( + 'Weekly bezwaren ran and was delivered.', + ) + expect(axios.get.mock.calls.filter(([url]) => url === BASE)).toHaveLength(2) + + axios.post.mockResolvedValue({ data: { id: 'run-10', status: 'partial' } }) + await wrapper + .findAll('[data-testid="scheduled-export-run"]')[1] + .trigger('click') + await flushPromises() + expect(axios.post).toHaveBeenLastCalledWith(`${BASE}/e2/run`) + expect(showWarning).toHaveBeenCalledWith( + 'Service desk snapshot ran, but not every delivery succeeded.', + ) + }) + + it('deletes an export after confirmation', async () => { + const wrapper = await mountList() + axios.delete.mockResolvedValue({ data: { deleted: true } }) + + await wrapper + .findAll('[data-testid="scheduled-export-delete"]')[1] + .trigger('click') + expect(axios.delete).not.toHaveBeenCalled() + await wrapper.find('[data-testid="confirm"]').trigger('click') + await flushPromises() + + expect(axios.delete).toHaveBeenCalledWith(`${BASE}/e2`) + expect(wrapper.findAll('tr.row')).toHaveLength(1) + }) + + it('opens the editor on the chosen export and for a new one', async () => { + const wrapper = await mountList() + + await wrapper + .findAll('[data-testid="scheduled-export-edit"]')[0] + .trigger('click') + expect(wrapper.find('[data-testid="export-editor"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="export-name"]').element.value).toBe( + 'Weekly bezwaren', + ) + await wrapper + .findComponent({ name: 'ScheduledExportModal' }) + .vm.$emit('close') + expect(wrapper.find('[data-testid="export-editor"]').exists()).toBe(false) + + await wrapper.find('[data-testid="scheduled-exports-new"]').trigger('click') + expect(wrapper.find('[data-testid="export-name"]').element.value).toBe('') + }) + + it('"View runs" lists the run history with a delivery summary, and a run opens its detail', async () => { + const wrapper = await mountList() + + await wrapper + .findAll('[data-testid="scheduled-export-runs"]')[0] + .trigger('click') + await flushPromises() + + expect(axios.get).toHaveBeenCalledWith(`${BASE}/e1/runs`, { + params: { limit: 200 }, + }) + expect(wrapper.find('[data-testid="export-run-history"]').exists()).toBe( + true, + ) + const rows = wrapper.findAll('tr.row') + expect(rows).toHaveLength(2) + expect(rows[0].text()).toContain('On schedule') + expect(rows[0].findAll('td')[3].text()).toBe('3') + expect(rows[0].find('[data-testid="export-run-outcome"]').text()).toBe( + 'delivered: 1, failed: 1, waiting: 1', + ) + expect(rows[1].find('[data-testid="export-run-outcome"]').text()).toBe( + 'Skipped: The previous run was still running', + ) + + await rows[0].find('[data-testid="export-run-open"]').trigger('click') + await flushPromises() + expect(wrapper.find('[data-testid="run-detail"]').exists()).toBe(true) + expect(axios.get).toHaveBeenCalledWith(`${BASE}/e1/runs/run-2`) + + await wrapper.find('[data-testid="export-runs-back"]').trigger('click') + expect(wrapper.find('[data-testid="export-run-history"]').exists()).toBe( + false, + ) + expect( + wrapper.findAll('[data-testid="scheduled-export-name"]'), + ).toHaveLength(2) + }) + + it('a row click in the run history also opens the run', async () => { + const wrapper = await mountList() + await wrapper + .findAll('[data-testid="scheduled-export-runs"]')[0] + .trigger('click') + await flushPromises() + + await wrapper.findAll('tr.row')[0].trigger('click') + await flushPromises() + expect( + wrapper.findComponent({ name: 'RunDetailModal' }).props('run').id, + ).toBe('run-2') + }) +}) diff --git a/src/components/Workspace/config/__tests__/LanguagesTab.edits.spec.js b/src/components/Workspace/config/__tests__/LanguagesTab.edits.spec.js new file mode 100644 index 000000000..37e7c7c19 --- /dev/null +++ b/src/components/Workspace/config/__tests__/LanguagesTab.edits.spec.js @@ -0,0 +1,175 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * LanguagesTab: editing and saving a variant's name and description, + * deleting a non-primary variant, the load failure, every refusal message, + * adding a blank variant, and doing nothing without a chosen language. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import LanguagesTab from '../LanguagesTab.vue' +import { api } from '../../../../services/api.js' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), + getLanguage: () => 'en', +})) +vi.mock('../../../../services/api.js', () => ({ + api: { + listTranslations: vi.fn(), + createTranslation: vi.fn(), + updateTranslation: vi.fn(), + deleteTranslation: vi.fn(), + setPrimaryTranslation: vi.fn(), + }, +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcButton: { + name: 'NcButton', + props: ['disabled'], + emits: ['click'], + template: + '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: + '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)">', + }, + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel'], + emits: ['update:modelValue'], + template: + '<select :aria-label="inputLabel" @change="$emit(\'update:modelValue\', options[$event.target.selectedIndex])"><option v-for="o in options" :key="o.code">{{ o.name }}</option></select>', + }, +})) + +const en = { + id: 1, + dashboardUuid: 'intra', + languageCode: 'en', + name: 'Intranet', + description: 'News', + widgetTreeJson: null, + isPrimary: 1, +} +const nl = { + id: 2, + dashboardUuid: 'intra', + languageCode: 'nl', + name: 'Intranet', + description: 'News', + widgetTreeJson: null, + isPrimary: 0, +} + +/** + * A refused request carrying an error code. + * + * @param {string} error The error code. + * @return {Error} The rejection. + */ +function refused(error) { + return Object.assign(new Error('x'), { response: { data: { error } } }) +} + +/** + * Mount the tab and let it load. + * + * @return {Promise<object>} The wrapper. + */ +async function loaded() { + const wrapper = mount(LanguagesTab, { props: { dashboardUuid: 'intra' } }) + await flushPromises() + return wrapper +} + +beforeEach(() => vi.clearAllMocks()) + +describe('LanguagesTab editing', () => { + it('saves the edited name and description of a variant', async () => { + api.listTranslations.mockResolvedValue({ data: { translations: [en, nl] } }) + api.updateTranslation.mockResolvedValue({ data: {} }) + const wrapper = await loaded() + const [, , nlName, nlDescription] = wrapper.findAll('input') + + await nlName.setValue('Intranet NL') + await nlDescription.setValue('Nieuws') + await wrapper.findAll('[data-testid="language-save"]')[1].trigger('click') + await flushPromises() + + expect(api.updateTranslation).toHaveBeenCalledWith('intra', 'nl', { name: 'Intranet NL', description: 'Nieuws' }) + expect(api.listTranslations).toHaveBeenCalledTimes(2) + }) + + it('deletes a non-primary variant and offers no delete for the primary', async () => { + api.listTranslations.mockResolvedValue({ data: { translations: [en, { ...nl, isPrimary: false }] } }) + api.deleteTranslation.mockResolvedValue({ data: {} }) + const wrapper = await loaded() + + expect(wrapper.findAll('[data-testid="language-delete"]')).toHaveLength(1) + await wrapper.find('[data-testid="language-delete"]').trigger('click') + await flushPromises() + + expect(api.deleteTranslation).toHaveBeenCalledWith('intra', 'nl') + }) + + it('says when the language versions could not be loaded', async () => { + api.listTranslations.mockRejectedValue(new Error('down')) + const wrapper = await loaded() + + expect(wrapper.find('[data-testid="languages-error"]').text()).toBe('The language versions could not be loaded.') + expect(wrapper.findAll('[data-testid="language-row"]')).toHaveLength(0) + }) + + it('treats a response without a list as no variants', async () => { + api.listTranslations.mockResolvedValue({ data: {} }) + const wrapper = await loaded() + + expect(wrapper.findAll('[data-testid="language-row"]')).toHaveLength(0) + }) + + it('explains each refusal of a change', async () => { + api.listTranslations.mockResolvedValue({ data: { translations: [en, nl] } }) + const wrapper = await loaded() + const cases = [ + ['language_exists', 'This dashboard already has that language.'], + ['last_variant', 'A dashboard keeps at least one language.'], + ['something_else', 'The change could not be saved.'], + ] + + for (const [code, message] of cases) { + api.updateTranslation.mockRejectedValueOnce(refused(code)) + await wrapper.find('[data-testid="language-save"]').trigger('click') + await flushPromises() + expect(wrapper.find('[data-testid="languages-error"]').text()).toBe(message) + } + + api.setPrimaryTranslation.mockRejectedValueOnce(new Error('network')) + await wrapper.find('[data-testid="language-make-primary"]').trigger('click') + await flushPromises() + expect(wrapper.find('[data-testid="languages-error"]').text()).toBe('The change could not be saved.') + }) + + it('adds nothing without a chosen language, and a blank variant without a source', async () => { + api.listTranslations.mockResolvedValue({ data: { translations: [en] } }) + api.createTranslation.mockRejectedValueOnce(refused('language_exists')) + const wrapper = await loaded() + + await wrapper.find('[data-testid="language-add"]').trigger('click') + await flushPromises() + expect(api.createTranslation).not.toHaveBeenCalled() + + wrapper.vm.newLanguage = { code: 'de' } + wrapper.vm.copyFrom = null + await wrapper.vm.add() + expect(api.createTranslation).toHaveBeenCalledWith('intra', { languageCode: 'de' }) + expect(wrapper.vm.error).toBe('This dashboard already has that language.') + }) +}) diff --git a/src/components/Workspace/config/__tests__/PublicationTab.spec.js b/src/components/Workspace/config/__tests__/PublicationTab.spec.js new file mode 100644 index 000000000..6bba9a98a --- /dev/null +++ b/src/components/Workspace/config/__tests__/PublicationTab.spec.js @@ -0,0 +1,130 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The Publication tab of the dashboard settings (REQ-SCHEDUI-001): it shows + * the status, publishes and unpublishes, schedules go-live and take-down + * through the store and explains a refusal (DashboardService::ERR_* + * messages). Only the HTTP client, toasts and l10n are mocked. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import PublicationTab, { scheduleRefusal, toIso } from '../PublicationTab.vue' +import { api } from '../../../../services/api.js' + +vi.mock('../../../../services/api.js', () => ({ + api: { + scheduleDashboard: vi.fn(), + publishDashboard: vi.fn(), + unpublishDashboard: vi.fn(), + }, +})) +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('@nextcloud/vue', () => ({ + NcButton: { + props: ['disabled', 'variant'], + emits: ['click'], + render() { + return h('button', { disabled: this.disabled, onClick: () => this.$emit('click') }, this.$slots.default?.()) + }, + }, +})) + +/** + * @param {number} status HTTP status. + * @param {string} message The server's message. + * @return {Error} An axios-like error. + */ +function refusal(status, message) { + return Object.assign(new Error('refused'), { response: { status, data: { message } } }) +} + +/** + * @param {object} dashboard The dashboard. + * @return {object} The wrapper. + */ +function mountTab(dashboard) { + return mount(PublicationTab, { props: { dashboard } }) +} + +beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() +}) + +describe('PublicationTab', () => { + it('shows the status and the one action that fits it', () => { + const published = mountTab({ uuid: 'd', publicationStatus: 'published' }) + expect(published.find('[data-testid="publication-status"]').text()).toBe('Published') + expect(published.find('[data-testid="publication-unpublish"]').exists()).toBe(true) + expect(published.find('[data-testid="publication-publish"]').exists()).toBe(false) + + const draft = mountTab({ uuid: 'd', publicationStatus: 'draft' }) + expect(draft.find('[data-testid="publication-status"]').text()).toBe('Draft') + expect(draft.find('[data-testid="publication-publish"]').exists()).toBe(true) + + const scheduled = mountTab({ uuid: 'd', publicationStatus: 'scheduled' }) + expect(scheduled.find('[data-testid="publication-status"]').text()).toBe('Scheduled') + expect(scheduled.find('[data-testid="publication-publish"]').exists()).toBe(true) + }) + + it('publishes and unpublishes the dashboard by its uuid', async () => { + api.publishDashboard.mockResolvedValue({ data: { dashboard: { uuid: 'd', publicationStatus: 'published' } } }) + api.unpublishDashboard.mockResolvedValue({ data: { dashboard: { uuid: 'd', publicationStatus: 'draft' } } }) + + await mountTab({ uuid: 'd', publicationStatus: 'draft' }).find('[data-testid="publication-publish"]').trigger('click') + await flushPromises() + expect(api.publishDashboard).toHaveBeenCalledWith('d') + + await mountTab({ uuid: 'd', publicationStatus: 'published' }).find('[data-testid="publication-unpublish"]').trigger('click') + await flushPromises() + expect(api.unpublishDashboard).toHaveBeenCalledWith('d') + }) + + it('schedules go-live and take-down through the store and clears the fields', async () => { + api.scheduleDashboard.mockResolvedValue({ data: { dashboard: { uuid: 'd', publicationStatus: 'scheduled' } } }) + const wrapper = mountTab({ uuid: 'd', publicationStatus: 'draft' }) + const save = wrapper.find('[data-testid="schedule-save"]') + expect(save.attributes('disabled')).toBeDefined() + + await wrapper.find('[data-testid="schedule-go-live"]').setValue('2099-10-01T09:00') + await wrapper.find('[data-testid="schedule-take-down"]').setValue('2099-10-02T17:00') + expect(save.attributes('disabled')).toBeUndefined() + await save.trigger('click') + await flushPromises() + + expect(api.scheduleDashboard).toHaveBeenCalledWith( + 'd', + new Date('2099-10-01T09:00').toISOString(), + new Date('2099-10-02T17:00').toISOString(), + ) + expect(wrapper.find('[data-testid="schedule-error"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="schedule-go-live"]').element.value).toBe('') + }) + + it('a past time is explained in the tab and the fields stay', async () => { + api.scheduleDashboard.mockRejectedValue(refusal(400, 'publishAt must be a future timestamp')) + const wrapper = mountTab({ uuid: 'd', publicationStatus: 'draft' }) + await wrapper.find('[data-testid="schedule-go-live"]').setValue('2020-01-01T00:00') + await wrapper.find('[data-testid="schedule-save"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="schedule-error"]').text()).toBe('Choose a time in the future.') + expect(wrapper.find('[data-testid="schedule-go-live"]').element.value).toBe('2020-01-01T00:00') + }) + + it('explains an end before the start, and any other refusal', () => { + expect(scheduleRefusal('unpublishAt must be after publishAt')).toBe('The dashboard has to go live before it comes down.') + expect(scheduleRefusal('')).toBe('The dashboard could not be scheduled.') + }) + + it('turns a local time into ISO, and an empty or unreadable one into null', () => { + expect(toIso('')).toBeNull() + expect(toIso('not a date')).toBeNull() + expect(toIso('2026-10-01T09:00')).toBe(new Date('2026-10-01T09:00').toISOString()) + }) +}) diff --git a/src/components/Workspace/config/__tests__/SharingConversation.spec.js b/src/components/Workspace/config/__tests__/SharingConversation.spec.js new file mode 100644 index 000000000..7a44e2d3a --- /dev/null +++ b/src/components/Workspace/config/__tests__/SharingConversation.spec.js @@ -0,0 +1,69 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The conversation part of the Sharing tab (REQ-LEAF-006): a switch on a + * shared dashboard that is stored at once, and a note on an unshared one. + * + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import SharingConversation from '../SharingConversation.vue' + +const api = vi.hoisted(() => ({ updateDashboard: vi.fn() })) +vi.mock('../../../../services/api.js', () => ({ api })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const SwitchStub = { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'loading', 'disabled', 'type'], + emits: ['update:modelValue'], + template: '<label class="switch" :data-checked="String(modelValue)"><slot /></label>', +} + +function mountIt(props) { + return mount(SharingConversation, { props, global: { stubs: { NcCheckboxRadioSwitch: SwitchStub } } }) +} + +describe('SharingConversation', () => { + beforeEach(() => { + api.updateDashboard.mockReset() + }) + + it('says the conversation appears once shared, without a switch, on an unshared dashboard', () => { + const wrapper = mountIt({ dashboard: { id: 1 }, shared: false }) + expect(wrapper.find('[data-test="sharing-conversation-unshared"]').text()).toBe( + 'This dashboard is yours alone. Share it with people or a group and the conversation appears here too.', + ) + expect(wrapper.findComponent(SwitchStub).exists()).toBe(false) + }) + + it('shows the switch on a shared dashboard, on by default', () => { + const wrapper = mountIt({ dashboard: { id: 1, conversationEnabled: null }, shared: true }) + expect(wrapper.findComponent(SwitchStub).props('modelValue')).toBe(true) + expect(wrapper.text()).toContain('Show the conversation beside the dashboard') + }) + + it('stores the switch at once and reports the stored value', async () => { + api.updateDashboard.mockResolvedValue({ data: {} }) + const wrapper = mountIt({ dashboard: { id: 4, conversationEnabled: 1 }, shared: true }) + wrapper.findComponent(SwitchStub).vm.$emit('update:modelValue', false) + await flushPromises() + expect(api.updateDashboard).toHaveBeenCalledWith(4, { conversationEnabled: false }) + expect(wrapper.emitted('update:conversationEnabled')).toEqual([[0]]) + expect(wrapper.findComponent(SwitchStub).props('modelValue')).toBe(false) + }) + + it('returns the switch when storing fails', async () => { + api.updateDashboard.mockRejectedValue(new Error('down')) + const wrapper = mountIt({ dashboard: { id: 4, conversationEnabled: 1 }, shared: true }) + wrapper.findComponent(SwitchStub).vm.$emit('update:modelValue', false) + await flushPromises() + expect(wrapper.findComponent(SwitchStub).props('modelValue')).toBe(true) + expect(wrapper.find('[role="alert"]').text()).toBe('The conversation setting could not be saved.') + expect(wrapper.emitted('update:conversationEnabled')).toBeUndefined() + }) +}) diff --git a/src/components/Workspace/config/__tests__/SharingEmbedTokens.spec.js b/src/components/Workspace/config/__tests__/SharingEmbedTokens.spec.js new file mode 100644 index 000000000..0cc0571f6 --- /dev/null +++ b/src/components/Workspace/config/__tests__/SharingEmbedTokens.spec.js @@ -0,0 +1,118 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The embed part of the Sharing tab (REQ-EMB-011): the dashboard's tokens + * only, a new token shown once with the code for the website, and Withdraw + * through the revocation (REQ-EMB-009). + * + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import SharingEmbedTokens from '../SharingEmbedTokens.vue' + +const embed = vi.hoisted(() => ({ listTokens: vi.fn(), createToken: vi.fn(), revokeToken: vi.fn() })) +const api = vi.hoisted(() => ({ getDashboardById: vi.fn() })) +vi.mock('../../../../services/embedApi.js', () => ({ embedApi: embed })) +vi.mock('../../../../services/api.js', () => ({ api })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const Button = { name: 'NcButton', emits: ['click'], template: '<button @click="$emit(\'click\', $event)"><slot /></button>' } +const FormStub = { name: 'EmbedTokenForm', props: ['dashboards', 'themes', 'defaults', 'saving'], emits: ['submit', 'cancel'], template: '<div class="form-stub" />' } +const DialogStub = { name: 'RevokeEmbedTokenDialog', props: ['open', 'name'], emits: ['update:open', 'confirm'], template: '<div class="revoke-stub" />' } + +const DASHBOARD = { id: 3, uuid: 'dash-3', name: 'Cases' } +const WHOLE = { id: 't-1', name: 'Intranet', subject: { type: 'dashboard', id: 'dash-3' }, hostOrigins: ['https://intra.nl'] } +const WIDGET = { id: 't-2', name: 'Website Zuiddrecht', subject: { type: 'widget', id: '11' }, hostOrigins: ['https://www.zuiddrecht.nl'] } +const OTHER = { id: 't-3', name: 'Elsewhere', subject: { type: 'dashboard', id: 'dash-9' }, hostOrigins: [] } + +function mountIt() { + return mount(SharingEmbedTokens, { + props: { dashboard: DASHBOARD }, + global: { + stubs: { + NcButton: Button, + NcNoteCard: { props: ['type'], template: '<div :class="\'note-\' + type"><slot /></div>' }, + NcLoadingIcon: true, + EmbedTokenForm: FormStub, + RevokeEmbedTokenDialog: DialogStub, + }, + }, + }) +} + +describe('SharingEmbedTokens', () => { + beforeEach(() => { + vi.clearAllMocks() + embed.listTokens.mockResolvedValue([WHOLE, WIDGET, OTHER]) + api.getDashboardById.mockResolvedValue({ data: { placements: [{ id: 11, customTitle: 'Open cases per case type' }] } }) + }) + + it('lists only the tokens of this dashboard and its widgets, with what they show', async () => { + const wrapper = mountIt() + await flushPromises() + expect(api.getDashboardById).toHaveBeenCalledWith(3) + expect(wrapper.find('[data-test="sharing-embed-row-t-1"]').text()).toContain('The whole dashboard') + expect(wrapper.find('[data-test="sharing-embed-row-t-2"]').text()).toContain('Widget Open cases per case type') + expect(wrapper.find('[data-test="sharing-embed-row-t-2"]').text()).toContain('https://www.zuiddrecht.nl') + expect(wrapper.find('[data-test="sharing-embed-row-t-3"]').exists()).toBe(false) + expect(wrapper.find('[data-test="sharing-embed-state-t-1"]').text()).toBe('Active') + }) + + it('starts a new token on this dashboard', async () => { + const wrapper = mountIt() + await flushPromises() + await wrapper.find('[data-test="sharing-embed-new"]').trigger('click') + const form = wrapper.findComponent(FormStub) + expect(form.props('dashboards')).toEqual([{ id: 3, uuid: 'dash-3', name: 'Cases' }]) + expect(form.props('defaults')).toEqual({ subjectType: 'dashboard', subjectId: 'dash-3', dashboardId: 3 }) + }) + + it('shows a new token once, lists it as Active and gives the iframe code with it', async () => { + const created = { ...WIDGET, id: 't-4' } + embed.createToken.mockResolvedValue({ id: 't-4', name: 'Website Zuiddrecht', jwt: 'header.body.sig' }) + const wrapper = mountIt() + await flushPromises() + embed.listTokens.mockResolvedValue([WHOLE, WIDGET, created]) + await wrapper.find('[data-test="sharing-embed-new"]').trigger('click') + wrapper.findComponent(FormStub).vm.$emit('submit', { name: 'Website Zuiddrecht' }) + await flushPromises() + + expect(wrapper.find('[data-test="sharing-embed-issued"]').text()).toContain('Token Website Zuiddrecht has been created. Copy it now: it is not shown again.') + expect(wrapper.find('[data-test="sharing-embed-jwt"]').text()).toBe('header.body.sig') + expect(wrapper.find('[data-test="sharing-embed-state-t-4"]').text()).toBe('Active') + const code = wrapper.find('[data-test="sharing-embed-code"] textarea').element.value + expect(code).toContain('<iframe src="') + expect(code).toContain('/index.php/apps/launchpad/embed/widget/11?token=header.body.sig') + + await wrapper.find('[data-test="sharing-embed-issued-done"]').trigger('click') + expect(wrapper.find('[data-test="sharing-embed-jwt"]').exists()).toBe(false) + expect(wrapper.find('[data-test="sharing-embed-code"] textarea').element.value).toContain('token=YOUR_TOKEN') + }) + + it('withdraws a token through the revocation and shows it as revoked', async () => { + embed.revokeToken.mockResolvedValue({ ...WHOLE, revokedAt: '2026-11-24T10:00:00Z', revocationReason: 'no_longer_needed' }) + const wrapper = mountIt() + await flushPromises() + await wrapper.find('[data-test="sharing-embed-withdraw-t-1"]').trigger('click') + wrapper.findComponent(DialogStub).vm.$emit('confirm', { reason: 'no_longer_needed', notes: '' }) + await flushPromises() + + expect(embed.revokeToken).toHaveBeenCalledWith('t-1', 'no_longer_needed', '') + expect(wrapper.find('[data-test="sharing-embed-state-t-1"]').text()).toBe('Revoked on 2026-11-24 (no_longer_needed)') + expect(wrapper.find('[data-test="sharing-embed-withdraw-t-1"]').exists()).toBe(false) + }) + + it('says when the tokens cannot be loaded', async () => { + embed.listTokens.mockRejectedValue(new Error('403')) + const wrapper = mountIt() + await flushPromises() + expect(wrapper.find('[data-test="sharing-embed-error"]').text()).toBe('Embed tokens could not be loaded.') + }) +}) diff --git a/src/components/Workspace/config/__tests__/VersionsTab.spec.js b/src/components/Workspace/config/__tests__/VersionsTab.spec.js new file mode 100644 index 000000000..428bb68f1 --- /dev/null +++ b/src/components/Workspace/config/__tests__/VersionsTab.spec.js @@ -0,0 +1,293 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * VersionsTab, the Versions tab of the dashboard settings: lists versions newest first, saves a named version + * and restores after confirmation (dashboard-versioning REQ-VERSUI-001..003). + * Response shapes are DashboardVersionApiController's: `{versions, + * modeSupported}` for the list, `{version}` (201) for a save, `{version, + * snapshot}` for a restore; each version is DashboardVersion::jsonSerialize. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import VersionsTab from '../VersionsTab.vue' +import { api } from '../../../../services/api.js' + +vi.mock('@nextcloud/l10n', () => ({ + getCanonicalLocale: () => 'en-GB', + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) + +vi.mock('../../../../services/api.js', () => ({ + api: { + listVersions: vi.fn(), + createVersion: vi.fn(), + restoreVersion: vi.fn(), + }, +})) + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnConfirmDialog: { + name: 'CnConfirmDialog', + props: ['dialogTitle', 'message', 'confirmLabel'], + emits: ['confirm', 'close'], + template: + '<div class="dialog">{{ message }}<button data-testid="cn-confirm-dialog-confirm" @click="$emit(\'confirm\')">{{ confirmLabel }}</button></div>', + }, + NcButton: { + name: 'NcButton', + props: ['disabled'], + emits: ['click'], + template: + '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: + '<input :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)">', + }, + NcLoadingIcon: { name: 'NcLoadingIcon', template: '<span class="loading" />' }, +})) + +function v(n, note = null, createdBy = 'sanne') { + return { + id: n, + dashboardUuid: 'dash-uuid', + versionNumber: n, + createdBy, + createdAt: `2026-09-2${n} 10:00:00`, + note, + sizeBytes: 120, + } +} + +function mountModal() { + return mount(VersionsTab, { + props: { dashboardUuid: 'dash-uuid' }, + }) +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('VersionsTab', () => { + it('REQ-VERSUI-001: lists versions newest first with author and note', async () => { + api.listVersions.mockResolvedValue({ + data: { + versions: [v(2), v(4, 'before the reorganisation'), v(1), v(3)], + modeSupported: true, + }, + }) + const wrapper = mountModal() + await flushPromises() + expect(api.listVersions).toHaveBeenCalledWith('dash-uuid') + const rows = wrapper.findAll('[data-testid="version-row"]') + expect(rows).toHaveLength(4) + expect(rows[0].text()).toContain('4') + expect(rows[0].text()).toContain('before the reorganisation') + expect(rows[0].text()).toContain('sanne') + expect(rows[3].text()).toContain('1') + }) + + // @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-the-owner-sees-the-version-history-req-versui-001 + it('REQ-VERSUI-001: draws the columns When, By and What changed, the newest marked current', async () => { + api.listVersions.mockResolvedValue({ data: { versions: [v(1), v(2)], modeSupported: true } }) + const wrapper = mountModal() + await flushPromises() + const headings = wrapper.findAll('thead th').map((th) => th.text()).filter((text) => text !== '') + expect(headings.slice(0, 3)).toEqual(['When', 'By', 'What changed']) + const rows = wrapper.findAll('[data-testid="version-row"]') + expect(rows[0].find('[data-testid="version-current"]').exists()).toBe(true) + expect(rows[1].find('[data-testid="version-current"]').exists()).toBe(false) + }) + + // @spec openspec/changes/archive/2026-11-24-version-change-notes/specs/dashboard-versioning/spec.md#requirement-a-template-update-is-noted-as-such-req-versui-005 + it('REQ-VERSUI-005: names a template author by the template', async () => { + api.listVersions.mockResolvedValue({ + data: { versions: [{ ...v(3, 'Updated from the template', 'admin'), createdByName: 'Template Intranet' }], modeSupported: true }, + }) + const wrapper = mountModal() + await flushPromises() + const row = wrapper.find('[data-testid="version-row"]') + expect(row.text()).toContain('Template Intranet') + expect(row.text()).not.toContain('admin') + }) + + it('REQ-VERSUI-002: saves a named version and puts it on top', async () => { + api.listVersions.mockResolvedValue({ + data: { versions: [v(1)], modeSupported: true }, + }) + api.createVersion.mockResolvedValue({ + data: { version: v(2, 'before the reorganisation') }, + }) + const wrapper = mountModal() + await flushPromises() + await wrapper.find('input').setValue('before the reorganisation') + await wrapper.find('[data-testid="version-save"]').trigger('click') + await flushPromises() + expect(api.createVersion).toHaveBeenCalledWith( + 'dash-uuid', + 'before the reorganisation', + ) + const rows = wrapper.findAll('[data-testid="version-row"]') + expect(rows).toHaveLength(2) + expect(rows[0].text()).toContain('before the reorganisation') + }) + + it('REQ-VERSUI-003: restore asks first, restores, reloads the list and tells the page', async () => { + api.listVersions.mockResolvedValueOnce({ + data: { versions: [v(2), v(1)], modeSupported: true }, + }) + api.restoreVersion.mockResolvedValue({ + data: { version: v(1), snapshot: '{}' }, + }) + api.listVersions.mockResolvedValueOnce({ + data: { + versions: [v(3, 'pre-restore'), v(2), v(1)], + modeSupported: true, + }, + }) + const wrapper = mountModal() + await flushPromises() + await wrapper.findAll('[data-testid="version-row"]')[1].trigger('click') + await wrapper.find('[data-testid="version-restore"]').trigger('click') + expect(api.restoreVersion).not.toHaveBeenCalled() + await wrapper + .find('[data-testid="cn-confirm-dialog-confirm"]') + .trigger('click') + await flushPromises() + expect(api.restoreVersion).toHaveBeenCalledWith('dash-uuid', 1) + expect(wrapper.emitted('restored')).toHaveLength(1) + expect(wrapper.findAll('[data-testid="version-row"]')[0].text()).toContain( + '3', + ) + }) + + it('cancelling the confirmation restores nothing', async () => { + api.listVersions.mockResolvedValue({ data: { versions: [v(2), v(1)], modeSupported: true } }) + const wrapper = mountModal() + await flushPromises() + + await wrapper.findAll('[data-testid="version-row"]')[1].trigger('click') + await wrapper.find('[data-testid="version-restore"]').trigger('click') + wrapper.findComponent({ name: 'CnConfirmDialog' }).vm.$emit('close') + await flushPromises() + expect(wrapper.vm.restoreTarget).toBeNull() + await wrapper.vm.confirmRestore() + expect(api.restoreVersion).not.toHaveBeenCalled() + }) + + it('saves a blank note as none, and keeps the list when the answer has no version', async () => { + api.listVersions.mockResolvedValue({ data: { versions: [v(1)], modeSupported: true } }) + api.createVersion.mockResolvedValue({ data: {} }) + const wrapper = mountModal() + await flushPromises() + + await wrapper.find('input').setValue(' ') + await wrapper.find('[data-testid="version-save"]').trigger('click') + await flushPromises() + + expect(api.createVersion).toHaveBeenCalledWith('dash-uuid', null) + expect(wrapper.findAll('[data-testid="version-row"]')).toHaveLength(1) + expect(wrapper.vm.error).toBe('') + }) + + it('says so when a version cannot be saved, keeping the note', async () => { + api.listVersions.mockResolvedValue({ data: { versions: [], modeSupported: true } }) + api.createVersion.mockRejectedValue(new Error('500')) + const wrapper = mountModal() + await flushPromises() + + await wrapper.find('input').setValue('before the move') + await wrapper.find('[data-testid="version-save"]').trigger('click') + await flushPromises() + + expect(wrapper.vm.error).toBe('The version could not be saved.') + expect(wrapper.vm.note).toBe('before the move') + expect(wrapper.vm.saving).toBe(false) + }) + + it('says so when a restore fails, without telling the page or reloading', async () => { + api.listVersions.mockResolvedValue({ data: { versions: [v(2), v(1)], modeSupported: true } }) + api.restoreVersion.mockRejectedValue(new Error('409')) + const wrapper = mountModal() + await flushPromises() + + await wrapper.findAll('[data-testid="version-row"]')[1].trigger('click') + await wrapper.find('[data-testid="version-restore"]').trigger('click') + await wrapper.find('[data-testid="cn-confirm-dialog-confirm"]').trigger('click') + await flushPromises() + + expect(api.restoreVersion).toHaveBeenCalledWith('dash-uuid', 1) + expect(wrapper.vm.error).toBe('The version could not be restored.') + expect(wrapper.emitted('restored')).toBeUndefined() + expect(api.listVersions).toHaveBeenCalledTimes(1) + }) + + it('formats no date as empty and an unreadable one as itself', async () => { + api.listVersions.mockResolvedValue({ data: { versions: [], modeSupported: true } }) + const wrapper = mountModal() + await flushPromises() + + expect(wrapper.vm.formatDate('')).toBe('') + expect(wrapper.vm.formatDate(null)).toBe('') + expect(wrapper.vm.formatDate('yesterday')).toBe('yesterday') + expect(wrapper.vm.formatDate('2026-09-21 10:00:00')).not.toBe('2026-09-21 10:00:00') + }) + + it('says so when versioning is not supported for the dashboard', async () => { + api.listVersions.mockResolvedValue({ + data: { versions: [], modeSupported: false }, + }) + const wrapper = mountModal() + await flushPromises() + expect(wrapper.find('[data-testid="version-unsupported"]').exists()).toBe( + true, + ) + expect(wrapper.find('[data-testid="version-save"]').exists()).toBe(false) + }) + + it('shows the error when the list cannot be read', async () => { + api.listVersions.mockRejectedValue( + Object.assign(new Error('x'), { + response: { status: 403, data: { error: 'forbidden' } }, + }), + ) + const wrapper = mountModal() + await flushPromises() + expect(wrapper.find('[data-testid="version-error"]').exists()).toBe(true) + }) + + it('reads the list again for another dashboard', async () => { + api.listVersions.mockResolvedValue({ data: { versions: [], modeSupported: true } }) + const wrapper = mountModal() + await flushPromises() + await wrapper.setProps({ dashboardUuid: 'other-uuid' }) + await flushPromises() + expect(api.listVersions).toHaveBeenLastCalledWith('other-uuid') + }) + + it('marks the newest as the current version, previews a chosen older one and offers no restore for the current (LpVersies)', async () => { + api.listVersions.mockResolvedValue({ data: { versions: [v(2, 'Widget News moved'), { ...v(1), createdByName: 'Sanne de Vries' }], modeSupported: true } }) + const wrapper = mountModal() + await flushPromises() + + const rows = wrapper.findAll('[data-testid="version-row"]') + expect(rows[0].find('[data-testid="version-current"]').exists()).toBe(true) + expect(rows[1].text()).toContain('Sanne de Vries') + expect(wrapper.find('[data-testid="version-restore"]').attributes('disabled')).toBeDefined() + expect(wrapper.find('[data-testid="version-preview"]').exists()).toBe(false) + + await rows[1].trigger('click') + expect(wrapper.find('[data-testid="version-preview"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="version-restore"]').attributes('disabled')).toBeUndefined() + + await wrapper.find('[data-testid="version-close"]').trigger('click') + expect(wrapper.emitted('close')).toHaveLength(1) + }) +}) diff --git a/src/components/Workspace/moreMenuItems.js b/src/components/Workspace/moreMenuItems.js new file mode 100644 index 000000000..f07adf21c --- /dev/null +++ b/src/components/Workspace/moreMenuItems.js @@ -0,0 +1,453 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The items of launchpad's one More menu (board LpMeer), built the same way + * on every page: the Dashboards group, the items under Settings and the + * This dashboard group. LaunchpadMoreMenu draws them. + */ + +import { CnDashboardIcon } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { h, markRaw } from 'vue' +import AccountOutline from 'vue-material-design-icons/AccountOutline.vue' +import BookOpenVariantOutline from 'vue-material-design-icons/BookOpenVariantOutline.vue' +import ChartBoxOutline from 'vue-material-design-icons/ChartBoxOutline.vue' +import ContentCopy from 'vue-material-design-icons/ContentCopy.vue' +import ContentSave from 'vue-material-design-icons/ContentSave.vue' +import FileReplaceOutline from 'vue-material-design-icons/FileReplaceOutline.vue' +import Home from 'vue-material-design-icons/Home.vue' +import LinkVariant from 'vue-material-design-icons/LinkVariant.vue' +import MapMarkerPath from 'vue-material-design-icons/MapMarkerPath.vue' +import Pencil from 'vue-material-design-icons/Pencil.vue' +import Plus from 'vue-material-design-icons/Plus.vue' +import PowerPlugOutline from 'vue-material-design-icons/PowerPlugOutline.vue' +import ShareVariant from 'vue-material-design-icons/ShareVariant.vue' +import ShieldAccountOutline from 'vue-material-design-icons/ShieldAccountOutline.vue' +import Sitemap from 'vue-material-design-icons/Sitemap.vue' +import Star from 'vue-material-design-icons/Star.vue' +import StarCheck from 'vue-material-design-icons/StarCheck.vue' +import StoreOutline from 'vue-material-design-icons/StoreOutline.vue' +import TrashCanOutline from 'vue-material-design-icons/TrashCanOutline.vue' +import ViewDashboardOutline from 'vue-material-design-icons/ViewDashboardOutline.vue' +import ViewGridOutline from 'vue-material-design-icons/ViewGridOutline.vue' +import { adminPageUrl } from '../../utils/adminPage.js' + +/** + * The sections of the navigation panel, in the panel's order. + */ +const SECTIONS = ['main', 'footer', 'settings'] + +/** The items of the Settings group, in the board's order. */ +const SETTINGS_ITEMS = ['personal-settings', 'admin-settings-link'] + +/** + * The order of the app's own destinations, as the boards list them. An + * entry not named here follows, in the panel's order. + */ +const LAUNCHPAD_ORDER = [ + 'StoreMenu', + 'admin-templates', + 'ReportsMenu', + 'FlowsMenu', + 'IntegrationsMenu', + 'Documentation', + 'FeaturesRoadmapMenu', +] + +/** + * Panel entries the Launchpad group leaves out because another item already + * offers them: the dashboards (the Dashboards group) and the in-app admin + * settings route (the Settings group links to the admin settings). + */ +const OFFERED_ELSEWHERE = ['dashboards', 'admin-settings'] + +/** + * The app's own destinations in the board's order. + * + * @param {object[]} items The resolved panel items. + * @return {object[]} The items, ordered. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ +export function orderDestinations(items) { + const rank = (item) => { + const at = LAUNCHPAD_ORDER.indexOf(item.id) + return at === -1 ? LAUNCHPAD_ORDER.length : at + } + return items + .map((item, index) => ({ item, index })) + .sort((a, b) => rank(a.item) - rank(b.item) || a.index - b.index) + .map(({ item }) => item) +} + +/** + * The Settings group's items: the personal settings and, for an + * administrator, the admin settings link. + * + * @param {Record<string, object[]>} sections The menu items by section. + * @return {object[]} The items. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ +export function settingsItems(sections) { + return SETTINGS_ITEMS.map((id) => + sections.settings.find((item) => item.id === id), + ).filter(Boolean) +} + +/** + * The Launchpad group's items: the app's own destinations in the board's + * order, without the ones another group already offers. + * + * @param {Record<string, object[]>} sections The menu items by section. + * @return {object[]} The items. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ +export function launchpadItems(sections) { + return orderDestinations( + [...sections.main, ...sections.footer, ...sections.settings].filter( + (item) => + !OFFERED_ELSEWHERE.includes(item.id) + && !SETTINGS_ITEMS.includes(item.id), + ), + ) +} + +/** + * Whether a destination leaves the instance (scheme-prefixed), which is + * the same test the panel's `NcAppNavigationItem` applies before it opens + * a new tab. + * + * @param {string} href The destination. + * @return {boolean} True for a `scheme://` URL. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ +export function isExternal(href) { + return /^(https?:)?\/\//.test(String(href ?? '')) +} + +/** + * Resolve one panel entry to a menu item: a link for `href`, a router + * target for `route`, a button for `action: "user-settings"`. The same + * precedence as the panel (`CnAppNav.itemTo` / `itemHref`): an action + * never carries a link. + * + * @param {object} item The manifest menu entry. + * @param {(() => void)|null} openUserSettings The injected personal-settings opener. + * @return {object|null} The menu item, or null when the entry has no destination. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ +export function resolveMenuItem(item, openUserSettings) { + const label = t('launchpad', String(item.label ?? item.id ?? '')) + if (item.action === 'user-settings') { + if (typeof openUserSettings !== 'function') { + return null + } + return { id: item.id, label, onClick: openUserSettings } + } + if (item.href) { + return { + id: item.id, + label, + href: item.href, + external: isExternal(item.href), + } + } + if (item.route) { + return { + id: item.id, + label, + to: item.query + ? { name: item.route, query: item.query } + : { name: item.route }, + } + } + return null +} + +/** + * The panel's destinations by section (`main`, `footer`, `settings`) for + * the chrome decision `App.vue` provides. The settings section opens with + * the personal settings and, for an administrator, the link to the admin + * settings, as the panel's settings foldout does. + * + * @param {{ entries: object[], isAdmin: boolean, includePersonalSettings: boolean }} chrome The chrome decision. + * @param {(() => void)|null} openUserSettings The injected personal-settings opener. + * @return {Record<string, object[]>} The menu items by section. + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ +export function startPageSections(chrome, openUserSettings) { + const bySection = Object.fromEntries(SECTIONS.map((s) => [s, []])) + for (const entry of chrome.entries) { + const section = entry.section ?? 'main' + if (!(section in bySection)) { + continue + } + const item = resolveMenuItem(entry, openUserSettings) + if (item) { + bySection[section].push(item) + } + } + const settings = [] + if (chrome.includePersonalSettings && typeof openUserSettings === 'function') { + settings.push({ + id: 'personal-settings', + label: t('launchpad', 'Personal settings'), + onClick: openUserSettings, + }) + } + if (chrome.isAdmin) { + settings.push({ + id: 'admin-settings-link', + label: t('launchpad', 'Admin settings'), + // The administration, a Launchpad page (admin-settings REQ-ADM-030). + href: adminPageUrl(), + external: false, + }) + } + bySection.settings = [...settings, ...bySection.settings] + return bySection +} + +/** + * Read the chrome decision `App.vue` provides, unwrapped, with defaults + * that keep the panel. + * + * @param {object|null} provided The injected `launchpadChrome` (a ref or a plain value). + * @return {{ railSuppressed: boolean, entries: object[], isAdmin: boolean, includePersonalSettings: boolean }} + * @spec openspec/specs/runtime-shell/spec.md#req-shell-009 + */ +export function readChrome(provided) { + const value = provided?.value ?? provided + return { + railSuppressed: value?.railSuppressed === true, + entries: Array.isArray(value?.entries) ? value.entries : [], + isAdmin: value?.isAdmin === true, + includePersonalSettings: value?.includePersonalSettings !== false, + } +} + +/** How many dashboards the menu lists before "All dashboards". */ +export const DASHBOARD_LIMIT = 8 + +/** Icons of the destinations under Settings, by menu entry id. */ +const DESTINATION_ICONS = { + StoreMenu: StoreOutline, + 'admin-templates': FileReplaceOutline, + ReportsMenu: ChartBoxOutline, + FlowsMenu: Sitemap, + IntegrationsMenu: PowerPlugOutline, + Documentation: BookOpenVariantOutline, + FeaturesRoadmapMenu: MapMarkerPath, + 'personal-settings': AccountOutline, + 'admin-settings-link': ShieldAccountOutline, +} + +/** + * The note beside a dashboard: default, shared or group. + * + * @param {boolean} isDefault Whether it is the person's default dashboard. + * @param {string} source The dashboard's section. + * @return {string|undefined} + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ +export function dashboardMeta(isDefault, source) { + if (isDefault) { + return t('launchpad', 'default') + } + if (source === 'shared') { + return t('launchpad', 'shared') + } + if (source === 'group') { + return t('launchpad', 'group') + } + return undefined +} + +/** + * The glyph a dashboard row shows: the dashboard's own icon (LpMeer draws + * Today's house, a chart for management information, a megaphone for the + * intranet), else the default dashboard's house or the generic dashboard. + * + * @param {object} dashboard The dashboard. + * @param {boolean} isDefault Whether it opens first. + * @return {object} A component that takes `size`. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ +export function dashboardIcon(dashboard, isDefault) { + const name = typeof dashboard?.icon === 'string' ? dashboard.icon.trim() : '' + if (name === '') { + return markRaw(isDefault ? Home : ViewDashboardOutline) + } + return markRaw({ + name: 'DashboardMenuIcon', + props: { size: { type: Number, default: 18 } }, + /** + * @return {object} The dashboard icon at the menu's size. + */ + render() { + return h(CnDashboardIcon, { name, size: this.size }) + }, + }) +} + +/** + * The Dashboards group: the person's own dashboards, then the shared and + * group ones, at most DASHBOARD_LIMIT, the open one checked, and "All + * dashboards" last. + * + * @param {object} options The dashboards and what choosing one does. + * @param {object[]} options.userDashboards The person's own dashboards. + * @param {object[]} options.groupDashboards The group, default and shared dashboards. + * @param {object[]} options.sharedDashboards Which of those came through a share. + * @param {string|number|null} options.activeId The open dashboard's id. + * @param {string} options.defaultUuid The uuid of the person's default dashboard. + * @param {(id: string|number, source: string) => void} options.onSwitch Open a dashboard. + * @param {() => void} options.onOpenAll Open the full list. + * @return {object[]} The items. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ +export function dashboardItems({ + userDashboards = [], + groupDashboards = [], + sharedDashboards = [], + activeId = null, + defaultUuid = '', + onSwitch, + onOpenAll, +}) { + const items = dashboardRows(userDashboards, groupDashboards, sharedDashboards) + .map(({ d, source }) => { + const isDefault = Boolean(d.uuid) && d.uuid === defaultUuid + return { + id: `dashboard-${d.id}`, + label: d.name || t('launchpad', 'Dashboard'), + icon: dashboardIcon(d, isDefault), + meta: dashboardMeta(isDefault, source), + checked: d.id === activeId, + onClick: () => onSwitch(d.id, source), + } + }) + items.push({ + id: 'all-dashboards', + label: t('launchpad', 'All dashboards'), + icon: markRaw(ViewGridOutline), + onClick: () => onOpenAll(), + }) + return items +} + +/** + * The dashboards the Dashboards group lists, each once with its section: + * the person's own first, then the shared and group ones, at most + * DASHBOARD_LIMIT. + * + * @param {object[]} userDashboards The person's own dashboards. + * @param {object[]} groupDashboards The group, default and shared dashboards. + * @param {object[]} sharedDashboards Which of those came through a share. + * @return {Array<{d: object, source: string}>} The rows. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ +function dashboardRows(userDashboards, groupDashboards, sharedDashboards) { + const shared = new Set(sharedDashboards.map((d) => d?.id)) + const seen = new Set() + return [ + ...userDashboards.map((d) => ({ d, source: 'user' })), + ...groupDashboards.map((d) => ({ d, source: shared.has(d?.id) ? 'shared' : 'group' })), + ] + .filter(({ d }) => { + const known = d && d.id !== undefined && d.id !== null && !seen.has(d.id) + if (known) { + seen.add(d.id) + } + return known + }) + .slice(0, DASHBOARD_LIMIT) +} + +/** + * A destination as a menu item: its link or router target, its action and + * its icon. + * + * @param {object} item The resolved destination. + * @return {object} The menu item. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ +export function destinationItem(item) { + return { + id: item.id, + label: item.label, + icon: DESTINATION_ICONS[item.id] ? markRaw(DESTINATION_ICONS[item.id]) : undefined, + href: item.href, + target: item.href && item.external ? '_blank' : undefined, + to: item.to, + onClick: item.onClick, + } +} + +/** + * The items under Settings, in the board's order: Personal settings, Admin + * settings (administrators only), then the app's own destinations + * (Marketplace, Templates, Reports, Flows, Integrations, Documentation, + * Features and roadmap). + * + * @param {Record<string, object[]>} sections The destinations by section. + * @return {object[]} The items. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ +export function settingsMenuItems(sections) { + return [...settingsItems(sections), ...launchpadItems(sections)].map(destinationItem) +} + +/** + * The This dashboard group, with what the person may do with the open + * dashboard: Edit, Add widget, Share, Copy link to this dashboard, Duplicate + * as new dashboard, Set as default, and Delete last. + * + * @param {object} options The dashboard, the permissions and the handlers. + * @param {object|null} options.dashboard The open dashboard. + * @param {boolean} options.isOwner Whether it is the person's own. + * @param {boolean} options.isDefault Whether it is the person's default. + * @param {boolean} options.isEditMode Whether it is being edited. + * @param {boolean} options.canEdit Whether the person may edit it. + * @param {boolean} options.canShare Whether the person may share it. + * @param {boolean} options.canDuplicate Whether the person may make a personal copy. + * @param {(event: string) => void} options.emit Report the chosen action. + * @return {object[]} The items. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ +export function dashboardActionItems(options) { + if (!options.dashboard) { + return [] + } + return actionRows(options) + .filter((row) => row.offered === true) + .map(({ id, label, icon, event, destructive }) => ({ + id, + label, + icon: markRaw(icon), + onClick: () => options.emit(event), + ...(destructive ? { destructive } : {}), + })) +} + +/** + * Every This dashboard action with whether this person is offered it. + * + * @param {object} options The options of {@link dashboardActionItems}. + * @return {object[]} The rows, in the board's order. + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-013-one-more-menu-the-same-on-every-page + */ +function actionRows(options) { + const editing = options.isEditMode === true + const isDefault = options.isDefault === true + return [ + { offered: options.canEdit, id: 'edit', label: editing ? t('launchpad', 'Save dashboard') : t('launchpad', 'Edit'), icon: editing ? ContentSave : Pencil, event: 'toggleEdit' }, + { offered: options.canEdit, id: 'add-widget', label: t('launchpad', 'Add widget'), icon: Plus, event: 'addWidget' }, + { offered: options.canShare, id: 'share', label: t('launchpad', 'Sharing'), icon: ShareVariant, event: 'share' }, + { offered: true, id: 'copy-link', label: t('launchpad', 'Copy link to this dashboard'), icon: LinkVariant, event: 'copyLink' }, + { offered: options.canDuplicate, id: 'duplicate', label: t('launchpad', 'Duplicate as new dashboard'), icon: ContentCopy, event: 'duplicate' }, + { offered: true, id: 'set-default', label: t('launchpad', 'Set as default'), icon: isDefault ? StarCheck : Star, event: 'setDefault' }, + { offered: options.isOwner, id: 'delete', label: t('launchpad', 'Delete'), icon: TrashCanOutline, event: 'delete', destructive: true }, + ] +} diff --git a/src/components/__tests__/AcknowledgementPrompt.deadline.spec.js b/src/components/__tests__/AcknowledgementPrompt.deadline.spec.js new file mode 100644 index 000000000..ca02100d2 --- /dev/null +++ b/src/components/__tests__/AcknowledgementPrompt.deadline.spec.js @@ -0,0 +1,119 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for AcknowledgementPrompt's fallback prompt text, the + * deadline line and its overdue marker, and the double-submit guard. + */ + +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import AcknowledgementPrompt from '../AcknowledgementPrompt.vue' +import { api } from '../../services/api.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), +})) + +vi.mock('../../services/api.js', () => ({ + api: { + acknowledge: vi.fn(), + getPendingAcknowledgements: vi.fn(), + }, +})) + +const BASE = { + id: 7, + widgetId: 'header', + requiresAcknowledgement: 1, + announcementKey: 'ak-1', + acknowledgementPrompt: '', + acknowledgementContentVersion: 1, + acknowledgementDeadline: null, +} + +/** + * Mount the prompt for a placement. + * + * @param {object} overrides Placement fields to change. + * @return {object} The wrapper. + */ +function mountPrompt(overrides = {}) { + const pinia = createPinia() + setActivePinia(pinia) + return mount(AcknowledgementPrompt, { + global: { plugins: [pinia] }, + props: { placement: { ...BASE, ...overrides } }, + }) +} + +beforeEach(() => { + vi.clearAllMocks() + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-06-15T12:00:00Z')) +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('AcknowledgementPrompt deadline and fallback', () => { + it('falls back to a generic prompt when the author gave no text', () => { + const wrapper = mountPrompt() + + expect( + wrapper.find('[data-testid="acknowledgement-prompt-text"]').text(), + ).toBe('Please confirm you have read this item.') + }) + + it('shows no deadline line without a deadline', () => { + const wrapper = mountPrompt() + + expect(wrapper.vm.isOverdue).toBe(false) + expect( + wrapper.find('[data-testid="acknowledgement-prompt-deadline"]').exists(), + ).toBe(false) + }) + + it('marks a past deadline overdue', () => { + const wrapper = mountPrompt({ acknowledgementDeadline: '2026-06-14' }) + const line = wrapper.find('[data-testid="acknowledgement-prompt-deadline"]') + + expect(wrapper.vm.isOverdue).toBe(true) + expect(line.classes()).toContain('launchpad-ack-prompt__deadline--overdue') + expect(line.text()).toBe('Deadline: {date}') + }) + + it('does not mark a deadline of today or later overdue', () => { + for (const deadline of ['2026-06-15', '2026-07-01']) { + const wrapper = mountPrompt({ acknowledgementDeadline: deadline }) + const line = wrapper.find('[data-testid="acknowledgement-prompt-deadline"]') + + expect(wrapper.vm.isOverdue).toBe(false) + expect(line.classes()).not.toContain( + 'launchpad-ack-prompt__deadline--overdue', + ) + } + }) + + it('ignores a second sign-off while the first is in flight', async () => { + let resolve + api.acknowledge.mockReturnValue(new Promise((r) => { resolve = r })) + const wrapper = mountPrompt() + + const first = wrapper.vm.signOff() + await wrapper.vm.signOff() + resolve({ data: {} }) + await first + + expect(api.acknowledge).toHaveBeenCalledTimes(1) + expect(wrapper.emitted('acknowledged')).toHaveLength(1) + expect(wrapper.vm.submitting).toBe(false) + }) +}) diff --git a/src/components/__tests__/ChoiceCards.spec.js b/src/components/__tests__/ChoiceCards.spec.js new file mode 100644 index 000000000..fc93323e0 --- /dev/null +++ b/src/components/__tests__/ChoiceCards.spec.js @@ -0,0 +1,64 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ChoiceCards: one choice as cards, a radiogroup of native radios. + * + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import ChoiceCards from '../ChoiceCards.vue' + +const options = [ + { value: 'a', label: 'First', hint: 'The first one.' }, + { value: 'b', label: 'Second' }, + { value: 'c', label: 'Third', disabled: true }, +] + +/** + * Mount the cards. + * + * @param {string} modelValue The chosen value. + * @return {object} The wrapper. + */ +function mountCards(modelValue = '') { + return mount(ChoiceCards, { props: { label: 'Kind', name: 'kind', modelValue, options, columns: 3 } }) +} + +describe('ChoiceCards', () => { + it('is a radiogroup named by its label, one radio per card', () => { + const wrapper = mountCards() + const group = wrapper.find('[role="radiogroup"]') + const labelId = group.attributes('aria-labelledby') + expect(wrapper.find(`#${labelId}`).text()).toBe('Kind') + expect(wrapper.findAll('input[type="radio"]').map((i) => i.attributes('name'))).toEqual(['kind', 'kind', 'kind']) + expect(wrapper.find('.choice-cards__grid--3').exists()).toBe(true) + }) + + it('shows each title and its line, marks the chosen card and checks its radio', () => { + const wrapper = mountCards('b') + const cards = wrapper.findAll('.choice-cards__card') + expect(cards[0].text()).toContain('First') + expect(cards[0].find('.choice-cards__hint').text()).toBe('The first one.') + expect(cards[1].find('.choice-cards__hint').exists()).toBe(false) + expect(cards[1].classes()).toContain('choice-cards__card--chosen') + expect(cards[1].find('input').element.checked).toBe(true) + expect(cards[0].find('input').element.checked).toBe(false) + }) + + it('emits the value of the card chosen, and a disabled card cannot be chosen', async () => { + const wrapper = mountCards('a') + await wrapper.find('input[value="b"]').setValue(true) + expect(wrapper.emitted('update:modelValue')).toEqual([['b']]) + + const third = wrapper.find('input[value="c"]') + expect(third.element.disabled).toBe(true) + expect(wrapper.findAll('.choice-cards__card')[2].classes()).toContain('choice-cards__card--disabled') + }) + + it('checks no card when none is chosen', () => { + expect(mountCards('').findAll('input').some((i) => i.element.checked)).toBe(false) + }) +}) diff --git a/src/components/__tests__/ConfirmDialogKeyboard.spec.js b/src/components/__tests__/ConfirmDialogKeyboard.spec.js new file mode 100644 index 000000000..facefc9f0 --- /dev/null +++ b/src/components/__tests__/ConfirmDialogKeyboard.spec.js @@ -0,0 +1,149 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Every confirmation launchpad asks, drawn by the real CnConfirmDialog with + * the texts its host passes: focus moves into the dialog when it opens, and + * Escape closes it without running the action. The + * destructive ones keep their red (error) confirm button. + */ + +// The suite aliases the package root to a stub, so the real dialog is loaded from the ESM build. +import CnConfirmDialog from '@conduction/nextcloud-vue/dist/esm/dialogs/CnConfirmDialog.vue.js' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, describe, expect, it } from 'vitest' + +const CONFIRMATIONS = { + 'take over a lock': { + dialogTitle: 'Take over editing?', + message: + 'A colleague can no longer save changes to this dashboard. Take over only when you know they have stopped.', + confirmLabel: 'Take over', + }, + 'restore a version': { + dialogTitle: 'Restore this version?', + message: + 'The dashboard goes back to how it was on Oct 30, 2026. How it looks now is saved as a version first, so you can undo this.', + confirmLabel: 'Restore', + }, + 'reset a personal view': { + dialogTitle: 'Reset your view?', + message: + 'Every widget you hid comes back, and the dashboard looks the way its owner set it up.', + confirmLabel: 'Reset my view', + }, + 'revoke a kiosk playlist': { + dialogTitle: 'Revoke this playlist?', + message: + 'Screens showing Lobby stop at their next check, and the link stops working for good.', + confirmLabel: 'Revoke', + variant: 'error', + }, + 'remove a demo showcase': { + dialogTitle: 'Remove showcase dashboard', + message: + 'Remove the School showcase dashboard for all users? You can reinstall it later.', + confirmLabel: 'Remove', + variant: 'error', + }, + 'delete a role permission': { + dialogTitle: 'Delete role permission', + message: 'Delete role permission for group "finance"?', + confirmLabel: 'Delete', + variant: 'error', + }, + 'delete a role layout default': { + dialogTitle: 'Delete layout default', + message: 'Delete layout default for "hr" / "news"?', + confirmLabel: 'Delete', + variant: 'error', + }, + 'delete a group dashboard': { + dialogTitle: 'Delete dashboard', + message: 'Delete this dashboard? This cannot be undone.', + confirmLabel: 'Delete', + variant: 'error', + }, +} + +let wrapper = null + +// jsdom has no layout: tabbable takes an element without client rects for hidden, +// and the dialog's focus trap would find nothing to focus. An element under +// `display: none` keeps no rects, as in a browser, because jsdom refuses to focus it. +Element.prototype.getClientRects = function () { + for (let node = this; node instanceof Element; node = node.parentElement) { + if (getComputedStyle(node).display === 'none') { + return [] + } + } + return [{ width: 10, height: 10, top: 0, left: 0, bottom: 10, right: 10 }] +} + +afterEach(() => { + wrapper?.unmount() + wrapper = null + document.body.innerHTML = '' +}) + +/** + * Wait until the dialog has opened and its focus trap has moved focus. + * + * @return {Promise<void>} + */ +async function settle() { + for (let i = 0; i < 10; i++) { + await flushPromises() + await new Promise((resolve) => setTimeout(resolve, 20)) + } +} + +describe.each(Object.entries(CONFIRMATIONS))( + 'the confirmation to %s', + (_name, props) => { + it('shows its texts and moves focus into the dialog', async () => { + wrapper = mount(CnConfirmDialog, { + props, + attachTo: document.body, + // The focus trap starts after the enter transition, which a stub never ends. + global: { stubs: { transition: false } }, + }) + await settle() + const dialog = document.querySelector('[role="dialog"]') + expect(dialog).not.toBeNull() + expect(dialog.textContent).toContain(props.dialogTitle) + expect(dialog.textContent).toContain(props.message) + expect(dialog.textContent).toContain(props.confirmLabel) + expect(dialog.contains(document.activeElement)).toBe(true) + const confirm = dialog.querySelector( + '[data-testid="cn-confirm-dialog-confirm"]', + ) + expect(confirm.className).toContain( + `button-vue--${props.variant ?? 'primary'}`, + ) + }) + + it('closes on Escape without confirming', async () => { + wrapper = mount(CnConfirmDialog, { + props, + attachTo: document.body, + // The focus trap starts after the enter transition, which a stub never ends. + global: { stubs: { transition: false } }, + }) + await settle() + expect( + document + .querySelector('[role="dialog"]') + .contains(document.activeElement), + ).toBe(true) + document.activeElement.dispatchEvent( + new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }), + ) + await settle() + // The dialog closes after its 300 ms leave animation. + await new Promise((resolve) => setTimeout(resolve, 400)) + expect(wrapper.emitted('close')).toBeTruthy() + expect(wrapper.emitted('confirm')).toBeUndefined() + }) + }, +) diff --git a/src/components/__tests__/DashboardFooter.edges.spec.js b/src/components/__tests__/DashboardFooter.edges.spec.js new file mode 100644 index 000000000..f1b3af035 --- /dev/null +++ b/src/components/__tests__/DashboardFooter.edges.spec.js @@ -0,0 +1,111 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the DashboardFooter resolution edges the main spec + * leaves out: non-string html, empty and non-object config, locale maps on + * config leaves, address splitting, the links/legal switch and the variant + * picker's fallbacks. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import DashboardFooter from '../DashboardFooter.vue' + +/** + * Mount the footer with the given payload. + * + * @param {object|null} footer The footer payload. + * @param {string} locale The viewer locale. + * @return {object} The wrapper. + */ +function mountFooter(footer, locale = 'en') { + return mount(DashboardFooter, { props: { footer, locale } }) +} + +describe('DashboardFooter edges', () => { + it('treats a non-string, non-object html as absent', () => { + const wrapper = mountFooter({ html: 42, config: null }) + + expect(wrapper.vm.resolvedHtml).toBeNull() + expect(wrapper.vm.showFooter).toBe(false) + }) + + it('treats a non-object or empty config as absent', () => { + expect(mountFooter({ html: null, config: 'x' }).vm.resolvedConfig).toBeNull() + expect(mountFooter({ html: null, config: {} }).vm.resolvedConfig).toBeNull() + }) + + it('with no config, defaults the derived fields', () => { + const vm = mountFooter({ html: '<p>x</p>', config: null }).vm + + expect(vm.layoutMode).toBe('columns') + expect(vm.orgName).toBe('') + expect(vm.addressLines).toEqual([]) + expect(vm.legalText).toBe('') + expect(vm.hasLinksOrLegal).toBe(false) + }) + + it('picks the locale on plain locale-map leaves and keeps link objects and arrays', () => { + const link = { label: 'Home', url: '/' } + const vm = mountFooter( + { + html: null, + config: { + organisation: { nl: 'Gemeente', en: 'Municipality' }, + link, + links: [link], + layoutMode: 'inline', + }, + }, + 'nl', + ).vm + + expect(vm.resolvedConfig).toEqual({ + organisation: 'Gemeente', + link, + links: [link], + layoutMode: 'inline', + }) + expect(vm.orgName).toBe('Gemeente') + expect(vm.layoutMode).toBe('inline') + }) + + it('treats an unknown layout mode as columns', () => { + const vm = mountFooter({ html: null, config: { layoutMode: 'grid' } }).vm + + expect(vm.layoutMode).toBe('columns') + }) + + it('splits the address into trimmed, non-empty lines', () => { + const vm = mountFooter({ + html: null, + config: { address: ' Street 1 \n\n 1234 AB City \n ' }, + }).vm + + expect(vm.addressLines).toEqual(['Street 1', '1234 AB City']) + }) + + it('hasLinksOrLegal is true for links, legal text or a copyright year alone', () => { + expect(mountFooter({ config: { links: [{ label: 'a' }] } }).vm.hasLinksOrLegal).toBe(true) + expect(mountFooter({ config: { legal: 'KvK 1' } }).vm.hasLinksOrLegal).toBe(true) + expect(mountFooter({ config: { copyrightYear: 2026 } }).vm.hasLinksOrLegal).toBe(true) + expect(mountFooter({ config: { links: [], organisation: 'X' } }).vm.hasLinksOrLegal).toBe(false) + }) + + it('pickVariant returns an empty string for a non-object or empty map', () => { + const vm = mountFooter(null).vm + + expect(vm.pickVariant(null)).toBe('') + expect(vm.pickVariant('nl')).toBe('') + expect(vm.pickVariant({})).toBe('') + expect(vm.pickVariant({ de: 'Hallo' })).toBe('Hallo') + }) + + it('applies only the colours that are set', () => { + expect(mountFooter({ html: 'x', textColor: '#111' }).vm.footerStyle).toEqual({ + color: '#111', + }) + expect(mountFooter(null).vm.footerStyle).toEqual({}) + }) +}) diff --git a/src/components/__tests__/DashboardFooter.spec.js b/src/components/__tests__/DashboardFooter.spec.js index ff7200c4f..4f0ac2185 100644 --- a/src/components/__tests__/DashboardFooter.spec.js +++ b/src/components/__tests__/DashboardFooter.spec.js @@ -109,6 +109,35 @@ describe('DashboardFooter', () => { expect(wrapper.html()).toContain('Bonjour') }) + it('falls back to the dashboard primary language before the first key (REQ-FTR-007)', () => { + const wrapper = mount(DashboardFooter, { + propsData: { + footer: { + mode: 'global', + html: { en: '<p>English</p>', fr: '<p>Français</p>' }, + config: null, + primaryLanguage: 'fr', + }, + locale: 'de', + }, + }) + expect(wrapper.html()).toContain('Français') + }) + + it('matches the language part of a regional locale (REQ-FTR-007)', () => { + const wrapper = mount(DashboardFooter, { + propsData: { + footer: { + mode: 'global', + html: { en: '<p>English</p>', nl: '<p>Welkom</p>' }, + config: null, + }, + locale: 'nl_BE', + }, + }) + expect(wrapper.html()).toContain('Welkom') + }) + it('applies admin colour overrides as inline style (REQ-FTR-009)', () => { const wrapper = mount(DashboardFooter, { propsData: { diff --git a/src/components/__tests__/HeaderSearchDropdown.spec.js b/src/components/__tests__/HeaderSearchDropdown.spec.js new file mode 100644 index 000000000..2be3584d3 --- /dev/null +++ b/src/components/__tests__/HeaderSearchDropdown.spec.js @@ -0,0 +1,245 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Unit tests for `HeaderSearchDropdown.vue` (header-search-dropdown, + * REQ-SRCH-013): the list under the core search field, its grouping and + * detail lines, the combobox keyboard, Escape, the shortcut tip, the + * "Show all results" hand-off, and that thematiq's field words stay. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const searchAll = vi.fn() +vi.mock('../../services/headerSearch.js', async (importOriginal) => ({ + ...(await importOriginal()), + searchAll: (...args) => searchAll(...args), +})) +const performFallback = vi.fn() +vi.mock('../../composables/useTileSearchHost.js', () => ({ + performFallback: (...args) => performFallback(...args), +})) +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), +})) + +const { default: HeaderSearchDropdown } = await import('../HeaderSearchDropdown.vue') + +const GROUPS = [ + { + id: 'launchpad', + name: 'Dashboards', + results: [ + { key: 'launchpad-0', title: 'Permits team', detail: 'Shared by Marieke Jansen · 14 widgets', icon: '/i.svg', url: '/apps/launchpad/#dashboard/permits' }, + { key: 'launchpad-1', title: 'Zuiddrecht intranet', detail: 'Group dashboard of Communications', icon: '', url: '/apps/launchpad/#dashboard/intranet' }, + ], + }, +] + +describe('HeaderSearchDropdown', () => { + let field + let wrapper + let assign + + beforeEach(() => { + vi.useFakeTimers() + searchAll.mockReset().mockResolvedValue(GROUPS) + performFallback.mockReset() + field = document.createElement('input') + field.className = 'unified-search-input' + field.placeholder = 'Zoek in Zuiddrecht' + document.body.appendChild(field) + assign = vi.fn() + vi.stubGlobal('location', { ...window.location, assign, pathname: '/apps/launchpad/' }) + }) + + afterEach(() => { + wrapper?.unmount() + wrapper = null + field.remove() + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + /** + * Mount, type the query and let the debounce and the search settle. + * + * @param {string} query What to type. + * @param {object} [props] Props. + */ + async function typeQuery(query, props = {}) { + wrapper = mount(HeaderSearchDropdown, { props, attachTo: document.body }) + field.value = query + field.dispatchEvent(new Event('input')) + await vi.advanceTimersByTimeAsync(300) + await flushPromises() + } + + /** + * Press a key on the field. + * + * @param {string} key The key. + */ + async function press(key) { + field.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })) + await flushPromises() + } + + const panel = () => document.querySelector('[data-testid="header-search-dropdown"]') + const selected = () => document.querySelector('[role="option"][aria-selected="true"]') + + it('makes the core field a combobox without touching its words', () => { + wrapper = mount(HeaderSearchDropdown, { attachTo: document.body }) + expect(field.getAttribute('role')).toBe('combobox') + expect(field.getAttribute('aria-expanded')).toBe('false') + expect(field.getAttribute('aria-controls')).toMatch(/^lp-header-search-/) + expect(field.placeholder).toBe('Zoek in Zuiddrecht') + }) + + it('stays closed under two characters', async () => { + await typeQuery('t') + expect(searchAll).not.toHaveBeenCalled() + expect(panel()).toBeNull() + }) + + it('opens under the field with the query, the group and the detail lines, first result selected', async () => { + await typeQuery('team') + expect(searchAll).toHaveBeenCalledWith('team', expect.any(Object)) + expect(panel().querySelector('[data-testid="header-search-query"]').textContent.trim()).toBe('You searched for team') + expect(panel().querySelector('[data-testid="header-search-group"]').textContent.trim()).toBe('DASHBOARDS') + const options = [...panel().querySelectorAll('[data-testid="header-search-option"]')] + expect(options.map((o) => [ + o.querySelector('.lp-header-search__title').textContent, + o.querySelector('.lp-header-search__detail').textContent, + ])).toEqual([ + ['Permits team', 'Shared by Marieke Jansen · 14 widgets'], + ['Zuiddrecht intranet', 'Group dashboard of Communications'], + ]) + expect(panel().querySelector('[role="listbox"]')).not.toBeNull() + expect(selected().textContent).toContain('Permits team') + expect(field.getAttribute('aria-expanded')).toBe('true') + expect(field.getAttribute('aria-activedescendant')).toBe(selected().id) + expect(field.value).toBe('team') + }) + + it('Arrow down then Enter opens the next result', async () => { + await typeQuery('team') + await press('ArrowDown') + expect(selected().textContent).toContain('Zuiddrecht intranet') + await press('Enter') + expect(assign).toHaveBeenCalledWith('/apps/launchpad/#dashboard/intranet') + expect(panel()).toBeNull() + }) + + it('Arrow up from the first result wraps to "Show all results", which hands the query to Nextcloud', async () => { + await typeQuery('team') + await press('ArrowUp') + expect(selected().getAttribute('data-testid')).toBe('header-search-show-all') + await press('Enter') + expect(performFallback).toHaveBeenCalledWith({ type: 'unified-search', query: 'team' }) + }) + + it('Escape closes the list and keeps the query and the focus', async () => { + await typeQuery('team') + field.focus() + await press('Escape') + expect(panel()).toBeNull() + expect(field.value).toBe('team') + expect(document.activeElement).toBe(field) + expect(field.getAttribute('aria-expanded')).toBe('false') + expect(field.hasAttribute('aria-activedescendant')).toBe(false) + }) + + it('ends with the tip of the first shortcut', async () => { + await typeQuery('team', { shortcuts: [{ prefix: '!top', name: 'TOPdesk', urlTemplate: 'https://t/{query}' }] }) + expect(panel().querySelector('[data-testid="header-search-tip"]').textContent.trim()) + .toBe('Tip: type !top to search TOPdesk directly') + }) + + it('shows no tip without shortcuts', async () => { + await typeQuery('team') + expect(panel().querySelector('[data-testid="header-search-tip"]')).toBeNull() + }) + + it('attaches once the top bar renders the field later', async () => { + field.remove() + wrapper = mount(HeaderSearchDropdown, { attachTo: document.body }) + document.body.appendChild(field) + await flushPromises() + await vi.advanceTimersByTimeAsync(0) + expect(field.getAttribute('role')).toBe('combobox') + }) + + it('lets go of the field on unmount', async () => { + await typeQuery('team') + wrapper.unmount() + wrapper = null + expect(field.getAttribute('aria-expanded')).toBe('false') + field.value = 'other' + field.dispatchEvent(new Event('input')) + await vi.advanceTimersByTimeAsync(300) + expect(searchAll).toHaveBeenCalledTimes(1) + }) + + describe('on Nextcloud 31+, where the top bar has only a button', () => { + let host + let label + + beforeEach(() => { + field.remove() + host = document.createElement('search') + host.className = 'unified-search-input' + const button = document.createElement('button') + button.className = 'unified-search-input__button' + label = document.createElement('span') + label.className = 'unified-search-input__label' + label.textContent = 'Search apps, files, tags, messages' + button.appendChild(label) + host.appendChild(button) + document.body.appendChild(host) + }) + + afterEach(() => { + host.remove() + }) + + const ownField = () => host.querySelector('[data-testid="header-search-field"]') + + it('places its own field there, a combobox with the button\'s words, and never decorates the landmark', () => { + wrapper = mount(HeaderSearchDropdown, { attachTo: document.body }) + expect(ownField()).not.toBeNull() + expect(ownField().getAttribute('role')).toBe('combobox') + expect(ownField().placeholder).toBe('Search apps, files, tags, messages') + expect(host.getAttribute('role')).toBeNull() + }) + + it('searches what is typed in that field', async () => { + wrapper = mount(HeaderSearchDropdown, { attachTo: document.body }) + ownField().value = 'team' + ownField().dispatchEvent(new Event('input')) + await vi.advanceTimersByTimeAsync(300) + await flushPromises() + expect(searchAll).toHaveBeenCalledWith('team', expect.any(Object)) + expect(panel()).not.toBeNull() + }) + + it('follows words thematiq writes into the button later', async () => { + wrapper = mount(HeaderSearchDropdown, { attachTo: document.body }) + label.textContent = 'Zoek in Zuiddrecht' + await flushPromises() + expect(ownField().placeholder).toBe('Zoek in Zuiddrecht') + expect(ownField().getAttribute('aria-label')).toBe('Zoek in Zuiddrecht') + }) + + it('takes its field out again on unmount', () => { + wrapper = mount(HeaderSearchDropdown, { attachTo: document.body }) + wrapper.unmount() + wrapper = null + expect(ownField()).toBeNull() + expect(host.classList.contains('lp-header-search-host')).toBe(false) + }) + }) +}) diff --git a/src/components/__tests__/HealthPingBadge.reading.spec.js b/src/components/__tests__/HealthPingBadge.reading.spec.js new file mode 100644 index 000000000..d9fdb2411 --- /dev/null +++ b/src/components/__tests__/HealthPingBadge.reading.spec.js @@ -0,0 +1,53 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The badge tells its tile the reading, so an icon-only tile can show the + * outage as a dot (icon-only-app-tiles REQ-ICT-003). + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-an-outage-req-ict-003 + */ +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import HealthPingBadge from '../HealthPingBadge.vue' +import { fetchHealthPingBadge } from '../../services/healthPingClient.js' + +vi.mock('../../services/healthPingClient.js', () => ({ + fetchHealthPingBadge: vi.fn(), +})) + +async function flush() { + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +beforeEach(() => { + fetchHealthPingBadge.mockReset() +}) + +describe('HealthPingBadge reading', () => { + it('reports an offline reading with since when, and draws nothing when hidden', async () => { + fetchHealthPingBadge.mockResolvedValue({ state: 'offline', checkedAt: '2026-11-25T09:20:00Z', latencyMs: null, stale: false, downSince: '2026-11-25T09:12:00Z' }) + const wrapper = mount(HealthPingBadge, { props: { placementId: 4, interval: 60, hidden: true } }) + await flush() + expect(wrapper.emitted('reading').at(-1)).toEqual([{ state: 'offline', downSince: '2026-11-25T09:12:00Z' }]) + expect(wrapper.find('.health-ping-badge').exists()).toBe(false) + wrapper.unmount() + }) + + it('reports no outage time for an online service, and draws the badge when not hidden', async () => { + fetchHealthPingBadge.mockResolvedValue({ state: 'online', checkedAt: '2026-11-25T09:20:00Z', latencyMs: 40, stale: false, downSince: null }) + const wrapper = mount(HealthPingBadge, { props: { placementId: 4, interval: 60 } }) + await flush() + expect(wrapper.emitted('reading').at(-1)).toEqual([{ state: 'online', downSince: null }]) + expect(wrapper.find('.health-ping-badge').exists()).toBe(true) + wrapper.unmount() + }) + + it('reports no state when the badge cannot be read', async () => { + fetchHealthPingBadge.mockRejectedValue(new Error('403')) + const wrapper = mount(HealthPingBadge, { props: { placementId: 4, interval: 60 } }) + await flush() + expect(wrapper.emitted('reading').at(-1)).toEqual([{ state: null, downSince: null }]) + wrapper.unmount() + }) +}) diff --git a/src/components/__tests__/HealthPingBadge.states.spec.js b/src/components/__tests__/HealthPingBadge.states.spec.js new file mode 100644 index 000000000..5b9467da1 --- /dev/null +++ b/src/components/__tests__/HealthPingBadge.states.spec.js @@ -0,0 +1,95 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `HealthPingBadge.vue` state edges: unknown and + * error answers, the tooltip without latency or check time, and that the + * poll stops on unmount. The browser client is mocked. + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import HealthPingBadge from '../HealthPingBadge.vue' +import { fetchHealthPingBadge } from '../../services/healthPingClient.js' + +vi.mock('../../services/healthPingClient.js', () => ({ + fetchHealthPingBadge: vi.fn(), +})) + +async function flushPromises() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +beforeEach(() => { + globalThis.t = (_app, key, vars) => + vars ? key.replace(/\{(\w+)\}/g, (_, name) => (Object.hasOwn(vars, name) ? vars[name] : `{${name}}`)) : key + fetchHealthPingBadge.mockReset() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('HealthPingBadge — answers that hide the badge', () => { + it('clears to hidden on an error answer, an empty answer or no state', async () => { + for (const answer of [{ error: 'forbidden', state: 'online' }, null, { checkedAt: 'x' }]) { + fetchHealthPingBadge.mockResolvedValueOnce(answer) + const wrapper = mount(HealthPingBadge, { propsData: { placementId: 1, interval: 60 } }) + await flushPromises() + expect(wrapper.vm.state).toBe(null) + expect(wrapper.vm.badgeClass).toBe('') + expect(wrapper.vm.tooltipText).toBe('') + wrapper.destroy?.() + wrapper.unmount?.() + } + }) + + it('labels an unknown state as nothing but keeps a class for it', async () => { + fetchHealthPingBadge.mockResolvedValueOnce({ state: 'maintenance', latencyMs: '12' }) + const wrapper = mount(HealthPingBadge, { propsData: { placementId: 1, interval: 60 } }) + await flushPromises() + expect(wrapper.vm.stateLabel).toBe('') + expect(wrapper.vm.badgeClass).toBe('health-ping-badge--maintenance') + expect(wrapper.vm.latencyMs).toBe(12) + expect(wrapper.vm.stateIcon).toBeTruthy() + }) +}) + +describe('HealthPingBadge — tooltip', () => { + it('says never checked and leaves out latency when the server has none', async () => { + fetchHealthPingBadge.mockResolvedValueOnce({ state: 'degraded', latencyMs: null, stale: 1 }) + const wrapper = mount(HealthPingBadge, { propsData: { placementId: 1, interval: 60 } }) + await flushPromises() + expect(wrapper.vm.checkedAt).toBe(null) + expect(wrapper.vm.latencyMs).toBe(null) + expect(wrapper.vm.stale).toBe(true) + expect(wrapper.vm.tooltipText).toBe('Degraded — checked never (last known)') + }) + + it('drops the last-known suffix when the answer is fresh', async () => { + fetchHealthPingBadge.mockResolvedValueOnce({ state: 'offline' }) + const wrapper = mount(HealthPingBadge, { propsData: { placementId: 1, interval: 60 } }) + await flushPromises() + expect(wrapper.vm.tooltipText).toBe('Offline — checked never') + }) +}) + +describe('HealthPingBadge — polling lifecycle', () => { + it('stops polling when unmounted and stopping twice is harmless', async () => { + vi.useFakeTimers() + fetchHealthPingBadge.mockResolvedValue({ state: 'online' }) + const wrapper = mount(HealthPingBadge, { propsData: { placementId: 5, interval: 15 } }) + expect(fetchHealthPingBadge).toHaveBeenCalledTimes(1) + expect(wrapper.vm.pollHandle).not.toBe(null) + if (wrapper.unmount) { + wrapper.unmount() + } else { + wrapper.destroy() + } + expect(wrapper.vm.pollHandle).toBe(null) + wrapper.vm.stopPolling() + vi.advanceTimersByTime(60000) + expect(fetchHealthPingBadge).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/components/__tests__/LazyMount.spec.js b/src/components/__tests__/LazyMount.spec.js new file mode 100644 index 000000000..c36ff8786 --- /dev/null +++ b/src/components/__tests__/LazyMount.spec.js @@ -0,0 +1,201 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest tests for `LazyMount.vue` and the widget wrapper's use of it + * (widgets REQ-WDG-044): a widget's content below the fold mounts when it + * comes into view, once the page has settled, or before printing; at once + * when eager or without IntersectionObserver; and stays mounted. + * + * @spec openspec/changes/archive/2026-11-25-widgets-below-the-fold-load-on-view/specs/widgets/spec.md#requirement-a-widget-below-the-fold-loads-when-it-comes-into-view-req-wdg-044 + */ + +import { mount, shallowMount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import LazyMount, { + IDLE_TIMEOUT_MS, + LazyMountSupport, + ROOT_MARGIN, + SETTLE_DELAY_MS, +} from '../LazyMount.vue' +import WidgetWrapper, { isExportRender } from '../WidgetWrapper.vue' + +/** A stand-in IntersectionObserver whose instances the test drives. */ +class FakeObserver { + static instances = [] + + constructor(callback, options) { + this.callback = callback + this.options = options + this.observed = [] + this.disconnected = false + FakeObserver.instances.push(this) + } + + observe(el) { + this.observed.push(el) + } + + disconnect() { + this.disconnected = true + } + + fire(isIntersecting) { + this.callback([{ isIntersecting }]) + } +} + +function mountLazy(props = {}) { + return mount(LazyMount, { + props, + slots: { default: () => h('p', { class: 'content' }, 'content') }, + }) +} + +beforeEach(() => { + FakeObserver.instances = [] + globalThis.t = (_app, key) => key +}) + +afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() +}) + +describe('LazyMount', () => { + it('mounts at once without IntersectionObserver', () => { + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(null) + const wrapper = mountLazy() + expect(wrapper.find('.content').exists()).toBe(true) + }) + + it('mounts at once when eager, without watching', () => { + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(FakeObserver) + const wrapper = mountLazy({ eager: true }) + expect(wrapper.find('.content').exists()).toBe(true) + expect(FakeObserver.instances).toHaveLength(0) + }) + + it('waits until the element comes within one viewport height', async () => { + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(FakeObserver) + const wrapper = mountLazy() + expect(wrapper.find('.content').exists()).toBe(false) + expect(wrapper.attributes('data-mounted')).toBe('false') + + const observer = FakeObserver.instances[0] + expect(observer.options).toEqual({ rootMargin: ROOT_MARGIN }) + expect(observer.observed).toEqual([wrapper.element]) + + observer.fire(false) + await wrapper.vm.$nextTick() + expect(wrapper.find('.content').exists()).toBe(false) + + observer.fire(true) + await wrapper.vm.$nextTick() + expect(wrapper.find('.content').exists()).toBe(true) + expect(observer.disconnected).toBe(true) + }) + + it('stays mounted once shown', async () => { + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(FakeObserver) + const wrapper = mountLazy() + FakeObserver.instances[0].fire(true) + await wrapper.vm.$nextTick() + FakeObserver.instances[0].fire(false) + await wrapper.setProps({ eager: false }) + expect(wrapper.find('.content').exists()).toBe(true) + }) + + it('mounts once the page has settled, at the next idle moment', async () => { + vi.useFakeTimers() + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(FakeObserver) + const idle = vi.fn((cb) => { + setTimeout(cb, 0) + return 7 + }) + window.requestIdleCallback = idle + window.cancelIdleCallback = vi.fn() + const wrapper = mountLazy() + + vi.advanceTimersByTime(SETTLE_DELAY_MS - 1) + await wrapper.vm.$nextTick() + expect(idle).not.toHaveBeenCalled() + expect(wrapper.find('.content').exists()).toBe(false) + + vi.advanceTimersByTime(1) + expect(idle).toHaveBeenCalledWith(expect.any(Function), { timeout: IDLE_TIMEOUT_MS }) + vi.advanceTimersByTime(1) + await wrapper.vm.$nextTick() + expect(wrapper.find('.content').exists()).toBe(true) + delete window.requestIdleCallback + delete window.cancelIdleCallback + }) + + it('mounts once the page has settled without requestIdleCallback', async () => { + vi.useFakeTimers() + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(FakeObserver) + const wrapper = mountLazy() + vi.advanceTimersByTime(SETTLE_DELAY_MS) + await wrapper.vm.$nextTick() + expect(wrapper.find('.content').exists()).toBe(true) + }) + + it('mounts before the page prints', async () => { + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(FakeObserver) + const wrapper = mountLazy() + window.dispatchEvent(new Event('beforeprint')) + await wrapper.vm.$nextTick() + expect(wrapper.find('.content').exists()).toBe(true) + }) + + it('mounts when it becomes eager', async () => { + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(FakeObserver) + const wrapper = mountLazy() + await wrapper.setProps({ eager: true }) + expect(wrapper.find('.content').exists()).toBe(true) + expect(FakeObserver.instances[0].disconnected).toBe(true) + }) + + it('stops watching when unmounted', () => { + vi.useFakeTimers() + vi.spyOn(LazyMountSupport, 'observer').mockReturnValue(FakeObserver) + const remove = vi.spyOn(window, 'removeEventListener') + const wrapper = mountLazy() + wrapper.unmount() + expect(FakeObserver.instances[0].disconnected).toBe(true) + expect(remove).toHaveBeenCalledWith('beforeprint', expect.any(Function)) + expect(vi.getTimerCount()).toBe(0) + }) +}) + +describe('WidgetWrapper mounts its content through LazyMount', () => { + function mountWrapper(editMode) { + return shallowMount(WidgetWrapper, { + propsData: { + placement: { id: 1, widgetId: 'data', showTitle: true }, + widget: { title: 'Widget' }, + editMode, + }, + mocks: { t: (_app, key) => key }, + global: { stubs: { CnWidgetWrapper: { template: '<div><slot /></div>' } } }, + }) + } + + it('defers in view mode', () => { + const lazy = mountWrapper(false).findComponent(LazyMount) + expect(lazy.exists()).toBe(true) + expect(lazy.props('eager')).toBe(false) + }) + + it('mounts at once in edit mode', () => { + expect(mountWrapper(true).findComponent(LazyMount).props('eager')).toBe(true) + }) + + it('knows the headless export render by ?export=1', () => { + expect(isExportRender({ search: '?export=1&subject=dashboard&id=4' })).toBe(true) + expect(isExportRender({ search: '?export=0' })).toBe(false) + expect(isExportRender({ search: '' })).toBe(false) + expect(isExportRender(null)).toBe(false) + }) +}) diff --git a/src/components/__tests__/OrgNavigationItem.spec.js b/src/components/__tests__/OrgNavigationItem.spec.js new file mode 100644 index 000000000..9e1ffbf30 --- /dev/null +++ b/src/components/__tests__/OrgNavigationItem.spec.js @@ -0,0 +1,166 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the interactive parts of `OrgNavigationItem.vue`: + * the disclosure toggle and its label, the section-header toggle, the + * navigate event (also bubbled from a child), indentation, deep + * auto-expansion and the URL boundary rules (REQ-ONAV-005, REQ-ONAV-009). + * Rendering of links, icons and the basic active match is pinned in + * OrgNavigationPanel.spec.js. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import OrgNavigationItem from '../OrgNavigationItem.vue' + +/** + * A translation stub that fills in the placeholders, so labels are asserted as rendered. + * + * @param {string} _app The app id. + * @param {string} text The source text. + * @param {object} [vars] The placeholder values. + * @return {string} the text with its placeholders filled in. + */ +function translate(_app, text, vars = {}) { + return text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? '') +} + +/** + * Mount one item. + * + * @param {object} node The tree node. + * @param {object} [props] Further props. + * @return {object} the wrapper. + */ +function mountItem(node, props = {}) { + return mount(OrgNavigationItem, { + props: { node, level: 1, currentUrl: '', ...props }, + global: { mocks: { t: translate } }, + }) +} + +const section = { + id: 's', + label: 'Section', + url: null, + icon: 'star', + children: [ + { id: 'c1', label: 'Child one', url: '/one', children: [] }, + { id: 'c2', label: 'Child two', url: '/two', children: [] }, + ], +} + +describe('OrgNavigationItem disclosure', () => { + it('expands and collapses its children from the toggle, with a matching label', async () => { + const wrapper = mountItem(section) + const toggle = wrapper.find('.org-nav-item__toggle') + + expect(toggle.element.tagName).toBe('BUTTON') + expect(toggle.attributes('aria-label')).toBe('Expand Section') + expect(toggle.text()).toBe('▸') + expect(wrapper.attributes('aria-expanded')).toBe('false') + expect(wrapper.find('.org-nav-item__children').exists()).toBe(false) + + await toggle.trigger('click') + expect(toggle.attributes('aria-label')).toBe('Collapse Section') + expect(toggle.text()).toBe('▾') + expect(wrapper.attributes('aria-expanded')).toBe('true') + expect(wrapper.findAll('.org-nav-item__children > li').map((li) => li.text())).toEqual(['Child one', 'Child two']) + + await toggle.trigger('click') + expect(wrapper.find('.org-nav-item__children').exists()).toBe(false) + }) + + it('toggles from the section header button too, which carries the icon', async () => { + const wrapper = mountItem(section) + const header = wrapper.find('.org-nav-item__row--section') + + expect(header.find('.org-nav-item__icon').exists()).toBe(true) + await header.trigger('click') + expect(wrapper.vm.expanded).toBe(true) + }) + + it('has a placeholder instead of a toggle, and no aria-expanded, without children', async () => { + const wrapper = mountItem({ id: 'e', label: 'Empty', url: null, children: [] }) + + expect(wrapper.find('button.org-nav-item__toggle').exists()).toBe(false) + expect(wrapper.find('.org-nav-item__toggle--placeholder').exists()).toBe(true) + expect(wrapper.attributes('aria-expanded')).toBeUndefined() + expect(wrapper.classes()).toContain('org-nav-item--section') + + await wrapper.find('.org-nav-item__row--section').trigger('click') + expect(wrapper.vm.expanded).toBe(false) + }) +}) + +describe('OrgNavigationItem navigation', () => { + it('emits navigate when its link is activated, and bubbles a child\'s', async () => { + const link = mountItem({ id: 'l', label: 'Link', url: '/link', children: [] }) + await link.find('a').trigger('click') + expect(link.emitted('navigate')).toHaveLength(1) + expect(link.find('a').attributes('target')).toBeUndefined() + expect(link.find('a').attributes('rel')).toBeUndefined() + + const parent = mountItem(section) + await parent.find('.org-nav-item__toggle').trigger('click') + await parent.findAll('.org-nav-item__children a')[1].trigger('click') + expect(parent.emitted('navigate')).toHaveLength(1) + }) + + it('indents 12px per level beyond the root, and passes the next level to children', async () => { + expect(mountItem(section).find('.org-nav-item__indent').attributes('style')).toContain('padding-left: 0px') + + const nested = mountItem(section, { level: 3 }) + expect(nested.find('.org-nav-item__indent').attributes('style')).toContain('padding-left: 24px') + await nested.find('.org-nav-item__toggle').trigger('click') + expect(nested.findAllComponents(OrgNavigationItem)[1].props('level')).toBe(4) + }) +}) + +describe('OrgNavigationItem active detection', () => { + it('auto-expands for an active grandchild and marks the active descendant', () => { + const tree = { + id: 'root', + label: 'Root', + url: null, + children: [ + { id: 'mid', label: 'Mid', url: null, children: [{ id: 'leaf', label: 'Leaf', url: '/deep', children: [] }] }, + ], + } + const wrapper = mountItem(tree, { currentUrl: '/deep' }) + + expect(wrapper.vm.expanded).toBe(true) + expect(wrapper.classes()).toContain('org-nav-item--has-active-child') + expect(wrapper.classes()).not.toContain('org-nav-item--active') + }) + + it('opens when a descendant becomes active after mounting (REQ-ONAV-009)', async () => { + const wrapper = mountItem(section, { currentUrl: '/elsewhere' }) + expect(wrapper.vm.expanded).toBe(false) + + await wrapper.setProps({ currentUrl: '/two' }) + + expect(wrapper.vm.expanded).toBe(true) + expect(wrapper.attributes('aria-expanded')).toBe('true') + }) + + it('stays collapsed when no descendant is active', () => { + const wrapper = mountItem(section, { currentUrl: '/elsewhere' }) + + expect(wrapper.vm.expanded).toBe(false) + expect(wrapper.classes()).not.toContain('org-nav-item--has-active-child') + }) + + it('matches a prefix only up to a path, query or fragment boundary', () => { + const active = (currentUrl) => mountItem({ id: 'h', label: 'Hub', url: '/hub', children: [] }, { currentUrl }).classes() + .includes('org-nav-item--active') + + expect(active('/hub?tab=1')).toBe(true) + expect(active('/hub#top')).toBe(true) + expect(active('/hub/x')).toBe(true) + expect(active('/hubs')).toBe(false) + expect(active('/other')).toBe(false) + expect(active('')).toBe(false) + }) +}) diff --git a/src/components/__tests__/OrgNavigationPanel.spec.js b/src/components/__tests__/OrgNavigationPanel.spec.js index b002b51b7..c2e609de0 100644 --- a/src/components/__tests__/OrgNavigationPanel.spec.js +++ b/src/components/__tests__/OrgNavigationPanel.spec.js @@ -14,9 +14,10 @@ import { mdiStar } from '@mdi/js' import { mount } from '@vue/test-utils' import { createPinia, setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import OrgNavigationItem from '../OrgNavigationItem.vue' import OrgNavigationPanel from '../OrgNavigationPanel.vue' +import { loadIconCatalogue } from '../../services/iconCatalogue.js' vi.mock('@nextcloud/axios', () => ({ default: { @@ -49,6 +50,9 @@ beforeEach(() => { setActivePinia(createPinia()) }) +// Legacy icon names resolve once the MDI catalogue has loaded. +beforeAll(() => loadIconCatalogue()) + describe('OrgNavigationPanel', () => { it('REQ-ONAV-008: panel does not render when shouldRender is false', () => { const wrapper = mount(OrgNavigationPanel, { diff --git a/src/components/__tests__/PublicDashboardGrid.embed.spec.js b/src/components/__tests__/PublicDashboardGrid.embed.spec.js new file mode 100644 index 000000000..f6cbf9769 --- /dev/null +++ b/src/components/__tests__/PublicDashboardGrid.embed.spec.js @@ -0,0 +1,61 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Inside an embed the public grid takes the token's context: the tenant + * theme colours it, a tile links out of the embed only when the scope allows + * `interact`; without a context it renders as before (embedded-analytics + * task 13). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-13 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import PublicDashboardGrid from '../PublicDashboardGrid.vue' + +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) + +const placements = [{ id: 1, widgetId: 'tile-mail', tileType: 'app', gridX: 0, gridY: 0, tileTitle: 'Mail', tileLinkValue: '/apps/mail' }] + +/** + * The grid's root and its one tile. + * + * @param {object|undefined} embedContext The embed context, if any. + * @return {{root: object, tile: object}} + */ +function render(embedContext) { + const wrapper = mount(PublicDashboardGrid, { props: { placements, ...(embedContext === undefined ? {} : { embedContext }) } }) + return { root: wrapper.find('.public-dashboard-grid'), tile: wrapper.find('.public-share-view__tile') } +} + +describe('PublicDashboardGrid in an embed', () => { + it('renders as before without a context', () => { + const { root, tile } = render() + expect(root.classes()).not.toContain('public-dashboard-grid--embed') + expect(root.attributes('data-embed-mode')).toBeUndefined() + expect(tile.attributes('href')).toBeTruthy() + expect(tile.attributes('target')).toBeUndefined() + }) + + it('drops tile links under a read-only scope', () => { + const { root, tile } = render({ scope: { mode: 'read', allowedActions: ['interact'] }, filters: {} }) + expect(root.classes()).toContain('public-dashboard-grid--embed') + expect(root.attributes('data-embed-mode')).toBe('read') + expect(tile.attributes('href')).toBeUndefined() + expect(tile.text()).toBe('Mail') + }) + + it('drops tile links when interactions leave out interact', () => { + const { tile } = render({ scope: { mode: 'read-with-interactions', allowedActions: ['export'] } }) + expect(tile.attributes('href')).toBeUndefined() + }) + + it('opens a tile link outside the embed when the scope allows interact', () => { + const { root, tile } = render({ scope: { mode: 'read-with-interactions', allowedActions: ['interact'] } }) + expect(root.attributes('data-embed-mode')).toBe('read-with-interactions') + expect(tile.attributes('href')).toBe(render().tile.attributes('href')) + expect(tile.attributes('target')).toBe('_blank') + expect(tile.attributes('rel')).toBe('noopener noreferrer') + }) +}) diff --git a/src/components/__tests__/PublicDashboardGrid.golden.spec.js b/src/components/__tests__/PublicDashboardGrid.golden.spec.js new file mode 100644 index 000000000..c0b5007c2 --- /dev/null +++ b/src/components/__tests__/PublicDashboardGrid.golden.spec.js @@ -0,0 +1,206 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for PublicDashboardGrid's items: the normalised display item of + * every placement shape, and the rendered markup of a mixed grid, compared + * with fixtures/PublicDashboardGrid.golden.json (one case per line). Set + * RECORD_GOLDEN=1 to rewrite it. + */ + +import { mount } from '@vue/test-utils' +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import PublicDashboardGrid from '../PublicDashboardGrid.vue' + +// The dashboard's own text widget, not the library stub, so the grid's text is real (REQ-PSHR-012). +vi.mock('@conduction/nextcloud-vue', async (importOriginal) => ({ + ...(await importOriginal()), + CnTextWidget: (await import('@conduction/nextcloud-vue/src/components/CnTextWidget/CnTextWidget.vue')).default, +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/PublicDashboardGrid.golden.json') + +const WIDGET_IDS = [ + 'tile-1', + 'tile-', + 'label', + 'header', + 'text', + 'image', + 'link', + 'divider', + 'calendar', + 'restricted', + 'Tile-1', + 'tile1', + '', + undefined, + null, + 0, + false, +] + +const TILE_TYPES = [undefined, '', 'app', 0, 1] + +const CONTENTS = { + none: undefined, + nullContent: null, + stringContent: 'text', + empty: {}, + labelOnly: { label: 'L' }, + titleOnly: { title: 'T' }, + labelAndTitle: { label: 'L', title: 'T' }, + textAndBody: { text: 'X', body: 'B', url: 'https://u' }, + bodyOnly: { body: 'B' }, + emptyStrings: { label: '', title: '', text: '', body: '', url: '' }, + array: ['a'], + falsyValues: { label: 0, text: 0, url: 0 }, +} + +const FIELDS = { + bare: {}, + customTitle: { customTitle: 'C', tileTitle: 'TT' }, + tileTitle: { customTitle: '', tileTitle: 'TT' }, + sized: { gridWidth: 6, gridHeight: 2 }, + zeroSize: { gridWidth: 0, gridHeight: 0 }, + hiddenTitle0: { showTitle: 0 }, + hiddenTitleFalse: { showTitle: false }, + shownTitle: { showTitle: 1 }, + nullTitle: { showTitle: null }, + tileLook: { + tileIcon: '/i.svg', + tileBackgroundColor: '#fff', + tileTextColor: '#000', + tileLinkValue: 'https://t', + }, + tileLookFalsy: { tileIcon: 0, tileBackgroundColor: false, tileTextColor: false }, + tileLookEmpty: { + tileIcon: '', + tileBackgroundColor: null, + tileTextColor: 0, + tileLinkValue: undefined, + }, +} + +/** + * The normalised items for a list of placements. + * + * @param {Array<object>} placements The placements to normalise. + * @return {Array<object>} The display items, JSON round-tripped. + */ +function itemsOf(placements) { + return JSON.parse( + JSON.stringify(PublicDashboardGrid.computed.items.call({ placements })), + ) +} + +/** + * Every single-placement case, keyed by a readable name. + * + * @return {object} Case name to placement. + */ +function placementCases() { + const all = {} + for (const widgetId of WIDGET_IDS) { + for (const tileType of TILE_TYPES) { + all[`widget ${String(widgetId)} / tileType ${String(tileType)}`] = { + id: 1, + widgetId, + tileType, + } + } + for (const [name, content] of Object.entries(CONTENTS)) { + all[`widget ${String(widgetId)} / content ${name}`] = { + id: 2, + widgetId, + content, + } + } + } + for (const [name, fields] of Object.entries(FIELDS)) { + for (const widgetId of ['tile-9', 'text', 'calendar']) { + all[`fields ${name} / widget ${widgetId}`] = { + id: 3, + widgetId, + content: { title: 'CT', text: 'CX' }, + ...fields, + } + } + } + return all +} + +const MIXED = [ + { id: 5, widgetId: 'text', gridX: 2, gridY: 1, content: { text: 'Hello' } }, + { + id: 4, + widgetId: 'tile-1', + gridX: 0, + gridY: 1, + tileTitle: 'Mail', + tileIcon: '/m.svg', + }, + { id: 3, widgetId: 'header', gridX: 1, gridY: 0, content: { label: 'Head' } }, + { id: 2, widgetId: 'calendar', gridX: 0, gridY: 0, isVisible: 1 }, + { + id: 1, + widgetId: 'image', + gridX: 3, + gridY: 0, + content: { url: '/p.png', title: 'Pic' }, + }, + { + id: 6, + widgetId: 'link', + gridX: 0, + gridY: 2, + isVisible: 0, + content: { url: '/x' }, + }, + { id: 7, widgetId: 'link', gridX: 1, gridY: 2, isVisible: false }, + { + id: 8, + widgetId: 'divider', + gridX: 2, + gridY: 2, + showTitle: 1, + customTitle: 'D', + }, + { + id: 9, + widgetId: 'link', + gridX: 3, + gridY: 2, + isVisible: null, + content: { url: '/y' }, + }, +] + +describe('PublicDashboardGrid items (golden)', () => { + it('matches the recorded items and markup', () => { + const actual = {} + for (const [name, placement] of Object.entries(placementCases())) { + actual[name] = itemsOf([placement]) + } + actual['mixed / items'] = itemsOf(MIXED) + actual['empty / items'] = itemsOf([]) + const wrapper = mount(PublicDashboardGrid, { props: { placements: MIXED } }) + actual['mixed / markup'] = wrapper.html() + wrapper.unmount() + if (process.env.RECORD_GOLDEN === '1') { + const lines = Object.entries(actual).map( + ([name, value]) => + `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`, + ) + fs.writeFileSync(FIXTURE, `{\n${lines.join(',\n')}\n}\n`) + return + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const name of Object.keys(expected)) { + expect(actual[name], name).toEqual(expected[name]) + } + }) +}) diff --git a/src/components/__tests__/PublicDashboardGrid.live.spec.js b/src/components/__tests__/PublicDashboardGrid.live.spec.js new file mode 100644 index 000000000..433c25fda --- /dev/null +++ b/src/components/__tests__/PublicDashboardGrid.live.spec.js @@ -0,0 +1,88 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The live widgets on the public grid: news, weather and live data render + * through the link's or playlist's token-scoped read (REQ-PSHR-011). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import PublicDashboardGrid from '../PublicDashboardGrid.vue' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, + t: (_app, text) => text, +})) + +async function flushPromises() { + for (let i = 0; i < 10; i++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} + +const placements = [ + { id: 1, widgetId: 'announcements', gridX: 0, gridY: 0, content: { category: '', limit: 5 } }, + { id: 2, widgetId: 'weather', gridX: 4, gridY: 0, content: { location: 'Zuiddrecht' } }, + { id: 3, widgetId: 'livetile', gridX: 8, gridY: 0, content: { label: 'Waiting time' } }, +] + +/** + * A token-scoped read answering per widget. + * + * @return {Function} The read. + */ +function reader() { + return vi.fn(async (placementId) => { + if (placementId === 1) { + return { widget: 'announcements', data: { announcements: [{ uuid: 'a', title: 'Canteen closed Friday' }] } } + } + if (placementId === 2) { + return { widget: 'weather', data: { location: 'Zuiddrecht', tempValue: 12, units: 'metric', condition: 'rain', conditionText: 'Light rain', stale: false } } + } + return { widget: 'livetile', data: { value: 7, stale: false } } + }) +} + +describe('PublicDashboardGrid live widgets', () => { + it('renders news, weather and live data with the token-scoped read', async () => { + const readWidget = reader() + const wrapper = mount(PublicDashboardGrid, { props: { placements, readWidget } }) + // The live widgets load on demand. + await vi.waitFor(() => expect(readWidget).toHaveBeenCalledTimes(3), { timeout: 5000 }) + await flushPromises() + + expect(readWidget).toHaveBeenCalledWith(1) + expect(readWidget).toHaveBeenCalledWith(2) + expect(readWidget).toHaveBeenCalledWith(3) + expect(wrapper.find('[data-test="public-news-widget"]').text()).toContain('Canteen closed Friday') + expect(wrapper.findComponent({ name: 'WeatherWidget' }).vm.reading.tempValue).toBe(12) + expect(wrapper.findComponent({ name: 'LiveTileWidget' }).vm.reading.value).toBe(7) + expect(wrapper.find('.public-share-view__widget-restricted').exists()).toBe(false) + }) + + it('keeps them behind the sign-in notice without a read (an embed)', () => { + const wrapper = mount(PublicDashboardGrid, { props: { placements } }) + + expect(wrapper.findAll('.public-share-view__widget-restricted')).toHaveLength(3) + expect(wrapper.findComponent({ name: 'WeatherWidget' }).exists()).toBe(false) + expect(wrapper.find('[data-test="public-news-widget"]').exists()).toBe(false) + }) + + it('hands the widgets the reading itself, not the {widget, data} envelope', async () => { + const readWidget = vi.fn().mockResolvedValue(undefined) + const wrapper = mount(PublicDashboardGrid, { props: { placements: [placements[1]], readWidget } }) + + expect(await wrapper.vm.readingSource(2)).toEqual({}) + expect(wrapper.vm.placementOf({ id: 99 })).toEqual({ id: 99 }) + }) + + it('still restricts a widget that is not a live one', () => { + const wrapper = mount(PublicDashboardGrid, { + props: { placements: [{ id: 4, widgetId: 'calendar', gridX: 0, gridY: 0 }], readWidget: reader() }, + }) + + expect(wrapper.find('.public-share-view__widget-restricted').exists()).toBe(true) + }) +}) diff --git a/src/components/__tests__/PublicDashboardGrid.markdown.spec.js b/src/components/__tests__/PublicDashboardGrid.markdown.spec.js new file mode 100644 index 000000000..f61adca1f --- /dev/null +++ b/src/components/__tests__/PublicDashboardGrid.markdown.spec.js @@ -0,0 +1,64 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * A text widget on a public link or kiosk screen renders its Markdown, + * sanitised as on the dashboard (REQ-PSHR-012). + * + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-text-in-markdown-on-public-screens-req-pshr-012 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import PublicDashboardGrid from '../PublicDashboardGrid.vue' + +// The dashboard's own text widget, not the library stub, so the grid's text is real (REQ-PSHR-012). +vi.mock('@conduction/nextcloud-vue', async (importOriginal) => ({ + ...(await importOriginal()), + CnTextWidget: (await import('@conduction/nextcloud-vue/src/components/CnTextWidget/CnTextWidget.vue')).default, +})) + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, +})) + +/** + * Mount the grid with one text placement. + * + * @param {object} content The placement's content. + * @return {object} The wrapper. + */ +function mountText(content) { + return mount(PublicDashboardGrid, { + props: { placements: [{ id: 1, widgetId: 'text', gridX: 0, gridY: 0, content }] }, + }) +} + +describe('PublicDashboardGrid text widgets', () => { + it('shows a Markdown list as a list, not as raw text', () => { + const wrapper = mountText({ contentMode: 'markdown', text: '- Monday 9:00 to 17:00\n- Tuesday *closed*' }) + const items = wrapper.findAll('li') + expect(items).toHaveLength(2) + expect(items[0].text()).toBe('Monday 9:00 to 17:00') + expect(wrapper.find('em').text()).toBe('closed') + expect(wrapper.text()).not.toContain('- Monday') + }) + + it('renders a Markdown link', () => { + const wrapper = mountText({ contentMode: 'markdown', text: 'See [the city](https://example.org)' }) + expect(wrapper.find('a[href="https://example.org"]').text()).toBe('the city') + }) + + it('strips scripts and event handlers', () => { + const wrapper = mountText({ contentMode: 'markdown', text: 'Hi <img src="x" onerror="alert(1)"><script>alert(2)</script>' }) + expect(wrapper.html()).not.toContain('onerror') + expect(wrapper.html()).not.toContain('<script') + expect(wrapper.text()).toContain('Hi') + }) + + it('falls back to a legacy body when the text is missing', () => { + const wrapper = mountText({ body: 'Lunch at noon' }) + expect(wrapper.text()).toContain('Lunch at noon') + }) +}) diff --git a/src/components/__tests__/PublicDashboardGrid.spec.js b/src/components/__tests__/PublicDashboardGrid.spec.js index 6503fb97f..800a7b9e6 100644 --- a/src/components/__tests__/PublicDashboardGrid.spec.js +++ b/src/components/__tests__/PublicDashboardGrid.spec.js @@ -11,6 +11,12 @@ import { mount } from '@vue/test-utils' import { describe, expect, it, vi } from 'vitest' import PublicDashboardGrid from '../PublicDashboardGrid.vue' +// The dashboard's own text widget, not the library stub, so the grid's text is real (REQ-PSHR-012). +vi.mock('@conduction/nextcloud-vue', async (importOriginal) => ({ + ...(await importOriginal()), + CnTextWidget: (await import('@conduction/nextcloud-vue/src/components/CnTextWidget/CnTextWidget.vue')).default, +})) + vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) describe('PublicDashboardGrid', () => { @@ -64,4 +70,22 @@ describe('PublicDashboardGrid', () => { const wrapper = mount(PublicDashboardGrid, { props: { placements: [] } }) expect(wrapper.text()).toContain('no publicly viewable content') }) + + it('names a tile that shows only its icon, and leaves a titled tile to its text', () => { + const tile = { widgetId: 'tile-mail', tileType: 'app', gridX: 0, gridY: 0, tileLinkValue: '/apps/mail', tileIcon: '/apps/mail/img/mail.svg' } + const wrapper = mount(PublicDashboardGrid, { props: { placements: [{ id: 1, ...tile }, { id: 2, ...tile, gridX: 1, tileTitle: 'Mail' }] } }) + const [untitled, titled] = wrapper.findAll('.public-share-view__tile') + expect(untitled.attributes('aria-label')).toBe('Tile') + expect(titled.attributes('aria-label')).toBeUndefined() + expect(titled.text()).toBe('Mail') + }) + + it('places a card at its column and row, so a narrow column stacks beside a wide card (LpPubliek)', () => { + const text = (id, gridX, gridY, gridWidth, gridHeight) => ({ id, widgetId: 'text', gridX, gridY, gridWidth, gridHeight, showTitle: 1, customTitle: String(id), content: { text: 'x' } }) + const wrapper = mount(PublicDashboardGrid, { props: { placements: [text(1, 0, 0, 8, 8), text(2, 8, 0, 4, 3), text(3, 8, 3, 4, 3)] } }) + const cells = wrapper.findAll('.public-share-view__cell') + expect(cells[0].attributes('style')).toContain('grid-area: 1 / 1 / span 8 / span 8') + expect(cells[2].attributes('style')).toContain('grid-area: 4 / 9 / span 3 / span 4') + }) }) + diff --git a/src/components/__tests__/PublicNewsWidget.spec.js b/src/components/__tests__/PublicNewsWidget.spec.js new file mode 100644 index 000000000..6f1891c8d --- /dev/null +++ b/src/components/__tests__/PublicNewsWidget.spec.js @@ -0,0 +1,70 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The news widget on a public link or kiosk screen (REQ-PSHR-011). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import PublicNewsWidget from '../PublicNewsWidget.vue' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, + t: (_app, text) => text, +})) + +async function flushPromises() { + for (let i = 0; i < 10; i++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} + +describe('PublicNewsWidget', () => { + it('lists the news items the token-scoped read answers, without likes or comments', async () => { + const readWidget = vi.fn().mockResolvedValue({ + widget: 'announcements', + data: { + announcements: [ + { uuid: 'a', title: 'Canteen closed Friday', body: 'Renovation', category: 'Facilities', publishAt: '2026-11-20T09:00:00Z' }, + { uuid: 'b', title: 'New desk hours', body: '' }, + ], + }, + }) + const wrapper = mount(PublicNewsWidget, { props: { placementId: 5, readWidget } }) + await flushPromises() + + expect(readWidget).toHaveBeenCalledWith(5) + const items = wrapper.findAll('[data-test="public-news-item"]') + expect(items).toHaveLength(2) + expect(items[0].text()).toContain('Canteen closed Friday') + expect(items[0].text()).toContain('Renovation') + expect(items[0].text()).toContain('Facilities') + expect(items[1].find('.public-news-widget__body').exists()).toBe(false) + expect(wrapper.find('[data-test="announcement-like"]').exists()).toBe(false) + }) + + it('says there is no news when the list is empty', async () => { + const readWidget = vi.fn().mockResolvedValue({ widget: 'announcements', data: { announcements: [] } }) + const wrapper = mount(PublicNewsWidget, { props: { placementId: 5, readWidget } }) + await flushPromises() + + expect(wrapper.text()).toContain('No news yet.') + }) + + it('says news is unavailable when the read fails', async () => { + const readWidget = vi.fn().mockRejectedValue(new Error('404')) + const wrapper = mount(PublicNewsWidget, { props: { placementId: 5, readWidget } }) + await flushPromises() + + expect(wrapper.text()).toContain('News is currently unavailable.') + expect(wrapper.findAll('[data-test="public-news-item"]')).toHaveLength(0) + }) + + it('formats a publish date and leaves an unparsable one empty', () => { + const wrapper = mount(PublicNewsWidget, { props: { placementId: 5, readWidget: vi.fn().mockResolvedValue({}) } }) + expect(wrapper.vm.formatDate('2026-11-20T09:00:00Z')).not.toBe('') + expect(wrapper.vm.formatDate('not a date')).toBe('') + }) +}) diff --git a/src/components/__tests__/RuntimeShellSearch.shortcuts.spec.js b/src/components/__tests__/RuntimeShellSearch.shortcuts.spec.js new file mode 100644 index 000000000..761c46021 --- /dev/null +++ b/src/components/__tests__/RuntimeShellSearch.shortcuts.spec.js @@ -0,0 +1,138 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for search shortcuts in `RuntimeShellSearch.vue` and + * `useTileSearch.js` (search-ai-prefix-shortcuts, REQ-SPX-002, REQ-SPX-003): + * a known prefix shows one result naming the site and opens it on Enter, + * an unknown prefix falls through to tile filtering, and `?` or `!` lists + * the shortcuts. + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import RuntimeShellSearch from '../RuntimeShellSearch.vue' +import { parsePrefix, shortcutUrl } from '../../composables/useTileSearch.js' + +const SHORTCUTS = [ + { + prefix: '!t', + name: 'TOPdesk', + urlTemplate: 'https://topdesk.gemeente.nl/tas/secure/search?q={query}', + }, + { + prefix: '!z', + name: 'Zaaksysteem', + urlTemplate: 'https://zaken.gemeente.nl/zoek?q={query}', + }, +] +const ITEMS = [ + { id: 'r1', label: '!x rapport' }, + { id: 'a1', label: 'Agenda' }, +] + +describe('search shortcuts', () => { + let wrapper + + beforeEach(() => { + globalThis.t = (_app, key) => key + }) + + afterEach(() => { + wrapper?.unmount() + }) + + function mountSearch() { + wrapper = mount(RuntimeShellSearch, { + attachTo: document.body, + props: { items: ITEMS, fallbackTarget: 'none', shortcuts: SHORTCUTS }, + }) + return wrapper + } + + async function type(value) { + const input = wrapper.find('input') + input.element.value = value + await input.trigger('input') + } + + it('parses the first word as a prefix, case-insensitively, and encodes the rest', () => { + expect(parsePrefix('!T printer 3e verdieping', SHORTCUTS)).toEqual({ + shortcut: SHORTCUTS[0], + rest: 'printer 3e verdieping', + }) + expect(parsePrefix('!x rapport', SHORTCUTS)).toBeNull() + expect(parsePrefix('printer !t', SHORTCUTS)).toBeNull() + expect(shortcutUrl(SHORTCUTS[0], 'printer 3e verdieping')).toBe( + 'https://topdesk.gemeente.nl/tas/secure/search?q=printer%203e%20verdieping', + ) + expect( + shortcutUrl({ urlTemplate: 'javascript:alert({query})' }, 'x'), + ).toBeNull() + }) + + it('REQ-SPX-002: the only result names the site and Enter opens it, without dimming tiles', async () => { + mountSearch() + await type('!t printer 3e verdieping') + + const options = wrapper.findAll('[data-test="quick-search-option"]') + expect(options).toHaveLength(1) + expect(options[0].text()).toBe('Search TOPdesk for printer 3e verdieping') + expect(wrapper.emitted('filter').at(-1)).toEqual([null]) + + await wrapper.find('input').trigger('keydown', { key: 'Enter' }) + expect(wrapper.emitted('fallback').at(-1)).toEqual([ + { + type: 'web-search', + url: 'https://topdesk.gemeente.nl/tas/secure/search?q=printer%203e%20verdieping', + }, + ]) + expect(wrapper.emitted('open')).toBeUndefined() + }) + + it('REQ-SPX-002: a prefix with nothing after it opens nothing', async () => { + mountSearch() + await type('!t') + await wrapper.find('input').trigger('keydown', { key: 'Enter' }) + expect(wrapper.emitted('fallback')).toBeUndefined() + }) + + it('REQ-SPX-002: an unknown prefix filters tiles as before', async () => { + mountSearch() + await type('!x rapport') + + const options = wrapper.findAll('[data-test="quick-search-option"]') + expect(options.map((option) => option.text())).toEqual(['!x rapport']) + expect(wrapper.emitted('filter').at(-1)).toEqual([['r1']]) + }) + + it('REQ-SPX-003: ? lists the shortcuts in a labelled list, and Enter types the prefix', async () => { + mountSearch() + await type('?') + + const list = wrapper.find('[role="listbox"]') + expect(list.attributes('aria-label')).toBe('Search shortcuts') + expect( + wrapper + .findAll('[data-test="quick-search-option"]') + .map((option) => option.text()), + ).toEqual(['!t TOPdesk', '!z Zaaksysteem']) + expect(wrapper.find('[data-test="quick-search-status"]').text()).toBe( + '!t TOPdesk, !z Zaaksysteem', + ) + + await wrapper.find('input').trigger('keydown', { key: 'Enter' }) + expect(wrapper.vm.search.state.query).toBe('!t ') + expect(wrapper.emitted('fallback')).toBeUndefined() + }) + + it('REQ-SPX-003: ! alone lists them too; without shortcuts ? is an ordinary query', async () => { + mountSearch() + await type('!') + expect(wrapper.findAll('[data-test="quick-search-option"]')).toHaveLength(2) + + await wrapper.setProps({ shortcuts: [] }) + await type('?') + expect(wrapper.find('[role="listbox"]').exists()).toBe(false) + }) +}) diff --git a/src/components/__tests__/TileWidget.create.spec.js b/src/components/__tests__/TileWidget.create.spec.js new file mode 100644 index 000000000..3dee58b36 --- /dev/null +++ b/src/components/__tests__/TileWidget.create.spec.js @@ -0,0 +1,130 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * integrations-office-tiles REQ-OFT-002: a `create` tile opens the name + * dialog instead of a link, creates the file through the office-tiles + * endpoint and opens it; a refusal shows the server's message. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const recordTileClick = vi.fn() +const createOfficeFile = vi.fn() +const showError = vi.fn() + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnWidgetEditCog: { name: 'CnWidgetEditCog', template: '<div class="cog" />' }, + CnDashboardIcon: { name: 'CnDashboardIcon', template: '<i />' }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => '/nc' + path })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('@nextcloud/dialogs', () => ({ showError })) +vi.mock('../../services/api.js', () => ({ api: { createOfficeFile } })) +vi.mock('../../composables/useTileClickTracking.js', () => ({ + useTileClickTracking: () => ({ recordTileClick }), +})) +vi.mock('../HealthPingBadge.vue', () => ({ default: { name: 'HealthPingBadge', template: '<span />' } })) +vi.mock('../../dialogs/OfficeFileDialog.vue', () => ({ + default: { + name: 'OfficeFileDialog', + props: ['open', 'title', 'defaultName', 'busy'], + emits: ['update:open', 'confirm'], + template: '<div v-if="open" class="office-dialog" :data-title="title" :data-name="defaultName" :data-busy="String(busy)" />', + }, +})) + +const { default: TileWidget } = await import('../TileWidget.vue') + +const CREATE = { id: 7, title: 'New document', linkType: 'create', linkValue: 'richdocuments:.docx', iconType: 'class', icon: 'icon-filetype-file' } + +describe('TileWidget create tile', () => { + let assign + + beforeEach(() => { + recordTileClick.mockReset() + createOfficeFile.mockReset() + showError.mockReset() + assign = vi.fn() + vi.stubGlobal('location', { ...window.location, assign }) + }) + + afterEach(() => { + vi.unstubAllGlobals() + document.head.querySelectorAll('style[id^="tile-"]').forEach((el) => el.remove()) + }) + + it('links nowhere and opens the name dialog on a click', async () => { + const wrapper = mount(TileWidget, { props: { tile: CREATE } }) + expect(wrapper.find('a').attributes('href')).toBe('#') + expect(wrapper.find('.office-dialog').exists()).toBe(false) + + await wrapper.find('a').trigger('click') + await flushPromises() + + const dialog = wrapper.find('.office-dialog') + expect(dialog.exists()).toBe(true) + expect(dialog.attributes('data-title')).toBe('New document') + expect(dialog.attributes('data-name')).toBe('New document') + expect(recordTileClick).toHaveBeenCalledWith(7) + }) + + it('does not open the dialog in edit mode', async () => { + const wrapper = mount(TileWidget, { props: { tile: CREATE, editMode: true } }) + await wrapper.find('a').trigger('click') + await flushPromises() + + expect(wrapper.find('.office-dialog').exists()).toBe(false) + }) + + it('creates the file from the creator and opens it', async () => { + createOfficeFile.mockResolvedValue({ data: { fileId: 42, path: '/Documents/Notulen.docx', url: '/f/42' } }) + const wrapper = mount(TileWidget, { props: { tile: CREATE } }) + await wrapper.find('a').trigger('click') + await flushPromises() + + wrapper.findComponent({ name: 'OfficeFileDialog' }).vm.$emit('confirm', { name: 'Notulen', folder: '/Documents' }) + await flushPromises() + + expect(createOfficeFile).toHaveBeenCalledWith({ creatorId: 'richdocuments:.docx', name: 'Notulen', folder: '/Documents' }) + expect(assign).toHaveBeenCalledWith('/f/42') + expect(wrapper.find('.office-dialog').exists()).toBe(false) + expect(showError).not.toHaveBeenCalled() + }) + + it('keeps the dialog open and shows the refusal message', async () => { + createOfficeFile.mockRejectedValue({ response: { status: 400, data: { error: 'invalid_filename', message: 'Unknown file creator' } } }) + const wrapper = mount(TileWidget, { props: { tile: CREATE } }) + await wrapper.find('a').trigger('click') + await flushPromises() + + wrapper.findComponent({ name: 'OfficeFileDialog' }).vm.$emit('confirm', { name: 'Notulen', folder: '/Documents' }) + await flushPromises() + + expect(showError).toHaveBeenCalledWith('Unknown file creator') + expect(assign).not.toHaveBeenCalled() + expect(wrapper.find('.office-dialog').attributes('data-busy')).toBe('false') + }) + + it('falls back to a generic message when the server sends none', async () => { + createOfficeFile.mockRejectedValue(new Error('network')) + const wrapper = mount(TileWidget, { props: { tile: CREATE } }) + await wrapper.find('a').trigger('click') + await flushPromises() + + wrapper.findComponent({ name: 'OfficeFileDialog' }).vm.$emit('confirm', { name: 'Notulen', folder: '/Documents' }) + await flushPromises() + + expect(showError).toHaveBeenCalledWith('The file could not be created.') + }) + + it('leaves other tiles without the dialog', () => { + const wrapper = mount(TileWidget, { props: { tile: { ...CREATE, id: 8, linkType: 'app', linkValue: 'files' } } }) + + expect(wrapper.findComponent({ name: 'OfficeFileDialog' }).exists()).toBe(false) + expect(wrapper.find('a').attributes('href')).toBe('/nc/apps/files') + }) +}) diff --git a/src/components/__tests__/TileWidget.linkTarget.spec.js b/src/components/__tests__/TileWidget.linkTarget.spec.js new file mode 100644 index 000000000..a1307d01d --- /dev/null +++ b/src/components/__tests__/TileWidget.linkTarget.spec.js @@ -0,0 +1,92 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * How TileWidget opens per link target (launcher-tile-open-behaviour D2, D3). + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnWidgetEditCog: { name: 'CnWidgetEditCog', template: '<div />' }, + CnDashboardIcon: { name: 'CnDashboardIcon', template: '<i />' }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => '/nc' + path })) +vi.mock('../../composables/useTileClickTracking.js', () => ({ + useTileClickTracking: () => ({ recordTileClick: vi.fn() }), +})) +vi.mock('../HealthPingBadge.vue', () => ({ default: { name: 'HealthPingBadge', template: '<span />' } })) + +const { default: TileWidget } = await import('../TileWidget.vue') +const { useTilePanelStore } = await import('../../stores/tilePanel.js') + +let nextId = 100 + +/** + * Mount a tile. + * + * @param {object} tileFields Tile fields. + * @param {object} props Extra props. + * @return {object} The wrapper. + */ +function mountTile(tileFields = {}, props = {}) { + return mount(TileWidget, { + attachTo: document.body, + props: { + tile: { id: nextId++, title: 'Files', linkType: 'app', linkValue: 'files', iconType: 'emoji', icon: 'x', ...tileFields }, + ...props, + }, + }) +} + +describe('TileWidget link target', () => { + beforeEach(() => { + setActivePinia(createPinia()) + }) + + it('opens per its own target, else the dashboard default, else the link type', () => { + const target = (tile, props) => mountTile(tile, props).find('a').attributes('target') + + expect(target({}, { linkTarget: 'new-tab' })).toBe('_blank') + expect(target({ linkType: 'url', linkValue: 'https://x.example' }, { linkTarget: 'same-tab' })).toBe('_self') + expect(target({}, { defaultLinkTarget: 'new-tab' })).toBe('_blank') + expect(target({ linkType: 'url', linkValue: 'https://x.example' }, {})).toBe('_blank') + expect(target({}, {})).toBe('_self') + expect(target({}, { linkTarget: 'side-panel' })).toBe('_self') + }) + + it('a side-panel tile opens the panel instead of navigating, and returns focus to itself', async () => { + const wrapper = mountTile({}, { linkTarget: 'side-panel' }) + const link = wrapper.find('a') + const event = new MouseEvent('click', { cancelable: true, bubbles: true }) + + link.element.dispatchEvent(event) + + const panel = useTilePanelStore() + expect(event.defaultPrevented).toBe(true) + expect(panel.isOpen).toBe(true) + expect(panel.url).toBe('/nc/apps/files') + expect(panel.title).toBe('Files') + expect(panel.sameOrigin).toBe(true) + expect(panel.opener).toBe(link.element) + wrapper.unmount() + }) + + it('an outside side-panel address is marked for the framing check', () => { + mountTile({ linkType: 'url', linkValue: 'https://x.example/page' }, { defaultLinkTarget: 'side-panel' }).find('a').trigger('click') + + expect(useTilePanelStore().sameOrigin).toBe(false) + expect(useTilePanelStore().url).toBe('https://x.example/page') + }) + + it('other targets and edit mode leave the panel closed', async () => { + await mountTile({}, { linkTarget: 'new-tab' }).find('a').trigger('click') + await mountTile({}, { linkTarget: 'side-panel', editMode: true }).find('a').trigger('click') + + expect(useTilePanelStore().isOpen).toBe(false) + }) +}) diff --git a/src/components/__tests__/TileWidget.officeNetwork.spec.js b/src/components/__tests__/TileWidget.officeNetwork.spec.js new file mode 100644 index 000000000..64059b08a --- /dev/null +++ b/src/components/__tests__/TileWidget.officeNetwork.spec.js @@ -0,0 +1,67 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest for `TileWidget.vue`'s office-network address: the tile opens it only + * when the server saw the request come from an office network AND the tile + * has one; everywhere else it opens its main address. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const network = vi.hoisted(() => ({ office: false })) + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnWidgetEditCog: { name: 'CnWidgetEditCog', template: '<div />' }, + CnDashboardIcon: { name: 'CnDashboardIcon', props: ['name', 'size'], template: '<i />' }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => '/nc' + path })) +vi.mock('../../composables/useTileClickTracking.js', () => ({ useTileClickTracking: () => ({ recordTileClick: vi.fn() }) })) +vi.mock('../HealthPingBadge.vue', () => ({ default: { name: 'HealthPingBadge', template: '<span />' } })) +vi.mock('../../utils/loadInitialState.js', () => ({ isOnOfficeNetwork: () => network.office })) + +const { default: TileWidget } = await import('../TileWidget.vue') + +let nextId = 1000 + +/** + * The href a tile renders. + * + * @param {object} fields The tile fields. + * @return {string} + */ +function hrefOf(fields) { + const tile = { id: nextId++, title: 'Zaaksysteem', linkType: 'url', linkValue: 'https://zaken.gemeente.nl', iconType: 'emoji', icon: '📋', ...fields } + return mount(TileWidget, { props: { tile } }).find('a').attributes('href') +} + +describe('TileWidget office-network address', () => { + beforeEach(() => { + network.office = false + }) + + it('opens the internal address at the office', () => { + network.office = true + expect(hrefOf({ internalUrl: 'http://zaken.intern' })).toBe('http://zaken.intern') + }) + + it('opens the main address at home', () => { + expect(hrefOf({ internalUrl: 'http://zaken.intern' })).toBe('https://zaken.gemeente.nl') + }) + + it('opens the main address at the office when the tile has no internal address', () => { + network.office = true + expect(hrefOf({ internalUrl: '' })).toBe('https://zaken.gemeente.nl') + expect(hrefOf({})).toBe('https://zaken.gemeente.nl') + }) + + it('routes an internal path through generateUrl, even for an app tile', () => { + network.office = true + expect(hrefOf({ linkType: 'app', linkValue: 'deck', internalUrl: '/apps/files' })).toBe('/nc/apps/files') + network.office = false + expect(hrefOf({ linkType: 'app', linkValue: 'deck', internalUrl: '/apps/files' })).toBe('/nc/apps/deck') + }) +}) diff --git a/src/components/__tests__/TileWidget.removeLocked.spec.js b/src/components/__tests__/TileWidget.removeLocked.spec.js new file mode 100644 index 000000000..bef83d610 --- /dev/null +++ b/src/components/__tests__/TileWidget.removeLocked.spec.js @@ -0,0 +1,44 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * A tile whose removal the host locks (a compulsory tile on a dashboard held + * with less than full permission) asks the edit cog to leave Delete out. + * + * @spec openspec/specs/permissions/spec.md + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnWidgetEditCog: { name: 'CnWidgetEditCog', props: ['canDelete'], template: '<div class="cog" />' }, + CnDashboardIcon: { name: 'CnDashboardIcon', template: '<i />' }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => '/nc' + path })) +vi.mock('../../composables/useTileClickTracking.js', () => ({ useTileClickTracking: () => ({ recordTileClick: vi.fn() }) })) +vi.mock('../HealthPingBadge.vue', () => ({ default: { name: 'HealthPingBadge', template: '<span />' } })) + +const { default: TileWidget } = await import('../TileWidget.vue') + +const TILE = { id: 3, title: 'Files', linkType: 'url', linkValue: '/apps/files', iconType: 'class', icon: 'icon-files' } + +/** + * The edit cog of a tile in edit mode. + * + * @param {object} props Extra props. + * @return {object} The cog wrapper. + */ +function cogOf(props) { + return mount(TileWidget, { + props: { tile: TILE, editMode: true, ...props }, + global: { mocks: { t: (_app, key) => key } }, + }).findComponent({ name: 'CnWidgetEditCog' }) +} + +describe('TileWidget removeLocked', () => { + it('offers Delete by default and leaves it out when removal is locked', () => { + expect(cogOf({}).props('canDelete')).toBe(true) + expect(cogOf({ removeLocked: true }).props('canDelete')).toBe(false) + }) +}) diff --git a/src/components/__tests__/TileWidget.spec.js b/src/components/__tests__/TileWidget.spec.js new file mode 100644 index 000000000..d4cfc40ea --- /dev/null +++ b/src/components/__tests__/TileWidget.spec.js @@ -0,0 +1,286 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `TileWidget.vue`: where a tile links to, how its icon + * renders, the edit cog and health badge it shows, the click it records and + * the title-colour style it injects once per tile. + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const recordTileClick = vi.fn() + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnWidgetEditCog: { + name: 'CnWidgetEditCog', + emits: ['edit', 'remove'], + template: '<div class="cog"><button class="cog-edit" @click="$emit(\'edit\')" /><button class="cog-remove" @click="$emit(\'remove\')" /></div>', + }, + CnDashboardIcon: { name: 'CnDashboardIcon', props: ['name', 'size'], template: '<i class="mdi" :data-name="name" />' }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => '/nc' + path })) +vi.mock('../../composables/useTileClickTracking.js', () => ({ + useTileClickTracking: () => ({ recordTileClick }), +})) +vi.mock('../HealthPingBadge.vue', () => ({ + default: { name: 'HealthPingBadge', props: ['placementId', 'interval', 'hidden'], emits: ['reading'], template: '<span class="badge" />' }, +})) +vi.mock('../../services/tileCount.js', async (importOriginal) => ({ + ...(await importOriginal()), + resolveTileCount: vi.fn(), +})) + +const { default: TileWidget } = await import('../TileWidget.vue') +const { resolveTileCount } = await import('../../services/tileCount.js') + +const SOURCE = { type: 'register', register: 'cases', schema: 'case', filter: { assignee: '@me' } } + +/** + * Mount an icon-only tile whose count source answers `count`. + * + * @param {object} fields Tile fields + * @param {object} content Placement content + * @param {number|null} count The count the source answers + * @return {Promise<object>} The wrapper + */ +async function mountCounted(fields, content, count) { + resolveTileCount.mockResolvedValue(count) + const wrapper = mount(TileWidget, { props: { tile: tile(fields), content: { iconOnly: true, countSource: SOURCE, ...content }, healthPingEnabled: true, placementId: 7 } }) + await new Promise((resolve) => setTimeout(resolve, 0)) + await wrapper.vm.$nextTick() + return wrapper +} + +let nextId = 1 + +/** + * A tile with a unique id, overridden by the given fields. + * + * @param {object} fields The fields to set + * @return {object} The tile + */ +function tile(fields = {}) { + return { id: nextId++, title: 'Deck', linkType: 'url', linkValue: 'https://example.org', iconType: 'emoji', icon: '📋', ...fields } +} + +describe('TileWidget', () => { + beforeEach(() => { + recordTileClick.mockReset() + }) + + afterEach(() => { + document.head.querySelectorAll('style[id^="tile-"]').forEach((el) => el.remove()) + }) + + it('shows only the glyph of an icon-only tile, with its name as tooltip and accessible name', () => { + const wrapper = mount(TileWidget, { props: { tile: tile({ title: 'TOPdesk' }), content: { iconOnly: true } } }) + + expect(wrapper.classes()).toContain('tile-widget--icon-only') + expect(wrapper.find('.tile-widget__title').exists()).toBe(false) + expect(wrapper.find('a').attributes('title')).toBe('TOPdesk') + expect(wrapper.find('a').attributes('aria-label')).toBe('TOPdesk') + }) + + // @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-an-outage-req-ict-003 + it('marks an icon-only tile with its pin, live count and outage, and names them', async () => { + const marked = await mountCounted({ title: 'Outlook web' }, { pinned: true }, 3) + expect(marked.find('[data-testid="tile-pin"]').exists()).toBe(true) + expect(marked.find('[data-testid="tile-badge"]').text()).toBe('3') + expect(marked.find('a').attributes('aria-label')).toBe('Outlook web, 3 open, pinned') + expect(marked.findComponent({ name: 'HealthPingBadge' }).props('hidden')).toBe(true) + + const down = await mountCounted({ title: 'Council' }, {}, 4) + down.findComponent({ name: 'HealthPingBadge' }).vm.$emit('reading', { state: 'offline', downSince: null }) + await down.vm.$nextTick() + expect(down.find('[data-testid="tile-outage"]').exists()).toBe(true) + expect(down.find('[data-testid="tile-badge"]').exists()).toBe(false) + expect(down.find('a').attributes('aria-label')).toBe('Council, outage') + + const since = new Date(2026, 10, 25, 9, 12).toISOString() + down.findComponent({ name: 'HealthPingBadge' }).vm.$emit('reading', { state: 'offline', downSince: since }) + await down.vm.$nextTick() + const time = new Date(since).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + expect(down.find('a').attributes('aria-label')).toBe(`Council, outage since ${time}`) + + down.findComponent({ name: 'HealthPingBadge' }).vm.$emit('reading', { state: 'online', downSince: null }) + await down.vm.$nextTick() + expect(down.find('[data-testid="tile-outage"]').exists()).toBe(false) + expect(down.find('[data-testid="tile-badge"]').text()).toBe('4') + + const many = await mountCounted({}, {}, 140) + expect(many.find('[data-testid="tile-badge"]').text()).toBe('99+') + }) + + // @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + it('ignores the static badge and status of older placements', async () => { + const wrapper = await mountCounted({ title: 'Mail' }, { countSource: undefined, badge: 5, status: 'down' }, 9) + expect(resolveTileCount).not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="tile-badge"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="tile-outage"]').exists()).toBe(false) + }) + + // @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-the-tile-colour-is-one-of-eight-theme-colours-req-ict-004 + it('renders through its colour token, else its hex colour', () => { + const token = mount(TileWidget, { props: { tile: tile({ backgroundColor: '#123456' }), content: { colourToken: '--sc-accent' } } }) + expect(token.find('.tile-widget').attributes('style')).toContain('--tile-bg-color: var(--sc-accent, #cc0000)') + const hex = mount(TileWidget, { props: { tile: tile({ backgroundColor: '#123456' }), content: {} } }) + expect(hex.find('.tile-widget').attributes('style')).toContain('--tile-bg-color: #123456') + }) + + // @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-a-tile-can-be-an-app-tile-with-only-its-icon-req-ict-001 + it('reads "Zaaksysteem, 14 open" and keeps every mark decorative', async () => { + const wrapper = await mountCounted({ title: 'Zaaksysteem' }, { pinned: true }, 14) + const link = wrapper.find('a') + expect(link.attributes('aria-label')).toBe('Zaaksysteem, 14 open, pinned') + expect(link.attributes('title')).toBe('Zaaksysteem') + expect(wrapper.find('[data-testid="tile-badge"]').attributes('aria-hidden')).toBe('true') + expect(wrapper.find('[data-testid="tile-pin"]').attributes('aria-hidden')).toBe('true') + expect(wrapper.text()).not.toContain('Zaaksysteem') + }) + + it('names no count for 0, a negative, an unreadable or no answer', async () => { + for (const count of [0, -2, 'many', null]) { + const wrapper = await mountCounted({ title: 'Mail' }, {}, count) + expect(wrapper.find('[data-testid="tile-badge"]').exists()).toBe(false) + expect(wrapper.find('a').attributes('aria-label')).toBe('Mail') + } + }) + + it('keeps its own drag grip and menu in edit mode as an app tile', () => { + const wrapper = mount(TileWidget, { props: { tile: tile({ title: 'Mail' }), content: { iconOnly: true }, editMode: true } }) + expect(wrapper.find('[data-testid="tile-drag-grip"]').exists()).toBe(true) + expect(wrapper.find('.tile-widget__edit').exists()).toBe(true) + }) + + it('keeps the name under the glyph without iconOnly', () => { + const wrapper = mount(TileWidget, { props: { tile: tile({ title: 'TOPdesk' }) } }) + + expect(wrapper.classes()).not.toContain('tile-widget--icon-only') + expect(wrapper.find('.tile-widget__title').text()).toBe('TOPdesk') + expect(wrapper.find('a').attributes('title')).toBeUndefined() + }) + + it('shows a drag grip in edit mode only (LpBewerken)', () => { + expect(mount(TileWidget, { props: { tile: tile() } }).find('[data-testid="tile-drag-grip"]').exists()).toBe(false) + expect(mount(TileWidget, { props: { tile: tile(), editMode: true } }).find('[data-testid="tile-drag-grip"]').exists()).toBe(true) + }) + + it('links an app tile through generateUrl in the same tab', () => { + const link = mount(TileWidget, { props: { tile: tile({ linkType: 'app', linkValue: 'deck' }) } }).find('a') + + expect(link.attributes('href')).toBe('/nc/apps/deck') + expect(link.attributes('target')).toBe('_self') + }) + + it('routes an internal absolute path through generateUrl', () => { + const link = mount(TileWidget, { props: { tile: tile({ linkType: 'internal', linkValue: '/apps/text' }) } }).find('a') + + expect(link.attributes('href')).toBe('/nc/apps/text') + }) + + it('passes external, protocol-relative and mailto links through, opening urls in a new tab', () => { + const external = mount(TileWidget, { props: { tile: tile() } }).find('a') + expect(external.attributes('href')).toBe('https://example.org') + expect(external.attributes('target')).toBe('_blank') + expect(external.attributes('rel')).toBe('noopener noreferrer') + + expect(mount(TileWidget, { props: { tile: tile({ linkValue: '//cdn.example.org' }) } }).find('a').attributes('href')) + .toBe('//cdn.example.org') + expect(mount(TileWidget, { props: { tile: tile({ linkType: 'mail', linkValue: 'mailto:a@example.org' }) } }).find('a').attributes('href')) + .toBe('mailto:a@example.org') + }) + + it('renders each icon type', () => { + expect(mount(TileWidget, { props: { tile: tile({ iconType: 'svg', icon: 'M0 0h24' }) } }).find('path').attributes('d')).toBe('M0 0h24') + expect(mount(TileWidget, { props: { tile: tile({ iconType: 'class', icon: 'icon-deck' }) } }).find('span.icon').classes()).toContain('icon-deck') + expect(mount(TileWidget, { props: { tile: tile({ iconType: 'url', icon: '/img/a.png' }) } }).find('img').attributes('src')).toBe('/img/a.png') + expect(mount(TileWidget, { props: { tile: tile() } }).find('.tile-widget__emoji').text()).toBe('📋') + expect(mount(TileWidget, { props: { tile: tile({ iconType: 'mdi', icon: 'Calendar' }) } }).find('.mdi').attributes('data-name')).toBe('Calendar') + }) + + it('shows the edit cog only in edit mode and forwards its events', async () => { + expect(mount(TileWidget, { props: { tile: tile() } }).find('.cog').exists()).toBe(false) + + const wrapper = mount(TileWidget, { props: { tile: tile(), editMode: true } }) + await wrapper.find('.cog-edit').trigger('click') + await wrapper.find('.cog-remove').trigger('click') + + expect(wrapper.emitted('edit')).toHaveLength(1) + expect(wrapper.emitted('remove')).toHaveLength(1) + }) + + it('shows the health badge only when a ping is configured', () => { + expect(mount(TileWidget, { props: { tile: tile() } }).findComponent({ name: 'HealthPingBadge' }).exists()).toBe(false) + + const badge = mount(TileWidget, { props: { tile: tile(), healthPingEnabled: true, placementId: 12, pingInterval: 30 } }) + .findComponent({ name: 'HealthPingBadge' }) + + expect(badge.props()).toEqual({ placementId: 12, interval: 30, hidden: false }) + }) + + it('records a click on the tile', async () => { + const item = tile() + const wrapper = mount(TileWidget, { props: { tile: item } }) + wrapper.find('a').element.addEventListener('click', (event) => event.preventDefault()) + + await wrapper.find('a').trigger('click') + + expect(recordTileClick).toHaveBeenCalledWith(item.id) + }) + + it('injects one title-colour style per tile, defaulting to white', () => { + const item = tile({ textColor: '#123456' }) + mount(TileWidget, { props: { tile: item } }) + mount(TileWidget, { props: { tile: item } }) + + const styles = document.head.querySelectorAll(`#tile-${item.id}-style`) + expect(styles).toHaveLength(1) + expect(styles[0].textContent).toContain('color: #123456 !important') + + const plain = tile() + mount(TileWidget, { props: { tile: plain } }) + expect(document.getElementById(`tile-${plain.id}-style`).textContent).toContain('color: #ffffff !important') + }) + + it('exposes its colours as CSS variables', () => { + const style = mount(TileWidget, { props: { tile: tile({ backgroundColor: '#000000' }) } }).find('.tile-widget').attributes('style') + + expect(style).toContain('--tile-bg-color: #000000') + expect(style).toContain('--tile-text-color: #ffffff') + }) + + describe('launch tiles (launcher-tile-launch-types)', () => { + it('hands a program address to the browser and shows the hint after a click', async () => { + const wrapper = mount(TileWidget, { props: { tile: tile({ linkType: 'program', linkValue: 'ms-word:ofe|u|https://docs.example.nl/a.docx' }) } }) + const link = wrapper.find('a') + expect(link.attributes('href')).toBe('ms-word:ofe|u|https://docs.example.nl/a.docx') + expect(link.attributes('target')).toBe('_self') + expect(wrapper.find('[role="status"]').exists()).toBe(false) + + await link.trigger('click') + + expect(wrapper.find('[role="status"]').text()).toBe('Nothing happened? The program may not be installed on this computer.') + }) + + it('links an RDP tile to its file and a gateway tile to the gateway in a new tab', () => { + const rdp = mount(TileWidget, { props: { tile: tile({ linkType: 'remote-desktop', linkValue: '' }), placementId: 9, content: { remote: { mode: 'rdp', host: 'pc12' } } } }).find('a') + expect(rdp.attributes('href')).toBe('/nc/apps/launchpad/api/tiles/9/rdp') + expect(rdp.attributes('target')).toBe('_self') + + const gateway = mount(TileWidget, { props: { tile: tile({ linkType: 'remote-desktop', linkValue: 'https://desktop.gemeente.nl/' }), content: { remote: { mode: 'gateway' } } } }).find('a') + expect(gateway.attributes('href')).toBe('https://desktop.gemeente.nl/') + expect(gateway.attributes('target')).toBe('_blank') + }) + + it('opens an sso tile at the address the server stored, and shows no hint for it', async () => { + const wrapper = mount(TileWidget, { props: { tile: tile({ linkType: 'sso', linkValue: 'https://launcher.myapps.microsoft.com/api/signin/a1b2c3?tenantId=contoso' }) } }) + const link = wrapper.find('a') + expect(link.attributes('href')).toBe('https://launcher.myapps.microsoft.com/api/signin/a1b2c3?tenantId=contoso') + expect(link.attributes('target')).toBe('_blank') + await link.trigger('click') + expect(wrapper.find('[role="status"]').exists()).toBe(false) + }) + }) +}) diff --git a/src/components/__tests__/WidgetRenderer.behaviour.spec.js b/src/components/__tests__/WidgetRenderer.behaviour.spec.js new file mode 100644 index 000000000..b2157bb1b --- /dev/null +++ b/src/components/__tests__/WidgetRenderer.behaviour.spec.js @@ -0,0 +1,334 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Behaviour tests for WidgetRenderer's dispatch computeds (registry entry, + * full-bleed, renderer props, tile detection and tile data, API version + * flags, empty message), its watchers and lifecycle hooks, the widget-store + * sync and the auto-refresh timer. Like WidgetRenderer.golden.spec.js they + * run the component options against a stand-in `this`; the item mapping, + * initWidget and the legacy mount loop are pinned there. + */ + +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { nextTick, ref } from 'vue' +import WidgetRenderer from '../WidgetRenderer.vue' +import { useCalculatedFieldsStore } from '../../stores/calculatedFields.js' +import { useTileStore } from '../../stores/tiles.js' +import { useWidgetStore } from '../../stores/widgets.js' + +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), error: vi.fn(), warn: vi.fn(), info: vi.fn() }, +})) + +const { computed, watch, methods } = WidgetRenderer + +/** + * A stand-in instance with every method bound to it. + * + * @param {object} state Data, computed values and overrides. + * @return {object} the instance. + */ +function instance(state = {}) { + const ctx = { refreshInterval: null, itemsLoading: false, localWidgetItemsData: { items: [], loading: false } } + for (const [name, fn] of Object.entries(methods)) { + ctx[name] = fn.bind(ctx) + } + return Object.assign(ctx, state) +} + +beforeEach(() => { + setActivePinia(createPinia()) +}) + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('WidgetRenderer dispatch computeds', () => { + it('reads the placement content as an object, empty when unset', () => { + expect(computed.normalizedContent.call({ placement: { content: { a: 1 } } })).toEqual({ a: 1 }) + expect(computed.normalizedContent.call({ placement: { content: null } })).toEqual({}) + expect(computed.normalizedContent.call({ placement: undefined })).toEqual({}) + }) + + it('gives a registry renderer its content with the dashboard period on a dated source (REQ-DPD-002)', () => { + const content = { label: 'Zaken', source: { register: 'zaken', schema: 'zaak', periodField: 'startDate' } } + const dated = computed.periodContent.call({ normalizedContent: content, dashboardPeriod: ref('year') }) + expect(Object.keys(dated.source.filter)).toEqual(['startDate[gte]', 'startDate[lte]']) + expect(dated.source.filter['startDate[gte]']).toBe(`${new Date().getFullYear()}-01-01`) + + expect(computed.periodContent.call({ normalizedContent: content, dashboardPeriod: null })).toBe(content) + const embed = { url: 'https://app.powerbi.com/x' } + expect(computed.periodContent.call({ normalizedContent: embed, dashboardPeriod: ref('quarter') })).toBe(embed) + }) + + it('finds a registry renderer only for a known, non-empty string widget id', () => { + const entry = computed.registryEntry.call({ placement: { widgetId: 'label' } }) + expect(entry).not.toBeNull() + expect(entry.renderer).toBeTruthy() + + expect(computed.registryEntry.call({ placement: { widgetId: 'no-such-widget' } })).toBeNull() + expect(computed.registryEntry.call({ placement: { widgetId: '' } })).toBeNull() + expect(computed.registryEntry.call({ placement: { widgetId: 42 } })).toBeNull() + expect(computed.registryEntry.call({ placement: null })).toBeNull() + }) + + it('renders only header, image, divider and section heading edge-to-edge', () => { + for (const widgetId of ['header', 'image', 'divider', 'section-heading']) { + expect(computed.isFullBleed.call({ placement: { widgetId } })).toBe(true) + } + expect(computed.isFullBleed.call({ placement: { widgetId: 'label' } })).toBe(false) + expect(computed.isFullBleed.call({ placement: null })).toBe(false) + }) + + it('binds the files backend only onto the files renderer', () => { + expect(computed.rendererProps.call({ placement: { widgetId: 'files' } })).toEqual({ apiBase: '/apps/launchpad' }) + expect(computed.rendererProps.call({ placement: { widgetId: 'label' } })).toEqual({}) + }) + + it('lets the menu offer its editor only in edit mode', () => { + expect(computed.rendererProps.call({ placement: { widgetId: 'menu' }, editMode: true })) + .toEqual({ isAdmin: true, canEdit: true }) + expect(computed.rendererProps.call({ placement: { widgetId: 'menu' }, editMode: false })) + .toEqual({ isAdmin: false, canEdit: false }) + expect(computed.rendererProps.call({ placement: { widgetId: 'label' }, editMode: true })).toEqual({}) + }) + + it('tells the link, links, quicklinks, tile and video widgets when the dashboard is in edit mode', () => { + for (const widgetId of ['link', 'links', 'quicklinks', 'tile', 'video']) { + expect(computed.rendererProps.call({ placement: { widgetId }, editMode: true })) + .toEqual({ isAdmin: true, canEdit: true }) + expect(computed.rendererProps.call({ placement: { widgetId }, editMode: false })) + .toEqual({ isAdmin: false, canEdit: false }) + } + }) + + it('treats a tile- widget id or a tileType as a tile', () => { + expect(computed.isTileWidget.call({ placement: { widgetId: 'tile-3' } })).toBe(true) + expect(computed.isTileWidget.call({ placement: { widgetId: 'mydash-tile', tileType: 'link' } })).toBe(true) + expect(computed.isTileWidget.call({ placement: { widgetId: 'recommendations' } })).toBe(false) + expect(computed.isTileWidget.call({ placement: { widgetId: null } })).toBe(false) + }) + + it('parses the tile id from the widget id, null for a non-tile', () => { + expect(computed.tileId.call({ isTileWidget: true, placement: { widgetId: 'tile-17' } })).toBe(17) + expect(computed.tileId.call({ isTileWidget: false, placement: { widgetId: 'tile-17' } })).toBeNull() + }) + + it('builds an inline tile from the placement', () => { + const placement = { + id: 9, + tileType: 'link', + tileTitle: 'Mail', + tileIcon: 'mail', + tileIconType: 'mdi', + tileBackgroundColor: '#000', + tileTextColor: '#fff', + tileLinkType: 'url', + tileLinkValue: 'https://example.org', + } + expect(computed.tileData.call({ isTileWidget: true, placement })).toEqual({ + id: 9, + title: 'Mail', + icon: 'mail', + iconType: 'mdi', + backgroundColor: '#000', + textColor: '#fff', + linkType: 'url', + linkValue: 'https://example.org', + internalUrl: '', + }) + }) + + it('resolves a referenced tile from the tile store, and none for a non-tile', () => { + useTileStore().tiles = [{ id: 3, title: 'Three' }, { id: 4, title: 'Four' }] + + expect(computed.tileData.call({ isTileWidget: true, tileId: 4, placement: { widgetId: 'tile-4' } })).toEqual({ id: 4, title: 'Four' }) + expect(computed.tileData.call({ isTileWidget: true, tileId: 5, placement: { widgetId: 'tile-5' } })).toBeUndefined() + expect(computed.tileData.call({ isTileWidget: false, placement: { widgetId: 'x' } })).toBeNull() + }) + + it('flags API widgets by their item API versions', () => { + const v1 = { widget: { itemApiVersions: [1] } } + const v2 = { widget: { itemApiVersions: [2] } } + expect(computed.isApiWidgetV1.call(v1)).toBe(true) + expect(computed.isApiWidgetV2.call(v1)).toBe(false) + expect(computed.isApiWidgetV2.call(v2)).toBe(true) + expect(computed.isApiWidgetV1.call({ widget: null })).toBeUndefined() + + expect(computed.isApiWidget.call({ isApiWidgetV1: false, isApiWidgetV2: true })).toBe(true) + expect(computed.isApiWidget.call({ isApiWidgetV1: undefined, isApiWidgetV2: undefined })).toBeUndefined() + }) + + it('answers the local items data and its empty message', () => { + const data = { items: [1], emptyContentMessage: 'Nothing here' } + expect(computed.widgetItemsData.call({ localWidgetItemsData: data })).toBe(data) + expect(computed.emptyContentMessage.call({ widgetItemsData: data })).toBe('Nothing here') + expect(computed.emptyContentMessage.call({ widgetItemsData: { items: [] } })).toBe('') + }) +}) + +describe('WidgetRenderer watchers and lifecycle', () => { + it('reinitialises on a new widget, or for a tile, but not when the widget goes away', () => { + const ctx = instance({ isTileWidget: false, initWidget: vi.fn() }) + watch.widget.handler.call(ctx, { id: 'w' }) + expect(ctx.initWidget).toHaveBeenCalledTimes(1) + + watch.widget.handler.call(ctx, null) + expect(ctx.initWidget).toHaveBeenCalledTimes(1) + + ctx.isTileWidget = true + watch.widget.handler.call(ctx, null) + expect(ctx.initWidget).toHaveBeenCalledTimes(2) + }) + + it('clears loading when a tile placement changes, and leaves it otherwise', () => { + const tile = instance({ isTileWidget: true, loading: true, placement: {} }) + watch.placement.handler.call(tile) + expect(tile.loading).toBe(false) + + const other = instance({ isTileWidget: false, loading: true, placement: {} }) + watch.placement.handler.call(other) + expect(other.loading).toBe(true) + }) + + it('subscribes on mount and initialises a widget or tile, but never a registry widget', () => { + const make = (state) => instance({ setupStoreSubscription: vi.fn(), initWidget: vi.fn(), ...state }) + + const registry = make({ registryEntry: { renderer: {} }, widget: { id: 'w' }, isTileWidget: false }) + WidgetRenderer.mounted.call(registry) + expect(registry.setupStoreSubscription).toHaveBeenCalledTimes(1) + expect(registry.initWidget).not.toHaveBeenCalled() + + const api = make({ registryEntry: null, widget: { id: 'w' }, isTileWidget: false }) + WidgetRenderer.mounted.call(api) + expect(api.initWidget).toHaveBeenCalledTimes(1) + + const tile = make({ registryEntry: null, widget: null, isTileWidget: true }) + WidgetRenderer.mounted.call(tile) + expect(tile.initWidget).toHaveBeenCalledTimes(1) + + const nothing = make({ registryEntry: null, widget: null, isTileWidget: false }) + WidgetRenderer.mounted.call(nothing) + expect(nothing.setupStoreSubscription).toHaveBeenCalledTimes(1) + expect(nothing.initWidget).not.toHaveBeenCalled() + }) + + it('clears the refresh timer and unsubscribes before unmount', () => { + const clear = vi.spyOn(globalThis, 'clearInterval') + const ctx = instance({ refreshInterval: 1234, unsubscribe: vi.fn() }) + WidgetRenderer.beforeUnmount.call(ctx) + expect(clear).toHaveBeenCalledWith(1234) + expect(ctx.unsubscribe).toHaveBeenCalledTimes(1) + + clear.mockClear() + WidgetRenderer.beforeUnmount.call(instance({ refreshInterval: null, unsubscribe: undefined })) + expect(clear).not.toHaveBeenCalled() + }) +}) + +describe('WidgetRenderer widget-store sync', () => { + it('copies its own widget items from the store on a store change, ignoring other widgets', async () => { + const store = useWidgetStore() + const ctx = instance({ widget: { id: 'w1' } }) + ctx.setupStoreSubscription() + + store.$patch((state) => { + state.widgetItems.other = { items: [{ title: 'not mine' }], loading: false } + }) + await nextTick() + expect(ctx.localWidgetItemsData).toEqual({ items: [], loading: false }) + + const data = { items: [{ title: 'mine' }], loading: false } + store.$patch((state) => { + state.widgetItems.w1 = data + }) + await nextTick() + expect(ctx.localWidgetItemsData).toEqual(data) + expect(ctx.localWidgetItemsData).not.toBe(store.widgetItems.w1) + + ctx.unsubscribe() + store.$patch((state) => { + state.widgetItems.w1 = { items: [], loading: true } + }) + await nextTick() + expect(ctx.localWidgetItemsData).toEqual(data) + }) + + it('syncs its items from the store on request, only when the store has them', () => { + const store = useWidgetStore() + const ctx = instance({ widget: { id: 'w1' } }) + + ctx.updateLocalWidgetItems() + expect(ctx.localWidgetItemsData).toEqual({ items: [], loading: false }) + + store.widgetItems.w1 = { items: [{ title: 'a' }], loading: false, emptyContentMessage: 'none' } + ctx.updateLocalWidgetItems() + expect(ctx.localWidgetItemsData).toEqual({ items: [{ title: 'a' }], loading: false, emptyContentMessage: 'none' }) + + const noWidget = instance({ widget: null }) + noWidget.updateLocalWidgetItems() + expect(noWidget.localWidgetItemsData).toEqual({ items: [], loading: false }) + }) +}) + +describe('WidgetRenderer.setupAutoRefresh', () => { + it('refreshes every interval, flagging itemsLoading until the refresh settles', async () => { + vi.useFakeTimers() + let settle + const ctx = instance({ + widget: { id: 'w1' }, + refreshWidgetItems: vi.fn(() => new Promise((resolve) => { + settle = resolve + })), + }) + + ctx.setupAutoRefresh(30) + await vi.advanceTimersByTimeAsync(29999) + expect(ctx.refreshWidgetItems).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + expect(ctx.refreshWidgetItems).toHaveBeenCalledWith('w1') + expect(ctx.itemsLoading).toBe(true) + + settle() + await vi.advanceTimersByTimeAsync(0) + expect(ctx.itemsLoading).toBe(false) + + clearInterval(ctx.refreshInterval) + }) + + it('replaces an existing timer instead of stacking a second one', async () => { + vi.useFakeTimers() + const ctx = instance({ widget: { id: 'w1' }, refreshWidgetItems: vi.fn(() => Promise.resolve()) }) + + ctx.setupAutoRefresh(10) + const first = ctx.refreshInterval + ctx.setupAutoRefresh(10) + expect(ctx.refreshInterval).not.toBe(first) + + await vi.advanceTimersByTimeAsync(10000) + expect(ctx.refreshWidgetItems).toHaveBeenCalledTimes(1) + + clearInterval(ctx.refreshInterval) + }) +}) + +describe('WidgetRenderer.onWidgetData (widget-calculated-fields task 19)', () => { + it('hands what the widget shows to the calculated fields of its placement', () => { + const store = useCalculatedFieldsStore() + const spy = vi.spyOn(store, 'setWidgetData') + instance({ placement: { id: 12 } }).onWidgetData({ total: 7 }) + expect(spy).toHaveBeenCalledWith('12', { total: 7 }) + }) + + it('does nothing for a placement without an id', () => { + const store = useCalculatedFieldsStore() + const spy = vi.spyOn(store, 'setWidgetData') + instance({ placement: {} }).onWidgetData({ total: 7 }) + expect(spy).not.toHaveBeenCalled() + }) +}) diff --git a/src/components/__tests__/WidgetRenderer.golden.spec.js b/src/components/__tests__/WidgetRenderer.golden.spec.js new file mode 100644 index 000000000..967c7ad22 --- /dev/null +++ b/src/components/__tests__/WidgetRenderer.golden.spec.js @@ -0,0 +1,235 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Characterisation tests pinning WidgetRenderer's item mapping, + * `initWidget` (tile, API and legacy paths, loading flags, error log) and + * the legacy mount retry loop, run against the component options with a + * stand-in `this`, so these can be split into named steps without + * changing behaviour. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import WidgetRenderer from '../WidgetRenderer.vue' +import { widgetBridge } from '../../services/widgetBridge.js' +import { logger } from '../../utils/logger.js' + +vi.mock('../../services/widgetBridge.js', () => ({ + widgetBridge: { + hasWidgetCallback: vi.fn(), + mountWidget: vi.fn(), + getRegisteredWidgetIds: vi.fn(() => ['a', 'b']), + }, +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), error: vi.fn(), warn: vi.fn(), info: vi.fn() }, +})) + +/** + * A stand-in component instance with every method bound to it. + * + * @param {object} state Data, computed values and overrides. + * @return {object} the instance. + */ +function instance(state) { + const ctx = { + loading: false, + $nextTick: (cb) => { + if (cb) { + cb() + } + return Promise.resolve() + }, + $refs: {}, + } + for (const [name, fn] of Object.entries(WidgetRenderer.methods)) { + ctx[name] = fn.bind(ctx) + } + return Object.assign(ctx, { + loadWidgetItems: vi.fn(() => Promise.resolve()), + updateLocalWidgetItems: vi.fn(), + setupAutoRefresh: vi.fn(), + mountLegacyWidget: vi.fn(), + }, state) +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('WidgetRenderer.widgetItems', () => { + it('maps API items onto the dashboard item props with stable keys', () => { + const items = [ + { sinceId: 's', id: 'i', link: '/l', iconUrl: '/i.png', title: 'T', subtitle: 'S', extra: 1 }, + { targetUrl: '/t', avatarUrl: '/a', avatarUsername: 'u', overlayIconUrl: '/o', mainText: 'M', subText: 'X' }, + { title: 'only title' }, + {}, + { id: 0, sinceId: 0, link: '', title: '' }, + ] + const mapped = WidgetRenderer.computed.widgetItems.call({ widgetItemsData: { items }, widget: { id: 'w' } }) + expect(mapped).toEqual([ + { ...items[0], id: 's-i-/l', targetUrl: '/l', avatarUrl: '/i.png', avatarUsername: '', overlayIconUrl: '', mainText: 'T', subText: 'S' }, + { ...items[1], id: '--/t', targetUrl: '/t', avatarUrl: '/a', avatarUsername: 'u', overlayIconUrl: '/o', mainText: 'M', subText: 'X' }, + { title: 'only title', id: '--only title', targetUrl: '', avatarUrl: '', avatarUsername: '', overlayIconUrl: '', mainText: 'only title', subText: '' }, + { id: '--3', targetUrl: '', avatarUrl: '', avatarUsername: '', overlayIconUrl: '', mainText: '', subText: '' }, + { sinceId: 0, link: '', title: '', id: '--4', targetUrl: '', avatarUrl: '', avatarUsername: '', overlayIconUrl: '', mainText: '', subText: '' }, + ]) + expect(logger.debug).toHaveBeenCalledWith('[WidgetRenderer] widgetItems computed:', { + widgetId: 'w', + rawItems: items, + itemsLength: 5, + widgetItemsData: { items }, + }) + }) + + it('reads missing items as an empty list', () => { + expect(WidgetRenderer.computed.widgetItems.call({ widgetItemsData: {}, widget: null })).toEqual([]) + }) +}) + +describe('WidgetRenderer.initWidget', () => { + it('stops without a widget or for a tile', async () => { + const none = instance({ widget: null, isTileWidget: false, isApiWidget: false, loading: true }) + await none.initWidget() + expect(none.loading).toBe(false) + expect(none.loadWidgetItems).not.toHaveBeenCalled() + + const tile = instance({ widget: null, isTileWidget: true, isApiWidget: false, loading: true }) + await tile.initWidget() + expect(tile.loading).toBe(false) + expect(tile.mountLegacyWidget).not.toHaveBeenCalled() + expect(logger.debug).toHaveBeenCalledTimes(2) + }) + + it('loads an API widget, syncs it, arms refresh and clears loading', async () => { + const widget = { id: 'w', reloadInterval: 30 } + const ctx = instance({ widget, isTileWidget: false, isApiWidget: true, isApiWidgetV1: true, isApiWidgetV2: false }) + ctx.loadWidgetItems = vi.fn(() => { + expect(ctx.loading).toBe(true) + return Promise.resolve() + }) + await ctx.initWidget() + expect(ctx.loadWidgetItems).toHaveBeenCalledWith(['w']) + expect(ctx.updateLocalWidgetItems).toHaveBeenCalledTimes(1) + expect(ctx.setupAutoRefresh).toHaveBeenCalledWith(30) + expect(ctx.loading).toBe(false) + expect(logger.debug.mock.calls.map((c) => c[0])).toEqual([ + '[WidgetRenderer] initWidget called:', + '[WidgetRenderer] Initializing widget:', + '[WidgetRenderer] Detected as API widget', + ]) + expect(logger.debug.mock.calls[0][1]).toEqual({ + widgetId: 'w', + isTileWidget: false, + isApiWidget: true, + isApiWidgetV1: true, + isApiWidgetV2: false, + itemApiVersions: undefined, + fullWidget: widget, + }) + }) + + it('arms no refresh without a positive interval and logs a failed load', async () => { + const ok = instance({ widget: { id: 'w', reloadInterval: 0 }, isTileWidget: false, isApiWidget: true }) + await ok.initWidget() + expect(ok.setupAutoRefresh).not.toHaveBeenCalled() + + const error = new Error('x') + const bad = instance({ widget: { id: 'w', reloadInterval: 5 }, isTileWidget: false, isApiWidget: true }) + bad.loadWidgetItems = vi.fn(() => Promise.reject(error)) + await bad.initWidget() + expect(logger.error).toHaveBeenCalledWith('Failed to initialize widget:', error) + expect(bad.updateLocalWidgetItems).not.toHaveBeenCalled() + expect(bad.loading).toBe(false) + }) + + it('mounts a legacy widget after a tick and 50 ms, never touching loading', async () => { + vi.useFakeTimers() + const ctx = instance({ widget: { id: 'legacy' }, isTileWidget: false, isApiWidget: false, loading: 'untouched' }) + const done = ctx.initWidget() + await Promise.resolve() + await vi.advanceTimersByTimeAsync(49) + expect(ctx.mountLegacyWidget).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + await done + expect(ctx.mountLegacyWidget).toHaveBeenCalledTimes(1) + expect(ctx.loading).toBe('untouched') + expect(logger.debug).toHaveBeenCalledWith('[WidgetRenderer] Legacy widget detected:', 'legacy') + + ctx.mountLegacyWidget = vi.fn(() => { + throw new Error('mount') + }) + const failing = ctx.initWidget() + await vi.advanceTimersByTimeAsync(50) + await failing + expect(logger.error).toHaveBeenCalledWith('Failed to initialize widget:', new Error('mount')) + expect(ctx.loading).toBe('untouched') + }) +}) + +describe('WidgetRenderer.mountLegacyWidget', () => { + function legacyInstance() { + const ctx = instance({ widget: { id: 'lw' } }) + ctx.mountLegacyWidget = WidgetRenderer.methods.mountLegacyWidget.bind(ctx) + ctx.$refs = { legacyWidgetContainer: { innerHTML: '<b>x</b>' } } + return ctx + } + + it('logs and stops without a container', () => { + const ctx = legacyInstance() + ctx.$refs = {} + ctx.mountLegacyWidget() + expect(logger.error).toHaveBeenCalledWith('[WidgetRenderer] No legacyWidgetContainer ref found!') + expect(widgetBridge.hasWidgetCallback).not.toHaveBeenCalled() + }) + + it('mounts at once when the callback is registered', () => { + widgetBridge.hasWidgetCallback.mockReturnValue(true) + const ctx = legacyInstance() + ctx.mountLegacyWidget() + expect(widgetBridge.mountWidget).toHaveBeenCalledWith('lw', ctx.$refs.legacyWidgetContainer, ctx.widget) + expect(logger.debug.mock.calls.map((c) => c[0])).toEqual([ + '[WidgetRenderer] Mounting legacy widget:', + '[WidgetRenderer] Mount attempt 1/20 for:', + '[WidgetRenderer] Callback found! Mounting:', + '[WidgetRenderer] After mountWidget, container innerHTML length:', + ]) + expect(logger.debug.mock.calls[3][1]).toBe(8) + }) + + it('retries with growing delays and gives up after 20 retries', async () => { + vi.useFakeTimers() + widgetBridge.hasWidgetCallback.mockReturnValue(false) + const ctx = legacyInstance() + ctx.mountLegacyWidget() + const delays = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000] + for (const delay of delays) { + await vi.advanceTimersByTimeAsync(delay - 1) + const calls = widgetBridge.hasWidgetCallback.mock.calls.length + await vi.advanceTimersByTimeAsync(1) + expect(widgetBridge.hasWidgetCallback.mock.calls.length).toBe(calls + 1) + } + expect(widgetBridge.hasWidgetCallback).toHaveBeenCalledTimes(21) + expect(logger.debug).toHaveBeenCalledWith('[WidgetRenderer] Mount attempt 21/20 for:', 'lw') + expect(logger.debug).toHaveBeenCalledWith('[WidgetRenderer] Callback not found yet, retrying in 1000ms...') + expect(logger.error).toHaveBeenCalledWith('[WidgetRenderer] Failed to mount widget after', 20, 'attempts:', 'lw') + expect(logger.debug).toHaveBeenLastCalledWith('[WidgetRenderer] Available callbacks:', ['a', 'b']) + await vi.advanceTimersByTimeAsync(5000) + expect(widgetBridge.hasWidgetCallback).toHaveBeenCalledTimes(21) + expect(widgetBridge.mountWidget).not.toHaveBeenCalled() + }) + + it('mounts on a later attempt once the callback appears', async () => { + vi.useFakeTimers() + widgetBridge.hasWidgetCallback.mockReturnValueOnce(false).mockReturnValueOnce(false).mockReturnValue(true) + const ctx = legacyInstance() + ctx.mountLegacyWidget() + await vi.advanceTimersByTimeAsync(300) + expect(widgetBridge.mountWidget).toHaveBeenCalledTimes(1) + expect(logger.debug).toHaveBeenCalledWith('[WidgetRenderer] Mount attempt 3/20 for:', 'lw') + }) +}) diff --git a/src/components/__tests__/WidgetRenderer.unknown.spec.js b/src/components/__tests__/WidgetRenderer.unknown.spec.js new file mode 100644 index 000000000..7f87c0b3d --- /dev/null +++ b/src/components/__tests__/WidgetRenderer.unknown.spec.js @@ -0,0 +1,60 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit test for `WidgetRenderer.vue` (REQ-WDG-009): a placement of a + * widget that is neither a registry type, a tile nor an installed Nextcloud + * widget renders the "Widget not available" empty state, not an empty + * legacy mount point. + */ + +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import WidgetRenderer from '../WidgetRenderer.vue' + +vi.mock('@conduction/nextcloud-vue', () => ({ + NcDashboardWidget: { name: 'NcDashboardWidget', template: '<div />' }, + NcEmptyContent: { name: 'NcEmptyContent', props: ['description'], template: '<div class="empty">{{ description }}</div>' }, + NcLoadingIcon: { name: 'NcLoadingIcon', template: '<span />' }, +})) +vi.mock('../../constants/widgetRegistry.js', () => ({ getWidgetTypeEntry: () => null })) +vi.mock('../../services/widgetDataAdapters.js', () => ({ + buildRendererExtraProps: () => ({}), + buildWidgetDataProvide: () => ({}), +})) +vi.mock('../../services/widgetBridge.js', () => ({ + widgetBridge: { hasWidgetCallback: () => true, mountWidget: vi.fn() }, +})) +vi.mock('../TileWidget.vue', () => ({ default: { name: 'TileWidget', template: '<div />' } })) +vi.mock('../Widgets/CalculatedFields/CalculatedValues.vue', () => ({ default: { name: 'CalculatedValues', template: '<div />' } })) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), error: vi.fn(), warn: vi.fn(), info: vi.fn() }, +})) + +beforeEach(() => { + setActivePinia(createPinia()) + globalThis.t = (_app, key) => key +}) + +describe('WidgetRenderer with an uninstalled widget', () => { + it('shows "Widget not available" and no legacy mount point', () => { + const wrapper = mount(WidgetRenderer, { + props: { widget: null, placement: { id: 3, widgetId: 'uninstalled_widget', content: {} } }, + global: { mocks: { t: (_app, key) => key } }, + }) + + expect(wrapper.find('.empty').text()).toBe('Widget not available') + expect(wrapper.find('.widget-renderer__legacy').exists()).toBe(false) + }) + + it('keeps the legacy mount point for an installed Nextcloud widget', () => { + const wrapper = mount(WidgetRenderer, { + props: { widget: { id: 'legacy', itemApiVersions: [] }, placement: { id: 4, widgetId: 'legacy', content: {} } }, + global: { mocks: { t: (_app, key) => key } }, + }) + + expect(wrapper.find('.widget-renderer__legacy').exists()).toBe(true) + expect(wrapper.find('.empty').exists()).toBe(false) + }) +}) diff --git a/src/components/__tests__/WidgetWrapper.chrome.spec.js b/src/components/__tests__/WidgetWrapper.chrome.spec.js new file mode 100644 index 000000000..962d5e88e --- /dev/null +++ b/src/components/__tests__/WidgetWrapper.chrome.spec.js @@ -0,0 +1,144 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `WidgetWrapper.vue` header and chrome decisions: + * when the header shows (including the 0 / '0' showTitle round-trip), + * which chrome variant and frame the card gets, the actions menu, the + * acknowledgement gate, and the events its overlays emit. + */ + +import { shallowMount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import WidgetWrapper from '../WidgetWrapper.vue' + +beforeEach(() => { + globalThis.t = (_app, key) => key +}) + +function mountWrapper(placement, props = {}) { + return shallowMount(WidgetWrapper, { + propsData: { placement, widget: { title: 'Widget' }, ...props }, + mocks: { t: (_app, key) => key }, + }) +} + +describe('WidgetWrapper — header visibility', () => { + it('treats 0, "0", false and "" as hidden and an absent flag as shown', () => { + const shown = (showTitle) => mountWrapper({ id: 1, widgetId: 'data', showTitle }).vm.showHeader + expect(shown(undefined)).toBe(true) + expect(shown(null)).toBe(true) + expect(shown(true)).toBe(true) + expect(shown(1)).toBe(true) + expect(shown('1')).toBe(true) + expect(shown(false)).toBe(false) + expect(shown(0)).toBe(false) + expect(shown('0')).toBe(false) + expect(shown('')).toBe(false) + }) + + it('never shows a header on a tile or an NC widget, which paint their own', () => { + expect(mountWrapper({ id: 1, widgetId: 'tile-42', showTitle: true }).vm.showHeader).toBe(false) + expect(mountWrapper({ id: 1, widgetId: 'nc-widget', showTitle: true }).vm.showHeader).toBe(false) + }) + + it('shows a chromeless widget header only with a custom title', () => { + expect(mountWrapper({ id: 1, widgetId: 'divider', showTitle: true }).vm.showHeader).toBe(false) + expect(mountWrapper({ id: 1, widgetId: 'label', customTitle: 'Section', showTitle: true }).vm.showHeader).toBe(true) + expect(mountWrapper({ id: 1, widgetId: 'label', customTitle: 'Section', showTitle: 0 }).vm.showHeader).toBe(false) + }) +}) + +describe('WidgetWrapper — chrome and frame', () => { + it('gives cards the dashboard chrome and chromeless surfaces the default frame', () => { + const card = mountWrapper({ id: 1, widgetId: 'data' }).vm + expect([card.wrapperChrome, card.isChromelessFrame, card.isTileWidget]).toEqual(['nc-dashboard', false, false]) + + for (const widgetId of ['tile-7', 'tile', 'header', 'label', 'divider']) { + const vm = mountWrapper({ id: 1, widgetId }).vm + expect([vm.wrapperChrome, vm.isChromelessFrame], widgetId).toEqual(['default', true]) + } + }) + + it('uses the widget icon and buttons when present', () => { + const vm = mountWrapper({ id: 1, widgetId: 'data' }, { widget: { iconUrl: '/i.svg', buttons: [{ text: 'Open' }] } }).vm + expect(vm.widgetIconUrl).toBe('/i.svg') + expect(vm.widgetButtons).toEqual([{ text: 'Open' }]) + const bare = mountWrapper({ id: 1, widgetId: 'data' }, { widget: null }).vm + expect(bare.widgetIconUrl).toBe(null) + expect(bare.widgetButtons).toEqual([]) + }) + + it('hides the actions menu when the content opts out, and in edit mode, where the three-dot menu takes its place', () => { + expect(mountWrapper({ id: 1, widgetId: 'data' }).vm.showActionsMenu).toBe(true) + expect(mountWrapper({ id: 1, widgetId: 'data', content: { showActions: false } }).vm.showActionsMenu).toBe(false) + expect(mountWrapper({ id: 1, widgetId: 'data' }, { editMode: true }).vm.showActionsMenu).toBe(false) + }) + + it('puts Upload in the title row of a compact Files card that allows uploads, and asks the widget', () => { + const files = { id: 9, widgetId: 'files', content: { layout: 'compact', allowUpload: true } } + const actions = mountWrapper(files).vm.headerActions + expect(actions.map((a) => a.label)).toEqual(['Upload']) + const heard = vi.fn() + window.addEventListener('cn-files-widget:upload', heard) + actions[0].run() + window.removeEventListener('cn-files-widget:upload', heard) + expect(heard.mock.calls[0][0].detail).toEqual({ placementId: 9 }) + + expect(mountWrapper({ ...files, content: { layout: 'compact' } }).vm.headerActions).toEqual([]) + expect(mountWrapper(files, { editMode: true }).vm.headerActions).toEqual([]) + }) + + it('shows a drag grip in edit mode only (LpBewerken)', () => { + expect(mountWrapper({ id: 1, widgetId: 'data' }).find('[data-testid="widget-drag-grip"]').exists()).toBe(false) + expect(mountWrapper({ id: 1, widgetId: 'data' }, { editMode: true }).find('[data-testid="widget-drag-grip"]').exists()).toBe(true) + }) + + it('offers removal unless the host locks it', () => { + expect(mountWrapper({ id: 1, widgetId: 'data' }).vm.canRemove).toBe(true) + expect(mountWrapper({ id: 1, widgetId: 'data', isCompulsory: true }, { removeLocked: true }).vm.canRemove).toBe(false) + }) + + it('tells the edit cog to leave Delete out when removal is locked', () => { + const CogStub = { name: 'WidgetEditMenu', props: ['removeLocked'], template: '<div />' } + const cog = (props) => shallowMount(WidgetWrapper, { + propsData: { placement: { id: 1, widgetId: 'data', isCompulsory: 1 }, widget: { title: 'Widget' }, editMode: true, ...props }, + mocks: { t: (_app, key) => key }, + global: { stubs: { WidgetEditMenu: CogStub } }, + }).findComponent(CogStub) + expect(cog({}).props('removeLocked')).toBe(false) + expect(cog({ removeLocked: true }).props('removeLocked')).toBe(true) + }) +}) + +describe('WidgetWrapper — acknowledgement gate', () => { + it('gates only an owed, required acknowledgement outside edit mode', () => { + const placement = { id: 3, widgetId: 'data', requiresAcknowledgement: '1' } + expect(mountWrapper(placement, { outstandingAcknowledgement: true }).vm.showAcknowledgementGate).toBe(true) + expect(mountWrapper(placement, { outstandingAcknowledgement: false }).vm.showAcknowledgementGate).toBe(false) + expect(mountWrapper(placement, { outstandingAcknowledgement: true, editMode: true }).vm.showAcknowledgementGate).toBe(false) + expect(mountWrapper({ ...placement, requiresAcknowledgement: 0 }, { outstandingAcknowledgement: true }).vm.showAcknowledgementGate).toBe(false) + }) + + it('re-emits the prompt\'s acknowledgement with the placement', async () => { + const placement = { id: 3, widgetId: 'data', requiresAcknowledgement: 1 } + const wrapper = mountWrapper(placement, { outstandingAcknowledgement: true }) + const prompt = wrapper.findComponent({ name: 'AcknowledgementPrompt' }) + expect(prompt.exists()).toBe(true) + prompt.vm.$emit('acknowledged') + expect(wrapper.emitted('acknowledged')).toEqual([[placement]]) + }) + + it('forwards the edit menu\'s edit, who-sees and remove with the placement and its id', () => { + const placement = { id: 9, widgetId: 'data' } + const wrapper = mountWrapper(placement, { editMode: true }) + const cog = wrapper.findComponent({ name: 'WidgetEditMenu' }) + expect(cog.exists()).toBe(true) + cog.vm.$emit('edit') + cog.vm.$emit('whoSees') + cog.vm.$emit('remove') + expect(wrapper.emitted('edit')).toEqual([[placement]]) + expect(wrapper.emitted('whoSees')).toEqual([[placement]]) + expect(wrapper.emitted('remove')).toEqual([[9]]) + }) +}) diff --git a/src/components/__tests__/WidgetWrapper.compulsory.spec.js b/src/components/__tests__/WidgetWrapper.compulsory.spec.js new file mode 100644 index 000000000..e83dd0813 --- /dev/null +++ b/src/components/__tests__/WidgetWrapper.compulsory.spec.js @@ -0,0 +1,57 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * In edit mode a compulsory widget carries a lock that says it cannot be + * removed; in view mode, and on an ordinary widget, there is none + * (permissions REQ-PERM-004 "Compulsory widget visual indicator"). + * + * @spec openspec/specs/permissions/spec.md + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import WidgetWrapper from '../WidgetWrapper.vue' + +vi.mock('@conduction/nextcloud-vue', async (importOriginal) => ({ + ...(await importOriginal()), + CnWidgetWrapper: { name: 'CnWidgetWrapper', template: '<div><slot /></div>' }, + NcActions: { name: 'NcActions', template: '<div><slot /></div>' }, + NcActionButton: { name: 'NcActionButton', template: '<button><slot /></button>' }, +})) + +const stubs = { WidgetRenderer: true, AcknowledgementPrompt: true, WidgetEditMenu: true, LockOutline: true } + +/** + * Mount a widget. + * + * @param {object} props The props. + * @return {object} The wrapper. + */ +function mountWidget(props) { + return mount(WidgetWrapper, { + props: { placement: { id: 7, widgetId: 'header', isCompulsory: 1 }, ...props }, + global: { stubs, mocks: { t: (_a, s) => s } }, + }) +} + +const lock = (wrapper) => wrapper.find('[data-testid="widget-compulsory-indicator"]') + +describe('WidgetWrapper compulsory indicator', () => { + it('shows a named lock on a compulsory widget in edit mode', () => { + const indicator = lock(mountWidget({ editMode: true })) + expect(indicator.exists()).toBe(true) + expect(indicator.attributes('role')).toBe('img') + expect(indicator.attributes('aria-label')).toBe('Required: this widget cannot be removed') + expect(indicator.attributes('title')).toBe('Required: this widget cannot be removed') + }) + + it('shows nothing in view mode', () => { + expect(lock(mountWidget({ editMode: false })).exists()).toBe(false) + }) + + it('shows nothing on a widget that is not compulsory, also when the flag comes as text', () => { + expect(lock(mountWidget({ editMode: true, placement: { id: 8, widgetId: 'text', isCompulsory: 0 } })).exists()).toBe(false) + expect(lock(mountWidget({ editMode: true, placement: { id: 9, widgetId: 'text', isCompulsory: '1' } })).exists()).toBe(true) + }) +}) diff --git a/src/components/__tests__/WidgetWrapper.embed.spec.js b/src/components/__tests__/WidgetWrapper.embed.spec.js new file mode 100644 index 000000000..c90dd4490 --- /dev/null +++ b/src/components/__tests__/WidgetWrapper.embed.spec.js @@ -0,0 +1,62 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * In view mode an administrator's widget offers "Create embed token", a link + * to Beheer ▸ Embeds with that widget pre-selected (embedded-analytics task 40). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import WidgetWrapper from '../WidgetWrapper.vue' + +vi.mock('@conduction/nextcloud-vue', async (importOriginal) => ({ + ...(await importOriginal()), + CnWidgetWrapper: { name: 'CnWidgetWrapper', template: '<div><slot /></div>' }, + CnWidgetEditCog: { name: 'CnWidgetEditCog', template: '<div class="edit-cog" />' }, + NcActions: { name: 'NcActions', template: '<div class="actions"><slot /></div>' }, + NcActionButton: { name: 'NcActionButton', emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>' }, +})) + +const href = '/index.php/apps/launchpad/admin/embeds?tab=embeds&embedType=widget&embedId=5&embedDashboard=7' +const stubs = { + WidgetRenderer: true, + AcknowledgementPrompt: true, + EyeOff: true, + CodeTags: true, + NcActionLink: { name: 'NcActionLink', props: ['href'], template: '<a :href="href"><slot /></a>' }, +} + +function mountWidget(props) { + return mount(WidgetWrapper, { + props: { placement: { id: 5, widgetId: 'text', isCompulsory: 0 }, ...props }, + global: { stubs, mocks: { t: (_a, s) => s } }, + }) +} + +const entry = (wrapper) => wrapper.find('[data-testid="widget-create-embed-token"]') + +describe('WidgetWrapper embed entry', () => { + it('links to Beheer ▸ Embeds with the widget pre-selected', () => { + const wrapper = mountWidget({ embedHref: href }) + expect(entry(wrapper).exists()).toBe(true) + expect(entry(wrapper).attributes('href')).toBe(href) + expect(entry(wrapper).text()).toBe('Create embed token') + expect(wrapper.find('[data-testid="widget-hide-for-me"]').exists()).toBe(false) + }) + + it('sits beside Hide for me in the same menu', () => { + const wrapper = mountWidget({ embedHref: href, canHideForMe: true }) + expect(wrapper.findAll('.actions')).toHaveLength(1) + expect(entry(wrapper).exists()).toBe(true) + expect(wrapper.find('[data-testid="widget-hide-for-me"]').exists()).toBe(true) + }) + + it('offers nothing without a link or in edit mode', () => { + expect(entry(mountWidget({})).exists()).toBe(false) + expect(mountWidget({}).find('.actions').exists()).toBe(false) + expect(entry(mountWidget({ embedHref: href, editMode: true })).exists()).toBe(false) + }) +}) diff --git a/src/components/__tests__/WidgetWrapper.hide.spec.js b/src/components/__tests__/WidgetWrapper.hide.spec.js index b69d1e7da..5f78f9397 100644 --- a/src/components/__tests__/WidgetWrapper.hide.spec.js +++ b/src/components/__tests__/WidgetWrapper.hide.spec.js @@ -19,6 +19,7 @@ vi.mock('@conduction/nextcloud-vue', async (importOriginal) => ({ }, NcActions: { name: 'NcActions', + props: ['forceMenu'], template: '<div class="actions"><slot /></div>', }, NcActionButton: { @@ -45,6 +46,13 @@ describe('WidgetWrapper hide for me', () => { expect(wrapper.emitted('hideForMe')[0][0].id).toBe(5) }) + it('keeps Hide for me inside the Widget options menu when it is the only item', () => { + const actions = mountWidget({ canHideForMe: true }).findComponent({ + name: 'NcActions', + }) + expect(actions.props('forceMenu')).toBe(true) + }) + it('offers nothing for a compulsory widget, in edit mode, or when not allowed', () => { expect( mountWidget({ diff --git a/src/components/__tests__/WidgetWrapper.outage.spec.js b/src/components/__tests__/WidgetWrapper.outage.spec.js new file mode 100644 index 000000000..9762aa65d --- /dev/null +++ b/src/components/__tests__/WidgetWrapper.outage.spec.js @@ -0,0 +1,59 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The card head carries what the renderer reports: the source line under the + * title and the "Outage" tag (REQ-IFRAME-005). + * + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import WidgetWrapper from '../WidgetWrapper.vue' + +vi.mock('@conduction/nextcloud-vue', async (importOriginal) => ({ + ...(await importOriginal()), + CnWidgetWrapper: { + name: 'CnWidgetWrapper', + props: ['subtitle'], + template: '<div><span class="subtitle">{{ subtitle }}</span><slot name="title-meta" /><slot /></div>', + }, + CnWidgetEditCog: { name: 'CnWidgetEditCog', template: '<div />' }, + NcActions: { name: 'NcActions', template: '<div><slot /></div>' }, + NcActionButton: { name: 'NcActionButton', template: '<button><slot /></button>' }, +})) + +const RendererStub = { name: 'WidgetRenderer', emits: ['status', 'editRequest'], template: '<div />' } + +function mountWidget() { + return mount(WidgetWrapper, { + props: { placement: { id: 5, widgetId: 'iframe', isCompulsory: 0 } }, + global: { + stubs: { WidgetRenderer: RendererStub, AcknowledgementPrompt: true }, + mocks: { t: (_a, s) => s }, + }, + }) +} + +describe('WidgetWrapper card head status', () => { + it('shows the source line and the Outage tag the renderer reports', async () => { + const wrapper = mountWidget() + expect(wrapper.find('[data-testid="widget-outage-tag"]').exists()).toBe(false) + wrapper.findComponent(RendererStub).vm.$emit('status', { subtitle: 'Embedded report · app.powerbi.com', outage: true }) + await wrapper.vm.$nextTick() + expect(wrapper.find('.subtitle').text()).toBe('Embedded report · app.powerbi.com') + expect(wrapper.find('[data-testid="widget-outage-tag"]').text()).toBe('Outage') + }) + + it('drops the tag when the outage ends and ignores a malformed status', async () => { + const wrapper = mountWidget() + const renderer = wrapper.findComponent(RendererStub) + renderer.vm.$emit('status', { subtitle: 'x', outage: true }) + await wrapper.vm.$nextTick() + renderer.vm.$emit('status', null) + await wrapper.vm.$nextTick() + expect(wrapper.find('[data-testid="widget-outage-tag"]').exists()).toBe(false) + expect(wrapper.find('.subtitle').text()).toBe('') + }) +}) diff --git a/src/components/__tests__/WidgetWrapper.spec.js b/src/components/__tests__/WidgetWrapper.spec.js index ecf5121d0..94f49160f 100644 --- a/src/components/__tests__/WidgetWrapper.spec.js +++ b/src/components/__tests__/WidgetWrapper.spec.js @@ -10,7 +10,7 @@ import { shallowMount } from '@vue/test-utils' import { beforeEach, describe, expect, it } from 'vitest' -import WidgetWrapper from '../WidgetWrapper.vue' +import WidgetWrapper, { sameDestination } from '../WidgetWrapper.vue' beforeEach(() => { globalThis.t = (_app, key) => key @@ -90,4 +90,135 @@ describe('WidgetWrapper — edit cog', () => { mountWrapper(placement, true).find('.launchpad-widget__cog').exists(), ).toBe(true) }) + + it('hands the edit mode to the renderer and opens the editor on its edit request', async () => { + const placement = { id: 4, widgetId: 'menu', styleConfig: {} } + const wrapper = shallowMount(WidgetWrapper, { + propsData: { placement, widget: { title: 'Widget' }, editMode: true }, + mocks: { t: (_app, key) => key }, + global: { + stubs: { + CnWidgetWrapper: { template: '<div><slot /></div>' }, + // The real LazyMount: edit mode mounts the renderer at once. + LazyMount: false, + }, + }, + }) + const renderer = wrapper.findComponent({ name: 'WidgetRenderer' }) + expect(renderer.props('editMode')).toBe(true) + renderer.vm.$emit('editRequest') + await wrapper.vm.$nextTick() + expect(wrapper.emitted('edit')).toEqual([[placement]]) + }) +}) + +describe('WidgetWrapper — header link (LpVandaag "Open agenda")', () => { + it('hands content.headerLink to the card', () => { + const wrapper = mountWrapper({ + id: 2, + widgetId: 'calendar', + showTitle: true, + content: { + headerLink: { + label: 'Open agenda', + href: '/index.php/apps/calendar/', + }, + }, + }) + expect(wrapper.vm.headerLink).toEqual({ + label: 'Open agenda', + href: '/index.php/apps/calendar/', + }) + }) + + it('hands none without a label or a link', () => { + for (const headerLink of [ + undefined, + { label: 'Open agenda' }, + { href: '/x' }, + { label: '', href: '/x' }, + ]) { + const wrapper = mountWrapper({ + id: 3, + widgetId: 'calendar', + showTitle: true, + content: { headerLink }, + }) + expect(wrapper.vm.headerLink).toBeNull() + } + }) +}) + +describe('WidgetWrapper — footer buttons and the Nextcloud widget header', () => { + it('leaves out a footer button that leads where the header link does', () => { + const wrapper = shallowMount(WidgetWrapper, { + propsData: { + placement: { + id: 4, + widgetId: 'calendar', + showTitle: true, + content: { + headerLink: { + label: 'Open agenda', + href: '/index.php/apps/calendar/', + }, + }, + }, + widget: { + title: 'Agenda', + buttons: [ + { + text: 'Meer activiteiten', + link: 'http://localhost:8080/apps/calendar', + }, + { text: 'Nieuw', link: '/apps/calendar/new' }, + ], + }, + }, + mocks: { t: (_app, key) => key }, + }) + expect(wrapper.vm.widgetButtons.map((b) => b.text)).toEqual(['Nieuw']) + }) + + it('keeps every footer button without a header link', () => { + const wrapper = shallowMount(WidgetWrapper, { + propsData: { + placement: { id: 5, widgetId: 'calendar', showTitle: true }, + widget: { title: 'Agenda', buttons: [{ text: 'A', link: '/a' }] }, + }, + mocks: { t: (_app, key) => key }, + }) + expect(wrapper.vm.widgetButtons).toHaveLength(1) + }) + + it('lets the card title a Nextcloud widget that draws no header of its own', () => { + const own = mountWrapper({ + id: 6, + widgetId: 'nc-widget', + showTitle: true, + content: {}, + }) + expect(own.vm.showHeader).toBe(false) + const titled = mountWrapper({ + id: 7, + widgetId: 'nc-widget', + showTitle: true, + customTitle: 'Verder waar u was', + content: { showHeader: false }, + }) + expect(titled.vm.showHeader).toBe(true) + }) +}) + +describe('sameDestination', () => { + it('compares the path, ignoring the host, /index.php and a trailing slash', () => { + expect( + sameDestination( + 'http://localhost:8080/apps/calendar', + '/index.php/apps/calendar/', + ), + ).toBe(true) + expect(sameDestination('/apps/calendar/new', '/apps/calendar')).toBe(false) + expect(sameDestination(undefined, '/apps/calendar')).toBe(false) + }) }) diff --git a/src/components/__tests__/fixtures/PublicDashboardGrid.golden.json b/src/components/__tests__/fixtures/PublicDashboardGrid.golden.json new file mode 100644 index 000000000..bb6217813 --- /dev/null +++ b/src/components/__tests__/fixtures/PublicDashboardGrid.golden.json @@ -0,0 +1,330 @@ +{ + "widget tile-1 / tileType undefined": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / tileType ": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / tileType 0": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content none": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content nullContent": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content stringContent": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content empty": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content labelOnly": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content titleOnly": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content labelAndTitle": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content textAndBody": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget tile-1 / content bodyOnly": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget tile-1 / content emptyStrings": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content array": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile-1 / content falsyValues": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / tileType undefined": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / tileType ": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / tileType 0": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content none": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content nullContent": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content stringContent": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content empty": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content labelOnly": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content titleOnly": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content labelAndTitle": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content textAndBody": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget tile- / content bodyOnly": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget tile- / content emptyStrings": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content array": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile- / content falsyValues": [{"id":2,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / tileType undefined": [{"id":1,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / tileType ": [{"id":1,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / tileType 0": [{"id":1,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content none": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content nullContent": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content stringContent": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content empty": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content labelOnly": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content titleOnly": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content labelAndTitle": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content textAndBody": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget label / content bodyOnly": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget label / content emptyStrings": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content array": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget label / content falsyValues": [{"id":2,"kind":"label","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / tileType undefined": [{"id":1,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / tileType ": [{"id":1,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / tileType 0": [{"id":1,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content none": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content nullContent": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content stringContent": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content empty": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content labelOnly": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content titleOnly": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content labelAndTitle": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content textAndBody": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget header / content bodyOnly": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget header / content emptyStrings": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content array": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget header / content falsyValues": [{"id":2,"kind":"header","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / tileType undefined": [{"id":1,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / tileType ": [{"id":1,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / tileType 0": [{"id":1,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content none": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content nullContent": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content stringContent": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content empty": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content labelOnly": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content titleOnly": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content labelAndTitle": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content textAndBody": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget text / content bodyOnly": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget text / content emptyStrings": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content array": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget text / content falsyValues": [{"id":2,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / tileType undefined": [{"id":1,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / tileType ": [{"id":1,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / tileType 0": [{"id":1,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content none": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content nullContent": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content stringContent": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content empty": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content labelOnly": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content titleOnly": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content labelAndTitle": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content textAndBody": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget image / content bodyOnly": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget image / content emptyStrings": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content array": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget image / content falsyValues": [{"id":2,"kind":"image","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / tileType undefined": [{"id":1,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / tileType ": [{"id":1,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / tileType 0": [{"id":1,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content none": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content nullContent": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content stringContent": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content empty": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content labelOnly": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content titleOnly": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content labelAndTitle": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content textAndBody": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget link / content bodyOnly": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget link / content emptyStrings": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content array": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget link / content falsyValues": [{"id":2,"kind":"link","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / tileType undefined": [{"id":1,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / tileType ": [{"id":1,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / tileType 0": [{"id":1,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content none": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content nullContent": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content stringContent": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content empty": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content labelOnly": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content titleOnly": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content labelAndTitle": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content textAndBody": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget divider / content bodyOnly": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget divider / content emptyStrings": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content array": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget divider / content falsyValues": [{"id":2,"kind":"divider","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget calendar / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget calendar / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget calendar / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget restricted / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget restricted / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget restricted / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget Tile-1 / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget Tile-1 / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget Tile-1 / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget tile1 / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget tile1 / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget tile1 / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget undefined / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget undefined / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget undefined / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget null / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget null / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget null / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget 0 / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget 0 / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget 0 / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / tileType undefined": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / tileType ": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / tileType app": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / tileType 0": [{"id":1,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / tileType 1": [{"id":1,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content none": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content nullContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content stringContent": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content empty": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content labelOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content titleOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"T","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content labelAndTitle": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"L","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content textAndBody": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"X","url":"https://u"}], + "widget false / content bodyOnly": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"B","url":""}], + "widget false / content emptyStrings": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content array": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "widget false / content falsyValues": [{"id":2,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""}], + "fields bare / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields bare / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields bare / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields customTitle / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"C","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields customTitle / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"C","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields customTitle / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"C","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileTitle / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"TT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileTitle / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"TT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileTitle / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"TT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields sized / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":6,"gridHeight":2,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields sized / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":6,"gridHeight":2,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields sized / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":6,"gridHeight":2,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields zeroSize / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields zeroSize / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields zeroSize / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields hiddenTitle0 / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":false,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields hiddenTitle0 / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":false,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields hiddenTitle0 / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":false,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields hiddenTitleFalse / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":false,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields hiddenTitleFalse / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":false,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields hiddenTitleFalse / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":false,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields shownTitle / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields shownTitle / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields shownTitle / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields nullTitle / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields nullTitle / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields nullTitle / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileLook / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"/i.svg","tileBackgroundColor":"#fff","tileTextColor":"#000","tileLink":"https://t","text":"CX","url":""}], + "fields tileLook / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"/i.svg","tileBackgroundColor":"#fff","tileTextColor":"#000","tileLink":"https://t","text":"CX","url":""}], + "fields tileLook / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"/i.svg","tileBackgroundColor":"#fff","tileTextColor":"#000","tileLink":"https://t","text":"CX","url":""}], + "fields tileLookFalsy / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileLookFalsy / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileLookFalsy / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileLookEmpty / widget tile-9": [{"id":3,"kind":"tile","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileLookEmpty / widget text": [{"id":3,"kind":"text","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "fields tileLookEmpty / widget calendar": [{"id":3,"kind":"restricted","gridX":null,"gridY":null,"gridWidth":4,"gridHeight":4,"title":"CT","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"CX","url":""}], + "mixed / items": [{"id":2,"kind":"restricted","gridX":0,"gridY":0,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""},{"id":3,"kind":"header","gridX":1,"gridY":0,"gridWidth":4,"gridHeight":4,"title":"Head","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""},{"id":1,"kind":"image","gridX":3,"gridY":0,"gridWidth":4,"gridHeight":4,"title":"Pic","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":"/p.png"},{"id":4,"kind":"tile","gridX":0,"gridY":1,"gridWidth":4,"gridHeight":4,"title":"Mail","showTitle":true,"tileIcon":"/m.svg","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""},{"id":5,"kind":"text","gridX":2,"gridY":1,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"Hello","url":""},{"id":8,"kind":"divider","gridX":2,"gridY":2,"gridWidth":4,"gridHeight":4,"title":"D","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":""},{"id":9,"kind":"link","gridX":3,"gridY":2,"gridWidth":4,"gridHeight":4,"title":"","showTitle":true,"tileIcon":"","tileBackgroundColor":"","tileTextColor":"","tileLink":"","text":"","url":"/y"}], + "empty / items": [], + "mixed / markup": "<div data-v-7700e0c6=\"\" class=\"public-dashboard-grid\">\n <div data-v-7700e0c6=\"\" class=\"public-share-view__grid\">\n <div data-v-7700e0c6=\"\" class=\"public-share-view__cell\" style=\"grid-area: 1 / 1 / span 4 / span 4;\">\n <!-- Tile — icon + label linking to its target. -->\n <!-- Static custom widgets that render safely for anonymous visitors. -->\n <div data-v-7700e0c6=\"\" class=\"public-share-view__widget\">\n <!--v-if-->\n <p data-v-7700e0c6=\"\" class=\"public-share-view__widget-restricted\">This widget is only visible to signed-in users.</p>\n </div>\n </div>\n <div data-v-7700e0c6=\"\" class=\"public-share-view__cell\" style=\"grid-area: 1 / 2 / span 4 / span 4;\">\n <!-- Tile — icon + label linking to its target. -->\n <!-- Static custom widgets that render safely for anonymous visitors. -->\n <div data-v-7700e0c6=\"\" class=\"public-share-view__widget\">\n <h2 data-v-7700e0c6=\"\" class=\"public-share-view__widget-title\">Head</h2>\n <h3 data-v-7700e0c6=\"\" class=\"public-share-view__widget-heading\">Head</h3>\n </div>\n </div>\n <div data-v-7700e0c6=\"\" class=\"public-share-view__cell\" style=\"grid-area: 1 / 4 / span 4 / span 4;\">\n <!-- Tile — icon + label linking to its target. -->\n <!-- Static custom widgets that render safely for anonymous visitors. -->\n <div data-v-7700e0c6=\"\" class=\"public-share-view__widget\">\n <h2 data-v-7700e0c6=\"\" class=\"public-share-view__widget-title\">Pic</h2><img data-v-7700e0c6=\"\" class=\"public-share-view__widget-image\" src=\"/p.png\" alt=\"Pic\">\n </div>\n </div>\n <div data-v-7700e0c6=\"\" class=\"public-share-view__cell\" style=\"grid-area: 2 / 1 / span 4 / span 4;\">\n <!-- Tile — icon + label linking to its target. --><a data-v-7700e0c6=\"\" class=\"public-share-view__tile\" href=\"#\"><img data-v-7700e0c6=\"\" class=\"public-share-view__tile-icon\" src=\"/m.svg\" alt=\"\"><span data-v-7700e0c6=\"\" class=\"public-share-view__tile-title\">Mail</span></a>\n </div>\n <div data-v-7700e0c6=\"\" class=\"public-share-view__cell\" style=\"grid-area: 2 / 3 / span 4 / span 4;\">\n <!-- Tile — icon + label linking to its target. -->\n <!-- Static custom widgets that render safely for anonymous visitors. -->\n <div data-v-7700e0c6=\"\" class=\"public-share-view__widget\">\n <!--v-if-->\n <div data-v-156219e3=\"\" data-v-7700e0c6=\"\" class=\"cn-text-widget public-share-view__widget-text\" style=\"width: 100%; height: 100%; padding: 16px; display: flex; align-items: safe center; justify-content: safe center; overflow: auto; background-color: transparent;\">\n <div data-v-156219e3=\"\" class=\"cn-text-widget__content cn-text-widget__content--html\" style=\"font-size: 14px; text-align: left; color: var(--color-main-text); width: 100%; overflow-wrap: break-word;\">Hello</div>\n <!--v-if-->\n </div>\n </div>\n </div>\n <div data-v-7700e0c6=\"\" class=\"public-share-view__cell\" style=\"grid-area: 3 / 3 / span 4 / span 4;\">\n <!-- Tile — icon + label linking to its target. -->\n <!-- Static custom widgets that render safely for anonymous visitors. -->\n <div data-v-7700e0c6=\"\" class=\"public-share-view__widget\">\n <!--v-if-->\n <hr data-v-7700e0c6=\"\" class=\"public-share-view__divider\">\n </div>\n </div>\n <div data-v-7700e0c6=\"\" class=\"public-share-view__cell\" style=\"grid-area: 3 / 4 / span 4 / span 4;\">\n <!-- Tile — icon + label linking to its target. -->\n <!-- Static custom widgets that render safely for anonymous visitors. -->\n <div data-v-7700e0c6=\"\" class=\"public-share-view__widget\">\n <!--v-if--><a data-v-7700e0c6=\"\" class=\"public-share-view__widget-link\" href=\"/y\">/y</a>\n </div>\n </div>\n </div>\n</div>" +} diff --git a/src/components/admin/AdminCustomCss.vue b/src/components/admin/AdminCustomCss.vue new file mode 100644 index 000000000..c3cfd3ec5 --- /dev/null +++ b/src/components/admin/AdminCustomCss.vue @@ -0,0 +1,199 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="custom-css" data-testid="admin-custom-css"> + <p class="custom-css__hint"> + {{ + t( + 'launchpad', + 'Cleaned on save: imports, addresses to other sites and script-like constructs are removed, and every rule is limited to LaunchPad.', + ) + }} + </p> + <label class="custom-css__label" for="launchpad-admin-custom-css"> + {{ t('launchpad', 'CSS for all of LaunchPad') }} + </label> + <textarea + id="launchpad-admin-custom-css" + v-model="css" + class="custom-css__input" + data-testid="admin-custom-css-input" + rows="10" + spellcheck="false" + :disabled="loading || saving" /> + <div class="custom-css__actions"> + <NcButton + variant="primary" + data-testid="admin-custom-css-save" + :disabled="loading || saving" + @click="save"> + {{ t('launchpad', 'Save') }} + </NcButton> + </div> + <p + v-if="removed.length > 0" + class="custom-css__removed" + role="status" + data-testid="admin-custom-css-removed"> + {{ t('launchpad', 'Removed: {constructs}', { constructs: removed.join(', ') }) }} + </p> + <p + v-else-if="saved" + class="custom-css__saved" + role="status" + data-testid="admin-custom-css-saved"> + {{ t('launchpad', 'CSS saved') }} + </p> + <p + v-if="error !== ''" + class="custom-css__error" + role="alert" + data-testid="admin-custom-css-error"> + {{ error }} + </p> + </div> +</template> + +<script> +import { NcButton } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +/** + * AdminCustomCss — Beheer ▸ General section for the administrator CSS of all + * of LaunchPad (platform-dashboard-theme-and-css REQ-THM-003). The server + * stores only the cleaned and scoped CSS; after a save the field shows that + * stored version and the section names what the cleaning removed. + */ +export default { + name: 'AdminCustomCss', + + components: { + NcButton, + }, + + data() { + return { + css: '', + removed: [], + saved: false, + error: '', + loading: true, + saving: false, + } + }, + + /** @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 */ + created() { + this.load() + }, + + methods: { + t, + + /** @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 */ + async load() { + this.loading = true + try { + const { data } = await api.getCustomCss() + this.css = typeof data?.customCss === 'string' ? data.customCss : '' + } catch (error) { + logger.error('Failed to load the custom CSS:', error) + this.error = t('launchpad', 'The custom CSS could not be loaded.') + } finally { + this.loading = false + } + }, + + /** + * Save the CSS, then show what the server stored and what it removed. + * + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + async save() { + this.saving = true + this.saved = false + this.error = '' + this.removed = [] + try { + const { data } = await api.updateCustomCss(this.css) + this.showSaved(data) + } catch (error) { + logger.error('Failed to save the custom CSS:', error) + this.error = saveErrorMessage(error) + } finally { + this.saving = false + } + }, + + /** + * Show the CSS the server stored and what its cleaning removed. + * + * @param {object|undefined} data The save response. + * @return {void} + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + showSaved(data) { + this.css = typeof data?.customCss === 'string' ? data.customCss : '' + this.removed = Array.isArray(data?.removed) ? data.removed : [] + this.saved = true + }, + }, +} + +/** + * The server's refusal message, or a general one when it sent none. + * + * @param {Error} error The failed request. + * @return {string} + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ +function saveErrorMessage(error) { + const message = error?.response?.data?.error + return typeof message === 'string' && message !== '' + ? message + : t('launchpad', 'The custom CSS could not be saved.') +} +</script> + +<style scoped> +.custom-css__hint { + color: var(--color-text-maxcontrast); + margin-bottom: 8px; +} + +.custom-css__label { + display: block; + font-weight: bold; + margin-bottom: 4px; +} + +.custom-css__input { + width: 100%; + font-family: var(--font-face-monospace, monospace); + color: var(--color-main-text); + background-color: var(--color-main-background); + border: 2px solid var(--color-border-maxcontrast); + border-radius: var(--border-radius-large); + padding: 8px; +} + +.custom-css__actions { + margin-top: 8px; +} + +.custom-css__removed, +.custom-css__saved { + margin-top: 8px; + color: var(--color-main-text); +} + +.custom-css__error { + margin-top: 8px; + color: var(--color-error-text, var(--color-error)); +} +</style> diff --git a/src/components/admin/AdminDemoData.vue b/src/components/admin/AdminDemoData.vue index 6d5703352..0ca592ba6 100644 --- a/src/components/admin/AdminDemoData.vue +++ b/src/components/admin/AdminDemoData.vue @@ -74,7 +74,19 @@ }} </div> - <div class="launchpad-demo-showcases__actions"> + <div v-if="choice !== null" class="launchpad-demo-showcases__actions"> + <NcCheckboxRadioSwitch + :modelValue="isChosen(showcase)" + :data-test="'showcase-choose-' + showcase.id" + @update:modelValue="(chosen) => $emit('choose', showcase.id, chosen)"> + {{ + showcase.isInstalled + ? t('launchpad', 'Installed') + : t('launchpad', 'Install on Next') + }} + </NcCheckboxRadioSwitch> + </div> + <div v-else class="launchpad-demo-showcases__actions"> <NcButton v-if="!showcase.isInstalled" variant="primary" @@ -105,19 +117,27 @@ </div> </template> - <DemoShowcaseUninstallDialog - :open="uninstallTarget !== null" - :showcaseName="uninstallTarget ? uninstallTarget.name : ''" - @update:open="uninstallTarget = null" - @confirm="onUninstallConfirm" /> + <CnConfirmDialog + v-if="uninstallTarget !== null" + :dialogTitle="t('launchpad', 'Remove showcase dashboard')" + :message=" + t( + 'launchpad', + 'Remove the {name} showcase dashboard for all users? You can reinstall it later.', + { name: uninstallTarget.name }, + ) + " + :confirmLabel="t('launchpad', 'Remove')" + variant="error" + @confirm="onUninstallConfirm" + @close="uninstallTarget = null" /> </div> </template> <script> -import { NcButton } from '@conduction/nextcloud-vue' +import { CnConfirmDialog, NcButton, NcCheckboxRadioSwitch } from '@conduction/nextcloud-vue' import { NcNoteCard } from '@nextcloud/vue' import ViewDashboard from 'vue-material-design-icons/ViewDashboard.vue' -import DemoShowcaseUninstallDialog from '../../dialogs/DemoShowcaseUninstallDialog.vue' import { api } from '../../services/api.js' export default { @@ -125,11 +145,28 @@ export default { components: { NcButton, - DemoShowcaseUninstallDialog, + NcCheckboxRadioSwitch, + CnConfirmDialog, NcNoteCard, ViewDashboard, }, + props: { + /** + * The setup wizard's demo choice, `{ [showcaseId]: boolean }`. When + * given, each card shows a checkbox instead of Install and Uninstall, + * and nothing is installed here: the wizard installs the checked + * showcases on Next. A showcase without an entry is checked when it + * is installed. + */ + choice: { + type: Object, + default: null, + }, + }, + + emits: ['choose'], + data() { return { loading: false, @@ -252,6 +289,18 @@ export default { } }, + /** + * Whether a showcase is checked in the wizard's demo choice. + * + * @param {object} showcase The showcase. + * @return {boolean} + * @spec openspec/specs/setup-wizard/spec.md#req-wiz-005 + */ + isChosen(showcase) { + const chosen = this.choice?.[showcase.id] + return chosen === undefined ? showcase.isInstalled === true : chosen === true + }, + /** * Hide a broken thumbnail so the card falls back to its icon. * diff --git a/src/components/admin/AdminSettings.vue b/src/components/admin/AdminSettings.vue index 31554495b..6eff80425 100644 --- a/src/components/admin/AdminSettings.vue +++ b/src/components/admin/AdminSettings.vue @@ -5,54 +5,122 @@ <template> <div class="launchpad-admin"> - <CnSettingsSection - :name="t('launchpad', 'LaunchPad settings')" - :description=" - t('launchpad', 'Configure dashboard permissions and defaults') - " - docUrl="https://launchpad.conduction.nl/docs/intro"> - <!-- Setup wizard banner (REQ-WIZ-001). Stays at the top of the - page, above the Beheer tabs, so the call-to-action is always - the first thing the admin sees regardless of active tab. --> - <div - v-if="wizardState && !wizardState.complete" - class="launchpad-admin__wizard-banner" - data-test="setup-wizard-banner"> - <div> - <strong>{{ t('launchpad', 'Run setup wizard') }}</strong> - <p> - {{ - t( - 'launchpad', - 'Get your intranet started: choose storage, configure groups, install demo data, and set up admin roles.', - ) - }} - </p> + <!-- The board look: the shell draws the h1, the path line and the + Documentatie button, and lays its sections out as cards in two + columns (board LpBeheerAlgemeen). The shell's own `look` switches + the board look on. The open tab is in the page's path + (`/apps/launchpad/admin/<tab>`, REQ-ADM-030), not in `?tab=`. --> + <CnAdminSettingsShell + ref="shell" + appId="launchpad" + appName="Launchpad" + look="board" + :title="pageTitle" + docUrl="https://launchpad.conduction.nl/docs/intro" + :breadcrumbs="breadcrumbs" + :breadcrumbNote="breadcrumbNote" + :showVersionCard="false" + :tabs="beheerTabs" + tabsVariant="underline" + tabQueryKey="" + lazyTabs + @tabChange="onTabChange"> + <!-- Each tab draws its own content in the shell's `tab-<id>` slot. + With `lazyTabs` the shell mounts only the open tab's slot: it + fetches fresh on each visit, and the page does not load all + tabs at once. Algemeen's panel + holds the setup wizard banner (REQ-WIZ-001); its cards are the + shell's default slot, which shows on the first tab only. --> + <template #tab-general> + <div + v-if="wizardState && !wizardState.complete" + class="launchpad-admin__wizard-banner" + data-test="setup-wizard-banner"> + <div> + <strong>{{ t('launchpad', 'Run setup wizard') }}</strong> + <p> + {{ + t( + 'launchpad', + 'Get your intranet started: configure groups, install demo data, and set up admin roles.', + ) + }} + </p> + </div> + <NcButton + variant="secondary" + data-test="setup-wizard-open" + @click="openWizard"> + {{ t('launchpad', 'Run setup wizard') }} + </NcButton> </div> - <NcButton - variant="primary" - data-test="setup-wizard-open" - @click="openWizard"> - {{ t('launchpad', 'Run setup wizard') }} - </NcButton> - </div> - <div - v-else-if="wizardState && wizardState.complete" - class="launchpad-admin__wizard-rerun" - data-test="setup-wizard-rerun"> - <NcButton - variant="tertiary" - data-test="setup-wizard-rerun-open" - @click="openWizard"> - {{ t('launchpad', 'Run setup wizard again') }} - </NcButton> - </div> - - <!-- Global Settings — always visible above the tab strip. --> - <div - class="launchpad-admin__section" - data-testid="admin-default-settings"> - <h3>{{ t('launchpad', 'Default settings') }}</h3> + <div + v-else-if="wizardState && wizardState.complete" + class="launchpad-admin__wizard-rerun" + data-test="setup-wizard-rerun"> + <NcButton + variant="tertiary" + data-test="setup-wizard-rerun-open" + @click="openWizard"> + {{ t('launchpad', 'Run setup wizard again') }} + </NcButton> + </div> + </template> + <template #tab-templates> + <TemplatesPage /> + </template> + <template #tab-operations> + <OperationsTab /> + </template> + <template #tab-roles-permissions> + <RolesPermissionsTab /> + </template> + <template #tab-versioning-audit> + <VersioningAuditTab /> + </template> + <template #tab-sharing> + <SharingTab + :groups="injectedAllGroups" + :configuredGroups="configuredGroups" /> + </template> + <template #tab-embeds> + <EmbedsTab /> + </template> + <template #tab-kiosk> + <KioskTab /> + </template> + <template #tab-communities> + <CommunitiesTab /> + </template> + <template #tab-org-navigation> + <OrgNavigationTab :groups="injectedAllGroups" /> + </template> + <template #tab-demo-data> + <DemoDataTab /> + </template> + <template #tab-group-dashboards> + <GroupDashboardsTab /> + </template> + <template #tab-detail-fields> + <MetadataFieldsSettings /> + </template> + <template #tab-profile-fields> + <ProfileFieldsTab /> + </template> + <template #tab-search-shortcuts> + <SearchShortcutsTab /> + </template> + <template #tab-app-catalogue> + <AppCatalogueTab :groups="injectedAllGroups" /> + </template> + + <!-- Algemeen (board LpBeheerAlgemeen): the organisation-wide + defaults, group-shared dashboards and the default-app note, + each a card of the shell's grid. --> + <template v-if="activeTab === 'general'"> + <CnSettingsSection + :name="t('launchpad', 'Default settings')" + data-testid="admin-default-settings"> <div class="launchpad-admin__field"> <NcSelect @@ -66,6 +134,7 @@ </div> <NcCheckboxRadioSwitch + type="switch" :modelValue="settings.allowUserDashboards" data-testid="admin-allow-user-dashboards" @update:modelValue=" @@ -83,6 +152,7 @@ </p> <NcCheckboxRadioSwitch + type="switch" :modelValue="settings.allowMultipleDashboards" @update:modelValue=" updateSetting('allowMultipleDashboards', $event) @@ -90,6 +160,46 @@ {{ t('launchpad', 'Allow users to have multiple dashboards') }} </NcCheckboxRadioSwitch> + <!-- REQ-PSP-003: on by default; switching it off gives the + default app back. --> + <NcCheckboxRadioSwitch + type="switch" + :modelValue="settings.defaultAppEnabled" + data-testid="admin-default-app-enabled" + @update:modelValue=" + updateSetting('defaultAppEnabled', $event) + "> + {{ t('launchpad', 'Open LaunchPad after signing in') }} + </NcCheckboxRadioSwitch> + <p class="launchpad-admin__hint launchpad-admin__hint--inline"> + {{ + t( + 'launchpad', + 'When on, LaunchPad is the default app, so people land on their Workspace page after signing in. A default app chosen by the administrator is kept. Switching this off restores Nextcloud\'s own default.', + ) + }} + </p> + + <!-- drill-down-cross-widget-filter REQ-CWF-010: off by default; + only later filter changes are recorded. --> + <NcCheckboxRadioSwitch + type="switch" + :modelValue="settings.filterTelemetryEnabled" + data-testid="admin-filter-telemetry-enabled" + @update:modelValue=" + updateSetting('filterTelemetryEnabled', $event) + "> + {{ t('launchpad', 'Record how dashboard filters are used') }} + </NcCheckboxRadioSwitch> + <p class="launchpad-admin__hint launchpad-admin__hint--inline"> + {{ + t( + 'launchpad', + 'When on, applying, resetting or bookmarking dashboard filters records which dimensions were filtered, never the values. Earlier filter changes are not recorded.', + ) + }} + </p> + <div class="launchpad-admin__field"> <NcSelect v-model="settings.defaultGridColumns" @@ -144,15 +254,57 @@ }} </p> </div> - </div> - - <!-- Group-shared dashboards (REQ-DASH-015..017). Kept above the - tabs because it owns the `set-group-default` / - `group-default-badge` data-test hooks (task 12.2). --> - <div class="launchpad-admin__section"> - <div class="launchpad-admin__section-header"> - <h3>{{ t('launchpad', 'Group-shared dashboards') }}</h3> - </div> + </CnSettingsSection> + + <!-- REQ-ASET-021: the outside websites widgets may embed or fetch from. --> + <AllowedSitesSettings /> + + <!-- launcher-tile-launch-types: program schemes and sign-on templates. --> + <TileLaunchSettings /> + + <!-- launcher-tile-internal-address REQ-TIA-001: the office networks a + tile's office-network address is used on. Saved on its own, so a + malformed range never blocks the other settings. --> + <CnSettingsSection + :name="t('launchpad', 'Office networks')" + data-testid="admin-office-networks"> + <p class="launchpad-admin__hint"> + {{ + t( + 'launchpad', + 'On these networks a tile with an address on the office network opens that address. One IPv4 or IPv6 range per line, such as 10.20.0.0/16.', + ) + }} + </p> + <label class="launchpad-admin__label" for="launchpad-office-networks"> + {{ t('launchpad', 'Office network ranges') }} + </label> + <textarea + id="launchpad-office-networks" + v-model="officeNetworksText" + class="launchpad-admin__textarea" + rows="4" + data-testid="admin-office-networks-input" /> + <p + v-if="officeNetworksError" + class="launchpad-admin__error" + role="alert" + data-testid="admin-office-networks-error"> + {{ officeNetworksError }} + </p> + <p class="launchpad-admin__hint" data-testid="admin-office-networks-current"> + {{ currentAddressLine }} + </p> + <NcButton + data-testid="admin-office-networks-save" + @click="saveOfficeNetworks"> + {{ t('launchpad', 'Save office networks') }} + </NcButton> + </CnSettingsSection> + + <!-- Group-shared dashboards (REQ-DASH-015..017). Owns the + `set-group-default` / `group-default-badge` data-test hooks. --> + <CnSettingsSection :name="t('launchpad', 'Group-shared dashboards')"> <p class="launchpad-admin__hint"> {{ @@ -210,51 +362,9 @@ </div> </div> </div> - </div> - - <!-- Beheer tabs — the IA's discrete admin areas. Each tab's - content only renders when active (admin-settings spec). --> - <BeheerTabs - :tabs="beheerTabs" - defaultTab="templates" - @change="onTabChange"> - <template #templates> - <TemplatesPage /> - </template> - <template #operations> - <OperationsTab /> - </template> - <template #roles-permissions> - <RolesPermissionsTab /> - </template> - <template #versioning-audit> - <VersioningAuditTab /> - </template> - <template #sharing> - <SharingTab - :groups="injectedAllGroups" - :configuredGroups="configuredGroups" /> - </template> - <template #kiosk> - <KioskTab /> - </template> - <template #org-navigation> - <OrgNavigationTab :groups="injectedAllGroups" /> - </template> - <template #demo-data> - <DemoDataTab /> - </template> - <template #group-dashboards> - <GroupDashboardsTab /> - </template> - <template #detail-fields> - <MetadataFieldsSettings /> - </template> - </BeheerTabs> - - <!-- Info --> - <div class="launchpad-admin__section"> - <h3>{{ t('launchpad', 'Setting as default app') }}</h3> + </CnSettingsSection> + + <CnSettingsSection :name="t('launchpad', 'Setting as default app')"> <p> {{ t( @@ -263,8 +373,14 @@ ) }} </p> - </div> - </CnSettingsSection> + </CnSettingsSection> + + <!-- Administrator CSS, cleaned and scoped on save (REQ-THM-003). --> + <CnSettingsSection :name="t('launchpad', 'Custom CSS')"> + <AdminCustomCss /> + </CnSettingsSection> + </template> + </CnAdminSettingsShell> <!-- Setup wizard modal (REQ-WIZ-002). --> <SetupWizardModal @@ -272,59 +388,93 @@ data-test="setup-wizard-modal" @close="closeWizard" @completed="onWizardCompleted" /> + + <!-- runtime-shell REQ-SHELL-011: the admin page's own first-visit + tour. Mounted once the General tab has been open, so it starts on + the general settings and keeps running when the tab changes. --> + <CnWalkthrough + v-if="adminTourMounted" + :appId="adminTourWalkthroughKey" + :manifest="adminTour" + :seenVersion="adminTourSeen" + :translate="translateTour" + look="board" + @complete="onAdminTourComplete" /> </div> </template> <script> import { + CnAdminSettingsShell, CnDashboardIcon, CnSettingsSection, + CnWalkthrough, NcButton, NcCheckboxRadioSwitch, NcSelect, NcTextField, } from '@conduction/nextcloud-vue' +import { generateUrl } from '@nextcloud/router' import SetupWizardModal from '../../modals/SetupWizardModal.vue' -import BeheerTabs from './BeheerTabs.vue' +import AdminCustomCss from './AdminCustomCss.vue' +import AllowedSitesSettings from './AllowedSitesSettings.vue' import MetadataFieldsSettings from './MetadataFieldsSettings.vue' +import AppCatalogueTab from './tabs/AppCatalogueTab.vue' +import CommunitiesTab from './tabs/CommunitiesTab.vue' import DemoDataTab from './tabs/DemoDataTab.vue' +import EmbedsTab from './tabs/EmbedsTab.vue' import GroupDashboardsTab from './tabs/GroupDashboardsTab.vue' import KioskTab from './tabs/KioskTab.vue' import OperationsTab from './tabs/OperationsTab.vue' import OrgNavigationTab from './tabs/OrgNavigationTab.vue' +import ProfileFieldsTab from './tabs/ProfileFieldsTab.vue' import RolesPermissionsTab from './tabs/RolesPermissionsTab.vue' +import SearchShortcutsTab from './tabs/SearchShortcutsTab.vue' import SharingTab from './tabs/SharingTab.vue' import TemplatesPage from './tabs/TemplatesPage.vue' import VersioningAuditTab from './tabs/VersioningAuditTab.vue' +import TileLaunchSettings from './TileLaunchSettings.vue' +import manifest from '../../manifest.json' import { api } from '../../services/api.js' +import { adminTab } from '../../utils/adminPage.js' +import { ADMIN_TOUR_WALKTHROUGH_KEY, adminTourManifest, loadAdminTourSeen, persistAdminTourSeen } from '../../utils/adminWalkthrough.js' import { logger } from '../../utils/logger.js' export default { name: 'AdminSettings', components: { + AdminCustomCss, + AllowedSitesSettings, + CnAdminSettingsShell, CnSettingsSection, + CnWalkthrough, NcButton, NcSelect, NcCheckboxRadioSwitch, NcTextField, CnDashboardIcon, SetupWizardModal, - BeheerTabs, TemplatesPage, OperationsTab, + EmbedsTab, RolesPermissionsTab, VersioningAuditTab, MetadataFieldsSettings, + TileLaunchSettings, KioskTab, + CommunitiesTab, + ProfileFieldsTab, + SearchShortcutsTab, SharingTab, OrgNavigationTab, DemoDataTab, GroupDashboardsTab, + AppCatalogueTab, }, - // REQ-INIT-004: read the initial-state snapshot the PHP admin form - // pushes via `LaunchPadAdmin::getForm()`. Treated as a hint for the + // REQ-INIT-004: read the initial-state snapshot the administration page + // pushes via `AdminPageController::show()`. Treated as a hint for the // initial render only — `loadData()` overwrites with the API truth. inject: { injectedAllGroups: { from: 'allGroups', default: () => [] }, @@ -340,6 +490,20 @@ export default { }, }, + props: { + /** + * The tab the page's address names (REQ-ADM-030). An unknown or + * empty tab opens General. + */ + tab: { + type: String, + default: '', + }, + }, + + emits: ['tabChange'], + + /** @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 */ data() { return { loading: true, @@ -351,12 +515,20 @@ export default { allowUserDashboards: this.allowUserDashboards ?? false, allowMultipleDashboards: true, + // drill-down-cross-widget-filter REQ-CWF-010: off by default. + filterTelemetryEnabled: false, + // REQ-PSP-003: on by default. + defaultAppEnabled: true, defaultGridColumns: 12, // dashboard-quota-limits REQ-QUOTA-001 — `0` = unlimited. maxDashboardsPerUser: 0, maxWidgetsPerDashboard: 0, }, + // launcher-tile-internal-address REQ-TIA-001. + officeNetworksText: '', + officeNetworksError: '', + permissionOptions: [ { id: 'view_only', label: this.t('launchpad', 'View only') }, { id: 'add_only', label: this.t('launchpad', 'Add only') }, @@ -371,65 +543,249 @@ export default { // Setup wizard banner state (REQ-WIZ-001). wizardState: null, showWizard: false, - activeTab: 'templates', + activeTab: adminTab(this.tab), + // runtime-shell REQ-SHELL-011: the admin tour, its seen version + // (null until loaded) and whether it has been mounted. + adminTour: adminTourManifest(manifest), + adminTourWalkthroughKey: ADMIN_TOUR_WALKTHROUGH_KEY, + adminTourSeen: null, + adminTourMounted: false, } }, computed: { + /** + * Whether the admin tour may be mounted now: there is one, its seen + * version is loaded, and the General tab is open (REQ-SHELL-011). + * + * @return {boolean} + * @spec openspec/changes/record-parity-requirements/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + */ + adminTourReady() { + return this.adminTour !== null && this.adminTourSeen !== null && this.activeTab === 'general' + }, + + /** + * The administrator's own address and whether it is inside the + * office networks, so a wrong proxy setup shows at once. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-administrators-declare-the-office-networks-req-tia-001 + */ + currentAddressLine() { + const address = this.settings.currentAddress || '' + if (address === '') { + return '' + } + if (this.settings.currentAddressInOfficeNetworks === true) { + return this.t('launchpad', 'Your current address is {address}, which is inside the office networks.', { address }) + } + return this.t('launchpad', 'Your current address is {address}, which is outside the office networks.', { address }) + }, + + /** + * The page title names the open tab, as the boards do + * ("Launchpad-beheer: algemeen"). + * + * @spec openspec/specs/admin-settings/spec.md + * @return {string} + */ + pageTitle() { + const tab = this.beheerTabs.find((entry) => entry.id === this.activeTab) + const label = tab ? tab.label.toLocaleLowerCase() : '' + // The tab name goes into text interpolation, which escapes it again. + return this.t('launchpad', 'Launchpad administration: {tab}', { tab: label }, undefined, { escape: false }) + }, + + /** + * The path line under the title: the Nextcloud administration + * settings, the app, then the open tab. + * + * @spec openspec/specs/admin-settings/spec.md + * @return {Array<{label: string, href?: string}>} + */ + breadcrumbs() { + const tab = this.beheerTabs.find((entry) => entry.id === this.activeTab) + const crumbs = [ + { + label: this.t('launchpad', 'Administration settings'), + href: generateUrl('/settings/admin'), + }, + { label: 'Launchpad' }, + ] + if (tab) { + crumbs.push({ label: tab.label }) + } + return crumbs + }, + + /** + * The note after the path. Only Algemeen has one: its settings hold + * for the whole organisation. + * + * @spec openspec/specs/admin-settings/spec.md + * @return {string} + */ + breadcrumbNote() { + return this.activeTab === 'general' + ? this.t('launchpad', 'applies to the whole organisation') + : '' + }, + /** * Ordered Beheer tab descriptors. Labels live here so they stay - * translatable in one place; the slugs match the named slots. + * translatable in one place; each `id` after the first names the shell slot + * `tab-<id>`; the first tab is the default slot. * * @spec openspec/changes/admin-group-management/tasks.md#task-1 - * @return {Array<{slug: string, label: string}>} + * @return {Array<{id: string, label: string}>} */ beheerTabs() { return [ - { slug: 'templates', label: this.t('launchpad', 'Templates') }, - { slug: 'operations', label: this.t('launchpad', 'Operations') }, + { id: 'general', label: this.t('launchpad', 'General') }, + { id: 'templates', label: this.t('launchpad', 'Templates') }, + { id: 'operations', label: this.t('launchpad', 'Controls') }, { - slug: 'roles-permissions', - label: this.t('launchpad', 'Roles & Permissions'), + id: 'roles-permissions', + label: this.t('launchpad', 'Roles and permissions'), }, { - slug: 'versioning-audit', - label: this.t('launchpad', 'Versioning & Audit'), + id: 'versioning-audit', + label: this.t('launchpad', 'Versions and analytics'), }, - { slug: 'sharing', label: this.t('launchpad', 'Sharing') }, - { slug: 'kiosk', label: this.t('launchpad', 'Kiosk') }, + { id: 'sharing', label: this.t('launchpad', 'Sharing') }, + { id: 'embeds', label: this.t('launchpad', 'Embeds') }, + { id: 'kiosk', label: this.t('launchpad', 'Kiosk') }, + { id: 'communities', label: this.t('launchpad', 'Communities') }, { - slug: 'org-navigation', - label: this.t('launchpad', 'Org navigation'), + id: 'org-navigation', + label: this.t('launchpad', 'Organisation menu'), }, - { slug: 'demo-data', label: this.t('launchpad', 'Demo data') }, + { id: 'demo-data', label: this.t('launchpad', 'Demo data') }, { - slug: 'group-dashboards', + id: 'group-dashboards', label: this.t('launchpad', 'Group dashboards'), }, { - slug: 'detail-fields', + id: 'detail-fields', label: this.t('launchpad', 'Detail fields'), }, + { + id: 'profile-fields', + label: this.t('launchpad', 'Profile fields'), + }, + { + id: 'search-shortcuts', + label: this.t('launchpad', 'Search shortcuts'), + }, + { + id: 'app-catalogue', + label: this.t('launchpad', 'App catalogue'), + }, ] }, }, /** @spec openspec/specs/admin-settings/spec.md */ + watch: { + /** + * Open the tab the address names when it changes (Back, Forward). + * + * @param {string} tab The tab the address names. + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ + tab(tab) { + this.showTab(adminTab(tab)) + }, + + /** + * Mount the admin tour once it is ready, and keep it mounted when the + * tab changes so a running tour continues (REQ-SHELL-011). + * + * @param {boolean} ready Whether the tour may be mounted. + * @spec openspec/changes/record-parity-requirements/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + */ + adminTourReady: { + immediate: true, + handler(ready) { + if (ready) { + this.adminTourMounted = true + } + }, + }, + }, + async created() { + this.loadAdminTour() await this.loadData() await this.loadGroupSharedDashboards() await this.loadWizardState() }, + /** @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 */ + mounted() { + this.showTab(this.activeTab) + }, + methods: { /** - * Switch the active admin tab. + * Switch the active admin tab, and tell the page so its address + * names the tab. * - * @param {string} slug Slug of the newly selected tab. + * @param {string} id The id of the newly opened tab. * @spec openspec/specs/admin-settings/spec.md + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 */ - onTabChange(slug) { - this.activeTab = slug + onTabChange(id) { + this.activeTab = id + this.$emit('tabChange', id) + }, + + /** + * Open a tab without a click: the one the address names. + * + * @param {string} id The tab's id. + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ + showTab(id) { + this.activeTab = id + const shell = this.$refs.shell + if (shell && shell.chosenTabId !== id) { + shell.chosenTabId = id + } + }, + + /** + * Read whether this administrator finished the admin tour (REQ-SHELL-011). + * + * @return {Promise<void>} + * @spec openspec/changes/record-parity-requirements/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + */ + async loadAdminTour() { + if (this.adminTour) { + this.adminTourSeen = await loadAdminTourSeen('launchpad') + } + }, + + /** + * Record the admin tour as finished, so it does not start again (REQ-SHELL-011). + * + * @return {void} + * @spec openspec/changes/record-parity-requirements/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + */ + onAdminTourComplete() { + this.adminTourSeen = String(this.adminTour.version || '') + persistAdminTourSeen('launchpad', this.adminTourSeen) + }, + + /** + * Translate a tour title, body or task through LaunchPad's catalogue. + * + * @param {string} text The source string. + * @return {string} + */ + translateTour(text) { + return this.t('launchpad', text) }, /** @spec openspec/specs/admin-settings/spec.md */ @@ -439,6 +795,7 @@ export default { const settingsRes = await api.getAdminSettings() const data = settingsRes.data?.data ?? settingsRes.data if (data) { + this.officeNetworksText = (Array.isArray(data.officeNetworks) ? data.officeNetworks : []).join('\n') this.settings = { ...this.settings, ...data, @@ -462,6 +819,9 @@ export default { defaultPermLevel: this.settings.defaultPermissionLevel?.id, allowUserDash: this.settings.allowUserDashboards, allowMultiDash: this.settings.allowMultipleDashboards, + filterTelemetryEnabled: + this.settings.filterTelemetryEnabled === true, + defaultAppEnabled: this.settings.defaultAppEnabled !== false, defaultGridCols: this.settings.defaultGridColumns, // dashboard-quota-limits REQ-QUOTA-001 — sent as integers; // the server clamps into [0, 10000]. @@ -477,6 +837,36 @@ export default { } }, + /** + * Save the office networks, one range per line, and show the server's + * verdict on the administrator's own address. A malformed range is + * refused by the server and nothing is stored. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-administrators-declare-the-office-networks-req-tia-001 + */ + async saveOfficeNetworks() { + this.officeNetworksError = '' + const ranges = this.officeNetworksText + .split(/[\n,]+/) + .map((range) => range.trim()) + .filter((range) => range !== '') + try { + await api.updateAdminSettings({ officeNetworks: ranges }) + } catch (error) { + this.officeNetworksError = this.t('launchpad', 'This is not a valid network range') + // The server names the range it refused after a colon; keep the + // translated sentence and add that range to it. + const detail = error?.response?.data?.error || error?.response?.data?.message + const named = typeof detail === 'string' ? detail.match(/^This is not a valid network range: (.+)$/) : null + if (named) { + this.officeNetworksError += ': ' + named[1] + } + return + } + await this.loadData() + }, + /** * Write one setting and persist the whole set. * @@ -655,31 +1045,6 @@ export default { </script> <style scoped> -.launchpad-admin { - max-width: 900px; -} - -.launchpad-admin__section { - margin-bottom: 32px; - padding-bottom: 32px; - border-bottom: 1px solid var(--color-border); -} - -.launchpad-admin__section h3 { - margin: 0 0 16px; -} - -.launchpad-admin__section-header { - display: flex; - align-items: center; - justify-content: space-between; - margin-bottom: 16px; -} - -.launchpad-admin__section-header h3 { - margin: 0; -} - .launchpad-admin__hint { color: var(--color-text-maxcontrast); margin-bottom: 16px; @@ -749,10 +1114,8 @@ export default { justify-content: space-between; gap: 16px; padding: 16px 20px; - margin-bottom: 24px; background: var(--color-primary-element-light); - border: 1px solid var(--color-primary-element); - border-radius: var(--border-radius); + border-radius: 12px; } .launchpad-admin__wizard-banner p { @@ -762,8 +1125,23 @@ export default { } .launchpad-admin__wizard-rerun { - margin-bottom: 16px; display: flex; justify-content: flex-end; } + +.launchpad-admin__label { + display: block; + margin-top: 8px; + font-weight: bold; +} + +.launchpad-admin__textarea { + width: 100%; + max-width: 480px; + font-family: monospace; +} + +.launchpad-admin__error { + color: var(--color-error-text); +} </style> diff --git a/src/components/admin/AllowedSitesSettings.vue b/src/components/admin/AllowedSitesSettings.vue new file mode 100644 index 000000000..c7314af40 --- /dev/null +++ b/src/components/admin/AllowedSitesSettings.vue @@ -0,0 +1,264 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <!-- REQ-ASET-021 (board LpBeheerAlgemeen): one list of the outside + websites widgets may embed or fetch from. The server normalises every + host and refuses an entry that is not one; its message shows here. --> + <CnSettingsSection + :name="t('launchpad', 'Allowed websites')" + data-testid="admin-allowed-sites"> + <p class="allowed-sites__hint"> + {{ t('launchpad', 'Widgets may only embed pages and fetch data from these sites.') }} + </p> + + <ul v-if="rows.length > 0" class="allowed-sites__list" data-testid="admin-allowed-sites-list"> + <li + v-for="row in rows" + :key="row.host" + class="allowed-sites__item" + data-testid="admin-allowed-site"> + <code class="allowed-sites__host">{{ row.host }}</code> + <NcSelect + :modelValue="optionFor(row.purpose)" + :options="purposeOptions" + :clearable="false" + :disabled="!loaded || saving" + :aria-label-combobox="t('launchpad', 'Purpose of {host}', { host: row.host })" + label="label" + class="allowed-sites__purpose" + @update:modelValue="(option) => setPurpose(row.host, option)" /> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove {host}', { host: row.host })" + :disabled="saving" + @click="removeRow(row.host)"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </li> + </ul> + <p v-else-if="loaded" class="allowed-sites__hint" data-testid="admin-allowed-sites-empty"> + {{ t('launchpad', 'No websites on this list yet.') }} + </p> + + <form class="allowed-sites__add" @submit.prevent="add"> + <NcTextField + v-model="newHost" + :label="t('launchpad', 'Website')" + :helperText="t('launchpad', 'A host such as www.example.com, without https:// or a path.')" + data-testid="admin-allowed-site-input" /> + <NcSelect + v-model="newPurpose" + :options="purposeOptions" + :clearable="false" + :inputLabel="t('launchpad', 'Purpose')" + label="label" + class="allowed-sites__purpose" + data-testid="admin-allowed-site-purpose" /> + <NcButton + type="submit" + :disabled="newHost.trim() === '' || saving" + data-testid="admin-allowed-site-add"> + {{ t('launchpad', 'Add website') }} + </NcButton> + </form> + + <p + v-if="error" + class="allowed-sites__error" + role="alert" + data-testid="admin-allowed-sites-error"> + {{ error }} + </p> + <div class="allowed-sites__actions"> + <NcButton + variant="primary" + :disabled="!loaded || saving" + data-testid="admin-allowed-sites-save" + @click="save"> + {{ t('launchpad', 'Save') }} + </NcButton> + </div> + </CnSettingsSection> +</template> + +<script> +import { CnSettingsSection, NcButton, NcSelect, NcTextField } from '@conduction/nextcloud-vue' +import { showSuccess } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' +import { api } from '../../services/api.js' +import { addRow, PURPOSES, rowsFrom, siteFor } from '../../utils/allowedSites.js' +import { logger } from '../../utils/logger.js' + +/** + * AllowedSitesSettings — the General tab's "Allowed websites" block + * (REQ-ASET-021): hosts with their purpose, Add website and Save. + * + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ +export default { + name: 'AllowedSitesSettings', + + components: { + CnSettingsSection, + NcButton, + NcSelect, + NcTextField, + }, + + data() { + return { + rows: [], + newHost: '', + newPurpose: null, + error: '', + loaded: false, + saving: false, + } + }, + + computed: { + /** + * @return {Array<{id: string, label: string}>} The purposes, translated. + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + purposeOptions() { + const labels = { + embed: t('launchpad', 'Embed'), + fetch: t('launchpad', 'Fetch'), + both: t('launchpad', 'Embed and fetch'), + } + return PURPOSES.map((id) => ({ id, label: labels[id] })) + }, + }, + + /** @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 */ + created() { + this.newPurpose = this.optionFor('embed') + this.load() + }, + + methods: { + t, + + /** + * @param {string} purpose The purpose id. + * @return {{id: string, label: string}} Its select option. + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + optionFor(purpose) { + return this.purposeOptions.find((option) => option.id === purpose) ?? this.purposeOptions[0] + }, + + /** + * Read the stored list. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + async load() { + try { + const { data } = await api.getAllowedSites() + this.rows = rowsFrom(data) + } catch (error) { + logger.error('Failed to load the allowed websites:', error) + } finally { + this.loaded = true + } + }, + + /** + * Add the entered host with the chosen purpose (saved with Save). + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + add() { + this.rows = addRow(this.rows, this.newHost, this.newPurpose?.id ?? 'embed') + this.newHost = '' + }, + + /** + * @param {string} host The row's host. + * @param {{id: string}|null} option The chosen purpose. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + setPurpose(host, option) { + this.rows = addRow(this.rows, host, option?.id ?? 'embed') + }, + + /** + * @param {string} host The row's host. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + removeRow(host) { + this.rows = this.rows.filter((row) => row.host !== host) + }, + + /** + * Save the list; the server's refusal is shown as it is. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + async save() { + this.saving = true + this.error = '' + try { + const { data } = await api.updateAllowedSites(this.rows.map((row) => siteFor(row.host, row.purpose))) + this.rows = rowsFrom(data) + showSuccess(t('launchpad', 'Allowed websites saved.')) + } catch (error) { + logger.error('Failed to save the allowed websites:', error) + this.error = error?.response?.data?.message || t('launchpad', 'The allowed websites could not be saved.') + } finally { + this.saving = false + } + }, + }, +} +</script> + +<style scoped> +.allowed-sites__hint { + color: var(--color-text-maxcontrast); + margin-bottom: 12px; +} + +.allowed-sites__list { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 16px; +} + +.allowed-sites__item, +.allowed-sites__add { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.allowed-sites__host { + flex: 1 1 200px; + overflow-wrap: anywhere; +} + +.allowed-sites__purpose { + min-width: 180px; +} + +.allowed-sites__error { + color: var(--color-error-text); + margin-top: 8px; +} + +.allowed-sites__actions { + margin-top: 16px; +} +</style> diff --git a/src/components/admin/AnnouncementEditorsPolicy.vue b/src/components/admin/AnnouncementEditorsPolicy.vue new file mode 100644 index 000000000..8578a28cc --- /dev/null +++ b/src/components/admin/AnnouncementEditorsPolicy.vue @@ -0,0 +1,96 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="announcement-editors" data-test="announcement-editors-policy"> + <h3>{{ t('launchpad', 'Announcement editors') }}</h3> + <p class="announcement-editors__hint"> + {{ t('launchpad', 'Members of these groups may write and publish announcements. Administrators always may.') }} + </p> + <NcSelectTags + v-model="editorGroups" + :options="groups" + :multiple="true" + :aria-label-combobox="t('launchpad', 'Announcement editor groups')" + :placeholder="t('launchpad', 'Select groups (leave empty for administrators only)')" + data-test="announcement-editor-groups" + @update:modelValue="save" /> + </div> +</template> + +<script> +import { NcSelectTags } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +/** + * AnnouncementEditorsPolicy — Beheer ▸ Sharing: the groups whose members + * may write announcements besides administrators (engagement-announcements + * D6). Reads and writes `announcementEditorGroups` through the admin + * settings API. + * + * @spec openspec/changes/engagement-announcements/tasks.md#task-2 + */ +export default { + name: 'AnnouncementEditorsPolicy', + + components: { + NcSelectTags, + }, + + props: { + /** Group ids offered in the picker. */ + groups: { + type: Array, + default: () => [], + }, + }, + + data() { + return { + editorGroups: [], + } + }, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-2 */ + created() { + this.load() + }, + + methods: { + t, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-2 */ + async load() { + try { + const { data } = await api.getAdminSettings() + const settings = data?.data ?? data ?? {} + this.editorGroups = Array.isArray(settings.announcementEditorGroups) + ? settings.announcementEditorGroups + : [] + } catch (error) { + logger.error('Failed to load announcement editors:', error) + } + }, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-2 */ + async save() { + try { + await api.updateAdminSettings({ announcementEditorGroups: this.editorGroups }) + } catch (error) { + logger.error('Failed to save announcement editors:', error) + } + }, + }, +} +</script> + +<style scoped> +.announcement-editors__hint { + color: var(--color-text-maxcontrast); + margin-bottom: 16px; +} +</style> diff --git a/src/components/admin/BeheerTabs.vue b/src/components/admin/BeheerTabs.vue deleted file mode 100644 index 3e52942c3..000000000 --- a/src/components/admin/BeheerTabs.vue +++ /dev/null @@ -1,238 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <div class="beheer-tabs" data-test="beheer-tabs"> - <div - class="beheer-tabs__strip" - role="tablist" - :aria-label="t('launchpad', 'Administration areas')"> - <button - v-for="tab in tabs" - :key="tab.slug" - type="button" - role="tab" - class="beheer-tabs__tab" - :class="{ 'beheer-tabs__tab--active': tab.slug === activeTab }" - :data-test="`tab-${tab.slug}`" - :aria-selected="String(tab.slug === activeTab)" - @click="selectTab(tab.slug)"> - {{ tab.label }} - </button> - </div> - - <div - class="beheer-tabs__panel" - role="tabpanel" - :data-test="`panel-${activeTab}`"> - <slot :name="activeTab" /> - </div> - </div> -</template> - -<script> -import { t } from '@nextcloud/l10n' - -/** - * Storage key for the persisted active Beheer tab. Exported so tests and - * the admin shell agree on the exact key (REQ-ASET tabbed Beheer layout). - * - * @type {string} - */ -export const ACTIVE_TAB_STORAGE_KEY = 'launchpad.admin.activeTab' - -/** - * BeheerTabs — a lightweight, router-free tab strip that organises the - * admin settings page into the IA's discrete Beheer areas. The active tab - * resolves with the precedence: - * 1. a `?tab=` query string (deep-link round-trip), else - * 2. the persisted `localStorage` value, else - * 3. the `defaultTab` prop (Templates by default). - * - * Only the active tab's slot is rendered, so no other tab's content sits in - * the DOM (admin-settings spec: "no other tab's content MUST be in the DOM"). - * Selecting a tab writes the slug to `localStorage` so it survives reloads. - */ -export default { - name: 'BeheerTabs', - - props: { - /** - * Ordered tab descriptors: `{ slug, label }`. The parent owns the - * labels so they stay translatable in one place. - */ - tabs: { - type: Array, - required: true, - validator: (value) => - Array.isArray(value) - && value.every( - (tab) => - typeof tab.slug === 'string' - && typeof tab.label === 'string', - ), - }, - - /** - * Slug used when neither a `?tab=` query nor a persisted value is - * present (admin-settings spec: Templates is the canonical landing). - */ - defaultTab: { - type: String, - default: '', - }, - }, - - emits: ['change'], - - data() { - return { - activeTab: '', - } - }, - - /** @spec openspec/specs/admin-settings/spec.md */ - created() { - this.activeTab = this.resolveInitialTab() - this.$emit('change', this.activeTab) - }, - - methods: { - t, - - /** - * Resolve the tab to show on first paint. The `?tab=` query string - * wins so deep-links round-trip on reload; otherwise the persisted - * value, otherwise the `defaultTab`, otherwise the first tab. The - * resolved value is always one of the known tab slugs. - * - * @return {string} The slug to activate. - */ - /** - * Pick the tab to open from the URL query, falling back to the - * configured default and then to the first known tab. - * - * @spec exclude in-component tab routing — reads the query string and the component's own `tabs`/`defaultTab` props to choose an initial slug. It encodes no admin-settings behaviour: which tabs exist, and what each one does, is specified and tagged where those tabs are defined. - * @return {string} The slug of the tab to activate. - */ - resolveInitialTab() { - const known = this.tabs.map((tab) => tab.slug) - const fallback = known.includes(this.defaultTab) - ? this.defaultTab - : known[0] || '' - - const fromQuery = this.readQueryTab() - if (fromQuery && known.includes(fromQuery)) { - return fromQuery - } - - const fromStorage = this.readStoredTab() - if (fromStorage && known.includes(fromStorage)) { - return fromStorage - } - - return fallback - }, - - /** - * Read the `tab` query-string parameter, tolerating environments - * (tests, SSR) where `window`/`URLSearchParams` is unavailable. - * - * @return {string|null} The requested tab slug, or null. - * @spec exclude in-component tab routing — reads the query string, `localStorage` and the component's own `tabs`/`defaultTab` props to choose a slug. It encodes no admin-settings behaviour: which tabs exist, and what each one does, is specified and tagged where those tabs are defined. - */ - readQueryTab() { - try { - if (typeof window === 'undefined' || !window.location) { - return null - } - const params = new URLSearchParams(window.location.search || '') - return params.get('tab') - } catch { - return null - } - }, - - /** - * Read the persisted tab slug from `localStorage`. - * - * @return {string|null} The persisted slug, or null. - * @spec exclude in-component tab routing — reads the query string, `localStorage` and the component's own `tabs`/`defaultTab` props to choose a slug. It encodes no admin-settings behaviour: which tabs exist, and what each one does, is specified and tagged where those tabs are defined. - */ - readStoredTab() { - try { - if (typeof localStorage === 'undefined') { - return null - } - return localStorage.getItem(ACTIVE_TAB_STORAGE_KEY) - } catch { - return null - } - }, - - /** - * Activate a tab, persist the choice, and notify the parent. A - * no-op when the slug is already active. - * - * @param {string} slug The tab slug to activate. - * @return {void} - * @spec exclude in-component tab routing — reads the query string, `localStorage` and the component's own `tabs`/`defaultTab` props to choose a slug. It encodes no admin-settings behaviour: which tabs exist, and what each one does, is specified and tagged where those tabs are defined. - */ - selectTab(slug) { - if (slug === this.activeTab) { - return - } - this.activeTab = slug - try { - if (typeof localStorage !== 'undefined') { - localStorage.setItem(ACTIVE_TAB_STORAGE_KEY, slug) - } - } catch { - // localStorage may be unavailable (private mode); the tab - // still switches for the current session. - } - this.$emit('change', slug) - }, - }, -} -</script> - -<style scoped> -.beheer-tabs__strip { - display: flex; - flex-wrap: wrap; - gap: 4px; - border-bottom: 1px solid var(--color-border); - margin-bottom: 24px; -} - -.beheer-tabs__tab { - background: transparent; - border: 0; - border-bottom: 2px solid transparent; - padding: 10px 16px; - cursor: pointer; - font: inherit; - color: var(--color-text-maxcontrast); - border-radius: var(--border-radius) var(--border-radius) 0 0; -} - -.beheer-tabs__tab:hover, -.beheer-tabs__tab:focus-visible { - background: var(--color-background-hover); - color: var(--color-main-text); - outline: none; -} - -.beheer-tabs__tab--active { - color: var(--color-main-text); - border-bottom-color: var(--color-primary-element); - font-weight: 600; -} - -.beheer-tabs__panel { - min-height: 120px; -} -</style> diff --git a/src/components/admin/DashboardBulkOperations.vue b/src/components/admin/DashboardBulkOperations.vue index 8b9a4db3c..cd02d4287 100644 --- a/src/components/admin/DashboardBulkOperations.vue +++ b/src/components/admin/DashboardBulkOperations.vue @@ -232,6 +232,56 @@ <script> import { api } from '../../services/api.js' +const CHANGED_COUNT_KEYS = [ + 'deletedCount', + 'movedCount', + 'updatedCount', + 'reindexedCount', + 'wouldDeleteCount', + 'wouldMoveCount', + 'wouldUpdateCount', + 'wouldReindexCount', +] + +const SKIPPED_COUNT_KEYS = ['skippedCount', 'wouldSkipCount'] + +/** + * The first count among `keys` that is set (not null or undefined), else 0. + * + * @param {object} data The bulk-result envelope. + * @param {string[]} keys The count keys, in order of preference. + * @return {number} The count. + */ +function firstCount(data, keys) { + const key = keys.find((name) => (data[name] ?? null) !== null) + return key === undefined ? 0 : data[key] +} + +/** + * The server's error text for a failed bulk request, or a generic message. + * + * @param {Error} e The rejected request's error. + * @return {string} The message to show. + */ +function bulkErrorMessage(e) { + return e?.response?.data?.error || t('launchpad', 'Bulk operation failed') +} + +/** + * Summarise a bulk-result envelope for the result panel. + * + * @param {object} data The bulk-result envelope. + * @return {object} The dry-run flag, changed and skipped counts, and errors. + */ +function bulkResultSummary(data) { + return { + dryRun: !!data.dryRun, + changed: firstCount(data, CHANGED_COUNT_KEYS), + skipped: firstCount(data, SKIPPED_COUNT_KEYS), + errors: Array.isArray(data.errors) ? data.errors : [], + } +} + export default { name: 'DashboardBulkOperations', @@ -277,7 +327,7 @@ export default { this.loading = true try { const { data } = await api.getVisibleDashboards() - this.dashboards = Array.isArray(data) ? data : data.dashboards || [] + this.dashboards = Array.isArray(data) ? data : (data?.items ?? []) } catch { this.errorMessage = t('launchpad', 'Failed to load dashboards') } finally { @@ -359,71 +409,78 @@ export default { this.modal = null }, - /** @spec openspec/specs/dashboard-bulk-operations/spec.md */ - async confirmAction() { - this.running = true - try { - const opts = { dryRun: this.dryRun } - let response - if (this.modal.action === 'delete') { - response = await api.bulkDeleteDashboards( - this.selectedUuids, - opts, - ) - } else if (this.modal.action === 'move') { - const parent = - this.parentUuidInput.trim() === '' - ? null - : this.parentUuidInput.trim() - response = await api.bulkMoveDashboards( + /** + * Send the pending bulk action to the server. + * + * @param {object} opts The shared request options (dry run). + * @return {Promise|undefined} The request, or undefined for an unknown action. + * @spec openspec/specs/dashboard-bulk-operations/spec.md + */ + sendBulkRequest(opts) { + const requests = { + delete: () => api.bulkDeleteDashboards(this.selectedUuids, opts), + move: () => + api.bulkMoveDashboards( this.selectedUuids, - parent, + this.parentUuidOrNull(), opts, - ) - } else if (this.modal.action === 'status') { - const extra = { ...opts } - if (this.statusInput === 'scheduled') { - extra.publishAt = this.publishAtInput - } - response = await api.bulkStatusDashboards( + ), + + status: () => + api.bulkStatusDashboards( this.selectedUuids, this.statusInput, - extra, - ) - } else if (this.modal.action === 'reindex') { - response = await api.bulkReindexDashboards( - this.selectedUuids, - opts, - ) - } + this.statusRequestOptions(opts), + ), + + reindex: () => api.bulkReindexDashboards(this.selectedUuids, opts), + } + const action = this.modal.action + return Object.hasOwn(requests, action) ? requests[action]() : undefined + }, + + /** + * The trimmed parent UUID, or null to move to the root. + * + * @return {string|null} The new parent's UUID or null. + * @spec openspec/specs/dashboard-bulk-operations/spec.md + */ + parentUuidOrNull() { + const parent = this.parentUuidInput.trim() + return parent === '' ? null : parent + }, + + /** + * The status request options: the shared options plus the publish + * date when the status is scheduled. + * + * @param {object} opts The shared request options (dry run). + * @return {object} The options for the status request. + * @spec openspec/specs/dashboard-bulk-operations/spec.md + */ + statusRequestOptions(opts) { + const extra = { ...opts } + if (this.statusInput === 'scheduled') { + extra.publishAt = this.publishAtInput + } + return extra + }, + /** @spec openspec/specs/dashboard-bulk-operations/spec.md */ + async confirmAction() { + this.running = true + try { + const request = this.sendBulkRequest({ dryRun: this.dryRun }) + const response = request === undefined ? undefined : await request const data = response?.data || {} - const changed = - data.deletedCount - ?? data.movedCount - ?? data.updatedCount - ?? data.reindexedCount - ?? data.wouldDeleteCount - ?? data.wouldMoveCount - ?? data.wouldUpdateCount - ?? data.wouldReindexCount - ?? 0 - const skipped = data.skippedCount ?? data.wouldSkipCount ?? 0 - this.resultSummary = { - dryRun: !!data.dryRun, - changed, - skipped, - errors: Array.isArray(data.errors) ? data.errors : [], - } + this.resultSummary = bulkResultSummary(data) if (!data.dryRun) { this.selectedUuids = [] this.loadDashboards() } } catch (e) { - this.errorMessage = - e?.response?.data?.error - || t('launchpad', 'Bulk operation failed') + this.errorMessage = bulkErrorMessage(e) } finally { this.running = false this.modal = null diff --git a/src/components/admin/DashboardRegistrySettings.vue b/src/components/admin/DashboardRegistrySettings.vue index 07b971175..b8471b9e9 100644 --- a/src/components/admin/DashboardRegistrySettings.vue +++ b/src/components/admin/DashboardRegistrySettings.vue @@ -6,8 +6,8 @@ <template> <!-- `section-dashboard-registry` is the anchor lib/Settings/connections.json links the Dashboard registry row to (adopt-connection-registry). Keep the - id stable. The link also carries ?tab=sharing, because BeheerTabs only - renders the active tab. --> + id stable. The link also carries ?tab=sharing, because the admin page + only mounts the open tab's content. --> <div id="section-dashboard-registry" class="registry-settings" @@ -46,6 +46,17 @@ data-test="registry-url" /> </div> + <div class="registry-settings__field"> + <!-- REQ-STORE-010: the name the marketplace banner shows. --> + <NcTextField + v-model="registryName" + :label="t('launchpad', 'Register name')" + :helperText="t('launchpad', 'Shown on the marketplace. Leave empty to show the address.')" + autocomplete="off" + :disabled="!loaded || saving" + data-test="registry-name" /> + </div> + <div class="registry-settings__field"> <NcTextField v-model="registryRegister" @@ -146,6 +157,7 @@ export default { return { registryUrl: '', registryRegister: '', + registryName: '', tokenInput: '', tokenConfigured: false, available: true, @@ -181,15 +193,17 @@ export default { }, /** - * Save the URL and register, and the token only when one was typed. + * Save the URL, register and name, and the token only when one was typed. * * @spec openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md#requirement-req-store-009-an-administrator-must-be-able-to-connect-a-registry-without-a-shell + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-010-the-marketplace-shows-dashboard-templates-as-cards * @return {Promise<void>} */ async save() { const payload = { registryUrl: this.registryUrl.trim(), registryRegister: this.registryRegister.trim(), + registryName: this.registryName.trim(), } if (this.tokenInput !== '') { payload.registryToken = this.tokenInput @@ -236,6 +250,7 @@ export default { * nothing to give back. * * @spec openspec/changes/store-plane-dashboard-sharing/specs/dashboard-store/spec.md#requirement-req-store-009-an-administrator-must-be-able-to-connect-a-registry-without-a-shell + * @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-010-the-marketplace-shows-dashboard-templates-as-cards * @param {object} data The redacted connection. */ apply(data) { @@ -245,6 +260,8 @@ export default { typeof data?.registryRegister === 'string' ? data.registryRegister : '' + this.registryName = + typeof data?.registryName === 'string' ? data.registryName : '' this.tokenConfigured = data?.tokenConfigured === true this.tokenInput = '' }, diff --git a/src/components/admin/DashboardSharingPolicy.vue b/src/components/admin/DashboardSharingPolicy.vue index fbfb88243..a77984a8f 100644 --- a/src/components/admin/DashboardSharingPolicy.vue +++ b/src/components/admin/DashboardSharingPolicy.vue @@ -48,15 +48,103 @@ }} </p> </div> + + <!-- REQ-SHARE-015 (board LpBeheerDelen): Everyone, Only these groups or Nobody. --> + <fieldset class="sharing-policy__field sharing-policy__choices" data-test="sharing-policy-allowed"> + <legend class="sharing-policy__label"> + {{ t('launchpad', 'Sharing allowed for') }} + </legend> + <NcCheckboxRadioSwitch + v-for="choice in allowedChoices" + :key="choice.id" + :modelValue="sharingAllowed" + :value="choice.id" + type="radio" + name="launchpad-sharing-allowed" + :data-test="`sharing-policy-allowed-choice-${choice.id}`" + @update:modelValue="onAllowedChange"> + {{ choice.label }} + </NcCheckboxRadioSwitch> + </fieldset> + + <div v-if="sharingAllowed === 'groups'" class="sharing-policy__field"> + <label class="sharing-policy__label"> + {{ t('launchpad', 'Groups that may share') }} + </label> + <NcSelectTags + v-model="allowedGroups" + :options="groups" + :multiple="true" + :aria-label-combobox="t('launchpad', 'Groups that may share')" + :placeholder="t('launchpad', 'Select groups')" + data-test="sharing-policy-allowed-groups" + @update:modelValue="saveLimits" /> + <p class="sharing-policy__hint"> + {{ + t( + 'launchpad', + 'Only members of these groups can share their dashboards. Leave empty to let everyone share.', + ) + }} + </p> + </div> + + <p + v-if="sharingAllowed === 'none'" + class="sharing-policy__hint" + data-test="sharing-policy-nobody-hint"> + {{ t('launchpad', 'Only administrators can share. Existing shares stay.') }} + </p> + + <div class="sharing-policy__field"> + <NcSelect + v-model="recipientScope" + :inputLabel="t('launchpad', 'Who can receive a share')" + :options="scopeOptions" + label="label" + trackBy="id" + :clearable="false" + data-test="sharing-policy-recipient-scope" + @update:modelValue="saveLimits" /> + </div> + + <div class="sharing-policy__field"> + <NcCheckboxRadioSwitch + :modelValue="publicLinksAllowed" + type="switch" + data-test="sharing-policy-public-links" + @update:modelValue="onPublicLinksChange"> + {{ t('launchpad', 'Allow public links') }} + </NcCheckboxRadioSwitch> + <p class="sharing-policy__hint"> + {{ + t( + 'launchpad', + 'Only for people who may share dashboards. A link always has an expiry date.', + ) + }} + </p> + </div> </div> </template> <script> -import { NcSelect, NcSelectTags } from '@conduction/nextcloud-vue' +import { NcCheckboxRadioSwitch, NcSelect, NcSelectTags } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' import { api } from '../../services/api.js' import { logger } from '../../utils/logger.js' +const SCOPE_OPTIONS = [ + { id: 'everyone', label: 'Everyone' }, + { id: 'shared-groups', label: 'Only people who share a group with the sharer' }, +] + +const ALLOWED_CHOICES = [ + { id: 'everyone', label: 'Everyone' }, + { id: 'groups', label: 'Only these groups' }, + { id: 'none', label: 'Nobody' }, +] + const PERMISSION_OPTIONS = [ { id: 'view_only', label: 'View only' }, { id: 'add_only', label: 'Add only' }, @@ -67,12 +155,14 @@ const PERMISSION_OPTIONS = [ * DashboardSharingPolicy — org-wide sharing defaults for the admin * Beheer ▸ Sharing tab (dashboard-sharing spec). Reads / writes * `defaultSharePermissionLevel` and `forcedShareGroups` via the admin - * settings API. + * settings API, and who may share and with whom: `sharingAllowedGroups` + * (empty = everyone) and `sharingRecipientScope` (REQ-SHARE-014). */ export default { name: 'DashboardSharingPolicy', components: { + NcCheckboxRadioSwitch, NcSelect, NcSelectTags, }, @@ -92,14 +182,29 @@ export default { label: t('launchpad', o.label), })), + scopeOptions: SCOPE_OPTIONS.map((o) => ({ + id: o.id, + label: t('launchpad', o.label), + })), + + allowedChoices: ALLOWED_CHOICES.map((o) => ({ + id: o.id, + label: t('launchpad', o.label), + })), + defaultPermission: null, forcedGroups: [], + allowedGroups: [], + recipientScope: null, + sharingAllowed: 'everyone', + publicLinksAllowed: true, } }, /** @spec openspec/specs/dashboard-sharing/spec.md */ created() { this.defaultPermission = this.permissionOptions[1] + this.recipientScope = this.scopeOptions[0] this.load() }, @@ -118,6 +223,16 @@ export default { this.forcedGroups = Array.isArray(settings.forcedShareGroups) ? settings.forcedShareGroups : [] + this.allowedGroups = Array.isArray(settings.sharingAllowedGroups) + ? settings.sharingAllowedGroups + : [] + this.recipientScope = + this.scopeOptions.find((o) => o.id === settings.sharingRecipientScope) + || this.scopeOptions[0] + this.sharingAllowed = ALLOWED_CHOICES.some((o) => o.id === settings.sharingAllowed) + ? settings.sharingAllowed + : (this.allowedGroups.length > 0 ? 'groups' : 'everyone') + this.publicLinksAllowed = settings.publicLinksAllowed !== false } catch (error) { logger.error('Failed to load sharing policy:', error) } @@ -134,6 +249,61 @@ export default { logger.error('Failed to save sharing policy:', error) } }, + + /** + * Save who may share and with whom (REQ-SHARE-014). A partial patch: + * the defaults above are left as they are. + * + * @spec openspec/changes/record-parity-requirements/specs/dashboard-sharing/spec.md#requirement-administrators-decide-who-may-share-and-with-whom-req-share-014 + */ + async saveLimits() { + try { + await api.updateAdminSettings({ + sharingAllowedGroups: this.allowedGroups, + sharingRecipientScope: this.recipientScope?.id, + }) + } catch (error) { + logger.error('Failed to save sharing limits:', error) + } + }, + + /** + * "Sharing allowed for" changed (REQ-SHARE-015). Only Nobody is stored + * as an override; Everyone clears the group list, which is what lets + * everyone share (REQ-SHARE-014), and Only these groups uses it. + * + * @param {string} value `everyone`, `groups` or `none`. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + async onAllowedChange(value) { + this.sharingAllowed = value + try { + await api.updateSharingPolicy({ sharingAllowed: value }) + if (value === 'everyone' && this.allowedGroups.length > 0) { + this.allowedGroups = [] + await this.saveLimits() + } + } catch (error) { + logger.error('Failed to save who may share:', error) + } + }, + + /** + * The public-link switch (REQ-SHARE-015). + * + * @param {boolean} value Whether public links may be created. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + async onPublicLinksChange(value) { + this.publicLinksAllowed = value === true + try { + await api.updateSharingPolicy({ publicLinksAllowed: this.publicLinksAllowed }) + } catch (error) { + logger.error('Failed to save the public link setting:', error) + } + }, }, } </script> @@ -148,6 +318,11 @@ export default { margin-bottom: 16px; } +.sharing-policy__choices { + border: none; + padding: 0; +} + .sharing-policy__label { display: block; margin-bottom: 4px; diff --git a/src/components/admin/EmbedTelemetryToggle.vue b/src/components/admin/EmbedTelemetryToggle.vue new file mode 100644 index 000000000..47de21767 --- /dev/null +++ b/src/components/admin/EmbedTelemetryToggle.vue @@ -0,0 +1,95 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="embed-telemetry-toggle" data-test="embed-telemetry-toggle"> + <h3>{{ t('launchpad', 'Embed usage') }}</h3> + <NcCheckboxRadioSwitch + :modelValue="enabled" + :disabled="loading" + data-test="embed-telemetry-switch" + @update:modelValue="onToggle"> + {{ t('launchpad', 'Collect embed usage telemetry') }} + </NcCheckboxRadioSwitch> + <p class="embed-telemetry-toggle__hint"> + {{ t('launchpad', 'Counts views and interactions of embedded widgets and dashboards per token, without IP addresses or visitor identifiers. When off, no usage is recorded.') }} + </p> + </div> +</template> + +<script> +import { NcCheckboxRadioSwitch } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { embedApi } from '../../services/embedApi.js' +import { logger } from '../../utils/logger.js' + +/** + * EmbedTelemetryToggle — Beheer ▸ Operations switch for embed usage + * telemetry (embedded-analytics task 30). The server writes the change to + * the audit log; the switch rolls back when saving fails. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-30 + */ +export default { + name: 'EmbedTelemetryToggle', + + components: { + NcCheckboxRadioSwitch, + }, + + data() { + return { + enabled: true, + loading: true, + } + }, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-30 */ + created() { + this.load() + }, + + methods: { + t, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-30 */ + async load() { + this.loading = true + try { + this.enabled = await embedApi.telemetryEnabled() + } catch (error) { + logger.error('Failed to load embed telemetry setting:', error) + } finally { + this.loading = false + } + }, + + /** + * Switch telemetry, showing the new state at once and rolling back if saving fails. + * + * @param {boolean} value The requested state. + * @spec openspec/changes/embedded-analytics/tasks.md#task-30 + */ + async onToggle(value) { + const previous = this.enabled + this.enabled = value + try { + this.enabled = await embedApi.setTelemetryEnabled(value) + } catch (error) { + this.enabled = previous + logger.error('Failed to save embed telemetry setting:', error) + } + }, + }, +} +</script> + +<style scoped> +.embed-telemetry-toggle__hint { + color: var(--color-text-maxcontrast); + margin-top: 8px; + font-size: 13px; +} +</style> diff --git a/src/components/admin/GroupPriorityOrder.vue b/src/components/admin/GroupPriorityOrder.vue index d45ee589b..54f295a8f 100644 --- a/src/components/admin/GroupPriorityOrder.vue +++ b/src/components/admin/GroupPriorityOrder.vue @@ -142,6 +142,7 @@ <script> import { showError, showSuccess } from '@nextcloud/dialogs' import { NcButton, NcTextField } from '@nextcloud/vue' +import { LIST_PROP } from '../../constants/propDefinitions.js' import { api } from '../../services/api.js' import { logger } from '../../utils/logger.js' @@ -164,10 +165,7 @@ export default { props: { // Optional initial seed for the active list (admin initial-state). // `loadGroups()` always overwrites with the API-truth at mount. - initialActive: { - type: Array, - default: () => [], - }, + initialActive: LIST_PROP, }, data() { diff --git a/src/components/admin/ImageHostSettings.vue b/src/components/admin/ImageHostSettings.vue new file mode 100644 index 000000000..24725cd2f --- /dev/null +++ b/src/components/admin/ImageHostSettings.vue @@ -0,0 +1,142 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="image-host-settings" data-test="image-host-settings"> + <h3>{{ t('launchpad', 'External image hosts') }}</h3> + <p class="image-host-settings__hint"> + {{ t('launchpad', 'Image widgets can show pictures from these websites. Enter one host name per line, such as images.example.com. Pictures from any other website are blocked.') }} + </p> + <NcTextArea + v-model="text" + :label="t('launchpad', 'Allowed image hosts')" + :disabled="!loaded || saving" + resize="vertical" + data-test="image-host-list" /> + <p + v-if="error" + class="image-host-settings__error" + role="alert" + data-test="image-host-error"> + {{ error }} + </p> + <div class="image-host-settings__actions"> + <NcButton + variant="primary" + :disabled="!loaded || saving" + data-test="image-host-save" + @click="save"> + {{ t('launchpad', 'Save image hosts') }} + </NcButton> + </div> + </div> +</template> + +<script> +import { NcButton, NcTextArea } from '@conduction/nextcloud-vue' +import { showSuccess } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +/** + * ImageHostSettings — Beheer ▸ Operations section for the external image + * host allow-list (REQ-IMG-006). The server checks every entry and answers + * the first one that is not a host name; that message is shown under the list. + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + */ +export default { + name: 'ImageHostSettings', + + components: { + NcButton, + NcTextArea, + }, + + data() { + return { + text: '', + error: '', + loaded: false, + saving: false, + } + }, + + /** @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator */ + created() { + this.load() + }, + + methods: { + t, + + /** + * Read the stored list. + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + * @return {Promise<void>} + */ + async load() { + try { + const { data } = await api.getImageHosts() + this.apply(data) + } catch (error) { + logger.error('Failed to load the image hosts:', error) + } finally { + this.loaded = true + } + }, + + /** + * Save the list, one host per line; the server's refusal is shown as it is. + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + * @return {Promise<void>} + */ + async save() { + this.saving = true + this.error = '' + const hosts = this.text.split('\n').map((line) => line.trim()).filter((line) => line !== '') + try { + const { data } = await api.updateImageHosts(hosts) + this.apply(data) + showSuccess(t('launchpad', 'Image hosts saved.')) + } catch (error) { + logger.error('Failed to save the image hosts:', error) + this.error = error?.response?.data?.message || t('launchpad', 'The image hosts could not be saved.') + } finally { + this.saving = false + } + }, + + /** + * Fill the list from a server answer. + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + * @param {object} data The answer, `{ hosts }`. + */ + apply(data) { + this.text = Array.isArray(data?.hosts) ? data.hosts.join('\n') : '' + }, + }, +} +</script> + +<style scoped> +.image-host-settings__hint { + color: var(--color-text-maxcontrast); + margin-bottom: 16px; +} + +.image-host-settings__error { + color: var(--color-error-text); + margin-top: 8px; +} + +.image-host-settings__actions { + margin-top: 16px; +} +</style> diff --git a/src/components/admin/LeaverHandoverSettings.vue b/src/components/admin/LeaverHandoverSettings.vue new file mode 100644 index 000000000..baf82a1bd --- /dev/null +++ b/src/components/admin/LeaverHandoverSettings.vue @@ -0,0 +1,190 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<!-- + LeaverHandoverSettings — the Clean up block of Beheer ▸ Operations + (board LpBeheerOnderhoud, REQ-SHARE-016): where the dashboards of people + who left go. Their manager, otherwise a named person; without a choice + REQ-SHARE-012 applies (someone with full rights, or deleted). +--> + +<template> + <div class="leaver-handover" data-test="leaver-handover"> + <h3>{{ t('launchpad', 'Clean up') }}</h3> + <p class="leaver-handover__label"> + {{ t('launchpad', 'Dashboards of people who left go to') }} + </p> + <NcCheckboxRadioSwitch + :modelValue="manager" + data-test="leaver-handover-manager" + @update:modelValue="onManagerChange"> + {{ t('launchpad', 'Their manager') }} + </NcCheckboxRadioSwitch> + + <div class="leaver-handover__field"> + <NcSelect + :modelValue="fallback" + :options="options" + :filterable="false" + :loading="searching" + :inputLabel="manager ? t('launchpad', 'Otherwise') : t('launchpad', 'A person')" + :placeholder="t('launchpad', 'Search for a person')" + label="displayName" + trackBy="id" + :clearable="true" + data-test="leaver-handover-fallback" + @search="onSearch" + @update:modelValue="onFallbackChange" /> + </div> + + <p class="leaver-handover__hint"> + {{ + t( + 'launchpad', + 'Without a choice, a dashboard goes to someone with full rights on it, or is deleted. Shares stay.', + ) + }} + </p> + </div> +</template> + +<script> +import { NcCheckboxRadioSwitch, NcSelect } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +/** + * Where a leaver's dashboards go (REQ-SHARE-016). + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ +export default { + name: 'LeaverHandoverSettings', + + components: { + NcCheckboxRadioSwitch, + NcSelect, + }, + + data() { + return { + manager: false, + fallback: null, + options: [], + searching: false, + searchSeq: 0, + } + }, + + /** + * Read the stored setting. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + async created() { + try { + const { data } = await api.getAdminSettings() + const handover = (data?.data ?? data ?? {}).leaverHandover ?? {} + this.manager = handover.manager === true + const uid = typeof handover.fallbackUid === 'string' ? handover.fallbackUid : '' + this.fallback = uid === '' ? null : { id: uid, displayName: uid } + } catch (error) { + logger.error('Failed to load the leaver handover:', error) + } + }, + + methods: { + t, + + /** + * Look people up for the "otherwise" person; a slower answer for an + * earlier query is dropped. + * + * @param {string} query The search text. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + async onSearch(query) { + const seq = ++this.searchSeq + if ((query ?? '').trim().length < 2) { + this.options = [] + return + } + this.searching = true + try { + const { data } = await api.searchSharees(query) + if (seq !== this.searchSeq) { + return + } + const users = (data?.data ?? data ?? {}).users ?? [] + this.options = users.map((user) => ({ id: user.id, displayName: user.displayName || user.id })) + } catch (error) { + logger.error('People search failed:', error) + this.options = [] + } finally { + if (seq === this.searchSeq) { + this.searching = false + } + } + }, + + /** + * "Their manager" switched. + * + * @param {boolean} value Whether a leaver's manager comes first. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + async onManagerChange(value) { + this.manager = value === true + await this.save() + }, + + /** + * The "otherwise" person chosen or cleared. + * + * @param {{id: string, displayName: string}|null} option The person, or null. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + async onFallbackChange(option) { + this.fallback = option ?? null + await this.save() + }, + + /** + * Store the setting. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + async save() { + try { + await api.updateLeaverHandover({ manager: this.manager, fallbackUid: this.fallback?.id ?? '' }) + } catch (error) { + logger.error('Failed to save the leaver handover:', error) + } + }, + }, +} +</script> + +<style scoped> +.leaver-handover__label { + font-weight: 500; + margin-bottom: 4px; +} + +.leaver-handover__field { + margin: 12px 0; + max-width: 400px; +} + +.leaver-handover__hint { + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/admin/OrgNavigationEditor.vue b/src/components/admin/OrgNavigationEditor.vue index 240bc7578..185e4e53d 100644 --- a/src/components/admin/OrgNavigationEditor.vue +++ b/src/components/admin/OrgNavigationEditor.vue @@ -116,6 +116,7 @@ import { translate as t } from '@nextcloud/l10n' import draggable from 'vuedraggable' import OrgNavigationEditorRow from './OrgNavigationEditorRow.vue' +import { LIST_PROP } from '../../constants/propDefinitions.js' import { ORG_NAV_POSITIONS, useOrgNavigationStore, @@ -154,10 +155,7 @@ export default { * editor still functions, but the visibility selector falls * back to a free-text input. */ - groups: { - type: Array, - default: () => [], - }, + groups: LIST_PROP, }, data() { diff --git a/src/components/admin/OrgNavigationEditorRow.vue b/src/components/admin/OrgNavigationEditorRow.vue index a355c47a1..23b01309b 100644 --- a/src/components/admin/OrgNavigationEditorRow.vue +++ b/src/components/admin/OrgNavigationEditorRow.vue @@ -133,7 +133,8 @@ import { CnIconBrowser } from '@conduction/nextcloud-vue' import { translate as t } from '@nextcloud/l10n' import draggable from 'vuedraggable' -import { ICON_CATALOGUE } from '../../services/iconCatalogue.js' +import { LIST_PROP, REQUIRED_OBJECT_PROP } from '../../constants/propDefinitions.js' +import { ICON_CATALOGUE, loadIconCatalogue } from '../../services/iconCatalogue.js' /** * OrgNavigationEditorRow — single row inside the admin tree editor. @@ -158,10 +159,7 @@ export default { }, props: { - node: { - type: Object, - required: true, - }, + node: REQUIRED_OBJECT_PROP, level: { type: Number, @@ -183,10 +181,7 @@ export default { default: 3, }, - groups: { - type: Array, - default: () => [], - }, + groups: LIST_PROP, }, emits: ['update', 'delete', 'moveUp', 'moveDown', 'addChild'], @@ -245,6 +240,10 @@ export default { }, }, + created() { + loadIconCatalogue().catch(() => {}) + }, + methods: { t, diff --git a/src/components/admin/PublicStartPageSettings.vue b/src/components/admin/PublicStartPageSettings.vue new file mode 100644 index 000000000..1eeb69056 --- /dev/null +++ b/src/components/admin/PublicStartPageSettings.vue @@ -0,0 +1,258 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="public-start-settings" data-test="public-start-settings"> + <h3>{{ t('launchpad', 'Public start page') }}</h3> + <p class="public-start-settings__hint"> + {{ + t( + 'launchpad', + 'Visitors who are not signed in see this public dashboard instead of the login screen. Staff sign in from it.', + ) + }} + </p> + + <p + v-if="loaded && active" + class="public-start-settings__status" + data-test="public-start-status"> + {{ t('launchpad', 'Public start page: {name}', { name: chosenName }) }} + </p> + <NcNoteCard + v-else-if="loaded && offReason" + type="warning" + data-test="public-start-reason"> + {{ offReason }} + </NcNoteCard> + + <div class="public-start-settings__field"> + <NcSelect + v-model="selected" + :inputLabel="t('launchpad', 'Public link')" + :options="options" + label="label" + trackBy="token" + :clearable="true" + :disabled="!loaded || saving" + :placeholder="t('launchpad', 'Choose a public link without a password')" + data-test="public-start-link" /> + <p + v-if="loaded && options.length === 0" + class="public-start-settings__hint" + data-test="public-start-no-links"> + {{ + t( + 'launchpad', + 'There is no public link without a password that has not expired. Share a dashboard on a public link first.', + ) + }} + </p> + </div> + + <NcCheckboxRadioSwitch + v-model="enabled" + type="switch" + :disabled="!loaded || saving" + data-test="public-start-enabled"> + {{ t('launchpad', 'Show the public start page to visitors who are not signed in') }} + </NcCheckboxRadioSwitch> + + <div class="public-start-settings__actions"> + <NcButton + variant="primary" + :disabled="!loaded || saving || (enabled && !selected)" + data-test="public-start-save" + @click="save"> + {{ t('launchpad', 'Save start page') }} + </NcButton> + </div> + </div> +</template> + +<script> +import { + NcButton, + NcCheckboxRadioSwitch, + NcNoteCard, + NcSelect, +} from '@conduction/nextcloud-vue' +import { showError, showSuccess } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +/** + * PublicStartPageSettings — Beheer ▸ Sharing section that picks the public + * link signed-out visitors see instead of the login form + * (sharing-public-start-page REQ-PSP-001, design D1). + * + * Only links the server offers are listed: no password, not revoked, not + * expired. When the chosen link later goes bad the start page is off, and + * this section says why; the server keeps the choice so the administrator + * sees what was chosen. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + */ +export default { + name: 'PublicStartPageSettings', + + components: { + NcButton, + NcCheckboxRadioSwitch, + NcNoteCard, + NcSelect, + }, + + data() { + return { + enabled: false, + token: '', + active: false, + reason: null, + candidates: [], + selected: null, + loaded: false, + saving: false, + } + }, + + computed: { + /** + * The links that may be chosen, named by their dashboard. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + * @return {Array<{token: string, label: string}>} + */ + options() { + return this.candidates.map((candidate) => ({ + token: candidate.token, + label: candidate.dashboardName || candidate.token, + })) + }, + + /** + * The name of the dashboard the start page shows. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + * @return {string} + */ + chosenName() { + const chosen = this.options.find((option) => option.token === this.token) + return chosen ? chosen.label : this.token + }, + + /** + * Why a switched-on start page is not shown, or '' when it is shown or off. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + * @return {string} + */ + offReason() { + if (!this.enabled || this.active) { + return '' + } + switch (this.reason) { + case 'no-link': + return t('launchpad', 'The start page is off: no public link is chosen.') + case 'not-found': + return t('launchpad', 'The start page is off: the chosen public link no longer exists.') + case 'revoked': + return t('launchpad', 'The start page is off: the chosen public link has been revoked.') + case 'password': + return t('launchpad', 'The start page is off: the chosen public link now has a password.') + case 'expired': + return t('launchpad', 'The start page is off: the chosen public link has expired.') + default: + return '' + } + }, + }, + + /** @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 */ + created() { + this.load() + }, + + methods: { + t, + + /** + * Read the status and the links that may be chosen. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + * @return {Promise<void>} + */ + async load() { + try { + const { data } = await api.getPublicStart() + this.candidates = Array.isArray(data?.candidates) ? data.candidates : [] + this.apply(data) + } catch (error) { + logger.error('Failed to load the public start page:', error) + } finally { + this.loaded = true + } + }, + + /** + * Save the chosen link and the switch; the server's refusal is shown as it is. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + * @return {Promise<void>} + */ + async save() { + this.saving = true + try { + const { data } = await api.updatePublicStart({ + enabled: this.enabled, + token: this.selected ? this.selected.token : '', + }) + this.apply(data) + showSuccess(t('launchpad', 'Start page saved.')) + } catch (error) { + logger.error('Failed to save the public start page:', error) + showError(error?.response?.data?.message || t('launchpad', 'The start page could not be saved.')) + } finally { + this.saving = false + } + }, + + /** + * Fill the section from a server status. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + * @param {object} data The status. + */ + apply(data) { + this.enabled = data?.enabled === true + this.token = typeof data?.token === 'string' ? data.token : '' + this.active = data?.active === true + this.reason = typeof data?.reason === 'string' ? data.reason : null + this.selected = this.options.find((option) => option.token === this.token) || null + }, + }, +} +</script> + +<style scoped> +.public-start-settings__hint { + color: var(--color-text-maxcontrast); + margin-bottom: 16px; +} + +.public-start-settings__status { + font-weight: bold; + margin-bottom: 16px; +} + +.public-start-settings__field { + margin-bottom: 16px; +} + +.public-start-settings__actions { + margin-top: 16px; +} +</style> diff --git a/src/components/admin/RoleLayoutDefaultsSection.vue b/src/components/admin/RoleLayoutDefaultsSection.vue index 7917562d5..70ea58a48 100644 --- a/src/components/admin/RoleLayoutDefaultsSection.vue +++ b/src/components/admin/RoleLayoutDefaultsSection.vue @@ -98,24 +98,26 @@ @update:row="editorRow = $event" @save="save" /> - <!-- Delete confirmation dialog (extracted per ADR-004) --> - <RoleLayoutDefaultDeleteDialog + <!-- Delete confirmation dialog --> + <CnConfirmDialog v-if="showDeleteDialog" - :open="showDeleteDialog" - :groupId="deleteTarget ? deleteTarget.groupId : ''" - :widgetId="deleteTarget ? deleteTarget.widgetId : ''" - @update:open="showDeleteDialog = $event" - @confirm="confirmDelete" /> + ref="deleteDialog" + :dialogTitle="t('launchpad', 'Delete layout default')" + :message="deleteMessage" + :confirmLabel="t('launchpad', 'Delete')" + variant="error" + @confirm="confirmDelete" + @close="showDeleteDialog = false" /> </div> </template> <script> -import { NcButton, NcEmptyContent } from '@conduction/nextcloud-vue' +import { CnConfirmDialog, NcButton, NcEmptyContent } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' import Delete from 'vue-material-design-icons/Delete.vue' import Pencil from 'vue-material-design-icons/Pencil.vue' import Plus from 'vue-material-design-icons/Plus.vue' import ViewDashboard from 'vue-material-design-icons/ViewDashboard.vue' -import RoleLayoutDefaultDeleteDialog from '../../dialogs/RoleLayoutDefaultDeleteDialog.vue' import RoleLayoutDefaultEditorDialog from '../../dialogs/RoleLayoutDefaultEditorDialog.vue' import { useRoleFeaturePermissionStore } from '../../stores/roleFeaturePermissions.js' import { logger } from '../../utils/logger.js' @@ -131,7 +133,7 @@ export default { Pencil, Delete, RoleLayoutDefaultEditorDialog, - RoleLayoutDefaultDeleteDialog, + CnConfirmDialog, }, /** @spec openspec/changes/role-based-content/tasks.md#task-6 */ @@ -149,6 +151,25 @@ export default { } }, + computed: { + /** + * The question in the delete confirmation. + * + * @return {string} The translated question. + * @spec openspec/changes/role-based-content/tasks.md#task-6 + */ + deleteMessage() { + return t( + 'launchpad', + 'Delete layout default for "{group}" / "{widget}"?', + { + group: this.deleteTarget ? this.deleteTarget.groupId : '', + widget: this.deleteTarget ? this.deleteTarget.widgetId : '', + }, + ) + }, + }, + /** @spec openspec/changes/role-based-content/tasks.md#task-6 */ async mounted() { try { @@ -226,85 +247,20 @@ export default { this.deleteTarget = null } catch (e) { logger.error('Failed to delete layout default', e) + this.$refs.deleteDialog?.setResult({ error: this.store.error }) } }, }, } </script> -<style scoped> -.launchpad-admin__hint { - color: var(--color-text-maxcontrast); - margin: 0 0 var(--default-grid-baseline) 0; -} - -.launchpad-admin__error { - background: var(--color-error); - color: var(--color-primary-element-text); - padding: var(--default-grid-baseline); - border-radius: var(--border-radius); - margin-bottom: var(--default-grid-baseline); -} - -.launchpad-admin__role-list { - display: flex; - flex-direction: column; - gap: var(--default-grid-baseline); - margin-bottom: var(--default-grid-baseline); -} - -.launchpad-admin__role-row { - display: flex; - align-items: center; - gap: var(--default-grid-baseline); - padding: var(--default-grid-baseline); - border: 1px solid var(--color-border); - border-radius: var(--border-radius); -} - -.launchpad-admin__role-meta { - display: flex; - flex-direction: column; - min-width: 200px; -} - -.launchpad-admin__role-group { - color: var(--color-text-maxcontrast); - font-family: var(--font-face-monospace, monospace); - font-size: 0.85em; -} - -.launchpad-admin__role-widgets { - flex: 1; - display: flex; - flex-wrap: wrap; - gap: 4px; -} - -.launchpad-admin__chip { - background: var(--color-background-hover); - padding: 2px 8px; - border-radius: var(--border-radius); - font-size: 0.85em; -} +<style scoped src="./roleSection.css"></style> +<style scoped> .launchpad-admin__chip--compulsory { background: var(--color-warning); } -.launchpad-admin__role-actions { - display: flex; - gap: 4px; -} - -.launchpad-admin__editor { - padding: calc(var(--default-grid-baseline) * 2); - display: flex; - flex-direction: column; - gap: var(--default-grid-baseline); - min-width: 480px; -} - .launchpad-admin__editor-row { display: flex; gap: var(--default-grid-baseline); diff --git a/src/components/admin/RolePermissionsSection.vue b/src/components/admin/RolePermissionsSection.vue index eccc0f841..eb802445e 100644 --- a/src/components/admin/RolePermissionsSection.vue +++ b/src/components/admin/RolePermissionsSection.vue @@ -98,23 +98,26 @@ @save="save" @close="closeEditor" /> - <!-- Delete confirmation dialog (ADR-004: extracted to dialogs/) --> - <RolePermissionDeleteDialog + <!-- Delete confirmation dialog --> + <CnConfirmDialog v-if="showDeleteDialog" - :open="showDeleteDialog" - :groupId="deleteTarget ? deleteTarget.groupId : ''" - @update:open="showDeleteDialog = $event" - @confirm="doDelete" /> + ref="deleteDialog" + :dialogTitle="t('launchpad', 'Delete role permission')" + :message="deleteMessage" + :confirmLabel="t('launchpad', 'Delete')" + variant="error" + @confirm="doDelete" + @close="showDeleteDialog = false" /> </div> </template> <script> -import { NcButton, NcEmptyContent } from '@conduction/nextcloud-vue' +import { CnConfirmDialog, NcButton, NcEmptyContent } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' import AccountGroup from 'vue-material-design-icons/AccountGroup.vue' import Delete from 'vue-material-design-icons/Delete.vue' import Pencil from 'vue-material-design-icons/Pencil.vue' import Plus from 'vue-material-design-icons/Plus.vue' -import RolePermissionDeleteDialog from '../../dialogs/RolePermissionDeleteDialog.vue' import RolePermissionEditorModal from '../../modals/RolePermissionEditorModal.vue' import { useRoleFeaturePermissionStore } from '../../stores/roleFeaturePermissions.js' import { logger } from '../../utils/logger.js' @@ -130,7 +133,7 @@ export default { Pencil, Delete, RolePermissionEditorModal, - RolePermissionDeleteDialog, + CnConfirmDialog, }, /** @spec openspec/specs/admin-roles/spec.md */ @@ -150,6 +153,20 @@ export default { } }, + computed: { + /** + * The question in the delete confirmation. + * + * @return {string} The translated question. + * @spec openspec/specs/admin-roles/spec.md + */ + deleteMessage() { + return t('launchpad', 'Delete role permission for group "{group}"?', { + group: this.deleteTarget ? this.deleteTarget.groupId : '', + }) + }, + }, + /** @spec openspec/specs/admin-roles/spec.md */ async mounted() { try { @@ -258,86 +275,21 @@ export default { this.deleteTarget = null } catch (e) { logger.error('Failed to delete role permission', e) + this.$refs.deleteDialog?.setResult({ error: this.store.error }) } }, }, } </script> -<style scoped> -.launchpad-admin__hint { - color: var(--color-text-maxcontrast); - margin: 0 0 var(--default-grid-baseline) 0; -} - -.launchpad-admin__error { - background: var(--color-error); - color: var(--color-primary-element-text); - padding: var(--default-grid-baseline); - border-radius: var(--border-radius); - margin-bottom: var(--default-grid-baseline); -} - -.launchpad-admin__role-list { - display: flex; - flex-direction: column; - gap: var(--default-grid-baseline); - margin-bottom: var(--default-grid-baseline); -} - -.launchpad-admin__role-row { - display: flex; - align-items: center; - gap: var(--default-grid-baseline); - padding: var(--default-grid-baseline); - border: 1px solid var(--color-border); - border-radius: var(--border-radius); -} - -.launchpad-admin__role-meta { - display: flex; - flex-direction: column; - min-width: 200px; -} - -.launchpad-admin__role-group { - color: var(--color-text-maxcontrast); - font-family: var(--font-face-monospace, monospace); - font-size: 0.85em; -} - -.launchpad-admin__role-widgets { - flex: 1; - display: flex; - flex-wrap: wrap; - gap: 4px; -} - -.launchpad-admin__chip { - background: var(--color-background-hover); - padding: 2px 8px; - border-radius: var(--border-radius); - font-size: 0.85em; -} +<style scoped src="./roleSection.css"></style> +<style scoped> .launchpad-admin__chip--denied { background: var(--color-error); color: var(--color-primary-element-text); } -.launchpad-admin__role-actions { - display: flex; - gap: 4px; -} - -.launchpad-admin__editor { - padding: calc(var(--default-grid-baseline) * 2); - display: flex; - flex-direction: column; - gap: var(--default-grid-baseline); - min-width: 480px; -} - .launchpad-admin__editor-actions { display: flex; justify-content: flex-end; diff --git a/src/components/admin/TileLaunchSettings.vue b/src/components/admin/TileLaunchSettings.vue new file mode 100644 index 000000000..f0aed6215 --- /dev/null +++ b/src/components/admin/TileLaunchSettings.vue @@ -0,0 +1,273 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <!-- launcher-tile-launch-types task 6: the two admin lists behind program + and single sign-on tiles. The server checks both (TileLaunchSettings) + and refuses a list whole, naming the entry; the message is shown here. --> + <CnSettingsSection + :name="t('launchpad', 'Program and sign-on tiles')" + data-testid="admin-tile-launch"> + <p class="tile-launch-settings__hint"> + {{ t('launchpad', 'Program tiles only work with the schemes you allow here. Single sign-on tiles open one of your sign-on templates; authors pick a template and enter the app id.') }} + </p> + + <h3 class="tile-launch-settings__heading"> + {{ t('launchpad', 'Allowed program schemes') }} + </h3> + <ul v-if="schemes.length > 0" class="tile-launch-settings__list" data-testid="admin-tile-schemes"> + <li v-for="scheme in schemes" :key="scheme" class="tile-launch-settings__item"> + <code>{{ scheme }}</code> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove {scheme}', { scheme })" + :disabled="saving" + @click="removeScheme(scheme)"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </li> + </ul> + <p v-else class="tile-launch-settings__hint"> + {{ t('launchpad', 'No schemes allowed yet, so program tiles do nothing.') }} + </p> + <form class="tile-launch-settings__add" @submit.prevent="addScheme"> + <NcTextField + v-model="newScheme" + :label="t('launchpad', 'Scheme')" + :helperText="t('launchpad', 'Lower-case, such as ms-word or vscode. javascript, data, file, vbscript, about and blob are never allowed.')" + data-testid="admin-tile-scheme-input" /> + <NcButton + type="submit" + variant="secondary" + :disabled="saving || newScheme.trim() === ''"> + {{ t('launchpad', 'Allow scheme') }} + </NcButton> + </form> + + <h3 class="tile-launch-settings__heading"> + {{ t('launchpad', 'Sign-on templates') }} + </h3> + <ul v-if="templates.length > 0" class="tile-launch-settings__list" data-testid="admin-sso-templates"> + <li v-for="template in templates" :key="template.key" class="tile-launch-settings__item"> + <span> + <strong>{{ template.name }}</strong> + <code class="tile-launch-settings__address">{{ template.urlTemplate }}</code> + </span> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove {name}', { name: template.name })" + :disabled="saving" + @click="removeTemplate(template.key)"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </li> + </ul> + <p v-else class="tile-launch-settings__hint"> + {{ t('launchpad', 'No sign-on templates yet.') }} + </p> + <form class="tile-launch-settings__add" @submit.prevent="addTemplate"> + <NcTextField + v-model="newTemplate.name" + :label="t('launchpad', 'Template name')" + data-testid="admin-sso-name-input" /> + <NcTextField + v-model="newTemplate.key" + :label="t('launchpad', 'Key')" + :helperText="t('launchpad', 'Lower-case letters, digits and hyphens.')" + data-testid="admin-sso-key-input" /> + <NcTextField + v-model="newTemplate.urlTemplate" + :label="t('launchpad', 'Sign-on address')" + :helperText="t('launchpad', 'An https address with {appId} where the app id goes.', { appId: '{appId}' })" + data-testid="admin-sso-url-input" /> + <NcButton + type="submit" + variant="secondary" + :disabled="saving || !templateComplete"> + {{ t('launchpad', 'Add template') }} + </NcButton> + </form> + + <p + v-if="error" + class="tile-launch-settings__error" + role="alert" + data-testid="admin-tile-launch-error"> + {{ error }} + </p> + </CnSettingsSection> +</template> + +<script> +import { CnSettingsSection, NcButton, NcTextField } from '@conduction/nextcloud-vue' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +export default { + name: 'TileLaunchSettings', + + components: { + CnSettingsSection, + NcButton, + NcTextField, + }, + + data() { + return { + schemes: [], + templates: [], + newScheme: '', + newTemplate: { name: '', key: '', urlTemplate: '' }, + saving: false, + error: '', + } + }, + + computed: { + /** + * Whether the new template has every field filled in. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-6 + */ + templateComplete() { + return ['name', 'key', 'urlTemplate'].every((field) => this.newTemplate[field].trim() !== '') + }, + }, + + /** @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-6 */ + created() { + this.load() + }, + + methods: { + t, + + /** + * Read both lists from the admin settings. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-6 + */ + async load() { + try { + const { data } = await api.getAdminSettings() + const settings = data?.data ?? data ?? {} + this.schemes = Array.isArray(settings.tileAllowedSchemes) ? settings.tileAllowedSchemes : [] + this.templates = Array.isArray(settings.ssoLaunchTemplates) ? settings.ssoLaunchTemplates : [] + } catch (error) { + logger.error('Failed to load the tile launch settings:', error) + } + }, + + /** + * Save one list. The server refuses a list whole, so on a refusal + * nothing changes here either and its message is shown. + * + * @param {string} key `tileAllowedSchemes` or `ssoLaunchTemplates`. + * @param {Array} value The whole new list. + * @return {Promise<boolean>} Whether it was saved. + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-6 + */ + async save(key, value) { + this.saving = true + this.error = '' + try { + await api.updateAdminSettings({ [key]: value }) + await this.load() + return true + } catch (error) { + this.error = error?.response?.data?.error || t('launchpad', 'The setting could not be saved.') + logger.error('Failed to save the tile launch settings:', error) + return false + } finally { + this.saving = false + } + }, + + /** @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-6 */ + async addScheme() { + if (await this.save('tileAllowedSchemes', [...this.schemes, this.newScheme.trim()])) { + this.newScheme = '' + } + }, + + /** + * @param {string} scheme The scheme to drop. + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-6 + */ + async removeScheme(scheme) { + await this.save('tileAllowedSchemes', this.schemes.filter((entry) => entry !== scheme)) + }, + + /** @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-6 */ + async addTemplate() { + const template = { + key: this.newTemplate.key.trim(), + name: this.newTemplate.name.trim(), + urlTemplate: this.newTemplate.urlTemplate.trim(), + } + if (await this.save('ssoLaunchTemplates', [...this.templates, template])) { + this.newTemplate = { name: '', key: '', urlTemplate: '' } + } + }, + + /** + * @param {string} key The key of the template to drop. + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-6 + */ + async removeTemplate(key) { + await this.save('ssoLaunchTemplates', this.templates.filter((entry) => entry.key !== key)) + }, + }, +} +</script> + +<style scoped> +.tile-launch-settings__hint { + color: var(--color-text-maxcontrast); + margin: 8px 0; +} + +.tile-launch-settings__heading { + margin: 16px 0 4px; + font-size: var(--default-font-size); + font-weight: bold; +} + +.tile-launch-settings__list { + margin: 0; + padding: 0; + list-style: none; +} + +.tile-launch-settings__item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 4px 0; + border-bottom: 1px solid var(--color-border); +} + +.tile-launch-settings__address { + display: block; + color: var(--color-text-maxcontrast); + overflow-wrap: anywhere; +} + +.tile-launch-settings__add { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 8px; + margin-top: 8px; +} + +.tile-launch-settings__error { + color: var(--color-error-text, var(--color-error)); + margin-top: 8px; +} +</style> diff --git a/src/components/admin/__tests__/AdminAnalytics.spec.js b/src/components/admin/__tests__/AdminAnalytics.spec.js new file mode 100644 index 000000000..39b140248 --- /dev/null +++ b/src/components/admin/__tests__/AdminAnalytics.spec.js @@ -0,0 +1,130 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `AdminAnalytics.vue`: loading the summary and the + * top dashboards for the chosen period, the empty and error states, and + * the CSV export download. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import AdminAnalytics from '../AdminAnalytics.vue' +import { api } from '../../../services/api.js' +import { logger } from '../../../utils/logger.js' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key, translate: (_app, key) => key })) +vi.mock('../../../services/api.js', () => ({ + api: { + getAnalyticsInstanceSummary: vi.fn(), + getAnalyticsTopDashboards: vi.fn(), + getAnalyticsCsvExport: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const TileClickReportStub = { name: 'TileClickReport', props: ['period'], template: '<div class="tile-report-stub" />' } + +const SUMMARY = { totalViewCount: 120, totalUniqueViewers: 30, dashboardCount: 4 } +const TOP = [ + { dashboardUuid: 'u1', name: 'Sales', viewCount: 80, uniqueViewerCount: 20 }, + { dashboardUuid: 'u2', name: '', viewCount: 40, uniqueViewerCount: 10 }, +] + +function mountAnalytics() { + return mount(AdminAnalytics, { global: { stubs: { TileClickReport: TileClickReportStub } } }) +} + +beforeEach(() => { + vi.clearAllMocks() + api.getAnalyticsInstanceSummary.mockResolvedValue({ data: SUMMARY }) + api.getAnalyticsTopDashboards.mockResolvedValue({ data: TOP }) +}) + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('AdminAnalytics', () => { + it('loads the 30-day summary and top 10 on creation', async () => { + const wrapper = mountAnalytics() + await wrapper.vm.$nextTick() + expect(wrapper.find('.launchpad-analytics__loading').exists()).toBe(true) + await flushPromises() + + expect(api.getAnalyticsInstanceSummary).toHaveBeenCalledWith('30d') + expect(api.getAnalyticsTopDashboards).toHaveBeenCalledWith('30d', 10) + expect(wrapper.findAll('.launchpad-analytics__metric-value').map((v) => v.text())).toEqual(['120', '30', '4']) + const rows = wrapper.findAll('tbody tr').map((r) => r.findAll('td').map((c) => c.text())) + expect(rows).toEqual([['Sales', '80', '20'], ['u2', '40', '10']]) + expect(wrapper.findComponent(TileClickReportStub).props('period')).toBe('30d') + }) + + it('reloads for a new period and passes it to the tile report', async () => { + const wrapper = mountAnalytics() + await flushPromises() + + await wrapper.find('select').setValue('7d') + await flushPromises() + + expect(api.getAnalyticsInstanceSummary).toHaveBeenLastCalledWith('7d') + expect(api.getAnalyticsTopDashboards).toHaveBeenLastCalledWith('7d', 10) + expect(wrapper.findComponent(TileClickReportStub).props('period')).toBe('7d') + }) + + it('shows zeros and the empty hint without data', async () => { + api.getAnalyticsInstanceSummary.mockResolvedValue({ data: null }) + api.getAnalyticsTopDashboards.mockResolvedValue({ data: { not: 'a list' } }) + const wrapper = mountAnalytics() + await flushPromises() + + expect(wrapper.findAll('.launchpad-analytics__metric-value').map((v) => v.text())).toEqual(['0', '0', '0']) + expect(wrapper.find('table').exists()).toBe(false) + expect(wrapper.text()).toContain('No view events recorded yet for this period.') + }) + + it('shows an error when either request fails', async () => { + api.getAnalyticsTopDashboards.mockRejectedValue(new Error('500')) + const wrapper = mountAnalytics() + await flushPromises() + + expect(wrapper.find('.launchpad-analytics__error').text()).toBe('Failed to load analytics data. Please try again.') + expect(logger.error).toHaveBeenCalledWith('Failed to load analytics:', expect.any(Error)) + }) + + it('downloads the CSV export named after today', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-03-11T12:00:00Z')) + api.getAnalyticsCsvExport.mockResolvedValue({ data: 'uuid,views\n' }) + URL.createObjectURL = vi.fn(() => 'blob:csv') + URL.revokeObjectURL = vi.fn() + const clicks = [] + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function() { + clicks.push({ href: this.getAttribute('href'), download: this.download }) + }) + const wrapper = mountAnalytics() + await flushPromises() + + await wrapper.find('.launchpad-analytics__button').trigger('click') + await flushPromises() + + expect(api.getAnalyticsCsvExport).toHaveBeenCalledWith('30d') + expect(URL.createObjectURL.mock.calls[0][0]).toBeInstanceOf(Blob) + expect(clicks).toEqual([{ href: 'blob:csv', download: 'dashboard-analytics-2026-03-11.csv' }]) + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:csv') + expect(wrapper.vm.exporting).toBe(false) + }) + + it('shows an error when the export fails', async () => { + api.getAnalyticsCsvExport.mockRejectedValue(new Error('x')) + const wrapper = mountAnalytics() + await flushPromises() + + await wrapper.find('.launchpad-analytics__button').trigger('click') + await flushPromises() + + expect(wrapper.find('.launchpad-analytics__error').text()).toBe('Failed to export analytics CSV. Please try again.') + expect(logger.error).toHaveBeenCalledWith('Failed to export analytics CSV:', expect.any(Error)) + }) +}) diff --git a/src/components/admin/__tests__/AdminCustomCss.spec.js b/src/components/admin/__tests__/AdminCustomCss.spec.js new file mode 100644 index 000000000..b5cdd16c2 --- /dev/null +++ b/src/components/admin/__tests__/AdminCustomCss.spec.js @@ -0,0 +1,98 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `AdminCustomCss.vue` (platform-dashboard-theme-and-css + * REQ-THM-003): loading the stored CSS, saving it, and showing what the + * server's cleaning removed. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import AdminCustomCss from '../AdminCustomCss.vue' +import { api } from '../../../services/api.js' + +vi.mock('@nextcloud/l10n', () => { + const t = (_app, key, vars = {}) => key.replace(/\{(\w+)\}/g, (_m, name) => vars[name] ?? `{${name}}`) + return { t, translate: t } +}) +vi.mock('../../../services/api.js', () => ({ + api: { + getCustomCss: vi.fn(), + updateCustomCss: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const NcButtonStub = { name: 'NcButton', props: ['disabled'], emits: ['click'], template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' } + +function mountSection() { + return mount(AdminCustomCss, { global: { stubs: { NcButton: NcButtonStub } } }) +} + +beforeEach(() => { + vi.clearAllMocks() + api.getCustomCss.mockResolvedValue({ data: { customCss: '.launchpad-workspace p {\n margin: 0;\n}' } }) +}) + +describe('AdminCustomCss', () => { + it('shows the stored CSS in a labelled field', async () => { + const wrapper = mountSection() + await flushPromises() + + const input = wrapper.find('[data-testid="admin-custom-css-input"]') + expect(input.element.value).toBe('.launchpad-workspace p {\n margin: 0;\n}') + expect(wrapper.find(`label[for="${input.attributes('id')}"]`).exists()).toBe(true) + }) + + it('saves what the administrator typed and says what was removed (the spec\'s "Import dropped")', async () => { + api.updateCustomCss.mockResolvedValue({ + data: { customCss: '.launchpad-workspace .tile-widget__title {\n font-weight: 700;\n}', removed: ['@import'] }, + }) + const wrapper = mountSection() + await flushPromises() + + const typed = '@import url(https://evil.example/x.css); .tile-widget__title { font-weight: 700; }' + await wrapper.find('[data-testid="admin-custom-css-input"]').setValue(typed) + await wrapper.find('[data-testid="admin-custom-css-save"]').trigger('click') + await flushPromises() + + expect(api.updateCustomCss).toHaveBeenCalledWith(typed) + expect(wrapper.find('[data-testid="admin-custom-css-removed"]').text()).toBe('Removed: @import') + expect(wrapper.find('[data-testid="admin-custom-css-input"]').element.value) + .toBe('.launchpad-workspace .tile-widget__title {\n font-weight: 700;\n}') + expect(wrapper.find('[data-testid="admin-custom-css-saved"]').exists()).toBe(false) + }) + + it('confirms a save that removed nothing', async () => { + api.updateCustomCss.mockResolvedValue({ data: { customCss: '', removed: [] } }) + const wrapper = mountSection() + await flushPromises() + + await wrapper.find('[data-testid="admin-custom-css-save"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="admin-custom-css-saved"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="admin-custom-css-removed"]').exists()).toBe(false) + }) + + it('shows the server\'s refusal, such as the size cap', async () => { + api.updateCustomCss.mockRejectedValue({ response: { data: { error: 'Custom CSS may be at most 20 KB.' } } }) + const wrapper = mountSection() + await flushPromises() + + await wrapper.find('[data-testid="admin-custom-css-save"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="admin-custom-css-error"]').text()).toBe('Custom CSS may be at most 20 KB.') + expect(wrapper.find('[data-testid="admin-custom-css-saved"]').exists()).toBe(false) + }) + + it('says so when the CSS cannot be loaded', async () => { + api.getCustomCss.mockRejectedValue(new Error('boom')) + const wrapper = mountSection() + await flushPromises() + + expect(wrapper.find('[data-testid="admin-custom-css-error"]').text()).toBe('The custom CSS could not be loaded.') + }) +}) diff --git a/src/components/admin/__tests__/AdminSettings.behaviour.spec.js b/src/components/admin/__tests__/AdminSettings.behaviour.spec.js new file mode 100644 index 000000000..f430e7d5d --- /dev/null +++ b/src/components/admin/__tests__/AdminSettings.behaviour.spec.js @@ -0,0 +1,283 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the behaviour of `AdminSettings.vue` (the tab + * markup has its own spec): loading and saving the general settings with + * quota clamping, the group dashboards it loads per configured group, the + * optimistic group default with rollback, the setup wizard, and the page + * title and breadcrumbs for the open tab. Child tabs are shallow-stubbed. + */ + +import { flushPromises, shallowMount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import AdminSettings from '../AdminSettings.vue' +import { api } from '../../../services/api.js' +import { logger } from '../../../utils/logger.js' + +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => `/index.php${path}`, +})) +vi.mock('../../../services/api.js', () => ({ + api: { + getAdminSettings: vi.fn(), + updateAdminSettings: vi.fn(), + listGroupDashboards: vi.fn(), + getSetupWizardState: vi.fn(), + setGroupDashboardDefault: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn(), warn: vi.fn() } })) + +const t = (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`) + +const GROUP_ROWS = { + default: [{ uuid: 'd1', isDefault: 1 }], + staff: [{ uuid: 's1', isDefault: 1 }, { uuid: 's2', isDefault: 0 }], +} + +async function mountSettings(provide = { configuredGroups: ['staff'] }) { + const wrapper = shallowMount(AdminSettings, { + global: { provide, mocks: { t } }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() + api.getAdminSettings.mockResolvedValue({ data: { defaultPermissionLevel: 'full', maxDashboardsPerUser: 5 } }) + api.updateAdminSettings.mockResolvedValue({}) + api.listGroupDashboards.mockImplementation(async (groupId) => ({ data: GROUP_ROWS[groupId] ?? [] })) + api.getSetupWizardState.mockResolvedValue({ data: { completed: false } }) + api.setGroupDashboardDefault.mockResolvedValue({}) +}) + +describe('AdminSettings: general settings', () => { + it('merges the stored settings and maps the permission level to its option', async () => { + const wrapper = await mountSettings() + + expect(wrapper.vm.loading).toBe(false) + expect(wrapper.vm.settings).toMatchObject({ + defaultPermissionLevel: { id: 'full', label: 'Full customization' }, + maxDashboardsPerUser: 5, + allowMultipleDashboards: true, + defaultGridColumns: 12, + }) + }) + + it('falls back to add only, reads a wrapped payload, and keeps defaults on failure', async () => { + api.getAdminSettings.mockResolvedValueOnce({ data: { data: { defaultPermissionLevel: 'odd', defaultGridColumns: 8 } } }) + const wrapped = await mountSettings() + expect(wrapped.vm.settings.defaultPermissionLevel.id).toBe('add_only') + expect(wrapped.vm.settings.defaultGridColumns).toBe(8) + + api.getAdminSettings.mockRejectedValueOnce(new Error('x')) + const failed = await mountSettings() + expect(failed.vm.settings.defaultGridColumns).toBe(12) + expect(failed.vm.loading).toBe(false) + expect(logger.error).toHaveBeenCalledWith('Failed to load admin data:', expect.any(Error)) + }) + + it('saves every setting under the API keys with clamped quotas', async () => { + const wrapper = await mountSettings() + wrapper.vm.settings.maxWidgetsPerDashboard = '20000' + + wrapper.vm.updateSetting('filterTelemetryEnabled', 'yes') + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenCalledWith({ + defaultPermLevel: 'full', + allowUserDash: false, + allowMultiDash: true, + filterTelemetryEnabled: false, + defaultAppEnabled: true, + defaultGridCols: 12, + maxDashboardsPerUser: 5, + maxWidgetsPerDashboard: 10000, + }) + }) + + it('saves the filter telemetry switch as a boolean (drill-down-cross-widget-filter REQ-CWF-010)', async () => { + const wrapper = await mountSettings() + + wrapper.vm.updateSetting('filterTelemetryEnabled', true) + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenLastCalledWith(expect.objectContaining({ filterTelemetryEnabled: true })) + expect(wrapper.find('[data-testid="admin-filter-telemetry-enabled"]').exists()).toBe(true) + }) + + it('saves the default app switch as a boolean, on unless switched off (REQ-PSP-003)', async () => { + const wrapper = await mountSettings() + + wrapper.vm.updateSetting('defaultAppEnabled', false) + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenLastCalledWith(expect.objectContaining({ defaultAppEnabled: false })) + expect(wrapper.find('[data-testid="admin-default-app-enabled"]').exists()).toBe(true) + }) + + it.each([ + ['12', 12], + [7.9, 7], + ['-3', 0], + ['abc', 0], + [undefined, 0], + [10000, 10000], + [10001, 10000], + ])('clamps a quota of %s to %s', async (value, clamped) => { + const wrapper = await mountSettings() + expect(wrapper.vm.clampQuota(value)).toBe(clamped) + }) + + it('stores the clamped quota on input and saves', async () => { + const wrapper = await mountSettings() + wrapper.vm.onQuotaInput('maxDashboardsPerUser', '-1') + await flushPromises() + + expect(wrapper.vm.settings.maxDashboardsPerUser).toBe(0) + expect(api.updateAdminSettings.mock.calls[0][0].maxDashboardsPerUser).toBe(0) + }) + + it('logs a failed save', async () => { + api.updateAdminSettings.mockRejectedValue(new Error('x')) + const wrapper = await mountSettings() + await wrapper.vm.saveSettings() + expect(logger.error).toHaveBeenCalledWith('Failed to save settings:', expect.any(Error)) + }) +}) + +describe('AdminSettings: group dashboards', () => { + it.each([ + [{}, ['default']], + [{ configuredGroups: ['staff'] }, ['default', 'staff']], + [{ configuredGroups: ['staff', 'default'] }, ['staff', 'default']], + [{ configuredGroups: 'nope' }, ['default']], + ])('loads the dashboards of the admin groups for %j', async (provide, groups) => { + const wrapper = await mountSettings(provide) + + expect(api.listGroupDashboards.mock.calls.map((c) => c[0])).toEqual(groups) + expect(Object.keys(wrapper.vm.groupSharedDashboards).sort()).toEqual([...groups].sort()) + expect(wrapper.vm.loadingGroupDashboards).toBe(false) + }) + + it('treats a failed or malformed group list as empty', async () => { + api.listGroupDashboards.mockImplementation(async (groupId) => { + if (groupId === 'staff') { + throw new Error('403') + } + return { data: 'nope' } + }) + const wrapper = await mountSettings() + + expect(wrapper.vm.groupSharedDashboards).toEqual({ default: [], staff: [] }) + expect(logger.warn).toHaveBeenCalledWith('Failed to load group dashboards for staff:', expect.any(Error)) + }) + + it('sets a group default optimistically', async () => { + const wrapper = await mountSettings() + await wrapper.vm.setGroupDefault('staff', 's2') + + expect(api.setGroupDashboardDefault).toHaveBeenCalledWith('staff', 's2') + expect(wrapper.vm.groupSharedDashboards.staff).toEqual([ + { uuid: 's1', isDefault: 0 }, + { uuid: 's2', isDefault: 1 }, + ]) + expect(wrapper.vm.groupSharedDashboards.default).toEqual(GROUP_ROWS.default) + expect(wrapper.vm.settingGroupDefault).toBeNull() + }) + + it('rolls the default back when saving it fails', async () => { + api.setGroupDashboardDefault.mockRejectedValue(new Error('x')) + const wrapper = await mountSettings() + + const pending = wrapper.vm.setGroupDefault('staff', 's2') + expect(wrapper.vm.settingGroupDefault).toBe('s2') + expect(wrapper.vm.groupSharedDashboards.staff[1].isDefault).toBe(1) + await pending + + expect(wrapper.vm.groupSharedDashboards.staff).toEqual(GROUP_ROWS.staff) + expect(logger.error).toHaveBeenCalledWith('Failed to set the group default dashboard', expect.any(Error)) + expect(wrapper.vm.settingGroupDefault).toBeNull() + }) + + it('handles a default for a group it has not loaded', async () => { + const wrapper = await mountSettings() + await wrapper.vm.setGroupDefault('unknown', 'x') + expect(wrapper.vm.groupSharedDashboards.unknown).toEqual([]) + }) +}) + +describe('AdminSettings: setup wizard', () => { + it('loads the wizard state, null when empty or failing', async () => { + expect((await mountSettings()).vm.wizardState).toEqual({ completed: false }) + + api.getSetupWizardState.mockResolvedValueOnce({ data: '' }) + expect((await mountSettings()).vm.wizardState).toBeNull() + + api.getSetupWizardState.mockRejectedValueOnce(new Error('x')) + expect((await mountSettings()).vm.wizardState).toBeNull() + expect(logger.warn).toHaveBeenCalledWith('Failed to load setup wizard state:', expect.any(Error)) + }) + + it('opens and closes, and reloads everything once completed', async () => { + const wrapper = await mountSettings() + wrapper.vm.openWizard() + expect(wrapper.vm.showWizard).toBe(true) + wrapper.vm.closeWizard() + expect(wrapper.vm.showWizard).toBe(false) + + wrapper.vm.openWizard() + vi.clearAllMocks() + await wrapper.vm.onWizardCompleted() + + expect(wrapper.vm.showWizard).toBe(false) + expect(api.getAdminSettings).toHaveBeenCalledTimes(1) + expect(api.listGroupDashboards).toHaveBeenCalledTimes(2) + expect(api.getSetupWizardState).toHaveBeenCalledTimes(1) + }) +}) + +describe('AdminSettings: title and breadcrumbs', () => { + it('names the open tab and notes organisation scope on General', async () => { + const wrapper = await mountSettings() + + expect(wrapper.vm.pageTitle).toBe('Launchpad administration: general') + expect(wrapper.vm.breadcrumbs).toEqual([ + { label: 'Administration settings', href: '/index.php/settings/admin' }, + { label: 'Launchpad' }, + { label: 'General' }, + ]) + expect(wrapper.vm.breadcrumbNote).toBe('applies to the whole organisation') + }) + + it('follows a tab change, and drops the tab crumb for an unknown tab', async () => { + const wrapper = await mountSettings() + + wrapper.vm.onTabChange('roles-permissions') + expect(wrapper.vm.pageTitle).toBe('Launchpad administration: roles and permissions') + expect(wrapper.vm.breadcrumbs[2]).toEqual({ label: 'Roles and permissions' }) + expect(wrapper.vm.breadcrumbNote).toBe('') + + wrapper.vm.onTabChange('gone') + expect(wrapper.vm.pageTitle).toBe('Launchpad administration: ') + expect(wrapper.vm.breadcrumbs).toHaveLength(2) + }) + + it('asks for the title unescaped, because the template escapes it once already', async () => { + const calls = [] + const spy = (app, text, vars, count, options) => { + calls.push({ text, options }) + return t(app, text, vars) + } + const wrapper = shallowMount(AdminSettings, { + global: { provide: { configuredGroups: ['staff'] }, mocks: { t: spy } }, + }) + await flushPromises() + void wrapper.vm.pageTitle + const title = calls.find((call) => call.text === 'Launchpad administration: {tab}') + expect(title.options).toEqual({ escape: false }) + }) +}) diff --git a/src/components/admin/__tests__/AdminSettings.officeNetworks.spec.js b/src/components/admin/__tests__/AdminSettings.officeNetworks.spec.js new file mode 100644 index 000000000..092c28f77 --- /dev/null +++ b/src/components/admin/__tests__/AdminSettings.officeNetworks.spec.js @@ -0,0 +1,114 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The "Office networks" card of `AdminSettings.vue`: it shows the stored + * ranges one per line, saves the edited list on its own, shows the server's + * refusal of a malformed range, and says whether the administrator's own + * address is inside. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-administrators-declare-the-office-networks-req-tia-001 + */ +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import AdminSettings from '../AdminSettings.vue' +import { api } from '../../../services/api.js' + +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => `/index.php${path}`, +})) +vi.mock('../../../services/api.js', () => ({ + api: { + getAdminSettings: vi.fn(), + updateAdminSettings: vi.fn(), + listGroupDashboards: vi.fn(), + getSetupWizardState: vi.fn(), + setGroupDashboardDefault: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn(), warn: vi.fn() } })) + +const t = (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_, key) => vars[key] ?? `{${key}}`) + +const ShellStub = { + name: 'CnAdminSettingsShell', + render() { + return h('div', Object.entries(this.$slots).map(([name, slot]) => h('section', { 'data-slot': name }, slot()))) + }, +} +const SectionStub = { + name: 'CnSettingsSection', + props: ['name'], + render() { + return h('div', { 'data-section': this.name }, this.$slots.default?.()) + }, +} + +/** + * Mount the admin page with the settings answer given. + * + * @param {object} settings What GET admin settings answers. + * @return {Promise<import('@vue/test-utils').VueWrapper>} + */ +async function mountPage(settings) { + api.getAdminSettings.mockResolvedValue({ data: settings }) + const stubs = { CnAdminSettingsShell: ShellStub, CnSettingsSection: SectionStub } + for (const name of ['TemplatesPage', 'OperationsTab', 'EmbedsTab', 'RolesPermissionsTab', 'VersioningAuditTab', 'SharingTab', 'KioskTab', 'OrgNavigationTab', 'DemoDataTab', 'GroupDashboardsTab', 'MetadataFieldsSettings', 'ProfileFieldsTab', 'SetupWizardModal', 'TileLaunchSettings', 'CommunitiesTab']) { + stubs[name] = { name, render: () => h('div') } + } + const wrapper = mount(AdminSettings, { + global: { provide: { configuredGroups: [], allGroups: [] }, mocks: { t }, stubs }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() + api.updateAdminSettings.mockResolvedValue({}) + api.listGroupDashboards.mockResolvedValue({ data: [] }) + api.getSetupWizardState.mockResolvedValue({ data: { complete: true } }) +}) + +describe('AdminSettings office networks', () => { + it('shows the stored ranges one per line and whether the current address is inside', async () => { + const wrapper = await mountPage({ officeNetworks: ['10.20.0.0/16', '2001:db8::/32'], currentAddress: '10.20.4.7', currentAddressInOfficeNetworks: true }) + + expect(wrapper.find('[data-testid="admin-office-networks-input"]').element.value).toBe('10.20.0.0/16\n2001:db8::/32') + expect(wrapper.find('[data-testid="admin-office-networks-current"]').text()) + .toBe('Your current address is 10.20.4.7, which is inside the office networks.') + }) + + it('says when the current address is outside', async () => { + const wrapper = await mountPage({ officeNetworks: [], currentAddress: '84.1.2.3', currentAddressInOfficeNetworks: false }) + expect(wrapper.find('[data-testid="admin-office-networks-current"]').text()) + .toBe('Your current address is 84.1.2.3, which is outside the office networks.') + }) + + it('saves the edited list on its own, trimmed and without blank lines, then reloads', async () => { + const wrapper = await mountPage({ officeNetworks: [], currentAddress: '10.20.4.7', currentAddressInOfficeNetworks: false }) + + await wrapper.find('[data-testid="admin-office-networks-input"]').setValue(' 10.20.0.0/16 \n\n2001:db8::/32') + await wrapper.find('[data-testid="admin-office-networks-save"]').trigger('click') + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenCalledTimes(1) + expect(api.updateAdminSettings).toHaveBeenCalledWith({ officeNetworks: ['10.20.0.0/16', '2001:db8::/32'] }) + expect(api.getAdminSettings).toHaveBeenCalledTimes(2) + expect(wrapper.find('[data-testid="admin-office-networks-error"]').exists()).toBe(false) + }) + + it('shows the refusal of a malformed range and does not reload', async () => { + const wrapper = await mountPage({ officeNetworks: ['10.20.0.0/16'], currentAddress: '', currentAddressInOfficeNetworks: false }) + api.updateAdminSettings.mockRejectedValue({ response: { status: 400, data: { error: 'This is not a valid network range: 10.20.0.0/40' } } }) + + await wrapper.find('[data-testid="admin-office-networks-input"]').setValue('10.20.0.0/40') + await wrapper.find('[data-testid="admin-office-networks-save"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="admin-office-networks-error"]').text()).toBe('This is not a valid network range: 10.20.0.0/40') + expect(api.getAdminSettings).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/components/admin/__tests__/AdminSettings.tabs.spec.js b/src/components/admin/__tests__/AdminSettings.tabs.spec.js new file mode 100644 index 000000000..bc1ea4a2c --- /dev/null +++ b/src/components/admin/__tests__/AdminSettings.tabs.spec.js @@ -0,0 +1,179 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The admin page opens on Algemeen (board LpBeheerAlgemeen). The library's + * admin shell draws the title, the path line and the cards; the defaults, + * group-shared dashboards and the default-app note are cards of Algemeen. + */ + +import { readFileSync } from 'fs' +import { join } from 'path' +import { describe, expect, it, vi } from 'vitest' +import AdminSettings from '../AdminSettings.vue' + +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => `/index.php${path}`, +})) + +/** + * A stand-in for `t()` that fills `{placeholders}`. + * + * @param {string} _app the app id (unused) + * @param {string} text the English source string + * @param {object} vars the placeholder values + * @return {string} the filled string + */ +function t(_app, text, vars = {}) { + return text.replace(/{(\w+)}/g, (_match, key) => vars[key] ?? `{${key}}`) +} + +/** + * Build a `this` for the computed properties, on one active tab. + * + * @param {string} activeTab the open tab's slug + * @return {object} the context + */ +function context(activeTab) { + const ctx = { t, activeTab } + ctx.beheerTabs = AdminSettings.computed.beheerTabs.call(ctx) + return ctx +} + +const source = readFileSync(join(__dirname, '../AdminSettings.vue'), 'utf8') + +describe('AdminSettings tabs', () => { + const tabs = AdminSettings.computed.beheerTabs.call({ t }) + const render = AdminSettings.render?.toString() ?? '' + + it('puts General first, the tab the shell opens on', () => { + expect(tabs[0]).toEqual({ id: 'general', label: 'General' }) + expect(tabs[1].id).toBe('templates') + }) + + it('hands the thirteen tabs to the admin shell as an underline strip', () => { + expect(tabs.map((tab) => tab.id)).toEqual([ + 'general', + 'templates', + 'operations', + 'roles-permissions', + 'versioning-audit', + 'sharing', + 'embeds', + 'kiosk', + 'communities', + 'org-navigation', + 'demo-data', + 'group-dashboards', + 'detail-fields', + 'profile-fields', + 'search-shortcuts', + 'app-catalogue', + ]) + expect(source).toContain(':tabs="beheerTabs"') + expect(render).toContain('tabsVariant: "underline"') + }) + + it('keeps the open tab in the page path, not in ?tab= or browser storage', () => { + expect(render).toContain('tabQueryKey: ""') + expect(source).not.toContain('tabStorageKey') + }) + + it('opens the tab the route names, and General for an unknown one', () => { + const data = (tab) => AdminSettings.data.call({ t, tab }).activeTab + expect(data('sharing')).toBe('sharing') + expect(data('nonsense')).toBe('general') + expect(data('')).toBe('general') + }) + + it('opens the route\'s tab in the shell without a click', () => { + const shell = { chosenTabId: '' } + const ctx = { activeTab: 'general', $refs: { shell } } + AdminSettings.methods.showTab.call(ctx, 'embeds') + expect(ctx.activeTab).toBe('embeds') + expect(shell.chosenTabId).toBe('embeds') + }) + + it('follows a new route tab (Back, Forward)', () => { + const ctx = { showTab: vi.fn() } + AdminSettings.watch.tab.call(ctx, 'kiosk') + expect(ctx.showTab).toHaveBeenCalledWith('kiosk') + AdminSettings.watch.tab.call(ctx, 'settings') + expect(ctx.showTab).toHaveBeenLastCalledWith('general') + }) + + it('gives every tab its own slot', () => { + for (const tab of tabs) { + expect(source).toContain(`<template #tab-${tab.id}>`) + } + }) + + it('lets the shell mount a tab\'s content only while that tab is open', () => { + expect(render).toContain('lazyTabs: ""') + for (const tab of tabs.slice(1)) { + const slot = new RegExp(`<template #tab-${tab.id}>\\s*<\\w+[^>]*>`) + const panel = source.match(slot) + expect(panel).not.toBeNull() + expect(panel[0]).not.toContain('v-if') + } + }) + + it('follows the tab the shell reports', () => { + expect(source).toContain('@tabChange="onTabChange"') + const ctx = { activeTab: 'general', $emit: vi.fn() } + AdminSettings.methods.onTabChange.call(ctx, 'sharing') + expect(ctx.activeTab).toBe('sharing') + // The page puts the tab in its address. + expect(ctx.$emit).toHaveBeenCalledWith('tabChange', 'sharing') + }) + + it('shows the setup wizard banner in the General panel', () => { + const general = source.indexOf('<template #tab-general>') + const banner = source.indexOf('data-test="setup-wizard-banner"') + const templates = source.indexOf('<template #tab-templates>') + expect(general).toBeGreaterThan(-1) + expect(banner).toBeGreaterThan(general) + expect(banner).toBeLessThan(templates) + }) + + it('draws the defaults as a card of General only', () => { + const general = source.indexOf('v-if="activeTab === \'general\'"') + const defaults = source.indexOf('data-testid="admin-default-settings"') + expect(general).toBeGreaterThan(-1) + expect(defaults).toBeGreaterThan(general) + }) +}) + +describe('AdminSettings page header', () => { + it('draws in the board look of the admin shell', () => { + expect(source).toContain('<CnAdminSettingsShell') + expect(source).toContain('look="board"') + expect(source).toContain(':showVersionCard="false"') + }) + + it('names the open tab in the title', () => { + expect(AdminSettings.computed.pageTitle.call(context('general'))).toBe( + 'Launchpad administration: general', + ) + expect(AdminSettings.computed.pageTitle.call(context('templates'))).toBe( + 'Launchpad administration: templates', + ) + }) + + it('ends the path on the open tab, the first step a link', () => { + const crumbs = AdminSettings.computed.breadcrumbs.call(context('general')) + expect(crumbs).toEqual([ + { label: 'Administration settings', href: '/index.php/settings/admin' }, + { label: 'Launchpad' }, + { label: 'General' }, + ]) + }) + + it('notes the reach of Algemeen only', () => { + expect(AdminSettings.computed.breadcrumbNote.call(context('general'))).toBe( + 'applies to the whole organisation', + ) + expect(AdminSettings.computed.breadcrumbNote.call(context('kiosk'))).toBe('') + }) +}) diff --git a/src/components/admin/__tests__/AdminSettings.template.spec.js b/src/components/admin/__tests__/AdminSettings.template.spec.js new file mode 100644 index 000000000..d289a8a2c --- /dev/null +++ b/src/components/admin/__tests__/AdminSettings.template.spec.js @@ -0,0 +1,248 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The template wiring of `AdminSettings.vue`: which component each tab slot + * draws and with which props, which handler each General control calls, + * and the wizard banner and group-default buttons. The admin shell is + * replaced by a stand-in that renders every slot it is given, so the slot + * contents are rendered here rather than only read as source text. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import AdminSettings from '../AdminSettings.vue' +import { api } from '../../../services/api.js' + +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => `/index.php${path}`, +})) +vi.mock('../../../services/api.js', () => ({ + api: { + getAdminSettings: vi.fn(), + updateAdminSettings: vi.fn(), + listGroupDashboards: vi.fn(), + getSetupWizardState: vi.fn(), + setGroupDashboardDefault: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn(), warn: vi.fn() } })) + +const t = (_app, text) => text + +/** Renders every slot it receives, each in a section named after the slot. */ +const ShellStub = { + name: 'CnAdminSettingsShell', + emits: ['tabChange'], + render() { + return h( + 'div', + Object.entries(this.$slots).map(([name, slot]) => + h('section', { 'data-slot': name }, slot()), + ), + ) + }, +} + +/** Renders its default slot so the cards' contents mount. */ +const SectionStub = { + name: 'CnSettingsSection', + props: ['name'], + render() { + return h('div', { 'data-section': this.name }, this.$slots.default?.()) + }, +} + +const TABS = [ + 'TemplatesPage', + 'OperationsTab', + 'RolesPermissionsTab', + 'VersioningAuditTab', + 'SharingTab', + 'KioskTab', + 'OrgNavigationTab', + 'DemoDataTab', + 'GroupDashboardsTab', + 'EmbedsTab', + 'MetadataFieldsSettings', + 'ProfileFieldsTab', + 'SetupWizardModal', +] + +const GROUP_ROWS = { + default: [{ uuid: 'd1', name: 'Main', icon: 'Star', isDefault: 1 }], + staff: [ + { uuid: 's1', name: 'Staff A', icon: 'Star', isDefault: 1 }, + { uuid: 's2', name: 'Staff B', icon: 'Star', isDefault: 0 }, + ], + empty: [], +} + +async function mountPage(provide = {}) { + const stubs = { CnAdminSettingsShell: ShellStub, CnSettingsSection: SectionStub } + for (const name of TABS) { + stubs[name] = { name, props: ['groups', 'configuredGroups'], render: () => h('div', { 'data-tab': name }) } + } + const wrapper = mount(AdminSettings, { + global: { + provide: { configuredGroups: ['staff', 'empty'], allGroups: ['admin', 'staff'], ...provide }, + mocks: { t }, + stubs, + }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() + api.getAdminSettings.mockResolvedValue({ data: { defaultPermissionLevel: 'full' } }) + api.updateAdminSettings.mockResolvedValue({}) + api.listGroupDashboards.mockImplementation(async (groupId) => ({ data: GROUP_ROWS[groupId] ?? [] })) + api.getSetupWizardState.mockResolvedValue({ data: { complete: false } }) + api.setGroupDashboardDefault.mockResolvedValue({}) +}) + +describe('AdminSettings tab slots', () => { + it('draws each tab component in its own slot', async () => { + const wrapper = await mountPage() + const expected = { + 'tab-templates': 'TemplatesPage', + 'tab-operations': 'OperationsTab', + 'tab-roles-permissions': 'RolesPermissionsTab', + 'tab-versioning-audit': 'VersioningAuditTab', + 'tab-sharing': 'SharingTab', + 'tab-kiosk': 'KioskTab', + 'tab-org-navigation': 'OrgNavigationTab', + 'tab-demo-data': 'DemoDataTab', + 'tab-group-dashboards': 'GroupDashboardsTab', + 'tab-embeds': 'EmbedsTab', + 'tab-detail-fields': 'MetadataFieldsSettings', + 'tab-profile-fields': 'ProfileFieldsTab', + } + for (const [slot, tab] of Object.entries(expected)) { + const section = wrapper.find(`[data-slot="${slot}"]`) + expect(section.exists()).toBe(true) + expect(section.find(`[data-tab="${tab}"]`).exists()).toBe(true) + } + }) + + it('hands the injected groups to the sharing and org-navigation tabs', async () => { + const wrapper = await mountPage() + + const sharing = wrapper.findComponent({ name: 'SharingTab' }) + expect(sharing.props('groups')).toEqual(['admin', 'staff']) + expect(sharing.props('configuredGroups')).toEqual(['staff', 'empty']) + expect(wrapper.findComponent({ name: 'OrgNavigationTab' }).props('groups')).toEqual(['admin', 'staff']) + }) + + it('follows the tab the shell reports and drops the General cards elsewhere', async () => { + const wrapper = await mountPage() + expect(wrapper.find('[data-section="Default settings"]').exists()).toBe(true) + + wrapper.findComponent({ name: 'CnAdminSettingsShell' }).vm.$emit('tabChange', 'kiosk') + await flushPromises() + + expect(wrapper.vm.activeTab).toBe('kiosk') + expect(wrapper.find('[data-section="Default settings"]').exists()).toBe(false) + }) +}) + +describe('AdminSettings setup wizard banner', () => { + it('opens the wizard from the banner while setup is not complete', async () => { + const wrapper = await mountPage() + expect(wrapper.find('[data-test="setup-wizard-rerun"]').exists()).toBe(false) + + await wrapper.find('[data-test="setup-wizard-open"]').trigger('click') + + expect(wrapper.find('[data-tab="SetupWizardModal"]').exists()).toBe(true) + }) + + it('offers a re-run once setup is complete', async () => { + api.getSetupWizardState.mockResolvedValue({ data: { complete: true } }) + const wrapper = await mountPage() + expect(wrapper.find('[data-test="setup-wizard-banner"]').exists()).toBe(false) + + await wrapper.find('[data-test="setup-wizard-rerun-open"]').trigger('click') + + expect(wrapper.vm.showWizard).toBe(true) + }) + + it('shows neither without a wizard state', async () => { + api.getSetupWizardState.mockRejectedValue(new Error('down')) + const wrapper = await mountPage() + + expect(wrapper.find('[data-test="setup-wizard-banner"]').exists()).toBe(false) + expect(wrapper.find('[data-test="setup-wizard-rerun"]').exists()).toBe(false) + }) +}) + +describe('AdminSettings General controls', () => { + const savedPayload = () => api.updateAdminSettings.mock.calls.at(-1)[0] + + it('saves the permission level and grid columns picked in the selects', async () => { + const wrapper = await mountPage() + const [permission, columns] = wrapper.findAllComponents({ name: 'NcSelect' }) + + permission.vm.$emit('update:modelValue', { id: 'view_only', label: 'View only' }) + await flushPromises() + expect(savedPayload().defaultPermLevel).toBe('view_only') + + columns.vm.$emit('update:modelValue', 8) + await flushPromises() + expect(savedPayload().defaultGridCols).toBe(8) + }) + + it('saves each switch under its own setting', async () => { + const wrapper = await mountPage() + const [allowUser, allowMultiple] = wrapper.findAllComponents({ name: 'NcCheckboxRadioSwitch' }) + + allowUser.vm.$emit('update:modelValue', true) + await flushPromises() + expect(savedPayload().allowUserDash).toBe(true) + + allowMultiple.vm.$emit('update:modelValue', false) + await flushPromises() + expect(savedPayload().allowMultiDash).toBe(false) + + expect(savedPayload()).not.toHaveProperty('startPageWithoutNavigation') + }) + + it('clamps and saves each quota field', async () => { + const wrapper = await mountPage() + const [dashboards, widgets] = wrapper.findAllComponents({ name: 'NcTextField' }) + + dashboards.vm.$emit('update:modelValue', '25') + await flushPromises() + expect(savedPayload().maxDashboardsPerUser).toBe(25) + + widgets.vm.$emit('update:modelValue', '99999') + await flushPromises() + expect(savedPayload().maxWidgetsPerDashboard).toBe(10000) + expect(wrapper.vm.settings.maxWidgetsPerDashboard).toBe(10000) + }) +}) + +describe('AdminSettings group-shared dashboards card', () => { + it('lists each group, marks its default and notes an empty group', async () => { + const wrapper = await mountPage() + const card = wrapper.find('[data-section="Group-shared dashboards"]') + + expect(card.findAll('h4').map((h4) => h4.text())).toEqual(['default', 'staff', 'empty']) + expect(card.findAll('[data-test="group-default-badge"]')).toHaveLength(2) + expect(card.findAll('[data-test="set-group-default"]')).toHaveLength(1) + expect(card.text()).toContain('No group-shared dashboards in this group yet.') + }) + + it('promotes a dashboard from its button', async () => { + const wrapper = await mountPage() + + await wrapper.find('[data-test="set-group-default"]').trigger('click') + await flushPromises() + + expect(api.setGroupDashboardDefault).toHaveBeenCalledWith('staff', 's2') + expect(wrapper.vm.groupSharedDashboards.staff.map((d) => d.isDefault)).toEqual([0, 1]) + }) +}) diff --git a/src/components/admin/__tests__/AllowedSitesSettings.spec.js b/src/components/admin/__tests__/AllowedSitesSettings.spec.js new file mode 100644 index 000000000..2a9e5f7db --- /dev/null +++ b/src/components/admin/__tests__/AllowedSitesSettings.spec.js @@ -0,0 +1,112 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * AllowedSitesSettings: the General tab's "Allowed websites" block lists the + * hosts with their purpose, adds and removes one, and saves the list through + * PUT /api/admin/allowed-sites; a refusal shows the server's message + * (REQ-ASET-021). + * + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../../services/api.js' + +vi.mock('../../../services/api.js', () => ({ + api: { getAllowedSites: vi.fn(), updateAllowedSites: vi.fn() }, +})) +vi.mock('@nextcloud/dialogs', () => ({ showSuccess: vi.fn() })) + +const { default: AllowedSitesSettings } = await import('../AllowedSitesSettings.vue') + +const stubs = { + CnSettingsSection: { name: 'CnSettingsSection', props: ['name'], template: '<section :data-name="name"><slot /></section>' }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: '<input class="text-field" :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options'], + emits: ['update:modelValue'], + template: '<select class="select" :value="modelValue && modelValue.id" @change="$emit(\'update:modelValue\', options.find((o) => o.id === $event.target.value))"><option v-for="o in options" :key="o.id" :value="o.id">{{ o.label }}</option></select>', + }, + NcButton: { + name: 'NcButton', + props: ['type', 'disabled', 'ariaLabel'], + emits: ['click'], + template: '<button class="button" :type="type || \'button\'" :disabled="disabled" :aria-label="ariaLabel" @click="$emit(\'click\')"><slot /></button>', + }, +} + +const board = { + data: { + sites: [ + { host: 'www.zuiddrecht.nl', embed: true, fetch: true }, + { host: 'app.powerbi.com', embed: true, fetch: false }, + ], + }, +} + +async function mountSettings() { + const wrapper = mount(AllowedSitesSettings, { global: { stubs } }) + await flushPromises() + return wrapper +} + +describe('AllowedSitesSettings', () => { + beforeEach(() => { + vi.clearAllMocks() + api.getAllowedSites.mockResolvedValue(board) + api.updateAllowedSites.mockImplementation(async (sites) => ({ data: { sites } })) + }) + + it('lists every host with its purpose', async () => { + const wrapper = await mountSettings() + const rows = wrapper.findAll('[data-testid="admin-allowed-site"]') + expect(rows).toHaveLength(2) + expect(rows[0].text()).toContain('www.zuiddrecht.nl') + expect(rows[0].find('select').element.value).toBe('both') + expect(rows[1].find('select').element.value).toBe('embed') + }) + + it('adds a website for Fetch, changes a purpose, removes one and saves the list', async () => { + const wrapper = await mountSettings() + await wrapper.find('[data-testid="admin-allowed-site-input"]').setValue('kcc-api.zuiddrecht.nl') + await wrapper.find('[data-testid="admin-allowed-site-purpose"]').setValue('fetch') + await wrapper.find('form').trigger('submit') + await wrapper.findAll('[data-testid="admin-allowed-site"]')[1].find('select').setValue('both') + await wrapper.findAll('[data-testid="admin-allowed-site"]')[0].find('button').trigger('click') + await wrapper.find('[data-testid="admin-allowed-sites-save"]').trigger('click') + await flushPromises() + + expect(api.updateAllowedSites).toHaveBeenCalledWith([ + { host: 'app.powerbi.com', embed: true, fetch: true }, + { host: 'kcc-api.zuiddrecht.nl', embed: false, fetch: true }, + ]) + expect(wrapper.findAll('[data-testid="admin-allowed-site"]')).toHaveLength(2) + expect(wrapper.find('[data-testid="admin-allowed-site-input"]').element.value).toBe('') + }) + + it('shows the server refusal and keeps the rows', async () => { + api.updateAllowedSites.mockRejectedValue({ response: { data: { message: '"*.zuiddrecht.nl" is not a host name.' } } }) + const wrapper = await mountSettings() + await wrapper.find('[data-testid="admin-allowed-site-input"]').setValue('*.zuiddrecht.nl') + await wrapper.find('form').trigger('submit') + await wrapper.find('[data-testid="admin-allowed-sites-save"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="admin-allowed-sites-error"]').text()).toBe('"*.zuiddrecht.nl" is not a host name.') + expect(wrapper.findAll('[data-testid="admin-allowed-site"]')).toHaveLength(3) + }) + + it('says when the list is empty, also when it cannot be read', async () => { + api.getAllowedSites.mockRejectedValue(new Error('offline')) + const wrapper = await mountSettings() + expect(wrapper.find('[data-testid="admin-allowed-sites-empty"]').exists()).toBe(true) + }) +}) diff --git a/src/components/admin/__tests__/BeheerTabs.spec.js b/src/components/admin/__tests__/BeheerTabs.spec.js deleted file mode 100644 index 6c2f90313..000000000 --- a/src/components/admin/__tests__/BeheerTabs.spec.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - * - * Vitest unit tests for `BeheerTabs.vue` (admin-settings spec). Covers: - * - tab switching renders only the active tab's slot - * - selecting a tab persists the slug to localStorage - * - the `?tab=` query string wins over the persisted value on first paint - * - the default tab is used when neither query nor storage is set - */ - -import { mount } from '@vue/test-utils' -import { beforeEach, describe, expect, it } from 'vitest' -import BeheerTabs, { ACTIVE_TAB_STORAGE_KEY } from '../BeheerTabs.vue' - -const tabs = [ - { slug: 'templates', label: 'Templates' }, - { slug: 'operations', label: 'Operations' }, - { slug: 'roles-permissions', label: 'Roles & Permissions' }, -] - -function mountTabs(props = {}, search = '') { - // Stub window.location.search for the deep-link path. - delete window.location - window.location = { search } - return mount(BeheerTabs, { - propsData: { tabs, defaultTab: 'templates', ...props }, - // VTU v2 merged v1's `scopedSlots` into `slots`; the v1 key is - // silently ignored, so every slot rendered empty. - slots: { - templates: '<div data-test="slot-templates">TEMPLATES</div>', - operations: '<div data-test="slot-operations">OPERATIONS</div>', - 'roles-permissions': '<div data-test="slot-roles">ROLES</div>', - }, - }) -} - -beforeEach(() => { - globalThis.t = (_app, key) => key - localStorage.clear() -}) - -describe('BeheerTabs', () => { - it('renders only the default tab slot on first visit', () => { - const wrapper = mountTabs() - expect(wrapper.find('[data-test="slot-templates"]').exists()).toBe(true) - expect(wrapper.find('[data-test="slot-operations"]').exists()).toBe(false) - expect(wrapper.find('[data-test="slot-roles"]').exists()).toBe(false) - }) - - it('switches the active tab and renders only that slot', async () => { - const wrapper = mountTabs() - await wrapper.find('[data-test="tab-operations"]').trigger('click') - expect(wrapper.find('[data-test="slot-operations"]').exists()).toBe(true) - expect(wrapper.find('[data-test="slot-templates"]').exists()).toBe(false) - }) - - it('persists the selected tab to localStorage', async () => { - const wrapper = mountTabs() - await wrapper.find('[data-test="tab-roles-permissions"]').trigger('click') - expect(localStorage.getItem(ACTIVE_TAB_STORAGE_KEY)).toBe( - 'roles-permissions', - ) - }) - - it('restores the persisted tab on next mount', () => { - localStorage.setItem(ACTIVE_TAB_STORAGE_KEY, 'operations') - const wrapper = mountTabs() - expect(wrapper.find('[data-test="slot-operations"]').exists()).toBe(true) - }) - - it('deep-links to a tab via the ?tab= query string (wins over storage)', () => { - localStorage.setItem(ACTIVE_TAB_STORAGE_KEY, 'operations') - const wrapper = mountTabs({}, '?tab=roles-permissions') - expect(wrapper.find('[data-test="slot-roles"]').exists()).toBe(true) - expect(wrapper.find('[data-test="slot-operations"]').exists()).toBe(false) - }) - - it('emits change with the active slug on mount and on switch', async () => { - const wrapper = mountTabs() - expect(wrapper.emitted('change')[0]).toEqual(['templates']) - await wrapper.find('[data-test="tab-operations"]').trigger('click') - expect(wrapper.emitted('change').at(-1)).toEqual(['operations']) - }) - - it('ignores an unknown ?tab= value and falls back to the default', () => { - const wrapper = mountTabs({}, '?tab=does-not-exist') - expect(wrapper.find('[data-test="slot-templates"]').exists()).toBe(true) - }) -}) diff --git a/src/components/admin/__tests__/ConfirmDeleteFlows.spec.js b/src/components/admin/__tests__/ConfirmDeleteFlows.spec.js new file mode 100644 index 000000000..a96cd716b --- /dev/null +++ b/src/components/admin/__tests__/ConfirmDeleteFlows.spec.js @@ -0,0 +1,371 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The confirm-then-act flows of four admin screens: deleting a group + * dashboard, a role permission and a role layout default, and removing a + * demo showcase. Each case opens the confirmation, checks its texts, then + * confirms or cancels and checks what reached the store or the API. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ManageGroupDashboardsModal from '../../../dialogs/ManageGroupDashboardsModal.vue' +import AdminDemoData from '../AdminDemoData.vue' +import RoleLayoutDefaultsSection from '../RoleLayoutDefaultsSection.vue' +import RolePermissionsSection from '../RolePermissionsSection.vue' +import { api } from '../../../services/api.js' +import { useGroupDashboardsStore } from '../../../stores/groupDashboards.js' +import { useRoleFeaturePermissionStore } from '../../../stores/roleFeaturePermissions.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { + get: vi.fn(() => Promise.resolve({ data: [] })), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/dialogs', () => ({ showSuccess: vi.fn(), showError: vi.fn() })) +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text) => text, + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), + n: (_app, one, many, count) => (count === 1 ? one : many), +})) +vi.mock('../../../services/api.js', () => ({ + api: { + listDemoShowcases: vi.fn(), + installDemoShowcase: vi.fn(), + uninstallDemoShowcase: vi.fn(), + }, +})) + +vi.mock('@conduction/nextcloud-vue', () => { + const ncButton = { + name: 'NcButton', + props: ['variant', 'disabled'], + emits: ['click'], + template: + '<button :data-variant="variant" @click="$emit(\'click\')"><slot /></button>', + } + return { + NcButton: ncButton, + NcEmptyContent: { name: 'NcEmptyContent', template: '<div><slot /></div>' }, + NcModal: { name: 'NcModal', template: '<div><slot /></div>' }, + NcTextField: { name: 'NcTextField', template: '<input>' }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + template: '<div />', + }, + NcSelect: { name: 'NcSelect', template: '<div />' }, + NcSelectTags: { name: 'NcSelectTags', template: '<div />' }, + NcPasswordField: { name: 'NcPasswordField', template: '<input>' }, + NcLoadingIcon: { name: 'NcLoadingIcon', template: '<span />' }, + NcNoteCard: { name: 'NcNoteCard', template: '<div><slot /></div>' }, + CnDashboardIcon: { name: 'CnDashboardIcon', template: '<span />' }, + CnIconBrowser: { name: 'CnIconBrowser', template: '<div />' }, + CnSettingsSection: { + name: 'CnSettingsSection', + template: '<div><slot /></div>', + }, + CnAdminSettingsShell: { + name: 'CnAdminSettingsShell', + template: '<div><slot /></div>', + }, + NcDialog: { + name: 'NcDialog', + props: ['name', 'open'], + emits: ['update:open'], + template: + '<div v-if="open" class="confirm"><h2>{{ name }}</h2><slot /><slot name="actions" /></div>', + }, + CnConfirmDialog: { + name: 'CnConfirmDialog', + components: { NcButton: ncButton }, + props: ['dialogTitle', 'message', 'confirmLabel', 'variant'], + emits: ['confirm', 'close'], + data: () => ({ result: null }), + methods: { + setResult(result) { + this.result = result + }, + }, + template: + '<div class="confirm"><h2>{{ dialogTitle }}</h2><p>{{ message }}</p>' + + '<p v-if="result" class="result">{{ result.error }}</p>' + + '<NcButton @click="$emit(\'close\')">Cancel</NcButton>' + + '<NcButton :variant="variant" @click="$emit(\'confirm\')">{{ confirmLabel }}</NcButton></div>', + }, + } +}) +vi.mock('@nextcloud/vue', () => { + const plain = (name) => ({ name, template: '<div><slot /></div>' }) + return { + NcButton: { + name: 'NcButton', + props: ['variant', 'disabled'], + emits: ['click'], + template: + '<button :data-variant="variant" @click="$emit(\'click\')"><slot /></button>', + }, + NcDialog: { + name: 'NcDialog', + props: ['name', 'open'], + template: '<div><slot /><slot name="actions" /></div>', + }, + NcEmptyContent: plain('NcEmptyContent'), + NcLoadingIcon: plain('NcLoadingIcon'), + NcNoteCard: plain('NcNoteCard'), + } +}) + +const tMixin = { + methods: { + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), + n: (_app, one, many, count) => (count === 1 ? one : many), + }, +} + +/** + * Mount a component with the global t/n mixin the app installs. + * + * @param {object} component The component. + * @param {object} props Its props. + * @return {object} The wrapper. + */ +function mountWith(component, props = {}) { + return mount(component, { + props, + global: { mixins: [tMixin], stubs: { teleport: true } }, + }) +} + +/** + * The open confirmation, its texts and its two buttons. + * + * @param {object} wrapper The wrapper. + * @return {object} The confirmation's parts. + */ +function confirmation(wrapper) { + const box = wrapper.find('.confirm') + if (!box.exists()) { + return null + } + const buttons = box.findAll('button') + return { + text: box.text(), + cancel: buttons.find((b) => b.text() === 'Cancel'), + confirm: buttons[buttons.length - 1], + } +} + +beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() +}) + +describe('group dashboard delete', () => { + /** + * Mount the modal with one group dashboard and open its delete question. + * + * @return {Promise<object>} The wrapper and the store. + */ + async function openDelete() { + const store = useGroupDashboardsStore() + store.fetchGroupDashboards = vi.fn(() => Promise.resolve()) + store.delete = vi.fn(() => Promise.resolve()) + const wrapper = mountWith(ManageGroupDashboardsModal, { + group: { id: 'staff', displayName: 'Staff' }, + }) + await flushPromises() + wrapper.vm.onDelete({ uuid: 'd-1', name: 'Rooster' }) + await flushPromises() + return { wrapper, store } + } + + it('asks first, then deletes the dashboard of that group', async () => { + const { wrapper, store } = await openDelete() + const c = confirmation(wrapper) + expect(c.text).toContain('Delete dashboard') + expect(c.text).toContain('Delete this dashboard? This cannot be undone.') + expect(c.confirm.text()).toBe('Delete') + expect(c.confirm.attributes('data-variant')).toBe('error') + expect(store.delete).not.toHaveBeenCalled() + await c.confirm.trigger('click') + await flushPromises() + expect(store.delete).toHaveBeenCalledWith('staff', 'd-1') + expect(confirmation(wrapper)).toBeNull() + }) + + it('cancel closes without deleting', async () => { + const { wrapper, store } = await openDelete() + await confirmation(wrapper).cancel.trigger('click') + await flushPromises() + expect(confirmation(wrapper)).toBeNull() + expect(store.delete).not.toHaveBeenCalled() + }) +}) + +describe('role permission delete', () => { + /** + * Mount the section and open the delete question for one row. + * + * @param {Function} deleteImpl The store's delete. + * @return {Promise<object>} The wrapper and the store. + */ + async function openDelete(deleteImpl) { + const store = useRoleFeaturePermissionStore() + store.loadPermissions = vi.fn(() => Promise.resolve()) + store.deletePermission = vi.fn(deleteImpl) + const wrapper = mountWith(RolePermissionsSection) + await flushPromises() + wrapper.vm.confirmDelete({ id: 7, groupId: 'finance' }) + await flushPromises() + return { wrapper, store } + } + + it('names the group, deletes on confirm and closes', async () => { + const { wrapper, store } = await openDelete(() => Promise.resolve()) + const c = confirmation(wrapper) + expect(c.text).toContain('Delete role permission') + expect(c.text).toContain('Delete role permission for group "finance"?') + expect(c.confirm.attributes('data-variant')).toBe('error') + await c.confirm.trigger('click') + await flushPromises() + expect(store.deletePermission).toHaveBeenCalledWith(7) + expect(confirmation(wrapper)).toBeNull() + }) + + it('a failed delete keeps the question open and leaves the row', async () => { + const { wrapper, store } = await openDelete(() => { + store.error = 'Server said no' + return Promise.reject(new Error('Server said no')) + }) + await confirmation(wrapper).confirm.trigger('click') + await flushPromises() + expect(store.deletePermission).toHaveBeenCalledWith(7) + expect(confirmation(wrapper)).not.toBeNull() + expect(wrapper.vm.deleteTarget).toEqual({ id: 7, groupId: 'finance' }) + }) + + it('a failed delete shows the store error in the confirmation', async () => { + const { wrapper, store } = await openDelete(() => { + store.error = 'Server said no' + return Promise.reject(new Error('Server said no')) + }) + await confirmation(wrapper).confirm.trigger('click') + await flushPromises() + expect(wrapper.find('.result').text()).toBe('Server said no') + }) + + it('cancel closes without deleting', async () => { + const { wrapper, store } = await openDelete(() => Promise.resolve()) + await confirmation(wrapper).cancel.trigger('click') + await flushPromises() + expect(confirmation(wrapper)).toBeNull() + expect(store.deletePermission).not.toHaveBeenCalled() + }) +}) + +describe('role layout default delete', () => { + /** + * Mount the section and open the delete question for one row. + * + * @param {Function} deleteImpl The store's delete. + * @return {Promise<object>} The wrapper and the store. + */ + async function openDelete(deleteImpl) { + const store = useRoleFeaturePermissionStore() + store.loadLayoutDefaults = vi.fn(() => Promise.resolve()) + store.deleteLayoutDefault = vi.fn(deleteImpl) + const wrapper = mountWith(RoleLayoutDefaultsSection) + await flushPromises() + wrapper.vm.openDeleteDialog({ id: 3, groupId: 'hr', widgetId: 'news' }) + await flushPromises() + return { wrapper, store } + } + + it('names the group and widget, deletes on confirm and closes', async () => { + const { wrapper, store } = await openDelete(() => Promise.resolve()) + const c = confirmation(wrapper) + expect(c.text).toContain('Delete layout default') + expect(c.text).toContain('Delete layout default for "hr" / "news"?') + expect(c.confirm.attributes('data-variant')).toBe('error') + await c.confirm.trigger('click') + await flushPromises() + expect(store.deleteLayoutDefault).toHaveBeenCalledWith(3) + expect(confirmation(wrapper)).toBeNull() + }) + + it('a failed delete keeps the question open', async () => { + const { wrapper, store } = await openDelete(() => + Promise.reject(new Error('no')), + ) + await confirmation(wrapper).confirm.trigger('click') + await flushPromises() + expect(store.deleteLayoutDefault).toHaveBeenCalledWith(3) + expect(confirmation(wrapper)).not.toBeNull() + }) + + it('a failed delete shows the store error in the confirmation', async () => { + const { wrapper, store } = await openDelete(() => { + store.error = 'Server said no' + return Promise.reject(new Error('Server said no')) + }) + await confirmation(wrapper).confirm.trigger('click') + await flushPromises() + expect(wrapper.find('.result').text()).toBe('Server said no') + }) + + it('cancel closes without deleting', async () => { + const { wrapper, store } = await openDelete(() => Promise.resolve()) + await confirmation(wrapper).cancel.trigger('click') + await flushPromises() + expect(confirmation(wrapper)).toBeNull() + expect(store.deleteLayoutDefault).not.toHaveBeenCalled() + }) +}) + +describe('demo showcase removal', () => { + /** + * Mount the demo data screen with one installed showcase and ask to remove it. + * + * @return {Promise<object>} The wrapper. + */ + async function openRemove() { + api.listDemoShowcases.mockResolvedValue({ data: [] }) + api.uninstallDemoShowcase.mockResolvedValue({ data: {} }) + const wrapper = mountWith(AdminDemoData) + await flushPromises() + wrapper.vm.uninstallTarget = { id: 'school', name: 'School' } + await flushPromises() + return wrapper + } + + it('names the showcase and removes it on confirm', async () => { + const wrapper = await openRemove() + const c = confirmation(wrapper) + expect(c.text).toContain('Remove showcase dashboard') + expect(c.text).toContain( + 'Remove the School showcase dashboard for all users? You can reinstall it later.', + ) + expect(c.confirm.text()).toBe('Remove') + expect(c.confirm.attributes('data-variant')).toBe('error') + await c.confirm.trigger('click') + await flushPromises() + expect(api.uninstallDemoShowcase).toHaveBeenCalledWith('school') + expect(confirmation(wrapper)).toBeNull() + }) + + it('cancel closes without removing', async () => { + const wrapper = await openRemove() + await confirmation(wrapper).cancel.trigger('click') + await flushPromises() + expect(confirmation(wrapper)).toBeNull() + expect(api.uninstallDemoShowcase).not.toHaveBeenCalled() + }) +}) diff --git a/src/components/admin/__tests__/ConfluenceImport.spec.js b/src/components/admin/__tests__/ConfluenceImport.spec.js new file mode 100644 index 000000000..d498d3578 --- /dev/null +++ b/src/components/admin/__tests__/ConfluenceImport.spec.js @@ -0,0 +1,158 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `ConfluenceImport.vue`: picking the archive, the + * dry-run preview and the import (with the optional parent), the busy + * labels, the results and the server or fallback error message. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ConfluenceImport from '../ConfluenceImport.vue' +import { api } from '../../../services/api.js' +import { logger } from '../../../utils/logger.js' + +vi.mock('../../../services/api.js', () => ({ + api: { confluenceImportDryRun: vi.fn(), confluenceImport: vi.fn() }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const ButtonStub = { + props: ['disabled'], + emits: ['click'], + template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', +} + +const ZIP = new File(['zip'], 'export.zip', { type: 'application/zip' }) + +function mountImport() { + return mount(ConfluenceImport, { + global: { stubs: { NcButton: ButtonStub, Eye: true, Upload: true } }, + }) +} + +const dryRunButton = (w) => w.find('[data-test="confluence-dry-run"]') +const importButton = (w) => w.find('[data-test="confluence-import-submit"]') + +/** + * Select a file on the archive input. + * + * @param {object} wrapper the mounted component. + * @param {File[]} files the selected files. + */ +async function pick(wrapper, files) { + const input = wrapper.find('[data-test="confluence-import-file"]') + Object.defineProperty(input.element, 'files', { value: files, configurable: true }) + await input.trigger('change') +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('ConfluenceImport', () => { + it('disables both actions until an archive is picked, and takes the picked file', async () => { + const wrapper = mountImport() + expect(dryRunButton(wrapper).attributes('disabled')).toBeDefined() + expect(importButton(wrapper).attributes('disabled')).toBeDefined() + + await pick(wrapper, [ZIP]) + expect(wrapper.vm.selectedFile).toBe(ZIP) + + await pick(wrapper, []) + expect(wrapper.vm.selectedFile).toBeNull() + }) + + it('does nothing without an archive', async () => { + const wrapper = mountImport() + await wrapper.vm.runDryRun() + await wrapper.vm.runImport() + expect(api.confluenceImportDryRun).not.toHaveBeenCalled() + expect(api.confluenceImport).not.toHaveBeenCalled() + }) + + it('previews the archive and lists its warnings', async () => { + let resolve + api.confluenceImportDryRun.mockReturnValue(new Promise((r) => { resolve = r })) + const wrapper = mountImport() + await pick(wrapper, [ZIP]) + + const pending = wrapper.vm.runDryRun() + await wrapper.vm.$nextTick() + expect(dryRunButton(wrapper).text()).toBe('Inspecting…') + expect(importButton(wrapper).attributes('disabled')).toBeDefined() + + resolve({ data: { pageCount: 4, attachmentCount: 2, estimatedDashboards: 4, assetFolder: '/Confluence', warnings: ['Skipped macro'] } }) + await pending + await flushPromises() + + expect(api.confluenceImportDryRun).toHaveBeenCalledWith(ZIP) + expect(wrapper.vm.dryRunResult.estimatedDashboards).toBe(4) + expect(wrapper.find('.launchpad-confluence-import__sub').exists()).toBe(true) + expect(wrapper.findAll('.launchpad-confluence-import__result li').map((li) => li.text())).toEqual(['Skipped macro']) + expect(dryRunButton(wrapper).text()).toBe('Dry-run preview') + }) + + it('imports under the given parent, replacing the preview with the result', async () => { + api.confluenceImportDryRun.mockResolvedValue({ data: { pageCount: 1 } }) + api.confluenceImport.mockResolvedValue({ + data: { createdDashboardCount: 3, skippedPageCount: 1, errors: [{ pageId: 'p9', reason: 'empty' }], warnings: ['w1'] }, + }) + const wrapper = mountImport() + await pick(wrapper, [ZIP]) + await wrapper.vm.runDryRun() + await flushPromises() + await wrapper.find('#launchpad-cfli-parent').setValue('parent-uuid') + + await wrapper.vm.runImport() + await flushPromises() + + expect(api.confluenceImport).toHaveBeenCalledWith(ZIP, { parentUuid: 'parent-uuid' }) + expect(wrapper.vm.dryRunResult).toBeNull() + expect(wrapper.findAll('.launchpad-confluence-import__result li').map((li) => li.text())).toEqual(['p9: empty', 'w1']) + expect(wrapper.find('.launchpad-confluence-import__sub').exists()).toBe(false) + }) + + it('imports as root dashboards without a parent', async () => { + api.confluenceImport.mockResolvedValue({ data: {} }) + const wrapper = mountImport() + await pick(wrapper, [ZIP]) + await wrapper.vm.runImport() + await flushPromises() + expect(api.confluenceImport).toHaveBeenCalledWith(ZIP, { parentUuid: null }) + }) + + it('shows the server error message, else a fallback, and logs', async () => { + api.confluenceImportDryRun.mockRejectedValue({ response: { data: { error: 'Not a Confluence export' } } }) + api.confluenceImport.mockRejectedValue(new Error('network')) + const wrapper = mountImport() + await pick(wrapper, [ZIP]) + + await wrapper.vm.runDryRun() + await flushPromises() + expect(wrapper.find('.launchpad-confluence-import__error').text()).toBe('Not a Confluence export') + + await wrapper.vm.runImport() + await flushPromises() + expect(wrapper.find('.launchpad-confluence-import__error').text()).toBe('Confluence import failed. Please try again.') + expect(wrapper.vm.running).toBe('') + expect(logger.error.mock.calls.map((c) => c[0])).toEqual([ + 'launchpad confluence dry-run failed', + 'launchpad confluence import failed', + ]) + }) + + it('clears results and errors when another archive is picked', async () => { + api.confluenceImportDryRun.mockRejectedValue(new Error('x')) + const wrapper = mountImport() + await pick(wrapper, [ZIP]) + await wrapper.vm.runDryRun() + await flushPromises() + expect(wrapper.vm.errorMessage).toBe('Confluence dry-run failed. Please try again.') + + await pick(wrapper, [ZIP]) + expect(wrapper.vm.errorMessage).toBe('') + expect(wrapper.find('.launchpad-confluence-import__error').exists()).toBe(false) + }) +}) diff --git a/src/components/admin/__tests__/DashboardBulkOperations.golden.spec.js b/src/components/admin/__tests__/DashboardBulkOperations.golden.spec.js new file mode 100644 index 000000000..c78909ca2 --- /dev/null +++ b/src/components/admin/__tests__/DashboardBulkOperations.golden.spec.js @@ -0,0 +1,227 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for DashboardBulkOperations' confirmAction: for every action, + * form input and response shape it records the API call made, the result + * summary, the error message and the selection left behind, and compares them + * with fixtures/DashboardBulkOperations.golden.json (one case per line). Set + * RECORD_GOLDEN=1 to rewrite it. + */ + +import { mount } from '@vue/test-utils' +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import DashboardBulkOperations from '../DashboardBulkOperations.vue' +import { api } from '../../../services/api.js' + +vi.mock('../../../services/api.js', () => ({ + api: { + getVisibleDashboards: vi.fn(), + bulkDeleteDashboards: vi.fn(), + bulkMoveDashboards: vi.fn(), + bulkStatusDashboards: vi.fn(), + bulkReindexDashboards: vi.fn(), + }, +})) + +const FIXTURE = path.resolve( + __dirname, + 'fixtures/DashboardBulkOperations.golden.json', +) + +const BULK_CALLS = [ + 'bulkDeleteDashboards', + 'bulkMoveDashboards', + 'bulkStatusDashboards', + 'bulkReindexDashboards', +] + +const ACTIONS = ['delete', 'move', 'status', 'reindex', 'other', 'constructor'] + +const RESPONSES = { + deleted: { data: { deletedCount: 2, skippedCount: 1 } }, + moved: { data: { movedCount: 3 } }, + updated: { data: { updatedCount: 4, errors: [{ uuid: 'b', error: 'x' }] } }, + reindexed: { data: { reindexedCount: 5, errors: 'not a list' } }, + wouldDelete: { data: { dryRun: true, wouldDeleteCount: 6, wouldSkipCount: 2 } }, + wouldMove: { data: { dryRun: true, wouldMoveCount: 7 } }, + wouldUpdate: { data: { dryRun: true, wouldUpdateCount: 8 } }, + wouldReindex: { data: { dryRun: 1, wouldReindexCount: 9 } }, + nullFirst: { + data: { + deletedCount: null, + movedCount: 0, + skippedCount: null, + wouldSkipCount: 4, + }, + }, + zeroFirst: { + data: { deletedCount: 0, movedCount: 3, skippedCount: 0, wouldSkipCount: 4 }, + }, + allCounts: { + data: { + deletedCount: 1, + movedCount: 2, + updatedCount: 3, + reindexedCount: 4, + wouldDeleteCount: 5, + wouldMoveCount: 6, + wouldUpdateCount: 7, + wouldReindexCount: 8, + }, + }, + laterCounts: { data: { wouldUpdateCount: 3, wouldReindexCount: 9 } }, + movedAndUpdated: { data: { movedCount: 2, updatedCount: 3 } }, + falsyData: { data: 0 }, + emptyData: { data: {} }, + nullData: { data: null }, + noData: {}, + undefinedResponse: undefined, + dryRunFalse: { data: { dryRun: false, updatedCount: 1 } }, +} + +const FAILURES = { + serverError: { response: { data: { error: 'Server said no' } } }, + emptyError: { response: { data: { error: '' } } }, + noResponse: new Error('network'), + nothing: undefined, +} + +const FORMS = { + plain: {}, + dryRun: { dryRun: true }, + parentEmpty: { parentUuidInput: '' }, + parentBlank: { parentUuidInput: ' ' }, + parentPadded: { parentUuidInput: ' parent-1 ' }, + parentDryRun: { parentUuidInput: 'p2', dryRun: true }, + statusDraft: { statusInput: 'draft' }, + statusScheduled: { + statusInput: 'scheduled', + publishAtInput: '2026-12-01T10:00', + }, + statusScheduledDryRun: { + statusInput: 'scheduled', + publishAtInput: '', + dryRun: true, + }, + statusPublishAtIgnored: { + statusInput: 'published', + publishAtInput: '2026-12-01T10:00', + }, +} + +/** + * Let pending promises settle. + */ +async function settle() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +/** + * Run confirmAction once and capture what it did. + * + * @param {object} spec The case: action, form fields and the API outcome. + * @return {Promise<object>} The recorded calls and component state. + */ +async function runCase(spec) { + vi.clearAllMocks() + api.getVisibleDashboards.mockResolvedValue({ + data: [{ uuid: 'a' }, { uuid: 'b' }], + }) + for (const name of BULK_CALLS) { + if (spec.failure !== undefined) { + api[name].mockRejectedValue(FAILURES[spec.failure]) + } else { + api[name].mockResolvedValue(RESPONSES[spec.response]) + } + } + const wrapper = mount(DashboardBulkOperations) + await settle() + const loadsBefore = api.getVisibleDashboards.mock.calls.length + await wrapper.setData({ + selectedUuids: ['a', 'b'], + modal: { action: spec.action, title: 'T', message: 'M' }, + ...FORMS[spec.form], + }) + const pending = wrapper.vm.confirmAction() + const runningDuring = wrapper.vm.running + await pending + await settle() + const calls = BULK_CALLS.flatMap((name) => + api[name].mock.calls.map((args) => ({ name, args })), + ) + const result = JSON.parse( + JSON.stringify({ + calls, + runningDuring, + running: wrapper.vm.running, + modal: wrapper.vm.modal, + resultSummary: wrapper.vm.resultSummary, + errorMessage: wrapper.vm.errorMessage, + selectedUuids: wrapper.vm.selectedUuids, + reloads: api.getVisibleDashboards.mock.calls.length - loadsBefore, + }), + ) + wrapper.unmount() + return result +} + +/** + * Every case the golden covers, keyed by a readable name. + * + * @return {object} Case name to case spec. + */ +function cases() { + const all = {} + for (const action of ACTIONS) { + for (const response of Object.keys(RESPONSES)) { + all[`${action} / plain / ${response}`] = { + action, + form: 'plain', + response, + } + } + for (const failure of Object.keys(FAILURES)) { + all[`${action} / plain / fails ${failure}`] = { + action, + form: 'plain', + failure, + } + } + for (const form of Object.keys(FORMS)) { + all[`${action} / ${form} / wouldMove`] = { + action, + form, + response: 'wouldMove', + } + } + } + return all +} + +describe('DashboardBulkOperations confirmAction (golden)', () => { + it('matches the recorded calls and state', async () => { + const expected = fs.existsSync(FIXTURE) + ? JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + : {} + const actual = {} + for (const [name, spec] of Object.entries(cases())) { + actual[name] = await runCase(spec) + } + if (process.env.RECORD_GOLDEN === '1') { + const lines = Object.entries(actual).map( + ([name, value]) => + `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`, + ) + fs.writeFileSync(FIXTURE, `{\n${lines.join(',\n')}\n}\n`) + return + } + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const name of Object.keys(expected)) { + expect(actual[name], name).toEqual(expected[name]) + } + }) +}) diff --git a/src/components/admin/__tests__/DashboardBulkOperations.interaction.spec.js b/src/components/admin/__tests__/DashboardBulkOperations.interaction.spec.js new file mode 100644 index 000000000..5a7479bc5 --- /dev/null +++ b/src/components/admin/__tests__/DashboardBulkOperations.interaction.spec.js @@ -0,0 +1,243 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the DashboardBulkOperations UI around confirmAction + * (which the golden spec covers): loading the list, row and select-all + * selection, the confirm modal per action, cancelling, and the result and + * error panels. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import DashboardBulkOperations from '../DashboardBulkOperations.vue' +import { api } from '../../../services/api.js' + +vi.mock('../../../services/api.js', () => ({ + api: { + getVisibleDashboards: vi.fn(), + bulkDeleteDashboards: vi.fn(), + bulkMoveDashboards: vi.fn(), + bulkStatusDashboards: vi.fn(), + bulkReindexDashboards: vi.fn(), + }, +})) + +const DASHBOARDS = [ + { uuid: 'a', name: 'Alpha', publicationStatus: 'draft' }, + { uuid: 'b', name: 'Beta' }, +] + +/** + * Let pending promises settle. + */ +async function settle() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +/** + * Mount the widget and wait for the dashboard list. + * + * @return {Promise<object>} The wrapper. + */ +async function mountWidget() { + const wrapper = mount(DashboardBulkOperations) + await settle() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() + api.getVisibleDashboards.mockResolvedValue({ data: DASHBOARDS }) +}) + +describe('DashboardBulkOperations interaction', () => { + it('lists the dashboards with their status, defaulting to published', async () => { + const wrapper = await mountWidget() + + const rows = wrapper.findAll('[data-test="bulk-ops-table"] tbody tr') + expect(rows).toHaveLength(2) + expect(rows[0].text()).toContain('Alpha') + expect(rows[0].text()).toContain('draft') + expect(rows[1].text()).toContain('published') + }) + + it('reads the { items, quota } envelope /api/dashboards/visible answers, and an envelope without items', async () => { + api.getVisibleDashboards.mockResolvedValueOnce({ + data: { items: [{ uuid: 'z', name: 'Zed' }], quota: { maxDashboards: 0 } }, + }) + const wrapper = await mountWidget() + expect(wrapper.vm.dashboards).toEqual([{ uuid: 'z', name: 'Zed' }]) + + api.getVisibleDashboards.mockResolvedValueOnce({ data: {} }) + await wrapper.vm.loadDashboards() + expect(wrapper.vm.dashboards).toEqual([]) + }) + + it('shows an error when the dashboards cannot be loaded', async () => { + api.getVisibleDashboards.mockRejectedValueOnce(new Error('down')) + const wrapper = await mountWidget() + + expect(wrapper.vm.loading).toBe(false) + expect(wrapper.find('[data-test="bulk-ops-error"]').text()).toBe( + 'Failed to load dashboards', + ) + }) + + it('toggles single rows on and off and enables the action select', async () => { + const wrapper = await mountWidget() + const select = wrapper.find('[data-test="bulk-ops-action-select"]') + expect(select.attributes('disabled')).toBeDefined() + + const boxes = wrapper.findAll('[data-test="bulk-ops-row-select"]') + await boxes[1].trigger('change') + expect(wrapper.vm.selectedUuids).toEqual(['b']) + expect(wrapper.vm.someSelected).toBe(true) + expect(wrapper.vm.allSelected).toBe(false) + expect(select.attributes('disabled')).toBeUndefined() + + await boxes[0].trigger('change') + expect(wrapper.vm.selectedUuids).toEqual(['b', 'a']) + expect(wrapper.vm.allSelected).toBe(true) + + await boxes[1].trigger('change') + expect(wrapper.vm.selectedUuids).toEqual(['a']) + }) + + it('select-all selects every row and clears them again', async () => { + const wrapper = await mountWidget() + const all = wrapper.find('[data-test="bulk-ops-select-all"]') + + await all.setValue(true) + expect(wrapper.vm.selectedUuids).toEqual(['a', 'b']) + + await all.setValue(false) + expect(wrapper.vm.selectedUuids).toEqual([]) + }) + + it('allSelected is false while there are no dashboards', async () => { + api.getVisibleDashboards.mockResolvedValueOnce({ data: [] }) + const wrapper = await mountWidget() + + expect(wrapper.vm.allSelected).toBe(false) + }) + + it('Apply stays disabled until an action is chosen', async () => { + const wrapper = await mountWidget() + const run = wrapper.find('[data-test="bulk-ops-run"]') + + await wrapper.setData({ selectedUuids: ['a'] }) + expect(run.attributes('disabled')).toBeDefined() + + await wrapper.find('[data-test="bulk-ops-action-select"]').setValue('reindex') + expect(run.attributes('disabled')).toBeUndefined() + }) + + it.each([ + ['delete', 'Delete dashboards?', 'About to delete {n} dashboards. This cannot be undone.'], + ['move', 'Move dashboards?', 'About to re-parent {n} dashboards.'], + ['status', 'Set publication status?', 'About to update the publication status of {n} dashboards.'], + ['reindex', 'Reindex dashboards for search?', 'About to reindex {n} dashboards for unified search.'], + ])('Apply opens the %s confirmation and clears earlier results', async (action, title, message) => { + const wrapper = await mountWidget() + await wrapper.setData({ + selectedUuids: ['a', 'b'], + selectedAction: action, + errorMessage: 'old', + resultSummary: { dryRun: true, changed: 1, skipped: 0, errors: [] }, + }) + + await wrapper.find('[data-test="bulk-ops-run"]').trigger('click') + + expect(wrapper.vm.modal).toEqual({ action, title, message }) + expect(wrapper.vm.errorMessage).toBe('') + expect(wrapper.vm.resultSummary).toBeNull() + const modal = wrapper.find('[data-test="bulk-ops-modal"]') + expect(modal.find('h4').text()).toBe(title) + expect(modal.find('[data-test="bulk-ops-parent-uuid"]').exists()).toBe(action === 'move') + expect(modal.find('[data-test="bulk-ops-status-select"]').exists()).toBe(action === 'status') + }) + + it('shows the publish date field only for a scheduled status', async () => { + const wrapper = await mountWidget() + await wrapper.setData({ + selectedUuids: ['a'], + modal: { action: 'status', title: 'T', message: 'M' }, + }) + expect(wrapper.find('[data-test="bulk-ops-publish-at"]').exists()).toBe(false) + + await wrapper.find('[data-test="bulk-ops-status-select"]').setValue('scheduled') + + expect(wrapper.find('[data-test="bulk-ops-publish-at"]').exists()).toBe(true) + }) + + it('Cancel closes the modal without calling the API', async () => { + const wrapper = await mountWidget() + await wrapper.setData({ + selectedUuids: ['a'], + modal: { action: 'delete', title: 'T', message: 'M' }, + }) + + const cancel = wrapper + .findAll('[data-test="bulk-ops-modal"] button') + .find((b) => b.text() === 'Cancel') + await cancel.trigger('click') + + expect(wrapper.vm.modal).toBeNull() + expect(wrapper.find('[data-test="bulk-ops-modal"]').exists()).toBe(false) + expect(api.bulkDeleteDashboards).not.toHaveBeenCalled() + }) + + it('OK runs a dry-run move and shows the preview count', async () => { + api.bulkMoveDashboards.mockResolvedValue({ + data: { dryRun: true, wouldMoveCount: 2 }, + }) + const wrapper = await mountWidget() + await wrapper.setData({ + selectedUuids: ['a', 'b'], + modal: { action: 'move', title: 'T', message: 'M' }, + }) + await wrapper.find('[data-test="bulk-ops-parent-uuid"]').setValue(' parent-1 ') + await wrapper.find('[data-test="bulk-ops-dryrun"]').setValue(true) + + await wrapper.find('[data-test="bulk-ops-confirm"]').trigger('click') + await settle() + + expect(api.bulkMoveDashboards).toHaveBeenCalledWith(['a', 'b'], 'parent-1', { + dryRun: true, + }) + const result = wrapper.find('[data-test="bulk-ops-result"]') + expect(result.text()).toBe('PREVIEW: would change {count} dashboards.') + expect(wrapper.vm.selectedUuids).toEqual(['a', 'b']) + }) + + it('lists per-dashboard errors of a real run', async () => { + api.bulkDeleteDashboards.mockResolvedValue({ + data: { + deletedCount: 1, + skippedCount: 1, + errors: [{ uuid: 'b', reason: 'locked' }], + }, + }) + const wrapper = await mountWidget() + await wrapper.setData({ + selectedUuids: ['a', 'b'], + modal: { action: 'delete', title: 'T', message: 'M' }, + }) + + await wrapper.find('[data-test="bulk-ops-confirm"]').trigger('click') + await settle() + + const result = wrapper.find('[data-test="bulk-ops-result"]') + expect(result.find('p').text()).toBe('Changed {count} dashboards. Skipped {skipped}.') + expect(result.findAll('li').map((li) => li.text())).toEqual(['b: locked']) + expect(wrapper.vm.resultSummary).toEqual({ + dryRun: false, + changed: 1, + skipped: 1, + errors: [{ uuid: 'b', reason: 'locked' }], + }) + expect(wrapper.vm.selectedUuids).toEqual([]) + }) +}) diff --git a/src/components/admin/__tests__/DashboardRegistrySettings.spec.js b/src/components/admin/__tests__/DashboardRegistrySettings.spec.js index 94443c46a..69090c537 100644 --- a/src/components/admin/__tests__/DashboardRegistrySettings.spec.js +++ b/src/components/admin/__tests__/DashboardRegistrySettings.spec.js @@ -111,6 +111,18 @@ describe('DashboardRegistrySettings', () => { ) }) + // @spec openspec/changes/store-page-board-sync/specs/dashboard-store/spec.md#requirement-req-store-010-the-marketplace-shows-dashboard-templates-as-cards + it('fills and saves the register name the marketplace banner shows', async () => { + const wrapper = await mountWith({ ...STORED, registryName: 'VNG dashboardregister' }) + + expect(wrapper.find('[data-test="registry-name"]').element.value).toBe('VNG dashboardregister') + await wrapper.find('[data-test="registry-name"]').setValue(' Other register ') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(api.updateStoreConfig.mock.calls[0][0].registryName).toBe('Other register') + }) + it('leaves the stored token alone when the field is empty on save', async () => { const wrapper = await mountWith(STORED) diff --git a/src/components/admin/__tests__/DashboardSharingPolicy.spec.js b/src/components/admin/__tests__/DashboardSharingPolicy.spec.js new file mode 100644 index 000000000..cd814f997 --- /dev/null +++ b/src/components/admin/__tests__/DashboardSharingPolicy.spec.js @@ -0,0 +1,116 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest tests for `DashboardSharingPolicy.vue`: "Sharing allowed for" + * Everyone, Only these groups or Nobody, and the public-link switch + * (dashboard-sharing REQ-SHARE-015, board LpBeheerDelen). + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const getAdminSettings = vi.fn() +const updateAdminSettings = vi.fn() +const updateSharingPolicy = vi.fn() +vi.mock('../../../services/api.js', () => ({ + api: { + getAdminSettings: (...args) => getAdminSettings(...args), + updateAdminSettings: (...args) => updateAdminSettings(...args), + updateSharingPolicy: (...args) => updateSharingPolicy(...args), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) + +const stubs = { + NcSelect: { template: '<div class="nc-select" />' }, + NcSelectTags: { template: '<div class="nc-select-tags" :data-test="$attrs[\'data-test\']" />' }, + NcCheckboxRadioSwitch: { + props: ['modelValue', 'value', 'type'], + emits: ['update:modelValue'], + template: + '<label :data-test="$attrs[\'data-test\']" :data-checked="String(type === \'radio\' ? modelValue === value : modelValue)" @click="$emit(\'update:modelValue\', type === \'radio\' ? value : !modelValue)"><slot /></label>', + }, +} + +let DashboardSharingPolicy + +beforeEach(async () => { + getAdminSettings.mockReset() + updateAdminSettings.mockReset() + updateAdminSettings.mockResolvedValue({}) + updateSharingPolicy.mockReset() + updateSharingPolicy.mockResolvedValue({}) + DashboardSharingPolicy = (await import('../DashboardSharingPolicy.vue')).default +}) + +async function mountPolicy(settings) { + getAdminSettings.mockResolvedValue({ data: settings }) + const wrapper = mount(DashboardSharingPolicy, { + props: { groups: ['sales', 'communicatie'] }, + global: { stubs }, + }) + await flushPromises() + return wrapper +} + +describe('DashboardSharingPolicy (REQ-SHARE-015)', () => { + it('offers Everyone, Only these groups and Nobody, with the stored choice selected', async () => { + const wrapper = await mountPolicy({ sharingAllowed: 'none', publicLinksAllowed: true }) + + expect(wrapper.find('[data-test="sharing-policy-allowed"]').text()).toContain('Sharing allowed for') + expect(wrapper.find('[data-test="sharing-policy-allowed-choice-everyone"]').attributes('data-checked')).toBe('false') + expect(wrapper.find('[data-test="sharing-policy-allowed-choice-groups"]').exists()).toBe(true) + expect(wrapper.find('[data-test="sharing-policy-allowed-choice-none"]').attributes('data-checked')).toBe('true') + expect(wrapper.find('[data-test="sharing-policy-nobody-hint"]').exists()).toBe(true) + expect(wrapper.find('[data-test="sharing-policy-allowed-choice-groups"]').text()).toBe('Only these groups') + }) + + it('reads an older server without the choice from the group list', async () => { + const withGroups = await mountPolicy({ sharingAllowedGroups: ['sales'] }) + expect(withGroups.vm.sharingAllowed).toBe('groups') + expect(withGroups.find('.nc-select-tags[data-test="sharing-policy-allowed-groups"]').exists()).toBe(true) + + const without = await mountPolicy({}) + expect(without.vm.sharingAllowed).toBe('everyone') + expect(without.vm.publicLinksAllowed).toBe(true) + }) + + it('saves Nobody, keeps the stored groups and hides the group picker', async () => { + const wrapper = await mountPolicy({ sharingAllowed: 'groups', sharingAllowedGroups: ['sales'] }) + + await wrapper.find('[data-test="sharing-policy-allowed-choice-none"]').trigger('click') + await flushPromises() + + expect(updateSharingPolicy).toHaveBeenCalledWith({ sharingAllowed: 'none' }) + expect(updateAdminSettings).not.toHaveBeenCalled() + expect(wrapper.find('.nc-select-tags[data-test="sharing-policy-allowed-groups"]').exists()).toBe(false) + }) + + it('switches public links off and says a link always expires', async () => { + const wrapper = await mountPolicy({ publicLinksAllowed: true }) + const field = wrapper.find('[data-test="sharing-policy-public-links"]') + expect(field.text()).toBe('Allow public links') + expect(wrapper.text()).toContain('A link always has an expiry date.') + + await field.trigger('click') + await flushPromises() + + expect(updateSharingPolicy).toHaveBeenCalledWith({ publicLinksAllowed: false }) + expect(wrapper.vm.publicLinksAllowed).toBe(false) + }) + + it('choosing Everyone clears the group list, the setting that lets everyone share', async () => { + const wrapper = await mountPolicy({ sharingAllowed: 'groups', sharingAllowedGroups: ['sales'] }) + + await wrapper.find('[data-test="sharing-policy-allowed-choice-everyone"]').trigger('click') + await flushPromises() + + expect(updateSharingPolicy).toHaveBeenCalledWith({ sharingAllowed: 'everyone' }) + expect(updateAdminSettings).toHaveBeenCalledWith(expect.objectContaining({ sharingAllowedGroups: [] })) + expect(wrapper.vm.allowedGroups).toEqual([]) + }) +}) diff --git a/src/components/admin/__tests__/EmbedTelemetryToggle.spec.js b/src/components/admin/__tests__/EmbedTelemetryToggle.spec.js new file mode 100644 index 000000000..354433d2b --- /dev/null +++ b/src/components/admin/__tests__/EmbedTelemetryToggle.spec.js @@ -0,0 +1,78 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The embed telemetry switch shows the stored state, saves a change through + * the admin API and rolls back when saving fails (embedded-analytics task 30). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-30 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import EmbedTelemetryToggle from '../EmbedTelemetryToggle.vue' +import { logger } from '../../../utils/logger.js' + +const http = vi.hoisted(() => ({ get: vi.fn(), put: vi.fn() })) +vi.mock('@nextcloud/axios', () => ({ default: http })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const SwitchStub = { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'disabled'], + emits: ['update:modelValue'], + template: '<label class="switch-stub"><slot /></label>', +} + +const mountToggle = () => mount(EmbedTelemetryToggle, { global: { stubs: { NcCheckboxRadioSwitch: SwitchStub } } }) + +describe('EmbedTelemetryToggle', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it.each([ + [{ enabled: false }, false], + [{ enabled: true }, true], + [{}, true], + ])('shows the stored setting %#', async (answer, enabled) => { + http.get.mockResolvedValue({ data: answer }) + const wrapper = mountToggle() + expect(wrapper.findComponent(SwitchStub).props('disabled')).toBe(true) + await flushPromises() + + expect(http.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/embed-settings/telemetry') + expect(wrapper.findComponent(SwitchStub).props()).toEqual({ modelValue: enabled, disabled: false }) + expect(wrapper.text()).toContain('Collect embed usage telemetry') + }) + + it('saves a change and takes the state the server stored', async () => { + http.get.mockResolvedValue({ data: { enabled: true } }) + http.put.mockResolvedValue({ data: { enabled: false } }) + const wrapper = mountToggle() + await flushPromises() + + wrapper.findComponent(SwitchStub).vm.$emit('update:modelValue', false) + await flushPromises() + + expect(http.put).toHaveBeenCalledWith('/index.php/apps/launchpad/api/embed-settings/telemetry', { enabled: false }) + expect(wrapper.findComponent(SwitchStub).props('modelValue')).toBe(false) + }) + + it('rolls back and logs when saving or loading fails', async () => { + http.get.mockRejectedValue(new Error('down')) + const wrapper = mountToggle() + await flushPromises() + expect(wrapper.vm.enabled).toBe(true) + expect(logger.error).toHaveBeenCalledWith('Failed to load embed telemetry setting:', expect.any(Error)) + + http.put.mockRejectedValue(new Error('forbidden')) + wrapper.findComponent(SwitchStub).vm.$emit('update:modelValue', false) + await flushPromises() + + expect(wrapper.vm.enabled).toBe(true) + expect(logger.error).toHaveBeenCalledWith('Failed to save embed telemetry setting:', expect.any(Error)) + }) +}) diff --git a/src/components/admin/__tests__/GroupDashboardsTab.modals.spec.js b/src/components/admin/__tests__/GroupDashboardsTab.modals.spec.js new file mode 100644 index 000000000..e0ea23ee3 --- /dev/null +++ b/src/components/admin/__tests__/GroupDashboardsTab.modals.spec.js @@ -0,0 +1,154 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * GroupDashboardsTab (admin-group-management): what the tab does when its + * modals report back, the empty state, and a group whose dashboard count + * cannot be loaded. The row actions themselves are in + * GroupDashboardsTab.spec.js. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import GroupDashboardsTab from '../tabs/GroupDashboardsTab.vue' +import { api } from '../../../services/api.js' +import { useGroupDashboardsStore } from '../../../stores/groupDashboards.js' + +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn() })) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, source) => source, +})) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => `/index.php${path}`, +})) +vi.mock('../../../services/api.js', () => ({ + api: { + getAdminGroups: vi.fn(), + listGroupDashboards: vi.fn(), + }, +})) + +const stubs = { + NcButton: { + emits: ['click'], + template: '<button @click="$emit(\'click\')"><slot /></button>', + }, + NcEmptyContent: { + props: ['name'], + template: '<div class="nc-empty-content">{{ name }}<slot name="icon" /></div>', + }, + NcLoadingIcon: { template: '<span />' }, + AccountMultipleIcon: { template: '<span class="icon-account-multiple" />' }, + CreateGroupDashboardModal: { + name: 'CreateGroupDashboardModal', + props: ['group'], + emits: ['close', 'created'], + template: '<div data-test="create-modal" />', + }, + ManageGroupDashboardsModal: { + name: 'ManageGroupDashboardsModal', + props: ['group'], + emits: ['close'], + template: '<div data-test="manage-modal" />', + }, +} + +const DASHBOARDS = { + default: [{ uuid: 'd1' }], + staff: [{ uuid: 's1' }, { uuid: 's2' }], +} + +async function mountTab() { + const wrapper = mount(GroupDashboardsTab, { global: { stubs, mocks: { t: (_a, s) => s } } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + api.getAdminGroups.mockResolvedValue({ data: { allKnown: [{ id: 'staff', displayName: 'Staff' }] } }) + api.listGroupDashboards.mockImplementation(async (groupId) => ({ data: DASHBOARDS[groupId] ?? [] })) +}) + +describe('GroupDashboardsTab modals', () => { + it('refreshes the group count after a create and closes the modal', async () => { + const wrapper = await mountTab() + expect(wrapper.find('[data-test="group-dashboards-count-staff"]').text()).toBe('2') + + await wrapper.find('[data-test="group-dashboards-create-staff"]').trigger('click') + const modal = wrapper.findComponent({ name: 'CreateGroupDashboardModal' }) + expect(modal.props('group')).toEqual({ id: 'staff', displayName: 'Staff' }) + + DASHBOARDS.staff = [{ uuid: 's1' }, { uuid: 's2' }, { uuid: 's3' }] + modal.vm.$emit('created') + await flushPromises() + + expect(api.listGroupDashboards).toHaveBeenLastCalledWith('staff') + expect(wrapper.find('[data-test="group-dashboards-count-staff"]').text()).toBe('3') + expect(wrapper.find('[data-test="create-modal"]').exists()).toBe(false) + DASHBOARDS.staff = [{ uuid: 's1' }, { uuid: 's2' }] + }) + + it('closes the create modal without refreshing', async () => { + const wrapper = await mountTab() + await wrapper.find('[data-test="group-dashboards-create-staff"]').trigger('click') + const calls = api.listGroupDashboards.mock.calls.length + + wrapper.findComponent({ name: 'CreateGroupDashboardModal' }).vm.$emit('close') + await flushPromises() + + expect(wrapper.find('[data-test="create-modal"]').exists()).toBe(false) + expect(api.listGroupDashboards.mock.calls.length).toBe(calls) + }) + + it('closes the manage modal', async () => { + const wrapper = await mountTab() + await wrapper.find('[data-test="group-dashboards-manage-default"]').trigger('click') + expect(wrapper.findComponent({ name: 'ManageGroupDashboardsModal' }).props('group').id).toBe('default') + + wrapper.findComponent({ name: 'ManageGroupDashboardsModal' }).vm.$emit('close') + await flushPromises() + + expect(wrapper.find('[data-test="manage-modal"]').exists()).toBe(false) + }) + + it('a create report without an open modal refreshes nothing', async () => { + const wrapper = await mountTab() + const calls = api.listGroupDashboards.mock.calls.length + + await wrapper.vm.onCreated() + + expect(api.listGroupDashboards.mock.calls.length).toBe(calls) + }) +}) + +describe('GroupDashboardsTab states', () => { + it('still lists every group when one count cannot be loaded', async () => { + api.listGroupDashboards.mockImplementation(async (groupId) => { + if (groupId === 'staff') { + throw new Error('500') + } + return { data: DASHBOARDS[groupId] } + }) + const wrapper = await mountTab() + + expect(wrapper.find('[data-test="group-dashboards-count-default"]').text()).toBe('1') + expect(wrapper.find('[data-test="group-dashboards-count-staff"]').text()).toBe('0') + }) + + it('shows the empty state when there are no groups', async () => { + const wrapper = await mountTab() + + useGroupDashboardsStore().groups = [] + await flushPromises() + + const empty = wrapper.find('.nc-empty-content') + expect(empty.text()).toContain('No groups configured') + expect(empty.find('.icon-account-multiple').exists()).toBe(true) + expect(wrapper.find('[data-test="group-dashboards-list"]').exists()).toBe(false) + }) +}) diff --git a/src/components/admin/__tests__/GroupPriorityOrder.dragdrop.spec.js b/src/components/admin/__tests__/GroupPriorityOrder.dragdrop.spec.js new file mode 100644 index 000000000..46f83181d --- /dev/null +++ b/src/components/admin/__tests__/GroupPriorityOrder.dragdrop.spec.js @@ -0,0 +1,271 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the drag-and-drop and save paths of + * `GroupPriorityOrder.vue` not covered by GroupPriorityOrder.spec.js: + * reordering within the active column, dropping between columns at an + * index or at the end, the debounced save, and load / save failures. + */ + +import { showError, showSuccess } from '@nextcloud/dialogs' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import GroupPriorityOrder from '../GroupPriorityOrder.vue' +import { api } from '../../../services/api.js' +import { logger } from '../../../utils/logger.js' + +vi.mock('../../../services/api.js', () => ({ + api: { getAdminGroups: vi.fn(), updateAdminGroupOrder: vi.fn() }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) + +const GROUPS = { + active: ['a', 'b', 'c'], + inactive: ['x', 'z'], + allKnown: [ + { id: 'a', displayName: 'Alpha' }, + { id: 'b', displayName: 'Beta' }, + { id: 'c', displayName: 'Gamma' }, + { id: 'x', displayName: 'Xray' }, + { id: 'z', displayName: 'Zulu' }, + { id: 'm', displayName: 'Mike' }, + ], +} + +async function mountOrder(payload = GROUPS) { + api.getAdminGroups.mockResolvedValue({ data: payload }) + const wrapper = mount(GroupPriorityOrder, { + global: { stubs: { NcButton: true, NcTextField: true } }, + }) + await flushPromises() + return wrapper +} + +/** + * Drag one id from a column position. + * + * @param {object} vm the component. + * @param {string} id the dragged id. + * @param {string} column 'active' or 'inactive'. + * @param {number} index its position. + * @return {object} the fake drag event. + */ +function drag(vm, id, column, index) { + const event = { dataTransfer: { setData: vi.fn(), effectAllowed: '', dropEffect: '' } } + vm.onDragStart(event, id, column, index) + return event +} + +beforeEach(() => { + vi.clearAllMocks() + vi.useFakeTimers() + globalThis.t = (_app, key) => key + api.updateAdminGroupOrder.mockResolvedValue({}) +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('GroupPriorityOrder drag and drop', () => { + it('marks the drag as a move carrying the id', async () => { + const wrapper = await mountOrder() + const event = drag(wrapper.vm, 'a', 'active', 0) + + expect(event.dataTransfer.effectAllowed).toBe('move') + expect(event.dataTransfer.setData).toHaveBeenCalledWith('text/plain', 'a') + expect(wrapper.vm.dragState).toEqual({ id: 'a', fromColumn: 'active', fromIndex: 0 }) + + const over = { dataTransfer: {} } + wrapper.vm.onDragOver(over, 'active') + expect(over.dataTransfer.dropEffect).toBe('move') + const itemOver = { dataTransfer: {} } + wrapper.vm.onItemDragOver(itemOver, 1, 'active') + expect(itemOver.dataTransfer.dropEffect).toBe('move') + wrapper.vm.onDragOver({}, 'active') + wrapper.vm.onItemDragOver({}, 0, 'active') + wrapper.vm.onDragStart({}, 'b', 'active', 1) + expect(wrapper.vm.dragState.id).toBe('b') + }) + + it.each([ + [0, 2, ['b', 'a', 'c']], + [0, 3, ['b', 'c', 'a']], + [2, 0, ['c', 'a', 'b']], + ])('moves active index %s onto item %s', async (from, to, order) => { + const wrapper = await mountOrder() + drag(wrapper.vm, GROUPS.active[from], 'active', from) + + wrapper.vm.onItemDrop({}, to, 'active') + + expect(wrapper.vm.active).toEqual(order) + expect(wrapper.vm.dragState).toBeNull() + }) + + it('ignores a drop onto itself or without a drag', async () => { + const wrapper = await mountOrder() + wrapper.vm.onItemDrop({}, 1, 'active') + wrapper.vm.onDrop({}, 'active') + + drag(wrapper.vm, 'b', 'active', 1) + wrapper.vm.onItemDrop({}, 1, 'active') + + expect(wrapper.vm.active).toEqual(['a', 'b', 'c']) + vi.runAllTimers() + expect(api.updateAdminGroupOrder).not.toHaveBeenCalled() + }) + + it('inserts an inactive group at the dropped position', async () => { + const wrapper = await mountOrder() + drag(wrapper.vm, 'z', 'inactive', 1) + + wrapper.vm.onItemDrop({}, 1, 'active') + + expect(wrapper.vm.active).toEqual(['a', 'z', 'b', 'c']) + expect(wrapper.vm.inactive).toEqual(['x']) + }) + + it.each([[-1], [3], [null]])('appends at the end for drop index %s', async (index) => { + const wrapper = await mountOrder() + wrapper.vm.moveBetweenColumns('x', 'inactive', 'active', index) + expect(wrapper.vm.active).toEqual(['a', 'b', 'c', 'x']) + }) + + it('drops on the inactive column sorted by display name', async () => { + const wrapper = await mountOrder({ ...GROUPS, inactive: ['x', 'z', 'q'] }) + drag(wrapper.vm, 'b', 'active', 1) + wrapper.vm.onDrop({}, 'inactive') + + expect(wrapper.vm.active).toEqual(['a', 'c']) + expect(wrapper.vm.inactive).toEqual(['b', 'q', 'x', 'z']) + }) + + it('drops on the active column at the end, and ignores reordering inside inactive', async () => { + const wrapper = await mountOrder() + drag(wrapper.vm, 'x', 'inactive', 0) + wrapper.vm.onDrop({}, 'active') + expect(wrapper.vm.active).toEqual(['a', 'b', 'c', 'x']) + + drag(wrapper.vm, 'z', 'inactive', 0) + wrapper.vm.onDrop({}, 'inactive') + expect(wrapper.vm.inactive).toEqual(['z']) + + wrapper.vm.moveBetweenColumns('a', 'active', 'active', 0) + expect(wrapper.vm.active).toEqual(['a', 'b', 'c', 'x']) + }) +}) + +describe('GroupPriorityOrder rendered columns', () => { + const ButtonStub = { emits: ['click'], template: '<button class="move-stub" @click="$emit(\'click\')"><slot /></button>' } + const FieldStub = { + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<input class="filter-stub" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + } + + async function mountRendered() { + api.getAdminGroups.mockResolvedValue({ data: GROUPS }) + const wrapper = mount(GroupPriorityOrder, { global: { stubs: { NcButton: ButtonStub, NcTextField: FieldStub } } }) + await flushPromises() + return wrapper + } + + const items = (wrapper, column) => wrapper.findAll(`.group-priority__list--${column} .group-priority__item`) + const labels = (wrapper, column) => items(wrapper, column).map((li) => li.find('.group-priority__label').text()) + + it('reorders the active column by dragging one item onto another', async () => { + const wrapper = await mountRendered() + const dataTransfer = { setData: vi.fn(), effectAllowed: '', dropEffect: '' } + + await items(wrapper, 'active')[2].trigger('dragstart', { dataTransfer }) + await items(wrapper, 'active')[0].trigger('dragover', { dataTransfer }) + await items(wrapper, 'active')[0].trigger('drop', { dataTransfer }) + + expect(labels(wrapper, 'active')).toEqual(['Gamma', 'Alpha', 'Beta']) + }) + + it('moves groups between columns by drag onto a column or with the buttons', async () => { + const wrapper = await mountRendered() + const dataTransfer = { setData: vi.fn() } + const list = (column) => wrapper.find(`.group-priority__list--${column}`) + + await items(wrapper, 'inactive')[0].trigger('dragstart', { dataTransfer }) + await list('active').trigger('dragover', { dataTransfer }) + await list('active').trigger('drop', { dataTransfer }) + expect(labels(wrapper, 'active')).toEqual(['Alpha', 'Beta', 'Gamma', 'Xray']) + + await items(wrapper, 'active')[0].trigger('dragstart', { dataTransfer }) + await list('inactive').trigger('dragover', { dataTransfer }) + await list('inactive').trigger('drop', { dataTransfer }) + expect(wrapper.vm.inactive).toEqual(['a', 'z']) + + await items(wrapper, 'inactive')[1].find('.move-stub').trigger('click') + await items(wrapper, 'active')[0].find('.move-stub').trigger('click') + expect(wrapper.vm.active).toEqual(['c', 'x', 'z']) + }) + + it('filters each column from its search field', async () => { + const wrapper = await mountRendered() + const [activeFilter, inactiveFilter] = wrapper.findAll('.filter-stub') + + await activeFilter.setValue('GAM') + await inactiveFilter.setValue('zu') + + expect(labels(wrapper, 'active')).toEqual(['Gamma']) + expect(items(wrapper, 'inactive').map((li) => li.text())).toEqual([expect.stringContaining('Zulu')]) + }) +}) + +describe('GroupPriorityOrder saving', () => { + it('saves once, 300 ms after the last change', async () => { + const wrapper = await mountOrder() + wrapper.vm.moveToActive('x') + vi.advanceTimersByTime(200) + wrapper.vm.moveToInactive('a') + vi.advanceTimersByTime(299) + expect(api.updateAdminGroupOrder).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + await flushPromises() + + expect(api.updateAdminGroupOrder).toHaveBeenCalledTimes(1) + expect(api.updateAdminGroupOrder).toHaveBeenCalledWith(['b', 'c', 'x']) + expect(showSuccess).toHaveBeenCalledWith('Group order saved.') + expect(wrapper.vm.saving).toBe(false) + }) + + it('reports a failed save', async () => { + api.updateAdminGroupOrder.mockRejectedValue(new Error('x')) + const wrapper = await mountOrder() + + await wrapper.vm.persist() + + expect(showError).toHaveBeenCalledWith('Failed to save group order.') + expect(logger.error).toHaveBeenCalledWith('Failed to save group order:', expect.any(Error)) + expect(wrapper.vm.saving).toBe(false) + }) + + it('drops a pending save on unmount', async () => { + const wrapper = await mountOrder() + wrapper.vm.moveToActive('x') + wrapper.unmount() + vi.runAllTimers() + expect(api.updateAdminGroupOrder).not.toHaveBeenCalled() + }) + + it('reports a failed load and treats missing lists as empty', async () => { + api.getAdminGroups.mockRejectedValueOnce(new Error('x')) + const failed = mount(GroupPriorityOrder, { props: { initialActive: ['seed'] }, global: { stubs: { NcButton: true, NcTextField: true } } }) + await flushPromises() + expect(showError).toHaveBeenCalledWith('Failed to load group list.') + expect(failed.vm.active).toEqual(['seed']) + expect(failed.vm.loading).toBe(false) + + const empty = await mountOrder({ active: 'a' }) + expect([empty.vm.active, empty.vm.inactive, empty.vm.allKnown]).toEqual([[], [], []]) + expect(empty.vm.displayName('ghost')).toBe('ghost') + expect(empty.vm.isStale('ghost')).toBe(true) + }) +}) diff --git a/src/components/admin/__tests__/ImageHostSettings.spec.js b/src/components/admin/__tests__/ImageHostSettings.spec.js new file mode 100644 index 000000000..1e78af07c --- /dev/null +++ b/src/components/admin/__tests__/ImageHostSettings.spec.js @@ -0,0 +1,96 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The external image host allow-list section shows the stored hosts one per + * line, saves the lines through the admin API, and shows the server's + * refusal under the list (REQ-IMG-006). + * + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ImageHostSettings from '../ImageHostSettings.vue' + +const http = vi.hoisted(() => ({ get: vi.fn(), put: vi.fn() })) +const dialogs = vi.hoisted(() => ({ showSuccess: vi.fn(), showError: vi.fn() })) +vi.mock('@nextcloud/axios', () => ({ default: http })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key, n: (_app, one) => one })) +vi.mock('@nextcloud/dialogs', () => dialogs) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const TextAreaStub = { + name: 'NcTextArea', + props: ['modelValue', 'label', 'disabled'], + emits: ['update:modelValue'], + template: '<textarea class="textarea-stub" :value="modelValue" />', +} +const ButtonStub = { + name: 'NcButton', + props: ['disabled'], + emits: ['click'], + template: '<button class="button-stub" @click="$emit(\'click\')"><slot /></button>', +} + +const URL = '/index.php/apps/launchpad/api/admin/image-hosts' + +/** + * Mount the section with stubbed Nextcloud components. + * + * @return {object} The wrapper. + */ +function mountSettings() { + return mount(ImageHostSettings, { + global: { stubs: { NcTextArea: TextAreaStub, NcButton: ButtonStub } }, + }) +} + +describe('ImageHostSettings', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('shows the stored hosts one per line', async () => { + http.get.mockResolvedValue({ data: { hosts: ['example.com', 'cdn.example.org'] } }) + const wrapper = mountSettings() + await flushPromises() + + expect(http.get).toHaveBeenCalledWith(URL) + expect(wrapper.findComponent(TextAreaStub).props('modelValue')).toBe('example.com\ncdn.example.org') + expect(wrapper.findComponent(TextAreaStub).props('disabled')).toBe(false) + }) + + it('saves the non-blank lines and shows what the server stored', async () => { + http.get.mockResolvedValue({ data: { hosts: [] } }) + http.put.mockResolvedValue({ data: { hosts: ['example.com', 'cdn.example.org'] } }) + const wrapper = mountSettings() + await flushPromises() + + wrapper.findComponent(TextAreaStub).vm.$emit('update:modelValue', ' Example.com \n\ncdn.example.org\n') + await wrapper.find('.button-stub').trigger('click') + await flushPromises() + + expect(http.put).toHaveBeenCalledWith(URL, { hosts: ['Example.com', 'cdn.example.org'] }) + expect(wrapper.findComponent(TextAreaStub).props('modelValue')).toBe('example.com\ncdn.example.org') + expect(dialogs.showSuccess).toHaveBeenCalled() + expect(wrapper.find('[data-test="image-host-error"]').exists()).toBe(false) + }) + + it('shows the server refusal under the list and keeps what was typed', async () => { + http.get.mockResolvedValue({ data: { hosts: [] } }) + http.put.mockRejectedValue({ response: { status: 400, data: { message: '"https://example.com" is not a host name.' } } }) + const wrapper = mountSettings() + await flushPromises() + + wrapper.findComponent(TextAreaStub).vm.$emit('update:modelValue', 'https://example.com') + await wrapper.find('.button-stub').trigger('click') + await flushPromises() + + const error = wrapper.find('[data-test="image-host-error"]') + expect(error.attributes('role')).toBe('alert') + expect(error.text()).toBe('"https://example.com" is not a host name.') + expect(wrapper.findComponent(TextAreaStub).props('modelValue')).toBe('https://example.com') + }) +}) diff --git a/src/components/admin/__tests__/LeaverHandoverSettings.spec.js b/src/components/admin/__tests__/LeaverHandoverSettings.spec.js new file mode 100644 index 000000000..72f1e203e --- /dev/null +++ b/src/components/admin/__tests__/LeaverHandoverSettings.spec.js @@ -0,0 +1,108 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest tests for `LeaverHandoverSettings.vue`, the Clean up block of + * Beheer ▸ Operations (dashboard-sharing REQ-SHARE-016, board LpBeheerOnderhoud). + * + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const getAdminSettings = vi.fn() +const updateLeaverHandover = vi.fn() +const searchSharees = vi.fn() +vi.mock('../../../services/api.js', () => ({ + api: { + getAdminSettings: (...args) => getAdminSettings(...args), + updateLeaverHandover: (...args) => updateLeaverHandover(...args), + searchSharees: (...args) => searchSharees(...args), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) + +const stubs = { + NcCheckboxRadioSwitch: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<label :data-test="$attrs[\'data-test\']" :data-checked="String(modelValue)" @click="$emit(\'update:modelValue\', !modelValue)"><slot /></label>', + }, + NcSelect: { + props: ['modelValue', 'options', 'inputLabel'], + emits: ['search', 'update:modelValue'], + template: '<div :data-test="$attrs[\'data-test\']" :data-label="inputLabel">{{ modelValue ? modelValue.displayName : \'\' }}</div>', + }, +} + +let LeaverHandoverSettings + +beforeEach(async () => { + getAdminSettings.mockReset() + updateLeaverHandover.mockReset() + updateLeaverHandover.mockResolvedValue({}) + searchSharees.mockReset() + LeaverHandoverSettings = (await import('../LeaverHandoverSettings.vue')).default +}) + +async function mountSettings(handover) { + getAdminSettings.mockResolvedValue({ data: { leaverHandover: handover } }) + const wrapper = mount(LeaverHandoverSettings, { global: { stubs } }) + await flushPromises() + return wrapper +} + +describe('LeaverHandoverSettings (REQ-SHARE-016)', () => { + it('shows the stored handover: the manager, otherwise the named person', async () => { + const wrapper = await mountSettings({ manager: true, fallbackUid: 'femke' }) + + expect(wrapper.text()).toContain('Dashboards of people who left go to') + expect(wrapper.find('[data-test="leaver-handover-manager"]').attributes('data-checked')).toBe('true') + const fallback = wrapper.find('[data-test="leaver-handover-fallback"]') + expect(fallback.text()).toBe('femke') + expect(fallback.attributes('data-label')).toBe('Otherwise') + }) + + it('reads no setting as no handover', async () => { + const wrapper = await mountSettings(undefined) + expect(wrapper.vm.manager).toBe(false) + expect(wrapper.vm.fallback).toBeNull() + expect(wrapper.find('[data-test="leaver-handover-fallback"]').attributes('data-label')).toBe('A person') + }) + + it('stores the manager switch and the chosen person', async () => { + const wrapper = await mountSettings({ manager: false, fallbackUid: '' }) + + await wrapper.find('[data-test="leaver-handover-manager"]').trigger('click') + await flushPromises() + expect(updateLeaverHandover).toHaveBeenLastCalledWith({ manager: true, fallbackUid: '' }) + + wrapper.findComponent(stubs.NcSelect).vm.$emit('update:modelValue', { id: 'femke', displayName: 'Femke de Wit' }) + await flushPromises() + expect(updateLeaverHandover).toHaveBeenLastCalledWith({ manager: true, fallbackUid: 'femke' }) + + wrapper.findComponent(stubs.NcSelect).vm.$emit('update:modelValue', null) + await flushPromises() + expect(updateLeaverHandover).toHaveBeenLastCalledWith({ manager: true, fallbackUid: '' }) + }) + + it('searches people from two characters and drops a stale answer', async () => { + const wrapper = await mountSettings({}) + let resolveFirst + searchSharees + .mockReturnValueOnce(new Promise((resolve) => { resolveFirst = resolve })) + .mockResolvedValueOnce({ data: { users: [{ id: 'femke', displayName: 'Femke de Wit' }] } }) + + await wrapper.vm.onSearch('f') + expect(searchSharees).not.toHaveBeenCalled() + + const first = wrapper.vm.onSearch('fe') + await wrapper.vm.onSearch('fem') + resolveFirst({ data: { users: [{ id: 'stale', displayName: 'Stale' }] } }) + await first + + expect(wrapper.vm.options).toEqual([{ id: 'femke', displayName: 'Femke de Wit' }]) + }) +}) diff --git a/src/components/admin/__tests__/OrgNavigationEditor.methods.spec.js b/src/components/admin/__tests__/OrgNavigationEditor.methods.spec.js new file mode 100644 index 000000000..1f8481203 --- /dev/null +++ b/src/components/admin/__tests__/OrgNavigationEditor.methods.spec.js @@ -0,0 +1,208 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the OrgNavigationEditor working-copy methods the + * main spec leaves out: nesting children, merging row edits, the move + * guards at either end, language switching, the position guard, the + * success toast timeout and the UUID fallback. + */ + +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import OrgNavigationEditor from '../OrgNavigationEditor.vue' +import { api } from '../../../services/api.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +vi.mock('../../../services/api.js', () => ({ + api: { + getOrgNavigation: vi.fn(), + updateOrgNavigation: vi.fn(), + getOrgNavigationPosition: vi.fn(), + updateOrgNavigationPosition: vi.fn(), + }, +})) + +const FIXED_UUID = '11111111-1111-4111-8111-111111111111' + +/** + * Let pending promises settle. + */ +async function flush() { + await new Promise((resolve) => setTimeout(resolve, 0)) + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +/** + * Mount the editor on a fresh pinia and wait for bootstrap. + * + * @return {Promise<object>} The wrapper. + */ +async function mountEditor() { + const pinia = createPinia() + setActivePinia(pinia) + const wrapper = mount(OrgNavigationEditor, { global: { plugins: [pinia] } }) + await flush() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() + api.getOrgNavigation.mockImplementation((lang) => + Promise.resolve({ + data: { tree: [{ id: `root-${lang}`, label: lang, children: [] }], language: lang }, + }), + ) + api.updateOrgNavigation.mockImplementation((tree, lang) => + Promise.resolve({ data: { tree, language: lang } }), + ) + api.getOrgNavigationPosition.mockResolvedValue({ data: { position: 'top' } }) + api.updateOrgNavigationPosition.mockResolvedValue({ data: { position: 'left' } }) + vi.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue(FIXED_UUID) +}) + +afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() +}) + +describe('OrgNavigationEditor methods', () => { + it('bootstraps the position and the Dutch tree from the store', async () => { + const wrapper = await mountEditor() + + expect(api.getOrgNavigation).toHaveBeenCalledWith('nl') + expect(wrapper.vm.selectedPosition).toBe('top') + expect(wrapper.vm.workingTree).toEqual([ + { id: 'root-nl', label: 'nl', children: [] }, + ]) + }) + + it('addChild creates the children list when missing and appends a link', async () => { + const wrapper = await mountEditor() + const parent = { id: 'p' } + + wrapper.vm.addChild({ parent, kind: 'link' }) + wrapper.vm.addChild({ parent, kind: 'section' }) + + expect(parent.children).toEqual([ + { + id: FIXED_UUID, + label: 'New link', + icon: null, + url: '/', + openInNewTab: false, + groupVisibility: null, + children: [], + }, + { + id: FIXED_UUID, + label: 'New section', + icon: null, + url: null, + openInNewTab: false, + groupVisibility: null, + children: [], + }, + ]) + }) + + it('onUpdate merges the patch into the node', async () => { + const wrapper = await mountEditor() + const node = { id: 'n', label: 'Old', url: '/a' } + + wrapper.vm.onUpdate({ node, patch: { label: 'New', openInNewTab: true } }) + + expect(node).toEqual({ id: 'n', label: 'New', url: '/a', openInNewTab: true }) + }) + + it('moveUp at the top and moveDown at the bottom leave the order alone', async () => { + const wrapper = await mountEditor() + const siblings = ['a', 'b', 'c'] + + wrapper.vm.moveUp({ siblings, index: 0 }) + wrapper.vm.moveDown({ siblings, index: 2 }) + + expect(siblings).toEqual(['a', 'b', 'c']) + }) + + it('moveDown swaps the node with the next sibling', async () => { + const wrapper = await mountEditor() + const siblings = ['a', 'b', 'c'] + + wrapper.vm.moveDown({ siblings, index: 0 }) + + expect(siblings).toEqual(['b', 'a', 'c']) + }) + + it('changing the language refetches and replaces the working tree with a copy', async () => { + const wrapper = await mountEditor() + + await wrapper.find('select').setValue('en') + await flush() + + expect(api.getOrgNavigation).toHaveBeenLastCalledWith('en') + expect(wrapper.vm.workingTree).toEqual([ + { id: 'root-en', label: 'en', children: [] }, + ]) + expect(wrapper.vm.workingTree).not.toBe(wrapper.vm.store.visibleTree) + }) + + it('an unknown position is not sent to the store', async () => { + const wrapper = await mountEditor() + + wrapper.vm.selectedPosition = 'bottom' + await wrapper.vm.onPositionChange() + + expect(api.updateOrgNavigationPosition).not.toHaveBeenCalled() + }) + + it('picking a position from the select persists it', async () => { + const wrapper = await mountEditor() + + await wrapper.findAll('select')[1].setValue('right') + await flush() + + expect(api.updateOrgNavigationPosition).toHaveBeenCalledWith('right') + }) + + it('hides the success message three seconds after a save', async () => { + const wrapper = await mountEditor() + vi.useFakeTimers() + + await wrapper.vm.save() + expect(wrapper.vm.successFlag).toBe(true) + + vi.advanceTimersByTime(2999) + expect(wrapper.vm.successFlag).toBe(true) + vi.advanceTimersByTime(1) + expect(wrapper.vm.successFlag).toBe(false) + }) + + it('cloneTree returns an empty list for a non-array', async () => { + const wrapper = await mountEditor() + + expect(wrapper.vm.cloneTree(null)).toEqual([]) + expect(wrapper.vm.cloneTree({ id: 'x' })).toEqual([]) + }) + + it('generateUuid falls back to a v4 UUID without crypto.randomUUID', async () => { + const wrapper = await mountEditor() + const original = globalThis.crypto + Object.defineProperty(globalThis, 'crypto', { value: {}, configurable: true }) + try { + const id = wrapper.vm.generateUuid() + expect(id).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, + ) + } finally { + Object.defineProperty(globalThis, 'crypto', { + value: original, + configurable: true, + }) + } + }) +}) diff --git a/src/components/admin/__tests__/OrgNavigationEditorRow.spec.js b/src/components/admin/__tests__/OrgNavigationEditorRow.spec.js new file mode 100644 index 000000000..b4fa7255d --- /dev/null +++ b/src/components/admin/__tests__/OrgNavigationEditorRow.spec.js @@ -0,0 +1,162 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `OrgNavigationEditorRow.vue`: the patches each field + * emits, the move / add-child / delete buttons and when they are disabled, + * the group visibility controls, and nested rows re-emitting their events. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import OrgNavigationEditorRow from '../OrgNavigationEditorRow.vue' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key, translate: (_app, key) => key })) + +const DraggableStub = { + props: ['list'], + template: '<ul class="draggable-stub"><template v-for="(element, index) in list" :key="element.id"><slot name="item" :element="element" :index="index" /></template></ul>', +} +const IconBrowserStub = { name: 'CnIconBrowser', emits: ['input'], template: '<div class="icon-stub" />' } + +const NODE = { id: 'n1', label: 'Home', url: '/home', icon: 'Home', openInNewTab: false, groupVisibility: null } + +function mountRow(props = {}) { + return mount(OrgNavigationEditorRow, { + props: { node: NODE, index: 0, siblings: [NODE, { id: 'n2' }], ...props }, + global: { stubs: { Draggable: DraggableStub, CnIconBrowser: IconBrowserStub } }, + }) +} + +const buttons = (wrapper) => wrapper.find('.org-nav-row__row').findAll('button.org-nav-row__btn') +const updates = (wrapper) => wrapper.emitted('update').map(([payload]) => payload.patch) + +describe('OrgNavigationEditorRow fields', () => { + it('emits label, url, icon and new-tab patches for the node', async () => { + const wrapper = mountRow() + + await wrapper.find('.org-nav-row__label').setValue('Start') + await wrapper.find('.org-nav-row__url').setValue('') + wrapper.findComponent(IconBrowserStub).vm.$emit('input', '') + wrapper.findComponent(IconBrowserStub).vm.$emit('input', 'Star') + await wrapper.find('.org-nav-row__row .org-nav-row__checkbox input').setValue(true) + + expect(wrapper.emitted('update')[0][0].node).toEqual(NODE) + expect(updates(wrapper)).toEqual([ + { label: 'Start' }, + { url: null }, + { icon: null }, + { icon: 'Star' }, + { openInNewTab: true }, + ]) + expect(wrapper.vm.localIcon).toBe('Star') + }) + + it('indents by level', () => { + expect(mountRow({ level: 3 }).find('.org-nav-row__row').attributes('style')).toContain('padding-left: 32px') + }) +}) + +describe('OrgNavigationEditorRow buttons', () => { + it('disables move up on the first row and move down on the last', () => { + const first = buttons(mountRow({ index: 0 })) + expect(first[0].attributes('disabled')).toBeDefined() + expect(first[1].attributes('disabled')).toBeUndefined() + + const last = buttons(mountRow({ index: 1 })) + expect(last[0].attributes('disabled')).toBeUndefined() + expect(last[1].attributes('disabled')).toBeDefined() + }) + + it('allows children only above the maximum depth', () => { + expect(buttons(mountRow({ level: 2, maxDepth: 3 }))[2].attributes('disabled')).toBeUndefined() + expect(buttons(mountRow({ level: 3, maxDepth: 3 }))[2].attributes('disabled')).toBeDefined() + }) + + it('emits move, add-child and delete with the row position', async () => { + const siblings = [{ id: 'a' }, NODE, { id: 'c' }] + const wrapper = mountRow({ index: 1, siblings }) + const [up, down, add, del] = buttons(wrapper) + + await up.trigger('click') + await down.trigger('click') + await add.trigger('click') + await del.trigger('click') + + expect(wrapper.emitted('moveUp')).toEqual([[{ siblings, index: 1 }]]) + expect(wrapper.emitted('moveDown')).toEqual([[{ siblings, index: 1 }]]) + expect(wrapper.emitted('addChild')).toEqual([[{ parent: NODE, kind: 'link' }]]) + expect(wrapper.emitted('delete')).toEqual([[{ siblings, index: 1 }]]) + }) +}) + +describe('OrgNavigationEditorRow visibility', () => { + const allToggle = (wrapper) => wrapper.find('.org-nav-row__visibility input[type="checkbox"]') + + it('restricts to no groups, then back to everyone', async () => { + const wrapper = mountRow() + expect(wrapper.find('.org-nav-row__groups-text').exists()).toBe(false) + + await allToggle(wrapper).setValue(false) + expect(wrapper.vm.localVisibility).toEqual([]) + expect(wrapper.find('.org-nav-row__groups-text').exists()).toBe(true) + + await allToggle(wrapper).setValue(true) + expect(wrapper.vm.localVisibility).toBeNull() + expect(updates(wrapper)).toEqual([{ groupVisibility: [] }, { groupVisibility: null }]) + }) + + it('parses free-text group ids, an empty list meaning everyone', async () => { + const wrapper = mountRow({ node: { ...NODE, groupVisibility: ['a'] } }) + const input = wrapper.find('.org-nav-row__groups-text') + expect(input.element.value).toBe('a') + + await input.setValue(' staff , ,ops ') + await input.setValue(' , ') + + expect(updates(wrapper)).toEqual([{ groupVisibility: ['staff', 'ops'] }, { groupVisibility: null }]) + expect(wrapper.vm.localVisibility).toEqual([]) + }) + + it('offers a multi-select when groups are known', async () => { + const wrapper = mountRow({ + node: { ...NODE, groupVisibility: ['g1'] }, + groups: [{ id: 'g1', displayName: 'One' }, { id: 'g2', displayName: 'Two' }], + }) + const select = wrapper.find('select.org-nav-row__groups') + expect(select.findAll('option').map((o) => o.element.value)).toEqual(['g1', 'g2']) + + select.findAll('option')[1].element.selected = true + await select.trigger('change') + + expect(updates(wrapper)).toEqual([{ groupVisibility: ['g1', 'g2'] }]) + }) +}) + +describe('OrgNavigationEditorRow children', () => { + it('renders children one level deeper and re-emits their events', async () => { + const first = { id: 'c1', label: 'First', url: '/c1' } + const second = { id: 'c2', label: 'Second', url: '/c2' } + const wrapper = mountRow({ node: { ...NODE, children: [first, second] } }) + const rowOf = (id) => wrapper.find(`[data-test-id="${id}"]`) + const childButtons = (id) => rowOf(id).find('.org-nav-row__row').findAll('button.org-nav-row__btn') + + expect(rowOf('c1').find('.org-nav-row__row').attributes('style')).toContain('padding-left: 16px') + + await rowOf('c1').find('.org-nav-row__label').setValue('Kid') + await childButtons('c2')[0].trigger('click') + await childButtons('c1')[1].trigger('click') + await childButtons('c1')[2].trigger('click') + await childButtons('c2')[3].trigger('click') + + expect(wrapper.emitted('update')).toEqual([[{ node: first, patch: { label: 'Kid' } }]]) + expect(wrapper.emitted('moveUp')).toEqual([[{ siblings: [first, second], index: 1 }]]) + expect(wrapper.emitted('moveDown')).toEqual([[{ siblings: [first, second], index: 0 }]]) + expect(wrapper.emitted('addChild')).toEqual([[{ parent: first, kind: 'link' }]]) + expect(wrapper.emitted('delete')).toEqual([[{ siblings: [first, second], index: 1 }]]) + }) + + it('renders no child list for a leaf', () => { + expect(mountRow().find('.draggable-stub').exists()).toBe(false) + }) +}) diff --git a/src/components/admin/__tests__/PublicStartPageSettings.spec.js b/src/components/admin/__tests__/PublicStartPageSettings.spec.js new file mode 100644 index 000000000..15164f5ba --- /dev/null +++ b/src/components/admin/__tests__/PublicStartPageSettings.spec.js @@ -0,0 +1,157 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `PublicStartPageSettings.vue` + * (sharing-public-start-page REQ-PSP-001): only the links the server offers + * are listed, by dashboard name; a live start page reads "Public start page: + * <name>"; a switched-on page whose link went bad says why; a save sends the + * chosen token and the switch, and a refusal shows the server's message. + * + * The `api` module is mocked at the import boundary. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-administrators-choose-a-public-link-as-the-start-page-req-psp-001 + */ + +import { showError, showSuccess } from '@nextcloud/dialogs' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import PublicStartPageSettings from '../PublicStartPageSettings.vue' +import { api } from '../../../services/api.js' + +vi.mock('../../../services/api.js', () => ({ + api: { + getPublicStart: vi.fn(), + updatePublicStart: vi.fn(), + }, +})) + +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), +})) + +const stubs = { + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel', 'disabled'], + emits: ['update:modelValue'], + template: '<div class="select"><span v-for="o in options" :key="o.token" class="option">{{ o.label }}</span></div>', + }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'disabled'], + emits: ['update:modelValue'], + template: '<label class="switch"><slot /></label>', + }, + NcNoteCard: { name: 'NcNoteCard', template: '<div class="note"><slot /></div>' }, + NcButton: { + name: 'NcButton', + props: ['variant', 'disabled'], + emits: ['click'], + template: '<button type="button" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, +} + +const NOORD = { token: 'noord', dashboardUuid: 'dash-noord', dashboardName: 'Bibliotheek Noord', expiresAt: null } +const ZUID = { token: 'zuid', dashboardUuid: 'dash-zuid', dashboardName: '', expiresAt: null } + +/** + * Mount the section over a server status. + * + * @param {object} status The GET answer. + * @return {Promise<object>} The wrapper, after the load settled + */ +async function mountWith(status) { + api.getPublicStart.mockResolvedValue({ data: status }) + const wrapper = mount(PublicStartPageSettings, { global: { stubs } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('PublicStartPageSettings', () => { + it('lists the offered links by dashboard name, the token when the dashboard has none', async () => { + const wrapper = await mountWith({ enabled: false, token: '', active: false, reason: 'off', candidates: [NOORD, ZUID] }) + + const select = wrapper.findComponent({ name: 'NcSelect' }) + expect(select.props('inputLabel')).toBe('Public link') + expect(wrapper.findAll('.option').map((o) => o.text())).toEqual(['Bibliotheek Noord', 'zuid']) + expect(wrapper.find('[data-test="public-start-no-links"]').exists()).toBe(false) + }) + + it('reads "Public start page: Bibliotheek Noord" when the start page is live', async () => { + const wrapper = await mountWith({ enabled: true, token: 'noord', active: true, reason: null, candidates: [NOORD] }) + + expect(wrapper.find('[data-test="public-start-status"]').text()).toBe('Public start page: Bibliotheek Noord') + expect(wrapper.findComponent({ name: 'NcSelect' }).props('modelValue')).toEqual({ token: 'noord', label: 'Bibliotheek Noord' }) + expect(wrapper.find('.note').exists()).toBe(false) + }) + + it.each([ + ['revoked', 'The start page is off: the chosen public link has been revoked.'], + ['password', 'The start page is off: the chosen public link now has a password.'], + ['expired', 'The start page is off: the chosen public link has expired.'], + ['not-found', 'The start page is off: the chosen public link no longer exists.'], + ['no-link', 'The start page is off: no public link is chosen.'], + ])('says why a switched-on start page is off (%s)', async (reason, message) => { + const wrapper = await mountWith({ enabled: true, token: 'noord', active: false, reason, candidates: [] }) + + expect(wrapper.find('[data-test="public-start-reason"]').text()).toBe(message) + expect(wrapper.find('[data-test="public-start-status"]').exists()).toBe(false) + expect(wrapper.find('[data-test="public-start-no-links"]').exists()).toBe(true) + }) + + it('says nothing about a start page that is switched off', async () => { + const wrapper = await mountWith({ enabled: false, token: '', active: false, reason: 'off', candidates: [NOORD] }) + + expect(wrapper.find('.note').exists()).toBe(false) + expect(wrapper.find('[data-test="public-start-status"]').exists()).toBe(false) + }) + + it('saves the chosen link and the switch, and shows the new status', async () => { + const wrapper = await mountWith({ enabled: false, token: '', active: false, reason: 'off', candidates: [NOORD] }) + api.updatePublicStart.mockResolvedValue({ data: { enabled: true, token: 'noord', active: true, reason: null } }) + + await wrapper.findComponent({ name: 'NcSelect' }).vm.$emit('update:modelValue', { token: 'noord', label: 'Bibliotheek Noord' }) + await wrapper.findComponent({ name: 'NcCheckboxRadioSwitch' }).vm.$emit('update:modelValue', true) + await wrapper.find('[data-test="public-start-save"]').trigger('click') + await flushPromises() + + expect(api.updatePublicStart).toHaveBeenCalledWith({ enabled: true, token: 'noord' }) + expect(showSuccess).toHaveBeenCalledWith('Start page saved.') + expect(wrapper.find('[data-test="public-start-status"]').text()).toBe('Public start page: Bibliotheek Noord') + }) + + it('cannot save a switched-on start page without a link', async () => { + const wrapper = await mountWith({ enabled: false, token: '', active: false, reason: 'off', candidates: [NOORD] }) + + await wrapper.findComponent({ name: 'NcCheckboxRadioSwitch' }).vm.$emit('update:modelValue', true) + + expect(wrapper.find('[data-test="public-start-save"]').attributes('disabled')).toBeDefined() + }) + + it('shows the server refusal as it is', async () => { + const wrapper = await mountWith({ enabled: false, token: '', active: false, reason: 'off', candidates: [NOORD] }) + api.updatePublicStart.mockRejectedValue({ response: { status: 400, data: { message: 'A public link with a password cannot be the start page.' } } }) + + await wrapper.findComponent({ name: 'NcSelect' }).vm.$emit('update:modelValue', { token: 'noord', label: 'Bibliotheek Noord' }) + await wrapper.find('[data-test="public-start-save"]').trigger('click') + await flushPromises() + + expect(showError).toHaveBeenCalledWith('A public link with a password cannot be the start page.') + expect(showSuccess).not.toHaveBeenCalled() + }) + + it('still renders when the status cannot be read', async () => { + api.getPublicStart.mockRejectedValue(new Error('offline')) + const wrapper = mount(PublicStartPageSettings, { global: { stubs } }) + await flushPromises() + + expect(wrapper.find('[data-test="public-start-settings"]').exists()).toBe(true) + expect(wrapper.find('[data-test="public-start-no-links"]').exists()).toBe(true) + }) +}) diff --git a/src/components/admin/__tests__/RoleLayoutDefaultsSection.spec.js b/src/components/admin/__tests__/RoleLayoutDefaultsSection.spec.js new file mode 100644 index 000000000..582893162 --- /dev/null +++ b/src/components/admin/__tests__/RoleLayoutDefaultsSection.spec.js @@ -0,0 +1,176 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `RoleLayoutDefaultsSection.vue`: loading the + * defaults, the rows with their grid and compulsory chips, the create and + * edit dialog, saving, and the confirmed delete with its failure path. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { reactive } from 'vue' +import RoleLayoutDefaultsSection from '../RoleLayoutDefaultsSection.vue' +import { logger } from '../../../utils/logger.js' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const store = vi.hoisted(() => ({ current: null })) +vi.mock('../../../stores/roleFeaturePermissions.js', () => ({ + useRoleFeaturePermissionStore: () => store.current, +})) + +const ROW = { id: 2, name: 'News first', groupId: 'staff', widgetId: 'news', gridX: 0, gridY: 1, gridWidth: 6, gridHeight: 3, isCompulsory: true } + +const DialogEditorStub = { + name: 'RoleLayoutDefaultEditorDialog', + props: ['open', 'row', 'saving'], + emits: ['update:open', 'update:row', 'save'], + template: '<div class="editor-stub" />', +} +const setResult = vi.fn() +const ConfirmStub = { + name: 'CnConfirmDialog', + props: ['message'], + emits: ['confirm', 'close'], + methods: { setResult }, + template: '<div class="confirm-stub">{{ message }}</div>', +} +const ButtonStub = { + props: ['ariaLabel'], + emits: ['click'], + template: '<button :aria-label="ariaLabel" @click="$emit(\'click\')"><slot /></button>', +} + +async function mountSection() { + const wrapper = mount(RoleLayoutDefaultsSection, { + global: { + mocks: { t: globalThis.t }, + stubs: { + RoleLayoutDefaultEditorDialog: DialogEditorStub, + CnConfirmDialog: ConfirmStub, + NcButton: ButtonStub, + NcEmptyContent: { template: '<div class="empty-stub" />' }, + ViewDashboard: true, + Plus: true, + Pencil: true, + Delete: true, + }, + }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() + globalThis.t = (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`) + store.current = reactive({ + layoutDefaults: [ROW], + loading: false, + saving: false, + error: null, + loadLayoutDefaults: vi.fn().mockResolvedValue(), + saveLayoutDefault: vi.fn().mockResolvedValue(), + deleteLayoutDefault: vi.fn().mockResolvedValue(), + }) +}) + +describe('RoleLayoutDefaultsSection', () => { + it('loads the defaults and lists them with their chips', async () => { + const wrapper = await mountSection() + + expect(store.current.loadLayoutDefaults).toHaveBeenCalledTimes(1) + const row = wrapper.find('.launchpad-admin__role-row') + expect(row.find('.launchpad-admin__role-group').text()).toBe('staff / news') + expect(row.find('.launchpad-admin__chip--compulsory').exists()).toBe(true) + expect(row.findAll('.launchpad-admin__chip')[0].text()).toBe('0,1 6×3') + }) + + it('shows the empty state, the store error, and logs a failed load', async () => { + store.current.layoutDefaults = [] + store.current.error = 'Boom' + store.current.loadLayoutDefaults.mockRejectedValue(new Error('x')) + const wrapper = await mountSection() + + expect(wrapper.find('.empty-stub').exists()).toBe(true) + expect(wrapper.find('.launchpad-admin__error').text()).toBe('Boom') + expect(logger.error).toHaveBeenCalledWith('Failed to load layout defaults', expect.any(Error)) + }) + + it('opens a blank row for create and the row for edit', async () => { + const wrapper = await mountSection() + + await wrapper.find('[data-testid="admin-add-layout-default"]').trigger('click') + expect(wrapper.findComponent(DialogEditorStub).props('row')).toEqual({ + id: null, name: '', groupId: '', widgetId: '', gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 4, sortOrder: 0, isCompulsory: false, description: '', + }) + + await wrapper.find('.launchpad-admin__role-row button[aria-label="Edit"]').trigger('click') + expect(wrapper.findComponent(DialogEditorStub).props('row')).toEqual(ROW) + }) + + it('saves the edited row and closes the dialog', async () => { + const wrapper = await mountSection() + wrapper.vm.openEdit(ROW) + await wrapper.vm.$nextTick() + const dialog = wrapper.findComponent(DialogEditorStub) + + dialog.vm.$emit('update:row', { ...ROW, gridWidth: 12 }) + dialog.vm.$emit('save') + await flushPromises() + + expect(store.current.saveLayoutDefault).toHaveBeenCalledWith({ ...ROW, gridWidth: 12 }) + expect(wrapper.findComponent(DialogEditorStub).exists()).toBe(false) + }) + + it('keeps the dialog open when saving fails, and closes on update:open', async () => { + store.current.saveLayoutDefault.mockRejectedValue(new Error('x')) + const wrapper = await mountSection() + wrapper.vm.openCreate() + await wrapper.vm.save() + expect(wrapper.vm.showEditor).toBe(true) + expect(logger.error).toHaveBeenCalledWith('Failed to save layout default', expect.any(Error)) + + await wrapper.vm.$nextTick() + wrapper.findComponent(DialogEditorStub).vm.$emit('update:open', false) + await wrapper.vm.$nextTick() + expect(wrapper.findComponent(DialogEditorStub).exists()).toBe(false) + }) + + it('confirms and deletes a default', async () => { + const wrapper = await mountSection() + await wrapper.find('.launchpad-admin__role-row button[aria-label="Delete"]').trigger('click') + + const confirm = wrapper.findComponent(ConfirmStub) + expect(confirm.text()).toBe('Delete layout default for "staff" / "news"?') + confirm.vm.$emit('confirm') + await flushPromises() + + expect(store.current.deleteLayoutDefault).toHaveBeenCalledWith(2) + expect(wrapper.findComponent(ConfirmStub).exists()).toBe(false) + expect(wrapper.vm.deleteTarget).toBeNull() + }) + + it('hands the store error to the dialog when deleting fails, and ignores a missing target', async () => { + store.current.deleteLayoutDefault.mockImplementation(async () => { + store.current.error = 'Locked' + throw new Error('x') + }) + const wrapper = await mountSection() + await wrapper.vm.confirmDelete() + expect(store.current.deleteLayoutDefault).not.toHaveBeenCalled() + + wrapper.vm.openDeleteDialog(ROW) + await wrapper.vm.$nextTick() + await wrapper.vm.confirmDelete() + + expect(setResult).toHaveBeenCalledWith({ error: 'Locked' }) + expect(wrapper.vm.showDeleteDialog).toBe(true) + expect(logger.error).toHaveBeenCalledWith('Failed to delete layout default', expect.any(Error)) + }) +}) diff --git a/src/components/admin/__tests__/RolePermissionsSection.spec.js b/src/components/admin/__tests__/RolePermissionsSection.spec.js new file mode 100644 index 000000000..6da26b395 --- /dev/null +++ b/src/components/admin/__tests__/RolePermissionsSection.spec.js @@ -0,0 +1,210 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `RolePermissionsSection.vue`: loading the role + * permissions, the create and edit forms with their widget CSV fields, the + * save payload, and the confirmed delete with its failure path. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { reactive } from 'vue' +import RolePermissionsSection from '../RolePermissionsSection.vue' +import { logger } from '../../../utils/logger.js' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const store = vi.hoisted(() => ({ current: null })) +vi.mock('../../../stores/roleFeaturePermissions.js', () => ({ + useRoleFeaturePermissionStore: () => store.current, +})) + +const ROW = { + id: 4, + name: 'Editors', + groupId: 'editors', + description: 'Can edit', + allowedWidgets: ['news', 'files'], + deniedWidgets: ['weather'], + priorityWeights: { news: 2 }, +} + +const EditorStub = { + name: 'RolePermissionEditorModal', + props: ['row', 'allowedWidgetsCsv', 'deniedWidgetsCsv', 'saving'], + emits: ['update:row', 'update:allowedWidgetsCsv', 'update:deniedWidgetsCsv', 'save', 'close'], + template: '<div class="editor-stub" />', +} +const setResult = vi.fn() +const DialogStub = { + name: 'CnConfirmDialog', + props: ['message'], + emits: ['confirm', 'close'], + methods: { setResult }, + template: '<div class="dialog-stub">{{ message }}</div>', +} + +async function mountSection() { + const wrapper = mount(RolePermissionsSection, { + global: { + stubs: { + RolePermissionEditorModal: EditorStub, + CnConfirmDialog: DialogStub, + NcButton: { emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>' }, + NcEmptyContent: { template: '<div class="empty-stub" />' }, + AccountGroup: true, + Plus: true, + Pencil: true, + Delete: true, + }, + }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() + store.current = reactive({ + permissions: [ROW], + loading: false, + saving: false, + error: null, + loadPermissions: vi.fn().mockResolvedValue(), + savePermission: vi.fn().mockResolvedValue(), + deletePermission: vi.fn().mockResolvedValue(), + }) +}) + +describe('RolePermissionsSection', () => { + it('loads the permissions on mount and logs a failure', async () => { + await mountSection() + expect(store.current.loadPermissions).toHaveBeenCalledTimes(1) + + store.current.loadPermissions.mockRejectedValue(new Error('x')) + await mountSection() + expect(logger.error).toHaveBeenCalledWith('Failed to load role permissions', expect.any(Error)) + }) + + it('shows the empty state and the store error', async () => { + store.current.permissions = [] + store.current.error = 'Boom' + const wrapper = await mountSection() + + expect(wrapper.find('.empty-stub').exists()).toBe(true) + expect(wrapper.find('.launchpad-admin__error').text()).toBe('Boom') + }) + + it('opens a blank create form', async () => { + const wrapper = await mountSection() + wrapper.vm.openEdit(ROW) + wrapper.vm.openCreate() + await wrapper.vm.$nextTick() + + expect(wrapper.findComponent(EditorStub).props()).toMatchObject({ + row: { id: null, name: '', groupId: '', description: '', allowedWidgets: [], deniedWidgets: [], priorityWeights: {} }, + allowedWidgetsCsv: '', + deniedWidgetsCsv: '', + }) + }) + + it('opens an edit form with the widget lists as CSV, defaulting missing ones', async () => { + const wrapper = await mountSection() + wrapper.vm.openEdit(ROW) + await wrapper.vm.$nextTick() + expect(wrapper.findComponent(EditorStub).props()).toMatchObject({ + allowedWidgetsCsv: 'news, files', + deniedWidgetsCsv: 'weather', + }) + + wrapper.vm.openEdit({ id: 5, name: 'Bare', groupId: 'g' }) + expect(wrapper.vm.editorRow).toMatchObject({ allowedWidgets: [], deniedWidgets: [], priorityWeights: {} }) + expect(wrapper.vm.allowedWidgetsCsv).toBe('') + }) + + it('saves the edited form with parsed widget lists and closes', async () => { + const wrapper = await mountSection() + wrapper.vm.openEdit(ROW) + await wrapper.vm.$nextTick() + const editor = wrapper.findComponent(EditorStub) + + editor.vm.$emit('update:row', { ...ROW, description: '' }) + editor.vm.$emit('update:allowedWidgetsCsv', ' news , ,calendar ') + editor.vm.$emit('update:deniedWidgetsCsv', '') + editor.vm.$emit('save') + await flushPromises() + + expect(store.current.savePermission).toHaveBeenCalledWith({ + name: 'Editors', + groupId: 'editors', + description: null, + allowedWidgets: ['news', 'calendar'], + deniedWidgets: [], + priorityWeights: { news: 2 }, + }) + expect(wrapper.findComponent(EditorStub).exists()).toBe(false) + }) + + it('keeps the form open and logs when saving fails', async () => { + store.current.savePermission.mockRejectedValue(new Error('x')) + const wrapper = await mountSection() + wrapper.vm.openCreate() + await wrapper.vm.save() + + expect(wrapper.vm.showEditor).toBe(true) + expect(logger.error).toHaveBeenCalledWith('Failed to save role permission', expect.any(Error)) + }) + + it('closes the form from the editor', async () => { + const wrapper = await mountSection() + wrapper.vm.openCreate() + await wrapper.vm.$nextTick() + wrapper.findComponent(EditorStub).vm.$emit('close') + await wrapper.vm.$nextTick() + expect(wrapper.findComponent(EditorStub).exists()).toBe(false) + }) + + it('confirms and deletes a row', async () => { + const wrapper = await mountSection() + wrapper.vm.confirmDelete(ROW) + await wrapper.vm.$nextTick() + + const dialog = wrapper.findComponent(DialogStub) + expect(dialog.text()).toBe('Delete role permission for group "editors"?') + + dialog.vm.$emit('confirm') + await flushPromises() + + expect(store.current.deletePermission).toHaveBeenCalledWith(4) + expect(wrapper.vm.showDeleteDialog).toBe(false) + expect(wrapper.vm.deleteTarget).toBeNull() + }) + + it('hands the store error to the dialog when deleting fails', async () => { + store.current.deletePermission.mockImplementation(async () => { + store.current.error = 'In use' + throw new Error('x') + }) + const wrapper = await mountSection() + wrapper.vm.confirmDelete(ROW) + await wrapper.vm.$nextTick() + + await wrapper.vm.doDelete() + + expect(setResult).toHaveBeenCalledWith({ error: 'In use' }) + expect(wrapper.vm.showDeleteDialog).toBe(true) + expect(logger.error).toHaveBeenCalledWith('Failed to delete role permission', expect.any(Error)) + }) + + it('does nothing when deleting without a target', async () => { + const wrapper = await mountSection() + expect(wrapper.vm.deleteMessage).toBe('Delete role permission for group ""?') + await wrapper.vm.doDelete() + expect(store.current.deletePermission).not.toHaveBeenCalled() + }) +}) diff --git a/src/components/admin/__tests__/TileLaunchSettings.spec.js b/src/components/admin/__tests__/TileLaunchSettings.spec.js new file mode 100644 index 000000000..8680cb0cd --- /dev/null +++ b/src/components/admin/__tests__/TileLaunchSettings.spec.js @@ -0,0 +1,147 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * TileLaunchSettings: the admin lists behind program and single sign-on + * tiles (launcher-tile-launch-types task 6, REQ-ASET-020). Each change saves + * the whole list through PUT /api/admin/settings; a refusal leaves the list + * as it was and shows the server's message. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../../services/api.js' + +vi.mock('../../../services/api.js', () => ({ + api: { getAdminSettings: vi.fn(), updateAdminSettings: vi.fn() }, +})) + +const { default: TileLaunchSettings } = await import('../TileLaunchSettings.vue') + +const stubs = { + CnSettingsSection: { name: 'CnSettingsSection', props: ['name'], template: '<section :data-name="name"><slot /></section>' }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: '<input class="text-field" :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcButton: { + name: 'NcButton', + props: ['type', 'disabled', 'ariaLabel'], + emits: ['click'], + template: '<button class="button" :type="type || \'button\'" :disabled="disabled" :aria-label="ariaLabel" @click="$emit(\'click\')"><slot /></button>', + }, +} + +const entra = { key: 'entra', name: 'Microsoft Entra ID', urlTemplate: 'https://launcher.myapps.microsoft.com/api/signin/{appId}?tenantId=contoso' } + +function settings(fields) { + return { data: { tileAllowedSchemes: [], ssoLaunchTemplates: [], ...fields } } +} + +async function mountSettings() { + const wrapper = mount(TileLaunchSettings, { global: { stubs } }) + await flushPromises() + return wrapper +} + +function field(wrapper, label) { + return wrapper.find(`input.text-field[aria-label="${label}"]`) +} + +describe('TileLaunchSettings', () => { + beforeEach(() => { + vi.clearAllMocks() + api.updateAdminSettings.mockResolvedValue({ data: { status: 'ok' } }) + }) + + it('shows both lists as stored', async () => { + api.getAdminSettings.mockResolvedValue(settings({ tileAllowedSchemes: ['ms-word'], ssoLaunchTemplates: [entra] })) + const wrapper = await mountSettings() + + expect(wrapper.find('[data-testid="admin-tile-schemes"]').text()).toContain('ms-word') + expect(wrapper.find('[data-testid="admin-sso-templates"]').text()).toContain('Microsoft Entra ID') + expect(wrapper.find('[data-testid="admin-sso-templates"]').text()).toContain(entra.urlTemplate) + }) + + it('says when nothing is allowed yet', async () => { + api.getAdminSettings.mockResolvedValue(settings({})) + const wrapper = await mountSettings() + + expect(wrapper.text()).toContain('No schemes allowed yet, so program tiles do nothing.') + expect(wrapper.text()).toContain('No sign-on templates yet.') + }) + + it('allows a scheme by saving the whole list', async () => { + api.getAdminSettings.mockResolvedValueOnce(settings({ tileAllowedSchemes: ['ms-word'] })) + .mockResolvedValueOnce(settings({ tileAllowedSchemes: ['ms-word', 'vscode'] })) + const wrapper = await mountSettings() + + await field(wrapper, 'Scheme').setValue(' vscode ') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenCalledWith({ tileAllowedSchemes: ['ms-word', 'vscode'] }) + expect(wrapper.find('[data-testid="admin-tile-schemes"]').text()).toContain('vscode') + expect(field(wrapper, 'Scheme').element.value).toBe('') + }) + + it('keeps the list and shows the refusal when the server refuses a scheme', async () => { + api.getAdminSettings.mockResolvedValue(settings({})) + api.updateAdminSettings.mockRejectedValue({ response: { status: 400, data: { error: 'The scheme "javascript" is never allowed on a tile.' } } }) + const wrapper = await mountSettings() + + await field(wrapper, 'Scheme').setValue('javascript') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.find('[role="alert"]').text()).toBe('The scheme "javascript" is never allowed on a tile.') + expect(wrapper.find('[data-testid="admin-tile-schemes"]').exists()).toBe(false) + expect(field(wrapper, 'Scheme').element.value).toBe('javascript') + }) + + it('removes a scheme', async () => { + api.getAdminSettings.mockResolvedValue(settings({ tileAllowedSchemes: ['ms-word', 'vscode'] })) + const wrapper = await mountSettings() + + await wrapper.findAll('[data-testid="admin-tile-schemes"] button')[0].trigger('click') + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenCalledWith({ tileAllowedSchemes: ['vscode'] }) + }) + + it('adds a template once every field is filled in', async () => { + api.getAdminSettings.mockResolvedValue(settings({})) + const wrapper = await mountSettings() + const submit = wrapper.findAll('form')[1].find('button[type="submit"]') + expect(submit.attributes('disabled')).toBeDefined() + + await field(wrapper, 'Template name').setValue('Microsoft Entra ID') + await field(wrapper, 'Key').setValue('entra') + await field(wrapper, 'Sign-on address').setValue(entra.urlTemplate) + expect(submit.attributes('disabled')).toBeUndefined() + await wrapper.findAll('form')[1].trigger('submit') + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenCalledWith({ ssoLaunchTemplates: [entra] }) + }) + + it('removes a template by its key', async () => { + api.getAdminSettings.mockResolvedValue(settings({ ssoLaunchTemplates: [entra, { key: 'kc', name: 'Keycloak', urlTemplate: 'https://sso.example.nl/{appId}' }] })) + const wrapper = await mountSettings() + + await wrapper.find('[data-testid="admin-sso-templates"] button').trigger('click') + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenCalledWith({ ssoLaunchTemplates: [{ key: 'kc', name: 'Keycloak', urlTemplate: 'https://sso.example.nl/{appId}' }] }) + }) + + it('names what each remove button removes, for screen readers', async () => { + api.getAdminSettings.mockResolvedValue(settings({ tileAllowedSchemes: ['ms-word'], ssoLaunchTemplates: [entra] })) + const wrapper = await mountSettings() + + const labels = wrapper.findAll('li button').map((b) => b.attributes('aria-label')) + expect(labels).toEqual(['Remove {scheme}', 'Remove {name}']) + }) +}) diff --git a/src/components/admin/__tests__/adminDataPanels.spec.js b/src/components/admin/__tests__/adminDataPanels.spec.js new file mode 100644 index 000000000..07778657d --- /dev/null +++ b/src/components/admin/__tests__/adminDataPanels.spec.js @@ -0,0 +1,254 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for AdminDemoData (install / uninstall demo showcases), + * ConditionalVisibilityOverview (the widgets-with-rules table) and the + * export half of DashboardExportImport plus its import paths not covered by + * DashboardExportImport.spec.js. + */ + +import { flushPromises, mount, shallowMount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import AdminDemoData from '../AdminDemoData.vue' +import ConditionalVisibilityOverview from '../ConditionalVisibilityOverview.vue' +import DashboardExportImport from '../DashboardExportImport.vue' +import { api } from '../../../services/api.js' +import { logger } from '../../../utils/logger.js' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, key) => key, + translate: (_app, key) => key, +})) +vi.mock('../../../services/api.js', () => ({ + api: { + listDemoShowcases: vi.fn(), + installDemoShowcase: vi.fn(), + uninstallDemoShowcase: vi.fn(), + getAdminWidgetsWithRules: vi.fn(), + exportDashboards: vi.fn(), + importDashboards: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const t = (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`) + +beforeEach(() => { + vi.clearAllMocks() +}) + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('AdminDemoData', () => { + const SHOWCASES = [ + { id: 'gov', title: 'Municipality', language: 'nl', isInstalled: false }, + { id: 'edu', title: 'School', language: 'en', isInstalled: true }, + ] + + async function mountDemo() { + const wrapper = shallowMount(AdminDemoData, { global: { mocks: { t } } }) + await flushPromises() + return wrapper + } + + beforeEach(() => { + api.listDemoShowcases.mockResolvedValue({ data: SHOWCASES }) + api.installDemoShowcase.mockResolvedValue({ data: {} }) + api.uninstallDemoShowcase.mockResolvedValue({}) + }) + + it('lists the showcases on mount', async () => { + const wrapper = await mountDemo() + expect(wrapper.vm.showcases).toEqual(SHOWCASES) + expect(wrapper.find('[data-test="showcase-card-gov"]').exists()).toBe(true) + expect(wrapper.vm.loading).toBe(false) + }) + + it('shows a load error, and an empty list for no data', async () => { + api.listDemoShowcases.mockRejectedValueOnce(new Error('x')) + const failed = await mountDemo() + expect(failed.find('.launchpad-demo-showcases__error').text()).toBe('Could not load demo showcases. Please try again.') + + api.listDemoShowcases.mockResolvedValueOnce({ data: null }) + expect((await mountDemo()).vm.showcases).toEqual([]) + }) + + it('installs a showcase, keeps skipped widgets as a warning and reloads', async () => { + api.installDemoShowcase.mockResolvedValue({ data: { skippedWidgets: ['weather'] } }) + const wrapper = await mountDemo() + + const pending = wrapper.vm.install(SHOWCASES[0]) + expect(wrapper.vm.busy.gov).toBe(true) + await pending + + expect(api.installDemoShowcase).toHaveBeenCalledWith('gov') + expect(wrapper.vm.warnings).toEqual({ gov: ['weather'] }) + expect(api.listDemoShowcases).toHaveBeenCalledTimes(2) + expect(wrapper.vm.busy.gov).toBe(false) + + api.installDemoShowcase.mockResolvedValue({ data: { skippedWidgets: [] } }) + await wrapper.vm.install(SHOWCASES[0]) + expect(wrapper.vm.warnings).toEqual({}) + }) + + it.each([ + [404, 'Showcase not found.'], + [403, 'You need admin privileges to install showcases.'], + [500, 'Could not install showcase. Please try again.'], + ])('explains a failed install with status %s', async (status, message) => { + api.installDemoShowcase.mockRejectedValue({ response: { status } }) + const wrapper = await mountDemo() + + await wrapper.vm.install(SHOWCASES[0]) + + expect(wrapper.vm.actionError).toBe(message) + expect(wrapper.find('[data-test="showcase-action-error"]').exists()).toBe(true) + expect(wrapper.vm.busy.gov).toBe(false) + }) + + it('uninstalls only after confirming, dropping its warning', async () => { + const wrapper = await mountDemo() + wrapper.vm.warnings.edu = ['x'] + + wrapper.vm.confirmUninstall(SHOWCASES[1]) + expect(wrapper.vm.uninstallTarget).toEqual(SHOWCASES[1]) + expect(api.uninstallDemoShowcase).not.toHaveBeenCalled() + + await wrapper.vm.onUninstallConfirm() + + expect(api.uninstallDemoShowcase).toHaveBeenCalledWith('edu') + expect(wrapper.vm.uninstallTarget).toBeNull() + expect(wrapper.vm.warnings).toEqual({}) + expect(api.listDemoShowcases).toHaveBeenCalledTimes(2) + }) + + it('does nothing when confirming without a target, and reports a failed uninstall', async () => { + const wrapper = await mountDemo() + await wrapper.vm.onUninstallConfirm() + expect(api.uninstallDemoShowcase).not.toHaveBeenCalled() + + api.uninstallDemoShowcase.mockRejectedValue(new Error('x')) + wrapper.vm.confirmUninstall(SHOWCASES[1]) + await wrapper.vm.onUninstallConfirm() + expect(wrapper.vm.actionError).toBe('Could not uninstall showcase. Please try again.') + expect(wrapper.vm.busy.edu).toBe(false) + }) + + it('hides a thumbnail that fails to load', async () => { + const wrapper = await mountDemo() + const target = { style: {} } + wrapper.vm.onThumbError({ target }) + expect(target.style.display).toBe('none') + }) +}) + +describe('ConditionalVisibilityOverview', () => { + const stubs = { + NcEmptyContent: { props: ['name'], template: '<div class="empty-stub">{{ name }}</div>' }, + NcLoadingIcon: { template: '<span class="loading-stub" />' }, + EyeOff: true, + } + const ROW = { placementId: 3, dashboardName: 'Ops', widgetType: 'news', ruleCount: 2, includeCount: 1, excludeCount: 1 } + + async function mountOverview() { + const wrapper = mount(ConditionalVisibilityOverview, { global: { stubs } }) + await flushPromises() + return wrapper + } + + it.each([ + ['a list', { data: [ROW] }], + ['a wrapped list', { data: { data: [ROW] } }], + ])('renders the rows from %s', async (_case, response) => { + api.getAdminWidgetsWithRules.mockResolvedValue(response) + const wrapper = await mountOverview() + + const cells = wrapper.findAll('[data-test="cv-overview-table"] tbody td').map((c) => c.text()) + expect(cells.slice(1)).toEqual(['news', '2', '1', '1']) + }) + + it('shows the empty state for no rows or a failure', async () => { + api.getAdminWidgetsWithRules.mockResolvedValueOnce({ data: {} }) + const empty = await mountOverview() + expect(empty.find('[data-test="cv-overview-table"]').exists()).toBe(false) + + api.getAdminWidgetsWithRules.mockRejectedValueOnce(new Error('x')) + const failed = await mountOverview() + expect(failed.vm.rows).toEqual([]) + expect(failed.vm.loading).toBe(false) + expect(logger.error).toHaveBeenCalledWith('Failed to load conditional visibility overview:', expect.any(Error)) + }) +}) + +describe('DashboardExportImport', () => { + function mountExportImport() { + return shallowMount(DashboardExportImport, { global: { mocks: { t } } }) + } + + it('downloads the site export with a timestamped name', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-03-11T09:08:07.123Z')) + const blob = new Blob(['zip']) + api.exportDashboards.mockResolvedValue({ data: blob }) + window.URL.createObjectURL = vi.fn(() => 'blob:zip') + window.URL.revokeObjectURL = vi.fn() + const clicks = [] + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function() { + clicks.push({ href: this.getAttribute('href'), download: this.download }) + }) + const wrapper = mountExportImport() + + await wrapper.vm.exportSite() + + expect(api.exportDashboards).toHaveBeenCalledWith({ scope: 'site' }) + expect(window.URL.createObjectURL).toHaveBeenCalledWith(blob) + expect(clicks).toEqual([{ href: 'blob:zip', download: 'launchpad-export-20260311090807.zip' }]) + expect(window.URL.revokeObjectURL).toHaveBeenCalledWith('blob:zip') + expect(wrapper.vm.exporting).toBe(false) + }) + + it('shows an export error and logs it', async () => { + api.exportDashboards.mockRejectedValue(new Error('x')) + const wrapper = mountExportImport() + + await wrapper.vm.exportSite() + + expect(wrapper.vm.exportError).toBe('Export failed. Please try again.') + expect(wrapper.vm.exporting).toBe(false) + expect(logger.error).toHaveBeenCalledWith('launchpad export failed', expect.any(Error)) + }) + + it('imports the picked archive with the preserve-UUIDs choice', async () => { + const file = new File(['zip'], 'a.zip') + api.importDashboards.mockResolvedValue({ data: { imported: 2, errors: [] } }) + const wrapper = mountExportImport() + + await wrapper.vm.runImport() + expect(api.importDashboards).not.toHaveBeenCalled() + + wrapper.vm.onFileSelected({ target: { files: [file] } }) + wrapper.vm.preserveUuids = true + await wrapper.vm.runImport() + + expect(api.importDashboards).toHaveBeenCalledWith(file, { preserveUuids: true }) + expect(wrapper.vm.importResult).toEqual({ imported: 2, errors: [] }) + expect(wrapper.vm.importing).toBe(false) + }) + + it('clears the earlier result when another file is picked', async () => { + const wrapper = mountExportImport() + wrapper.vm.importResult = { imported: 1 } + wrapper.vm.importError = 'old' + + wrapper.vm.onFileSelected({ target: { files: [] } }) + + expect(wrapper.vm.selectedFile).toBeNull() + expect(wrapper.vm.importResult).toBeNull() + expect(wrapper.vm.importError).toBe('') + }) +}) diff --git a/src/components/admin/__tests__/adminPanels.spec.js b/src/components/admin/__tests__/adminPanels.spec.js new file mode 100644 index 000000000..f077e936d --- /dev/null +++ b/src/components/admin/__tests__/adminPanels.spec.js @@ -0,0 +1,355 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for four small admin panels: HealthPanel, + * PrometheusMetricsPanel, LegacyWidgetBridgeToggle and + * DashboardSharingPolicy. Each loads from the admin API on creation; the + * toggle and the sharing policy save back and handle failures. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import AnnouncementEditorsPolicy from '../AnnouncementEditorsPolicy.vue' +import DashboardSharingPolicy from '../DashboardSharingPolicy.vue' +import HealthPanel from '../HealthPanel.vue' +import LegacyWidgetBridgeToggle from '../LegacyWidgetBridgeToggle.vue' +import PrometheusMetricsPanel from '../PrometheusMetricsPanel.vue' +import { api } from '../../../services/api.js' +import { logger } from '../../../utils/logger.js' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) +vi.mock('../../../services/api.js', () => ({ + api: { + getHealth: vi.fn(), + getMetrics: vi.fn(), + getAdminSettings: vi.fn(), + updateAdminSettings: vi.fn(), + }, +})) +vi.mock('../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const ButtonStub = { + props: ['disabled'], + emits: ['click'], + template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', +} +const SwitchStub = { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'disabled'], + emits: ['update:modelValue'], + template: '<label class="switch-stub"><slot /></label>', +} +const SelectStub = { + name: 'NcSelect', + props: ['modelValue', 'options'], + emits: ['update:modelValue'], + template: '<div class="select-stub" />', +} +const TagsStub = { + name: 'NcSelectTags', + props: ['modelValue', 'options'], + emits: ['update:modelValue'], + template: '<div class="tags-stub" />', +} + +const stubs = { + NcButton: ButtonStub, + NcLoadingIcon: { template: '<span class="loading-stub" />' }, + ContentCopy: true, + NcCheckboxRadioSwitch: SwitchStub, + NcSelect: SelectStub, + NcSelectTags: TagsStub, +} + +const mountWith = (component, props = {}) => mount(component, { props, global: { stubs } }) + +beforeEach(() => { + vi.clearAllMocks() + api.updateAdminSettings.mockResolvedValue({}) +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('HealthPanel', () => { + it.each([ + ['an ok status', { data: { status: 'ok' } }, 'Healthy'], + ['a wrapped ok status', { data: { data: { status: 'ok' } } }, 'Healthy'], + ['another status', { data: { status: 'degraded' } }, 'Degraded'], + ['no data', { data: null }, 'Degraded'], + ])('shows %s as %s', async (_case, response, label) => { + api.getHealth.mockResolvedValue(response) + const wrapper = mountWith(HealthPanel) + expect(wrapper.find('[data-test="health-badge"]').text()).toBe('Checking…') + await flushPromises() + expect(wrapper.find('[data-test="health-badge"]').text()).toBe(label) + }) + + it('shows degraded when the check fails', async () => { + api.getHealth.mockRejectedValue(new Error('503')) + const wrapper = mountWith(HealthPanel) + await flushPromises() + expect(wrapper.find('.health-panel__badge--bad').exists()).toBe(true) + }) +}) + +describe('PrometheusMetricsPanel', () => { + it('shows the metrics text as returned', async () => { + api.getMetrics.mockResolvedValue({ data: 'launchpad_up 1\n' }) + const wrapper = mountWith(PrometheusMetricsPanel) + expect(wrapper.find('.loading-stub').exists()).toBe(true) + await flushPromises() + expect(wrapper.find('[data-test="metrics-body"]').text()).toBe('launchpad_up 1') + expect(wrapper.find('button').attributes('disabled')).toBeUndefined() + }) + + it('pretty-prints a non-text payload', async () => { + api.getMetrics.mockResolvedValue({ data: { up: 1 } }) + const wrapper = mountWith(PrometheusMetricsPanel) + await flushPromises() + expect(wrapper.vm.body).toBe('{\n "up": 1\n}') + }) + + it('shows an error and disables copy when loading fails', async () => { + api.getMetrics.mockRejectedValue(new Error('403')) + const wrapper = mountWith(PrometheusMetricsPanel) + await flushPromises() + expect(wrapper.find('[data-test="metrics-error"]').exists()).toBe(true) + expect(wrapper.find('button').attributes('disabled')).toBeDefined() + }) + + it('copies the body and shows "Copied" for two seconds', async () => { + vi.useFakeTimers() + const writeText = vi.fn().mockResolvedValue() + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }) + api.getMetrics.mockResolvedValue({ data: 'm 1' }) + const wrapper = mountWith(PrometheusMetricsPanel) + await flushPromises() + + await wrapper.find('button').trigger('click') + await flushPromises() + expect(writeText).toHaveBeenCalledWith('m 1') + expect(wrapper.find('button').text()).toBe('Copied') + + vi.advanceTimersByTime(1999) + await wrapper.vm.$nextTick() + expect(wrapper.find('button').text()).toBe('Copied') + + vi.advanceTimersByTime(1) + await wrapper.vm.$nextTick() + expect(wrapper.find('button').text()).toBe('Copy') + }) + + it('stays on "Copy" when the clipboard refuses or is missing', async () => { + Object.defineProperty(navigator, 'clipboard', { + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + configurable: true, + }) + api.getMetrics.mockResolvedValue({ data: 'm 1' }) + const wrapper = mountWith(PrometheusMetricsPanel) + await flushPromises() + + await wrapper.vm.copy() + expect(wrapper.vm.copied).toBe(false) + + Object.defineProperty(navigator, 'clipboard', { value: undefined, configurable: true }) + await wrapper.vm.copy() + expect(wrapper.vm.copied).toBe(false) + }) +}) + +describe('LegacyWidgetBridgeToggle', () => { + it.each([ + [{ data: { legacyWidgetBridgeEnabled: false } }, false], + [{ data: { data: { legacyWidgetBridgeEnabled: true } } }, true], + [{ data: {} }, true], + ])('reads the stored setting %#', async (response, enabled) => { + api.getAdminSettings.mockResolvedValue(response) + const wrapper = mountWith(LegacyWidgetBridgeToggle) + expect(wrapper.findComponent(SwitchStub).props('disabled')).toBe(true) + await flushPromises() + + expect(wrapper.findComponent(SwitchStub).props()).toEqual({ modelValue: enabled, disabled: false }) + }) + + it('stays enabled and logs when loading fails', async () => { + api.getAdminSettings.mockRejectedValue(new Error('x')) + const wrapper = mountWith(LegacyWidgetBridgeToggle) + await flushPromises() + expect(wrapper.vm.enabled).toBe(true) + expect(logger.error).toHaveBeenCalledWith('Failed to load bridge setting:', expect.any(Error)) + }) + + it('saves a toggle and reverts it when saving fails', async () => { + api.getAdminSettings.mockResolvedValue({ data: {} }) + const wrapper = mountWith(LegacyWidgetBridgeToggle) + await flushPromises() + + wrapper.findComponent(SwitchStub).vm.$emit('update:modelValue', false) + await flushPromises() + expect(api.updateAdminSettings).toHaveBeenCalledWith({ legacyWidgetBridgeEnabled: false }) + expect(wrapper.vm.enabled).toBe(false) + + api.updateAdminSettings.mockRejectedValue(new Error('x')) + wrapper.findComponent(SwitchStub).vm.$emit('update:modelValue', true) + await flushPromises() + expect(wrapper.vm.enabled).toBe(false) + expect(logger.error).toHaveBeenCalledWith('Failed to save bridge setting:', expect.any(Error)) + }) +}) + +describe('DashboardSharingPolicy', () => { + it('loads the stored level and forced groups', async () => { + api.getAdminSettings.mockResolvedValue({ + data: { defaultSharePermissionLevel: 'full', forcedShareGroups: ['staff'] }, + }) + const wrapper = mountWith(DashboardSharingPolicy, { groups: ['staff', 'ops'] }) + await flushPromises() + + expect(wrapper.findComponent(SelectStub).props('modelValue')).toEqual({ id: 'full', label: 'Full customization' }) + expect(wrapper.findComponent(TagsStub).props()).toEqual({ modelValue: ['staff'], options: ['staff', 'ops'] }) + }) + + it('defaults to add only and no groups for missing or unknown values', async () => { + api.getAdminSettings.mockResolvedValue({ data: { data: { defaultSharePermissionLevel: 'odd', forcedShareGroups: 'x' } } }) + const wrapper = mountWith(DashboardSharingPolicy) + await flushPromises() + + expect(wrapper.vm.defaultPermission).toEqual({ id: 'add_only', label: 'Add only' }) + expect(wrapper.vm.forcedGroups).toEqual([]) + }) + + it('keeps the defaults and logs when loading fails', async () => { + api.getAdminSettings.mockRejectedValue(new Error('x')) + const wrapper = mountWith(DashboardSharingPolicy) + await flushPromises() + expect(wrapper.vm.defaultPermission.id).toBe('add_only') + expect(logger.error).toHaveBeenCalledWith('Failed to load sharing policy:', expect.any(Error)) + }) + + it('saves the level id and groups on every change', async () => { + api.getAdminSettings.mockResolvedValue({ data: {} }) + const wrapper = mountWith(DashboardSharingPolicy, { groups: ['a', 'b'] }) + await flushPromises() + + wrapper.findComponent(SelectStub).vm.$emit('update:modelValue', { id: 'view_only', label: 'View only' }) + await flushPromises() + wrapper.findComponent(TagsStub).vm.$emit('update:modelValue', ['b']) + await flushPromises() + + expect(api.updateAdminSettings.mock.calls).toEqual([ + [{ defaultSharePermissionLevel: 'view_only', forcedShareGroups: [] }], + [{ defaultSharePermissionLevel: 'view_only', forcedShareGroups: ['b'] }], + ]) + }) + + it('logs a failed save', async () => { + api.getAdminSettings.mockResolvedValue({ data: {} }) + api.updateAdminSettings.mockRejectedValue(new Error('x')) + const wrapper = mountWith(DashboardSharingPolicy) + await flushPromises() + + await wrapper.vm.save() + expect(logger.error).toHaveBeenCalledWith('Failed to save sharing policy:', expect.any(Error)) + }) +}) + +describe('AnnouncementEditorsPolicy', () => { + it('loads the stored editor groups and offers the given groups', async () => { + api.getAdminSettings.mockResolvedValue({ data: { data: { announcementEditorGroups: ['communicatie'] } } }) + const wrapper = mountWith(AnnouncementEditorsPolicy, { groups: ['communicatie', 'hr'] }) + await flushPromises() + + expect(wrapper.findComponent(TagsStub).props()).toEqual({ modelValue: ['communicatie'], options: ['communicatie', 'hr'] }) + }) + + it('reads a stored value that is not a list as no groups', async () => { + api.getAdminSettings.mockResolvedValue({ data: { announcementEditorGroups: 'hr' } }) + const wrapper = mountWith(AnnouncementEditorsPolicy) + await flushPromises() + + expect(wrapper.vm.editorGroups).toEqual([]) + }) + + it('saves the chosen groups on every change', async () => { + api.getAdminSettings.mockResolvedValue({ data: {} }) + const wrapper = mountWith(AnnouncementEditorsPolicy, { groups: ['a', 'b'] }) + await flushPromises() + + wrapper.findComponent(TagsStub).vm.$emit('update:modelValue', ['b']) + await flushPromises() + + expect(api.updateAdminSettings).toHaveBeenCalledWith({ announcementEditorGroups: ['b'] }) + }) + + it('logs a failed load and a failed save', async () => { + api.getAdminSettings.mockRejectedValue(new Error('x')) + api.updateAdminSettings.mockRejectedValue(new Error('y')) + const wrapper = mountWith(AnnouncementEditorsPolicy) + await flushPromises() + await wrapper.vm.save() + + expect(logger.error).toHaveBeenCalledWith('Failed to load announcement editors:', expect.any(Error)) + expect(logger.error).toHaveBeenCalledWith('Failed to save announcement editors:', expect.any(Error)) + }) +}) + +describe('DashboardSharingPolicy sharing limits (REQ-SHARE-014)', () => { + const scope = (wrapper) => wrapper.find('[data-test="sharing-policy-recipient-scope"]').findComponent(SelectStub) + const allowed = (wrapper) => wrapper.find('[data-test="sharing-policy-allowed-groups"]').findComponent(TagsStub) + + it('loads the allowed groups and the recipient scope', async () => { + api.getAdminSettings.mockResolvedValue({ + data: { sharingAllowedGroups: ['communicatie'], sharingRecipientScope: 'shared-groups' }, + }) + const wrapper = mountWith(DashboardSharingPolicy, { groups: ['communicatie', 'staff'] }) + await flushPromises() + + expect(wrapper.vm.allowedGroups).toEqual(['communicatie']) + expect(wrapper.vm.recipientScope).toEqual({ id: 'shared-groups', label: 'Only people who share a group with the sharer' }) + }) + + it('reads missing or unknown values as everyone may share with anyone', async () => { + api.getAdminSettings.mockResolvedValue({ data: { sharingAllowedGroups: 'x', sharingRecipientScope: 'odd' } }) + const wrapper = mountWith(DashboardSharingPolicy) + await flushPromises() + + expect(wrapper.vm.allowedGroups).toEqual([]) + expect(wrapper.vm.recipientScope.id).toBe('everyone') + }) + + it('saves only the two limits when either changes', async () => { + api.getAdminSettings.mockResolvedValue({ data: {} }) + const wrapper = mountWith(DashboardSharingPolicy, { groups: ['a', 'b'] }) + await flushPromises() + api.updateAdminSettings.mockClear() + // REQ-SHARE-015: the group picker shows under Only these groups. + wrapper.vm.sharingAllowed = 'groups' + await flushPromises() + + wrapper.vm.allowedGroups = ['a'] + allowed(wrapper).vm.$emit('update:modelValue', ['a']) + await flushPromises() + wrapper.vm.recipientScope = wrapper.vm.scopeOptions[1] + scope(wrapper).vm.$emit('update:modelValue', wrapper.vm.scopeOptions[1]) + await flushPromises() + + expect(api.updateAdminSettings.mock.calls).toEqual([ + [{ sharingAllowedGroups: ['a'], sharingRecipientScope: 'everyone' }], + [{ sharingAllowedGroups: ['a'], sharingRecipientScope: 'shared-groups' }], + ]) + }) + + it('logs a failed save of the limits', async () => { + api.getAdminSettings.mockResolvedValue({ data: {} }) + api.updateAdminSettings.mockRejectedValue(new Error('x')) + const wrapper = mountWith(DashboardSharingPolicy) + await flushPromises() + + await wrapper.vm.saveLimits() + expect(logger.error).toHaveBeenCalledWith('Failed to save sharing limits:', expect.any(Error)) + }) +}) + diff --git a/src/components/admin/__tests__/fixtures/DashboardBulkOperations.golden.json b/src/components/admin/__tests__/fixtures/DashboardBulkOperations.golden.json new file mode 100644 index 000000000..8b555d6e9 --- /dev/null +++ b/src/components/admin/__tests__/fixtures/DashboardBulkOperations.golden.json @@ -0,0 +1,194 @@ +{ + "delete / plain / deleted": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":2,"skipped":1,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / moved": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":3,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / updated": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":4,"skipped":0,"errors":[{"uuid":"b","error":"x"}]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / reindexed": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":5,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / wouldDelete": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":6,"skipped":2,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / plain / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / plain / wouldUpdate": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":8,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / plain / wouldReindex": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":9,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / plain / nullFirst": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":4,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / zeroFirst": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / allCounts": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":1,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / laterCounts": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":3,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / movedAndUpdated": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":2,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / falsyData": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / emptyData": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / nullData": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / noData": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / undefinedResponse": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / dryRunFalse": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":1,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "delete / plain / fails serverError": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Server said no","selectedUuids":["a","b"],"reloads":0}, + "delete / plain / fails emptyError": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "delete / plain / fails noResponse": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "delete / plain / fails nothing": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "delete / dryRun / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / parentEmpty / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / parentBlank / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / parentPadded / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / parentDryRun / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / statusDraft / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / statusScheduled / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / statusScheduledDryRun / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "delete / statusPublishAtIgnored / wouldMove": {"calls":[{"name":"bulkDeleteDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / plain / deleted": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":2,"skipped":1,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / moved": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":3,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / updated": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":4,"skipped":0,"errors":[{"uuid":"b","error":"x"}]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / reindexed": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":5,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / wouldDelete": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":6,"skipped":2,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / plain / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / plain / wouldUpdate": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":8,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / plain / wouldReindex": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":9,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / plain / nullFirst": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":4,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / zeroFirst": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / allCounts": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":1,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / laterCounts": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":3,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / movedAndUpdated": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":2,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / falsyData": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / emptyData": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / nullData": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / noData": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / undefinedResponse": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / dryRunFalse": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":1,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "move / plain / fails serverError": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Server said no","selectedUuids":["a","b"],"reloads":0}, + "move / plain / fails emptyError": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "move / plain / fails noResponse": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "move / plain / fails nothing": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "move / dryRun / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / parentEmpty / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / parentBlank / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / parentPadded / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],"parent-1",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / parentDryRun / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],"p2",{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / statusDraft / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / statusScheduled / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / statusScheduledDryRun / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "move / statusPublishAtIgnored / wouldMove": {"calls":[{"name":"bulkMoveDashboards","args":[["a","b"],null,{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / plain / deleted": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":2,"skipped":1,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / moved": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":3,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / updated": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":4,"skipped":0,"errors":[{"uuid":"b","error":"x"}]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / reindexed": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":5,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / wouldDelete": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":6,"skipped":2,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / plain / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / plain / wouldUpdate": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":8,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / plain / wouldReindex": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":9,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / plain / nullFirst": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":4,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / zeroFirst": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / allCounts": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":1,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / laterCounts": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":3,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / movedAndUpdated": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":2,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / falsyData": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / emptyData": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / nullData": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / noData": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / undefinedResponse": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / dryRunFalse": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":1,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "status / plain / fails serverError": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Server said no","selectedUuids":["a","b"],"reloads":0}, + "status / plain / fails emptyError": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "status / plain / fails noResponse": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "status / plain / fails nothing": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "status / dryRun / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / parentEmpty / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / parentBlank / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / parentPadded / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / parentDryRun / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / statusDraft / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"draft",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / statusScheduled / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"scheduled",{"dryRun":false,"publishAt":"2026-12-01T10:00"}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / statusScheduledDryRun / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"scheduled",{"dryRun":true,"publishAt":""}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "status / statusPublishAtIgnored / wouldMove": {"calls":[{"name":"bulkStatusDashboards","args":[["a","b"],"published",{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / plain / deleted": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":2,"skipped":1,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / moved": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":3,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / updated": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":4,"skipped":0,"errors":[{"uuid":"b","error":"x"}]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / reindexed": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":5,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / wouldDelete": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":6,"skipped":2,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / plain / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / plain / wouldUpdate": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":8,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / plain / wouldReindex": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":9,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / plain / nullFirst": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":4,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / zeroFirst": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / allCounts": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":1,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / laterCounts": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":3,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / movedAndUpdated": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":2,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / falsyData": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / emptyData": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / nullData": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / noData": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / undefinedResponse": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / dryRunFalse": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":1,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "reindex / plain / fails serverError": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Server said no","selectedUuids":["a","b"],"reloads":0}, + "reindex / plain / fails emptyError": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "reindex / plain / fails noResponse": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "reindex / plain / fails nothing": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":null,"errorMessage":"Bulk operation failed","selectedUuids":["a","b"],"reloads":0}, + "reindex / dryRun / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / parentEmpty / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / parentBlank / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / parentPadded / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / parentDryRun / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / statusDraft / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / statusScheduled / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / statusScheduledDryRun / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":true}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "reindex / statusPublishAtIgnored / wouldMove": {"calls":[{"name":"bulkReindexDashboards","args":[["a","b"],{"dryRun":false}]}],"runningDuring":true,"running":false,"modal":null,"resultSummary":{"dryRun":true,"changed":7,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":["a","b"],"reloads":0}, + "other / plain / deleted": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / moved": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / updated": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / reindexed": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / wouldDelete": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / wouldUpdate": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / wouldReindex": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / nullFirst": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / zeroFirst": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / allCounts": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / laterCounts": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / movedAndUpdated": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / falsyData": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / emptyData": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / nullData": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / noData": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / undefinedResponse": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / dryRunFalse": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / fails serverError": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / fails emptyError": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / fails noResponse": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / plain / fails nothing": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / dryRun / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / parentEmpty / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / parentBlank / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / parentPadded / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / parentDryRun / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / statusDraft / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / statusScheduled / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / statusScheduledDryRun / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "other / statusPublishAtIgnored / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / deleted": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / moved": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / updated": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / reindexed": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / wouldDelete": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / wouldUpdate": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / wouldReindex": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / nullFirst": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / zeroFirst": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / allCounts": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / laterCounts": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / movedAndUpdated": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / falsyData": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / emptyData": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / nullData": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / noData": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / undefinedResponse": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / dryRunFalse": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / fails serverError": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / fails emptyError": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / fails noResponse": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / plain / fails nothing": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / dryRun / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / parentEmpty / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / parentBlank / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / parentPadded / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / parentDryRun / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / statusDraft / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / statusScheduled / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / statusScheduledDryRun / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1}, + "constructor / statusPublishAtIgnored / wouldMove": {"calls":[],"runningDuring":false,"running":false,"modal":null,"resultSummary":{"dryRun":false,"changed":0,"skipped":0,"errors":[]},"errorMessage":"","selectedUuids":[],"reloads":1} +} diff --git a/src/components/admin/__tests__/fixtures/roleSectionStyles.golden.json b/src/components/admin/__tests__/fixtures/roleSectionStyles.golden.json new file mode 100644 index 000000000..e0534a554 --- /dev/null +++ b/src/components/admin/__tests__/fixtures/roleSectionStyles.golden.json @@ -0,0 +1,122 @@ +{ + "RolePermissionsSection.vue": { + "rules": { + ".launchpad-admin__chip": { + "body": "background: var(--color-background-hover); padding: 2px 8px; border-radius: var(--border-radius); font-size: 0.85em", + "scoped": true + }, + ".launchpad-admin__chip--denied": { + "body": "background: var(--color-error); color: var(--color-primary-element-text)", + "scoped": true + }, + ".launchpad-admin__editor": { + "body": "padding: calc(var(--default-grid-baseline) * 2); display: flex; flex-direction: column; gap: var(--default-grid-baseline); min-width: 480px", + "scoped": true + }, + ".launchpad-admin__editor-actions": { + "body": "display: flex; justify-content: flex-end; gap: var(--default-grid-baseline); margin-top: var(--default-grid-baseline)", + "scoped": true + }, + ".launchpad-admin__error": { + "body": "background: var(--color-error); color: var(--color-primary-element-text); padding: var(--default-grid-baseline); border-radius: var(--border-radius); margin-bottom: var(--default-grid-baseline)", + "scoped": true + }, + ".launchpad-admin__hint": { + "body": "color: var(--color-text-maxcontrast); margin: 0 0 var(--default-grid-baseline) 0", + "scoped": true + }, + ".launchpad-admin__role-actions": { + "body": "display: flex; gap: 4px", + "scoped": true + }, + ".launchpad-admin__role-group": { + "body": "color: var(--color-text-maxcontrast); font-family: var(--font-face-monospace, monospace); font-size: 0.85em", + "scoped": true + }, + ".launchpad-admin__role-list": { + "body": "display: flex; flex-direction: column; gap: var(--default-grid-baseline); margin-bottom: var(--default-grid-baseline)", + "scoped": true + }, + ".launchpad-admin__role-meta": { + "body": "display: flex; flex-direction: column; min-width: 200px", + "scoped": true + }, + ".launchpad-admin__role-row": { + "body": "display: flex; align-items: center; gap: var(--default-grid-baseline); padding: var(--default-grid-baseline); border: 1px solid var(--color-border); border-radius: var(--border-radius)", + "scoped": true + }, + ".launchpad-admin__role-widgets": { + "body": "flex: 1; display: flex; flex-wrap: wrap; gap: 4px", + "scoped": true + } + }, + "count": 12, + "order": [ + ".launchpad-admin__chip before .launchpad-admin__chip--denied", + ".launchpad-admin__editor before .launchpad-admin__editor-actions" + ] + }, + "RoleLayoutDefaultsSection.vue": { + "rules": { + ".launchpad-admin__chip": { + "body": "background: var(--color-background-hover); padding: 2px 8px; border-radius: var(--border-radius); font-size: 0.85em", + "scoped": true + }, + ".launchpad-admin__chip--compulsory": { + "body": "background: var(--color-warning)", + "scoped": true + }, + ".launchpad-admin__editor": { + "body": "padding: calc(var(--default-grid-baseline) * 2); display: flex; flex-direction: column; gap: var(--default-grid-baseline); min-width: 480px", + "scoped": true + }, + ".launchpad-admin__editor-row > *": { + "body": "flex: 1", + "scoped": true + }, + ".launchpad-admin__editor-row": { + "body": "display: flex; gap: var(--default-grid-baseline)", + "scoped": true + }, + ".launchpad-admin__error": { + "body": "background: var(--color-error); color: var(--color-primary-element-text); padding: var(--default-grid-baseline); border-radius: var(--border-radius); margin-bottom: var(--default-grid-baseline)", + "scoped": true + }, + ".launchpad-admin__hint": { + "body": "color: var(--color-text-maxcontrast); margin: 0 0 var(--default-grid-baseline) 0", + "scoped": true + }, + ".launchpad-admin__role-actions": { + "body": "display: flex; gap: 4px", + "scoped": true + }, + ".launchpad-admin__role-group": { + "body": "color: var(--color-text-maxcontrast); font-family: var(--font-face-monospace, monospace); font-size: 0.85em", + "scoped": true + }, + ".launchpad-admin__role-list": { + "body": "display: flex; flex-direction: column; gap: var(--default-grid-baseline); margin-bottom: var(--default-grid-baseline)", + "scoped": true + }, + ".launchpad-admin__role-meta": { + "body": "display: flex; flex-direction: column; min-width: 200px", + "scoped": true + }, + ".launchpad-admin__role-row": { + "body": "display: flex; align-items: center; gap: var(--default-grid-baseline); padding: var(--default-grid-baseline); border: 1px solid var(--color-border); border-radius: var(--border-radius)", + "scoped": true + }, + ".launchpad-admin__role-widgets": { + "body": "flex: 1; display: flex; flex-wrap: wrap; gap: 4px", + "scoped": true + } + }, + "count": 13, + "order": [ + ".launchpad-admin__chip before .launchpad-admin__chip--compulsory", + ".launchpad-admin__editor before .launchpad-admin__editor-row", + ".launchpad-admin__editor before .launchpad-admin__editor-row > *", + ".launchpad-admin__editor-row before .launchpad-admin__editor-row > *" + ] + } +} diff --git a/src/components/admin/__tests__/roleSectionStyles.golden.spec.js b/src/components/admin/__tests__/roleSectionStyles.golden.spec.js new file mode 100644 index 000000000..f46ff6d48 --- /dev/null +++ b/src/components/admin/__tests__/roleSectionStyles.golden.spec.js @@ -0,0 +1,114 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for the styles of RolePermissionsSection and + * RoleLayoutDefaultsSection: every rule each component gets from its style + * blocks (a `src` block read from its file), whether the block is scoped, + * and for each selector that extends another (`.a` and `.a--b`) which comes + * first, compared with fixtures/roleSectionStyles.golden.json. + * Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it } from 'vitest' + +const FIXTURE = path.resolve(__dirname, 'fixtures/roleSectionStyles.golden.json') +const ADMIN = path.resolve(__dirname, '..') +const COMPONENTS = ['RolePermissionsSection.vue', 'RoleLayoutDefaultsSection.vue'] + +/** + * The style blocks of a single-file component, in order, `src` blocks read + * from their file. + * + * @param {string} file The component file name. + * @return {Array<{scoped: boolean, css: string}>} The blocks. + */ +function styleBlocks(file) { + const source = fs.readFileSync(path.join(ADMIN, file), 'utf8') + const blocks = [] + for (const match of source.matchAll(/<style([^>]*)>([\s\S]*?)<\/style>/g)) { + const attrs = match[1] + const src = /src="([^"]+)"/.exec(attrs) + blocks.push({ + scoped: /\bscoped\b/.test(attrs), + css: src ? fs.readFileSync(path.join(ADMIN, src[1]), 'utf8') : match[2], + }) + } + return blocks +} + +/** + * The rules of a stylesheet as selector and normalised declarations. + * + * @param {string} css The stylesheet. + * @return {Array<Array<string>>} Pairs of selector and declarations. + */ +function rules(css) { + const out = [] + const text = css.replace(/\/\*[\s\S]*?\*\//g, '') + for (const match of text.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { + const declarations = match[2] + .split(';') + .map((d) => d.trim().replace(/\s+/g, ' ')) + .filter(Boolean) + .join('; ') + out.push([match[1].trim().replace(/\s+/g, ' '), declarations]) + } + return out +} + +/** + * What one component gets: its rules by selector, the scoped flags, and the + * order of selectors that extend one another. + * + * @param {string} file The component file name. + * @return {object} The contract. + */ +function contract(file) { + const blocks = styleBlocks(file) + const all = blocks.flatMap((block) => + rules(block.css).map(([selector, body]) => ({ + selector, + body, + scoped: block.scoped, + })), + ) + const bySelector = {} + for (const rule of all) { + bySelector[rule.selector] = { body: rule.body, scoped: rule.scoped } + } + const selectors = all.map((rule) => rule.selector) + const order = [] + for (const base of selectors) { + for (const extended of selectors) { + if (extended !== base && extended.startsWith(base)) { + order.push( + `${base} ${selectors.indexOf(base) < selectors.indexOf(extended) ? 'before' : 'after'} ${extended}`, + ) + } + } + } + return { + rules: Object.fromEntries(Object.entries(bySelector).sort()), + count: all.length, + order: order.sort(), + } +} + +describe('admin role section styles (golden)', () => { + it('matches the recorded rules case by case', () => { + const actual = Object.fromEntries( + COMPONENTS.map((file) => [file, contract(file)]), + ) + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const [name, value] of Object.entries(expected)) { + expect(actual[name], name).toEqual(value) + } + }) +}) diff --git a/src/components/admin/embed/EmbedTokenForm.vue b/src/components/admin/embed/EmbedTokenForm.vue new file mode 100644 index 000000000..954c6b6a1 --- /dev/null +++ b/src/components/admin/embed/EmbedTokenForm.vue @@ -0,0 +1,469 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <form class="embed-token-form" data-test="embed-token-form" @submit.prevent="submit"> + <NcTextField + v-model="form.name" + :label="t('launchpad', 'Name')" + :error="errors.name !== ''" + :helperText="errors.name" + required + data-test="embed-token-name" /> + <NcTextArea + v-model="form.description" + :label="t('launchpad', 'Description')" + data-test="embed-token-description" /> + + <template v-if="!editing"> + <fieldset class="embed-token-form__group"> + <legend>{{ t('launchpad', 'What to embed') }}</legend> + <NcCheckboxRadioSwitch + v-for="option in subjectTypes" + :key="option.id" + v-model="form.subjectType" + type="radio" + name="embed-subject-type" + :value="option.id" + :data-test="`embed-subject-type-${option.id}`"> + {{ option.label }} + </NcCheckboxRadioSwitch> + <NcSelect + :modelValue="selectedDashboard" + :inputLabel="t('launchpad', 'Dashboard')" + :options="dashboards" + label="name" + trackBy="id" + :clearable="false" + data-test="embed-subject-dashboard" + @update:modelValue="pickDashboard" /> + <NcSelect + v-if="form.subjectType === 'widget'" + :modelValue="selectedPlacement" + :inputLabel="t('launchpad', 'Widget')" + :options="placementOptions" + :loading="loadingPlacements" + :disabled="form.dashboardId === null" + label="label" + trackBy="id" + :clearable="false" + data-test="embed-subject-widget" + @update:modelValue="form.subjectId = $event ? String($event.id) : ''" /> + <p v-if="errors.subject !== ''" class="embed-token-form__error" role="alert"> + {{ errors.subject }} + </p> + <NcTextArea + v-if="form.subjectType === 'dashboard'" + v-model="form.filterContext" + :label="t('launchpad', 'Pinned filters, one dimension=value per line')" + data-test="embed-token-filter-context" /> + </fieldset> + + <fieldset class="embed-token-form__group"> + <legend>{{ t('launchpad', 'Scope') }}</legend> + <NcCheckboxRadioSwitch + v-for="option in modes" + :key="option.id" + v-model="form.mode" + type="radio" + name="embed-scope-mode" + :value="option.id" + :data-test="`embed-scope-mode-${option.id}`"> + {{ option.label }} + </NcCheckboxRadioSwitch> + <template v-if="form.mode === 'read-with-interactions'"> + <NcCheckboxRadioSwitch + v-for="option in actions" + :key="option.id" + v-model="form.allowedActions" + type="checkbox" + :value="option.id" + :data-test="`embed-scope-action-${option.id}`"> + {{ option.label }} + </NcCheckboxRadioSwitch> + <NcTextField + v-model="form.allowedFilters" + :label="t('launchpad', 'Filters viewers may change, comma-separated')" + data-test="embed-token-allowed-filters" /> + </template> + </fieldset> + + <fieldset class="embed-token-form__group"> + <legend>{{ t('launchpad', 'Sites that may embed it') }}</legend> + <ul class="embed-token-form__origins" data-test="embed-token-origins"> + <li v-for="origin in form.hostOrigins" :key="origin"> + <code>{{ origin }}</code> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove {origin}', { origin })" + @click="removeOrigin(origin)"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </li> + </ul> + <div class="embed-token-form__add-origin"> + <NcTextField + v-model="newOrigin" + :label="t('launchpad', 'Origin, e.g. https://www.example.com')" + :error="errors.hostOrigins !== ''" + :helperText="errors.hostOrigins" + data-test="embed-token-new-origin" + @keydown.enter.prevent="addOrigin" /> + <NcButton data-test="embed-token-add-origin" @click="addOrigin"> + {{ t('launchpad', 'Add') }} + </NcButton> + </div> + <NcButton variant="tertiary" data-test="embed-token-csp-toggle" @click="showCsp = !showCsp"> + {{ showCsp ? t('launchpad', 'Hide CSP header') : t('launchpad', 'Preview CSP header') }} + </NcButton> + <pre v-if="showCsp" class="embed-token-form__csp" data-test="embed-token-csp">Content-Security-Policy: {{ csp }}</pre> + </fieldset> + + <NcSelect + :modelValue="selectedTheme" + :inputLabel="t('launchpad', 'Theme')" + :options="themeOptions" + label="name" + trackBy="id" + :clearable="false" + data-test="embed-token-theme" + @update:modelValue="form.tenantThemeId = $event && $event.id !== '' ? $event.id : null" /> + <NcTextField + v-model="form.tokenExpiresAt" + type="date" + :label="t('launchpad', 'Expires on (optional)')" + data-test="embed-token-expires" /> + </template> + + <fieldset class="embed-token-form__group"> + <legend>{{ t('launchpad', 'Rate limit') }}</legend> + <p class="embed-token-form__hint"> + {{ t('launchpad', 'Leave empty to use the organisation default.') }} + </p> + <NcTextField + v-model="form.requestsPerMinute" + type="number" + min="1" + :label="t('launchpad', 'Requests per minute')" + data-test="embed-token-rpm" /> + <NcTextField + v-model="form.burstSize" + type="number" + min="1" + :label="t('launchpad', 'Burst size')" + data-test="embed-token-burst" /> + </fieldset> + + <div class="embed-token-form__actions"> + <NcButton data-test="embed-token-cancel" @click="$emit('cancel')"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + type="submit" + variant="primary" + :disabled="saving" + data-test="embed-token-submit"> + {{ editing ? t('launchpad', 'Save') : t('launchpad', 'Create token') }} + </NcButton> + </div> + </form> +</template> + +<script> +import { NcButton, NcCheckboxRadioSwitch, NcSelect, NcTextArea, NcTextField } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { api } from '../../../services/api.js' +import { + createPayload, + cspPreview, + formFromToken, + normaliseOrigin, + originProblem, + updatePayload, +} from '../../../utils/embedToken.js' +import { logger } from '../../../utils/logger.js' + +/** + * EmbedTokenForm — the create and edit form of an embed token + * (embedded-analytics task 18). Creating asks for the subject, scope, host + * origins, theme, expiry and rate limit; editing a stored token only offers + * what may change after issue (name, description, rate limit). Emits the + * payload; the manager sends it. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-18 + */ +export default { + name: 'EmbedTokenForm', + + components: { + NcButton, + NcCheckboxRadioSwitch, + NcSelect, + NcTextArea, + NcTextField, + }, + + props: { + /** The stored token to edit; null to create one. */ + token: { + type: Object, + default: null, + }, + + /** The dashboards a token can embed: {id, uuid, name}. */ + dashboards: { + type: Array, + default: () => [], + }, + + /** The tenant themes: {id, name}. */ + themes: { + type: Array, + default: () => [], + }, + + /** Pre-selected subject of a new token: {subjectType, subjectId, dashboardId}. */ + defaults: { + type: Object, + default: () => ({}), + }, + + /** Whether the manager is saving. */ + saving: { + type: Boolean, + default: false, + }, + }, + + emits: ['submit', 'cancel'], + + data() { + return { + form: formFromToken(this.token, this.defaults), + placements: [], + loadingPlacements: false, + newOrigin: '', + showCsp: false, + errors: { name: '', subject: '', hostOrigins: '' }, + } + }, + + computed: { + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + editing() { + return this.token !== null + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + subjectTypes() { + return [ + { id: 'dashboard', label: t('launchpad', 'A dashboard') }, + { id: 'widget', label: t('launchpad', 'One widget') }, + ] + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + modes() { + return [ + { id: 'read', label: t('launchpad', 'Read only') }, + { id: 'read-with-interactions', label: t('launchpad', 'Read with interactions') }, + ] + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + actions() { + return [ + { id: 'interact', label: t('launchpad', 'Change filters') }, + { id: 'drillDown', label: t('launchpad', 'Drill down') }, + { id: 'export', label: t('launchpad', 'Export data') }, + ] + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + selectedDashboard() { + return this.dashboards.find((dashboard) => dashboard.id === this.form.dashboardId) ?? null + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + placementOptions() { + return this.placements.map((placement) => ({ + id: placement.id, + label: placement.customTitle || placement.tileTitle || `${placement.widgetId} #${placement.id}`, + })) + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + selectedPlacement() { + return this.placementOptions.find((option) => String(option.id) === String(this.form.subjectId)) ?? null + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + themeOptions() { + return [{ id: '', name: t('launchpad', 'Default theme') }, ...this.themes] + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + selectedTheme() { + return this.themeOptions.find((theme) => theme.id === (this.form.tenantThemeId ?? '')) ?? this.themeOptions[0] + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + csp() { + return cspPreview(this.form.hostOrigins) + }, + }, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-18 */ + created() { + if (this.form.subjectType === 'widget' && this.form.dashboardId !== null) { + this.loadPlacements(this.form.dashboardId) + } + }, + + methods: { + t, + + /** + * Choose a dashboard: the subject of a dashboard token, the source of a widget token's placements. + * + * @param {object|null} dashboard The dashboard. + * @spec openspec/changes/embedded-analytics/tasks.md#task-18 + */ + pickDashboard(dashboard) { + this.form.dashboardId = dashboard?.id ?? null + this.form.subjectId = this.form.subjectType === 'dashboard' ? (dashboard?.uuid ?? '') : '' + if (this.form.subjectType === 'widget' && dashboard) { + this.loadPlacements(dashboard.id) + } + }, + + /** + * Load the widget placements of a dashboard. + * + * @param {number|string} dashboardId The dashboard's numeric id. + * @spec openspec/changes/embedded-analytics/tasks.md#task-18 + */ + async loadPlacements(dashboardId) { + this.loadingPlacements = true + try { + const { data } = await api.getDashboardById(dashboardId) + this.placements = Array.isArray(data?.placements) ? data.placements : [] + } catch (error) { + this.placements = [] + logger.error('Failed to load the widgets of the dashboard:', error) + } finally { + this.loadingPlacements = false + } + }, + + /** + * Add the typed origin when the server would accept it. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-003--csp-frame-ancestors-enforced-from-token-hostorigins + */ + addOrigin() { + const problem = originProblem(this.newOrigin) + if (problem === 'wildcard') { + this.errors.hostOrigins = t('launchpad', 'Wildcards are not allowed; list each site.') + return + } + if (problem === 'invalid') { + this.errors.hostOrigins = t('launchpad', 'An origin is a scheme and a host, e.g. https://www.example.com, without a path.') + return + } + const origin = normaliseOrigin(this.newOrigin) + if (!this.form.hostOrigins.includes(origin)) { + this.form.hostOrigins.push(origin) + } + this.newOrigin = '' + this.errors.hostOrigins = '' + }, + + /** + * Remove an origin. + * + * @param {string} origin The origin. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + removeOrigin(origin) { + this.form.hostOrigins = this.form.hostOrigins.filter((item) => item !== origin) + }, + + /** + * Check the form and emit its payload. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-18 + */ + submit() { + this.errors = { + name: this.form.name.trim() === '' ? t('launchpad', 'Give the token a name.') : '', + subject: !this.editing && this.form.subjectId === '' ? t('launchpad', 'Choose what to embed.') : '', + hostOrigins: !this.editing && this.form.hostOrigins.length === 0 ? t('launchpad', 'Add at least one site that may embed it.') : '', + } + if (Object.values(this.errors).some((message) => message !== '')) { + return + } + this.$emit('submit', this.editing ? updatePayload(this.form) : createPayload(this.form)) + }, + }, +} +</script> + +<style scoped> +.embed-token-form { + display: flex; + flex-direction: column; + gap: 12px; + max-width: 640px; +} + +.embed-token-form__group { + display: flex; + flex-direction: column; + gap: 8px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); + padding: 12px; +} + +.embed-token-form__group legend { + font-weight: bold; + padding: 0 4px; +} + +.embed-token-form__origins { + display: flex; + flex-direction: column; + gap: 4px; +} + +.embed-token-form__origins li, +.embed-token-form__add-origin, +.embed-token-form__actions { + display: flex; + align-items: center; + gap: 8px; +} + +.embed-token-form__actions { + justify-content: flex-end; +} + +.embed-token-form__csp { + background: var(--color-background-dark); + border-radius: var(--border-radius); + padding: 8px; + white-space: pre-wrap; + word-break: break-all; +} + +.embed-token-form__hint { + color: var(--color-text-maxcontrast); +} + +.embed-token-form__error { + color: var(--color-error-text); +} +</style> diff --git a/src/components/admin/embed/EmbedTokenManager.vue b/src/components/admin/embed/EmbedTokenManager.vue new file mode 100644 index 000000000..e5ec56094 --- /dev/null +++ b/src/components/admin/embed/EmbedTokenManager.vue @@ -0,0 +1,513 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <section class="embed-token-manager" data-test="embed-token-manager"> + <h3>{{ t('launchpad', 'Embed tokens') }}</h3> + + <NcNoteCard v-if="issued" type="warning" data-test="embed-token-issued"> + <p>{{ t('launchpad', 'Copy this token now. It is shown only once and cannot be retrieved later; keep it safe.') }}</p> + <code class="embed-token-manager__jwt" data-test="embed-token-jwt">{{ issued.jwt }}</code> + <div class="embed-token-manager__row"> + <NcButton data-test="embed-token-copy" @click="copyJwt"> + {{ copied ? t('launchpad', 'Copied') : t('launchpad', 'Copy') }} + </NcButton> + <NcButton variant="tertiary" data-test="embed-token-issued-done" @click="issued = null"> + {{ t('launchpad', 'Done') }} + </NcButton> + </div> + </NcNoteCard> + + <NcNoteCard v-if="error !== ''" type="error" data-test="embed-token-error"> + {{ error }} + </NcNoteCard> + + <EmbedTokenForm + v-if="view === 'create' || view === 'edit'" + :key="view + (selected ? selected.id : '')" + :token="view === 'edit' ? selected : null" + :dashboards="dashboards" + :themes="themes" + :defaults="defaults" + :saving="saving" + @submit="save" + @cancel="view = selected ? 'detail' : 'list'" /> + + <div v-else-if="view === 'detail' && selected" class="embed-token-manager__detail" data-test="embed-token-detail"> + <NcButton variant="tertiary" data-test="embed-token-back" @click="backToList"> + {{ t('launchpad', 'Back to all tokens') }} + </NcButton> + <h4>{{ selected.name }}</h4> + <dl class="embed-token-manager__facts"> + <dt>{{ t('launchpad', 'Status') }}</dt> + <dd :data-test="'embed-token-status-' + statusOf(selected)"> + {{ statusLabel(selected) }} + </dd> + <dt>{{ t('launchpad', 'Embeds') }}</dt> + <dd>{{ subjectLabel(selected) }}</dd> + <dt>{{ t('launchpad', 'Scope') }}</dt> + <dd>{{ scopeLabel(selected) }}</dd> + <dt>{{ t('launchpad', 'Sites') }}</dt> + <dd>{{ (selected.hostOrigins || []).join(', ') }}</dd> + <dt>{{ t('launchpad', 'Expires') }}</dt> + <dd>{{ selected.tokenExpiresAt || t('launchpad', 'Never') }}</dd> + <dt>{{ t('launchpad', 'Created') }}</dt> + <dd>{{ selected.createdAt }}</dd> + <template v-if="selected.revokedAt"> + <dt>{{ t('launchpad', 'Revoked') }}</dt> + <dd>{{ selected.revokedAt }} ({{ selected.revocationReason }})</dd> + </template> + </dl> + <div class="embed-token-manager__row"> + <NcButton data-test="embed-token-edit" @click="view = 'edit'"> + {{ t('launchpad', 'Edit') }} + </NcButton> + <NcButton data-test="embed-token-reissue" :disabled="saving" @click="reissue(selected)"> + {{ t('launchpad', 'Re-issue') }} + </NcButton> + <NcButton + v-if="!selected.revokedAt" + variant="error" + data-test="embed-token-revoke" + @click="revoking = selected"> + {{ t('launchpad', 'Revoke') }} + </NcButton> + <NcButton + v-else + data-test="embed-token-unrevoke" + :disabled="saving" + @click="unrevoke(selected)"> + {{ t('launchpad', 'Restore') }} + </NcButton> + </div> + <EmbedUsageReport :key="'usage-' + selected.id" :tokenId="selected.id" :tokenName="selected.name" /> + </div> + + <template v-else> + <div class="embed-token-manager__row"> + <NcButton variant="primary" data-test="embed-token-new" @click="startCreate"> + {{ t('launchpad', 'New embed token') }} + </NcButton> + </div> + <NcLoadingIcon v-if="loading" /> + <p v-else-if="tokens.length === 0" class="embed-token-manager__empty" data-test="embed-token-empty"> + {{ t('launchpad', 'No embed tokens yet.') }} + </p> + <table v-else class="embed-token-manager__table" data-test="embed-token-table"> + <thead> + <tr> + <th scope="col">{{ t('launchpad', 'Name') }}</th> + <th scope="col">{{ t('launchpad', 'Status') }}</th> + <th scope="col">{{ t('launchpad', 'Embeds') }}</th> + <th scope="col">{{ t('launchpad', 'Created') }}</th> + <th scope="col">{{ t('launchpad', 'Revoked') }}</th> + <th scope="col"><span class="hidden-visually">{{ t('launchpad', 'Actions') }}</span></th> + </tr> + </thead> + <tbody> + <tr v-for="token in tokens" :key="token.id" :data-test="'embed-token-row-' + token.id"> + <td>{{ token.name }}</td> + <td> + <span :class="'embed-token-manager__status--' + statusOf(token)">{{ statusLabel(token) }}</span> + </td> + <td>{{ subjectLabel(token) }}</td> + <td>{{ token.createdAt }}</td> + <td>{{ token.revokedAt || '' }}</td> + <td> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Open {name}', { name: token.name })" + :data-test="'embed-token-open-' + token.id" + @click="open(token)"> + {{ t('launchpad', 'Open') }} + </NcButton> + </td> + </tr> + </tbody> + </table> + </template> + + <RevokeEmbedTokenDialog + v-if="revoking" + :open="true" + :name="revoking.name" + @update:open="revoking = $event ? revoking : null" + @confirm="revoke" /> + </section> +</template> + +<script> +import { NcButton, NcLoadingIcon, NcNoteCard } from '@conduction/nextcloud-vue' +import { showSuccess } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' +import RevokeEmbedTokenDialog from '../../../dialogs/RevokeEmbedTokenDialog.vue' +import EmbedTokenForm from './EmbedTokenForm.vue' +import EmbedUsageReport from './EmbedUsageReport.vue' +import { api } from '../../../services/api.js' +import { embedApi } from '../../../services/embedApi.js' +import { tokenStatus } from '../../../utils/embedToken.js' +import { logger } from '../../../utils/logger.js' + +/** + * EmbedTokenManager — Beheer ▸ Embeds: every embed token, issuing one (the + * JWT shown once with a copy button), its details with edit, re-issue, + * revoke and restore, and its usage report (embedded-analytics tasks 15 and + * 27). Opened from a dashboard or widget with `defaults`, it starts on the + * create form for that subject (task 40). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + * @spec openspec/changes/embedded-analytics/tasks.md#task-27 + */ +export default { + name: 'EmbedTokenManager', + + components: { + EmbedTokenForm, + EmbedUsageReport, + NcButton, + NcLoadingIcon, + NcNoteCard, + RevokeEmbedTokenDialog, + }, + + props: { + /** Subject to pre-select and open the create form for: {subjectType, subjectId, dashboardId}. */ + defaults: { + type: Object, + default: () => ({}), + }, + }, + + data() { + return { + tokens: [], + dashboards: [], + themes: [], + loading: true, + saving: false, + view: this.defaults?.subjectId ? 'create' : 'list', + selected: null, + issued: null, + copied: false, + revoking: null, + error: '', + } + }, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-15 */ + created() { + this.load() + }, + + methods: { + t, + + /** + * Load the tokens, and the dashboards and themes the form offers. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + */ + async load() { + this.loading = true + this.error = '' + const [tokens, dashboards, themes] = await Promise.allSettled([ + embedApi.listTokens(), + api.getVisibleDashboards(), + embedApi.listThemes(), + ]) + if (tokens.status === 'fulfilled') { + this.tokens = tokens.value + } else { + this.error = t('launchpad', 'Embed tokens could not be loaded.') + logger.error('Failed to load embed tokens:', tokens.reason) + } + const dashboardList = dashboards.status === 'fulfilled' ? dashboards.value?.data : null + this.dashboards = (Array.isArray(dashboardList) ? dashboardList : (dashboardList?.items ?? dashboardList?.results ?? [])) + .map((dashboard) => ({ id: dashboard.id, uuid: dashboard.uuid, name: dashboard.name })) + this.themes = themes.status === 'fulfilled' ? themes.value.map((theme) => ({ id: theme.id, name: theme.name })) : [] + this.loading = false + }, + + /** + * Open the create form. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + startCreate() { + this.selected = null + this.view = 'create' + }, + + /** + * Show a token's details. + * + * @param {object} token The token. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + open(token) { + this.selected = token + this.view = 'detail' + }, + + /** + * Back to the list. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + backToList() { + this.selected = null + this.view = 'list' + }, + + /** + * Create or update a token from the form. + * + * @param {object} payload The form's payload. + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + */ + async save(payload) { + this.saving = true + this.error = '' + try { + if (this.view === 'edit') { + this.selected = await embedApi.updateToken(this.selected.id, payload) + this.replace(this.selected) + this.view = 'detail' + } else { + this.showIssued(await embedApi.createToken(payload)) + this.tokens = await embedApi.listTokens() + this.view = 'list' + } + } catch (error) { + this.error = this.messageOf(error, t('launchpad', 'The embed token could not be saved.')) + logger.error('Failed to save embed token:', error) + } finally { + this.saving = false + } + }, + + /** + * Re-issue a token: the old one is revoked, the new JWT shown once. + * + * @param {object} token The token. + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + */ + async reissue(token) { + this.saving = true + this.error = '' + try { + this.showIssued(await embedApi.reissueToken(token.id)) + this.tokens = await embedApi.listTokens() + this.backToList() + } catch (error) { + this.error = this.messageOf(error, t('launchpad', 'The embed token could not be re-issued.')) + logger.error('Failed to re-issue embed token:', error) + } finally { + this.saving = false + } + }, + + /** + * Revoke the token in the dialog. + * + * @param {{reason: string, notes: string}} choice The reason and notes. + * @spec openspec/changes/embedded-analytics/tasks.md#task-27 + */ + async revoke({ reason, notes }) { + const token = this.revoking + this.revoking = null + this.error = '' + try { + const updated = await embedApi.revokeToken(token.id, reason, notes) + this.replace(updated) + if (this.selected?.id === updated.id) { + this.selected = updated + } + showSuccess(t('launchpad', 'Token revoked.')) + } catch (error) { + this.error = this.messageOf(error, t('launchpad', 'The embed token could not be revoked.')) + logger.error('Failed to revoke embed token:', error) + } + }, + + /** + * Clear a token's revocation. + * + * @param {object} token The token. + * @spec openspec/changes/embedded-analytics/tasks.md#task-27 + */ + async unrevoke(token) { + this.saving = true + this.error = '' + try { + const updated = await embedApi.unrevokeToken(token.id) + this.replace(updated) + this.selected = updated + showSuccess(t('launchpad', 'Token restored.')) + } catch (error) { + this.error = this.messageOf(error, t('launchpad', 'The embed token could not be restored.')) + logger.error('Failed to restore embed token:', error) + } finally { + this.saving = false + } + }, + + /** + * Show a freshly issued JWT. + * + * @param {object} result {jwt, ...}. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + showIssued(result) { + this.issued = result + this.copied = false + }, + + /** + * Copy the issued JWT to the clipboard. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + async copyJwt() { + try { + await navigator.clipboard.writeText(this.issued.jwt) + this.copied = true + } catch (error) { + logger.error('Failed to copy the embed token:', error) + } + }, + + /** + * Put an updated token in the list. + * + * @param {object} token The token's metadata. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + replace(token) { + this.tokens = this.tokens.map((item) => (item.id === token.id ? token : item)) + }, + + /** + * The server's message of a refusal, or a fallback. + * + * @param {Error} error The failure. + * @param {string} fallback The fallback message. + * @return {string} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + messageOf(error, fallback) { + return error?.response?.data?.message || fallback + }, + + /** + * @param {object} token The token. + * @return {string} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + statusOf(token) { + return tokenStatus(token) + }, + + /** + * @param {object} token The token. + * @return {string} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + statusLabel(token) { + return { + active: t('launchpad', 'Active'), + expired: t('launchpad', 'Expired'), + revoked: t('launchpad', 'Revoked'), + }[tokenStatus(token)] + }, + + /** + * @param {object} token The token. + * @return {string} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + subjectLabel(token) { + const subject = token.subject ?? {} + if (subject.type === 'widget') { + return t('launchpad', 'Widget {id}', { id: subject.id }) + } + const dashboard = this.dashboards.find((item) => item.uuid === subject.id) + return t('launchpad', 'Dashboard {name}', { name: dashboard?.name ?? subject.id }) + }, + + /** + * @param {object} token The token. + * @return {string} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + scopeLabel(token) { + if (token.scope?.mode !== 'read-with-interactions') { + return t('launchpad', 'Read only') + } + const actions = (token.scope.allowedActions ?? []).join(', ') + return actions === '' ? t('launchpad', 'Read with interactions') : t('launchpad', 'Read with interactions: {actions}', { actions }) + }, + }, +} +</script> + +<style scoped> +.embed-token-manager { + display: flex; + flex-direction: column; + gap: 12px; +} + +.embed-token-manager__row { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.embed-token-manager__jwt { + display: block; + margin: 8px 0; + word-break: break-all; + user-select: all; +} + +.embed-token-manager__table { + width: 100%; + border-collapse: collapse; +} + +.embed-token-manager__table th, +.embed-token-manager__table td { + text-align: start; + padding: 6px 8px; + border-bottom: 1px solid var(--color-border); +} + +.embed-token-manager__status--active { + color: var(--color-success-text); +} + +.embed-token-manager__status--expired { + color: var(--color-warning-text); +} + +.embed-token-manager__status--revoked { + color: var(--color-error-text); +} + +.embed-token-manager__facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 4px 16px; +} + +.embed-token-manager__facts dt { + font-weight: bold; +} + +.embed-token-manager__empty { + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/admin/embed/EmbedUsageReport.vue b/src/components/admin/embed/EmbedUsageReport.vue new file mode 100644 index 000000000..56ca6e063 --- /dev/null +++ b/src/components/admin/embed/EmbedUsageReport.vue @@ -0,0 +1,266 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <section class="embed-usage-report" data-test="embed-usage-report"> + <h4>{{ t('launchpad', 'Usage, last {days} days', { days: report ? report.days : 7 }) }}</h4> + <NcLoadingIcon v-if="loading" /> + <NcNoteCard v-else-if="error !== ''" type="error"> + {{ error }} + </NcNoteCard> + <template v-else-if="report"> + <NcNoteCard v-if="!report.telemetryEnabled" type="info" data-test="embed-usage-disabled"> + {{ t('launchpad', 'Embed usage telemetry is off; no new usage is recorded.') }} + </NcNoteCard> + <NcNoteCard v-if="report.summary.usedAfterRevocation > 0" type="warning" data-test="embed-usage-after-revocation"> + {{ n('launchpad', '%n request arrived after the token was revoked.', '%n requests arrived after the token was revoked.', report.summary.usedAfterRevocation) }} + </NcNoteCard> + + <dl class="embed-usage-report__summary" data-test="embed-usage-summary"> + <dt>{{ t('launchpad', 'Page views') }}</dt> + <dd data-test="embed-usage-pageviews"> + {{ report.summary.pageViews }} + </dd> + <dt>{{ t('launchpad', 'Last activity') }}</dt> + <dd>{{ report.summary.lastActivity || t('launchpad', 'None') }}</dd> + <dt>{{ t('launchpad', 'Rate limited') }}</dt> + <dd data-test="embed-usage-rate-limited"> + {{ report.rateLimited }} + </dd> + </dl> + + <div + v-for="chart in charts" + :key="chart.id" + class="embed-usage-report__chart" + :data-test="'embed-usage-' + chart.id"> + <h5>{{ chart.title }}</h5> + <p v-if="chart.rows.length === 0" class="embed-usage-report__empty"> + {{ t('launchpad', 'No data') }} + </p> + <table v-else> + <caption class="hidden-visually"> + {{ chart.title }} + </caption> + <tbody> + <tr v-for="row in chart.rows" :key="row.label"> + <th scope="row"> + {{ row.label }} + </th> + <td class="embed-usage-report__bar-cell"> + <span class="embed-usage-report__bar" :style="{ width: barWidth(row.count, chart.max) }" /> + </td> + <td class="embed-usage-report__count"> + {{ row.count }} + </td> + </tr> + </tbody> + </table> + </div> + + <NcButton + v-if="report.telemetryEnabled" + data-test="embed-usage-export" + @click="exportCsv"> + {{ t('launchpad', 'Export CSV') }} + </NcButton> + </template> + </section> +</template> + +<script> +import { NcButton, NcLoadingIcon, NcNoteCard } from '@conduction/nextcloud-vue' +import { n, t } from '@nextcloud/l10n' +import { embedApi } from '../../../services/embedApi.js' +import { logger } from '../../../utils/logger.js' + +/** + * EmbedUsageReport — the aggregate usage of one embed token over the last + * seven days (embedded-analytics task 17, REQ-EMB-008): page views, last + * activity, rate-limit hits, and page views by date, host origin, viewport, + * browser and interaction as bar rows. Aggregates only: no individual + * visitor rows exist to show. The CSV export holds the same aggregates and + * is offered only while telemetry is collected. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-17 + */ +export default { + name: 'EmbedUsageReport', + + components: { + NcButton, + NcLoadingIcon, + NcNoteCard, + }, + + props: { + /** The token id. */ + tokenId: { + type: String, + required: true, + }, + + /** The token's name, for the export file name. */ + tokenName: { + type: String, + default: '', + }, + }, + + data() { + return { + report: null, + loading: true, + error: '', + } + }, + + computed: { + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + charts() { + if (!this.report) { + return [] + } + const viewports = { + small: t('launchpad', 'Small'), + medium: t('launchpad', 'Medium'), + large: t('launchpad', 'Large'), + unknown: t('launchpad', 'Unknown'), + } + const interactions = { + filterApplied: t('launchpad', 'Filter applied'), + drillDown: t('launchpad', 'Drill down'), + export: t('launchpad', 'Export'), + } + const chart = (id, title, rows) => ({ id, title, rows, max: Math.max(0, ...rows.map((row) => row.count)) }) + return [ + chart('by-date', t('launchpad', 'Page views by date'), this.report.byDate ?? []), + chart('by-origin', t('launchpad', 'Page views by site'), this.report.byHostOrigin ?? []), + chart('by-viewport', t('launchpad', 'Page views by screen size'), Object.entries(this.report.byViewport ?? {}) + .map(([key, count]) => ({ label: viewports[key] ?? key, count }))), + chart('by-browser', t('launchpad', 'Page views by browser'), this.report.byBrowser ?? []), + chart('interactions', t('launchpad', 'Interactions'), Object.entries(this.report.interactions ?? {}) + .map(([key, count]) => ({ label: interactions[key] ?? key, count }))), + ] + }, + }, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-17 */ + created() { + this.load() + }, + + methods: { + t, + n, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-17 */ + async load() { + this.loading = true + this.error = '' + try { + this.report = await embedApi.tokenUsage(this.tokenId) + } catch (error) { + this.error = t('launchpad', 'The usage report could not be loaded.') + logger.error('Failed to load embed usage:', error) + } finally { + this.loading = false + } + }, + + /** + * A bar's width relative to the largest count of its chart. + * + * @param {number} count The count. + * @param {number} max The largest count. + * @return {string} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + barWidth(count, max) { + return max > 0 ? `${Math.round((count / max) * 100)}%` : '0%' + }, + + /** + * The report's aggregates as CSV: one `chart,label,count` row per bar. + * + * @return {string} + * @spec openspec/changes/embedded-analytics/tasks.md#task-17 + */ + csv() { + const quote = (value) => `"${String(value).replace(/"/g, '""')}"` + const lines = ['chart,label,count'] + for (const chart of this.charts) { + for (const row of chart.rows) { + lines.push([quote(chart.id), quote(row.label), row.count].join(',')) + } + } + return lines.join('\n') + '\n' + }, + + /** + * Download the CSV. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + exportCsv() { + const url = URL.createObjectURL(new Blob([this.csv()], { type: 'text/csv' })) + const link = document.createElement('a') + link.href = url + link.download = `embed-usage-${(this.tokenName || this.tokenId).replace(/[^a-z0-9-]+/gi, '-').toLowerCase()}.csv` + link.click() + URL.revokeObjectURL(url) + }, + }, +} +</script> + +<style scoped> +.embed-usage-report { + display: flex; + flex-direction: column; + gap: 12px; +} + +.embed-usage-report__summary { + display: grid; + grid-template-columns: max-content 1fr; + gap: 4px 16px; +} + +.embed-usage-report__summary dt, +.embed-usage-report__chart th { + font-weight: bold; + text-align: start; +} + +.embed-usage-report__chart table { + width: 100%; + max-width: 640px; +} + +.embed-usage-report__chart th, +.embed-usage-report__chart td { + padding: 2px 8px; +} + +.embed-usage-report__bar-cell { + width: 60%; +} + +.embed-usage-report__bar { + display: block; + height: 12px; + background: var(--color-primary-element); + border-radius: var(--border-radius); +} + +.embed-usage-report__count { + text-align: end; +} + +.embed-usage-report__empty { + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/admin/embed/TenantThemeManager.vue b/src/components/admin/embed/TenantThemeManager.vue new file mode 100644 index 000000000..5aa131bfd --- /dev/null +++ b/src/components/admin/embed/TenantThemeManager.vue @@ -0,0 +1,408 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <section class="tenant-theme-manager" data-test="tenant-theme-manager"> + <h3>{{ t('launchpad', 'Embed themes') }}</h3> + + <NcNoteCard v-if="error !== ''" type="error" data-test="tenant-theme-error"> + {{ error }} + </NcNoteCard> + + <form + v-if="editing" + class="tenant-theme-manager__form" + data-test="tenant-theme-form" + @submit.prevent="save"> + <NcTextField v-model="form.name" :label="t('launchpad', 'Name')" required data-test="tenant-theme-name" /> + <div v-for="variable in variables" :key="variable.name" class="tenant-theme-manager__variable"> + <input + :id="'tenant-theme-' + variable.name" + v-model="form.cssVariables[variable.name]" + type="color" + :aria-label="variable.label" + :data-test="'tenant-theme-color' + variable.name"> + <NcTextField + v-model="form.cssVariables[variable.name]" + :label="variable.label + ' (' + variable.name + ')'" + :data-test="'tenant-theme-var' + variable.name" /> + </div> + <NcTextField + v-model="form.logoUrl" + :label="t('launchpad', 'Logo URL (https)')" + data-test="tenant-theme-logo" /> + <NcTextArea + v-model="form.customCss" + :label="t('launchpad', 'Custom CSS, :root rules only')" + :error="cssProblem !== ''" + :helperText="cssProblem" + data-test="tenant-theme-css" /> + + <div class="tenant-theme-manager__preview" :style="previewStyle" data-test="tenant-theme-preview"> + <img v-if="safeLogo" :src="safeLogo" alt="" class="tenant-theme-manager__preview-logo"> + <strong>{{ t('launchpad', 'Sample widget') }}</strong> + <p>{{ t('launchpad', 'Text on the surface colour.') }}</p> + <span class="tenant-theme-manager__preview-button">{{ t('launchpad', 'Primary action') }}</span> + </div> + + <div class="tenant-theme-manager__row tenant-theme-manager__row--end"> + <NcButton data-test="tenant-theme-cancel" @click="editing = null"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + type="submit" + variant="primary" + :disabled="saving || cssProblem !== ''" + data-test="tenant-theme-save"> + {{ t('launchpad', 'Save') }} + </NcButton> + </div> + </form> + + <template v-else> + <div class="tenant-theme-manager__row"> + <NcButton variant="primary" data-test="tenant-theme-new" @click="edit(null)"> + {{ t('launchpad', 'New theme') }} + </NcButton> + </div> + <NcLoadingIcon v-if="loading" /> + <p v-else-if="themes.length === 0" class="tenant-theme-manager__empty" data-test="tenant-theme-empty"> + {{ t('launchpad', 'No themes yet. Embeds use the default theme.') }} + </p> + <table v-else class="tenant-theme-manager__table" data-test="tenant-theme-table"> + <thead> + <tr> + <th scope="col">{{ t('launchpad', 'Name') }}</th> + <th scope="col">{{ t('launchpad', 'Primary colour') }}</th> + <th scope="col">{{ t('launchpad', 'Logo') }}</th> + <th scope="col">{{ t('launchpad', 'Created') }}</th> + <th scope="col">{{ t('launchpad', 'Tokens') }}</th> + <th scope="col"><span class="hidden-visually">{{ t('launchpad', 'Actions') }}</span></th> + </tr> + </thead> + <tbody> + <tr v-for="theme in themes" :key="theme.id" :data-test="'tenant-theme-row-' + theme.id"> + <td>{{ theme.name }}</td> + <td> + <span class="tenant-theme-manager__swatch" :style="{ background: (theme.cssVariables || {})['--c-primary'] }" /> + {{ (theme.cssVariables || {})['--c-primary'] || '' }} + </td> + <td>{{ theme.logoUrl ? t('launchpad', 'Yes') : t('launchpad', 'No') }}</td> + <td>{{ theme.createdAt }}</td> + <td>{{ theme.tokenCount || 0 }}</td> + <td class="tenant-theme-manager__row"> + <NcButton variant="tertiary" :data-test="'tenant-theme-edit-' + theme.id" @click="edit(theme)"> + {{ t('launchpad', 'Edit') }} + </NcButton> + <NcButton variant="tertiary" :data-test="'tenant-theme-copy-' + theme.id" @click="copyJson(theme)"> + {{ t('launchpad', 'Copy JSON') }} + </NcButton> + <NcButton variant="tertiary" :data-test="'tenant-theme-delete-' + theme.id" @click="deleting = theme"> + {{ t('launchpad', 'Delete') }} + </NcButton> + </td> + </tr> + </tbody> + </table> + </template> + + <DeleteTenantThemeDialog + v-if="deleting" + :open="true" + :name="deleting.name" + :tokenCount="deleting.tokenCount || 0" + @update:open="deleting = $event ? deleting : null" + @confirm="remove" /> + </section> +</template> + +<script> +import { NcButton, NcLoadingIcon, NcNoteCard, NcTextArea, NcTextField } from '@conduction/nextcloud-vue' +import { showSuccess } from '@nextcloud/dialogs' +import { t } from '@nextcloud/l10n' +import DeleteTenantThemeDialog from '../../../dialogs/DeleteTenantThemeDialog.vue' +import { embedApi } from '../../../services/embedApi.js' +import { onlyRootRules } from '../../../utils/embedToken.js' +import { logger } from '../../../utils/logger.js' + +/** The variables the form offers, with the platform defaults of a new theme. */ +const VARIABLES = [ + { name: '--c-primary', fallback: '#0b5394' }, + { name: '--c-surface', fallback: '#ffffff' }, + { name: '--c-text', fallback: '#222222' }, + { name: '--c-border', fallback: '#dddddd' }, +] + +/** + * TenantThemeManager — Beheer ▸ Embeds: the tenant themes embeds can use + * (embedded-analytics task 16, REQ-EMB-005). Lists them with their primary + * colour and how many tokens use them; creates and edits them with a live + * preview; deletes them, warning first when tokens use one; copies a + * theme's JSON. The server checks names, values, :root-only CSS, the https + * logo and contrast; its refusal message is shown. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ +export default { + name: 'TenantThemeManager', + + components: { + DeleteTenantThemeDialog, + NcButton, + NcLoadingIcon, + NcNoteCard, + NcTextArea, + NcTextField, + }, + + data() { + return { + themes: [], + loading: true, + saving: false, + editing: null, + deleting: null, + form: this.emptyForm(), + error: '', + } + }, + + computed: { + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + variables() { + const labels = { + '--c-primary': t('launchpad', 'Primary colour'), + '--c-surface': t('launchpad', 'Surface colour'), + '--c-text': t('launchpad', 'Text colour'), + '--c-border': t('launchpad', 'Border colour'), + } + return VARIABLES.map((variable) => ({ ...variable, label: labels[variable.name] })) + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + cssProblem() { + return onlyRootRules(this.form.customCss) ? '' : t('launchpad', 'Custom CSS may only set :root rules.') + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + previewStyle() { + const vars = this.form.cssVariables + return { + ...vars, + background: vars['--c-surface'], + color: vars['--c-text'], + borderColor: vars['--c-border'], + '--preview-primary': vars['--c-primary'], + } + }, + + /** @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md */ + safeLogo() { + return /^https:\/\//.test(this.form.logoUrl) ? this.form.logoUrl : '' + }, + }, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-16 */ + created() { + this.load() + }, + + methods: { + t, + + /** + * @return {object} A new theme's form. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + emptyForm() { + return { + name: '', + cssVariables: Object.fromEntries(VARIABLES.map((variable) => [variable.name, variable.fallback])), + logoUrl: '', + customCss: '', + } + }, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-16 */ + async load() { + this.loading = true + this.error = '' + try { + this.themes = await embedApi.listThemes() + } catch (error) { + this.error = t('launchpad', 'Themes could not be loaded.') + logger.error('Failed to load tenant themes:', error) + } finally { + this.loading = false + } + }, + + /** + * Open the form for a theme, or for a new one. + * + * @param {object|null} theme The theme. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + edit(theme) { + const form = this.emptyForm() + if (theme) { + form.name = theme.name ?? '' + form.cssVariables = { ...form.cssVariables, ...(theme.cssVariables ?? {}) } + form.logoUrl = theme.logoUrl ?? '' + form.customCss = theme.customCss ?? '' + } + this.form = form + this.editing = theme ?? { id: '' } + this.error = '' + }, + + /** @spec openspec/changes/embedded-analytics/tasks.md#task-16 */ + async save() { + this.saving = true + this.error = '' + const theme = { + name: this.form.name.trim(), + cssVariables: Object.fromEntries(Object.entries(this.form.cssVariables).filter(([, value]) => String(value).trim() !== '')), + logoUrl: this.form.logoUrl.trim(), + customCss: this.form.customCss, + } + try { + if (this.editing.id) { + await embedApi.updateTheme(this.editing.id, theme) + } else { + await embedApi.createTheme(theme) + } + this.editing = null + showSuccess(t('launchpad', 'Theme saved.')) + await this.load() + } catch (error) { + this.error = error?.response?.data?.message || t('launchpad', 'The theme could not be saved.') + logger.error('Failed to save tenant theme:', error) + } finally { + this.saving = false + } + }, + + /** + * Delete the theme in the dialog; one tokens use is deleted with force, the dialog having warned. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ + async remove() { + const theme = this.deleting + this.deleting = null + this.error = '' + try { + await embedApi.deleteTheme(theme.id, (theme.tokenCount ?? 0) > 0) + this.themes = this.themes.filter((item) => item.id !== theme.id) + showSuccess(t('launchpad', 'Theme deleted.')) + } catch (error) { + this.error = error?.response?.data?.message || t('launchpad', 'The theme could not be deleted.') + logger.error('Failed to delete tenant theme:', error) + } + }, + + /** + * Copy a theme's JSON (name, variables, logo, custom CSS) for documentation. + * + * @param {object} theme The theme. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + async copyJson(theme) { + const { name, cssVariables, logoUrl, customCss } = theme + try { + await navigator.clipboard.writeText(JSON.stringify({ name, cssVariables, logoUrl, customCss }, null, 2)) + showSuccess(t('launchpad', 'Theme JSON copied.')) + } catch (error) { + logger.error('Failed to copy the theme JSON:', error) + } + }, + }, +} +</script> + +<style scoped> +.tenant-theme-manager { + display: flex; + flex-direction: column; + gap: 12px; +} + +.tenant-theme-manager__form { + display: flex; + flex-direction: column; + gap: 8px; + max-width: 640px; +} + +.tenant-theme-manager__row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.tenant-theme-manager__row--end { + justify-content: flex-end; +} + +.tenant-theme-manager__variable { + display: flex; + align-items: flex-end; + gap: 8px; +} + +.tenant-theme-manager__variable input[type='color'] { + width: 44px; + height: 36px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius); +} + +.tenant-theme-manager__preview { + border: 1px solid; + border-radius: var(--border-radius-large); + padding: 12px; +} + +.tenant-theme-manager__preview-logo { + display: block; + max-height: 32px; + margin-bottom: 8px; +} + +.tenant-theme-manager__preview-button { + display: inline-block; + padding: 4px 12px; + border-radius: var(--border-radius); + background: var(--preview-primary); + color: var(--color-primary-element-text); +} + +.tenant-theme-manager__table { + width: 100%; + border-collapse: collapse; +} + +.tenant-theme-manager__table th, +.tenant-theme-manager__table td { + text-align: start; + padding: 6px 8px; + border-bottom: 1px solid var(--color-border); +} + +.tenant-theme-manager__swatch { + display: inline-block; + width: 16px; + height: 16px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius); + vertical-align: middle; +} + +.tenant-theme-manager__empty { + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/components/admin/embed/__tests__/EmbedTokenForm.spec.js b/src/components/admin/embed/__tests__/EmbedTokenForm.spec.js new file mode 100644 index 000000000..b18dd80f6 --- /dev/null +++ b/src/components/admin/embed/__tests__/EmbedTokenForm.spec.js @@ -0,0 +1,160 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The embed token form: subject picking (dashboard, or a widget of a + * dashboard), host origins checked as the server checks them, the CSP + * preview, required fields, and the edit form offering only what may change + * (embedded-analytics task 18). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-18 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import EmbedTokenForm from '../EmbedTokenForm.vue' + +const dashboardsApi = vi.hoisted(() => ({ getDashboardById: vi.fn() })) +vi.mock('../../../../services/api.js', () => ({ api: dashboardsApi })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`) })) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +function Field (name) { + return { + name, + props: ['modelValue', 'label', 'error', 'helperText'], + emits: ['update:modelValue', 'keydown'], + template: `<label class="${name}" :data-label="label">{{ helperText }}<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)"></label>`, +} +} +const Choice = { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'value', 'type'], + emits: ['update:modelValue'], + template: '<label class="choice"><input :type="type" @change="toggle"><slot /></label>', + methods: { + toggle() { + if (this.type === 'radio') { + this.$emit('update:modelValue', this.value) + } else { + const list = [...this.modelValue] + this.$emit('update:modelValue', list.includes(this.value) ? list.filter((item) => item !== this.value) : [...list, this.value]) + } + }, + }, +} +const Select = { name: 'NcSelect', props: ['modelValue', 'options', 'inputLabel', 'disabled', 'loading'], emits: ['update:modelValue'], template: '<div class="select" />' } +const Button = { name: 'NcButton', props: ['type'], emits: ['click'], template: '<button :type="type || \'button\'" @click="$emit(\'click\')"><slot /></button>' } + +const DASHBOARDS = [{ id: 7, uuid: 'dash-uuid', name: 'Mijn week' }, { id: 8, uuid: 'other', name: 'Team' }] + +function mountForm (props = {}) { + return mount(EmbedTokenForm, { + props: { dashboards: DASHBOARDS, themes: [{ id: 'th-1', name: 'Zeist' }], ...props }, + global: { stubs: { NcTextField: Field('text-field'), NcTextArea: Field('text-area'), NcCheckboxRadioSwitch: Choice, NcSelect: Select, NcButton: Button } }, +}) +} + +const select = (wrapper, test) => wrapper.findAllComponents(Select).find((item) => item.attributes('data-test') === test) + +/** + * Type an origin and press Add. + * + * @param {object} wrapper The mounted form. + * @param {string} origin The origin. + */ +async function addOrigin(wrapper, origin) { + await wrapper.find('[data-test="embed-token-new-origin"] input').setValue(origin) + await wrapper.find('[data-test="embed-token-add-origin"]').trigger('click') +} + +describe('EmbedTokenForm', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('refuses wildcard and malformed origins and adds a valid one normalised, once', async () => { + const wrapper = mountForm() + + await addOrigin(wrapper, 'https://*.zeist.nl') + expect(wrapper.find('[data-test="embed-token-new-origin"]').text()).toBe('Wildcards are not allowed; list each site.') + await addOrigin(wrapper, 'https://www.zeist.nl/woo') + expect(wrapper.find('[data-test="embed-token-new-origin"]').text()).toContain('without a path') + await addOrigin(wrapper, 'https://WWW.Zeist.nl/') + await addOrigin(wrapper, 'https://www.zeist.nl') + + expect(wrapper.findAll('[data-test="embed-token-origins"] code').map((node) => node.text())).toEqual(['https://www.zeist.nl']) + expect(wrapper.find('[data-test="embed-token-new-origin"]').text()).toBe('') + + await wrapper.find('[data-test="embed-token-csp-toggle"]').trigger('click') + expect(wrapper.find('[data-test="embed-token-csp"]').text()).toBe('Content-Security-Policy: frame-ancestors https://www.zeist.nl') + + await wrapper.find('[data-test="embed-token-origins"] button').trigger('click') + expect(wrapper.findAll('[data-test="embed-token-origins"] code')).toHaveLength(0) + }) + + it('names every missing required field and emits nothing', async () => { + const wrapper = mountForm() + await wrapper.find('form').trigger('submit') + + expect(wrapper.emitted('submit')).toBeUndefined() + expect(wrapper.find('[data-test="embed-token-name"]').text()).toBe('Give the token a name.') + expect(wrapper.find('[role="alert"]').text()).toBe('Choose what to embed.') + expect(wrapper.find('[data-test="embed-token-new-origin"]').text()).toBe('Add at least one site that may embed it.') + }) + + it('emits the create payload of a dashboard token', async () => { + const wrapper = mountForm() + await wrapper.find('[data-test="embed-token-name"] input').setValue('Zeist WOO') + select(wrapper, 'embed-subject-dashboard').vm.$emit('update:modelValue', DASHBOARDS[0]) + await wrapper.find('[data-test="embed-scope-mode-read-with-interactions"] input').trigger('change') + await wrapper.find('[data-test="embed-scope-action-export"] input').trigger('change') + await addOrigin(wrapper, 'https://a.nl') + select(wrapper, 'embed-token-theme').vm.$emit('update:modelValue', { id: 'th-1', name: 'Zeist' }) + await wrapper.find('form').trigger('submit') + + expect(wrapper.emitted('submit')).toEqual([[{ + name: 'Zeist WOO', + description: '', + subject: { type: 'dashboard', id: 'dash-uuid' }, + scope: { mode: 'read-with-interactions', allowedFilters: [], allowedActions: ['export'] }, + hostOrigins: ['https://a.nl'], + tenantThemeId: 'th-1', + tokenExpiresAt: null, + rateLimitPolicy: null, + }]]) + expect(dashboardsApi.getDashboardById).not.toHaveBeenCalled() + }) + + it('offers the widgets of the chosen dashboard for a widget token', async () => { + dashboardsApi.getDashboardById.mockResolvedValue({ data: { placements: [{ id: 41, widgetId: 'chart', customTitle: 'Aanvragen' }, { id: 42, widgetId: 'text' }] } }) + const wrapper = mountForm() + await wrapper.find('[data-test="embed-subject-type-widget"] input').trigger('change') + select(wrapper, 'embed-subject-dashboard').vm.$emit('update:modelValue', DASHBOARDS[1]) + await flushPromises() + + expect(dashboardsApi.getDashboardById).toHaveBeenCalledWith(8) + const widgets = select(wrapper, 'embed-subject-widget') + expect(widgets.props('options')).toEqual([{ id: 41, label: 'Aanvragen' }, { id: 42, label: 'text #42' }]) + widgets.vm.$emit('update:modelValue', { id: 42, label: 'text #42' }) + await wrapper.find('[data-test="embed-token-name"] input').setValue('Tekst') + await addOrigin(wrapper, 'https://a.nl') + await wrapper.find('form').trigger('submit') + + expect(wrapper.emitted('submit')[0][0].subject).toEqual({ type: 'widget', id: '42' }) + expect(wrapper.find('[data-test="embed-token-filter-context"]').exists()).toBe(false) + }) + + it('edits only name, description and rate limit of a stored token', async () => { + const token = { id: 't-1', name: 'Zeist', description: '', subject: { type: 'dashboard', id: 'dash-uuid' }, scope: { mode: 'read' }, hostOrigins: ['https://a.nl'], rateLimitPolicy: null } + const wrapper = mountForm({ token }) + + expect(wrapper.find('[data-test="embed-subject-dashboard"]').exists()).toBe(false) + expect(wrapper.find('[data-test="embed-token-origins"]').exists()).toBe(false) + await wrapper.find('[data-test="embed-token-rpm"] input').setValue('120') + await wrapper.find('form').trigger('submit') + + expect(wrapper.emitted('submit')).toEqual([[{ name: 'Zeist', description: '', rateLimitPolicy: { requestsPerMinute: 120, burstSize: 120 } }]]) + expect(wrapper.find('[data-test="embed-token-submit"]').text()).toBe('Save') + }) +}) diff --git a/src/components/admin/embed/__tests__/EmbedTokenManager.spec.js b/src/components/admin/embed/__tests__/EmbedTokenManager.spec.js new file mode 100644 index 000000000..91b4ea939 --- /dev/null +++ b/src/components/admin/embed/__tests__/EmbedTokenManager.spec.js @@ -0,0 +1,204 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The embed token manager lists tokens with their status, issues one and + * shows its JWT once, revokes with a reason and restores, re-issues, and + * shows the server's refusal (embedded-analytics tasks 15, 27 and 40). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + * @spec openspec/changes/embedded-analytics/tasks.md#task-27 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import EmbedTokenManager from '../EmbedTokenManager.vue' + +const embed = vi.hoisted(() => ({ + listTokens: vi.fn(), + listThemes: vi.fn(), + createToken: vi.fn(), + updateToken: vi.fn(), + revokeToken: vi.fn(), + unrevokeToken: vi.fn(), + reissueToken: vi.fn(), +})) +const dashboards = vi.hoisted(() => ({ getVisibleDashboards: vi.fn() })) +const toasts = vi.hoisted(() => ({ showSuccess: vi.fn() })) +vi.mock('../../../../services/embedApi.js', () => ({ embedApi: embed })) +vi.mock('../../../../services/api.js', () => ({ api: dashboards })) +vi.mock('@nextcloud/dialogs', () => toasts) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), + n: (_app, one, many, count) => (count === 1 ? one : many).replace('%n', count), +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const Button = { name: 'NcButton', emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>' } +const FormStub = { name: 'EmbedTokenForm', props: ['token', 'dashboards', 'themes', 'defaults', 'saving'], emits: ['submit', 'cancel'], template: '<div class="form-stub" />' } +const DialogStub = { name: 'RevokeEmbedTokenDialog', props: ['open', 'name'], emits: ['update:open', 'confirm'], template: '<div class="revoke-stub" />' } + +const ACTIVE = { id: 't-1', name: 'Zeist WOO', subject: { type: 'dashboard', id: 'dash-uuid' }, scope: { mode: 'read' }, hostOrigins: ['https://a.nl'], createdAt: '2026-05-22T14:30:00Z' } +const REVOKED = { ...ACTIVE, id: 't-2', name: 'Oud', revokedAt: '2026-05-23T08:00:00Z', revocationReason: 'no_longer_needed' } + +function mountManager (props = {}) { + return mount(EmbedTokenManager, { + props, + global: { + stubs: { + NcButton: Button, + NcNoteCard: { props: ['type'], template: '<div :class="\'note-\' + type"><slot /></div>' }, + NcLoadingIcon: true, + EmbedTokenForm: FormStub, + EmbedUsageReport: { props: ['tokenId', 'tokenName'], template: '<div class="usage-stub" />' }, + RevokeEmbedTokenDialog: DialogStub, + }, + }, +}) +} + +describe('EmbedTokenManager', () => { + beforeEach(() => { + vi.clearAllMocks() + embed.listTokens.mockResolvedValue([ACTIVE, REVOKED]) + embed.listThemes.mockResolvedValue([{ id: 'th-1', name: 'Zeist', cssVariables: {} }]) + dashboards.getVisibleDashboards.mockResolvedValue({ data: { items: [{ id: 7, uuid: 'dash-uuid', name: 'Mijn week', extra: 1 }] } }) + }) + + it('lists every token with its status and subject', async () => { + const wrapper = mountManager() + await flushPromises() + + const rows = wrapper.findAll('tbody tr') + expect(rows).toHaveLength(2) + expect(rows[0].text()).toContain('Zeist WOO') + expect(rows[0].text()).toContain('Active') + expect(rows[0].text()).toContain('Dashboard Mijn week') + expect(rows[1].text()).toContain('Revoked') + }) + + it('says so when there are no tokens, and when they cannot be loaded', async () => { + embed.listTokens.mockResolvedValueOnce([]) + const empty = mountManager() + await flushPromises() + expect(empty.find('[data-test="embed-token-empty"]').exists()).toBe(true) + + embed.listTokens.mockRejectedValueOnce(new Error('503')) + const failed = mountManager() + await flushPromises() + expect(failed.find('[data-test="embed-token-error"]').text()).toBe('Embed tokens could not be loaded.') + }) + + it('issues a token and shows its JWT once, with the keep-safe warning and a copy button', async () => { + embed.createToken.mockResolvedValue({ id: 't-3', name: 'Nieuw', jwt: 'aaa.bbb.ccc' }) + const writeText = vi.fn().mockResolvedValue() + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="embed-token-new"]').trigger('click') + const form = wrapper.findComponent(FormStub) + expect(form.props()).toMatchObject({ token: null, dashboards: [{ id: 7, uuid: 'dash-uuid', name: 'Mijn week' }], themes: [{ id: 'th-1', name: 'Zeist' }] }) + form.vm.$emit('submit', { name: 'Nieuw' }) + await flushPromises() + + expect(embed.createToken).toHaveBeenCalledWith({ name: 'Nieuw' }) + expect(wrapper.find('[data-test="embed-token-jwt"]').text()).toBe('aaa.bbb.ccc') + expect(wrapper.find('[data-test="embed-token-issued"]').text()).toContain('It is shown only once') + expect(wrapper.findComponent(FormStub).exists()).toBe(false) + + await wrapper.find('[data-test="embed-token-copy"]').trigger('click') + await flushPromises() + expect(writeText).toHaveBeenCalledWith('aaa.bbb.ccc') + expect(wrapper.find('[data-test="embed-token-copy"]').text()).toBe('Copied') + + await wrapper.find('[data-test="embed-token-issued-done"]').trigger('click') + expect(wrapper.find('[data-test="embed-token-jwt"]').exists()).toBe(false) + }) + + it('shows the server refusal of a create and keeps the form', async () => { + embed.createToken.mockRejectedValue({ response: { data: { message: 'Wildcard origin \'*\' is not permitted.' } } }) + const wrapper = mountManager() + await flushPromises() + await wrapper.find('[data-test="embed-token-new"]').trigger('click') + wrapper.findComponent(FormStub).vm.$emit('submit', { name: 'x' }) + await flushPromises() + + expect(wrapper.find('[data-test="embed-token-error"]').text()).toBe('Wildcard origin \'*\' is not permitted.') + expect(wrapper.findComponent(FormStub).exists()).toBe(true) + }) + + it('revokes with the reason and notes from the dialog and shows the new status', async () => { + embed.revokeToken.mockResolvedValue({ ...ACTIVE, revokedAt: '2026-05-24T10:00:00Z', revocationReason: 'compromised' }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="embed-token-open-t-1"]').trigger('click') + expect(wrapper.find('[data-test="embed-token-status-active"]').exists()).toBe(true) + await wrapper.find('[data-test="embed-token-revoke"]').trigger('click') + const dialog = wrapper.findComponent(DialogStub) + expect(dialog.props('name')).toBe('Zeist WOO') + dialog.vm.$emit('confirm', { reason: 'compromised', notes: 'gelekt' }) + await flushPromises() + + expect(embed.revokeToken).toHaveBeenCalledWith('t-1', 'compromised', 'gelekt') + expect(wrapper.findComponent(DialogStub).exists()).toBe(false) + expect(wrapper.find('[data-test="embed-token-status-revoked"]').exists()).toBe(true) + expect(wrapper.find('[data-test="embed-token-unrevoke"]').exists()).toBe(true) + expect(toasts.showSuccess).toHaveBeenCalledWith('Token revoked.') + }) + + it('restores a revoked token', async () => { + embed.unrevokeToken.mockResolvedValue({ ...REVOKED, revokedAt: null }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="embed-token-open-t-2"]').trigger('click') + await wrapper.find('[data-test="embed-token-unrevoke"]').trigger('click') + await flushPromises() + + expect(embed.unrevokeToken).toHaveBeenCalledWith('t-2') + expect(wrapper.find('[data-test="embed-token-status-active"]').exists()).toBe(true) + expect(toasts.showSuccess).toHaveBeenCalledWith('Token restored.') + }) + + it('re-issues: shows the new JWT and reloads the list', async () => { + embed.reissueToken.mockResolvedValue({ id: 't-9', jwt: 'new.jwt.value' }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="embed-token-open-t-1"]').trigger('click') + await wrapper.find('[data-test="embed-token-reissue"]').trigger('click') + await flushPromises() + + expect(embed.reissueToken).toHaveBeenCalledWith('t-1') + expect(embed.listTokens).toHaveBeenCalledTimes(2) + expect(wrapper.find('[data-test="embed-token-jwt"]').text()).toBe('new.jwt.value') + expect(wrapper.find('[data-test="embed-token-table"]').exists()).toBe(true) + }) + + it('edits only through the update call and returns to the detail view', async () => { + embed.updateToken.mockResolvedValue({ ...ACTIVE, name: 'Zeist WOO 2' }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="embed-token-open-t-1"]').trigger('click') + await wrapper.find('[data-test="embed-token-edit"]').trigger('click') + expect(wrapper.findComponent(FormStub).props('token')).toEqual(ACTIVE) + wrapper.findComponent(FormStub).vm.$emit('submit', { name: 'Zeist WOO 2' }) + await flushPromises() + + expect(embed.updateToken).toHaveBeenCalledWith('t-1', { name: 'Zeist WOO 2' }) + expect(embed.createToken).not.toHaveBeenCalled() + expect(wrapper.find('[data-test="embed-token-detail"] h4').text()).toBe('Zeist WOO 2') + }) + + it('opens on the create form for a subject handed in from a dashboard', async () => { + const defaults = { subjectType: 'dashboard', subjectId: 'dash-uuid', dashboardId: 7 } + const wrapper = mountManager({ defaults }) + await flushPromises() + + expect(wrapper.findComponent(FormStub).props('defaults')).toEqual(defaults) + expect(wrapper.find('[data-test="embed-token-table"]').exists()).toBe(false) + }) +}) diff --git a/src/components/admin/embed/__tests__/EmbedUsageReport.spec.js b/src/components/admin/embed/__tests__/EmbedUsageReport.spec.js new file mode 100644 index 000000000..c956687e4 --- /dev/null +++ b/src/components/admin/embed/__tests__/EmbedUsageReport.spec.js @@ -0,0 +1,91 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The usage report shows a token's aggregate use: the summary, a bar row per + * date, site, screen size, browser and interaction, use after revocation, + * and a CSV of the same aggregates only while telemetry is on + * (embedded-analytics task 17). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-17 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import EmbedUsageReport from '../EmbedUsageReport.vue' + +const embed = vi.hoisted(() => ({ tokenUsage: vi.fn() })) +vi.mock('../../../../services/embedApi.js', () => ({ embedApi: embed })) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), + n: (_app, one, many, count) => (count === 1 ? one : many).replace('%n', count), +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const REPORT = { + tokenId: 't-1', + days: 7, + telemetryEnabled: true, + summary: { pageViews: 12, lastActivity: '2026-05-22T14:30:00Z', usedAfterRevocation: 0 }, + byDate: [{ label: '2026-05-21', count: 4 }, { label: '2026-05-22', count: 8 }], + byHostOrigin: [{ label: 'https://www.zeist.nl', count: 12 }], + byViewport: { small: 2, medium: 0, large: 10, unknown: 0 }, + byBrowser: [{ label: 'Firefox 128', count: 12 }], + interactions: { filterApplied: 3, drillDown: 1, export: 0 }, + rateLimited: 1, +} + +function mountReport () { + return mount(EmbedUsageReport, { + props: { tokenId: 't-1', tokenName: 'Zeist WOO' }, + global: { + stubs: { + NcButton: { emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>' }, + NcNoteCard: { props: ['type'], template: '<div class="note"><slot /></div>' }, + NcLoadingIcon: true, + }, + }, +}) +} + +describe('EmbedUsageReport', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('shows the summary and one bar row per aggregate, scaled to the largest', async () => { + embed.tokenUsage.mockResolvedValue(REPORT) + const wrapper = mountReport() + await flushPromises() + + expect(embed.tokenUsage).toHaveBeenCalledWith('t-1') + expect(wrapper.find('[data-test="embed-usage-pageviews"]').text()).toBe('12') + expect(wrapper.find('[data-test="embed-usage-rate-limited"]').text()).toBe('1') + const dates = wrapper.findAll('[data-test="embed-usage-by-date"] tr') + expect(dates.map((row) => row.find('th').text())).toEqual(['2026-05-21', '2026-05-22']) + expect(dates[0].find('.embed-usage-report__bar').attributes('style')).toContain('width: 50%') + expect(dates[1].find('.embed-usage-report__bar').attributes('style')).toContain('width: 100%') + expect(wrapper.findAll('[data-test="embed-usage-by-viewport"] th').map((cell) => cell.text())).toEqual(['Small', 'Medium', 'Large', 'Unknown']) + expect(wrapper.find('[data-test="embed-usage-interactions"]').text()).toContain('Filter applied') + expect(wrapper.find('[data-test="embed-usage-after-revocation"]').exists()).toBe(false) + expect(wrapper.vm.csv().split('\n').slice(0, 3)).toEqual(['chart,label,count', '"by-date","2026-05-21",4', '"by-date","2026-05-22",8']) + }) + + it('warns about use after revocation, and offers no export while telemetry is off', async () => { + embed.tokenUsage.mockResolvedValue({ ...REPORT, telemetryEnabled: false, summary: { ...REPORT.summary, usedAfterRevocation: 3 } }) + const wrapper = mountReport() + await flushPromises() + + expect(wrapper.find('[data-test="embed-usage-after-revocation"]').text()).toBe('3 requests arrived after the token was revoked.') + expect(wrapper.find('[data-test="embed-usage-disabled"]').exists()).toBe(true) + expect(wrapper.find('[data-test="embed-usage-export"]').exists()).toBe(false) + }) + + it('says so when the report cannot be loaded', async () => { + embed.tokenUsage.mockRejectedValue(new Error('503')) + const wrapper = mountReport() + await flushPromises() + + expect(wrapper.text()).toContain('The usage report could not be loaded.') + }) +}) diff --git a/src/components/admin/embed/__tests__/TenantThemeManager.spec.js b/src/components/admin/embed/__tests__/TenantThemeManager.spec.js new file mode 100644 index 000000000..30080f5c3 --- /dev/null +++ b/src/components/admin/embed/__tests__/TenantThemeManager.spec.js @@ -0,0 +1,146 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The tenant theme manager lists themes, creates and edits them with a live + * preview, refuses non-:root CSS while typing, shows the server's refusal, + * deletes (forcing only after warning about tokens) and copies a theme's JSON + * (embedded-analytics task 16). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import TenantThemeManager from '../TenantThemeManager.vue' + +const embed = vi.hoisted(() => ({ listThemes: vi.fn(), createTheme: vi.fn(), updateTheme: vi.fn(), deleteTheme: vi.fn() })) +const toasts = vi.hoisted(() => ({ showSuccess: vi.fn() })) +vi.mock('../../../../services/embedApi.js', () => ({ embedApi: embed })) +vi.mock('@nextcloud/dialogs', () => toasts) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text, n: (_app, one, many, count) => (count === 1 ? one : many).replace('%n', count) })) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +function Field (name) { + return { + name, + props: ['modelValue', 'label', 'error', 'helperText'], + emits: ['update:modelValue'], + template: `<label class="${name}">{{ helperText }}<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)"></label>`, +} +} +const Button = { name: 'NcButton', props: ['type', 'disabled'], emits: ['click'], template: '<button :type="type || \'button\'" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' } +const DialogStub = { name: 'DeleteTenantThemeDialog', props: ['open', 'name', 'tokenCount'], emits: ['update:open', 'confirm'], template: '<div class="delete-stub" />' } + +const ZEIST = { id: 'th-1', name: 'Zeist', cssVariables: { '--c-primary': '#0b5394', '--c-surface': '#ffffff' }, logoUrl: 'https://www.zeist.nl/logo.svg', customCss: '', createdAt: '2026-05-22T14:30:00Z', tokenCount: 2 } +const UNUSED = { id: 'th-2', name: 'Leeg', cssVariables: {}, logoUrl: '', customCss: '', tokenCount: 0 } + +function mountManager () { + return mount(TenantThemeManager, { + global: { + stubs: { + NcTextField: Field('text-field'), + NcTextArea: Field('text-area'), + NcButton: Button, + NcNoteCard: { props: ['type'], template: '<div class="note"><slot /></div>' }, + NcLoadingIcon: true, + DeleteTenantThemeDialog: DialogStub, + }, + }, +}) +} + +describe('TenantThemeManager', () => { + beforeEach(() => { + vi.clearAllMocks() + embed.listThemes.mockResolvedValue([ZEIST, UNUSED]) + }) + + it('lists the themes with their primary colour and token count', async () => { + const wrapper = mountManager() + await flushPromises() + + const row = wrapper.find('[data-test="tenant-theme-row-th-1"]') + expect(row.text()).toContain('Zeist') + expect(row.text()).toContain('#0b5394') + expect(row.findAll('td')[4].text()).toBe('2') + }) + + it('creates a theme from the form, dropping empty variables, with a live preview', async () => { + embed.createTheme.mockResolvedValue({ id: 'th-3' }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="tenant-theme-new"]').trigger('click') + await wrapper.find('[data-test="tenant-theme-name"] input').setValue('Amsterdam') + await wrapper.find('[data-test="tenant-theme-var--c-primary"] input').setValue('#ec0000') + await wrapper.find('[data-test="tenant-theme-var--c-border"] input').setValue('') + expect(wrapper.find('[data-test="tenant-theme-preview"]').attributes('style')).toContain('--preview-primary: #ec0000') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(embed.createTheme).toHaveBeenCalledWith({ + name: 'Amsterdam', + cssVariables: { '--c-primary': '#ec0000', '--c-surface': '#ffffff', '--c-text': '#222222' }, + logoUrl: '', + customCss: '', + }) + expect(embed.listThemes).toHaveBeenCalledTimes(2) + expect(wrapper.find('form').exists()).toBe(false) + expect(toasts.showSuccess).toHaveBeenCalledWith('Theme saved.') + }) + + it('edits a theme through the update call and shows a server refusal', async () => { + embed.updateTheme.mockRejectedValue({ response: { data: { message: 'Primary colour contrast is 2.1:1; at least 4.5:1 is required.' } } }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="tenant-theme-edit-th-1"]').trigger('click') + expect(wrapper.find('[data-test="tenant-theme-name"] input').element.value).toBe('Zeist') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(embed.updateTheme).toHaveBeenCalledWith('th-1', expect.objectContaining({ name: 'Zeist', logoUrl: 'https://www.zeist.nl/logo.svg' })) + expect(wrapper.find('[data-test="tenant-theme-error"]').text()).toBe('Primary colour contrast is 2.1:1; at least 4.5:1 is required.') + expect(wrapper.find('form').exists()).toBe(true) + }) + + it('refuses non-:root custom CSS before saving', async () => { + const wrapper = mountManager() + await flushPromises() + await wrapper.find('[data-test="tenant-theme-new"]').trigger('click') + await wrapper.find('[data-test="tenant-theme-css"] input').setValue('body { color: red; }') + + expect(wrapper.find('[data-test="tenant-theme-css"]').text()).toBe('Custom CSS may only set :root rules.') + expect(wrapper.find('[data-test="tenant-theme-save"]').attributes('disabled')).toBeDefined() + }) + + it('forces the delete of a theme in use only after the dialog warned, and not of an unused one', async () => { + embed.deleteTheme.mockResolvedValue({ deleted: true }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="tenant-theme-delete-th-1"]').trigger('click') + expect(wrapper.findComponent(DialogStub).props()).toMatchObject({ name: 'Zeist', tokenCount: 2 }) + wrapper.findComponent(DialogStub).vm.$emit('confirm') + await flushPromises() + await wrapper.find('[data-test="tenant-theme-delete-th-2"]').trigger('click') + wrapper.findComponent(DialogStub).vm.$emit('confirm') + await flushPromises() + + expect(embed.deleteTheme.mock.calls).toEqual([['th-1', true], ['th-2', false]]) + expect(wrapper.findAll('tbody tr')).toHaveLength(0) + }) + + it('copies a theme as JSON', async () => { + const writeText = vi.fn().mockResolvedValue() + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }) + const wrapper = mountManager() + await flushPromises() + + await wrapper.find('[data-test="tenant-theme-copy-th-1"]').trigger('click') + await flushPromises() + + expect(JSON.parse(writeText.mock.calls[0][0])).toEqual({ name: 'Zeist', cssVariables: ZEIST.cssVariables, logoUrl: ZEIST.logoUrl, customCss: '' }) + }) +}) diff --git a/src/components/admin/roleSection.css b/src/components/admin/roleSection.css new file mode 100644 index 000000000..2f8cdaa0a --- /dev/null +++ b/src/components/admin/roleSection.css @@ -0,0 +1,77 @@ +/* + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Styles shared by the admin role sections (RolePermissionsSection, + * RoleLayoutDefaultsSection): the hint, the error banner, the role list and + * its rows, chips and actions, and the editor body. Each section adds its + * own chip variant and editor layout after this sheet. + */ + +.launchpad-admin__hint { + color: var(--color-text-maxcontrast); + margin: 0 0 var(--default-grid-baseline) 0; +} + +.launchpad-admin__error { + background: var(--color-error); + color: var(--color-primary-element-text); + padding: var(--default-grid-baseline); + border-radius: var(--border-radius); + margin-bottom: var(--default-grid-baseline); +} + +.launchpad-admin__role-list { + display: flex; + flex-direction: column; + gap: var(--default-grid-baseline); + margin-bottom: var(--default-grid-baseline); +} + +.launchpad-admin__role-row { + display: flex; + align-items: center; + gap: var(--default-grid-baseline); + padding: var(--default-grid-baseline); + border: 1px solid var(--color-border); + border-radius: var(--border-radius); +} + +.launchpad-admin__role-meta { + display: flex; + flex-direction: column; + min-width: 200px; +} + +.launchpad-admin__role-group { + color: var(--color-text-maxcontrast); + font-family: var(--font-face-monospace, monospace); + font-size: 0.85em; +} + +.launchpad-admin__role-widgets { + flex: 1; + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.launchpad-admin__chip { + background: var(--color-background-hover); + padding: 2px 8px; + border-radius: var(--border-radius); + font-size: 0.85em; +} + +.launchpad-admin__role-actions { + display: flex; + gap: 4px; +} + +.launchpad-admin__editor { + padding: calc(var(--default-grid-baseline) * 2); + display: flex; + flex-direction: column; + gap: var(--default-grid-baseline); + min-width: 480px; +} diff --git a/src/components/admin/tabs/AppCatalogueTab.vue b/src/components/admin/tabs/AppCatalogueTab.vue new file mode 100644 index 000000000..930ae4641 --- /dev/null +++ b/src/components/admin/tabs/AppCatalogueTab.vue @@ -0,0 +1,626 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="app-catalogue-tab" data-testid="app-catalogue-tab"> + <h3>{{ t('launchpad', 'App catalogue') }}</h3> + <p class="app-catalogue-tab__intro"> + {{ + t( + 'launchpad', + 'The approved apps people can add as a tile from Add. An app without groups is visible to everyone.', + ) + }} + </p> + + <p v-if="loading"> + {{ t('launchpad', 'Loading…') }} + </p> + <template v-else> + <p + v-if="error" + class="app-catalogue-tab__error" + role="alert" + data-testid="app-catalogue-error"> + {{ error }} + </p> + <p v-if="notice" role="status" data-testid="app-catalogue-notice"> + {{ notice }} + </p> + + <section class="app-catalogue-tab__section" data-testid="app-catalogue-requests"> + <h4>{{ t('launchpad', 'Open requests') }}</h4> + <p v-if="requests.length === 0" class="app-catalogue-tab__empty"> + {{ t('launchpad', 'There are no open requests.') }} + </p> + <ul v-else class="app-catalogue-tab__list"> + <li + v-for="request in requests" + :key="request.uuid" + class="app-catalogue-tab__item" + data-testid="app-catalogue-request"> + <div class="app-catalogue-tab__item-text"> + <strong>{{ request.appName }}</strong> + <span>{{ askedBy(request) }}</span> + <span v-if="request.purpose">{{ request.purpose }}</span> + </div> + <form + v-if="declining === request.uuid" + class="app-catalogue-tab__decline" + @submit.prevent="decline(request)"> + <NcTextField + v-model="declineNote" + :label="t('launchpad', 'Why is it declined?')" + :required="true" /> + <div class="app-catalogue-tab__actions"> + <NcButton + type="submit" + variant="error" + :disabled="busy || declineNote.trim() === ''"> + {{ t('launchpad', 'Decline request') }} + </NcButton> + <NcButton variant="tertiary" @click="cancelDecline"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + </div> + </form> + <div v-else class="app-catalogue-tab__actions"> + <NcButton + variant="primary" + :disabled="busy" + @click="startApprove(request)"> + {{ t('launchpad', 'Approve') }} + </NcButton> + <NcButton :disabled="busy" @click="startDecline(request)"> + {{ t('launchpad', 'Decline') }} + </NcButton> + </div> + </li> + </ul> + </section> + + <section class="app-catalogue-tab__section" data-testid="app-catalogue-entries"> + <h4>{{ t('launchpad', 'Approved apps') }}</h4> + <p v-if="apps.length === 0" class="app-catalogue-tab__empty"> + {{ t('launchpad', 'The catalogue is empty.') }} + </p> + <ul v-else class="app-catalogue-tab__list"> + <li + v-for="app in apps" + :key="app.uuid" + class="app-catalogue-tab__item" + data-testid="app-catalogue-entry"> + <div class="app-catalogue-tab__item-text"> + <strong>{{ app.name }}</strong> + <span>{{ app.linkValue }}</span> + <span data-testid="app-catalogue-entry-groups"> + {{ groupNames(app.targetGroups) }} + </span> + </div> + <div class="app-catalogue-tab__actions"> + <NcButton :disabled="busy" @click="startEdit(app)"> + {{ t('launchpad', 'Edit') }} + </NcButton> + <NcButton + variant="tertiary" + :disabled="busy" + @click="remove(app)"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </div> + </li> + </ul> + <NcButton + v-if="!form" + data-testid="app-catalogue-add" + @click="startCreate"> + {{ t('launchpad', 'Add app') }} + </NcButton> + </section> + + <form + v-if="form" + class="app-catalogue-tab__form" + data-testid="app-catalogue-form" + @submit.prevent="save"> + <h4>{{ formTitle }}</h4> + <NcTextField + v-model="form.name" + :label="t('launchpad', 'Name')" + :required="true" /> + <NcTextField + v-model="form.description" + :label="t('launchpad', 'Short description')" /> + <NcSelect + v-model="form.linkType" + :inputLabel="t('launchpad', 'Address type')" + :options="linkTypeOptions" + :reduce="(option) => option.id" + label="label" + :clearable="false" /> + <NcTextField + v-model="form.linkValue" + :label=" + form.linkType === 'app' + ? t('launchpad', 'Nextcloud app id') + : t('launchpad', 'Web address') + " + :required="true" /> + <NcTextField + v-model="form.icon" + :label="t('launchpad', 'Icon (icon class or image address)')" /> + <NcSelect + v-model="form.targetGroups" + :inputLabel="t('launchpad', 'Visible to groups')" + :placeholder="t('launchpad', 'Everyone')" + :options="groupOptions" + :reduce="(option) => option.id" + label="displayName" + :multiple="true" /> + <div class="app-catalogue-tab__actions"> + <NcButton + type="submit" + variant="primary" + :disabled="busy || form.name.trim() === '' || form.linkValue.trim() === ''"> + {{ t('launchpad', 'Save app') }} + </NcButton> + <NcButton variant="tertiary" @click="closeForm"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + </div> + </form> + + <section class="app-catalogue-tab__section" data-testid="app-catalogue-manager"> + <h4>{{ t('launchpad', 'Who decides on requests') }}</h4> + <p class="app-catalogue-tab__empty"> + {{ + t( + 'launchpad', + 'Administrators always hear about new requests. Members of this group do too.', + ) + }} + </p> + <NcSelect + v-model="managerGroup" + :inputLabel="t('launchpad', 'Catalogue manager group')" + :placeholder="t('launchpad', 'None')" + :options="groupOptions" + :reduce="(option) => option.id" + label="displayName" + @update:modelValue="saveManagerGroup" /> + </section> + </template> + </div> +</template> + +<script> +import axios from '@nextcloud/axios' +import { t } from '@nextcloud/l10n' +import { generateUrl } from '@nextcloud/router' +import { NcButton, NcSelect, NcTextField } from '@nextcloud/vue' + +const BASE = '/apps/launchpad/api/admin/catalogue' + +/** + * An empty catalogue form, optionally prefilled with a name. + * + * @param {string} name The name to start with. + * @return {object} The form fields. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ +function emptyForm(name = '') { + return { + name, + description: '', + icon: '', + linkType: 'url', + linkValue: '', + targetGroups: [], + } +} + +/** + * AppCatalogueTab: the administrator keeps the catalogue of approved apps + * (REQ-ACAT-001) and decides on the requests for missing ones + * (REQ-ACAT-004). Approving opens the form prefilled with the requested + * name; saving it creates the entry and links the request to it. + * Declining asks for a note first. + * + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md + */ +export default { + name: 'AppCatalogueTab', + + components: { NcButton, NcSelect, NcTextField }, + + props: { + /** The server's groups, as `{ id, displayName }`. */ + groups: { + type: Array, + default: () => [], + }, + }, + + data() { + return { + apps: [], + requests: [], + managerGroup: null, + loading: true, + busy: false, + error: '', + notice: '', + // The open form: null, or the fields plus how it saves. + form: null, + // 'create', 'edit' (with formUuid) or 'approve' (with formUuid). + formMode: 'create', + formUuid: '', + declining: '', + declineNote: '', + } + }, + + computed: { + /** + * Group picker options; plain group ids are accepted too. + * + * @return {Array<{id: string, displayName: string}>} + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + groupOptions() { + return this.groups.map((group) => + typeof group === 'string' + ? { id: group, displayName: group } + : { id: group.id, displayName: group.displayName || group.id }, + ) + }, + + /** + * The two kinds of address an entry can have. + * + * @return {Array<{id: string, label: string}>} + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + linkTypeOptions() { + return [ + { id: 'url', label: t('launchpad', 'Web address') }, + { id: 'app', label: t('launchpad', 'Nextcloud app') }, + ] + }, + + /** + * The heading of the open form. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + formTitle() { + if (this.formMode === 'approve') { + return t('launchpad', 'Approve request') + } + return this.formMode === 'edit' + ? t('launchpad', 'Edit app') + : t('launchpad', 'Add app') + }, + }, + + /** @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 */ + async mounted() { + await this.load() + }, + + methods: { + /** @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 */ + async load() { + this.loading = true + try { + const response = await axios.get(generateUrl(BASE)) + this.apps = response?.data?.apps || [] + this.requests = response?.data?.requests || [] + this.managerGroup = response?.data?.managerGroup || null + } catch { + this.error = t('launchpad', 'The app catalogue could not be loaded.') + } finally { + this.loading = false + } + }, + + /** + * The names of an entry's groups, or "Everyone" without any. + * + * @param {Array<string>} ids Group ids. + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + groupNames(ids) { + if (!Array.isArray(ids) || ids.length === 0) { + return t('launchpad', 'Everyone') + } + return ids + .map((id) => this.groupOptions.find((group) => group.id === id)?.displayName || id) + .join(', ') + }, + + /** + * Who asked for an app. + * + * @param {object} request The open request. + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + askedBy(request) { + return t('launchpad', 'Asked by {user}', { user: request.requestedBy }) + }, + + /** @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 */ + startCreate() { + this.openForm('create', '', emptyForm()) + }, + + /** + * Open the form on an existing entry. + * + * @param {object} app The entry. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + startEdit(app) { + this.openForm('edit', app.uuid, { + name: app.name || '', + description: app.description || '', + icon: app.icon || '', + linkType: app.linkType === 'app' ? 'app' : 'url', + linkValue: app.linkValue || '', + targetGroups: [...(app.targetGroups || [])], + }) + }, + + /** + * Approving opens the form prefilled with the requested name. + * + * @param {object} request The open request. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-administrators-decide-on-requests-and-the-requester-hears-back-req-acat-004 + */ + startApprove(request) { + this.cancelDecline() + this.openForm('approve', request.uuid, emptyForm(request.appName || '')) + }, + + /** + * @param {string} mode create, edit or approve. + * @param {string} uuid The entry or request it saves to. + * @param {object} fields The starting fields. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + openForm(mode, uuid, fields) { + this.formMode = mode + this.formUuid = uuid + this.form = fields + this.error = '' + this.notice = '' + }, + + /** @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 */ + closeForm() { + this.form = null + this.formUuid = '' + this.formMode = 'create' + }, + + /** @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-administrators-keep-a-catalogue-of-approved-apps-req-acat-001 */ + async save() { + if (!this.form) { + return + } + const body = { + name: this.form.name.trim(), + description: this.form.description.trim(), + icon: this.form.icon.trim(), + iconType: /^https?:\/\//i.test(this.form.icon.trim()) ? 'url' : 'class', + linkType: this.form.linkType, + linkValue: this.form.linkValue.trim(), + targetGroups: this.form.targetGroups, + } + this.busy = true + this.error = '' + this.notice = '' + try { + if (this.formMode === 'approve') { + const response = await axios.post( + generateUrl(`${BASE}/requests/${this.formUuid}/approve`), + body, + ) + this.requests = this.requests.filter((request) => request.uuid !== this.formUuid) + if (response?.data?.app) { + this.apps.push(response.data.app) + } + this.notice = t('launchpad', '{name} is now in the app catalogue', { name: body.name }) + } else if (this.formMode === 'edit') { + const response = await axios.put(generateUrl(`${BASE}/${this.formUuid}`), body) + const saved = response?.data?.app + this.apps = this.apps.map((app) => + app.uuid === this.formUuid && saved ? saved : app, + ) + this.notice = t('launchpad', 'App saved.') + } else { + const response = await axios.post(generateUrl(BASE), body) + if (response?.data?.app) { + this.apps.push(response.data.app) + } + this.notice = t('launchpad', 'App saved.') + } + this.closeForm() + } catch (err) { + this.error = this.failure(err, t('launchpad', 'The app could not be saved.')) + } finally { + this.busy = false + } + }, + + /** + * @param {object} app The entry to remove. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-administrators-keep-a-catalogue-of-approved-apps-req-acat-001 + */ + async remove(app) { + this.busy = true + this.error = '' + this.notice = '' + try { + await axios.delete(generateUrl(`${BASE}/${app.uuid}`)) + this.apps = this.apps.filter((entry) => entry.uuid !== app.uuid) + if (this.formMode === 'edit' && this.formUuid === app.uuid) { + this.closeForm() + } + } catch (err) { + this.error = this.failure(err, t('launchpad', 'The app could not be removed.')) + } finally { + this.busy = false + } + }, + + /** + * @param {object} request The request to decline. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + startDecline(request) { + if (this.formMode === 'approve') { + this.closeForm() + } + this.declining = request.uuid + this.declineNote = '' + }, + + /** @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 */ + cancelDecline() { + this.declining = '' + this.declineNote = '' + }, + + /** + * Decline a request; the note is required and goes to the requester. + * + * @param {object} request The open request. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-administrators-decide-on-requests-and-the-requester-hears-back-req-acat-004 + */ + async decline(request) { + const note = this.declineNote.trim() + if (note === '') { + return + } + this.busy = true + this.error = '' + this.notice = '' + try { + await axios.post(generateUrl(`${BASE}/requests/${request.uuid}/decline`), { note }) + this.requests = this.requests.filter((entry) => entry.uuid !== request.uuid) + this.cancelDecline() + this.notice = t('launchpad', 'The request was declined.') + } catch (err) { + this.error = this.failure(err, t('launchpad', 'The request could not be declined.')) + } finally { + this.busy = false + } + }, + + /** + * Store the optional manager group; clearing it stores none. + * + * @param {string|null} groupId The group, or null. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + async saveManagerGroup(groupId) { + this.error = '' + try { + const response = await axios.put(generateUrl(`${BASE}/settings`), { + managerGroup: groupId || '', + }) + this.managerGroup = response?.data?.managerGroup || null + } catch (err) { + this.error = this.failure(err, t('launchpad', 'The manager group could not be saved.')) + } + }, + + /** + * The message for a failed call: a decided request has its own text. + * + * @param {object} err The axios error. + * @param {string} fallback The translated fallback. + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/tasks.md#task-8 + */ + failure(err, fallback) { + if (err?.response?.status === 409) { + return t('launchpad', 'Someone already decided on this request.') + } + return fallback + }, + }, +} +</script> + +<style scoped> +.app-catalogue-tab { + display: flex; + flex-direction: column; + gap: 16px; + max-width: 760px; +} + +.app-catalogue-tab__section, +.app-catalogue-tab__form, +.app-catalogue-tab__decline { + display: flex; + flex-direction: column; + gap: 8px; +} + +.app-catalogue-tab__form { + padding: 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); +} + +.app-catalogue-tab__list { + display: flex; + flex-direction: column; + gap: 8px; + padding: 0; + margin: 0; + list-style: none; +} + +.app-catalogue-tab__item { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 8px; + padding: 8px 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); +} + +.app-catalogue-tab__item-text { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + overflow-wrap: anywhere; +} + +.app-catalogue-tab__actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.app-catalogue-tab__intro, +.app-catalogue-tab__empty { + color: var(--color-text-maxcontrast); +} + +.app-catalogue-tab__error { + color: var(--color-error-text); +} +</style> diff --git a/src/components/admin/tabs/CommunitiesTab.vue b/src/components/admin/tabs/CommunitiesTab.vue new file mode 100644 index 000000000..70ed804df --- /dev/null +++ b/src/components/admin/tabs/CommunitiesTab.vue @@ -0,0 +1,200 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="communities-tab" data-testid="communities-tab"> + <h3>{{ t('launchpad', 'Pinned communities') }}</h3> + <p class="communities-tab__intro"> + {{ + t( + 'launchpad', + 'The Communities widget lists the open Talk conversations each person may join. The conversations pinned here show first, marked as pinned by your organisation. Enter one Talk conversation token per line, at most 20. The token is the last part of the conversation link, after /call/.', + ) + }} + </p> + + <label class="communities-tab__label" for="launchpad-pinned-communities"> + {{ t('launchpad', 'Conversation tokens') }} + </label> + <textarea + id="launchpad-pinned-communities" + v-model="draft" + class="communities-tab__tokens" + rows="6" + data-testid="communities-tokens" + :aria-invalid="error !== '' ? 'true' : 'false'" + aria-describedby="launchpad-pinned-communities-status" /> + + <div class="communities-tab__actions"> + <NcButton + variant="primary" + :disabled="saving" + data-testid="communities-save" + @click="save"> + {{ t('launchpad', 'Save') }} + </NcButton> + <p + id="launchpad-pinned-communities-status" + class="communities-tab__status" + :class="{ 'communities-tab__status--error': error !== '' }" + role="status" + aria-live="polite"> + {{ status }} + </p> + </div> + </div> +</template> + +<script> +import { translate as t } from '@nextcloud/l10n' +import { NcButton } from '@nextcloud/vue' +import { api } from '../../../services/api.js' +import { logger } from '../../../utils/logger.js' + +/** Most conversations an administrator may pin (engagement-communities D3). */ +export const PINNED_COMMUNITIES_MAX = 20 + +/** + * The tokens of the textarea: one per line, blanks and duplicates dropped. + * + * @param {string} text The textarea text. + * @return {string[]} The tokens, in the order given. + */ +export function tokensOf(text) { + return [ + ...new Set( + String(text || '') + .split(/[\s,]+/) + .map((token) => token.trim()) + .filter((token) => token !== ''), + ), + ] +} + +/** + * CommunitiesTab: the administrator's list of pinned Talk conversations + * (openspec/changes/engagement-communities, REQ-COMM-003). The server + * validates the tokens; its refusal is shown here. + */ +export default { + name: 'CommunitiesTab', + + components: { NcButton }, + + data() { + return { + draft: '', + saving: false, + error: '', + saved: false, + } + }, + + computed: { + /** + * The line under the Save button: the refusal, or that it was saved. + * + * @return {string} The text. + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 + */ + status() { + if (this.error !== '') { + return this.error + } + return this.saved ? t('launchpad', 'Pinned communities saved.') : '' + }, + }, + + /** @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 */ + async created() { + try { + const response = await api.getAdminSettings() + const data = response?.data?.data ?? response?.data ?? {} + const pinned = Array.isArray(data.pinnedCommunities) ? data.pinnedCommunities : [] + this.draft = pinned.join('\n') + } catch (error) { + logger.error('Failed to load the pinned communities:', error) + } + }, + + methods: { + t, + + /** + * Save the pinned tokens. Too many is refused here; the token shape is + * the server's to judge, and its message is shown. + * + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-administrators-pin-official-communities-req-comm-003 + */ + async save() { + const tokens = tokensOf(this.draft) + this.saved = false + if (tokens.length > PINNED_COMMUNITIES_MAX) { + this.error = t('launchpad', 'At most {max} conversations can be pinned.', { + max: PINNED_COMMUNITIES_MAX, + }) + return + } + + this.saving = true + this.error = '' + try { + await api.updateAdminSettings({ pinnedCommunities: tokens }) + this.draft = tokens.join('\n') + this.saved = true + } catch (error) { + this.error = + error?.response?.data?.error + || t('launchpad', 'The pinned communities could not be saved.') + } finally { + this.saving = false + } + }, + }, +} +</script> + +<style scoped> +.communities-tab { + display: flex; + flex-direction: column; + gap: 8px; + max-width: 720px; +} + +.communities-tab__intro { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.communities-tab__label { + font-weight: bold; +} + +.communities-tab__tokens { + width: 100%; + font-family: var(--font-face-monospace, monospace); + background: var(--color-main-background); + color: var(--color-main-text); + border: 1px solid var(--color-border-dark); + border-radius: var(--border-radius); +} + +.communities-tab__actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; +} + +.communities-tab__status { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.communities-tab__status--error { + color: var(--color-error-text, var(--color-error)); +} +</style> diff --git a/src/components/admin/tabs/EmbedsTab.vue b/src/components/admin/tabs/EmbedsTab.vue new file mode 100644 index 000000000..a0c62c0f9 --- /dev/null +++ b/src/components/admin/tabs/EmbedsTab.vue @@ -0,0 +1,70 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="embeds-tab" data-test="embeds-tab"> + <p class="embeds-tab__intro"> + {{ t('launchpad', 'Embed tokens let other websites show a dashboard or widget without a Nextcloud login. Each token names what it shows, which sites may frame it and what viewers may do.') }} + </p> + <div class="embeds-tab__section"> + <EmbedTokenManager :defaults="defaults" /> + </div> + <div class="embeds-tab__section"> + <TenantThemeManager /> + </div> + </div> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import EmbedTokenManager from '../embed/EmbedTokenManager.vue' +import TenantThemeManager from '../embed/TenantThemeManager.vue' +import { embedDefaultsFrom } from '../../../utils/embedToken.js' + +/** + * EmbedsTab — Beheer ▸ Embeds: the embed token manager and the tenant + * theme manager (embedded-analytics task 40). The telemetry switch stays + * under Operations. A link from a dashboard or widget (`embedType`, + * `embedId`, `embedDashboard`) opens the create form for that subject. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + */ +export default { + name: 'EmbedsTab', + + components: { + EmbedTokenManager, + TenantThemeManager, + }, + + data() { + return { + defaults: embedDefaultsFrom(typeof window === 'undefined' ? '' : window.location.search), + } + }, + + methods: { + t, + }, +} +</script> + +<style scoped> +.embeds-tab { + display: flex; + flex-direction: column; + gap: 24px; +} + +.embeds-tab__intro { + color: var(--color-text-maxcontrast); + max-width: 760px; +} + +.embeds-tab__section { + border-top: 1px solid var(--color-border); + padding-top: 16px; +} +</style> diff --git a/src/components/admin/tabs/KioskTab.vue b/src/components/admin/tabs/KioskTab.vue index 38e1bc843..46737ee52 100644 --- a/src/components/admin/tabs/KioskTab.vue +++ b/src/components/admin/tabs/KioskTab.vue @@ -93,25 +93,29 @@ @update:open="formOpen = $event" @save="savePlaylist" /> - <RevokeKioskPlaylistDialog - :open="revokeTarget !== null" - :name="revokeTarget?.name ?? ''" - @update:open=" - (v) => { - if (!v) revokeTarget = null - } + <CnConfirmDialog + v-if="revokeTarget !== null" + :dialogTitle="t('launchpad', 'Revoke this playlist?')" + :message=" + t( + 'launchpad', + 'Screens showing {name} stop at their next check, and the link stops working for good.', + { name: revokeTarget.name ?? '' }, + ) " - @confirm="revoke" /> + :confirmLabel="t('launchpad', 'Revoke')" + variant="error" + @confirm="revoke" + @close="revokeTarget = null" /> </div> </template> <script> -import { NcButton } from '@conduction/nextcloud-vue' +import { CnConfirmDialog, NcButton } from '@conduction/nextcloud-vue' import { showSuccess } from '@nextcloud/dialogs' import { t } from '@nextcloud/l10n' import { generateUrl } from '@nextcloud/router' import KioskPlaylistDialog from '../../../dialogs/KioskPlaylistDialog.vue' -import RevokeKioskPlaylistDialog from '../../../dialogs/RevokeKioskPlaylistDialog.vue' import { api } from '../../../services/api.js' import { useKioskPlaylistStore } from '../../../stores/kioskPlaylists.js' @@ -128,7 +132,7 @@ export default { components: { KioskPlaylistDialog, NcButton, - RevokeKioskPlaylistDialog, + CnConfirmDialog, }, /** @spec openspec/specs/dashboard-kiosk-mode/spec.md */ diff --git a/src/components/admin/tabs/OperationsTab.vue b/src/components/admin/tabs/OperationsTab.vue index 94c1a6a35..ded346e65 100644 --- a/src/components/admin/tabs/OperationsTab.vue +++ b/src/components/admin/tabs/OperationsTab.vue @@ -14,6 +14,12 @@ <div class="operations-tab__section"> <LegacyWidgetBridgeToggle /> </div> + <div class="operations-tab__section"> + <EmbedTelemetryToggle /> + </div> + <div class="operations-tab__section"> + <ImageHostSettings /> + </div> <div class="operations-tab__section"> <DashboardExportImport /> </div> @@ -23,6 +29,10 @@ <div class="operations-tab__section"> <ConfluenceImport /> </div> + <!-- REQ-SHARE-016 (board LpBeheerOnderhoud): the Clean up block. --> + <div class="operations-tab__section"> + <LeaverHandoverSettings /> + </div> </div> </template> @@ -30,14 +40,18 @@ import ConfluenceImport from '../ConfluenceImport.vue' import DashboardBulkOperations from '../DashboardBulkOperations.vue' import DashboardExportImport from '../DashboardExportImport.vue' +import EmbedTelemetryToggle from '../EmbedTelemetryToggle.vue' import HealthPanel from '../HealthPanel.vue' +import ImageHostSettings from '../ImageHostSettings.vue' +import LeaverHandoverSettings from '../LeaverHandoverSettings.vue' import LegacyWidgetBridgeToggle from '../LegacyWidgetBridgeToggle.vue' import PrometheusMetricsPanel from '../PrometheusMetricsPanel.vue' /** * OperationsTab — Beheer ▸ Operations tab. Aggregates instance health * (prometheus-metrics spec), the Prometheus metrics panel, the legacy widget - * bridge toggle (legacy-widget-bridge spec), and the relocated export/import, + * bridge toggle (legacy-widget-bridge spec), the embed telemetry switch + * (embedded-analytics), the external image host allow-list (REQ-IMG-006), and the relocated export/import, * bulk-operations, and Confluence-import surfaces previously stacked inside * the monolithic `AdminSettings.vue`. */ @@ -48,9 +62,12 @@ export default { HealthPanel, PrometheusMetricsPanel, LegacyWidgetBridgeToggle, + EmbedTelemetryToggle, + ImageHostSettings, DashboardExportImport, DashboardBulkOperations, ConfluenceImport, + LeaverHandoverSettings, }, } </script> diff --git a/src/components/admin/tabs/OrgNavigationTab.vue b/src/components/admin/tabs/OrgNavigationTab.vue index 3a3c00e18..3ffa404c1 100644 --- a/src/components/admin/tabs/OrgNavigationTab.vue +++ b/src/components/admin/tabs/OrgNavigationTab.vue @@ -11,6 +11,7 @@ <script> import OrgNavigationEditor from '../OrgNavigationEditor.vue' +import { LIST_PROP } from '../../../constants/propDefinitions.js' /** * OrgNavigationTab — Beheer ▸ Org navigation tab. Hosts the relocated @@ -26,10 +27,7 @@ export default { props: { /** Groups passed through to the editor for its group picker. */ - groups: { - type: Array, - default: () => [], - }, + groups: LIST_PROP, }, } </script> diff --git a/src/components/admin/tabs/ProfileFieldsTab.vue b/src/components/admin/tabs/ProfileFieldsTab.vue new file mode 100644 index 000000000..1686e2e79 --- /dev/null +++ b/src/components/admin/tabs/ProfileFieldsTab.vue @@ -0,0 +1,296 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="profile-fields-tab" data-testid="profile-fields-tab"> + <h3>{{ t('launchpad', 'Profile fields') }}</h3> + <p class="profile-fields-tab__intro"> + {{ + t( + 'launchpad', + 'Extra fields on colleague cards in the people widget, such as office location or expertise. People fill them in on their personal settings, or they come from an LDAP attribute.', + ) + }} + </p> + + <p v-if="loading"> + {{ t('launchpad', 'Loading…') }} + </p> + <form v-else class="profile-fields-tab__form" @submit.prevent="save"> + <fieldset + v-for="(field, index) in fields" + :key="index" + class="profile-fields-tab__field"> + <legend>{{ field.label || t('launchpad', 'New field') }}</legend> + <label> + {{ t('launchpad', 'Label') }} + <input + v-model="field.label" + type="text" + maxlength="64" + required /> + </label> + <label> + {{ t('launchpad', 'Key') }} + <input + v-model="field.key" + type="text" + maxlength="32" + pattern="[a-z][a-z0-9_]*" + required /> + </label> + <label> + {{ t('launchpad', 'Type') }} + <select v-model="field.type"> + <option value="text">{{ t('launchpad', 'Text') }}</option> + <option value="tags">{{ t('launchpad', 'Tags') }}</option> + <option value="date">{{ t('launchpad', 'Date') }}</option> + </select> + </label> + <label> + {{ t('launchpad', 'Filled by') }} + <select v-model="field.source"> + <option value="self"> + {{ t('launchpad', 'The person') }} + </option> + <option value="ldap"> + {{ t('launchpad', 'LDAP attribute') }} + </option> + </select> + </label> + <label v-if="field.source === 'ldap'"> + {{ t('launchpad', 'LDAP attribute') }} + <input + v-model="field.ldapAttribute" + type="text" + placeholder="physicalDeliveryOfficeName" + required /> + </label> + <label> + {{ t('launchpad', 'Who may see it') }} + <select v-model="field.visibility"> + <option value="everyone"> + {{ t('launchpad', 'Everyone') }} + </option> + <option value="groups"> + {{ t('launchpad', 'People in the same group') }} + </option> + </select> + </label> + <label class="profile-fields-tab__check"> + <input v-model="field.searchable" type="checkbox" /> + {{ t('launchpad', 'Searchable in the people widget') }} + </label> + <label class="profile-fields-tab__check"> + <input v-model="field.shownInWidget" type="checkbox" /> + {{ t('launchpad', 'Shown on the card') }} + </label> + <!-- REQ-ACK-010: one field is the Department of read confirmations. --> + <label class="profile-fields-tab__check"> + <input + :checked="field.department === true" + type="checkbox" + data-testid="profile-field-department" + @change="setDepartment(index, $event.target.checked)" /> + {{ t('launchpad', 'Department in read confirmations') }} + </label> + <!-- REQ-PEX-005: one date field is the start date of new colleagues. --> + <label v-if="field.type === 'date'" class="profile-fields-tab__check"> + <input + :checked="field.startDate === true" + type="checkbox" + data-testid="profile-field-start-date" + @change="setStartDate(index, $event.target.checked)" /> + {{ t('launchpad', 'Start date of new colleagues') }} + </label> + <NcButton variant="tertiary" @click="remove(index)"> + {{ t('launchpad', 'Remove field') }} + </NcButton> + </fieldset> + + <p v-if="error" class="profile-fields-tab__error" role="alert"> + {{ error }} + </p> + <p v-if="saved" role="status"> + {{ t('launchpad', 'Profile fields saved.') }} + </p> + + <div class="profile-fields-tab__actions"> + <NcButton :disabled="fields.length >= maxFields" @click="add"> + {{ t('launchpad', 'Add field') }} + </NcButton> + <NcButton type="submit" variant="primary" :disabled="saving"> + {{ t('launchpad', 'Save profile fields') }} + </NcButton> + </div> + </form> + </div> +</template> + +<script> +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' +import { NcButton } from '@nextcloud/vue' + +const MAX_FIELDS = 10 +const URL = '/apps/launchpad/api/profile-fields/definitions' + +/** + * ProfileFieldsTab: the administrator defines up to ten custom profile + * fields for the people widget (REQ-PEX-001). + * + * @spec openspec/specs/people-widget/spec.md + */ +export default { + name: 'ProfileFieldsTab', + + components: { NcButton }, + + data() { + return { + fields: [], + loading: true, + saving: false, + error: '', + saved: false, + maxFields: MAX_FIELDS, + } + }, + + /** @spec openspec/specs/people-widget/spec.md */ + async mounted() { + try { + const response = await axios.get(generateUrl(URL)) + this.fields = response?.data?.fields || [] + } catch { + this.error = t('launchpad', 'The profile fields could not be loaded.') + } finally { + this.loading = false + } + }, + + methods: { + /** @spec openspec/specs/people-widget/spec.md */ + add() { + if (this.fields.length >= MAX_FIELDS) { + return + } + this.fields.push({ + key: '', + label: '', + type: 'text', + source: 'self', + ldapAttribute: '', + searchable: true, + shownInWidget: true, + visibility: 'everyone', + department: false, + startDate: false, + }) + }, + + /** + * Mark one field as the department of read confirmations; marking it + * unmarks every other field, so at most one is (REQ-ACK-010). + * + * @param {number} index Position in the list. + * @param {boolean} checked Whether it is now the department. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + setDepartment(index, checked) { + this.fields = this.fields.map((field, position) => ({ + ...field, + department: position === index ? checked : (checked ? false : field.department === true), + })) + }, + + /** + * Mark one date field as the start date of new colleagues; marking it + * unmarks every other field, so at most one is (REQ-PEX-005). + * + * @param {number} index Position in the list. + * @param {boolean} checked Whether it is now the start date. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-a-profile-field-can-hold-a-start-date-req-pex-005 + */ + setStartDate(index, checked) { + this.fields = this.fields.map((field, position) => ({ + ...field, + startDate: position === index ? checked : (checked ? false : field.startDate === true), + })) + }, + + /** + * Remove the field at a position. + * + * @param {number} index Position in the list. + * @spec openspec/specs/people-widget/spec.md + */ + remove(index) { + this.fields.splice(index, 1) + }, + + /** @spec openspec/specs/people-widget/spec.md */ + async save() { + this.saving = true + this.error = '' + this.saved = false + try { + const response = await axios.put(generateUrl(URL), { + fields: this.fields, + }) + this.fields = response?.data?.fields || [] + this.saved = true + } catch (err) { + this.error = + err?.response?.data?.error + || t('launchpad', 'The profile fields could not be saved.') + } finally { + this.saving = false + } + }, + }, +} +</script> + +<style scoped> +.profile-fields-tab__form { + display: flex; + flex-direction: column; + gap: 12px; + max-width: 640px; +} + +.profile-fields-tab__field { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 8px; + padding: 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); +} + +.profile-fields-tab__field label { + display: flex; + flex-direction: column; + gap: 2px; +} + +.profile-fields-tab__field .profile-fields-tab__check { + flex-direction: row; + align-items: center; + gap: 6px; +} + +.profile-fields-tab__actions { + display: flex; + gap: 8px; +} + +.profile-fields-tab__error { + color: var(--color-error-text); +} +</style> diff --git a/src/components/admin/tabs/SearchShortcutsTab.vue b/src/components/admin/tabs/SearchShortcutsTab.vue new file mode 100644 index 000000000..7df55c5ea --- /dev/null +++ b/src/components/admin/tabs/SearchShortcutsTab.vue @@ -0,0 +1,217 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <div class="search-shortcuts-tab" data-testid="search-shortcuts-tab"> + <h3>{{ t('launchpad', 'Search shortcuts') }}</h3> + <p class="search-shortcuts-tab__intro"> + {{ + t( + 'launchpad', + 'A search that starts with a prefix, such as !t printer, goes straight to that site in a new tab. Typing ? in a search box lists the shortcuts.', + ) + }} + </p> + + <p v-if="loading"> + {{ t('launchpad', 'Loading…') }} + </p> + <form v-else class="search-shortcuts-tab__form" @submit.prevent="save"> + <table v-if="shortcuts.length > 0" class="search-shortcuts-tab__table"> + <thead> + <tr> + <th scope="col"> + {{ t('launchpad', 'Prefix') }} + </th> + <th scope="col"> + {{ t('launchpad', 'Name') }} + </th> + <th scope="col"> + {{ t('launchpad', 'Address with {query}') }} + </th> + <th scope="col"> + <span class="hidden-visually">{{ + t('launchpad', 'Actions') + }}</span> + </th> + </tr> + </thead> + <tbody> + <tr v-for="(shortcut, index) in shortcuts" :key="index"> + <td> + <input + v-model="shortcut.prefix" + type="text" + maxlength="11" + pattern="![A-Za-z0-9]{1,10}" + placeholder="!t" + :aria-label="t('launchpad', 'Prefix')" + required /> + </td> + <td> + <input + v-model="shortcut.name" + type="text" + maxlength="64" + placeholder="TOPdesk" + :aria-label="t('launchpad', 'Name')" + required /> + </td> + <td> + <input + v-model="shortcut.urlTemplate" + type="url" + placeholder="https://example.org/search?q={query}" + :aria-label="t('launchpad', 'Address with {query}')" + required /> + </td> + <td> + <NcButton variant="tertiary" @click="remove(index)"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </td> + </tr> + </tbody> + </table> + <p v-else> + {{ t('launchpad', 'No search shortcuts yet.') }} + </p> + + <p v-if="error" class="search-shortcuts-tab__error" role="alert"> + {{ error }} + </p> + <p v-if="saved" role="status"> + {{ t('launchpad', 'Search shortcuts saved.') }} + </p> + + <div class="search-shortcuts-tab__actions"> + <NcButton :disabled="shortcuts.length >= maxShortcuts" @click="add"> + {{ t('launchpad', 'Add shortcut') }} + </NcButton> + <NcButton type="submit" variant="primary" :disabled="saving"> + {{ t('launchpad', 'Save search shortcuts') }} + </NcButton> + </div> + </form> + </div> +</template> + +<script> +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' +import { NcButton } from '@nextcloud/vue' + +const MAX_SHORTCUTS = 30 +const URL = '/apps/launchpad/api/admin/search-shortcuts' + +/** + * SearchShortcutsTab: the administrator's search shortcuts (REQ-SPX-001). + * The server validates every entry; its refusal is shown as is. + * + * @spec openspec/specs/tile-quick-search/spec.md + */ +export default { + name: 'SearchShortcutsTab', + + components: { NcButton }, + + data() { + return { + shortcuts: [], + loading: true, + saving: false, + error: '', + saved: false, + maxShortcuts: MAX_SHORTCUTS, + } + }, + + /** @spec openspec/specs/tile-quick-search/spec.md */ + async mounted() { + try { + const response = await axios.get(generateUrl(URL)) + this.shortcuts = response?.data?.shortcuts || [] + } catch { + this.error = t('launchpad', 'The search shortcuts could not be loaded.') + } finally { + this.loading = false + } + }, + + methods: { + /** @spec openspec/specs/tile-quick-search/spec.md */ + add() { + if (this.shortcuts.length < MAX_SHORTCUTS) { + this.shortcuts.push({ prefix: '', name: '', urlTemplate: '' }) + } + }, + + /** + * Remove the shortcut at a position. + * + * @param {number} index Position in the list. + * @spec openspec/specs/tile-quick-search/spec.md + */ + remove(index) { + this.shortcuts.splice(index, 1) + }, + + /** @spec openspec/specs/tile-quick-search/spec.md */ + async save() { + this.saving = true + this.error = '' + this.saved = false + try { + const response = await axios.put(generateUrl(URL), { + shortcuts: this.shortcuts, + }) + this.shortcuts = response?.data?.shortcuts || [] + this.saved = true + } catch (err) { + this.error = + err?.response?.data?.error + || t('launchpad', 'The search shortcuts could not be saved.') + } finally { + this.saving = false + } + }, + }, +} +</script> + +<style scoped> +.search-shortcuts-tab__form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.search-shortcuts-tab__table { + width: 100%; + border-collapse: collapse; +} + +.search-shortcuts-tab__table th { + text-align: start; + padding: 4px; +} + +.search-shortcuts-tab__table td { + padding: 4px; +} + +.search-shortcuts-tab__table input { + width: 100%; +} + +.search-shortcuts-tab__actions { + display: flex; + gap: 8px; +} + +.search-shortcuts-tab__error { + color: var(--color-error-text); +} +</style> diff --git a/src/components/admin/tabs/SharingTab.vue b/src/components/admin/tabs/SharingTab.vue index 30472493b..0b8172873 100644 --- a/src/components/admin/tabs/SharingTab.vue +++ b/src/components/admin/tabs/SharingTab.vue @@ -7,31 +7,40 @@ <div class="sharing-tab" data-test="sharing-tab"> <DashboardSharingPolicy :groups="groups" /> <div class="sharing-tab__spacer" /> + <AnnouncementEditorsPolicy :groups="groups" /> + <div class="sharing-tab__spacer" /> <GroupPriorityOrder :initialActive="configuredGroups" /> <div class="sharing-tab__spacer" /> <DashboardRegistrySettings /> + <div class="sharing-tab__spacer" /> + <PublicStartPageSettings /> </div> </template> <script> +import AnnouncementEditorsPolicy from '../AnnouncementEditorsPolicy.vue' import DashboardRegistrySettings from '../DashboardRegistrySettings.vue' import DashboardSharingPolicy from '../DashboardSharingPolicy.vue' import GroupPriorityOrder from '../GroupPriorityOrder.vue' +import PublicStartPageSettings from '../PublicStartPageSettings.vue' /** * SharingTab — Beheer ▸ Sharing tab (dashboard-sharing spec). Hosts the * org-wide sharing defaults plus the relocated `GroupPriorityOrder` editor * (group resolution order is a sharing concern), and the dashboard registry * connection, which is how dashboards are shared ACROSS instances - * (dashboard-store spec). + * (dashboard-store spec), and the public start page signed-out visitors + * see instead of the login form (sharing-public-start-page). */ export default { name: 'SharingTab', components: { + AnnouncementEditorsPolicy, DashboardRegistrySettings, DashboardSharingPolicy, GroupPriorityOrder, + PublicStartPageSettings, }, props: { diff --git a/src/components/admin/tabs/TemplatesPage.vue b/src/components/admin/tabs/TemplatesPage.vue index f3311a2ce..167368a9d 100644 --- a/src/components/admin/tabs/TemplatesPage.vue +++ b/src/components/admin/tabs/TemplatesPage.vue @@ -27,6 +27,101 @@ }} </p> + <section + v-if="shippedTemplates.length > 0" + class="launchpad-admin__shipped" + data-testid="admin-shipped-templates" + :aria-label="t('launchpad', 'Ready-made templates')"> + <h4>{{ t('launchpad', 'Ready-made templates') }}</h4> + <p class="launchpad-admin__hint"> + {{ + t( + 'launchpad', + 'Add a template that comes with LaunchPad. Then edit it to choose who gets it.', + ) + }} + </p> + <div + v-for="shipped in shippedTemplates" + :key="shipped.id" + class="launchpad-admin__template" + :data-testid="`admin-shipped-template-${shipped.id}`"> + <div class="launchpad-admin__template-info"> + <strong>{{ shipped.name }}</strong> + <span class="launchpad-admin__template-groups">{{ + shipped.description + }}</span> + <span + v-if="shipped.registers && shipped.registers.length > 0" + class="launchpad-admin__template-groups" + data-testid="admin-shipped-template-registers"> + {{ + t( + 'launchpad', + 'Its lists read these registers: {registers}. A list whose register is not on this instance is hidden for members.', + { registers: shipped.registers.join(', ') }, + ) + }} + </span> + <span + v-if="shipped.missingWidgets.length > 0" + class="launchpad-admin__template-groups" + data-testid="admin-shipped-template-missing"> + {{ + t( + 'launchpad', + 'No app here provides these widgets, so they will show empty: {widgets}', + { widgets: shipped.missingWidgets.join(', ') }, + ) + }} + </span> + </div> + <div class="launchpad-admin__template-actions"> + <NcButton + v-if="shipped.isInstalled && shipped.updateAvailable" + variant="secondary" + data-testid="admin-shipped-template-update" + @click="openShippedUpdate(shipped)"> + {{ + t('launchpad', 'Update to version {version}', { + version: shipped.version, + }) + }} + </NcButton> + <span + v-if="shipped.isInstalled" + class="launchpad-admin__badge" + data-testid="admin-shipped-template-added"> + {{ t('launchpad', 'Added') }} + </span> + <NcButton + v-else + variant="secondary" + :disabled="installingId !== null" + data-testid="admin-shipped-template-add" + @click="installShipped(shipped)"> + {{ t('launchpad', 'Add template') }} + </NcButton> + </div> + </div> + </section> + + <p + v-if="statusMessage !== ''" + class="launchpad-admin__status" + role="status" + data-testid="admin-templates-status"> + {{ statusMessage }} + </p> + + <p + v-if="errorMessage !== ''" + class="launchpad-admin__error" + role="alert" + data-testid="admin-templates-error"> + {{ errorMessage }} + </p> + <div v-if="templates.length === 0" class="launchpad-admin__empty"> <NcEmptyContent :description="t('launchpad', 'No templates yet')"> <template #icon> @@ -39,7 +134,8 @@ <div v-for="template in templates" :key="template.id" - class="launchpad-admin__template"> + class="launchpad-admin__template" + :data-testid="`admin-template-row-${template.id}`"> <div class="launchpad-admin__template-info"> <CnDashboardIcon :name="template.icon" :size="20" /> <strong>{{ template.name }}</strong> @@ -55,7 +151,13 @@ variant="secondary" data-testid="admin-resync-template" @click="openResyncModal(template)"> - {{ t('launchpad', 'Re-sync to existing copies') }} + {{ t('launchpad', 'Push changes') }} + </NcButton> + <NcButton + variant="secondary" + data-testid="admin-download-template" + @click="downloadTemplate(template)"> + {{ t('launchpad', 'Download') }} </NcButton> <NcButton variant="secondary" @click="editTemplate(template)"> {{ t('launchpad', 'Edit') }} @@ -73,6 +175,12 @@ @close="closeResyncModal" @resynced="closeResyncModal" /> + <ShippedTemplateUpdateDialog + :open="updatingShipped !== null" + :shipped="updatingShipped" + @update:open="closeShippedUpdate" + @updated="onShippedUpdated" /> + <TemplateEditorModal :open="isEditorOpen" :template="editingTemplate" @@ -86,6 +194,7 @@ import { CnDashboardIcon, NcButton, NcEmptyContent } from '@conduction/nextcloud import { t } from '@nextcloud/l10n' import Plus from 'vue-material-design-icons/Plus.vue' import ViewDashboard from 'vue-material-design-icons/ViewDashboard.vue' +import ShippedTemplateUpdateDialog from '../../../dialogs/ShippedTemplateUpdateDialog.vue' import TemplateEditorModal from '../../../modals/TemplateEditorModal.vue' import TemplateResyncModal from '../../../modals/TemplateResyncModal.vue' import { api } from '../../../services/api.js' @@ -112,11 +221,17 @@ export default { CnDashboardIcon, TemplateResyncModal, TemplateEditorModal, + ShippedTemplateUpdateDialog, }, data() { return { templates: [], + shippedTemplates: [], + installingId: null, + errorMessage: '', + statusMessage: '', + updatingShipped: null, isEditorOpen: false, editingTemplate: null, resyncingTemplate: null, @@ -126,6 +241,7 @@ export default { /** @spec openspec/specs/admin-templates/spec.md */ created() { this.loadTemplates() + this.loadShippedTemplates() }, methods: { @@ -141,6 +257,121 @@ export default { } }, + /** + * Load the templates LaunchPad ships with. A failure hides the + * section and says so, the list of templates below still works. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + async loadShippedTemplates() { + try { + const { data } = await api.getShippedTemplates() + this.shippedTemplates = Array.isArray(data) ? data : [] + } catch (error) { + logger.error('Failed to load shipped templates:', error) + this.errorMessage = t( + 'launchpad', + 'The ready-made templates could not be loaded.', + ) + } + }, + + /** + * Add a shipped template, then show it in the list. + * + * @param {object} shipped The shipped template to add. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + async installShipped(shipped) { + this.installingId = shipped.id + this.errorMessage = '' + try { + await api.installShippedTemplate(shipped.id) + await Promise.all([ + this.loadTemplates(), + this.loadShippedTemplates(), + ]) + } catch (error) { + logger.error('Failed to add shipped template:', error) + this.errorMessage = t( + 'launchpad', + 'The template "{name}" could not be added.', + { name: shipped.name }, + ) + } finally { + this.installingId = null + } + }, + + /** + * Open the dialog that shows what updating an installed ready-made + * template changes. + * + * @param {object} shipped The shipped template to update. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + openShippedUpdate(shipped) { + this.statusMessage = '' + this.updatingShipped = shipped + }, + + /** @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 */ + closeShippedUpdate() { + this.updatingShipped = null + }, + + /** + * The update ran: say what it did and show the new state. + * + * @param {object} result The update result from the server. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + async onShippedUpdated(result) { + this.updatingShipped = null + this.statusMessage = t( + 'launchpad', + 'Updated "{name}" to version {version}. Members with a copy: {count}.', + { + name: result.name, + version: result.version, + count: result.copies, + }, + ) + await Promise.all([this.loadTemplates(), this.loadShippedTemplates()]) + }, + + /** + * Download one template as an archive that another LaunchPad can + * import (REQ-EXIM-012). + * + * @param {object} template The template to download. + * @spec openspec/specs/dashboard-export-import/spec.md#req-exim-012 + */ + async downloadTemplate(template) { + this.errorMessage = '' + try { + const response = await api.exportDashboards({ + scope: 'dashboard', + dashboardUuid: template.uuid, + }) + const url = window.URL.createObjectURL(response.data) + const link = document.createElement('a') + link.href = url + link.download = `launchpad-template-${template.slug || template.uuid}.zip` + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + window.URL.revokeObjectURL(url) + } catch (error) { + logger.error('Failed to download template:', error) + this.errorMessage = t( + 'launchpad', + 'The template "{name}" could not be downloaded.', + { name: template.name }, + ) + } + }, + /** @spec openspec/specs/admin-templates/spec.md */ createTemplate() { this.editingTemplate = null @@ -290,4 +521,21 @@ export default { .launchpad-admin__empty { padding: 48px 0; } + +.launchpad-admin__shipped { + margin-bottom: 24px; +} + +.launchpad-admin__shipped h4 { + margin: 0 0 4px; +} + +.launchpad-admin__status { + margin-bottom: 16px; +} + +.launchpad-admin__error { + color: var(--color-error); + margin-bottom: 16px; +} </style> diff --git a/src/components/admin/tabs/__tests__/AppCatalogueTab.spec.js b/src/components/admin/tabs/__tests__/AppCatalogueTab.spec.js new file mode 100644 index 000000000..4d3a39d10 --- /dev/null +++ b/src/components/admin/tabs/__tests__/AppCatalogueTab.spec.js @@ -0,0 +1,269 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `AppCatalogueTab.vue` (REQ-ACAT-001, REQ-ACAT-004): + * the administrator's catalogue and open requests load, an entry is added + * for a group, approving opens the form prefilled with the requested name + * and saves through the approve call, declining needs a note, and the + * manager group is stored. + */ + +import axios from '@nextcloud/axios' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import AppCatalogueTab from '../AppCatalogueTab.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => path, +})) + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) +const stubs = { + NcButton: { + props: ['disabled'], + emits: ['click'], + template: + '<button :type="$attrs.type || \'button\'" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcTextField: { + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: + '<label>{{ label }}<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" /></label>', + }, + NcSelect: { + props: ['modelValue', 'inputLabel', 'options'], + emits: ['update:modelValue'], + template: '<div class="nc-select" :data-label="inputLabel" />', + }, +} + +const ZAAK = { + uuid: 'app-1', + name: 'Zaaksysteem', + description: '', + icon: '', + iconType: 'class', + linkType: 'url', + linkValue: 'https://zaken.example.nl', + targetGroups: ['burgerzaken'], +} +const KAART = { + uuid: 'req-1', + requestedBy: 'pieter', + appName: 'Kaartviewer', + purpose: 'Ik moet percelen bekijken bij vergunningen', + status: 'open', +} +const GROUPS = [ + { id: 'burgerzaken', displayName: 'Burgerzaken' }, + { id: 'admin', displayName: 'admin' }, +] + +/** + * Mount the tab on a loaded catalogue. + * + * @param {object} data The admin index response. + * @return {Promise<object>} The wrapper. + */ +async function mountTab(data) { + axios.get.mockResolvedValue({ data }) + const wrapper = mount(AppCatalogueTab, { + props: { groups: GROUPS }, + global: { stubs }, + }) + await settle() + await settle() + return wrapper +} + +function button (wrapper, text) { + return wrapper.findAll('button').find((candidate) => candidate.text() === text) +} +function field (wrapper, label) { + return wrapper.findAll('label').find((candidate) => candidate.text() === label).find('input') +} + +describe('AppCatalogueTab', () => { + beforeEach(() => { + axios.get.mockReset() + axios.post.mockReset() + axios.put.mockReset() + axios.delete.mockReset() + }) + + it('lists the entries with their group names and the open requests', async () => { + const wrapper = await mountTab({ + apps: [ZAAK, { ...ZAAK, uuid: 'app-2', name: 'Agenda', targetGroups: [] }], + requests: [KAART], + managerGroup: '', + }) + + expect(axios.get).toHaveBeenCalledWith('/apps/launchpad/api/admin/catalogue') + const entries = wrapper.findAll('[data-testid="app-catalogue-entry"]') + expect(entries).toHaveLength(2) + expect(entries[0].text()).toContain('Zaaksysteem') + expect(entries[0].find('[data-testid="app-catalogue-entry-groups"]').text()).toBe('Burgerzaken') + expect(entries[1].find('[data-testid="app-catalogue-entry-groups"]').text()).toBe('Everyone') + const request = wrapper.find('[data-testid="app-catalogue-request"]') + expect(request.text()).toContain('Kaartviewer') + expect(request.text()).toContain('Asked by pieter') + }) + + it('labels every group picker', async () => { + const wrapper = await mountTab({ apps: [], requests: [], managerGroup: '' }) + await button(wrapper, 'Add app').trigger('click') + + const labels = wrapper.findAll('.nc-select').map((select) => select.attributes('data-label')) + expect(labels).toEqual(['Address type', 'Visible to groups', 'Catalogue manager group']) + }) + + it('adds an app for one group and lists it', async () => { + const wrapper = await mountTab({ apps: [], requests: [], managerGroup: '' }) + axios.post.mockImplementation((url, body) => + Promise.resolve({ data: { app: { ...body, uuid: 'new-1' } } }), + ) + + await button(wrapper, 'Add app').trigger('click') + await field(wrapper, 'Name').setValue('Zaaksysteem') + await field(wrapper, 'Web address').setValue('https://zaken.example.nl') + wrapper.vm.form.targetGroups = ['burgerzaken'] + await wrapper.find('[data-testid="app-catalogue-form"]').trigger('submit') + await settle() + + expect(axios.post).toHaveBeenCalledWith('/apps/launchpad/api/admin/catalogue', { + name: 'Zaaksysteem', + description: '', + icon: '', + iconType: 'class', + linkType: 'url', + linkValue: 'https://zaken.example.nl', + targetGroups: ['burgerzaken'], + }) + expect(wrapper.find('[data-testid="app-catalogue-form"]').exists()).toBe(false) + const entry = wrapper.find('[data-testid="app-catalogue-entry"]') + expect(entry.find('[data-testid="app-catalogue-entry-groups"]').text()).toBe('Burgerzaken') + }) + + it('edits an entry through the update call', async () => { + const wrapper = await mountTab({ apps: [ZAAK], requests: [], managerGroup: '' }) + axios.put.mockImplementation((url, body) => + Promise.resolve({ data: { app: { ...ZAAK, ...body } } }), + ) + + await button(wrapper, 'Edit').trigger('click') + expect(field(wrapper, 'Name').element.value).toBe('Zaaksysteem') + await field(wrapper, 'Name').setValue('Zaken') + await wrapper.find('[data-testid="app-catalogue-form"]').trigger('submit') + await settle() + + expect(axios.put.mock.calls[0][0]).toBe('/apps/launchpad/api/admin/catalogue/app-1') + expect(axios.put.mock.calls[0][1].name).toBe('Zaken') + expect(wrapper.find('[data-testid="app-catalogue-entry"]').text()).toContain('Zaken') + }) + + it('removes an entry', async () => { + const wrapper = await mountTab({ apps: [ZAAK], requests: [], managerGroup: '' }) + axios.delete.mockResolvedValue({ data: { deleted: true } }) + + await button(wrapper, 'Remove').trigger('click') + await settle() + + expect(axios.delete).toHaveBeenCalledWith('/apps/launchpad/api/admin/catalogue/app-1') + expect(wrapper.findAll('[data-testid="app-catalogue-entry"]')).toHaveLength(0) + }) + + it('approves a request through the prefilled form and adds the entry', async () => { + const wrapper = await mountTab({ apps: [], requests: [KAART], managerGroup: '' }) + axios.post.mockImplementation((url, body) => + Promise.resolve({ data: { request: { ...KAART, status: 'approved' }, app: { ...body, uuid: 'new-2' } } }), + ) + + await button(wrapper, 'Approve').trigger('click') + expect(wrapper.find('[data-testid="app-catalogue-form"] h4').text()).toBe('Approve request') + expect(field(wrapper, 'Name').element.value).toBe('Kaartviewer') + await field(wrapper, 'Web address').setValue('https://kaart.example.nl') + await wrapper.find('[data-testid="app-catalogue-form"]').trigger('submit') + await settle() + + expect(axios.post.mock.calls[0][0]).toBe( + '/apps/launchpad/api/admin/catalogue/requests/req-1/approve', + ) + expect(axios.post.mock.calls[0][1]).toMatchObject({ + name: 'Kaartviewer', + linkValue: 'https://kaart.example.nl', + }) + expect(wrapper.findAll('[data-testid="app-catalogue-request"]')).toHaveLength(0) + expect(wrapper.find('[data-testid="app-catalogue-entry"]').text()).toContain('Kaartviewer') + expect(wrapper.find('[data-testid="app-catalogue-notice"]').text()).toBe( + 'Kaartviewer is now in the app catalogue', + ) + }) + + it('declines a request only with a note', async () => { + const wrapper = await mountTab({ apps: [], requests: [KAART], managerGroup: '' }) + axios.post.mockResolvedValue({ data: { request: { ...KAART, status: 'declined' } } }) + + await button(wrapper, 'Decline').trigger('click') + expect(button(wrapper, 'Decline request').attributes('disabled')).toBeDefined() + await field(wrapper, 'Why is it declined?').setValue('Gebruik de kaartlaag in het zaaksysteem') + expect(button(wrapper, 'Decline request').attributes('disabled')).toBeUndefined() + await wrapper.find('.app-catalogue-tab__decline').trigger('submit') + await settle() + + expect(axios.post).toHaveBeenCalledWith( + '/apps/launchpad/api/admin/catalogue/requests/req-1/decline', + { note: 'Gebruik de kaartlaag in het zaaksysteem' }, + ) + expect(wrapper.findAll('[data-testid="app-catalogue-request"]')).toHaveLength(0) + expect(wrapper.find('[data-testid="app-catalogue-notice"]').text()).toBe('The request was declined.') + }) + + it('says when someone else already decided on the request', async () => { + const wrapper = await mountTab({ apps: [], requests: [KAART], managerGroup: '' }) + axios.post.mockRejectedValue({ response: { status: 409, data: { code: 'request_not_open' } } }) + + await button(wrapper, 'Decline').trigger('click') + await field(wrapper, 'Why is it declined?').setValue('Nee') + await wrapper.find('.app-catalogue-tab__decline').trigger('submit') + await settle() + + expect(wrapper.find('[data-testid="app-catalogue-error"]').text()).toBe( + 'Someone already decided on this request.', + ) + expect(wrapper.findAll('[data-testid="app-catalogue-request"]')).toHaveLength(1) + }) + + it('stores the manager group, and none when cleared', async () => { + const wrapper = await mountTab({ apps: [], requests: [], managerGroup: '' }) + axios.put.mockImplementation((url, body) => Promise.resolve({ data: { managerGroup: body.managerGroup } })) + + await wrapper.vm.saveManagerGroup('burgerzaken') + expect(axios.put).toHaveBeenLastCalledWith('/apps/launchpad/api/admin/catalogue/settings', { + managerGroup: 'burgerzaken', + }) + expect(wrapper.vm.managerGroup).toBe('burgerzaken') + + await wrapper.vm.saveManagerGroup(null) + expect(axios.put).toHaveBeenLastCalledWith('/apps/launchpad/api/admin/catalogue/settings', { + managerGroup: '', + }) + expect(wrapper.vm.managerGroup).toBeNull() + }) + + it('shows an error when the catalogue cannot be loaded', async () => { + axios.get.mockRejectedValue(new Error('down')) + const wrapper = mount(AppCatalogueTab, { props: { groups: GROUPS }, global: { stubs } }) + await settle() + await settle() + + expect(wrapper.find('[data-testid="app-catalogue-error"]').text()).toBe( + 'The app catalogue could not be loaded.', + ) + }) +}) diff --git a/src/components/admin/tabs/__tests__/CommunitiesTab.spec.js b/src/components/admin/tabs/__tests__/CommunitiesTab.spec.js new file mode 100644 index 000000000..3e3317a90 --- /dev/null +++ b/src/components/admin/tabs/__tests__/CommunitiesTab.spec.js @@ -0,0 +1,96 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * CommunitiesTab: an administrator pins up to 20 Talk conversations + * (openspec/changes/engagement-communities REQ-COMM-003). + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const getAdminSettings = vi.fn() +const updateAdminSettings = vi.fn() +vi.mock('../../../../services/api.js', () => ({ + api: { + getAdminSettings: (...args) => getAdminSettings(...args), + updateAdminSettings: (...args) => updateAdminSettings(...args), + }, +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +import CommunitiesTab, { tokensOf } from '../CommunitiesTab.vue' + +const NcButton = { + name: 'NcButton', + props: ['disabled', 'variant'], + emits: ['click'], + template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', +} + +/** + * Mount the tab over the stored pinned list. + * + * @param {Array<string>} pinned The stored tokens. + * @return {Promise<object>} The wrapper. + */ +async function mountTab(pinned) { + getAdminSettings.mockResolvedValue({ data: { data: { pinnedCommunities: pinned } } }) + const wrapper = mount(CommunitiesTab, { global: { stubs: { NcButton } } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + getAdminSettings.mockReset() + updateAdminSettings.mockReset() +}) + +describe('CommunitiesTab', () => { + it('shows the stored tokens one per line', async () => { + const wrapper = await mountTab(['vraagict', 'duurzaam42']) + + expect(wrapper.find('textarea').element.value).toBe('vraagict\nduurzaam42') + }) + + it('saves the tokens as a list, blanks and duplicates dropped', async () => { + updateAdminSettings.mockResolvedValue({ data: { status: 'ok' } }) + const wrapper = await mountTab([]) + + await wrapper.find('textarea').setValue(' vraagict \n\nduurzaam42\nvraagict\n') + await wrapper.find('[data-testid="communities-save"]').trigger('click') + await flushPromises() + + expect(updateAdminSettings).toHaveBeenCalledWith({ pinnedCommunities: ['vraagict', 'duurzaam42'] }) + expect(wrapper.find('[role="status"]').text()).toBe('Pinned communities saved.') + }) + + it('shows the server refusal on the field', async () => { + updateAdminSettings.mockRejectedValue({ + response: { status: 400, data: { error: "Invalid value for pinnedCommunities: 'Vraag' is not a Talk conversation token (4 to 30 lowercase letters and digits)." } }, + }) + const wrapper = await mountTab([]) + + await wrapper.find('textarea').setValue('Vraag') + await wrapper.find('[data-testid="communities-save"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[role="status"]').text()).toContain("'Vraag' is not a Talk conversation token") + expect(wrapper.find('textarea').attributes('aria-invalid')).toBe('true') + }) + + it('refuses more than twenty before asking the server', async () => { + const wrapper = await mountTab([]) + + await wrapper.find('textarea').setValue(Array.from({ length: 21 }, (_v, i) => `room${i}`).join('\n')) + await wrapper.find('[data-testid="communities-save"]').trigger('click') + + expect(updateAdminSettings).not.toHaveBeenCalled() + expect(wrapper.find('[role="status"]').text()).toBe('At most 20 conversations can be pinned.') + }) + + it('reads tokens split by lines, spaces or commas', () => { + expect(tokensOf('a1b2, c3d4\ne5f6 a1b2')).toEqual(['a1b2', 'c3d4', 'e5f6']) + expect(tokensOf('')).toEqual([]) + }) +}) diff --git a/src/components/admin/tabs/__tests__/KioskTab.actions.spec.js b/src/components/admin/tabs/__tests__/KioskTab.actions.spec.js new file mode 100644 index 000000000..d61d47027 --- /dev/null +++ b/src/components/admin/tabs/__tests__/KioskTab.actions.spec.js @@ -0,0 +1,238 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * KioskTab: the row actions and failure messages the listing spec leaves + * out (dashboard-kiosk-mode REQ-KIOSKUI-001): copying the public link, + * editing an existing playlist, the save, revoke and load errors, and + * dismissing the revoke confirmation. Responses are KioskController's. + */ + +import axios from '@nextcloud/axios' +import { showSuccess } from '@nextcloud/dialogs' +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import KioskTab from '../KioskTab.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/dialogs', () => ({ showSuccess: vi.fn(), showError: vi.fn() })) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcButton: { + name: 'NcButton', + emits: ['click'], + template: '<button @click="$emit(\'click\')"><slot /></button>', + }, + CnConfirmDialog: { + name: 'CnConfirmDialog', + props: ['dialogTitle', 'message', 'confirmLabel', 'variant'], + emits: ['confirm', 'close'], + template: '<div class="revoke-stub">{{ message }}</div>', + }, + // The playlist dialog is stubbed per mount; these keep its import resolvable. + NcDialog: { name: 'NcDialog', template: '<div />' }, + NcSelect: { name: 'NcSelect', template: '<div />' }, + NcTextField: { name: 'NcTextField', template: '<div />' }, +})) + +const lobby = { + id: 1, + name: 'Lobby', + token: 'a b/c', + entries: [{ dashboardUuid: 'n', dwellSeconds: 30 }], + refreshSeconds: 300, +} + +const body = { + name: 'Lobby 2', + entries: [{ dashboardUuid: 'n', dwellSeconds: 15 }], + refreshSeconds: 120, +} + +let dashboardsResponse + +function mountTab() { + return mount(KioskTab, { + global: { + stubs: { + KioskPlaylistDialog: { + name: 'KioskPlaylistDialog', + props: ['open', 'playlist', 'dashboards'], + emits: ['save', 'update:open'], + template: '<div class="form-stub" />', + }, + }, + }, + }) +} + +async function mounted() { + const wrapper = mountTab() + await flushPromises() + return wrapper +} + +const errorText = (wrapper) => wrapper.find('[role="alert"]').text() +const dialog = (wrapper) => wrapper.findComponent({ name: 'KioskPlaylistDialog' }) + +beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + dashboardsResponse = { data: { items: [{ uuid: 'n', name: 'Nieuws' }] } } + axios.get.mockImplementation((url) => + url.includes('/api/kiosk/playlists') + ? Promise.resolve({ data: [lobby] }) + : Promise.resolve(dashboardsResponse), + ) +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('KioskTab loading', () => { + it('reads the dashboards from an items envelope', async () => { + const wrapper = await mounted() + + expect(dialog(wrapper).props('dashboards')).toEqual([{ uuid: 'n', name: 'Nieuws' }]) + expect(wrapper.find('[role="alert"]').exists()).toBe(false) + }) + + it('falls back to no dashboards for an unexpected payload', async () => { + dashboardsResponse = { data: null } + const wrapper = await mounted() + + expect(dialog(wrapper).props('dashboards')).toEqual([]) + }) + + it('says so when the playlists cannot be loaded', async () => { + axios.get.mockRejectedValue(new Error('down')) + const wrapper = await mounted() + + expect(errorText(wrapper)).toBe('The playlists could not be loaded.') + expect(wrapper.find('.kiosk-tab__empty').exists()).toBe(true) + }) +}) + +describe('KioskTab copy link', () => { + it('copies the encoded absolute link and confirms', async () => { + const writeText = vi.fn().mockResolvedValue() + vi.stubGlobal('navigator', { clipboard: { writeText } }) + const wrapper = await mounted() + + await wrapper.find('[data-testid="kiosk-copy"]').trigger('click') + await flushPromises() + + expect(writeText).toHaveBeenCalledWith( + window.location.origin + '/index.php/apps/launchpad/kiosk/a%20b%2Fc', + ) + expect(showSuccess).toHaveBeenCalledWith('Link copied') + }) + + it('tells the admin to copy by hand when the clipboard refuses', async () => { + vi.stubGlobal('navigator', { clipboard: { writeText: vi.fn().mockRejectedValue(new Error('denied')) } }) + const wrapper = await mounted() + + await wrapper.find('[data-testid="kiosk-copy"]').trigger('click') + await flushPromises() + + expect(showSuccess).not.toHaveBeenCalled() + expect(errorText(wrapper)).toBe('The link could not be copied. Select it and copy it by hand.') + }) +}) + +describe('KioskTab edit and save', () => { + it('opens the form on a row and saves it with a PUT', async () => { + axios.put.mockResolvedValue({ data: { ...lobby, ...body } }) + const wrapper = await mounted() + + await wrapper.find('[data-testid="kiosk-edit"]').trigger('click') + expect(dialog(wrapper).props('open')).toBe(true) + expect(dialog(wrapper).props('playlist')).toEqual(lobby) + + dialog(wrapper).vm.$emit('save', body) + await flushPromises() + + expect(axios.put).toHaveBeenCalledWith('/index.php/apps/launchpad/api/kiosk/playlists/1', body) + expect(axios.post).not.toHaveBeenCalled() + expect(dialog(wrapper).props('open')).toBe(false) + expect(wrapper.find('[data-testid="kiosk-row"]').text()).toContain('Lobby 2') + }) + + it('closes the form when the dialog asks to', async () => { + const wrapper = await mounted() + await wrapper.find('[data-testid="kiosk-new"]').trigger('click') + + dialog(wrapper).vm.$emit('update:open', false) + await flushPromises() + + expect(dialog(wrapper).props('open')).toBe(false) + }) + + it('explains a 403 and keeps the form open', async () => { + axios.post.mockRejectedValue({ response: { status: 403 } }) + const wrapper = await mounted() + await wrapper.find('[data-testid="kiosk-new"]').trigger('click') + + dialog(wrapper).vm.$emit('save', body) + await flushPromises() + + expect(errorText(wrapper)).toBe('You may only put dashboards you own or manage in a playlist.') + expect(dialog(wrapper).props('open')).toBe(true) + }) + + it('reports any other save failure generically, and clears it on the next save', async () => { + axios.post.mockRejectedValueOnce({ response: { status: 500 } }) + axios.post.mockResolvedValueOnce({ data: { ...lobby, id: 2 } }) + const wrapper = await mounted() + await wrapper.find('[data-testid="kiosk-new"]').trigger('click') + + dialog(wrapper).vm.$emit('save', body) + await flushPromises() + expect(errorText(wrapper)).toBe('The playlist could not be saved.') + + dialog(wrapper).vm.$emit('save', body) + await flushPromises() + expect(wrapper.find('[role="alert"]').exists()).toBe(false) + }) +}) + +describe('KioskTab revoke', () => { + it('dismissing the confirmation revokes nothing', async () => { + const wrapper = await mounted() + await wrapper.find('[data-testid="kiosk-revoke"]').trigger('click') + + wrapper.findComponent({ name: 'CnConfirmDialog' }).vm.$emit('close') + await flushPromises() + + expect(wrapper.findComponent({ name: 'CnConfirmDialog' }).exists()).toBe(false) + expect(axios.delete).not.toHaveBeenCalled() + }) + + it('reports a failed revoke and keeps the row', async () => { + axios.delete.mockRejectedValue(new Error('500')) + const wrapper = await mounted() + await wrapper.find('[data-testid="kiosk-revoke"]').trigger('click') + + wrapper.findComponent({ name: 'CnConfirmDialog' }).vm.$emit('confirm') + await flushPromises() + + expect(errorText(wrapper)).toBe('The playlist could not be revoked.') + expect(wrapper.findAll('[data-testid="kiosk-row"]')).toHaveLength(1) + }) + + it('a confirm without a target does nothing', async () => { + const wrapper = await mounted() + + await wrapper.vm.revoke() + + expect(axios.delete).not.toHaveBeenCalled() + }) +}) diff --git a/src/components/admin/tabs/__tests__/KioskTab.spec.js b/src/components/admin/tabs/__tests__/KioskTab.spec.js index 7860ea00a..1481216d9 100644 --- a/src/components/admin/tabs/__tests__/KioskTab.spec.js +++ b/src/components/admin/tabs/__tests__/KioskTab.spec.js @@ -29,6 +29,12 @@ vi.mock('@conduction/nextcloud-vue', () => ({ template: '<button @click="$emit(\'click\')"><slot /></button>', }, NcDialog: { name: 'NcDialog', template: '<div />' }, + CnConfirmDialog: { + name: 'CnConfirmDialog', + props: ['dialogTitle', 'message', 'confirmLabel', 'variant'], + emits: ['confirm', 'close'], + template: '<div class="revoke-stub">{{ message }}</div>', + }, NcSelect: { name: 'NcSelect', template: '<div />' }, NcTextField: { name: 'NcTextField', template: '<div />' }, })) @@ -55,12 +61,6 @@ function mountTab() { emits: ['save', 'update:open'], template: '<div class="form-stub" />', }, - RevokeKioskPlaylistDialog: { - name: 'RevokeKioskPlaylistDialog', - props: ['open', 'name'], - emits: ['confirm', 'update:open'], - template: '<div class="revoke-stub" />', - }, }, }, }) @@ -117,14 +117,11 @@ describe('KioskTab', () => { const wrapper = mountTab() await flushPromises() await wrapper.find('[data-testid="kiosk-revoke"]').trigger('click') - expect( - wrapper - .findComponent({ name: 'RevokeKioskPlaylistDialog' }) - .props('open'), - ).toBe(true) - wrapper - .findComponent({ name: 'RevokeKioskPlaylistDialog' }) - .vm.$emit('confirm') + const confirm = wrapper.findComponent({ name: 'CnConfirmDialog' }) + expect(confirm.exists()).toBe(true) + expect(confirm.props('message')).toContain('Lobby') + expect(confirm.props('variant')).toBe('error') + confirm.vm.$emit('confirm') await flushPromises() expect(axios.delete).toHaveBeenCalledWith( '/index.php/apps/launchpad/api/kiosk/playlists/1', diff --git a/src/components/admin/tabs/__tests__/ProfileFieldsTab.department.spec.js b/src/components/admin/tabs/__tests__/ProfileFieldsTab.department.spec.js new file mode 100644 index 000000000..c523f1e3c --- /dev/null +++ b/src/components/admin/tabs/__tests__/ProfileFieldsTab.department.spec.js @@ -0,0 +1,54 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ProfileFieldsTab: one field is the Department of read confirmations; + * marking another unmarks the first (REQ-ACK-010). + * + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + +import axios from '@nextcloud/axios' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ProfileFieldsTab from '../ProfileFieldsTab.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), put: vi.fn() } })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => path, +})) + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) +const stubs = { + NcButton: { emits: ['click'], template: '<button :type="$attrs.type || \'button\'" @click="$emit(\'click\')"><slot /></button>' }, +} +const field = (key, department) => ({ key, label: key, type: 'text', source: 'self', ldapAttribute: '', searchable: false, shownInWidget: true, visibility: 'everyone', department }) + +describe('ProfileFieldsTab department', () => { + beforeEach(() => { + axios.get.mockReset() + axios.put.mockReset() + }) + + it('keeps at most one field as the department and saves it', async () => { + axios.get.mockResolvedValue({ data: { fields: [field('team', true), field('unit', false)] } }) + axios.put.mockImplementation(async (_url, body) => ({ data: { fields: body.fields } })) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await settle() + + const boxes = () => wrapper.findAll('[data-testid="profile-field-department"]') + expect(boxes().map((box) => box.element.checked)).toEqual([true, false]) + + await boxes()[1].setValue(true) + expect(boxes().map((box) => box.element.checked)).toEqual([false, true]) + + await boxes()[1].setValue(false) + expect(boxes().map((box) => box.element.checked)).toEqual([false, false]) + + await boxes()[0].setValue(true) + await wrapper.find('form').trigger('submit') + await settle() + expect(axios.put.mock.calls[0][1].fields.map((f) => f.department)).toEqual([true, false]) + }) +}) diff --git a/src/components/admin/tabs/__tests__/ProfileFieldsTab.edit.spec.js b/src/components/admin/tabs/__tests__/ProfileFieldsTab.edit.spec.js new file mode 100644 index 000000000..aff033143 --- /dev/null +++ b/src/components/admin/tabs/__tests__/ProfileFieldsTab.edit.spec.js @@ -0,0 +1,177 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for editing in `ProfileFieldsTab.vue` (REQ-PEX-001): + * every control writes its own property of the field that is sent on save, + * the LDAP attribute only shows for an LDAP field, a field can be removed, + * the ten-field cap holds in code as well as on the button, and load and + * save failures show their message. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ProfileFieldsTab from '../ProfileFieldsTab.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), put: vi.fn() } })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => path, +})) + +const stubs = { + NcButton: { + props: ['disabled'], + emits: ['click'], + template: + '<button :type="$attrs.type || \'button\'" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, +} + +function field (overrides = {}) { + return { + key: 'office', + label: 'Office', + type: 'text', + source: 'self', + ldapAttribute: '', + searchable: true, + shownInWidget: true, + visibility: 'everyone', + ...overrides, +} +} + +async function mountTab(fields) { + axios.get.mockResolvedValue({ data: { fields } }) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await flushPromises() + return wrapper +} + +function button (wrapper, label) { + return wrapper.findAll('button').find((b) => b.text() === label) +} + +beforeEach(() => { + axios.get.mockReset() + axios.put.mockReset() + axios.put.mockImplementation((_url, body) => Promise.resolve({ data: { fields: body.fields } })) +}) + +describe('ProfileFieldsTab editing', () => { + it('writes every control into the field that is saved', async () => { + const wrapper = await mountTab([field()]) + const selects = wrapper.findAll('fieldset select') + const checks = wrapper.findAll('fieldset input[type="checkbox"]') + + await selects[0].setValue('tags') + await selects[1].setValue('ldap') + await wrapper.find('input[placeholder="physicalDeliveryOfficeName"]').setValue('roomNumber') + await wrapper.findAll('fieldset select')[2].setValue('groups') + await checks[0].setValue(false) + await checks[1].setValue(false) + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(axios.put).toHaveBeenCalledWith('/apps/launchpad/api/profile-fields/definitions', { + fields: [ + field({ + type: 'tags', + source: 'ldap', + ldapAttribute: 'roomNumber', + visibility: 'groups', + searchable: false, + shownInWidget: false, + }), + ], + }) + }) + + it('shows the LDAP attribute only for an LDAP field', async () => { + const wrapper = await mountTab([field()]) + expect(wrapper.find('input[placeholder="physicalDeliveryOfficeName"]').exists()).toBe(false) + + await wrapper.findAll('fieldset select')[1].setValue('ldap') + + expect(wrapper.find('input[placeholder="physicalDeliveryOfficeName"]').exists()).toBe(true) + }) + + it('names an unlabelled field "New field"', async () => { + const wrapper = await mountTab([field({ label: '' })]) + + expect(wrapper.find('legend').text()).toBe('New field') + }) + + it('removes the field whose button is pressed, not the first', async () => { + const wrapper = await mountTab([field({ key: 'a', label: 'A' }), field({ key: 'b', label: 'B' })]) + + await wrapper.findAll('fieldset')[1].findAll('button').find((b) => b.text() === 'Remove field').trigger('click') + + expect(wrapper.findAll('legend').map((l) => l.text())).toEqual(['A']) + expect(wrapper.vm.fields.map((f) => f.key)).toEqual(['a']) + }) + + it('adds nothing past ten fields even when called directly', async () => { + const wrapper = await mountTab(Array.from({ length: 10 }, (_, i) => field({ key: 'f' + i }))) + + wrapper.vm.add() + + expect(wrapper.vm.fields).toHaveLength(10) + expect(button(wrapper, 'Add field').attributes('disabled')).toBeDefined() + }) +}) + +describe('ProfileFieldsTab failures', () => { + it('says so when the definitions cannot be loaded and still shows the form', async () => { + axios.get.mockRejectedValue(new Error('down')) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await flushPromises() + + expect(wrapper.find('[role="alert"]').text()).toBe('The profile fields could not be loaded.') + expect(wrapper.find('form').exists()).toBe(true) + expect(wrapper.vm.fields).toEqual([]) + }) + + it('treats a load without a fields list as none', async () => { + axios.get.mockResolvedValue({ data: {} }) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await flushPromises() + + expect(wrapper.findAll('fieldset')).toHaveLength(0) + }) + + it('shows the server\'s error for a refused save', async () => { + const wrapper = await mountTab([field()]) + axios.put.mockRejectedValue({ response: { data: { error: 'Key "office" is used twice.' } } }) + + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.find('[role="alert"]').text()).toBe('Key "office" is used twice.') + expect(wrapper.find('[role="status"]').exists()).toBe(false) + expect(wrapper.vm.saving).toBe(false) + }) + + it('falls back to a generic message when the save fails without one', async () => { + const wrapper = await mountTab([field()]) + axios.put.mockRejectedValue(new Error('network')) + + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.find('[role="alert"]').text()).toBe('The profile fields could not be saved.') + }) + + it('empties the list when a save answers without fields', async () => { + const wrapper = await mountTab([field()]) + axios.put.mockResolvedValue({ data: {} }) + + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.vm.fields).toEqual([]) + expect(wrapper.find('[role="status"]').text()).toBe('Profile fields saved.') + }) +}) diff --git a/src/components/admin/tabs/__tests__/ProfileFieldsTab.spec.js b/src/components/admin/tabs/__tests__/ProfileFieldsTab.spec.js new file mode 100644 index 000000000..61e5d4ec1 --- /dev/null +++ b/src/components/admin/tabs/__tests__/ProfileFieldsTab.spec.js @@ -0,0 +1,123 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `ProfileFieldsTab.vue` (REQ-PEX-001): the + * administrator's field definitions load, a field is added with safe + * defaults, at most ten are allowed, and saving sends the list. + */ + +import axios from '@nextcloud/axios' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ProfileFieldsTab from '../ProfileFieldsTab.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), put: vi.fn() } })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => path, +})) + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) +const stubs = { + NcButton: { + props: ['disabled'], + emits: ['click'], + template: + '<button :type="$attrs.type || \'button\'" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, +} +const OFFICE = { + key: 'office', + label: 'Kantoorlocatie', + type: 'text', + source: 'ldap', + ldapAttribute: 'physicalDeliveryOfficeName', + searchable: false, + shownInWidget: true, + visibility: 'everyone', +} + +describe('ProfileFieldsTab', () => { + beforeEach(() => { + axios.get.mockReset() + axios.put.mockReset() + }) + + it('loads the definitions and shows the LDAP attribute of an LDAP field', async () => { + axios.get.mockResolvedValue({ data: { fields: [OFFICE] } }) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await settle() + await settle() + + expect(axios.get).toHaveBeenCalledWith( + '/apps/launchpad/api/profile-fields/definitions', + ) + expect(wrapper.find('legend').text()).toBe('Kantoorlocatie') + expect( + wrapper.find('input[placeholder="physicalDeliveryOfficeName"]').element + .value, + ).toBe('physicalDeliveryOfficeName') + }) + + it('adds a searchable text field for everyone and saves the list', async () => { + axios.get.mockResolvedValue({ data: { fields: [] } }) + axios.put.mockImplementation((url, body) => + Promise.resolve({ data: { fields: body.fields } }), + ) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await settle() + await settle() + + const add = wrapper + .findAll('button') + .find((button) => button.text() === 'Add field') + await add.trigger('click') + const inputs = wrapper.findAll('fieldset input[type="text"]') + await inputs[0].setValue('Expertise') + await inputs[1].setValue('expertise') + await wrapper.find('form').trigger('submit') + await settle() + + expect(axios.put).toHaveBeenCalledWith( + '/apps/launchpad/api/profile-fields/definitions', + { + fields: [ + { + key: 'expertise', + label: 'Expertise', + type: 'text', + source: 'self', + ldapAttribute: '', + searchable: true, + shownInWidget: true, + visibility: 'everyone', + department: false, + startDate: false, + }, + ], + }, + ) + expect(wrapper.text()).toContain('Profile fields saved.') + }) + + it('stops at ten fields', async () => { + axios.get.mockResolvedValue({ + data: { + fields: Array.from({ length: 10 }, (_, i) => ({ + ...OFFICE, + key: 'f' + i, + source: 'self', + })), + }, + }) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await settle() + await settle() + + const add = wrapper + .findAll('button') + .find((button) => button.text() === 'Add field') + expect(add.attributes('disabled')).toBeDefined() + }) +}) diff --git a/src/components/admin/tabs/__tests__/ProfileFieldsTab.startDate.spec.js b/src/components/admin/tabs/__tests__/ProfileFieldsTab.startDate.spec.js new file mode 100644 index 000000000..07f750f04 --- /dev/null +++ b/src/components/admin/tabs/__tests__/ProfileFieldsTab.startDate.spec.js @@ -0,0 +1,59 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ProfileFieldsTab: a field can be a date, and one date field is the start + * date of new colleagues; marking another unmarks the first (REQ-PEX-005). + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-a-profile-field-can-hold-a-start-date-req-pex-005 + */ + +import axios from '@nextcloud/axios' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ProfileFieldsTab from '../ProfileFieldsTab.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), put: vi.fn() } })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => path, +})) + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) +const stubs = { + NcButton: { emits: ['click'], template: '<button :type="$attrs.type || \'button\'" @click="$emit(\'click\')"><slot /></button>' }, +} +const field = (key, type, startDate) => ({ key, label: key, type, source: 'self', ldapAttribute: '', searchable: false, shownInWidget: true, visibility: 'everyone', department: false, startDate }) + +describe('ProfileFieldsTab start date (REQ-PEX-005)', () => { + beforeEach(() => { + axios.get.mockReset() + axios.put.mockReset() + }) + + it('offers the Date type and the start-date mark only on date fields', async () => { + axios.get.mockResolvedValue({ data: { fields: [field('joined', 'date', true), field('office', 'text', false)] } }) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await settle() + + expect(wrapper.find('select option[value="date"]').exists()).toBe(true) + expect(wrapper.findAll('[data-testid="profile-field-start-date"]')).toHaveLength(1) + }) + + it('keeps at most one date field as the start date and saves it', async () => { + axios.get.mockResolvedValue({ data: { fields: [field('joined', 'date', true), field('started', 'date', false)] } }) + axios.put.mockImplementation(async (_url, body) => ({ data: { fields: body.fields } })) + const wrapper = mount(ProfileFieldsTab, { global: { stubs } }) + await settle() + + const boxes = () => wrapper.findAll('[data-testid="profile-field-start-date"]') + expect(boxes().map((box) => box.element.checked)).toEqual([true, false]) + + await boxes()[1].setValue(true) + expect(boxes().map((box) => box.element.checked)).toEqual([false, true]) + + await wrapper.find('form').trigger('submit') + await settle() + expect(axios.put.mock.calls[0][1].fields.map((f) => f.startDate)).toEqual([false, true]) + }) +}) diff --git a/src/components/admin/tabs/__tests__/SearchShortcutsTab.spec.js b/src/components/admin/tabs/__tests__/SearchShortcutsTab.spec.js new file mode 100644 index 000000000..1dda0399d --- /dev/null +++ b/src/components/admin/tabs/__tests__/SearchShortcutsTab.spec.js @@ -0,0 +1,105 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `SearchShortcutsTab.vue` (REQ-SPX-001): the list + * loads, a shortcut is added and saved, and the server's refusal of a plain + * http address is shown. + */ + +import axios from '@nextcloud/axios' +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import SearchShortcutsTab from '../SearchShortcutsTab.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), put: vi.fn() } })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => path, +})) + +function settle() { + return new Promise((resolve) => setTimeout(resolve, 0)) +} +const stubs = { + NcButton: { + props: ['disabled'], + emits: ['click'], + template: + '<button :type="$attrs.type || \'button\'" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, +} + +describe('SearchShortcutsTab', () => { + beforeEach(() => { + axios.get.mockReset() + axios.put.mockReset() + }) + + it('adds the TOPdesk shortcut and saves the list', async () => { + axios.get.mockResolvedValue({ data: { shortcuts: [] } }) + axios.put.mockImplementation((url, body) => + Promise.resolve({ data: { shortcuts: body.shortcuts } }), + ) + const wrapper = mount(SearchShortcutsTab, { global: { stubs } }) + await settle() + await settle() + + await wrapper + .findAll('button') + .find((button) => button.text() === 'Add shortcut') + .trigger('click') + const inputs = wrapper.findAll('tbody input') + await inputs[0].setValue('!t') + await inputs[1].setValue('TOPdesk') + await inputs[2].setValue( + 'https://topdesk.gemeente.nl/tas/secure/search?q={query}', + ) + await wrapper.find('form').trigger('submit') + await settle() + + expect(axios.put).toHaveBeenCalledWith( + '/apps/launchpad/api/admin/search-shortcuts', + { + shortcuts: [ + { + prefix: '!t', + name: 'TOPdesk', + urlTemplate: + 'https://topdesk.gemeente.nl/tas/secure/search?q={query}', + }, + ], + }, + ) + expect(wrapper.text()).toContain('Search shortcuts saved.') + }) + + it('shows the server refusal of a plain http address', async () => { + axios.get.mockResolvedValue({ + data: { + shortcuts: [ + { + prefix: '!i', + name: 'Intranet', + urlTemplate: 'http://intranet.gemeente.nl/zoek?q={query}', + }, + ], + }, + }) + axios.put.mockRejectedValue({ + response: { + data: { error: 'Use an https address that contains {query}: !i' }, + }, + }) + const wrapper = mount(SearchShortcutsTab, { global: { stubs } }) + await settle() + await settle() + + await wrapper.find('form').trigger('submit') + await settle() + + expect(wrapper.find('[role="alert"]').text()).toBe( + 'Use an https address that contains {query}: !i', + ) + }) +}) diff --git a/src/components/admin/tabs/__tests__/TemplatesPage.list.spec.js b/src/components/admin/tabs/__tests__/TemplatesPage.list.spec.js new file mode 100644 index 000000000..7a17b0905 --- /dev/null +++ b/src/components/admin/tabs/__tests__/TemplatesPage.list.spec.js @@ -0,0 +1,222 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * TemplatesPage: the admin template list itself (admin-templates spec): + * the empty state, each row's groups summary and default badge, and the + * create, edit, delete and re-sync actions with the modals they drive. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcButton: { + name: 'NcButton', + props: ['disabled', 'variant'], + emits: ['click'], + template: + '<button :disabled="disabled" @click="$emit(\'click\')"><slot name="icon" /><slot /></button>', + }, + NcEmptyContent: { + name: 'NcEmptyContent', + props: ['description'], + template: '<div class="empty">{{ description }}<slot name="icon" /></div>', + }, + CnDashboardIcon: { name: 'CnDashboardIcon', template: '<i />' }, +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const { api } = vi.hoisted(() => ({ + api: { + getAdminTemplates: vi.fn(), + getShippedTemplates: vi.fn(), + deleteAdminTemplate: vi.fn(), + }, +})) +vi.mock('../../../../services/api.js', () => ({ api })) +vi.mock('../../../../modals/TemplateEditorModal.vue', () => ({ + default: { + name: 'TemplateEditorModal', + props: ['open', 'template'], + emits: ['close', 'saved'], + template: '<div />', + }, +})) +vi.mock('../../../../modals/TemplateResyncModal.vue', () => ({ + default: { + name: 'TemplateResyncModal', + props: ['open', 'template'], + emits: ['close', 'resynced'], + template: '<div />', + }, +})) +vi.mock('../../../../dialogs/ShippedTemplateUpdateDialog.vue', () => ({ + default: { name: 'ShippedTemplateUpdateDialog', template: '<div />' }, +})) + +import TemplatesPage from '../TemplatesPage.vue' +import { logger } from '../../../../utils/logger.js' + +const TEMPLATES = [ + { id: 1, name: 'Staff start', icon: 'Star', isDefault: 1, targetGroups: ['staff', 'hr'] }, + { id: 2, name: 'Everyone', icon: 'Star', isDefault: 0, targetGroups: [] }, +] + +async function mountPage() { + const wrapper = mount(TemplatesPage) + await flushPromises() + return wrapper +} + +function rowButton(wrapper, rowIndex, label) { + return wrapper + .findAll('.launchpad-admin__template') + [rowIndex].findAll('button') + .find((b) => b.text() === label) +} + +beforeEach(() => { + vi.clearAllMocks() + api.getAdminTemplates.mockResolvedValue({ data: TEMPLATES }) + api.getShippedTemplates.mockResolvedValue({ data: [] }) + api.deleteAdminTemplate.mockResolvedValue({}) +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('TemplatesPage list', () => { + it('shows the empty state without templates', async () => { + api.getAdminTemplates.mockResolvedValue({ data: null }) + const wrapper = await mountPage() + + expect(wrapper.find('.empty').text()).toContain('No templates yet') + expect(wrapper.findAll('.launchpad-admin__template')).toHaveLength(0) + }) + + it('keeps the list empty and logs when loading fails', async () => { + api.getAdminTemplates.mockRejectedValue(new Error('down')) + const wrapper = await mountPage() + + expect(wrapper.vm.templates).toEqual([]) + expect(logger.error).toHaveBeenCalledWith('Failed to load templates:', expect.any(Error)) + }) + + it('lists each template with its groups and the default badge', async () => { + const wrapper = await mountPage() + const rows = wrapper.findAll('.launchpad-admin__template') + + expect(rows).toHaveLength(2) + expect(rows[0].find('.launchpad-admin__template-groups').text()).toBe('staff, hr') + expect(rows[0].find('.launchpad-admin__badge').exists()).toBe(true) + expect(rows[1].find('.launchpad-admin__template-groups').text()).toBe('All users') + // Each row carries its template's id, so a test finds one template among same-named ones. + expect(rows.map((row) => row.attributes('data-testid'))).toEqual( + wrapper.vm.templates.map((template) => `admin-template-row-${template.id}`), + ) + expect(rows[1].find('.launchpad-admin__badge').exists()).toBe(false) + }) +}) + +describe('TemplatesPage editor', () => { + it('opens an empty editor from Create template', async () => { + const wrapper = await mountPage() + + await wrapper.find('[data-testid="admin-create-template"]').trigger('click') + + const editor = wrapper.findComponent({ name: 'TemplateEditorModal' }) + expect(editor.props('open')).toBe(true) + expect(editor.props('template')).toBeNull() + }) + + it('opens the editor on a row\'s template and closes it again', async () => { + const wrapper = await mountPage() + + await rowButton(wrapper, 1, 'Edit').trigger('click') + const editor = wrapper.findComponent({ name: 'TemplateEditorModal' }) + expect(editor.props('open')).toBe(true) + expect(editor.props('template')).toEqual(TEMPLATES[1]) + + editor.vm.$emit('close') + await flushPromises() + expect(editor.props('open')).toBe(false) + expect(editor.props('template')).toBeNull() + }) + + it('reloads the list and closes the editor after a save', async () => { + const wrapper = await mountPage() + await rowButton(wrapper, 0, 'Edit').trigger('click') + api.getAdminTemplates.mockResolvedValue({ data: [TEMPLATES[0]] }) + + wrapper.findComponent({ name: 'TemplateEditorModal' }).vm.$emit('saved') + await flushPromises() + + expect(api.getAdminTemplates).toHaveBeenCalledTimes(2) + expect(wrapper.findAll('.launchpad-admin__template')).toHaveLength(1) + expect(wrapper.findComponent({ name: 'TemplateEditorModal' }).props('open')).toBe(false) + }) +}) + +describe('TemplatesPage delete', () => { + it('deletes after confirmation and reloads', async () => { + vi.stubGlobal('confirm', vi.fn(() => true)) + const wrapper = await mountPage() + + await rowButton(wrapper, 1, 'Delete').trigger('click') + await flushPromises() + + expect(confirm).toHaveBeenCalledWith('Are you sure you want to delete this template?') + expect(api.deleteAdminTemplate).toHaveBeenCalledWith(2) + expect(api.getAdminTemplates).toHaveBeenCalledTimes(2) + }) + + it('does nothing when the confirmation is declined', async () => { + vi.stubGlobal('confirm', vi.fn(() => false)) + const wrapper = await mountPage() + + await rowButton(wrapper, 1, 'Delete').trigger('click') + await flushPromises() + + expect(api.deleteAdminTemplate).not.toHaveBeenCalled() + expect(api.getAdminTemplates).toHaveBeenCalledTimes(1) + }) + + it('logs a failed delete without reloading', async () => { + vi.stubGlobal('confirm', vi.fn(() => true)) + api.deleteAdminTemplate.mockRejectedValue(new Error('403')) + const wrapper = await mountPage() + + await rowButton(wrapper, 0, 'Delete').trigger('click') + await flushPromises() + + expect(logger.error).toHaveBeenCalledWith('Failed to delete template:', expect.any(Error)) + expect(api.getAdminTemplates).toHaveBeenCalledTimes(1) + }) +}) + +describe('TemplatesPage re-sync', () => { + it('opens the re-sync modal on a row and closes it on close or after a re-sync', async () => { + const wrapper = await mountPage() + const modal = () => wrapper.findComponent({ name: 'TemplateResyncModal' }) + expect(modal().props('open')).toBe(false) + + await wrapper.findAll('[data-testid="admin-resync-template"]')[0].trigger('click') + expect(modal().props('open')).toBe(true) + expect(modal().props('template')).toEqual(TEMPLATES[0]) + + modal().vm.$emit('resynced') + await flushPromises() + expect(modal().props('open')).toBe(false) + + await wrapper.findAll('[data-testid="admin-resync-template"]')[1].trigger('click') + modal().vm.$emit('close') + await flushPromises() + expect(modal().props('template')).toBeNull() + }) +}) diff --git a/src/components/admin/tabs/__tests__/TemplatesPage.shipped.spec.js b/src/components/admin/tabs/__tests__/TemplatesPage.shipped.spec.js new file mode 100644 index 000000000..bdd9af03b --- /dev/null +++ b/src/components/admin/tabs/__tests__/TemplatesPage.shipped.spec.js @@ -0,0 +1,261 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * TemplatesPage: the ready-made templates section and the per-template + * download (admin-templates REQ-TMPL-018, dashboard-export-import + * REQ-EXIM-012). Payloads are the shapes ShippedTemplateService::listTemplates + * and Dashboard::jsonSerialize return. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcButton: { + name: 'NcButton', + props: ['disabled'], + emits: ['click'], + template: + '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcEmptyContent: { name: 'NcEmptyContent', template: '<div class="empty" />' }, + CnDashboardIcon: { name: 'CnDashboardIcon', template: '<i />' }, +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const { api } = vi.hoisted(() => ({ + api: { + getAdminTemplates: vi.fn(), + getShippedTemplates: vi.fn(), + installShippedTemplate: vi.fn(), + exportDashboards: vi.fn(), + }, +})) +vi.mock('../../../../services/api.js', () => ({ api })) +// The two modals are the page's own children and not under test here. +vi.mock('../../../../modals/TemplateEditorModal.vue', () => ({ + default: { name: 'TemplateEditorModal', template: '<div />' }, +})) +vi.mock('../../../../modals/TemplateResyncModal.vue', () => ({ + default: { name: 'TemplateResyncModal', template: '<div />' }, +})) + +vi.mock('../../../../dialogs/ShippedTemplateUpdateDialog.vue', () => ({ + default: { name: 'ShippedTemplateUpdateDialog', template: '<div />' }, +})) + +import TemplatesPage from '../TemplatesPage.vue' + +function shipped(overrides = {}) { + return { + id: 'mijn-werkdag', + name: 'Mijn werkdag', + description: 'Startpagina voor medewerkers', + language: 'nl', + version: 1, + widgetCount: 8, + isInstalled: false, + installedUuid: '', + installedVersion: null, + missingWidgets: [], + registers: ['dossiq', 'pipelinq'], + ...overrides, + } +} + +const installedTemplate = { + id: 4, + uuid: 'uuid-4', + name: 'Mijn werkdag', + icon: null, + slug: null, + isDefault: 0, + targetGroups: [], +} + +function mountPage() { + return mount(TemplatesPage, { + global: { + stubs: { + TemplateResyncModal: true, + TemplateEditorModal: true, + Plus: true, + ViewDashboard: true, + }, + }, + }) +} + +beforeEach(() => { + vi.clearAllMocks() + api.getAdminTemplates.mockResolvedValue({ data: [] }) + api.getShippedTemplates.mockResolvedValue({ data: [shipped()] }) +}) + +describe('TemplatesPage ready-made templates', () => { + it('lists a shipped template with an add button', async () => { + const wrapper = mountPage() + await flushPromises() + + const row = wrapper.find( + '[data-testid="admin-shipped-template-mijn-werkdag"]', + ) + expect(row.exists()).toBe(true) + expect(row.text()).toContain('Mijn werkdag') + expect(row.text()).toContain('Startpagina voor medewerkers') + expect(row.find('[data-testid="admin-shipped-template-add"]').exists()).toBe( + true, + ) + expect( + row.find('[data-testid="admin-shipped-template-added"]').exists(), + ).toBe(false) + expect( + row.find('[data-testid="admin-shipped-template-missing"]').exists(), + ).toBe(false) + }) + + it('adds the template, then shows it in the list and marks it added', async () => { + api.installShippedTemplate.mockResolvedValue({ + data: { uuid: 'uuid-4', alreadyInstalled: false }, + }) + const wrapper = mountPage() + await flushPromises() + api.getAdminTemplates.mockResolvedValue({ data: [installedTemplate] }) + api.getShippedTemplates.mockResolvedValue({ + data: [shipped({ isInstalled: true, installedUuid: 'uuid-4' })], + }) + + await wrapper + .find('[data-testid="admin-shipped-template-add"]') + .trigger('click') + await flushPromises() + + expect(api.installShippedTemplate).toHaveBeenCalledTimes(1) + expect(api.installShippedTemplate).toHaveBeenCalledWith('mijn-werkdag') + expect( + wrapper.find('[data-testid="admin-shipped-template-added"]').exists(), + ).toBe(true) + expect( + wrapper.find('[data-testid="admin-shipped-template-add"]').exists(), + ).toBe(false) + expect(wrapper.find('.launchpad-admin__templates').text()).toContain( + 'Mijn werkdag', + ) + expect(wrapper.find('[data-testid="admin-templates-error"]').exists()).toBe( + false, + ) + }) + + it('says so when adding fails, and leaves the button', async () => { + api.installShippedTemplate.mockRejectedValue(new Error('500')) + const wrapper = mountPage() + await flushPromises() + + await wrapper + .find('[data-testid="admin-shipped-template-add"]') + .trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="admin-templates-error"]').text()).toBe( + 'The template "Mijn werkdag" could not be added.', + ) + expect( + wrapper + .find('[data-testid="admin-shipped-template-add"]') + .attributes('disabled'), + ).toBeUndefined() + }) + + it('names the registers the lists read and the hide rule', async () => { + const wrapper = mountPage() + await flushPromises() + + expect( + wrapper.find('[data-testid="admin-shipped-template-registers"]').text(), + ).toBe( + 'Its lists read these registers: dossiq, pipelinq. A list whose register is not on this instance is hidden for members.', + ) + }) + + it('names the widgets no app provides', async () => { + api.getShippedTemplates.mockResolvedValue({ + data: [shipped({ missingWidgets: ['decidesk', 'activity'] })], + }) + const wrapper = mountPage() + await flushPromises() + + expect( + wrapper.find('[data-testid="admin-shipped-template-missing"]').text(), + ).toBe( + 'No app here provides these widgets, so they will show empty: decidesk, activity', + ) + }) + + it('says so when the shipped list fails, and still lists the templates', async () => { + api.getShippedTemplates.mockRejectedValue(new Error('500')) + api.getAdminTemplates.mockResolvedValue({ data: [installedTemplate] }) + const wrapper = mountPage() + await flushPromises() + + expect( + wrapper.find('[data-testid="admin-shipped-templates"]').exists(), + ).toBe(false) + expect(wrapper.find('[data-testid="admin-templates-error"]').text()).toBe( + 'The ready-made templates could not be loaded.', + ) + expect(wrapper.find('.launchpad-admin__templates').text()).toContain( + 'Mijn werkdag', + ) + }) +}) + +describe('TemplatesPage download', () => { + it('asks for a one-dashboard export of that template', async () => { + api.getAdminTemplates.mockResolvedValue({ data: [installedTemplate] }) + api.exportDashboards.mockResolvedValue({ data: new Blob(['zip']) }) + window.URL.createObjectURL = vi.fn(() => 'blob:x') + window.URL.revokeObjectURL = vi.fn() + const click = vi + .spyOn(HTMLAnchorElement.prototype, 'click') + .mockImplementation(() => {}) + const wrapper = mountPage() + await flushPromises() + + await wrapper + .find('[data-testid="admin-download-template"]') + .trigger('click') + await flushPromises() + + expect(api.exportDashboards).toHaveBeenCalledWith({ + scope: 'dashboard', + dashboardUuid: 'uuid-4', + }) + expect(click).toHaveBeenCalledTimes(1) + expect(click.mock.instances[0].download).toBe( + 'launchpad-template-uuid-4.zip', + ) + expect(window.URL.revokeObjectURL).toHaveBeenCalledWith('blob:x') + click.mockRestore() + }) + + it('says so when the download fails', async () => { + api.getAdminTemplates.mockResolvedValue({ data: [installedTemplate] }) + api.exportDashboards.mockRejectedValue(new Error('404')) + const wrapper = mountPage() + await flushPromises() + + await wrapper + .find('[data-testid="admin-download-template"]') + .trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="admin-templates-error"]').text()).toBe( + 'The template "Mijn werkdag" could not be downloaded.', + ) + }) +}) diff --git a/src/components/admin/tabs/__tests__/TemplatesPage.shippedUpdate.spec.js b/src/components/admin/tabs/__tests__/TemplatesPage.shippedUpdate.spec.js new file mode 100644 index 000000000..725493f04 --- /dev/null +++ b/src/components/admin/tabs/__tests__/TemplatesPage.shippedUpdate.spec.js @@ -0,0 +1,236 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * TemplatesPage: updating an installed ready-made template (admin-templates + * REQ-TMPL-020). The page is mounted with the real update dialog, so the + * test covers the wiring from the button to the two server calls. Payloads + * are the shapes ShippedTemplateService::listTemplates and + * ShippedTemplateUpdateService::update return. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcButton: { + name: 'NcButton', + props: ['disabled'], + emits: ['click'], + template: + '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcDialog: { + name: 'NcDialog', + props: ['open', 'name'], + emits: ['update:open'], + template: + '<div v-if="open" class="dialog"><h2>{{ name }}</h2><slot /><slot name="actions" /></div>', + }, + NcEmptyContent: { name: 'NcEmptyContent', template: '<div class="empty" />' }, + CnDashboardIcon: { name: 'CnDashboardIcon', template: '<i />' }, +})) +vi.mock('../../../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const { api } = vi.hoisted(() => ({ + api: { + getAdminTemplates: vi.fn(), + getShippedTemplates: vi.fn(), + installShippedTemplate: vi.fn(), + updateShippedTemplate: vi.fn(), + exportDashboards: vi.fn(), + }, +})) +vi.mock('../../../../services/api.js', () => ({ api })) +vi.mock('../../../../modals/TemplateEditorModal.vue', () => ({ + default: { name: 'TemplateEditorModal', template: '<div />' }, +})) +vi.mock('../../../../modals/TemplateResyncModal.vue', () => ({ + default: { name: 'TemplateResyncModal', template: '<div />' }, +})) + +import TemplatesPage from '../TemplatesPage.vue' + +function shipped(overrides = {}) { + return { + id: 'mijn-werkdag', + name: 'Mijn werkdag', + description: 'Startpagina voor medewerkers', + language: 'nl', + version: 3, + widgetCount: 7, + isInstalled: true, + installedUuid: 'uuid-4', + installedVersion: 2, + updateAvailable: true, + missingWidgets: [], + ...overrides, + } +} + +function plan(overrides = {}) { + return { + templateId: 'mijn-werkdag', + uuid: 'uuid-4', + id: 4, + name: 'Mijn werkdag', + installedVersion: 2, + version: 3, + upToDate: false, + dryRun: true, + applied: false, + added: ['Mijn tickets (object-list)'], + removed: ['Eigen notitie (text)'], + changed: [{ widget: 'Mijn zaken (object-list)', fields: ['position'] }], + unchanged: 4, + copies: 12, + resync: null, + ...overrides, + } +} + +function mountPage() { + return mount(TemplatesPage, { + global: { stubs: { Plus: true, ViewDashboard: true } }, + }) +} + +const updateButton = '[data-testid="admin-shipped-template-update"]' + +beforeEach(() => { + vi.clearAllMocks() + api.getAdminTemplates.mockResolvedValue({ data: [] }) + api.getShippedTemplates.mockResolvedValue({ data: [shipped()] }) +}) + +describe('TemplatesPage update of a ready-made template', () => { + it('offers the update only when a newer version ships', async () => { + const wrapper = mountPage() + await flushPromises() + expect(wrapper.find(updateButton).text()).toBe('Update to version 3') + + api.getShippedTemplates.mockResolvedValue({ + data: [shipped({ installedVersion: 3, updateAvailable: false })], + }) + const upToDate = mountPage() + await flushPromises() + expect(upToDate.find(updateButton).exists()).toBe(false) + expect( + upToDate.find('[data-testid="admin-shipped-template-added"]').exists(), + ).toBe(true) + }) + + it('shows what changes before anything is written', async () => { + api.updateShippedTemplate.mockResolvedValue({ data: plan() }) + const wrapper = mountPage() + await flushPromises() + + await wrapper.find(updateButton).trigger('click') + await flushPromises() + + expect(api.updateShippedTemplate).toHaveBeenCalledTimes(1) + expect(api.updateShippedTemplate).toHaveBeenCalledWith('mijn-werkdag', { + dryRun: true, + }) + const dialog = wrapper.find('[data-testid="shipped-update-plan"]') + expect(dialog.text()).toContain('from version 2 to version 3') + expect(wrapper.find('[data-testid="shipped-update-added"]').text()).toBe( + 'Mijn tickets (object-list)', + ) + expect(wrapper.find('[data-testid="shipped-update-removed"]').text()).toBe( + 'Eigen notitie (text)', + ) + expect(wrapper.find('[data-testid="shipped-update-changed"]').text()).toBe( + 'Mijn zaken (object-list)', + ) + expect( + wrapper.find('[data-testid="shipped-update-copies"]').text(), + ).toContain('Members with a copy of this template: 12.') + }) + + it('cancelling writes nothing', async () => { + api.updateShippedTemplate.mockResolvedValue({ data: plan() }) + const wrapper = mountPage() + await flushPromises() + await wrapper.find(updateButton).trigger('click') + await flushPromises() + + await wrapper.find('[data-testid="shipped-update-cancel"]').trigger('click') + await flushPromises() + + expect(api.updateShippedTemplate).toHaveBeenCalledTimes(1) + expect(wrapper.find('[data-testid="shipped-update-plan"]').exists()).toBe( + false, + ) + }) + + it('updates on confirm, says so and drops the button', async () => { + api.updateShippedTemplate.mockResolvedValue({ data: plan() }) + const wrapper = mountPage() + await flushPromises() + await wrapper.find(updateButton).trigger('click') + await flushPromises() + + api.updateShippedTemplate.mockResolvedValue({ + data: plan({ + dryRun: false, + applied: true, + resync: { async: false, affectedCount: 12, totalCopies: 12 }, + }), + }) + api.getShippedTemplates.mockResolvedValue({ + data: [shipped({ installedVersion: 3, updateAvailable: false })], + }) + await wrapper.find('[data-testid="shipped-update-confirm"]').trigger('click') + await flushPromises() + + expect(api.updateShippedTemplate).toHaveBeenCalledTimes(2) + expect(api.updateShippedTemplate).toHaveBeenLastCalledWith('mijn-werkdag') + expect(wrapper.find('[data-testid="admin-templates-status"]').text()).toBe( + 'Updated "Mijn werkdag" to version 3. Members with a copy: 12.', + ) + expect(wrapper.find(updateButton).exists()).toBe(false) + expect(wrapper.find('[data-testid="shipped-update-plan"]').exists()).toBe( + false, + ) + }) + + it('says so when the plan cannot be loaded, and cannot be confirmed', async () => { + api.updateShippedTemplate.mockRejectedValue(new Error('500')) + const wrapper = mountPage() + await flushPromises() + + await wrapper.find(updateButton).trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="shipped-update-error"]').text()).toBe( + 'The changes could not be worked out. Nothing was updated.', + ) + expect( + wrapper + .find('[data-testid="shipped-update-confirm"]') + .attributes('disabled'), + ).toBeDefined() + }) + + it('says so when the update fails and keeps the button', async () => { + api.updateShippedTemplate.mockResolvedValueOnce({ data: plan() }) + api.updateShippedTemplate.mockRejectedValueOnce(new Error('500')) + const wrapper = mountPage() + await flushPromises() + await wrapper.find(updateButton).trigger('click') + await flushPromises() + + await wrapper.find('[data-testid="shipped-update-confirm"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="shipped-update-error"]').text()).toBe( + 'The template "Mijn werkdag" could not be updated.', + ) + expect(wrapper.find(updateButton).exists()).toBe(true) + }) +}) diff --git a/src/composables/__tests__/filterTelemetry.spec.js b/src/composables/__tests__/filterTelemetry.spec.js new file mode 100644 index 000000000..cced9e98e --- /dev/null +++ b/src/composables/__tests__/filterTelemetry.spec.js @@ -0,0 +1,159 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Filter telemetry (drill-down-cross-widget-filter REQ-CWF-010): rows carry + * dimensions and operators, never values, and are written only when the + * organisation opted in. + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-15 + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createFilterTelemetry, filterDelta } from '../filterTelemetry.js' +import { useFilterBus } from '../useFilterBus.js' + +const NOW = () => new Date('2026-11-15T12:00:00.000Z') + +/** + * A recorder with a recording post double. + * + * @param {boolean} enabled Whether telemetry is on. + * @return {{telemetry: object, post: Function}} + */ +function recorder(enabled = true) { + const post = vi.fn(() => Promise.resolve({})) + const telemetry = createFilterTelemetry({ enabled: () => enabled, dashboardId: 'd-1', userId: 'alice', post, now: NOW }) + return { telemetry, post } +} + +describe('filterDelta', () => { + it('keeps dimension, operator, source, source widget and pinned, and drops the value', () => { + expect(filterDelta([ + { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: 'w-1', pinned: false }, + { dimension: 'period.month', value: '2026-11', source: 'urlBootstrap', sourceWidgetId: null, pinned: true }, + { dimension: '', value: 'x' }, + null, + ])).toEqual([ + { dimension: 'gemeenteCode', operator: 'eq', source: 'widgetClick', sourceWidgetId: 'w-1', pinned: false }, + { dimension: 'period.month', operator: 'eq', source: 'urlBootstrap', pinned: true }, + ]) + }) +}) + +describe('createFilterTelemetry', () => { + it('writes a row without values when telemetry is on', async () => { + const { telemetry, post } = recorder() + + const row = await telemetry.record('apply', [{ dimension: 'wijkCode', operator: 'eq', value: 'WK1', source: 'widgetClick', sourceWidgetId: 'w-2' }], 'w-2') + + const expected = { + dashboardId: 'd-1', + userId: 'alice', + eventType: 'apply', + filterDelta: [{ dimension: 'wijkCode', operator: 'eq', source: 'widgetClick', sourceWidgetId: 'w-2', pinned: false }], + timestamp: '2026-11-15T12:00:00.000Z', + widgetId: 'w-2', + } + expect(row).toEqual(expected) + expect(post).toHaveBeenCalledWith(expected) + expect(JSON.stringify(post.mock.calls)).not.toContain('WK1') + }) + + it('writes nothing when telemetry is off, the context is incomplete, the type is unknown or nothing changed', async () => { + const clause = [{ dimension: 'a', operator: 'eq', value: 1 }] + const off = recorder(false) + expect(await off.telemetry.record('apply', clause)).toBeNull() + expect(off.post).not.toHaveBeenCalled() + + const post = vi.fn() + const anonymous = createFilterTelemetry({ enabled: () => true, dashboardId: 'd-1', userId: '', post }) + expect(await anonymous.record('apply', clause)).toBeNull() + const noDashboard = createFilterTelemetry({ enabled: () => true, dashboardId: '', userId: 'alice', post }) + expect(await noDashboard.record('apply', clause)).toBeNull() + + const on = recorder() + expect(await on.telemetry.record('click', clause)).toBeNull() + expect(await on.telemetry.record('reset', [])).toBeNull() + expect(post).not.toHaveBeenCalled() + expect(on.post).not.toHaveBeenCalled() + }) + + it('asks whether telemetry is on at every record, so switching it on only affects later changes', async () => { + let enabled = false + const post = vi.fn(() => Promise.resolve()) + const telemetry = createFilterTelemetry({ enabled: () => enabled, dashboardId: 'd-1', userId: 'alice', post, now: NOW }) + + await telemetry.record('apply', [{ dimension: 'a' }]) + enabled = true + await telemetry.record('apply', [{ dimension: 'b' }]) + + expect(post).toHaveBeenCalledTimes(1) + expect(post.mock.calls[0][0].filterDelta[0].dimension).toBe('b') + }) + + it('drops a failed write instead of failing the filter change', async () => { + const post = vi.fn(() => Promise.reject(new Error('offline'))) + const telemetry = createFilterTelemetry({ enabled: () => true, dashboardId: 'd-1', userId: 'alice', post, now: NOW }) + + await expect(telemetry.record('apply', [{ dimension: 'a' }])).resolves.toBeNull() + }) +}) + +describe('the filter bus with telemetry', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('records an apply for an accepted click, a reset of the cleared clauses, and nothing for an empty reset', () => { + const record = vi.fn() + const bus = useFilterBus({ telemetry: { record } }) + + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: 'w-1' }) + expect(record).toHaveBeenLastCalledWith('apply', [expect.objectContaining({ dimension: 'gemeenteCode' })], 'w-1') + + bus.hydrate([{ dimension: 'year', operator: 'eq', value: 2026, pinned: true }], 'savedView') + bus.publish({ dimension: 'status', operator: 'eq', value: 'open', source: 'userExplicit' }) + record.mockClear() + + expect(bus.reset()).toBe(true) + expect(record).toHaveBeenCalledTimes(1) + const [type, cleared] = record.mock.calls[0] + expect(type).toBe('reset') + expect(cleared.map((clause) => clause.dimension)).toEqual(['status']) + + record.mockClear() + expect(bus.reset()).toBe(false) + expect(record).not.toHaveBeenCalled() + }) + + it('records nothing for a refused click', () => { + const record = vi.fn() + const bus = useFilterBus({ canAccess: () => false, telemetry: { record } }) + + expect(bus.publish({ dimension: 'a', operator: 'eq', value: 1 }).accepted).toBe(false) + expect(record).not.toHaveBeenCalled() + }) + + it('records a bookmark on the next tick for clauses restored from the URL only', () => { + const record = vi.fn() + const bus = useFilterBus({ telemetry: { record } }) + + bus.hydrate([{ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355' }], 'urlBootstrap') + expect(record).not.toHaveBeenCalled() + vi.runAllTimers() + expect(record).toHaveBeenCalledTimes(1) + expect(record.mock.calls[0][0]).toBe('bookmark') + expect(record.mock.calls[0][1].map((clause) => clause.dimension)).toEqual(['gemeenteCode']) + + record.mockClear() + bus.hydrate([{ dimension: 'wijkCode', operator: 'eq', value: 'WK1' }], 'savedView') + bus.hydrate([], 'urlBootstrap') + vi.runAllTimers() + expect(record).not.toHaveBeenCalled() + }) +}) diff --git a/src/composables/__tests__/fixtures/nudgePlacement.golden.json b/src/composables/__tests__/fixtures/nudgePlacement.golden.json new file mode 100644 index 000000000..bc5715135 --- /dev/null +++ b/src/composables/__tests__/fixtures/nudgePlacement.golden.json @@ -0,0 +1,9729 @@ +{ + "top left | none | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "top left | none | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "top left | none | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "top left | none | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "top left | none | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | none | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "top left | not an array | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "top left | not an array | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "top left | not an array | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "top left | not an array | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | not an array | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "top left | mixed | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "top left | mixed | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "top left | mixed | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "top left | mixed | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "top left | mixed | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "top left | mixed | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "top left | mixed | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "top left | mixed | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "top left | mixed | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "top left | mixed | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "right edge | none | default | move-up": { + "gridX": 10, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | move-down": { + "gridX": 10, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | move-left": { + "gridX": 9, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | move-right": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | shrink-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | grow-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | none | default | shrink-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | none | default | unknown": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | toString": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | __proto__": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | constructor": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | default | undefined": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | move-up": { + "gridX": 4, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | move-down": { + "gridX": 4, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | move-left": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | move-right": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": -4, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | shrink-width": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | grow-height": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | none | six columns | shrink-height": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | none | six columns | unknown": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | toString": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | __proto__": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | constructor": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | six columns | undefined": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | move-up": { + "gridX": 10, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | move-down": { + "gridX": 10, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | move-left": { + "gridX": 9, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | move-right": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | shrink-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | grow-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | none | zero columns | shrink-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | none | zero columns | unknown": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | toString": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | __proto__": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | constructor": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | zero columns | undefined": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | move-up": { + "gridX": 1, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | move-down": { + "gridX": 1, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | move-left": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | move-right": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": -7, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | shrink-width": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | grow-height": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | none | three columns | shrink-height": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | none | three columns | unknown": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | toString": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | __proto__": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | constructor": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | none | three columns | undefined": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | move-up": { + "gridX": 10, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | move-down": { + "gridX": 10, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | move-left": { + "gridX": 9, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | move-right": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | shrink-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | grow-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | not an array | default | shrink-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | not an array | default | unknown": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | toString": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | __proto__": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | constructor": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | default | undefined": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | move-up": { + "gridX": 4, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | move-down": { + "gridX": 4, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | move-left": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | move-right": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": -4, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | shrink-width": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | grow-height": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | not an array | six columns | shrink-height": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | not an array | six columns | unknown": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | toString": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | __proto__": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | constructor": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | six columns | undefined": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | move-up": { + "gridX": 10, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | move-down": { + "gridX": 10, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | move-left": { + "gridX": 9, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | move-right": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | shrink-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | grow-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | not an array | zero columns | shrink-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | not an array | zero columns | unknown": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | toString": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | __proto__": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | constructor": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | zero columns | undefined": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | move-up": { + "gridX": 1, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | move-down": { + "gridX": 1, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | move-left": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | move-right": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": -7, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | shrink-width": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | grow-height": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | not an array | three columns | shrink-height": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | not an array | three columns | unknown": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | toString": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | __proto__": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | constructor": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | not an array | three columns | undefined": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | default | move-up": { + "gridX": 10, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 5 + } + ] + }, + "right edge | mixed | default | move-down": { + "gridX": 10, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 7 + }, + { + "id": 7, + "gridY": 7 + } + ] + }, + "right edge | mixed | default | move-left": { + "gridX": 9, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | default | move-right": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | default | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | default | shrink-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | default | grow-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [ + { + "id": 4, + "gridY": 7 + }, + { + "id": 7, + "gridY": 7 + } + ] + }, + "right edge | mixed | default | shrink-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 4, + "gridY": 5 + } + ] + }, + "right edge | mixed | default | unknown": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | default | toString": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | default | __proto__": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | default | constructor": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | default | undefined": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | six columns | move-up": { + "gridX": 4, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | move-down": { + "gridX": 4, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | move-left": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | move-right": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": -4, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | shrink-width": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | grow-height": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [] + }, + "right edge | mixed | six columns | shrink-height": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "right edge | mixed | six columns | unknown": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | toString": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | __proto__": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | constructor": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | six columns | undefined": { + "gridX": 4, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | zero columns | move-up": { + "gridX": 10, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 5 + } + ] + }, + "right edge | mixed | zero columns | move-down": { + "gridX": 10, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 7 + }, + { + "id": 7, + "gridY": 7 + } + ] + }, + "right edge | mixed | zero columns | move-left": { + "gridX": 9, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | zero columns | move-right": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | zero columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | zero columns | shrink-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | zero columns | grow-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [ + { + "id": 4, + "gridY": 7 + }, + { + "id": 7, + "gridY": 7 + } + ] + }, + "right edge | mixed | zero columns | shrink-height": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 4, + "gridY": 5 + } + ] + }, + "right edge | mixed | zero columns | unknown": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | zero columns | toString": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | zero columns | __proto__": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | zero columns | constructor": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | zero columns | undefined": { + "gridX": 10, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 4, + "gridY": 6 + } + ] + }, + "right edge | mixed | three columns | move-up": { + "gridX": 1, + "gridY": 2, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 5 + } + ] + }, + "right edge | mixed | three columns | move-down": { + "gridX": 1, + "gridY": 4, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | three columns | move-left": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 6 + } + ] + }, + "right edge | mixed | three columns | move-right": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 6 + } + ] + }, + "right edge | mixed | three columns | grow-width": { + "gridX": 10, + "gridY": 3, + "gridWidth": -7, + "gridHeight": 3, + "pushed": [] + }, + "right edge | mixed | three columns | shrink-width": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 6 + } + ] + }, + "right edge | mixed | three columns | grow-height": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 4, + "pushed": [ + { + "id": 2, + "gridY": 7 + } + ] + }, + "right edge | mixed | three columns | shrink-height": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 5 + } + ] + }, + "right edge | mixed | three columns | unknown": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 6 + } + ] + }, + "right edge | mixed | three columns | toString": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 6 + } + ] + }, + "right edge | mixed | three columns | __proto__": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 6 + } + ] + }, + "right edge | mixed | three columns | constructor": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 6 + } + ] + }, + "right edge | mixed | three columns | undefined": { + "gridX": 1, + "gridY": 3, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 6 + } + ] + }, + "too wide | none | default | move-up": { + "gridX": 6, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | move-down": { + "gridX": 6, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | move-left": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | move-right": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": 4, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | shrink-width": { + "gridX": 7, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | grow-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | none | default | shrink-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | unknown": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | toString": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | __proto__": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | constructor": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | default | undefined": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | move-down": { + "gridX": 0, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | move-left": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | move-right": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": -2, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | shrink-width": { + "gridX": 1, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | grow-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | none | six columns | shrink-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | unknown": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | toString": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | __proto__": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | constructor": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | six columns | undefined": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | move-up": { + "gridX": 6, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | move-down": { + "gridX": 6, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | move-left": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | move-right": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": 4, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | shrink-width": { + "gridX": 7, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | grow-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | none | zero columns | shrink-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | unknown": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | toString": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | __proto__": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | constructor": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | zero columns | undefined": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | move-down": { + "gridX": 0, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | move-left": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | move-right": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": -5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | shrink-width": { + "gridX": 0, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | grow-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | none | three columns | shrink-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | unknown": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | toString": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | __proto__": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | constructor": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | none | three columns | undefined": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | move-up": { + "gridX": 6, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | move-down": { + "gridX": 6, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | move-left": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | move-right": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": 4, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | shrink-width": { + "gridX": 7, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | grow-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | not an array | default | shrink-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | unknown": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | toString": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | __proto__": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | constructor": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | default | undefined": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | move-down": { + "gridX": 0, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | move-left": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | move-right": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": -2, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | shrink-width": { + "gridX": 1, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | grow-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | not an array | six columns | shrink-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | unknown": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | toString": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | __proto__": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | constructor": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | six columns | undefined": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | move-up": { + "gridX": 6, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | move-down": { + "gridX": 6, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | move-left": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | move-right": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": 4, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | shrink-width": { + "gridX": 7, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | grow-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | not an array | zero columns | shrink-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | unknown": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | toString": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | __proto__": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | constructor": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | zero columns | undefined": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | move-down": { + "gridX": 0, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | move-left": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | move-right": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": -5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | shrink-width": { + "gridX": 0, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | grow-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | not an array | three columns | shrink-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | unknown": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | toString": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | __proto__": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | constructor": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | not an array | three columns | undefined": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | move-up": { + "gridX": 6, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | move-down": { + "gridX": 6, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | move-left": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | move-right": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": 4, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | shrink-width": { + "gridX": 7, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | grow-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | mixed | default | shrink-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | unknown": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | toString": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | __proto__": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | constructor": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | default | undefined": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "too wide | mixed | six columns | move-down": { + "gridX": 0, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 4 + }, + { + "id": 6, + "gridY": 4 + } + ] + }, + "too wide | mixed | six columns | move-left": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | six columns | move-right": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | six columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": -2, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | six columns | shrink-width": { + "gridX": 1, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | six columns | grow-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 4 + }, + { + "id": 6, + "gridY": 4 + }, + { + "gridY": 4 + }, + { + "id": 8, + "gridY": 4 + } + ] + }, + "too wide | mixed | six columns | shrink-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | six columns | unknown": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | six columns | toString": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | six columns | __proto__": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | six columns | constructor": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | six columns | undefined": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | zero columns | move-up": { + "gridX": 6, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | move-down": { + "gridX": 6, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | move-left": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | move-right": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": 4, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | shrink-width": { + "gridX": 7, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | grow-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [] + }, + "too wide | mixed | zero columns | shrink-height": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | unknown": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | toString": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | __proto__": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | constructor": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | zero columns | undefined": { + "gridX": 6, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "too wide | mixed | three columns | move-down": { + "gridX": 0, + "gridY": 2, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 4 + }, + { + "id": 6, + "gridY": 4 + } + ] + }, + "too wide | mixed | three columns | move-left": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | three columns | move-right": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | three columns | grow-width": { + "gridX": 8, + "gridY": 1, + "gridWidth": -5, + "gridHeight": 2, + "pushed": [] + }, + "too wide | mixed | three columns | shrink-width": { + "gridX": 0, + "gridY": 1, + "gridWidth": 5, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | three columns | grow-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 4 + }, + { + "id": 6, + "gridY": 4 + }, + { + "gridY": 4 + }, + { + "id": 8, + "gridY": 4 + } + ] + }, + "too wide | mixed | three columns | shrink-height": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | three columns | unknown": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | three columns | toString": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | three columns | __proto__": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | three columns | constructor": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "too wide | mixed | three columns | undefined": { + "gridX": 0, + "gridY": 1, + "gridWidth": 6, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | none | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "missing fields | none | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "missing fields | none | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "missing fields | none | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "missing fields | none | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | none | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "missing fields | not an array | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "missing fields | not an array | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "missing fields | not an array | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "missing fields | not an array | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | not an array | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "missing fields | mixed | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | mixed | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | mixed | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | mixed | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | mixed | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | mixed | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | mixed | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | mixed | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "missing fields | mixed | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "missing fields | mixed | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | none | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "string fields | none | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "string fields | none | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "string fields | none | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "string fields | none | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | none | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "string fields | not an array | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "string fields | not an array | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "string fields | not an array | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "string fields | not an array | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | not an array | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "string fields | mixed | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "string fields | mixed | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "string fields | mixed | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "string fields | mixed | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "string fields | mixed | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "string fields | mixed | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "string fields | mixed | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "string fields | mixed | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "string fields | mixed | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "string fields | mixed | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 5, + "gridY": 2 + }, + { + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | none | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "no placement | none | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "no placement | none | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "no placement | none | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "no placement | none | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | none | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "no placement | not an array | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "no placement | not an array | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "no placement | not an array | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [] + }, + "no placement | not an array | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | not an array | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [] + }, + "no placement | mixed | default | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 3 + }, + { + "id": 2, + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "no placement | mixed | default | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 3, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 1, + "gridY": 3 + }, + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "no placement | mixed | default | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | default | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 3 + }, + { + "id": 2, + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "no placement | mixed | six columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 3, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 1, + "gridY": 3 + }, + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "no placement | mixed | six columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | six columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 3 + }, + { + "id": 2, + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "no placement | mixed | zero columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 3, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 1, + "gridY": 3 + }, + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "no placement | mixed | zero columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | zero columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | move-up": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | move-down": { + "gridX": 0, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 3 + }, + { + "id": 2, + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "no placement | mixed | three columns | move-left": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | move-right": { + "gridX": 1, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 3, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | grow-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 3, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | shrink-width": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | grow-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 3, + "pushed": [ + { + "id": 1, + "gridY": 3 + }, + { + "id": 2, + "gridY": 3 + }, + { + "id": 5, + "gridY": 3 + }, + { + "id": 8, + "gridY": 3 + } + ] + }, + "no placement | mixed | three columns | shrink-height": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | unknown": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | toString": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | __proto__": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | constructor": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + }, + "no placement | mixed | three columns | undefined": { + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2, + "pushed": [ + { + "id": 1, + "gridY": 2 + }, + { + "id": 5, + "gridY": 2 + }, + { + "id": 8, + "gridY": 2 + } + ] + } +} diff --git a/src/composables/__tests__/fixtures/quickSearchTitle.golden.json b/src/composables/__tests__/fixtures/quickSearchTitle.golden.json new file mode 100644 index 000000000..d83ebce83 --- /dev/null +++ b/src/composables/__tests__/fixtures/quickSearchTitle.golden.json @@ -0,0 +1,455 @@ +{ + "resolveWidgetTitle | undefined | null": "t:Widget", + "resolveWidgetTitle | undefined | custom tile with title": "Mail", + "resolveWidgetTitle | undefined | custom tile without title": "t:Tile", + "resolveWidgetTitle | undefined | custom title": "My cal", + "resolveWidgetTitle | undefined | empty custom title": "t:Widget", + "resolveWidgetTitle | undefined | catalog widget": "t:Widget", + "resolveWidgetTitle | undefined | catalog widget without title": "t:Widget", + "resolveWidgetTitle | undefined | proxy to catalog": "t:Widget", + "resolveWidgetTitle | undefined | proxy to untitled": "t:Widget", + "resolveWidgetTitle | undefined | proxy to unknown": "t:Widget", + "resolveWidgetTitle | undefined | untitled widget proxying a titled one": "t:Widget", + "resolveWidgetTitle | undefined | proxy without id": "t:Widget", + "resolveWidgetTitle | undefined | registry type": "t:Chart", + "resolveWidgetTitle | undefined | registry blank name": "t:Widget", + "resolveWidgetTitle | undefined | registry without name": "t:Widget", + "resolveWidgetTitle | undefined | unknown": "t:Widget", + "resolveWidgetTitle | undefined | tile type other": "t:Chart", + "resolveWidgetTitle | empty | null": "t:Widget", + "resolveWidgetTitle | empty | custom tile with title": "Mail", + "resolveWidgetTitle | empty | custom tile without title": "t:Tile", + "resolveWidgetTitle | empty | custom title": "My cal", + "resolveWidgetTitle | empty | empty custom title": "t:Widget", + "resolveWidgetTitle | empty | catalog widget": "t:Widget", + "resolveWidgetTitle | empty | catalog widget without title": "t:Widget", + "resolveWidgetTitle | empty | proxy to catalog": "t:Widget", + "resolveWidgetTitle | empty | proxy to untitled": "t:Widget", + "resolveWidgetTitle | empty | proxy to unknown": "t:Widget", + "resolveWidgetTitle | empty | untitled widget proxying a titled one": "t:Widget", + "resolveWidgetTitle | empty | proxy without id": "t:Widget", + "resolveWidgetTitle | empty | registry type": "t:Chart", + "resolveWidgetTitle | empty | registry blank name": "t:Widget", + "resolveWidgetTitle | empty | registry without name": "t:Widget", + "resolveWidgetTitle | empty | unknown": "t:Widget", + "resolveWidgetTitle | empty | tile type other": "t:Chart", + "resolveWidgetTitle | full | null": "t:Widget", + "resolveWidgetTitle | full | custom tile with title": "Mail", + "resolveWidgetTitle | full | custom tile without title": "t:Tile", + "resolveWidgetTitle | full | custom title": "My cal", + "resolveWidgetTitle | full | empty custom title": "Calendar", + "resolveWidgetTitle | full | catalog widget": "Calendar", + "resolveWidgetTitle | full | catalog widget without title": "t:Widget", + "resolveWidgetTitle | full | proxy to catalog": "Deals overview", + "resolveWidgetTitle | full | proxy to untitled": "t:Widget", + "resolveWidgetTitle | full | proxy to unknown": "t:Widget", + "resolveWidgetTitle | full | untitled widget proxying a titled one": "Deals overview", + "resolveWidgetTitle | full | proxy without id": "t:Widget", + "resolveWidgetTitle | full | registry type": "Catalog chart", + "resolveWidgetTitle | full | registry blank name": "t:Widget", + "resolveWidgetTitle | full | registry without name": "t:Widget", + "resolveWidgetTitle | full | unknown": "t:Widget", + "resolveWidgetTitle | full | tile type other": "Catalog chart", + "activateSearchResult | no grid | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | missing | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | link | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | link without click | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focusable | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focusable with tabindex | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, not focusable | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focus not a function | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | bare | undefined": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no grid | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | missing | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | link | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | link without click | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focusable | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focusable with tabindex | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, not focusable | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focus not a function | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | bare | no placement": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no grid | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | missing | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | link | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | link without click | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focusable | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focusable with tabindex | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, not focusable | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no link, focus not a function | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | bare | id null": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | no grid | id zero": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | missing | id zero": { + "value": false, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"0\"]" + ] + }, + "activateSearchResult | link | id zero": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"0\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "link click" + ] + }, + "activateSearchResult | link without click | id zero": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"0\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "setAttribute tabindex=-1", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, focusable | id zero": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"0\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "setAttribute tabindex=-1", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, focusable with tabindex | id zero": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"0\"]", + "item.querySelector a[href]", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, not focusable | id zero": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"0\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]" + ] + }, + "activateSearchResult | no link, focus not a function | id zero": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"0\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]" + ] + }, + "activateSearchResult | bare | id zero": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"0\"]", + "item.querySelector a[href]" + ] + }, + "activateSearchResult | no grid | id number": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | missing | id number": { + "value": false, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"12\"]" + ] + }, + "activateSearchResult | link | id number": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"12\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "link click" + ] + }, + "activateSearchResult | link without click | id number": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"12\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "setAttribute tabindex=-1", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, focusable | id number": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"12\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "setAttribute tabindex=-1", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, focusable with tabindex | id number": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"12\"]", + "item.querySelector a[href]", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, not focusable | id number": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"12\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]" + ] + }, + "activateSearchResult | no link, focus not a function | id number": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"12\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]" + ] + }, + "activateSearchResult | bare | id number": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"12\"]", + "item.querySelector a[href]" + ] + }, + "activateSearchResult | no grid | id with quote": { + "value": false, + "log": [ + "getElementById launchpad-main-content" + ] + }, + "activateSearchResult | missing | id with quote": { + "value": false, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"a\\\"b\"]" + ] + }, + "activateSearchResult | link | id with quote": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"a\\\"b\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "link click" + ] + }, + "activateSearchResult | link without click | id with quote": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"a\\\"b\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "setAttribute tabindex=-1", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, focusable | id with quote": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"a\\\"b\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]", + "setAttribute tabindex=-1", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, focusable with tabindex | id with quote": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"a\\\"b\"]", + "item.querySelector a[href]", + "focus {\"preventScroll\":true}" + ] + }, + "activateSearchResult | no link, not focusable | id with quote": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"a\\\"b\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]" + ] + }, + "activateSearchResult | no link, focus not a function | id with quote": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"a\\\"b\"]", + "scroll {\"behavior\":\"smooth\",\"block\":\"center\"}", + "item.querySelector a[href]" + ] + }, + "activateSearchResult | bare | id with quote": { + "value": true, + "log": [ + "getElementById launchpad-main-content", + "grid.querySelector .launchpad-grid-item[data-placement-id=\"a\\\"b\"]", + "item.querySelector a[href]" + ] + } +} diff --git a/src/composables/__tests__/nudgePlacement.golden.spec.js b/src/composables/__tests__/nudgePlacement.golden.spec.js new file mode 100644 index 000000000..6be0026c2 --- /dev/null +++ b/src/composables/__tests__/nudgePlacement.golden.spec.js @@ -0,0 +1,96 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for nudgePlacement(): every action against a set of placements, + * neighbours and column counts, compared with + * fixtures/nudgePlacement.golden.json. Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it } from 'vitest' +import { nudgePlacement } from '../useGridManager.js' + +const FIXTURE = path.resolve(__dirname, 'fixtures/nudgePlacement.golden.json') + +const ACTIONS = [ + 'move-up', + 'move-down', + 'move-left', + 'move-right', + 'grow-width', + 'shrink-width', + 'grow-height', + 'shrink-height', + 'unknown', + 'toString', + '__proto__', + 'constructor', + undefined, +] + +const PLACEMENTS = { + 'top left': { id: 1, gridX: 0, gridY: 0, gridWidth: 2, gridHeight: 2 }, + 'right edge': { id: 1, gridX: 10, gridY: 3, gridWidth: 2, gridHeight: 3 }, + 'too wide': { id: 1, gridX: 8, gridY: 1, gridWidth: 6, gridHeight: 2 }, + 'missing fields': { id: 1 }, + 'string fields': { + id: 1, + gridX: '2', + gridY: '1', + gridWidth: '3', + gridHeight: '3', + }, + 'no placement': undefined, +} + +const NEIGHBOURS = { + none: [], + 'not an array': 'nope', + mixed: [ + null, + undefined, + { id: 1, gridX: 0, gridY: 0, gridWidth: 12, gridHeight: 12 }, + { id: 2, gridX: 0, gridY: 2, gridWidth: 2, gridHeight: 2 }, + { id: 3, gridX: 2, gridY: 0, gridWidth: 1, gridHeight: 1 }, + { id: 4, gridX: 9, gridY: 4, gridWidth: 3, gridHeight: 2 }, + { id: 5 }, + { id: 6, gridX: 'x', gridY: 3, gridWidth: Infinity, gridHeight: 2 }, + { id: 7, gridX: 11, gridY: 6, gridWidth: 1, gridHeight: 1 }, + { gridX: 1, gridY: 1, gridWidth: 1, gridHeight: 1 }, + { id: 8, gridX: 0, gridY: 1, gridWidth: 2, gridHeight: NaN }, + { id: 9, gridX: 0, gridY: 5, gridWidth: '2', gridHeight: '9' }, + ], +} + +const OPTIONS = { + default: undefined, + 'six columns': { gridColumns: 6 }, + 'zero columns': { gridColumns: 0 }, + 'three columns': { gridColumns: 3 }, +} + +describe('nudgePlacement (golden)', () => { + it('matches the recorded results', () => { + const actual = {} + for (const [p, placement] of Object.entries(PLACEMENTS)) { + for (const [n, neighbours] of Object.entries(NEIGHBOURS)) { + for (const [o, options] of Object.entries(OPTIONS)) { + for (const action of ACTIONS) { + actual[`${p} | ${n} | ${o} | ${action}`] = nudgePlacement( + placement, + action, + neighbours, + options, + ) + } + } + } + } + if (process.env.RECORD_GOLDEN === '1') { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + expect(actual).toEqual(JSON.parse(fs.readFileSync(FIXTURE, 'utf8'))) + }) +}) diff --git a/src/composables/__tests__/placeNewWidget.golden.spec.js b/src/composables/__tests__/placeNewWidget.golden.spec.js new file mode 100644 index 000000000..9fa389caa --- /dev/null +++ b/src/composables/__tests__/placeNewWidget.golden.spec.js @@ -0,0 +1,37 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Characterisation tests pinning `placeNewWidget`'s size fallbacks and + * bottom-edge computation for malformed input, so it can be split into + * named steps without changing behaviour. + */ + +import { describe, expect, it } from 'vitest' +import { DEFAULT_H, DEFAULT_W, placeNewWidget } from '../useGridManager.js' + +describe('placeNewWidget fallbacks', () => { + it.each([ + [null, DEFAULT_W, DEFAULT_H], + [undefined, DEFAULT_W, DEFAULT_H], + [0, DEFAULT_W, DEFAULT_H], + [{ w: 0, h: -1 }, DEFAULT_W, DEFAULT_H], + [{ w: NaN, h: Infinity }, DEFAULT_W, DEFAULT_H], + [{ w: '3', h: '2' }, DEFAULT_W, DEFAULT_H], + [{ w: 0.5, h: 7 }, 0.5, 7], + ])('sizes %j', (spec, w, h) => { + expect(placeNewWidget(spec, [])).toEqual({ x: 0, y: 0, w, h, pushed: [] }) + }) + + it.each([ + [null, 0], + ['x', 0], + [[{}], 1], + [[{ gridY: 'a', gridHeight: 'b' }], 1], + [[{ gridY: 3 }, { gridHeight: 5 }], 5], + [[{ gridY: -4, gridHeight: 2 }], 0], + [[{ gridY: 2, gridHeight: 0 }, { gridY: 1, gridHeight: 1 }], 2], + ])('appends below %j', (placements, y) => { + expect(placeNewWidget({ w: 1, h: 1 }, placements)).toEqual({ x: 0, y, w: 1, h: 1, pushed: [] }) + }) +}) diff --git a/src/composables/__tests__/quickSearchTitle.golden.spec.js b/src/composables/__tests__/quickSearchTitle.golden.spec.js new file mode 100644 index 000000000..9288697c8 --- /dev/null +++ b/src/composables/__tests__/quickSearchTitle.golden.spec.js @@ -0,0 +1,193 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for resolveWidgetTitle and activateSearchResult: a matrix of + * placements and widget catalogs, and of opened results against fake grid + * items, compared with fixtures/quickSearchTitle.golden.json case by case. + * Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + dashboardWidgetRegistry: { + chart: { displayName: 'Chart' }, + blank: { displayName: '' }, + bare: {}, + }, +})) + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, str) => `t:${str}`, +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/quickSearchTitle.golden.json') + +const PLACEMENTS = { + null: null, + 'custom tile with title': { + tileType: 'custom', + tileTitle: 'Mail', + customTitle: 'X', + }, + 'custom tile without title': { tileType: 'custom', tileTitle: '' }, + 'custom title': { widgetId: 'calendar', customTitle: 'My cal' }, + 'empty custom title': { widgetId: 'calendar', customTitle: '' }, + 'catalog widget': { widgetId: 'calendar' }, + 'catalog widget without title': { widgetId: 'untitled' }, + 'proxy to catalog': { widgetId: 'nc-widget', content: { widgetId: 'deals' } }, + 'proxy to untitled': { + widgetId: 'nc-widget', + content: { widgetId: 'untitled' }, + }, + 'proxy to unknown': { widgetId: 'nc-widget', content: { widgetId: 'nope' } }, + 'untitled widget proxying a titled one': { + widgetId: 'untitled', + content: { widgetId: 'deals' }, + }, + 'proxy without id': { widgetId: 'nc-widget', content: {} }, + 'registry type': { widgetId: 'chart', content: { widgetId: 'nope' } }, + 'registry blank name': { widgetId: 'blank' }, + 'registry without name': { widgetId: 'bare' }, + unknown: { widgetId: 'mystery' }, + 'tile type other': { tileType: 'app', widgetId: 'chart' }, +} + +const CATALOGS = { + undefined, + empty: [], + full: [ + { id: 'calendar', title: 'Calendar' }, + { id: 'deals', title: 'Deals overview' }, + { id: 'untitled', title: '' }, + { id: 'chart', title: 'Catalog chart' }, + ], +} + +/** + * A fake grid item that logs what is done to it. + * + * @param {object} spec Which methods and attributes the item has. + * @param {Array<string>} log Receives one entry per effect. + * @return {object} The item. + */ +function fakeItem(spec, log) { + const item = { attrs: { ...(spec.attrs || {}) } } + item.hasAttribute = (name) => name in item.attrs + item.setAttribute = (name, value) => { + log.push(`setAttribute ${name}=${value}`) + item.attrs[name] = value + } + if (spec.scroll) { + item.scrollIntoView = (opts) => log.push(`scroll ${JSON.stringify(opts)}`) + } + if (spec.focus === 'broken') { + item.focus = 'not a function' + } else if (spec.focus) { + item.focus = (opts) => log.push(`focus ${JSON.stringify(opts)}`) + } + item.querySelector = (selector) => { + log.push(`item.querySelector ${selector}`) + if (!spec.link) { + return null + } + return spec.link === 'clickable' + ? { click: () => log.push('link click') } + : { click: 'not a function' } + } + return item +} + +const ITEMS = { + missing: null, + link: { scroll: true, focus: true, link: 'clickable' }, + 'link without click': { scroll: true, focus: true, link: 'broken' }, + 'no link, focusable': { scroll: true, focus: true }, + 'no link, focusable with tabindex': { focus: true, attrs: { tabindex: '0' } }, + 'no link, not focusable': { scroll: true }, + 'no link, focus not a function': { scroll: true, focus: 'broken' }, + bare: {}, +} + +const RESULTS = { + undefined, + 'no placement': {}, + 'id null': { placement: { id: null } }, + 'id zero': { placement: { id: 0 } }, + 'id number': { placement: { id: 12 } }, + 'id with quote': { placement: { id: 'a"b' } }, +} + +/** + * Run activateSearchResult with a grid (or none) holding one item. + * + * @param {object} result The opened result. + * @param {{grid: boolean, item: object|null}} setup The page. + * @return {Promise<object>} What it returned and did. + */ +async function activate(result, setup) { + const { activateSearchResult } = await import('../useTileSearchHost.js') + const log = [] + const grid = { + querySelector: (selector) => { + log.push(`grid.querySelector ${selector}`) + return setup.item ? fakeItem(setup.item, log) : null + }, + } + vi.spyOn(document, 'getElementById').mockImplementation((id) => { + log.push(`getElementById ${id}`) + return setup.grid ? grid : null + }) + const value = activateSearchResult(result) + return { value, log } +} + +/** + * Record every case of the two functions. + * + * @return {Promise<object>} The outcomes by case name. + */ +async function record() { + const { resolveWidgetTitle } = await import('../../utils/widgetTitle.js') + const actual = {} + for (const [catalogName, catalog] of Object.entries(CATALOGS)) { + for (const [name, placement] of Object.entries(PLACEMENTS)) { + actual[`resolveWidgetTitle | ${catalogName} | ${name}`] = + resolveWidgetTitle(placement, catalog) + } + } + for (const [resultName, result] of Object.entries(RESULTS)) { + actual[`activateSearchResult | no grid | ${resultName}`] = await activate( + result, + { grid: false, item: null }, + ) + vi.restoreAllMocks() + for (const [itemName, item] of Object.entries(ITEMS)) { + actual[`activateSearchResult | ${itemName} | ${resultName}`] = + await activate(result, { grid: true, item }) + vi.restoreAllMocks() + } + } + return actual +} + +describe('quick search title and activation (golden)', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + it('matches the recorded outcomes case by case', async () => { + const actual = await record() + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const [name, value] of Object.entries(expected)) { + expect(actual[name], name).toEqual(value) + } + }) +}) diff --git a/src/composables/__tests__/useCalculatedFields.spec.js b/src/composables/__tests__/useCalculatedFields.spec.js new file mode 100644 index 000000000..86892b890 --- /dev/null +++ b/src/composables/__tests__/useCalculatedFields.spec.js @@ -0,0 +1,110 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The calculated-fields store and composable re-evaluate the dashboard when a + * widget's data or the filters change (tasks 17, 18). + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it } from 'vitest' +import { effectScope, nextTick, ref } from 'vue' +import { useCalculatedFieldsStore } from '../../stores/calculatedFields.js' +import { parse } from '../../utils/calculatedFields/parser.js' +import { useCalculatedFields } from '../useCalculatedFields.js' + +/** + * A widget with calculated fields parsed from expressions. + * + * @param {string} id - The widget id. + * @param {Record<string, string>} fields - Name => expression. + * @return {object} + */ +function widget(id, fields) { + const names = Object.keys(fields) + return { + id, + calculatedFields: names.map((name) => ({ name, expression: fields[name], compiledExpression: parse(fields[name], { calculatedNames: names }) })), + } +} + +describe('useCalculatedFieldsStore', () => { + beforeEach(() => { + setActivePinia(createPinia()) + }) + + it('re-evaluates the readers of a widget when its data arrives', () => { + const store = useCalculatedFieldsStore() + store.setWidgets([widget('a', { share: 'part / widget:b.whole * 100' }), { id: 'b' }]) + store.setWidgetData('a', { part: 10 }) + + expect(store.valuesOf('a')).toEqual({ share: null }) + + store.setWidgetData('b', { whole: 40 }) + + expect(store.valuesOf('a')).toEqual({ share: 25 }) + expect(store.errorsOf('a')).toEqual({}) + }) + + it('counts filter changes and keeps the filters', () => { + const store = useCalculatedFieldsStore() + store.setFilters([{ dimension: 'year', value: 2026 }]) + store.setFilters(null) + + expect(store.filterRevision).toBe(2) + expect(store.filters).toEqual([]) + }) + + it('answers empty values and errors for an unknown widget, and forgets all on reset', () => { + const store = useCalculatedFieldsStore() + store.setWidgets([widget('w', { one: '1' })]) + + expect(store.valuesOf('w')).toEqual({ one: 1 }) + expect(store.valuesOf('nope')).toEqual({}) + + store.reset() + + expect(store.valuesOf('w')).toEqual({}) + expect(store.widgets).toEqual([]) + }) +}) + +describe('useCalculatedFields', () => { + beforeEach(() => { + setActivePinia(createPinia()) + }) + + it('reports the widget data and answers values and errors as maps that follow changes', async () => { + const store = useCalculatedFieldsStore() + store.setWidgets([widget('w', { ratio: 'a / b' })]) + const data = ref({ a: 6, b: 3 }) + const scope = effectScope() + const { values, errors } = scope.run(() => useCalculatedFields({ widgetId: 'w', data })) + + expect(values.value.get('ratio')).toBe(2) + expect(errors.value.size).toBe(0) + + data.value = { a: 6, b: 0 } + await nextTick() + + expect(values.value.get('ratio')).toBeNull() + expect(errors.value.get('ratio')).toMatchObject({ expression: 'a / b' }) + scope.stop() + }) + + it('passes filter changes to the store', async () => { + const store = useCalculatedFieldsStore() + const filters = ref([]) + const scope = effectScope() + scope.run(() => useCalculatedFields({ widgetId: 'w', filters })) + + filters.value = [{ dimension: 'region', value: 'north' }] + await nextTick() + + expect(store.filters).toEqual([{ dimension: 'region', value: 'north' }]) + expect(store.filterRevision).toBe(1) + scope.stop() + }) +}) diff --git a/src/composables/__tests__/useDashboardFilter.spec.js b/src/composables/__tests__/useDashboardFilter.spec.js new file mode 100644 index 000000000..51690c5cf --- /dev/null +++ b/src/composables/__tests__/useDashboardFilter.spec.js @@ -0,0 +1,93 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useDashboardFilter: the `?f=` parameter round-trips the filter state, uses + * the short keys, stays small, and reads a malformed value as no filter + * (drill-down-cross-widget-filter task 20; REQ-CWF-003). + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { deserializeFilterState, serializeFilterState } from '../useDashboardFilter.js' + +const CLAUSES = [ + { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: 'w-chart-gemeenten', pinned: false }, + { dimension: 'wijkCode', operator: 'in', value: ['WK0355001', 'WK0355002'], source: 'widgetClick', sourceWidgetId: 'w-map-wijken', pinned: false }, + { dimension: 'period.month', operator: 'between', value: ['2026-01', '2026-03'], source: 'userExplicit', sourceWidgetId: null, pinned: true }, + { dimension: 'naam', operator: 'contains', value: 'Zeiste ëë', source: 'savedView', sourceWidgetId: null, pinned: false }, + { dimension: 'status', operator: 'notNull', source: 'userExplicit', sourceWidgetId: null, pinned: false }, +] + +/** + * Decode a parameter the way a reader would, to inspect its JSON. + * + * @param {string} param The parameter value. + * @return {unknown} + */ +function payloadOf(param) { + const base64 = param.replace(/-/g, '+').replace(/_/g, '/') + const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4)) + return JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)))) +} + +let warn + +beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) + +afterEach(() => { + warn.mockRestore() +}) + +describe('useDashboardFilter', () => { + it('round-trips every operator, value shape and source', () => { + const param = serializeFilterState(CLAUSES) + + expect(param).toMatch(/^[A-Za-z0-9_-]+$/) + expect(deserializeFilterState(param)).toEqual({ clauses: CLAUSES, error: null }) + }) + + it('writes the short keys and leaves out what is empty', () => { + expect(payloadOf(serializeFilterState(CLAUSES.slice(2, 3).concat(CLAUSES.slice(4))))).toEqual([ + { d: 'period.month', o: 'between', v: ['2026-01', '2026-03'], s: 'userExplicit', p: true }, + { d: 'status', o: 'notNull', s: 'userExplicit' }, + ]) + }) + + it('keeps ten clauses under 2 KB', () => { + const ten = Array.from({ length: 10 }, (_, i) => ({ + dimension: `dimension${i}`, operator: 'in', value: [`GM03${i}5`, `GM03${i}6`], source: 'widgetClick', sourceWidgetId: `w-widget-${i}`, + })) + + expect(serializeFilterState(ten).length).toBeLessThan(2048) + }) + + it('has no parameter for no clauses, and no parameter reads as no clauses', () => { + expect(serializeFilterState([])).toBe('') + expect(serializeFilterState(undefined)).toBe('') + expect(deserializeFilterState('')).toEqual({ clauses: [], error: null }) + expect(deserializeFilterState(null)).toEqual({ clauses: [], error: null }) + expect(warn).not.toHaveBeenCalled() + }) + + it('a clause without a source comes back as URL bootstrap', () => { + const param = btoa(JSON.stringify([{ d: 'status', o: 'eq', v: 'open' }])).replace(/=+$/, '') + + expect(deserializeFilterState(param).clauses).toEqual([ + { dimension: 'status', operator: 'eq', value: 'open', source: 'urlBootstrap', sourceWidgetId: null, pinned: false }, + ]) + }) + + it.each([ + ['not base64url', '%%%'], + ['not JSON', btoa('not json')], + ['not a list', btoa(JSON.stringify({ d: 'status' }))], + ['an unknown operator', btoa(JSON.stringify([{ d: 'status', o: 'like', v: 'x' }]))], + ['a clause without a value', btoa(JSON.stringify([{ d: 'status', o: 'eq' }]))], + ['an unknown source', btoa(JSON.stringify([{ d: 'status', o: 'eq', v: 1, s: 'hack' }]))], + ])('reads a parameter that is %s as no filter, with one warning', (_label, param) => { + expect(deserializeFilterState(param.replace(/=+$/, ''))).toEqual({ clauses: [], error: 'malformed' }) + expect(warn).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/composables/__tests__/useDashboardFilterSession.spec.js b/src/composables/__tests__/useDashboardFilterSession.spec.js new file mode 100644 index 000000000..a866701e6 --- /dev/null +++ b/src/composables/__tests__/useDashboardFilterSession.spec.js @@ -0,0 +1,96 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useDashboardFilterSession: the first dashboard of a page load opens with + * the URL's filter, a later one starts empty, the bus follows the + * dashboard's own hierarchies and the chips get their level labels + * (drill-down-cross-widget-filter task 4; REQ-CWF-003, REQ-CWF-004). + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { serializeFilterState } from '../useDashboardFilter.js' +import { hierarchiesOf, levelLabels, useDashboardFilterSession } from '../useDashboardFilterSession.js' + +const ADMINISTRATIVE = { + id: 'nl-administrative', + levels: [ + { dimension: 'provincieCode', label: 'Provincie' }, + { dimension: 'gemeenteCode', parentDimension: 'provincieCode', label: 'Gemeente' }, + { dimension: 'wijkCode', parentDimension: 'gemeenteCode', label: 'Wijk' }, + ], +} +const ZEIST = { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: 'w-a', pinned: false } + +/** + * A location and history at a URL. + * + * @param {string} href The URL. + * @return {{location: {href: string}, history: object}} + */ +function browserAt(href) { + const location = { href } + return { location, history: { state: null, replaceState: vi.fn((_s, _t, url) => { location.href = url }) } } +} + +beforeEach(() => vi.useFakeTimers()) +afterEach(() => vi.useRealTimers()) + +describe('useDashboardFilterSession', () => { + const bookmarked = 'https://cloud.example/apps/launchpad/?f=' + serializeFilterState([ZEIST]) + + it('the first dashboard opens with the bookmarked filter', () => { + const { location, history } = browserAt(bookmarked) + const session = useDashboardFilterSession({ dashboard: { hierarchies: [ADMINISTRATIVE] }, readUrl: true, location, history }) + + expect(session.clauses.value.map((clause) => [clause.dimension, clause.source])).toEqual([['gemeenteCode', 'urlBootstrap']]) + }) + + it('a dashboard switched to later starts empty', () => { + const { location, history } = browserAt(bookmarked) + const session = useDashboardFilterSession({ dashboard: { hierarchies: [ADMINISTRATIVE] }, readUrl: false, location, history }) + + expect(session.clauses.value).toEqual([]) + }) + + it('the bus drills down through the dashboard hierarchy', () => { + const { location, history } = browserAt('https://cloud.example/apps/launchpad/') + const session = useDashboardFilterSession({ dashboard: { hierarchies: [ADMINISTRATIVE] }, readUrl: true, location, history }) + + session.bus.publish( + { dimension: 'wijkCode', operator: 'eq', value: 'WK035501', source: 'widgetClick', sourceWidgetId: 'w-wijken' }, + { row: { wijkCode: 'WK035501', gemeenteCode: 'GM0355', provincieCode: 'PV26' } }, + ) + + expect(session.clauses.value.find((clause) => clause.dimension === 'gemeenteCode')).toMatchObject({ value: 'GM0355', source: 'parentScope' }) + // The nl-administrative preset's own labels, in the reader's language (REQ-CWF-011). + expect(session.labels).toEqual({ provincieCode: 'Province', gemeenteCode: 'Municipality', wijkCode: 'District' }) + }) + + it('remove and reset reach the bus, stop writes the URL one last time', () => { + const { location, history } = browserAt(bookmarked) + const session = useDashboardFilterSession({ dashboard: null, readUrl: true, location, history }) + + expect(session.remove('gemeenteCode')).toBe(true) + expect(session.reset()).toBe(false) + session.stop() + + expect(new URL(location.href).searchParams.has('f')).toBe(false) + }) +}) + +describe('hierarchiesOf / levelLabels', () => { + it('keeps only descriptors with levels and labels only labelled levels', () => { + const hierarchies = hierarchiesOf({ hierarchies: [ADMINISTRATIVE, null, { id: 'broken' }] }) + + expect(hierarchies).toEqual([ADMINISTRATIVE]) + expect(hierarchiesOf({})).toEqual([]) + expect(levelLabels([{ id: 'x', levels: [{ dimension: 'a', label: '' }, { dimension: 'b', label: 'B' }] }])).toEqual({ b: 'B' }) + }) + + it('labels a preset\'s levels with the preset\'s labels in the reader\'s language (REQ-CWF-011)', () => { + const stored = { id: 'nl-administrative', levels: [{ dimension: 'provincieCode', label: 'Province' }, { dimension: 'blokCode', label: 'Blok' }] } + + expect(levelLabels([stored])).toEqual({ provincieCode: 'Province', blokCode: 'Blok' }) + }) +}) diff --git a/src/composables/__tests__/useDashboardPresence.spec.js b/src/composables/__tests__/useDashboardPresence.spec.js new file mode 100644 index 000000000..5a7945e6e --- /dev/null +++ b/src/composables/__tests__/useDashboardPresence.spec.js @@ -0,0 +1,110 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useDashboardPresence: announces the editor, renews on a heartbeat, takes + * the colleagues the server answers, and withdraws on stop and page hide + * (building-edit-a-dashboard-together, task 1.1). + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { PRESENCE_BEAT_MS, useDashboardPresence } from '../useDashboardPresence.js' + +vi.mock('../../services/api.js', () => ({ + api: { + joinPresence: vi.fn(), + leavePresence: vi.fn(() => Promise.resolve({ status: 204 })), + }, +})) + +function failure(status) { + return Object.assign(new Error('http'), { response: { status } }) +} + +beforeEach(() => { + vi.clearAllMocks() + vi.useFakeTimers() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('useDashboardPresence', () => { + it('announces, renews every beat with the latest colleagues, and withdraws on stop', async () => { + const marieke = { displayName: 'Marieke Jansen', since: '2026-11-14T10:42:00+01:00' } + api.joinPresence + .mockResolvedValueOnce({ data: { editors: [] } }) + .mockResolvedValueOnce({ data: { editors: [marieke] } }) + const presence = useDashboardPresence() + + expect(await presence.start('d-1')).toBe(true) + expect(presence.state.status).toBe('editing') + expect(presence.state.editors).toEqual([]) + + await vi.advanceTimersByTimeAsync(PRESENCE_BEAT_MS) + expect(api.joinPresence).toHaveBeenCalledTimes(2) + expect(presence.state.editors).toEqual([marieke]) + + await presence.stop() + expect(api.leavePresence).toHaveBeenCalledWith('d-1') + expect(presence.state).toEqual({ status: 'none', uuid: null, editors: [] }) + await vi.advanceTimersByTimeAsync(PRESENCE_BEAT_MS) + expect(api.joinPresence).toHaveBeenCalledTimes(2) + }) + + it('a refused start reports false, starts no heartbeat and calls no onRefused', async () => { + const onRefused = vi.fn() + api.joinPresence.mockRejectedValue(failure(403)) + const presence = useDashboardPresence({ onRefused }) + + expect(await presence.start('d-1')).toBe(false) + expect(presence.state.status).toBe('forbidden') + await vi.advanceTimersByTimeAsync(PRESENCE_BEAT_MS) + expect(api.joinPresence).toHaveBeenCalledTimes(1) + expect(onRefused).not.toHaveBeenCalled() + + await presence.stop() + expect(api.leavePresence).not.toHaveBeenCalled() + }) + + it('a refused renewal stops the heartbeat and calls onRefused once', async () => { + const onRefused = vi.fn() + api.joinPresence.mockResolvedValueOnce({ data: { editors: [] } }).mockRejectedValue(failure(404)) + const presence = useDashboardPresence({ onRefused }) + await presence.start('d-1') + + await vi.advanceTimersByTimeAsync(PRESENCE_BEAT_MS * 2) + expect(onRefused).toHaveBeenCalledTimes(1) + expect(api.joinPresence).toHaveBeenCalledTimes(2) + expect(presence.state.status).toBe('forbidden') + }) + + it('a network failure keeps the last colleagues and tries again', async () => { + const marieke = { displayName: 'Marieke Jansen', since: 's' } + api.joinPresence + .mockResolvedValueOnce({ data: { editors: [marieke] } }) + .mockRejectedValueOnce(new Error('Network Error')) + .mockResolvedValueOnce({ data: { editors: [] } }) + const presence = useDashboardPresence() + await presence.start('d-1') + + await vi.advanceTimersByTimeAsync(PRESENCE_BEAT_MS) + expect(presence.state.editors).toEqual([marieke]) + expect(presence.state.status).toBe('editing') + await vi.advanceTimersByTimeAsync(PRESENCE_BEAT_MS) + expect(presence.state.editors).toEqual([]) + await presence.stop() + }) + + it('withdraws with keepalive when the page is hidden while editing', async () => { + api.joinPresence.mockResolvedValue({ data: { editors: [] } }) + const presence = useDashboardPresence() + await presence.start('d-1') + + window.dispatchEvent(new Event('pagehide')) + expect(api.leavePresence).toHaveBeenCalledWith('d-1', true) + await presence.stop() + }) +}) diff --git a/src/composables/__tests__/useEmbedContext.spec.js b/src/composables/__tests__/useEmbedContext.spec.js new file mode 100644 index 000000000..e1e022f95 --- /dev/null +++ b/src/composables/__tests__/useEmbedContext.spec.js @@ -0,0 +1,161 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The iframe side of an embed: it loads its subject with the URL token, or + * the SDK's, as a Bearer credential; it answers only the parent window at an + * origin the token lists; it relays events and resize answers only there; + * and it shows only the actions the token's scope allows. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-006--js-sdk-exposes-render-event-and-resize-apis + */ + +import { describe, expect, it, vi } from 'vitest' +import { MESSAGES } from '../../embed-sdk/src/postMessage.js' +import { subjectOf, useEmbedContext } from '../useEmbedContext.js' + +const HOST = 'https://www.zeist.nl' + +/** + * A token whose claims list the host origins. + * + * @param {Array<string>} hostOrigins The origins. + * @return {string} + */ +function jwt(hostOrigins = [HOST]) { + const claims = btoa(JSON.stringify({ iss: 'launchpad', jti: 'token-1', hostOrigins })).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_') + return `eyJhbGciOiJSUzI1NiJ9.${claims}.c2ln` +} + +/** + * A framed iframe window. + * + * @param {string} search The query string. + * @return {object} + */ +function frame(search = '') { + return { + location: { pathname: '/index.php/apps/launchpad/embed/widget/42', search }, + parent: { postMessage: vi.fn() }, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + document: { documentElement: { scrollWidth: 600, scrollHeight: 420 } }, + } +} + +const PAYLOAD = { + subjectType: 'widget', + scope: { mode: 'read-with-interactions', allowedActions: ['drillDown'], allowedFilters: ['status'] }, + filters: { gemeente: 'Zeist' }, + themeCss: ':root{--c-primary:#004f9f;}', + placements: [{ id: 42 }], +} + +describe('useEmbedContext', () => { + it('reads the subject from the embed path', () => { + expect(subjectOf('/index.php/apps/launchpad/embed/dashboard/dash%20uuid/')).toEqual({ subjectType: 'dashboard', subjectId: 'dash uuid', base: '/index.php/apps/launchpad' }) + expect(subjectOf('/apps/launchpad/embed/report/1')).toEqual({ subjectType: '', subjectId: '', base: '' }) + }) + + it('loads the subject with the URL token as a Bearer credential, once', async () => { + const win = frame(`?token=${jwt()}&viewport=small`) + const load = vi.fn().mockResolvedValue(PAYLOAD) + const context = useEmbedContext({ win, load }) + + const stop = context.start() + await context.fetchSubject() + + expect(load).toHaveBeenCalledTimes(1) + expect(load).toHaveBeenCalledWith('/index.php/apps/launchpad/embed/widget/42/data', jwt(), { viewport: 'small' }) + expect(context.placements.value).toEqual([{ id: 42 }]) + expect(context.filters.value).toEqual({ gemeente: 'Zeist' }) + expect(context.themeCss.value).toBe(':root{--c-primary:#004f9f;}') + expect(win.addEventListener).toHaveBeenCalledWith('message', context.onMessage) + stop() + expect(win.removeEventListener).toHaveBeenCalledWith('message', context.onMessage) + }) + + it('answers the handshake of a listed parent with ready, to that origin only', async () => { + const win = frame(`?token=${jwt()}`) + const context = useEmbedContext({ win, load: vi.fn().mockResolvedValue(PAYLOAD) }) + + await context.onMessage({ source: win.parent, origin: 'https://WWW.zeist.nl', data: { type: MESSAGES.init, token: 'ignored', nonce: 'n1' } }) + + expect(win.parent.postMessage).toHaveBeenCalledWith({ type: MESSAGES.ready, nonce: 'n1' }, HOST) + expect(context.parentOrigin.value).toBe(HOST) + expect(context.token.value).toBe(jwt()) + }) + + it('takes the token from the handshake when the URL has none', async () => { + const win = frame('') + const load = vi.fn().mockResolvedValue(PAYLOAD) + const context = useEmbedContext({ win, load }) + + await context.onMessage({ source: win.parent, origin: HOST, data: { type: MESSAGES.init, token: jwt(), nonce: 'n2' } }) + + expect(load).toHaveBeenCalledWith('/index.php/apps/launchpad/embed/widget/42/data', jwt(), {}) + expect(win.parent.postMessage).toHaveBeenCalledWith({ type: MESSAGES.ready, nonce: 'n2' }, HOST) + }) + + it('says nothing to a parent the token does not list, or to another window', async () => { + const win = frame(`?token=${jwt()}`) + const load = vi.fn().mockResolvedValue(PAYLOAD) + const context = useEmbedContext({ win, load }) + + await context.onMessage({ source: win.parent, origin: 'https://evil.example.com', data: { type: MESSAGES.init, nonce: 'n3' } }) + await context.onMessage({ source: {}, origin: HOST, data: { type: MESSAGES.init, nonce: 'n4' } }) + await context.onMessage({ source: win.parent, origin: HOST, data: 'launchpad-embed:init' }) + + expect(win.parent.postMessage).not.toHaveBeenCalled() + expect(context.parentOrigin.value).toBe('') + expect(context.relay('export', {})).toBe(false) + }) + + it('passes the server refusal back on the handshake', async () => { + const win = frame(`?token=${jwt()}`) + const refusal = { response: { data: { error: 'token_revoked', message: 'The provided token has been revoked' } } } + const context = useEmbedContext({ win, load: vi.fn().mockRejectedValue(refusal) }) + + await context.onMessage({ source: win.parent, origin: HOST, data: { type: MESSAGES.init, nonce: 'n5' } }) + + expect(win.parent.postMessage).toHaveBeenCalledWith( + { type: MESSAGES.error, nonce: 'n5', error: 'token_revoked', message: 'The provided token has been revoked' }, + HOST, + ) + expect(context.error.value.error).toBe('token_revoked') + }) + + it('reports a missing token or an unreadable answer without a request', async () => { + const load = vi.fn().mockRejectedValue(new Error('network')) + const bare = useEmbedContext({ win: frame(''), load }) + await bare.fetchSubject() + expect(load).not.toHaveBeenCalled() + expect(bare.error.value.error).toBe('missing_token') + + const broken = useEmbedContext({ win: frame(`?token=${jwt()}`), load }) + await broken.fetchSubject() + expect(broken.error.value).toEqual({ error: 'unavailable', message: 'The embed could not be loaded.' }) + }) + + it('relays events and answers resize once the parent is known', async () => { + const win = frame(`?token=${jwt()}`) + const context = useEmbedContext({ win, load: vi.fn().mockResolvedValue(PAYLOAD) }) + await context.onMessage({ source: win.parent, origin: HOST, data: { type: MESSAGES.init, nonce: 'n6' } }) + + expect(context.relay('drillDown', { status: 'open' })).toBe(true) + await context.onMessage({ source: win.parent, origin: HOST, data: { type: MESSAGES.resize, nonce: 'r1', width: 640, height: 360 } }) + + expect(win.parent.postMessage).toHaveBeenCalledWith({ type: MESSAGES.event, event: 'drillDown', payload: { status: 'open' } }, HOST) + expect(win.parent.postMessage).toHaveBeenCalledWith({ type: MESSAGES.resized, nonce: 'r1', width: 640, height: 420 }, HOST) + }) + + it('allows only the actions the scope names', async () => { + const context = useEmbedContext({ win: frame(`?token=${jwt()}`), load: vi.fn().mockResolvedValue(PAYLOAD) }) + expect(context.canRun('drillDown')).toBe(false) + + await context.fetchSubject() + + expect(context.canRun('drillDown')).toBe(true) + expect(context.canRun('export')).toBe(false) + }) +}) diff --git a/src/composables/__tests__/useFilterBus.spec.js b/src/composables/__tests__/useFilterBus.spec.js new file mode 100644 index 000000000..824f54c37 --- /dev/null +++ b/src/composables/__tests__/useFilterBus.spec.js @@ -0,0 +1,321 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useFilterBus: conflict resolution, toggling, reset and hierarchy resolution + * (drill-down-cross-widget-filter tasks 18 and 19; REQ-CWF-001, -002, -004, + * -005, -006). + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { breadcrumbPath, resolveHierarchy, useFilterBus } from '../useFilterBus.js' + +const NL_ADMINISTRATIVE = { + id: 'nl-administrative', + levels: [ + { dimension: 'provincieCode', label: 'hierarchy.level.province', parentDimension: null }, + { dimension: 'gemeenteCode', label: 'hierarchy.level.municipality', parentDimension: 'provincieCode' }, + { dimension: 'wijkCode', label: 'hierarchy.level.district', parentDimension: 'gemeenteCode' }, + { dimension: 'buurtCode', label: 'hierarchy.level.neighbourhood', parentDimension: 'wijkCode' }, + ], +} + +/** + * A widget-click clause. + * + * @param {string} dimension The dimension. + * @param {unknown} value The value. + * @param {string} widget The publishing widget. + * @return {object} + */ +function click(dimension, value, widget = 'A') { + return { dimension, operator: 'eq', value, source: 'widgetClick', sourceWidgetId: widget } +} + +/** + * The bus state as dimension => [value, source]. + * + * @param {object} bus The bus. + * @return {object} + */ +function state(bus) { + return Object.fromEntries(bus.clauses.value.map((clause) => [clause.dimension, [clause.value, clause.source]])) +} + +let warn + +beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) + +afterEach(() => { + warn.mockRestore() +}) + +describe('useFilterBus conflict resolution', () => { + it('a widget click adds a clause naming its widget, and subscribers hear it', () => { + const bus = useFilterBus() + const heard = [] + bus.subscribe((clauses) => heard.push(clauses.map((clause) => clause.value))) + + expect(bus.publish(click('gemeenteCode', 'GM0355'))).toEqual({ accepted: true, toggled: false, audit: null }) + expect(bus.clauses.value).toEqual([ + { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: 'A', pinned: false }, + ]) + expect(heard).toEqual([['GM0355']]) + }) + + it('a widget click replaces another widget click for the same dimension, with a toast', () => { + const bus = useFilterBus() + bus.publish(click('gemeenteCode', 'GM0355', 'A')) + + const result = bus.publish(click('gemeenteCode', 'GM0344', 'B')) + + expect(result.audit).toEqual({ dimension: 'gemeenteCode', from: 'GM0355', to: 'GM0344', fromSource: 'widgetClick', toSource: 'widgetClick', silent: false }) + expect(state(bus)).toEqual({ gemeenteCode: ['GM0344', 'widgetClick'] }) + expect(bus.clauses.value[0].sourceWidgetId).toBe('B') + }) + + it('a widget click replaces a URL-bootstrap clause silently', () => { + const bus = useFilterBus() + bus.hydrate([{ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355' }]) + + const result = bus.publish(click('gemeenteCode', 'GM0344')) + + expect(result.audit.silent).toBe(true) + expect(state(bus)).toEqual({ gemeenteCode: ['GM0344', 'widgetClick'] }) + }) + + it('a pinned clause is never replaced, and the drop is logged once', () => { + const bus = useFilterBus() + bus.publish({ dimension: 'status', operator: 'eq', value: 'open', source: 'userExplicit', pinned: true }) + const heard = vi.fn() + bus.subscribe(heard) + + expect(bus.publish(click('status', 'closed'))).toEqual({ accepted: false, reason: 'pinned' }) + expect(state(bus)).toEqual({ status: ['open', 'userExplicit'] }) + expect(heard).not.toHaveBeenCalled() + expect(warn).toHaveBeenCalledTimes(1) + }) + + it('the same clause clicked twice on the same widget toggles it off', () => { + const bus = useFilterBus() + bus.publish(click('gemeenteCode', 'GM0355')) + + expect(bus.publish(click('gemeenteCode', 'GM0355')).toggled).toBe(true) + expect(bus.clauses.value).toEqual([]) + }) + + it('the same value from another widget is a replacement, not a toggle', () => { + const bus = useFilterBus() + bus.publish(click('gemeenteCode', 'GM0355', 'A')) + + const result = bus.publish(click('gemeenteCode', 'GM0355', 'B')) + expect(result.toggled).toBe(false) + expect(result.audit.silent).toBe(true) + expect(bus.clauses.value[0].sourceWidgetId).toBe('B') + }) + + it('refuses a clause the user may not see and leaves the bus untouched', () => { + const bus = useFilterBus({ canAccess: (clause) => clause.value !== 'GM0344' }) + bus.publish(click('gemeenteCode', 'GM0355')) + + expect(bus.publish(click('gemeenteCode', 'GM0344'))).toEqual({ accepted: false, reason: 'forbidden' }) + expect(state(bus)).toEqual({ gemeenteCode: ['GM0355', 'widgetClick'] }) + }) + + it('reset clears every non-pinned clause, and on an empty bus does nothing at all', () => { + const bus = useFilterBus() + bus.publish({ dimension: 'year', operator: 'eq', value: 2026, source: 'userExplicit', pinned: true }) + bus.publish(click('gemeenteCode', 'GM0355')) + bus.publish(click('status', 'open', 'C')) + const heard = vi.fn() + bus.subscribe(heard) + + expect(bus.reset()).toBe(true) + expect(state(bus)).toEqual({ year: [2026, 'userExplicit'] }) + expect(heard).toHaveBeenCalledTimes(1) + + expect(bus.reset()).toBe(false) + expect(heard).toHaveBeenCalledTimes(1) + }) + + it('removes one non-pinned clause, never a pinned one', () => { + const bus = useFilterBus() + bus.publish({ dimension: 'year', operator: 'eq', value: 2026, pinned: true }) + bus.publish(click('status', 'open')) + + expect(bus.remove('year')).toBe(false) + expect(bus.remove('status')).toBe(true) + expect(bus.remove('status')).toBe(false) + expect(Object.keys(state(bus))).toEqual(['year']) + }) + + it('gives a widget only the clauses it consumes, also when it mounts later', () => { + const bus = useFilterBus() + bus.publish(click('gemeenteCode', 'GM0355')) + bus.publish(click('status', 'open', 'C')) + + expect(bus.clausesFor(['gemeenteCode']).map((clause) => clause.value)).toEqual(['GM0355']) + expect(bus.clausesFor(['period.month'])).toEqual([]) + expect(bus.clausesFor(undefined)).toEqual([]) + }) + + it('hydrates restored clauses as URL bootstrap and keeps a pinned clause', () => { + const bus = useFilterBus() + bus.publish({ dimension: 'year', operator: 'eq', value: 2026, pinned: true }) + + bus.hydrate([ + { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: 'A' }, + { dimension: 'year', operator: 'eq', value: 2020 }, + ]) + + expect(state(bus)).toEqual({ year: [2026, 'userExplicit'], gemeenteCode: ['GM0355', 'urlBootstrap'] }) + }) + + it('ignores a clause without a dimension', () => { + const bus = useFilterBus() + expect(bus.publish({ value: 1 })).toEqual({ accepted: false, reason: 'invalid' }) + expect(bus.publish(null)).toEqual({ accepted: false, reason: 'invalid' }) + }) +}) + +describe('useFilterBus hierarchy resolution', () => { + const row = { wijkCode: 'WK0355001', gemeenteCode: 'GM0355', provincieCode: 'PV26' } + + it('drilling down to a wijk infers the gemeente and provincie as parent scope', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + + bus.publish(click('wijkCode', 'WK0355001'), { row }) + + expect(state(bus)).toEqual({ + provincieCode: ['PV26', 'parentScope'], + gemeenteCode: ['GM0355', 'parentScope'], + wijkCode: ['WK0355001', 'widgetClick'], + }) + expect(bus.breadcrumb('nl-administrative')).toEqual([ + { dimension: 'provincieCode', label: 'hierarchy.level.province', value: 'PV26', pinned: false }, + { dimension: 'gemeenteCode', label: 'hierarchy.level.municipality', value: 'GM0355', pinned: false }, + { dimension: 'wijkCode', label: 'hierarchy.level.district', value: 'WK0355001', pinned: false }, + ]) + }) + + it('drilling up to a provincie clears the gemeente and wijk below it', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + bus.publish(click('gemeenteCode', 'GM0355')) + bus.publish(click('wijkCode', 'WK0355001', 'B'), { row }) + + bus.publish(click('provincieCode', 'PV09', 'P')) + + expect(state(bus)).toEqual({ provincieCode: ['PV09', 'widgetClick'] }) + expect(bus.breadcrumb('nl-administrative').map((step) => step.value)).toEqual(['PV09']) + }) + + it('a wijk in another gemeente moves the inferred ancestors with it', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + bus.publish(click('wijkCode', 'WK0355001'), { row }) + + bus.publish(click('wijkCode', 'WK0344002'), { row: { gemeenteCode: 'GM0344', provincieCode: 'PV26' } }) + + expect(state(bus)).toEqual({ + provincieCode: ['PV26', 'parentScope'], + gemeenteCode: ['GM0344', 'parentScope'], + wijkCode: ['WK0344002', 'widgetClick'], + }) + }) + + it('a wijk under a gemeente pinned to another value is refused', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + bus.publish({ dimension: 'gemeenteCode', operator: 'eq', value: 'GM0344', pinned: true }) + + expect(bus.publish(click('wijkCode', 'WK0355001'), { row })).toEqual({ accepted: false, reason: 'pinned' }) + expect(Object.keys(state(bus))).toEqual(['gemeenteCode']) + }) + + it('toggling the wijk off takes its inferred ancestors with it', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + bus.publish(click('wijkCode', 'WK0355001'), { row }) + + bus.publish(click('wijkCode', 'WK0355001'), { row }) + + expect(bus.clauses.value).toEqual([]) + }) + + it('an ancestor missing from the row is skipped with a warning', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + + bus.publish(click('wijkCode', 'WK0355001'), { row: { gemeenteCode: 'GM0355' } }) + + expect(Object.keys(state(bus))).toEqual(['gemeenteCode', 'wijkCode']) + expect(warn).toHaveBeenCalledTimes(1) + }) + + it('resolveHierarchy leaves a dimension outside every hierarchy alone', () => { + expect(resolveHierarchy({ dimension: 'status' }, [NL_ADMINISTRATIVE], row)).toEqual({ descendants: [], ancestors: [] }) + expect(resolveHierarchy({ dimension: 'gemeenteCode' }, [NL_ADMINISTRATIVE], row).descendants).toEqual(['wijkCode', 'buurtCode']) + }) +}) + +describe('useFilterBus going back up the breadcrumb (REQ-CWF-004)', () => { + const wijkRow = { wijkCode: 'WK0355001', gemeenteCode: 'GM0355', provincieCode: 'PV26' } + + it('going back to the provincie clears the gemeente and wijk and keeps the provincie as the reader\'s own', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + bus.publish(click('wijkCode', 'WK0355001'), { row: wijkRow }) + + expect(bus.popTo('provincieCode')).toBe(true) + + expect(state(bus)).toEqual({ provincieCode: ['PV26', 'userExplicit'] }) + expect(bus.breadcrumb('nl-administrative').map((step) => step.value)).toEqual(['PV26']) + }) + + it('going back to the gemeente keeps the provincie above it as parent scope', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + bus.publish(click('wijkCode', 'WK0355001'), { row: wijkRow }) + + bus.popTo('gemeenteCode') + + expect(state(bus)).toEqual({ provincieCode: ['PV26', 'parentScope'], gemeenteCode: ['GM0355', 'userExplicit'] }) + }) + + it('a wijk in another gemeente after going back replaces the provincie with the new ancestors', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + bus.publish(click('wijkCode', 'WK0355001'), { row: wijkRow }) + bus.popTo('provincieCode') + + bus.publish(click('wijkCode', 'WK0344002'), { row: { wijkCode: 'WK0344002', gemeenteCode: 'GM0344', provincieCode: 'PV27' } }) + + expect(state(bus)).toEqual({ + provincieCode: ['PV27', 'parentScope'], + gemeenteCode: ['GM0344', 'parentScope'], + wijkCode: ['WK0344002', 'widgetClick'], + }) + }) + + it('keeps a pinned level below, and changes nothing for the deepest level or an unknown one', () => { + const bus = useFilterBus({ hierarchies: [NL_ADMINISTRATIVE] }) + bus.hydrate([{ dimension: 'wijkCode', operator: 'eq', value: 'WK0355001', source: 'userExplicit', pinned: true }]) + bus.publish(click('provincieCode', 'PV26', 'P')) + const heard = vi.fn() + bus.subscribe(heard) + + expect(bus.popTo('wijkCode')).toBe(false) + expect(bus.popTo('status')).toBe(false) + expect(bus.popTo('buurtCode')).toBe(false) + expect(heard).not.toHaveBeenCalled() + expect(bus.popTo('provincieCode')).toBe(false) + expect(state(bus)).toEqual({ wijkCode: ['WK0355001', 'userExplicit'], provincieCode: ['PV26', 'widgetClick'] }) + }) + + it('breadcrumbPath reads the path from any clause list, with the pinned flag', () => { + const clauses = [ + { dimension: 'gemeenteCode', value: 'GM0355', pinned: true }, + { dimension: 'status', value: 'open' }, + ] + expect(breadcrumbPath([NL_ADMINISTRATIVE], clauses, 'nl-administrative')).toEqual([ + { dimension: 'gemeenteCode', label: 'hierarchy.level.municipality', value: 'GM0355', pinned: true }, + ]) + expect(breadcrumbPath([NL_ADMINISTRATIVE], clauses, 'other')).toEqual([]) + expect(breadcrumbPath(null, null, 'nl-administrative')).toEqual([]) + }) +}) diff --git a/src/composables/__tests__/useFilterUrlSync.spec.js b/src/composables/__tests__/useFilterUrlSync.spec.js new file mode 100644 index 000000000..11bf842f5 --- /dev/null +++ b/src/composables/__tests__/useFilterUrlSync.spec.js @@ -0,0 +1,138 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useFilterUrlSync: a link with `?f=` opens with its filter as urlBootstrap + * clauses, a change is written back once per burst, an empty bus removes the + * parameter, and the URL is replaced, never pushed + * (drill-down-cross-widget-filter task 4; REQ-CWF-003). + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { deserializeFilterState, serializeFilterState } from '../useDashboardFilter.js' +import { useFilterBus } from '../useFilterBus.js' +import { urlWithFilter, useFilterUrlSync } from '../useFilterUrlSync.js' + +const ZEIST = { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: 'w-a', pinned: false } +const OPEN = { dimension: 'status', operator: 'eq', value: 'open', source: 'widgetClick', sourceWidgetId: 'w-b', pinned: false } + +/** + * A location and a history that write into each other, like the browser's. + * + * @param {string} href The starting URL. + * @return {{location: {href: string}, history: {state: unknown, replaceState: Function, pushState: Function}}} + */ +function browserAt(href) { + const location = { href } + const history = { + state: { route: 'dashboard' }, + replaceState: vi.fn((_state, _title, url) => { location.href = url }), + pushState: vi.fn(), + } + return { location, history } +} + +/** + * The clauses the URL's `f` parameter carries. + * + * @param {string} href The URL. + * @return {Array<object>} + */ +function filterIn(href) { + const param = new URL(href).searchParams.get('f') + return param === null ? [] : deserializeFilterState(param).clauses +} + +beforeEach(() => vi.useFakeTimers()) +afterEach(() => vi.useRealTimers()) + +describe('useFilterUrlSync', () => { + it('opens a bookmarked link with its clauses as urlBootstrap', () => { + const { location, history } = browserAt('https://cloud.example/apps/launchpad/?f=' + serializeFilterState([ZEIST])) + const bus = useFilterBus() + + const sync = useFilterUrlSync({ bus, location, history }) + + expect(bus.clauses.value).toHaveLength(1) + expect(bus.clauses.value[0]).toMatchObject({ dimension: 'gemeenteCode', value: 'GM0355', source: 'urlBootstrap' }) + expect(sync.restored).toHaveLength(1) + // Reading the URL is not a change of it. + vi.runAllTimers() + expect(history.replaceState).not.toHaveBeenCalled() + }) + + it('opens unfiltered on a malformed parameter and leaves the URL alone', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const { location, history } = browserAt('https://cloud.example/apps/launchpad/?f=%%%not-base64') + const bus = useFilterBus() + + useFilterUrlSync({ bus, location, history }) + + expect(bus.clauses.value).toEqual([]) + expect(history.replaceState).not.toHaveBeenCalled() + warn.mockRestore() + }) + + it('with hydrate off, ignores the URL filter and still writes', () => { + const { location, history } = browserAt('https://cloud.example/apps/launchpad/?f=' + serializeFilterState([ZEIST])) + const bus = useFilterBus() + + useFilterUrlSync({ bus, location, history, hydrate: false }) + expect(bus.clauses.value).toEqual([]) + + bus.publish(OPEN) + vi.runAllTimers() + expect(filterIn(location.href).map((clause) => clause.dimension)).toEqual(['status']) + }) + + it('writes a burst of clicks to the URL once, after the debounce', () => { + const { location, history } = browserAt('https://cloud.example/apps/launchpad/?tab=2') + const bus = useFilterBus() + useFilterUrlSync({ bus, location, history, debounceMs: 500 }) + + bus.publish(ZEIST) + bus.publish(OPEN) + vi.advanceTimersByTime(499) + expect(history.replaceState).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + expect(history.replaceState).toHaveBeenCalledTimes(1) + expect(history.pushState).not.toHaveBeenCalled() + expect(history.replaceState.mock.calls[0][0]).toEqual({ route: 'dashboard' }) + expect(new URL(location.href).searchParams.get('tab')).toBe('2') + expect(filterIn(location.href).map((clause) => clause.dimension)).toEqual(['gemeenteCode', 'status']) + }) + + it('removes the parameter when the bus is reset', () => { + const { location, history } = browserAt('https://cloud.example/apps/launchpad/?f=' + serializeFilterState([ZEIST])) + const bus = useFilterBus() + useFilterUrlSync({ bus, location, history }) + + bus.reset() + vi.runAllTimers() + + expect(new URL(location.href).searchParams.has('f')).toBe(false) + expect(history.replaceState).toHaveBeenCalledTimes(1) + }) + + it('writes a waiting change on stop and listens no longer', () => { + const { location, history } = browserAt('https://cloud.example/apps/launchpad/') + const bus = useFilterBus() + const sync = useFilterUrlSync({ bus, location, history }) + + bus.publish(ZEIST) + sync.stop() + expect(filterIn(location.href)).toHaveLength(1) + + bus.publish(OPEN) + vi.runAllTimers() + expect(history.replaceState).toHaveBeenCalledTimes(1) + }) +}) + +describe('urlWithFilter', () => { + it('keeps the other parameters and drops f for no clauses', () => { + const href = urlWithFilter('https://cloud.example/x?a=1&f=abc', []) + expect(href).toBe('https://cloud.example/x?a=1') + }) +}) diff --git a/src/composables/__tests__/useGridManager.spec.js b/src/composables/__tests__/useGridManager.spec.js index 4806665d2..601d65e84 100644 --- a/src/composables/__tests__/useGridManager.spec.js +++ b/src/composables/__tests__/useGridManager.spec.js @@ -40,6 +40,7 @@ import { DEFAULT_COLUMNS, DEFAULT_H, DEFAULT_W, + defaultSizeFor, getColumnOpts, GRID_MARGIN, MIN_CELLS, @@ -558,3 +559,24 @@ describe('nudgePlacement (keyboard-accessible repositioning)', () => { }) }) }) + +describe('quicklinks sizing — REQ-QLNK-011', () => { + it('a new quicklinks widget is 4 columns by 2 rows', () => { + expect(defaultSizeFor('quicklinks', 12)).toEqual({ w: 4, h: 2 }) + }) +}) + +describe('divider sizing — REQ-DIV-006', () => { + it('a new divider spans every column and is one row tall; other widgets keep the default', () => { + expect(defaultSizeFor('divider', 12)).toEqual({ w: 12, h: 1 }) + expect(defaultSizeFor('divider', 6)).toEqual({ w: 6, h: 1 }) + expect(defaultSizeFor('calendar', 12)).toEqual({ w: DEFAULT_W, h: DEFAULT_H }) + }) + + it('a divider shrinks to one row; any other widget stops at two', () => { + const rect = { id: 1, gridX: 0, gridY: 0, gridWidth: 8, gridHeight: 2 } + expect(nudgePlacement({ ...rect, widgetId: 'divider' }, 'shrink-height', []).gridHeight).toBe(1) + expect(nudgePlacement({ ...rect, widgetId: 'divider', gridHeight: 1 }, 'shrink-height', []).gridHeight).toBe(1) + expect(nudgePlacement({ ...rect, widgetId: 'text' }, 'shrink-height', []).gridHeight).toBe(2) + }) +}) diff --git a/src/composables/__tests__/useTileSearchHost.sidePanel.spec.js b/src/composables/__tests__/useTileSearchHost.sidePanel.spec.js new file mode 100644 index 000000000..033735859 --- /dev/null +++ b/src/composables/__tests__/useTileSearchHost.sidePanel.spec.js @@ -0,0 +1,77 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Quick search opens a side-panel tile in the panel, as a click does + * (launcher-tile-open-behaviour task 8): activation clicks the rendered tile + * link, and TileWidget's click handler decides where it opens. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' + +vi.mock('@conduction/nextcloud-vue', () => ({ + CnWidgetEditCog: { name: 'CnWidgetEditCog', template: '<div />' }, + CnDashboardIcon: { name: 'CnDashboardIcon', template: '<i />' }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => '/nc' + path })) +vi.mock('../useTileClickTracking.js', () => ({ useTileClickTracking: () => ({ recordTileClick: vi.fn() }) })) +vi.mock('../../components/HealthPingBadge.vue', () => ({ default: { name: 'HealthPingBadge', template: '<span />' } })) + +const { default: TileWidget } = await import('../../components/TileWidget.vue') +const { activateSearchResult, GRID_CONTAINER_ID } = await import('../useTileSearchHost.js') +const { useTilePanelStore } = await import('../../stores/tilePanel.js') + +/** + * Mount one tile inside a grid item, as Views.vue renders it. + * + * @param {number} id The placement id. + * @param {object} props TileWidget props. + * @return {object} The wrapper. + */ +function mountGridTile(id, props) { + const host = document.createElement('div') + host.id = GRID_CONTAINER_ID + document.body.appendChild(host) + + return mount( + { render: () => h('div', { class: 'launchpad-grid-item', 'data-placement-id': String(id) }, [h(TileWidget, props)]) }, + { attachTo: host }, + ) +} + +describe('quick search on a side-panel tile', () => { + beforeEach(() => { + setActivePinia(createPinia()) + }) + + afterEach(() => { + document.body.innerHTML = '' + }) + + it('opens the tile in the panel', () => { + mountGridTile(7, { tile: { id: 7, title: 'Files', linkType: 'app', linkValue: 'files' }, linkTarget: 'side-panel' }) + + expect(activateSearchResult({ id: 7, placement: { id: 7 } })).toBe(true) + + const panel = useTilePanelStore() + expect(panel.isOpen).toBe(true) + expect(panel.url).toBe('/nc/apps/files') + expect(panel.title).toBe('Files') + }) + + it('leaves the panel closed for a tile that opens in a tab', () => { + mountGridTile(8, { tile: { id: 8, title: 'Deck', linkType: 'app', linkValue: 'deck' }, defaultLinkTarget: 'new-tab' }) + const link = document.querySelector('[data-placement-id="8"] a') + link.addEventListener('click', (event) => event.preventDefault()) + + activateSearchResult({ id: 8, placement: { id: 8 } }) + + expect(useTilePanelStore().isOpen).toBe(false) + expect(link.getAttribute('target')).toBe('_blank') + }) +}) diff --git a/src/composables/filterTelemetry.js b/src/composables/filterTelemetry.js new file mode 100644 index 000000000..499e79dc1 --- /dev/null +++ b/src/composables/filterTelemetry.js @@ -0,0 +1,146 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +/** + * filterTelemetry — records how a dashboard's filters are used, as + * `filter_event` objects in the launchpad register (REQ-CWF-010). + * + * A row names the dimensions and operators that changed and where they came + * from, never the values. Nothing is written unless the organisation switched + * telemetry on, so the recorder is a no-op by default. A failed write is + * logged and dropped: telemetry never gets in the way of filtering. + * + * @module composables/filterTelemetry + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-010-telemetry-of-filter-usage-is-opt-in-and-aggregated + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' +import { logger } from '../utils/logger.js' + +/** The register and schema the rows are written to. */ +export const FILTER_EVENT_REGISTER = 'launchpad' +export const FILTER_EVENT_SCHEMA = 'filter_event' + +/** The event types the `filter_event` schema accepts. */ +const EVENT_TYPES = ['apply', 'reset', 'bookmark', 'share'] + +/** + * The clauses as a filter delta: dimension, operator, source, source widget + * and pinned flag, with the value left out. + * + * @param {Array<object>} clauses The bus clauses. + * @return {Array<object>} The delta items. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-15 + */ +export function filterDelta(clauses) { + return (Array.isArray(clauses) ? clauses : []) + .filter((clause) => clause && typeof clause.dimension === 'string' && clause.dimension !== '') + .map(deltaItem) +} + +/** + * Whether a value is a non-empty string. + * + * @param {unknown} value The value. + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-15 + */ +function isFilled(value) { + return typeof value === 'string' && value !== '' +} + +/** + * One clause as a delta item: the known fields only, empty sources left out. + * + * @param {object} clause A clause with a dimension. + * @return {object} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-15 + */ +function deltaItem(clause) { + const item = { + dimension: clause.dimension, + operator: isFilled(clause.operator) ? clause.operator : 'eq', + } + for (const key of ['source', 'sourceWidgetId']) { + if (isFilled(clause[key])) { + item[key] = clause[key] + } + } + item.pinned = clause.pinned === true + return item +} + +/** + * Write one row to the register. + * + * @param {object} row The `filter_event` row. + * @return {Promise<unknown>} + */ +function postToRegister(row) { + return axios.post( + generateUrl('/apps/openregister/api/objects/{register}/{schema}', { + register: FILTER_EVENT_REGISTER, + schema: FILTER_EVENT_SCHEMA, + }), + row, + ) +} + +/** + * Create the recorder for one open dashboard. + * + * @param {object} options The recorder's context. + * @param {() => boolean} options.enabled Whether the organisation switched telemetry on; asked on every record. + * @param {string} options.dashboardId The dashboard's uuid. + * @param {string} options.userId The current user's id. + * @param {(row: object) => Promise<unknown>} [options.post] Writes a row (the register by default). + * @param {() => Date} [options.now] The clock. + * @return {{record: (eventType: string, clauses: Array<object>, widgetId?: string|null) => Promise<object|null>}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-15 + */ +export function createFilterTelemetry({ enabled, dashboardId, userId, post = postToRegister, now = () => new Date() }) { + /** + * Whether an event may be written. + * + * @param {string} eventType The event type. + * @param {Array<object>} delta The event's delta. + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-15 + */ + function mayRecord(eventType, delta) { + return enabled() === true && Boolean(dashboardId) && Boolean(userId) && EVENT_TYPES.includes(eventType) && delta.length > 0 + } + + /** + * Record one filter change. + * + * @param {string} eventType `apply`, `reset`, `bookmark` or `share`. + * @param {Array<object>} clauses The clauses added or removed. + * @param {string|null} [widgetId] The clicked widget, for a widget click. + * @return {Promise<object|null>} The row written, or null when nothing was written. + */ + async function record(eventType, clauses, widgetId = null) { + const delta = filterDelta(clauses) + if (!mayRecord(eventType, delta)) { + return null + } + + const row = { dashboardId, userId, eventType, filterDelta: delta, timestamp: now().toISOString() } + if (isFilled(widgetId)) { + row.widgetId = widgetId + } + + try { + await post(row) + } catch (error) { + logger.warn('[launchpad] the filter telemetry row was not written', error) + return null + } + return row + } + + return { record } +} diff --git a/src/composables/useCalculatedFields.js b/src/composables/useCalculatedFields.js new file mode 100644 index 000000000..d3f9db697 --- /dev/null +++ b/src/composables/useCalculatedFields.js @@ -0,0 +1,46 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { computed, unref, watch } from 'vue' +import { useCalculatedFieldsStore } from '../stores/calculatedFields.js' + +/** + * The calculated fields of one widget (REQ-CALC-003, REQ-CALC-008). + * + * Watches the widget's source data and the dashboard filters, reports them to + * the calculated-fields store (which re-evaluates every field of the + * dashboard in dependency order, so dependent widgets follow), and answers + * this widget's values and inline errors as `Map`s keyed by field name. + * + * @param {object} options The inputs. + * @param {string|import('vue').Ref<string>} options.widgetId The widget. + * @param {object|import('vue').Ref<object>} [options.data] The widget's current source data. + * @param {object[]|import('vue').Ref<object[]>} [options.filters] The dashboard's active filters. + * @return {{values: import('vue').ComputedRef<Map<string, unknown>>, errors: import('vue').ComputedRef<Map<string, object>>}} The values and errors. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +export function useCalculatedFields({ widgetId, data = undefined, filters = undefined }) { + const store = useCalculatedFieldsStore() + + if (data !== undefined) { + watch( + () => [unref(widgetId), unref(data)], + ([id, current]) => store.setWidgetData(id, current), + { immediate: true, deep: true }, + ) + } + if (filters !== undefined) { + watch( + () => unref(filters), + (current) => store.setFilters(current), + { deep: true }, + ) + } + + const values = computed(() => new Map(Object.entries(store.valuesOf(unref(widgetId))))) + const errors = computed(() => new Map(Object.entries(store.errorsOf(unref(widgetId))))) + + return { values, errors } +} diff --git a/src/composables/useDashboardFilter.js b/src/composables/useDashboardFilter.js new file mode 100644 index 000000000..119082ab2 --- /dev/null +++ b/src/composables/useDashboardFilter.js @@ -0,0 +1,240 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useDashboardFilter — the URL form of a dashboard's filter state + * (drill-down-cross-widget-filter, REQ-CWF-003). + * + * The whole filter state travels in ONE query parameter, `?f=<base64url>` + * (design D4). Its payload is a JSON array of clauses with short keys, so a + * dashboard with ten clauses stays well under the 2 KB a URL can safely carry: + * + * d dimension e.g. "gemeenteCode", "period.month" + * o operator eq | in | between | gte | lte | contains | notNull + * v value scalar, array, or [low, high]; absent for notNull + * s source userExplicit | widgetClick | urlBootstrap | savedView | parentScope + * w sourceWidgetId only when set + * p pinned only when true + * + * base64url (RFC 4648 §5, no padding) needs no percent-encoding, so the + * parameter survives copy and paste. A malformed parameter never breaks the + * page: it reads as an empty filter state with one console warning. + */ + +import { logger } from '../utils/logger.js' + +/** + * The query parameter that carries the filter state. + * + * @type {string} + */ +export const FILTER_PARAM = 'f' + +/** + * The comparison operators a clause may use. + * + * @type {string[]} + */ +export const OPERATORS = ['eq', 'in', 'between', 'gte', 'lte', 'contains', 'notNull'] + +/** + * Where a clause can come from. `savedView` is no longer written, but still + * decodes, so a link copied from an applied saved view keeps its filters. + * + * @type {string[]} + */ +export const SOURCES = ['userExplicit', 'widgetClick', 'urlBootstrap', 'savedView', 'parentScope'] + +/** + * Base64url-encode a UTF-8 string, without padding. + * + * @param {string} text The text. + * @return {string} + */ +function toBase64Url(text) { + const bytes = new TextEncoder().encode(text) + let binary = '' + bytes.forEach((byte) => { + binary += String.fromCharCode(byte) + }) + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +/** + * Decode a base64url string to UTF-8 text. + * + * @param {string} encoded The base64url text. + * @return {string} + * @throws {Error} When the text is not base64url or not UTF-8. + */ +function fromBase64Url(encoded) { + if (!/^[A-Za-z0-9_-]*$/.test(encoded)) { + throw new Error('not base64url') + } + const base64 = encoded.replace(/-/g, '+').replace(/_/g, '/') + const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4) + const binary = atob(padded) + const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0)) + return new TextDecoder('utf-8', { fatal: true }).decode(bytes) +} + +/** + * A clause in its short URL form. + * + * @param {object} clause The clause. + * @return {object} + */ +function compact(clause) { + const short = { d: clause.dimension, o: clause.operator } + if (clause.operator !== 'notNull') { + short.v = clause.value + } + if (clause.source) { + short.s = clause.source + } + if (clause.sourceWidgetId) { + short.w = clause.sourceWidgetId + } + if (clause.pinned === true) { + short.p = true + } + return short +} + +/** + * Whether a value is a plain object (not null, not a list). + * + * @param {object} short The compact clause. + * @return {boolean} + */ +function isPlainObject(short) { + return Boolean(short) && typeof short === 'object' && !Array.isArray(short) +} + +/** + * Whether a compact clause names a dimension and a known operator. + * + * @param {object} short The compact clause. + * @return {boolean} + */ +function hasDimensionAndOperator(short) { + return typeof short.d === 'string' && short.d !== '' && OPERATORS.includes(short.o) +} + +/** + * Whether a compact clause carries the value its operator needs and a known source. + * + * @param {object} short The compact clause. + * @return {boolean} + */ +function hasValueAndSource(short) { + return (short.o === 'notNull' || 'v' in short) && (short.s === undefined || SOURCES.includes(short.s)) +} + +/** + * Whether a compact clause from the URL is well formed. + * + * @param {object} short The compact clause. + * @return {boolean} + */ +function isWellFormed(short) { + return isPlainObject(short) && hasDimensionAndOperator(short) && hasValueAndSource(short) +} + +/** + * The widget a compact clause came from, or null. + * + * @param {object} short The compact clause. + * @return {string|null} + */ +function sourceWidgetOf(short) { + return typeof short.w === 'string' && short.w !== '' ? short.w : null +} + +/** + * A clause read back from its short URL form, or null when it is not one. + * + * @param {unknown} short The short form. + * @return {object|null} + */ +function expand(short) { + if (!isWellFormed(short)) { + return null + } + const clause = { + dimension: short.d, + operator: short.o, + source: short.s || 'urlBootstrap', + sourceWidgetId: sourceWidgetOf(short), + pinned: short.p === true, + } + if (short.o !== 'notNull') { + clause.value = short.v + } + return clause +} + +/** + * The URL parameter value for a set of clauses; '' when there are none. + * + * @param {Array<object>} clauses The active clauses. + * @return {string} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-003-url-encoding-makes-filtered-views-bookmarkable + */ +export function serializeFilterState(clauses) { + const list = (Array.isArray(clauses) ? clauses : []).filter((clause) => clause && typeof clause.dimension === 'string') + if (list.length === 0) { + return '' + } + return toBase64Url(JSON.stringify(list.map(compact))) +} + +/** + * The clauses an encoded filter parameter holds. + * + * @param {string} param The URL parameter. + * @return {Array<object>} The clauses. + * @throws {Error} When it is not a list of well-formed clauses. + */ +function parseClauses(param) { + const parsed = JSON.parse(fromBase64Url(String(param))) + if (!Array.isArray(parsed)) { + throw new Error('not a list of clauses') + } + const clauses = parsed.map(expand) + if (clauses.includes(null)) { + throw new Error('a clause is malformed') + } + return clauses +} + +/** + * The clauses a URL parameter value carries. Anything malformed (not base64url, + * not JSON, not a list, or a clause without a dimension or with an unknown + * operator) gives no clauses, an `error`, and one console warning. + * + * @param {string|null|undefined} param The `f` parameter value. + * @return {{clauses: Array<object>, error: string|null}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-003-url-encoding-makes-filtered-views-bookmarkable + */ +export function deserializeFilterState(param) { + if (param === null || param === undefined || param === '') { + return { clauses: [], error: null } + } + try { + return { clauses: parseClauses(param), error: null } + } catch (error) { + logger.warn('[launchpad] the filter in the URL could not be read; the dashboard opens unfiltered:', error.message) + return { clauses: [], error: 'malformed' } + } +} + +/** + * The composable. + * + * @return {{serializeFilterState: typeof serializeFilterState, deserializeFilterState: typeof deserializeFilterState, FILTER_PARAM: string}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-003-url-encoding-makes-filtered-views-bookmarkable + */ +export function useDashboardFilter() { + return { serializeFilterState, deserializeFilterState, FILTER_PARAM } +} diff --git a/src/composables/useDashboardFilterSession.js b/src/composables/useDashboardFilterSession.js new file mode 100644 index 000000000..75466f533 --- /dev/null +++ b/src/composables/useDashboardFilterSession.js @@ -0,0 +1,87 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useDashboardFilterSession — one filter bus per open dashboard + * (drill-down-cross-widget-filter, REQ-CWF-003, -006, -007). + * + * The dashboard view opens a session when a dashboard becomes active and + * stops it when another one does: filters belong to a dashboard, so a switch + * starts with an empty bus. Only the first session of a page load reads the + * `f` parameter, because that is the one a bookmarked link points at; a later + * dashboard switch pushes a fresh URL without it. + * + * The session's `clauses` is the bus's own reactive list, which the view + * hands to the active-filters panel; `labels` names each hierarchy level for + * the chips. + */ + +import { presetLevelLabels } from '../utils/hierarchyPresets.js' +import { useFilterBus } from './useFilterBus.js' +import { useFilterUrlSync } from './useFilterUrlSync.js' + +/** + * The hierarchy descriptors a dashboard declares, or none. + * + * @param {object|null} dashboard The dashboard. + * @return {Array<object>} + */ +export function hierarchiesOf(dashboard) { + const declared = dashboard?.hierarchies + return Array.isArray(declared) ? declared.filter((entry) => entry && Array.isArray(entry.levels)) : [] +} + +/** + * A display label per hierarchy level dimension. + * + * A preset's levels carry the preset's labels in the reader's language + * (REQ-CWF-011); any other hierarchy shows the labels it stores. + * + * @param {Array<object>} hierarchies The hierarchy descriptors. + * @return {{[key: string]: string}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ +export function levelLabels(hierarchies) { + const labels = {} + for (const hierarchy of hierarchies) { + const preset = presetLevelLabels(hierarchy.id) ?? {} + for (const level of hierarchy.levels) { + if (!level || typeof level.dimension !== 'string') { + continue + } + const label = preset[level.dimension] ?? level.label + if (typeof label === 'string' && label !== '') { + labels[level.dimension] = label + } + } + } + return labels +} + +/** + * Open the filter session of a dashboard. + * + * @param {object} options The session. + * @param {object|null} options.dashboard The active dashboard. + * @param {boolean} options.readUrl Whether the URL's `f` parameter seeds the bus (the first dashboard of a page load). + * @param {{href: string}} [options.location] The location (window.location). + * @param {{replaceState: (state: unknown, title: string, url: string) => void, state: unknown}} [options.history] The history (window.history). + * @param {{record: (eventType: string, clauses: Array<object>, widgetId?: string|null) => unknown}|null} [options.telemetry] Records filter changes when the organisation opted in (REQ-CWF-010). + * @return {{bus: object, clauses: import('vue').ShallowRef<Array<object>>, labels: {[key: string]: string}, remove: (dimension: string) => boolean, reset: () => boolean, popTo: (dimension: string) => boolean, stop: () => void}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-003-url-encoding-makes-filtered-views-bookmarkable + */ +export function useDashboardFilterSession({ dashboard, readUrl, location = window.location, history = window.history, telemetry = null }) { + const hierarchies = hierarchiesOf(dashboard) + const bus = useFilterBus({ hierarchies, telemetry }) + const sync = useFilterUrlSync({ bus, location, history, hydrate: readUrl }) + + return { + bus, + clauses: bus.clauses, + labels: levelLabels(hierarchies), + remove: (dimension) => bus.remove(dimension), + reset: () => bus.reset(), + popTo: (dimension) => bus.popTo(dimension), + stop: () => sync.stop(), + } +} diff --git a/src/composables/useDashboardPresence.js b/src/composables/useDashboardPresence.js new file mode 100644 index 000000000..a0c93e985 --- /dev/null +++ b/src/composables/useDashboardPresence.js @@ -0,0 +1,134 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { reactive } from 'vue' +import { api } from '../services/api.js' + +/** + * How often an editor renews its presence. The server drops an editor 90 + * seconds after its last renewal, so 30 seconds survives two missed beats. + */ +export const PRESENCE_BEAT_MS = 30 * 1000 + +/** + * Who else edits the dashboard this person is editing + * (building-edit-a-dashboard-together, task 1.1). + * + * `state.editors` holds the colleagues as `{displayName, since}`, longest + * first; `state.status` is `none`, `editing`, or `forbidden` when the server + * refused (403) or did not know the dashboard (404). A failed renewal keeps + * the last list; the next beat tries again. `onRefused` is called once when a + * renewal is refused, so the page can leave edit mode. + * + * @param {object} [options] Options. + * @param {() => void} [options.onRefused] Called when a renewal is refused. + * @return {{state: object, start: (uuid: string) => Promise<boolean>, stop: () => Promise<void>}} + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ +export function useDashboardPresence({ onRefused } = {}) { + const state = reactive({ + status: 'none', + uuid: null, + editors: [], + }) + let timer = null + + /** + * Withdraw the presence while the page closes. + * + * @return {void} + */ + const onPageHide = () => { + if (state.status === 'editing' && state.uuid) { + api.leavePresence(state.uuid, true).catch(() => {}) + } + } + + /** + * Stop the heartbeat and the page-hide listener. + * + * @return {void} + */ + function clear() { + if (timer !== null) { + clearInterval(timer) + timer = null + } + window.removeEventListener('pagehide', onPageHide) + } + + /** + * Announce or renew, and take the colleagues the server answers. + * + * @return {Promise<boolean>} False when the server refused. + */ + async function beat() { + const uuid = state.uuid + const renewal = state.status === 'editing' && timer !== null + try { + const { data } = await api.joinPresence(uuid) + if (state.uuid !== uuid) { + return true + } + state.status = 'editing' + state.editors = Array.isArray(data?.editors) ? data.editors : [] + return true + } catch (error) { + const status = error?.response?.status + if (status === 403 || status === 404) { + clear() + state.status = 'forbidden' + state.editors = [] + if (renewal && typeof onRefused === 'function') { + onRefused() + } + return false + } + // A network hiccup: keep the last list, the next beat tries again. + return state.status === 'editing' + } + } + + /** + * Start announcing this person on a dashboard. + * + * @param {string} uuid The dashboard UUID. + * @return {Promise<boolean>} False when the server refused. + */ + async function start(uuid) { + await stop() + state.uuid = uuid + state.status = 'editing' + const joined = await beat() + if (state.status === 'editing') { + timer = setInterval(beat, PRESENCE_BEAT_MS) + window.addEventListener('pagehide', onPageHide) + } + return joined + } + + /** + * Stop announcing; tells the server when this person was editing. + * + * @return {Promise<void>} + */ + async function stop() { + const uuid = state.uuid + const wasEditing = state.status === 'editing' + clear() + state.status = 'none' + state.uuid = null + state.editors = [] + if (wasEditing && uuid) { + try { + await api.leavePresence(uuid) + } catch { + // A missed leave costs at most the 90-second timeout. + } + } + } + + return { state, start, stop } +} diff --git a/src/composables/useEmbedContext.js b/src/composables/useEmbedContext.js new file mode 100644 index 000000000..6345db1a9 --- /dev/null +++ b/src/composables/useEmbedContext.js @@ -0,0 +1,188 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The iframe side of an embed (embedded-analytics tasks 14, 23): which + * subject this page shows and with which token, the subject's data with the + * token's scope and theme, and the conversation with the host page. + * + * The token comes from the page URL (`?token=`, the plain-iframe form) or + * from the SDK's `init` message. A message is answered only when it comes + * from the parent window at an origin the token lists, and everything is + * posted to that origin only. The scope hides what the token does not allow + * (`canRun`); the server refuses it regardless. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-006--js-sdk-exposes-render-event-and-resize-apis + */ + +import { computed, ref } from 'vue' +import { decodeClaims, MESSAGES, post } from '../embed-sdk/src/postMessage.js' + +/** + * The subject this page shows, from `/embed/{subjectType}/{subjectId}`. + * + * @param {string} pathname The page path. + * @return {{subjectType: string, subjectId: string, base: string}} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ +export function subjectOf(pathname) { + const match = /^(.*)\/embed\/(widget|dashboard)\/([^/]+)\/?$/.exec(String(pathname || '')) + if (!match) { + return { subjectType: '', subjectId: '', base: '' } + } + return { subjectType: match[2], subjectId: decodeURIComponent(match[3]), base: match[1] } +} + +/** + * The embed context of this page. + * + * @param {object} options The environment. + * @param {Window} options.win The iframe's window. + * @param {(url: string, token: string, params: object) => Promise<object>} options.load Fetches the subject. + * @return {object} The context. + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ +export function useEmbedContext({ win, load }) { + const subject = subjectOf(win.location.pathname) + const token = ref(new URLSearchParams(win.location.search).get('token') || '') + const viewport = new URLSearchParams(win.location.search).get('viewport') || '' + const parentOrigin = ref('') + const payload = ref(null) + const error = ref(null) + const loading = ref(false) + let loaded = null + + const claims = computed(() => decodeClaims(token.value)) + const hostOrigins = computed(() => (Array.isArray(claims.value.hostOrigins) ? claims.value.hostOrigins : []) + .map((origin) => String(origin).replace(/\/+$/, '').toLowerCase())) + const scope = computed(() => payload.value?.scope || { mode: 'read', allowedActions: [], allowedFilters: [] }) + const themeCss = computed(() => payload.value?.themeCss || '') + const filters = computed(() => payload.value?.filters || {}) + const placements = computed(() => (Array.isArray(payload.value?.placements) ? payload.value.placements : [])) + + /** + * Whether the token lets the embed run an action (interact, export, drillDown). + * + * @param {string} action The action. + * @return {boolean} + */ + const canRun = (action) => scope.value.mode === 'read-with-interactions' + && Array.isArray(scope.value.allowedActions) + && scope.value.allowedActions.includes(action) + + /** + * Load the subject once per token. + * + * @return {Promise<void>} + */ + const fetchSubject = () => { + if (!token.value || !subject.subjectType) { + error.value = { error: 'missing_token', message: 'No token provided.' } + return Promise.resolve() + } + if (loaded) { + return loaded + } + loading.value = true + const url = `${subject.base}/embed/${encodeURIComponent(subject.subjectType)}/${encodeURIComponent(subject.subjectId)}/data` + loaded = load(url, token.value, viewport ? { viewport } : {}) + .then((data) => { + payload.value = data + error.value = null + }) + .catch((failure) => { + error.value = failure?.response?.data?.error + ? failure.response.data + : { error: 'unavailable', message: 'The embed could not be loaded.' } + }) + .finally(() => { + loading.value = false + }) + return loaded + } + + /** + * Relay an event to the host page, once it has introduced itself. + * + * @param {string} eventType filterApplied, drillDown, export, … + * @param {unknown} eventPayload The event's payload. + * @return {boolean} Whether it was posted. + */ + const relay = (eventType, eventPayload) => { + if (!parentOrigin.value) { + return false + } + post(win.parent, parentOrigin.value, MESSAGES.event, { event: eventType, payload: eventPayload }) + return true + } + + /** + * Answer the SDK: the init handshake and resize requests. + * + * @param {MessageEvent} event The message. + * @return {Promise<void>} + */ + const onMessage = async (event) => { + const data = event?.data + if (event?.source !== win.parent || win.parent === win || typeof data?.type !== 'string') { + return + } + if (data.type === MESSAGES.init && !token.value && typeof data.token === 'string') { + token.value = data.token + } + const origin = String(event.origin || '').toLowerCase() + if (!hostOrigins.value.includes(origin)) { + // Not one of the token's pages: no answer at all, so nothing leaks. + return + } + parentOrigin.value = origin + + if (data.type === MESSAGES.init) { + await fetchSubject() + if (error.value) { + post(win.parent, origin, MESSAGES.error, { nonce: data.nonce, ...error.value }) + } else { + post(win.parent, origin, MESSAGES.ready, { nonce: data.nonce }) + } + } else if (data.type === MESSAGES.resize) { + const root = win.document.documentElement + post(win.parent, origin, MESSAGES.resized, { + nonce: data.nonce, + width: Math.round(Number(data.width) || root.scrollWidth || 0), + height: Math.round(root.scrollHeight || Number(data.height) || 0), + }) + } + } + + /** + * Start: listen for the host and load the subject when the URL has the token. + * + * @return {() => void} Stops listening. + */ + const start = () => { + win.addEventListener('message', onMessage) + if (token.value) { + fetchSubject() + } + return () => win.removeEventListener('message', onMessage) + } + + return { + subject, + token, + claims, + scope, + themeCss, + filters, + placements, + payload, + error, + loading, + parentOrigin, + canRun, + relay, + onMessage, + fetchSubject, + start, + } +} diff --git a/src/composables/useFilterBus.js b/src/composables/useFilterBus.js new file mode 100644 index 000000000..83d5ae610 --- /dev/null +++ b/src/composables/useFilterBus.js @@ -0,0 +1,526 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useFilterBus — the dashboard's shared filter state + * (drill-down-cross-widget-filter, REQ-CWF-001, -002, -004, -005, -006). + * + * THE CONTRACT + * ------------ + * A widget that declares `publishes` turns a click into a clause + * `{dimension, operator, value, source, sourceWidgetId, pinned}` and hands it + * to `publish()`. The bus keeps AT MOST ONE clause per dimension and tells + * every subscriber the new clause list after each change; the dashboard passes + * the clauses a widget `consumes` to that widget, which re-renders. + * + * CONFLICTS (REQ-CWF-005): last write wins per dimension. + * - a pinned clause is never replaced; the publication is dropped with one + * console line, so a developer can see why the click did not stick; + * - widget click over widget click replaces it and asks for a toast + * (`audit.silent === false`), naming the old and the new value; + * - anything over a `urlBootstrap` or `parentScope` clause replaces it + * silently: those are an initial state and an inference, not a choice; + * - the same clause clicked again on the same widget toggles it off + * (REQ-CWF-001). + * + * HIERARCHIES (REQ-CWF-004). A dimension that is a level of a dashboard + * hierarchy (e.g. provincieCode > gemeenteCode > wijkCode > buurtCode): + * - publishing it clears every DESCENDANT level's clause (drilling up); + * - its ANCESTOR levels are inferred as `parentScope` clauses from the + * clicked row, when the row carries the ancestor's field (drilling down). + * A missing ancestor value is skipped with a console warning; + * - a clause whose last explicit descendant is gone leaves with it. + * + * ACCESS (REQ-CWF-004). An optional `canAccess(clause)` refuses a clause for + * a scope the user may not see; the bus is then left untouched and the caller + * gets `reason: 'forbidden'` to explain the refusal next to the widget. + */ + +import { shallowRef } from 'vue' +import { logger } from '../utils/logger.js' + +/** + * Sources whose clause gives way silently to a newer one for its dimension. + * + * @type {string[]} + */ +const TRANSIENT_SOURCES = ['urlBootstrap', 'parentScope'] + +/** + * Whether two values are the same filter value (scalars, arrays, tuples). + * + * @param {unknown} left A value. + * @param {unknown} right Another. + * @return {boolean} + */ +function sameValue(left, right) { + return JSON.stringify(left) === JSON.stringify(right) +} + +/** + * A clause with every field present. + * + * @param {object} clause The published clause. + * @return {object} + */ +function normalise(clause) { + const normalised = { + dimension: String(clause.dimension), + operator: clause.operator || 'eq', + source: clause.source || 'userExplicit', + sourceWidgetId: clause.sourceWidgetId || null, + pinned: clause.pinned === true, + } + if (normalised.operator !== 'notNull') { + normalised.value = clause.value + } + return normalised +} + +/** + * The hierarchy a dimension is a level of, with its position. + * + * @param {Array<object>} hierarchies The dashboard's hierarchy descriptors. + * @param {string} dimension The dimension. + * @return {{levels: Array<object>, index: number}|null} + */ +function levelOf(hierarchies, dimension) { + for (const hierarchy of Array.isArray(hierarchies) ? hierarchies : []) { + const levels = Array.isArray(hierarchy?.levels) ? hierarchy.levels : [] + const index = levels.findIndex((level) => level && level.dimension === dimension) + if (index !== -1) { + return { levels, index } + } + } + return null +} + +/** + * The ancestor levels of a dimension in the dashboard's hierarchies, + * broadest first; none when it is no hierarchy level. + * + * @param {Array<object>} hierarchies The dashboard's hierarchy descriptors. + * @param {string} dimension The dimension. + * @return {string[]} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ +export function ancestorDimensions(hierarchies, dimension) { + const position = levelOf(hierarchies, dimension) + return position === null ? [] : position.levels.slice(0, position.index).map((level) => level.dimension) +} + +/** + * Apply the hierarchy to a publication: the descendant dimensions to clear and + * the ancestor clauses to infer from the clicked row. + * + * @param {object} clause The new clause. + * @param {Array<object>} hierarchies The dashboard's hierarchy descriptors. + * @param {object} row The clicked row's fields, where ancestor values are read. + * @return {{descendants: string[], ancestors: Array<object>}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ +export function resolveHierarchy(clause, hierarchies, row = {}) { + const position = levelOf(hierarchies, clause.dimension) + if (position === null) { + return { descendants: [], ancestors: [] } + } + const descendants = position.levels.slice(position.index + 1).map((level) => level.dimension) + const ancestors = position.levels.slice(0, position.index) + .map((level) => ancestorOf(level, row)) + .filter((ancestor) => ancestor !== null) + return { descendants, ancestors } +} + +/** + * A field of the clicked row, or undefined when there is no row. + * + * @param {object} row The clicked row's fields. + * @param {string} dimension The field. + * @return {string|number|boolean|undefined} + */ +function rowValue(row, dimension) { + return row && typeof row === 'object' ? row[dimension] : undefined +} + +/** + * Whether a value is missing: undefined, null or empty text. + * + * @param {string|number|boolean|null|undefined} value The value. + * @return {boolean} + */ +function isBlank(value) { + return value === undefined || value === null || value === '' +} + +/** + * The inferred clause of one ancestor level, read from the clicked row, or + * null (with a warning) when the row does not carry it. + * + * @param {object} level The hierarchy level. + * @param {object} row The clicked row's fields. + * @return {object|null} + */ +function ancestorOf(level, row) { + const value = rowValue(row, level.dimension) + if (isBlank(value)) { + logger.warn(`[launchpad] no ${level.dimension} on the clicked row; the breadcrumb skips that level`) + return null + } + return { dimension: level.dimension, operator: 'eq', value, source: 'parentScope', sourceWidgetId: null, pinned: false } +} + +/** + * The active path of one hierarchy, broadest level first: each level that + * has a clause, with its value. + * + * @param {Array<object>} hierarchies The dashboard's hierarchy descriptors. + * @param {Array<object>} clauses The bus's clauses. + * @param {string} hierarchyId The hierarchy id. + * @return {Array<{dimension: string, label: string, value: unknown, pinned: boolean}>} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ +export function breadcrumbPath(hierarchies, clauses, hierarchyId) { + const hierarchy = (Array.isArray(hierarchies) ? hierarchies : []).find((entry) => entry && entry.id === hierarchyId) + const levels = Array.isArray(hierarchy?.levels) ? hierarchy.levels : [] + const list = Array.isArray(clauses) ? clauses : [] + const path = [] + for (const level of levels) { + const clause = list.find((entry) => entry.dimension === level.dimension) + if (clause) { + path.push({ dimension: level.dimension, label: level.label, value: clause.value, pinned: clause.pinned === true }) + } + } + return path +} + +/** + * Whether a published clause names a dimension. + * + * @param {object} clause The clause. + * @return {boolean} + */ +function hasDimension(clause) { + return Boolean(clause) && typeof clause.dimension === 'string' && clause.dimension !== '' +} + +/** + * Whether a click repeats the same widget's same filter, which toggles it off. + * + * @param {object} incoming The new clause. + * @param {object} existing The clause on the same dimension. + * @return {boolean} + */ +function isSameClick(incoming, existing) { + return incoming.source === 'widgetClick' + && existing.source === 'widgetClick' + && existing.sourceWidgetId === incoming.sourceWidgetId + && existing.operator === incoming.operator + && sameValue(existing.value, incoming.value) +} + +/** + * The audit line of a replaced clause. + * + * @param {object} incoming The new clause. + * @param {object} existing The clause it replaces. + * @return {object} + */ +function replaceAudit(incoming, existing) { + return { + dimension: incoming.dimension, + from: existing.value, + to: incoming.value, + fromSource: existing.source, + toSource: incoming.source, + silent: TRANSIENT_SOURCES.includes(existing.source) || sameValue(existing.value, incoming.value), + } +} + +/** + * The filter bus. + * + * @param {object} [options] Bus options. + * @param {Array<object>} [options.hierarchies] The dashboard's hierarchy descriptors. + * @param {(clause: object) => boolean} [options.canAccess] False refuses the clause. + * @param {{record: (eventType: string, clauses: Array<object>, widgetId?: string|null) => unknown}|null} [options.telemetry] Records filter changes (REQ-CWF-010); none by default. + * @return {object} The bus: `clauses` (a read-only ref), `hierarchies` (as given, for widget validation), `publish`, `remove`, `reset`, `hydrate`, `subscribe`, `clausesFor`, `breadcrumb`, `popTo`. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-001-widget-click-publishes-to-the-filter-bus + */ +export function useFilterBus({ hierarchies = [], canAccess = () => true, telemetry = null } = {}) { + const clauses = shallowRef([]) + const subscribers = new Set() + + /** + * Replace the clause list and tell every subscriber. + * + * @param {Array<object>} next The new list. + * @return {void} + */ + function commit(next) { + clauses.value = Object.freeze(next.slice()) + subscribers.forEach((subscriber) => subscriber(clauses.value)) + } + + /** + * Drop `parentScope` clauses that no longer have an explicit clause below them. + * + * @param {Array<object>} list The clause list. + * @return {Array<object>} + */ + function pruneOrphanedAncestors(list) { + return list.filter((clause) => { + if (clause.source !== 'parentScope') { + return true + } + const position = levelOf(hierarchies, clause.dimension) + if (position === null) { + return true + } + const below = position.levels.slice(position.index + 1).map((level) => level.dimension) + return list.some((other) => other.source !== 'parentScope' && below.includes(other.dimension)) + }) + } + + /** + * Decide what an incoming clause does to the existing one for its dimension. + * + * @param {object} incoming The new clause. + * @param {object|undefined} existing The clause it meets. + * @return {{action: string, audit: object|null}} `add`, `replace`, `drop` or `toggle`. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-005-filter-conflict-resolution-is-last-write-wins-per-dimension + */ + function applyConflictResolution(incoming, existing) { + if (!existing) { + return { action: 'add', audit: null } + } + if (existing.pinned) { + return { action: 'drop', audit: null } + } + if (isSameClick(incoming, existing)) { + return { action: 'toggle', audit: null } + } + return { action: 'replace', audit: replaceAudit(incoming, existing) } + } + + /** + * Publish a clause. + * + * @param {object} clause The clause: `{dimension, operator, value, source, sourceWidgetId, pinned}`. + * @param {object} [context] `{row}`: the clicked row, for inferring ancestor levels. + * @return {{accepted: boolean, reason?: string, toggled?: boolean, audit?: object|null}} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-001-widget-click-publishes-to-the-filter-bus + */ + function publish(clause, context = {}) { + if (!hasDimension(clause)) { + return { accepted: false, reason: 'invalid' } + } + const incoming = normalise(clause) + if (canAccess(incoming) !== true) { + return { accepted: false, reason: 'forbidden' } + } + return settle(incoming, context) + } + + /** + * Settle a permitted clause against the one already on its dimension: + * a pinned one drops it, the same click toggles it off, anything else + * replaces it with its hierarchy. + * + * @param {object} incoming The normalised new clause. + * @param {object} context The publish context (the clicked row). + * @return {object} The publish answer. + */ + function settle(incoming, context) { + const existing = clauses.value.find((entry) => entry.dimension === incoming.dimension) + const decision = applyConflictResolution(incoming, existing) + if (decision.action === 'drop') { + logger.warn(`[launchpad] ${incoming.dimension} is pinned; the new filter was dropped`) + return { accepted: false, reason: 'pinned' } + } + if (decision.action === 'toggle') { + commit(pruneOrphanedAncestors(clauses.value.filter((entry) => entry !== existing))) + return { accepted: true, toggled: true, audit: null } + } + + return drill(incoming, decision, context) + } + + /** + * Apply a new clause with its hierarchy: the ancestors it implies are + * inferred, its descendants cleared, and a pinned ancestor with another + * value refuses it. + * + * @param {object} incoming The new clause. + * @param {object} decision The conflict decision for its dimension. + * @param {object} context The publish context (the clicked row). + * @return {object} The publish answer. + */ + function drill(incoming, decision, context) { + const { descendants, ancestors } = resolveHierarchy(incoming, hierarchies, context.row) + const pinnedAncestor = ancestors.find((ancestor) => clauses.value.some( + (entry) => entry.dimension === ancestor.dimension && entry.pinned && !sameValue(entry.value, ancestor.value), + )) + if (pinnedAncestor) { + logger.warn(`[launchpad] ${pinnedAncestor.dimension} is pinned to another value; the new filter was dropped`) + return { accepted: false, reason: 'pinned' } + } + + const replaced = new Set([incoming.dimension, ...ancestors.map((ancestor) => ancestor.dimension)]) + const kept = clauses.value.filter((entry) => { + if (replaced.has(entry.dimension)) { + return entry.pinned + } + return entry.pinned || !descendants.includes(entry.dimension) + }) + const inferred = ancestors.filter((ancestor) => !kept.some((entry) => entry.dimension === ancestor.dimension)) + commit(pruneOrphanedAncestors([...kept, ...inferred, incoming])) + telemetry?.record('apply', [incoming], incoming.sourceWidgetId) + return { accepted: true, toggled: false, audit: decision.audit } + } + + /** + * Remove the clause for one dimension, unless it is pinned. + * + * @param {string} dimension The dimension. + * @return {boolean} Whether anything was removed. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-007-filter-stack-ui-shows-every-active-clause-with-its-source + */ + function remove(dimension) { + const existing = clauses.value.find((entry) => entry.dimension === dimension) + if (!existing || existing.pinned) { + return false + } + commit(pruneOrphanedAncestors(clauses.value.filter((entry) => entry !== existing))) + return true + } + + /** + * Clear every non-pinned clause. A bus with nothing to clear is left + * untouched and tells nobody, so a double click makes no noise. + * + * @return {boolean} Whether anything was cleared. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-006-reset-filters-clears-all-non-pinned-clauses + */ + function reset() { + const kept = clauses.value.filter((entry) => entry.pinned) + if (kept.length === clauses.value.length) { + return false + } + const cleared = clauses.value.filter((entry) => !entry.pinned) + commit(kept) + telemetry?.record('reset', cleared) + return true + } + + /** + * Whether a restored clause may join: it names a dimension no clause holds yet. + * + * @param {object} clause The restored clause. + * @param {Array<object>} next The clauses so far. + * @return {boolean} + */ + function isRestorable(clause, next) { + return Boolean(clause) && typeof clause.dimension === 'string' && !next.some((entry) => entry.dimension === clause.dimension) + } + + /** + * A restored clause as the bus holds it: a pinned one keeps its source. + * + * @param {object} clause The restored clause. + * @param {string} source Where the restore came from. + * @return {object} + */ + function restoredClause(clause, source) { + return normalise({ ...clause, source: clause.pinned ? clause.source : source }) + } + + /** + * Replace the state with clauses restored from elsewhere (the URL, a saved + * view), marked with that origin. Pinned clauses already on the bus stay. + * + * @param {Array<object>} restored The clauses. + * @param {string} [source] Their origin, `urlBootstrap` by default. + * @return {void} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-003-url-encoding-makes-filtered-views-bookmarkable + */ + function hydrate(restored, source = 'urlBootstrap') { + const pinned = clauses.value.filter((entry) => entry.pinned) + const next = [...pinned] + for (const clause of Array.isArray(restored) ? restored : []) { + if (isRestorable(clause, next)) { + next.push(restoredClause(clause, source)) + } + } + commit(next) + const bookmarked = next.filter((entry) => !pinned.includes(entry)) + if (telemetry && source === 'urlBootstrap' && bookmarked.length > 0) { + // REQ-CWF-010: a bookmarked URL is recorded on the next tick, after the page settled. + setTimeout(() => telemetry.record('bookmark', bookmarked), 0) + } + } + + /** + * Listen to every change; the listener gets the new clause list. + * + * @param {(clauses: Array<object>) => void} listener Gets the new clause list. + * @return {() => boolean} Stops listening. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-002-all-consuming-widgets-re-render-on-filter-change + */ + function subscribe(listener) { + subscribers.add(listener) + return () => subscribers.delete(listener) + } + + /** + * The clauses a widget consumes, for its filter context. A widget mounting + * later gets the current state the same way, so it never renders unfiltered. + * + * @param {string[]} consumes The dimensions the widget consumes. + * @return {Array<object>} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-002-all-consuming-widgets-re-render-on-filter-change + */ + function clausesFor(consumes) { + const dimensions = Array.isArray(consumes) ? consumes : [] + return clauses.value.filter((entry) => dimensions.includes(entry.dimension)) + } + + /** + * The active path of a hierarchy, broadest level first, for the breadcrumb. + * + * @param {string} hierarchyId The hierarchy id. + * @return {Array<{dimension: string, label: string, value: unknown}>} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ + function breadcrumb(hierarchyId) { + return breadcrumbPath(hierarchies, clauses.value, hierarchyId) + } + + /** + * Go back up a hierarchy to one level, the way a breadcrumb click does: + * the levels below it are cleared (pinned ones stay), and an inferred + * clause on that level becomes the reader's own, so it stays once + * nothing below it is left. + * + * @param {string} dimension The level to go back to. + * @return {boolean} Whether anything changed. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ + function popTo(dimension) { + const position = levelOf(hierarchies, dimension) + const target = clauses.value.find((entry) => entry.dimension === dimension) + if (position === null || !target) { + return false + } + const below = position.levels.slice(position.index + 1).map((level) => level.dimension) + const next = clauses.value + .filter((entry) => entry.pinned || !below.includes(entry.dimension)) + .map((entry) => (entry === target && entry.source === 'parentScope' ? { ...entry, source: 'userExplicit' } : entry)) + if (next.length === clauses.value.length && next.every((entry, index) => entry === clauses.value[index])) { + return false + } + commit(pruneOrphanedAncestors(next)) + return true + } + + return { clauses, hierarchies, publish, remove, reset, hydrate, subscribe, clausesFor, breadcrumb, popTo } +} diff --git a/src/composables/useFilterUrlSync.js b/src/composables/useFilterUrlSync.js new file mode 100644 index 000000000..261343649 --- /dev/null +++ b/src/composables/useFilterUrlSync.js @@ -0,0 +1,105 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * useFilterUrlSync — keeps the dashboard's filter bus and the address bar in + * step (drill-down-cross-widget-filter, REQ-CWF-003). + * + * On start the `f` parameter is read once and its clauses enter the bus as + * `urlBootstrap`, so a bookmarked or shared link opens with the same filter. + * After that every change of the bus is written back to the URL, debounced so + * a burst of clicks rewrites the address once. An empty bus removes `f`. The + * URL is replaced, never pushed: filtering is not navigation, so the back + * button still leaves the dashboard instead of stepping through clicks. + */ + +import { deserializeFilterState, FILTER_PARAM, serializeFilterState } from './useDashboardFilter.js' + +/** + * Milliseconds a change waits before the URL is rewritten. + * + * @type {number} + */ +export const URL_SYNC_DEBOUNCE_MS = 500 + +/** + * The URL with `f` set to the encoded clauses, or without `f` when there are none. + * + * @param {string} href The current URL. + * @param {Array<object>} clauses The bus's clauses. + * @return {string} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-003-url-encoding-makes-filtered-views-bookmarkable + */ +export function urlWithFilter(href, clauses) { + const url = new URL(href) + const list = Array.isArray(clauses) ? clauses : [] + if (list.length === 0) { + url.searchParams.delete(FILTER_PARAM) + } else { + url.searchParams.set(FILTER_PARAM, serializeFilterState(list)) + } + return url.toString() +} + +/** + * Connect a bus to the address bar. + * + * @param {object} options The wiring. + * @param {object} options.bus A bus from useFilterBus(). + * @param {{href: string}} [options.location] The location to read (window.location). + * @param {{replaceState: (state: unknown, title: string, url: string) => void, state: unknown}} [options.history] The history to write (window.history). + * @param {number} [options.debounceMs] The debounce delay. + * @param {boolean} [options.hydrate] Whether the URL's `f` seeds the bus; false only writes. + * @return {{stop: () => void, flush: () => void, restored: Array<object>}} `stop` ends the sync, `flush` writes now; `restored` the clauses read from the URL. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-003-url-encoding-makes-filtered-views-bookmarkable + */ +export function useFilterUrlSync({ bus, location = window.location, history = window.history, debounceMs = URL_SYNC_DEBOUNCE_MS, hydrate = true }) { + const param = hydrate ? new URL(location.href).searchParams.get(FILTER_PARAM) : null + const restored = param ? deserializeFilterState(param).clauses : [] + if (restored.length > 0) { + bus.hydrate(restored, 'urlBootstrap') + } + + let timer = null + let pending = null + + /** + * Write the pending clause list to the URL, when it changes the URL. + * + * @return {void} + */ + function flush() { + if (timer !== null) { + clearTimeout(timer) + timer = null + } + if (pending === null) { + return + } + const next = urlWithFilter(location.href, pending) + pending = null + if (next !== location.href) { + history.replaceState(history.state, '', next) + } + } + + const unsubscribe = bus.subscribe((clauses) => { + pending = clauses + if (timer !== null) { + clearTimeout(timer) + } + timer = setTimeout(flush, debounceMs) + }) + + /** + * End the sync; a change still waiting is written first. + * + * @return {void} + */ + function stop() { + unsubscribe() + flush() + } + + return { stop, flush, restored } +} diff --git a/src/composables/useGridManager.js b/src/composables/useGridManager.js index 7ef425bc0..8e22e2fb9 100644 --- a/src/composables/useGridManager.js +++ b/src/composables/useGridManager.js @@ -178,9 +178,31 @@ export const DEFAULT_H = 4 * @spec openspec/specs/grid-layout/spec.md */ export function placeNewWidget(spec, placements) { - const w = spec && Number.isFinite(spec.w) && spec.w > 0 ? spec.w : DEFAULT_W - const h = spec && Number.isFinite(spec.h) && spec.h > 0 ? spec.h : DEFAULT_H + const w = positiveCells(spec?.w, DEFAULT_W) + const h = positiveCells(spec?.h, DEFAULT_H) + return { x: 0, y: lowestBottomEdge(placements), w, h, pushed: [] } +} + +/** + * A finite, positive cell count, or the fallback. + * + * @param {unknown} value the requested cell count. + * @param {number} fallback the default cell count. + * @return {number} the cell count to use. + */ +function positiveCells(value, fallback) { + return Number.isFinite(value) && value > 0 ? value : fallback +} + +/** + * The lowest occupied bottom edge (`gridY + gridHeight`) of the placements; + * a missing `gridY` reads as 0 and a missing `gridHeight` as 1. + * + * @param {Array<object>} placements current placements (non-arrays read as none). + * @return {number} the bottom edge, 0 for an empty dashboard. + */ +function lowestBottomEdge(placements) { const safePlacements = Array.isArray(placements) ? placements : [] let bottomY = 0 for (const p of safePlacements) { @@ -188,8 +210,7 @@ export function placeNewWidget(spec, placements) { const ph = Number.isFinite(p.gridHeight) ? p.gridHeight : 1 bottomY = Math.max(bottomY, y + ph) } - - return { x: 0, y: bottomY, w, h, pushed: [] } + return bottomY } /** @@ -200,6 +221,50 @@ export function placeNewWidget(spec, placements) { */ export const MIN_CELLS = 2 +/** + * Widget types that may be one row tall, below {@link MIN_CELLS}. A divider + * is a single line between sections (REQ-DIV-006), a section heading one + * heading over them (REQ-WDG-031). + * + * @type {ReadonlyArray<string>} + */ +export const ONE_ROW_TYPES = Object.freeze(['divider', 'section-heading']) + +/** + * New-widget sizes for types whose spec names one other than the default. + * Quicklinks is a compact row of icons, 4 by 2 (REQ-QLNK-011). An app tile + * is one cell of two columns by two rows, the tile square inside it (REQ-APPTILE-002). + * + * @type {Readonly<Record<string, {w: number, h: number}>>} + */ +const TYPE_DEFAULT_SIZES = Object.freeze({ + quicklinks: Object.freeze({ w: 4, h: 2 }), + 'app-tile': Object.freeze({ w: 2, h: 2 }), +}) + +/** + * The size a new widget of a type gets when the caller names none: a divider + * spans every column and is one row tall (REQ-DIV-006); a type in + * {@link TYPE_DEFAULT_SIZES} gets its own size; anything else is + * {@link DEFAULT_W} by {@link DEFAULT_H}. + * + * @param {string} type The widget type. + * @param {number} [columns] The dashboard's column count. + * @return {{w: number, h: number}} The size. + * @spec openspec/specs/divider-widget/spec.md + * @spec openspec/specs/quicklinks-widget/spec.md + */ +export function defaultSizeFor(type, columns = DEFAULT_COLUMNS) { + if (type === 'divider' || type === 'section-heading') { + return { w: columns, h: 1 } + } + const own = TYPE_DEFAULT_SIZES[type] + if (own) { + return { ...own } + } + return { w: DEFAULT_W, h: DEFAULT_H } +} + /** * Whether two grid rectangles overlap. * @@ -216,6 +281,92 @@ function rectsOverlap(a, b) { return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h } +/** + * The grid rectangle of a neighbouring placement, with a missing or + * non-finite position read as 0 and a missing size as 1. + * + * @param {{gridX?: number, gridY?: number, gridWidth?: number, gridHeight?: number}} other A placement in LaunchPad field-name form. + * @return {{x: number, y: number, w: number, h: number}} Its rectangle. + */ +function neighbourRect(other) { + return { + x: Number.isFinite(other.gridX) ? other.gridX : 0, + y: Number.isFinite(other.gridY) ? other.gridY : 0, + w: Number.isFinite(other.gridWidth) ? other.gridWidth : 1, + h: Number.isFinite(other.gridHeight) ? other.gridHeight : 1, + } +} + +/** + * The grid rectangle of the placement being nudged, with a missing or + * non-finite position read as 0 and a missing size as {@link MIN_CELLS}. + * + * @param {{gridX?: number, gridY?: number, gridWidth?: number, gridHeight?: number}} [placement] A placement in LaunchPad field-name form. + * @return {{x: number, y: number, w: number, h: number}} Its rectangle. + */ +function placementRect(placement) { + return { + x: Number.isFinite(placement?.gridX) ? placement.gridX : 0, + y: Number.isFinite(placement?.gridY) ? placement.gridY : 0, + w: Number.isFinite(placement?.gridWidth) ? placement.gridWidth : MIN_CELLS, + h: Number.isFinite(placement?.gridHeight) ? placement.gridHeight : MIN_CELLS, + } +} + +/** + * One keyboard step per action: each takes the current rectangle and the + * column count and returns the moved or resized rectangle. + */ +const NUDGES = { + 'move-up': (rect) => ({ ...rect, y: Math.max(0, rect.y - 1) }), + 'move-down': (rect) => ({ ...rect, y: rect.y + 1 }), + 'move-left': (rect) => ({ ...rect, x: Math.max(0, rect.x - 1) }), + 'move-right': (rect, columns) => ({ + ...rect, + x: Math.min(Math.max(0, columns - rect.w), rect.x + 1), + }), + 'grow-width': (rect, columns) => ({ + ...rect, + w: Math.min(columns - rect.x, rect.w + 1), + }), + 'shrink-width': (rect) => ({ ...rect, w: Math.max(MIN_CELLS, rect.w - 1) }), + 'grow-height': (rect) => ({ ...rect, h: rect.h + 1 }), + 'shrink-height': (rect, columns, minHeight = MIN_CELLS) => ({ ...rect, h: Math.max(minHeight, rect.h - 1) }), +} + +/** + * Shift a rectangle left so it ends inside the grid's columns. + * + * @param {{x: number, y: number, w: number, h: number}} rect The rectangle. + * @param {number} columns The column count. + * @return {{x: number, y: number, w: number, h: number}} The rectangle, inside the columns. + */ +function keepInColumns(rect, columns) { + if (rect.x + rect.w > columns) { + return { ...rect, x: Math.max(0, columns - rect.w) } + } + return rect +} + +/** + * The neighbours a nudged rectangle overlaps, each pushed to the row below it. + * The moved placement itself and empty entries are skipped. + * + * @param {{rect: {x: number, y: number, w: number, h: number}, id?: (number|string)}} moved The nudged rectangle and the id of its placement. + * @param {Array<object>} allPlacements Every placement on the dashboard. + * @return {Array<{id: (number|string), gridY: number}>} The pushed neighbours. + */ +function pushedNeighbours(moved, allPlacements) { + const others = Array.isArray(allPlacements) ? allPlacements : [] + return others + .filter( + (other) => + other !== null && other !== undefined && other.id !== moved.id, + ) + .filter((other) => rectsOverlap(moved.rect, neighbourRect(other))) + .map((other) => ({ id: other.id, gridY: moved.rect.y + moved.rect.h })) +} + /** * Compute the candidate rectangle for a keyboard-driven move or resize of * an existing placement, reusing the same collision model as @@ -232,8 +383,9 @@ function rectsOverlap(a, b) { * resize by one cell, clamped to {@link MIN_CELLS} and the column * count. * - * @param {{gridX: number, gridY: number, gridWidth: number, gridHeight: number, id?: (number|string)}} placement - * the placement being moved/resized (LaunchPad field-name form) + * @param {{gridX: number, gridY: number, gridWidth: number, gridHeight: number, id?: (number|string), widgetId?: string}} placement + * the placement being moved/resized (LaunchPad field-name form); a type in + * {@link ONE_ROW_TYPES} may shrink to one row * @param {string} action one of the supported action strings above * @param {Array<object>} allPlacements every placement on the dashboard * (used to compute push-down side effects), in LaunchPad field-name form @@ -247,78 +399,16 @@ function rectsOverlap(a, b) { */ export function nudgePlacement(placement, action, allPlacements, options = {}) { const columns = options.gridColumns || DEFAULT_COLUMNS - - const x = Number.isFinite(placement?.gridX) ? placement.gridX : 0 - const y = Number.isFinite(placement?.gridY) ? placement.gridY : 0 - const w = Number.isFinite(placement?.gridWidth) ? placement.gridWidth : MIN_CELLS - const h = Number.isFinite(placement?.gridHeight) - ? placement.gridHeight - : MIN_CELLS - - let nx = x - let ny = y - let nw = w - let nh = h - - switch (action) { - case 'move-up': - ny = Math.max(0, y - 1) - break - case 'move-down': - ny = y + 1 - break - case 'move-left': - nx = Math.max(0, x - 1) - break - case 'move-right': - nx = Math.min(Math.max(0, columns - w), x + 1) - break - case 'grow-width': - nw = Math.min(columns - x, w + 1) - break - case 'shrink-width': - nw = Math.max(MIN_CELLS, w - 1) - break - case 'grow-height': - nh = h + 1 - break - case 'shrink-height': - nh = Math.max(MIN_CELLS, h - 1) - break - default: - // Unknown action → no change. - break - } - - // Keep the widget inside the horizontal bounds after any width change. - if (nx + nw > columns) { - nx = Math.max(0, columns - nw) - } - - const newRect = { x: nx, y: ny, w: nw, h: nh } - const pushed = [] - const others = Array.isArray(allPlacements) ? allPlacements : [] - for (const other of others) { - if (other === null || other === undefined || other.id === placement?.id) { - continue - } - const otherRect = { - x: Number.isFinite(other.gridX) ? other.gridX : 0, - y: Number.isFinite(other.gridY) ? other.gridY : 0, - w: Number.isFinite(other.gridWidth) ? other.gridWidth : 1, - h: Number.isFinite(other.gridHeight) ? other.gridHeight : 1, - } - if (rectsOverlap(newRect, otherRect)) { - pushed.push({ id: other.id, gridY: ny + nh }) - } - } + const minHeight = ONE_ROW_TYPES.includes(placement?.widgetId) ? 1 : MIN_CELLS + const nudge = Object.hasOwn(NUDGES, action) ? NUDGES[action] : (rect) => rect + const rect = keepInColumns(nudge(placementRect(placement), columns, minHeight), columns) return { - gridX: nx, - gridY: ny, - gridWidth: nw, - gridHeight: nh, - pushed, + gridX: rect.x, + gridY: rect.y, + gridWidth: rect.w, + gridHeight: rect.h, + pushed: pushedNeighbours({ rect, id: placement?.id }, allPlacements), } } diff --git a/src/composables/useTileClickTracking.js b/src/composables/useTileClickTracking.js index 27b1798e8..a83203e24 100644 --- a/src/composables/useTileClickTracking.js +++ b/src/composables/useTileClickTracking.js @@ -24,6 +24,7 @@ import axios from '@nextcloud/axios' import { generateUrl } from '@nextcloud/router' import { logger } from '../utils/logger.js' +import { recordTileUse } from '../utils/tileSort.js' const baseUrl = generateUrl('/apps/launchpad') @@ -78,8 +79,14 @@ function isTrackingActive() { /** * Tile usage-analytics client hook. * - * @return {{recordTileClick: (placementId: (string|number)) => void}} + * Besides the anonymous server call it hands out `recordTileUse()`, which + * keeps `{count, lastUsedAt}` per placement in this browser only, for a + * container sorted by most or last used (launcher-tile-sorting). Those counts + * are never sent to the server. + * + * @return {{recordTileClick: (placementId: (string|number)) => void, recordTileUse: (placementId: (string|number)) => void}} * @spec openspec/specs/dashboard-view-analytics/spec.md + * @spec openspec/changes/launcher-tile-sorting/specs/container-widget/spec.md */ export function useTileClickTracking() { /** @@ -110,7 +117,7 @@ export function useTileClickTracking() { }) } - return { recordTileClick } + return { recordTileClick, recordTileUse } } /** diff --git a/src/composables/useTileSearch.js b/src/composables/useTileSearch.js index ede1885c8..00e60a141 100644 --- a/src/composables/useTileSearch.js +++ b/src/composables/useTileSearch.js @@ -291,6 +291,99 @@ export function isCtrlKFocusShortcut(event) { return Boolean(event.ctrlKey || event.metaKey) } +/** + * Split a query into a known search shortcut and the rest (REQ-SPX-002). + * The first word must equal a shortcut prefix, case-insensitively. + * + * @param {string} query The raw query. + * @param {Array<{prefix: string, name: string, urlTemplate: string}>} shortcuts The admin's shortcuts. + * @return {{shortcut: object, rest: string}|null} The match, or null. + * @spec openspec/specs/tile-quick-search/spec.md + */ +export function parsePrefix(query, shortcuts) { + const trimmed = String(query ?? '').trim() + if (!trimmed.startsWith('!') || !Array.isArray(shortcuts)) { + return null + } + const [first, ...rest] = trimmed.split(/\s+/) + const shortcut = shortcuts.find( + (entry) => String(entry?.prefix || '').toLowerCase() === first.toLowerCase(), + ) + return shortcut ? { shortcut, rest: rest.join(' ') } : null +} + +/** + * The address a shortcut opens for a query: its template with the + * URL-encoded query, only when the template is a valid https `{query}` + * address (REQ-SPX-002). + * + * @param {{urlTemplate: string}} shortcut The shortcut. + * @param {string} rest The query after the prefix. + * @return {string|null} The address, or null. + * @spec openspec/specs/tile-quick-search/spec.md + */ +export function shortcutUrl(shortcut, rest) { + if (!isValidFallbackTemplate(shortcut?.urlTemplate)) { + return null + } + return shortcut.urlTemplate.replace('{query}', encodeURIComponent(rest)) +} + +/** + * Whether a query asks for the shortcut list: `!` alone or `?` (REQ-SPX-003). + * + * @param {string} query The raw query. + * @return {boolean} True for the list. + * @spec openspec/specs/tile-quick-search/spec.md + */ +export function isShortcutListQuery(query) { + const trimmed = String(query ?? '').trim() + return trimmed === '!' || trimmed === '?' +} + +/** + * Result kinds that come from a search shortcut rather than a tile. + * + * @type {string[]} + */ +const SHORTCUT_KINDS = ['shortcut', 'shortcut-list'] + +/** + * The results a query yields from the search shortcuts: the shortcut list + * for `!` or `?` (REQ-SPX-003), or the one shortcut a known prefix names + * (REQ-SPX-002). Null when the query is neither, so tile ranking applies. + * + * @param {string} trimmed The trimmed query. + * @param {Array<{prefix: string, name: string, urlTemplate: string}>} shortcuts The admin's shortcuts. + * @return {Array<object>|null} The results, or null. + * @spec openspec/specs/tile-quick-search/spec.md + */ +export function shortcutResults(trimmed, shortcuts) { + if (isShortcutListQuery(trimmed) && shortcuts.length > 0) { + return shortcuts.map((shortcut) => ({ + id: `shortcut-list:${shortcut.prefix}`, + label: `${shortcut.prefix} ${shortcut.name}`, + kind: 'shortcut-list', + shortcut, + item: null, + })) + } + const prefixed = parsePrefix(trimmed, shortcuts) + if (!prefixed) { + return null + } + return [ + { + id: `shortcut:${prefixed.shortcut.prefix}`, + label: prefixed.shortcut.name, + kind: 'shortcut', + shortcut: prefixed.shortcut, + rest: prefixed.rest, + item: null, + }, + ] +} + /** * Factory — one instance per mounted search bar. Mirrors the * `useGridManager()` shape: a `reactive()` reactive `state` plus @@ -307,12 +400,24 @@ export function isCtrlKFocusShortcut(event) { * @param {() => string} [options.getFallbackTarget] returns the current * `quicksearch_fallback_target` value; consulted lazily so the caller * can change it without recreating the composable. + * @param {() => Array<object>} [options.getShortcuts] returns the admin's + * search shortcuts (REQ-SPX-002); consulted on every recompute. * @return {object} the `{state, ...methods}` API — see inline method docs. * * @spec openspec/specs/tile-quick-search/spec.md */ export function useTileSearch(options = {}) { - const { onOpen, onFallback, getFallbackTarget } = options + const { onOpen, onFallback, getFallbackTarget, getShortcuts } = options + + /** + * The admin's shortcuts, or an empty list. + * + * @return {Array<object>} Shortcuts. + */ + function shortcuts() { + const list = typeof getShortcuts === 'function' ? getShortcuts() : [] + return Array.isArray(list) ? list : [] + } const state = reactive({ query: '', @@ -337,6 +442,13 @@ export function useTileSearch(options = {}) { state.activeIndex = -1 return } + // REQ-SPX-002/003: a shortcut list or a known prefix wins over tile ranking. + const fromShortcuts = shortcutResults(trimmed, shortcuts()) + if (fromShortcuts) { + state.results = fromShortcuts + state.activeIndex = 0 + return + } state.results = rankItems(trimmed, items) state.activeIndex = state.results.length > 0 ? 0 : -1 } @@ -412,6 +524,9 @@ export function useTileSearch(options = {}) { */ function pressEnter() { const result = activeResult() + if (result && SHORTCUT_KINDS.includes(result.kind)) { + return pressShortcut(result) + } if (result) { if (typeof onOpen === 'function') { onOpen(result.item) @@ -424,10 +539,43 @@ export function useTileSearch(options = {}) { ? getFallbackTarget() : FALLBACK_TARGET_NONE const action = resolveFallbackAction(target, state.query.trim()) + notifyFallback(action) + return action + } + + /** + * Enter on a shortcut result. On a listed shortcut it types the prefix + * (REQ-SPX-003); on a prefixed query it opens the shortcut's site with + * the rest of the query, or does nothing without one (REQ-SPX-002). + * + * @param {object} result the active `shortcut` or `shortcut-list` result. + * @return {{type: 'shortcut-list', shortcut: object}|{type: 'web-search', url: string}|{type: 'none'}} + * the action taken. + */ + function pressShortcut(result) { + if (result.kind === 'shortcut-list') { + setQuery(`${result.shortcut.prefix} `) + return { type: 'shortcut-list', shortcut: result.shortcut } + } + const url = result.rest ? shortcutUrl(result.shortcut, result.rest) : null + if (!url) { + return { type: FALLBACK_TARGET_NONE } + } + const action = { type: 'web-search', url } + notifyFallback(action) + return action + } + + /** + * Hand a fallback action to the caller's `onFallback`, when given. + * + * @param {object} action the resolved action. + * @return {void} + */ + function notifyFallback(action) { if (typeof onFallback === 'function') { onFallback(action) } - return action } /** diff --git a/src/composables/useTileSearchHost.js b/src/composables/useTileSearchHost.js index 890fc94aa..80317cb91 100644 --- a/src/composables/useTileSearchHost.js +++ b/src/composables/useTileSearchHost.js @@ -112,24 +112,49 @@ export function buildSearchableTiles(placements, availableWidgets) { * @spec openspec/specs/tile-quick-search/spec.md#req-qsearch-003 */ export function activateSearchResult(item) { - const placementId = String(item?.placement?.id ?? '') - const grid = gridContainer() - if (!placementId || !grid) { - return false - } - const el = grid.querySelector( - `.launchpad-grid-item[data-placement-id="${placementId.replace(/"/g, '\\"')}"]`, - ) + const el = resultTile(item) if (!el) { return false } if (typeof el.scrollIntoView === 'function') { el.scrollIntoView({ behavior: 'smooth', block: 'center' }) } + openTile(el) + return true +} + +/** + * The rendered grid item of an opened search result, or null when the page + * has no grid or the result names no placement the grid shows. + * + * @param {{placement: object}} item the opened result. + * @return {HTMLElement|null} the grid item. + * @spec openspec/specs/tile-quick-search/spec.md#req-qsearch-003 + */ +function resultTile(item) { + const placementId = String(item?.placement?.id ?? '') + const grid = gridContainer() + if (!placementId || !grid) { + return null + } + return grid.querySelector( + `.launchpad-grid-item[data-placement-id="${placementId.replace(/"/g, '\\"')}"]`, + ) +} + +/** + * Open a grid item: follow its link when it has one, otherwise focus the + * item itself (made focusable first when it is not). + * + * @param {HTMLElement} el the grid item. + * @return {void} + * @spec openspec/specs/tile-quick-search/spec.md#req-qsearch-003 + */ +function openTile(el) { const link = el.querySelector('a[href]') if (link && typeof link.click === 'function') { link.click() - return true + return } if (typeof el.focus === 'function') { if (!el.hasAttribute('tabindex')) { @@ -137,7 +162,6 @@ export function activateSearchResult(item) { } el.focus({ preventScroll: true }) } - return true } /** diff --git a/src/composables/useVisibilityPreview.js b/src/composables/useVisibilityPreview.js index 37cc85319..1e14ee383 100644 --- a/src/composables/useVisibilityPreview.js +++ b/src/composables/useVisibilityPreview.js @@ -17,26 +17,81 @@ import { reactive } from 'vue' import { api } from '../services/api.js' +/** + * The id the preview endpoint echoes back for a rule: its server id, or for + * a never-saved draft its negative local key, so a matched draft can be + * named without colliding with a stored rule. + * + * @param {object} rule one entry of the in-editor rule set + * @return {number|null|undefined} the correlation id + */ +export function previewRuleId(rule) { + return rule.id ?? rule._localKey +} + /** * @param {object} rule one entry of the in-editor rule set: - * `{id?: number, ruleType: string, ruleConfig: object, isInclude: boolean}` - * @return {{ruleType: string, ruleConfig: object, isInclude: boolean, id: (number|undefined)}} + * `{id?: number, _localKey?: number, ruleType: string, ruleConfig: object, isInclude: boolean}` + * @return {{ruleType: string, ruleConfig: object, isInclude: boolean, id: (number|null|undefined)}} */ function toPreviewRule(rule) { return { - id: rule.id, + id: previewRuleId(rule), ruleType: rule.ruleType, ruleConfig: rule.ruleConfig, isInclude: rule.isInclude, } } +/** + * The preview request: the rules as the editor holds them, the context, and + * — when given — who to view as, how the rules combine and the placement. + * + * @param {object[]} rules the in-editor rule set + * @param {object} context `{groups?, datetime?, userId?, match?, placementId?}` + * @return {object} the request body + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ +export function previewBody(rules, context) { + const given = context || {} + const body = { + rules: (rules || []).map(toPreviewRule), + context: previewContext(given), + } + if (given.match) { + body.match = given.match + } + if (given.placementId !== null && given.placementId !== undefined) { + body.placementId = Number(given.placementId) + } + return body +} + +/** + * The preview context: the groups and the moment, and who to view as when + * a person is chosen. + * + * @param {object} context `{groups?, datetime?, userId?}` + * @return {object} the context to send + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ +function previewContext(context) { + const sent = { + groups: context.groups || [], + datetime: context.datetime || null, + } + if (context.userId) { + sent.userId = context.userId + } + return sent +} + /** * Build the preview composable's reactive state + `runPreview` action. * * @return {{ * state: {loading: boolean, error: (Error|null), result: (object|null)}, - * runPreview: (rules: object[], context: {groups: string[], datetime: string}) => Promise<object>, + * runPreview: (rules: object[], context: object) => Promise<object>, * reset: () => void, * }} * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-004-preview-as-audience-and-date @@ -55,22 +110,20 @@ export function useVisibilityPreview() { * * @param {object[]} rules the current in-editor rule set (unsaved edits * included — REQ-CVUI-004 "Preview evaluates unsaved edits") - * @param {object} context `{groups: string[], datetime: string}` + * @param {object} context `{groups?: string[], datetime: string, userId?: string, + * match?: 'any'|'all', placementId?: number}`; with `userId` the rules are + * evaluated as that person (View as), `match` says how the include rules + * combine, `placementId` names the placement whose rules these are * @return {Promise<{visible: boolean, matchedIncludeRuleIds: number[], matchedExcludeRuleIds: number[]}>} * the preview result * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-004-preview-as-audience-and-date + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 */ async function runPreview(rules, context) { state.loading = true state.error = null try { - const body = { - rules: (rules || []).map(toPreviewRule), - context: { - groups: (context && context.groups) || [], - datetime: (context && context.datetime) || null, - }, - } + const body = previewBody(rules, context) const { data } = await api.previewVisibility(body) const result = data && data.data ? data.data : data state.result = result diff --git a/src/constants/__tests__/fixtures/propDefinitions.golden.json b/src/constants/__tests__/fixtures/propDefinitions.golden.json new file mode 100644 index 000000000..2bc323e00 --- /dev/null +++ b/src/constants/__tests__/fixtures/propDefinitions.golden.json @@ -0,0 +1,2546 @@ +{ + "../../App.vue | manifest": { + "type": "Object", + "required": true, + "validator": false + }, + "../../App.vue | registry": { + "type": "Object", + "required": true, + "validator": false + }, + "../../App.vue | pageTypes": { + "type": "Object", + "required": true, + "validator": false + }, + "../../App.vue | permissions": { + "type": "Array", + "required": false, + "validator": false, + "default": [ + "user" + ], + "fresh": true + }, + "../../components/AcknowledgementPrompt.vue | placement": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/Announcements/AnnouncementCard.vue | announcement": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/Announcements/AnnouncementCard.vue | reactions": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "likes": 0, + "comments": 0, + "liked": false + }, + "fresh": true + }, + "../../components/Announcements/AnnouncementCard.vue | preview": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Announcements/AnnouncementCard.vue | confirmed": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Announcements/AnnouncementCard.vue | canReport": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Announcements/NoticeBanner.vue | notice": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/Announcements/NoticeBanner.vue | preview": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/ChoiceCards.vue | label": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/ChoiceCards.vue | name": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/ChoiceCards.vue | modelValue": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/ChoiceCards.vue | options": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/ChoiceCards.vue | columns": { + "type": "Number", + "required": false, + "validator": false, + "default": 2 + }, + "../../components/DashboardFooter.vue | footer": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/DashboardFooter.vue | locale": { + "type": "String", + "required": false, + "validator": false, + "default": "en" + }, + "../../components/HeaderSearchDropdown.vue | shortcuts": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/HeaderSearchDropdown.vue | fieldSelector": { + "type": "String", + "required": false, + "validator": false, + "default": ".unified-search-input, #unified-search input, .unified-search__input, input.unified-search-menu__input" + }, + "../../components/HealthPingBadge.vue | placementId": { + "type": [ + "Number", + "String" + ], + "required": false, + "validator": false, + "default": null + }, + "../../components/HealthPingBadge.vue | hidden": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/HealthPingBadge.vue | interval": { + "type": "Number", + "required": false, + "validator": false, + "default": 60 + }, + "../../components/LazyMount.vue | eager": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/OrgNavigationItem.vue | node": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/OrgNavigationItem.vue | level": { + "type": "Number", + "required": false, + "validator": false, + "default": 1 + }, + "../../components/OrgNavigationItem.vue | currentUrl": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/PublicDashboardGrid.vue | placements": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/PublicDashboardGrid.vue | embedContext": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/PublicDashboardGrid.vue | readWidget": { + "type": "Function", + "required": false, + "validator": false, + "default": null + }, + "../../components/PublicNewsWidget.vue | placementId": { + "type": [ + "Number", + "String" + ], + "required": true, + "validator": false + }, + "../../components/PublicNewsWidget.vue | readWidget": { + "type": "Function", + "required": true, + "validator": false + }, + "../../components/RuntimeShellSearch.vue | items": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/RuntimeShellSearch.vue | fallbackTarget": { + "type": "String", + "required": false, + "validator": false, + "default": "none" + }, + "../../components/RuntimeShellSearch.vue | placeholder": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/RuntimeShellSearch.vue | shortcuts": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/ScheduledExports/ExportOptionFields.vue | fields": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/ScheduledExports/ExportOptionFields.vue | values": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/ScheduledExports/ExportRunHistory.vue | exportData": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/ScheduledExports/ExportStatus.vue | status": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/TileWidget.vue | tile": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/TileWidget.vue | editMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/TileWidget.vue | removeLocked": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/TileWidget.vue | placementId": { + "type": [ + "Number", + "String" + ], + "required": false, + "validator": false, + "default": null + }, + "../../components/TileWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/TileWidget.vue | healthPingEnabled": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/TileWidget.vue | pingInterval": { + "type": "Number", + "required": false, + "validator": false, + "default": 60 + }, + "../../components/TileWidget.vue | linkTarget": { + "type": "String", + "required": false, + "validator": false, + "default": null + }, + "../../components/TileWidget.vue | defaultLinkTarget": { + "type": "String", + "required": false, + "validator": false, + "default": null + }, + "../../components/WidgetRenderer.vue | widget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/WidgetRenderer.vue | placement": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/WidgetRenderer.vue | editMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/WidgetWrapper.vue | placement": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/WidgetWrapper.vue | widget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/WidgetWrapper.vue | availableWidgets": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/WidgetWrapper.vue | editMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/WidgetWrapper.vue | outstandingAcknowledgement": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/WidgetWrapper.vue | canHideForMe": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/WidgetWrapper.vue | removeLocked": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/WidgetWrapper.vue | embedHref": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Widgets/CalculatedFields/CalculatedValues.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/ConditionalVisibilityEditor.vue | placementId": { + "type": [ + "Number", + "String" + ], + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/ConditionalVisibilityEditor.vue | availableGroups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Widgets/ConditionalVisibilityEditor.vue | ruleMatch": { + "type": "String", + "required": false, + "validator": false, + "default": "any" + }, + "../../components/Widgets/Renderers/ActivityReportWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ActivityReportWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/ActivityReportWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "days": 30 + }, + "fresh": true + }, + "../../components/Widgets/Renderers/AiAssistantWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/AiAssistantWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/AiAssistantWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/AiAssistantWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "agentUuid": "" + }, + "fresh": true + }, + "../../components/Widgets/Renderers/AnnouncementsWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/AnnouncementsWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/AnnouncementsWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "category": "", + "limit": 10 + }, + "fresh": true + }, + "../../components/Widgets/Renderers/AssignedCasesWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/AssignedCasesWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/AssignedCasesWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/AssignedCasesWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "register": "dossiq", + "schema": "case", + "limit": 4 + }, + "fresh": true + }, + "../../components/Widgets/Renderers/AttentionWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/AttentionWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/AttentionWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "limit": 5 + }, + "fresh": true + }, + "../../components/Widgets/Renderers/CalendarWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/CalendarWidget.vue | placementId": { + "type": [ + "Number", + "String" + ], + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/CalendarWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/CalendarWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "internalCalendars": [], + "externalIcsUrls": [], + "viewMode": "agenda", + "daysAhead": 7, + "colorByCalendar": true + }, + "fresh": true + }, + "../../components/Widgets/Renderers/CalendarWidgetForm.vue | calendarsFetcher": { + "type": "Function", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/ChartHost.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ChartHost.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ChartSourceForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/ChartSourceForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ClockWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ClockWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/ClockWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "style": "digital", + "hourFormat": "auto", + "timezone": "", + "showDate": true + }, + "fresh": true + }, + "../../components/Widgets/Renderers/ColleagueActivityWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ColleagueActivityWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/ColleagueActivityWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "limit": 10, + "days": 7 + }, + "fresh": true + }, + "../../components/Widgets/Renderers/CommunitiesWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/CommunitiesWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/CommunitiesWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/CommunitiesWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "title": "", + "onlyPinned": false + }, + "fresh": true + }, + "../../components/Widgets/Renderers/ConnectionsWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ConnectionsWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ConnectionsWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/ConnectionsWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ContainerChild.vue | placement": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/Widgets/Renderers/ContainerChild.vue | editMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/Renderers/ContainerChild.vue | canEditTile": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/Renderers/ContainerWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ContainerWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/ContainerWidget.vue | editMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/Renderers/ContainerWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/ContainerWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "placements": [], + "backgroundColor": "transparent", + "padding": "medium", + "title": "", + "sortBy": "manual" + }, + "fresh": true + }, + "../../components/Widgets/Renderers/FilesWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/FilesWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/IframeWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/IframeWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/IframeWidget.vue | loadTimeoutMs": { + "type": "Number", + "required": false, + "validator": false, + "default": 6000 + }, + "../../components/Widgets/Renderers/IframeWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/IframeWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "url": "", + "title": "", + "height": 400, + "aspect": "none", + "sandbox": [ + "allow-scripts", + "allow-same-origin" + ], + "allowListChecked": false + }, + "fresh": true + }, + "../../components/Widgets/Renderers/ImageWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/ImageWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "url": "", + "alt": "", + "link": "", + "fit": "cover" + }, + "fresh": true + }, + "../../components/Widgets/Renderers/ImageWidgetForm.vue | fileUploadFn": { + "type": "Function", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/LinkButtonHost.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/LinkButtonHost.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/LinkButtonHost.vue | isAdmin": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/Renderers/LinkButtonHost.vue | canEdit": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/Renderers/LiveTileWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/LiveTileWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/LiveTileWidget.vue | readingSource": { + "type": "Function", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/LiveTileWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/LiveTileWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "label": "", + "sourceMode": "url", + "url": "", + "sourceId": "", + "valueExpr": "", + "refresh": 300, + "format": { + "prefix": "", + "suffix": "", + "thousands": false + }, + "badge": { + "thresholds": [] + }, + "linkUrl": "", + "linkTarget": "same-tab" + }, + "fresh": true + }, + "../../components/Widgets/Renderers/NewsWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/NewsWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/NewsWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/NewsWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "feedUrls": [], + "layout": "list", + "itemLimit": 10, + "showThumbnails": true, + "showSummary": true, + "summaryMaxChars": 200, + "dateFormat": "relative", + "metadataFilter": null + }, + "fresh": true + }, + "../../components/Widgets/Renderers/PeriodFieldSelect.vue | register": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Widgets/Renderers/PeriodFieldSelect.vue | schema": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Widgets/Renderers/PeriodFieldSelect.vue | modelValue": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Widgets/Renderers/RecentWorkWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/RecentWorkWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/RecentWorkWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "limit": 6 + }, + "fresh": true + }, + "../../components/Widgets/Renderers/SearchWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/SearchWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/SearchWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/SearchWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "placeholder": "", + "fallbackTarget": "" + }, + "fresh": true + }, + "../../components/Widgets/Renderers/SectionHeadingWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/SectionHeadingWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/SectionHeadingWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "title": "", + "description": "" + }, + "fresh": true + }, + "../../components/Widgets/Renderers/StatsBlockHost.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/StatsBlockHost.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/StatusReportWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/StatusReportWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/StatusReportWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/TileHost.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/TileHost.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/TileHost.vue | editMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/Renderers/VideoHost.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/VideoHost.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/VideoHost.vue | canEdit": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/Renderers/VideoWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/VideoWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/WeatherWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/WeatherWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/WeatherWidget.vue | readingSource": { + "type": "Function", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/WeatherWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/WeatherWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "location": "", + "unitsOverride": "" + }, + "fresh": true + }, + "../../components/Widgets/Renderers/WikiPagesWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/WikiPagesWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/WikiPagesWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/WikiPagesWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "space": "", + "limit": 3 + }, + "fresh": true + }, + "../../components/Widgets/Renderers/WorkPackagesWidget.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/WorkPackagesWidget.vue | content": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Widgets/Renderers/WorkPackagesWidgetForm.vue | editingWidget": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Widgets/Renderers/WorkPackagesWidgetForm.vue | value": { + "type": "Object", + "required": false, + "validator": false, + "default": { + "scope": "mine", + "project": "", + "limit": 4 + }, + "fresh": true + }, + "../../components/Widgets/VisibilityRuleRow.vue | rule": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/Widgets/VisibilityRuleRow.vue | availableGroups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Widgets/VisibilityRuleRow.vue | busy": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/VisibilityRuleRow.vue | isNew": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/WidgetContextMenu.vue | top": { + "type": "Number", + "required": true, + "validator": false + }, + "../../components/Widgets/WidgetContextMenu.vue | left": { + "type": "Number", + "required": true, + "validator": false + }, + "../../components/Widgets/WidgetContextMenu.vue | removeLocked": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/WidgetEditMenu.vue | menuLabel": { + "type": "String", + "required": false, + "validator": false, + "default": "Widget menu" + }, + "../../components/Widgets/WidgetEditMenu.vue | removeLocked": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Widgets/WidgetRowFilter.vue | modelValue": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/ActiveFiltersPanel.vue | clauses": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/ActiveFiltersPanel.vue | labels": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Workspace/ActiveFiltersPanel.vue | widgetNames": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Workspace/CoEditorsBanner.vue | editors": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/DashboardBreadcrumb.vue | dashboard": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/DashboardDiscussion.vue | dashboard": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/DashboardDiscussion.vue | sharedWithMe": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/DashboardDiscussion.vue | currentUserId": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/DashboardEditBar.vue | dashboardName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/DashboardEditBar.vue | columns": { + "type": "Number", + "required": false, + "validator": false, + "default": 12 + }, + "../../components/Workspace/DashboardEditBar.vue | canConfigure": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardLanguageHeading.vue | dashboard": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/DashboardMoreMenu.vue | dashboard": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/DashboardMoreMenu.vue | source": { + "type": "String", + "required": false, + "validator": false, + "default": "user" + }, + "../../components/Workspace/DashboardMoreMenu.vue | userDashboards": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/DashboardMoreMenu.vue | groupDashboards": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/DashboardMoreMenu.vue | sharedDashboards": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/DashboardMoreMenu.vue | defaultUuid": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/DashboardMoreMenu.vue | canEdit": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardMoreMenu.vue | canShare": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardMoreMenu.vue | canDuplicate": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardMoreMenu.vue | canViewReadReceipts": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardMoreMenu.vue | isEditMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardPageHeader.vue | dashboard": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/Workspace/DashboardPageHeader.vue | source": { + "type": "String", + "required": false, + "validator": false, + "default": "user" + }, + "../../components/Workspace/DashboardPageHeader.vue | isDefault": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardPageHeader.vue | permissionLevel": { + "type": "String", + "required": false, + "validator": false, + "default": "full" + }, + "../../components/Workspace/DashboardPageHeader.vue | showsPeriod": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardPageHeader.vue | period": { + "type": "String", + "required": false, + "validator": false, + "default": "month" + }, + "../../components/Workspace/DashboardReactions.vue | dashboardUuid": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/DashboardRowActions.vue | dashboard": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/Workspace/DashboardRowActions.vue | source": { + "type": "String", + "required": true, + "validator": true + }, + "../../components/Workspace/DashboardRowActions.vue | canEdit": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardRowActions.vue | defaultUuid": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/DashboardRowActions.vue | isEditMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardRowActions.vue | activeDashboardId": { + "type": [ + "String", + "Number" + ], + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/DashboardRowActions.vue | canShare": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardRowActions.vue | canEmbed": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardRowActions.vue | buttonType": { + "type": "String", + "required": false, + "validator": false, + "default": "tertiary-no-background" + }, + "../../components/Workspace/DashboardRowActions.vue | iconSize": { + "type": "Number", + "required": false, + "validator": false, + "default": 18 + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | filterFields": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | isOpen": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | groupName": { + "type": "String", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | groupDashboards": { + "type": "Array", + "required": true, + "validator": true + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | userDashboards": { + "type": "Array", + "required": true, + "validator": true + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | activeDashboardId": { + "type": [ + "String", + "Number" + ], + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | allowUserDashboards": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | canEdit": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | defaultUuid": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | isEditMode": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | dashboardQuotaReached": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/DashboardSwitcherSidebar.vue | dashboardQuotaTooltip": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/DetailFilter.vue | fields": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/EditLockBanner.vue | status": { + "type": "String", + "required": true, + "validator": false + }, + "../../components/Workspace/EditLockBanner.vue | holderName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/Workspace/EditLockBanner.vue | expiresIn": { + "type": "Number", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/EditLockBanner.vue | isAdmin": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/FilterBreadcrumb.vue | hierarchies": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/FilterBreadcrumb.vue | clauses": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/FilterBreadcrumb.vue | labels": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/Workspace/HiddenWidgetsControl.vue | hiddenPlacements": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/HiddenWidgetsControl.vue | availableWidgets": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/InstallBanner.vue | kiosk": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/InstallBanner.vue | isPublic": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/LaunchpadMoreMenu.vue | dashboards": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/LaunchpadMoreMenu.vue | settings": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/LaunchpadMoreMenu.vue | actions": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/LaunchpadMoreMenuItem.vue | item": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/Workspace/PhoneHiddenNotice.vue | titles": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/config/DetailsTab.vue | dashboardUuid": { + "type": "String", + "required": true, + "validator": false + }, + "../../components/Workspace/config/ExportsTab.vue | subjects": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/Workspace/config/ExportsTab.vue | defaultSubject": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/config/LanguagesTab.vue | dashboardUuid": { + "type": "String", + "required": true, + "validator": false + }, + "../../components/Workspace/config/PublicationTab.vue | dashboard": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/config/SharingConversation.vue | dashboard": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/config/SharingConversation.vue | shared": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/Workspace/config/SharingEmbedTokens.vue | dashboard": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/Workspace/config/VersionsTab.vue | dashboardUuid": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/admin/AdminDemoData.vue | choice": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/admin/AdminSettings.vue | tab": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/admin/AnnouncementEditorsPolicy.vue | groups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/DashboardSharingPolicy.vue | groups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/GroupPriorityOrder.vue | initialActive": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/OrgNavigationEditor.vue | groups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/OrgNavigationEditorRow.vue | node": { + "type": "Object", + "required": true, + "validator": false + }, + "../../components/admin/OrgNavigationEditorRow.vue | level": { + "type": "Number", + "required": false, + "validator": false, + "default": 1 + }, + "../../components/admin/OrgNavigationEditorRow.vue | index": { + "type": "Number", + "required": true, + "validator": false + }, + "../../components/admin/OrgNavigationEditorRow.vue | siblings": { + "type": "Array", + "required": true, + "validator": false + }, + "../../components/admin/OrgNavigationEditorRow.vue | maxDepth": { + "type": "Number", + "required": false, + "validator": false, + "default": 3 + }, + "../../components/admin/OrgNavigationEditorRow.vue | groups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/TileClickReport.vue | period": { + "type": "String", + "required": false, + "validator": false, + "default": "30d" + }, + "../../components/admin/embed/EmbedTokenForm.vue | token": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../components/admin/embed/EmbedTokenForm.vue | dashboards": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/embed/EmbedTokenForm.vue | themes": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/embed/EmbedTokenForm.vue | defaults": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/admin/embed/EmbedTokenForm.vue | saving": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../components/admin/embed/EmbedTokenManager.vue | defaults": { + "type": "Object", + "required": false, + "validator": false, + "default": {}, + "fresh": true + }, + "../../components/admin/embed/EmbedUsageReport.vue | tokenId": { + "type": "String", + "required": true, + "validator": false + }, + "../../components/admin/embed/EmbedUsageReport.vue | tokenName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../components/admin/tabs/AppCatalogueTab.vue | groups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/tabs/OrgNavigationTab.vue | groups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/tabs/SharingTab.vue | groups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../components/admin/tabs/SharingTab.vue | configuredGroups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../dialogs/CreateGroupDashboardModal.vue | group": { + "type": "Object", + "required": true, + "validator": true + }, + "../../dialogs/DeleteDashboardDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/DeleteDashboardDialog.vue | name": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../dialogs/DeleteDashboardDialog.vue | childCount": { + "type": "Number", + "required": false, + "validator": false, + "default": 0 + }, + "../../dialogs/DeleteTenantThemeDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/DeleteTenantThemeDialog.vue | name": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../dialogs/DeleteTenantThemeDialog.vue | tokenCount": { + "type": "Number", + "required": false, + "validator": false, + "default": 0 + }, + "../../dialogs/GroupDashboardRenameDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/GroupDashboardRenameDialog.vue | currentName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../dialogs/KioskPlaylistDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/KioskPlaylistDialog.vue | playlist": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../dialogs/KioskPlaylistDialog.vue | dashboards": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../dialogs/ManageGroupDashboardsModal.vue | group": { + "type": "Object", + "required": true, + "validator": true + }, + "../../dialogs/OfficeFileDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/OfficeFileDialog.vue | title": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../dialogs/OfficeFileDialog.vue | defaultName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../dialogs/OfficeFileDialog.vue | busy": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../dialogs/PublicSharePasswordDialog.vue | error": { + "type": "String", + "required": false, + "validator": false, + "default": null + }, + "../../dialogs/PublicSharePasswordDialog.vue | loading": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../dialogs/ReadConfirmationDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/ReadConfirmationDialog.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../dialogs/RevokeEmbedTokenDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/RevokeEmbedTokenDialog.vue | name": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../dialogs/RoleLayoutDefaultEditorDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/RoleLayoutDefaultEditorDialog.vue | row": { + "type": "Object", + "required": true, + "validator": false + }, + "../../dialogs/RoleLayoutDefaultEditorDialog.vue | saving": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../dialogs/ShippedTemplateUpdateDialog.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../dialogs/ShippedTemplateUpdateDialog.vue | shipped": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/AcknowledgementReportModal.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/AcknowledgementReportModal.vue | announcementKey": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/AcknowledgementReportModal.vue | announcementUuid": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/AcknowledgementReportModal.vue | title": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/AcknowledgementReportModal.vue | dashboardName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/AddTilesModal.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/AddTilesModal.vue | catalogueApps": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/AddTilesModal.vue | discoveredApps": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/AddTilesModal.vue | officeTiles": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/AddTilesModal.vue | placements": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/AddTilesModal.vue | requestAppFn": { + "type": "Function", + "required": false, + "validator": false, + "default": null + }, + "../../modals/AddTilesModal.vue | addTiles": { + "type": "Function", + "required": true, + "validator": false + }, + "../../modals/BookmarkImportModal.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/BookmarkImportModal.vue | importBookmarks": { + "type": "Function", + "required": true, + "validator": false + }, + "../../modals/BookmarkImportModal.vue | initialFile": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/DashboardConfigModal.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/DashboardConfigModal.vue | dashboard": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/DashboardConfigModal.vue | canDelete": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/DashboardConfigModal.vue | mode": { + "type": "String", + "required": false, + "validator": true, + "default": "edit" + }, + "../../modals/DashboardConfigModal.vue | defaultUuid": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/DashboardConfigModal.vue | parentOptions": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/DashboardConfigModal.vue | saveError": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/DashboardConfigModal.vue | canManagePublication": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/DashboardConfigModal.vue | canScheduleExports": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/DashboardConfigModal.vue | canViewVersions": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/DashboardConfigModal.vue | exportSubjects": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/DashboardConfigModal.vue | initialTab": { + "type": "String", + "required": false, + "validator": true, + "default": "general" + }, + "../../modals/PreviewModal.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../modals/PreviewModal.vue | exportData": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/RolePermissionEditorModal.vue | row": { + "type": "Object", + "required": true, + "validator": false + }, + "../../modals/RolePermissionEditorModal.vue | allowedWidgetsCsv": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/RolePermissionEditorModal.vue | deniedWidgetsCsv": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/RolePermissionEditorModal.vue | saving": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/RunDetailModal.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../modals/RunDetailModal.vue | exportData": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/RunDetailModal.vue | run": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/ScheduledExportModal.vue | open": { + "type": "Boolean", + "required": true, + "validator": false + }, + "../../modals/ScheduledExportModal.vue | exportData": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/ScheduledExportModal.vue | subjects": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/ScheduledExportModal.vue | defaultSubject": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/TemplateEditorModal.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/TemplateEditorModal.vue | template": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/TemplateResyncModal.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/TemplateResyncModal.vue | template": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/TileEditor.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/TileEditor.vue | tile": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/TileEditor.vue | dashboardName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/TileEditor.vue | groupName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/TileEditor.vue | groupSort": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/TileEditor.vue | inGroup": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/VisibilityRulesModal.vue | placementId": { + "type": [ + "Number", + "String" + ], + "required": false, + "validator": false, + "default": null + }, + "../../modals/VisibilityRulesModal.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/VisibilityRulesModal.vue | availableGroups": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/VisibilityRulesModal.vue | widgetTitle": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/VisibilityRulesModal.vue | dashboardName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/VisibilityRulesModal.vue | ruleMatch": { + "type": "String", + "required": false, + "validator": false, + "default": "any" + }, + "../../modals/WidgetMovePanel.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/WidgetMovePanel.vue | placement": { + "type": "Object", + "required": false, + "validator": false, + "default": null + }, + "../../modals/WidgetMovePanel.vue | allPlacements": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/WidgetMovePanel.vue | gridColumns": { + "type": "Number", + "required": false, + "validator": false, + "default": 12 + }, + "../../modals/WidgetPickerModal.vue | open": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../modals/WidgetPickerModal.vue | widgets": { + "type": "Array", + "required": true, + "validator": false + }, + "../../modals/WidgetPickerModal.vue | placedWidgetIds": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/WidgetPickerModal.vue | discoveredApps": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/WidgetPickerModal.vue | placedAppIds": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/WidgetPickerModal.vue | customTypes": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/WidgetPickerModal.vue | catalogueApps": { + "type": "Array", + "required": false, + "validator": false, + "default": [], + "fresh": true + }, + "../../modals/WidgetPickerModal.vue | dashboardName": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../modals/WidgetPickerModal.vue | allowedWidgets": { + "type": "Array", + "required": false, + "validator": false, + "default": null + }, + "../../modals/WidgetPickerModal.vue | requestAppFn": { + "type": "Function", + "required": false, + "validator": false, + "default": null + }, + "../../views/AdminPage.vue | tab": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../views/AdminSettingsRedirect.vue | tab": { + "type": "String", + "required": false, + "validator": false, + "default": "" + }, + "../../views/DashboardPublicShareView.vue | token": { + "type": "String", + "required": true, + "validator": false + }, + "../../views/DashboardPublicShareView.vue | startPage": { + "type": "Boolean", + "required": false, + "validator": false, + "default": false + }, + "../../views/KioskPlayerView.vue | token": { + "type": "String", + "required": true, + "validator": false + } +} diff --git a/src/constants/__tests__/propDefinitions.golden.spec.js b/src/constants/__tests__/propDefinitions.golden.spec.js new file mode 100644 index 000000000..8bd660c8b --- /dev/null +++ b/src/constants/__tests__/propDefinitions.golden.spec.js @@ -0,0 +1,91 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for the props contract of every component under src/: per + * prop its type, whether it is required, and its default (a factory is + * called twice, recording the value and whether the two calls give separate + * objects). Compared with fixtures/propDefinitions.golden.json case by case. + * Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it } from 'vitest' + +const FIXTURE = path.resolve(__dirname, 'fixtures/propDefinitions.golden.json') + +const COMPONENTS = import.meta.glob(['../../**/*.vue', '!../../**/__tests__/**']) + +/** + * The type of a prop as names. + * + * @param {unknown} type The prop's `type` option. + * @return {Array<string>|string|null} The constructor names. + */ +function typeNames(type) { + if (Array.isArray(type)) { + return type.map((entry) => entry.name) + } + return type ? type.name : null +} + +/** + * The recorded contract of one prop definition. + * + * @param {object|Function|Array} definition The prop definition. + * @return {object} Its type, required flag, validator and default. + */ +function contractOf(definition) { + if (typeof definition === 'function' || Array.isArray(definition)) { + return { type: typeNames(definition) } + } + if (definition === null) { + return { type: null } + } + const contract = { + type: typeNames(definition.type), + required: definition.required === true, + validator: typeof definition.validator === 'function', + } + if (!('default' in definition)) { + return contract + } + const value = definition.default + if (typeof value === 'function' && definition.type !== Function) { + const first = value() + const second = value() + contract.default = first === undefined ? '(undefined)' : first + contract.fresh = + typeof first === 'object' && first !== null ? first !== second : 'n/a' + } else { + contract.default = value === undefined ? '(undefined)' : value + } + return contract +} + +describe('component props (golden)', () => { + it('matches the recorded contracts case by case', async () => { + const actual = {} + for (const [file, load] of Object.entries(COMPONENTS).sort()) { + const props = (await load()).default?.props + if (Array.isArray(props)) { + actual[file] = props + continue + } + for (const [name, definition] of Object.entries(props || {})) { + actual[`${file} | ${name}`] = JSON.parse( + JSON.stringify(contractOf(definition)), + ) + } + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const [name, value] of Object.entries(expected)) { + expect(actual[name], name).toEqual(value) + } + }) +}) diff --git a/src/constants/__tests__/widgetRegistry.spec.js b/src/constants/__tests__/widgetRegistry.spec.js index 0bfca9f6b..5597484f7 100644 --- a/src/constants/__tests__/widgetRegistry.spec.js +++ b/src/constants/__tests__/widgetRegistry.spec.js @@ -11,6 +11,7 @@ * responsibility and are tested there, not re-frozen here. */ +import { loadLazyComponent } from '@conduction/nextcloud-vue' import { beforeEach, describe, expect, it } from 'vitest' beforeEach(() => { @@ -153,8 +154,8 @@ describe('widgetRegistry — news is LaunchPad-owned', () => { const { getWidgetTypeEntry } = await import('../widgetRegistry.js') const entry = getWidgetTypeEntry('news') expect(entry).toBeTruthy() - expect(entry.renderer?.name).toBe('NewsWidget') - expect(entry.form?.name).toBe('NewsWidgetForm') + expect((await loadLazyComponent(entry.renderer))?.name).toBe('NewsWidget') + expect((await loadLazyComponent(entry.form))?.name).toBe('NewsWidgetForm') }) it('keeps the content shape a pre-move placement was authored with', async () => { @@ -176,3 +177,39 @@ describe('widgetRegistry — news is LaunchPad-owned', () => { expect(listWidgetTypes()).toContain('news') }) }) + +describe('offeredForViewer (wiki-widget REQ-WIKI-004)', () => { + it('offers a type without an app always, and a type with one only when it is enabled for the viewer', async () => { + const { offeredForViewer, getWidgetTypeEntry } = await import('../widgetRegistry.js') + expect(offeredForViewer({ displayName: 'Clock' }, {})).toBe(true) + expect(offeredForViewer(getWidgetTypeEntry('wiki-pages'), {})).toBe(false) + expect(offeredForViewer(getWidgetTypeEntry('wiki-pages'), { openregister: false })).toBe(false) + expect(offeredForViewer(getWidgetTypeEntry('wiki-pages'), { openregister: true })).toBe(true) + }) +}) + +describe('section-heading (REQ-WDG-031)', () => { + it('is offered to everyone as "Section heading" with the format-header-1 icon', async () => { + const { getWidgetTypeEntry, listWidgetTypes, offeredForViewer } = await import('../widgetRegistry.js') + expect(listWidgetTypes()).toContain('section-heading') + const entry = getWidgetTypeEntry('section-heading') + expect(entry.icon).toBe('FormatHeader1') + expect((await loadLazyComponent(entry.renderer)).name).toBe('SectionHeadingWidget') + expect((await loadLazyComponent(entry.form)).name).toBe('SectionHeadingWidgetForm') + expect(offeredForViewer(entry, {})).toBe(true) + }) + + it('may take one grid row', async () => { + const { getWidgetTypeEntry } = await import('../widgetRegistry.js') + expect(getWidgetTypeEntry('section-heading').minHeight).toBe(1) + }) +}) + +describe('phone readiness (REQ-MRA-007)', () => { + it('marks the assistant as not ready for a phone and leaves other types shown', async () => { + const { getWidgetTypeEntry } = await import('../widgetRegistry.js') + const { isPhoneReady } = await import('../../utils/phoneHiddenWidgets.js') + expect(isPhoneReady(getWidgetTypeEntry('ai-assistant'))).toBe(false) + expect(isPhoneReady(getWidgetTypeEntry('clock'))).toBe(true) + }) +}) diff --git a/src/constants/propDefinitions.js b/src/constants/propDefinitions.js new file mode 100644 index 000000000..5ace44957 --- /dev/null +++ b/src/constants/propDefinitions.js @@ -0,0 +1,104 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Prop definitions that many components declare the same way. + * + * Every widget renderer takes `content` and `placement`, every widget form + * `editingWidget` and `value`, and most dialogs an `open` flag, so the same + * definitions recur across the app. Vue copies a prop definition when it + * normalises a component's props, so one definition object can serve many + * components. + */ + +/** + * An object prop that defaults to a fresh shallow copy of `defaults`. + * + * @param {object} defaults The default's keys and values. + * @return {{type: ObjectConstructor, default: function(): object}} The prop definition. + * @spec openspec/specs/widgets/spec.md + */ +export function objectProp(defaults) { + return { + type: Object, + default: () => ({ ...defaults }), + } +} + +/** + * An object prop that defaults to a fresh empty object. + * + * @type {{type: ObjectConstructor, default: function(): object}} + */ +export const OBJECT_PROP = objectProp({}) + +/** + * An object prop that defaults to null, such as the placement being edited + * (null in create mode). + * + * @type {{type: ObjectConstructor, default: null}} + */ +export const NULLABLE_OBJECT_PROP = { + type: Object, + default: null, +} + +/** + * A required object prop. + * + * @type {{type: ObjectConstructor, required: true}} + */ +export const REQUIRED_OBJECT_PROP = { + type: Object, + required: true, +} + +/** + * A list prop that defaults to a fresh empty array. + * + * @type {{type: ArrayConstructor, default: function(): Array}} + */ +export const LIST_PROP = { + type: Array, + default: () => [], +} + +/** + * A text prop that defaults to the empty string. + * + * @type {{type: StringConstructor, default: string}} + */ +export const TEXT_PROP = { + type: String, + default: '', +} + +/** + * A required text prop. + * + * @type {{type: StringConstructor, required: true}} + */ +export const REQUIRED_TEXT_PROP = { + type: String, + required: true, +} + +/** + * A flag prop that defaults to false. + * + * @type {{type: BooleanConstructor, default: boolean}} + */ +export const FLAG_PROP = { + type: Boolean, + default: false, +} + +/** + * A required flag prop, such as a dialog's `open`. + * + * @type {{type: BooleanConstructor, required: true}} + */ +export const REQUIRED_FLAG_PROP = { + type: Boolean, + required: true, +} diff --git a/src/constants/widgetRegistry.js b/src/constants/widgetRegistry.js index 5effd6b88..2e03daecf 100644 --- a/src/constants/widgetRegistry.js +++ b/src/constants/widgetRegistry.js @@ -19,6 +19,10 @@ * CnChartWidget's apexcharts props) * - `stats-block` → StatsBlockHost (maps `content` onto CnStatsBlockWidget's * separate props) + * - `tile` → TileHost (a `create` office tile opens the new-file + * dialog; every other tile renders through CnDashTileWidget) + * - `video` → VideoHost (resolves a Nextcloud-file source's streaming + * URL for the viewer, REQ-VID-006) * `files` keeps the communal CnFilesWidget renderer — its launchpad backend * `apiBase` is injected by WidgetRenderer.rendererProps, not the registry. * @@ -39,7 +43,6 @@ import { // Forms for types the communal registry leaves `form: null` (renderer-only // in OpenBuild) but which LaunchPad configures — they rely on LaunchPad- // injected context (NC widget catalog, people API, calendar/graphql sources). - CnCalendarWidgetForm as CalendarForm, getDefaultContent as cnGetDefaultContent, getWidgetTypeEntry as cnGetWidgetTypeEntry, listWidgetTypes as cnListWidgetTypes, @@ -48,11 +51,66 @@ import { // registration guard below. CnNcWidgetWidget, dashboardWidgetRegistry, + lazyComponent, CnNcDashboardWidgetForm as NcDashboardForm, CnPeopleWidgetForm as PeopleForm, registerDashboardWidget, CnSpendAnalyticsWidgetForm as SpendAnalyticsForm, } from '@conduction/nextcloud-vue' + +// Renderers and forms load with the first widget of their type, not with the +// dashboard bundle. +const ActivityReportWidget = lazyComponent(() => import('../components/Widgets/Renderers/ActivityReportWidget.vue'), 'ActivityReportWidget') +const ActivityReportWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/ActivityReportWidgetForm.vue'), 'ActivityReportWidgetForm') +const AiAssistantWidget = lazyComponent(() => import('../components/Widgets/Renderers/AiAssistantWidget.vue'), 'AiAssistantWidget') +const AiAssistantWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/AiAssistantWidgetForm.vue'), 'AiAssistantWidgetForm') +const AnnouncementsWidget = lazyComponent(() => import('../components/Widgets/Renderers/AnnouncementsWidget.vue'), 'AnnouncementsWidget') +const AnnouncementsWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/AnnouncementsWidgetForm.vue'), 'AnnouncementsWidgetForm') +const AssignedCasesWidget = lazyComponent(() => import('../components/Widgets/Renderers/AssignedCasesWidget.vue'), 'AssignedCasesWidget') +const AssignedCasesWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/AssignedCasesWidgetForm.vue'), 'AssignedCasesWidgetForm') +const ConnectionsWidget = lazyComponent(() => import('../components/Widgets/Renderers/ConnectionsWidget.vue'), 'ConnectionsWidget') +const ConnectionsWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/ConnectionsWidgetForm.vue'), 'ConnectionsWidgetForm') +const AttentionWidget = lazyComponent(() => import('../components/Widgets/Renderers/AttentionWidget.vue'), 'AttentionWidget') +const AttentionWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/AttentionWidgetForm.vue'), 'AttentionWidgetForm') +const ChartHost = lazyComponent(() => import('../components/Widgets/Renderers/ChartHost.vue'), 'ChartHost') +const ChartSourceForm = lazyComponent(() => import('../components/Widgets/Renderers/ChartSourceForm.vue'), 'ChartSourceForm') +const ClockWidget = lazyComponent(() => import('../components/Widgets/Renderers/ClockWidget.vue'), 'ClockWidget') +const ClockWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/ClockWidgetForm.vue'), 'ClockWidgetForm') +const RecentWorkWidget = lazyComponent(() => import('../components/Widgets/Renderers/RecentWorkWidget.vue'), 'RecentWorkWidget') +const RecentWorkWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/RecentWorkWidgetForm.vue'), 'RecentWorkWidgetForm') +const ColleagueActivityWidget = lazyComponent(() => import('../components/Widgets/Renderers/ColleagueActivityWidget.vue'), 'ColleagueActivityWidget') +const ColleagueActivityWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/ColleagueActivityWidgetForm.vue'), 'ColleagueActivityWidgetForm') +const CommunitiesWidget = lazyComponent(() => import('../components/Widgets/Renderers/CommunitiesWidget.vue'), 'CommunitiesWidget') +const CommunitiesWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/CommunitiesWidgetForm.vue'), 'CommunitiesWidgetForm') +const ContainerWidget = lazyComponent(() => import('../components/Widgets/Renderers/ContainerWidget.vue'), 'ContainerWidget') +const ContainerWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/ContainerWidgetForm.vue'), 'ContainerWidgetForm') +const IframeWidget = lazyComponent(() => import('../components/Widgets/Renderers/IframeWidget.vue'), 'IframeWidget') +const IframeWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/IframeWidgetForm.vue'), 'IframeWidgetForm') +const LinkButtonWidget = lazyComponent(() => import('../components/Widgets/Renderers/LinkButtonHost.vue'), 'LinkButtonWidget') +const LiveTileWidget = lazyComponent(() => import('../components/Widgets/Renderers/LiveTileWidget.vue'), 'LiveTileWidget') +const CalendarWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/CalendarWidgetForm.vue'), 'CalendarWidgetForm') +const ImageWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/ImageWidgetForm.vue'), 'ImageWidgetForm') +const LiveTileWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/LiveTileWidgetForm.vue'), 'LiveTileWidgetForm') +const NewsWidget = lazyComponent(() => import('../components/Widgets/Renderers/NewsWidget.vue'), 'NewsWidget') +const NewsWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/NewsWidgetForm.vue'), 'NewsWidgetForm') +const SearchWidget = lazyComponent(() => import('../components/Widgets/Renderers/SearchWidget.vue'), 'SearchWidget') +const SearchWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/SearchWidgetForm.vue'), 'SearchWidgetForm') +// `section-heading` — "Tussenkop": a full-width heading with one line of +// explanation over the widgets or tiles that follow it (REQ-WDG-031). +const SectionHeadingWidget = lazyComponent(() => import('../components/Widgets/Renderers/SectionHeadingWidget.vue'), 'SectionHeadingWidget') +const SectionHeadingWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/SectionHeadingWidgetForm.vue'), 'SectionHeadingWidgetForm') +const StatsBlockHost = lazyComponent(() => import('../components/Widgets/Renderers/StatsBlockHost.vue'), 'StatsBlockHost') +const StatusReportWidget = lazyComponent(() => import('../components/Widgets/Renderers/StatusReportWidget.vue'), 'StatusReportWidget') +const StatusReportWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/StatusReportWidgetForm.vue'), 'StatusReportWidgetForm') +const TileHost = lazyComponent(() => import('../components/Widgets/Renderers/TileHost.vue'), 'TileHost') +const VideoHost = lazyComponent(() => import('../components/Widgets/Renderers/VideoHost.vue'), 'VideoHost') +const VideoWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/VideoWidgetForm.vue'), 'VideoWidgetForm') +const WeatherWidget = lazyComponent(() => import('../components/Widgets/Renderers/WeatherWidget.vue'), 'WeatherWidget') +const WeatherWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/WeatherWidgetForm.vue'), 'WeatherWidgetForm') +const WikiPagesWidget = lazyComponent(() => import('../components/Widgets/Renderers/WikiPagesWidget.vue'), 'WikiPagesWidget') +const WikiPagesWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/WikiPagesWidgetForm.vue'), 'WikiPagesWidgetForm') +const WorkPackagesWidget = lazyComponent(() => import('../components/Widgets/Renderers/WorkPackagesWidget.vue'), 'WorkPackagesWidget') +const WorkPackagesWidgetForm = lazyComponent(() => import('../components/Widgets/Renderers/WorkPackagesWidgetForm.vue'), 'WorkPackagesWidgetForm') // `clock` and `weather` — LaunchPad-only "ambient tile" widget types with no // communal nc-vue equivalent (openspec/specs/clock-weather-widgets/spec.md). Both // self-register into the shared `dashboardWidgetRegistry` below, exactly @@ -62,38 +120,32 @@ import { // `ai-assistant` — ask Hermiq about the dashboard (search-ai-dashboard-assistant, // openspec/specs/launchpad-ai-dashboard-assistant). Same LaunchPad-only // registration pattern as `clock`/`weather`. -import AiAssistantWidget from '../components/Widgets/Renderers/AiAssistantWidget.vue' -import AiAssistantWidgetForm from '../components/Widgets/Renderers/AiAssistantWidgetForm.vue' -import ChartHost from '../components/Widgets/Renderers/ChartHost.vue' -import ClockWidget from '../components/Widgets/Renderers/ClockWidget.vue' -import ClockWidgetForm from '../components/Widgets/Renderers/ClockWidgetForm.vue' -import ContainerWidget from '../components/Widgets/Renderers/ContainerWidget.vue' +// `assigned-cases` — the viewer's open cases from an OpenRegister register, +// dossiq's by default (openspec/changes/assigned-cases-widget). +// `pie-chart` and `graph` — presets of the shared chart stack (ChartHost over +// CnChartWidget) with a source form for a register query or entered values +// (openspec/changes/chart-presets). +// `communities` — the open Talk conversations the viewer may join +// (openspec/changes/engagement-communities). Same LaunchPad-only registration +// pattern as `clock`/`weather`. // `iframe` — embeds an admin-allow-listed external URL in a sandboxed // frame, with a client-side graceful-degradation fallback for targets that // refuse framing (REQ-IFRAME-001..004, openspec/specs/iframe-embed-widget). // Same LaunchPad-only registration pattern as `clock`/`weather`/`livetile`. -import IframeWidget from '../components/Widgets/Renderers/IframeWidget.vue' -import IframeWidgetForm from '../components/Widgets/Renderers/IframeWidgetForm.vue' // LaunchPad-specific host wrappers (app-side orchestration, NOT generic // dashboard widgets — see docs/migration/widget-library-to-ncvue.md). -import LinkButtonWidget from '../components/Widgets/Renderers/LinkButtonHost.vue' // `livetile` — server-fetched, ICache-cached data-bound tile // (REQ-LIVETILE-001..005, openspec/specs/live-data-tile-widget/spec.md). Same // LaunchPad-only registration pattern as `clock`/`weather`. -import LiveTileWidget from '../components/Widgets/Renderers/LiveTileWidget.vue' -import LiveTileWidgetForm from '../components/Widgets/Renderers/LiveTileWidgetForm.vue' // `news` — moved out of nc-vue, whose renderer had no way to fetch a feed. // LaunchPad owns the feed path, so it owns the widget. -import NewsWidget from '../components/Widgets/Renderers/NewsWidget.vue' -import NewsWidgetForm from '../components/Widgets/Renderers/NewsWidgetForm.vue' // `search` — the quick-search / launcher bar, formerly runtime-shell chrome // (openspec/specs/tile-quick-search). Registered below like the other // LaunchPad-only types. -import SearchWidget from '../components/Widgets/Renderers/SearchWidget.vue' -import SearchWidgetForm from '../components/Widgets/Renderers/SearchWidgetForm.vue' -import StatsBlockHost from '../components/Widgets/Renderers/StatsBlockHost.vue' -import WeatherWidget from '../components/Widgets/Renderers/WeatherWidget.vue' -import WeatherWidgetForm from '../components/Widgets/Renderers/WeatherWidgetForm.vue' +// `wiki-pages` — search, favourites and recent pages of the wiki, read through +// OpenRegister's XWiki integration (openspec/changes/wiki-widget). +// `work-packages` — open OpenProject work packages through the official +// integration (openspec/changes/work-packages-widget). /** * @typedef {object} WidgetRegistryEntry @@ -103,6 +155,7 @@ import WeatherWidgetForm from '../components/Widgets/Renderers/WeatherWidgetForm * @property {string} displayName Human-readable type name for the type picker * @property {string} icon Material Design icon name used in the type picker * @property {{graphql?: string[]}} [requires] Soft runtime-source declaration for cross-app widgets (REQ-SAW-001). NEVER a `manifest.dependencies` entry. + * @property {string} [requiresApp] The app the widget reads through; the picker offers the type only when the initial state's `integrationApps` says it is enabled for the viewer. */ /** @@ -116,8 +169,21 @@ const RENDERER_OVERRIDES = { container: ContainerWidget, chart: ChartHost, 'stats-block': StatsBlockHost, + // integrations-office-tiles: a `create` tile opens the new-file dialog; + // every other tile still renders through CnDashTileWidget. + tile: TileHost, + // REQ-VID-006: a Nextcloud-file video is resolved for its viewer first. + video: VideoHost, } +/** + * Communal types LaunchPad offers although the app-dashboard set leaves them + * out: the map (board LpManagement, "Public space reports on the map"). + * + * @type {string[]} + */ +const EXTRA_TYPES = ['map'] + /** * Types whose form LaunchPad supplies even though the communal entry is * `form: null` (renderer-only in OpenBuild). The forms need LaunchPad-injected @@ -126,10 +192,17 @@ const RENDERER_OVERRIDES = { * @type {Record<string, object>} */ const FORM_OVERRIDES = { - calendar: CalendarForm, + // widget-content-forms-board-sync (REQ-CAL-020, REQ-IMG-020): the content + // forms as board LpWidgetInstellen draws them. + calendar: CalendarWidgetForm, + image: ImageWidgetForm, people: PeopleForm, 'spend-analytics': SpendAnalyticsForm, 'nc-widget': NcDashboardForm, + // launcher-tile-sorting: the communal fields plus "Sort tiles". + container: ContainerWidgetForm, + // REQ-VID-005: the URL is checked by the parse endpoint. + video: VideoWidgetForm, } // The shared bundle (beta.155) exports CnNcWidgetWidget but its self- @@ -166,6 +239,71 @@ registerDashboardWidget('ai-assistant', { }, displayName: 'Assistant', icon: 'RobotOutline', + // The chat panel needs a wide screen: board LpMobiel names "Assistent" + // among the widgets a phone hides (REQ-MRA-007). + mobileReady: false, +}) + +// `attention`: "First today", the ranked list of what the user's apps say +// needs attention (openspec/specs/attention-feed). LaunchPad-only: it reads +// LaunchPad's own sources endpoint. Same registration pattern as `clock`. +registerDashboardWidget('attention', { + renderer: AttentionWidget, + form: AttentionWidgetForm, + defaultContent: { + limit: 5, + }, + displayName: 'First today', + icon: 'AlertCircleOutline', +}) + +// `colleague-activity`: what colleagues did recently, filtered server-side to +// what the reader may see (dashboards-and-who-may-see-them REQ-DWMS-007). +registerDashboardWidget('colleague-activity', { + renderer: ColleagueActivityWidget, + form: ColleagueActivityWidgetForm, + defaultContent: { + limit: 10, + days: 7, + }, + displayName: 'Colleague activity', + icon: 'AccountMultipleOutline', +}) + +// `recent-work`: "Verder waar u was" on LpVandaag, the reader's own recent +// work from the Activity app. +registerDashboardWidget('recent-work', { + renderer: RecentWorkWidget, + form: RecentWorkWidgetForm, + defaultContent: { + limit: 6, + }, + displayName: 'Recent work', + icon: 'History', +}) + +// `activity-report`: a person's activity per type and per day, with the purpose +// shown whenever it is about a named person; the server gates who may read whom +// and logs every such read (dashboards-and-who-may-see-them REQ-DWMS-005/006). +registerDashboardWidget('activity-report', { + renderer: ActivityReportWidget, + form: ActivityReportWidgetForm, + defaultContent: { + days: 30, + }, + displayName: 'Activity report', + icon: 'CalendarMonthOutline', +}) + +// `status-report`: a dated status report on one body of work, prefilled by the +// product and kept with the person's rating and summary; the kept report says +// which values were computed and which were written (REQ-DWMS-004). +registerDashboardWidget('status-report', { + renderer: StatusReportWidget, + form: StatusReportWidgetForm, + defaultContent: {}, + displayName: 'Status report', + icon: 'ClipboardTextOutline', }) registerDashboardWidget('clock', { @@ -183,6 +321,17 @@ registerDashboardWidget('clock', { // `weather` — server-fetched, ICache-cached ambient tile (REQ-WEATHER- // 001..003). Same LaunchPad-only registration pattern as `clock`. +registerDashboardWidget('communities', { + renderer: CommunitiesWidget, + form: CommunitiesWidgetForm, + defaultContent: { + title: '', + onlyPinned: false, + }, + displayName: 'Communities', + icon: 'AccountGroupOutline', +}) + registerDashboardWidget('weather', { renderer: WeatherWidget, form: WeatherWidgetForm, @@ -253,6 +402,132 @@ registerDashboardWidget('search', { icon: 'Magnify', }) +// REQ-WDG-031: "Tussenkop" of boards LpIntranet and LpWerkplek, a heading on +// the page ground; the label widget's group heading has no line of +// explanation, so this is a type of its own. +registerDashboardWidget('section-heading', { + renderer: SectionHeadingWidget, + form: SectionHeadingWidgetForm, + defaultContent: { + title: '', + description: '', + }, + displayName: 'Section heading', + icon: 'FormatHeader1', + // One row, as the boards draw it. Under the grid's two-row minimum a + // heading seeded one row high grew into the tiles below it, and the grid + // moved it under every other widget. + minHeight: 1, +}) + +// wiki-widget REQ-WIKI-001..004: the wiki through OpenRegister's XWiki +// integration; offered only where OpenRegister is enabled for the viewer. +registerDashboardWidget('wiki-pages', { + renderer: WikiPagesWidget, + form: WikiPagesWidgetForm, + defaultContent: { + space: '', + limit: 3, + }, + displayName: 'Wiki', + icon: 'BookOpenPageVariantOutline', + requiresApp: 'openregister', +}) + +// work-packages-widget REQ-WP-001..004: open OpenProject work packages, read +// through integration_openproject with the viewer's own token. +registerDashboardWidget('work-packages', { + renderer: WorkPackagesWidget, + form: WorkPackagesWidgetForm, + defaultContent: { + scope: 'mine', + project: '', + limit: 4, + }, + displayName: 'My work packages', + icon: 'ClipboardCheckOutline', + requiresApp: 'integration_openproject', +}) + +// assigned-cases-widget REQ-CASES-001..004: the viewer's open cases, deadline +// first, with counts per status; offered and shown only where dossiq is. +registerDashboardWidget('assigned-cases', { + renderer: AssignedCasesWidget, + form: AssignedCasesWidgetForm, + defaultContent: { + register: 'dossiq', + schema: 'case', + limit: 4, + }, + displayName: 'My cases', + icon: 'BriefcaseOutline', + requiresApp: 'dossiq', +}) + +// dashboard-connections-widget REQ-LP-CONN-005: the connections the widgets +// on this dashboard use, with the state integriq holds; offered only with integriq. +registerDashboardWidget('connections', { + renderer: ConnectionsWidget, + form: ConnectionsWidgetForm, + defaultContent: {}, + displayName: 'Connections of this dashboard', + icon: 'PowerPlugOutline', + requiresApp: 'integriq', +}) + +// chart-presets REQ-CHARTP-001..003: "Cirkeldiagram" and "Grafiek" of board +// LpManagement as presets of the chart stack, not a second one. +registerDashboardWidget('pie-chart', { + renderer: ChartHost, + form: ChartSourceForm, + defaultContent: { + chartKind: 'donut', + source: 'register', + dataSource: { + register: '', + schema: '', + filter: {}, + groupBy: { field: '', metric: 'count', metricField: '', sort: 'desc', limit: 8 }, + }, + showTotal: true, + legendValues: true, + legendPosition: 'right', + }, + displayName: 'Pie chart', + icon: 'ChartDonut', +}) + +registerDashboardWidget('graph', { + renderer: ChartHost, + form: ChartSourceForm, + defaultContent: { + chartKind: 'bar', + source: 'register', + dataSource: { + register: '', + schema: '', + filter: {}, + bucket: { field: '', interval: 'month', metric: 'count', metricField: '' }, + }, + legendPosition: 'bottom', + }, + displayName: 'Graph', + icon: 'ChartBar', +}) + +// engagement-announcements REQ-ANN-001..003: targeted news with likes, +// comments and follow per category; notices show as banners instead. +registerDashboardWidget('announcements', { + renderer: AnnouncementsWidget, + form: AnnouncementsWidgetForm, + defaultContent: { + category: '', + limit: 10, + }, + displayName: 'Announcements', + icon: 'BullhornOutline', +}) + // `news` — RSS/Atom headlines fetched server-side // (openspec/specs/news-widget). Registered after the shared catalog import, so // this entry replaces the communal one while nc-vue still ships it. @@ -319,7 +594,7 @@ function decorate(type, entry) { */ function offerableTypes() { const types = new Set(cnListWidgetTypes('app-dashboard')) - for (const type of Object.keys(FORM_OVERRIDES)) { + for (const type of [...Object.keys(FORM_OVERRIDES), ...EXTRA_TYPES]) { if (cnGetWidgetTypeEntry(type)) { types.add(type) } @@ -373,3 +648,18 @@ export function getWidgetTypeEntry(type) { export function getDefaultContent(type) { return cnGetDefaultContent(type) } + +/** + * Whether the picker offers a widget type to this viewer: always, unless the + * type reads through an app (`requiresApp`) that is not enabled for them. + * + * @param {WidgetRegistryEntry|null} entry The type's entry. + * @param {Record<string, boolean|string>} integrationApps Which apps are enabled for the viewer; a renamed fleet app answers with its installed id. + * @return {boolean} Whether to offer it. + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-picker-offers-the-wiki-only-where-it-can-work-req-wiki-004 + */ +export function offeredForViewer(entry, integrationApps) { + const app = entry?.requiresApp + const enabled = integrationApps?.[app] + return !app || enabled === true || (typeof enabled === 'string' && enabled !== '') +} diff --git a/src/dialogs/CreateGroupDashboardModal.vue b/src/dialogs/CreateGroupDashboardModal.vue index 220cfb1bc..d801a300b 100644 --- a/src/dialogs/CreateGroupDashboardModal.vue +++ b/src/dialogs/CreateGroupDashboardModal.vue @@ -82,7 +82,7 @@ import { NcSelect, NcTextField, } from '@nextcloud/vue' -import { ICON_CATALOGUE } from '../services/iconCatalogue.js' +import { DASHBOARD_ICON_CATALOGUE } from '../services/iconCatalogue.js' import { useGroupDashboardsStore } from '../stores/groupDashboards.js' /** @@ -139,7 +139,7 @@ export default { * @return {object} the frozen icon catalogue. */ iconCatalogue() { - return ICON_CATALOGUE + return DASHBOARD_ICON_CATALOGUE }, layoutTemplates() { diff --git a/src/dialogs/DeleteDashboardDialog.vue b/src/dialogs/DeleteDashboardDialog.vue index 44a04bce1..48088c888 100644 --- a/src/dialogs/DeleteDashboardDialog.vue +++ b/src/dialogs/DeleteDashboardDialog.vue @@ -41,6 +41,7 @@ <script> import { NcButton, NcDialog } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' +import { REQUIRED_FLAG_PROP, TEXT_PROP } from '../constants/propDefinitions.js' /** * DeleteDashboardDialog: the confirmation before a dashboard is deleted. @@ -59,15 +60,9 @@ export default { }, props: { - open: { - type: Boolean, - required: true, - }, + open: REQUIRED_FLAG_PROP, - name: { - type: String, - default: '', - }, + name: TEXT_PROP, /** Dashboards under this one, once the server has told us. */ childCount: { diff --git a/src/dialogs/DeleteTenantThemeDialog.vue b/src/dialogs/DeleteTenantThemeDialog.vue new file mode 100644 index 000000000..5bb087da5 --- /dev/null +++ b/src/dialogs/DeleteTenantThemeDialog.vue @@ -0,0 +1,70 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcDialog + :name="t('launchpad', 'Delete theme')" + :open="open" + @update:open="$emit('update:open', $event)"> + <template #default> + <p>{{ t('launchpad', 'Delete {name}? This cannot be undone.', { name }) }}</p> + <p v-if="tokenCount > 0" data-test="delete-theme-in-use"> + {{ n('launchpad', '%n embed token uses this theme and falls back to the default theme.', '%n embed tokens use this theme and fall back to the default theme.', tokenCount) }} + </p> + </template> + <template #actions> + <NcButton variant="tertiary" @click="$emit('update:open', false)"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + variant="error" + data-test="delete-theme-confirm" + @click="$emit('confirm')"> + {{ t('launchpad', 'Delete') }} + </NcButton> + </template> + </NcDialog> +</template> + +<script> +import { NcButton, NcDialog } from '@conduction/nextcloud-vue' +import { n, t } from '@nextcloud/l10n' +import { REQUIRED_FLAG_PROP, TEXT_PROP } from '../constants/propDefinitions.js' + +/** + * DeleteTenantThemeDialog: the confirmation before a tenant theme is + * deleted, warning when embed tokens still use it (embedded-analytics task 16). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ +export default { + name: 'DeleteTenantThemeDialog', + + components: { + NcButton, + NcDialog, + }, + + props: { + open: REQUIRED_FLAG_PROP, + + /** The theme's name. */ + name: TEXT_PROP, + + /** How many embed tokens use the theme. */ + tokenCount: { + type: Number, + default: 0, + }, + }, + + emits: ['update:open', 'confirm'], + + methods: { + t, + n, + }, +} +</script> diff --git a/src/dialogs/DemoShowcaseUninstallDialog.vue b/src/dialogs/DemoShowcaseUninstallDialog.vue deleted file mode 100644 index 510e5837d..000000000 --- a/src/dialogs/DemoShowcaseUninstallDialog.vue +++ /dev/null @@ -1,73 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Remove showcase dashboard')" - :open="open" - @update:open="$emit('update:open', $event)"> - <template #default> - <p> - {{ - t( - 'launchpad', - 'Remove the {name} showcase dashboard for all users? You can reinstall it later.', - { name: showcaseName }, - ) - }} - </p> - </template> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton variant="error" @click="$emit('confirm')"> - {{ t('launchpad', 'Remove') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' - -/** - * DemoShowcaseUninstallDialog — confirmation dialog extracted from - * `AdminDemoData.vue` per ADR-004 modal-isolation. - * - * Replaces a `window.confirm()`. The native dialog is not themeable, is not - * translatable beyond the string passed to it, renders outside the app's - * stacking context, and — the reason it matters here — it blocks the whole - * browser thread, so it cannot be driven by the e2e suite or read by a - * screen reader as part of the page. - * - * The parent owns the showcase row and the uninstall action; this dialog - * only renders the confirmation prompt. - * - * @spec openspec/specs/demo-data-showcases/spec.md - */ -export default { - name: 'DemoShowcaseUninstallDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - - showcaseName: { - type: String, - default: '', - }, - }, - - emits: ['update:open', 'confirm'], -} -</script> diff --git a/src/dialogs/ForceReleaseLockDialog.vue b/src/dialogs/ForceReleaseLockDialog.vue deleted file mode 100644 index 126af7700..000000000 --- a/src/dialogs/ForceReleaseLockDialog.vue +++ /dev/null @@ -1,72 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Take over editing?')" - :open="open" - @update:open="$emit('update:open', $event)"> - <template #default> - <p> - {{ - t( - 'launchpad', - '{name} can no longer save changes to this dashboard. Take over only when you know they have stopped.', - { name: holderName || t('launchpad', 'A colleague') }, - ) - }} - </p> - </template> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton - variant="primary" - data-testid="edit-lock-take-over-confirm" - @click="$emit('confirm')"> - {{ t('launchpad', 'Take over') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' -import { t } from '@nextcloud/l10n' - -/** - * ForceReleaseLockDialog: the confirmation before an administrator - * force-releases a colleague's editing lock (ADR-004 modal isolation). - * - * @spec openspec/specs/dashboard-locking/spec.md - */ -export default { - name: 'ForceReleaseLockDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - - holderName: { - type: String, - default: '', - }, - }, - - emits: ['update:open', 'confirm'], - - methods: { - t, - }, -} -</script> diff --git a/src/dialogs/GroupDashboardDeleteDialog.vue b/src/dialogs/GroupDashboardDeleteDialog.vue deleted file mode 100644 index 5485be4c3..000000000 --- a/src/dialogs/GroupDashboardDeleteDialog.vue +++ /dev/null @@ -1,56 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Delete dashboard')" - :open="open" - @update:open="$emit('update:open', $event)"> - <template #default> - <p> - {{ t('launchpad', 'Delete this dashboard? This cannot be undone.') }} - </p> - </template> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton variant="error" @click="$emit('confirm')"> - {{ t('launchpad', 'Delete') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' - -/** - * GroupDashboardDeleteDialog — confirmation extracted from - * `ManageGroupDashboardsModal.vue` per ADR-004 modal-isolation. - * - * Replaces a `window.confirm()`, which is unthemeable, blocks the browser - * thread, and therefore cannot be exercised by the e2e suite. - * - * @spec openspec/specs/admin-templates/spec.md - */ -export default { - name: 'GroupDashboardDeleteDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - }, - - emits: ['update:open', 'confirm'], -} -</script> diff --git a/src/dialogs/GroupDashboardRenameDialog.vue b/src/dialogs/GroupDashboardRenameDialog.vue index e72603453..92f9e4b83 100644 --- a/src/dialogs/GroupDashboardRenameDialog.vue +++ b/src/dialogs/GroupDashboardRenameDialog.vue @@ -31,6 +31,7 @@ <script> import { NcButton, NcDialog, NcTextField } from '@conduction/nextcloud-vue' +import { REQUIRED_FLAG_PROP, TEXT_PROP } from '../constants/propDefinitions.js' /** * GroupDashboardRenameDialog — rename prompt extracted from @@ -55,15 +56,9 @@ export default { }, props: { - open: { - type: Boolean, - required: true, - }, + open: REQUIRED_FLAG_PROP, - currentName: { - type: String, - default: '', - }, + currentName: TEXT_PROP, }, emits: ['update:open', 'confirm'], diff --git a/src/dialogs/KioskPlaylistDialog.vue b/src/dialogs/KioskPlaylistDialog.vue index 2f9a3845f..ecfcbf7d4 100644 --- a/src/dialogs/KioskPlaylistDialog.vue +++ b/src/dialogs/KioskPlaylistDialog.vue @@ -95,6 +95,11 @@ <script> import { NcButton, NcDialog, NcSelect, NcTextField } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' +import { + LIST_PROP, + NULLABLE_OBJECT_PROP, + REQUIRED_FLAG_PROP, +} from '../constants/propDefinitions.js' /** Limits enforced by KioskService (DWELL_MIN/MAX, REFRESH_MIN/MAX). */ export const DWELL_MIN = 10 @@ -123,22 +128,13 @@ export default { }, props: { - open: { - type: Boolean, - required: true, - }, + open: REQUIRED_FLAG_PROP, /** Playlist to edit, or null for a new one. */ - playlist: { - type: Object, - default: null, - }, + playlist: NULLABLE_OBJECT_PROP, /** Dashboards to choose from (`uuid`, `name`). */ - dashboards: { - type: Array, - default: () => [], - }, + dashboards: LIST_PROP, }, emits: ['update:open', 'save'], diff --git a/src/dialogs/ManageGroupDashboardsModal.vue b/src/dialogs/ManageGroupDashboardsModal.vue index a9c8c1303..677558caf 100644 --- a/src/dialogs/ManageGroupDashboardsModal.vue +++ b/src/dialogs/ManageGroupDashboardsModal.vue @@ -86,17 +86,23 @@ @update:open="renameTarget = null" @confirm="onRenameConfirm" /> - <GroupDashboardDeleteDialog - :open="deleteTarget !== null" - @update:open="deleteTarget = null" - @confirm="onDeleteConfirm" /> + <CnConfirmDialog + v-if="deleteTarget !== null" + :dialogTitle="t('launchpad', 'Delete dashboard')" + :message=" + t('launchpad', 'Delete this dashboard? This cannot be undone.') + " + :confirmLabel="t('launchpad', 'Delete')" + variant="error" + @confirm="onDeleteConfirm" + @close="deleteTarget = null" /> </NcDialog> </template> <script> +import { CnConfirmDialog } from '@conduction/nextcloud-vue' import { NcButton, NcDialog, NcEmptyContent, NcLoadingIcon } from '@nextcloud/vue' import ViewDashboardIcon from 'vue-material-design-icons/ViewDashboard.vue' -import GroupDashboardDeleteDialog from './GroupDashboardDeleteDialog.vue' import GroupDashboardRenameDialog from './GroupDashboardRenameDialog.vue' import { useGroupDashboardsStore } from '../stores/groupDashboards.js' @@ -112,7 +118,7 @@ export default { name: 'ManageGroupDashboardsModal', components: { - GroupDashboardDeleteDialog, + CnConfirmDialog, GroupDashboardRenameDialog, NcButton, NcDialog, diff --git a/src/dialogs/OfficeFileDialog.vue b/src/dialogs/OfficeFileDialog.vue new file mode 100644 index 000000000..c3bf7b73a --- /dev/null +++ b/src/dialogs/OfficeFileDialog.vue @@ -0,0 +1,136 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcDialog + :name="title" + :open="open" + @update:open="$emit('update:open', $event)"> + <template #default> + <div class="office-file-dialog"> + <NcTextField + v-model="name" + :label="t('launchpad', 'File name')" + :disabled="busy" + @keyup.enter="submit" /> + <NcTextField + v-model="folder" + :label="t('launchpad', 'Folder')" + :disabled="busy" + @keyup.enter="submit" /> + </div> + </template> + <template #actions> + <NcButton variant="tertiary" :disabled="busy" @click="$emit('update:open', false)"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton variant="primary" :disabled="!canSubmit" @click="submit"> + {{ t('launchpad', 'Create') }} + </NcButton> + </template> + </NcDialog> +</template> + +<script> +import { NcButton, NcDialog, NcTextField } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { FLAG_PROP, REQUIRED_FLAG_PROP, TEXT_PROP } from '../constants/propDefinitions.js' + +/** The folder a new office file goes to unless the person picks another. */ +export const DEFAULT_OFFICE_FOLDER = '/Documents' + +/** + * OfficeFileDialog — the name and folder a "New ..." office tile asks for + * before it creates the file (REQ-OFT-002). The dialog owns only the draft + * values; the tile does the request and emits nothing else. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ +export default { + name: 'OfficeFileDialog', + + components: { + NcButton, + NcDialog, + NcTextField, + }, + + props: { + open: REQUIRED_FLAG_PROP, + + /** The dialog heading, the tile's own label such as "New document". */ + title: TEXT_PROP, + + /** The name the field starts with. */ + defaultName: TEXT_PROP, + + /** Whether the file is being created; the fields and buttons are then disabled. */ + busy: FLAG_PROP, + }, + + emits: ['update:open', 'confirm'], + + data() { + return { + name: this.defaultName, + folder: DEFAULT_OFFICE_FOLDER, + } + }, + + computed: { + /** + * A name and a folder that are not blank, and no request under way. + * + * @return {boolean} Whether Create may be pressed. + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + canSubmit() { + return !this.busy && this.name.trim() !== '' && this.folder.trim() !== '' + }, + }, + + watch: { + /** + * Start from the default name and folder each time the dialog opens. + * + * @param {boolean} isOpen The new open state. + * @return {void} + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + open(isOpen) { + if (isOpen) { + this.name = this.defaultName + this.folder = DEFAULT_OFFICE_FOLDER + } + }, + }, + + methods: { + t, + + /** + * Emit the trimmed name and folder when they pass canSubmit; Enter + * reaches this without the disabled button, so the guard lives here. + * + * @return {void} + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + submit() { + if (!this.canSubmit) { + return + } + this.$emit('confirm', { name: this.name.trim(), folder: this.folder.trim() }) + }, + }, +} +</script> + +<style scoped> +.office-file-dialog { + display: flex; + flex-direction: column; + gap: var(--default-grid-baseline, 4px); +} +</style> diff --git a/src/dialogs/ReadConfirmationDialog.vue b/src/dialogs/ReadConfirmationDialog.vue index 26eaa8df0..34f041cc7 100644 --- a/src/dialogs/ReadConfirmationDialog.vue +++ b/src/dialogs/ReadConfirmationDialog.vue @@ -36,27 +36,27 @@ </p> </div> <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton - variant="primary" - data-testid="read-confirmation-save" - @click="save"> - {{ t('launchpad', 'Save') }} - </NcButton> + <CnDialogActions + :confirmLabel="t('launchpad', 'Save')" + :cancelLabel="t('launchpad', 'Cancel')" + @cancel="$emit('update:open', false)" + @submit="save" /> </template> </NcDialog> </template> <script> import { - NcButton, + CnDialogActions, NcCheckboxRadioSwitch, NcDialog, NcTextField, } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' +import { + NULLABLE_OBJECT_PROP, + REQUIRED_FLAG_PROP, +} from '../constants/propDefinitions.js' /** * ReadConfirmationDialog: an editor asks readers to confirm they have read @@ -70,23 +70,17 @@ export default { name: 'ReadConfirmationDialog', components: { - NcButton, + CnDialogActions, NcCheckboxRadioSwitch, NcDialog, NcTextField, }, props: { - open: { - type: Boolean, - required: true, - }, + open: REQUIRED_FLAG_PROP, /** The widget placement being set up. */ - placement: { - type: Object, - default: null, - }, + placement: NULLABLE_OBJECT_PROP, }, emits: ['update:open', 'save'], diff --git a/src/dialogs/ResetPersonalViewDialog.vue b/src/dialogs/ResetPersonalViewDialog.vue deleted file mode 100644 index 34f5b7883..000000000 --- a/src/dialogs/ResetPersonalViewDialog.vue +++ /dev/null @@ -1,66 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Reset your view?')" - :open="open" - @update:open="$emit('update:open', $event)"> - <template #default> - <p> - {{ - t( - 'launchpad', - 'Every widget you hid comes back, and the dashboard looks the way its owner set it up.', - ) - }} - </p> - </template> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton - variant="primary" - data-testid="hidden-reset-confirm" - @click="$emit('confirm')"> - {{ t('launchpad', 'Reset my view') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' -import { t } from '@nextcloud/l10n' - -/** - * ResetPersonalViewDialog: the confirmation before a person's whole - * personal layer is deleted (ADR-004 modal isolation). - * - * @spec openspec/specs/dashboards/spec.md - */ -export default { - name: 'ResetPersonalViewDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - }, - - emits: ['update:open', 'confirm'], - - methods: { - t, - }, -} -</script> diff --git a/src/dialogs/RestoreVersionDialog.vue b/src/dialogs/RestoreVersionDialog.vue deleted file mode 100644 index 70518764b..000000000 --- a/src/dialogs/RestoreVersionDialog.vue +++ /dev/null @@ -1,73 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Restore this version?')" - :open="open" - @update:open="$emit('update:open', $event)"> - <template #default> - <p> - {{ - t( - 'launchpad', - 'The dashboard goes back to how it was on {date}. How it looks now is saved as a version first, so you can undo this.', - { date }, - ) - }} - </p> - </template> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton - variant="primary" - data-testid="version-restore-confirm" - @click="$emit('confirm')"> - {{ t('launchpad', 'Restore') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' -import { t } from '@nextcloud/l10n' - -/** - * RestoreVersionDialog: the confirmation before a dashboard version is - * restored (ADR-004 modal isolation). - * - * @spec openspec/specs/dashboard-versioning/spec.md - */ -export default { - name: 'RestoreVersionDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - - /** The version's date as shown in the list. */ - date: { - type: String, - default: '', - }, - }, - - emits: ['update:open', 'confirm'], - - methods: { - t, - }, -} -</script> diff --git a/src/dialogs/RevokeEmbedTokenDialog.vue b/src/dialogs/RevokeEmbedTokenDialog.vue new file mode 100644 index 000000000..c8f7a67b7 --- /dev/null +++ b/src/dialogs/RevokeEmbedTokenDialog.vue @@ -0,0 +1,103 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcDialog + :name="t('launchpad', 'Revoke embed token')" + :open="open" + @update:open="$emit('update:open', $event)"> + <template #default> + <p> + {{ t('launchpad', 'Revoke {name}? Sites embedding it stop showing it within a minute.', { name }) }} + </p> + <NcSelect + v-model="reason" + :inputLabel="t('launchpad', 'Reason')" + :options="reasons" + label="label" + trackBy="id" + :clearable="false" + data-test="revoke-embed-token-reason" /> + <NcTextArea + v-model="notes" + :label="t('launchpad', 'Notes (optional)')" + data-test="revoke-embed-token-notes" /> + </template> + <template #actions> + <NcButton variant="tertiary" @click="$emit('update:open', false)"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + variant="error" + data-test="revoke-embed-token-confirm" + @click="$emit('confirm', { reason: reason.id, notes: notes.trim() })"> + {{ t('launchpad', 'Revoke') }} + </NcButton> + </template> + </NcDialog> +</template> + +<script> +import { NcButton, NcDialog, NcSelect, NcTextArea } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { REQUIRED_FLAG_PROP, TEXT_PROP } from '../constants/propDefinitions.js' +import { REVOKE_REASONS } from '../utils/embedToken.js' + +/** + * RevokeEmbedTokenDialog: the confirmation before an embed token is revoked, + * with the reason and optional notes the audit record keeps + * (embedded-analytics task 27, REQ-EMB-009). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-27 + */ +export default { + name: 'RevokeEmbedTokenDialog', + + components: { + NcButton, + NcDialog, + NcSelect, + NcTextArea, + }, + + props: { + open: REQUIRED_FLAG_PROP, + + /** The token's name. */ + name: TEXT_PROP, + }, + + emits: ['update:open', 'confirm'], + + data() { + const reasons = this.reasonOptions() + return { + reasons, + reason: reasons[0], + notes: '', + } + }, + + methods: { + t, + + /** + * The revocation reasons, labelled. + * + * @return {Array<{id: string, label: string}>} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + reasonOptions() { + const labels = { + compromised: t('launchpad', 'The token was exposed'), + no_longer_needed: t('launchpad', 'No longer needed'), + host_decommissioned: t('launchpad', 'The embedding site is gone'), + other: t('launchpad', 'Other'), + } + return REVOKE_REASONS.map((id) => ({ id, label: labels[id] })) + }, + }, +} +</script> diff --git a/src/dialogs/RevokeKioskPlaylistDialog.vue b/src/dialogs/RevokeKioskPlaylistDialog.vue deleted file mode 100644 index bbb3f2877..000000000 --- a/src/dialogs/RevokeKioskPlaylistDialog.vue +++ /dev/null @@ -1,72 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Revoke this playlist?')" - :open="open" - @update:open="$emit('update:open', $event)"> - <template #default> - <p> - {{ - t( - 'launchpad', - 'Screens showing {name} stop at their next check, and the link stops working for good.', - { name }, - ) - }} - </p> - </template> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton - variant="error" - data-testid="kiosk-revoke-confirm" - @click="$emit('confirm')"> - {{ t('launchpad', 'Revoke') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' -import { t } from '@nextcloud/l10n' - -/** - * RevokeKioskPlaylistDialog: the confirmation before a kiosk link is - * revoked (ADR-004 modal isolation). - * - * @spec openspec/specs/dashboard-kiosk-mode/spec.md - */ -export default { - name: 'RevokeKioskPlaylistDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - - name: { - type: String, - default: '', - }, - }, - - emits: ['update:open', 'confirm'], - - methods: { - t, - }, -} -</script> diff --git a/src/dialogs/RoleLayoutDefaultDeleteDialog.vue b/src/dialogs/RoleLayoutDefaultDeleteDialog.vue deleted file mode 100644 index 7770c3450..000000000 --- a/src/dialogs/RoleLayoutDefaultDeleteDialog.vue +++ /dev/null @@ -1,58 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Delete layout default')" - :open="open" - @update:open="$emit('update:open', $event)"> - <template #default> - <p> - {{ - t( - 'launchpad', - 'Delete layout default for "{group}" / "{widget}"?', - { group: groupId, widget: widgetId }, - ) - }} - </p> - </template> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton variant="error" @click="$emit('confirm')"> - {{ t('launchpad', 'Delete') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' - -/** - * RoleLayoutDefaultDeleteDialog — confirmation extracted from - * `RoleLayoutDefaultsSection.vue` per ADR-004 modal-isolation rule. - * - * @spec openspec/specs/admin-roles/spec.md - */ -export default { - name: 'RoleLayoutDefaultDeleteDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { type: Boolean, required: true }, - groupId: { type: String, default: '' }, - widgetId: { type: String, default: '' }, - }, - - emits: ['update:open', 'confirm'], -} -</script> diff --git a/src/dialogs/RolePermissionDeleteDialog.vue b/src/dialogs/RolePermissionDeleteDialog.vue deleted file mode 100644 index 640f4b33f..000000000 --- a/src/dialogs/RolePermissionDeleteDialog.vue +++ /dev/null @@ -1,64 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Delete role permission')" - :open="open" - @update:open="$emit('update:open', $event)"> - <template #default> - <p> - {{ - t('launchpad', 'Delete role permission for group "{group}"?', { - group: groupId, - }) - }} - </p> - </template> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton variant="error" @click="$emit('confirm')"> - {{ t('launchpad', 'Delete') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' - -/** - * RolePermissionDeleteDialog — confirmation dialog extracted from - * `RolePermissionsSection.vue` per ADR-004 modal-isolation rule. The - * parent owns the target row + delete action; this dialog only renders - * the confirmation prompt. - * - * @spec openspec/specs/admin-roles/spec.md - */ -export default { - name: 'RolePermissionDeleteDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - - groupId: { - type: String, - default: '', - }, - }, - - emits: ['update:open', 'confirm'], -} -</script> diff --git a/src/dialogs/ScheduleDashboardDialog.vue b/src/dialogs/ScheduleDashboardDialog.vue deleted file mode 100644 index f53ea528e..000000000 --- a/src/dialogs/ScheduleDashboardDialog.vue +++ /dev/null @@ -1,137 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcDialog - :name="t('launchpad', 'Schedule dashboard')" - :open="open" - @update:open="$emit('update:open', $event)"> - <div class="schedule-dialog"> - <label class="schedule-dialog__field"> - {{ t('launchpad', 'Goes live on') }} - <input - v-model="goLive" - type="datetime-local" - data-testid="schedule-go-live" /> - </label> - <label class="schedule-dialog__field"> - {{ t('launchpad', 'Comes down on (optional)') }} - <input - v-model="takeDown" - type="datetime-local" - data-testid="schedule-take-down" /> - </label> - <p - v-if="error" - class="schedule-dialog__error" - role="alert" - data-testid="schedule-error"> - {{ error }} - </p> - </div> - <template #actions> - <NcButton variant="tertiary" @click="$emit('update:open', false)"> - {{ t('launchpad', 'Cancel') }} - </NcButton> - <NcButton - variant="primary" - :disabled="!goLive && !takeDown" - data-testid="schedule-save" - @click="save"> - {{ t('launchpad', 'Schedule') }} - </NcButton> - </template> - </NcDialog> -</template> - -<script> -import { NcButton, NcDialog } from '@conduction/nextcloud-vue' -import { t } from '@nextcloud/l10n' - -/** - * ScheduleDashboardDialog: set when a dashboard goes live, when it comes - * down, or both. Emits `save` with ISO-8601 strings (or null) for - * `publishAt` and `unpublishAt`; the host shows the server's refusal - * through the `error` prop. - * - * @spec openspec/specs/dashboards/spec.md - */ -export default { - name: 'ScheduleDashboardDialog', - - components: { - NcButton, - NcDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - - /** Why the last attempt was refused. */ - error: { - type: String, - default: '', - }, - }, - - emits: ['update:open', 'save'], - - /** @spec openspec/specs/dashboards/spec.md */ - data() { - return { goLive: '', takeDown: '' } - }, - - methods: { - t, - - /** - * Turn a `datetime-local` value into ISO-8601 with the viewer's offset. - * - * @param {string} local Value like `2026-10-01T09:00`. - * @return {string|null} ISO string, or null when empty. - * @spec openspec/specs/dashboards/spec.md - */ - toIso(local) { - if (!local) { - return null - } - const date = new Date(local) - return Number.isNaN(date.getTime()) ? null : date.toISOString() - }, - - /** - * Emit the chosen times. - * - * @spec openspec/specs/dashboards/spec.md - */ - save() { - this.$emit('save', { - publishAt: this.toIso(this.goLive), - unpublishAt: this.toIso(this.takeDown), - }) - }, - }, -} -</script> - -<style scoped> -.schedule-dialog { - display: flex; - flex-direction: column; - gap: 12px; -} - -.schedule-dialog__field { - display: flex; - flex-direction: column; -} - -.schedule-dialog__error { - color: var(--color-error-text); -} -</style> diff --git a/src/dialogs/ShippedTemplateUpdateDialog.vue b/src/dialogs/ShippedTemplateUpdateDialog.vue new file mode 100644 index 000000000..5656b32c8 --- /dev/null +++ b/src/dialogs/ShippedTemplateUpdateDialog.vue @@ -0,0 +1,258 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcDialog + :name="t('launchpad', 'Update template')" + :open="open" + data-testid="shipped-template-update-dialog" + @update:open="onOpenChange"> + <template #default> + <p v-if="loading" data-testid="shipped-update-loading"> + {{ t('launchpad', 'Working out what changes.') }} + </p> + <p + v-else-if="errorMessage !== ''" + class="shipped-update__error" + role="alert" + data-testid="shipped-update-error"> + {{ errorMessage }} + </p> + <div v-else-if="plan !== null" data-testid="shipped-update-plan"> + <p> + {{ + t( + 'launchpad', + 'This brings "{name}" from version {from} to version {to}. Its name, its groups and whether it is the default stay as they are.', + { + name: plan.name, + from: plan.installedVersion, + to: plan.version, + }, + ) + }} + </p> + <p v-if="!hasChanges" data-testid="shipped-update-nothing"> + {{ t('launchpad', 'The widgets stay as they are.') }} + </p> + <template v-if="plan.added.length > 0"> + <h4>{{ t('launchpad', 'Widgets added') }}</h4> + <ul data-testid="shipped-update-added"> + <li v-for="widget in plan.added" :key="`a-${widget}`"> + {{ widget }} + </li> + </ul> + </template> + <template v-if="plan.removed.length > 0"> + <h4>{{ t('launchpad', 'Widgets removed') }}</h4> + <ul data-testid="shipped-update-removed"> + <li v-for="widget in plan.removed" :key="`r-${widget}`"> + {{ widget }} + </li> + </ul> + </template> + <template v-if="plan.changed.length > 0"> + <h4>{{ t('launchpad', 'Widgets changed') }}</h4> + <ul data-testid="shipped-update-changed"> + <li + v-for="change in plan.changed" + :key="`c-${change.widget}`"> + {{ change.widget }} + </li> + </ul> + </template> + <p class="shipped-update__hint"> + {{ + t( + 'launchpad', + 'Changes you made to the widgets of this template by hand are replaced.', + ) + }} + </p> + <p class="shipped-update__hint" data-testid="shipped-update-copies"> + {{ + t( + 'launchpad', + 'Members with a copy of this template: {count}. Their copies follow. A widget a member added stays.', + { count: plan.copies }, + ) + }} + </p> + </div> + </template> + <template #actions> + <NcButton + variant="tertiary" + data-testid="shipped-update-cancel" + @click="$emit('update:open', false)"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + variant="primary" + :disabled="plan === null || loading || updating" + data-testid="shipped-update-confirm" + @click="confirm"> + {{ t('launchpad', 'Update') }} + </NcButton> + </template> + </NcDialog> +</template> + +<script> +import { NcButton, NcDialog } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { + NULLABLE_OBJECT_PROP, + REQUIRED_FLAG_PROP, +} from '../constants/propDefinitions.js' +import { api } from '../services/api.js' +import { logger } from '../utils/logger.js' + +/** + * ShippedTemplateUpdateDialog: shows what updating an installed ready-made + * template changes, before anything is written (admin-templates + * REQ-TMPL-020). Opening it asks the server for a dry run; "Update" then + * runs the update for real and reports the result to the parent. + * + * In its own file per ADR-004 modal isolation. The parent owns the list of + * shipped templates; this dialog owns the plan and the update call. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ +export default { + name: 'ShippedTemplateUpdateDialog', + + components: { + NcButton, + NcDialog, + }, + + props: { + open: REQUIRED_FLAG_PROP, + + /** The shipped template row, as the listing returns it. */ + shipped: NULLABLE_OBJECT_PROP, + }, + + emits: ['update:open', 'updated'], + + data() { + return { + plan: null, + loading: false, + updating: false, + errorMessage: '', + } + }, + + computed: { + /** + * Whether the update touches any widget. + * + * @return {boolean} False when every widget stays as it is. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + hasChanges() { + return ( + this.plan !== null + && this.plan.added.length + + this.plan.removed.length + + this.plan.changed.length + > 0 + ) + }, + }, + + watch: { + open: { + immediate: true, + /** + * Load the plan each time the dialog opens. + * + * @param {boolean} isOpen Whether the dialog is now open. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + handler(isOpen) { + if (isOpen && this.shipped !== null) { + this.loadPlan() + } + }, + }, + }, + + methods: { + t, + + /** + * Pass a close from the dialog chrome on to the parent. + * + * @param {boolean} isOpen The dialog's new open state. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + onOpenChange(isOpen) { + this.$emit('update:open', isOpen) + }, + + /** + * Ask the server what the update would change. Writes nothing. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + async loadPlan() { + this.plan = null + this.errorMessage = '' + this.loading = true + try { + const { data } = await api.updateShippedTemplate(this.shipped.id, { + dryRun: true, + }) + this.plan = data + } catch (error) { + logger.error('Failed to load the template update plan:', error) + this.errorMessage = t( + 'launchpad', + 'The changes could not be worked out. Nothing was updated.', + ) + } finally { + this.loading = false + } + }, + + /** + * Run the update and hand the result to the parent. + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + async confirm() { + this.updating = true + this.errorMessage = '' + try { + const { data } = await api.updateShippedTemplate(this.shipped.id) + this.$emit('updated', data) + } catch (error) { + logger.error('Failed to update the shipped template:', error) + this.plan = null + this.errorMessage = t( + 'launchpad', + 'The template "{name}" could not be updated.', + { name: this.shipped.name }, + ) + } finally { + this.updating = false + } + }, + }, +} +</script> + +<style scoped> +.shipped-update__hint { + color: var(--color-text-maxcontrast); +} + +.shipped-update__error { + color: var(--color-error); +} +</style> diff --git a/src/dialogs/__tests__/EmbedDialogs.spec.js b/src/dialogs/__tests__/EmbedDialogs.spec.js new file mode 100644 index 000000000..67e6c4c98 --- /dev/null +++ b/src/dialogs/__tests__/EmbedDialogs.spec.js @@ -0,0 +1,55 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The embed dialogs: revoking asks a reason (the first by default) and + * optional notes; deleting a theme warns how many tokens use it + * (embedded-analytics tasks 16 and 27). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-27 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import DeleteTenantThemeDialog from '../DeleteTenantThemeDialog.vue' +import RevokeEmbedTokenDialog from '../RevokeEmbedTokenDialog.vue' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => vars[key] ?? `{${key}}`), + n: (_app, one, many, count) => (count === 1 ? one : many).replace('%n', count), +})) + +const Select = { name: 'NcSelect', props: ['modelValue', 'options'], emits: ['update:modelValue'], template: '<div class="select" />' } +const stubs = { + NcDialog: { props: ['name', 'open'], template: '<div class="dialog"><h2>{{ name }}</h2><slot /><slot name="actions" /></div>' }, + NcButton: { emits: ['click'], template: '<button @click="$emit(\'click\')"><slot /></button>' }, + NcSelect: Select, + NcTextArea: { props: ['modelValue'], emits: ['update:modelValue'], template: '<textarea :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' }, +} + +describe('RevokeEmbedTokenDialog', () => { + it('offers the admin reasons and confirms the chosen reason with trimmed notes', async () => { + const wrapper = mount(RevokeEmbedTokenDialog, { props: { open: true, name: 'Zeist WOO' }, global: { stubs } }) + + expect(wrapper.text()).toContain('Revoke Zeist WOO?') + const select = wrapper.findComponent(Select) + expect(select.props('options').map((option) => option.id)).toEqual(['compromised', 'no_longer_needed', 'host_decommissioned', 'other']) + expect(select.props('modelValue').id).toBe('compromised') + + select.vm.$emit('update:modelValue', select.props('options')[2]) + await wrapper.find('textarea').setValue(' site offline ') + await wrapper.find('[data-test="revoke-embed-token-confirm"]').trigger('click') + + expect(wrapper.emitted('confirm')).toEqual([[{ reason: 'host_decommissioned', notes: 'site offline' }]]) + }) +}) + +describe('DeleteTenantThemeDialog', () => { + it('warns only when tokens use the theme', () => { + const used = mount(DeleteTenantThemeDialog, { props: { open: true, name: 'Zeist', tokenCount: 2 }, global: { stubs } }) + expect(used.find('[data-test="delete-theme-in-use"]').text()).toBe('2 embed tokens use this theme and fall back to the default theme.') + + const unused = mount(DeleteTenantThemeDialog, { props: { open: true, name: 'Zeist' }, global: { stubs } }) + expect(unused.find('[data-test="delete-theme-in-use"]').exists()).toBe(false) + }) +}) diff --git a/src/dialogs/__tests__/ForceReleaseLockDialog.spec.js b/src/dialogs/__tests__/ForceReleaseLockDialog.spec.js deleted file mode 100644 index 06f89e866..000000000 --- a/src/dialogs/__tests__/ForceReleaseLockDialog.spec.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - * - * ForceReleaseLockDialog: the confirmation before an administrator takes - * over a colleague's lock (dashboard-locking REQ-LOCKUI-003). - */ - -import { mount } from '@vue/test-utils' -import { describe, expect, it, vi } from 'vitest' -import ForceReleaseLockDialog from '../ForceReleaseLockDialog.vue' - -vi.mock('@nextcloud/l10n', () => ({ - t: (_app, text, vars = {}) => - text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), -})) - -vi.mock('@conduction/nextcloud-vue', () => ({ - NcDialog: { - name: 'NcDialog', - props: ['name', 'open'], - template: - '<div v-if="open" class="dialog"><h2>{{ name }}</h2><slot /><slot name="actions" /></div>', - }, - NcButton: { - name: 'NcButton', - emits: ['click'], - template: '<button @click="$emit(\'click\')"><slot /></button>', - }, -})) - -describe('ForceReleaseLockDialog', () => { - it('names the holder and confirms or cancels', async () => { - const wrapper = mount(ForceReleaseLockDialog, { - props: { open: true, holderName: 'Sanne' }, - }) - expect(wrapper.text()).toContain('Sanne') - const [cancel, confirm] = wrapper.findAll('button') - await confirm.trigger('click') - expect(wrapper.emitted('confirm')).toHaveLength(1) - await cancel.trigger('click') - expect(wrapper.emitted('update:open')[0]).toEqual([false]) - }) -}) diff --git a/src/dialogs/__tests__/ManageGroupDashboardsModal.spec.js b/src/dialogs/__tests__/ManageGroupDashboardsModal.spec.js new file mode 100644 index 000000000..cdedc938d --- /dev/null +++ b/src/dialogs/__tests__/ManageGroupDashboardsModal.spec.js @@ -0,0 +1,191 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The manage-group-dashboards modal: it loads the group's dashboards, shows + * loading, empty and list states, marks the default, and sends set-default, + * rename and delete to the store for that group. A failed delete keeps the + * modal open and re-enables the row. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useGroupDashboardsStore } from '../../stores/groupDashboards.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() } })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ ...(await importOriginal()), generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/dialogs', () => ({ showSuccess: vi.fn(), showError: vi.fn() })) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), + n: (_app, one, many, count) => (count === 1 ? one : many), +})) + +const { default: ManageGroupDashboardsModal } = await import('../ManageGroupDashboardsModal.vue') + +const stubs = { + NcDialog: { + name: 'NcDialog', + props: ['name', 'open', 'size'], + emits: ['update:open'], + template: '<div class="dialog" :data-name="name"><slot /><slot name="actions" /></div>', + }, + NcButton: { + name: 'NcButton', + props: ['variant', 'disabled'], + emits: ['click'], + template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcEmptyContent: { name: 'NcEmptyContent', props: ['name'], template: '<div class="empty">{{ name }}</div>' }, + NcLoadingIcon: { name: 'NcLoadingIcon', template: '<span />' }, + ViewDashboardIcon: { name: 'ViewDashboardIcon', template: '<span />' }, + GroupDashboardRenameDialog: { + name: 'GroupDashboardRenameDialog', + props: ['open', 'currentName'], + emits: ['update:open', 'confirm'], + template: '<div v-if="open" class="rename" :data-current="currentName" />', + }, + CnConfirmDialog: { + name: 'CnConfirmDialog', + props: ['dialogTitle', 'message', 'confirmLabel', 'variant'], + emits: ['confirm', 'close'], + template: '<div class="confirm">{{ message }}</div>', + }, +} + +const group = { id: 'staff', displayName: 'Staff' } +const dashboards = [ + { uuid: 'd-1', name: 'Roster', isDefault: true }, + { uuid: 'd-2', name: 'Leave', isDefault: false }, +] + +let store + +/** + * Mount the modal over a store whose fetch resolves when told to. + * + * @param {Array} rows The dashboards the fetch stores for the group. + * @return {{wrapper: import('@vue/test-utils').VueWrapper, finishFetch: Function}} + */ +function mountModal(rows = dashboards) { + let finishFetch + store.fetchGroupDashboards = vi.fn(() => new Promise((resolve) => { + finishFetch = () => { + store.dashboardsByGroup = { ...store.dashboardsByGroup, [group.id]: rows } + resolve() + } + })) + const wrapper = mount(ManageGroupDashboardsModal, { props: { group }, global: { stubs } }) + return { wrapper, finishFetch: () => finishFetch() } +} + +/** + * Mount the modal with its dashboards loaded. + * + * @param {Array} rows The dashboards. + * @return {Promise<import('@vue/test-utils').VueWrapper>} + */ +async function loaded(rows = dashboards) { + const { wrapper, finishFetch } = mountModal(rows) + finishFetch() + await flushPromises() + return wrapper +} + +beforeEach(() => { + setActivePinia(createPinia()) + store = useGroupDashboardsStore() + store.setDefault = vi.fn(() => Promise.resolve()) + store.update = vi.fn(() => Promise.resolve()) + store.delete = vi.fn(() => Promise.resolve()) +}) + +describe('ManageGroupDashboardsModal', () => { + it('names the group and shows loading until the group\'s dashboards arrive', async () => { + const { wrapper, finishFetch } = mountModal() + + expect(store.fetchGroupDashboards).toHaveBeenCalledWith('staff') + expect(wrapper.find('.dialog').attributes('data-name')).toMatch(/^Manage dashboards for /) + expect(wrapper.find('.empty').text()).toBe('Loading dashboards') + + finishFetch() + await flushPromises() + + expect(wrapper.findAll('.mgd__row-name').map((n) => n.text())).toEqual(['Roster', 'Leave']) + }) + + it('says so when the group has no dashboards', async () => { + const wrapper = await loaded([]) + + expect(wrapper.find('[data-test="manage-group-dashboards-empty"]').text()).toBe('No dashboards in this group yet') + }) + + it('badges the default and offers set-default only on the others', async () => { + const wrapper = await loaded() + + expect(wrapper.find('[data-test="mgd-row-d-1"] [data-test="mgd-default-badge"]').exists()).toBe(true) + expect(wrapper.find('[data-test="mgd-row-d-2"] [data-test="mgd-default-badge"]').exists()).toBe(false) + expect(wrapper.find('[data-test="mgd-set-default-d-1"]').exists()).toBe(false) + + await wrapper.find('[data-test="mgd-set-default-d-2"]').trigger('click') + + expect(store.setDefault).toHaveBeenCalledWith('staff', 'd-2') + }) + + it('renames through the rename dialog, for that group', async () => { + const wrapper = await loaded() + + await wrapper.find('[data-test="mgd-rename-d-2"]').trigger('click') + expect(wrapper.find('.rename').attributes('data-current')).toBe('Leave') + + wrapper.findComponent({ name: 'GroupDashboardRenameDialog' }).vm.$emit('confirm', 'Holidays') + await flushPromises() + + expect(store.update).toHaveBeenCalledWith('staff', 'd-2', { name: 'Holidays' }) + expect(wrapper.find('.rename').exists()).toBe(false) + }) + + it('closing the rename dialog renames nothing', async () => { + const wrapper = await loaded() + + await wrapper.find('[data-test="mgd-rename-d-2"]').trigger('click') + wrapper.findComponent({ name: 'GroupDashboardRenameDialog' }).vm.$emit('update:open', false) + await flushPromises() + + expect(wrapper.find('.rename').exists()).toBe(false) + await wrapper.vm.onRenameConfirm('Late answer') + expect(store.update).not.toHaveBeenCalled() + }) + + it('a refused delete keeps the modal open and re-enables the row', async () => { + let reject + store.delete = vi.fn(() => new Promise((_resolve, r) => { + reject = r + })) + const wrapper = await loaded() + + await wrapper.find('[data-test="mgd-delete-d-2"]').trigger('click') + wrapper.findComponent({ name: 'CnConfirmDialog' }).vm.$emit('confirm') + await flushPromises() + + expect(store.delete).toHaveBeenCalledWith('staff', 'd-2') + expect(wrapper.find('[data-test="mgd-delete-d-2"]').attributes('disabled')).toBeDefined() + + reject(new Error('refused')) + await flushPromises() + + expect(wrapper.find('[data-test="mgd-delete-d-2"]').attributes('disabled')).toBeUndefined() + expect(wrapper.emitted('close')).toBeUndefined() + }) + + it('close and dismissing the dialog both close the modal', async () => { + const wrapper = await loaded() + + await wrapper.find('[data-test="mgd-close"]').trigger('click') + wrapper.findComponent({ name: 'NcDialog' }).vm.$emit('update:open', false) + + expect(wrapper.emitted('close')).toHaveLength(2) + }) +}) diff --git a/src/dialogs/__tests__/OfficeFileDialog.spec.js b/src/dialogs/__tests__/OfficeFileDialog.spec.js new file mode 100644 index 000000000..ad7738383 --- /dev/null +++ b/src/dialogs/__tests__/OfficeFileDialog.spec.js @@ -0,0 +1,82 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * integrations-office-tiles REQ-OFT-002: the "New ..." dialog asks for a name + * and folder, starts from the tile label and /Documents, and only confirms a + * non-blank name and folder. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + NcDialog: { name: 'NcDialog', props: ['name', 'open'], template: '<div class="dialog"><slot /><slot name="actions" /></div>' }, + NcButton: { name: 'NcButton', props: ['disabled', 'variant'], emits: ['click'], template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label', 'disabled'], + emits: ['update:modelValue', 'keyup'], + template: '<input :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" @keyup="$emit(\'keyup\', $event)" />', + }, +})) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) + +const { default: OfficeFileDialog } = await import('../OfficeFileDialog.vue') + +function mountDialog(props = {}) { + return mount(OfficeFileDialog, { props: { open: true, title: 'New document', defaultName: 'New document', ...props } }) +} + +describe('OfficeFileDialog', () => { + it('starts from the tile label and the Documents folder', () => { + const inputs = mountDialog().findAll('input') + + expect(inputs[0].element.value).toBe('New document') + expect(inputs[1].element.value).toBe('/Documents') + }) + + it('confirms the trimmed name and folder', async () => { + const wrapper = mountDialog() + const [name, folder] = wrapper.findAll('input') + await name.setValue(' Notulen ') + await folder.setValue(' /Projects ') + await wrapper.findAll('button')[1].trigger('click') + + expect(wrapper.emitted('confirm')).toEqual([[{ name: 'Notulen', folder: '/Projects' }]]) + }) + + it('refuses a blank name, also on Enter', async () => { + const wrapper = mountDialog() + const name = wrapper.findAll('input')[0] + await name.setValue(' ') + await name.trigger('keyup', { key: 'Enter' }) + + expect(wrapper.findAll('button')[1].attributes('disabled')).toBeDefined() + expect(wrapper.emitted('confirm')).toBeUndefined() + }) + + it('confirms nothing while a file is being created', async () => { + const wrapper = mountDialog({ busy: true }) + wrapper.vm.submit() + + expect(wrapper.emitted('confirm')).toBeUndefined() + }) + + it('cancels by closing', async () => { + const wrapper = mountDialog() + await wrapper.findAll('button')[0].trigger('click') + + expect(wrapper.emitted('update:open')).toEqual([[false]]) + }) + + it('resets the name and folder when it opens again', async () => { + const wrapper = mountDialog({ open: false }) + await wrapper.findAll('input')[0].setValue('Other') + await wrapper.setProps({ open: true }) + + expect(wrapper.findAll('input')[0].element.value).toBe('New document') + }) +}) diff --git a/src/dialogs/__tests__/ReadConfirmationDialog.spec.js b/src/dialogs/__tests__/ReadConfirmationDialog.spec.js index 1ac5907cc..e6c05ea29 100644 --- a/src/dialogs/__tests__/ReadConfirmationDialog.spec.js +++ b/src/dialogs/__tests__/ReadConfirmationDialog.spec.js @@ -18,10 +18,12 @@ vi.mock('@conduction/nextcloud-vue', () => ({ props: ['open'], template: '<div v-if="open"><slot /><slot name="actions" /></div>', }, - NcButton: { - name: 'NcButton', - emits: ['click'], - template: '<button @click="$emit(\'click\')"><slot /></button>', + CnDialogActions: { + name: 'CnDialogActions', + props: { canSubmit: { type: Boolean, default: true } }, + emits: ['cancel', 'submit'], + template: + '<button data-testid="cn-dialog-actions-submit" :disabled="!canSubmit" @click="$emit(\'submit\')" />', }, NcCheckboxRadioSwitch: { name: 'NcCheckboxRadioSwitch', @@ -49,7 +51,9 @@ describe('ReadConfirmationDialog', () => { .find('input.prompt') .setValue('I have read the new expense rules') await wrapper.find('input[type="date"]').setValue('2026-10-15') - await wrapper.find('[data-testid="read-confirmation-save"]').trigger('click') + await wrapper + .find('[data-testid="cn-dialog-actions-submit"]') + .trigger('click') expect(wrapper.emitted('save')[0][0]).toEqual({ requiresAcknowledgement: 1, acknowledgementPrompt: 'I have read the new expense rules', @@ -71,7 +75,9 @@ describe('ReadConfirmationDialog', () => { }) expect(wrapper.find('input.ask').element.checked).toBe(true) await wrapper.find('input.ask').setValue(false) - await wrapper.find('[data-testid="read-confirmation-save"]').trigger('click') + await wrapper + .find('[data-testid="cn-dialog-actions-submit"]') + .trigger('click') expect(wrapper.emitted('save')[0][0]).toEqual({ requiresAcknowledgement: 0, acknowledgementPrompt: 'Read it', diff --git a/src/dialogs/__tests__/RoleLayoutDefaultEditorDialog.fields.spec.js b/src/dialogs/__tests__/RoleLayoutDefaultEditorDialog.fields.spec.js new file mode 100644 index 000000000..4c5ac5353 --- /dev/null +++ b/src/dialogs/__tests__/RoleLayoutDefaultEditorDialog.fields.spec.js @@ -0,0 +1,149 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The role layout default editor: every field emits the whole row with only + * its own key changed (numbers as numbers), the title says add or edit, and + * cancel and save are disabled while saving. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text) => text, + translate: (_app, text) => text, +})) + +vi.mock('@conduction/nextcloud-vue', () => ({ + NcDialog: { + name: 'NcDialog', + props: ['open', 'name'], + emits: ['update:open'], + template: '<div class="dialog" :data-name="name"><slot /><slot name="actions" /></div>', + }, + NcButton: { + name: 'NcButton', + props: ['variant', 'disabled'], + emits: ['click'], + template: '<button :class="variant" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label', 'type', 'placeholder'], + emits: ['update:modelValue'], + template: '<input :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<label><input type="checkbox" :checked="modelValue" @change="$emit(\'update:modelValue\', $event.target.checked)" /><slot /></label>', + }, +})) + +const { default: RoleLayoutDefaultEditorDialog } = await import('../RoleLayoutDefaultEditorDialog.vue') + +const row = { + id: 7, + name: 'Managers', + groupId: 'managers', + widgetId: 'analytics_dashboard', + gridX: 0, + gridY: 2, + gridWidth: 6, + gridHeight: 4, + sortOrder: 1, + isCompulsory: false, + description: null, +} + +/** + * Mount the editor. + * + * @param {object} props Props over the defaults. + * @return {import('@vue/test-utils').VueWrapper} + */ +function mountEditor(props = {}) { + return mount(RoleLayoutDefaultEditorDialog, { props: { open: true, row, ...props } }) +} + +/** + * The text field with the given label. + * + * @param {import('@vue/test-utils').VueWrapper} wrapper The editor. + * @param {string} label Its label. + * @return {import('@vue/test-utils').DOMWrapper} + */ +function input(wrapper, label) { + return wrapper.find(`input[aria-label="${label}"]`) +} + +describe('RoleLayoutDefaultEditorDialog', () => { + it('says edit for a stored row and add for a new one', () => { + expect(mountEditor().find('.dialog').attributes('data-name')).toBe('Edit layout default') + expect(mountEditor({ row: { ...row, id: null } }).find('.dialog').attributes('data-name')).toBe('Add layout default') + }) + + it('shows the row, numbers as text and a missing description as empty', () => { + const wrapper = mountEditor() + + expect(input(wrapper, 'Name').element.value).toBe('Managers') + expect(input(wrapper, 'Grid Y').element.value).toBe('2') + expect(input(wrapper, 'Height (rows)').element.value).toBe('4') + expect(input(wrapper, 'Description (optional)').element.value).toBe('') + }) + + it.each([ + ['Name', 'Directors', { name: 'Directors' }], + ['Group ID', 'directors', { groupId: 'directors' }], + ['Widget ID', 'kpi', { widgetId: 'kpi' }], + ['Description (optional)', 'For the board', { description: 'For the board' }], + ])('the %s field emits the row with only that text changed', async (label, value, change) => { + const wrapper = mountEditor() + + await input(wrapper, label).setValue(value) + + expect(wrapper.emitted('update:row')).toEqual([[{ ...row, ...change }]]) + }) + + it.each([ + ['Grid X', 'gridX'], + ['Grid Y', 'gridY'], + ['Width (columns)', 'gridWidth'], + ['Height (rows)', 'gridHeight'], + ['Sort order', 'sortOrder'], + ])('the %s field emits its value as a number', async (label, key) => { + const wrapper = mountEditor() + + await input(wrapper, label).setValue('12') + + expect(wrapper.emitted('update:row')).toEqual([[{ ...row, [key]: 12 }]]) + }) + + it('the compulsory switch emits the row with the flag set', async () => { + const wrapper = mountEditor() + + await wrapper.find('input[type="checkbox"]').setValue(true) + + expect(wrapper.emitted('update:row')).toEqual([[{ ...row, isCompulsory: true }]]) + }) + + it('cancel closes and save saves', async () => { + const wrapper = mountEditor() + const buttons = wrapper.findAll('button') + + await buttons.find((b) => b.text() === 'Cancel').trigger('click') + await buttons.find((b) => b.text() === 'Save').trigger('click') + + expect(wrapper.emitted('update:open')).toEqual([[false]]) + expect(wrapper.emitted('save')).toHaveLength(1) + }) + + it('while saving both buttons are disabled and save says so', () => { + const buttons = mountEditor({ saving: true }).findAll('button') + + expect(buttons.map((b) => b.text())).toEqual(['Cancel', 'Saving…']) + expect(buttons.every((b) => b.attributes('disabled') !== undefined)).toBe(true) + }) +}) diff --git a/src/dialogs/__tests__/RoleLayoutDefaultEditorDialog.spec.js b/src/dialogs/__tests__/RoleLayoutDefaultEditorDialog.spec.js new file mode 100644 index 000000000..b57b81af1 --- /dev/null +++ b/src/dialogs/__tests__/RoleLayoutDefaultEditorDialog.spec.js @@ -0,0 +1,136 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The role layout-default editor dialog mounted: its title for an existing + * and a new row, what it emits for each edited field, and its Save and + * Cancel buttons. The other small dialogs are in smallDialogs.spec.js. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import RoleLayoutDefaultEditorDialog from '../RoleLayoutDefaultEditorDialog.vue' + +/** + * Translate as the identity, filling {placeholders}. + * + * @param {string} app The app id. + * @param {string} text The text. + * @param {object} vars The placeholders. + * @return {string} The text. + */ +const tr = (app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m)) + +const stubs = vi.hoisted(() => { + const dialog = { + name: 'NcDialog', + props: { open: { type: Boolean, default: true }, name: String }, + template: '<div v-if="open" class="dialog" :data-name="name"><slot /><slot name="actions" /></div>', + } + const button = { + name: 'NcButton', + props: ['disabled', 'variant'], + emits: ['click'], + template: '<button :disabled="disabled" :data-variant="variant" @click="$emit(\'click\')"><slot /></button>', + } + const textField = { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue', 'keyup'], + template: '<input class="field" :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" @keyup.enter="$emit(\'keyup\', $event)">', + } + const checkbox = { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<input type="checkbox" class="check" :checked="modelValue" @change="$emit(\'update:modelValue\', $event.target.checked)">', + } + return { dialog, button, textField, checkbox } +}) + +vi.mock('@nextcloud/l10n', () => ({ + t: (app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m)), + translate: (app, text) => text, +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcDialog: stubs.dialog, + NcButton: stubs.button, + NcTextField: stubs.textField, + NcCheckboxRadioSwitch: stubs.checkbox, +})) + +/** + * Mount a dialog with a global t(). + * + * @param {object} component The dialog. + * @param {object} props Its props. + * @return {object} The wrapper. + */ +const mounted = (component, props) => mount(component, { props, global: { mocks: { t: tr } } }) + +/** + * The button with this text. + * + * @param {object} wrapper The wrapper. + * @param {string} text The button text. + * @return {object} The DOM wrapper. + */ +const button = (wrapper, text) => wrapper.findAll('button').find((b) => b.text() === text) + +describe('RoleLayoutDefaultEditorDialog', () => { + const row = { id: 7, name: 'Managers', groupId: 'managers', widgetId: 'analytics', gridX: 0, gridY: 1, gridWidth: 4, gridHeight: 3, sortOrder: 2, isCompulsory: false, description: '' } + + /** + * The field with this aria-label. + * + * @param {object} wrapper The wrapper. + * @param {string} label The label. + * @return {object} The input. + */ + const field = (wrapper, label) => wrapper.get(`input[aria-label="${label}"]`) + + it('titles an existing row Edit and a new one Add', () => { + expect(mounted(RoleLayoutDefaultEditorDialog, { open: true, row }).get('.dialog').attributes('data-name')).toBe('Edit layout default') + expect(mounted(RoleLayoutDefaultEditorDialog, { open: true, row: { ...row, id: null } }).get('.dialog').attributes('data-name')).toBe('Add layout default') + }) + + it('emits the whole row with each edited field, numbers as numbers', async () => { + const wrapper = mounted(RoleLayoutDefaultEditorDialog, { open: true, row }) + + await field(wrapper, 'Name').setValue('Leads') + await field(wrapper, 'Group ID').setValue('leads') + await field(wrapper, 'Widget ID').setValue('calendar') + await field(wrapper, 'Grid X').setValue('2') + await field(wrapper, 'Grid Y').setValue('5') + await field(wrapper, 'Width (columns)').setValue('6') + await field(wrapper, 'Height (rows)').setValue('2') + await field(wrapper, 'Sort order').setValue('9') + await field(wrapper, 'Description (optional)').setValue('For leads') + await wrapper.get('input.check').setValue(true) + + expect(wrapper.emitted('update:row')).toEqual([ + [{ ...row, name: 'Leads' }], + [{ ...row, groupId: 'leads' }], + [{ ...row, widgetId: 'calendar' }], + [{ ...row, gridX: 2 }], + [{ ...row, gridY: 5 }], + [{ ...row, gridWidth: 6 }], + [{ ...row, gridHeight: 2 }], + [{ ...row, sortOrder: 9 }], + [{ ...row, description: 'For leads' }], + [{ ...row, isCompulsory: true }], + ]) + }) + + it('saves or cancels, and disables both while saving', async () => { + const idle = mounted(RoleLayoutDefaultEditorDialog, { open: true, row }) + await button(idle, 'Save').trigger('click') + await button(idle, 'Cancel').trigger('click') + expect(idle.emitted('save')).toHaveLength(1) + expect(idle.emitted('update:open')).toEqual([[false]]) + + const busy = mounted(RoleLayoutDefaultEditorDialog, { open: true, row, saving: true }) + expect(button(busy, 'Saving…').attributes('disabled')).toBeDefined() + expect(button(busy, 'Cancel').attributes('disabled')).toBeDefined() + }) +}) diff --git a/src/dialogs/__tests__/ScheduleDashboardDialog.spec.js b/src/dialogs/__tests__/ScheduleDashboardDialog.spec.js deleted file mode 100644 index e2e3a8899..000000000 --- a/src/dialogs/__tests__/ScheduleDashboardDialog.spec.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - * - * ScheduleDashboardDialog (REQ-SCHEDUI-001): go-live, take-down or both, - * as ISO strings the schedule endpoint parses; the refusal is shown. - */ - -import { mount } from '@vue/test-utils' -import { describe, expect, it, vi } from 'vitest' -import ScheduleDashboardDialog from '../ScheduleDashboardDialog.vue' - -vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) -vi.mock('@conduction/nextcloud-vue', () => ({ - NcDialog: { - name: 'NcDialog', - props: ['open'], - template: '<div v-if="open"><slot /><slot name="actions" /></div>', - }, - NcButton: { - name: 'NcButton', - props: ['disabled'], - emits: ['click'], - template: - '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', - }, -})) - -describe('ScheduleDashboardDialog', () => { - it('REQ-SCHEDUI-001: emits go-live and take-down as ISO strings', async () => { - const wrapper = mount(ScheduleDashboardDialog, { props: { open: true } }) - await wrapper - .find('[data-testid="schedule-go-live"]') - .setValue('2026-10-01T09:00') - await wrapper - .find('[data-testid="schedule-take-down"]') - .setValue('2026-10-02T17:00') - await wrapper.find('[data-testid="schedule-save"]').trigger('click') - const { publishAt, unpublishAt } = wrapper.emitted('save')[0][0] - expect(new Date(publishAt).getTime()).toBe( - new Date('2026-10-01T09:00').getTime(), - ) - expect(new Date(unpublishAt).getTime()).toBe( - new Date('2026-10-02T17:00').getTime(), - ) - }) - - it('REQ-SCHEDUI-002: a take-down alone is allowed', async () => { - const wrapper = mount(ScheduleDashboardDialog, { props: { open: true } }) - await wrapper - .find('[data-testid="schedule-take-down"]') - .setValue('2026-10-02T17:00') - await wrapper.find('[data-testid="schedule-save"]').trigger('click') - expect(wrapper.emitted('save')[0][0].publishAt).toBeNull() - }) - - it('REQ-SCHEDUI-001: shows the refusal', () => { - const wrapper = mount(ScheduleDashboardDialog, { - props: { open: true, error: 'Choose a time in the future.' }, - }) - expect(wrapper.find('[data-testid="schedule-error"]').text()).toBe( - 'Choose a time in the future.', - ) - }) -}) diff --git a/src/dialogs/__tests__/ShippedTemplateUpdateDialog.spec.js b/src/dialogs/__tests__/ShippedTemplateUpdateDialog.spec.js new file mode 100644 index 000000000..cd31507cd --- /dev/null +++ b/src/dialogs/__tests__/ShippedTemplateUpdateDialog.spec.js @@ -0,0 +1,215 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ShippedTemplateUpdateDialog (admin-templates REQ-TMPL-020): opening asks + * the server for a dry run and shows what is added, removed and changed; + * "Update" runs the real update and emits the result; a failed dry run or + * update shows its message and keeps Update disabled. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const post = vi.fn() +vi.mock('@nextcloud/axios', () => ({ default: { post: (...a) => post(...a) } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (p) => `/index.php${p}` })) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => vars[k]), +})) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcDialog: { + name: 'NcDialog', + props: ['open', 'name'], + emits: ['update:open'], + template: '<div v-if="open"><slot /><slot name="actions" /></div>', + }, + NcButton: { + name: 'NcButton', + props: ['disabled', 'variant'], + emits: ['click'], + template: '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, +})) + +const { default: ShippedTemplateUpdateDialog } = await import('../ShippedTemplateUpdateDialog.vue') + +const URL = '/index.php/apps/launchpad/api/admin/templates/shipped/7/update' +const shipped = { id: 7, name: 'Intranet' } + +/** + * Let the axios promise and the follow-up render settle. + * + * @param {object} wrapper the mounted dialog. + */ +async function settle(wrapper) { + await new Promise((resolve) => setTimeout(resolve, 0)) + await wrapper.vm.$nextTick() +} + +/** + * Build a dry-run plan. + * + * @param {object} overrides fields to replace. + * @return {object} the plan. + */ +function plan(overrides = {}) { + return { + name: 'Intranet', + installedVersion: '1.0', + version: '1.2', + added: [], + removed: [], + changed: [], + copies: 3, + ...overrides, + } +} + +beforeEach(() => { + post.mockReset() +}) + +describe('ShippedTemplateUpdateDialog — dry run', () => { + it('asks for a dry run when mounted open and shows the plan', async () => { + post.mockResolvedValue({ + data: plan({ + added: ['news'], + removed: ['clock'], + changed: [{ widget: 'weather' }], + }), + }) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + expect(wrapper.find('[data-testid="shipped-update-loading"]').exists()).toBe(true) + await settle(wrapper) + + expect(post).toHaveBeenCalledTimes(1) + expect(post).toHaveBeenCalledWith(URL, { dryRun: true }) + expect(wrapper.find('[data-testid="shipped-update-loading"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="shipped-update-plan"]').text()).toContain( + 'This brings "Intranet" from version 1.0 to version 1.2.', + ) + expect(wrapper.find('[data-testid="shipped-update-added"]').text()).toBe('news') + expect(wrapper.find('[data-testid="shipped-update-removed"]').text()).toBe('clock') + expect(wrapper.find('[data-testid="shipped-update-changed"]').text()).toBe('weather') + expect(wrapper.find('[data-testid="shipped-update-nothing"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="shipped-update-copies"]').text()).toBe( + 'Members with a copy of this template: 3. Their copies follow. A widget a member added stays.', + ) + expect(wrapper.vm.hasChanges).toBe(true) + }) + + it('says the widgets stay when nothing is added, removed or changed', async () => { + post.mockResolvedValue({ data: plan() }) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + await settle(wrapper) + expect(wrapper.vm.hasChanges).toBe(false) + expect(wrapper.find('[data-testid="shipped-update-nothing"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="shipped-update-added"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="shipped-update-removed"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="shipped-update-changed"]').exists()).toBe(false) + }) + + it('reports no changes before a plan is loaded', () => { + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: false, shipped } }) + expect(wrapper.vm.hasChanges).toBe(false) + }) + + it('does not ask while closed, and asks once it opens', async () => { + post.mockResolvedValue({ data: plan() }) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: false, shipped } }) + await settle(wrapper) + expect(post).not.toHaveBeenCalled() + await wrapper.setProps({ open: true }) + await settle(wrapper) + expect(post).toHaveBeenCalledWith(URL, { dryRun: true }) + }) + + it('does not ask without a template', async () => { + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped: null } }) + await settle(wrapper) + expect(post).not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="shipped-update-confirm"]').attributes('disabled')).toBeDefined() + }) + + it('shows an error and keeps Update disabled when the dry run fails', async () => { + post.mockRejectedValue(new Error('500')) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + await settle(wrapper) + expect(wrapper.find('[data-testid="shipped-update-error"]').text()).toBe( + 'The changes could not be worked out. Nothing was updated.', + ) + expect(wrapper.vm.plan).toBeNull() + expect(wrapper.vm.loading).toBe(false) + expect(wrapper.find('[data-testid="shipped-update-confirm"]').attributes('disabled')).toBeDefined() + }) + + it('clears an earlier error when the plan is loaded again', async () => { + post.mockRejectedValueOnce(new Error('500')).mockResolvedValueOnce({ data: plan() }) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + await settle(wrapper) + await wrapper.setProps({ open: false }) + await wrapper.setProps({ open: true }) + await settle(wrapper) + expect(wrapper.vm.errorMessage).toBe('') + expect(wrapper.find('[data-testid="shipped-update-plan"]').exists()).toBe(true) + }) +}) + +describe('ShippedTemplateUpdateDialog — update', () => { + it('runs the real update and emits its result', async () => { + post + .mockResolvedValueOnce({ data: plan({ added: ['news'] }) }) + .mockResolvedValueOnce({ data: { id: 7, version: '1.2' } }) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + await settle(wrapper) + const confirm = wrapper.find('[data-testid="shipped-update-confirm"]') + expect(confirm.attributes('disabled')).toBeUndefined() + await confirm.trigger('click') + await settle(wrapper) + expect(post).toHaveBeenNthCalledWith(2, URL, { dryRun: false }) + expect(wrapper.emitted('updated')).toEqual([[{ id: 7, version: '1.2' }]]) + expect(wrapper.vm.updating).toBe(false) + }) + + it('names the template and drops the plan when the update fails', async () => { + post + .mockResolvedValueOnce({ data: plan() }) + .mockRejectedValueOnce(new Error('409')) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + await settle(wrapper) + await wrapper.vm.confirm() + await settle(wrapper) + expect(wrapper.emitted('updated')).toBeUndefined() + expect(wrapper.vm.plan).toBeNull() + expect(wrapper.vm.updating).toBe(false) + expect(wrapper.find('[data-testid="shipped-update-error"]').text()).toBe( + 'The template "Intranet" could not be updated.', + ) + }) + + it('disables Update while an update is in flight', async () => { + post.mockResolvedValueOnce({ data: plan() }) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + await settle(wrapper) + wrapper.vm.updating = true + await wrapper.vm.$nextTick() + expect(wrapper.find('[data-testid="shipped-update-confirm"]').attributes('disabled')).toBeDefined() + }) +}) + +describe('ShippedTemplateUpdateDialog — closing', () => { + it('asks the parent to close on Cancel', async () => { + post.mockResolvedValue({ data: plan() }) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + await wrapper.find('[data-testid="shipped-update-cancel"]').trigger('click') + expect(wrapper.emitted('update:open')).toEqual([[false]]) + }) + + it('passes a close from the dialog chrome on to the parent', async () => { + post.mockResolvedValue({ data: plan() }) + const wrapper = mount(ShippedTemplateUpdateDialog, { props: { open: true, shipped } }) + wrapper.findComponent({ name: 'NcDialog' }).vm.$emit('update:open', false) + expect(wrapper.emitted('update:open')).toEqual([[false]]) + }) +}) diff --git a/src/dialogs/__tests__/dialogActions.golden.spec.js b/src/dialogs/__tests__/dialogActions.golden.spec.js new file mode 100644 index 000000000..7888a597c --- /dev/null +++ b/src/dialogs/__tests__/dialogActions.golden.spec.js @@ -0,0 +1,149 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for the footer of ReadConfirmationDialog: per filled-in state, the footer buttons (label, + * disabled) and the events that Cancel and the primary button emit, compared + * with fixtures/dialogActions.golden.json case by case. The CnDialogActions + * double follows nc-vue's component: a cancel button and a primary button + * disabled while saving or when canSubmit is false. Set RECORD_GOLDEN=1 to + * rewrite it. + */ + +import { mount } from '@vue/test-utils' +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import ReadConfirmationDialog from '../ReadConfirmationDialog.vue' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, text) => text })) +vi.mock('@conduction/nextcloud-vue', () => ({ + NcDialog: { + name: 'NcDialog', + props: ['open', 'name'], + emits: ['update:open'], + template: + '<div v-if="open"><slot /><footer><slot name="actions" /></footer></div>', + }, + NcButton: { + name: 'NcButton', + props: ['disabled', 'variant'], + emits: ['click'], + template: + '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + CnDialogActions: { + name: 'CnDialogActions', + props: { + saving: { type: Boolean, default: false }, + canSubmit: { type: Boolean, default: true }, + confirmLabel: { type: String, default: 'Save' }, + cancelLabel: { type: String, default: 'Cancel' }, + variant: { type: String, default: 'primary' }, + confirmIcon: { type: String, default: '' }, + }, + emits: ['cancel', 'submit'], + template: + '<button :disabled="saving" @click="$emit(\'cancel\')">{{ cancelLabel }}</button><button :disabled="saving || !canSubmit" @click="$emit(\'submit\')">{{ confirmLabel }}</button>', + }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<label><slot /></label>', + }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label', 'placeholder'], + emits: ['update:modelValue'], + template: '<input />', + }, +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/dialogActions.golden.json') + +const CONFIRMATIONS = { + 'no placement': { placement: null }, + 'asks with prompt and deadline': { + placement: { + requiresAcknowledgement: '1', + acknowledgementPrompt: 'Read it', + acknowledgementDeadline: '2026-12-01', + }, + }, + 'asks, blank prompt': { + placement: { requiresAcknowledgement: 1, acknowledgementPrompt: ' ' }, + }, + 'switched on in the dialog': { + placement: { requiresAcknowledgement: 0 }, + ask: true, + prompt: ' Got it ', + }, +} + +/** + * An emitted value with every ISO timestamp written back as the viewer's + * local `YYYY-MM-DDTHH:mm`, so the recording does not depend on the time zone. + * + * @param {unknown} value The emitted events. + * @return {unknown} The same events, time zone free. + */ +function local(value) { + return JSON.parse( + JSON.stringify(value, (_key, entry) => { + if (typeof entry !== 'string' || !/^\d{4}-\d\d-\d\dT.*Z$/.test(entry)) { + return entry + } + const date = new Date(entry) + const pad = (n) => String(n).padStart(2, '0') + return `local ${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}` + }), + ) +} + +/** + * The footer buttons and what clicking each emits, each on a fresh mount. + * + * @param {Function} make Mounts the dialog in its state. + * @return {Promise<object>} The outcome. + */ +async function footer(make) { + const first = await make() + const buttons = first.findAll('footer button').map((b) => ({ + text: b.text(), + disabled: b.attributes('disabled') !== undefined, + })) + const clicks = {} + for (let index = 0; index < buttons.length; index++) { + const wrapper = await make() + await wrapper.findAll('footer button').at(index).trigger('click') + clicks[buttons[index].text] = local(wrapper.emitted()) + delete clicks[buttons[index].text].click + } + return { buttons, clicks } +} + +describe('dialog footers (golden)', () => { + it('matches the recorded outcomes case by case', async () => { + const actual = {} + for (const [name, state] of Object.entries(CONFIRMATIONS)) { + actual[`read confirmation | ${name}`] = await footer(async () => { + const wrapper = mount(ReadConfirmationDialog, { + props: { open: true, placement: state.placement }, + }) + if ('ask' in state) { + await wrapper.setData({ ask: state.ask, prompt: state.prompt }) + } + return wrapper + }) + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const [name, value] of Object.entries(expected)) { + expect(actual[name], name).toEqual(value) + } + }) +}) diff --git a/src/dialogs/__tests__/fixtures/dialogActions.golden.json b/src/dialogs/__tests__/fixtures/dialogActions.golden.json new file mode 100644 index 000000000..02302f571 --- /dev/null +++ b/src/dialogs/__tests__/fixtures/dialogActions.golden.json @@ -0,0 +1,130 @@ +{ + "read confirmation | no placement": { + "buttons": [ + { + "text": "Cancel", + "disabled": false + }, + { + "text": "Save", + "disabled": false + } + ], + "clicks": { + "Cancel": { + "update:open": [ + [ + false + ] + ] + }, + "Save": { + "save": [ + [ + { + "requiresAcknowledgement": 0, + "acknowledgementPrompt": null, + "acknowledgementDeadline": null + } + ] + ] + } + } + }, + "read confirmation | asks with prompt and deadline": { + "buttons": [ + { + "text": "Cancel", + "disabled": false + }, + { + "text": "Save", + "disabled": false + } + ], + "clicks": { + "Cancel": { + "update:open": [ + [ + false + ] + ] + }, + "Save": { + "save": [ + [ + { + "requiresAcknowledgement": 1, + "acknowledgementPrompt": "Read it", + "acknowledgementDeadline": "2026-12-01" + } + ] + ] + } + } + }, + "read confirmation | asks, blank prompt": { + "buttons": [ + { + "text": "Cancel", + "disabled": false + }, + { + "text": "Save", + "disabled": false + } + ], + "clicks": { + "Cancel": { + "update:open": [ + [ + false + ] + ] + }, + "Save": { + "save": [ + [ + { + "requiresAcknowledgement": 1, + "acknowledgementPrompt": null, + "acknowledgementDeadline": null + } + ] + ] + } + } + }, + "read confirmation | switched on in the dialog": { + "buttons": [ + { + "text": "Cancel", + "disabled": false + }, + { + "text": "Save", + "disabled": false + } + ], + "clicks": { + "Cancel": { + "update:open": [ + [ + false + ] + ] + }, + "Save": { + "save": [ + [ + { + "requiresAcknowledgement": 1, + "acknowledgementPrompt": "Got it", + "acknowledgementDeadline": null + } + ] + ] + } + } + } +} diff --git a/src/dialogs/__tests__/smallDialogs.spec.js b/src/dialogs/__tests__/smallDialogs.spec.js new file mode 100644 index 000000000..7b2afb313 --- /dev/null +++ b/src/dialogs/__tests__/smallDialogs.spec.js @@ -0,0 +1,157 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The three small dashboard dialogs: rename (only a changed, non-blank name + * is confirmed, trimmed), delete (names the dashboards deleted with it) and + * the public-share password prompt (unlocks unless a check is running). + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (match, key) => (key in vars ? String(vars[key]) : match)), + translate: (_app, text) => text, +})) + +const dialog = { + name: 'NcDialog', + props: ['open', 'name', 'noClose'], + emits: ['update:open'], + template: '<div class="dialog" :data-name="name"><slot /><slot name="actions" /></div>', +} +const button = { + name: 'NcButton', + props: ['variant', 'disabled'], + emits: ['click'], + template: '<button :class="variant" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', +} +const field = { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue', 'keyup'], + template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" @keyup="$emit(\'keyup\', $event)" />', +} + +vi.mock('@conduction/nextcloud-vue', () => ({ NcDialog: dialog, NcButton: button, NcTextField: field })) +vi.mock('@nextcloud/vue/components/NcDialog', () => ({ default: dialog })) +vi.mock('@nextcloud/vue/components/NcButton', () => ({ default: button })) +vi.mock('@nextcloud/vue/components/NcPasswordField', () => ({ default: { ...field, name: 'NcPasswordField' } })) +vi.mock('@nextcloud/vue/components/NcNoteCard', () => ({ + default: { name: 'NcNoteCard', props: ['type'], template: '<div class="note"><slot /></div>' }, +})) + +const { default: GroupDashboardRenameDialog } = await import('../GroupDashboardRenameDialog.vue') +const { default: DeleteDashboardDialog } = await import('../DeleteDashboardDialog.vue') +const { default: PublicSharePasswordDialog } = await import('../PublicSharePasswordDialog.vue') + +describe('GroupDashboardRenameDialog', () => { + const rename = (wrapper) => wrapper.findAll('button').find((b) => b.text() === 'Rename') + + it('starts from the current name with Rename disabled', () => { + const wrapper = mount(GroupDashboardRenameDialog, { props: { open: true, currentName: 'Team' } }) + + expect(wrapper.find('input').element.value).toBe('Team') + expect(rename(wrapper).attributes('disabled')).toBeDefined() + }) + + it('confirms a changed name, trimmed', async () => { + const wrapper = mount(GroupDashboardRenameDialog, { props: { open: true, currentName: 'Team' } }) + + await wrapper.find('input').setValue(' Sales ') + await rename(wrapper).trigger('click') + + expect(wrapper.emitted('confirm')).toEqual([['Sales']]) + }) + + it('confirms on Enter too', async () => { + const wrapper = mount(GroupDashboardRenameDialog, { props: { open: true, currentName: 'Team' } }) + + await wrapper.find('input').setValue('Ops') + await wrapper.find('input').trigger('keyup.enter') + + expect(wrapper.emitted('confirm')).toEqual([['Ops']]) + }) + + it('does not confirm a blank or unchanged name', async () => { + const wrapper = mount(GroupDashboardRenameDialog, { props: { open: true, currentName: 'Team' } }) + + await wrapper.find('input').setValue(' ') + await wrapper.find('input').trigger('keyup.enter') + await wrapper.find('input').setValue(' Team ') + await wrapper.find('input').trigger('keyup.enter') + + expect(wrapper.emitted('confirm')).toBeUndefined() + }) + + it('resets the draft when reopened and closes on Cancel', async () => { + const wrapper = mount(GroupDashboardRenameDialog, { props: { open: true, currentName: 'Team' } }) + await wrapper.find('input').setValue('Draft') + await wrapper.setProps({ open: false, currentName: 'Renamed' }) + await wrapper.setProps({ open: true }) + + expect(wrapper.find('input').element.value).toBe('Renamed') + + await wrapper.findAll('button').find((b) => b.text() === 'Cancel').trigger('click') + expect(wrapper.emitted('update:open')).toEqual([[false]]) + }) +}) + +describe('DeleteDashboardDialog', () => { + it('names the dashboard and confirms on Delete', async () => { + const wrapper = mount(DeleteDashboardDialog, { props: { open: true, name: 'Team' } }) + + expect(wrapper.text()).toContain('Delete Team? This cannot be undone.') + expect(wrapper.find('[data-testid="delete-dashboard-children"]').exists()).toBe(false) + + await wrapper.find('[data-testid="delete-dashboard-confirm"]').trigger('click') + expect(wrapper.emitted('confirm')).toHaveLength(1) + }) + + it('names how many dashboards are deleted with it', () => { + const wrapper = mount(DeleteDashboardDialog, { props: { open: true, name: 'Team', childCount: 3 } }) + + expect(wrapper.find('[data-testid="delete-dashboard-children"]').text()) + .toBe('Dashboards under Team: 3. They are deleted with it.') + }) + + it('closes on Cancel without confirming', async () => { + const wrapper = mount(DeleteDashboardDialog, { props: { open: true, name: 'Team' } }) + + await wrapper.findAll('button').find((b) => b.text() === 'Cancel').trigger('click') + + expect(wrapper.emitted('update:open')).toEqual([[false]]) + expect(wrapper.emitted('confirm')).toBeUndefined() + }) +}) + +describe('PublicSharePasswordDialog', () => { + it('unlocks with the typed password', async () => { + const wrapper = mount(PublicSharePasswordDialog) + + await wrapper.find('input').setValue('s3cret') + await wrapper.find('button').trigger('click') + await wrapper.find('input').trigger('keyup.enter') + + expect(wrapper.emitted('unlock')).toEqual([['s3cret'], ['s3cret']]) + }) + + it('does not unlock while a check is running', async () => { + const wrapper = mount(PublicSharePasswordDialog, { props: { loading: true } }) + + await wrapper.find('input').setValue('x') + await wrapper.find('input').trigger('keyup.enter') + + expect(wrapper.find('button').attributes('disabled')).toBeDefined() + expect(wrapper.emitted('unlock')).toBeUndefined() + }) + + it('shows the error only when there is one', async () => { + const wrapper = mount(PublicSharePasswordDialog) + expect(wrapper.find('.note').exists()).toBe(false) + + await wrapper.setProps({ error: 'Wrong password' }) + expect(wrapper.find('.note').text()).toBe('Wrong password') + }) +}) diff --git a/src/embed-entry.js b/src/embed-entry.js new file mode 100644 index 000000000..a48f69ab5 --- /dev/null +++ b/src/embed-entry.js @@ -0,0 +1,38 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Embed entry point (embedded-analytics task 23). Boots `EmbedView` in the + * page `templates/embed.php` serves at `/apps/launchpad/embed/{subjectType}/{subjectId}`. + * The view reads its subject from the path and its token from `?token=` or + * the SDK's handshake, verifies the parent's origin against the token's host + * origins and relays events to it. + */ + +import { + registerBuiltinDashboardWidgets, + registerTranslations, +} from '@conduction/nextcloud-vue' +import { translatePlural as n, translate as t } from '@nextcloud/l10n' +import { createPinia } from 'pinia' +import { createApp, h } from 'vue' +import EmbedView from './views/EmbedView.vue' + +import './publicPath.js' +import 'gridstack/dist/gridstack.min.css' +import '@conduction/nextcloud-vue/css/index.css' + +// Widget types self-register on import; see public.js. +registerBuiltinDashboardWidgets() +registerTranslations() + +const app = createApp({ + name: 'LaunchpadEmbedRoot', + render: () => h(EmbedView), +}) + +app.mixin({ methods: { t, n } }) +app.use(createPinia()) +app.mount('#embed-vue') + +export default app diff --git a/src/embed-sdk/README.md b/src/embed-sdk/README.md new file mode 100644 index 000000000..0ee107c31 --- /dev/null +++ b/src/embed-sdk/README.md @@ -0,0 +1,80 @@ +# LaunchPad embed SDK + +Embed a LaunchPad widget or dashboard in any web page with an embed token. + +An administrator issues the token in LaunchPad (Admin settings, Embed tokens) for one widget or +dashboard and the exact origins of the pages that may show it. The token is shown once. + +The SDK is served by your Nextcloud instance, with the app, so it always matches the LaunchPad +version that renders the embed. It is not published on npm. + +| File | Address | +| --- | --- | +| UMD bundle (global `LaunchPadEmbed`) | `https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.umd.js` | +| ES module | `https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.esm.js` | + +Both are public, may be loaded from any origin and are cached for a day. Add `?v=<app version>` +to load a new copy after an upgrade; the `X-LaunchPad-Version` header names the version served. + +## Plain iframe + +```html +<iframe + src="https://cloud.example.nl/index.php/apps/launchpad/embed/widget/42?token=<jwt>" + title="Open requests" + style="border: 0; width: 100%; height: 400px"></iframe> +``` + +## Script tag (UMD) + +```html +<script src="https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.umd.js"></script> +<script> + LaunchPadEmbed.render(document.getElementById('woo'), { + baseUrl: 'https://cloud.example.nl/index.php/apps/launchpad', + token: '<jwt>', + subjectType: 'widget', + subjectId: '42', + }) +</script> +``` + +## JavaScript (ESM) + +```js +import { LaunchPadEmbed } from 'https://cloud.example.nl/index.php/apps/launchpad/embed-sdk/embed-sdk.esm.js' + +const embed = await LaunchPadEmbed.render(document.getElementById('woo'), { + baseUrl: 'https://cloud.example.nl/index.php/apps/launchpad', + token: '<jwt>', + subjectType: 'widget', + subjectId: '42', + title: 'Open requests', +}) + +embed.on('filterApplied', (filter) => console.log(filter)) +embed.on('error', ({ error, message }) => console.warn(error, message)) +window.addEventListener('resize', () => embed.resize()) +``` + +`render()` resolves once the embed has loaded and accepted the handshake; it rejects when the +embed refuses (for instance `origin_mismatch` when the page is not one of the token's origins). + +## TypeScript + +The types are in `src/types.ts` in the LaunchPad repository: `EmbedConfig`, `EmbedInstance`, +`EmbedEventType`. Copy them into your project, or declare the module yourself. + +## Security + +- Messages are only accepted from the embed's own window at the LaunchPad origin, and only + posted to that origin, never `*`. +- The embed answers only a parent page whose origin the token lists; the server also refuses + framing from other origins (`Content-Security-Policy: frame-ancestors`). +- A read token cannot change anything, whatever runs in the page: writes are refused by the + server. + +## Releases + +The SDK is built with the app (`npm run build` runs `npm run build:embed-sdk`, which writes +`js/embed-sdk/`), so every LaunchPad release carries its own SDK. diff --git a/src/embed-sdk/__tests__/LaunchPadEmbed.spec.js b/src/embed-sdk/__tests__/LaunchPadEmbed.spec.js new file mode 100644 index 000000000..e302042b0 --- /dev/null +++ b/src/embed-sdk/__tests__/LaunchPadEmbed.spec.js @@ -0,0 +1,207 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @conduction/launchpad-embed: render creates the iframe and completes the + * handshake, events reach every listener until removed, resize posts and + * resolves, messages from any other window or origin are ignored, and two + * embeds on one page do not hear each other (embedded-analytics task 34). + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-006--js-sdk-exposes-render-event-and-resize-apis + */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { embedUrl, LaunchPadEmbed } from '../src/LaunchPadEmbed.js' +import { decodeClaims, isFrom, MESSAGES, originOf, post } from '../src/postMessage.js' + +const BASE = 'https://cloud.example.nl/index.php/apps/launchpad' +const ORIGIN = 'https://cloud.example.nl' +const CONFIG = { baseUrl: BASE, token: 'h.p.s', subjectType: 'widget', subjectId: '42', timeout: 200 } + +/** + * Deliver a message to the host page as if the given window sent it. + * + * @param {object} data The message. + * @param {Window} source The sender. + * @param {string} [origin] The sender's origin. + */ +function deliver(data, source, origin = ORIGIN) { + window.dispatchEvent(new MessageEvent('message', { data, source, origin })) +} + +/** + * Render an embed and play the iframe's side of the handshake. + * + * @param {object} [config] The embed config. + * @return {Promise<{embed: object, iframe: HTMLIFrameElement, posted: object}>} + */ +async function rendered(config = CONFIG) { + const container = document.createElement('div') + document.body.appendChild(container) + const pending = LaunchPadEmbed.render(container, config) + const iframe = container.querySelector('iframe') + const posted = vi.spyOn(iframe.contentWindow, 'postMessage') + iframe.dispatchEvent(new Event('load')) + const [init, target] = posted.mock.calls[0] + deliver({ type: MESSAGES.ready, nonce: init.nonce }, iframe.contentWindow) + const embed = await pending + return { embed, iframe, posted, init, target } +} + +afterEach(() => { + document.body.innerHTML = '' + vi.restoreAllMocks() +}) + +describe('LaunchPadEmbed.render', () => { + it('creates the iframe and hands the token over to the LaunchPad origin only', async () => { + const { embed, iframe, init, target } = await rendered() + + expect(iframe.src).toBe(`${BASE}/embed/widget/42?token=h.p.s`) + expect(iframe.title).toBe('LaunchPad') + expect(iframe.getAttribute('referrerpolicy')).toBe('strict-origin-when-cross-origin') + expect(init).toMatchObject({ type: MESSAGES.init, token: 'h.p.s' }) + expect(typeof init.nonce).toBe('string') + expect(target).toBe(ORIGIN) + expect(embed.iframe).toBe(iframe) + }) + + it('rejects and removes the iframe when the embed refuses the handshake', async () => { + const container = document.body.appendChild(document.createElement('div')) + const pending = LaunchPadEmbed.render(container, CONFIG) + const iframe = container.querySelector('iframe') + const posted = vi.spyOn(iframe.contentWindow, 'postMessage') + iframe.dispatchEvent(new Event('load')) + deliver({ type: MESSAGES.error, nonce: posted.mock.calls[0][0].nonce, error: 'origin_mismatch', message: 'Not here' }, iframe.contentWindow) + + await expect(pending).rejects.toMatchObject({ message: 'Not here', code: 'origin_mismatch' }) + expect(container.querySelector('iframe')).toBeNull() + }) + + it('rejects when the embed never answers', async () => { + const container = document.body.appendChild(document.createElement('div')) + const pending = LaunchPadEmbed.render(container, { ...CONFIG, timeout: 10 }) + container.querySelector('iframe').dispatchEvent(new Event('load')) + + await expect(pending).rejects.toThrow('did not answer launchpad-embed:init in time') + }) + + it('refuses an incomplete config before creating anything', async () => { + const container = document.createElement('div') + + await expect(LaunchPadEmbed.render(container, { ...CONFIG, token: '' })).rejects.toThrow('config.token') + await expect(LaunchPadEmbed.render(container, { ...CONFIG, subjectType: 'report' })).rejects.toThrow('subjectType') + await expect(LaunchPadEmbed.render(null, CONFIG)).rejects.toThrow('container') + expect(container.children).toHaveLength(0) + }) + + it('encodes the subject and passes the viewport on', () => { + expect(embedUrl({ ...CONFIG, baseUrl: `${BASE}/`, subjectType: 'dashboard', subjectId: 'a b/c', viewport: 'small' })) + .toBe(`${BASE}/embed/dashboard/a%20b%2Fc?token=h.p.s&viewport=small`) + }) +}) + +describe('an embed instance', () => { + it('relays events to every listener until they are removed', async () => { + const { embed, iframe } = await rendered() + const first = vi.fn() + const second = vi.fn() + embed.on('filterApplied', first).on('filterApplied', second) + + deliver({ type: MESSAGES.event, event: 'filterApplied', payload: { gemeente: 'Zeist' } }, iframe.contentWindow) + embed.off('filterApplied', first) + deliver({ type: MESSAGES.event, event: 'filterApplied', payload: { gemeente: 'Utrecht' } }, iframe.contentWindow) + embed.off('filterApplied') + deliver({ type: MESSAGES.event, event: 'filterApplied', payload: {} }, iframe.contentWindow) + + expect(first.mock.calls).toEqual([[{ gemeente: 'Zeist' }]]) + expect(second.mock.calls).toEqual([[{ gemeente: 'Zeist' }], [{ gemeente: 'Utrecht' }]]) + expect(() => embed.on('export', 'not a function')).toThrow(TypeError) + }) + + it('ignores messages from another origin, another window or of another kind', async () => { + const { embed, iframe } = await rendered() + const handler = vi.fn() + embed.on('drillDown', handler) + + deliver({ type: MESSAGES.event, event: 'drillDown', payload: 1 }, iframe.contentWindow, 'https://evil.example.com') + deliver({ type: MESSAGES.event, event: 'drillDown', payload: 2 }, window) + deliver({ type: 'other:event', event: 'drillDown', payload: 3 }, iframe.contentWindow) + deliver('launchpad-embed:event', iframe.contentWindow) + + expect(handler).not.toHaveBeenCalled() + }) + + it('reports an unsolicited refusal as an error event', async () => { + const { embed, iframe } = await rendered() + const handler = vi.fn() + embed.on('error', handler) + + deliver({ type: MESSAGES.error, error: 'token_revoked', message: 'Withdrawn' }, iframe.contentWindow) + + expect(handler).toHaveBeenCalledWith({ error: 'token_revoked', message: 'Withdrawn' }) + }) + + it('posts the container size on resize and resolves with what the embed took', async () => { + const { embed, iframe, posted } = await rendered() + Object.defineProperty(iframe.parentElement, 'clientWidth', { value: 640, configurable: true }) + Object.defineProperty(iframe.parentElement, 'clientHeight', { value: 360, configurable: true }) + + const resizing = embed.resize() + const [message, target] = posted.mock.calls.at(-1) + expect(message).toMatchObject({ type: MESSAGES.resize, width: 640, height: 360 }) + expect(target).toBe(ORIGIN) + deliver({ type: MESSAGES.resized, nonce: message.nonce, width: 640, height: 412 }, iframe.contentWindow) + + await expect(resizing).resolves.toEqual({ width: 640, height: 412 }) + }) + + it('keeps two embeds on one page apart', async () => { + const one = await rendered() + const two = await rendered({ ...CONFIG, subjectId: '43' }) + const heardByOne = vi.fn() + const heardByTwo = vi.fn() + one.embed.on('export', heardByOne) + two.embed.on('export', heardByTwo) + + deliver({ type: MESSAGES.event, event: 'export', payload: 'two' }, two.iframe.contentWindow) + + expect(heardByOne).not.toHaveBeenCalled() + expect(heardByTwo).toHaveBeenCalledWith('two') + }) + + it('rejects pending requests and stops listening once destroyed', async () => { + const { embed, iframe } = await rendered() + const handler = vi.fn() + embed.on('export', handler) + const resizing = embed.resize() + + embed.destroy() + deliver({ type: MESSAGES.event, event: 'export', payload: 1 }, iframe.contentWindow) + + await expect(resizing).rejects.toThrow('destroyed') + expect(handler).not.toHaveBeenCalled() + expect(document.querySelector('iframe[src*="/embed/widget/42"]')).toBeNull() + }) +}) + +describe('the message helpers', () => { + it('never post to every origin', () => { + const target = { postMessage: vi.fn() } + + expect(() => post(target, '*', MESSAGES.event)).toThrow('explicit origin') + post(target, ORIGIN, MESSAGES.event, { event: 'export' }) + expect(target.postMessage).toHaveBeenCalledWith({ event: 'export', type: MESSAGES.event }, ORIGIN) + }) + + it('read origins and unverified claims defensively', () => { + const claims = btoa(JSON.stringify({ iss: 'launchpad', hostOrigins: ['https://www.zeist.nl'] })).replace(/=+$/, '') + + expect(originOf('https://WWW.Zeist.nl/woo/')).toBe('https://www.zeist.nl') + expect(originOf('not a url')).toBe('') + expect(decodeClaims(`h.${claims}.s`)).toEqual({ iss: 'launchpad', hostOrigins: ['https://www.zeist.nl'] }) + expect(decodeClaims('h.!!!.s')).toEqual({}) + expect(decodeClaims('only-one-part')).toEqual({}) + expect(isFrom({ data: null, source: window, origin: ORIGIN }, { origin: ORIGIN, source: window })).toBe(false) + }) +}) diff --git a/src/embed-sdk/__tests__/dist.spec.js b/src/embed-sdk/__tests__/dist.spec.js new file mode 100644 index 000000000..248a1850c --- /dev/null +++ b/src/embed-sdk/__tests__/dist.spec.js @@ -0,0 +1,81 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The embed SDK builds into an ES module and a UMD bundle under the app's + * js/embed-sdk/, the names EmbedSdkController serves, and both expose render() + * (embedded-analytics tasks 19 and 24). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-19 + * @spec openspec/changes/embedded-analytics/tasks.md#task-24 + */ + +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { createRequire } from 'node:module' +import { join, resolve } from 'node:path' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + +const require = createRequire(__filename) +const webpack = require('webpack') +const configs = require('../webpack.config.cjs') + +let out + +/** + * Run the SDK build into a temporary directory. + * + * @return {Promise<void>} + */ +function build() { + const local = configs.map((config) => ({ ...config, output: { ...config.output, path: out } })) + return new Promise((resolve, reject) => { + webpack(local, (error, stats) => { + if (error || stats.hasErrors()) { + reject(error ?? new Error(stats.toString('errors-only'))) + return + } + resolve() + }) + }) +} + +describe('embed-sdk distribution', () => { + beforeAll(async () => { + out = mkdtempSync(join(__dirname, '.dist-')) + await build() + }, 60000) + + afterAll(() => { + rmSync(out, { recursive: true, force: true }) + }) + + it('builds one ESM and one UMD bundle into the app\'s js/embed-sdk/, the names the app serves', () => { + expect(configs.map((config) => config.output.filename)).toEqual(['embed-sdk.esm.js', 'embed-sdk.umd.js']) + for (const config of configs) { + expect(config.output.path).toBe(resolve(__dirname, '../../../js/embed-sdk')) + } + const controller = readFileSync(resolve(__dirname, '../../../lib/Controller/EmbedSdkController.php'), 'utf8') + expect(controller).toContain("'embed-sdk.esm.js'") + expect(controller).toContain("'embed-sdk.umd.js'") + }) + + it('is not an npm package: private, and the app build builds it', () => { + const pkg = JSON.parse(readFileSync(resolve(__dirname, '../package.json'), 'utf8')) + const app = JSON.parse(readFileSync(resolve(__dirname, '../../../package.json'), 'utf8')) + expect(pkg.private).toBe(true) + expect(pkg.publishConfig).toBeUndefined() + expect(app.scripts.build).toContain('npm run build:embed-sdk') + }) + + it('the ES module exports render and LaunchPadEmbed', async () => { + const sdk = await import(/* @vite-ignore */ join(out, 'embed-sdk.esm.js')) + expect(typeof sdk.render).toBe('function') + expect(typeof sdk.default.render).toBe('function') + }) + + it('the UMD bundle sets the LaunchPadEmbed global', () => { + const scope = {} + new Function(readFileSync(join(out, 'embed-sdk.umd.js'), 'utf8')).call(scope) + expect(typeof scope.LaunchPadEmbed.render).toBe('function') + }) +}) diff --git a/src/embed-sdk/package.json b/src/embed-sdk/package.json new file mode 100644 index 000000000..83cfea95c --- /dev/null +++ b/src/embed-sdk/package.json @@ -0,0 +1,8 @@ +{ + "private": true, + "description": "The LaunchPad embed SDK, built into js/embed-sdk/ and served by the app at /apps/launchpad/embed-sdk/.", + "license": "EUPL-1.2", + "sideEffects": false, + "type": "module", + "types": "src/types.ts" +} diff --git a/src/embed-sdk/src/LaunchPadEmbed.js b/src/embed-sdk/src/LaunchPadEmbed.js new file mode 100644 index 000000000..080272608 --- /dev/null +++ b/src/embed-sdk/src/LaunchPadEmbed.js @@ -0,0 +1,263 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * @conduction/launchpad-embed — embed a LaunchPad widget or dashboard in any page + * (embedded-analytics tasks 19-22, REQ-EMB-006). + * + * const embed = await LaunchPadEmbed.render(container, { + * baseUrl: 'https://cloud.example.nl/index.php/apps/launchpad', + * token, subjectType: 'widget', subjectId: '42', + * }) + * embed.on('filterApplied', (payload) => …) + * await embed.resize() + * + * The iframe page needs the token to load, so its URL carries it; the + * handshake then hands the token over by postMessage for the embed's own + * requests and proves both ends: the SDK accepts messages only from the + * iframe's window at the LaunchPad origin, and the iframe answers only a + * parent whose origin the token lists. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-006--js-sdk-exposes-render-event-and-resize-apis + */ + +import { isFrom, MESSAGES, originOf, post } from './postMessage.js' + +const DEFAULT_TIMEOUT = 10000 + +/** + * A random handshake nonce. + * + * @return {string} + */ +function nonce() { + if (globalThis.crypto?.randomUUID) { + return globalThis.crypto.randomUUID() + } + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}` +} + +/** + * One rendered embed: its iframe, its listeners and its resize. + */ +export class EmbedInstance { + + /** + * @param {HTMLIFrameElement} iframe The embed's iframe. + * @param {string} origin The LaunchPad origin. + * @param {Window} host The host page's window. + * @param {number} timeout Milliseconds to wait for an answer. + */ + constructor(iframe, origin, host, timeout) { + this.iframe = iframe + this.origin = origin + this.host = host + this.timeout = timeout + this.listeners = new Map() + this.pending = new Map() + this.onMessage = this.receive.bind(this) + host.addEventListener('message', this.onMessage) + } + + /** + * Listen for an event the embed relays (filterApplied, drillDown, export, error, …). + * + * @param {string} eventType The event. + * @param {(payload: unknown) => void} handler Called with the event's payload. + * @return {EmbedInstance} This embed, for chaining. + */ + on(eventType, handler) { + if (typeof handler !== 'function') { + throw new TypeError('An embed event handler must be a function.') + } + if (!this.listeners.has(eventType)) { + this.listeners.set(eventType, new Set()) + } + this.listeners.get(eventType).add(handler) + return this + } + + /** + * Stop listening; without a handler, drop every listener of the event. + * + * @param {string} eventType The event. + * @param {(payload: unknown) => void} [handler] The handler given to on(). + * @return {EmbedInstance} This embed, for chaining. + */ + off(eventType, handler) { + if (handler === undefined) { + this.listeners.delete(eventType) + } else { + this.listeners.get(eventType)?.delete(handler) + } + return this + } + + /** + * Tell the embed its container's size and wait until it has re-measured. + * + * @return {Promise<{width: number, height: number}>} The size the embed took. + */ + resize() { + const container = this.iframe.parentElement + const width = Math.round(container?.clientWidth || this.iframe.clientWidth || 0) + const height = Math.round(container?.clientHeight || this.iframe.clientHeight || 0) + return this.request(MESSAGES.resize, MESSAGES.resized, { width, height }) + } + + /** + * Remove the iframe and every listener. + * + * @return {void} + */ + destroy() { + this.host.removeEventListener('message', this.onMessage) + this.listeners.clear() + for (const { reject, timer } of this.pending.values()) { + clearTimeout(timer) + reject(new Error('The embed was destroyed.')) + } + this.pending.clear() + this.iframe.remove() + } + + /** + * Post a message and wait for its answer, matched by nonce. + * + * @param {string} type The message. + * @param {string} answer The answer's type. + * @param {object} payload The message's payload. + * @return {Promise<object>} The answer. + */ + request(type, answer, payload) { + const id = nonce() + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.pending.delete(id) + reject(new Error(`The embed did not answer ${type} in time.`)) + }, this.timeout) + this.pending.set(id, { answer, resolve, reject, timer }) + post(this.iframe.contentWindow, this.origin, type, { ...payload, nonce: id }) + }) + } + + /** + * Handle a message from the embed: an answer to a request, or an event. + * + * @param {MessageEvent} event The message. + * @return {void} + */ + receive(event) { + if (!isFrom(event, { origin: this.origin, source: this.iframe.contentWindow })) { + return + } + const data = event.data + const waiting = data.nonce !== undefined ? this.pending.get(data.nonce) : undefined + if (waiting && (data.type === waiting.answer || data.type === MESSAGES.error)) { + clearTimeout(waiting.timer) + this.pending.delete(data.nonce) + if (data.type === MESSAGES.error) { + waiting.reject(Object.assign(new Error(data.message || 'The embed refused.'), { code: data.error })) + } else { + const answer = { ...data } + delete answer.type + delete answer.nonce + waiting.resolve(answer) + } + return + } + if (data.type === MESSAGES.event && typeof data.event === 'string') { + this.emit(data.event, data.payload) + } else if (data.type === MESSAGES.error) { + this.emit('error', { error: data.error, message: data.message }) + } + } + + /** + * Call every handler of an event; one failing handler does not stop the others. + * + * @param {string} eventType The event. + * @param {unknown} payload Its payload. + * @return {void} + */ + emit(eventType, payload) { + for (const handler of [...(this.listeners.get(eventType) || [])]) { + try { + handler(payload) + } catch (failure) { + // A host handler's failure is the host's; report it without stopping the others. + setTimeout(() => { + throw failure + }) + } + } + } + +} + +/** + * The iframe URL of an embed. + * + * @param {object} config The embed config. + * @return {string} + */ +export function embedUrl(config) { + const base = String(config.baseUrl || '').replace(/\/+$/, '') + const url = new URL(`${base}/embed/${encodeURIComponent(config.subjectType)}/${encodeURIComponent(config.subjectId)}`) + url.searchParams.set('token', config.token) + if (config.viewport) { + url.searchParams.set('viewport', config.viewport) + } + return url.toString() +} + +/** + * Render an embed into a container: create the iframe, wait for it to load, + * hand over the token and resolve once the embed says it is ready. + * + * @param {HTMLElement} container Where the iframe goes. + * @param {{baseUrl: string, token: string, subjectType: string, subjectId: string, title?: string, viewport?: string, timeout?: number}} config The embed. + * @param {Window} [host] The host page's window (for tests). + * @return {Promise<EmbedInstance>} + */ +export function render(container, config, host = globalThis.window) { + if (!container || typeof container.appendChild !== 'function') { + return Promise.reject(new TypeError('LaunchPadEmbed.render needs a container element.')) + } + for (const key of ['baseUrl', 'token', 'subjectType', 'subjectId']) { + if (!config?.[key]) { + return Promise.reject(new TypeError(`LaunchPadEmbed.render needs config.${key}.`)) + } + } + if (!['widget', 'dashboard'].includes(config.subjectType)) { + return Promise.reject(new TypeError('config.subjectType is "widget" or "dashboard".')) + } + + const origin = originOf(config.baseUrl) + const document = container.ownerDocument + const iframe = document.createElement('iframe') + iframe.src = embedUrl(config) + iframe.title = config.title || 'LaunchPad' + iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin') + iframe.style.border = '0' + iframe.style.width = '100%' + iframe.style.height = '100%' + + const embed = new EmbedInstance(iframe, origin, host, config.timeout || DEFAULT_TIMEOUT) + + return new Promise((resolve, reject) => { + iframe.addEventListener('load', () => { + embed.request(MESSAGES.init, MESSAGES.ready, { token: config.token }) + .then(() => resolve(embed)) + .catch((failure) => { + embed.destroy() + reject(failure) + }) + }, { once: true }) + container.appendChild(iframe) + }) +} + +export const LaunchPadEmbed = Object.freeze({ render }) + +export default LaunchPadEmbed diff --git a/src/embed-sdk/src/postMessage.js b/src/embed-sdk/src/postMessage.js new file mode 100644 index 000000000..6bf049ab3 --- /dev/null +++ b/src/embed-sdk/src/postMessage.js @@ -0,0 +1,105 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The message protocol between a host page and a LaunchPad embed iframe + * (embedded-analytics REQ-EMB-006). Every message is a plain object whose + * `type` starts with `launchpad-embed:`; both sides accept one only from the + * window and origin they expect, and post only to a named origin, never `*`. + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-006--js-sdk-exposes-render-event-and-resize-apis + */ + +export const PREFIX = 'launchpad-embed:' + +export const MESSAGES = Object.freeze({ + init: `${PREFIX}init`, + ready: `${PREFIX}ready`, + error: `${PREFIX}error`, + event: `${PREFIX}event`, + resize: `${PREFIX}resize`, + resized: `${PREFIX}resized`, +}) + +/** The events an embed relays to its host. */ +export const EVENTS = Object.freeze(['filterApplied', 'drillDown', 'export', 'error', 'resized']) + +/** + * The `scheme://host[:port]` of a URL, '' when it has none. + * + * @param {string} url The URL. + * @param {string} [base] The base for a relative URL. + * @return {string} The origin. + */ +export function originOf(url, base) { + try { + const parsed = new URL(url, base) + if (parsed.origin === 'null') { + return '' + } + return parsed.origin.toLowerCase() + } catch { + return '' + } +} + +/** + * Whether a message event comes from the expected window and origin and + * carries one of our types. + * + * @param {MessageEvent} event The event. + * @param {{origin: string, source: object|null}} expected Who may send it. + * @return {boolean} + */ +export function isFrom(event, expected) { + return Boolean(event) + && typeof event.data === 'object' + && event.data !== null + && typeof event.data.type === 'string' + && event.data.type.startsWith(PREFIX) + && expected.source !== null + && event.source === expected.source + && typeof event.origin === 'string' + && event.origin.toLowerCase() === expected.origin +} + +/** + * Post one message to a window at a named origin. + * + * @param {Window} target The receiving window. + * @param {string} origin Its origin; never '*'. + * @param {string} type One of MESSAGES. + * @param {object} [payload] The rest of the message. + * @return {void} + */ +export function post(target, origin, type, payload = {}) { + if (!target || !origin || origin === '*') { + throw new Error('An embed message needs a target window and an explicit origin.') + } + target.postMessage({ ...payload, type }, origin) +} + +/** + * The claims of a JWT, unverified ({} when it is not one). The embed reads + * `hostOrigins` from them to check its parent; the server verifies the + * signature on every request. + * + * @param {string} jwt The token. + * @return {object} The claims. + */ +export function decodeClaims(jwt) { + const segments = String(jwt || '').split('.') + if (segments.length !== 3) { + return {} + } + try { + const base64 = segments[1].replace(/-/g, '+').replace(/_/g, '/') + const json = decodeURIComponent( + Array.from(atob(base64), (char) => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`).join(''), + ) + const claims = JSON.parse(json) + return claims && typeof claims === 'object' ? claims : {} + } catch { + return {} + } +} diff --git a/src/embed-sdk/src/types.ts b/src/embed-sdk/src/types.ts new file mode 100644 index 000000000..a8451be3e --- /dev/null +++ b/src/embed-sdk/src/types.ts @@ -0,0 +1,46 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Type definitions of `@conduction/launchpad-embed` (embedded-analytics task 19). + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-006--js-sdk-exposes-render-event-and-resize-apis + */ + +export type SubjectType = 'widget' | 'dashboard' + +export interface EmbedConfig { + /** Where LaunchPad lives, e.g. `https://cloud.example.nl/index.php/apps/launchpad`. */ + baseUrl: string + /** The embed token (JWT) issued for this subject. */ + token: string + subjectType: SubjectType + subjectId: string + /** The iframe's accessible title. */ + title?: string + /** `small`, `medium`, `large` or a width, for usage statistics. */ + viewport?: string + /** Milliseconds to wait for the embed to answer (default 10000). */ + timeout?: number +} + +export type EmbedEventType = 'filterApplied' | 'drillDown' | 'export' | 'error' | 'resized' + +export interface EmbedError { + error: string + message: string +} + +export type EmbedEventHandler = (payload: unknown) => void + +export interface EmbedInstance { + readonly iframe: HTMLIFrameElement + on(eventType: EmbedEventType | string, handler: EmbedEventHandler): EmbedInstance + off(eventType: EmbedEventType | string, handler?: EmbedEventHandler): EmbedInstance + resize(): Promise<{ width: number, height: number }> + destroy(): void +} + +export interface LaunchPadEmbedApi { + render(container: HTMLElement, config: EmbedConfig): Promise<EmbedInstance> +} diff --git a/src/embed-sdk/webpack.config.cjs b/src/embed-sdk/webpack.config.cjs new file mode 100644 index 000000000..ac17a5bae --- /dev/null +++ b/src/embed-sdk/webpack.config.cjs @@ -0,0 +1,46 @@ +/* + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Builds the two distributions of the embed SDK into the app's js/embed-sdk/ + * (shipped in the app package and served by EmbedSdkController): an ES module + * and a UMD bundle that exposes the global `LaunchPadEmbed`. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-19 + * @spec openspec/changes/embedded-analytics/tasks.md#task-24 + */ + +const path = require('path') + +const entry = path.join(__dirname, 'src', 'LaunchPadEmbed.js') +const dist = path.join(__dirname, '..', '..', 'js', 'embed-sdk') + +const shared = { + mode: 'production', + entry, + devtool: 'source-map', + target: ['web', 'es2020'], +} + +module.exports = [ + { + ...shared, + name: 'esm', + experiments: { outputModule: true }, + output: { + path: dist, + filename: 'embed-sdk.esm.js', + library: { type: 'module' }, + }, + }, + { + ...shared, + name: 'umd', + output: { + path: dist, + filename: 'embed-sdk.umd.js', + library: { name: 'LaunchPadEmbed', type: 'umd', export: 'default' }, + globalObject: 'this', + }, + }, +] diff --git a/src/kiosk.js b/src/kiosk.js index 2b52552d6..80cadf01a 100644 --- a/src/kiosk.js +++ b/src/kiosk.js @@ -14,6 +14,7 @@ import { createApp, h } from 'vue' import KioskPlayerView from './views/KioskPlayerView.vue' import './publicPath.js' +import './styles/kiosk.css' const pathSegments = window.location.pathname.replace(/\/+$/, '').split('/') const token = pathSegments[pathSegments.length - 1] || '' diff --git a/src/main.js b/src/main.js index 719f13398..cd7954f04 100644 --- a/src/main.js +++ b/src/main.js @@ -36,11 +36,10 @@ import { registerBuiltinDashboardWidgets, registerDashboardWidget, registerIcons, + registerTranslations, useAppManifest, } from '@conduction/nextcloud-vue' -import axios from '@nextcloud/axios' import { translatePlural as n, translate as t } from '@nextcloud/l10n' -import { generateUrl } from '@nextcloud/router' import { createPinia } from 'pinia' import { createApp, h, reactive } from 'vue' import { createRouter, createWebHistory } from 'vue-router' @@ -48,18 +47,39 @@ import App from './App.vue' import { LAUNCHPAD_ICONS } from './icons.js' import bundledStub from './manifest.json' import registry from './registry.js' +// Captures the boot address before the router's catch-all redirects it. +import { appBase } from './utils/bootPath.js' +import { applyCustomCss, GLOBAL_STYLE_ID } from './utils/customCss.js' +import { mountHeaderSearch } from './utils/headerSearchMount.js' import { loadInitialState } from './utils/loadInitialState.js' import { logger } from './utils/logger.js' import { permissionGuard, routesFromManifest } from './utils/manifestRoutes.js' import { mergeManifestFragments } from './utils/mergeManifestFragments.js' import { currentPermissions } from './utils/permissions.js' +import { runtimeManifestRequest } from './utils/runtimeManifestRequest.js' import './publicPath.js' import './services/widgetBridge.js' +// Captures the browser's install prompt early, for the phone install banner +// (platform-baseline REQ-PLB-009). +import './utils/installPrompt.js' import 'gridstack/dist/gridstack.min.css' +// The library's own stylesheet (board look, widgets, dialogs). Without it +// the page only had the library CSS another app's bundle happened to load. +import '@conduction/nextcloud-vue/css/index.css' import './styles/workspace.css' +import './styles/modals.css' +import './styles/kiosk.css' +import './styles/print.css' registerBuiltinDashboardWidgets() +// The library's own strings ("Good afternoon, {name}" in the greeting header, +// its dialogs and empty states) live in the `nextcloud-vue` translation +// domain, which only exists once the app registers it. Without this call a +// Dutch start page greeted in English. +// @spec openspec/changes/archive/2026-11-24-start-page-board-sync/specs/lpvandaag-start-page/spec.md#requirement-the-start-page-greets-the-reader +registerTranslations() + // Populate the shared CnIcon registry with the MDI icons LaunchPad's // manifests name (ADR-077 rule 3). // @@ -104,7 +124,8 @@ registerDashboardWidget('nc-widget', { // does not expose (it declares no `exports` map) — so the require always threw // and the surrounding try/catch silently skipped manifest registration // entirely. Importing it from the barrel makes the registration actually run. -useAppManifest('launchpad', bundledStub) +// nc-vue's merge and the runtime loader below share one `/api/manifest` request. +useAppManifest('launchpad', bundledStub, { fetcher: runtimeManifestRequest }) // Note: GridStack v12 dropped the separate `gridstack-extra.min.css` // helper file — the per-column-count CSS rules used by responsive // breakpoints are now generated dynamically by the engine at init time. @@ -123,6 +144,10 @@ const pinia = createPinia() // by the reader); descendants `inject(key, default)` to read. const initialState = loadInitialState('workspace') +// platform-dashboard-theme-and-css REQ-THM-003 / D4: the administrator CSS for +// all of LaunchPad, already cleaned and scoped by the server, inserted as text. +applyCustomCss(GLOBAL_STYLE_ID, initialState.customCss) + // --- Runtime manifest loader (ADR-036 Decision 8) --- // // `useRuntimeManifest` from @conduction/nextcloud-vue is available in @@ -141,8 +166,7 @@ const manifestLoading = reactive({ value: true }) ;(async () => { try { - const url = generateUrl('/apps/launchpad/api/manifest') - const response = await axios.get(url) + const response = await runtimeManifestRequest() if ( response @@ -181,8 +205,7 @@ const RoutePageRenderer = { ...CnPageRenderer } * @return {string} The router base. */ function routerBase() { - const match = window.location.pathname.match(/^(.*\/apps\/launchpad)(?:\/|$)/) - return match ? match[1] : generateUrl('/apps/launchpad') + return appBase(window.location.pathname) } // The permissions this account holds, from the server's own answer rather than @@ -238,4 +261,10 @@ app.provide('manifestLoading', manifestLoading) app.mount('#workspace-vue') +// header-search-dropdown REQ-SRCH-013: the top bar's search field shows its +// results under the field on LaunchPad pages, with the first search shortcut +// as the tip. +// @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field +mountHeaderSearch(initialState.searchShortcuts) + export default app diff --git a/src/manifest.d/dashboards-and-who-may-see-them.json b/src/manifest.d/dashboards-and-who-may-see-them.json new file mode 100644 index 000000000..5c4b83d32 --- /dev/null +++ b/src/manifest.d/dashboards-and-who-may-see-them.json @@ -0,0 +1,136 @@ +{ + "_note": "ADR-037 manifest fragment for dashboards-and-who-may-see-them task 2.2 (REQ-DWMS-003). The report gallery is an ordinary index over launchpad's own endpoint (entitySource endpoint, GET /api/reports): the definitions ship with the app and are not OpenRegister objects, so there is no register to point at and no component to write. A report whose registers or schemas are missing stays in the list, says Unavailable and names them (the endpoint answers available and missing per row). Opening a row runs the report through GET /api/reports/{id}, which answers an unavailable report with available false and no result rather than an error. Save as dashboard is the endpoint's POST /api/reports/{id}/dashboard: a dashboard owned by the caller holding the result; the server refuses an unavailable report.", + "menu": [], + "pages": [ + { + "id": "ReportLibrary", + "route": "/reports/library", + "type": "index", + "title": "Ready-made reports", + "config": { + "entitySource": "endpoint", + "sourceConfig": { + "url": "/apps/launchpad/api/reports", + "rowsPath": "reports" + }, + "rowRoute": "ReportRun", + "showAdd": false, + "showEditAction": false, + "showCopyAction": false, + "showDeleteAction": false, + "selectable": false, + "emptyText": "No reports ship with this version.", + "columns": [ + { + "key": "title", + "label": "Report", + "cellClass": "cn-cell--strong" + }, + { + "key": "description", + "label": "What it shows" + }, + { + "key": "available", + "label": "Status", + "formatter": "valueMap", + "formatterOptions": { + "map": { + "true": "Available", + "false": "Unavailable" + } + } + }, + { + "key": "missing", + "label": "Missing registers or schemas" + } + ], + "actions": [ + "builtin:view", + { + "id": "report-save-as-dashboard", + "label": "Save as dashboard", + "icon": "ViewDashboardOutline", + "type": "api-call", + "url": "/apps/launchpad/api/reports/{objectId}/dashboard", + "method": "POST", + "successMessage": "The report was saved as a dashboard of your own.", + "errorMessage": "The report could not be saved as a dashboard. An unavailable report cannot be saved." + } + ] + } + }, + { + "id": "ReportRun", + "route": "/reports/library/:id", + "type": "detail", + "title": "Report", + "config": { + "entitySource": "endpoint", + "sourceConfig": { + "url": "/apps/launchpad/api/reports/{id}" + }, + "headerActions": [ + { + "id": "report-run-save-as-dashboard", + "label": "Save as dashboard", + "icon": "ViewDashboardOutline", + "type": "api-call", + "url": "/apps/launchpad/api/reports/{objectId}/dashboard", + "method": "POST", + "successMessage": "The report was saved as a dashboard of your own.", + "errorMessage": "The report could not be saved as a dashboard. An unavailable report cannot be saved." + } + ], + "widgets": [ + { + "id": "report-run-about", + "type": "data", + "title": "About this report", + "content": { + "title": "About this report", + "columns": 2, + "include": [ + "title", + "description", + "available", + "missing" + ] + } + }, + { + "id": "report-run-result", + "type": "data", + "title": "Result", + "content": { + "title": "Result", + "columns": 1, + "include": [ + "result" + ] + } + } + ], + "layout": [ + { + "id": "1", + "widgetId": "report-run-about", + "gridX": 0, + "gridY": 0, + "gridWidth": 12, + "gridHeight": 4 + }, + { + "id": "2", + "widgetId": "report-run-result", + "gridX": 0, + "gridY": 4, + "gridWidth": 12, + "gridHeight": 8 + } + ] + } + } + ] +} diff --git a/src/manifest.json b/src/manifest.json index 1a120bf9a..7bdd7b9bb 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -16,17 +16,10 @@ "display": "cards", "optionsSource": "datasets", "configKey": "demo_dataset", + "loadAction": "load-demo-data", "title": "Load example data?", "required": false, - "body": "Example data fills the lists, detail pages and dashboards so you can see the app working straight away. Pick \"None\" on a production install." - }, - { - "id": "load-demo-data", - "type": "run-action", - "action": "load-demo-data", - "title": "Load the example data", - "required": false, - "body": "Loads what you picked. The data is obviously sample data, it is safe to run more than once, and you can delete it afterwards." + "body": "Example data fills the lists, detail pages and dashboards so you can see the app working straight away. Each card has its own Load button. Pick \"None\" on a production install." }, { "id": "done", @@ -36,7 +29,15 @@ ] }, "version": "0.2.0", - "dependencies": [], + "openbuildEditable": false, + "look": "board", + "dependencies": [ + { + "id": "openregister", + "required": false, + "name": "OpenRegister" + } + ], "observability": { "_note": "LaunchPad consumes the OpenRegister AppHost observability engine (ADR-040). These descriptors reproduce the output of the now-deleted hand-written HealthController + MetricsController. The /api/health and /api/metrics routes are aliased to the AppHost generic controllers in lib/AppInfo/Application.php, so the engine reads this block at request time. The Prometheus prefix is the runtime app id `launchpad`. Parity: implicit launchpad_info/launchpad_up plus launchpad_dashboards_total/widgets_total/tiles_total match the pre-adoption contract; documented intentional improvements are the now-public health endpoint and the added health `app`/`version` fields (ADR-006).", "health": { @@ -127,7 +128,7 @@ }, { "id": "StoreMenu", - "label": "Store", + "label": "Marketplace", "icon": "StoreOutline", "route": "Store", "section": "footer", @@ -138,7 +139,7 @@ "label": "Reports", "icon": "ChartBoxOutline", "route": "Reports", - "section": "footer", + "section": "settings", "order": 95 }, { @@ -163,13 +164,19 @@ "id": "Store", "route": "/store", "type": "store", - "title": "Store", + "title": "Marketplace", "config": { "app": "launchpad", - "title": "Store", - "description": "Install a dashboard another organisation published. Point LaunchPad at a registry and browse what it offers." + "title": "Marketplace", + "description": "Install a dashboard another organisation published. Point LaunchPad at a registry and browse what it offers.", + "categoryLenses": true, + "pageSize": 8, + "banner": { + "settingsUrl": "/index.php/apps/launchpad/admin/sharing", + "settingsLabel": "Open the Sharing tab" + } }, - "_note": "ADR-080. Discovery is engine-owned: openregister's GenericStoreService owns the SSRF guard, the redirect refusal and the Bearer-only token. Install is LaunchPad's, in Controller\\StoreController, and runs through the existing ImportService. With no registry configured the page makes NO network call and reports not_configured. There is deliberately NO top-level `store` block: it configures the engine's GenericStoreController, which cannot write a LaunchPad dashboard, so the engine alias yields to the leaf controller. The block this replaced declared `openregister.configset` types, which would have offered configuration sets to somebody looking for a dashboard." + "_note": "ADR-080. Discovery is engine-owned: openregister's GenericStoreService owns the SSRF guard, the redirect refusal and the Bearer-only token. Install is LaunchPad's, in Controller\\StoreController, and runs through the existing ImportService. With no registry configured the page makes NO network call and reports not_configured. There is deliberately NO top-level `store` block: it configures the engine's GenericStoreController, which cannot write a LaunchPad dashboard, so the engine alias yields to the leaf controller. The block this replaced declared `openregister.configset` types, which would have offered configuration sets to somebody looking for a dashboard. Board LpStore (store-page-board-sync REQ-STORE-010): the lenses are All, Installed, Update available and the categories the register's items carry (categoryLenses), not the engine's kind lenses, which are not dashboard kinds; 8 cards a page; the banner names the register the items answer carries (registry, checkedAt) and, without one, links to the Sharing tab." }, { "id": "dashboard-detail", @@ -188,21 +195,22 @@ "route": "/admin/templates", "type": "custom", "title": "Templates", - "component": "AdminSettingsRedirect", + "component": "AdminPage", "permission": "admin", - "_note": "REDIRECTS to /settings/admin/launchpad. TemplatesPage is a TAB inside the Nextcloud admin section, not a page of its own; routing it in-app would render half an admin surface next to the real one.", + "_note": "The administration page (admin-settings REQ-ADM-030) on its Templates tab. TemplatesPage is a TAB of the administration, so this route opens that tab rather than a page of its own.", "config": { - "documentationUrl": "https://launchpad.conduction.nl" + "documentationUrl": "https://launchpad.conduction.nl", + "tab": "templates" } }, { "id": "admin-settings", - "route": "/admin/settings", + "route": "/admin/:tab?", "type": "custom", "title": "Admin settings", - "component": "AdminSettingsRedirect", + "component": "AdminPage", "permission": "admin", - "_note": "REDIRECTS to /settings/admin/launchpad. The admin surface is a Nextcloud settings section (lib/Settings/LaunchPadAdmin.php, mounted by src/admin.js), not an in-app page — the component this once named, AdminSettingsPage, has never existed. The route resolves so the menu entry is not a dead link, and lands where the functionality is." + "_note": "The administration, a Launchpad page over the full width (admin-settings REQ-ADM-030): the shell's top bar and More menu, no settings menu, the tabs over the full width. The tab is the route's; the server renders /apps/launchpad/admin/<tab> only for a (delegated) administrator (AdminPageController). Nextcloud's settings entry links here (lib/Settings/LaunchPadAdmin.php)." }, { "id": "Flows", @@ -211,9 +219,10 @@ "title": "Flows", "config": { "entitySource": "flows", - "app": "launchpad" + "app": "launchpad", + "rowRoute": "FlowDetail" }, - "_note": "ADR-110 Decision 4: a flow is app-specific, so the authoring surface lives here rather than behind a deep link to another app's list. An ordinary index over the named `flows` source (config.entitySource) rather than the deprecated `flows` page type, reading OpenRegister's one native flow store (ADR-065), scoped to this app by config.app." + "_note": "ADR-110 Decision 4: a flow is app-specific, so the authoring surface lives here rather than behind a deep link to another app's list. An ordinary index over the named `flows` source (config.entitySource) rather than the deprecated `flows` page type, reading OpenRegister's one native flow store (ADR-065), scoped to this app by config.app. rowRoute names the FlowDetail page (a route name, not a path): a named-source page has no register and schema, so without it a row click opens nothing and Edit falls back to the source's own /flows path." }, { "id": "FlowDetail", @@ -221,13 +230,15 @@ "type": "flow", "title": "Flow", "config": { + "listMode": true, + "testPayload": true, "app": "launchpad" }, "_note": "The shared CnFlowDetail canvas over the same single engine. Controls render in the NC app sidebar so the canvas keeps full width." }, { "id": "Reports", - "_note": "ADR-112 / ADR-114 Decision 3. ONE card, deliberately. LaunchPad's register holds a single schema — dashboard — so a second report would either repeat this one or invent a reading the data cannot support. The `widgets` array holds widget descriptors rather than references, so grouping by it would bucket objects and render noise; it is left out rather than shipped as a chart that looks like an answer.", + "_note": "ADR-112 / ADR-114 Decision 3. ONE declarative report over LaunchPad's own register, deliberately: it holds a single schema — dashboard — so a second one would either repeat this one or invent a reading the data cannot support. The second card is the gallery of shipped report definitions (dashboards-and-who-may-see-them REQ-DWMS-003, src/manifest.d), which read other apps' registers and say when those are missing. The `widgets` array holds widget descriptors rather than references, so grouping by it would bucket objects and render noise; it is left out rather than shipped as a chart that looks like an answer.", "route": "/reports", "type": "reports", "title": "Reports", @@ -240,6 +251,13 @@ "description": "How many dashboards there are, and who they belong to.", "icon": "ViewDashboardOutline", "route": "DashboardsReport" + }, + { + "id": "ReportLibrary", + "label": "Ready-made reports", + "description": "Reports that ship with LaunchPad: run one without composing a dashboard, or save its result as a dashboard of your own.", + "icon": "ChartBoxOutline", + "route": "ReportLibrary" } ] } @@ -260,7 +278,7 @@ "label": "Dashboards", "icon": "ViewDashboardOutline", "route": { - "name": "dashboards" + "name": "Workspace" }, "format": { "style": "decimal", @@ -281,7 +299,7 @@ "label": "Personal", "icon": "ViewDashboardOutline", "route": { - "name": "dashboards" + "name": "Workspace" }, "format": { "style": "decimal", @@ -305,7 +323,7 @@ "label": "Shared with a group", "icon": "Sitemap", "route": { - "name": "dashboards" + "name": "Workspace" }, "format": { "style": "decimal", @@ -329,7 +347,7 @@ "label": "Admin templates", "icon": "FileReplaceOutline", "route": { - "name": "admin-templates" + "name": "admin-templates-index" }, "format": { "style": "decimal", @@ -379,7 +397,7 @@ "hideHeader": true, "emptyText": "No dashboards yet", "viewAllRoute": { - "name": "dashboards" + "name": "Workspace" }, "viewAllLabel": "Open a dashboard", "columns": [ @@ -470,55 +488,127 @@ ], "walkthrough": { "enabled": true, - "version": 1, + "version": 2, "completionConfigKey": "walkthrough_completed_version", "tours": [ { "id": "launchpad:getting-started", "title": "Getting started", "trigger": "first-visit", + "startOn": ["Workspace", "dashboard-detail"], "steps": [ { - "id": "welcome", - "placement": "center", - "title": "Welcome to Launchpad", - "body": "A short tour of the main screens. It takes under a minute, and you can close it at any point and pick it up again from the help menu.", + "id": "dashboards", + "placement": "bottom", + "title": "Here you switch between dashboards", + "body": "Your own dashboards, what colleagues share with you and the organisation's group dashboards are under More, next to the marketplace and the settings. Pick one to open it.", "target": { - "kind": "page", - "ref": "Workspace" + "kind": "element", + "ref": "launchpad-more-menu" }, "advanceOn": { "type": "manual" } }, { - "id": "go-dashboard-detail", - "placement": "right", - "body": "Open Dashboards from the menu.", - "task": "Click Dashboards in the menu", + "id": "more-menu", + "placement": "bottom", + "body": "Reports and Flows are under More as well.", + "task": "Open Flows from More", "target": { - "kind": "nav-item", - "ref": "dashboards" + "kind": "element", + "ref": "launchpad-more-menu" }, "advanceOn": { "type": "route-match", - "route": "Workspace" + "route": "Flows" + }, + "allowManualNext": true + } + ] + }, + { + "id": "launchpad:admin-getting-started", + "title": "Admin settings tour", + "trigger": "manual", + "steps": [ + { + "id": "general", + "placement": "bottom", + "title": "General", + "body": "The defaults every dashboard starts from: who may create dashboards, the permission level and the grid. This tour is shown once.", + "target": { + "kind": "element", + "ref": "admin-default-settings" + }, + "advanceOn": { + "type": "manual" } }, { - "id": "go-flows", - "placement": "right", - "body": "Flows automate the repetitive parts of this app. Have a look, though you do not have to build one now.", - "task": "Open Flows from the menu", + "id": "templates", + "placement": "bottom", + "title": "Templates", + "body": "Under Templates you build the dashboards that groups and new users get.", "target": { - "kind": "nav-item", - "ref": "FlowsMenu" + "kind": "element", + "ref": "cn-admin-settings-tabs" }, "advanceOn": { - "type": "route-match", - "route": "Flows" + "type": "manual" + } + }, + { + "id": "roles", + "placement": "bottom", + "title": "Roles and permissions", + "body": "Under Roles and permissions you choose who may manage LaunchPad and what each role may change.", + "target": { + "kind": "element", + "ref": "cn-admin-settings-tabs" }, - "allowManualNext": true + "advanceOn": { + "type": "manual" + } + }, + { + "id": "sharing", + "placement": "bottom", + "title": "Sharing", + "body": "Under Sharing you set who may share dashboards and with whom.", + "target": { + "kind": "element", + "ref": "cn-admin-settings-tabs" + }, + "advanceOn": { + "type": "manual" + } + }, + { + "id": "kiosk", + "placement": "bottom", + "title": "Kiosk", + "body": "Under Kiosk you make playlists of dashboards for a screen that needs no login.", + "target": { + "kind": "element", + "ref": "cn-admin-settings-tabs" + }, + "advanceOn": { + "type": "manual" + } + }, + { + "id": "demo-data", + "placement": "bottom", + "title": "Demo data", + "body": "Under Demo data you load example dashboards to try LaunchPad, and remove them again.", + "target": { + "kind": "element", + "ref": "cn-admin-settings-tabs" + }, + "advanceOn": { + "type": "manual" + } } ] } diff --git a/src/modals/AcknowledgementReportModal.vue b/src/modals/AcknowledgementReportModal.vue index 62ead5c68..6b6cd4e0e 100644 --- a/src/modals/AcknowledgementReportModal.vue +++ b/src/modals/AcknowledgementReportModal.vue @@ -4,24 +4,30 @@ --> <!-- - AcknowledgementReportModal — admin read-receipt report (REQ-ACK-004/006). - - Opens for a single `announcementKey` and shows, for the current content - version: acknowledged / pending / overdue counts, the per-user - acknowledgement timestamps, the outstanding (pending) user list, and a CSV - export button that streams the compliance file. This is deliberately the - ORG-wide read-receipt report — distinct from the compliance-audit-panel's - per-user deadline dismissal (see design "Explicit differentiation"). + AcknowledgementReportModal — the read confirmations of one announcement + (REQ-ACK-004/006, as board LpLeesbevestigingen draws it: REQ-ACK-010). + + "Read confirmations: <title>" under "Announcement · <dashboard>": the + confirmed count over the audience with the number still to go and the + deadline, a bar, the filters Everyone, Confirmed and Not confirmed yet, a + table of Employee, Department and Status, how many are shown, and Download + (the CSV with the date and time of each confirmation) and Close. --> <template> <NcModal v-if="open" + class="launchpad-modal" size="large" - :name="t('launchpad', 'Read-receipt report')" + :name="heading" @close="$emit('close')"> <div class="launchpad-ack-report" data-testid="acknowledgement-report"> - <h2>{{ t('launchpad', 'Read-receipt report') }}</h2> + <p class="launchpad-ack-report__eyebrow" data-testid="ack-report-eyebrow"> + {{ eyebrow }} + </p> + <h2 class="launchpad-ack-report__title"> + {{ heading }} + </h2> <div v-if="loading" class="launchpad-ack-report__loading"> <NcLoadingIcon :size="32" /> @@ -30,81 +36,99 @@ <div v-else-if="error" class="launchpad-ack-report__error" + role="alert" data-testid="acknowledgement-report-error"> {{ error }} </div> <template v-else-if="report"> - <div class="launchpad-ack-report__stats"> - <span - class="launchpad-ack-report__stat launchpad-ack-report__stat--ack" - data-testid="ack-count"> - {{ t('launchpad', 'Acknowledged') }}: - {{ report.acknowledgedCount }} - </span> - <span - class="launchpad-ack-report__stat launchpad-ack-report__stat--pending" - data-testid="pending-count"> - {{ t('launchpad', 'Pending') }}: {{ report.pendingCount }} - </span> - <span - v-if="report.overdue" - class="launchpad-ack-report__stat launchpad-ack-report__stat--overdue" - data-testid="overdue-flag"> - {{ t('launchpad', 'Overdue') }} + <p class="launchpad-ack-report__summary" data-testid="ack-summary"> + <strong>{{ summary.confirmed }}</strong> + <span> · {{ summary.left }}</span> + <span v-if="summary.deadline" :class="{ 'launchpad-ack-report__overdue': report.overdue }"> + · {{ summary.deadline }} </span> + </p> + <div + class="launchpad-ack-report__bar" + role="progressbar" + :aria-valuenow="counts.percent" + aria-valuemin="0" + aria-valuemax="100" + :aria-label="t('launchpad', 'Read confirmations')" + data-testid="ack-bar"> + <span class="launchpad-ack-report__bar-fill" :style="{ width: `${counts.percent}%` }" /> + </div> + + <div class="launchpad-ack-report__filters" role="group" :aria-label="t('launchpad', 'Show')"> + <NcButton + v-for="option in filterOptions" + :key="option.id" + :variant="filter === option.id ? 'primary' : 'secondary'" + :aria-pressed="filter === option.id ? 'true' : 'false'" + :data-testid="`ack-filter-${option.id}`" + @click="filter = option.id"> + {{ option.label }} + </NcButton> </div> <table class="launchpad-ack-report__table"> <thead> <tr> - <th scope="col">{{ t('launchpad', 'User') }}</th> + <th scope="col">{{ t('launchpad', 'Employee') }}</th> + <th scope="col">{{ report.departmentLabel || t('launchpad', 'Department') }}</th> <th scope="col">{{ t('launchpad', 'Status') }}</th> - <th scope="col"> - {{ t('launchpad', 'Acknowledged at') }} - </th> </tr> </thead> <tbody> <tr - v-for="row in report.rows" + v-for="row in shownRows" :key="row.userId" :data-testid="`ack-row-${row.userId}`"> - <td>{{ row.userId }}</td> <td> - <span - :class="`launchpad-ack-report__badge launchpad-ack-report__badge--${row.status}`"> - {{ - row.status === 'acknowledged' - ? t('launchpad', 'Acknowledged') - : t('launchpad', 'Pending') - }} + <span class="launchpad-ack-report__person"> + <span class="launchpad-ack-report__initials" aria-hidden="true">{{ initialsOf(row.displayName || row.userId) }}</span> + {{ row.displayName || row.userId }} + </span> + </td> + <td>{{ row.department || '—' }}</td> + <td> + <span :class="`launchpad-ack-report__badge launchpad-ack-report__badge--${row.status}`"> + {{ statusLabel(row) }} </span> </td> - <td>{{ row.acknowledgedAt || '—' }}</td> </tr> </tbody> </table> - <div class="launchpad-ack-report__actions"> - <a - :href="csvUrl" - class="launchpad-ack-report__csv" - download - data-testid="acknowledgement-report-csv"> - <NcButton variant="secondary"> - {{ t('launchpad', 'Export CSV') }} - </NcButton> - </a> - </div> + <p class="launchpad-ack-report__note" data-testid="ack-shown"> + {{ shownLine }} + </p> </template> + + <div class="launchpad-ack-report__actions"> + <NcButton + v-if="report && csvUrl" + :href="csvUrl" + download + variant="secondary" + data-testid="acknowledgement-report-csv"> + {{ t('launchpad', 'Download') }} + </NcButton> + <NcButton variant="primary" data-testid="acknowledgement-report-close" @click="$emit('close')"> + {{ t('launchpad', 'Close') }} + </NcButton> + </div> </div> </NcModal> </template> <script> import { NcButton, NcLoadingIcon, NcModal } from '@conduction/nextcloud-vue' +import { FLAG_PROP, TEXT_PROP } from '../constants/propDefinitions.js' +import { announcementsApi } from '../services/announcementsApi.js' import { api } from '../services/api.js' +import { filterReceipts, FILTERS, initialsOf, receiptCounts, receiptDate } from '../utils/readReceipts.js' export default { name: 'AcknowledgementReportModal', @@ -116,15 +140,21 @@ export default { }, props: { - open: { - type: Boolean, - default: false, - }, + open: FLAG_PROP, - announcementKey: { - type: String, - default: '', - }, + announcementKey: TEXT_PROP, + + /** + * An announcement's uuid: read its confirmations from the + * announcements API instead of a widget placement's (REQ-ANN-007). + */ + announcementUuid: TEXT_PROP, + + /** The announcement's title, e.g. "New procedure for Woo requests". */ + title: TEXT_PROP, + + /** The dashboard the announcement is on. */ + dashboardName: TEXT_PROP, }, emits: ['close'], @@ -134,6 +164,7 @@ export default { loading: false, error: '', report: null, + filter: 'everyone', } }, @@ -145,7 +176,87 @@ export default { * @spec openspec/changes/dashboard-acknowledgements/specs/dashboard-acknowledgements/spec.md */ csvUrl() { - return api.getAcknowledgementReportCsvUrl(this.announcementKey) + return this.announcementUuid ? '' : api.getAcknowledgementReportCsvUrl(this.announcementKey) + }, + + /** + * @return {string} "Read confirmations: <title>". + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + heading() { + return this.title + ? t('launchpad', 'Read confirmations: {title}', { title: this.title }) + : t('launchpad', 'Read confirmations') + }, + + /** + * @return {string} "Announcement · <dashboard>". + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + eyebrow() { + return this.dashboardName + ? t('launchpad', 'Announcement · {dashboard}', { dashboard: this.dashboardName }) + : t('launchpad', 'Announcement') + }, + + /** + * @return {{confirmed: number, audience: number, left: number, percent: number}} The counts. + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + counts() { + return receiptCounts(this.report) + }, + + /** + * The summary line's parts: the count over the audience, the number + * still to go and the deadline ('' without one). + * + * @return {{confirmed: string, left: string, deadline: string}} The parts. + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + summary() { + return { + confirmed: t('launchpad', '{confirmed} of {audience} confirmed', { confirmed: this.counts.confirmed, audience: this.counts.audience }), + left: t('launchpad', '{count} to go', { count: this.counts.left }), + deadline: this.deadline ? t('launchpad', 'deadline {date}', { date: this.deadline }) : '', + } + }, + + /** + * @return {string} How many rows are shown, and what Download gives. + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + shownLine() { + return t('launchpad', '{shown} of {total} shown. Download gives the full list with the date and time of each confirmation.', { shown: this.shownRows.length, total: this.counts.audience }) + }, + + /** + * @return {string} The deadline in the reader's language, or ''. + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + deadline() { + return receiptDate(this.report?.deadline, { weekday: 'long', day: 'numeric', month: 'long' }) + }, + + /** + * @return {Array<{id: string, label: string}>} The filters. + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + filterOptions() { + const labels = { + everyone: t('launchpad', 'Everyone'), + confirmed: t('launchpad', 'Confirmed'), + pending: t('launchpad', 'Not confirmed yet'), + } + return FILTERS.map((id) => ({ id, label: labels[id] })) + }, + + /** + * @return {Array<object>} The rows the chosen filter shows. + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + shownRows() { + return filterReceipts(this.report?.rows, this.filter) }, }, @@ -161,7 +272,8 @@ export default { * @spec openspec/changes/dashboard-acknowledgements/specs/dashboard-acknowledgements/spec.md */ handler(isOpen) { - if (isOpen && this.announcementKey) { + if (isOpen && (this.announcementKey || this.announcementUuid)) { + this.filter = 'everyone' this.loadReport() } }, @@ -179,24 +291,53 @@ export default { this.loadReport() } }, + + /** + * Reload the report when the targeted announcement changes. + * + * @param {string} uuid the new announcement uuid. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + announcementUuid(uuid) { + if (this.open && uuid) { + this.loadReport() + } + }, }, methods: { + initialsOf, + /** - * Fetch the audience-scoped read-receipt report (REQ-ACK-004). + * @param {object} row A report row. + * @return {string} "Confirmed <date>" or "Not yet". + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + statusLabel(row) { + if (row.status !== 'acknowledged') { + return t('launchpad', 'Not yet') + } + const date = receiptDate(row.acknowledgedAt, { day: 'numeric', month: 'short' }) + return date ? t('launchpad', 'Confirmed {date}', { date }) : t('launchpad', 'Confirmed') + }, + + /** + * Fetch the audience-scoped read-receipt report (REQ-ACK-004), of an + * announcement when its uuid is given (REQ-ANN-007). * * @return {Promise<void>} resolves once the report is loaded. * @spec openspec/changes/dashboard-acknowledgements/specs/dashboard-acknowledgements/spec.md + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 */ async loadReport() { this.loading = true this.error = '' this.report = null try { - const response = await api.getAcknowledgementReport( - this.announcementKey, - ) - this.report = response.data + this.report = this.announcementUuid + ? await announcementsApi.receipts(this.announcementUuid) + : (await api.getAcknowledgementReport(this.announcementKey)).data } catch { this.error = t( 'launchpad', @@ -215,6 +356,15 @@ export default { padding: 16px; } +.launchpad-ack-report__eyebrow { + margin: 0; + color: var(--color-text-maxcontrast); +} + +.launchpad-ack-report__title { + margin: 0 0 12px; +} + .launchpad-ack-report__loading { display: flex; justify-content: center; @@ -222,34 +372,36 @@ export default { } .launchpad-ack-report__error { - color: var(--color-error); + color: var(--color-error-text, var(--color-error)); padding: 12px 0; } -.launchpad-ack-report__stats { - display: flex; - gap: 12px; - margin: 12px 0; - flex-wrap: wrap; +.launchpad-ack-report__summary { + margin: 0 0 8px; } -.launchpad-ack-report__stat { - padding: 4px 12px; - border-radius: var(--border-radius-pill, 100px); - font-weight: 600; - background: var(--color-background-dark); +.launchpad-ack-report__overdue { + color: var(--color-error-text, var(--color-error)); } -.launchpad-ack-report__stat--ack { - color: var(--color-success); +.launchpad-ack-report__bar { + height: 8px; + border-radius: var(--border-radius-pill, 100px); + background: var(--color-background-dark); + overflow: hidden; } -.launchpad-ack-report__stat--pending { - color: var(--color-warning-text, var(--color-warning)); +.launchpad-ack-report__bar-fill { + display: block; + height: 100%; + background: var(--color-success); } -.launchpad-ack-report__stat--overdue { - color: var(--color-error); +.launchpad-ack-report__filters { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin: 16px 0 8px; } .launchpad-ack-report__table { @@ -260,26 +412,47 @@ export default { .launchpad-ack-report__table th, .launchpad-ack-report__table td { - text-align: left; + text-align: start; padding: 6px 8px; border-bottom: 1px solid var(--color-border); } +.launchpad-ack-report__person { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.launchpad-ack-report__initials { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border-radius: 50%; + background: var(--color-primary-element-light, var(--color-background-dark)); + color: var(--color-primary-element-light-text, var(--color-main-text)); + font-size: 0.75rem; + font-weight: 600; +} + .launchpad-ack-report__badge--acknowledged { - color: var(--color-success); + color: var(--color-success-text, var(--color-success)); } .launchpad-ack-report__badge--pending { color: var(--color-warning-text, var(--color-warning)); } +.launchpad-ack-report__note { + color: var(--color-text-maxcontrast); + margin-top: 12px; +} + .launchpad-ack-report__actions { margin-top: 16px; display: flex; justify-content: flex-end; -} - -.launchpad-ack-report__csv { - text-decoration: none; + gap: 8px; } </style> diff --git a/src/modals/AddTilesModal.vue b/src/modals/AddTilesModal.vue new file mode 100644 index 000000000..a6b7e35f4 --- /dev/null +++ b/src/modals/AddTilesModal.vue @@ -0,0 +1,685 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcModal + v-model:show="isOpen" + class="launchpad-modal add-tiles-modal" + :name="t('launchpad', 'Add tiles')" + size="normal" + @close="close"> + <div class="add-tiles" data-testid="add-tiles"> + <h2 class="add-tiles__title"> + {{ t('launchpad', 'Add tiles') }} + </h2> + + <!-- 1. App catalogue (REQ-TILE-043) --> + <section class="add-tiles__section" data-testid="add-tiles-catalogue"> + <h3 class="add-tiles__section-title"> + {{ t('launchpad', 'App catalogue') }} + </h3> + <NcTextField + v-model="search" + :label="t('launchpad', 'Search apps')" + :showTrailingButton="search !== ''" + @trailingButtonClick="search = ''" /> + <ul v-if="catalogueRows.length > 0" class="add-tiles__rows"> + <li + v-for="row in catalogueRows" + :key="row.choice.key" + class="add-tiles__row" + data-testid="add-tiles-catalogue-row"> + <span class="add-tiles__row-name">{{ row.app.name }}</span> + <span class="add-tiles__row-meta">{{ signOnLabel(row.app) }}</span> + <span v-if="row.onDashboard" class="add-tiles__row-meta"> + {{ t('launchpad', 'On your dashboard') }} + </span> + <NcButton + v-else + :variant="isChosen(row.choice.key) ? 'primary' : 'secondary'" + :aria-pressed="isChosen(row.choice.key) ? 'true' : 'false'" + :aria-label="t('launchpad', 'Add {name}', { name: row.app.name })" + @click="toggle(row.choice)"> + {{ isChosen(row.choice.key) ? t('launchpad', 'Added') : t('launchpad', 'Add') }} + </NcButton> + </li> + </ul> + <p v-else class="add-tiles__empty"> + {{ t('launchpad', 'No apps found') }} + </p> + + <form + v-if="requestAppFn && request.open" + class="add-tiles__request" + :aria-label="t('launchpad', 'Ask IT for an app')" + @submit.prevent="submitRequest"> + <NcTextField v-model="request.name" :label="t('launchpad', 'App name')" :required="true" /> + <NcTextField v-model="request.purpose" :label="t('launchpad', 'What do you need it for?')" /> + <div class="add-tiles__request-actions"> + <span + v-if="request.message" + class="add-tiles__message" + :class="{ 'add-tiles__message--error': request.failed }" + role="status">{{ request.message }}</span> + <NcButton variant="tertiary" @click="closeRequestForm"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton variant="primary" type="submit" :disabled="!canSendRequest"> + {{ t('launchpad', 'Send request') }} + </NcButton> + </div> + </form> + <NcButton + v-else-if="requestAppFn" + variant="tertiary" + data-testid="add-tiles-request" + @click="openRequestForm"> + {{ t('launchpad', 'Ask IT for an app') }} + </NcButton> + </section> + + <!-- 2. Found on this server (REQ-TILE-044): the apps of the + person's own app menu that have no tile yet. --> + <section + v-if="foundRows.length > 0" + class="add-tiles__section" + data-testid="add-tiles-found"> + <h3 class="add-tiles__section-title"> + {{ t('launchpad', 'Found on this server') }} + </h3> + <ul class="add-tiles__rows"> + <li + v-for="row in foundRows" + :key="row.choice.key" + class="add-tiles__row" + data-testid="add-tiles-found-row"> + <span class="add-tiles__row-name">{{ row.app.name }}</span> + <span class="add-tiles__row-meta">{{ t('launchpad', 'Running') }}</span> + <NcButton + :variant="isChosen(row.choice.key) ? 'primary' : 'secondary'" + :aria-pressed="isChosen(row.choice.key) ? 'true' : 'false'" + :aria-label="t('launchpad', 'Add {name}', { name: row.app.name })" + @click="toggle(row.choice)"> + {{ isChosen(row.choice.key) ? t('launchpad', 'Added') : t('launchpad', 'Add as tile') }} + </NcButton> + </li> + </ul> + </section> + + <!-- 3. Ready-made tiles for Office, from the office tile pack. --> + <fieldset + v-if="officeRows.length > 0" + class="add-tiles__section add-tiles__office" + data-testid="add-tiles-office"> + <legend class="add-tiles__section-title"> + {{ t('launchpad', 'Ready-made tiles for Office') }} + </legend> + <label + v-for="row in officeRows" + :key="row.choice.key" + class="add-tiles__check"> + <input + type="checkbox" + :checked="row.onDashboard || isChosen(row.choice.key)" + :disabled="row.onDashboard" + :data-testid="'add-tiles-office-' + row.choice.key" + @change="setChosen(row.choice, $event.target.checked)"> + {{ row.pack.title }} + </label> + </fieldset> + + <!-- 4. Import bookmarks: hands the file to the bookmark import. --> + <section class="add-tiles__section" data-testid="add-tiles-bookmarks"> + <h3 class="add-tiles__section-title"> + {{ t('launchpad', 'Import bookmarks') }} + </h3> + <div + class="add-tiles__drop" + :class="{ 'add-tiles__drop--over': dragOver }" + data-testid="add-tiles-drop" + @dragover.prevent="dragOver = true" + @dragleave="dragOver = false" + @drop.prevent="onDrop"> + <span>{{ t('launchpad', 'Drop the bookmarks file your browser exported here') }}</span> + <label class="add-tiles__file"> + <input + type="file" + accept=".html,.htm,text/html" + class="add-tiles__file-input" + data-testid="add-tiles-bookmark-file" + @change="onFile($event.target.files && $event.target.files[0])"> + <span class="add-tiles__file-button">{{ t('launchpad', 'Choose file') }}</span> + </label> + </div> + </section> + + <p + v-if="error" + class="add-tiles__message add-tiles__message--error" + role="alert"> + {{ error }} + </p> + + <div class="add-tiles__actions"> + <NcButton @click="close"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + variant="primary" + :disabled="chosenTiles.length === 0 || busy" + data-testid="add-tiles-confirm" + @click="submit"> + {{ addLabel }} + </NcButton> + </div> + </div> + </NcModal> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcButton, NcModal, NcTextField } from '@nextcloud/vue' +import { + catalogueChoice, + discoveredChoice, + existingTileKeys, + officeChoice, + signOnKind, + tilesToAdd, +} from '../utils/addTiles.js' +import { sendAppRequest } from '../utils/appRequest.js' + +/** + * The Ask IT form when nothing is typed. + * + * @return {{open: boolean, name: string, purpose: string, busy: boolean, failed: boolean, message: string}} + */ +function emptyRequest() { + return { open: false, name: '', purpose: '', busy: false, failed: false, message: '' } +} + +/** + * AddTilesModal — "Add tiles" as board LpTegelToevoegen draws it + * (REQ-TILE-043): the app catalogue with search, sign-on kind per row and + * Ask IT for an app; the apps found on this server that have no tile + * (REQ-TILE-044); ready-made Office tiles to tick; and the bookmark import. + * One primary button says how many tiles it adds. The dialog never places a + * tile twice: a tile the dashboard holds is shown as such, and two sections + * offering the same app add it once. + * + * The host does the API work: it passes the lists and `addTiles(choices)`, + * and opens its bookmark import when the dialog emits `importBookmarks`. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ +export default { + name: 'AddTilesModal', + + components: { NcButton, NcModal, NcTextField }, + + props: { + /** Whether the dialog is open. */ + open: { type: Boolean, default: false }, + /** The catalogue entries the person's groups may see (`GET /api/catalogue`). */ + catalogueApps: { type: Array, default: () => [] }, + /** The apps of the person's app menu (`GET /api/tiles/discover`). */ + discoveredApps: { type: Array, default: () => [] }, + /** The office tile pack (`GET /api/office-tiles`). */ + officeTiles: { type: Array, default: () => [] }, + /** The active dashboard's placements, to leave out tiles it holds. */ + placements: { type: Array, default: () => [] }, + /** `async ({appName, purpose})`: ask IT for an app; absent hides the request. */ + requestAppFn: { type: Function, default: null }, + /** `async (choices)`: place the chosen tiles. */ + addTiles: { type: Function, required: true }, + }, + + emits: ['close', 'importBookmarks', 'added'], + + data() { + return { + search: '', + chosen: [], + busy: false, + error: '', + dragOver: false, + request: emptyRequest(), + } + }, + + computed: { + /** + * Two-way `show` for NcModal: closing it closes the dialog. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + isOpen: { + /** + * @return {boolean} whether the dialog is open. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + get() { + return this.open + }, + + /** + * @param {boolean} value the new `show`. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + set(value) { + if (!value) { + this.close() + } + }, + }, + + /** + * Whether the request can be sent: a name, and nothing in flight. + * + * @return {boolean} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + canSendRequest() { + return !this.request.busy && this.request.name.trim() !== '' + }, + + /** + * The keys of the tiles the dashboard holds. + * + * @return {Set<string>} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + existing() { + return existingTileKeys(this.placements) + }, + + /** + * The catalogue rows matching the search, by name or description. + * + * @return {Array<{app: object, choice: object, onDashboard: boolean}>} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + catalogueRows() { + const query = this.search.trim().toLowerCase() + return this.catalogueApps + .filter((app) => !query + || String(app.name || '').toLowerCase().includes(query) + || String(app.description || '').toLowerCase().includes(query)) + .map((app) => { + const choice = catalogueChoice(app) + return { app, choice, onDashboard: this.existing.has(choice.key) } + }) + }, + + /** + * The found apps without a tile on the dashboard. + * + * @return {Array<{app: object, choice: object}>} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-tiles-for-services-found-on-the-server-req-tile-044 + */ + foundRows() { + return this.discoveredApps + .filter((app) => app && app.appId) + .map((app) => ({ app, choice: discoveredChoice(app) })) + .filter((row) => !this.existing.has(row.choice.key)) + }, + + /** + * The office pack tiles to tick. + * + * @return {Array<{pack: object, choice: object, onDashboard: boolean}>} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + officeRows() { + return this.officeTiles + .filter((pack) => pack && pack.linkType && pack.title) + .map((pack) => { + const choice = officeChoice(pack) + return { pack, choice, onDashboard: this.existing.has(choice.key) } + }) + }, + + /** + * The tiles the button adds: once each, none the dashboard holds. + * + * @return {Array<object>} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + chosenTiles() { + return tilesToAdd(this.chosen, this.existing) + }, + + /** + * "Add 3 tiles". + * + * @return {string} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + addLabel() { + const count = this.chosenTiles.length + if (count === 0) { + return t('launchpad', 'Add tiles') + } + if (count === 1) { + return t('launchpad', 'Add 1 tile') + } + return t('launchpad', 'Add {count} tiles', { count }) + }, + }, + + watch: { + /** + * Start afresh each time the dialog opens. + * + * @param {boolean} value whether it is open. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + open(value) { + if (value) { + this.reset() + } + }, + }, + + methods: { + t, + + /** + * Whether a choice is chosen. + * + * @param {string} key The choice key. + * @return {boolean} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + isChosen(key) { + return this.chosen.some((choice) => choice.key === key) + }, + + /** + * Choose or drop a choice. + * + * @param {{key: string}} choice The choice. + * @param {boolean} on Whether it is chosen. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + setChosen(choice, on) { + const without = this.chosen.filter((item) => item.key !== choice.key) + this.chosen = on ? [...without, choice] : without + }, + + /** + * Flip a choice. + * + * @param {{key: string}} choice The choice. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + toggle(choice) { + this.setChosen(choice, !this.isChosen(choice.key)) + }, + + /** + * The sign-on line of a catalogue row. + * + * @param {object} app The catalogue entry. + * @return {string} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + signOnLabel(app) { + const kind = signOnKind(app) + if (kind === 'sso') { + return t('launchpad', 'Single sign-on') + } + return kind === 'nextcloud' + ? t('launchpad', 'Signs in with your Nextcloud account') + : t('launchpad', 'Asks for its own sign-in') + }, + + /** + * A dropped bookmarks file. + * + * @param {DragEvent} event The drop. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + onDrop(event) { + this.dragOver = false + this.onFile(event?.dataTransfer?.files?.[0]) + }, + + /** + * Hand a bookmarks file to the bookmark import. + * + * @param {File|undefined} file The file. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + onFile(file) { + if (file) { + this.$emit('importBookmarks', file) + } + }, + + /** + * Place the chosen tiles, then close. + * + * @return {Promise<void>} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + async submit() { + const tiles = this.chosenTiles + if (tiles.length === 0 || this.busy) { + return + } + this.busy = true + this.error = '' + try { + await this.addTiles(tiles) + this.$emit('added', tiles) + this.close() + } catch { + this.error = t('launchpad', 'The tiles could not be added.') + } finally { + this.busy = false + } + }, + + /** + * Open the request form, starting from the search. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + openRequestForm() { + this.request = { ...emptyRequest(), open: true, name: this.search.trim() } + }, + + /** + * Close the request form. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + closeRequestForm() { + this.request = emptyRequest() + }, + + /** + * Ask IT for the app and say how it went. + * + * @return {Promise<void>} + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + async submitRequest() { + if (!this.canSendRequest || !this.requestAppFn) { + return + } + this.request.busy = true + const outcome = await sendAppRequest(this.requestAppFn, this.request.name, this.request.purpose) + this.request = { + ...this.request, + busy: false, + failed: outcome.failed, + message: outcome.message, + name: outcome.failed ? this.request.name : '', + purpose: outcome.failed ? this.request.purpose : '', + } + }, + + /** + * Forget the choices and the forms. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + reset() { + this.search = '' + this.chosen = [] + this.error = '' + this.closeRequestForm() + }, + + /** + * Close the dialog. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + close() { + this.reset() + this.$emit('close') + }, + }, +} +</script> + +<style scoped> +.add-tiles { + display: flex; + flex-direction: column; + gap: 20px; + box-sizing: border-box; + width: min(720px, 100%); + padding: 24px; +} + +.add-tiles__title { + margin: 0; +} + +.add-tiles__section { + display: flex; + flex-direction: column; + gap: 8px; + border: 0; + margin: 0; + padding: 0; +} + +.add-tiles__section-title { + margin: 0; + font-size: 16px; + font-weight: 600; +} + +.add-tiles__rows { + margin: 0; + padding: 0; + list-style: none; +} + +.add-tiles__row { + display: flex; + gap: 12px; + align-items: center; + padding: 6px 0; + border-bottom: 1px solid var(--color-border); +} + +.add-tiles__row-name { + flex: 1; + min-width: 0; + font-weight: 500; +} + +.add-tiles__row-meta, +.add-tiles__empty { + color: var(--color-text-maxcontrast); + font-size: 13px; +} + +.add-tiles__office { + flex-flow: row wrap; + gap: 8px 16px; +} + +.add-tiles__office .add-tiles__section-title { + width: 100%; + margin-bottom: 4px; +} + +.add-tiles__check { + display: inline-flex; + gap: 6px; + align-items: center; + cursor: pointer; +} + +.add-tiles__drop { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + justify-content: center; + padding: 20px; + border: 2px dashed var(--color-border-dark); + border-radius: var(--border-radius-large); + color: var(--color-text-maxcontrast); +} + +.add-tiles__drop--over { + border-color: var(--color-primary-element); + background: var(--color-primary-element-light); +} + +.add-tiles__file { + position: relative; + cursor: pointer; +} + +.add-tiles__file-input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; +} + +.add-tiles__file-button { + display: inline-block; + padding: 6px 14px; + border: 1px solid var(--color-border-dark); + border-radius: var(--border-radius-element, var(--border-radius-pill)); + color: var(--color-main-text); +} + +.add-tiles__file:focus-within .add-tiles__file-button { + outline: 2px solid var(--color-primary-element); + outline-offset: 2px; +} + +.add-tiles__request { + display: flex; + flex-direction: column; + gap: 8px; +} + +.add-tiles__request-actions, +.add-tiles__actions { + display: flex; + gap: 8px; + justify-content: flex-end; +} + +.add-tiles__message { + margin: 0; +} + +.add-tiles__message--error { + color: var(--color-error-text, var(--color-error)); +} +</style> diff --git a/src/modals/AnnouncementEditorModal.vue b/src/modals/AnnouncementEditorModal.vue new file mode 100644 index 000000000..84a26d9ca --- /dev/null +++ b/src/modals/AnnouncementEditorModal.vue @@ -0,0 +1,653 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcModal + class="launchpad-modal" + size="large" + :name="t('launchpad', 'New announcement')" + @close="$emit('close')"> + <div class="announcement-editor" data-test="announcement-editor"> + <h2>{{ t('launchpad', 'New announcement') }}</h2> + + <div class="announcement-editor__columns"> + <form + id="announcement-editor-form" + class="announcement-editor__form" + data-test="announcement-editor-form" + @submit.prevent="submit"> + <NcTextField v-model="form.title" :label="t('launchpad', 'Title')" :required="true" data-test="editor-title" /> + <NcTextArea v-model="form.body" :label="t('launchpad', 'Text')" data-test="editor-body" /> + <NcSelect + v-model="form.targetGroups" + :options="groupOptions" + :multiple="true" + :reduce="(option) => option.id" + label="displayName" + :inputLabel="t('launchpad', 'Target group')" + :placeholder="t('launchpad', 'Everyone')" + data-test="editor-groups" /> + + <!-- REQ-ANN-006 (board LpAankondiging): the kind as two choice cards. --> + <fieldset class="announcement-editor__kinds" data-test="editor-kind"> + <legend>{{ t('launchpad', 'Kind') }}</legend> + <label + v-for="option in kindOptions" + :key="option.value" + class="announcement-editor__kind" + :class="{ 'announcement-editor__kind--chosen': form.kind === option.value }" + :data-test="`editor-kind-${option.value}`"> + <input + v-model="form.kind" + class="announcement-editor__kind-input" + type="radio" + name="announcement-kind" + :value="option.value"> + <span class="announcement-editor__kind-label">{{ option.label }}</span> + <span class="announcement-editor__kind-hint">{{ option.hint }}</span> + </label> + </fieldset> + + <template v-if="form.kind === 'notice'"> + <NcSelect + v-model="form.level" + :options="levelOptions" + :inputLabel="t('launchpad', 'Level')" + :reduce="(option) => option.value" + label="label" + :clearable="false" + data-test="editor-level" /> + <NcCheckboxRadioSwitch v-model="form.dismissible" data-test="editor-dismissible"> + {{ t('launchpad', 'Readers may dismiss this notice') }} + </NcCheckboxRadioSwitch> + </template> + <template v-else> + <NcTextField v-model="form.category" :label="t('launchpad', 'Category')" data-test="editor-category" /> + <!-- REQ-ANN-007: ask the audience to confirm they have read it, before a date. --> + <NcCheckboxRadioSwitch v-model="form.requiresConfirmation" data-test="editor-requires-confirmation"> + {{ t('launchpad', 'Ask for read confirmation') }} + </NcCheckboxRadioSwitch> + <label v-if="form.requiresConfirmation" class="announcement-editor__label"> + {{ t('launchpad', 'Confirm before') }} + <input v-model="form.confirmBefore" type="date" data-test="editor-confirm-before"> + </label> + <NcCheckboxRadioSwitch v-model="form.allowComments" data-test="editor-comments"> + {{ t('launchpad', 'Allow comments and following') }} + </NcCheckboxRadioSwitch> + </template> + + <div class="announcement-editor__times"> + <label class="announcement-editor__label"> + {{ t('launchpad', 'Publish on (optional)') }} + <input v-model="form.publishAt" type="datetime-local" data-test="editor-publish-at"> + </label> + <!-- REQ-ANN-001 (board LpAankondiging): every announcement has an + end time, "Show until". --> + <label class="announcement-editor__label"> + {{ t('launchpad', 'Show until') }} + <input + v-model="form.expiresAt" + type="datetime-local" + required + aria-describedby="announcement-editor-show-until-hint" + data-test="editor-expires-at"> + </label> + </div> + <p id="announcement-editor-show-until-hint" class="announcement-editor__hint" data-test="editor-show-until-hint"> + {{ t('launchpad', 'After this time the announcement disappears from every dashboard.') }} + </p> + </form> + + <!-- REQ-ANN-006: "This is how it looks", a live preview that follows every field. --> + <aside class="announcement-editor__preview" :aria-label="t('launchpad', 'This is how it looks')" data-test="editor-preview-pane"> + <h3 class="announcement-editor__preview-title"> + {{ t('launchpad', 'This is how it looks') }} + </h3> + <NoticeBanner v-if="form.kind === 'notice'" :notice="previewItem" :preview="true" /> + <AnnouncementCard v-else :announcement="previewItem" :preview="true" /> + <p class="announcement-editor__hint" data-test="editor-preview-note"> + {{ previewNote }} + </p> + <p v-if="visibleUntil" data-test="editor-visible-until"> + {{ t('launchpad', 'Visible until {when}', { when: visibleUntil }) }} + </p> + <p data-test="editor-reach"> + {{ n('launchpad', 'Reaches {count} person', 'Reaches {count} people', reach, { count: reach }) }} + </p> + <form class="announcement-editor__preview-as" @submit.prevent="checkPreviewAs"> + <NcTextField v-model="previewAs" :label="t('launchpad', 'Preview as (user id)')" data-test="editor-preview-as" /> + <NcButton type="submit" variant="secondary" :disabled="previewAs.trim() === ''"> + {{ t('launchpad', 'Check') }} + </NcButton> + </form> + <p v-if="previewAsAnswer !== null" data-test="editor-preview-as-answer"> + {{ previewAsAnswer ? t('launchpad', '{user} sees this announcement', { user: previewAsUser }) : t('launchpad', '{user} does not see this announcement', { user: previewAsUser }) }} + </p> + </aside> + </div> + + <p v-if="error" class="announcement-editor__error" role="alert" data-test="editor-error"> + {{ error }} + </p> + + <!-- REQ-ANN-006: Cancel and one primary action, Schedule (Publish + when Publish on is empty or past). --> + <div class="announcement-editor__actions"> + <NcButton variant="tertiary" :disabled="busy" data-test="editor-cancel" @click="$emit('close')"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + variant="primary" + :disabled="busy || form.title.trim() === ''" + data-test="editor-publish" + @click="submit"> + {{ scheduled ? t('launchpad', 'Schedule') : t('launchpad', 'Publish') }} + </NcButton> + </div> + </div> + </NcModal> +</template> + +<script> +import { NcModal } from '@conduction/nextcloud-vue' +import { getCanonicalLocale, n, t } from '@nextcloud/l10n' +import { NcButton, NcCheckboxRadioSwitch, NcSelect, NcTextArea, NcTextField } from '@nextcloud/vue' +import AnnouncementCard from '../components/Announcements/AnnouncementCard.vue' +import NoticeBanner from '../components/Announcements/NoticeBanner.vue' +import { announcementsApi } from '../services/announcementsApi.js' +import { logger } from '../utils/logger.js' + +/** + * A `datetime-local` value as an ISO string with the browser's offset, or null when empty. + * + * @param {string} value The input value. + * @return {string|null} + */ +export function toIso(value) { + if (!value) { + return null + } + const date = new Date(value) + return Number.isNaN(date.getTime()) ? null : date.toISOString() +} + +/** + * Why the form cannot go on: no end time, or an end time not after the + * publish time; '' when it can (REQ-ANN-001). + * + * @param {string} publishAt The publish time (`datetime-local`), '' for when it is published. + * @param {string} expiresAt The end time (`datetime-local`). + * @param {Date} now The current moment, standing in for an empty publish time. + * @return {string} The refusal, or ''. + * @spec openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md#requirement-authors-publish-targeted-announcements-req-ann-001 + */ +export function endTimeProblem(publishAt, expiresAt, now) { + const end = toIso(expiresAt) + if (end === null) { + return t('launchpad', 'Choose until when the announcement shows') + } + const start = toIso(publishAt) ?? now.toISOString() + if (new Date(end) <= new Date(start)) { + return t('launchpad', 'The end time must be after the publish time') + } + return '' +} + +/** + * The "Confirm before" date as the moment it ends: the end of that day in + * the author's time zone, or null without a date (REQ-ANN-007). + * + * @param {string} date The `date` input value, `YYYY-MM-DD`. + * @return {string|null} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ +export function confirmBeforeIso(date) { + return date ? toIso(`${date}T23:59`) : null +} + +/** + * Why the read confirmation cannot go on: a "Confirm before" date that is + * not after the publish time; '' when it can (REQ-ANN-007). + * + * @param {string} publishAt The publish time (`datetime-local`), '' for when it is published. + * @param {string|null} confirmBefore The deadline, ISO 8601, or null. + * @param {Date} now The current moment, standing in for an empty publish time. + * @return {string} The refusal, or ''. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ +export function confirmBeforeProblem(publishAt, confirmBefore, now) { + if (!confirmBefore) { + return '' + } + const start = toIso(publishAt) ?? now.toISOString() + return new Date(confirmBefore) <= new Date(start) + ? t('launchpad', 'The confirm-before date must be after the publish time') + : '' +} + +/** + * The end time as the preview names it, "30 October 17:00" in the + * reader's language, or '' without one. + * + * @param {string} expiresAt The end time (`datetime-local`). + * @param {string} [locale] BCP 47 locale. + * @return {string} + * @spec openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md#requirement-authors-publish-targeted-announcements-req-ann-001 + */ +export function visibleUntilText(expiresAt, locale) { + const iso = toIso(expiresAt) + if (iso === null) { + return '' + } + const date = new Date(iso) + const day = date.toLocaleDateString(locale, { day: 'numeric', month: 'long' }) + const time = date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' }) + return `${day} ${time}` +} + +/** + * The note under the preview: only the author sees it until the + * publication time, named when there is one (REQ-ANN-006). + * + * @param {string} publishAt The publish time (`datetime-local`), '' for when it is published. + * @param {string} [locale] BCP 47 locale. + * @return {string} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + */ +export function previewNoteText(publishAt, locale) { + const when = visibleUntilText(publishAt, locale) + return when === '' + ? t('launchpad', 'Only you see this preview until you publish the announcement.') + : t('launchpad', 'Only you see this preview until {when}.', { when }) +} + +/** + * The groups the target group picker offers, with the chosen ones that + * the list does not hold kept, so a stored choice never disappears. + * + * @param {Array<object>} groups `{id, displayName}` from the server. + * @param {Array<string>} chosen The chosen group ids. + * @return {Array<object>} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + */ +export function groupChoices(groups, chosen) { + const known = new Set(groups.map((group) => group.id)) + return [ + ...groups, + ...chosen.filter((id) => !known.has(id)).map((id) => ({ id, displayName: id })), + ] +} + +/** + * AnnouncementEditorModal — one dialog as board LpAankondiging draws it: the + * form on the left, "This is how it looks" on the right, a live preview of + * the same card or banner readers get that follows every field without + * saving, with the number of people the targeting reaches and "Preview as" + * one person (REQ-ANN-004). It ends with Cancel and one primary action: + * Schedule, or Publish when Publish on is empty or past (REQ-ANN-006). A + * news item can ask for a read confirmation before a date; the preview then + * shows "I have read this" and "Confirm before <date>" (REQ-ANN-007). + * + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + * + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + * @spec openspec/changes/engagement-announcements/specs/announcements/spec.md#requirement-authors-preview-before-publishing-req-ann-004 + * @spec openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md#requirement-authors-publish-targeted-announcements-req-ann-001 + */ +export default { + name: 'AnnouncementEditorModal', + + components: { AnnouncementCard, NcButton, NcCheckboxRadioSwitch, NcModal, NcSelect, NcTextArea, NcTextField, NoticeBanner }, + + emits: ['close', 'published'], + + data() { + return { + busy: false, + groups: [], + error: '', + uuid: '', + reach: 0, + previewAs: '', + previewAsUser: '', + previewAsAnswer: null, + form: { + kind: 'news', + title: '', + body: '', + category: '', + targetGroups: [], + level: 'info', + dismissible: true, + allowComments: true, + publishAt: '', + expiresAt: '', + requiresConfirmation: false, + confirmBefore: '', + }, + } + }, + + computed: { + /** + * The kind as two choice cards (REQ-ANN-006). + * + * @return {Array<object>} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + */ + kindOptions() { + return [ + { value: 'news', label: t('launchpad', 'News'), hint: t('launchpad', 'Shown in the Announcements widget.') }, + { value: 'notice', label: t('launchpad', 'Maintenance notice'), hint: t('launchpad', 'Shown at the top of every dashboard until the end time.') }, + ] + }, + + /** + * @return {Array<object>} The target group picker's options. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + */ + groupOptions() { + return groupChoices(this.groups, this.form.targetGroups) + }, + + /** + * @return {string} Who sees the preview, and until when. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + */ + previewNote() { + return previewNoteText(this.form.publishAt, getCanonicalLocale()) + }, + + /** @return {Array<object>} */ + levelOptions() { + return [ + { value: 'info', label: t('launchpad', 'Information') }, + { value: 'warning', label: t('launchpad', 'Warning') }, + ] + }, + + /** + * @return {object} The fields the API takes. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + payload() { + const isNotice = this.form.kind === 'notice' + return { + kind: this.form.kind, + title: this.form.title.trim(), + body: this.form.body, + category: this.form.category.trim() || null, + targetGroups: this.form.targetGroups, + level: isNotice ? this.form.level : null, + dismissible: isNotice ? this.form.dismissible : false, + allowComments: isNotice ? false : this.form.allowComments, + publishAt: toIso(this.form.publishAt), + expiresAt: toIso(this.form.expiresAt), + requiresConfirmation: !isNotice && this.form.requiresConfirmation, + confirmBefore: !isNotice && this.form.requiresConfirmation ? confirmBeforeIso(this.form.confirmBefore) : null, + } + }, + + /** + * The end time as the preview names it. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md#requirement-authors-publish-targeted-announcements-req-ann-001 + */ + visibleUntil() { + return visibleUntilText(this.form.expiresAt, getCanonicalLocale()) + }, + + /** + * Whether the publish time lies in the future, so the confirm button + * schedules rather than publishes. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md#requirement-authors-publish-targeted-announcements-req-ann-001 + */ + scheduled() { + const start = toIso(this.form.publishAt) + return start !== null && new Date(start).getTime() > Date.now() + }, + + /** @return {object} The draft as the card or banner renders it. */ + previewItem() { + return { uuid: this.uuid || 'preview', ...this.payload } + }, + }, + + watch: { + 'form.targetGroups': { + /** @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 */ + handler() { + this.loadReach() + }, + + deep: true, + }, + }, + + /** @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 */ + mounted() { + this.loadGroups() + this.loadReach() + }, + + methods: { + n, + t, + + /** + * Save the announcement and publish it, or schedule it for its + * publish time, in one step (REQ-ANN-006). + * + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + * @spec openspec/changes/archive/2026-11-24-announcement-show-until/specs/announcements/spec.md#requirement-authors-publish-targeted-announcements-req-ann-001 + */ + async submit() { + if (this.busy || this.form.title.trim() === '') { + return + } + const problem = endTimeProblem(this.form.publishAt, this.form.expiresAt, new Date()) + || confirmBeforeProblem(this.form.publishAt, this.payload.confirmBefore, new Date()) + if (problem !== '') { + this.error = problem + return + } + await this.run(async () => { + const saved = this.uuid + ? await announcementsApi.update(this.uuid, this.payload) + : await announcementsApi.create(this.payload) + this.uuid = saved.uuid + const published = await announcementsApi.publish(this.uuid) + this.$emit('published', published) + }) + }, + + /** + * Count the people the target groups reach; the preview keeps the + * last count when the server does not answer. + * + * @return {Promise<void>} + * @spec openspec/changes/engagement-announcements/specs/announcements/spec.md#requirement-authors-preview-before-publishing-req-ann-004 + */ + async loadReach() { + try { + this.reach = (await announcementsApi.reach(this.form.targetGroups)) ?? 0 + } catch (error) { + logger.error('Announcement reach failed:', error) + } + }, + + /** + * Load the groups the target group picker offers. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + */ + async loadGroups() { + try { + this.groups = (await announcementsApi.groups()) ?? [] + } catch (error) { + logger.error('Announcement groups failed:', error) + } + }, + + /** @spec openspec/changes/engagement-announcements/tasks.md#task-8 */ + async checkPreviewAs() { + const user = this.previewAs.trim() + await this.run(async () => { + const { reachesUser } = await announcementsApi.reachFor(this.payload.targetGroups, user) + this.previewAsUser = user + this.previewAsAnswer = reachesUser === true + }) + }, + + /** + * Run one API step, showing the server's refusal. + * + * @param {Function} step The step. + * @return {Promise<void>} + */ + async run(step) { + this.busy = true + this.error = '' + try { + await step() + } catch (error) { + logger.error('Announcement editor step failed:', error) + this.error = error?.response?.data?.message ?? error?.response?.data?.error ?? t('launchpad', 'Something went wrong') + } finally { + this.busy = false + } + }, + }, +} +</script> + +<style scoped> +.announcement-editor { + display: flex; + flex-direction: column; + gap: 12px; + padding: 16px; +} + +.announcement-editor__columns { + display: grid; + grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); + gap: 24px; + align-items: start; +} + +.announcement-editor__form, +.announcement-editor__preview { + display: flex; + flex-direction: column; + gap: 12px; +} + +.announcement-editor__preview { + padding: 12px; + border-radius: var(--border-radius-large); + background: var(--color-background-dark); +} + +.announcement-editor__preview-title { + margin: 0; + font-size: 1em; +} + +.announcement-editor__kinds { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; + margin: 0; + padding: 0; + border: 0; +} + +.announcement-editor__kinds legend { + margin-bottom: 4px; +} + +.announcement-editor__kind { + position: relative; + display: flex; + flex-direction: column; + gap: 4px; + padding: 12px; + border: 2px solid var(--color-border); + border-radius: var(--border-radius-large); + cursor: pointer; +} + +.announcement-editor__kind--chosen { + border-color: var(--color-primary-element); +} + +.announcement-editor__kind:focus-within { + outline: 2px solid var(--color-main-text); + outline-offset: 2px; +} + +.announcement-editor__kind-input { + position: absolute; + opacity: 0; + pointer-events: none; +} + +.announcement-editor__kind-label { + font-weight: bold; +} + +.announcement-editor__kind-hint { + color: var(--color-text-maxcontrast); +} + +.announcement-editor__times { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} + +.announcement-editor__label { + display: flex; + flex-direction: column; + gap: 4px; +} + +.announcement-editor__hint { + margin: -8px 0 0; + color: var(--color-text-maxcontrast); +} + +.announcement-editor__preview .announcement-editor__hint { + margin: 0; +} + +.announcement-editor__preview-as { + display: flex; + align-items: flex-end; + gap: 8px; +} + +.announcement-editor__actions { + display: flex; + justify-content: flex-end; + gap: 8px; +} + +.announcement-editor__error { + color: var(--color-error-text, var(--color-error)); +} + +@media (max-width: 720px) { + .announcement-editor__columns, + .announcement-editor__times { + grid-template-columns: 1fr; + } +} +</style> diff --git a/src/modals/BookmarkImportModal.vue b/src/modals/BookmarkImportModal.vue new file mode 100644 index 000000000..bfaf931c5 --- /dev/null +++ b/src/modals/BookmarkImportModal.vue @@ -0,0 +1,363 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcModal + v-model:show="isOpen" + class="launchpad-modal" + :name="t('launchpad', 'Import bookmarks')" + size="normal" + @close="$emit('close')"> + <div class="bookmark-import" data-testid="bookmark-import"> + <h2>{{ t('launchpad', 'Import bookmarks') }}</h2> + <p class="bookmark-import__hint"> + {{ t('launchpad', 'Choose the bookmarks file your browser exported, then tick what to add.') }} + </p> + + <input + type="file" + accept=".html,.htm,text/html" + :aria-label="t('launchpad', 'Import bookmarks')" + data-testid="bookmark-import-file" + @change="onFile($event.target.files && $event.target.files[0])"> + + <p + v-if="error" + class="bookmark-import__error" + role="alert" + data-testid="bookmark-import-error"> + {{ error }} + </p> + + <fieldset v-if="parsed && parsed.folders.length > 0" class="bookmark-import__group"> + <legend>{{ t('launchpad', 'Folders') }}</legend> + <label + v-for="(folder, index) in parsed.folders" + :key="'f' + index" + class="bookmark-import__option"> + <input + type="checkbox" + :checked="folderIndexes.has(index)" + :disabled="folder.bookmarks.length === 0" + data-testid="bookmark-import-folder" + @change="toggle(folderIndexes, index, $event.target.checked)"> + {{ folder.name }} ({{ folder.bookmarks.length }}) + </label> + </fieldset> + + <fieldset v-if="parsed && parsed.bookmarks.length > 0" class="bookmark-import__group"> + <legend>{{ t('launchpad', 'Loose bookmarks') }}</legend> + <label + v-for="(bookmark, index) in parsed.bookmarks" + :key="'b' + index" + class="bookmark-import__option"> + <input + type="checkbox" + :checked="bookmarkIndexes.has(index)" + data-testid="bookmark-import-bookmark" + @change="toggle(bookmarkIndexes, index, $event.target.checked)"> + {{ bookmark.title }} + </label> + </fieldset> + + <p + v-if="skipped.length > 0" + class="bookmark-import__note" + role="status" + data-testid="bookmark-import-skipped"> + {{ t('launchpad', '{count} skipped: only web addresses can become tiles', { count: skipped.length }) }} + </p> + + <div class="bookmark-import__actions"> + <NcButton @click="close"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + variant="primary" + :disabled="!canImport" + data-testid="bookmark-import-confirm" + @click="submit"> + {{ t('launchpad', 'Import bookmarks') }} + </NcButton> + </div> + </div> + </NcModal> +</template> + +<script> +import { t } from '@nextcloud/l10n' +import { NcButton, NcModal } from '@nextcloud/vue' +import { chosenBookmarks, readBookmarkFile } from '../utils/bookmarkFile.js' + +/** + * BookmarkImportModal — import a browser bookmarks file as tiles + * (launcher-bookmark-import REQ-BMI-001..004). + * + * The file is read in the browser; the user ticks folders and loose + * bookmarks; only those are sent. The server skips addresses that are not + * web addresses and lists them back, and refuses with 409 an import the + * dashboard has no room for. + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md + */ +export default { + name: 'BookmarkImportModal', + + components: { NcButton, NcModal }, + + props: { + /** Whether the dialog is open. */ + open: { type: Boolean, default: false }, + /** + * Sends the chosen bookmarks; resolves to `{placements, skipped}` and + * rejects with the axios error (409 carries `limit` and `current`). + */ + importBookmarks: { type: Function, required: true }, + /** A file to read on open, handed over by Add tiles (REQ-TILE-043). */ + initialFile: { type: Object, default: null }, + }, + + emits: ['close', 'imported'], + + data() { + return { + parsed: null, + folderIndexes: new Set(), + bookmarkIndexes: new Set(), + error: '', + skipped: [], + busy: false, + } + }, + + computed: { + /** + * Bound to the modal's visibility. + * + * @return {boolean} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ + isOpen: { + /** + * Whether the dialog shows. + * + * @return {boolean} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ + get() { + return this.open + }, + + /** + * Closing the modal closes the dialog. + * + * @param {boolean} value Whether it shows. + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ + set(value) { + if (!value) { + this.close() + } + }, + }, + + /** + * Whether something is chosen and nothing is in flight. + * + * @return {boolean} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ + canImport() { + return !this.busy && this.parsed !== null && (this.folderIndexes.size + this.bookmarkIndexes.size) > 0 + }, + }, + + watch: { + /** + * Read the handed-over file when the dialog opens with one. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + open: { + immediate: true, + /** + * @param {boolean} value whether the dialog is open. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + handler(value) { + if (value && this.initialFile) { + this.onFile(this.initialFile) + } + }, + }, + }, + + methods: { + /** + * Read the chosen file, refusing a too large one before anything is sent + * (REQ-BMI-004), and tick every folder and bookmark in it. + * + * @param {File|undefined} file The chosen file. + * @return {Promise<void>} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-large-files-are-refused-in-the-browser-req-bmi-004 + */ + async onFile(file) { + this.reset() + if (!file) { + return + } + try { + const parsed = await readBookmarkFile(file) + if (parsed.total === 0) { + this.error = t('launchpad', 'This file holds no bookmarks.') + return + } + this.parsed = parsed + this.folderIndexes = new Set(parsed.folders.map((_f, i) => i).filter((i) => parsed.folders[i].bookmarks.length > 0)) + this.bookmarkIndexes = new Set(parsed.bookmarks.map((_b, i) => i)) + } catch (e) { + this.error = this.refusal(e) + } + }, + + /** + * The message for a refused file. + * + * @param {Error & {code?: string}} e The refusal. + * @return {string} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-large-files-are-refused-in-the-browser-req-bmi-004 + */ + refusal(e) { + if (e && e.code === 'too-large') { + return t('launchpad', 'This file is larger than 5 MB. Export one folder at a time.') + } + if (e && e.code === 'too-many') { + return t('launchpad', 'This file has more than 2,000 bookmarks. Export one folder at a time.') + } + return t('launchpad', 'This file holds no bookmarks.') + }, + + /** + * Tick or untick one folder or bookmark. + * + * @param {Set<number>} set The chosen indexes. + * @param {number} index The item. + * @param {boolean} checked Whether it is ticked now. + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ + toggle(set, index, checked) { + const next = new Set(set) + if (checked) { + next.add(index) + } else { + next.delete(index) + } + if (set === this.folderIndexes) { + this.folderIndexes = next + } else { + this.bookmarkIndexes = next + } + }, + + /** + * Send the chosen bookmarks. On success the dialog reports the skipped + * ones or closes; on 409 it says how much room is left (REQ-BMI-003). + * + * @return {Promise<void>} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-the-import-respects-the-widget-quota-as-one-operation-req-bmi-003 + */ + async submit() { + if (!this.canImport) { + return + } + this.busy = true + this.error = '' + try { + const result = await this.importBookmarks(chosenBookmarks(this.parsed, this.folderIndexes, this.bookmarkIndexes)) + this.skipped = Array.isArray(result?.skipped) ? result.skipped : [] + this.$emit('imported', result) + if (this.skipped.length === 0) { + this.close() + } else { + this.parsed = null + } + } catch (e) { + const body = e?.response?.data + if (e?.response?.status === 409 && Number.isFinite(body?.limit) && Number.isFinite(body?.current)) { + this.error = t('launchpad', 'This dashboard can take {count} more. Choose fewer folders or bookmarks.', { count: Math.max(0, body.limit - body.current) }) + } else { + this.error = t('launchpad', 'The bookmarks could not be imported.') + } + } finally { + this.busy = false + } + }, + + /** + * Clear what the dialog read and reported. + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ + reset() { + this.parsed = null + this.folderIndexes = new Set() + this.bookmarkIndexes = new Set() + this.error = '' + this.skipped = [] + }, + + /** + * Close and forget. + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ + close() { + this.reset() + this.$emit('close') + }, + }, +} +</script> + +<style scoped> +.bookmark-import { + display: flex; + flex-direction: column; + gap: 12px; + padding: 16px; +} + +.bookmark-import__hint, +.bookmark-import__note { + color: var(--color-text-maxcontrast); +} + +.bookmark-import__error { + color: var(--color-error-text, var(--color-error)); +} + +.bookmark-import__group { + display: flex; + flex-direction: column; + gap: 4px; + max-height: 240px; + overflow-y: auto; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); + padding: 8px; +} + +.bookmark-import__option { + display: flex; + gap: 8px; + align-items: center; +} + +.bookmark-import__actions { + display: flex; + justify-content: flex-end; + gap: 8px; +} +</style> diff --git a/src/modals/DashboardConfigModal.vue b/src/modals/DashboardConfigModal.vue index 688e17020..3a171d44f 100644 --- a/src/modals/DashboardConfigModal.vue +++ b/src/modals/DashboardConfigModal.vue @@ -4,11 +4,24 @@ --> <template> - <NcModal v-if="open" size="normal" :name="modalTitle" @close="$emit('close')"> + <NcModal + v-if="open" + class="launchpad-modal launchpad-modal--wide" + size="normal" + :name="modalTitle" + @close="$emit('close')"> <div class="dashboard-config"> - <h2 class="dashboard-config__title"> - {{ modalTitle }} - </h2> + <header class="dashboard-config__head"> + <p + v-if="!isCreate && dashboard?.name" + class="launchpad-modal__kicker" + data-testid="dashboard-config-kicker"> + {{ dashboard.name }} + </p> + <h2 class="dashboard-config__title launchpad-modal__title"> + {{ modalTitle }} + </h2> + </header> <!-- Tab strip (dashboard-sharing spec). Sharing is no longer a free-floating field set in the modal body — it lives in its @@ -17,9 +30,11 @@ follow the fleet tablist pattern (nc-vue CnTabbedFormDialog / NC sidebar tabs): justified tabs, icon + label, active primary underline. --> + <!-- cn-look-board keeps the theme's button rules off the tabs, + which are drawn as words on an underline, not as buttons. --> <ul v-if="!isCreate" - class="dashboard-config__tabs" + class="dashboard-config__tabs cn-look-board" role="tablist" data-test="config-tabs"> <li @@ -38,8 +53,15 @@ }" :data-test="`config-tab-${tab.id}`" @click="currentTab = tab.id"> - <component :is="tab.icon" v-if="tab.icon" :size="16" /> + <!-- LpDashboardInstellingen draws the tabs as words alone, so the + strip fits the dialog without scrolling sideways. --> <span>{{ tab.label }}</span> + <span + v-if="tab.count" + class="dashboard-config__tab-count" + :data-test="`config-tab-count-${tab.id}`"> + {{ tab.count }} + </span> </button> </li> </ul> @@ -93,6 +115,9 @@ trackBy="uuid" :clearable="false" data-testid="dashboard-parent-select" /> + <span class="dashboard-config__hint" data-testid="dashboard-parent-hint"> + {{ t('launchpad', 'This builds a tree of dashboards under Dashboards in the More menu') }} + </span> </div> <div class="dashboard-config__field"> <NcTextField @@ -107,6 +132,34 @@ data-testid="dashboard-slug-input" @update:modelValue="form.slug = $event" /> </div> + <!-- launcher-tile-open-behaviour D2: how a tile without its + own choice opens on this dashboard. --> + <div class="dashboard-config__field"> + <NcSelect + v-model="form.defaultLinkTarget" + :inputLabel="t('launchpad', 'Opens in')" + :options="linkTargetChoices" + label="label" + trackBy="id" + :clearable="false" + data-testid="dashboard-link-target-select" /> + </div> + <!-- REQ-CWF-011: the hierarchies the filter bus joins widgets on. --> + <div class="dashboard-config__field"> + <NcSelect + v-model="form.hierarchies" + :inputLabel="t('launchpad', 'Drill-down levels')" + :options="hierarchyChoices" + label="name" + trackBy="id" + multiple + keepOpen + :placeholder="t('launchpad', 'None')" + data-testid="dashboard-hierarchies-select" /> + <span class="dashboard-config__hint"> + {{ t('launchpad', 'A click on an area in one widget filters the other widgets, and a click on a smaller area also selects the area it belongs to.') }} + </span> + </div> </template> <p v-if="saveError" @@ -125,21 +178,9 @@ :uploadFn="iconUploadFn" @input="form.icon = $event" /> </div> - </div> - <!-- /general panel --> - - <!-- - Wave3.8 — explicit "default dashboard" pin. Lives in its own - Default tab now (dashboard-sharing spec tab split). Wrapped in - `v-if="!isCreate"` because pinning a not-yet-saved dashboard is - meaningless. - --> - <div - v-show="!isCreate && currentTab === 'default'" - id="config-panel-default" - role="tabpanel" - data-test="config-panel-default" - class="dashboard-config__panel"> + <!-- The default switch and the detail fields live under Details, + as board LpDashboardInstellingen draws them (three tabs: + Details, Talen, Delen). --> <div v-if="!isCreate" class="dashboard-config__field dashboard-config__field--toggle"> @@ -158,8 +199,110 @@ </span> </NcCheckboxRadioSwitch> </div> + <DetailsTab + v-if="!isCreate && canManageShares && dashboard?.uuid" + :dashboardUuid="dashboard.uuid" /> + <!-- Display (REQ-THM-004): the instance theme, read-only; a + dashboard picks no theme and no layout preset. --> + <section + v-if="!isCreate && canManageShares" + class="dashboard-config__display" + data-test="config-display"> + <h3 class="dashboard-config__section-heading"> + {{ t('launchpad', 'Display') }} + </h3> + <div class="dashboard-config__field"> + <NcTextField + :modelValue="themeName" + :label="t('launchpad', 'Theme')" + readonly + data-testid="display-theme" /> + <p class="dashboard-config__hint" data-testid="display-theme-hint"> + {{ t('launchpad', 'The theme is the same for every dashboard. Set this dashboard\'s own colours under Own look.') }} + </p> + </div> + </section> + <!-- Own look (REQ-THM-001/002, board LpDashboardInstellingen): + accent, background colour and background image of THIS + dashboard, a block on Details with the same contrast check + the server applies; there is no separate Look tab. --> + <section + v-if="!isCreate && canManageShares" + class="dashboard-config__look" + data-test="config-look"> + <h3 class="dashboard-config__section-heading"> + {{ t('launchpad', 'Own look') }} + </h3> + <p class="dashboard-config__hint"> + {{ t('launchpad', 'Give this dashboard its own colors. Leave a field empty to follow the theme.') }} + </p> + <div class="dashboard-config__field dashboard-config__look-row"> + <NcTextField + :modelValue="look.accent" + :label="t('launchpad', 'Accent color')" + placeholder="#1f5c3a" + data-testid="look-accent" + @update:modelValue="look.accent = $event" /> + <input + type="color" + class="dashboard-config__swatch" + :value="lookAccentHex || '#000000'" + :aria-label="t('launchpad', 'Accent color')" + @input="look.accent = $event.target.value"> + </div> + <div class="dashboard-config__field dashboard-config__look-row"> + <NcTextField + :modelValue="look.background" + :label="t('launchpad', 'Background color')" + placeholder="#ffffff" + data-testid="look-background" + @update:modelValue="look.background = $event" /> + <input + type="color" + class="dashboard-config__swatch" + :value="lookBackgroundHex || '#ffffff'" + :aria-label="t('launchpad', 'Background color')" + @input="look.background = $event.target.value"> + </div> + <p + v-if="lookFormatError" + class="dashboard-config__error" + role="alert" + data-testid="look-format-error"> + {{ lookFormatError }} + </p> + <p + v-else-if="!lookAccentCheck.readable" + class="dashboard-config__error" + role="alert" + data-testid="look-contrast-error"> + {{ t('launchpad', 'Buttons in this colour are hard to see (contrast {ratio} to 1, needs 3 to 1)', { ratio: lookAccentCheck.ratio.toFixed(1) }) }} + </p> + <div class="dashboard-config__field"> + <label class="dashboard-config__label" for="look-image-input"> + {{ t('launchpad', 'Image') }} + </label> + <input + id="look-image-input" + type="file" + accept="image/png,image/jpeg,image/gif,image/webp,image/svg+xml" + data-testid="look-image-input" + :disabled="lookUploading" + @change="onLookImage"> + <p v-if="look.resource" class="dashboard-config__hint" data-testid="look-image-name"> + {{ look.resource }} + <NcButton variant="tertiary" data-testid="look-image-clear" @click="look.resource = ''"> + {{ t('launchpad', 'Remove') }} + </NcButton> + </p> + <p v-if="lookUploadError" class="dashboard-config__error" role="alert"> + {{ lookUploadError }} + </p> + </div> + </section> </div> - <!-- /default panel --> + <!-- /general panel --> + <div v-if="!isCreate && currentTab === 'languages' && dashboard?.uuid" @@ -170,14 +313,6 @@ <LanguagesTab :dashboardUuid="dashboard.uuid" /> </div> - <div - v-if="!isCreate && currentTab === 'details' && dashboard?.uuid" - id="config-panel-details" - role="tabpanel" - data-test="config-panel-details" - class="dashboard-config__panel"> - <DetailsTab :dashboardUuid="dashboard.uuid" /> - </div> <!-- Sharing panel (dashboard-sharing spec). The sharee picker and per-share permission rows are reachable ONLY from this tab. --> @@ -194,30 +329,39 @@ {{ t('launchpad', 'Share with users and groups') }} </label> - <NcSelect - :modelValue="null" - :options="shareeOptions" - :filterable="false" - :loading="shareeLoading" - :aria-label-combobox=" - t('launchpad', 'Share with users and groups') - " - :placeholder="t('launchpad', 'Search users and groups…')" - label="displayName" - trackBy="key" - :clearable="false" - @search="onShareeSearch" - @update:modelValue="onShareeSelected"> - <template #option="option"> - <span class="sharee-option"> - <AccountGroup - v-if="option.shareType === 'group'" - :size="18" /> - <Account v-else :size="18" /> - {{ option.displayName }} - </span> - </template> - </NcSelect> + <!-- REQ-SHARE-015: under Nobody only an administrator adds shares. --> + <template v-if="sharingPolicy.mayShare"> + <NcSelect + :modelValue="null" + :options="shareeOptions" + :filterable="false" + :loading="shareeLoading" + :aria-label-combobox=" + t('launchpad', 'Share with users and groups') + " + :placeholder="t('launchpad', 'Search users and groups…')" + label="displayName" + trackBy="key" + :clearable="false" + @search="onShareeSearch" + @update:modelValue="onShareeSelected"> + <template #option="option"> + <span class="sharee-option"> + <AccountGroup + v-if="option.shareType === 'group'" + :size="18" /> + <Account v-else :size="18" /> + {{ option.displayName }} + </span> + </template> + </NcSelect> + </template> + <p + v-else + class="dashboard-config__hint" + data-test="share-not-allowed-hint"> + {{ t('launchpad', 'Your administrator does not allow you to share dashboards.') }} + </p> <ul v-if="localShares.length > 0" @@ -259,6 +403,14 @@ <p v-else class="dashboard-config__hint"> {{ t('launchpad', 'Not shared with anyone yet.') }} </p> + <p + v-if="localShares.length > 0 && isUnpublished" + class="dashboard-config__hint" + data-test="share-unpublished-hint"> + {{ + t('launchpad', 'Colleagues see this dashboard once you publish it') + }} + </p> <p v-if="sharesDirty" class="dashboard-config__hint dashboard-config__hint--dirty"> @@ -352,20 +504,31 @@ {{ t('launchpad', 'No public links yet.') }} </p> - <div class="dashboard-config__public-create"> + <p + v-if="!canCreatePublicLink" + class="dashboard-config__hint" + data-test="public-share-off-hint"> + {{ t('launchpad', 'Public links are switched off.') }} + </p> + <div v-else class="dashboard-config__public-create"> <NcTextField v-model="newSharePassword" type="password" :label="t('launchpad', 'Password (optional)')" autocomplete="new-password" /> + <!-- REQ-SHARE-015: every new public link has an expiry date. --> <input v-model="newShareExpiry" class="dashboard-config__public-date" type="date" - :aria-label="t('launchpad', 'Expiry date (optional)')" /> + required + aria-required="true" + data-test="public-share-expiry" + :aria-label="t('launchpad', 'Expiry date (required)')" /> <NcButton variant="secondary" - :disabled="creatingPublicShare" + data-test="public-share-create" + :disabled="creatingPublicShare || !newShareExpiry" @click="onCreatePublicShare"> <template #icon> <Plus :size="20" /> @@ -374,10 +537,60 @@ </NcButton> </div> </div> + + <!-- REQ-LEAF-006: the Talk conversation beside a shared dashboard. --> + <SharingConversation + v-if="!isCreate && canManageShares" + :dashboard="dashboard" + :shared="isSharedDashboard" + @update:conversationEnabled="onConversationChanged" /> + + <!-- REQ-EMB-011: the dashboard's embed tokens. The embed token + API is admin-only, so the part is too. --> + <SharingEmbedTokens + v-if="!isCreate && canManageShares && isAdmin && currentTab === 'sharing'" + :dashboard="dashboard" /> </div> <!-- /sharing panel --> - <div class="dashboard-config__actions"> + <!-- REQ-SCHEDUI-001: publish, unpublish and the schedule. --> + <div + v-if="!isCreate && currentTab === 'publication'" + id="config-panel-publication" + role="tabpanel" + data-test="config-panel-publication" + class="dashboard-config__panel"> + <PublicationTab :dashboard="dashboard" /> + </div> + + <!-- REQ-SCH-011: the scheduled exports of this dashboard. --> + <div + v-if="!isCreate && currentTab === 'exports'" + id="config-panel-exports" + role="tabpanel" + data-test="config-panel-exports" + class="dashboard-config__panel"> + <ExportsTab + :subjects="exportSubjects" + :defaultSubject="{ type: 'dashboard', id: dashboard.uuid }" /> + </div> + + <!-- Board LpVersies: the saved versions of this dashboard. --> + <div + v-if="!isCreate && currentTab === 'versions'" + id="config-panel-versions" + role="tabpanel" + data-test="config-panel-versions" + class="dashboard-config__panel"> + <VersionsTab + :dashboardUuid="dashboard.uuid" + @restored="$emit('versionRestored', $event)" + @close="$emit('close')" /> + </div> + + <!-- The Versions tab ends in its own Close and Restore this version + (LpVersies); the dialog's Save does not apply there. --> + <div v-if="currentTab !== 'versions' || isCreate" class="dashboard-config__actions"> <NcButton v-if="canDelete && !isCreate" variant="error" @@ -424,27 +637,43 @@ import { NcSelect, NcTextField, } from '@nextcloud/vue' +import { defineAsyncComponent } from 'vue' import Account from 'vue-material-design-icons/Account.vue' import AccountGroup from 'vue-material-design-icons/AccountGroup.vue' +import CalendarClock from 'vue-material-design-icons/CalendarClock.vue' +import CalendarExport from 'vue-material-design-icons/CalendarExport.vue' import Check from 'vue-material-design-icons/Check.vue' import Close from 'vue-material-design-icons/Close.vue' import ContentCopy from 'vue-material-design-icons/ContentCopy.vue' import ContentSave from 'vue-material-design-icons/ContentSave.vue' import Delete from 'vue-material-design-icons/Delete.vue' import FormatListBulleted from 'vue-material-design-icons/FormatListBulleted.vue' +import History from 'vue-material-design-icons/History.vue' import Lock from 'vue-material-design-icons/Lock.vue' import Plus from 'vue-material-design-icons/Plus.vue' import ShareVariant from 'vue-material-design-icons/ShareVariant.vue' -import StarOutline from 'vue-material-design-icons/StarOutline.vue' import Translate from 'vue-material-design-icons/Translate.vue' -import Tune from 'vue-material-design-icons/Tune.vue' import DetailsTab from '../components/Workspace/config/DetailsTab.vue' import LanguagesTab from '../components/Workspace/config/LanguagesTab.vue' +import SharingConversation from '../components/Workspace/config/SharingConversation.vue' +import { FLAG_PROP, LIST_PROP, NULLABLE_OBJECT_PROP, TEXT_PROP } from '../constants/propDefinitions.js' import { api } from '../services/api.js' -import { ICON_CATALOGUE } from '../services/iconCatalogue.js' -import { uploadDataUrl } from '../services/resourceService.js' +import { DASHBOARD_ICON_CATALOGUE } from '../services/iconCatalogue.js' +import { uploadDataUrl, uploadFile } from '../services/resourceService.js' import { usePublicShareStore } from '../stores/publicShares.js' +import { isCollaborative } from '../utils/dashboardDiscussion.js' +import { accentCheck, normaliseHex } from '../utils/dashboardLook.js' +import { hierarchyPresets } from '../utils/hierarchyPresets.js' +import { instanceThemeName } from '../utils/instanceTheme.js' +import { readSharingPolicy } from '../utils/loadInitialState.js' import { logger } from '../utils/logger.js' +import { NEW_TAB, SAME_TAB, SIDE_PANEL } from '../utils/tileLinkTarget.js' + +/* Loaded when their tab opens: they bring the export editor and the store. */ +const SharingEmbedTokens = defineAsyncComponent(() => import('../components/Workspace/config/SharingEmbedTokens.vue')) +const ExportsTab = defineAsyncComponent(() => import('../components/Workspace/config/ExportsTab.vue')) +const PublicationTab = defineAsyncComponent(() => import('../components/Workspace/config/PublicationTab.vue')) +const VersionsTab = defineAsyncComponent(() => import('../components/Workspace/config/VersionsTab.vue')) const PERMISSION_OPTIONS = [ { value: 'view_only', label: 'View only' }, @@ -452,12 +681,28 @@ const PERMISSION_OPTIONS = [ { value: 'full', label: 'Full access' }, ] +/** + * The ids of picked hierarchy choices, as one comparable string. + * + * @param {Array<{id: string}>} choices The choices. + * @return {string} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ +function hierarchyIds(choices) { + return (choices || []).map((choice) => choice.id).join('\n') +} + export default { name: 'DashboardConfigModal', components: { DetailsTab, + ExportsTab, LanguagesTab, + SharingConversation, + SharingEmbedTokens, + PublicationTab, + VersionsTab, NcModal, NcButton, NcTextField, @@ -469,30 +714,27 @@ export default { Close, Account, AccountGroup, - Tune, - ShareVariant, - StarOutline, ContentCopy, Check, Lock, CnIconBrowser, }, - props: { - open: { - type: Boolean, + inject: { + // Server-computed admin flag (PageController initial state); only + // decides whether the embed tokens show. The server checks again. + isAdmin: { + from: 'isAdmin', default: false, }, + }, - dashboard: { - type: Object, - default: null, - }, + props: { + open: FLAG_PROP, - canDelete: { - type: Boolean, - default: false, - }, + dashboard: NULLABLE_OBJECT_PROP, + + canDelete: FLAG_PROP, mode: { type: String, @@ -507,25 +749,28 @@ export default { * fetches it once via `GET /api/dashboards/default` and * passes it down both here and to `DashboardSwitcherSidebar`. */ - defaultUuid: { - type: String, - default: '', - }, + defaultUuid: TEXT_PROP, /** * Dashboards that may be chosen as parent (dashboard-tree-navigation). * The server refuses a cycle; the host leaves the dashboard itself out. */ - parentOptions: { - type: Array, - default: () => [], - }, + parentOptions: LIST_PROP, /** Why the last save was refused, shown in the General tab. */ - saveError: { - type: String, - default: '', - }, + saveError: TEXT_PROP, + + /** Whether the Publication tab is offered: the owner or an administrator. */ + canManagePublication: FLAG_PROP, + + /** Whether the Exports tab is offered. */ + canScheduleExports: FLAG_PROP, + + /** Whether the Versions tab is offered: the owner or an administrator. */ + canViewVersions: FLAG_PROP, + + /** This dashboard and its widgets as export subjects: `{type, id, label}`. */ + exportSubjects: LIST_PROP, /** * Tab to land on when the modal opens (dashboard-sharing spec). The @@ -535,15 +780,17 @@ export default { initialTab: { type: String, default: 'general', - validator: (v) => ['general', 'sharing', 'default'].includes(v), + validator: (v) => ['general', 'sharing', 'default', 'publication', 'exports'].includes(v), }, }, - emits: ['close', 'save', 'delete', 'setDefault'], + emits: ['close', 'save', 'delete', 'setDefault', 'versionRestored'], data() { return { - currentTab: this.initialTab || 'general', + currentTab: + this.initialTab === 'default' ? 'general' : this.initialTab || 'general', + form: { name: '', description: '', @@ -561,9 +808,19 @@ export default { // (uuid '' for none) and the web address name. parent: null, slug: '', + // launcher-tile-open-behaviour D2: `{id, label}`, id '' for + // the link-type rule. + defaultLinkTarget: null, + // REQ-CWF-011: the picked hierarchy choices, `{id, name, descriptor}`. + hierarchies: [], }, saving: false, + // REQ-THM-001: the look being edited, and the stored one it started from. + look: { accent: '', background: '', resource: '' }, + initialLook: { accent: '', background: '', resource: '' }, + lookUploading: false, + lookUploadError: '', // Server snapshot of shares as last loaded; used to compute dirty state. serverShares: [], // Local in-progress edit list; mutations buffer here until Save. @@ -587,6 +844,47 @@ export default { }, computed: { + /** + * The instance theme's name, shown read-only on Details. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md#requirement-the-details-tab-shows-the-instance-theme-read-only-req-thm-004 + */ + themeName() { + return instanceThemeName() + }, + + /** + * The hierarchies an owner can pick: the presets, then any other + * hierarchy the dashboard stores, so saving does not drop it. + * + * @return {Array<{id: string, name: string, descriptor: object}>} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + hierarchyChoices() { + const presets = hierarchyPresets() + const stored = Array.isArray(this.dashboard?.hierarchies) ? this.dashboard.hierarchies : [] + const others = stored + .filter((entry) => entry && typeof entry.id === 'string' && !presets.some((preset) => preset.id === entry.id)) + .map((entry) => ({ id: entry.id, name: entry.id, descriptor: entry })) + return [...presets, ...others] + }, + + /** + * The dashboard default choices for how tiles open. + * + * @return {Array<{id: string, label: string}>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + linkTargetChoices() { + return [ + { id: '', label: t('launchpad', 'Web addresses in a new tab, apps in the same tab') }, + { id: SAME_TAB, label: t('launchpad', 'Same tab') }, + { id: NEW_TAB, label: t('launchpad', 'New tab') }, + { id: SIDE_PANEL, label: t('launchpad', 'Panel beside the tiles') }, + ] + }, + /** * Parent choices: "No parent" first, then the other dashboards. * @@ -616,7 +914,7 @@ export default { * @return {object} the frozen icon catalogue. */ iconCatalogue() { - return ICON_CATALOGUE + return DASHBOARD_ICON_CATALOGUE }, /** @@ -638,47 +936,77 @@ export default { * Config-drawer tab descriptors. The Sharing tab is only offered when * the user can manage shares — REQ-SHARE-001 is owner-only, so a * recipient must not be shown a share-management surface at all. + * Publication is for the owner or an administrator (REQ-SCHEDUI-001), + * and so are the Versions (board LpVersies). * * @spec openspec/specs/dashboard-sharing/spec.md#req-share-001 + * @spec openspec/specs/dashboards/spec.md#requirement-req-dash-039-versions-are-a-tab-of-the-dashboard-settings + * @spec openspec/specs/dashboards/spec.md#requirement-a-manager-can-publish-unpublish-and-schedule-a-dashboard-req-schedui-001 + * @spec openspec/specs/scheduled-exports/spec.md#requirement-req-sch-011-scheduled-exports-live-in-the-dashboard-settings + * @spec openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 * @return {Array<{id: string, label: string}>} */ tabs() { - const list = [ - { id: 'general', label: t('launchpad', 'General'), icon: Tune }, + const hasUuid = Boolean(this.dashboard?.uuid) + return [ + { id: 'general', label: t('launchpad', 'Details'), icon: FormatListBulleted, offered: true }, + // dashboard-language-and-details-tabs: language versions, for the + // owner (a dashboard needs a uuid first, so the strip is hidden + // while creating). + { id: 'languages', label: t('launchpad', 'Languages'), icon: Translate, offered: this.canManageShares && hasUuid }, + { id: 'sharing', label: t('launchpad', 'Sharing'), icon: ShareVariant, count: this.localShares.length, offered: this.canManageShares }, + { id: 'publication', label: t('launchpad', 'Publication'), icon: CalendarClock, offered: this.canManagePublication && hasUuid }, + { id: 'exports', label: t('launchpad', 'Exports'), icon: CalendarExport, offered: this.canScheduleExports && hasUuid }, + { id: 'versions', label: t('launchpad', 'Versions'), icon: History, offered: this.canViewVersions && hasUuid }, ] - if (this.canManageShares) { - list.push({ - id: 'sharing', - label: t('launchpad', 'Sharing'), - icon: ShareVariant, - }) - } - list.push({ - id: 'default', - label: t('launchpad', 'Default'), - icon: StarOutline, - }) - // dashboard-language-and-details-tabs: language versions and - // detail fields, for the owner (a dashboard needs a uuid first, - // so the strip is hidden while creating). - if (this.canManageShares && this.dashboard?.uuid) { - list.push( - { - id: 'languages', - label: t('launchpad', 'Languages'), - icon: Translate, - }, - { - id: 'details', - label: t('launchpad', 'Details'), - icon: FormatListBulleted, - }, - ) - } - return list + .filter((tab) => tab.offered) + .map(({ offered, ...tab }) => tab) + }, + + /** + * Whether the dashboard is a draft or still scheduled, so share + * recipients do not see it yet (REQ-DASH-036). + * + * @return {boolean} + * @spec openspec/specs/dashboard-sharing/spec.md + */ + isUnpublished() { + const status = this.dashboard?.publicationStatus || 'published' + return status === 'draft' || status === 'scheduled' + }, + + /** + * Whether the dashboard is shared: a group dashboard or one with stored shares. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ + isSharedDashboard() { + return isCollaborative({ dashboard: this.dashboard, ownShares: this.serverShares }) }, /** @spec openspec/specs/dashboards/spec.md */ + /** + * What the Sharing tab may offer the viewer (REQ-SHARE-015). + * + * @return {{mayShare: boolean, publicLinksAllowed: boolean}} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + sharingPolicy() { + return readSharingPolicy() + }, + + /** + * Whether the viewer may create a public link: they may share and + * public links are on (REQ-SHARE-015). Existing links stay listed. + * + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + canCreatePublicLink() { + return this.sharingPolicy.mayShare && this.sharingPolicy.publicLinksAllowed + }, + canManageShares() { // Only the owner can see / manage shares. return ( @@ -691,7 +1019,7 @@ export default { modalTitle() { return this.isCreate ? t('launchpad', 'Create dashboard') - : t('launchpad', 'Dashboard configuration') + : t('launchpad', 'Dashboard settings') }, /** @spec openspec/specs/dashboards/spec.md */ @@ -730,7 +1058,62 @@ export default { /** @spec openspec/specs/dashboards/spec.md */ canSave() { - return this.form.name.trim().length > 0 + return this.form.name.trim().length > 0 && this.lookValid + }, + + /** @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 */ + lookAccentHex() { + return normaliseHex(this.look.accent) + }, + + /** @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 */ + lookBackgroundHex() { + return normaliseHex(this.look.background) + }, + + /** + * A colour field that holds something other than a colour. + * + * @return {string} the message, or '' when both fields are empty or colours. + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 + */ + lookFormatError() { + const bad = [this.look.accent, this.look.background].some( + (value) => String(value).trim() !== '' && normaliseHex(value) === null, + ) + return bad ? t('launchpad', 'Enter colors like #1f5c3a.') : '' + }, + + /** @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 */ + lookAccentCheck() { + return accentCheck(this.lookAccentHex, this.lookBackgroundHex) + }, + + /** @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-a-look-must-stay-readable-req-thm-002 */ + lookValid() { + return this.lookFormatError === '' && this.lookAccentCheck.readable + }, + + /** + * The look fields that changed, as the update route takes them ('' clears), + * or null when nothing changed, so a rename stays a metadata edit. + * + * @return {object|null} + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 + */ + lookPayload() { + const fields = { + themeAccent: ['accent', this.lookAccentHex ?? ''], + themeBackgroundColor: ['background', this.lookBackgroundHex ?? ''], + themeBackgroundResource: ['resource', this.look.resource || ''], + } + const payload = {} + for (const [field, [key, value]] of Object.entries(fields)) { + if (value !== (this.initialLook[key] || '')) { + payload[field] = value + } + } + return Object.keys(payload).length > 0 ? payload : null }, /** @spec openspec/specs/dashboards/spec.md */ @@ -770,7 +1153,9 @@ export default { // top-bar share action opens directly on Sharing). Fall back // to General if the requested tab is the share tab but the // user cannot manage shares. - const wanted = this.initialTab || 'general' + // `default` was its own tab; the switch now sits under Details. + const wanted + = this.initialTab === 'default' ? 'general' : this.initialTab || 'general' this.currentTab = wanted === 'sharing' && !this.canManageShares ? 'general' @@ -784,6 +1169,13 @@ export default { this.form.name = this.dashboard.name || '' this.form.description = this.dashboard.description || '' this.form.slug = this.dashboard.slug || '' + this.form.defaultLinkTarget = + this.linkTargetChoices.find( + (c) => c.id === (this.dashboard.defaultLinkTarget || ''), + ) || this.linkTargetChoices[0] + this._initialLinkTarget = this.form.defaultLinkTarget.id + this.form.hierarchies = this.storedHierarchyChoices() + this._initialHierarchies = hierarchyIds(this.form.hierarchies) this.form.parent = this.parentChoices.find( (p) => p.uuid === (this.dashboard.parentUuid || ''), @@ -794,6 +1186,14 @@ export default { // only null/empty falls back to DEFAULT_ICON // (REQ-ICON-002 + REQ-ICON-009). this.form.icon = this.dashboard.icon || DEFAULT_ICON + // REQ-THM-001: the stored look, and a snapshot to send only what changes. + this.initialLook = { + accent: this.dashboard.themeAccent || '', + background: this.dashboard.themeBackgroundColor || '', + resource: this.dashboard.themeBackgroundResource || '', + } + this.look = { ...this.initialLook } + this.lookUploadError = '' // Wave3.8 — initial toggle state mirrors whether // THIS dashboard's UUID matches the user's pinned // default. Snapshot for the dirty-check in onSave. @@ -812,7 +1212,60 @@ export default { }, methods: { + /** + * The conversation switch was stored: let the open page follow it. + * + * @param {number} value 1 shows the conversation, 0 hides it. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ + async onConversationChanged(value) { + // Loaded on use: the store module reads the user's language on import. + const { useDashboardStore } = await import('../stores/dashboard.js') + useDashboardStore().applyFieldsPatch(this.dashboard?.uuid, { conversationEnabled: value }) + }, + t, + + /** + * The choices of the hierarchies the dashboard stores, in stored order. + * + * @return {Array<{id: string, name: string, descriptor: object}>} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + storedHierarchyChoices() { + const stored = Array.isArray(this.dashboard?.hierarchies) ? this.dashboard.hierarchies : [] + return stored + .map((entry) => this.hierarchyChoices.find((choice) => choice.id === entry?.id)) + .filter(Boolean) + }, + + /** + * Upload a chosen background image through LaunchPad's resource + * uploads and keep its file name (REQ-THM-001). + * + * @param {Event} event The file input's change event. + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 + */ + async onLookImage(event) { + const file = event?.target?.files?.[0] + if (!file) { + return + } + this.lookUploading = true + this.lookUploadError = '' + try { + const resource = await uploadFile(file) + this.look.resource = resource.name + } catch (error) { + logger.error('Failed to upload the background image:', error) + this.lookUploadError = t('launchpad', 'Failed to upload image') + } finally { + this.lookUploading = false + } + }, + /** * Resolve a permission level to its select option, falling back to * the first option for unknown levels. @@ -869,18 +1322,18 @@ export default { * Mint a new public link, optionally password-protected and/or expiring. * * @spec openspec/changes/dashboard-public-share/specs/dashboard-public-share/spec.md + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 */ async onCreatePublicShare() { - if (!this.dashboard?.uuid) { + // REQ-SHARE-015: the server refuses a link without an expiry date. + if (!this.dashboard?.uuid || !this.newShareExpiry) { return } this.creatingPublicShare = true try { // The date input yields `YYYY-MM-DD`; the backend expects an // ISO 8601 instant, so pin expiry to end-of-day UTC. - const expiresAt = this.newShareExpiry - ? `${this.newShareExpiry}T23:59:59Z` - : null + const expiresAt = `${this.newShareExpiry}T23:59:59Z` await usePublicShareStore().createShare(this.dashboard.uuid, { password: this.newSharePassword || null, expiresAt, @@ -1105,6 +1558,16 @@ export default { : { parentUuid: this.form.parent?.uuid ?? '', slug: this.form.slug.trim(), + ...(this.lookPayload ? { look: this.lookPayload } : {}), + // Only when changed: it needs full edit rights, so a + // metadata-only editor's save must not carry it. + ...((this.form.defaultLinkTarget?.id ?? '') !== this._initialLinkTarget + ? { defaultLinkTarget: this.form.defaultLinkTarget?.id ?? '' } + : {}), + // REQ-CWF-011: only when changed, for the same reason. + ...(hierarchyIds(this.form.hierarchies) !== this._initialHierarchies + ? { hierarchies: this.form.hierarchies.map((choice) => choice.descriptor) } + : {}), }), }) @@ -1214,52 +1677,77 @@ export default { font-weight: 600; } -/* Fleet tablist design (nc-vue CnTabbedFormDialog / NC sidebar tabs): - justified full-width tabs, icon + label, primary underline on the - active tab, border underline on hover. */ +/* Tabs as boards LpDashboardInstellingen and LpDelen draw them: words on + the strip's rule, 44px high, the active one bold over a 3px primary line. */ .dashboard-config__tabs { display: flex; - justify-content: space-between; + flex-wrap: wrap; + justify-content: flex-start; + gap: 4px; list-style: none; - margin: 8px 0 16px; + /* Against the dialog's 20px gap: 12px under the title, 16px over the panel. */ + margin: -8px 0 -4px; padding: 0; border-bottom: 1px solid var(--color-border); } .dashboard-config__tab-item { display: flex; - flex: 1; -} - -.dashboard-config__tab-item:hover { - background-color: var(--color-background-hover); + flex: none; } -.dashboard-config__tab { - flex: 1; - display: flex; +.dashboard-config__tabs .dashboard-config__tab { + display: inline-flex; align-items: center; - justify-content: center; gap: 8px; - background: transparent; + width: auto; + height: 44px; + min-height: 44px; + margin: 0; + padding: 0 14px; border: 0; - border-bottom: 2px solid transparent; - padding: 10px; + /* Core's hover and focus rules for buttons colour the border with a + stronger selector; the underline is the tab's state, not the pointer's. */ + border-bottom: 3px solid transparent !important; + border-radius: 0; + background: transparent; cursor: pointer; - font: inherit; - text-align: center; - color: var(--color-text-maxcontrast); + font-family: var(--font-face); + font-size: 15px; + font-weight: 500; + white-space: nowrap; + color: color-mix(in srgb, var(--color-main-text) 85%, var(--color-main-background)); } -.dashboard-config__tab:hover { - border-bottom-color: var(--color-border); +.dashboard-config__tabs .dashboard-config__tab:hover { + background: transparent; + border-bottom-color: var(--color-border) !important; } -.dashboard-config__tab--active, -.dashboard-config__tab--active:hover { +.dashboard-config__tabs .dashboard-config__tab--active, +.dashboard-config__tabs .dashboard-config__tab--active:hover { color: var(--color-main-text); - border-bottom-color: var(--color-primary-element); - font-weight: 600; + border-bottom-color: var(--color-primary-element) !important; + font-weight: 700; +} + +/* + * Phone width (NcModal's own breakpoint): four labelled tabs need more room + * than the screen has, so the strip scrolls inside its own row instead of + * widening the modal body. + */ +@media only screen and (max-width: 512px) { + .dashboard-config__tabs { + overflow-x: auto; + } + + .dashboard-config__tab-item { + flex: 1 0 auto; + } + + .dashboard-config__tab { + white-space: nowrap; + } } .dashboard-config__panel { @@ -1394,6 +1882,7 @@ export default { display: flex; justify-content: space-between; align-items: center; + flex-wrap: wrap; gap: 12px; margin-top: 8px; } @@ -1444,4 +1933,43 @@ export default { .dashboard-config__error { color: var(--color-error-text); } + +/* The count on the Delen tab (board LpDashboardInstellingen). */ +.dashboard-config__tab-count { + min-width: 22px; + box-sizing: border-box; + padding: 0 6px; + border-radius: 11px; + background: var(--color-border); + font-size: 12px; + font-weight: 700; + line-height: 22px; + text-align: center; +} + +.dashboard-config__look { + margin-top: 16px; +} + +.dashboard-config__section-heading { + margin: 0 0 8px; + font-size: 1.1em; + font-weight: bold; +} + +.dashboard-config__look-row { + display: flex; + align-items: flex-end; + gap: 8px; +} + +.dashboard-config__swatch { + inline-size: 44px; + block-size: 44px; + padding: 2px; + border: 1px solid var(--color-border-dark); + border-radius: var(--border-radius); + background: var(--color-main-background); + cursor: pointer; +} </style> diff --git a/src/modals/PreviewModal.vue b/src/modals/PreviewModal.vue new file mode 100644 index 000000000..61d03fe82 --- /dev/null +++ b/src/modals/PreviewModal.vue @@ -0,0 +1,311 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcModal + v-if="open" + class="launchpad-modal launchpad-modal--wide" + size="large" + :name="t('launchpad', 'Preview')" + @close="$emit('close')"> + <div class="export-preview" data-testid="export-preview"> + <header> + <p class="launchpad-modal__kicker"> + {{ exportData?.name ?? '' }} + </p> + <h2 class="launchpad-modal__title"> + {{ t('launchpad', 'Preview') }} + </h2> + <p class="export-preview__hint"> + {{ + t( + 'launchpad', + 'The preview is made the way a recipient would get it, but nothing is sent.', + ) + }} + </p> + </header> + + <div class="export-preview__choices"> + <NcSelect + v-model="format" + :inputLabel="t('launchpad', 'Format')" + :options="formatOptions" + label="label" + :clearable="false" + data-testid="preview-format" /> + <NcSelect + v-model="recipient" + :inputLabel="t('launchpad', 'As received by')" + :options="recipientOptions" + label="label" + :clearable="false" + data-testid="preview-recipient" /> + <NcButton + variant="primary" + :disabled="loading || !format" + data-testid="preview-render" + @click="render"> + {{ t('launchpad', 'Make preview') }} + </NcButton> + </div> + + <div v-if="loading" class="export-preview__loading"> + <NcLoadingIcon :size="32" /> + </div> + <p + v-else-if="error" + class="export-preview__error" + role="alert" + data-testid="preview-error"> + {{ error }} + </p> + <template v-else-if="result"> + <object + v-if="result.format === 'pdf'" + class="export-preview__frame" + :data="result.url" + type="application/pdf" + :aria-label="t('launchpad', 'Preview of the PDF')" + data-testid="preview-pdf"> + <a :href="result.url" :download="result.filename">{{ + t('launchpad', 'Download the preview') + }}</a> + </object> + <img + v-else-if="result.format === 'png'" + class="export-preview__image" + :src="result.url" + :alt=" + t('launchpad', 'Preview of {name}', { + name: exportData?.name ?? '', + }) + " + data-testid="preview-png" /> + <p v-else data-testid="preview-download"> + {{ t('launchpad', 'This format cannot be shown here.') }} + <a :href="result.url" :download="result.filename">{{ + t('launchpad', 'Download {filename}', { + filename: result.filename, + }) + }}</a> + </p> + </template> + </div> + </NcModal> +</template> + +<script> +import { + NcButton, + NcLoadingIcon, + NcModal, + NcSelect, +} from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import { + NULLABLE_OBJECT_PROP, + REQUIRED_FLAG_PROP, +} from '../constants/propDefinitions.js' +import { useExportsStore } from '../stores/scheduledExports.js' +import { + EXPORT_FORMATS, + formatLabel, + recipientId, + recipientLabel, + serverMessage, +} from '../utils/scheduledExports.js' + +/** + * PreviewModal: render a scheduled export in one format, filtered for one + * recipient, without delivering it and without a run-row (REQ-SCH-009). + * A PDF or PNG shows in the dialog; a CSV or XLSX is offered as a download. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-16 + */ +export default { + name: 'PreviewModal', + + components: { + NcButton, + NcLoadingIcon, + NcModal, + NcSelect, + }, + + props: { + open: REQUIRED_FLAG_PROP, + + /** The export to preview. */ + exportData: NULLABLE_OBJECT_PROP, + }, + + emits: ['close'], + + /** @spec openspec/changes/scheduled-exports/tasks.md#task-16 */ + data() { + return { + format: null, + recipient: null, + loading: false, + error: '', + result: null, + } + }, + + computed: { + /** + * @return {object[]} The four formats as options. + * @spec openspec/changes/scheduled-exports/tasks.md#task-16 + */ + formatOptions() { + return EXPORT_FORMATS.map((id) => ({ id, label: formatLabel(id) })) + }, + + /** + * @return {object[]} "No recipient" and each recipient of the export. + * @spec openspec/changes/scheduled-exports/tasks.md#task-16 + */ + recipientOptions() { + return [ + { id: '', label: t('launchpad', 'No recipient (all data)') }, + ...(this.exportData?.recipients ?? []).map((r, i) => ({ + id: recipientId(r, i), + label: recipientLabel(r, i), + })), + ] + }, + }, + + watch: { + open: { + immediate: true, + /** + * Start each opening with the export's first format and no recipient. + * + * @param {boolean} isOpen New open state. + * @spec openspec/changes/scheduled-exports/tasks.md#task-16 + */ + handler(isOpen) { + if (!isOpen) { + this.clear() + return + } + const first = this.exportData?.renderTargets?.[0]?.format ?? 'pdf' + this.format = + this.formatOptions.find((option) => option.id === first) + ?? this.formatOptions[0] + this.recipient = this.recipientOptions[0] + this.error = '' + }, + }, + }, + + /** Let go of the rendered file. */ + beforeUnmount() { + this.clear() + }, + + methods: { + t, + + /** + * Drop the shown preview and free its object URL. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-16 + */ + clear() { + if (this.result?.url) { + URL.revokeObjectURL(this.result.url) + } + this.result = null + }, + + /** + * Ask the server for the preview and show it. + * + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-009-manual-run-now-and-preview-actions + */ + async render() { + const format = this.format?.id + if (!format || !this.exportData?.id) { + return + } + this.clear() + this.loading = true + this.error = '' + try { + const blob = await useExportsStore().previewExport( + this.exportData.id, + this.recipient?.id ?? '', + format, + ) + const base = String(this.exportData.name || 'export').replace( + /[\\/:*?"<>|]+/g, + '-', + ) + this.result = { + format, + url: URL.createObjectURL(blob), + filename: `${base}.${format}`, + } + } catch (e) { + this.error = await serverMessage( + e, + t('launchpad', 'The preview could not be made.'), + ) + } finally { + this.loading = false + } + }, + }, +} +</script> + +<style scoped> +.export-preview { + padding: 24px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.export-preview__hint { + color: var(--color-text-maxcontrast); + margin: 0; +} + +.export-preview__choices { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: flex-end; +} + +.export-preview__choices > :not(:last-child) { + flex: 1 1 200px; +} + +.export-preview__frame { + width: 100%; + height: 60vh; + border: 1px solid var(--color-border); +} + +.export-preview__image { + max-width: 100%; + border: 1px solid var(--color-border); +} + +.export-preview__loading { + display: flex; + justify-content: center; +} + +.export-preview__error { + color: var(--color-error-text); +} +</style> diff --git a/src/modals/RunDetailModal.vue b/src/modals/RunDetailModal.vue new file mode 100644 index 000000000..7989de87e --- /dev/null +++ b/src/modals/RunDetailModal.vue @@ -0,0 +1,427 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcModal + v-if="open" + class="launchpad-modal launchpad-modal--wide" + size="large" + :name="t('launchpad', 'Run details')" + @close="$emit('close')"> + <div class="run-detail" data-testid="run-detail"> + <header> + <p class="launchpad-modal__kicker" data-testid="run-detail-export"> + {{ exportData?.name ?? '' }} + </p> + <h2 class="launchpad-modal__title"> + {{ t('launchpad', 'Run details') }} + </h2> + </header> + + <p + v-if="error" + class="run-detail__error" + role="alert" + data-testid="run-detail-error"> + {{ error }} + </p> + + <dl class="run-detail__facts"> + <dt>{{ t('launchpad', 'Started') }}</dt> + <dd data-testid="run-detail-started"> + {{ formatDateTime(current.startedAt) }} + </dd> + <dt>{{ t('launchpad', 'Finished') }}</dt> + <dd>{{ formatDateTime(current.finishedAt) || '–' }}</dd> + <dt>{{ t('launchpad', 'Status') }}</dt> + <dd><ExportStatus :status="current.status" /></dd> + <dt>{{ t('launchpad', 'Triggered') }}</dt> + <dd> + {{ + current.triggeredBy === 'manual' + ? t('launchpad', 'By hand by {user}', { + user: current.triggeredByUser ?? '', + }) + : t('launchpad', 'On schedule') + }} + </dd> + <template v-if="current.skipReason"> + <dt>{{ t('launchpad', 'Skipped because') }}</dt> + <dd>{{ current.skipReason }}</dd> + </template> + </dl> + + <section aria-labelledby="run-detail-deliveries"> + <div class="run-detail__section-head"> + <h3 id="run-detail-deliveries"> + {{ t('launchpad', 'Deliveries') }} + </h3> + <NcButton + v-if="hasFailedDelivery" + variant="primary" + :disabled="retrying" + data-testid="run-detail-retry" + @click="retry"> + <template #icon> + <Refresh :size="20" /> + </template> + {{ t('launchpad', 'Retry failed deliveries') }} + </NcButton> + </div> + <p v-if="deliveries.length === 0"> + {{ t('launchpad', 'Nothing was delivered in this run.') }} + </p> + <table v-else class="run-detail__table"> + <thead> + <tr> + <th scope="col"> + {{ t('launchpad', 'Recipient') }} + </th> + <th scope="col"> + {{ t('launchpad', 'Channel') }} + </th> + <th scope="col"> + {{ t('launchpad', 'Status') }} + </th> + <th scope="col"> + {{ t('launchpad', 'Attempts') }} + </th> + <th scope="col"> + {{ t('launchpad', 'Error') }} + </th> + </tr> + </thead> + <tbody> + <tr + v-for="(delivery, index) in deliveries" + :key="`${delivery.recipientId}-${index}`" + data-testid="run-detail-delivery"> + <td>{{ recipientName(delivery) }}</td> + <td>{{ channelLabel(delivery.channel) }}</td> + <td><ExportStatus :status="delivery.status" /></td> + <td>{{ delivery.attemptCount ?? 0 }}</td> + <td class="run-detail__error-cell"> + {{ delivery.error ?? '' }} + </td> + </tr> + </tbody> + </table> + </section> + + <section aria-labelledby="run-detail-artefacts"> + <h3 id="run-detail-artefacts"> + {{ t('launchpad', 'Files') }} + </h3> + <p v-if="artefacts.length === 0"> + {{ t('launchpad', 'No files were made in this run.') }} + </p> + <table v-else class="run-detail__table"> + <thead> + <tr> + <th scope="col"> + {{ t('launchpad', 'Format') }} + </th> + <th scope="col"> + {{ t('launchpad', 'Size') }} + </th> + <th scope="col"> + {{ t('launchpad', 'SHA-256') }} + </th> + <th scope="col"> + {{ t('launchpad', 'File') }} + </th> + </tr> + </thead> + <tbody> + <tr + v-for="(artefact, index) in artefacts" + :key="`${artefact.sha256}-${index}`" + data-testid="run-detail-artefact"> + <td>{{ formatLabel(artefact.format) }}</td> + <td>{{ formatBytes(artefact.sizeBytes) }}</td> + <td> + <code :title="artefact.sha256">{{ + String(artefact.sha256 ?? '').slice(0, 12) + }}</code> + </td> + <td> + <a + v-if="artefactDownloadUrl(artefact.storagePath)" + :href="artefactDownloadUrl(artefact.storagePath)" + download + data-testid="run-detail-download"> + {{ t('launchpad', 'Download') }} + </a> + <span v-else class="run-detail__muted"> + {{ + t( + 'launchpad', + 'Removed after the retention period', + ) + }} + </span> + </td> + </tr> + </tbody> + </table> + </section> + </div> + </NcModal> +</template> + +<script> +import { NcButton, NcModal } from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import Refresh from 'vue-material-design-icons/Refresh.vue' +import ExportStatus from '../components/ScheduledExports/ExportStatus.vue' +import { + NULLABLE_OBJECT_PROP, + REQUIRED_FLAG_PROP, +} from '../constants/propDefinitions.js' +import { useExportsStore } from '../stores/scheduledExports.js' +import { + artefactDownloadUrl, + channelLabel, + formatBytes, + formatDateTime, + formatLabel, + recipientLabel, + serverMessage, +} from '../utils/scheduledExports.js' + +/** + * RunDetailModal: one run of a scheduled export: when it fired, how it + * ended, each delivery (channel, status, attempts, error) and each file + * it made (format, size, hash, download). When a delivery failed for good + * a Retry button asks the server to attempt those deliveries again. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ +export default { + name: 'RunDetailModal', + + components: { + ExportStatus, + NcButton, + NcModal, + Refresh, + }, + + props: { + open: REQUIRED_FLAG_PROP, + + /** The export the run belongs to. */ + exportData: NULLABLE_OBJECT_PROP, + + /** The run-row as the history listed it. */ + run: NULLABLE_OBJECT_PROP, + }, + + emits: ['close', 'retried'], + + /** @spec openspec/changes/scheduled-exports/tasks.md#task-15 */ + data() { + return { + loaded: null, + retrying: false, + error: '', + } + }, + + computed: { + /** + * @return {object} The run: as read from the server, else as listed. + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ + current() { + return this.loaded ?? this.run ?? {} + }, + + /** + * @return {object[]} The deliveries of the run. + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ + deliveries() { + return this.current.deliveries ?? [] + }, + + /** + * @return {object[]} The files the run made. + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ + artefacts() { + return this.current.renderArtefacts ?? [] + }, + + /** + * @return {boolean} Whether a delivery failed for good, so it can be retried. + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + hasFailedDelivery() { + return this.deliveries.some( + (delivery) => delivery.status === 'failed-permanent', + ) + }, + }, + + watch: { + open: { + immediate: true, + /** + * Read the run with every delivery each time the dialog opens. + * + * @param {boolean} isOpen New open state. + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ + handler(isOpen) { + if (isOpen) { + this.load() + } + }, + }, + }, + + methods: { + t, + artefactDownloadUrl, + channelLabel, + formatBytes, + formatDateTime, + formatLabel, + + /** + * Read the run from the server. + * + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ + async load() { + this.loaded = null + this.error = '' + if (!this.exportData?.id || !this.run?.id) { + return + } + try { + this.loaded = await useExportsStore().fetchRun( + this.exportData.id, + this.run.id, + ) + } catch (e) { + this.error = await serverMessage( + e, + t('launchpad', 'The run could not be loaded.'), + ) + } + }, + + /** + * The recipient of a delivery, by its channel and address when the export still has it. + * + * @param {object} delivery The delivery. + * @return {string} The name. + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ + recipientName(delivery) { + const recipients = this.exportData?.recipients ?? [] + const index = recipients.findIndex( + (r, i) => String(r.id ?? i) === String(delivery.recipientId), + ) + if (index === -1) { + return String(delivery.recipientId ?? '') + } + return recipientLabel(recipients[index], index) + }, + + /** + * Retry the deliveries that failed for good; the answer replaces the run. + * + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-006-retry-with-exponential-backoff-and-dead-letter + */ + async retry() { + this.retrying = true + this.error = '' + try { + this.loaded = await useExportsStore().retryRun( + this.exportData.id, + this.current.id, + ) + this.$emit('retried', this.loaded) + } catch (e) { + this.error = await serverMessage( + e, + t('launchpad', 'The deliveries could not be retried.'), + ) + } finally { + this.retrying = false + } + }, + }, +} +</script> + +<style scoped> +.run-detail { + padding: 24px; + display: flex; + flex-direction: column; + gap: 20px; +} + +.run-detail h3 { + margin: 0; + font-size: 1.1em; + font-weight: bold; +} + +.run-detail__facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 4px 16px; + margin: 0; +} + +.run-detail__facts dt { + font-weight: bold; +} + +.run-detail__facts dd { + margin: 0; +} + +.run-detail__section-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 8px; +} + +.run-detail__table { + width: 100%; + border-collapse: collapse; +} + +.run-detail__table th, +.run-detail__table td { + padding: 4px 8px; + text-align: start; + vertical-align: top; + border-bottom: 1px solid var(--color-border); +} + +.run-detail__error-cell { + color: var(--color-error-text); + overflow-wrap: anywhere; +} + +.run-detail__error { + color: var(--color-error-text); +} + +.run-detail__muted { + color: var(--color-text-maxcontrast); +} +</style> diff --git a/src/modals/ScheduledExportModal.vue b/src/modals/ScheduledExportModal.vue new file mode 100644 index 000000000..d49536e6b --- /dev/null +++ b/src/modals/ScheduledExportModal.vue @@ -0,0 +1,1315 @@ +<!-- + - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + - SPDX-License-Identifier: EUPL-1.2 +--> + +<template> + <NcModal + v-if="open" + class="launchpad-modal launchpad-modal--wide" + size="large" + :name="title" + @close="$emit('close')"> + <form + class="export-editor" + data-testid="export-editor" + @submit.prevent="save"> + <h2 class="launchpad-modal__title"> + {{ title }} + </h2> + + <NcNoteCard + v-if="error" + type="error" + role="alert" + data-testid="export-editor-error"> + {{ error }} + </NcNoteCard> + + <!-- Basic --> + <section + class="export-editor__section" + aria-labelledby="export-editor-basic"> + <h3 id="export-editor-basic"> + {{ t('launchpad', 'General') }} + </h3> + <NcTextField + v-model="form.name" + :label="t('launchpad', 'Name')" + data-testid="export-name" /> + <NcTextArea + v-model="form.description" + :label="t('launchpad', 'Description (optional)')" + :helperText=" + t( + 'launchpad', + 'Shown in the email and on the cover page of the PDF.', + ) + " + data-testid="export-description" /> + <NcSelect + v-model="form.subject" + :inputLabel="t('launchpad', 'What to export')" + :options="subjectOptions" + label="label" + :clearable="false" + data-testid="export-subject" /> + <NcCheckboxRadioSwitch + v-model="form.enabled" + type="switch" + data-testid="export-enabled"> + {{ t('launchpad', 'Run on schedule') }} + </NcCheckboxRadioSwitch> + </section> + + <!-- Recurrence --> + <section + class="export-editor__section" + aria-labelledby="export-editor-recurrence"> + <h3 id="export-editor-recurrence"> + {{ t('launchpad', 'When') }} + </h3> + <NcSelect + :modelValue="recurrenceTypeOption" + :inputLabel="t('launchpad', 'Repeats')" + :options="recurrenceTypeOptions" + label="label" + :clearable="false" + data-testid="export-recurrence-type" + @update:modelValue=" + form.recurrence.type = $event?.id ?? 'weekly' + " /> + + <fieldset + v-if="form.recurrence.type === 'weekly'" + class="export-editor__days" + data-testid="export-days"> + <legend>{{ t('launchpad', 'On these days') }}</legend> + <NcCheckboxRadioSwitch + v-for="day in weekdays" + :key="day.code" + :modelValue="form.recurrence.daysOfWeek.includes(day.code)" + :data-testid="`export-day-${day.code}`" + @update:modelValue="toggleDay(day.code, $event)"> + {{ day.label }} + </NcCheckboxRadioSwitch> + </fieldset> + + <template v-if="form.recurrence.type === 'monthly'"> + <NcCheckboxRadioSwitch + v-model="form.recurrence.lastDay" + type="switch" + data-testid="export-last-day"> + {{ t('launchpad', 'On the last day of the month') }} + </NcCheckboxRadioSwitch> + <NcTextField + v-if="!form.recurrence.lastDay" + :modelValue="String(form.recurrence.dayOfMonth)" + type="number" + min="1" + max="31" + :label="t('launchpad', 'Day of the month')" + :helperText=" + t( + 'launchpad', + 'In a shorter month the export runs on its last day.', + ) + " + data-testid="export-day-of-month" + @update:modelValue=" + form.recurrence.dayOfMonth = + Number.parseInt($event, 10) || 1 + " /> + </template> + + <NcTextField + v-if="form.recurrence.type === 'cron'" + v-model="form.recurrence.expression" + :label="t('launchpad', 'Cron expression')" + :helperText=" + t( + 'launchpad', + 'Five fields: minute, hour, day of the month, month and day of the week, for example 0 9 * * 1.', + ) + " + data-testid="export-cron" /> + <NcTextField + v-else + v-model="form.recurrence.timeOfDay" + type="time" + :label="t('launchpad', 'Time')" + data-testid="export-time" /> + + <NcTextField + v-model="form.runTimezone" + :label="t('launchpad', 'Time zone')" + :helperText="t('launchpad', 'For example Europe/Amsterdam.')" + data-testid="export-timezone" /> + + <p + class="export-editor__summary" + data-testid="export-recurrence-summary"> + {{ recurrenceSummary }} + </p> + </section> + + <!-- Render targets --> + <section + class="export-editor__section" + aria-labelledby="export-editor-targets"> + <h3 id="export-editor-targets"> + {{ t('launchpad', 'Files to make') }} + </h3> + <div + v-for="(target, index) in form.renderTargets" + :key="target.key" + class="export-editor__item" + data-testid="export-target"> + <div class="export-editor__item-head"> + <NcSelect + :modelValue=" + formatOptions.find( + (option) => option.id === target.format, + ) + " + :inputLabel="t('launchpad', 'Format')" + :options="formatOptions" + label="label" + :clearable="false" + data-testid="export-target-format" + @update:modelValue="setFormat(target, $event?.id)" /> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove this file')" + :disabled="form.renderTargets.length === 1" + data-testid="export-target-remove" + @click="form.renderTargets.splice(index, 1)"> + <template #icon> + <Delete :size="20" /> + </template> + </NcButton> + </div> + <ExportOptionFields + :fields="formatFields(target.format)" + :values="target.formatOptions" + @update=" + (key, value) => (target.formatOptions[key] = value) + " /> + <NcTextField + v-model="target.filenamePattern" + :label="t('launchpad', 'File name')" + :helperText=" + t( + 'launchpad', + 'You can use {name}, {date}, {recipient} and {ext}.', + ) + " + data-testid="export-target-filename" /> + </div> + <NcButton + variant="secondary" + data-testid="export-target-add" + @click="addTarget"> + <template #icon> + <Plus :size="20" /> + </template> + {{ t('launchpad', 'Add a file') }} + </NcButton> + </section> + + <!-- Recipients --> + <section + class="export-editor__section" + aria-labelledby="export-editor-recipients"> + <h3 id="export-editor-recipients"> + {{ t('launchpad', 'Recipients') }} + </h3> + <div + v-for="(recipient, index) in form.recipients" + :key="recipient.key" + class="export-editor__item" + data-testid="export-recipient"> + <div class="export-editor__item-head"> + <NcSelect + :modelValue=" + channelOptions.find( + (option) => option.id === recipient.channel, + ) + " + :inputLabel="t('launchpad', 'Send by')" + :options="channelOptions" + label="label" + :clearable="false" + data-testid="export-recipient-channel" + @update:modelValue="setChannel(recipient, $event?.id)" /> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove this recipient')" + :disabled="form.recipients.length === 1" + data-testid="export-recipient-remove" + @click="form.recipients.splice(index, 1)"> + <template #icon> + <Delete :size="20" /> + </template> + </NcButton> + </div> + <NcCheckboxRadioSwitch v-model="recipient.enabled" type="switch"> + {{ t('launchpad', 'Send to this recipient') }} + </NcCheckboxRadioSwitch> + <NcTextField + v-if="recipient.channel === 'email'" + v-model="recipient.addresses" + :label="t('launchpad', 'Email addresses')" + :helperText=" + t('launchpad', 'Separate addresses with commas.') + " + data-testid="export-recipient-addresses" /> + <ExportOptionFields + v-else + :fields="channelFields(recipient.channel)" + :values="recipient.channelConfig" + @update=" + (key, value) => (recipient.channelConfig[key] = value) + " /> + + <fieldset + class="export-editor__filters" + data-testid="export-recipient-filters"> + <legend> + {{ t('launchpad', 'Filters for this recipient') }} + </legend> + <p class="export-editor__hint"> + {{ + t( + 'launchpad', + 'This recipient gets the data filtered on these values, for example gemeenteCode GM0355.', + ) + }} + </p> + <div + v-for="(filter, filterIndex) in recipient.filters" + :key="filter.key" + class="export-editor__filter" + data-testid="export-filter"> + <NcTextField + v-model="filter.field" + :label="t('launchpad', 'Field')" + data-testid="export-filter-field" /> + <NcTextField + v-model="filter.value" + :label="t('launchpad', 'Value')" + data-testid="export-filter-value" /> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Remove this filter')" + @click="recipient.filters.splice(filterIndex, 1)"> + <template #icon> + <Delete :size="20" /> + </template> + </NcButton> + </div> + <NcButton + variant="tertiary" + data-testid="export-filter-add" + @click=" + recipient.filters.push({ + key: nextKey(), + field: '', + value: '', + }) + "> + <template #icon> + <Plus :size="20" /> + </template> + {{ t('launchpad', 'Add a filter') }} + </NcButton> + </fieldset> + </div> + <NcButton + variant="secondary" + data-testid="export-recipient-add" + @click="addRecipient"> + <template #icon> + <Plus :size="20" /> + </template> + {{ t('launchpad', 'Add a recipient') }} + </NcButton> + </section> + + <div class="export-editor__actions"> + <NcButton variant="tertiary" @click="$emit('close')"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + variant="primary" + :disabled="saving" + data-testid="export-save" + @click="save"> + {{ t('launchpad', 'Save') }} + </NcButton> + </div> + </form> + </NcModal> +</template> + +<script> +import { + NcButton, + NcCheckboxRadioSwitch, + NcModal, + NcNoteCard, + NcSelect, + NcTextArea, + NcTextField, +} from '@conduction/nextcloud-vue' +import { t } from '@nextcloud/l10n' +import Delete from 'vue-material-design-icons/Delete.vue' +import Plus from 'vue-material-design-icons/Plus.vue' +import ExportOptionFields from '../components/ScheduledExports/ExportOptionFields.vue' +import { + LIST_PROP, + NULLABLE_OBJECT_PROP, + REQUIRED_FLAG_PROP, +} from '../constants/propDefinitions.js' +import { useExportsStore } from '../stores/scheduledExports.js' +import { + channelLabel, + EXPORT_CHANNELS, + EXPORT_FORMATS, + formatLabel, + serverMessage, +} from '../utils/scheduledExports.js' + +const DAY_CODES = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] + +const DEFAULT_FILENAME = '{name}-{date}.{ext}' + +/** Format options a new render target of each format starts with. */ +const FORMAT_DEFAULTS = { + pdf: { pageSize: 'A4', orientation: 'portrait', header: true, footer: true }, + png: { width: 1920, height: 1080, dpi: 96 }, + csv: { delimiter: ',', quoteChar: '"' }, + xlsx: { sheetPerWidget: true }, +} + +/** Channel settings a new recipient of each channel starts with. */ +const CHANNEL_DEFAULTS = { + email: {}, + nextcloudFiles: { targetPath: '/Reports', overwrite: false }, + webhook: { url: '', signingSecret: '' }, + sftp: { + host: '', + port: 22, + username: '', + remotePath: '', + password: '', + privateKey: '', + hostKeySha256: '', + }, +} + +/** Channel settings that hold a secret: sent only when filled in. */ +const SECRET_KEYS = ['password', 'privateKey', 'signingSecret'] + +let keySeed = 0 + +/** + * A key for a row of the form, stable while the row lives. + * + * @return {string} The key. + */ +function newKey() { + keySeed += 1 + return `row-${keySeed}` +} + +/** + * A plain copy of an object (or an empty object). + * + * @param {object|undefined} value The object. + * @return {object} The copy. + */ +function copy(value) { + return value && typeof value === 'object' + ? JSON.parse(JSON.stringify(value)) + : {} +} + +/** + * ScheduledExportModal: create or edit one scheduled export, in four + * sections: what (name, description, the dashboard or widget), when (a + * daily, weekly, monthly or cron recurrence with its time zone), which + * files (render targets with their format options) and who gets them + * (recipients with their channel settings and filter context). Saving + * POSTs a new export or PATCHes an existing one; a refusal shows the + * server's reason. + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ +export default { + name: 'ScheduledExportModal', + + components: { + Delete, + ExportOptionFields, + NcButton, + NcCheckboxRadioSwitch, + NcModal, + NcNoteCard, + NcSelect, + NcTextArea, + NcTextField, + Plus, + }, + + props: { + open: REQUIRED_FLAG_PROP, + + /** The export to edit; null creates a new one. */ + exportData: NULLABLE_OBJECT_PROP, + + /** What can be exported: `{type: 'dashboard'|'widget', id, label}`. */ + subjects: LIST_PROP, + + /** The subject a new export starts with: `{type, id}`. */ + defaultSubject: NULLABLE_OBJECT_PROP, + }, + + emits: ['close', 'saved'], + + /** @spec openspec/changes/scheduled-exports/tasks.md#task-12 */ + data() { + return { + form: this.emptyForm(), + saving: false, + error: '', + } + }, + + computed: { + /** + * @return {string} The dialog title. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + title() { + return this.exportData?.id + ? t('launchpad', 'Edit scheduled export') + : t('launchpad', 'New scheduled export') + }, + + /** + * The subjects as select options, plus the edited export's own + * subject when it is not among them. + * + * @return {object[]} `{id, type, label}` options. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + subjectOptions() { + const options = this.subjects.map((subject) => + this.subjectOption(subject.type, subject.id, subject.label), + ) + const current = this.form.subject + if (current && !options.some((option) => option.key === current.key)) { + options.push(current) + } + return options + }, + + /** + * @return {object[]} The recurrence types as options. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + recurrenceTypeOptions() { + return [ + { id: 'daily', label: t('launchpad', 'Every day') }, + { id: 'weekly', label: t('launchpad', 'Every week') }, + { id: 'monthly', label: t('launchpad', 'Every month') }, + { id: 'cron', label: t('launchpad', 'Custom (cron expression)') }, + ] + }, + + /** + * @return {object|null} The option of the chosen recurrence type. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + recurrenceTypeOption() { + return ( + this.recurrenceTypeOptions.find( + (option) => option.id === this.form.recurrence.type, + ) ?? null + ) + }, + + /** + * @return {object[]} The days of the week, Monday first, as `{code, label}`. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + weekdays() { + const labels = [ + t('launchpad', 'Monday'), + t('launchpad', 'Tuesday'), + t('launchpad', 'Wednesday'), + t('launchpad', 'Thursday'), + t('launchpad', 'Friday'), + t('launchpad', 'Saturday'), + t('launchpad', 'Sunday'), + ] + return DAY_CODES.map((code, i) => ({ code, label: labels[i] })) + }, + + /** + * @return {object[]} The render formats as options. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + formatOptions() { + return EXPORT_FORMATS.map((id) => ({ id, label: formatLabel(id) })) + }, + + /** + * @return {object[]} The delivery channels as options. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + channelOptions() { + return EXPORT_CHANNELS.map((id) => ({ id, label: channelLabel(id) })) + }, + + /** + * The recurrence in words, so the author sees what the editor means. + * + * @return {string} The summary. + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-001-recurrence-editor-produces-deterministic-next-run-timestamps + */ + recurrenceSummary() { + const rule = this.form.recurrence + const time = rule.timeOfDay + switch (rule.type) { + case 'daily': + return t('launchpad', 'Runs every day at {time}.', { time }) + case 'weekly': { + const days = this.weekdays + .filter((day) => rule.daysOfWeek.includes(day.code)) + .map((day) => day.label) + .join(', ') + return days + ? t('launchpad', 'Runs every {days} at {time}.', { + days, + time, + }) + : t('launchpad', 'Choose at least one day.') + } + case 'monthly': + return rule.lastDay + ? t( + 'launchpad', + 'Runs on the last day of every month at {time}.', + { time }, + ) + : t( + 'launchpad', + 'Runs on day {day} of every month at {time}.', + { day: rule.dayOfMonth, time }, + ) + default: + return t( + 'launchpad', + 'Runs when the cron expression {expression} matches.', + { expression: rule.expression }, + ) + } + }, + }, + + watch: { + open: { + immediate: true, + /** + * Fill the form from the export each time the dialog opens. + * + * @param {boolean} isOpen New open state. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + handler(isOpen) { + if (isOpen) { + this.form = this.formFrom(this.exportData) + this.error = '' + } + }, + }, + }, + + methods: { + t, + + /** + * @return {string} A fresh row key. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + nextKey() { + return newKey() + }, + + /** + * One subject option. + * + * @param {string} type dashboard or widget. + * @param {string} id The subject id. + * @param {string} label Its name. + * @return {object} The option. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + subjectOption(type, id, label) { + const name = label || String(id) + return { + key: `${type}:${id}`, + type, + id: String(id), + label: + type === 'widget' + ? t('launchpad', 'Widget: {name}', { name }) + : t('launchpad', 'Dashboard: {name}', { name }), + } + }, + + /** + * The form of a new export. + * + * @return {object} The form. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + emptyForm() { + let subject = null + if (this.defaultSubject?.id) { + const known = this.subjects.find( + (s) => + s.type === this.defaultSubject.type + && String(s.id) === String(this.defaultSubject.id), + ) + subject = this.subjectOption( + this.defaultSubject.type, + this.defaultSubject.id, + known?.label, + ) + } + return { + name: '', + description: '', + enabled: true, + subject, + runTimezone: + Intl.DateTimeFormat().resolvedOptions().timeZone + || 'Europe/Amsterdam', + + recurrence: { + type: 'weekly', + timeOfDay: '09:00', + daysOfWeek: ['MO'], + dayOfMonth: 1, + lastDay: false, + expression: '0 9 * * 1', + }, + + renderTargets: [this.newTarget('pdf')], + recipients: [this.newRecipient('email')], + } + }, + + /** + * The form of an existing export, or of a new one. + * + * @param {object|null} source The export. + * @return {object} The form. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + formFrom(source) { + const form = this.emptyForm() + if (!source) { + return form + } + const rule = source.recurrence ?? {} + const known = this.subjects.find( + (s) => + s.type === source.subjectType + && String(s.id) === String(source.subjectId), + ) + return { + name: source.name ?? '', + description: source.description ?? '', + enabled: source.enabled !== false, + subject: source.subjectId + ? this.subjectOption( + source.subjectType ?? 'dashboard', + source.subjectId, + known?.label, + ) + : null, + + runTimezone: source.runTimezone || form.runTimezone, + recurrence: { + ...form.recurrence, + type: rule.type ?? 'weekly', + timeOfDay: rule.timeOfDay ?? form.recurrence.timeOfDay, + daysOfWeek: Array.isArray(rule.daysOfWeek) + ? [...rule.daysOfWeek] + : [], + + dayOfMonth: rule.dayOfMonth ?? 1, + lastDay: rule.lastDay === true, + expression: rule.expression ?? '', + }, + + renderTargets: (source.renderTargets ?? []).map((target) => ({ + key: newKey(), + original: copy(target), + format: target.format, + formatOptions: { + ...FORMAT_DEFAULTS[target.format], + ...copy(target.formatOptions), + }, + filenamePattern: target.filenamePattern ?? DEFAULT_FILENAME, + })), + + recipients: (source.recipients ?? []).map((recipient) => { + const config = copy(recipient.channelConfig) + return { + key: newKey(), + original: copy(recipient), + enabled: recipient.enabled !== false, + channel: recipient.channel, + channelConfig: config, + addresses: Array.isArray(config.addresses) + ? config.addresses.join(', ') + : (config.to ?? ''), + filters: Object.entries(recipient.filterContext ?? {}).map( + ([field, value]) => ({ + key: newKey(), + field, + value: + typeof value === 'string' + ? value + : JSON.stringify(value), + }), + ), + } + }), + } + }, + + /** + * A new render target of a format. + * + * @param {string} format The format. + * @return {object} The target row. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + newTarget(format) { + return { + key: newKey(), + original: {}, + format, + formatOptions: { ...FORMAT_DEFAULTS[format] }, + filenamePattern: DEFAULT_FILENAME, + } + }, + + /** + * A new recipient of a channel. + * + * @param {string} channel The channel. + * @return {object} The recipient row. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + newRecipient(channel) { + return { + key: newKey(), + original: {}, + enabled: true, + channel, + channelConfig: { ...CHANNEL_DEFAULTS[channel] }, + addresses: '', + filters: [], + } + }, + + /** + * Add a render target (a PDF). + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + addTarget() { + this.form.renderTargets.push(this.newTarget('pdf')) + }, + + /** + * Add a recipient (an email). + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + addRecipient() { + this.form.recipients.push(this.newRecipient('email')) + }, + + /** + * Change a target's format; its options start over for the new format. + * + * @param {object} target The target row. + * @param {string} format The new format. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + setFormat(target, format) { + if (!format || format === target.format) { + return + } + target.format = format + target.formatOptions = { ...FORMAT_DEFAULTS[format] } + }, + + /** + * Change a recipient's channel; its settings start over for the new channel. + * + * @param {object} recipient The recipient row. + * @param {string} channel The new channel. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + setChannel(recipient, channel) { + if (!channel || channel === recipient.channel) { + return + } + recipient.channel = channel + recipient.channelConfig = { ...CHANNEL_DEFAULTS[channel] } + recipient.addresses = '' + }, + + /** + * Switch a day of the week on or off for a weekly recurrence. + * + * @param {string} code MO to SU. + * @param {boolean} on Whether the day is chosen. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + toggleDay(code, on) { + const days = this.form.recurrence.daysOfWeek.filter( + (day) => day !== code, + ) + if (on) { + days.push(code) + } + this.form.recurrence.daysOfWeek = DAY_CODES.filter((day) => + days.includes(day), + ) + }, + + /** + * The option fields of a render format. + * + * @param {string} format The format. + * @return {object[]} The fields. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + formatFields(format) { + switch (format) { + case 'pdf': + return [ + { + key: 'pageSize', + kind: 'select', + label: t('launchpad', 'Page size'), + options: ['A4', 'A3', 'Letter'].map((id) => ({ + id, + label: id, + })), + }, + { + key: 'orientation', + kind: 'select', + label: t('launchpad', 'Orientation'), + options: [ + { + id: 'portrait', + label: t('launchpad', 'Portrait'), + }, + { + id: 'landscape', + label: t('launchpad', 'Landscape'), + }, + ], + }, + { + key: 'header', + kind: 'switch', + label: t('launchpad', 'Header on every page'), + }, + { + key: 'footer', + kind: 'switch', + label: t('launchpad', 'Footer on every page'), + }, + ] + case 'png': + return [ + { + key: 'width', + type: 'number', + label: t('launchpad', 'Width in pixels'), + }, + { + key: 'height', + type: 'number', + label: t('launchpad', 'Height in pixels'), + }, + { + key: 'dpi', + type: 'number', + label: t('launchpad', 'Resolution (DPI)'), + }, + ] + case 'csv': + return [ + { + key: 'delimiter', + kind: 'select', + label: t('launchpad', 'Separator'), + options: [ + { id: ',', label: t('launchpad', 'Comma (,)') }, + { id: ';', label: t('launchpad', 'Semicolon (;)') }, + { id: '\t', label: t('launchpad', 'Tab') }, + ], + }, + { + key: 'quoteChar', + label: t('launchpad', 'Quote character'), + }, + ] + case 'xlsx': + return [ + { + key: 'sheetPerWidget', + kind: 'switch', + label: t('launchpad', 'One sheet per widget'), + }, + ] + default: + return [] + } + }, + + /** + * The settings fields of a delivery channel (email has its own field). + * + * @param {string} channel The channel. + * @return {object[]} The fields. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + channelFields(channel) { + const source = { + key: 'openconnectorSourceId', + label: t('launchpad', 'OpenConnector source (optional)'), + help: t( + 'launchpad', + 'Send through this OpenConnector source, which holds the credentials.', + ), + } + switch (channel) { + case 'nextcloudFiles': + return [ + { key: 'targetPath', label: t('launchpad', 'Folder') }, + { + key: 'overwrite', + kind: 'switch', + label: t( + 'launchpad', + 'Replace a file with the same name', + ), + }, + ] + case 'webhook': + return [ + { + key: 'url', + type: 'url', + label: t('launchpad', 'Web address (URL)'), + }, + { + key: 'signingSecret', + kind: 'secret', + label: t('launchpad', 'Signing secret'), + help: t( + 'launchpad', + 'Signs every request so the receiver can check it came from LaunchPad.', + ), + }, + source, + ] + case 'sftp': + return [ + { key: 'host', label: t('launchpad', 'Server') }, + { + key: 'port', + type: 'number', + label: t('launchpad', 'Port'), + }, + { key: 'username', label: t('launchpad', 'User name') }, + { + key: 'password', + kind: 'secret', + label: t('launchpad', 'Password'), + }, + { + key: 'privateKey', + kind: 'textarea', + label: t( + 'launchpad', + 'Private key (instead of a password)', + ), + }, + { + key: 'remotePath', + label: t('launchpad', 'Folder on the server'), + }, + { + key: 'hostKeySha256', + label: t( + 'launchpad', + 'Server key fingerprint (SHA-256)', + ), + }, + source, + ] + default: + return [] + } + }, + + /** + * The recurrence as the API stores it, with only the fields of its type. + * + * @return {object} The recurrence. + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-001-recurrence-editor-produces-deterministic-next-run-timestamps + */ + recurrencePayload() { + const rule = this.form.recurrence + switch (rule.type) { + case 'cron': + return { type: 'cron', expression: rule.expression.trim() } + case 'weekly': + return { + type: 'weekly', + daysOfWeek: [...rule.daysOfWeek], + timeOfDay: rule.timeOfDay, + } + case 'monthly': + return rule.lastDay + ? { + type: 'monthly', + lastDay: true, + timeOfDay: rule.timeOfDay, + } + : { + type: 'monthly', + dayOfMonth: Number(rule.dayOfMonth), + timeOfDay: rule.timeOfDay, + } + default: + return { type: 'daily', timeOfDay: rule.timeOfDay } + } + }, + + /** + * One recipient as the API stores it. An empty secret is left out; the + * redacted placeholder is sent back so the stored secret is kept. + * + * @param {object} recipient The recipient row. + * @return {object} The recipient. + * @spec openspec/changes/scheduled-exports/specs/scheduled-exports/spec.md#requirement-req-sch-004-per-recipient-filter-context + */ + recipientPayload(recipient) { + const config = { ...recipient.channelConfig } + if (recipient.channel === 'email') { + delete config.to + config.addresses = recipient.addresses + .split(',') + .map((a) => a.trim()) + .filter(Boolean) + } + for (const key of Object.keys(config)) { + if ( + (SECRET_KEYS.includes(key) || key === 'openconnectorSourceId') + && (config[key] === '' || config[key] === null) + ) { + delete config[key] + } + } + const result = { + ...recipient.original, + enabled: recipient.enabled, + channel: recipient.channel, + channelConfig: config, + } + delete result.filterContext + const filters = recipient.filters.filter( + (filter) => filter.field.trim() !== '', + ) + if (filters.length > 0) { + result.filterContext = Object.fromEntries( + filters.map((filter) => [ + filter.field.trim(), + this.filterValue(filter.value), + ]), + ) + } + return result + }, + + /** + * A typed filter value: a JSON list or object stays one, anything else is text. + * + * @param {string} value What was typed. + * @return {string|object|Array} The value. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + filterValue(value) { + const text = String(value ?? '').trim() + if (/^[[{]/.test(text)) { + try { + return JSON.parse(text) + } catch { + return text + } + } + return text + }, + + /** + * The export as the API takes it. + * + * @return {object} The export. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + payload() { + const form = this.form + return { + name: form.name.trim(), + description: form.description, + enabled: form.enabled, + subjectType: form.subject?.type ?? 'dashboard', + subjectId: form.subject?.id ?? '', + runTimezone: form.runTimezone.trim(), + recurrence: this.recurrencePayload(), + renderTargets: form.renderTargets.map((target) => ({ + ...target.original, + format: target.format, + formatOptions: { ...target.formatOptions }, + filenamePattern: target.filenamePattern || DEFAULT_FILENAME, + })), + + recipients: form.recipients.map((recipient) => + this.recipientPayload(recipient), + ), + } + }, + + /** + * Save: POST a new export or PATCH this one, then tell the list. + * + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + async save() { + if (this.saving) { + return + } + this.saving = true + this.error = '' + try { + const body = this.payload() + if (this.exportData?.id) { + body.id = this.exportData.id + } + const saved = await useExportsStore().saveExport(body) + this.$emit('saved', saved) + this.$emit('close') + } catch (e) { + this.error = await serverMessage( + e, + t('launchpad', 'The scheduled export could not be saved.'), + ) + } finally { + this.saving = false + } + }, + }, +} +</script> + +<style scoped> +.export-editor { + padding: 24px; + display: flex; + flex-direction: column; + gap: 20px; +} + +.export-editor__section { + display: flex; + flex-direction: column; + gap: 8px; +} + +.export-editor__section h3 { + margin: 0; + font-size: 1.1em; + font-weight: bold; +} + +.export-editor__item { + display: flex; + flex-direction: column; + gap: 8px; + padding: 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); +} + +.export-editor__item-head, +.export-editor__filter { + display: flex; + gap: 8px; + align-items: flex-end; +} + +.export-editor__item-head > :first-child, +.export-editor__filter > :not(:last-child) { + flex: 1 1 0; +} + +.export-editor__days, +.export-editor__filters { + display: flex; + flex-wrap: wrap; + gap: 4px 16px; + border: 0; + padding: 0; + margin: 0; +} + +.export-editor__filters { + flex-direction: column; +} + +.export-editor__days legend, +.export-editor__filters legend { + font-weight: bold; + margin-bottom: 4px; +} + +.export-editor__hint, +.export-editor__summary { + color: var(--color-text-maxcontrast); + margin: 0; +} + +.export-editor__actions { + display: flex; + justify-content: flex-end; + gap: 8px; +} +</style> diff --git a/src/modals/SetupWizardModal.vue b/src/modals/SetupWizardModal.vue index 3b5f9c418..e4fda197f 100644 --- a/src/modals/SetupWizardModal.vue +++ b/src/modals/SetupWizardModal.vue @@ -5,6 +5,7 @@ <template> <NcModal + class="launchpad-modal" :name="t('launchpad', 'LaunchPad setup wizard')" size="large" @close="onClose"> @@ -29,85 +30,14 @@ {{ t( 'launchpad', - 'Configure your LaunchPad instance with storage, group ordering, demo data, admin roles, and footer settings.', + 'This setup sets the groups, the example dashboards and the roles, in five steps. Existing dashboards stay as they are.', ) }} </p> </div> - <!-- Step 2 — Storage backend (REQ-WIZ-003) --> + <!-- Step 2 — Group priority order (REQ-WIZ-004; embeds existing UI) --> <div v-else-if="currentStep === 2" class="setup-wizard__step"> - <h3>{{ t('launchpad', 'Storage backend') }}</h3> - <p> - {{ - t( - 'launchpad', - 'Choose how LaunchPad stores dashboard content.', - ) - }} - </p> - - <label class="setup-wizard__radio"> - <input - v-model="storage" - type="radio" - value="database" - data-test="storage-database" /> - <div> - <strong>{{ - t('launchpad', 'Database (default)') - }}</strong> - <p class="setup-wizard__hint"> - {{ - t( - 'launchpad', - 'Store dashboard content in the LaunchPad database table.', - ) - }} - </p> - </div> - </label> - - <label - class="setup-wizard__radio" - :class="{ - 'setup-wizard__radio--disabled': !groupfolderAvailable, - }" - :title=" - groupfolderAvailable - ? '' - : t( - 'launchpad', - 'GroupFolder app is not installed. Install \'Nextcloud GroupFolders\' to use this option.', - ) - "> - <input - v-model="storage" - type="radio" - value="groupfolder" - :disabled="!groupfolderAvailable" - data-test="storage-groupfolder" /> - <div> - <strong>{{ - t( - 'launchpad', - 'GroupFolder (recommended for org use)', - ) - }}</strong> - <p class="setup-wizard__hint"> - {{ - t( - 'launchpad', - 'Store dashboard content in Nextcloud GroupFolders for collaborative access.', - ) - }} - </p> - </div> - </label> - </div> - - <!-- Step 3 — Group priority order (REQ-WIZ-004; embeds existing UI) --> - <div v-else-if="currentStep === 3" class="setup-wizard__step"> <h3>{{ t('launchpad', 'Group priority order') }}</h3> <p> {{ @@ -120,63 +50,37 @@ <GroupPriorityOrder :initialActive="[]" /> </div> - <!-- Step 4 — Demo data (REQ-WIZ-005; delivered by demo-data-showcases sibling). --> - <div v-else-if="currentStep === 4" class="setup-wizard__step"> + <!-- Step 3 — Demo data (REQ-WIZ-005; delivered by demo-data-showcases sibling). --> + <div v-else-if="currentStep === 3" class="setup-wizard__step"> <h3>{{ t('launchpad', 'Demo data') }}</h3> - <AdminDemoData data-test="demo-data-panel" /> + <AdminDemoData + data-test="demo-data-panel" + :choice="demoChoice" + @choose="onDemoChoose" /> </div> - <!-- Step 5 — Admin roles (REQ-WIZ-006; sibling capability pending) --> - <!-- TODO: admin-roles integration — admin-roles capability is delivered through - AdminController role endpoints (POST/DELETE /api/admin/roles), not a Vue - panel; build a dedicated AdminRolesPanel.vue and swap the stub below. --> - <div v-else-if="currentStep === 5" class="setup-wizard__step"> + <!-- Step 4 — Admin roles (REQ-WIZ-006): one group gets the admin role on Next. --> + <div v-else-if="currentStep === 4" class="setup-wizard__step"> <h3>{{ t('launchpad', 'Admin roles') }}</h3> <p> {{ t( 'launchpad', - 'Assign the "Dashboard Admin" role to a Nextcloud group to delegate LaunchPad administration.', - ) - }} - </p> - <p class="setup-wizard__note" data-test="admin-roles-stub"> - {{ - t( - 'launchpad', - 'The admin-roles capability is not yet available; this step will activate once it ships.', + "Assign 'Dashboard Admin' role to a group to delegate LaunchPad administration to group members.", ) }} </p> + <NcSelect + v-model="roleGroup" + :options="roleGroups" + :inputLabel="t('launchpad', 'Group')" + :placeholder="t('launchpad', 'No group')" + :loading="roleGroupsLoading" + data-test="setup-wizard-role-group" /> </div> - <!-- Step 6 — Footer config (REQ-WIZ-007; sibling capability pending) --> - <!-- TODO: footer-customization integration — footer is currently - surfaced through admin endpoints (FooterService + AdminSetting - KEY_FOOTER_*); build a FooterSettingsPanel.vue and swap the - stub below. --> - <div v-else-if="currentStep === 6" class="setup-wizard__step"> - <h3>{{ t('launchpad', 'Footer configuration') }}</h3> - <p> - {{ - t( - 'launchpad', - 'Customize the footer content and appearance for your intranet.', - ) - }} - </p> - <p class="setup-wizard__note" data-test="footer-stub"> - {{ - t( - 'launchpad', - 'The footer-customization capability is not yet available; this step will activate once it ships.', - ) - }} - </p> - </div> - - <!-- Step 7 — Done (REQ-WIZ-002 final step) --> - <div v-else-if="currentStep === 7" class="setup-wizard__step"> + <!-- Step 5 — Done (REQ-WIZ-012 final step) --> + <div v-else-if="currentStep === 5" class="setup-wizard__step"> <h3>{{ t('launchpad', 'All set') }}</h3> <p> {{ @@ -221,21 +125,24 @@ </template> <script> -import { NcButton, NcModal } from '@conduction/nextcloud-vue' +import { NcButton, NcModal, NcSelect } from '@conduction/nextcloud-vue' import AdminDemoData from '../components/admin/AdminDemoData.vue' import GroupPriorityOrder from '../components/admin/GroupPriorityOrder.vue' import { api } from '../services/api.js' import { logger } from '../utils/logger.js' /** - * SetupWizardModal — multi-step first-run wizard (REQ-WIZ-002). + * SetupWizardModal — the five-step first-run wizard (REQ-WIZ-012): + * Welcome, Groups, Examples, Roles, Done. * * The shell owns navigation state; per-step bodies inline simple UI for - * Welcome / Storage / Done and embed canonical sibling components for - * Group order. Steps 4-6 render lightweight stubs because their sibling - * capabilities (demo-data-showcases, admin-roles, footer-customization) - * ship on parallel branches; the merge agent reconciles by replacing - * the stub blocks with the real embeds. + * Welcome / Done and embed canonical sibling components for the group + * order and the demo data. The storage step was retired (decision 131) + * and the footer step too: the footer is set on its own admin tab. Step 3 + * keeps the checked demos and installs them on Next; Step 4 gives the one + * selected group the admin role on Next. + * + * @spec openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/setup-wizard/spec.md#requirement-req-wiz-012-multi-step-wizard-flow-with-5-steps */ export default { name: 'SetupWizardModal', @@ -245,18 +152,24 @@ export default { GroupPriorityOrder, NcButton, NcModal, + NcSelect, }, emits: ['close', 'completed'], + /** @spec openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/setup-wizard/spec.md#requirement-req-wiz-012-multi-step-wizard-flow-with-5-steps */ data() { return { currentStep: 1, - totalSteps: 7, + totalSteps: 5, loading: false, - storage: 'database', - groupfolderAvailable: false, completed: false, + // Step 3: `{ [showcaseId]: boolean }`, kept here so Back keeps it. + demoChoice: {}, + // Step 4: the group ids, and the one chosen for the admin role. + roleGroups: [], + roleGroupsLoading: false, + roleGroup: null, } }, @@ -266,6 +179,20 @@ export default { }, }, + watch: { + /** + * Load the groups when Step 4 opens. + * + * @param {number} step The step now shown. + * @spec openspec/specs/setup-wizard/spec.md#req-wiz-006 + */ + currentStep(step) { + if (step === 4) { + this.loadRoleGroups() + } + }, + }, + async created() { await this.loadState() }, @@ -276,8 +203,6 @@ export default { try { const { data } = await api.getSetupWizardState() if (data) { - this.storage = data.contentStorage || 'database' - this.groupfolderAvailable = !!data.groupfolderAvailable if (data.currentRecommendedStep && !data.complete) { this.currentStep = Math.max( 1, @@ -287,7 +212,7 @@ export default { } } catch (error) { // REQ-WIZ-008: a failed state read MUST NOT block the wizard. - // Default to Step 1 with a Database default. + // Default to Step 1. logger.warn('Failed to load wizard state', error) } }, @@ -299,10 +224,6 @@ export default { } this.loading = true try { - if (this.currentStep === 2) { - await api.setSetupWizardStorage(this.storage) - } - if (this.isFinalStep) { await api.completeSetupWizard() this.completed = true @@ -310,6 +231,11 @@ export default { this.$emit('close') return } + if (this.currentStep === 3) { + await this.installChosenDemos() + } else if (this.currentStep === 4 && this.roleGroup) { + await this.assignRoleGroup() + } this.currentStep += 1 } catch (error) { logger.error('Wizard step failed', error) @@ -318,6 +244,78 @@ export default { } }, + /** + * Record a demo checkbox. + * + * @param {string} id The showcase id. + * @param {boolean} chosen Whether it is checked. + * @spec openspec/specs/setup-wizard/spec.md#req-wiz-005 + */ + onDemoChoose(id, chosen) { + this.demoChoice = { ...this.demoChoice, [id]: chosen } + }, + + /** + * Install the checked showcases that are not installed yet. An + * unchecked installed showcase stays installed. + * + * @return {Promise<void>} + * @spec openspec/specs/setup-wizard/spec.md#req-wiz-005 + */ + async installChosenDemos() { + const wanted = Object.keys(this.demoChoice).filter((id) => this.demoChoice[id] === true) + if (wanted.length === 0) { + return + } + const { data } = await api.listDemoShowcases() + const installed = new Set((data || []).filter((showcase) => showcase.isInstalled).map((showcase) => showcase.id)) + for (const id of wanted.filter((candidate) => !installed.has(candidate))) { + try { + await api.installDemoShowcase(id) + } catch (error) { + logger.error('Demo install failed', error) + } + } + }, + + /** + * Load the Nextcloud groups Step 4 offers, once. + * + * @return {Promise<void>} + * @spec openspec/specs/setup-wizard/spec.md#req-wiz-006 + */ + async loadRoleGroups() { + if (this.roleGroups.length > 0 || this.roleGroupsLoading) { + return + } + this.roleGroupsLoading = true + try { + const { data } = await api.getAdminGroups() + this.roleGroups = [...(data?.active || []), ...(data?.inactive || [])] + } catch (error) { + logger.warn('Failed to load groups', error) + } finally { + this.roleGroupsLoading = false + } + }, + + /** + * Give the selected group the admin role. A group that already has + * it is left as it is. + * + * @return {Promise<void>} + * @spec openspec/specs/setup-wizard/spec.md#req-wiz-006 + */ + async assignRoleGroup() { + try { + await api.assignAdminRoleToGroup(this.roleGroup) + } catch (error) { + if (error?.response?.status !== 409) { + throw error + } + } + }, + /** @spec openspec/specs/setup-wizard/spec.md */ onBack() { if (this.currentStep > 1) { @@ -379,26 +377,6 @@ export default { margin: 0 0 8px; } -.setup-wizard__radio { - display: flex; - gap: 12px; - padding: 12px; - border: 1px solid var(--color-border); - border-radius: var(--border-radius); - cursor: pointer; -} - -.setup-wizard__radio--disabled { - opacity: 0.5; - cursor: not-allowed; -} - -.setup-wizard__hint { - color: var(--color-text-maxcontrast); - margin: 4px 0 0; - font-size: 13px; -} - .setup-wizard__note { padding: 12px; background: var(--color-background-dark); diff --git a/src/modals/TemplateEditorModal.vue b/src/modals/TemplateEditorModal.vue index 1a527b4e7..3bb3ae132 100644 --- a/src/modals/TemplateEditorModal.vue +++ b/src/modals/TemplateEditorModal.vue @@ -18,6 +18,7 @@ <template> <NcModal v-if="open" + class="launchpad-modal" :name=" isEdit ? t('launchpad', 'Edit template') @@ -62,12 +63,12 @@ </div> <div class="launchpad-admin__field"> - <label>{{ t('launchpad', 'Target groups') }}</label> - <NcSelectTags + <NcSelect v-model="form.targetGroups" + class="launchpad-admin__target-groups" :options="availableGroups" :multiple="true" - :aria-label-combobox="t('launchpad', 'Target groups')" + :inputLabel="t('launchpad', 'Target groups')" :placeholder=" t('launchpad', 'Select groups (leave empty for all users)') " /> @@ -105,10 +106,10 @@ import { NcCheckboxRadioSwitch, NcModal, NcSelect, - NcSelectTags, NcTextField, } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' +import { FLAG_PROP, NULLABLE_OBJECT_PROP } from '../constants/propDefinitions.js' import { api } from '../services/api.js' import { logger } from '../utils/logger.js' @@ -135,7 +136,6 @@ export default { components: { NcButton, NcSelect, - NcSelectTags, NcTextField, NcCheckboxRadioSwitch, NcModal, @@ -143,18 +143,12 @@ export default { props: { /** Visibility toggle owned by the parent page. */ - open: { - type: Boolean, - default: false, - }, + open: FLAG_PROP, /** * The template to edit, or `null` to open a blank create form. */ - template: { - type: Object, - default: null, - }, + template: NULLABLE_OBJECT_PROP, }, emits: ['close', 'saved'], @@ -197,6 +191,7 @@ export default { handler(isOpen) { if (isOpen) { this.seedForm() + this.loadGroups() } }, }, @@ -212,6 +207,24 @@ export default { methods: { t, + /** + * Load the Nextcloud group ids the target groups field offers, once. + * + * @return {Promise<void>} + * @spec openspec/specs/admin-templates/spec.md + */ + async loadGroups() { + if (this.availableGroups.length > 0) { + return + } + try { + const { data } = await api.getAdminGroups() + this.availableGroups = [...(data?.active || []), ...(data?.inactive || [])] + } catch (error) { + logger.error('Failed to load groups:', error) + } + }, + /** * Build the working copy from the `template` prop. * @@ -276,6 +289,10 @@ export default { font-weight: 500; } +.launchpad-admin__target-groups { + width: 100%; +} + .launchpad-admin__modal { padding: 24px; } diff --git a/src/modals/TemplateResyncModal.vue b/src/modals/TemplateResyncModal.vue index ee7592867..75f0e5996 100644 --- a/src/modals/TemplateResyncModal.vue +++ b/src/modals/TemplateResyncModal.vue @@ -4,53 +4,113 @@ --> <!-- - TemplateResyncModal — admin "Re-sync to existing copies" dialog - (admin-template-resync REQ-RESYNC-001..005). - - Lets an admin push an updated template onto its already-provisioned user - copies. A strategy choice (overwrite / merge) selects between replacing - the whole layout or reconciling template-origin placements while keeping - each user's personally-added widgets. Apply is gated behind a completed - Dry-run for the currently-selected strategy — switching strategy or - re-opening the dialog resets the plan so a stale preview can never be - applied. + TemplateResyncModal — the rollout window behind "Push changes" on a + template (board LpBeheerSjablonen; admin-templates REQ-RESYNC-001..008). + + On open it runs a dry run for the preselected choice (Keep personal + changes, `merge`) and says, in the board's words, what the template gained + and lost since the copies were last synced and how many people changed + their copy. "How to update?" offers the three strategies with their + consequence; choosing another one runs a fresh dry run, so the push button + only ever applies the plan of the choice on screen. The button names the + number of dashboards it pushes to. --> <template> <NcModal v-if="open" - size="large" - :name="t('launchpad', 'Re-sync to existing copies')" + class="launchpad-modal" + size="normal" + :name="title" @close="handleClose"> <div class="launchpad-resync" data-testid="template-resync-dialog"> - <h2>{{ t('launchpad', 'Re-sync to existing copies') }}</h2> - <p class="launchpad-resync__hint"> + <h2 data-testid="template-resync-title"> + {{ title }} + </h2> + + <p + v-if="plan" + class="launchpad-resync__hint" + data-testid="template-resync-template"> {{ - t( - 'launchpad', - 'Push this template’s current layout to everyone who already has a copy.', - ) + t('launchpad', 'Template "{name}" has {count} copies.', { + name: template ? template.name : '', + count: plan.totalCopies, + }) }} </p> - <div class="launchpad-resync__field"> - <NcSelect - v-model="strategy" - :inputLabel="t('launchpad', 'Strategy')" - :options="strategyOptions" - label="label" - trackBy="id" - :clearable="false" - data-testid="template-resync-strategy" - @update:modelValue="handleStrategyChange" /> - <p class="launchpad-resync__strategy-hint"> - {{ strategyHint }} - </p> - </div> + <ul + v-if="plan" + class="launchpad-resync__changes" + data-testid="template-resync-changes"> + <li v-if="gained.length > 0" data-testid="template-resync-gained"> + {{ + t('launchpad', 'Added since the last sync: {widgets}', { + widgets: gained.join(', '), + }) + }} + </li> + <li v-if="lost.length > 0" data-testid="template-resync-lost"> + {{ + t('launchpad', 'Removed since the last sync: {widgets}', { + widgets: lost.join(', '), + }) + }} + </li> + <li + v-if="gained.length === 0 && lost.length === 0" + data-testid="template-resync-no-changes"> + {{ + t( + 'launchpad', + 'No widgets were added or removed since the last sync.', + ) + }} + </li> + </ul> + + <fieldset + class="launchpad-resync__choices" + data-testid="template-resync-strategy"> + <legend class="launchpad-resync__legend"> + {{ t('launchpad', 'How to update?') }} + </legend> + <label + v-for="choice in choices" + :key="choice.id" + class="launchpad-resync__choice" + :class="{ 'launchpad-resync__choice--active': strategy === choice.id }"> + <input + type="radio" + name="launchpad-resync-strategy" + :value="choice.id" + :checked="strategy === choice.id" + :disabled="applying" + :data-testid="`template-resync-choice-${choice.id}`" + @change="chooseStrategy(choice.id)"> + <span class="launchpad-resync__choice-text"> + <span class="launchpad-resync__choice-label">{{ choice.label }}</span> + <span class="launchpad-resync__choice-consequence">{{ choice.consequence }}</span> + </span> + </label> + </fieldset> + + <p + v-if="plan && plan.changedByOwnerCount > 0" + class="launchpad-resync__changed" + data-testid="template-resync-changed-count"> + {{ + t('launchpad', '{count} people changed their dashboard.', { + count: plan.changedByOwnerCount, + }) + }} + </p> <div v-if="error" class="launchpad-resync__error" + role="alert" data-testid="template-resync-error"> {{ error }} </div> @@ -59,46 +119,10 @@ <NcLoadingIcon :size="32" /> </div> - <template v-else-if="plan"> - <div - class="launchpad-resync__summary" - data-testid="template-resync-summary"> - {{ - t('launchpad', '{count} of {total} copies affected', { - count: plan.affectedCount, - total: plan.totalCopies, - }) - }} - </div> - - <table v-if="plan.copies.length > 0" class="launchpad-resync__table"> - <thead> - <tr> - <th scope="col">{{ t('launchpad', 'User') }}</th> - <th scope="col">{{ t('launchpad', 'Add') }}</th> - <th scope="col">{{ t('launchpad', 'Update') }}</th> - <th scope="col">{{ t('launchpad', 'Remove') }}</th> - <th scope="col">{{ t('launchpad', 'Unchanged') }}</th> - </tr> - </thead> - <tbody> - <tr - v-for="copy in plan.copies" - :key="copy.dashboardId" - :data-testid="`template-resync-copy-${copy.dashboardId}`"> - <td>{{ copy.userId }}</td> - <td>{{ copy.toAdd }}</td> - <td>{{ copy.toUpdate }}</td> - <td>{{ copy.toRemove }}</td> - <td>{{ copy.toPreserve }}</td> - </tr> - </tbody> - </table> - </template> - <div v-if="applied" class="launchpad-resync__success" + role="status" data-testid="template-resync-success"> <span v-if="applied.async"> {{ @@ -125,19 +149,12 @@ @click="handleClose"> {{ t('launchpad', 'Close') }} </NcButton> - <NcButton - variant="secondary" - data-testid="template-resync-dryrun" - :disabled="loading" - @click="runDryRun"> - {{ t('launchpad', 'Dry-run') }} - </NcButton> <NcButton variant="primary" data-testid="template-resync-apply" :disabled="!canApply" @click="apply"> - {{ t('launchpad', 'Apply') }} + {{ pushLabel }} </NcButton> </div> </div> @@ -149,14 +166,17 @@ import { NcButton, NcLoadingIcon, NcModal, - NcSelect, } from '@conduction/nextcloud-vue' +import { FLAG_PROP, NULLABLE_OBJECT_PROP } from '../constants/propDefinitions.js' import { api } from '../services/api.js' +/** The choice the window opens with (REQ-RESYNC-008). */ +const DEFAULT_STRATEGY = 'merge' + /** - * Admin dialog for pushing a template update to its provisioned copies. + * The rollout window: what a push changes, how to update, and the push. * - * @spec openspec/specs/admin-templates/spec.md + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ export default { name: 'TemplateResyncModal', @@ -164,39 +184,42 @@ export default { components: { NcModal, NcButton, - NcSelect, NcLoadingIcon, }, props: { - open: { - type: Boolean, - default: false, - }, + open: FLAG_PROP, - template: { - type: Object, - default: null, - }, + template: NULLABLE_OBJECT_PROP, }, emits: ['close', 'resynced'], data() { return { - strategy: { - id: 'overwrite', - label: t('launchpad', 'Overwrite — replace the whole layout'), - }, + strategy: DEFAULT_STRATEGY, - strategyOptions: [ + choices: [ { - id: 'overwrite', - label: t('launchpad', 'Overwrite — replace the whole layout'), + id: 'add_only', + label: t('launchpad', 'Only add new widgets'), + consequence: t( + 'launchpad', + 'Nothing disappears; personal layout stays.', + ), }, { id: 'merge', - label: t('launchpad', 'Merge — keep personally added widgets'), + label: t('launchpad', 'Keep personal changes'), + consequence: t( + 'launchpad', + 'The template wins, except what someone moved or added themselves.', + ), + }, + { + id: 'overwrite', + label: t('launchpad', 'Replace everything with the template'), + consequence: t('launchpad', 'Personal changes are lost.'), }, ], @@ -205,67 +228,93 @@ export default { error: '', plan: null, applied: null, + requestSeq: 0, } }, computed: { /** - * Apply is disabled until a dry-run for the currently-selected - * strategy has been reviewed (REQ-RESYNC-002 / tasks.md). + * The push button applies only a plan computed for the choice on + * screen (REQ-RESYNC-002). * - * @return {boolean} whether the Apply button is enabled. - * @spec openspec/specs/admin-templates/spec.md + * @return {boolean} whether the push button is enabled. + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ canApply() { return ( this.plan !== null + && this.plan.strategy === this.strategy && this.loading === false && this.applying === false ) }, /** - * Human-readable explanation of the selected strategy's semantics. + * The window's title, naming the number of dashboards once known. * - * @return {string} the strategy hint text. - * @spec openspec/specs/admin-templates/spec.md + * @return {string} the title. + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ - strategyHint() { - if (this.strategy?.id === 'merge') { - return t( - 'launchpad', - 'Adds and updates template widgets and restores compulsory widgets, but keeps widgets users added themselves.', - ) + title() { + if (!this.plan) { + return t('launchpad', 'Push changes') } - return t( - 'launchpad', - 'Replaces each copy’s entire layout with the template’s current layout — personally-added widgets will be removed.', - ) + return t('launchpad', 'Push changes to {count} dashboards', { + count: this.plan.totalCopies, + }) }, - }, - watch: { /** - * Reset all report/result state whenever the dialog opens or - * closes, so a stale plan from a previous template can never be - * applied to a different one. + * The confirm button's label, naming the number of dashboards. * - * @param {boolean} isOpen whether the modal is now open. - * @return {void} - * @spec openspec/specs/admin-templates/spec.md + * @return {string} the label. + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen + */ + pushLabel() { + if (!this.plan) { + return t('launchpad', 'Push changes') + } + return t('launchpad', 'Push to {count} dashboards', { + count: this.plan.totalCopies, + }) + }, + + /** + * Widgets the template gained since the copies were last synced. + * + * @return {string[]} the widget names. + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ + gained() { + return Array.isArray(this.plan?.gained) ? this.plan.gained : [] + }, + + /** + * Widgets the template lost since the copies were last synced. + * + * @return {string[]} the widget names. + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen + */ + lost() { + return Array.isArray(this.plan?.lost) ? this.plan.lost : [] + }, + }, + + watch: { open: { immediate: true, /** - * Clear any previous dry-run plan when the modal opens, so Apply - * stays disabled until a fresh plan is produced. + * On open: back to Keep personal changes and a fresh dry run, so a + * plan from an earlier template can never be applied. * * @param {boolean} isOpen Whether the modal is now open. - * @spec openspec/specs/admin-templates/spec.md + * @return {void} + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ handler(isOpen) { if (isOpen) { this.resetState() + this.runDryRun() } }, }, @@ -275,13 +324,13 @@ export default { t, /** - * Clear the plan/result/error state (REQ-RESYNC-002 — a fresh - * dry-run must always be reviewed before Apply unlocks). + * Clear the plan, result and error, and preselect Keep personal changes. * * @return {void} - * @spec openspec/specs/admin-templates/spec.md + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ resetState() { + this.strategy = DEFAULT_STRATEGY this.loading = false this.applying = false this.error = '' @@ -290,52 +339,65 @@ export default { }, /** - * Strategy changed — any previously-reviewed plan applied to the - * old strategy is no longer valid. + * Another choice: its own dry run replaces the shown plan. * + * @param {string} id The strategy id (`add_only`, `merge`, `overwrite`). * @return {void} - * @spec openspec/specs/admin-templates/spec.md + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ - handleStrategyChange() { - this.plan = null + chooseStrategy(id) { + if (id === this.strategy) { + return + } + this.strategy = id this.applied = null - this.error = '' + this.runDryRun() }, /** - * Compute the re-sync plan without mutating anything - * (REQ-RESYNC-002). + * Compute the plan for the current choice without changing anything + * (REQ-RESYNC-002). A slower answer for an earlier choice is dropped. * * @return {Promise<void>} resolves once the plan is loaded. - * @spec openspec/specs/admin-templates/spec.md + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ async runDryRun() { if (!this.template) { return } + const seq = ++this.requestSeq + const strategy = this.strategy this.loading = true this.error = '' - this.applied = null try { const { data } = await api.resyncAdminTemplate(this.template.id, { - strategy: this.strategy.id, + strategy, dryRun: true, }) - this.plan = data + if (seq !== this.requestSeq) { + return + } + this.plan = { ...data, strategy } } catch { + if (seq !== this.requestSeq) { + return + } + this.plan = null this.error = t('launchpad', 'Could not compute the re-sync plan.') } finally { - this.loading = false + if (seq === this.requestSeq) { + this.loading = false + } } }, /** - * Apply the reviewed plan (REQ-RESYNC-001, REQ-RESYNC-005). + * Push the plan on screen (REQ-RESYNC-001, REQ-RESYNC-005). * * @return {Promise<void>} resolves once the re-sync request completes. - * @spec openspec/specs/admin-templates/spec.md + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ async apply() { if (!this.template || !this.canApply) { @@ -347,7 +409,7 @@ export default { try { const { data } = await api.resyncAdminTemplate(this.template.id, { - strategy: this.strategy.id, + strategy: this.strategy, dryRun: false, }) this.applied = data @@ -361,7 +423,7 @@ export default { }, /** - * Close the dialog. + * Close the window. * * @return {void} * @spec openspec/specs/admin-templates/spec.md @@ -380,46 +442,75 @@ export default { .launchpad-resync__hint { color: var(--color-text-maxcontrast); - margin-bottom: 16px; + margin-bottom: 8px; } -.launchpad-resync__field { - margin-bottom: 16px; +.launchpad-resync__changes { + margin: 0 0 16px; + padding-inline-start: 20px; + list-style: disc; } -.launchpad-resync__strategy-hint { - color: var(--color-text-maxcontrast); - font-size: 13px; - margin-top: 4px; +.launchpad-resync__choices { + border: none; + margin: 0 0 12px; + padding: 0; + display: flex; + flex-direction: column; + gap: 8px; } -.launchpad-resync__error { - color: var(--color-error); - padding: 8px 0; +.launchpad-resync__legend { + font-weight: 600; + margin-bottom: 8px; } -.launchpad-resync__loading { +.launchpad-resync__choice { display: flex; - justify-content: center; - padding: 24px; + align-items: flex-start; + gap: 10px; + padding: 10px 12px; + border: 1px solid var(--color-border); + border-radius: var(--border-radius-large); + cursor: pointer; +} + +.launchpad-resync__choice--active { + border-color: var(--color-primary-element); + background-color: var(--color-primary-element-light); +} + +.launchpad-resync__choice input { + margin-top: 3px; +} + +.launchpad-resync__choice-text { + display: flex; + flex-direction: column; } -.launchpad-resync__summary { +.launchpad-resync__choice-label { font-weight: 600; - margin: 12px 0; } -.launchpad-resync__table { - width: 100%; - border-collapse: collapse; - margin-bottom: 12px; +.launchpad-resync__choice-consequence { + color: var(--color-text-maxcontrast); + font-size: 13px; +} + +.launchpad-resync__changed { + margin: 8px 0; +} + +.launchpad-resync__error { + color: var(--color-error); + padding: 8px 0; } -.launchpad-resync__table th, -.launchpad-resync__table td { - text-align: left; - padding: 6px 8px; - border-bottom: 1px solid var(--color-border); +.launchpad-resync__loading { + display: flex; + justify-content: center; + padding: 12px; } .launchpad-resync__success { diff --git a/src/modals/TileEditor.vue b/src/modals/TileEditor.vue index f7c6740d5..255cb01b5 100644 --- a/src/modals/TileEditor.vue +++ b/src/modals/TileEditor.vue @@ -11,54 +11,253 @@ renders empty and never writes back. Use `v-model` throughout. --> <NcModal v-model:show="isOpen" - :name="tile ? t('launchpad', 'Edit Tile') : t('launchpad', 'Create Tile')" + class="launchpad-modal" + :name="heading" size="normal" @close="$emit('close')"> + <!-- tile-form-board-sync REQ-TILE-040: one 640 px form, in the board's order. --> <div class="tile-editor"> - <h2> - {{ - tile - ? t('launchpad', 'Edit Tile') - : t('launchpad', 'Create Tile') - }} + <h2 class="tile-editor__heading"> + {{ heading }} </h2> + <p class="tile-editor__where" data-testid="tile-editor-where"> + {{ whereLine }} + </p> - <div class="tile-editor__preview"> - <div - class="tile-preview" - :style="{ - backgroundColor: form.backgroundColor, - color: form.textColor, - }"> - <img - v-if="isUrlIcon" - class="tile-preview__icon" - :src="displayIcon" - alt="" /> - <svg - v-else - class="tile-preview__icon" - :style="{ fill: form.textColor }" - viewBox="0 0 24 24"> - <path :d="displayIcon" /> - </svg> - <span class="tile-preview__title">{{ form.title }}</span> + <div class="tile-editor__form"> + <div class="form-row"> + <div class="form-row__item"> + <NcTextField + v-model="form.title" + :label="t('launchpad', 'Name')" + :placeholder="t('launchpad', 'Enter tile name')" + required /> + </div> + <div class="form-row__item"> + <NcTextField + :modelValue="groupLabel" + :label="t('launchpad', 'Group')" + :helperText="groupName ? '' : t('launchpad', 'Tiles in a group share its sort order.')" + disabled + data-testid="tile-group" /> + </div> </div> - </div> - <div class="tile-editor__form"> - <NcTextField - v-model="form.title" - :label="t('launchpad', 'Title')" - :placeholder="t('launchpad', 'Enter tile title')" - required /> + <!-- launcher-tile-launch-types: what the tile opens. The server + checks every type (TileLinkValidator); an sso tile's address + is resolved there from the template, so it has no address field. --> + <ChoiceCards + :modelValue="form.linkType" + :options="linkTypeOptions" + :label="t('launchpad', 'Tile type')" + :columns="2" + name="tile-link-type" + data-testid="tile-link-type" + @update:modelValue="onLinkType" /> - <div class="tile-editor__field"> + <template v-if="form.linkType === 'program'"> + <NcTextField + v-model="form.linkValue" + :label="t('launchpad', 'Program address')" + :helperText="programHelp" + type="text" + data-testid="tile-program-address" /> + </template> + + <template v-else-if="form.linkType === 'remote-desktop'"> + <fieldset class="tile-editor__fieldset"> + <legend>{{ t('launchpad', 'Connection') }}</legend> + <NcCheckboxRadioSwitch + :modelValue="form.remoteMode === 'gateway'" + type="radio" + name="tile-remote-mode" + data-testid="tile-remote-gateway" + @update:modelValue="form.remoteMode = 'gateway'"> + {{ t('launchpad', 'Through a web gateway') }} + </NcCheckboxRadioSwitch> + <NcCheckboxRadioSwitch + :modelValue="form.remoteMode === 'rdp'" + type="radio" + name="tile-remote-mode" + data-testid="tile-remote-rdp" + @update:modelValue="form.remoteMode = 'rdp'"> + {{ t('launchpad', 'Download an RDP file') }} + </NcCheckboxRadioSwitch> + </fieldset> + + <NcTextField + v-if="form.remoteMode === 'gateway'" + v-model="form.remoteUrl" + :label="t('launchpad', 'Gateway address')" + :helperText="t('launchpad', 'An https address, such as your Guacamole, Citrix or Azure Virtual Desktop web page.')" + type="text" + data-testid="tile-remote-url" /> + <template v-else> + <div class="form-row"> + <div class="form-row__item"> + <NcTextField + v-model="form.rdpHost" + :label="t('launchpad', 'Computer or server')" + type="text" + data-testid="tile-rdp-host" /> + </div> + <div class="form-row__item"> + <NcTextField + v-model="form.rdpPort" + :label="t('launchpad', 'Port')" + :helperText="t('launchpad', 'Leave empty for {port}.', { port: DEFAULT_RDP_PORT })" + type="number" + data-testid="tile-rdp-port" /> + </div> + </div> + <NcTextField + v-model="form.rdpRemoteApp" + :label="t('launchpad', 'Published program (optional)')" + :helperText="t('launchpad', 'The RemoteApp name, such as ||Belastingen. Leave empty for the whole desktop.')" + type="text" + data-testid="tile-rdp-program" /> + <NcTextField + v-model="form.rdpGateway" + :label="t('launchpad', 'Remote desktop gateway (optional)')" + type="text" + data-testid="tile-rdp-gateway" /> + </template> + </template> + + <template v-else-if="form.linkType === 'sso'"> + <NcSelect + :modelValue="form.ssoTemplate || null" + :options="ssoTemplateOptions" + :inputLabel="t('launchpad', 'Sign-on template')" + :reduce="(option) => option.value" + :clearable="false" + label="label" + data-testid="tile-sso-template" + @update:modelValue="form.ssoTemplate = $event" /> + <p v-if="ssoTemplateOptions.length === 0" class="tile-editor__hint-small"> + {{ t('launchpad', 'No sign-on templates yet. An administrator adds them on the LaunchPad admin page.') }} + </p> + <NcTextField + v-model="form.ssoAppId" + :label="t('launchpad', 'App id')" + :helperText="t('launchpad', 'The id the identity provider gives this app.')" + type="text" + data-testid="tile-sso-app-id" /> + </template> + + <!-- Web address and internal address side by side (REQ-TILE-040). --> + <div class="form-row"> + <div v-if="hasWebAddress" class="form-row__item"> + <NcTextField + v-model="form.linkValue" + :label="t('launchpad', 'Web address')" + :placeholder="t('launchpad', 'https://example.com or /apps/files')" + type="text" /> + </div> + <div v-if="!inGroup" class="form-row__item"> + <NcTextField + v-model="form.internalUrl" + :label="t('launchpad', 'Internal address (optional)')" + :placeholder="t('launchpad', 'e.g. http://intranet.local')" + type="text" /> + </div> + </div> + <p v-if="!inGroup" class="tile-editor__hint-small tile-editor__address-in-effect"> + {{ addressInEffect }} + </p> + <!-- REQ-TILE-041: a tile in a group is a child of the group, not a + placement of its own, so what needs its own placement on the + server (launching, the availability check, the office-network + address, where it opens) is not offered here. --> + <p v-else class="tile-editor__hint-small" data-testid="tile-in-group-hint"> + {{ t('launchpad', 'A tile in a group opens its web address in a new tab.') }} + </p> + + <!-- Launcher-tile-open-behaviour: how the tile opens, as three cards. --> + <div v-if="!inGroup" class="tile-editor__opens-in" data-test="tile-editor-opens-in"> + <ChoiceCards + :modelValue="form.linkTarget" + :options="linkTargetOptions" + :label="t('launchpad', 'Open in')" + :columns="3" + name="tile-link-target" + @update:modelValue="form.linkTarget = $event" /> + <p class="tile-editor__hint" data-test="tile-editor-opens-in-default"> + <template v-if="form.linkTarget === ''"> + {{ t('launchpad', 'None chosen: the tile opens as the dashboard decides.') }} + </template> + <NcButton + v-else + variant="tertiary" + data-test="tile-editor-follow-dashboard" + @click="form.linkTarget = ''"> + {{ t('launchpad', 'Open as the dashboard decides') }} + </NcButton> + </p> + <p + v-if="panelRefusal" + class="tile-editor__hint" + data-test="tile-editor-panel-refusal"> + {{ panelRefusal }} + </p> + </div> + + <!-- The icon with its preview, a picker on demand and an upload. --> + <div class="tile-editor__field tile-editor__icon"> + <span class="tile-editor__label">{{ t('launchpad', 'Icon') }}</span> + <div class="tile-editor__icon-row"> + <div + class="tile-preview" + :style="{ + background: previewBackground, + color: form.colourToken ? '#ffffff' : form.textColor, + }"> + <img + v-if="isUrlIcon" + class="tile-preview__icon" + :src="displayIcon" + alt="" /> + <svg + v-else + class="tile-preview__icon" + :style="{ fill: form.textColor }" + viewBox="0 0 24 24"> + <path :d="displayIcon" /> + </svg> + <span class="tile-preview__title">{{ form.title }}</span> + </div> + <div class="tile-editor__icon-actions"> + <NcButton + data-testid="tile-icon-choose" + :aria-expanded="iconBrowserOpen ? 'true' : 'false'" + @click="iconBrowserOpen = !iconBrowserOpen"> + {{ iconBrowserOpen ? t('launchpad', 'Close the icon list') : t('launchpad', 'Choose an icon') }} + </NcButton> + <NcButton + data-testid="tile-icon-upload" + :disabled="iconUploading" + @click="pickIconFile"> + {{ t('launchpad', 'Upload another icon') }} + </NcButton> + <input + ref="iconFile" + class="tile-editor__file" + type="file" + accept="image/png,image/jpeg,image/gif,image/webp,image/svg+xml" + tabindex="-1" + aria-hidden="true" + @change="onIconFile"> + <p v-if="iconUploadError" class="tile-editor__warning" role="alert"> + {{ iconUploadError }} + </p> + </div> + </div> <!-- No `url-icon-groups`: CnIconBrowser ships the NL Design sets (Gemeente / Den Haag / RVO) by default and fetches RVO's 1.9 MB only when its tab is opened. Passing them explicitly, as this used to, forced the whole pack into the eager bundle. --> <CnIconBrowser + v-if="iconBrowserOpen" inline :label="t('launchpad', 'Icon')" :value="displayIcon" @@ -66,65 +265,110 @@ @input="onIcon" /> </div> - <div class="form-row"> - <div class="form-row__item"> - <label>{{ t('launchpad', 'Background Color') }}</label> - <NcColorPicker v-model="form.backgroundColor"> - <NcButton - variant="tertiary" - :aria-label=" - t('launchpad', 'Pick background color') - "> - <template #icon> - <div - class="color-preview" - :style="{ - backgroundColor: form.backgroundColor, - }" /> - </template> - {{ form.backgroundColor }} - </NcButton> - </NcColorPicker> + <div class="tile-editor__field"> + <span :id="colourLabelId" class="tile-editor__label">{{ t('launchpad', 'Colour') }}</span> + <!-- REQ-ICT-004 (board LpTegelBewerken): eight theme colours, + each previewing the white icon; "Own colour" keeps the + colour pickers for a hex colour. --> + <div + class="tile-editor__swatches" + role="radiogroup" + :aria-labelledby="colourLabelId" + data-test="tile-editor-swatches"> + <label + v-for="swatch in colourSwatches" + :key="swatch.token" + class="tile-editor__swatch" + :class="{ 'tile-editor__swatch--on': form.colourToken === swatch.token }" + :style="{ background: swatch.css }" + :title="swatch.label"> + <input + type="radio" + class="tile-editor__swatch-input" + name="tile-colour" + :value="swatch.token" + :checked="form.colourToken === swatch.token" + :aria-label="swatch.label" + :data-test="'tile-editor-swatch' + swatch.token" + @change="form.colourToken = swatch.token"> + <span class="tile-editor__swatch-icon" aria-hidden="true">A</span> + </label> + <label class="tile-editor__swatch-own"> + <input + type="radio" + name="tile-colour" + value="" + :checked="form.colourToken === ''" + data-test="tile-editor-swatch-own" + @change="form.colourToken = ''"> + {{ t('launchpad', 'Own colour') }} + </label> </div> + <div v-if="form.colourToken === ''" class="form-row"> + <div class="form-row__item"> + <NcColorPicker v-model="form.backgroundColor"> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Pick background color')"> + <template #icon> + <div + class="color-preview" + :style="{ + backgroundColor: form.backgroundColor, + }" /> + </template> + {{ t('launchpad', 'Background') }} {{ form.backgroundColor }} + </NcButton> + </NcColorPicker> + </div> - <div class="form-row__item"> - <label>{{ t('launchpad', 'Text Color') }}</label> - <NcColorPicker v-model="form.textColor"> - <NcButton - variant="tertiary" - :aria-label="t('launchpad', 'Pick text color')"> - <template #icon> - <div - class="color-preview" - :style="{ - backgroundColor: form.textColor, - }" /> - </template> - {{ form.textColor }} - </NcButton> - </NcColorPicker> + <div class="form-row__item"> + <NcColorPicker v-model="form.textColor"> + <NcButton + variant="tertiary" + :aria-label="t('launchpad', 'Pick text color')"> + <template #icon> + <div + class="color-preview" + :style="{ + backgroundColor: form.textColor, + }" /> + </template> + {{ t('launchpad', 'Icon and text') }} {{ form.textColor }} + </NcButton> + </NcColorPicker> + </div> </div> </div> - <NcTextField - v-model="form.linkValue" - :label="t('launchpad', 'URL')" - :placeholder=" - t('launchpad', 'https://example.com or /apps/files') - " - type="text" /> + <!-- REQ-TILE-041: the sort order of the tile's group. --> + <NcSelect + :modelValue="groupSortBy" + :options="groupSortOptions" + :inputLabel="t('launchpad', 'Sort order in this group')" + :reduce="(option) => option.value" + :clearable="false" + :disabled="!groupName" + label="label" + data-testid="tile-group-sort" + @update:modelValue="groupSortBy = $event" /> - <div class="tile-editor__health-ping"> + <div v-if="!inGroup" class="tile-editor__health-ping"> <NcCheckboxRadioSwitch :modelValue="form.healthPingEnabled" type="switch" @update:modelValue="onHealthPingToggle"> - {{ - t('launchpad', 'Show a live status badge (health ping)') - }} + {{ t('launchpad', 'Check availability') }} </NcCheckboxRadioSwitch> <template v-if="form.healthPingEnabled"> + <!-- REQ-TILE-042: the last check's result with its time. --> + <p + v-if="tile && tile.id" + class="tile-editor__hint-small tile-editor__last-check" + data-testid="tile-last-check"> + {{ lastCheck }} + </p> <NcTextField v-model="form.healthUrl" :label="t('launchpad', 'Health check URL')" @@ -166,8 +410,9 @@ <div class="tile-editor__actions"> <NcButton v-if="tile" variant="error" @click="$emit('delete')"> - {{ t('launchpad', 'Delete') }} + {{ t('launchpad', 'Delete tile') }} </NcButton> + <span v-else /> <div class="tile-editor__actions-right"> <NcButton @click="$emit('close')"> {{ t('launchpad', 'Cancel') }} @@ -190,16 +435,42 @@ import { NcCheckboxRadioSwitch, NcColorPicker, NcModal, + NcSelect, NcTextField, } from '@conduction/nextcloud-vue' import { mdiLink } from '@mdi/js' -import { validateHealthPingConfig } from '../services/healthPingClient.js' -import { ICON_CATALOGUE, normaliseIconValue } from '../services/iconCatalogue.js' +import { translate as t } from '@nextcloud/l10n' +import ChoiceCards from '../components/ChoiceCards.vue' +import { FLAG_PROP, NULLABLE_OBJECT_PROP, TEXT_PROP } from '../constants/propDefinitions.js' +import { fetchHealthPingBadge, validateHealthPingConfig } from '../services/healthPingClient.js' +import { ICON_CATALOGUE, loadIconCatalogue, normaliseIconValue } from '../services/iconCatalogue.js' +import { validateIframeUrl } from '../services/iframeClient.js' +import { uploadFile } from '../services/resourceService.js' +import { isOnOfficeNetwork, loadInitialState } from '../utils/loadInitialState.js' +import { lastCheckLine } from '../utils/tileAvailability.js' +import { isColourToken, TILE_COLOUR_TOKENS, tileBackground } from '../utils/tileColour.js' +import { DEFAULT_RDP_PORT, launchFields, LINK_PROGRAM, LINK_REMOTE, LINK_SSO } from '../utils/tileLaunch.js' +import { NEW_TAB, SAME_TAB, SIDE_PANEL } from '../utils/tileLinkTarget.js' +import { normaliseSortMode } from '../utils/tileSort.js' const MIN_PING_INTERVAL = 15 const DEFAULT_PING_INTERVAL = 60 const DEFAULT_EXPECTED_STATUS = 200 +/** + * The admin's allowed program schemes and the sign-on template names. + * + * @return {{schemes: string[], templates: Array<{key: string, name: string}>}} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-4 + */ +function tileLaunchOptions() { + const state = loadInitialState('workspace') + return { + schemes: Array.isArray(state.tileAllowedSchemes) ? state.tileAllowedSchemes : [], + templates: Array.isArray(state.ssoLaunchTemplates) ? state.ssoLaunchTemplates : [], + } +} + export default { name: 'TileEditor', @@ -209,19 +480,27 @@ export default { NcTextField, NcColorPicker, NcCheckboxRadioSwitch, + NcSelect, CnIconBrowser, + ChoiceCards, }, props: { - open: { - type: Boolean, - default: false, - }, + open: FLAG_PROP, - tile: { - type: Object, - default: null, - }, + tile: NULLABLE_OBJECT_PROP, + + /** The dashboard the tile is on, for the line under the heading. */ + dashboardName: TEXT_PROP, + + /** The title of the group (container) the tile is in; '' for none. */ + groupName: TEXT_PROP, + + /** The group's stored sort mode (`content.sortBy`). */ + groupSort: TEXT_PROP, + + /** Whether the tile is a child of a group rather than a placement of its own. */ + inGroup: FLAG_PROP, }, emits: ['close', 'save', 'delete'], @@ -234,20 +513,180 @@ export default { iconType: 'svg', backgroundColor: '#0082c9', textColor: '#ffffff', + colourToken: '', linkType: 'url', linkValue: '', + internalUrl: '', + linkTarget: '', healthPingEnabled: false, healthUrl: '', expectedStatus: DEFAULT_EXPECTED_STATUS, pingInterval: DEFAULT_PING_INTERVAL, + ...launchFields({}), }, healthUrlError: '', + iconBrowserOpen: false, + iconUploading: false, + iconUploadError: '', + // REQ-TILE-042: the last health ping reading of the tile. + lastReading: null, + groupSortBy: normaliseSortMode(this.groupSort), + onOfficeNetwork: isOnOfficeNetwork(), + panelRefusal: '', MIN_PING_INTERVAL, + DEFAULT_RDP_PORT, + // launcher-tile-launch-types: the admin's allowed schemes and the + // names of the sign-on templates (never their addresses). + launchOptions: tileLaunchOptions(), } }, computed: { + /** + * The eight theme colours, each with its name for screen readers. + * + * @return {Array<{token: string, label: string, css: string}>} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-the-tile-colour-is-one-of-eight-theme-colours-req-ict-004 + */ + colourSwatches() { + const names = { + '--sc-primary': t('launchpad', 'Primary'), + '--sc-primary-deep': t('launchpad', 'Primary, dark'), + '--sc-accent': t('launchpad', 'Accent'), + '--sc-accent-deep': t('launchpad', 'Accent, dark'), + '--sc-work-ink': t('launchpad', 'Ink'), + '--sc-work-text': t('launchpad', 'Text grey'), + '--sc-work-muted': t('launchpad', 'Muted grey'), + '--sc-work-field': t('launchpad', 'Field grey'), + } + return TILE_COLOUR_TOKENS.map(({ token }) => ({ + token, + label: names[token], + css: tileBackground(null, { colourToken: token }), + })) + }, + + /** + * The preview's background: the chosen token, else the hex colour. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-the-tile-colour-is-one-of-eight-theme-colours-req-ict-004 + */ + previewBackground() { + return tileBackground({ backgroundColor: this.form.backgroundColor }, { colourToken: this.form.colourToken }) + }, + + /** + * The id the swatch group is labelled by. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-the-tile-colour-is-one-of-eight-theme-colours-req-ict-004 + */ + colourLabelId() { + return 'tile-editor-colour-' + (this.tile?.id ?? 'new') + }, + + /** + * The "Opens in" choices. The panel is unavailable for an outside + * address whose host is not on the embed allow-list. + * + * Three cards (REQ-TILE-040); none chosen ('') follows the dashboard. + * + * @return {Array<{value: string, label: string, hint: string, disabled: boolean}>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + */ + linkTargetOptions() { + return [ + { value: SAME_TAB, label: t('launchpad', 'Same tab'), hint: t('launchpad', 'Replaces Launchpad in this tab.'), disabled: false }, + { value: NEW_TAB, label: t('launchpad', 'New tab'), hint: t('launchpad', 'Launchpad stays open.'), disabled: false }, + { + value: SIDE_PANEL, + label: t('launchpad', 'In Launchpad, next to the tiles'), + hint: t('launchpad', 'Opens in a panel beside the tiles.'), + disabled: this.panelRefusal !== '', + }, + ] + }, + + /** + * The form's heading: "Edit tile: <name>", or "New tile". + * + * @return {string} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + */ + heading() { + if (!this.tile) { + return t('launchpad', 'New tile') + } + return t('launchpad', 'Edit tile: {name}', { name: this.tile.title || '' }) + }, + + /** + * The line under the heading: "<group> · <dashboard>". + * + * @return {string} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + */ + whereLine() { + if (!this.dashboardName) { + return this.groupLabel + } + return t('launchpad', '{group} · {dashboard}', { group: this.groupLabel, dashboard: this.dashboardName }) + }, + + /** + * The tile's group as the Group field shows it. + * + * @return {string} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + groupLabel() { + return this.groupName || t('launchpad', 'No group') + }, + + /** + * The group's sort orders, by the names the form gives them; the + * values are the container's stored modes (src/utils/tileSort.js). + * + * @return {Array<{value: string, label: string}>} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + groupSortOptions() { + const options = [ + { value: 'last-used', label: t('launchpad', 'Last used first') }, + { value: 'alphabetical', label: t('launchpad', 'Alphabetical') }, + { value: 'random', label: t('launchpad', 'Random') }, + { value: 'manual', label: t('launchpad', 'As placed') }, + ] + if (!options.some((option) => option.value === this.groupSortBy)) { + options.push({ value: this.groupSortBy, label: t('launchpad', 'Most used first') }) + } + return options + }, + + /** + * Whether the tile type has a web address field of its own: a program, + * remote desktop or sign-on tile has its own fields instead. + * + * @return {boolean} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + */ + hasWebAddress() { + return ![LINK_PROGRAM, LINK_REMOTE, LINK_SSO].includes(this.form.linkType) + }, + + /** + * The result of the last availability check with its time. + * + * @return {string} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-last-availability-check-in-the-form-req-tile-042 + */ + lastCheck() { + return lastCheckLine(this.lastReading, new Date(), t) + }, + isOpen: { /** @spec openspec/specs/tiles/spec.md */ get() { @@ -300,9 +739,112 @@ export default { displayIcon() { return normaliseIconValue(this.form.icon) }, + + /** + * What a tile can open. A type this editor does not offer (an older + * `app` or `internal` tile) stays selectable so editing keeps it. + * + * Four choice cards with one line of explanation each (REQ-TILE-040). + * + * @return {Array<{value: string, label: string, hint: string}>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-4 + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + linkTypeOptions() { + const options = [ + { value: 'url', label: t('launchpad', 'Web address'), hint: t('launchpad', 'A website or a page on this Nextcloud.') }, + ] + // REQ-TILE-041: a tile in a group has no placement the server can + // launch, so it only opens an address. + if (!this.inGroup) { + options.push(...this.launchTypeOptions) + } + const current = this.form.linkType + if (current && !options.some((option) => option.value === current)) { + options.unshift({ + value: current, + label: current === 'app' ? t('launchpad', 'Nextcloud app') : t('launchpad', 'Link'), + hint: t('launchpad', 'An older tile type, kept while you edit.'), + }) + } + return options + }, + + /** + * The tile types the server launches for a tile of its own. + * + * @return {Array<{value: string, label: string, hint: string}>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-4 + */ + launchTypeOptions() { + return [ + { value: LINK_SSO, label: t('launchpad', 'App with single sign-on'), hint: t('launchpad', 'Signs in through your identity provider.') }, + { value: LINK_REMOTE, label: t('launchpad', 'Legacy Windows program'), hint: t('launchpad', 'Through remote desktop or a web gateway.') }, + { value: LINK_PROGRAM, label: t('launchpad', 'Program on this computer'), hint: t('launchpad', 'Starts a program installed on the device.') }, + ] + }, + + /** + * The sign-on templates an author picks from. + * + * @return {Array<{value: string, label: string}>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-4 + */ + ssoTemplateOptions() { + return this.launchOptions.templates.map((template) => ({ value: template.key, label: template.name })) + }, + + /** + * The helper line under a program address: which schemes work. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-4 + */ + programHelp() { + if (this.launchOptions.schemes.length === 0) { + return t('launchpad', 'No program schemes are allowed yet. An administrator allows them on the LaunchPad admin page.') + } + return t('launchpad', 'Allowed schemes: {schemes}', { schemes: this.launchOptions.schemes.join(', ') }) + }, + + /** + * Which address this tile opens for the author right now, from the + * same server answer every viewer gets (launcher-tile-internal-address D3). + * + * @return {string} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-the-tile-opens-the-address-that-fits-the-network-req-tia-003 + */ + addressInEffect() { + if (this.onOfficeNetwork) { + return t('launchpad', 'You are on the office network: this tile opens the internal address') + } + return t('launchpad', 'You are not on the office network: this tile opens the main address') + }, }, watch: { + /** + * Re-check whether the address may open in the panel whenever it changes. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + 'form.linkValue': function() { + this.checkPanelAllowed() + }, + + /** + * Follow the group's stored order when the parent changes it. + * + * @param {string} value The stored sort mode. + * @return {void} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + groupSort(value) { + this.groupSortBy = normaliseSortMode(value) + }, + tile: { immediate: true, /** @@ -311,20 +853,31 @@ export default { * @param {object|null} newTile Tile to edit; null opens a blank * form for a new tile. * @spec openspec/specs/tiles/spec.md + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-last-availability-check-in-the-form-req-tile-042 */ handler(newTile) { if (newTile) { this.form = { + ...launchFields({}), ...newTile, + internalUrl: newTile.internalUrl || '', iconType: newTile.iconType || 'class', + colourToken: isColourToken(newTile.colourToken) ? newTile.colourToken : '', + linkTarget: newTile.linkTarget || '', } } else { this.resetForm() } + this.lastReading = null + this.loadLastCheck() }, }, }, + created() { + loadIconCatalogue().catch(() => {}) + }, + methods: { /** * Store the picked icon. CnIconBrowser emits an SVG path (MDI) or a URL @@ -342,6 +895,24 @@ export default { this.form.iconType = isCustomIconUrl(value) ? 'url' : 'svg' }, + /** + * Switch what the tile opens. Leaving a type whose address the server + * resolves clears the stale address. + * + * @param {string} value The new link type. + * @return {void} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-launch-types/tasks.md#task-4 + */ + onLinkType(value) { + if (value === this.form.linkType) { + return + } + if ([LINK_REMOTE, LINK_SSO].includes(this.form.linkType) || [LINK_REMOTE, LINK_SSO].includes(value)) { + this.form.linkValue = '' + } + this.form.linkType = value + }, + /** @spec openspec/specs/tiles/spec.md */ resetForm() { this.form = { @@ -350,12 +921,16 @@ export default { iconType: 'svg', backgroundColor: '#0082c9', textColor: '#ffffff', + colourToken: '', linkType: 'url', linkValue: '', + internalUrl: '', + linkTarget: '', healthPingEnabled: false, healthUrl: '', expectedStatus: DEFAULT_EXPECTED_STATUS, pingInterval: DEFAULT_PING_INTERVAL, + ...launchFields({}), } this.healthUrlError = '' }, @@ -367,11 +942,77 @@ export default { * @param {boolean} value the new toggle state. * @return {void} * @spec openspec/specs/service-health-ping/spec.md + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-last-availability-check-in-the-form-req-tile-042 */ onHealthPingToggle(value) { this.form.healthPingEnabled = value if (!value) { this.healthUrlError = '' + } else { + this.loadLastCheck() + } + }, + + /** + * Read the tile's last health ping, for the line under the switch. + * Only a saved tile with the check on has one; a failed read shows + * "Not checked yet". + * + * @return {Promise<void>} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-last-availability-check-in-the-form-req-tile-042 + */ + async loadLastCheck() { + const id = this.tile?.id + if (!id || !this.form.healthPingEnabled || this.lastReading) { + return + } + try { + const reading = await fetchHealthPingBadge(id) + if (this.tile?.id === id) { + this.lastReading = reading + } + } catch { + this.lastReading = null + } + }, + + /** + * Open the file chooser for "Upload another icon". + * + * @return {void} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + */ + pickIconFile() { + this.$refs.iconFile?.click() + }, + + /** + * Upload the chosen file as the tile's icon; the stored icon becomes + * the resource's URL, as an upload in the icon browser makes it. + * + * @param {Event} event The file input's change event. + * @return {Promise<void>} + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + * @spec openspec/specs/resource-uploads/spec.md + */ + async onIconFile(event) { + const file = event?.target?.files?.[0] + if (!file) { + return + } + this.iconUploading = true + this.iconUploadError = '' + try { + const resource = await uploadFile(file) + this.form.icon = resource.url + this.form.iconType = 'url' + } catch { + this.iconUploadError = t('launchpad', 'The icon could not be uploaded.') + } finally { + this.iconUploading = false + if (event.target) { + event.target.value = '' + } } }, @@ -434,14 +1075,55 @@ export default { } }, - /** @spec openspec/specs/tiles/spec.md */ + /** + * Whether the address may open in the panel. An address on this + * Nextcloud (an app, an internal path) always may; an outside one only + * when its host is on the embed allow-list. A refused address cannot + * keep the panel as its choice. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + async checkPanelAllowed() { + const value = String(this.form.linkValue || '').trim() + if (this.form.linkType !== 'url' || !/^https?:\/\//i.test(value)) { + this.panelRefusal = '' + return + } + const result = await validateIframeUrl({ url: value }) + if (String(this.form.linkValue || '').trim() !== value) { + return + } + if (result.valid === false) { + this.panelRefusal = t('launchpad', 'This address cannot open in the panel.') + if (this.form.linkTarget === SIDE_PANEL) { + this.form.linkTarget = '' + } + } else { + this.panelRefusal = '' + } + }, + + /** + * Emit the tile, with the group's sort order when the tile is in a group. + * + * @return {void} + * @spec openspec/specs/tiles/spec.md + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ saveTile() { - this.$emit('save', { + const tile = { ...this.form, expectedStatus: Number(this.form.expectedStatus) || DEFAULT_EXPECTED_STATUS, + pingInterval: this.clampPingInterval(this.form.pingInterval), - }) + } + // REQ-TILE-041: the group's order travels with the save, for the group. + if (this.groupName) { + tile.groupSortBy = this.groupSortBy + } + this.$emit('save', tile) }, }, } @@ -450,6 +1132,59 @@ export default { <style scoped> .tile-editor { padding: 20px; + max-width: 640px; + box-sizing: border-box; +} + +.tile-editor__heading { + margin-bottom: 2px !important; +} + +.tile-editor__where { + margin: 0 0 16px; + color: var(--color-text-maxcontrast); +} + +.tile-editor__label { + font-weight: 600; + font-size: 14px; +} + +.tile-editor__icon-row { + display: flex; + align-items: center; + gap: 16px; +} + +.tile-editor__icon-actions { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 8px; +} + +.tile-editor__file { + display: none; +} + +.tile-editor__last-check { + margin: 0; +} + +.tile-editor__opens-in { + display: flex; + flex-direction: column; + gap: 4px; +} + +.tile-editor__fieldset { + border: none; + margin: 0; + padding: 0; +} + +.tile-editor__fieldset legend { + font-weight: bold; } .tile-editor h2 { @@ -457,10 +1192,51 @@ export default { margin-bottom: 20px; } -.tile-editor__preview { +.tile-editor__swatches { display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; + margin-bottom: 8px; +} + +.tile-editor__swatch { + position: relative; + display: inline-flex; + align-items: center; justify-content: center; - margin-bottom: 30px; + width: 36px; + height: 36px; + border: 2px solid transparent; + border-radius: var(--border-radius-large); + color: #ffffff; + font-weight: 700; + cursor: pointer; +} + +.tile-editor__swatch--on { + outline: 2px solid var(--color-main-text); + outline-offset: 2px; +} + +.tile-editor__swatch:focus-within { + outline: 2px solid var(--color-primary-element); + outline-offset: 2px; +} + +.tile-editor__swatch-input { + position: absolute; + inset: 0; + margin: 0; + opacity: 0; + cursor: pointer; +} + +.tile-editor__swatch-own { + display: inline-flex; + gap: 6px; + align-items: center; + margin-inline-start: 8px; } .tile-preview { @@ -468,8 +1244,9 @@ export default { flex-direction: column; align-items: center; justify-content: center; - width: 120px; - height: 120px; + flex: 0 0 auto; + width: 96px; + height: 96px; border-radius: var(--border-radius-large); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); padding: 12px; @@ -559,6 +1336,12 @@ export default { color: var(--color-warning-text, var(--color-text-maxcontrast)); } +.tile-editor__hint { + margin: 4px 0 0; + font-size: 13px; + color: var(--color-text-maxcontrast); +} + .tile-editor__hint-small { margin: -4px 0 0; font-size: 12px; diff --git a/src/modals/VersionHistoryModal.vue b/src/modals/VersionHistoryModal.vue deleted file mode 100644 index 74073762f..000000000 --- a/src/modals/VersionHistoryModal.vue +++ /dev/null @@ -1,352 +0,0 @@ -<!-- - - SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - - SPDX-License-Identifier: EUPL-1.2 ---> - -<template> - <NcModal - v-if="open" - size="normal" - :name="t('launchpad', 'Version history')" - @close="$emit('close')"> - <div class="launchpad-versions" data-testid="version-history"> - <h2>{{ t('launchpad', 'Version history') }}</h2> - - <div v-if="loading" class="launchpad-versions__loading"> - <NcLoadingIcon :size="32" /> - </div> - - <p - v-else-if="error" - class="launchpad-versions__error" - role="alert" - data-testid="version-error"> - {{ error }} - </p> - - <p v-else-if="!modeSupported" data-testid="version-unsupported"> - {{ - t( - 'launchpad', - 'This dashboard is stored in a way that does not keep versions.', - ) - }} - </p> - - <template v-else> - <div class="launchpad-versions__save"> - <NcTextField - v-model="note" - :label=" - t('launchpad', 'Note for this version (optional)') - " /> - <NcButton - variant="secondary" - :disabled="saving" - data-testid="version-save" - @click="saveVersion"> - {{ t('launchpad', 'Save this version now') }} - </NcButton> - </div> - - <p v-if="sortedVersions.length === 0"> - {{ t('launchpad', 'No versions saved yet.') }} - </p> - <table v-else class="launchpad-versions__table"> - <thead> - <tr> - <th scope="col"> - {{ t('launchpad', 'Version') }} - </th> - <th scope="col"> - {{ t('launchpad', 'Saved on') }} - </th> - <th scope="col"> - {{ t('launchpad', 'By') }} - </th> - <th scope="col"> - {{ t('launchpad', 'Note') }} - </th> - <th scope="col"> - <span class="hidden-visually">{{ - t('launchpad', 'Actions') - }}</span> - </th> - </tr> - </thead> - <tbody> - <tr - v-for="version in sortedVersions" - :key="version.versionNumber" - data-testid="version-row"> - <td>{{ version.versionNumber }}</td> - <td>{{ formatDate(version.createdAt) }}</td> - <td>{{ version.createdBy }}</td> - <td>{{ noteLabel(version.note) }}</td> - <td> - <NcButton - variant="tertiary" - data-testid="version-restore" - @click="askRestore(version)"> - {{ t('launchpad', 'Restore') }} - </NcButton> - </td> - </tr> - </tbody> - </table> - </template> - </div> - - <RestoreVersionDialog - :open="restoreTarget !== null" - :date="restoreTarget ? formatDate(restoreTarget.createdAt) : ''" - @update:open="onRestoreDialog" - @confirm="confirmRestore" /> - </NcModal> -</template> - -<script> -import { - NcButton, - NcLoadingIcon, - NcModal, - NcTextField, -} from '@conduction/nextcloud-vue' -import { t } from '@nextcloud/l10n' -import RestoreVersionDialog from '../dialogs/RestoreVersionDialog.vue' -import { api } from '../services/api.js' - -/** - * VersionHistoryModal: the saved versions of one dashboard, newest first, - * with "Save this version now" and a confirmed restore. After a restore the - * list is read again, so the `pre-restore` version that makes the restore - * reversible shows at the top, and `restored` tells the page to reload. - * - * @spec openspec/specs/dashboard-versioning/spec.md - */ -export default { - name: 'VersionHistoryModal', - - components: { - NcButton, - NcLoadingIcon, - NcModal, - NcTextField, - RestoreVersionDialog, - }, - - props: { - open: { - type: Boolean, - required: true, - }, - - dashboardUuid: { - type: String, - default: '', - }, - }, - - emits: ['close', 'restored'], - - /** @spec openspec/specs/dashboard-versioning/spec.md */ - data() { - return { - versions: [], - modeSupported: true, - loading: false, - saving: false, - error: '', - note: '', - restoreTarget: null, - } - }, - - computed: { - /** - * @return {Array<object>} Versions, newest first. - * @spec openspec/specs/dashboard-versioning/spec.md - */ - sortedVersions() { - return [...this.versions].sort( - (a, b) => b.versionNumber - a.versionNumber, - ) - }, - }, - - watch: { - open: { - immediate: true, - /** - * Read the list each time the dialog opens. - * - * @param {boolean} isOpen New open state. - * @spec openspec/specs/dashboard-versioning/spec.md - */ - handler(isOpen) { - if (isOpen && this.dashboardUuid) { - this.load() - } - }, - }, - }, - - methods: { - t, - - /** - * Read the version list. - * - * @return {Promise<void>} - * @spec openspec/specs/dashboard-versioning/spec.md - */ - async load() { - this.loading = true - this.error = '' - try { - const { data } = await api.listVersions(this.dashboardUuid) - this.versions = Array.isArray(data?.versions) ? data.versions : [] - this.modeSupported = data?.modeSupported !== false - } catch { - this.error = t( - 'launchpad', - 'The version history could not be loaded.', - ) - } finally { - this.loading = false - } - }, - - /** - * Save the dashboard as it is now, with the typed note. - * - * @return {Promise<void>} - * @spec openspec/specs/dashboard-versioning/spec.md - */ - async saveVersion() { - this.saving = true - this.error = '' - try { - const note = this.note.trim() === '' ? null : this.note.trim() - const { data } = await api.createVersion(this.dashboardUuid, note) - if (data?.version) { - this.versions = [data.version, ...this.versions] - } - this.note = '' - } catch { - this.error = t('launchpad', 'The version could not be saved.') - } finally { - this.saving = false - } - }, - - /** - * Open the confirmation for one version. - * - * @param {object} version The version row. - * @spec openspec/specs/dashboard-versioning/spec.md - */ - askRestore(version) { - this.restoreTarget = version - }, - - /** - * The confirmation closed without confirming. - * - * @param {boolean} isOpen New open state. - * @spec openspec/specs/dashboard-versioning/spec.md - */ - onRestoreDialog(isOpen) { - if (!isOpen) { - this.restoreTarget = null - } - }, - - /** - * Restore the chosen version, read the list again and tell the page. - * - * @return {Promise<void>} - * @spec openspec/specs/dashboard-versioning/spec.md - */ - async confirmRestore() { - const target = this.restoreTarget - this.restoreTarget = null - if (!target) { - return - } - try { - await api.restoreVersion(this.dashboardUuid, target.versionNumber) - } catch { - this.error = t('launchpad', 'The version could not be restored.') - return - } - this.$emit('restored', target) - await this.load() - }, - - /** - * Show a stored `Y-m-d H:i:s` timestamp in the viewer's locale. - * - * @param {string} value Timestamp from the server. - * @return {string} Formatted date and time, or the raw value. - * @spec openspec/specs/dashboard-versioning/spec.md - */ - formatDate(value) { - if (!value) { - return '' - } - const parsed = new Date(String(value).replace(' ', 'T')) - if (Number.isNaN(parsed.getTime())) { - return String(value) - } - return parsed.toLocaleString(undefined, { - dateStyle: 'medium', - timeStyle: 'short', - }) - }, - - /** - * The note column; the automatic safety copy gets a readable label. - * - * @param {string|null} note Stored note. - * @return {string} Text for the note column. - * @spec openspec/specs/dashboard-versioning/spec.md - */ - noteLabel(note) { - if (note === 'pre-restore') { - return t('launchpad', 'Saved automatically before a restore') - } - return note ?? '' - }, - }, -} -</script> - -<style scoped> -.launchpad-versions { - padding: 16px; -} - -.launchpad-versions__save { - display: flex; - gap: 8px; - align-items: flex-end; - margin-bottom: 16px; -} - -.launchpad-versions__table { - width: 100%; - border-collapse: collapse; -} - -.launchpad-versions__table th, -.launchpad-versions__table td { - padding: 4px 8px; - text-align: start; - border-bottom: 1px solid var(--color-border); -} - -.launchpad-versions__error { - color: var(--color-error-text); -} -</style> diff --git a/src/modals/VisibilityRulesModal.vue b/src/modals/VisibilityRulesModal.vue index 3b1ff5480..29921d9ac 100644 --- a/src/modals/VisibilityRulesModal.vue +++ b/src/modals/VisibilityRulesModal.vue @@ -6,21 +6,30 @@ <template> <NcModal v-if="open" + class="launchpad-modal" size="normal" - :name="t('launchpad', 'Visibility rules')" + :name="t('launchpad', 'Who sees this widget?')" @close="$emit('close')"> <div class="visibility-rules" data-test="visibility-rules-modal"> - <h2 class="visibility-rules__title"> - {{ t('launchpad', 'Visibility rules') }} + <h2 class="visibility-rules__title" data-test="visibility-rules-title"> + {{ t('launchpad', 'Who sees this widget?') }} </h2> + <p + v-if="subtitle" + class="visibility-rules__subtitle" + data-test="visibility-rules-subtitle"> + {{ subtitle }} + </p> <ConditionalVisibilityEditor :placementId="placementId" - :availableGroups="availableGroups" + :availableGroups="offeredGroups" + :ruleMatch="ruleMatch" data-test="conditional-visibility-editor" @ruleAdded="$emit('ruleAdded')" @ruleUpdated="$emit('ruleUpdated')" - @ruleRemoved="$emit('ruleRemoved')" /> + @ruleRemoved="$emit('ruleRemoved')" + @ruleMatchChanged="$emit('ruleMatchChanged', $event)" /> </div> </NcModal> </template> @@ -29,12 +38,16 @@ import { NcModal } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' import ConditionalVisibilityEditor from '../components/Widgets/ConditionalVisibilityEditor.vue' +import { FLAG_PROP, LIST_PROP } from '../constants/propDefinitions.js' +import { api } from '../services/api.js' /** - * VisibilityRulesModal — the placement's "Visibility" settings surface - * (conditional-visibility-editor spec, REQ-CVUI-001). Opens from the widget - * context menu and hosts `ConditionalVisibilityEditor` as its single - * section body; all rule builder/list/preview behaviour lives there. + * VisibilityRulesModal — "Who sees this widget?" (board LpZichtbaarheid, + * conditional-visibility-editor REQ-CVUI-001 and REQ-CVUI-006). Titled with + * the widget and the dashboard under it; opens from the widget's menu and + * its right-click menu in edit mode, and hosts `ConditionalVisibilityEditor` + * as its single section body; all rule builder/list/preview behaviour lives + * there. */ export default { name: 'VisibilityRulesModal', @@ -52,22 +65,96 @@ export default { }, /** Whether the modal is shown. */ - open: { - type: Boolean, - default: false, - }, + open: FLAG_PROP, /** Optional group-id list for the group-rule picker. */ - availableGroups: { - type: Array, - default: () => [], + availableGroups: LIST_PROP, + + /** The widget's title, shown under the dialog title. */ + widgetTitle: { + type: String, + default: '', + }, + + /** The dashboard's name, shown after the widget's title. */ + dashboardName: { + type: String, + default: '', + }, + + /** How the widget's include rules combine: `any` or `all`. */ + ruleMatch: { + type: String, + default: 'any', + }, + }, + + emits: ['close', 'ruleAdded', 'ruleUpdated', 'ruleRemoved', 'ruleMatchChanged'], + + data() { + return { + loadedGroups: [], + } + }, + + computed: { + /** + * The line under the title: "<widget> · <dashboard>", or whichever + * of the two is known. + * + * @return {string} the line, empty when neither is known. + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + subtitle() { + return [this.widgetTitle, this.dashboardName].filter((part) => part).join(' · ') + }, + + /** + * The groups the pickers offer: the passed list, else the instance's groups. + * + * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-002-per-rule-row-editor-for-all-four-rule-types + */ + offeredGroups() { + return this.availableGroups.length > 0 ? this.availableGroups : this.loadedGroups }, }, - emits: ['close', 'ruleAdded', 'ruleUpdated', 'ruleRemoved'], + watch: { + open: { + immediate: true, + /** + * Read the groups on opening when none were passed. + * + * @param {boolean} isOpen whether the modal is shown. + * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-002-per-rule-row-editor-for-all-four-rule-types + */ + handler(isOpen) { + if (isOpen && this.availableGroups.length === 0) { + this.loadGroups() + } + }, + }, + }, methods: { t, + + /** + * Read every Nextcloud group as `{id, displayName}`. The list is + * admin-only; anyone else keeps an empty list, and a stored rule + * still shows the groups it names. + * + * @spec openspec/specs/conditional-visibility-editor/spec.md#requirement-req-cvui-002-per-rule-row-editor-for-all-four-rule-types + */ + async loadGroups() { + try { + const res = await api.getAdminGroups() + const allKnown = res?.data?.allKnown + this.loadedGroups = Array.isArray(allKnown) ? allKnown : [] + } catch { + this.loadedGroups = [] + } + }, }, } </script> @@ -78,6 +165,11 @@ export default { } .visibility-rules__title { - margin: 0 0 8px; + margin: 0 0 4px; +} + +.visibility-rules__subtitle { + margin: 0 0 16px; + color: var(--color-text-maxcontrast); } </style> diff --git a/src/modals/WidgetMovePanel.vue b/src/modals/WidgetMovePanel.vue index 7efeb22f7..e362cbe9c 100644 --- a/src/modals/WidgetMovePanel.vue +++ b/src/modals/WidgetMovePanel.vue @@ -6,6 +6,7 @@ <template> <NcModal v-if="open" + class="launchpad-modal" size="small" :name="t('launchpad', 'Move widget')" @close="onCancel"> @@ -125,6 +126,11 @@ import { NcButton, NcModal } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' import { nudgePlacement } from '../composables/useGridManager.js' +import { + FLAG_PROP, + LIST_PROP, + NULLABLE_OBJECT_PROP, +} from '../constants/propDefinitions.js' /** * WidgetMovePanel — keyboard-operable move/resize panel for a dashboard @@ -162,20 +168,11 @@ export default { }, props: { - open: { - type: Boolean, - default: false, - }, + open: FLAG_PROP, - placement: { - type: Object, - default: null, - }, + placement: NULLABLE_OBJECT_PROP, - allPlacements: { - type: Array, - default: () => [], - }, + allPlacements: LIST_PROP, gridColumns: { type: Number, @@ -217,18 +214,25 @@ export default { * @param {boolean} isOpen Whether the panel is now open. * @spec openspec/specs/grid-layout/spec.md */ - open(isOpen) { - if (isOpen) { - this.working = this.initialRect() - this.$nextTick(() => { - if ( - this.$refs.panel - && typeof this.$refs.panel.focus === 'function' - ) { - this.$refs.panel.focus() - } - }) - } + open: { + immediate: true, + /** + * @spec openspec/specs/grid-layout/spec.md + * @param {boolean} isOpen Whether the panel is now open. + */ + handler(isOpen) { + if (isOpen) { + this.working = this.initialRect() + this.$nextTick(() => { + if ( + this.$refs.panel + && typeof this.$refs.panel.focus === 'function' + ) { + this.$refs.panel.focus() + } + }) + } + }, }, /** @spec openspec/specs/grid-layout/spec.md */ @@ -267,6 +271,7 @@ export default { apply(action) { const base = { id: this.placement ? this.placement.id : undefined, + widgetId: this.placement ? this.placement.widgetId : undefined, gridX: this.working.gridX, gridY: this.working.gridY, gridWidth: this.working.gridWidth, diff --git a/src/modals/WidgetPickerModal.vue b/src/modals/WidgetPickerModal.vue index 4480d9d11..4ea5d0262 100644 --- a/src/modals/WidgetPickerModal.vue +++ b/src/modals/WidgetPickerModal.vue @@ -4,15 +4,26 @@ --> <template> + <!-- widget-picker-board-sync REQ-WDG-040: one 720 px dialog, titled with + the dashboard over "Add widget": the search, the kinds and, to their + right, the cards in two columns under three headings; Cancel and + Add widget at the foot. A card is chosen by a click and placed with + Add widget. --> <NcModal v-if="open" - size="normal" + class="launchpad-modal widget-picker-modal" + size="large" :name="t('launchpad', 'Add widget')" @close="$emit('close')"> <div class="widget-picker"> - <h2 class="widget-picker__title"> - {{ t('launchpad', 'Add widget') }} - </h2> + <div class="widget-picker__heading"> + <p v-if="dashboardName" class="widget-picker__dashboard"> + {{ dashboardName }} + </p> + <h2 class="widget-picker__title"> + {{ t('launchpad', 'Add widget') }} + </h2> + </div> <div class="widget-picker__search"> <NcTextField @@ -28,165 +39,521 @@ </NcTextField> </div> - <div class="widget-picker__list"> - <button - v-for="widget in filteredWidgets" - :key="widget.id" - class="widget-picker__widget" - :class="{ 'widget-picker__widget--placed': isPlaced(widget.id) }" - @click="addWidget(widget)"> - <img - v-if="widget.iconUrl" - :src="widget.iconUrl" - :alt="widget.title" - class="widget-picker__widget-icon" /> - <span - v-else-if="widget.iconClass" - :class="widget.iconClass" - class="widget-picker__widget-icon" /> - <div class="widget-picker__widget-info"> - <span class="widget-picker__widget-title">{{ - widget.title - }}</span> - <span - v-if="isPlaced(widget.id)" - class="widget-picker__widget-badge"> - {{ t('launchpad', 'Already added') }} - </span> - </div> - <Plus - v-if="!isPlaced(widget.id)" - :size="20" - class="widget-picker__widget-action" /> - <Check - v-else - :size="20" - class="widget-picker__widget-action widget-picker__widget-action--check" /> - </button> - - <NcEmptyContent - v-if="filteredWidgets.length === 0" - :description="t('launchpad', 'No widgets found')"> - <template #icon> - <Magnify :size="48" /> - </template> - </NcEmptyContent> + <div class="widget-picker__body"> + <!-- REQ-WDG-041: the kinds, each with its count. --> + <nav class="widget-picker__kinds" :aria-label="t('launchpad', 'Kinds of widget')"> + <button + v-for="kind in kinds" + :key="kind" + type="button" + class="widget-picker__kind" + :class="{ 'widget-picker__kind--chosen': chosenKind === kind }" + :aria-pressed="chosenKind === kind ? 'true' : 'false'" + :data-testid="`widget-picker-kind-${kind}`" + @click="chosenKind = kind"> + <span class="widget-picker__kind-label">{{ kindLabel(kind) }}</span> <span class="widget-picker__kind-count">{{ counts[kind] }}</span> + </button> + </nav> + + <div class="widget-picker__list"> + <section + v-for="section in visibleSections" + :key="section.id" + class="widget-picker__section" + :data-testid="`widget-picker-section-${section.id}`"> + <h3 class="widget-picker__section-title"> + {{ section.label }} + </h3> + <div class="widget-picker__grid"> + <button + v-for="card in section.cards" + :key="card.key" + type="button" + class="widget-picker__widget" + :class="{ + 'widget-picker__widget--chosen': chosenKey === card.key, + 'widget-picker__widget--disabled': card.disabled, + }" + :aria-pressed="chosenKey === card.key ? 'true' : 'false'" + :aria-disabled="card.disabled ? 'true' : 'false'" + :data-testid="card.testid" + @click="choose(card)" + @dblclick="place(card)"> + <span + v-if="card.icon.kind === 'tile' || card.icon.kind === 'own'" + class="widget-picker__widget-icon widget-picker__tile-swatch" + :class="{ 'widget-picker__tile-swatch--own': card.icon.kind === 'own' }" + :style="card.icon.kind === 'tile' ? { '--widget-picker-tile-colour': tileColour(card.icon.appId) } : {}" + aria-hidden="true"> + <Plus v-if="card.icon.kind === 'own'" :size="18" /> + <img + v-else-if="card.icon.url" + :src="card.icon.url" + alt="" + class="widget-picker__tile-image"> + <span + v-else-if="card.icon.className" + :class="card.icon.className" + class="widget-picker__tile-image" /> + <span + v-else-if="card.icon.mask" + class="widget-picker__tile-glyph" + :style="{ '--widget-picker-tile-icon': `url("${card.icon.mask}")` }" /> + </span> + <img + v-else-if="card.icon.url" + :src="card.icon.url" + alt="" + class="widget-picker__widget-icon"> + <span + v-else-if="card.icon.className" + :class="card.icon.className" + class="widget-picker__widget-icon" + aria-hidden="true" /> + <ViewDashboardOutline + v-else + :size="24" + class="widget-picker__widget-icon widget-picker__widget-icon--type" /> + <span class="widget-picker__widget-info"> + <span class="widget-picker__widget-title">{{ card.title }}</span> + <span class="widget-picker__widget-line">{{ card.line }}</span> + <span v-if="card.disabled" class="widget-picker__widget-badge widget-picker__widget-badge--refused"> + {{ t('launchpad', 'Not allowed for your role') }} + </span> + <span v-else-if="card.legacy" class="widget-picker__widget-badge"> + {{ t('launchpad', 'Older widget type') }} + </span> + <span v-if="card.badge" class="widget-picker__widget-badge"> + {{ card.badge }} + </span> + </span> + <Check + v-if="chosenKey === card.key" + :size="20" + class="widget-picker__widget-action widget-picker__widget-action--check" /> + </button> + </div> + </section> + + <NcEmptyContent + v-if="visibleSections.length === 0" + :description="t('launchpad', 'No widgets found')"> + <template #icon> + <Magnify :size="48" /> + </template> + </NcEmptyContent> + + <section + v-if="requestAppFn" + class="widget-picker__section widget-picker__section--request" + data-testid="widget-picker-request"> + <NcButton + v-if="!requestFormOpen" + variant="tertiary" + @click="openRequestForm"> + {{ t('launchpad', 'Can\'t find your app?') }} + </NcButton> + <form + v-else + class="widget-picker__request" + :aria-label="t('launchpad', 'Ask IT for an app')" + @submit.prevent="submitRequest"> + <h4 class="widget-picker__request-title"> + {{ t('launchpad', 'Ask IT for an app') }} + </h4> + <NcTextField + v-model="requestAppName" + :label="t('launchpad', 'App name')" + :required="true" /> + <NcTextField + v-model="requestPurpose" + :label="t('launchpad', 'What do you need it for?')" /> + <p + v-if="requestMessage" + class="widget-picker__request-message" + :class="{ 'widget-picker__request-message--error': requestFailed }" + role="status"> + {{ requestMessage }} + </p> + <div class="widget-picker__request-actions"> + <NcButton + variant="primary" + type="submit" + :disabled="requestBusy || requestAppName.trim() === ''"> + {{ t('launchpad', 'Send request') }} + </NcButton> + <NcButton variant="tertiary" @click="closeRequestForm"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + </div> + </form> + </section> + </div> + </div> + + <div class="widget-picker__actions"> + <NcButton data-testid="widget-picker-cancel" @click="$emit('close')"> + {{ t('launchpad', 'Cancel') }} + </NcButton> + <NcButton + variant="primary" + data-testid="widget-picker-add" + :disabled="!chosenCard" + @click="place(chosenCard)"> + {{ t('launchpad', 'Add widget') }} + </NcButton> </div> </div> </NcModal> </template> <script> +import { appTileColourValue } from '@conduction/nextcloud-vue' import { t } from '@nextcloud/l10n' -import { NcEmptyContent, NcModal, NcTextField } from '@nextcloud/vue' +import { NcButton, NcEmptyContent, NcModal, NcTextField } from '@nextcloud/vue' import Check from 'vue-material-design-icons/Check.vue' import Magnify from 'vue-material-design-icons/Magnify.vue' import Plus from 'vue-material-design-icons/Plus.vue' +import ViewDashboardOutline from 'vue-material-design-icons/ViewDashboardOutline.vue' +import { FLAG_PROP, LIST_PROP, TEXT_PROP } from '../constants/propDefinitions.js' +import { countByKind, filterCards, kindLabel, KINDS, pickerCards, sectionLabel, SECTIONS } from '../utils/widgetPickerCards.js' +/** + * WidgetPickerModal — "Add widget" as board LpWidgetKiezen draws it + * (widget-picker-board-sync): the search, the kinds with their counts, the + * cards in two columns under "Widgets from Launchpad", "App tiles" and + * "From other Nextcloud apps", a grey card for what the role may not add and + * Cancel and Add widget at the foot. Each card still places through the + * event it always did (`add`, `addCustom`, `addApp`, `addCatalogueApp`, + * `addOfficePack`), now when Add widget is pressed. + * + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md + * @spec openspec/specs/widgets/spec.md#requirement-widget-picker-req-wdg-010 + */ export default { name: 'WidgetPickerModal', components: { + NcButton, NcModal, NcTextField, NcEmptyContent, Magnify, Plus, Check, + ViewDashboardOutline, }, props: { - open: { - type: Boolean, - default: false, - }, + open: FLAG_PROP, widgets: { type: Array, required: true, }, - placedWidgetIds: { + placedWidgetIds: LIST_PROP, + + /** + * The apps this server runs for the user (`GET /api/tiles/discover`): + * `[{ appId, name, href, icon }]`. + */ + discoveredApps: LIST_PROP, + + /** The discovered app ids already on the dashboard. */ + placedAppIds: LIST_PROP, + + /** + * The widget types Launchpad builds itself (text, image, news and + * more): `[{ type, title }]`. Picking one opens its form on that type. + */ + customTypes: LIST_PROP, + + /** + * The app catalogue entries the user's groups may see + * (`GET /api/catalogue`): `[{ uuid, name, description, icon, iconType, linkType, linkValue }]`. + */ + catalogueApps: LIST_PROP, + + /** The dashboard the widget goes on, shown over the title. */ + dashboardName: TEXT_PROP, + + /** + * The widget ids the viewer's role may add (initial state + * `allowedWidgets`, REQ-RFP-010); `null` for no restriction. + */ + allowedWidgets: { type: Array, - default: () => [], + default: null, + }, + + /** + * Sends a request for a missing app: `({ appName, purpose }) => Promise`. + * Without it the "Can't find your app?" form is not offered. + */ + requestAppFn: { + type: Function, + default: null, }, }, - emits: ['close', 'add'], + emits: ['close', 'add', 'addApp', 'addCatalogueApp', 'addCustom', 'addOfficePack'], data() { return { searchQuery: '', + chosenKind: 'all', + chosenKey: '', + requestFormOpen: false, + requestAppName: '', + requestPurpose: '', + requestBusy: false, + requestMessage: '', + requestFailed: false, } }, computed: { - /** @spec openspec/specs/widgets/spec.md */ - filteredWidgets() { - if (!this.searchQuery) { - return this.sortedWidgets - } - const query = this.searchQuery.toLowerCase() - return this.sortedWidgets.filter((w) => - w.title.toLowerCase().includes(query), - ) + /** + * The kinds in the column. + * + * @return {Array<string>} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-kinds-with-counts-req-wdg-041 + */ + kinds() { + return KINDS }, - /** @spec openspec/specs/widgets/spec.md */ - sortedWidgets() { - return [...this.widgets].sort((a, b) => { - const aPlaced = this.isPlaced(a.id) - const bPlaced = this.isPlaced(b.id) - if (aPlaced !== bPlaced) { - return aPlaced ? 1 : -1 - } - return (a.order || 0) - (b.order || 0) - }) + /** + * Every card the picker offers. + * + * @return {Array<object>} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md + */ + cards() { + return pickerCards({ + customTypes: this.customTypes, + officePack: true, + catalogueApps: this.catalogueApps, + discoveredApps: this.discoveredApps, + widgets: this.widgets, + allowedWidgets: this.allowedWidgets, + placedWidgetIds: this.placedWidgetIds, + placedAppIds: this.placedAppIds, + }, t) + }, + + /** + * The number of cards per kind. + * + * @return {Record<string, number>} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-kinds-with-counts-req-wdg-041 + */ + counts() { + return countByKind(this.cards) + }, + + /** + * The cards of the chosen kind that match the search. + * + * @return {Array<object>} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-kinds-with-counts-req-wdg-041 + */ + filteredCards() { + return filterCards(this.cards, this.chosenKind, this.searchQuery) + }, + + /** + * The sections that have a card to show, in board order. + * + * @return {Array<{id: string, label: string, cards: Array<object>}>} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-the-widget-picker-as-lpwidgetkiezen-draws-it-req-wdg-040 + */ + visibleSections() { + return SECTIONS + .map((id) => ({ id, label: sectionLabel(id, t), cards: this.filteredCards.filter((card) => card.section === id) })) + .filter((section) => section.cards.length > 0) + }, + + /** + * The chosen card, while it is still shown and allowed. + * + * @return {object|null} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-the-widget-picker-as-lpwidgetkiezen-draws-it-req-wdg-040 + */ + chosenCard() { + return this.filteredCards.find((card) => card.key === this.chosenKey && !card.disabled) ?? null }, }, watch: { /** - * Clear the search box when the picker closes, so the next open - * starts from the full widget list. + * Clear the search, the kind and the choice when the picker closes, + * so the next open starts from every widget. * * @param {boolean} isOpen Whether the picker is now open. * @spec openspec/specs/widgets/spec.md + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-kinds-with-counts-req-wdg-041 */ open(isOpen) { if (!isOpen) { this.searchQuery = '' + this.chosenKind = 'all' + this.chosenKey = '' + this.closeRequestForm() } }, }, methods: { t, - isPlaced(widgetId) { - return this.placedWidgetIds.includes(widgetId) + + /** + * The column's label of a kind. + * + * @param {string} kind The kind. + * @return {string} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-kinds-with-counts-req-wdg-041 + */ + kindLabel(kind) { + return kindLabel(kind, t) }, /** - * Ask the host to place the chosen widget. + * The colour an app's tile gets when placed, for its card. * - * @param {object} widget The picked widget definition; only `id` is - * forwarded. - * @spec openspec/specs/widgets/spec.md + * @param {string} appId The app id. + * @return {string} A CSS colour value. + * @spec openspec/changes/app-tile-widget/specs/app-tile-widget/spec.md#requirement-the-add-flow-offers-every-app-as-its-own-tile-req-apptile-001 */ - addWidget(widget) { - this.$emit('add', widget.id) + tileColour(appId) { + return appTileColourValue('', appId) + }, + + /** + * Choose a card; a card the role may not add cannot be chosen. + * + * @param {object} card The card. + * @return {void} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-widgets-the-role-may-not-add-req-wdg-043 + */ + choose(card) { + if (card.disabled) { + return + } + this.chosenKey = card.key + }, + + /** + * Place a card through its own event. The picker closes after a + * Nextcloud widget or an app tile; for a Launchpad type or the office + * pack the host opens the form or closes it itself. + * + * @param {object|null} card The card. + * @return {void} + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-the-widget-picker-as-lpwidgetkiezen-draws-it-req-wdg-040 + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-app-tiles-in-the-picker-req-wdg-042 + */ + place(card) { + if (!card || card.disabled) { + return + } + const { event, arg } = card.action + if (arg === undefined) { + this.$emit(event) + } else { + this.$emit(event, arg) + } + this.chosenKey = '' + if (event === 'add' || event === 'addApp' || event === 'addCatalogueApp') { + this.$emit('close') + } + }, + + /** + * Open the request form, starting from what the user searched for. + * + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-users-can-ask-for-a-missing-app-req-acat-003 + */ + openRequestForm() { + this.requestFormOpen = true + this.requestAppName = this.searchQuery.trim() + this.requestPurpose = '' + this.requestMessage = '' + this.requestFailed = false + }, + + /** + * Close the request form and forget what was typed. + * + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-users-can-ask-for-a-missing-app-req-acat-003 + */ + closeRequestForm() { + this.requestFormOpen = false + this.requestAppName = '' + this.requestPurpose = '' + this.requestMessage = '' + this.requestFailed = false + }, + + /** + * Send the request and say how it went: sent, refused because the + * user has too many open requests, or not sent. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-users-can-ask-for-a-missing-app-req-acat-003 + */ + async submitRequest() { + const appName = this.requestAppName.trim() + if (appName === '' || this.requestBusy) { + return + } + this.requestBusy = true + this.requestMessage = '' + try { + await this.requestAppFn({ appName, purpose: this.requestPurpose.trim() }) + this.requestFailed = false + this.requestMessage = t('launchpad', 'Your request was sent to IT') + this.requestAppName = '' + this.requestPurpose = '' + } catch (error) { + this.requestFailed = true + this.requestMessage = error?.response?.data?.code === 'request_limit' + ? t('launchpad', 'You have 10 open requests. Wait for an answer first.') + : t('launchpad', 'Your request could not be sent. Try again later.') + } finally { + this.requestBusy = false + } }, }, } </script> <style scoped> +/* REQ-WDG-040: the dialog is 720 px wide (narrower on a small screen). */ +.widget-picker-modal :deep(.modal-container) { + width: 720px; + max-width: calc(100vw - 32px); +} + .widget-picker { padding: 24px; display: flex; flex-direction: column; gap: 16px; max-height: 80vh; + box-sizing: border-box; +} + +.widget-picker__heading { + display: flex; + flex-direction: column; + gap: 2px; +} + +.widget-picker__dashboard { + margin: 0; + color: var(--color-text-maxcontrast); } .widget-picker__title { @@ -199,35 +566,126 @@ export default { flex-shrink: 0; } +.widget-picker__body { + flex: 1; + min-height: 0; + display: flex; + gap: 16px; +} + +.widget-picker__kinds { + flex: 0 0 168px; + display: flex; + flex-direction: column; + gap: 2px; + overflow-y: auto; +} + +.widget-picker__kind { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; + padding: 8px 10px; + border: none; + border-radius: var(--border-radius-large); + background: transparent; + color: var(--color-main-text); + text-align: start; + cursor: pointer; +} + +.widget-picker__kind:hover, +.widget-picker__kind:focus-visible { + background: var(--color-background-hover); +} + +.widget-picker__kind--chosen { + background: var(--color-primary-element-light); + font-weight: 600; +} + +.widget-picker__kind-count { + color: var(--color-text-maxcontrast); + font-variant-numeric: tabular-nums; +} + .widget-picker__list { flex: 1; + min-width: 0; overflow-y: auto; display: flex; flex-direction: column; - gap: 4px; + gap: 16px; +} + +.widget-picker__section { + display: flex; + flex-direction: column; + gap: 8px; +} + +.widget-picker__section-title { + margin: 0; + font-size: 16px; + font-weight: 600; +} + +.widget-picker__grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} + +@media (max-width: 600px) { + .widget-picker__body { + flex-direction: column; + } + + .widget-picker__kinds { + flex: 0 0 auto; + flex-direction: row; + flex-wrap: wrap; + } + + .widget-picker__grid { + grid-template-columns: minmax(0, 1fr); + } } .widget-picker__widget { display: flex; - align-items: center; + align-items: flex-start; gap: 12px; padding: 12px; - border: none; - background: transparent; + border: 2px solid var(--color-border); + background: var(--color-main-background); border-radius: var(--border-radius-large); cursor: pointer; - transition: background var(--animation-quick) ease; - text-align: left; + transition: background var(--animation-quick) ease, border-color var(--animation-quick) ease; + text-align: start; width: 100%; + min-width: 0; } .widget-picker__widget:hover, -.widget-picker__widget:focus { +.widget-picker__widget:focus-visible { background: var(--color-background-hover); } -.widget-picker__widget--placed { - opacity: 0.6; +.widget-picker__widget--chosen { + border-color: var(--color-primary-element); +} + +/* REQ-WDG-043: what the role may not add is a grey card. */ +.widget-picker__widget--disabled { + cursor: not-allowed; + opacity: 0.55; + filter: grayscale(1); +} + +.widget-picker__widget--disabled:hover { + background: var(--color-main-background); } .widget-picker__widget-icon { @@ -236,30 +694,107 @@ export default { flex-shrink: 0; } +.widget-picker__widget-icon--type { + color: var(--color-primary-element); +} + +.widget-picker__tile-swatch { + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: var(--border-radius, 8px); + background-color: var(--widget-picker-tile-colour); + color: #fff; +} + +.widget-picker__tile-swatch--own { + border: 2px dashed var(--color-border-dark); + background-color: transparent; + color: var(--color-main-text); +} + +.widget-picker__tile-image { + width: 55%; + height: 55%; + object-fit: contain; + filter: brightness(0) invert(1); +} + +.widget-picker__tile-glyph { + width: 55%; + height: 55%; + background-color: currentColor; + mask: var(--widget-picker-tile-icon) center / contain no-repeat; + -webkit-mask: var(--widget-picker-tile-icon) center / contain no-repeat; +} + .widget-picker__widget-info { flex: 1; min-width: 0; + display: flex; + flex-direction: column; + gap: 2px; } .widget-picker__widget-title { - display: block; - font-weight: 500; + font-weight: 600; color: var(--color-main-text); + overflow-wrap: anywhere; } +.widget-picker__widget-line, .widget-picker__widget-badge { - display: block; font-size: 12px; color: var(--color-text-maxcontrast); } +.widget-picker__widget-badge--refused { + font-weight: 600; +} + .widget-picker__widget-action { flex-shrink: 0; - color: var(--color-text-maxcontrast); } .widget-picker__widget-action--check { - color: var(--color-success); + color: var(--color-primary-element); +} + +.widget-picker__section--request { + align-items: flex-start; +} + +.widget-picker__request { + display: flex; + flex-direction: column; + gap: 8px; + width: 100%; +} + +.widget-picker__request-title { + margin: 0; + font-weight: 600; +} + +.widget-picker__request-actions { + display: flex; + gap: 8px; +} + +.widget-picker__request-message { + margin: 0; + color: var(--color-success-text); +} + +.widget-picker__request-message--error { + color: var(--color-error-text); +} + +.widget-picker__actions { + display: flex; + justify-content: flex-end; + gap: 8px; + flex-shrink: 0; } /* WCAG 2.2 AA SC 2.3.3 (Animation from Interactions). Honour the OS-level diff --git a/src/modals/__tests__/AcknowledgementReportModal.spec.js b/src/modals/__tests__/AcknowledgementReportModal.spec.js new file mode 100644 index 000000000..a36c10ca3 --- /dev/null +++ b/src/modals/__tests__/AcknowledgementReportModal.spec.js @@ -0,0 +1,157 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `AcknowledgementReportModal.vue`: the read + * confirmations dialog (REQ-ACK-004/006/010) — the heading, the count over + * the audience, the filters, the table with department and status, the + * shown line, Download and Close. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import AcknowledgementReportModal from '../AcknowledgementReportModal.vue' +import { announcementsApi } from '../../services/announcementsApi.js' +import { api } from '../../services/api.js' + +vi.mock('../../services/api.js', () => ({ + api: { + getAcknowledgementReport: vi.fn(), + getAcknowledgementReportCsvUrl: vi.fn((key) => `/csv/${key}`), + }, +})) + +vi.mock('../../services/announcementsApi.js', () => ({ + announcementsApi: { receipts: vi.fn() }, +})) + +const stubs = { + NcModal: { props: ['name'], emits: ['close'], template: '<div class="nc-modal-stub" :data-name="name"><slot /></div>' }, + NcButton: { + props: ['href', 'variant'], + emits: ['click'], + template: '<a v-if="href" :href="href" class="button"><slot /></a><button v-else class="button" :data-variant="variant" @click="$emit(\'click\')"><slot /></button>', + }, + NcLoadingIcon: { template: '<span class="loading-stub" />' }, +} + +const REPORT = { + deadline: '2026-10-30 17:00:00', + overdue: false, + departmentLabel: 'Afdeling', + rows: [ + { userId: 'sanne', displayName: 'Sanne de Vries', department: 'KCC', status: 'acknowledged', acknowledgedAt: '2026-10-13 10:00:00' }, + { userId: 'pieter', displayName: 'Pieter Jansen', department: 'Burgerzaken', status: 'pending', acknowledgedAt: null }, + { userId: 'kees', status: 'pending', acknowledgedAt: null }, + ], +} + +function mountModal(props = {}) { + return mount(AcknowledgementReportModal, { + props: { open: true, announcementKey: 'policy-2026', title: 'New procedure for Woo requests', dashboardName: 'Intranet Zuiddrecht', ...props }, + global: { stubs }, + }) +} + +function cells(wrapper, userId) { + return wrapper.find(`[data-testid="ack-row-${userId}"]`).findAll('td').map((cell) => cell.text()) +} + +beforeEach(() => { + globalThis.t = (_app, key, vars) => key.replace(/\{(\w+)\}/g, (_, name) => (vars && name in vars ? String(vars[name]) : `{${name}}`)) + api.getAcknowledgementReport.mockReset() +}) + +describe('AcknowledgementReportModal', () => { + it('shows the heading, the count over the audience and every row', async () => { + api.getAcknowledgementReport.mockResolvedValue({ data: REPORT }) + const wrapper = mountModal() + expect(wrapper.find('.loading-stub').exists()).toBe(true) + await flushPromises() + + expect(api.getAcknowledgementReport).toHaveBeenCalledWith('policy-2026') + expect(wrapper.find('h2').text()).toBe('Read confirmations: New procedure for Woo requests') + expect(wrapper.find('[data-testid="ack-report-eyebrow"]').text()).toBe('Announcement · Intranet Zuiddrecht') + const summary = wrapper.find('[data-testid="ack-summary"]').text() + expect(summary).toContain('1 of 3 confirmed') + expect(summary).toContain('2 to go') + expect(summary).toContain('deadline ') + expect(wrapper.find('[data-testid="ack-bar"]').attributes('aria-valuenow')).toBe('33') + expect(wrapper.find('thead').text()).toContain('Afdeling') + + expect(cells(wrapper, 'sanne')[0]).toBe('SV Sanne de Vries') + expect(cells(wrapper, 'sanne')[1]).toBe('KCC') + expect(cells(wrapper, 'sanne')[2]).toMatch(/^Confirmed .+/) + expect(cells(wrapper, 'pieter')).toEqual(['PJ Pieter Jansen', 'Burgerzaken', 'Not yet']) + expect(cells(wrapper, 'kees')).toEqual(['K kees', '—', 'Not yet']) + expect(wrapper.find('[data-testid="ack-shown"]').text()).toMatch(/^3 of 3 shown\./) + expect(wrapper.find('[data-testid="acknowledgement-report-csv"]').attributes('href')).toBe('/csv/policy-2026') + }) + + it('filters to who has not confirmed yet and to who has', async () => { + api.getAcknowledgementReport.mockResolvedValue({ data: REPORT }) + const wrapper = mountModal() + await flushPromises() + + await wrapper.find('[data-testid="ack-filter-pending"]').trigger('click') + expect(wrapper.findAll('tbody tr').map((row) => row.attributes('data-testid'))).toEqual(['ack-row-pieter', 'ack-row-kees']) + expect(wrapper.find('[data-testid="ack-filter-pending"]').attributes('data-variant')).toBe('primary') + expect(wrapper.find('[data-testid="ack-shown"]').text()).toMatch(/^2 of 3 shown\./) + + await wrapper.find('[data-testid="ack-filter-confirmed"]').trigger('click') + expect(wrapper.findAll('tbody tr')).toHaveLength(1) + + await wrapper.find('[data-testid="ack-filter-everyone"]').trigger('click') + expect(wrapper.findAll('tbody tr')).toHaveLength(3) + }) + + it('falls back to plain headings and Department without a title or label', async () => { + api.getAcknowledgementReport.mockResolvedValue({ data: { rows: [] } }) + const wrapper = mountModal({ title: '', dashboardName: '' }) + await flushPromises() + expect(wrapper.find('h2').text()).toBe('Read confirmations') + expect(wrapper.find('[data-testid="ack-report-eyebrow"]').text()).toBe('Announcement') + expect(wrapper.find('thead').text()).toContain('Department') + expect(wrapper.find('[data-testid="ack-summary"]').text()).toBe('0 of 0 confirmed · 0 to go') + }) + + it('shows an error and no report when loading fails, and closes', async () => { + api.getAcknowledgementReport.mockRejectedValue(new Error('403')) + const wrapper = mountModal() + await flushPromises() + expect(wrapper.find('[data-testid="acknowledgement-report-error"]').text()).toBe('Could not load the read-receipt report.') + expect(wrapper.find('table').exists()).toBe(false) + expect(wrapper.find('[data-testid="acknowledgement-report-csv"]').exists()).toBe(false) + await wrapper.find('[data-testid="acknowledgement-report-close"]').trigger('click') + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('does not load while closed and reloads for another announcement', async () => { + api.getAcknowledgementReport.mockResolvedValue({ data: REPORT }) + const wrapper = mountModal({ open: false }) + await flushPromises() + expect(api.getAcknowledgementReport).not.toHaveBeenCalled() + await wrapper.setProps({ open: true }) + await flushPromises() + await wrapper.setProps({ announcementKey: 'other' }) + await flushPromises() + expect(api.getAcknowledgementReport).toHaveBeenLastCalledWith('other') + }) + + // @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + it('reads an announcement\'s confirmations from the announcements API, without Download', async () => { + announcementsApi.receipts.mockResolvedValue(REPORT) + const wrapper = mountModal({ announcementKey: '', announcementUuid: 'u-1', dashboardName: '' }) + await flushPromises() + + expect(announcementsApi.receipts).toHaveBeenCalledWith('u-1') + expect(api.getAcknowledgementReport).not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="ack-summary"]').text()).toContain('1 of 3 confirmed') + expect(wrapper.find('[data-testid="acknowledgement-report-csv"]').exists()).toBe(false) + + announcementsApi.receipts.mockResolvedValue({ ...REPORT, rows: [] }) + await wrapper.setProps({ announcementUuid: 'u-2' }) + await flushPromises() + expect(announcementsApi.receipts).toHaveBeenLastCalledWith('u-2') + }) +}) diff --git a/src/modals/__tests__/AddTilesModal.spec.js b/src/modals/__tests__/AddTilesModal.spec.js new file mode 100644 index 000000000..45b095ab8 --- /dev/null +++ b/src/modals/__tests__/AddTilesModal.spec.js @@ -0,0 +1,228 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The Add tiles dialog (add-tiles-dialog REQ-TILE-043, REQ-TILE-044): the four + * sections in board order, counting, adding from each section, no duplicate + * tile, and the hand-over to the bookmark import. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md + */ +import { flushPromises, mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import AddTilesModal from '../AddTilesModal.vue' +import BookmarkImportModal from '../BookmarkImportModal.vue' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, key, vars = {}) => key.replace(/\{(\w+)\}/g, (_m, k) => String(vars[k] ?? `{${k}}`)), +})) + +const stubs = { + NcModal: { name: 'NcModal', props: ['name'], emits: ['close'], template: '<div class="nc-modal-stub"><slot /></div>' }, + NcButton: { + props: ['disabled', 'variant'], + emits: ['click'], + template: '<button class="btn" :data-variant="variant" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: '<input class="field" :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)">', + }, +} + +const CATALOGUE = [ + { uuid: 'c1', name: 'Wiki', description: 'Team pages', linkType: 'url', linkValue: 'https://wiki.test' }, + { uuid: 'c2', name: 'Deck', description: 'Boards', linkType: 'app', linkValue: 'deck' }, +] +const FOUND = [ + { appId: 'grafana', name: 'Grafana', href: '/apps/grafana/' }, + { appId: 'deck', name: 'Deck', href: '/apps/deck/' }, +] +const OFFICE = [ + { title: 'Word', linkType: 'create', linkValue: 'doc', icon: 'icon-filetype-file', iconType: 'class' }, + { title: 'Excel', linkType: 'create', linkValue: 'xls', icon: 'icon-filetype-file', iconType: 'class' }, + { title: 'PowerPoint', linkType: 'create', linkValue: 'ppt', icon: 'icon-filetype-file', iconType: 'class' }, + { title: 'Outlook web', linkType: 'url', linkValue: 'https://outlook.office.com/mail/', icon: '', iconType: 'class' }, +] + +function mountModal(props = {}) { + return mount(AddTilesModal, { + props: { + open: true, + catalogueApps: CATALOGUE, + discoveredApps: FOUND, + officeTiles: OFFICE, + placements: [], + addTiles: vi.fn().mockResolvedValue(undefined), + ...props, + }, + global: { stubs }, + }) +} + +const confirm = (wrapper) => wrapper.find('[data-testid="add-tiles-confirm"]') +const office = (wrapper, key) => wrapper.find(`[data-testid="add-tiles-office-${key}"]`) + +describe('AddTilesModal sections', () => { + it('shows the four sections in board order', () => { + const wrapper = mountModal() + const order = ['add-tiles-catalogue', 'add-tiles-found', 'add-tiles-office', 'add-tiles-bookmarks'] + const found = wrapper.findAll('[data-testid^="add-tiles-"]') + .map((node) => node.attributes('data-testid')) + .filter((id) => order.includes(id)) + expect(found).toEqual(order) + }) + + it('names how each catalogue app signs on and filters by the search', async () => { + const wrapper = mountModal() + const rows = wrapper.findAll('[data-testid="add-tiles-catalogue-row"]') + expect(rows[0].text()).toContain('Asks for its own sign-in') + expect(rows[1].text()).toContain('Signs in with your Nextcloud account') + await wrapper.find('input.field').setValue('boards') + expect(wrapper.findAll('[data-testid="add-tiles-catalogue-row"]').map((row) => row.text())).toEqual([expect.stringContaining('Deck')]) + }) + + it('lists a found app without a tile as Running with Add as tile', () => { + const wrapper = mountModal({ placements: [{ widgetId: 'app-tile', content: { appId: 'deck' } }] }) + const rows = wrapper.findAll('[data-testid="add-tiles-found-row"]') + expect(rows).toHaveLength(1) + expect(rows[0].text()).toContain('Grafana') + expect(rows[0].text()).toContain('Running') + expect(rows[0].text()).toContain('Add as tile') + }) +}) + +describe('AddTilesModal Add Office tiles (scenario)', () => { + it('reads Add 3 tiles after ticking Word, Excel and Outlook web and adds three tiles', async () => { + const addTiles = vi.fn().mockResolvedValue(undefined) + const wrapper = mountModal({ addTiles }) + expect(confirm(wrapper).text()).toBe('Add tiles') + expect(confirm(wrapper).attributes('disabled')).toBeDefined() + + await office(wrapper, 'create:doc').setValue(true) + expect(confirm(wrapper).text()).toBe('Add 1 tile') + await office(wrapper, 'create:xls').setValue(true) + await office(wrapper, 'url:https://outlook.office.com/mail/').setValue(true) + expect(confirm(wrapper).text()).toBe('Add 3 tiles') + + await confirm(wrapper).trigger('click') + await flushPromises() + expect(addTiles).toHaveBeenCalledTimes(1) + expect(addTiles.mock.calls[0][0].map((choice) => choice.tile.title)).toEqual(['Word', 'Excel', 'Outlook web']) + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('unticking takes a tile off the count', async () => { + const wrapper = mountModal() + await office(wrapper, 'create:doc').setValue(true) + await office(wrapper, 'create:doc').setValue(false) + expect(confirm(wrapper).text()).toBe('Add tiles') + }) +}) + +describe('AddTilesModal adding from each section without duplicates', () => { + it('adds from the catalogue, the found apps and Office together, the same app once', async () => { + const addTiles = vi.fn().mockResolvedValue(undefined) + const wrapper = mountModal({ addTiles }) + const catalogueDeck = wrapper.findAll('[data-testid="add-tiles-catalogue-row"]')[1].find('button') + await catalogueDeck.trigger('click') + expect(catalogueDeck.text()).toBe('Added') + await wrapper.findAll('[data-testid="add-tiles-found-row"]')[0].find('button').trigger('click') + // Deck found on the server is the same tile as Deck from the catalogue: + // it already reads Added there. + expect(wrapper.findAll('[data-testid="add-tiles-found-row"]')[1].find('button').text()).toBe('Added') + await office(wrapper, 'create:ppt').setValue(true) + expect(confirm(wrapper).text()).toBe('Add 3 tiles') + + await confirm(wrapper).trigger('click') + await flushPromises() + const added = addTiles.mock.calls[0][0] + expect(added.map((choice) => choice.key)).toEqual(['app:deck', 'app:grafana', 'create:ppt']) + expect(added[1]).toEqual({ key: 'app:grafana', kind: 'app-tile', tile: { appId: 'grafana' } }) + }) + + it('shows a catalogue app and an office tile the dashboard holds as such, not as a choice', () => { + const wrapper = mountModal({ + placements: [ + { tileLinkType: 'url', tileLinkValue: 'https://wiki.test' }, + { tileLinkType: 'create', tileLinkValue: 'doc' }, + ], + }) + const wiki = wrapper.findAll('[data-testid="add-tiles-catalogue-row"]')[0] + expect(wiki.text()).toContain('On your dashboard') + expect(wiki.find('button').exists()).toBe(false) + expect(office(wrapper, 'create:doc').element.disabled).toBe(true) + }) + + it('keeps the dialog open and says so when adding fails', async () => { + const wrapper = mountModal({ addTiles: vi.fn().mockRejectedValue(new Error('409')) }) + await office(wrapper, 'create:doc').setValue(true) + await confirm(wrapper).trigger('click') + await flushPromises() + expect(wrapper.find('[role="alert"]').text()).toBe('The tiles could not be added.') + expect(wrapper.emitted('close')).toBeUndefined() + }) + + it('forgets the choices when it opens again', async () => { + const wrapper = mountModal() + await office(wrapper, 'create:doc').setValue(true) + await wrapper.setProps({ open: false }) + await wrapper.setProps({ open: true }) + expect(confirm(wrapper).text()).toBe('Add tiles') + }) +}) + +describe('AddTilesModal ask IT and bookmarks', () => { + it('asks IT for an app, starting from the search', async () => { + const requestAppFn = vi.fn().mockResolvedValue({}) + const wrapper = mountModal({ requestAppFn }) + await wrapper.find('input.field').setValue('Grafana') + await wrapper.find('[data-testid="add-tiles-request"]').trigger('click') + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(requestAppFn).toHaveBeenCalledWith({ appName: 'Grafana', purpose: '' }) + expect(wrapper.find('[role="status"]').text()).toBe('Your request was sent to IT') + }) + + it('hides Ask IT without a request function', () => { + expect(mountModal().find('[data-testid="add-tiles-request"]').exists()).toBe(false) + }) + + it('hands a chosen or dropped bookmarks file to the bookmark import', async () => { + const wrapper = mountModal() + const file = { name: 'bookmarks.html' } + const input = wrapper.find('[data-testid="add-tiles-bookmark-file"]') + Object.defineProperty(input.element, 'files', { value: [file], configurable: true }) + await input.trigger('change') + await wrapper.find('[data-testid="add-tiles-drop"]').trigger('drop', { dataTransfer: { files: [file] } }) + expect(wrapper.emitted('importBookmarks')).toEqual([[file], [file]]) + }) +}) + +describe('BookmarkImportModal reads a handed-over file', () => { + it('reads the initial file when it opens with one', async () => { + const text = '<DL><p><DT><A HREF="https://wiki.example">Wiki</A></DL>' + const wrapper = mount(BookmarkImportModal, { + props: { open: true, importBookmarks: vi.fn(), initialFile: { size: text.length, text: async () => text } }, + global: { stubs }, + }) + await flushPromises() + expect(wrapper.findAll('[data-testid="bookmark-import-bookmark"]')).toHaveLength(1) + }) +}) + +describe('AddTilesModal ask IT failure', () => { + it('keeps what was typed and marks the message when the request fails', async () => { + const requestAppFn = vi.fn().mockRejectedValue(new Error('offline')) + const wrapper = mountModal({ requestAppFn }) + await wrapper.find('[data-testid="add-tiles-request"]').trigger('click') + await wrapper.find('form input.field').setValue('Kaartviewer') + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(wrapper.find('[role="status"]').classes()).toContain('add-tiles__message--error') + expect(wrapper.find('form input.field').element.value).toBe('Kaartviewer') + }) +}) diff --git a/src/modals/__tests__/BookmarkImportModal.spec.js b/src/modals/__tests__/BookmarkImportModal.spec.js new file mode 100644 index 000000000..734086296 --- /dev/null +++ b/src/modals/__tests__/BookmarkImportModal.spec.js @@ -0,0 +1,124 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The bookmark import dialog: reading the file, ticking folders, refusing a + * too large file before sending, the skipped list and the quota message + * (launcher-bookmark-import REQ-BMI-001..004). + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md + */ +import { flushPromises, mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import BookmarkImportModal from '../BookmarkImportModal.vue' + +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, key, vars = {}) => key.replace(/\{(\w+)\}/g, (_m, k) => String(vars[k] ?? `{${k}}`)), +})) + +const stubs = { + NcModal: { name: 'NcModal', props: ['name'], emits: ['close'], template: '<div class="nc-modal-stub"><slot /></div>' }, + NcButton: { props: ['disabled'], emits: ['click'], template: '<button class="btn" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, +} + +const FILE = `<DL><p> +<DT><H3>Werk</H3><DL><p><DT><A HREF="https://wiki.example">Wiki</A><DT><A HREF="https://mail.example">Mail</A></DL><p> +<DT><H3>Privé</H3><DL><p><DT><A HREF="https://bank.example">Bank</A></DL><p> +<DT><A HREF="javascript:alert(1)">Run</A> +</DL>` + +const fileOf = (text, size) => ({ size: size ?? text.length, text: async () => text }) + +function mountModal(importBookmarks = vi.fn()) { + return mount(BookmarkImportModal, { + props: { open: true, importBookmarks }, + global: { stubs, mocks: { t: (_a, k, vars = {}) => k.replace(/\{(\w+)\}/g, (_m, key) => String(vars[key] ?? `{${key}}`)) } }, + }) +} + +async function choose(wrapper, file) { + const input = wrapper.find('[data-testid="bookmark-import-file"]') + Object.defineProperty(input.element, 'files', { value: [file], configurable: true }) + await input.trigger('change') + await flushPromises() +} + +const confirm = (wrapper) => wrapper.find('[data-testid="bookmark-import-confirm"]') + +describe('BookmarkImportModal', () => { + it('shows the folders and loose bookmarks of the file, all ticked, and labels every control', async () => { + const wrapper = mountModal() + expect(confirm(wrapper).attributes('disabled')).toBeDefined() + await choose(wrapper, fileOf(FILE)) + + const folders = wrapper.findAll('[data-testid="bookmark-import-folder"]') + expect(folders).toHaveLength(2) + expect(folders.every((box) => box.element.checked)).toBe(true) + expect(wrapper.text()).toContain('Werk (2)') + expect(wrapper.findAll('[data-testid="bookmark-import-bookmark"]')).toHaveLength(1) + for (const box of wrapper.findAll('input[type="checkbox"]')) { + expect(box.element.closest('label')).not.toBeNull() + } + expect(wrapper.find('[data-testid="bookmark-import-file"]').attributes('aria-label')).toBe('Import bookmarks') + expect(confirm(wrapper).attributes('disabled')).toBeUndefined() + }) + + it('sends only the ticked folder: Werk, without Privé or the loose bookmark', async () => { + const importBookmarks = vi.fn().mockResolvedValue({ placements: [{ id: 1 }], skipped: [] }) + const wrapper = mountModal(importBookmarks) + await choose(wrapper, fileOf(FILE)) + const folders = wrapper.findAll('[data-testid="bookmark-import-folder"]') + await folders[1].setValue(false) + await wrapper.find('[data-testid="bookmark-import-bookmark"]').setValue(false) + await confirm(wrapper).trigger('click') + await flushPromises() + + expect(importBookmarks).toHaveBeenCalledWith({ + folders: [{ name: 'Werk', bookmarks: [{ title: 'Wiki', url: 'https://wiki.example' }, { title: 'Mail', url: 'https://mail.example' }] }], + bookmarks: [], + }) + expect(wrapper.emitted('imported')[0][0]).toEqual({ placements: [{ id: 1 }], skipped: [] }) + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('says how many bookmarks were skipped and stays open', async () => { + const importBookmarks = vi.fn().mockResolvedValue({ placements: [], skipped: [{ title: 'Run', url: 'javascript:alert(1)', reason: 'x' }] }) + const wrapper = mountModal(importBookmarks) + await choose(wrapper, fileOf(FILE)) + await confirm(wrapper).trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="bookmark-import-skipped"]').text()).toBe('1 skipped: only web addresses can become tiles') + expect(wrapper.emitted('close')).toBeUndefined() + }) + + it('says how much room is left when the import does not fit (409)', async () => { + const importBookmarks = vi.fn().mockRejectedValue({ response: { status: 409, data: { quota: 'widgets', limit: 20, current: 18 } } }) + const wrapper = mountModal(importBookmarks) + await choose(wrapper, fileOf(FILE)) + await confirm(wrapper).trigger('click') + await flushPromises() + + const error = wrapper.find('[data-testid="bookmark-import-error"]') + expect(error.attributes('role')).toBe('alert') + expect(error.text()).toBe('This dashboard can take 2 more. Choose fewer folders or bookmarks.') + }) + + it('refuses a file with more than 2,000 bookmarks and sends nothing', async () => { + const many = '<DL><p>' + Array.from({ length: 2001 }, (_v, i) => `<DT><A HREF="https://e.org/${i}">${i}</A>`).join('') + '</DL>' + const importBookmarks = vi.fn() + const wrapper = mountModal(importBookmarks) + await choose(wrapper, fileOf(many)) + + expect(wrapper.find('[data-testid="bookmark-import-error"]').text()).toBe('This file has more than 2,000 bookmarks. Export one folder at a time.') + expect(confirm(wrapper).attributes('disabled')).toBeDefined() + expect(importBookmarks).not.toHaveBeenCalled() + }) + + it('refuses a file over 5 MB without reading it', async () => { + const wrapper = mountModal() + await choose(wrapper, { size: 6 * 1024 * 1024, text: () => { throw new Error('read') } }) + expect(wrapper.find('[data-testid="bookmark-import-error"]').text()).toBe('This file is larger than 5 MB. Export one folder at a time.') + }) +}) diff --git a/src/modals/__tests__/DashboardConfigModal.hierarchies.spec.js b/src/modals/__tests__/DashboardConfigModal.hierarchies.spec.js new file mode 100644 index 000000000..c55a3d38f --- /dev/null +++ b/src/modals/__tests__/DashboardConfigModal.hierarchies.spec.js @@ -0,0 +1,143 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The dashboard settings pick the hierarchies the filter bus joins widgets on + * (drill-down-cross-widget-filter, REQ-CWF-011). + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, h } from 'vue' +import DashboardConfigModal from '../DashboardConfigModal.vue' +import { api } from '../../services/api.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (p, params = {}) => + '/index.php' + p.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) +vi.mock('../../services/api.js', () => ({ + api: { listShares: vi.fn(), searchSharees: vi.fn(), replaceShares: vi.fn() }, +})) +vi.mock('../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const store = vi.hoisted(() => ({ + fetchShares: vi.fn(), + createShare: vi.fn(), + revokeShare: vi.fn(), +})) +vi.mock('../../stores/publicShares.js', () => ({ + usePublicShareStore: () => store, +})) + +vi.mock('@nextcloud/vue', async () => { + const { defineComponent: define, h: render } = await import('vue') + const named = (name, tag) => define({ + name, + inheritAttrs: true, + render() { + return render(tag, { class: `${name}-stub` }, [this.$slots.default?.(), this.$slots.icon?.()]) + }, + }) + return { + NcModal: named('NcModal', 'div'), + NcButton: named('NcButton', 'button'), + NcTextField: named('NcTextField', 'div'), + NcSelect: named('NcSelect', 'div'), + NcCheckboxRadioSwitch: named('NcCheckboxRadioSwitch', 'label'), + } +}) + +const IconBrowserStub = defineComponent({ + name: 'CnIconBrowser', + render() { + return h('div', { class: 'icon-browser-stub' }) + }, +}) + +/** + * Mount the modal on an owned dashboard with one share and one public link. + * + * @param {object} props Prop overrides + * @return {Promise<object>} The wrapper, after the shares have loaded + */ +async function mountModal(props = {}) { + const wrapper = mount(DashboardConfigModal, { + props: { + open: true, + dashboard: { + id: 3, + uuid: 'uuid-3', + name: 'Marketing', + description: '', + slug: 'marketing', + parentUuid: '', + icon: 'ViewDashboard', + isOwner: true, + permissionLevel: 'full', + }, + mode: 'edit', + parentOptions: [{ uuid: 'uuid-1', name: 'Root' }], + ...props, + }, + global: { + stubs: { + DetailsTab: true, + LanguagesTab: true, + CnIconBrowser: IconBrowserStub, + }, + }, + }) + await flushPromises() + return wrapper +} + +const BASE = { id: 3, uuid: 'uuid-3', name: 'M', description: '', slug: 'm', parentUuid: '', isOwner: true, permissionLevel: 'full' } +const OWN = { id: 'own-taxonomy', levels: [{ dimension: 'regio', label: 'Regio', parentDimension: null }] } + +describe('DashboardConfigModal drill-down levels', () => { + beforeEach(() => { + globalThis.t = (_app, key) => key + vi.clearAllMocks() + api.listShares.mockResolvedValue({ data: [] }) + api.searchSharees.mockResolvedValue({ data: { users: [], groups: [] } }) + api.replaceShares.mockResolvedValue({ data: {} }) + store.fetchShares.mockResolvedValue([]) + }) + + it('offers the presets and keeps a stored hierarchy that is no preset, seeded from the dashboard', async () => { + const wrapper = await mountModal({ dashboard: { ...BASE, hierarchies: [OWN] } }) + + expect(wrapper.vm.hierarchyChoices.map((choice) => choice.id)).toEqual(['nl-administrative', 'own-taxonomy']) + expect(wrapper.vm.form.hierarchies.map((choice) => choice.id)).toEqual(['own-taxonomy']) + expect(wrapper.find('[data-testid="dashboard-hierarchies-select"]').exists()).toBe(true) + expect((await mountModal()).vm.form.hierarchies).toEqual([]) + }) + + it('sends the hierarchies only when the choice changed, an empty choice clearing them', async () => { + const unchanged = await mountModal({ dashboard: { ...BASE, hierarchies: [OWN] } }) + await unchanged.vm.onSave() + expect(unchanged.emitted('save')[0][0]).not.toHaveProperty('hierarchies') + + const picked = await mountModal() + picked.vm.form.hierarchies = picked.vm.hierarchyChoices.filter((choice) => choice.id === 'nl-administrative') + await picked.vm.onSave() + expect(picked.emitted('save')[0][0].hierarchies).toEqual([{ + id: 'nl-administrative', + levels: [ + { dimension: 'provincieCode', label: 'Province', parentDimension: null }, + { dimension: 'gemeenteCode', label: 'Municipality', parentDimension: 'provincieCode' }, + { dimension: 'wijkCode', label: 'District', parentDimension: 'gemeenteCode' }, + { dimension: 'buurtCode', label: 'Neighbourhood', parentDimension: 'wijkCode' }, + ], + }]) + + const cleared = await mountModal({ dashboard: { ...BASE, hierarchies: [OWN] } }) + cleared.vm.form.hierarchies = [] + await cleared.vm.onSave() + expect(cleared.emitted('save')[0][0].hierarchies).toEqual([]) + }) +}) diff --git a/src/modals/__tests__/DashboardConfigModal.linkTarget.spec.js b/src/modals/__tests__/DashboardConfigModal.linkTarget.spec.js new file mode 100644 index 000000000..d7be31b51 --- /dev/null +++ b/src/modals/__tests__/DashboardConfigModal.linkTarget.spec.js @@ -0,0 +1,134 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The dashboard default for how tiles open (launcher-tile-open-behaviour D2). + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, h } from 'vue' +import DashboardConfigModal from '../DashboardConfigModal.vue' +import { api } from '../../services/api.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (p, params = {}) => + '/index.php' + p.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) +vi.mock('../../services/api.js', () => ({ + api: { listShares: vi.fn(), searchSharees: vi.fn(), replaceShares: vi.fn() }, +})) +vi.mock('../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const store = vi.hoisted(() => ({ + fetchShares: vi.fn(), + createShare: vi.fn(), + revokeShare: vi.fn(), +})) +vi.mock('../../stores/publicShares.js', () => ({ + usePublicShareStore: () => store, +})) + +vi.mock('@nextcloud/vue', async () => { + const { defineComponent: define, h: render } = await import('vue') + const named = (name, tag) => define({ + name, + inheritAttrs: true, + render() { + return render(tag, { class: `${name}-stub` }, [this.$slots.default?.(), this.$slots.icon?.()]) + }, + }) + return { + NcModal: named('NcModal', 'div'), + NcButton: named('NcButton', 'button'), + NcTextField: named('NcTextField', 'div'), + NcSelect: named('NcSelect', 'div'), + NcCheckboxRadioSwitch: named('NcCheckboxRadioSwitch', 'label'), + } +}) + +const IconBrowserStub = defineComponent({ + name: 'CnIconBrowser', + render() { + return h('div', { class: 'icon-browser-stub' }) + }, +}) + +/** + * Mount the modal on an owned dashboard with one share and one public link. + * + * @param {object} props Prop overrides + * @return {Promise<object>} The wrapper, after the shares have loaded + */ +async function mountModal(props = {}) { + const wrapper = mount(DashboardConfigModal, { + props: { + open: true, + dashboard: { + id: 3, + uuid: 'uuid-3', + name: 'Marketing', + description: '', + slug: 'marketing', + parentUuid: '', + icon: 'ViewDashboard', + isOwner: true, + permissionLevel: 'full', + }, + mode: 'edit', + parentOptions: [{ uuid: 'uuid-1', name: 'Root' }], + ...props, + }, + global: { + stubs: { + DetailsTab: true, + LanguagesTab: true, + CnIconBrowser: IconBrowserStub, + }, + }, + }) + await flushPromises() + return wrapper +} + +describe('DashboardConfigModal tile link default', () => { + beforeEach(() => { + globalThis.t = (_app, key) => key + vi.clearAllMocks() + api.listShares.mockResolvedValue({ data: [] }) + api.searchSharees.mockResolvedValue({ data: { users: [], groups: [] } }) + api.replaceShares.mockResolvedValue({ data: {} }) + store.fetchShares.mockResolvedValue([]) + }) + + it('offers the link-type rule and the three targets, seeded from the dashboard', async () => { + const wrapper = await mountModal({ + dashboard: { id: 3, uuid: 'uuid-3', name: 'M', description: '', slug: 'm', parentUuid: '', isOwner: true, permissionLevel: 'full', defaultLinkTarget: 'side-panel' }, + }) + + expect(wrapper.vm.linkTargetChoices.map((c) => c.id)).toEqual(['', 'same-tab', 'new-tab', 'side-panel']) + expect(wrapper.vm.form.defaultLinkTarget.id).toBe('side-panel') + expect((await mountModal()).vm.form.defaultLinkTarget.id).toBe('') + }) + + it('sends the default only when it changed, an empty one clearing it', async () => { + const unchanged = await mountModal() + await unchanged.vm.onSave() + expect(unchanged.emitted('save')[0][0]).not.toHaveProperty('defaultLinkTarget') + + const changed = await mountModal() + changed.vm.form.defaultLinkTarget = changed.vm.linkTargetChoices.find((c) => c.id === 'new-tab') + await changed.vm.onSave() + expect(changed.emitted('save')[0][0].defaultLinkTarget).toBe('new-tab') + + const cleared = await mountModal({ + dashboard: { id: 3, uuid: 'uuid-3', name: 'M', description: '', slug: 'm', parentUuid: '', isOwner: true, permissionLevel: 'full', defaultLinkTarget: 'new-tab' }, + }) + cleared.vm.form.defaultLinkTarget = cleared.vm.linkTargetChoices[0] + await cleared.vm.onSave() + expect(cleared.emitted('save')[0][0].defaultLinkTarget).toBe('') + }) +}) diff --git a/src/modals/__tests__/DashboardConfigModal.look.spec.js b/src/modals/__tests__/DashboardConfigModal.look.spec.js new file mode 100644 index 000000000..df9a3d504 --- /dev/null +++ b/src/modals/__tests__/DashboardConfigModal.look.spec.js @@ -0,0 +1,103 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The Look tab of the dashboard configuration (platform-dashboard-theme-and-css + * REQ-THM-001/002): the owner gets the tab, the contrast check runs while + * choosing, and only the look fields that changed are sent with the save. + */ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/router', async (importOriginal) => ({ ...(await importOriginal()), generateUrl: (path) => path })) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ ...(await importOriginal()), t: (_app, key, vars = {}) => key.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m)) })) +vi.mock('../../services/resourceService.js', () => ({ + uploadDataUrl: vi.fn(), + uploadFile: vi.fn(async () => ({ url: '/apps/launchpad/resource/resource_x.1.jpg', name: 'resource_x.1.jpg', size: 3 })), +})) + +import DashboardConfigModal from '../DashboardConfigModal.vue' +import { uploadFile } from '../../services/resourceService.js' + +const computed = DashboardConfigModal.computed + +/** + * A host with the look computeds bound, as the component would have them. + * + * @param {object} look The look being edited. + * @param {object} initialLook The stored look. + * @return {object} + */ +function host(look, initialLook = { accent: '', background: '', resource: '' }) { + const self = { look, initialLook, form: { name: 'Team Groen' } } + for (const name of ['lookAccentHex', 'lookBackgroundHex', 'lookFormatError', 'lookAccentCheck', 'lookValid', 'lookPayload', 'canSave']) { + Object.defineProperty(self, name, { get: () => computed[name].call(self) }) + } + return self +} + +describe('DashboardConfigModal look', () => { + // @spec openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 + it('has no separate Look tab: the look is a block on Details', () => { + const tabs = computed.tabs.call({ canManageShares: true, dashboard: { uuid: 'u-1' }, localShares: [] }) + expect(tabs.map((tab) => tab.id)).toEqual(['general', 'languages', 'sharing']) + expect(computed.tabs.call({ canManageShares: false, dashboard: { uuid: 'u-1' }, localShares: [] }).map((tab) => tab.id)).toEqual(['general']) + }) + + it('refuses a pale accent while choosing and blocks the save (REQ-THM-002)', () => { + const pale = host({ accent: '#f5f5dc', background: '', resource: '' }) + expect(pale.lookAccentCheck).toEqual({ ratio: 1.1, readable: false }) + expect(pale.canSave).toBe(false) + + const green = host({ accent: '#1f5c3a', background: '', resource: '' }) + expect(green.lookValid).toBe(true) + expect(green.canSave).toBe(true) + }) + + it('says when a field holds something other than a colour', () => { + expect(host({ accent: 'green', background: '', resource: '' }).lookFormatError).toBe('Enter colors like #1f5c3a.') + expect(host({ accent: 'green', background: '', resource: '' }).canSave).toBe(false) + expect(host({ accent: '', background: '', resource: '' }).lookFormatError).toBe('') + }) + + it('sends only the look fields that changed, and nothing for a rename', () => { + const stored = { accent: '#1f5c3a', background: '', resource: 'resource_a.png' } + expect(host({ ...stored }, stored).lookPayload).toBeNull() + expect(host({ ...stored, accent: '#1F5C3A' }, stored).lookPayload).toBeNull() + expect(host({ ...stored, background: '#12301F', resource: '' }, stored).lookPayload).toEqual({ + themeBackgroundColor: '#12301f', + themeBackgroundResource: '', + }) + }) + + it('uploads a background image and keeps its resource name', async () => { + const self = { look: { accent: '', background: '', resource: '' }, lookUploading: false, lookUploadError: '' } + const file = new Blob(['x'], { type: 'image/jpeg' }) + + await DashboardConfigModal.methods.onLookImage.call(self, { target: { files: [file] } }) + + expect(uploadFile).toHaveBeenCalledWith(file) + expect(self.look.resource).toBe('resource_x.1.jpg') + expect(self.lookUploading).toBe(false) + }) + + // @spec openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md#requirement-the-details-tab-shows-the-instance-theme-read-only-req-thm-004 + it('emits the changed look with the save', async () => { + const emitted = [] + const self = host({ accent: '#1f5c3a', background: '', resource: '' }) + Object.assign(self, { + isCreate: false, + canManageShares: false, + sharesDirty: false, + dashboard: { id: 7, uuid: 'u-7' }, + form: { name: 'Team Groen', description: '', icon: 'x', parent: { uuid: '' }, slug: '', isDefault: false, hierarchies: [] }, + _initialIsDefault: false, + _initialHierarchies: '', + $emit: (...args) => emitted.push(args), + }) + + await DashboardConfigModal.methods.onSave.call(self) + + expect(emitted[0][0]).toBe('save') + expect(emitted[0][1].look).toEqual({ themeAccent: '#1f5c3a' }) + }) +}) diff --git a/src/modals/__tests__/DashboardConfigModal.publicationExports.spec.js b/src/modals/__tests__/DashboardConfigModal.publicationExports.spec.js new file mode 100644 index 000000000..bc9a5dd13 --- /dev/null +++ b/src/modals/__tests__/DashboardConfigModal.publicationExports.spec.js @@ -0,0 +1,190 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The dashboard settings hold publication, the scheduled exports and the + * versions in their own tabs (REQ-SCHEDUI-001, REQ-SCH-011, board + * LpVersies): which person gets which tab, and what each panel is handed. + */ + +import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import DashboardConfigModal from '../DashboardConfigModal.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ generateUrl: (p) => `/index.php${p}` })) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) + +vi.mock('../../services/api.js', () => ({ + api: { + listShares: vi.fn().mockResolvedValue({ data: [] }), + searchSharees: vi.fn().mockResolvedValue({ data: [] }), + replaceShares: vi.fn().mockResolvedValue({ data: {} }), + }, +})) + +vi.mock('@nextcloud/vue', () => ({ + NcModal: { + props: ['name', 'size'], + render() { + return h('div', { class: 'nc-modal-stub' }, this.$slots.default?.()) + }, + }, + NcButton: { + props: ['type', 'disabled'], + render() { + return h('button', this.$slots.default?.()) + }, + }, + NcTextField: { + props: ['value', 'label', 'placeholder'], + render() { + return h('input') + }, + }, + NcSelect: { + render() { + return h('div', { class: 'nc-select-stub' }, this.$slots.default?.()) + }, + }, + NcCheckboxRadioSwitch: { + props: ['checked', 'type'], + render() { + return h('label', this.$slots.default?.()) + }, + }, +})) + +vi.mock('../../components/Workspace/config/PublicationTab.vue', () => ({ + __esModule: true, + default: { + name: 'PublicationTab', + props: ['dashboard'], + render() { + return h('div', { class: 'publication-stub' }) + }, + }, +})) +vi.mock('../../components/Workspace/config/ExportsTab.vue', () => ({ + __esModule: true, + default: { + name: 'ExportsTab', + props: ['subjects', 'defaultSubject'], + render() { + return h('div', { class: 'exports-stub' }) + }, + }, +})) + +vi.mock('../../components/Workspace/config/VersionsTab.vue', () => ({ + __esModule: true, + default: { + name: 'VersionsTab', + props: ['dashboardUuid'], + emits: ['restored'], + render() { + return h('div', { class: 'versions-stub' }) + }, + }, +})) + +const dashboard = { + id: 3, + uuid: 'uuid-3', + name: 'Marketing', + description: '', + icon: 'ViewDashboard', + isOwner: true, + permissionLevel: 'full', +} + +const subjects = [ + { type: 'dashboard', id: 'uuid-3', label: 'Marketing' }, + { type: 'widget', id: '41', label: 'KPI' }, +] + +/** + * @param {object} props Props on top of an open, owned dashboard. + * @return {object} The wrapper. + */ +function mountModal(props = {}) { + return mount(DashboardConfigModal, { + attachTo: document.body, + props: { open: true, dashboard, ...props }, + }) +} + +const tabIds = (wrapper) => wrapper.findAll('[role="tab"]').map((tab) => tab.attributes('data-test')) + +enableAutoUnmount(afterEach) + +describe('DashboardConfigModal publication and exports tabs', () => { + beforeEach(() => { + vi.clearAllMocks() + setActivePinia(createPinia()) + }) + + it('adds Publication and Exports after Sharing when the host allows them', () => { + const wrapper = mountModal({ canManagePublication: true, canScheduleExports: true, exportSubjects: subjects }) + expect(tabIds(wrapper)).toEqual([ + 'config-tab-general', + 'config-tab-languages', + 'config-tab-sharing', + 'config-tab-publication', + 'config-tab-exports', + ]) + expect(wrapper.find('[data-test="config-tab-publication"]').text()).toContain('Publication') + expect(wrapper.find('[data-test="config-tab-exports"]').text()).toContain('Exports') + }) + + it('leaves both tabs out without the host\'s permission, and while creating', () => { + expect(tabIds(mountModal())).not.toContain('config-tab-publication') + expect(tabIds(mountModal())).not.toContain('config-tab-exports') + const create = mountModal({ mode: 'create', dashboard: null, canManagePublication: true, canScheduleExports: true }) + expect(create.find('[data-test="config-tabs"]').exists()).toBe(false) + }) + + it('offers an administrator the Publication tab on a dashboard they do not own', () => { + const wrapper = mountModal({ dashboard: { ...dashboard, isOwner: false }, canManagePublication: true }) + expect(tabIds(wrapper)).toEqual(['config-tab-general', 'config-tab-publication']) + }) + + it('hands the Publication panel the dashboard', async () => { + const wrapper = mountModal({ canManagePublication: true, initialTab: 'publication' }) + await vi.dynamicImportSettled() + await flushPromises() + expect(wrapper.find('[data-test="config-panel-publication"]').exists()).toBe(true) + expect(wrapper.findComponent({ name: 'PublicationTab' }).props('dashboard')).toEqual(dashboard) + }) + + it('hands the Exports panel this dashboard and its widgets, a new export starting on the dashboard', async () => { + const wrapper = mountModal({ canScheduleExports: true, exportSubjects: subjects }) + await wrapper.find('[data-test="config-tab-exports"]').trigger('click') + await vi.dynamicImportSettled() + await flushPromises() + const tab = wrapper.findComponent({ name: 'ExportsTab' }) + expect(tab.props('subjects')).toEqual(subjects) + expect(tab.props('defaultSubject')).toEqual({ type: 'dashboard', id: 'uuid-3' }) + }) + + it('ends the strip with Versions for the owner or an administrator', () => { + const wrapper = mountModal({ canManagePublication: true, canScheduleExports: true, canViewVersions: true }) + expect(tabIds(wrapper).at(-1)).toBe('config-tab-versions') + expect(wrapper.find('[data-test="config-tab-versions"]').text()).toContain('Versions') + expect(tabIds(mountModal())).not.toContain('config-tab-versions') + }) + + it('hands the Versions panel the dashboard, and passes a restore on', async () => { + const wrapper = mountModal({ canViewVersions: true, initialTab: 'versions' }) + await vi.dynamicImportSettled() + await flushPromises() + const tab = wrapper.findComponent({ name: 'VersionsTab' }) + expect(tab.props('dashboardUuid')).toBe('uuid-3') + tab.vm.$emit('restored', { versionNumber: 2 }) + expect(wrapper.emitted('versionRestored')).toEqual([[{ versionNumber: 2 }]]) + }) +}) diff --git a/src/modals/__tests__/DashboardConfigModal.sharing.spec.js b/src/modals/__tests__/DashboardConfigModal.sharing.spec.js new file mode 100644 index 000000000..39d74de45 --- /dev/null +++ b/src/modals/__tests__/DashboardConfigModal.sharing.spec.js @@ -0,0 +1,556 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `DashboardConfigModal.vue` behaviour beyond the tab + * split: seeding the form on open, the buffered user/group share list and + * when Save replaces it on the server, sharee search, public links, the save + * payload with its default-pin event, and delete. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import DashboardConfigModal from '../DashboardConfigModal.vue' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (p, params = {}) => + '/index.php' + p.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) + +vi.mock('../../services/api.js', () => ({ + api: { + listShares: vi.fn(), + searchSharees: vi.fn(), + replaceShares: vi.fn(), + }, +})) +vi.mock('../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +// REQ-SHARE-015: the viewer's sharing policy from the workspace initial state. +const initialState = vi.hoisted(() => ({ sharingPolicy: null })) +vi.mock('@nextcloud/initial-state', () => ({ + loadState: (_app, key, fallback) => (key === 'sharingPolicy' && initialState.sharingPolicy !== null + ? initialState.sharingPolicy + : fallback), +})) + +const store = vi.hoisted(() => ({ + fetchShares: vi.fn(), + createShare: vi.fn(), + revokeShare: vi.fn(), +})) +vi.mock('../../stores/publicShares.js', () => ({ + usePublicShareStore: () => store, +})) + +vi.mock('@nextcloud/vue', () => { + const passthrough = (tag, cls) => ({ + render() { + return h(tag, { class: cls }, this.$slots.default?.()) + }, + }) + return { + NcModal: passthrough('div', 'nc-modal-stub'), + NcButton: passthrough('button', 'nc-button-stub'), + NcTextField: { render: () => h('input') }, + NcSelect: passthrough('div', 'nc-select-stub'), + NcCheckboxRadioSwitch: passthrough('label', 'nc-switch-stub'), + } +}) + +const SHARES = [ + { shareType: 'user', shareWith: 'alice', permissionLevel: 'view_only', displayName: 'Alice' }, + { shareType: 'group', shareWith: 'sales', permissionLevel: 'full', displayName: 'Sales' }, +] + +const SHAREES = { + data: { + users: [{ id: 'bob', displayName: 'Bob' }], + groups: [{ id: 'ops', displayName: 'Ops' }], + }, +} + +function dashboard (extra = {}) { + return { + id: 3, + uuid: 'uuid-3', + name: ' Marketing ', + description: ' Team board ', + slug: 'marketing', + parentUuid: 'uuid-1', + icon: 'ViewDashboard', + isOwner: true, + permissionLevel: 'add_only', + ...extra, +} +} + +function mountModal(props = {}) { + return mount(DashboardConfigModal, { + propsData: { + open: true, + dashboard: dashboard(), + mode: 'edit', + parentOptions: [{ uuid: 'uuid-1', name: 'Root' }], + ...props, + }, + stubs: { + DetailsTab: true, + LanguagesTab: true, + CnIconBrowser: true, + }, + }) +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + vi.clearAllMocks() + initialState.sharingPolicy = null + api.listShares.mockResolvedValue({ data: SHARES.map((s) => ({ ...s })) }) + api.searchSharees.mockResolvedValue(SHAREES) + api.replaceShares.mockResolvedValue({ data: {} }) + store.fetchShares.mockResolvedValue([{ id: 1, token: 'tok1' }]) + store.createShare.mockResolvedValue({}) + store.revokeShare.mockResolvedValue({}) +}) + +describe('DashboardConfigModal: sharing an unpublished dashboard', () => { + const hint = (wrapper) => wrapper.find('[data-test="share-unpublished-hint"]') + + it('tells the owner that colleagues see a shared draft once it is published', async () => { + const wrapper = mountModal({ dashboard: dashboard({ publicationStatus: 'draft' }) }) + await flushPromises() + + expect(hint(wrapper).text()).toBe('Colleagues see this dashboard once you publish it') + }) + + it('shows the hint for a scheduled dashboard too', async () => { + const wrapper = mountModal({ dashboard: dashboard({ publicationStatus: 'scheduled' }) }) + await flushPromises() + + expect(hint(wrapper).exists()).toBe(true) + }) + + it('shows no hint once the dashboard is published, or for a legacy row', async () => { + const published = mountModal({ dashboard: dashboard({ publicationStatus: 'published' }) }) + const legacy = mountModal() + await flushPromises() + + expect(hint(published).exists()).toBe(false) + expect(hint(legacy).exists()).toBe(false) + }) + + it('shows no hint while the draft is not shared with anyone', async () => { + api.listShares.mockResolvedValue({ data: [] }) + const wrapper = mountModal({ dashboard: dashboard({ publicationStatus: 'draft' }) }) + await flushPromises() + + expect(hint(wrapper).exists()).toBe(false) + }) +}) + +describe('DashboardConfigModal: opening', () => { + it('seeds the form from the dashboard and loads shares, suggestions and links', async () => { + const wrapper = mountModal({ defaultUuid: 'uuid-3' }) + await flushPromises() + + expect(wrapper.vm.form.name).toBe(' Marketing ') + expect(wrapper.vm.form.slug).toBe('marketing') + expect(wrapper.vm.form.parent).toEqual({ uuid: 'uuid-1', name: 'Root' }) + expect(wrapper.vm.form.isDefault).toBe(true) + expect(api.listShares).toHaveBeenCalledWith(3) + expect(api.searchSharees).toHaveBeenCalledWith('') + expect(store.fetchShares).toHaveBeenCalledWith('uuid-3') + expect(wrapper.vm.localShares).toEqual(SHARES) + expect(wrapper.vm.shareeOptions.map((o) => o.key)).toEqual(['user:bob', 'group:ops']) + expect(wrapper.vm.publicShares).toEqual([{ id: 1, token: 'tok1' }]) + expect(wrapper.vm.sharesDirty).toBe(false) + }) + + it('falls back to "No parent" for an unknown parent', () => { + const wrapper = mountModal({ dashboard: dashboard({ parentUuid: 'gone' }) }) + expect(wrapper.vm.form.parent).toEqual({ uuid: '', name: 'No parent' }) + }) + + it('does not load shares for a dashboard the user does not own', async () => { + const wrapper = mountModal({ dashboard: dashboard({ isOwner: false }) }) + await flushPromises() + + expect(wrapper.vm.canManageShares).toBe(false) + expect(api.listShares).not.toHaveBeenCalled() + expect(store.fetchShares).not.toHaveBeenCalled() + expect(wrapper.vm.tabs.map((tab) => tab.id)).toEqual(['general']) + }) + + it('starts empty on create, titled and labelled for creating', () => { + const wrapper = mountModal({ mode: 'create', dashboard: null }) + + expect(wrapper.vm.form.name).toBe('') + expect(wrapper.vm.form.isDefault).toBe(false) + expect(wrapper.vm.modalTitle).toBe('Create dashboard') + expect(wrapper.vm.primaryButtonLabel).toBe('Create') + expect(api.listShares).not.toHaveBeenCalled() + }) + + it('labels the primary button while saving', async () => { + const wrapper = mountModal() + expect(wrapper.vm.modalTitle).toBe('Dashboard settings') + expect(wrapper.vm.primaryButtonLabel).toBe('Save') + wrapper.vm.saving = true + expect(wrapper.vm.primaryButtonLabel).toBe('Saving…') + await wrapper.setProps({ mode: 'create' }) + expect(wrapper.vm.primaryButtonLabel).toBe('Creating…') + }) + + it('shows the dashboard permission level, defaulting to full access', () => { + expect(mountModal().vm.selectedPermission.value).toBe('add_only') + expect(mountModal({ dashboard: dashboard({ permissionLevel: undefined }) }).vm.selectedPermission.value).toBe('full') + expect(mountModal({ dashboard: dashboard({ permissionLevel: 'odd' }) }).vm.selectedPermission.value).toBe('full') + }) + + it('maps a share level to its option, unknown levels to view only', () => { + const wrapper = mountModal() + expect(wrapper.vm.permissionOptionFor('full')).toEqual({ value: 'full', label: 'Full access' }) + expect(wrapper.vm.permissionOptionFor('nope')).toEqual({ value: 'view_only', label: 'View only' }) + }) + + it('clears the share state when closed', async () => { + const wrapper = mountModal() + await flushPromises() + wrapper.vm.newSharePassword = 'secret' + + await wrapper.setProps({ open: false }) + + expect(wrapper.vm.localShares).toEqual([]) + expect(wrapper.vm.serverShares).toEqual([]) + expect(wrapper.vm.publicShares).toEqual([]) + expect(wrapper.vm.newSharePassword).toBe('') + }) + + it('logs and empties the lists when loading fails', async () => { + api.listShares.mockRejectedValue(new Error('a')) + api.searchSharees.mockRejectedValue(new Error('b')) + store.fetchShares.mockRejectedValue(new Error('c')) + const wrapper = mountModal() + await flushPromises() + + expect(wrapper.vm.localShares).toEqual([]) + expect(wrapper.vm.shareeSuggestions).toEqual([]) + expect(wrapper.vm.publicShares).toEqual([]) + expect(wrapper.vm.publicSharesLoading).toBe(false) + expect(logger.error.mock.calls.map((c) => c[0])).toEqual([ + 'Failed to load shares:', + 'Sharee suggestion preload failed:', + 'Failed to load public shares:', + ]) + }) +}) + +describe('DashboardConfigModal: user and group shares', () => { + it('buffers a picked sharee once, as view only', async () => { + const wrapper = mountModal() + await flushPromises() + const bob = { shareType: 'user', id: 'bob', displayName: 'Bob' } + + wrapper.vm.onShareeSelected(bob) + wrapper.vm.onShareeSelected(bob) + wrapper.vm.onShareeSelected(null) + + expect(wrapper.vm.localShares).toHaveLength(3) + expect(wrapper.vm.localShares[2]).toEqual({ + shareType: 'user', + shareWith: 'bob', + permissionLevel: 'view_only', + displayName: 'Bob', + }) + expect(wrapper.vm.sharesDirty).toBe(true) + expect(api.replaceShares).not.toHaveBeenCalled() + }) + + it('changes and removes buffered shares', async () => { + const wrapper = mountModal() + await flushPromises() + + wrapper.vm.onShareLevelChange(0, null) + wrapper.vm.onShareLevelChange(5, { value: 'full' }) + wrapper.vm.onShareLevelChange(0, { value: 'view_only' }) + expect(wrapper.vm.sharesDirty).toBe(false) + + wrapper.vm.onShareLevelChange(0, { value: 'full' }) + expect(wrapper.vm.localShares[0].permissionLevel).toBe('full') + expect(wrapper.vm.serverShares[0].permissionLevel).toBe('view_only') + expect(wrapper.vm.sharesDirty).toBe(true) + + wrapper.vm.onShareRemove(1) + expect(wrapper.vm.localShares.map((s) => s.shareWith)).toEqual(['alice']) + }) + + it('searches sharees for two or more characters only', async () => { + const wrapper = mountModal() + await flushPromises() + api.searchSharees.mockClear() + api.searchSharees.mockResolvedValue({ data: { users: [{ id: 'carol', displayName: 'Carol' }] } }) + + await wrapper.vm.onShareeSearch('c') + expect(api.searchSharees).not.toHaveBeenCalled() + + await wrapper.vm.onShareeSearch(' ca ') + expect(api.searchSharees).toHaveBeenCalledWith('ca') + expect(wrapper.vm.shareeOptions).toEqual([ + { key: 'user:carol', shareType: 'user', id: 'carol', displayName: 'Carol' }, + ]) + expect(wrapper.vm.shareeLoading).toBe(false) + + await wrapper.vm.onShareeSearch('') + expect(wrapper.vm.shareeOptions.map((o) => o.key)).toEqual(['user:bob', 'group:ops']) + }) + + it('drops a stale search result', async () => { + const wrapper = mountModal() + await flushPromises() + let resolveFirst + api.searchSharees + .mockReturnValueOnce(new Promise((resolve) => { resolveFirst = resolve })) + .mockResolvedValueOnce({ data: { users: [{ id: 'dave', displayName: 'Dave' }] } }) + + const first = wrapper.vm.onShareeSearch('al') + await wrapper.vm.onShareeSearch('da') + resolveFirst({ data: { users: [{ id: 'alice', displayName: 'Alice' }] } }) + await first + + expect(wrapper.vm.shareeOptions.map((o) => o.id)).toEqual(['dave']) + }) + + it('empties the options when a search fails', async () => { + const wrapper = mountModal() + await flushPromises() + api.searchSharees.mockRejectedValue(new Error('x')) + + await wrapper.vm.onShareeSearch('zz') + + expect(wrapper.vm.shareeOptions).toEqual([]) + expect(logger.error).toHaveBeenCalledWith('Sharee search failed:', expect.any(Error)) + }) +}) + +describe('DashboardConfigModal: public links', () => { + it('creates a link with password and end-of-day expiry, then reloads', async () => { + const wrapper = mountModal() + await flushPromises() + store.fetchShares.mockClear() + wrapper.vm.newSharePassword = 'pw' + wrapper.vm.newShareExpiry = '2026-12-31' + + await wrapper.vm.onCreatePublicShare() + + expect(store.createShare).toHaveBeenCalledWith('uuid-3', { + password: 'pw', + expiresAt: '2026-12-31T23:59:59Z', + }) + expect(wrapper.vm.newSharePassword).toBe('') + expect(wrapper.vm.newShareExpiry).toBe('') + expect(store.fetchShares).toHaveBeenCalledWith('uuid-3') + expect(wrapper.vm.creatingPublicShare).toBe(false) + }) + + it('creates a link without password once an expiry date is set', async () => { + const wrapper = mountModal() + await flushPromises() + wrapper.vm.newShareExpiry = '2027-01-15' + await wrapper.vm.onCreatePublicShare() + expect(store.createShare).toHaveBeenCalledWith('uuid-3', { password: null, expiresAt: '2027-01-15T23:59:59Z' }) + }) + + // REQ-SHARE-015: every new public link has an expiry date. + it('creates no link without an expiry date and keeps the create button disabled', async () => { + const wrapper = mountModal() + await flushPromises() + await wrapper.vm.onCreatePublicShare() + expect(store.createShare).not.toHaveBeenCalled() + + const expiry = wrapper.find('[data-test="public-share-expiry"]') + if (expiry.exists()) { + expect(expiry.attributes('required')).toBeDefined() + } + }) + + it('keeps the inputs when creating a link fails', async () => { + store.createShare.mockRejectedValue(new Error('x')) + const wrapper = mountModal() + await flushPromises() + wrapper.vm.newSharePassword = 'pw' + wrapper.vm.newShareExpiry = '2026-12-31' + + await wrapper.vm.onCreatePublicShare() + + expect(wrapper.vm.newSharePassword).toBe('pw') + expect(wrapper.vm.creatingPublicShare).toBe(false) + expect(logger.error).toHaveBeenCalledWith('Failed to create public share:', expect.any(Error)) + }) + + it('revokes a link and reloads, logging a failure', async () => { + const wrapper = mountModal() + await flushPromises() + store.fetchShares.mockClear() + + await wrapper.vm.onRevokePublicShare(1) + expect(store.revokeShare).toHaveBeenCalledWith('uuid-3', 1) + expect(store.fetchShares).toHaveBeenCalledTimes(1) + + store.revokeShare.mockRejectedValue(new Error('x')) + await wrapper.vm.onRevokePublicShare(2) + expect(logger.error).toHaveBeenCalledWith('Failed to revoke public share:', expect.any(Error)) + }) + + it('does nothing with links for a dashboard without uuid', async () => { + const wrapper = mountModal({ dashboard: dashboard({ uuid: undefined }) }) + await flushPromises() + + await wrapper.vm.onCreatePublicShare() + await wrapper.vm.onRevokePublicShare(1) + + expect(store.createShare).not.toHaveBeenCalled() + expect(store.revokeShare).not.toHaveBeenCalled() + expect(store.fetchShares).not.toHaveBeenCalled() + expect(wrapper.vm.publicShares).toEqual([]) + }) + + it('builds the public URL and copies it', async () => { + const writeText = vi.fn().mockResolvedValue() + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }) + const wrapper = mountModal() + + expect(wrapper.vm.publicShareUrl('abc')).toBe(`${window.location.origin}/index.php/apps/launchpad/s/abc`) + await wrapper.vm.copyPublicShareUrl({ token: 'abc' }) + + expect(writeText).toHaveBeenCalledWith(`${window.location.origin}/index.php/apps/launchpad/s/abc`) + expect(wrapper.vm.copiedToken).toBe('abc') + + writeText.mockRejectedValue(new Error('denied')) + await wrapper.vm.copyPublicShareUrl({ token: 'def' }) + expect(wrapper.vm.copiedToken).toBe('abc') + expect(logger.error).toHaveBeenCalledWith('Clipboard write failed:', expect.any(Error)) + }) +}) + +describe('DashboardConfigModal: save and delete', () => { + it('emits the trimmed edit payload without touching unchanged shares', async () => { + const wrapper = mountModal() + await flushPromises() + + await wrapper.vm.onSave() + + expect(api.replaceShares).not.toHaveBeenCalled() + expect(wrapper.emitted('save')).toEqual([[{ + id: 3, + name: 'Marketing', + description: 'Team board', + icon: 'ViewDashboard', + parentUuid: 'uuid-1', + slug: 'marketing', + }]]) + expect(wrapper.emitted('setDefault')).toBeUndefined() + expect(wrapper.vm.saving).toBe(false) + }) + + it('replaces changed shares before emitting save', async () => { + const wrapper = mountModal() + await flushPromises() + wrapper.vm.onShareRemove(0) + + await wrapper.vm.onSave() + + expect(api.replaceShares).toHaveBeenCalledWith(3, [ + { shareType: 'group', shareWith: 'sales', permissionLevel: 'full' }, + ]) + expect(wrapper.emitted('save')).toHaveLength(1) + }) + + it('still emits save when replacing shares fails', async () => { + api.replaceShares.mockRejectedValue(new Error('x')) + const wrapper = mountModal() + await flushPromises() + wrapper.vm.onShareRemove(0) + + await wrapper.vm.onSave() + + expect(logger.error).toHaveBeenCalledWith('Failed to replace shares:', expect.any(Error)) + expect(wrapper.emitted('save')).toHaveLength(1) + }) + + it('emits setDefault only when the default switch changed', async () => { + const wrapper = mountModal({ defaultUuid: 'other' }) + await flushPromises() + wrapper.vm.form.isDefault = true + + await wrapper.vm.onSave() + + expect(wrapper.emitted('setDefault')).toEqual([[{ uuid: 'uuid-3', isDefault: true }]]) + }) + + it('emits a create payload without parent or slug', async () => { + const wrapper = mountModal({ mode: 'create', dashboard: null }) + wrapper.vm.form.name = ' New ' + wrapper.vm.form.isDefault = true + + await wrapper.vm.onSave() + + const [[payload]] = wrapper.emitted('save') + expect(payload).toEqual({ id: null, name: 'New', description: '', icon: payload.icon }) + expect(payload.icon).toBeTruthy() + expect(wrapper.emitted('setDefault')).toBeUndefined() + expect(api.replaceShares).not.toHaveBeenCalled() + }) + + it('does not save a blank name', async () => { + const wrapper = mountModal() + wrapper.vm.form.name = ' ' + expect(wrapper.vm.canSave).toBe(false) + + await wrapper.vm.onSave() + + expect(wrapper.emitted('save')).toBeUndefined() + }) + + it('emits delete with the dashboard only when allowed', () => { + const denied = mountModal() + denied.vm.onDelete() + expect(denied.emitted('delete')).toBeUndefined() + + const allowed = mountModal({ canDelete: true }) + allowed.vm.onDelete() + expect(allowed.emitted('delete')).toEqual([[allowed.props('dashboard')]]) + }) +}) + +describe('DashboardConfigModal: the sharing policy (REQ-SHARE-015)', () => { + it('offers adding people and creating a link when the page carries no policy', async () => { + const wrapper = mountModal() + await flushPromises() + expect(wrapper.find('[data-test="share-not-allowed-hint"]').exists()).toBe(false) + expect(wrapper.find('[data-test="public-share-off-hint"]').exists()).toBe(false) + expect(wrapper.find('[data-test="public-share-create"]').exists()).toBe(true) + }) + + it('under Nobody offers no add and no public link, and keeps the existing shares listed', async () => { + initialState.sharingPolicy = { mayShare: false, publicLinksAllowed: true } + const wrapper = mountModal() + await flushPromises() + expect(wrapper.find('[data-test="share-not-allowed-hint"]').exists()).toBe(true) + expect(wrapper.find('[data-test="public-share-create"]').exists()).toBe(false) + expect(wrapper.text()).toContain('Alice') + }) + + it('with public links off offers no new link', async () => { + initialState.sharingPolicy = { mayShare: true, publicLinksAllowed: false } + const wrapper = mountModal() + await flushPromises() + expect(wrapper.find('[data-test="share-not-allowed-hint"]').exists()).toBe(false) + expect(wrapper.find('[data-test="public-share-off-hint"]').text()).toBe('Public links are switched off.') + expect(wrapper.find('[data-test="public-share-create"]').exists()).toBe(false) + }) +}) diff --git a/src/modals/__tests__/DashboardConfigModal.spec.js b/src/modals/__tests__/DashboardConfigModal.spec.js index a8b67b9de..82f20e536 100644 --- a/src/modals/__tests__/DashboardConfigModal.spec.js +++ b/src/modals/__tests__/DashboardConfigModal.spec.js @@ -9,8 +9,8 @@ * - the `initialTab` prop lands the modal on the requested tab */ -import { mount } from '@vue/test-utils' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { enableAutoUnmount, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { h } from 'vue' import DashboardConfigModal from '../DashboardConfigModal.vue' @@ -18,6 +18,9 @@ vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, })) vi.mock('@nextcloud/router', () => ({ generateUrl: (p) => `/index.php${p}` })) +vi.mock('@nextcloud/capabilities', () => ({ + getCapabilities: () => ({ nldesign: { tokenSet: { name: 'Huisstijl Zuiddrecht' } }, theming: { name: 'Nextcloud' } }), +})) vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) vi.mock('../../services/api.js', () => ({ @@ -70,8 +73,11 @@ const ownedDashboard = { permissionLevel: 'full', } +// Attached, because jsdom computes no style for a detached element and +// `isVisible()` would then miss the panels' `v-show`. function mountModal(props = {}) { return mount(DashboardConfigModal, { + attachTo: document.body, propsData: { open: true, dashboard: ownedDashboard, @@ -90,6 +96,8 @@ function mountModal(props = {}) { }) } +enableAutoUnmount(afterEach) + beforeEach(() => { globalThis.t = (_app, key) => key vi.clearAllMocks() @@ -103,6 +111,11 @@ describe('DashboardConfigModal tab split', () => { expect(wrapper.find('[data-test="config-tab-sharing"]').exists()).toBe(true) }) + it('keeps the theme button look off the tab strip', () => { + const wrapper = mountModal() + expect(wrapper.find('[data-test="config-tabs"]').classes()).toContain('cn-look-board') + }) + it('does not show the sharee picker on the General panel', async () => { const wrapper = mountModal() await wrapper.vm.$nextTick() @@ -143,4 +156,84 @@ describe('DashboardConfigModal tab split', () => { }) expect(wrapper.vm.currentTab).toBe('general') }) + + it('has the board\'s tabs: Details, Languages, Sharing', () => { + const wrapper = mountModal() + const ids = wrapper + .findAll('[role="tab"]') + .map((tab) => tab.attributes('data-test')) + // dashboard-theme-readonly REQ-THM-001: the look is a block on Details. + expect(ids).toEqual([ + 'config-tab-general', + 'config-tab-languages', + 'config-tab-sharing', + ]) + expect(wrapper.find('[data-test="config-tab-general"]').text()).toContain( + 'Details', + ) + }) + + it('puts the default switch under Details', () => { + const wrapper = mountModal() + const general = wrapper.find('[data-test="config-panel-general"]') + expect(general.text()).toContain('Default dashboard') + expect(wrapper.find('[data-test="config-panel-default"]').exists()).toBe( + false, + ) + }) + + // @spec openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md#requirement-each-dashboard-can-have-its-own-look-req-thm-001 + it('draws Own look on the Details tab, with no layout preset field', () => { + const wrapper = mountModal() + const general = wrapper.find('[data-test="config-panel-general"]') + const look = general.find('[data-test="config-look"]') + expect(look.exists()).toBe(true) + expect(look.text()).toContain('Own look') + expect(look.find('[data-testid="look-accent"]').exists()).toBe(true) + expect(look.find('[data-testid="look-background"]').exists()).toBe(true) + expect(look.find('[data-testid="look-image-input"]').exists()).toBe(true) + expect(general.text()).not.toMatch(/layout of this dashboard|Indeling van dit dashboard/i) + expect(wrapper.find('[data-test="config-panel-look"]').exists()).toBe(false) + }) + + // @spec openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md#requirement-the-details-tab-shows-the-instance-theme-read-only-req-thm-004 + it('shows the instance theme read-only under Display, with no theme choice or layout field', () => { + const wrapper = mountModal() + const general = wrapper.find('[data-test="config-panel-general"]') + const display = general.find('[data-test="config-display"]') + expect(display.exists()).toBe(true) + expect(display.text()).toContain('Display') + const theme = display.find('[data-testid="display-theme"]') + expect(theme.attributes('readonly')).toBeDefined() + expect(wrapper.vm.themeName).toBe('Huisstijl Zuiddrecht') + expect(display.find('[data-testid="display-theme-hint"]').text()).toContain('Own look') + expect(display.find('.nc-select-stub').exists()).toBe(false) + expect(general.text()).not.toMatch(/layout of this dashboard|Indeling van dit dashboard/i) + }) + + it('shows no theme field while creating a dashboard', () => { + const wrapper = mountModal({ dashboard: null }) + expect(wrapper.find('[data-test="config-display"]').exists()).toBe(false) + }) + + it('offers no Own look while creating a dashboard', () => { + const wrapper = mountModal({ dashboard: null }) + expect(wrapper.find('[data-test="config-look"]').exists()).toBe(false) + }) + + it('lands on Details when an old caller asks for the default tab', () => { + const wrapper = mountModal({ initialTab: 'default' }) + expect(wrapper.vm.currentTab).toBe('general') + }) + + it('counts the shares on the Sharing tab', async () => { + const wrapper = mountModal() + // Let the modal's own share load settle first; it resets the list. + await new Promise((resolve) => setTimeout(resolve, 0)) + wrapper.vm.localShares = [{ shareWith: 'a' }, { shareWith: 'b' }] + await wrapper.vm.$nextTick() + expect( + wrapper.find('[data-test="config-tab-count-sharing"]').text(), + ).toBe('2') + }) }) diff --git a/src/modals/__tests__/DashboardConfigModal.wiring.spec.js b/src/modals/__tests__/DashboardConfigModal.wiring.spec.js new file mode 100644 index 000000000..329c7e733 --- /dev/null +++ b/src/modals/__tests__/DashboardConfigModal.wiring.spec.js @@ -0,0 +1,275 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the template wiring of `DashboardConfigModal.vue`: + * every field, picker and button in the rendered modal reaches the form + * state, method or emit it is bound to. The sibling specs call the methods + * directly; these drive the controls the user touches. + * + * The Nextcloud components are named stubs that render their slots, so the + * test can find each one and emit the event the real component would. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, h } from 'vue' +import DashboardConfigModal from '../DashboardConfigModal.vue' +import { api } from '../../services/api.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (p, params = {}) => + '/index.php' + p.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) +vi.mock('../../services/api.js', () => ({ + api: { listShares: vi.fn(), searchSharees: vi.fn(), replaceShares: vi.fn() }, +})) +vi.mock('../../utils/logger.js', () => ({ logger: { error: vi.fn() } })) + +const store = vi.hoisted(() => ({ + fetchShares: vi.fn(), + createShare: vi.fn(), + revokeShare: vi.fn(), +})) +vi.mock('../../stores/publicShares.js', () => ({ + usePublicShareStore: () => store, +})) + +vi.mock('@nextcloud/vue', async () => { + const { defineComponent: define, h: render } = await import('vue') + const named = (name, tag) => define({ + name, + inheritAttrs: true, + render() { + return render(tag, { class: `${name}-stub` }, [this.$slots.default?.(), this.$slots.icon?.()]) + }, + }) + return { + NcModal: named('NcModal', 'div'), + NcButton: named('NcButton', 'button'), + NcTextField: named('NcTextField', 'div'), + NcSelect: named('NcSelect', 'div'), + NcCheckboxRadioSwitch: named('NcCheckboxRadioSwitch', 'label'), + } +}) + +const IconBrowserStub = defineComponent({ + name: 'CnIconBrowser', + render() { + return h('div', { class: 'icon-browser-stub' }) + }, +}) + +/** + * Mount the modal on an owned dashboard with one share and one public link. + * + * @param {object} props Prop overrides + * @return {Promise<object>} The wrapper, after the shares have loaded + */ +async function mountModal(props = {}) { + const wrapper = mount(DashboardConfigModal, { + props: { + open: true, + dashboard: { + id: 3, + uuid: 'uuid-3', + name: 'Marketing', + description: '', + slug: 'marketing', + parentUuid: '', + icon: 'ViewDashboard', + isOwner: true, + permissionLevel: 'full', + }, + mode: 'edit', + parentOptions: [{ uuid: 'uuid-1', name: 'Root' }], + ...props, + }, + global: { + stubs: { + DetailsTab: true, + LanguagesTab: true, + CnIconBrowser: IconBrowserStub, + }, + }, + }) + await flushPromises() + return wrapper +} + +/** + * The text field with the given label. + * + * @param {object} wrapper The mounted modal + * @param {string} label The field label + * @return {object} The stub + */ +function textField(wrapper, label) { + return wrapper.findAllComponents({ name: 'NcTextField' }).find((c) => c.vm.$attrs.label === label) +} + +/** + * The button with the given aria-label or text. + * + * @param {object} wrapper The mounted modal + * @param {string} name The label + * @return {object} The button wrapper + */ +function button(wrapper, name) { + return wrapper.findAll('button').find((b) => b.attributes('aria-label') === name || b.text().trim() === name) +} + +beforeEach(() => { + globalThis.t = (_app, key) => key + vi.clearAllMocks() + api.listShares.mockResolvedValue({ + data: [{ shareType: 'user', shareWith: 'alice', permissionLevel: 'view_only', displayName: 'Alice' }], + }) + api.searchSharees.mockResolvedValue({ data: { users: [{ id: 'bob', displayName: 'Bob' }], groups: [] } }) + api.replaceShares.mockResolvedValue({ data: {} }) + store.fetchShares.mockResolvedValue([{ id: 11, token: 'tok11', passwordRequired: true, expiresAt: '2026-12-31' }]) + store.createShare.mockResolvedValue({}) + store.revokeShare.mockResolvedValue({}) +}) + +describe('DashboardConfigModal wiring: details fields', () => { + it('writes the title, web address name and default switch into the form', async () => { + const wrapper = await mountModal() + + textField(wrapper, 'Title').vm.$emit('update:modelValue', 'Sales') + textField(wrapper, 'Web address name').vm.$emit('update:modelValue', 'sales') + wrapper.findComponent({ name: 'NcCheckboxRadioSwitch' }).vm.$emit('update:modelValue', true) + + expect(wrapper.vm.form).toMatchObject({ name: 'Sales', slug: 'sales', isDefault: true }) + }) + + it('writes the description, the parent and the icon into the form', async () => { + const wrapper = await mountModal() + + await wrapper.find('[data-testid="dashboard-description-input"]').setValue('For the sales team') + const parent = wrapper.findAllComponents({ name: 'NcSelect' }).find((c) => c.attributes('data-testid') === 'dashboard-parent-select') + parent.vm.$emit('update:modelValue', { uuid: 'uuid-1', name: 'Root' }) + wrapper.findComponent({ name: 'CnIconBrowser' }).vm.$emit('input', '/apps/launchpad/resource/7') + + expect(wrapper.vm.form.description).toBe('For the sales team') + expect(wrapper.vm.form.parent).toEqual({ uuid: 'uuid-1', name: 'Root' }) + expect(wrapper.vm.form.icon).toBe('/apps/launchpad/resource/7') + }) + + it('says the parent places the dashboard under Dashboards in the More menu', async () => { + const wrapper = await mountModal() + + expect(wrapper.find('[data-testid="dashboard-parent-hint"]').text()).toBe( + 'This builds a tree of dashboards under Dashboards in the More menu', + ) + expect(wrapper.text()).not.toMatch(/side ?bar/i) + }) + + it('ignores a write to the admin-managed permission level', async () => { + const wrapper = await mountModal() + + wrapper.vm.selectedPermission = { value: 'view_only' } + + expect(wrapper.vm.selectedPermission.value).toBe('full') + }) +}) + +describe('DashboardConfigModal wiring: user and group shares', () => { + it('buffers a sharee picked in the search select, and searches what is typed', async () => { + const wrapper = await mountModal() + const picker = wrapper.findAllComponents({ name: 'NcSelect' }).find((c) => c.vm.$attrs.trackBy === 'key') + + picker.vm.$emit('update:modelValue', { shareType: 'group', id: 'ops', displayName: 'Ops' }) + picker.vm.$emit('search', 'bo') + await flushPromises() + + expect(wrapper.vm.localShares.map((s) => s.shareWith)).toEqual(['alice', 'ops']) + expect(api.searchSharees).toHaveBeenCalledWith('bo') + }) + + it('changes a share level from its row select, and removes it from its row button', async () => { + const wrapper = await mountModal() + const level = wrapper.findAllComponents({ name: 'NcSelect' }).find((c) => c.classes().includes('dashboard-config__share-level')) + + level.vm.$emit('update:modelValue', { value: 'full', label: 'Full' }) + expect(wrapper.vm.localShares[0].permissionLevel).toBe('full') + + await button(wrapper, 'Remove share').trigger('click') + expect(wrapper.vm.localShares).toEqual([]) + }) +}) + +describe('DashboardConfigModal wiring: public links', () => { + it('selects the link text on focus', async () => { + const wrapper = await mountModal() + const input = wrapper.find('.dashboard-config__public-url') + const select = vi.spyOn(input.element, 'select') + + await input.trigger('focus') + + expect(select).toHaveBeenCalled() + expect(input.element.value).toBe(`${window.location.origin}/index.php/apps/launchpad/s/tok11`) + }) + + it('copies a link from its copy button', async () => { + const writeText = vi.fn().mockResolvedValue() + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }) + const wrapper = await mountModal() + + await button(wrapper, 'Copy link').trigger('click') + await flushPromises() + + expect(writeText).toHaveBeenCalledWith(`${window.location.origin}/index.php/apps/launchpad/s/tok11`) + }) + + it('revokes a link from its revoke button', async () => { + const wrapper = await mountModal() + + await button(wrapper, 'Revoke link').trigger('click') + await flushPromises() + + expect(store.revokeShare).toHaveBeenCalledWith('uuid-3', 11) + }) + + it('creates a link from the password and expiry the user entered', async () => { + const wrapper = await mountModal() + + textField(wrapper, 'Password (optional)').vm.$emit('update:modelValue', 's3cret') + await wrapper.find('.dashboard-config__public-date').setValue('2027-01-31') + await button(wrapper, 'Create public link').trigger('click') + await flushPromises() + + expect(store.createShare).toHaveBeenCalledWith('uuid-3', { password: 's3cret', expiresAt: '2027-01-31T23:59:59Z' }) + }) +}) + +describe('DashboardConfigModal wiring: actions', () => { + it('emits close from the modal and from Cancel', async () => { + const wrapper = await mountModal() + + wrapper.findComponent({ name: 'NcModal' }).vm.$emit('close') + await button(wrapper, 'Cancel').trigger('click') + + expect(wrapper.emitted('close')).toHaveLength(2) + }) + + it('emits delete from the delete button, which only shows when allowed', async () => { + expect((await mountModal()).find('[data-testid="dashboard-delete-button"]').exists()).toBe(false) + const wrapper = await mountModal({ canDelete: true }) + + await wrapper.find('[data-testid="dashboard-delete-button"]').trigger('click') + + expect(wrapper.emitted('delete')).toEqual([[expect.objectContaining({ id: 3, uuid: 'uuid-3' })]]) + }) + + it('emits save from the save button', async () => { + const wrapper = await mountModal() + + await wrapper.find('[data-testid="dashboard-save-button"]').trigger('click') + await flushPromises() + + expect(wrapper.emitted('save')).toHaveLength(1) + expect(wrapper.emitted('save')[0][0]).toMatchObject({ id: 3, name: 'Marketing' }) + }) +}) diff --git a/src/modals/__tests__/PreviewModal.spec.js b/src/modals/__tests__/PreviewModal.spec.js new file mode 100644 index 000000000..8263ed8fa --- /dev/null +++ b/src/modals/__tests__/PreviewModal.spec.js @@ -0,0 +1,184 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * PreviewModal (scheduled-exports task 16): POSTs /api/exports/{id}/preview + * with the chosen format and recipient and asks for the file; a PDF is + * embedded, a PNG shown as an image, a CSV or XLSX offered as a download, + * and a refused render (422, JSON inside the Blob) shows the reason. Only + * HTTP, the router, l10n and the object-URL API are mocked. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import PreviewModal from '../PreviewModal.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, + generateRemoteUrl: (service) => `/remote.php/${service}`, +})) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) +vi.mock( + '@conduction/nextcloud-vue', + () => import('./helpers/scheduledExportStubs.js'), +) + +const BASE = '/index.php/apps/launchpad/api/exports' + +const exportData = { + id: 'e1', + name: 'CBS return', + renderTargets: [{ format: 'xlsx' }, { format: 'pdf' }], + recipients: [ + { + id: 'r1', + channel: 'email', + channelConfig: { addresses: ['compliance@gemeente.nl'] }, + }, + { + id: 'r2', + channel: 'sftp', + channelConfig: { host: 'sftp.cbs.nl' }, + filterContext: { gemeenteCode: 'GM0355' }, + }, + ], +} + +const originalCreate = URL.createObjectURL +const originalRevoke = URL.revokeObjectURL + +/** + * Mount the preview for the export. + * + * @return {object} The wrapper. + */ +function mountPreview() { + return mount(PreviewModal, { props: { open: true, exportData } }) +} + +describe('PreviewModal', () => { + beforeEach(() => { + vi.clearAllMocks() + setActivePinia(createPinia()) + URL.createObjectURL = vi.fn(() => 'blob:preview-1') + URL.revokeObjectURL = vi.fn() + }) + + afterEach(() => { + URL.createObjectURL = originalCreate + URL.revokeObjectURL = originalRevoke + }) + + it("starts on the export's first format and offers each recipient", () => { + const wrapper = mountPreview() + const format = wrapper.find('[data-testid="preview-format"]') + expect(format.element.value).toBe('Excel workbook (XLSX)') + const recipients = wrapper + .find('[data-testid="preview-recipient"]') + .findAll('option') + .map((o) => o.text()) + expect(recipients).toEqual([ + 'No recipient (all data)', + 'Email: compliance@gemeente.nl', + 'SFTP: sftp.cbs.nl', + ]) + }) + + it('embeds a PDF rendered without a recipient', async () => { + axios.post.mockResolvedValue({ + data: new Blob(['%PDF'], { type: 'application/pdf' }), + }) + const wrapper = mountPreview() + + await wrapper.find('[data-testid="preview-format"]').setValue('PDF document') + await wrapper.find('[data-testid="preview-render"]').trigger('click') + await flushPromises() + + expect(axios.post).toHaveBeenCalledWith(`${BASE}/e1/preview`, null, { + params: { recipientId: '', format: 'pdf' }, + responseType: 'blob', + }) + const pdf = wrapper.find('[data-testid="preview-pdf"]') + expect(pdf.attributes('data')).toBe('blob:preview-1') + expect(pdf.attributes('type')).toBe('application/pdf') + }) + + it('shows a PNG as an image', async () => { + axios.post.mockResolvedValue({ + data: new Blob(['png'], { type: 'image/png' }), + }) + const wrapper = mountPreview() + + await wrapper.find('[data-testid="preview-format"]').setValue('PNG image') + await wrapper.find('[data-testid="preview-render"]').trigger('click') + await flushPromises() + + const img = wrapper.find('[data-testid="preview-png"]') + expect(img.attributes('src')).toBe('blob:preview-1') + expect(img.attributes('alt')).toBe('Preview of CBS return') + }) + + it('offers a CSV for the chosen recipient as a download', async () => { + axios.post.mockResolvedValue({ + data: new Blob(['a;b'], { type: 'text/csv' }), + }) + const wrapper = mountPreview() + + await wrapper.find('[data-testid="preview-format"]').setValue('CSV table') + await wrapper + .find('[data-testid="preview-recipient"]') + .setValue('SFTP: sftp.cbs.nl') + await wrapper.find('[data-testid="preview-render"]').trigger('click') + await flushPromises() + + expect(axios.post.mock.calls[0][2].params).toEqual({ + recipientId: 'r2', + format: 'csv', + }) + const link = wrapper.find('[data-testid="preview-download"] a') + expect(link.attributes('href')).toBe('blob:preview-1') + expect(link.attributes('download')).toBe('CBS return.csv') + expect(wrapper.find('[data-testid="preview-pdf"]').exists()).toBe(false) + }) + + it('shows the reason a render was refused', async () => { + const body = new Blob( + [ + JSON.stringify({ + error: 'render_failed', + message: 'No headless browser is configured', + }), + ], + { type: 'application/json' }, + ) + axios.post.mockRejectedValue({ response: { status: 422, data: body } }) + const wrapper = mountPreview() + + await wrapper.find('[data-testid="preview-render"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="preview-error"]').text()).toBe( + 'No headless browser is configured', + ) + expect(URL.createObjectURL).not.toHaveBeenCalled() + }) + + it('frees the previous file when a new preview is made', async () => { + axios.post.mockResolvedValue({ data: new Blob(['x']) }) + const wrapper = mountPreview() + await wrapper.find('[data-testid="preview-render"]').trigger('click') + await flushPromises() + await wrapper.find('[data-testid="preview-render"]').trigger('click') + await flushPromises() + + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:preview-1') + }) +}) diff --git a/src/modals/__tests__/RolePermissionEditorModal.spec.js b/src/modals/__tests__/RolePermissionEditorModal.spec.js new file mode 100644 index 000000000..0b0a3ee38 --- /dev/null +++ b/src/modals/__tests__/RolePermissionEditorModal.spec.js @@ -0,0 +1,102 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `RolePermissionEditorModal.vue`: the title, the + * field updates it emits without mutating the row, the locked group id when + * editing, and when Save is enabled. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import RolePermissionEditorModal from '../RolePermissionEditorModal.vue' + +const TextFieldStub = { + props: ['modelValue', 'label', 'disabled'], + emits: ['update:modelValue'], + template: '<input class="field" :data-label="label" :disabled="disabled" :value="modelValue" />', +} + +const ButtonStub = { + props: ['disabled'], + emits: ['click'], + template: '<button class="btn" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', +} + +const stubs = { + NcModal: { emits: ['close'], template: '<div class="nc-modal-stub"><slot /></div>' }, + NcTextField: TextFieldStub, + NcButton: ButtonStub, +} + +function mountModal(props = {}) { + return mount(RolePermissionEditorModal, { + propsData: { row: { name: 'Editors', groupId: 'editors', description: '' }, ...props }, + stubs, + }) +} + +function field (wrapper, label) { + return wrapper.findAllComponents(TextFieldStub).find((f) => f.props('label') === label) +} +function button (wrapper, label) { + return wrapper.findAll('button.btn').find((b) => b.text() === label) +} + +describe('RolePermissionEditorModal', () => { + it('titles a new row "Add" and an existing one "Edit"', () => { + expect(mountModal().find('h3').text()).toBe('Add role permission') + expect(mountModal({ row: { id: 3, name: 'a', groupId: 'g' } }).find('h3').text()).toBe('Edit role permission') + }) + + it('emits a copy of the row with the edited field, leaving the prop untouched', () => { + const row = { name: 'Editors', groupId: 'editors', description: '' } + const wrapper = mountModal({ row }) + + field(wrapper, 'Name').vm.$emit('update:modelValue', 'Writers') + field(wrapper, 'Nextcloud group ID').vm.$emit('update:modelValue', 'writers') + field(wrapper, 'Description (optional)').vm.$emit('update:modelValue', 'Can write') + + expect(wrapper.emitted('update:row')).toEqual([ + [{ name: 'Writers', groupId: 'editors', description: '' }], + [{ name: 'Editors', groupId: 'writers', description: '' }], + [{ name: 'Editors', groupId: 'editors', description: 'Can write' }], + ]) + expect(row).toEqual({ name: 'Editors', groupId: 'editors', description: '' }) + }) + + it('forwards the widget CSV fields as their own update events', () => { + const wrapper = mountModal({ allowedWidgetsCsv: 'a', deniedWidgetsCsv: 'b' }) + expect(field(wrapper, 'Allowed widget IDs (comma separated)').props('modelValue')).toBe('a') + + field(wrapper, 'Allowed widget IDs (comma separated)').vm.$emit('update:modelValue', 'a,c') + field(wrapper, 'Denied widget IDs (comma separated)').vm.$emit('update:modelValue', 'd') + + expect(wrapper.emitted('update:allowedWidgetsCsv')).toEqual([['a,c']]) + expect(wrapper.emitted('update:deniedWidgetsCsv')).toEqual([['d']]) + expect(wrapper.emitted('update:row')).toBeUndefined() + }) + + it('locks the group id only when editing an existing row', () => { + expect(field(mountModal(), 'Nextcloud group ID').props('disabled')).toBe(false) + expect(field(mountModal({ row: { id: 1, name: 'a', groupId: 'g' } }), 'Nextcloud group ID').props('disabled')).toBe(true) + }) + + it.each([ + ['a complete row', { name: 'n', groupId: 'g' }, false, false], + ['a missing name', { name: '', groupId: 'g' }, false, true], + ['a missing group', { name: 'n', groupId: '' }, false, true], + ['a save in progress', { name: 'n', groupId: 'g' }, true, true], + ])('Save with %s is disabled: %s', (_case, row, saving, disabled) => { + const save = button(mountModal({ row, saving }), 'Save') + expect(save.attributes('disabled') !== undefined).toBe(disabled) + }) + + it('emits save and close from its buttons', async () => { + const wrapper = mountModal() + await button(wrapper, 'Save').trigger('click') + await button(wrapper, 'Cancel').trigger('click') + expect(wrapper.emitted('save')).toHaveLength(1) + expect(wrapper.emitted('close')).toHaveLength(1) + }) +}) diff --git a/src/modals/__tests__/RunDetailModal.spec.js b/src/modals/__tests__/RunDetailModal.spec.js new file mode 100644 index 000000000..85c856ace --- /dev/null +++ b/src/modals/__tests__/RunDetailModal.spec.js @@ -0,0 +1,209 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * RunDetailModal (scheduled-exports task 15): reads the run from + * GET /api/exports/{id}/runs/{runId}, lists its deliveries and render + * artefacts with a Files download link, and offers Retry only when a + * delivery failed for good, POSTing .../retry and showing the answer. + * Run-rows are AuditLog's shape. Only HTTP, the router and l10n are mocked. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import RunDetailModal from '../RunDetailModal.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, + generateRemoteUrl: (service) => `/remote.php/${service}`, +})) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) +vi.mock( + '@conduction/nextcloud-vue', + () => import('./helpers/scheduledExportStubs.js'), +) + +const BASE = '/index.php/apps/launchpad/api/exports' + +const exportData = { + id: 'e1', + name: 'Weekly bezwaren', + recipients: [ + { + id: 'r1', + channel: 'email', + channelConfig: { addresses: ['wethouder@gemeente.nl'] }, + }, + { + id: 'r2', + channel: 'webhook', + channelConfig: { url: 'https://hooks.example.org/lp' }, + }, + ], +} + +/** + * A run-row. + * + * @param {string} webhookStatus The webhook delivery's status. + * @return {object} The run. + */ +function run(webhookStatus) { + return { + id: 'run-1', + exportId: 'e1', + startedAt: '2026-11-09T09:00:00+01:00', + finishedAt: '2026-11-09T09:01:00+01:00', + status: webhookStatus === 'success' ? 'success' : 'partial', + triggeredBy: 'manual', + triggeredByUser: 'sanne', + renderArtefacts: [ + { + format: 'pdf', + sizeBytes: 2048, + sha256: 'a'.repeat(64), + storagePath: + '/sanne/files/Apps/LaunchPad/Exports/e1/Weekly bezwaren.pdf', + }, + { + format: 'csv', + sizeBytes: 300, + sha256: 'b'.repeat(64), + storagePath: null, + }, + ], + deliveries: [ + { + recipientId: 'r1', + channel: 'email', + status: 'success', + attemptCount: 1, + providerMessageId: 'm-1', + }, + { + recipientId: 'r2', + channel: 'webhook', + status: webhookStatus, + attemptCount: 5, + error: + webhookStatus === 'success' + ? undefined + : 'HTTP 503 from receiver', + }, + ], + } +} + +/** + * Mount the detail with the server answering this run. + * + * @param {object} answer The run the GET returns. + * @return {Promise<object>} The wrapper. + */ +async function mountDetail(answer) { + axios.get.mockResolvedValue({ data: answer }) + const wrapper = mount(RunDetailModal, { + props: { open: true, exportData, run: { id: 'run-1', status: 'running' } }, + }) + await flushPromises() + return wrapper +} + +describe('RunDetailModal', () => { + beforeEach(() => { + vi.clearAllMocks() + setActivePinia(createPinia()) + }) + + it('reads the run and shows its deliveries and files', async () => { + const wrapper = await mountDetail(run('failed-permanent')) + + expect(axios.get).toHaveBeenCalledWith(`${BASE}/e1/runs/run-1`) + expect(wrapper.find('[data-testid="run-detail-export"]').text()).toBe( + 'Weekly bezwaren', + ) + expect(wrapper.text()).toContain('By hand by sanne') + + const deliveries = wrapper.findAll('[data-testid="run-detail-delivery"]') + expect(deliveries).toHaveLength(2) + const cells = deliveries[1].findAll('td').map((td) => td.text()) + expect(cells).toEqual([ + 'Webhook: https://hooks.example.org/lp', + 'Webhook', + 'Failed for good', + '5', + 'HTTP 503 from receiver', + ]) + expect(deliveries[0].findAll('td')[0].text()).toBe( + 'Email: wethouder@gemeente.nl', + ) + + const artefacts = wrapper.findAll('[data-testid="run-detail-artefact"]') + expect(artefacts).toHaveLength(2) + expect(artefacts[0].text()).toContain('PDF document') + expect(artefacts[0].text()).toContain('2.0 KB') + expect( + artefacts[0] + .find('[data-testid="run-detail-download"]') + .attributes('href'), + ).toBe( + '/remote.php/dav/files/sanne/Apps/LaunchPad/Exports/e1/Weekly%20bezwaren.pdf', + ) + expect( + artefacts[1].find('[data-testid="run-detail-download"]').exists(), + ).toBe(false) + expect(artefacts[1].text()).toContain('Removed after the retention period') + }) + + it('offers Retry when a delivery failed for good, and shows the retried run', async () => { + const wrapper = await mountDetail(run('failed-permanent')) + axios.post.mockResolvedValue({ data: run('success') }) + + const retry = wrapper.find('[data-testid="run-detail-retry"]') + expect(retry.exists()).toBe(true) + await retry.trigger('click') + await flushPromises() + + expect(axios.post).toHaveBeenCalledWith(`${BASE}/e1/runs/run-1/retry`) + expect(wrapper.emitted('retried')[0][0].status).toBe('success') + expect(wrapper.find('[data-testid="run-detail-retry"]').exists()).toBe(false) + expect( + wrapper.findAll('[data-testid="run-detail-delivery"]')[1].text(), + ).toContain('Succeeded') + }) + + it('offers no Retry when no delivery failed for good', async () => { + expect( + (await mountDetail(run('success'))) + .find('[data-testid="run-detail-retry"]') + .exists(), + ).toBe(false) + expect( + (await mountDetail(run('retrying'))) + .find('[data-testid="run-detail-retry"]') + .exists(), + ).toBe(false) + }) + + it("shows the server's reason when the retry is refused", async () => { + const wrapper = await mountDetail(run('failed-permanent')) + axios.post.mockRejectedValue({ + response: { status: 404, data: { error: 'Run not found' } }, + }) + + await wrapper.find('[data-testid="run-detail-retry"]').trigger('click') + await flushPromises() + + expect(wrapper.find('[data-testid="run-detail-error"]').text()).toBe( + 'Run not found', + ) + }) +}) diff --git a/src/modals/__tests__/ScheduledExportModal.spec.js b/src/modals/__tests__/ScheduledExportModal.spec.js new file mode 100644 index 000000000..9234237d1 --- /dev/null +++ b/src/modals/__tests__/ScheduledExportModal.spec.js @@ -0,0 +1,300 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * ScheduledExportModal (scheduled-exports task 12): a new export is POSTed + * and an existing one PATCHed to the export API in the shape + * ScheduledExportService::validate() and RecurrenceResolver::validate() + * accept; a 400 shows the server's reason. Only HTTP, the router and l10n + * are mocked; the store is the real one. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import ScheduledExportModal from '../ScheduledExportModal.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, + generateRemoteUrl: (service) => `/remote.php/${service}`, +})) +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) +vi.mock( + '@conduction/nextcloud-vue', + () => import('./helpers/scheduledExportStubs.js'), +) + +const BASE = '/index.php/apps/launchpad/api/exports' + +const subjects = [ + { type: 'dashboard', id: 'd-1', label: 'Bezwaren' }, + { type: 'widget', id: '7', label: 'KPI' }, +] + +/** + * Mount the editor. + * + * @param {object} props Extra props. + * @return {object} The wrapper. + */ +function mountEditor(props = {}) { + return mount(ScheduledExportModal, { + props: { + open: true, + subjects, + defaultSubject: { type: 'dashboard', id: 'd-1' }, + ...props, + }, + }) +} + +const byTestId = (wrapper, id) => wrapper.find(`[data-testid="${id}"]`) + +describe('ScheduledExportModal', () => { + beforeEach(() => { + vi.clearAllMocks() + setActivePinia(createPinia()) + }) + + it('creates a weekly PDF-by-email export with a POST in the validated shape', async () => { + axios.post.mockResolvedValue({ data: { id: 'e1', name: 'Weekly bezwaren' } }) + const wrapper = mountEditor() + + await byTestId(wrapper, 'export-name').setValue('Weekly bezwaren') + await byTestId(wrapper, 'export-day-WE').find('input').setValue(true) + await byTestId(wrapper, 'export-time').setValue('08:30') + await byTestId(wrapper, 'export-timezone').setValue('Europe/Amsterdam') + await byTestId(wrapper, 'export-recipient-addresses').setValue( + 'wethouder@gemeente.nl, griffie@gemeente.nl', + ) + expect(byTestId(wrapper, 'export-recurrence-summary').text()).toBe( + 'Runs every Monday, Wednesday at 08:30.', + ) + + await byTestId(wrapper, 'export-save').trigger('click') + await flushPromises() + + expect(axios.post).toHaveBeenCalledTimes(1) + const [url, body] = axios.post.mock.calls[0] + expect(url).toBe(BASE) + expect(body).toEqual({ + name: 'Weekly bezwaren', + description: '', + enabled: true, + subjectType: 'dashboard', + subjectId: 'd-1', + runTimezone: 'Europe/Amsterdam', + recurrence: { + type: 'weekly', + daysOfWeek: ['MO', 'WE'], + timeOfDay: '08:30', + }, + renderTargets: [ + { + format: 'pdf', + formatOptions: { + pageSize: 'A4', + orientation: 'portrait', + header: true, + footer: true, + }, + filenamePattern: '{name}-{date}.{ext}', + }, + ], + recipients: [ + { + enabled: true, + channel: 'email', + channelConfig: { + addresses: ['wethouder@gemeente.nl', 'griffie@gemeente.nl'], + }, + }, + ], + }) + expect(wrapper.emitted('saved')[0][0]).toEqual({ + id: 'e1', + name: 'Weekly bezwaren', + }) + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it("shows the server's validation error and stays open", async () => { + axios.post.mockRejectedValue({ + response: { + status: 400, + data: { + error: 'invalid_argument', + message: 'The name is required and at most 255 characters.', + }, + }, + }) + const wrapper = mountEditor() + + await byTestId(wrapper, 'export-save').trigger('click') + await flushPromises() + + const alert = byTestId(wrapper, 'export-editor-error') + expect(alert.exists()).toBe(true) + expect(alert.attributes('role')).toBe('alert') + expect(alert.text()).toBe('The name is required and at most 255 characters.') + expect(wrapper.emitted('close')).toBeUndefined() + expect(wrapper.emitted('saved')).toBeUndefined() + }) + + it('edits an export with a PATCH, keeping redacted secrets and the filter context', async () => { + axios.patch.mockResolvedValue({ data: { id: 'e9', name: 'CBS return' } }) + const exportData = { + id: 'e9', + name: 'CBS return', + description: 'Maandelijks', + enabled: true, + subjectType: 'widget', + subjectId: '7', + runTimezone: 'Europe/Amsterdam', + recurrence: { type: 'monthly', dayOfMonth: 1, timeOfDay: '08:00' }, + nextRunAt: '2026-12-01T08:00:00+01:00', + renderTargets: [ + { + format: 'xlsx', + formatOptions: { sheetPerWidget: true }, + filenamePattern: 'cbs-{date}.{ext}', + }, + ], + recipients: [ + { + id: 'r1', + enabled: true, + channel: 'sftp', + filterContext: { gemeenteCode: 'GM0355' }, + channelConfig: { + host: 'sftp.cbs.nl', + port: 22, + username: 'gm0355', + password: '********', + remotePath: '/dropbox', + }, + retryPolicy: { maxAttempts: 3 }, + }, + ], + } + const wrapper = mountEditor({ exportData }) + + expect(byTestId(wrapper, 'export-name').element.value).toBe('CBS return') + expect( + wrapper.findComponent({ name: 'NcPasswordField' }).props('helperText'), + ).toBe('Saved. Leave it as it is to keep it, or type a new one.') + + await byTestId(wrapper, 'export-last-day').find('input').setValue(true) + await byTestId(wrapper, 'field-host').setValue('sftp2.cbs.nl') + await byTestId(wrapper, 'export-filter-add').trigger('click') + const filters = wrapper.findAll('[data-testid="export-filter"]') + expect(filters).toHaveLength(2) + await filters[1].find('[data-testid="export-filter-field"]').setValue('jaar') + await filters[1].find('[data-testid="export-filter-value"]').setValue('2026') + + await byTestId(wrapper, 'export-save').trigger('click') + await flushPromises() + + const [url, body] = axios.patch.mock.calls[0] + expect(url).toBe(`${BASE}/e9`) + expect(body.id).toBe('e9') + expect(body.nextRunAt).toBeUndefined() + expect(body.subjectType).toBe('widget') + expect(body.subjectId).toBe('7') + expect(body.recurrence).toEqual({ + type: 'monthly', + lastDay: true, + timeOfDay: '08:00', + }) + expect(body.renderTargets).toEqual([ + { + format: 'xlsx', + formatOptions: { sheetPerWidget: true }, + filenamePattern: 'cbs-{date}.{ext}', + }, + ]) + expect(body.recipients).toEqual([ + { + id: 'r1', + enabled: true, + channel: 'sftp', + retryPolicy: { maxAttempts: 3 }, + filterContext: { gemeenteCode: 'GM0355', jaar: '2026' }, + channelConfig: { + host: 'sftp2.cbs.nl', + port: 22, + username: 'gm0355', + password: '********', + remotePath: '/dropbox', + }, + }, + ]) + }) + + it('sends a cron recurrence with only its expression', async () => { + axios.post.mockResolvedValue({ data: { id: 'e2' } }) + const wrapper = mountEditor() + + await byTestId(wrapper, 'export-recurrence-type').setValue( + 'Custom (cron expression)', + ) + expect(byTestId(wrapper, 'export-time').exists()).toBe(false) + await byTestId(wrapper, 'export-cron').setValue('0 2 * * 1-5') + await byTestId(wrapper, 'export-save').trigger('click') + await flushPromises() + + expect(axios.post.mock.calls[0][1].recurrence).toEqual({ + type: 'cron', + expression: '0 2 * * 1-5', + }) + }) + + it('adds a render target with its own format options and a webhook recipient', async () => { + axios.post.mockResolvedValue({ data: { id: 'e3' } }) + const wrapper = mountEditor() + + expect( + byTestId(wrapper, 'export-target-remove').attributes('disabled'), + ).toBeDefined() + await byTestId(wrapper, 'export-target-add').trigger('click') + const targets = wrapper.findAll('[data-testid="export-target"]') + expect(targets).toHaveLength(2) + await targets[1] + .find('[data-testid="export-target-format"]') + .setValue('CSV table') + await targets[1] + .find('[data-testid="field-delimiter"]') + .setValue('Semicolon (;)') + + await byTestId(wrapper, 'export-recipient-channel').setValue('Webhook') + expect(byTestId(wrapper, 'export-recipient-addresses').exists()).toBe(false) + await byTestId(wrapper, 'field-url').setValue('https://hooks.example.org/lp') + await byTestId(wrapper, 'export-save').trigger('click') + await flushPromises() + + const body = axios.post.mock.calls[0][1] + expect(body.renderTargets.map((target) => target.format)).toEqual([ + 'pdf', + 'csv', + ]) + expect(body.renderTargets[1].formatOptions).toEqual({ + delimiter: ';', + quoteChar: '"', + }) + // The empty signing secret is not sent, so nothing is stored for it. + expect(body.recipients).toEqual([ + { + enabled: true, + channel: 'webhook', + channelConfig: { url: 'https://hooks.example.org/lp' }, + }, + ]) + }) +}) diff --git a/src/modals/__tests__/SetupWizardModal.spec.js b/src/modals/__tests__/SetupWizardModal.spec.js index 1133ad915..e8441ad9e 100644 --- a/src/modals/__tests__/SetupWizardModal.spec.js +++ b/src/modals/__tests__/SetupWizardModal.spec.js @@ -3,9 +3,9 @@ * SPDX-License-Identifier: EUPL-1.2 * * Vitest unit tests for `SetupWizardModal.vue`. Covers REQ-WIZ-002 - * (multi-step shell), REQ-WIZ-003 (storage backend persistence on - * Step 2 → Next), REQ-WIZ-008 (state load on mount), and REQ-WIZ-009 - * (Finish triggers `completeSetupWizard`). + * (six-step shell; the storage step was retired by decision 131), + * REQ-WIZ-008 (state load on mount), and REQ-WIZ-009 (Finish triggers + * `completeSetupWizard`). * * The `api` module is mocked at the import boundary so no HTTP traffic * is generated. The embedded `GroupPriorityOrder` is stubbed to avoid @@ -20,8 +20,11 @@ import { api } from '../../services/api.js' vi.mock('../../services/api.js', () => ({ api: { getSetupWizardState: vi.fn(), - setSetupWizardStorage: vi.fn(), completeSetupWizard: vi.fn(), + listDemoShowcases: vi.fn(), + installDemoShowcase: vi.fn(), + getAdminGroups: vi.fn(), + assignAdminRoleToGroup: vi.fn(), }, })) @@ -51,17 +54,23 @@ beforeEach(() => { data: { complete: false, currentRecommendedStep: 1, - contentStorage: 'database', - groupfolderAvailable: true, stepStatuses: { 1: 'done', 2: 'pending' }, }, }) - api.setSetupWizardStorage - .mockReset() - .mockResolvedValue({ data: { complete: false } }) api.completeSetupWizard .mockReset() .mockResolvedValue({ data: { complete: true } }) + api.listDemoShowcases.mockReset().mockResolvedValue({ + data: [ + { id: 'engineering', name: 'Engineering', language: 'en', description: '', isInstalled: false }, + { id: 'sales', name: 'Sales', language: 'en', description: '', isInstalled: true }, + ], + }) + api.installDemoShowcase.mockReset().mockResolvedValue({ data: {} }) + api.getAdminGroups.mockReset().mockResolvedValue({ + data: { active: ['engineering'], inactive: ['sales', 'marketing'] }, + }) + api.assignAdminRoleToGroup.mockReset().mockResolvedValue({ data: {} }) }) function mountWizard() { @@ -87,7 +96,7 @@ describe('SetupWizardModal', () => { expect(api.getSetupWizardState).toHaveBeenCalledOnce() }) - it('REQ-WIZ-002: starts at step 1 with the counter rendered', async () => { + it('REQ-WIZ-012: starts at step 1 with the counter rendered', async () => { const wrapper = mountWizard() await flush() @@ -97,7 +106,7 @@ describe('SetupWizardModal', () => { expect(wrapper.find('[data-test="setup-wizard-counter"]').exists()).toBe( true, ) - expect(wrapper.vm.totalSteps).toBe(7) + expect(wrapper.vm.totalSteps).toBe(5) }) it('REQ-WIZ-002: Next advances; Back returns; counter updates', async () => { @@ -112,30 +121,26 @@ describe('SetupWizardModal', () => { expect(wrapper.vm.currentStep).toBe(1) }) - it('REQ-WIZ-003: Step 2 Next persists the storage choice via the API', async () => { + it('decision 131: Step 2 is the group order and no storage step renders', async () => { const wrapper = mountWizard() await flush() - // Advance to Step 2. await wrapper.find('[data-test="setup-wizard-next"]').trigger('click') await flush() expect(wrapper.vm.currentStep).toBe(2) - - // Change selection then click Next. - wrapper.vm.storage = 'groupfolder' - await wrapper.find('[data-test="setup-wizard-next"]').trigger('click') - await flush() - - expect(api.setSetupWizardStorage).toHaveBeenCalledWith('groupfolder') - expect(wrapper.vm.currentStep).toBe(3) + expect(wrapper.find('.group-priority-stub').exists()).toBe(true) + expect(wrapper.find('[data-test="storage-database"]').exists()).toBe(false) + expect(wrapper.find('[data-test="storage-groupfolder"]').exists()).toBe( + false, + ) }) - it('REQ-WIZ-002: Step 7 Next is labelled Finish and calls completeSetupWizard', async () => { + it('REQ-WIZ-012: Step 5 Next is labelled Finish and calls completeSetupWizard', async () => { const wrapper = mountWizard() await flush() - // Jump straight to step 7 to keep the test focused. - wrapper.vm.currentStep = 7 + // Jump straight to step 5 to keep the test focused. + wrapper.vm.currentStep = 5 await flush() // The Vue mixin's t() stub returns the bare key; the component @@ -150,35 +155,125 @@ describe('SetupWizardModal', () => { expect(wrapper.emitted('close')).toBeTruthy() }) - it('REQ-WIZ-003: GroupFolder radio is disabled when the app is missing', async () => { + it('REQ-WIZ-002: Skip advances without committing on optional steps', async () => { + const wrapper = mountWizard() + await flush() + wrapper.vm.currentStep = 4 + await flush() + + await wrapper.find('[data-test="setup-wizard-skip"]').trigger('click') + expect(wrapper.vm.currentStep).toBe(5) + expect(wrapper.vm.isFinalStep).toBe(true) + expect(api.completeSetupWizard).not.toHaveBeenCalled() + }) + + it('REQ-WIZ-012: no step shows the footer editor', async () => { + const wrapper = mountWizard() + await flush() + + for (let step = 1; step <= 5; step++) { + wrapper.vm.currentStep = step + await flush() + expect(wrapper.find('[data-test="footer-stub"]').exists()).toBe(false) + expect(wrapper.text()).not.toContain('Footer configuration') + } + }) + + it('REQ-WIZ-012: the welcome step names groups, example dashboards and roles', async () => { + const wrapper = mountWizard() + await flush() + + expect(wrapper.text()).toContain( + 'This setup sets the groups, the example dashboards and the roles, in five steps. Existing dashboards stay as they are.', + ) + }) + + it('REQ-WIZ-012: a recommended step past five opens the last step', async () => { api.getSetupWizardState.mockResolvedValueOnce({ - data: { - complete: false, - currentRecommendedStep: 1, - contentStorage: 'database', - groupfolderAvailable: false, - stepStatuses: { 1: 'done' }, - }, + data: { complete: false, currentRecommendedStep: 6 }, }) const wrapper = mountWizard() await flush() - // Advance to step 2. + expect(wrapper.vm.currentStep).toBe(5) + }) + it('REQ-WIZ-005: Next on Step 3 installs only the checked demos that are not installed', async () => { + const wrapper = mountWizard() + await flush() + wrapper.vm.currentStep = 3 + await flush() + wrapper.vm.onDemoChoose('engineering', true) + wrapper.vm.onDemoChoose('sales', false) + expect(api.installDemoShowcase).not.toHaveBeenCalled() + await wrapper.find('[data-test="setup-wizard-next"]').trigger('click') await flush() + expect(api.installDemoShowcase).toHaveBeenCalledTimes(1) + expect(api.installDemoShowcase).toHaveBeenCalledWith('engineering') + expect(wrapper.vm.currentStep).toBe(4) + }) - const radio = wrapper.find('[data-test="storage-groupfolder"]') - expect(radio.attributes('disabled')).toBeDefined() + it('REQ-WIZ-005: the demo choice survives Back from Step 4', async () => { + const wrapper = mountWizard() + await flush() + wrapper.vm.currentStep = 3 + await flush() + wrapper.vm.onDemoChoose('engineering', true) + await wrapper.find('[data-test="setup-wizard-next"]').trigger('click') + await flush() + await wrapper.find('[data-test="setup-wizard-back"]').trigger('click') + await flush() + expect(wrapper.vm.currentStep).toBe(3) + expect(wrapper.vm.demoChoice).toEqual({ engineering: true }) + expect(api.installDemoShowcase).toHaveBeenCalledTimes(1) }) - it('REQ-WIZ-002: Skip advances without committing on optional steps', async () => { + it('REQ-WIZ-005: Next with nothing checked installs nothing', async () => { + const wrapper = mountWizard() + await flush() + wrapper.vm.currentStep = 3 + await flush() + await wrapper.find('[data-test="setup-wizard-next"]').trigger('click') + await flush() + expect(api.installDemoShowcase).not.toHaveBeenCalled() + expect(wrapper.vm.currentStep).toBe(4) + }) + + it('REQ-WIZ-006: Step 4 offers every group and gives the chosen one the admin role on Next', async () => { const wrapper = mountWizard() await flush() wrapper.vm.currentStep = 4 await flush() + expect(wrapper.vm.roleGroups).toEqual(['engineering', 'sales', 'marketing']) - await wrapper.find('[data-test="setup-wizard-skip"]').trigger('click') + wrapper.vm.roleGroup = 'sales' + await wrapper.find('[data-test="setup-wizard-next"]').trigger('click') + await flush() + expect(api.assignAdminRoleToGroup).toHaveBeenCalledOnce() + expect(api.assignAdminRoleToGroup).toHaveBeenCalledWith('sales') + expect(wrapper.vm.currentStep).toBe(5) + }) + + it('REQ-WIZ-006: Next on Step 4 without a group assigns nothing', async () => { + const wrapper = mountWizard() + await flush() + wrapper.vm.currentStep = 4 + await flush() + await wrapper.find('[data-test="setup-wizard-next"]').trigger('click') + await flush() + expect(api.assignAdminRoleToGroup).not.toHaveBeenCalled() + expect(wrapper.vm.currentStep).toBe(5) + }) + + it('REQ-WIZ-006: a group that already has the role still moves on', async () => { + api.assignAdminRoleToGroup.mockRejectedValueOnce({ response: { status: 409 } }) + const wrapper = mountWizard() + await flush() + wrapper.vm.currentStep = 4 + await flush() + wrapper.vm.roleGroup = 'sales' + await wrapper.find('[data-test="setup-wizard-next"]').trigger('click') + await flush() expect(wrapper.vm.currentStep).toBe(5) - expect(api.setSetupWizardStorage).not.toHaveBeenCalled() }) }) diff --git a/src/modals/__tests__/TemplateEditorModal.spec.js b/src/modals/__tests__/TemplateEditorModal.spec.js new file mode 100644 index 000000000..173e57e78 --- /dev/null +++ b/src/modals/__tests__/TemplateEditorModal.spec.js @@ -0,0 +1,233 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `TemplateEditorModal.vue`: seeding the working copy + * from the `template` prop on open, the create/edit title, and saving + * through the create or update endpoint. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import TemplateEditorModal from '../TemplateEditorModal.vue' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => key })) +vi.mock('../../services/api.js', () => ({ + api: { + createAdminTemplate: vi.fn(), + updateAdminTemplate: vi.fn(), + getAdminGroups: vi.fn(() => Promise.resolve({ data: { active: ['sales'], inactive: ['hr', 'it'] } })), + }, +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { error: vi.fn() }, +})) + +const ButtonStub = { + emits: ['click'], + template: '<button class="btn" @click="$emit(\'click\')"><slot /></button>', +} + +const stubs = { + NcModal: { + name: 'NcModal', + props: ['name'], + emits: ['close'], + template: '<div class="nc-modal-stub" :data-name="name"><slot /></div>', + }, + NcButton: ButtonStub, + NcTextField: true, + NcSelect: true, + NcCheckboxRadioSwitch: true, +} + +function mountModal(props = {}) { + return mount(TemplateEditorModal, { + propsData: { open: true, template: null, ...props }, + stubs, + }) +} + +/** + * Click the button whose text is `label`. + * + * @param {object} wrapper the mounted modal. + * @param {string} label the button text. + */ +async function click(wrapper, label) { + const button = wrapper.findAll('button.btn').find((b) => b.text() === label) + await button.trigger('click') + await flushPromises() +} + +beforeEach(() => { + api.createAdminTemplate.mockReset().mockResolvedValue({}) + api.updateAdminTemplate.mockReset().mockResolvedValue({}) + logger.error.mockReset() +}) + +describe('TemplateEditorModal', () => { + it('renders nothing while closed', () => { + expect(mountModal({ open: false }).find('.nc-modal-stub').exists()).toBe(false) + }) + + it('opens a blank create form with the add-only permission', () => { + const wrapper = mountModal() + + expect(wrapper.vm.form).toEqual({ + id: null, + name: '', + description: '', + targetGroups: [], + permissionLevel: { id: 'add_only', label: 'Add only' }, + isDefault: false, + }) + expect(wrapper.vm.isEdit).toBe(false) + expect(wrapper.find('h2').text()).toBe('Create template') + }) + + it('seeds an edit form from the template, mapping the permission id to its option', () => { + const wrapper = mountModal({ + template: { id: 7, name: 'Sales', description: 'd', targetGroups: ['sales'], permissionLevel: 'full', isDefault: true }, + }) + + expect(wrapper.vm.form).toEqual({ + id: 7, + name: 'Sales', + description: 'd', + targetGroups: ['sales'], + permissionLevel: { id: 'full', label: 'Full customization' }, + isDefault: true, + }) + expect(wrapper.vm.isEdit).toBe(true) + expect(wrapper.find('h2').text()).toBe('Edit template') + expect(wrapper.find('.nc-modal-stub').attributes('data-name')).toBe('Edit template') + }) + + it('falls back to add-only for an unknown permission level', () => { + const wrapper = mountModal({ template: { id: 1, name: 'x', permissionLevel: 'bogus' } }) + expect(wrapper.vm.form.permissionLevel).toEqual({ id: 'add_only', label: 'Add only' }) + }) + + it('re-seeds when reopened, dropping unsaved edits', async () => { + const wrapper = mountModal({ template: { id: 2, name: 'Original', permissionLevel: 'view_only' } }) + wrapper.vm.form.name = 'Edited but cancelled' + + await wrapper.setProps({ open: false }) + await wrapper.setProps({ open: true }) + + expect(wrapper.vm.form.name).toBe('Original') + }) + + it('re-seeds when the template changes while open, but not while closed', async () => { + const wrapper = mountModal({ template: { id: 2, name: 'A' } }) + await wrapper.setProps({ template: { id: 3, name: 'B' } }) + expect(wrapper.vm.form.name).toBe('B') + + await wrapper.setProps({ open: false }) + wrapper.vm.form.name = 'kept' + await wrapper.setProps({ template: { id: 4, name: 'C' } }) + expect(wrapper.vm.form.name).toBe('kept') + }) + + it('creates a new template with the permission id and emits saved', async () => { + const wrapper = mountModal() + Object.assign(wrapper.vm.form, { name: 'New', description: 'desc', targetGroups: ['g'], isDefault: true }) + + await click(wrapper, 'Save') + + expect(api.createAdminTemplate).toHaveBeenCalledWith({ + name: 'New', + description: 'desc', + targetGroups: ['g'], + permissionLevel: 'add_only', + isDefault: true, + }) + expect(api.updateAdminTemplate).not.toHaveBeenCalled() + expect(wrapper.emitted('saved')).toHaveLength(1) + }) + + it('updates an existing template by id', async () => { + const wrapper = mountModal({ + template: { id: 9, name: 'T', description: '', targetGroups: [], permissionLevel: 'view_only', isDefault: false }, + }) + + await click(wrapper, 'Save') + + expect(api.updateAdminTemplate).toHaveBeenCalledWith(9, { + name: 'T', + description: '', + targetGroups: [], + permissionLevel: 'view_only', + isDefault: false, + }) + expect(api.createAdminTemplate).not.toHaveBeenCalled() + expect(wrapper.emitted('saved')).toHaveLength(1) + }) + + it('logs a failed save and does not emit saved', async () => { + const failure = new Error('500') + api.createAdminTemplate.mockRejectedValue(failure) + const wrapper = mountModal() + + await click(wrapper, 'Save') + + expect(logger.error).toHaveBeenCalledWith('Failed to save template:', failure) + expect(wrapper.emitted('saved')).toBeUndefined() + }) + + it('saves what the user enters in the form controls, and closes from the modal', async () => { + const field = (name) => ({ name, props: ['modelValue', 'label'], emits: ['update:modelValue'], template: '<div />' }) + const wrapper = mount(TemplateEditorModal, { + propsData: { open: true, template: null }, + stubs: { + ...stubs, + NcTextField: field('NcTextField'), + NcSelect: field('NcSelect'), + NcCheckboxRadioSwitch: field('NcCheckboxRadioSwitch'), + }, + }) + + const [name, description] = wrapper.findAllComponents({ name: 'NcTextField' }) + name.vm.$emit('update:modelValue', 'Onboarding') + description.vm.$emit('update:modelValue', 'For new staff') + const [groups, permission] = wrapper.findAllComponents({ name: 'NcSelect' }) + groups.vm.$emit('update:modelValue', ['hr', 'it']) + permission.vm.$emit('update:modelValue', { id: 'view_only', label: 'View only' }) + wrapper.findComponent({ name: 'NcCheckboxRadioSwitch' }).vm.$emit('update:modelValue', true) + await click(wrapper, 'Save') + + expect(api.createAdminTemplate).toHaveBeenCalledWith({ + name: 'Onboarding', + description: 'For new staff', + targetGroups: ['hr', 'it'], + permissionLevel: 'view_only', + isDefault: true, + }) + + wrapper.findComponent({ name: 'NcModal' }).vm.$emit('close') + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('emits close from Cancel', async () => { + const wrapper = mountModal() + await click(wrapper, 'Cancel') + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('offers every Nextcloud group id as a target group', async () => { + const wrapper = mountModal() + await flushPromises() + expect(api.getAdminGroups).toHaveBeenCalled() + expect(wrapper.vm.availableGroups).toEqual(['sales', 'hr', 'it']) + }) + + it('draws the target groups field over the full width, so a chosen group leaves room to click', async () => { + const wrapper = mountModal() + await flushPromises() + const [groups] = wrapper.findAllComponents({ name: 'NcSelect' }) + expect(groups.classes()).toContain('launchpad-admin__target-groups') + }) +}) diff --git a/src/modals/__tests__/TemplateResyncModal.spec.js b/src/modals/__tests__/TemplateResyncModal.spec.js index 0354b3452..883c024ba 100644 --- a/src/modals/__tests__/TemplateResyncModal.spec.js +++ b/src/modals/__tests__/TemplateResyncModal.spec.js @@ -2,10 +2,13 @@ * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> * SPDX-License-Identifier: EUPL-1.2 * - * Vitest tests for `TemplateResyncModal.vue` (admin-template-resync). - * Covers: Apply gated behind a completed Dry-run for the current - * strategy, strategy selection binding, and strategy-change resetting - * a stale plan. + * Vitest tests for `TemplateResyncModal.vue`, the rollout window + * (admin-templates REQ-RESYNC-008, board LpBeheerSjablonen). + * Covers: the dry run on open for Keep personal changes, the change summary + * and changed-copies count, the three choices, a fresh dry run per choice, + * the push button naming the dashboards, and a stale answer being dropped. + * + * @spec openspec/changes/archive/2026-11-25-template-rollout-choices/specs/admin-templates/spec.md#requirement-req-resync-008-the-rollout-window-says-what-will-happen */ import { mount } from '@vue/test-utils' @@ -23,32 +26,28 @@ vi.mock('../../services/api.js', () => ({ })) const stubs = { - NcModal: { template: '<div class="nc-modal"><slot /></div>' }, + NcModal: { + props: ['name'], + template: '<div class="nc-modal" :data-name="name"><slot /></div>', + }, NcButton: { emits: ['click'], template: '<button class="nc-button" :data-testid="$attrs[\'data-testid\']" :disabled="$attrs.disabled" @click="$emit(\'click\')"><slot /></button>', }, - // Vue 3 renamed the `v-model` contract: the prop is `modelValue` - // (was `value`) and the event is `update:modelValue` (was `input`). - // The component under test uses `v-model="strategy"`, so a stub still - // emitting `input` never writes back — `strategy` stayed on its - // initial option and the plan-reset assertions failed. - NcSelect: { - props: ['modelValue', 'options'], - emits: ['update:modelValue'], - template: - '<select class="nc-select" :data-testid="$attrs[\'data-testid\']" @change="onChange"><option v-for="o in options" :key="o.id" :value="o.id">{{ o.label }}</option></select>', - methods: { - onChange(event) { - const opt = this.options.find((o) => o.id === event.target.value) - this.$emit('update:modelValue', opt) - }, - }, - }, NcLoadingIcon: { template: '<div class="nc-loading" />' }, } +const PLAN = { + templateId: 1, + totalCopies: 212, + affectedCount: 200, + copies: [], + gained: ['Leesbevestiging', 'Verjaardagen'], + lost: ['Oud nieuws'], + changedByOwnerCount: 38, +} + let TemplateResyncModal beforeEach(async () => { @@ -60,98 +59,150 @@ beforeEach(async () => { TemplateResyncModal = (await import('../TemplateResyncModal.vue')).default }) +async function flush (wrapper) { + await new Promise((resolve) => setTimeout(resolve, 0)) + await wrapper.vm.$nextTick() +} + function mountModal(propsData = {}) { return mount(TemplateResyncModal, { propsData: { open: true, - template: { id: 1, name: 'Marketing Dashboard' }, + template: { id: 1, name: 'Intranet medewerkers' }, ...propsData, }, stubs, }) } -describe('TemplateResyncModal', () => { - it('disables Apply until a dry-run has been reviewed', async () => { - const wrapper = mountModal() - const apply = wrapper.find('[data-testid="template-resync-apply"]') - expect(apply.attributes('disabled')).toBeDefined() - }) - - it('enables Apply once a dry-run resolves, and calls the API with dryRun:true', async () => { - resyncAdminTemplateMock.mockResolvedValueOnce({ - data: { totalCopies: 8, affectedCount: 3, copies: [] }, - }) +const apply = (w) => w.find('[data-testid="template-resync-apply"]') +describe('TemplateResyncModal (rollout window)', () => { + it('runs a dry run for Keep personal changes on open and keeps the push disabled until it answers', async () => { + resyncAdminTemplateMock.mockReturnValueOnce(new Promise(() => {})) const wrapper = mountModal() - await wrapper.find('[data-testid="template-resync-dryrun"]').trigger('click') - await new Promise((resolve) => setTimeout(resolve, 0)) - await wrapper.vm.$nextTick() expect(resyncAdminTemplateMock).toHaveBeenCalledWith(1, { - strategy: 'overwrite', + strategy: 'merge', dryRun: true, }) + expect( + wrapper.find('[data-testid="template-resync-choice-merge"]').element.checked, + ).toBe(true) + expect( + wrapper.find('[data-testid="template-resync-choice-add_only"]').element.checked, + ).toBe(false) + expect(apply(wrapper).attributes('disabled')).toBeDefined() + }) - const apply = wrapper.find('[data-testid="template-resync-apply"]') - expect(apply.attributes('disabled')).toBeUndefined() + it('says what the template gained and lost, how many people changed their copy, and names the dashboards', async () => { + resyncAdminTemplateMock.mockResolvedValueOnce({ data: PLAN }) + const wrapper = mountModal() + await flush(wrapper) + + expect(wrapper.find('[data-testid="template-resync-title"]').text()).toBe( + 'Push changes to 212 dashboards', + ) + expect(wrapper.find('[data-testid="template-resync-template"]').text()).toBe( + 'Template "Intranet medewerkers" has 212 copies.', + ) + expect(wrapper.find('[data-testid="template-resync-gained"]').text()).toBe( + 'Added since the last sync: Leesbevestiging, Verjaardagen', + ) + expect(wrapper.find('[data-testid="template-resync-lost"]').text()).toBe( + 'Removed since the last sync: Oud nieuws', + ) + expect( + wrapper.find('[data-testid="template-resync-changed-count"]').text(), + ).toBe('38 people changed their dashboard.') + expect(apply(wrapper).text()).toBe('Push to 212 dashboards') + expect(apply(wrapper).attributes('disabled')).toBeUndefined() }) - it('resets the plan (re-disabling Apply) when the strategy changes after a dry-run', async () => { + it('offers the three choices, each with its consequence', async () => { + resyncAdminTemplateMock.mockResolvedValueOnce({ data: PLAN }) + const wrapper = mountModal() + await flush(wrapper) + + const text = wrapper.find('[data-testid="template-resync-strategy"]').text() + expect(text).toContain('How to update?') + expect(text).toContain('Only add new widgets') + expect(text).toContain('Nothing disappears; personal layout stays.') + expect(text).toContain('Keep personal changes') + expect(text).toContain('The template wins, except what someone moved or added themselves.') + expect(text).toContain('Replace everything with the template') + expect(text).toContain('Personal changes are lost.') + }) + + it('says nothing changed when the template gained and lost nothing', async () => { resyncAdminTemplateMock.mockResolvedValueOnce({ - data: { totalCopies: 8, affectedCount: 3, copies: [] }, + data: { ...PLAN, gained: [], lost: [], changedByOwnerCount: 0 }, }) - const wrapper = mountModal() - await wrapper.find('[data-testid="template-resync-dryrun"]').trigger('click') - await new Promise((resolve) => setTimeout(resolve, 0)) - await wrapper.vm.$nextTick() - - expect( - wrapper - .find('[data-testid="template-resync-apply"]') - .attributes('disabled'), - ).toBeUndefined() - - // Switch strategy — the previous plan no longer applies. - await wrapper - .find('[data-testid="template-resync-strategy"]') - .setValue('merge') + await flush(wrapper) - expect(wrapper.vm.strategy.id).toBe('merge') - expect( - wrapper - .find('[data-testid="template-resync-apply"]') - .attributes('disabled'), - ).toBeDefined() + expect(wrapper.find('[data-testid="template-resync-no-changes"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="template-resync-changed-count"]').exists()).toBe(false) }) - it('applies with dryRun:false using the selected strategy and emits "resynced"', async () => { + it('runs a fresh dry run for another choice and pushes with that strategy', async () => { resyncAdminTemplateMock - .mockResolvedValueOnce({ - data: { totalCopies: 8, affectedCount: 3, copies: [] }, - }) - .mockResolvedValueOnce({ - data: { async: false, affectedCount: 3, totalCopies: 8 }, - }) - + .mockResolvedValueOnce({ data: PLAN }) + .mockResolvedValueOnce({ data: { ...PLAN, affectedCount: 150 } }) + .mockResolvedValueOnce({ data: { async: false, affectedCount: 150, totalCopies: 212 } }) const wrapper = mountModal() - await wrapper.find('[data-testid="template-resync-dryrun"]').trigger('click') - await new Promise((resolve) => setTimeout(resolve, 0)) - await wrapper.vm.$nextTick() + await flush(wrapper) - await wrapper.find('[data-testid="template-resync-apply"]').trigger('click') - await new Promise((resolve) => setTimeout(resolve, 0)) - await wrapper.vm.$nextTick() + await wrapper.find('[data-testid="template-resync-choice-add_only"]').trigger('change') + expect(resyncAdminTemplateMock).toHaveBeenLastCalledWith(1, { + strategy: 'add_only', + dryRun: true, + }) + await flush(wrapper) + expect(wrapper.vm.plan.strategy).toBe('add_only') + expect(apply(wrapper).attributes('disabled')).toBeUndefined() + await apply(wrapper).trigger('click') + await flush(wrapper) expect(resyncAdminTemplateMock).toHaveBeenLastCalledWith(1, { - strategy: 'overwrite', + strategy: 'add_only', dryRun: false, }) expect(wrapper.emitted('resynced')).toBeTruthy() + expect(wrapper.find('[data-testid="template-resync-success"]').text()).toBe( + 'Re-sync applied — 150 copies updated.', + ) + }) + + it('drops a slower answer for an earlier choice', async () => { + let resolveFirst + resyncAdminTemplateMock + .mockReturnValueOnce(new Promise((resolve) => { resolveFirst = resolve })) + .mockResolvedValueOnce({ data: { ...PLAN, totalCopies: 5 } }) + const wrapper = mountModal() + + await wrapper.find('[data-testid="template-resync-choice-overwrite"]').trigger('change') + await flush(wrapper) + resolveFirst({ data: PLAN }) + await flush(wrapper) + + expect(wrapper.vm.plan.strategy).toBe('overwrite') + expect(apply(wrapper).text()).toBe('Push to 5 dashboards') + }) + + it('shows an error and keeps the push disabled when the dry run fails', async () => { + resyncAdminTemplateMock.mockRejectedValueOnce(new Error('boom')) + const wrapper = mountModal() + await flush(wrapper) + + expect(wrapper.find('[data-testid="template-resync-error"]').text()).toBe( + 'Could not compute the re-sync plan.', + ) + expect(apply(wrapper).attributes('disabled')).toBeDefined() }) it('emits "close" when Close is clicked', async () => { + resyncAdminTemplateMock.mockResolvedValueOnce({ data: PLAN }) const wrapper = mountModal() await wrapper.find('[data-testid="template-resync-cancel"]').trigger('click') expect(wrapper.emitted('close')).toBeTruthy() diff --git a/src/modals/__tests__/TileEditor.boardSync.spec.js b/src/modals/__tests__/TileEditor.boardSync.spec.js new file mode 100644 index 000000000..ccc6c2f84 --- /dev/null +++ b/src/modals/__tests__/TileEditor.boardSync.spec.js @@ -0,0 +1,242 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The tile form as board LpTegelBewerken draws it (tile-form-board-sync): + * the heading and where line, the fields in order, the group and its sort + * order, the last availability check and the icon upload. + * + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import TileEditor from '../TileEditor.vue' +import { fetchHealthPingBadge } from '../../services/healthPingClient.js' +import { uploadFile } from '../../services/resourceService.js' + +vi.mock('../../services/healthPingClient.js', () => ({ validateHealthPingConfig: vi.fn(), fetchHealthPingBadge: vi.fn() })) +vi.mock('../../services/resourceService.js', () => ({ uploadFile: vi.fn() })) +vi.mock('../../services/iframeClient.js', () => ({ validateIframeUrl: vi.fn().mockResolvedValue({ valid: true, errors: [] }) })) + +const stubs = { + NcModal: { name: 'NcModal', props: ['show', 'name'], template: '<div class="modal" :data-name="name"><slot /></div>' }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label', 'disabled', 'helperText'], + emits: ['update:modelValue'], + template: '<input class="text-field field" :data-label="label" :disabled="disabled" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel', 'disabled'], + emits: ['update:modelValue'], + template: '<div class="select field" :data-label="inputLabel" :data-disabled="disabled ? \'yes\' : \'no\'" :data-value="modelValue"><button v-for="o in options" :key="o.value" class="option" :data-value="o.value" @click="$emit(\'update:modelValue\', o.value)">{{ o.label }}</button></div>', + }, + NcColorPicker: { name: 'NcColorPicker', template: '<div class="color-picker"><slot /></div>' }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'type'], + emits: ['update:modelValue'], + template: '<label class="switch field" :data-label="type === \'switch\' ? \'switch\' : \'\'" @click="$emit(\'update:modelValue\', !modelValue)"><slot /></label>', + }, + NcButton: { name: 'NcButton', props: ['disabled'], emits: ['click'], template: '<button class="button" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, + CnIconBrowser: { name: 'CnIconBrowser', template: '<div class="icon-browser" />' }, +} + +const caseSystem = { id: 7, title: 'Case system', linkType: 'sso', linkValue: '', linkTarget: 'new-tab', ssoTemplate: 'entra', ssoAppId: 'z1' } + +/** + * Mount the editor. + * + * @param {object|null} tile The tile. + * @param {object} [props] More props. + * @return {object} The wrapper. + */ +function mountEditor(tile, props = {}) { + return mount(TileEditor, { props: { open: true, tile, dashboardName: 'My workspace', ...props }, global: { stubs } }) +} + +/** + * A button by its text. + * + * @param {object} wrapper The wrapper. + * @param {string} text The text. + * @return {object|undefined} The button. + */ +function button(wrapper, text) { + return wrapper.findAll('button.button').find((b) => b.text() === text) +} + +describe('TileEditor as LpTegelBewerken draws it', () => { + const plainT = globalThis.t + + beforeEach(() => { + globalThis.t = (_app, key, vars) => key.replace(/\{(\w+)\}/g, (match, name) => (vars && name in vars ? String(vars[name]) : match)) + fetchHealthPingBadge.mockReset() + uploadFile.mockReset() + }) + + afterEach(() => { + globalThis.t = plainT + }) + + it('titles the form Edit tile: <name> under <group> · <dashboard>', () => { + const wrapper = mountEditor(caseSystem, { groupName: 'Work apps' }) + expect(wrapper.find('h2').text()).toBe('Edit tile: Case system') + expect(wrapper.find('.modal').attributes('data-name')).toBe('Edit tile: Case system') + expect(wrapper.find('[data-testid="tile-editor-where"]').text()).toBe('Work apps · My workspace') + expect(mountEditor(caseSystem).find('[data-testid="tile-editor-where"]').text()).toBe('No group · My workspace') + }) + + it('shows the fields in the board\'s order, with App with single sign-on and New tab chosen', () => { + const wrapper = mountEditor({ ...caseSystem, linkType: 'url', linkValue: 'https://zaak.example' }) + const html = wrapper.html() + const order = [ + 'data-label="Name"', + 'data-label="Group"', + 'data-testid="tile-link-type"', + 'data-label="Web address"', + 'data-label="Internal address (optional)"', + 'data-test="tile-editor-opens-in"', + 'tile-editor__icon', + 'Colour', + 'data-label="Sort order in this group"', + 'tile-editor__health-ping', + 'Delete tile', + ].map((needle) => html.indexOf(needle)) + expect(order.every((at) => at >= 0)).toBe(true) + expect([...order].sort((a, b) => a - b)).toEqual(order) + + const sso = mountEditor(caseSystem) + expect(sso.find('[data-testid="tile-link-type"] input[value="sso"]').element.checked).toBe(true) + expect(sso.find('[data-test="tile-editor-opens-in"] input[value="new-tab"]').element.checked).toBe(true) + }) + + it('puts Delete tile at the left and Cancel and Save at the right, and only for a saved tile', () => { + const actions = mountEditor(caseSystem).find('.tile-editor__actions') + expect(actions.element.firstElementChild.textContent.trim()).toBe('Delete tile') + expect(actions.find('.tile-editor__actions-right').findAll('button').map((b) => b.text())).toEqual(['Cancel', 'Save']) + expect(button(mountEditor(null), 'Delete tile')).toBeUndefined() + }) + + it('shows the group and the group\'s sort order, and saves the order with the tile', async () => { + const wrapper = mountEditor(caseSystem, { groupName: 'Work apps', groupSort: 'manual' }) + expect(wrapper.find('.text-field[data-label="Group"]').element.value).toBe('Work apps') + const sort = wrapper.find('.select[data-label="Sort order in this group"]') + expect(sort.attributes('data-disabled')).toBe('no') + expect(sort.attributes('data-value')).toBe('manual') + expect(sort.findAll('.option').map((o) => o.text())).toEqual(['Last used first', 'Alphabetical', 'Random', 'As placed']) + + await sort.find('.option[data-value="last-used"]').trigger('click') + await button(wrapper, 'Save').trigger('click') + expect(wrapper.emitted('save')[0][0].groupSortBy).toBe('last-used') + }) + + it('keeps a most-used group as it is, and offers no sort order outside a group', async () => { + const most = mountEditor(caseSystem, { groupName: 'Work apps', groupSort: 'most-used' }) + expect(most.find('.select[data-label="Sort order in this group"] .option[data-value="most-used"]').text()).toBe('Most used first') + + const loose = mountEditor(caseSystem) + expect(loose.find('.text-field[data-label="Group"]').element.value).toBe('No group') + expect(loose.find('.select[data-label="Sort order in this group"]').attributes('data-disabled')).toBe('yes') + await button(loose, 'Save').trigger('click') + expect(loose.emitted('save')[0][0]).not.toHaveProperty('groupSortBy') + }) + + it('in a group, offers only a web address and none of what needs a tile of its own', async () => { + const tile = { title: 'Intranet', linkType: 'url', linkValue: 'https://intranet.example.org' } + const wrapper = mountEditor(tile, { groupName: 'Work apps', groupSort: 'alphabetical', inGroup: true }) + expect(wrapper.findAll('[data-testid="tile-link-type"] input').map((input) => input.element.value)).toEqual(['url']) + expect(wrapper.find('.text-field[data-label="Internal address (optional)"]').exists()).toBe(false) + expect(wrapper.find('[data-test="tile-editor-opens-in"]').exists()).toBe(false) + expect(wrapper.find('.tile-editor__health-ping').exists()).toBe(false) + expect(wrapper.find('[data-testid="tile-in-group-hint"]').text()).toBe('A tile in a group opens its web address in a new tab.') + expect(wrapper.find('.text-field[data-label="Web address"]').exists()).toBe(true) + expect(wrapper.find('.select[data-label="Sort order in this group"]').attributes('data-value')).toBe('alphabetical') + + await button(wrapper, 'Save').trigger('click') + expect(wrapper.emitted('save')[0][0]).toMatchObject({ title: 'Intranet', linkValue: 'https://intranet.example.org', groupSortBy: 'alphabetical' }) + }) + + it('keeps an older type of a group tile selectable', () => { + const wrapper = mountEditor({ title: 'Files', linkType: 'app', linkValue: 'files' }, { groupName: 'Work apps', inGroup: true }) + expect(wrapper.findAll('[data-testid="tile-link-type"] input').map((input) => input.element.value)).toEqual(['app', 'url']) + }) + + it('outside a group still offers the four types, the internal address and the check', () => { + const wrapper = mountEditor(caseSystem) + expect(wrapper.findAll('[data-testid="tile-link-type"] input')).toHaveLength(4) + expect(wrapper.find('.tile-editor__health-ping').exists()).toBe(true) + expect(wrapper.find('[data-testid="tile-in-group-hint"]').exists()).toBe(false) + }) + + it('reads the last check under Check availability', async () => { + const at = new Date() + at.setHours(10, 40, 0, 0) + fetchHealthPingBadge.mockResolvedValue({ state: 'online', checkedAt: at.toISOString() }) + const wrapper = mountEditor({ ...caseSystem, healthPingEnabled: true, healthUrl: 'https://zaak.example/health' }) + await flushPromises() + + expect(fetchHealthPingBadge).toHaveBeenCalledWith(7) + expect(wrapper.find('.tile-editor__health-ping').text()).toContain('Check availability') + expect(wrapper.find('[data-testid="tile-last-check"]').text()).toBe('Reachable at the last check, today 10:40') + }) + + it('reads the last check once the switch is turned on, and says not checked yet when the read fails', async () => { + fetchHealthPingBadge.mockRejectedValue(new Error('404')) + const wrapper = mountEditor(caseSystem) + await flushPromises() + expect(fetchHealthPingBadge).not.toHaveBeenCalled() + + await wrapper.find('.tile-editor__health-ping .switch').trigger('click') + await flushPromises() + expect(fetchHealthPingBadge).toHaveBeenCalledWith(7) + expect(wrapper.find('[data-testid="tile-last-check"]').text()).toBe('Not checked yet') + }) + + it('shows no last check for a tile that is not saved yet', async () => { + const wrapper = mountEditor(null) + await wrapper.find('.tile-editor__health-ping .switch').trigger('click') + await flushPromises() + expect(fetchHealthPingBadge).not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="tile-last-check"]').exists()).toBe(false) + }) + + it('opens the icon list on demand and stores an uploaded icon as its URL', async () => { + const wrapper = mountEditor(caseSystem) + expect(wrapper.find('.icon-browser').exists()).toBe(false) + await wrapper.find('[data-testid="tile-icon-choose"]').trigger('click') + expect(wrapper.find('.icon-browser').exists()).toBe(true) + + uploadFile.mockResolvedValue({ url: '/apps/launchpad/resource/zaak.png', name: 'zaak.png', size: 10 }) + const input = wrapper.find('input[type="file"]') + const file = new File(['x'], 'zaak.png', { type: 'image/png' }) + Object.defineProperty(input.element, 'files', { value: [file] }) + await input.trigger('change') + await flushPromises() + + expect(uploadFile).toHaveBeenCalledWith(file) + expect(wrapper.vm.form.icon).toBe('/apps/launchpad/resource/zaak.png') + expect(wrapper.vm.form.iconType).toBe('url') + }) + + it('says so when the icon upload fails, and keeps the icon', async () => { + uploadFile.mockRejectedValue(new Error('file_too_large')) + const wrapper = mountEditor({ ...caseSystem, icon: 'M0 0h24v24H0z', iconType: 'svg' }) + const input = wrapper.find('input[type="file"]') + Object.defineProperty(input.element, 'files', { value: [new File(['x'], 'big.png', { type: 'image/png' })] }) + await input.trigger('change') + await flushPromises() + + expect(wrapper.find('[role="alert"]').text()).toBe('The icon could not be uploaded.') + expect(wrapper.vm.form.icon).toBe('M0 0h24v24H0z') + }) + + it('opens the file chooser from Upload another icon', async () => { + const wrapper = mountEditor(caseSystem) + const click = vi.spyOn(wrapper.find('input[type="file"]').element, 'click').mockImplementation(() => {}) + await button(wrapper, 'Upload another icon').trigger('click') + expect(click).toHaveBeenCalled() + }) +}) diff --git a/src/modals/__tests__/TileEditor.interaction.spec.js b/src/modals/__tests__/TileEditor.interaction.spec.js new file mode 100644 index 000000000..18491d85c --- /dev/null +++ b/src/modals/__tests__/TileEditor.interaction.spec.js @@ -0,0 +1,197 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `TileEditor.vue` driven through its rendered form: + * every field writes back into the form, the health-ping fields appear with + * the switch, and the modal and action buttons emit what the parent acts on. + * + * The Nextcloud form controls are replaced by minimal stand-ins that render + * their slot and emit the same events, so the template's own bindings run. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import TileEditor from '../TileEditor.vue' +import { validateHealthPingConfig } from '../../services/healthPingClient.js' + +vi.mock('../../services/healthPingClient.js', () => ({ + validateHealthPingConfig: vi.fn(), +})) + +const stubs = { + NcModal: { + name: 'NcModal', + props: ['show', 'name'], + emits: ['close', 'update:show'], + template: '<div class="nc-modal-stub"><slot /></div>', + }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue', 'blur'], + template: '<input class="text-field" :data-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" @blur="$emit(\'blur\')" />', + }, + NcColorPicker: { + name: 'NcColorPicker', + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<div class="color-picker"><slot /></div>', + }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<label class="switch"><slot /></label>', + }, + NcButton: { + name: 'NcButton', + emits: ['click'], + template: '<button class="button" @click="$emit(\'click\')"><slot /></button>', + }, + CnIconBrowser: { name: 'CnIconBrowser', template: '<div class="icon-browser" />' }, +} + +function mountEditor(tile = null) { + return mount(TileEditor, { propsData: { open: true, tile }, stubs }) +} + +function field(wrapper, label) { + return wrapper.find(`input.text-field[data-label="${label}"]`) +} + +function button(wrapper, text) { + return wrapper.findAll('button.button').find((b) => b.text() === text) +} + +describe('TileEditor form bindings', () => { + it('titles the editor by whether a tile is being edited', () => { + expect(mountEditor().find('h2').text()).toBe('New tile') + expect(mountEditor({ id: 1, title: 'Files' }).find('h2').text()).toBe('Edit tile: Files') + }) + + it('writes the title and URL fields back and shows the title in the preview', async () => { + const wrapper = mountEditor() + + await field(wrapper, 'Name').setValue('Bestanden') + await field(wrapper, 'Web address').setValue('/apps/files') + + expect(wrapper.vm.form.title).toBe('Bestanden') + expect(wrapper.vm.form.linkValue).toBe('/apps/files') + expect(wrapper.find('.tile-preview__title').text()).toBe('Bestanden') + }) + + it('writes both colours back into the form and the preview', async () => { + const wrapper = mountEditor() + const [background, text] = wrapper.findAllComponents({ name: 'NcColorPicker' }) + + background.vm.$emit('update:modelValue', '#123456') + text.vm.$emit('update:modelValue', '#abcdef') + await flushPromises() + + expect(wrapper.vm.form.backgroundColor).toBe('#123456') + expect(wrapper.vm.form.textColor).toBe('#abcdef') + const style = wrapper.find('.tile-preview').attributes('style') + expect(style).toContain('background: rgb(18, 52, 86)') + expect(style).toContain('color: rgb(171, 205, 239)') + }) +}) + +describe('TileEditor health-ping fields', () => { + it('shows the health fields only once the switch is on, and writes them back', async () => { + const wrapper = mountEditor() + expect(field(wrapper, 'Health check URL').exists()).toBe(false) + + // The health switch, not one of the "Opens in" radios before it. + wrapper.find('.tile-editor__health-ping').findComponent({ name: 'NcCheckboxRadioSwitch' }).vm.$emit('update:modelValue', true) + await flushPromises() + + await field(wrapper, 'Health check URL').setValue('https://status.example.org') + await field(wrapper, 'Expected HTTP status').setValue('204') + await field(wrapper, 'Check interval (seconds)').setValue('30') + + expect(wrapper.vm.form.healthPingEnabled).toBe(true) + expect(wrapper.vm.form.healthUrl).toBe('https://status.example.org') + expect(wrapper.vm.form.expectedStatus).toBe('204') + expect(wrapper.vm.form.pingInterval).toBe('30') + }) + + it('checks the URL on blur, shows a refusal, and clears it while typing', async () => { + validateHealthPingConfig.mockResolvedValue({ valid: false, errors: ['host_not_allowed'] }) + const wrapper = mountEditor({ id: 1, title: 'T', healthPingEnabled: true, healthUrl: 'https://blocked.example' }) + + await field(wrapper, 'Health check URL').trigger('blur') + await flushPromises() + expect(wrapper.find('.tile-editor__warning').text()).toBe('This host is not on the allow-list.') + + await field(wrapper, 'Health check URL').setValue('https://other.example') + expect(wrapper.find('.tile-editor__warning').exists()).toBe(false) + }) +}) + +describe('TileEditor actions', () => { + it('offers Delete only for an existing tile and emits delete', async () => { + expect(button(mountEditor(), 'Delete tile')).toBeUndefined() + + const wrapper = mountEditor({ id: 1, title: 'T' }) + await button(wrapper, 'Delete tile').trigger('click') + + expect(wrapper.emitted('delete')).toHaveLength(1) + }) + + it('emits close from Cancel and save with the normalised form from Save', async () => { + const wrapper = mountEditor() + await field(wrapper, 'Name').setValue('Mail') + + await button(wrapper, 'Cancel').trigger('click') + await button(wrapper, 'Save').trigger('click') + + expect(wrapper.emitted('close')).toHaveLength(1) + expect(wrapper.emitted('save')[0][0]).toMatchObject({ title: 'Mail', expectedStatus: 200, pingInterval: 60 }) + }) + + it('forwards the modal closing as close, and ignores it opening', async () => { + const wrapper = mountEditor() + const modal = wrapper.findComponent({ name: 'NcModal' }) + + modal.vm.$emit('update:show', true) + expect(wrapper.emitted('close')).toBeUndefined() + + modal.vm.$emit('update:show', false) + modal.vm.$emit('close') + expect(wrapper.emitted('close')).toHaveLength(2) + expect(modal.props('name')).toBe('New tile') + }) +}) + +describe('TileEditor theme colours (REQ-ICT-004)', () => { + // @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-the-tile-colour-is-one-of-eight-theme-colours-req-ict-004 + it('offers eight named swatches and stores the chosen token', async () => { + const wrapper = mountEditor() + const swatches = wrapper.findAll('[data-test^="tile-editor-swatch--sc-"]') + expect(swatches).toHaveLength(8) + expect(swatches.map((s) => s.attributes('aria-label'))).toEqual([ + 'Primary', 'Primary, dark', 'Accent', 'Accent, dark', 'Ink', 'Text grey', 'Muted grey', 'Field grey', + ]) + expect(wrapper.find('[data-test="tile-editor-swatches"]').attributes('role')).toBe('radiogroup') + + await wrapper.find('[data-test="tile-editor-swatch--sc-primary"]').trigger('change') + expect(wrapper.vm.form.colourToken).toBe('--sc-primary') + expect(wrapper.find('.tile-preview').attributes('style')).toContain('var(--sc-primary') + // The hex pickers make way for the token. + expect(wrapper.findAllComponents({ name: 'NcColorPicker' })).toHaveLength(0) + + await wrapper.find('[data-test="tile-editor-swatch-own"]').trigger('change') + expect(wrapper.vm.form.colourToken).toBe('') + expect(wrapper.findAllComponents({ name: 'NcColorPicker' })).toHaveLength(2) + }) + + it('seeds a stored token and ignores one that is not a token', async () => { + const wrapper = mountEditor() + await wrapper.setProps({ tile: { id: 4, title: 'Z', colourToken: '--sc-accent' } }) + expect(wrapper.vm.form.colourToken).toBe('--sc-accent') + expect(wrapper.find('[data-test="tile-editor-swatch--sc-accent"]').element.checked).toBe(true) + await wrapper.setProps({ tile: { id: 5, title: 'Y', colourToken: 'red' } }) + expect(wrapper.vm.form.colourToken).toBe('') + }) +}) diff --git a/src/modals/__tests__/TileEditor.launchTypes.spec.js b/src/modals/__tests__/TileEditor.launchTypes.spec.js new file mode 100644 index 000000000..b2d35b3c3 --- /dev/null +++ b/src/modals/__tests__/TileEditor.launchTypes.spec.js @@ -0,0 +1,157 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the launch types of `TileEditor.vue` + * (launcher-tile-launch-types task 4): the "Tile type" choice cards + * (tile-form-board-sync REQ-TILE-040), the fields each + * type shows, the template picker with no free address field for single + * sign-on, and the hint naming the schemes an administrator allowed. + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const initialState = { tileAllowedSchemes: [], ssoLaunchTemplates: [] } + +vi.mock('../../services/healthPingClient.js', () => ({ validateHealthPingConfig: vi.fn() })) +vi.mock('../../utils/loadInitialState.js', () => ({ loadInitialState: () => ({ ...initialState }), isOnOfficeNetwork: () => false })) + +const { default: TileEditor } = await import('../TileEditor.vue') + +const stubs = { + NcModal: { name: 'NcModal', props: ['show', 'name'], template: '<div><slot /></div>' }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label', 'helperText'], + emits: ['update:modelValue'], + template: '<label class="text-field" :data-label="label"><input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" /><small>{{ helperText }}</small></label>', + }, + NcSelect: { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel'], + emits: ['update:modelValue'], + template: '<div class="select" :data-label="inputLabel"><button v-for="o in options" :key="o.value" class="option" :data-value="o.value" @click="$emit(\'update:modelValue\', o.value)">{{ o.label }}</button></div>', + }, + NcColorPicker: { name: 'NcColorPicker', template: '<div><slot /></div>' }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'type'], + emits: ['update:modelValue'], + template: '<label class="switch" :data-type="type" @click="$emit(\'update:modelValue\', true)"><slot /></label>', + }, + NcButton: { name: 'NcButton', emits: ['click'], template: '<button class="button" @click="$emit(\'click\')"><slot /></button>' }, + CnIconBrowser: { name: 'CnIconBrowser', template: '<div />' }, +} + +function mountEditor(tile = null) { + return mount(TileEditor, { props: { open: true, tile }, global: { stubs } }) +} + +function labels(wrapper) { + return wrapper.findAll('.text-field').map((f) => f.attributes('data-label')) +} + +async function pick(wrapper, selectLabel, value) { + await wrapper.find(`.select[data-label="${selectLabel}"] .option[data-value="${value}"]`).trigger('click') +} + +function typeCards(wrapper) { + return wrapper.find('[data-testid="tile-link-type"]').findAll('.choice-cards__card') +} + +async function pickType(wrapper, value) { + await wrapper.find(`[data-testid="tile-link-type"] input[value="${value}"]`).setValue(true) +} + +describe('TileEditor launch types', () => { + const plainT = globalThis.t + + beforeEach(() => { + initialState.tileAllowedSchemes = [] + initialState.ssoLaunchTemplates = [] + // Script-level t() with the placeholders filled in, so the hint's schemes can be read. + globalThis.t = (_app, key, vars) => key.replace(/\{(\w+)\}/g, (match, name) => (vars && name in vars ? String(vars[name]) : match)) + }) + + afterEach(() => { + globalThis.t = plainT + }) + + it('offers the four tile types as choice cards, each with one line of explanation', () => { + const wrapper = mountEditor() + expect(wrapper.find('[data-testid="tile-link-type"]').attributes('role')).toBe('radiogroup') + expect(typeCards(wrapper).map((c) => c.find('.choice-cards__title').text())) + .toEqual(['Web address', 'App with single sign-on', 'Legacy Windows program', 'Program on this computer']) + expect(typeCards(wrapper).map((c) => c.attributes('data-value'))).toEqual(['url', 'sso', 'remote-desktop', 'program']) + expect(typeCards(wrapper).every((c) => c.find('.choice-cards__hint').text() !== '')).toBe(true) + expect(wrapper.find('[data-testid="tile-link-type"] input[value="url"]').element.checked).toBe(true) + }) + + it('keeps an older app tile selectable under its own label', () => { + const cards = typeCards(mountEditor({ id: 1, title: 'Files', linkType: 'app', linkValue: 'files' })) + expect(cards[0].attributes('data-value')).toBe('app') + expect(cards[0].find('.choice-cards__title').text()).toBe('Nextcloud app') + expect(cards[0].find('input').element.checked).toBe(true) + expect(labels(mountEditor({ id: 1, title: 'Files', linkType: 'app', linkValue: 'files' }))).toContain('Web address') + }) + + it('asks a program tile for its address and names the allowed schemes', async () => { + initialState.tileAllowedSchemes = ['ms-word', 'vscode'] + const wrapper = mountEditor() + await pickType(wrapper, 'program') + + expect(labels(wrapper)).toContain('Program address') + expect(labels(wrapper)).not.toContain('Web address') + expect(wrapper.find('.text-field[data-label="Program address"] small').text()).toBe('Allowed schemes: ms-word, vscode') + }) + + it('says when no scheme is allowed yet', async () => { + const wrapper = mountEditor() + await pickType(wrapper, 'program') + expect(wrapper.find('.text-field[data-label="Program address"] small').text()) + .toBe('No program schemes are allowed yet. An administrator allows them on the LaunchPad admin page.') + }) + + it('shows the gateway address, or the RDP fields, for a remote desktop', async () => { + const wrapper = mountEditor() + await pickType(wrapper, 'remote-desktop') + expect(labels(wrapper)).toContain('Gateway address') + expect(labels(wrapper)).not.toContain('Computer or server') + + await wrapper.find('[data-testid="tile-remote-rdp"]').trigger('click') + + expect(labels(wrapper)).toEqual(expect.arrayContaining(['Computer or server', 'Port', 'Published program (optional)', 'Remote desktop gateway (optional)'])) + expect(labels(wrapper)).not.toContain('Gateway address') + expect(wrapper.vm.form.remoteMode).toBe('rdp') + }) + + it('lets an sso author pick a template and enter an app id, with no address field', async () => { + initialState.ssoLaunchTemplates = [{ key: 'entra', name: 'Microsoft Entra ID' }] + const wrapper = mountEditor() + await pickType(wrapper, 'sso') + + expect(labels(wrapper)).toEqual(expect.arrayContaining(['Name', 'App id', 'Internal address (optional)'])) + expect(labels(wrapper)).not.toContain('Web address') + expect(wrapper.find('.select[data-label="Sign-on template"]').findAll('.option').map((o) => o.text())).toEqual(['Microsoft Entra ID']) + + await pick(wrapper, 'Sign-on template', 'entra') + await wrapper.find('.text-field[data-label="App id"] input').setValue('a1b2c3') + await wrapper.findAll('button.button').find((b) => b.text() === 'Save').trigger('click') + + expect(wrapper.emitted('save')[0][0]).toMatchObject({ linkType: 'sso', ssoTemplate: 'entra', ssoAppId: 'a1b2c3' }) + }) + + it('says when there are no sign-on templates', async () => { + const wrapper = mountEditor() + await pickType(wrapper, 'sso') + expect(wrapper.text()).toContain('No sign-on templates yet. An administrator adds them on the LaunchPad admin page.') + }) + + it('clears an address the server resolved when the type changes', async () => { + const wrapper = mountEditor({ id: 4, title: 'Salaris', linkType: 'sso', linkValue: 'https://launcher.example/a1', ssoTemplate: 'entra', ssoAppId: 'a1' }) + await pickType(wrapper, 'url') + expect(wrapper.vm.form.linkValue).toBe('') + expect(wrapper.vm.form.linkType).toBe('url') + }) +}) diff --git a/src/modals/__tests__/TileEditor.officeNetwork.spec.js b/src/modals/__tests__/TileEditor.officeNetwork.spec.js new file mode 100644 index 000000000..92427823b --- /dev/null +++ b/src/modals/__tests__/TileEditor.officeNetwork.spec.js @@ -0,0 +1,59 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest for `TileEditor.vue`'s office-network address: the field is pre-filled + * from the tile, saved with it, and the line below it says which address the + * tile opens for the author right now. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-internal-address/specs/tiles/spec.md#requirement-a-tile-can-hold-an-office-network-address-req-tia-002 + */ +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const network = vi.hoisted(() => ({ office: false })) + +vi.mock('../../services/healthPingClient.js', () => ({ validateHealthPingConfig: vi.fn() })) +vi.mock('../../utils/loadInitialState.js', () => ({ isOnOfficeNetwork: () => network.office, loadInitialState: () => ({ tileAllowedSchemes: [], ssoLaunchTemplates: [] }) })) + +const { default: TileEditor } = await import('../TileEditor.vue') + +/** + * Mount the editor for a tile. + * + * @param {object|null} tile The tile, or null for a new one. + * @return {import('@vue/test-utils').VueWrapper} + */ +function mountEditor(tile) { + return mount(TileEditor, { propsData: { open: true, tile } }) +} + +describe('TileEditor office-network address', () => { + beforeEach(() => { + network.office = false + }) + + it('pre-fills the internal address and saves it with the tile', () => { + const wrapper = mountEditor({ id: 1, title: 'Zaaksysteem', linkType: 'url', linkValue: 'https://zaken.gemeente.nl', internalUrl: 'http://zaken.intern' }) + expect(wrapper.vm.form.internalUrl).toBe('http://zaken.intern') + + wrapper.vm.saveTile() + expect(wrapper.emitted('save')[0][0]).toMatchObject({ linkValue: 'https://zaken.gemeente.nl', internalUrl: 'http://zaken.intern' }) + }) + + it('starts empty for a new tile and for a tile without one', () => { + expect(mountEditor(null).vm.form.internalUrl).toBe('') + expect(mountEditor({ id: 2, title: 'Deck' }).vm.form.internalUrl).toBe('') + }) + + it('says the tile opens the internal address on the office network', () => { + network.office = true + const wrapper = mountEditor({ id: 3, title: 'Zaaksysteem' }) + expect(wrapper.vm.addressInEffect).toBe('You are on the office network: this tile opens the internal address') + }) + + it('says the tile opens the main address elsewhere', () => { + const wrapper = mountEditor({ id: 4, title: 'Zaaksysteem' }) + expect(wrapper.vm.addressInEffect).toBe('You are not on the office network: this tile opens the main address') + }) +}) diff --git a/src/modals/__tests__/TileEditor.opensIn.spec.js b/src/modals/__tests__/TileEditor.opensIn.spec.js new file mode 100644 index 000000000..0d60c1115 --- /dev/null +++ b/src/modals/__tests__/TileEditor.opensIn.spec.js @@ -0,0 +1,133 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The tile editor's "Open in" choice (launcher-tile-open-behaviour D1, D4), + * as three choice cards (tile-form-board-sync REQ-TILE-040). + * + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-tile-form-as-lptegelbewerken-draws-it-req-tile-040 + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import TileEditor from '../TileEditor.vue' +import { validateIframeUrl } from '../../services/iframeClient.js' + +vi.mock('../../services/healthPingClient.js', () => ({ validateHealthPingConfig: vi.fn() })) +vi.mock('../../services/iframeClient.js', () => ({ validateIframeUrl: vi.fn() })) + +const stubs = { + NcModal: { name: 'NcModal', template: '<div><slot /></div>' }, + NcTextField: { + name: 'NcTextField', + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: '<input class="text-field" :data-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcColorPicker: { name: 'NcColorPicker', template: '<div><slot /></div>' }, + NcCheckboxRadioSwitch: { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'value', 'disabled', 'type'], + emits: ['update:modelValue'], + template: '<label class="radio" :data-value="value" :data-disabled="disabled ? \'yes\' : \'no\'" @click="$emit(\'update:modelValue\', value)"><slot /></label>', + }, + NcButton: { name: 'NcButton', emits: ['click'], template: '<button class="button" @click="$emit(\'click\')"><slot /></button>' }, + CnIconBrowser: { name: 'CnIconBrowser', template: '<div />' }, +} + +/** + * Mount the editor. + * + * @param {object|null} tile The tile, or null for a new one. + * @return {object} The wrapper. + */ +function mountEditor(tile = null) { + return mount(TileEditor, { propsData: { open: true, tile }, stubs }) +} + +/** + * The radio for a value. + * + * @param {object} wrapper The wrapper. + * @param {string} value The link target, '' for the dashboard. + * @return {object} The radio. + */ +function radio(wrapper, value) { + return wrapper.find(`[data-test="tile-editor-opens-in"] .choice-cards__card[data-value="${value}"]`) +} + +/** + * Whether a card's radio is disabled. + * + * @param {object} wrapper The wrapper. + * @param {string} value The link target. + * @return {boolean} + */ +function disabled(wrapper, value) { + return radio(wrapper, value).find('input').element.disabled +} + +describe('TileEditor opens in', () => { + beforeEach(() => { + validateIframeUrl.mockReset() + }) + + it('offers the three targets as cards, none chosen follows the dashboard, and saves the chosen one', async () => { + const wrapper = mountEditor({ id: 1, title: 'Files', linkType: 'app', linkValue: 'files' }) + + expect(wrapper.find('[data-test="tile-editor-opens-in"] [role="radiogroup"]').exists()).toBe(true) + expect(wrapper.findAll('[data-test="tile-editor-opens-in"] .choice-cards__card').map((r) => r.attributes('data-value'))) + .toEqual(['same-tab', 'new-tab', 'side-panel']) + expect(wrapper.findAll('[data-test="tile-editor-opens-in"] .choice-cards__title').map((r) => r.text())) + .toEqual(['Same tab', 'New tab', 'In Launchpad, next to the tiles']) + expect(wrapper.vm.form.linkTarget).toBe('') + expect(wrapper.find('[data-test="tile-editor-opens-in-default"]').text()).toContain('as the dashboard decides') + + await radio(wrapper, 'side-panel').find('input').setValue(true) + wrapper.vm.saveTile() + + expect(wrapper.emitted('save')[0][0].linkTarget).toBe('side-panel') + expect(validateIframeUrl).not.toHaveBeenCalled() + }) + + it('goes back to the dashboard\'s choice from the button under the cards', async () => { + const wrapper = mountEditor({ id: 5, title: 'T', linkType: 'url', linkValue: '', linkTarget: 'new-tab' }) + expect(radio(wrapper, 'new-tab').find('input').element.checked).toBe(true) + + await wrapper.find('[data-test="tile-editor-follow-dashboard"]').trigger('click') + + expect(wrapper.vm.form.linkTarget).toBe('') + expect(wrapper.findAll('[data-test="tile-editor-opens-in"] input').some((i) => i.element.checked)).toBe(false) + }) + + it('seeds the choice from the tile', () => { + expect(mountEditor({ id: 2, title: 'T', linkType: 'url', linkValue: '', linkTarget: 'new-tab' }).vm.form.linkTarget).toBe('new-tab') + expect(mountEditor(null).vm.form.linkTarget).toBe('') + }) + + it('greys out the panel with a reason for an outside host not on the allow-list, and drops that choice', async () => { + validateIframeUrl.mockResolvedValue({ valid: false, errors: ['host_not_allowed'] }) + const wrapper = mountEditor({ id: 3, title: 'Ext', linkType: 'url', linkValue: '', linkTarget: 'side-panel' }) + + await wrapper.find('input.text-field[data-label="Web address"]').setValue('https://blocked.example/page') + await flushPromises() + + expect(validateIframeUrl).toHaveBeenCalledWith({ url: 'https://blocked.example/page' }) + expect(disabled(wrapper, 'side-panel')).toBe(true) + expect(wrapper.find('[data-test="tile-editor-panel-refusal"]').text()).toContain('cannot open in the panel') + expect(wrapper.vm.form.linkTarget).toBe('') + }) + + it('keeps the panel for an allowed outside host', async () => { + validateIframeUrl.mockResolvedValue({ valid: true, errors: [] }) + const wrapper = mountEditor({ id: 4, title: 'Ok', linkType: 'url', linkValue: '', linkTarget: 'side-panel' }) + + await wrapper.find('input.text-field[data-label="Web address"]').setValue('https://ok.example') + await flushPromises() + + expect(disabled(wrapper, 'side-panel')).toBe(false) + expect(wrapper.find('[data-test="tile-editor-panel-refusal"]').exists()).toBe(false) + expect(wrapper.vm.form.linkTarget).toBe('side-panel') + }) +}) diff --git a/src/modals/__tests__/TileEditor.spec.js b/src/modals/__tests__/TileEditor.spec.js index e93556836..93ddd05e8 100644 --- a/src/modals/__tests__/TileEditor.spec.js +++ b/src/modals/__tests__/TileEditor.spec.js @@ -11,9 +11,10 @@ import { mdiAlertCircle, mdiLink } from '@mdi/js' import { mount } from '@vue/test-utils' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import TileEditor from '../TileEditor.vue' import { validateHealthPingConfig } from '../../services/healthPingClient.js' +import { loadIconCatalogue } from '../../services/iconCatalogue.js' vi.mock('../../services/healthPingClient.js', () => ({ validateHealthPingConfig: vi.fn(), @@ -23,6 +24,9 @@ function mountEditor(tile) { return mount(TileEditor, { propsData: { open: true, tile } }) } +// Legacy icon names resolve once the MDI catalogue has loaded. +beforeAll(() => loadIconCatalogue()) + describe('TileEditor legacy-icon display', () => { it('resolves a legacy lowercase MDI shortname to its path', () => { const wrapper = mountEditor({ diff --git a/src/modals/__tests__/VersionHistoryModal.spec.js b/src/modals/__tests__/VersionHistoryModal.spec.js deleted file mode 100644 index 2e38f4e2c..000000000 --- a/src/modals/__tests__/VersionHistoryModal.spec.js +++ /dev/null @@ -1,172 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> - * SPDX-License-Identifier: EUPL-1.2 - * - * VersionHistoryModal: lists versions newest first, saves a named version - * and restores after confirmation (dashboard-versioning REQ-VERSUI-001..003). - * Response shapes are DashboardVersionApiController's: `{versions, - * modeSupported}` for the list, `{version}` (201) for a save, `{version, - * snapshot}` for a restore; each version is DashboardVersion::jsonSerialize. - */ - -import { flushPromises, mount } from '@vue/test-utils' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import VersionHistoryModal from '../VersionHistoryModal.vue' -import { api } from '../../services/api.js' - -vi.mock('@nextcloud/l10n', () => ({ - t: (_app, text, vars = {}) => - text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), -})) - -vi.mock('../../services/api.js', () => ({ - api: { - listVersions: vi.fn(), - createVersion: vi.fn(), - restoreVersion: vi.fn(), - }, -})) - -vi.mock('@conduction/nextcloud-vue', () => ({ - NcModal: { - name: 'NcModal', - props: ['name'], - emits: ['close'], - template: '<div class="modal"><slot /></div>', - }, - NcDialog: { - name: 'NcDialog', - props: ['name', 'open'], - template: - '<div v-if="open" class="dialog"><slot /><slot name="actions" /></div>', - }, - NcButton: { - name: 'NcButton', - props: ['disabled'], - emits: ['click'], - template: - '<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', - }, - NcTextField: { - name: 'NcTextField', - props: ['modelValue', 'label'], - emits: ['update:modelValue'], - template: - '<input :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)">', - }, - NcLoadingIcon: { name: 'NcLoadingIcon', template: '<span class="loading" />' }, -})) - -function v(n, note = null, createdBy = 'sanne') { - return { - id: n, - dashboardUuid: 'dash-uuid', - versionNumber: n, - createdBy, - createdAt: `2026-09-2${n} 10:00:00`, - note, - sizeBytes: 120, - } -} - -function mountModal() { - return mount(VersionHistoryModal, { - props: { open: true, dashboardUuid: 'dash-uuid' }, - }) -} - -beforeEach(() => { - vi.clearAllMocks() -}) - -describe('VersionHistoryModal', () => { - it('REQ-VERSUI-001: lists versions newest first with author and note', async () => { - api.listVersions.mockResolvedValue({ - data: { - versions: [v(2), v(4, 'before the reorganisation'), v(1), v(3)], - modeSupported: true, - }, - }) - const wrapper = mountModal() - await flushPromises() - expect(api.listVersions).toHaveBeenCalledWith('dash-uuid') - const rows = wrapper.findAll('[data-testid="version-row"]') - expect(rows).toHaveLength(4) - expect(rows[0].text()).toContain('4') - expect(rows[0].text()).toContain('before the reorganisation') - expect(rows[0].text()).toContain('sanne') - expect(rows[3].text()).toContain('1') - }) - - it('REQ-VERSUI-002: saves a named version and puts it on top', async () => { - api.listVersions.mockResolvedValue({ - data: { versions: [v(1)], modeSupported: true }, - }) - api.createVersion.mockResolvedValue({ - data: { version: v(2, 'before the reorganisation') }, - }) - const wrapper = mountModal() - await flushPromises() - await wrapper.find('input').setValue('before the reorganisation') - await wrapper.find('[data-testid="version-save"]').trigger('click') - await flushPromises() - expect(api.createVersion).toHaveBeenCalledWith( - 'dash-uuid', - 'before the reorganisation', - ) - const rows = wrapper.findAll('[data-testid="version-row"]') - expect(rows).toHaveLength(2) - expect(rows[0].text()).toContain('before the reorganisation') - }) - - it('REQ-VERSUI-003: restore asks first, restores, reloads the list and tells the page', async () => { - api.listVersions.mockResolvedValueOnce({ - data: { versions: [v(2), v(1)], modeSupported: true }, - }) - api.restoreVersion.mockResolvedValue({ - data: { version: v(1), snapshot: '{}' }, - }) - api.listVersions.mockResolvedValueOnce({ - data: { - versions: [v(3, 'pre-restore'), v(2), v(1)], - modeSupported: true, - }, - }) - const wrapper = mountModal() - await flushPromises() - await wrapper.findAll('[data-testid="version-restore"]')[1].trigger('click') - expect(api.restoreVersion).not.toHaveBeenCalled() - await wrapper - .find('[data-testid="version-restore-confirm"]') - .trigger('click') - await flushPromises() - expect(api.restoreVersion).toHaveBeenCalledWith('dash-uuid', 1) - expect(wrapper.emitted('restored')).toHaveLength(1) - expect(wrapper.findAll('[data-testid="version-row"]')[0].text()).toContain( - '3', - ) - }) - - it('says so when versioning is not supported for the dashboard', async () => { - api.listVersions.mockResolvedValue({ - data: { versions: [], modeSupported: false }, - }) - const wrapper = mountModal() - await flushPromises() - expect(wrapper.find('[data-testid="version-unsupported"]').exists()).toBe( - true, - ) - expect(wrapper.find('[data-testid="version-save"]').exists()).toBe(false) - }) - - it('shows the error when the list cannot be read', async () => { - api.listVersions.mockRejectedValue( - Object.assign(new Error('x'), { - response: { status: 403, data: { error: 'forbidden' } }, - }), - ) - const wrapper = mountModal() - await flushPromises() - expect(wrapper.find('[data-testid="version-error"]').exists()).toBe(true) - }) -}) diff --git a/src/modals/__tests__/VisibilityRulesModal.spec.js b/src/modals/__tests__/VisibilityRulesModal.spec.js index fee81c10c..6f8b4a4e2 100644 --- a/src/modals/__tests__/VisibilityRulesModal.spec.js +++ b/src/modals/__tests__/VisibilityRulesModal.spec.js @@ -14,12 +14,17 @@ * its own `close`. */ -import { mount } from '@vue/test-utils' -import { beforeEach, describe, expect, it } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' import VisibilityRulesModal from '../VisibilityRulesModal.vue' +import { api } from '../../services/api.js' + +vi.mock('../../services/api.js', () => ({ + api: { getAdminGroups: vi.fn() }, +})) const ConditionalVisibilityEditorStub = { - props: ['placementId', 'availableGroups'], + props: ['placementId', 'availableGroups', 'ruleMatch'], template: '<div class="editor-stub" :data-placement-id="placementId" />', } @@ -37,6 +42,8 @@ function mountModal(props = {}) { beforeEach(() => { globalThis.t = (_app, key) => key + vi.clearAllMocks() + api.getAdminGroups.mockResolvedValue({ data: { active: [], inactive: [], allKnown: [] } }) }) describe('VisibilityRulesModal', () => { @@ -69,4 +76,47 @@ describe('VisibilityRulesModal', () => { expect(wrapper.emitted('ruleUpdated')).toBeTruthy() expect(wrapper.emitted('ruleRemoved')).toBeTruthy() }) + + it('offers the instance\'s groups when none are passed (launchpad#97)', async () => { + const groups = [{ id: 'mkt', displayName: 'Marketing' }] + api.getAdminGroups.mockResolvedValue({ data: { active: [], inactive: groups, allKnown: groups } }) + const wrapper = mountModal() + await flushPromises() + + expect(api.getAdminGroups).toHaveBeenCalledTimes(1) + expect(wrapper.findComponent(ConditionalVisibilityEditorStub).props('availableGroups')).toEqual(groups) + }) + + it('does not read the groups when a list is passed or the modal is closed', async () => { + mountModal({ availableGroups: ['marketing'] }) + mountModal({ open: false }) + await flushPromises() + + expect(api.getAdminGroups).not.toHaveBeenCalled() + }) + + it('offers no groups when the list is refused', async () => { + api.getAdminGroups.mockRejectedValue(new Error('403')) + const wrapper = mountModal() + await flushPromises() + + expect(wrapper.findComponent(ConditionalVisibilityEditorStub).props('availableGroups')).toEqual([]) + }) +}) + +describe('VisibilityRulesModal — Who sees this widget?', () => { + // @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + it('is titled Who sees this widget? with the widget and the dashboard under it', () => { + const wrapper = mountModal({ widgetTitle: 'News', dashboardName: 'Home', ruleMatch: 'all' }) + expect(wrapper.find('[data-test="visibility-rules-title"]').text()).toBe('Who sees this widget?') + expect(wrapper.find('[data-test="visibility-rules-subtitle"]').text()).toBe('News · Home') + expect(wrapper.findComponent(ConditionalVisibilityEditorStub).props('ruleMatch')).toBe('all') + }) + + it('leaves the line out when neither name is known, and passes the saved mode on', async () => { + const wrapper = mountModal() + expect(wrapper.find('[data-test="visibility-rules-subtitle"]').exists()).toBe(false) + await wrapper.findComponent(ConditionalVisibilityEditorStub).vm.$emit('ruleMatchChanged', 'all') + expect(wrapper.emitted('ruleMatchChanged')).toEqual([['all']]) + }) }) diff --git a/src/modals/__tests__/WidgetMovePanel.buttons.spec.js b/src/modals/__tests__/WidgetMovePanel.buttons.spec.js new file mode 100644 index 000000000..40163ee69 --- /dev/null +++ b/src/modals/__tests__/WidgetMovePanel.buttons.spec.js @@ -0,0 +1,123 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `WidgetMovePanel.vue` driven by its buttons rather + * than the keyboard: each position and size button applies its action, the + * Cancel/Confirm buttons and the modal close emit what the parent acts on, + * and reopening or swapping the placement resets the pending rectangle. + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it } from 'vitest' +import WidgetMovePanel from '../WidgetMovePanel.vue' + +const stubs = { + NcModal: { + name: 'NcModal', + emits: ['close'], + template: '<div class="nc-modal-stub"><slot /></div>', + }, + NcButton: { + emits: ['click'], + template: '<button @click="$emit(\'click\')"><slot /></button>', + }, +} + +beforeEach(() => { + globalThis.t = (_app, key, params) => { + if (!params) { + return key + } + return key.replace(/\{(\w+)\}/g, (_m, name) => String(params[name])) + } +}) + +const PLACEMENT = { id: 'p1', gridX: 3, gridY: 2, gridWidth: 4, gridHeight: 4 } + +function mountPanel(props = {}) { + return mount(WidgetMovePanel, { + propsData: { open: true, placement: PLACEMENT, allPlacements: [], gridColumns: 12, ...props }, + stubs, + }) +} + +function rect(wrapper) { + const { gridX, gridY, gridWidth, gridHeight } = wrapper.vm.working + return { gridX, gridY, gridWidth, gridHeight } +} + +describe('WidgetMovePanel buttons', () => { + it.each([ + ['move-up', { gridX: 3, gridY: 1, gridWidth: 4, gridHeight: 4 }], + ['move-down', { gridX: 3, gridY: 3, gridWidth: 4, gridHeight: 4 }], + ['move-left', { gridX: 2, gridY: 2, gridWidth: 4, gridHeight: 4 }], + ['move-right', { gridX: 4, gridY: 2, gridWidth: 4, gridHeight: 4 }], + ['grow-width', { gridX: 3, gridY: 2, gridWidth: 5, gridHeight: 4 }], + ['shrink-width', { gridX: 3, gridY: 2, gridWidth: 3, gridHeight: 4 }], + ['grow-height', { gridX: 3, gridY: 2, gridWidth: 4, gridHeight: 5 }], + ['shrink-height', { gridX: 3, gridY: 2, gridWidth: 4, gridHeight: 3 }], + ])('%s applies its action to the pending rectangle', async (action, expected) => { + const wrapper = mountPanel() + + await wrapper.find(`[data-test="${action}"]`).trigger('click') + + expect(rect(wrapper)).toEqual(expected) + expect(wrapper.find('[data-test="widget-move-readout"]').text()).toBe( + `Column ${expected.gridX + 1}, row ${expected.gridY + 1}, ${expected.gridWidth} wide by ${expected.gridHeight} tall`, + ) + }) + + it('Confirm emits save with the pending rectangle, then close', async () => { + const wrapper = mountPanel() + await wrapper.find('[data-test="move-right"]').trigger('click') + + await wrapper.find('[data-test="move-save"]').trigger('click') + + expect(wrapper.emitted('save')[0][0]).toMatchObject({ gridX: 4, gridY: 2, gridWidth: 4, gridHeight: 4 }) + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('Cancel and the modal close emit close without save', async () => { + const wrapper = mountPanel() + + await wrapper.find('[data-test="move-cancel"]').trigger('click') + wrapper.findComponent({ name: 'NcModal' }).vm.$emit('close') + + expect(wrapper.emitted('close')).toHaveLength(2) + expect(wrapper.emitted('save')).toBeUndefined() + }) + + it('a key without an action does nothing and is not swallowed', async () => { + const wrapper = mountPanel() + const event = new KeyboardEvent('keydown', { key: 'a', cancelable: true }) + + wrapper.find('[data-test="widget-move-panel"]').element.dispatchEvent(event) + + expect(event.defaultPrevented).toBe(false) + expect(rect(wrapper)).toEqual({ gridX: 3, gridY: 2, gridWidth: 4, gridHeight: 4 }) + }) +}) + +describe('WidgetMovePanel reset', () => { + it('renders nothing while closed and resets the pending rectangle when reopened', async () => { + const wrapper = mountPanel({ open: false }) + expect(wrapper.find('[data-test="widget-move-panel"]').exists()).toBe(false) + + await wrapper.setProps({ open: true }) + await wrapper.find('[data-test="move-down"]').trigger('click') + await wrapper.setProps({ open: false }) + await wrapper.setProps({ open: true }) + await flushPromises() + + expect(rect(wrapper)).toEqual({ gridX: 3, gridY: 2, gridWidth: 4, gridHeight: 4 }) + }) + + it('takes the new placement when it changes, defaulting missing geometry', async () => { + const wrapper = mountPanel() + + await wrapper.setProps({ placement: { id: 'p2', gridX: 1, gridY: 'x' } }) + + expect(rect(wrapper)).toEqual({ gridX: 1, gridY: 0, gridWidth: 2, gridHeight: 2 }) + }) +}) diff --git a/src/modals/__tests__/WidgetMovePanel.spec.js b/src/modals/__tests__/WidgetMovePanel.spec.js index 2c062f83d..ceef60c66 100644 --- a/src/modals/__tests__/WidgetMovePanel.spec.js +++ b/src/modals/__tests__/WidgetMovePanel.spec.js @@ -11,7 +11,7 @@ * - no pointer/mouse events are required to drive any of this */ -import { mount } from '@vue/test-utils' +import { flushPromises, mount } from '@vue/test-utils' import { beforeEach, describe, expect, it } from 'vitest' import WidgetMovePanel from '../WidgetMovePanel.vue' @@ -131,4 +131,15 @@ describe('WidgetMovePanel', () => { expect(panel.attributes('aria-label')).toBeTruthy() expect(panel.attributes('tabindex')).toBe('0') }) + + it('a panel that mounts already open takes the keyboard focus', async () => { + const wrapper = mount(WidgetMovePanel, { + propsData: { open: true, placement: { id: 'p1', gridX: 3, gridY: 2, gridWidth: 4, gridHeight: 4 }, allPlacements: [], gridColumns: 12 }, + stubs, + attachTo: document.body, + }) + await flushPromises() + expect(document.activeElement).toBe(wrapper.find('[data-test="widget-move-panel"]').element) + wrapper.unmount() + }) }) diff --git a/src/modals/__tests__/WidgetPickerModal.boardSync.spec.js b/src/modals/__tests__/WidgetPickerModal.boardSync.spec.js new file mode 100644 index 000000000..d66de792f --- /dev/null +++ b/src/modals/__tests__/WidgetPickerModal.boardSync.spec.js @@ -0,0 +1,165 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The widget picker as board LpWidgetKiezen draws it (widget-picker-board-sync): + * the dashboard over the title, the kinds with their counts, choosing and + * placing a card, the grey card for what the role may not add and the label + * for an older widget type. + * + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import WidgetPickerModal from '../WidgetPickerModal.vue' + +const stubs = { + NcModal: { props: ['name'], emits: ['close'], template: '<div class="nc-modal" :data-name="name"><slot /></div>' }, + NcTextField: { + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: '<input class="nc-text" :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcEmptyContent: { props: ['description'], template: '<div class="nc-empty">{{ description }}</div>' }, + NcButton: { props: ['disabled'], emits: ['click'], template: '<button class="nc-button" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, +} + +/** + * Mount the picker. + * + * @param {object} props Extra props. + * @return {object} The wrapper. + */ +function mountPicker(props = {}) { + return mount(WidgetPickerModal, { + props: { + open: true, + dashboardName: 'My workspace', + widgets: [{ id: 'notes', title: 'Notes', itemApiVersions: [] }], + customTypes: [ + { type: 'clock', title: 'Clock' }, + { type: 'iframe', title: 'Embedded page' }, + { type: 'pie-chart', title: 'Pie chart' }, + { type: 'graph', title: 'Graph' }, + ], + catalogueApps: [{ uuid: 'z1', name: 'Case system', description: 'Cases', icon: '', iconType: 'class' }], + ...props, + }, + global: { stubs, mocks: { t: (_app, text) => text } }, + }) +} + +const kind = (wrapper, id) => wrapper.find(`[data-testid="widget-picker-kind-${id}"]`) +const titles = (wrapper) => wrapper.findAll('.widget-picker__widget .widget-picker__widget-title').map((node) => node.text()) +const add = (wrapper) => wrapper.find('[data-testid="widget-picker-add"]') + +describe('WidgetPickerModal as LpWidgetKiezen draws it', () => { + it('puts the dashboard over "Add widget", then the search, the kinds and the sections', () => { + const wrapper = mountPicker() + const heading = wrapper.find('.widget-picker__heading') + expect(heading.find('.widget-picker__dashboard').text()).toBe('My workspace') + expect(heading.find('h2').text()).toBe('Add widget') + const html = wrapper.html() + const order = ['widget-picker__heading', 'widget-picker__search', 'widget-picker__kinds', 'widget-picker__list', 'widget-picker__actions'].map((name) => html.indexOf(name)) + expect([...order].sort((a, b) => a - b)).toEqual(order) + expect(wrapper.find('.widget-picker__grid').exists()).toBe(true) + expect(mountPicker({ dashboardName: '' }).find('.widget-picker__dashboard').exists()).toBe(false) + }) + + it('lists the kinds with their counts in a navigation, All chosen', () => { + const wrapper = mountPicker() + expect(wrapper.find('nav.widget-picker__kinds').attributes('aria-label')).toBe('Kinds of widget') + expect(wrapper.findAll('.widget-picker__kind').map((node) => `${node.find('.widget-picker__kind-label').text()} ${node.find('.widget-picker__kind-count').text()}`)).toEqual([ + 'All 8', 'Content 2', 'Tiles and links 2', 'People 0', 'Data and charts 2', 'From other apps 1', 'Office 1', + ]) + expect(kind(wrapper, 'all').attributes('aria-pressed')).toBe('true') + }) + + it('shows only the chosen kind, its count equal to its cards, and searches within it', async () => { + const wrapper = mountPicker() + await kind(wrapper, 'data').trigger('click') + expect(kind(wrapper, 'data').attributes('aria-pressed')).toBe('true') + expect(kind(wrapper, 'all').attributes('aria-pressed')).toBe('false') + expect(titles(wrapper)).toEqual(['Pie chart', 'Graph']) + expect(kind(wrapper, 'data').text()).toContain('2') + + await wrapper.find('.nc-text').setValue('graph') + expect(titles(wrapper)).toEqual(['Graph']) + await wrapper.find('.nc-text').setValue('clock') + expect(wrapper.find('.nc-empty').text()).toBe('No widgets found') + }) + + it('chooses a card on a click, places it only with Add widget, and Cancel closes', async () => { + const wrapper = mountPicker() + expect(add(wrapper).attributes('disabled')).toBeDefined() + + const clock = wrapper.find('[data-testid="widget-picker-type-clock"]') + await clock.trigger('click') + expect(clock.attributes('aria-pressed')).toBe('true') + expect(clock.classes()).toContain('widget-picker__widget--chosen') + expect(wrapper.emitted('addCustom')).toBeUndefined() + expect(add(wrapper).attributes('disabled')).toBeUndefined() + + await add(wrapper).trigger('click') + expect(wrapper.emitted('addCustom')).toEqual([['clock']]) + expect(add(wrapper).attributes('disabled')).toBeDefined() + + await wrapper.find('[data-testid="widget-picker-cancel"]').trigger('click') + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('places a card on a double click', async () => { + const wrapper = mountPicker() + await wrapper.find('[data-testid="widget-picker-catalogue-z1"]').trigger('dblclick') + expect(wrapper.emitted('addCatalogueApp')[0][0]).toMatchObject({ uuid: 'z1' }) + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('forgets a choice the search hides', async () => { + const wrapper = mountPicker() + await wrapper.find('[data-testid="widget-picker-type-clock"]').trigger('click') + await wrapper.find('.nc-text').setValue('graph') + expect(add(wrapper).attributes('disabled')).toBeDefined() + }) + + it('shows what the role may not add as a grey card that cannot be chosen', async () => { + const wrapper = mountPicker({ allowedWidgets: ['clock', 'pie-chart', 'graph', 'notes', 'tile'] }) + const card = wrapper.find('[data-testid="widget-picker-type-iframe"]') + expect(card.classes()).toContain('widget-picker__widget--disabled') + expect(card.attributes('aria-disabled')).toBe('true') + expect(card.text()).toContain('Not allowed for your role') + expect(wrapper.find('[data-testid="widget-picker-type-clock"]').attributes('aria-disabled')).toBe('false') + + await card.trigger('click') + expect(card.attributes('aria-pressed')).toBe('false') + expect(add(wrapper).attributes('disabled')).toBeDefined() + await card.trigger('dblclick') + expect(wrapper.emitted('addCustom')).toBeUndefined() + }) + + it('labels an older Nextcloud widget type', () => { + const card = mountPicker().find('[data-testid="widget-picker-widget-notes"]') + expect(card.text()).toContain('Older widget type') + expect(card.text()).toContain('A widget from another Nextcloud app.') + }) + + it('draws an app tile in its colour and ends the App tiles with Own tile', () => { + const wrapper = mountPicker() + const section = wrapper.find('[data-testid="widget-picker-section-tiles"]') + const cards = section.findAll('.widget-picker__widget') + expect(cards.map((card) => card.find('.widget-picker__widget-title').text())).toEqual(['Case system', 'Own tile']) + expect(cards[0].find('.widget-picker__tile-swatch').attributes('style')).toContain('--widget-picker-tile-colour') + expect(cards[1].find('.widget-picker__tile-swatch--own').exists()).toBe(true) + }) + + it('starts again on All with no choice after it closes', async () => { + const wrapper = mountPicker() + await kind(wrapper, 'data').trigger('click') + await wrapper.find('[data-testid="widget-picker-type-graph"]').trigger('click') + await wrapper.setProps({ open: false }) + await wrapper.setProps({ open: true }) + expect(kind(wrapper, 'all').attributes('aria-pressed')).toBe('true') + expect(add(wrapper).attributes('disabled')).toBeDefined() + }) +}) diff --git a/src/modals/__tests__/WidgetPickerModal.catalogue.spec.js b/src/modals/__tests__/WidgetPickerModal.catalogue.spec.js new file mode 100644 index 000000000..94f82f265 --- /dev/null +++ b/src/modals/__tests__/WidgetPickerModal.catalogue.spec.js @@ -0,0 +1,154 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * launcher-app-catalogue: the add flow lists the catalogue entries the + * server returned for the user, narrows them with the search box, asks the + * host to place one as a tile, and offers "Can't find your app?" to ask IT + * for a missing one. + * + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md + */ + +import { flushPromises, mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import WidgetPickerModal from '../WidgetPickerModal.vue' +import { tileFromCatalogueApp } from '../../utils/discoveredTile.js' + +const stubs = { + NcModal: { template: '<div class="nc-modal"><slot /></div>' }, + NcTextField: { + props: ['modelValue', 'label'], + emits: ['update:modelValue'], + template: '<input class="nc-text" :aria-label="label" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcButton: { + props: ['disabled', 'type', 'variant'], + emits: ['click'], + template: '<button class="nc-button" :type="type || \'button\'" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', + }, + NcEmptyContent: { template: '<div class="nc-empty"><slot name="icon" /></div>' }, +} + +const ZAAK = { uuid: 'z1', name: 'Zaaksysteem', description: 'Cases and permits', icon: 'icon-folder', iconType: 'class', linkType: 'url', linkValue: 'https://zaken.example.nl' } +const AGENDA = { uuid: 'a1', name: 'Agenda', description: 'Your calendar', icon: '/apps/calendar/img/calendar.svg', iconType: 'url', linkType: 'app', linkValue: 'calendar' } + +/** + * Mount the picker. + * + * @param {object} props Extra props. + * @return {object} The wrapper. + */ +function mountPicker(props = {}) { + return mount(WidgetPickerModal, { + props: { open: true, widgets: [], catalogueApps: [ZAAK, AGENDA], ...props }, + global: { stubs, mocks: { t: (_app, text) => text } }, + }) +} + +const rows = (wrapper) => wrapper.findAll('[data-testid^="widget-picker-catalogue-"]') + +describe('From the app catalogue', () => { + it('lists the entries the server returned, with their descriptions', () => { + const wrapper = mountPicker() + // widget-picker-board-sync REQ-WDG-042: the catalogue's apps are the App tiles. + const section = wrapper.find('[data-testid="widget-picker-section-tiles"]') + expect(section.find('h3').text()).toBe('App tiles') + expect(rows(wrapper).map((row) => row.text())).toEqual([ + expect.stringContaining('Zaaksysteem'), + expect.stringContaining('Agenda'), + ]) + expect(rows(wrapper)[0].text()).toContain('Cases and permits') + expect(rows(wrapper)[0].find('span.icon-folder').exists()).toBe(true) + expect(rows(wrapper)[1].find('img').attributes('src')).toBe('/apps/calendar/img/calendar.svg') + }) + + it('narrows with the same search box', async () => { + const wrapper = mountPicker() + await wrapper.find('.nc-text').setValue('zaak') + expect(rows(wrapper)).toHaveLength(1) + expect(rows(wrapper)[0].text()).toContain('Zaaksysteem') + await wrapper.find('.nc-text').setValue('calendar') + expect(rows(wrapper)[0].text()).toContain('Agenda') + }) + + it('asks the host to place the picked entry with Add widget', async () => { + const wrapper = mountPicker() + await rows(wrapper)[0].trigger('click') + await wrapper.find('[data-testid="widget-picker-add"]').trigger('click') + expect(wrapper.emitted('addCatalogueApp')[0]).toEqual([ZAAK]) + }) + + it('is left out when the catalogue has nothing for the user', () => { + expect(mountPicker({ catalogueApps: [] }).find('[data-testid="widget-picker-catalogue"]').exists()).toBe(false) + }) + + it('turns an entry into an ordinary tile', () => { + expect(tileFromCatalogueApp(ZAAK)).toEqual({ title: 'Zaaksysteem', icon: 'icon-folder', iconType: 'class', linkType: 'url', linkValue: 'https://zaken.example.nl' }) + expect(tileFromCatalogueApp(AGENDA)).toEqual({ title: 'Agenda', icon: '/apps/calendar/img/calendar.svg', iconType: 'url', linkType: 'app', linkValue: 'calendar' }) + expect(tileFromCatalogueApp({ name: 'X', linkType: 'odd', linkValue: 'https://x.nl' })).toEqual({ title: 'X', icon: '', iconType: 'class', linkType: 'url', linkValue: 'https://x.nl' }) + }) +}) + +describe("Can't find your app?", () => { + const openForm = async (wrapper) => { + await wrapper.find('[data-testid="widget-picker-request"] .nc-button').trigger('click') + } + + it('is offered only when the host can send a request', () => { + expect(mountPicker().find('[data-testid="widget-picker-request"]').exists()).toBe(false) + expect(mountPicker({ requestAppFn: vi.fn() }).find('[data-testid="widget-picker-request"]').text()).toContain("Can't find your app?") + }) + + it('sends the name and purpose and says the request was sent', async () => { + const requestAppFn = vi.fn().mockResolvedValue({}) + const wrapper = mountPicker({ requestAppFn }) + await wrapper.find('.nc-text').setValue('kaart') + await openForm(wrapper) + const fields = wrapper.findAll('form .nc-text') + expect(fields[0].element.value).toBe('kaart') + await fields[0].setValue('Kaartviewer') + await fields[1].setValue(' Ik moet percelen bekijken bij vergunningen ') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(requestAppFn).toHaveBeenCalledWith({ appName: 'Kaartviewer', purpose: 'Ik moet percelen bekijken bij vergunningen' }) + expect(wrapper.find('[role="status"]').text()).toBe('Your request was sent to IT') + expect(wrapper.find('[role="status"]').classes()).not.toContain('widget-picker__request-message--error') + }) + + it('names the open-request limit when the server refuses', async () => { + const requestAppFn = vi.fn().mockRejectedValue({ response: { status: 429, data: { code: 'request_limit' } } }) + const wrapper = mountPicker({ requestAppFn }) + await openForm(wrapper) + await wrapper.findAll('form .nc-text')[0].setValue('Kaartviewer') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.find('[role="status"]').text()).toBe('You have 10 open requests. Wait for an answer first.') + expect(wrapper.find('[role="status"]').classes()).toContain('widget-picker__request-message--error') + }) + + it('says when a request could not be sent, and sends nothing without a name', async () => { + const requestAppFn = vi.fn().mockRejectedValue(new Error('offline')) + const wrapper = mountPicker({ requestAppFn }) + await openForm(wrapper) + await wrapper.find('form').trigger('submit') + expect(requestAppFn).not.toHaveBeenCalled() + + await wrapper.findAll('form .nc-text')[0].setValue('Kaartviewer') + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(wrapper.find('[role="status"]').text()).toBe('Your request could not be sent. Try again later.') + }) + + it('closes and forgets the form when the picker closes', async () => { + const wrapper = mountPicker({ requestAppFn: vi.fn() }) + await openForm(wrapper) + await wrapper.findAll('form .nc-text')[0].setValue('Kaartviewer') + await wrapper.setProps({ open: false }) + await wrapper.setProps({ open: true }) + expect(wrapper.find('form').exists()).toBe(false) + expect(wrapper.vm.requestAppName).toBe('') + }) +}) diff --git a/src/modals/__tests__/WidgetPickerModal.discovered.spec.js b/src/modals/__tests__/WidgetPickerModal.discovered.spec.js new file mode 100644 index 000000000..7da84534a --- /dev/null +++ b/src/modals/__tests__/WidgetPickerModal.discovered.spec.js @@ -0,0 +1,131 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * launcher-discover-server-services: the add flow lists the apps this server + * runs for the user, marks the ones already on the dashboard, and a click + * asks the host to place one as a tile. + * + * @spec openspec/changes/archive/2026-11-19-launcher-discover-server-services/specs/tiles/spec.md + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import WidgetPickerModal from '../WidgetPickerModal.vue' +import { appTileFromDiscoveredApp, discoveredAppIdsOnDashboard } from '../../utils/discoveredTile.js' + +const stubs = { + NcModal: { template: '<div class="nc-modal"><slot /></div>' }, + NcTextField: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<input class="nc-text" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcEmptyContent: { template: '<div class="nc-empty"><slot name="icon" /></div>' }, + NcButton: { props: ['disabled'], emits: ['click'], template: '<button class="nc-button" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, +} + +const DECK = { appId: 'deck', name: 'Deck', href: '/apps/deck/', icon: '/apps/deck/img/deck.svg' } +const CHAT = { appId: 'context_chat_ui', name: 'Context Chat', href: '/apps/app_api/embedded/context_chat_ui/', icon: '/apps/app_api/img/app.svg' } + +function mountPicker(props = {}) { + return mount(WidgetPickerModal, { + props: { open: true, widgets: [], discoveredApps: [DECK, CHAT], placedAppIds: ['deck'], ...props }, + global: { stubs, mocks: { t: (_app, text) => text } }, + }) +} + +const SECTION = '[data-testid="widget-picker-section-tiles"]' + +/** + * Choose a card and press Add widget. + * + * @param {object} wrapper the mounted picker. + * @param {object} card the card. + * @return {Promise<void>} + */ +async function place(wrapper, card) { + await card.trigger('click') + await wrapper.find('[data-testid="widget-picker-add"]').trigger('click') +} + +describe('App tiles', () => { + it('lists the discovered apps with their names', () => { + const wrapper = mountPicker() + const section = wrapper.find(SECTION) + expect(section.exists()).toBe(true) + expect(section.find('h3').text()).toBe('App tiles') + expect(section.findAll('[data-testid^="widget-picker-app-tile-"]').map((row) => row.text())).toEqual([ + expect.stringContaining('Deck'), + expect.stringContaining('Context Chat'), + ]) + expect(section.find('[data-testid="widget-picker-custom-tile"]').text()).toContain('Own tile') + expect(section.findAll('.widget-picker__widget').at(-1).attributes('data-testid')).toBe('widget-picker-custom-tile') + }) + + it('marks an app already on the dashboard', () => { + const rows = mountPicker().findAll(`${SECTION} [data-testid^="widget-picker-app-tile-"]`) + expect(rows[0].text()).toContain('On this dashboard') + expect(rows[1].text()).not.toContain('On this dashboard') + }) + + it('narrows with the search box', async () => { + const wrapper = mountPicker() + await wrapper.find('.nc-text').setValue('chat') + const rows = wrapper.findAll(`${SECTION} .widget-picker__widget`) + expect(rows).toHaveLength(1) + expect(rows[0].text()).toContain('Context Chat') + }) + + it('asks the host to place the chosen app with Add widget, also when it is there already', async () => { + const wrapper = mountPicker() + await place(wrapper, wrapper.get('[data-testid="widget-picker-app-tile-deck"]')) + expect(wrapper.emitted('addApp')[0]).toEqual([DECK]) + expect(wrapper.emitted('close')).toHaveLength(1) + }) + + it('draws each app entry in the colour its tile gets', () => { + const swatch = mountPicker().get('[data-testid="widget-picker-app-tile-deck"] .widget-picker__tile-swatch') + expect(swatch.attributes('style')).toContain('--cn-app-tile-deck') + }) + + it('offers a custom tile that opens the tile form', async () => { + const wrapper = mountPicker({ discoveredApps: [] }) + await place(wrapper, wrapper.get('[data-testid="widget-picker-custom-tile"]')) + expect(wrapper.emitted('addCustom')[0]).toEqual(['tile']) + }) + + it('leaves the custom tile out when the search does not match it', async () => { + const wrapper = mountPicker({ discoveredApps: [] }) + await wrapper.find('.nc-text').setValue('weather') + expect(wrapper.find(SECTION).exists()).toBe(false) + }) +}) + +describe('the tile a discovered app becomes', () => { + it('is an app tile for that app, in its default colour, with its count', () => { + expect(appTileFromDiscoveredApp(DECK)).toEqual({ + type: 'app-tile', + content: { appId: 'deck', colour: '', showCount: true }, + }) + }) + + it('names an app without its own page by its menu id too', () => { + expect(appTileFromDiscoveredApp(CHAT).content.appId).toBe('context_chat_ui') + }) + + it('reads which apps are on the dashboard from its app-tile widgets', () => { + expect(discoveredAppIdsOnDashboard([ + { widgetId: 'app-tile', content: { appId: 'deck' } }, + { widgetId: 'app-tile', content: {} }, + ], [DECK, CHAT])).toEqual(['deck']) + }) + + it('reads which apps are on the dashboard from its app tiles', () => { + expect(discoveredAppIdsOnDashboard([ + { tileLinkType: 'app', tileLinkValue: 'deck' }, + { tileLinkType: 'url', tileLinkValue: '/apps/app_api/embedded/context_chat_ui/' }, + { widgetId: 'weather' }, + ], [DECK, CHAT])).toEqual(['deck', 'context_chat_ui']) + }) +}) diff --git a/src/modals/__tests__/WidgetPickerModal.office.spec.js b/src/modals/__tests__/WidgetPickerModal.office.spec.js new file mode 100644 index 000000000..469026d11 --- /dev/null +++ b/src/modals/__tests__/WidgetPickerModal.office.spec.js @@ -0,0 +1,75 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * integrations-office-tiles REQ-OFT-001: the add flow offers "Office tiles", + * one click asks the host to place the pack, and a search for something else + * leaves it out. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import WidgetPickerModal from '../WidgetPickerModal.vue' + +const stubs = { + NcModal: { template: '<div class="nc-modal"><slot /></div>' }, + NcTextField: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<input class="nc-text" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcEmptyContent: { template: '<div class="nc-empty"><slot name="icon" /></div>' }, + NcButton: { props: ['disabled'], emits: ['click'], template: '<button class="nc-button" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, +} + +/** + * Choose a card and press Add widget. + * + * @param {object} wrapper the mounted picker. + * @param {object} card the card. + * @return {Promise<void>} + */ +async function place(wrapper, card) { + await card.trigger('click') + await wrapper.find('[data-testid="widget-picker-add"]').trigger('click') +} + + +function mountPicker(props = {}) { + return mount(WidgetPickerModal, { + props: { open: true, widgets: [{ id: 'notes', title: 'Notes' }], ...props }, + global: { stubs, mocks: { t: (_app, text) => text } }, + }) +} + +describe('Office tiles in the picker', () => { + it('offers the pack and asks the host to place it', async () => { + const wrapper = mountPicker() + const pack = wrapper.find('[data-testid="widget-picker-office-pack"]') + + expect(pack.text()).toContain('Office tiles') + await place(wrapper, pack) + + expect(wrapper.emitted('addOfficePack')).toHaveLength(1) + expect(wrapper.emitted('add')).toBeUndefined() + }) + + it('keeps the pack for a matching search and drops it for another', async () => { + const wrapper = mountPicker() + await wrapper.find('input.nc-text').setValue('office') + expect(wrapper.find('[data-testid="widget-picker-office-pack"]').exists()).toBe(true) + + await wrapper.find('input.nc-text').setValue('notes') + expect(wrapper.find('[data-testid="widget-picker-office-pack"]').exists()).toBe(false) + }) + + it('shows the empty state only when the pack is filtered out too', async () => { + const wrapper = mountPicker({ widgets: [] }) + expect(wrapper.find('.nc-empty').exists()).toBe(false) + + await wrapper.find('input.nc-text').setValue('zzz') + expect(wrapper.find('.nc-empty').exists()).toBe(true) + }) +}) diff --git a/src/modals/__tests__/WidgetPickerModal.sections.spec.js b/src/modals/__tests__/WidgetPickerModal.sections.spec.js new file mode 100644 index 000000000..8138a6b26 --- /dev/null +++ b/src/modals/__tests__/WidgetPickerModal.sections.spec.js @@ -0,0 +1,116 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The picker the Meer menu's "Add widget" opens is the one place to add + * anything: the app catalogue, Launchpad's own widget types, the Nextcloud + * widgets, the office tile pack and the apps discovered on this server. + * + * @spec openspec/changes/archive/2026-11-19-launcher-discover-server-services/specs/tiles/spec.md + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md + * @spec openspec/specs/widgets/spec.md#requirement-widget-picker-req-wdg-010 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import WidgetPickerModal from '../WidgetPickerModal.vue' + +const stubs = { + NcModal: { template: '<div class="nc-modal"><slot /></div>' }, + NcTextField: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<input class="nc-text" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcEmptyContent: { template: '<div class="nc-empty"><slot name="icon" /></div>' }, + NcButton: { props: ['disabled'], emits: ['click'], template: '<button class="nc-button" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, +} + +/** + * Choose a card and press Add widget. + * + * @param {object} wrapper the mounted picker. + * @param {object} card the card. + * @return {Promise<void>} + */ +async function place(wrapper, card) { + await card.trigger('click') + await wrapper.find('[data-testid="widget-picker-add"]').trigger('click') +} + + +const FILES = { appId: 'files', name: 'Files', href: '/apps/files', icon: '' } +const MAIL = { uuid: 'c-1', name: 'Mail', icon: '', iconType: 'url' } + +function mountPicker(props = {}) { + return mount(WidgetPickerModal, { + props: { + open: true, + widgets: [{ id: 'notes', title: 'Notes' }], + discoveredApps: [FILES], + catalogueApps: [MAIL], + customTypes: [{ type: 'text', title: 'Text' }, { type: 'image', title: 'Image' }], + ...props, + }, + global: { stubs, mocks: { t: (_app, text) => text } }, + }) +} + +describe('WidgetPickerModal sections', () => { + it('shows the Launchpad widgets, the App tiles and the other apps\' widgets, in that order', () => { + const wrapper = mountPicker() + const ids = wrapper + .findAll('section[data-testid^="widget-picker-section-"]') + .map((section) => section.attributes('data-testid')) + + expect(ids).toEqual([ + 'widget-picker-section-launchpad', + 'widget-picker-section-tiles', + 'widget-picker-section-apps', + ]) + expect(wrapper.findAll('section h3').map((h) => h.text())).toEqual(['Widgets from Launchpad', 'App tiles', 'From other Nextcloud apps']) + expect(wrapper.find('[data-testid="widget-picker-section-launchpad"] [data-testid="widget-picker-office-pack"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="widget-picker-section-tiles"]').text()).toContain('Mail') + expect(wrapper.find('[data-testid="widget-picker-section-tiles"]').text()).toContain('Files') + expect(wrapper.find('[data-testid="widget-picker-section-apps"]').text()).toContain('Notes') + expect(wrapper.find('.nc-empty').exists()).toBe(false) + }) + + it('places what each section offers through its own event', async () => { + const wrapper = mountPicker() + + await place(wrapper, wrapper.find('[data-testid="widget-picker-catalogue-c-1"]')) + await place(wrapper, wrapper.find('[data-testid="widget-picker-office-pack"]')) + await place(wrapper, wrapper.find('[data-testid="widget-picker-app-tile-files"]')) + + expect(wrapper.emitted('addCatalogueApp')).toEqual([[MAIL]]) + expect(wrapper.emitted('addOfficePack')).toHaveLength(1) + expect(wrapper.emitted('addApp')).toEqual([[FILES]]) + }) + + it('lists each Launchpad type and asks for its form when one is picked', async () => { + const wrapper = mountPicker() + + expect(wrapper.findAll('[data-testid^="widget-picker-type-"] .widget-picker__widget-title').map((row) => row.text())).toEqual(['Text', 'Image']) + await place(wrapper, wrapper.find('[data-testid="widget-picker-type-image"]')) + + expect(wrapper.emitted('addCustom')).toEqual([['image']]) + expect(wrapper.emitted('add')).toBeUndefined() + }) + + it('searches the Launchpad types by title and leaves the section out without a match', async () => { + const wrapper = mountPicker({ discoveredApps: [], catalogueApps: [] }) + + await wrapper.find('.nc-text').setValue('IMA') + expect(wrapper.findAll('[data-testid^="widget-picker-type-"] .widget-picker__widget-title').map((row) => row.text())).toEqual(['Image']) + + await wrapper.find('.nc-text').setValue('nothing like it') + expect(wrapper.find('[data-testid="widget-picker-section-launchpad"]').exists()).toBe(false) + }) + + it('renders nothing while closed', () => { + const wrapper = mountPicker({ open: false }) + expect(wrapper.find('.nc-modal').exists()).toBe(false) + }) +}) diff --git a/src/modals/__tests__/WidgetPickerModal.spec.js b/src/modals/__tests__/WidgetPickerModal.spec.js new file mode 100644 index 000000000..e70ba8d61 --- /dev/null +++ b/src/modals/__tests__/WidgetPickerModal.spec.js @@ -0,0 +1,140 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the widget list in `WidgetPickerModal.vue`: order + * (unplaced first, then by `order`), the placed badge, search, the empty + * state, the add event and resetting the search on close. The discovered + * apps section has its own spec. Since widget-picker-board-sync the Nextcloud + * widgets stand as cards under "From other Nextcloud apps", and a card is + * placed with Add widget after it is chosen. + * + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md#requirement-the-widget-picker-as-lpwidgetkiezen-draws-it-req-wdg-040 + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import WidgetPickerModal from '../WidgetPickerModal.vue' + +const stubs = { + NcModal: { emits: ['close'], template: '<div class="nc-modal"><slot /></div>' }, + NcTextField: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: '<input class="nc-text" :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', + }, + NcEmptyContent: { props: ['description'], template: '<div class="nc-empty">{{ description }}</div>' }, + NcButton: { props: ['disabled'], emits: ['click'], template: '<button class="nc-button" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>' }, +} + +const WIDGETS = [ + { id: 'notes', title: 'Notes', order: 3 }, + { id: 'mail', title: 'Mail', order: 1, iconUrl: '/mail.svg' }, + { id: 'deck', title: 'Deck', order: 2, iconClass: 'icon-deck' }, + { id: 'talk', title: 'Talk' }, +] + +function mountPicker(props = {}) { + return mount(WidgetPickerModal, { + props: { open: true, widgets: WIDGETS, placedWidgetIds: ['mail'], ...props }, + global: { stubs, mocks: { t: (_app, text) => text } }, + }) +} + +/** + * The widget rows outside the discovered-apps section, as their titles. + * + * @param {object} wrapper the mounted picker. + * @return {string[]} the titles in display order. + */ +function titles(wrapper) { + return rowsOf(wrapper).map((row) => row.find('.widget-picker__widget-title').text()) +} + +/** + * The Nextcloud widget cards. + * + * @param {object} wrapper the mounted picker. + * @return {Array<object>} the cards. + */ +function rowsOf(wrapper) { + return wrapper.findAll('[data-testid="widget-picker-section-apps"] .widget-picker__widget') +} + +/** + * Choose a card and press Add widget. + * + * @param {object} wrapper the mounted picker. + * @param {object} card the card. + * @return {Promise<void>} + */ +async function place(wrapper, card) { + await card.trigger('click') + await wrapper.find('[data-testid="widget-picker-add"]').trigger('click') +} + +describe('WidgetPickerModal widget list', () => { + it('renders nothing while closed', () => { + expect(mountPicker({ open: false }).find('.nc-modal').exists()).toBe(false) + }) + + it('lists unplaced widgets by order first, placed widgets last', () => { + expect(titles(mountPicker())).toEqual(['Talk', 'Deck', 'Notes', 'Mail']) + }) + + it('badges a placed widget and shows its icon', () => { + const rows = rowsOf(mountPicker()) + const mail = rows[3] + + expect(mail.find('.widget-picker__widget-badge').text()).toBe('Already added') + expect(mail.find('img').attributes('src')).toBe('/mail.svg') + expect(rows[1].find('span.icon-deck').exists()).toBe(true) + expect(rows[0].find('.widget-picker__widget-badge').exists()).toBe(false) + }) + + it('filters by title, case-insensitively', async () => { + const wrapper = mountPicker() + await wrapper.find('.nc-text').setValue('DE') + expect(titles(wrapper)).toEqual(['Deck']) + }) + + it('shows the empty state when nothing matches', async () => { + const wrapper = mountPicker() + expect(wrapper.find('.nc-empty').exists()).toBe(false) + + await wrapper.find('.nc-text').setValue('zzz') + + expect(titles(wrapper)).toEqual([]) + expect(wrapper.find('.nc-empty').text()).toBe('No widgets found') + }) + + it('emits add with the widget id once chosen and placed, placed or not, and closes', async () => { + const wrapper = mountPicker() + await rowsOf(wrapper)[0].trigger('click') + expect(wrapper.emitted('add')).toBeUndefined() + + await place(wrapper, rowsOf(wrapper)[0]) + await place(wrapper, rowsOf(wrapper)[3]) + expect(wrapper.emitted('add')).toEqual([['talk'], ['mail']]) + expect(wrapper.emitted('close')).toHaveLength(2) + }) + + it('clears the search when closed', async () => { + const wrapper = mountPicker() + await wrapper.find('.nc-text').setValue('deck') + + await wrapper.setProps({ open: false }) + expect(wrapper.vm.searchQuery).toBe('') + + await wrapper.setProps({ open: true }) + expect(titles(wrapper)).toHaveLength(4) + expect(wrapper.vm.chosenKind).toBe('all') + }) + + it('keeps the search while the modal stays open', async () => { + const wrapper = mountPicker() + await wrapper.find('.nc-text').setValue('deck') + await wrapper.setProps({ widgets: [...WIDGETS] }) + expect(wrapper.vm.searchQuery).toBe('deck') + }) +}) diff --git a/src/modals/__tests__/helpers/scheduledExportStubs.js b/src/modals/__tests__/helpers/scheduledExportStubs.js new file mode 100644 index 000000000..ef9c9dce1 --- /dev/null +++ b/src/modals/__tests__/helpers/scheduledExportStubs.js @@ -0,0 +1,102 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Small stand-ins for the `@conduction/nextcloud-vue` components the + * scheduled-exports screens use, shared by their specs through + * `vi.mock('@conduction/nextcloud-vue', () => import('./helpers/scheduledExportStubs.js'))`. + * Each renders plain HTML and keeps the props/events the screens rely on, + * so a spec can type, pick, click and read what is shown. + */ + +export const NcModal = { + name: 'NcModal', + props: ['name', 'size'], + emits: ['close'], + template: '<div class="modal"><slot /></div>', +} + +export const NcButton = { + name: 'NcButton', + props: ['disabled', 'variant'], + emits: ['click'], + template: + '<button type="button" :disabled="disabled" @click="$emit(\'click\')"><slot name="icon" /><slot /></button>', +} + +function field(tag) { + return { + props: ['modelValue', 'label', 'helperText', 'type'], + emits: ['update:modelValue'], + template: `<${tag} :aria-label="label" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />`, + } +} + +export const NcTextField = { name: 'NcTextField', ...field('input') } +export const NcPasswordField = { name: 'NcPasswordField', ...field('input') } +export const NcTextArea = { name: 'NcTextArea', ...field('textarea') } + +export const NcSelect = { + name: 'NcSelect', + props: ['modelValue', 'options', 'inputLabel', 'label', 'clearable'], + emits: ['update:modelValue'], + template: + '<select :aria-label="inputLabel" @change="$emit(\'update:modelValue\', options[$event.target.selectedIndex])">' + + '<option v-for="o in options" :key="o.label" :selected="modelValue && o.label === modelValue.label">{{ o.label }}</option>' + + '</select>', +} + +export const NcCheckboxRadioSwitch = { + name: 'NcCheckboxRadioSwitch', + props: ['modelValue', 'type'], + emits: ['update:modelValue'], + template: + '<label><input type="checkbox" :checked="modelValue" @change="$emit(\'update:modelValue\', $event.target.checked)"><slot /></label>', +} + +export const NcNoteCard = { + name: 'NcNoteCard', + props: ['type'], + template: '<div class="note"><slot /></div>', +} + +export const NcLoadingIcon = { + name: 'NcLoadingIcon', + template: '<span class="loading" />', +} + +export const NcActions = { + name: 'NcActions', + template: '<div class="actions"><slot /></div>', +} + +export const NcActionButton = { + name: 'NcActionButton', + props: ['disabled', 'closeAfterClick'], + emits: ['click'], + template: + '<button type="button" :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', +} + +export const CnConfirmDialog = { + name: 'CnConfirmDialog', + props: ['dialogTitle', 'message', 'confirmLabel'], + emits: ['confirm', 'close'], + template: + '<div class="confirm">{{ message }}<button type="button" data-testid="confirm" @click="$emit(\'confirm\')">{{ confirmLabel }}</button></div>', +} + +/** Renders each row with the column slots, like the library table, and emits `row-click`. */ +export const CnDataTable = { + name: 'CnDataTable', + props: ['columns', 'rows', 'loading', 'emptyText', 'rowKey'], + emits: ['row-click'], + template: + '<table><tbody>' + + '<tr v-for="row in rows" :key="row.id" class="row" @click="$emit(\'row-click\', row)">' + + '<td v-for="col in columns" :key="col.key"><slot :name="\'column-\' + col.key" :row="row" :value="row[col.key]">{{ row[col.key] }}</slot></td>' + + '<td><slot name="row-actions" :row="row" /></td>' + + '</tr>' + + '<tr v-if="!rows || rows.length === 0"><td class="empty">{{ emptyText }}</td></tr>' + + '</tbody></table>', +} diff --git a/src/public.js b/src/public.js index 1862eaabf..fe21dc43e 100644 --- a/src/public.js +++ b/src/public.js @@ -12,43 +12,59 @@ // Widget types self-register via import-time side effects that `sideEffects` // tree-shaking (ADR-061) would otherwise drop; calling this no-op forces the // aggregator — and every widget registration — into the bundle. See main.js. -import { registerBuiltinDashboardWidgets } from '@conduction/nextcloud-vue' +import { + registerBuiltinDashboardWidgets, + registerTranslations, +} from '@conduction/nextcloud-vue' import { translatePlural as n, translate as t } from '@nextcloud/l10n' import { createPinia } from 'pinia' import { createApp, h } from 'vue' import DashboardPublicShareView from './views/DashboardPublicShareView.vue' +import { hideCursorWhenIdle, isKioskMode, KIOSK_CLASS } from './utils/kioskMode.js' +import { loadInitialState } from './utils/loadInitialState.js' +import { publicPageToken } from './utils/publicStart.js' import './publicPath.js' import 'gridstack/dist/gridstack.min.css' +// The library's own stylesheet (board look, widgets, dialogs). Without it +// the page only had the library CSS another app's bundle happened to load. +import '@conduction/nextcloud-vue/css/index.css' +import './styles/kiosk.css' registerBuiltinDashboardWidgets() +// The library's own strings (the greeting header among them) in the +// viewer's language. See main.js. +registerTranslations() // Vue 3 has no global Vue constructor — pinia and t/n are installed on the // app instance created below (`Vue.prototype.x` becomes an app-level mixin). const pinia = createPinia() -// The token is the last path segment of /apps/launchpad/s/{token}. -// -// This previously read a `public-share-token` initial-state key first, -// described as the primary source. That read was dead: no PHP ever provides -// that key (PageController::publicShare renders the template without any -// provideInitialState call), so it always returned the fallback and the path -// parse below did the real work — as templates/public.php already documents. -// It also broke REQ-INIT-003, which routes every initial-state read through -// src/utils/loadInitialState.js. The page is served anonymously, so adding a -// key to that contract would be a server change with no consumer; reading the -// URL is the correct source here. -const pathSegments = window.location.pathname.replace(/\/+$/, '').split('/') -const token = pathSegments[pathSegments.length - 1] || '' +// The token is the last path segment of /apps/launchpad/s/{token}, read from +// the URL: the share page is rendered without initial state. The public start +// page at /apps/launchpad/start is the exception (sharing-public-start-page +// D3): the server hands over the chosen link's token as `publicStartToken`, +// read through the initial-state contract (REQ-INIT-003), and the view adds +// its sign-in bar. +const { token, startPage } = publicPageToken( + window.location.pathname, + loadInitialState('public-start').publicStartToken, +) // Props are flat in Vue 3 — the Vue-2 `{ props: { … } }` createElement data // object is gone. const app = createApp({ name: 'LaunchpadPublicShareRoot', - render: () => h(DashboardPublicShareView, { token }), + render: () => h(DashboardPublicShareView, { token, startPage }), }) app.mixin({ methods: { t, n } }) app.use(pinia) app.mount('#public-share-vue') +// REQ-KIOSK-001: a public kiosk screen has no scrollbars and hides an idle cursor. +if (isKioskMode()) { + document.documentElement.classList.add(KIOSK_CLASS) + hideCursorWhenIdle(document) +} + export default app diff --git a/src/registry.js b/src/registry.js index abebf6650..5ef87e264 100644 --- a/src/registry.js +++ b/src/registry.js @@ -12,10 +12,15 @@ * and the manifest names it, so it has to be resolvable by name. */ -import AdminSettingsRedirect from './views/AdminSettingsRedirect.vue' -import WorkspaceApp from './views/WorkspaceApp.vue' +import { defineAsyncComponent } from 'vue' + +// The dashboard view and everything under it load as a chunk of their own, +// fetched when the dashboard route first renders. +const WorkspaceApp = defineAsyncComponent(() => import(/* webpackChunkName: "workspace" */ './views/WorkspaceApp.vue').then((m) => m.default)) +const AdminPage = defineAsyncComponent(() => import(/* webpackChunkName: "admin-page" */ './views/AdminPage.vue').then((m) => m.default)) export default { WorkspaceApp: { kind: 'page', component: WorkspaceApp }, - AdminSettingsRedirect: { kind: 'page', component: AdminSettingsRedirect }, + // The administration (admin-settings REQ-ADM-030), loaded with the admin routes. + AdminPage: { kind: 'page', component: AdminPage }, } diff --git a/src/services/__tests__/activityReport.spec.js b/src/services/__tests__/activityReport.spec.js new file mode 100644 index 000000000..8509a3fef --- /dev/null +++ b/src/services/__tests__/activityReport.spec.js @@ -0,0 +1,67 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The activity report client: the query, a refusal as an answer, and the + * CSV link over the same query (dashboards-and-who-may-see-them REQ-DWMS-005/006). + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const get = vi.fn() +vi.mock('@nextcloud/axios', () => ({ default: { get: (...args) => get(...args) } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) + +import { activityReportCsvUrl, loadActivityReport } from '../activityReport.js' + +beforeEach(() => { + get.mockReset() +}) + +describe('loadActivityReport', () => { + it('leaves the user out when it is yourself, and passes the period', async () => { + get.mockResolvedValue({ data: { subject: 'me', self: true, from: '2026-09-01', to: '2026-09-30', purpose: null, available: true, counts: { a: 2 }, days: { '2026-09-03': 2 }, total: 2 } }) + + const report = await loadActivityReport({ user: ' ', from: '2026-09-01', to: '2026-09-30' }) + + expect(get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/activity-report', { params: { from: '2026-09-01', to: '2026-09-30' } }) + expect(report).toEqual({ refused: false, subject: 'me', self: true, from: '2026-09-01', to: '2026-09-30', purpose: null, available: true, counts: { a: 2 }, days: { '2026-09-03': 2 }, total: 2 }) + }) + + it('sends the trimmed user and keeps the purpose', async () => { + get.mockResolvedValue({ data: { subject: 'alice', self: false, from: '2026-09-01', to: '2026-09-30', purpose: 'workload balancing', available: true, counts: [], days: null, total: '0' } }) + + const report = await loadActivityReport({ user: ' alice ', from: '2026-09-01', to: '2026-09-30' }) + + expect(get.mock.calls[0][1].params.user).toBe('alice') + expect(report.purpose).toBe('workload balancing') + expect(report.counts).toEqual({}) + expect(report.days).toEqual({}) + expect(report.total).toBe(0) + }) + + it('answers a refusal with its status and whether reporting is on', async () => { + get.mockRejectedValue({ response: { status: 403, data: { error: 'off', activityReportingEnabled: false } } }) + + await expect(loadActivityReport({ user: 'alice', from: '2026-09-01', to: '2026-09-30' })) + .resolves.toEqual({ refused: true, status: 403, message: 'off', enabled: false }) + }) + + it('throws anything else', async () => { + get.mockRejectedValue({ response: { status: 500, data: {} } }) + + await expect(loadActivityReport({ user: '', from: '2026-09-01', to: '2026-09-30' })).rejects.toEqual({ response: { status: 500, data: {} } }) + }) +}) + +describe('activityReportCsvUrl', () => { + it('asks the export for the same person and period', () => { + expect(activityReportCsvUrl({ user: 'alice', from: '2026-09-01', to: '2026-09-30' })) + .toBe('/index.php/apps/launchpad/api/activity-report/export?user=alice&from=2026-09-01&to=2026-09-30') + }) + + it('leaves the user out for yourself', () => { + expect(activityReportCsvUrl({ user: '', from: '2026-09-01', to: '2026-09-02' })) + .toBe('/index.php/apps/launchpad/api/activity-report/export?from=2026-09-01&to=2026-09-02') + }) +}) diff --git a/src/services/__tests__/api.spec.js b/src/services/__tests__/api.spec.js new file mode 100644 index 000000000..f0d92adaf --- /dev/null +++ b/src/services/__tests__/api.spec.js @@ -0,0 +1,344 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The `api` client: for each call, the HTTP verb, the URL (with path + * segments encoded), the body and the query/request options it sends, and + * the branches that add or leave out optional parameters. + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../api.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +const B = '/index.php/apps/launchpad' +const VERBS = ['get', 'post', 'put', 'delete'] + +beforeEach(() => { + for (const verb of VERBS) { + axios[verb].mockReset() + axios[verb].mockReturnValue(`${verb}-response`) + } +}) + +/** + * Assert exactly one axios call was made, with this verb and arguments, + * and that the client returned its promise unchanged. + * + * @param {*} returned what the api method returned. + * @param {string} verb the expected axios method. + * @param {Array} args the expected arguments. + */ +function expectOnly(returned, verb, ...args) { + expect(returned).toBe(`${verb}-response`) + expect(axios[verb]).toHaveBeenCalledTimes(1) + expect(axios[verb]).toHaveBeenCalledWith(...args) + for (const other of VERBS.filter((v) => v !== verb)) { + expect(axios[other]).not.toHaveBeenCalled() + } +} + +describe('api: plain calls', () => { + const data = { name: 'x' } + const CASES = [ + ['getDashboards', [], 'get', [`${B}/api/dashboards`]], + ['createGroupDashboard', ['g 1', data], 'post', [`${B}/api/dashboards/group/g%201`, data]], + ['updateGroupDashboard', ['g/1', 'u?', data], 'put', [`${B}/api/dashboards/group/g%2F1/u%3F`, data]], + ['deleteGroupDashboard', ['g', 'u'], 'delete', [`${B}/api/dashboards/group/g/u`]], + ['getActiveDashboard', [], 'get', [`${B}/api/dashboard`]], + ['setActiveDashboardPreference', ['u1'], 'post', [`${B}/api/dashboards/active`, { uuid: 'u1' }]], + ['setDefaultDashboardPreference', ['u1'], 'post', [`${B}/api/dashboards/default`, { uuid: 'u1' }]], + ['clearDefaultDashboardPreference', [], 'post', [`${B}/api/dashboards/default`, { uuid: '' }]], + ['getDefaultDashboardPreference', [], 'get', [`${B}/api/dashboards/default`]], + ['createDashboard', [data], 'post', [`${B}/api/dashboard`, data]], + ['updateDashboard', [3, data], 'put', [`${B}/api/dashboard/3`, data]], + ['activateDashboard', [3], 'post', [`${B}/api/dashboard/3/activate`]], + ['getDashboardById', [3], 'get', [`${B}/api/dashboard/3`]], + ['listGroupDashboards', ['a&b'], 'get', [`${B}/api/dashboards/group/a%26b`]], + ['setGroupDashboardDefault', ['g', 'u'], 'post', [`${B}/api/dashboards/group/g/default`, { uuid: 'u' }]], + ['acquireLock', ['u 1'], 'post', [`${B}/api/dashboards/u%201/lock`]], + ['heartbeatLock', ['u'], 'put', [`${B}/api/dashboards/u/lock`]], + ['releaseLock', ['u'], 'delete', [`${B}/api/dashboards/u/lock`]], + ['releaseLockOnPageHide', ['u'], 'delete', [`${B}/api/dashboards/u/lock`, { adapter: 'fetch', fetchOptions: { keepalive: true } }]], + ['forceReleaseLock', ['u'], 'post', [`${B}/api/dashboards/u/lock/force-release`]], + ['listVersions', ['u'], 'get', [`${B}/api/dashboards/u/versions`]], + ['createVersion', ['u', 'note'], 'post', [`${B}/api/dashboards/u/versions`, { note: 'note' }]], + ['restoreVersion', ['u', 4], 'post', [`${B}/api/dashboards/u/versions/4/restore`]], + ['publishDashboard', ['u'], 'post', [`${B}/api/dashboards/u/publish`]], + ['unpublishDashboard', ['u'], 'post', [`${B}/api/dashboards/u/unpublish`]], + ['recordDashboardViewEvent', ['u'], 'post', [`${B}/api/dashboards/u/view-event`, {}]], + ['recordTileClick', ['p#1'], 'post', [`${B}/api/tile-click/p%231`, {}]], + ['getTileAnalyticsConfig', [], 'get', [`${B}/api/tile-analytics/config`]], + ['getDashboardTree', [], 'get', [`${B}/api/dashboards/tree`]], + ['getDashboardPath', ['u'], 'get', [`${B}/api/dashboards/u/path`]], + ['listShares', [9], 'get', [`${B}/api/dashboard/9/shares`]], + ['replaceShares', [9, ['s']], 'put', [`${B}/api/dashboard/9/shares`, { shares: ['s'] }]], + ['searchSharees', ['ali'], 'get', [`${B}/api/sharees`, { params: { query: 'ali' } }]], + ['getAvailableWidgets', [], 'get', [`${B}/api/widgets`]], + ['getCalendarWidgetCalendars', [], 'get', [`${B}/api/widgets/calendar/calendars`]], + ['addWidget', [9, data], 'post', [`${B}/api/dashboard/9/widgets`, data]], + ['addTile', [9, data], 'post', [`${B}/api/dashboard/9/tile`, data]], + ['importBookmarks', [9, data], 'post', [`${B}/api/dashboard/9/tiles/import`, data]], + ['discoverApps', [], 'get', [`${B}/api/tiles/discover`]], + ['updateWidgetPlacement', [5, data], 'put', [`${B}/api/widgets/5`, data]], + ['removeWidget', [5], 'delete', [`${B}/api/widgets/5`]], + ['getWidgetRules', [5], 'get', [`${B}/api/widgets/5/rules`]], + ['addWidgetRule', [5, data], 'post', [`${B}/api/widgets/5/rules`, data]], + ['deleteRule', [6], 'delete', [`${B}/api/rules/6`]], + ['updateRule', [6, data], 'put', [`${B}/api/rules/6`, data]], + ['previewVisibility', [data], 'post', [`${B}/api/visibility/preview`, data]], + ['getAdminWidgetsWithRules', [], 'get', [`${B}/api/admin/widgets/with-rules`]], + ['getMetrics', [], 'get', [`${B}/api/metrics`, { responseType: 'text' }]], + ['getHealth', [], 'get', [`${B}/api/health`]], + ['getAdminTemplates', [], 'get', [`${B}/api/admin/templates`]], + ['getShippedTemplates', [], 'get', [`${B}/api/admin/templates/shipped`]], + ['installShippedTemplate', ['t1'], 'post', [`${B}/api/admin/templates/shipped/t1/install`]], + ['createAdminTemplate', [data], 'post', [`${B}/api/admin/templates`, data]], + ['updateAdminTemplate', [2, data], 'put', [`${B}/api/admin/templates/2`, data]], + ['deleteAdminTemplate', [2], 'delete', [`${B}/api/admin/templates/2`]], + ['resyncAdminTemplate', [2, { strategy: 'merge', dryRun: true }], 'post', [`${B}/api/admin/templates/2/resync`, { strategy: 'merge', dryRun: true }]], + ['getAdminSettings', [], 'get', [`${B}/api/admin/settings`]], + ['getStoreConfig', [], 'get', [`${B}/api/store/config`]], + ['updateStoreConfig', [data], 'put', [`${B}/api/store/config`, data]], + ['updateAdminSettings', [data], 'put', [`${B}/api/admin/settings`, data]], + ['getAdminGroups', [], 'get', [`${B}/api/admin/groups`]], + ['updateAdminGroupOrder', [['a', 'b']], 'post', [`${B}/api/admin/groups`, { groups: ['a', 'b'] }]], + ['getActionMatrix', [], 'get', [`${B}/api/admin/action-matrix`]], + ['updateActionMatrix', [{ a: 1 }], 'put', [`${B}/api/admin/action-matrix`, { matrix: { a: 1 } }]], + ['getSetupWizardState', [], 'get', [`${B}/api/admin/setup-wizard/state`]], + ['completeSetupWizard', [], 'post', [`${B}/api/admin/setup-wizard/complete`]], + ['listTranslations', ['u'], 'get', [`${B}/api/dashboards/u/translations`]], + ['createTranslation', ['u', data], 'post', [`${B}/api/dashboards/u/translations`, data]], + ['updateTranslation', ['u', 'pt-BR', data], 'put', [`${B}/api/dashboards/u/translations/pt-BR`, data]], + ['deleteTranslation', ['u', 'de'], 'delete', [`${B}/api/dashboards/u/translations/de`]], + ['setPrimaryTranslation', ['u', 'de'], 'post', [`${B}/api/dashboards/u/translations/de/set-primary`]], + ['getResolvedDashboard', ['u'], 'get', [`${B}/api/dashboards/u/resolved`]], + ['getMetadataFieldDefinitions', [], 'get', [`${B}/api/metadata-fields`]], + ['createMetadataField', [data], 'post', [`${B}/api/admin/metadata-fields`, data]], + ['updateMetadataField', ['f/1', data], 'put', [`${B}/api/admin/metadata-fields/f%2F1`, data]], + ['deleteMetadataField', ['f1'], 'delete', [`${B}/api/admin/metadata-fields/f1`]], + ['getMetadataFields', [], 'get', [`${B}/api/admin/metadata-fields`]], + ['getDashboardMetadata', ['u'], 'get', [`${B}/api/dashboards/u/metadata`]], + ['updateDashboardMetadata', ['u', { k: 'v' }], 'put', [`${B}/api/dashboards/u/metadata`, { metadata: { k: 'v' } }]], + ['getOrgNavigationPosition', [], 'get', [`${B}/api/admin/org-navigation/position`]], + ['updateOrgNavigationPosition', ['top'], 'put', [`${B}/api/admin/org-navigation/position`, { position: 'top' }]], + ['listDemoShowcases', [], 'get', [`${B}/api/admin/demo-showcases`]], + ['uninstallDemoShowcase', ['d 1'], 'delete', [`${B}/api/admin/demo-showcases/d%201`]], + ['getTiles', [], 'get', [`${B}/api/tiles`]], + ['createTile', [data], 'post', [`${B}/api/tiles`, data]], + ['updateTile', [8, data], 'put', [`${B}/api/tiles/8`, data]], + ['deleteTile', [8], 'delete', [`${B}/api/tiles/8`]], + ['getDashboardReactions', ['u'], 'get', [`${B}/api/dashboards/u/reactions`]], + ['addDashboardReaction', ['u', '👍'], 'post', [`${B}/api/dashboards/u/reactions`, { emoji: '👍' }]], + ['getDashboardReactors', ['u', '👍'], 'get', [`${B}/api/dashboards/u/reactions/%F0%9F%91%8D/users`]], + ['removeDashboardReaction', ['u', '👍'], 'delete', [`${B}/api/dashboards/u/reactions/%F0%9F%91%8D`]], + ['getPendingAcknowledgements', [], 'get', [`${B}/api/acknowledgements/pending`]], + ['getAcknowledgementReport', ['k/1'], 'get', [`${B}/api/acknowledgements/report/k%2F1`]], + ] + + it.each(CASES)('%s sends the expected request', (method, args, verb, expected) => { + expectOnly(api[method](...args), verb, ...expected) + }) +}) + +describe('api: optional parameters', () => { + it('getVisibleDashboards adds the metadata filter only when it has keys', () => { + expectOnly(api.getVisibleDashboards(), 'get', `${B}/api/dashboards/visible`) + axios.get.mockClear() + api.getVisibleDashboards({}) + expect(axios.get).toHaveBeenCalledWith(`${B}/api/dashboards/visible`) + axios.get.mockClear() + api.getVisibleDashboards({ team: 'ops' }) + expect(axios.get).toHaveBeenCalledWith(`${B}/api/dashboards/visible`, { + params: { metadata: { team: 'ops' } }, + }) + }) + + it('deleteDashboard sends cascade only when asked', () => { + expectOnly(api.deleteDashboard(4), 'delete', `${B}/api/dashboard/4`) + axios.delete.mockClear() + api.deleteDashboard(4, true) + expect(axios.delete).toHaveBeenCalledWith(`${B}/api/dashboard/4`, { + params: { cascade: true }, + }) + }) + + it.each([[undefined], [null], ['']])('forkDashboard leaves out an empty name (%s)', (name) => { + expectOnly(api.forkDashboard('s/1', name), 'post', `${B}/api/dashboards/s%2F1/fork`, {}) + }) + + it('forkDashboard sends a given name', () => { + expectOnly(api.forkDashboard('s', 'Copy'), 'post', `${B}/api/dashboards/s/fork`, { name: 'Copy' }) + }) + + it('scheduleDashboard adds unpublishAt only when set', () => { + expectOnly(api.scheduleDashboard('u', '2026-01-01'), 'post', `${B}/api/dashboards/u/schedule`, { + publishAt: '2026-01-01', + }) + axios.post.mockClear() + api.scheduleDashboard('u', '2026-01-01', '2026-02-01') + expect(axios.post).toHaveBeenCalledWith(`${B}/api/dashboards/u/schedule`, { + publishAt: '2026-01-01', + unpublishAt: '2026-02-01', + }) + }) + + it('analytics calls default to 30 days and 10 rows', () => { + api.getAnalyticsTopTiles() + api.getAnalyticsTopDashboards('7d', 3) + api.getAnalyticsTileDashboardBreakdown('u 1') + api.getAnalyticsInstanceSummary() + expect(axios.get.mock.calls).toEqual([ + [`${B}/api/admin/analytics/tiles/top`, { params: { period: '30d', limit: 10 } }], + [`${B}/api/admin/analytics/dashboards/top`, { params: { period: '7d', limit: 3 } }], + [`${B}/api/admin/analytics/tiles/by-dashboard/u%201`, { params: { period: '30d' } }], + [`${B}/api/admin/analytics/summary`, { params: { period: '30d' } }], + ]) + }) + + it('CSV exports ask for a blob', () => { + api.getAnalyticsCsvExport() + api.getTileAnalyticsCsvExport('90d') + expect(axios.get.mock.calls).toEqual([ + [`${B}/api/admin/analytics/export`, { params: { period: '30d' }, responseType: 'blob' }], + [`${B}/api/admin/analytics/tiles/export`, { params: { period: '90d' }, responseType: 'blob' }], + ]) + }) + + it.each([ + ['/team/ops/', 'team/ops'], + ['//a//', 'a'], + ['plain', 'plain'], + [null, ''], + [undefined, ''], + ])('getDashboardByPath trims slashes from %s', (path, clean) => { + expectOnly(api.getDashboardByPath(path), 'get', `${B}/api/dashboards/by-path/${clean}`) + }) + + it('getWidgetItems repeats widgets[] and defaults the limit to 7', () => { + api.getWidgetItems(['a', 'b c']) + api.getWidgetItems([], 3) + expect(axios.get.mock.calls).toEqual([ + [`${B}/api/widgets/items?widgets%5B%5D=a&widgets%5B%5D=b+c&limit=7`], + [`${B}/api/widgets/items?limit=3`], + ]) + }) + + it('updateShippedTemplate defaults dryRun to false', () => { + api.updateShippedTemplate('t') + api.updateShippedTemplate('t', { dryRun: true }) + expect(axios.post.mock.calls).toEqual([ + [`${B}/api/admin/templates/shipped/t/update`, { dryRun: false }], + [`${B}/api/admin/templates/shipped/t/update`, { dryRun: true }], + ]) + }) + + it('exportDashboards defaults to site scope and adds a dashboard only when given', () => { + api.exportDashboards() + api.exportDashboards({ scope: 'dashboard', dashboardUuid: 'u1' }) + expect(axios.post.mock.calls).toEqual([ + [`${B}/api/admin/export`, null, { params: { scope: 'site' }, responseType: 'blob' }], + [`${B}/api/admin/export`, null, { params: { scope: 'dashboard', dashboardUuid: 'u1' }, responseType: 'blob' }], + ]) + }) + + it('importDashboards uploads the file as multipart with preserveUuids', () => { + const file = new Blob(['{}']) + api.importDashboards(file) + api.importDashboards(file, { preserveUuids: true }) + + const [[url, form, options], [, , options2]] = axios.post.mock.calls + expect(url).toBe(`${B}/api/admin/import`) + expect(form).toBeInstanceOf(FormData) + expect(form.get('file')).toBeInstanceOf(Blob) + expect(options).toEqual({ + params: { preserveUuids: false }, + headers: { 'Content-Type': 'multipart/form-data' }, + }) + expect(options2.params).toEqual({ preserveUuids: true }) + }) + + it('confluence import sends the file, with a parent only when given', () => { + const file = new Blob(['zip']) + api.confluenceImportDryRun(file) + api.confluenceImport(file) + api.confluenceImport(file, { parentUuid: 'p1' }) + + const calls = axios.post.mock.calls + expect(calls[0][0]).toBe(`${B}/api/admin/import/confluence/dry-run`) + expect(calls[0][1].get('file')).toBeInstanceOf(Blob) + expect(calls[0][2]).toEqual({ headers: { 'Content-Type': 'multipart/form-data' } }) + expect(calls[1][0]).toBe(`${B}/api/admin/import/confluence`) + expect(calls[1][2]).toEqual({ params: {}, headers: { 'Content-Type': 'multipart/form-data' } }) + expect(calls[2][2]).toEqual({ + params: { parentUuid: 'p1' }, + headers: { 'Content-Type': 'multipart/form-data' }, + }) + }) + + it('org navigation defaults to Dutch', () => { + api.getOrgNavigation() + api.getOrgNavigation('en') + api.updateOrgNavigation([{ id: 1 }]) + expect(axios.get.mock.calls).toEqual([ + [`${B}/api/admin/org-navigation`, { params: { lang: 'nl' } }], + [`${B}/api/admin/org-navigation`, { params: { lang: 'en' } }], + ]) + expect(axios.put).toHaveBeenCalledWith( + `${B}/api/admin/org-navigation`, + { tree: [{ id: 1 }] }, + { params: { lang: 'nl' } }, + ) + }) + + it('bulk operations send their uuids with dry-run defaults', () => { + api.bulkDeleteDashboards(['a']) + api.bulkDeleteDashboards(['a'], { dryRun: true, cascade: true }) + api.bulkMoveDashboards(['a'], 'p') + api.bulkStatusDashboards(['a'], 'published') + api.bulkStatusDashboards(['a'], 'scheduled', { publishAt: 'T', dryRun: true }) + api.bulkReindexDashboards(['a']) + expect(axios.post.mock.calls).toEqual([ + [`${B}/api/admin/dashboards/bulk-delete`, { dashboardUuids: ['a'], dryRun: false, cascade: false }], + [`${B}/api/admin/dashboards/bulk-delete`, { dashboardUuids: ['a'], dryRun: true, cascade: true }], + [`${B}/api/admin/dashboards/bulk-move`, { dashboardUuids: ['a'], parentUuid: 'p', dryRun: false }], + [`${B}/api/admin/dashboards/bulk-status`, { dashboardUuids: ['a'], publicationStatus: 'published', publishAt: null, dryRun: false }], + [`${B}/api/admin/dashboards/bulk-status`, { dashboardUuids: ['a'], publicationStatus: 'scheduled', publishAt: 'T', dryRun: true }], + [`${B}/api/admin/dashboards/bulk-reindex`, { dashboardUuids: ['a'], dryRun: false }], + ]) + }) + + it('installDemoShowcase defaults to Dutch and sends force only when set', () => { + api.installDemoShowcase('d/1') + api.installDemoShowcase('d', { lang: 'en', force: true }) + expect(axios.post.mock.calls).toEqual([ + [`${B}/api/admin/demo-showcases/d%2F1/install`, null, { params: { lang: 'nl' } }], + [`${B}/api/admin/demo-showcases/d/install`, null, { params: { lang: 'en', force: true } }], + ]) + }) + + it('acknowledge defaults the content version to 1', () => { + api.acknowledge('policy') + api.acknowledge('policy', 3) + expect(axios.post.mock.calls).toEqual([ + [`${B}/api/acknowledgements`, { announcementKey: 'policy', contentVersion: 1 }], + [`${B}/api/acknowledgements`, { announcementKey: 'policy', contentVersion: 3 }], + ]) + }) + + it('getAcknowledgementReportCsvUrl builds a URL without a request', () => { + expect(api.getAcknowledgementReportCsvUrl('a b')).toBe( + `${B}/api/acknowledgements/report/a%20b/csv`, + ) + for (const verb of VERBS) { + expect(axios[verb]).not.toHaveBeenCalled() + } + }) +}) diff --git a/src/services/__tests__/assignedCases.spec.js b/src/services/__tests__/assignedCases.spec.js new file mode 100644 index 000000000..daff1c162 --- /dev/null +++ b/src/services/__tests__/assignedCases.spec.js @@ -0,0 +1,64 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The assigned cases client: what OpenRegister answers for the viewer's + * cases, the counts per status and the status pills + * (assigned-cases-widget REQ-CASES-001..002). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { caseStatus, loadAssignedCases, READ_LIMIT } from '../assignedCases.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => `/index.php${path.replace(/\{(\w+)\}/g, (_m, key) => params[key])}`, +})) + +const IN_BEHANDELING = { id: 's1', name: 'In behandeling', colour: 'purple' } +const WACHT = { id: 's2', name: 'Wacht op aanvrager', colour: 'orange' } + +beforeEach(() => { + axios.get.mockReset() +}) + +describe('loadAssignedCases', () => { + it('asks OpenRegister for the viewer\'s cases, deadline first, with their status', async () => { + axios.get.mockResolvedValue({ data: { results: [] } }) + await loadAssignedCases({ register: 'dossiq', schema: 'case', userId: 'pieter' }) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/openregister/api/objects/dossiq/case', { + params: { assignee: 'pieter', '_order[deadline]': 'asc', '_extend[]': 'status', _limit: READ_LIMIT }, + }) + }) + + it('leaves closed cases out and counts the open ones per status', async () => { + axios.get.mockResolvedValue({ data: { results: [ + { id: 'c1', title: 'Kapvergunning Molenweg 4', identifier: 'Z-2026-0412', deadline: '2026-10-05', status: IN_BEHANDELING }, + { id: 'c2', title: 'Dakkapel Kerkstraat 12', identifier: 'Z-2026-0440', deadline: '2026-10-21', status: WACHT }, + { id: 'c3', title: 'Evenement Stadshaven', identifier: 'Z-2026-0431', deadline: '2026-10-08', status: IN_BEHANDELING }, + { id: 'c4', title: 'Afgerond', status: { id: 's9', name: 'Afgerond' }, isFinalStatus: true }, + { id: '', title: 'no id' }, + ] } }) + const result = await loadAssignedCases({ register: 'dossiq', schema: 'case', userId: 'pieter' }) + expect(result.state).toBe('ok') + expect(result.total).toBe(3) + expect(result.cases.map((record) => record.identifier)).toEqual(['Z-2026-0412', 'Z-2026-0440', 'Z-2026-0431']) + expect(result.counts).toEqual([ + { key: 's1', label: 'In behandeling', variant: 'purple', count: 2 }, + { key: 's2', label: 'Wacht op aanvrager', variant: 'warning', count: 1 }, + ]) + }) + + it('reads a failure as an error', async () => { + axios.get.mockRejectedValue(new Error('403')) + expect(await loadAssignedCases({ register: 'dossiq', schema: 'case', userId: 'pieter' })).toEqual({ state: 'error', cases: [], counts: [], total: 0 }) + }) +}) + +describe('caseStatus', () => { + it('falls back to the public status label when the status is not extended', () => { + expect(caseStatus({ status: 'uuid-1', statusPublicLabel: 'In behandeling' })).toEqual({ key: 'uuid-1', label: 'In behandeling', variant: 'default' }) + expect(caseStatus({ status: { id: 'x', name: 'Nieuw', colour: 'unknown' } }).variant).toBe('default') + }) +}) diff --git a/src/services/__tests__/attentionFeed.spec.js b/src/services/__tests__/attentionFeed.spec.js new file mode 100644 index 000000000..7a412aa05 --- /dev/null +++ b/src/services/__tests__/attentionFeed.spec.js @@ -0,0 +1,453 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The attention feed's rules (openspec/specs/attention-feed REQ-ATT-003..005): + * tokens, the one filter behind both the count and the link, the comparison, + * the ranking, and what a failure becomes. + * + * The sources are the declarations the proposal asks dossiq, pipelinq, + * decidiq and learniq to ship, in the shape AttentionSourceService returns. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const get = vi.fn() +vi.mock('@nextcloud/axios', () => ({ default: { get: (...args) => get(...args) } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) + +import { + actionPath, + checkSource, + countPath, + expandToRecords, + filterPairs, + loadAttentionFeed, + needsAttention, + rank, + resolveToken, +} from '../attentionFeed.js' + +// Monday 5 October 2026, 14:30 local time. +const ctx = { userId: 'pieter', now: new Date(2026, 9, 5, 14, 30, 0) } + +const dossiq = { + appId: 'dossiq', + appName: 'Dossiq', + id: 'cases-past-deadline', + title: 'Cases past their deadline', + reason: '{value} of your cases are past their deadline or end today.', + severity: 'error', + source: { + register: 'dossiq', + schema: 'case', + filter: { + assignee: '@me', + isFinalStatus: false, + statusHiddenInLists: false, + isDraft: false, + 'deadline[lt]': '@today+1d', + }, + }, + op: 'gt', + value: 0, + action: { label: 'Open these cases', path: '/apps/dossiq/cases' }, +} +const pipelinq = { + appId: 'pipelinq', + appName: 'Pipelinq', + id: 'tickets-past-deadline', + title: 'Tickets past their deadline', + reason: '{value} of your tickets in progress are past their deadline or end today.', + severity: 'error', + source: { + register: 'pipelinq', + schema: 'ticket', + filter: { + assignee: '@me', + status: 'in_progress', + 'slaDeadline[lt]': '@today+1d', + }, + }, + op: 'gt', + value: 0, + action: { label: 'Open these tickets', path: '/apps/pipelinq/tickets' }, +} +const decidiq = { + appId: 'decidiq', + appName: 'Decidiq', + id: 'decisions-open-for-voting', + title: 'Decisions wait for the vote', + reason: '{value} decisions are open for voting.', + severity: 'warning', + source: { + register: 'decidiq', + schema: 'decision', + filter: { lifecycle: 'voting' }, + }, + op: 'gt', + value: 0, + action: { label: 'Open these decisions', path: '/apps/decidiq/decisions' }, +} + +/** Split `a=b&c=d` into decoded pairs. */ +function pairsOf(url) { + const query = url.includes('?') ? url.slice(url.indexOf('?') + 1) : '' + return query === '' + ? [] + : query.split('&').map((part) => part.split('=').map(decodeURIComponent)) +} + +/** Answer each OpenRegister count by register, or reject. */ +function answerCounts(byRegister) { + get.mockImplementation((url) => { + if (url.endsWith('/api/attention/sources')) { + return Promise.resolve({ data: byRegister.__sources }) + } + const register = /\/api\/objects\/([^/]+)\//.exec(url)[1] + const answer = byRegister[register] + return answer instanceof Error + ? Promise.reject(answer) + : Promise.resolve({ data: answer }) + }) +} + +beforeEach(() => { + get.mockReset() +}) + +describe('resolveToken', () => { + it('resolves every token the contract names', () => { + expect(resolveToken('@me', ctx)).toBe('pieter') + expect(resolveToken('@today', ctx)).toBe('2026-10-05') + expect(resolveToken('@today+1d', ctx)).toBe('2026-10-06') + expect(resolveToken('@today-7d', ctx)).toBe('2026-09-28') + expect(resolveToken('@today+30d', ctx)).toBe('2026-11-04') + expect(resolveToken('@monthStart', ctx)).toBe('2026-10-01') + expect(resolveToken('@quarterStart', ctx)).toBe('2026-10-01') + expect(resolveToken('@yearStart', ctx)).toBe('2026-01-01') + expect(resolveToken('@now', ctx)).toBe(ctx.now.toISOString()) + }) + + it('leaves everything that is not a token alone', () => { + expect(resolveToken('in_progress', ctx)).toBe('in_progress') + expect(resolveToken(false, ctx)).toBe(false) + expect(resolveToken(3, ctx)).toBe(3) + expect(resolveToken('mail@example.org', ctx)).toBe('mail@example.org') + }) + + it('throws on a token it does not know, and on @me without a user', () => { + expect(() => resolveToken('@manager', ctx)).toThrow('unknown token @manager') + expect(() => resolveToken('@today+1w', ctx)).toThrow('unknown token') + expect(() => resolveToken('@me', { userId: '', now: ctx.now })).toThrow( + '@me needs a signed-in user', + ) + }) +}) + +describe('the count and the link', () => { + it('the count and the link carry the same filter', () => { + const count = countPath(dossiq, ctx) + const link = actionPath(dossiq) + + expect(count).toBe( + '/apps/openregister/api/objects/dossiq/case' + + '?assignee=pieter&isFinalStatus=false&statusHiddenInLists=false&isDraft=false&deadline[lt]=2026-10-06&_limit=1', + ) + expect(link).toBe( + '/apps/dossiq/cases' + + '?assignee=@me&isFinalStatus=false&statusHiddenInLists=false&isDraft=false&deadline[lt]=@today%2B1d', + ) + + // The serialised addresses, compared: same keys in the same order, + // and each link value resolves to the count's value. This is the + // check all four app lanes had to add after a live defect. + const countPairs = pairsOf(count).filter(([key]) => key !== '_limit') + const linkPairs = pairsOf(link) + expect(linkPairs.map(([key]) => key)).toEqual(countPairs.map(([key]) => key)) + expect( + linkPairs.map(([, value]) => String(resolveToken(value, ctx))), + ).toEqual(countPairs.map(([, value]) => value)) + }) + + it('holds for every declaration the apps are asked to ship', () => { + for (const source of [dossiq, pipelinq, decidiq]) { + const countPairs = pairsOf(countPath(source, ctx)).filter( + ([key]) => key !== '_limit', + ) + const linkPairs = pairsOf(actionPath(source)) + expect( + linkPairs.map(([key]) => key), + source.appId, + ).toEqual(Object.keys(source.source.filter)) + expect( + linkPairs.map(([, value]) => String(resolveToken(value, ctx))), + source.appId, + ).toEqual(countPairs.map(([, value]) => value)) + } + }) + + it('writes a list as repeated key[] pairs in both', () => { + const source = { + ...decidiq, + source: { + register: 'decidiq', + schema: 'governance-commitment', + filter: { lifecycle: ['open', 'in-execution'] }, + }, + } + + expect(filterPairs(source.source.filter)).toEqual([ + ['lifecycle[]', 'open'], + ['lifecycle[]', 'in-execution'], + ]) + expect(countPath(source, ctx)).toContain( + '?lifecycle[]=open&lifecycle[]=in-execution&_limit=1', + ) + expect(actionPath(source)).toBe( + '/apps/decidiq/decisions?lifecycle[]=open&lifecycle[]=in-execution', + ) + }) + + it('links to the bare path when there is no filter', () => { + const source = { + ...decidiq, + source: { register: 'decidiq', schema: 'decision', filter: {} }, + } + + expect(actionPath(source)).toBe('/apps/decidiq/decisions') + expect(countPath(source, ctx)).toBe( + '/apps/openregister/api/objects/decidiq/decision?_limit=1', + ) + }) + + it('encodes a value that could break out of the query', () => { + const source = { + ...decidiq, + source: { register: 'r', schema: 's', filter: { title: 'a&b=c #d' } }, + } + + expect(actionPath(source)).toBe( + '/apps/decidiq/decisions?title=a%26b%3Dc%20%23d', + ) + expect(pairsOf(countPath(source, ctx))).toEqual([ + ['title', 'a&b=c #d'], + ['_limit', '1'], + ]) + }) +}) + +describe('needsAttention', () => { + it('compares with every operator', () => { + expect(needsAttention(1, 'gt', 0)).toBe(true) + expect(needsAttention(0, 'gt', 0)).toBe(false) + expect(needsAttention(0, 'gte', 0)).toBe(true) + expect(needsAttention(2, 'lt', 3)).toBe(true) + expect(needsAttention(3, 'lt', 3)).toBe(false) + expect(needsAttention(3, 'lte', 3)).toBe(true) + expect(needsAttention(3, 'eq', 3)).toBe(true) + expect(needsAttention(3, 'neq', 3)).toBe(false) + expect(() => needsAttention(1, 'contains', 0)).toThrow('unknown operator') + }) +}) + +describe('rank', () => { + it('ranks by severity, then count, then app', () => { + const entry = (appName, severity, count, id = 'x') => ({ + appName, + severity, + count, + id, + }) + const ranked = rank([ + entry('Decidiq', 'warning', 2), + entry('Learniq', 'info', 99), + entry('Dossiq', 'error', 3), + entry('Pipelinq', 'error', 5), + entry('Alpha', 'warning', 2), + entry('Alpha', 'warning', 2, 'a'), + ]) + + expect(ranked.map((e) => `${e.appName}/${e.id}`)).toEqual([ + 'Pipelinq/x', + 'Dossiq/x', + 'Alpha/a', + 'Alpha/x', + 'Decidiq/x', + 'Learniq/x', + ]) + }) +}) + +describe('checkSource', () => { + it('fills the count into the reason and links into the app', async () => { + get.mockResolvedValue({ data: { total: 3, results: [{}] } }) + + const entry = await checkSource(dossiq, ctx) + + expect(get).toHaveBeenCalledTimes(1) + expect(get.mock.calls[0][0]).toBe(`/index.php${countPath(dossiq, ctx)}`) + expect(entry).toMatchObject({ + key: 'dossiq/cases-past-deadline', + failed: false, + count: 3, + attention: true, + reason: '3 of your cases are past their deadline or end today.', + actionLabel: 'Open these cases', + href: `/index.php${actionPath(dossiq)}`, + }) + }) + + it('a zero is checked and needs no attention', async () => { + get.mockResolvedValue({ data: { total: 0, results: [] } }) + + expect(await checkSource(dossiq, ctx)).toMatchObject({ + failed: false, + count: 0, + attention: false, + }) + }) + + it.each([ + [ + 'a server error', + () => Promise.reject(new Error('Request failed with status code 500')), + ], + [ + 'no access', + () => Promise.reject(new Error('Request failed with status code 403')), + ], + [ + 'an answer without a total', + () => Promise.resolve({ data: { results: [] } }), + ], + [ + 'a total that is not a number', + () => Promise.resolve({ data: { total: '3' } }), + ], + ['an empty answer', () => Promise.resolve({ data: null })], + ])('%s is a failure, never a zero', async (_name, answer) => { + get.mockImplementation(answer) + + const entry = await checkSource(dossiq, ctx) + + expect(entry.failed).toBe(true) + expect(entry).not.toHaveProperty('count') + expect(entry).not.toHaveProperty('attention') + }) + + it('an unknown token fails the source and sends nothing', async () => { + const source = { + ...dossiq, + source: { ...dossiq.source, filter: { owner: '@manager' } }, + } + + const entry = await checkSource(source, ctx) + + expect(get).not.toHaveBeenCalled() + expect(entry.failed).toBe(true) + expect(entry.error).toContain('@manager') + }) +}) + +describe('loadAttentionFeed', () => { + it('merges the apps, ranks them and uses the user the endpoint names', async () => { + answerCounts({ + __sources: { + userId: 'pieter', + sources: [decidiq, dossiq, pipelinq], + invalid: [], + }, + dossiq: { total: 3 }, + pipelinq: { total: 5 }, + decidiq: { total: 2 }, + }) + + const feed = await loadAttentionFeed({ now: ctx.now }) + + expect(get.mock.calls[0][0]).toBe( + '/index.php/apps/launchpad/api/attention/sources', + ) + expect(feed.items.map((item) => item.appId)).toEqual([ + 'pipelinq', + 'dossiq', + 'decidiq', + ]) + expect(feed.failedApps).toEqual([]) + expect(feed.sourceCount).toBe(3) + const dossiqCall = get.mock.calls + .map(([url]) => url) + .find((url) => url.includes('/objects/dossiq/')) + expect(dossiqCall).toContain('assignee=pieter') + }) + + it('names a failed app and an invalid declaration, and keeps the others', async () => { + answerCounts({ + __sources: { + userId: 'pieter', + sources: [dossiq, pipelinq], + invalid: [ + { + appId: 'learniq', + appName: 'Learniq', + message: 'item "late": ...', + }, + ], + }, + dossiq: new Error('Request failed with status code 500'), + pipelinq: { total: 5 }, + }) + + const feed = await loadAttentionFeed({ now: ctx.now }) + + expect(feed.items.map((item) => item.appId)).toEqual(['pipelinq']) + expect(feed.failedApps).toEqual(['Dossiq', 'Learniq']) + expect(feed.sourceCount).toBe(3) + }) + + it('reports no sources as no sources', async () => { + answerCounts({ __sources: { userId: 'pieter', sources: [], invalid: [] } }) + + expect(await loadAttentionFeed({ now: ctx.now })).toEqual({ + items: [], + failedApps: [], + sourceCount: 0, + }) + }) + + it('rejects when the sources endpoint itself fails', async () => { + get.mockRejectedValue(new Error('Request failed with status code 500')) + + await expect(loadAttentionFeed()).rejects.toThrow('500') + }) +}) + +describe('expandToRecords (LpVandaag one card per record)', () => { + const entry = { key: 'dossiq/late', id: 'late', appId: 'dossiq', appName: 'dossiq', title: 'Cases past their deadline', severity: 'error', count: 2, itemPath: '/apps/dossiq/cases', schema: 'case' } + + it('makes one item per listed record, named by it, with the source title as reason and a link to it', () => { + const items = expandToRecords([{ ...entry, objects: [{ id: 'a1', title: 'Parking permit Stationsstraat 3' }, { id: 'b2', title: 'Parking permit Kerkstraat 12' }] }], (schema) => `Open ${schema}`) + expect(items.map((i) => [i.title, i.reason, i.actionLabel, i.href])).toEqual([ + ['Parking permit Stationsstraat 3', 'Cases past their deadline', 'Open case', '/index.php/apps/dossiq/cases/a1'], + ['Parking permit Kerkstraat 12', 'Cases past their deadline', 'Open case', '/index.php/apps/dossiq/cases/b2'], + ]) + expect(new Set(items.map((i) => i.key)).size).toBe(2) + }) + + it('names each card\'s action by the source when the source names one (REQ-ATT-007)', () => { + const items = expandToRecords([{ ...entry, actionLabel: 'Zaak openen', objects: [{ id: 'a1', title: 'A' }, { id: 'b2', title: 'B' }] }], (schema) => `Open ${schema}`) + expect(items.map((i) => i.actionLabel)).toEqual(['Zaak openen', 'Zaak openen']) + }) + + it('keeps a source that listed no records as one item', () => { + expect(expandToRecords([{ ...entry, objects: [] }], () => 'Open')).toEqual([{ ...entry, objects: [] }]) + }) +}) + +describe('countPath with records', () => { + it('asks for as many records as the cards can show', () => { + const source = { source: { register: 'dossiq', schema: 'case', filter: {} } } + expect(countPath(source, { perSource: 3 })).toContain('_limit=3') + expect(countPath(source, {})).toContain('_limit=1') + }) +}) diff --git a/src/services/__tests__/dashboardConnections.spec.js b/src/services/__tests__/dashboardConnections.spec.js new file mode 100644 index 000000000..90d6994ea --- /dev/null +++ b/src/services/__tests__/dashboardConnections.spec.js @@ -0,0 +1,96 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The connections one dashboard uses and their states (REQ-LP-CONN-005). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import connectionUses from '../../../lib/Settings/connection-uses.json' +import declarations from '../../../lib/Settings/connections.json' +import { connectionsUsedBy, fetchConnectionRows, joinConnectionStates, lastErrorOf, statusLabelOf } from '../dashboardConnections.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params) => path.replace(/\{(\w+)\}/g, (_, key) => params[key]), +})) + +beforeEach(() => { + axios.get.mockReset() +}) + +describe('connection-uses.json', () => { + it('maps exactly the connections connections.json declares', () => { + expect(Object.keys(connectionUses.connections).sort()).toEqual(declarations.connections.map((c) => c.key).sort()) + }) +}) + +describe('connectionsUsedBy', () => { + it('lists the connections of the management dashboard once each, in declared order, and leaves the unused out', () => { + const placements = [ + { widgetId: 'livetile', content: {} }, + { widgetId: 'news', content: {} }, + { widgetId: 'livetile', content: {} }, + { widgetId: 'text', content: {} }, + ] + expect(connectionsUsedBy(placements).map((c) => c.key)).toEqual(['news-feeds', 'live-tiles']) + }) + + it('counts a tile only when its health ping is on', () => { + expect(connectionsUsedBy([{ widgetId: 'tile', content: { healthPingEnabled: false } }])).toEqual([]) + expect(connectionsUsedBy([{ widgetId: 'app-tile', content: { healthPingEnabled: true } }]).map((c) => c.key)) + .toEqual(['health-ping']) + }) + + it('gives nothing for no placements or a missing list', () => { + expect(connectionsUsedBy([])).toEqual([]) + expect(connectionsUsedBy(null)).toEqual([]) + }) +}) + +describe('status labels and times', () => { + it('names the status as the Integrations page does, and a missing row as not configured', () => { + expect(statusLabelOf({ status: 'configured' })).toBe('Configured') + expect(statusLabelOf({ status: 'error' })).toBe('Error') + expect(statusLabelOf(null)).toBe('Not configured') + }) + + it('takes the last error from the row, else from a failed last check', () => { + expect(lastErrorOf({ lastErrorAt: '2026-11-25T09:30:00Z' })).toBe('2026-11-25T09:30:00Z') + expect(lastErrorOf({ status: 'error', checkedAt: '2026-11-25T09:30:00Z' })).toBe('2026-11-25T09:30:00Z') + expect(lastErrorOf({ status: 'configured', checkedAt: '2026-11-25T09:30:00Z' })).toBeNull() + }) +}) + +describe('joinConnectionStates', () => { + it('joins integriq\'s rows by key with the status, last success, last error and message', () => { + const used = [{ key: 'live-tiles', title: 'Live tiles' }, { key: 'news-feeds', title: 'News feeds' }, { key: 'weather', title: 'Weather provider' }] + const rows = [ + { key: 'live-tiles', title: 'Live tiles', status: 'configured', lastSuccessAt: '2026-11-25T10:44:00Z' }, + { key: 'news-feeds', title: 'News feeds', status: 'error', checkedAt: '2026-11-25T09:30:00Z', statusMessage: 'feeds.example.nl answered 503' }, + { key: 'dashboard-registry', status: 'configured' }, + ] + const lines = joinConnectionStates(used, rows) + expect(lines.map((l) => l.key)).toEqual(['live-tiles', 'news-feeds', 'weather']) + expect(lines[0]).toMatchObject({ statusLabel: 'Configured', isError: false, lastSuccessAt: '2026-11-25T10:44:00Z', lastErrorAt: null }) + expect(lines[1]).toMatchObject({ statusLabel: 'Error', isError: true, lastErrorAt: '2026-11-25T09:30:00Z', message: 'feeds.example.nl answered 503' }) + expect(lines[2]).toMatchObject({ title: 'Weather provider', status: 'unconfigured', statusLabel: 'Not configured', message: '' }) + }) +}) + +describe('fetchConnectionRows', () => { + it('reads this app\'s rows from integriq through OpenRegister', async () => { + axios.get.mockResolvedValue({ data: { results: [{ key: 'news-feeds' }] } }) + expect(await fetchConnectionRows()).toEqual({ state: 'ok', rows: [{ key: 'news-feeds' }] }) + expect(axios.get).toHaveBeenCalledWith( + '/apps/openregister/api/objects/integriq/app_connection', + { params: { app: 'launchpad', _limit: 100 } }, + ) + }) + + it('says error when the read fails', async () => { + axios.get.mockRejectedValue(new Error('403')) + expect(await fetchConnectionRows()).toEqual({ state: 'error', rows: [] }) + }) +}) diff --git a/src/services/__tests__/embedApi.spec.js b/src/services/__tests__/embedApi.spec.js new file mode 100644 index 000000000..657a58c8a --- /dev/null +++ b/src/services/__tests__/embedApi.spec.js @@ -0,0 +1,68 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The admin embed API client calls the token and theme routes with the + * right verbs, paths and bodies (embedded-analytics tasks 15, 16, 17, 27). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { embedApi } from '../embedApi.js' + +const http = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() })) +vi.mock('@nextcloud/axios', () => ({ default: http })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) + +const base = '/index.php/apps/launchpad/api' + +describe('embedApi', () => { + beforeEach(() => { + vi.clearAllMocks() + for (const verb of Object.values(http)) { + verb.mockResolvedValue({ data: { ok: true } }) + } + }) + + it('lists tokens and themes from results, empty when the answer has none', async () => { + http.get.mockResolvedValueOnce({ data: { results: [{ id: 't-1' }] } }).mockResolvedValueOnce({ data: {} }) + expect(await embedApi.listTokens()).toEqual([{ id: 't-1' }]) + expect(await embedApi.listThemes()).toEqual([]) + expect(http.get.mock.calls).toEqual([[`${base}/embed-tokens`], [`${base}/tenant-themes`]]) + }) + + it('sends each token action to its route', async () => { + await embedApi.createToken({ name: 'Zeist' }) + await embedApi.updateToken('t/1', { name: 'Z' }) + await embedApi.revokeToken('t-1', 'other', '') + await embedApi.revokeToken('t-1', 'compromised', 'gelekt') + await embedApi.unrevokeToken('t-1') + await embedApi.reissueToken('t-1') + await embedApi.tokenUsage('t-1') + + expect(http.post.mock.calls).toEqual([ + [`${base}/embed-tokens`, { name: 'Zeist' }], + [`${base}/embed-tokens/t-1/revoke`, { reason: 'other', notes: null }], + [`${base}/embed-tokens/t-1/revoke`, { reason: 'compromised', notes: 'gelekt' }], + [`${base}/embed-tokens/t-1/unrevoke`], + [`${base}/embed-tokens/t-1/re-issue`], + ]) + expect(http.put).toHaveBeenCalledWith(`${base}/embed-tokens/t%2F1`, { name: 'Z' }) + expect(http.get).toHaveBeenCalledWith(`${base}/embed-tokens/t-1/usage`) + }) + + it('sends each theme action to its route, forcing a delete only when asked', async () => { + await embedApi.createTheme({ name: 'Zeist' }) + await embedApi.updateTheme('th-1', { name: 'Zeist' }) + await embedApi.deleteTheme('th-1') + await embedApi.deleteTheme('th-1', true) + + expect(http.post).toHaveBeenCalledWith(`${base}/tenant-themes`, { name: 'Zeist' }) + expect(http.put).toHaveBeenCalledWith(`${base}/tenant-themes/th-1`, { name: 'Zeist' }) + expect(http.delete.mock.calls).toEqual([ + [`${base}/tenant-themes/th-1`, { params: {} }], + [`${base}/tenant-themes/th-1`, { params: { force: true } }], + ]) + }) +}) diff --git a/src/services/__tests__/endpointClients.spec.js b/src/services/__tests__/endpointClients.spec.js new file mode 100644 index 000000000..e56e359f2 --- /dev/null +++ b/src/services/__tests__/endpointClients.spec.js @@ -0,0 +1,205 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The small endpoint clients (health ping, iframe, live tile, weather): the + * URL each one calls, what it returns from the response, and how the + * validators and availability checks fail closed when the request errors. + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { fetchHealthPingBadge, validateHealthPingConfig } from '../healthPingClient.js' +import { checkIframeFramable, validateIframeUrl } from '../iframeClient.js' +import { + fetchConnectorAvailability, + fetchLiveTileValue, + validateLiveTileSource, +} from '../liveTileClient.js' +import { fetchWeatherReading } from '../weatherClient.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + '/index.php' + path.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) + +beforeEach(() => { + axios.get.mockReset() + axios.post.mockReset() +}) + +describe('healthPingClient', () => { + it('fetches the badge of one placement and returns its data', async () => { + const badge = { state: 'up', checkedAt: '2026-01-01', latencyMs: 12, stale: false } + axios.get.mockResolvedValue({ data: badge }) + + await expect(fetchHealthPingBadge(42)).resolves.toBe(badge) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/health-ping/42') + }) + + it('returns an empty object when the response carries no data', async () => { + axios.get.mockResolvedValue({ data: null }) + await expect(fetchHealthPingBadge(1)).resolves.toEqual({}) + axios.get.mockResolvedValue(undefined) + await expect(fetchHealthPingBadge(1)).resolves.toEqual({}) + }) + + it('lets a failed badge request reject so the badge can hide', async () => { + axios.get.mockRejectedValue(new Error('403')) + await expect(fetchHealthPingBadge(1)).rejects.toThrow('403') + }) + + it('posts the config for validation and returns the verdict', async () => { + const verdict = { valid: false, errors: ['host_not_allowed'] } + axios.post.mockResolvedValue({ data: verdict }) + const config = { healthPingEnabled: true, healthUrl: 'https://x.test/h' } + + await expect(validateHealthPingConfig(config)).resolves.toBe(verdict) + expect(axios.post).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/health-ping/validate', + { config }, + ) + }) + + it('treats an empty validation answer as valid', async () => { + axios.post.mockResolvedValue({ data: null }) + await expect(validateHealthPingConfig({})).resolves.toEqual({ valid: true, errors: [] }) + }) + + it('fails closed when the validation endpoint errors', async () => { + axios.post.mockRejectedValue(new Error('500')) + await expect(validateHealthPingConfig({})).resolves.toEqual({ + valid: false, + errors: ['validation_unavailable'], + }) + }) +}) + +describe('iframeClient', () => { + it('posts the config to the URL validator and returns the verdict', async () => { + const verdict = { valid: true, errors: [] } + axios.post.mockResolvedValue({ data: verdict }) + const config = { url: 'https://embed.test', height: 300 } + + await expect(validateIframeUrl(config)).resolves.toBe(verdict) + expect(axios.post).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/iframe/validate-url', + { config }, + ) + }) + + it('treats an empty validator answer as valid and an error as invalid', async () => { + axios.post.mockResolvedValueOnce({}) + await expect(validateIframeUrl({})).resolves.toEqual({ valid: true, errors: [] }) + + axios.post.mockRejectedValueOnce(new Error('network')) + await expect(validateIframeUrl({})).resolves.toEqual({ + valid: false, + errors: ['validation_unavailable'], + }) + }) + + it('asks the server whether a URL may be framed', async () => { + const answer = { framable: true, reason: 'ok' } + axios.post.mockResolvedValue({ data: answer }) + + await expect(checkIframeFramable('https://embed.test/page')).resolves.toBe(answer) + expect(axios.post).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/iframe/framable', + { url: 'https://embed.test/page' }, + ) + }) + + it('reports not framable on an empty answer or a failed check', async () => { + axios.post.mockResolvedValueOnce({ data: undefined }) + await expect(checkIframeFramable('u')).resolves.toEqual({ + framable: false, + reason: 'no_response', + }) + + axios.post.mockRejectedValueOnce(new Error('timeout')) + await expect(checkIframeFramable('u')).resolves.toEqual({ + framable: false, + reason: 'check_unavailable', + }) + }) +}) + +describe('liveTileClient', () => { + it('fetches the value of one placement', async () => { + const reading = { value: 7, formatted: '7', badge: null, fetchedAt: null, stale: true } + axios.get.mockResolvedValue({ data: reading }) + + await expect(fetchLiveTileValue('p-9')).resolves.toBe(reading) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/livetile/p-9') + }) + + it('returns an empty object for an empty value response and rejects on error', async () => { + axios.get.mockResolvedValueOnce({}) + await expect(fetchLiveTileValue(1)).resolves.toEqual({}) + + axios.get.mockRejectedValueOnce(new Error('404')) + await expect(fetchLiveTileValue(1)).rejects.toThrow('404') + }) + + it('offers connector mode only when the status says available === true', async () => { + axios.get.mockResolvedValueOnce({ data: { available: true } }) + await expect(fetchConnectorAvailability()).resolves.toBe(true) + expect(axios.get).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/livetile/connector/status', + ) + + axios.get.mockResolvedValueOnce({ data: { available: 'true' } }) + await expect(fetchConnectorAvailability()).resolves.toBe(false) + + axios.get.mockResolvedValueOnce({ data: null }) + await expect(fetchConnectorAvailability()).resolves.toBe(false) + }) + + it('treats an unreachable status endpoint as unavailable', async () => { + axios.get.mockRejectedValue(new Error('502')) + await expect(fetchConnectorAvailability()).resolves.toBe(false) + }) + + it('validates a source config and fails closed on error', async () => { + const verdict = { valid: false, errors: ['bad_expr'] } + axios.post.mockResolvedValueOnce({ data: verdict }) + const config = { sourceMode: 'url', url: 'https://src.test', valueExpr: '$.n' } + + await expect(validateLiveTileSource(config)).resolves.toBe(verdict) + expect(axios.post).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/livetile/validate-source', + { config }, + ) + + axios.post.mockResolvedValueOnce(null) + await expect(validateLiveTileSource(config)).resolves.toEqual({ valid: true, errors: [] }) + + axios.post.mockRejectedValueOnce(new Error('500')) + await expect(validateLiveTileSource(config)).resolves.toEqual({ + valid: false, + errors: ['validation_unavailable'], + }) + }) +}) + +describe('weatherClient', () => { + it('fetches the reading of one placement', async () => { + const reading = { location: 'Amsterdam', tempValue: 11, units: 'metric', stale: false } + axios.get.mockResolvedValue({ data: reading }) + + await expect(fetchWeatherReading(5)).resolves.toBe(reading) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/weather/5') + }) + + it('returns an empty object without data and rejects on error', async () => { + axios.get.mockResolvedValueOnce({ data: '' }) + await expect(fetchWeatherReading(5)).resolves.toEqual({}) + + axios.get.mockRejectedValueOnce(new Error('500')) + await expect(fetchWeatherReading(5)).rejects.toThrow('500') + }) +}) diff --git a/src/services/__tests__/fetchFinanceSummary.golden.spec.js b/src/services/__tests__/fetchFinanceSummary.golden.spec.js new file mode 100644 index 000000000..c0bdfabf0 --- /dev/null +++ b/src/services/__tests__/fetchFinanceSummary.golden.spec.js @@ -0,0 +1,113 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for fetchFinanceSummary(): a set of GraphQL answers and errors, + * each with the variables sent, compared with + * fixtures/fetchFinanceSummary.golden.json. Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { GraphQLSourceError, queryGraphql } from '../graphqlClient.js' +import { fetchFinanceSummary } from '../spendAnalytics.js' + +vi.mock('../graphqlClient.js', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, queryGraphql: vi.fn() } +}) + +const FIXTURE = path.resolve(__dirname, 'fixtures/fetchFinanceSummary.golden.json') + +const ROWS = [ + { totalAmount: 100, currency: 'EUR', category: 'IT', bookedAt: '2026-01-15' }, + { totalAmount: '50.5', currency: 'USD', category: 'IT', bookedAt: '2026-02-10' }, + { totalAmount: 0.1, category: 'Travel', bookedAt: '2026-01-31T10:00:00Z' }, + { totalAmount: 0.2, currency: 5, category: '', bookedAt: 20260101 }, + { totalAmount: 'abc', category: null, bookedAt: '2025-12' }, + { totalAmount: -30, currency: 'GBP', category: 'Travel' }, + { totalAmount: null, category: 'Office', bookedAt: '' }, + { totalAmount: 7, currency: '', category: 'Office', bookedAt: '2026-02-01' }, +] + +const ANSWERS = { + 'all rows': { transactions: ROWS }, + 'first row only': { transactions: ROWS.slice(0, 1) }, + 'from the second row': { transactions: ROWS.slice(1) }, + 'rows without currency': { transactions: ROWS.slice(2, 5) }, + 'rows reversed': { transactions: [...ROWS].reverse() }, + 'equal amounts': { + transactions: [ + { totalAmount: 5, category: 'B', bookedAt: '2026-03-01' }, + { totalAmount: 5, category: 'A', bookedAt: '2026-01-01' }, + ], + }, + 'empty list': { transactions: [] }, + 'not a list': { transactions: 'nope' }, + 'no transactions key': {}, + null: null, + undefined, + 'null row': { transactions: [null] }, + 'row without fields': { transactions: [{}] }, +} + +const ERRORS = { + 'source error': new GraphQLSourceError( + 'not_installed', + 'financeq', + 'financeq is not installed', + ), + 'other error': new TypeError('boom'), +} + +const PARAMS = { + 'period only': { period: 'month' }, + 'all filters': { period: 'ytd', categoryIds: ['IT'], departmentIds: ['d1'] }, + 'null filters': { period: 'fy', categoryIds: null, departmentIds: undefined }, +} + +/** + * Run one case and record what it resolved to, or what it rejected with, + * and the request it sent. + * + * @param {object} params The aggregation parameters. + * @return {Promise<object>} The outcome. + */ +async function outcome(params) { + try { + const result = await fetchFinanceSummary(params) + return { result, sent: queryGraphql.mock.calls } + } catch (error) { + return { + rejected: `${error.constructor.name}: ${error.message}`, + sent: queryGraphql.mock.calls, + } + } +} + +describe('fetchFinanceSummary (golden)', () => { + it('matches the recorded results', async () => { + const actual = {} + for (const [p, params] of Object.entries(PARAMS)) { + for (const [a, answer] of Object.entries(ANSWERS)) { + queryGraphql.mockReset() + queryGraphql.mockResolvedValue(answer) + actual[`${p} | ${a}`] = await outcome(params) + } + for (const [e, error] of Object.entries(ERRORS)) { + queryGraphql.mockReset() + queryGraphql.mockRejectedValue(error) + actual[`${p} | ${e}`] = await outcome(params) + } + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + for (const key of Object.keys(expected)) { + expect(actual[key], key).toEqual(expected[key]) + } + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + }) +}) diff --git a/src/services/__tests__/fetchPeoplePage.golden.spec.js b/src/services/__tests__/fetchPeoplePage.golden.spec.js new file mode 100644 index 000000000..f17c3bc6c --- /dev/null +++ b/src/services/__tests__/fetchPeoplePage.golden.spec.js @@ -0,0 +1,73 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for fetchPeoplePage(): a set of arguments against a set of + * answers, with the URL requested, compared with + * fixtures/fetchPeoplePage.golden.json. Set RECORD_GOLDEN=1 to rewrite it. + */ + +import axios from '@nextcloud/axios' +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { fetchPeoplePage } from '../widgetDataAdapters.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/fetchPeoplePage.golden.json') + +const ARGS = { + none: undefined, + empty: {}, + 'all set': { + offset: 20, + limit: 10, + filters: [{ field: 'group', value: 'sales' }], + excludeDisabled: true, + sortBy: 'displayName', + }, + 'falsy values': { + offset: 0, + limit: 0, + filters: null, + excludeDisabled: false, + sortBy: '', + }, + 'null paging': { offset: null, limit: null, excludeDisabled: 'yes', sortBy: 5 }, + 'filters object': { filters: { group: 'a & b' } }, +} + +const ANSWERS = { + page: { data: { users: [{ id: 'u1' }], total: 31, hasMore: true } }, + 'loose fields': { data: { users: 'x', total: '31', hasMore: 'true' } }, + 'no data': { data: null }, + 'no response': undefined, +} + +describe('fetchPeoplePage (golden)', () => { + it('matches the recorded results', async () => { + const actual = {} + for (const [a, args] of Object.entries(ARGS)) { + for (const [r, answer] of Object.entries(ANSWERS)) { + axios.get.mockReset() + axios.get.mockResolvedValue(answer) + const result = await fetchPeoplePage(args) + actual[`${a} | ${r}`] = { result, requested: axios.get.mock.calls } + } + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + for (const key of Object.keys(expected)) { + expect(actual[key], key).toEqual(expected[key]) + } + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + }) +}) diff --git a/src/services/__tests__/fixtures/fetchFinanceSummary.golden.json b/src/services/__tests__/fixtures/fetchFinanceSummary.golden.json new file mode 100644 index 000000000..546e8f353 --- /dev/null +++ b/src/services/__tests__/fixtures/fetchFinanceSummary.golden.json @@ -0,0 +1,1568 @@ +{ + "period only | all rows": { + "result": { + "available": true, + "empty": false, + "total": 127.79999999999998, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 150.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 100.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | first row only": { + "result": { + "available": true, + "empty": false, + "total": 100, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 100 + } + ], + "trend": [ + { + "month": "2026-01", + "amount": 100 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | from the second row": { + "result": { + "available": true, + "empty": false, + "total": 27.800000000000004, + "currency": "USD", + "byCategory": [ + { + "category": "IT", + "amount": 50.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 0.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | rows without currency": { + "result": { + "available": true, + "empty": false, + "total": 0.30000000000000004, + "currency": "EUR", + "byCategory": [ + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": 0.1 + } + ], + "trend": [ + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 0.1 + }, + { + "month": "unknown", + "amount": 0.2 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | rows reversed": { + "result": { + "available": true, + "empty": false, + "total": 127.8, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 150.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 100.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | equal amounts": { + "result": { + "available": true, + "empty": false, + "total": 10, + "currency": "EUR", + "byCategory": [ + { + "category": "B", + "amount": 5 + }, + { + "category": "A", + "amount": 5 + } + ], + "trend": [ + { + "month": "2026-01", + "amount": 5 + }, + { + "month": "2026-03", + "amount": 5 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | empty list": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | not a list": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | no transactions key": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | null": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | undefined": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | null row": { + "rejected": "TypeError: Cannot read properties of null (reading 'currency')", + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | row without fields": { + "result": { + "available": true, + "empty": false, + "total": 0, + "currency": "EUR", + "byCategory": [ + { + "category": "uncategorised", + "amount": 0 + } + ], + "trend": [ + { + "month": "unknown", + "amount": 0 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | source error": { + "result": { + "available": false, + "reason": "financeq is not installed", + "code": "not_installed" + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "period only | other error": { + "rejected": "TypeError: boom", + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "month", + "categoryIds": [], + "departmentIds": [] + } + } + ] + ] + }, + "all filters | all rows": { + "result": { + "available": true, + "empty": false, + "total": 127.79999999999998, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 150.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 100.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | first row only": { + "result": { + "available": true, + "empty": false, + "total": 100, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 100 + } + ], + "trend": [ + { + "month": "2026-01", + "amount": 100 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | from the second row": { + "result": { + "available": true, + "empty": false, + "total": 27.800000000000004, + "currency": "USD", + "byCategory": [ + { + "category": "IT", + "amount": 50.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 0.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | rows without currency": { + "result": { + "available": true, + "empty": false, + "total": 0.30000000000000004, + "currency": "EUR", + "byCategory": [ + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": 0.1 + } + ], + "trend": [ + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 0.1 + }, + { + "month": "unknown", + "amount": 0.2 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | rows reversed": { + "result": { + "available": true, + "empty": false, + "total": 127.8, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 150.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 100.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | equal amounts": { + "result": { + "available": true, + "empty": false, + "total": 10, + "currency": "EUR", + "byCategory": [ + { + "category": "B", + "amount": 5 + }, + { + "category": "A", + "amount": 5 + } + ], + "trend": [ + { + "month": "2026-01", + "amount": 5 + }, + { + "month": "2026-03", + "amount": 5 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | empty list": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | not a list": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | no transactions key": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | null": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | undefined": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | null row": { + "rejected": "TypeError: Cannot read properties of null (reading 'currency')", + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | row without fields": { + "result": { + "available": true, + "empty": false, + "total": 0, + "currency": "EUR", + "byCategory": [ + { + "category": "uncategorised", + "amount": 0 + } + ], + "trend": [ + { + "month": "unknown", + "amount": 0 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | source error": { + "result": { + "available": false, + "reason": "financeq is not installed", + "code": "not_installed" + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "all filters | other error": { + "rejected": "TypeError: boom", + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "ytd", + "categoryIds": [ + "IT" + ], + "departmentIds": [ + "d1" + ] + } + } + ] + ] + }, + "null filters | all rows": { + "result": { + "available": true, + "empty": false, + "total": 127.79999999999998, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 150.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 100.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | first row only": { + "result": { + "available": true, + "empty": false, + "total": 100, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 100 + } + ], + "trend": [ + { + "month": "2026-01", + "amount": 100 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | from the second row": { + "result": { + "available": true, + "empty": false, + "total": 27.800000000000004, + "currency": "USD", + "byCategory": [ + { + "category": "IT", + "amount": 50.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 0.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | rows without currency": { + "result": { + "available": true, + "empty": false, + "total": 0.30000000000000004, + "currency": "EUR", + "byCategory": [ + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": 0.1 + } + ], + "trend": [ + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 0.1 + }, + { + "month": "unknown", + "amount": 0.2 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | rows reversed": { + "result": { + "available": true, + "empty": false, + "total": 127.8, + "currency": "EUR", + "byCategory": [ + { + "category": "IT", + "amount": 150.5 + }, + { + "category": "Office", + "amount": 7 + }, + { + "category": "uncategorised", + "amount": 0.2 + }, + { + "category": "Travel", + "amount": -29.9 + } + ], + "trend": [ + { + "month": "", + "amount": 0 + }, + { + "month": "2025-12", + "amount": 0 + }, + { + "month": "2026-01", + "amount": 100.1 + }, + { + "month": "2026-02", + "amount": 57.5 + }, + { + "month": "unknown", + "amount": -29.8 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | equal amounts": { + "result": { + "available": true, + "empty": false, + "total": 10, + "currency": "EUR", + "byCategory": [ + { + "category": "B", + "amount": 5 + }, + { + "category": "A", + "amount": 5 + } + ], + "trend": [ + { + "month": "2026-01", + "amount": 5 + }, + { + "month": "2026-03", + "amount": 5 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | empty list": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | not a list": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | no transactions key": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | null": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | undefined": { + "result": { + "available": true, + "empty": true, + "total": 0, + "currency": "EUR", + "byCategory": [], + "trend": [] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | null row": { + "rejected": "TypeError: Cannot read properties of null (reading 'currency')", + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | row without fields": { + "result": { + "available": true, + "empty": false, + "total": 0, + "currency": "EUR", + "byCategory": [ + { + "category": "uncategorised", + "amount": 0 + } + ], + "trend": [ + { + "month": "unknown", + "amount": 0 + } + ] + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | source error": { + "result": { + "available": false, + "reason": "financeq is not installed", + "code": "not_installed" + }, + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + }, + "null filters | other error": { + "rejected": "TypeError: boom", + "sent": [ + [ + { + "app": "financeq", + "query": "query SpendSummary($period: String!, $categoryIds: [String!], $departmentIds: [String!]) {\n transactions(period: $period, categoryIds: $categoryIds, departmentIds: $departmentIds)\n {\n totalAmount\n currency\n category\n bookedAt\n }\n}", + "variables": { + "period": "fy", + "categoryIds": null, + "departmentIds": [] + } + } + ] + ] + } +} diff --git a/src/services/__tests__/fixtures/fetchPeoplePage.golden.json b/src/services/__tests__/fixtures/fetchPeoplePage.golden.json new file mode 100644 index 000000000..248bde3f1 --- /dev/null +++ b/src/services/__tests__/fixtures/fetchPeoplePage.golden.json @@ -0,0 +1,314 @@ +{ + "none | page": { + "result": { + "users": [ + { + "id": "u1" + } + ], + "total": 31, + "hasMore": true + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?limit=50&offset=0" + ] + ] + }, + "none | loose fields": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?limit=50&offset=0" + ] + ] + }, + "none | no data": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?limit=50&offset=0" + ] + ] + }, + "none | no response": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?limit=50&offset=0" + ] + ] + }, + "empty | page": { + "result": { + "users": [ + { + "id": "u1" + } + ], + "total": 31, + "hasMore": true + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?limit=50&offset=0" + ] + ] + }, + "empty | loose fields": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?limit=50&offset=0" + ] + ] + }, + "empty | no data": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?limit=50&offset=0" + ] + ] + }, + "empty | no response": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?limit=50&offset=0" + ] + ] + }, + "all set | page": { + "result": { + "users": [ + { + "id": "u1" + } + ], + "total": 31, + "hasMore": true + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%5B%7B%22field%22%3A%22group%22%2C%22value%22%3A%22sales%22%7D%5D&excludeDisabled=1&sortBy=displayName&limit=10&offset=20" + ] + ] + }, + "all set | loose fields": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%5B%7B%22field%22%3A%22group%22%2C%22value%22%3A%22sales%22%7D%5D&excludeDisabled=1&sortBy=displayName&limit=10&offset=20" + ] + ] + }, + "all set | no data": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%5B%7B%22field%22%3A%22group%22%2C%22value%22%3A%22sales%22%7D%5D&excludeDisabled=1&sortBy=displayName&limit=10&offset=20" + ] + ] + }, + "all set | no response": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%5B%7B%22field%22%3A%22group%22%2C%22value%22%3A%22sales%22%7D%5D&excludeDisabled=1&sortBy=displayName&limit=10&offset=20" + ] + ] + }, + "falsy values | page": { + "result": { + "users": [ + { + "id": "u1" + } + ], + "total": 31, + "hasMore": true + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%5B%5D&excludeDisabled=0&limit=0&offset=0" + ] + ] + }, + "falsy values | loose fields": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%5B%5D&excludeDisabled=0&limit=0&offset=0" + ] + ] + }, + "falsy values | no data": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%5B%5D&excludeDisabled=0&limit=0&offset=0" + ] + ] + }, + "falsy values | no response": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%5B%5D&excludeDisabled=0&limit=0&offset=0" + ] + ] + }, + "null paging | page": { + "result": { + "users": [ + { + "id": "u1" + } + ], + "total": 31, + "hasMore": true + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?excludeDisabled=1&sortBy=5&limit=50&offset=0" + ] + ] + }, + "null paging | loose fields": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?excludeDisabled=1&sortBy=5&limit=50&offset=0" + ] + ] + }, + "null paging | no data": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?excludeDisabled=1&sortBy=5&limit=50&offset=0" + ] + ] + }, + "null paging | no response": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?excludeDisabled=1&sortBy=5&limit=50&offset=0" + ] + ] + }, + "filters object | page": { + "result": { + "users": [ + { + "id": "u1" + } + ], + "total": 31, + "hasMore": true + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%7B%22group%22%3A%22a+%26+b%22%7D&limit=50&offset=0" + ] + ] + }, + "filters object | loose fields": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%7B%22group%22%3A%22a+%26+b%22%7D&limit=50&offset=0" + ] + ] + }, + "filters object | no data": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%7B%22group%22%3A%22a+%26+b%22%7D&limit=50&offset=0" + ] + ] + }, + "filters object | no response": { + "result": { + "users": [], + "total": 0, + "hasMore": false + }, + "requested": [ + [ + "/index.php/apps/launchpad/api/people?filters=%7B%22group%22%3A%22a+%26+b%22%7D&limit=50&offset=0" + ] + ] + } +} diff --git a/src/services/__tests__/fixtures/needsAttention.golden.json b/src/services/__tests__/fixtures/needsAttention.golden.json new file mode 100644 index 000000000..9e3f378f1 --- /dev/null +++ b/src/services/__tests__/fixtures/needsAttention.golden.json @@ -0,0 +1,3074 @@ +{ + "gt | zero | zero": { + "result": false + }, + "gt | zero | one": { + "result": false + }, + "gt | zero | five": { + "result": false + }, + "gt | zero | negative": { + "result": true + }, + "gt | zero | string one": { + "result": false + }, + "gt | zero | NaN": { + "result": false + }, + "gt | zero | undefined": { + "result": false + }, + "gt | zero | null": { + "result": false + }, + "gt | one | zero": { + "result": true + }, + "gt | one | one": { + "result": false + }, + "gt | one | five": { + "result": false + }, + "gt | one | negative": { + "result": true + }, + "gt | one | string one": { + "result": false + }, + "gt | one | NaN": { + "result": false + }, + "gt | one | undefined": { + "result": false + }, + "gt | one | null": { + "result": true + }, + "gt | five | zero": { + "result": true + }, + "gt | five | one": { + "result": true + }, + "gt | five | five": { + "result": false + }, + "gt | five | negative": { + "result": true + }, + "gt | five | string one": { + "result": true + }, + "gt | five | NaN": { + "result": false + }, + "gt | five | undefined": { + "result": false + }, + "gt | five | null": { + "result": true + }, + "gt | negative | zero": { + "result": false + }, + "gt | negative | one": { + "result": false + }, + "gt | negative | five": { + "result": false + }, + "gt | negative | negative": { + "result": false + }, + "gt | negative | string one": { + "result": false + }, + "gt | negative | NaN": { + "result": false + }, + "gt | negative | undefined": { + "result": false + }, + "gt | negative | null": { + "result": false + }, + "gt | string one | zero": { + "result": true + }, + "gt | string one | one": { + "result": false + }, + "gt | string one | five": { + "result": false + }, + "gt | string one | negative": { + "result": true + }, + "gt | string one | string one": { + "result": false + }, + "gt | string one | NaN": { + "result": false + }, + "gt | string one | undefined": { + "result": false + }, + "gt | string one | null": { + "result": true + }, + "gt | NaN | zero": { + "result": false + }, + "gt | NaN | one": { + "result": false + }, + "gt | NaN | five": { + "result": false + }, + "gt | NaN | negative": { + "result": false + }, + "gt | NaN | string one": { + "result": false + }, + "gt | NaN | NaN": { + "result": false + }, + "gt | NaN | undefined": { + "result": false + }, + "gt | NaN | null": { + "result": false + }, + "gt | undefined | zero": { + "result": false + }, + "gt | undefined | one": { + "result": false + }, + "gt | undefined | five": { + "result": false + }, + "gt | undefined | negative": { + "result": false + }, + "gt | undefined | string one": { + "result": false + }, + "gt | undefined | NaN": { + "result": false + }, + "gt | undefined | undefined": { + "result": false + }, + "gt | undefined | null": { + "result": false + }, + "gt | null | zero": { + "result": false + }, + "gt | null | one": { + "result": false + }, + "gt | null | five": { + "result": false + }, + "gt | null | negative": { + "result": true + }, + "gt | null | string one": { + "result": false + }, + "gt | null | NaN": { + "result": false + }, + "gt | null | undefined": { + "result": false + }, + "gt | null | null": { + "result": false + }, + "gte | zero | zero": { + "result": true + }, + "gte | zero | one": { + "result": false + }, + "gte | zero | five": { + "result": false + }, + "gte | zero | negative": { + "result": true + }, + "gte | zero | string one": { + "result": false + }, + "gte | zero | NaN": { + "result": false + }, + "gte | zero | undefined": { + "result": false + }, + "gte | zero | null": { + "result": true + }, + "gte | one | zero": { + "result": true + }, + "gte | one | one": { + "result": true + }, + "gte | one | five": { + "result": false + }, + "gte | one | negative": { + "result": true + }, + "gte | one | string one": { + "result": true + }, + "gte | one | NaN": { + "result": false + }, + "gte | one | undefined": { + "result": false + }, + "gte | one | null": { + "result": true + }, + "gte | five | zero": { + "result": true + }, + "gte | five | one": { + "result": true + }, + "gte | five | five": { + "result": true + }, + "gte | five | negative": { + "result": true + }, + "gte | five | string one": { + "result": true + }, + "gte | five | NaN": { + "result": false + }, + "gte | five | undefined": { + "result": false + }, + "gte | five | null": { + "result": true + }, + "gte | negative | zero": { + "result": false + }, + "gte | negative | one": { + "result": false + }, + "gte | negative | five": { + "result": false + }, + "gte | negative | negative": { + "result": true + }, + "gte | negative | string one": { + "result": false + }, + "gte | negative | NaN": { + "result": false + }, + "gte | negative | undefined": { + "result": false + }, + "gte | negative | null": { + "result": false + }, + "gte | string one | zero": { + "result": true + }, + "gte | string one | one": { + "result": true + }, + "gte | string one | five": { + "result": false + }, + "gte | string one | negative": { + "result": true + }, + "gte | string one | string one": { + "result": true + }, + "gte | string one | NaN": { + "result": false + }, + "gte | string one | undefined": { + "result": false + }, + "gte | string one | null": { + "result": true + }, + "gte | NaN | zero": { + "result": false + }, + "gte | NaN | one": { + "result": false + }, + "gte | NaN | five": { + "result": false + }, + "gte | NaN | negative": { + "result": false + }, + "gte | NaN | string one": { + "result": false + }, + "gte | NaN | NaN": { + "result": false + }, + "gte | NaN | undefined": { + "result": false + }, + "gte | NaN | null": { + "result": false + }, + "gte | undefined | zero": { + "result": false + }, + "gte | undefined | one": { + "result": false + }, + "gte | undefined | five": { + "result": false + }, + "gte | undefined | negative": { + "result": false + }, + "gte | undefined | string one": { + "result": false + }, + "gte | undefined | NaN": { + "result": false + }, + "gte | undefined | undefined": { + "result": false + }, + "gte | undefined | null": { + "result": false + }, + "gte | null | zero": { + "result": true + }, + "gte | null | one": { + "result": false + }, + "gte | null | five": { + "result": false + }, + "gte | null | negative": { + "result": true + }, + "gte | null | string one": { + "result": false + }, + "gte | null | NaN": { + "result": false + }, + "gte | null | undefined": { + "result": false + }, + "gte | null | null": { + "result": true + }, + "lt | zero | zero": { + "result": false + }, + "lt | zero | one": { + "result": true + }, + "lt | zero | five": { + "result": true + }, + "lt | zero | negative": { + "result": false + }, + "lt | zero | string one": { + "result": true + }, + "lt | zero | NaN": { + "result": false + }, + "lt | zero | undefined": { + "result": false + }, + "lt | zero | null": { + "result": false + }, + "lt | one | zero": { + "result": false + }, + "lt | one | one": { + "result": false + }, + "lt | one | five": { + "result": true + }, + "lt | one | negative": { + "result": false + }, + "lt | one | string one": { + "result": false + }, + "lt | one | NaN": { + "result": false + }, + "lt | one | undefined": { + "result": false + }, + "lt | one | null": { + "result": false + }, + "lt | five | zero": { + "result": false + }, + "lt | five | one": { + "result": false + }, + "lt | five | five": { + "result": false + }, + "lt | five | negative": { + "result": false + }, + "lt | five | string one": { + "result": false + }, + "lt | five | NaN": { + "result": false + }, + "lt | five | undefined": { + "result": false + }, + "lt | five | null": { + "result": false + }, + "lt | negative | zero": { + "result": true + }, + "lt | negative | one": { + "result": true + }, + "lt | negative | five": { + "result": true + }, + "lt | negative | negative": { + "result": false + }, + "lt | negative | string one": { + "result": true + }, + "lt | negative | NaN": { + "result": false + }, + "lt | negative | undefined": { + "result": false + }, + "lt | negative | null": { + "result": true + }, + "lt | string one | zero": { + "result": false + }, + "lt | string one | one": { + "result": false + }, + "lt | string one | five": { + "result": true + }, + "lt | string one | negative": { + "result": false + }, + "lt | string one | string one": { + "result": false + }, + "lt | string one | NaN": { + "result": false + }, + "lt | string one | undefined": { + "result": false + }, + "lt | string one | null": { + "result": false + }, + "lt | NaN | zero": { + "result": false + }, + "lt | NaN | one": { + "result": false + }, + "lt | NaN | five": { + "result": false + }, + "lt | NaN | negative": { + "result": false + }, + "lt | NaN | string one": { + "result": false + }, + "lt | NaN | NaN": { + "result": false + }, + "lt | NaN | undefined": { + "result": false + }, + "lt | NaN | null": { + "result": false + }, + "lt | undefined | zero": { + "result": false + }, + "lt | undefined | one": { + "result": false + }, + "lt | undefined | five": { + "result": false + }, + "lt | undefined | negative": { + "result": false + }, + "lt | undefined | string one": { + "result": false + }, + "lt | undefined | NaN": { + "result": false + }, + "lt | undefined | undefined": { + "result": false + }, + "lt | undefined | null": { + "result": false + }, + "lt | null | zero": { + "result": false + }, + "lt | null | one": { + "result": true + }, + "lt | null | five": { + "result": true + }, + "lt | null | negative": { + "result": false + }, + "lt | null | string one": { + "result": true + }, + "lt | null | NaN": { + "result": false + }, + "lt | null | undefined": { + "result": false + }, + "lt | null | null": { + "result": false + }, + "lte | zero | zero": { + "result": true + }, + "lte | zero | one": { + "result": true + }, + "lte | zero | five": { + "result": true + }, + "lte | zero | negative": { + "result": false + }, + "lte | zero | string one": { + "result": true + }, + "lte | zero | NaN": { + "result": false + }, + "lte | zero | undefined": { + "result": false + }, + "lte | zero | null": { + "result": true + }, + "lte | one | zero": { + "result": false + }, + "lte | one | one": { + "result": true + }, + "lte | one | five": { + "result": true + }, + "lte | one | negative": { + "result": false + }, + "lte | one | string one": { + "result": true + }, + "lte | one | NaN": { + "result": false + }, + "lte | one | undefined": { + "result": false + }, + "lte | one | null": { + "result": false + }, + "lte | five | zero": { + "result": false + }, + "lte | five | one": { + "result": false + }, + "lte | five | five": { + "result": true + }, + "lte | five | negative": { + "result": false + }, + "lte | five | string one": { + "result": false + }, + "lte | five | NaN": { + "result": false + }, + "lte | five | undefined": { + "result": false + }, + "lte | five | null": { + "result": false + }, + "lte | negative | zero": { + "result": true + }, + "lte | negative | one": { + "result": true + }, + "lte | negative | five": { + "result": true + }, + "lte | negative | negative": { + "result": true + }, + "lte | negative | string one": { + "result": true + }, + "lte | negative | NaN": { + "result": false + }, + "lte | negative | undefined": { + "result": false + }, + "lte | negative | null": { + "result": true + }, + "lte | string one | zero": { + "result": false + }, + "lte | string one | one": { + "result": true + }, + "lte | string one | five": { + "result": true + }, + "lte | string one | negative": { + "result": false + }, + "lte | string one | string one": { + "result": true + }, + "lte | string one | NaN": { + "result": false + }, + "lte | string one | undefined": { + "result": false + }, + "lte | string one | null": { + "result": false + }, + "lte | NaN | zero": { + "result": false + }, + "lte | NaN | one": { + "result": false + }, + "lte | NaN | five": { + "result": false + }, + "lte | NaN | negative": { + "result": false + }, + "lte | NaN | string one": { + "result": false + }, + "lte | NaN | NaN": { + "result": false + }, + "lte | NaN | undefined": { + "result": false + }, + "lte | NaN | null": { + "result": false + }, + "lte | undefined | zero": { + "result": false + }, + "lte | undefined | one": { + "result": false + }, + "lte | undefined | five": { + "result": false + }, + "lte | undefined | negative": { + "result": false + }, + "lte | undefined | string one": { + "result": false + }, + "lte | undefined | NaN": { + "result": false + }, + "lte | undefined | undefined": { + "result": false + }, + "lte | undefined | null": { + "result": false + }, + "lte | null | zero": { + "result": true + }, + "lte | null | one": { + "result": true + }, + "lte | null | five": { + "result": true + }, + "lte | null | negative": { + "result": false + }, + "lte | null | string one": { + "result": true + }, + "lte | null | NaN": { + "result": false + }, + "lte | null | undefined": { + "result": false + }, + "lte | null | null": { + "result": true + }, + "eq | zero | zero": { + "result": true + }, + "eq | zero | one": { + "result": false + }, + "eq | zero | five": { + "result": false + }, + "eq | zero | negative": { + "result": false + }, + "eq | zero | string one": { + "result": false + }, + "eq | zero | NaN": { + "result": false + }, + "eq | zero | undefined": { + "result": false + }, + "eq | zero | null": { + "result": false + }, + "eq | one | zero": { + "result": false + }, + "eq | one | one": { + "result": true + }, + "eq | one | five": { + "result": false + }, + "eq | one | negative": { + "result": false + }, + "eq | one | string one": { + "result": false + }, + "eq | one | NaN": { + "result": false + }, + "eq | one | undefined": { + "result": false + }, + "eq | one | null": { + "result": false + }, + "eq | five | zero": { + "result": false + }, + "eq | five | one": { + "result": false + }, + "eq | five | five": { + "result": true + }, + "eq | five | negative": { + "result": false + }, + "eq | five | string one": { + "result": false + }, + "eq | five | NaN": { + "result": false + }, + "eq | five | undefined": { + "result": false + }, + "eq | five | null": { + "result": false + }, + "eq | negative | zero": { + "result": false + }, + "eq | negative | one": { + "result": false + }, + "eq | negative | five": { + "result": false + }, + "eq | negative | negative": { + "result": true + }, + "eq | negative | string one": { + "result": false + }, + "eq | negative | NaN": { + "result": false + }, + "eq | negative | undefined": { + "result": false + }, + "eq | negative | null": { + "result": false + }, + "eq | string one | zero": { + "result": false + }, + "eq | string one | one": { + "result": false + }, + "eq | string one | five": { + "result": false + }, + "eq | string one | negative": { + "result": false + }, + "eq | string one | string one": { + "result": true + }, + "eq | string one | NaN": { + "result": false + }, + "eq | string one | undefined": { + "result": false + }, + "eq | string one | null": { + "result": false + }, + "eq | NaN | zero": { + "result": false + }, + "eq | NaN | one": { + "result": false + }, + "eq | NaN | five": { + "result": false + }, + "eq | NaN | negative": { + "result": false + }, + "eq | NaN | string one": { + "result": false + }, + "eq | NaN | NaN": { + "result": false + }, + "eq | NaN | undefined": { + "result": false + }, + "eq | NaN | null": { + "result": false + }, + "eq | undefined | zero": { + "result": false + }, + "eq | undefined | one": { + "result": false + }, + "eq | undefined | five": { + "result": false + }, + "eq | undefined | negative": { + "result": false + }, + "eq | undefined | string one": { + "result": false + }, + "eq | undefined | NaN": { + "result": false + }, + "eq | undefined | undefined": { + "result": true + }, + "eq | undefined | null": { + "result": false + }, + "eq | null | zero": { + "result": false + }, + "eq | null | one": { + "result": false + }, + "eq | null | five": { + "result": false + }, + "eq | null | negative": { + "result": false + }, + "eq | null | string one": { + "result": false + }, + "eq | null | NaN": { + "result": false + }, + "eq | null | undefined": { + "result": false + }, + "eq | null | null": { + "result": true + }, + "neq | zero | zero": { + "result": false + }, + "neq | zero | one": { + "result": true + }, + "neq | zero | five": { + "result": true + }, + "neq | zero | negative": { + "result": true + }, + "neq | zero | string one": { + "result": true + }, + "neq | zero | NaN": { + "result": true + }, + "neq | zero | undefined": { + "result": true + }, + "neq | zero | null": { + "result": true + }, + "neq | one | zero": { + "result": true + }, + "neq | one | one": { + "result": false + }, + "neq | one | five": { + "result": true + }, + "neq | one | negative": { + "result": true + }, + "neq | one | string one": { + "result": true + }, + "neq | one | NaN": { + "result": true + }, + "neq | one | undefined": { + "result": true + }, + "neq | one | null": { + "result": true + }, + "neq | five | zero": { + "result": true + }, + "neq | five | one": { + "result": true + }, + "neq | five | five": { + "result": false + }, + "neq | five | negative": { + "result": true + }, + "neq | five | string one": { + "result": true + }, + "neq | five | NaN": { + "result": true + }, + "neq | five | undefined": { + "result": true + }, + "neq | five | null": { + "result": true + }, + "neq | negative | zero": { + "result": true + }, + "neq | negative | one": { + "result": true + }, + "neq | negative | five": { + "result": true + }, + "neq | negative | negative": { + "result": false + }, + "neq | negative | string one": { + "result": true + }, + "neq | negative | NaN": { + "result": true + }, + "neq | negative | undefined": { + "result": true + }, + "neq | negative | null": { + "result": true + }, + "neq | string one | zero": { + "result": true + }, + "neq | string one | one": { + "result": true + }, + "neq | string one | five": { + "result": true + }, + "neq | string one | negative": { + "result": true + }, + "neq | string one | string one": { + "result": false + }, + "neq | string one | NaN": { + "result": true + }, + "neq | string one | undefined": { + "result": true + }, + "neq | string one | null": { + "result": true + }, + "neq | NaN | zero": { + "result": true + }, + "neq | NaN | one": { + "result": true + }, + "neq | NaN | five": { + "result": true + }, + "neq | NaN | negative": { + "result": true + }, + "neq | NaN | string one": { + "result": true + }, + "neq | NaN | NaN": { + "result": true + }, + "neq | NaN | undefined": { + "result": true + }, + "neq | NaN | null": { + "result": true + }, + "neq | undefined | zero": { + "result": true + }, + "neq | undefined | one": { + "result": true + }, + "neq | undefined | five": { + "result": true + }, + "neq | undefined | negative": { + "result": true + }, + "neq | undefined | string one": { + "result": true + }, + "neq | undefined | NaN": { + "result": true + }, + "neq | undefined | undefined": { + "result": false + }, + "neq | undefined | null": { + "result": true + }, + "neq | null | zero": { + "result": true + }, + "neq | null | one": { + "result": true + }, + "neq | null | five": { + "result": true + }, + "neq | null | negative": { + "result": true + }, + "neq | null | string one": { + "result": true + }, + "neq | null | NaN": { + "result": true + }, + "neq | null | undefined": { + "result": true + }, + "neq | null | null": { + "result": false + }, + "upper case | zero | zero": { + "error": "unknown operator GT" + }, + "upper case | zero | one": { + "error": "unknown operator GT" + }, + "upper case | zero | five": { + "error": "unknown operator GT" + }, + "upper case | zero | negative": { + "error": "unknown operator GT" + }, + "upper case | zero | string one": { + "error": "unknown operator GT" + }, + "upper case | zero | NaN": { + "error": "unknown operator GT" + }, + "upper case | zero | undefined": { + "error": "unknown operator GT" + }, + "upper case | zero | null": { + "error": "unknown operator GT" + }, + "upper case | one | zero": { + "error": "unknown operator GT" + }, + "upper case | one | one": { + "error": "unknown operator GT" + }, + "upper case | one | five": { + "error": "unknown operator GT" + }, + "upper case | one | negative": { + "error": "unknown operator GT" + }, + "upper case | one | string one": { + "error": "unknown operator GT" + }, + "upper case | one | NaN": { + "error": "unknown operator GT" + }, + "upper case | one | undefined": { + "error": "unknown operator GT" + }, + "upper case | one | null": { + "error": "unknown operator GT" + }, + "upper case | five | zero": { + "error": "unknown operator GT" + }, + "upper case | five | one": { + "error": "unknown operator GT" + }, + "upper case | five | five": { + "error": "unknown operator GT" + }, + "upper case | five | negative": { + "error": "unknown operator GT" + }, + "upper case | five | string one": { + "error": "unknown operator GT" + }, + "upper case | five | NaN": { + "error": "unknown operator GT" + }, + "upper case | five | undefined": { + "error": "unknown operator GT" + }, + "upper case | five | null": { + "error": "unknown operator GT" + }, + "upper case | negative | zero": { + "error": "unknown operator GT" + }, + "upper case | negative | one": { + "error": "unknown operator GT" + }, + "upper case | negative | five": { + "error": "unknown operator GT" + }, + "upper case | negative | negative": { + "error": "unknown operator GT" + }, + "upper case | negative | string one": { + "error": "unknown operator GT" + }, + "upper case | negative | NaN": { + "error": "unknown operator GT" + }, + "upper case | negative | undefined": { + "error": "unknown operator GT" + }, + "upper case | negative | null": { + "error": "unknown operator GT" + }, + "upper case | string one | zero": { + "error": "unknown operator GT" + }, + "upper case | string one | one": { + "error": "unknown operator GT" + }, + "upper case | string one | five": { + "error": "unknown operator GT" + }, + "upper case | string one | negative": { + "error": "unknown operator GT" + }, + "upper case | string one | string one": { + "error": "unknown operator GT" + }, + "upper case | string one | NaN": { + "error": "unknown operator GT" + }, + "upper case | string one | undefined": { + "error": "unknown operator GT" + }, + "upper case | string one | null": { + "error": "unknown operator GT" + }, + "upper case | NaN | zero": { + "error": "unknown operator GT" + }, + "upper case | NaN | one": { + "error": "unknown operator GT" + }, + "upper case | NaN | five": { + "error": "unknown operator GT" + }, + "upper case | NaN | negative": { + "error": "unknown operator GT" + }, + "upper case | NaN | string one": { + "error": "unknown operator GT" + }, + "upper case | NaN | NaN": { + "error": "unknown operator GT" + }, + "upper case | NaN | undefined": { + "error": "unknown operator GT" + }, + "upper case | NaN | null": { + "error": "unknown operator GT" + }, + "upper case | undefined | zero": { + "error": "unknown operator GT" + }, + "upper case | undefined | one": { + "error": "unknown operator GT" + }, + "upper case | undefined | five": { + "error": "unknown operator GT" + }, + "upper case | undefined | negative": { + "error": "unknown operator GT" + }, + "upper case | undefined | string one": { + "error": "unknown operator GT" + }, + "upper case | undefined | NaN": { + "error": "unknown operator GT" + }, + "upper case | undefined | undefined": { + "error": "unknown operator GT" + }, + "upper case | undefined | null": { + "error": "unknown operator GT" + }, + "upper case | null | zero": { + "error": "unknown operator GT" + }, + "upper case | null | one": { + "error": "unknown operator GT" + }, + "upper case | null | five": { + "error": "unknown operator GT" + }, + "upper case | null | negative": { + "error": "unknown operator GT" + }, + "upper case | null | string one": { + "error": "unknown operator GT" + }, + "upper case | null | NaN": { + "error": "unknown operator GT" + }, + "upper case | null | undefined": { + "error": "unknown operator GT" + }, + "upper case | null | null": { + "error": "unknown operator GT" + }, + "unknown | zero | zero": { + "error": "unknown operator between" + }, + "unknown | zero | one": { + "error": "unknown operator between" + }, + "unknown | zero | five": { + "error": "unknown operator between" + }, + "unknown | zero | negative": { + "error": "unknown operator between" + }, + "unknown | zero | string one": { + "error": "unknown operator between" + }, + "unknown | zero | NaN": { + "error": "unknown operator between" + }, + "unknown | zero | undefined": { + "error": "unknown operator between" + }, + "unknown | zero | null": { + "error": "unknown operator between" + }, + "unknown | one | zero": { + "error": "unknown operator between" + }, + "unknown | one | one": { + "error": "unknown operator between" + }, + "unknown | one | five": { + "error": "unknown operator between" + }, + "unknown | one | negative": { + "error": "unknown operator between" + }, + "unknown | one | string one": { + "error": "unknown operator between" + }, + "unknown | one | NaN": { + "error": "unknown operator between" + }, + "unknown | one | undefined": { + "error": "unknown operator between" + }, + "unknown | one | null": { + "error": "unknown operator between" + }, + "unknown | five | zero": { + "error": "unknown operator between" + }, + "unknown | five | one": { + "error": "unknown operator between" + }, + "unknown | five | five": { + "error": "unknown operator between" + }, + "unknown | five | negative": { + "error": "unknown operator between" + }, + "unknown | five | string one": { + "error": "unknown operator between" + }, + "unknown | five | NaN": { + "error": "unknown operator between" + }, + "unknown | five | undefined": { + "error": "unknown operator between" + }, + "unknown | five | null": { + "error": "unknown operator between" + }, + "unknown | negative | zero": { + "error": "unknown operator between" + }, + "unknown | negative | one": { + "error": "unknown operator between" + }, + "unknown | negative | five": { + "error": "unknown operator between" + }, + "unknown | negative | negative": { + "error": "unknown operator between" + }, + "unknown | negative | string one": { + "error": "unknown operator between" + }, + "unknown | negative | NaN": { + "error": "unknown operator between" + }, + "unknown | negative | undefined": { + "error": "unknown operator between" + }, + "unknown | negative | null": { + "error": "unknown operator between" + }, + "unknown | string one | zero": { + "error": "unknown operator between" + }, + "unknown | string one | one": { + "error": "unknown operator between" + }, + "unknown | string one | five": { + "error": "unknown operator between" + }, + "unknown | string one | negative": { + "error": "unknown operator between" + }, + "unknown | string one | string one": { + "error": "unknown operator between" + }, + "unknown | string one | NaN": { + "error": "unknown operator between" + }, + "unknown | string one | undefined": { + "error": "unknown operator between" + }, + "unknown | string one | null": { + "error": "unknown operator between" + }, + "unknown | NaN | zero": { + "error": "unknown operator between" + }, + "unknown | NaN | one": { + "error": "unknown operator between" + }, + "unknown | NaN | five": { + "error": "unknown operator between" + }, + "unknown | NaN | negative": { + "error": "unknown operator between" + }, + "unknown | NaN | string one": { + "error": "unknown operator between" + }, + "unknown | NaN | NaN": { + "error": "unknown operator between" + }, + "unknown | NaN | undefined": { + "error": "unknown operator between" + }, + "unknown | NaN | null": { + "error": "unknown operator between" + }, + "unknown | undefined | zero": { + "error": "unknown operator between" + }, + "unknown | undefined | one": { + "error": "unknown operator between" + }, + "unknown | undefined | five": { + "error": "unknown operator between" + }, + "unknown | undefined | negative": { + "error": "unknown operator between" + }, + "unknown | undefined | string one": { + "error": "unknown operator between" + }, + "unknown | undefined | NaN": { + "error": "unknown operator between" + }, + "unknown | undefined | undefined": { + "error": "unknown operator between" + }, + "unknown | undefined | null": { + "error": "unknown operator between" + }, + "unknown | null | zero": { + "error": "unknown operator between" + }, + "unknown | null | one": { + "error": "unknown operator between" + }, + "unknown | null | five": { + "error": "unknown operator between" + }, + "unknown | null | negative": { + "error": "unknown operator between" + }, + "unknown | null | string one": { + "error": "unknown operator between" + }, + "unknown | null | NaN": { + "error": "unknown operator between" + }, + "unknown | null | undefined": { + "error": "unknown operator between" + }, + "unknown | null | null": { + "error": "unknown operator between" + }, + "empty string | zero | zero": { + "error": "unknown operator " + }, + "empty string | zero | one": { + "error": "unknown operator " + }, + "empty string | zero | five": { + "error": "unknown operator " + }, + "empty string | zero | negative": { + "error": "unknown operator " + }, + "empty string | zero | string one": { + "error": "unknown operator " + }, + "empty string | zero | NaN": { + "error": "unknown operator " + }, + "empty string | zero | undefined": { + "error": "unknown operator " + }, + "empty string | zero | null": { + "error": "unknown operator " + }, + "empty string | one | zero": { + "error": "unknown operator " + }, + "empty string | one | one": { + "error": "unknown operator " + }, + "empty string | one | five": { + "error": "unknown operator " + }, + "empty string | one | negative": { + "error": "unknown operator " + }, + "empty string | one | string one": { + "error": "unknown operator " + }, + "empty string | one | NaN": { + "error": "unknown operator " + }, + "empty string | one | undefined": { + "error": "unknown operator " + }, + "empty string | one | null": { + "error": "unknown operator " + }, + "empty string | five | zero": { + "error": "unknown operator " + }, + "empty string | five | one": { + "error": "unknown operator " + }, + "empty string | five | five": { + "error": "unknown operator " + }, + "empty string | five | negative": { + "error": "unknown operator " + }, + "empty string | five | string one": { + "error": "unknown operator " + }, + "empty string | five | NaN": { + "error": "unknown operator " + }, + "empty string | five | undefined": { + "error": "unknown operator " + }, + "empty string | five | null": { + "error": "unknown operator " + }, + "empty string | negative | zero": { + "error": "unknown operator " + }, + "empty string | negative | one": { + "error": "unknown operator " + }, + "empty string | negative | five": { + "error": "unknown operator " + }, + "empty string | negative | negative": { + "error": "unknown operator " + }, + "empty string | negative | string one": { + "error": "unknown operator " + }, + "empty string | negative | NaN": { + "error": "unknown operator " + }, + "empty string | negative | undefined": { + "error": "unknown operator " + }, + "empty string | negative | null": { + "error": "unknown operator " + }, + "empty string | string one | zero": { + "error": "unknown operator " + }, + "empty string | string one | one": { + "error": "unknown operator " + }, + "empty string | string one | five": { + "error": "unknown operator " + }, + "empty string | string one | negative": { + "error": "unknown operator " + }, + "empty string | string one | string one": { + "error": "unknown operator " + }, + "empty string | string one | NaN": { + "error": "unknown operator " + }, + "empty string | string one | undefined": { + "error": "unknown operator " + }, + "empty string | string one | null": { + "error": "unknown operator " + }, + "empty string | NaN | zero": { + "error": "unknown operator " + }, + "empty string | NaN | one": { + "error": "unknown operator " + }, + "empty string | NaN | five": { + "error": "unknown operator " + }, + "empty string | NaN | negative": { + "error": "unknown operator " + }, + "empty string | NaN | string one": { + "error": "unknown operator " + }, + "empty string | NaN | NaN": { + "error": "unknown operator " + }, + "empty string | NaN | undefined": { + "error": "unknown operator " + }, + "empty string | NaN | null": { + "error": "unknown operator " + }, + "empty string | undefined | zero": { + "error": "unknown operator " + }, + "empty string | undefined | one": { + "error": "unknown operator " + }, + "empty string | undefined | five": { + "error": "unknown operator " + }, + "empty string | undefined | negative": { + "error": "unknown operator " + }, + "empty string | undefined | string one": { + "error": "unknown operator " + }, + "empty string | undefined | NaN": { + "error": "unknown operator " + }, + "empty string | undefined | undefined": { + "error": "unknown operator " + }, + "empty string | undefined | null": { + "error": "unknown operator " + }, + "empty string | null | zero": { + "error": "unknown operator " + }, + "empty string | null | one": { + "error": "unknown operator " + }, + "empty string | null | five": { + "error": "unknown operator " + }, + "empty string | null | negative": { + "error": "unknown operator " + }, + "empty string | null | string one": { + "error": "unknown operator " + }, + "empty string | null | NaN": { + "error": "unknown operator " + }, + "empty string | null | undefined": { + "error": "unknown operator " + }, + "empty string | null | null": { + "error": "unknown operator " + }, + "prototype key | zero | zero": { + "error": "unknown operator toString" + }, + "prototype key | zero | one": { + "error": "unknown operator toString" + }, + "prototype key | zero | five": { + "error": "unknown operator toString" + }, + "prototype key | zero | negative": { + "error": "unknown operator toString" + }, + "prototype key | zero | string one": { + "error": "unknown operator toString" + }, + "prototype key | zero | NaN": { + "error": "unknown operator toString" + }, + "prototype key | zero | undefined": { + "error": "unknown operator toString" + }, + "prototype key | zero | null": { + "error": "unknown operator toString" + }, + "prototype key | one | zero": { + "error": "unknown operator toString" + }, + "prototype key | one | one": { + "error": "unknown operator toString" + }, + "prototype key | one | five": { + "error": "unknown operator toString" + }, + "prototype key | one | negative": { + "error": "unknown operator toString" + }, + "prototype key | one | string one": { + "error": "unknown operator toString" + }, + "prototype key | one | NaN": { + "error": "unknown operator toString" + }, + "prototype key | one | undefined": { + "error": "unknown operator toString" + }, + "prototype key | one | null": { + "error": "unknown operator toString" + }, + "prototype key | five | zero": { + "error": "unknown operator toString" + }, + "prototype key | five | one": { + "error": "unknown operator toString" + }, + "prototype key | five | five": { + "error": "unknown operator toString" + }, + "prototype key | five | negative": { + "error": "unknown operator toString" + }, + "prototype key | five | string one": { + "error": "unknown operator toString" + }, + "prototype key | five | NaN": { + "error": "unknown operator toString" + }, + "prototype key | five | undefined": { + "error": "unknown operator toString" + }, + "prototype key | five | null": { + "error": "unknown operator toString" + }, + "prototype key | negative | zero": { + "error": "unknown operator toString" + }, + "prototype key | negative | one": { + "error": "unknown operator toString" + }, + "prototype key | negative | five": { + "error": "unknown operator toString" + }, + "prototype key | negative | negative": { + "error": "unknown operator toString" + }, + "prototype key | negative | string one": { + "error": "unknown operator toString" + }, + "prototype key | negative | NaN": { + "error": "unknown operator toString" + }, + "prototype key | negative | undefined": { + "error": "unknown operator toString" + }, + "prototype key | negative | null": { + "error": "unknown operator toString" + }, + "prototype key | string one | zero": { + "error": "unknown operator toString" + }, + "prototype key | string one | one": { + "error": "unknown operator toString" + }, + "prototype key | string one | five": { + "error": "unknown operator toString" + }, + "prototype key | string one | negative": { + "error": "unknown operator toString" + }, + "prototype key | string one | string one": { + "error": "unknown operator toString" + }, + "prototype key | string one | NaN": { + "error": "unknown operator toString" + }, + "prototype key | string one | undefined": { + "error": "unknown operator toString" + }, + "prototype key | string one | null": { + "error": "unknown operator toString" + }, + "prototype key | NaN | zero": { + "error": "unknown operator toString" + }, + "prototype key | NaN | one": { + "error": "unknown operator toString" + }, + "prototype key | NaN | five": { + "error": "unknown operator toString" + }, + "prototype key | NaN | negative": { + "error": "unknown operator toString" + }, + "prototype key | NaN | string one": { + "error": "unknown operator toString" + }, + "prototype key | NaN | NaN": { + "error": "unknown operator toString" + }, + "prototype key | NaN | undefined": { + "error": "unknown operator toString" + }, + "prototype key | NaN | null": { + "error": "unknown operator toString" + }, + "prototype key | undefined | zero": { + "error": "unknown operator toString" + }, + "prototype key | undefined | one": { + "error": "unknown operator toString" + }, + "prototype key | undefined | five": { + "error": "unknown operator toString" + }, + "prototype key | undefined | negative": { + "error": "unknown operator toString" + }, + "prototype key | undefined | string one": { + "error": "unknown operator toString" + }, + "prototype key | undefined | NaN": { + "error": "unknown operator toString" + }, + "prototype key | undefined | undefined": { + "error": "unknown operator toString" + }, + "prototype key | undefined | null": { + "error": "unknown operator toString" + }, + "prototype key | null | zero": { + "error": "unknown operator toString" + }, + "prototype key | null | one": { + "error": "unknown operator toString" + }, + "prototype key | null | five": { + "error": "unknown operator toString" + }, + "prototype key | null | negative": { + "error": "unknown operator toString" + }, + "prototype key | null | string one": { + "error": "unknown operator toString" + }, + "prototype key | null | NaN": { + "error": "unknown operator toString" + }, + "prototype key | null | undefined": { + "error": "unknown operator toString" + }, + "prototype key | null | null": { + "error": "unknown operator toString" + }, + "constructor | zero | zero": { + "error": "unknown operator constructor" + }, + "constructor | zero | one": { + "error": "unknown operator constructor" + }, + "constructor | zero | five": { + "error": "unknown operator constructor" + }, + "constructor | zero | negative": { + "error": "unknown operator constructor" + }, + "constructor | zero | string one": { + "error": "unknown operator constructor" + }, + "constructor | zero | NaN": { + "error": "unknown operator constructor" + }, + "constructor | zero | undefined": { + "error": "unknown operator constructor" + }, + "constructor | zero | null": { + "error": "unknown operator constructor" + }, + "constructor | one | zero": { + "error": "unknown operator constructor" + }, + "constructor | one | one": { + "error": "unknown operator constructor" + }, + "constructor | one | five": { + "error": "unknown operator constructor" + }, + "constructor | one | negative": { + "error": "unknown operator constructor" + }, + "constructor | one | string one": { + "error": "unknown operator constructor" + }, + "constructor | one | NaN": { + "error": "unknown operator constructor" + }, + "constructor | one | undefined": { + "error": "unknown operator constructor" + }, + "constructor | one | null": { + "error": "unknown operator constructor" + }, + "constructor | five | zero": { + "error": "unknown operator constructor" + }, + "constructor | five | one": { + "error": "unknown operator constructor" + }, + "constructor | five | five": { + "error": "unknown operator constructor" + }, + "constructor | five | negative": { + "error": "unknown operator constructor" + }, + "constructor | five | string one": { + "error": "unknown operator constructor" + }, + "constructor | five | NaN": { + "error": "unknown operator constructor" + }, + "constructor | five | undefined": { + "error": "unknown operator constructor" + }, + "constructor | five | null": { + "error": "unknown operator constructor" + }, + "constructor | negative | zero": { + "error": "unknown operator constructor" + }, + "constructor | negative | one": { + "error": "unknown operator constructor" + }, + "constructor | negative | five": { + "error": "unknown operator constructor" + }, + "constructor | negative | negative": { + "error": "unknown operator constructor" + }, + "constructor | negative | string one": { + "error": "unknown operator constructor" + }, + "constructor | negative | NaN": { + "error": "unknown operator constructor" + }, + "constructor | negative | undefined": { + "error": "unknown operator constructor" + }, + "constructor | negative | null": { + "error": "unknown operator constructor" + }, + "constructor | string one | zero": { + "error": "unknown operator constructor" + }, + "constructor | string one | one": { + "error": "unknown operator constructor" + }, + "constructor | string one | five": { + "error": "unknown operator constructor" + }, + "constructor | string one | negative": { + "error": "unknown operator constructor" + }, + "constructor | string one | string one": { + "error": "unknown operator constructor" + }, + "constructor | string one | NaN": { + "error": "unknown operator constructor" + }, + "constructor | string one | undefined": { + "error": "unknown operator constructor" + }, + "constructor | string one | null": { + "error": "unknown operator constructor" + }, + "constructor | NaN | zero": { + "error": "unknown operator constructor" + }, + "constructor | NaN | one": { + "error": "unknown operator constructor" + }, + "constructor | NaN | five": { + "error": "unknown operator constructor" + }, + "constructor | NaN | negative": { + "error": "unknown operator constructor" + }, + "constructor | NaN | string one": { + "error": "unknown operator constructor" + }, + "constructor | NaN | NaN": { + "error": "unknown operator constructor" + }, + "constructor | NaN | undefined": { + "error": "unknown operator constructor" + }, + "constructor | NaN | null": { + "error": "unknown operator constructor" + }, + "constructor | undefined | zero": { + "error": "unknown operator constructor" + }, + "constructor | undefined | one": { + "error": "unknown operator constructor" + }, + "constructor | undefined | five": { + "error": "unknown operator constructor" + }, + "constructor | undefined | negative": { + "error": "unknown operator constructor" + }, + "constructor | undefined | string one": { + "error": "unknown operator constructor" + }, + "constructor | undefined | NaN": { + "error": "unknown operator constructor" + }, + "constructor | undefined | undefined": { + "error": "unknown operator constructor" + }, + "constructor | undefined | null": { + "error": "unknown operator constructor" + }, + "constructor | null | zero": { + "error": "unknown operator constructor" + }, + "constructor | null | one": { + "error": "unknown operator constructor" + }, + "constructor | null | five": { + "error": "unknown operator constructor" + }, + "constructor | null | negative": { + "error": "unknown operator constructor" + }, + "constructor | null | string one": { + "error": "unknown operator constructor" + }, + "constructor | null | NaN": { + "error": "unknown operator constructor" + }, + "constructor | null | undefined": { + "error": "unknown operator constructor" + }, + "constructor | null | null": { + "error": "unknown operator constructor" + }, + "proto | zero | zero": { + "error": "unknown operator __proto__" + }, + "proto | zero | one": { + "error": "unknown operator __proto__" + }, + "proto | zero | five": { + "error": "unknown operator __proto__" + }, + "proto | zero | negative": { + "error": "unknown operator __proto__" + }, + "proto | zero | string one": { + "error": "unknown operator __proto__" + }, + "proto | zero | NaN": { + "error": "unknown operator __proto__" + }, + "proto | zero | undefined": { + "error": "unknown operator __proto__" + }, + "proto | zero | null": { + "error": "unknown operator __proto__" + }, + "proto | one | zero": { + "error": "unknown operator __proto__" + }, + "proto | one | one": { + "error": "unknown operator __proto__" + }, + "proto | one | five": { + "error": "unknown operator __proto__" + }, + "proto | one | negative": { + "error": "unknown operator __proto__" + }, + "proto | one | string one": { + "error": "unknown operator __proto__" + }, + "proto | one | NaN": { + "error": "unknown operator __proto__" + }, + "proto | one | undefined": { + "error": "unknown operator __proto__" + }, + "proto | one | null": { + "error": "unknown operator __proto__" + }, + "proto | five | zero": { + "error": "unknown operator __proto__" + }, + "proto | five | one": { + "error": "unknown operator __proto__" + }, + "proto | five | five": { + "error": "unknown operator __proto__" + }, + "proto | five | negative": { + "error": "unknown operator __proto__" + }, + "proto | five | string one": { + "error": "unknown operator __proto__" + }, + "proto | five | NaN": { + "error": "unknown operator __proto__" + }, + "proto | five | undefined": { + "error": "unknown operator __proto__" + }, + "proto | five | null": { + "error": "unknown operator __proto__" + }, + "proto | negative | zero": { + "error": "unknown operator __proto__" + }, + "proto | negative | one": { + "error": "unknown operator __proto__" + }, + "proto | negative | five": { + "error": "unknown operator __proto__" + }, + "proto | negative | negative": { + "error": "unknown operator __proto__" + }, + "proto | negative | string one": { + "error": "unknown operator __proto__" + }, + "proto | negative | NaN": { + "error": "unknown operator __proto__" + }, + "proto | negative | undefined": { + "error": "unknown operator __proto__" + }, + "proto | negative | null": { + "error": "unknown operator __proto__" + }, + "proto | string one | zero": { + "error": "unknown operator __proto__" + }, + "proto | string one | one": { + "error": "unknown operator __proto__" + }, + "proto | string one | five": { + "error": "unknown operator __proto__" + }, + "proto | string one | negative": { + "error": "unknown operator __proto__" + }, + "proto | string one | string one": { + "error": "unknown operator __proto__" + }, + "proto | string one | NaN": { + "error": "unknown operator __proto__" + }, + "proto | string one | undefined": { + "error": "unknown operator __proto__" + }, + "proto | string one | null": { + "error": "unknown operator __proto__" + }, + "proto | NaN | zero": { + "error": "unknown operator __proto__" + }, + "proto | NaN | one": { + "error": "unknown operator __proto__" + }, + "proto | NaN | five": { + "error": "unknown operator __proto__" + }, + "proto | NaN | negative": { + "error": "unknown operator __proto__" + }, + "proto | NaN | string one": { + "error": "unknown operator __proto__" + }, + "proto | NaN | NaN": { + "error": "unknown operator __proto__" + }, + "proto | NaN | undefined": { + "error": "unknown operator __proto__" + }, + "proto | NaN | null": { + "error": "unknown operator __proto__" + }, + "proto | undefined | zero": { + "error": "unknown operator __proto__" + }, + "proto | undefined | one": { + "error": "unknown operator __proto__" + }, + "proto | undefined | five": { + "error": "unknown operator __proto__" + }, + "proto | undefined | negative": { + "error": "unknown operator __proto__" + }, + "proto | undefined | string one": { + "error": "unknown operator __proto__" + }, + "proto | undefined | NaN": { + "error": "unknown operator __proto__" + }, + "proto | undefined | undefined": { + "error": "unknown operator __proto__" + }, + "proto | undefined | null": { + "error": "unknown operator __proto__" + }, + "proto | null | zero": { + "error": "unknown operator __proto__" + }, + "proto | null | one": { + "error": "unknown operator __proto__" + }, + "proto | null | five": { + "error": "unknown operator __proto__" + }, + "proto | null | negative": { + "error": "unknown operator __proto__" + }, + "proto | null | string one": { + "error": "unknown operator __proto__" + }, + "proto | null | NaN": { + "error": "unknown operator __proto__" + }, + "proto | null | undefined": { + "error": "unknown operator __proto__" + }, + "proto | null | null": { + "error": "unknown operator __proto__" + }, + "own property check | zero | zero": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | zero | one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | zero | five": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | zero | negative": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | zero | string one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | zero | NaN": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | zero | undefined": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | zero | null": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | one | zero": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | one | one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | one | five": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | one | negative": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | one | string one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | one | NaN": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | one | undefined": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | one | null": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | five | zero": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | five | one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | five | five": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | five | negative": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | five | string one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | five | NaN": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | five | undefined": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | five | null": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | negative | zero": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | negative | one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | negative | five": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | negative | negative": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | negative | string one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | negative | NaN": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | negative | undefined": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | negative | null": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | string one | zero": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | string one | one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | string one | five": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | string one | negative": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | string one | string one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | string one | NaN": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | string one | undefined": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | string one | null": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | NaN | zero": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | NaN | one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | NaN | five": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | NaN | negative": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | NaN | string one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | NaN | NaN": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | NaN | undefined": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | NaN | null": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | undefined | zero": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | undefined | one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | undefined | five": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | undefined | negative": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | undefined | string one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | undefined | NaN": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | undefined | undefined": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | undefined | null": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | null | zero": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | null | one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | null | five": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | null | negative": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | null | string one": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | null | NaN": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | null | undefined": { + "error": "unknown operator hasOwnProperty" + }, + "own property check | null | null": { + "error": "unknown operator hasOwnProperty" + }, + "undefined | zero | zero": { + "error": "unknown operator undefined" + }, + "undefined | zero | one": { + "error": "unknown operator undefined" + }, + "undefined | zero | five": { + "error": "unknown operator undefined" + }, + "undefined | zero | negative": { + "error": "unknown operator undefined" + }, + "undefined | zero | string one": { + "error": "unknown operator undefined" + }, + "undefined | zero | NaN": { + "error": "unknown operator undefined" + }, + "undefined | zero | undefined": { + "error": "unknown operator undefined" + }, + "undefined | zero | null": { + "error": "unknown operator undefined" + }, + "undefined | one | zero": { + "error": "unknown operator undefined" + }, + "undefined | one | one": { + "error": "unknown operator undefined" + }, + "undefined | one | five": { + "error": "unknown operator undefined" + }, + "undefined | one | negative": { + "error": "unknown operator undefined" + }, + "undefined | one | string one": { + "error": "unknown operator undefined" + }, + "undefined | one | NaN": { + "error": "unknown operator undefined" + }, + "undefined | one | undefined": { + "error": "unknown operator undefined" + }, + "undefined | one | null": { + "error": "unknown operator undefined" + }, + "undefined | five | zero": { + "error": "unknown operator undefined" + }, + "undefined | five | one": { + "error": "unknown operator undefined" + }, + "undefined | five | five": { + "error": "unknown operator undefined" + }, + "undefined | five | negative": { + "error": "unknown operator undefined" + }, + "undefined | five | string one": { + "error": "unknown operator undefined" + }, + "undefined | five | NaN": { + "error": "unknown operator undefined" + }, + "undefined | five | undefined": { + "error": "unknown operator undefined" + }, + "undefined | five | null": { + "error": "unknown operator undefined" + }, + "undefined | negative | zero": { + "error": "unknown operator undefined" + }, + "undefined | negative | one": { + "error": "unknown operator undefined" + }, + "undefined | negative | five": { + "error": "unknown operator undefined" + }, + "undefined | negative | negative": { + "error": "unknown operator undefined" + }, + "undefined | negative | string one": { + "error": "unknown operator undefined" + }, + "undefined | negative | NaN": { + "error": "unknown operator undefined" + }, + "undefined | negative | undefined": { + "error": "unknown operator undefined" + }, + "undefined | negative | null": { + "error": "unknown operator undefined" + }, + "undefined | string one | zero": { + "error": "unknown operator undefined" + }, + "undefined | string one | one": { + "error": "unknown operator undefined" + }, + "undefined | string one | five": { + "error": "unknown operator undefined" + }, + "undefined | string one | negative": { + "error": "unknown operator undefined" + }, + "undefined | string one | string one": { + "error": "unknown operator undefined" + }, + "undefined | string one | NaN": { + "error": "unknown operator undefined" + }, + "undefined | string one | undefined": { + "error": "unknown operator undefined" + }, + "undefined | string one | null": { + "error": "unknown operator undefined" + }, + "undefined | NaN | zero": { + "error": "unknown operator undefined" + }, + "undefined | NaN | one": { + "error": "unknown operator undefined" + }, + "undefined | NaN | five": { + "error": "unknown operator undefined" + }, + "undefined | NaN | negative": { + "error": "unknown operator undefined" + }, + "undefined | NaN | string one": { + "error": "unknown operator undefined" + }, + "undefined | NaN | NaN": { + "error": "unknown operator undefined" + }, + "undefined | NaN | undefined": { + "error": "unknown operator undefined" + }, + "undefined | NaN | null": { + "error": "unknown operator undefined" + }, + "undefined | undefined | zero": { + "error": "unknown operator undefined" + }, + "undefined | undefined | one": { + "error": "unknown operator undefined" + }, + "undefined | undefined | five": { + "error": "unknown operator undefined" + }, + "undefined | undefined | negative": { + "error": "unknown operator undefined" + }, + "undefined | undefined | string one": { + "error": "unknown operator undefined" + }, + "undefined | undefined | NaN": { + "error": "unknown operator undefined" + }, + "undefined | undefined | undefined": { + "error": "unknown operator undefined" + }, + "undefined | undefined | null": { + "error": "unknown operator undefined" + }, + "undefined | null | zero": { + "error": "unknown operator undefined" + }, + "undefined | null | one": { + "error": "unknown operator undefined" + }, + "undefined | null | five": { + "error": "unknown operator undefined" + }, + "undefined | null | negative": { + "error": "unknown operator undefined" + }, + "undefined | null | string one": { + "error": "unknown operator undefined" + }, + "undefined | null | NaN": { + "error": "unknown operator undefined" + }, + "undefined | null | undefined": { + "error": "unknown operator undefined" + }, + "undefined | null | null": { + "error": "unknown operator undefined" + }, + "null | zero | zero": { + "error": "unknown operator null" + }, + "null | zero | one": { + "error": "unknown operator null" + }, + "null | zero | five": { + "error": "unknown operator null" + }, + "null | zero | negative": { + "error": "unknown operator null" + }, + "null | zero | string one": { + "error": "unknown operator null" + }, + "null | zero | NaN": { + "error": "unknown operator null" + }, + "null | zero | undefined": { + "error": "unknown operator null" + }, + "null | zero | null": { + "error": "unknown operator null" + }, + "null | one | zero": { + "error": "unknown operator null" + }, + "null | one | one": { + "error": "unknown operator null" + }, + "null | one | five": { + "error": "unknown operator null" + }, + "null | one | negative": { + "error": "unknown operator null" + }, + "null | one | string one": { + "error": "unknown operator null" + }, + "null | one | NaN": { + "error": "unknown operator null" + }, + "null | one | undefined": { + "error": "unknown operator null" + }, + "null | one | null": { + "error": "unknown operator null" + }, + "null | five | zero": { + "error": "unknown operator null" + }, + "null | five | one": { + "error": "unknown operator null" + }, + "null | five | five": { + "error": "unknown operator null" + }, + "null | five | negative": { + "error": "unknown operator null" + }, + "null | five | string one": { + "error": "unknown operator null" + }, + "null | five | NaN": { + "error": "unknown operator null" + }, + "null | five | undefined": { + "error": "unknown operator null" + }, + "null | five | null": { + "error": "unknown operator null" + }, + "null | negative | zero": { + "error": "unknown operator null" + }, + "null | negative | one": { + "error": "unknown operator null" + }, + "null | negative | five": { + "error": "unknown operator null" + }, + "null | negative | negative": { + "error": "unknown operator null" + }, + "null | negative | string one": { + "error": "unknown operator null" + }, + "null | negative | NaN": { + "error": "unknown operator null" + }, + "null | negative | undefined": { + "error": "unknown operator null" + }, + "null | negative | null": { + "error": "unknown operator null" + }, + "null | string one | zero": { + "error": "unknown operator null" + }, + "null | string one | one": { + "error": "unknown operator null" + }, + "null | string one | five": { + "error": "unknown operator null" + }, + "null | string one | negative": { + "error": "unknown operator null" + }, + "null | string one | string one": { + "error": "unknown operator null" + }, + "null | string one | NaN": { + "error": "unknown operator null" + }, + "null | string one | undefined": { + "error": "unknown operator null" + }, + "null | string one | null": { + "error": "unknown operator null" + }, + "null | NaN | zero": { + "error": "unknown operator null" + }, + "null | NaN | one": { + "error": "unknown operator null" + }, + "null | NaN | five": { + "error": "unknown operator null" + }, + "null | NaN | negative": { + "error": "unknown operator null" + }, + "null | NaN | string one": { + "error": "unknown operator null" + }, + "null | NaN | NaN": { + "error": "unknown operator null" + }, + "null | NaN | undefined": { + "error": "unknown operator null" + }, + "null | NaN | null": { + "error": "unknown operator null" + }, + "null | undefined | zero": { + "error": "unknown operator null" + }, + "null | undefined | one": { + "error": "unknown operator null" + }, + "null | undefined | five": { + "error": "unknown operator null" + }, + "null | undefined | negative": { + "error": "unknown operator null" + }, + "null | undefined | string one": { + "error": "unknown operator null" + }, + "null | undefined | NaN": { + "error": "unknown operator null" + }, + "null | undefined | undefined": { + "error": "unknown operator null" + }, + "null | undefined | null": { + "error": "unknown operator null" + }, + "null | null | zero": { + "error": "unknown operator null" + }, + "null | null | one": { + "error": "unknown operator null" + }, + "null | null | five": { + "error": "unknown operator null" + }, + "null | null | negative": { + "error": "unknown operator null" + }, + "null | null | string one": { + "error": "unknown operator null" + }, + "null | null | NaN": { + "error": "unknown operator null" + }, + "null | null | undefined": { + "error": "unknown operator null" + }, + "null | null | null": { + "error": "unknown operator null" + }, + "number | zero | zero": { + "error": "unknown operator 1" + }, + "number | zero | one": { + "error": "unknown operator 1" + }, + "number | zero | five": { + "error": "unknown operator 1" + }, + "number | zero | negative": { + "error": "unknown operator 1" + }, + "number | zero | string one": { + "error": "unknown operator 1" + }, + "number | zero | NaN": { + "error": "unknown operator 1" + }, + "number | zero | undefined": { + "error": "unknown operator 1" + }, + "number | zero | null": { + "error": "unknown operator 1" + }, + "number | one | zero": { + "error": "unknown operator 1" + }, + "number | one | one": { + "error": "unknown operator 1" + }, + "number | one | five": { + "error": "unknown operator 1" + }, + "number | one | negative": { + "error": "unknown operator 1" + }, + "number | one | string one": { + "error": "unknown operator 1" + }, + "number | one | NaN": { + "error": "unknown operator 1" + }, + "number | one | undefined": { + "error": "unknown operator 1" + }, + "number | one | null": { + "error": "unknown operator 1" + }, + "number | five | zero": { + "error": "unknown operator 1" + }, + "number | five | one": { + "error": "unknown operator 1" + }, + "number | five | five": { + "error": "unknown operator 1" + }, + "number | five | negative": { + "error": "unknown operator 1" + }, + "number | five | string one": { + "error": "unknown operator 1" + }, + "number | five | NaN": { + "error": "unknown operator 1" + }, + "number | five | undefined": { + "error": "unknown operator 1" + }, + "number | five | null": { + "error": "unknown operator 1" + }, + "number | negative | zero": { + "error": "unknown operator 1" + }, + "number | negative | one": { + "error": "unknown operator 1" + }, + "number | negative | five": { + "error": "unknown operator 1" + }, + "number | negative | negative": { + "error": "unknown operator 1" + }, + "number | negative | string one": { + "error": "unknown operator 1" + }, + "number | negative | NaN": { + "error": "unknown operator 1" + }, + "number | negative | undefined": { + "error": "unknown operator 1" + }, + "number | negative | null": { + "error": "unknown operator 1" + }, + "number | string one | zero": { + "error": "unknown operator 1" + }, + "number | string one | one": { + "error": "unknown operator 1" + }, + "number | string one | five": { + "error": "unknown operator 1" + }, + "number | string one | negative": { + "error": "unknown operator 1" + }, + "number | string one | string one": { + "error": "unknown operator 1" + }, + "number | string one | NaN": { + "error": "unknown operator 1" + }, + "number | string one | undefined": { + "error": "unknown operator 1" + }, + "number | string one | null": { + "error": "unknown operator 1" + }, + "number | NaN | zero": { + "error": "unknown operator 1" + }, + "number | NaN | one": { + "error": "unknown operator 1" + }, + "number | NaN | five": { + "error": "unknown operator 1" + }, + "number | NaN | negative": { + "error": "unknown operator 1" + }, + "number | NaN | string one": { + "error": "unknown operator 1" + }, + "number | NaN | NaN": { + "error": "unknown operator 1" + }, + "number | NaN | undefined": { + "error": "unknown operator 1" + }, + "number | NaN | null": { + "error": "unknown operator 1" + }, + "number | undefined | zero": { + "error": "unknown operator 1" + }, + "number | undefined | one": { + "error": "unknown operator 1" + }, + "number | undefined | five": { + "error": "unknown operator 1" + }, + "number | undefined | negative": { + "error": "unknown operator 1" + }, + "number | undefined | string one": { + "error": "unknown operator 1" + }, + "number | undefined | NaN": { + "error": "unknown operator 1" + }, + "number | undefined | undefined": { + "error": "unknown operator 1" + }, + "number | undefined | null": { + "error": "unknown operator 1" + }, + "number | null | zero": { + "error": "unknown operator 1" + }, + "number | null | one": { + "error": "unknown operator 1" + }, + "number | null | five": { + "error": "unknown operator 1" + }, + "number | null | negative": { + "error": "unknown operator 1" + }, + "number | null | string one": { + "error": "unknown operator 1" + }, + "number | null | NaN": { + "error": "unknown operator 1" + }, + "number | null | undefined": { + "error": "unknown operator 1" + }, + "number | null | null": { + "error": "unknown operator 1" + } +} diff --git a/src/services/__tests__/fixtures/queryGraphql.golden.json b/src/services/__tests__/fixtures/queryGraphql.golden.json new file mode 100644 index 000000000..0301e3915 --- /dev/null +++ b/src/services/__tests__/fixtures/queryGraphql.golden.json @@ -0,0 +1,1526 @@ +{ + "app and query | data": { + "result": { + "rows": [ + 1, + 2 + ] + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | null data": { + "result": {}, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | no data key": { + "result": {}, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | no body": { + "result": {}, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | no response": { + "result": {}, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "financeq", + "message": "bad field" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | error without message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "financeq", + "message": "GraphQL error" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | null first error": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "financeq", + "message": "GraphQL error" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | empty errors": { + "result": { + "x": 2 + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | errors not a list": { + "result": { + "x": 3 + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | 404": { + "rejected": { + "name": "GraphQLSourceError", + "code": "not_installed", + "app": "financeq", + "message": "financeq is not installed" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | 500": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "financeq", + "message": "Server Error" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | 404 as text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "financeq", + "message": "Not Found" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "timeout", + "app": "financeq", + "message": "financeq did not respond in time" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | 404 and timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "not_installed", + "app": "financeq", + "message": "financeq is not installed" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | no message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "financeq", + "message": "Network error" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | null": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "financeq", + "message": "Network error" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "app and query | text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "financeq", + "message": "Network error" + }, + "sent": [ + [ + "/apps/financeq/graphql", + { + "query": "query X { x }", + "variables": {} + }, + { + "timeout": 5000 + } + ] + ] + }, + "with variables and timeout | data": { + "result": { + "rows": [ + 1, + 2 + ] + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | null data": { + "result": {}, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | no data key": { + "result": {}, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | no body": { + "result": {}, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | no response": { + "result": {}, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "dossiq", + "message": "bad field" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | error without message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "dossiq", + "message": "GraphQL error" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | null first error": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "dossiq", + "message": "GraphQL error" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | empty errors": { + "result": { + "x": 2 + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | errors not a list": { + "result": { + "x": 3 + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | 404": { + "rejected": { + "name": "GraphQLSourceError", + "code": "not_installed", + "app": "dossiq", + "message": "dossiq is not installed" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | 500": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "dossiq", + "message": "Server Error" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | 404 as text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "dossiq", + "message": "Not Found" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "timeout", + "app": "dossiq", + "message": "dossiq did not respond in time" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | 404 and timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "not_installed", + "app": "dossiq", + "message": "dossiq is not installed" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | no message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "dossiq", + "message": "Network error" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | null": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "dossiq", + "message": "Network error" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "with variables and timeout | text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "dossiq", + "message": "Network error" + }, + "sent": [ + [ + "/apps/dossiq/graphql", + { + "query": "query Y { y }", + "variables": { + "period": "month" + } + }, + { + "timeout": 100 + } + ] + ] + }, + "null variables | data": { + "result": { + "rows": [ + 1, + 2 + ] + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | null data": { + "result": {}, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | no data key": { + "result": {}, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | no body": { + "result": {}, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | no response": { + "result": {}, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "a", + "message": "bad field" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | error without message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "a", + "message": "GraphQL error" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | null first error": { + "rejected": { + "name": "GraphQLSourceError", + "code": "graphql_errors", + "app": "a", + "message": "GraphQL error" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | empty errors": { + "result": { + "x": 2 + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | errors not a list": { + "result": { + "x": 3 + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | 404": { + "rejected": { + "name": "GraphQLSourceError", + "code": "not_installed", + "app": "a", + "message": "a is not installed" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | 500": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "a", + "message": "Server Error" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | 404 as text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "a", + "message": "Not Found" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "timeout", + "app": "a", + "message": "a did not respond in time" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | 404 and timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "not_installed", + "app": "a", + "message": "a is not installed" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | no message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "a", + "message": "Network error" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | null": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "a", + "message": "Network error" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "null variables | text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "network_error", + "app": "a", + "message": "Network error" + }, + "sent": [ + [ + "/apps/a/graphql", + { + "query": "q", + "variables": null + }, + { + "timeout": 5000 + } + ] + ] + }, + "blank app | data": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | null data": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | no data key": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | no body": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | no response": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | error without message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | null first error": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | empty errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | errors not a list": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | 404": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | 500": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | 404 as text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | 404 and timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | no message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | null": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "blank app | text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": " ", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | data": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | null data": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | no data key": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | no body": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | no response": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | error without message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | null first error": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | empty errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | errors not a list": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | 404": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | 500": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | 404 as text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | 404 and timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | no message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | null": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "missing app | text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "undefined", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | data": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | null data": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | no data key": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | no body": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | no response": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | error without message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | null first error": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | empty errors": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | errors not a list": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | 404": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | 500": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | 404 as text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | 404 and timeout": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | no message": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | null": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + }, + "numeric app | text": { + "rejected": { + "name": "GraphQLSourceError", + "code": "invalid_app", + "app": "7", + "message": "A sibling app id is required" + }, + "sent": [] + } +} diff --git a/src/services/__tests__/fixtures/resourceUploads.golden.json b/src/services/__tests__/fixtures/resourceUploads.golden.json new file mode 100644 index 000000000..6973986e1 --- /dev/null +++ b/src/services/__tests__/fixtures/resourceUploads.golden.json @@ -0,0 +1,582 @@ +{ + "uploadDataUrl | success": { + "result": { + "url": "/r/a.png", + "name": "a.png", + "size": 12 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | success without name and size": { + "result": { + "url": "/r/b.png", + "name": "", + "size": 0 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | success without url": { + "rejected": { + "name": "ResourceUploadError", + "code": "unknown_error", + "message": "Unexpected server response", + "httpStatus": 200 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | error envelope": { + "rejected": { + "name": "ResourceUploadError", + "code": "file_too_large", + "message": "Too big", + "httpStatus": 200 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | unknown status": { + "rejected": { + "name": "ResourceUploadError", + "code": "unknown_error", + "message": "Unexpected server response", + "httpStatus": 200 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | no body": { + "rejected": { + "name": "ResourceUploadError", + "code": "unknown_error", + "message": "Unexpected server response", + "httpStatus": 204 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | no response": { + "rejected": { + "name": "ResourceUploadError", + "code": "unknown_error", + "message": "Unexpected server response" + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | server error envelope": { + "rejected": { + "name": "ResourceUploadError", + "code": "file_too_large", + "message": "Too big", + "httpStatus": 413 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | envelope without message": { + "rejected": { + "name": "ResourceUploadError", + "code": "forbidden", + "message": "forbidden", + "httpStatus": 403 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | envelope with numeric message": { + "rejected": { + "name": "ResourceUploadError", + "code": "mime_mismatch", + "message": "mime_mismatch", + "httpStatus": 400 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | envelope with numeric error": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Bad", + "httpStatus": 400 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | envelope with another status": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Unprocessable", + "httpStatus": 422 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | not an error envelope": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Gateway", + "httpStatus": 502 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | network": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Network Error" + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | no message": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Network error" + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadDataUrl | null": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Network error" + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources", + { + "base64": "data:image/png;base64,AAAA" + } + ] + ] + }, + "uploadFile | success": { + "result": { + "url": "/r/a.png", + "name": "a.png", + "size": 12 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | success without name and size": { + "result": { + "url": "/r/b.png", + "name": "", + "size": 0 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | success without url": { + "rejected": { + "name": "ResourceUploadError", + "code": "unknown_error", + "message": "Unexpected server response", + "httpStatus": 200 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | error envelope": { + "rejected": { + "name": "ResourceUploadError", + "code": "file_too_large", + "message": "Too big", + "httpStatus": 200 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | unknown status": { + "rejected": { + "name": "ResourceUploadError", + "code": "unknown_error", + "message": "Unexpected server response", + "httpStatus": 200 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | no body": { + "rejected": { + "name": "ResourceUploadError", + "code": "unknown_error", + "message": "Unexpected server response", + "httpStatus": 204 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | no response": { + "rejected": { + "name": "ResourceUploadError", + "code": "unknown_error", + "message": "Unexpected server response" + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | server error envelope": { + "rejected": { + "name": "ResourceUploadError", + "code": "file_too_large", + "message": "Too big", + "httpStatus": 413 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | envelope without message": { + "rejected": { + "name": "ResourceUploadError", + "code": "forbidden", + "message": "forbidden", + "httpStatus": 403 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | envelope with numeric message": { + "rejected": { + "name": "ResourceUploadError", + "code": "mime_mismatch", + "message": "mime_mismatch", + "httpStatus": 400 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | envelope with numeric error": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Bad", + "httpStatus": 400 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | envelope with another status": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Unprocessable", + "httpStatus": 422 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | not an error envelope": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Gateway", + "httpStatus": 502 + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | network": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Network Error" + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | no message": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Network error" + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + }, + "uploadFile | null": { + "rejected": { + "name": "ResourceUploadError", + "code": "network_error", + "message": "Network error" + }, + "sent": [ + [ + "/index.php/apps/launchpad/api/resources/upload", + [ + [ + "file", + "pic.png", + 3, + "image/png" + ] + ] + ] + ] + } +} diff --git a/src/services/__tests__/headerSearch.spec.js b/src/services/__tests__/headerSearch.spec.js new file mode 100644 index 000000000..1448bedd3 --- /dev/null +++ b/src/services/__tests__/headerSearch.spec.js @@ -0,0 +1,118 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Unit tests for the data side of the top bar's results list + * (header-search-dropdown, REQ-SRCH-013): provider order, grouping, the + * detail line, the shortcut tip and the keyboard selection arithmetic. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const get = vi.fn() +vi.mock('@nextcloud/axios', () => ({ default: { get: (...args) => get(...args) } })) +vi.mock('@nextcloud/router', () => ({ + generateOcsUrl: (path, params = {}) => '/ocs/v2.php/' + path.replace('{providerId}', params.providerId ?? ''), +})) + +const { + firstShortcut, + groupResults, + isSearchable, + moveSelection, + orderProviders, + PER_GROUP_LIMIT, + searchAll, + toResult, +} = await import('../headerSearch.js') + +describe('headerSearch', () => { + beforeEach(() => { + get.mockReset() + }) + + it('opens from two characters on', () => { + expect(isSearchable('t')).toBe(false) + expect(isSearchable(' t ')).toBe(false) + expect(isSearchable('te')).toBe(true) + expect(isSearchable(null)).toBe(false) + }) + + it('puts LaunchPad dashboards first, then the providers by order and name', () => { + const ordered = orderProviders([ + { id: 'files', name: 'Files', order: 5 }, + { id: 'launchpad', name: 'Dashboards', order: 50 }, + { id: 'contacts', name: 'Contacts', order: 5 }, + { id: 'mail', name: 'Mail' }, + null, + ]) + expect(ordered.map((p) => p.id)).toEqual(['launchpad', 'contacts', 'files', 'mail']) + }) + + it('keeps a result\'s icon, name, detail line and link', () => { + expect(toResult({ + title: 'Permits team', + subline: 'Shared by Marieke Jansen · 14 widgets', + thumbnailUrl: '/icon.svg', + resourceUrl: '/apps/launchpad/#dashboard/u1', + }, 'launchpad', 0)).toEqual({ + key: 'launchpad-0', + title: 'Permits team', + detail: 'Shared by Marieke Jansen · 14 widgets', + icon: '/icon.svg', + url: '/apps/launchpad/#dashboard/u1', + }) + expect(toResult({ title: 'x', icon: 'icon-files' }, 'files', 2).icon).toBe('icon-files') + }) + + it('groups per provider, skips empty answers and caps each group', () => { + const many = Array.from({ length: PER_GROUP_LIMIT + 3 }, (_, i) => ({ title: `f${i}` })) + const groups = groupResults( + [{ id: 'launchpad', name: 'Dashboards' }, { id: 'mail', name: 'Mail' }, { id: 'files', name: 'Files' }], + { launchpad: [{ title: 'Permits team' }, { title: '' }], mail: [], files: many }, + ) + expect(groups.map((g) => g.name)).toEqual(['Dashboards', 'Files']) + expect(groups[0].results.map((r) => r.title)).toEqual(['Permits team']) + expect(groups[1].results).toHaveLength(PER_GROUP_LIMIT) + }) + + it('takes the first usable shortcut for the tip', () => { + expect(firstShortcut([{ prefix: '', name: 'X' }, { prefix: '!top', name: 'TOPdesk' }])).toEqual({ prefix: '!top', name: 'TOPdesk' }) + expect(firstShortcut([])).toBeNull() + expect(firstShortcut(undefined)).toBeNull() + }) + + it('moves the selection with wrap-around', () => { + expect(moveSelection(0, 1, 3)).toBe(1) + expect(moveSelection(2, 1, 3)).toBe(0) + expect(moveSelection(0, -1, 3)).toBe(2) + expect(moveSelection(-1, 1, 3)).toBe(0) + expect(moveSelection(-1, -1, 3)).toBe(2) + expect(moveSelection(0, 1, 0)).toBe(-1) + }) + + it('asks every provider and returns the grouped answers, LaunchPad first', async () => { + get.mockImplementation((url) => { + if (url === '/ocs/v2.php/search/providers') { + return Promise.resolve({ data: { ocs: { data: [{ id: 'files', name: 'Files', order: 5 }, { id: 'launchpad', name: 'Dashboards', order: 50 }] } } }) + } + if (url.endsWith('/launchpad/search')) { + return Promise.resolve({ data: { ocs: { data: { entries: [{ title: 'Permits team' }] } } } }) + } + return Promise.reject(new Error('down')) + }) + const groups = await searchAll('team', { route: '/apps/launchpad/' }) + expect(groups).toHaveLength(1) + expect(groups[0].id).toBe('launchpad') + const providerCall = get.mock.calls.find(([url]) => url.endsWith('/launchpad/search')) + expect(providerCall[1].params.term).toBe('team') + expect(providerCall[1].headers['OCS-APIRequest']).toBe('true') + }) + + it('returns no groups when the provider list fails', async () => { + get.mockRejectedValue(new Error('offline')) + expect(await searchAll('team', { route: '/' })).toEqual([]) + }) +}) diff --git a/src/services/__tests__/iconCatalogue.spec.js b/src/services/__tests__/iconCatalogue.spec.js index 7b7a629a5..6fe04a337 100644 --- a/src/services/__tests__/iconCatalogue.spec.js +++ b/src/services/__tests__/iconCatalogue.spec.js @@ -3,15 +3,25 @@ * SPDX-License-Identifier: EUPL-1.2 */ +import { DASHBOARD_ICONS } from '@conduction/nextcloud-vue' import * as mdi from '@mdi/js' -import { describe, expect, it } from 'vitest' -import { ICON_CATALOGUE, normaliseIconValue } from '../iconCatalogue.js' +import { beforeAll, describe, expect, it } from 'vitest' +import { DASHBOARD_ICON_CATALOGUE, ICON_CATALOGUE, loadIconCatalogue, normaliseIconValue } from '../iconCatalogue.js' + +describe('before @mdi/js has loaded', () => { + it('has an empty catalogue and leaves names unchanged', () => { + expect(ICON_CATALOGUE).toHaveLength(0) + expect(normaliseIconValue('star')).toBe('star') + }) +}) describe('ICON_CATALOGUE', () => { - it('is a frozen, non-empty array', () => { + beforeAll(() => loadIconCatalogue()) + + it('is a non-empty array once loaded', async () => { expect(Array.isArray(ICON_CATALOGUE)).toBe(true) expect(ICON_CATALOGUE.length).toBeGreaterThan(0) - expect(Object.isFrozen(ICON_CATALOGUE)).toBe(true) + expect(await loadIconCatalogue()).toBe(ICON_CATALOGUE) }) it('produces entries shaped { key, label, value, search, path }', () => { @@ -32,7 +42,26 @@ describe('ICON_CATALOGUE', () => { }) }) +describe('DASHBOARD_ICON_CATALOGUE', () => { + it('offers exactly the shared registry names, stored as the name', () => { + expect(Object.isFrozen(DASHBOARD_ICON_CATALOGUE)).toBe(true) + expect(DASHBOARD_ICON_CATALOGUE.map((entry) => entry.key)).toEqual(Object.keys(DASHBOARD_ICONS)) + for (const entry of DASHBOARD_ICON_CATALOGUE) { + expect(entry.value).toBe(entry.key) + expect(entry.search).toBe(entry.key.toLowerCase()) + expect(entry.component).toBe(DASHBOARD_ICONS[entry.key]) + } + }) + + it('spaces the camel-cased name for its label', () => { + const entry = DASHBOARD_ICON_CATALOGUE.find((e) => e.key === 'ViewDashboard') + expect(entry.label).toBe('View Dashboard') + }) +}) + describe('normaliseIconValue', () => { + beforeAll(() => loadIconCatalogue()) + it('maps a lowercase legacy name to its MDI path', () => { expect(normaliseIconValue('star')).toBe(mdi.mdiStar) expect(normaliseIconValue('folder')).toBe(mdi.mdiFolder) diff --git a/src/services/__tests__/lazyIconCatalogue.spec.js b/src/services/__tests__/lazyIconCatalogue.spec.js new file mode 100644 index 000000000..d9608937c --- /dev/null +++ b/src/services/__tests__/lazyIconCatalogue.spec.js @@ -0,0 +1,20 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { describe, expect, it, vi } from 'vitest' +import { ICON_CATALOGUE, LAZY_ICON_CATALOGUE } from '../iconCatalogue.js' + +describe('LAZY_ICON_CATALOGUE', () => { + it('loads nothing until it is read', () => { + expect(ICON_CATALOGUE).toHaveLength(0) + }) + + it('starts the catalogue load on its first read and then shows the full set', async () => { + expect(LAZY_ICON_CATALOGUE.length).toBe(0) + await vi.waitFor(() => expect(ICON_CATALOGUE.length).toBeGreaterThan(1000), { timeout: 10000 }) + expect(LAZY_ICON_CATALOGUE.length).toBe(ICON_CATALOGUE.length) + expect(LAZY_ICON_CATALOGUE[0]).toBe(ICON_CATALOGUE[0]) + }) +}) diff --git a/src/services/__tests__/liveTileConnections.spec.js b/src/services/__tests__/liveTileConnections.spec.js new file mode 100644 index 000000000..3ca464883 --- /dev/null +++ b/src/services/__tests__/liveTileConnections.spec.js @@ -0,0 +1,54 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The connections the Live data form offers (REQ-LIVETILE-020). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { fetchLiveTileConnections, lastSuccessOf, toConnectionOption } from '../liveTileConnections.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params) => path.replace(/\{(\w+)\}/g, (_, key) => params[key]), +})) + +beforeEach(() => { + axios.get.mockReset() +}) + +describe('lastSuccessOf', () => { + it('prefers the row\'s own last success, else a successful last check', () => { + expect(lastSuccessOf({ lastSuccessAt: '2026-11-25T10:38:00Z', checkedAt: 'x' })).toBe('2026-11-25T10:38:00Z') + expect(lastSuccessOf({ status: 'ok', checkedAt: '2026-11-25T10:00:00Z' })).toBe('2026-11-25T10:00:00Z') + expect(lastSuccessOf({ status: 'error', checkedAt: '2026-11-25T10:00:00Z' })).toBeNull() + expect(lastSuccessOf(null)).toBeNull() + }) +}) + +describe('toConnectionOption', () => { + it('uses the source id as the value and the title as the label', () => { + expect(toConnectionOption({ sourceId: 'kcc-queue', title: 'Contact centre queue', lastSuccessAt: 't' })) + .toEqual({ value: 'kcc-queue', label: 'Contact centre queue', lastSuccessAt: 't' }) + expect(toConnectionOption({ id: 7 })).toEqual({ value: '7', label: '7', lastSuccessAt: null }) + expect(toConnectionOption({ title: 'No id' })).toBeNull() + }) +}) + +describe('fetchLiveTileConnections', () => { + it('reads integriq\'s connections of this app and leaves out rows without an id', async () => { + axios.get.mockResolvedValue({ data: { results: [{ sourceId: 'a', title: 'A' }, { title: 'none' }] } }) + const list = await fetchLiveTileConnections() + expect(axios.get).toHaveBeenCalledWith( + '/apps/openregister/api/objects/integriq/app_connection', + { params: { app: 'launchpad', _limit: 100 } }, + ) + expect(list).toEqual([{ value: 'a', label: 'A', lastSuccessAt: null }]) + }) + + it('gives an empty list when the read fails', async () => { + axios.get.mockRejectedValue(new Error('403')) + expect(await fetchLiveTileConnections()).toEqual([]) + }) +}) diff --git a/src/services/__tests__/needsAttention.golden.spec.js b/src/services/__tests__/needsAttention.golden.spec.js new file mode 100644 index 000000000..fddf68108 --- /dev/null +++ b/src/services/__tests__/needsAttention.golden.spec.js @@ -0,0 +1,80 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for needsAttention(): every operator against a set of counts and + * right-hand sides, compared with fixtures/needsAttention.golden.json. Set + * RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it } from 'vitest' +import { needsAttention } from '../attentionFeed.js' + +const FIXTURE = path.resolve(__dirname, 'fixtures/needsAttention.golden.json') + +const OPS = { + gt: 'gt', + gte: 'gte', + lt: 'lt', + lte: 'lte', + eq: 'eq', + neq: 'neq', + 'upper case': 'GT', + unknown: 'between', + 'empty string': '', + 'prototype key': 'toString', + constructor: 'constructor', + proto: '__proto__', + 'own property check': 'hasOwnProperty', + undefined, + null: null, + number: 1, +} + +const VALUES = { + zero: 0, + one: 1, + five: 5, + negative: -2, + 'string one': '1', + NaN, + undefined, + null: null, +} + +/** + * Run one case and record its result or the error it throws. + * + * @param {Array} args The arguments. + * @return {object} The outcome. + */ +function outcome(args) { + try { + return { result: needsAttention(...args) } + } catch (error) { + return { error: error.message } + } +} + +describe('needsAttention (golden)', () => { + it('matches the recorded results', () => { + const actual = {} + for (const [o, op] of Object.entries(OPS)) { + for (const [c, count] of Object.entries(VALUES)) { + for (const [v, value] of Object.entries(VALUES)) { + actual[`${o} | ${c} | ${v}`] = outcome([count, op, value]) + } + } + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + for (const key of Object.keys(expected)) { + expect(actual[key], key).toEqual(expected[key]) + } + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + }) +}) diff --git a/src/services/__tests__/peopleNewColleaguesWidget.spec.js b/src/services/__tests__/peopleNewColleaguesWidget.spec.js new file mode 100644 index 000000000..11d9c0812 --- /dev/null +++ b/src/services/__tests__/peopleNewColleaguesWidget.spec.js @@ -0,0 +1,122 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * People widget "New colleagues" (REQ-PPL-014): LaunchPad's people source + * (`buildWidgetDataProvide().cnPeopleSource`) drives nextcloud-vue's + * CnPeopleWidget in `selectionMode: 'new'`. The widget lists the colleagues + * `GET /api/people/new` returns, with "Starts {weekday}" for a future start, + * and says so when no profile field is marked as the start date. + * + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ + +import { flushPromises, mount } from '@vue/test-utils' +import fs from 'fs' +import path from 'path' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), + translatePlural: (_app, one, many, count) => + (count === 1 ? one : many).replace('%n', String(count)), + getCanonicalLocale: () => 'en-GB', + getLanguage: () => 'en', + getLocale: () => 'en_GB', +})) +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, + generateOcsUrl: (path) => `/ocs/v2.php${path}`, + imagePath: (app, file) => `/${app}/img/${file}`, + linkTo: (app, file) => `/${app}/${file}`, +})) + +import axios from '@nextcloud/axios' +import CnPeopleWidget from '@conduction/nextcloud-vue/src/components/CnPeopleWidget/CnPeopleWidget.vue' +import { buildWidgetDataProvide } from '../widgetDataAdapters.js' + +/** + * Mount the people widget on a New colleagues placement with LaunchPad's source. + * + * @param {object} content Extra placement content. + * @return {Promise<object>} The wrapper after the first fetch. + */ +async function mountNewColleagues(content = {}) { + const wrapper = mount(CnPeopleWidget, { + props: { content: { selectionMode: 'new', layout: 'list', newSinceDays: 30, newUntilDays: 14, ...content } }, + global: { provide: buildWidgetDataProvide(() => 7) }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + axios.get.mockReset() +}) + +describe('People widget: New colleagues through the LaunchPad source', () => { + it('lists the colleagues the endpoint returns, asking with the placement window', async () => { + axios.get.mockResolvedValue({ + data: { + configured: true, + users: [ + { id: 'yasmina', displayName: 'Yasmina El Amrani', role: 'Beleidsadviseur', startDate: '2026-12-07', starts: true }, + { id: 'thomas', displayName: 'Thomas de Wit', role: 'Jurist', startDate: '2026-11-18', starts: false }, + ], + }, + }) + const wrapper = await mountNewColleagues() + + expect(axios.get).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/people/new', + { params: { since: 30, until: 14 } }, + ) + const names = wrapper.findAll('.cn-people-widget__name').map((n) => n.text()) + expect(names).toEqual(['Yasmina El Amrani', 'Thomas de Wit']) + const starts = wrapper.findAll('[data-testid="cn-people-starts"]') + expect(starts).toHaveLength(1) + expect(starts[0].text()).toBe('Starts Monday') + }) + + it('says so when no profile field is marked as the start date', async () => { + axios.get.mockResolvedValue({ data: { configured: false, users: [] } }) + const wrapper = await mountNewColleagues() + + expect(wrapper.findAll('.cn-people-widget__item')).toHaveLength(0) + expect(wrapper.find('.cn-people-widget__state').exists()).toBe(true) + }) + + it('shows the error state when the read fails', async () => { + axios.get.mockRejectedValue(new Error('down')) + const wrapper = await mountNewColleagues() + + expect(wrapper.find('.cn-people-widget__retry').exists()).toBe(true) + }) +}) + +describe('People widget: New colleagues in every LaunchPad locale', () => { + const KEYS = [ + 'The administrator has not set a start date field.', + 'Starts {weekday}', + 'Selection', + 'People by filter', + 'New colleagues', + 'Started in the last (days, 1–90)', + 'Starts within (days, 0–30)', + 'Must be between {min} and {max}', + ] + const root = path.resolve(__dirname, '../../..') + const ncVue = path.join(root, 'node_modules/@conduction/nextcloud-vue/l10n') + const locales = fs.readdirSync(path.join(root, 'l10n')) + .filter((file) => /^[a-z]{2}(_[A-Z]{2})?\.json$/.test(file) && file !== 'en.json') + .map((file) => file.slice(0, -5)) + + it.each(locales)('nextcloud-vue translates every New colleagues string in %s', (locale) => { + const catalogue = JSON.parse(fs.readFileSync(path.join(ncVue, `${locale}.json`), 'utf8')).translations + expect(KEYS.filter((key) => typeof catalogue[key] !== 'string' || catalogue[key] === '')).toEqual([]) + }) +}) diff --git a/src/services/__tests__/publicWidgetClient.spec.js b/src/services/__tests__/publicWidgetClient.spec.js new file mode 100644 index 000000000..b72993442 --- /dev/null +++ b/src/services/__tests__/publicWidgetClient.spec.js @@ -0,0 +1,55 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The token-scoped live widget reads of a public link and a kiosk screen + * (REQ-PSHR-011). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { kioskWidgetReader, shareWidgetReader } from '../publicWidgetClient.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => '/index.php' + path, +})) + +beforeEach(() => { + axios.get.mockReset() + axios.get.mockResolvedValue({ data: { widget: 'weather', data: { tempValue: 12 } } }) +}) + +describe('publicWidgetClient', () => { + it('reads a placement through the share token, with the password header', async () => { + const read = shareWidgetReader('abc', 'secret') + const result = await read(7) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/s/abc/placements/7', { headers: { 'X-Share-Password': 'secret' } }) + expect(result).toEqual({ widget: 'weather', data: { tempValue: 12 } }) + }) + + it('encodes the token', async () => { + await shareWidgetReader('a/b c')(7) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/s/a%2Fb%20c/placements/7', { headers: {} }) + }) + + it('sends no password header for an open link', async () => { + await shareWidgetReader('abc')(7) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/s/abc/placements/7', { headers: {} }) + }) + + it('reads a placement through the kiosk playlist token', async () => { + await kioskWidgetReader('kiosk1')(9) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/kiosk/kiosk1/placements/9', { headers: {} }) + }) + + it('answers an empty object when the response has no body', async () => { + axios.get.mockResolvedValue({}) + expect(await kioskWidgetReader('kiosk1')(9)).toEqual({}) + }) + + it('lets a refused read reject, so the widget shows its failed state', async () => { + axios.get.mockRejectedValue(new Error('404')) + await expect(shareWidgetReader('abc')(7)).rejects.toThrow('404') + }) +}) diff --git a/src/services/__tests__/queryGraphql.golden.spec.js b/src/services/__tests__/queryGraphql.golden.spec.js new file mode 100644 index 000000000..c45062067 --- /dev/null +++ b/src/services/__tests__/queryGraphql.golden.spec.js @@ -0,0 +1,122 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for queryGraphql(): a set of call parameters against answers + * and request failures, each with the request sent, compared with + * fixtures/queryGraphql.golden.json. Set RECORD_GOLDEN=1 to rewrite it. + */ + +import axios from '@nextcloud/axios' +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { queryGraphql } from '../graphqlClient.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { post: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + Object.entries(params).reduce( + (acc, [key, value]) => acc.replace(`{${key}}`, value), + path, + ), +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/queryGraphql.golden.json') + +const PARAMS = { + 'app and query': { app: 'financeq', query: 'query X { x }' }, + 'with variables and timeout': { + app: 'dossiq', + query: 'query Y { y }', + variables: { period: 'month' }, + timeoutMs: 100, + }, + 'null variables': { app: 'a', query: 'q', variables: null }, + 'blank app': { app: ' ', query: 'q' }, + 'missing app': { query: 'q' }, + 'numeric app': { app: 7, query: 'q' }, +} + +const ANSWERS = { + data: { data: { data: { rows: [1, 2] } } }, + 'null data': { data: { data: null } }, + 'no data key': { data: {} }, + 'no body': { data: null }, + 'no response': undefined, + errors: { data: { errors: [{ message: 'bad field' }, { message: 'two' }] } }, + 'error without message': { data: { errors: [{}], data: { x: 1 } } }, + 'null first error': { data: { errors: [null] } }, + 'empty errors': { data: { errors: [], data: { x: 2 } } }, + 'errors not a list': { data: { errors: 'oops', data: { x: 3 } } }, +} + +const FAILURES = { + 404: Object.assign(new Error('Not Found'), { response: { status: 404 } }), + '404 as text': Object.assign(new Error('Not Found'), { + response: { status: '404' }, + }), + 500: Object.assign(new Error('Server Error'), { response: { status: 500 } }), + timeout: Object.assign(new Error('timeout of 5000ms exceeded'), { + code: 'ECONNABORTED', + }), + '404 and timeout': Object.assign(new Error('both'), { + code: 'ECONNABORTED', + response: { status: 404 }, + }), + 'no message': Object.assign(new Error(''), { code: 'ERR_NETWORK' }), + null: null, + text: 'down', +} + +/** + * Run one case and record what it resolved to, or the error it rejected + * with, and the request it sent. + * + * @param {object} params The call parameters. + * @return {Promise<object>} The outcome. + */ +async function outcome(params) { + try { + const result = await queryGraphql(params) + return { result, sent: axios.post.mock.calls } + } catch (error) { + return { + rejected: { + name: error.name, + code: error.code, + app: error.app, + message: error.message, + }, + sent: axios.post.mock.calls, + } + } +} + +describe('queryGraphql (golden)', () => { + it('matches the recorded results', async () => { + const actual = {} + for (const [p, params] of Object.entries(PARAMS)) { + for (const [a, answer] of Object.entries(ANSWERS)) { + axios.post.mockReset() + axios.post.mockResolvedValue(answer) + actual[`${p} | ${a}`] = await outcome(params) + } + for (const [f, failure] of Object.entries(FAILURES)) { + axios.post.mockReset() + axios.post.mockRejectedValue(failure) + actual[`${p} | ${f}`] = await outcome(params) + } + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + for (const key of Object.keys(expected)) { + expect(actual[key], key).toEqual(expected[key]) + } + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + }) +}) diff --git a/src/services/__tests__/resourceUploads.golden.spec.js b/src/services/__tests__/resourceUploads.golden.spec.js new file mode 100644 index 000000000..b69828646 --- /dev/null +++ b/src/services/__tests__/resourceUploads.golden.spec.js @@ -0,0 +1,145 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for uploadDataUrl() and uploadFile(): each against a set of + * server answers and request failures, with the request sent, compared with + * fixtures/resourceUploads.golden.json. Set RECORD_GOLDEN=1 to rewrite it. + */ + +import axios from '@nextcloud/axios' +import fs from 'node:fs' +import path from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { uploadDataUrl, uploadFile } from '../resourceService.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { post: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/resourceUploads.golden.json') + +const ANSWERS = { + success: { + status: 200, + data: { status: 'success', url: '/r/a.png', name: 'a.png', size: 12 }, + }, + 'success without name and size': { + status: 201, + data: { status: 'success', url: '/r/b.png', name: 3, size: '12' }, + }, + 'success without url': { status: 200, data: { status: 'success' } }, + 'error envelope': { + status: 200, + data: { status: 'error', error: 'file_too_large', message: 'Too big' }, + }, + 'unknown status': { status: 200, data: { status: 'pending', url: '/r/c' } }, + 'no body': { status: 204, data: null }, + 'no response': undefined, +} + +const FAILURES = { + 'server error envelope': Object.assign(new Error('Request failed'), { + response: { + status: 413, + data: { status: 'error', error: 'file_too_large', message: 'Too big' }, + }, + }), + 'envelope without message': Object.assign(new Error('Request failed'), { + response: { status: 403, data: { status: 'error', error: 'forbidden' } }, + }), + 'envelope with numeric message': Object.assign(new Error('x'), { + response: { + status: 400, + data: { status: 'error', error: 'mime_mismatch', message: 5 }, + }, + }), + 'envelope with numeric error': Object.assign(new Error('Bad'), { + response: { status: 400, data: { status: 'error', error: 9 } }, + }), + 'envelope with another status': Object.assign(new Error('Unprocessable'), { + response: { + status: 422, + data: { status: 'fail', error: 'invalid_svg', message: 'Bad SVG' }, + }, + }), + 'not an error envelope': Object.assign(new Error('Gateway'), { + response: { status: 502, data: '<html>' }, + }), + network: Object.assign(new Error('Network Error'), { code: 'ERR_NETWORK' }), + 'no message': new Error(''), + null: null, +} + +const CALLS = { + uploadDataUrl: () => uploadDataUrl('data:image/png;base64,AAAA'), + uploadFile: () => + uploadFile(new File(['abc'], 'pic.png', { type: 'image/png' })), +} + +/** + * The request axios was given, with a form written as its entries. + * + * @return {Array} The recorded calls. + */ +function sent() { + return axios.post.mock.calls.map(([url, body, ...rest]) => [ + url, + body instanceof FormData + ? [...body.entries()].map(([k, v]) => [k, v.name, v.size, v.type]) + : body, + ...rest, + ]) +} + +/** + * Run one case and record what it resolved to, or the error it rejected + * with, and the request it sent. + * + * @param {() => Promise<object>} call The upload to run. + * @return {Promise<object>} The outcome. + */ +async function outcome(call) { + try { + return { result: await call(), sent: sent() } + } catch (error) { + return { + rejected: { + name: error.name, + code: error.code, + message: error.message, + httpStatus: error.httpStatus, + }, + sent: sent(), + } + } +} + +describe('resource uploads (golden)', () => { + it('matches the recorded results', async () => { + const actual = {} + for (const [c, call] of Object.entries(CALLS)) { + for (const [a, answer] of Object.entries(ANSWERS)) { + axios.post.mockReset() + axios.post.mockResolvedValue(answer) + actual[`${c} | ${a}`] = await outcome(call) + } + for (const [f, failure] of Object.entries(FAILURES)) { + axios.post.mockReset() + axios.post.mockRejectedValue(failure) + actual[`${c} | ${f}`] = await outcome(call) + } + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + for (const key of Object.keys(expected)) { + expect(actual[key], key).toEqual(expected[key]) + } + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + }) +}) diff --git a/src/services/__tests__/sourceAvailability.spec.js b/src/services/__tests__/sourceAvailability.spec.js new file mode 100644 index 000000000..1b88f8c43 --- /dev/null +++ b/src/services/__tests__/sourceAvailability.spec.js @@ -0,0 +1,114 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * sourceAvailability (admin-templates REQ-TMPL-022): which placements may + * hide when their register/schema is absent, and the once-per-page probe + * that tells "not here" (404) apart from "could not tell" (any other failure). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + hidesWhenUnavailable, + isSourceAvailable, + resetSourceAvailability, + sourceKey, +} from '../sourceAvailability.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + '/index.php' + path.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) + +beforeEach(() => { + axios.get.mockReset() + resetSourceAvailability() +}) + +describe('sourceKey', () => { + it('reads an object-list source at the top of its content', () => { + expect(sourceKey({ register: 'dossiq', schema: 'case' })).toBe('dossiq/case') + }) + + it('reads a stat widget source under `source`', () => { + expect(sourceKey({ source: { register: 'pipelinq', schema: 'lead' } })).toBe('pipelinq/lead') + }) + + it('prefers a top-level register over `source`', () => { + expect(sourceKey({ register: 'a', schema: 'b', source: { register: 'c', schema: 'd' } })).toBe('a/b') + }) + + it('is empty when either half or the content is missing', () => { + expect(sourceKey({ register: 'a' })).toBe('') + expect(sourceKey({ source: { schema: 'b' } })).toBe('') + expect(sourceKey(null)).toBe('') + expect(sourceKey(undefined)).toBe('') + }) +}) + +describe('hidesWhenUnavailable', () => { + const content = { register: 'r', schema: 's', hideWhenUnavailable: true } + + it('is true for an object-list or stat that asks to hide and names a source', () => { + expect(hidesWhenUnavailable({ widgetId: 'object-list', content })).toBe(true) + expect(hidesWhenUnavailable({ widgetId: 'stat', content: { source: { register: 'r', schema: 's' }, hideWhenUnavailable: true } })).toBe(true) + }) + + it('is false for another widget type', () => { + expect(hidesWhenUnavailable({ widgetId: 'news', content })).toBe(false) + }) + + it('is false unless the flag is exactly true', () => { + expect(hidesWhenUnavailable({ widgetId: 'object-list', content: { ...content, hideWhenUnavailable: 'yes' } })).toBe(false) + expect(hidesWhenUnavailable({ widgetId: 'object-list', content: { register: 'r', schema: 's' } })).toBe(false) + }) + + it('is false without content, a source, or a placement', () => { + expect(hidesWhenUnavailable({ widgetId: 'object-list' })).toBe(false) + expect(hidesWhenUnavailable({ widgetId: 'object-list', content: { hideWhenUnavailable: true } })).toBe(false) + expect(hidesWhenUnavailable(null)).toBe(false) + }) +}) + +describe('isSourceAvailable', () => { + it('asks OpenRegister for one object and answers true', async () => { + axios.get.mockResolvedValue({ data: {} }) + + await expect(isSourceAvailable('dossiq', 'case')).resolves.toBe(true) + expect(axios.get).toHaveBeenCalledWith( + '/index.php/apps/openregister/api/objects/dossiq/case', + { params: { _limit: 1 } }, + ) + }) + + it('answers false only for a 404', async () => { + axios.get.mockRejectedValue({ response: { status: 404 } }) + + await expect(isSourceAvailable('gone', 'x')).resolves.toBe(false) + }) + + it.each([ + ['a 403', { response: { status: 403 } }], + ['a 500', { response: { status: 500 } }], + ['no response', new Error('Network Error')], + ['nothing', undefined], + ])('answers null for %s', async (_label, error) => { + axios.get.mockRejectedValue(error) + + await expect(isSourceAvailable('r', 's')).resolves.toBeNull() + }) + + it('asks once per source and shares the answer until reset', async () => { + axios.get.mockResolvedValue({ data: {} }) + + await Promise.all([isSourceAvailable('r', 's'), isSourceAvailable('r', 's')]) + await isSourceAvailable('r', 'other') + expect(axios.get).toHaveBeenCalledTimes(2) + + resetSourceAvailability() + await isSourceAvailable('r', 's') + expect(axios.get).toHaveBeenCalledTimes(3) + }) +}) diff --git a/src/services/__tests__/statusReport.spec.js b/src/services/__tests__/statusReport.spec.js new file mode 100644 index 000000000..9a566f2d3 --- /dev/null +++ b/src/services/__tests__/statusReport.spec.js @@ -0,0 +1,60 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The status report client (dashboards-and-who-may-see-them REQ-DWMS-004). + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const post = vi.fn() +vi.mock('@nextcloud/axios', () => ({ default: { post: (...args) => post(...args) } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) + +import { draftStatusReport, keepStatusReport, subjectOf } from '../statusReport.js' + +beforeEach(() => { + post.mockReset() +}) + +describe('subjectOf', () => { + it('keeps the filled, trimmed keys and splits closed values written with commas', () => { + expect(subjectOf({ register: ' dossiq ', schema: 'case', title: '', deadline: '2026-12-31', closedValues: 'done, closed ,', other: 'x' })) + .toEqual({ register: 'dossiq', schema: 'case', deadline: '2026-12-31', closedValues: ['done', 'closed'] }) + }) + + it('takes closed values stored as a list and leaves out an empty one', () => { + expect(subjectOf({ register: 'r', schema: 's', closedValues: ['done', ' '] })).toEqual({ register: 'r', schema: 's', closedValues: ['done'] }) + expect(subjectOf({ register: 'r', schema: 's', closedValues: [] })).toEqual({ register: 'r', schema: 's' }) + expect(subjectOf(undefined)).toEqual({}) + }) +}) + +describe('draftStatusReport and keepStatusReport', () => { + it('posts the subject for a draft', async () => { + post.mockResolvedValue({ data: { health: 'on-track' } }) + + await expect(draftStatusReport({ register: 'r', schema: 's' })).resolves.toEqual({ refused: false, report: { health: 'on-track' } }) + expect(post).toHaveBeenCalledWith('/index.php/apps/launchpad/api/status-reports/draft', { register: 'r', schema: 's' }) + }) + + it('posts the subject with the rating and summary to keep', async () => { + post.mockResolvedValue({ data: { id: 'k' } }) + + await expect(keepStatusReport({ register: 'r', schema: 's' }, 'at-risk', 'Text')).resolves.toEqual({ refused: false, report: { id: 'k' } }) + expect(post).toHaveBeenCalledWith('/index.php/apps/launchpad/api/status-reports', { register: 'r', schema: 's', health: 'at-risk', summary: 'Text' }) + }) + + it('answers an HTTP refusal with its status', async () => { + post.mockRejectedValue({ response: { status: 503, data: { error: 'x' } } }) + + await expect(keepStatusReport({}, 'on-track', 'x')).resolves.toEqual({ refused: true, status: 503 }) + }) + + it('throws a failure that is not an HTTP answer', async () => { + const failure = new Error('network') + post.mockRejectedValue(failure) + + await expect(draftStatusReport({})).rejects.toBe(failure) + }) +}) diff --git a/src/services/__tests__/talkCommunities.spec.js b/src/services/__tests__/talkCommunities.spec.js new file mode 100644 index 000000000..c90234ca5 --- /dev/null +++ b/src/services/__tests__/talkCommunities.spec.js @@ -0,0 +1,136 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Talk communities: what the widget is given from Talk's OCS answers + * (openspec/changes/engagement-communities REQ-COMM-001..003). + */ + +import { describe, expect, it, vi } from 'vitest' +import { + communityUrl, + joinCommunity, + loadCommunities, +} from '../talkCommunities.js' + +const ocs = (data) => ({ data: { ocs: { meta: { status: 'ok' }, data } } }) + +/** + * A client answering the listed-room and room endpoints. + * + * @param {Array<object>} listed The open rooms Talk lists. + * @param {Array<object>} own The viewer's rooms. + * @return {object} The client. + */ +function client(listed, own) { + return { + get: vi.fn((url) => + Promise.resolve(ocs(url.endsWith('/listed-room') ? listed : own)), + ), + post: vi.fn().mockResolvedValue(ocs([])), + delete: vi.fn().mockResolvedValue(ocs([])), + } +} + +const DUURZAAMHEID = { + token: 'duurzaam42', + displayName: 'Duurzaamheid', + description: 'Ideeën voor een groenere organisatie', + listable: 2, + participantCount: 14, +} +const VRAAG_ICT = { token: 'vraagict', displayName: 'Vraag het de ICT', description: '', listable: 1 } + +describe('loadCommunities', () => { + it('asks Talk as the viewer for the listed rooms and their own rooms, with the OCS header', async () => { + const http = client([DUURZAAMHEID], []) + + await loadCommunities([], { client: http }) + + const urls = http.get.mock.calls.map(([url]) => url) + expect(urls).toEqual([ + expect.stringMatching(/\/ocs\/v2\.php\/apps\/spreed\/api\/v4\/listed-room$/), + expect.stringMatching(/\/ocs\/v2\.php\/apps\/spreed\/api\/v4\/room$/), + ]) + for (const [, config] of http.get.mock.calls) { + expect(config.headers['OCS-APIRequest']).toBe('true') + } + }) + + it('lists each open room with name, description and member count, and marks the joined ones', async () => { + const own = [{ ...VRAAG_ICT }, { token: 'privateroom', displayName: 'Team', listable: 0 }] + + const communities = await loadCommunities([], { client: client([DUURZAAMHEID], own) }) + + expect(communities).toEqual([ + { + token: 'duurzaam42', + name: 'Duurzaamheid', + description: 'Ideeën voor een groenere organisatie', + members: 14, + joined: false, + pinned: false, + }, + { + token: 'vraagict', + name: 'Vraag het de ICT', + description: '', + members: null, + joined: true, + pinned: false, + }, + ]) + }) + + it('puts the pinned ones first in the order pinned, the rest by name, each once', async () => { + const listed = [ + { token: 'zzzzroom', displayName: 'Zeilen', listable: 2 }, + DUURZAAMHEID, + VRAAG_ICT, + { token: 'aaaaroom', displayName: 'Atletiek', listable: 2 }, + ] + + const communities = await loadCommunities(['vraagict', 'notvisible', 'zzzzroom'], { + client: client(listed, [VRAAG_ICT]), + }) + + expect(communities.map((c) => [c.token, c.pinned])).toEqual([ + ['vraagict', true], + ['zzzzroom', true], + ['aaaaroom', false], + ['duurzaam42', false], + ]) + }) + + it('fails when Talk does', async () => { + const http = { get: vi.fn().mockRejectedValue(new Error('Request failed with status code 404')) } + + await expect(loadCommunities([], { client: http })).rejects.toThrow('404') + }) +}) + +describe('joinCommunity and communityUrl', () => { + it('joins through Talk as the viewer and opens the conversation in Talk', async () => { + const http = client([], []) + + await joinCommunity('duurzaam42', { client: http }) + + // Talk has no POST on participants/self (that path only removes you); + // joining a listable conversation is opening a session on it. + const session = /\/ocs\/v2\.php\/apps\/spreed\/api\/v4\/room\/duurzaam42\/participants\/active$/ + expect(http.post).toHaveBeenCalledWith( + expect.stringMatching(session), + {}, + expect.objectContaining({ headers: expect.objectContaining({ 'OCS-APIRequest': 'true' }) }), + ) + expect(http.delete).toHaveBeenCalledWith(expect.stringMatching(session), expect.anything()) + expect(communityUrl('duurzaam42')).toMatch(/\/call\/duurzaam42$/) + }) + + it('is joined even when closing the session fails', async () => { + const http = client([], []) + http.delete.mockRejectedValue(new Error('404')) + + await expect(joinCommunity('duurzaam42', { client: http })).resolves.toBeUndefined() + }) +}) diff --git a/src/services/__tests__/tileCount.spec.js b/src/services/__tests__/tileCount.spec.js new file mode 100644 index 000000000..107e35201 --- /dev/null +++ b/src/services/__tests__/tileCount.spec.js @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + +/** + * The live count of an app tile (icon-only-app-tiles REQ-ICT-002). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + clearTileCounts, + COUNT_TTL_MS, + countLabel, + registerQuery, + registerTotal, + resolveTileCount, + sourceType, + widgetItemsCount, +} from '../tileCount.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params) => path.replace(/\{(\w+)\}/g, (_, key) => params[key]), + generateOcsUrl: (path) => '/ocs/v2.php' + path, +})) + +const CASES = { type: 'register', register: 'dossiq', schema: 'case', filter: { assignee: '@me', isFinalStatus: false } } + +beforeEach(() => { + axios.get.mockReset() + clearTileCounts() +}) + +describe('sourceType', () => { + it('knows register and nc-widget sources, a typeless register source too', () => { + expect(sourceType(CASES)).toBe('register') + expect(sourceType({ register: 'r', schema: 's' })).toBe('register') + expect(sourceType({ type: 'nc-widget', widgetId: 'spreed' })).toBe('nc-widget') + expect(sourceType({ type: 'nc-widget' })).toBeNull() + expect(sourceType({ type: 'register', register: 'r' })).toBeNull() + expect(sourceType({ type: 'sql' })).toBeNull() + expect(sourceType(null)).toBeNull() + }) +}) + +describe('Open cases on the Zaaksysteem tile (scenario)', () => { + it('asks OpenRegister with @me as the viewer and shows the total', async () => { + axios.get.mockResolvedValue({ data: { total: 14, results: [{}] } }) + expect(await resolveTileCount(CASES, 'pieter')).toBe(14) + expect(axios.get).toHaveBeenCalledWith('/apps/openregister/api/objects/dossiq/case', { + params: { _limit: 1, assignee: 'pieter', isFinalStatus: false }, + }) + expect(countLabel(14)).toBe('14') + }) + + it('shows no pill when the register is missing', async () => { + axios.get.mockRejectedValue({ response: { status: 404 } }) + expect(await resolveTileCount(CASES, 'pieter')).toBeNull() + expect(countLabel(null)).toBe('') + }) +}) + +describe('nc-widget sources', () => { + it('counts the items the dashboard widget returns', async () => { + axios.get.mockResolvedValue({ data: { ocs: { data: { spreed: [{}, {}, {}] } } } }) + expect(await resolveTileCount({ type: 'nc-widget', widgetId: 'spreed' }, 'pieter')).toBe(3) + expect(axios.get).toHaveBeenCalledWith('/ocs/v2.php/apps/dashboard/api/v2/widget-items', { params: { 'widgets[]': 'spreed' } }) + }) + + it('reads no count for a widget the answer does not hold', () => { + expect(widgetItemsCount({ ocs: { data: {} } }, 'spreed')).toBeNull() + expect(widgetItemsCount({ ocs: { data: { spreed: { items: [{}] } } } }, 'spreed')).toBe(1) + }) +}) + +describe('throttling', () => { + it('asks each source at most once a minute', async () => { + axios.get.mockResolvedValue({ data: { total: 2 } }) + await resolveTileCount(CASES, 'pieter', 1000) + await resolveTileCount(CASES, 'pieter', 1000 + COUNT_TTL_MS - 1) + expect(axios.get).toHaveBeenCalledTimes(1) + await resolveTileCount(CASES, 'pieter', 1000 + COUNT_TTL_MS) + expect(axios.get).toHaveBeenCalledTimes(2) + }) + + it('asks nothing for no source', async () => { + expect(await resolveTileCount(undefined, 'pieter')).toBeNull() + expect(axios.get).not.toHaveBeenCalled() + }) +}) + +describe('labels and parsing', () => { + it('shows no pill on 0, 99+ above 99', () => { + expect(countLabel(0)).toBe('') + expect(countLabel(-1)).toBe('') + expect(countLabel(99)).toBe('99') + expect(countLabel(100)).toBe('99+') + expect(countLabel(3.7)).toBe('3') + }) + + it('reads the total, else the results', () => { + expect(registerTotal({ total: 0 })).toBe(0) + expect(registerTotal({ results: [{}, {}] })).toBe(2) + expect(registerTotal({})).toBeNull() + expect(registerQuery(undefined, 'x')).toEqual({ _limit: 1 }) + }) +}) diff --git a/src/services/__tests__/widgetBridge.spec.js b/src/services/__tests__/widgetBridge.spec.js index c7e5b53e3..f7b475218 100644 --- a/src/services/__tests__/widgetBridge.spec.js +++ b/src/services/__tests__/widgetBridge.spec.js @@ -116,3 +116,28 @@ describe('WidgetBridge OCA.Dashboard exposure (CnNcWidgetWidget contract)', () = expect(() => widgetBridge.setWidgetMetadata(null)).not.toThrow() }) }) + +describe('WidgetBridge mounting clears the container without HTML injection', () => { + it('removes the previous content before calling a dashboard widget callback', () => { + const container = document.createElement('div') + container.appendChild(document.createElement('span')) + const seen = [] + widgetBridge.widgetCallbacks.set('notes', (el) => seen.push(el.childNodes.length)) + + widgetBridge.mountWidget('notes', container, {}) + + expect(seen).toEqual([0]) + }) + + it('removes the previous content before calling a status widget callback', () => { + const container = document.createElement('div') + container.appendChild(document.createElement('span')) + const seen = [] + widgetBridge.statusCallbacks.set('weather', (el) => seen.push(el.childNodes.length)) + + widgetBridge.mountStatusWidget('weather', container) + + expect(seen).toEqual([0]) + widgetBridge.statusCallbacks.delete('weather') + }) +}) diff --git a/src/services/__tests__/widgetDataAdapters.spec.js b/src/services/__tests__/widgetDataAdapters.spec.js new file mode 100644 index 000000000..ee3e3157d --- /dev/null +++ b/src/services/__tests__/widgetDataAdapters.spec.js @@ -0,0 +1,187 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * widgetDataAdapters: the calendar adapter's request and normalised result, + * the provide() map the data widgets inject, and the renderer extra props. + * fetchPeoplePage has its own golden spec. + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + fetchFinanceSummary, + fetchSpendNarrative, + fetchVendorCommitments, + resolveDeepLink, +} from '../spendAnalytics.js' +import { + buildRendererExtraProps, + buildWidgetDataProvide, + fetchCalendarEvents, +} from '../widgetDataAdapters.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path, params = {}) => + '/index.php' + path.replace(/\{(\w+)\}/g, (_m, k) => String(params[k])), +})) + +beforeEach(() => { + axios.get.mockReset() +}) + +describe('fetchCalendarEvents', () => { + it('requests the placement events for the window and returns them', async () => { + const events = [{ id: 'e1' }] + const failures = [{ calendar: 'c2' }] + axios.get.mockResolvedValue({ data: { events, failures } }) + + const result = await fetchCalendarEvents(17, { from: '2026-01-01', to: '2026-01-31' }) + + expect(axios.get).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/widgets/calendar/17/events', + { params: { from: '2026-01-01', to: '2026-01-31' } }, + ) + expect(result).toEqual({ events, failures }) + }) + + it('sends an undefined window when called without arguments', async () => { + axios.get.mockResolvedValue({ data: {} }) + await fetchCalendarEvents('p1') + expect(axios.get).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/widgets/calendar/p1/events', + { params: { from: undefined, to: undefined } }, + ) + }) + + it('replaces non-array events and failures with empty lists', async () => { + axios.get.mockResolvedValueOnce({ data: { events: 'x', failures: { a: 1 } } }) + await expect(fetchCalendarEvents(1)).resolves.toEqual({ events: [], failures: [] }) + + axios.get.mockResolvedValueOnce(undefined) + await expect(fetchCalendarEvents(1)).resolves.toEqual({ events: [], failures: [] }) + }) + + it('rejects when the request fails', async () => { + axios.get.mockRejectedValue(new Error('503')) + await expect(fetchCalendarEvents(1)).rejects.toThrow('503') + }) +}) + +describe('buildWidgetDataProvide', () => { + it('wires the people and spend adapters to their functions', () => { + const provided = buildWidgetDataProvide(() => 1) + + expect(Object.keys(provided)).toEqual([ + 'cnPeopleSource', + 'cnCalendarSource', + 'cnSpendAnalyticsSource', + ]) + expect(typeof provided.cnPeopleSource.fetchPeople).toBe('function') + expect(provided.cnSpendAnalyticsSource).toEqual({ + fetchSummary: fetchFinanceSummary, + fetchVendorCommitments, + fetchNarrative: fetchSpendNarrative, + resolveDeepLink, + }) + }) + + it('reads the placement id at call time for calendar events', async () => { + let placementId = 'first' + const provided = buildWidgetDataProvide(() => placementId) + axios.get.mockResolvedValue({ data: { events: [], failures: [] } }) + + placementId = 'second' + await provided.cnCalendarSource.fetchEvents({ from: 'a', to: 'b' }) + + expect(axios.get).toHaveBeenCalledWith( + '/index.php/apps/launchpad/api/widgets/calendar/second/events', + { params: { from: 'a', to: 'b' } }, + ) + }) +}) + +describe('buildWidgetDataProvide people source', () => { + it('asks for no birthdates when the placement switches them off', async () => { + const provided = buildWidgetDataProvide(() => 1, () => ({ showBirthdays: false })) + axios.get.mockResolvedValue({ data: { users: [], total: 0, hasMore: false } }) + + await provided.cnPeopleSource.fetchPeople({ offset: 0, limit: 50 }) + + expect(axios.get.mock.calls[0][0]).toContain('showBirthdays=0') + }) + + it('asks for birthdates when the placement leaves the switch unset', async () => { + const provided = buildWidgetDataProvide(() => 1) + axios.get.mockResolvedValue({ data: { users: [], total: 0, hasMore: false } }) + + await provided.cnPeopleSource.fetchPeople({ offset: 0, limit: 50 }) + + expect(axios.get.mock.calls[0][0]).toContain('showBirthdays=1') + }) + + it('searches the whole directory with q, keeping the widget filters', async () => { + const provided = buildWidgetDataProvide(() => 1) + axios.get.mockResolvedValue({ data: { users: [{ uid: 'pieter' }], total: 1, hasMore: false } }) + const filters = [{ fieldName: 'group', operator: 'in', values: ['gw'] }] + + const page = await provided.cnPeopleSource.searchPeople({ q: 'subsidie', filters, offset: 0, limit: 50 }) + + const query = new URLSearchParams(axios.get.mock.calls[0][0].split('?')[1]) + expect(query.get('q')).toBe('subsidie') + expect(JSON.parse(query.get('filters'))).toEqual(filters) + expect(page.users).toEqual([{ uid: 'pieter' }]) + }) + + it('sends no q on a plain page request', async () => { + const provided = buildWidgetDataProvide(() => 1) + axios.get.mockResolvedValue({ data: { users: [], total: 0, hasMore: false } }) + + await provided.cnPeopleSource.fetchPeople({ offset: 0, limit: 50 }) + + expect(axios.get.mock.calls[0][0]).not.toContain('q=') + }) +}) + +describe('buildRendererExtraProps', () => { + it('gives the files widget its api base and others nothing', () => { + expect(buildRendererExtraProps('files')).toEqual({ apiBase: '/apps/launchpad' }) + expect(buildRendererExtraProps('news')).toEqual({}) + expect(buildRendererExtraProps(undefined)).toEqual({}) + }) +}) + +// @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 +describe('the new colleagues source', () => { + it('reads GET /api/people/new with the windows', async () => { + const { fetchNewPeople } = await import('../widgetDataAdapters.js') + axios.get.mockResolvedValue({ data: { configured: true, users: [{ id: 'yasmina' }] } }) + const answer = await fetchNewPeople({ since: 30, until: 14 }) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/people/new', { params: { since: 30, until: 14 } }) + expect(answer).toEqual({ configured: true, users: [{ id: 'yasmina' }] }) + }) + + it('is offered on every placement and to the forms outside one', async () => { + const { buildPeopleSource } = await import('../widgetDataAdapters.js') + const provided = buildWidgetDataProvide(() => 1) + expect(typeof provided.cnPeopleSource.fetchNewPeople).toBe('function') + expect(typeof provided.cnPeopleSource.hasStartDateField).toBe('function') + const source = buildPeopleSource() + expect(typeof source.fetchPeople).toBe('function') + expect(typeof source.hasStartDateField).toBe('function') + }) + + it('answers whether a start date field exists, asking once and again after a failure', async () => { + vi.resetModules() + const { hasStartDateField } = await import('../widgetDataAdapters.js') + axios.get.mockRejectedValueOnce(new Error('down')) + expect(await hasStartDateField()).toBe(false) + axios.get.mockResolvedValue({ data: { configured: true, users: [] } }) + expect(await hasStartDateField()).toBe(true) + expect(await hasStartDateField()).toBe(true) + expect(axios.get).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/services/__tests__/wikiPages.spec.js b/src/services/__tests__/wikiPages.spec.js new file mode 100644 index 000000000..5fd4639cf --- /dev/null +++ b/src/services/__tests__/wikiPages.spec.js @@ -0,0 +1,58 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The wiki pages service: what OpenRegister's XWiki search answers, and the + * favourites kept in the person's preference (wiki-widget REQ-WIKI-001..002). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { MAX_FAVOURITES, readWikiFavourites, saveWikiFavourites, searchWikiPages, wikiPage } from '../wikiPages.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn(), put: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) + +beforeEach(() => { + axios.get.mockReset() + axios.put.mockReset().mockResolvedValue({ data: {} }) +}) + +describe('wikiPages', () => { + it('searches through OpenRegister with the query and limit', async () => { + axios.get.mockResolvedValue({ data: { results: [{ reference: 'A.B', title: 'B', space: 'A', url: 'https://wiki/b' }, { title: 'no reference' }] } }) + expect(await searchWikiPages('kap', 5)).toEqual({ state: 'ok', pages: [{ reference: 'A.B', title: 'B', space: 'A', url: 'https://wiki/b' }] }) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/openregister/api/integrations/xwiki/search', { params: { q: 'kap', limit: 5 } }) + }) + + it('reads a 503 as not connected and any other failure as unavailable', async () => { + axios.get.mockRejectedValueOnce({ response: { status: 503 } }) + expect((await searchWikiPages('', 3)).state).toBe('not-connected') + axios.get.mockRejectedValueOnce({ response: { status: 404 } }) + expect((await searchWikiPages('', 3)).state).toBe('unavailable') + }) + + it('keeps only an http(s) page address and titles a page by its reference without a title', () => { + expect(wikiPage({ reference: 'X', url: 'javascript:alert(1)' })).toEqual({ reference: 'X', title: 'X', space: '', url: '' }) + expect(wikiPage({ id: 'Y', url: 'http://wiki/y' }).url).toBe('http://wiki/y') + }) + + it('reads the favourites from the preference, empty when there are none or they are broken', async () => { + axios.get.mockResolvedValueOnce({ data: { value: JSON.stringify([{ reference: 'A', title: 'A' }]) } }) + expect(await readWikiFavourites()).toEqual([{ reference: 'A', title: 'A', space: '', url: '' }]) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/preferences/wiki-favourites') + axios.get.mockResolvedValueOnce({ data: { value: '{broken' } }) + expect(await readWikiFavourites()).toEqual([]) + axios.get.mockResolvedValueOnce({ data: { value: null } }) + expect(await readWikiFavourites()).toEqual([]) + }) + + it('keeps at most the newest favourites', async () => { + const pages = Array.from({ length: MAX_FAVOURITES + 5 }, (_, i) => ({ reference: `P${i}`, title: `P${i}`, space: '', url: '', extra: true })) + const kept = await saveWikiFavourites(pages) + expect(kept).toHaveLength(MAX_FAVOURITES) + expect(kept[0]).toEqual({ reference: 'P0', title: 'P0', space: '', url: '' }) + const [, body] = axios.put.mock.calls[0] + expect(JSON.parse(body.value)).toEqual(kept) + }) +}) diff --git a/src/services/__tests__/workPackages.spec.js b/src/services/__tests__/workPackages.spec.js new file mode 100644 index 000000000..2da5193c4 --- /dev/null +++ b/src/services/__tests__/workPackages.spec.js @@ -0,0 +1,32 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The work packages client (work-packages-widget REQ-WP-001..002). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { loadWorkPackages } from '../workPackages.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) + +beforeEach(() => { + axios.get.mockReset() +}) + +describe('loadWorkPackages', () => { + it('asks launchpad with the scope, project and limit and makes the connect address absolute', async () => { + axios.get.mockResolvedValue({ data: { state: 'not-connected', workPackages: [], connectUrl: '/settings/user/openproject' } }) + expect(await loadWorkPackages({ scope: 'mine', project: '', limit: 4 })).toEqual({ state: 'not-connected', workPackages: [], connectUrl: '/index.php/settings/user/openproject' }) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/work-packages', { params: { scope: 'mine', project: '', limit: 4 } }) + }) + + it('reads a failed request or an odd answer as an error', async () => { + axios.get.mockRejectedValueOnce(new Error('500')) + expect((await loadWorkPackages({ scope: 'mine', project: '', limit: 4 })).state).toBe('error') + axios.get.mockResolvedValueOnce({ data: null }) + expect(await loadWorkPackages({ scope: 'mine', project: '', limit: 4 })).toEqual({ state: 'error', workPackages: [], connectUrl: '' }) + }) +}) diff --git a/src/services/activityReport.js b/src/services/activityReport.js new file mode 100644 index 000000000..f58bb3e1f --- /dev/null +++ b/src/services/activityReport.js @@ -0,0 +1,86 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * A person's activity as counts per type and per day, with the purpose the + * administrator recorded (openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them + * REQ-DWMS-005 and REQ-DWMS-006). + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +const REPORT_URL = '/apps/launchpad/api/activity-report' + +/** + * The query the report and its CSV share: an empty user means the reader. + * + * @param {object} request the request + * @param {string} request.user the person reported on, empty for yourself + * @param {string} request.from first day, YYYY-MM-DD + * @param {string} request.to last day, YYYY-MM-DD + * @return {object} the query parameters + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 + */ +function queryOf({ user, from, to }) { + const params = {} + if (typeof user === 'string' && user.trim() !== '') { + params.user = user.trim() + } + if (from) { + params.from = from + } + if (to) { + params.to = to + } + return params +} + +/** + * Load the report. A refusal is an answer, not an error: it comes back as + * `{ refused: true, message, enabled }` so the screen can say why. + * + * @param {object} request the request, as for queryOf + * @return {Promise<object>} the report, or the refusal + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.2 + */ +export async function loadActivityReport(request) { + try { + const { data } = await axios.get(generateUrl(REPORT_URL), { params: queryOf(request) }) + return { + refused: false, + subject: String(data?.subject ?? ''), + self: data?.self === true, + from: String(data?.from ?? ''), + to: String(data?.to ?? ''), + purpose: typeof data?.purpose === 'string' && data.purpose !== '' ? data.purpose : null, + available: data?.available === true, + counts: data?.counts && typeof data.counts === 'object' && !Array.isArray(data.counts) ? data.counts : {}, + days: data?.days && typeof data.days === 'object' && !Array.isArray(data.days) ? data.days : {}, + total: Number(data?.total) || 0, + } + } catch (error) { + const status = error?.response?.status + if (status === 400 || status === 403) { + return { + refused: true, + status, + message: String(error.response.data?.error ?? ''), + enabled: error.response.data?.activityReportingEnabled === true, + } + } + throw error + } +} + +/** + * The CSV of the same report, for a download link. + * + * @param {object} request the request, as for queryOf + * @return {string} the URL + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-4.6 + */ +export function activityReportCsvUrl(request) { + const query = new URLSearchParams(queryOf(request)).toString() + return generateUrl(REPORT_URL + '/export') + (query === '' ? '' : '?' + query) +} diff --git a/src/services/announcementsApi.js b/src/services/announcementsApi.js new file mode 100644 index 000000000..b10661125 --- /dev/null +++ b/src/services/announcementsApi.js @@ -0,0 +1,151 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Client for the announcements API (engagement-announcements): the list a + * reader sees, likes and comments, followed categories, authoring with the + * preview's reach count, and the notices a reader dismissed, kept in the + * per-user preference `dismissed-notices`. + * + * @spec openspec/changes/engagement-announcements/specs/announcements/spec.md + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +const base = () => generateUrl('/apps/launchpad/api/announcements') +const DISMISSED_KEY = 'dismissed-notices' + +export const announcementsApi = { + /** @return {Promise<object>} `{announcements, drafts, followedCategories, canAuthor, reactions}`. */ + async list() { + const { data } = await axios.get(base()) + return data + }, + + /** @param {string} uuid The announcement. @return {Promise<object>} `{likes, liked}`. */ + async like(uuid) { + return (await axios.post(`${base()}/${uuid}/like`)).data + }, + + /** @param {string} uuid The announcement. @return {Promise<object>} `{likes, liked}`. */ + async unlike(uuid) { + return (await axios.delete(`${base()}/${uuid}/like`)).data + }, + + /** @param {string} uuid The announcement. @return {Promise<Array>} The comments, oldest first. */ + async comments(uuid) { + return (await axios.get(`${base()}/${uuid}/comments`)).data.comments ?? [] + }, + + /** + * @param {string} uuid The announcement. @param {string} message The text. @return {Promise<object>} The new comment. + * @param message + */ + async comment(uuid, message) { + return (await axios.post(`${base()}/${uuid}/comments`, { message })).data + }, + + /** @param {string} category The category. @return {Promise<Array<string>>} The followed categories. */ + async follow(category) { + return (await axios.post(`${base()}/follows`, { category })).data.followedCategories ?? [] + }, + + /** @param {string} category The category. @return {Promise<Array<string>>} The followed categories. */ + async unfollow(category) { + return (await axios.delete(`${base()}/follows/${encodeURIComponent(category)}`)).data.followedCategories ?? [] + }, + + /** @param {object} input The author fields. @return {Promise<object>} The draft. */ + async create(input) { + return (await axios.post(base(), input)).data + }, + + /** + * @param {string} uuid The announcement. @param {object} input The author fields. @return {Promise<object>} The announcement. + * @param input + */ + async update(uuid, input) { + return (await axios.put(`${base()}/${uuid}`, input)).data + }, + + /** @param {string} uuid The announcement. @return {Promise<object>} The published announcement. */ + async publish(uuid) { + return (await axios.post(`${base()}/${uuid}/publish`)).data + }, + + /** + * The groups the announcement form offers as the target group. + * + * @return {Promise<Array<object>>} `{id, displayName}`, sorted by name. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-the-announcement-form-as-lpaankondiging-draws-it-req-ann-006 + */ + /** + * Which announcements the reader confirmed, and which read + * confirmations the reader may open (REQ-ANN-007). + * + * @return {Promise<{confirmed: Array<string>, receipts: Array<string>}>} + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + async readState() { + return (await axios.get(`${base()}/read-state`)).data + }, + + /** + * "I have read this" for the signed-in reader (REQ-ANN-007). + * + * @param {string} uuid The announcement. + * @return {Promise<object>} `{uuid, confirmed, confirmedAt}`. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + async confirmRead(uuid) { + return (await axios.post(`${base()}/${uuid}/read`)).data + }, + + /** + * Who confirmed and who has not yet, for the author (REQ-ANN-007). + * + * @param {string} uuid The announcement. + * @return {Promise<object>} The report the Read confirmations dialog shows. + * @spec openspec/changes/archive/2026-11-24-announcement-form-board-sync/specs/announcements/spec.md#requirement-an-announcement-asks-for-a-read-confirmation-req-ann-007 + */ + async receipts(uuid) { + return (await axios.get(`${base()}/${uuid}/receipts`)).data + }, + + async groups() { + return (await axios.get(`${base()}/groups`)).data.groups ?? [] + }, + + /** @param {Array<string>} groups The target groups. @return {Promise<number>} How many people they reach. */ + async reach(groups) { + return (await axios.get(`${base()}/reach`, { params: { groups } })).data.reach ?? 0 + }, + + /** + * "Preview as": the reach and whether the targeting reaches one person. + * + * @param {Array<string>} groups The target groups. + * @param {string} user The person. + * @return {Promise<object>} `{reach, reachesUser}`. + */ + async reachFor(groups, user) { + return (await axios.get(`${base()}/reach`, { params: { groups, user } })).data + }, + + /** @return {Promise<Array<string>>} The uuids of the notices this reader dismissed. */ + async dismissedNotices() { + const { data } = await axios.get(generateUrl(`/apps/launchpad/api/preferences/${DISMISSED_KEY}`)) + try { + const parsed = JSON.parse(data?.value ?? '[]') + return Array.isArray(parsed) ? parsed.filter((uuid) => typeof uuid === 'string') : [] + } catch { + return [] + } + }, + + /** @param {Array<string>} uuids The dismissed notices to store. @return {Promise<void>} */ + async saveDismissedNotices(uuids) { + await axios.put(generateUrl(`/apps/launchpad/api/preferences/${DISMISSED_KEY}`), { value: JSON.stringify(uuids) }) + }, +} diff --git a/src/services/api.js b/src/services/api.js index bb793cdc1..899b60c59 100644 --- a/src/services/api.js +++ b/src/services/api.js @@ -285,6 +285,36 @@ export const api = { ) }, + /** + * Announce or renew editing a dashboard; resolves to + * `{editors: [{displayName, since}]}`, the colleagues editing it. + * + * @param {string} uuid UUID of the dashboard. + * @return {Promise} Axios response. + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ + joinPresence(uuid) { + return axios.post( + `${baseUrl}/api/dashboards/${encodeURIComponent(uuid)}/presence`, + ) + }, + + /** + * Stop editing a dashboard. With `onPageHide` the request survives the + * page closing (fetch adapter with `keepalive`). + * + * @param {string} uuid UUID of the dashboard. + * @param {boolean} [onPageHide] Whether the page is closing. + * @return {Promise} Axios response (204). + * @spec openspec/changes/archive/2026-11-19-building-edit-a-dashboard-together/tasks.md#task-1.1 + */ + leavePresence(uuid, onPageHide = false) { + return axios.delete( + `${baseUrl}/api/dashboards/${encodeURIComponent(uuid)}/presence`, + onPageHide ? { adapter: 'fetch', fetchOptions: { keepalive: true } } : undefined, + ) + }, + /** * Force-release another person's lock; administrators only (REQ-LOCK-005). * @@ -660,6 +690,71 @@ export const api = { return axios.post(`${baseUrl}/api/dashboard/${dashboardId}/tile`, data) }, + /** + * Import chosen browser bookmarks onto a dashboard as containers and tiles. + * + * @param {number|string} dashboardId Numeric id of the target dashboard. + * @param {{folders: Array<object>, bookmarks: Array<object>}} data The chosen folders and loose bookmarks. + * @return {Promise} Axios response with `{placements, skipped}`; 409 when the import does not fit the quota. + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md + */ + importBookmarks(dashboardId, data) { + return axios.post(`${baseUrl}/api/dashboard/${dashboardId}/tiles/import`, data) + }, + + /** + * The apps this server runs for the current user, to place as tiles. + * + * @return {Promise} Axios response resolving to `{ apps: [{ appId, name, href, icon }] }`. + * @spec openspec/changes/archive/2026-11-19-launcher-discover-server-services/specs/tiles/spec.md#requirement-the-add-flow-lists-the-apps-this-server-runs-for-the-user-req-disc-001 + */ + discoverApps() { + return axios.get(`${baseUrl}/api/tiles/discover`) + }, + + /** + * The app catalogue entries the current user's groups may see. + * + * @return {Promise} Axios response resolving to `{ apps: [{ uuid, name, description, icon, iconType, linkType, linkValue }] }`. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-users-add-catalogue-apps-as-tiles-from-the-add-flow-req-acat-002 + */ + catalogueApps() { + return axios.get(`${baseUrl}/api/catalogue`) + }, + + /** + * Ask IT for an app the catalogue lacks. + * + * @param {{appName: string, purpose: string}} request The app and what it is needed for. + * @return {Promise} Axios response resolving to `{ request }`; a 429 carries `code: 'request_limit'`. + * @spec openspec/changes/archive/2026-11-19-launcher-app-catalogue/specs/app-catalogue/spec.md#requirement-users-can-ask-for-a-missing-app-req-acat-003 + */ + requestCatalogueApp(request) { + return axios.post(`${baseUrl}/api/catalogue/requests`, request) + }, + + /** + * The office tile pack for the current user: a "New ..." tile per file + * creator the server's office apps register, and the enabled office apps. + * + * @return {Promise} Axios response resolving to `{ tiles: [{ title, linkType, linkValue, icon, iconType }] }`. + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-the-add-flow-offers-an-office-tile-pack-built-from-what-the-server-has-req-oft-001 + */ + officeTilePack() { + return axios.get(`${baseUrl}/api/office-tiles`) + }, + + /** + * Create a file from an office app's blank template under a free name. + * + * @param {{creatorId: string, name: string, folder: string}} request The creator, the name without extension and the folder. + * @return {Promise} Axios response resolving to `{ fileId, path, url }`. + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md#requirement-a-new-tile-creates-a-real-document-and-never-overwrites-req-oft-002 + */ + createOfficeFile(request) { + return axios.post(`${baseUrl}/api/office-tiles/create`, request) + }, + /** * Update an existing widget placement. * @@ -769,6 +864,44 @@ export const api = { return axios.get(`${baseUrl}/api/admin/templates`) }, + /** + * List the templates LaunchPad ships with, and whether each is installed. + * + * @return {Promise} Axios response resolving to the shipped templates. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + getShippedTemplates() { + return axios.get(`${baseUrl}/api/admin/templates/shipped`) + }, + + /** + * Add a shipped template as an admin template. + * + * @param {string} id Shipped template id, for example `mijn-werkdag`. + * @return {Promise} Axios response resolving to the installed template. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-018 + */ + installShippedTemplate(id) { + return axios.post(`${baseUrl}/api/admin/templates/shipped/${id}/install`) + }, + + /** + * Update an installed shipped template to the version LaunchPad ships + * now, in place. With `dryRun` the server only reports what would change. + * + * @param {string} id Shipped template id, for example `mijn-werkdag`. + * @param {object} [options] Call options. + * @param {boolean} [options.dryRun] Report the changes, write nothing. + * @return {Promise} Axios response resolving to the widgets added, + * removed and changed. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-020 + */ + updateShippedTemplate(id, { dryRun = false } = {}) { + return axios.post(`${baseUrl}/api/admin/templates/shipped/${id}/update`, { + dryRun, + }) + }, + /** * Create an admin dashboard template. * @@ -826,6 +959,76 @@ export const api = { return axios.get(`${baseUrl}/api/admin/settings`) }, + /** + * Read the public start page: whether it is on, the chosen link, whether + * it can be shown and why not, and the links that may be chosen. + * Admin-only on the server (sharing-public-start-page REQ-PSP-001). + * + * @return {Promise} Axios response resolving to + * `{ enabled, token, active, reason, candidates }`. + */ + getPublicStart() { + return axios.get(`${baseUrl}/api/admin/public-start`) + }, + + /** + * Choose the public start page's link and switch it on or off. Admin-only + * on the server; a link with a password or a past expiry answers 400 + * (sharing-public-start-page REQ-PSP-001). + * + * @param {{enabled: boolean, token: string}} data The choice. + * @return {Promise} The axios response, the new status. + */ + updatePublicStart(data) { + return axios.put(`${baseUrl}/api/admin/public-start`, data) + }, + + /** + * Read the external hosts image widgets may load pictures from. + * Admin-only on the server (REQ-IMG-006). + * + * @return {Promise} Axios response resolving to `{ hosts }`. + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + */ + getImageHosts() { + return axios.get(`${baseUrl}/api/admin/image-hosts`) + }, + + /** + * Replace the image host allow-list. Admin-only on the server; an entry + * that is not a bare host name answers 400 with `{ message }` (REQ-IMG-006). + * + * @param {string[]} hosts The host names. + * @return {Promise} Axios response resolving to the stored `{ hosts }`. + * @spec openspec/specs/image-widget/spec.md#requirement-req-img-006-external-image-hosts-are-allow-listed-by-an-administrator + */ + updateImageHosts(hosts) { + return axios.put(`${baseUrl}/api/admin/image-hosts`, { hosts }) + }, + + /** + * Read the allowed websites, each `{host, embed, fetch}`. Admin-only on + * the server (REQ-ASET-021). + * + * @return {Promise} Axios response resolving to `{ sites }`. + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + getAllowedSites() { + return axios.get(`${baseUrl}/api/admin/allowed-sites`) + }, + + /** + * Replace the allowed websites. Admin-only on the server; an entry that is + * not a host, or has no purpose, answers 400 with `{ message }` (REQ-ASET-021). + * + * @param {Array<{host: string, embed: boolean, fetch: boolean}>} sites The sites. + * @return {Promise} Axios response resolving to the stored `{ sites }`. + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + updateAllowedSites(sites) { + return axios.put(`${baseUrl}/api/admin/allowed-sites`, { sites }) + }, + /** * Read the dashboard registry connection. Admin-only on the server. * @@ -864,6 +1067,51 @@ export const api = { return axios.put(`${baseUrl}/api/admin/settings`, data) }, + /** + * Set who may share (`everyone`, `groups`, `none`) and whether public + * links may be created. Admin-only on the server; a partial patch. + * + * @param {{sharingAllowed?: string, publicLinksAllowed?: boolean}} data The policy fields to change. + * @return {Promise} The axios response. + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-can-stop-sharing-and-limit-public-links-req-share-015 + */ + updateSharingPolicy(data) { + return axios.put(`${baseUrl}/api/admin/sharing-policy`, data) + }, + + /** + * Set where a leaver's dashboards go: their manager or not, and the person + * otherwise ('' for nobody). Admin-only on the server. + * + * @param {{manager: boolean, fallbackUid: string}} data The handover. + * @return {Promise} The axios response. + * @spec openspec/changes/archive/2026-11-25-sharing-policy-board-sync/specs/dashboard-sharing/spec.md#requirement-administrators-choose-where-a-leavers-dashboards-go-req-share-016 + */ + updateLeaverHandover(data) { + return axios.put(`${baseUrl}/api/admin/leaver-handover`, data) + }, + + /** + * Read the administrator CSS for all of LaunchPad. Admin-only on the server. + * + * @return {Promise} Axios response resolving to `{ customCss }`. + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + getCustomCss() { + return axios.get(`${baseUrl}/api/admin/custom-css`) + }, + + /** + * Save the administrator CSS for all of LaunchPad; the server cleans and scopes it. + * + * @param {string} customCss The CSS; '' clears it. + * @return {Promise} Axios response resolving to `{ customCss, removed }`. + * @spec openspec/changes/archive/2026-11-19-platform-dashboard-theme-and-css/specs/dashboards/spec.md#requirement-administrators-add-custom-css-cleaned-and-scoped-req-thm-003 + */ + updateCustomCss(customCss) { + return axios.put(`${baseUrl}/api/admin/custom-css`, { customCss }) + }, + // Admin group-priority order (REQ-ASET-012/013/014). // Both endpoints are admin-only on the server side; the UI gates // rendering of the section behind the same admin check. @@ -914,17 +1162,6 @@ export const api = { return axios.post(`${baseUrl}/api/admin/setup-wizard/complete`) }, - /** - * Persist the setup wizard's content-storage choice (REQ-WIZ-003). - * - * @param {string} storage Backend to store widget content in — - * `database` or `groupfolder`. - * @return {Promise} Axios response resolving to the updated wizard state. - */ - setSetupWizardStorage(storage) { - return axios.post(`${baseUrl}/api/admin/setup-wizard/storage`, { storage }) - }, - /** * Export dashboards as a downloadable archive (REQ-EXIM-002..004). * Requires Nextcloud-admin, gated server-side; the admin UI renders the @@ -1353,6 +1590,17 @@ export const api = { ) }, + /** + * Give a Nextcloud group the LaunchPad admin role (REQ-WIZ-006). Admin-only. + * + * @param {string} groupId The group id. + * @return {Promise} Axios response resolving to the created assignment. + * @spec openspec/specs/setup-wizard/spec.md#req-wiz-006 + */ + assignAdminRoleToGroup(groupId) { + return axios.post(`${baseUrl}/api/admin/roles`, { groupId, role: 'admin' }) + }, + // Tile endpoints getTiles() { return axios.get(`${baseUrl}/api/tiles`) diff --git a/src/services/assignedCases.js b/src/services/assignedCases.js new file mode 100644 index 000000000..bad722e3c --- /dev/null +++ b/src/services/assignedCases.js @@ -0,0 +1,129 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The open cases assigned to the viewer, read from an OpenRegister register + * (dossiq's `dossiq` register and `case` schema by default) with the viewer's + * own session, so OpenRegister decides which cases they may see. + * + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +/** How many open cases one read takes in, for the counts per status. */ +export const READ_LIMIT = 100 + +/** The status colours of a case type, as status pill variants. */ +const COLOUR_VARIANTS = { + blue: 'primary', + 'blue-light': 'info', + green: 'success', + 'green-light': 'success', + orange: 'warning', + 'orange-light': 'warning', + red: 'error', + 'red-light': 'error', + purple: 'purple', + 'purple-light': 'purple', + teal: 'teal', + 'teal-light': 'teal', + grey: 'default', + 'grey-light': 'default', +} + +/** + * The first of some values that is a non-empty string, as a string. + * + * @param {...unknown} values The candidates. + * @return {string} The value, '' for none. + */ +function firstText(...values) { + const found = values.find((value) => typeof value === 'string' && value !== '') + return found === undefined ? '' : found +} + +/** + * A case's status: its name and pill variant, from the extended status + * object or the case's own public label. + * + * @param {object} record The case. + * @return {{key: string, label: string, variant: string}} + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-counts-the-open-cases-per-status-req-cases-002 + */ +export function caseStatus(record) { + const status = record?.status + if (status && typeof status === 'object') { + const label = firstText(status.name, status.publicLabel) + return { + key: firstText(status.id, status.uuid, status['@self']?.id, label), + label, + variant: COLOUR_VARIANTS[status.colour] || 'default', + } + } + const label = firstText(record?.statusPublicLabel) + return { key: firstText(status, label), label, variant: 'default' } +} + +/** + * One case as the widget shows it. + * + * @param {object} record The case. + * @return {{id: string, title: string, identifier: string, deadline: string, status: object}} + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-lists-the-viewers-open-cases-deadline-first-req-cases-001 + */ +export function caseItem(record) { + return { + id: firstText(record.id, record.uuid, record['@self']?.id), + title: firstText(record.title, record.identifier), + identifier: firstText(record.identifier), + deadline: firstText(record.deadline, record.statutoryDeadline), + status: caseStatus(record), + } +} + +/** + * The counts per status over cases. + * + * @param {Array<object>} cases The cases, as {@link caseItem} gives them. + * @return {Array<{key: string, label: string, variant: string, count: number}>} + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-counts-the-open-cases-per-status-req-cases-002 + */ +export function countsPerStatus(cases) { + const counts = new Map() + for (const { status } of cases) { + if (status.label !== '') { + const entry = counts.get(status.key) || { key: status.key, label: status.label, variant: status.variant, count: 0 } + entry.count++ + counts.set(status.key, entry) + } + } + return [...counts.values()] +} + +/** + * Read the open cases assigned to a person, deadline first, with the counts + * per status over them. + * + * @param {{register: string, schema: string, userId: string}} query Where to read and for whom. + * @return {Promise<{state: string, cases: Array<object>, counts: Array<object>, total: number}>} + * `state` is `ok` or `error`. + * @spec openspec/changes/assigned-cases-widget/specs/assigned-cases-widget/spec.md#requirement-the-widget-lists-the-viewers-open-cases-deadline-first-req-cases-001 + */ +export async function loadAssignedCases({ register, schema, userId }) { + try { + const url = generateUrl('/apps/openregister/api/objects/{register}/{schema}', { register, schema }) + const { data } = await axios.get(url, { + params: { assignee: userId, '_order[deadline]': 'asc', '_extend[]': 'status', _limit: READ_LIMIT }, + }) + const records = Array.isArray(data?.results) ? data.results : [] + const cases = records + .filter((record) => record && record.isFinalStatus !== true) + .map(caseItem) + .filter((entry) => entry.id !== '' && entry.title !== '') + return { state: 'ok', cases, counts: countsPerStatus(cases), total: cases.length } + } catch { + return { state: 'error', cases: [], counts: [], total: 0 } + } +} diff --git a/src/services/attentionFeed.js b/src/services/attentionFeed.js new file mode 100644 index 000000000..8055b339b --- /dev/null +++ b/src/services/attentionFeed.js @@ -0,0 +1,313 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The attention feed's browser half (openspec/specs/attention-feed). Pure + * functions plus one loader: no component state lives here, so every rule can + * be tested without mounting anything. + * + * A source is what an app declared in its `appinfo/attention.json`, as + * `GET /api/attention/sources` returns it. For each one the feed asks + * OpenRegister for a count as the signed-in user, decides whether it needs + * attention, and builds the link into the app FROM THE SAME FILTER, so the + * number and the list it opens cannot drift (REQ-ATT-003). + * + * A count that cannot run is a FAILED entry. It is never a zero: a zero says + * "nothing to do", and that is the one thing a failure must not say + * (REQ-ATT-005). + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +/** Most urgent first. */ +export const SEVERITIES = ['error', 'warning', 'info'] + +const DAY_TOKEN = /^@today([+-])(\d+)d$/ + +/** + * Format a date as local `YYYY-MM-DD`. + * + * @param {Date} date The date. + * @return {string} The date-only string. + */ +function ymd(date) { + const month = String(date.getMonth() + 1).padStart(2, '0') + const day = String(date.getDate()).padStart(2, '0') + return `${date.getFullYear()}-${month}-${day}` +} + +/** + * Resolve one filter value. A value that starts with `@` MUST be a token this + * function knows; anything else throws, so an unknown token fails its source + * instead of being sent to OpenRegister as a literal (REQ-ATT-003). + * + * @param {unknown} value The filter value. + * @param {{userId: string, now: Date}} ctx Who asks, and when. + * @return {unknown} The resolved value. + * @spec openspec/specs/attention-feed/spec.md#req-att-003 + */ +export function resolveToken(value, ctx) { + if (typeof value !== 'string' || value.charAt(0) !== '@') { + return value + } + const now = ctx.now + if (value === '@me') { + if (!ctx.userId) { + throw new Error('@me needs a signed-in user') + } + return ctx.userId + } + if (value === '@now') { + return now.toISOString() + } + if (value === '@today') { + return ymd(now) + } + const delta = DAY_TOKEN.exec(value) + if (delta) { + const days = Number(delta[2]) * (delta[1] === '-' ? -1 : 1) + return ymd(new Date(now.getFullYear(), now.getMonth(), now.getDate() + days)) + } + if (value === '@monthStart') { + return ymd(new Date(now.getFullYear(), now.getMonth(), 1)) + } + if (value === '@quarterStart') { + return ymd( + new Date(now.getFullYear(), Math.floor(now.getMonth() / 3) * 3, 1), + ) + } + if (value === '@yearStart') { + return ymd(new Date(now.getFullYear(), 0, 1)) + } + throw new Error(`unknown token ${value}`) +} + +/** + * Write a flat filter as query pairs, in the filter's own key order. A list + * becomes repeated `key[]` pairs, the form OpenRegister reads as an IN-list. + * `resolve` is applied to every value: the count passes the token resolver, + * the link passes nothing. + * + * @param {object} filter The declared filter. + * @param {(value: unknown) => unknown} [resolve] Maps each value before it is written. + * @return {Array<[string, string]>} The pairs. + * @spec openspec/specs/attention-feed/spec.md#req-att-003 + */ +export function filterPairs(filter, resolve = (value) => value) { + const pairs = [] + for (const [key, value] of Object.entries(filter || {})) { + if (Array.isArray(value)) { + for (const entry of value) { + pairs.push([`${key}[]`, String(resolve(entry))]) + } + } else { + pairs.push([key, String(resolve(value))]) + } + } + return pairs +} + +/** + * Join pairs into a query string. Brackets in keys and `@` in values stay + * readable (`deadline[lt]=@today%2B1d`); everything else is percent-encoded, + * `+` included, because a bare `+` in a query reads as a space. + * + * @param {Array<[string, string]>} pairs The pairs. + * @return {string} `a=b&c=d`, or an empty string. + * @spec openspec/specs/attention-feed/spec.md#req-att-003 + */ +export function toQuery(pairs) { + return pairs + .map( + ([key, value]) => + `${encodeURIComponent(key).replace(/%5B/g, '[').replace(/%5D/g, ']')}=${encodeURIComponent(value).replace(/%40/g, '@')}`, + ) + .join('&') +} + +/** + * The OpenRegister request that counts a source, tokens resolved. + * + * @param {object} source A source from the sources endpoint. + * @param {{userId: string, now: Date}} ctx Who asks, and when. + * @return {string} App-relative URL, before `generateUrl`. + * @spec openspec/specs/attention-feed/spec.md#req-att-003 + */ +export function countPath(source, ctx) { + const { register, schema, filter } = source.source + const pairs = filterPairs(filter, (value) => resolveToken(value, ctx)) + pairs.push(['_limit', String(Math.max(1, Number(ctx?.perSource) || 1))]) + return `/apps/openregister/api/objects/${encodeURIComponent(register)}/${encodeURIComponent(schema)}?${toQuery(pairs)}` +} + +/** + * The link into the owning app: the declared path with the SAME filter as its + * query, tokens left as written, which is what the apps' own links carry. + * + * @param {object} source A source from the sources endpoint. + * @return {string} App-relative URL, before `generateUrl`. + * @spec openspec/specs/attention-feed/spec.md#req-att-003 + */ +export function actionPath(source) { + const query = toQuery(filterPairs(source.source.filter)) + return query === '' ? source.action.path : `${source.action.path}?${query}` +} + +/** The rule operators a source may declare, each comparing count to value. */ +const OPERATORS = { + gt: (count, value) => count > value, + gte: (count, value) => count >= value, + lt: (count, value) => value > count, + lte: (count, value) => value >= count, + eq: (count, value) => count === value, + neq: (count, value) => count !== value, +} + +/** + * Whether a count needs attention under the source's rule. + * + * @param {number} count The count. + * @param {string} op `gt`, `gte`, `lt`, `lte`, `eq` or `neq`. + * @param {number} value The right-hand side. + * @return {boolean} True when the item should be shown. + * @spec openspec/specs/attention-feed/spec.md#req-att-004 + */ +export function needsAttention(count, op, value) { + if (!Object.hasOwn(OPERATORS, op)) { + throw new Error(`unknown operator ${op}`) + } + return OPERATORS[op](count, value) +} + +/** + * Order the entries that need attention: severity, then the higher count, + * then app name, then item id, so the order is stable. + * + * @param {Array<object>} entries Entries with `severity`, `count`, `appName`, `id`. + * @return {Array<object>} A sorted copy. + * @spec openspec/specs/attention-feed/spec.md#req-att-004 + */ +export function rank(entries) { + return [...entries].sort( + (a, b) => + SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity) + || b.count - a.count + || a.appName.localeCompare(b.appName) + || a.id.localeCompare(b.id), + ) +} + +/** + * Count one source. Resolves to an entry that is either checked (`count`, + * `attention`) or failed (`failed: true`). It never rejects, so one source + * cannot take the others down, and it never turns a failure into a zero. + * + * @param {object} source A source from the sources endpoint. + * @param {{userId: string, now: Date}} ctx Who asks, and when. + * @return {Promise<object>} The entry. + * @spec openspec/specs/attention-feed/spec.md#req-att-005 + */ +export async function checkSource(source, ctx) { + const entry = { + key: `${source.appId}/${source.id}`, + id: source.id, + appId: source.appId, + appName: source.appName, + title: source.title, + severity: source.severity, + actionLabel: source.action.label, + href: generateUrl(actionPath(source)), + } + try { + const { data } = await axios.get(generateUrl(countPath(source, ctx))) + const total = data?.total + if (typeof total !== 'number' || !Number.isFinite(total)) { + throw new Error('the answer has no numeric total') + } + return { + ...entry, + failed: false, + count: total, + attention: needsAttention(total, source.op, source.value), + reason: source.reason.replace(/\{value\}/g, String(total)), + objects: Array.isArray(data?.results) ? data.results : [], + itemPath: source.action.path, + schema: source.source.schema, + } + } catch (error) { + return { ...entry, failed: true, error: error?.message || String(error) } + } +} + +/** + * One card per record instead of one per source (LpVandaag "Vandaag eerst": + * "Parkeervergunningen binnenstad … Zaak openen"): each record a source + * counted becomes its own item, named by the record, with the source's title + * as its reason and a link to the record. A source whose answer listed no + * records stays one item. + * + * @param {Array<object>} entries Ranked entries that need attention. + * @param {function(string, object): string} label Names the action, given the schema, when the source names none. + * @return {Array<object>} The items. + * @spec openspec/specs/attention-feed/spec.md#req-att-004 + * @spec openspec/changes/archive/2026-11-24-start-page-board-sync/specs/attention-feed/spec.md#requirement-vandaag-eerst-can-draw-one-card-per-record-req-att-007 + */ +export function expandToRecords(entries, label) { + const items = [] + for (const entry of entries) { + const records = (entry.objects || []).filter((record) => record && (record.id || record.uuid)) + if (records.length === 0) { + items.push(entry) + continue + } + for (const record of records) { + const id = String(record.id || record.uuid) + items.push({ + ...entry, + key: `${entry.key}/${id}`, + id: `${entry.id}/${id}`, + title: String(record.title || record.name || id), + reason: entry.title, + // The source's own action ("Zaak openen") first (REQ-ATT-007). + actionLabel: entry.actionLabel || label(entry.schema, record), + href: generateUrl(`${entry.itemPath}/${encodeURIComponent(id)}`), + }) + } + } + return items +} + +/** + * Load the whole feed: the declared sources, each one counted. + * + * Rejects only when the sources endpoint itself fails; the widget then says + * the list could not be loaded. + * + * @param {{now?: Date, perSource?: number}} [ctx] When (default now), and how many records to list per source (default 1, only counted). Who asks comes from the endpoint. + * @return {Promise<{items: Array<object>, failedApps: Array<string>, sourceCount: number}>} The ranked items that need attention, the names of apps whose count failed or whose declaration is invalid, and how many sources were declared. + * @spec openspec/specs/attention-feed/spec.md#req-att-005 + */ +export async function loadAttentionFeed(ctx = {}) { + const { data } = await axios.get( + generateUrl('/apps/launchpad/api/attention/sources'), + ) + const context = { userId: data?.userId || '', now: ctx.now || new Date(), perSource: ctx.perSource || 1 } + const sources = Array.isArray(data?.sources) ? data.sources : [] + const invalid = Array.isArray(data?.invalid) ? data.invalid : [] + + const entries = await Promise.all( + sources.map((source) => checkSource(source, context)), + ) + + const failedApps = [ + ...entries.filter((entry) => entry.failed).map((entry) => entry.appName), + ...invalid.map((entry) => entry.appName || entry.appId), + ] + + return { + items: rank(entries.filter((entry) => !entry.failed && entry.attention)), + failedApps: [...new Set(failedApps)].sort((a, b) => a.localeCompare(b)), + sourceCount: sources.length + invalid.length, + } +} diff --git a/src/services/colleagueActivity.js b/src/services/colleagueActivity.js new file mode 100644 index 000000000..507fbbb4f --- /dev/null +++ b/src/services/colleagueActivity.js @@ -0,0 +1,33 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Recent colleague activity, as the server filtered it for the reader + * (openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them REQ-DWMS-007). + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +/** + * Load what other people did recently that the signed-in user may see. + * + * @param {object} options the request + * @param {number} options.limit how many entries to list + * @param {number} options.days how many days back + * @return {Promise<{available: boolean, days: number, entries: Array<object>, total: number, counts: object, actors: number}>} + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-5.1 + */ +export async function loadColleagueActivity({ limit, days }) { + const { data } = await axios.get(generateUrl('/apps/launchpad/api/colleague-activity'), { + params: { limit, days }, + }) + return { + available: data?.available === true, + days: Number(data?.days) || days, + entries: Array.isArray(data?.entries) ? data.entries : [], + total: Number(data?.total) || 0, + counts: data?.counts && typeof data.counts === 'object' ? data.counts : {}, + actors: Number(data?.actors) || 0, + } +} diff --git a/src/services/dashboardConnections.js b/src/services/dashboardConnections.js new file mode 100644 index 000000000..0de01cc0b --- /dev/null +++ b/src/services/dashboardConnections.js @@ -0,0 +1,129 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The connections one dashboard uses, with the state integriq holds for each + * (REQ-LP-CONN-005, board LpManagement "Koppelingen van dit dashboard"). + * + * Which widget type uses which declared connection is configuration + * (lib/Settings/connection-uses.json, next to connections.json), not code per + * widget type. The states are integriq's `app_connection` rows for this app, + * read through OpenRegister with the viewer's own session; nothing here ever + * calls a connection itself. + */ + +import { formatConnectionStatus } from '@conduction/nextcloud-vue/dist/esm/utils/builtInFormatters.js' +import connectionUses from '../../lib/Settings/connection-uses.json' +import declarations from '../../lib/Settings/connections.json' +import { fetchAppConnectionRows, lastSuccessOf } from './liveTileConnections.js' + +/** Statuses integriq stores for a connection whose last check failed. */ +const ERROR_STATUSES = Object.freeze(['error', 'failed']) + +/** + * Whether a placement is a launcher tile with its health ping switched on. + * + * @param {object} placement A placement row. + * @return {boolean} true for a tile that pings its service. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +function isPingingTile(placement) { + const id = String(placement?.widgetId ?? '') + const tile = id === 'tile' || id === 'app-tile' || id.startsWith('tile-') || Boolean(placement?.tileType) + return tile && placement?.content?.healthPingEnabled === true +} + +/** + * The declared connections the placements use, once each, in declared order. + * A connection no placement uses is left out. + * + * @param {Array<object>} placements The dashboard's placements. + * @param {{connections: Array<object>}} [declared] The connections.json declaration. + * @param {{connections: Record<string, {uses?: string[], healthPingTiles?: boolean}>}} [uses] The uses map. + * @return {Array<{key: string, title: string, order: number}>} The connections in use. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +export function connectionsUsedBy(placements, declared = declarations, uses = connectionUses) { + const list = Array.isArray(placements) ? placements : [] + const types = new Set(list.map((placement) => String(placement?.widgetId ?? ''))) + const pinging = list.some(isPingingTile) + const map = uses?.connections ?? {} + return (declared?.connections ?? []) + .filter((connection) => { + const entry = map[connection.key] ?? {} + const byType = (entry.uses ?? []).some((type) => types.has(type)) + return byType || (entry.healthPingTiles === true && pinging) + }) + .sort((a, b) => (Number(a.order) || 0) - (Number(b.order) || 0)) + .map((connection) => ({ key: connection.key, title: connection.title, order: Number(connection.order) || 0 })) +} + +/** + * When a connection last failed: its own last-error time, else the time of + * its last check when that check failed, else null. + * + * @param {object|null} row An `app_connection` object. + * @return {string|null} The ISO time, or null when unknown. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +export function lastErrorOf(row) { + const own = row?.lastErrorAt ?? row?.lastError ?? null + if (typeof own === 'string' && own !== '') { + return own + } + const status = String(row?.status ?? '').toLowerCase() + if (ERROR_STATUSES.includes(status) && typeof row?.checkedAt === 'string' && row.checkedAt !== '') { + return row.checkedAt + } + return null +} + +/** + * The status as the Integrations page names it: the same `connectionStatus` + * formatter its Status column uses (REQ-LP-CONN-004). A connection integriq + * holds no row for yet reads as not configured. + * + * @param {object|null} row An `app_connection` object. + * @return {string} The status label. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +export function statusLabelOf(row) { + const status = typeof row?.status === 'string' && row.status !== '' ? row.status : 'unconfigured' + return formatConnectionStatus(status) +} + +/** + * The connections in use joined with integriq's rows, by connection key. + * + * @param {Array<{key: string, title: string}>} used The connections in use. + * @param {Array<object>} rows The `app_connection` rows of this app. + * @return {Array<object>} One line per connection: key, title, status, label, last success, last error, message. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +export function joinConnectionStates(used, rows) { + const byKey = new Map((Array.isArray(rows) ? rows : []).filter((row) => row?.key).map((row) => [row.key, row])) + return (Array.isArray(used) ? used : []).map((connection) => { + const row = byKey.get(connection.key) ?? null + const status = typeof row?.status === 'string' && row.status !== '' ? row.status : 'unconfigured' + return { + key: connection.key, + title: (typeof row?.title === 'string' && row.title !== '') ? row.title : connection.title, + status, + statusLabel: statusLabelOf(row), + isError: ERROR_STATUSES.includes(status), + lastSuccessAt: lastSuccessOf(row), + lastErrorAt: lastErrorOf(row), + message: typeof row?.statusMessage === 'string' ? row.statusMessage : '', + } + }) +} + +/** + * Integriq's connection rows of this app, read with the viewer's session. + * + * @return {Promise<{state: string, rows: Array<object>}>} `ok` with the rows, or `error` when the read fails. + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +export function fetchConnectionRows() { + return fetchAppConnectionRows() +} diff --git a/src/services/embedApi.js b/src/services/embedApi.js new file mode 100644 index 000000000..62092064e --- /dev/null +++ b/src/services/embedApi.js @@ -0,0 +1,179 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The admin embed API (embedded-analytics): embed tokens, tenant themes, + * usage reports and the telemetry switch. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + * @spec openspec/changes/embedded-analytics/tasks.md#task-30 + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +const baseUrl = generateUrl('/apps/launchpad') + +const tokenUrl = (id = '') => `${baseUrl}/api/embed-tokens${id === '' ? '' : `/${encodeURIComponent(id)}`}` +const themeUrl = (id = '') => `${baseUrl}/api/tenant-themes${id === '' ? '' : `/${encodeURIComponent(id)}`}` + +export const embedApi = { + /** + * Whether embed usage telemetry is collected. + * + * @return {Promise<boolean>} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + async telemetryEnabled() { + const { data } = await axios.get(`${baseUrl}/api/embed-settings/telemetry`) + return data?.enabled !== false + }, + + /** + * Turn embed usage telemetry on or off; resolves with the stored state. + * + * @param {boolean} enabled Whether to collect. + * @return {Promise<boolean>} + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md + */ + async setTelemetryEnabled(enabled) { + const { data } = await axios.put(`${baseUrl}/api/embed-settings/telemetry`, { enabled }) + return data?.enabled !== false + }, + + /** + * Every embed token's metadata (never a JWT). + * + * @return {Promise<Array<object>>} + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + */ + async listTokens() { + const { data } = await axios.get(tokenUrl()) + return Array.isArray(data?.results) ? data.results : [] + }, + + /** + * Issue a token; the answer holds the JWT, shown this once. + * + * @param {object} token {name, description, subject, scope, hostOrigins, tenantThemeId, tokenExpiresAt, rateLimitPolicy}. + * @return {Promise<object>} {id, name, jwt, warning, createdAt}. + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + */ + async createToken(token) { + const { data } = await axios.post(tokenUrl(), token) + return data + }, + + /** + * Update a token's name, description or rate limit. + * + * @param {string} id The token id. + * @param {object} changes {name, description, rateLimitPolicy}. + * @return {Promise<object>} The token's metadata. + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + */ + async updateToken(id, changes) { + const { data } = await axios.put(tokenUrl(id), changes) + return data + }, + + /** + * Revoke a token. + * + * @param {string} id The token id. + * @param {string} reason One of the revocation reasons. + * @param {string} notes Optional notes. + * @return {Promise<object>} The token's metadata. + * @spec openspec/changes/embedded-analytics/tasks.md#task-27 + */ + async revokeToken(id, reason, notes = '') { + const { data } = await axios.post(`${tokenUrl(id)}/revoke`, { reason, notes: notes === '' ? null : notes }) + return data + }, + + /** + * Clear a token's revocation. + * + * @param {string} id The token id. + * @return {Promise<object>} The token's metadata. + * @spec openspec/changes/embedded-analytics/tasks.md#task-27 + */ + async unrevokeToken(id) { + const { data } = await axios.post(`${tokenUrl(id)}/unrevoke`) + return data + }, + + /** + * Re-issue a token: the old one is revoked, the new JWT is shown once. + * + * @param {string} id The token id. + * @return {Promise<object>} {id, name, jwt, warning, createdAt}. + * @spec openspec/changes/embedded-analytics/tasks.md#task-15 + */ + async reissueToken(id) { + const { data } = await axios.post(`${tokenUrl(id)}/re-issue`) + return data + }, + + /** + * A token's usage over the last seven days, in aggregate. + * + * @param {string} id The token id. + * @return {Promise<object>} + * @spec openspec/changes/embedded-analytics/tasks.md#task-17 + */ + async tokenUsage(id) { + const { data } = await axios.get(`${tokenUrl(id)}/usage`) + return data + }, + + /** + * Every tenant theme, with how many tokens use it. + * + * @return {Promise<Array<object>>} + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ + async listThemes() { + const { data } = await axios.get(themeUrl()) + return Array.isArray(data?.results) ? data.results : [] + }, + + /** + * Create a tenant theme. + * + * @param {object} theme {name, cssVariables, logoUrl, customCss}. + * @return {Promise<object>} The stored theme. + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ + async createTheme(theme) { + const { data } = await axios.post(themeUrl(), theme) + return data + }, + + /** + * Replace a tenant theme. + * + * @param {string} id The theme id. + * @param {object} theme {name, cssVariables, logoUrl, customCss}. + * @return {Promise<object>} The stored theme. + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ + async updateTheme(id, theme) { + const { data } = await axios.put(themeUrl(id), theme) + return data + }, + + /** + * Delete a tenant theme; one that tokens use only with force. + * + * @param {string} id The theme id. + * @param {boolean} force Delete even when tokens use it. + * @return {Promise<object>} {deleted, tokenCount}. + * @spec openspec/changes/embedded-analytics/tasks.md#task-16 + */ + async deleteTheme(id, force = false) { + const { data } = await axios.delete(themeUrl(id), { params: force ? { force: true } : {} }) + return data + }, +} diff --git a/src/services/graphqlClient.js b/src/services/graphqlClient.js index 73d58790a..e631fbca6 100644 --- a/src/services/graphqlClient.js +++ b/src/services/graphqlClient.js @@ -106,31 +106,52 @@ export async function queryGraphql({ { timeout: timeoutMs }, ) } catch (err) { - // A 404 means the sibling app's GraphQL route is absent — i.e. the - // app is not installed. Map it to the empty-state contract code. - const status = err?.response?.status - if (status === 404) { - throw new GraphQLSourceError( - 'not_installed', - app, - `${app} is not installed`, - ) - } - // axios surfaces request timeouts as ECONNABORTED. - if (err?.code === 'ECONNABORTED') { - throw new GraphQLSourceError( - 'timeout', - app, - `${app} did not respond in time`, - ) - } - throw new GraphQLSourceError( - 'network_error', + throw transportError(err, app) + } + + return dataOf(response, app) +} + +/** + * The typed error for a failed GraphQL request: a 404 means the sibling + * app's route is absent, so the app is not installed; axios reports a + * request timeout as `ECONNABORTED`; anything else is a network error. + * + * @param {unknown} err The caught request error. + * @param {string} app The sibling app id the call targeted. + * @return {GraphQLSourceError} The error to throw. + */ +function transportError(err, app) { + if (err?.response?.status === 404) { + return new GraphQLSourceError( + 'not_installed', app, - err?.message || 'Network error', + `${app} is not installed`, ) } + if (err?.code === 'ECONNABORTED') { + return new GraphQLSourceError( + 'timeout', + app, + `${app} did not respond in time`, + ) + } + return new GraphQLSourceError( + 'network_error', + app, + err?.message || 'Network error', + ) +} +/** + * The `data` payload of a GraphQL response, or an empty object when it has none. + * + * @param {object} response The axios response. + * @param {string} app The sibling app id the call targeted. + * @return {object} The GraphQL `data` object. + * @throws {GraphQLSourceError} With `graphql_errors` and the first error's message when the source returned `errors[]`. + */ +function dataOf(response, app) { const body = response?.data if (body && Array.isArray(body.errors) && body.errors.length > 0) { const first = body.errors[0]?.message || 'GraphQL error' diff --git a/src/services/headerSearch.js b/src/services/headerSearch.js new file mode 100644 index 000000000..4caf13e11 --- /dev/null +++ b/src/services/headerSearch.js @@ -0,0 +1,221 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The data side of the top bar's results list (header-search-dropdown, + * REQ-SRCH-013): it asks Nextcloud's unified search providers for a query, + * groups their answers per provider with LaunchPad's dashboards first, and + * builds the shortcut tip. The list itself is `HeaderSearchDropdown.vue`. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + +import axios from '@nextcloud/axios' +import { generateOcsUrl } from '@nextcloud/router' + +/** The OCS headers the unified search API needs to answer JSON. */ +const OCS_CONFIG = { headers: { 'OCS-APIRequest': 'true', Accept: 'application/json' } } + +/** LaunchPad's own provider id (REQ-SRCH-001). */ +export const LAUNCHPAD_PROVIDER_ID = 'launchpad' + +/** The list opens from this many characters on. */ +export const MIN_QUERY_LENGTH = 2 + +/** Results shown per provider group. */ +export const PER_GROUP_LIMIT = 5 + +/** + * Whether a query is long enough to open the list. + * + * @param {string} query The field's value. + * @return {boolean} True from two characters on (spaces at the ends ignored). + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export function isSearchable(query) { + return typeof query === 'string' && query.trim().length >= MIN_QUERY_LENGTH +} + +/** + * The providers in the order the list shows them: LaunchPad's dashboards + * first, then by the provider's own order, then by name. + * + * @param {Array<{id: string, name?: string, order?: number}>} providers The providers. + * @return {Array<object>} A sorted copy. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export function orderProviders(providers) { + const list = Array.isArray(providers) ? providers.filter((p) => p && typeof p.id === 'string') : [] + return list.slice().sort((a, b) => { + const aFirst = a.id === LAUNCHPAD_PROVIDER_ID ? 0 : 1 + const bFirst = b.id === LAUNCHPAD_PROVIDER_ID ? 0 : 1 + if (aFirst !== bFirst) { + return aFirst - bFirst + } + const aOrder = Number.isFinite(a.order) ? a.order : Number.MAX_SAFE_INTEGER + const bOrder = Number.isFinite(b.order) ? b.order : Number.MAX_SAFE_INTEGER + if (aOrder !== bOrder) { + return aOrder - bOrder + } + return String(a.name ?? a.id).localeCompare(String(b.name ?? b.id)) + }) +} + +/** + * One result as the list shows it: icon, name, one detail line and a link. + * + * @param {object} entry A unified search entry. + * @param {string} providerId The provider that answered it. + * @param {number} index Its place in the provider's answer. + * @return {{key: string, title: string, detail: string, icon: string, url: string}} The row. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export function toResult(entry, providerId, index) { + return { + key: `${providerId}-${index}`, + title: String(entry?.title ?? ''), + detail: String(entry?.subline ?? ''), + icon: String(entry?.thumbnailUrl || entry?.icon || ''), + url: String(entry?.resourceUrl ?? ''), + } +} + +/** + * Group the providers' answers: one group per provider that found + * something, in provider order, each capped at {@link PER_GROUP_LIMIT}. + * + * @param {Array<{id: string, name?: string}>} providers The providers, already ordered. + * @param {Object<string, Array<object>>} entriesByProvider The entries each provider returned, by id. + * @return {Array<{id: string, name: string, results: Array<object>}>} The groups. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export function groupResults(providers, entriesByProvider) { + const groups = [] + for (const provider of providers) { + const entries = entriesByProvider?.[provider.id] + if (!Array.isArray(entries) || entries.length === 0) { + continue + } + groups.push({ + id: provider.id, + name: String(provider.name ?? provider.id), + results: entries + .slice(0, PER_GROUP_LIMIT) + .map((entry, index) => toResult(entry, provider.id, index)) + .filter((result) => result.title !== ''), + }) + } + return groups.filter((group) => group.results.length > 0) +} + +/** + * The first configured search shortcut, for the tip at the foot of the list. + * + * @param {Array<{prefix?: string, name?: string}>} shortcuts The admin's shortcuts (REQ-SPX-002). + * @return {{prefix: string, name: string}|null} The shortcut, or null when none is usable. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export function firstShortcut(shortcuts) { + if (!Array.isArray(shortcuts)) { + return null + } + for (const shortcut of shortcuts) { + const prefix = String(shortcut?.prefix ?? '').trim() + const name = String(shortcut?.name ?? '').trim() + if (prefix !== '' && name !== '') { + return { prefix, name } + } + } + return null +} + +/** + * The next selected index when an arrow key moves the selection; wraps at + * both ends, and stays at -1 for an empty list. + * + * @param {number} current The selected index. + * @param {number} delta +1 for Arrow down, -1 for Arrow up. + * @param {number} count The number of options. + * @return {number} The new index. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export function moveSelection(current, delta, count) { + if (count <= 0) { + return -1 + } + if (current < 0) { + return delta > 0 ? 0 : count - 1 + } + return (((current + delta) % count) + count) % count +} + +/** + * The providers Nextcloud offers on this page. + * + * @param {string} route The current route, so providers can rank themselves. + * @param {AbortSignal} [signal] Cancels the request. + * @return {Promise<Array<object>>} The providers, or an empty list on failure. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export async function fetchProviders(route, signal) { + try { + const response = await axios.get(generateOcsUrl('search/providers'), { + ...OCS_CONFIG, + params: { from: route }, + signal, + }) + const data = response?.data?.ocs?.data + return Array.isArray(data) ? data : [] + } catch { + return [] + } +} + +/** + * One provider's entries for a query. + * + * @param {string} providerId The provider. + * @param {string} query The query. + * @param {string} route The current route. + * @param {AbortSignal} [signal] Cancels the request. + * @return {Promise<Array<object>>} The entries, or an empty list on failure. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export async function fetchProviderEntries(providerId, query, route, signal) { + try { + const response = await axios.get( + generateOcsUrl('search/providers/{providerId}/search', { providerId }), + { + ...OCS_CONFIG, + params: { term: query, from: route, limit: PER_GROUP_LIMIT }, + signal, + }, + ) + const entries = response?.data?.ocs?.data?.entries + return Array.isArray(entries) ? entries : [] + } catch { + return [] + } +} + +/** + * Search every provider for a query and group the answers. + * + * @param {string} query The query. + * @param {object} [options] Options. + * @param {string} [options.route] The current route (defaults to the location's path). + * @param {AbortSignal} [options.signal] Cancels the requests. + * @return {Promise<Array<{id: string, name: string, results: Array<object>}>>} The groups. + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ +export async function searchAll(query, { route = window.location.pathname, signal } = {}) { + const providers = orderProviders(await fetchProviders(route, signal)) + const answers = await Promise.all( + providers.map((provider) => fetchProviderEntries(provider.id, query, route, signal)), + ) + const entriesByProvider = {} + providers.forEach((provider, index) => { + entriesByProvider[provider.id] = answers[index] + }) + return groupResults(providers, entriesByProvider) +} diff --git a/src/services/iconCatalogue.js b/src/services/iconCatalogue.js index ff3168673..aeacd9979 100644 --- a/src/services/iconCatalogue.js +++ b/src/services/iconCatalogue.js @@ -6,14 +6,92 @@ * surfaces (tiles, org-nav, dashboards). LaunchPad already depends on `@mdi/js` * and stores icons as SVG path strings, so we use the path-based `mdiCatalogue` * adapter — the emitted/stored value is a self-contained path that - * CnDashboardIcon / CnTileWidget render anywhere. Built once and frozen so it - * isn't made reactive when referenced from components. + * CnDashboardIcon / CnTileWidget render anywhere. + * + * `@mdi/js` holds every MDI icon (about 2.8 MB), so it is loaded on demand by + * {@link loadIconCatalogue} instead of with the page. Until it arrives the + * catalogue is empty and {@link normaliseIconValue} returns its input; both + * are reactive, so a picker or icon that reads them updates once it loads. + */ + +import { DASHBOARD_ICONS, mdiCatalogue } from '@conduction/nextcloud-vue' +import { markRaw, shallowReactive, shallowRef } from 'vue' + +/** + * The full MDI catalogue, filled by {@link loadIconCatalogue}. Shallow, so the + * entries are not made reactive. + * + * @type {Array<object>} */ +export const ICON_CATALOGUE = shallowReactive([]) -import { mdiCatalogue } from '@conduction/nextcloud-vue' -import * as mdi from '@mdi/js' +const mdiIcons = shallowRef(null) +let catalogueLoad = null -export const ICON_CATALOGUE = Object.freeze(mdiCatalogue(mdi)) +/** + * Load `@mdi/js` once and fill {@link ICON_CATALOGUE}. + * + * @spec openspec/specs/dashboard-icons/spec.md#req-icon-009 + * @return {Promise<Array<object>>} The filled catalogue. + */ +export function loadIconCatalogue() { + if (!catalogueLoad) { + catalogueLoad = import(/* webpackChunkName: "mdi-icons" */ '@mdi/js') + .then((mdi) => { + const icons = markRaw({ ...mdi }) + ICON_CATALOGUE.splice(0, ICON_CATALOGUE.length, ...mdiCatalogue(icons)) + mdiIcons.value = icons + return ICON_CATALOGUE + }) + .catch((error) => { + catalogueLoad = null + throw error + }) + } + return catalogueLoad +} + +/** + * {@link ICON_CATALOGUE} for an app-wide provide: the first read, which is a + * picker rendering, starts {@link loadIconCatalogue}, so a page that never + * opens a picker never fetches `@mdi/js`. + * + * @spec openspec/specs/dashboard-icons/spec.md#req-icon-009 + */ +export const LAZY_ICON_CATALOGUE = new Proxy(ICON_CATALOGUE, { + /** + * Read from the catalogue, starting its load on the first read. + * + * @spec openspec/specs/dashboard-icons/spec.md#req-icon-009 + * @param {Array<object>} target The catalogue. + * @param {string|symbol} key The property read. + * @return {unknown} The property's value. + */ + get(target, key) { + if (!catalogueLoad) { + loadIconCatalogue().catch(() => {}) + } + return Reflect.get(target, key) + }, +}) + +/** + * The dashboard icon picker's catalogue: the names of the shared icon + * registry (`DASHBOARD_ICONS` in nextcloud-vue), so a picked icon is stored + * as its registry name (REQ-ICON-003). Tiles and the organisation navigation + * keep the full MDI catalogue above. + * + * @spec openspec/specs/dashboard-icons/spec.md#req-icon-003 + */ +export const DASHBOARD_ICON_CATALOGUE = Object.freeze( + Object.keys(DASHBOARD_ICONS).map((key) => ({ + key, + label: key.replace(/([a-z\d])([A-Z])/g, '$1 $2'), + value: key, + search: key.toLowerCase(), + component: DASHBOARD_ICONS[key], + })), +) // A bare icon-name token: a letter followed by letters/digits and word // separators only. SVG path strings (commas, dots — see CnDashboardIcon's @@ -35,6 +113,8 @@ const BARE_ICON_NAME = /^[A-Za-z][A-Za-z0-9 _-]*$/ * This is what lets the single `icon` column hold legacy names, SVG paths and * custom URLs side by side and still render, with no data migration * (REQ-ICON-009 "Mixed values across rows render without migration"). + * Before `@mdi/js` has loaded the value comes back unchanged and the load + * starts; a caller inside a computed or render recomputes once it arrives. * * @spec openspec/specs/dashboard-icons/spec.md#req-icon-009 * @param {string|null|undefined} value stored `icon` field value. @@ -50,6 +130,11 @@ export function normaliseIconValue(value) { .filter(Boolean) .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) .join('') - const path = mdi['mdi' + pascal] + const icons = mdiIcons.value + if (!icons) { + loadIconCatalogue().catch(() => {}) + return value + } + const path = icons['mdi' + pascal] return typeof path === 'string' ? path : value } diff --git a/src/services/liveTileConnections.js b/src/services/liveTileConnections.js new file mode 100644 index 000000000..d567d83a6 --- /dev/null +++ b/src/services/liveTileConnections.js @@ -0,0 +1,87 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The connections a Live data widget can read from (REQ-LIVETILE-020). + * + * The rows are integriq's `app_connection` objects for this app, the same rows + * the Integrations page lists, read through OpenRegister with the editor's own + * session so the editor only sees what OpenRegister lets them read. + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +/** Statuses integriq uses for a connection whose last check succeeded. */ +const SUCCESS_STATUSES = Object.freeze(['ok', 'connected', 'healthy', 'success']) + +/** + * When a connection last succeeded: its own last-success time, else the time + * of its last check when that check succeeded, else null. + * + * @param {object} row An `app_connection` object. + * @return {string|null} the ISO time, or null when unknown. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ +export function lastSuccessOf(row) { + const own = row?.lastSuccessAt ?? row?.lastSuccess ?? null + if (typeof own === 'string' && own !== '') { + return own + } + const status = String(row?.status ?? '').toLowerCase() + if (SUCCESS_STATUSES.includes(status) && typeof row?.checkedAt === 'string' && row.checkedAt !== '') { + return row.checkedAt + } + return null +} + +/** + * One `app_connection` row as a choice in the Live data form. The value is the + * integriq source id the live tile resolves; a row without one is left out. + * + * @param {object} row An `app_connection` object. + * @return {{value: string, label: string, lastSuccessAt: (string|null)}|null} the choice. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ +export function toConnectionOption(row) { + const value = row?.sourceId ?? row?.source ?? row?.id ?? null + if (value === null || value === undefined || String(value) === '') { + return null + } + const title = typeof row?.title === 'string' && row.title !== '' ? row.title : String(value) + return { value: String(value), label: title, lastSuccessAt: lastSuccessOf(row) } +} + +/** + * The connections of this app. Fails soft: no integriq, no register or a + * refused read gives an empty list, and the form then asks for a source id. + * + * @return {Promise<Array<{value: string, label: string, lastSuccessAt: (string|null)}>>} the choices. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + */ +export async function fetchLiveTileConnections() { + const { rows } = await fetchAppConnectionRows() + return rows.map(toConnectionOption).filter((option) => option !== null) +} + +/** + * Integriq's `app_connection` rows of this app, read through OpenRegister + * with the viewer's own session. Fails soft: no integriq, no register or a + * refused read gives state `error` and no rows. + * + * @return {Promise<{state: string, rows: Array<object>}>} `ok` with the rows, or `error`. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/live-data-tile-widget/spec.md#requirement-the-live-data-form-as-lpwidgetinstellen-draws-it-req-livetile-020 + * @spec openspec/changes/archive/2026-11-25-dashboard-connections-widget/specs/app-connections/spec.md#requirement-req-lp-conn-005-a-dashboard-shows-the-state-of-its-own-connections + */ +export async function fetchAppConnectionRows() { + const url = generateUrl('/apps/openregister/api/objects/{register}/{schema}', { + register: 'integriq', + schema: 'app_connection', + }) + try { + const response = await axios.get(url, { params: { app: 'launchpad', _limit: 100 } }) + return { state: 'ok', rows: Array.isArray(response?.data?.results) ? response.data.results : [] } + } catch { + return { state: 'error', rows: [] } + } +} diff --git a/src/services/publicWidgetClient.js b/src/services/publicWidgetClient.js new file mode 100644 index 000000000..ecd5896dc --- /dev/null +++ b/src/services/publicWidgetClient.js @@ -0,0 +1,54 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Token-scoped reads of the live widgets (news, weather, live data) on a + * public link or a kiosk screen. The anonymous visitor only ever calls + * LaunchPad's own per-placement endpoint behind the link's or playlist's + * token; the server decides whether the placement is shared. + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +/** + * A reader of one placement's `{widget, data}` through a token route. + * + * @param {string} route The route prefix, `s` (share) or `kiosk`. + * @param {string} token The share or playlist token. + * @param {object} headers The request headers. + * @return {function((number|string)): Promise<{widget: string, data: object}>} The reader. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +function tokenReader(route, token, headers) { + const base = generateUrl('/apps/launchpad') + '/' + route + '/' + encodeURIComponent(token) + '/placements/' + return async (placementId) => { + const response = await axios.get(base + encodeURIComponent(String(placementId)), { headers }) + return response?.data || {} + } +} + +/** + * The live widget reader of a public share link, passing the password the + * visitor unlocked the link with. + * + * @param {string} token The share token. + * @param {string|null} password The share password, when the link has one. + * @return {function((number|string)): Promise<{widget: string, data: object}>} The reader. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +export function shareWidgetReader(token, password = null) { + const headers = password ? { 'X-Share-Password': password } : {} + return tokenReader('s', token, headers) +} + +/** + * The live widget reader of a kiosk playlist. + * + * @param {string} token The playlist token. + * @return {function((number|string)): Promise<{widget: string, data: object}>} The reader. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ +export function kioskWidgetReader(token) { + return tokenReader('kiosk', token, {}) +} diff --git a/src/services/resourceService.js b/src/services/resourceService.js index a58c74f8c..d750bbaee 100644 --- a/src/services/resourceService.js +++ b/src/services/resourceService.js @@ -60,41 +60,9 @@ export class ResourceUploadError extends Error { * @spec openspec/specs/resource-uploads/spec.md */ export async function uploadDataUrl(dataUrl) { - const url = generateUrl('/apps/launchpad/api/resources') - - let response - try { - response = await axios.post(url, { base64: dataUrl }) - } catch (err) { - const data = err?.response?.data - if (data && data.status === 'error' && typeof data.error === 'string') { - throw new ResourceUploadError( - data.error, - typeof data.message === 'string' ? data.message : data.error, - err?.response?.status, - ) - } - throw new ResourceUploadError( - 'network_error', - err?.message || 'Network error', - err?.response?.status, - ) - } - - const body = response?.data - if (!body || body.status !== 'success' || typeof body.url !== 'string') { - throw new ResourceUploadError( - body?.error || 'unknown_error', - body?.message || 'Unexpected server response', - response?.status, - ) - } - - return { - url: body.url, - name: typeof body.name === 'string' ? body.name : '', - size: typeof body.size === 'number' ? body.size : 0, - } + return postResource(generateUrl('/apps/launchpad/api/resources'), { + base64: dataUrl, + }) } /** @@ -120,26 +88,59 @@ export async function uploadFile(file) { const formData = new FormData() formData.append('file', file) + // Let the browser/axios set the multipart boundary and CSRF token. + return postResource(url, formData) +} + +/** + * Post an upload and read the resource envelope the server answers with. + * + * @param {string} url The upload endpoint. + * @param {object|FormData} payload The request body. + * @return {Promise<{url: string, name: string, size: number}>} The persisted resource info. + * @throws {ResourceUploadError} On a server-side rejection or a transport failure. + */ +async function postResource(url, payload) { let response try { - // Let the browser/axios set the multipart boundary and CSRF token. - response = await axios.post(url, formData) + response = await axios.post(url, payload) } catch (err) { - const data = err?.response?.data - if (data && data.status === 'error' && typeof data.error === 'string') { - throw new ResourceUploadError( - data.error, - typeof data.message === 'string' ? data.message : data.error, - err?.response?.status, - ) - } - throw new ResourceUploadError( - 'network_error', - err?.message || 'Network error', + throw rejectionError(err) + } + return resourceOf(response) +} + +/** + * The error for a failed upload request: the server's own error code and + * message when it answered with an error envelope, `network_error` otherwise. + * + * @param {unknown} err The caught request error. + * @return {ResourceUploadError} The error to throw. + */ +function rejectionError(err) { + const data = err?.response?.data + if (data && data.status === 'error' && typeof data.error === 'string') { + return new ResourceUploadError( + data.error, + typeof data.message === 'string' ? data.message : data.error, err?.response?.status, ) } + return new ResourceUploadError( + 'network_error', + err?.message || 'Network error', + err?.response?.status, + ) +} +/** + * The resource info of a successful upload response. + * + * @param {object} response The axios response. + * @return {{url: string, name: string, size: number}} The persisted resource info. + * @throws {ResourceUploadError} When the response is not a success envelope with a URL. + */ +function resourceOf(response) { const body = response?.data if (!body || body.status !== 'success' || typeof body.url !== 'string') { throw new ResourceUploadError( diff --git a/src/services/sourceAvailability.js b/src/services/sourceAvailability.js new file mode 100644 index 000000000..497f178c9 --- /dev/null +++ b/src/services/sourceAvailability.js @@ -0,0 +1,121 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +/** + * Whether a register and schema exist on this instance, asked once per + * page and remembered (admin-templates REQ-TMPL-022). + * + * A ready-made template lists objects of several apps. On an instance + * without one of those apps, OpenRegister answers 404 ("Register not + * found") and the list widget would show "Could not load these records" + * to every employee. The page asks first, with the cheapest request there + * is, and hides a list that asked to be hidden when its source is not + * there. Any other failure (403, 500, no network) is NOT "not here": the + * widget then renders and shows its own error line, because that is a + * fault someone has to see. + * + * @type {Map<string, Promise<boolean|null>>} + */ +const probes = new Map() + +/** + * The widget types that read one register and schema and can hide when it + * is not here: a list, and a number (the app tiles of Mijn werkdag v4). + */ +const HIDEABLE_TYPES = ['object-list', 'stat'] + +/** + * The key a placement's source is remembered under. + * + * @param {object} content The object-list widget's content. + * @return {string} `register/schema`, or '' when either is missing. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-022 + */ +export function sourceKey(content) { + // An object-list names its source at the top of its content; a stat + // widget names it under `source`. + const from = + content && !content.register && content.source ? content.source : content + const register = from && from.register + const schema = from && from.schema + if (!register || !schema) { + return '' + } + return `${register}/${schema}` +} + +/** + * Whether a placement asks to be hidden when its source is not here. + * + * @param {object} placement A widget placement. + * @return {boolean} True for an object-list or a stat with `hideWhenUnavailable`. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-022 + */ +export function hidesWhenUnavailable(placement) { + return ( + !!placement + && HIDEABLE_TYPES.includes(placement.widgetId) + && !!placement.content + && placement.content.hideWhenUnavailable === true + && sourceKey(placement.content) !== '' + ) +} + +/** + * Ask OpenRegister whether the source exists. One request per source per + * page; later callers share the answer. + * + * @param {string} register The register slug. + * @param {string} schema The schema slug. + * @return {Promise<boolean|null>} true: there; false: OpenRegister says + * 404; null: could not tell (any other failure). + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-022 + */ +export function isSourceAvailable(register, schema) { + const key = `${register}/${schema}` + if (!probes.has(key)) { + probes.set(key, probe(register, schema)) + } + return probes.get(key) +} + +/** + * Forget every answer (tests, and a page that re-reads after an install). + * + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-022 + */ +export function resetSourceAvailability() { + probes.clear() +} + +/** + * The request behind {@link isSourceAvailable}. + * + * @param {string} register The register slug. + * @param {string} schema The schema slug. + * @return {Promise<boolean|null>} See {@link isSourceAvailable}. + * @spec openspec/specs/admin-templates/spec.md#req-tmpl-022 + */ +async function probe(register, schema) { + try { + await axios.get( + generateUrl('/apps/openregister/api/objects/{register}/{schema}', { + register, + schema, + }), + { params: { _limit: 1 } }, + ) + return true + } catch (error) { + const status = error && error.response && error.response.status + if (status === 404) { + return false + } + return null + } +} diff --git a/src/services/spendAnalytics.js b/src/services/spendAnalytics.js index dad6511b4..2562cb095 100644 --- a/src/services/spendAnalytics.js +++ b/src/services/spendAnalytics.js @@ -114,48 +114,89 @@ export async function fetchFinanceSummary({ } const rows = Array.isArray(data?.transactions) ? data.transactions : [] - if (rows.length === 0) { - return { - available: true, - empty: true, - total: 0, - currency: 'EUR', - byCategory: [], - trend: [], - } + return rows.length === 0 ? emptyFinanceSummary() : summariseTransactions(rows) +} + +/** + * The finance summary for a period without transactions. + * + * @return {object} `{available, empty, total, currency, byCategory, trend}` + */ +function emptyFinanceSummary() { + return { + available: true, + empty: true, + total: 0, + currency: 'EUR', + byCategory: [], + trend: [], } +} - const currency = - rows.find((row) => typeof row.currency === 'string')?.currency || 'EUR' - const total = rows.reduce((sum, row) => sum + (Number(row.totalAmount) || 0), 0) +/** + * A transaction's amount, with a missing or non-numeric amount read as 0. + * + * @param {object} row A transaction. + * @return {number} The amount. + */ +function amountOf(row) { + return Number(row.totalAmount) || 0 +} + +/** + * A transaction's category, `uncategorised` when it has none. + * + * @param {object} row A transaction. + * @return {string} The category. + */ +function categoryOf(row) { + return typeof row.category === 'string' && row.category + ? row.category + : 'uncategorised' +} - // Aggregate by category (top categories view). - const byCategoryMap = new Map() +/** + * A transaction's booking month (`YYYY-MM`), `unknown` when it has no date. + * + * @param {object} row A transaction. + * @return {string} The month. + */ +function monthOf(row) { + return typeof row.bookedAt === 'string' ? row.bookedAt.slice(0, 7) : 'unknown' +} + +/** + * Sum the transaction amounts per key, in the order the keys first appear. + * + * @param {Array<object>} rows The transactions. + * @param {(row: object) => string} keyOf Reads the key of a transaction. + * @return {Array<[string, number]>} The key and amount pairs. + */ +function sumAmountsBy(rows, keyOf) { + const totals = new Map() for (const row of rows) { - const key = - typeof row.category === 'string' && row.category - ? row.category - : 'uncategorised' - byCategoryMap.set( - key, - (byCategoryMap.get(key) || 0) + (Number(row.totalAmount) || 0), - ) + const key = keyOf(row) + totals.set(key, (totals.get(key) || 0) + amountOf(row)) } - const byCategory = [...byCategoryMap.entries()] + return [...totals.entries()] +} + +/** + * The finance summary of a non-empty list of transactions: the total, the + * first currency named, the amount per category (largest first) and per + * booking month (oldest first). + * + * @param {Array<object>} rows The transactions. + * @return {object} `{available, empty, total, currency, byCategory, trend}` + */ +function summariseTransactions(rows) { + const currency = + rows.find((row) => typeof row.currency === 'string')?.currency || 'EUR' + const total = rows.reduce((sum, row) => sum + amountOf(row), 0) + const byCategory = sumAmountsBy(rows, categoryOf) .map(([category, amount]) => ({ category, amount })) .sort((a, b) => b.amount - a.amount) - - // Aggregate by booking month (trend view). - const trendMap = new Map() - for (const row of rows) { - const month = - typeof row.bookedAt === 'string' ? row.bookedAt.slice(0, 7) : 'unknown' - trendMap.set( - month, - (trendMap.get(month) || 0) + (Number(row.totalAmount) || 0), - ) - } - const trend = [...trendMap.entries()] + const trend = sumAmountsBy(rows, monthOf) .map(([month, amount]) => ({ month, amount })) .sort((a, b) => a.month.localeCompare(b.month)) diff --git a/src/services/statusReport.js b/src/services/statusReport.js new file mode 100644 index 000000000..50bffab09 --- /dev/null +++ b/src/services/statusReport.js @@ -0,0 +1,89 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Status reports: the product prefills the figures, the rating and a + * summary; a person may rewrite the rating and the summary before keeping it + * (openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them REQ-DWMS-004). + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +const SUBJECT_KEYS = ['register', 'schema', 'title', 'deadline', 'statusProperty', 'dueProperty'] + +/** + * The body of work as the endpoints take it, from a widget's content. + * `closedValues` may be stored as a list or as a comma-separated string. + * + * @param {object} content the widget content + * @return {object} the subject + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ +export function subjectOf(content) { + const subject = {} + for (const key of SUBJECT_KEYS) { + const value = content?.[key] + if (typeof value === 'string' && value.trim() !== '') { + subject[key] = value.trim() + } + } + const raw = content?.closedValues + const closed = (Array.isArray(raw) ? raw : String(raw ?? '').split(',')) + .map((value) => String(value).trim()) + .filter((value) => value !== '') + if (closed.length > 0) { + subject.closedValues = closed + } + return subject +} + +/** + * Turn a refused request into an answer the widget can say in words. + * + * @param {Error} error the axios error + * @return {{refused: true, status: number}} the refusal + * @throws {Error} anything that is not an HTTP refusal + */ +function refusalOf(error) { + const status = error?.response?.status + if (typeof status === 'number' && status >= 400 && status < 600) { + return { refused: true, status } + } + throw error +} + +/** + * Ask the product to prefill a report on the body of work. + * + * @param {object} subject the body of work, from subjectOf + * @return {Promise<object>} the draft, or a refusal + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ +export async function draftStatusReport(subject) { + try { + const { data } = await axios.post(generateUrl('/apps/launchpad/api/status-reports/draft'), subject) + return { refused: false, report: data } + } catch (error) { + return refusalOf(error) + } +} + +/** + * Keep the report with the person's rating and summary. The server computes + * the figures again; a person cannot write them. + * + * @param {object} subject the body of work, from subjectOf + * @param {string} health the rating + * @param {string} summary the summary + * @return {Promise<object>} the kept report, or a refusal + * @spec openspec/changes/archive/2026-11-19-dashboards-and-who-may-see-them/tasks.md#task-3.3 + */ +export async function keepStatusReport(subject, health, summary) { + try { + const { data } = await axios.post(generateUrl('/apps/launchpad/api/status-reports'), { ...subject, health, summary }) + return { refused: false, report: data } + } catch (error) { + return refusalOf(error) + } +} diff --git a/src/services/talkCommunities.js b/src/services/talkCommunities.js new file mode 100644 index 000000000..ceb38ea4f --- /dev/null +++ b/src/services/talkCommunities.js @@ -0,0 +1,162 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Talk communities: the open Talk conversations a viewer may join, read from + * Nextcloud Talk's OCS API as the signed-in user (engagement-communities D1). + * Talk's own visibility rules decide what each person sees; LaunchPad keeps + * nothing about conversations. + */ + +import axios from '@nextcloud/axios' +import { generateOcsUrl, generateUrl } from '@nextcloud/router' + +/** The OCS headers Talk needs to answer JSON. */ +const OCS_CONFIG = { headers: { 'OCS-APIRequest': 'true', Accept: 'application/json' } } + +/** Talk's `listable` values above 0 mean an open conversation (1 users, 2 everyone). */ +const LISTABLE_NONE = 0 + +/** + * The OCS URL of a Talk v4 endpoint. + * + * @param {string} path The path after `apps/spreed/api/v4/`. + * @return {string} The URL. + */ +function talkUrl(path) { + return generateOcsUrl(`apps/spreed/api/v4/${path}`) +} + +/** + * The rooms of an OCS answer, or an empty list. + * + * @param {object} response The axios response. + * @return {Array<object>} The rooms. + */ +function roomsOf(response) { + const data = response?.data?.ocs?.data + return Array.isArray(data) ? data : [] +} + +/** + * The member count Talk reports for a room, or null when it reports none. + * + * @param {object} room A Talk room. + * @return {number|null} The count. + */ +function memberCount(room) { + for (const key of ['participantCount', 'participantsCount', 'memberCount']) { + if (Number.isInteger(room?.[key])) { + return room[key] + } + } + return null +} + +/** + * One community as the widget shows it. + * + * @param {object} room A Talk room. + * @param {{joined: boolean, pinned: boolean}} marks Whether the viewer joined it, and whether it is pinned. + * @return {{token: string, name: string, description: string, members: number|null, joined: boolean, pinned: boolean}} The community. + */ +function community(room, marks) { + return { + token: String(room.token), + name: String(room.displayName || room.name || room.token), + description: String(room.description || ''), + members: memberCount(room), + joined: marks.joined, + pinned: marks.pinned, + } +} + +/** + * Load the open conversations the viewer may join, with the ones they joined + * marked, the pinned ones first in the order pinned, the rest by name. + * + * The listed rooms are the open conversations Talk lets the viewer find; the + * viewer's own rooms tell which they joined, and add the open ones they are + * already in when Talk leaves those out of the listing. + * + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-the-communities-widget-lists-open-talk-conversations-the-viewer-may-join-req-comm-001 + * @param {Array<string>} pinned The pinned tokens, in the order pinned. + * @param {object} [opts] Options. + * @param {object} [opts.client] An axios-like client, for tests. + * @return {Promise<Array<object>>} The communities. + */ +export async function loadCommunities(pinned = [], opts = {}) { + const client = opts.client || axios + const [listed, own] = await Promise.all([ + client.get(talkUrl('listed-room'), OCS_CONFIG), + client.get(talkUrl('room'), OCS_CONFIG), + ]) + const ownRooms = roomsOf(own) + const joined = new Set(ownRooms.map((room) => String(room.token))) + const pinnedOrder = new Map( + (Array.isArray(pinned) ? pinned : []).map((token, index) => [token, index]), + ) + + const byToken = new Map() + const add = (room) => { + const token = String(room?.token || '') + if (token === '' || byToken.has(token)) { + return + } + byToken.set( + token, + community(room, { joined: joined.has(token), pinned: pinnedOrder.has(token) }), + ) + } + roomsOf(listed).forEach(add) + ownRooms.filter((room) => Number(room.listable) > LISTABLE_NONE).forEach(add) + + return [...byToken.values()].sort((a, b) => compareCommunities(a, b, pinnedOrder)) +} + +/** + * Pinned first in the order pinned, then by name. + * + * @param {object} a A community. + * @param {object} b Another community. + * @param {Map<string, number>} pinnedOrder Position of each pinned token. + * @return {number} The sort order. + */ +function compareCommunities(a, b, pinnedOrder) { + if (a.pinned !== b.pinned) { + return a.pinned ? -1 : 1 + } + if (a.pinned) { + return pinnedOrder.get(a.token) - pinnedOrder.get(b.token) + } + return a.name.localeCompare(b.name) +} + +/** + * Join a conversation as the viewer. Talk adds a user who joins a listable + * conversation as a member; the session that join opens is closed again, so + * the viewer does not show as present in the conversation. + * + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-one-click-joins-a-community-req-comm-002 + * @param {string} token The conversation token. + * @param {object} [opts] Options. + * @param {object} [opts.client] An axios-like client, for tests. + * @return {Promise<void>} Resolves once Talk added the viewer. + */ +export async function joinCommunity(token, opts = {}) { + const client = opts.client || axios + const session = talkUrl(`room/${encodeURIComponent(token)}/participants/active`) + await client.post(session, {}, OCS_CONFIG) + await client.delete(session, OCS_CONFIG).catch(() => {}) +} + +/** + * The Talk page of a conversation. + * + * @spec openspec/changes/engagement-communities/specs/communities-widget/spec.md#requirement-one-click-joins-a-community-req-comm-002 + * @param {string} token The conversation token. + * @return {string} The URL. + */ +export function communityUrl(token) { + return generateUrl(`/call/${encodeURIComponent(token)}`) +} diff --git a/src/services/tileCount.js b/src/services/tileCount.js new file mode 100644 index 000000000..0241b8d6c --- /dev/null +++ b/src/services/tileCount.js @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + +/** + * The live count of an icon-only app tile (REQ-ICT-002), read from the + * tile's `content.countSource`: + * + * - `{type: 'register', register, schema, filter}`: the OpenRegister objects + * the viewer may read that match the filter, asked with the viewer's own + * session; a filter value `@me` stands for the viewer. A source with a + * register and a schema and no type is a register source. + * - `{type: 'nc-widget', widgetId}`: the items a Nextcloud dashboard widget + * (API v2) returns for the viewer. + * + * No app is named here. A source that does not answer (app missing, refused, + * offline) counts as no count: the tile shows no pill and no error. Each + * source is asked at most once a minute, however many tiles name it. + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ + +import axios from '@nextcloud/axios' +import { generateOcsUrl, generateUrl } from '@nextcloud/router' + +/** How long a count is reused, in milliseconds. */ +export const COUNT_TTL_MS = 60 * 1000 + +/** @type {Map<string, {at: number, value: Promise<number|null>}>} */ +const cache = new Map() + +/** + * The kind of a count source, or null when it is not one. + * + * @param {object|null} source The count source. + * @return {'register'|'nc-widget'|null} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ +export function sourceType(source) { + if (!source || typeof source !== 'object') { + return null + } + if (source.type === 'nc-widget') { + return typeof source.widgetId === 'string' && source.widgetId !== '' ? 'nc-widget' : null + } + if (source.type === undefined || source.type === 'register') { + return source.register && source.schema ? 'register' : null + } + return null +} + +/** + * The query of a register source, with `@me` replaced by the viewer. + * + * @param {object} filter The source's filter. + * @param {string} uid The viewer. + * @return {object} the query parameters. + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ +export function registerQuery(filter, uid) { + const params = { _limit: 1 } + for (const [key, value] of Object.entries(filter || {})) { + params[key] = value === '@me' ? uid : value + } + return params +} + +/** + * The count in a register answer: its total, else the number of results. + * + * @param {object} data The answer. + * @return {number|null} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ +export function registerTotal(data) { + const total = Number(data?.total) + if (Number.isFinite(total) && total >= 0) { + return total + } + return Array.isArray(data?.results) ? data.results.length : null +} + +/** + * The count in a dashboard API v2 answer for one widget. + * + * @param {object} data The OCS answer. + * @param {string} widgetId The widget. + * @return {number|null} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ +export function widgetItemsCount(data, widgetId) { + const entry = data?.ocs?.data?.[widgetId] + const items = Array.isArray(entry) ? entry : entry?.items + return Array.isArray(items) ? items.length : null +} + +/** + * Ask the source for its count. + * + * @param {object} source The count source. + * @param {string} uid The viewer. + * @return {Promise<number|null>} the count, null when the source does not answer. + */ +async function fetchCount(source, uid) { + try { + if (sourceType(source) === 'register') { + const url = generateUrl('/apps/openregister/api/objects/{register}/{schema}', { + register: source.register, + schema: source.schema, + }) + const response = await axios.get(url, { params: registerQuery(source.filter, uid) }) + return registerTotal(response?.data) + } + const url = generateOcsUrl('/apps/dashboard/api/v2/widget-items') + const response = await axios.get(url, { params: { 'widgets[]': source.widgetId } }) + return widgetItemsCount(response?.data, source.widgetId) + } catch { + return null + } +} + +/** + * The count of a tile's source, reusing an answer younger than a minute. + * + * @param {object|null} source The count source. + * @param {string} uid The viewer. + * @param {number} [now] The current time in milliseconds. + * @return {Promise<number|null>} the count, null for none. + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ +export function resolveTileCount(source, uid, now = Date.now()) { + if (sourceType(source) === null) { + return Promise.resolve(null) + } + const key = JSON.stringify([uid, source]) + const hit = cache.get(key) + if (hit && now - hit.at < COUNT_TTL_MS) { + return hit.value + } + const value = fetchCount(source, uid) + cache.set(key, { at: now, value }) + return value +} + +/** + * The pill text for a count: '' for none or 0, "99+" above 99. + * + * @param {number|null} count The count. + * @return {string} + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ +export function countLabel(count) { + const value = Number(count) + if (count === null || !Number.isFinite(value) || value <= 0) { + return '' + } + return value > 99 ? '99+' : String(Math.floor(value)) +} + +/** + * Forget every cached count (tests, and a viewer who switches account). + * + * @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-an-app-tile-shows-a-live-count-req-ict-002 + */ +export function clearTileCounts() { + cache.clear() +} diff --git a/src/services/widgetBridge.js b/src/services/widgetBridge.js index 1a663e618..b518d3821 100644 --- a/src/services/widgetBridge.js +++ b/src/services/widgetBridge.js @@ -138,7 +138,7 @@ class WidgetBridge { if (callback && typeof callback === 'function') { try { // Clear container first - container.innerHTML = '' + container.replaceChildren() logger.debug('[WidgetBridge] Calling widget callback for:', widgetId) // Call the widget's callback with the container and widget data @@ -175,7 +175,7 @@ class WidgetBridge { if (callback && typeof callback === 'function') { try { - container.innerHTML = '' + container.replaceChildren() callback(container) logger.debug('LaunchPad: Mounted status widget:', widgetId) } catch (error) { diff --git a/src/services/widgetDataAdapters.js b/src/services/widgetDataAdapters.js index 232738d52..9c51342b8 100644 --- a/src/services/widgetDataAdapters.js +++ b/src/services/widgetDataAdapters.js @@ -24,14 +24,30 @@ import { * launchpad's `/apps/launchpad/api/people` and returns `{ users, total, hasMore }`. * Axios is lazy-imported (keeps it out of the vitest css-no-op transform path). * - * @param {object} args `{ offset, limit, filters, excludeDisabled, sortBy }`. + * @param {object} args `{ offset, limit, filters, excludeDisabled, sortBy, showBirthdays, q }`; + * `q` searches the whole directory by name, email and profile fields (REQ-PEX-003). * @return {Promise<{users: object[], total: number, hasMore: boolean}>} page. + * @spec openspec/specs/people-widget/spec.md */ export async function fetchPeoplePage(args = {}) { const [{ default: axios }, { generateUrl: genUrl }] = await Promise.all([ import('@nextcloud/axios'), import('@nextcloud/router'), ]) + const url = `${genUrl('/apps/launchpad/api/people')}?${peopleQuery(args)}` + const response = await axios.get(url) + return peoplePageOf(response) +} + +/** + * The people endpoint's query string: the filters, the disabled-account + * switch, the sort key and the search text only when given, then the page + * size and offset. + * + * @param {object} args `{ offset, limit, filters, excludeDisabled, sortBy, showBirthdays, q }`. + * @return {string} The query string. + */ +function peopleQuery(args) { const params = new URLSearchParams() if (args.filters !== undefined) { params.append('filters', JSON.stringify(args.filters || [])) @@ -42,10 +58,24 @@ export async function fetchPeoplePage(args = {}) { if (args.sortBy) { params.append('sortBy', String(args.sortBy)) } + if (args.showBirthdays !== undefined) { + params.append('showBirthdays', args.showBirthdays ? '1' : '0') + } + if (args.q) { + params.append('q', String(args.q)) + } params.append('limit', String(args.limit ?? 50)) params.append('offset', String(args.offset ?? 0)) - const url = `${genUrl('/apps/launchpad/api/people')}?${params.toString()}` - const response = await axios.get(url) + return params.toString() +} + +/** + * The page of people in a people endpoint response, with empty defaults. + * + * @param {object} response The axios response. + * @return {{users: object[], total: number, hasMore: boolean}} The page. + */ +function peoplePageOf(response) { const data = response?.data || {} return { users: Array.isArray(data.users) ? data.users : [], @@ -81,18 +111,93 @@ export async function fetchCalendarEvents(placementId, args = {}) { } } +/** + * The new colleagues for CnPeopleWidget's `selectionMode: 'new'`: + * `GET /apps/launchpad/api/people/new?since=&until=`, answered as + * `{ configured, users }` (each with id, displayName, avatarUrl, role, + * organisation, startDate, starts). A failed read throws, so the widget shows + * its error state. + * + * @param {object} [args] `{ since, until }` in days. + * @return {Promise<{configured: boolean, users: Array<object>}>} + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ +export async function fetchNewPeople(args = {}) { + const [{ default: axios }, { generateUrl: genUrl }] = await Promise.all([ + import('@nextcloud/axios'), + import('@nextcloud/router'), + ]) + const response = await axios.get(genUrl('/apps/launchpad/api/people/new'), { + params: { since: args.since, until: args.until }, + }) + const data = response?.data || {} + return { + configured: data.configured === true, + users: Array.isArray(data.users) ? data.users : [], + } +} + +/** The one start-date answer of this page load (a promise), or null. */ +let startDateFieldAnswer = null + +/** + * Whether an administrator marked a profile field as the start date, which + * is when the people widget form offers New colleagues. Asked once per page + * load; a failed read offers nothing. + * + * @return {Promise<boolean>} + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ +export function hasStartDateField() { + if (startDateFieldAnswer === null) { + startDateFieldAnswer = fetchNewPeople({ since: 1, until: 0 }) + .then((answer) => answer.configured === true) + .catch(() => { + startDateFieldAnswer = null + return false + }) + } + return startDateFieldAnswer +} + +/** + * The people source for places outside a placement (the widget forms): + * the directory, the new colleagues and the start-date question. + * + * @return {object} the `cnPeopleSource` adapter. + * @spec openspec/changes/archive/2026-11-25-people-new-colleagues/specs/people-widget/spec.md#requirement-the-people-widget-can-list-new-colleagues-req-ppl-014 + */ +export function buildPeopleSource() { + return { + fetchPeople: fetchPeoplePage, + searchPeople: fetchPeoplePage, + fetchNewPeople, + hasStartDateField, + } +} + /** * Build the `provide()` map of data-source adapters for the nc-vue data * widgets. Calendar is placement-scoped, so the caller passes a getter for the * current placement id. * * @param {() => (string|number|undefined)} getPlacementId returns the placement id. + * @param {() => (object|undefined)} [getContent] returns the placement content; the people adapter sends its `showBirthdays` switch. * @return {object} the injected `cn*Source` adapters. - * @spec exclude wiring-only assembly — returns a literal map of the adapter functions defined in this file, each of which carries its own @spec; it encodes no behaviour of its own beyond naming the injection keys the nc-vue widgets expect. + * @spec openspec/specs/people-widget/spec.md */ -export function buildWidgetDataProvide(getPlacementId) { +export function buildWidgetDataProvide(getPlacementId, getContent = () => ({})) { + const people = (args) => fetchPeoplePage({ + ...args, + showBirthdays: (getContent() || {}).showBirthdays !== false, + }) return { - cnPeopleSource: { fetchPeople: fetchPeoplePage }, + cnPeopleSource: { + fetchPeople: people, + searchPeople: people, + fetchNewPeople, + hasStartDateField, + }, cnCalendarSource: { fetchEvents: (args) => fetchCalendarEvents(getPlacementId(), args), }, diff --git a/src/services/wikiPages.js b/src/services/wikiPages.js new file mode 100644 index 000000000..3b44ecd4a --- /dev/null +++ b/src/services/wikiPages.js @@ -0,0 +1,107 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The wiki pages a person can open, read through OpenRegister's XWiki + * integration. OpenRegister routes the call to the `xwiki` source of the + * connector app, which holds the wiki's address and credentials, so the + * browser never sees either. The person's favourite pages are kept in their + * launchpad preference `wiki-favourites`. + * + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +const FAVOURITES_KEY = 'wiki-favourites' + +/** The most favourites a person keeps; the preference store caps a value at 8 KB. */ +export const MAX_FAVOURITES = 20 + +/** + * A wiki page as the widget shows it. + * + * @typedef {object} WikiPage + * @property {string} reference The page's XWiki reference. + * @property {string} title The page title. + * @property {string} space The space it lives in. + * @property {string} url The page's http(s) address in the wiki, '' when unknown or of another scheme. + */ + +/** + * A page row from the integration as a {@link WikiPage}, or null without a reference. + * + * @param {object} row The row. + * @return {WikiPage|null} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-wiki-widget-shows-favourites-recent-pages-and-search-req-wiki-001 + */ +export function wikiPage(row) { + const reference = String(row?.reference || row?.id || '') + if (reference === '') { + return null + } + return { + reference, + title: String(row.title || reference), + space: String(row.space || ''), + url: typeof row.url === 'string' && /^https?:\/\//i.test(row.url) ? row.url : '', + } +} + +/** + * Search the wiki. An empty query lists the most recent pages. + * + * @param {string} query The search text. + * @param {number} limit The most pages. + * @return {Promise<{state: string, pages: Array<WikiPage>}>} `state` is + * `ok`, `not-connected` (OpenRegister answers that no XWiki source is set + * up or the wiki is down) or `unavailable` (OpenRegister is not there). + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-the-wiki-widget-shows-favourites-recent-pages-and-search-req-wiki-001 + */ +export async function searchWikiPages(query, limit) { + try { + const { data } = await axios.get(generateUrl('/apps/openregister/api/integrations/xwiki/search'), { + params: { q: query, limit }, + }) + const rows = Array.isArray(data?.results) ? data.results : [] + return { state: 'ok', pages: rows.map(wikiPage).filter(Boolean) } + } catch (error) { + const status = error?.response?.status + return { state: status === 503 ? 'not-connected' : 'unavailable', pages: [] } + } +} + +/** + * The person's favourite pages; empty when none are kept or the read fails. + * + * @return {Promise<Array<WikiPage>>} + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-person-keeps-favourite-pages-req-wiki-002 + */ +export async function readWikiFavourites() { + try { + const { data } = await axios.get(generateUrl(`/apps/launchpad/api/preferences/${FAVOURITES_KEY}`)) + const parsed = JSON.parse(data?.value ?? '[]') + return Array.isArray(parsed) ? parsed.map(wikiPage).filter(Boolean) : [] + } catch { + return [] + } +} + +/** + * Keep the person's favourite pages, at most {@link MAX_FAVOURITES}. + * + * @param {Array<WikiPage>} pages The favourites, newest first. + * @return {Promise<Array<WikiPage>>} What was kept. + * @spec openspec/changes/wiki-widget/specs/wiki-widget/spec.md#requirement-a-person-keeps-favourite-pages-req-wiki-002 + */ +export async function saveWikiFavourites(pages) { + const kept = pages.slice(0, MAX_FAVOURITES).map((page) => ({ + reference: page.reference, + title: page.title, + space: page.space, + url: page.url, + })) + await axios.put(generateUrl(`/apps/launchpad/api/preferences/${FAVOURITES_KEY}`), { value: JSON.stringify(kept) }) + return kept +} diff --git a/src/services/workPackages.js b/src/services/workPackages.js new file mode 100644 index 000000000..1d07506e9 --- /dev/null +++ b/src/services/workPackages.js @@ -0,0 +1,36 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The open OpenProject work packages of the work packages widget, from + * launchpad's `/api/work-packages`, which asks the official OpenProject + * integration with the person's own token. + * + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +/** + * Read the open work packages. + * + * @param {{scope: string, project: string, limit: number}} query What to list. + * @return {Promise<{state: string, workPackages: Array<object>, connectUrl?: string}>} + * `state` is `ok`, `not-installed`, `not-connected` or `error`. + * @spec openspec/changes/work-packages-widget/specs/work-packages-widget/spec.md#requirement-the-widget-lists-open-work-packages-due-date-first-req-wp-001 + */ +export async function loadWorkPackages({ scope, project, limit }) { + try { + const { data } = await axios.get(generateUrl('/apps/launchpad/api/work-packages'), { + params: { scope, project, limit }, + }) + return { + state: typeof data?.state === 'string' ? data.state : 'error', + workPackages: Array.isArray(data?.workPackages) ? data.workPackages : [], + connectUrl: typeof data?.connectUrl === 'string' ? generateUrl(data.connectUrl) : '', + } + } catch { + return { state: 'error', workPackages: [], connectUrl: '' } + } +} diff --git a/src/startRedirect.js b/src/startRedirect.js new file mode 100644 index 000000000..3fe67eaaa --- /dev/null +++ b/src/startRedirect.js @@ -0,0 +1,17 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Login-page redirect to the public start page (sharing-public-start-page, + * design D2). Added to the login page by `PublicStartRedirectListener` only + * for a signed-out GET without `redirect_url`, `direct` or `clear`, while the + * start page is on. The target is a fixed same-origin path, never taken from + * the request. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-signed-out-visitors-land-on-the-start-page-req-psp-002 + */ + +import { generateUrl } from '@nextcloud/router' +import { startPageUrl } from './utils/publicStart.js' + +window.location.replace(startPageUrl(generateUrl)) diff --git a/src/stores/__tests__/bootReads.firstLoad.spec.js b/src/stores/__tests__/bootReads.firstLoad.spec.js new file mode 100644 index 000000000..12955dc77 --- /dev/null +++ b/src/stores/__tests__/bootReads.firstLoad.spec.js @@ -0,0 +1,83 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The tiles and the pending acknowledgements: the first read takes what the + * page carries, every later read (and a page without them) asks the API. + * + * @spec openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/tasks.md#task-4 + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { takeBootRead } from '../../utils/loadInitialState.js' +import { useDashboardStore } from '../dashboard.js' +import { useTileStore } from '../tiles.js' + +vi.mock('../../services/api.js', () => ({ + api: { + getTiles: vi.fn(), + getPendingAcknowledgements: vi.fn(), + }, +})) +vi.mock('../../utils/loadInitialState.js', () => ({ + takeBootRead: vi.fn(), + takeDashboardFirstLoad: vi.fn(() => null), +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +beforeEach(() => { + setActivePinia(createPinia()) + vi.resetAllMocks() +}) + +describe('tile store first load', () => { + it('takes the tiles the page carries without asking the API', async () => { + takeBootRead.mockReturnValue([{ id: 7, title: 'Mail' }]) + const store = useTileStore() + + await store.loadTiles() + + expect(takeBootRead).toHaveBeenCalledWith('tiles') + expect(store.tiles).toEqual([{ id: 7, title: 'Mail' }]) + expect(api.getTiles).not.toHaveBeenCalled() + }) + + it('asks the API when the page carries none', async () => { + takeBootRead.mockReturnValue(undefined) + api.getTiles.mockResolvedValue({ data: [{ id: 8 }] }) + const store = useTileStore() + + await store.loadTiles() + + expect(api.getTiles).toHaveBeenCalledTimes(1) + expect(store.tiles).toEqual([{ id: 8 }]) + }) +}) + +describe('pending acknowledgements first load', () => { + it('takes the items the page carries without asking the API', async () => { + takeBootRead.mockReturnValue({ count: 1, items: [{ announcementKey: 'a1' }] }) + const store = useDashboardStore() + + await store.fetchPendingAcknowledgements() + + expect(takeBootRead).toHaveBeenCalledWith('pendingAcknowledgements') + expect(store.pendingAcknowledgements).toEqual([{ announcementKey: 'a1' }]) + expect(api.getPendingAcknowledgements).not.toHaveBeenCalled() + }) + + it('asks the API when the page carries none, or a malformed part', async () => { + takeBootRead.mockReturnValue({ count: 1 }) + api.getPendingAcknowledgements.mockResolvedValue({ data: { items: [{ announcementKey: 'a2' }] } }) + const store = useDashboardStore() + + await store.fetchPendingAcknowledgements() + + expect(api.getPendingAcknowledgements).toHaveBeenCalledTimes(1) + expect(store.pendingAcknowledgements).toEqual([{ announcementKey: 'a2' }]) + }) +}) diff --git a/src/stores/__tests__/dashboard.firstLoad.spec.js b/src/stores/__tests__/dashboard.firstLoad.spec.js new file mode 100644 index 000000000..a0b13e87f --- /dev/null +++ b/src/stores/__tests__/dashboard.firstLoad.spec.js @@ -0,0 +1,133 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The dashboard store's first load comes from the page's initial state + * (dashboard-first-load-from-initial-state): the visible list and the + * active dashboard the page already computed, without asking the API + * again. Every later load, and a page without the key, fetches both. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md#task-4 + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +let pushedState = {} + +vi.mock('@nextcloud/initial-state', () => ({ + loadState: (_app, key, fallback) => (Object.hasOwn(pushedState, key) ? pushedState[key] : fallback), +})) + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() }, +})) + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), +})) + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, str) => str, + translatePlural: (_app, sing, plur, n) => (n === 1 ? sing : plur), +})) + +vi.mock('../../services/api.js', () => ({ + api: { + getDashboards: vi.fn(), + getVisibleDashboards: vi.fn(), + getActiveDashboard: vi.fn(), + }, +})) + +const firstLoad = { + visible: { + items: [{ id: 1, uuid: 'a', name: 'Team', source: 'group', isOwner: false }], + quota: { maxDashboards: 5, dashboardsUsed: 1, maxWidgetsPerDashboard: 40 }, + }, + active: { + dashboard: { id: 1, uuid: 'a', name: 'Team' }, + placements: [{ id: 7, widgetId: 'clock' }], + permissionLevel: 'view_only', + isOwner: false, + sharedBy: null, + hasVariants: false, + }, +} + +let mockApi + +beforeEach(async () => { + vi.resetModules() + setActivePinia(createPinia()) + pushedState = {} + const mod = await import('../../services/api.js') + mockApi = mod.api + for (const fn of Object.values(mockApi)) { + fn.mockReset() + } +}) + +describe('dashboard store — first load from the initial state', () => { + it('fills the list and the active dashboard without asking the API', async () => { + pushedState = { dashboardFirstLoad: firstLoad } + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + + await store.loadDashboards() + + expect(mockApi.getVisibleDashboards).not.toHaveBeenCalled() + expect(mockApi.getActiveDashboard).not.toHaveBeenCalled() + expect(store.dashboards).toHaveLength(1) + expect(store.quota.maxDashboards).toBe(5) + expect(store.activeDashboard.uuid).toBe('a') + expect(store.widgetPlacements).toEqual([{ id: 7, widgetId: 'clock' }]) + expect(store.permissionLevel).toBe('view_only') + expect(store.loadedOnce).toBe(true) + }) + + it('asks the API on every load after the first', async () => { + pushedState = { dashboardFirstLoad: firstLoad } + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + mockApi.getVisibleDashboards.mockResolvedValue({ data: { items: [], quota: null } }) + mockApi.getActiveDashboard.mockResolvedValue({ data: null }) + + await store.loadDashboards() + await store.loadDashboards() + + expect(mockApi.getVisibleDashboards).toHaveBeenCalledTimes(1) + expect(mockApi.getActiveDashboard).toHaveBeenCalledTimes(1) + expect(store.dashboards).toEqual([]) + }) + + it('keeps the list when the page had no active dashboard', async () => { + pushedState = { dashboardFirstLoad: { visible: firstLoad.visible, active: null } } + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + + await store.loadDashboards() + + expect(mockApi.getActiveDashboard).not.toHaveBeenCalled() + expect(store.dashboards).toHaveLength(1) + expect(store.activeDashboard).toBeNull() + }) + + it('fetches both when the page did not carry them', async () => { + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + mockApi.getVisibleDashboards.mockResolvedValue({ data: [{ id: 2, uuid: 'b', source: 'user' }] }) + mockApi.getActiveDashboard.mockResolvedValue({ data: null }) + + await store.loadDashboards() + + expect(mockApi.getVisibleDashboards).toHaveBeenCalledTimes(1) + expect(mockApi.getActiveDashboard).toHaveBeenCalledTimes(1) + expect(store.dashboards).toHaveLength(1) + }) +}) diff --git a/src/stores/__tests__/dashboard.golden.spec.js b/src/stores/__tests__/dashboard.golden.spec.js new file mode 100644 index 000000000..5b68e1e19 --- /dev/null +++ b/src/stores/__tests__/dashboard.golden.spec.js @@ -0,0 +1,450 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for the dashboard store's resolveActive getter and its + * loadDashboards, createDashboard, addWidgetToDashboard and addTileToDashboard + * actions: each case starts from a fresh store, and the result, the state it + * leaves, the API calls, the toasts and the log lines are compared with + * fixtures/dashboard.golden.json. Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { createPinia, setActivePinia } from 'pinia' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), +})) + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, str, vars) => `${str}${vars ? JSON.stringify(vars) : ''}`, + translatePlural: (_app, sing, plur, n) => (n === 1 ? sing : plur), +})) + +vi.mock('../../utils/logger.js', () => ({ + logger: { warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() }, +})) + +vi.mock('../../services/api.js', () => ({ + api: { + getDashboards: vi.fn(), + getVisibleDashboards: vi.fn(), + getActiveDashboard: vi.fn(), + createDashboard: vi.fn(), + addWidget: vi.fn(), + addTile: vi.fn(), + updateWidgetPlacement: vi.fn(), + }, +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/dashboard.golden.json') + +/** + * A rejected request as axios gives it. + * + * @param {number} status The HTTP status. + * @param {object} data The response body. + * @return {Error} The error. + */ +function httpError(status, data) { + return Object.assign(new Error(`Request failed with status ${status}`), { + response: { status, data }, + }) +} + +const ROWS = [ + { id: 1, uuid: 'u1', source: 'user', isDefault: 0 }, + { id: 2, uuid: 'g1', source: 'group', groupId: 'sales', isDefault: 0 }, + { id: 3, uuid: 'g2', source: 'group', groupId: 'sales', isDefault: '1' }, + { id: 4, uuid: 'd1', source: 'default', isDefault: 0 }, + { id: 5, uuid: 'd2', source: 'default', isDefault: 1 }, + { id: 6, uuid: 'g3', source: 'group', groupId: 'hr', isDefault: 1 }, + { id: 7, uuid: 's1', source: 'shared', isDefault: 1 }, +] + +/** + * The rows at the given positions of ROWS. + * + * @param {Array<number>} picks Positions. + * @return {Array<object>} The rows. + */ +function rows(picks) { + return picks.map((index) => ROWS[index]) +} + +const RESOLVE_STATES = { + 'no list': { dashboards: null }, + 'empty list': { dashboards: [] }, + 'active still visible by id': { + dashboards: rows([0, 1, 2]), + activeDashboard: { id: 2 }, + primaryGroup: 'sales', + }, + 'active still visible by uuid': { + dashboards: rows([0, 1]), + activeDashboard: { id: 'g1' }, + }, + 'active id zero': { + dashboards: [{ id: 0, source: 'user' }, ...rows([4])], + activeDashboard: { id: 0 }, + }, + 'active gone': { + dashboards: rows([0, 3]), + activeDashboard: { id: 99 }, + }, + 'active null id': { + dashboards: rows([0, 3]), + activeDashboard: { id: null }, + }, + 'primary group default': { + dashboards: rows([0, 1, 2, 4, 5]), + primaryGroup: 'sales', + }, + 'other group default only': { + dashboards: rows([0, 5, 6]), + primaryGroup: 'sales', + }, + 'default default without primary': { + dashboards: rows([0, 1, 2, 4, 5]), + }, + 'default default after another default-group': { + dashboards: rows([0, 3, 4]), + }, + 'first in primary group': { + dashboards: rows([0, 3, 1, 2]), + primaryGroup: 'sales', + }, + 'first in primary group without defaults': { + dashboards: rows([0, 3, 1]), + primaryGroup: 'sales', + }, + 'primary group without rows': { + dashboards: rows([0, 3, 6]), + primaryGroup: 'finance', + }, + 'first default-group': { dashboards: rows([0, 1, 3]) }, + 'first personal': { dashboards: rows([1, 6, 0]) }, + 'only shared': { dashboards: rows([6]) }, + 'shared default only': { dashboards: rows([1, 6]).concat([ROWS[6]]) }, + 'primary group null': { + dashboards: rows([1, 0]), + primaryGroup: null, + }, +} + +const LOAD_CASES = { + 'visible list with quota': { + visible: { + data: { + items: [{ id: 1 }, { id: 2, source: 'group' }], + quota: { maxDashboards: 5, dashboardsUsed: 2 }, + }, + }, + active: { + data: { + dashboard: { id: 1, name: 'Mine' }, + placements: [{ id: 10 }], + permissionLevel: 'view', + isOwner: false, + sharedBy: 'bob', + hasVariants: true, + }, + }, + }, + 'visible bare array': { + visible: { + data: [ + { id: 1, source: null }, + { id: 3, source: 'default' }, + ], + }, + active: { data: { dashboard: { id: 3 } } }, + }, + 'visible object without items': { + visible: { data: { quota: { maxWidgetsPerDashboard: 9 } } }, + active: { data: null }, + }, + 'visible null payload': { + visible: { data: null }, + active: { data: { dashboard: null, hasVariants: 'yes' } }, + }, + 'visible fails, fallback works': { + visibleError: new Error('visible down'), + fallback: { data: { items: [{ id: 8 }], quota: null } }, + active: { data: { dashboard: { id: 8 }, placements: null } }, + }, + 'both fail': { + visibleError: new Error('visible down'), + fallbackError: new Error('list down'), + }, + 'active fails': { + visible: { data: [{ id: 1 }] }, + activeError: new Error('active down'), + }, + 'items null': { + visible: { data: { items: null, quota: { dashboardsUsed: 1 } } }, + active: {}, + }, +} + +const CREATE_CASES = { + 'string name': { payload: 'Team', answer: { data: { dashboard: { id: 1 } } } }, + 'default name': { + payload: undefined, + answer: { data: { dashboard: { id: 2, source: 'group' }, placements: [] } }, + }, + 'object payload': { + payload: { name: 'Board', description: 'About', icon: 'star' }, + answer: { + data: { dashboard: { id: 3 }, placements: [{ id: 30 }, { id: 31 }] }, + }, + }, + 'object without name or icon': { + payload: { description: null }, + answer: { data: { dashboard: { id: 4, source: null } } }, + }, + 'personal dashboards disabled': { + payload: 'X', + error: httpError(403, { error: 'personal_dashboards_disabled' }), + }, + 'other 403': { payload: 'X', error: httpError(403, { error: 'forbidden' }) }, + 'quota exceeded': { + payload: 'X', + error: httpError(409, { error: 'quota_exceeded', limit: 3 }), + }, + 'other 409': { payload: 'X', error: httpError(409, { error: 'conflict' }) }, + 'no response': { payload: 'X', error: new Error('offline') }, + 'answer without dashboard': { payload: 'X', answer: { data: {} } }, +} + +const WIDGETS = { + 'widget id': 'calendar', + 'custom payload': { type: 'label', content: { text: 'Hi' } }, + 'custom without content': { type: 'text', content: null }, + 'object without type': { kind: 'x' }, + null: null, +} + +const POSITIONS = { + none: null, + explicit: { x: 2, y: 3, w: 5, h: 6 }, + 'explicit without size': { x: 0, y: 0 }, + 'explicit zero size': { x: 1, y: 1, w: 0, h: 0 }, + 'size only': { w: 3, h: 1 }, + 'x only': { x: 4 }, + 'non-finite y': { x: 1, y: Infinity, w: 2 }, + 'zero size only': { w: 0, h: null }, +} + +const STATES = { + empty: { activeDashboard: { id: 7 }, widgetPlacements: [] }, + 'with placements': { + activeDashboard: { id: 7, gridColumns: 6 }, + widgetPlacements: [ + { id: 1, gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 2 }, + { id: 2, gridX: 4, gridY: 1, gridWidth: 2, gridHeight: 5 }, + ], + }, + 'no active dashboard': { activeDashboard: null, widgetPlacements: [] }, +} + +const FAILURES = { + 'widget quota': httpError(409, { + error: 'quota_exceeded', + quota: 'widgets', + limit: 12, + }), + 'other error': new Error('server down'), +} + +/** + * The JSON-safe form of a value: errors as their message, functions dropped. + * + * @param {unknown} value The value. + * @return {unknown} The plain value. + */ +function plain(value) { + return JSON.parse( + JSON.stringify(value, (_key, entry) => + entry instanceof Error ? `Error: ${entry.message}` : entry, + ) ?? 'null', + ) +} + +/** + * Wait for the promises a store action left running. + * + * @return {Promise<void>} + */ +function settle() { + return new Promise((resolve) => setTimeout(resolve, 0)) +} + +/** + * Run one store case on a fresh store and record everything it touched. + * + * @param {object} state The state to start from. + * @param {(store: object) => unknown} run Runs the case. + * @return {Promise<object>} The outcome. + */ +async function outcome(state, run) { + setActivePinia(createPinia()) + const { api } = await import('../../services/api.js') + const { logger } = await import('../../utils/logger.js') + const { showError } = await import('@nextcloud/dialogs') + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + Object.assign(store, state) + let result + try { + result = { value: await run(store) } + } catch (error) { + result = { rejected: error.message } + } + await settle() + const calls = {} + for (const [name, fn] of Object.entries(api)) { + if (fn.mock.calls.length > 0) { + calls[name] = fn.mock.calls + } + } + return plain({ + result, + state: { + dashboards: store.dashboards, + activeDashboard: store.activeDashboard, + widgetPlacements: store.widgetPlacements, + quota: store.quota, + permissionLevel: store.permissionLevel, + loading: store.loading, + }, + calls, + toasts: showError.mock.calls, + warnings: logger.warn.mock.calls, + errors: logger.error.mock.calls, + }) +} + +/** + * Reset every mock, then let the API answer the way one case needs. + * + * @param {object} answers Per API method: `{value}` resolves, `{error}` rejects. + * @return {Promise<void>} + */ +async function answer(answers) { + vi.clearAllMocks() + const { api } = await import('../../services/api.js') + for (const fn of Object.values(api)) { + fn.mockReset() + fn.mockResolvedValue({ data: null }) + } + for (const [name, { value, error }] of Object.entries(answers)) { + if (error) { + api[name].mockRejectedValue(error) + } else { + api[name].mockResolvedValue(value) + } + } +} + +/** + * The API answers of one loadDashboards case. + * + * @param {object} spec The case. + * @return {object} The answers. + */ +function loadAnswers(spec) { + return { + getVisibleDashboards: spec.visibleError + ? { error: spec.visibleError } + : { value: spec.visible }, + getDashboards: spec.fallbackError + ? { error: spec.fallbackError } + : { value: spec.fallback }, + getActiveDashboard: spec.activeError + ? { error: spec.activeError } + : { value: spec.active }, + } +} + +/** + * Record every case of the cases this golden covers. + * + * @return {Promise<object>} The outcomes by case name. + */ +async function record() { + const actual = {} + for (const [name, state] of Object.entries(RESOLVE_STATES)) { + await answer({}) + actual[`resolveActive | ${name}`] = await outcome( + state, + (store) => store.resolveActive, + ) + } + for (const [name, spec] of Object.entries(LOAD_CASES)) { + await answer(loadAnswers(spec)) + actual[`loadDashboards | ${name}`] = await outcome( + { dashboards: [{ id: 'old' }], quota: { maxDashboards: 1 } }, + (store) => store.loadDashboards(), + ) + } + for (const [name, spec] of Object.entries(CREATE_CASES)) { + await answer({ + createDashboard: spec.error + ? { error: spec.error } + : { value: spec.answer }, + getVisibleDashboards: { value: { data: [{ id: 'reloaded' }] } }, + }) + actual[`createDashboard | ${name}`] = await outcome( + { dashboards: [{ id: 0 }] }, + (store) => store.createDashboard(spec.payload), + ) + } + for (const [s, state] of Object.entries(STATES)) { + for (const [p, position] of Object.entries(POSITIONS)) { + for (const [w, widget] of Object.entries(WIDGETS)) { + await answer({ addWidget: { value: { data: { id: 'new' } } } }) + actual[`addWidgetToDashboard | ${s} | ${p} | ${w}`] = await outcome( + structuredClone(state), + (store) => store.addWidgetToDashboard(widget, position), + ) + } + await answer({ addTile: { value: { data: { id: 'tile' } } } }) + actual[`addTileToDashboard | ${s} | ${p}`] = await outcome( + structuredClone(state), + (store) => + store.addTileToDashboard({ title: 'T', icon: 'i' }, position), + ) + } + for (const [f, error] of Object.entries(FAILURES)) { + await answer({ addWidget: { error }, addTile: { error } }) + actual[`addWidgetToDashboard | ${s} | failure | ${f}`] = await outcome( + structuredClone(state), + (store) => store.addWidgetToDashboard('calendar'), + ) + await answer({ addWidget: { error }, addTile: { error } }) + actual[`addTileToDashboard | ${s} | failure | ${f}`] = await outcome( + structuredClone(state), + (store) => store.addTileToDashboard({ title: 'T' }), + ) + } + } + return actual +} + +describe('dashboard store (golden)', () => { + it('matches the recorded results', async () => { + const actual = await record() + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + for (const key of Object.keys(expected)) { + expect(actual[key], key).toEqual(expected[key]) + } + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + }) +}) diff --git a/src/stores/__tests__/dashboard.persistence.spec.js b/src/stores/__tests__/dashboard.persistence.spec.js new file mode 100644 index 000000000..dde1aa5a2 --- /dev/null +++ b/src/stores/__tests__/dashboard.persistence.spec.js @@ -0,0 +1,434 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the dashboard store's persistence actions: + * publish / unpublish, placement saves routed per dashboard source, + * push-down merges, removal of (compulsory) placements, single-placement + * patches, the dashboard tree, view events and metadata fields, plus the + * acknowledgement and lookup getters. + * + * The api module, dialogs, l10n and logger are mocked; nothing else is. + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), +})) + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, str) => str, + translatePlural: (_app, sing, plur, n) => (n === 1 ? sing : plur), +})) + +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +vi.mock('../../services/api.js', () => ({ + api: { + publishDashboard: vi.fn(), + unpublishDashboard: vi.fn(), + updateDashboard: vi.fn(), + updateGroupDashboard: vi.fn(), + removeWidget: vi.fn(), + updateWidgetPlacement: vi.fn(), + getDashboardTree: vi.fn(), + recordDashboardViewEvent: vi.fn(), + getMetadataFields: vi.fn(), + }, +})) + +const { showError } = await import('@nextcloud/dialogs') +const { logger } = await import('../../utils/logger.js') +const { api } = await import('../../services/api.js') +const { LAYOUT_SAVE_RETRY_DELAYS_MS, useDashboardStore } = await import('../dashboard.js') + +describe('dashboard store persistence', () => { + let store + + beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + store = useDashboardStore() + }) + + describe('setGridColumns', () => { + it('stores a personal dashboard\'s columns and shows them at once', async () => { + store.dashboards = [{ id: 4, gridColumns: 12 }, { id: 5, gridColumns: 12 }] + store.activeDashboard = { id: 4, gridColumns: 12, source: 'user' } + api.updateDashboard.mockResolvedValue({ data: {} }) + + await expect(store.setGridColumns(8)).resolves.toBe(true) + + expect(api.updateDashboard).toHaveBeenCalledWith(4, { gridColumns: 8 }) + expect(store.activeDashboard.gridColumns).toBe(8) + expect(store.dashboards).toEqual([{ id: 4, gridColumns: 8 }, { id: 5, gridColumns: 12 }]) + }) + + it('sends a group dashboard\'s columns to the group endpoint', async () => { + store.activeDashboard = { id: 9, uuid: 'g-1', groupId: 'staff', gridColumns: 12, source: 'group' } + api.updateGroupDashboard.mockResolvedValue({ data: {} }) + + await store.setGridColumns(6) + + expect(api.updateGroupDashboard).toHaveBeenCalledWith('staff', 'g-1', { gridColumns: 6 }) + expect(api.updateDashboard).not.toHaveBeenCalled() + }) + + it('puts the old count back and says so when the save is refused', async () => { + store.activeDashboard = { id: 4, gridColumns: 12, source: 'user' } + api.updateDashboard.mockRejectedValue(new Error('403')) + + await expect(store.setGridColumns(8)).resolves.toBe(false) + + expect(store.activeDashboard.gridColumns).toBe(12) + expect(showError).toHaveBeenCalledWith('The number of columns could not be saved.') + }) + + it('does nothing for the current count or without a dashboard', async () => { + await expect(store.setGridColumns(8)).resolves.toBe(false) + store.activeDashboard = { id: 4, gridColumns: 8 } + await expect(store.setGridColumns(8)).resolves.toBe(false) + expect(api.updateDashboard).not.toHaveBeenCalled() + }) + }) + + describe('publishDashboard / unpublishDashboard', () => { + it('patches the listed and active copy with the publication fields only', async () => { + store.dashboards = [{ uuid: 'd1', name: 'Home', publicationStatus: 'draft' }, { uuid: 'd2', name: 'Other' }] + store.activeDashboard = { uuid: 'd1', name: 'Home', publicationStatus: 'draft' } + const returned = { uuid: 'd1', name: 'Renamed', publicationStatus: 'published', publishAt: null, publishedAt: '2026-11-01T10:00:00Z' } + api.publishDashboard.mockResolvedValue({ data: { dashboard: returned } }) + + await expect(store.publishDashboard('d1')).resolves.toBe(returned) + + expect(api.publishDashboard).toHaveBeenCalledWith('d1') + const patched = { uuid: 'd1', name: 'Home', publicationStatus: 'published', publishAt: null, publishedAt: '2026-11-01T10:00:00Z', unpublishAt: null } + expect(store.dashboards).toEqual([patched, { uuid: 'd2', name: 'Other' }]) + expect(store.activeDashboard).toEqual(patched) + }) + + it('answers null without patching when the response carries no dashboard', async () => { + store.dashboards = [{ uuid: 'd1', publicationStatus: 'published' }] + api.unpublishDashboard.mockResolvedValue({ data: {} }) + + await expect(store.unpublishDashboard('d1')).resolves.toBeNull() + expect(store.dashboards).toEqual([{ uuid: 'd1', publicationStatus: 'published' }]) + }) + + it('logs, shows an error and answers null when the call fails', async () => { + const failure = new Error('403') + api.publishDashboard.mockRejectedValue(failure) + api.unpublishDashboard.mockRejectedValue(failure) + + await expect(store.publishDashboard('d1')).resolves.toBeNull() + await expect(store.unpublishDashboard('d1')).resolves.toBeNull() + + expect(logger.error).toHaveBeenCalledWith('Failed to publish dashboard:', failure) + expect(logger.error).toHaveBeenCalledWith('Failed to unpublish dashboard:', failure) + expect(showError).toHaveBeenNthCalledWith(1, 'Publish dashboard') + expect(showError).toHaveBeenNthCalledWith(2, 'Unpublish dashboard') + }) + }) + + describe('updatePlacements', () => { + const placements = [ + { id: 1, gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 2, title: 'A' }, + { id: 2, gridX: 4, gridY: 0, gridWidth: 2, gridHeight: 3, title: 'B' }, + ] + const geometry = [ + { id: 1, gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 2 }, + { id: 2, gridX: 4, gridY: 0, gridWidth: 2, gridHeight: 3 }, + ] + + it('saves a personal dashboard through its own endpoint with geometry only', async () => { + store.activeDashboard = { id: 7, uuid: 'u7', source: 'user' } + api.updateDashboard.mockResolvedValue({ data: {} }) + + await store.updatePlacements(placements) + + expect(store.widgetPlacements).toStrictEqual(placements) + expect(api.updateDashboard).toHaveBeenCalledWith(7, { placements: geometry }) + expect(api.updateGroupDashboard).not.toHaveBeenCalled() + expect(store.saving).toBe(false) + }) + + it.each(['group', 'default'])('saves a %s dashboard through the group endpoint', async (source) => { + store.activeDashboard = { id: 7, uuid: 'u7', groupId: 'staff', source } + api.updateGroupDashboard.mockResolvedValue({ data: {} }) + + await store.updatePlacements(placements) + + expect(api.updateGroupDashboard).toHaveBeenCalledWith('staff', 'u7', { placements: geometry }) + expect(api.updateDashboard).not.toHaveBeenCalled() + }) + + it('keeps the local layout, reports the failure and retries three times', async () => { + vi.useFakeTimers() + try { + store.activeDashboard = { id: 7, source: 'user' } + const failure = new Error('500') + api.updateDashboard.mockRejectedValue(failure) + + const done = store.updatePlacements(placements) + await vi.runAllTimersAsync() + await done + + expect(store.widgetPlacements).toStrictEqual(placements) + expect(store.saving).toBe(false) + expect(api.updateDashboard).toHaveBeenCalledTimes(1 + LAYOUT_SAVE_RETRY_DELAYS_MS.length) + expect(logger.error).toHaveBeenCalledWith('Failed to save placements:', failure) + expect(showError).toHaveBeenNthCalledWith(1, 'The layout could not be saved. Trying again.') + expect(showError).toHaveBeenLastCalledWith('The layout could not be saved.') + expect(showError).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + } + }) + + it('stops retrying once a retry saves, without a second notice', async () => { + vi.useFakeTimers() + try { + store.activeDashboard = { id: 7, source: 'user' } + api.updateDashboard.mockRejectedValueOnce(new Error('500')).mockResolvedValue({ data: {} }) + + const done = store.updatePlacements(placements) + await vi.runAllTimersAsync() + await done + + expect(api.updateDashboard).toHaveBeenCalledTimes(2) + expect(showError).toHaveBeenCalledTimes(1) + expect(store.saving).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + it('drops the retries of an older layout once a newer one is saved', async () => { + vi.useFakeTimers() + try { + store.activeDashboard = { id: 7, source: 'user' } + api.updateDashboard.mockRejectedValueOnce(new Error('500')).mockResolvedValue({ data: {} }) + + const older = store.updatePlacements(placements) + await vi.advanceTimersByTimeAsync(0) + const newer = store.updatePlacements(placements.slice(0, 1)) + await vi.runAllTimersAsync() + await Promise.all([older, newer]) + + // The failed first save and the newer save; no retry of the older. + expect(api.updateDashboard).toHaveBeenCalledTimes(2) + expect(api.updateDashboard).toHaveBeenLastCalledWith(7, { placements: geometry.slice(0, 1) }) + expect(store.saving).toBe(false) + } finally { + vi.useRealTimers() + } + }) + }) + + describe('applyPushedPlacements', () => { + it('does nothing for an empty or missing push list', async () => { + await store.applyPushedPlacements([]) + await store.applyPushedPlacements(undefined) + + expect(api.updateDashboard).not.toHaveBeenCalled() + }) + + it('moves only the pushed placements down, matching ids as strings, in one save', async () => { + store.activeDashboard = { id: 3, source: 'user' } + store.widgetPlacements = [ + { id: 1, gridX: 0, gridY: 0, gridWidth: 2, gridHeight: 2 }, + { id: 2, gridX: 0, gridY: 2, gridWidth: 2, gridHeight: 2 }, + ] + api.updateDashboard.mockResolvedValue({ data: {} }) + + await store.applyPushedPlacements([{ id: '2', gridY: 5 }]) + + expect(store.widgetPlacements.map((p) => p.gridY)).toEqual([0, 5]) + expect(api.updateDashboard).toHaveBeenCalledTimes(1) + expect(api.updateDashboard.mock.calls[0][1].placements[1]).toEqual({ id: 2, gridX: 0, gridY: 5, gridWidth: 2, gridHeight: 2 }) + }) + }) + + describe('removeWidgetFromDashboard', () => { + it('refuses a compulsory placement without full permission', async () => { + store.widgetPlacements = [{ id: 1, isCompulsory: true }] + store.permissionLevel = 'add_only' + + await store.removeWidgetFromDashboard(1) + + expect(api.removeWidget).not.toHaveBeenCalled() + expect(logger.warn).toHaveBeenCalledWith('Cannot remove compulsory widget') + expect(store.widgetPlacements).toHaveLength(1) + }) + + it('removes a compulsory placement with full permission', async () => { + store.widgetPlacements = [{ id: 1, isCompulsory: true }, { id: 2 }] + api.removeWidget.mockResolvedValue({}) + + await store.removeWidgetFromDashboard(1) + + expect(api.removeWidget).toHaveBeenCalledWith(1) + expect(store.widgetPlacements).toEqual([{ id: 2 }]) + }) + + it('keeps the placement when the delete fails', async () => { + store.widgetPlacements = [{ id: 2 }] + const failure = new Error('gone') + api.removeWidget.mockRejectedValue(failure) + + await store.removeWidgetFromDashboard(2) + + expect(store.widgetPlacements).toEqual([{ id: 2 }]) + expect(logger.error).toHaveBeenCalledWith('Failed to remove widget:', failure) + }) + }) + + describe('updateWidgetPlacement', () => { + it('replaces the placement with the server copy', async () => { + store.widgetPlacements = [{ id: 1, title: 'old' }, { id: 2, title: 'x' }] + api.updateWidgetPlacement.mockResolvedValue({ data: { id: 2, title: 'new' } }) + + await store.updateWidgetPlacement(2, { title: 'new' }) + + expect(api.updateWidgetPlacement).toHaveBeenCalledWith(2, { title: 'new' }) + expect(store.widgetPlacements).toEqual([{ id: 1, title: 'old' }, { id: 2, title: 'new' }]) + }) + + it('leaves the list alone for an unknown placement', async () => { + store.widgetPlacements = [{ id: 1 }] + api.updateWidgetPlacement.mockResolvedValue({ data: { id: 9 } }) + + await store.updateWidgetPlacement(9, {}) + + expect(store.widgetPlacements).toEqual([{ id: 1 }]) + }) + + it('logs the failure and its response body', async () => { + const failure = Object.assign(new Error('422'), { response: { data: { message: 'bad' } } }) + api.updateWidgetPlacement.mockRejectedValue(failure) + + await store.updateWidgetPlacement(1, {}) + + expect(logger.error).toHaveBeenCalledWith('Failed to update widget placement:', failure) + expect(logger.error).toHaveBeenCalledWith('Error details:', { message: 'bad' }) + }) + }) + + describe('loadDashboardTree', () => { + it('stores an array answer and anything else as empty', async () => { + api.getDashboardTree.mockResolvedValueOnce({ data: [{ uuid: 'root', children: [] }] }) + await store.loadDashboardTree() + expect(store.dashboardTree).toEqual([{ uuid: 'root', children: [] }]) + + api.getDashboardTree.mockResolvedValueOnce({ data: { tree: [] } }) + await store.loadDashboardTree() + expect(store.dashboardTree).toEqual([]) + }) + + it('empties the tree when loading fails', async () => { + store.dashboardTree = [{ uuid: 'stale' }] + const failure = new Error('down') + api.getDashboardTree.mockRejectedValue(failure) + + await store.loadDashboardTree() + + expect(store.dashboardTree).toEqual([]) + expect(logger.error).toHaveBeenCalledWith('Failed to load dashboard tree:', failure) + }) + }) + + describe('recordViewEvent', () => { + it('skips an empty uuid and records a given one', async () => { + api.recordDashboardViewEvent.mockResolvedValue({}) + + await store.recordViewEvent('') + await store.recordViewEvent('d1') + + expect(api.recordDashboardViewEvent).toHaveBeenCalledTimes(1) + expect(api.recordDashboardViewEvent).toHaveBeenCalledWith('d1') + }) + + it('only warns when recording fails', async () => { + const failure = new Error('offline') + api.recordDashboardViewEvent.mockRejectedValue(failure) + + await expect(store.recordViewEvent('d1')).resolves.toBeUndefined() + expect(logger.warn).toHaveBeenCalledWith('Failed to record dashboard view event:', failure) + }) + }) + + describe('fetchMetadataFields', () => { + it('accepts a wrapped list, a bare list, and treats anything else as empty', async () => { + api.getMetadataFields.mockResolvedValueOnce({ data: { fields: [{ key: 'owner' }] } }) + await store.fetchMetadataFields() + expect(store.metadataFields).toEqual([{ key: 'owner' }]) + + api.getMetadataFields.mockResolvedValueOnce({ data: [{ key: 'topic' }] }) + await store.fetchMetadataFields() + expect(store.metadataFields).toEqual([{ key: 'topic' }]) + + api.getMetadataFields.mockResolvedValueOnce({ data: 'nope' }) + await store.fetchMetadataFields() + expect(store.metadataFields).toEqual([]) + }) + + it('is silent for a forbidden answer and logs any other failure', async () => { + api.getMetadataFields.mockRejectedValueOnce({ response: { status: 403 } }) + await store.fetchMetadataFields() + expect(logger.error).not.toHaveBeenCalled() + + const failure = { response: { status: 500 } } + api.getMetadataFields.mockRejectedValueOnce(failure) + store.metadataFields = [{ key: 'stale' }] + await store.fetchMetadataFields() + expect(logger.error).toHaveBeenCalledWith('Failed to load metadata fields:', failure) + expect(store.metadataFields).toEqual([]) + }) + }) + + describe('getters', () => { + it('finds placements by id and lists the compulsory ones', () => { + store.widgetPlacements = [{ id: 1, isCompulsory: true }, { id: 2 }] + + expect(store.getPlacementById(2)).toEqual({ id: 2 }) + expect(store.getPlacementById(3)).toBeUndefined() + expect(store.compulsoryPlacements).toEqual([{ id: 1, isCompulsory: true }]) + }) + + it('counts outstanding acknowledgements and collects their keys', () => { + store.pendingAcknowledgements = [{ announcementKey: 'a' }, { announcementKey: '' }, { announcementKey: 'b' }] + + expect(store.outstandingAcknowledgementCount).toBe(3) + expect([...store.pendingAnnouncementKeys]).toEqual(['a', 'b']) + }) + + it('marks a placement outstanding only when it requires acknowledgement of a pending key', () => { + store.pendingAcknowledgements = [{ announcementKey: 'a' }] + + expect(store.isPlacementOutstanding({ requiresAcknowledgement: '1', announcementKey: 'a' })).toBe(true) + expect(store.isPlacementOutstanding({ requiresAcknowledgement: 1, announcementKey: 'b' })).toBe(false) + expect(store.isPlacementOutstanding({ requiresAcknowledgement: 1 })).toBe(false) + expect(store.isPlacementOutstanding({ requiresAcknowledgement: 0, announcementKey: 'a' })).toBe(false) + expect(store.isPlacementOutstanding(null)).toBe(false) + }) + + it('answers cached metadata or an empty object, and sorts fields by order then label', () => { + store.metadataByDashboard = { d1: { owner: 'x' } } + store.metadataFields = [ + { label: 'Zeta', sortOrder: 1 }, + { label: 'beta', sortOrder: 2 }, + { label: 'Alpha', sortOrder: 1 }, + { label: 'Gamma' }, + ] + + expect(store.metadataFor('d1')).toEqual({ owner: 'x' }) + expect(store.metadataFor('d2')).toEqual({}) + expect(store.metadataFieldsSorted.map((f) => f.label)).toEqual(['Gamma', 'Alpha', 'Zeta', 'beta']) + }) + }) +}) diff --git a/src/stores/__tests__/dashboard.reactions.spec.js b/src/stores/__tests__/dashboard.reactions.spec.js new file mode 100644 index 000000000..7b0c2eb62 --- /dev/null +++ b/src/stores/__tests__/dashboard.reactions.spec.js @@ -0,0 +1,127 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the dashboard store's reaction actions + * (REQ-RXN-001..003): the cached summary per dashboard, the missing-input + * guards, and how failures are reported. + */ + +import { showError } from '@nextcloud/dialogs' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { useDashboardStore } from '../dashboard.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), +})) + +vi.mock('../../utils/logger.js', () => ({ + logger: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() }, +})) + +vi.mock('../../services/api.js', () => ({ + api: { + getDashboardReactions: vi.fn(), + addDashboardReaction: vi.fn(), + removeDashboardReaction: vi.fn(), + }, +})) + +beforeEach(() => { + setActivePinia(createPinia()) + vi.resetAllMocks() +}) + +describe('dashboard store reactions', () => { + it('caches the fetched summary per dashboard', async () => { + const store = useDashboardStore() + store.reactionsSummary = { other: { '👍': 1 } } + api.getDashboardReactions.mockResolvedValue({ data: { '🎉': 2 } }) + + const summary = await store.fetchReactionsSummary('d-1') + + expect(api.getDashboardReactions).toHaveBeenCalledWith('d-1') + expect(summary).toEqual({ '🎉': 2 }) + expect(store.reactionsSummary).toEqual({ + other: { '👍': 1 }, + 'd-1': { '🎉': 2 }, + }) + }) + + it('returns null without a dashboard or when the fetch fails', async () => { + const store = useDashboardStore() + + expect(await store.fetchReactionsSummary('')).toBeNull() + expect(api.getDashboardReactions).not.toHaveBeenCalled() + + api.getDashboardReactions.mockRejectedValue(new Error('down')) + expect(await store.fetchReactionsSummary('d-1')).toBeNull() + expect(store.reactionsSummary).toEqual({}) + }) + + it('adding a reaction stores the returned summary', async () => { + const store = useDashboardStore() + api.addDashboardReaction.mockResolvedValue({ data: { '👍': 3 } }) + + const summary = await store.addReaction('d-1', '👍') + + expect(api.addDashboardReaction).toHaveBeenCalledWith('d-1', '👍') + expect(summary).toEqual({ '👍': 3 }) + expect(store.reactionsSummary['d-1']).toEqual({ '👍': 3 }) + }) + + it('adding or removing needs both a dashboard and an emoji', async () => { + const store = useDashboardStore() + + expect(await store.addReaction('d-1', '')).toBeNull() + expect(await store.addReaction('', '👍')).toBeNull() + expect(await store.removeReaction('d-1', '')).toBeNull() + expect(api.addDashboardReaction).not.toHaveBeenCalled() + expect(api.removeDashboardReaction).not.toHaveBeenCalled() + }) + + it('a failed add shows the server error, else a generic one', async () => { + const store = useDashboardStore() + api.addDashboardReaction.mockRejectedValueOnce({ + response: { data: { error: 'Unknown emoji' } }, + }) + expect(await store.addReaction('d-1', '🦄')).toBeNull() + expect(showError).toHaveBeenLastCalledWith('Unknown emoji') + + api.addDashboardReaction.mockRejectedValueOnce(new Error('x')) + expect(await store.addReaction('d-1', '🦄')).toBeNull() + expect(showError).toHaveBeenLastCalledWith('Operation failed') + expect(store.reactionsSummary).toEqual({}) + }) + + it('removing a reaction refetches the summary', async () => { + const store = useDashboardStore() + api.removeDashboardReaction.mockResolvedValue({}) + api.getDashboardReactions.mockResolvedValue({ data: { '👍': 0 } }) + + const summary = await store.removeReaction('d-1', '👍') + + expect(api.removeDashboardReaction).toHaveBeenCalledWith('d-1', '👍') + expect(api.getDashboardReactions).toHaveBeenCalledWith('d-1') + expect(summary).toEqual({ '👍': 0 }) + expect(store.reactionsSummary['d-1']).toEqual({ '👍': 0 }) + }) + + it('a failed remove shows the error and does not refetch', async () => { + const store = useDashboardStore() + api.removeDashboardReaction.mockRejectedValue({ + response: { data: { error: 'Not yours' } }, + }) + + expect(await store.removeReaction('d-1', '👍')).toBeNull() + expect(showError).toHaveBeenCalledWith('Not yours') + expect(api.getDashboardReactions).not.toHaveBeenCalled() + }) +}) diff --git a/src/stores/__tests__/dashboard.spec.js b/src/stores/__tests__/dashboard.spec.js index 259fb63be..5944add97 100644 --- a/src/stores/__tests__/dashboard.spec.js +++ b/src/stores/__tests__/dashboard.spec.js @@ -170,6 +170,20 @@ describe('useDashboardStore — source-aware getters', () => { }) }) +describe('useDashboardStore — createDashboard widgets choice (REQ-SHELL-005)', () => { + it('sends the widgets choice only when one is given', async () => { + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + mockApi.createDashboard.mockResolvedValue({ data: { dashboard: { id: 1 }, placements: [] } }) + + await store.createDashboard({ name: 'Mine', widgets: 'starters' }) + await store.createDashboard({ name: 'Plain' }) + + expect(mockApi.createDashboard.mock.calls[0][0]).toEqual({ name: 'Mine', description: undefined, icon: null, widgets: 'starters' }) + expect(mockApi.createDashboard.mock.calls[1][0]).not.toHaveProperty('widgets') + }) +}) + describe('useDashboardStore — createDashboard gating (REQ-ASET-003 extended)', () => { beforeEach(async () => { const { showError } = await import('@nextcloud/dialogs') @@ -283,6 +297,28 @@ describe('useDashboardStore — forkDashboard (REQ-DASH-020)', () => { expect(showError).toHaveBeenCalledWith('Dashboard not found') }) + it('names the dashboard limit and rereads the quota on a quota 409 (REQ-QUOTA-006)', async () => { + const { showError } = await import('@nextcloud/dialogs') + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + + const err = new Error('Conflict') + err.response = { + status: 409, + data: { error: 'quota_exceeded', quota: 'dashboards', limit: 5, current: 5 }, + } + mockApi.forkDashboard.mockRejectedValue(err) + mockApi.getVisibleDashboards.mockResolvedValue({ + data: { items: [], quota: { maxDashboards: 5, dashboardsUsed: 5, maxWidgetsPerDashboard: 0 } }, + }) + + await expect(store.forkDashboard('src-uuid')).rejects.toBe(err) + expect(showError).toHaveBeenCalledWith( + 'You have reached the limit of {limit} dashboards', + ) + expect(mockApi.getVisibleDashboards).toHaveBeenCalled() + }) + it('shows the generic fork-failure toast on unrelated errors', async () => { const { showError } = await import('@nextcloud/dialogs') const { useDashboardStore } = await import('../dashboard.js') @@ -335,6 +371,27 @@ describe('useDashboardStore — loadDashboards source plumbing', () => { expect(store.dashboards[2].source).toBe('default') }) + it('asks for the active dashboard without waiting for the list', async () => { + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + + let answerList + mockApi.getVisibleDashboards.mockReturnValue(new Promise((resolve) => { + answerList = resolve + })) + mockApi.getActiveDashboard.mockResolvedValue({ data: { dashboard: { id: 1, uuid: 'a' }, placements: [{ id: 9 }] } }) + + const load = store.loadDashboards() + await Promise.resolve() + expect(mockApi.getActiveDashboard).toHaveBeenCalledTimes(1) + + answerList({ data: [{ id: 1, uuid: 'a', source: 'user', name: 'Mine' }] }) + await load + + expect(store.dashboards).toHaveLength(1) + expect(store.widgetPlacements).toEqual([{ id: 9 }]) + }) + it('falls back to /api/dashboards and tags rows as `source: "user"`', async () => { const { useDashboardStore } = await import('../dashboard.js') const store = useDashboardStore() @@ -486,6 +543,51 @@ describe('useDashboardStore — persistActivePreference (REQ-DASH-019)', () => { }) }) +describe('useDashboardStore — a dashboard the address names', () => { + it('is opened after the first load, so the stored preference does not replace it', async () => { + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + + mockApi.getVisibleDashboards.mockResolvedValue({ + data: [ + { id: 35, uuid: 'linked', source: 'user', name: 'Route check' }, + { id: 36, uuid: 'stored', source: 'user', name: 'Andere' }, + ], + }) + mockApi.getActiveDashboard.mockResolvedValue({ + data: { dashboard: { id: 36, uuid: 'stored' }, placements: [{ id: 9 }], permissionLevel: 'full' }, + }) + mockApi.getDashboardById.mockResolvedValue({ + data: { dashboard: { id: 35, uuid: 'linked' }, placements: [], permissionLevel: 'full', isOwner: true }, + }) + mockApi.activateDashboard.mockResolvedValue({ data: {} }) + mockApi.setActiveDashboardPreference.mockResolvedValue({ data: {} }) + + await store.openDashboard('35') + expect(mockApi.getDashboardById).not.toHaveBeenCalled() + await store.loadDashboards() + + expect(store.activeDashboard.uuid).toBe('linked') + expect(store.widgetPlacements).toEqual([]) + expect(mockApi.setActiveDashboardPreference).toHaveBeenCalledWith('linked') + }) + + it('is opened at once when the first load has finished', async () => { + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + store.loadedOnce = true + mockApi.getDashboardById.mockResolvedValue({ + data: { dashboard: { id: 35, uuid: 'linked' }, placements: [], permissionLevel: 'full', isOwner: true }, + }) + mockApi.setActiveDashboardPreference.mockResolvedValue({ data: {} }) + + await store.openDashboard(35) + + expect(store.activeDashboard.uuid).toBe('linked') + expect(store.requestedDashboardId).toBeNull() + }) +}) + describe('useDashboardStore — switchDashboard wires the active-pref POST', () => { it('calls setActiveDashboardPreference with the new uuid after a successful switch', async () => { const { useDashboardStore } = await import('../dashboard.js') diff --git a/src/stores/__tests__/dashboard.visibility.spec.js b/src/stores/__tests__/dashboard.visibility.spec.js new file mode 100644 index 000000000..38772916b --- /dev/null +++ b/src/stores/__tests__/dashboard.visibility.spec.js @@ -0,0 +1,103 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the dashboard store's refresh of the widgets the + * visibility rules hide for viewers (REQ-VIS-013): the flag is copied onto + * the loaded placements and the layout itself is left alone. + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' +import { useDashboardStore } from '../dashboard.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), +})) + +vi.mock('../../utils/logger.js', () => ({ + logger: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() }, +})) + +vi.mock('../../services/api.js', () => ({ + api: { + getDashboardById: vi.fn(), + }, +})) + +beforeEach(() => { + setActivePinia(createPinia()) + vi.resetAllMocks() +}) + +describe('dashboard store widget visibility', () => { + it('copies hiddenForViewers onto the loaded placements and keeps their layout', async () => { + const store = useDashboardStore() + store.activeDashboard = { id: 7 } + store.widgetPlacements = [ + { id: 1, gridX: 4, hiddenForViewers: false }, + { id: 2, gridX: 0, hiddenForViewers: true }, + { id: 3, gridX: 8 }, + ] + api.getDashboardById.mockResolvedValue({ + data: { + placements: [ + { id: 1, gridX: 0, hiddenForViewers: true }, + { id: 2, gridX: 0, hiddenForViewers: false }, + ], + }, + }) + + await store.refreshPlacementVisibility() + + expect(api.getDashboardById).toHaveBeenCalledWith(7) + expect(store.widgetPlacements).toEqual([ + { id: 1, gridX: 4, hiddenForViewers: true }, + { id: 2, gridX: 0, hiddenForViewers: false }, + { id: 3, gridX: 8 }, + ]) + }) + + it('does nothing without an active dashboard', async () => { + const store = useDashboardStore() + + await store.refreshPlacementVisibility() + + expect(api.getDashboardById).not.toHaveBeenCalled() + }) + + it('logs a failed read and leaves the placements as they were', async () => { + const store = useDashboardStore() + store.activeDashboard = { id: 7 } + store.widgetPlacements = [{ id: 1, hiddenForViewers: true }] + api.getDashboardById.mockRejectedValue(new Error('down')) + + await store.refreshPlacementVisibility() + + expect(logger.error).toHaveBeenCalled() + expect(store.widgetPlacements).toEqual([{ id: 1, hiddenForViewers: true }]) + }) + + it('reloads the active placements in place, and keeps them when the read fails', async () => { + const store = useDashboardStore() + store.activeDashboard = { id: 7 } + store.widgetPlacements = [{ id: 1, content: { text: 'old' } }] + api.getDashboardById.mockResolvedValueOnce({ data: { placements: [{ id: 1, content: { text: 'new' } }] } }) + + await store.reloadPlacements() + expect(store.widgetPlacements).toEqual([{ id: 1, content: { text: 'new' } }]) + expect(store.loading).toBe(false) + + api.getDashboardById.mockRejectedValueOnce(new Error('down')) + await store.reloadPlacements() + expect(store.widgetPlacements).toEqual([{ id: 1, content: { text: 'new' } }]) + expect(logger.error).toHaveBeenCalled() + }) +}) diff --git a/src/stores/__tests__/dashboardActions.golden.spec.js b/src/stores/__tests__/dashboardActions.golden.spec.js new file mode 100644 index 000000000..ab7b14cb4 --- /dev/null +++ b/src/stores/__tests__/dashboardActions.golden.spec.js @@ -0,0 +1,331 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for the dashboard store's forkDashboard, applyPublicationPatch, + * effectivePublicationStatus, dashboardByPath, fetchDashboardMetadata and updateDashboardMetadata + * actions: each case starts from a fresh store, and the result, the state it + * leaves, the API calls, the toasts and the log lines are compared with + * fixtures/dashboardActions.golden.json. Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { createPinia, setActivePinia } from 'pinia' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), +})) + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, str, vars) => `${str}${vars ? JSON.stringify(vars) : ''}`, + translatePlural: (_app, sing, plur, n) => (n === 1 ? sing : plur), +})) + +vi.mock('../../utils/logger.js', () => ({ + logger: { warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() }, +})) + +vi.mock('../../services/api.js', () => ({ + api: { + activateDashboard: vi.fn(), + forkDashboard: vi.fn(), + getDashboardById: vi.fn(), + getDashboardByPath: vi.fn(), + getDashboardMetadata: vi.fn(), + setActiveDashboardPreference: vi.fn(), + updateDashboardMetadata: vi.fn(), + }, +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/dashboardActions.golden.json') + +/** + * A rejected request as axios gives it. + * + * @param {number} status The HTTP status. + * @param {object} data The response body. + * @return {Error} The error. + */ +function httpError(status, data) { + return Object.assign(new Error(`Request failed with status ${status}`), { + response: { status, data }, + }) +} + +const FAILURES = { + 'personal dashboards disabled': httpError(403, { + error: 'personal_dashboards_disabled', + }), + 'other 403': httpError(403, { error: 'forbidden' }), + '403 without body': httpError(403, null), + 'not found': httpError(404, {}), + 'server error with message': httpError(500, { message: 'Bad key' }), + 'validation with empty message': httpError(400, { message: '' }), + 'no response': new Error('offline'), + null: null, +} + +const START = { + dashboards: [{ id: 1, uuid: 'a', publicationStatus: 'draft' }], + activeDashboard: { id: 1, uuid: 'a' }, + widgetPlacements: [{ id: 9 }], + permissionLevel: 'view', + metadataByDashboard: { old: { k: 'v' } }, + pathCache: { cached: { id: 'hit' }, nulled: null }, +} + +const FORK_ANSWERS = { + 'fork with dashboard': { + data: { dashboard: { id: 2, uuid: 'b', name: 'Copy' } }, + }, + 'fork without dashboard': { data: {} }, + 'no data': { data: null }, + 'no response': undefined, +} + +const PATCHES = { + null: null, + 'no uuid': { publicationStatus: 'published' }, + 'active and listed': { + uuid: 'a', + publicationStatus: 'scheduled', + publishAt: '2030-01-01', + publishedAt: null, + unpublishAt: '2031-01-01', + extra: 'ignored', + }, + 'listed without unpublish': { uuid: 'a', publicationStatus: 'published' }, + 'unknown uuid': { uuid: 'zz', publicationStatus: 'draft', unpublishAt: null }, +} + +const PATCH_STATES = { + start: {}, + 'active differs': { activeDashboard: { uuid: 'other' } }, + 'no active': { activeDashboard: null }, + 'active only': { dashboards: [], activeDashboard: { uuid: 'a', name: 'A' } }, +} + +const STATUS_CASES = { + null: null, + 'no status': {}, + draft: { publicationStatus: 'draft' }, + published: { publicationStatus: 'published' }, + 'scheduled without date': { publicationStatus: 'scheduled' }, + 'scheduled past': { + publicationStatus: 'scheduled', + publishAt: '2026-01-01T00:00:00Z', + }, + 'scheduled exactly now': { + publicationStatus: 'scheduled', + publishAt: '2026-06-01T12:00:00Z', + }, + 'scheduled future': { + publicationStatus: 'scheduled', + publishAt: '2027-01-01T00:00:00Z', + }, + 'scheduled invalid date': { publicationStatus: 'scheduled', publishAt: 'soon' }, +} + +const PATHS = { + undefined, + empty: '', + slashes: '///', + trimmed: '/team/sales/', + 'double trailing': 'team//', + cached: 'cached', + 'cached null': '/nulled', + number: 42, +} + +const PATH_ANSWERS = { + found: { data: { dashboard: { id: 5 } } }, + 'no dashboard': { data: {} }, + 'no data': {}, + 'no response': undefined, +} + +const METADATA_ANSWERS = { + map: { data: { a: '1', b: 2 } }, + array: { data: ['x'] }, + string: { data: 'text' }, + number: { data: 5 }, + null: { data: null }, + 'no response': undefined, +} + +/** + * The JSON-safe form of a value: errors as their message, undefined as a tag. + * + * @param {unknown} value The value. + * @return {unknown} The plain value. + */ +function plain(value) { + return JSON.parse( + JSON.stringify(value, (_key, entry) => { + if (entry instanceof Error) { + return `Error: ${entry.message}` + } + return entry === undefined ? '(undefined)' : entry + }) ?? 'null', + ) +} + +/** + * Run one store case on a fresh store and record everything it touched. + * + * @param {object} state The state to start from. + * @param {(store: object) => unknown} run Runs the case. + * @return {Promise<object>} The outcome. + */ +async function outcome(state, run) { + setActivePinia(createPinia()) + const { api } = await import('../../services/api.js') + const { logger } = await import('../../utils/logger.js') + const { showError } = await import('@nextcloud/dialogs') + const { useDashboardStore } = await import('../dashboard.js') + const store = useDashboardStore() + Object.assign(store, structuredClone({ ...START, ...state })) + let result + try { + result = { value: await run(store) } + } catch (error) { + result = { rejected: error === null ? 'null' : error.message } + } + const calls = {} + for (const [name, fn] of Object.entries(api)) { + if (fn.mock.calls.length > 0) { + calls[name] = fn.mock.calls + } + } + return plain({ + result, + state: { + dashboards: store.dashboards, + activeDashboard: store.activeDashboard, + widgetPlacements: store.widgetPlacements, + permissionLevel: store.permissionLevel, + loading: store.loading, + metadataByDashboard: store.metadataByDashboard, + pathCache: store.pathCache, + }, + calls, + toasts: showError.mock.calls, + errors: logger.error.mock.calls, + }) +} + +/** + * Reset every mock, then let one API method resolve or reject. + * + * @param {string} name The API method. + * @param {{value?: unknown, error?: unknown}} answer Resolves with value, or rejects with error. + * @return {Promise<void>} + */ +async function answer(name, answer) { + vi.clearAllMocks() + const { api } = await import('../../services/api.js') + for (const fn of Object.values(api)) { + fn.mockReset() + } + // A fork switches to the new dashboard and loads its placements. + api.activateDashboard.mockResolvedValue({ data: {} }) + api.setActiveDashboardPreference.mockResolvedValue({ data: {} }) + api.getDashboardById.mockImplementation(async (id) => ({ + data: { dashboard: { id, uuid: 'b', name: 'Copy' }, isOwner: true, placements: [{ id: 7 }] }, + })) + if ('error' in answer) { + api[name].mockRejectedValue(answer.error) + } else { + api[name].mockResolvedValue(answer.value) + } +} + +/** + * Every API answer of one action: the resolved answers, then the failures. + * + * @param {object} answers Resolved answers by case name. + * @return {Array<Array>} Pairs of case name and answer. + */ +function answersAndFailures(answers) { + return [ + ...Object.entries(answers).map(([name, value]) => [name, { value }]), + ...Object.entries(FAILURES).map(([name, error]) => [ + `fails: ${name}`, + { error }, + ]), + ] +} + +/** + * Record every case of the actions this golden covers. + * + * @return {Promise<object>} The outcomes by case name. + */ +async function record() { + const actual = {} + for (const [name, reply] of answersAndFailures(FORK_ANSWERS)) { + await answer('forkDashboard', reply) + actual[`forkDashboard | ${name}`] = await outcome({}, (store) => + store.forkDashboard('src', name.startsWith('fails') ? null : 'Mine'), + ) + } + for (const [stateName, state] of Object.entries(PATCH_STATES)) { + for (const [name, patch] of Object.entries(PATCHES)) { + await answer('forkDashboard', { value: undefined }) + actual[`applyPublicationPatch | ${stateName} | ${name}`] = await outcome( + state, + (store) => store.applyPublicationPatch(structuredClone(patch)), + ) + } + } + const now = vi + .spyOn(Date, 'now') + .mockReturnValue(Date.parse('2026-06-01T12:00:00Z')) + for (const [name, dashboard] of Object.entries(STATUS_CASES)) { + actual[`effectivePublicationStatus | ${name}`] = await outcome({}, (store) => + store.effectivePublicationStatus(dashboard), + ) + } + now.mockRestore() + for (const [pathName, value] of Object.entries(PATHS)) { + for (const [name, reply] of answersAndFailures(PATH_ANSWERS)) { + await answer('getDashboardByPath', reply) + actual[`dashboardByPath | ${pathName} | ${name}`] = await outcome( + {}, + (store) => store.dashboardByPath(value), + ) + } + } + for (const uuid of ['', 'old', 'u2']) { + for (const [name, reply] of answersAndFailures(METADATA_ANSWERS)) { + await answer('getDashboardMetadata', reply) + actual[`fetchDashboardMetadata | ${uuid} | ${name}`] = await outcome( + {}, + (store) => store.fetchDashboardMetadata(uuid), + ) + await answer('updateDashboardMetadata', reply) + actual[`updateDashboardMetadata | ${uuid} | ${name}`] = await outcome( + {}, + (store) => store.updateDashboardMetadata(uuid, { k: 'new' }), + ) + } + } + return actual +} + +describe('dashboard store actions (golden)', () => { + it('matches the recorded outcomes case by case', async () => { + const actual = await record() + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const [name, value] of Object.entries(expected)) { + expect(actual[name], name).toEqual(value) + } + }) +}) diff --git a/src/stores/__tests__/fixtures/dashboard.golden.json b/src/stores/__tests__/fixtures/dashboard.golden.json new file mode 100644 index 000000000..4a8afc06c --- /dev/null +++ b/src/stores/__tests__/fixtures/dashboard.golden.json @@ -0,0 +1,8031 @@ +{ + "resolveActive | no list": { + "result": { + "value": null + }, + "state": { + "dashboards": null, + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | empty list": { + "result": { + "value": null + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | active still visible by id": { + "result": { + "value": { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + }, + { + "id": 3, + "uuid": "g2", + "source": "group", + "groupId": "sales", + "isDefault": "1" + } + ], + "activeDashboard": { + "id": 2 + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | active still visible by uuid": { + "result": { + "value": { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + } + ], + "activeDashboard": { + "id": "g1" + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | active id zero": { + "result": { + "value": { + "id": 0, + "source": "user" + } + }, + "state": { + "dashboards": [ + { + "id": 0, + "source": "user" + }, + { + "id": 5, + "uuid": "d2", + "source": "default", + "isDefault": 1 + } + ], + "activeDashboard": { + "id": 0 + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | active gone": { + "result": { + "value": { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + } + ], + "activeDashboard": { + "id": 99 + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | active null id": { + "result": { + "value": { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + } + ], + "activeDashboard": { + "id": null + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | primary group default": { + "result": { + "value": { + "id": 3, + "uuid": "g2", + "source": "group", + "groupId": "sales", + "isDefault": "1" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + }, + { + "id": 3, + "uuid": "g2", + "source": "group", + "groupId": "sales", + "isDefault": "1" + }, + { + "id": 5, + "uuid": "d2", + "source": "default", + "isDefault": 1 + }, + { + "id": 6, + "uuid": "g3", + "source": "group", + "groupId": "hr", + "isDefault": 1 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | other group default only": { + "result": { + "value": { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 6, + "uuid": "g3", + "source": "group", + "groupId": "hr", + "isDefault": 1 + }, + { + "id": 7, + "uuid": "s1", + "source": "shared", + "isDefault": 1 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | default default without primary": { + "result": { + "value": { + "id": 5, + "uuid": "d2", + "source": "default", + "isDefault": 1 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + }, + { + "id": 3, + "uuid": "g2", + "source": "group", + "groupId": "sales", + "isDefault": "1" + }, + { + "id": 5, + "uuid": "d2", + "source": "default", + "isDefault": 1 + }, + { + "id": 6, + "uuid": "g3", + "source": "group", + "groupId": "hr", + "isDefault": 1 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | default default after another default-group": { + "result": { + "value": { + "id": 5, + "uuid": "d2", + "source": "default", + "isDefault": 1 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + }, + { + "id": 5, + "uuid": "d2", + "source": "default", + "isDefault": 1 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | first in primary group": { + "result": { + "value": { + "id": 3, + "uuid": "g2", + "source": "group", + "groupId": "sales", + "isDefault": "1" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + }, + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + }, + { + "id": 3, + "uuid": "g2", + "source": "group", + "groupId": "sales", + "isDefault": "1" + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | first in primary group without defaults": { + "result": { + "value": { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + }, + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | primary group without rows": { + "result": { + "value": { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + }, + { + "id": 7, + "uuid": "s1", + "source": "shared", + "isDefault": 1 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | first default-group": { + "result": { + "value": { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + }, + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + }, + { + "id": 4, + "uuid": "d1", + "source": "default", + "isDefault": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | first personal": { + "result": { + "value": { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + }, + { + "id": 7, + "uuid": "s1", + "source": "shared", + "isDefault": 1 + }, + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | only shared": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 7, + "uuid": "s1", + "source": "shared", + "isDefault": 1 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | shared default only": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + }, + { + "id": 7, + "uuid": "s1", + "source": "shared", + "isDefault": 1 + }, + { + "id": 7, + "uuid": "s1", + "source": "shared", + "isDefault": 1 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "resolveActive | primary group null": { + "result": { + "value": { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + } + }, + "state": { + "dashboards": [ + { + "id": 2, + "uuid": "g1", + "source": "group", + "groupId": "sales", + "isDefault": 0 + }, + { + "id": 1, + "uuid": "u1", + "source": "user", + "isDefault": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [] + }, + "loadDashboards | visible list with quota": { + "result": {}, + "state": { + "dashboards": [ + { + "id": 1, + "source": "user" + }, + { + "id": 2, + "source": "group" + } + ], + "activeDashboard": { + "id": 1, + "name": "Mine", + "isOwner": false, + "sharedBy": "bob", + "hasVariants": true + }, + "widgetPlacements": [ + { + "id": 10 + } + ], + "quota": { + "maxDashboards": 5, + "dashboardsUsed": 2, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "view", + "loading": false + }, + "calls": { + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "loadDashboards | visible bare array": { + "result": {}, + "state": { + "dashboards": [ + { + "id": 1, + "source": "user" + }, + { + "id": 3, + "source": "default" + } + ], + "activeDashboard": { + "id": 3, + "isOwner": true, + "sharedBy": null, + "hasVariants": false + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 1 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "loadDashboards | visible object without items": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 9 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "loadDashboards | visible null payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": { + "isOwner": true, + "sharedBy": null, + "hasVariants": false + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 1 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "loadDashboards | visible fails, fallback works": { + "result": {}, + "state": { + "dashboards": [ + { + "id": 8, + "source": "user" + } + ], + "activeDashboard": { + "id": 8, + "isOwner": true, + "sharedBy": null, + "hasVariants": false + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 1 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "getDashboards": [ + [] + ], + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ] + }, + "toasts": [], + "warnings": [ + [ + "Falling back to /api/dashboards (visible endpoint failed):", + "Error: visible down" + ] + ], + "errors": [] + }, + "loadDashboards | both fail": { + "result": {}, + "state": { + "dashboards": [ + { + "id": "old" + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 1 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "getDashboards": [ + [] + ], + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ] + }, + "toasts": [], + "warnings": [ + [ + "Falling back to /api/dashboards (visible endpoint failed):", + "Error: visible down" + ] + ], + "errors": [ + [ + "Failed to load dashboards:", + "Error: list down" + ] + ] + }, + "loadDashboards | active fails": { + "result": {}, + "state": { + "dashboards": [ + { + "id": 1, + "source": "user" + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 1 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to load the active dashboard:", + "Error: active down" + ] + ] + }, + "loadDashboards | items null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 1, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "createDashboard | string name": { + "result": {}, + "state": { + "dashboards": [ + { + "id": 0 + }, + { + "id": 1, + "source": "user" + } + ], + "activeDashboard": { + "id": 1 + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "Team" + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "createDashboard | default name": { + "result": {}, + "state": { + "dashboards": [ + { + "id": 0 + }, + { + "id": 2, + "source": "group" + } + ], + "activeDashboard": { + "id": 2, + "source": "group" + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "My Dashboard" + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "createDashboard | object payload": { + "result": {}, + "state": { + "dashboards": [ + { + "id": 0 + }, + { + "id": 3, + "source": "user" + } + ], + "activeDashboard": { + "id": 3 + }, + "widgetPlacements": [ + { + "id": 30 + }, + { + "id": 31 + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "Board", + "description": "About", + "icon": "star" + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "createDashboard | object without name or icon": { + "result": {}, + "state": { + "dashboards": [ + { + "id": 0 + }, + { + "id": 4, + "source": "user" + } + ], + "activeDashboard": { + "id": 4, + "source": null + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "My Dashboard", + "description": null, + "icon": null + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "createDashboard | personal dashboards disabled": { + "result": { + "rejected": "Request failed with status 403" + }, + "state": { + "dashboards": [ + { + "id": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "X" + } + ] + ] + }, + "toasts": [ + [ + "Personal dashboards are not enabled by your administrator" + ] + ], + "warnings": [], + "errors": [ + [ + "Failed to create dashboard:", + "Error: Request failed with status 403" + ] + ] + }, + "createDashboard | other 403": { + "result": { + "rejected": "Request failed with status 403" + }, + "state": { + "dashboards": [ + { + "id": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "X" + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to create dashboard:", + "Error: Request failed with status 403" + ] + ] + }, + "createDashboard | quota exceeded": { + "result": { + "rejected": "Request failed with status 409" + }, + "state": { + "dashboards": [ + { + "id": "reloaded", + "source": "user" + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "getVisibleDashboards": [ + [] + ], + "getActiveDashboard": [ + [] + ], + "createDashboard": [ + [ + { + "name": "X" + } + ] + ] + }, + "toasts": [ + [ + "You have reached the limit of {limit} dashboards{\"limit\":3}" + ] + ], + "warnings": [], + "errors": [ + [ + "Failed to create dashboard:", + "Error: Request failed with status 409" + ] + ] + }, + "createDashboard | other 409": { + "result": { + "rejected": "Request failed with status 409" + }, + "state": { + "dashboards": [ + { + "id": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "X" + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to create dashboard:", + "Error: Request failed with status 409" + ] + ] + }, + "createDashboard | no response": { + "result": { + "rejected": "offline" + }, + "state": { + "dashboards": [ + { + "id": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "X" + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to create dashboard:", + "Error: offline" + ] + ] + }, + "createDashboard | answer without dashboard": { + "result": { + "rejected": "Cannot read properties of undefined (reading 'source')" + }, + "state": { + "dashboards": [ + { + "id": 0 + } + ], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "createDashboard": [ + [ + { + "name": "X" + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to create dashboard:", + "Error: Cannot read properties of undefined (reading 'source')" + ] + ] + }, + "addWidgetToDashboard | empty | none | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | none | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | none | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | none | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | none | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | empty | none": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | empty | explicit": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit without size | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit without size | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit without size | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit without size | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit without size | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | empty | explicit without size": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit zero size | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit zero size | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit zero size | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit zero size | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | explicit zero size | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | empty | explicit zero size": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | size only | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 1 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | size only | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 1, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | size only | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 1, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | size only | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 1 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | size only | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 1 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | empty | size only": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 0, + "gridWidth": 3, + "gridHeight": 1 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | x only | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | x only | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | x only | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | x only | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | x only | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | empty | x only": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | non-finite y | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | non-finite y | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | non-finite y | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | non-finite y | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | non-finite y | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | empty | non-finite y": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | zero size only | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | zero size only | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | zero size only | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | zero size only | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | zero size only | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | empty | zero size only": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [ + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | empty | failure | widget quota": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [ + [ + "You have reached the limit of {limit} widgets on this dashboard{\"limit\":12}" + ] + ], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Request failed with status 409" + ] + ] + }, + "addTileToDashboard | empty | failure | widget quota": { + "result": { + "rejected": "Request failed with status 409" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [ + [ + "You have reached the limit of {limit} widgets on this dashboard{\"limit\":12}" + ] + ], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Request failed with status 409" + ] + ] + }, + "addWidgetToDashboard | empty | failure | other error": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: server down" + ] + ] + }, + "addTileToDashboard | empty | failure | other error": { + "result": { + "rejected": "server down" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7 + }, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: server down" + ] + ] + }, + "addWidgetToDashboard | with placements | none | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | none | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | none | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | none | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | none | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | with placements | none": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | with placements | explicit": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 2, + "gridY": 3, + "gridWidth": 5, + "gridHeight": 6 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit without size | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit without size | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit without size | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit without size | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit without size | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | with placements | explicit without size": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 0, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit zero size | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit zero size | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit zero size | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit zero size | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | explicit zero size | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | with placements | explicit zero size": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 1, + "gridY": 1, + "gridWidth": 0, + "gridHeight": 0 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | size only | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 6, + "gridWidth": 3, + "gridHeight": 1 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | size only | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 6, + "gridWidth": 3, + "gridHeight": 1, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | size only | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 6, + "gridWidth": 3, + "gridHeight": 1, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | size only | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 6, + "gridWidth": 3, + "gridHeight": 1 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | size only | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 6, + "gridWidth": 3, + "gridHeight": 1 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | with placements | size only": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 6, + "gridWidth": 3, + "gridHeight": 1 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | x only | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | x only | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | x only | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | x only | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | x only | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | with placements | x only": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | non-finite y | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | non-finite y | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | non-finite y | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | non-finite y | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | non-finite y | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | with placements | non-finite y": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | zero size only | widget id": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | zero size only | custom payload": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "label", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4, + "content": { + "text": "Hi" + } + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | zero size only | custom without content": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "text", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4, + "content": {} + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | zero size only | object without type": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": { + "kind": "x" + }, + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | zero size only | null": { + "result": { + "value": { + "id": "new" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "new" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": null, + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addTileToDashboard | with placements | zero size only": { + "result": { + "value": { + "id": "tile" + } + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + }, + { + "id": "tile" + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "icon": "i", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [] + }, + "addWidgetToDashboard | with placements | failure | widget quota": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [ + [ + "You have reached the limit of {limit} widgets on this dashboard{\"limit\":12}" + ] + ], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Request failed with status 409" + ] + ] + }, + "addTileToDashboard | with placements | failure | widget quota": { + "result": { + "rejected": "Request failed with status 409" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [ + [ + "You have reached the limit of {limit} widgets on this dashboard{\"limit\":12}" + ] + ], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Request failed with status 409" + ] + ] + }, + "addWidgetToDashboard | with placements | failure | other error": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addWidget": [ + [ + 7, + { + "widgetId": "calendar", + "gridX": 0, + "gridY": 6, + "gridWidth": 4, + "gridHeight": 4 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: server down" + ] + ] + }, + "addTileToDashboard | with placements | failure | other error": { + "result": { + "rejected": "server down" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "id": 7, + "gridColumns": 6 + }, + "widgetPlacements": [ + { + "id": 1, + "gridX": 0, + "gridY": 0, + "gridWidth": 4, + "gridHeight": 2 + }, + { + "id": 2, + "gridX": 4, + "gridY": 1, + "gridWidth": 2, + "gridHeight": 5 + } + ], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": { + "addTile": [ + [ + 7, + { + "title": "T", + "gridX": 0, + "gridY": 6, + "gridWidth": 2, + "gridHeight": 2 + } + ] + ] + }, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: server down" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | none | widget id": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | none | custom payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | none | custom without content": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | none | object without type": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | none | null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | none": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit | widget id": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit | custom payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit | custom without content": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit | object without type": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit | null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | explicit": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit without size | widget id": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit without size | custom payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit without size | custom without content": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit without size | object without type": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit without size | null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | explicit without size": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit zero size | widget id": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit zero size | custom payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit zero size | custom without content": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit zero size | object without type": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | explicit zero size | null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | explicit zero size": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | size only | widget id": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | size only | custom payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | size only | custom without content": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | size only | object without type": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | size only | null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | size only": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | x only | widget id": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | x only | custom payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | x only | custom without content": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | x only | object without type": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | x only | null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | x only": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | non-finite y | widget id": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | non-finite y | custom payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | non-finite y | custom without content": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | non-finite y | object without type": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | non-finite y | null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | non-finite y": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | zero size only | widget id": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | zero size only | custom payload": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | zero size only | custom without content": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | zero size only | object without type": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | zero size only | null": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | zero size only": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | failure | widget quota": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | failure | widget quota": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addWidgetToDashboard | no active dashboard | failure | other error": { + "result": {}, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add widget:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + }, + "addTileToDashboard | no active dashboard | failure | other error": { + "result": { + "rejected": "Cannot read properties of null (reading 'id')" + }, + "state": { + "dashboards": [], + "activeDashboard": null, + "widgetPlacements": [], + "quota": { + "maxDashboards": 0, + "dashboardsUsed": 0, + "maxWidgetsPerDashboard": 0 + }, + "permissionLevel": "full", + "loading": false + }, + "calls": {}, + "toasts": [], + "warnings": [], + "errors": [ + [ + "Failed to add tile:", + "Error: Cannot read properties of null (reading 'id')" + ] + ] + } +} diff --git a/src/stores/__tests__/fixtures/dashboardActions.golden.json b/src/stores/__tests__/fixtures/dashboardActions.golden.json new file mode 100644 index 000000000..72a41a325 --- /dev/null +++ b/src/stores/__tests__/fixtures/dashboardActions.golden.json @@ -0,0 +1,9802 @@ +{ + "forkDashboard | fork with dashboard": { + "result": { + "value": { + "id": 2, + "uuid": "b", + "name": "Copy" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + }, + { + "id": 2, + "uuid": "b", + "name": "Copy", + "source": "user", + "isOwner": true, + "sharedBy": null + } + ], + "activeDashboard": { + "id": 2, + "uuid": "b", + "name": "Copy", + "isOwner": true, + "sharedBy": "(undefined)", + "hasVariants": false + }, + "widgetPlacements": [ + { + "id": 7 + } + ], + "permissionLevel": "full", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "activateDashboard": [ + [ + 2 + ] + ], + "forkDashboard": [ + [ + "src", + "Mine" + ] + ], + "getDashboardById": [ + [ + 2 + ] + ], + "setActiveDashboardPreference": [ + [ + "b" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "forkDashboard | fork without dashboard": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + "Mine" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "forkDashboard | no data": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + "Mine" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "forkDashboard | no response": { + "result": { + "rejected": "Cannot read properties of undefined (reading 'data')" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + "Mine" + ] + ] + }, + "toasts": [ + [ + "Failed to fork dashboard" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + "Error: Cannot read properties of undefined (reading 'data')" + ] + ] + }, + "forkDashboard | fails: personal dashboards disabled": { + "result": { + "rejected": "Request failed with status 403" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + null + ] + ] + }, + "toasts": [ + [ + "Personal dashboards are not enabled by your administrator" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + "Error: Request failed with status 403" + ] + ] + }, + "forkDashboard | fails: other 403": { + "result": { + "rejected": "Request failed with status 403" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + null + ] + ] + }, + "toasts": [ + [ + "Failed to fork dashboard" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + "Error: Request failed with status 403" + ] + ] + }, + "forkDashboard | fails: 403 without body": { + "result": { + "rejected": "Request failed with status 403" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + null + ] + ] + }, + "toasts": [ + [ + "Failed to fork dashboard" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + "Error: Request failed with status 403" + ] + ] + }, + "forkDashboard | fails: not found": { + "result": { + "rejected": "Request failed with status 404" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + null + ] + ] + }, + "toasts": [ + [ + "Dashboard not found" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + "Error: Request failed with status 404" + ] + ] + }, + "forkDashboard | fails: server error with message": { + "result": { + "rejected": "Request failed with status 500" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + null + ] + ] + }, + "toasts": [ + [ + "Failed to fork dashboard" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + "Error: Request failed with status 500" + ] + ] + }, + "forkDashboard | fails: validation with empty message": { + "result": { + "rejected": "Request failed with status 400" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + null + ] + ] + }, + "toasts": [ + [ + "Failed to fork dashboard" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + "Error: Request failed with status 400" + ] + ] + }, + "forkDashboard | fails: no response": { + "result": { + "rejected": "offline" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + null + ] + ] + }, + "toasts": [ + [ + "Failed to fork dashboard" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + "Error: offline" + ] + ] + }, + "forkDashboard | fails: null": { + "result": { + "rejected": "null" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "forkDashboard": [ + [ + "src", + null + ] + ] + }, + "toasts": [ + [ + "Failed to fork dashboard" + ] + ], + "errors": [ + [ + "Failed to fork dashboard:", + null + ] + ] + }, + "applyPublicationPatch | start | null": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | start | no uuid": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | start | active and listed": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "scheduled", + "publishAt": "2030-01-01", + "publishedAt": null, + "unpublishAt": "2031-01-01" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a", + "publicationStatus": "scheduled", + "publishAt": "2030-01-01", + "publishedAt": null, + "unpublishAt": "2031-01-01" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | start | listed without unpublish": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "published", + "publishAt": "(undefined)", + "publishedAt": "(undefined)", + "unpublishAt": null + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a", + "publicationStatus": "published", + "publishAt": "(undefined)", + "publishedAt": "(undefined)", + "unpublishAt": null + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | start | unknown uuid": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active differs | null": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "uuid": "other" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active differs | no uuid": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "uuid": "other" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active differs | active and listed": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "scheduled", + "publishAt": "2030-01-01", + "publishedAt": null, + "unpublishAt": "2031-01-01" + } + ], + "activeDashboard": { + "uuid": "other" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active differs | listed without unpublish": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "published", + "publishAt": "(undefined)", + "publishedAt": "(undefined)", + "unpublishAt": null + } + ], + "activeDashboard": { + "uuid": "other" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active differs | unknown uuid": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "uuid": "other" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | no active | null": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": null, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | no active | no uuid": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": null, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | no active | active and listed": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "scheduled", + "publishAt": "2030-01-01", + "publishedAt": null, + "unpublishAt": "2031-01-01" + } + ], + "activeDashboard": null, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | no active | listed without unpublish": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "published", + "publishAt": "(undefined)", + "publishedAt": "(undefined)", + "unpublishAt": null + } + ], + "activeDashboard": null, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | no active | unknown uuid": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": null, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active only | null": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "uuid": "a", + "name": "A" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active only | no uuid": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "uuid": "a", + "name": "A" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active only | active and listed": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "uuid": "a", + "name": "A", + "publicationStatus": "scheduled", + "publishAt": "2030-01-01", + "publishedAt": null, + "unpublishAt": "2031-01-01" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active only | listed without unpublish": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "uuid": "a", + "name": "A", + "publicationStatus": "published", + "publishAt": "(undefined)", + "publishedAt": "(undefined)", + "unpublishAt": null + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "applyPublicationPatch | active only | unknown uuid": { + "result": { + "value": "(undefined)" + }, + "state": { + "dashboards": [], + "activeDashboard": { + "uuid": "a", + "name": "A" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | null": { + "result": { + "value": "draft" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | no status": { + "result": { + "value": "published" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | draft": { + "result": { + "value": "draft" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | published": { + "result": { + "value": "published" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | scheduled without date": { + "result": { + "value": "scheduled" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | scheduled past": { + "result": { + "value": "published" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | scheduled exactly now": { + "result": { + "value": "published" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | scheduled future": { + "result": { + "value": "scheduled" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "effectivePublicationStatus | scheduled invalid date": { + "result": { + "value": "scheduled" + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | no dashboard": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | no data": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | undefined | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | no dashboard": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | no data": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | empty | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | no dashboard": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | no data": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | slashes | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | trimmed | found": { + "result": { + "value": { + "id": 5 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": { + "id": 5 + } + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | trimmed | no dashboard": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | trimmed | no data": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | trimmed | no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | trimmed | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | trimmed | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | trimmed | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | trimmed | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | trimmed | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 500" + ] + ] + }, + "dashboardByPath | trimmed | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 400" + ] + ] + }, + "dashboardByPath | trimmed | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: offline" + ] + ] + }, + "dashboardByPath | trimmed | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team/sales": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team/sales" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + null + ] + ] + }, + "dashboardByPath | double trailing | found": { + "result": { + "value": { + "id": 5 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": { + "id": 5 + } + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | double trailing | no dashboard": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | double trailing | no data": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | double trailing | no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | double trailing | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | double trailing | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | double trailing | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | double trailing | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | double trailing | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 500" + ] + ] + }, + "dashboardByPath | double trailing | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 400" + ] + ] + }, + "dashboardByPath | double trailing | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: offline" + ] + ] + }, + "dashboardByPath | double trailing | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null, + "team": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "team" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + null + ] + ] + }, + "dashboardByPath | cached | found": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | no dashboard": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | no data": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | no response": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | fails: personal dashboards disabled": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | fails: other 403": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | fails: 403 without body": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | fails: not found": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | fails: server error with message": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | fails: validation with empty message": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | fails: no response": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached | fails: null": { + "result": { + "value": { + "id": "hit" + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | no dashboard": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | no data": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | cached null | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "dashboardByPath | number | found": { + "result": { + "value": { + "id": 5 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": { + "id": 5 + }, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | number | no dashboard": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | number | no data": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | number | no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | number | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | number | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | number | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 403" + ] + ] + }, + "dashboardByPath | number | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "dashboardByPath | number | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 500" + ] + ] + }, + "dashboardByPath | number | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: Request failed with status 400" + ] + ] + }, + "dashboardByPath | number | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + "Error: offline" + ] + ] + }, + "dashboardByPath | number | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "42": null, + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardByPath": [ + [ + "42" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to resolve dashboard path:", + null + ] + ] + }, + "fetchDashboardMetadata | | map": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | map": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | array": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | array": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | string": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | string": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | number": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | number": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | null": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | no response": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | fails: personal dashboards disabled": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | fails: other 403": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | fails: 403 without body": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | fails: not found": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | fails: server error with message": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | fails: validation with empty message": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | fails: no response": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | | fails: null": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": {}, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | old | map": { + "result": { + "value": { + "a": "1", + "b": 2 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "a": "1", + "b": 2 + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | map": { + "result": { + "value": { + "a": "1", + "b": 2 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "a": "1", + "b": 2 + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | old | array": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | array": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | old | string": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | string": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | old | number": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | number": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | old | null": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | null": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | old | no response": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | no response": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | old | fails: personal dashboards disabled": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 403" + ] + ] + }, + "fetchDashboardMetadata | old | fails: other 403": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 403" + ] + ] + }, + "fetchDashboardMetadata | old | fails: 403 without body": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 403" + ] + ] + }, + "fetchDashboardMetadata | old | fails: not found": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | old | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 404" + ] + ] + }, + "fetchDashboardMetadata | old | fails: server error with message": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to load dashboard metadata:", + "Error: Request failed with status 500" + ] + ] + }, + "updateDashboardMetadata | old | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Bad key" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 500" + ] + ] + }, + "fetchDashboardMetadata | old | fails: validation with empty message": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to load dashboard metadata:", + "Error: Request failed with status 400" + ] + ] + }, + "updateDashboardMetadata | old | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 400" + ] + ] + }, + "fetchDashboardMetadata | old | fails: no response": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to load dashboard metadata:", + "Error: offline" + ] + ] + }, + "updateDashboardMetadata | old | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: offline" + ] + ] + }, + "fetchDashboardMetadata | old | fails: null": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "old" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to load dashboard metadata:", + null + ] + ] + }, + "updateDashboardMetadata | old | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "old", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + null + ] + ] + }, + "fetchDashboardMetadata | u2 | map": { + "result": { + "value": { + "a": "1", + "b": 2 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": { + "a": "1", + "b": 2 + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | map": { + "result": { + "value": { + "a": "1", + "b": 2 + } + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": { + "a": "1", + "b": 2 + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | u2 | array": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | array": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | u2 | string": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | string": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | u2 | number": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | number": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | u2 | null": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | null": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | u2 | no response": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | no response": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [], + "errors": [] + }, + "fetchDashboardMetadata | u2 | fails: personal dashboards disabled": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | fails: personal dashboards disabled": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 403" + ] + ] + }, + "fetchDashboardMetadata | u2 | fails: other 403": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | fails: other 403": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 403" + ] + ] + }, + "fetchDashboardMetadata | u2 | fails: 403 without body": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | fails: 403 without body": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 403" + ] + ] + }, + "fetchDashboardMetadata | u2 | fails: not found": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [] + }, + "updateDashboardMetadata | u2 | fails: not found": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 404" + ] + ] + }, + "fetchDashboardMetadata | u2 | fails: server error with message": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to load dashboard metadata:", + "Error: Request failed with status 500" + ] + ] + }, + "updateDashboardMetadata | u2 | fails: server error with message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Bad key" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 500" + ] + ] + }, + "fetchDashboardMetadata | u2 | fails: validation with empty message": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to load dashboard metadata:", + "Error: Request failed with status 400" + ] + ] + }, + "updateDashboardMetadata | u2 | fails: validation with empty message": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: Request failed with status 400" + ] + ] + }, + "fetchDashboardMetadata | u2 | fails: no response": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to load dashboard metadata:", + "Error: offline" + ] + ] + }, + "updateDashboardMetadata | u2 | fails: no response": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + "Error: offline" + ] + ] + }, + "fetchDashboardMetadata | u2 | fails: null": { + "result": { + "value": {} + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + }, + "u2": {} + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "getDashboardMetadata": [ + [ + "u2" + ] + ] + }, + "toasts": [], + "errors": [ + [ + "Failed to load dashboard metadata:", + null + ] + ] + }, + "updateDashboardMetadata | u2 | fails: null": { + "result": { + "value": null + }, + "state": { + "dashboards": [ + { + "id": 1, + "uuid": "a", + "publicationStatus": "draft" + } + ], + "activeDashboard": { + "id": 1, + "uuid": "a" + }, + "widgetPlacements": [ + { + "id": 9 + } + ], + "permissionLevel": "view", + "loading": false, + "metadataByDashboard": { + "old": { + "k": "v" + } + }, + "pathCache": { + "cached": { + "id": "hit" + }, + "nulled": null + } + }, + "calls": { + "updateDashboardMetadata": [ + [ + "u2", + { + "k": "new" + } + ] + ] + }, + "toasts": [ + [ + "Failed to update dashboard metadata" + ] + ], + "errors": [ + [ + "Failed to update dashboard metadata:", + null + ] + ] + } +} diff --git a/src/stores/__tests__/fixtures/orgNavigationUpdateTree.golden.json b/src/stores/__tests__/fixtures/orgNavigationUpdateTree.golden.json new file mode 100644 index 000000000..7ae11f000 --- /dev/null +++ b/src/stores/__tests__/fixtures/orgNavigationUpdateTree.golden.json @@ -0,0 +1,584 @@ +{ + "given | tree and language": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [ + { + "id": "n2" + } + ], + "language": "fr", + "error": null, + "loading": false + } + }, + "given | tree only": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [], + "language": "en", + "error": null, + "loading": false + } + }, + "given | tree not a list": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [ + { + "id": "n1", + "label": "Home" + } + ], + "language": "en", + "error": null, + "loading": false + } + }, + "given | no data": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [ + { + "id": "n1", + "label": "Home" + } + ], + "language": "en", + "error": null, + "loading": false + } + }, + "given | no response": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [], + "language": "nl", + "error": "Failed to save navigation", + "loading": false + } + }, + "given | server error text": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [], + "language": "nl", + "error": "Not allowed", + "loading": false + } + }, + "given | server error empty": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [], + "language": "nl", + "error": "Failed to save navigation", + "loading": false + } + }, + "given | response without data": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [], + "language": "nl", + "error": "Failed to save navigation", + "loading": false + } + }, + "given | null": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "en" + ] + ], + "state": { + "tree": [], + "language": "nl", + "error": "Failed to save navigation", + "loading": false + } + }, + "from the store | tree and language": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [ + { + "id": "n2" + } + ], + "language": "fr", + "error": null, + "loading": false + } + }, + "from the store | tree only": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [], + "language": "de", + "error": null, + "loading": false + } + }, + "from the store | tree not a list": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [ + { + "id": "n1", + "label": "Home" + } + ], + "language": "de", + "error": null, + "loading": false + } + }, + "from the store | no data": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [ + { + "id": "n1", + "label": "Home" + } + ], + "language": "de", + "error": null, + "loading": false + } + }, + "from the store | no response": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [], + "language": "de", + "error": "Failed to save navigation", + "loading": false + } + }, + "from the store | server error text": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [], + "language": "de", + "error": "Not allowed", + "loading": false + } + }, + "from the store | server error empty": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [], + "language": "de", + "error": "Failed to save navigation", + "loading": false + } + }, + "from the store | response without data": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [], + "language": "de", + "error": "Failed to save navigation", + "loading": false + } + }, + "from the store | null": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "de" + ] + ], + "state": { + "tree": [], + "language": "de", + "error": "Failed to save navigation", + "loading": false + } + }, + "store language empty | tree and language": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [ + { + "id": "n2" + } + ], + "language": "fr", + "error": null, + "loading": false + } + }, + "store language empty | tree only": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [], + "language": "nl", + "error": null, + "loading": false + } + }, + "store language empty | tree not a list": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [ + { + "id": "n1", + "label": "Home" + } + ], + "language": "nl", + "error": null, + "loading": false + } + }, + "store language empty | no data": { + "result": true, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [ + { + "id": "n1", + "label": "Home" + } + ], + "language": "nl", + "error": null, + "loading": false + } + }, + "store language empty | no response": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [], + "language": "", + "error": "Failed to save navigation", + "loading": false + } + }, + "store language empty | server error text": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [], + "language": "", + "error": "Not allowed", + "loading": false + } + }, + "store language empty | server error empty": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [], + "language": "", + "error": "Failed to save navigation", + "loading": false + } + }, + "store language empty | response without data": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [], + "language": "", + "error": "Failed to save navigation", + "loading": false + } + }, + "store language empty | null": { + "result": false, + "calls": [ + [ + [ + { + "id": "n1", + "label": "Home" + } + ], + "nl" + ] + ], + "state": { + "tree": [], + "language": "", + "error": "Failed to save navigation", + "loading": false + } + } +} diff --git a/src/stores/__tests__/fixtures/widgetItems.golden.json b/src/stores/__tests__/fixtures/widgetItems.golden.json new file mode 100644 index 000000000..27da0ac63 --- /dev/null +++ b/src/stores/__tests__/fixtures/widgetItems.golden.json @@ -0,0 +1,1368 @@ +{ + "empty | none | full entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 2 + } + ], + "emptyContentMessage": "Empty", + "halfEmptyContentMessage": "Half", + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "empty | none | entry without fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "empty | none | entry with null fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "empty | none | unrequested id": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "other": { + "items": [ + { + "id": 3 + } + ], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "empty | none | no entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": {}, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "empty | none | null data": { + "result": { + "value": "(undefined)" + }, + "widgetItems": {}, + "calls": [ + [ + [] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot convert undefined or null to object" + ] + ] + }, + "empty | none | no response": { + "result": { + "value": "(undefined)" + }, + "widgetItems": {}, + "calls": [ + [ + [] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot read properties of undefined (reading 'data')" + ] + ] + }, + "empty | none | fails": { + "result": { + "value": "(undefined)" + }, + "widgetItems": {}, + "calls": [ + [ + [] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "Error: down" + ] + ] + }, + "empty | one | full entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 2 + } + ], + "emptyContentMessage": "Empty", + "halfEmptyContentMessage": "Half", + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "empty | one | entry without fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "empty | one | entry with null fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": true + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "empty | one | unrequested id": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": true + }, + "other": { + "items": [ + { + "id": 3 + } + ], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "empty | one | no entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": true + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "empty | one | null data": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot convert undefined or null to object" + ] + ] + }, + "empty | one | no response": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot read properties of undefined (reading 'data')" + ] + ] + }, + "empty | one | fails": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "Error: down" + ] + ] + }, + "empty | two | full entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 2 + } + ], + "emptyContentMessage": "Empty", + "halfEmptyContentMessage": "Half", + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "empty | two | entry without fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + }, + "b": { + "loading": true + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "empty | two | entry with null fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": true + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "empty | two | unrequested id": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": true + }, + "b": { + "loading": true + }, + "other": { + "items": [ + { + "id": 3 + } + ], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "empty | two | no entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": true + }, + "b": { + "loading": true + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "empty | two | null data": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": false + }, + "b": { + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot convert undefined or null to object" + ] + ] + }, + "empty | two | no response": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": false + }, + "b": { + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot read properties of undefined (reading 'data')" + ] + ] + }, + "empty | two | fails": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "loading": false + }, + "b": { + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "Error: down" + ] + ] + }, + "earlier items | none | full entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 2 + } + ], + "emptyContentMessage": "Empty", + "halfEmptyContentMessage": "Half", + "loading": false + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "earlier items | none | entry without fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "earlier items | none | entry with null fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "earlier items | none | unrequested id": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "other": { + "items": [ + { + "id": 3 + } + ], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "earlier items | none | no entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [] + }, + "earlier items | none | null data": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot convert undefined or null to object" + ] + ] + }, + "earlier items | none | no response": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot read properties of undefined (reading 'data')" + ] + ] + }, + "earlier items | none | fails": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "Error: down" + ] + ] + }, + "earlier items | one | full entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 2 + } + ], + "emptyContentMessage": "Empty", + "halfEmptyContentMessage": "Half", + "loading": false + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "earlier items | one | entry without fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "earlier items | one | entry with null fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": true, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "earlier items | one | unrequested id": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": true, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "other": { + "items": [ + { + "id": 3 + } + ], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "earlier items | one | no entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": true, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [] + }, + "earlier items | one | null data": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot convert undefined or null to object" + ] + ] + }, + "earlier items | one | no response": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot read properties of undefined (reading 'data')" + ] + ] + }, + "earlier items | one | fails": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + } + }, + "calls": [ + [ + [ + "a" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "Error: down" + ] + ] + }, + "earlier items | two | full entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 2 + } + ], + "emptyContentMessage": "Empty", + "halfEmptyContentMessage": "Half", + "loading": false + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "earlier items | two | entry without fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "loading": true + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "earlier items | two | entry with null fields": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": true, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "items": [], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "earlier items | two | unrequested id": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": true, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "loading": true + }, + "other": { + "items": [ + { + "id": 3 + } + ], + "emptyContentMessage": "", + "halfEmptyContentMessage": "", + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "earlier items | two | no entries": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": true, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "loading": true + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [] + }, + "earlier items | two | null data": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot convert undefined or null to object" + ] + ] + }, + "earlier items | two | no response": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "TypeError: Cannot read properties of undefined (reading 'data')" + ] + ] + }, + "earlier items | two | fails": { + "result": { + "value": "(undefined)" + }, + "widgetItems": { + "a": { + "items": [ + { + "id": 1 + } + ], + "emptyContentMessage": "none", + "loading": false, + "extra": "kept" + }, + "z": { + "items": [], + "loading": false + }, + "b": { + "loading": false + } + }, + "calls": [ + [ + [ + "a", + "b" + ] + ] + ], + "errors": [ + [ + "Failed to load widget items:", + "Error: down" + ] + ] + } +} diff --git a/src/stores/__tests__/groupDashboards.spec.js b/src/stores/__tests__/groupDashboards.spec.js index 09b8cc509..c3d31b591 100644 --- a/src/stores/__tests__/groupDashboards.spec.js +++ b/src/stores/__tests__/groupDashboards.spec.js @@ -137,9 +137,9 @@ describe('useGroupDashboardsStore — CRUD', () => { expect(store.dashboardsFor('admins')[0].uuid).toBe('u2') }) - it('delete surfaces last_group_dashboard as the localized toast', async () => { + it('delete surfaces the last-in-group refusal as the localized toast', async () => { const err = new Error('last') - err.response = { data: { error: 'last_group_dashboard' } } + err.response = { data: { error: 'Cannot delete the only dashboard in the group' } } mockApi.deleteGroupDashboard.mockRejectedValueOnce(err) const { useGroupDashboardsStore } = await import('../groupDashboards.js') const store = useGroupDashboardsStore() diff --git a/src/stores/__tests__/orgNavigation.failures.spec.js b/src/stores/__tests__/orgNavigation.failures.spec.js new file mode 100644 index 000000000..b52062556 --- /dev/null +++ b/src/stores/__tests__/orgNavigation.failures.spec.js @@ -0,0 +1,113 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the orgNavigation store's failure and fallback + * paths: a failed tree load, a failed or unknown position load, and the + * position save's fallbacks and error messages. + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { useOrgNavigationStore } from '../orgNavigation.js' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +vi.mock('../../services/api.js', () => ({ + api: { + getOrgNavigation: vi.fn(), + updateOrgNavigation: vi.fn(), + getOrgNavigationPosition: vi.fn(), + updateOrgNavigationPosition: vi.fn(), + }, +})) + +beforeEach(() => { + setActivePinia(createPinia()) + vi.resetAllMocks() +}) + +describe('orgNavigation store failures', () => { + it('a failed tree load empties the tree and keeps the error message', async () => { + const store = useOrgNavigationStore() + store.tree = [{ id: 'old' }] + api.getOrgNavigation.mockRejectedValue(new Error('Gone')) + + await store.fetchTree('en') + + expect(api.getOrgNavigation).toHaveBeenCalledWith('en') + expect(store.tree).toEqual([]) + expect(store.error).toBe('Gone') + expect(store.loading).toBe(false) + }) + + it('a failed tree load without a message uses a generic one', async () => { + const store = useOrgNavigationStore() + api.getOrgNavigation.mockRejectedValue({}) + + await store.fetchTree() + + expect(store.error).toBe('Failed to load navigation') + }) + + it('an unknown position from the server keeps the current one', async () => { + const store = useOrgNavigationStore() + store.position = 'left' + api.getOrgNavigationPosition.mockResolvedValue({ data: { position: 'bottom' } }) + + await store.fetchPosition() + + expect(store.position).toBe('left') + }) + + it('a failed position load keeps the position and records the error', async () => { + const store = useOrgNavigationStore() + store.position = 'top' + api.getOrgNavigationPosition.mockRejectedValueOnce(new Error('Timeout')) + await store.fetchPosition() + expect(store.position).toBe('top') + expect(store.error).toBe('Timeout') + + api.getOrgNavigationPosition.mockRejectedValueOnce(null) + await store.fetchPosition() + expect(store.error).toBe('Failed to load position') + }) + + it('saving an unsupported position is refused without a request', async () => { + const store = useOrgNavigationStore() + + const ok = await store.updatePosition('bottom') + + expect(ok).toBe(false) + expect(store.error).toBe('Unsupported position') + expect(api.updateOrgNavigationPosition).not.toHaveBeenCalled() + }) + + it('a saved position without one in the response keeps the requested one', async () => { + const store = useOrgNavigationStore() + store.error = 'old' + api.updateOrgNavigationPosition.mockResolvedValue({ data: {} }) + + const ok = await store.updatePosition('right') + + expect(ok).toBe(true) + expect(store.position).toBe('right') + expect(store.error).toBeNull() + }) + + it('a failed position save shows the server error, else a generic one', async () => { + const store = useOrgNavigationStore() + api.updateOrgNavigationPosition.mockRejectedValueOnce({ + response: { data: { error: 'Admins only' } }, + }) + expect(await store.updatePosition('left')).toBe(false) + expect(store.error).toBe('Admins only') + + api.updateOrgNavigationPosition.mockRejectedValueOnce(new Error('x')) + expect(await store.updatePosition('left')).toBe(false) + expect(store.error).toBe('Failed to save position') + }) +}) diff --git a/src/stores/__tests__/orgNavigation.firstLoad.spec.js b/src/stores/__tests__/orgNavigation.firstLoad.spec.js new file mode 100644 index 000000000..f776ea20e --- /dev/null +++ b/src/stores/__tests__/orgNavigation.firstLoad.spec.js @@ -0,0 +1,66 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The org navigation store's first load: from the initial state when the + * page carries it, from the API when it does not. + * + * @spec openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/tasks.md#task-4 + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { takeOrgNavigation } from '../../utils/loadInitialState.js' +import { useOrgNavigationStore } from '../orgNavigation.js' + +vi.mock('../../services/api.js', () => ({ + api: { + getOrgNavigation: vi.fn(), + getOrgNavigationPosition: vi.fn(), + }, +})) +vi.mock('../../utils/loadInitialState.js', () => ({ takeOrgNavigation: vi.fn() })) + +beforeEach(() => { + setActivePinia(createPinia()) + vi.resetAllMocks() +}) + +describe('orgNavigation store first load', () => { + it('takes the position and the tree the page carries, without asking the API', async () => { + takeOrgNavigation.mockReturnValue({ position: 'left', tree: [{ id: 'n1' }], language: 'en' }) + const store = useOrgNavigationStore() + + await store.loadFirst() + + expect(store.position).toBe('left') + expect(store.tree).toEqual([{ id: 'n1' }]) + expect(store.language).toBe('en') + expect(api.getOrgNavigation).not.toHaveBeenCalled() + expect(api.getOrgNavigationPosition).not.toHaveBeenCalled() + }) + + it('keeps the hidden default for a position it does not know', async () => { + takeOrgNavigation.mockReturnValue({ position: 'sideways', tree: [], language: 'nl' }) + const store = useOrgNavigationStore() + + await store.loadFirst() + + expect(store.position).toBe('hidden') + }) + + it('asks the API for both when the page carries none', async () => { + takeOrgNavigation.mockReturnValue(null) + api.getOrgNavigationPosition.mockResolvedValue({ data: { position: 'top' } }) + api.getOrgNavigation.mockResolvedValue({ data: { tree: [{ id: 'n2' }], language: 'nl' } }) + const store = useOrgNavigationStore() + + await store.loadFirst() + + expect(api.getOrgNavigationPosition).toHaveBeenCalledTimes(1) + expect(api.getOrgNavigation).toHaveBeenCalledWith('nl') + expect(store.position).toBe('top') + expect(store.tree).toEqual([{ id: 'n2' }]) + }) +}) diff --git a/src/stores/__tests__/orgNavigationUpdateTree.golden.spec.js b/src/stores/__tests__/orgNavigationUpdateTree.golden.spec.js new file mode 100644 index 000000000..cd7a01e73 --- /dev/null +++ b/src/stores/__tests__/orgNavigationUpdateTree.golden.spec.js @@ -0,0 +1,100 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for the orgNavigation store's updateTree action: a set of + * languages and API answers and failures, each on a fresh store, compared with + * fixtures/orgNavigationUpdateTree.golden.json. Set RECORD_GOLDEN=1 to rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { createPinia, setActivePinia } from 'pinia' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('../../services/api.js', () => ({ + api: { updateOrgNavigation: vi.fn() }, +})) + +const FIXTURE = path.resolve( + __dirname, + 'fixtures/orgNavigationUpdateTree.golden.json', +) + +const TREE = [{ id: 'n1', label: 'Home' }] + +const LANGUAGES = { + given: { lang: 'en', state: {} }, + 'from the store': { lang: undefined, state: { language: 'de' } }, + 'store language empty': { lang: '', state: { language: '' } }, +} + +const ANSWERS = { + 'tree and language': { + data: { tree: [{ id: 'n2' }], language: 'fr' }, + }, + 'tree only': { data: { tree: [] } }, + 'tree not a list': { data: { tree: 'x', language: '' } }, + 'no data': { data: null }, + 'no response': undefined, +} + +const FAILURES = { + 'server error text': { response: { data: { error: 'Not allowed' } } }, + 'server error empty': { response: { data: { error: '' } } }, + 'response without data': { response: {} }, + 'no response': new Error('offline'), + null: null, +} + +/** + * Run updateTree on a fresh store and record what it returned and left. + * + * @param {object} language The language case. + * @return {Promise<object>} The outcome. + */ +async function outcome(language) { + setActivePinia(createPinia()) + const { api } = await import('../../services/api.js') + const { useOrgNavigationStore } = await import('../orgNavigation.js') + const store = useOrgNavigationStore() + Object.assign(store, { error: 'earlier' }, language.state) + const result = await store.updateTree(TREE, language.lang) + return { + result, + calls: api.updateOrgNavigation.mock.calls, + state: { + tree: store.tree, + language: store.language, + error: store.error, + loading: store.loading, + }, + } +} + +describe('orgNavigation updateTree (golden)', () => { + it('matches the recorded results', async () => { + const { api } = await import('../../services/api.js') + const actual = {} + for (const [l, language] of Object.entries(LANGUAGES)) { + for (const [a, answer] of Object.entries(ANSWERS)) { + api.updateOrgNavigation.mockReset() + api.updateOrgNavigation.mockResolvedValue(answer) + actual[`${l} | ${a}`] = await outcome(language) + } + for (const [f, failure] of Object.entries(FAILURES)) { + api.updateOrgNavigation.mockReset() + api.updateOrgNavigation.mockRejectedValue(failure) + actual[`${l} | ${f}`] = await outcome(language) + } + } + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + for (const key of Object.keys(expected)) { + expect(actual[key], key).toEqual(expected[key]) + } + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + }) +}) diff --git a/src/stores/__tests__/publicShares.spec.js b/src/stores/__tests__/publicShares.spec.js new file mode 100644 index 000000000..2a68533b6 --- /dev/null +++ b/src/stores/__tests__/publicShares.spec.js @@ -0,0 +1,95 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the public-share store: creating, listing and + * revoking a dashboard's public shares through the API, and remembering + * which share tokens the viewer unlocked in localStorage. + */ + +import axios from '@nextcloud/axios' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { usePublicShareStore } from '../publicShares.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), delete: vi.fn() }, +})) + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +const BASE = '/index.php/apps/launchpad/api/dashboards' + +describe('publicShares store', () => { + beforeEach(() => { + localStorage.clear() + vi.clearAllMocks() + setActivePinia(createPinia()) + }) + + it('creates a share with only the options given and lists it under its dashboard', async () => { + axios.post.mockResolvedValueOnce({ data: { id: 1, token: 't1' } }) + axios.post.mockResolvedValueOnce({ data: { id: 2, token: 't2' } }) + const store = usePublicShareStore() + + const created = await store.createShare('dash/1') + await store.createShare('dash/1', { password: 'secret', expiresAt: '2027-01-01' }) + + expect(created).toEqual({ id: 1, token: 't1' }) + expect(axios.post.mock.calls).toEqual([ + [`${BASE}/dash%2F1/public-share`, {}], + [`${BASE}/dash%2F1/public-share`, { password: 'secret', expiresAt: '2027-01-01' }], + ]) + expect(store.sharesFor('dash/1').map((s) => s.id)).toEqual([1, 2]) + expect(store.loading).toBe(false) + }) + + it('stops loading when creating fails', async () => { + axios.post.mockRejectedValueOnce(new Error('403')) + const store = usePublicShareStore() + + await expect(store.createShare('d')).rejects.toThrow('403') + expect(store.loading).toBe(false) + expect(store.sharesFor('d')).toEqual([]) + }) + + it('fetches the shares of a dashboard and replaces what was known', async () => { + axios.get.mockResolvedValueOnce({ data: [{ id: 5 }] }) + const store = usePublicShareStore() + store.sharesByDashboard.d = [{ id: 1 }] + + expect(await store.fetchShares('d')).toEqual([{ id: 5 }]) + expect(axios.get).toHaveBeenCalledWith(`${BASE}/d/public-shares`) + expect(store.sharesFor('d')).toEqual([{ id: 5 }]) + expect(store.loading).toBe(false) + }) + + it('revokes a share and drops it from the list', async () => { + axios.delete.mockResolvedValue({}) + const store = usePublicShareStore() + store.sharesByDashboard.d = [{ id: 1 }, { id: 2 }] + + await store.revokeShare('d', 1) + await store.revokeShare('unknown', 9) + + expect(axios.delete.mock.calls).toEqual([[`${BASE}/d/public-shares/1`], [`${BASE}/unknown/public-shares/9`]]) + expect(store.sharesFor('d')).toEqual([{ id: 2 }]) + expect(store.sharesFor('unknown')).toEqual([]) + }) + + it('remembers unlocked tokens in localStorage and forgets them again', () => { + localStorage.setItem('mydash_unlocked_tokens', JSON.stringify({ old: true })) + const store = usePublicShareStore() + + expect(store.isUnlocked('old')).toBe(true) + store.markUnlocked('new') + expect(store.isUnlocked('new')).toBe(true) + expect(JSON.parse(localStorage.getItem('mydash_unlocked_tokens'))).toEqual({ old: true, new: true }) + + store.clearUnlocked('old') + expect(store.isUnlocked('old')).toBe(false) + expect(JSON.parse(localStorage.getItem('mydash_unlocked_tokens'))).toEqual({ new: true }) + }) +}) diff --git a/src/stores/__tests__/roleFeaturePermissions.spec.js b/src/stores/__tests__/roleFeaturePermissions.spec.js new file mode 100644 index 000000000..e3fdf9cdd --- /dev/null +++ b/src/stores/__tests__/roleFeaturePermissions.spec.js @@ -0,0 +1,134 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the role-feature permission store: loading the + * permissions and layout defaults (wrapped or bare payloads), saving one + * (replacing the entry for the same group, or the same group and widget), + * deleting one, and the error and busy flags around every call. + */ + +import axios from '@nextcloud/axios' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useRoleFeaturePermissionStore } from '../roleFeaturePermissions.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), delete: vi.fn() }, +})) + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +const PERMS = '/index.php/apps/launchpad/api/role-feature-permissions' +const DEFAULTS = '/index.php/apps/launchpad/api/role-layout-defaults' + +describe('roleFeaturePermissions store', () => { + let store + + beforeEach(() => { + vi.clearAllMocks() + setActivePinia(createPinia()) + store = useRoleFeaturePermissionStore() + }) + + it('loads permissions from a wrapped or bare payload, and nothing from a non-list', async () => { + axios.get.mockResolvedValueOnce({ data: { data: [{ id: 1 }] } }) + await store.loadPermissions() + expect(store.permissions).toEqual([{ id: 1 }]) + + axios.get.mockResolvedValueOnce({ data: [{ id: 2 }] }) + await store.loadPermissions() + expect(store.permissions).toEqual([{ id: 2 }]) + + axios.get.mockResolvedValueOnce({ data: { data: 'nope' } }) + await store.loadPermissions() + expect(store.permissions).toEqual([]) + expect(axios.get).toHaveBeenCalledWith(PERMS) + expect(store.loading).toBe(false) + }) + + it('loads layout defaults the same way', async () => { + axios.get.mockResolvedValueOnce({ data: [{ id: 'd1' }] }) + await store.loadLayoutDefaults() + expect(axios.get).toHaveBeenCalledWith(DEFAULTS) + expect(store.layoutDefaults).toEqual([{ id: 'd1' }]) + }) + + it('records the error of a failed load and rethrows it', async () => { + axios.get.mockRejectedValueOnce(new Error('offline')) + await expect(store.loadPermissions()).rejects.toThrow('offline') + expect([store.error, store.loading]).toEqual(['offline', false]) + + axios.get.mockRejectedValueOnce({}) + await expect(store.loadLayoutDefaults()).rejects.toEqual({}) + expect(store.error).toBe('Failed to load role-layout defaults') + }) + + it('saves a permission, replacing the entry of the same group', async () => { + store.permissions = [{ id: 1, groupId: 'admin', features: [] }, { id: 2, groupId: 'staff' }] + axios.post.mockResolvedValueOnce({ data: { data: { id: 1, groupId: 'admin', features: ['x'] } } }) + axios.post.mockResolvedValueOnce({ data: { id: 3, groupId: 'guests' } }) + + const saved = await store.savePermission({ groupId: 'admin', features: ['x'] }) + await store.savePermission({ groupId: 'guests' }) + + expect(saved).toEqual({ id: 1, groupId: 'admin', features: ['x'] }) + expect(axios.post).toHaveBeenCalledWith(PERMS, { groupId: 'admin', features: ['x'] }) + expect(store.permissions.map((p) => [p.id, p.groupId])).toEqual([[1, 'admin'], [2, 'staff'], [3, 'guests']]) + expect(store.permissions[0].features).toEqual(['x']) + expect(store.saving).toBe(false) + }) + + it('saves a layout default keyed by group and widget', async () => { + store.layoutDefaults = [{ id: 'a', groupId: 'g', widgetId: 'w1', x: 0 }] + axios.post.mockResolvedValueOnce({ data: { id: 'a', groupId: 'g', widgetId: 'w1', x: 4 } }) + axios.post.mockResolvedValueOnce({ data: { id: 'b', groupId: 'g', widgetId: 'w2' } }) + + await store.saveLayoutDefault({ groupId: 'g', widgetId: 'w1', x: 4 }) + await store.saveLayoutDefault({ groupId: 'g', widgetId: 'w2' }) + + expect(axios.post).toHaveBeenCalledWith(DEFAULTS, { groupId: 'g', widgetId: 'w1', x: 4 }) + expect(store.layoutDefaults).toEqual([ + { id: 'a', groupId: 'g', widgetId: 'w1', x: 4 }, + { id: 'b', groupId: 'g', widgetId: 'w2' }, + ]) + }) + + it('deletes permissions and layout defaults by id', async () => { + axios.delete.mockResolvedValue({}) + store.permissions = [{ id: 1 }, { id: 2 }] + store.layoutDefaults = [{ id: 'a' }, { id: 'b' }] + + await store.deletePermission(1) + await store.deleteLayoutDefault('b') + + expect(axios.delete.mock.calls).toEqual([[`${PERMS}/1`], [`${DEFAULTS}/b`]]) + expect(store.permissions).toEqual([{ id: 2 }]) + expect(store.layoutDefaults).toEqual([{ id: 'a' }]) + }) + + it('keeps the lists and records the error when a write fails', async () => { + store.permissions = [{ id: 1 }] + store.layoutDefaults = [{ id: 'a' }] + const cases = [ + [() => store.savePermission({}), axios.post, 'Failed to save permission'], + [() => store.deletePermission(1), axios.delete, 'Failed to delete permission'], + [() => store.saveLayoutDefault({}), axios.post, 'Failed to save layout default'], + [() => store.deleteLayoutDefault('a'), axios.delete, 'Failed to delete layout default'], + ] + + for (const [call, method, message] of cases) { + method.mockRejectedValueOnce({}) + await expect(call()).rejects.toEqual({}) + expect([store.error, store.saving]).toEqual([message, false]) + } + + axios.post.mockRejectedValueOnce(new Error('conflict')) + await expect(store.savePermission({})).rejects.toThrow('conflict') + expect(store.error).toBe('conflict') + expect(store.permissions).toEqual([{ id: 1 }]) + expect(store.layoutDefaults).toEqual([{ id: 'a' }]) + }) +}) diff --git a/src/stores/__tests__/scheduledExports.spec.js b/src/stores/__tests__/scheduledExports.spec.js new file mode 100644 index 000000000..a6e31ad0a --- /dev/null +++ b/src/stores/__tests__/scheduledExports.spec.js @@ -0,0 +1,120 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the scheduled-exports store (scheduled-exports + * tasks 17-18): every call goes to the export API, "Run now" polls the run + * until it settles, preview asks for the file, and the lists follow saves, + * deletes and retries. + */ + +import axios from '@nextcloud/axios' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useExportsStore } from '../scheduledExports.js' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), delete: vi.fn() }, +})) + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, +})) + +const BASE = '/index.php/apps/launchpad/api/exports' + +describe('scheduledExports store', () => { + beforeEach(() => { + vi.clearAllMocks() + setActivePinia(createPinia()) + }) + + it('runs now and polls the run until it is no longer running', async () => { + axios.post.mockResolvedValueOnce({ data: { id: 'r1', status: 'running' } }) + axios.get + .mockResolvedValueOnce({ data: { id: 'r1', status: 'running' } }) + .mockResolvedValueOnce({ data: { id: 'r1', status: 'success' } }) + const store = useExportsStore() + const seen = [] + + const run = await store.runExportNow('e1', { onProgress: (r) => seen.push(r.status), interval: 0 }) + + expect(axios.post).toHaveBeenCalledWith(`${BASE}/e1/run`) + expect(axios.get).toHaveBeenCalledWith(`${BASE}/e1/runs/r1`) + expect(axios.get).toHaveBeenCalledTimes(2) + expect(seen).toEqual(['running', 'running', 'success']) + expect(run.status).toBe('success') + expect(store.runsByExport.e1).toEqual([{ id: 'r1', status: 'success' }]) + expect(store.running).toEqual({}) + }) + + it('stops polling after the poll budget and clears the running flag on failure', async () => { + axios.post.mockResolvedValueOnce({ data: { id: 'r1', status: 'running' } }) + axios.get.mockResolvedValue({ data: { id: 'r1', status: 'running' } }) + const store = useExportsStore() + + const run = await store.runExportNow('e1', { interval: 0, maxPolls: 3 }) + expect(axios.get).toHaveBeenCalledTimes(3) + expect(run.status).toBe('running') + + axios.post.mockRejectedValueOnce(new Error('404')) + await expect(store.runExportNow('e2', { interval: 0 })).rejects.toThrow('404') + expect(store.running).toEqual({}) + }) + + it('previews one format for one recipient as a file', async () => { + const blob = new Blob(['%PDF']) + axios.post.mockResolvedValueOnce({ data: blob }) + + const result = await useExportsStore().previewExport('e1', 'gm', 'pdf') + + expect(axios.post).toHaveBeenCalledWith(`${BASE}/e1/preview`, null, { params: { recipientId: 'gm', format: 'pdf' }, responseType: 'blob' }) + expect(result).toBe(blob) + }) + + it('creates with POST, updates with PATCH and deletes, keeping the list in step', async () => { + axios.get.mockResolvedValueOnce({ data: { results: [{ id: 'e1', name: 'A' }] } }) + axios.post.mockResolvedValueOnce({ data: { id: 'e2', name: 'B' } }) + axios.patch.mockResolvedValueOnce({ data: { id: 'e1', name: 'A2' } }) + axios.delete.mockResolvedValueOnce({}) + const store = useExportsStore() + + await store.fetchExports() + await store.saveExport({ name: 'B' }) + await store.saveExport({ id: 'e1', name: 'A2' }) + await store.deleteExport('e2') + + expect(axios.get).toHaveBeenCalledWith(BASE, { params: { limit: 200 } }) + expect(axios.post).toHaveBeenCalledWith(BASE, { name: 'B' }) + expect(axios.patch).toHaveBeenCalledWith(`${BASE}/e1`, { id: 'e1', name: 'A2' }) + expect(axios.delete).toHaveBeenCalledWith(`${BASE}/e2`) + expect(store.exports).toEqual([{ id: 'e1', name: 'A2' }]) + }) + + it('loads runs and replaces a retried run', async () => { + axios.get.mockResolvedValueOnce({ data: { results: [{ id: 'r1', status: 'partial' }, { id: 'r0', status: 'success' }] } }) + axios.post.mockResolvedValueOnce({ data: { id: 'r1', status: 'running' } }) + const store = useExportsStore() + + await store.fetchRuns('e1') + const retried = await store.retryRun('e1', 'r1') + + expect(axios.post).toHaveBeenCalledWith(`${BASE}/e1/runs/r1/retry`) + expect(retried.status).toBe('running') + expect(store.runsByExport.e1.map((r) => r.status)).toEqual(['running', 'success']) + }) + + it('reads one run and replaces the listed row with it', async () => { + axios.get + .mockResolvedValueOnce({ data: { results: [{ id: 'r1', status: 'running' }, { id: 'r0', status: 'success' }] } }) + .mockResolvedValueOnce({ data: { id: 'r1', status: 'partial', deliveries: [{ status: 'failed-permanent' }] } }) + const store = useExportsStore() + + await store.fetchRuns('e1') + const run = await store.fetchRun('e1', 'r1') + + expect(axios.get).toHaveBeenLastCalledWith(`${BASE}/e1/runs/r1`) + expect(run.deliveries).toHaveLength(1) + expect(store.runsByExport.e1.map((r) => r.status)).toEqual(['partial', 'success']) + }) +}) diff --git a/src/stores/__tests__/tilePanel.spec.js b/src/stores/__tests__/tilePanel.spec.js new file mode 100644 index 000000000..213117640 --- /dev/null +++ b/src/stores/__tests__/tilePanel.spec.js @@ -0,0 +1,43 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The one panel beside the tiles (launcher-tile-open-behaviour D3). + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useTilePanelStore } from '../tilePanel.js' + +describe('tilePanel store', () => { + beforeEach(() => { + setActivePinia(createPinia()) + }) + + it('opening another tile replaces the panel, and closing returns focus to the last opener', () => { + const first = { focus: vi.fn() } + const second = { focus: vi.fn() } + const panel = useTilePanelStore() + + panel.open({ url: '/a', title: 'A', sameOrigin: true, opener: first }) + panel.open({ url: 'https://b.example', title: 'B', opener: second }) + + expect([panel.isOpen, panel.url, panel.title, panel.sameOrigin]).toEqual([true, 'https://b.example', 'B', false]) + + panel.close() + + expect([panel.isOpen, panel.url, panel.title, panel.opener]).toEqual([false, null, '', null]) + expect(second.focus).toHaveBeenCalledTimes(1) + expect(first.focus).not.toHaveBeenCalled() + }) + + it('closes without an opener', () => { + const panel = useTilePanelStore() + panel.open({ url: '/a' }) + panel.close() + + expect(panel.isOpen).toBe(false) + }) +}) diff --git a/src/stores/__tests__/tilesAndWidgets.spec.js b/src/stores/__tests__/tilesAndWidgets.spec.js new file mode 100644 index 000000000..d2e5f4362 --- /dev/null +++ b/src/stores/__tests__/tilesAndWidgets.spec.js @@ -0,0 +1,159 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the tile store (load, create, update, delete, and + * the logged failures) and the widget store's catalogue load, item lookups + * and refresh. + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { widgetBridge } from '../../services/widgetBridge.js' +import { logger } from '../../utils/logger.js' +import { useTileStore } from '../tiles.js' +import { useWidgetStore } from '../widgets.js' + +vi.mock('../../utils/logger.js', () => ({ + logger: { error: vi.fn(), debug: vi.fn() }, +})) + +vi.mock('../../services/api.js', () => ({ + api: { + getTiles: vi.fn(), + createTile: vi.fn(), + updateTile: vi.fn(), + deleteTile: vi.fn(), + getAvailableWidgets: vi.fn(), + getWidgetItems: vi.fn(), + }, +})) + +vi.mock('../../services/widgetBridge.js', () => ({ + widgetBridge: { setWidgetMetadata: vi.fn() }, +})) + +const initialState = vi.hoisted(() => ({ values: {} })) +vi.mock('@nextcloud/initial-state', () => ({ + loadState: (app, key, fallback) => (key in initialState.values ? initialState.values[key] : fallback), +})) + +beforeEach(() => { + vi.clearAllMocks() + initialState.values = {} + setActivePinia(createPinia()) +}) + +describe('tiles store', () => { + it('loads tiles and logs a failed load without throwing', async () => { + const store = useTileStore() + api.getTiles.mockResolvedValueOnce({ data: [{ id: 1 }] }) + await store.loadTiles() + expect([store.tiles, store.loading]).toEqual([[{ id: 1 }], false]) + + const failure = new Error('down') + api.getTiles.mockRejectedValueOnce(failure) + await store.loadTiles() + expect(logger.error).toHaveBeenCalledWith('Failed to load tiles:', failure) + expect([store.tiles, store.loading]).toEqual([[{ id: 1 }], false]) + }) + + it('creates, updates and deletes tiles in the list', async () => { + const store = useTileStore() + store.tiles = [{ id: 1, title: 'A' }] + api.createTile.mockResolvedValueOnce({ data: { id: 2, title: 'B' } }) + api.updateTile.mockResolvedValue({ data: { id: 1, title: 'A2' } }) + api.deleteTile.mockResolvedValueOnce({}) + + expect(await store.createTile({ title: 'B' })).toEqual({ id: 2, title: 'B' }) + expect(await store.updateTile(1, { title: 'A2' })).toEqual({ id: 1, title: 'A2' }) + await store.updateTile(99, { title: 'ghost' }) + await store.deleteTile(2) + + expect(api.createTile).toHaveBeenCalledWith({ title: 'B' }) + expect(api.updateTile).toHaveBeenCalledWith(1, { title: 'A2' }) + expect(api.deleteTile).toHaveBeenCalledWith(2) + expect(store.tiles).toEqual([{ id: 1, title: 'A2' }]) + }) + + it('logs and rethrows a failed write, leaving the list alone', async () => { + const store = useTileStore() + store.tiles = [{ id: 1 }] + const cases = [ + [() => store.createTile({}), api.createTile, 'Failed to create tile:'], + [() => store.updateTile(1, {}), api.updateTile, 'Failed to update tile:'], + [() => store.deleteTile(1), api.deleteTile, 'Failed to delete tile:'], + ] + + for (const [call, method, message] of cases) { + const failure = new Error(message) + method.mockRejectedValueOnce(failure) + await expect(call()).rejects.toBe(failure) + expect(logger.error).toHaveBeenLastCalledWith(message, failure) + } + expect(store.tiles).toEqual([{ id: 1 }]) + }) +}) + +describe('widgets store', () => { + it('loads the widget catalogue and hands it to the dashboard bridge', async () => { + const store = useWidgetStore() + const widgets = [{ id: 'weather', title: 'Weather' }] + api.getAvailableWidgets.mockResolvedValueOnce({ data: widgets }) + + await store.loadAvailableWidgets() + + expect(store.availableWidgets).toEqual(widgets) + expect(widgetBridge.setWidgetMetadata).toHaveBeenCalledWith(widgets) + expect(store.getWidgetById('weather')).toEqual(widgets[0]) + expect(store.getWidgetById('nope')).toBeUndefined() + expect(store.loading).toBe(false) + }) + + it('takes the catalogue from the initial state without calling GET /api/widgets', async () => { + const store = useWidgetStore() + const widgets = [{ id: 'activity', title: 'Activity' }] + initialState.values = { widgets } + + await store.loadAvailableWidgets() + + expect(api.getAvailableWidgets).not.toHaveBeenCalled() + expect(store.availableWidgets).toEqual(widgets) + expect(widgetBridge.setWidgetMetadata).toHaveBeenCalledWith(widgets) + }) + + it('falls back to GET /api/widgets when the initial state carries no catalogue', async () => { + const store = useWidgetStore() + initialState.values = { widgets: [] } + api.getAvailableWidgets.mockResolvedValueOnce({ data: [{ id: 'notes' }] }) + + await store.loadAvailableWidgets() + + expect(api.getAvailableWidgets).toHaveBeenCalledTimes(1) + expect(store.availableWidgets).toEqual([{ id: 'notes' }]) + }) + + it('logs a failed catalogue load', async () => { + const store = useWidgetStore() + const failure = new Error('500') + api.getAvailableWidgets.mockRejectedValueOnce(failure) + + await store.loadAvailableWidgets() + + expect(logger.error).toHaveBeenCalledWith('Failed to load available widgets:', failure) + expect(widgetBridge.setWidgetMetadata).not.toHaveBeenCalled() + expect(store.loading).toBe(false) + }) + + it('answers an empty entry for unknown widgets and refreshes one widget', async () => { + const store = useWidgetStore() + expect(store.getWidgetItems('x')).toEqual({ items: [], loading: false }) + + api.getWidgetItems.mockResolvedValueOnce({ data: { x: { items: [1] } } }) + await store.refreshWidgetItems('x') + + expect(api.getWidgetItems).toHaveBeenCalledWith(['x']) + expect(store.getWidgetItems('x')).toEqual({ items: [1], emptyContentMessage: '', halfEmptyContentMessage: '', loading: false }) + }) +}) diff --git a/src/stores/__tests__/widgetItems.golden.spec.js b/src/stores/__tests__/widgetItems.golden.spec.js new file mode 100644 index 000000000..a7fe6ad33 --- /dev/null +++ b/src/stores/__tests__/widgetItems.golden.spec.js @@ -0,0 +1,153 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Golden test for the widgets store's loadWidgetItems action: start states, + * API answers and failures, each on a fresh store, compared with + * fixtures/widgetItems.golden.json case by case. Set RECORD_GOLDEN=1 to + * rewrite it. + */ + +import fs from 'node:fs' +import path from 'node:path' +import { createPinia, setActivePinia } from 'pinia' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('../../utils/logger.js', () => ({ + logger: { warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() }, +})) + +vi.mock('../../services/api.js', () => ({ + api: { getWidgetItems: vi.fn() }, +})) + +vi.mock('../../services/widgetBridge.js', () => ({ + widgetBridge: { setWidgetMetadata: vi.fn() }, +})) + +const FIXTURE = path.resolve(__dirname, 'fixtures/widgetItems.golden.json') + +const STARTS = { + empty: {}, + 'earlier items': { + a: { + items: [{ id: 1 }], + emptyContentMessage: 'none', + loading: false, + extra: 'kept', + }, + z: { items: [], loading: false }, + }, +} + +const IDS = { + none: [], + one: ['a'], + two: ['a', 'b'], +} + +const ANSWERS = { + 'full entries': { + data: { + a: { + items: [{ id: 2 }], + emptyContentMessage: 'Empty', + halfEmptyContentMessage: 'Half', + }, + b: { items: [] }, + }, + }, + 'entry without fields': { data: { a: {} } }, + 'entry with null fields': { + data: { + b: { + items: null, + emptyContentMessage: null, + halfEmptyContentMessage: '', + }, + }, + }, + 'unrequested id': { data: { other: { items: [{ id: 3 }] } } }, + 'no entries': { data: {} }, + 'null data': { data: null }, + 'no response': undefined, +} + +/** + * Run loadWidgetItems on a fresh store and record what it left. + * + * @param {object} start The widgetItems to start from. + * @param {Array<string>} ids The ids to load. + * @return {Promise<object>} The outcome. + */ +async function outcome(start, ids) { + setActivePinia(createPinia()) + const { api } = await import('../../services/api.js') + const { logger } = await import('../../utils/logger.js') + const { useWidgetStore } = await import('../widgets.js') + const store = useWidgetStore() + store.widgetItems = structuredClone(start) + let result + try { + result = { value: (await store.loadWidgetItems(ids)) ?? '(undefined)' } + } catch (error) { + result = { rejected: error.message } + } + return JSON.parse( + JSON.stringify({ + result, + widgetItems: store.widgetItems, + calls: api.getWidgetItems.mock.calls, + errors: logger.error.mock.calls.map(([text, error]) => [ + text, + String(error), + ]), + }), + ) +} + +/** + * Record every case. + * + * @return {Promise<object>} The outcomes by case name. + */ +async function record() { + const { api } = await import('../../services/api.js') + const actual = {} + const replies = [ + ...Object.entries(ANSWERS).map(([name, value]) => [name, { value }]), + ['fails', { error: new Error('down') }], + ] + for (const [startName, start] of Object.entries(STARTS)) { + for (const [idsName, ids] of Object.entries(IDS)) { + for (const [name, reply] of replies) { + vi.clearAllMocks() + api.getWidgetItems.mockReset() + if (reply.error) { + api.getWidgetItems.mockRejectedValue(reply.error) + } else { + api.getWidgetItems.mockResolvedValue(reply.value) + } + actual[`${startName} | ${idsName} | ${name}`] = await outcome( + start, + ids, + ) + } + } + } + return actual +} + +describe('widgets store loadWidgetItems (golden)', () => { + it('matches the recorded outcomes case by case', async () => { + const actual = await record() + if (process.env.RECORD_GOLDEN) { + fs.writeFileSync(FIXTURE, JSON.stringify(actual, null, '\t') + '\n') + } + const expected = JSON.parse(fs.readFileSync(FIXTURE, 'utf8')) + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + for (const [name, value] of Object.entries(expected)) { + expect(actual[name], name).toEqual(value) + } + }) +}) diff --git a/src/stores/calculatedFields.js b/src/stores/calculatedFields.js new file mode 100644 index 000000000..203ba108e --- /dev/null +++ b/src/stores/calculatedFields.js @@ -0,0 +1,118 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { defineStore } from 'pinia' +import { evaluateDashboard } from '../utils/calculatedFields/dashboardValues.js' + +/** + * The calculated-field values of the open dashboard (REQ-CALC-003). + * + * Widget renderers report their current source data with `setWidgetData`; + * the dashboard reports its widgets with `setWidgets` and its active filters + * with `setFilters`. Every report re-evaluates all calculated fields in + * topological order, so a field reading another widget follows that widget's + * data and calculated values. Filters change what the renderers load; the + * filter revision is kept so a renderer that reloads after a filter change + * re-evaluates even when the data happens to be identical. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +export const useCalculatedFieldsStore = defineStore('calculatedFields', { + state: () => ({ + widgets: [], + dataById: {}, + filters: [], + filterRevision: 0, + values: {}, + errors: {}, + }), + + getters: { + /** + * The calculated values of one widget, by field name. + * + * @param {object} state The store state. + * @return {function(string): Record<string, unknown>} The lookup. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + valuesOf: (state) => (widgetId) => state.values[String(widgetId)] || {}, + + /** + * The inline errors of one widget, by field name. + * + * @param {object} state The store state. + * @return {function(string): Record<string, object>} The lookup. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-008-inline-error-display-preserves-dashboard-usability + */ + errorsOf: (state) => (widgetId) => state.errors[String(widgetId)] || {}, + }, + + actions: { + /** + * Set the dashboard's widgets and re-evaluate. + * + * @param {object[]} widgets The widgets, each `{id, calculatedFields}`. + * @return {void} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + setWidgets(widgets) { + this.widgets = Array.isArray(widgets) ? widgets : [] + this.recompute() + }, + + /** + * Record one widget's current source data and re-evaluate. + * + * @param {string} widgetId The widget. + * @param {object} data Its source data. + * @return {void} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + setWidgetData(widgetId, data) { + this.dataById = { ...this.dataById, [String(widgetId)]: data ?? {} } + this.recompute() + }, + + /** + * Record the dashboard's active filters and re-evaluate. + * + * @param {object[]} filters The filter clauses. + * @return {void} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + setFilters(filters) { + this.filters = Array.isArray(filters) ? filters : [] + this.filterRevision++ + this.recompute() + }, + + /** + * Forget the dashboard (on leaving it). + * + * @return {void} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + reset() { + this.widgets = [] + this.dataById = {} + this.filters = [] + this.values = {} + this.errors = {} + }, + + /** + * Re-evaluate every calculated field in topological order. + * + * @param {{now?: number}} [options] Evaluation options. + * @return {void} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + recompute(options = {}) { + const { values, errors } = evaluateDashboard(this.widgets, this.dataById, options) + this.values = values + this.errors = errors + }, + }, +}) diff --git a/src/stores/dashboard.js b/src/stores/dashboard.js index 4d7966fa2..e1ff99936 100644 --- a/src/stores/dashboard.js +++ b/src/stores/dashboard.js @@ -7,12 +7,34 @@ import { showError } from '@nextcloud/dialogs' import { translate as t } from '@nextcloud/l10n' import { defineStore } from 'pinia' import { - DEFAULT_H, - DEFAULT_W, + defaultSizeFor, placeNewWidget, } from '../composables/useGridManager.js' import { api } from '../services/api.js' +import { takeBootRead, takeDashboardFirstLoad } from '../utils/loadInitialState.js' import { logger } from '../utils/logger.js' +import { parseServerStamp } from '../utils/serverStamp.js' + +/** + * Waits before each automatic retry of a failed layout save: three retries, + * so a save is tried four times in all (grid-layout "Save failure with retry"). + * + * @spec openspec/specs/grid-layout/spec.md + */ +export const LAYOUT_SAVE_RETRY_DELAYS_MS = [1000, 2000, 4000] + +/** Counts layout saves, so a retry stops once a newer layout is being saved. */ +let layoutSaveSequence = 0 + +/** + * Resolve after `ms` milliseconds. + * + * @param {number} ms The wait. + * @return {Promise<void>} + */ +function wait(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} /** * Stable backend error code returned by `POST /api/dashboard` when the admin @@ -51,6 +73,400 @@ export const STATUS_DRAFT = 'draft' export const STATUS_PUBLISHED = 'published' export const STATUS_SCHEDULED = 'scheduled' +/** + * The checks resolveActive tries in order (REQ-DASH-018), each a predicate + * over the visible rows, or `false` when it does not apply: + * + * 1. activeDashboard if still in the visible list + * 2. group-shared isDefault=1 in primaryGroup (state.primaryGroup) + * 3. default-group isDefault=1 + * 4. first group-shared in primaryGroup + * 5. first default-group dashboard + * 6. first personal dashboard + * + * @param {object} state The Pinia store state. + * @return {Array<((d: object) => boolean)|false>} The checks. + */ +function resolutionRules(state) { + const activeId = state.activeDashboard?.id + const primary = state.primaryGroup || '' + const inPrimary = (d) => d.source === SOURCE_GROUP && d.groupId === primary + const inDefault = (d) => d.source === SOURCE_DEFAULT + const isDefault = (d) => Number(d.isDefault) === 1 + const hasActive = activeId !== undefined && activeId !== null + return [ + hasActive && ((d) => d.id === activeId || d.uuid === activeId), + primary !== '' && ((d) => inPrimary(d) && isDefault(d)), + (d) => inDefault(d) && isDefault(d), + primary !== '' && inPrimary, + inDefault, + (d) => d.source === SOURCE_USER, + ] +} + +/** + * The visible-dashboards and active-dashboard answers of a load. The page's + * first load comes from its initial state, which carries both payloads + * already, so the workspace opens without asking for them again; every + * later load, or a page without them, fetches both together. + * + * @return {Promise<Array<{data: (object|Array|null)}>>} The visible and the active response. + * @spec openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md#task-3 + */ +function firstDashboardResponses() { + const firstLoad = takeDashboardFirstLoad() + if (firstLoad !== null) { + return Promise.resolve([{ data: firstLoad.visible }, { data: firstLoad.active }]) + } + return Promise.all([fetchVisibleDashboards(), fetchActiveDashboard()]) +} + +/** + * Fetch the active dashboard. It is asked for together with the list, so a + * failure here must not take the list down with it: the load then has no + * active dashboard, as it had when the two were asked for one after the other. + * + * @return {Promise<{data: (object|null)}>} The axios response, or an empty one. + * @spec openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md#task-3 + */ +async function fetchActiveDashboard() { + try { + return await api.getActiveDashboard() + } catch (error) { + logger.error('Failed to load the active dashboard:', error) + return { data: null } + } +} + +/** + * Fetch the visible dashboards (REQ-DASH-013), falling back to + * `/api/dashboards` when the `/visible` endpoint fails, so older clients + * keep working. + * + * @return {Promise<object>} The axios response. + */ +async function fetchVisibleDashboards() { + try { + return await api.getVisibleDashboards() + } catch (visibleError) { + logger.warn( + 'Falling back to /api/dashboards (visible endpoint failed):', + visibleError, + ) + return await api.getDashboards() + } +} + +/** + * The quota envelope of a dashboard list response, or null when the + * response carries none (a bare array or an older backend). + * + * @param {unknown} payload The list response body. + * @return {object|null} The quota. + */ +function quotaOf(payload) { + if (!payload || Array.isArray(payload) || !payload.quota) { + return null + } + return { + maxDashboards: payload.quota.maxDashboards ?? 0, + dashboardsUsed: payload.quota.dashboardsUsed ?? 0, + maxWidgetsPerDashboard: payload.quota.maxWidgetsPerDashboard ?? 0, + } +} + +/** + * The dashboard rows of a list response, each tagged with its source; + * older backends may not tag rows, so an untagged row is personal. + * + * @param {unknown} payload The list response body: `{items}` or a bare array. + * @return {Array<object>} The rows. + */ +function dashboardRowsOf(payload) { + const rows = Array.isArray(payload) ? payload : (payload?.items ?? []) + return (rows || []).map((d) => ({ + ...d, + source: d.source ?? SOURCE_USER, + })) +} + +/** + * The active dashboard of a getActive response with its ownership tags. + * getActive can resolve a group or showcase dashboard the user does not own + * (via the last-used preference), so the tags it returns are kept; an older + * backend that omits them means the user owns it. `hasVariants` says the + * dashboard has more than one language version. + * + * @param {object} data The getActive response body. + * @return {object} The active dashboard. + */ +function activeDashboardOf(data) { + return { + ...data.dashboard, + isOwner: data.isOwner ?? true, + sharedBy: data.sharedBy ?? null, + hasVariants: data.hasVariants === true, + } +} + +/** + * The request body for a new personal dashboard: a plain name string, or an + * object with name/description/icon and an optional `widgets` seed choice + * (legacy callers may pass a string). + * + * @param {string|object} payload The createDashboard argument. + * @return {object} The request body. + */ +function newDashboardData(payload) { + if (typeof payload === 'string') { + return { name: payload } + } + return { + name: payload.name || 'My Dashboard', + description: payload.description, + // Optional registry key from the `dashboard-icons` + // capability — null/undefined skips the field server-side. + icon: payload.icon ?? null, + // `starters` or `none`; absent seeds the default widget bundle. + ...(payload.widgets ? { widgets: payload.widgets } : {}), + } +} + +/** + * Tell the user why a dashboard could not be created, when the backend says. + * REQ-ASET-003 (extended): the stable `personal_dashboards_disabled` 403 + * gets a localised toast, as the UI may have offered a stale affordance or + * the call may bypass the UI altogether. REQ-QUOTA-006 (race case): the + * structured 409 `quota_exceeded` gets a clear message, and the quota + * envelope is refreshed so the button disables. + * + * @param {object} store The dashboard store. + * @param {object} error The axios error. + * @return {void} + */ +function reportCreateFailure(store, error) { + const status = error?.response?.status + const code = error?.response?.data?.error + if (status === 403 && code === ERR_PERSONAL_DASHBOARDS_DISABLED) { + showError( + t( + 'launchpad', + 'Personal dashboards are not enabled by your administrator', + ), + ) + } + reportDashboardQuota(store, error) +} + +/** + * On the structured 409 `quota_exceeded` of a create or fork, name the + * dashboard limit and reread the quota envelope so the button disables + * (REQ-QUOTA-006, race case). + * + * @param {object} store The dashboard store. + * @param {object} error The axios error. + * @return {boolean} Whether the error was a quota refusal. + */ +function reportDashboardQuota(store, error) { + if ( + error?.response?.status !== 409 + || error?.response?.data?.error !== 'quota_exceeded' + ) { + return false + } + const limit = error.response.data.limit + showError( + t('launchpad', 'You have reached the limit of {limit} dashboards', { + limit, + }), + ) + store.loadDashboards().catch(() => {}) + return true +} + +/** + * Where a new widget or tile goes (REQ-GRID-006 / REQ-GRID-014). A position + * with both `x` and `y` is honoured as given, its missing size taken from + * `size`; otherwise `placeNewWidget` appends it below the existing widgets. + * + * @param {object|null} position Explicit `{x, y, w, h}`, or a partial size. + * @param {{size: {w: number, h: number}, store: object}} context The default size and the dashboard store. + * @return {{x: number, y: number, w: number, h: number, pushed: Array}} The placement. + */ +function newPlacement(position, context) { + const { size, store } = context + if (position && Number.isFinite(position.x) && Number.isFinite(position.y)) { + return { + x: position.x, + y: position.y, + w: position.w ?? size.w, + h: position.h ?? size.h, + pushed: [], + } + } + return placeNewWidget( + { w: position?.w ?? size.w, h: position?.h ?? size.h }, + store.widgetPlacements, + { gridColumns: store.activeDashboard?.gridColumns }, + ) +} + +/** + * The addWidget request body. AddWidgetModal emits a `{type, content}` + * payload for the registry-driven custom widgets (label, text, image, …); + * the legacy callers pass a Nextcloud Dashboard API widget id as a string. + * Both funnel through here into the API contract (`widgetId` string plus + * `content` object for custom widgets). + * + * @param {string|object} widgetId A widget id, or a `{type, content}` payload. + * @param {{x: number, y: number, w: number, h: number}} placement Where it goes. + * @return {object} The request body. + */ +function widgetRequestBody(widgetId, placement) { + const isCustomPayload = + widgetId !== null + && typeof widgetId === 'object' + && typeof widgetId.type === 'string' + const requestBody = { + widgetId: isCustomPayload ? widgetId.type : widgetId, + gridX: placement.x, + gridY: placement.y, + gridWidth: placement.w, + gridHeight: placement.h, + } + if (isCustomPayload) { + requestBody.content = widgetId.content ?? {} + } + return requestBody +} + +/** + * The toast text for a dashboard that could not be forked (REQ-ASET-003, + * extended): the stable `personal_dashboards_disabled` 403 and a 404 get + * their own message, anything else the generic one. + * + * @param {object} error The axios error. + * @return {string} The localised message. + * @spec openspec/specs/dashboards/spec.md + */ +function forkFailureText(error) { + const status = error?.response?.status + if ( + status === 403 + && error?.response?.data?.error === ERR_PERSONAL_DASHBOARDS_DISABLED + ) { + return t( + 'launchpad', + 'Personal dashboards are not enabled by your administrator', + ) + } + if (status === 404) { + return t('launchpad', 'Dashboard not found') + } + return t('launchpad', 'Failed to fork dashboard') +} + +/** + * The publication-state fields of an updated dashboard entity, as they are + * patched onto the copies already in the store (REQ-DASH-031..037). + * + * @param {object} dashboard The updated entity. + * @return {object} The publication fields. + * @spec openspec/specs/dashboards/spec.md + */ +function publicationFields(dashboard) { + return { + publicationStatus: dashboard.publicationStatus, + publishAt: dashboard.publishAt, + publishedAt: dashboard.publishedAt, + unpublishAt: dashboard.unpublishAt ?? null, + } +} + +/** + * The effective status of a scheduled dashboard (REQ-DASH-034): published + * once its valid publish moment has passed, scheduled otherwise. + * + * @param {string|null|undefined} publishAt The scheduled publish moment. + * @return {string} `'published' | 'scheduled'`. + * @spec openspec/specs/dashboards/spec.md + */ +function scheduledStatus(publishAt) { + if (!publishAt) { + return STATUS_SCHEDULED + } + const when = parseServerStamp(publishAt) + if (when === null) { + return STATUS_SCHEDULED + } + return when.getTime() <= Date.now() ? STATUS_PUBLISHED : STATUS_SCHEDULED +} + +/** + * The cache key of a dashboard slug-chain path (REQ-DASH-027): the path + * without leading and trailing slashes, or `''` when there is none. + * + * @param {unknown} path The slash-joined slug chain. + * @return {string} The key. + * @spec openspec/specs/dashboards/spec.md + */ +function dashboardPathKey(path) { + return String(path || '') + .replace(/\/+$/, '') + .replace(/^\/+/, '') +} + +/** + * The metadata map of a metadata response (REQ-MDFL-004/005): its body when + * that is a plain object, otherwise an empty map. + * + * @param {object|undefined} response The axios response. + * @return {object} The metadata map. + * @spec openspec/specs/dashboards/spec.md + */ +function metadataMapOf(response) { + const payload = response?.data + return payload && typeof payload === 'object' && !Array.isArray(payload) + ? payload + : {} +} + +/** + * The dashboard a slug-chain path resolves to (REQ-DASH-027), or null when + * none does; a failure other than a 404 miss is logged. + * + * @param {string} key The path cache key. + * @return {Promise<object|null>} The dashboard payload or null. + * @spec openspec/specs/dashboards/spec.md + */ +async function resolveDashboardPath(key) { + try { + const response = await api.getDashboardByPath(key) + return response?.data?.dashboard ?? null + } catch (error) { + if (error?.response?.status !== 404) { + logger.error('Failed to resolve dashboard path:', error) + } + return null + } +} + +/** + * Cache a dashboard's metadata map on the store and return it. + * + * @param {object} store The dashboard store. + * @param {{uuid: string, map: object}} entry The dashboard UUID and its map. + * @return {object} The map. + * @spec openspec/specs/dashboards/spec.md + */ +function cacheMetadata(store, { uuid, map }) { + store.metadataByDashboard = { + ...store.metadataByDashboard, + [uuid]: map, + } + return map +} + export const useDashboardStore = defineStore('dashboard', { state: () => ({ // `dashboards` carries every dashboard visible to the user @@ -75,6 +491,10 @@ export const useDashboardStore = defineStore('dashboard', { // backend 7-step precedence (REQ-DASH-018). primaryGroup: '', loading: false, + // The first loadDashboards() has finished. + loadedOnce: false, + // A dashboard the address asked for before that load finished. + requestedDashboardId: null, saving: false, // REQ-RXN-003 — per-dashboard reactions summary cache. // Map<uuid, {counts: {emoji: number, ...}, mine: [emoji, ...], enabled: boolean}>. @@ -257,62 +677,12 @@ export const useDashboardStore = defineStore('dashboard', { */ resolveActive: (state) => { const list = state.dashboards || [] - if (list.length === 0) { - return null - } - - // Step 1: honour the currently-active dashboard if still visible. - const activeId = state.activeDashboard?.id - if (activeId !== undefined && activeId !== null) { - const stillVisible = list.find( - (d) => d.id === activeId || d.uuid === activeId, - ) - if (stillVisible !== undefined) { - return stillVisible + for (const rule of resolutionRules(state).filter(Boolean)) { + const match = list.find(rule) + if (match !== undefined) { + return match } } - - const primary = state.primaryGroup || '' - const inPrimary = (d) => - d.source === SOURCE_GROUP && d.groupId === primary - const inDefault = (d) => d.source === SOURCE_DEFAULT - const isDefault = (d) => Number(d.isDefault) === 1 - - // Step 2: primary-group default. - if (primary !== '') { - const groupDefault = list.find((d) => inPrimary(d) && isDefault(d)) - if (groupDefault !== undefined) { - return groupDefault - } - } - - // Step 3: default-group default. - const defaultDefault = list.find((d) => inDefault(d) && isDefault(d)) - if (defaultDefault !== undefined) { - return defaultDefault - } - - // Step 4: first group-shared in primary group. - if (primary !== '') { - const firstInGroup = list.find((d) => inPrimary(d)) - if (firstInGroup !== undefined) { - return firstInGroup - } - } - - // Step 5: first default-group dashboard. - const firstInDefault = list.find((d) => inDefault(d)) - if (firstInDefault !== undefined) { - return firstInDefault - } - - // Step 6: first personal dashboard. - const firstPersonal = list.find((d) => d.source === SOURCE_USER) - if (firstPersonal !== undefined) { - return firstPersonal - } - - // Step 7: nothing. return null }, @@ -341,8 +711,18 @@ export const useDashboardStore = defineStore('dashboard', { // outstanding mandatory-read items. Failures are non-fatal — a broken // acknowledgement fetch must never blank the dashboard, so the list is // simply left empty (no forced-delivery gate). - /** @spec openspec/changes/dashboard-acknowledgements/specs/dashboard-acknowledgements/spec.md */ + // The first read takes the items the page carries + // (workspace-boot-reads-from-initial-state); every later one asks. + /** + * @spec openspec/changes/dashboard-acknowledgements/specs/dashboard-acknowledgements/spec.md + * @spec openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/tasks.md#task-3 + */ async fetchPendingAcknowledgements() { + const carried = takeBootRead('pendingAcknowledgements') + if (carried && Array.isArray(carried.items)) { + this.pendingAcknowledgements = carried.items + return + } try { const response = await api.getPendingAcknowledgements() this.pendingAcknowledgements = response?.data?.items ?? [] @@ -374,62 +754,29 @@ export const useDashboardStore = defineStore('dashboard', { ) }, - /** @spec openspec/specs/dashboards/spec.md */ + /** + * @spec openspec/specs/dashboards/spec.md + * @spec openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md#task-3 + */ async loadDashboards() { this.loading = true try { - // REQ-DASH-013: prefer the `/visible` endpoint so the store - // receives the source-tagged union of personal + group + - // default-group dashboards. Older clients that only know - // `/api/dashboards` keep working server-side, but the - // listing UI uses the unioned source of truth. - let response - try { - response = await api.getVisibleDashboards() - } catch (visibleError) { - logger.warn( - 'Falling back to /api/dashboards (visible endpoint failed):', - visibleError, - ) - response = await api.getDashboards() - } // dashboard-quota-limits REQ-QUOTA-006: the list response is // now `{items: [...], quota: {...}}`. Stay tolerant of older // backends that returned a bare array so a version skew never // blanks the dashboard list. - const payload = response.data - const rows = Array.isArray(payload) - ? payload - : (payload?.items ?? []) - if (payload && !Array.isArray(payload) && payload.quota) { - this.quota = { - maxDashboards: payload.quota.maxDashboards ?? 0, - dashboardsUsed: payload.quota.dashboardsUsed ?? 0, - maxWidgetsPerDashboard: - payload.quota.maxWidgetsPerDashboard ?? 0, - } + // The list and the active dashboard do not depend on each + // other, so they are asked for together: one round trip, not two. + const [visibleResponse, activeResponse] = await firstDashboardResponses() + const payload = visibleResponse.data + const quota = quotaOf(payload) + if (quota !== null) { + this.quota = quota } - // Defensive default — older backends may not tag rows. - this.dashboards = (rows || []).map((d) => ({ - ...d, - source: d.source ?? SOURCE_USER, - })) - - // Load the active dashboard - const activeResponse = await api.getActiveDashboard() + this.dashboards = dashboardRowsOf(payload) + if (activeResponse.data) { - this.activeDashboard = { - ...activeResponse.data.dashboard, - // getActive can now resolve a group/showcase dashboard - // the user doesn't own (via the last-used preference), - // so honour the ownership tags it returns; default to - // owner when an older backend omits them. - isOwner: activeResponse.data.isOwner ?? true, - sharedBy: activeResponse.data.sharedBy ?? null, - // dashboard-language-and-details-tabs: more than one - // language version, so the page reads the resolved one. - hasVariants: activeResponse.data.hasVariants === true, - } + this.activeDashboard = activeDashboardOf(activeResponse.data) this.widgetPlacements = activeResponse.data.placements || [] this.permissionLevel = activeResponse.data.permissionLevel || 'full' @@ -438,9 +785,33 @@ export const useDashboardStore = defineStore('dashboard', { logger.error('Failed to load dashboards:', error) } finally { this.loading = false + this.loadedOnce = true + } + + const requested = this.requestedDashboardId + this.requestedDashboardId = null + if (requested !== null && String(this.activeDashboardId) !== String(requested)) { + await this.switchDashboard(requested) } }, + /** + * Open the dashboard an address names (`/dashboards/:id`). Before the + * first load has finished the request is kept and applied when it + * does, so the stored active dashboard does not replace it. + * + * @param {string|number} dashboardId Id of the dashboard to open. + * @return {Promise<void>} + * @spec openspec/specs/manifest-routing/spec.md#requirement-req-route-003-a-dashboard-has-an-address + */ + async openDashboard(dashboardId) { + if (!this.loadedOnce) { + this.requestedDashboardId = dashboardId + return + } + await this.switchDashboard(dashboardId) + }, + /** * Make another dashboard active and load its placements. * @@ -491,6 +862,53 @@ export const useDashboardStore = defineStore('dashboard', { } }, + /** + * Re-read the active dashboard's placements in place, without the + * loading state, so a kiosk screen updates with no flash + * (REQ-KIOSK-004). A failed read keeps what is on screen. + * + * @return {Promise<void>} + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + async reloadPlacements() { + const id = this.activeDashboard?.id + if (!id) { + return + } + try { + const response = await api.getDashboardById(id) + this.widgetPlacements = response.data.placements || [] + } catch (error) { + logger.error('Failed to reload the dashboard:', error) + } + }, + + /** + * Re-read whether the visibility rules hide each placement of the + * active dashboard for its viewers, and copy that onto the loaded + * placements. The layout itself is left alone, so unsaved edits stay. + * + * @return {Promise<void>} + * @spec openspec/specs/conditional-visibility/spec.md + */ + async refreshPlacementVisibility() { + const id = this.activeDashboard?.id + if (!id) { + return + } + try { + const response = await api.getDashboardById(id) + const hidden = new Map( + (response.data.placements || []).map((p) => [p.id, p.hiddenForViewers === true]), + ) + this.widgetPlacements = this.widgetPlacements.map((p) => + hidden.has(p.id) ? { ...p, hiddenForViewers: hidden.get(p.id) } : p, + ) + } catch (error) { + logger.error('Failed to refresh widget visibility:', error) + } + }, + /** * Persist the active-dashboard preference (REQ-DASH-019). * @@ -592,24 +1010,35 @@ export const useDashboardStore = defineStore('dashboard', { if (!dashboard || !dashboard.uuid) { return } + const fields = publicationFields(dashboard) const idx = this.dashboards.findIndex((d) => d.uuid === dashboard.uuid) if (idx >= 0) { - this.dashboards[idx] = { - ...this.dashboards[idx], - publicationStatus: dashboard.publicationStatus, - publishAt: dashboard.publishAt, - publishedAt: dashboard.publishedAt, - unpublishAt: dashboard.unpublishAt ?? null, - } + this.dashboards[idx] = { ...this.dashboards[idx], ...fields } } if (this.activeDashboard?.uuid === dashboard.uuid) { - this.activeDashboard = { - ...this.activeDashboard, - publicationStatus: dashboard.publicationStatus, - publishAt: dashboard.publishAt, - publishedAt: dashboard.publishedAt, - unpublishAt: dashboard.unpublishAt ?? null, - } + this.activeDashboard = { ...this.activeDashboard, ...fields } + } + }, + + /** + * Merge changed fields into a loaded dashboard and, when it is open, + * into the active one, so the page follows a setting stored elsewhere. + * + * @param {string} uuid The dashboard's uuid. + * @param {object} fields The changed fields. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 + */ + applyFieldsPatch(uuid, fields) { + if (!uuid || !fields) { + return + } + const idx = this.dashboards.findIndex((d) => d.uuid === uuid) + if (idx >= 0) { + this.dashboards[idx] = { ...this.dashboards[idx], ...fields } + } + if (this.activeDashboard?.uuid === uuid) { + this.activeDashboard = { ...this.activeDashboard, ...fields } } }, @@ -631,15 +1060,7 @@ export const useDashboardStore = defineStore('dashboard', { if (status !== STATUS_SCHEDULED) { return status } - const publishAt = dashboard.publishAt - if (!publishAt) { - return STATUS_SCHEDULED - } - const when = new Date(publishAt) - if (Number.isNaN(when.getTime())) { - return STATUS_SCHEDULED - } - return when.getTime() <= Date.now() ? STATUS_PUBLISHED : STATUS_SCHEDULED + return scheduledStatus(dashboard.publishAt) }, /** @@ -651,18 +1072,7 @@ export const useDashboardStore = defineStore('dashboard', { * @spec openspec/specs/dashboards/spec.md */ async createDashboard(payload = 'My Dashboard') { - // Accept either a plain name string or an object with - // name/description/icon (legacy callers may pass a string). - const data = - typeof payload === 'string' - ? { name: payload } - : { - name: payload.name || 'My Dashboard', - description: payload.description, - // Optional registry key from the `dashboard-icons` - // capability — null/undefined skips the field server-side. - icon: payload.icon ?? null, - } + const data = newDashboardData(payload) this.loading = true try { const response = await api.createDashboard(data) @@ -680,40 +1090,7 @@ export const useDashboardStore = defineStore('dashboard', { // dashboard renders cleanly until the user adds widgets. this.widgetPlacements = response.data.placements ?? [] } catch (error) { - // REQ-ASET-003 (extended): when the backend returns the - // stable `personal_dashboards_disabled` envelope, surface - // a localised toast — the UI may have offered a stale - // affordance or the call may bypass the UI altogether. - if ( - error?.response?.status === 403 - && error?.response?.data?.error - === ERR_PERSONAL_DASHBOARDS_DISABLED - ) { - showError( - t( - 'launchpad', - 'Personal dashboards are not enabled by your administrator', - ), - ) - } - // dashboard-quota-limits REQ-QUOTA-006 (race case): the UI - // affordance may have been stale (limit reached in another - // tab). Surface the structured 409 as a clear message and - // refresh the quota envelope so the button disables. - if ( - error?.response?.status === 409 - && error?.response?.data?.error === 'quota_exceeded' - ) { - const limit = error.response.data.limit - showError( - t( - 'launchpad', - 'You have reached the limit of {limit} dashboards', - { limit }, - ), - ) - this.loadDashboards().catch(() => {}) - } + reportCreateFailure(this, error) logger.error('Failed to create dashboard:', error) throw error } finally { @@ -751,34 +1128,16 @@ export const useDashboardStore = defineStore('dashboard', { sharedBy: null, }) this.activeDashboard = { ...fork, isOwner: true, sharedBy: null } - // Placements come back via the next switchDashboard / - // loadDashboards round-trip — fork is a brand-new - // active dashboard but the by-id endpoint is the - // canonical source of truth for placements. this.widgetPlacements = [] this.permissionLevel = 'full' + // The fork carries the source's widgets; the by-id + // endpoint is the canonical source of its placements. + await this.switchDashboard(fork.id) } return fork } catch (error) { - // REQ-ASET-003 (extended): surface the localised toast - // for the gating envelope. Other errors (404 source - // not visible, 500 rollback) are surfaced via the - // caller; we just log here. - if ( - error?.response?.status === 403 - && error?.response?.data?.error - === ERR_PERSONAL_DASHBOARDS_DISABLED - ) { - showError( - t( - 'launchpad', - 'Personal dashboards are not enabled by your administrator', - ), - ) - } else if (error?.response?.status === 404) { - showError(t('launchpad', 'Dashboard not found')) - } else { - showError(t('launchpad', 'Failed to fork dashboard')) + if (!reportDashboardQuota(this, error)) { + showError(forkFailureText(error)) } logger.error('Failed to fork dashboard:', error) throw error @@ -796,6 +1155,7 @@ export const useDashboardStore = defineStore('dashboard', { * @param {Array<object>} placements Every placement on the dashboard, * carrying the geometry to store. * @spec openspec/specs/dashboards/spec.md + * @spec openspec/specs/grid-layout/spec.md */ async updatePlacements(placements) { logger.debug( @@ -808,40 +1168,102 @@ export const useDashboardStore = defineStore('dashboard', { // Debounced save to backend this.saving = true - try { - const placementsData = placements.map((p) => ({ - id: p.id, - gridX: p.gridX, - gridY: p.gridY, - gridWidth: p.gridWidth, - gridHeight: p.gridHeight, - })) - logger.debug( - '[DashboardStore] Sending placements to API:', - JSON.stringify(placementsData, null, 2), - ) + const sequence = ++layoutSaveSequence + const placementsData = placements.map((p) => ({ + id: p.id, + gridX: p.gridX, + gridY: p.gridY, + gridWidth: p.gridWidth, + gridHeight: p.gridHeight, + })) + logger.debug( + '[DashboardStore] Sending placements to API:', + JSON.stringify(placementsData, null, 2), + ) - // REQ-DASH-013 — route the PUT to the correct endpoint - // based on the active dashboard's source. - const active = this.activeDashboard - if ( - active - && (active.source === SOURCE_GROUP - || active.source === SOURCE_DEFAULT) - ) { - await api.updateGroupDashboard(active.groupId, active.uuid, { + // REQ-DASH-013 — route the PUT to the correct endpoint + // based on the active dashboard's source. + const active = this.activeDashboard + const save = () => ( + active + && (active.source === SOURCE_GROUP + || active.source === SOURCE_DEFAULT) + ? api.updateGroupDashboard(active.groupId, active.uuid, { placements: placementsData, }) - } else { - await api.updateDashboard(active.id, { + : api.updateDashboard(active.id, { placements: placementsData, }) + ) + + // A failed save is reported once and retried automatically, up + // to three times; a newer layout replaces the retries of an older + // one (grid-layout "Save failure with retry"). + try { + for (let attempt = 0; ; attempt++) { + try { + await save() + logger.debug('[DashboardStore] Successfully saved placements') + return + } catch (error) { + logger.error('Failed to save placements:', error) + if (attempt === 0) { + showError(t('launchpad', 'The layout could not be saved. Trying again.')) + } + if (attempt >= LAYOUT_SAVE_RETRY_DELAYS_MS.length) { + showError(t('launchpad', 'The layout could not be saved.')) + return + } + } + await wait(LAYOUT_SAVE_RETRY_DELAYS_MS[attempt]) + if (sequence !== layoutSaveSequence) { + return + } } - logger.debug('[DashboardStore] Successfully saved placements') - } catch (error) { - logger.error('Failed to save placements:', error) } finally { - this.saving = false + if (sequence === layoutSaveSequence) { + this.saving = false + } + } + }, + + /** + * Give the active dashboard 6, 8 or 12 grid columns (the edit bar's + * Columns), through the personal or the group endpoint like the + * placements. The grid follows at once; a refused save puts the old + * count back. + * + * @param {number} columns The new column count. + * @return {Promise<boolean>} Whether the server stored it. + * @spec openspec/specs/dashboards/spec.md#requirement-req-dash-038-the-edit-bar + */ + async setGridColumns(columns) { + const active = this.activeDashboard + if (!active || active.gridColumns === columns) { + return false + } + const previous = active.gridColumns + const apply = (value) => { + this.activeDashboard = { ...this.activeDashboard, gridColumns: value } + this.dashboards = this.dashboards.map((d) => + d.id === active.id ? { ...d, gridColumns: value } : d, + ) + } + apply(columns) + try { + if (active.source === SOURCE_GROUP || active.source === SOURCE_DEFAULT) { + await api.updateGroupDashboard(active.groupId, active.uuid, { + gridColumns: columns, + }) + } else { + await api.updateDashboard(active.id, { gridColumns: columns }) + } + return true + } catch (error) { + logger.error('Failed to save the grid columns:', error) + apply(previous) + showError(t('launchpad', 'The number of columns could not be saved.')) + return false } }, @@ -867,54 +1289,14 @@ export const useDashboardStore = defineStore('dashboard', { */ async addWidgetToDashboard(widgetId, position = null) { try { - // AddWidgetModal emits a `{type, content}` payload for the - // registry-driven custom widgets (label, text, image, …). - // The legacy callers — sidebar "Add widget" buttons that - // pick a Nextcloud Dashboard API widget by id — pass a - // plain string. Both must funnel through the same store - // method, so unpack the object form into the API contract - // (`widgetId` string + `content` object) here rather than - // pushing the type-discrimination into every caller. - const isCustomPayload = - widgetId !== null - && typeof widgetId === 'object' - && typeof widgetId.type === 'string' - const resolvedWidgetId = isCustomPayload ? widgetId.type : widgetId - const resolvedContent = isCustomPayload - ? (widgetId.content ?? {}) - : null - - const placement = - position - && Number.isFinite(position.x) - && Number.isFinite(position.y) - ? { - x: position.x, - y: position.y, - w: position.w ?? DEFAULT_W, - h: position.h ?? DEFAULT_H, - pushed: [], - } - : placeNewWidget( - { w: position?.w, h: position?.h }, - this.widgetPlacements, - { gridColumns: this.activeDashboard?.gridColumns }, - ) - - const requestBody = { - widgetId: resolvedWidgetId, - gridX: placement.x, - gridY: placement.y, - gridWidth: placement.w, - gridHeight: placement.h, - } - if (resolvedContent !== null) { - requestBody.content = resolvedContent - } - + const type = typeof widgetId === 'object' && widgetId !== null ? widgetId.type : widgetId + const placement = newPlacement(position, { + size: defaultSizeFor(type, this.activeDashboard?.gridColumns || undefined), + store: this, + }) const response = await api.addWidget( this.activeDashboard.id, - requestBody, + widgetRequestBody(widgetId, placement), ) this.widgetPlacements.push(response.data) @@ -932,6 +1314,23 @@ export const useDashboardStore = defineStore('dashboard', { } }, + /** + * Import chosen browser bookmarks onto the active dashboard. The server + * appends the containers and tiles at the bottom and answers with them + * and the skipped bookmarks; the new placements join the store. A 409 + * (not enough room left) is rethrown for the dialog to explain. + * + * @param {{folders: Array<object>, bookmarks: Array<object>}} chosen The chosen folders and loose bookmarks. + * @return {Promise<{placements: Array<object>, skipped: Array<object>}>} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md + */ + async importBookmarks(chosen) { + const response = await api.importBookmarks(this.activeDashboard.id, chosen) + const placements = Array.isArray(response.data?.placements) ? response.data.placements : [] + this.widgetPlacements.push(...placements) + return { placements, skipped: Array.isArray(response.data?.skipped) ? response.data.skipped : [] } + }, + /** * Add a tile to the active dashboard. Tiles default to a smaller * 2×2 footprint than regular widgets but still funnel through @@ -946,22 +1345,10 @@ export const useDashboardStore = defineStore('dashboard', { */ async addTileToDashboard(tileData, position = null) { try { - const placement = - position - && Number.isFinite(position.x) - && Number.isFinite(position.y) - ? { - x: position.x, - y: position.y, - w: position.w ?? 2, - h: position.h ?? 2, - pushed: [], - } - : placeNewWidget( - { w: position?.w ?? 2, h: position?.h ?? 2 }, - this.widgetPlacements, - { gridColumns: this.activeDashboard?.gridColumns }, - ) + const placement = newPlacement(position, { + size: { w: 2, h: 2 }, + store: this, + }) const response = await api.addTile(this.activeDashboard.id, { ...tileData, @@ -1141,9 +1528,7 @@ export const useDashboardStore = defineStore('dashboard', { * @spec openspec/specs/dashboards/spec.md */ async dashboardByPath(path) { - const key = String(path || '') - .replace(/\/+$/, '') - .replace(/^\/+/, '') + const key = dashboardPathKey(path) if (key === '') { return null } @@ -1152,18 +1537,9 @@ export const useDashboardStore = defineStore('dashboard', { return this.pathCache[key] } - try { - const response = await api.getDashboardByPath(key) - const payload = response?.data?.dashboard ?? null - this.pathCache[key] = payload - return payload - } catch (error) { - if (error?.response?.status !== 404) { - logger.error('Failed to resolve dashboard path:', error) - } - this.pathCache[key] = null - return null - } + const payload = await resolveDashboardPath(key) + this.pathCache[key] = payload + return payload }, /** @@ -1357,27 +1733,12 @@ export const useDashboardStore = defineStore('dashboard', { try { const response = await api.getDashboardMetadata(uuid) - const payload = response?.data - const map = - payload && typeof payload === 'object' && !Array.isArray(payload) - ? payload - : {} - this.metadataByDashboard = { - ...this.metadataByDashboard, - [uuid]: map, - } - return map + return cacheMetadata(this, { uuid, map: metadataMapOf(response) }) } catch (error) { - if ( - error?.response?.status !== 403 - && error?.response?.status !== 404 - ) { + if (![403, 404].includes(error?.response?.status)) { logger.error('Failed to load dashboard metadata:', error) } - this.metadataByDashboard = { - ...this.metadataByDashboard, - [uuid]: {}, - } + cacheMetadata(this, { uuid, map: {} }) return {} } }, @@ -1402,16 +1763,7 @@ export const useDashboardStore = defineStore('dashboard', { try { const response = await api.updateDashboardMetadata(uuid, metadata) - const payload = response?.data - const map = - payload && typeof payload === 'object' && !Array.isArray(payload) - ? payload - : {} - this.metadataByDashboard = { - ...this.metadataByDashboard, - [uuid]: map, - } - return map + return cacheMetadata(this, { uuid, map: metadataMapOf(response) }) } catch (error) { const message = error?.response?.data?.message diff --git a/src/stores/groupDashboards.js b/src/stores/groupDashboards.js index c7959e4a1..c4765f0f8 100644 --- a/src/stores/groupDashboards.js +++ b/src/stores/groupDashboards.js @@ -24,13 +24,13 @@ import { api } from '../services/api.js' export const DEFAULT_GROUP_ID = 'default' /** - * Stable backend error code returned by `DELETE /api/dashboards/group/...` - * when the deletion would leave the group with no dashboard at all - * (REQ-DASH-016 last-in-group guard). + * The error `DELETE /api/dashboards/group/...` answers when the deletion + * would leave the group with no dashboard at all (REQ-DASH-014 + * last-in-group guard). * * @type {string} */ -const ERR_LAST_GROUP_DASHBOARD = 'last_group_dashboard' +const ERR_LAST_GROUP_DASHBOARD = 'Cannot delete the only dashboard in the group' export const useGroupDashboardsStore = defineStore('groupDashboards', { state: () => ({ diff --git a/src/stores/orgNavigation.js b/src/stores/orgNavigation.js index 872bd601d..86c049234 100644 --- a/src/stores/orgNavigation.js +++ b/src/stores/orgNavigation.js @@ -18,6 +18,7 @@ import { defineStore } from 'pinia' import { api } from '../services/api.js' +import { takeOrgNavigation } from '../utils/loadInitialState.js' /** * Allowed values for the global rail position (REQ-ONAV-004). @@ -26,6 +27,19 @@ import { api } from '../services/api.js' */ export const ORG_NAV_POSITIONS = Object.freeze(['left', 'right', 'top', 'hidden']) +/** + * The message for a failed tree save: the `error` string of the response + * body when the backend sent one, a generic message otherwise. + * + * @param {unknown} err The caught request error. + * @return {string} The message. + */ +function saveErrorOf(err) { + const responseError = + err && err.response && err.response.data ? err.response.data.error : null + return responseError || 'Failed to save navigation' +} + export const useOrgNavigationStore = defineStore('orgNavigation', { state: () => ({ // Current filtered tree for the active language. Empty array @@ -134,17 +148,34 @@ export const useOrgNavigationStore = defineStore('orgNavigation', { this.error = null return true } catch (err) { - const responseError = - err && err.response && err.response.data - ? err.response.data.error - : null - this.error = responseError || 'Failed to save navigation' + this.error = saveErrorOf(err) return false } finally { this.loading = false } }, + /** + * The shell's first load: the position and tree the page carries, + * or both from the API when it carries none. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/tasks.md#task-3 + */ + async loadFirst() { + const firstLoad = takeOrgNavigation() + if (firstLoad === null) { + await Promise.all([this.fetchPosition(), this.fetchTree()]) + return + } + if (ORG_NAV_POSITIONS.includes(firstLoad.position)) { + this.position = firstLoad.position + } + this.tree = firstLoad.tree + this.language = firstLoad.language + this.error = null + }, + /** * Fetch the current global rail position (REQ-ONAV-004). * diff --git a/src/stores/scheduledExports.js b/src/stores/scheduledExports.js new file mode 100644 index 000000000..3f7eef6af --- /dev/null +++ b/src/stores/scheduledExports.js @@ -0,0 +1,183 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' +import { defineStore } from 'pinia' + +const baseUrl = generateUrl('/apps/launchpad/api/exports') + +/** How long runExportNow waits between run-status polls, in milliseconds. */ +export const POLL_INTERVAL_MS = 2000 + +/** How many polls runExportNow makes before it gives up waiting. */ +export const MAX_POLLS = 90 + +/** + * Wait a number of milliseconds. + * + * @param {number} ms The wait. + * @return {Promise<void>} + */ +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** + * Scheduled exports through the LaunchPad export API (never straight to + * OpenRegister: the API validates, schedules and keeps channel secrets + * encrypted and redacted). + * + * @spec openspec/changes/scheduled-exports/tasks.md#task-17 + */ +export const useExportsStore = defineStore('scheduledExports', { + state: () => ({ + /** @type {object[]} the exports the user may see */ + exports: [], + /** @type {Record<string, object[]>} run-rows per export id, newest first */ + runsByExport: {}, + /** @type {Record<string, boolean>} export ids with a "Run now" in progress */ + running: {}, + loading: false, + }), + + actions: { + /** + * Load the exports the user may see. + * + * @return {Promise<object[]>} + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + async fetchExports() { + this.loading = true + try { + const { data } = await axios.get(baseUrl, { params: { limit: 200 } }) + this.exports = data.results ?? [] + return this.exports + } finally { + this.loading = false + } + }, + + /** + * Create or update an export; the saved export replaces the listed one. + * + * @param {object} exportData The export; with an `id` it is updated. + * @return {Promise<object>} The saved export. + * @spec openspec/changes/scheduled-exports/tasks.md#task-12 + */ + async saveExport(exportData) { + const { data } = exportData.id + ? await axios.patch(`${baseUrl}/${exportData.id}`, exportData) + : await axios.post(baseUrl, exportData) + const index = this.exports.findIndex((e) => e.id === data.id) + if (index === -1) { + this.exports.push(data) + } else { + this.exports.splice(index, 1, data) + } + return data + }, + + /** + * Soft-delete an export. + * + * @param {string} exportId The export. + * @return {Promise<void>} + * @spec openspec/changes/scheduled-exports/tasks.md#task-13 + */ + async deleteExport(exportId) { + await axios.delete(`${baseUrl}/${exportId}`) + this.exports = this.exports.filter((e) => e.id !== exportId) + }, + + /** + * "Run now": start a manual run and poll its run-row until it is no + * longer running (or the poll budget is spent). `onProgress` gets the + * row after every poll, for a progress toast. + * + * @param {string} exportId The export. + * @param {{onProgress?: function(object): void, interval?: number, maxPolls?: number}} [options] Polling options. + * @return {Promise<object>} The last run-row seen. + * @spec openspec/changes/scheduled-exports/tasks.md#task-17 + */ + async runExportNow(exportId, { onProgress = () => {}, interval = POLL_INTERVAL_MS, maxPolls = MAX_POLLS } = {}) { + this.running = { ...this.running, [exportId]: true } + try { + let { data: run } = await axios.post(`${baseUrl}/${exportId}/run`) + onProgress(run) + for (let poll = 0; run.status === 'running' && poll < maxPolls; poll++) { + await wait(interval) + run = (await axios.get(`${baseUrl}/${exportId}/runs/${run.id}`)).data + onProgress(run) + } + this.runsByExport = { ...this.runsByExport, [exportId]: [run, ...(this.runsByExport[exportId] ?? []).filter((r) => r.id !== run.id)] } + return run + } finally { + const rest = { ...this.running } + delete rest[exportId] + this.running = rest + } + }, + + /** + * "Preview": render for one recipient in one format, without delivering. + * + * @param {string} exportId The export. + * @param {string} recipientId The recipient whose filter context applies ('' for none). + * @param {string} format pdf, png, csv or xlsx. + * @return {Promise<Blob>} The rendered file. + * @spec openspec/changes/scheduled-exports/tasks.md#task-18 + */ + async previewExport(exportId, recipientId, format) { + const { data } = await axios.post(`${baseUrl}/${exportId}/preview`, null, { + params: { recipientId: recipientId ?? '', format }, + responseType: 'blob', + }) + return data + }, + + /** + * Load an export's run history. + * + * @param {string} exportId The export. + * @return {Promise<object[]>} The run-rows, newest first. + * @spec openspec/changes/scheduled-exports/tasks.md#task-14 + */ + async fetchRuns(exportId) { + const { data } = await axios.get(`${baseUrl}/${exportId}/runs`, { params: { limit: 200 } }) + this.runsByExport = { ...this.runsByExport, [exportId]: data.results ?? [] } + return this.runsByExport[exportId] + }, + + /** + * Load one run-row with every delivery; it replaces the listed row. + * + * @param {string} exportId The export. + * @param {string} runId The run. + * @return {Promise<object>} The run-row. + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ + async fetchRun(exportId, runId) { + const { data } = await axios.get(`${baseUrl}/${exportId}/runs/${runId}`) + const runs = this.runsByExport[exportId] ?? [] + this.runsByExport = { ...this.runsByExport, [exportId]: runs.map((r) => (r.id === runId ? data : r)) } + return data + }, + + /** + * Retry every delivery of a run that failed for good. + * + * @param {string} exportId The export. + * @param {string} runId The run. + * @return {Promise<object>} The updated run-row. + * @spec openspec/changes/scheduled-exports/tasks.md#task-15 + */ + async retryRun(exportId, runId) { + const { data } = await axios.post(`${baseUrl}/${exportId}/runs/${runId}/retry`) + const runs = this.runsByExport[exportId] ?? [] + this.runsByExport = { ...this.runsByExport, [exportId]: runs.map((r) => (r.id === runId ? data : r)) } + return data + }, + }, +}) diff --git a/src/stores/tilePanel.js b/src/stores/tilePanel.js new file mode 100644 index 000000000..52e8fa15c --- /dev/null +++ b/src/stores/tilePanel.js @@ -0,0 +1,68 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The one panel beside the tiles that a `side-panel` tile opens in + * (launcher-tile-open-behaviour D3). A tile writes here; `WorkspaceApp` + * renders `TileSidePanel` from it. Opening another tile replaces the panel. + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +import { defineStore } from 'pinia' + +export const useTilePanelStore = defineStore('launchpad-tile-panel', { + state: () => ({ + /** The address shown, or null when the panel is closed. */ + url: null, + /** The tile's title, shown in the panel header. */ + title: '', + /** Whether the address is on this Nextcloud (no framing check needed). */ + sameOrigin: false, + /** The element focus returns to on close. */ + opener: null, + }), + + getters: { + isOpen: (state) => state.url !== null, + }, + + actions: { + /** + * Open the panel, replacing whatever it showed. + * + * @param {object} tile The tile being opened. + * @param {string} tile.url The address to show. + * @param {string} [tile.title] The tile's title. + * @param {boolean} [tile.sameOrigin] Whether the address is on this Nextcloud. + * @param {HTMLElement|null} [tile.opener] The element focus returns to on close. + * @return {void} + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md#requirement-a-tile-can-open-its-app-in-a-panel-beside-the-tiles-req-tob-003 + */ + open({ url, title = '', sameOrigin = false, opener = null }) { + this.url = url + this.title = title + this.sameOrigin = sameOrigin + this.opener = opener + }, + + /** + * Close the panel and return focus to the tile that opened it. + * + * @return {void} + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md#requirement-a-tile-can-open-its-app-in-a-panel-beside-the-tiles-req-tob-003 + */ + close() { + const opener = this.opener + this.url = null + this.title = '' + this.sameOrigin = false + this.opener = null + if (opener && typeof opener.focus === 'function') { + opener.focus() + } + }, + }, +}) diff --git a/src/stores/tiles.js b/src/stores/tiles.js index e43ea7c2c..714ebd359 100644 --- a/src/stores/tiles.js +++ b/src/stores/tiles.js @@ -5,6 +5,7 @@ import { defineStore } from 'pinia' import { api } from '../services/api.js' +import { takeBootRead } from '../utils/loadInitialState.js' import { logger } from '../utils/logger.js' export const useTileStore = defineStore('tiles', { @@ -14,8 +15,19 @@ export const useTileStore = defineStore('tiles', { }), actions: { - /** @spec openspec/specs/tiles/spec.md */ + /** + * Load the user's tiles: the first load from the tiles the page + * carries, every later load (and a page without them) from the API. + * + * @return {Promise<void>} + * @spec openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/tasks.md#task-3 + */ async loadTiles() { + const carried = takeBootRead('tiles') + if (Array.isArray(carried)) { + this.tiles = carried + return + } this.loading = true try { const response = await api.getTiles() diff --git a/src/stores/widgets.js b/src/stores/widgets.js index bc6e20a95..b669a12e5 100644 --- a/src/stores/widgets.js +++ b/src/stores/widgets.js @@ -6,8 +6,41 @@ import { defineStore } from 'pinia' import { api } from '../services/api.js' import { widgetBridge } from '../services/widgetBridge.js' +import { initialWidgetCatalogue } from '../utils/loadInitialState.js' import { logger } from '../utils/logger.js' +/** + * Set the loading flag of each listed widget's items entry, keeping the rest + * of the entry. + * + * @param {object} widgetItems The store's items entries by widget id. + * @param {{widgetIds: string[], loading: boolean}} change The widgets and the flag. + * @return {void} + * @spec openspec/specs/widgets/spec.md + */ +function markLoading(widgetItems, { widgetIds, loading }) { + for (const id of widgetIds) { + widgetItems[id] = { ...widgetItems[id], loading } + } +} + +/** + * The loaded items entry of one widget from its items response, with empty + * defaults for the fields the response leaves out. + * + * @param {object} data The widget's part of the items response. + * @return {object} The items entry. + * @spec openspec/specs/widgets/spec.md + */ +function widgetItemsEntry(data) { + return { + items: data.items || [], + emptyContentMessage: data.emptyContentMessage || '', + halfEmptyContentMessage: data.halfEmptyContentMessage || '', + loading: false, + } +} + export const useWidgetStore = defineStore('widgets', { state: () => ({ availableWidgets: [], @@ -26,8 +59,22 @@ export const useWidgetStore = defineStore('widgets', { }, actions: { - /** @spec openspec/specs/widgets/spec.md */ + /** + * Fill the card library's widget list: from the page's initial state + * when it carries one, so no `GET /api/widgets` is needed + * (REQ-RFP-010), otherwise from that call. + * + * @spec openspec/specs/widgets/spec.md + * @spec openspec/specs/role-feature-permissions/spec.md#requirement-req-rfp-010-initial-state-widget-allowlist + */ async loadAvailableWidgets() { + const catalogue = initialWidgetCatalogue() + if (catalogue.length > 0) { + this.availableWidgets = catalogue + widgetBridge.setWidgetMetadata(this.availableWidgets) + return + } + this.loading = true try { const response = await api.getAvailableWidgets() @@ -51,10 +98,7 @@ export const useWidgetStore = defineStore('widgets', { */ async loadWidgetItems(widgetIds) { logger.debug('[WidgetStore] loadWidgetItems called:', widgetIds) - // Mark widgets as loading - for (const id of widgetIds) { - this.widgetItems[id] = { ...this.widgetItems[id], loading: true } - } + markLoading(this.widgetItems, { widgetIds, loading: true }) try { const response = await api.getWidgetItems(widgetIds) @@ -68,21 +112,11 @@ export const useWidgetStore = defineStore('widgets', { 'Items:', data.items, ) - this.widgetItems[widgetId] = { - items: data.items || [], - emptyContentMessage: data.emptyContentMessage || '', - halfEmptyContentMessage: data.halfEmptyContentMessage || '', - loading: false, - } + this.widgetItems[widgetId] = widgetItemsEntry(data) } } catch (error) { logger.error('Failed to load widget items:', error) - for (const id of widgetIds) { - this.widgetItems[id] = { - ...this.widgetItems[id], - loading: false, - } - } + markLoading(this.widgetItems, { widgetIds, loading: false }) } }, diff --git a/src/styles/__tests__/workspaceLinksWidget.spec.js b/src/styles/__tests__/workspaceLinksWidget.spec.js new file mode 100644 index 000000000..1a6af7860 --- /dev/null +++ b/src/styles/__tests__/workspaceLinksWidget.spec.js @@ -0,0 +1,26 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The workspace stylesheet leaves the links widget's own layouts alone: + * card, inline and icon-only are drawn by CnLinksWidget, with their icons + * (openspec/specs/links-widget, REQ-LNKS-004 and -005). A page-wide rule on + * `.cn-links-widget` restyles every links widget on every dashboard. + */ + +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(resolve(__dirname, '../workspace.css'), 'utf8') + +describe('workspace.css and the links widget', () => { + it('targets the links widget only inside the board look', () => { + const selectors = (css.replace(/\/\*[\s\S]*?\*\//g, '').match(/[^{}]+(?=\{)/g) ?? []) + .flatMap((list) => list.split(/,(?![^(]*\))/)) + const linkRules = selectors.filter((selector) => selector.includes('.cn-links-widget')) + for (const selector of linkRules) { + expect(selector.trim()).toMatch(/^\.cn-look-board /) + } + }) +}) diff --git a/src/styles/kiosk.css b/src/styles/kiosk.css new file mode 100644 index 000000000..7b9f1b9c8 --- /dev/null +++ b/src/styles/kiosk.css @@ -0,0 +1,25 @@ +/* + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Kiosk mode (REQ-KIOSK-001): the dashboard fills the screen with no + * scrollbars, and the cursor hides while the pointer is idle. + */ + +html.launchpad-kiosk, +html.launchpad-kiosk body { + overflow: hidden; +} + +html.launchpad-kiosk #launchpad-app.launchpad-app--kiosk { + position: fixed; + inset: 0; + z-index: 2000; + overflow: hidden; + background-color: var(--color-main-background); +} + +html.launchpad-kiosk--idle, +html.launchpad-kiosk--idle * { + cursor: none !important; +} diff --git a/src/styles/modals.css b/src/styles/modals.css new file mode 100644 index 000000000..527dfe0c7 --- /dev/null +++ b/src/styles/modals.css @@ -0,0 +1,45 @@ +/* + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * LaunchPad's modals draw their own title (an h2 in the body, as the boards + * do). NcModal also draws its `name` in a header bar over the backdrop, so + * the title showed twice, the second one floating over the top bar. The name + * stays on the modal for the accessible label; only its visible copy is + * hidden. + */ +.modal-mask.launchpad-modal .modal-header__name { + display: none; +} + +/* + * The board dialog frame (LpDashboardInstellingen, LpVersies): 720px wide, + * the dashboard's name as a small line over a 20px title. + * + * Capped at the wrapper's width: this rule outranks NcModal's phone rule + * (full width at 512px and below), so a bare 720px left the frame wider + * than a phone screen, centred, with its left edge cut off. + */ +.modal-mask.launchpad-modal--wide .modal-wrapper--normal > .modal-container { + width: min(720px, 100%); +} + +/* + * The house style (thematiq) sets heading and paragraph type with + * !important on bare `h2` and `p`, which beats any class here. The frame's + * two lines need their board sizes, so they answer with !important too and + * win on specificity. + */ +.modal-mask.launchpad-modal .launchpad-modal__kicker { + margin: 0; + font-size: 13px !important; + font-weight: 600 !important; + color: var(--color-text-maxcontrast); +} + +.modal-mask.launchpad-modal h2.launchpad-modal__title { + margin: 0; + font-size: 20px !important; + font-weight: 700 !important; + line-height: 1.3; +} diff --git a/src/styles/print.css b/src/styles/print.css new file mode 100644 index 000000000..1501039a6 --- /dev/null +++ b/src/styles/print.css @@ -0,0 +1,38 @@ +/* + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * Download the dashboard (REQ-DPD-003): the PDF is the page printed in the + * reader's browser. Print the dashboard name, its meta line and the widgets; + * the chosen period stays visible; Nextcloud's top bar, the docked menu and the + * Download button are left out. + */ + +@media print { + #header, + #body-user #header, + .app-navigation, + .launchpad-page-header__dock, + .launchpad-print-hide { + display: none !important; + } + + html, + body, + #content, + #content-vue, + #app-content, + #app-content-vue, + #launchpad-app { + height: auto !important; + min-height: 0 !important; + overflow: visible !important; + margin: 0 !important; + padding-top: 0 !important; + background: #fff !important; + } + + .grid-stack-item { + break-inside: avoid; + } +} diff --git a/src/styles/workspace.css b/src/styles/workspace.css index 86d8d8346..2759359c9 100644 --- a/src/styles/workspace.css +++ b/src/styles/workspace.css @@ -144,3 +144,397 @@ .vs__dropdown-menu { --vs-dropdown-z-index: 10100; } + +/* ========================================================= + A list widget on a dashboard keeps every column inside its card. + The case lists of "Mijn werkdag" are six columns wide and hold four + columns (number, case, status, deadline). Under the table's automatic + layout a long case number or title widened its column and pushed + Status and Termijn past the card edge, where they were cut off + (LpStart, :8080 07 Oct). A fixed layout shares the width between the + columns, and a value too long for its column ends in an ellipsis; the + whole value stays in the cell's title on the row's detail page. + ========================================================= */ +.launchpad-container .cn-object-list-widget table.cn-data-table { + table-layout: fixed; + width: 100%; +} + +.launchpad-container .cn-object-list-widget table.cn-data-table td, +.launchpad-container .cn-object-list-widget table.cn-data-table th { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* ========================================================= + A dashboard without a navigation panel (REQ-SHELL-009) runs from edge to + edge, 28px in from the window: 20px here and the grid's own 8px item + margin (LpVandaag, LpWerkplek, LpIntranet). + The container is also the page's scroller, so the inset is padding, not a + max-width: the scrollbar sits at the window edge. The id outranks the + page's own scoped `padding: 8px 0 0`. + ========================================================= */ +#content.app-launchpad .launchpad-container { + box-sizing: border-box; + width: 100%; + padding-inline: 20px; +} + +/* ========================================================= + A widget card in the board look, as the Launchpad boards draw it: a white + card with a hairline and a 12px radius, a 16px bold title 16px from the + top and 18px in, its content on that same inset, and no title icon. The + Nextcloud look keeps the native dashboard panel (chrome="nc-dashboard"). + ========================================================= */ +.cn-look-board .launchpad-container .cn-widget-wrapper.cn-widget-wrapper--nc-dashboard { + border: 1px solid var(--cn-board-hairline, var(--color-border)); + border-radius: var(--cn-board-card-radius, 12px); + background: var(--color-main-background); + -webkit-backdrop-filter: none; + backdrop-filter: none; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-widget-wrapper__header { + padding: 16px 18px 8px; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-widget-wrapper__icon { + display: none; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-widget-wrapper__title { + font-size: 16px; + font-weight: 700; + line-height: 1.2; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-widget-wrapper__content { + padding: 0 18px 12px; +} + +/* The card gives the inset; a widget inside it adds none of its own, so its + first line starts on the title's 18px (the agenda, recent work, mail). The + renderer's own 16px padding added a second inset. */ +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard :is(.widget-renderer, .cn-links-widget, .cn-menu-widget) { + padding: 0; +} + +/* "Vandaag eerst" draws its own heading inside the card, 14px from the top + (LpVandaag); the card's title row is not shown for it. */ +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .widget-renderer:has(> .attention-widget) { + padding: 14px 0 4px; +} + +/* Bookmark groups are headed by a small uppercase label (LpWerkplek). */ +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-links-widget__section-title { + margin: 0; + color: var(--color-text-maxcontrast); + font-size: 12px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +/* A list in a card starts with a rule under the title, as the boards draw + the rows of recent work, mail, the agenda and status lists. */ +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard :is(.cn-nc-widget-widget__item--vertical, .cn-calendar-widget__list-row):first-child, +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-status-list__item:first-child { + border-top: 1px solid var(--color-border); +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-calendar-widget__body, +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-nc-widget-widget__body { + padding: 0; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-nc-widget-widget__body--vertical { + gap: 0; +} + +/* ========================================================= + Mijn werkdag 4 on the start page, as LpStart draws it. Each rule keys on + a widget the template declares, so a dashboard that declares none of + them looks as before. + ========================================================= */ + +/* The greeting and the section labels sit on the page ground, not in a + card: a theme that paints every element with "widget" in its class + (thematiq's solid-background rule) made them white boxes. */ +.launchpad-container + .launchpad-widget:has(.cn-header-widget--ground):not(#lp-ground-a):not( + #lp-ground-b + ), +.launchpad-container + .launchpad-widget:has(.cn-header-widget--ground) + .cn-widget-wrapper:not(#lp-ground-a):not(#lp-ground-b), +.launchpad-container + .launchpad-widget:has(.cn-header-widget--ground) + [class*='widget']:not([class*='widget__']):not(#lp-ground-a):not(#lp-ground-b), +.launchpad-container + .launchpad-widget:has(.cn-label-widget):not(#lp-ground-a):not(#lp-ground-b), +.launchpad-container + .launchpad-widget:has(.cn-label-widget) + .cn-widget-wrapper:not(#lp-ground-a):not(#lp-ground-b), +.launchpad-container + .launchpad-widget:has(.cn-label-widget) + [class*='widget']:not(#lp-ground-a):not(#lp-ground-b), +.launchpad-container + .launchpad-widget:has(.lp-section-heading):not(#lp-ground-a):not(#lp-ground-b), +.launchpad-container + .launchpad-widget:has(.lp-section-heading) + .cn-widget-wrapper:not(#lp-ground-a):not(#lp-ground-b) { + background: transparent; + border: none; + box-shadow: none; +} + +/* A greeting's call to action at the right of the greeting row, as a plain + outlined button. */ +.launchpad-container .cn-header-widget--ground { + position: relative; +} + +/* A plain or ground greeting has no banner height of its own. The library + says so (`--plain` resets its 120px banner minimum), but the same scoped + rules arrive more than once on this page (other apps' bundles inject the + library CSS too), and a later copy of the 120px rule beat the reset. The + greeting then stood 120px tall in its 104px cell, and the cell scrolled. */ +.launchpad-container .cn-header-widget.cn-header-widget--plain { + min-height: 0; +} + +.launchpad-container .cn-header-widget--ground .cn-header-widget__cta { + position: absolute; + inset-inline-end: 0; + top: 50%; + transform: translateY(-50%); + padding: 8px 16px; + border: 1px solid var(--color-border-dark); + border-radius: var(--border-radius-element, 8px); + background: var(--color-main-background); + color: var(--color-main-text) !important; + font-weight: 600; + text-decoration: none !important; +} + +/* With the workspace controls docked in the greeting row + (headerActionsDock.js), the row is the greeting, then the actions at its + right, as LpStart draws it. A call to action stays at the right of the + greeting text, which now ends where the controls begin, so the two never + overlap. */ +.launchpad-container .cn-header-widget--ground:has(> .launchpad-header-actions) { + display: flex; + align-items: center; + gap: 10px; + position: static; +} + +.launchpad-container + .cn-header-widget--ground:has(> .launchpad-header-actions) + > .cn-header-widget__content { + position: relative; + flex: 1 1 auto; + min-width: 0; + align-self: stretch; + display: flex; + flex-direction: column; + justify-content: center; +} + +/* The library's 8px top margin would put the button 8px below the + controls' centre line. */ +.launchpad-container + .cn-header-widget--ground:has(> .launchpad-header-actions) + .cn-header-widget__cta { + margin-top: 0; +} + +.launchpad-container .launchpad-header-actions { + flex: none; + display: flex; + align-items: center; +} + +/* On a phone the greeting takes the row, and a call to action wraps + under it with the controls at its right, instead of covering the heading + (LpVandaag at 390px). */ +@media (max-width: 640px) { + .launchpad-container .cn-header-widget--ground:has(> .launchpad-header-actions) { + flex-wrap: wrap; + } + + .launchpad-container + .cn-header-widget--ground:has(> .launchpad-header-actions) + > .cn-header-widget__content { + flex-basis: 100%; + } + + .launchpad-container + .cn-header-widget--ground:has(> .launchpad-header-actions) + .cn-header-widget__cta { + position: static; + align-self: flex-start; + margin-top: 8px; + transform: none; + } + + .launchpad-container .cn-header-widget--ground > .launchpad-header-actions { + position: absolute; + inset-inline-end: 0; + bottom: 0; + } +} + +/* A section label reads as a heading at the left edge. */ +.launchpad-container .cn-label-widget { + justify-content: flex-start !important; + align-items: flex-end !important; + padding-inline: 0; +} + +/* The app tiles: the number card fills its cell. The wrapper's and the + renderer's 16px padding left a 64px card for an 81px tile, which cut + the label and the caption off. */ +.launchpad-container + .launchpad-widget:has(.cn-stat-widget) + .cn-widget-wrapper__content, +.launchpad-container .launchpad-widget:has(.cn-stat-widget) .widget-renderer { + padding: 0; +} + +/* A section label starts at the card edge below it, as LpStart draws it. */ +.launchpad-container + .launchpad-widget:has(.cn-label-widget) + .cn-widget-wrapper__content, +.launchpad-container .launchpad-widget:has(.cn-label-widget) .widget-renderer, +.launchpad-container .cn-label-widget.cn-label-widget { + padding: 0; +} + +/* ========================================================= + A counter in the board look, as LpVandaag draws "Mijn werk": the app's + glyph in a 36px tinted square beside two lines, the label in 13px muted + and the number in 26px bold with its caption on the same baseline, the + card padded 12px 16px. The glyph leaves the title row so it can sit + beside both lines. + ========================================================= */ +.cn-look-board .launchpad-container .cn-kpi-card--horizontal.cn-kpi-card--board { + padding: 12px 16px !important; + border: none !important; + color: var(--color-main-text) !important; + text-decoration: none !important; +} + +.cn-look-board .launchpad-container .cn-kpi-card--horizontal.cn-kpi-card--board .cn-kpi-card__body { + display: grid; + grid-template-columns: 36px minmax(0, 1fr); + column-gap: 12px; + row-gap: 1px; + align-items: center; +} + +.cn-look-board .launchpad-container .cn-kpi-card--horizontal.cn-kpi-card--board .cn-kpi-card__title { + display: contents; +} + +.cn-look-board .launchpad-container .cn-kpi-card--horizontal.cn-kpi-card--board .cn-kpi-card__glyph { + display: flex; + grid-row: 1 / span 2; + grid-column: 1; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + border-radius: 8px; + background: var(--color-primary-element-light, #eaf0f7); + color: var(--color-primary-element-light-text, #234a78); +} + +.cn-look-board .launchpad-container .cn-kpi-card--horizontal.cn-kpi-card--board .cn-kpi-card__title-text { + grid-column: 2; + overflow: hidden; + color: var(--color-text-maxcontrast); + font-size: 13px; + font-weight: 400; + line-height: 1.2; + text-overflow: ellipsis; + white-space: nowrap; +} + +.cn-look-board .launchpad-container .cn-kpi-card--horizontal.cn-kpi-card--board .cn-kpi-card__value-row { + display: flex; + grid-column: 2; + align-items: baseline; + gap: 6px; +} + +.cn-look-board .launchpad-container .cn-kpi-card--horizontal.cn-kpi-card--board .cn-kpi-card__value { + color: var(--color-main-text); + font-size: 26px; + font-weight: 700; + line-height: 1.1; +} + +.cn-look-board .launchpad-container .cn-kpi-card--horizontal.cn-kpi-card--board .cn-kpi-card__label { + color: var(--color-text-maxcontrast); + font-size: 13px; +} + +/* The counter pads itself; its card adds no inset. */ +.cn-look-board .launchpad-container .launchpad-widget:has(.cn-stat-widget) .cn-widget-wrapper__content { + padding: 0; +} + +/* A tile on a dashboard that fills the screen is square: its rows take the + tile's own size (fitRows) and the cards beside it take the rest of the + height (LpVandaag). The square comes from the cell's width. */ +.launchpad-container--fill .grid-stack-item:is([data-cn-widget-id='tile'], [data-cn-widget-id='app-tile']) { + aspect-ratio: 1 / 1; +} + +/* An app tile fills its cell like a launcher tile: the renderer's 16px + padding made it a 68px square in a 100px cell. */ +.launchpad-container .launchpad-widget:has(.cn-app-tile-widget) .cn-widget-wrapper__content, +.launchpad-container .launchpad-widget:has(.cn-app-tile-widget) .widget-renderer { + padding: 0; +} + +/* The organisation menu as LpWerkplek draws it: each group a small uppercase + label and its links in a flat list on the card's inset, no carets. The + board's menu opens fully (expandedByDefault); a tree that starts closed + keeps its carets, or its children could never be opened (REQ-MENU-005). */ +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-menu-tree-node--depth-1 > .cn-menu-tree-node__row { + padding: 6px 0 2px !important; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-menu-widget--expanded .cn-menu-tree-node--depth-1 > .cn-menu-tree-node__row :is(.cn-menu-tree-node__caret, .cn-menu-tree-node__caret-spacer) { + display: none; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-menu-tree-node--depth-1 > .cn-menu-tree-node__row .cn-menu-tree-node__label { + color: var(--color-text-maxcontrast); + font-size: 12px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-menu-tree-node--depth-2 > .cn-menu-tree-node__row { + padding-inline-start: 0 !important; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-menu-tree-node__label-button { + min-height: 0; + margin: 0; + padding-inline: 0; +} + +/* The first group label stands 14px under the title (LpWerkplek). */ +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-menu-tree-node--depth-1:first-child > .cn-menu-tree-node__row { + padding-top: 6px !important; +} + +.cn-look-board .launchpad-container .cn-widget-wrapper--nc-dashboard .cn-menu-widget--expanded .cn-menu-tree-node--depth-2 > .cn-menu-tree-node__row :is(.cn-menu-tree-node__caret, .cn-menu-tree-node__caret-spacer) { + display: none; +} diff --git a/src/utils/__tests__/addTiles.spec.js b/src/utils/__tests__/addTiles.spec.js new file mode 100644 index 000000000..7f7cca30f --- /dev/null +++ b/src/utils/__tests__/addTiles.spec.js @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + +/** + * The choices of the Add tiles dialog (REQ-TILE-043, REQ-TILE-044). + */ + +import { describe, expect, it } from 'vitest' +import { + catalogueChoice, + discoveredChoice, + existingTileKeys, + officeChoice, + signOnKind, + tileKey, + tilesToAdd, +} from '../addTiles.js' + +describe('tileKey', () => { + it('keys a tile by its link, an app link by the app alone', () => { + expect(tileKey({ linkType: 'url', linkValue: 'https://a.test' })).toBe('url:https://a.test') + expect(tileKey({ linkType: 'app', linkValue: 'mail' })).toBe('app:mail') + expect(tileKey({ linkType: 'app', linkValue: '/apps/mail/' })).toBe('app:mail') + expect(tileKey({})).toBe('url:') + }) +}) + +describe('existingTileKeys', () => { + it('reads tiles and app tiles of the dashboard', () => { + const keys = existingTileKeys([ + { tileLinkType: 'url', tileLinkValue: 'https://a.test' }, + { widgetId: 'app-tile', content: { appId: 'deck' } }, + { widgetId: 'clock' }, + ]) + expect([...keys]).toEqual(['url:https://a.test', 'app:deck']) + expect(existingTileKeys(null).size).toBe(0) + }) +}) + +describe('choices per section', () => { + it('makes a catalogue entry an ordinary tile', () => { + expect(catalogueChoice({ name: 'Wiki', icon: 'i', iconType: 'url', linkType: 'url', linkValue: 'https://wiki.test' })).toEqual({ + key: 'url:https://wiki.test', + kind: 'tile', + tile: { title: 'Wiki', icon: 'i', iconType: 'url', linkType: 'url', linkValue: 'https://wiki.test' }, + }) + }) + + it('makes a found app its own app tile', () => { + expect(discoveredChoice({ appId: 'grafana', name: 'Grafana' })).toEqual({ key: 'app:grafana', kind: 'app-tile', tile: { appId: 'grafana' } }) + }) + + it('makes an office pack tile a tile of its own', () => { + expect(officeChoice({ title: 'New document', linkType: 'create', linkValue: 'richdocuments-doc', icon: 'icon-filetype-file', iconType: 'class' })).toEqual({ + key: 'create:richdocuments-doc', + kind: 'tile', + tile: { title: 'New document', icon: 'icon-filetype-file', iconType: 'class', linkType: 'create', linkValue: 'richdocuments-doc' }, + }) + }) +}) + +describe('tilesToAdd', () => { + it('adds each tile once and none the dashboard holds', () => { + const mail = officeChoice({ title: 'Mail', linkType: 'app', linkValue: 'mail' }) + const mailFound = discoveredChoice({ appId: 'mail' }) + const deck = discoveredChoice({ appId: 'deck' }) + const files = officeChoice({ title: 'Files', linkType: 'app', linkValue: 'files' }) + expect(tilesToAdd([mail, mailFound, deck, files], new Set(['app:deck']))).toEqual([mail, files]) + expect(tilesToAdd(null)).toEqual([]) + }) +}) + +describe('signOnKind', () => { + it('reads the sign-on from the link, single sign-on when the entry says so', () => { + expect(signOnKind({ linkType: 'app' })).toBe('nextcloud') + expect(signOnKind({ linkType: 'url' })).toBe('own') + expect(signOnKind({ linkType: 'url', signOn: 'sso' })).toBe('sso') + }) +}) diff --git a/src/utils/__tests__/adminWalkthrough.spec.js b/src/utils/__tests__/adminWalkthrough.spec.js new file mode 100644 index 000000000..c0dafa4de --- /dev/null +++ b/src/utils/__tests__/adminWalkthrough.spec.js @@ -0,0 +1,173 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * runtime-shell REQ-SHELL-011: the admin settings page's own first-visit tour. + */ + +import { __resetWalkthroughCacheForTests, useWalkthrough, WALKTHROUGH_SEEN_STORAGE_PREFIX } from '@conduction/nextcloud-vue' +import { afterEach, describe, expect, it, vi } from 'vitest' +import manifest from '../../manifest.json' +import { + ADMIN_TOUR_COMPLETION_KEY, + ADMIN_TOUR_ID, + ADMIN_TOUR_STORAGE_SUFFIX, + ADMIN_TOUR_WALKTHROUGH_KEY, + adminTourManifest, + adminTourStorage, + loadAdminTourSeen, + persistAdminTourSeen, +} from '../adminWalkthrough.js' + +// The suite aliases the library to a stub; this spec runs the library's own +// walkthrough engine and persistence, with only HTTP and storage injected. +vi.mock('@conduction/nextcloud-vue', () => import('../../../node_modules/@conduction/nextcloud-vue/src/composables/useWalkthrough.js')) + +/** + * A Map-backed Storage for one test. + * + * @return {Storage} + */ +function memoryStorage() { + const items = new Map() + return { + getItem: (key) => (items.has(key) ? items.get(key) : null), + setItem: (key, value) => items.set(key, String(value)), + removeItem: (key) => items.delete(key), + items, + } +} + +afterEach(() => { + __resetWalkthroughCacheForTests() +}) + +describe('the admin tour in src/manifest.json', () => { + const tour = manifest.walkthrough.tours.find((candidate) => candidate.id === ADMIN_TOUR_ID) + + it('declares launchpad:admin-getting-started next to the Workspace tour', () => { + expect(tour).toBeDefined() + expect(manifest.walkthrough.tours[0].id).toBe('launchpad:getting-started') + }) + + it('is manual there, so the Workspace shell never starts it', () => { + expect(tour.trigger).toBe('manual') + const wt = useWalkthrough('launchpad-shell-test', manifest) + expect(wt.autoStartTour.value.id).toBe('launchpad:getting-started') + }) + + // @spec openspec/changes/archive/2026-11-24-setup-five-steps-and-admin-tour/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + it('walks six stops: General, Templates, Roles, Sharing, Kiosk and Demo data', () => { + expect(tour.steps.map((step) => step.id)).toEqual(['general', 'templates', 'roles', 'sharing', 'kiosk', 'demo-data']) + expect(tour.steps.map((step) => step.title)).toEqual(['General', 'Templates', 'Roles and permissions', 'Sharing', 'Kiosk', 'Demo data']) + expect(tour.steps[0].body).toContain('This tour is shown once.') + expect(tour.steps[0].target).toEqual({ kind: 'element', ref: 'admin-default-settings' }) + for (const step of tour.steps) { + expect(step.title).not.toBe('') + expect(step.body).not.toBe('') + } + }) +}) + +describe('adminTourManifest', () => { + it('hands the admin page only the admin tour, as a first-visit tour with its own completion key', () => { + const admin = adminTourManifest(manifest) + + expect(admin.version).toBe(manifest.version) + expect(admin.walkthrough.completionConfigKey).toBe(ADMIN_TOUR_COMPLETION_KEY) + expect(admin.walkthrough.completionConfigKey).not.toBe(manifest.walkthrough.completionConfigKey) + expect(admin.walkthrough.tours).toHaveLength(1) + expect(admin.walkthrough.tours[0].id).toBe(ADMIN_TOUR_ID) + expect(admin.walkthrough.tours[0].trigger).toBe('first-visit') + }) + + it('leaves the manifest itself unchanged', () => { + adminTourManifest(manifest) + + expect(manifest.walkthrough.tours.find((candidate) => candidate.id === ADMIN_TOUR_ID).trigger).toBe('manual') + }) + + it('answers null without an admin tour or with walkthroughs switched off', () => { + expect(adminTourManifest({ walkthrough: { tours: [{ id: 'other' }] } })).toBeNull() + expect(adminTourManifest({ walkthrough: { enabled: false, tours: [{ id: ADMIN_TOUR_ID }] } })).toBeNull() + expect(adminTourManifest(null)).toBeNull() + }) + + it('starts for an administrator who never finished it, and not for one who did', () => { + const fresh = useWalkthrough('launchpad-admin-fresh', adminTourManifest(manifest), { seenVersion: '' }) + expect(fresh.autoStartTour.value.id).toBe(ADMIN_TOUR_ID) + + const done = useWalkthrough('launchpad-admin-done', adminTourManifest(manifest), { seenVersion: manifest.version }) + expect(done.autoStartTour.value).toBeNull() + }) + + it('starts on the admin page while the shell runs the Workspace walkthrough under the app id', () => { + const shell = useWalkthrough('launchpad', manifest, { seenVersion: '' }) + expect(shell.autoStartTour.value.id).toBe('launchpad:getting-started') + + const admin = useWalkthrough(ADMIN_TOUR_WALKTHROUGH_KEY, adminTourManifest(manifest), { seenVersion: '' }) + expect(ADMIN_TOUR_WALKTHROUGH_KEY).not.toBe('launchpad') + expect(admin.autoStartTour.value.id).toBe(ADMIN_TOUR_ID) + }) +}) + +describe('adminTourStorage', () => { + it('keeps the admin mirror under its own key, apart from the Workspace mirror', () => { + const base = memoryStorage() + const scoped = adminTourStorage(base) + + scoped.setItem('k', '1') + + expect(base.getItem('k' + ADMIN_TOUR_STORAGE_SUFFIX)).toBe('1') + expect(base.getItem('k')).toBeNull() + expect(scoped.getItem('k')).toBe('1') + scoped.removeItem('k') + expect(base.getItem('k' + ADMIN_TOUR_STORAGE_SUFFIX)).toBeNull() + }) + + it('keeps nothing without a usable storage', () => { + const scoped = adminTourStorage(null) + + scoped.setItem('k', '1') + + expect(scoped.getItem('k')).toBeNull() + }) +}) + +describe('loading and recording the admin tour', () => { + it('reads the admin preference, not the Workspace one', async () => { + const http = { get: vi.fn().mockResolvedValue({ data: { value: null } }) } + + await loadAdminTourSeen('launchpad', { http, storage: memoryStorage() }) + + expect(http.get).toHaveBeenCalledTimes(1) + expect(http.get.mock.calls[0][0]).toMatch(/\/apps\/launchpad\/api\/preferences\/admin-walkthrough-completed-version$/) + }) + + it('is unseen for an administrator who finished only the Workspace tour', async () => { + const storage = memoryStorage() + storage.setItem(WALKTHROUGH_SEEN_STORAGE_PREFIX + 'launchpad', '0.2.0') + const http = { get: vi.fn().mockResolvedValue({ data: { value: null } }) } + + expect(await loadAdminTourSeen('launchpad', { http, storage })).toBe('') + }) + + it('answers the version the server preference records', async () => { + const http = { get: vi.fn().mockResolvedValue({ data: { value: '0.2.0' } }) } + + expect(await loadAdminTourSeen('launchpad', { http, storage: memoryStorage() })).toBe('0.2.0') + }) + + it('records the finished tour in the admin preference and the admin mirror only', async () => { + const storage = memoryStorage() + const http = { put: vi.fn().mockResolvedValue({}) } + + expect(await persistAdminTourSeen('launchpad', '0.2.0', { http, storage })).toBe(true) + + expect(http.put).toHaveBeenCalledTimes(1) + expect(http.put.mock.calls[0][0]).toMatch(/\/api\/preferences\/admin-walkthrough-completed-version$/) + expect(http.put.mock.calls[0][1]).toEqual({ value: '0.2.0' }) + expect(storage.getItem(WALKTHROUGH_SEEN_STORAGE_PREFIX + 'launchpad')).toBeNull() + expect(storage.getItem(WALKTHROUGH_SEEN_STORAGE_PREFIX + 'launchpad' + ADMIN_TOUR_STORAGE_SUFFIX)).toBe('0.2.0') + }) +}) diff --git a/src/utils/__tests__/allowedSites.spec.js b/src/utils/__tests__/allowedSites.spec.js new file mode 100644 index 000000000..a96c3798d --- /dev/null +++ b/src/utils/__tests__/allowedSites.spec.js @@ -0,0 +1,40 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The allowed websites rows: purpose per site, the stored shape, and adding a + * host (REQ-ASET-021). + * + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + +import { describe, expect, it } from 'vitest' +import { addRow, purposeOf, rowsFrom, siteFor } from '../allowedSites.js' + +describe('allowed websites rows', () => { + it('reads the purpose of a site', () => { + expect(purposeOf({ embed: true, fetch: true })).toBe('both') + expect(purposeOf({ embed: false, fetch: true })).toBe('fetch') + expect(purposeOf({ embed: true, fetch: false })).toBe('embed') + expect(purposeOf(null)).toBe('embed') + }) + + it('writes a site as the server stores it', () => { + expect(siteFor(' app.powerbi.com ', 'embed')).toEqual({ host: 'app.powerbi.com', embed: true, fetch: false }) + expect(siteFor('kcc-api.zuiddrecht.nl', 'fetch')).toEqual({ host: 'kcc-api.zuiddrecht.nl', embed: false, fetch: true }) + expect(siteFor('www.zuiddrecht.nl', 'both')).toEqual({ host: 'www.zuiddrecht.nl', embed: true, fetch: true }) + }) + + it('builds rows from an answer and skips what is not a site', () => { + expect(rowsFrom({ sites: [{ host: 'app.powerbi.com', embed: true }, { host: '' }, null, { embed: true }] })) + .toEqual([{ host: 'app.powerbi.com', purpose: 'embed' }]) + expect(rowsFrom(undefined)).toEqual([]) + }) + + it('adds a host once and gives a known host the new purpose', () => { + const rows = [{ host: 'app.powerbi.com', purpose: 'embed' }] + expect(addRow(rows, ' ', 'fetch')).toBe(rows) + expect(addRow(rows, 'kcc-api.zuiddrecht.nl', 'fetch')).toEqual([...rows, { host: 'kcc-api.zuiddrecht.nl', purpose: 'fetch' }]) + expect(addRow(rows, 'APP.powerbi.com', 'both')).toEqual([{ host: 'app.powerbi.com', purpose: 'both' }]) + }) +}) diff --git a/src/utils/__tests__/appRequest.spec.js b/src/utils/__tests__/appRequest.spec.js new file mode 100644 index 000000000..a3b376ffa --- /dev/null +++ b/src/utils/__tests__/appRequest.spec.js @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + +/** + * Asking IT for a missing app from the Add tiles dialog (REQ-TILE-043). + */ + +import { describe, expect, it, vi } from 'vitest' +import { sendAppRequest } from '../appRequest.js' + +describe('sendAppRequest', () => { + it('sends the trimmed name and purpose and says it was sent', async () => { + const fn = vi.fn().mockResolvedValue({}) + expect(await sendAppRequest(fn, ' Kaartviewer ', ' percelen ')).toEqual({ failed: false, message: 'Your request was sent to IT' }) + expect(fn).toHaveBeenCalledWith({ appName: 'Kaartviewer', purpose: 'percelen' }) + }) + + it('names the open-request limit', async () => { + const fn = vi.fn().mockRejectedValue({ response: { data: { code: 'request_limit' } } }) + expect(await sendAppRequest(fn, 'x', '')).toEqual({ failed: true, message: 'You have 10 open requests. Wait for an answer first.' }) + }) + + it('says when the request could not be sent', async () => { + const fn = vi.fn().mockRejectedValue(new Error('offline')) + expect(await sendAppRequest(fn, 'x', '')).toEqual({ failed: true, message: 'Your request could not be sent. Try again later.' }) + }) +}) diff --git a/src/utils/__tests__/bookmarkFile.spec.js b/src/utils/__tests__/bookmarkFile.spec.js new file mode 100644 index 000000000..0db37bf45 --- /dev/null +++ b/src/utils/__tests__/bookmarkFile.spec.js @@ -0,0 +1,92 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The bookmarks file parser on Firefox, Chrome and Edge exports, with nested + * folders and non-web links, and its size and count limits (REQ-BMI-001, + * REQ-BMI-004). + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md + */ +import { readFileSync } from 'fs' +import path from 'path' +import { describe, expect, it } from 'vitest' +import { chosenBookmarks, MAX_BOOKMARKS, MAX_FILE_BYTES, parseBookmarks, readBookmarkFile } from '../bookmarkFile.js' + +const fixture = (name) => readFileSync(path.join(__dirname, 'fixtures', name), 'utf8') + +describe('parseBookmarks', () => { + it('reads a Firefox export: loose bookmarks, folders, nested folders flattened in', () => { + const parsed = parseBookmarks(fixture('bookmarks-firefox.html')) + expect(parsed.bookmarks).toEqual([ + { title: 'Mozilla', url: 'https://www.mozilla.org/' }, + { title: 'Bookmarklet', url: 'javascript:alert(1)' }, + ]) + expect(parsed.folders).toEqual([ + { + name: 'Werk', + bookmarks: [ + { title: 'Wiki', url: 'https://wiki.example.org/' }, + { title: 'Mail & agenda', url: 'https://mail.example.org/' }, + { title: 'Planning', url: 'https://plan.example.org/' }, + ], + }, + { name: 'Bookmarks Toolbar', bookmarks: [{ title: 'News', url: 'https://news.example.org/' }] }, + ]) + expect(parsed.total).toBe(6) + }) + + it('reads a Chrome export, keeping a file link for the server to skip and an empty folder', () => { + const parsed = parseBookmarks(fixture('bookmarks-chrome.html')) + expect(parsed.bookmarks).toEqual([]) + expect(parsed.folders.map((f) => [f.name, f.bookmarks.map((b) => b.url)])).toEqual([ + ['Bookmarks bar', ['https://www.google.com/', 'http://bank.example.nl/', 'file:///C:/Users/pieter/notes.txt']], + ['Other bookmarks', []], + ]) + expect(parsed.total).toBe(3) + }) + + it('reads an Edge export and titles an untitled bookmark with its address', () => { + const parsed = parseBookmarks(fixture('bookmarks-edge.html')) + expect(parsed.folders).toEqual([ + { + name: 'Favorites bar', + bookmarks: [ + { title: 'Bing', url: 'https://www.bing.com/' }, + { title: 'https://intranet.gemeente.nl/', url: 'https://intranet.gemeente.nl/' }, + ], + }, + ]) + expect(parsed.bookmarks).toEqual([{ title: 'Outlook', url: 'https://outlook.office.com/' }]) + }) + + it('returns nothing for a file that is not a bookmarks file', () => { + expect(parseBookmarks('<html><body>hello</body></html>')).toEqual({ folders: [], bookmarks: [], total: 0 }) + expect(parseBookmarks('')).toEqual({ folders: [], bookmarks: [], total: 0 }) + }) +}) + +describe('readBookmarkFile', () => { + const file = (text, size) => ({ size: size ?? text.length, text: async () => text }) + + it('refuses a file over 5 MB before reading it', async () => { + const big = { size: MAX_FILE_BYTES + 1, text: () => { throw new Error('read') } } + await expect(readBookmarkFile(big)).rejects.toMatchObject({ code: 'too-large' }) + }) + + it('refuses more than 2,000 bookmarks and accepts exactly 2,000', async () => { + const many = (n) => '<DL><p>' + Array.from({ length: n }, (_v, i) => `<DT><A HREF="https://e.org/${i}">${i}</A>`).join('') + '</DL>' + await expect(readBookmarkFile(file(many(MAX_BOOKMARKS + 1)))).rejects.toMatchObject({ code: 'too-many' }) + await expect(readBookmarkFile(file(many(MAX_BOOKMARKS)))).resolves.toMatchObject({ total: MAX_BOOKMARKS }) + }) +}) + +describe('chosenBookmarks', () => { + it('sends only the ticked folders and loose bookmarks', () => { + const parsed = parseBookmarks(fixture('bookmarks-firefox.html')) + expect(chosenBookmarks(parsed, new Set([0]), new Set([1]))).toEqual({ + folders: [parsed.folders[0]], + bookmarks: [{ title: 'Bookmarklet', url: 'javascript:alert(1)' }], + }) + }) +}) diff --git a/src/utils/__tests__/bootPath.spec.js b/src/utils/__tests__/bootPath.spec.js new file mode 100644 index 000000000..455a61ad9 --- /dev/null +++ b/src/utils/__tests__/bootPath.spec.js @@ -0,0 +1,53 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The app prefix an address carries, so the addresses the app writes stay + * under the base its router is mounted on. + * + * @spec openspec/specs/dashboard-deeplinking/spec.md + */ + +import { describe, expect, it, vi } from 'vitest' +import { appBase, dashboardUuidFromHash } from '../bootPath.js' + +// Pretty URLs on: generateUrl drops the front controller. +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => path, +})) + +describe('appBase', () => { + it('keeps the front controller when the page was opened through it', () => { + expect(appBase('/index.php/apps/launchpad/finance/q1')).toBe('/index.php/apps/launchpad') + expect(appBase('/index.php/apps/launchpad')).toBe('/index.php/apps/launchpad') + }) + + it('has no front controller when the address had none', () => { + expect(appBase('/apps/launchpad/finance')).toBe('/apps/launchpad') + }) + + it('keeps a subdirectory install', () => { + expect(appBase('/cloud/index.php/apps/launchpad/x')).toBe('/cloud/index.php/apps/launchpad') + }) + + it('falls back to generateUrl off the app', () => { + expect(appBase('/settings/user')).toBe('/apps/launchpad') + expect(appBase('')).toBe('/apps/launchpad') + }) +}) + +describe('dashboardUuidFromHash', () => { + it('reads the uuid of a unified search link, with or without a widget hint', () => { + expect(dashboardUuidFromHash('#dashboard/abc-123')).toBe('abc-123') + expect(dashboardUuidFromHash('#dashboard/abc-123;widget=42')).toBe('abc-123') + expect(dashboardUuidFromHash('#dashboard/a%20b')).toBe('a b') + }) + + it('names no dashboard for any other hash', () => { + expect(dashboardUuidFromHash('')).toBe('') + expect(dashboardUuidFromHash('#user-settings')).toBe('') + expect(dashboardUuidFromHash('#dashboard/')).toBe('') + expect(dashboardUuidFromHash('#dashboard/%E0%A4%A')).toBe('') + expect(dashboardUuidFromHash(null)).toBe('') + }) +}) diff --git a/src/utils/__tests__/clickedRow.spec.js b/src/utils/__tests__/clickedRow.spec.js new file mode 100644 index 000000000..4ea8743fa --- /dev/null +++ b/src/utils/__tests__/clickedRow.spec.js @@ -0,0 +1,63 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * clickedRow: a click on a hierarchy level reads the levels above it from one + * record of the clicked category, so the bus can infer them + * (drill-down-cross-widget-filter task 23; REQ-CWF-004). + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { clickedRow, missingAncestors } from '../clickedRow.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path, vars = {}) => path.replace(/{(\w+)}/g, (_m, key) => vars[key]) })) + +const NL = { id: 'nl', levels: [{ dimension: 'provincieCode' }, { dimension: 'gemeenteCode' }, { dimension: 'wijkCode' }] } +const WIJK_CLICK = [{ dimension: 'wijkCode' }] +const SELECTION = { field: 'wijkCode', value: 'WK035501' } +const SOURCE = { register: 'cwf', schema: 'melding', filter: { gemeenteCode: 'GM0355' } } + +beforeEach(() => { + axios.get.mockReset() +}) + +describe('missingAncestors', () => { + it('names the levels above a published level that the row does not hold', () => { + expect(missingAncestors([NL], WIJK_CLICK, { wijkCode: 'WK035501' })).toEqual(['provincieCode', 'gemeenteCode']) + expect(missingAncestors([NL], WIJK_CLICK, { wijkCode: 'WK035501', gemeenteCode: 'GM0355', provincieCode: '' })).toEqual(['provincieCode']) + expect(missingAncestors([NL], [{ dimension: 'provincieCode' }], {})).toEqual([]) + expect(missingAncestors([NL], [{ dimension: 'status' }], {})).toEqual([]) + }) +}) + +describe('clickedRow', () => { + it('reads the ancestors from the first record of the clicked category', async () => { + axios.get.mockResolvedValue({ data: { results: [{ wijkCode: 'WK035501', gemeenteCode: 'GM0355', provincieCode: 'PV26', status: 'open' }] } }) + + const row = await clickedRow({ selection: SELECTION, clauses: WIJK_CLICK, hierarchies: [NL], dataSource: SOURCE }) + + expect(row).toEqual({ wijkCode: 'WK035501', gemeenteCode: 'GM0355', provincieCode: 'PV26' }) + expect(axios.get).toHaveBeenCalledWith('/apps/openregister/api/objects/cwf/melding', { params: { wijkCode: 'WK035501', _limit: 1 } }) + }) + + it('asks nothing when no ancestor is missing or the chart has no register', async () => { + expect(await clickedRow({ selection: { field: 'provincieCode', value: 'PV26' }, clauses: [{ dimension: 'provincieCode' }], hierarchies: [NL], dataSource: SOURCE })) + .toEqual({ provincieCode: 'PV26' }) + expect(await clickedRow({ selection: SELECTION, clauses: WIJK_CLICK, hierarchies: [NL], dataSource: { url: '/x' } })) + .toEqual({ wijkCode: 'WK035501' }) + expect(axios.get).not.toHaveBeenCalled() + }) + + it('leaves the row as it was when the record is missing, lacks a level or cannot be read', async () => { + axios.get.mockResolvedValueOnce({ data: { results: [] } }) + expect(await clickedRow({ selection: SELECTION, clauses: WIJK_CLICK, hierarchies: [NL], dataSource: SOURCE })).toEqual({ wijkCode: 'WK035501' }) + + axios.get.mockResolvedValueOnce({ data: { results: [{ gemeenteCode: 'GM0355', provincieCode: null }] } }) + expect(await clickedRow({ selection: SELECTION, clauses: WIJK_CLICK, hierarchies: [NL], dataSource: SOURCE })).toEqual({ wijkCode: 'WK035501', gemeenteCode: 'GM0355' }) + + axios.get.mockRejectedValueOnce(new Error('403')) + expect(await clickedRow({ selection: SELECTION, clauses: WIJK_CLICK, hierarchies: [NL], dataSource: SOURCE })).toEqual({ wijkCode: 'WK035501' }) + }) +}) diff --git a/src/utils/__tests__/customCss.spec.js b/src/utils/__tests__/customCss.spec.js new file mode 100644 index 000000000..a50ed8a91 --- /dev/null +++ b/src/utils/__tests__/customCss.spec.js @@ -0,0 +1,50 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + */ +import { afterEach, describe, expect, it } from 'vitest' +import { applyCustomCss, GLOBAL_STYLE_ID } from '../customCss.js' + +describe('applyCustomCss (REQ-THM-003)', () => { + afterEach(() => { + document.head.innerHTML = '' + }) + + it('inserts the CSS as text, never as markup', () => { + const css = '.launchpad-workspace p { content: "</style><img src=x onerror=alert(1)>"; }' + const style = applyCustomCss(GLOBAL_STYLE_ID, css) + + expect(style.tagName).toBe('STYLE') + expect(style.textContent).toBe(css) + expect(style.children).toHaveLength(0) + expect(document.head.querySelectorAll('img')).toHaveLength(0) + }) + + it('replaces the CSS in the same element', () => { + applyCustomCss(GLOBAL_STYLE_ID, '.launchpad-workspace a { color: red; }') + applyCustomCss(GLOBAL_STYLE_ID, '.launchpad-workspace a { color: blue; }') + + const styles = document.head.querySelectorAll(`#${GLOBAL_STYLE_ID}`) + expect(styles).toHaveLength(1) + expect(styles[0].textContent).toBe('.launchpad-workspace a { color: blue; }') + }) + + it('removes the element when the CSS is empty or missing', () => { + applyCustomCss(GLOBAL_STYLE_ID, '.launchpad-workspace a { color: red; }') + + expect(applyCustomCss(GLOBAL_STYLE_ID, ' ')).toBeNull() + expect(document.getElementById(GLOBAL_STYLE_ID)).toBeNull() + expect(applyCustomCss(GLOBAL_STYLE_ID, null)).toBeNull() + }) + + it('does not take over an element of another kind with the same id', () => { + const div = document.createElement('div') + div.id = GLOBAL_STYLE_ID + document.head.appendChild(div) + + const style = applyCustomCss(GLOBAL_STYLE_ID, '.launchpad-workspace a { color: red; }') + + expect(style.tagName).toBe('STYLE') + expect(document.head.querySelectorAll(`#${GLOBAL_STYLE_ID}`)).toHaveLength(1) + }) +}) diff --git a/src/utils/__tests__/dashboardDiscussion.spec.js b/src/utils/__tests__/dashboardDiscussion.spec.js new file mode 100644 index 000000000..1cd16b105 --- /dev/null +++ b/src/utils/__tests__/dashboardDiscussion.spec.js @@ -0,0 +1,56 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * When a dashboard shows its discussion (openregister-leaf-integrations + * tasks 4 to 6). + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-5 + */ + +import { describe, expect, it } from 'vitest' +import { conversationEnabled, discussionAvailable, isCollaborative } from '../dashboardDiscussion.js' + +describe('discussionAvailable', () => { + it('needs both OpenRegister and Talk', () => { + expect(discussionAvailable({ openregister: '/apps/openregister', spreed: '/apps/spreed' })).toBe(true) + expect(discussionAvailable({ openregister: '/apps/openregister' })).toBe(false) + expect(discussionAvailable({ spreed: '/apps/spreed' })).toBe(false) + expect(discussionAvailable(null)).toBe(false) + }) +}) + +describe('isCollaborative', () => { + const personal = { id: 7, uuid: 'u-7', type: 'user', userId: 'alice' } + + it('is true for a group dashboard', () => { + expect(isCollaborative({ dashboard: { id: 1, uuid: 'g', type: 'group_shared' } })).toBe(true) + }) + + it('is true for a dashboard shared with me, matched by id or uuid', () => { + expect(isCollaborative({ dashboard: personal, sharedWithMe: [{ id: 7 }] })).toBe(true) + expect(isCollaborative({ dashboard: personal, sharedWithMe: [{ uuid: 'u-7' }] })).toBe(true) + }) + + it('is true for my dashboard with shares, and false for my unshared one', () => { + expect(isCollaborative({ dashboard: personal, ownShares: [{ shareType: 'user', shareWith: 'bob' }] })).toBe(true) + expect(isCollaborative({ dashboard: personal, ownShares: [] })).toBe(false) + }) + + it('is false for an admin template and for no dashboard', () => { + expect(isCollaborative({ dashboard: { id: 2, uuid: 't', type: 'admin_template' }, ownShares: [{}] })).toBe(false) + expect(isCollaborative({ dashboard: null })).toBe(false) + }) +}) + +/** @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/dashboard-talk-leaf/spec.md#requirement-the-conversation-is-switched-on-from-the-sharing-tab-req-leaf-006 */ +describe('conversationEnabled', () => { + it('shows the conversation unless the dashboard switched it off', () => { + expect(conversationEnabled({ conversationEnabled: null })).toBe(true) + expect(conversationEnabled({})).toBe(true) + expect(conversationEnabled(null)).toBe(true) + expect(conversationEnabled({ conversationEnabled: 1 })).toBe(true) + expect(conversationEnabled({ conversationEnabled: 0 })).toBe(false) + expect(conversationEnabled({ conversationEnabled: false })).toBe(false) + }) +}) diff --git a/src/utils/__tests__/dashboardLook.spec.js b/src/utils/__tests__/dashboardLook.spec.js new file mode 100644 index 000000000..88f27c45e --- /dev/null +++ b/src/utils/__tests__/dashboardLook.spec.js @@ -0,0 +1,61 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The look of one dashboard on the client (platform-dashboard-theme-and-css + * REQ-THM-001/002): the same contrast rules as DashboardLook.php, and the + * scoped style that draws a look on the dashboard region only. + */ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) + +import { accentCheck, contrast, lookStyle, normaliseHex, textColorFor } from '../dashboardLook.js' + +describe('dashboardLook', () => { + it('normalises hex colours and refuses anything else', () => { + expect(normaliseHex(' #1F5C3A ')).toBe('#1f5c3a') + expect(normaliseHex('#abc')).toBe('#aabbcc') + expect(normaliseHex('green')).toBeNull() + expect(normaliseHex('url(x)')).toBeNull() + expect(normaliseHex(null)).toBeNull() + }) + + it('measures WCAG contrast like the server', () => { + expect(contrast('#000000', '#ffffff')).toBeCloseTo(21, 3) + expect(contrast('#777777', '#ffffff')).toBeCloseTo(4.48, 2) + }) + + it('puts white text on a dark green background (REQ-THM-002)', () => { + expect(textColorFor('#12301f')).toBe('#ffffff') + expect(textColorFor('#f5f5dc')).toBe('#000000') + }) + + it('refuses a pale accent on the white instance background with the ratio the server gives', () => { + expect(accentCheck('#f5f5dc', null)).toEqual({ ratio: 1.1, readable: false }) + expect(accentCheck('#1f5c3a', null).readable).toBe(true) + expect(accentCheck('#ffffff', '#12301f').readable).toBe(true) + expect(accentCheck(null, null)).toEqual({ ratio: null, readable: true }) + }) + + it('draws a look as scoped variables, and nothing for a dashboard that follows the theme', () => { + expect(lookStyle(null)).toEqual({}) + expect(lookStyle({ themeAccent: null, themeBackgroundColor: null, themeBackgroundResource: null })).toEqual({}) + + expect(lookStyle({ themeAccent: '#1f5c3a', themeBackgroundColor: '#12301f', themeBackgroundResource: 'resource_a.b.jpg' })).toEqual({ + '--color-primary-element': '#1f5c3a', + '--color-primary-element-text': '#ffffff', + 'background-color': '#12301f', + color: '#ffffff', + '--color-main-text': '#ffffff', + 'background-image': 'url("/index.php/apps/launchpad/resource/resource_a.b.jpg")', + 'background-size': 'cover', + 'background-position': 'center', + }) + }) + + it('never turns a stored value into CSS it was not meant to be', () => { + const style = lookStyle({ themeAccent: 'red;}body{display:none', themeBackgroundResource: '../x.png") ; foo: url("y' }) + expect(style).toEqual({}) + }) +}) diff --git a/src/utils/__tests__/dashboardPeriod.spec.js b/src/utils/__tests__/dashboardPeriod.spec.js new file mode 100644 index 000000000..9853e57a5 --- /dev/null +++ b/src/utils/__tests__/dashboardPeriod.spec.js @@ -0,0 +1,119 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The dashboard period: read from and kept in the address, its start per + * choice, and added to the query of a widget that names a period field + * (dashboard-period-and-download REQ-DPD-002). + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + +import { describe, expect, it } from 'vitest' +import { addressWithPeriod, contentWithPeriod, namesPeriod, periodFieldOf, PERIODS, periodStart, readPeriod, withPeriod } from '../dashboardPeriod.js' + +const NOW = new Date(2026, 10, 23, 14, 30) + +describe('readPeriod and addressWithPeriod', () => { + it('offers This month, Quarter and Year, This month first', () => { + expect(PERIODS).toEqual(['month', 'quarter', 'year']) + }) + + it('reads the period from the address, This month otherwise', () => { + expect(readPeriod('?period=quarter')).toBe('quarter') + expect(readPeriod('?kiosk=1&period=year')).toBe('year') + expect(readPeriod('?period=decade')).toBe('month') + expect(readPeriod('')).toBe('month') + }) + + it('keeps the period in the address with the rest of the query and the hash', () => { + expect(addressWithPeriod('https://nc.example/apps/launchpad/d/abc?edit=1#w', 'quarter')).toBe('/apps/launchpad/d/abc?edit=1&period=quarter#w') + expect(addressWithPeriod('https://nc.example/apps/launchpad?period=year', 'month')).toBe('/apps/launchpad?period=month') + expect(addressWithPeriod('https://nc.example/apps/launchpad', 'nonsense')).toBe('/apps/launchpad?period=month') + }) +}) + +describe('periodStart', () => { + it('starts this month, this quarter and this year', () => { + expect(periodStart('month', NOW)).toEqual(new Date(2026, 10, 1)) + expect(periodStart('quarter', NOW)).toEqual(new Date(2026, 9, 1)) + expect(periodStart('year', NOW)).toEqual(new Date(2026, 0, 1)) + expect(periodStart('quarter', new Date(2026, 2, 31))).toEqual(new Date(2026, 0, 1)) + expect(periodStart('quarter', new Date(2026, 3, 1))).toEqual(new Date(2026, 3, 1)) + }) +}) + +describe('periodFieldOf and namesPeriod', () => { + it('reads the period field from the source or the chart data source', () => { + expect(periodFieldOf({ source: { register: 'r', periodField: 'startDate' } })).toBe('startDate') + expect(periodFieldOf({ dataSource: { periodField: ' decidedOn ' } })).toBe('decidedOn') + expect(periodFieldOf({ props: { dataSource: { periodField: 'x' } } })).toBe('x') + expect(periodFieldOf({ source: 'manual' })).toBe('') + expect(periodFieldOf({ dataSource: { periodField: '' } })).toBe('') + expect(periodFieldOf(null)).toBe('') + }) + + it('offers the period only when a placement names a period field', () => { + const dated = { content: { dataSource: { periodField: 'startDate' } } } + const embed = { content: { url: 'https://app.powerbi.com/x' } } + expect(namesPeriod([embed, dated])).toBe(true) + expect(namesPeriod([embed])).toBe(false) + expect(namesPeriod(null)).toBe(false) + }) +}) + +describe('withPeriod', () => { + it('adds the field between the period start and now to the filter, keeping the rest', () => { + const source = { register: 'zaken', schema: 'zaak', filter: { status: 'open' } } + expect(withPeriod(source, 'startDate', 'quarter', NOW)).toEqual({ + register: 'zaken', + schema: 'zaak', + filter: { status: 'open', 'startDate[gte]': '2026-10-01', 'startDate[lte]': NOW.toISOString() }, + }) + expect(source.filter).toEqual({ status: 'open' }) + }) + + it('leaves a source without a period field, and no source, as they are', () => { + const source = { register: 'zaken' } + expect(withPeriod(source, '', 'year', NOW)).toBe(source) + expect(withPeriod(null, 'startDate', 'year', NOW)).toBeNull() + }) +}) + +describe('contentWithPeriod', () => { + const range = { 'startDate[gte]': '2026-10-01', 'startDate[lte]': NOW.toISOString() } + + it('adds the period to the stat card\'s source', () => { + const content = { label: 'Zaken', source: { register: 'zaken', schema: 'zaak', metric: 'count', filter: { status: 'open' }, periodField: 'startDate' } } + expect(contentWithPeriod(content, 'quarter', NOW).source.filter).toEqual({ status: 'open', ...range }) + expect(content.source.filter).toEqual({ status: 'open' }) + }) + + it('adds the period to the stats block\'s and the chart\'s data source', () => { + const block = { title: 'Open', dataSource: { register: 'zaken', schema: 'zaak', periodField: 'startDate' } } + expect(contentWithPeriod(block, 'quarter', NOW).dataSource.filter).toEqual(range) + + const nested = { props: { chartKind: 'bar', dataSource: { register: 'zaken', schema: 'zaak', periodField: 'startDate' } } } + const dated = contentWithPeriod(nested, 'quarter', NOW) + expect(dated.props.dataSource.filter).toEqual(range) + expect(dated.props.chartKind).toBe('bar') + }) + + it('adds the period to the table, whose content is its own source', () => { + const table = { register: 'zaken', schema: 'zaak', filter: { status: 'open' }, limit: 10, periodField: 'startDate' } + const dated = contentWithPeriod(table, 'quarter', NOW) + expect(dated.filter).toEqual({ status: 'open', ...range }) + expect(dated.limit).toBe(10) + expect(periodFieldOf(table)).toBe('startDate') + expect(namesPeriod([{ content: table }])).toBe(true) + }) + + it('leaves content without a period field, an unknown period and no content as they are', () => { + const table = { register: 'zaken', schema: 'zaak', filter: {} } + const embed = { url: 'https://app.powerbi.com/x' } + expect(contentWithPeriod(table, 'quarter', NOW)).toBe(table) + expect(contentWithPeriod(embed, 'year', NOW)).toBe(embed) + expect(contentWithPeriod({ source: { periodField: 'startDate' } }, 'decade', NOW)).toEqual({ source: { periodField: 'startDate' } }) + expect(contentWithPeriod(null, 'year', NOW)).toBeNull() + }) +}) diff --git a/src/utils/__tests__/embedOutage.spec.js b/src/utils/__tests__/embedOutage.spec.js new file mode 100644 index 000000000..fb7d41a47 --- /dev/null +++ b/src/utils/__tests__/embedOutage.spec.js @@ -0,0 +1,100 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The source line and the outage cause of an embedded page or report. + * + * @spec openspec/changes/archive/2026-11-24-embed-outage-state/specs/iframe-embed-widget/spec.md#requirement-the-outage-state-of-an-embedded-report-req-iframe-005 + */ + +import { describe, expect, it } from 'vitest' +import { + clockTime, + embedHost, + embedSourceLine, + isReport, + outageCauseLine, + ownCause, +} from '../embedOutage.js' + +function t(_app, key, vars) { + return key.replace(/\{(\w+)\}/g, (_, name) => (vars && name in vars ? vars[name] : `{${name}}`)) +} + +const report = { + url: 'https://app.powerbi.com/reportEmbed?id=1', + kind: 'report', + connection: { account: 'Pieter Jansen' }, +} + +describe('embedSourceLine', () => { + it('names the kind, the host and the signed-in account', () => { + expect(embedSourceLine(report, t)).toBe('Embedded report · app.powerbi.com · Signed in as Pieter Jansen') + }) + + it('leaves the account out when the connection does not sign in', () => { + expect(embedSourceLine({ url: 'https://example.com/a' }, t)).toBe('Embedded page · example.com') + expect(embedSourceLine({ url: 'https://example.com/a', connection: { account: ' ' } }, t)).toBe('Embedded page · example.com') + }) + + it('is empty without a parseable URL', () => { + expect(embedSourceLine({}, t)).toBe('') + expect(embedSourceLine({ url: 'not a url' }, t)).toBe('') + expect(embedSourceLine(null, t)).toBe('') + }) +}) + +describe('helpers', () => { + it('reads the host and the kind', () => { + expect(embedHost(' https://a.example.com:8443/x ')).toBe('a.example.com:8443') + expect(embedHost(42)).toBe('') + expect(isReport(report)).toBe(true) + expect(isReport({ kind: 'page' })).toBe(false) + expect(isReport(undefined)).toBe(false) + }) + + it('pads the clock time', () => { + expect(clockTime(new Date(2026, 10, 24, 9, 5))).toBe('09:05') + }) + + it('words every own cause and nothing for an unknown one', () => { + expect(ownCause('blocked', t)).toBe('the site refuses to be embedded') + expect(ownCause('unreachable', t)).toBe('the site could not be reached') + expect(ownCause('timeout', t)).toBe('the page did not finish loading') + expect(ownCause('error', t)).toBe('a network error') + expect(ownCause('unknown', t)).toBe('') + }) +}) + +describe('outageCauseLine', () => { + const now = new Date(2026, 10, 24, 11, 0) + + it('takes the connection error and its time (token expired at 09:30)', () => { + const content = { ...report, connection: { error: 'token expired', errorAt: new Date(2026, 10, 24, 9, 30).toISOString() } } + expect(outageCauseLine({ content, reason: 'blocked', failedAt: now, now }, t)) + .toBe('Gave an error today at 09:30: token expired') + }) + + it('names the date when the connection failed on another day', () => { + const at = new Date(2026, 10, 23, 16, 45) + const content = { connection: { error: 'token expired', errorAt: at.toISOString() } } + expect(outageCauseLine({ content, reason: 'unknown', failedAt: null, now }, t)) + .toBe(`Gave an error on ${at.toLocaleDateString()} at 16:45: token expired`) + }) + + it('gives the cause without a time when the connection has no valid time', () => { + const content = { connection: { error: 'token expired', errorAt: 'yesterday' } } + expect(outageCauseLine({ content, reason: 'unknown', failedAt: now, now }, t)).toBe('Gave an error: token expired') + }) + + it('falls back to what the widget found and when', () => { + const failedAt = new Date(2026, 10, 24, 10, 12) + expect(outageCauseLine({ content: {}, reason: 'timeout', failedAt, now }, t)) + .toBe('Gave an error today at 10:12: the page did not finish loading') + }) + + it('is empty when no cause is known', () => { + expect(outageCauseLine({ content: {}, reason: 'unknown', failedAt: now, now }, t)).toBe('') + expect(outageCauseLine({ content: { connection: { error: ' ' } }, reason: 'unknown', failedAt: now, now }, t)).toBe('') + }) +}) diff --git a/src/utils/__tests__/embedToken.spec.js b/src/utils/__tests__/embedToken.spec.js new file mode 100644 index 000000000..a8fbe81cf --- /dev/null +++ b/src/utils/__tests__/embedToken.spec.js @@ -0,0 +1,152 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The embed-token admin helpers: the origin rule and CSP preview the server + * applies, a token's status, and the payloads built from the form + * (embedded-analytics tasks 15, 16, 18 and 40). + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-18 + */ + +import { describe, expect, it } from 'vitest' +import { + createPayload, + cspPreview, + embedAdminSearch, + embedDefaultsFrom, + formFromToken, + onlyRootRules, + originProblem, + parseFilterContext, + rateLimitPolicy, + tokenStatus, + updatePayload, +} from '../embedToken.js' + +describe('embed token helpers', () => { + it.each([ + ['https://www.zeist.nl', ''], + ['https://intranet.zeist.nl:8443/', ''], + ['http://localhost', ''], + ['https://*.zeist.nl', 'wildcard'], + ['*', 'wildcard'], + ['https://www.zeist.nl/woo', 'invalid'], + ['www.zeist.nl', 'invalid'], + ['ftp://zeist.nl', 'invalid'], + ['', 'invalid'], + ])('judges origin %s as "%s"', (origin, problem) => { + expect(originProblem(origin)).toBe(problem) + }) + + it('previews the frame-ancestors header from the valid, normalised origins', () => { + expect(cspPreview(['https://WWW.Zeist.nl/', 'https://www.zeist.nl', 'https://*.x.nl', 'https://a.nl'])) + .toBe('frame-ancestors https://www.zeist.nl https://a.nl') + expect(cspPreview([])).toBe("frame-ancestors 'none'") + }) + + it('says revoked before expired, and active otherwise', () => { + const now = Date.parse('2026-05-22T14:30:00Z') + expect(tokenStatus({ revokedAt: '2026-05-01T00:00:00Z', tokenExpiresAt: '2026-05-02T00:00:00Z' }, now)).toBe('revoked') + expect(tokenStatus({ tokenExpiresAt: '2026-05-22T14:30:00Z' }, now)).toBe('expired') + expect(tokenStatus({ tokenExpiresAt: '2026-05-23T00:00:00Z' }, now)).toBe('active') + expect(tokenStatus({ tokenExpiresAt: null }, now)).toBe('active') + }) + + it('reads pinned filters as dimension=value lines', () => { + expect(parseFilterContext('status = open\n\n=x\nyear=2026\nnoequals')).toEqual({ status: 'open', year: '2026' }) + }) + + it('uses the organisation default without a rate, and the rate as burst without a burst', () => { + expect(rateLimitPolicy('', 10)).toBeNull() + expect(rateLimitPolicy('600', '')).toEqual({ requestsPerMinute: 600, burstSize: 600 }) + expect(rateLimitPolicy(600, '60')).toEqual({ requestsPerMinute: 600, burstSize: 60 }) + }) + + it('builds a read-only create payload without actions or filters', () => { + const form = { + ...formFromToken(null, { subjectType: 'dashboard', subjectId: 'dash-uuid', dashboardId: 7 }), + name: ' Zeist WOO ', + filterContext: 'status=open', + allowedActions: ['export'], + allowedFilters: 'status', + hostOrigins: ['https://WWW.Zeist.nl/'], + tenantThemeId: 'th-1', + tokenExpiresAt: '2026-12-31', + requestsPerMinute: '600', + burstSize: '60', + } + expect(createPayload(form)).toEqual({ + name: 'Zeist WOO', + description: '', + subject: { type: 'dashboard', id: 'dash-uuid', filterContext: { status: 'open' } }, + scope: { mode: 'read', allowedFilters: [], allowedActions: [] }, + hostOrigins: ['https://www.zeist.nl'], + tenantThemeId: 'th-1', + tokenExpiresAt: '2026-12-31T00:00:00Z', + rateLimitPolicy: { requestsPerMinute: 600, burstSize: 60 }, + }) + }) + + it('keeps the allowed actions and filters of an interactive scope, in canonical order', () => { + const form = { + ...formFromToken(null, { subjectType: 'widget', subjectId: '42' }), + name: 'Grafiek', + mode: 'read-with-interactions', + allowedActions: ['export', 'bogus', 'interact'], + allowedFilters: 'status, year,status', + hostOrigins: ['https://a.nl'], + } + const payload = createPayload(form) + expect(payload.subject).toEqual({ type: 'widget', id: '42' }) + expect(payload.scope).toEqual({ mode: 'read-with-interactions', allowedFilters: ['status', 'year'], allowedActions: ['interact', 'export'] }) + expect(payload.tenantThemeId).toBeNull() + expect(payload.tokenExpiresAt).toBeNull() + expect(payload.rateLimitPolicy).toBeNull() + }) + + it('round-trips a stored token into the form, and updates only what may change', () => { + const token = { + name: 'Zeist', + description: 'WOO', + subject: { type: 'dashboard', id: 'd', filterContext: { status: 'open' } }, + scope: { mode: 'read-with-interactions', allowedActions: ['drillDown'], allowedFilters: ['status', 'year'] }, + hostOrigins: ['https://a.nl'], + tokenExpiresAt: '2026-12-31T00:00:00Z', + rateLimitPolicy: { requestsPerMinute: 100, burstSize: 10 }, + } + const form = formFromToken(token) + expect(form).toMatchObject({ filterContext: 'status=open', allowedFilters: 'status, year', tokenExpiresAt: '2026-12-31', requestsPerMinute: 100 }) + expect(updatePayload({ ...form, name: 'Zeist 2 ' })).toEqual({ name: 'Zeist 2', description: 'WOO', rateLimitPolicy: { requestsPerMinute: 100, burstSize: 10 } }) + }) + + it('accepts only :root rules in custom CSS', () => { + expect(onlyRootRules('')).toBe(true) + expect(onlyRootRules(':root { --gap: 8px; }\n/* body { } */:root{--x:1}')).toBe(true) + expect(onlyRootRules(':root { --gap: 8px; } body { color: red; }')).toBe(false) + expect(onlyRootRules(':root, body { color: red; }')).toBe(false) + }) + + it('reads the subject of a link into Beheer ▸ Embeds', () => { + expect(embedDefaultsFrom('?tab=embeds&embedType=dashboard&embedId=dash-uuid&embedDashboard=7')) + .toEqual({ subjectType: 'dashboard', subjectId: 'dash-uuid', dashboardId: 7 }) + expect(embedDefaultsFrom('?embedType=widget&embedId=42')).toEqual({ subjectType: 'widget', subjectId: '42', dashboardId: null }) + expect(embedDefaultsFrom('?embedType=page&embedId=1')).toEqual({}) + expect(embedDefaultsFrom('?tab=embeds')).toEqual({}) + }) +}) + +describe('embedAdminSearch', () => { + it('builds the link embedDefaultsFrom reads back', () => { + const search = embedAdminSearch('widget', 42, 7) + expect(search).toBe('tab=embeds&embedType=widget&embedId=42&embedDashboard=7') + expect(embedDefaultsFrom(`?${search}`)).toEqual({ subjectType: 'widget', subjectId: '42', dashboardId: 7 }) + expect(embedAdminSearch('dashboard', 'dash-uuid')).toBe('tab=embeds&embedType=dashboard&embedId=dash-uuid&embedDashboard=') + }) + + it('gives nothing without a valid subject', () => { + expect(embedAdminSearch('page', 1, 7)).toBe('') + expect(embedAdminSearch('widget', '', 7)).toBe('') + expect(embedAdminSearch('widget', null, 7)).toBe('') + }) +}) diff --git a/src/utils/__tests__/embedTokenSharing.spec.js b/src/utils/__tests__/embedTokenSharing.spec.js new file mode 100644 index 000000000..33605e319 --- /dev/null +++ b/src/utils/__tests__/embedTokenSharing.spec.js @@ -0,0 +1,44 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. <info@conduction.nl> + * SPDX-License-Identifier: EUPL-1.2 + * + * The Sharing tab's embed helpers: which tokens belong to a dashboard and + * the code a website pastes (REQ-EMB-011). + * + * @spec openspec/changes/archive/2026-11-24-sharing-tab-embed-and-conversation/specs/embedded-analytics/spec.md#requirement-embed-tokens-on-the-sharing-tab-req-emb-011 + */ + +import { describe, expect, it } from 'vitest' +import { embedCode, tokensForDashboard } from '../embedToken.js' + +const TOKENS = [ + { id: 'a', name: 'Whole', subject: { type: 'dashboard', id: 'dash-1' } }, + { id: 'b', name: 'Widget here', subject: { type: 'widget', id: '7' } }, + { id: 'c', name: 'Other dashboard', subject: { type: 'dashboard', id: 'dash-2' } }, + { id: 'd', name: 'Widget elsewhere', subject: { type: 'widget', id: '99' } }, + { id: 'e', name: 'No subject' }, +] + +describe('tokensForDashboard', () => { + it('keeps the dashboard token and the tokens of its own widgets', () => { + expect(tokensForDashboard(TOKENS, 'dash-1', [7, 8]).map((token) => token.id)).toEqual(['a', 'b']) + }) + + it('finds nothing without a uuid or placements', () => { + expect(tokensForDashboard(TOKENS, '', [])).toEqual([]) + expect(tokensForDashboard(null, 'dash-1')).toEqual([]) + }) +}) + +describe('embedCode', () => { + it('is an iframe on the public embed route with the token', () => { + const code = embedCode({ name: 'Website Zuiddrecht', subject: { type: 'widget', id: '7' } }, 'https://cloud.example/index.php/apps/launchpad/', 'jwt.value') + expect(code).toBe('<iframe src="https://cloud.example/index.php/apps/launchpad/embed/widget/7?token=jwt.value" title="Website Zuiddrecht" width="100%" height="480" style="border:0" loading="lazy"></iframe>') + }) + + it('uses a placeholder once the token is no longer at hand, and escapes the name', () => { + const code = embedCode({ name: 'A "quoted" <name>', subject: { type: 'dashboard', id: 'dash-1' } }, 'https://x') + expect(code).toContain('src="https://x/embed/dashboard/dash-1?token=YOUR_TOKEN"') + expect(code).toContain('title="A "quoted" <name>"') + }) +}) diff --git a/src/utils/__tests__/fixtures/bookmarks-chrome.html b/src/utils/__tests__/fixtures/bookmarks-chrome.html new file mode 100644 index 000000000..2689490d1 --- /dev/null +++ b/src/utils/__tests__/fixtures/bookmarks-chrome.html @@ -0,0 +1,21 @@ +<!DOCTYPE NETSCAPE-Bookmark-file-1> +<!-- This is an automatically generated file. + It will be read and overwritten. + DO NOT EDIT! --> +<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"> +<TITLE>Bookmarks +

Bookmarks

+

+

Bookmarks bar

+

+

Google +

Privé

+

+

Bank +
Notes +

+

+

Other bookmarks

+

+

+

diff --git a/src/utils/__tests__/fixtures/bookmarks-edge.html b/src/utils/__tests__/fixtures/bookmarks-edge.html new file mode 100644 index 000000000..54f4fefac --- /dev/null +++ b/src/utils/__tests__/fixtures/bookmarks-edge.html @@ -0,0 +1,15 @@ + + + +Bookmarks +

Bookmarks

+

+

Favorites bar

+

+

Bing +
+

+

Outlook +

diff --git a/src/utils/__tests__/fixtures/bookmarks-firefox.html b/src/utils/__tests__/fixtures/bookmarks-firefox.html new file mode 100644 index 000000000..021aaf12e --- /dev/null +++ b/src/utils/__tests__/fixtures/bookmarks-firefox.html @@ -0,0 +1,27 @@ + + + + +Bookmarks +

Bookmarks Menu

+ +

+

Mozilla +
Bookmarklet +

Werk

+

+

Wiki +
Mail & agenda +

Projecten

+

+

Planning +

+

+

Bookmarks Toolbar

+

+

News +

+

diff --git a/src/utils/__tests__/gridItemLabel.spec.js b/src/utils/__tests__/gridItemLabel.spec.js new file mode 100644 index 000000000..f10de5091 --- /dev/null +++ b/src/utils/__tests__/gridItemLabel.spec.js @@ -0,0 +1,40 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * grid-layout REQ-GRID-008 / REQ-GRID-KBD-001: the accessible name of a grid item. + */ + +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@conduction/nextcloud-vue', () => ({ + dashboardWidgetRegistry: { + text: { displayName: 'Text' }, + }, +})) + +const { gridItemLabel } = await import('../gridItemLabel.js') + +const PLACEMENT = { id: 7, widgetId: 'text', customTitle: 'Team Announcements', gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 2 } + +describe('gridItemLabel', () => { + it('names the widget by its title outside edit mode', () => { + expect(gridItemLabel(PLACEMENT, { editing: false, columns: 12, availableWidgets: [] })) + .toBe('Widget: Team Announcements') + }) + + it('adds the position and size in edit mode', () => { + expect(gridItemLabel({ ...PLACEMENT, gridX: 3, gridY: 5 }, { editing: true, columns: 12, availableWidgets: [] })) + .toBe('Widget: Team Announcements, column 4 of 12, row 6, 4 columns wide, 2 rows tall') + }) + + it('falls back to the type name when the placement has no title', () => { + expect(gridItemLabel({ ...PLACEMENT, customTitle: '' }, { editing: false, columns: 12, availableWidgets: [] })) + .toBe('Widget: Text') + }) + + it('reads a missing rectangle as the top-left single cell', () => { + expect(gridItemLabel({ widgetId: 'text', customTitle: 'Notes' }, { editing: true, columns: 6, availableWidgets: [] })) + .toBe('Widget: Notes, column 1 of 6, row 1, 1 columns wide, 1 rows tall') + }) +}) diff --git a/src/utils/__tests__/groupOptions.spec.js b/src/utils/__tests__/groupOptions.spec.js new file mode 100644 index 000000000..b471bb819 --- /dev/null +++ b/src/utils/__tests__/groupOptions.spec.js @@ -0,0 +1,35 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { describe, expect, it } from 'vitest' +import { toGroupOptions } from '../groupOptions.js' + +describe('toGroupOptions', () => { + it('turns plain ids into options labelled by the id', () => { + expect(toGroupOptions(['marketing', 'sales'])).toEqual([ + { id: 'marketing', displayName: 'marketing' }, + { id: 'sales', displayName: 'sales' }, + ]) + }) + + it('keeps a group\'s display name, and falls back to its id', () => { + expect(toGroupOptions([{ id: 'mkt', displayName: 'Marketing' }, { id: 'ops' }])).toEqual([ + { id: 'mkt', displayName: 'Marketing' }, + { id: 'ops', displayName: 'ops' }, + ]) + }) + + it('adds chosen ids the list does not carry, once', () => { + expect(toGroupOptions(['sales'], ['sales', 'gone'])).toEqual([ + { id: 'sales', displayName: 'sales' }, + { id: 'gone', displayName: 'gone' }, + ]) + }) + + it('drops entries without an id and survives missing input', () => { + expect(toGroupOptions([{ displayName: 'x' }, '', null])).toEqual([]) + expect(toGroupOptions(undefined, undefined)).toEqual([]) + }) +}) diff --git a/src/utils/__tests__/groupTiles.spec.js b/src/utils/__tests__/groupTiles.spec.js new file mode 100644 index 000000000..5a5b5a73d --- /dev/null +++ b/src/utils/__tests__/groupTiles.spec.js @@ -0,0 +1,155 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * A tile inside a group read into the tile form and written back into the + * group with the group's sort order (tile-form-board-sync REQ-TILE-041). + */ + +import { describe, expect, it } from 'vitest' +import { + groupChildFromTile, + groupChildToTile, + isGroupTileChild, + withGroupTileRemoved, + withGroupTileSaved, +} from '../groupTiles.js' + +const caseSystem = { + type: 'tile', + gridX: 2, + gridY: 0, + gridWidth: 2, + gridHeight: 2, + content: { + title: 'Case system', + icon: 'M1 1', + iconType: 'svg', + backgroundColor: '#123456', + textColor: '#ffffff', + linkType: 'url', + linkValue: 'https://cases.example.org', + healthPingEnabled: true, + internalUrl: 'http://cases.local', + pinned: true, + }, +} + +const bookmark = { + type: 'link', + gridX: 0, + gridY: 0, + content: { label: 'Intranet', url: 'https://intranet.example.org', actionType: 'external' }, +} + +describe('isGroupTileChild', () => { + it('takes a tile and a link that opens one address', () => { + expect(isGroupTileChild(caseSystem)).toBe(true) + expect(isGroupTileChild(bookmark)).toBe(true) + expect(isGroupTileChild({ type: 'link', content: { url: '/apps/files' } })).toBe(true) + }) + + it('leaves an office New tile, an action link, a link list and other widgets alone', () => { + expect(isGroupTileChild({ type: 'tile', content: { linkType: 'create', linkValue: 'docx' } })).toBe(false) + expect(isGroupTileChild({ type: 'link', content: { url: 'x', actionType: 'createFile' } })).toBe(false) + expect(isGroupTileChild({ type: 'link', content: { url: 'x', links: [{ url: 'y' }] } })).toBe(false) + expect(isGroupTileChild({ type: 'link', content: { url: ' ' } })).toBe(false) + expect(isGroupTileChild({ type: 'label', content: { text: 'Hi' } })).toBe(false) + expect(isGroupTileChild(null)).toBe(false) + expect(isGroupTileChild('tile')).toBe(false) + }) +}) + +describe('groupChildToTile', () => { + it('reads the fields the form edits from a tile child', () => { + expect(groupChildToTile(caseSystem)).toEqual({ + title: 'Case system', + icon: 'M1 1', + iconType: 'svg', + backgroundColor: '#123456', + textColor: '#ffffff', + linkType: 'url', + linkValue: 'https://cases.example.org', + }) + }) + + it('reads a link child as a web address tile', () => { + expect(groupChildToTile(bookmark)).toEqual({ + title: 'Intranet', + iconType: 'svg', + linkType: 'url', + linkValue: 'https://intranet.example.org', + }) + }) +}) + +describe('groupChildFromTile', () => { + it('writes the form result and keeps every key the form does not edit, and the layout', () => { + const saved = groupChildFromTile(caseSystem, { ...groupChildToTile(caseSystem), title: 'Cases', healthPingEnabled: false }) + expect(saved.type).toBe('tile') + expect(saved.gridX).toBe(2) + expect(saved.content.title).toBe('Cases') + // Launch, availability and office-network settings are kept, not dropped. + expect(saved.content.healthPingEnabled).toBe(true) + expect(saved.content.internalUrl).toBe('http://cases.local') + expect(saved.content.pinned).toBe(true) + }) + + it('turns a link child into a tile node without its link keys', () => { + const saved = groupChildFromTile(bookmark, { ...groupChildToTile(bookmark), icon: 'M2 2' }) + expect(saved.type).toBe('tile') + expect(saved.gridX).toBe(0) + expect(saved.content).toEqual({ + title: 'Intranet', + icon: 'M2 2', + iconType: 'svg', + linkType: 'url', + linkValue: 'https://intranet.example.org', + }) + }) + + it('paints a theme colour as its CSS variable and drops an emptied field', () => { + const saved = groupChildFromTile(caseSystem, { ...groupChildToTile(caseSystem), colourToken: '--sc-primary', textColor: '' }) + expect(saved.content.colourToken).toBe('--sc-primary') + expect(saved.content.backgroundColor).toBe('var(--sc-primary, #3669a5)') + expect('textColor' in saved.content).toBe(false) + }) +}) + +describe('withGroupTileSaved', () => { + const group = { title: 'Work apps', sortBy: 'manual', placements: [bookmark, caseSystem] } + + it('replaces the one child and writes the group sort order', () => { + const content = withGroupTileSaved(group, 1, { ...groupChildToTile(caseSystem), groupSortBy: 'last-used' }) + expect(content.title).toBe('Work apps') + expect(content.sortBy).toBe('last-used') + expect(content.placements[0]).toBe(bookmark) + expect(content.placements[1].content.title).toBe('Case system') + // The stored content is not changed in place. + expect(group.sortBy).toBe('manual') + expect(group.placements[1]).toBe(caseSystem) + }) + + it('keeps the sort order when the form carries none, and normalises an unknown one', () => { + expect(withGroupTileSaved(group, 0, groupChildToTile(bookmark)).sortBy).toBe('manual') + expect(withGroupTileSaved(group, 0, { ...groupChildToTile(bookmark), groupSortBy: 'sideways' }).sortBy).toBe('manual') + }) + + it('answers null for a child that is not there or not a tile', () => { + expect(withGroupTileSaved(group, 5, {})).toBeNull() + expect(withGroupTileSaved({ placements: [{ type: 'label' }] }, 0, {})).toBeNull() + expect(withGroupTileSaved({}, 0, {})).toBeNull() + }) +}) + +describe('withGroupTileRemoved', () => { + it('removes the one child', () => { + const content = withGroupTileRemoved({ title: 'Work apps', placements: [bookmark, caseSystem] }, 0) + expect(content).toEqual({ title: 'Work apps', placements: [caseSystem] }) + }) + + it('answers null for a child that is not a tile', () => { + expect(withGroupTileRemoved({ placements: [{ type: 'label' }] }, 0)).toBeNull() + expect(withGroupTileRemoved(null, 0)).toBeNull() + }) +}) diff --git a/src/utils/__tests__/headerActionsDock.spec.js b/src/utils/__tests__/headerActionsDock.spec.js new file mode 100644 index 000000000..aadf213d1 --- /dev/null +++ b/src/utils/__tests__/headerActionsDock.spec.js @@ -0,0 +1,77 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The top-right controls dock into a greeting row on the page ground and + * float otherwise (LpStart; floating, they covered the greeting). + * + * @spec openspec/specs/runtime-shell/spec.md#requirement-req-shell-009-no-navigation-panel-the-destinations-are-in-the-more-menu + */ + +import { beforeEach, describe, expect, it } from 'vitest' +import { HEADER_ACTIONS_CLASS, PAGE_HEADER_DOCK_CLASS, resolveHeaderActionsTarget } from '../headerActionsDock.js' + +/** + * @param {string} html Inner HTML of the container. + * @return {HTMLElement} The container, attached to the document. + */ +function container(html) { + const el = document.createElement('div') + el.className = 'launchpad-container' + el.innerHTML = html + document.body.appendChild(el) + return el +} + +const GROUND = '' + +describe('resolveHeaderActionsTarget', () => { + beforeEach(() => { + document.body.innerHTML = '' + }) + + it('floats when there is no container', () => { + expect(resolveHeaderActionsTarget(null, false)).toBeNull() + }) + + it('floats on a dashboard without a greeting on the page ground', () => { + const el = container('
') + expect(resolveHeaderActionsTarget(el, false)).toBeNull() + expect(el.querySelector('.' + HEADER_ACTIONS_CLASS)).toBeNull() + }) + + it('docks into the greeting row, after the greeting, and reuses the same element', () => { + const el = container(GROUND) + const target = resolveHeaderActionsTarget(el, false) + const header = el.querySelector('.cn-header-widget--ground') + expect(target).not.toBeNull() + expect(target.parentElement).toBe(header) + expect(header.lastElementChild).toBe(target) + expect(resolveHeaderActionsTarget(el, false)).toBe(target) + expect(el.querySelectorAll('.' + HEADER_ACTIONS_CLASS)).toHaveLength(1) + }) + + it('floats while editing and removes the actions element', () => { + const el = container(GROUND) + resolveHeaderActionsTarget(el, false) + expect(resolveHeaderActionsTarget(el, true)).toBeNull() + expect(el.querySelector('.' + HEADER_ACTIONS_CLASS)).toBeNull() + }) + + it('moves to the new greeting row when another dashboard replaces it', () => { + const el = container(GROUND) + const first = resolveHeaderActionsTarget(el, false) + el.innerHTML = GROUND + const second = resolveHeaderActionsTarget(el, false) + expect(second).not.toBe(first) + expect(second.parentElement).toBe(el.querySelector('.cn-header-widget--ground')) + }) + + it('docks into the page title row on a dashboard without a greeting row', () => { + const el = container('
') + const slot = el.querySelector('.' + PAGE_HEADER_DOCK_CLASS) + expect(resolveHeaderActionsTarget(el, false)).toBe(slot) + expect(resolveHeaderActionsTarget(el, true)).toBe(slot) + expect(el.querySelector('.' + HEADER_ACTIONS_CLASS)).toBeNull() + }) +}) diff --git a/src/utils/__tests__/headerSearchField.spec.js b/src/utils/__tests__/headerSearchField.spec.js new file mode 100644 index 000000000..69cbab94b --- /dev/null +++ b/src/utils/__tests__/headerSearchField.spec.js @@ -0,0 +1,126 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Unit tests for `headerSearchField.js` (header-search-dropdown, REQ-SRCH-013): + * which element the top bar's results list serves, across core's top bar + * shapes, and that LaunchPad's own field comes out again cleanly. + * + * @spec openspec/changes/archive/2026-11-25-header-search-dropdown/specs/nc-unified-search-integration/spec.md#requirement-req-srch-013-the-top-bar-search-shows-its-results-under-the-field + */ + +import { afterEach, describe, expect, it } from 'vitest' +import { + fieldWords, + INLINE_FIELD_CLASS, + INLINE_HOST_CLASS, + removeInlineField, + resolveSearchField, +} from '../headerSearchField.js' + +/** + * Nextcloud 31+'s desktop top bar search: a landmark with only a button. + * + * @param {object} [options] Options. + * @param {string} [options.label] The button's visible words. + * @param {boolean} [options.mobile] The small-screen variant. + * @return {HTMLElement} The landmark, attached to the body. + */ +function coreLandmark({ label = 'Search apps, files, tags, messages', mobile = false } = {}) { + const host = document.createElement('search') + host.className = mobile ? 'unified-search-input unified-search-input--mobile' : 'unified-search-input' + const button = document.createElement('button') + button.className = 'unified-search-input__button' + button.setAttribute('aria-label', 'Unified search') + const span = document.createElement('span') + span.className = 'unified-search-input__label' + span.textContent = label + button.appendChild(span) + host.appendChild(button) + document.body.appendChild(host) + return host +} + +describe('resolveSearchField', () => { + afterEach(() => { + document.body.innerHTML = '' + }) + + it('gives null when nothing matched', () => { + expect(resolveSearchField(null, 'Search')).toBeNull() + }) + + it('uses a core text field as it is', () => { + const input = document.createElement('input') + document.body.appendChild(input) + expect(resolveSearchField(input, 'Search')).toEqual({ field: input, created: false, label: null }) + }) + + it('uses the text field inside a wrapper', () => { + const wrapper = document.createElement('div') + const input = document.createElement('input') + wrapper.appendChild(input) + expect(resolveSearchField(wrapper, 'Search').field).toBe(input) + }) + + it('places LaunchPad\'s own field in the button\'s place on Nextcloud 31+, with the button\'s words', () => { + const host = coreLandmark({ label: 'Zoek in Zuiddrecht' }) + const resolved = resolveSearchField(host, 'Search') + expect(resolved.created).toBe(true) + expect(resolved.field.tagName).toBe('INPUT') + expect(resolved.field.type).toBe('search') + expect(resolved.field.classList.contains(INLINE_FIELD_CLASS)).toBe(true) + expect(resolved.field.placeholder).toBe('Zoek in Zuiddrecht') + expect(resolved.field.getAttribute('aria-label')).toBe('Zoek in Zuiddrecht') + expect(resolved.field.nextElementSibling.className).toBe('unified-search-input__button') + expect(host.classList.contains(INLINE_HOST_CLASS)).toBe(true) + expect(resolved.label.textContent).toBe('Zoek in Zuiddrecht') + }) + + it('leaves the small-screen button alone', () => { + expect(resolveSearchField(coreLandmark({ mobile: true }), 'Search')).toBeNull() + expect(document.querySelector(`.${INLINE_FIELD_CLASS}`)).toBeNull() + }) + + it('gives null for a shape it does not know', () => { + const div = document.createElement('div') + expect(resolveSearchField(div, 'Search')).toBeNull() + }) +}) + +describe('fieldWords', () => { + it('prefers the visible label, then the accessible name, then the fallback', () => { + const button = document.createElement('button') + expect(fieldWords(button, 'Search')).toBe('Search') + button.setAttribute('aria-label', 'Unified search') + expect(fieldWords(button, 'Search')).toBe('Unified search') + const span = document.createElement('span') + span.className = 'unified-search-input__label' + span.textContent = ' Zoeken ' + button.appendChild(span) + expect(fieldWords(button, 'Search')).toBe('Zoeken') + expect(fieldWords(null, 'Search')).toBe('Search') + }) +}) + +describe('removeInlineField', () => { + afterEach(() => { + document.body.innerHTML = '' + }) + + it('takes LaunchPad\'s field out and gives the button back', () => { + const host = coreLandmark() + const { field } = resolveSearchField(host, 'Search') + removeInlineField(field) + expect(host.querySelector('input')).toBeNull() + expect(host.classList.contains(INLINE_HOST_CLASS)).toBe(false) + }) + + it('never removes a core field', () => { + const input = document.createElement('input') + document.body.appendChild(input) + removeInlineField(input) + removeInlineField(null) + expect(document.body.contains(input)).toBe(true) + }) +}) diff --git a/src/utils/__tests__/hierarchyPresets.spec.js b/src/utils/__tests__/hierarchyPresets.spec.js new file mode 100644 index 000000000..e0ad66fac --- /dev/null +++ b/src/utils/__tests__/hierarchyPresets.spec.js @@ -0,0 +1,40 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The hierarchy presets a dashboard owner picks from (REQ-CWF-011). + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-011-a-dashboard-stores-its-hierarchies + */ + +import { describe, expect, it, vi } from 'vitest' +import { hierarchyPresets, NL_ADMINISTRATIVE, presetLevelLabels } from '../hierarchyPresets.js' + +vi.mock('@nextcloud/l10n', () => ({ t: (_app, key) => `nl:${key}` })) + +describe('hierarchyPresets', () => { + it('ships nl-administrative as province > municipality > district > neighbourhood, each level under the one above', () => { + const preset = hierarchyPresets().find((entry) => entry.id === NL_ADMINISTRATIVE) + + expect(preset.name).toBe('nl:Dutch administrative areas') + expect(preset.descriptor).toEqual({ + id: 'nl-administrative', + levels: [ + { dimension: 'provincieCode', label: 'Province', parentDimension: null }, + { dimension: 'gemeenteCode', label: 'Municipality', parentDimension: 'provincieCode' }, + { dimension: 'wijkCode', label: 'District', parentDimension: 'gemeenteCode' }, + { dimension: 'buurtCode', label: 'Neighbourhood', parentDimension: 'wijkCode' }, + ], + }) + }) + + it('stores the English source labels and shows the translated ones', () => { + expect(presetLevelLabels(NL_ADMINISTRATIVE)).toEqual({ + provincieCode: 'nl:Province', + gemeenteCode: 'nl:Municipality', + wijkCode: 'nl:District', + buurtCode: 'nl:Neighbourhood', + }) + expect(presetLevelLabels('own-taxonomy')).toBeNull() + }) +}) diff --git a/src/utils/__tests__/installPrompt.spec.js b/src/utils/__tests__/installPrompt.spec.js new file mode 100644 index 000000000..335b8ccd7 --- /dev/null +++ b/src/utils/__tests__/installPrompt.spec.js @@ -0,0 +1,120 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * When the phone install banner shows, and the 30-day Not now + * (platform-baseline REQ-PLB-009, board LpMobiel). + * + * @spec openspec/changes/archive/2026-11-24-phone-install-banner/specs/platform-baseline/spec.md#requirement-a-phone-offers-to-put-launchpad-on-the-home-screen-req-plb-009 + */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + capturePrompt, + clearPrompt, + installPrompt, + isStandalone, + NOT_NOW_KEY, + NOT_NOW_MS, + readNotNowAt, + shouldShowInstallBanner, + writeNotNowAt, +} from '../installPrompt.js' + +const NOW = Date.UTC(2026, 9, 5, 11, 0) +const PHONE = { width: 390, standalone: false, kiosk: false, isPublic: false, notNowAt: null, now: NOW } + +afterEach(() => { + clearPrompt() +}) + +describe('shouldShowInstallBanner', () => { + it('shows on a phone in a browser tab', () => { + expect(shouldShowInstallBanner(PHONE)).toBe(true) + }) + + it.each([ + [767, true], + [768, false], + [1440, false], + ])('at %i px shows: %s', (width, shown) => { + expect(shouldShowInstallBanner({ ...PHONE, width })).toBe(shown) + }) + + it('hides once the page runs as an installed app', () => { + expect(shouldShowInstallBanner({ ...PHONE, standalone: true })).toBe(false) + }) + + it('hides in the kiosk view and on a public page', () => { + expect(shouldShowInstallBanner({ ...PHONE, kiosk: true })).toBe(false) + expect(shouldShowInstallBanner({ ...PHONE, isPublic: true })).toBe(false) + }) + + it('stays hidden for 30 days after Not now, then shows again', () => { + expect(shouldShowInstallBanner({ ...PHONE, notNowAt: NOW - NOT_NOW_MS + 1000 })).toBe(false) + expect(shouldShowInstallBanner({ ...PHONE, notNowAt: NOW - NOT_NOW_MS })).toBe(true) + }) + + it('hides when the width is unknown', () => { + expect(shouldShowInstallBanner({ ...PHONE, width: undefined })).toBe(false) + }) +}) + +describe('Not now storage', () => { + it('writes and reads the moment', () => { + const store = new Map() + const storage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, v) } + writeNotNowAt(storage, NOW) + expect(store.get(NOT_NOW_KEY)).toBe(String(NOW)) + expect(readNotNowAt(storage)).toBe(NOW) + }) + + it('reads never from an empty or garbled value', () => { + expect(readNotNowAt({ getItem: () => null })).toBeNull() + expect(readNotNowAt({ getItem: () => 'soon' })).toBeNull() + expect(readNotNowAt(null)).toBeNull() + }) + + it('a blocked storage only means the banner shows', () => { + const blocked = { + getItem: () => { throw new Error('SecurityError') }, + setItem: () => { throw new Error('QuotaExceededError') }, + } + expect(readNotNowAt(blocked)).toBeNull() + expect(() => writeNotNowAt(blocked, NOW)).not.toThrow() + }) +}) + +describe('isStandalone', () => { + it('reads the standalone display mode', () => { + expect(isStandalone({ navigator: {}, matchMedia: () => ({ matches: true }) })).toBe(true) + expect(isStandalone({ navigator: {}, matchMedia: () => ({ matches: false }) })).toBe(false) + }) + + it('reads Safari on iOS opened from the home screen', () => { + expect(isStandalone({ navigator: { standalone: true } })).toBe(true) + }) + + it('is false without a window or when matchMedia throws', () => { + expect(isStandalone(null)).toBe(false) + expect(isStandalone({ navigator: {}, matchMedia: () => { throw new Error('x') } })).toBe(false) + }) +}) + +describe('the captured prompt', () => { + it('keeps the beforeinstallprompt event and stops the browser bar', () => { + const event = { preventDefault: vi.fn() } + capturePrompt(event) + expect(event.preventDefault).toHaveBeenCalled() + expect(installPrompt()).toBe(event) + clearPrompt() + expect(installPrompt()).toBeNull() + }) + + it('is captured from the window event', () => { + const event = new Event('beforeinstallprompt') + window.dispatchEvent(event) + expect(installPrompt()).toBe(event) + expect(event.defaultPrevented).toBe(false) + }) +}) diff --git a/src/utils/__tests__/instanceTheme.spec.js b/src/utils/__tests__/instanceTheme.spec.js new file mode 100644 index 000000000..182765a2f --- /dev/null +++ b/src/utils/__tests__/instanceTheme.spec.js @@ -0,0 +1,46 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The instance theme name the dashboard settings show read-only (REQ-THM-004). + * + * @spec openspec/changes/archive/2026-11-24-dashboard-theme-readonly/specs/dashboards/spec.md#requirement-the-details-tab-shows-the-instance-theme-read-only-req-thm-004 + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const capabilities = vi.fn() +vi.mock('@nextcloud/capabilities', () => ({ getCapabilities: () => capabilities() })) + +const { instanceThemeName } = await import('../instanceTheme.js') + +describe('instanceThemeName', () => { + beforeEach(() => capabilities.mockReset()) + + it('reads the active thematiq theme when thematiq sets one', () => { + capabilities.mockReturnValue({ + nldesign: { tokenSet: { id: 'zuiddrecht', name: 'Huisstijl Zuiddrecht' } }, + theming: { name: 'Nextcloud' }, + }) + expect(instanceThemeName()).toBe('Huisstijl Zuiddrecht') + }) + + it('falls back to the Nextcloud theming name without thematiq', () => { + capabilities.mockReturnValue({ theming: { name: 'Gemeente Cloud' } }) + expect(instanceThemeName()).toBe('Gemeente Cloud') + }) + + it('falls back to theming when thematiq publishes an empty name', () => { + capabilities.mockReturnValue({ nldesign: { tokenSet: { name: ' ' } }, theming: { name: 'Nextcloud' } }) + expect(instanceThemeName()).toBe('Nextcloud') + }) + + it('is empty without capabilities', () => { + capabilities.mockImplementation(() => { + throw new Error('no capabilities') + }) + expect(instanceThemeName()).toBe('') + capabilities.mockReturnValue(null) + expect(instanceThemeName()).toBe('') + }) +}) diff --git a/src/utils/__tests__/kioskMode.spec.js b/src/utils/__tests__/kioskMode.spec.js new file mode 100644 index 000000000..90b98b90d --- /dev/null +++ b/src/utils/__tests__/kioskMode.spec.js @@ -0,0 +1,81 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + CURSOR_IDLE_MS, + hideCursorWhenIdle, + IDLE_CLASS, + KIOSK_CLASS, + kioskFlag, + startKioskView, + withoutKiosk, +} from '../kioskMode.js' + +afterEach(() => { + vi.useRealTimers() + document.documentElement.className = '' +}) + +describe('kioskFlag', () => { + it('is on only for kiosk=1', () => { + expect(kioskFlag('?kiosk=1')).toBe(true) + expect(kioskFlag('?a=b&kiosk=1')).toBe(true) + expect(kioskFlag('?kiosk=0')).toBe(false) + expect(kioskFlag('?kiosk=true')).toBe(false) + expect(kioskFlag('')).toBe(false) + expect(kioskFlag(undefined)).toBe(false) + }) +}) + +describe('withoutKiosk', () => { + it('drops the flag and keeps the rest of the address', () => { + expect(withoutKiosk('https://nc.example/index.php/apps/launchpad/lobby?kiosk=1')).toBe( + 'https://nc.example/index.php/apps/launchpad/lobby', + ) + expect(withoutKiosk('https://nc.example/apps/launchpad/x?a=1&kiosk=1#top')).toBe( + 'https://nc.example/apps/launchpad/x?a=1#top', + ) + }) +}) + +describe('hideCursorWhenIdle', () => { + it('hides the cursor after the idle time and shows it on movement', () => { + vi.useFakeTimers() + const stop = hideCursorWhenIdle(document) + const root = document.documentElement + + vi.advanceTimersByTime(CURSOR_IDLE_MS - 1) + expect(root.classList.contains(IDLE_CLASS)).toBe(false) + vi.advanceTimersByTime(1) + expect(root.classList.contains(IDLE_CLASS)).toBe(true) + + document.dispatchEvent(new Event('mousemove')) + expect(root.classList.contains(IDLE_CLASS)).toBe(false) + + stop() + vi.advanceTimersByTime(CURSOR_IDLE_MS) + expect(root.classList.contains(IDLE_CLASS)).toBe(false) + }) +}) + +describe('startKioskView', () => { + it('marks the page, leaves for the normal route on Escape, and undoes it all', () => { + const assign = vi.fn() + const win = { document, location: { href: 'https://nc.example/apps/launchpad/lobby?kiosk=1', assign } } + const stop = startKioskView(win) + expect(document.documentElement.classList.contains(KIOSK_CLASS)).toBe(true) + + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' })) + expect(assign).not.toHaveBeenCalled() + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })) + expect(assign).toHaveBeenCalledWith('https://nc.example/apps/launchpad/lobby') + + stop() + expect(document.documentElement.classList.contains(KIOSK_CLASS)).toBe(false) + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })) + expect(assign).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/utils/__tests__/loadInitialState.spec.js b/src/utils/__tests__/loadInitialState.spec.js index 7f3d4a0c8..43fd5608f 100644 --- a/src/utils/__tests__/loadInitialState.spec.js +++ b/src/utils/__tests__/loadInitialState.spec.js @@ -97,11 +97,11 @@ describe('loadInitialState', () => { const message = warn.mock.calls[0][0] expect(message).toMatch(/LaunchPad initial-state schema mismatch/) expect(message).toMatch(/server v99/) - expect(message).toMatch(/client v2/) + expect(message).toMatch(/client v3/) }) it('does not warn when the schema versions match', async () => { - pushedState = { _schemaVersion: 2 } + pushedState = { _schemaVersion: 3 } const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const { loadInitialState } = await import('../loadInitialState.js') @@ -110,6 +110,15 @@ describe('loadInitialState', () => { expect(warn).not.toHaveBeenCalled() }) + it('reads the public start page token, empty when the server pushed none', async () => { + pushedState = { publicStartToken: 'Bib1Noord', _schemaVersion: 3 } + const { loadInitialState } = await import('../loadInitialState.js') + expect(loadInitialState('public-start')).toEqual({ publicStartToken: 'Bib1Noord' }) + + pushedState = {} + expect(loadInitialState('public-start')).toEqual({ publicStartToken: '' }) + }) + it('throws on an unknown page identifier', async () => { const { loadInitialState } = await import('../loadInitialState.js') expect(() => loadInitialState('not-a-page')).toThrow(/unknown page/) @@ -230,7 +239,7 @@ describe('loadInitialState', () => { }) it('fills defaults for every admin key the server omitted', async () => { - pushedState = { _schemaVersion: 2 } + pushedState = { _schemaVersion: 3 } const { loadInitialState } = await import('../loadInitialState.js') const state = loadInitialState('admin') @@ -254,14 +263,14 @@ describe('loadInitialState', () => { } }) - it('exports INITIAL_STATE_SCHEMA_VERSION matching the PHP constant (2)', async () => { + it('exports INITIAL_STATE_SCHEMA_VERSION matching the PHP constant (3)', async () => { const mod = await import('../loadInitialState.js') - expect(mod.INITIAL_STATE_SCHEMA_VERSION).toBe(2) + expect(mod.INITIAL_STATE_SCHEMA_VERSION).toBe(3) }) describe('quicksearchFallbackTarget (tile-quick-search REQ-QSEARCH-004)', () => { it('defaults to "none" when the server omits the key (older deploy)', async () => { - pushedState = { _schemaVersion: 2 } + pushedState = { _schemaVersion: 3 } const { loadInitialState } = await import('../loadInitialState.js') const state = loadInitialState('workspace') expect(state.quicksearchFallbackTarget).toBe('none') @@ -269,7 +278,7 @@ describe('loadInitialState', () => { it('returns the server-pushed value when present', async () => { pushedState = { - _schemaVersion: 2, + _schemaVersion: 3, quicksearchFallbackTarget: 'unified-search', } const { loadInitialState } = await import('../loadInitialState.js') @@ -278,3 +287,119 @@ describe('loadInitialState', () => { }) }) }) + +/** + * @spec openspec/changes/archive/2026-11-25-dashboard-first-load-from-initial-state/tasks.md#task-4 + */ +describe('takeDashboardFirstLoad', () => { + it('hands out the first load once, then null', async () => { + const firstLoad = { visible: { items: [], quota: null }, active: { dashboard: { uuid: 'a' } } } + pushedState = { dashboardFirstLoad: firstLoad } + + const { takeDashboardFirstLoad } = await import('../loadInitialState.js') + + expect(takeDashboardFirstLoad()).toEqual(firstLoad) + expect(takeDashboardFirstLoad()).toBeNull() + }) + + it('is null when the page did not carry it', async () => { + const { takeDashboardFirstLoad, loadInitialState } = await import('../loadInitialState.js') + + expect(loadInitialState('workspace').dashboardFirstLoad).toBeNull() + expect(takeDashboardFirstLoad()).toBeNull() + }) + + it('is null for a value without the visible list', async () => { + pushedState = { dashboardFirstLoad: { active: null } } + + const { takeDashboardFirstLoad } = await import('../loadInitialState.js') + + expect(takeDashboardFirstLoad()).toBeNull() + }) + + it('gives a missing active dashboard as null', async () => { + pushedState = { dashboardFirstLoad: { visible: [] } } + + const { takeDashboardFirstLoad } = await import('../loadInitialState.js') + + expect(takeDashboardFirstLoad()).toEqual({ visible: [], active: null }) + }) +}) + +/** + * @spec openspec/changes/archive/2026-11-25-org-navigation-from-initial-state/tasks.md#task-4 + */ +describe('takeOrgNavigation', () => { + it('hands out the org navigation once, then null', async () => { + pushedState = { orgNavigation: { position: 'left', tree: [{ id: 'n1' }], language: 'nl' } } + + const { takeOrgNavigation } = await import('../loadInitialState.js') + + expect(takeOrgNavigation()).toEqual({ position: 'left', tree: [{ id: 'n1' }], language: 'nl' }) + expect(takeOrgNavigation()).toBeNull() + }) + + it('is null when the page did not carry it', async () => { + const { takeOrgNavigation, loadInitialState } = await import('../loadInitialState.js') + + expect(loadInitialState('workspace').orgNavigation).toBeNull() + expect(takeOrgNavigation()).toBeNull() + }) + + it('is null for a value without a position or a tree', async () => { + pushedState = { orgNavigation: { position: 'left', tree: 'not a list' } } + + const { takeOrgNavigation } = await import('../loadInitialState.js') + + expect(takeOrgNavigation()).toBeNull() + }) +}) + +/** + * @spec openspec/changes/archive/2026-11-25-workspace-boot-reads-from-initial-state/tasks.md#task-4 + */ +describe('takeBootRead', () => { + it('hands out each part once, then undefined', async () => { + pushedState = { workspaceBootReads: { tiles: [{ id: 1 }], defaultDashboard: { uuid: 'u' } } } + + const { takeBootRead } = await import('../loadInitialState.js') + + expect(takeBootRead('tiles')).toEqual([{ id: 1 }]) + expect(takeBootRead('tiles')).toBeUndefined() + expect(takeBootRead('defaultDashboard')).toEqual({ uuid: 'u' }) + }) + + it('is undefined for a part the page did not carry, and without the key', async () => { + pushedState = { workspaceBootReads: { tiles: [] } } + const { takeBootRead, loadInitialState } = await import('../loadInitialState.js') + expect(takeBootRead('pendingAcknowledgements')).toBeUndefined() + + vi.resetModules() + pushedState = {} + const fresh = await import('../loadInitialState.js') + expect(fresh.loadInitialState('workspace').workspaceBootReads).toBeNull() + expect(fresh.takeBootRead('tiles')).toBeUndefined() + expect(loadInitialState).toBeTypeOf('function') + }) +}) + +/** + * @spec openspec/changes/archive/2026-11-25-manifest-cached-per-user/tasks.md#task-4 + */ +describe('takeRuntimeManifest', () => { + it('hands out the kept manifest once, then null', async () => { + pushedState = { runtimeManifest: { $schema: 'x', pages: [] } } + + const { takeRuntimeManifest } = await import('../loadInitialState.js') + + expect(takeRuntimeManifest()).toEqual({ $schema: 'x', pages: [] }) + expect(takeRuntimeManifest()).toBeNull() + }) + + it('is null without the key, and for a value that is not a manifest', async () => { + pushedState = { runtimeManifest: { pages: [] } } + const { takeRuntimeManifest, loadInitialState } = await import('../loadInitialState.js') + expect(takeRuntimeManifest()).toBeNull() + expect(loadInitialState('workspace').runtimeManifest).toEqual({ pages: [] }) + }) +}) diff --git a/src/utils/__tests__/logger.spec.js b/src/utils/__tests__/logger.spec.js new file mode 100644 index 000000000..2ab048011 --- /dev/null +++ b/src/utils/__tests__/logger.spec.js @@ -0,0 +1,65 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The app's console boundary: `warn` and `error` always forward their + * arguments verbatim, `debug` only when `launchpad:debug` is set to '1', + * read per call, and stays silent when storage throws. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { logger } from '../logger.js' + +beforeEach(() => { + vi.spyOn(console, 'debug').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + localStorage.clear() +}) + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + localStorage.clear() +}) + +describe('logger', () => { + it('forwards warn and error arguments verbatim', () => { + const err = new Error('x') + logger.warn('Unknown internal action:', 'foo') + logger.error('Failed:', err) + + expect(console.warn).toHaveBeenCalledWith('Unknown internal action:', 'foo') + expect(console.error).toHaveBeenCalledWith('Failed:', err) + }) + + it('keeps debug silent by default', () => { + logger.debug('[WidgetStore] trace') + + expect(console.debug).not.toHaveBeenCalled() + }) + + it('writes debug only while the key is exactly "1", re-read on every call', () => { + localStorage.setItem('launchpad:debug', '1') + logger.debug('a', 1) + expect(console.debug).toHaveBeenCalledWith('a', 1) + + localStorage.setItem('launchpad:debug', 'true') + logger.debug('b') + localStorage.removeItem('launchpad:debug') + logger.debug('c') + + expect(console.debug).toHaveBeenCalledTimes(1) + }) + + it('stays silent when storage throws', () => { + vi.stubGlobal('localStorage', { + getItem: () => { + throw new Error('SecurityError') + }, + }) + + expect(() => logger.debug('x')).not.toThrow() + expect(console.debug).not.toHaveBeenCalled() + }) +}) diff --git a/src/utils/__tests__/manifestRouteNames.spec.js b/src/utils/__tests__/manifestRouteNames.spec.js new file mode 100644 index 000000000..721624ef7 --- /dev/null +++ b/src/utils/__tests__/manifestRouteNames.spec.js @@ -0,0 +1,66 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Every named route the manifest links to must be a route the router has. + * `routesFromManifest` names one route per page id and nothing else, so an + * unknown name only shows up at runtime as a vue-router MATCHER_NOT_FOUND + * error in the browser console. + * + * @spec openspec/specs/runtime-shell/spec.md + */ + +import { describe, expect, it } from 'vitest' +import manifest from '../../manifest.json' +import { routesFromManifest } from '../manifestRoutes.js' + +/** + * Collect every `{ name }` object held under a key ending in "route" + * (route, viewAllRoute, ...), with the JSON path it was found at. + * + * @param {*} node The manifest node to walk. + * @param {string} path The JSON path of `node`. + * @param {Array} found Accumulator. + * + * @return {Array<{path: string, name: string}>} The named route references. + */ +function namedRouteRefs(node, path = '', found = []) { + if (Array.isArray(node)) { + node.forEach((child, i) => namedRouteRefs(child, `${path}[${i}]`, found)) + } else if (node && typeof node === 'object') { + for (const [key, value] of Object.entries(node)) { + if (/route$/i.test(key) && value && typeof value === 'object' && typeof value.name === 'string') { + found.push({ path: `${path}.${key}`, name: value.name }) + } + namedRouteRefs(value, `${path}.${key}`, found) + } + } + return found +} + +describe('manifest route names', () => { + const routeNames = new Set(routesFromManifest(manifest, {}).map((r) => r.name).filter(Boolean)) + + it('finds the named route references it checks', () => { + expect(namedRouteRefs(manifest).length).toBeGreaterThan(0) + }) + + it('links widgets only to routes the router registers', () => { + const unknown = namedRouteRefs(manifest).filter((ref) => !routeNames.has(ref.name)) + expect(unknown).toEqual([]) + }) + + it('points every menu route at a registered route', () => { + const unknown = (manifest.menu ?? []) + .filter((item) => typeof item.route === 'string' && !routeNames.has(item.route)) + .map((item) => ({ id: item.id, route: item.route })) + expect(unknown).toEqual([]) + }) + + it('flags a name the router does not have', () => { + const refs = namedRouteRefs({ widgets: [{ content: { route: { name: 'dashboards' } } }] }) + expect(refs.filter((ref) => !routeNames.has(ref.name))).toEqual([ + { path: '.widgets[0].content.route', name: 'dashboards' }, + ]) + }) +}) diff --git a/src/utils/__tests__/manifestRoutesCatchAll.spec.js b/src/utils/__tests__/manifestRoutesCatchAll.spec.js new file mode 100644 index 000000000..c1f7be8a6 --- /dev/null +++ b/src/utils/__tests__/manifestRoutesCatchAll.spec.js @@ -0,0 +1,58 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The catch-all keeps a dashboard's slug address (dashboard-deeplinking + * REQ-DDL-003, REQ-DDL-006): it is an alias of the start page, not a + * redirect that would rewrite the address to `/` in history. + * + * @spec openspec/specs/dashboard-deeplinking/spec.md + */ + +import { describe, expect, it } from 'vitest' +import { createMemoryHistory, createRouter } from 'vue-router' +import { routesFromManifest } from '../manifestRoutes.js' + +const component = { render: () => null } +const manifest = { + pages: [ + { id: 'Workspace', route: '/' }, + { id: 'Store', route: '/store' }, + { id: 'dashboard-detail', route: '/dashboards/:id' }, + ], +} + +/** + * A router over the given manifest, on memory history. + * + * @param {object} m The manifest. + * @return {object} the router. + */ +function routerFor(m) { + return createRouter({ history: createMemoryHistory(), routes: routesFromManifest(m, component) }) +} + +describe('routesFromManifest catch-all', () => { + it('serves a slug chain as the start page and keeps its address', async () => { + const router = routerFor(manifest) + await router.push('/team/sales') + + expect(router.currentRoute.value.name).toBe('Workspace') + expect(router.currentRoute.value.fullPath).toBe('/team/sales') + }) + + it('still routes the declared pages to themselves', async () => { + const router = routerFor(manifest) + await router.push('/store') + expect(router.currentRoute.value.name).toBe('Store') + + await router.push('/dashboards/7') + expect(router.currentRoute.value.name).toBe('dashboard-detail') + }) + + it('redirects to / when the manifest has no start page', async () => { + const routes = routesFromManifest({ pages: [{ id: 'Store', route: '/store' }] }, component) + + expect(routes.at(-1)).toEqual({ path: '/:pathMatch(.*)*', redirect: '/' }) + }) +}) diff --git a/src/utils/__tests__/narrowGridLayout.spec.js b/src/utils/__tests__/narrowGridLayout.spec.js new file mode 100644 index 000000000..9f79a005c --- /dev/null +++ b/src/utils/__tests__/narrowGridLayout.spec.js @@ -0,0 +1,81 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { describe, expect, it, vi } from 'vitest' +import { + DASHBOARD_BREAKPOINTS, + dashboardColumnLayout, + dashboardGridColumnOpts, + readingOrder, +} from '../narrowGridLayout.js' + +vi.mock('@conduction/nextcloud-vue', () => ({ + getDashboardColumnOpts: (breakpoints, layout) => ({ + breakpoints: breakpoints.map((point) => ({ ...point })), + layout, + breakpointForWindow: true, + }), +})) + +/** + * The top of board LpWerkplek on a 12-column grid: two tile groups side by + * side under their headings, a clock on the right and a search bar below. + * + * @return {Array} + */ +function workplace() { + const tile = (id, x, y) => ({ id, x, y, w: 1, h: 2 }) + return [ + { id: 'clock', x: 8, y: 0, w: 4, h: 3 }, + { id: 'my-apps', x: 0, y: 0, w: 4, h: 1 }, + { id: 'collaborate', x: 4, y: 0, w: 4, h: 1 }, + tile('case', 0, 1), tile('mail', 1, 1), tile('topdesk', 2, 1), tile('council', 3, 1), + tile('talk', 4, 1), tile('calendar', 5, 1), + tile('land', 0, 3), tile('claims', 1, 3), + tile('people', 4, 3), + { id: 'search', x: 0, y: 5, w: 8, h: 2 }, + ] +} + +describe('narrowGridLayout', () => { + it('keeps four columns on a phone', () => { + expect(DASHBOARD_BREAKPOINTS.map((point) => point.c)).toEqual([12, 8, 4]) + const opts = dashboardGridColumnOpts() + expect(opts.breakpoints.at(-1)).toEqual({ w: 768, c: 4 }) + expect(opts.layout).toBe(dashboardColumnLayout) + }) + + it('reads each tile group under its own heading', () => { + expect(readingOrder(workplace(), 12).map((node) => node.id)).toEqual([ + 'my-apps', 'case', 'mail', 'topdesk', 'council', 'land', 'claims', + 'collaborate', 'talk', 'calendar', 'people', + 'clock', 'search', + ]) + }) + + it('flows the tiles four to a row and gives every other widget a full row', () => { + const placed = [] + const nodes = workplace() + dashboardColumnLayout(4, 12, placed, nodes) + const at = Object.fromEntries(placed.map((node) => [node.id, [node.x, node.y, node.w]])) + + expect(nodes).toEqual([]) + expect(at['my-apps']).toEqual([0, 0, 4]) + expect(at.case).toEqual([0, 1, 1]) + expect(at.council).toEqual([3, 1, 1]) + expect(at.land).toEqual([0, 3, 1]) + expect(at.claims).toEqual([1, 3, 1]) + expect(at.collaborate).toEqual([0, 5, 4]) + expect(at.talk).toEqual([0, 6, 1]) + expect(at.clock).toEqual([0, 8, 4]) + expect(at.search).toEqual([0, 11, 4]) + }) + + it('moves and scales on a wider grid', () => { + const placed = [] + dashboardColumnLayout(8, 12, placed, [{ id: 'a', x: 6, y: 2, w: 6, h: 2 }]) + expect(placed).toEqual([{ id: 'a', x: 4, y: 2, w: 4, h: 2 }]) + }) +}) diff --git a/src/utils/__tests__/newWidgetSize.spec.js b/src/utils/__tests__/newWidgetSize.spec.js new file mode 100644 index 000000000..02cbd8bfd --- /dev/null +++ b/src/utils/__tests__/newWidgetSize.spec.js @@ -0,0 +1,24 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * header-widget REQ-HDR-009: default grid sizing for a header widget. + */ + +import { describe, expect, it } from 'vitest' +import { newWidgetSize } from '../newWidgetSize.js' + +describe('newWidgetSize', () => { + it('a header spans the full grid and is sized for the medium preset by default', () => { + expect(newWidgetSize({ type: 'header', content: {} }, 12, 60)).toEqual({ w: 12, h: 4 }) + }) + + it('a header follows its chosen preset and the dashboard column count', () => { + expect(newWidgetSize({ type: 'header', content: { height: 'small' } }, 12, 60)).toEqual({ w: 12, h: 2 }) + expect(newWidgetSize({ type: 'header', content: { height: 'xlarge' } }, 24, 60)).toEqual({ w: 24, h: 8 }) + }) + + it('other widget types keep the default size', () => { + expect(newWidgetSize({ type: 'text', content: {} }, 12, 60)).toBeNull() + }) +}) diff --git a/src/utils/__tests__/officeTiles.spec.js b/src/utils/__tests__/officeTiles.spec.js new file mode 100644 index 000000000..67f31f18a --- /dev/null +++ b/src/utils/__tests__/officeTiles.spec.js @@ -0,0 +1,43 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * integrations-office-tiles: the pack becomes one container of 2 by 2 tiles, + * two per row, with app tiles linking to the app's own page. + * + * @spec openspec/changes/integrations-office-tiles/specs/office-tiles/spec.md + */ + +import { describe, expect, it } from 'vitest' +import { officePackContainer } from '../officeTiles.js' + +const DOC = { title: 'New document', linkType: 'create', linkValue: 'richdocuments:.docx', icon: 'icon-filetype-file', iconType: 'class' } +const SHEET = { title: 'New spreadsheet', linkType: 'create', linkValue: 'richdocuments:.xlsx', icon: 'icon-filetype-file', iconType: 'class' } +const FILES = { title: 'Files', linkType: 'app', linkValue: 'files', icon: 'icon-files', iconType: 'class' } + +describe('officePackContainer', () => { + it('places the tiles two per row in 2 by 2 cells', () => { + const { content } = officePackContainer([DOC, SHEET, FILES], 'Office') + + expect(content.title).toBe('Office') + expect(content.placements.map((p) => [p.gridX, p.gridY, p.gridWidth, p.gridHeight])).toEqual([ + [0, 0, 2, 2], + [2, 0, 2, 2], + [0, 2, 2, 2], + ]) + expect(content.placements.every((p) => p.type === 'tile')).toBe(true) + }) + + it('keeps a create tile on its creator and links an app tile to its own page', () => { + const [doc, files] = officePackContainer([DOC, FILES], 'Office').content.placements + + expect(doc.content).toMatchObject({ title: 'New document', linkType: 'create', linkValue: 'richdocuments:.docx' }) + expect(files.content).toMatchObject({ title: 'Files', linkType: 'app', linkValue: '/apps/files/', icon: 'icon-files' }) + }) + + it('sizes the container to its rows plus the title row', () => { + expect(officePackContainer([DOC, SHEET, FILES], 'Office').size).toEqual({ w: 4, h: 5 }) + expect(officePackContainer([DOC], 'Office').size).toEqual({ w: 4, h: 3 }) + expect(officePackContainer([], 'Office').size).toEqual({ w: 4, h: 3 }) + }) +}) diff --git a/src/utils/__tests__/phoneHiddenWidgets.spec.js b/src/utils/__tests__/phoneHiddenWidgets.spec.js new file mode 100644 index 000000000..c6abf6d33 --- /dev/null +++ b/src/utils/__tests__/phoneHiddenWidgets.spec.js @@ -0,0 +1,99 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The phone notice names the hidden widgets: three by title, the rest + * counted (launchpad-mobile-remote-access REQ-MRA-007, board LpMobiel). + * + * @spec openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/specs/launchpad-mobile-remote-access/spec.md#requirement-the-phone-notice-names-the-hidden-widgets-req-mra-007 + */ + +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => String(vars[k])), +})) + +import { + hiddenWidgetTitle, + isPhoneReady, + isPhoneWidth, + namedList, + phoneHiddenPlacements, + phoneHiddenSentence, +} from '../phoneHiddenWidgets.js' + +describe('isPhoneReady', () => { + it('hides only a type that says mobileReady false', () => { + expect(isPhoneReady({ mobileReady: false })).toBe(false) + expect(isPhoneReady({ mobileReady: true })).toBe(true) + expect(isPhoneReady({})).toBe(true) + expect(isPhoneReady(null)).toBe(true) + }) +}) + +describe('isPhoneWidth', () => { + it('is a phone at 390 px, not at 1280 px or an unknown width', () => { + expect(isPhoneWidth(390)).toBe(true) + expect(isPhoneWidth(1280)).toBe(false) + expect(isPhoneWidth(0)).toBe(false) + expect(isPhoneWidth(undefined)).toBe(false) + }) +}) + +describe('phoneHiddenPlacements', () => { + it('keeps the placements whose type is not ready for a phone', () => { + const entries = { assistant: { mobileReady: false }, tile: { mobileReady: true } } + const placements = [{ id: 1, widgetId: 'assistant' }, { id: 2, widgetId: 'tile' }, { id: 3, widgetId: 'other' }] + expect(phoneHiddenPlacements(placements, (type) => entries[type] ?? null).map((p) => p.id)).toEqual([1]) + expect(phoneHiddenPlacements(null, () => null)).toEqual([]) + }) +}) + +describe('hiddenWidgetTitle', () => { + it('prefers the own title, then the content title, the type name and the type', () => { + expect(hiddenWidgetTitle({ customTitle: 'Snel beginnen (Word)', widgetId: 'tile' }, { displayName: 'Tile' })).toBe('Snel beginnen (Word)') + expect(hiddenWidgetTitle({ content: { title: 'Nieuws' }, widgetId: 'news' }, { displayName: 'News' })).toBe('Nieuws') + expect(hiddenWidgetTitle({ customTitle: ' ', widgetId: 'assistant' }, { displayName: 'Assistent' })).toBe('Assistent') + expect(hiddenWidgetTitle({ widgetId: 'assistant' }, null)).toBe('assistant') + expect(hiddenWidgetTitle({}, null)).toBe('') + }) +}) + +describe('namedList', () => { + it('names one, two and three widgets', () => { + expect(namedList([])).toBe('') + expect(namedList(['A'])).toBe('A') + expect(namedList(['A', 'B'])).toBe('A and B') + expect(namedList(['A', 'B', 'C'])).toBe('A, B and C') + }) + + it('names three and counts the rest', () => { + expect(namedList(['A', 'B', 'C', 'D', 'E'])).toBe('A, B, C and 2 more') + }) +}) + +describe('phoneHiddenSentence', () => { + it('says nothing when nothing is hidden', () => { + expect(phoneHiddenSentence([])).toBe('') + expect(phoneHiddenSentence(undefined)).toBe('') + }) + + it('counts and names two hidden widgets', () => { + expect(phoneHiddenSentence(['Snel beginnen (Word)', 'Assistent'])) + .toBe('2 widgets do not work on a phone and are hidden: Snel beginnen (Word) and Assistent.') + }) + + it('says one widget in the singular', () => { + expect(phoneHiddenSentence(['Assistent'])).toBe('One widget does not work on a phone and is hidden: Assistent.') + }) + + it('counts all five but names three', () => { + expect(phoneHiddenSentence(['A', 'B', 'C', 'D', 'E'])) + .toBe('5 widgets do not work on a phone and are hidden: A, B, C and 2 more.') + }) + + it('offers no desktop layout', () => { + expect(phoneHiddenSentence(['A', 'B'])).not.toMatch(/desktop/i) + }) +}) diff --git a/src/utils/__tests__/placementContent.spec.js b/src/utils/__tests__/placementContent.spec.js new file mode 100644 index 000000000..0ccc0d030 --- /dev/null +++ b/src/utils/__tests__/placementContent.spec.js @@ -0,0 +1,25 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { describe, expect, it } from 'vitest' +import { placementContent } from '../placementContent.js' + +describe('placementContent', () => { + it('reads the placement content as an object, empty when unset', () => { + expect(placementContent({ widgetId: 'text', content: { a: 1 } })).toEqual({ a: 1 }) + expect(placementContent({ widgetId: 'text', content: null })).toEqual({}) + expect(placementContent(undefined)).toEqual({}) + }) + + it('turns files-widget upload off when the placement never set it', () => { + expect(placementContent({ widgetId: 'files', content: { folderPath: '/a' } })).toEqual({ folderPath: '/a', allowUpload: false }) + expect(placementContent({ widgetId: 'files', content: null })).toEqual({ allowUpload: false }) + }) + + it('keeps an upload choice the author made', () => { + expect(placementContent({ widgetId: 'files', content: { allowUpload: true } })).toEqual({ allowUpload: true }) + expect(placementContent({ widgetId: 'files', content: { allowUpload: false } })).toEqual({ allowUpload: false }) + }) +}) diff --git a/src/utils/__tests__/printDashboard.spec.js b/src/utils/__tests__/printDashboard.spec.js new file mode 100644 index 000000000..82df53322 --- /dev/null +++ b/src/utils/__tests__/printDashboard.spec.js @@ -0,0 +1,62 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Download the dashboard: the reader's browser prints the page as it is now; + * nothing goes to the server. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-reader-can-download-the-dashboard-req-dpd-003 + */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { printDashboard, PRINTING_CLASS } from '../printDashboard.js' + +afterEach(() => { + document.title = '' + document.documentElement.classList.remove(PRINTING_CLASS) + vi.restoreAllMocks() +}) + +describe('printDashboard', () => { + it('prints under the dashboard name and restores the title after the dialog closes', () => { + document.title = 'Launchpad - Nextcloud' + let seen = null + vi.spyOn(window, 'print').mockImplementation(() => { + seen = { title: document.title, printing: document.documentElement.classList.contains(PRINTING_CLASS) } + }) + expect(printDashboard(' Managementinformatie ')).toBe(true) + expect(seen).toEqual({ title: 'Managementinformatie', printing: true }) + window.dispatchEvent(new Event('afterprint')) + expect(document.title).toBe('Launchpad - Nextcloud') + expect(document.documentElement.classList.contains(PRINTING_CLASS)).toBe(false) + }) + + it('keeps the page title for a dashboard without a name', () => { + document.title = 'Launchpad' + vi.spyOn(window, 'print').mockImplementation(() => { + expect(document.title).toBe('Launchpad') + }) + printDashboard('') + expect(window.print).toHaveBeenCalledTimes(1) + }) + + it('sends nothing to the server', () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(() => Promise.resolve(new Response(''))) + vi.spyOn(window, 'print').mockImplementation(() => {}) + printDashboard('Managementinformatie') + expect(fetchSpy).not.toHaveBeenCalled() + }) + + it('restores at once when the browser has no afterprint event', () => { + const doc = { title: 'Launchpad', documentElement: document.createElement('html') } + const win = { print: vi.fn() } + expect(printDashboard('Managementinformatie', { win, doc })).toBe(true) + expect(win.print).toHaveBeenCalledTimes(1) + expect(doc.title).toBe('Launchpad') + expect(doc.documentElement.classList.contains(PRINTING_CLASS)).toBe(false) + }) + + it('does nothing where the browser cannot print', () => { + expect(printDashboard('Managementinformatie', { win: {}, doc: document })).toBe(false) + }) +}) diff --git a/src/utils/__tests__/publicStart.spec.js b/src/utils/__tests__/publicStart.spec.js new file mode 100644 index 000000000..d6062db52 --- /dev/null +++ b/src/utils/__tests__/publicStart.spec.js @@ -0,0 +1,47 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * sharing-public-start-page: the start page's address, the sign-in address + * with `direct=1`, and which token the public page shows. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md + */ + +import { describe, expect, it } from 'vitest' +import { publicPageToken, signInUrl, startPageUrl } from '../publicStart.js' + +const generateUrl = (path) => '/index.php' + path + +describe('publicStart addresses', () => { + it('sends the redirect to the fixed start page path', () => { + expect(startPageUrl(generateUrl)).toBe('/index.php/apps/launchpad/start') + }) + + it('signs in through the login form with direct=1', () => { + expect(signInUrl(generateUrl)).toBe('/index.php/login?direct=1') + }) +}) + +describe('publicPageToken', () => { + it('shows the start page link when the server handed over its token', () => { + expect(publicPageToken('/index.php/apps/launchpad/start', 'Bib1Noord')).toEqual({ + token: 'Bib1Noord', + startPage: true, + }) + }) + + it('reads a share page token from the last path segment, trailing slash or not', () => { + expect(publicPageToken('/index.php/apps/launchpad/s/abc123', '')).toEqual({ token: 'abc123', startPage: false }) + expect(publicPageToken('/index.php/apps/launchpad/s/abc123/', '')).toEqual({ token: 'abc123', startPage: false }) + }) + + it('ignores a start token that is not a non-empty string', () => { + expect(publicPageToken('/apps/launchpad/s/abc123', null)).toEqual({ token: 'abc123', startPage: false }) + expect(publicPageToken('/apps/launchpad/s/abc123', 42)).toEqual({ token: 'abc123', startPage: false }) + }) + + it('answers an empty token for an empty path', () => { + expect(publicPageToken('', '')).toEqual({ token: '', startPage: false }) + }) +}) diff --git a/src/utils/__tests__/readReceipts.spec.js b/src/utils/__tests__/readReceipts.spec.js new file mode 100644 index 000000000..2d2d69ded --- /dev/null +++ b/src/utils/__tests__/readReceipts.spec.js @@ -0,0 +1,48 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The read confirmations counts, filters and initials (REQ-ACK-010). + * + * @spec openspec/changes/archive/2026-11-24-read-receipts-dialog/specs/dashboard-acknowledgements/spec.md#requirement-the-read-confirmations-dialog-req-ack-010 + */ + +import { describe, expect, it } from 'vitest' +import { filterReceipts, initialsOf, receiptCounts, receiptDate } from '../readReceipts.js' + +function rows(confirmed, pending) { + return [ + ...Array.from({ length: confirmed }, (_, i) => ({ userId: `c${i}`, status: 'acknowledged' })), + ...Array.from({ length: pending }, (_, i) => ({ userId: `p${i}`, status: 'pending' })), + ] +} + +describe('read confirmations', () => { + it('counts 128 of 164 confirmed with 36 to go', () => { + expect(receiptCounts({ rows: rows(128, 36) })).toEqual({ confirmed: 128, audience: 164, left: 36, percent: 78 }) + expect(receiptCounts(null)).toEqual({ confirmed: 0, audience: 0, left: 0, percent: 0 }) + }) + + it('filters Not confirmed yet to the 36 who have not', () => { + const all = rows(128, 36) + expect(filterReceipts(all, 'pending')).toHaveLength(36) + expect(filterReceipts(all, 'pending').every((row) => row.status === 'pending')).toBe(true) + expect(filterReceipts(all, 'confirmed')).toHaveLength(128) + expect(filterReceipts(all, 'everyone')).toBe(all) + expect(filterReceipts(undefined, 'pending')).toEqual([]) + }) + + it('takes the initials of a name', () => { + expect(initialsOf('Sanne de Vries')).toBe('SV') + expect(initialsOf('Pieter Jansen')).toBe('PJ') + expect(initialsOf('admin')).toBe('A') + expect(initialsOf('jan van der berg')).toBe('JB') + expect(initialsOf(' ')).toBe('?') + }) + + it('formats a date and leaves a bad one out', () => { + expect(receiptDate('2026-10-13 10:00:00')).not.toBe('') + expect(receiptDate('not a date')).toBe('') + expect(receiptDate(null)).toBe('') + }) +}) diff --git a/src/utils/__tests__/returnFocus.spec.js b/src/utils/__tests__/returnFocus.spec.js new file mode 100644 index 000000000..5e212f7e5 --- /dev/null +++ b/src/utils/__tests__/returnFocus.spec.js @@ -0,0 +1,80 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `dialogReturnFocus` (REQ-WDG-013). + */ + +import { afterEach, describe, expect, it } from 'vitest' +import { dialogReturnFocus, restoreLostFocus } from '../returnFocus.js' + +afterEach(() => { + document.body.innerHTML = '' +}) + +/** + * Put the More menu button on the page. + * + * @return {HTMLElement} the button. + */ +function moreMenuButton() { + document.body.innerHTML = '
' + return document.querySelector('button') +} + +describe('dialogReturnFocus', () => { + it('returns to the element that opened the dialog while it is on the page', () => { + moreMenuButton() + const cog = document.createElement('button') + document.body.appendChild(cog) + + expect(dialogReturnFocus(cog)).toBe(cog) + }) + + it('falls back to the More menu button when the opener is gone or was the body', () => { + const button = moreMenuButton() + const removedMenuItem = document.createElement('button') + + expect(dialogReturnFocus(removedMenuItem)).toBe(button) + expect(dialogReturnFocus(document.body)).toBe(button) + expect(dialogReturnFocus(null)).toBe(button) + }) + + it('leaves focus alone when there is no More menu', () => { + expect(dialogReturnFocus(null)).toBe(false) + }) +}) + +describe('restoreLostFocus', () => { + it('moves focus that fell to the page to the More menu button when the opener is gone', async () => { + const button = moreMenuButton() + const removedPickerItem = document.createElement('button') + document.activeElement.blur() + + await restoreLostFocus(removedPickerItem) + + expect(document.activeElement).toBe(button) + }) + + it('moves focus that fell to the page back to an opener still on the page', async () => { + moreMenuButton() + const cog = document.createElement('button') + document.body.appendChild(cog) + + await restoreLostFocus(cog) + + expect(document.activeElement).toBe(cog) + }) + + it('leaves focus where a focus trap or the user already put it', async () => { + const button = moreMenuButton() + const field = document.createElement('input') + document.body.appendChild(field) + field.focus() + + await restoreLostFocus(null) + + expect(document.activeElement).toBe(field) + expect(document.activeElement).not.toBe(button) + }) +}) diff --git a/src/utils/__tests__/rowFilter.spec.js b/src/utils/__tests__/rowFilter.spec.js new file mode 100644 index 000000000..a1cbcca35 --- /dev/null +++ b/src/utils/__tests__/rowFilter.spec.js @@ -0,0 +1,41 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * filterRows: the pure filter behind a widget's row filter (REQ-DWMS-008). + */ + +import { describe, expect, it } from 'vitest' +import { filterRows } from '../rowFilter.js' + +const ROWS = [ + { title: 'Bouwvergunning Dorpsstraat', reason: '3 open' }, + { title: 'Kapvergunning', reason: 'Wacht op advies' }, + { title: 'Melding', reason: null }, +] + +describe('filterRows', () => { + it('keeps every row for an empty or blank term, as a new array', () => { + const all = filterRows(ROWS, ' ', ['title']) + expect(all).toEqual(ROWS) + expect(all).not.toBe(ROWS) + }) + + it('matches case-insensitively on any named field, in the original order', () => { + expect(filterRows(ROWS, 'VERGUNNING', ['title']).map((r) => r.title)).toEqual([ + 'Bouwvergunning Dorpsstraat', + 'Kapvergunning', + ]) + expect(filterRows(ROWS, 'advies', ['title', 'reason']).map((r) => r.title)).toEqual(['Kapvergunning']) + }) + + it('skips missing values and never mutates the rows', () => { + const before = JSON.stringify(ROWS) + expect(filterRows(ROWS, 'null', ['reason'])).toEqual([]) + expect(JSON.stringify(ROWS)).toBe(before) + }) + + it('treats a missing list as empty', () => { + expect(filterRows(undefined, 'x', ['title'])).toEqual([]) + }) +}) diff --git a/src/utils/__tests__/runtimeManifestRequest.spec.js b/src/utils/__tests__/runtimeManifestRequest.spec.js new file mode 100644 index 000000000..b4ec45953 --- /dev/null +++ b/src/utils/__tests__/runtimeManifestRequest.spec.js @@ -0,0 +1,55 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +import axios from '@nextcloud/axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { takeRuntimeManifest } from '../loadInitialState.js' +import { resetRuntimeManifestRequest, runtimeManifestRequest } from '../runtimeManifestRequest.js' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('../loadInitialState.js', () => ({ takeRuntimeManifest: vi.fn(() => null) })) + +beforeEach(() => { + resetRuntimeManifestRequest() + axios.get.mockReset() + axios.get.mockResolvedValue({ status: 200, data: { $schema: 'x' } }) + takeRuntimeManifest.mockReset() + takeRuntimeManifest.mockReturnValue(null) +}) + +describe('runtimeManifestRequest', () => { + it('fetches the manifest once however many callers ask', async () => { + const first = runtimeManifestRequest() + const second = runtimeManifestRequest() + + expect(second).toBe(first) + expect(axios.get).toHaveBeenCalledTimes(1) + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/api/manifest') + expect((await second).data).toEqual({ $schema: 'x' }) + }) + + it('hands a failure to every caller without asking again', async () => { + axios.get.mockRejectedValue(new Error('down')) + + await expect(runtimeManifestRequest()).rejects.toThrow('down') + await expect(runtimeManifestRequest()).rejects.toThrow('down') + expect(axios.get).toHaveBeenCalledTimes(1) + }) +}) + +/** + * @spec openspec/changes/archive/2026-11-25-manifest-cached-per-user/tasks.md#task-4 + */ +describe('runtimeManifestRequest with a kept manifest', () => { + it('answers from the manifest the page carries, without asking', async () => { + takeRuntimeManifest.mockReturnValue({ $schema: 'kept', pages: [] }) + + const response = await runtimeManifestRequest() + + expect(axios.get).not.toHaveBeenCalled() + expect(response).toEqual({ status: 200, data: { $schema: 'kept', pages: [] } }) + }) +}) diff --git a/src/utils/__tests__/serverStamp.spec.js b/src/utils/__tests__/serverStamp.spec.js new file mode 100644 index 000000000..1d0791465 --- /dev/null +++ b/src/utils/__tests__/serverStamp.spec.js @@ -0,0 +1,26 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + */ + +import { describe, expect, it } from 'vitest' +import { parseServerStamp } from '../serverStamp.js' + +describe('parseServerStamp', () => { + it('reads a bare server stamp as UTC', () => { + expect(parseServerStamp('2026-11-23 08:00:00')?.toISOString()).toBe('2026-11-23T08:00:00.000Z') + expect(parseServerStamp('2026-11-23T08:00')?.toISOString()).toBe('2026-11-23T08:00:00.000Z') + }) + + it('keeps an explicit offset or Z as written', () => { + expect(parseServerStamp('2026-11-23T09:00:00+01:00')?.toISOString()).toBe('2026-11-23T08:00:00.000Z') + expect(parseServerStamp('2026-11-23T08:00:00Z')?.toISOString()).toBe('2026-11-23T08:00:00.000Z') + }) + + it('answers null for nothing or something unreadable', () => { + expect(parseServerStamp(null)).toBeNull() + expect(parseServerStamp(undefined)).toBeNull() + expect(parseServerStamp('')).toBeNull() + expect(parseServerStamp('never')).toBeNull() + }) +}) diff --git a/src/utils/__tests__/tileAvailability.spec.js b/src/utils/__tests__/tileAvailability.spec.js new file mode 100644 index 000000000..a0948bd4c --- /dev/null +++ b/src/utils/__tests__/tileAvailability.spec.js @@ -0,0 +1,41 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The line under the tile form's Check availability switch (REQ-TILE-042). + * + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-the-last-availability-check-in-the-form-req-tile-042 + */ + +import { describe, expect, it } from 'vitest' +import { lastCheckLine } from '../tileAvailability.js' + +const t = (_app, key, vars) => key.replace(/\{(\w+)\}/g, (match, name) => (vars && name in vars ? String(vars[name]) : match)) +const now = new Date(2026, 10, 25, 14, 5) + +describe('lastCheckLine', () => { + it('reads a reachable tile checked today with the clock time', () => { + const at = new Date(2026, 10, 25, 10, 40) + expect(lastCheckLine({ state: 'online', checkedAt: at.toISOString() }, now, t)) + .toBe('Reachable at the last check, today 10:40') + }) + + it('counts a slow answer as reachable', () => { + const at = new Date(2026, 10, 25, 9, 5) + expect(lastCheckLine({ state: 'degraded', checkedAt: at.toISOString() }, now, t)) + .toBe('Reachable at the last check, today 09:05') + }) + + it('reads an unreachable tile, and names the date of an older check', () => { + const at = new Date(2026, 10, 24, 23, 59) + expect(lastCheckLine({ state: 'offline', checkedAt: at.toISOString() }, now, t)) + .toBe(`Not reachable at the last check, ${at.toLocaleDateString()} 23:59`) + }) + + it('says not checked yet without a reading, a state or a usable time', () => { + expect(lastCheckLine(null, now, t)).toBe('Not checked yet') + expect(lastCheckLine({ state: null, checkedAt: null }, now, t)).toBe('Not checked yet') + expect(lastCheckLine({ state: 'online', checkedAt: 'not a time' }, now, t)).toBe('Not checked yet') + expect(lastCheckLine({ state: 'unknown', checkedAt: now.toISOString() }, now, t)).toBe('Not checked yet') + }) +}) diff --git a/src/utils/__tests__/tileColour.spec.js b/src/utils/__tests__/tileColour.spec.js new file mode 100644 index 000000000..156d38e15 --- /dev/null +++ b/src/utils/__tests__/tileColour.spec.js @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The theme colours of a tile (icon-only-app-tiles REQ-ICT-004). + */ + +import { describe, expect, it } from 'vitest' +import { isColourToken, TILE_COLOUR_TOKENS, tileBackground } from '../tileColour.js' + +describe('tileBackground', () => { + it('renders through a known token with its fallback', () => { + expect(tileBackground({ backgroundColor: '#123456' }, { colourToken: '--sc-primary' })).toBe('var(--sc-primary, #3669a5)') + }) + + it('falls back to the primary colour for a token the palette does not know', () => { + expect(tileBackground(null, { colourToken: '--sc-brand-new' })).toBe('var(--sc-brand-new, var(--sc-primary, #3669a5))') + }) + + it('keeps a hex colour, and uses the primary colour without one', () => { + expect(tileBackground({ backgroundColor: '#123456' }, {})).toBe('#123456') + expect(tileBackground({ backgroundColor: '#123456' }, { colourToken: 'red' })).toBe('#123456') + expect(tileBackground(null, null)).toBe('var(--sc-primary, #3669a5)') + }) + + it('has eight tokens', () => { + expect(TILE_COLOUR_TOKENS.map((entry) => entry.token)).toHaveLength(8) + expect(isColourToken('--sc-work-ink')).toBe(true) + expect(isColourToken('--other')).toBe(false) + }) +}) diff --git a/src/utils/__tests__/tileLaunch.spec.js b/src/utils/__tests__/tileLaunch.spec.js new file mode 100644 index 000000000..1e4f0fb86 --- /dev/null +++ b/src/utils/__tests__/tileLaunch.spec.js @@ -0,0 +1,69 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `tileLaunch.js`: the content a launch tile is saved + * with, the editor fields read back from it, and the link and target the + * browser follows per type (launcher-tile-launch-types D2). + */ + +import { describe, expect, it } from 'vitest' +import { + DEFAULT_RDP_PORT, + isLaunchType, + launchContent, + launchFields, + launchHref, + launchTarget, +} from '../tileLaunch.js' + +const generateUrl = (path) => '/nc' + path + +describe('tileLaunch', () => { + it('knows the three launch types', () => { + expect(['program', 'remote-desktop', 'sso'].map(isLaunchType)).toEqual([true, true, true]) + expect(['url', 'app', 'internal', undefined].map(isLaunchType)).toEqual([false, false, false, false]) + expect(DEFAULT_RDP_PORT).toBe(3389) + }) + + it('saves a gateway tile with its address only', () => { + expect(launchContent({ linkType: 'remote-desktop', remoteMode: 'gateway', remoteUrl: ' https://desktop.gemeente.nl/ ', rdpHost: 'stale' })) + .toEqual({ remote: { mode: 'gateway', url: 'https://desktop.gemeente.nl/' } }) + }) + + it('saves an RDP tile with the fields that were filled in', () => { + expect(launchContent({ linkType: 'remote-desktop', remoteMode: 'rdp', rdpHost: ' rds01.gemeente.local ', rdpPort: '', rdpRemoteApp: '||Belastingen', rdpGateway: 'rdgw.gemeente.nl' })) + .toEqual({ remote: { mode: 'rdp', host: 'rds01.gemeente.local', remoteApp: '||Belastingen', gateway: 'rdgw.gemeente.nl' } }) + expect(launchContent({ linkType: 'remote-desktop', remoteMode: 'rdp', rdpHost: 'pc12', rdpPort: '3390' })) + .toEqual({ remote: { mode: 'rdp', host: 'pc12', port: '3390' } }) + }) + + it('saves an sso tile with its template and app id, and other types with nothing', () => { + expect(launchContent({ linkType: 'sso', ssoTemplate: 'entra', ssoAppId: ' a1b2c3 ' })).toEqual({ sso: { template: 'entra', appId: 'a1b2c3' } }) + expect(launchContent({ linkType: 'program', linkValue: 'ms-word:x' })).toEqual({}) + expect(launchContent({ linkType: 'url' })).toEqual({}) + }) + + it('reads the editor fields back from the content', () => { + expect(launchFields({ remote: { mode: 'rdp', host: 'pc12', port: 3390, remoteApp: '||App', gateway: 'gw' }, sso: { template: 'entra', appId: 'a1' } })) + .toEqual({ remoteMode: 'rdp', remoteUrl: '', rdpHost: 'pc12', rdpPort: '3390', rdpRemoteApp: '||App', rdpGateway: 'gw', ssoTemplate: 'entra', ssoAppId: 'a1' }) + expect(launchFields(null)).toEqual({ remoteMode: 'gateway', remoteUrl: '', rdpHost: '', rdpPort: '', rdpRemoteApp: '', rdpGateway: '', ssoTemplate: '', ssoAppId: '' }) + }) + + it('links each launch type as design D2 says', () => { + expect(launchHref({ linkType: 'program', linkValue: 'ms-word:ofe' }, null, 7, generateUrl)).toBe('ms-word:ofe') + expect(launchHref({ linkType: 'sso', linkValue: 'https://idp/a1' }, { sso: {} }, 7, generateUrl)).toBe('https://idp/a1') + expect(launchHref({ linkType: 'remote-desktop', linkValue: 'https://gw/' }, { remote: { mode: 'gateway' } }, 7, generateUrl)).toBe('https://gw/') + expect(launchHref({ linkType: 'remote-desktop', linkValue: '' }, { remote: { mode: 'rdp' } }, 7, generateUrl)).toBe('/nc/apps/launchpad/api/tiles/7/rdp') + expect(launchHref({ linkType: 'remote-desktop', linkValue: '' }, { remote: { mode: 'rdp' } }, null, generateUrl)).toBeNull() + expect(launchHref({ linkType: 'url', linkValue: 'https://example.org' }, null, 7, generateUrl)).toBeNull() + }) + + it('opens gateway and sso tiles in a new tab, program and RDP tiles in place', () => { + expect(launchTarget({ linkType: 'sso' }, null)).toBe('_blank') + expect(launchTarget({ linkType: 'remote-desktop' }, { remote: { mode: 'gateway' } })).toBe('_blank') + expect(launchTarget({ linkType: 'remote-desktop' }, { remote: { mode: 'rdp' } })).toBe('_self') + expect(launchTarget({ linkType: 'program' }, null)).toBe('_self') + expect(launchTarget({ linkType: 'url' }, null)).toBeNull() + }) +}) diff --git a/src/utils/__tests__/tileLinkTarget.spec.js b/src/utils/__tests__/tileLinkTarget.spec.js new file mode 100644 index 000000000..df4c919b5 --- /dev/null +++ b/src/utils/__tests__/tileLinkTarget.spec.js @@ -0,0 +1,36 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * How a tile opens: the tile's choice, the dashboard default, then the + * link-type rule (launcher-tile-open-behaviour D2). + * + * @spec openspec/changes/archive/2026-11-19-launcher-tile-open-behaviour/specs/tiles/spec.md + */ + +import { describe, expect, it } from 'vitest' +import { isLinkTarget, isSameOrigin, LINK_TARGETS, resolveLinkTarget } from '../tileLinkTarget.js' + +describe('tileLinkTarget', () => { + it('knows the three targets', () => { + expect(LINK_TARGETS).toEqual(['same-tab', 'new-tab', 'side-panel']) + expect(LINK_TARGETS.map(isLinkTarget)).toEqual([true, true, true]) + expect(['', null, undefined, '_blank'].map(isLinkTarget)).toEqual([false, false, false, false]) + }) + + it('resolves the tile first, then the dashboard, then the link type', () => { + expect(resolveLinkTarget('side-panel', 'same-tab', 'url')).toBe('side-panel') + expect(resolveLinkTarget(null, 'new-tab', 'app')).toBe('new-tab') + expect(resolveLinkTarget('', 'bogus', 'url')).toBe('new-tab') + expect(resolveLinkTarget(null, null, 'app')).toBe('same-tab') + expect(resolveLinkTarget(undefined, undefined, 'internal')).toBe('same-tab') + }) + + it('tells an address on this Nextcloud from an outside one', () => { + const origin = 'https://cloud.example' + expect(isSameOrigin('/nc/apps/files', origin)).toBe(true) + expect(isSameOrigin('https://cloud.example/apps/deck', origin)).toBe(true) + expect(isSameOrigin('https://other.example/', origin)).toBe(false) + expect(isSameOrigin('http://[bad', origin)).toBe(false) + }) +}) diff --git a/src/utils/__tests__/tileSort.spec.js b/src/utils/__tests__/tileSort.spec.js new file mode 100644 index 000000000..e2b055640 --- /dev/null +++ b/src/utils/__tests__/tileSort.spec.js @@ -0,0 +1,144 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `tileSort.js` (launcher-tile-sorting): every sort + * mode with its tie rules, the once-per-load shuffle, the row-by-row reflow, + * and the browser-only usage counts with storage available and blocked. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + __resetTileSortForTest, + childTitle, + forgetTileUse, + normaliseSortMode, + readTileUse, + recordTileUse, + reflowChildren, + sortChildren, + TILE_USE_KEY, +} from '../tileSort.js' + +const tile = (id, title, w = 1, h = 1) => ({ id, type: 'link', content: { title }, gridX: 0, gridY: 0, gridWidth: w, gridHeight: h }) +const titles = (list) => list.map(childTitle) + +// "Zaaksysteem", "Agenda" and "Mail", placed in that order. +const applicaties = () => [tile(1, 'Zaaksysteem'), tile(2, 'Agenda'), tile(3, 'Mail')] + +beforeEach(() => { + localStorage.clear() + __resetTileSortForTest() +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('sortChildren', () => { + it('keeps the stored order by hand, and for an unknown mode', () => { + expect(titles(sortChildren(applicaties(), 'manual'))).toEqual(['Zaaksysteem', 'Agenda', 'Mail']) + expect(titles(sortChildren(applicaties(), 'by-colour'))).toEqual(['Zaaksysteem', 'Agenda', 'Mail']) + expect(normaliseSortMode('by-colour')).toBe('manual') + expect(normaliseSortMode('most-used')).toBe('most-used') + }) + + it('sorts alphabetically in the viewer\'s locale, case and accents aside, numbers numerically', () => { + expect(titles(sortChildren(applicaties(), 'alphabetical', { locale: 'nl' }))).toEqual(['Agenda', 'Mail', 'Zaaksysteem']) + const mixed = [tile(1, 'zaak 10'), tile(2, 'Émail'), tile(3, 'zaak 9'), tile(4, 'agenda')] + expect(titles(sortChildren(mixed, 'alphabetical', { locale: 'nl' }))).toEqual(['agenda', 'Émail', 'zaak 9', 'zaak 10']) + }) + + it('puts the most used first, equal counts and unused tiles alphabetically', () => { + const use = { 1: { count: 3, lastUsedAt: 10 }, 3: { count: 1, lastUsedAt: 50 } } + expect(titles(sortChildren(applicaties(), 'most-used', { use, locale: 'nl' }))).toEqual(['Zaaksysteem', 'Mail', 'Agenda']) + expect(titles(sortChildren(applicaties(), 'most-used', { use: {}, locale: 'nl' }))).toEqual(['Agenda', 'Mail', 'Zaaksysteem']) + }) + + it('puts the last used first', () => { + const use = { 1: { count: 3, lastUsedAt: 10 }, 3: { count: 1, lastUsedAt: 50 } } + expect(titles(sortChildren(applicaties(), 'last-used', { use, locale: 'nl' }))).toEqual(['Mail', 'Zaaksysteem', 'Agenda']) + }) + + it('shuffles once per page load and keeps that order', () => { + const draws = [0.9, 0.1, 0.5, 0.3, 0.7, 0.2] + vi.spyOn(Math, 'random').mockImplementation(() => draws.shift()) + + const first = titles(sortChildren(applicaties(), 'random')) + expect(first).toEqual(['Agenda', 'Mail', 'Zaaksysteem']) + expect(titles(sortChildren(applicaties(), 'random'))).toEqual(first) + + __resetTileSortForTest() + expect(titles(sortChildren(applicaties(), 'random'))).toEqual(['Mail', 'Zaaksysteem', 'Agenda']) + }) + + it('never changes the array it is given', () => { + const children = applicaties() + sortChildren(children, 'alphabetical') + expect(titles(children)).toEqual(['Zaaksysteem', 'Agenda', 'Mail']) + }) +}) + +describe('childTitle', () => { + it('reads the title, a label, or a tile title, in that order', () => { + expect(childTitle({ content: { title: ' Mail ' } })).toBe('Mail') + expect(childTitle({ content: { label: 'Agenda' } })).toBe('Agenda') + expect(childTitle({ tileTitle: 'Zaaksysteem' })).toBe('Zaaksysteem') + expect(childTitle({})).toBe('') + }) +}) + +describe('reflowChildren', () => { + it('fills rows from the top left, keeping each size and wrapping when a tile does not fit', () => { + const placed = reflowChildren([tile(1, 'a', 2, 1), tile(2, 'b', 1, 2), tile(3, 'c', 2, 1), tile(4, 'd', 4, 1)], 4) + expect(placed.map((c) => [c.gridX, c.gridY, c.gridWidth, c.gridHeight])).toEqual([ + [0, 0, 2, 1], + [2, 0, 1, 2], + [0, 2, 2, 1], + [0, 3, 4, 1], + ]) + }) + + it('treats a missing size as two by two, and caps a width at the grid', () => { + const placed = reflowChildren([{ id: 1 }, { id: 2, gridWidth: 9 }], 4) + expect(placed.map((c) => [c.gridX, c.gridY])).toEqual([[0, 0], [0, 2]]) + }) +}) + +describe('usage in this browser', () => { + it('counts uses and remembers the last one', () => { + recordTileUse(7, 1000) + recordTileUse(7, 2000) + recordTileUse('9', 1500) + expect(readTileUse()).toEqual({ 7: { count: 2, lastUsedAt: 2000 }, 9: { count: 1, lastUsedAt: 1500 } }) + recordTileUse(null) + expect(Object.keys(readTileUse())).toEqual(['7', '9']) + }) + + it('forgets the given placements only', () => { + recordTileUse(7, 1000) + recordTileUse(9, 1000) + forgetTileUse([7, 'nope']) + expect(Object.keys(readTileUse())).toEqual(['9']) + }) + + it('reads nothing from unusable storage contents', () => { + localStorage.setItem(TILE_USE_KEY, '{broken') + expect(readTileUse()).toEqual({}) + localStorage.setItem(TILE_USE_KEY, '[1,2]') + expect(readTileUse()).toEqual({}) + }) + + it('does not throw when storage is blocked', () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new Error('SecurityError') + }) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('QuotaExceededError') + }) + + expect(() => recordTileUse(7)).not.toThrow() + expect(() => forgetTileUse([7])).not.toThrow() + expect(readTileUse()).toEqual({}) + }) +}) diff --git a/src/utils/__tests__/urlAllowList.spec.js b/src/utils/__tests__/urlAllowList.spec.js new file mode 100644 index 000000000..654875827 --- /dev/null +++ b/src/utils/__tests__/urlAllowList.spec.js @@ -0,0 +1,89 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The client-side URL checks of the iframe and live tile forms keep refusing + * what they refused before: hosts the server's allow-list rejects, schemes + * other than http(s) (`javascript:`, `data:`, `ftp:`), and malformed URLs. + */ + +import { describe, expect, it, vi } from 'vitest' +import { allowListMessage, urlFieldErrors } from '../urlAllowList.js' + +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) + +const INVALID = 'Enter a valid http(s) URL.' + +describe('urlFieldErrors', () => { + it.each([ + ['javascript:alert(1)'], + ['JavaScript:alert(document.cookie)'], + ['data:text/html,'], + ['data:image/svg+xml;base64,PHN2Zz4='], + ['ftp://files.example'], + ['file:///etc/passwd'], + ['vbscript:msgbox(1)'], + ['//ok.example'], + ['ok.example'], + ['https://'], + ['http:/one-slash.example'], + [' javascript:alert(1) '], + ['javascript:alert(1)//https://ok.example'], + ['data:text/html,https://ok.example'], + ])('refuses %s', (url) => { + expect(urlFieldErrors(url, '')).toEqual([INVALID]) + }) + + it.each([[''], [' '], [null], [undefined], [42]])( + 'requires a URL (%s)', + (url) => { + expect(urlFieldErrors(url, '')).toEqual(['URL is required']) + }, + ) + + it.each([ + ['https://ok.example'], + ['HTTP://OK.EXAMPLE/x'], + [' https://ok.example '], + ])('accepts the http(s) URL %s', (url) => { + expect(urlFieldErrors(url, '')).toEqual([]) + }) + + it('keeps refusing a URL the allow-list check rejected', () => { + expect( + urlFieldErrors('https://evil.example', 'Not on the allow-list'), + ).toEqual(['Not on the allow-list']) + expect( + urlFieldErrors('javascript:alert(1)', 'Not on the allow-list'), + ).toEqual([INVALID, 'Not on the allow-list']) + }) +}) + +describe('allowListMessage', () => { + it('names a host the server does not allow', () => { + expect( + allowListMessage({ valid: false, errors: ['host_not_allowed'] }), + ).toBe('This host is not on the allow-list.') + expect( + allowListMessage({ + valid: false, + errors: ['invalid_url', 'host_not_allowed'], + }), + ).toBe('This host is not on the allow-list.') + }) + + it('names a URL the server finds malformed', () => { + expect(allowListMessage({ valid: false, errors: ['invalid_url'] })).toBe( + INVALID, + ) + }) + + it('raises nothing for an allowed URL', () => { + expect(allowListMessage({ valid: true, errors: [] })).toBe('') + }) + + it('raises nothing unless the answer says valid is false', () => { + expect(allowListMessage({ errors: ['host_not_allowed'] })).toBe('') + expect(allowListMessage({ valid: null, errors: ['invalid_url'] })).toBe('') + }) +}) diff --git a/src/utils/__tests__/visibilitySentence.spec.js b/src/utils/__tests__/visibilitySentence.spec.js new file mode 100644 index 000000000..e43bb6f52 --- /dev/null +++ b/src/utils/__tests__/visibilitySentence.spec.js @@ -0,0 +1,143 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The words of "Who sees this widget?" (board LpZichtbaarheid): each rule's + * kind and value, and the View as sentence for a person who does and who + * does not see the widget (conditional-visibility-editor REQ-CVUI-006). + * + * @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-rules-dialog-as-lpzichtbaarheid-draws-it-req-cvui-006 + */ + +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', () => ({ + t: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => String(vars[k])), +})) + +import { + dayRanges, + decidingRules, + formatMoment, + joinList, + ruleKindLabel, + ruleValue, + visibilitySentence, +} from '../visibilitySentence.js' + +const KCC = { id: 1, ruleType: 'group', ruleConfig: { groups: ['kcc'] }, isInclude: true } +const OFFICE_HOURS = { + id: 2, + ruleType: 'time', + ruleConfig: { startTime: '08:00', endTime: '17:00', days: ['mon', 'tue', 'wed', 'thu', 'fri'] }, + isInclude: true, +} +const HOLIDAY = { id: 3, ruleType: 'date', ruleConfig: { startDate: '2026-12-24', endDate: '2026-12-26' }, isInclude: false } +const GROUP_NAMES = { kcc: 'KCC' } +const TUESDAY = 'Tuesday 13 October 10:00' + +describe('the View as sentence (scenario: View as Sanne)', () => { + it('says that Sanne sees the widget, because Sanne is in KCC and the moment is within the times', () => { + expect(visibilitySentence({ + name: 'Sanne de Vries', + moment: TUESDAY, + rules: [KCC, OFFICE_HOURS], + result: { visible: true, matchedIncludeRuleIds: [1, 2], matchedExcludeRuleIds: [] }, + groupNames: GROUP_NAMES, + })).toBe('Sanne de Vries sees this widget, because Sanne de Vries is in KCC and Tuesday 13 October 10:00 is within the times.') + }) + + it('says that a person outside KCC does not see the widget when all rules must match', () => { + expect(visibilitySentence({ + name: 'Piet Jansen', + moment: TUESDAY, + rules: [KCC, OFFICE_HOURS], + result: { visible: false, matchedIncludeRuleIds: [2], matchedExcludeRuleIds: [] }, + groupNames: GROUP_NAMES, + })).toBe('Piet Jansen does not see this widget, because Piet Jansen is not in KCC.') + }) + + it('names every include rule when one rule is enough and none matches', () => { + expect(visibilitySentence({ + name: 'Piet Jansen', + moment: 'Saturday 17 October 10:00', + rules: [KCC, OFFICE_HOURS], + result: { visible: false, matchedIncludeRuleIds: [], matchedExcludeRuleIds: [] }, + groupNames: GROUP_NAMES, + })).toBe('Piet Jansen does not see this widget, because Piet Jansen is not in KCC and Saturday 17 October 10:00 is outside the times.') + }) + + it('names the hide rule that matched', () => { + expect(visibilitySentence({ + name: 'Sanne de Vries', + moment: 'Thursday 24 December 10:00', + rules: [KCC, HOLIDAY], + result: { visible: false, matchedIncludeRuleIds: [1], matchedExcludeRuleIds: [3] }, + })).toBe('Sanne de Vries does not see this widget, because Thursday 24 December 10:00 is within the period.') + }) + + it('says that no rule limits a widget without include rules, and nothing without a result', () => { + expect(visibilitySentence({ name: 'Sanne de Vries', moment: TUESDAY, rules: [], result: { visible: true } })) + .toBe('Sanne de Vries sees this widget: no rule limits who sees it.') + expect(visibilitySentence({ name: 'Sanne de Vries', moment: TUESDAY, rules: [], result: { visible: false } })) + .toBe('') + expect(visibilitySentence({ name: 'Sanne de Vries', moment: TUESDAY, rules: [], result: null })).toBe('') + }) + + it('says a profile field matches or not, and joins several groups with or', () => { + const field = { id: 4, ruleType: 'attribute', ruleConfig: { attribute: 'department', operator: 'equals', value: 'IT' }, isInclude: true } + const groups = { id: 5, ruleType: 'group', ruleConfig: { groups: ['kcc', 'sales', 'board'] }, isInclude: true } + expect(visibilitySentence({ + name: 'Sanne de Vries', + moment: TUESDAY, + rules: [field, groups], + result: { visible: false, matchedIncludeRuleIds: [], matchedExcludeRuleIds: [] }, + groupNames: GROUP_NAMES, + })).toBe('Sanne de Vries does not see this widget, because the profile field department of Sanne de Vries does not match and Sanne de Vries is not in KCC, sales or board.') + }) +}) + +describe('the rule cards', () => { + it('names each kind', () => { + expect([KCC, OFFICE_HOURS, HOLIDAY, { ruleType: 'attribute' }, { ruleType: 'weather' }].map(ruleKindLabel)) + .toEqual(['Groups', 'Times', 'Period', 'Profile field', '']) + }) + + it('shows each value', () => { + expect(ruleValue(OFFICE_HOURS)).toBe('Mon–Fri 08:00–17:00') + expect(ruleValue({ ruleType: 'time', ruleConfig: { startTime: '09:00', endTime: '12:00' } })).toBe('09:00–12:00') + expect(ruleValue(HOLIDAY)).toBe('2026-12-24 – 2026-12-26') + expect(ruleValue({ ruleType: 'date', ruleConfig: { startDate: '2026-12-01' } })).toBe(`2026-12-01 – ${'\u2026'}`) + expect(ruleValue({ ruleType: 'attribute', ruleConfig: { attribute: 'language', operator: 'equals', value: 'nl' } })).toBe('language Equals nl') + expect(ruleValue(KCC)).toBe('kcc') + expect(ruleValue({ ruleType: 'weather' })).toBe('') + }) + + it('writes three or more days in a row as a range', () => { + expect(dayRanges(['mon', 'tue', 'wed', 'thu', 'fri'])).toBe('Mon–Fri') + expect(dayRanges(['sat', 'mon', 'sun'])).toBe('Mon, Sat, Sun') + expect(dayRanges([])).toBe('') + }) +}) + +describe('helpers', () => { + it('joins lists with and or or', () => { + expect(joinList([])).toBe('') + expect(joinList(['a'])).toBe('a') + expect(joinList(['a', 'b', 'c'])).toBe('a, b and c') + expect(joinList(['a', 'b'], true)).toBe('a or b') + }) + + it('says a moment as weekday, day, month and time', () => { + expect(formatMoment(new Date(2026, 9, 13, 10, 0), 'en-GB')).toBe('Tuesday 13 October 10:00') + expect(formatMoment('not a date')).toBe('') + }) + + it('picks the hide rules first, then the include rules that decided', () => { + const rules = [KCC, OFFICE_HOURS, HOLIDAY] + expect(decidingRules(rules, { visible: false, matchedIncludeRuleIds: [1, 2], matchedExcludeRuleIds: [3] })) + .toEqual([{ rule: HOLIDAY, matched: true }]) + expect(decidingRules(rules, { visible: true, matchedIncludeRuleIds: [2], matchedExcludeRuleIds: [] })) + .toEqual([{ rule: OFFICE_HOURS, matched: true }]) + }) +}) diff --git a/src/utils/__tests__/widgetBusConsumption.spec.js b/src/utils/__tests__/widgetBusConsumption.spec.js new file mode 100644 index 000000000..4a4d3192d --- /dev/null +++ b/src/utils/__tests__/widgetBusConsumption.spec.js @@ -0,0 +1,82 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * widgetBusConsumption: a placement's bus declarations and the data-source + * filter the bus's clauses make for it (drill-down-cross-widget-filter + * tasks 8 and 10; REQ-CWF-002, REQ-CWF-008). + */ + +import { describe, expect, it } from 'vitest' +import { busDeclarationsOf, consumedFilter, publishedClauses, withBusFilter } from '../widgetBusConsumption.js' + +describe('busDeclarationsOf', () => { + it('reads the declarations from the content, else from content.props, strings as dimensions', () => { + expect(busDeclarationsOf({ consumes: ['gemeenteCode', { dimension: 'wijkCode', field: 'wijk' }, '', 4] })).toEqual({ + publishes: [], + consumes: [{ dimension: 'gemeenteCode' }, { dimension: 'wijkCode', field: 'wijk' }], + }) + expect(busDeclarationsOf({ props: { publishes: [{ dimension: 'gemeenteCode', fromField: 'gemeente' }] } })).toEqual({ + publishes: [{ dimension: 'gemeenteCode', fromField: 'gemeente' }], + consumes: [], + }) + expect(busDeclarationsOf(null)).toEqual({ publishes: [], consumes: [] }) + }) +}) + +describe('consumedFilter', () => { + const clauses = [ + { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355' }, + { dimension: 'status', operator: 'in', value: ['open', 'paused'] }, + { dimension: 'period.month', operator: 'between', value: ['2026-01', '2026-03'] }, + { dimension: 'wijkCode', operator: 'eq', value: 'WK035501' }, + ] + + it('filters on the consumed dimensions, on their declared field', () => { + expect(consumedFilter(clauses, [{ dimension: 'gemeenteCode', field: 'gemeente' }, { dimension: 'status' }])).toEqual({ + gemeente: 'GM0355', + status: ['open', 'paused'], + }) + }) + + it('leaves out dimensions it does not consume and operators a data source cannot take', () => { + expect(consumedFilter(clauses, [{ dimension: 'period.month' }, { dimension: 'buurtCode' }])).toEqual({}) + expect(consumedFilter([{ dimension: 'status', operator: 'in', value: 'open' }], ['status'])).toEqual({}) + }) +}) + +describe('withBusFilter', () => { + it('adds the bus filter over the declared one', () => { + const source = { schema: 'zaak', filter: { type: 'bezwaar', gemeente: 'GM0001' }, groupBy: { field: 'status' } } + + expect(withBusFilter(source, { gemeente: 'GM0355' })).toEqual({ + schema: 'zaak', + filter: { type: 'bezwaar', gemeente: 'GM0355' }, + groupBy: { field: 'status' }, + }) + expect(source.filter).toEqual({ type: 'bezwaar', gemeente: 'GM0001' }) + }) + + it('returns the same source when there is nothing to add', () => { + const source = { schema: 'zaak' } + expect(withBusFilter(source, {})).toBe(source) + expect(withBusFilter(null, { a: 1 })).toBeNull() + }) +}) + +describe('publishedClauses (REQ-CWF-001)', () => { + it('publishes a widget click for each dimension published from the picked field', () => { + const publishes = [{ dimension: 'gemeenteCode', fromField: 'gemeente' }, { dimension: 'status', fromField: 'status' }, 'anyField'] + expect(publishedClauses(publishes, { field: 'gemeente', value: 'GM0355' }, '7')).toEqual([ + { dimension: 'gemeenteCode', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: '7' }, + { dimension: 'anyField', operator: 'eq', value: 'GM0355', source: 'widgetClick', sourceWidgetId: '7' }, + ]) + }) + + it('publishes nothing for an empty pick', () => { + const publishes = [{ dimension: 'gemeenteCode' }] + expect(publishedClauses(publishes, null, '7')).toEqual([]) + expect(publishedClauses(publishes, { field: 'gemeente', value: '' }, '7')).toEqual([]) + expect(publishedClauses(publishes, { field: 'gemeente', value: null }, '7')).toEqual([]) + }) +}) diff --git a/src/utils/__tests__/widgetBusDeclarations.spec.js b/src/utils/__tests__/widgetBusDeclarations.spec.js new file mode 100644 index 000000000..b47ac9123 --- /dev/null +++ b/src/utils/__tests__/widgetBusDeclarations.spec.js @@ -0,0 +1,64 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * validateBusDeclarations: a widget consuming a dimension no hierarchy on the + * dashboard has gets a warning and stays out of the bus; one publishing from + * a field its data lacks gets an error and stays out; matching declarations + * pass (drill-down-cross-widget-filter task 21; REQ-CWF-008). + */ + +import { describe, expect, it } from 'vitest' +import { validateBusDeclarations } from '../widgetBusDeclarations.js' + +const HIERARCHIES = [{ + id: 'nl-administrative', + levels: [ + { dimension: 'provincieCode' }, + { dimension: 'gemeenteCode', parentDimension: 'provincieCode' }, + ], +}] + +describe('validateBusDeclarations', () => { + it('REQ-CWF-008: a consumed dimension outside every hierarchy warns and keeps the widget out', () => { + const result = validateBusDeclarations({ widget: { consumes: ['wijkCode'] }, hierarchies: HIERARCHIES }) + + expect(result.participates).toBe(false) + expect(result.findings).toEqual([{ level: 'warning', code: 'consumes-unknown-dimension', dimension: 'wijkCode' }]) + }) + + it('REQ-CWF-008: publishing from a field the data lacks is an error and keeps the widget out', () => { + const result = validateBusDeclarations({ + widget: { publishes: [{ dimension: 'gemeenteCode', operator: 'eq', fromField: 'missingField' }] }, + hierarchies: HIERARCHIES, + sampleRow: { gemeente: 'GM0355', inwoners: 65000 }, + }) + + expect(result.participates).toBe(false) + expect(result.findings).toEqual([{ level: 'error', code: 'publishes-missing-field', dimension: 'gemeenteCode', field: 'missingField' }]) + }) + + it('REQ-CWF-008: matching declarations pass', () => { + const result = validateBusDeclarations({ + widget: { + consumes: [{ dimension: 'provincieCode', operator: 'eq', intoFilter: 'provincie' }, 'gemeenteCode'], + publishes: [{ dimension: 'gemeenteCode', fromField: 'code' }, { dimension: 'provincieCode' }], + }, + hierarchies: HIERARCHIES, + sampleRow: { code: 'GM0355', provincieCode: 'PV26' }, + }) + + expect(result).toEqual({ participates: true, findings: [] }) + }) + + it('without a sample row the published fields are not judged', () => { + const result = validateBusDeclarations({ widget: { publishes: [{ dimension: 'gemeenteCode', fromField: 'x' }] }, hierarchies: HIERARCHIES }) + + expect(result.participates).toBe(true) + }) + + it('a widget without declarations, or with malformed ones, passes and declares nothing', () => { + expect(validateBusDeclarations({ widget: {}, hierarchies: [] })).toEqual({ participates: true, findings: [] }) + expect(validateBusDeclarations({ widget: { consumes: [null, 7, { dimension: '' }] }, hierarchies: null }).participates).toBe(true) + }) +}) diff --git a/src/utils/__tests__/widgetBusNotices.spec.js b/src/utils/__tests__/widgetBusNotices.spec.js new file mode 100644 index 000000000..abd072e63 --- /dev/null +++ b/src/utils/__tests__/widgetBusNotices.spec.js @@ -0,0 +1,38 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The widget dialog warns about filter declarations that do not fit the + * dashboard (drill-down-cross-widget-filter task 9, REQ-CWF-008). + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-9 + */ + +import { describe, expect, it, vi } from 'vitest' +import { busNotices } from '../widgetBusNotices.js' + +vi.mock('@nextcloud/l10n', () => ({ + translate: (...args) => args[1].replace(/\{(\w+)\}/g, (_m, key) => (args[2] || {})[key]), +})) + +const HIERARCHIES = [{ id: 'nl', levels: [{ dimension: 'gemeenteCode' }, { dimension: 'wijkCode' }] }] + +describe('busNotices', () => { + it('warns about a consumed dimension no hierarchy publishes', () => { + expect(busNotices({ consumes: ['buurtCode'] }, HIERARCHIES)).toEqual([{ + id: 'consumes-unknown-dimension:buurtCode', + type: 'warning', + text: 'This widget consumes buurtCode, but no hierarchy on this dashboard publishes it. It shows its data unfiltered.', + }]) + }) + + it('says nothing for a widget that fits or declares nothing', () => { + expect(busNotices({ consumes: ['wijkCode'], publishes: [{ dimension: 'gemeenteCode', fromField: 'gemeente' }] }, HIERARCHIES)).toEqual([]) + expect(busNotices({ dataSource: {} }, HIERARCHIES)).toEqual([]) + expect(busNotices(null, [])).toEqual([]) + }) + + it('reads declarations under props too, and treats a dashboard without hierarchies as having none', () => { + expect(busNotices({ props: { consumes: ['gemeenteCode'] } }, undefined)).toHaveLength(1) + }) +}) diff --git a/src/utils/__tests__/widgetContentForms.spec.js b/src/utils/__tests__/widgetContentForms.spec.js new file mode 100644 index 000000000..02d868669 --- /dev/null +++ b/src/utils/__tests__/widgetContentForms.spec.js @@ -0,0 +1,101 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The pure helpers behind the Live data, Image and Calendar content forms + * (widget-content-forms-board-sync: REQ-LIVETILE-020, REQ-IMG-020, REQ-CAL-020). + */ + +import { describe, expect, it } from 'vitest' +import { contentForPeriod, isIcsAddress, periodOf } from '../calendarPeriod.js' +import { describeImageFile, formatBytes, isUploadableImage, MAX_IMAGE_BYTES } from '../imageFile.js' +import { + knownColour, + previewValue, + refreshLabel, + refreshOptions, + suffixToUnit, + unitToSuffix, +} from '../liveTilePreview.js' + +describe('live tile unit', () => { + it('puts a space before a word and none before a symbol', () => { + expect(unitToSuffix('minutes')).toBe(' minutes') + expect(unitToSuffix(' minuten ')).toBe(' minuten') + expect(unitToSuffix('%')).toBe('%') + expect(unitToSuffix('')).toBe('') + expect(unitToSuffix(null)).toBe('') + }) + + it('shows the stored suffix without its space', () => { + expect(suffixToUnit(' minutes')).toBe('minutes') + expect(suffixToUnit(undefined)).toBe('') + }) +}) + +describe('live tile refresh', () => { + it('names whole minutes from five up in minutes, the rest in seconds', () => { + expect(refreshLabel(300)).toBe('Every 5 minutes') + expect(refreshLabel(300, true)).toBe('Refreshes every 5 minutes') + expect(refreshLabel(90)).toBe('Every 90 seconds') + expect(refreshLabel(30, true)).toBe('Refreshes every 30 seconds') + }) + + it('offers the four choices and keeps a stored interval that is not one of them', () => { + expect(refreshOptions(300).map((o) => o.value)).toEqual([300, 900, 1800, 3600]) + expect(refreshOptions(45).map((o) => o.value)).toEqual([45, 300, 900, 1800, 3600]) + expect(refreshOptions(0).map((o) => o.value)).toEqual([300, 900, 1800, 3600]) + }) +}) + +describe('live tile colour and preview', () => { + it('accepts the theme colours only', () => { + expect(knownColour('primary')).toBe('primary') + expect(knownColour('#ff0000')).toBe('') + expect(knownColour(undefined)).toBe('') + }) + + it('shows the reading with prefix and unit, a dash without one', () => { + const format = { prefix: '', suffix: ' minutes', thousands: false } + expect(previewValue({ value: 12 }, format)).toBe('12 minutes') + expect(previewValue(null, format)).toBe('— minutes') + expect(previewValue({ value: 'high' }, { prefix: '> ', suffix: '', thousands: false })).toBe('> high') + expect(previewValue({ value: 1234567 }, { prefix: '', suffix: '', thousands: true })).toBe((1234567).toLocaleString()) + }) +}) + +describe('image file', () => { + it('takes images up to 5 MB', () => { + expect(isUploadableImage({ type: 'image/png', size: 1000 })).toBeNull() + expect(isUploadableImage({ type: 'image/png', size: MAX_IMAGE_BYTES })).toBeNull() + expect(isUploadableImage({ type: 'image/png', size: MAX_IMAGE_BYTES + 1 })).toBe('size') + expect(isUploadableImage({ type: 'application/pdf', size: 10 })).toBe('type') + expect(isUploadableImage(null)).toBe('type') + }) + + it('describes size and dimensions, leaving out what is not known', () => { + expect(formatBytes(512)).toBe('512 B') + expect(formatBytes(820 * 1024)).toBe('820 KB') + expect(formatBytes(1.5 * 1024 * 1024)).toBe('1.5 MB') + expect(describeImageFile({ size: 1.5 * 1024 * 1024, width: 1600, height: 900 })).toBe('1.5 MB · 1600 × 900') + expect(describeImageFile({ size: null, width: null, height: null })).toBe('') + expect(describeImageFile(null)).toBe('') + }) +}) + +describe('calendar period', () => { + it('maps 7 days to the agenda over seven days and Month to the month view', () => { + expect(contentForPeriod('week')).toEqual({ viewMode: 'agenda', daysAhead: 7 }) + expect(contentForPeriod('month')).toEqual({ viewMode: 'month', daysAhead: 31 }) + expect(periodOf({ viewMode: 'month' })).toBe('month') + expect(periodOf({ viewMode: 'week' })).toBe('week') + expect(periodOf(null)).toBe('week') + }) + + it('accepts https ICS addresses only', () => { + expect(isIcsAddress('https://example.com/a.ics')).toBe(true) + expect(isIcsAddress('http://example.com/a.ics')).toBe(false) + expect(isIcsAddress('webcal://example.com')).toBe(false) + expect(isIcsAddress(42)).toBe(false) + }) +}) diff --git a/src/utils/__tests__/widgetPickerCards.spec.js b/src/utils/__tests__/widgetPickerCards.spec.js new file mode 100644 index 000000000..60fdcca0d --- /dev/null +++ b/src/utils/__tests__/widgetPickerCards.spec.js @@ -0,0 +1,134 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The widget picker's cards, kinds and counts (widget-picker-board-sync). + * + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md + */ + +import { describe, expect, it } from 'vitest' +import { countByKind, filterCards, isLegacyWidget, kindLabel, kindOfType, KINDS, pickerCards, roleAllows, sectionLabel, typeLine } from '../widgetPickerCards.js' + +const t = (_app, text) => text + +const INPUT = { + customTypes: [ + { type: 'pie-chart', title: 'Pie chart' }, + { type: 'graph', title: 'Graph' }, + { type: 'clock', title: 'Clock' }, + { type: 'iframe', title: 'Embedded page' }, + { type: 'people', title: 'People' }, + { type: 'container', title: 'Container' }, + { type: 'work-packages', title: 'My work packages' }, + ], + officePack: true, + catalogueApps: [{ uuid: 'z1', name: 'Case system', description: 'Cases for the front office', icon: '/z.svg', iconType: 'url' }], + discoveredApps: [{ appId: 'deck', name: 'Deck', icon: '/deck.svg' }], + widgets: [ + { id: 'notes', title: 'Notes', itemApiVersions: [1, 2] }, + { id: 'oldie', title: 'Old widget', itemApiVersions: [] }, + ], + allowedWidgets: null, + placedWidgetIds: ['notes'], + placedAppIds: ['deck'], +} + +describe('widget picker kinds', () => { + it('lists the seven kinds of the board in order, with their labels', () => { + expect(KINDS).toEqual(['all', 'content', 'tiles', 'people', 'data', 'apps', 'office']) + expect(KINDS.map((kind) => kindLabel(kind, t))).toEqual(['All', 'Content', 'Tiles and links', 'People', 'Data and charts', 'From other apps', 'Office']) + expect(kindLabel('unknown', t)).toBe('unknown') + }) + + it('puts each type in one kind, content when it names none', () => { + expect(['pie-chart', 'graph', 'stat', 'table'].map(kindOfType)).toEqual(['data', 'data', 'data', 'data']) + expect(['tile', 'container', 'link'].map(kindOfType)).toEqual(['tiles', 'tiles', 'tiles']) + expect(kindOfType('people')).toBe('people') + expect(kindOfType('assigned-cases')).toBe('apps') + expect(['clock', 'iframe', 'section-heading', 'something-new'].map(kindOfType)).toEqual(['content', 'content', 'content', 'content']) + }) + + it('names the three sections and gives every type one line', () => { + expect(['launchpad', 'tiles', 'apps', 'x'].map((id) => sectionLabel(id, t))).toEqual(['Widgets from Launchpad', 'App tiles', 'From other Nextcloud apps', 'x']) + expect(typeLine('pie-chart', t)).toBe('Shares of a whole as a pie.') + expect(typeLine('iframe', t)).toBe('A page from another site.') + expect(typeLine('brand-new', t)).toBe('A Launchpad widget.') + }) +}) + +describe('pickerCards', () => { + it('makes one card per offer, in section order, App tiles ending with Own tile', () => { + const cards = pickerCards(INPUT, t) + expect(cards.map((card) => card.section)).toEqual([ + 'launchpad', 'launchpad', 'launchpad', 'launchpad', 'launchpad', 'launchpad', 'launchpad', 'launchpad', + 'tiles', 'tiles', 'tiles', + 'apps', 'apps', + ]) + expect(cards.filter((card) => card.section === 'tiles').map((card) => card.title)).toEqual(['Case system', 'Deck', 'Own tile']) + expect(cards.find((card) => card.key === 'catalogue:z1')).toMatchObject({ kind: 'tiles', line: 'Cases for the front office', action: { event: 'addCatalogueApp' } }) + expect(cards.find((card) => card.key === 'app:deck').badge).toBe('On this dashboard') + expect(cards.find((card) => card.key === 'own-tile').action).toEqual({ event: 'addCustom', arg: 'tile' }) + expect(cards.find((card) => card.key === 'office-pack')).toMatchObject({ kind: 'office', action: { event: 'addOfficePack' } }) + }) + + it('puts placed Nextcloud widgets last and badges them, and marks an older widget type', () => { + const cards = pickerCards(INPUT, t).filter((card) => card.section === 'apps') + expect(cards.map((card) => card.title)).toEqual(['Old widget', 'Notes']) + expect(cards[1].badge).toBe('Already added') + expect(cards[0].legacy).toBe(true) + expect(cards[1].legacy).toBe(false) + expect(cards[1].action).toEqual({ event: 'add', arg: 'notes' }) + }) + + it('greys out what the role may not add, as the server decides it', () => { + const cards = pickerCards({ ...INPUT, allowedWidgets: ['clock', 'notes'] }, t) + const disabled = Object.fromEntries(cards.map((card) => [card.key, card.disabled])) + expect(disabled['type:clock']).toBe(false) + expect(disabled['type:iframe']).toBe(true) + expect(disabled['widget:notes']).toBe(false) + expect(disabled['widget:oldie']).toBe(true) + // App tiles and Own tile follow `tile`; the office pack follows `container`. + expect(disabled['catalogue:z1']).toBe(true) + expect(disabled['own-tile']).toBe(true) + expect(disabled['office-pack']).toBe(true) + expect(pickerCards({ ...INPUT, allowedWidgets: ['tile'] }, t).find((card) => card.key === 'own-tile').disabled).toBe(false) + }) + + it('leaves the office pack out when it is not offered', () => { + expect(pickerCards({ ...INPUT, officePack: false }, t).some((card) => card.key === 'office-pack')).toBe(false) + expect(pickerCards({}, t).map((card) => card.key)).toEqual(['own-tile']) + }) +}) + +describe('counting and filtering', () => { + const cards = pickerCards(INPUT, t) + + it('counts the cards of each kind, and every card under All', () => { + expect(countByKind(cards)).toEqual({ all: 13, content: 2, tiles: 4, people: 1, data: 2, apps: 3, office: 1 }) + }) + + it('filters to the chosen kind, and searches within it by title or line', () => { + expect(filterCards(cards, 'data', '').map((card) => card.title)).toEqual(['Pie chart', 'Graph']) + expect(filterCards(cards, 'data', 'PIE').map((card) => card.title)).toEqual(['Pie chart']) + expect(filterCards(cards, 'tiles', 'front office').map((card) => card.title)).toEqual(['Case system']) + expect(filterCards(cards, 'all', 'clock').map((card) => card.title)).toEqual(['Clock']) + expect(filterCards(cards, 'people', 'clock')).toEqual([]) + }) +}) + +describe('role and older widgets', () => { + it('allows everything without a list, and only what the list names with one', () => { + expect(roleAllows('iframe', null)).toBe(true) + expect(roleAllows('iframe', undefined)).toBe(true) + expect(roleAllows('iframe', [])).toBe(false) + expect(roleAllows('iframe', ['iframe'])).toBe(true) + }) + + it('calls a widget older only when it says it has no item API', () => { + expect(isLegacyWidget({ itemApiVersions: [] })).toBe(true) + expect(isLegacyWidget({ itemApiVersions: [1] })).toBe(false) + expect(isLegacyWidget({})).toBe(false) + expect(isLegacyWidget(null)).toBe(false) + }) +}) diff --git a/src/utils/addTiles.js b/src/utils/addTiles.js new file mode 100644 index 000000000..323275098 --- /dev/null +++ b/src/utils/addTiles.js @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The choices of the Add tiles dialog (REQ-TILE-043): what each section + * offers as a tile, which tiles a dashboard already holds, and the chosen + * tiles without duplicates. + * + * A choice is `{key, kind, tile}`: `kind` is `tile` for an ordinary tile + * (`{title, icon, iconType, linkType, linkValue}`) or `app-tile` for a + * discovered app (`{appId}`). The key is what makes two choices the same + * tile: the link for a tile, the app for an app tile. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + +import { tileFromCatalogueApp } from './discoveredTile.js' + +/** + * The key of an ordinary tile: its link type and value; an app tile and an + * app-link tile to the same app share it. + * + * @param {{linkType?: string, linkValue?: string}} tile The tile. + * @return {string} the key. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ +export function tileKey(tile) { + const type = String(tile?.linkType || 'url') + let value = String(tile?.linkValue || '') + if (type === 'app') { + value = value.replace(/^\/apps\//, '').replace(/\/$/, '') + } + return `${type}:${value}` +} + +/** + * The keys of the tiles a dashboard already holds. + * + * @param {Array} placements The dashboard's placements. + * @return {Set} the keys. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ +export function existingTileKeys(placements) { + const keys = new Set() + for (const placement of placements || []) { + if (placement?.widgetId === 'app-tile' && placement.content?.appId) { + keys.add(tileKey({ linkType: 'app', linkValue: placement.content.appId })) + } else if (placement?.tileLinkType) { + keys.add(tileKey({ linkType: placement.tileLinkType, linkValue: placement.tileLinkValue })) + } + } + return keys +} + +/** + * A catalogue entry as a choice. + * + * @param {object} app The catalogue entry. + * @return {{key: string, kind: string, tile: object}} the choice. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ +export function catalogueChoice(app) { + const tile = tileFromCatalogueApp(app) + return { key: tileKey(tile), kind: 'tile', tile } +} + +/** + * A discovered app as a choice: its own app tile. + * + * @param {{appId: string}} app The discovered app. + * @return {{key: string, kind: string, tile: object}} the choice. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-tiles-for-services-found-on-the-server-req-tile-044 + */ +export function discoveredChoice(app) { + return { + key: tileKey({ linkType: 'app', linkValue: app.appId }), + kind: 'app-tile', + tile: { appId: String(app.appId) }, + } +} + +/** + * An office pack tile as a choice: one tile of its own. + * + * @param {{title: string, linkType: string, linkValue: string, icon?: string, iconType?: string}} pack The pack tile. + * @return {{key: string, kind: string, tile: object}} the choice. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ +export function officeChoice(pack) { + const tile = { + title: String(pack.title || ''), + icon: pack.icon || '', + iconType: pack.iconType === 'url' ? 'url' : 'class', + linkType: pack.linkType, + linkValue: String(pack.linkValue || ''), + } + return { key: tileKey(tile), kind: 'tile', tile } +} + +/** + * The chosen tiles to add: one per key, leaving out what the dashboard holds. + * + * @param {Array<{key: string}>} choices The chosen choices, in order. + * @param {Set} existing The keys on the dashboard. + * @return {Array<{key: string, kind: string, tile: object}>} the tiles to add. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ +export function tilesToAdd(choices, existing = new Set()) { + const seen = new Set(existing) + const out = [] + for (const choice of choices || []) { + if (!choice?.key || seen.has(choice.key)) { + continue + } + seen.add(choice.key) + out.push(choice) + } + return out +} + +/** + * How a catalogue app signs on: with the person's Nextcloud account, by + * single sign-on, or on the site itself. + * + * @param {{linkType?: string, signOn?: string}} app The catalogue entry. + * @return {'nextcloud'|'sso'|'own'} the kind. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ +export function signOnKind(app) { + if (app?.signOn === 'sso') { + return 'sso' + } + return app?.linkType === 'app' ? 'nextcloud' : 'own' +} diff --git a/src/utils/adminPage.js b/src/utils/adminPage.js new file mode 100644 index 000000000..c2306a84f --- /dev/null +++ b/src/utils/adminPage.js @@ -0,0 +1,74 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The administration page's address: `/apps/launchpad/admin/`, a + * Launchpad page over the full width (admin-settings REQ-ADM-030). The tab + * is in the path, so a link opens it and switching tabs changes it. + * + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ + +import { generateUrl } from '@nextcloud/router' + +/** The tab a page without a (known) tab opens on. */ +export const DEFAULT_ADMIN_TAB = 'general' + +/** + * The tabs of the administration, as `AdminSettings.vue` declares them and + * `AdminPageController::TABS` knows them. + */ +export const ADMIN_TABS = [ + 'general', + 'templates', + 'operations', + 'roles-permissions', + 'versioning-audit', + 'sharing', + 'embeds', + 'kiosk', + 'communities', + 'org-navigation', + 'demo-data', + 'group-dashboards', + 'detail-fields', + 'profile-fields', + 'search-shortcuts', + 'app-catalogue', +] + +/** + * The tab to open for the one an address names: that tab when it exists, + * else General. + * + * @param {string} [tab] The tab the address names. + * @return {string} A tab id. + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ +export function adminTab(tab) { + return ADMIN_TABS.includes(tab) ? tab : DEFAULT_ADMIN_TAB +} + +/** + * The address of the administration page on one tab. + * + * @param {string} [tab] The tab. + * @return {string} The URL. + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ +export function adminPageUrl(tab = DEFAULT_ADMIN_TAB) { + // The tab is one of ADMIN_TABS, so it needs no encoding. + return generateUrl(`/apps/launchpad/admin/${adminTab(tab)}`) +} + +/** + * Whether an address is the administration page, which the server renders + * with the administration's initial state. + * + * @param {string} pathname The pathname. + * @return {boolean} True for `…/apps/launchpad/admin` and its tabs. + * @spec openspec/changes/archive/2026-11-24-admin-full-width-page/specs/admin-settings/spec.md#requirement-the-administration-is-a-launchpad-page-over-the-full-width-req-adm-030 + */ +export function isAdminPagePath(pathname) { + return /\/apps\/launchpad\/admin(?:\/|$)/.test(String(pathname ?? '')) +} diff --git a/src/utils/adminWalkthrough.js b/src/utils/adminWalkthrough.js new file mode 100644 index 000000000..e825609f5 --- /dev/null +++ b/src/utils/adminWalkthrough.js @@ -0,0 +1,133 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The admin settings page's own first-visit tour (runtime-shell REQ-SHELL-011). + * + * The tour is declared in `src/manifest.json` as `launchpad:admin-getting-started` + * with `trigger: "manual"`, so the Workspace shell never starts it there. The + * admin page is its own bundle (src/admin.js) without the shell, and runs the + * tour itself: as a first-visit tour, with its own per-user completion + * preference and its own browser mirror, so finishing the Workspace tour does + * not close the admin tour and finishing the admin tour does not close the + * Workspace tour. The admin page is only served to administrators, so nobody + * else ever sees it. + */ + +import { loadWalkthroughSeenVersion, persistWalkthroughSeenVersion } from '@conduction/nextcloud-vue' + +/** + * The admin tour's id in `manifest.walkthrough.tours`. + */ +export const ADMIN_TOUR_ID = 'launchpad:admin-getting-started' + +/** + * The key the admin page's walkthrough runs under. The library keeps one + * walkthrough per key, and the shell around the admin page already runs the + * Workspace walkthrough under the app id, where the admin tour is manual. + */ +export const ADMIN_TOUR_WALKTHROUGH_KEY = 'launchpad:admin-tour' + +/** + * The per-user preference that records the admin tour as seen, next to the + * Workspace tour's `walkthrough_completed_version`. + */ +export const ADMIN_TOUR_COMPLETION_KEY = 'admin-walkthrough-completed-version' + +/** + * Appended to the library's browser-mirror key, so the admin tour's mirror is + * not the Workspace tour's. + */ +export const ADMIN_TOUR_STORAGE_SUFFIX = ':admin-tour' + +/** + * The manifest the admin page hands the walkthrough: only the admin tour, as a + * first-visit tour, with the admin completion key. Null when the manifest + * declares no admin tour. + * + * @param {object} manifest The app manifest. + * @return {object|null} `{ version, walkthrough }` or null. + * @spec openspec/changes/record-parity-requirements/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + */ +export function adminTourManifest(manifest) { + const walkthrough = manifest?.walkthrough + const tours = Array.isArray(walkthrough?.tours) ? walkthrough.tours : [] + const tour = tours.find((candidate) => candidate && candidate.id === ADMIN_TOUR_ID) + if (!tour || walkthrough.enabled === false) { + return null + } + return { + version: manifest.version, + walkthrough: { + enabled: true, + version: walkthrough.version, + completionConfigKey: ADMIN_TOUR_COMPLETION_KEY, + tours: [{ ...tour, trigger: 'first-visit' }], + }, + } +} + +/** + * A storage that keeps the admin tour's browser mirror under its own keys. + * Without a usable base storage it keeps nothing, rather than falling back to + * the shared mirror. + * + * @param {Storage|null} [base] The storage to wrap; `window.localStorage` when omitted. + * @return {{getItem: (key: string) => (string|null), setItem: (key: string, value: string) => void, removeItem: (key: string) => void}} The scoped storage. + * @spec openspec/changes/record-parity-requirements/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + */ +export function adminTourStorage(base) { + const storage = base === undefined ? browserStorage() : base + if (!storage) { + return { getItem: () => null, setItem: () => {}, removeItem: () => {} } + } + return { + getItem: (key) => storage.getItem(key + ADMIN_TOUR_STORAGE_SUFFIX), + setItem: (key, value) => storage.setItem(key + ADMIN_TOUR_STORAGE_SUFFIX, value), + removeItem: (key) => storage.removeItem(key + ADMIN_TOUR_STORAGE_SUFFIX), + } +} + +/** + * The version the user last finished the admin tour at, or '' when never. + * + * @param {string} appId The app id. + * @param {object} [options] `{ http, storage }` injection points for tests. + * @return {Promise} The seen version. + * @spec openspec/changes/record-parity-requirements/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + */ +export function loadAdminTourSeen(appId, options = {}) { + return loadWalkthroughSeenVersion(appId, ADMIN_TOUR_COMPLETION_KEY, { + http: options.http, + storage: adminTourStorage(options.storage), + }) +} + +/** + * Record the admin tour as finished at a version, for this user. + * + * @param {string} appId The app id. + * @param {string} version The app version. + * @param {object} [options] `{ http, storage }` injection points for tests. + * @return {Promise} True when the server preference was written. + * @spec openspec/changes/record-parity-requirements/specs/runtime-shell/spec.md#requirement-the-admin-area-has-its-own-first-visit-tour-req-shell-011 + */ +export function persistAdminTourSeen(appId, version, options = {}) { + return persistWalkthroughSeenVersion(appId, ADMIN_TOUR_COMPLETION_KEY, version, { + http: options.http, + storage: adminTourStorage(options.storage), + }) +} + +/** + * The browser's localStorage, or null where it cannot be used. + * + * @return {Storage|null} + */ +function browserStorage() { + try { + return typeof window === 'undefined' ? null : window.localStorage + } catch { + return null + } +} diff --git a/src/utils/allowedSites.js b/src/utils/allowedSites.js new file mode 100644 index 000000000..f7612c352 --- /dev/null +++ b/src/utils/allowedSites.js @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: EUPL-1.2 +// Copyright (C) 2026 Conduction B.V. + +/** + * The allowed websites list of the General tab (REQ-ASET-021): each host with + * its purpose, Embed, Fetch or Embed and fetch. Pure, so the mapping runs + * under vitest with nothing mocked; the server normalises and checks hosts. + * + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ + +/** @type {string[]} The purposes, in the order the select offers them. */ +export const PURPOSES = ['embed', 'fetch', 'both'] + +/** + * The purpose of a stored site. + * + * @param {{embed?: boolean, fetch?: boolean}} site The site. + * @return {'embed'|'fetch'|'both'} The purpose; `embed` when neither is set. + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ +export function purposeOf(site) { + if (site?.embed === true && site?.fetch === true) { + return 'both' + } + return site?.fetch === true ? 'fetch' : 'embed' +} + +/** + * A site as the server stores it. + * + * @param {string} host The host. + * @param {string} purpose `embed`, `fetch` or `both`. + * @return {{host: string, embed: boolean, fetch: boolean}} The site. + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ +export function siteFor(host, purpose) { + return { + host: String(host ?? '').trim(), + embed: purpose === 'embed' || purpose === 'both', + fetch: purpose === 'fetch' || purpose === 'both', + } +} + +/** + * The rows the block edits, from a server answer: `{host, purpose}`. + * + * @param {object} data The answer, `{sites}`. + * @return {Array<{host: string, purpose: string}>} The rows. + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ +export function rowsFrom(data) { + const sites = Array.isArray(data?.sites) ? data.sites : [] + return sites + .filter((site) => typeof site?.host === 'string' && site.host !== '') + .map((site) => ({ host: site.host, purpose: purposeOf(site) })) +} + +/** + * Add a row; a host already on the list takes the new purpose instead of + * appearing twice. A blank host adds nothing. + * + * @param {Array<{host: string, purpose: string}>} rows The rows. + * @param {string} host The entered host. + * @param {string} purpose The chosen purpose. + * @return {Array<{host: string, purpose: string}>} The new rows. + * @spec openspec/changes/archive/2026-11-24-allowed-websites-list/specs/admin-settings/spec.md#requirement-one-list-of-allowed-websites-with-a-purpose-per-site-req-aset-021 + */ +export function addRow(rows, host, purpose) { + const entered = String(host ?? '').trim() + if (entered === '') { + return rows + } + const key = entered.toLowerCase() + if (rows.some((row) => row.host.toLowerCase() === key)) { + return rows.map((row) => (row.host.toLowerCase() === key ? { ...row, purpose } : row)) + } + return [...rows, { host: entered, purpose }] +} diff --git a/src/utils/appRequest.js b/src/utils/appRequest.js new file mode 100644 index 000000000..c89bd4a2f --- /dev/null +++ b/src/utils/appRequest.js @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Sending a request for a missing app to IT and saying how it went + * (launcher-app-catalogue REQ-ACAT-003), for the dialogs that offer it. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ + +import { t } from '@nextcloud/l10n' + +/** + * Send the request through the host's function. + * + * @param {function({appName: string, purpose: string}): Promise} requestAppFn The host's request function. + * @param {string} appName The app asked for. + * @param {string} purpose What it is for. + * @return {Promise<{failed: boolean, message: string}>} how it went. + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md#requirement-the-add-tiles-dialog-req-tile-043 + */ +export async function sendAppRequest(requestAppFn, appName, purpose) { + try { + await requestAppFn({ appName: appName.trim(), purpose: purpose.trim() }) + return { failed: false, message: t('launchpad', 'Your request was sent to IT') } + } catch (error) { + const limit = error?.response?.data?.code === 'request_limit' + return { + failed: true, + message: limit + ? t('launchpad', 'You have 10 open requests. Wait for an answer first.') + : t('launchpad', 'Your request could not be sent. Try again later.'), + } + } +} diff --git a/src/utils/bookmarkFile.js b/src/utils/bookmarkFile.js new file mode 100644 index 000000000..503abe65e --- /dev/null +++ b/src/utils/bookmarkFile.js @@ -0,0 +1,155 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Reads the bookmarks file a browser exports (the Netscape bookmark HTML that + * Firefox, Chrome and Edge all write) in the browser, so the raw file never + * reaches the server (launcher-bookmark-import D1). + * + * The result is `{folders: [{name, bookmarks: [{title, url}]}], bookmarks: + * [{title, url}], total}`: each top-level folder with every bookmark under it, + * nested folders flattened in (D4), and the loose top-level bookmarks. Nothing + * is filtered here; the server decides which addresses may become tiles and + * lists the rest back. + * + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md + */ + +/** The largest file read, in bytes (REQ-BMI-004). */ +export const MAX_FILE_BYTES = 5 * 1024 * 1024 + +/** The most bookmarks one import may carry (REQ-BMI-004). */ +export const MAX_BOOKMARKS = 2000 + +/** + * The element children of a node with the given tag name. + * + * @param {Element} node - the parent. + * @param {string} tag - the upper-case tag name. + * @return {Element[]} + */ +function childrenNamed(node, tag) { + return Array.from(node.children).filter((child) => child.tagName === tag) +} + +/** + * One bookmark from an anchor. + * + * @param {Element} anchor - an `` element. + * @return {{title: string, url: string}} + */ +function bookmarkOf(anchor) { + const url = (anchor.getAttribute('href') || '').trim() + const title = (anchor.textContent || '').trim() + return { title: title || url, url } +} + +/** + * The list of a folder entry: the `
` inside its `
`, or the one right + * after it when the parser left it as a sibling. + * + * @param {Element} entry - the folder's `
`. + * @return {Element|null} + */ +function listOf(entry) { + const inside = childrenNamed(entry, 'DL')[0] + if (inside) { + return inside + } + let next = entry.nextElementSibling + while (next && next.tagName === 'P') { + next = next.nextElementSibling + } + return next && next.tagName === 'DL' ? next : null +} + +/** + * The entries of a list. The HTML parser keeps `
` under its `
`, but a + * stray `

` can wrap one; those are looked into as well. + * + * @param {Element} list - a `

`. + * @return {Element[]} + */ +function entriesOf(list) { + const entries = [] + for (const child of Array.from(list.children)) { + if (child.tagName === 'DT') { + entries.push(child) + } else if (child.tagName === 'P') { + entries.push(...childrenNamed(child, 'DT')) + } + } + return entries +} + +/** + * Parse a bookmarks file into its top-level folders and loose bookmarks. + * + * @param {string} html - the file's text. + * @param {typeof DOMParser} [Parser] - the parser (the browser's by default). + * @return {{folders: Array<{name: string, bookmarks: Array<{title: string, url: string}>}>, bookmarks: Array<{title: string, url: string}>, total: number}} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ +export function parseBookmarks(html, Parser = globalThis.DOMParser) { + const doc = new Parser().parseFromString(String(html || ''), 'text/html') + const root = doc.querySelector('dl') + const folders = [] + const bookmarks = [] + if (!root) { + return { folders, bookmarks, total: 0 } + } + + for (const entry of entriesOf(root)) { + const heading = childrenNamed(entry, 'H3')[0] + if (heading) { + const list = listOf(entry) + const inner = list ? Array.from(list.querySelectorAll('a[href]')).map(bookmarkOf) : [] + folders.push({ name: (heading.textContent || '').trim(), bookmarks: inner }) + continue + } + const anchor = childrenNamed(entry, 'A')[0] + if (anchor && anchor.hasAttribute('href')) { + bookmarks.push(bookmarkOf(anchor)) + } + } + + const total = bookmarks.length + folders.reduce((sum, folder) => sum + folder.bookmarks.length, 0) + return { folders, bookmarks, total } +} + +/** + * Read a chosen file, refusing one over 5 MB or over 2,000 bookmarks before + * anything is sent (REQ-BMI-004). The refusal is an Error whose `code` is + * `too-large` or `too-many`. + * + * @param {File|Blob} file - the chosen file. + * @param {typeof DOMParser} [Parser] - the parser (the browser's by default). + * @return {Promise>} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-large-files-are-refused-in-the-browser-req-bmi-004 + */ +export async function readBookmarkFile(file, Parser = globalThis.DOMParser) { + if (file.size > MAX_FILE_BYTES) { + throw Object.assign(new Error('too-large'), { code: 'too-large' }) + } + const parsed = parseBookmarks(await file.text(), Parser) + if (parsed.total > MAX_BOOKMARKS) { + throw Object.assign(new Error('too-many'), { code: 'too-many' }) + } + return parsed +} + +/** + * The request body for the chosen folders and loose bookmarks. + * + * @param {ReturnType} parsed - the parsed file. + * @param {Set} folderIndexes - the chosen folders. + * @param {Set} bookmarkIndexes - the chosen loose bookmarks. + * @return {{folders: Array<{name: string, bookmarks: Array<{title: string, url: string}>}>, bookmarks: Array<{title: string, url: string}>}} + * @spec openspec/changes/launcher-bookmark-import/specs/tiles/spec.md#requirement-users-can-import-a-browser-bookmarks-file-as-tiles-req-bmi-001 + */ +export function chosenBookmarks(parsed, folderIndexes, bookmarkIndexes) { + return { + folders: parsed.folders.filter((_folder, index) => folderIndexes.has(index)), + bookmarks: parsed.bookmarks.filter((_bookmark, index) => bookmarkIndexes.has(index)), + } +} diff --git a/src/utils/bootPath.js b/src/utils/bootPath.js new file mode 100644 index 000000000..445d1fb3d --- /dev/null +++ b/src/utils/bootPath.js @@ -0,0 +1,71 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The address the page was opened on. + * + * Read once, when the bundle is evaluated: the router's catch-all redirects a + * slug address (`/apps/launchpad/`) to `/` before any route component + * is created, so `window.location.pathname` read later no longer holds the + * slug the server resolved. + * + * @spec openspec/specs/dashboard-deeplinking/spec.md + */ + +import { generateUrl } from '@nextcloud/router' + +const BOOT_PATH = typeof window === 'undefined' ? '' : window.location.pathname +const BOOT_HASH = typeof window === 'undefined' ? '' : window.location.hash + +/** + * The pathname the page was loaded with, before any client-side navigation. + * + * @return {string} The boot pathname. + */ +export function bootPath() { + return BOOT_PATH +} + +/** + * The hash the page was loaded with, before any client-side navigation. + * + * @return {string} The boot hash, with its `#`, or ''. + */ +export function bootHash() { + return BOOT_HASH +} + +/** + * The dashboard uuid a `#dashboard/` hash names, as unified search + * links a result (`#dashboard/` or `#dashboard/;widget=`). + * + * @param {string} hash The location hash. + * @return {string} The uuid, or '' when the hash names no dashboard. + */ +export function dashboardUuidFromHash(hash) { + const match = /^#dashboard\/([^;?&/]+)/.exec(String(hash ?? '')) + if (!match) { + return '' + } + try { + return decodeURIComponent(match[1]) + } catch { + return '' + } +} + +/** + * The app prefix the page was opened under: `/index.php/apps/launchpad` or + * `/apps/launchpad`, whichever the address carried. Nextcloud serves both, + * and the router is mounted on this one, so an address the app writes must + * use it too: a path under the other form is outside the router's base, and + * nothing that reads the location against that base (the menu widget's + * active item) matches it. `generateUrl` is only the fallback. + * + * @param {string} [pathname] The pathname to read; the boot pathname by default. + * @return {string} The app prefix, without a trailing slash. + */ +export function appBase(pathname = BOOT_PATH) { + const match = String(pathname ?? '').match(/^(.*\/apps\/launchpad)(?:\/|$)/) + return match ? match[1] : generateUrl('/apps/launchpad') +} diff --git a/src/utils/calculatedFields/__tests__/cycleDetector.spec.js b/src/utils/calculatedFields/__tests__/cycleDetector.spec.js new file mode 100644 index 000000000..d1908600a --- /dev/null +++ b/src/utils/calculatedFields/__tests__/cycleDetector.spec.js @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Cycle detection across calculated fields and widgets (tasks 7, 9). + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ + +import { describe, expect, it } from 'vitest' +import { assertAcyclic } from '../cycleDetector.js' +import { CalculatedFieldError, parse } from '../parser.js' + +/** + * A widget with calculated fields parsed from expressions. + * + * @param {string} id - The widget id. + * @param {Record} fields - Name => expression. + * @return {object} + */ +function widget(id, fields) { + const names = Object.keys(fields) + return { + id, + calculatedFields: names.map((name) => ({ name, compiledExpression: parse(fields[name], { calculatedNames: names }) })), + } +} + +/** + * The cycleDetected detail. + * + * @param {Array} widgets - The widgets. + * @return {object} + */ +function cycle(widgets) { + try { + assertAcyclic(widgets) + } catch (e) { + expect(e).toBeInstanceOf(CalculatedFieldError) + return e.detail + } + throw new Error('expected a cycle') +} + +describe('assertAcyclic', () => { + it('rejects a self-reference', () => { + expect(cycle([widget('A', { x: 'widget:self.x + 1' })])).toMatchObject({ error: 'cycleDetected', cycle: ['A.x', 'A.x'], widgets: ['A'] }) + }) + + it('rejects mutual and longer cycles inside a widget', () => { + expect(cycle([widget('A', { x: 'y * 2', y: 'x / 2' })]).cycle).toEqual(['A.x', 'A.y', 'A.x']) + expect(cycle([widget('A', { p: 'q', q: 'r', r: 'p + 1', s: 'revenue' })]).cycle).toEqual(['A.p', 'A.q', 'A.r', 'A.p']) + }) + + it('rejects two widgets that read each other, naming both', () => { + const detail = cycle([widget('A', { a: 'widget:B.x' }), widget('B', { b: 'widget:A.y' })]) + + expect(detail.error).toBe('cycleDetected') + expect(detail.widgets).toEqual(['A', 'B']) + expect(detail.message).toBe('Calculated fields depend on each other in a cycle: A -> B -> A') + }) + + it('accepts an acyclic graph and orders dependencies first', () => { + const order = assertAcyclic([ + widget('A', { share: 'widget:B.total / revenue', pct: 'share * 100' }), + widget('B', { total: 'sum(x, y)' }), + ]) + + expect(order).toEqual(['B.total', 'A.share', 'A.pct']) + expect(assertAcyclic([])).toEqual([]) + expect(assertAcyclic([widget('C', { z: 'widget:unknown.v' })])).toEqual(['C.z']) + }) +}) diff --git a/src/utils/calculatedFields/__tests__/dashboardValues.spec.js b/src/utils/calculatedFields/__tests__/dashboardValues.spec.js new file mode 100644 index 000000000..8966d2678 --- /dev/null +++ b/src/utils/calculatedFields/__tests__/dashboardValues.spec.js @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Dashboard-wide evaluation of calculated fields in dependency order + * (tasks 13, 17, 18). + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + +import { describe, expect, it } from 'vitest' +import { dependentWidgets, evaluateDashboard } from '../dashboardValues.js' +import { parse } from '../parser.js' + +/** + * A widget with calculated fields parsed from expressions. + * + * @param {string} id - The widget id. + * @param {Record} fields - Name => expression. + * @return {object} + */ +function widget(id, fields) { + const names = Object.keys(fields) + return { + id, + calculatedFields: names.map((name) => ({ + name, + expression: fields[name], + compiledExpression: parse(fields[name], { calculatedNames: names }), + })), + } +} + +describe('evaluateDashboard', () => { + it('evaluates each widget\'s fields on its own source data', () => { + const result = evaluateDashboard( + [widget('sales', { margin: '(revenue - cost) / revenue * 100' })], + { sales: { revenue: 150000, cost: 90000 } }, + ) + + expect(result.values).toEqual({ sales: { margin: 40 } }) + expect(result.errors).toEqual({ sales: {} }) + }) + + it('resolves a cross-widget reference to the other widget\'s current data', () => { + const result = evaluateDashboard( + [widget('a', { vsTarget: 'widget:target.target_revenue / revenue * 100' }), { id: 'target' }], + { a: { revenue: 150000 }, target: { target_revenue: 120000 } }, + ) + + expect(result.values.a.vsTarget).toBe(80) + }) + + it('evaluates a field read by another widget before the reader, whatever the widget order', () => { + const widgets = [ + widget('a', { doubled: 'widget:b.net * 2' }), + widget('b', { net: 'revenue - refunds' }), + ] + const result = evaluateDashboard(widgets, { b: { revenue: 100, refunds: 30 } }) + + expect(result.values.b.net).toBe(70) + expect(result.values.a.doubled).toBe(140) + }) + + it('chains calculated fields of the same widget', () => { + const result = evaluateDashboard( + [widget('w', { total: 'net * 2', net: 'revenue - cost' })], + { w: { revenue: 10, cost: 4 } }, + ) + + expect(result.values.w).toEqual({ net: 6, total: 12 }) + }) + + it('re-evaluates with the new data after a filter changed the source data', () => { + const widgets = [widget('a', { share: 'part / widget:b.whole * 100' }), { id: 'b' }] + + const before = evaluateDashboard(widgets, { a: { part: 25 }, b: { whole: 100 } }) + const after = evaluateDashboard(widgets, { a: { part: 25 }, b: { whole: 50 } }) + + expect(before.values.a.share).toBe(25) + expect(after.values.a.share).toBe(50) + }) + + it('reports a failing field inline with its expression and keeps the others', () => { + const result = evaluateDashboard( + [widget('w', { ratio: 'a / b', sum: 'a + b' }), widget('v', { one: '1 + 1' })], + { w: { a: 1, b: 0 } }, + ) + + expect(result.values.w.ratio).toBeNull() + expect(result.errors.w.ratio).toMatchObject({ expression: 'a / b', inputs: { a: 1, b: 0 } }) + expect(typeof result.errors.w.ratio.error).toBe('string') + expect(result.values.w.sum).toBe(1) + expect(result.values.v.one).toBe(2) + expect(result.errors.v).toEqual({}) + }) + + it('propagates null to a reader of a failed field', () => { + const result = evaluateDashboard( + [widget('w', { ratio: 'a / b' }), widget('v', { scaled: 'widget:w.ratio * 10' })], + { w: { a: 1, b: 0 } }, + ) + + expect(result.values.v.scaled).toBeNull() + expect(result.errors.v).toEqual({}) + }) + + it('marks every field of the widgets in a cycle and still evaluates the others', () => { + const result = evaluateDashboard( + [ + widget('a', { x: 'widget:b.y + 1' }), + widget('b', { y: 'widget:a.x + 1' }), + widget('c', { z: '2 * 3' }), + ], + {}, + ) + + expect(result.values.a.x).toBeNull() + expect(result.values.b.y).toBeNull() + expect(result.errors.a.x.error).toContain('cycle') + expect(result.errors.b.y.expression).toBe('widget:a.x + 1') + expect(result.values.c).toEqual({}) + }) + + it('skips fields without a compiled expression and widgets without fields', () => { + const result = evaluateDashboard( + [{ id: 'w', calculatedFields: [{ name: 'draft', expression: 'a +' }] }, { id: 7 }, null], + {}, + ) + + expect(result.values).toEqual({ w: {}, 7: {} }) + }) + + it('evaluates against a fixed clock when one is given', () => { + const result = evaluateDashboard([widget('w', { day: 'today()' })], {}, { now: Date.UTC(2026, 4, 22, 15, 0, 0) }) + + expect(result.values.w.day).toBe('2026-05-22T00:00:00Z') + }) +}) + +describe('dependentWidgets', () => { + it('answers the changed widget and every widget reading it, directly or transitively', () => { + const widgets = [ + widget('a', { x: 'widget:b.y + 1' }), + widget('b', { y: 'widget:c.total' }), + widget('c', { total: 'n' }), + widget('d', { other: '1' }), + ] + + expect(dependentWidgets(widgets, 'c')).toEqual(['a', 'b', 'c']) + expect(dependentWidgets(widgets, 'a')).toEqual(['a']) + expect(dependentWidgets(widgets, 'd')).toEqual(['d']) + }) +}) diff --git a/src/utils/calculatedFields/__tests__/errorText.spec.js b/src/utils/calculatedFields/__tests__/errorText.spec.js new file mode 100644 index 000000000..c37857264 --- /dev/null +++ b/src/utils/calculatedFields/__tests__/errorText.spec.js @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The words for calculated-field error codes and the inline hover text + * (widget-calculated-fields task 49). + * + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-49 + */ + +import { describe, expect, it, vi } from 'vitest' +import { calculatedFieldErrorText, calculatedFieldMessage } from '../errorText.js' + +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, key) => (key in vars ? vars[key] : `{${key}}`)), +})) + +describe('calculatedFieldMessage', () => { + it('has a sentence for every code the parser, checker, cycle detector and server answer', () => { + for (const code of ['parseError', 'invalidExpression', 'typeError', 'cycleDetected', 'unknownFunction', 'functionNotAllowed', 'arityMismatch', 'functionSignature', 'duplicateField', 'downgraded_evaluation_mode']) { + expect(calculatedFieldMessage(code)).toEqual(expect.any(String)) + } + expect(calculatedFieldMessage('nope')).toBeNull() + }) +}) + +describe('calculatedFieldErrorText', () => { + it('names the reason, the formula and the values read', () => { + expect(calculatedFieldErrorText({ error: 'division by zero', expression: 'a / b', inputs: { a: 4, b: 0, c: null } })) + .toBe('This value could not be calculated (division by zero).\nFormula: a / b\nValues read: a = 4, b = 0, c = empty') + }) + + it('uses the sentence of a known code', () => { + expect(calculatedFieldErrorText({ error: 'cycleDetected', expression: 'x', inputs: {} })) + .toBe('The formula refers back to itself through other fields.\nFormula: x') + }) +}) diff --git a/src/utils/calculatedFields/__tests__/evaluator.spec.js b/src/utils/calculatedFields/__tests__/evaluator.spec.js new file mode 100644 index 000000000..21dbd8f9f --- /dev/null +++ b/src/utils/calculatedFields/__tests__/evaluator.spec.js @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +import { describe, expect, it } from 'vitest' +import suite from '../../../../tests/fixtures/calculated-fields/shared-evaluator-test-suite.json' +import { evaluate, evaluateField, EvaluationError, readPath } from '../evaluator.js' +import { parse } from '../parser.js' + +/** + * Deep equality with numbers equal to within 1e-9 (REQ-CALC-005). + * + * @param {*} actual The value. + * @param {*} expected The expected value. + */ +function expectClose(actual, expected) { + if (typeof expected === 'number') { + expect(typeof actual).toBe('number') + expect(Math.abs(actual - expected)).toBeLessThanOrEqual(1e-9) + return + } + expect(actual).toEqual(expected) +} + +describe('the shared evaluator suite (REQ-CALC-005)', () => { + it('holds at least 50 cases, errors included', () => { + expect(suite.cases.length).toBeGreaterThanOrEqual(50) + expect(suite.cases.some((c) => 'error' in c)).toBe(true) + }) + + for (const c of suite.cases) { + it(c.name, () => { + const names = Object.keys(c.context.calculated ?? {}) + expect(parse(c.expression, { calculatedNames: names })).toEqual(c.ast) + if ('error' in c) { + expect(() => evaluate(c.ast, c.context, { now: c.now })).toThrow(new EvaluationError(c.error)) + return + } + expectClose(evaluate(c.ast, c.context, { now: c.now }), c.expected) + }) + } +}) + +describe('evaluate', () => { + it('recomputes from new inputs without anything cached (REQ-CALC-003)', () => { + const ast = parse('revenue - cost') + expect(evaluate(ast, { row: { revenue: 100000, cost: 60000 } })).toBe(40000) + expect(evaluate(ast, { row: { revenue: 110000, cost: 70000 } })).toBe(40000) + expect(evaluate(ast, { row: { revenue: 120000, cost: 70000 } })).toBe(50000) + }) + + it('reads a cross-widget calculated value before the widget\'s data', () => { + const ast = parse('widget:w2.total') + expect(evaluate(ast, { widgets: { w2: { total: 1 } }, widgetCalculated: { w2: { total: 2 } } })).toBe(2) + expect(evaluate(ast, { widgets: {} })).toBeNull() + }) + + it('refuses a value of the wrong kind at run time', () => { + expect(() => evaluate(parse('a + 1'), { row: { a: 'x' } })).toThrow('+ needs a number') + expect(() => evaluate(parse('a and true'), { row: { a: 1 } })).toThrow("'and' needs a boolean") + expect(() => evaluate(parse('a < b'), { row: { a: 1, b: 'x' } })).toThrow("'<' needs two numbers, two strings or two dates") + expect(() => evaluate({ type: 'call', name: 'nope', args: [] })).toThrow("unknown function 'nope'") + }) + + it('uses the current time when none is given', () => { + const before = Date.now() + const now = Date.parse(evaluate(parse('now()'))) + expect(now).toBeGreaterThanOrEqual(Math.floor(before / 1000) * 1000) + }) +}) + +describe('readPath', () => { + it('reads through objects and lists, null when absent', () => { + expect(readPath({ a: { b: 1 } }, 'a.b')).toBe(1) + expect(readPath({ a: [{ b: 1 }, { c: 2 }, { b: [3, 4] }] }, 'a.b')).toEqual([1, null, 3, 4]) + expect(readPath({ a: 1 }, 'a.b')).toBeNull() + expect(readPath(null, 'a')).toBeNull() + }) +}) + +describe('evaluateField (REQ-CALC-008)', () => { + it('returns the value of a field that evaluates', () => { + const field = { expression: 'a / b', compiledExpression: parse('a / b') } + expect(evaluateField(field, { row: { a: 1, b: 4 } })).toEqual({ value: 0.25 }) + }) + + it('turns a failure into an inline error with the expression and the inputs it read', () => { + const field = { expression: 'a / b + widget:w2.x + rate', compiledExpression: parse('a / b + widget:w2.x + rate', { calculatedNames: ['rate'] }) } + expect(evaluateField(field, { row: { a: 1, b: 0 }, widgets: { w2: { x: 3 } }, calculated: { rate: 2 } })).toEqual({ + error: 'division by zero', + expression: 'a / b + widget:w2.x + rate', + inputs: { a: 1, b: 0, 'widget:w2.x': 3, rate: 2 }, + }) + }) + + it('reports a failure that is not an evaluation error without its message', () => { + const field = { expression: 'x', compiledExpression: { type: 'bogus' } } + expect(evaluateField(field, {})).toEqual({ error: 'unknown node \'bogus\'', expression: 'x', inputs: {} }) + expect(evaluateField({ compiledExpression: null }, {})).toEqual({ error: 'evaluation failed', expression: '', inputs: {} }) + }) +}) diff --git a/src/utils/calculatedFields/__tests__/formatOptions.spec.js b/src/utils/calculatedFields/__tests__/formatOptions.spec.js new file mode 100644 index 000000000..499154f28 --- /dev/null +++ b/src/utils/calculatedFields/__tests__/formatOptions.spec.js @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Format options applied at display time only (tasks 34-36). + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ + +import { describe, expect, it } from 'vitest' +import { formatCalculatedValue, formatDate, formatDuration, formatNumber } from '../formatOptions.js' + +describe('formatNumber', () => { + it('formats a currency in the field\'s locale', () => { + expect(formatNumber(145000, { style: 'currency', currency: 'EUR', locale: 'nl-NL' })).toBe( + new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(145000), + ) + }) + + it('applies the fraction digits', () => { + expect(formatNumber(40, { minimumFractionDigits: 2, maximumFractionDigits: 2, locale: 'en-US' })).toBe('40.00') + expect(formatNumber(1.23456, { maximumFractionDigits: 1, locale: 'en-US' })).toBe('1.2') + }) + + it('falls back to a decimal when a currency style names no currency', () => { + expect(formatNumber(12.5, { style: 'currency', locale: 'en-US' })).toBe('12.5') + }) + + it('uses the viewer\'s locale when the options name none', () => { + expect(formatNumber(1234.5, {}, 'de-DE')).toBe('1.234,5') + }) +}) + +describe('formatDate', () => { + it('formats an ISO instant in UTC by default', () => { + expect(formatDate('2026-04-21T23:30:00Z', { dateStyle: 'short', locale: 'en-GB' })).toBe('21/04/2026') + }) + + it('honours a time zone', () => { + expect(formatDate('2026-04-21T23:30:00Z', { dateStyle: 'short', timeZone: 'Europe/Amsterdam', locale: 'en-GB' })).toBe('22/04/2026') + }) + + it('answers the value itself when it is no date', () => { + expect(formatDate('not a date', {})).toBe('not a date') + }) +}) + +describe('formatDuration', () => { + it('formats days with literal text', () => { + expect(formatDuration(21 * 86400, { pattern: "d' dagen'" })).toBe('21 dagen') + }) + + it('pads doubled tokens and carries the remainder into the largest unit', () => { + expect(formatDuration(90061, { pattern: 'h:mm:ss' })).toBe('25:01:01') + expect(formatDuration(90061, { pattern: "d'd' hh'h'" })).toBe('1d 01h') + }) + + it('keeps the sign of a negative duration', () => { + expect(formatDuration(-3600, { pattern: 'h:mm' })).toBe('-1:00') + }) + + it('uses h:mm:ss without a pattern', () => { + expect(formatDuration(61, {})).toBe('0:01:01') + }) +}) + +describe('formatCalculatedValue', () => { + it('formats by the return type and leaves the value untouched', () => { + const value = 145000 + const field = { returnType: 'number', formatOptions: { style: 'currency', currency: 'EUR', locale: 'nl-NL' } } + + expect(formatCalculatedValue(value, field)).toContain('145.000,00') + expect(value).toBe(145000) + }) + + it('formats a date and a duration', () => { + expect(formatCalculatedValue('2026-04-21T00:00:00Z', { returnType: 'date', formatOptions: { dateStyle: 'short', locale: 'en-GB' } })).toBe('21/04/2026') + expect(formatCalculatedValue(172800, { returnType: 'duration', formatOptions: { pattern: "d' dagen'" } })).toBe('2 dagen') + }) + + it('shows null as empty and other values as text', () => { + expect(formatCalculatedValue(null, { returnType: 'number' })).toBe('') + expect(formatCalculatedValue(true, { returnType: 'boolean' })).toBe('true') + expect(formatCalculatedValue('High Value', { returnType: 'string' })).toBe('High Value') + }) +}) diff --git a/src/utils/calculatedFields/__tests__/parser.cases.spec.js b/src/utils/calculatedFields/__tests__/parser.cases.spec.js new file mode 100644 index 000000000..160d0223c --- /dev/null +++ b/src/utils/calculatedFields/__tests__/parser.cases.spec.js @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The parser's case table (widget-calculated-fields task 41): every + * operator, every literal kind, every built-in function at its minimum + * arity, every arity bound refused, unknown functions refused, and malformed + * input refused as a column-positioned parse error. Each case is one test. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-001-formula-parser-produces-deterministic-ast + */ + +import { describe, expect, it } from 'vitest' +import { isAstNode } from '../ast.js' +import { FUNCTIONS } from '../functions.js' +import { CalculatedFieldError, parse } from '../parser.js' + +const field = (path, source = 'self') => ({ type: 'fieldRef', source, path }) + +/** + * The refusal detail a parse throws. + * + * @param {string} expression - The expression. + * @param {object} options - Parse options. + * @return {object} + */ +function refusal(expression, options = {}) { + try { + parse(expression, options) + } catch (e) { + expect(e).toBeInstanceOf(CalculatedFieldError) + return e.detail + } + throw new Error(`expected '${expression}' to be refused`) +} + +/** + * A call of a function with n field arguments. + * + * @param {string} name - The function. + * @param {number} n - The argument count. + * @return {string} + */ +const callOf = (name, n) => `${name}(${Array.from({ length: n }, (_, i) => `f${i}`).join(', ')})` + +const BINARY = ['+', '-', '*', '/', '%', '<', '<=', '>', '>=', '==', '!=', 'and', 'or'] + +describe('binary operators', () => { + it.each(BINARY)('parses a %s b', (op) => { + expect(parse(`a ${op} b`)).toEqual({ type: 'binary', op, left: field('a'), right: field('b') }) + }) + + it.each(['+', '-', '*', '/', '%', 'and', 'or'])('associates a %s b %s c to the left', (op) => { + expect(parse(`a ${op} b ${op} c`)).toEqual({ + type: 'binary', + op, + left: { type: 'binary', op, left: field('a'), right: field('b') }, + right: field('c'), + }) + }) +}) + +describe('unary operators', () => { + it('parses negation', () => { + expect(parse('-a')).toEqual({ type: 'unary', op: '-', operand: field('a') }) + }) + + it('parses not', () => { + expect(parse('not a')).toEqual({ type: 'unary', op: 'not', operand: field('a') }) + }) + + it('parses a double negation', () => { + expect(parse('--a')).toEqual({ type: 'unary', op: '-', operand: { type: 'unary', op: '-', operand: field('a') } }) + }) + + it('binds negation tighter than multiplication', () => { + expect(parse('-a * b')).toEqual({ type: 'binary', op: '*', left: { type: 'unary', op: '-', operand: field('a') }, right: field('b') }) + }) +}) + +describe('literals', () => { + it.each([ + ['0', 0], + ['42', 42], + ['3.25', 3.25], + ['1e3', 1000], + ['1.5e2', 150], + ['2.5e-1', 0.25], + ])('parses the number %s', (text, value) => { + expect(parse(text)).toEqual({ type: 'literal', valueType: 'number', value }) + }) + + it.each([ + ['"plain"', 'plain'], + ["'single'", 'single'], + ['""', ''], + ['"with space"', 'with space'], + ['"esc \\"q\\""', 'esc "q"'], + ])('parses the string %s', (text, value) => { + expect(parse(text)).toEqual({ type: 'literal', valueType: 'string', value }) + }) + + it.each([ + ['true', 'boolean', true], + ['false', 'boolean', false], + ['null', 'null', null], + ])('parses the keyword %s', (text, valueType, value) => { + expect(parse(text)).toEqual({ type: 'literal', valueType, value }) + }) +}) + +describe('references', () => { + it.each([ + ['revenue', field('revenue')], + ['order.total', field('order.total')], + ['a.b.c', field('a.b.c')], + ['widget:w1.count', field('count', 'widget:w1')], + ['widget:self.revenue', field('revenue')], + ])('parses %s', (text, ast) => { + expect(parse(text)).toEqual(ast) + }) + + it('reads a declared name as a calculated field', () => { + expect(parse('margin * 2', { calculatedNames: ['margin'] }).left).toEqual({ type: 'calculatedRef', name: 'margin' }) + }) +}) + +describe('built-in functions', () => { + it.each(Object.keys(FUNCTIONS))('parses %s at its minimum arity into a well-formed call', (name) => { + const n = name === 'if' ? 3 : FUNCTIONS[name].min + const ast = parse(callOf(name, n)) + expect(isAstNode(ast)).toBe(true) + if (name !== 'if') { + expect(ast).toEqual({ type: 'call', name, args: Array.from({ length: n }, (_, i) => field(`f${i}`)) }) + } + }) + + it.each(Object.keys(FUNCTIONS).filter((name) => Number.isFinite(FUNCTIONS[name].max)))('refuses %s above its maximum arity', (name) => { + expect(refusal(callOf(name, FUNCTIONS[name].max + 1))).toMatchObject({ error: 'arityMismatch', name }) + }) + + it.each(Object.keys(FUNCTIONS).filter((name) => FUNCTIONS[name].min > 0))('refuses %s below its minimum arity', (name) => { + expect(refusal(callOf(name, FUNCTIONS[name].min - 1))).toMatchObject({ error: 'arityMismatch', name }) + }) + + it.each(['eval', 'exec', 'system', 'require', 'fetch', 'Math', 'constructor'])('refuses the unknown function %s', (name) => { + expect(refusal(`${name}(a)`)).toMatchObject({ error: 'unknownFunction', name }) + }) + + it.each(['sum', 'now', 'concat'])('refuses %s when the allowlist leaves it out', (name) => { + expect(refusal(callOf(name, FUNCTIONS[name].min), { allowedFunctions: ['abs'] })).toMatchObject({ error: 'functionNotAllowed', name }) + }) +}) + +describe('malformed input', () => { + it.each([ + '', + ' ', + '(', + ')', + '(a', + 'a)', + 'a +', + '* a', + 'a b', + 'a ,b', + '"open', + "'open", + 'a # b', + 'a & b', + 'a | b', + 'a = b', + 'abs(a,', + 'abs(a b)', + 'widget:', + 'widget:abc', + 'other:abc.x', + '1..2', + ])('refuses %j as a parse error with a column', (text) => { + const detail = refusal(text) + expect(detail.error).toBe('parseError') + expect(detail.message).toMatch(/column \d+$/) + }) +}) diff --git a/src/utils/calculatedFields/__tests__/parser.spec.js b/src/utils/calculatedFields/__tests__/parser.spec.js new file mode 100644 index 000000000..79cee33ae --- /dev/null +++ b/src/utils/calculatedFields/__tests__/parser.spec.js @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The calculated-field parser (widget-calculated-fields tasks 1, 2, 4, 5): + * every node type, precedence, whitespace-independent ASTs, column-positioned + * parse errors and the function allowlist. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-001-formula-parser-produces-deterministic-ast + */ + +import { describe, expect, it } from 'vitest' +import { FUNCTIONS } from '../functions.js' +import { CalculatedFieldError, parse, referencesOf } from '../parser.js' + +const field = (path, source = 'self') => ({ type: 'fieldRef', source, path }) +const num = (value) => ({ type: 'literal', valueType: 'number', value }) + +/** + * The refusal detail a parse throws. + * + * @param {Function} fn - The throwing call. + * @return {object} + */ +function refusal(fn) { + try { + fn() + } catch (e) { + expect(e).toBeInstanceOf(CalculatedFieldError) + return e.detail + } + throw new Error('expected a refusal') +} + +describe('parse', () => { + it('parses the spec\'s ratio into a binary * at the root', () => { + expect(parse('(revenue - refunds) / revenue * 100')).toEqual({ + type: 'binary', + op: '*', + left: { type: 'binary', op: '/', left: { type: 'binary', op: '-', left: field('revenue'), right: field('refunds') }, right: field('revenue') }, + right: num(100), + }) + }) + + it('gives the same AST for spellings that differ only in whitespace', () => { + expect(parse('( a + b )')).toEqual(parse('(a+b)')) + expect(parse(' sum(a ,b)\n')).toEqual(parse('sum(a,b)')) + }) + + it('builds every literal kind', () => { + expect(parse('1.5e2')).toEqual(num(150)) + expect(parse('"a \\"b\\""')).toEqual({ type: 'literal', valueType: 'string', value: 'a "b"' }) + expect(parse("'x'")).toEqual({ type: 'literal', valueType: 'string', value: 'x' }) + expect(parse('true')).toEqual({ type: 'literal', valueType: 'boolean', value: true }) + expect(parse('false')).toEqual({ type: 'literal', valueType: 'boolean', value: false }) + expect(parse('null')).toEqual({ type: 'literal', valueType: 'null', value: null }) + }) + + it('resolves references to fields, other widgets and calculated fields', () => { + expect(parse('order.total')).toEqual(field('order.total')) + expect(parse('widget:abc123.count')).toEqual(field('count', 'widget:abc123')) + expect(parse('margin', { calculatedNames: ['margin'] })).toEqual({ type: 'calculatedRef', name: 'margin' }) + expect(parse('widget:self.margin', { calculatedNames: ['margin'] })).toEqual({ type: 'calculatedRef', name: 'margin' }) + expect(parse('widget:self.revenue')).toEqual(field('revenue')) + }) + + it('follows the precedence: or < and < not < comparison < + < * < unary', () => { + expect(parse('a or b and not c > 1 + 2 * -d')).toEqual({ + type: 'binary', + op: 'or', + left: field('a'), + right: { + type: 'binary', + op: 'and', + left: field('b'), + right: { + type: 'unary', + op: 'not', + operand: { + type: 'binary', + op: '>', + left: field('c'), + right: { type: 'binary', op: '+', left: num(1), right: { type: 'binary', op: '*', left: num(2), right: { type: 'unary', op: '-', operand: field('d') } } }, + }, + }, + }, + }) + expect(parse('a - b - c')).toEqual({ type: 'binary', op: '-', left: { type: 'binary', op: '-', left: field('a'), right: field('b') }, right: field('c') }) + expect(parse('a % b <= c != d').op).toBe('!=') + }) + + it('builds if and calls, with a variadic sum', () => { + expect(parse('if(a > 0, "up", "down")')).toEqual({ + type: 'if', + cond: { type: 'binary', op: '>', left: field('a'), right: num(0) }, + then: { type: 'literal', valueType: 'string', value: 'up' }, + else: { type: 'literal', valueType: 'string', value: 'down' }, + }) + expect(parse('sum(revenue, cost, profit)')).toEqual({ type: 'call', name: 'sum', args: [field('revenue'), field('cost'), field('profit')] }) + expect(parse('now()')).toEqual({ type: 'call', name: 'now', args: [] }) + }) + + it('reports a parse error with its column', () => { + expect(refusal(() => parse('(revenue - refunds'))).toEqual({ error: 'parseError', message: "Expected ')' at column 19", column: 19 }) + expect(refusal(() => parse('a + * b')).column).toBe(5) + expect(refusal(() => parse('a b')).column).toBe(3) + expect(refusal(() => parse('"open')).column).toBe(1) + expect(refusal(() => parse('a # b')).column).toBe(3) + expect(refusal(() => parse('')).message).toBe('Unexpected end of expression at column 1') + expect(refusal(() => parse('widget:abc')).error).toBe('parseError') + expect(refusal(() => parse('other:abc.x')).error).toBe('parseError') + }) + + it('refuses an unknown function, a disallowed one and a wrong argument count', () => { + expect(refusal(() => parse('eval("revenue * 2")'))).toMatchObject({ error: 'unknownFunction', name: 'eval' }) + expect(refusal(() => parse('now()', { allowedFunctions: ['abs', 'round', 'sum'] }))).toMatchObject({ error: 'functionNotAllowed', name: 'now' }) + expect(parse('abs(x)', { allowedFunctions: ['abs'] }).name).toBe('abs') + expect(refusal(() => parse('pow(2)'))).toMatchObject({ error: 'arityMismatch', name: 'pow' }) + expect(refusal(() => parse('now(1)'))).toMatchObject({ error: 'arityMismatch', name: 'now' }) + expect(refusal(() => parse('sum()')).message).toBe("'sum' takes at least 1 argument(s), got 0") + expect(refusal(() => parse('if(a, b)'))).toMatchObject({ error: 'arityMismatch', name: 'if' }) + }) + + it('allows exactly the documented built-in set', () => { + expect(Object.keys(FUNCTIONS)).toHaveLength(39) + for (const name of ['abs', 'countIf', 'dateDiff', 'durationFormat', 'concat', 'coalesce', 'toDate']) { + expect(FUNCTIONS[name]).toBeDefined() + } + }) + + it('lists the references an AST makes', () => { + expect(referencesOf(parse('if(margin > 0, widget:b.x, revenue)', { calculatedNames: ['margin'] }))).toEqual({ + fields: [{ source: 'widget:b', path: 'x' }, { source: 'self', path: 'revenue' }], + calculated: ['margin'], + }) + }) +}) diff --git a/src/utils/calculatedFields/__tests__/typeChecker.spec.js b/src/utils/calculatedFields/__tests__/typeChecker.spec.js new file mode 100644 index 000000000..9d340f1a8 --- /dev/null +++ b/src/utils/calculatedFields/__tests__/typeChecker.spec.js @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +import { describe, expect, it } from 'vitest' +import { parse } from '../parser.js' +import { inferType, typeOfPath, typeOfProperty } from '../typeChecker.js' + +const schema = { + revenue: 'number', + cost: 'integer', + customerName: 'string', + active: 'boolean', + opened: { type: 'string', format: 'date-time' }, + closed: { type: 'string', format: 'date' }, + lines: 'array', + notes: 'object', +} + +const typeOf = (expression, options) => inferType(parse(expression, options), schema, options) +function refusal (expression, options) { + try { + typeOf(expression, options) + } catch (e) { + return e.detail + } + return null +} + +describe('inferType (REQ-CALC-002)', () => { + it.each([ + ['revenue - cost', 'number'], + ['coalesce(null, revenue, 0)', 'number'], + ['revenue > cost', 'boolean'], + ['active and revenue > 0', 'boolean'], + ['not active', 'boolean'], + ['-revenue', 'number'], + ['if(revenue > 100, "High", "Low")', 'string'], + ['if(active, null, 1)', 'number'], + ['concat(customerName, revenue)', 'string'], + ['dateDiff(closed, opened, "days")', 'number'], + ['dateAdd(opened, 1, "days")', 'date'], + ['durationBetween(closed, opened)', 'duration'], + ['-durationBetween(closed, opened)', 'duration'], + ['durationFormat(durationBetween(closed, opened))', 'string'], + ['sum(lines)', 'number'], + ['count(lines)', 'number'], + ['case(revenue > 10, "a", "b")', 'string'], + ['ifNull(notes, 1)', 'any'], + ['null', 'null'], + ['coalesce(null, null)', 'null'], + ['toDate(customerName) > opened', 'boolean'], + ['notes + 1', 'number'], + ['unknownField * 2', 'number'], + ])('%s is %s', (expression, type) => { + expect(typeOf(expression)).toBe(type) + }) + + it('refuses a binary operator on mismatched operands, naming both', () => { + expect(refusal('revenue + customerName')).toEqual({ + error: 'typeError', + message: "Cannot apply '+' to revenue (number) and customerName (string)", + operands: ['revenue', 'customerName'], + }) + expect(refusal('active and revenue').error).toBe('typeError') + expect(refusal('customerName == revenue').operands).toEqual(['customerName', 'revenue']) + expect(refusal('active < active').error).toBe('typeError') + expect(refusal('-customerName').operands).toEqual(['customerName']) + expect(refusal('not revenue').error).toBe('typeError') + }) + + it('refuses a function argument the signature does not take', () => { + expect(refusal('round(revenue, "two")')).toEqual({ + error: 'functionSignature', + name: 'round', + argument: 2, + message: "'round' argument 2 must be number, got \"two\" (string)", + }) + expect(refusal('abs("hello")').name).toBe('abs') + expect(refusal('upper(revenue)').argument).toBe(1) + expect(refusal('count(revenue)').error).toBe('functionSignature') + expect(refusal('case(revenue, 1, 2)').name).toBe('case') + expect(refusal('sum(revenue, customerName)').argument).toBe(2) + }) + + it('refuses branches and coalesce values of different types', () => { + expect(refusal('if(active, 1, "one")').error).toBe('typeError') + expect(refusal('coalesce(revenue, customerName)').operands).toEqual(['revenue', 'customerName']) + expect(refusal('if(revenue, 1, 2)').error).toBe('typeError') + }) + + it('uses the types of other calculated fields and other widgets', () => { + const options = { calculatedNames: ['profit'], calculatedTypes: { profit: 'string' }, widgetSchemas: { w2: { total: 'number' } } } + expect(refusal('profit + 1', options).operands).toEqual(['profit', '1']) + expect(typeOf('widget:w2.total * 2', options)).toBe('number') + expect(refusal('widget:w2.total + "x"', options).operands).toEqual(['widget:w2.total', '"x"']) + expect(typeOf('widget:w3.anything', options)).toBe('any') + }) + + it('refuses a function it has no signature for', () => { + expect(() => inferType({ type: 'call', name: 'nope', args: [] }, schema)).toThrow("Unknown function 'nope'") + }) +}) + +describe('schema types', () => { + it('maps JSON-schema properties to calculated-field types', () => { + expect(typeOfProperty({ type: ['null', 'integer'] })).toBe('number') + expect(typeOfProperty({ type: 'string', format: 'duration' })).toBe('duration') + expect(typeOfProperty('date')).toBe('date') + expect(typeOfProperty(null)).toBe('any') + }) + + it('reads dotted paths in a nested schema, through arrays', () => { + const nested = { properties: { order: { type: 'object', properties: { total: { type: 'number' } } }, lines: { type: 'array', items: { properties: { kind: { type: 'string' } } } } } } + expect(typeOfPath(nested, 'order.total')).toBe('number') + expect(typeOfPath(nested, 'lines.kind')).toBe('string') + expect(typeOfPath(nested, 'order.missing')).toBe('any') + expect(typeOfPath(null, 'x')).toBe('any') + }) +}) diff --git a/src/utils/calculatedFields/__tests__/validate.spec.js b/src/utils/calculatedFields/__tests__/validate.spec.js new file mode 100644 index 000000000..8109bfaf1 --- /dev/null +++ b/src/utils/calculatedFields/__tests__/validate.spec.js @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +import { describe, expect, it } from 'vitest' +import { describeNode, isAstNode } from '../ast.js' +import { allowedFunctions, DEFAULT_ALLOWED_FUNCTIONS } from '../config.js' +import { FUNCTIONS } from '../functions.js' +import { parse } from '../parser.js' +import { parseAndValidate } from '../validate.js' + +function refusal (widget, options) { + try { + parseAndValidate(widget, options) + } catch (e) { + return e.detail + } + return null +} + +describe('parseAndValidate', () => { + const fieldSchema = { revenue: 'number', cost: 'number', name: 'string' } + + it('compiles every field and types it in dependency order', () => { + const { fields, order } = parseAndValidate({ + id: 'w1', + calculatedFields: [ + { name: 'margin', expression: 'profit / revenue' }, + { name: 'profit', expression: 'revenue - cost' }, + ], + }, { fieldSchema }) + expect(order).toEqual(['w1.profit', 'w1.margin']) + expect(fields.map((f) => [f.name, f.returnType])).toEqual([['margin', 'number'], ['profit', 'number']]) + expect(fields[0].compiledExpression).toEqual(parse('profit / revenue', { calculatedNames: ['margin', 'profit'] })) + }) + + it('refuses a parse error, a type error and a cycle, naming the field', () => { + expect(refusal({ id: 'w1', calculatedFields: [{ name: 'x', expression: 'revenue +' }] }, { fieldSchema })).toMatchObject({ error: 'parseError', field: 'x' }) + expect(refusal({ id: 'w1', calculatedFields: [{ name: 'x', expression: 'revenue + name' }] }, { fieldSchema })).toMatchObject({ error: 'typeError', field: 'x' }) + expect(refusal({ id: 'w1', calculatedFields: [{ name: 'a', expression: 'b + 1' }, { name: 'b', expression: 'a + 1' }] }, { fieldSchema })).toMatchObject({ error: 'cycleDetected' }) + }) + + it('refuses a cycle across widgets', () => { + const other = { id: 'w2', calculatedFields: [{ name: 'y', compiledExpression: parse('widget:w1.x') }] } + expect(refusal({ id: 'w1', calculatedFields: [{ name: 'x', expression: 'widget:w2.y' }] }, { otherWidgets: [other] })).toMatchObject({ error: 'cycleDetected' }) + }) + + it('refuses a function the instance does not allow, and a field declared twice', () => { + expect(refusal({ id: 'w1', calculatedFields: [{ name: 'x', expression: 'sqrt(revenue)' }] }, { fieldSchema, setting: { allowedFunctions: ['abs'] } })).toMatchObject({ error: 'functionNotAllowed', field: 'x' }) + expect(refusal({ id: 'w1', calculatedFields: [{ name: 'x', expression: '1' }, { name: 'x', expression: '2' }] })).toMatchObject({ error: 'duplicateField', field: 'x' }) + }) + + it('accepts a widget without calculated fields', () => { + expect(parseAndValidate({ id: 7 })).toEqual({ fields: [], order: [] }) + }) +}) + +describe('allowedFunctions (REQ-CALC-009)', () => { + it('allows every built-in by default', () => { + expect(allowedFunctions()).toEqual(Object.keys(FUNCTIONS).sort()) + expect(DEFAULT_ALLOWED_FUNCTIONS).toHaveLength(Object.keys(FUNCTIONS).length) + }) + + it('narrows to the listed built-ins and drops unknown names', () => { + expect(allowedFunctions({ allowedFunctions: ['round', 'eval', ' abs ', 'round'] })).toEqual(['abs', 'round']) + expect(allowedFunctions({ allowedFunctions: 'upper, lower,system' })).toEqual(['lower', 'upper']) + expect(allowedFunctions({ allowedFunctions: [] })).toEqual([]) + }) +}) + +describe('isAstNode', () => { + it('accepts every node the parser produces', () => { + for (const expression of ['1', '"s"', 'true', 'null', 'a.b', 'widget:w.x', 'c', '-a', 'not a', 'a + b', 'if(a, 1, 2)', 'round(a, 2)']) { + expect(isAstNode(parse(expression, { calculatedNames: ['c'] })), expression).toBe(true) + } + }) + + it('refuses malformed nodes', () => { + expect(isAstNode(null)).toBe(false) + expect(isAstNode([])).toBe(false) + expect(isAstNode({ type: 'eval', code: 'x' })).toBe(false) + expect(isAstNode({ type: 'literal', valueType: 'number', value: '1' })).toBe(false) + expect(isAstNode({ type: 'literal', valueType: 'number', value: 1, extra: true })).toBe(false) + expect(isAstNode({ type: 'binary', op: '**', left: parse('1'), right: parse('2') })).toBe(false) + expect(isAstNode({ type: 'fieldRef', source: 'other', path: 'x' })).toBe(false) + expect(isAstNode({ type: 'call', name: 'abs', args: [{ type: 'nope' }] })).toBe(false) + }) + + it('names nodes for error messages', () => { + expect(describeNode(parse('widget:w.x'))).toBe('widget:w.x') + expect(describeNode(parse('"s"'))).toBe('"s"') + expect(describeNode(parse('abs(1)'))).toBe('abs(…)') + expect(describeNode(null)).toBe('?') + }) +}) diff --git a/src/utils/calculatedFields/ast.js b/src/utils/calculatedFields/ast.js new file mode 100644 index 000000000..93f2b7742 --- /dev/null +++ b/src/utils/calculatedFields/ast.js @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The calculated-field AST (REQ-CALC-001): seven node kinds, plain + * JSON-serialisable objects, the same shape the PHP evaluator reads. + * + * @typedef {{type: 'literal', valueType: 'number'|'string'|'boolean'|'null', value: number|string|boolean|null}} LiteralNode + * @typedef {{type: 'fieldRef', source: string, path: string}} FieldRefNode `source` is `self` or `widget:`. + * @typedef {{type: 'calculatedRef', name: string}} CalculatedRefNode + * @typedef {{type: 'binary', op: string, left: AstNode, right: AstNode}} BinaryNode + * @typedef {{type: 'unary', op: '-'|'not', operand: AstNode}} UnaryNode + * @typedef {{type: 'if', cond: AstNode, then: AstNode, else: AstNode}} IfNode + * @typedef {{type: 'call', name: string, args: AstNode[]}} CallNode + * @typedef {LiteralNode|FieldRefNode|CalculatedRefNode|BinaryNode|UnaryNode|IfNode|CallNode} AstNode + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-001-formula-parser-produces-deterministic-ast + */ + +/** + * The node kinds and the keys each one carries. + * + * @type {Readonly>} + */ +export const NODE_KEYS = Object.freeze({ + literal: ['valueType', 'value'], + fieldRef: ['source', 'path'], + calculatedRef: ['name'], + binary: ['op', 'left', 'right'], + unary: ['op', 'operand'], + if: ['cond', 'then', 'else'], + call: ['name', 'args'], +}) + +/** + * The binary operators. + */ +export const BINARY_OPS = Object.freeze(['+', '-', '*', '/', '%', '<', '<=', '>', '>=', '==', '!=', 'and', 'or']) + +/** + * The literal value types. + */ +const LITERAL_TYPES = Object.freeze(['number', 'string', 'boolean', 'null']) + +/** + * The checks per node kind, beyond carrying exactly its keys. + */ +const NODE_CHECKS = { + literal: (n) => LITERAL_TYPES.includes(n.valueType) && (n.valueType === 'null' ? n.value === null : typeof n.value === n.valueType), + fieldRef: (n) => typeof n.source === 'string' && (n.source === 'self' || n.source.startsWith('widget:')) && typeof n.path === 'string' && n.path !== '', + calculatedRef: (n) => typeof n.name === 'string' && n.name !== '', + binary: (n) => BINARY_OPS.includes(n.op) && isAstNode(n.left) && isAstNode(n.right), + unary: (n) => (n.op === '-' || n.op === 'not') && isAstNode(n.operand), + if: (n) => isAstNode(n.cond) && isAstNode(n.then) && isAstNode(n.else), + call: (n) => typeof n.name === 'string' && Array.isArray(n.args) && n.args.every(isAstNode), +} + +/** + * Whether a value is a well-formed AST node, recursively: one of the seven + * kinds, carrying exactly that kind's keys, with valid operators and children. + * A stored `compiledExpression` is checked with this before it is evaluated. + * + * @param {unknown} node The value. + * @return {boolean} True for a well-formed node. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-001-formula-parser-produces-deterministic-ast + */ +export function isAstNode(node) { + if (!node || typeof node !== 'object' || Array.isArray(node) || !Object.hasOwn(NODE_KEYS, node.type)) { + return false + } + const keys = Object.keys(node).filter((key) => key !== 'type').sort() + const expected = [...NODE_KEYS[node.type]].sort() + if (keys.length !== expected.length || keys.some((key, i) => key !== expected[i])) { + return false + } + return NODE_CHECKS[node.type](node) +} + +/** + * How each node type is named in an error message. + */ +const NODE_DESCRIPTIONS = { + fieldRef: (node) => (node.source === 'self' ? node.path : `${node.source}.${node.path}`), + calculatedRef: (node) => node.name, + literal: (node) => (node.valueType === 'string' ? JSON.stringify(node.value) : String(node.value)), + call: (node) => `${node.name}(…)`, + binary: (node) => `(… ${node.op} …)`, + unary: (node) => `${node.op} …`, + if: () => 'if(…)', +} + +/** + * A short, readable name of a node for an error message: the field or + * calculated-field name, a literal's value, or the called function. + * + * @param {AstNode} node The node. + * @return {string} The name. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-002-type-checking-at-save-time + */ +export function describeNode(node) { + const type = node?.type + return Object.hasOwn(NODE_DESCRIPTIONS, type) ? NODE_DESCRIPTIONS[type](node) : '?' +} diff --git a/src/utils/calculatedFields/config.js b/src/utils/calculatedFields/config.js new file mode 100644 index 000000000..2af39de2d --- /dev/null +++ b/src/utils/calculatedFields/config.js @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Which built-in functions this instance lets a calculated field call + * (REQ-CALC-009). By default every built-in; an administrator may narrow it. + * Names that are not built-ins are dropped, so a stale setting can never + * allow an unknown function. The parser refuses a call outside the list with + * `unknownFunction` at parse time. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-009-allowlisted-function-set-with-named-signatures + */ + +import { FUNCTIONS, isBuiltIn } from './functions.js' + +/** + * Every built-in function name, in a stable order. + * + * @type {readonly string[]} + */ +export const DEFAULT_ALLOWED_FUNCTIONS = Object.freeze(Object.keys(FUNCTIONS).sort()) + +/** + * The functions an instance allows, from its setting. + * + * @param {{allowedFunctions?: string[]|string|null}|null} [setting] The instance setting: a list, a comma-separated string, or absent for all. + * @return {string[]} The allowed function names. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-009-allowlisted-function-set-with-named-signatures + */ +export function allowedFunctions(setting = null) { + const raw = setting?.allowedFunctions + if (raw === undefined || raw === null) { + return [...DEFAULT_ALLOWED_FUNCTIONS] + } + const names = Array.isArray(raw) ? raw : String(raw).split(',') + return [...new Set(names.map((name) => String(name).trim()).filter(isBuiltIn))].sort() +} diff --git a/src/utils/calculatedFields/cycleDetector.js b/src/utils/calculatedFields/cycleDetector.js new file mode 100644 index 000000000..40a47d5f4 --- /dev/null +++ b/src/utils/calculatedFields/cycleDetector.js @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Cycle detection for calculated fields (REQ-CALC-006): within a widget a + * calculated field may not depend on itself through other calculated fields, + * and across a dashboard a widget whose calculated fields read another widget + * may not be read back by it. A cycle is refused with `cycleDetected`, naming + * what forms it; an acyclic set gets its evaluation order. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ + +import { CalculatedFieldError, referencesOf } from './parser.js' + +/** + * A topological order of a graph, or the first cycle found. + * + * @param {Map>} graph - Node => the nodes it depends on. + * @return {{order: string[], cycle: string[]|null}} + */ +function topologicalOrder(graph) { + const walk = { graph, state: new Map(), order: [], stack: [], cycle: null } + for (const node of [...graph.keys()].sort()) { + visit(walk, node) + } + return { order: walk.cycle ? [] : walk.order, cycle: walk.cycle } +} + +/** + * Visit a node depth-first: its dependencies first, then itself. + * + * @param {{graph: Map, state: Map, order: string[], stack: string[], cycle: (string[]|null)}} walk - The walk, extended here. + * @param {string} node - The node. + * @return {void} + */ +function visit(walk, node) { + if (walk.cycle || walk.state.get(node) === 'done') { + return + } + if (walk.state.get(node) === 'active') { + walk.cycle = cycleAt(walk.stack, node) + return + } + walk.state.set(node, 'active') + walk.stack.push(node) + for (const dependency of dependenciesOf(walk.graph, node)) { + visit(walk, dependency) + } + walk.stack.pop() + walk.state.set(node, 'done') + walk.order.push(node) +} + +/** + * The cycle closed by reaching a node already on the stack. + * + * @param {string[]} stack - The nodes being visited. + * @param {string} node - The node reached again. + * @return {string[]} The cycle, its first node repeated last. + */ +function cycleAt(stack, node) { + return [...stack.slice(stack.indexOf(node)), node] +} + +/** + * A node's dependencies, sorted. + * + * @param {Map>} graph - The graph. + * @param {string} node - The node. + * @return {string[]} Its dependencies; none when it has no entry. + */ +function dependenciesOf(graph, node) { + return [...(graph.get(node) || [])].sort() +} + +/** + * Refuse a dashboard's calculated fields when they form a cycle; otherwise + * answer the order to evaluate them in, as `.`. + * + * @param {Array<{id: string, calculatedFields?: Array<{name: string, compiledExpression: object}>}>} widgets - The dashboard's widgets. + * @return {string[]} The evaluation order, dependencies first. + * @throws {CalculatedFieldError} `cycleDetected` with the `cycle` and the `widgets` in it. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ +export function assertAcyclic(widgets) { + const { fieldGraph, widgetGraph } = dependencyGraphs(widgets || []) + const fields = topologicalOrder(fieldGraph) + if (fields.cycle) { + throw cycleError(fields.cycle, fields.cycle.map((node) => node.slice(0, node.indexOf('.')))) + } + const across = topologicalOrder(widgetGraph) + if (across.cycle) { + throw cycleError(across.cycle, across.cycle) + } + return fields.order +} + +/** + * The field-level and widget-level dependency graphs of a dashboard. + * + * @param {Array} widgets - The dashboard's widgets. + * @return {{fieldGraph: Map>, widgetGraph: Map>}} + */ +function dependencyGraphs(widgets) { + const fieldGraph = new Map() + const widgetGraph = new Map() + const calculated = new Map() + for (const widget of widgets) { + calculated.set(String(widget.id), new Set(calculatedFieldsOf(widget).map((field) => field.name))) + widgetGraph.set(String(widget.id), new Set()) + } + + for (const widget of widgets) { + const id = String(widget.id) + for (const field of calculatedFieldsOf(widget)) { + fieldGraph.set(`${id}.${field.name}`, fieldDependencies(id, field, calculated, widgetGraph)) + } + } + + return { fieldGraph, widgetGraph } +} + +/** + * A widget's calculated fields. + * + * @param {{calculatedFields?: Array}} widget - The widget. + * @return {Array} Its calculated fields; none when unset. + */ +function calculatedFieldsOf(widget) { + return widget.calculatedFields || [] +} + +/** + * The calculated fields one field depends on; records the widgets it reads in the widget graph. + * + * @param {string} id - The field's widget. + * @param {{compiledExpression: object}} field - The field. + * @param {Map>} calculated - Calculated field names per widget. + * @param {Map>} widgetGraph - Widget dependencies, extended here. + * @return {Set} The `.` nodes it depends on. + */ +function fieldDependencies(id, field, calculated, widgetGraph) { + const refs = referencesOf(field.compiledExpression) + const dependencies = new Set(refs.calculated.map((name) => `${id}.${name}`)) + for (const ref of refs.fields) { + const target = targetWidget(id, ref) + linkWidgets(widgetGraph, id, target) + if (calculated.get(target)?.has(ref.path)) { + dependencies.add(`${target}.${ref.path}`) + } + } + return dependencies +} + +/** + * The widget a field reference reads. + * + * @param {string} id - The reading widget. + * @param {{source: string}} ref - The field reference. + * @return {string} The widget id read. + */ +function targetWidget(id, ref) { + return ref.source === 'self' ? id : ref.source.slice('widget:'.length) +} + +/** + * Record that one widget reads another. + * + * @param {Map>} widgetGraph - Widget dependencies. + * @param {string} from - The reading widget. + * @param {string} to - The widget read. + * @return {void} + */ +function linkWidgets(widgetGraph, from, to) { + if (to === from) { + return + } + widgetGraph.get(from).add(to) + if (!widgetGraph.has(to)) { + widgetGraph.set(to, new Set()) + } +} + +/** + * The cycleDetected refusal. + * + * @param {string[]} cycle - The nodes of the cycle, first repeated last. + * @param {string[]} widgetIds - The widgets the nodes belong to. + * @return {CalculatedFieldError} + */ +function cycleError(cycle, widgetIds) { + return new CalculatedFieldError({ + error: 'cycleDetected', + message: `Calculated fields depend on each other in a cycle: ${cycle.join(' -> ')}`, + cycle, + widgets: [...new Set(widgetIds)], + }) +} diff --git a/src/utils/calculatedFields/dashboardValues.js b/src/utils/calculatedFields/dashboardValues.js new file mode 100644 index 000000000..f888b1102 --- /dev/null +++ b/src/utils/calculatedFields/dashboardValues.js @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Evaluate every calculated field of a dashboard in dependency order + * (REQ-CALC-003, REQ-CALC-008). + * + * Each widget's calculated fields read that widget's source data (`row`), + * its own earlier calculated values, and the data and calculated values of + * the widgets they reference (`widget:.`). The fields run in the + * topological order the cycle detector answers, so a field that reads + * another widget's calculated field always sees its current value. A field + * that fails yields `null` and an inline error; the other fields and widgets + * still evaluate. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ + +import { assertAcyclic } from './cycleDetector.js' +import { evaluateField } from './evaluator.js' +import { CalculatedFieldError } from './parser.js' + +/** + * The calculated fields of a widget that can be evaluated: they carry a + * compiled expression. + * + * @param {object} widget The widget. + * @return {object[]} The fields. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +export function compiledFieldsOf(widget) { + return (widget?.calculatedFields || []).filter((field) => field && field.name && field.compiledExpression) +} + +/** + * Split a `.` node of the cycle detector's order. Field + * names are identifiers, so the last dot separates them. + * + * @param {string} node The node. + * @return {{widgetId: string, name: string}} Its parts. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +function splitNode(node) { + const at = node.lastIndexOf('.') + return { widgetId: node.slice(0, at), name: node.slice(at + 1) } +} + +/** + * The evaluable widgets, each with only its compiled fields, keyed by id. + * + * @param {object[]} widgets The dashboard's widgets. + * @return {Map} The widgets by id. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +function widgetsById(widgets) { + const byId = new Map() + for (const widget of (widgets || []).filter(hasId)) { + byId.set(String(widget.id), { id: String(widget.id), calculatedFields: compiledFieldsOf(widget) }) + } + return byId +} + +/** + * Whether a widget carries an id. + * + * @param {object} widget The widget. + * @return {boolean} True when it has one. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +function hasId(widget) { + return widget?.id !== undefined && widget?.id !== null +} + +/** + * Empty value and error records for every widget. + * + * @param {Map} byId The widgets by id. + * @return {{values: object, errors: object}} The records. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +function emptyResult(byId) { + const values = {} + const errors = {} + for (const id of byId.keys()) { + values[id] = {} + errors[id] = {} + } + return { values, errors } +} + +/** + * Mark every field of the widgets in a cycle as failed with the cycle error, + * so those widgets show an inline error while the rest of the dashboard + * renders. + * + * @param {{values: object, errors: object}} result The result to fill. + * @param {Map} byId The widgets by id. + * @param {CalculatedFieldError} error The cycle error. + * @return {void} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ +function markCycle(result, byId, error) { + for (const id of cycleWidgets(error, byId)) { + for (const field of byId.get(String(id))?.calculatedFields || []) { + result.values[id][field.name] = null + result.errors[id][field.name] = { error: error.message, expression: field.expression ?? '', inputs: {} } + } + } +} + +/** + * The widgets a cycle error names, else every widget. + * + * @param {CalculatedFieldError} error The cycle error. + * @param {Map} byId The widgets by id. + * @return {string[]} The widget ids. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ +function cycleWidgets(error, byId) { + const listed = error.detail?.widgets + return listed?.length ? listed : [...byId.keys()] +} + +/** + * The fields' evaluation order, or null after marking a cycle on the result. + * + * @param {Map} byId The widgets by id. + * @param {{values: object, errors: object}} result The result to mark on a cycle. + * @return {string[]|null} The `.` nodes in order. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ +function evaluationOrder(byId, result) { + try { + return assertAcyclic([...byId.values()]) + } catch (error) { + if (!(error instanceof CalculatedFieldError)) { + throw error + } + markCycle(result, byId, error) + return null + } +} + +/** + * Evaluate one field of the order into the result: its value, or null and + * an inline error. + * + * @param {string} node The `.` node. + * @param {Map} byId The widgets by id. + * @param {Record} data Each widget's source data, by widget id. + * @param {{values: object, errors: object}} result The result to fill. + * @param {{now?: number}} options Evaluation options. + * @return {void} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +function evaluateNode(node, byId, data, result, options) { + const { widgetId, name } = splitNode(node) + const field = byId.get(widgetId)?.calculatedFields.find((candidate) => candidate.name === name) + if (!field) { + return + } + const outcome = evaluateField(field, { + row: data[widgetId] ?? {}, + calculated: result.values[widgetId], + widgets: data, + widgetCalculated: result.values, + }, options) + const failed = Object.hasOwn(outcome, 'error') + result.values[widgetId][name] = failed ? null : outcome.value + if (failed) { + result.errors[widgetId][name] = outcome + } +} + +/** + * Evaluate the calculated fields of every widget on the dashboard. + * + * @param {object[]} widgets The widgets, each `{id, calculatedFields}`. + * @param {Record} dataById Each widget's current source data, by widget id. + * @param {{now?: number}} [options] Evaluation options (a fixed clock for tests). + * @return {{values: Record>, errors: Record>}} Values and inline errors per widget id and field name. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +export function evaluateDashboard(widgets, dataById, options = {}) { + const byId = widgetsById(widgets) + const result = emptyResult(byId) + const data = dataById || {} + for (const node of evaluationOrder(byId, result) || []) { + evaluateNode(node, byId, data, result, options) + } + + return result +} + +/** + * The widgets whose calculated fields read a given widget, directly or + * through other widgets: the ones to re-evaluate when its data changes. + * + * @param {object[]} widgets The dashboard's widgets. + * @param {string} changedId The widget whose data changed. + * @return {string[]} The changed widget and every widget depending on it, sorted. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +export function dependentWidgets(widgets, changedId) { + const readers = readersOf(widgets) + const seen = new Set([String(changedId)]) + const queue = [String(changedId)] + while (queue.length > 0) { + const fresh = [...(readers.get(queue.shift()) || [])].filter((reader) => !seen.has(reader)) + fresh.forEach((reader) => { + seen.add(reader) + queue.push(reader) + }) + } + return [...seen].sort() +} + +/** + * For every widget id, the widgets whose calculated fields read it. + * + * @param {object[]} widgets The dashboard's widgets. + * @return {Map>} The readers by widget id. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +function readersOf(widgets) { + const readers = new Map() + for (const widget of widgetsById(widgets).values()) { + const targets = widget.calculatedFields.flatMap((field) => [...referencedWidgets(field.compiledExpression)]) + targets.forEach((target) => addReader(readers, target, widget.id)) + } + return readers +} + +/** + * Note that a widget reads a target widget. + * + * @param {Map>} readers The readers by widget id, extended in place. + * @param {string} target The widget read. + * @param {string} reader The reading widget. + * @return {void} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +function addReader(readers, target, reader) { + if (!readers.has(target)) { + readers.set(target, new Set()) + } + readers.get(target).add(reader) +} + +/** + * The ids of the widgets an expression reads through `widget:` refs. + * + * @param {object} node An AST node. + * @param {Set} [found] The ids found so far. + * @return {Set} The ids. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ +function referencedWidgets(node, found = new Set()) { + if (node && typeof node === 'object') { + const id = widgetRefOf(node) + if (id !== null) { + found.add(id) + } + Object.values(node).forEach((value) => referencedWidgets(value, found)) + } + return found +} + +/** + * The widget id a `widget:` field reference names, else null. + * + * @param {object} node An AST node. + * @return {string|null} The id. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ +function widgetRefOf(node) { + const named = node.type === 'fieldRef' && typeof node.source === 'string' && node.source.startsWith('widget:') + return named ? node.source.slice('widget:'.length) : null +} diff --git a/src/utils/calculatedFields/errorText.js b/src/utils/calculatedFields/errorText.js new file mode 100644 index 000000000..6851034b7 --- /dev/null +++ b/src/utils/calculatedFields/errorText.js @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The words a person reads for a calculated field's error codes and + * warnings (REQ-CALC-008). The parser, type checker, cycle detector and the + * server answer a code; the evaluator answers a short technical reason. This + * turns either into a translated sentence. + */ + +import { translate as t } from '@nextcloud/l10n' + +/** + * The translated sentence per error or warning code. + * + * @return {{[code: string]: string}} + */ +function messages() { + return { + parseError: t('launchpad', 'The formula cannot be read.'), + invalidExpression: t('launchpad', 'The formula cannot be read.'), + typeError: t('launchpad', 'The formula mixes values that do not go together, such as text and a number.'), + cycleDetected: t('launchpad', 'The formula refers back to itself through other fields.'), + unknownFunction: t('launchpad', 'The formula uses a function that does not exist.'), + functionNotAllowed: t('launchpad', 'The formula uses a function this instance does not allow.'), + arityMismatch: t('launchpad', 'A function in the formula has the wrong number of values.'), + functionSignature: t('launchpad', 'A function in the formula is given the wrong kind of value.'), + duplicateField: t('launchpad', 'Two calculated fields on this widget have the same name.'), + downgraded_evaluation_mode: t('launchpad', 'This field is calculated in the browser only: it cannot be stored in the register.'), + } +} + +/** + * The sentence for an error or warning code, or null for a code it does not know. + * + * @param {string} code The code. + * @return {string|null} + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-49 + */ +export function calculatedFieldMessage(code) { + return messages()[code] ?? null +} + +/** + * The hover text of a field that could not be calculated: what went wrong, + * the formula, and the values it read. + * + * @param {{error?: string, expression?: string, inputs?: object}} failure The evaluator's error envelope. + * @return {string} + * @spec openspec/changes/widget-calculated-fields/tasks.md#task-49 + */ +export function calculatedFieldErrorText(failure) { + const reason = calculatedFieldMessage(failure?.error) ?? t('launchpad', 'This value could not be calculated ({reason}).', { reason: failure?.error || '?' }) + const inputs = Object.entries(failure?.inputs || {}) + .map(([name, value]) => `${name} = ${value === null || value === undefined ? t('launchpad', 'empty') : JSON.stringify(value)}`) + .join(', ') + const lines = [reason, t('launchpad', 'Formula: {expression}', { expression: failure?.expression || '' })] + if (inputs !== '') { + lines.push(t('launchpad', 'Values read: {inputs}', { inputs })) + } + return lines.join('\n') +} diff --git a/src/utils/calculatedFields/evaluator.js b/src/utils/calculatedFields/evaluator.js new file mode 100644 index 000000000..5b0d290cc --- /dev/null +++ b/src/utils/calculatedFields/evaluator.js @@ -0,0 +1,634 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The client-side calculated-field evaluator (REQ-CALC-003, REQ-CALC-005, + * REQ-CALC-008): an AST evaluated on a row, deterministically. The PHP + * evaluator mirrors it; the shared suite in + * `src/utils/calculatedFields/shared-evaluator-test-suite.json` pins both. + * + * Values: numbers (IEEE 754), strings, booleans, null, lists (array fields), + * dates (UTC ISO strings `YYYY-MM-DDTHH:MM:SSZ`) and durations (seconds). + * Null propagates: an operator or function given null answers null, except + * coalesce, ifNull, case and the list aggregates, which handle null + * themselves; nulls inside a list are skipped. A runtime failure (division by + * zero, an invalid date, a value of the wrong kind) throws an + * `EvaluationError`; `evaluateField` turns it into the inline error the widget + * shows, with the expression and the inputs it read. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-005-identical-results-between-evaluators + */ + +import { referencesOf } from './parser.js' + +/** + * A calculated field that failed at run time. + */ +export class EvaluationError extends Error { + /** + * @param {string} message What failed, e.g. `division by zero`. + */ + constructor(message) { + super(message) + this.name = 'EvaluationError' + } +} + +const DAY = 86400 +const UNIT_SECONDS = { seconds: 1, minutes: 60, hours: 3600, days: DAY, weeks: 7 * DAY } + +/** + * Read a dotted path from a value; through a list it reads every element, so + * `lines.amount` on rows with a `lines` array is the list of amounts. + * + * @param {unknown} value The row, or the list of rows. + * @param {string} path The dotted path. + * @return {unknown} The value, a list, or null when absent. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-003-client-side-evaluator-reactive-to-filter-changes + */ +export function readPath(value, path) { + let current = value + for (const part of String(path).split('.')) { + if (Array.isArray(current)) { + current = current.flatMap((item) => { + const next = item === null || typeof item !== 'object' ? null : item[part] + return next === undefined ? [null] : (Array.isArray(next) ? next : [next]) + }) + } else if (current !== null && typeof current === 'object') { + current = Object.hasOwn(current, part) ? current[part] : null + } else { + return null + } + } + return current === undefined ? null : current +} + +/** + * A number, or a runtime error naming the operation. + * + * @param {unknown} value The value. + * @param {string} what The operation, for the message. + * @return {number} The number. + */ +function num(value, what) { + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new EvaluationError(`${what} needs a number`) + } + return value +} + +/** + * A string, or a runtime error naming the operation. + * + * @param {unknown} value The value. + * @param {string} what The operation. + * @return {string} The string. + */ +function str(value, what) { + if (typeof value !== 'string') { + throw new EvaluationError(`${what} needs a string`) + } + return value +} + +/** + * A list, or a runtime error naming the operation. + * + * @param {unknown} value The value. + * @param {string} what The operation. + * @return {Array} The list. + */ +function list(value, what) { + if (!Array.isArray(value)) { + throw new EvaluationError(`${what} needs a list`) + } + return value +} + +/** + * A finite number result, or a runtime error. + * + * @param {number} value The result. + * @return {number} The result. + */ +function finite(value) { + if (!Number.isFinite(value)) { + throw new EvaluationError('numeric overflow') + } + return value +} + +/** + * Epoch seconds of a date value. + * + * @param {unknown} value An ISO date string or epoch milliseconds. + * @return {number} Epoch seconds. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-005-identical-results-between-evaluators + */ +export function dateSeconds(value) { + const ms = typeof value === 'number' ? value : (typeof value === 'string' ? Date.parse(value) : NaN) + if (!Number.isFinite(ms)) { + throw new EvaluationError('invalid date') + } + return Math.floor(ms / 1000) +} + +/** + * The canonical date value of epoch seconds: `YYYY-MM-DDTHH:MM:SSZ`. + * + * @param {number} seconds Epoch seconds. + * @return {string} The date. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-005-identical-results-between-evaluators + */ +export function isoDate(seconds) { + return new Date(seconds * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z') +} + +/** + * The text of a value, as concat and toString give it. + * + * @param {unknown} value The value. + * @return {string} The text. + */ +function text(value) { + if (typeof value === 'string') return value + if (typeof value === 'number') return String(num(value, 'toString')) + if (typeof value === 'boolean') return value ? 'true' : 'false' + throw new EvaluationError('toString needs a scalar') +} + +/** + * Round half away from zero to `digits` decimals, as PHP's round does: the + * product is first trimmed to 15 significant digits so 1.005 rounds to 1.01. + * + * @param {number} value The number. + * @param {number} digits The decimals. + * @return {number} The rounded number. + */ +function roundHalfAway(value, digits) { + const factor = 10 ** Math.trunc(digits) + const scaled = Number((Math.abs(value) * factor).toPrecision(15)) + const rounded = Math.round(scaled) / factor + return finite(value < 0 ? -rounded : rounded) +} + +/** + * The numbers of the arguments of sum/avg/min/max, lists flattened and the + * nulls inside them skipped. + * + * @param {Array} args The arguments. + * @param {string} what The function. + * @return {number[]} The numbers. + */ +function numbersOf(args, what) { + return args.flatMap((arg) => (Array.isArray(arg) ? arg.filter((v) => v !== null) : [arg])).map((v) => num(v, what)) +} + +/** + * Add calendar months to epoch seconds, clamping the day to the month's end. + * + * @param {number} seconds Epoch seconds. + * @param {number} months Months to add (whole). + * @return {number} Epoch seconds. + */ +function addMonths(seconds, months) { + const d = new Date(seconds * 1000) + const year = d.getUTCFullYear() + const month = d.getUTCMonth() + Math.trunc(months) + const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate() + const day = Math.min(d.getUTCDate(), lastDay) + return Date.UTC(year, month, day, d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds()) / 1000 +} + +/** + * Whole calendar months from `start` to `end` (negative when end is earlier). + * + * @param {number} end Epoch seconds. + * @param {number} start Epoch seconds. + * @return {number} Months. + */ +function monthsBetween(end, start) { + if (end < start) return -monthsBetween(start, end) + const a = new Date(end * 1000) + const b = new Date(start * 1000) + let months = (a.getUTCFullYear() - b.getUTCFullYear()) * 12 + (a.getUTCMonth() - b.getUTCMonth()) + if (addMonths(start, months) > end) months -= 1 + return months +} + +/** + * A unit name of dateAdd / dateDiff, or a runtime error. + * + * @param {string} unit The unit. + * @return {string} The unit. + */ +function unitOf(unit) { + if (!Object.hasOwn(UNIT_SECONDS, unit) && unit !== 'months' && unit !== 'years') { + throw new EvaluationError(`unknown unit '${unit}'`) + } + return unit +} + +const PATTERN_TOKENS = /yyyy|MM|dd|HH|mm|ss/g + +/** + * Format epoch seconds with yyyy, MM, dd, HH, mm and ss (UTC). + * + * @param {number} seconds Epoch seconds. + * @param {string} pattern The pattern. + * @return {string} The formatted date. + */ +function formatPattern(seconds, pattern) { + const iso = isoDate(seconds) + const parts = { yyyy: iso.slice(0, 4), MM: iso.slice(5, 7), dd: iso.slice(8, 10), HH: iso.slice(11, 13), mm: iso.slice(14, 16), ss: iso.slice(17, 19) } + return pattern.replace(PATTERN_TOKENS, (token) => parts[token]) +} + +/** + * Parse a date written in a yyyy/MM/dd/HH/mm/ss pattern (UTC). + * + * @param {string} value The text. + * @param {string} pattern The pattern. + * @return {number} Epoch seconds. + */ +function parsePattern(value, pattern) { + const order = [] + const source = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(PATTERN_TOKENS, (token) => { + order.push(token) + return token === 'yyyy' ? '(\\d{4})' : '(\\d{2})' + }) + const match = new RegExp(`^${source}$`).exec(value) + if (!match) throw new EvaluationError('invalid date') + const p = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0 } + order.forEach((token, i) => { p[token] = Number(match[i + 1]) }) + const ms = Date.UTC(p.yyyy, p.MM - 1, p.dd, p.HH, p.mm, p.ss) + if (new Date(ms).getUTCDate() !== p.dd || new Date(ms).getUTCMonth() !== p.MM - 1) throw new EvaluationError('invalid date') + return ms / 1000 +} + +/** + * Format a duration in seconds with hh (total hours), mm and ss. + * + * @param {number} seconds The duration. + * @param {string} pattern The pattern. + * @return {string} The text, `-` first for a negative duration. + */ +function formatDuration(seconds, pattern) { + const total = Math.round(Math.abs(seconds)) + const parts = { + hh: String(Math.floor(total / 3600)).padStart(2, '0'), + mm: String(Math.floor((total % 3600) / 60)).padStart(2, '0'), + ss: String(total % 60).padStart(2, '0'), + } + return (seconds < 0 ? '-' : '') + pattern.replace(/hh|mm|ss/g, (token) => parts[token]) +} + +/** + * The functions that handle null arguments themselves. + */ +const NULL_AWARE = new Set(['coalesce', 'ifNull', 'case', 'count', 'countIf', 'sumIf', 'avgIf']) + +/** + * Every built-in function on its evaluated arguments. + */ +const IMPLEMENTATIONS = { + abs: ([x]) => Math.abs(num(x, 'abs')), + round: ([x, d = 0]) => roundHalfAway(num(x, 'round'), num(d, 'round')), + ceil: ([x]) => Math.ceil(num(x, 'ceil')), + floor: ([x]) => Math.floor(num(x, 'floor')), + min: (args) => { const n = numbersOf(args, 'min'); return n.length ? Math.min(...n) : null }, + max: (args) => { const n = numbersOf(args, 'max'); return n.length ? Math.max(...n) : null }, + pow: ([x, y]) => finite(num(x, 'pow') ** num(y, 'pow')), + sqrt: ([x]) => { + if (num(x, 'sqrt') < 0) throw new EvaluationError('square root of a negative number') + return Math.sqrt(x) + }, + log: ([x, base]) => { + if (num(x, 'log') <= 0) throw new EvaluationError('logarithm of a number that is not positive') + if (base === undefined) return Math.log(x) + if (num(base, 'log') <= 0 || base === 1) throw new EvaluationError('invalid logarithm base') + return Math.log(x) / Math.log(base) + }, + sum: (args) => finite(numbersOf(args, 'sum').reduce((a, b) => a + b, 0)), + avg: (args) => { const n = numbersOf(args, 'avg'); return n.length ? finite(n.reduce((a, b) => a + b, 0) / n.length) : null }, + count: ([items]) => (items === null ? 0 : list(items, 'count').filter((v) => v !== null).length), + countIf: ([items, value]) => (items === null ? 0 : list(items, 'countIf').filter((v) => v !== null && v === value).length), + sumIf: ([values, keys, value]) => matching(values, keys, value, 'sumIf').reduce((a, b) => a + b, 0), + avgIf: ([values, keys, value]) => { + const picked = matching(values, keys, value, 'avgIf') + return picked.length ? finite(picked.reduce((a, b) => a + b, 0) / picked.length) : null + }, + now: (_, ctx) => isoDate(Math.floor(ctx.now / 1000)), + today: (_, ctx) => isoDate(Math.floor(ctx.now / 1000 / DAY) * DAY), + dateDiff: ([end, start, unit = 'days']) => { + const a = dateSeconds(end) + const b = dateSeconds(start) + const u = unitOf(str(unit, 'dateDiff')) + if (u === 'months') return monthsBetween(a, b) + if (u === 'years') return Math.trunc(monthsBetween(a, b) / 12) + return Math.trunc((a - b) / UNIT_SECONDS[u]) + }, + dateAdd: ([date, amount, unit]) => { + const s = dateSeconds(date) + const n = Math.trunc(num(amount, 'dateAdd')) + const u = unitOf(str(unit, 'dateAdd')) + if (u === 'months') return isoDate(addMonths(s, n)) + if (u === 'years') return isoDate(addMonths(s, n * 12)) + return isoDate(s + n * UNIT_SECONDS[u]) + }, + formatDate: ([date, pattern]) => formatPattern(dateSeconds(date), str(pattern, 'formatDate')), + parseDate: ([value, pattern]) => isoDate(pattern === undefined ? dateSeconds(str(value, 'parseDate')) : parsePattern(str(value, 'parseDate'), str(pattern, 'parseDate'))), + durationBetween: ([end, start]) => dateSeconds(end) - dateSeconds(start), + durationFormat: ([seconds, pattern = 'hh:mm:ss']) => formatDuration(num(seconds, 'durationFormat'), str(pattern, 'durationFormat')), + concat: (args) => args.map(text).join(''), + upper: ([s]) => str(s, 'upper').toUpperCase(), + lower: ([s]) => str(s, 'lower').toLowerCase(), + trim: ([s]) => str(s, 'trim').trim(), + contains: ([s, part]) => str(s, 'contains').includes(str(part, 'contains')), + startsWith: ([s, part]) => str(s, 'startsWith').startsWith(str(part, 'startsWith')), + endsWith: ([s, part]) => str(s, 'endsWith').endsWith(str(part, 'endsWith')), + replace: ([s, search, replacement]) => { + if (str(search, 'replace') === '') return str(s, 'replace') + return str(s, 'replace').split(search).join(str(replacement, 'replace')) + }, + format: ([template, ...args]) => str(template, 'format').replace(/\{(\d+)\}/g, (whole, i) => (Number(i) < args.length ? text(args[Number(i)]) : whole)), + coalesce: (args) => args.find((v) => v !== null) ?? null, + ifNull: ([value, fallback]) => (value === null ? fallback : value), + case: (args) => { + for (let i = 0; i + 1 < args.length; i += 2) { + if (args[i] === true) return args[i + 1] + } + return args.length % 2 === 1 ? args[args.length - 1] : null + }, + toNumber: ([v]) => { + if (typeof v === 'number') return num(v, 'toNumber') + if (typeof v === 'boolean') return v ? 1 : 0 + if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v.trim()))) return Number(v.trim()) + throw new EvaluationError('cannot convert to a number') + }, + toString: ([v]) => text(v), + toBool: ([v]) => { + if (typeof v === 'boolean') return v + if (typeof v === 'number') return v !== 0 + const word = typeof v === 'string' ? v.trim().toLowerCase() : null + if (['true', '1', 'yes'].includes(word)) return true + if (['false', '0', 'no', ''].includes(word)) return false + throw new EvaluationError('cannot convert to a boolean') + }, + toDate: ([v]) => isoDate(dateSeconds(v)), +} + +/** + * The numbers of `values` whose key in `keys` equals `value`, nulls skipped. + * + * @param {Array|null} values The values. + * @param {Array|null} keys The keys, position by position. + * @param {unknown} value The key to match. + * @param {string} what The function. + * @return {number[]} The matching numbers. + */ +function matching(values, keys, value, what) { + if (values === null || keys === null) return [] + const v = list(values, what) + const k = list(keys, what) + const picked = [] + for (let i = 0; i < Math.min(v.length, k.length); i++) { + if (k[i] !== null && k[i] === value && v[i] !== null) picked.push(num(v[i], what)) + } + return picked +} + +/** + * A divisor that is not zero, or a runtime error. + * + * @param {unknown} b The divisor. + * @param {string} op The operator. + * @return {number} The divisor. + */ +function divisor(b, op) { + if (num(b, op) === 0) throw new EvaluationError('division by zero') + return b +} + +/** + * The arithmetic and equality operators, on evaluated, non-null operands. + */ +const BINARY_OPERATORS = { + '+': (a, b) => finite(num(a, '+') + num(b, '+')), + '-': (a, b) => finite(num(a, '-') - num(b, '-')), + '*': (a, b) => finite(num(a, '*') * num(b, '*')), + '/': (a, b) => { + const d = divisor(b, '/') + return finite(num(a, '/') / d) + }, + '%': (a, b) => { + const d = divisor(b, '%') + return num(a, '%') % d + }, + '==': (a, b) => a === b, + '!=': (a, b) => a !== b, +} + +/** + * Apply a binary operator to two evaluated, non-null operands. + * + * @param {string} op The operator. + * @param {unknown} a The left value. + * @param {unknown} b The right value. + * @return {unknown} The result. + */ +function applyBinary(op, a, b) { + if (Object.hasOwn(BINARY_OPERATORS, op)) return BINARY_OPERATORS[op](a, b) + if (typeof a !== typeof b || (typeof a !== 'number' && typeof a !== 'string')) { + throw new EvaluationError(`'${op}' needs two numbers, two strings or two dates`) + } + return { '<': a < b, '<=': a <= b, '>': a > b, '>=': a >= b }[op] +} + +/** + * A boolean operand, or a runtime error. + * + * @param {unknown} value The value. + * @param {string} what The operator. + * @return {boolean} The boolean. + */ +function bool(value, what) { + if (typeof value !== 'boolean') throw new EvaluationError(`'${what}' needs a boolean`) + return value +} + +/** + * The value of a field reference: the row's own field, or another widget's + * calculated value or data field. + * + * @param {object} node The fieldRef node. + * @param {object} env The evaluation environment. + * @return {unknown} The value. + */ +function fieldValue(node, env) { + if (node.source === 'self') return readPath(env.row, node.path) + const id = node.source.slice('widget:'.length) + const calculated = env.widgetCalculated[id] + if (calculated && Object.hasOwn(calculated, node.path)) return calculated[node.path] + return readPath(env.widgets[id] ?? null, node.path) +} + +/** + * The value of a unary expression; null stays null. + * + * @param {object} node The unary node. + * @param {object} env The evaluation environment. + * @return {unknown} The value. + */ +function unaryValue(node, env) { + const v = env.run(node.operand) + if (v === null) return null + return node.op === 'not' ? !bool(v, 'not') : -num(v, '-') +} + +/** + * The value of a binary expression; a null operand makes it null. + * + * @param {object} node The binary node. + * @param {object} env The evaluation environment. + * @return {unknown} The value. + */ +function binaryValue(node, env) { + const a = env.run(node.left) + const b = env.run(node.right) + if (a === null || b === null) return null + if (node.op === 'and') return bool(a, 'and') && bool(b, 'and') + if (node.op === 'or') return bool(a, 'or') || bool(b, 'or') + return applyBinary(node.op, a, b) +} + +/** + * The value of an if expression; a null condition makes it null. + * + * @param {object} node The if node. + * @param {object} env The evaluation environment. + * @return {unknown} The value. + */ +function ifValue(node, env) { + const cond = env.run(node.cond) + if (cond === null) return null + return bool(cond, 'if') ? env.run(node.then) : env.run(node.else) +} + +/** + * The value of a function call; a null argument makes it null unless the + * function handles nulls itself. + * + * @param {object} node The call node. + * @param {object} env The evaluation environment. + * @return {unknown} The value. + */ +function callValue(node, env) { + const impl = IMPLEMENTATIONS[node.name] + if (!impl) throw new EvaluationError(`unknown function '${node.name}'`) + const args = node.args.map(env.run) + if (!NULL_AWARE.has(node.name) && args.some((v) => v === null)) return null + const result = impl(args, env.ctx) + return result === undefined ? null : result +} + +/** + * How each node type is evaluated. + */ +const NODE_EVALUATORS = { + literal: (node) => node.value, + fieldRef: fieldValue, + calculatedRef: (node, env) => (Object.hasOwn(env.calculated, node.name) ? env.calculated[node.name] : null), + unary: unaryValue, + binary: binaryValue, + if: ifValue, + call: callValue, +} + +/** + * Evaluate an AST on a row. + * + * @param {object} ast The compiled expression. + * @param {{row?: object, calculated?: object, widgets?: object, widgetCalculated?: object}} [context] The row; this widget's calculated values; other widgets' data and calculated values by id. + * @param {{now?: number}} [options] The current time in epoch ms (for now() and today()). + * @return {unknown} The value. + * @throws {EvaluationError} When the evaluation fails. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-005-identical-results-between-evaluators + */ +export function evaluate(ast, context = {}, options = {}) { + const env = { + ctx: { now: Number.isFinite(options.now) ? options.now : Date.now() }, + row: context.row ?? {}, + calculated: context.calculated ?? {}, + widgets: context.widgets ?? {}, + widgetCalculated: context.widgetCalculated ?? {}, + } + env.run = (node) => { + if (!Object.hasOwn(NODE_EVALUATORS, node.type)) throw new EvaluationError(`unknown node '${node.type}'`) + return NODE_EVALUATORS[node.type](node, env) + } + return env.run(ast) +} + +/** + * The value one field reference reads, or null when it cannot be read. + * + * @param {{source: string, path: string}} ref The reference. + * @param {object} context As for {@link evaluate}. + * @param {object} options As for {@link evaluate}. + * @return {unknown} The value. + */ +function inputValue(ref, context, options) { + try { + return evaluate({ type: 'fieldRef', source: ref.source, path: ref.path }, context, options) + } catch { + return null + } +} + +/** + * The values an expression reads, by field path and calculated-field name, + * for the inline error of a failed field. + * + * @param {object|undefined} ast The compiled expression. + * @param {object} context As for {@link evaluate}. + * @param {object} options As for {@link evaluate}. + * @return {object} The inputs. + */ +function inputsOf(ast, context, options) { + const inputs = {} + const refs = ast ? referencesOf(ast) : { fields: [], calculated: [] } + for (const ref of refs.fields) { + const key = ref.source === 'self' ? ref.path : `${ref.source}.${ref.path}` + inputs[key] = inputValue(ref, context, options) + } + const calculated = context.calculated ?? {} + for (const name of refs.calculated) { + inputs[name] = Object.hasOwn(calculated, name) ? calculated[name] : null + } + return inputs +} + +/** + * Evaluate one calculated field for the widget, never throwing: a failure + * becomes `{ error, expression, inputs }` so the cell shows an inline error + * with the expression and the values it read, and every other field and + * widget renders as usual (REQ-CALC-008). + * + * @param {{expression?: string, compiledExpression: object}} field The calculated field. + * @param {object} [context] As for {@link evaluate}. + * @param {object} [options] As for {@link evaluate}. + * @return {{value: unknown}|{error: string, expression: string, inputs: object}} The value, or the error. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-008-inline-error-display-preserves-dashboard-usability + */ +export function evaluateField(field, context = {}, options = {}) { + try { + return { value: evaluate(field.compiledExpression, context, options) } + } catch (e) { + return { + error: e instanceof EvaluationError ? e.message : 'evaluation failed', + expression: field.expression ?? '', + inputs: inputsOf(field.compiledExpression, context, options), + } + } +} diff --git a/src/utils/calculatedFields/formatOptions.js b/src/utils/calculatedFields/formatOptions.js new file mode 100644 index 000000000..8c787c681 --- /dev/null +++ b/src/utils/calculatedFields/formatOptions.js @@ -0,0 +1,252 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Format options of a calculated field, applied at display time only + * (REQ-CALC-010). + * + * A calculated value stays in its native type (number, ISO date string, + * seconds for a duration) for alerting, export and drill-down; these helpers + * only turn it into the string a renderer shows. They never change the value + * itself. + * + * @typedef {object} NumberFormatOptions + * @property {'decimal'|'currency'|'percent'} [style] The number style. + * @property {number} [minimumFractionDigits] Fewest fraction digits. + * @property {number} [maximumFractionDigits] Most fraction digits. + * @property {string} [currency] ISO 4217 code, for the currency style. + * @property {string} [locale] BCP 47 locale, else the viewer's. + * + * @typedef {object} DateFormatOptions + * @property {'short'|'medium'|'long'|'full'} [dateStyle] The date style. + * @property {'short'|'medium'|'long'|'full'} [timeStyle] The time style. + * @property {string} [timeZone] IANA time zone, default UTC (dates are UTC instants). + * @property {string} [locale] BCP 47 locale, else the viewer's. + * + * @typedef {object} DurationFormatOptions + * @property {string} pattern Tokens `d`, `h`, `m`, `s` (zero-padded `hh`, `mm`, `ss`); text in single quotes is literal. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ + +const NUMBER_KEYS = ['style', 'minimumFractionDigits', 'maximumFractionDigits', 'currency'] +const DATE_KEYS = ['dateStyle', 'timeStyle', 'timeZone'] +const UNITS = ['d', 'h', 'm', 's'] +const UNIT_SECONDS = { d: 86400, h: 3600, m: 60, s: 1 } + +/** + * The listed keys of an options object that are set. + * + * @param {object} options The options. + * @param {string[]} keys The keys to keep. + * @return {object} The picked options. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +function pick(options, keys) { + const picked = {} + for (const key of keys) { + if (options[key] !== undefined && options[key] !== null && options[key] !== '') { + picked[key] = options[key] + } + } + return picked +} + +/** + * Format a number with `Intl.NumberFormat`. + * + * @param {number} value The value. + * @param {NumberFormatOptions} options The options. + * @param {string} [locale] The fallback locale. + * @return {string} The display string. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +export function formatNumber(value, options = {}, locale = undefined) { + const intl = pick(options, NUMBER_KEYS) + if (intl.style === 'currency' && !intl.currency) { + delete intl.style + } + return new Intl.NumberFormat(localeOf(options, locale), intl).format(value) +} + +/** + * The locale the options name, else the fallback. + * + * @param {{locale?: string}} options The options. + * @param {string} [locale] The fallback locale. + * @return {string|undefined} The locale. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +function localeOf(options, locale) { + return options.locale || locale +} + +/** + * Format an ISO date string with `Intl.DateTimeFormat`, in UTC unless a time + * zone is set. + * + * @param {string} value The ISO date. + * @param {DateFormatOptions} options The options. + * @param {string} [locale] The fallback locale. + * @return {string} The display string; the value itself when it is no date. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +export function formatDate(value, options = {}, locale = undefined) { + const date = new Date(value) + if (Number.isNaN(date.getTime())) { + return String(value) + } + return new Intl.DateTimeFormat(localeOf(options, locale), dateIntl(options)).format(date) +} + +/** + * The `Intl.DateTimeFormat` options: UTC unless a zone is set, a medium date + * when neither style is. + * + * @param {DateFormatOptions} options The options. + * @return {object} The Intl options. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +function dateIntl(options) { + const intl = { timeZone: 'UTC', ...pick(options, DATE_KEYS) } + if (!intl.dateStyle && !intl.timeStyle) { + intl.dateStyle = 'medium' + } + return intl +} + +/** + * Format a duration in seconds with a token pattern: `d` days, `h` hours, + * `m` minutes, `s` seconds; a doubled token is zero-padded; text between + * single quotes is literal. The largest unit in the pattern carries the + * remainder of the units the pattern leaves out. + * + * @param {number} seconds The duration. + * @param {DurationFormatOptions} options The options. + * @return {string} The display string. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +export function formatDuration(seconds, options = {}) { + const parts = tokenise(durationPattern(options)) + const amounts = durationAmounts(Math.round(Math.abs(seconds)), parts) + const sign = seconds < 0 ? '-' : '' + return sign + parts.map((part) => renderPart(part, amounts)).join('') +} + +/** + * The duration pattern of the options, `h:mm:ss` without one. + * + * @param {DurationFormatOptions} options The options. + * @return {string} The pattern. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +function durationPattern(options) { + return typeof options.pattern === 'string' && options.pattern !== '' ? options.pattern : 'h:mm:ss' +} + +/** + * The amount of each unit the pattern uses; the largest carries the rest. + * + * @param {number} total The whole seconds. + * @param {Array<{unit?: string}>} parts The pattern parts. + * @return {Record} The amounts by unit. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +function durationAmounts(total, parts) { + const amounts = {} + let rest = total + for (const unit of UNITS.filter((candidate) => parts.some((part) => part.unit === candidate))) { + amounts[unit] = Math.floor(rest / UNIT_SECONDS[unit]) + rest -= amounts[unit] * UNIT_SECONDS[unit] + } + return amounts +} + +/** + * One pattern part as text: a literal as is, a unit zero-padded to its width. + * + * @param {{unit?: string, width?: number, literal?: string}} part The part. + * @param {Record} amounts The amounts by unit. + * @return {string} The text. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +function renderPart(part, amounts) { + if (part.literal !== undefined) { + return part.literal + } + return String(amounts[part.unit]).padStart(part.width, '0') +} + +/** + * Split a duration pattern into unit tokens and literal text. + * + * @param {string} pattern The pattern. + * @return {Array<{unit?: string, width?: number, literal?: string}>} The parts. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +function tokenise(pattern) { + const parts = [] + let at = 0 + while (at < pattern.length) { + const { part, next } = readPart(pattern, at) + parts.push(part) + at = next + } + return parts +} + +/** + * Read the pattern part starting at a position: quoted literal text, a run + * of one unit token, or a single literal character. + * + * @param {string} pattern The pattern. + * @param {number} at The position. + * @return {{part: object, next: number}} The part and the position after it. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +function readPart(pattern, at) { + const char = pattern[at] + if (char === "'") { + const end = pattern.indexOf("'", at + 1) + const stop = end === -1 ? pattern.length : end + return { part: { literal: pattern.slice(at + 1, stop) }, next: stop + 1 } + } + if (!'dhms'.includes(char)) { + return { part: { literal: char }, next: at + 1 } + } + let width = 1 + while (pattern[at + width] === char) { + width++ + } + return { part: { unit: char, width }, next: at + width } +} + +/** + * The formatters by return type, first match wins: `null` shows as an + * empty string, anything unmatched as its string (`true`/`false` for booleans). + * + * @type {Array<{applies: function(unknown, object): boolean, format: function(unknown, object, string=): string}>} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +const FORMATTERS = [ + { applies: (value) => value === null || value === undefined, format: () => '' }, + { applies: (value, field) => typeof value === 'number' && field.returnType === 'duration', format: (value, options) => formatDuration(value, options) }, + { applies: (value) => typeof value === 'number', format: formatNumber }, + { applies: (value, field) => typeof value === 'string' && field.returnType === 'date', format: formatDate }, +] + +/** + * The display string of a calculated value: its format options applied by + * its return type. `null` shows as an empty string. The value passed in is + * never changed, so alerting and export keep the native value. + * + * @param {unknown} value The evaluated value. + * @param {{returnType?: string, formatOptions?: object}} field The calculated field. + * @param {string} [locale] The viewer's locale, used when the options name none. + * @return {string} The display string. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-010-format-options-applied-at-render-time + */ +export function formatCalculatedValue(value, field = {}, locale) { + const formatter = FORMATTERS.find((candidate) => candidate.applies(value, field)) + return formatter ? formatter.format(value, field.formatOptions || {}, locale) : String(value) +} diff --git a/src/utils/calculatedFields/functions.js b/src/utils/calculatedFields/functions.js new file mode 100644 index 000000000..859fa842b --- /dev/null +++ b/src/utils/calculatedFields/functions.js @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The built-in functions a calculated field may call, with their arity + * (REQ-CALC-009). The parser refuses any other name, and a call with too few + * or too many arguments. `max: Infinity` marks a variadic function. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-009-allowlisted-function-set-with-named-signatures + */ + +/** + * Every built-in function, by name: its group and how many arguments it takes. + * + * @type {Readonly>} + */ +export const FUNCTIONS = Object.freeze({ + abs: { group: 'math', min: 1, max: 1 }, + round: { group: 'math', min: 1, max: 2 }, + ceil: { group: 'math', min: 1, max: 1 }, + floor: { group: 'math', min: 1, max: 1 }, + min: { group: 'math', min: 1, max: Infinity }, + max: { group: 'math', min: 1, max: Infinity }, + pow: { group: 'math', min: 2, max: 2 }, + sqrt: { group: 'math', min: 1, max: 1 }, + log: { group: 'math', min: 1, max: 2 }, + sum: { group: 'math', min: 1, max: Infinity }, + avg: { group: 'math', min: 1, max: Infinity }, + count: { group: 'aggregate', min: 1, max: 1 }, + countIf: { group: 'aggregate', min: 2, max: 2 }, + sumIf: { group: 'aggregate', min: 3, max: 3 }, + avgIf: { group: 'aggregate', min: 3, max: 3 }, + now: { group: 'date', min: 0, max: 0 }, + today: { group: 'date', min: 0, max: 0 }, + dateDiff: { group: 'date', min: 2, max: 3 }, + dateAdd: { group: 'date', min: 3, max: 3 }, + formatDate: { group: 'date', min: 2, max: 2 }, + parseDate: { group: 'date', min: 1, max: 2 }, + durationBetween: { group: 'duration', min: 2, max: 2 }, + durationFormat: { group: 'duration', min: 1, max: 2 }, + concat: { group: 'string', min: 1, max: Infinity }, + upper: { group: 'string', min: 1, max: 1 }, + lower: { group: 'string', min: 1, max: 1 }, + trim: { group: 'string', min: 1, max: 1 }, + contains: { group: 'string', min: 2, max: 2 }, + startsWith: { group: 'string', min: 2, max: 2 }, + endsWith: { group: 'string', min: 2, max: 2 }, + replace: { group: 'string', min: 3, max: 3 }, + format: { group: 'string', min: 1, max: Infinity }, + coalesce: { group: 'conditional', min: 1, max: Infinity }, + ifNull: { group: 'conditional', min: 2, max: 2 }, + case: { group: 'conditional', min: 2, max: Infinity }, + toNumber: { group: 'coercion', min: 1, max: 1 }, + toString: { group: 'coercion', min: 1, max: 1 }, + toBool: { group: 'coercion', min: 1, max: 1 }, + toDate: { group: 'coercion', min: 1, max: 1 }, +}) + +/** + * Whether a name is a built-in function at all. + * + * @param {string} name - The name. + * @return {boolean} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-009-allowlisted-function-set-with-named-signatures + */ +export function isBuiltIn(name) { + return Object.hasOwn(FUNCTIONS, name) +} diff --git a/src/utils/calculatedFields/parser.js b/src/utils/calculatedFields/parser.js new file mode 100644 index 000000000..b9ed54362 --- /dev/null +++ b/src/utils/calculatedFields/parser.js @@ -0,0 +1,650 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * The calculated-field formula parser (REQ-CALC-001, REQ-CALC-009): an + * expression becomes a canonical, JSON-serialisable AST, the same for any + * spelling that differs only in whitespace. Refusals are thrown as a + * `CalculatedFieldError` whose `detail` is the API's 400 body. + * + * Grammar, loosest first: `or`, `and`, `not`, comparison (`< <= > >= == !=`), + * `+ -`, `* / %`, unary `-`, then a primary: a number, a quoted string, + * `true`, `false`, `null`, a parenthesised expression, `if(cond, then, else)`, + * a call `name(args…)`, or a reference. A reference is a dotted path + * (`revenue`, `order.total`) on the widget itself, `widget:.` on + * another widget, or the name of one of this widget's calculated fields. + * + * AST nodes: `literal {valueType, value}`, `fieldRef {source, path}`, + * `calculatedRef {name}`, `binary {op, left, right}`, `unary {op, operand}`, + * `if {cond, then, else}`, `call {name, args}`. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-001-formula-parser-produces-deterministic-ast + */ + +import { FUNCTIONS, isBuiltIn } from './functions.js' + +/** + * A refused expression; `detail` is the 400 body (`error`, `message`, …). + */ +export class CalculatedFieldError extends Error { + /** + * @param {object} detail - The refusal: `error` and `message`, plus `column`, `name` or `cycle`. + */ + constructor(detail) { + super(detail.message) + this.name = 'CalculatedFieldError' + this.detail = detail + } +} + +const COMPARISON = ['<=', '>=', '==', '!=', '<', '>'] +const KEYWORDS = { and: 'and', or: 'or', not: 'not', true: 'true', false: 'false', null: 'null', if: 'if' } + +/** + * The token readers, tried in this order at each position. + */ +const READERS = [readWhitespace, readComparison, readPunctuation, readString, readNumber, readWord] + +/** + * Split an expression into tokens, each with its 1-based column. + * + * @param {string} source - The expression. + * @return {Array<{kind: string, value: string|number|null, column: number}>} + */ +function tokenize(source) { + const tokens = [] + let i = 0 + while (i < source.length) { + const read = readAt(source, i) + if (read.token) { + tokens.push(read.token) + } + i = read.next + } + tokens.push({ kind: 'end', value: null, column: source.length + 1 }) + return tokens +} + +/** + * The token that starts at a position, tried reader by reader in order. + * + * @param {string} source - The expression. + * @param {number} i - The 0-based position. + * @return {{token: object|null, next: number}} The token (null for whitespace) and where the next one starts. + * @throws {CalculatedFieldError} When no reader accepts the character. + */ +function readAt(source, i) { + for (const reader of READERS) { + const read = reader(source, i) + if (read) { + return read + } + } + throw parseError(`Unexpected character '${source[i]}'`, i + 1) +} + +/** + * Whitespace: skipped. + * + * @param {string} source - The expression. + * @param {number} i - The position. + * @return {object|null} + */ +function readWhitespace(source, i) { + return /\s/.test(source[i]) ? { token: null, next: i + 1 } : null +} + +/** + * A two-character comparison operator. + * + * @param {string} source - The expression. + * @param {number} i - The position. + * @return {object|null} + */ +function readComparison(source, i) { + const two = source.slice(i, i + 2) + return COMPARISON.includes(two) ? { token: { kind: 'op', value: two, column: i + 1 }, next: i + 2 } : null +} + +/** + * A one-character operator, parenthesis or comma. + * + * @param {string} source - The expression. + * @param {number} i - The position. + * @return {object|null} + */ +function readPunctuation(source, i) { + const ch = source[i] + if (!'+-*/%<>(),'.includes(ch)) { + return null + } + return { token: { kind: '(),'.includes(ch) ? ch : 'op', value: ch, column: i + 1 }, next: i + 1 } +} + +/** + * A quoted string; a backslash takes the next character literally. + * + * @param {string} source - The expression. + * @param {number} i - The position. + * @return {object|null} + * @throws {CalculatedFieldError} When the string is not closed. + */ +function readString(source, i) { + const quote = source[i] + if (quote !== '"' && quote !== "'") { + return null + } + const { text, end } = scanString(source, i + 1, quote) + if (end >= source.length) { + throw parseError('Unterminated string', i + 1) + } + return { token: { kind: 'string', value: text, column: i + 1 }, next: end + 1 } +} + +/** + * The text of a string up to its closing quote. + * + * @param {string} source - The expression. + * @param {number} start - The position after the opening quote. + * @param {string} quote - The quote character. + * @return {{text: string, end: number}} The text and the closing quote's position (source.length when unclosed). + */ +function scanString(source, start, quote) { + let j = start + let text = '' + while (j < source.length && source[j] !== quote) { + const escaped = source[j] === '\\' && j + 1 < source.length + j += escaped ? 1 : 0 + text += source[j] + j++ + } + return { text, end: j } +} + +/** + * A number literal. + * + * @param {string} source - The expression. + * @param {number} i - The position. + * @return {object|null} + */ +function readNumber(source, i) { + const number = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(i)) + return number ? { token: { kind: 'number', value: Number(number[0]), column: i + 1 }, next: i + number[0].length } : null +} + +/** + * A keyword or a name: letters, digits and underscores, an optional + * `:source` part, and dotted parts. + */ +const WORD_PATTERN = new RegExp(String.raw`^[A-Za-z_][A-Za-z0-9_]*(?::[A-Za-z0-9_-]+)?(?:\.[A-Za-z_][A-Za-z0-9_]*)*`) + +/** + * A keyword or a (dotted, optionally source-prefixed) name. + * + * @param {string} source - The expression. + * @param {number} i - The position. + * @return {object|null} + */ +function readWord(source, i) { + const word = WORD_PATTERN.exec(source.slice(i)) + if (!word) { + return null + } + return { token: { kind: Object.hasOwn(KEYWORDS, word[0]) ? KEYWORDS[word[0]] : 'name', value: word[0], column: i + 1 }, next: i + word[0].length } +} + +/** + * Refuse a call to an unknown function or one this instance does not allow. + * + * @param {{value: string, column: number}} token - The function name token. + * @param {Set|null} allowed - The allowlist; null allows every built-in. + * @return {void} + * @throws {CalculatedFieldError} `unknownFunction` or `functionNotAllowed`. + */ +function assertCallable(token, allowed) { + const name = token.value + if (!isBuiltIn(name)) { + throw new CalculatedFieldError({ error: 'unknownFunction', name, message: `Unknown function '${name}'`, column: token.column }) + } + if (allowed !== null && !allowed.has(name)) { + throw new CalculatedFieldError({ error: 'functionNotAllowed', name, message: `The function '${name}' is not allowed on this instance`, column: token.column }) + } +} + +/** + * Refuse a call with the wrong number of arguments. + * + * @param {{value: string, column: number}} token - The function name token. + * @param {number} count - The number of arguments given. + * @return {void} + * @throws {CalculatedFieldError} `arityMismatch`. + */ +function assertArity(token, count) { + const name = token.value + const { min, max } = FUNCTIONS[name] + if (count >= min && count <= max) { + return + } + throw new CalculatedFieldError({ + error: 'arityMismatch', + name, + message: `'${name}' takes ${arityText(min, max)} argument(s), got ${count}`, + column: token.column, + }) +} + +/** + * How many arguments a function takes, in words. + * + * @param {number} min - The fewest. + * @param {number} max - The most; Infinity for no limit. + * @return {string|number} + */ +function arityText(min, max) { + if (max === Infinity) { + return `at least ${min}` + } + return min === max ? min : `${min} to ${max}` +} + +/** + * Literal builders by token kind. + */ +const LITERALS = { + number: (token) => ({ type: 'literal', valueType: 'number', value: token.value }), + string: (token) => ({ type: 'literal', valueType: 'string', value: token.value }), + true: () => ({ type: 'literal', valueType: 'boolean', value: true }), + false: () => ({ type: 'literal', valueType: 'boolean', value: false }), + null: () => ({ type: 'literal', valueType: 'null', value: null }), +} + +/** + * The literal a token stands for, or null when it is not a literal. + * + * @param {{kind: string, value: (string|number|null)}} token - The token. + * @return {object|null} + */ +function literalOf(token) { + return Object.hasOwn(LITERALS, token.kind) ? LITERALS[token.kind](token) : null +} + +/** + * The refusal for a token that cannot start an operand. + * + * @param {{kind: string, value: (string|number|null), column: number}} token - The token. + * @return {CalculatedFieldError} + */ +function unexpected(token) { + return parseError(token.kind === 'end' ? 'Unexpected end of expression' : `Unexpected '${token.value}'`, token.column) +} + +/** + * A parse refusal at a column. + * + * @param {string} message - What is wrong. + * @param {number} column - The 1-based column. + * @return {CalculatedFieldError} + */ +function parseError(message, column) { + return new CalculatedFieldError({ error: 'parseError', message: `${message} at column ${column}`, column }) +} + +/** + * The reference a dotted name stands for on the widget itself. + * + * @param {string} path - The name. + * @param {Set} calculatedNames - This widget's calculated field names. + * @return {object} A `calculatedRef` or a `fieldRef` on `self`. + */ +function selfReference(path, calculatedNames) { + return calculatedNames.has(path) ? { type: 'calculatedRef', name: path } : { type: 'fieldRef', source: 'self', path } +} + +/** + * The reference a `widget:.` name stands for. + * + * @param {{value: string, column: number}} token - The name token. + * @param {Set} calculatedNames - This widget's calculated field names. + * @return {object} The reference. + * @throws {CalculatedFieldError} When the field is missing. + */ +function widgetReference(token, calculatedNames) { + const text = token.value + const dot = text.indexOf('.') + if (dot === -1) { + throw parseError('A widget reference needs a field, e.g. widget:.', token.column) + } + const source = text.slice(0, dot) + const path = text.slice(dot + 1) + return source === 'widget:self' ? selfReference(path, calculatedNames) : { type: 'fieldRef', source, path } +} + +/** + * The reference a name token stands for. + * + * @param {{value: string, column: number}} token - The name token. + * @param {Set} calculatedNames - This widget's calculated field names. + * @return {object} The reference. + * @throws {CalculatedFieldError} On an unknown reference source. + */ +function referenceOf(token, calculatedNames) { + const text = token.value + if (text.startsWith('widget:')) { + return widgetReference(token, calculatedNames) + } + if (text.includes(':')) { + throw parseError(`Unknown reference '${text}'`, token.column) + } + return selfReference(text, calculatedNames) +} + +/** + * The operators of the tighter binary levels. + */ +const MULTIPLICATIVE = ['*', '/', '%'] +const ADDITIVE = ['+', '-'] + +/** + * A recursive-descent parser over one token list. + */ +class Parser { + /** + * @param {Array} tokens - The tokens, ending with `end`. + * @param {Set} calculatedNames - This widget's calculated field names. + * @param {Set|null} allowed - The function allowlist; null allows every built-in. + */ + constructor(tokens, calculatedNames, allowed) { + this.tokens = tokens + this.pos = 0 + this.calculatedNames = calculatedNames + this.allowed = allowed + } + + /** + * @return {object} The current token. + */ + peek() { + return this.tokens[this.pos] + } + + /** + * @return {object} The current token, consumed. + */ + next() { + return this.tokens[this.pos++] + } + + /** + * Consume a token of a kind, or refuse. + * + * @param {string} kind - The token kind. + * @param {string} what - How to name it in the refusal. + * @return {object} The token. + * @throws {CalculatedFieldError} When the current token is of another kind. + */ + expect(kind, what) { + const token = this.peek() + if (token.kind !== kind) { + throw parseError(`Expected ${what}`, token.column) + } + return this.next() + } + + /** + * @param {string[]} ops - Operators. + * @return {boolean} Whether the current token is one of them. + */ + isOp(ops) { + const token = this.peek() + return token.kind === 'op' && ops.includes(token.value) + } + + /** + * Parse the whole token list. + * + * @return {object} The AST. + * @throws {CalculatedFieldError} When tokens remain after the expression. + */ + parseAll() { + const ast = this.orExpr() + const token = this.peek() + if (token.kind !== 'end') { + throw parseError(`Unexpected '${token.value}'`, token.column) + } + return ast + } + + /** + * A left-associative chain of keyword operators (`and`, `or`). + * + * @param {string} kind - The keyword's token kind. + * @param {function(): object} operand - Parses one operand. + * @return {object} The AST. + */ + keywordChain(kind, operand) { + let left = operand() + while (this.peek().kind === kind) { + this.next() + left = { type: 'binary', op: kind, left, right: operand() } + } + return left + } + + /** + * A left-associative chain of symbol operators. + * + * @param {string[]} ops - The operators of this level. + * @param {function(): object} operand - Parses one operand. + * @return {object} The AST. + */ + operatorChain(ops, operand) { + let left = operand() + while (this.isOp(ops)) { + const op = this.next().value + left = { type: 'binary', op, left, right: operand() } + } + return left + } + + /** + * @return {object} An `or` expression; every sub-expression starts here. + */ + orExpr() { + return this.keywordChain('or', () => this.andExpr()) + } + + /** + * @return {object} An `and` expression. + */ + andExpr() { + return this.keywordChain('and', () => this.notExpr()) + } + + /** + * @return {object} A `not` expression. + */ + notExpr() { + if (this.peek().kind !== 'not') { + return this.comparison() + } + this.next() + return { type: 'unary', op: 'not', operand: this.notExpr() } + } + + /** + * @return {object} A comparison. + */ + comparison() { + return this.operatorChain(COMPARISON, () => this.additive()) + } + + /** + * @return {object} A sum or difference. + */ + additive() { + return this.operatorChain(ADDITIVE, () => this.multiplicative()) + } + + /** + * @return {object} A product, quotient or remainder. + */ + multiplicative() { + return this.operatorChain(MULTIPLICATIVE, () => this.unary()) + } + + /** + * @return {object} A negation or a primary. + */ + unary() { + if (!this.isOp(['-'])) { + return this.primary() + } + this.next() + return { type: 'unary', op: '-', operand: this.unary() } + } + + /** + * @return {object} A literal, a parenthesised expression, an `if`, a call or a reference. + * @throws {CalculatedFieldError} When the token cannot start an operand. + */ + primary() { + const token = this.next() + return literalOf(token) ?? this.nonLiteral(token) + } + + /** + * A primary that is not a literal. + * + * @param {object} token - Its first token, consumed. + * @return {object} The AST. + * @throws {CalculatedFieldError} When the token cannot start an operand. + */ + nonLiteral(token) { + switch (token.kind) { + case '(': + return this.parenthesised() + case 'if': + return this.ifCall(token) + case 'name': + return this.peek().kind === '(' ? this.call(token) : referenceOf(token, this.calculatedNames) + default: + throw unexpected(token) + } + } + + /** + * @return {object} The expression inside parentheses, the `(` already consumed. + */ + parenthesised() { + const inner = this.orExpr() + this.expect(')', "')'") + return inner + } + + /** + * @return {Array} A parenthesised, comma-separated argument list. + */ + args() { + this.expect('(', "'('") + const list = this.peek().kind === ')' ? [] : this.argList() + this.expect(')', "')'") + return list + } + + /** + * @return {Array} One or more comma-separated arguments. + */ + argList() { + const list = [this.orExpr()] + while (this.peek().kind === ',') { + this.next() + list.push(this.orExpr()) + } + return list + } + + /** + * @param {object} token - The function name token. + * @return {object} A `call` node. + * @throws {CalculatedFieldError} On an unknown or disallowed function or a wrong argument count. + */ + call(token) { + assertCallable(token, this.allowed) + const list = this.args() + assertArity(token, list.length) + return { type: 'call', name: token.value, args: list } + } + + /** + * @param {object} token - The `if` token. + * @return {object} An `if` node. + * @throws {CalculatedFieldError} Unless it has exactly 3 arguments. + */ + ifCall(token) { + const list = this.args() + if (list.length !== 3) { + throw new CalculatedFieldError({ error: 'arityMismatch', name: 'if', message: `'if' takes 3 arguments, got ${list.length}`, column: token.column }) + } + return { type: 'if', cond: list[0], then: list[1], else: list[2] } + } +} + +/** + * Parse an expression into its AST. + * + * @param {string} expression - The formula. + * @param {object} [options] - Parse options. + * @param {string[]} [options.calculatedNames] - This widget's calculated field names (become `calculatedRef`). + * @param {string[]|null} [options.allowedFunctions] - This instance's allowlist; null allows every built-in. + * @return {object} The AST. + * @throws {CalculatedFieldError} On a syntax error, an unknown or disallowed function, or a wrong number of arguments. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-001-formula-parser-produces-deterministic-ast + */ +export function parse(expression, options = {}) { + const calculatedNames = new Set(options.calculatedNames || []) + const allowed = Array.isArray(options.allowedFunctions) ? new Set(options.allowedFunctions) : null + return new Parser(tokenize(String(expression ?? '')), calculatedNames, allowed).parseAll() +} + +/** + * The child nodes of an AST node. + * + * @param {object} node - The node. + * @return {Array} Its children, possibly undefined. + */ +function childrenOf(node) { + return [node.left, node.right, node.operand, node.cond, node.then, node.else, ...(node.args || [])] +} + +/** + * Collect a node's references, then its children's. + * + * @param {object|undefined} node - The node. + * @param {{fields: Array, calculated: string[]}} found - Extended here. + * @return {void} + */ +function collectReferences(node, found) { + if (!node || typeof node !== 'object') { + return + } + if (node.type === 'fieldRef') { + found.fields.push({ source: node.source, path: node.path }) + } else if (node.type === 'calculatedRef') { + found.calculated.push(node.name) + } + childrenOf(node).forEach((child) => collectReferences(child, found)) +} + +/** + * Every reference an AST makes: widget-relative field refs and calculated refs. + * + * @param {object} ast - The AST. + * @return {{fields: Array<{source: string, path: string}>, calculated: string[]}} + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ +export function referencesOf(ast) { + const found = { fields: [], calculated: [] } + collectReferences(ast, found) + return found +} diff --git a/src/utils/calculatedFields/typeChecker.js b/src/utils/calculatedFields/typeChecker.js new file mode 100644 index 000000000..5aee9a220 --- /dev/null +++ b/src/utils/calculatedFields/typeChecker.js @@ -0,0 +1,361 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Type checking of a calculated field at save time (REQ-CALC-002): the type of + * every sub-expression is inferred from the source fields' schema, and an + * operator or function given arguments it does not take is refused with a + * `CalculatedFieldError` (`typeError` naming the operands, or + * `functionSignature` naming the function and the argument). + * + * Types: number, string, boolean, date, duration, null, list (an array field) + * and any (a field whose type the schema does not say; checked at run time). + * `null` fits every parameter: it propagates to a null result when evaluated. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-002-type-checking-at-save-time + */ + +import { describeNode } from './ast.js' +import { CalculatedFieldError } from './parser.js' + +const NUM = ['number'] +const STR = ['string'] +const DATE = ['date'] +const LIST = ['list'] +const ANY = ['*'] +const NUM_OR_LIST = ['number', 'list'] + +/** + * Each function's parameter types (`params`, then `rest` for every further + * argument) and its return type, or `unify` when it returns the common type + * of the arguments `unify` picks. + */ +const SIGNATURES = Object.freeze({ + abs: { params: [NUM], returns: 'number' }, + round: { params: [NUM, NUM], returns: 'number' }, + ceil: { params: [NUM], returns: 'number' }, + floor: { params: [NUM], returns: 'number' }, + min: { params: [], rest: NUM_OR_LIST, returns: 'number' }, + max: { params: [], rest: NUM_OR_LIST, returns: 'number' }, + pow: { params: [NUM, NUM], returns: 'number' }, + sqrt: { params: [NUM], returns: 'number' }, + log: { params: [NUM, NUM], returns: 'number' }, + sum: { params: [], rest: NUM_OR_LIST, returns: 'number' }, + avg: { params: [], rest: NUM_OR_LIST, returns: 'number' }, + count: { params: [LIST], returns: 'number' }, + countIf: { params: [LIST, ANY], returns: 'number' }, + sumIf: { params: [LIST, LIST, ANY], returns: 'number' }, + avgIf: { params: [LIST, LIST, ANY], returns: 'number' }, + now: { params: [], returns: 'date' }, + today: { params: [], returns: 'date' }, + dateDiff: { params: [DATE, DATE, STR], returns: 'number' }, + dateAdd: { params: [DATE, NUM, STR], returns: 'date' }, + formatDate: { params: [DATE, STR], returns: 'string' }, + parseDate: { params: [STR, STR], returns: 'date' }, + durationBetween: { params: [DATE, DATE], returns: 'duration' }, + durationFormat: { params: [['duration', 'number'], STR], returns: 'string' }, + concat: { params: [], rest: ANY, returns: 'string' }, + upper: { params: [STR], returns: 'string' }, + lower: { params: [STR], returns: 'string' }, + trim: { params: [STR], returns: 'string' }, + contains: { params: [STR, STR], returns: 'boolean' }, + startsWith: { params: [STR, STR], returns: 'boolean' }, + endsWith: { params: [STR, STR], returns: 'boolean' }, + replace: { params: [STR, STR, STR], returns: 'string' }, + format: { params: [STR], rest: ANY, returns: 'string' }, + coalesce: { params: [], rest: ANY, unify: (types) => types }, + ifNull: { params: [ANY, ANY], unify: (types) => types }, + case: { params: [], rest: ANY, unify: caseValueTypes }, + toNumber: { params: [ANY], returns: 'number' }, + toString: { params: [ANY], returns: 'string' }, + toBool: { params: [ANY], returns: 'boolean' }, + toDate: { params: [ANY], returns: 'date' }, +}) + +const ARITHMETIC = ['+', '-', '*', '/', '%'] +const ORDERING = ['<', '<=', '>', '>='] +const ORDERABLE = ['number', 'string', 'date', 'duration'] + +/** + * Whether an argument of `actual` type fits a parameter that takes `allowed`. + * + * @param {string} actual The argument's type. + * @param {string[]} allowed The parameter's types (`*` for any). + * @return {boolean} True when it fits. + */ +function fits(actual, allowed) { + return actual === 'any' || actual === 'null' || allowed.includes('*') || allowed.includes(actual) +} + +/** + * The common type of several values (branches, coalesce arguments): `null` + * when all are null, `any` when one is, else the one type they share. + * + * @param {string[]} types The types. + * @param {AstNode[]} nodes The nodes, for the error message. + * @return {string} The common type. + * @throws {CalculatedFieldError} `typeError` when they differ. + */ +function unify(types, nodes) { + const known = types.filter((type) => type !== 'null') + if (known.length === 0) return 'null' + if (known.includes('any')) return 'any' + const first = known[0] + const other = known.findIndex((type) => type !== first) + if (other === -1) return first + const names = nodes.filter((_, i) => types[i] !== 'null').map(describeNode) + throw new CalculatedFieldError({ + error: 'typeError', + message: `The values ${names[0]} (${first}) and ${names[other]} (${known[other]}) do not have the same type`, + operands: [names[0], names[other]], + }) +} + +/** + * The value types of a `case(cond1, value1, cond2, value2, …, default?)`: every + * second argument, plus a trailing default. The conditions must be boolean. + * + * @param {string[]} types The argument types. + * @param {AstNode[]} args The arguments. + * @return {{types: string[], nodes: AstNode[]}} The value types and nodes. + * @throws {CalculatedFieldError} `functionSignature` for a non-boolean condition. + */ +function caseValueTypes(types, args) { + const values = [] + const nodes = [] + for (let i = 0; i < types.length; i += 2) { + if (i + 1 >= types.length) { + values.push(types[i]) + nodes.push(args[i]) + break + } + if (!fits(types[i], ['boolean'])) { + throw signatureError('case', i, args[i], types[i], ['boolean']) + } + values.push(types[i + 1]) + nodes.push(args[i + 1]) + } + return { types: values, nodes } +} + +/** + * A refused function argument. + * + * @param {string} name The function. + * @param {number} index The argument's position (0-based). + * @param {AstNode} node The argument. + * @param {string} actual Its type. + * @param {string[]} allowed What the parameter takes. + * @return {CalculatedFieldError} The error. + */ +function signatureError(name, index, node, actual, allowed) { + return new CalculatedFieldError({ + error: 'functionSignature', + name, + argument: index + 1, + message: `'${name}' argument ${index + 1} must be ${allowed.join(' or ')}, got ${describeNode(node)} (${actual})`, + }) +} + +/** + * The calculated-field type of each JSON-schema type other than string. + */ +const PROPERTY_TYPES = { + number: 'number', + integer: 'number', + boolean: 'boolean', + array: 'list', + date: 'date', + duration: 'duration', +} + +/** + * The calculated-field type of a string property, by its format. + */ +const STRING_FORMAT_TYPES = { + date: 'date', + 'date-time': 'date', + duration: 'duration', +} + +/** + * The type of a schema property: number, string, boolean, date, duration, + * list, or any when the schema does not say. + * + * @param {unknown} property A JSON-schema property, or a type name. + * @return {string} The calculated-field type. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-002-type-checking-at-save-time + */ +export function typeOfProperty(property) { + const spec = typeof property === 'string' ? { type: property } : (property || {}) + const type = Array.isArray(spec.type) ? spec.type.find((t) => t !== 'null') : spec.type + if (type === 'string') return Object.hasOwn(STRING_FORMAT_TYPES, spec.format) ? STRING_FORMAT_TYPES[spec.format] : 'string' + return Object.hasOwn(PROPERTY_TYPES, type) ? PROPERTY_TYPES[type] : 'any' +} + +/** + * The type of a dotted path in a field schema, which is either a flat map + * (`{ revenue: 'number' }`) or a JSON schema with nested `properties`. + * + * @param {object|null} schema The field schema. + * @param {string} path The dotted path. + * @return {string} The type, or any when the schema does not know the path. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-002-type-checking-at-save-time + */ +export function typeOfPath(schema, path) { + if (!schema || typeof schema !== 'object') return 'any' + if (!schema.properties && Object.hasOwn(schema, path)) { + return typeOfProperty(schema[path]) + } + let node = schema + for (const part of path.split('.')) { + const next = node?.properties?.[part] ?? (node?.type === 'array' ? node.items?.properties?.[part] : undefined) + if (!next) return 'any' + node = next + } + return typeOfProperty(node) +} + +/** + * The type of a binary expression. + * + * @param {object} node The binary node. + * @param {string} left The left operand's type. + * @param {string} right The right operand's type. + * @return {string} The result type. + * @throws {CalculatedFieldError} `typeError` naming both operands. + */ +function binaryType(node, left, right) { + const refuse = () => new CalculatedFieldError({ + error: 'typeError', + message: `Cannot apply '${node.op}' to ${describeNode(node.left)} (${left}) and ${describeNode(node.right)} (${right})`, + operands: [describeNode(node.left), describeNode(node.right)], + }) + const known = [left, right].filter((type) => type !== 'any' && type !== 'null') + const result = operatorResult(node.op, known) + if (result === null) throw refuse() + return result +} + +/** + * The result type of a binary operator on its known operand types, or null + * when it does not take them: arithmetic on numbers, and/or on booleans, + * ordering on orderable types, and comparison on two of the same type. + * + * @param {string} op The operator. + * @param {string[]} known The operand types that are not any or null. + * @return {string|null} The result type, or null. + */ +function operatorResult(op, known) { + if (ARITHMETIC.includes(op)) return known.every((type) => type === 'number') ? 'number' : null + if (op === 'and' || op === 'or') return known.every((type) => type === 'boolean') ? 'boolean' : null + if (ORDERING.includes(op) && known.some((type) => !ORDERABLE.includes(type))) return null + return known.length === 2 && known[0] !== known[1] ? null : 'boolean' +} + +/** + * The type of a call, checking every argument against the signature. + * + * @param {object} node The call node. + * @param {string[]} types The argument types. + * @return {string} The return type. + * @throws {CalculatedFieldError} `functionSignature` for an argument it does not take. + */ +function callType(node, types) { + const signature = SIGNATURES[node.name] + if (!signature) { + throw new CalculatedFieldError({ error: 'unknownFunction', name: node.name, message: `Unknown function '${node.name}'` }) + } + types.forEach((type, i) => { + const allowed = i < signature.params.length ? signature.params[i] : signature.rest + if (allowed && !fits(type, allowed)) { + throw signatureError(node.name, i, node.args[i], type, allowed) + } + }) + if (!signature.unify) return signature.returns + const picked = signature.unify(types, node.args) + return Array.isArray(picked) ? unify(picked, node.args) : unify(picked.types, picked.nodes) +} + +/** + * The type of a unary expression: not takes a boolean, minus a number or a duration. + * + * @param {object} node The unary node. + * @param {object} env The inference environment. + * @return {string} The type. + * @throws {CalculatedFieldError} `typeError` naming the operand. + */ +function unaryType(node, env) { + const type = env.infer(node.operand) + const allowed = node.op === 'not' ? ['boolean'] : ['number', 'duration'] + if (!fits(type, allowed)) { + throw new CalculatedFieldError({ + error: 'typeError', + message: `Cannot apply '${node.op}' to ${describeNode(node.operand)} (${type})`, + operands: [describeNode(node.operand)], + }) + } + if (node.op === 'not') return 'boolean' + return type === 'duration' ? 'duration' : 'number' +} + +/** + * The type of an if expression: a boolean condition and the unified branches. + * + * @param {object} node The if node. + * @param {object} env The inference environment. + * @return {string} The type. + * @throws {CalculatedFieldError} `typeError` for a condition that is not boolean. + */ +function ifType(node, env) { + const cond = env.infer(node.cond) + if (!fits(cond, ['boolean'])) { + throw new CalculatedFieldError({ + error: 'typeError', + message: `The condition ${describeNode(node.cond)} must be boolean, got ${cond}`, + operands: [describeNode(node.cond)], + }) + } + return unify([env.infer(node.then), env.infer(node.else)], [node.then, node.else]) +} + +/** + * How the type of each node type is inferred. + */ +const NODE_TYPES = { + literal: (node) => node.valueType, + fieldRef: (node, env) => (node.source === 'self' + ? typeOfPath(env.fieldSchema, node.path) + : typeOfPath(env.widgetSchemas[node.source.slice('widget:'.length)], node.path)), + calculatedRef: (node, env) => env.calculatedTypes[node.name] || 'any', + unary: unaryType, + binary: (node, env) => binaryType(node, env.infer(node.left), env.infer(node.right)), + if: ifType, + call: (node, env) => callType(node, node.args.map(env.infer)), +} + +/** + * Infer the type of an expression, refusing one whose operators or functions + * get arguments they do not take. + * + * @param {AstNode} ast The parsed expression. + * @param {object|null} fieldSchema The widget's source fields: a flat map or a JSON schema. + * @param {{calculatedTypes?: object, widgetSchemas?: object}} [options] Types of this widget's other calculated fields, and the field schemas of other widgets by id. + * @return {string} The expression's type. + * @throws {CalculatedFieldError} `typeError`, `functionSignature` or `unknownFunction`. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-002-type-checking-at-save-time + */ +export function inferType(ast, fieldSchema, options = {}) { + const env = { + fieldSchema, + calculatedTypes: options.calculatedTypes || {}, + widgetSchemas: options.widgetSchemas || {}, + } + env.infer = (node) => { + if (!Object.hasOwn(NODE_TYPES, node.type)) { + throw new CalculatedFieldError({ error: 'typeError', message: `Unknown node '${node.type}'` }) + } + return NODE_TYPES[node.type](node, env) + } + return env.infer(ast) +} diff --git a/src/utils/calculatedFields/validate.js b/src/utils/calculatedFields/validate.js new file mode 100644 index 000000000..9d56ca89d --- /dev/null +++ b/src/utils/calculatedFields/validate.js @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2026 Conduction B.V. + +/** + * Validation of a widget's calculated fields before it is saved (REQ-CALC-001, + * REQ-CALC-002, REQ-CALC-006): every expression is parsed against the allowed + * functions, the dashboard is checked for cycles, and each field's type is + * inferred in dependency order so a field reading another one knows its type. + * The first refusal is thrown with the field it concerns. + * + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ + +import { allowedFunctions } from './config.js' +import { assertAcyclic } from './cycleDetector.js' +import { CalculatedFieldError, parse } from './parser.js' +import { inferType } from './typeChecker.js' + +/** + * A refusal with the field it concerns added to its detail. + * + * @param {CalculatedFieldError} error The refusal. + * @param {string} field The field name. + * @return {CalculatedFieldError} The same error. + */ +function forField(error, field) { + if (error instanceof CalculatedFieldError && error.detail.field === undefined) { + error.detail = { ...error.detail, field } + } + return error +} + +/** + * Refuse a widget that declares a calculated field name twice. + * + * @param {string[]} names The declared names, in order. + * @return {void} + * @throws {CalculatedFieldError} `duplicateField`. + */ +function assertUniqueNames(names) { + const duplicate = names.find((name, i) => names.indexOf(name) !== i) + if (duplicate !== undefined) { + throw new CalculatedFieldError({ error: 'duplicateField', field: duplicate, message: `The calculated field '${duplicate}' is declared twice` }) + } +} + +/** + * One declared field with its compiled expression. + * + * @param {{name: string, expression: string}} field The declared field. + * @param {string[]} names The widget's calculated field names. + * @param {Set|null} allowed The allowed functions. + * @return {object} The field with `compiledExpression`. + * @throws {CalculatedFieldError} The parse error, naming the field. + */ +function compileField(field, names, allowed) { + try { + return { ...field, compiledExpression: parse(field.expression, { calculatedNames: names, allowedFunctions: allowed }) } + } catch (e) { + throw forField(e, field.name) + } +} + +/** + * Type-check this widget's fields in evaluation order, setting each field's + * `returnType` so later fields see the types of the ones they read. + * + * @param {string} id The widget id. + * @param {Array} fields The compiled fields. + * @param {string[]} order The dashboard's evaluation order. + * @param {object} options As for {@link parseAndValidate}. + * @return {void} + * @throws {CalculatedFieldError} The type error, naming the field. + */ +function typeFields(id, fields, order, options) { + const calculatedTypes = {} + const byName = new Map(fields.map((field) => [field.name, field])) + for (const node of order.filter((entry) => entry.startsWith(`${id}.`))) { + const field = byName.get(node.slice(id.length + 1)) + try { + field.returnType = inferType(field.compiledExpression, options.fieldSchema ?? null, { + calculatedTypes, + widgetSchemas: options.widgetSchemas ?? {}, + }) + } catch (e) { + throw forField(e, field.name) + } + calculatedTypes[field.name] = field.returnType + } +} + +/** + * Parse, cycle-check and type-check a widget's calculated fields. + * + * @param {{id: string|number, calculatedFields?: Array<{name: string, expression: string}>}} widget The widget being saved. + * @param {{fieldSchema?: object, otherWidgets?: Array, widgetSchemas?: object, setting?: object}} [options] The widget's source fields, the dashboard's other widgets (with compiled fields), their field schemas by id, and the instance's function setting. + * @return {{fields: Array, order: string[]}} The fields with `compiledExpression` and `returnType`, and the dashboard's evaluation order. + * @throws {CalculatedFieldError} parseError, unknownFunction, arityMismatch, typeError, functionSignature or cycleDetected. + * @spec openspec/changes/widget-calculated-fields/specs/calculated-fields/spec.md#requirement-req-calc-006-cross-widget-references-with-cycle-detection + */ +export function parseAndValidate(widget, options = {}) { + const id = String(widget.id) + const declared = Array.isArray(widget.calculatedFields) ? widget.calculatedFields : [] + const names = declared.map((field) => field.name) + assertUniqueNames(names) + const allowed = allowedFunctions(options.setting) + const fields = declared.map((field) => compileField(field, names, allowed)) + + const others = (options.otherWidgets || []).filter((other) => String(other.id) !== id) + const order = assertAcyclic([{ id, calculatedFields: fields }, ...others]) + typeFields(id, fields, order, options) + return { fields, order } +} diff --git a/src/utils/calendarPeriod.js b/src/utils/calendarPeriod.js new file mode 100644 index 000000000..aab31fef8 --- /dev/null +++ b/src/utils/calendarPeriod.js @@ -0,0 +1,42 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The Calendar form's period (REQ-CAL-020) over the content the Calendar + * renderer reads: 7 days is the agenda over seven days, Month the month view. + */ + +/** + * The period of stored content: Month for the month view, else 7 days. + * + * @param {{viewMode?: string}|null} content The stored content. + * @return {'week'|'month'} the period. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ +export function periodOf(content) { + return content?.viewMode === 'month' ? 'month' : 'week' +} + +/** + * The renderer fields for a period. + * + * @param {'week'|'month'} period The period. + * @return {{viewMode: string, daysAhead: number}} the fields. + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ +export function contentForPeriod(period) { + return period === 'month' + ? { viewMode: 'month', daysAhead: 31 } + : { viewMode: 'agenda', daysAhead: 7 } +} + +/** + * Whether an address can be an external calendar: https with a host. + * + * @param {string} address The address. + * @return {boolean} + * @spec openspec/changes/archive/2026-11-25-widget-content-forms-board-sync/specs/calendar-widget/spec.md#requirement-the-calendar-content-form-req-cal-020 + */ +export function isIcsAddress(address) { + return typeof address === 'string' && /^https:\/\/[^\s/]+/i.test(address.trim()) +} diff --git a/src/utils/clickedRow.js b/src/utils/clickedRow.js new file mode 100644 index 000000000..12ed12839 --- /dev/null +++ b/src/utils/clickedRow.js @@ -0,0 +1,100 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * clickedRow — the fields of the category a reader clicked on a chart, for + * the filter bus (drill-down-cross-widget-filter REQ-CWF-004). + * + * A chart click names only the field the chart groups by. When that field is + * published as a hierarchy level (a wijk), the bus infers the levels above it + * (gemeente, provincie) from the clicked row, so the row is completed from + * one record of the clicked category: each ancestor is read from the + * record's field named like the ancestor's dimension. A record that cannot be + * read leaves the row as it was, and the bus skips those levels with a + * warning. + */ + +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' +import { ancestorDimensions } from '../composables/useFilterBus.js' + +/** + * Whether a value is missing: undefined, null or empty text. + * + * @param {unknown} value The value. + * @return {boolean} + */ +function isBlank(value) { + return value === undefined || value === null || value === '' +} + +/** + * The ancestor dimensions the clauses need that the row does not hold. + * + * @param {Array} hierarchies The dashboard's hierarchy descriptors. + * @param {Array<{dimension: string}>} clauses The clauses the click publishes. + * @param {object} row The row so far. + * @return {string[]} + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ +export function missingAncestors(hierarchies, clauses, row) { + const missing = new Set() + for (const clause of clauses) { + for (const dimension of ancestorDimensions(hierarchies, clause.dimension)) { + if (isBlank(row[dimension])) { + missing.add(dimension) + } + } + } + return [...missing] +} + +/** + * The first record of the clicked category in the chart's register and + * schema, or null when it cannot be read. + * + * @param {{register: string, schema: string}} source The chart's data source. + * @param {string} field The grouped field. + * @param {unknown} value The clicked key. + * @return {Promise} + */ +async function firstRecord(source, field, value) { + try { + const { data } = await axios.get( + generateUrl('/apps/openregister/api/objects/{register}/{schema}', { register: source.register, schema: source.schema }), + { params: { [field]: value, _limit: 1 } }, + ) + const results = Array.isArray(data?.results) ? data.results : [] + return results[0] && typeof results[0] === 'object' ? results[0] : null + } catch { + return null + } +} + +/** + * The clicked row: the grouped field with the clicked key and, when the + * published clauses are hierarchy levels, the ancestor fields of one record + * of that category. + * + * @param {object} options The click. + * @param {{field: string, value: unknown}} options.selection CnChartWidget's `select` payload. + * @param {Array<{dimension: string}>} options.clauses The clauses the click publishes. + * @param {Array} options.hierarchies The dashboard's hierarchy descriptors. + * @param {object|null} options.dataSource The chart's data source (`register`, `schema`). + * @return {Promise} The row. + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/specs/cross-widget-filter/spec.md#requirement-req-cwf-004-drill-down-hierarchies-update-breadcrumb-and-descendant-filters + */ +export async function clickedRow({ selection, clauses, hierarchies, dataSource }) { + const row = { [selection.field]: selection.value } + const missing = missingAncestors(hierarchies, clauses, row) + if (missing.length === 0 || !selection.field || !dataSource?.register || !dataSource?.schema) { + return row + } + const record = await firstRecord(dataSource, selection.field, selection.value) + for (const dimension of missing) { + if (record && !isBlank(record[dimension])) { + row[dimension] = record[dimension] + } + } + return row +} diff --git a/src/utils/customCss.js b/src/utils/customCss.js new file mode 100644 index 000000000..c68169b56 --- /dev/null +++ b/src/utils/customCss.js @@ -0,0 +1,57 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Administrator CSS on the page (platform-dashboard-theme-and-css + * REQ-THM-003, design D4). The server stores only cleaned and scoped CSS; + * the page inserts it as the text of a ` diff --git a/src/views/AdminSettingsRedirect.vue b/src/views/AdminSettingsRedirect.vue index 4727cf130..aa51e3105 100644 --- a/src/views/AdminSettingsRedirect.vue +++ b/src/views/AdminSettingsRedirect.vue @@ -14,21 +14,17 @@ + + diff --git a/src/views/KioskPlayerView.vue b/src/views/KioskPlayerView.vue index 513648baf..badcc7590 100644 --- a/src/views/KioskPlayerView.vue +++ b/src/views/KioskPlayerView.vue @@ -16,10 +16,56 @@ v-else-if="current" class="kiosk-player__dashboard" data-testid="kiosk-dashboard"> -

- {{ current.dashboard?.name || current.dashboard?.title || '' }} -

- + +
+ +

+ {{ current.dashboard?.name || current.dashboard?.title || '' }} +

+

+ {{ clockTime }} + {{ clockDate }} +

+
+ + + +

+ {{ announcement }} +

+

+ {{ t('launchpad', 'Reconnecting…') }} +

{{ t('launchpad', 'This playlist has no dashboards to show.') }} @@ -32,16 +78,44 @@ import axios from '@nextcloud/axios' import { translate as t } from '@nextcloud/l10n' import { generateUrl } from '@nextcloud/router' import PublicDashboardGrid from '../components/PublicDashboardGrid.vue' +import { REQUIRED_TEXT_PROP } from '../constants/propDefinitions.js' +import { kioskWidgetReader } from '../services/publicWidgetClient.js' +import { houseEmblem } from '../utils/houseEmblem.js' +import { hideCursorWhenIdle } from '../utils/kioskMode.js' + +/** + * The locale Nextcloud renders the page in (``), for the + * band's clock; undefined lets the browser choose. + * + * @return {string|undefined} + */ +function pageLocale() { + const locale = document.documentElement?.dataset?.locale || '' + return locale === '' ? undefined : locale.replace('_', '-') +} /** A network failure is retried this soon, whatever the refresh interval. */ const RETRY_MS = 30 * 1000 +/** The next entry is fetched this long before its turn (REQ-KIOSK-004). */ +export const PREFETCH_LEAD_MS = 5 * 1000 + +/** An entry that has not loaded this long after its turn is skipped (REQ-KIOSK-005). */ +export const ENTRY_TIMEOUT_MS = 10 * 1000 + /** * KioskPlayerView: the full-screen player behind a kiosk link. It shows * each dashboard of the playlist for its dwell time, starts over at the * end, re-reads the playlist every `refreshSeconds`, shows a message once * the link is revoked (404), and keeps the last good playlist when the - * network fails, retrying every 30 seconds. No login and no controls. + * network fails, retrying every 30 seconds with a small reconnect indicator + * on screen until a read succeeds. No login and no controls. + * + * Each next entry is fetched on its own about 5 seconds before its turn, so + * the screen shows fresh data without a loading state (REQ-KIOSK-004). An + * entry that fails, or has not loaded 10 seconds after its turn, is skipped + * without a message and tried again on the next loop (REQ-KIOSK-005). The + * cursor hides after 10 seconds without pointer movement (REQ-KIOSK-001). * * @spec openspec/specs/dashboard-kiosk-mode/spec.md */ @@ -53,13 +127,13 @@ export default { }, props: { - token: { - type: String, - required: true, - }, + token: REQUIRED_TEXT_PROP, }, - /** @spec openspec/specs/dashboard-kiosk-mode/spec.md */ + /** + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 + */ data() { return { entries: [], @@ -67,12 +141,60 @@ export default { refreshSeconds: 300, unavailable: false, loaded: false, + offline: false, dwellTimer: null, + prefetchTimer: null, refreshTimer: null, + prefetched: null, + advancing: false, + stopCursor: null, + shownAt: 0, + dwellMs: 0, + nowMs: Date.now(), + tickTimer: null, + announcement: '', + clockMs: Date.now(), + clockTimer: null, } }, computed: { + /** + * The live widgets' token-scoped read through this playlist (REQ-PSHR-011). + * + * @return {function((number|string)): Promise} The read. + * @spec openspec/changes/archive/2026-11-24-public-live-widgets/specs/dashboard-public-share/spec.md#requirement-live-widgets-on-a-public-link-and-a-kiosk-screen-req-pshr-011 + */ + readWidget() { + return kioskWidgetReader(this.token) + }, + + /** + * The emblem of the house style, else Nextcloud's logo. + * + * @return {string} The image address, or ''. + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + emblem() { + return houseEmblem() + }, + + /** + * @return {string} The time in the band, hours and minutes. + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + clockTime() { + return new Date(this.clockMs).toLocaleTimeString(pageLocale(), { hour: '2-digit', minute: '2-digit' }) + }, + + /** + * @return {string} The date in the band, weekday, day and month. + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + clockDate() { + return new Date(this.clockMs).toLocaleDateString(pageLocale(), { weekday: 'long', day: 'numeric', month: 'long' }) + }, + /** * @return {object|null} The entry on screen now. * @spec openspec/specs/dashboard-kiosk-mode/spec.md @@ -80,16 +202,64 @@ export default { current() { return this.entries[this.index] ?? null }, + + /** + * The position line: "2 of 4 · next in 18 s", or '' for a playlist + * of one dashboard or none. + * + * @return {string} + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 + */ + positionText() { + if (this.entries.length <= 1 || !this.current) { + return '' + } + const seconds = Math.max(0, Math.ceil((this.shownAt + this.dwellMs - this.nowMs) / 1000)) + return t('launchpad', '{index} of {total} · next in {seconds} s', { + index: this.index + 1, + total: this.entries.length, + seconds, + }) + }, + }, + + watch: { + /** + * The band's clock runs while a dashboard shows. + * + * @param {object|null} entry The entry on screen. + * @return {void} + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + current(entry) { + if (entry && this.clockTimer === null) { + this.clockMs = Date.now() + this.clockTimer = setInterval(() => { + this.clockMs = Date.now() + }, 15000) + } + }, }, - /** @spec openspec/specs/dashboard-kiosk-mode/spec.md */ + /** + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 + */ async mounted() { + this.stopCursor = hideCursorWhenIdle(document) await this.load() }, - /** @spec openspec/specs/dashboard-kiosk-mode/spec.md */ + /** + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 + */ beforeUnmount() { + this.stopCursor?.() + clearInterval(this.tickTimer) + clearInterval(this.clockTimer) clearTimeout(this.dwellTimer) + clearTimeout(this.prefetchTimer) clearTimeout(this.refreshTimer) }, @@ -112,6 +282,7 @@ export default { { headers: { Accept: 'application/json' } }, ) this.apply(data) + this.offline = false next = this.refreshSeconds * 1000 } catch (error) { const status = error?.response?.status @@ -124,6 +295,7 @@ export default { // Anything else is a blip: keep what is on screen. next = RETRY_MS this.loaded = true + this.offline = true } clearTimeout(this.refreshTimer) this.refreshTimer = setTimeout(() => this.load(), next) @@ -148,27 +320,152 @@ export default { this.entries = entries this.unavailable = false this.loaded = true - if (firstLoad || this.dwellTimer === null) { + if (firstLoad || (this.dwellTimer === null && !this.advancing)) { this.scheduleNext() } }, /** - * Show the current entry for its dwell time, then move on. + * Show the current entry for its dwell time, fetch the next one + * shortly before the end, then move on. * * @spec openspec/specs/dashboard-kiosk-mode/spec.md + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 */ scheduleNext() { clearTimeout(this.dwellTimer) + clearTimeout(this.prefetchTimer) this.dwellTimer = null + this.syncTick() if (this.entries.length === 0) { return } - const dwell = Math.max(10, Number(this.current?.dwellSeconds) || 10) - this.dwellTimer = setTimeout(() => { - this.index = (this.index + 1) % this.entries.length - this.scheduleNext() - }, dwell * 1000) + const dwellMs = Math.max(10, Number(this.current?.dwellSeconds) || 10) * 1000 + this.dwellMs = dwellMs + this.shownAt = Date.now() + this.nowMs = this.shownAt + const next = (this.index + 1) % this.entries.length + this.prefetchTimer = setTimeout( + () => this.prefetch(next), + Math.max(0, dwellMs - PREFETCH_LEAD_MS), + ) + this.dwellTimer = setTimeout(() => this.advance(), dwellMs) + }, + + /** + * Start fetching an entry before its turn. + * + * @param {number} index The entry's position in the playlist. + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + prefetch(index) { + const entry = this.entries[index] + if (entry) { + this.prefetched = { index, uuid: entry.dashboard?.uuid, result: this.fetchEntry(entry) } + } + }, + + /** + * Fetch one entry's render payload, or null when it fails. + * + * @param {object} entry The entry as the playlist read gave it. + * @return {Promise} The fresh entry, or null. + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + fetchEntry(entry) { + const uuid = entry?.dashboard?.uuid + if (!uuid) { + return Promise.resolve(null) + } + return axios + .get( + generateUrl( + `/apps/launchpad/kiosk/${encodeURIComponent(this.token)}/dashboards/${encodeURIComponent(uuid)}`, + ), + { headers: { Accept: 'application/json' } }, + ) + .then(({ data }) => (data?.dashboard ? { ...entry, ...data } : null)) + .catch(() => null) + }, + + /** + * Wait for an entry's read from the moment its turn comes, or null + * once it has not answered within the entry timeout (REQ-KIOSK-005). + * + * @param {Promise} read The entry's read. + * @return {Promise} The fresh entry, or null. + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + */ + withinEntryTimeout(read) { + let timer = null + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(null), ENTRY_TIMEOUT_MS) + }) + return Promise.race([read, timeout]).finally(() => clearTimeout(timer)) + }, + + /** + * Move to the next entry that loads: the prefetched one when it + * arrived, otherwise each following entry in turn. A failed entry + * is skipped this loop only. When none loads, the screen keeps what + * it shows. + * + * @return {Promise} + * @spec openspec/specs/dashboard-kiosk-mode/spec.md + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 + */ + async advance() { + this.dwellTimer = null + this.advancing = true + const count = this.entries.length + for (let step = 1; step <= count; step++) { + const index = (this.index + step) % count + const entry = this.entries[index] + const ready = this.prefetched?.index === index && this.prefetched.uuid === entry?.dashboard?.uuid + const fresh = await this.withinEntryTimeout(ready ? this.prefetched.result : this.fetchEntry(entry)) + if (fresh !== null && this.entries[index]?.dashboard?.uuid === fresh.dashboard?.uuid) { + const moved = index !== this.index + this.entries.splice(index, 1, fresh) + this.index = index + if (moved) { + this.announce(fresh) + } + break + } + } + this.prefetched = null + this.advancing = false + this.scheduleNext() + }, + + /** + * Count the seconds down only while a playlist of more than one + * dashboard plays; a single dashboard or none needs no clock. + * + * @return {void} + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 + */ + syncTick() { + if (this.entries.length > 1 && this.tickTimer === null) { + this.tickTimer = setInterval(() => { + this.nowMs = Date.now() + }, 1000) + } else if (this.entries.length <= 1 && this.tickTimer !== null) { + clearInterval(this.tickTimer) + this.tickTimer = null + } + }, + + /** + * Tell screen readers, politely, which dashboard now shows. + * + * @param {object} entry The entry now on screen. + * @return {void} + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 + */ + announce(entry) { + const name = entry?.dashboard?.name || entry?.dashboard?.title || '' + this.announcement = name === '' ? '' : t('launchpad', 'Now showing {name}', { name }) }, /** @@ -178,24 +475,165 @@ export default { */ stop() { clearTimeout(this.dwellTimer) + clearTimeout(this.prefetchTimer) this.dwellTimer = null + this.prefetched = null this.entries = [] + this.syncTick() }, }, } diff --git a/src/views/__tests__/AdminPage.spec.js b/src/views/__tests__/AdminPage.spec.js new file mode 100644 index 000000000..0374964f3 --- /dev/null +++ b/src/views/__tests__/AdminPage.spec.js @@ -0,0 +1,159 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The administration as a Launchpad page (admin-settings REQ-ADM-030): the + * tab comes from the route, opening another tab pushes its address, a page + * reached inside the app loads the address from the server, and the More + * menu links to the page. + */ + +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +const boot = vi.hoisted(() => ({ path: '/index.php/apps/launchpad/admin/general' })) + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => '/index.php' + path, +})) +vi.mock('../../utils/bootPath.js', () => ({ + bootPath: () => boot.path, +})) +vi.mock('../../utils/loadInitialState.js', () => ({ + loadInitialState: () => ({ allGroups: [{ id: 'staff', displayName: 'Staff' }] }), +})) +vi.mock('../../components/admin/AdminSettings.vue', () => ({ + default: { + name: 'AdminSettings', + props: ['tab'], + emits: ['tabChange'], + inject: { allGroups: { default: () => [] } }, + template: '
', + }, +})) +vi.mock('../AdminSettingsRedirect.vue', () => ({ + default: { + name: 'AdminSettingsRedirect', + props: ['tab'], + template: '
', + }, +})) + +import AdminPage from '../AdminPage.vue' +import { startPageSections } from '../../components/Workspace/moreMenuItems.js' +import manifest from '../../manifest.json' +import { ADMIN_TABS, adminPageUrl, adminTab, isAdminPagePath } from '../../utils/adminPage.js' +import { routesFromManifest } from '../../utils/manifestRoutes.js' + +/** + * Mount the page on a route tab. + * + * @param {string} tab The route's tab. + * @return {{ wrapper: object, router: { push: Function } }} + */ +function mountPage(tab) { + const router = { push: vi.fn() } + const wrapper = mount(AdminPage, { + props: { tab }, + global: { mocks: { $router: router } }, + }) + return { wrapper, router } +} + +describe('the administration page address', () => { + it('is /apps/launchpad/admin/, General for an unknown or missing tab', () => { + expect(adminPageUrl('templates')).toBe('/index.php/apps/launchpad/admin/templates') + expect(adminPageUrl()).toBe('/index.php/apps/launchpad/admin/general') + expect(adminPageUrl('settings')).toBe('/index.php/apps/launchpad/admin/general') + expect(adminTab('')).toBe('general') + expect(ADMIN_TABS[0]).toBe('general') + }) + + it('recognises the page under either app prefix', () => { + expect(isAdminPagePath('/index.php/apps/launchpad/admin/embeds')).toBe(true) + expect(isAdminPagePath('/apps/launchpad/admin')).toBe(true) + expect(isAdminPagePath('/apps/launchpad/')).toBe(false) + expect(isAdminPagePath('/apps/launchpad/administration-of-x')).toBe(false) + expect(isAdminPagePath('/settings/admin/launchpad')).toBe(false) + }) + + it('knows the same tabs as the server', async () => { + const { readFileSync } = await import('node:fs') + const { join } = await import('node:path') + const php = readFileSync(join(__dirname, '../../../lib/Controller/AdminPageController.php'), 'utf8') + for (const tab of ADMIN_TABS) { + expect(php).toContain(`'${tab}',`) + } + }) +}) + +describe('AdminPage', () => { + it('opens the tab the route names', () => { + const { wrapper } = mountPage('embeds') + expect(wrapper.find('[data-testid="admin-settings"]').attributes('data-tab')).toBe('embeds') + }) + + it('opens General for an unknown or missing tab', () => { + expect(mountPage('nonsense').wrapper.find('[data-testid="admin-settings"]').attributes('data-tab')).toBe('general') + expect(mountPage('').wrapper.find('[data-testid="admin-settings"]').attributes('data-tab')).toBe('general') + }) + + it('hands the administration initial state to the tabs', () => { + const { wrapper } = mountPage('general') + expect(wrapper.find('[data-testid="admin-settings"]').attributes('data-groups')).toBe('1') + }) + + it('puts an opened tab in the address as a new history entry', async () => { + const { wrapper, router } = mountPage('general') + await wrapper.findComponent({ name: 'AdminSettings' }).vm.$emit('tabChange', 'sharing') + expect(router.push).toHaveBeenCalledWith({ name: 'admin-settings', params: { tab: 'sharing' } }) + }) + + it('pushes nothing for the tab already open', async () => { + const { wrapper, router } = mountPage('sharing') + await wrapper.findComponent({ name: 'AdminSettings' }).vm.$emit('tabChange', 'sharing') + expect(router.push).not.toHaveBeenCalled() + }) + + it('loads the page from the server when reached from another page of the app', () => { + boot.path = '/index.php/apps/launchpad/' + try { + const { wrapper } = mountPage('templates') + expect(wrapper.find('[data-testid="admin-settings"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="admin-redirect"]').attributes('data-tab')).toBe('templates') + } finally { + boot.path = '/index.php/apps/launchpad/admin/general' + } + }) +}) + +describe('the administration routes', () => { + const routes = routesFromManifest(manifest, {}) + + it('serve /admin/:tab? and /admin/templates with the page, for administrators', () => { + const admin = routes.find((route) => route.name === 'admin-settings') + expect(admin.path).toBe('/admin/:tab?') + expect(admin.props).toBe(true) + expect(admin.meta.permission).toBe('admin') + const page = manifest.pages.find((p) => p.id === 'admin-settings') + expect(page.component).toBe('AdminPage') + const templates = manifest.pages.find((p) => p.id === 'admin-templates-index') + expect(templates.component).toBe('AdminPage') + expect(templates.config.tab).toBe('templates') + }) +}) + +describe('the More menu', () => { + it('links an administrator to the administration page on General', () => { + const chrome = { entries: [], isAdmin: true, includePersonalSettings: false } + const link = startPageSections(chrome, null).settings.find((item) => item.id === 'admin-settings-link') + expect(link.href).toBe('/index.php/apps/launchpad/admin/general') + expect(link.external).toBe(false) + }) + + it('offers a member no administration link', () => { + const chrome = { entries: [], isAdmin: false, includePersonalSettings: false } + const ids = startPageSections(chrome, null).settings.map((item) => item.id) + expect(ids).not.toContain('admin-settings-link') + }) +}) diff --git a/src/views/__tests__/AdminSettingsRedirect.spec.js b/src/views/__tests__/AdminSettingsRedirect.spec.js new file mode 100644 index 000000000..b5d7ac755 --- /dev/null +++ b/src/views/__tests__/AdminSettingsRedirect.spec.js @@ -0,0 +1,64 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `AdminSettingsRedirect.vue`: on mount it sends the + * browser to the Launchpad administration page on the route's tab + * (admin-settings REQ-ADM-030), and shows a link to the same page for when + * the redirect does not happen. + */ + +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import AdminSettingsRedirect from '../AdminSettingsRedirect.vue' + +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => '/index.php' + path, +})) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, +})) + +const originalLocation = window.location + +beforeEach(() => { + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: { href: 'http://localhost/index.php/apps/launchpad/admin' }, + }) +}) + +afterEach(() => { + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: originalLocation, + }) +}) + +describe('AdminSettingsRedirect', () => { + it('sends the browser to the administration page on mount', () => { + mount(AdminSettingsRedirect) + + expect(window.location.href).toBe('/index.php/apps/launchpad/admin/general') + }) + + it('opens the tab it is given, and General for an unknown one', () => { + mount(AdminSettingsRedirect, { props: { tab: 'templates' } }) + expect(window.location.href).toBe('/index.php/apps/launchpad/admin/templates') + + mount(AdminSettingsRedirect, { props: { tab: 'settings' } }) + expect(window.location.href).toBe('/index.php/apps/launchpad/admin/general') + }) + + it('shows a link to the same page as a fallback', () => { + const wrapper = mount(AdminSettingsRedirect) + + const link = wrapper.find('[data-testid="AdminSettingsRedirect"] a') + expect(link.attributes('href')).toBe('/index.php/apps/launchpad/admin/general') + expect(link.text()).toBe('Continue to the administration settings') + expect(wrapper.find('p').text()).toBe('Opening the administration settings…') + }) +}) diff --git a/src/views/__tests__/DashboardPublicShareView.errorIcon.spec.js b/src/views/__tests__/DashboardPublicShareView.errorIcon.spec.js new file mode 100644 index 000000000..81d86f481 --- /dev/null +++ b/src/views/__tests__/DashboardPublicShareView.errorIcon.spec.js @@ -0,0 +1,74 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * DashboardPublicShareView: the error state puts the alert icon in the + * empty-content icon slot, next to the not-found title and description. + * Only HTTP, the share store and the layout components are doubled; the + * icon itself is the real one. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import DashboardPublicShareView from '../DashboardPublicShareView.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => '/index.php' + path, +})) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, +})) + +const shareStore = { + isUnlocked: vi.fn(), + clearUnlocked: vi.fn(), + markUnlocked: vi.fn(), +} +vi.mock('../../stores/publicShares.js', () => ({ + usePublicShareStore: () => shareStore, +})) + +beforeEach(() => { + vi.clearAllMocks() + shareStore.isUnlocked.mockReturnValue(false) +}) + +describe('DashboardPublicShareView error icon', () => { + it('renders the alert icon in the empty-content icon slot for a missing share', async () => { + axios.get.mockRejectedValue(Object.assign(new Error('HTTP 404'), { response: { status: 404, data: {} } })) + const wrapper = mount(DashboardPublicShareView, { + props: { token: 'tok' }, + global: { + stubs: { + PublicSharePasswordDialog: true, + PublicDashboardGrid: true, + NcLoadingIcon: true, + NcEmptyContent: { + name: 'NcEmptyContent', + props: ['name', 'description'], + render() { + return h('div', { class: 'empty' }, [ + h('span', { class: 'empty__icon' }, this.$slots.icon?.()), + h('span', { class: 'empty__name' }, this.name), + h('span', { class: 'empty__description' }, this.description), + ]) + }, + }, + }, + }, + }) + await flushPromises() + + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/s/tok/data', { headers: {} }) + expect(wrapper.find('.public-share-view__error').exists()).toBe(true) + expect(wrapper.find('.empty__icon .alert-circle-icon svg').exists()).toBe(true) + expect(wrapper.find('.empty__name').text()).toBe('Not found') + expect(wrapper.find('.empty__description').text()).toBe('This shared dashboard does not exist or has expired.') + }) +}) diff --git a/src/views/__tests__/DashboardPublicShareView.spec.js b/src/views/__tests__/DashboardPublicShareView.spec.js new file mode 100644 index 000000000..0a0015717 --- /dev/null +++ b/src/views/__tests__/DashboardPublicShareView.spec.js @@ -0,0 +1,304 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for `DashboardPublicShareView.vue`, the anonymous + * read-only view of a shared dashboard: the data request for its token, the + * rendered dashboard, the password prompt on a protected share (and dropping + * a stale unlock), not-found and server errors, and the unlock flow — wrong + * password, throttling, a failed check, a double submit, and a successful + * unlock that reloads with the password. + * + * Only HTTP, the share store and child components are doubled. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import DashboardPublicShareView from '../DashboardPublicShareView.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => '/index.php' + path, +})) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, +})) + +const shareStore = { + isUnlocked: vi.fn(), + clearUnlocked: vi.fn(), + markUnlocked: vi.fn(), +} +vi.mock('../../stores/publicShares.js', () => ({ + usePublicShareStore: () => shareStore, +})) + +const TOKEN = 'ab/c d' +const DATA_URL = '/index.php/apps/launchpad/s/ab%2Fc%20d/data' +const UNLOCK_URL = '/index.php/apps/launchpad/s/ab%2Fc%20d/unlock' + +/** + * An error as axios rejects with it. + * + * @param {number} status The HTTP status + * @param {object} data The response body + * @return {Error} The error + */ +function httpError(status, data = {}) { + return Object.assign(new Error('HTTP ' + status), { response: { status, data } }) +} + +/** + * Mount the view for the test token. + * + * @return {Promise} The wrapper, after the first load settled + */ +async function mountView() { + const wrapper = mount(DashboardPublicShareView, { + props: { token: TOKEN }, + global: { + stubs: { + PublicSharePasswordDialog: { + name: 'PublicSharePasswordDialog', + props: ['error', 'loading'], + emits: ['unlock'], + render: () => h('div', { class: 'password-dialog' }), + }, + PublicDashboardGrid: { + name: 'PublicDashboardGrid', + props: ['placements'], + render: () => h('div', { class: 'grid' }), + }, + NcLoadingIcon: { name: 'NcLoadingIcon', render: () => h('span', { class: 'loading-icon' }) }, + NcEmptyContent: { + name: 'NcEmptyContent', + props: ['name', 'description'], + render() { + return h('div', { class: 'empty' }, [this.name, ' | ', this.description]) + }, + }, + AlertCircleIcon: true, + }, + }, + }) + await flushPromises() + return wrapper +} + +const dialog = (wrapper) => wrapper.findComponent({ name: 'PublicSharePasswordDialog' }) + +beforeEach(() => { + vi.clearAllMocks() + shareStore.isUnlocked.mockReturnValue(false) +}) + +describe('DashboardPublicShareView loading', () => { + it('loads the share for its encoded token without a password header', async () => { + axios.get.mockResolvedValue({ data: { dashboard: { name: 'Board' }, share: {}, placements: [] } }) + await mountView() + + expect(axios.get).toHaveBeenCalledWith(DATA_URL, { headers: {} }) + }) + + it('renders the dashboard read-only with its name and description', async () => { + axios.get.mockResolvedValue({ + data: { dashboard: { name: 'Board', description: 'Weekly numbers' }, share: { token: TOKEN }, placements: [{ id: 1 }] }, + }) + const wrapper = await mountView() + + expect(wrapper.find('h1').text()).toBe('Board') + expect(wrapper.find('.public-share-view__badge').text()).toBe('Read-only view') + expect(wrapper.find('.public-share-view__description').text()).toBe('Weekly numbers') + expect(wrapper.findComponent({ name: 'PublicDashboardGrid' }).exists()).toBe(true) + expect(wrapper.vm.share).toEqual({ token: TOKEN }) + }) + + it('hands the shared placements to the grid', async () => { + const placements = [{ id: 1, widgetId: 'text', content: { text: 'Hello' } }] + axios.get.mockResolvedValue({ + data: { dashboard: { name: 'Board' }, share: {}, placements }, + }) + const wrapper = await mountView() + + expect( + wrapper.findComponent({ name: 'PublicDashboardGrid' }).props('placements'), + ).toEqual(placements) + }) + + it('falls back to the title and leaves out an empty description', async () => { + axios.get.mockResolvedValue({ data: { dashboard: { title: 'Titled' }, share: {} } }) + const wrapper = await mountView() + + expect(wrapper.find('h1').text()).toBe('Titled') + expect(wrapper.find('.public-share-view__description').exists()).toBe(false) + }) + + it('shows the loading icon while the share loads', async () => { + axios.get.mockReturnValue(new Promise(() => {})) + const wrapper = await mountView() + + expect(wrapper.find('.public-share-view__loading').exists()).toBe(true) + expect(wrapper.findComponent({ name: 'NcLoadingIcon' }).exists()).toBe(true) + }) + + it('asks for the password on a protected share', async () => { + axios.get.mockRejectedValue(httpError(401, { passwordRequired: true })) + const wrapper = await mountView() + + expect(dialog(wrapper).exists()).toBe(true) + expect(dialog(wrapper).props()).toEqual({ error: null, loading: false }) + expect(shareStore.clearUnlocked).not.toHaveBeenCalled() + }) + + it('drops a stored unlock the server no longer accepts', async () => { + shareStore.isUnlocked.mockReturnValue(true) + axios.get.mockRejectedValue(httpError(401, { passwordRequired: true })) + await mountView() + + expect(shareStore.isUnlocked).toHaveBeenCalledWith(TOKEN) + expect(shareStore.clearUnlocked).toHaveBeenCalledWith(TOKEN) + }) + + it('says a missing or expired share was not found', async () => { + axios.get.mockRejectedValue(httpError(404)) + const wrapper = await mountView() + + expect(wrapper.vm.error).toBe('not_found') + expect(wrapper.find('.empty').text()).toBe('Not found | This shared dashboard does not exist or has expired.') + expect(dialog(wrapper).exists()).toBe(false) + }) + + it('treats any other failure, including a 401 without a password, as a server error', async () => { + for (const failure of [httpError(500), httpError(401, {}), new Error('offline')]) { + axios.get.mockRejectedValueOnce(failure) + const wrapper = await mountView() + + expect(wrapper.vm.error).toBe('server_error') + expect(wrapper.find('.empty').text()).toBe('Error | An error occurred loading the shared dashboard.') + wrapper.unmount() + } + }) +}) + +describe('DashboardPublicShareView unlock', () => { + /** + * Mount on a protected share. + * + * @return {Promise} The wrapper showing the password dialog + */ + async function protectedView() { + axios.get.mockRejectedValueOnce(httpError(401, { passwordRequired: true })) + return mountView() + } + + it('unlocks, remembers the token and reloads with the password header', async () => { + const wrapper = await protectedView() + axios.post.mockResolvedValue({ data: { access: true } }) + axios.get.mockResolvedValueOnce({ data: { dashboard: { name: 'Secret board' }, share: {}, placements: [] } }) + + await dialog(wrapper).vm.$emit('unlock', 'hunter2') + await flushPromises() + + expect(axios.post).toHaveBeenCalledWith(UNLOCK_URL, { password: 'hunter2' }) + expect(shareStore.markUnlocked).toHaveBeenCalledWith(TOKEN) + expect(axios.get).toHaveBeenLastCalledWith(DATA_URL, { headers: { 'X-Share-Password': 'hunter2' } }) + expect(dialog(wrapper).exists()).toBe(false) + expect(wrapper.find('h1').text()).toBe('Secret board') + expect(wrapper.vm.unlocking).toBe(false) + }) + + it('reports a wrong password without reloading', async () => { + const wrapper = await protectedView() + axios.post.mockResolvedValue({ data: { access: false } }) + + await dialog(wrapper).vm.$emit('unlock', 'nope') + await flushPromises() + + expect(shareStore.markUnlocked).not.toHaveBeenCalled() + expect(axios.get).toHaveBeenCalledTimes(1) + expect(dialog(wrapper).props()).toEqual({ error: 'Incorrect password. Please try again.', loading: false }) + }) + + it('reports a throttled unlock', async () => { + const wrapper = await protectedView() + axios.post.mockRejectedValue(httpError(429)) + + await dialog(wrapper).vm.$emit('unlock', 'again') + await flushPromises() + + expect(dialog(wrapper).props('error')).toBe('unlock_throttled') + }) + + it('reports an unlock request that fails otherwise', async () => { + const wrapper = await protectedView() + axios.post.mockRejectedValue(httpError(500)) + + await dialog(wrapper).vm.$emit('unlock', 'x') + await flushPromises() + + expect(dialog(wrapper).props('error')).toBe('Failed to verify password.') + expect(wrapper.vm.unlocking).toBe(false) + }) + + it('ignores a second submit while one is being checked, and shows it is busy', async () => { + const wrapper = await protectedView() + let answer + axios.post.mockReturnValue(new Promise((resolve) => { answer = resolve })) + + await dialog(wrapper).vm.$emit('unlock', 'first') + expect(dialog(wrapper).props('loading')).toBe(true) + await dialog(wrapper).vm.$emit('unlock', 'second') + + expect(axios.post).toHaveBeenCalledTimes(1) + answer({ data: { access: false } }) + await flushPromises() + expect(dialog(wrapper).props('loading')).toBe(false) + }) + + it('clears an earlier unlock error when trying again', async () => { + const wrapper = await protectedView() + axios.post.mockResolvedValueOnce({ data: { access: false } }) + await dialog(wrapper).vm.$emit('unlock', 'wrong') + await flushPromises() + expect(dialog(wrapper).props('error')).not.toBeNull() + + let answer + axios.post.mockReturnValueOnce(new Promise((resolve) => { answer = resolve })) + await dialog(wrapper).vm.$emit('unlock', 'retry') + expect(dialog(wrapper).props('error')).toBeNull() + answer({ data: { access: false } }) + await flushPromises() + }) +}) + +describe('DashboardPublicShareView live widgets (REQ-PSHR-011)', () => { + it('hands the grid a read through the share token, without a password on an open link', async () => { + axios.get.mockResolvedValueOnce({ data: { dashboard: { name: 'Open board' }, share: {}, placements: [] } }) + const wrapper = await mountView() + axios.get.mockResolvedValueOnce({ data: { widget: 'weather', data: {} } }) + + const grid = wrapper.findComponent({ name: 'PublicDashboardGrid' }) + await grid.vm.$attrs.readWidget(4) + + expect(axios.get).toHaveBeenLastCalledWith('/index.php/apps/launchpad/s/ab%2Fc%20d/placements/4', { headers: {} }) + }) + + it('passes the password the link was unlocked with to the live widget reads', async () => { + axios.get.mockRejectedValueOnce(httpError(401, { passwordRequired: true })) + const wrapper = await mountView() + axios.post.mockResolvedValue({ data: { access: true } }) + axios.get.mockResolvedValueOnce({ data: { dashboard: { name: 'Secret board' }, share: {}, placements: [] } }) + await dialog(wrapper).vm.$emit('unlock', 'hunter2') + await flushPromises() + axios.get.mockResolvedValueOnce({ data: { widget: 'weather', data: {} } }) + + await wrapper.findComponent({ name: 'PublicDashboardGrid' }).vm.$attrs.readWidget(4) + + expect(axios.get).toHaveBeenLastCalledWith('/index.php/apps/launchpad/s/ab%2Fc%20d/placements/4', { headers: { 'X-Share-Password': 'hunter2' } }) + }) +}) diff --git a/src/views/__tests__/DashboardPublicShareView.startPage.spec.js b/src/views/__tests__/DashboardPublicShareView.startPage.spec.js new file mode 100644 index 000000000..b8bfe80e9 --- /dev/null +++ b/src/views/__tests__/DashboardPublicShareView.startPage.spec.js @@ -0,0 +1,101 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * sharing-public-start-page REQ-PSP-003: as the public start page the view + * carries a bar with the organisation's name and a "Sign in" link to the + * login form with `direct=1`; as a plain share page it has no such bar. The + * data still comes from the share's own `/s/{token}/data`. + * + * Only HTTP, the share store and child components are doubled. + * + * @spec openspec/changes/sharing-public-start-page/specs/dashboard-public-share/spec.md#requirement-the-start-page-offers-a-way-in-for-staff-req-psp-003 + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import DashboardPublicShareView from '../DashboardPublicShareView.vue' + +vi.mock('@nextcloud/axios', () => ({ + default: { get: vi.fn(), post: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => '/index.php' + path, +})) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + translate: (_app, text) => text, +})) +vi.mock('../../stores/publicShares.js', () => ({ + usePublicShareStore: () => ({ isUnlocked: vi.fn(), clearUnlocked: vi.fn(), markUnlocked: vi.fn() }), +})) + +/** + * Mount the view. + * + * @param {object} props The props + * @return {Promise} The wrapper, after the first load settled + */ +async function mountView(props) { + const wrapper = mount(DashboardPublicShareView, { + props, + global: { + stubs: { + PublicSharePasswordDialog: true, + PublicDashboardGrid: { name: 'PublicDashboardGrid', render: () => h('div', { class: 'grid' }) }, + NcLoadingIcon: true, + NcEmptyContent: { name: 'NcEmptyContent', props: ['name'], render() { return h('div', { class: 'empty' }, this.name) } }, + AlertCircleIcon: true, + }, + }, + }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + vi.clearAllMocks() + window.OC = { ...(window.OC || {}), theme: { name: 'Bibliotheek Noord' } } + axios.get.mockResolvedValue({ data: { dashboard: { name: 'Bibliotheek Noord' }, share: {}, placements: [] } }) +}) + +afterEach(() => { + delete window.OC.theme +}) + +describe('DashboardPublicShareView as the public start page', () => { + it('shows the organisation and a Sign in link to the login form with direct=1', async () => { + const wrapper = await mountView({ token: 'Bib1Noord', startPage: true }) + + const bar = wrapper.find('nav.public-share-view__start-bar') + expect(bar.exists()).toBe(true) + expect(bar.attributes('aria-label')).toBe('Sign in') + expect(bar.find('.public-share-view__organisation').text()).toBe('Bibliotheek Noord') + const link = bar.find('a.public-share-view__sign-in') + expect(link.text()).toBe('Sign in for employees') + expect(link.attributes('href')).toBe('/index.php/login?direct=1') + }) + + it('reads the chosen link through the share data endpoint', async () => { + await mountView({ token: 'Bib1Noord', startPage: true }) + + expect(axios.get).toHaveBeenCalledWith('/index.php/apps/launchpad/s/Bib1Noord/data', { headers: {} }) + }) + + it('keeps the way in when the link cannot be loaded', async () => { + axios.get.mockRejectedValue(Object.assign(new Error('HTTP 404'), { response: { status: 404, data: {} } })) + const wrapper = await mountView({ token: 'Bib1Noord', startPage: true }) + + expect(wrapper.find('.empty').text()).toBe('Not found') + expect(wrapper.find('a.public-share-view__sign-in').exists()).toBe(true) + }) + + it('has no sign-in bar on a plain share page', async () => { + const wrapper = await mountView({ token: 'abc123' }) + + expect(wrapper.find('nav.public-share-view__start-bar').exists()).toBe(false) + expect(wrapper.find('h1').text()).toBe('Bibliotheek Noord') + }) +}) diff --git a/src/views/__tests__/EmbedView.drillDown.spec.js b/src/views/__tests__/EmbedView.drillDown.spec.js new file mode 100644 index 000000000..35d01fb6c --- /dev/null +++ b/src/views/__tests__/EmbedView.drillDown.spec.js @@ -0,0 +1,83 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * A drill-down in an embed reaches the host page: a tile the visitor opens + * is relayed as a `drillDown` event when the token's scope allows it, and + * not at all when it does not (embedded-analytics REQ-EMB-006). + * + * @spec openspec/changes/embedded-analytics/specs/embedded-analytics/spec.md#requirement-req-emb-006--js-sdk-exposes-render-event-and-resize-apis + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { computed, ref } from 'vue' +import EmbedView from '../EmbedView.vue' + +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) + +const context = vi.hoisted(() => ({ current: null })) +vi.mock('../../composables/useEmbedContext.js', () => ({ useEmbedContext: () => context.current })) + +const placements = [{ id: 7, widgetId: 'tile-mail', tileType: 'app', gridX: 0, gridY: 0, tileTitle: 'Mail', tileLinkValue: '/apps/mail' }] + +/** + * An embed context with a loaded subject under the given scope. + * + * @param {object} scope The token's scope. + * @return {object} + */ +function embedContext(scope) { + const payload = ref({ scope, filters: {}, placements }) + const canRun = (action) => scope.mode === 'read-with-interactions' && scope.allowedActions.includes(action) + return { + loading: ref(false), + error: ref(null), + payload, + placements: computed(() => payload.value.placements), + scope: computed(() => scope), + filters: computed(() => ({})), + canRun, + relay: vi.fn(() => true), + start: () => () => {}, + } +} + +/** + * Mount the embed page and click its one tile. + * + * @param {object} scope The token's scope. + * @return {Promise<{relay: Function, tile: object}>} + */ +async function clickTile(scope) { + context.current = embedContext(scope) + const wrapper = mount(EmbedView, { global: { stubs: { NcLoadingIcon: true, NcEmptyContent: true } } }) + const tile = wrapper.find('.public-share-view__tile') + await tile.trigger('click') + return { relay: context.current.relay, tile } +} + +describe('EmbedView drill-down relay', () => { + beforeEach(() => { + context.current = null + }) + + it('relays the opened tile to the host page when the scope allows drillDown', async () => { + const { relay, tile } = await clickTile({ mode: 'read-with-interactions', allowedActions: ['drillDown'], allowedFilters: [] }) + expect(relay).toHaveBeenCalledTimes(1) + expect(relay).toHaveBeenCalledWith('drillDown', { placementId: 7, title: 'Mail', link: '/apps/mail', source: 'user-interaction' }) + expect(tile.attributes('href'), 'the tile stays a focusable control').toBe('#') + }) + + it('relays nothing under a read-only scope', async () => { + const { relay, tile } = await clickTile({ mode: 'read', allowedActions: ['drillDown'], allowedFilters: [] }) + expect(tile.attributes('href')).toBeUndefined() + expect(relay).not.toHaveBeenCalled() + }) + + it('relays nothing when interactions leave out drillDown', async () => { + const { relay } = await clickTile({ mode: 'read-with-interactions', allowedActions: ['interact'], allowedFilters: [] }) + expect(relay).not.toHaveBeenCalled() + }) +}) diff --git a/src/views/__tests__/KioskPlayerView.emptyPlaylist.spec.js b/src/views/__tests__/KioskPlayerView.emptyPlaylist.spec.js new file mode 100644 index 000000000..6e05e136d --- /dev/null +++ b/src/views/__tests__/KioskPlayerView.emptyPlaylist.spec.js @@ -0,0 +1,52 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * KioskPlayerView with a playlist that holds no dashboards: it says so, + * starts no rotation and only waits for the next refresh + * (dashboard-kiosk-mode REQ-KIOSKUI-002). + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import KioskPlayerView from '../KioskPlayerView.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/l10n', () => ({ translate: (_app, text) => text })) + +beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('KioskPlayerView empty playlist', () => { + it('REQ-KIOSKUI-002: shows the empty message and schedules only the next read, no rotation', async () => { + axios.get.mockResolvedValue({ + data: { playlist: { id: 1, name: 'Lobby', token: 'tok', refreshSeconds: 60 }, entries: [] }, + }) + const wrapper = mount(KioskPlayerView, { + props: { token: 'tok' }, + global: { stubs: { PublicDashboardGrid: { template: '
' } } }, + }) + await flushPromises() + + expect(wrapper.text()).toContain('This playlist has no dashboards to show.') + expect(wrapper.find('[data-testid="kiosk-dashboard"]').exists()).toBe(false) + expect(wrapper.vm.dwellTimer).toBeNull() + expect(wrapper.vm.prefetchTimer).toBeNull() + // The next playlist read, and the idle-cursor timer (REQ-KIOSK-001). + expect(vi.getTimerCount()).toBe(2) + + await vi.advanceTimersByTimeAsync(59_000) + expect(axios.get).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1_000) + expect(axios.get).toHaveBeenCalledTimes(2) + wrapper.unmount() + }) +}) diff --git a/src/views/__tests__/KioskPlayerView.position.spec.js b/src/views/__tests__/KioskPlayerView.position.spec.js new file mode 100644 index 000000000..fbe7e9ee1 --- /dev/null +++ b/src/views/__tests__/KioskPlayerView.position.spec.js @@ -0,0 +1,167 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * KioskPlayerView: the position line "2 of 4 · next in 18 s" on a playlist + * of more than one dashboard, and the polite announcement when it moves on + * (dashboard-kiosk-mode REQ-KIOSKUI-003, board LpKiosk). + * + * @spec openspec/changes/archive/2026-11-24-kiosk-position-indicator/specs/dashboard-kiosk-mode/spec.md#requirement-the-kiosk-screen-shows-where-the-playlist-is-req-kioskui-003 + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import KioskPlayerView from '../KioskPlayerView.vue' + +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('@nextcloud/router', () => ({ generateUrl: (path) => `/index.php${path}` })) +vi.mock('@nextcloud/l10n', () => ({ + translate: (_app, text, vars = {}) => text.replace(/\{(\w+)\}/g, (_m, k) => String(vars[k] ?? `{${k}}`)), +})) + +const PLAYLIST_URL = '/index.php/apps/launchpad/kiosk/tok' + +const entry = (uuid, name) => ({ dwellSeconds: 30, dashboard: { uuid, name }, placements: [] }) + +/** + * Serve a playlist: the playlist read and each entry read. + * + * @param {Array} entries The playlist's entries. + */ +function serve(entries) { + axios.get.mockImplementation((url) => { + if (url === PLAYLIST_URL) { + return Promise.resolve({ data: { playlist: { refreshSeconds: 300 }, entries } }) + } + const uuid = url.split('/').pop() + return Promise.resolve({ data: entries.find((e) => e.dashboard.uuid === uuid) }) + }) +} + +function mountPlayer() { + return mount(KioskPlayerView, { + props: { token: 'tok' }, + global: { stubs: { PublicDashboardGrid: { template: '
' } } }, + }) +} + +const CANTEEN = [entry('a', 'Nieuws'), entry('b', 'Kantine'), entry('c', 'Agenda'), entry('d', 'Weer')] + +beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('KioskPlayerView position line (REQ-KIOSKUI-003)', () => { + it('reads "2 of 4 · next in 18 s" 12 seconds into the second dashboard', async () => { + serve(CANTEEN) + const wrapper = mountPlayer() + await flushPromises() + expect(wrapper.find('[data-testid="kiosk-position"]').text()).toBe('1 of 4 · next in 30 s') + + await vi.advanceTimersByTimeAsync(30_000) + expect(wrapper.text()).toContain('Kantine') + expect(wrapper.find('[data-testid="kiosk-position"]').text()).toBe('2 of 4 · next in 30 s') + + await vi.advanceTimersByTimeAsync(12_000) + expect(wrapper.find('[data-testid="kiosk-position"]').text()).toBe('2 of 4 · next in 18 s') + wrapper.unmount() + }) + + it('counts down every second', async () => { + serve(CANTEEN) + const wrapper = mountPlayer() + await flushPromises() + await vi.advanceTimersByTimeAsync(1_000) + expect(wrapper.find('[data-testid="kiosk-position"]').text()).toBe('1 of 4 · next in 29 s') + await vi.advanceTimersByTimeAsync(1_000) + expect(wrapper.find('[data-testid="kiosk-position"]').text()).toBe('1 of 4 · next in 28 s') + wrapper.unmount() + }) + + it('shows no position line for a playlist of one dashboard', async () => { + serve([entry('a', 'Nieuws')]) + const wrapper = mountPlayer() + await flushPromises() + expect(wrapper.text()).toContain('Nieuws') + expect(wrapper.find('[data-testid="kiosk-position"]').exists()).toBe(false) + wrapper.unmount() + }) + + it('is text hidden from screen readers, not a control', async () => { + serve(CANTEEN) + const wrapper = mountPlayer() + await flushPromises() + const line = wrapper.find('[data-testid="kiosk-position"]') + expect(line.element.tagName).toBe('P') + expect(line.attributes('aria-hidden')).toBe('true') + expect(line.attributes('tabindex')).toBeUndefined() + wrapper.unmount() + }) + + it('politely names the new dashboard when the playlist moves on', async () => { + serve(CANTEEN) + const wrapper = mountPlayer() + await flushPromises() + const live = wrapper.find('[data-testid="kiosk-announcement"]') + expect(live.attributes('aria-live')).toBe('polite') + expect(live.text()).toBe('') + + await vi.advanceTimersByTimeAsync(30_000) + expect(wrapper.find('[data-testid="kiosk-announcement"]').text()).toBe('Now showing Kantine') + wrapper.unmount() + }) + + it('announces nothing when a one-dashboard playlist starts over', async () => { + serve([entry('a', 'Nieuws')]) + const wrapper = mountPlayer() + await flushPromises() + await vi.advanceTimersByTimeAsync(30_000) + expect(wrapper.find('[data-testid="kiosk-announcement"]').text()).toBe('') + wrapper.unmount() + }) + + it('moves the reconnect note above the position line', async () => { + let reads = 0 + axios.get.mockImplementation((url) => { + if (url === PLAYLIST_URL) { + reads += 1 + return reads === 1 + ? Promise.resolve({ data: { playlist: { refreshSeconds: 30 }, entries: CANTEEN } }) + : Promise.reject(Object.assign(new Error('net'), { response: { status: 502 } })) + } + const uuid = url.split('/').pop() + return Promise.resolve({ data: CANTEEN.find((e) => e.dashboard.uuid === uuid) }) + }) + const wrapper = mountPlayer() + await flushPromises() + await vi.advanceTimersByTimeAsync(30_000) + const note = wrapper.find('[data-testid="kiosk-reconnecting"]') + expect(note.exists()).toBe(true) + expect(note.classes()).toContain('kiosk-player__reconnect--above') + wrapper.unmount() + }) +}) + +describe('KioskPlayerView position clock', () => { + it('runs no clock for a single dashboard, and stops it on unmount', async () => { + serve([entry('a', 'Nieuws')]) + const single = mountPlayer() + await flushPromises() + expect(single.vm.tickTimer).toBeNull() + single.unmount() + + serve(CANTEEN) + const many = mountPlayer() + await flushPromises() + expect(many.vm.tickTimer).not.toBeNull() + const clear = vi.spyOn(globalThis, 'clearInterval') + many.unmount() + expect(clear).toHaveBeenCalled() + }) +}) diff --git a/src/views/__tests__/KioskPlayerView.spec.js b/src/views/__tests__/KioskPlayerView.spec.js index e8af2fd36..c32b6dc8c 100644 --- a/src/views/__tests__/KioskPlayerView.spec.js +++ b/src/views/__tests__/KioskPlayerView.spec.js @@ -43,6 +43,34 @@ function httpError(status) { return Object.assign(new Error('http'), { response: { status } }) } +const PLAYLIST_URL = '/index.php/apps/launchpad/kiosk/tok' + +/** + * Answer the player's reads: the playlist read takes the next of + * `playlistAnswers` (the last one repeats), an entry read asks `entry`. + * + * @param {Array} playlistAnswers Each returns a promise. + * @param {(uuid: string) => Promise} entry Answers an entry read. + */ +function serve(playlistAnswers, entry = (uuid) => Promise.resolve({ data: payload.entries.find((e) => e.dashboard.uuid === uuid) })) { + let reads = 0 + axios.get.mockImplementation((url) => { + if (url === PLAYLIST_URL) { + const answer = playlistAnswers[Math.min(reads, playlistAnswers.length - 1)] + reads += 1 + return answer() + } + return entry(url.split('/').pop()) + }) +} + +/** @return {number} How often the playlist itself was read. */ +function playlistReads() { + return axios.get.mock.calls.filter(([url]) => url === PLAYLIST_URL).length +} + +const ok = () => Promise.resolve({ data: payload }) + function mountPlayer() { return mount(KioskPlayerView, { props: { token: 'tok' }, @@ -63,7 +91,7 @@ afterEach(() => { describe('KioskPlayerView', () => { it('REQ-KIOSKUI-002: rotates through the playlist and starts over', async () => { - axios.get.mockResolvedValue({ data: payload }) + serve([ok]) const wrapper = mountPlayer() await flushPromises() expect(axios.get).toHaveBeenCalledWith( @@ -79,17 +107,16 @@ describe('KioskPlayerView', () => { }) it('REQ-KIOSKUI-002: re-reads the playlist on the refresh interval', async () => { - axios.get.mockResolvedValue({ data: payload }) + serve([ok]) const wrapper = mountPlayer() await flushPromises() await vi.advanceTimersByTimeAsync(300_000) - expect(axios.get).toHaveBeenCalledTimes(2) + expect(playlistReads()).toBe(2) wrapper.unmount() }) it('REQ-KIOSKUI-002: a revoked link shows that the playlist is gone', async () => { - axios.get.mockResolvedValueOnce({ data: payload }) - axios.get.mockRejectedValueOnce(httpError(404)) + serve([ok, () => Promise.reject(httpError(404))]) const wrapper = mountPlayer() await flushPromises() await vi.advanceTimersByTimeAsync(300_000) @@ -99,9 +126,7 @@ describe('KioskPlayerView', () => { }) it('REQ-KIOSKUI-002: a network blip keeps the last playlist and tries again', async () => { - axios.get.mockResolvedValueOnce({ data: payload }) - axios.get.mockRejectedValueOnce(new Error('Network Error')) - axios.get.mockResolvedValue({ data: payload }) + serve([ok, () => Promise.reject(new Error('Network Error')), ok]) const wrapper = mountPlayer() await flushPromises() await vi.advanceTimersByTimeAsync(300_000) @@ -110,15 +135,128 @@ describe('KioskPlayerView', () => { ) expect(wrapper.find('[data-testid="kiosk-dashboard"]').exists()).toBe(true) await vi.advanceTimersByTimeAsync(30_000) - expect(axios.get).toHaveBeenCalledTimes(3) + expect(playlistReads()).toBe(3) + wrapper.unmount() + }) + + it('REQ-KIOSK-005: a failed read shows a reconnect indicator until a read succeeds', async () => { + serve([ok, () => Promise.reject(new Error('Network Error')), ok]) + const wrapper = mountPlayer() + await flushPromises() + const indicator = () => wrapper.find('[data-testid="kiosk-reconnecting"]') + expect(indicator().exists()).toBe(false) + await vi.advanceTimersByTimeAsync(300_000) + expect(indicator().exists()).toBe(true) + expect(indicator().attributes('role')).toBe('status') + expect(wrapper.text()).toContain('Nieuws') + await vi.advanceTimersByTimeAsync(30_000) + expect(indicator().exists()).toBe(false) wrapper.unmount() }) it('shows the unavailable message when the first read is refused', async () => { - axios.get.mockRejectedValue(httpError(404)) + serve([() => Promise.reject(httpError(404))]) const wrapper = mountPlayer() await flushPromises() expect(wrapper.find('[data-testid="kiosk-unavailable"]').exists()).toBe(true) wrapper.unmount() }) + + it('REQ-KIOSK-004: fetches the next entry 5 seconds before its turn and shows that fresh data', async () => { + const fresh = { dwellSeconds: 20, dashboard: { uuid: 'k', name: 'Kantine vers' }, placements: [] } + serve([ok], () => Promise.resolve({ data: fresh })) + const wrapper = mountPlayer() + await flushPromises() + const entryReads = () => axios.get.mock.calls.filter(([url]) => url !== PLAYLIST_URL).map(([url]) => url) + + await vi.advanceTimersByTimeAsync(24_000) + expect(entryReads()).toEqual([]) + await vi.advanceTimersByTimeAsync(1_000) + expect(entryReads()).toEqual(['/index.php/apps/launchpad/kiosk/tok/dashboards/k']) + expect(wrapper.text()).toContain('Nieuws') + + await vi.advanceTimersByTimeAsync(5_000) + expect(wrapper.text()).toContain('Kantine vers') + expect(entryReads()).toHaveLength(1) + wrapper.unmount() + }) + + it('REQ-KIOSK-005: skips an entry that fails and tries it again on the next loop', async () => { + const three = { + ...payload, + entries: [...payload.entries, { dwellSeconds: 30, dashboard: { uuid: 'p', name: 'Parkeren' }, placements: [] }], + } + const attempts = { k: 0 } + serve([() => Promise.resolve({ data: three })], (uuid) => { + if (uuid === 'k') { + attempts.k += 1 + return Promise.reject(httpError(500)) + } + return Promise.resolve({ data: three.entries.find((e) => e.dashboard.uuid === uuid) }) + }) + const wrapper = mountPlayer() + await flushPromises() + + await vi.advanceTimersByTimeAsync(30_000) + expect(wrapper.text()).toContain('Parkeren') + expect(wrapper.text()).not.toContain('500') + expect(attempts.k).toBe(1) + + // Parkeren 30 s, Nieuws 30 s: the next loop reaches Kantine again. + await vi.advanceTimersByTimeAsync(60_000) + expect(attempts.k).toBe(2) + wrapper.unmount() + }) + + it('REQ-KIOSK-005: skips an entry that does not answer within 10 seconds', async () => { + serve([ok], (uuid) => (uuid === 'k' ? new Promise(() => {}) : Promise.resolve({ data: payload.entries[0] }))) + const wrapper = mountPlayer() + await flushPromises() + + await vi.advanceTimersByTimeAsync(30_000) + expect(wrapper.text()).toContain('Nieuws') + await vi.advanceTimersByTimeAsync(5_000) + expect(wrapper.text()).toContain('Nieuws') + expect(wrapper.find('[data-testid="kiosk-dashboard"]').exists()).toBe(true) + wrapper.unmount() + }) + + it('REQ-KIOSK-005: the 10 seconds count from the entry\'s turn, not from its early fetch', async () => { + const fresh = { dwellSeconds: 20, dashboard: { uuid: 'k', name: 'Kantine vers' }, placements: [] } + // Fetched at 25 s, its turn at 30 s, the answer at 37 s: 7 s after its turn. + serve([ok], () => new Promise((resolve) => setTimeout(() => resolve({ data: fresh }), 12_000))) + const wrapper = mountPlayer() + await flushPromises() + + await vi.advanceTimersByTimeAsync(38_000) + expect(wrapper.text()).toContain('Kantine vers') + wrapper.unmount() + }) + + it('REQ-KIOSK-001: hides the cursor after 10 seconds without movement', async () => { + serve([ok]) + const wrapper = mountPlayer() + await flushPromises() + await vi.advanceTimersByTimeAsync(10_000) + expect(document.documentElement.classList.contains('launchpad-kiosk--idle')).toBe(true) + document.dispatchEvent(new Event('mousemove')) + expect(document.documentElement.classList.contains('launchpad-kiosk--idle')).toBe(false) + wrapper.unmount() + expect(document.documentElement.classList.contains('launchpad-kiosk--idle')).toBe(false) + }) +}) + +describe('KioskPlayerView live widgets (REQ-PSHR-011)', () => { + it('reads the live widgets through the playlist token', async () => { + serve([ok]) + const wrapper = mountPlayer() + await flushPromises() + axios.get.mockResolvedValueOnce({ data: { widget: 'livetile', data: { value: 7 } } }) + + const result = await wrapper.vm.readWidget(9) + + expect(axios.get).toHaveBeenLastCalledWith('/index.php/apps/launchpad/kiosk/tok/placements/9', { headers: {} }) + expect(result).toEqual({ widget: 'livetile', data: { value: 7 } }) + wrapper.unmount() + }) }) diff --git a/src/views/__tests__/Views.customWidgetNotices.spec.js b/src/views/__tests__/Views.customWidgetNotices.spec.js new file mode 100644 index 000000000..b4737f2a5 --- /dev/null +++ b/src/views/__tests__/Views.customWidgetNotices.spec.js @@ -0,0 +1,27 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The widget dialog gets the edited widget's filter notices + * (drill-down-cross-widget-filter task 9). + * + * @spec openspec/changes/archive/2026-11-25-drill-down-cross-widget-filter/tasks.md#task-9 + */ + +import { describe, expect, it } from 'vitest' +import Views from '../Views.vue' + +const notices = (state) => Views.computed.customWidgetNotices.call(state) + +describe('Views.customWidgetNotices', () => { + it('hands the dialog a warning for a consumed dimension the dashboard does not publish', () => { + const result = notices({ customWidgetEditing: { content: { consumes: ['buurtCode'] } }, filterSession: { bus: { hierarchies: [] } } }) + expect(result).toHaveLength(1) + expect(result[0]).toMatchObject({ id: 'consumes-unknown-dimension:buurtCode', type: 'warning' }) + }) + + it('hands nothing when no widget is edited, or there is no filter session', () => { + expect(notices({ customWidgetEditing: null, filterSession: null })).toEqual([]) + expect(notices({ customWidgetEditing: { content: {} }, filterSession: null })).toEqual([]) + }) +}) diff --git a/src/views/__tests__/Views.editGate.methods.spec.js b/src/views/__tests__/Views.editGate.methods.spec.js new file mode 100644 index 000000000..9360e57bb --- /dev/null +++ b/src/views/__tests__/Views.editGate.methods.spec.js @@ -0,0 +1,176 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The workspace page's edit-mode gate (already editing, no dashboard, + * editing accepted or refused) and what it guards: the widget picker and the + * tile editor. Also the read-confirmation save without a placement, and + * the dashboard config save (create, edit with tree fields, refusals the + * form explains). Run against the real Views methods on a stand-in host; + * only HTTP, stores and the logger are doubled. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +vi.mock('../../services/api.js', () => ({ + api: { + updateDashboard: vi.fn(), + }, +})) +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +let Views + +/** + * A host carrying the real Views methods. + * + * @param {object} state Data and overrides. + * @return {object} the host. + */ +function makeHost(state = {}) { + const host = { + activeDashboard: null, + isEditMode: false, + presence: { start: vi.fn() }, + isWidgetModalOpen: false, + isTileEditorOpen: false, + editingTile: null, + } + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + return Object.assign(host, state) +} + +beforeEach(async () => { + vi.clearAllMocks() + Views = (await import('../Views.vue')).default +}) + +describe('Views edit-mode gate', () => { + it('is already open in edit mode without announcing the presence again', async () => { + const host = makeHost({ isEditMode: true, activeDashboard: { uuid: 'd' } }) + expect(await host.enterEditMode()).toBe(true) + expect(host.presence.start).not.toHaveBeenCalled() + }) + + it('stays closed without an active dashboard', async () => { + const host = makeHost({ activeDashboard: {} }) + expect(await host.enterEditMode()).toBe(false) + expect(host.presence.start).not.toHaveBeenCalled() + expect(host.isEditMode).toBe(false) + }) + + it('opens the widget picker once the presence is accepted and reads the discovered apps', async () => { + const host = makeHost({ activeDashboard: { id: 12 } }) + host.presence.start.mockResolvedValue(true) + host.loadDiscoveredApps = vi.fn() + + await host.openWidgetModal() + + expect(host.presence.start).toHaveBeenCalledWith('12') + expect(host.isEditMode).toBe(true) + expect(host.isWidgetModalOpen).toBe(true) + expect(host.loadDiscoveredApps).toHaveBeenCalledTimes(1) + }) + + it('keeps the widget picker closed when editing is refused', async () => { + const host = makeHost({ activeDashboard: { uuid: 'd' } }) + host.presence.start.mockResolvedValue(false) + host.loadDiscoveredApps = vi.fn() + + await host.openWidgetModal() + + expect(host.isWidgetModalOpen).toBe(false) + expect(host.loadDiscoveredApps).not.toHaveBeenCalled() + }) + + it('opens the tile editor on the given tile, or a new one, in edit mode', async () => { + const tile = { id: 3, title: 'Mail' } + const host = makeHost({ isEditMode: true, activeDashboard: { uuid: 'd' } }) + + await host.openTileEditor(tile) + expect(host.editingTile).toBe(tile) + expect(host.isTileEditorOpen).toBe(true) + + host.isTileEditorOpen = false + await host.openTileEditor() + expect(host.editingTile).toBeNull() + expect(host.isTileEditorOpen).toBe(true) + }) + + it('keeps the tile editor closed when editing is refused', async () => { + const host = makeHost({ activeDashboard: { uuid: 'd' } }) + host.presence.start.mockResolvedValue(false) + + await host.openTileEditor({ id: 3 }) + + expect(host.presence.start).toHaveBeenCalledWith('d') + expect(host.isTileEditorOpen).toBe(false) + expect(host.editingTile).toBeNull() + }) +}) + +describe('Views read confirmation save', () => { + it('does nothing when no placement was being configured', async () => { + const host = makeHost({ readConfirmationPlacement: null }) + host.updateWidgetPlacement = vi.fn() + host.onWidgetAcknowledged = vi.fn() + + await host.saveReadConfirmation({ requiresAcknowledgement: true }) + + expect(host.updateWidgetPlacement).not.toHaveBeenCalled() + expect(host.onWidgetAcknowledged).not.toHaveBeenCalled() + }) +}) + +describe('Views dashboard config save', () => { + it('creates a dashboard when the form has no id, then closes', async () => { + const host = makeHost({ configSaveError: 'old' }) + host.createDashboard = vi.fn().mockResolvedValue({}) + host.closeConfigModal = vi.fn() + + await host.saveDashboardConfig({ id: null, name: 'HR', description: 'People', icon: 'mdi' }) + + expect(host.createDashboard).toHaveBeenCalledWith({ name: 'HR', description: 'People', icon: 'mdi' }) + expect(api.updateDashboard).not.toHaveBeenCalled() + expect(host.closeConfigModal).toHaveBeenCalledTimes(1) + expect(host.configSaveError).toBe('') + }) + + it('updates with the parent and web address name, reloads and closes', async () => { + api.updateDashboard.mockResolvedValue({ data: {} }) + const host = makeHost({ configSaveError: '' }) + host.loadDashboards = vi.fn().mockResolvedValue() + host.closeConfigModal = vi.fn() + + await host.saveDashboardConfig({ id: 5, name: 'HR', description: '', icon: 'x', parentUuid: '', slug: 'hr' }) + + expect(api.updateDashboard).toHaveBeenCalledWith(5, { name: 'HR', description: '', icon: 'x', parentUuid: '', slug: 'hr' }) + expect(host.loadDashboards).toHaveBeenCalledTimes(1) + expect(host.closeConfigModal).toHaveBeenCalledTimes(1) + }) + + it('explains a vanished parent, and falls back for an unknown refusal, keeping the form open', async () => { + const host = makeHost({ configSaveError: '' }) + host.loadDashboards = vi.fn() + host.closeConfigModal = vi.fn() + + const gone = Object.assign(new Error('404'), { response: { data: { message: 'Parent dashboard not found' } } }) + api.updateDashboard.mockRejectedValue(gone) + await host.saveDashboardConfig({ id: 5, name: 'HR', description: '', icon: 'x', parentUuid: 'p' }) + expect(api.updateDashboard).toHaveBeenCalledWith(5, { name: 'HR', description: '', icon: 'x', parentUuid: 'p' }) + expect(logger.error).toHaveBeenCalledWith('Failed to save dashboard:', gone) + expect(host.configSaveError).toBe('The chosen parent dashboard no longer exists.') + + api.updateDashboard.mockRejectedValue(new Error('offline')) + await host.saveDashboardConfig({ id: 5, name: 'HR', description: '', icon: 'x' }) + expect(host.configSaveError).toBe('The dashboard could not be saved.') + expect(host.closeConfigModal).not.toHaveBeenCalled() + }) +}) diff --git a/src/views/__tests__/Views.failurePaths.methods.spec.js b/src/views/__tests__/Views.failurePaths.methods.spec.js new file mode 100644 index 000000000..7f35e6798 --- /dev/null +++ b/src/views/__tests__/Views.failurePaths.methods.spec.js @@ -0,0 +1,151 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The workspace page's failure paths: a failed metadata-field or filter + * read, the personal layer refusing "show again" or "reset", the schedule + * refusals the dialog explains, a refused version-support probe, and + * deleting a dashboard (no target, a plain failure). Run against the real + * Views methods on a stand-in host; only HTTP, stores, dialogs and the + * logger are doubled. + */ + +import { showError } from '@nextcloud/dialogs' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +vi.mock('../../services/api.js', () => ({ + api: { + getMetadataFieldDefinitions: vi.fn(), + getVisibleDashboards: vi.fn(), + scheduleDashboard: vi.fn(), + listVersions: vi.fn(), + deleteDashboard: vi.fn(), + }, +})) +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +let Views + +/** + * A host carrying the real Views methods. + * + * @param {object} state Data and overrides. + * @return {object} the host. + */ +function makeHost(state = {}) { + const host = { activeDashboard: null, versionSupport: {}, isAdmin: false } + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + host.switchDashboard = vi.fn() + return Object.assign(host, state) +} + +/** + * An error as axios rejects with it. + * + * @param {number} status HTTP status. + * @param {object} data Response body. + * @return {Error} the error. + */ +function httpError(status, data = {}) { + return Object.assign(new Error(`HTTP ${status}`), { response: { status, data } }) +} + +beforeEach(async () => { + setActivePinia(createPinia()) + vi.clearAllMocks() + Views = (await import('../Views.vue')).default +}) + +describe('Views metadata fields and filter', () => { + it('keeps the fields from the server and empties them when the read fails', async () => { + api.getMetadataFieldDefinitions.mockResolvedValue({ data: { fields: [{ key: 'team' }] } }) + const host = makeHost({ detailFields: [] }) + await host.loadDetailFields() + expect(host.detailFields).toEqual([{ key: 'team' }]) + + api.getMetadataFieldDefinitions.mockRejectedValue(new Error('down')) + await host.loadDetailFields() + expect(host.detailFields).toEqual([]) + }) + + it('a failed filter read is logged and clears the filter', async () => { + const error = new Error('down') + api.getVisibleDashboards.mockRejectedValue(error) + const host = makeHost({ detailFilterUuids: ['a'] }) + + await host.onDetailFilter({ team: 'hr' }) + + expect(api.getVisibleDashboards).toHaveBeenCalledWith({ team: 'hr' }) + expect(logger.error).toHaveBeenCalledWith('Failed to filter dashboards:', error) + expect(host.detailFilterUuids).toBeNull() + }) +}) + +describe('Views personal layer refusals', () => { + it('"Hide for me" does nothing without an active dashboard', async () => { + const layer = { hide: vi.fn() } + const host = makeHost({ activeDashboard: null, personalLayer: layer, availableWidgets: [] }) + + await host.onHideForMe({ id: 9 }) + + expect(layer.hide).not.toHaveBeenCalled() + expect(host.switchDashboard).not.toHaveBeenCalled() + }) + + it('a refused "show again" says so and does not re-read', async () => { + const layer = { showAgain: vi.fn().mockRejectedValue(new Error('no')) } + const host = makeHost({ activeDashboard: { id: 4 }, personalLayer: layer }) + + await host.onShowAgain(9) + + expect(layer.showAgain).toHaveBeenCalledWith(4, 9) + expect(showError).toHaveBeenCalledWith('The widget could not be shown again.') + expect(host.switchDashboard).not.toHaveBeenCalled() + }) + + it('a refused reset says so and does not re-read', async () => { + const layer = { reset: vi.fn().mockRejectedValue(new Error('no')) } + const host = makeHost({ activeDashboard: { id: 4 }, personalLayer: layer }) + + await host.onResetPersonalView() + + expect(layer.reset).toHaveBeenCalledWith(4) + expect(showError).toHaveBeenCalledWith('Your view could not be reset.') + expect(host.switchDashboard).not.toHaveBeenCalled() + }) +}) + +describe('Views delete dashboard', () => { + it('does nothing without a confirmed target', async () => { + const host = makeHost({ deleteTarget: null, deleteChildCount: 0 }) + + await host.confirmDeleteDashboard() + + expect(api.deleteDashboard).not.toHaveBeenCalled() + }) + + it('a plain failure is logged and keeps the dialog on its target', async () => { + const error = httpError(500) + api.deleteDashboard.mockRejectedValue(error) + const target = { id: 7 } + const host = makeHost({ deleteTarget: target, deleteChildCount: 0 }) + host.loadDashboards = vi.fn() + host.closeConfigModal = vi.fn() + + await host.confirmDeleteDashboard() + + expect(api.deleteDashboard).toHaveBeenCalledWith(7, false) + expect(logger.error).toHaveBeenCalledWith('Failed to delete dashboard:', error) + expect(host.deleteTarget).toBe(target) + expect(host.deleteChildCount).toBe(0) + expect(host.loadDashboards).not.toHaveBeenCalled() + }) +}) diff --git a/src/views/__tests__/Views.firstLoadRequests.methods.spec.js b/src/views/__tests__/Views.firstLoadRequests.methods.spec.js new file mode 100644 index 000000000..416399f5a --- /dev/null +++ b/src/views/__tests__/Views.firstLoadRequests.methods.spec.js @@ -0,0 +1,205 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * What the workspace page asks while it loads: the detail fields wait for + * the switcher, the boot view-event waits for the page to settle (or for the + * page to be left), and the acknowledgements and the default-dashboard + * preference go out together with the first loads. Run against the real + * Views options on a stand-in host; only HTTP, stores and the settle timer + * are doubled. + */ + +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { LazyMountSupport, SETTLE_DELAY_MS } from '../../components/LazyMount.vue' +import { api } from '../../services/api.js' +import { useDashboardStore } from '../../stores/dashboard.js' +import { useTileStore } from '../../stores/tiles.js' +import { useWidgetStore } from '../../stores/widgets.js' +import { takeBootRead } from '../../utils/loadInitialState.js' + +vi.mock('../../services/api.js', () => ({ + api: { + getMetadataFieldDefinitions: vi.fn(), + getDefaultDashboardPreference: vi.fn(), + recordDashboardViewEvent: vi.fn(), + }, +})) +vi.mock('../../utils/loadInitialState.js', async (importOriginal) => ({ + ...(await importOriginal()), + takeBootRead: vi.fn(), +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +let Views + +/** + * A host carrying the real Views methods. + * + * @param {object} state Data and overrides. + * @return {object} the host. + */ +function makeHost(state = {}) { + const host = { + detailFields: [], + detailFieldsRequested: false, + defaultDashboardUuid: '', + viewEventLastSent: Object.create(null), + historyBooted: false, + canEdit: false, + grid: {}, + } + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + host.recordViewEvent = vi.fn() + return Object.assign(host, state) +} + +beforeEach(async () => { + setActivePinia(createPinia()) + vi.clearAllMocks() + Views = (await import('../Views.vue')).default + // No Web Locks in this host: recordViewEventDebounced sends directly. + vi.stubGlobal('navigator', {}) +}) + +afterEach(() => { + vi.unstubAllGlobals() + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('Views detail fields', () => { + it('are not asked for on mount, but the first time the switcher opens, and only once', async () => { + api.getMetadataFieldDefinitions.mockResolvedValue({ data: { fields: [{ key: 'team' }] } }) + const host = makeHost() + + Views.watch.sidebarOpen.call(host, false) + expect(api.getMetadataFieldDefinitions).not.toHaveBeenCalled() + + Views.watch.sidebarOpen.call(host, true) + await host.loadDetailFieldsOnce() + Views.watch.sidebarOpen.call(host, true) + + expect(api.getMetadataFieldDefinitions).toHaveBeenCalledTimes(1) + expect(host.detailFields).toEqual([{ key: 'team' }]) + }) +}) + +describe('Views boot view-event', () => { + it('is recorded once the page has settled, not while it loads', () => { + vi.useFakeTimers() + vi.stubGlobal('requestIdleCallback', undefined) + const host = makeHost() + + Views.watch['activeDashboard.uuid'].handler.call(Object.assign(host, { + openFilterSession: vi.fn(), + pushUrlForActiveDashboard: vi.fn(), + }), 'd1') + expect(host.recordViewEvent).not.toHaveBeenCalled() + + vi.advanceTimersByTime(SETTLE_DELAY_MS) + expect(host.recordViewEvent).toHaveBeenCalledTimes(1) + expect(host.recordViewEvent).toHaveBeenCalledWith('d1') + }) + + it('is sent at once when the page is left before it settled', () => { + const cancel = vi.fn() + vi.spyOn(LazyMountSupport, 'whenSettled').mockReturnValue(cancel) + const host = makeHost({ + presence: { stop: vi.fn() }, + grid: { detach: vi.fn() }, + filterSession: null, + headerActionsObserver: null, + }) + host.recordViewEventAfterLoad('d1') + expect(host.recordViewEvent).not.toHaveBeenCalled() + + Views.beforeUnmount.call(host) + + expect(cancel).toHaveBeenCalled() + expect(host.recordViewEvent).toHaveBeenCalledWith('d1') + }) + + it('a switch after the boot is recorded at once', () => { + const settle = vi.spyOn(LazyMountSupport, 'whenSettled') + const host = makeHost({ historyBooted: true, openFilterSession: vi.fn(), pushUrlForActiveDashboard: vi.fn() }) + + Views.watch['activeDashboard.uuid'].handler.call(host, 'd2') + + expect(settle).not.toHaveBeenCalled() + expect(host.recordViewEvent).toHaveBeenCalledWith('d2') + }) +}) + +describe('Views first loads', () => { + it('asks for the acknowledgements and the default dashboard before the dashboards have loaded', async () => { + let finishTiles + const dashboardStore = useDashboardStore() + vi.spyOn(dashboardStore, 'loadDashboards').mockResolvedValue() + vi.spyOn(dashboardStore, 'fetchPendingAcknowledgements').mockResolvedValue() + vi.spyOn(useWidgetStore(), 'loadAvailableWidgets').mockResolvedValue() + vi.spyOn(useTileStore(), 'loadTiles').mockReturnValue(new Promise((resolve) => { finishTiles = resolve })) + api.getDefaultDashboardPreference.mockResolvedValue({ data: { uuid: 'd9' } }) + const host = makeHost({ + openDeepLinkedDashboard: vi.fn(), + openHashLinkedDashboard: vi.fn(), + replaceUrlAfterBoot: vi.fn(), + }) + + const booting = Views.created.call(host) + expect(dashboardStore.fetchPendingAcknowledgements).toHaveBeenCalledTimes(1) + expect(api.getDefaultDashboardPreference).toHaveBeenCalledTimes(1) + + finishTiles() + await booting + expect(host.defaultDashboardUuid).toBe('d9') + expect(host.historyBooted).toBe(true) + }) +}) + +describe('Views boot view-event, two dashboards during the boot', () => { + it('records only the dashboard the boot ends on', () => { + const cancelFirst = vi.fn() + const sends = [] + vi.spyOn(LazyMountSupport, 'whenSettled').mockImplementation((send) => { + sends.push(send) + return sends.length === 1 ? cancelFirst : vi.fn() + }) + const host = makeHost() + + host.recordViewEventAfterLoad('stored') + host.recordViewEventAfterLoad('deep-linked') + sends[1]() + + expect(cancelFirst).toHaveBeenCalled() + expect(host.recordViewEvent.mock.calls).toEqual([['deep-linked']]) + }) +}) + +describe('Views default dashboard', () => { + it('takes the pin the page carries, without asking the API', async () => { + takeBootRead.mockReturnValue({ uuid: 'd7' }) + const host = makeHost() + + await host.loadDefaultDashboardPreference() + + expect(takeBootRead).toHaveBeenCalledWith('defaultDashboard') + expect(host.defaultDashboardUuid).toBe('d7') + expect(api.getDefaultDashboardPreference).not.toHaveBeenCalled() + }) + + it('asks the API when the page carries no pin', async () => { + takeBootRead.mockReturnValue(undefined) + api.getDefaultDashboardPreference.mockResolvedValue({ data: { uuid: 'd8' } }) + const host = makeHost() + + await host.loadDefaultDashboardPreference() + + expect(host.defaultDashboardUuid).toBe('d8') + }) +}) diff --git a/src/views/__tests__/Views.groupTiles.methods.spec.js b/src/views/__tests__/Views.groupTiles.methods.spec.js new file mode 100644 index 000000000..4518d0649 --- /dev/null +++ b/src/views/__tests__/Views.groupTiles.methods.spec.js @@ -0,0 +1,153 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * A tile inside a group edited with the tile form (tile-form-board-sync + * REQ-TILE-041): the dashboard opens the form with the group's name and sort + * order, writes the save into the group's children with the group's order in + * one placement update, and deletes a group tile the same way. Run against the + * real Views methods and computed values on a stand-in host. + * + * @spec openspec/changes/tile-form-board-sync/specs/tiles/spec.md#requirement-a-tiles-group-and-the-groups-order-req-tile-041 + */ + +import { showError } from '@nextcloud/dialogs' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +let Views + +const bookmark = { type: 'link', gridX: 0, content: { label: 'Intranet', url: 'https://intranet.example.org', actionType: 'external' } } +const caseSystem = { type: 'tile', gridX: 2, content: { title: 'Case system', linkType: 'url', linkValue: 'https://cases.example.org', healthPingEnabled: true } } + +/** + * A host carrying the real Views methods and the group computed values. + * + * @param {object} state Data and overrides. + * @return {object} the host. + */ +function makeHost(state = {}) { + const host = { + isEditMode: true, + activeDashboard: { uuid: 'd' }, + isTileEditorOpen: false, + editingTile: null, + editingGroupTile: null, + widgetPlacements: [ + { id: 9, widgetId: 'tile', tileType: 'custom' }, + { id: 41, widgetId: 'container', content: { title: 'Work apps', sortBy: 'manual', placements: [bookmark, caseSystem] } }, + ], + updateWidgetPlacement: vi.fn().mockResolvedValue({}), + removeWidget: vi.fn(), + } + for (const [name, fn] of Object.entries(Views.methods)) { + if (!(name in host)) { + host[name] = fn.bind(host) + } + } + for (const name of ['editingGroup', 'editingGroupTitle', 'editingGroupSort']) { + Object.defineProperty(host, name, { get: () => Views.computed[name].call(host) }) + } + return Object.assign(host, state) +} + +beforeEach(async () => { + vi.clearAllMocks() + Views = (await import('../Views.vue')).default +}) + +describe('Views — a tile in a group', () => { + it('provides the opener to the groups on the dashboard', async () => { + const host = makeHost() + const provided = Views.provide.call(host) + await provided.openGroupTileEditor({ containerId: 41, index: 1 }) + expect(host.isTileEditorOpen).toBe(true) + }) + + it('opens the form on the tile with the group name and sort order', async () => { + const host = makeHost() + await host.openGroupTileEditor({ containerId: 41, index: 1 }) + expect(host.editingGroupTile).toEqual({ containerId: 41, index: 1 }) + expect(host.editingTile.title).toBe('Case system') + expect(host.editingGroupTitle).toBe('Work apps') + expect(host.editingGroupSort).toBe('manual') + }) + + it('opens nothing for a child that is not a tile, or a group that is gone', async () => { + const host = makeHost() + host.widgetPlacements[1].content.placements.push({ type: 'label', content: {} }) + await host.openGroupTileEditor({ containerId: 41, index: 2 }) + await host.openGroupTileEditor({ containerId: 99, index: 0 }) + expect(host.isTileEditorOpen).toBe(false) + expect(host.editingGroupTitle).toBe('') + expect(host.editingGroupSort).toBe('') + }) + + it('saves the tile into the group with the group sort order, in one update, keeping what the form does not edit', async () => { + const host = makeHost() + await host.openGroupTileEditor({ containerId: 41, index: 1 }) + await host.saveTile({ ...host.editingTile, title: 'Cases', healthPingEnabled: false, groupSortBy: 'last-used' }) + + expect(host.updateWidgetPlacement).toHaveBeenCalledTimes(1) + const [id, payload] = host.updateWidgetPlacement.mock.calls[0] + expect(id).toBe(41) + expect(payload.content.sortBy).toBe('last-used') + expect(payload.content.title).toBe('Work apps') + expect(payload.content.placements[0]).toBe(bookmark) + expect(payload.content.placements[1].content).toMatchObject({ title: 'Cases', healthPingEnabled: true }) + expect(host.isTileEditorOpen).toBe(false) + expect(host.editingGroupTile).toBeNull() + }) + + it('turns a saved bookmark link into a tile node', async () => { + const host = makeHost() + await host.openGroupTileEditor({ containerId: 41, index: 0 }) + await host.saveTile({ ...host.editingTile }) + const child = host.updateWidgetPlacement.mock.calls[0][1].content.placements[0] + expect(child.type).toBe('tile') + expect(child.content).toMatchObject({ title: 'Intranet', linkType: 'url', linkValue: 'https://intranet.example.org' }) + expect(child.content.url).toBeUndefined() + }) + + it('deletes a group tile from the form and from the tile menu, never the group', async () => { + const host = makeHost() + await host.openGroupTileEditor({ containerId: 41, index: 0 }) + await host.deleteTile() + expect(host.removeWidget).not.toHaveBeenCalled() + expect(host.updateWidgetPlacement.mock.calls[0][1].content.placements).toEqual([caseSystem]) + expect(host.isTileEditorOpen).toBe(false) + + await host.openGroupTileEditor({ containerId: 41, index: 1, remove: true }) + expect(host.updateWidgetPlacement.mock.calls[1][1].content.placements).toEqual([bookmark]) + expect(host.isTileEditorOpen).toBe(false) + }) + + it('keeps the form open and says so when the group cannot be saved', async () => { + const host = makeHost() + host.updateWidgetPlacement.mockRejectedValue(new Error('500')) + await host.openGroupTileEditor({ containerId: 41, index: 1 }) + await host.saveTile({ ...host.editingTile }) + expect(showError).toHaveBeenCalledWith('The group could not be saved.') + expect(host.isTileEditorOpen).toBe(true) + }) + + it('says the tile is gone when its group changed under the form', async () => { + const host = makeHost() + await host.openGroupTileEditor({ containerId: 41, index: 1 }) + host.widgetPlacements[1].content = { title: 'Work apps', placements: [bookmark] } + await host.saveTile({ ...host.editingTile }) + expect(host.updateWidgetPlacement).not.toHaveBeenCalled() + expect(showError).toHaveBeenCalledWith('This tile is no longer in its group. Reload the dashboard and try again.') + }) + + it('saves a tile on the dashboard itself as before', async () => { + const host = makeHost() + await host.openTileEditor({ id: 9, title: 'Mail' }) + await host.saveTile({ title: 'Mail', linkType: 'url', linkValue: '/apps/mail' }) + expect(host.updateWidgetPlacement).toHaveBeenCalledWith(9, expect.objectContaining({ tileTitle: 'Mail' })) + }) +}) diff --git a/src/views/__tests__/Views.loadingState.spec.js b/src/views/__tests__/Views.loadingState.spec.js index e9717761d..8a2bbf585 100644 --- a/src/views/__tests__/Views.loadingState.spec.js +++ b/src/views/__tests__/Views.loadingState.spec.js @@ -138,19 +138,19 @@ async function mountViews({ activeDashboard = null, loading = false } = {}) { describe('Views — initial-load shim', () => { // Mounting the full Views tree pulls in the heavy CnWidgetWrapper widget // chrome; give these a generous timeout so they stay green under parallel - // full-suite load (they run ~4.5s in isolation). + // full-suite load (the first one pays the dynamic import of the library barrel, ~12s in isolation on 2.81 and over 20s on a loaded machine). it('renders the loading shim, NOT the empty-state CTA, while loading=true and activeDashboard is null', async () => { const wrapper = await mountViews({ activeDashboard: null, loading: true }) expect(wrapper.find('.launchpad-loading').exists()).toBe(true) expect(wrapper.findComponent({ name: 'NcLoadingIcon' }).exists()).toBe(true) expect(wrapper.find('.launchpad-empty').exists()).toBe(false) - }, 20000) + }, 90000) it('renders the empty-state CTA once loading=false and activeDashboard is still null', async () => { const wrapper = await mountViews({ activeDashboard: null, loading: false }) expect(wrapper.find('.launchpad-loading').exists()).toBe(false) expect(wrapper.find('.launchpad-empty').exists()).toBe(true) - }, 20000) + }, 90000) }) diff --git a/src/views/__tests__/Views.look.spec.js b/src/views/__tests__/Views.look.spec.js new file mode 100644 index 000000000..dcbd2adf2 --- /dev/null +++ b/src/views/__tests__/Views.look.spec.js @@ -0,0 +1,74 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The dashboard page draws the active dashboard's look on its region and sends + * a changed look with the save (platform-dashboard-theme-and-css REQ-THM-001/002). + */ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/router', async (importOriginal) => ({ ...(await importOriginal()), generateUrl: (path) => path })) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, key, vars = {}) => key.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m)), +})) +vi.mock('../../services/api.js', () => ({ api: { updateDashboard: vi.fn() } })) + +import Views from '../Views.vue' +import { api } from '../../services/api.js' + +describe('Views dashboard look', () => { + it('draws the active dashboard\'s look, and nothing for one that follows the theme', () => { + expect(Views.computed.dashboardLookStyle.call({ activeDashboard: { themeAccent: null } })).toEqual({}) + expect(Views.computed.dashboardLookStyle.call({ activeDashboard: { themeAccent: '#1f5c3a' } })).toEqual({ + '--color-primary-element': '#1f5c3a', + '--color-primary-element-text': '#ffffff', + }) + }) + + it('sends the changed look with the rest of the save', async () => { + api.updateDashboard.mockResolvedValueOnce({}) + const self = { configSaveError: '', loadDashboards: vi.fn(), closeConfigModal: vi.fn(), treeSaveMessage: vi.fn() } + + await Views.methods.saveDashboardConfig.call(self, { id: 7, name: 'Team Groen', description: '', icon: 'x', parentUuid: '', look: { themeAccent: '#1f5c3a' } }) + + expect(api.updateDashboard).toHaveBeenCalledWith(7, { name: 'Team Groen', description: '', icon: 'x', parentUuid: '', themeAccent: '#1f5c3a' }) + expect(self.closeConfigModal).toHaveBeenCalled() + }) + + it('sends changed hierarchies and rebuilds the open dashboard\'s filter bus on them (REQ-CWF-011)', async () => { + api.updateDashboard.mockResolvedValue({}) + const self = { configSaveError: '', loadDashboards: vi.fn(), closeConfigModal: vi.fn(), treeSaveMessage: vi.fn(), openFilterSession: vi.fn(), activeDashboard: { id: 7 } } + const hierarchies = [{ id: 'nl-administrative', levels: [{ dimension: 'provincieCode', label: 'Province', parentDimension: null }] }] + + await Views.methods.saveDashboardConfig.call(self, { id: 7, name: 'N', description: '', icon: 'x', hierarchies }) + + expect(api.updateDashboard).toHaveBeenLastCalledWith(7, { name: 'N', description: '', icon: 'x', hierarchies }) + expect(self.openFilterSession).toHaveBeenCalledWith(false) + + await Views.methods.saveDashboardConfig.call(self, { id: 7, name: 'N', description: '', icon: 'x' }) + expect(api.updateDashboard).toHaveBeenLastCalledWith(7, { name: 'N', description: '', icon: 'x' }) + expect(self.openFilterSession).toHaveBeenCalledTimes(1) + + await Views.methods.saveDashboardConfig.call(self, { id: 8, name: 'N', description: '', icon: 'x', hierarchies: [] }) + expect(self.openFilterSession).toHaveBeenCalledTimes(1) + }) + + it('names the measured ratio when the server refuses a pale accent', () => { + const error = { response: { data: { error: 'contrast_too_low', ratio: 1.1, message: 'x' } } } + + expect(Views.methods.treeSaveMessage.call({}, error)).toBe('Buttons in this colour are hard to see (contrast 1.1 to 1, needs 3 to 1)') + }) + + it('puts the active dashboard\'s administrator CSS on the page as text, and takes it off again (REQ-THM-003)', () => { + const watcher = Views.watch['activeDashboard.customCss'] + const css = '.launchpad-dashboard[data-dashboard-uuid="u1"] body {\n display: none;\n}' + + expect(watcher.immediate).toBe(true) + watcher.handler(css) + expect(document.getElementById('launchpad-dashboard-custom-css').textContent).toBe(css) + + watcher.handler(null) + expect(document.getElementById('launchpad-dashboard-custom-css')).toBeNull() + }) +}) diff --git a/src/views/__tests__/Views.period.methods.spec.js b/src/views/__tests__/Views.period.methods.spec.js new file mode 100644 index 000000000..b98585c3a --- /dev/null +++ b/src/views/__tests__/Views.period.methods.spec.js @@ -0,0 +1,61 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The workspace's period choice (dashboard-period-and-download REQ-DPD-002): + * offered when a shown widget names a period field, and kept in the address + * without touching the stored dashboard. Run against the real Views methods + * and computed properties on a stand-in host. + * + * @spec openspec/changes/archive/2026-11-25-dashboard-period-and-download/specs/dashboards/spec.md#requirement-a-dashboard-can-have-a-period-that-its-figures-follow-req-dpd-002 + */ + +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import { logger } from '../../utils/logger.js' + +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +let Views + +beforeAll(async () => { + Views = (await import('../Views.vue')).default +}) + +afterEach(() => { + vi.restoreAllMocks() + window.history.replaceState(null, '', '/') +}) + +describe('Views period', () => { + it('offers the period only when a shown placement names a period field', () => { + const dated = { shownPlacements: [{ content: { dataSource: { periodField: 'startDate' } } }] } + const plain = { shownPlacements: [{ content: { url: 'https://example.org' } }] } + expect(Views.computed.showsPeriod.call(dated)).toBe(true) + expect(Views.computed.showsPeriod.call(plain)).toBe(false) + }) + + it('takes the chosen period and keeps it in the address, the rest of the address kept', () => { + window.history.replaceState(null, '', '/apps/launchpad/d/abc?edit=1') + const host = { dashboardPeriod: 'month' } + Views.methods.onPeriodChange.call(host, 'quarter') + expect(host.dashboardPeriod).toBe('quarter') + expect(window.location.pathname + window.location.search).toBe('/apps/launchpad/d/abc?edit=1&period=quarter') + }) + + it('falls back to This month for an unknown choice', () => { + const host = { dashboardPeriod: 'year' } + Views.methods.onPeriodChange.call(host, 'decade') + expect(host.dashboardPeriod).toBe('month') + expect(window.location.search).toBe('?period=month') + }) + + it('logs, and keeps the choice, when the address cannot be rewritten', () => { + vi.spyOn(window.history, 'replaceState').mockImplementation(() => { throw new Error('SecurityError') }) + const host = { dashboardPeriod: 'month' } + Views.methods.onPeriodChange.call(host, 'year') + expect(host.dashboardPeriod).toBe('year') + expect(logger.warn).toHaveBeenCalled() + }) +}) diff --git a/src/views/__tests__/Views.placementEmbed.methods.spec.js b/src/views/__tests__/Views.placementEmbed.methods.spec.js new file mode 100644 index 000000000..ff6f62c54 --- /dev/null +++ b/src/views/__tests__/Views.placementEmbed.methods.spec.js @@ -0,0 +1,42 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The workspace gives each widget the Beheer ▸ Embeds link for an embed + * token of that one widget, only for an administrator (embedded-analytics + * task 40). Run against the real Views method on a stand-in host. + * + * @spec openspec/changes/embedded-analytics/tasks.md#task-40 + */ + +import { beforeAll, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path) => `/index.php${path}`, +})) +vi.mock('../../services/api.js', () => ({ api: {} })) +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) + +let Views + +beforeAll(async () => { + Views = (await import('../Views.vue')).default +}) + +const hrefFor = (host, placement) => Views.methods.placementEmbedHref.call(host, placement) +const dashboard = { id: 7, uuid: 'dash-uuid' } + +describe('Views placementEmbedHref', () => { + it('links an administrator to a widget token for the placement', () => { + expect(hrefFor({ isAdmin: true, activeDashboard: dashboard }, { id: 5 })) + .toBe('/index.php/apps/launchpad/admin/embeds?tab=embeds&embedType=widget&embedId=5&embedDashboard=7') + }) + + it('gives nothing to a non-administrator or without a saved dashboard and placement', () => { + expect(hrefFor({ isAdmin: false, activeDashboard: dashboard }, { id: 5 })).toBe('') + expect(hrefFor({ isAdmin: null, activeDashboard: dashboard }, { id: 5 })).toBe('') + expect(hrefFor({ isAdmin: true, activeDashboard: null }, { id: 5 })).toBe('') + expect(hrefFor({ isAdmin: true, activeDashboard: dashboard }, {})).toBe('') + }) +}) diff --git a/src/views/__tests__/Views.templateWiring.coverage.spec.js b/src/views/__tests__/Views.templateWiring.coverage.spec.js new file mode 100644 index 000000000..901ebe249 --- /dev/null +++ b/src/views/__tests__/Views.templateWiring.coverage.spec.js @@ -0,0 +1,858 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Mounted Views.vue: the template's event wiring (top-bar cog, sidebar, + * dialogs, grid items, right-click menu), the header-actions docking and + * the created / mounted / beforeUnmount lifecycle. Only HTTP (axios), the + * Nextcloud globals and the store actions that would hit the server are + * mocked; child components are stubbed so their events can be emitted. + */ + +import axios from '@nextcloud/axios' +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/l10n', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + t: (_app, key) => key, + translate: (_app, key) => key, + translatePlural: (_app, sing, plur, n) => (n === 1 ? sing : plur), + } +}) +vi.mock('@nextcloud/dialogs', () => ({ + showSuccess: vi.fn(), + showError: vi.fn(), +})) +vi.mock('@nextcloud/initial-state', () => ({ + loadState: vi.fn((_app, _key, fallback) => fallback), +})) +vi.mock('@nextcloud/axios', () => ({ + default: { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + }, +})) +vi.mock('@nextcloud/router', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + generateUrl: (path) => path, + } +}) + +const BASE = '/apps/launchpad' + +/** + * A stub that renders nothing and keeps every bound prop / listener in `$attrs`. + * + * @param {string} name Component name (for findComponent). + * @param {object} extra Extra options (props, template, inject). + * @return {object} the stub. + */ +function passthrough(name, extra = {}) { + return { + name, + inheritAttrs: false, + template: '
', + ...extra, + } +} + +const stubs = { + teleport: { template: '
' }, + DashboardSwitcherSidebar: passthrough('DashboardSwitcherSidebar', { + props: { isOpen: Boolean }, + template: '
', + }), + SidebarBackdrop: passthrough('SidebarBackdrop', { + template: '
', + }), + DashboardRowActions: passthrough('DashboardRowActions', { + template: '
', + }), + DashboardMoreMenu: passthrough('DashboardMoreMenu', { + template: '
', + }), + NcButton: { + name: 'NcButton', + template: '', + }, + MenuIcon: { name: 'MenuIcon', template: '' }, + ShareVariant: { name: 'ShareVariant', template: '' }, + ViewDashboard: { template: '' }, + NcLoadingIcon: { template: '' }, + NcEmptyContent: { + name: 'NcEmptyContent', + props: { name: String, description: String }, + template: '
{{ description }}
', + }, + StartPageMenu: passthrough('StartPageMenu'), + HiddenWidgetsControl: passthrough('HiddenWidgetsControl'), + DeleteDashboardDialog: passthrough('DeleteDashboardDialog', { + props: { open: Boolean, name: String }, + }), + CnConfirmDialog: passthrough('CnConfirmDialog', { + template: '
', + }), + DashboardEditBar: passthrough('DashboardEditBar', { + props: { dashboardName: String, columns: Number, canConfigure: Boolean }, + }), + AcknowledgementReportModal: passthrough('AcknowledgementReportModal', { + props: { open: Boolean, announcementKey: String }, + }), + DashboardReactions: passthrough('DashboardReactions', { template: '
' }), + DashboardLanguageHeading: passthrough('DashboardLanguageHeading'), + DashboardBreadcrumb: passthrough('DashboardBreadcrumb'), + EditLockBanner: passthrough('EditLockBanner', { props: { status: String } }), + CoEditorsBanner: passthrough('CoEditorsBanner', { props: { editors: Array } }), + CnDashboardGrid: { + name: 'CnDashboardGrid', + props: { layout: { type: Array, default: () => [] } }, + template: + '
', + }, + TileWidget: passthrough('TileWidget', { + props: { placementId: [Number, String] }, + template: '
', + }), + WidgetWrapper: passthrough('WidgetWrapper', { + props: { placement: Object }, + template: + '
', + }), + WidgetPickerModal: passthrough('WidgetPickerModal'), + CnAddWidgetModal: passthrough('CnAddWidgetModal', { + props: { show: Boolean, editingWidget: Object }, + // Mirrors CnNcDashboardWidgetForm, which reads the injected catalog. + inject: { widgets: { default: null }, cnOffersPeriodField: { default: false } }, + template: + '
  • {{ w.id }}
', + }), + DashboardConfigModal: passthrough('DashboardConfigModal', { + props: { open: Boolean, mode: String, initialTab: String }, + }), + CnWidgetStyleEditorModal: passthrough('CnWidgetStyleEditorModal', { + props: { show: Boolean, widget: Object }, + }), + TileEditor: passthrough('TileEditor', { + props: { open: Boolean, tile: Object }, + }), + WidgetContextMenu: passthrough('WidgetContextMenu', { + props: { top: Number, left: Number }, + template: '
', + }), + ReadConfirmationDialog: passthrough('ReadConfirmationDialog', { + props: { placement: Object }, + template: '
', + }), + WidgetMovePanel: passthrough('WidgetMovePanel', { + props: { open: Boolean, placement: Object }, + }), + VisibilityRulesModal: passthrough('VisibilityRulesModal', { + props: { open: Boolean, placementId: [Number, String], widgetTitle: String, dashboardName: String, ruleMatch: String }, + }), +} + +let wrapper = null + +/** + * Answer the axios mock per URL. + * + * @param {object} overrides `{get: fn(url), post: fn(url)}` replacements. + */ +function routeAxios(overrides = {}) { + axios.get.mockImplementation( + overrides.get + ?? ((url) => { + if (url === `${BASE}/api/dashboards/default`) { + return Promise.resolve({ data: { uuid: 'u-default' } }) + } + return Promise.resolve({ data: {} }) + }), + ) + axios.post.mockImplementation( + overrides.post ?? (() => Promise.resolve({ data: { acquiredAt: 1 } })), + ) + axios.put.mockImplementation(() => Promise.resolve({ data: {} })) + axios.delete.mockImplementation(() => Promise.resolve({ data: {} })) +} + +/** + * Mount Views with real stores whose server-bound actions are mocked. + * + * @param {object} opts Store state and injections. + * @return {Promise<{wrapper: object, dashStore: object}>} the mount. + */ +async function mountViews({ + activeDashboard = { id: 7, uuid: 'u-7', name: 'Home', isOwner: true }, + widgetPlacements = [], + permissionLevel = 'full', + isAdmin = false, + allowUserDashboards = true, + availableWidgets = [], + attach = false, +} = {}) { + const pinia = createPinia() + setActivePinia(pinia) + + const { default: Views } = await import('../Views.vue') + const { useDashboardStore } = await import('../../stores/dashboard.js') + const { useWidgetStore } = await import('../../stores/widgets.js') + const { useTileStore } = await import('../../stores/tiles.js') + + const dashStore = useDashboardStore() + dashStore.activeDashboard = activeDashboard + dashStore.dashboards = activeDashboard ? [activeDashboard] : [] + dashStore.widgetPlacements = widgetPlacements + dashStore.permissionLevel = permissionLevel + dashStore.loading = false + dashStore.loadDashboards = vi.fn(() => Promise.resolve()) + dashStore.fetchPendingAcknowledgements = vi.fn(() => Promise.resolve()) + dashStore.recordViewEvent = vi.fn() + dashStore.switchDashboard = vi.fn(() => Promise.resolve()) + dashStore.removeWidgetFromDashboard = vi.fn(() => Promise.resolve()) + dashStore.updateWidgetPlacement = vi.fn(() => Promise.resolve()) + dashStore.updatePlacements = vi.fn() + + const widgetStore = useWidgetStore() + widgetStore.availableWidgets = availableWidgets + widgetStore.loadAvailableWidgets = vi.fn(() => Promise.resolve()) + + const tileStore = useTileStore() + tileStore.tiles = [] + tileStore.loadTiles = vi.fn(() => Promise.resolve()) + + wrapper = mount(Views, { + global: { + plugins: [pinia], + provide: { + isAdmin, + allowUserDashboards, + primaryGroupName: '', + }, + // Attached mounts keep the real Teleport, so the controls land + // where the view sends them. + stubs: attach ? { ...stubs, teleport: false } : stubs, + mocks: { + t: (_app, key) => key, + n: (_app, sing, plur, count) => (count === 1 ? sing : plur), + }, + }, + attachTo: attach ? document.body : undefined, + }) + await flushPromises() + return { wrapper, dashStore } +} + +beforeEach(() => { + vi.clearAllMocks() + globalThis.t = (_app, key) => key + window.history.replaceState(null, '', '/apps/launchpad') + routeAxios() +}) + +afterEach(() => { + if (wrapper) { + wrapper.unmount() + wrapper = null + } + document.body.innerHTML = '' +}) + +describe('Views — the Meer menu and sidebar wiring', () => { + it('opens the sidebar from the Meer menu\'s "All dashboards" and closes it through the sidebar and the backdrop', async () => { + const { wrapper } = await mountViews() + const sidebar = () => wrapper.findComponent({ name: 'DashboardSwitcherSidebar' }) + const more = () => wrapper.findComponent({ name: 'DashboardMoreMenu' }) + + expect(sidebar().props('isOpen')).toBe(false) + expect(wrapper.find('.stub-backdrop').exists()).toBe(false) + + await more().vm.$emit('openAll') + expect(sidebar().props('isOpen')).toBe(true) + expect(wrapper.find('.stub-backdrop').exists()).toBe(true) + + await wrapper.findComponent({ name: 'SidebarBackdrop' }).vm.$emit('close') + expect(sidebar().props('isOpen')).toBe(false) + + await more().vm.$emit('openAll') + await sidebar().vm.$emit('update:open', false) + expect(sidebar().props('isOpen')).toBe(false) + expect(wrapper.find('.stub-backdrop').exists()).toBe(false) + }, 90000) + + it('the Meer menu\'s "Share" opens the config drawer on the sharing tab', async () => { + const { wrapper } = await mountViews() + await wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('share') + await flushPromises() + const config = wrapper.findComponent({ name: 'DashboardConfigModal' }) + expect(config.props('open')).toBe(true) + expect(config.props('initialTab')).toBe('sharing') + }, 90000) + + it('the Meer menu\'s "Edit" announces the editor and enters edit mode; the edit bar opens the settings', async () => { + const { wrapper } = await mountViews() + const cog = wrapper.findComponent({ name: 'DashboardMoreMenu' }) + + cog.vm.$emit('toggleEdit') + await flushPromises() + expect(axios.post).toHaveBeenCalledWith(`${BASE}/api/dashboards/u-7/presence`) + expect(wrapper.find('.launchpad-container').classes()).toContain('launchpad-edit-mode') + + wrapper.findComponent({ name: 'DashboardEditBar' }).vm.$emit('openSettings') + await flushPromises() + const config = wrapper.findComponent({ name: 'DashboardConfigModal' }) + expect(config.props('open')).toBe(true) + expect(config.props('initialTab')).toBe('general') + }, 90000) + + it('the Meer menu\'s "Add widget" opens the widget picker with the server apps and the catalogue', async () => { + const discovered = [{ appId: 'files', name: 'Files', href: '/apps/files', icon: '' }] + const catalogue = [{ uuid: 'c-1', name: 'Mail', icon: '', iconType: 'url' }] + routeAxios({ + get: (url) => { + if (url === `${BASE}/api/tiles/discover`) { + return Promise.resolve({ data: { apps: discovered } }) + } + if (url === `${BASE}/api/catalogue`) { + return Promise.resolve({ data: { apps: catalogue } }) + } + return Promise.resolve({ data: {} }) + }, + }) + const { wrapper } = await mountViews() + const picker = () => wrapper.findComponent({ name: 'WidgetPickerModal' }) + expect(picker().exists()).toBe(false) + + wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('addWidget') + await flushPromises() + + expect(axios.post).toHaveBeenCalledWith(`${BASE}/api/dashboards/u-7/presence`) + expect(picker().vm.$attrs.open).toBe(true) + expect(picker().vm.$attrs.discoveredApps).toEqual(discovered) + expect(picker().vm.$attrs.catalogueApps).toEqual(catalogue) + expect(wrapper.findComponent({ name: 'CnAddWidgetModal' }).props('show')).toBe(false) + }, 90000) + + it('a Launchpad type picked in the picker opens the custom widget form on it, with no second menu entry', async () => { + const { wrapper, dashStore } = await mountViews() + const picker = () => wrapper.findComponent({ name: 'WidgetPickerModal' }) + wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('addWidget') + await flushPromises() + + expect(picker().vm.$attrs.customTypes).toEqual(expect.arrayContaining([expect.objectContaining({ type: 'text' })])) + picker().vm.$emit('addCustom', 'text') + await flushPromises() + + expect(dashStore.switchDashboard).not.toHaveBeenCalled() + expect(picker().vm.$attrs.open).toBe(false) + const form = wrapper.findComponent({ name: 'CnAddWidgetModal' }) + expect(form.props('show')).toBe(true) + expect(wrapper.vm.customWidgetPreselectedType).toBeNull() + expect(wrapper.vm.customWidgetInitialType).toBe('text') + }, 90000) + + it('offers the widget forms a date field for the dashboard period (REQ-DPD-002)', async () => { + const { wrapper } = await mountViews() + expect(wrapper.findComponent({ name: 'CnAddWidgetModal' }).vm.cnOffersPeriodField).toBe(true) + }, 90000) + + it('the Meer menu\'s "Set as default" toggles the pinned default dashboard over HTTP', async () => { + const { wrapper } = await mountViews() + const cog = wrapper.findComponent({ name: 'DashboardMoreMenu' }) + + cog.vm.$emit('setDefault') + await flushPromises() + expect(axios.post).toHaveBeenCalledWith( + `${BASE}/api/dashboards/default`, + { uuid: 'u-7' }, + ) + expect(wrapper.vm.defaultDashboardUuid).toBe('u-7') + }, 90000) + + it('REQ-SCH-011 and REQ-SCHEDUI-001: the settings get the Publication and Exports tabs with this dashboard and its widgets', async () => { + const { wrapper } = await mountViews({ + widgetPlacements: [{ id: 41, widgetId: 'launchpad_text', gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 2, customTitle: 'KPI' }], + }) + const menu = wrapper.findComponent({ name: 'DashboardMoreMenu' }) + expect(menu.vm.$attrs.canScheduleExports).toBeUndefined() + + await wrapper.setData({ isConfigModalOpen: true }) + const config = wrapper.findComponent({ name: 'DashboardConfigModal' }) + expect(config.vm.$attrs.canManagePublication).toBe(true) + expect(config.vm.$attrs.canScheduleExports).toBe(true) + expect(config.vm.$attrs.exportSubjects).toEqual([ + { type: 'dashboard', id: 'u-7', label: 'Home' }, + { type: 'widget', id: '41', label: expect.any(String) }, + ]) + }, 90000) + + it('the Meer menu offers no Versions: the settings carry them as a tab', async () => { + const { wrapper } = await mountViews() + const menu = wrapper.findComponent({ name: 'DashboardMoreMenu' }) + expect(menu.vm.$attrs.canViewHistory).toBeUndefined() + await wrapper.setData({ isConfigModalOpen: true }) + expect(wrapper.findComponent({ name: 'DashboardConfigModal' }).vm.$attrs.canViewVersions).toBe(true) + }, 90000) + + it('the Meer menu\'s "Copy link" puts the dashboard\'s own address on the clipboard', async () => { + const writeText = vi.fn().mockResolvedValue() + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }) + const { wrapper } = await mountViews() + axios.get.mockImplementation((url) => Promise.resolve({ data: url.endsWith('/path') ? { path: '/home' } : {} })) + await wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('copyLink') + await flushPromises() + expect(writeText).toHaveBeenCalledWith(expect.stringMatching(/^https?:\/\/[^/]+.*\/home$/)) + }, 90000) + + it('the Meer menu\'s "Copy link" falls back to the id address, and says so when copying fails', async () => { + const writeText = vi.fn().mockRejectedValue(new Error('denied')) + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }) + const { wrapper } = await mountViews() + axios.get.mockImplementation(() => Promise.resolve({ data: {} })) + await wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('copyLink') + await flushPromises() + expect(writeText).toHaveBeenCalledWith(expect.stringMatching(/\/dashboards\/\d+$/)) + }, 90000) + + it('the Meer menu\'s "Duplicate" forks the open dashboard', async () => { + const { wrapper } = await mountViews() + await wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('duplicate') + await flushPromises() + expect(axios.post).toHaveBeenCalledWith(`${BASE}/api/dashboards/u-7/fork`, expect.anything()) + }, 90000) + + it('edit mode shows the edit bar: its settings, columns and Done', async () => { + const { wrapper } = await mountViews() + const bar = () => wrapper.findComponent({ name: 'DashboardEditBar' }) + expect(bar().exists()).toBe(false) + + wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('toggleEdit') + await flushPromises() + expect(bar().exists()).toBe(true) + expect(bar().props('canConfigure')).toBe(true) + expect(bar().props('columns')).toBe(12) + + await bar().vm.$emit('openSettings') + const config = wrapper.findComponent({ name: 'DashboardConfigModal' }) + expect(config.props('open')).toBe(true) + expect(config.props('initialTab')).toBe('general') + + await bar().vm.$emit('setColumns', 8) + await flushPromises() + expect(axios.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/dashboard\/\d+$/), + { gridColumns: 8 }, + ) + expect(bar().props('columns')).toBe(8) + + await bar().vm.$emit('done') + await flushPromises() + expect(bar().exists()).toBe(false) + }, 90000) + + it('the Meer menu\'s "Delete" opens the delete dialog for the active dashboard', async () => { + const { wrapper } = await mountViews() + await wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('delete') + + const dialog = wrapper.findComponent({ name: 'DeleteDashboardDialog' }) + expect(dialog.props('open')).toBe(true) + expect(dialog.props('name')).toBe('Home') + }, 90000) +}) + +describe('Views — read receipts and the colleagues editing', () => { + it('"Read receipts" opens the report for the first announcement; its close shuts it', async () => { + const { wrapper } = await mountViews({ + widgetPlacements: [ + { id: 1, widgetId: 'text', requiresAcknowledgement: '1', announcementKey: 'ann-a' }, + { id: 2, widgetId: 'text', requiresAcknowledgement: 1, announcementKey: 'ann-b' }, + { id: 3, widgetId: 'text', requiresAcknowledgement: 1, announcementKey: 'ann-a' }, + { id: 4, widgetId: 'text', requiresAcknowledgement: 0, announcementKey: 'ann-c' }, + ], + }) + const report = () => wrapper.findComponent({ name: 'AcknowledgementReportModal' }) + expect(report().exists()).toBe(false) + + await wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('readReceipts') + expect(report().props('open')).toBe(true) + expect(report().props('announcementKey')).toBe('ann-a') + + await report().vm.$emit('close') + expect(report().props('open')).toBe(false) + }, 90000) + + it('in edit mode the colleagues editing are shown, in view mode not', async () => { + const marieke = { displayName: 'Marieke Jansen', since: '2026-11-14T10:42:00+01:00' } + const { wrapper } = await mountViews() + expect(wrapper.findComponent({ name: 'CoEditorsBanner' }).exists()).toBe(false) + + axios.post.mockImplementation(() => Promise.resolve({ data: { editors: [marieke] } })) + + wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('toggleEdit') + await flushPromises() + expect(wrapper.findComponent({ name: 'CoEditorsBanner' }).props('editors')).toEqual([marieke]) + }, 90000) +}) + +describe('Views — grid items', () => { + const tile = { + id: 11, + tileType: 'custom', + tileTitle: 'Mail', + tileIcon: 'mdi-mail', + tileLinkType: 'url', + tileLinkValue: 'https://mail', + content: { healthPingEnabled: true, pingInterval: 30 }, + } + const widget = { id: 12, widgetId: 'nc-calendar', content: {} } + + it('a tile\'s edit opens the tile editor with its data; its remove deletes the placement', async () => { + const { wrapper, dashStore } = await mountViews({ widgetPlacements: [tile, widget] }) + const tileStub = wrapper.findComponent({ name: 'TileWidget' }) + expect(tileStub.props('placementId')).toBe(11) + + await tileStub.vm.$emit('edit') + await flushPromises() + const editor = wrapper.findComponent({ name: 'TileEditor' }) + expect(editor.props('open')).toBe(true) + expect(editor.props('tile')).toMatchObject({ + id: 11, + title: 'Mail', + linkValue: 'https://mail', + healthPingEnabled: true, + pingInterval: 30, + }) + + await tileStub.vm.$emit('remove') + await flushPromises() + expect(dashStore.removeWidgetFromDashboard).toHaveBeenCalledWith(11) + }, 90000) + + it('a widget\'s remove, style and edit reach the store and the style editor', async () => { + const { wrapper, dashStore } = await mountViews({ widgetPlacements: [tile, widget] }) + const wrapperStub = wrapper.findComponent({ name: 'WidgetWrapper' }) + expect(wrapperStub.props('placement')).toEqual(widget) + + await wrapperStub.vm.$emit('remove') + await flushPromises() + expect(dashStore.removeWidgetFromDashboard).toHaveBeenCalledWith(12) + + expect(wrapper.findComponent({ name: 'CnWidgetStyleEditorModal' }).exists()).toBe(false) + await wrapperStub.vm.$emit('style') + let editor = wrapper.findComponent({ name: 'CnWidgetStyleEditorModal' }) + expect(editor.props('show')).toBe(true) + expect(editor.props('widget')).toEqual(widget) + + await editor.vm.$emit('close') + await flushPromises() + expect(wrapper.findComponent({ name: 'CnWidgetStyleEditorModal' }).exists()).toBe(false) + + // A stock Nextcloud widget has no registry form, so "edit" also + // lands on the style editor. + await wrapperStub.vm.$emit('edit') + editor = wrapper.findComponent({ name: 'CnWidgetStyleEditorModal' }) + expect(editor.props('show')).toBe(true) + }, 90000) + + // @spec openspec/changes/archive/2026-11-24-visibility-dialog-board-sync/specs/conditional-visibility-editor/spec.md#requirement-the-dialog-is-in-the-widgets-menu-req-cvui-007 + it('"Who sees this widget?" in the widget\'s menu opens the dialog for that widget', async () => { + const news = { ...widget, customTitle: 'News', ruleMatch: 'all' } + const { wrapper, dashStore } = await mountViews({ widgetPlacements: [news] }) + dashStore.refreshPlacementVisibility = vi.fn() + + await wrapper.findComponent({ name: 'WidgetWrapper' }).vm.$emit('whoSees', news) + await flushPromises() + + const modal = wrapper.findComponent({ name: 'VisibilityRulesModal' }) + expect(modal.props('open')).toBe(true) + expect(modal.props('placementId')).toBe(news.id) + expect(modal.props('widgetTitle')).toBe('News') + expect(modal.props('dashboardName')).toBe('Home') + expect(modal.props('ruleMatch')).toBe('all') + + await modal.vm.$emit('ruleMatchChanged', 'any') + expect(dashStore.widgetPlacements[0].ruleMatch).toBe('any') + expect(dashStore.refreshPlacementVisibility).toHaveBeenCalled() + expect(modal.props('ruleMatch')).toBe('any') + }, 90000) +}) + +describe('Views — right-click context menu', () => { + const placement = { id: 21, widgetId: 'nc-calendar', content: {} } + + /** + * Mount, enter edit mode through the cog and right-click the widget. + * + * @return {Promise<{wrapper: object, dashStore: object}>} the mount. + */ + async function openMenu() { + const mounted = await mountViews({ widgetPlacements: [placement] }) + mounted.wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('toggleEdit') + await flushPromises() + await mounted.wrapper + .find('.launchpad-grid-item[data-placement-id="21"]') + .trigger('contextmenu', { clientX: 40, clientY: 50 }) + return mounted + } + + it('opens at the cursor only in edit mode', async () => { + const { wrapper } = await mountViews({ widgetPlacements: [placement] }) + await wrapper.find('.launchpad-grid-item').trigger('contextmenu', { clientX: 40, clientY: 50 }) + expect(wrapper.find('.stub-ctx').exists()).toBe(false) + + wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('toggleEdit') + await flushPromises() + await wrapper.find('.launchpad-grid-item').trigger('contextmenu', { clientX: 40, clientY: 50 }) + const menu = wrapper.findComponent({ name: 'WidgetContextMenu' }) + expect(menu.props('left')).toBe(40) + expect(menu.props('top')).toBe(50) + }, 90000) + + it('"Edit" closes the menu and opens the style editor for the widget', async () => { + const { wrapper } = await openMenu() + await wrapper.findComponent({ name: 'WidgetContextMenu' }).vm.$emit('edit') + + expect(wrapper.find('.stub-ctx').exists()).toBe(false) + expect(wrapper.findComponent({ name: 'CnWidgetStyleEditorModal' }).props('widget')).toEqual(placement) + }, 90000) + + it('"Move" opens the keyboard move panel for the widget', async () => { + const { wrapper } = await openMenu() + await wrapper.findComponent({ name: 'WidgetContextMenu' }).vm.$emit('move') + + const panel = wrapper.findComponent({ name: 'WidgetMovePanel' }) + expect(panel.props('open')).toBe(true) + expect(panel.props('placement')).toEqual(placement) + expect(wrapper.find('.stub-ctx').exists()).toBe(false) + }, 90000) + + it('"Remove" deletes the placement through the store', async () => { + const { wrapper, dashStore } = await openMenu() + await wrapper.findComponent({ name: 'WidgetContextMenu' }).vm.$emit('remove') + await flushPromises() + + expect(dashStore.removeWidgetFromDashboard).toHaveBeenCalledWith(21) + expect(wrapper.find('.stub-ctx').exists()).toBe(false) + }, 90000) + + it('"Visibility rules" opens the rules editor for the placement', async () => { + const { wrapper } = await openMenu() + await wrapper.findComponent({ name: 'WidgetContextMenu' }).vm.$emit('visibilityRules') + + const modal = wrapper.findComponent({ name: 'VisibilityRulesModal' }) + expect(modal.props('open')).toBe(true) + expect(modal.props('placementId')).toBe(21) + }, 90000) + + it('"Read confirmation" opens its dialog; closing it without saving drops it', async () => { + const { wrapper, dashStore } = await openMenu() + const menu = wrapper.findComponent({ name: 'WidgetContextMenu' }) + await menu.vm.$emit('readConfirmation') + await menu.vm.$emit('close') + expect(wrapper.find('.stub-ctx').exists()).toBe(false) + + const dialog = wrapper.findComponent({ name: 'ReadConfirmationDialog' }) + expect(dialog.props('placement')).toEqual(placement) + + await dialog.vm.$emit('update:open', true) + expect(wrapper.find('.stub-read-confirmation').exists()).toBe(true) + await dialog.vm.$emit('update:open', false) + expect(wrapper.find('.stub-read-confirmation').exists()).toBe(false) + expect(dashStore.updateWidgetPlacement).not.toHaveBeenCalled() + }, 90000) +}) + +describe('Views — lifecycle', () => { + it('loads the stores, the default preference and the personal layer of a dashboard it does not own', async () => { + const { dashStore } = await mountViews({ + activeDashboard: { id: 9, uuid: 'u-9', name: 'Team', isOwner: false }, + }) + + expect(dashStore.loadDashboards).toHaveBeenCalledTimes(1) + expect(dashStore.fetchPendingAcknowledgements).toHaveBeenCalledTimes(1) + expect(axios.get).toHaveBeenCalledWith(`${BASE}/api/dashboards/default`) + expect(axios.get).toHaveBeenCalledWith(`${BASE}/api/dashboards/9/personal-layer`) + // The boot view-event waits for the page to settle; leaving sends it. + expect(wrapper.vm.defaultDashboardUuid).toBe('u-default') + expect(dashStore.recordViewEvent).not.toHaveBeenCalled() + wrapper.unmount() + wrapper = null + expect(dashStore.recordViewEvent).toHaveBeenCalledWith('u-9') + }, 90000) + + it('logs a failed default-preference read and keeps no default', async () => { + const { logger } = await import('../../utils/logger.js') + const error = vi.spyOn(logger, 'error').mockImplementation(() => {}) + const failure = new Error('down') + routeAxios({ + get: (url) => (url === `${BASE}/api/dashboards/default` + ? Promise.reject(failure) + : Promise.resolve({ data: {} })), + }) + + await mountViews() + + expect(error).toHaveBeenCalledWith( + '[Views] Failed to load default-dashboard preference:', + failure, + ) + expect(wrapper.vm.defaultDashboardUuid).toBe('') + error.mockRestore() + }, 90000) + + it('`?edit=1` in the address opens the page in edit mode for an editor', async () => { + window.history.replaceState(null, '', '/apps/launchpad?edit=1') + await mountViews() + + expect(axios.post).toHaveBeenCalledWith(`${BASE}/api/dashboards/u-7/presence`) + expect(wrapper.find('.launchpad-container').classes()).toContain('launchpad-edit-mode') + }, 90000) + + it('`?edit=1` is ignored for a view-only reader', async () => { + window.history.replaceState(null, '', '/apps/launchpad?edit=1') + await mountViews({ permissionLevel: 'view_only' }) + + expect(axios.post).not.toHaveBeenCalled() + expect(wrapper.find('.launchpad-container').classes()).not.toContain('launchpad-edit-mode') + }, 90000) + + it('switching to another dashboard records a view and pushes its address', async () => { + const { dashStore } = await mountViews() + routeAxios({ + get: (url) => (url === `${BASE}/api/dashboards/u-8/path` + ? Promise.resolve({ data: { path: 'team/hr' } }) + : Promise.resolve({ data: {} })), + }) + const push = vi.spyOn(window.history, 'pushState') + + dashStore.activeDashboard = { id: 8, uuid: 'u-8', name: 'HR', isOwner: true } + await flushPromises() + + expect(dashStore.recordViewEvent).toHaveBeenCalledWith('u-8') + expect(push).toHaveBeenCalledWith( + { uuid: 'u-8', source: 'launchpad-deeplink' }, + '', + `${BASE}/team/hr`, + ) + push.mockRestore() + }, 90000) + + it('docks the controls into a greeting row, floats them in edit mode and docks again after', async () => { + await mountViews({ + widgetPlacements: [{ id: 31, widgetId: 'header', ground: true, content: {} }], + attach: true, + }) + const controls = () => document.querySelector('[data-testid="launchpad-top-controls"]') + + expect(controls().classList.contains('launchpad-floating-controls--docked')).toBe(true) + expect(controls().closest('.cn-header-widget--ground')).not.toBeNull() + + wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('toggleEdit') + await flushPromises() + expect(controls().classList.contains('launchpad-floating-controls--docked')).toBe(false) + expect(controls().closest('.cn-header-widget--ground')).toBeNull() + }, 90000) + + it('docks the controls once a greeting row appears after mount', async () => { + const { dashStore } = await mountViews({ + widgetPlacements: [{ id: 41, widgetId: 'nc-calendar', content: {} }], + attach: true, + }) + const controls = () => document.querySelector('[data-testid="launchpad-top-controls"]') + // Without a greeting row the page title row holds the controls. + expect(controls().closest('.launchpad-page-header')).not.toBeNull() + + dashStore.widgetPlacements = [ + { id: 41, widgetId: 'nc-calendar', content: {} }, + { id: 42, widgetId: 'header', ground: true, content: { ground: true } }, + ] + await flushPromises() + // The MutationObserver callback runs as a microtask after the DOM change. + await new Promise((resolve) => setTimeout(resolve, 0)) + await flushPromises() + + expect(controls().closest('.cn-header-widget--ground')).not.toBeNull() + }, 90000) + + it('unmounting withdraws the presence and stops following the back button', async () => { + await mountViews() + wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('toggleEdit') + await flushPromises() + const removed = vi.spyOn(window, 'removeEventListener') + const popHandler = wrapper.vm.handleHistoryPopState + + wrapper.unmount() + wrapper = null + await flushPromises() + + expect(axios.delete).toHaveBeenCalledWith(`${BASE}/api/dashboards/u-7/presence`, undefined) + expect(removed).toHaveBeenCalledWith('popstate', popHandler) + removed.mockRestore() + }, 90000) + + it('a refused renewal (403) drops the page back to view mode', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }) + try { + await mountViews() + wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$emit('toggleEdit') + await flushPromises() + expect(wrapper.find('.launchpad-container').classes()).toContain('launchpad-edit-mode') + + axios.post.mockImplementation(() => Promise.reject({ response: { status: 403 } })) + vi.advanceTimersByTime(30 * 1000) + await flushPromises() + + expect(wrapper.findComponent({ name: 'EditLockBanner' }).props('status')).toBe('forbidden') + expect(wrapper.find('.launchpad-container').classes()).not.toContain('launchpad-edit-mode') + } finally { + vi.useRealTimers() + } + }, 90000) +}) + +describe('Views — states without a full dashboard', () => { + it('explains that personal dashboards are off when the admin disabled them', async () => { + await mountViews({ activeDashboard: null, allowUserDashboards: false }) + + expect(wrapper.find('.stub-empty').text()).toBe( + 'Personal dashboards are not enabled by your administrator', + ) + }, 90000) + + it('offers no versions and no duplicate for a dashboard without a uuid', async () => { + await mountViews({ activeDashboard: { id: 5, name: 'Legacy', isOwner: true } }) + + await wrapper.setData({ isConfigModalOpen: true }) + expect(wrapper.findComponent({ name: 'DashboardConfigModal' }).vm.$attrs.canViewVersions).toBe(false) + expect(wrapper.findComponent({ name: 'DashboardMoreMenu' }).vm.$attrs.canDuplicate).toBe(false) + }, 90000) + + it('hands the Nextcloud widget catalog from the widget store to the add-widget form', async () => { + await mountViews({ availableWidgets: [{ id: 'calendar' }, { id: 'mail' }] }) + + expect(wrapper.findAll('.stub-add-widget li').map((li) => li.text())).toEqual(['calendar', 'mail']) + }, 90000) +}) + +describe('Views — the reactions bar at the foot', () => { + /** + * @spec openspec/changes/archive/2026-11-24-reactions-bar-at-the-foot/specs/dashboard-reactions/spec.md#requirement-req-rxn-010-a-viewer-can-react-from-the-dashboard + */ + it('renders the reactions bar after the grid, under the last widget', async () => { + const { wrapper } = await mountViews({ + widgetPlacements: [{ id: 1, widgetId: 'text', gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 2 }], + }) + const grid = wrapper.find('.stub-grid').element + const bar = wrapper.find('.stub-reactions').element + expect(grid).toBeTruthy() + expect(bar).toBeTruthy() + expect(grid.compareDocumentPosition(bar) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + }, 90000) +}) diff --git a/src/views/__tests__/Views.widgetPicker.methods.spec.js b/src/views/__tests__/Views.widgetPicker.methods.spec.js new file mode 100644 index 000000000..f082bdda4 --- /dev/null +++ b/src/views/__tests__/Views.widgetPicker.methods.spec.js @@ -0,0 +1,53 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * What the workspace hands the widget picker (widget-picker-board-sync): the + * role's allow-list for the grey cards, and an app tile from the picker + * placed as one cell. Run against the real Views methods and computed + * properties on a stand-in host. + * + * @spec openspec/changes/widget-picker-board-sync/specs/widgets/spec.md + */ + +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' + +const state = { allowedWidgets: null } + +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) +vi.mock('../../utils/loadInitialState.js', async (importOriginal) => ({ + ...(await importOriginal()), + loadInitialState: () => ({ allowedWidgets: state.allowedWidgets }), +})) + +let Views + +beforeAll(async () => { + Views = (await import('../Views.vue')).default +}) + +afterEach(() => { + state.allowedWidgets = null +}) + +describe('Views and the widget picker', () => { + it('hands the picker the role\'s allow-list, or null for no limit', () => { + expect(Views.computed.pickerAllowedWidgets.call({})).toBeNull() + state.allowedWidgets = ['clock', 'tile'] + expect(Views.computed.pickerAllowedWidgets.call({})).toEqual(['clock', 'tile']) + state.allowedWidgets = 'garbage' + expect(Views.computed.pickerAllowedWidgets.call({})).toBeNull() + }) + + it('places a catalogue app from the picker as a one-cell tile', async () => { + const host = { addTileToDashboard: vi.fn().mockResolvedValue({ id: 9 }) } + const app = { uuid: 'z1', name: 'Case system', icon: '/z.svg', iconType: 'url', linkType: 'url', linkValue: 'https://zaken.example' } + await Views.methods.addCatalogueApp.call(host, app) + expect(host.addTileToDashboard).toHaveBeenCalledWith( + { title: 'Case system', icon: '/z.svg', iconType: 'url', linkType: 'url', linkValue: 'https://zaken.example' }, + { w: 1, h: 1 }, + ) + }) +}) diff --git a/src/views/__tests__/ViewsAddTiles.spec.js b/src/views/__tests__/ViewsAddTiles.spec.js new file mode 100644 index 000000000..10516b11d --- /dev/null +++ b/src/views/__tests__/ViewsAddTiles.spec.js @@ -0,0 +1,115 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Views' side of the Add tiles dialog (add-tiles-dialog REQ-TILE-043): it + * opens with its lists loaded, places the chosen tiles and hands a bookmarks + * file to the bookmark import. + * + * @spec openspec/changes/add-tiles-dialog/specs/tiles/spec.md + */ +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { logger } from '../../utils/logger.js' + +vi.mock('../../services/api.js', () => ({ + api: { + catalogueApps: vi.fn(), + discoverApps: vi.fn(), + officeTilePack: vi.fn(), + }, +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) + +let Views + +function makeHost(state = {}) { + const host = { + widgetPlacements: [], + discoveredApps: [], + catalogueApps: [], + officeTiles: [], + isAddTilesOpen: false, + isBookmarkImportOpen: false, + bookmarkInitialFile: null, + ...state, + } + for (const [name, fn] of Object.entries(Views.methods)) { + if (!(name in state)) { + host[name] = fn.bind(host) + } + } + return host +} + +beforeEach(async () => { + setActivePinia(createPinia()) + vi.clearAllMocks() + Views = (await import('../Views.vue')).default +}) + +describe('Views Add tiles', () => { + it('opens the dialog with the catalogue, the found apps and the office pack loaded', async () => { + const office = [{ title: 'Word', linkType: 'create', linkValue: 'doc' }] + api.discoverApps.mockResolvedValue({ data: { apps: [{ appId: 'grafana' }] } }) + api.catalogueApps.mockResolvedValue({ data: { apps: [{ name: 'Wiki' }] } }) + api.officeTilePack.mockResolvedValue({ data: { tiles: office } }) + const host = makeHost() + + await host.openAddTilesModal() + + expect(host.isAddTilesOpen).toBe(true) + expect(host.discoveredApps).toEqual([{ appId: 'grafana' }]) + expect(host.catalogueApps).toEqual([{ name: 'Wiki' }]) + expect(host.officeTiles).toEqual(office) + }) + + it('leaves the Office section empty when the pack does not load', async () => { + const error = new Error('down') + api.officeTilePack.mockRejectedValue(error) + const host = makeHost({ officeTiles: ['stale'] }) + + await host.loadOfficeTiles() + + expect(host.officeTiles).toEqual([]) + expect(logger.warn).toHaveBeenCalledWith('[Views] Could not load the office tiles:', error) + }) + + it('places a found app as an app tile and the rest as tiles, in order', async () => { + const calls = [] + const addWidgetToDashboard = vi.fn(async (payload) => calls.push(['widget', payload])) + const addTileToDashboard = vi.fn(async (tile) => calls.push(['tile', tile])) + const host = makeHost({ addWidgetToDashboard, addTileToDashboard }) + const word = { title: 'Word', linkType: 'create', linkValue: 'doc' } + + await host.addChosenTiles([ + { key: 'app:grafana', kind: 'app-tile', tile: { appId: 'grafana' } }, + { key: 'create:doc', kind: 'tile', tile: word }, + ]) + + expect(calls).toEqual([ + ['widget', { type: 'app-tile', content: { appId: 'grafana', colour: '', showCount: true } }], + ['tile', word], + ]) + }) + + it('stops and rejects when a placement fails, so the dialog stays open', async () => { + const host = makeHost({ addTileToDashboard: vi.fn().mockRejectedValue(new Error('409')) }) + await expect(host.addChosenTiles([{ kind: 'tile', tile: { title: 'x' } }])).rejects.toThrow('409') + }) + + it('hands a bookmarks file to the bookmark import', () => { + const host = makeHost({ isAddTilesOpen: true }) + const file = { name: 'bookmarks.html' } + + host.onAddTilesImportBookmarks(file) + + expect(host.isAddTilesOpen).toBe(false) + expect(host.bookmarkInitialFile).toBe(file) + expect(host.isBookmarkImportOpen).toBe(true) + }) +}) diff --git a/src/views/__tests__/ViewsBootPath.spec.js b/src/views/__tests__/ViewsBootPath.spec.js new file mode 100644 index 000000000..7d31137a3 --- /dev/null +++ b/src/views/__tests__/ViewsBootPath.spec.js @@ -0,0 +1,51 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * A slug address opens the dashboard it names even though the router's + * catch-all has already redirected the address to `/` when the workspace + * page is created (REQ-DDL-002). + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../services/api.js', () => ({ + api: { getDefaultDashboardPreference: vi.fn(async () => ({ data: { uuid: '' } })) }, +})) +vi.mock('../../stores/dashboard.js', () => ({ + useDashboardStore: () => ({ + loadDashboards: vi.fn(async () => {}), + fetchPendingAcknowledgements: vi.fn(), + }), +})) +vi.mock('../../stores/widgets.js', () => ({ + useWidgetStore: () => ({ loadAvailableWidgets: vi.fn(async () => {}) }), +})) +vi.mock('../../stores/tiles.js', () => ({ + useTileStore: () => ({ loadTiles: vi.fn(async () => {}) }), +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +beforeEach(() => { + vi.resetModules() +}) + +describe('Views boot address', () => { + it('hands the deep-link check the address the page was opened on, not the redirected one', async () => { + window.history.replaceState(null, '', '/index.php/apps/launchpad/team/a') + const Views = (await import('../Views.vue')).default + // The router's catch-all redirect, before the route component exists. + window.history.replaceState(null, '', '/index.php/apps/launchpad/') + + const openDeepLinkedDashboard = vi.fn(async () => {}) + const openHashLinkedDashboard = vi.fn(async () => {}) + const host = { grid: {}, canEdit: false, openDeepLinkedDashboard, openHashLinkedDashboard, replaceUrlAfterBoot: vi.fn(async () => {}), loadDefaultDashboardPreference: vi.fn(async () => {}) } + await Views.created.call(host) + + expect(openDeepLinkedDashboard).toHaveBeenCalledWith( + '/index.php/apps/launchpad/team/a', + ) + }) +}) diff --git a/src/views/__tests__/ViewsCoEditing.spec.js b/src/views/__tests__/ViewsCoEditing.spec.js new file mode 100644 index 000000000..82dde9523 --- /dev/null +++ b/src/views/__tests__/ViewsCoEditing.spec.js @@ -0,0 +1,126 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The workspace page enters edit mode while colleagues edit the same + * dashboard, shows them, and withdraws its presence on every way out + * (building-edit-a-dashboard-together, tasks 1.1 and 1.4). The real + * Views.vue methods run against a small host object, with the presence + * composable driven through the real api module shapes. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useDashboardPresence } from '../../composables/useDashboardPresence.js' +import { api } from '../../services/api.js' + +vi.mock('../../services/api.js', () => ({ + api: { + joinPresence: vi.fn(), + leavePresence: vi.fn(() => Promise.resolve({ status: 204 })), + acquireLock: vi.fn(), + }, +})) + +let Views +function failure(status) { + return Object.assign(new Error('http'), { response: { status, data: {} } }) +} + +/** + * A host with the Views methods bound, as the component would have them. + * + * @return {object} host + */ +function makeHost() { + const host = { + isEditMode: false, + isWidgetModalOpen: false, + isTileEditorOpen: false, + activeDashboard: { id: 7, uuid: 'dash-uuid', name: 'Finance' }, + closeWidgetModal: vi.fn(), + closeStyleEditor: vi.fn(), + grid: { closeContextMenu: vi.fn() }, + } + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + // The mapped store action, replaced after binding. + host.switchDashboard = vi.fn() + host.presence = useDashboardPresence({ onRefused: () => host.onPresenceRefused() }) + return host +} + +beforeEach(async () => { + vi.clearAllMocks() + Views = (await import('../Views.vue')).default +}) + +describe('Views co-editing', () => { + it('a second editor edits instead of waiting, and sees the first one', async () => { + const marieke = { displayName: 'Marieke Jansen', since: '2026-11-14T10:42:00+01:00' } + api.joinPresence.mockResolvedValue({ data: { editors: [marieke] } }) + const host = makeHost() + await host.toggleEditMode() + expect(api.joinPresence).toHaveBeenCalledWith('dash-uuid') + expect(api.acquireLock).not.toHaveBeenCalled() + expect(host.isEditMode).toBe(true) + expect(host.presence.state.editors).toEqual([marieke]) + await host.presence.stop() + }) + + it('no edit rights (403) or an unknown dashboard (404) keep the page read-only', async () => { + const host = makeHost() + api.joinPresence.mockRejectedValue(failure(403)) + await host.toggleEditMode() + expect(host.isEditMode).toBe(false) + expect(host.presence.state.status).toBe('forbidden') + + await host.openWidgetModal() + expect(host.isWidgetModalOpen).toBe(false) + + api.joinPresence.mockRejectedValue(failure(404)) + await host.toggleEditMode() + expect(host.isEditMode).toBe(false) + }) + + it('a failed request does not stop the editor', async () => { + api.joinPresence.mockRejectedValue(new Error('Network Error')) + const host = makeHost() + await host.toggleEditMode() + expect(host.isEditMode).toBe(true) + await host.presence.stop() + }) + + it('leaving edit mode and switching dashboards withdraw the presence', async () => { + api.joinPresence.mockResolvedValue({ data: { editors: [] } }) + const host = makeHost() + await host.toggleEditMode() + await host.toggleEditMode() + expect(host.isEditMode).toBe(false) + expect(api.leavePresence).toHaveBeenCalledTimes(1) + expect(api.leavePresence).toHaveBeenLastCalledWith('dash-uuid') + + await host.toggleEditMode() + await host.onSidebarSwitch(8, 'group') + expect(host.isEditMode).toBe(false) + expect(api.leavePresence).toHaveBeenCalledTimes(2) + expect(host.switchDashboard).toHaveBeenCalledWith(8) + }) + + it('a refused renewal drops the page back to view mode', async () => { + vi.useFakeTimers() + try { + api.joinPresence.mockResolvedValueOnce({ data: { editors: [] } }) + const host = makeHost() + await host.toggleEditMode() + expect(host.isEditMode).toBe(true) + + api.joinPresence.mockRejectedValue(failure(403)) + await vi.advanceTimersByTimeAsync(30 * 1000) + expect(host.isEditMode).toBe(false) + expect(host.presence.state.status).toBe('forbidden') + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/views/__tests__/ViewsCompulsoryRemove.spec.js b/src/views/__tests__/ViewsCompulsoryRemove.spec.js new file mode 100644 index 000000000..1938b0061 --- /dev/null +++ b/src/views/__tests__/ViewsCompulsoryRemove.spec.js @@ -0,0 +1,84 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Deleting a compulsory widget from a template copy says why it cannot be + * done and sends nothing; any other widget is removed as before + * (admin-templates REQ-TMPL-023). Both menus end in `removeWidget`, which is + * what is called here, the way the menus call it. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('@nextcloud/l10n', async (importOriginal) => ({ + ...(await importOriginal()), + t: (_app, text, vars = {}) => + text.replace(/\{(\w+)\}/g, (_m, k) => vars[k] ?? `{${k}}`), +})) + +let Views +let showError + +/** + * @param {object[]} placements The dashboard's placements. + * @param {string} permissionLevel The copy's permission level. + * @return {object} host with the real Views methods. + */ +function makeHost(placements, permissionLevel = 'add_only') { + const host = { + widgetPlacements: placements, + permissionLevel, + } + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + // The store action is mapped into `methods`; the double goes on after + // the bind, as ViewsPersonalHide.spec.js does with `switchDashboard`. + host.removeWidgetFromDashboard = vi.fn().mockResolvedValue() + return host +} + +const attention = { + id: 7, + widgetId: 'attention', + customTitle: 'Vandaag eerst', + isCompulsory: 1, +} +const cases = { + id: 8, + widgetId: 'object-list', + customTitle: 'Mijn zaken', + isCompulsory: 0, +} + +beforeEach(async () => { + vi.clearAllMocks() + Views = (await import('../Views.vue')).default + showError = (await import('@nextcloud/dialogs')).showError +}) + +describe('Views removes a widget', () => { + it('explains a compulsory widget and sends nothing', async () => { + const host = makeHost([attention, cases]) + await host.removeWidget(7) + expect(showError).toHaveBeenCalledWith( + '"Vandaag eerst" is part of the start page your administrator set for your group and cannot be removed.', + ) + expect(host.removeWidgetFromDashboard).not.toHaveBeenCalled() + }) + + it('removes a widget that is not compulsory, with no message', async () => { + const host = makeHost([attention, cases]) + await host.removeWidget(8) + expect(showError).not.toHaveBeenCalled() + expect(host.removeWidgetFromDashboard).toHaveBeenCalledWith(8) + }) + + it('lets a full-permission copy remove a compulsory widget', async () => { + const host = makeHost([attention], 'full') + await host.removeWidget(7) + expect(showError).not.toHaveBeenCalled() + expect(host.removeWidgetFromDashboard).toHaveBeenCalledWith(7) + }) +}) diff --git a/src/views/__tests__/ViewsDeepLinkPrefix.spec.js b/src/views/__tests__/ViewsDeepLinkPrefix.spec.js new file mode 100644 index 000000000..1d8c3293a --- /dev/null +++ b/src/views/__tests__/ViewsDeepLinkPrefix.spec.js @@ -0,0 +1,92 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * With pretty URLs on, `generateUrl` drops `/index.php`, but a page opened + * through the front controller has its router mounted under it. The deep + * link the page writes keeps the prefix it was opened on, so the address + * stays under the router's base. A unified search result's + * `#dashboard/` link opens the dashboard it names. + * + * @spec openspec/specs/dashboard-deeplinking/spec.md + */ + +import { beforeAll, describe, expect, it, vi } from 'vitest' + +vi.mock('../../services/api.js', () => ({ + api: { getDashboardPath: vi.fn(), getDashboardByPath: vi.fn() }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => path, + generateOcsUrl: (path) => `/ocs/v2.php${path}`, + imagePath: (app, file) => `/${app}/img/${file}`, + generateFilePath: (app, type, file) => `/${app}/${type}/${file}`, + linkTo: (app, file) => `/${app}/${file}`, +})) +vi.mock('../../stores/tileSearch.js', () => ({ + useTileSearchStore: vi.fn(), +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +let Views + +/** + * A host carrying the real Views methods. + * + * @param {object} state Data and overrides. + * @return {object} the host. + */ +function makeHost(state = {}) { + const host = { activeDashboard: null } + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + return Object.assign(host, state) +} + +beforeAll(async () => { + window.history.replaceState(null, '', '/index.php/apps/launchpad/team/hr') + Views = (await import('../Views.vue')).default +}) + +describe('Views deep link under the front controller', () => { + it('builds the address under the prefix the page was opened on', () => { + expect(makeHost().buildDeepLinkUrl('team/hr')).toBe('/index.php/apps/launchpad/team/hr') + }) + + it('leaves the boot address alone when it already is the deep link', () => { + const replace = vi.spyOn(window.history, 'replaceState') + makeHost({ injectedDeepLinkPath: 'team/hr', activeDashboard: { uuid: 'u-hr' } }) + .replaceUrlFromInitialState() + expect(replace).not.toHaveBeenCalled() + expect(window.location.pathname).toBe('/index.php/apps/launchpad/team/hr') + }) +}) + +describe('Views unified search link', () => { + it('opens the dashboard a #dashboard/ hash names', async () => { + const switchDashboard = vi.fn() + const host = makeHost({ + activeDashboard: { uuid: 'u-other' }, + dashboards: [{ id: 1, uuid: 'u-other' }, { id: 2, uuid: 'u-target' }], + switchDashboard, + }) + await host.openHashLinkedDashboard('#dashboard/u-target;widget=7') + expect(switchDashboard).toHaveBeenCalledWith(2) + }) + + it('keeps the open dashboard for its own uuid, an unknown uuid or another hash', async () => { + const switchDashboard = vi.fn() + const host = makeHost({ + activeDashboard: { uuid: 'u-other' }, + dashboards: [{ id: 1, uuid: 'u-other' }], + switchDashboard, + }) + await host.openHashLinkedDashboard('#dashboard/u-other') + await host.openHashLinkedDashboard('#dashboard/u-gone') + await host.openHashLinkedDashboard('#user-settings') + expect(switchDashboard).not.toHaveBeenCalled() + }) +}) diff --git a/src/views/__tests__/ViewsDialogFocus.spec.js b/src/views/__tests__/ViewsDialogFocus.spec.js new file mode 100644 index 000000000..43e53233a --- /dev/null +++ b/src/views/__tests__/ViewsDialogFocus.spec.js @@ -0,0 +1,90 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Closing the widget picker or the widget form never leaves focus on the page + * body (REQ-WDG-013 "focus MUST return to the element that triggered the open"). + */ + +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) + +let Views + +/** + * A host with the real Views methods. + * + * @return {object} host + */ +function makeHost() { + const host = {} + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + return host +} + +/** + * Put the More menu button on the page. + * + * @return {HTMLElement} the button. + */ +function moreMenuButton() { + const menu = document.createElement('div') + menu.setAttribute('data-testid', 'launchpad-more-menu') + menu.innerHTML = '' + document.body.appendChild(menu) + return menu.querySelector('button') +} + +/** + * Let the restore's task run. + * + * @return {Promise} + */ +function settle() { + return new Promise((resolve) => setTimeout(resolve, 5)) +} + +beforeEach(async () => { + setActivePinia(createPinia()) + Views = (await import('../Views.vue')).default +}) + +afterEach(() => { + document.body.innerHTML = '' +}) + +describe('Views widget dialog focus', () => { + it('a widget form closed before its focus trap ran gives focus to the More menu button', async () => { + const button = moreMenuButton() + const pickerItem = document.createElement('button') + document.body.appendChild(pickerItem) + pickerItem.focus() + const host = makeHost() + host.widgetDialogOpener = document.activeElement + host.isCustomWidgetModalOpen = true + pickerItem.remove() + + host.closeCustomWidgetModal() + await settle() + + expect(host.isCustomWidgetModalOpen).toBe(false) + expect(document.activeElement).toBe(button) + }) + + it('a dismissed widget picker gives focus back to the More menu button', async () => { + const button = moreMenuButton() + const host = makeHost() + host.widgetDialogOpener = null + host.isWidgetModalOpen = true + + host.onWidgetPickerClose() + await settle() + + expect(host.isWidgetModalOpen).toBe(false) + expect(document.activeElement).toBe(button) + }) +}) diff --git a/src/views/__tests__/ViewsEditLock.spec.js b/src/views/__tests__/ViewsEditLock.spec.js deleted file mode 100644 index 14dbdba1f..000000000 --- a/src/views/__tests__/ViewsEditLock.spec.js +++ /dev/null @@ -1,144 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2026 Conduction B.V. - * SPDX-License-Identifier: EUPL-1.2 - * - * The workspace page enters edit mode only with the lock, and gives it back - * on every way out (dashboard-locking REQ-LOCKUI-001..003). The real - * Views.vue methods run against a small host object, with the lock - * composable driven through the real api module shapes. - */ - -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { useDashboardLock } from '../../composables/useDashboardLock.js' -import { api } from '../../services/api.js' - -vi.mock('../../services/api.js', () => ({ - api: { - acquireLock: vi.fn(), - heartbeatLock: vi.fn(), - releaseLock: vi.fn(() => Promise.resolve({ status: 204 })), - releaseLockOnPageHide: vi.fn(() => Promise.resolve({ status: 204 })), - forceReleaseLock: vi.fn(), - }, -})) - -let Views -function conflict(status, data) { - return Object.assign(new Error('http'), { response: { status, data } }) -} - -/** - * A host with the Views methods bound, as the component would have them. - * - * @return {object} host - */ -function makeHost() { - const host = { - isEditMode: false, - isWidgetModalOpen: false, - isTileEditorOpen: false, - forceReleaseDialogOpen: false, - activeDashboard: { id: 7, uuid: 'dash-uuid', name: 'Finance' }, - closeWidgetModal: vi.fn(), - closeStyleEditor: vi.fn(), - grid: { closeContextMenu: vi.fn() }, - } - for (const [name, fn] of Object.entries(Views.methods)) { - host[name] = fn.bind(host) - } - // The mapped store action, replaced after binding. - host.switchDashboard = vi.fn() - host.editLock = useDashboardLock({ onLost: () => host.onEditLockLost() }) - return host -} - -beforeEach(async () => { - vi.clearAllMocks() - Views = (await import('../Views.vue')).default -}) - -describe('Views edit lock', () => { - it('REQ-LOCKUI-001: Edit enters edit mode when the lock is granted', async () => { - api.acquireLock.mockResolvedValue({ - data: { displayName: 'Pieter', expiresIn: 900 }, - }) - const host = makeHost() - await host.toggleEditMode() - expect(api.acquireLock).toHaveBeenCalledWith('dash-uuid') - expect(host.isEditMode).toBe(true) - host.editLock.stop() - }) - - it("REQ-LOCKUI-001: a colleague's lock keeps the page read-only", async () => { - api.acquireLock.mockRejectedValue( - conflict(409, { - code: 'lock_conflict', - lock: { displayName: 'Sanne', expiresIn: 900 }, - }), - ) - const host = makeHost() - await host.toggleEditMode() - expect(host.isEditMode).toBe(false) - expect(host.editLock.state.status).toBe('blocked') - - await host.openWidgetModal() - expect(host.isWidgetModalOpen).toBe(false) - await host.openTileEditor() - expect(host.isTileEditorOpen).toBe(false) - }) - - it('REQ-LOCKUI-001: 403 and a failed request keep the page read-only', async () => { - const host = makeHost() - api.acquireLock.mockRejectedValue(conflict(403, { code: 'lock_forbidden' })) - await host.toggleEditMode() - expect(host.isEditMode).toBe(false) - api.acquireLock.mockRejectedValue(new Error('Network Error')) - await host.toggleEditMode() - expect(host.isEditMode).toBe(false) - }) - - it('REQ-LOCKUI-001: leaving edit mode and switching dashboards release the lock', async () => { - api.acquireLock.mockResolvedValue({ data: {} }) - const host = makeHost() - await host.toggleEditMode() - await host.toggleEditMode() - expect(host.isEditMode).toBe(false) - expect(api.releaseLock).toHaveBeenCalledTimes(1) - - await host.toggleEditMode() - await host.onSidebarSwitch(8, 'group') - expect(host.isEditMode).toBe(false) - expect(api.releaseLock).toHaveBeenCalledTimes(2) - expect(host.switchDashboard).toHaveBeenCalledWith(8) - }) - - it('REQ-LOCKUI-002: a lost lock drops the page to view mode', async () => { - vi.useFakeTimers() - api.acquireLock.mockResolvedValue({ data: {} }) - api.heartbeatLock.mockRejectedValue( - conflict(404, { code: 'lock_not_found' }), - ) - const host = makeHost() - await host.toggleEditMode() - await vi.advanceTimersByTimeAsync(5 * 60 * 1000) - expect(host.isEditMode).toBe(false) - expect(host.editLock.state.status).toBe('lost') - vi.useRealTimers() - }) - - it('REQ-LOCKUI-003: a confirmed take-over edits', async () => { - api.acquireLock.mockRejectedValueOnce( - conflict(409, { code: 'lock_conflict', lock: { displayName: 'Sanne' } }), - ) - api.forceReleaseLock.mockResolvedValue({ data: { status: 'ok' } }) - const host = makeHost() - await host.toggleEditMode() - api.acquireLock.mockResolvedValue({ data: {} }) - host.forceReleaseDialogOpen = true - await host.onTakeOverConfirmed() - expect(host.forceReleaseDialogOpen).toBe(false) - expect(api.forceReleaseLock).toHaveBeenCalledWith('dash-uuid') - expect(host.isEditMode).toBe(true) - host.editLock.stop() - }) -}) diff --git a/src/views/__tests__/ViewsEditorsAndRowActions.spec.js b/src/views/__tests__/ViewsEditorsAndRowActions.spec.js new file mode 100644 index 000000000..560841b7a --- /dev/null +++ b/src/views/__tests__/ViewsEditorsAndRowActions.spec.js @@ -0,0 +1,536 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the editor and row-action methods of `Views.vue`: + * opening the config, share and create modals, the style editor round trip, + * the tile editor (edit pre-fill, close, delete), the custom-widget modal, + * server-app discovery, the upload and calendar transports, the row-cog + * actions that switch first and then act, the sidebar create and delete + * dialog, and publishing the active dashboard. + * + * The methods run on a plain host object, as the sibling Views specs do, so + * the grid, stores and modals are not mounted. Only the HTTP layer, the + * resource uploads and the logger are doubled; the dashboard store is the + * real Pinia store with its two publish actions spied. + */ + +import { showError } from '@nextcloud/dialogs' +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { uploadDataUrl, uploadFile } from '../../services/resourceService.js' +import { logger } from '../../utils/logger.js' + +vi.mock('../../services/api.js', () => ({ + api: { + discoverApps: vi.fn(), + getCalendarWidgetCalendars: vi.fn(), + officeTilePack: vi.fn(), + }, +})) +vi.mock('../../services/resourceService.js', () => ({ + uploadDataUrl: vi.fn(), + uploadFile: vi.fn(), +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) + +let Views + +/** + * A host carrying the given state, with every Views method bound to it + * unless the state overrides it. + * + * @param {object} state Fields and overrides + * @return {object} The host + */ +function makeHost(state = {}) { + const host = { + activeDashboard: null, + widgetPlacements: [], + permissionLevel: 'full', + isConfigModalOpen: false, + configModalMode: null, + configModalInitialTab: null, + configSaveError: 'stale', + isStyleEditorOpen: false, + editingPlacement: null, + styleEditorWidget: null, + isTileEditorOpen: false, + editingTile: null, + isCustomWidgetModalOpen: false, + customWidgetPreselectedType: 'x', + customWidgetEditing: 'x', + discoveredApps: ['stale'], + deleteTarget: null, + deleteChildCount: 3, + dashboards: [], + ...state, + } + for (const [name, fn] of Object.entries(Views.methods)) { + if (!(name in state)) { + host[name] = fn.bind(host) + } + } + return host +} + +beforeEach(async () => { + setActivePinia(createPinia()) + vi.clearAllMocks() + Views = (await import('../Views.vue')).default +}) + +describe('Views config modal openers', () => { + it('opens the config modal for the active dashboard on its general tab', () => { + const host = makeHost() + host.openConfigModal() + expect(host).toMatchObject({ configModalMode: 'edit', configModalInitialTab: 'general', isConfigModalOpen: true }) + }) + + it('opens the same modal on the sharing tab for the share action', () => { + const host = makeHost() + host.openShareDrawer() + expect(host).toMatchObject({ configModalMode: 'edit', configModalInitialTab: 'sharing', isConfigModalOpen: true }) + }) + + it('opens it in create mode, also through handleCreateDashboard', () => { + const host = makeHost({ configModalInitialTab: 'sharing' }) + host.handleCreateDashboard() + expect(host).toMatchObject({ configModalMode: 'create', isConfigModalOpen: true }) + expect(host.configModalInitialTab).toBe('sharing') + }) +}) + +describe('Views style editor', () => { + it('adds a widget through the store action', async () => { + const addWidgetToDashboard = vi.fn().mockResolvedValue(undefined) + await makeHost({ addWidgetToDashboard }).addWidget('notes') + expect(addWidgetToDashboard).toHaveBeenCalledWith('notes') + }) + + it('opens on a deep clone, so editing it leaves the live placement alone', () => { + const placement = { id: 4, customTitle: 'Nieuws', styleConfig: { color: 'red' } } + const host = makeHost() + + host.openStyleEditor(placement) + host.styleEditorWidget.styleConfig.color = 'blue' + + expect(host.isStyleEditorOpen).toBe(true) + expect(host.editingPlacement).toBe(placement) + expect(host.styleEditorWidget).not.toBe(placement) + expect(placement.styleConfig.color).toBe('red') + }) + + it('persists only the chrome and style of the saved clone, then closes', async () => { + const updateWidgetPlacement = vi.fn().mockResolvedValue(undefined) + const host = makeHost({ updateWidgetPlacement, editingPlacement: { id: 4 }, isStyleEditorOpen: true, styleEditorWidget: {} }) + + await host.onStyleSaved({ + id: 999, + widgetId: 'other', + showTitle: false, + customTitle: 'Agenda', + customIcon: 'mdi-calendar', + styleConfig: { backgroundColor: '#fff' }, + }) + + expect(updateWidgetPlacement).toHaveBeenCalledWith(4, { + showTitle: false, + customTitle: 'Agenda', + customIcon: 'mdi-calendar', + styleConfig: { backgroundColor: '#fff' }, + }) + expect(host).toMatchObject({ isStyleEditorOpen: false, editingPlacement: null, styleEditorWidget: null }) + }) + + it('saves nothing and stays open without a placement being edited', async () => { + const updateWidgetPlacement = vi.fn() + const host = makeHost({ updateWidgetPlacement, isStyleEditorOpen: true }) + + await host.onStyleSaved({ showTitle: true }) + + expect(updateWidgetPlacement).not.toHaveBeenCalled() + expect(host.isStyleEditorOpen).toBe(true) + }) + + it('deletes the edited placement and closes, and does nothing without one', async () => { + const removeWidget = vi.fn().mockResolvedValue(undefined) + const host = makeHost({ removeWidget, editingPlacement: { id: 8 }, isStyleEditorOpen: true }) + + await host.deleteWidget() + expect(removeWidget).toHaveBeenCalledWith(8) + expect(host.isStyleEditorOpen).toBe(false) + + removeWidget.mockClear() + const idle = makeHost({ removeWidget, isStyleEditorOpen: true }) + await idle.deleteWidget() + expect(removeWidget).not.toHaveBeenCalled() + expect(idle.isStyleEditorOpen).toBe(true) + }) +}) + +describe('Views tile editor', () => { + it('pre-fills the editor from a tile placement, health-ping config included', () => { + const openTileEditor = vi.fn() + makeHost({ openTileEditor }).openTileEditorForEdit({ + id: 12, + tileTitle: 'Status', + tileIcon: 'mdi-pulse', + tileIconType: 'mdi', + tileBackgroundColor: '#000', + tileTextColor: '#fff', + tileLinkType: 'url', + tileLinkValue: 'https://status.example.nl', + content: { healthPingEnabled: true, healthUrl: 'https://status.example.nl/health', expectedStatus: 204, pingInterval: 30 }, + }) + + expect(openTileEditor).toHaveBeenCalledWith({ + id: 12, + title: 'Status', + icon: 'mdi-pulse', + iconType: 'mdi', + backgroundColor: '#000', + textColor: '#fff', + linkType: 'url', + linkValue: 'https://status.example.nl', + internalUrl: '', + healthPingEnabled: true, + healthUrl: 'https://status.example.nl/health', + expectedStatus: 204, + pingInterval: 30, + linkTarget: '', + colourToken: '', + }) + }) + + // @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-the-tile-colour-is-one-of-eight-theme-colours-req-ict-004 + it('saves the colour token and keeps what the form does not edit', async () => { + const updateWidgetPlacement = vi.fn().mockResolvedValue(undefined) + const placement = { + id: 8, + content: { iconOnly: true, pinned: true, countSource: { register: 'r', schema: 's' }, healthPingEnabled: true, colourToken: '--sc-accent' }, + } + const host = makeHost({ updateWidgetPlacement, closeTileEditor: vi.fn(), editingTile: { id: 8 }, widgetPlacements: [placement] }) + + await host.saveTile({ title: 'Zaaksysteem', linkType: 'url', linkValue: 'https://z.test', colourToken: '--sc-primary', healthPingEnabled: false }) + + const { content } = updateWidgetPlacement.mock.calls[0][1] + expect(content).toMatchObject({ iconOnly: true, pinned: true, countSource: { register: 'r', schema: 's' }, colourToken: '--sc-primary', healthPingEnabled: false }) + }) + + // @spec openspec/changes/archive/2026-11-25-icon-only-app-tiles/specs/tiles/spec.md#requirement-the-tile-colour-is-one-of-eight-theme-colours-req-ict-004 + it('drops a colour token the form cleared, and stores one on a new tile', async () => { + const updateWidgetPlacement = vi.fn().mockResolvedValue(undefined) + const host = makeHost({ + updateWidgetPlacement, + closeTileEditor: vi.fn(), + editingTile: { id: 9 }, + widgetPlacements: [{ id: 9, content: { colourToken: '--sc-accent' } }], + }) + await host.saveTile({ title: 'Mail', linkType: 'url', linkValue: 'https://m.test', colourToken: '' }) + expect(updateWidgetPlacement.mock.calls[0][1].content).not.toHaveProperty('colourToken') + + const addTileToDashboard = vi.fn().mockResolvedValue({ id: 30 }) + const fresh = makeHost({ updateWidgetPlacement: vi.fn(), addTileToDashboard, closeTileEditor: vi.fn(), editingTile: null }) + await fresh.saveTile({ title: 'Wiki', linkType: 'url', linkValue: 'https://w.test', colourToken: '--sc-work-ink' }) + expect(fresh.updateWidgetPlacement).toHaveBeenCalledWith(30, { content: expect.objectContaining({ colourToken: '--sc-work-ink' }) }) + }) + + it('defaults the health-ping fields for a tile without content', () => { + const openTileEditor = vi.fn() + makeHost({ openTileEditor }).openTileEditorForEdit({ id: 3, content: { healthPingEnabled: 'yes' } }) + + expect(openTileEditor.mock.calls[0][0]).toMatchObject({ + id: 3, + healthPingEnabled: false, + healthUrl: '', + expectedStatus: 200, + pingInterval: 60, + }) + + openTileEditor.mockClear() + makeHost({ openTileEditor }).openTileEditorForEdit({ id: 5 }) + expect(openTileEditor.mock.calls[0][0]).toMatchObject({ id: 5, healthPingEnabled: false, pingInterval: 60 }) + }) + + it('closes and forgets the tile being edited', () => { + const host = makeHost({ isTileEditorOpen: true, editingTile: { id: 1 } }) + host.closeTileEditor() + expect(host).toMatchObject({ isTileEditorOpen: false, editingTile: null }) + }) + + it('deletes the edited tile and closes, and does nothing for a new tile', async () => { + const removeWidget = vi.fn().mockResolvedValue(undefined) + const host = makeHost({ removeWidget, isTileEditorOpen: true, editingTile: { id: 21 } }) + + await host.deleteTile() + expect(removeWidget).toHaveBeenCalledWith(21) + expect(host.isTileEditorOpen).toBe(false) + + removeWidget.mockClear() + const fresh = makeHost({ removeWidget, isTileEditorOpen: true, editingTile: null }) + await fresh.deleteTile() + expect(removeWidget).not.toHaveBeenCalled() + expect(fresh.isTileEditorOpen).toBe(true) + }) +}) + +describe('Views custom widget modal', () => { + it('opens in create mode with the preselected type once edit mode is entered', async () => { + const host = makeHost({ enterEditMode: vi.fn().mockResolvedValue(true) }) + await host.openCustomWidgetModal('label') + expect(host).toMatchObject({ isCustomWidgetModalOpen: true, customWidgetPreselectedType: 'label', customWidgetEditing: null }) + + const picker = makeHost({ enterEditMode: vi.fn().mockResolvedValue(true) }) + await picker.openCustomWidgetModal() + expect(picker.customWidgetPreselectedType).toBeNull() + }) + + it('stays closed when edit mode is refused', async () => { + const host = makeHost({ enterEditMode: vi.fn().mockResolvedValue(false) }) + await host.openCustomWidgetModal('label') + expect(host.isCustomWidgetModalOpen).toBe(false) + expect(host.customWidgetPreselectedType).toBe('x') + }) + + it('opens in edit mode on an existing placement, and closes clean', () => { + const placement = { id: 2, type: 'label' } + const host = makeHost() + + host.openCustomWidgetEdit(placement) + expect(host).toMatchObject({ isCustomWidgetModalOpen: true, customWidgetEditing: placement, customWidgetPreselectedType: null }) + + host.closeCustomWidgetModal() + expect(host).toMatchObject({ isCustomWidgetModalOpen: false, customWidgetEditing: null, customWidgetPreselectedType: null }) + }) +}) + +describe('Views server-app discovery', () => { + it('keeps the discovered apps the server answers', async () => { + const apps = [{ appId: 'files', name: 'Files', href: '/apps/files/', icon: '/f.svg' }] + api.discoverApps.mockResolvedValue({ data: { apps } }) + const host = makeHost() + + await host.loadDiscoveredApps() + + expect(host.discoveredApps).toEqual(apps) + }) + + it('reads a malformed answer as no apps', async () => { + api.discoverApps.mockResolvedValue({ data: { apps: 'files' } }) + const host = makeHost() + + await host.loadDiscoveredApps() + + expect(host.discoveredApps).toEqual([]) + expect(logger.warn).not.toHaveBeenCalled() + }) + + it('leaves the section empty and warns when discovery fails', async () => { + const error = new Error('offline') + api.discoverApps.mockRejectedValue(error) + const host = makeHost() + + await host.loadDiscoveredApps() + + expect(host.discoveredApps).toEqual([]) + expect(logger.warn).toHaveBeenCalledWith('[Views] Could not discover the server apps:', error) + }) + + it('places a discovered app as its own app tile, logging a failure instead of throwing', async () => { + const addWidgetToDashboard = vi.fn().mockResolvedValue({ id: 1 }) + const host = makeHost({ addWidgetToDashboard }) + + await host.addDiscoveredApp({ appId: 'deck', name: 'Deck', href: 'https://elders.example.nl/', icon: '/deck.svg' }) + expect(addWidgetToDashboard).toHaveBeenCalledWith({ + type: 'app-tile', + content: { appId: 'deck', colour: '', showCount: true }, + }) + + const error = new Error('quota') + addWidgetToDashboard.mockRejectedValueOnce(error) + await expect(host.addDiscoveredApp({ appId: 'deck', name: 'Deck', href: '/x', icon: '' })).resolves.toBeUndefined() + expect(logger.error).toHaveBeenCalledWith('[Views] Failed to place a discovered app:', error) + }) +}) + +describe('Views office tile pack', () => { + const DOC = { title: 'New document', linkType: 'create', linkValue: 'richdocuments:.docx', icon: 'icon-filetype-file', iconType: 'class' } + const MAIL = { title: 'Mail', linkType: 'app', linkValue: 'mail', icon: 'icon-mail', iconType: 'class' } + + it('places the pack as one container titled Office and closes the picker', async () => { + api.officeTilePack.mockResolvedValueOnce({ data: { tiles: [DOC, MAIL] } }) + const addWidgetToDashboard = vi.fn().mockResolvedValue({ id: 5 }) + const closeWidgetModal = vi.fn() + const host = makeHost({ addWidgetToDashboard, closeWidgetModal }) + + await host.addOfficePack() + + expect(addWidgetToDashboard).toHaveBeenCalledTimes(1) + const [payload, size] = addWidgetToDashboard.mock.calls[0] + expect(payload.type).toBe('container') + expect(payload.content.title).toBe('Office') + expect(payload.content.placements.map((p) => p.content.title)).toEqual(['New document', 'Mail']) + expect(size).toEqual({ w: 4, h: 3 }) + expect(closeWidgetModal).toHaveBeenCalledTimes(1) + }) + + it('places nothing for an empty pack and says so', async () => { + api.officeTilePack.mockResolvedValueOnce({ data: { tiles: [] } }) + const addWidgetToDashboard = vi.fn() + const host = makeHost({ addWidgetToDashboard, closeWidgetModal: vi.fn() }) + + await host.addOfficePack() + + expect(addWidgetToDashboard).not.toHaveBeenCalled() + expect(showError).toHaveBeenCalledWith('This server has no office apps to make tiles for.') + }) + + it('keeps the picker open when the placement is refused', async () => { + api.officeTilePack.mockResolvedValueOnce({ data: { tiles: [DOC] } }) + const closeWidgetModal = vi.fn() + const host = makeHost({ addWidgetToDashboard: vi.fn().mockResolvedValue(undefined), closeWidgetModal }) + + await host.addOfficePack() + + expect(closeWidgetModal).not.toHaveBeenCalled() + }) + + it('logs and reports a failed pack request', async () => { + const error = new Error('down') + api.officeTilePack.mockRejectedValueOnce(error) + const host = makeHost({ addWidgetToDashboard: vi.fn(), closeWidgetModal: vi.fn() }) + + await expect(host.addOfficePack()).resolves.toBeUndefined() + expect(logger.error).toHaveBeenCalledWith('[Views] Failed to place the office tiles:', error) + expect(showError).toHaveBeenCalledWith('The office tiles could not be added.') + }) +}) + +describe('Views upload and calendar transports', () => { + it('uploads an icon as a data URL and answers its address', async () => { + uploadDataUrl.mockResolvedValue('/resources/icon.png') + const file = new File(['x'], 'icon.png') + + await expect(makeHost().iconUploadFn(file)).resolves.toBe('/resources/icon.png') + expect(uploadDataUrl).toHaveBeenCalledWith(file) + }) + + it('uploads an image file and answers only its url', async () => { + uploadFile.mockResolvedValue({ url: '/resources/foto.jpg', id: 9, size: 100 }) + const file = new File(['x'], 'foto.jpg') + + await expect(makeHost().imageFileUpload(file)).resolves.toEqual({ url: '/resources/foto.jpg' }) + expect(uploadFile).toHaveBeenCalledWith(file) + }) + + it('answers the user\'s calendars, or none for an empty answer', async () => { + const calendars = [{ key: 'personal', name: 'Persoonlijk', color: '#00f' }] + api.getCalendarWidgetCalendars.mockResolvedValueOnce({ data: { calendars } }) + await expect(makeHost().fetchCalendars()).resolves.toEqual(calendars) + + api.getCalendarWidgetCalendars.mockResolvedValueOnce({ data: {} }) + await expect(makeHost().fetchCalendars()).resolves.toEqual([]) + + api.getCalendarWidgetCalendars.mockResolvedValueOnce(undefined) + await expect(makeHost().fetchCalendars()).resolves.toEqual([]) + }) +}) + +describe('Views row-cog actions', () => { + it('switches to another row before toggling edit mode', async () => { + const order = [] + const onSidebarSwitch = vi.fn(async () => order.push('switch')) + const toggleEditMode = vi.fn(() => order.push('toggle')) + const host = makeHost({ onSidebarSwitch, toggleEditMode, activeDashboard: { id: 1 } }) + + await host.onRowToggleEdit({ id: 2 }, 'group') + + expect(onSidebarSwitch).toHaveBeenCalledWith(2, 'group') + expect(order).toEqual(['switch', 'toggle']) + }) + + it('does not switch when the row is already active', async () => { + const onSidebarSwitch = vi.fn() + const host = makeHost({ onSidebarSwitch, activeDashboard: { id: 2 } }) + + await host.onRowOpenConfig({ id: 2 }, 'user') + + expect(onSidebarSwitch).not.toHaveBeenCalled() + expect(host).toMatchObject({ isConfigModalOpen: true, configModalInitialTab: 'general' }) + }) + + it('switches without an active dashboard, then opens the widget picker', async () => { + const onSidebarSwitch = vi.fn().mockResolvedValue(undefined) + const openWidgetModal = vi.fn() + const host = makeHost({ onSidebarSwitch, openWidgetModal }) + + await host.onRowAddWidget({ id: 7 }, 'default') + + expect(onSidebarSwitch).toHaveBeenCalledWith(7, 'default') + expect(openWidgetModal).toHaveBeenCalledWith() + }) + + it('closes the picker and opens the custom widget form on the Launchpad type picked in it', async () => { + const openCustomWidgetModal = vi.fn() + const host = makeHost({ openCustomWidgetModal, isWidgetModalOpen: true }) + + await host.onPickCustomWidget('image') + + expect(host.isWidgetModalOpen).toBe(false) + expect(openCustomWidgetModal).toHaveBeenCalledWith(null, 'image') + }) + + it('opens the form on an initial type without preselecting it, and forgets it on close', async () => { + const host = makeHost({ enterEditMode: vi.fn().mockResolvedValue(true) }) + + await host.openCustomWidgetModal(null, 'news') + expect(host).toMatchObject({ isCustomWidgetModalOpen: true, customWidgetPreselectedType: null, customWidgetInitialType: 'news' }) + + host.closeCustomWidgetModal() + expect(host.customWidgetInitialType).toBeNull() + }) +}) + +describe('Views sidebar create and delete dialog', () => { + it('forks the active dashboard as a personal copy', async () => { + const forkDashboard = vi.fn().mockResolvedValue({ id: 9 }) + await makeHost({ forkDashboard, activeDashboard: { uuid: 'u-1' } }).onSidebarCreateDashboard() + expect(forkDashboard).toHaveBeenCalledWith('u-1', null) + }) + + it('forks nothing without an active dashboard, and swallows a refused fork', async () => { + const forkDashboard = vi.fn().mockRejectedValue(new Error('403')) + await makeHost({ forkDashboard }).onSidebarCreateDashboard() + expect(forkDashboard).not.toHaveBeenCalled() + + await expect(makeHost({ forkDashboard, activeDashboard: { uuid: 'u-1' } }).onSidebarCreateDashboard()).resolves.toBeUndefined() + expect(forkDashboard).toHaveBeenCalledTimes(1) + }) + + it('asks to delete the current dashboard with no child count', async () => { + const dashboard = { id: 4, name: 'Team' } + const host = makeHost() + + await host.deleteCurrentDashboard(dashboard) + + expect(host.deleteTarget).toBe(dashboard) + expect(host.deleteChildCount).toBe(0) + }) + + it('clears the target when the dialog closes, and keeps it while open', () => { + const host = makeHost({ deleteTarget: { id: 4 }, deleteChildCount: 2 }) + + host.onDeleteDialog(true) + expect(host.deleteTarget).toEqual({ id: 4 }) + expect(host.deleteChildCount).toBe(2) + + host.onDeleteDialog(false) + expect(host.deleteTarget).toBeNull() + expect(host.deleteChildCount).toBe(0) + }) +}) diff --git a/src/views/__tests__/ViewsFillHeight.spec.js b/src/views/__tests__/ViewsFillHeight.spec.js new file mode 100644 index 000000000..527c48716 --- /dev/null +++ b/src/views/__tests__/ViewsFillHeight.spec.js @@ -0,0 +1,89 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * A dashboard whose placement asks for it (`content.fillHeight`) fills the + * height below the top bar (LpVandaag): the page hands the grid + * `fillHeight`, and outside edit mode marks the placements whose rows size + * to their content (`content.fitRows`). + */ + +import { beforeAll, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +// The unit suite runs against a stub of nextcloud-vue (vitest.config.js), so +// the divider's registered minimum is supplied here. +vi.mock('../../constants/widgetRegistry.js', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getWidgetTypeEntry: (type) => (type === 'divider' ? { minHeight: 1 } : actual.getWidgetTypeEntry(type)), + } +}) + +let Views + +beforeAll(async () => { + Views = (await import('../Views.vue')).default +}) + +/** + * A host with the page's own computed properties. + * + * @param {object[]} placements The shown placements. + * @param {boolean} isEditMode Whether the page is in edit mode. + * @return {object} + */ +function makeHost(placements, isEditMode = false) { + const host = { shownPlacements: placements, isEditMode } + Object.defineProperty(host, 'fillsHeight', { + get: () => Views.computed.fillsHeight.call(host), + }) + Object.defineProperty(host, 'gridLayout', { + get: () => Views.computed.gridLayout.call(host), + }) + return host +} + +const header = { + id: 1, + widgetId: 'header', + content: { fillHeight: true, fitRows: true }, +} +const counter = { id: 2, widgetId: 'stat', content: { fitRows: true } } +const tiles = { id: 3, widgetId: 'app-tiles', content: {} } + +describe('Views: a dashboard that fills the height', () => { + it('fills when a placement asks for it, and marks the rows that fit their content', () => { + const host = makeHost([header, counter, tiles]) + expect(host.fillsHeight).toBe(true) + expect(host.gridLayout.map((p) => p.fitRows === true)).toEqual([ + true, + true, + false, + ]) + expect(host.gridLayout[2]).toBe(tiles) + }) + + it('hands the placements over unchanged while editing', () => { + const host = makeHost([header, counter, tiles], true) + expect(host.gridLayout).toEqual(host.shownPlacements) + host.gridLayout.forEach((p, i) => expect(p).toBe(host.shownPlacements[i])) + expect(host.gridLayout[0].fitRows).toBeUndefined() + }) + + it('gives a divider the one-row minimum its type registers, and other widgets none', () => { + const divider = { id: 4, widgetId: 'divider', gridHeight: 1, content: {} } + const host = makeHost([divider, tiles], true) + expect(host.gridLayout[0].minHeight).toBe(1) + expect(host.gridLayout[1]).toBe(tiles) + }) + + it('does not fill a dashboard that does not ask', () => { + const host = makeHost([counter, tiles]) + expect(host.fillsHeight).toBe(false) + expect(host.gridLayout).toEqual(host.shownPlacements) + host.gridLayout.forEach((p, i) => expect(p).toBe(host.shownPlacements[i])) + }) +}) diff --git a/src/views/__tests__/ViewsHideUnavailableSource.spec.js b/src/views/__tests__/ViewsHideUnavailableSource.spec.js new file mode 100644 index 000000000..c7ea34776 --- /dev/null +++ b/src/views/__tests__/ViewsHideUnavailableSource.spec.js @@ -0,0 +1,167 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * A list that asked to be hidden when its register is not on this instance + * is left out of the grid outside edit mode, after OpenRegister answered + * 404 for its source; every other failure keeps the list on the page + * (admin-templates REQ-TMPL-022). Asked the way the page asks: through the + * page's own watcher, computed and probe, with the probe's HTTP call the + * only thing replaced. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('@nextcloud/router', async (importOriginal) => ({ + ...(await importOriginal()), + generateUrl: (path, vars) => path.replace(/\{(\w+)\}/g, (_m, k) => vars[k]), +})) +const { get } = vi.hoisted(() => ({ get: vi.fn() })) +vi.mock('@nextcloud/axios', () => ({ default: { get } })) + +let Views +let resetSourceAvailability + +/** + * @param {object[]} placements The dashboard's placements. + * @param {boolean} isEditMode Whether the page is in edit mode. + * @return {object} host with the real Views methods and computed. + */ +function makeHost(placements, isEditMode = false) { + const host = { widgetPlacements: placements, isEditMode, unavailableSources: {} } + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + Object.defineProperty(host, 'shownPlacements', { + get: () => Views.computed.shownPlacements.call(host), + }) + return host +} + +const header = { id: 1, widgetId: 'header', content: { title: 'Mijn werkdag' } } +const cases = { + id: 2, + widgetId: 'object-list', + content: { register: 'dossiq', schema: 'case', hideWhenUnavailable: true }, +} +const tickets = { + id: 3, + widgetId: 'object-list', + content: { register: 'pipelinq', schema: 'ticket', hideWhenUnavailable: true }, +} +const plainList = { + id: 4, + widgetId: 'object-list', + content: { register: 'pipelinq', schema: 'lead' }, +} + +function answer(register) { + if (register === 'dossiq') { + return Promise.resolve({ data: { results: [], total: 0 } }) + } + if (register === 'pipelinq') { + return Promise.reject({ response: { status: 404 } }) + } + return Promise.reject({ response: { status: 500 } }) +} + +beforeEach(async () => { + vi.clearAllMocks() + get.mockImplementation((url) => answer(url.split('/')[5])) + ;({ resetSourceAvailability } = + await import('../../services/sourceAvailability.js')) + resetSourceAvailability() + Views = (await import('../Views.vue')).default +}) + +describe('Views hides a list whose register is not here', () => { + it('leaves out the list OpenRegister answered 404 for, and keeps the others', async () => { + const host = makeHost([header, cases, tickets, plainList]) + expect(host.shownPlacements.map((p) => p.id)).toEqual([1, 2, 3, 4]) + + await host.probeHideableSources() + + expect(host.shownPlacements.map((p) => p.id)).toEqual([1, 2, 4]) + // The list without the flag was not asked about: it renders as before. + expect(get).toHaveBeenCalledTimes(2) + expect(get).toHaveBeenCalledWith( + '/apps/openregister/api/objects/pipelinq/ticket', + { params: { _limit: 1 } }, + ) + }) + + it('keeps every list in edit mode', async () => { + const host = makeHost([header, cases, tickets], true) + await host.probeHideableSources() + expect(host.shownPlacements.map((p) => p.id)).toEqual([1, 2, 3]) + }) + + it('keeps a list whose source could not be asked', async () => { + const broken = { + id: 5, + widgetId: 'object-list', + content: { + register: 'learniq', + schema: 'pupil', + hideWhenUnavailable: true, + }, + } + const host = makeHost([header, broken]) + await host.probeHideableSources() + expect(host.shownPlacements.map((p) => p.id)).toEqual([1, 5]) + }) + + it('asks once per source, not once per list', async () => { + const second = { ...tickets, id: 6 } + const host = makeHost([tickets, second]) + await host.probeHideableSources() + await host.probeHideableSources() + expect(get).toHaveBeenCalledTimes(1) + expect(host.shownPlacements).toEqual([]) + }) +}) + +describe('Views hides an app tile whose register is not here', () => { + it('leaves out a stat that names its source under `source`, and keeps one whose source is here', async () => { + // Mijn werkdag 4: one number per app, each reading its own register. + const caseTile = { + id: 5, + widgetId: 'stat', + content: { + source: { register: 'dossiq', schema: 'case', metric: 'count' }, + hideWhenUnavailable: true, + }, + } + const ticketTile = { + id: 6, + widgetId: 'stat', + content: { + source: { register: 'pipelinq', schema: 'ticket', metric: 'count' }, + hideWhenUnavailable: true, + }, + } + const plainTile = { + id: 7, + widgetId: 'stat', + content: { + source: { register: 'pipelinq', schema: 'lead', metric: 'count' }, + }, + } + const host = makeHost([header, caseTile, ticketTile, plainTile]) + + await host.probeHideableSources() + + expect(host.shownPlacements.map((p) => p.id)).toEqual([1, 5, 7]) + expect(get).toHaveBeenCalledTimes(2) + }) +}) + +describe('Views never shows a placement with isVisible 0', () => { + it('leaves it out in view mode and in edit mode, and keeps the rest', () => { + const hidden = { id: 7, widgetId: 'files-favorites', isVisible: 0, content: {} } + const shown = { ...header, isVisible: 1 } + expect(makeHost([shown, hidden]).shownPlacements.map((p) => p.id)).toEqual([1]) + expect(makeHost([shown, hidden], true).shownPlacements.map((p) => p.id)).toEqual([1]) + }) +}) diff --git a/src/views/__tests__/ViewsNavigationAndSave.spec.js b/src/views/__tests__/ViewsNavigationAndSave.spec.js new file mode 100644 index 000000000..a8da24416 --- /dev/null +++ b/src/views/__tests__/ViewsNavigationAndSave.spec.js @@ -0,0 +1,628 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * The workspace page's deep-link history (building the address, replacing + * it at boot, pushing it on a switch, following the back button), the + * default-dashboard preference from a row and from the config modal, the + * active dashboard's source, the per-dashboard view-event debounce, the + * tile search dimming and saving a tile or custom widget. Run against the + * real Views methods and computeds on a stand-in host. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { api } from '../../services/api.js' +import { useTileSearchStore } from '../../stores/tileSearch.js' +import { logger } from '../../utils/logger.js' + +vi.mock('../../services/api.js', () => ({ + api: { + getDashboardPath: vi.fn(), + getDashboardByPath: vi.fn(), + setDefaultDashboardPreference: vi.fn(), + clearDefaultDashboardPreference: vi.fn(), + }, +})) +vi.mock('@nextcloud/router', () => ({ + generateUrl: (path) => `/index.php${path}`, + generateOcsUrl: (path) => `/ocs/v2.php${path}`, + imagePath: (app, file) => `/${app}/img/${file}`, + generateFilePath: (app, type, file) => `/${app}/${type}/${file}`, + linkTo: (app, file) => `/${app}/${file}`, +})) +vi.mock('../../stores/tileSearch.js', () => ({ + useTileSearchStore: vi.fn(), +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})) + +let Views + +/** + * A host carrying the real Views methods. + * + * @param {object} state Data and overrides. + * @return {object} the host. + */ +function makeHost(state = {}) { + const host = { activeDashboard: null, defaultDashboardUuid: '', viewEventLastSent: {} } + for (const [name, fn] of Object.entries(Views.methods)) { + host[name] = fn.bind(host) + } + return Object.assign(host, state) +} + +/** + * Point the jsdom location at a path without navigating. + * + * @param {string} path The pathname. + */ +function at(path) { + window.history.replaceState(null, '', path) +} + +beforeEach(async () => { + vi.clearAllMocks() + at('/index.php/apps/launchpad') + Views = (await import('../Views.vue')).default +}) + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('Views deep-link history', () => { + it('builds an address under the app prefix, adding the leading slash', () => { + const host = makeHost() + expect(host.buildDeepLinkUrl('team/hr')).toBe('/index.php/apps/launchpad/team/hr') + expect(host.buildDeepLinkUrl('/team/hr')).toBe('/index.php/apps/launchpad/team/hr') + expect(host.buildDeepLinkUrl('')).toBe('') + expect(host.buildDeepLinkUrl(null)).toBe('') + }) + + it('pushes a history entry for a dashboard change only once the boot is over', () => { + const handler = Views.watch['activeDashboard.uuid'].handler + const host = makeHost({ openFilterSession: vi.fn(), recordViewEventAfterLoad: vi.fn(), recordViewEventDebounced: vi.fn(), pushUrlForActiveDashboard: vi.fn() }) + + // The boot: no dashboard yet, the stored active one, then the deep-linked one. + handler.call(host, 'u-b', null) + handler.call(host, 'u-a', 'u-b') + expect(host.pushUrlForActiveDashboard).not.toHaveBeenCalled() + expect(host.recordViewEventAfterLoad.mock.calls).toEqual([['u-b'], ['u-a']]) + + host.historyBooted = true + handler.call(host, 'u-b', 'u-a') + expect(host.pushUrlForActiveDashboard).toHaveBeenCalledTimes(1) + }) + + it('lets every filter session of the boot read the address, and no session after it', () => { + const handler = Views.watch['activeDashboard.uuid'].handler + const host = makeHost({ historyBooted: false, openFilterSession: vi.fn(), recordViewEventDebounced: vi.fn(), pushUrlForActiveDashboard: vi.fn() }) + + // The boot: the stored active one, then the deep-linked one. + handler.call(host, 'u-b', undefined) + handler.call(host, 'u-a', 'u-b') + expect(host.openFilterSession.mock.calls).toEqual([[true], [true]]) + + host.historyBooted = true + handler.call(host, 'u-b', 'u-a') + expect(host.openFilterSession.mock.calls[2]).toEqual([false]) + }) + + it('replaces the boot address with the injected deep link, unless it is already there', () => { + const replace = vi.spyOn(window.history, 'replaceState') + const host = makeHost({ injectedDeepLinkPath: 'team/hr', activeDashboard: { uuid: 'u-hr' } }) + + host.replaceUrlFromInitialState() + expect(replace).toHaveBeenCalledWith({ uuid: 'u-hr', source: 'launchpad-deeplink' }, '', '/index.php/apps/launchpad/team/hr') + + replace.mockClear() + at('/index.php/apps/launchpad/team/hr/') + replace.mockClear() + host.replaceUrlFromInitialState() + expect(replace).not.toHaveBeenCalled() + + makeHost({ injectedDeepLinkPath: '' }).replaceUrlFromInitialState() + expect(replace).not.toHaveBeenCalled() + }) + + it('keeps the query and hash when it replaces the boot address', () => { + const replace = vi.spyOn(window.history, 'replaceState') + at('/index.php/apps/launchpad/?kiosk=1#top') + + makeHost({ injectedDeepLinkPath: 'team/hr', activeDashboard: { uuid: 'u-hr' } }).replaceUrlFromInitialState() + + expect(replace).toHaveBeenCalledWith( + { uuid: 'u-hr', source: 'launchpad-deeplink' }, + '', + '/index.php/apps/launchpad/team/hr?kiosk=1#top', + ) + }) + + it('treats an address without the front controller as the deep link itself', async () => { + const replace = vi.spyOn(window.history, 'replaceState') + const push = vi.spyOn(window.history, 'pushState') + api.getDashboardPath.mockResolvedValue({ data: { path: 'team/hr' } }) + at('/apps/launchpad/team/hr') + replace.mockClear() + const host = makeHost({ injectedDeepLinkPath: 'team/hr', activeDashboard: { uuid: 'u-hr' } }) + + host.replaceUrlFromInitialState() + await host.pushUrlForActiveDashboard() + + expect(replace).not.toHaveBeenCalled() + expect(push).not.toHaveBeenCalled() + }) + + it('opens the dashboard a slug address names, not the stored active one', async () => { + const switchDashboard = vi.fn() + const dashboards = [{ id: 1, uuid: 'u-a' }, { id: 2, uuid: 'u-b' }] + const host = makeHost({ + injectedActiveDashboardId: 'u-a', + injectedDeepLinkPath: '/team/a', + activeDashboard: { id: 2, uuid: 'u-b' }, + dashboards, + switchDashboard, + }) + + await host.openDeepLinkedDashboard('/apps/launchpad/team/a/') + expect(switchDashboard).toHaveBeenCalledWith(1) + }) + + it('keeps the stored dashboard for an address the server did not resolve', async () => { + const switchDashboard = vi.fn() + const state = { + injectedActiveDashboardId: 'u-a', + injectedDeepLinkPath: '/team/a', + activeDashboard: { id: 2, uuid: 'u-b' }, + dashboards: [{ id: 1, uuid: 'u-a' }, { id: 2, uuid: 'u-b' }], + switchDashboard, + } + + await makeHost(state).openDeepLinkedDashboard('/index.php/apps/launchpad/dashboards/2') + await makeHost(state).openDeepLinkedDashboard('/index.php/apps/launchpad') + await makeHost({ ...state, activeDashboard: { id: 1, uuid: 'u-a' } }) + .openDeepLinkedDashboard('/index.php/apps/launchpad/team/a') + expect(switchDashboard).not.toHaveBeenCalled() + }) + + it('logs instead of failing when the history refuses the replacement', () => { + const error = new Error('refused') + vi.spyOn(window.history, 'replaceState').mockImplementation(() => { + throw error + }) + + makeHost({ injectedDeepLinkPath: 'x', activeDashboard: null }).replaceUrlFromInitialState() + + expect(logger.warn).toHaveBeenCalledWith('[Views] history.replaceState failed:', error) + }) + + it('writes the address of a dashboard the route opened over the one the server rendered', async () => { + const replace = vi.spyOn(window.history, 'replaceState') + const push = vi.spyOn(window.history, 'pushState') + api.getDashboardPath.mockResolvedValue({ data: { path: '/linked' } }) + at('/index.php/apps/launchpad/other?f=x') + replace.mockClear() + const host = makeHost({ + injectedActiveDashboardId: 'u-other', + activeDashboard: { id: 7, uuid: 'u-linked' }, + }) + + await host.replaceUrlAfterBoot() + + expect(api.getDashboardPath).toHaveBeenCalledWith('u-linked') + expect(replace).toHaveBeenCalledWith( + { uuid: 'u-linked', source: 'launchpad-deeplink' }, + '', + '/index.php/apps/launchpad/linked?f=x', + ) + expect(push).not.toHaveBeenCalled() + }) + + it('falls back to the id address after the boot when the dashboard has no path', async () => { + const replace = vi.spyOn(window.history, 'replaceState') + api.getDashboardPath.mockResolvedValue({ data: { path: '' } }) + at('/index.php/apps/launchpad/other') + replace.mockClear() + + await makeHost({ + injectedActiveDashboardId: 'u-other', + activeDashboard: { id: 7, uuid: 'u-linked' }, + }).replaceUrlAfterBoot() + + expect(replace).toHaveBeenCalledWith( + { uuid: 'u-linked', source: 'launchpad-deeplink' }, + '', + '/index.php/apps/launchpad/dashboards/7', + ) + }) + + it('leaves the address alone after the boot when the server rendered the open dashboard', async () => { + const replace = vi.spyOn(window.history, 'replaceState') + replace.mockClear() + + await makeHost({ + injectedActiveDashboardId: 'u-a', + activeDashboard: { id: 1, uuid: 'u-a' }, + }).replaceUrlAfterBoot() + await makeHost({ injectedActiveDashboardId: 'u-a', activeDashboard: null }).replaceUrlAfterBoot() + + expect(api.getDashboardPath).not.toHaveBeenCalled() + expect(replace).not.toHaveBeenCalled() + }) + + it('pushes the active dashboard\'s path, once, and nothing without a uuid or path', async () => { + const push = vi.spyOn(window.history, 'pushState') + api.getDashboardPath.mockResolvedValue({ data: { path: 'team/hr' } }) + const host = makeHost({ activeDashboard: { uuid: 'u-hr' } }) + + await host.pushUrlForActiveDashboard() + expect(api.getDashboardPath).toHaveBeenCalledWith('u-hr') + expect(push).toHaveBeenCalledWith({ uuid: 'u-hr', source: 'launchpad-deeplink' }, '', '/index.php/apps/launchpad/team/hr') + + push.mockClear() + at('/index.php/apps/launchpad/team/hr') + await host.pushUrlForActiveDashboard() + expect(push).not.toHaveBeenCalled() + + api.getDashboardPath.mockResolvedValue({ data: {} }) + at('/index.php/apps/launchpad') + await host.pushUrlForActiveDashboard() + expect(push).not.toHaveBeenCalled() + + api.getDashboardPath.mockClear() + await makeHost({ activeDashboard: null }).pushUrlForActiveDashboard() + expect(api.getDashboardPath).not.toHaveBeenCalled() + }) + + it('logs a failed path lookup', async () => { + const error = new Error('down') + api.getDashboardPath.mockRejectedValue(error) + + await makeHost({ activeDashboard: { uuid: 'u' } }).pushUrlForActiveDashboard() + + expect(logger.warn).toHaveBeenCalledWith('[Views] failed to push URL for active dashboard:', error) + }) + + it('follows the back button to the dashboard at the address, giving back the edit lock first', async () => { + const order = [] + api.getDashboardByPath.mockResolvedValue({ data: { dashboard: { id: 0 } } }) + const host = makeHost({ activeDashboard: { uuid: 'u-now' } }) + host.dropEditLock = vi.fn(async () => order.push('drop')) + host.switchDashboard = vi.fn(async (id) => order.push(`switch ${id}`)) + at('/index.php/apps/launchpad/team/hr/') + + await host.handleHistoryPopState({ state: { uuid: 'u-hr' } }) + + expect(api.getDashboardByPath).toHaveBeenCalledWith('team/hr') + expect(order).toEqual(['drop', 'switch 0']) + }) + + it('ignores a pop to the active dashboard, to the bare app address, or to an unknown path', async () => { + const host = makeHost({ activeDashboard: { uuid: 'u-hr' } }) + host.dropEditLock = vi.fn() + host.switchDashboard = vi.fn() + + at('/index.php/apps/launchpad/team/hr') + await host.handleHistoryPopState({ state: { uuid: 'u-hr' } }) + at('/index.php/apps/launchpad/') + await host.handleHistoryPopState({ state: null }) + at('/elsewhere/team') + await host.handleHistoryPopState(undefined) + expect(api.getDashboardByPath).not.toHaveBeenCalled() + + api.getDashboardByPath.mockResolvedValue({ data: { dashboard: null } }) + at('/index.php/apps/launchpad/gone') + await host.handleHistoryPopState({ state: {} }) + expect(api.getDashboardByPath).toHaveBeenCalledWith('gone') + expect(host.switchDashboard).not.toHaveBeenCalled() + + const error = new Error('down') + api.getDashboardByPath.mockRejectedValue(error) + await host.handleHistoryPopState({ state: {} }) + expect(logger.warn).toHaveBeenCalledWith('[Views] popstate path resolution failed:', error) + }) +}) + +describe('Views default-dashboard preference', () => { + it('a row sets the default, and clears it when it already is the default', async () => { + const host = makeHost() + + await host.onRowSetDefault({ uuid: 'u1' }, 'user') + expect(api.setDefaultDashboardPreference).toHaveBeenCalledWith('u1') + expect(host.defaultDashboardUuid).toBe('u1') + + await host.onRowSetDefault({ uuid: 'u1' }, 'user') + expect(api.clearDefaultDashboardPreference).toHaveBeenCalledTimes(1) + expect(host.defaultDashboardUuid).toBe('') + + await host.onRowSetDefault({}, 'user') + expect(api.setDefaultDashboardPreference).toHaveBeenCalledTimes(1) + }) + + it('a failing row update keeps the old default and logs', async () => { + const error = new Error('down') + api.setDefaultDashboardPreference.mockRejectedValueOnce(error) + const host = makeHost({ defaultDashboardUuid: 'old' }) + + await host.onRowSetDefault({ uuid: 'u1' }, 'user') + + expect(host.defaultDashboardUuid).toBe('old') + expect(logger.error).toHaveBeenCalledWith('[Views] Failed to update default-dashboard preference:', error) + }) + + it('the modal sets the default, clears only its own default, and ignores a missing uuid', async () => { + const host = makeHost({ defaultDashboardUuid: 'other' }) + + await host.onModalSetDefault({ uuid: 'u1', isDefault: false }) + expect(api.clearDefaultDashboardPreference).not.toHaveBeenCalled() + expect(host.defaultDashboardUuid).toBe('other') + + await host.onModalSetDefault({ uuid: 'u1', isDefault: true }) + expect(api.setDefaultDashboardPreference).toHaveBeenCalledWith('u1') + expect(host.defaultDashboardUuid).toBe('u1') + + await host.onModalSetDefault({ uuid: 'u1', isDefault: false }) + expect(api.clearDefaultDashboardPreference).toHaveBeenCalledTimes(1) + expect(host.defaultDashboardUuid).toBe('') + + await host.onModalSetDefault({ uuid: '', isDefault: true }) + expect(api.setDefaultDashboardPreference).toHaveBeenCalledTimes(1) + + const error = new Error('down') + api.setDefaultDashboardPreference.mockRejectedValueOnce(error) + await host.onModalSetDefault({ uuid: 'u2', isDefault: true }) + expect(host.defaultDashboardUuid).toBe('') + expect(logger.error).toHaveBeenCalledWith('[Views] Failed to update default-dashboard preference from modal:', error) + }) +}) + +describe('Views computeds', () => { + it('resolves the active dashboard\'s source from the sidebar buckets, else from ownership', () => { + const source = (state) => Views.computed.activeDashboardSource.call({ + userDashboards: [{ id: 1 }], + defaultGroupDashboards: [{ id: 2 }], + groupSharedDashboards: [{ id: 3 }], + sharedWithMeDashboards: [{ id: 4 }], + ...state, + }) + + expect(source({ activeDashboard: { id: 1 } })).toBe('user') + expect(source({ activeDashboard: { id: 2 } })).toBe('default') + expect(source({ activeDashboard: { id: 3 } })).toBe('group') + expect(source({ activeDashboard: { id: 4 } })).toBe('shared') + expect(source({ activeDashboard: { id: 5, isOwner: false } })).toBe('group') + expect(source({ activeDashboard: { id: 5 } })).toBe('user') + expect(source({ activeDashboard: null, userDashboards: undefined })).toBe('user') + }) + + it('dims tiles the search does not match, but never the search widget itself', () => { + const isDimmed = vi.fn((id) => id === 7) + useTileSearchStore.mockReturnValue({ isDimmed }) + const dimmed = Views.computed.isTileDimmed.call({}) + + expect(dimmed({ id: 7, widgetId: 'tile-1' })).toBe(true) + expect(dimmed({ id: 8, widgetId: 'tile-2' })).toBe(false) + expect(dimmed({ id: 7, widgetId: 'search' })).toBe(false) + expect(isDimmed).toHaveBeenCalledTimes(2) + }) +}) + +describe('Views view events', () => { + it('records a dashboard view at most once a second per dashboard', () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-01-01T10:00:00Z')) + const host = makeHost({ recordViewEvent: vi.fn() }) + + host.recordViewEventDebounced('a') + host.recordViewEventDebounced('a') + host.recordViewEventDebounced('b') + expect(host.recordViewEvent.mock.calls).toEqual([['a'], ['b']]) + + vi.advanceTimersByTime(999) + host.recordViewEventDebounced('a') + expect(host.recordViewEvent).toHaveBeenCalledTimes(2) + + vi.advanceTimersByTime(1) + host.recordViewEventDebounced('a') + expect(host.recordViewEvent.mock.calls).toEqual([['a'], ['b'], ['a']]) + + host.recordViewEventDebounced('') + expect(host.recordViewEvent).toHaveBeenCalledTimes(3) + }) + + it('sends no view-event while the administrator switched analytics off', () => { + const input = document.createElement('input') + input.type = 'hidden' + input.id = 'initial-state-launchpad-analyticsEnabled' + input.value = btoa(JSON.stringify(false)) + document.body.appendChild(input) + try { + const host = makeHost({ recordViewEvent: vi.fn() }) + host.recordViewEventDebounced('a') + expect(host.recordViewEvent).not.toHaveBeenCalled() + } finally { + input.remove() + } + }) + + it('sends one view-event across two tabs of the same dashboard, holding the lock a second', async () => { + vi.useFakeTimers() + const held = new Set() + const locks = { + request: vi.fn(async (name, options, callback) => { + if (held.has(name)) { + return callback(null) + } + held.add(name) + try { + return await callback({ name }) + } finally { + held.delete(name) + } + }), + } + vi.stubGlobal('navigator', { locks }) + const recordViewEvent = vi.fn() + const first = makeHost({ recordViewEvent }) + const second = makeHost({ recordViewEvent }) + + first.recordViewEventDebounced('a') + second.recordViewEventDebounced('a') + second.recordViewEventDebounced('b') + await vi.advanceTimersByTimeAsync(0) + expect(recordViewEvent.mock.calls).toEqual([['a'], ['b']]) + expect(locks.request).toHaveBeenCalledWith('launchpad-view-event:a', { ifAvailable: true }, expect.any(Function)) + + await vi.advanceTimersByTimeAsync(1000) + makeHost({ recordViewEvent }).recordViewEventDebounced('a') + await vi.advanceTimersByTimeAsync(0) + expect(recordViewEvent.mock.calls).toEqual([['a'], ['b'], ['a']]) + vi.unstubAllGlobals() + }) + + it('sends anyway when the lock request fails', async () => { + vi.stubGlobal('navigator', { locks: { request: vi.fn().mockRejectedValue(new Error('SecurityError')) } }) + const host = makeHost({ recordViewEvent: vi.fn() }) + + host.recordViewEventDebounced('a') + await Promise.resolve() + await Promise.resolve() + + expect(host.recordViewEvent).toHaveBeenCalledWith('a') + vi.unstubAllGlobals() + }) +}) + +describe('Views saving tiles and custom widgets', () => { + const tile = { + title: 'Mail', + icon: 'mail', + iconType: 'mdi', + backgroundColor: '#000', + textColor: '#fff', + linkType: 'url', + linkValue: 'https://example.org', + } + + it('updates the edited tile with its fields and the health-ping defaults', async () => { + const host = makeHost({ editingTile: { id: 5 }, updateWidgetPlacement: vi.fn(), closeTileEditor: vi.fn() }) + + await host.saveTile(tile) + + expect(host.updateWidgetPlacement).toHaveBeenCalledWith(5, { + tileTitle: 'Mail', + tileIcon: 'mail', + tileIconType: 'mdi', + tileBackgroundColor: '#000', + tileTextColor: '#fff', + tileLinkType: 'url', + tileLinkValue: 'https://example.org', + content: { healthPingEnabled: false, healthUrl: '', expectedStatus: 200, pingInterval: 60, internalUrl: '' }, + }) + expect(host.closeTileEditor).toHaveBeenCalledTimes(1) + }) + + it('adds a new tile, patching the health ping only when it is enabled', async () => { + const host = makeHost({ + editingTile: null, + addTileToDashboard: vi.fn(async () => ({ id: 9 })), + updateWidgetPlacement: vi.fn(), + closeTileEditor: vi.fn(), + }) + + await host.saveTile(tile) + expect(host.addTileToDashboard).toHaveBeenCalledWith(tile) + expect(host.updateWidgetPlacement).not.toHaveBeenCalled() + + await host.saveTile({ ...tile, healthPingEnabled: true, healthUrl: '/status', expectedStatus: 204, pingInterval: 30 }) + expect(host.updateWidgetPlacement).toHaveBeenCalledWith(9, { + content: { healthPingEnabled: true, healthUrl: '/status', expectedStatus: 204, pingInterval: 30, internalUrl: '' }, + }) + expect(host.closeTileEditor).toHaveBeenCalledTimes(2) + }) + + it('adds a new tile with an office-network address, patching it in (launcher-tile-internal-address)', async () => { + const host = makeHost({ + editingTile: null, + addTileToDashboard: vi.fn(async () => ({ id: 9 })), + updateWidgetPlacement: vi.fn(), + closeTileEditor: vi.fn(), + }) + + await host.saveTile({ ...tile, internalUrl: 'http://zaken.intern' }) + expect(host.updateWidgetPlacement).toHaveBeenCalledWith(9, { + content: { healthPingEnabled: false, healthUrl: '', expectedStatus: 200, pingInterval: 60, internalUrl: 'http://zaken.intern' }, + }) + }) + + it('keeps the tile editor open and logs when saving fails', async () => { + const error = new Error('down') + const host = makeHost({ editingTile: { id: 5 }, updateWidgetPlacement: vi.fn().mockRejectedValue(error), closeTileEditor: vi.fn() }) + + await host.saveTile(tile) + + expect(host.closeTileEditor).not.toHaveBeenCalled() + expect(logger.error).toHaveBeenCalledWith('[Views] Failed to save tile:', error) + }) + + it('updates an edited custom widget\'s content, or creates one and then patches its chrome', async () => { + const editing = makeHost({ + customWidgetEditing: { id: 3, styleConfig: {} }, + updateWidgetPlacement: vi.fn(), + addWidgetToDashboard: vi.fn(), + closeCustomWidgetModal: vi.fn(), + }) + await editing.saveCustomWidget({ type: 'text', content: { text: 'Hi' } }) + expect(editing.updateWidgetPlacement).toHaveBeenCalledWith(3, expect.objectContaining({ content: { text: 'Hi' } })) + expect(editing.addWidgetToDashboard).not.toHaveBeenCalled() + expect(editing.closeCustomWidgetModal).toHaveBeenCalledTimes(1) + + const creating = makeHost({ + customWidgetEditing: null, + updateWidgetPlacement: vi.fn(), + addWidgetToDashboard: vi.fn(async () => ({ id: 11, styleConfig: {} })), + closeCustomWidgetModal: vi.fn(), + }) + await creating.saveCustomWidget({ type: 'text', content: { text: 'Hi' } }) + expect(creating.addWidgetToDashboard).toHaveBeenCalledWith({ type: 'text', content: { text: 'Hi' } }, null) + expect(creating.updateWidgetPlacement).toHaveBeenCalledWith(11, expect.any(Object)) + expect(creating.updateWidgetPlacement.mock.calls[0][1]).not.toHaveProperty('content') + expect(creating.closeCustomWidgetModal).toHaveBeenCalledTimes(1) + }) + + it('starts a new header at the full grid width and as tall as its preset', async () => { + const host = makeHost({ + activeDashboard: { id: 1, gridColumns: 12 }, + customWidgetEditing: null, + updateWidgetPlacement: vi.fn(), + addWidgetToDashboard: vi.fn(async () => ({ id: 12, styleConfig: {} })), + closeCustomWidgetModal: vi.fn(), + }) + await host.saveCustomWidget({ type: 'header', content: { title: 'Hi', height: 'large' } }) + expect(host.addWidgetToDashboard).toHaveBeenCalledWith( + { type: 'header', content: { title: 'Hi', height: 'large' } }, + { w: 12, h: 6 }, + ) + }) + + it('skips the chrome patch when nothing was created, and logs a failed save', async () => { + const host = makeHost({ + customWidgetEditing: null, + updateWidgetPlacement: vi.fn(), + addWidgetToDashboard: vi.fn(async () => null), + closeCustomWidgetModal: vi.fn(), + }) + await host.saveCustomWidget({ type: 'text', content: {} }) + expect(host.updateWidgetPlacement).not.toHaveBeenCalled() + expect(host.closeCustomWidgetModal).toHaveBeenCalledTimes(1) + + const error = new Error('down') + host.addWidgetToDashboard = vi.fn().mockRejectedValue(error) + await host.saveCustomWidget({ type: 'text', content: {} }) + expect(host.closeCustomWidgetModal).toHaveBeenCalledTimes(1) + expect(logger.error).toHaveBeenCalledWith('[Views] Failed to save custom widget:', error) + }) +}) diff --git a/src/views/__tests__/ViewsPhoneHidden.spec.js b/src/views/__tests__/ViewsPhoneHidden.spec.js new file mode 100644 index 000000000..5623edd0d --- /dev/null +++ b/src/views/__tests__/ViewsPhoneHidden.spec.js @@ -0,0 +1,72 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * On a phone the workspace hides the widgets whose type is not ready for a + * phone and names them for the notice; on a larger screen and in edit mode + * nothing is hidden (launchpad-mobile-remote-access REQ-MRA-007). Asked + * through the page's own computed, with the registry lookup replaced. + * + * @spec openspec/changes/archive/2026-11-24-phone-hidden-widgets-named/specs/launchpad-mobile-remote-access/spec.md#requirement-the-phone-notice-names-the-hidden-widgets-req-mra-007 + */ + +import { beforeAll, describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('../../constants/widgetRegistry.js', async (importOriginal) => { + const original = await importOriginal() + const entries = { + assistant: { displayName: 'Assistent', mobileReady: false }, + tile: { displayName: 'Tile', mobileReady: false }, + text: { displayName: 'Text', mobileReady: true }, + } + return { + ...original, + getWidgetTypeEntry: (type) => entries[type] ?? null, + offeredForViewer: () => true, + } +}) + +let Views + +beforeAll(async () => { + Views = (await import('../Views.vue')).default +}) + +const placements = [ + { id: 1, widgetId: 'tile', customTitle: 'Snel beginnen (Word)' }, + { id: 2, widgetId: 'assistant' }, + { id: 3, widgetId: 'text', customTitle: 'Welkom' }, + { id: 4, widgetId: 'assistant', isVisible: 0 }, +] + +function host(viewportWidth, isEditMode = false) { + return { widgetPlacements: placements, isEditMode, unavailableSources: {}, integrationApps: [], viewportWidth } +} + +describe('Views on a phone', () => { + it('hides the widgets not ready for a phone and names them', () => { + const vm = host(390) + expect(Views.computed.shownPlacements.call(vm).map((p) => p.id)).toEqual([3]) + expect(Views.computed.phoneHiddenTitles.call(vm)).toEqual(['Snel beginnen (Word)', 'Assistent']) + }) + + it('hides nothing on a larger screen', () => { + const vm = host(1280) + expect(Views.computed.shownPlacements.call(vm).map((p) => p.id)).toEqual([1, 2, 3]) + expect(Views.computed.phoneHiddenTitles.call(vm)).toEqual([]) + }) + + it('hides nothing in edit mode', () => { + const vm = host(390, true) + expect(Views.computed.shownPlacements.call(vm).map((p) => p.id)).toEqual([1, 2, 3]) + expect(Views.computed.phoneHiddenTitles.call(vm)).toEqual([]) + }) + + it('follows the viewport width', () => { + const vm = { viewportWidth: 1280 } + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 390 }) + Views.methods.onViewportResize.call(vm) + expect(vm.viewportWidth).toBe(390) + }) +}) diff --git a/src/views/__tests__/ViewsPlacementActions.spec.js b/src/views/__tests__/ViewsPlacementActions.spec.js new file mode 100644 index 000000000..9dce045ad --- /dev/null +++ b/src/views/__tests__/ViewsPlacementActions.spec.js @@ -0,0 +1,291 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the placement-level methods of `Views.vue`: the render + * key, widget lookup, tile projection, the widget context menu (edit through + * the content editor or the style editor, remove, visibility rules, keyboard + * move) and persisting a keyboard move with the placements it pushed, plus + * the acknowledgement hooks. + * + * The methods run on a plain host object, as the sibling Views specs do, so + * the grid, stores and modals are not mounted. The widget registry lookup and + * the logger are doubled. + */ + +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const logged = [] +vi.mock('../../utils/logger.js', () => ({ + logger: { error: (...args) => logged.push(args), warn: vi.fn(), info: vi.fn(), debug: vi.fn() }, +})) +const registry = {} +vi.mock('../../constants/widgetRegistry.js', async (importOriginal) => ({ + ...(await importOriginal()), + getWidgetTypeEntry: (type) => registry[type], +})) +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) + +let Views +let useDashboardStore + +/** + * A host carrying the given state, with every Views method bound to it. + * + * @param {object} state Fields the methods read + * @return {object} The host + */ +function makeHost(state = {}) { + const host = { + availableWidgets: [], + widgetPlacements: [], + movePanelOpen: false, + movePanelPlacement: null, + isVisibilityModalOpen: false, + visibilityPlacementId: null, + ackReportOpen: false, + ackReportKey: null, + ...state, + } + for (const [name, fn] of Object.entries(Views.methods)) { + if (!(name in state)) { + host[name] = fn.bind(host) + } + } + return host +} + +beforeEach(async () => { + setActivePinia(createPinia()) + vi.clearAllMocks() + logged.length = 0 + for (const key of Object.keys(registry)) { + delete registry[key] + } + Views = (await import('../Views.vue')).default; + ({ useDashboardStore } = await import('../../stores/dashboard.js')) +}) + +describe('Views placements', () => { + it('keys a placement by its id as text', () => { + expect(makeHost().placementItemKey({ id: 42, gridX: 3 })).toBe('42') + }) + + it('finds a registered widget by id, and nothing for an unknown one', () => { + const host = makeHost({ availableWidgets: [{ id: 'notes', title: 'Notes' }, { id: 'mail' }] }) + + expect(host.getWidget('notes')).toEqual({ id: 'notes', title: 'Notes' }) + expect(host.getWidget('calendar')).toBeUndefined() + }) + + it('projects a custom tile placement into tile data, and nothing for other placements', () => { + const host = makeHost() + const tile = { + id: 9, + tileType: 'custom', + tileTitle: 'Intranet', + tileIcon: 'mdi-home', + tileIconType: 'mdi', + tileBackgroundColor: '#123456', + tileTextColor: '#ffffff', + tileLinkType: 'url', + tileLinkValue: 'https://intranet.example.nl', + } + + expect(host.isTilePlacement(tile)).toBe(true) + expect(host.getTileData(tile)).toEqual({ + id: 9, + title: 'Intranet', + icon: 'mdi-home', + iconType: 'mdi', + backgroundColor: '#123456', + textColor: '#ffffff', + linkType: 'url', + linkValue: 'https://intranet.example.nl', + internalUrl: '', + }) + expect(host.isTilePlacement({ id: 1, widgetId: 'notes' })).toBe(false) + expect(host.getTileData({ id: 1, tileType: 'preset' })).toBeNull() + }) +}) + +describe('Views widget context menu', () => { + it('hands a right click to the grid manager', () => { + const grid = { onWidgetRightClick: vi.fn() } + const event = new MouseEvent('contextmenu') + const placement = { id: 1 } + + makeHost({ grid }).onWidgetRightClick(event, placement) + + expect(grid.onWidgetRightClick).toHaveBeenCalledWith(event, placement) + }) + + it('resolves a widget type only for a registered type with a form', () => { + registry.label = { form: {} } + registry['nc-widget'] = { form: null } + const host = makeHost() + + expect(host.resolveWidgetType({ widgetId: 'label' })).toBe('label') + expect(host.resolveWidgetType({ widgetId: 'nc-widget' })).toBeNull() + expect(host.resolveWidgetType({ widgetId: 'unknown' })).toBeNull() + expect(host.resolveWidgetType({ widgetId: '' })).toBeNull() + expect(host.resolveWidgetType({ widgetId: 7 })).toBeNull() + expect(host.resolveWidgetType(null)).toBeNull() + }) + + it('edits a registry widget in the content editor with its type set', () => { + registry.label = { form: {} } + const openCustomWidgetEdit = vi.fn() + const openStyleEditor = vi.fn() + const host = makeHost({ openCustomWidgetEdit, openStyleEditor }) + + host.handleContextMenuEdit({ id: 3, widgetId: 'label' }) + + expect(openCustomWidgetEdit).toHaveBeenCalledWith({ id: 3, widgetId: 'label', type: 'label' }) + expect(openStyleEditor).not.toHaveBeenCalled() + }) + + it('edits any other widget in the style editor', () => { + const openCustomWidgetEdit = vi.fn() + const openStyleEditor = vi.fn() + const host = makeHost({ openCustomWidgetEdit, openStyleEditor }) + const placement = { id: 4, widgetId: 'recommendations' } + + host.handleContextMenuEdit(placement) + + expect(openStyleEditor).toHaveBeenCalledWith(placement) + expect(openCustomWidgetEdit).not.toHaveBeenCalled() + }) + + it('removes a placement by id, ignoring one without an id', async () => { + const removeWidget = vi.fn().mockResolvedValue() + const host = makeHost({ removeWidget }) + + await host.handleContextMenuRemove({}) + await host.handleContextMenuRemove(null) + expect(removeWidget).not.toHaveBeenCalled() + + await host.handleContextMenuRemove({ id: 5 }) + expect(removeWidget).toHaveBeenCalledWith(5) + expect(logged).toEqual([]) + }) + + it('logs a remove that fails instead of throwing', async () => { + const failure = new Error('gone') + const host = makeHost({ removeWidget: vi.fn().mockRejectedValue(failure) }) + + await expect(host.handleContextMenuRemove({ id: 5 })).resolves.toBeUndefined() + + expect(logged).toEqual([['[Views] Failed to remove widget via context menu:', failure]]) + }) + + it('offers Remove for a compulsory widget only with full permission', () => { + const compulsory = { id: 5, isCompulsory: 1 } + const addOnly = makeHost({ permissionLevel: 'add_only', grid: { state: { selectedWidget: compulsory } } }) + const full = makeHost({ permissionLevel: 'full', grid: { state: { selectedWidget: compulsory } } }) + + expect(Views.computed.contextMenuCanRemove.call(addOnly)).toBe(false) + expect(Views.computed.contextMenuCanRemove.call(full)).toBe(true) + expect(addOnly.isRemovablePlacement({ id: 6, isCompulsory: 0 })).toBe(true) + expect(addOnly.isRemovablePlacement(null)).toBe(true) + }) + + it('opens and closes the visibility rules for a placement', () => { + const host = makeHost() + + host.handleContextMenuVisibilityRules({}) + expect(host.isVisibilityModalOpen).toBe(false) + + host.handleContextMenuVisibilityRules({ id: 6 }) + expect([host.isVisibilityModalOpen, host.visibilityPlacementId]).toEqual([true, 6]) + + host.closeVisibilityRules() + expect([host.isVisibilityModalOpen, host.visibilityPlacementId]).toEqual([false, null]) + }) + + it('opens and closes the keyboard move panel for a placement', () => { + const host = makeHost() + const placement = { id: 7, gridX: 0 } + + host.handleContextMenuMove(undefined) + expect(host.movePanelOpen).toBe(false) + + host.handleContextMenuMove(placement) + expect([host.movePanelOpen, host.movePanelPlacement]).toEqual([true, placement]) + + host.closeMovePanel() + expect([host.movePanelOpen, host.movePanelPlacement]).toEqual([false, null]) + }) +}) + +describe('Views keyboard move', () => { + const placements = [ + { id: 1, gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 2 }, + { id: 2, gridX: 4, gridY: 0, gridWidth: 4, gridHeight: 2 }, + { id: 3, gridX: 0, gridY: 2, gridWidth: 4, gridHeight: 2 }, + ] + + it('writes the moved rectangle and the pushed placements in one update, and closes the panel', async () => { + const updatePlacements = vi.fn().mockResolvedValue() + const host = makeHost({ widgetPlacements: placements, movePanelOpen: true, movePanelPlacement: placements[0], updatePlacements }) + + await host.handleMoveSave({ gridX: 2, gridY: 1, gridWidth: 6, gridHeight: 3, pushed: [{ id: 3, gridY: 4 }] }) + + expect(updatePlacements).toHaveBeenCalledWith([ + { id: 1, gridX: 2, gridY: 1, gridWidth: 6, gridHeight: 3 }, + placements[1], + { id: 3, gridX: 0, gridY: 4, gridWidth: 4, gridHeight: 2 }, + ]) + expect(updatePlacements.mock.calls[0][0][1]).toBe(placements[1]) + expect([host.movePanelOpen, host.movePanelPlacement]).toEqual([false, null]) + }) + + it('accepts a move without pushed placements', async () => { + const updatePlacements = vi.fn().mockResolvedValue() + const host = makeHost({ widgetPlacements: placements, movePanelPlacement: placements[1], updatePlacements }) + + await host.handleMoveSave({ gridX: 8, gridY: 0, gridWidth: 4, gridHeight: 2 }) + + expect(updatePlacements.mock.calls[0][0][1]).toEqual({ id: 2, gridX: 8, gridY: 0, gridWidth: 4, gridHeight: 2 }) + }) + + it('only closes the panel without a placement or a rectangle', async () => { + const updatePlacements = vi.fn() + for (const [placement, rect] of [[null, { gridX: 0 }], [placements[0], null]]) { + const host = makeHost({ widgetPlacements: placements, movePanelOpen: true, movePanelPlacement: placement, updatePlacements }) + await host.handleMoveSave(rect) + expect(host.movePanelOpen).toBe(false) + } + + expect(updatePlacements).not.toHaveBeenCalled() + }) + + it('logs a move that cannot be saved', async () => { + const failure = new Error('conflict') + const host = makeHost({ widgetPlacements: placements, movePanelPlacement: placements[0], updatePlacements: vi.fn().mockRejectedValue(failure) }) + + await host.handleMoveSave({ gridX: 0, gridY: 0, gridWidth: 4, gridHeight: 2 }) + + expect(logged).toEqual([['[Views] Failed to persist keyboard move:', failure]]) + }) +}) + +describe('Views acknowledgements', () => { + it('refreshes the outstanding acknowledgements after one is given', () => { + const store = useDashboardStore() + const fetch = vi.spyOn(store, 'fetchPendingAcknowledgements').mockResolvedValue() + + makeHost().onWidgetAcknowledged() + + expect(fetch).toHaveBeenCalledTimes(1) + }) + + it('opens the read-receipt report for an announcement', () => { + const host = makeHost() + + host.openAcknowledgementReport('welcome-2026') + + expect([host.ackReportOpen, host.ackReportKey]).toEqual([true, 'welcome-2026']) + }) +}) diff --git a/src/views/__tests__/ViewsSchedule.spec.js b/src/views/__tests__/ViewsSchedule.spec.js index 045be9ff1..e33c00933 100644 --- a/src/views/__tests__/ViewsSchedule.spec.js +++ b/src/views/__tests__/ViewsSchedule.spec.js @@ -2,15 +2,13 @@ * SPDX-FileCopyrightText: 2026 Conduction B.V. * SPDX-License-Identifier: EUPL-1.2 * - * The workspace page schedules the active dashboard through the store and - * explains a refusal (sharing-dashboard-schedule-screen REQ-SCHEDUI-001, - * DashboardService::ERR_* messages), and says when it goes live or comes - * down. + * The workspace page decides who manages publication and says when the + * active dashboard goes live or comes down (REQ-SCHEDUI-001). Scheduling + * itself is in PublicationTab.spec.js. */ import { createPinia, setActivePinia } from 'pinia' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { api } from '../../services/api.js' vi.mock('../../services/api.js', () => ({ api: { @@ -32,8 +30,6 @@ function makeHost(dashboard, isAdmin = false) { const host = { activeDashboard: dashboard, isAdmin, - scheduleDialogOpen: true, - scheduleError: '', } for (const [name, fn] of Object.entries(Views.methods)) { host[name] = fn.bind(host) @@ -65,52 +61,6 @@ describe('Views schedule', () => { ) }) - it('REQ-SCHEDUI-001: schedules through the store and closes the dialog', async () => { - api.scheduleDashboard.mockResolvedValue({ - data: { - dashboard: { - uuid: 'd', - publicationStatus: 'scheduled', - publishAt: '2026-10-01 09:00:00', - unpublishAt: '2026-10-02 17:00:00', - }, - }, - }) - const host = makeHost({ uuid: 'd', isOwner: true }) - await host.onScheduleActive({ - publishAt: '2026-10-01T07:00:00.000Z', - unpublishAt: '2026-10-02T15:00:00.000Z', - }) - expect(api.scheduleDashboard).toHaveBeenCalledWith( - 'd', - '2026-10-01T07:00:00.000Z', - '2026-10-02T15:00:00.000Z', - ) - expect(host.scheduleDialogOpen).toBe(false) - }) - - it('REQ-SCHEDUI-001: a past time is explained and the dialog stays', async () => { - api.scheduleDashboard.mockRejectedValue( - Object.assign(new Error('x'), { - response: { - status: 400, - data: { - status: 'error', - error: 'invalid_argument', - message: 'publishAt must be a future timestamp', - }, - }, - }), - ) - const host = makeHost({ uuid: 'd', isOwner: true }) - await host.onScheduleActive({ - publishAt: '2020-01-01T00:00:00.000Z', - unpublishAt: null, - }) - expect(host.scheduleError).toBe('Choose a time in the future.') - expect(host.scheduleDialogOpen).toBe(true) - }) - it('REQ-SCHEDUI-001: says when it goes live and comes down', () => { const host = makeHost({ uuid: 'd', @@ -122,4 +72,18 @@ describe('Views schedule', () => { expect(host.publicationNote).toContain('Goes live on') expect(host.publicationNote).toContain('Comes down on') }) + + it('REQ-SCHEDUI-001: shows the stored UTC time in the viewer\'s own time', () => { + const host = makeHost({ + uuid: 'd', + isOwner: true, + publicationStatus: 'scheduled', + publishAt: '2026-11-23 08:00:00', + }) + const local = new Date(Date.UTC(2026, 10, 23, 8, 0)).toLocaleString(undefined, { + dateStyle: 'medium', + timeStyle: 'short', + }) + expect(host.publicationNote).toBe(`Goes live on ${local}.`) + }) }) diff --git a/src/views/__tests__/ViewsTalkDisabled.spec.js b/src/views/__tests__/ViewsTalkDisabled.spec.js new file mode 100644 index 000000000..e78bffa83 --- /dev/null +++ b/src/views/__tests__/ViewsTalkDisabled.spec.js @@ -0,0 +1,345 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * A collaborative dashboard with Talk disabled renders fully and surfaces + * no error (openregister-leaf-integrations task 15, REQ-LEAF-004): the + * mounted page keeps its region and its widgets, the discussion leaves no + * trace in the DOM, nothing asks for the Talk integration, and neither a + * console error nor an error toast appears. The same mount with Talk + * installed shows the discussion, so the test can tell the two apart. + * DashboardDiscussion is mounted for real; only its leaf is stubbed. + * + * @spec openspec/changes/openregister-leaf-integrations/tasks.md#task-15 + */ + +import axios from '@nextcloud/axios' +import { showError } from '@nextcloud/dialogs' +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +// p-queue (pulled in by @nextcloud/vue) hands itself to Node's +// `events.setMaxListeners`, which refuses anything but a Node EventEmitter +// or a DOM EventTarget and throws under jsdom. A browser has no +// `process.getBuiltinModule`, so the call never runs there; this spec gives +// p-queue the browser's answer. +vi.hoisted(() => { + const builtin = globalThis.process?.getBuiltinModule + if (typeof builtin === 'function') { + globalThis.process.getBuiltinModule = (id) => (id === 'node:events' || id === 'events' ? undefined : builtin(id)) + } +}) + +vi.mock('@nextcloud/l10n', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + t: (_app, key) => key, + translate: (_app, key) => key, + translatePlural: (_app, sing, plur, n) => (n === 1 ? sing : plur), + } +}) +vi.mock('@nextcloud/dialogs', () => ({ + showSuccess: vi.fn(), + showError: vi.fn(), +})) +vi.mock('@nextcloud/initial-state', () => ({ + loadState: vi.fn((_app, _key, fallback) => fallback), +})) +vi.mock('@nextcloud/axios', () => ({ + default: { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + }, +})) +vi.mock('@nextcloud/router', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + generateUrl: (path) => path, + } +}) + +const BASE = '/apps/launchpad' + +/** + * A stub that renders nothing and keeps every bound prop / listener in `$attrs`. + * + * @param {string} name Component name (for findComponent). + * @param {object} extra Extra options (props, template, inject). + * @return {object} the stub. + */ +function passthrough(name, extra = {}) { + return { + name, + inheritAttrs: false, + template: '
', + ...extra, + } +} + +const stubs = { + teleport: { template: '
' }, + DashboardSwitcherSidebar: passthrough('DashboardSwitcherSidebar', { + props: { isOpen: Boolean }, + template: '
', + }), + SidebarBackdrop: passthrough('SidebarBackdrop', { + template: '
', + }), + DashboardRowActions: passthrough('DashboardRowActions', { + template: '
', + }), + DashboardMoreMenu: passthrough('DashboardMoreMenu', { + template: '
', + }), + NcButton: { + name: 'NcButton', + template: '', + }, + MenuIcon: { name: 'MenuIcon', template: '' }, + ShareVariant: { name: 'ShareVariant', template: '' }, + ViewDashboard: { template: '' }, + NcLoadingIcon: { template: '' }, + NcEmptyContent: { + name: 'NcEmptyContent', + props: { name: String, description: String }, + template: '
{{ description }}
', + }, + StartPageMenu: passthrough('StartPageMenu'), + HiddenWidgetsControl: passthrough('HiddenWidgetsControl'), + DeleteDashboardDialog: passthrough('DeleteDashboardDialog', { + props: { open: Boolean, name: String }, + }), + CnConfirmDialog: passthrough('CnConfirmDialog', { + template: '
', + }), + AcknowledgementReportModal: passthrough('AcknowledgementReportModal', { + props: { open: Boolean, announcementKey: String }, + }), + DashboardReactions: passthrough('DashboardReactions'), + CnIntegrationTab: passthrough('CnIntegrationTab', { + props: { integrationId: String, objectId: String }, + template: '
', + }), + DashboardLanguageHeading: passthrough('DashboardLanguageHeading'), + DashboardBreadcrumb: passthrough('DashboardBreadcrumb'), + EditLockBanner: passthrough('EditLockBanner', { props: { status: String } }), + CoEditorsBanner: passthrough('CoEditorsBanner', { props: { editors: Array } }), + CnDashboardGrid: { + name: 'CnDashboardGrid', + props: { layout: { type: Array, default: () => [] } }, + template: + '
', + }, + TileWidget: passthrough('TileWidget', { + props: { placementId: [Number, String] }, + template: '
', + }), + WidgetWrapper: passthrough('WidgetWrapper', { + props: { placement: Object }, + template: + '
', + }), + WidgetPickerModal: passthrough('WidgetPickerModal'), + CnAddWidgetModal: passthrough('CnAddWidgetModal', { + props: { show: Boolean, editingWidget: Object }, + // Mirrors CnNcDashboardWidgetForm, which reads the injected catalog. + inject: { widgets: { default: null } }, + template: + '
  • {{ w.id }}
', + }), + DashboardConfigModal: passthrough('DashboardConfigModal', { + props: { open: Boolean, mode: String, initialTab: String }, + }), + CnWidgetStyleEditorModal: passthrough('CnWidgetStyleEditorModal', { + props: { show: Boolean, widget: Object }, + }), + TileEditor: passthrough('TileEditor', { + props: { open: Boolean, tile: Object }, + }), + WidgetContextMenu: passthrough('WidgetContextMenu', { + props: { top: Number, left: Number }, + template: '
', + }), + ReadConfirmationDialog: passthrough('ReadConfirmationDialog', { + props: { placement: Object }, + template: '
', + }), + WidgetMovePanel: passthrough('WidgetMovePanel', { + props: { open: Boolean, placement: Object }, + }), + VisibilityRulesModal: passthrough('VisibilityRulesModal', { + props: { open: Boolean, placementId: [Number, String] }, + }), +} + +let wrapper = null + +/** + * Answer the axios mock per URL. + * + * @param {object} overrides `{get: fn(url), post: fn(url)}` replacements. + */ +function routeAxios(overrides = {}) { + axios.get.mockImplementation( + overrides.get + ?? ((url) => { + if (url === `${BASE}/api/dashboards/default`) { + return Promise.resolve({ data: { uuid: 'u-default' } }) + } + return Promise.resolve({ data: {} }) + }), + ) + axios.post.mockImplementation( + overrides.post ?? (() => Promise.resolve({ data: { acquiredAt: 1 } })), + ) + axios.put.mockImplementation(() => Promise.resolve({ data: {} })) + axios.delete.mockImplementation(() => Promise.resolve({ data: {} })) +} + +/** + * Mount Views with real stores whose server-bound actions are mocked. + * + * @param {object} opts Store state and injections. + * @return {Promise<{wrapper: object, dashStore: object}>} the mount. + */ +async function mountViews({ + activeDashboard = { id: 7, uuid: 'u-7', name: 'Home', isOwner: true }, + widgetPlacements = [], + permissionLevel = 'full', + isAdmin = false, + allowUserDashboards = true, + availableWidgets = [], + attach = false, +} = {}) { + const pinia = createPinia() + setActivePinia(pinia) + + const { default: Views } = await import('../Views.vue') + const { useDashboardStore } = await import('../../stores/dashboard.js') + const { useWidgetStore } = await import('../../stores/widgets.js') + const { useTileStore } = await import('../../stores/tiles.js') + + const dashStore = useDashboardStore() + dashStore.activeDashboard = activeDashboard + dashStore.dashboards = activeDashboard ? [activeDashboard] : [] + dashStore.widgetPlacements = widgetPlacements + dashStore.permissionLevel = permissionLevel + dashStore.loading = false + dashStore.loadDashboards = vi.fn(() => Promise.resolve()) + dashStore.fetchPendingAcknowledgements = vi.fn(() => Promise.resolve()) + dashStore.recordViewEvent = vi.fn() + dashStore.switchDashboard = vi.fn(() => Promise.resolve()) + dashStore.removeWidgetFromDashboard = vi.fn(() => Promise.resolve()) + dashStore.updateWidgetPlacement = vi.fn(() => Promise.resolve()) + dashStore.updatePlacements = vi.fn() + + const widgetStore = useWidgetStore() + widgetStore.availableWidgets = availableWidgets + widgetStore.loadAvailableWidgets = vi.fn(() => Promise.resolve()) + + const tileStore = useTileStore() + tileStore.tiles = [] + tileStore.loadTiles = vi.fn(() => Promise.resolve()) + + wrapper = mount(Views, { + global: { + plugins: [pinia], + provide: { + isAdmin, + allowUserDashboards, + primaryGroupName: '', + }, + // Attached mounts keep the real Teleport, so the controls land + // where the view sends them. + stubs: attach ? { ...stubs, teleport: false } : stubs, + mocks: { + t: (_app, key) => key, + n: (_app, sing, plur, count) => (count === 1 ? sing : plur), + }, + }, + attachTo: attach ? document.body : undefined, + }) + await flushPromises() + return { wrapper, dashStore } +} + +beforeEach(() => { + vi.clearAllMocks() + globalThis.t = (_app, key) => key + window.history.replaceState(null, '', '/apps/launchpad') + routeAxios() +}) + +afterEach(() => { + if (wrapper) { + wrapper.unmount() + wrapper = null + } + document.body.innerHTML = '' +}) + +const groupDashboard = { id: 7, uuid: 'g-7', name: 'Team', type: 'group_shared', isOwner: false } +const placement = { id: 11, widgetId: 'tile', gridX: 0, gridY: 0, gridWidth: 2, gridHeight: 2, content: {} } + +/** + * Mount the page on a group dashboard with these apps installed, recording console errors. + * + * @param {object} appswebroots The installed apps' web roots. + * @return {Promise<{wrapper: object, errors: object}>} the mount and the console.error spy. + */ +async function mountWithApps(appswebroots) { + window.OC = { ...(window.OC || {}), currentUser: 'alice', appswebroots } + const errors = vi.spyOn(console, 'error') + const mounted = await mountViews({ activeDashboard: groupDashboard, widgetPlacements: [placement] }) + await flushPromises() + return { wrapper: mounted.wrapper, errors } +} + +// Load the page before any console spy: the library's own load-time +// notices are not the page's errors. +beforeAll(async () => { + await import('../Views.vue') +}, 90000) + +afterEach(() => { + vi.restoreAllMocks() + delete window.OC.appswebroots +}) + +describe('Views — a collaborative dashboard with Talk disabled', () => { + it('renders the dashboard and its widgets, with no discussion and no error', async () => { + const { wrapper, errors } = await mountWithApps({ openregister: '/apps/openregister' }) + + expect(wrapper.find('[data-testid="launchpad-dashboard-region"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="launchpad-dashboard-region"]').attributes('data-dashboard-uuid')).toBe('g-7') + expect(wrapper.findComponent({ name: 'CnDashboardGrid' }).props('layout').map((p) => p.id)).toEqual([11]) + expect(wrapper.find('[data-testid="dashboard-discussion"]').exists()).toBe(false) + expect(wrapper.find('.stub-talk-leaf').exists()).toBe(false) + + const requested = [...axios.get.mock.calls, ...axios.post.mock.calls].map(([url]) => String(url)) + expect(requested.filter((url) => url.includes('integrations/talk') || url.includes('/shares'))).toEqual([]) + expect(errors).not.toHaveBeenCalled() + expect(showError).not.toHaveBeenCalled() + }, 90000) + + it('renders nothing of the discussion without OpenRegister either', async () => { + const { wrapper, errors } = await mountWithApps({ spreed: '/apps/spreed' }) + + expect(wrapper.find('[data-testid="launchpad-dashboard-region"]').exists()).toBe(true) + expect(wrapper.find('[data-testid="dashboard-discussion"]').exists()).toBe(false) + expect(errors).not.toHaveBeenCalled() + expect(showError).not.toHaveBeenCalled() + }, 90000) + + it('shows the discussion on the same dashboard once Talk is installed', async () => { + const { wrapper } = await mountWithApps({ openregister: '/apps/openregister', spreed: '/apps/spreed' }) + + expect(wrapper.find('[data-testid="dashboard-discussion"]').exists()).toBe(true) + expect(wrapper.findComponent({ name: 'CnIntegrationTab' }).props()).toEqual({ integrationId: 'talk', objectId: 'g-7' }) + }, 90000) +}) diff --git a/src/views/__tests__/ViewsTileMinWidth.spec.js b/src/views/__tests__/ViewsTileMinWidth.spec.js new file mode 100644 index 000000000..50fb325b5 --- /dev/null +++ b/src/views/__tests__/ViewsTileMinWidth.spec.js @@ -0,0 +1,49 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * A tile is a widget of one cell (LpWerkplek): the grid gets a one-column + * minimum for every tile placement, so it does not widen a tile to the + * grid's two-column minimum and push its neighbours out of place. + */ + +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() })) +vi.mock('@nextcloud/axios', () => ({ default: { get: vi.fn() } })) +vi.mock('../../constants/widgetRegistry.js', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getWidgetTypeEntry: (type) => (type === 'divider' ? { minHeight: 1 } : actual.getWidgetTypeEntry(type)), + } +}) + +const { isTilePlacement, withTypeMinHeight } = await import('../Views.vue') + +describe('Views: one-cell tiles', () => { + it('knows launcher, inline and app tiles', () => { + expect(isTilePlacement({ widgetId: 'tile' })).toBe(true) + expect(isTilePlacement({ widgetId: 'tile-12' })).toBe(true) + expect(isTilePlacement({ widgetId: 'mydash-tile', tileType: 'custom' })).toBe(true) + expect(isTilePlacement({ widgetId: 'app-tile' })).toBe(true) + expect(isTilePlacement({ widgetId: 'calendar' })).toBe(false) + }) + + it('gives a tile a one-column minimum and leaves other widgets at the grid minimum', () => { + expect(withTypeMinHeight({ id: 1, widgetId: 'tile' }).minWidth).toBe(1) + expect(withTypeMinHeight({ id: 2, widgetId: 'calendar' }).minWidth).toBeUndefined() + }) + + it('gives a tile a one-row minimum, so a one-cell tile stays one cell (LpMobiel)', () => { + expect(withTypeMinHeight({ id: 5, widgetId: 'app-tile' }).minHeight).toBe(1) + expect(withTypeMinHeight({ id: 6, widgetId: 'tile' }).minHeight).toBe(1) + expect(withTypeMinHeight({ id: 7, widgetId: 'calendar' }).minHeight).toBeUndefined() + expect(withTypeMinHeight({ id: 8, widgetId: 'tile', minHeight: 2 }).minHeight).toBe(2) + }) + + it('keeps a divider\'s one-row minimum and a minimum the placement sets itself', () => { + expect(withTypeMinHeight({ id: 3, widgetId: 'divider' }).minHeight).toBe(1) + expect(withTypeMinHeight({ id: 4, widgetId: 'tile', minWidth: 3 }).minWidth).toBe(3) + }) +}) diff --git a/src/views/__tests__/ViewsTree.spec.js b/src/views/__tests__/ViewsTree.spec.js index 8a38bd5c7..f3e5a12bb 100644 --- a/src/views/__tests__/ViewsTree.spec.js +++ b/src/views/__tests__/ViewsTree.spec.js @@ -37,8 +37,8 @@ function makeHost() { deleteChildCount: 0, configSaveError: '', isConfigModalOpen: true, - // Switching gives back the editing lock (REQ-LOCKUI-001). - editLock: { release: vi.fn() }, + // Switching withdraws the presence (building-edit-a-dashboard-together). + presence: { stop: vi.fn() }, } for (const [name, fn] of Object.entries(Views.methods)) { host[name] = fn.bind(host) diff --git a/src/views/__tests__/ViewsVersionHistory.spec.js b/src/views/__tests__/ViewsVersionHistory.spec.js index a34a3c9a5..0eae9bfb4 100644 --- a/src/views/__tests__/ViewsVersionHistory.spec.js +++ b/src/views/__tests__/ViewsVersionHistory.spec.js @@ -2,9 +2,10 @@ * SPDX-FileCopyrightText: 2026 Conduction B.V. * SPDX-License-Identifier: EUPL-1.2 * - * The workspace page offers "Version history" to the owner or an - * administrator when versioning is supported, and reloads the dashboard - * after a restore (dashboard-versioning REQ-VERSUI-001, REQ-VERSUI-003). + * The workspace page offers the Versions tab of the dashboard settings to + * the owner or an administrator (board LpVersies; the tab itself says when a + * dashboard keeps no versions), and reloads the dashboard after a restore + * (dashboard-versioning REQ-VERSUI-001, REQ-VERSUI-003). * The real Views.vue computed and methods run against a small host. */ @@ -23,13 +24,13 @@ let Views * @return {object} host with Views methods and the gate computed. */ function makeHost(dashboard, isAdmin = false) { - const host = { activeDashboard: dashboard, isAdmin, versionSupport: {} } + const host = { activeDashboard: dashboard, isAdmin } for (const [name, fn] of Object.entries(Views.methods)) { host[name] = fn.bind(host) } host.switchDashboard = vi.fn() - Object.defineProperty(host, 'canViewVersionHistory', { - get: () => Views.computed.canViewVersionHistory.call(host), + Object.defineProperty(host, 'canManagePublication', { + get: () => Views.computed.canManagePublication.call(host), }) return host } @@ -39,43 +40,16 @@ beforeEach(async () => { Views = (await import('../Views.vue')).default }) -describe('Views version history gate', () => { - it('REQ-VERSUI-001: the owner gets the entry once versioning is confirmed', async () => { - api.listVersions.mockResolvedValue({ - data: { versions: [], modeSupported: true }, - }) - const host = makeHost({ id: 1, uuid: 'u-1', isOwner: true }) - expect(host.canViewVersionHistory).toBe(false) - await host.checkVersionSupport() - expect(api.listVersions).toHaveBeenCalledWith('u-1') - expect(host.canViewVersionHistory).toBe(true) - await host.checkVersionSupport() - expect(api.listVersions).toHaveBeenCalledTimes(1) - }) - - it('REQ-VERSUI-001: a colleague who does not own it gets no entry and no request', async () => { - const host = makeHost({ id: 1, uuid: 'u-1', isOwner: false }) - await host.checkVersionSupport() +describe('Views Versions tab gate', () => { + it('REQ-VERSUI-001: the owner and an administrator get the Versions tab, without asking the server first', () => { + expect(makeHost({ id: 1, uuid: 'u-1', isOwner: true }).canManagePublication).toBe(true) + expect(makeHost({ id: 1, uuid: 'u-1', isOwner: false }, true).canManagePublication).toBe(true) expect(api.listVersions).not.toHaveBeenCalled() - expect(host.canViewVersionHistory).toBe(false) - }) - - it('REQ-VERSUI-001: an administrator gets the entry on a dashboard they do not own', async () => { - api.listVersions.mockResolvedValue({ - data: { versions: [], modeSupported: true }, - }) - const host = makeHost({ id: 1, uuid: 'u-1', isOwner: false }, true) - await host.checkVersionSupport() - expect(host.canViewVersionHistory).toBe(true) }) - it('REQ-VERSUI-001: an unsupported dashboard hides the entry', async () => { - api.listVersions.mockResolvedValue({ - data: { versions: [], modeSupported: false }, - }) - const host = makeHost({ id: 1, uuid: 'u-1', isOwner: true }) - await host.checkVersionSupport() - expect(host.canViewVersionHistory).toBe(false) + it('REQ-VERSUI-001: a colleague who does not own it, or a dashboard without a uuid, gets no tab', () => { + expect(makeHost({ id: 1, uuid: 'u-1', isOwner: false }).canManagePublication).toBe(false) + expect(makeHost({ id: 1, isOwner: true }).canManagePublication).toBe(false) }) it('REQ-VERSUI-003: a restore reloads the dashboard from the server', async () => { diff --git a/src/views/__tests__/WorkspaceApp.behaviour.spec.js b/src/views/__tests__/WorkspaceApp.behaviour.spec.js new file mode 100644 index 000000000..738a8fa03 --- /dev/null +++ b/src/views/__tests__/WorkspaceApp.behaviour.spec.js @@ -0,0 +1,207 @@ +/** + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * SPDX-License-Identifier: EUPL-1.2 + * + * Vitest unit tests for the behaviour of `WorkspaceApp.vue` beyond its + * chrome: the `/dashboards/:id` route parameter selecting a dashboard, + * creating a first dashboard from the empty state (and logging a failure), + * which footer the active dashboard resolves to, and the org navigation rail. + * + * The two stores and the logger are doubled; child components are stubbed. + */ + +import { mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { h } from 'vue' +import WorkspaceApp from '../WorkspaceApp.vue' + +const dashboardStore = { + activeDashboardId: null, + openDashboard: vi.fn(), + createDashboard: vi.fn(), +} +const orgNavStore = { shouldRender: false, position: 'top', loadFirst: vi.fn() } +const logged = [] + +vi.mock('../../stores/dashboard.js', () => ({ + useDashboardStore: () => dashboardStore, +})) +vi.mock('../../stores/orgNavigation.js', () => ({ + useOrgNavigationStore: () => orgNavStore, +})) +vi.mock('../../utils/logger.js', () => ({ + logger: { error: (...args) => logged.push(args) }, +})) + +/** + * Mount the shell. + * + * @param {object} options The options + * @param {object} [options.provide] Injected initial state + * @param {object} [options.route] The current route + * @return {object} The wrapper + */ +function mountShell({ provide = {}, route = { params: {} } } = {}) { + return mount(WorkspaceApp, { + global: { + provide, + mocks: { $route: route }, + stubs: { + Views: { name: 'Views', render: () => h('div', { class: 'views-stub' }) }, + DashboardFooter: { name: 'DashboardFooter', props: ['footer', 'locale'], render: () => null }, + OrgNavigationPanel: { name: 'OrgNavigationPanel', render: () => h('nav', { class: 'org-nav-stub' }) }, + StartPageMenu: true, + TileSidePanel: true, + NcButton: { + name: 'NcButton', + emits: ['click'], + render() { + return h('button', { class: this.$attrs.class, onClick: () => this.$emit('click') }) + }, + }, + MenuIcon: true, + }, + }, + }) +} + +const footerOf = (wrapper) => wrapper.findComponent({ name: 'DashboardFooter' }).props('footer') + +beforeEach(() => { + vi.clearAllMocks() + logged.length = 0 + dashboardStore.activeDashboardId = null + orgNavStore.shouldRender = false + orgNavStore.position = 'top' +}) + +describe('WorkspaceApp route parameter', () => { + it('switches to the dashboard the route names', () => { + dashboardStore.activeDashboardId = 'a' + mountShell({ route: { params: { id: 'b' } } }) + + expect(dashboardStore.openDashboard).toHaveBeenCalledWith('b') + }) + + it('does not switch to the dashboard that is already active, compared as text', () => { + dashboardStore.activeDashboardId = 7 + mountShell({ route: { params: { id: '7' } } }) + + expect(dashboardStore.openDashboard).not.toHaveBeenCalled() + }) + + it('does nothing without a dashboard in the route', () => { + for (const id of [undefined, null, '']) { + mountShell({ route: { params: { id } } }).unmount() + } + + expect(dashboardStore.openDashboard).not.toHaveBeenCalled() + }) +}) + +describe('WorkspaceApp first dashboard', () => { + it('creates a first dashboard from the empty state', async () => { + dashboardStore.createDashboard.mockResolvedValue({}) + const wrapper = mountShell({ provide: { allowUserDashboards: true } }) + + await wrapper.find('.workspace-shell__empty-cta').trigger('click') + + expect(dashboardStore.createDashboard).toHaveBeenCalledWith({ name: 'My workspace', widgets: 'starters' }) + expect(logged).toEqual([]) + wrapper.unmount() + }) + + it('creates an empty first dashboard from Start empty', async () => { + dashboardStore.createDashboard.mockResolvedValue({}) + const wrapper = mountShell({ provide: { allowUserDashboards: true } }) + + await wrapper.find('.workspace-shell__empty-blank').trigger('click') + + expect(dashboardStore.createDashboard).toHaveBeenCalledWith({ name: 'My workspace', widgets: 'none' }) + wrapper.unmount() + }) + + it('logs a first dashboard that cannot be created', async () => { + const failure = new Error('quota') + dashboardStore.createDashboard.mockRejectedValue(failure) + const wrapper = mountShell({ provide: { allowUserDashboards: true } }) + + await wrapper.vm.onCreateFirstDashboard() + + expect(logged).toEqual([['[WorkspaceApp] Failed to create first dashboard:', failure]]) + wrapper.unmount() + }) +}) + +describe('WorkspaceApp active dashboard', () => { + const instanceFooter = { text: 'Instance footer' } + + it('uses the instance footer without an active dashboard', () => { + const wrapper = mountShell({ provide: { effectiveFooter: instanceFooter } }) + + expect(footerOf(wrapper)).toEqual(instanceFooter) + expect(wrapper.findComponent({ name: 'DashboardFooter' }).props('locale')).toBe('en') + wrapper.unmount() + }) + + it('uses the active dashboard\'s own footer, even when it hides the footer', () => { + const own = { text: 'Team footer' } + const withOwn = mountShell({ + provide: { activeDashboardId: 'u1', effectiveFooter: instanceFooter, userDashboards: [{ id: 'u1', name: 'Mine', effectiveFooter: own }] }, + }) + expect(footerOf(withOwn)).toEqual(own) + withOwn.unmount() + + const hidden = mountShell({ + provide: { activeDashboardId: 'g1', effectiveFooter: instanceFooter, groupDashboards: [null, { id: 'g1', name: 'Team', effectiveFooter: null }] }, + }) + expect(footerOf(hidden)).toBeNull() + hidden.unmount() + }) + + it('falls back to the instance footer when the dashboard has none or is unknown', () => { + for (const dashboards of [[{ id: 'u1', name: 'Mine' }], []]) { + const wrapper = mountShell({ + provide: { activeDashboardId: 'u1', effectiveFooter: instanceFooter, userDashboards: dashboards }, + }) + expect(footerOf(wrapper)).toEqual(instanceFooter) + wrapper.unmount() + } + }) +}) + +describe('WorkspaceApp org navigation', () => { + it('renders the rail with a class for its position when it should render', () => { + orgNavStore.shouldRender = true + orgNavStore.position = 'left' + const wrapper = mountShell() + + expect(wrapper.find('.org-nav-stub').exists()).toBe(true) + expect(wrapper.classes()).toContain('workspace-shell--org-nav-left') + wrapper.unmount() + }) + + it('names an unset position hidden', () => { + orgNavStore.shouldRender = true + orgNavStore.position = '' + const wrapper = mountShell() + + expect(wrapper.classes()).toContain('workspace-shell--org-nav-hidden') + wrapper.unmount() + }) + + it('loads the position and the tree itself, because the rail mounts only once they are known', () => { + const wrapper = mountShell() + + expect(orgNavStore.loadFirst).toHaveBeenCalledTimes(1) + wrapper.unmount() + }) + + it('adds no rail and no class when it should not render', () => { + const wrapper = mountShell() + + expect(wrapper.find('.org-nav-stub').exists()).toBe(false) + expect(wrapper.classes()).toEqual(['workspace-shell']) + wrapper.unmount() + }) +}) diff --git a/src/views/__tests__/WorkspaceApp.spec.js b/src/views/__tests__/WorkspaceApp.spec.js index 3aa762c55..a4f149bb9 100644 --- a/src/views/__tests__/WorkspaceApp.spec.js +++ b/src/views/__tests__/WorkspaceApp.spec.js @@ -7,9 +7,8 @@ * - the in-page edit toolbar was removed — editing actions now live in * the per-dashboard cog menu (DashboardRowActions), so the page chrome * stays clean (regression-guarded below), - * - REQ-SHELL-004 (hamburger as `NcButton type="tertiary"` + active-dashboard label), - * - REQ-SHELL-005 (empty-state branch on `allowUserDashboards`), - * - REQ-SHELL-006 (SidebarBackdrop rendered when sidebarOpen). + * - REQ-SHELL-004 (no sidebar toggle, no title strip), + * - REQ-SHELL-005 (empty-state branch on `allowUserDashboards`). * * The embedded Views.vue child is stubbed because it depends on Pinia * stores + GridStack — neither is in scope for runtime-shell unit tests. @@ -23,6 +22,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import RuntimeShellSearch from '../../components/RuntimeShellSearch.vue' import WorkspaceApp from '../WorkspaceApp.vue' +vi.mock('@nextcloud/auth', async (importOriginal) => ({ + ...(await importOriginal()), + getCurrentUser: () => ({ uid: 'pieter', displayName: 'Pieter Jansen' }), +})) + beforeEach(() => { globalThis.t = (_app, key) => key }) @@ -59,15 +63,14 @@ function mountShell(options = {}) { openCustomWidgetModal: vi.fn(), }, }, - SidebarBackdrop: true, DashboardSwitcherSidebar: true, // Stub `NcButton` to a transparent `